Python 不带for循环的行、列分配
我编写了一个小脚本,通过了解numpy数组的行和列坐标来为其赋值:Python 不带for循环的行、列分配,python,numpy,Python,Numpy,我编写了一个小脚本,通过了解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 = 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循环的方法
类似的方法是否可行?我知道这还不起作用
gridarray[rows,cols] += data
gridarray_counts[rows,cols] += 1
您可以直接执行此操作:
gridarray[(rows,cols)]+=data
gridarray_counts[(rows,cols)]+=1
我会使用
bincount
,但是现在bincount只需要1dArray,所以您需要编写自己的ndbincout,比如:
def ndbincount(x,权重=无,形状=无):
如果形状为“无”:
形状=x.max(1)+1
x=np.ravel\u多重指数(x,形状)
out=np.bincount(x,权重,最小长度=np.prod(形状))
out.shape=shape
返回
然后你可以做:
gridarray = 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)
x = np.vstack([rows, cols])
temp = ndbincount(x, data, gridarray.shape)
gridarray = gridarray + temp
gridarray_counts = ndbincount(x, shape=gridarray.shape)
不幸的是,这不会产生相同的(正确的)输出。@supercube啊,好的,我假设了唯一的索引。我将保留这个答案,以防它对其他可能具有唯一索引的人有所帮助。只是为了向未来的读者澄清一下,这个看似简单的解决方案是不起作用的,实际上是不起作用的,因为
行、列
包含重复的索引。有关更多详细信息,请参阅。该方法非常有效,比for循环分配方法快10倍。