猿问

Pandas groupby 并在列表中获取字典

我正在尝试提取分组的行数据以使用值将其与另一个文件的标签颜色一起绘制。


我的数据框如下所示。


df = pd.DataFrame({'x': [1, 4, 5], 'y': [3, 2, 5], 'label': [1.0, 1.0, 2.0]})


    x   y   label

0   1   3   1.0

1   4   2   1.0

2   5   5   2.0

我想获得一组标签列表,例如


{'1.0': [{'index': 0, 'x': 1, 'y': 3}, {'index': 1, 'x': 4, 'y': 2}],

 '2.0': [{'index': 2, 'x': 5, 'y': 5}]}

这该怎么做?


LEATH
浏览 419回答 9
9回答

杨__羊羊

您可以使用itertuples和defulatdict:itertuples 返回命名元组以迭代数据帧:for row in df.itertuples():    print(row)Pandas(Index=0, x=1, y=3, label=1.0)Pandas(Index=1, x=4, y=2, label=1.0)Pandas(Index=2, x=5, y=5, label=2.0)所以利用这一点:from collections import defaultdictdictionary = defaultdict(list)for row in df.itertuples():    dummy['x'] = row.x    dummy['y'] = row.y    dummy['index'] = row.Index    dictionary[row.label].append(dummy)dict(dictionary)> {1.0: [{'x': 1, 'y': 3, 'index': 0}, {'x': 4, 'y': 2, 'index': 1}], 2.0: [{'x': 5, 'y': 5, 'index': 2}]}
随时随地看视频慕课网APP

相关分类

Python
我要回答