尝试按聚合中的多行分组时缺少列

2024-09-20 04:12:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含相关信息的数据帧,我想按一列(比如id)分组,其他具有相同id的列用“|”连接。但是,当我运行代码时,我的大多数列都会丢失(只有前3列出现),我不知道出了什么问题。你知道吗

我的代码是:

df = df.groupby('id').agg(lambda col: '|'.join(set(col))).reset_index()

例如,我的数据

  id   words    ... (other columns here)
0  a     asd
1  a     rtr
2  b       s
3  c  rrtttt
4  c    dsfd

我想要

id               ... (other columns here)
a        asd|rtr
b              s
c    rrtttt|dsfd

但我的其他专栏也是这样分组的。现在,我的其他列只是没有出现在我的输出数据集中。不确定出了什么问题。谢谢!你知道吗


Tags: columns数据代码信息iddfherecol
1条回答
网友
1楼 · 发布于 2024-09-20 04:12:52

转换为字符串之前,您可以使用agg(set)applymap避免lambda:

df.astype(str).groupby('id').agg(set).applymap('|'.join)

最小可验证示例

df = pd.DataFrame({
   'id': ['a', 'a', 'b', 'c', 'c'],
   'numbers': [1, 2, 2, 3, 3],
   'words': ['asd', 'rtr', 's', 'rrtttt', 'dsfd']})
df

  id  numbers   words
0  a        1     asd
1  a        2     rtr
2  b        2       s
3  c        3  rrtttt
4  c        3    dsfd

df.astype(str).groupby('id').agg(set).applymap('|'.join)

   numbers        words
id                     
a      1|2      asd|rtr
b        2            s
c        3  rrtttt|dsfd

相关问题 更多 >