选择条件满足的所有熊猫行

时间:2019-01-22 21:20:24

标签: python python-3.x pandas group-by pandas-groupby

我有一个数据框

 Id  Seqno. Event
 1     2    A 
 1     3    B 
 1     5    A 
 1     6    A 
 1     7    D
 2     0    E
 2     1    A 
 2     2    B 
 2     4    A 
 2     6    B

我想让所有事件发生,因为每个ID最近发生的模式A计数= 2。序号是每个ID的序号。 输出将是

 Id  Seqno. Event 
 1     5    A 
 1     6    A 
 1     7    D
 2     1    A 
 2     2    B 
 2     4    A 
 2     6    B

到目前为止,我尝试过

  y=x.groupby('Id').apply( lambda 
  x:x.eventtype.eq('A').cumsum().tail(2)).reset_index()
  p=y.groupby('Id').apply(lambda x:       
  x.iloc[0]).reset_index(drop=True)
  q= x.reset_index()
  s= pd.merge(q,p,on='Id')
  dd= s[s['index']>=s['level_1']]

我想知道是否有一个很好的方法。

2 个答案:

答案 0 :(得分:3)

head() { return { title: 'That', meta: [ { hid: `og:description`, name: 'og:description', content: '3' }, { hid: `og:title`, name: 'og:title', content: '4' } ] } groupby一起使用,从每个组的A计数中减去它,然后进行过滤:

cumsum

答案 1 :(得分:2)

通过groupbycumcount的解释(从注释中),通过感冒,ALollz和Vaishali获得计数,然后我们使用reindexffill < / p>

s=df.loc[df.Event=='A'].groupby('Id').cumcount(ascending=False).add(1).reindex(df.index)
s.groupby(df['Id']).ffill()
Out[57]: 
0    3.0
1    3.0
2    2.0
3    1.0
4    1.0
5    NaN
6    2.0
7    2.0
8    1.0
9    1.0
dtype: float64
yourdf=df[s.groupby(df['Id']).ffill()<=2]
yourdf
Out[58]: 
   Id  Seqno. Event
2   1       5     A
3   1       6     A
4   1       7     D
6   2       1     A
7   2       2     B
8   2       4     A
9   2       6     B
相关问题