[英]Compare pandas dataframes for common rows in two dataframes
我有这样的两个数据帧df-1和df-2,
import pandas as pd
raw_data = {'company': ['comp1', 'comp1', 'comp1', 'comp1', 'comp2', 'comp2', 'comp2', 'comp2', 'comp3', 'comp3', 'comp3', 'comp3'],
'region': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'name': ['John', 'Jake', 'Alice', 'Mathew', 'Mark', 'Jacon', 'Ryan', 'Sone', 'Steve', 'Rooke', 'Rani', 'Alice'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df1 = pd.DataFrame(raw_data, columns = ['company', 'region', 'name', 'preTestScore'])
print df1
raw_data = {'company': [ 'comp1', 'comp1', 'comp2', 'comp2', 'comp2', 'comp2', 'comp3', 'comp3', 'comp3'],
'region': [ '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd'],
'name': [ 'Alice', 'Mathew', 'Mark', 'Jacon', 'Ryan', 'Sone', 'Steve', 'Rooke', 'Rani', ],
'status': [ 'great', 'average', 'average', 'average', 'good', 'great', 'average', 'average', 'average']}
df2 = pd.DataFrame(raw_data, columns = ['company', 'region', 'name', 'status'])
print df2
如何在df-1中找到与df-2相同的公司,地区和名称行。 换句话说,如何使用所有三列的组合来查找内部联接。
这取决于你的意思
df-1中的行与df-2相同。
因为列不相同。
如果您指的是列的交集具有相同值的行,则可以执行内部联接用户merge
:
In [13]: pd.merge(df1, df2, how='inner')
Out[13]:
company region name preTestScore status
0 comp1 2nd Alice 31 great
1 comp1 2nd Mathew 2 average
2 comp2 1st Mark 3 average
3 comp2 1st Jacon 4 average
4 comp2 2nd Ryan 24 good
5 comp2 2nd Sone 31 great
6 comp3 1st Steve 2 average
7 comp3 1st Rooke 3 average
8 comp3 2nd Rani 2 average
编辑
如果您希望更好地控制连接列,可以使用merge
功能的on
或left_on
和right_on
参数。 如果不这样做,pandas将假设您指的是两个数据帧的列的交集。
result = pd.merge(df1,df2, on=['company','region','region'],how="left")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.