繁体   English   中英

pandas:如果组的最后一行具有特定的列值,如何删除组的所有行

[英]pandas: how to drop all rows of a group if the last row of the group has certain column value

我有一个df,如下所示

    a    c    d
0  ABC   0.4  y
1  ABC   0.3  x
2  DEF   0.3  x
3  DEF   0.2  x
4  DEF   0.5  x
5  DEF   0.4  y

我想按列'c'对df进行排序,然后按列'a'对df进行排序,然后如果组的最后一行的列'd'='y'的值,则删除组的所有行

我预期的 output 是

    a    c    d
2  DEF   0.2  x
3  DEF   0.3  x
4  DEF   0.4  y
5  DEF   0.5  x

因此,在按 col 'c' 作为组 d = y 中的最后一行排序后,组 'ABC' 被删除,但组 'DEF' 保留为 DEF col d = x 中的最后一行

直接从你的逻辑:

mask = (df.sort_values('c')     # sort the values by `c`
          .groupby('a')['d']    # groupby `a` and look at `d`
          .transform('last')    # select the last rows
          .ne('y')              # check if last rows are `y`
          .reindex(df.index)    # reindex as the original data
       )

df = df[mask]

Output:

     a    c  d
2  DEF  0.3  x
3  DEF  0.2  x
4  DEF  0.5  x
5  DEF  0.4  y

让我们做filter

df=df.groupby('a').filter(lambda x : x.at[x['c'].idxmax(),'d']!='y')
Out[278]: 
     a    c  d
2  DEF  0.3  x
3  DEF  0.2  x
4  DEF  0.5  x
5  DEF  0.4  y

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM