我想在数据框的多个列上使用 .notnull()
来消除包含“NaN”值的行。
假设我有以下 df
:
A B C
0 1 1 1
1 1 NaN 1
2 1 NaN NaN
3 NaN 1 1
我尝试使用此语法但它不起作用?你知道我做错了什么吗?
df[[df.A.notnull()],[df.B.notnull()],[df.C.notnull()]]
我得到这个错误:
TypeError: 'Series' objects are mutable, thus they cannot be hashed
我应该怎么做才能获得以下输出?
A B C
0 1 1 1
有什么想法吗?
最佳答案
您可以先通过 df[['A','B','C']]
选择列的子集,然后应用 notnull
并指定是否 all
掩码中的值为 True
:
print (df[['A','B','C']].notnull())
A B C
0 True True True
1 True False True
2 True False False
3 False True True
print (df[['A','B','C']].notnull().all(1))
0 True
1 False
2 False
3 False
dtype: bool
print (df[df[['A','B','C']].notnull().all(1)])
A B C
0 1.0 1.0 1.0
print (df.dropna(subset=['A', 'B', 'C']))
A B C
0 1.0 1.0 1.0
什么是相同的:
print (df.dropna(subset=['A', 'B', 'C'], how='any'))
意味着删除所有行,其中至少有一个 NaN
值。
关于python - 在 Pandas 中使用 .notnull() 时正确的语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38702332/