gpt4 book ai didi

python - 当特定列相同时追加 id

转载 作者:行者123 更新时间:2023-12-05 05:38:59 26 4
gpt4 key购买 nike

比如我有这张表

| ID       | VALUE        |

| -------- | -------------- |
| 1 | row24 |
| 2 | row24 |
| 3 | row1 |
| 4 | row15 |
| 5 | row16 |
| 6 | row17 |
| 8 | row24 |
| 7 | row17 |
| 9 | row19 |

输出应该是:

| ID       | VALUE        |

| -------- | -------------- |
| [1,2,8] | row24 |

| 3 | row1 |
| 4 | row15 |
| 5 | row16 |
| [6,7] | row17 |
| 9 | row19 |

我认为 pandas 中的 groupby 可能是一个解决方案,我尝试了一些但它没有用...

最佳答案

如果需要组合列表和标量,请使用 GroupBy.agg使用 lambda 函数:

df =  (df.groupby('VALUE', sort=False)['ID']
.agg(lambda x: list(x) if len(x) > 1 else x)
.reset_index(name='IDS'))
print (df)
VALUE IDS
0 row24 [1, 2, 8]
1 row1 3
2 row15 4
3 row16 5
4 row17 [6, 7]
5 row19 9

因为 ig aggregate only list get oalso one element lists:

df =  (df.groupby('VALUE', sort=False)['ID']
.agg(list)
.reset_index(name='IDS'))
print (df)
VALUE IDS
0 row24 [1, 2, 8]
1 row1 [3]
2 row15 [4]
3 row16 [5]
4 row17 [6, 7]
5 row19 [9]

关于python - 当特定列相同时追加 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72796634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com