20

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?

5 Answers 5

29

According to Pandas documentation in 23.3

values = {'salary': -1, 'age': -1}
df.fillna(value=values, inplace=True)
Sign up to request clarification or add additional context in comments.

Comments

18

Try this:

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

5 Comments

Thanks to @piRSquared's answer, here's the final answer I was looking for: df.loc[:, ['salary', 'age']].fillna(-1, inplace=True)
inplace=True does not work on sub-slices: stackoverflow.com/questions/46377263/…
This does not work anymore. However df.loc[:, ['salary', 'age']] = df.loc[:, ['salary', 'age']].fillna(-1) does.
@FrancisSmart see Cheng's comment above yours. It refers to the same thing.
@piRSquared Just trying to make the answer a little more accessible.
8

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

1 Comment

This was the only approach that worked for me. Thanks!
5

I was hoping fillna() had subset parameter like drop(), maybe should post request to pandas however this is the cleanest version in my opinion.

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

Comments

2

You can do:

df = df.assign(
    salary=df.salary.fillna(-1),
    age=df.age.fillna(-1),
)

if you want to chain it with other operations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.