【问题标题】:Merge two data frames with different left_on and right_on length lists合并两个具有不同 left_on 和 right_on 长度列表的数据帧
【发布时间】:2017-05-09 20:37:28
【问题描述】:

我有以下问题。我有两个数据框,想根据第一个数据框中的两列和第二个数据框中的一列合并它们:

import pandas as pd

new1 = pd.DataFrame({0:['a','b','c'], 1:['q1','q2','q3'], 2:['t3','t2','t1']})
new2 = pd.DataFrame({0:['aq1','bq2','cq3'], 1:['la1','la2','la3']})
pd.merge(new1,new2, how='inner', left_on=[0,1], right_on=[0])

此代码不起作用,因为

ValueError: len(right_on) must equal len(left_on)

对于这种情况,pandas 有一些标准方法吗?或者解决问题的唯一方法是在 new1 数据框中创建添加列:

import pandas as pd

new1 = pd.DataFrame({0:['a','b','c'], 1:['q1','q2','q3'], 2:['t3','t2','t1']})
new1[3] = new1[0] + new1[1]
new2 = pd.DataFrame({0:['aq1','bq2','cq3'], 1:['la1','la2','la3']})
print(pd.merge(new1,new2, how='inner', left_on=[3], right_on=[0]))

【问题讨论】:

    标签: python pandas merge


    【解决方案1】:

    您可以在合并中进行求和,而不是创建新列。

    pd.merge(new1,new2, how='inner', left_on=[new1[0]+new1[1]], right_on=[0]) 
    

    你得到

        0_x 1_x 2   0_y 1_y
    0   a   q1  t3  aq1 la1
    1   b   q2  t2  bq2 la2
    2   c   q3  t1  cq3 la3
    

    【讨论】:

    • 这么简单!谢谢!
    猜你喜欢
    • 2021-09-29
    • 2019-02-27
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    相关资源
    最近更新 更多