Home > Blockchain >  Concat two dataframes with different indices
Concat two dataframes with different indices

Time:06-28

I am trying to concatenate two dataframes. I've tried using merge(), join(), concat() in pandas, but none gave me my desired output.

df1:

Index value
0 a
1 b
2 c
3 d
4 e

df2:

Index value
1 f
2 g
3 h
4 i
5 j

desired output:

Index col1 col2
0 a f
1 b g
2 c h
3 d i
4 e j

Thanks in advance!

CodePudding user response:

You can just use pd.merge and specify the index left join as follows:

import pandas as pd

df1 = pd.DataFrame(data={'value': list('ABCDE')})
df2 = pd.DataFrame(data={'value': list('FGHIJ')}, index=range(1, 6))

pd.merge(df1.rename(columns={'value': 'col1'}), df2.reset_index(drop=True).rename(columns={'value': 'col2'}), how='left', left_index=True, right_index=True)

-----------------------------------
    col1  col2
0   A     F
1   B     G
2   C     H
3   D     I
4   E     J
-----------------------------------

CodePudding user response:

Does resetting the index of df2 work for your use case?

pd.concat([df1,df2.reset_index(drop=True)], axis=1) \
    .set_axis(['Col1', 'Col2'], axis=1, inplace=False)

Result

  Col1 Col2
0    a    f
1    b    g
2    c    h
3    d    i
4    e    j
  • Related