[英]Delete specific value and subsequent row in a pandas df
I want to delete
specific rows
in a pandas
df
. 我想
delete
pandas
df
特定rows
。 I want to remove a row
based on an undesired value plus the subsequent row
. 我想删除一个
row
基于在不恰当的值加上后续row
。 For the following df
I want to remove the row
where Code == 'Cat'
plus the subsequent row
. 对于下面的
df
我想删除的row
那里Code == 'Cat'
加上后续row
。 Below is my attempt. 以下是我的尝试。
import pandas as pd
import pandas as pd 将熊猫作为pd导入
d = ({
'Code' : ['Foo','Bar','Cat','Foo','Foo'],
'Int' : ['x','y','a','a','x'],
})
df = pd.DataFrame(d)
df = df[df.Code.shift()!='Cat']
Code Int
0 Foo x
1 Bar y
2 Cat a
4 Foo x
Intended Output: 预期输出:
Code Val
0 Foo x
1 Bar y
2 Foo x
Use boolean indexing
with ~
operator (logical NOT ) and |
将
boolean indexing
与~
运算符(逻辑NOT )和|
operator (logical OR ): 运算符(逻辑或 ):
df[~(df.Code.eq('Cat') | df.Code.shift(1).eq('Cat'))]
Code Int
0 Foo x
1 Bar y
4 Foo x
One other way: 另一种方式:
df = df[~((df['Code'] == 'Cat') | (df['Code'].shift(1) == 'Cat'))]
And now: 现在:
print(df)
Is: 方法是:
Code Val
0 Foo x
1 Bar y
4 Foo x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.