57

I have two Pandas DataFrames, each with different columns. I want to basically glue them together horizontally (they each have the same number of rows so this shouldn't be an issue).

There must be a simple way of doing this but I've gone through the docs and concat isn't what I'm looking for (I don't think).

Any ideas?

Thanks!

anon_swe
  • 8,791
  • 24
  • 85
  • 145
  • 13
    You want `pd.concat([df1,df2], axis=1)` to concatenate horizontally – EdChum Jun 23 '17 at 14:05
  • 11
    You might have problem with indexes if they are different. Then set the index of df2 with the index of df1: `pd.concat([df1, df2.set_index(df1.index)], axis=1)` – ivankeller Jul 14 '20 at 12:36

1 Answers1

89

concat is indeed what you're looking for, you just have to pass it a different value for the "axis" argument than the default. Code sample below:

import pandas as pd

df1 = pd.DataFrame({
    'A': [1,2,3,4,5],
    'B': [1,2,3,4,5]
})

df2 = pd.DataFrame({
    'C': [1,2,3,4,5],
    'D': [1,2,3,4,5]
})

df_concat = pd.concat([df1, df2], axis=1)

print(df_concat)

With the result being:

   A  B  C  D
0  1  1  1  1
1  2  2  2  2
2  3  3  3  3
3  4  4  4  4
4  5  5  5  5
nslamberth
  • 1,147
  • 8
  • 10
  • 3
    Would be more useful if you could post the result along with the snippet so that others don't have to go through the process of copying and running your code themselves to validate it. – Phoenix Apr 07 '21 at 07:57
  • 3
    @Phoenix if you were able to run the example, you can just edit the answer and add the result there – Ufos Apr 08 '21 at 14:50
  • 1
    No worries, just updated. – nslamberth Apr 08 '21 at 14:52