python - python如何从字典列表中对两个相似的值进行分组?
问题描述
鉴于下面的字典列表,我需要在元素具有相似且独特的形状和颜色的情况下应用一些操作。如何使用 python 或 pandas 对它们进行分组?
mylist = [
{'id': 11, 'Shape': 'circle', 'Color': 'orange'},
{'id': 73, 'Shape': 'square', 'Color': 'red'},
{'id': 33, 'Shape': 'circle', 'Color': 'orange'},
{'id': 83, 'Shape': 'square', 'Color': 'blue'},
{'id': 34, 'Shape': 'square', 'Color': 'red'}
]
# grouped by Shape and Color
[{'id': 11, 'Shape': 'circle', 'Color': 'orange'}, {'id': 33, 'Shape': 'circle', 'Color': 'orange'}]
[{'id': 73, 'Shape': 'square', 'Color': 'red'}, {'id': 34, 'Shape': 'square', 'Color': 'red'}]
[{'id': 83, 'Shape': 'square', 'Color': 'blue'}]
解决方案
你可以使用groupby
和to_dict('records')
:
result = [g.to_dict('records') for _,g in pd.DataFrame(mylist).groupby(['Shape', 'Color'])]
输出:
[[{'id': 11, 'Shape': 'circle', 'Color': 'orange'},
{'id': 33, 'Shape': 'circle', 'Color': 'orange'}],
[{'id': 83, 'Shape': 'square', 'Color': 'blue'}],
[{'id': 73, 'Shape': 'square', 'Color': 'red'},
{'id': 34, 'Shape': 'square', 'Color': 'red'}]]
推荐阅读
- javascript - 如何隐藏子元素而不是使用纯 Javascript 删除?
- python - 如何修复我的 IF 语句,以便我无法从列表中删除和附加项目
- javascript - 如何以简单的方式创建数据表?
- python - 无法传递自定义响应
- node.js - Mongoose 公式函数返回 null
- angular - 我正在尝试将用户的电子邮件存储到本地存储中,以便我可以从每个组件中获取它,但它不起作用
- amazon-s3 - 使用 aws 胶合并来自 ec2 的表
- r - 如何通过 linux(ubuntu)在多个 .RData 中找到特定对象(数据)?
- r - 如何将此 curl 命令转换为 R curl 调用?
- jsf - Payara 5 上的 Richfaces 3:无法读取请求序言