【问题标题】:Use .apply to recode nan rows into a different value使用 .apply 将 nan 行重新编码为不同的值
【发布时间】:2026-02-01 10:10:01
【问题描述】:

我正在尝试根据值为 0、1 的原始 groupid 创建一个新的 groupid。我使用了以下代码,但未能将 nan 行编码为 2。

final['groupid2'] = final['groupid'].apply(lambda x: 2 if x == np.nan else x)

我也尝试了以下代码,但它给出了一个属性错误

final['groupid2'] = final['groupid'].apply(lambda x: 2 if x.isnull() else x)

有人能解释一下为什么会这样吗?谢谢

【问题讨论】:

  • 啊,是的。谢谢!

标签: python pandas lambda apply


【解决方案1】:

如果需要,使用pd.isnull 检查标量使用apply

final = pd.DataFrame({'groupid': [1, 0, np.nan],\
                     'B': [400, 500, 600]})
final['groupid2'] = final['groupid'].apply(lambda x: 2 if pd.isnull(x) else x)
print (final)
   groupid    B  groupid2
0      1.0  400       1.0
1      0.0  500       0.0
2      NaN  600       2.0

Details:

lambda 函数中的值x 是标量,因为Series.apply 循环列的每个值。所以函数pd.Series.isnull() 失败了。

为了更好的测试,可以将 lambda 函数重写为:

def f(x):
    print (x)
    print (pd.isnull(x))
    return 2 if pd.isnull(x) else x

1.0
False
0.0
False
nan
True

final['groupid2'] = final['groupid'].apply(f)

但更好的是Series.fillna:

final['groupid2'] = final['groupid'].fillna(2)

【讨论】:

    最近更新 更多