Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从中选择条件为真的所有行_Python_Python 3.x_Pandas_Group By_Pandas Groupby - Fatal编程技术网

Python 从中选择条件为真的所有行

Python 从中选择条件为真的所有行,python,python-3.x,pandas,group-by,pandas-groupby,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的计数以来发生的所有事件。Seqno。是每个ID的序列号。 输出将是 Id Seqno. Event 1

我有一个数据帧

 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的计数以来发生的所有事件。Seqno。是每个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']]

我想知道是否有一个好办法。

多亏了cold、ALollz和Vaishali,通过使用
groupby
cumcount
的解释(从评论中),我们使用
reindex
ffill

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
s=df.loc[df.Event=='A'].groupby('Id').cumcount(升序=False).添加(1).重新索引(df.index)
s、 groupby(df['Id']).ffill()
出[57]:
0    3.0
1    3.0
2    2.0
3    1.0
4    1.0
5南
6    2.0
7    2.0
8    1.0
9    1.0
数据类型:64

yourdf=df[s.groupby(df['Id']).ffill()将
groupby
cumsum
一起使用,从每组A的计数中减去它,然后过滤:

g = df['Event'].eq('A').groupby(df['Id'])
df[(g.transform('sum') - g.cumsum()).le(1)]

   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

第2组不应该只包括最后2行吗?因为我们正在查找第二次出现A以后的行…如果我错了,请更正我。谢谢@coldspeed。实际上,对于每个组,我们都从上一次或最近的事件中计算A。一旦我们的计数等于2,我们将返回所有行(包括第二次出现的)直到结束(最近一次)该组的事件。逻辑仍然没有意义。对于Id 2,您包括序号为1的行,其中A的计数仍然为1。是的,@Vaishali,没错。对我来说仍然没有意义,OP。这是第二次从组的底部向上计数,然后返回下面的所有内容