【问题标题】:Work with date in DataFrame in Python Pandas?在 Python Pandas 的 DataFrame 中使用日期?
【发布时间】:2021-04-01 01:55:43
【问题描述】:

我有如下数据框:

rng = pd.date_range('2020-12-01', periods=5, freq='D')
df = pd.DataFrame({"ID" : ["1", "2", "1", "1", "2"],
                   "Date" : rng,
                   "status" : ["B2", "G8", "G8", "R7", "G8"]})

我需要在哪里创建 DataFrame:

  1. New1 = 最后一个 B2 状态协议的日期
  2. New2 = G8 状态的最后协议日期

下面我上传我需要的结果:

【问题讨论】:

    标签: python pandas dataframe date aggregation


    【解决方案1】:

    第一个想法是通过Series.isin 仅过滤带有status 的行,然后使用DataFrame.pivot_tablelast 聚合函数:

    df = (df[df['status'].isin(['B2','G8'])]
            .pivot_table(index='ID', columns='status', values='Date', aggfunc='last')
            .rename(columns={'B2':'New1','G8':'New2'})
            .reset_index()
            .rename_axis(None, axis=1)
            )
    
    print (df)
      ID       New1       New2
    0  1 2020-12-01 2020-12-03
    1  2        NaT 2020-12-05
    

    或者您可以在Date 中将不匹配的行替换为statusNaT

    df = (df.assign(Date = df['Date'].where(df['status'].isin(['B2','G8'])))
            .pivot_table(index='ID', columns='status', values='Date', aggfunc='last')
            .rename(columns={'B2':'New1','G8':'New2'})
            .reset_index()
            .rename_axis(None, axis=1)
            )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 2015-09-17
      • 2021-03-31
      • 2013-11-18
      相关资源
      最近更新 更多