我有一些代码可以在任意数据帧中查找丢失的值。出于我的目的,empty表示null或空字符串。以下是一个按预期工作的示例:
s1 = pd.Series(name="Strings", data=['aa', 'bb', ''], dtype=str)
s2 = pd.Series(name="Ints", data=[1, 2, 3], dtype=int)
s3 = pd.Series(name="Floats", data=[1.1, 2.2, np.nan], dtype=float)
df = pd.concat([s1, s2, s3], axis="columns")
empty = (df == '') | df.isnull()
让我们添加另一个具有可为null布尔值的列:
s4 = pd.Series(name="Nullable_Booleans", data=[True, False, pd.NA], dtype="boolean")
df = pd.concat([s1, s2, s3, s4], axis="columns")
empty = (df == '') | df.isnull()
现在空字符串的测试中断:
TypeError: values should be boolean numpy array. Use the 'pd.array' function instead
当数据帧可能包含可为null的布尔值时,检查任意数据帧是否有空字符串的好方法是什么?
替换:
empty = (df == '') | df.isnull()
带有:
empty = (df.astype('object') == '') | df.isnull()
空:
Strings Ints Floats Nullable_Booleans
0 False False False False
1 False False False False
2 True False True True