我有一个数据框,其中包含如下列:
Date temp_data holiday day
01.01.2000 10000 0 1
02.01.2000 0 1 2
03.01.2000 2000 0 3
..
..
..
30.01.2000 200 0 30
31.01.2000 0 1 31
01.02.2000 0 1 1
02.02.2000 2500 0 2
当有数据时,假期 = 0 - 表示工作日
没有数据时假期 = 1 - 表示非工作日
我正在尝试提取两个新列 每月第一工作日 和 last_working_day_of_month
数据框应该是这样的
Date temp_data holiday day first_wd_of_month last_wd_of_month
01.01.2000 10000 0 1 1 0
02.01.2000 0 1 2 0 0
03.01.2000 2000 0 3 0 0
..
..
..
30.01.2000 200 0 30 0 1
31.01.2000 0 1 31 0 0
01.02.2000 0 1 1 0 0
02.02.2000 2500 0 2 1 0
谁能帮我解决这个问题吗?
最佳答案
解决方案
# Convert the column to datetime
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
# mask the dates when there is holdiday
w = df['Date'].mask(df['holiday'] == 1)
# group the working dates by monthly frequency
g = w.groupby(df['Date'].dt.to_period('M'))
# transform each group to get the first and last working day per month
# then compare with current date to identify whether the current
# day is the first or last working day
df['first_wd_of_month'] = df['Date'] == g.transform('first')
df['last_wd_of_month' ] = (df['Date'] == g.transform('last')) & ~df['first_wd_of_month']
结果
Date temp_data holiday day first_wd_of_month last_wd_of_month
0 2000-01-01 10000 0 1 True False
1 2000-01-02 0 1 2 False False
2 2000-01-03 2000 0 3 False False
3 2000-01-30 200 0 30 False True
...
4 2000-01-31 0 1 31 False False
5 2000-02-01 0 1 1 False False
6 2000-02-02 2500 0 2 True False
关于python - 从时间序列生成日期特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73789609/