如何并排合并两个数据框?

82 投票
6 回答
152382 浏览
提问于 2025-04-18 07:42

有没有什么简单的方法可以把两个数据框并排合并在一起呢?

这两个数据框都有30行,但列数不同,比如,df1有20列,而df2有40列。

我想知道怎么才能轻松得到一个新的数据框,它有30行和60列?

df3 = pd.someSpecialMergeFunct(df1, df2)

或者,也许在添加数据时,有什么特别的参数可以用。

df3 = pd.append(df1, df2, left_index=False, right_index=false, how='left')

另外,如果可以的话,我希望重复的列名能够自动处理。

谢谢!

6 个回答

0
  • 你可以通过一个管道来实现这个功能。

** 使用管道来转换你的数字数据,比如:

Num_pipeline = Pipeline
([("select_numeric", DataFrameSelector([columns with numerical value])),
("imputer", SimpleImputer(strategy="median")),
])

** 对于分类数据也是一样:

cat_pipeline = Pipeline([
    ("select_cat", DataFrameSelector([columns with categorical data])),
    ("cat_encoder", OneHotEncoder(sparse=False)),
])

** 然后使用特征联合将这些转换结果合并在一起。

preprocess_pipeline = FeatureUnion(transformer_list=[
    ("num_pipeline", num_pipeline),
    ("cat_pipeline", cat_pipeline),
])
2

我发现其他的回答对我来说不太管用,尤其是我从谷歌搜索过来的时候。

我做的事情是直接在原来的数据框中添加新的列。

# list(df2) gives you the column names of df2
# you then use these as the column names for df

df[list(df2)] = df2
6

如果你想把两个数据框合并在一起,而这两个数据框有相同的列名,你可以这样做:

df_concat = pd.merge(df1, df2, on='common_column_name', how='outer')
13

我在尝试做类似的事情时看到了你的问题:

横向合并数据框

所以在我切割数据框之后,首先要确保它们的索引是一样的。在你的情况下,两个数据框的索引都需要从0到29。然后通过索引将这两个数据框合并在一起。

df1.reset_index(drop=True).merge(df2.reset_index(drop=True), left_index=True, right_index=True)
145

你可以使用 concat 函数来实现这个功能(axis=1 是指按列合并):

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

可以查看 pandas 的文档,了解如何合并和连接数据: http://pandas.pydata.org/pandas-docs/stable/merging.html

撰写回答