Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I would like to fill missing values in one column with values from another column, using fillna method.

(I read that looping through each row would be very bad practice and that it would be better to do everything in one go but I could not find out how to do it with fillna.)

Data before:

Day  Cat1  Cat2

1    cat   mouse

2    dog   elephant

3    cat   giraf

4    NaN   ant

Data after:

Day  Cat1  Cat2

1    cat   mouse

2    dog   elephant

3    cat   giraf

4    ant   ant

1 Answer

0 votes
by (41.4k points)

Pass that column to fillna, it will fill the values corresponding to the matching indexes:

In [17]: df['Cat1'].fillna(df['Cat2'])

Out[17]:

0    cat

1    dog

2    cat

3    ant

Name: Cat1, dtype: object

Browse Categories

...