Home > Backend Development > Python Tutorial > How to Perform Different Types of Joins Using Pandas Merge?

How to Perform Different Types of Joins Using Pandas Merge?

Barbara Streisand
Release: 2024-12-21 19:06:11
Original
603 people have browsed it

How to Perform Different Types of Joins Using Pandas Merge?

Pandas Merging 101

Merging Basics - Basic Types of Joins

Pandas merge functionality offers different types of joins:

INNER JOIN

  • Represented by below diagram:
    [Image of an INNER JOIN graphic]
  • Use left.merge(right, on='key') to perform an INNER JOIN.

    • Example:

      left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})
      right = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value': np.random.randn(4)})
      
      left.merge(right, on='key')
      # Output:
      #   key   value_x   value_y
      # 0   B  0.400157  1.867558
      # 1   D  2.240893 -0.977278
      Copy after login

LEFT OUTER JOIN

  • Represented by below diagram:
    [Image of a LEFT OUTER JOIN graphic]
  • Use left.merge(right, on='key', how='left') to perform a LEFT OUTER JOIN.

    • Example:

      left.merge(right, on='key', how='left')
      # Output:
      #   key   value_x   value_y
      # 0   A  1.764052       NaN
      # 1   B  0.400157  1.867558
      # 2   C  0.978738       NaN
      # 3   D  2.240893 -0.977278
      Copy after login

RIGHT OUTER JOIN

  • Represented by below diagram:
    [Image of a RIGHT OUTER JOIN graphic]
  • Use left.merge(right, on='key', how='right') to perform a RIGHT OUTER JOIN.

    • Example:

      left.merge(right, on='key', how='right')
      # Output:
      #   key   value_x   value_y
      # 0   B  0.400157  1.867558
      # 1   D  2.240893 -0.977278
      # 2   E       NaN  0.950088
      # 3   F       NaN -0.151357
      Copy after login

FULL OUTER JOIN

  • Represented by below diagram:
    [Image of a FULL OUTER JOIN graphic]
  • Use left.merge(right, on='key', how='outer') to perform a FULL OUTER JOIN.

    • Example:

      left.merge(right, on='key', how='outer')
      # Output:
      #   key   value_x   value_y
      # 0   A  1.764052       NaN
      # 1   B  0.400157  1.867558
      # 2   C  0.978738       NaN
      # 3   D  2.240893 -0.977278
      # 4   E       NaN  0.950088
      # 5   F       NaN -0.151357
      Copy after login

The above is the detailed content of How to Perform Different Types of Joins Using Pandas Merge?. 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