How can I merge together several pandas dataframes on a certain column without 'pandas.merge'?

前端 未结 2 392
星月不相逢
星月不相逢 2021-01-27 13:15

I often find myself with several pandas dataframes in the following form:

import pandas as pd
df1 = pd.read_table(\'filename1.dat\')
df2 = pd.read_table(\'filen         


        
相关标签:
2条回答
  • 2021-01-27 13:57

    Assuming that the three dataframes have the same index, you could just add columns to get the desired dataframes and not worry about merging, like so,

    import pandas as pd
    
    #create the dataframe
    colA = ['name1', 'name2', 'name3', 'name4']
    first = [ 342, 822, 121, 3434]
    second = [ 8,1,1,2]
    third = [ 910,301,132, 299]
    df1 = pd.DataFrame({'colA': colA, 'first': first})
    df2 = pd.DataFrame({'colA': colA, 'second': second})
    df3 = pd.DataFrame({'colA': colA, 'third': third})
    
    
    df_merged = df1.copy()
    df_merged['second']= df2.second
    df_merged['third']= df3.third
    print (df_merged.head())
    
        colA  first  second  third
    0  name1    342       8    910
    1  name2    822       1    301
    2  name3    121       1    132
    3  name4   3434       2    299
    
    0 讨论(0)
  • 2021-01-27 14:04

    You can set columnA as the index and concat (reset index at the end):

    dfs = [df1, df2, df3]
    
    pd.concat([df.set_index('columnA') for df in dfs], axis=1).reset_index()
    Out: 
      columnA  first_values  second_values  third_values
    0   name1           342              8           910
    1   name2           822              1           301
    2   name3           121              1           132
    3   name4          3434              2           299
    
    0 讨论(0)
提交回复
热议问题