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

How to sort a Python dict by value

Example:

x1 = {'a': 5, 'b': 7, 'c': 9, 'd': 1}

sorted(x1.items(), key=lambda x: x[1])
[('d', 1), ('c', 9), ('b', 7), ('a', 5)]

# Or:

import operator
print(sorted(x1.items(), key=operator.itemgetter(1)))

Output:

[('d', 1), ('a', 5), ('b', 7), ('c', 9)]