【问题标题】:convert from year-month-date to year-Quarter in pandas在熊猫中从年月日转换为年季
【发布时间】:2020-10-06 13:58:24
【问题描述】:

我有一个 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 的内容,并且必须是字符串而不是 periods

【问题讨论】:

  • IIUC df['first_date'].dt.to_period('Q')
  • 从你的代码我得到2018Q1,你能在年和Q之间加“-”

标签: python pandas


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 2019-02-05
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多