how to horizontaly concatonate pandas datafarmes in python

To horizontally concatenate pandas dataframes in Python, you can use the concat function from the pandas library. Here is an example:

main.py
import pandas as pd

# Create two sample dataframes
df1 = pd.DataFrame({'A': [1, 2, 3],
                    'B': [4, 5, 6]})

df2 = pd.DataFrame({'C': [7, 8, 9],
                    'D': [10, 11, 12]})

# Concatenate the dataframes horizontally
result = pd.concat([df1, df2], axis=1)

print(result)
299 chars
14 lines

This will output the concatenated dataframe:

main.py
   A  B  C   D
0  1  4  7  10
1  2  5  8  11
2  3  6  9  12
60 chars
5 lines

In the concat function, we pass a list of dataframes to be concatenated as the first argument. The axis=1 parameter indicates that the concatenation should be done horizontally.

Note that the dataframes being concatenated should have the same number of rows, otherwise pandas will raise a ValueError.

gistlibby LogSnag