我正在尝试提取分组行数据以使用值将标签颜色绘制为另一个文件.
我的数据框如下所示.
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}]}
这该怎么做?
@H_502_20@解决方法:您可以使用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 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] 举报,一经查实,本站将立刻删除。