【问题标题】:Groupby and subsetting rows based on condition基于条件的分组和子集行
【发布时间】:2018-12-27 15:27:21
【问题描述】:

我想过滤我的数据框。

我的数据框

  Col1    col2
0    A  event1
1    A  event2
2    A  event3
3    A  event2
4    B  event1
5    B  event3
6    B  event2
7    B  event2

输出数据帧

  Col1    col2
     A  event1
     B  event1
     B  event3

它应该为每个组返回 event2 之前的行。 到目前为止我试过了

df.groupby('col1').apply(lambda x :x[0:x[x['col2'] == 'event2'].index[0]])

但它没有返回所需的行。

【问题讨论】:

    标签: python pandas dataframe group-by pandas-groupby


    【解决方案1】:

    我们可以使用groupbycumsum 来做到这一点,然后是最后的过滤步骤:

    df[df.col2.eq('event2').groupby(df.Col1).cumsum().eq(0)]
    
      Col1    col2
    0    A  event1
    4    B  event1
    5    B  event3
    

    要将索引重置为单调递增的范围,请使用

    df[df.col2.eq('event2').groupby(df.Col1).cumsum().eq(0)].reset_index(drop=True)
    
      Col1    col2
    0    A  event1
    1    B  event1
    2    B  event3
    

    Scott Boston 建议在布尔掩码上使用 cumprod 对上述解决方案进行很好的改进。原理是一样的,但是更干净:

    df[df.col2.ne('event2').groupby(df.Col1).cumprod()]
    
      Col1    col2
    0    A  event1
    4    B  event1
    5    B  event3
    

    W-B 建议的基于groupby + idxmax 的过滤:

    df[df.index < df.col2.eq('event2').groupby(df.Col1).transform('idxmax')]
    
      Col1    col2
    0    A  event1
    4    B  event1
    5    B  event3
    

    【讨论】:

    • 我通过少一种方法得到了。 df[df.col2.ne('event2').groupby(df.Col1).cumprod()]
    • @ScottBoston 太棒了。不知道您可以将 cumprod 与这样的布尔值一起使用。我可以吗?
    • 这很好:-)
    • 你也想添加这个吗df[df.index&lt;df.col2.eq('event2').groupby(df.Col1).transform('idxmax')]
    • @W-B 谢谢人 :) 这是一种不同的方法,请添加答案,我一定会投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2019-12-19
    • 1970-01-01
    • 2014-10-30
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多