gpt4 book ai didi

python - 为 pandas 列创建类别计数字典

转载 作者:行者123 更新时间:2023-12-01 01:43:53 26 4
gpt4 key购买 nike

我有以下数据框:

person    pets
John [cat, dog]
Amy [bird, fish, cat]
Dave [cow, horse, dog]
Mary [lamb, camel, rino]
Jim [bird, dog]

我想要聚合 pets 列以查找每种宠物类型的出现情况。此示例的预期答案应该是:

{cat: 2, dog: 3, bird:2, fish:1, cow:1, horse:1, lamb: 1, camel: 1, rino:1}

除了逐行循环整个数据框之外,还有更优雅的方式来获取结果吗?谢谢!

最佳答案

通过仅使用内置函数,您可以执行以下操作:

a = [j for i in df['pets'] for j in i]

{i:a.count(i) for i in set(a)}

{'fish': 1,'bird': 2,'dog': 3,'camel': 1,'cat': 2,'lamb': 1,'horse': 1,'cow': 1,'rhino': 1}

关于python - 为 pandas 列创建类别计数字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51602125/

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