在熊猫DataFrame中用其他文本连接行

时间:2019-08-31 19:48:10

标签: python pandas dataframe pandas-groupby

我需要实现以下逻辑的帮助:在对DataFrame进行分组时,我希望某些列与另一文本串联在一起。例如:

输入:

id | col1 | col2
---|------|------
1  |  A   | 12
1  |  B   | 43
---|------|-----

应用类似 df.groupby(id).concatrows("text_"+col1+":"+col2.astype(str)), 所需的输出应为:

id | new col
---|-----------------------
1  | text_A:12;text_B:43   
---|-----------------------

因此它应该是";".join(),但具有更大的灵活性。

2 个答案:

答案 0 :(得分:2)

以下是一个选项:

df.groupby('id').apply(lambda g: ';'.join('text_' + g.col1 + ':' + g.col2.astype(str)))

输出:

id
1    text_A:12;text_B:43

答案 1 :(得分:0)

另一种选择是在连接组之前先连接col1和col2,

("text_" + df['col1'] + ":" + df['col2'].astype(str)).groupby(df['id']).apply(';'.join)