Home > Backend Development > Python Tutorial > How Can I Fill Missing Values in One Column with Values from Another Column in Pandas?

How Can I Fill Missing Values in One Column with Values from Another Column in Pandas?

Patricia Arquette
Release: 2024-11-10 03:24:02
Original
261 people have browsed it

How Can I Fill Missing Values in One Column with Values from Another Column in Pandas?

Filling Missing Values with Values from Another Column using fillna()

Problem:

I need to fill missing values in one column (e.g., Cat2) with values from another column (e.g., Cat1) using Pandas' fillna() method. It's recommended to avoid inefficient row-wise looping and perform the operation in a single step.

Solution:

Pandas allows you to pass an entire column as an argument to fillna(). It will align the values based on matching indexes and fill the missing values accordingly.

df['Cat2'].fillna(df['Cat1'])
Copy after login

Example:

Consider the following data:

Day Cat1 Cat2
1 cat mouse
2 dog elephant
3 cat giraf
4 NaN ant

After applying the fillna() method, the missing value in Cat2 for Day 4 will be filled with ant:

Day Cat1 Cat2
1 cat mouse
2 dog elephant
3 cat giraf
4 ant ant

The above is the detailed content of How Can I Fill Missing Values in One Column with Values from Another Column in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template