Python Pandas: Update a dataframe value from another dataframe

Given two dataframes, we have to update a dataframe value from another one. By Pranit Sharma Last updated : September 29, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

We will be having two different DataFrames, both of the DataFrames consist of some similar values. Suppose we have two DataFrames containing the information of employees.

The attributes in this DataFrame are employee id, employee name, and employee city, we have several similar values in both DataFrame and we will update the rows in the first DataFrame using matching values from the second DataFrame.

Updating a dataframe value from another dataframe

To update a dataframe value from another dataframe, create a separate DataFrame for a similar row and then we will rest the index of the first DataFrame with the column of the second DataFrame with the help of DataFrame.set_index() and DataFrame.update() methods.

Let us understand with the help of an example,

Python program to update a dataframe value from another dataframe

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {
    'emp_id':[101,102,103],
    'emp_name':['Mukesh','Manish','Mohan'],
    'city':['Surat','Ahemdabad','Noida']
}

d2 = {
    'emp_id':[102],
    'emp_name':['Manish'],
    'city':['Gurugram']
}

# Creating DataFrames
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

# Display the DataFrames
print("Original DataFrame 1:\n",df1,"\n\n")
print("Original DataFrame 2:\n",df2,"\n\n")

df1.set_index('emp_id', inplace=True)
df1.update(df2.set_index('emp_id'))
df1.reset_index()

# Display modified DataFrame
print("Modified DataFrame 1:\n",df1)

Output

The output of the above program is:

Example: Update a dataframe value from another dataframe

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.