如何合并数据框中的行与不同的列?

Bel*_*a92 5 python dataframe pandas pandas-groupby

我想将数据帧的行与一个公共列值合并,然后合并用逗号分隔的其余列值作为字符串值,并转换为数组/列表以获取int值。

A   B     C    D
1  one   100  value
4  four  400  value
5  five  500  value
2  two   200  value
Run Code Online (Sandbox Code Playgroud)

预期结果如下:

   A                B                 C            D
[1,4,5,2]  one,four,five,two  [100,400,500,200]  value
Run Code Online (Sandbox Code Playgroud)

我可以对D列使用groupby,但是如何一次在df中将apply作为列的apply(np.array)和apply(','。join)应用于A,C列呢?

iam*_*aus 2

df = df.groupby('D').apply(lambda x: pd.Series([list(x.A),','.join(x.B),list(x.C)])).reset_index().rename({0:'A',1:'B',2:'C'}, axis=1)

df = df[['A','B','C','D']]
Run Code Online (Sandbox Code Playgroud)

输出

              A                  B                     C      D
0  [1, 4, 5, 2]  one,four,five,two  [100, 400, 500, 200]  value
Run Code Online (Sandbox Code Playgroud)