大熊猫的功能与我的期望相反

时间:2017-07-20 03:43:29

标签: python pandas

我正在尝试在Pandas DataFrame列中将NaN转换为0,而“where”函数的行为与我期望的相反。

以下代码将创建一个数据框,其中包含一个列为NaN的索引为4,5,6和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 个答案:

答案 0 :(得分:3)

 df.where(condition,other)

其中method是if-then惯用法的应用。对于调用DataFrame中的每个元素,如果cond为True,则使用该元素;否则使用DataFrame other中的相应元素。

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

您的代码中的简单更改将正常工作:

变化

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

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

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

答案 1 :(得分: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)与文档相反:

  

返回与self相同形状的对象及其对应的条目   来自自我,其中cond是假的,否则来自其他。

因此它在False时返回当前值,否则(当为True时)返回0