pandas 替换列的子集的空值 [英] pandas replace null values for a subset of columns

查看:55
本文介绍了 pandas 替换列的子集的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多列的数据框,例如:

I have a data frame with many columns, say:

df:
name   salary  age   title
John      100   35    eng
Bill      200  NaN    adm
Lena      NaN   28    NaN
Jane      120   45    eng

我要替换薪水和年龄中的空值,但在其他列中不使用.我知道我可以做这样的事情:

I want to replace the null values in salary and age, but no in the other columns. I know I can do something like this:

u = df[['salary', 'age']]
df[['salary', 'age']] = u.fillna(-1)

但这似乎很简洁,因为它涉及复制.有没有更有效的方法可以做到这一点?

But this seems terse as it involves copying. Is there a more efficient way to do this?

推荐答案

尝试一下:

df.loc[:, ['salary', 'age']].fillna(-1, inplace=True)

这篇关于 pandas 替换列的子集的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆