在pandas数据框中检查是否有空值。

19

我想找到数据框中的None所在位置。

pd.DataFrame([None,np.nan]).isnull()
OUT: 
      0
0  True
1  True

isnull()函数可用于查找numpy Nan和None值。

我只想要None值,而不是numpy Nan。有没有更简单的方法可以避免遍历整个数据框架?

编辑: 阅读评论后,我意识到我的工作中的数据框也包括字符串,因此None值没有被强制转换为numpy Nan。因此Pisdom给出的答案是有效的。


据我所知,这在Pandas中是不可能的:Pandas将None视为缺失数据,并将它们(等同于)NaN。即使通过“循环遍历数据框”,您也无法区分NoneNaN。请参阅有关缺失数据的文档 - user707650
1
你可能需要重新考虑你的问题,并看看是否真的需要区分NaN和None。或者,你可以引入一个(布尔)列来指示一个值是None还是浮点值(包括NaN);也就是所谓的掩码。 - user707650
4个回答

20
如果你想为每一行获取True/False值,你可以使用以下代码。下面是一个DataFrame示例的结果:
df = pd.DataFrame([[None, 3], ["", np.nan]])

df
#      0      1
#0  None    3.0
#1          NaN

如何检查None

可用方法:.isnull()

>>> df[0].isnull()
0     True
1    False
Name: 0, dtype: bool

可用: .apply == 或者 is None

>>> df[0].apply(lambda x: x == None)
0     True
1    False
Name: 0, dtype: bool

>>> df[0].apply(lambda x: x is None)
0     True
1    False
Name: 0, dtype: bool

可用: .values == None

>>> df[0].values == None
array([ True, False])

无法使用: is==

>>> df[0] is None
False

>>> df[0] == None
0    False
1    False
Name: 0, dtype: bool

不可用: .values None

>>> df[0].values is None
False

如何检查 np.nan

可用方法: .isnull()

>>> df[1].isnull()
0    False
1     True
Name: 1, dtype: bool

可用:np.isnan

>>> np.isnan(df[1])
0    False
1     True
Name: 1, dtype: bool

>>> np.isnan(df[1].values)
array([False,  True])

>>> df[1].apply(lambda x: np.isnan(x))
0    False
1     True
Name: 1, dtype: bool

不可用: is== np.nan

>>> df[1] is np.nan
False

>>> df[1] == np.nan
0    False
1    False
Name: 1, dtype: bool

>>> df[1].values is np.nan
False

>>> df[1].values == np.nan
array([False, False])

>>> df[1].apply(lambda x: x is np.nan)
0    False
1    False
Name: 1, dtype: bool

>>> df[1].apply(lambda x: x == np.nan)
0    False
1    False
Name: 1, dtype: bool

9
您可以使用带有lambda的applymap来检查元素是否为None,例如:(这里给出了一个不同的示例,在您原始的示例中,由于数据类型为float,None被强制转换为np.nan,因此您需要一个对象类型的列来保持None,或者如@Evert所评论的那样,在数字类型列中,None和NaN是无法区分的):
df = pd.DataFrame([[None, 3], ["", np.nan]])

df
#      0      1
#0  None    3.0
#1          NaN

df.applymap(lambda x: x is None)

#       0       1
#0   True   False
#1  False   False

1
这仅仅是因为你使用了一个空字符串,从而改变了数据类型;如果将字符串更改为任何数字(整数或浮点数),那么 None 将会变成 NaN - user707650
@Evert 是的。我已经添加了注释,即 None 只能存在于 object 类型的列中。 - Psidom

1

问题:如何在DataFrame / Series中检查None

答案:isna可以工作,但也会捕捉到nan。 两个建议:

  1. 使用x.isna()并将none替换为nan
  2. 如果您真的关心Nonex.applymap(type) == type(None)

我更喜欢比较类型,因为例如nan == nan是false。 在我的情况下,None出现了意外,所以x[x.isna()] = nan解决了问题。

示例:

x = pd.DataFrame([12, False, 0, nan, None]).T

x.isna()
      0      1      2     3     4
0  False  False  False  True  True

x.applymap(type) == type(None)
       0      1      2      3     4
0  False  False  False  False  True

x
    0      1  2    3     4
0  12  False  0  NaN  None

x[x.isna()] = nan
    0      1  2    3    4
0  12  False  0  NaN  NaN

0
要获取非空值的整体概述,你只需使用 df.info()。
[Dataframe ifo output](link1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接