简体   繁体   中英

Extract month name from date column pandas

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.

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 .

检查这个https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.month_name.html

df['month'] = pd.DatetimeIndex(df['Date']).month_name()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM