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'])
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!