深度阅读

How to merge two Pandas DataFrames by column?

作者
作者
2023年08月22日
更新时间
10.09 分钟
阅读时间
0
阅读量

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).

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。