删除numpy中的循环以进行简单的矩阵分配 [英] Removing loops in numpy for a simple matrix assignment
问题描述
如何在这种简单的矩阵分配中删除循环以提高性能?
How can I remove loops in this simple matrix assignment in order to increase performance?
nk,ncol,nrow=index.shape
for kk in range(0,nk):
for ii in range(0,nrow):
for jj in range(0,ncol):
idx=index[kk][ii][jj]
counter[idx][ii][jj]+=1
我来自C ++,发现很难适应numpy的函数来进行一些非常基本的矩阵操作,例如这样.我想我已经将其简化为一个一维的循环,但是对于我所需要的来说,这仍然太慢了,在我看来,必须有一种更直接的方法来完成它.有什么建议么?谢谢
I come from C++ and I am finding it difficult to adapt to numpy's functions to do some very basic matrix manipulation like this one. I think I have simplified it to a one dimensional loop, but this is still too slow for what I need and it seems to me that there is got to be a more direct way of doing it. Any suggestions? thanks
for kk in range(0,nk):
xx,yy = np.meshgrid(np.arange(ncol),np.arange(nrow))
counter[index[kk,:,:].flatten(),yy.flatten(),xx.flatten()]+=1
推荐答案
如果我理解正确,那么您正在寻找:
If I understand it correctly, you are looking for this:
uniq, counter = np.unique(index, return_counts=True, axis=0)
uniq
应该为您提供一组唯一的 x,y
s( x,y
将被展平为单个数组),并且< index
The uniq
should give you unique set of x,y
s (x,y
will be flattened into a single array) and counter
corresponding number of repetitions in the array index
编辑 :
每个OP的评论如下:
xx,yy = np.meshgrid(np.arange(ncol),np.arange(nrow))
idx, counts = np.unique(np.vstack((index.flatten(),np.repeat(yy.flatten(),nk),np.repeat(xx.flatten(),nk))), return_counts=True,axis=1)
counter[tuple(idx)] = counts
这篇关于删除numpy中的循环以进行简单的矩阵分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!