[英]Get business days between consecutive rows pandas
很简单的问题。
我知道:
df.diff()
给了我之间的日子,我知道我可以和
df.loc[df.Date.weekday == 4, 'Diff'] = 1
但这不是最佳选择。 我试过了
np.busday_count()
但是遇到一个我不太了解的错误。 这是带有该错误的示例代码:
In [36]: df = pd.DataFrame.from_dict({1: {'Date': '2016-01-01'}, 2: {'Date': '2016-01-02'}, 3: {'Date': '2016-01-03'}}, orient='index')
In [37]: df['Date'] = df.Date.astype('<M8[D]')
In [38]: np.busday_count(df.Date, df.Date.shift(1))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-07a4ae9a16f6> in <module>()
----> 1 np.busday_count(df.Date, df.Date.shift(1))
TypeError: Iterator operand 0 dtype could not be cast from dtype('<M8[ns]') to dtype('<M8[D]') according to the rule 'safe'
In [39]: df = pd.DataFrame.from_dict({1: {'Date': '2016-01-01'}, 2: {'Date': '2016-01-02'}, 3: {'Date': '2016-01-03'}}, orient='index')
In [40]: np.busday_count(df.Date, df.Date.shift(1))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-40-07a4ae9a16f6> in <module>()
----> 1 np.busday_count(df.Date, df.Date.shift(1))
TypeError: Iterator operand or requested dtype holds references, but the REFS_OK flag was not enabled
使用np.busday_count
您也可以尝试:
x3 = [x.strftime('%Y-%m-%d') for x in df.Date]
x4 = [x.strftime('%Y-%m-%d') for x in df.Date.shift(1).fillna(0)]
np.busday_count(x4,x3)
array([12001, 1, 0])
%timeit np.busday_count(x4,x3)
The slowest run took 4.58 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 12.5 µs per loop
或者,如果您希望:
x1 = [x.date() for x in df.Date]
x2 = [x.date() for x in df.Date.shift(1).fillna(0)]
np.busday_count(x2,x1)
array([12001, 1, 0])
%timeit np.busday_count(x2,x1)
10000 loops, best of 3: 43.4 µs per loop
得到它了!
因此,我不知道这是否适合每个人的需求,但这是可行的:
np.busday_count(df.Date.values.tolist(), df.Date.shift(1).fillna(df.Date).values.tolist())
因此,添加tolist()和.fillna()部分都是必要的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.