如果特定值之后的字符串不等于值列表,我希望删除行。具体来说,如果 'Up' 或 'Left'
之后的后续行后面没有 'Right'
或 'Down'
那么我'我的目标是删除这些行。
import pandas as pd
df = pd.DataFrame({
'Label' : ['A','B','A','B','B','B','A','B','B','A','A','A'],
'Item' : ['X','Left','X','Left','Down','Right','Up','Y','Right','Y','Right','Up'],
})
df1 = df[~(df['Item'].isin(['Up','Left']).shift(1)) & (df['Item'].isin(['Right','Down']))]
Label Item
0 A X
1 B Left
2 A X # Drop. Not Right/Down
3 B Left
4 B Down # Keep. Right/Down
5 B Right
6 A Up
7 B Y # Drop. Not Right/Down
8 B Right
9 A Y
10 A Right
11 A Up
预期输出:
Label Item
0 A X
1 B Left
3 B Left
4 B Down
5 B Right
6 A Up
8 B Right
9 A Y
10 A Right
11 A Up
最佳答案
您的代码很好,只是缺少第二个条件中的not
if the subsequent row after either 'Up' or 'Left' is not followed by 'Right' or 'Down' then I'm aiming to drop those rows.
所以应该是这样的:
df1 = df[~(((df['Item'].isin(['Up','Left']).shift(1)) & ~(df['Item'].isin(['Right','Down']))))]
关于python - 如果字符串不等于值则删除行 - Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67085285/