gpt4 book ai didi

python-3.x - 使用 Pandas 从数据框中获取同名行列表

转载 作者:行者123 更新时间:2023-12-04 22:55:51 26 4
gpt4 key购买 nike

正在寻找一种获取部分行列表的方法。

Name    x   y   r
a 9 81 63
a 98 5 89
b 51 50 73
b 41 22 14
c 6 18 1
c 1 93 55
d 57 2 90
d 58 24 20

所以我试图按如下方式获取字典,
di = {a:{0: [9,81,63], 1: [98,5,89]},
b:{0:[51,50,73], 1:[41,22,14]},
c:{0:[6,18,1], 1:[1,93,55]},
d:{0:[57,2,90], 1:[58,24,20]}}

最佳答案

有时最好尽量减少占用空间和开销。
使用 itertools.count , collections.defaultdict

from itertools import count
from collections import defaultdict

counts = {k: count(0) for k in df.Name.unique()}
d = defaultdict(dict)

for k, *v in df.values.tolist():
d[k][next(counts[k])] = v

dict(d)

{'a': {0: [9, 81, 63], 1: [98, 5, 89]},
'b': {0: [51, 50, 73], 1: [41, 22, 14]},
'c': {0: [6, 18, 1], 1: [1, 93, 55]},
'd': {0: [57, 2, 90], 1: [58, 24, 20]}}

关于python-3.x - 使用 Pandas 从数据框中获取同名行列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47429910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com