首页 > 解决方案 > 在 Pandas DataFrame 的日期列上使用 numpy is_busday 函数

问题描述

我将我的 Excel 文件加载到 Pandas 数据框中,Excel 文件上有日期列。加载后,我将日期列转换为 datetime64[ns]

df['Date'] = pd.to_datetime(df['Date'])

我在 Dataframe 上创建了一个名为“Is_Business_Day”的新列 在此列上,我应用了 Numpy 的 is_busday 来查看日期是工作日还是周末

我尝试了两个代码,但没有工作

df['Is_Business_Day']= [np.is_busday(np.datetime64(x)) for x in df['Date']]

df['Is_Business_Day']= [np.is_busday(x) for x in df['Date']]

错误信息是:

TypeError: Iterator operand 0 dtype could not be cast from dtype('<M8[us]') to dtype('<M8[D]') according to the rule 'safe'

试图四处寻找解决方案,但找不到任何东西。谁能给我一些提示?谢谢。

标签: pythonpandasnumpy

解决方案


方法一:

df['Date']在将其提供给之前转换为字符串np.is_busday

df['Is_Business_Day'] = [np.is_busday(x) for x in df['Date'].astype(str)]

方法二:

您可以只使用pandas而不是numpy,并检查是否Date在从最短日期到最长日期的工作日范围内:

bus_days = pd.bdate_range(df['Date'].min(), df['Date'].max())

df['Is_Business_Day'] = df['Date'].isin(bus_days)

例子:

>>> df = pd.DataFrame({'Date':pd.date_range(pd.to_datetime('today'), pd.to_datetime('2018-09-15'))})
>>> df
         Date
0  2018-08-29
1  2018-08-30
2  2018-08-31
3  2018-09-01
4  2018-09-02
5  2018-09-03
6  2018-09-04
7  2018-09-05
8  2018-09-06
9  2018-09-07
10 2018-09-08
11 2018-09-09
12 2018-09-10
13 2018-09-11
14 2018-09-12
15 2018-09-13
16 2018-09-14
17 2018-09-15

你可以做:

方法一

>>> df['Is_Business_Day'] = [np.is_busday(x) for x in df['Date'].astype(str)]
>>> df
         Date  Is_Business_Day
0  2018-08-29             True
1  2018-08-30             True
2  2018-08-31             True
3  2018-09-01            False
4  2018-09-02            False
5  2018-09-03             True
6  2018-09-04             True
7  2018-09-05             True
8  2018-09-06             True
9  2018-09-07             True
10 2018-09-08            False
11 2018-09-09            False
12 2018-09-10             True
13 2018-09-11             True
14 2018-09-12             True
15 2018-09-13             True
16 2018-09-14             True
17 2018-09-15            False

方法二

>>> bus_days = pd.bdate_range(df['Date'].min(), df['Date'].max())
>>> df['Is_Business_Day'] = df['Date'].isin(bus_days)
>>> df
         Date  Is_Business_Day
0  2018-08-29             True
1  2018-08-30             True
2  2018-08-31             True
3  2018-09-01            False
4  2018-09-02            False
5  2018-09-03             True
6  2018-09-04             True
7  2018-09-05             True
8  2018-09-06             True
9  2018-09-07             True
10 2018-09-08            False
11 2018-09-09            False
12 2018-09-10             True
13 2018-09-11             True
14 2018-09-12             True
15 2018-09-13             True
16 2018-09-14             True
17 2018-09-15            False

推荐阅读