In Pandas, you can usemerge()
Functions to implement connection operations similar to those in SQL. The following are table example explanations of four basic connection types: left join, right join, inner join, and outer join.
Suppose we have two DataFrames:df1
anddf2
。
import pandas as pd # Create a sample DataFramedf1 = ({ 'key': ['A', 'B', 'C', 'D'], 'value1': [1, 2, 3, 4] }) df2 = ({ 'key': ['B', 'D', 'E', 'F'], 'value2': [5, 6, 7, 8] })
1. Left Join
Left connection returns to the left DataFrame (df1
) all rows even with the right DataFrame(df2
There are no matching rows in ) . If there is a matching row in the right DataFrame, the matching value is returned, otherwise NaN is returned.
result_left = (df1, df2, on='key', how='left') print(result_left)
Output result:
key value1 value2
0 A 1 NaN
1 B 2 5.0
2 C 3 NaN
3 D 4 6.0
2. Right Join
Right connection returns to the right DataFrame (df2
) all rows even with the left DataFrame(df1
There are no matching rows in ) . If there is a matching row in the left DataFrame, the matching value is returned, otherwise NaN is returned.
result_right = (df1, df2, on='key', how='right') print(result_right)
Output result:
key value1 value2
0 B 2 5.0
1 D 4 6.0
2 E NaN 7.0
3 F NaN 8.0
3. Inner Join
The intra-connect returns the matching rows that are shared in two DataFrames. The result will only be returned if there are matching rows in both DataFrames.
result_inner = (df1, df2, on='key', how='inner') print(result_inner)
Output result:
key value1 value2
0 B 2 5.0
1 D 4 6.0
4. Outer Join
The outer join returns all rows in two DataFrames. If there is no matching row on one side, the value of that side will be set to NaN.
result_outer = (df1, df2, on='key', how='outer') print(result_outer)
Output result:
key value1 value2
0 A 1 NaN
1 B 2 5.0
2 C 3 NaN
3 D 4 6.0
4 E NaN 7.0
5 F NaN 8.0
This is the end of this article about the specific implementation of pandas table connection. For more related pandas table connection content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!