繁体   English   中英

从日期列 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 是 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

这是给出月份的编号,而不是名称。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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