Pun*_*nha 0 python group-by dataframe pandas pandas-groupby
我有一个看起来像熊猫的“数据框”,如果需要pd.Dataframe下表,也请告诉我。
iD a b c
c1 2 3 4
c1 2 3 4
c1 2 3 4
c1 2 E 4
c1 2 3 4
c2 3 4 5
c2 3 4 5
c2 3 E 5
c2 3 4 5
Run Code Online (Sandbox Code Playgroud)
现在在此数据帧中有两个ID c1和c2。每当“ E”出现在“ b”列中时,我想删除上面的所有行。
我的最终数据框应该看起来像
iD a b c
c1 2 E 4
c1 2 3 4
c2 3 E 5
c2 3 4 5
Run Code Online (Sandbox Code Playgroud)
只是想使问题简短,以便人们回答。请让我知道是否需要在数据框中添加一些额外的数据点
在布尔值的掩码上使用groupby和cumsum,以比较列“ b”和字母“ E”:
df[df.b.eq('E').groupby(df.iD).cumsum()]
iD a b c
3 c1 2 E 4
4 c1 2 3 4
7 c2 3 E 5
8 c2 3 4 5
Run Code Online (Sandbox Code Playgroud)
df[df.b.eq('E').groupby(df.iD).cumsum()].reset_index(drop=True)
iD a b c
0 c1 2 E 4
1 c1 2 3 4
2 c2 3 E 5
3 c2 3 4 5
Run Code Online (Sandbox Code Playgroud)