How to merge two Pandas DataFrames by column?

Published on Aug. 22, 2023, 12:19 p.m.

To merge two Pandas DataFrames by column, you can use the pd.concat() method with the axis=1 argument. Here is an example:

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]})

# Merge the two DataFrames by column
merged_df = pd.concat([df1, df2], axis=1)

# Print the merged DataFrame
print(merged_df)

This code will output the following merged DataFrame:

A  B  C   D
0  1  4  7  10
1  2  5  8  11
2  3  6  9  12

In this example, the pd.concat() method is used to concatenate the two DataFrames along the axis=1 direction. The resulting DataFrame contains all columns from both DataFrames.

Note that the pd.concat() method works best when the two DataFrames have the same number of rows. If the two DataFrames have different numbers of rows, you may need to adjust your merging strategy accordingly (e.g. using pd.merge() or filling missing values with NaN).

Tags: