从日期列中提取月份名称 pandas

Extract month name from date column pandas

我有一个df

Name Date
A    2021-04-21
B    2021-03-21
C    2021-02-23
D    2021-03-22

Date 的 dtype 是对象

我想要另一列作为

Name Date         Month
A    2021-04-21   April
B    2021-03-21   March
C    2021-02-23   February
D    2021-03-22   January

尝试过

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

这是给出月份的数字而不是名称。

使用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

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

注意:如果您使用 dt.strftime,请注意您的 locale

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

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