【发布时间】:2017-12-01 18:59:36
【问题描述】:
我有一个大型 2d numpy 数组和两个 1d 数组,它们表示 2d 数组中的 x/y 索引。我想使用这些一维数组对二维数组执行操作。 我可以使用 for 循环来做到这一点,但是在处理大型数组时它非常慢。有没有更快的方法?我尝试将一维数组简单地用作索引,但这不起作用。看这个例子:
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 的(v.低效)for 循环的情况下解决这个问题。
【问题讨论】:
-
您可以通过将循环中的行更改为
cnt_a[xpos[i],ypos[i]] += 1,将第一个 for 循环的速度提高一倍。 -
x和y在2-column数组中,这是一个相关的Q&A。
标签: python arrays python-2.7 performance numpy