2012-10-22 69 views

回答

11

使用BDay()可獲取範圍內的營業日。

from pandas.tseries.offsets import * 

In [185]: s 
Out[185]: 
2011-01-01 -0.011629 
2011-01-02 -0.089666 
2011-01-03 -1.314430 
2011-01-04 -1.867307 
2011-01-05 0.779609 
2011-01-06 0.588950 
2011-01-07 -2.505803 
2011-01-08 0.800262 
2011-01-09 0.376406 
2011-01-10 -0.469988 
Freq: D 

In [186]: s.asfreq(BDay()) 
Out[186]: 
2011-01-03 -1.314430 
2011-01-04 -1.867307 
2011-01-05 0.779609 
2011-01-06 0.588950 
2011-01-07 -2.505803 
2011-01-10 -0.469988 
Freq: B 

隨着切片:

In [187]: x=datetime(2011, 1, 5) 

In [188]: y=datetime(2011, 1, 9) 

In [189]: s.ix[x:y] 
Out[189]: 
2011-01-05 0.779609 
2011-01-06 0.588950 
2011-01-07 -2.505803 
2011-01-08 0.800262 
2011-01-09 0.376406 
Freq: D 

In [190]: s.ix[x:y].asfreq(BDay()) 
Out[190]: 
2011-01-05 0.779609 
2011-01-06 0.588950 
2011-01-07 -2.505803 
Freq: B 

count()

In [191]: s.ix[x:y].asfreq(BDay()).count() 
Out[191]: 3 
+0

哇..完美!非常感謝你! –

17

您還可以使用date_range用於此目的。

In [3]: pd.date_range('2011-01-05', '2011-01-09', freq=BDay()) 

Out[3]: DatetimeIndex(['2011-01-05', '2011-01-06', '2011-01-07'], dtype='datetime64[ns]', freq='B', tz=None) 

編輯

或者更簡單

In [7]: pd.bdate_range('2011-01-05', '2011-01-09') 

Out[7]: DatetimeIndex(['2011-01-05', '2011-01-06', '2011-01-07'], dtype='datetime64[ns]', freq='B', tz=None) 

注意,開始和結束日期包含在內。 來源:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.bdate_range.html

10

使用bdate_range或BDay()時要小心 - 名稱可能誤導你認爲它是一個工作日的範圍,而實際上它只是週末被剝離的日曆日(即它不考慮假期)。

14

從v0.14開始,您可以使用假日日曆。

 
from pandas.tseries.holiday import USFederalHolidayCalendar 
from pandas.tseries.offsets import CustomBusinessDay 

us_bd = CustomBusinessDay(calendar=USFederalHolidayCalendar()) 
print pd.DatetimeIndex(start='2010-01-01',end='2010-01-15', freq=us_bd) 

回報:

 
DatetimeIndex(['2010-01-04', '2010-01-05', '2010-01-06', '2010-01-07', 
       '2010-01-08', '2010-01-11', '2010-01-12', '2010-01-13', 
       '2010-01-14', '2010-01-15'], 
       dtype='datetime64[ns]', freq='C') 
+1

如果您想要日期範圍內的天數,您可以將其作爲'pd.DatetimeIndex(start ='2010-01-01',end ='2010-01-15',freq = us_bd).shape [ 0]' – tsando

相關問題