【问题标题】:Round Date in Pandas Dataframe [duplicate]Pandas Dataframe中的圆形日期[重复]
【发布时间】:2017-07-25 12:33:38
【问题描述】:

我正在尝试将以下数据框中的日期四舍五入到下个月的第一天 - 即 1997-10-10 将导致 1997-11-01:

Date

1997-10-10
1997-05-27
1997-04-30
1997-12-19
1997-08-12

目前我的代码如下:

df = pd.read_csv(XXX)

df['Date'] = pd.to_datetime(df.Date)
df['Date'] = df['Date'].dt.date.replace(day = 1)

根据python library documentation

date.replace(year=self.year, month=self.month, day=self.day)
Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified. For example, if d == date(2002, 12, 31), then d.replace(day=26) == date(2002, 12, 26).

我曾假设我可以使用 .replace 与只有 1 个参数 - 天 - 但是我收到了许多错误。

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    我觉得你需要MonthBegin(0):

    df['Date'] = pd.to_datetime(df.Date) + pd.offsets.MonthBegin(0)
    print (df)
            Date
    0 1997-11-01
    1 1997-06-01
    2 1997-05-01
    3 1998-01-01
    4 1997-09-01
    

    【讨论】:

    • 太好了,谢谢! - 不能再接受 12 分钟的回答
    猜你喜欢
    • 2021-08-13
    • 2021-02-15
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2013-11-18
    相关资源
    最近更新 更多