Pandas merge functionality offers different types of joins:
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
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
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
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
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!