python - 如果字符串不等于值则删除行 - Pandas

如果特定值之后的字符串不等于值列表,我希望删除行。具体来说,如果 '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/

相关文章:

postgresql - 尝试访问数据库或从数据库获取数据时,用户的 PostgresQL 密码身份

scala - 在范围内显示时未找到隐式

design-patterns - 使用字符串与枚举作为工厂方法的参数?

c++ - 为什么 sizeof 运算符对数组产生不同的结果

unix - Linux : How to AWK to find maximums in ever

r - 在 R 中的特定值之后将每行的值设置为 NA

python - 避免嵌套 .apply()

r - 有条件地替换 R 中的值

string - 为什么 String::from(&str) 和 &str.to_string()

javascript - jQuery 获取所有 值的数组