Python Pandas – 查找两个数据帧之间不同的行

Python Pandas – 查找两个数据帧之间不同的行

要查找两个数据帧之间不同的行,请使用concat()方法。首先,让我们使用别名导入所需的库-

import pandas as pd

使用两列创建DataFrame1-

dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Reg_Price": [1000, 1500, 1100, 800, 1100, 900]
   }
)

使用两列创建DataFrame2-

dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Reg_Price": [1000, 1300, 1000, 800, 1100, 800]
   }
)

查找两个数据帧之间不同的行并拼接结果-

print"\nUncommon rows between two DataFrames...\n", pd.concat([dataFrame1, dataFrame2]).drop_duplicates(keep=False)

示例

以下是代码-

import pandas as pd

# 创建DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Reg_Price": [1000, 1500, 1100, 800, 1100, 900]
   }
)

print"DataFrame1 ...\n",dataFrame1

# 创建DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Reg_Price": [1000, 1300, 1000, 800, 1100, 800]
   }
)

print"\nDataFrame2 ...\n",dataFrame2

# 查找两个数据帧之间不同的行并将结果拼接
print"\nUncommon rows between two DataFrames...\n",pd.concat([dataFrame1,dataFrame2]).drop_duplicates(keep=False)


输出

将产生以下输出-

DataFrame1 ...
      Car   Reg_Price
0     BMW        1000
1   Lexus        1500
2    Audi        1100
3   Tesla         800
4  Bentley        1100
5   Jaguar         900

DataFrame2 ...
      Car   Reg_Price
0     BMW        1000
1   Lexus        1300
2    Audi        1000
3   Tesla         800
4  Bentley        1100
5   Jaguar         800

Uncommon rows between two DataFrames...
      Car   Reg_Price
1   Lexus        1500
2    Audi        1100
5  Jaguar         900
1   Lexus        1300
2    Audi        1000
5  Jaguar         800

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程