问题描述
我在 Pandas 中有一个日历表,有几个列,如日期、年、月,我想在另一列中添加一个新列,其中包含日期的当前月份偏移量。例如。对于 2021-02-01 日期,我希望当前月份的偏移量为 -1,而对于 2021-04-01,则偏移量为 +1。
这是日历表现在的样子:
这是我想要的:
非常感谢您的帮助。
解决方法
这将向数据框中添加一列 MonthOffset,其偏移量为当前月份。
df['MonthOffset'] = df['MonthNumber'] - datetime.today().month
,
您可以通过 Series.dt.to_period
减去月份周期:
df = pd.DataFrame({'Date':pd.date_range('2020-01-01','2021-05-01',freq='MS')})
now = pd.to_datetime('now').to_period('m').ordinal
df['MonthOffset'] = df['Date'].dt.to_period('m').astype('int') - now
print (df)
Date MonthOffset
0 2020-01-01 -14
1 2020-02-01 -13
2 2020-03-01 -12
3 2020-04-01 -11
4 2020-05-01 -10
5 2020-06-01 -9
6 2020-07-01 -8
7 2020-08-01 -7
8 2020-09-01 -6
9 2020-10-01 -5
10 2020-11-01 -4
11 2020-12-01 -3
12 2021-01-01 -2
13 2021-02-01 -1
14 2021-03-01 0
15 2021-04-01 1
16 2021-05-01 2