Home > Backend Development > Python Tutorial > How Do I Perform Different Types of Pandas DataFrames Joins?

How Do I Perform Different Types of Pandas DataFrames Joins?

Mary-Kate Olsen
Release: 2024-12-26 10:56:14
Original
747 people have browsed it

How Do I Perform Different Types of Pandas DataFrames Joins?

Pandas Merging 101: The Basics

JOINing DataFrames

Merging DataFrames in Pandas involves combining two or more DataFrames based on common key columns. There are several types of joins, including:

  • INNER JOIN: Returns only rows where keys match in both DataFrames.

    • df1.merge(df2, on='key', how='inner')
  • LEFT JOIN: Includes all rows from the left DataFrame, and matching rows from the right DataFrame. Missing values from the right are filled with NaNs.

    • df1.merge(df2, on='key', how='left')
  • RIGHT JOIN: Includes all rows from the right DataFrame, and matching rows from the left DataFrame. Missing values from the left are filled with NaNs.

    • df1.merge(df2, on='key', how='right')
  • FULL OUTER JOIN: Includes all rows from both DataFrames, filling missing values with NaNs.

    • df1.merge(df2, on='key', how='outer')

Different Key Column Names

If key columns have different names, use left_on and right_on arguments:

  • df1.merge(df2, left_on='key1', right_on='key2', how='inner')

Avoiding Duplicate Key Columns in Output

When merging on different key columns, set the index as a preliminary step:

  • df1.set_index('key1').merge(df2, left_index=True, right_on='key2')

Merging on Multiple Columns

Join on multiple columns by passing a list to on (or left_on and right_on):

  • df1.merge(df2, on=['key1', 'key2'], how='inner')

Generalizing to Multiple DataFrames

To merge multiple DataFrames, use pd.merge_asof for approximate joins or pd.merge_ordered for ordered joins.

The above is the detailed content of How Do I Perform Different Types of Pandas DataFrames Joins?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template