yog*_*123 4 python dictionary numpy frequency
我需要从循环中创建一个字典,该循环遍历2列数字的数组.下面是数组的一小部分:
array([[ 0, 1],
[ 1, 0],
[ 1, 2],
[ 2, 3],
[ 2, 1]])
Run Code Online (Sandbox Code Playgroud)
我想创建一个字典,它将第一列的唯一编号作为键(例如本例中为{0,1,2}),并将第二列中的相应数字作为值.
对于此示例,字典将如下所示:
dict = {0:[1], 1:[0,2], 2:[3,1]}
Run Code Online (Sandbox Code Playgroud)
我的数组很长(370,000 x 2)所以我想通过一个有效的循环来做到这一点.任何建议将不胜感激!
你可以defaultdict用来完成这个.
from collections import defaultdict
a = np.array([[ 0, 1],[ 1, 0],[ 1, 2],[ 2, 3], [ 2, 1]])
d = defaultdict(list)
for x,y in a:
d[x].append(y)
Run Code Online (Sandbox Code Playgroud)