2017-07-20 32 views
2

我试图在Pandas DataFrame列中将NaN转换为0,并且“where”函数的行为与我期望的相反。pandas其中函数行为与我所期望的相反

下面的代码将在索引4,5,6创建包含一列与NaN的数据帧和7.

from collections import Counter 
import pandas as pd 

x = Counter(pd.np.random.choice(24,2000)) 
df = pd.DataFrame({'x':x}) 
df.loc[4:7,'x'] = pd.np.nan 
df 

我用

df.where(df.isnull() == True,0) 

期待其中NaN值分别为到被改为0.相反,发生的事情是一切,但NaN的变为0.

任何人都可以解释背后的逻辑在哪里工作?

回答

2
df.where(condition,other) 

其中方法是如果 - 则成语的一个应用程序。对于调用DataFrame中的每个元素,如果cond为True,则使用该元素;否则使用DataFrame中的相应元素。

简单如果条件满足,则数据帧是不变的,否则设置为0(其他参数中提到的任何值)

在你的代码的简单改变将正常工作:

变化

df.where(df.isnull() == True,0) 

df.where(df.notnull() == True,0) 

df.where(df.isnull() != True,0) 
1

首先,你需要使用:

df.mask(df.isnull() == True,0) 

或者

df.where(df.isnull() != True,0) 

输出 - 头(10):

 x 
0 85.0 
1 96.0 
2 78.0 
3 93.0 
4 0.0 
5 0.0 
6 0.0 
7 0.0 
8 100.0 
9 77.0 

现在,df.where(condition,0)状态:

返回与自身形状相同的对象,其相应条目 来自self,其中cond为True,否则为其他。

因此,当条件为真则返回当前值,否则为0。

df.mask(condition,0)则相反的文档状态:

返回相同的形状自的目的,并且其相应的项 来自自我cond是假的,否则是来自其他。

所以假当返回当前值,否则(当真)返回0

相关问题