Python - How to remove a pandas dataframe from another dataframe?

Given two dataframes, we need to remove a pandas dataframe from another dataframe. By Pranit Sharma Last updated : September 26, 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.

Remove a pandas dataframe from another dataframe

To remove a pandas dataframe from another dataframe, we are going to concatenate two dataframes and we will drop all the duplicates from this new dataframe, in this way we can achieve this task.

Pandas concat() is used for combining or joining two DataFrames, but it is a method that appends or inserts one (or more) DataFrame below the other.

Let us understand with the help of an example,

Python program to remove a pandas dataframe from another dataframe

# Importing pandas package

import pandas as pd

# Creating a dictionary
d1 = {
    'Asia':['India','China','Sri-Lanka','Japan'],
    'Europe':['Russia','Germany','France','Sweden']
}

d2 = {
    'Asia':['Bangladesh','China','Myanmar','Maldives'],
    'Europe':['Finland','Norway','Russia','Itlay']
}

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

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

# Concatenating two dataframes
result = pd.concat([df1, df2, df2]).drop_duplicates(keep=False)

# Display result
print("Result:\n",result)

Output

The output of the above program is:

Example: Remove a pandas dataframe from another dataframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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