熊猫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}]}

这该怎么做?

莫希特·莫特瓦尼(Mohit Motwani)

您可以使用itertuplesdefulatdict

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 defaultdict
dictionary = 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}]}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章