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 Python skills with w3resource's quiz



Python: Tips of the Day

For-else construct useful when searched for something and find it:

# For example assume that I need to search through a list and process each item until a flag item is found and 
# then stop processing. If the flag item is missing then an exception needs to be raised.

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")