我有一个大的2d numpy数组和两个表示2d数组中x/y索引的1d数组。我想使用这些1d数组对2d数组执行操作。使用for循环可以实现,但在处理大型数组时速度非常慢。是否有更快的方法?我尝试将1d数组简单地用作索引,但没有成功。请参考以下示例:
import numpy as np
# Two example 2d arrays
cnt_a = np.zeros((4,4))
cnt_b = np.zeros((4,4))
# 1d arrays holding x and y indices
xpos = [0,0,1,2,1,2,1,0,0,0,0,1,1,1,2,2,3]
ypos = [3,2,1,1,3,0,1,0,0,1,2,1,2,3,3,2,0]
# This method works, but is very slow for a large array
for i in range(0,len(xpos)):
cnt_a[xpos[i],ypos[i]] = cnt_a[xpos[i],ypos[i]] + 1
# This method is fast, but gives incorrect answer
cnt_b[xpos,ypos] = cnt_b[xpos,ypos]+1
# Print the results
print 'Good:'
print cnt_a
print ''
print 'Bad:'
print cnt_b
这将输出以下内容:
Good:
[[ 2. 1. 2. 1.]
[ 0. 3. 1. 2.]
[ 1. 1. 1. 1.]
[ 1. 0. 0. 0.]]
Bad:
[[ 1. 1. 1. 1.]
[ 0. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 0. 0. 0.]]
对于cnt_b数组,Numpy明显没有正确求和,但我不确定如何修复它,而不使用计算cnt_a时使用的(非常低效的)for循环。
cnt_a[xpos[i],ypos[i]] += 1
来将第一个for循环的速度提高约一倍。 - Zinkix
和y
的2列
数组,这里有一个相关的Q&A
。 - Divakar