w3resource

Pandas: Update null elements with value in the same location in other


15. Combine DataFrames by Filling Nulls from Another

Write a Pandas program to Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame.

Test Data:

Original DataFrames:
     A  B
0  NaN  3
1  0.0  4
2  NaN  5
   A    B
0  1  3.0
1  1  NaN
2  3  3.0

Sample Solution:

Python Code :

import pandas as pd
df1 = pd.DataFrame({'A': [None, 0, None], 'B': [3, 4, 5]})
df2 = pd.DataFrame({'A': [1, 1, 3], 'B': [3, None, 3]})
df1.combine_first(df2)
print("Original DataFrames:")
print(df1)
print("--------------------")
print(df2)
print("\nMerge two dataframes with different columns:")
result = df1.combine_first(df2)
print(result)

Sample Output:

Original DataFrames:
     A  B
0  NaN  3
1  0.0  4
2  NaN  5
--------------------
   A    B
0  1  3.0
1  1  NaN
2  3  3.0

Merge two dataframes with different columns:
     A  B
0  1.0  3
1  0.0  4
2  3.0  5

For more Practice: Solve these Related Problems:

  • Write a Pandas program to combine two DataFrames by filling null values in one with non-null values from the other using combine_first().
  • Write a Pandas program to merge two DataFrames and then use fillna() to replace missing entries from one DataFrame with values from the other.
  • Write a Pandas program to update a DataFrame by filling its null values with corresponding non-null values from a second DataFrame and then output the result.
  • Write a Pandas program to combine two DataFrames with overlapping data by filling missing data from one DataFrame with available data from the other.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to merge two given dataframes with different columns.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.