python – Numpy矢量化算法,用相同的时间戳来总结数字
发布时间:2020-12-20 11:21:38 所属栏目:Python 来源:网络整理
导读:我有两个数组P和T. P [i]是一个数字,其时间戳是T [i];可能存在重复的时间戳. 我想生成另外两个数组Q和U,其中Q [i]具有时间戳U [i],并且Q [i]是P中具有时间戳U [i]的所有元素的总和; 例如,对于 P = [1,2,3,4,5] T = [0,1,1] 我会生产 Q = [3,12] U = [0,1];
我有两个数组P和T. P [i]是一个数字,其时间戳是T [i];可能存在重复的时间戳.
我想生成另外两个数组Q和U,其中Q [i]具有时间戳U [i],并且Q [i]是P中具有时间戳U [i]的所有元素的总和; 例如,对于 P = [1,2,3,4,5] 我会生产 Q = [3,12] 有没有一种快速的方法在numpy中这样做,希望它可以矢量化它? 解决方法
使用numpy 1.4或更高版本:
import numpy as np P = np.array([1,5]) T = np.array([0,1]) U,inverse = np.unique(T,return_inverse=True) Q = np.bincount(inverse,weights=P) print (Q,U) # (array([ 3.,12.]),array([0,1])) 请注意,这不是最快的解决方案.我用这种方式测试速度: import numpy as np N = 1000 P = np.repeat(np.array([1,5]),N) T = np.repeat(np.array([0,1]),N) def using_bincount(): U,return_inverse=True) Q = np.bincount(inverse,weights=P) return Q,U # (array([ 3.,1])) def using_lc(): U = list(set(T)) Q = [sum([p for (p,t) in zip(P,T) if t == u]) for u in U] return Q,U def using_slice(): U = np.unique(T) Q = np.array([P[T == u].sum() for u in U]) return Q,U 对于小型阵列,wim’s solution更快(N = 1): % python -mtimeit -s'import test' 'test.using_lc()' 100000 loops,best of 3: 18.4 usec per loop % python -mtimeit -s'import test' 'test.using_slice()' 10000 loops,best of 3: 66.8 usec per loop % python -mtimeit -s'import test' 'test.using_bincount()' 10000 loops,best of 3: 52.8 usec per loop 对于大型阵列,joris’s solution更快(N = 1000): % python -mtimeit -s'import test' 'test.using_lc()' 100 loops,best of 3: 9.93 msec per loop % python -mtimeit -s'import test' 'test.using_slice()' 1000 loops,best of 3: 390 usec per loop % python -mtimeit -s'import test' 'test.using_bincount()' 1000 loops,best of 3: 846 usec per loop 我怀疑在这种情况下是否重要,但基准测试可能会根据numpy,python,OS或硬件的版本而改变.在您的机器上重复这些基准测试并不会有什么坏处. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |