2017-07-25 32 views
-1

我試圖從這個數據框圓下方的日期到下個月的第一天 - 即1997年10月10日將導致1997年11月1日:回合日期

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個參數 - 天 - 但我收到一些錯誤。

回答

2

我想你需要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 
+0

那是輝煌的感謝! - 不能接受另外12分鐘的答案 – christaylor