首页 > 解决方案 > 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'}]

标签: pythonpandas

解决方案


你可以使用groupbyto_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'}]]

推荐阅读