gpt4 book ai didi

python - Pandas numpy.where() 使用 - 没有得到想要的结果

转载 作者:行者123 更新时间:2023-11-28 22:37:15 25 4
gpt4 key购买 nike

我正在尝试根据 NaN 值将两列合并为第三列

df['code2'] = np.where(df['code']==np.nan, df['code'], df['code1'])

我只得到 code2 中 code1 列的值。结果如图所示输出图像

enter image description here

请告诉我我写的代码有什么问题。谢谢

最佳答案

我想你需要isnull用于比较 NaN:

df['code2'] = np.where(df['code'].isnull(), df['code'], df['code1'])

Docs :

Warning

One has to be mindful that in python (and numpy), the nan's don’t compare equal, but None's do. Note that Pandas/numpy uses the fact that np.nan != np.nan, and treats None like np.nan.

In [11]: None == None
Out[11]: True

In [12]: np.nan == np.nan
Out[12]: False

So as compared to above, a scalar equality comparison versus a None/np.nan doesn’t provide useful information.

In [13]: df2['one'] == np.nan
Out[13]:
a False
b False
c False
d False
e False
f False
g False
h False
Name: one, dtype: bool

关于python - Pandas numpy.where() 使用 - 没有得到想要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36685963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com