首页 > 解决方案 > 加入合并多个数据框

问题描述

我的数据是这样的:

Name    test1   test2    test3     Count
Emp1    X,Y      A       a1,a2      1
Emp2    X       A,B,C    a3         2
Emp3    Z        C       a4,a5,a6   3

将具有多个值的test1test2单元格拆分为单独的行并将它们合并在一起。

    df2 =  df.test1.str.split(',').apply(pd.Series)
    df2.index =  df.set_index(['Name', 'Count']).index
    df2=df2.stack().reset_index(['Name', 'Count'])
    df3 = df.test2.str.split(',').apply(pd.Series)
    df3.index = df.set_index(['Name', 'Count']).index
    df3=df3.stack().reset_index(['Name', 'Count'])

    df2.merge(df3,on=['Name', 'Count'],how='outer')

出的代码是:

Out[132]: 
   Name  Count 0_x 0_y
0  Emp1      1   X   A
1  Emp1      1   Y   A
2  Emp2      2   X   A
3  Emp2      2   X   B
4  Emp2      2   X   C
5  Emp3      3   Z   C

将具有多个值的 Test3 拆分为单个行的代码

    df4.index = df.set_index(['Name', 'Count']).index
    df4=df4.stack().reset_index(['Name', 'Count'])

谁能帮助我,如何将Test3 与 test2 和 test1多连接,就像我在上面的代码中合并了 Test1 和 Test 一样?

标签: pythonpandas

解决方案


(不确定我理解正确,但是)以下this answer,你可以

expand(expand(df.drop('test3', 1), 'test1', ','), 'test2')

或者

expand_all(df.drop('test3', axis=1), cols=['test1', 'test2'], seps=[',', ','])

两者都输出

    Name    test1   test2   Count
0   Emp1    X   A   1
1   Emp1    Y   A   1
2   Emp2    X   A   2
3   Emp2    X   B   2
4   Emp2    X   C   2
5   Emp3    Z   C   3

细节:

def expand(df, col, sep=','):
    r = df[col].str.split(sep)
    d = {c: df[c].values.repeat(r.str.len(), axis=0) for c in df.columns}
    d[col] = [i for sub in r for i in sub]
    return pd.DataFrame(d)

推荐阅读