【问题标题】:How to merge two dataframes side-by-side?如何并排合并两个数据框?
【发布时间】:2014-07-16 11:50:40
【问题描述】:

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

两个数据框都有 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:如果可能的话,我希望复制的列名可以自动解析。

谢谢!

【问题讨论】:

标签: python pandas


【解决方案1】:

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

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

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

【讨论】:

  • 看看这个链接 - chris.friedline.net/2015-12-15-rutgers/lessons/python2/…。并且您可能需要在连接它们之前 reset_index() ,以防您无法并排连接它们。这个答案是正确的。但是,我只是想为即使在回答后仍可能被卡住的人添加一个注释。
  • @PallavBakshi 是的,我需要将 .reset_index(drop=True) 添加到我已完成选择以重新对齐行的数据框中。
  • 将列表更改为生成器可能会更高效,这样可以避免创建大型中间对象:pd.concat((df1, df2), axis=1)
【解决方案2】:

我在尝试实现以下目标时遇到了您的问题:

因此,一旦我对数据帧进行切片,我首先要确保它们的索引是相同的。在您的情况下,两个数据帧都需要从 0 到 29 进行索引。然后按索引合并两个数据帧。

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

【讨论】:

  • 有史以来最好的解决方案
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

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

    我所做的是在原始 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
    

    【讨论】:

      【解决方案5】:
      • 有办法,您可以通过管道来实现。

      ** 使用管道将数字数据转换为 ex-

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

      ** 然后使用 Feature union 将这些转换加在一起

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

      【讨论】:

        猜你喜欢
        • 2017-08-15
        • 1970-01-01
        • 2012-10-08
        • 1970-01-01
        • 2020-03-17
        • 1970-01-01
        相关资源
        最近更新 更多