我有一個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
這是給出月份的編號,而不是名稱。
uj5u.com熱心網友回復:
使用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.
uj5u.com熱心網友回復:
檢查這個 https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.month_name.html
df['month'] = pd.DatetimeIndex(df['Date']).month_name()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483915.html
