0

HI all I have a column in a dataframe that looks like:

print(df['Date']):

29-Nov-16
4-Dec-16
1-Oct-16
30-Nov-19
30-Jun-20
28-Apr-16
24-May-16

And i am trying to get an output that looks like

print(df):
Date            Month          Year
29-Nov-16       Nov             2016
4-Dec-16       Dec             2016
1-Oct-16       Oct             2016
30-Nov-19       Nov             2019
30-Jun-20       Jun             2020
28-Apr-16       Apr             2016
24-May-16       May             2016

I have tried the following:

df['Month'] = pd.datetime(df['Date']).month
df['Year'] = pd.datetime(df['Date']).year

but am getting a TypeError: cannot convert the series to <class 'int'>

Any ideas or references to help out? Thanks!

SOK
  • 1,732
  • 2
  • 15
  • 33

2 Answers2

2

Use strftime and str.split and assign them to new columns

df_final = df.assign(**pd.to_datetime(df['Date']).dt.strftime('%b-%Y')
                                                 .str.split('-', expand=True)
                                                 .set_axis(['Month','Year'], axis=1))

Out[32]:
        Date Month  Year
0  29-Nov-16   Nov  2016
1   4-Dec-16   Dec  2016
2   1-Oct-16   Oct  2016
3  30-Nov-19   Nov  2019
4  30-Jun-20   Jun  2020
5  28-Apr-16   Apr  2016
6  24-May-16   May  2016
Andy L.
  • 24,909
  • 4
  • 17
  • 29
1

you are missing dt after pd.datetime(df['Date'])

try this:

df['Month'] = pd.datetime(df['Date']).dt.month
df['Year'] = pd.datetime(df['Date']).dt.year
Hamid
  • 612
  • 1
  • 8
  • 20