Skip to content Skip to sidebar Skip to footer

Merge Two Dataframes With Different Indices While Preserving The Main Dataframe's Index Using A One-line Code

I have two dataframes; the first one(df1) is: df1 = pd.DataFrame({'col1': [0,1], 'col2': [0,1]}) df1 = df1.rename(index = {k:v for k,v in zip([0,1],['zero','one'])}) print(df1)

Solution 1:

You can create df2.index by df1.index by set_index, only necessary same length of both DataFrames:

df = df1.join(df2.set_index(df1.index))

Or:

df = pd.concat([df1, df2.set_index(df1.index)], axis=1)
print (df)
      col1  col2  col3  col4  col5  col6  col7  col8  col9
zero     0     0     2     2     2     2     2     2     2
one      1     1     3     3     3     3     3     3     3

If have list same length like both DataFrames pass nested list for distinguish you want pass list, not list of column names (df2.set_index(L) or df2.set_index(['a','b'])):

L = ['a','b']
df = pd.concat([df1.set_index([L]), df2.set_index([L])], axis=1)
print (df)
   col1  col2  col3  col4  col5  col6  col7  col8  col9
a     0     0     2     2     2     2     2     2     2
b     1     1     3     3     3     3     3     3     3

Post a Comment for "Merge Two Dataframes With Different Indices While Preserving The Main Dataframe's Index Using A One-line Code"