Adnan Toky
Adnan Toky

Reputation: 1943

How to apply different method parameters for different columns in pandas fillna() method

I have a data frame like this.

Name    Roll    GPA
A       10      5.0
B       NaN     4.5
C       12      NaN

I am using:

df.fillna(method='ffill', inplace=True)

But it fills all the columns using ffill method.

But I want to fill the NaN value using both ffill & bfill method. For example, I want to apply method='ffill' to the Roll column and method='bfill' to the GPA column. How can I do this?

Upvotes: 4

Views: 674

Answers (1)

cs95
cs95

Reputation: 402603

You can do both.

df2 = df.assign(Roll=df.Roll.ffill(), GPA=df.GPA.bfill())

Upvotes: 4

Related Questions