【问题标题】:Pandas- how to do merge on multiple columns including indexPandas-如何合并多个列,包括索引
【发布时间】:2016-10-10 16:29:16
【问题描述】:

我想在 Pandas 中对多个列执行合并,其中一列是索引列。

以下是示例数据框:

    df1 = pd.DataFrame(np.random.rand(4,4), columns=list('ABCD'))
    df2 = pd.DataFrame(np.random.rand(4,4), columns=list('EFGH'), index= [5,2,4,1])
    df1['E'] = ['hello','hello','hello','world']
    df2['E'] = ['world','world','hello','hello']

我想对索引和列 E 执行内部合并,这样它只会返回一行:(index,E) = (1,'hello')。

【问题讨论】:

    标签: python pandas merge


    【解决方案1】:

    这个呢?

    In [82]: pd.merge(df1.reset_index(), df2.reset_index(), on=['index','E']).set_index('index')
    Out[82]:
                  A        B         C         D      E        F         G         H
    index
    1      0.516878  0.56163  0.082839  0.420587  hello  0.62601  0.787371  0.121979
    

    【讨论】:

      猜你喜欢
      • 2023-01-18
      • 2015-12-01
      • 1970-01-01
      • 2019-12-09
      • 2021-04-02
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      相关资源
      最近更新 更多