我有以下DF
45 2018-01-01
73 2018-02-08
74 2018-02-08
75 2018-02-08
76 2018-02-08
我想用以下格式以一种简单的方式提取月份名称和年份:
45 Jan-2018
73 Feb-2018
74 Feb-2018
75 Feb-2018
76 Feb-2018
我使用了df.Date.dt.to_period("M")
格式,该格式返回"2018-01"
。
答案 0 :(得分:1)
将日期从对象日期更改为实际日期时间,然后使用dt访问所需的内容。
import pandas as pd
df = pd.DataFrame({'Date':['2019-01-01','2019-02-08']})
df['Date'] = pd.to_datetime(df['Date'])
# You can format your date as you wish
df['Mon_Year'] = df['Date'].dt.strftime('%b-%Y')
# the result is object/string unlike `.dt.to_period('M')` that retains datetime data type.
print(df['Mon_Year'])
答案 1 :(得分:0)
首先使用
将列转换为日期时间数据类型import concurrent.futures
那你就可以了
sales_df['Date'] = pd.to_datetime(sales_df['Date'])