JAG2024
JAG2024

Reputation: 4317

Change day of DateTime object using values in pandas dataframe column

Say I have a data frame of 10,000+ rows with columns Day and Month where Month is a datetime object. The value for "day" in the Month object is incorrect so I want to replace it with the corresponding value from the Day column. How would I go about doing that?

import datetime as dt

df = pd.DataFrame({
'Month': [dt.date(2017,9,1),dt.date(2017,11,1),dt.date(2017,9,1)],
'Day': [7, 21,14],
})

Day Month
7   2017-09-01
21  2017-11-01
14  2017-09-01

So I want the end result to look like this:

Day Month       New_Col
7   2017-09-01  2017-09-07
21  2017-11-01  2017-11-21
14  2017-09-01  2017-09-14

Upvotes: 1

Views: 1117

Answers (1)

jezrael
jezrael

Reputation: 862406

Convert column Month to datetimes by to_datetime and add column Day converted to_timedeltas:

df['New_Col'] = pd.to_datetime(df['Month']) + pd.to_timedelta(df['Day'], unit='d')
print (df)
        Month  Day    New_Col
0  2017-09-01    7 2017-09-08
1  2017-11-01   21 2017-11-22
2  2017-09-01   14 2017-09-15

If need subtract one day:

df['New_Col'] = pd.to_datetime(df['Month']) + pd.to_timedelta(df['Day'] - 1, unit='d')
print (df)
        Month  Day    New_Col
0  2017-09-01    7 2017-09-07
1  2017-11-01   21 2017-11-21
2  2017-09-01   14 2017-09-14

Upvotes: 2

Related Questions