使用2个掩码进行布尔索引:
boolean indexing
。
df1 = df[(df['a'].isnull() == df['b'].isnull()) & (df['a'] != df['b'])]
print (df1)
a b
2 2.0 0.0
4 0.0 1.0
细节:
print ((df['a'].isnull() == df['b'].isnull()))
0 False
1 True
2 True
3 False
4 True
dtype: bool
print ((df['a'] != df['b']))
0 True
1 False
2 True
3 True
4 True
dtype: bool
print ((df['a'].isnull() == df['b'].isnull()) & (df['a'] != df['b']))
0 False
1 False
2 True
3 False
4 True
dtype: bool
处理多列的通用解决方案 - 首先使用all
检查每行中所有的True
是否不是NaN
,然后通过eq
与第一列比较并使用any
返回每行至少一个True
:
df1 = df[df.notnull().all(axis=1) & df.ne(df.iloc[:, 0], axis=0).any(axis=1)]
print (df1)
a b
2 2.0 0.0
4 0.0 1.0
细节:
print (df.notnull())
a b
0 False True
1 True True
2 True True
3 True False
4 True True
print (df.notnull().all(axis=1))
0 False
1 True
2 True
3 False
4 True
dtype: bool
print (df.ne(df.iloc[:, 0], axis=0))
a b
0 True True
1 False False
2 False True
3 False True
4 False True
print (df.ne(df.iloc[:, 0], axis=0).any(axis=1))
0 True
1 False
2 True
3 True
4 True
dtype: bool
另一个解决方案:
df = df[(df['a'].notnull()) & (df['b'].notnull()) & (df['a'] != df['b'])]
print (df)
a b
2 2.0 0.0
4 0.0 1.0
0
并返回行吗?还是其他什么?谢谢。 - jezrael