从年月日转换为熊猫年季

时间:2020-06-16 20:46:39

标签: python pandas

我有一个pandas数据框,其中一列(first_date)包含以下格式的日期: 2018-03-31

#I have created a monthly level data using the below code
    dataset['first_date']=pd.to_datetime(dataset['first_date']) 
    dataset['first_date'].apply(lambda x: x.strftime('%Y-%m'))
    **output: 2018-03**

我的问题:使用first_date我想创建一个新列,以获取年份和季度。 输出类似 2018-Q1 的内容,并且必须以字符串形式出现在期间

1 个答案:

答案 0 :(得分:1)

尝试一下:

df['first_date'] = pd.to_datetime(df['first_date']).dt.strftime('%Y-%m')
df['quarter'] = pd.to_datetime(df['first_date']).dt.to_period('Q').astype(str).str.replace('Q', '-Q')
print(df)

 first_date  quarter
0    2018-03  2018-Q1
1    2018-03  2018-Q1
2    2018-03  2018-Q1
3    2018-03  2018-Q1
4    2018-03  2018-Q1
5    2018-05  2018-Q2
6    2018-09  2018-Q3