python - 从时间序列生成日期特征

标签 python pandas dataframe time-series

我有一个数据框,其中包含如下列:

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/

相关文章:

python - 如何在 postgresql 中存储超过 1600 列

python - 带有排序列表的 Pandas 列的名字

python - 确定脚本是否在 pythonw 中运行?

python - 在 matplotlib 中对 x 轴进行排序

python - 使用字典和正则表达式重命名列名

python-2.7 - 用python减去两列不同的Dataframe

r - 为数据框中的所有字符串分配相同的值

python - tkinter 中的边框未显示

python - 在python中的类中定义一个方法

python - groupby 在有序分类列上的奇怪行为