Pandas - dataframe.apply(lambad x: x is np.nan) 不起作用 [英] Pandas - dataframe.apply(lambad x: x is np.nan) does not work

查看:68
本文介绍了Pandas - dataframe.apply(lambad x: x is np.nan) 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上dataframe中的一列有Nan和float,我想用apply来计算列中的值.如果值为nan,则返回else,计算.

So basically a column in dataframe has Nan and float, I want to use apply to calculate the value in the column. If the value is nan, then return else, calculate.

但看起来 x 是 lambda 中的 np.nan 并没有给我正确的答案.这是一个例子

But looks like x is np.nan in lambda does not give me the right answer. here is an example

In[6]: df = pd.DataFrame({'A':[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]})
In[7]: df.A.apply(lambda x: x is np.nan)

Out[7]: 
0    False
1    False
2    False
3    False
4    False
5    False

有人知道原因吗?

推荐答案

第一件事.得到你想要的:

First things first. To get what you want:

df.A.isnull()

其次,np.nan 没有可比性.按照设计 np.nan == np.nan 是假的.

Secondly, np.nan is not comparable. By design np.nan == np.nan is False.

为了解决这个问题,pandas 和 numpy 有特定的函数来测试它是否为空.你可以:

To get around this, pandas and numpy have specific functions to test if it is null. You could:

df.A.apply(pd.isnull)

但这与以下内容相同:

df.A.isnull()

我上面提到的.

这篇关于Pandas - dataframe.apply(lambad x: x is np.nan) 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆