如果数据框中的列名称相同,则连接列

Tor*_*s91 2 python dataframe pandas

我试过重新搜索堆栈,但无法解决我的问题

如果列名相同,我想连接列:

例子:

input = { 'A' : [0,1,0,1,0], 'B' : [0,1,1,1,1], 'C':[1,1,1,1,0],
          'D' : [1,1,0,0,0], 'E' : [1,0,1,0,1]}

df = pd.DataFrame(input)
df.columns = ['A','B','C','C','B']

   A  B  C  C  B
0  0  0  1  1  1
1  1  1  1  1  0
2  0  1  1  0  1
3  1  1  1  0  0
4  0  1  0  0  1
Run Code Online (Sandbox Code Playgroud)

期望的输出:

   A    B    C
0  0  0;1  1;1
1  1  1;0  1;1
2  0  1;1  1;0
3  1  1;0  1;0
4  0  1;1  0;0
Run Code Online (Sandbox Code Playgroud)

任何指针都受到高度赞赏。

jez*_*ael 5

您可以按列名分组和重复获得数据帧,因此使用applyjoin每行的捧场:

DF = DF.astype(str).groupby(DF.columns, axis=1).agg(lambda x: x.apply(';'.join, 1))
Run Code Online (Sandbox Code Playgroud)

或者:

DF = DF.astype(str).groupby(DF.columns, axis=1).agg(lambda x: [';'.join(y) for y in x.to_numpy()])
Run Code Online (Sandbox Code Playgroud)
print (DF)
   A    B    C
0  0  0;1  1;1
1  1  1;0  1;1
2  0  1;1  1;0
3  1  1;0  1;0
4  0  1;1  0;0
Run Code Online (Sandbox Code Playgroud)