使用数组中的分组列创建dict并将剩余的列分配给dict的值 [英] Create dict using a grouping column in an array and assigning the remaining columns to values of the dict
本文介绍了使用数组中的分组列创建dict并将剩余的列分配给dict的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 type(s1)= numpy.ndarray
。我想通过使用 s1
的第一列作为键并其余作为键的值来创建字典。第一列具有重复的值。
这是np.array。
I have a type(s1) = numpy.ndarray
. I want to create a dictionary by using the first column of s1
as key and rest as values to the key. The first column has repeated values.
Here is np.array.
s1 = np.array([[1L, 'R', 4],
[1L, 'D', 3],
[1L, 'I', 10],
[1L, 'K', 0.0],
[2L, 'R', 11],
[2L, 'D', 13],
[2L, 'I', 1],
[2L, 'K', 6],
[3L, 'R', 12],
[3L, 'D', 17],
[3L, 'I', 23],
[3L, 'K', 10]], dtype=object)
我想获得以下信息:
{'1':[['R',4],['D',3],['I',10],['K',0]],
'2':[['R',11],['D',13],['I',1],['K',6]],
'3':[['R',12],['D',17],['I',23],['K',10]]}
这是我尝试并得到的:
In [18]: {x[0]:[x[1],x[2]] for x in s1}
Out[18]: {1L: ['K', 0.0], 2L: ['D', 6], 3L: ['K', 10]}
我看到分组列具有重复值的问题。但是我无法执行添加。我想念的窍门是什么?
I see the problem that the grouping column has repeated values. But I am unable to do the appending. What is the trick I am missing?
推荐答案
您可以简单地使用 defaultdict
:
You can simply built them with defaultdict
:
d=collections.defaultdict(list)
for k,*v in s1 : d[k].append(list(v))
用于
defaultdict(list,
{1: [['R', 4], ['D', 3], ['I', 10], ['K', 0.0]],
2: [['R', 11], ['D', 13], ['I', 1], ['K', 6]],
3: [['R', 12], ['D', 17], ['I', 23], ['K', 10]]})
编辑
您可以在字典中嵌套字典:
You can nest dicts in dicts :
d=collections.defaultdict(dict)
for k1,k2,v in s1 : d[k1][k2]=v
#defaultdict(dict,
# {1: {'D': 3, 'I': 10, 'K': 0.0, 'R': 4},
# 2: {'D': 13, 'I': 1, 'K': 6, 'R': 11},
# 3: {'D': 17, 'I': 23, 'K': 10, 'R': 12}})
In [67]: d[2]['K']
Out[67]: 6
请参见此处进行概括。
这篇关于使用数组中的分组列创建dict并将剩余的列分配给dict的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文