python - 匹配两个数据框以选择具有完全匹配的行项目的项目

标签 python pandas

我想从“表”中选择与“criteria”数据框中的数据完全匹配的数据。

import pandas as pd
table = pd.DataFrame(data = {'RowID':[1,2,3,4,5,6,7,8,9,10],
                             'CusID':[1,1,1,1,2,2,3,3,4,4],
                             'Area':['A','A','A','A','A','A','A','A','B','B'],
                             'Income':[800,900,1000,900,1000,800,400,400,900,1000],})
 
 
criteria = pd.DataFrame(data = {'CusID':[1,2,4],
                             'Area':['A','A','B'],
                             'Income':[800,1000,700],})

根据标准,我只期望 RowID 1 和 5 的行。我尝试使用下面的代码。

tableMatched= table[(table['CusID'].isin(criteria['CusID'])) & (table['Area'].isin(criteria['Area']))& (table['Income'].isin(criteria['Income']))]

但是根据我的代码,我也得到了 RowID 3,6 和 10。 这就是我的预期结果是; RowID CusID 地区收入 1 1 A 800 5 2 A 1000

如果有人可以帮助我正确编码,请感激。

最佳答案

使用merge仅当没有参数 on 时,它才会连接到两个 DataFrame 中的所有相同列:

df = pd.merge(table, criteria)
print (df)
  Area  CusID  Income  RowID
0    A      1     800      1
1    A      2    1000      5

关于python - 匹配两个数据框以选择具有完全匹配的行项目的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47374052/

相关文章:

python - Matplotlib 交互式条形图

python - Pandas DataFrame 到以元组为键和值的字典

python - asyncio.create_task 装饰器不会同时执行

python - 在python numpy.linalg中使用逆矩阵函数 "inv"

python - 循环一个函数直到它达到阈值然后完成脚本

python - 使用 Windows 复制对话框进行复制

python - PyMySQL:插入数据准备语句

python-3.x - 来自 DataFrame 的一张图上的多个图

Python "if does not exist, then..."逻辑?

python - 按字典值过滤数据框,但有时包括值,有时排除它们