我想找到数据框中没有找到的地方。
pd.DataFrame([None,np.nan]).isnull()
OUT:
0
0 True
1 True
isnull()找到numpy Nan和None值。
我只想要None值而不是numpy Nan。如果没有循环遍历数据框,有没有更简单的方法呢?
编辑: 在阅读完评论后,我意识到在我的工作中我的数据框中也包含了字符串,所以None并没有被强制为numpy Nan。所以Pisdom的答案是有效的。
答案 0 :(得分:3)
您可以将applymap
与lambda
一起使用来检查element is None
是否如下所示(构建了一个不同的示例,与原始版本一样,None
被强制执行np.nan
因为数据类型为float
,您需要object
类型列按原样保留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 :(得分:1)
如果要为每一行获取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
is
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