How to change the month of a datetime object in pandas?

Asked

Viewed 349 times

-1

good afternoon, I have a column of the pandas dataset for the month of September whose . head() is:

[in] :df_setembro.head()

[out]:

 0    01/08/2018
 1    02/08/2018
 2    03/08/2018
 3    04/08/2018
 4    05/08/2018

would like to change the number of the month to the correct number 09 but whenever I try to make changes python points out that the column is of type Series for more that I have already switched to used the function to_datetime, someone knows how to help me?

  • A curiosity: if it refers to the month of September, where the value 8 appeared in the month?

  • federal government data, I imagine some server gave Ctr+c and Ctr+v on CSV August and did not fix

1 answer

0


It is possible to use the lambda apply method that filters the dates of the month of August and then replace.

import pandas as pd

df = pd.DataFrame({'year': [2018, 2018, 2018, 2018, 2018, 2018],
                   'month': [8, 8, 8, 8, 8, 12],
                   'day': [1, 2, 3, 4, 5, 31]
})

df2 = pd.to_datetime(df)

print(df2)

df3 = df2[df2.apply(lambda dt: dt.month == 8)].apply(lambda dt: dt.replace(month=9))

print(df3)
  • look I tried to use this selection and the output was the same: Attributeerror: ("'Series' Object has no attribute 'Month'", 'occurred at index code')

  • edited with the full example

  • Look, I’m really lost. My date is not as divided as yours, where each column refers to the day, month and year. they are all together and when I try to follow their resolution the result is: day is out of range for Month

Browser other questions tagged

You are not signed in. Login or sign up in order to post.