【问题标题】:Python calculate a new column based on Date columnPython根据日期列计算新列
【发布时间】:2017-08-05 12:46:30
【问题描述】:

得到一个日期列,其值如下:"1997-08-05T00:00:00" 从 1997 年到 2017 年,其值为一周中的 5 个工作日。

我想在数据集中创建一个新列来计算日期的四分之一。 例如:

1997-01-01 to 1997-03-31 should become Q1
1997-04-01 to 1997-06-30 should become Q2
1997-07-01 to 1997-09-30 should become Q3
1997-10-01 to 1997-12-31 should become Q4

不仅是 1997 年,而且直到 2017 年的所有日期都应该在名为“季度”的新列上获得一个值。 如果不考虑年份,01-01 到 03-31 之间的日期被指定为 Q1 等等,那就太好了

(日期看起来都是这样的:1997-08-05T00:00:00 但我不需要T00:00:00 的部分)

【问题讨论】:

    标签: python pandas date


    【解决方案1】:

    只要您的 Date 列是日期时间格式,您就可以使用 pandas to_period 函数。

    df['quarter'] = df['Date'].dt.to_period('Q')
    

    这将以类似于 2017Q3 的格式返回季度。然后,您可以通过以下方式去掉年份:

    df['quarter'] = df['quarter'].apply(lambda x: str(x)[-2:])
    

    这将为您提供一列 Q1、Q2、Q3、Q4 值。

    【讨论】:

      【解决方案2】:

      使用“季度”。

      例如:

      pd.to_datetime(pd.DataFrame(['1997-08-05T00:00:00'])[0]).dt.quarter
      >>>3
      

      然后只需在数字前添加“Q”字母即可。

      【讨论】:

        猜你喜欢
        • 2017-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-09
        相关资源
        最近更新 更多