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)
示例
以下是代码 -
import pandas as pd输出结果# 创建 DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90] }
)
print"DataFrame1 ...\n",dataFrame1
# 创建 DataFrame2
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
"Units": [100, 250, 150, 80, 130, 90]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# 检查是否相等
print"\nAre both the DataFrames equal? ",dataFrame1.equals(dataFrame2)
# 查找两个 DataFrame 之间的公共行
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
以上是 Python Pandas - 查找两个数据帧之间的公共行 的全部内容, 来源链接: utcz.com/z/327445.html