【问题标题】:Pandas - merge two DataFrames with Identical Column Names and combine information of two DataFrames in one cellPandas - 合并两个具有相同列名的 DataFrame,并将两个 DataFrame 的信息合并到一个单元格中
【发布时间】:2020-06-13 17:33:59
【问题描述】:

我在第一列中有两个具有相同列名和相同 ID 的数据框。在第一个数据框中,我有 int 信息,在第二个 - str 中。

以下是它们的外观示例:

ID    Cat1    Cat2    Cat3  
1     1        1       0 
2     0        2       1 
3     0        0       5


ID    Cat1    Cat2    Cat3 
1     text    text    text 
2     text    text    text
3     text    text    text

我想将它们合并到一个 DataFrame 中,并将两个 Data Frames 的信息合并到同一个单元格中。所以结果应该是这样的:

ID    Cat1      Cat2         Cat3  
1    1, text   1, text     0, text 
2    0, text   2, text     1, text  
3    0, text   0, text     5, text

我尝试使用 pandas.combine,但无法正常工作。

这个任务能解决吗?

【问题讨论】:

  • 请提供一个可重现的示例,以便人们可以复制您的代码并更轻松地获取数据以帮助您
  • 这是我在平台上的第一个问题,对不起。以后会做的,谢谢

标签: python pandas dataframe merge


【解决方案1】:

filter取出要合并的列;添加 ', ' 并将相关列从 int 转换为 string。最后在列轴上连接回 df.ID

Merged_Dfs = (df.filter(like='Cat').astype(str)
             .add(', ')
             .add(df1.filter(like='Cat').astype(str)))

pd.concat([df.ID,
           Merged_Dfs
           ],axis=1)

    ID  Cat1    Cat2    Cat3
0   1   1, text 1, text 0, text
1   2   0, text 2, text 1, text
2   3   0, text 0, text 5, text

或者,您可以使用 pandas insert 将 df.ID 挂钩到 Merged Dfs 作为第一列

Merged_Dfs.insert(0,'ID',df.ID)

print(Merged_Dfs)

【讨论】:

    【解决方案2】:

    您可以使用combine 连接两个数据框,使用pd.Series.str.cat 连接每个数据框的元素:

    df1.set_index('ID').astype(str).combine(df2.set_index('ID'), lambda x,y: x.str.cat(y, sep=', '))
    

    这需要将索引设置为 ID 并将数字作为字符串。

    输出:

           Cat1     Cat2     Cat3
    ID                           
    1   1, text  1, text  0, text
    2   0, text  2, text  1, text
    3   0, text  0, text  5, text
    

    【讨论】:

      【解决方案3】:

      您可以使用pandas.DataFrame.conbine 合并两个数据框。但是,您需要将正确的函数传递给属性func


      merge = lambda x,y: [x,y]
      df1.combine(df2, func = lambda s1,s2: s1.combine(s2, func = merge))
      

      注意这个函数的变量是pandas.Series。因此,调用pandas.Series.combine 以获得正确的结果。

      【讨论】:

      • 谢谢,它有效。我之前使用了不正确的 lambda 函数
      猜你喜欢
      • 2014-09-28
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      相关资源
      最近更新 更多