我想从“表”中选择与“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/