1

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

perhaps you can check another question of mine: stackoverflow.com/questions/54609989/….
@JAG2024 Sorry, I am offline now, on phone only.
That's okay! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.