您当前的方法存在一些问题。首先,np.bincount(x)
会给你计数的x
每正整数值从0开始 和max(x)
结束:
print(np.bincount([1, 1, 3, 3, 3, 4]))
# [0, 2, 0, 3, 1]
# i.e. [count for 0, count for 1, count for 2, count for 3, count for 4]
因此,如果不是在acc.flat
每个位置被索引,长度 np.bincount(raveled)
将大于唯一索引的数量。什么 你实际上想要的是计数只有acc.flat
那些 索引至少一次。
其次,你想要做的是将bin计数分配到相应的 指数到acc.flat
。您拨打np.resize
所要做的就是重复您的二进制数组中的部分 ,以使其与acc.flat
, 相同,然后将其重新塑造成与acc
相同的形状。这不会导致将 计数器分配到acc
中的正确位置!
我会解决这个问题的方法是使用np.unique
代替 np.bincount
,并用它来恢复这两个独特的指数及其对应的 计数。然后这些可用于将正确的计数分配到acc
内的正确唯一位置:
import numpy as np
# some example data
acc = np.zeros((4, 3))
legit_indices = np.array([[0, 1],
[0, 1],
[1, 2],
[1, 0],
[1, 0],
[1, 0]])
# convert the index array into a set of indices into acc.flat
flat_idx = np.ravel_multi_index(legit_indices.T, acc.shape)
# get the set of unique indices and their corresponding counts
uidx, ucounts = np.unique(flat_idx, return_counts=True)
# assign the count value to each unique index in acc.flat
acc.flat[uidx] = ucounts
# confirm that this matches the result of your for loop
acc2 = np.zeros_like(acc)
for ii, jj in legit_indices:
acc2[ii, jj] += 1
assert np.array_equal(acc, acc2)
我理解了关于使用np.unique的第二部分。但我不太确定,我得到的关于np.bincount的部分是np.bincount(raveled)的长度将大于唯一索引的数目。 “你介意详细说明还是陈述一个例子? – goh 2015-02-11 14:30:59
我举了一个例子:'np.bincount([1,3,3,3,4])'给你指数为0,1,2,3和4,而你只希望实际发生的指数至少有一次(即1,3和4)。 – 2015-02-11 14:42:43