在 Pandas 数据框中对日期进行四舍五入

4

我尝试将下面的数据框中的日期四舍五入到下个月的第一天 - 即 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库文档,涉及到IT技术,详见此处
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).

我曾认为只需使用一个参数(day)即可使用 .replace,但是我收到了许多错误信息。
1个回答

12

我认为你需要使用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分钟才能接受答案。 - christaylor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接