Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round Date in Pandas Dataframe [duplicate]

I'm attempting to round the date from this dataframe below to the 1st day of the next month - i.e. 1997-10-10 would result in 1997-11-01:

Date

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

Currently my code looks like:

df = pd.read_csv(XXX)

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

According to the 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).

I had presumed that I could use .replace with only 1 argument - day -however I'm receiving a number of errors.

like image 459
christaylor Avatar asked Dec 18 '22 05:12

christaylor


1 Answers

I think you need 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
like image 65
jezrael Avatar answered Jan 05 '23 13:01

jezrael