w3resource

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

Pandas Joining and merging DataFrame: Exercise-15 with Solution

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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/joining-and-merging/pandas-joining-and-merging-dataframe-exercise-15.php