20 Examples to Master Merging DataFrames in Python Pandas | by Soner Yıldırım | May, 2023


Example 8— merge on multiple columns

We will create two new DataFrames for this example.

products = pd.DataFrame(

{
"pg": ["A", "A", "A", "B", "B", "B"],
"id": [101, 102, 103, 101, 102, 104],
"price": np.random.randint(50, 80, size=6),
"cost": np.random.randint(40, 50, size=6),
"discount": [0.1, 0.1, 0, 0, 0.2, 0]
}

)

sales = pd.DataFrame(

{
"pg": ["A", "A", "A", "B", "B", "B"],
"id": [101, 102, 105, 101, 102, 106],
"sales_qty": np.random.randint(1, 10, size=6),
"discount": [0, 0.1, 0.1, 0.2, 0, 0]
}

)

(image by author)

To merge DataFrames on multiple columns, we write the column names as a Python list.

merged_df = products.merge(sales, on=["pg", "id"])
(image by author)



Source link

Leave a Comment