gpt4 book ai didi

python - 在 Pandas 中使用 .notnull() 时正确的语法是什么?

转载 作者:太空狗 更新时间:2023-10-29 18:01:23 27 4
gpt4 key购买 nike

我想在数据框的多个列上使用 .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

另一个解决方案来自Ayhandropna 评论:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com