Python 将数据框中的行与另一个文本合并
我需要帮助实现以下逻辑:在对数据帧进行分组时,我希望某些列与另一个文本连接起来。例如: 输入:Python 将数据框中的行与另一个文本合并,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我需要帮助实现以下逻辑:在对数据帧进行分组时,我希望某些列与另一个文本连接起来。例如: 输入: id | col1 | col2 ---|------|------ 1 | A | 12 1 | B | 43 ---|------|----- 在应用了类似 df.groupby(id).concatrows(“text_“+col1+”:“+col2.astype(str)), 所需输出应为: id | new col ---|----------------------- 1
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()
,但具有更大的灵活性。一个选项可以是:
df.groupby('id').apply(lambda g:';'.join('text_'+g.col1+':'+g.col2.astype(str)))
输出:
id
1 text_A:12;text_B:43
另一个选项是在连接组之前先连接col1和col2
("text_" + df['col1'] + ":" + df['col2'].astype(str)).groupby(df['id']).apply(';'.join)