【问题标题】:Compare pandas dataframes for common rows in two dataframes比较两个数据帧中常见行的熊猫数据帧
【发布时间】:2019-05-17 18:02:31
【问题描述】:

我有两个这样的数据框 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相同。换句话说,如何找到所有三列组合的内连接。

【问题讨论】:

  • 您使用哪些列来确定它们是否相同?公司、地区和名称?试试df1.merge(df2)。这不是你要求的,但我觉得这就是你想要的最终结果。

标签: python pandas


【解决方案1】:

这取决于你的意思

df-1 中的行与 df-2 相同。

因为列不相同。

如果您的意思是列的交集具有相同值的行,您可以执行inner join user 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 函数的onleft_onright_on 参数。如果你不这样做,pandas 会假设你的意思是两个数据框的列的交集。

【讨论】:

    【解决方案2】:
    result = pd.merge(df1,df2, on=['company','region','region'],how="left")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多