i have a df
Name Date
A 2021-04-21
B 2021-03-21
C 2021-02-23
D 2021-03-22
and the dtype of Date is object
i want another column as
Name Date Month
A 2021-04-21 April
B 2021-03-21 March
C 2021-02-23 February
D 2021-03-22 January
Tried with
df['month'] = pd.DatetimeIndex(df['Date']).month
this is giving the number of the month but not the name.
CodePudding user response:
Use dt.strftime
:
df['Month'] = pd.to_datetime(df['Date']).dt.strftime('%B')
print(df)
# Output
Name Date Month
0 A 2021-04-21 April
1 B 2021-03-21 March
2 C 2021-02-23 February
3 D 2021-03-22 March
Or dt.month_name
:
df['Month'] = pd.to_datetime(df['Date']).dt.month_name()
print(df)
# Output
Name Date Month
0 A 2021-04-21 April
1 B 2021-03-21 March
2 C 2021-02-23 February
3 D 2021-03-22 March
Note: take care of your locale
if you use dt.strftime
.
CodePudding user response:
Check this https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.month_name.html
df['month'] = pd.DatetimeIndex(df['Date']).month_name()