【问题标题】:How can I add a pandas column with a current month offset?如何添加具有当前月份偏移量的 pandas 列?
【发布时间】:2021-06-22 05:48:14
【问题描述】:

我在 Pandas 中有一个日历表,其中包含日期、年份、月份等几列,我想在另一列中添加一个新列,其中包含日期的当前月份偏移量。例如。对于日期 2021-02-01,我希望当前月份的偏移量为 -1,对于 2021-04-01,偏移量为 +1。

这是日历表现在的样子:

这是我想要的:

感谢您的帮助。

【问题讨论】:

  • df['Date'].dt.month - pd.Timestamp.today().month 适合你吗?

标签: python pandas date datetime


【解决方案1】:

您可以通过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

【讨论】:

    【解决方案2】:

    这将在数据框中添加一个 MonthOffset 列,其中包含当前月份的偏移量。

    df['MonthOffset'] = df['MonthNumber'] - datetime.today().month
    

    【讨论】:

    • 其他答案更合适,因为它们不需要任何进一步的导入——我的需要从日期时间导入日期时间。
    猜你喜欢
    • 2018-11-15
    • 1970-01-01
    • 2020-09-27
    • 2018-07-12
    • 2021-11-10
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多