【问题标题】:Find first occure in pandas df for a given column查找给定列的 pandas df 中的第一个出现
【发布时间】:2021-04-26 23:10:00
【问题描述】:

对于每个 customer_id 和 partition_date,我想找到给定 customer_id 出现在数据集中的第一个日期。这是我迄今为止尝试过的,但我一直收到以下错误:

df['first_seen_date'] = df.sort_values('partition_date').groupby('customer_id').first()

error:  Wrong number of items passed 3, placement implies 1

df

customer_id  partition_date  
24242        01.01.2020
24242        02.01.2020
24242        04.01.2020
35439        06.01.2020
35439        05.01.2020
35439        07.01.2020

期望的输出df

customer_id  first_seen_date
24242        01.01.2020
35439        05.01.2020

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你很接近,分配给新的DataFrame

    df1 = df.sort_values('partition_date').groupby('customer_id', as_index=False).first()
    

    或者使用DataFrame.drop_duplicates:

    df1 = df.sort_values('partition_date').drop_duplicates('customer_id')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多