Python 函数的行为与我期望的相反
我试图将Pandas DataFrame列中的NaN转换为0,“where”函数的行为与我预期的相反 下面的代码将创建一个数据框,其中包含一列,索引为4、5、6和7的NaNPython 函数的行为与我期望的相反,python,pandas,Python,Pandas,我试图将Pandas DataFrame列中的NaN转换为0,“where”函数的行为与我预期的相反 下面的代码将创建一个数据框,其中包含一列,索引为4、5、6和7的NaN 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.wh
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
谁能解释一下where的工作原理吗?首先,您需要使用:
df.mask(df.isnull() == True,0)
或
输出——压头(10):
现在,各国:
返回一个与self形状相同的对象及其相应的条目
是来自自我,条件为真,否则来自他人
因此,当条件为真时,它返回当前值,否则返回0
相反的文档是否说明:
返回一个与self形状相同的对象及其相应的条目
来自自身,其中cond为False,否则来自其他
因此,如果为False,则返回当前值;否则(如果为True),则返回0
where方法是if-then习惯用法的应用。对于调用数据帧中的每个元素,如果cond为True,则使用该元素;否则,将使用DataFrame other中的相应元素
简单地说,如果满足条件,则数据帧不变,否则设置为0(其他参数中提到的任何值)
对代码进行简单更改即可:
改变
df.where(df.isnull() == True,0)
到
或
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,other)
df.where(df.isnull() == True,0)
df.where(df.notnull() == True,0)
df.where(df.isnull() != True,0)