【问题标题】:Merge multiple tables and join the same column with comma split合并多个表并使用逗号拆分连接同一列
【发布时间】:2020-03-27 05:48:43
【问题描述】:

我有大约 15 个具有相同数量的唯一 ID 的 csv 文件。对于每个文件,col1 包含不同的文本。如何将它们连接在一起以创建一个包含这 15 个文件中所有信息的新表?我尝试使用pd.merge,创建一个新的col1 逗号拆分这些文本并删除重复的col1。会有一些名为col1_x、col1_y、col1_y等的列。还有其他更好的方法来实现吗?

我的意见是,

df1:
ID   col1    location    gender
1    Airplane   NY         F
2    Bus        CA         M
3    NaN        FL         M
4    Bus        WA         F

df2:   
ID   col1    location    gender
1    Apple      NY         F
2    Peach      CA         M
3    Melon      FL         M
4    Banana     WA         F

df3: 
ID   col1    location    gender
1    NaN        NY         F
2    Football   CA         M
3    Boxing     FL         M
4    Running    WA         F

预期输出是,

ID   col1                location    gender
1    Airplane,Apple         NY         F
2    Bus,Peach,Football     CA         M
3    Melon,Boxing           FL         M
4    Bus,Banana,Running     WA         F

【问题讨论】:

    标签: python pandas numpy dataframe merge


    【解决方案1】:

    对于您的数据,您可以:

    (pd.concat(df.melt(id_vars='ID').dropna() for df in [df1,df2,df3])
        .groupby(['ID','variable'])['value'].apply(lambda x: ','.join(x.unique()))
        .unstack()
    )
    

    输出:

    variable                col1 gender location
    ID                                          
    1             Airplane,Apple      F       NY
    2         Bus,Peach,Football      M       CA
    3               Melon,Boxing      M       FL
    4         Bus,Banana,Running      F       WA
    

    【讨论】:

      【解决方案2】:

      你可以使用concat + groupby:

      merged = pd.concat([df1, df2, df3], sort=False)
      result = merged.dropna().groupby(['location', 'gender'], as_index=False).agg({'col1' : ','.join}).reset_index(drop=True)
      print(result)
      

      输出

        location gender                col1
      0       CA      M  Bus,Peach,Football
      1       FL      M        Melon,Boxing
      2       NY      F      Airplane,Apple
      3       WA      F  Bus,Banana,Running
      

      【讨论】:

        猜你喜欢
        • 2011-06-19
        • 1970-01-01
        • 1970-01-01
        • 2020-03-05
        • 1970-01-01
        • 1970-01-01
        • 2015-10-13
        • 2021-03-02
        • 1970-01-01
        相关资源
        最近更新 更多