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

时间:2014-05-27 14:01:52

标签: python pandas

有没有办法方便地并排合并两个数据框?

两个数据帧都有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')

ps:如果可能的话,我希望可以自动解析复制的列名。

谢谢!

5 个答案:

答案 0 :(得分:28)

您可以使用concat函数(axis=1将连接为列):

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

请参阅有关合并/连接的pandas文档:http://pandas.pydata.org/pandas-docs/stable/merging.html

答案 1 :(得分:2)

当我尝试实现以下内容时,我遇到了您的问题:

Merge dataframe sideways

因此,一旦我切割了数据帧,我首先确保它们的索引是相同的。在你的情况下,两个数据帧都需要从0到29编制索引。然后用索引合并两个数据帧。

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

答案 2 :(得分:2)

如果您想将 2 个数据框与公共列名组合在一起,您可以执行以下操作:

from decouple import config, Csv

ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())

答案 3 :(得分:1)

我发现从 Google 进来时,其他答案对我来说并不合适。

我所做的是在原始 df 中设置新列。

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

df[ list(df2.columns) ] = df2

答案 4 :(得分: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),
])