Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert year and month name into datetime column for pandas dataframe

Tags:

python

pandas

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'
like image 522
user308827 Avatar asked Jun 03 '18 06:06

user308827


People also ask

How do I merge year and month column in pandas?

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.


1 Answers

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]
like image 130
jezrael Avatar answered Sep 22 '22 06:09

jezrael