Skip to content Skip to sidebar Skip to footer

Pandas Replace Null Values For A Subset Of Columns

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

Solution 1:

Try this:

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

Solution 2:

According to Pandas documentation in 23.3

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

Solution 3:

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.035.0   eng
    1  Bill   200.0  -1.0   adm
    2  Lena    -1.028.0   NaN
    3  Jane   120.045.0   eng

Solution 4:

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)

Solution 5:

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.

Post a Comment for "Pandas Replace Null Values For A Subset Of Columns"