【发布时间】:2021-03-27 20:46:53
【问题描述】:
我有一个数组indexs。它很长(>10k),每个 int 值都相当小(
indexs = np.array([1, 4, 3, 0, 0, 1, 2, 0]) # int index array
indexs_max = 4 # already known
现在我想计算每个索引值的出现次数(例如 0 表示 3 次,1 表示 2 次...),并将 counts 设为 np.array([3, 2, 1, 1, 1])。我测试了以下4种方法:
UPDATE:_test4 是@Ch3steR 的溶胶:
indexs = np.random.randint(0, 10, (20000,))
indexs_max = 9
def _test1():
counts = np.zeros((indexs_max + 1, ), dtype=np.int32)
for ind in indexs:
counts[ind] += 1
return counts
def _test2():
counts = np.zeros((indexs_max + 1,), dtype=np.int32)
uniq_vals, uniq_cnts = np.unique(indexs, return_counts=True)
counts[uniq_vals] = uniq_cnts
# this is because some value in range may be missing
return counts
def _test3():
therange = np.arange(0, indexs_max + 1)
counts = np.sum(indexs[None] == therange[:, None], axis=1)
return counts
def _test4():
return np.bincount(indexs, minlength=indexs_max+1)
运行500次,它们的使用时间分别为32.499472856521606s、0.31386804580688477s、0.14069509506225586s、0.017721891403198242s。 虽然_test3 是最快的,但它使用了额外的大内存。
所以我要求任何更好的方法。谢谢你:) (@Ch3steR)
UPDATE:np.bincount 目前看来是最佳选择。
【问题讨论】:
标签: python numpy matrix parallel-processing torch