如何修复:ValueError不能用含有NA/NaN值的非布尔数组进行屏蔽

835 阅读2分钟

在使用pandas时,你可能遇到的一个错误是。

ValueError: Cannot mask with non-boolean array containing NA / NaN values

这个错误通常发生在你试图在pandas DataFrame中找到包含一个特定字符串的行,但你要搜索的列有NaN值。

下面的例子展示了如何在实践中解决这个错误。

如何重现这个错误

假设我们有如下的pandas DataFrame。

import pandas as pd
import numpy as np

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B'],
                   'position': ['Guard', 'Guard', np.nan, 'Guard', 'Forward'],
                   'points': [22, 28, 14, 13, 19]})

#view DataFrame
print(df)

  team position  points
0    A    Guard      22
1    A    Guard      28
2    A      NaN      14
3    B    Guard      13
4    B  Forward      19

现在假设我们试图访问DataFrame中位置列包含字符串 "Guard "的所有行。

#access all rows where position column contains 'Guard'
df[df['position'].str.contains('Guard')]

ValueError: Cannot mask with non-boolean array containing NA / NaN values

我们会收到一个错误,因为位置列中有一个NaN值。

如何修复这个错误

为了避免这个错误,我们只需要在str.contains()函数中使用参数na=False

#access all rows where position column contains 'Guard', ignore NaN
df[df['position'].str.contains('Guard', na=False)]

        team	position  points
0	A	Guard	  22
1	A	Guard	  28
3	B	Guard	  13

这次我们能够访问所有在position列中包含 "Guard "的行,而没有任何错误。

另一种避免这种错误的方法是使用**.fillna(False)**,如下所示。

#access all rows where position column contains 'Guard', ignore NaN
df[df['position'].str.contains('Guard').fillna(False)]

        team	position  points
0	A	Guard	  22
1	A	Guard	  28
3	B	Guard	  13

再一次,我们能够访问所有在位置列中包含 "Guard "的行,没有任何错误。

其他资源

下面的教程解释了如何修复Python中的其他常见错误:

如何修复Pandas中的KeyError
如何修复ValueError:无法将浮点数NaN转换为整数
如何修复ValueError:操作数不能与形状一起广播