这本质上是对我的 answer here 内容的重新哈希处理.
我在尝试解决 this question 时遇到了一些奇怪的行为, 使用 pd.notnull
。
考虑
x = ('A4', nan)
我想检查这些项目中哪些是空的。直接使用 np.isnan
会抛出 TypeError(但我已经找到解决方法)。
使用 pd.notnull
无效。
>>> pd.notnull(x)
True
它将元组视为单个值(而不是可迭代的值)。此外,将其转换为列表然后进行测试也会给出错误的答案。
>>> pd.notnull(list(x))
array([ True, True])
因为第二个值是nan
,所以我要找的结果应该是[True, False]
。当您预转换为系列时,它终于起作用了:
>>> pd.Series(x).notnull()
0 True
1 False
dtype: bool
因此,解决方案是对其进行系列化,然后测试值。
沿着类似的路线,另一个(公认的迂回)解决方案是预转换为 object
dtype numpy 数组,以及 pd.notnull
或 np.isnan
将直接工作:
>>> pd.notnull(np.array(x, dtype=object))
Out[151]: array([True, False])
我想象pd.notnull
直接将x
暗中转换为字符串数组,将NaN渲染为字符串“nan”,所以它不再是一个“空”值。
pd.notnull
在这里做同样的事情吗?还是我应该注意幕后发生的其他事情?
注意事项
In [156]: pd.__version__
Out[156]: '0.22.0'
最佳答案
这是与此行为相关的问题:https://github.com/pandas-dev/pandas/issues/20675 .
简而言之,如果传递给 notnull
的参数是 list
类型,则在内部将其转换为 np.array
并使用 np .asarray
方法。出现此错误是因为,如果未指定 dtype
,numpy 会将 np.nan
转换为 string
(pd. isnull
作为 null 值):
a = ['A4', np.nan]
np.asarray(a)
# array(['A4', 'nan'], dtype='<U3')
此问题已在 0.23.0 版中通过使用 dtype=object
调用 np.asarray
得到修复。
关于python - pd.notnull 奇怪的 null 检查行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51035790/