Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我如何在numpy中使用'np.choose'或'np.take'或类似的词来对其进行矢量化?_Python_Pandas_Numpy - Fatal编程技术网

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]