Python 我如何在numpy中使用'np.choose'或'np.take'或类似的词来对其进行矢量化?
我想对下面的Python 我如何在numpy中使用'np.choose'或'np.take'或类似的词来对其进行矢量化?,python,pandas,numpy,Python,Pandas,Numpy,我想对下面的do_permutation函数进行矢量化。我想删除python中的循环,改为使用numpy方法 import numpy as np def do_permutation(indices): perm = np.zeros(len(indices), dtype='int32') for i, o in enumerate(indices): perm[o] = i return perm assert list(do_permutati
do_permutation
函数进行矢量化。我想删除python中的循环,改为使用numpy方法
import numpy as np
def do_permutation(indices):
perm = np.zeros(len(indices), dtype='int32')
for i, o in enumerate(indices):
perm[o] = i
return perm
assert list(do_permutation([3, 2, 4, 1, 0])) == [4, 3, 1, 0, 2]
您可以分配给使用给定索引索引索引的数组切片
def do_排列(索引):
N=len(指数);
perm=np.zero(N,dtype='int32')
perm[index]=np.arange(N)
回烫
一般的解决方案是
do_perm = np.argsort
但是,此解决方案是O(N log N)
。对于足够长的索引,实际上是从零到N的排列,一个O(N)
解决方案是值得的。在这种情况下,请使用直接订购:
def do_perm(indices):
perm = np.empty_like(indices)
perm[indices] = np.arange(len(indices))
return perm
最后一行也可以写成
np.put(perm, indices, np.arange(indices.size))
使用允许您透明地处理展开的
索引。我最初的想法是np。选择和np.take
。在我看来:断言列表(np.argsort([3,2,4,1,0])==[4,3,1,0,2]
。