Ajay Chinni
Ajay Chinni

Reputation: 840

Replace Multiple columns at once with fillna()

I have this dataFrame with two column of Null values

import numpy as np
import pandas as pd
ddd = pd.DataFrame({'a' : [1,2,3],'b' : [np.nan,np.nan,np.nan],'c' : [np.nan,np.nan,np.nan] })

I want to replace column b and c with column a values. I am doing this

ddd[['b','c']]= ddd.fillna(ddd.a)

I get error ValueError: Columns must be same length as key

When i do this the values still remain as NAN

ddd.iloc[:,1:] = ddd.fillna(ddd.a)

It only works if i do individually like this

ddd.b = ddd.fillna(ddd.a)
ddd.c = ddd.fillna(ddd.a)

My Expected output is

   a    b    c
0  1  1.0  1.0
1  2  2.0  2.0
2  3  3.0  3.0

Anyway to make in work in single line I have more than 500 columns in my dataset

Upvotes: 1

Views: 94

Answers (1)

gtomer
gtomer

Reputation: 6564

This will iterate on all the column BUT the first one:

for column in df.columns[1:]:
    ddd[column]= ddd['a']

Upvotes: 1

Related Questions