pandas 熊猫替换列子集的空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37191893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:13:56  来源:igfitidea点击:

pandas replace null values for a subset of columns

pythonpandas

提问by breezymri

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?

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

回答by piRSquared

Try this:

尝试这个:

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

回答by Muhammad Raihan Muhaimin

According to Pandas documentation in 23.3

根据 23.3 中的 Pandas 文档

values = {'salary': -1, 'age': -1}
df = df.fillna(value=values)

回答by xirururu

It is not so beautiful, but it works:

它不是那么漂亮,但它有效:

df.salary.fillna(-1, inplace=True)
df.age.fillna(-1, inplace=True)
df
>>>    name  salary   age title
    0  John   101.0  35.0   eng
    1  Bill   200.0  -1.0   adm
    2  Lena    -1.0  28.0   NaN
    3  Jane   120.0  45.0   eng