【问题标题】:How to create columns based on date in DataFrame in Python Pandas?如何在 Python Pandas 的 DataFrame 中根据日期创建列?
【发布时间】:2021-03-31 05:40:08
【问题描述】:

我有如下数据框:

rng = pd.date_range('2020-12-01', periods=5, freq='D')
df = pd.DataFrame({"ID" : ["1", "2", "1", "1", "2"],
                   "Date" : rng,
                   "kind" : ["active", "not_active", "active", "active", "not_active"],
                   "status" : ["b2", "b2", "g8", "g8", "v10"]})

我需要创建 DataFrame,它将显示最后一个活动和最后一个非活动协议的状态。下面我上传结果示例:

【问题讨论】:

    标签: python pandas dataframe date aggregation


    【解决方案1】:

    如果日期时间已排序,您可以使用DataFrame.pivot_table:

    df = (df.pivot_table(index='ID', columns='kind', values='status', aggfunc='last')
            .reset_index()
            .rename_axis(None, axis=1))
    

    如果不确定是否排序添加DataFrame.sort_values:

    df = (df.sort_values(['ID','Date'])
            .pivot_table(index='ID', columns='kind', values='status', aggfunc='last')
            .reset_index()
            .rename_axis(None, axis=1))
    print (df)
      ID active not_active
    0  1     g8        NaN
    1  2    NaN        v10
    

    【讨论】:

      猜你喜欢
      • 2023-02-15
      • 2021-03-20
      • 2021-12-14
      • 1970-01-01
      • 2019-04-29
      • 2022-07-13
      • 1970-01-01
      • 2021-04-29
      • 2022-12-10
      相关资源
      最近更新 更多