【问题标题】:Filter column for multiple values but only select the last one for one criteria过滤多个值的列,但只为一个条件选择最后一个
【发布时间】:2022-09-30 23:18:03
【问题描述】:

我有一个类似于这个的数据框

df = pd.DataFrame({\'date\':[20220101,20220102,20220103,20220101,20220102,20220101], \'id\':[1,1,1,2,2,3], \'value\':[11,22,33,44,55,66], \'categorie\':[\'a\',\'a\',\'c\',\'a\',\'c\',\'c\']})

       date  id  value categorie
   20220101   1     11         a
   20220102   1     22         a
   20220103   1     33         c
   20220101   2     44         a
   20220102   2     55         c
   20220101   3     66         c

我现在想根据列 \'categorie\' 中的多个值对 df 进行切片,并且目前正在使用

df = df[df[\'categorie\'].isin([\'a\',\'c\'])]

除此之外,我希望能够只为类别 \'a\' 获得 [-1] 行

    date  id  value categorie
20220102   1     22         a
20220103   1     33         c
20220101   2     44         a
20220102   2     55         c
20220101   3     66         c

代替

    date  id  value categorie
20220101   1     11         a
20220102   1     22         a 
20220103   1     33         c
20220101   2     44         a
20220102   2     55         c
20220101   3     66         c

我认为最接近的方法是将其视为 id 和 categorie 的 groupby 最大值,但我很好奇是否有更 Pythonic 的方式。

    标签: python dataframe slice


    【解决方案1】:

    'a' 和 'c' 是您数据中唯一的类别,如果您只需要最新的类别,请删除重复项

    # drop duplicates and keep the last
    df.drop_duplicates(subset=['id','categorie'], keep='last')
    

    或者

    # select the categories of 'a' and 'c' and drop the duplicates from among them
    (df.loc[df['categorie'].isin(['a','c'])]
     .drop_duplicates(subset=['id','categorie'], keep='last'))
    
        date       id   value   categorie
    1   20220102    1      22   a
    2   20220103    1      33   c
    3   20220101    2      44   a
    4   20220102    2      55   c
    5   20220101    3      66   c
    

    【讨论】:

    • 不幸的是,在我的实际数据集中会有更多。它基本上是盘中数据,从一个类别中我只需要最后一个值
    • 添加了替代解决方案。 drop_duplicate 只会保留最后一个值
    • 它如何无法回答您的问题?我错过了什么?
    猜你喜欢
    • 1970-01-01
    • 2011-05-09
    • 2012-02-22
    • 2021-12-23
    • 2013-08-22
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    相关资源
    最近更新 更多