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

问题描述 投票:0回答:2

我有一个df

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

Date 的数据类型是 object

我想要另一栏作为

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

这给出了月份的数字,但没有给出名称。

python pandas dataframe datetime series
2个回答
3
投票

使用

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

注意:如果您使用

locale
,请照顾好您的
dt.strftime


1
投票

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

df['month'] = pd.DatetimeIndex(df['Date']).month_name()
© www.soinside.com 2019 - 2024. All rights reserved.