没有forloop的行、列赋值

2024-06-28 11:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个小脚本,通过知道numpy数组的行和列坐标来为其赋值:

gridarray = np.zeros([3,3])
gridarray_counts = np.zeros([3,3])

cols = np.random.random_integers(0,2,15)
rows = np.random.random_integers(0,2,15)
data = np.random.random_integers(0,9,15)

for nn in np.arange(len(data)):
    gridarray[rows[nn],cols[nn]] += data[nn]
    gridarray_counts[rows[nn],cols[nn]] += 1

实际上,我知道在同一个网格单元中存储了多少个值,它们的和是多少。但是,在长度为100000+的数组上执行此操作会变得相当缓慢。有没有其他不使用for循环的方法?在

有没有类似的方法?我知道这还不行。在

^{pr2}$

Tags: 方法integersnumpy脚本fordatanpzeros
2条回答

您可以直接执行以下操作:

gridarray[(rows,cols)]+=data
gridarray_counts[(rows,cols)]+=1

我将使用bincount来实现这一点,但目前bincount只接受1darray,因此您需要编写自己的ndbincout,类似于:

def ndbincount(x, weights=None, shape=None):
    if shape is None:
        shape = x.max(1) + 1

    x = np.ravel_multi_index(x, shape)
    out = np.bincount(x, weights, minlength=np.prod(shape))
    out.shape = shape
    return out

然后您可以:

^{pr2}$

相关问题 更多 >