Python Pandas - 查找两个 DataFrames 之间不常见的行
pythonserver side programmingprogramming更新于 2025/10/28 8:44:17
要查找两个 DataFrames 之间不常见的行,请使用 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]
}
)
查找两个 DataFrame 之间的不常见行并连接结果−
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
# 查找两个 DataFrame 之间不常见的行并连接结果
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 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

