how to horizontally concat two dataframes in python

You can horizontally concatenate two dataframes in pandas using the concat function with the axis=1 parameter.

Here's an example:

main.py
import pandas as pd

df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                    'B': ['B0', 'B1', 'B2', 'B3'],
                    'C': ['C0', 'C1', 'C2', 'C3'],
                    'D': ['D0', 'D1', 'D2', 'D3']})

df2 = pd.DataFrame({'E': ['E0', 'E1', 'E2', 'E3'],
                    'F': ['F0', 'F1', 'F2', 'F3'],
                    'G': ['G0', 'G1', 'G2', 'G3'],
                    'H': ['H0', 'H1', 'H2', 'H3']})

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

print(concatenated_df)
505 chars
16 lines

This will give you the following output:

main.py
    A   B   C   D   E   F   G   H
0  A0  B0  C0  D0  E0  F0  G0  H0
1  A1  B1  C1  D1  E1  F1  G1  H1
2  A2  B2  C2  D2  E2  F2  G2  H2
3  A3  B3  C3  D3  E3  F3  G3  H3
170 chars
6 lines

Here, df1 and df2 are concatenated horizontally, i.e. the columns of df1 and df2 are combined to form a new dataframe concatenated_df.

related categories

gistlibby LogSnag