How do i convert year and month name into datetime column for this dataframe:
region year Months
0 alabama 2018 January
1 alabama 2018 February
2 alabama 2018 March
3 alabama 2018 April
4 alabama 2018 May
When I do this:
pd.to_datetime(df_sub['year'] * 10000 + df_sub['Months'] * 100, format='%Y%m')
I get this error:
*** TypeError: unsupported operand type(s) for +: 'int' and 'str'
One of the ways to combine 3 columns corresponding to Year, Month, and Day in a dataframe is to parse them as date variable while loading the file as Pandas dataframe. While loading the file as Pandas' data frame using read_csv() function we can specify the column names to be combined into datetime column.
You can convert year
column to string, add Months
and use parameter format
in to_datetime
by http://strftime.org/:
print (pd.to_datetime(df_sub['year'].astype(str) + df_sub['Months'], format='%Y%B'))
0 2018-01-01
1 2018-02-01
2 2018-03-01
3 2018-04-01
4 2018-05-01
dtype: datetime64[ns]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With