Search code examples
pythonpandasdataframefillna

fillna(0) only for specific columns without naming each of them


I'm trying to use pandas fillna() on specific columns. The problem is, I don't want to name all these columns. I have one DF, let's call it df_abc, and another one df_123.

df_abc has the columns

A | B | C

x | y | z

k | w | k

df_123 has the columns

1 | 2 | 3

e | e | z

now I'm merging these the way I want and the result is:

A | B | C | 1 | 2 | 3

x | y | z |nan|nan|nan

k | w | k | e | e | z

Now I want use fillna() to fill the columns 1, 2, 3 with 0. I tried:

columns = list(df_123.columns.values)
self.df_result[columns] = self.df_result[columns].fillna(0)

It gives me

ValueError: Columns must be same length as key

I think there has to be a way to fill these columns in a clean way.


Solution

  • You can use slicing to do that incase you dont want to fill the nan for first three columns i.e

    df.iloc[:,3:] = df.iloc[:,3:].fillna(0)