Python Pandas ŌĆō 查找两个数据帧之间的常见行
要查找两个DataFrame之间的共同行,请使用merge()方法。让我们先创建具有两列的DataFrame1 –
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90] }
)
创建带有两列的DataFrame2 –
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
"Units": [100, 250, 150, 80, 130, 90]
}
)
要查找共同的行 –
dataFrame1.merge(dataFrame2, how = 'inner' ,indicator=False)
更多Pandas文章,请阅读:Pandas教程
示例
以下是代码 –
import pandas as pd
# Create DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90] }
)
print"DataFrame1 ...\n",dataFrame1
# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
"Units": [100, 250, 150, 80, 130, 90]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# check for equality
print"\nAre both the DataFrames equal? ",dataFrame1.equals(dataFrame2)
# finding common rows between two DataFrames
resData = dataFrame1.merge(dataFrame2, how = 'inner' ,indicator=False)
print"\nCommon rows between two DataFrames...\n",resData
输出
这将产生以下输出 –
DataFrame1 ...
Car Units
0 BMW 100
1 Lexus 150
2 Audi 110
3 Tesla 80
4 Bentley 110
5 Jaguar 90
DataFrame2 ...
Car Units
0 BMW 100
1 Lexus 250
2 Audi 150
3 Mustang 80
4 Bentley 130
5 Jaguar 90
Are both the DataFrames equal? False
Common rows between two DataFrames...
Car Units
0 BMW 100
1 Jaguar 90