Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.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数组的排列以将其与另一个数组对齐?_Python_Numpy_Permutation - Fatal编程技术网

Python 找到numpy数组的排列以将其与另一个数组对齐?

Python 找到numpy数组的排列以将其与另一个数组对齐?,python,numpy,permutation,Python,Numpy,Permutation,我有两个numpy数组,例如 将numpy导入为np x=np.array([3,1,4]) y=np.数组([4,3,2,1,0]) 每个都包含唯一的值。x中的值保证是y中值的子集 我想找到数组y中x的每个元素的索引 在上面的数组中,这将是 [1,3,0] 到目前为止,我一直在循环中一次找到一个索引: idxs=[] 对于x中的val: append(np.argwhere(y==val)[0,0]) 但当我的阵列很大时,速度会很慢 有更有效的方法吗?将np.isin与np.argwhe

我有两个numpy数组,例如

将numpy导入为np
x=np.array([3,1,4])
y=np.数组([4,3,2,1,0])
每个都包含唯一的值。
x
中的值保证是
y
中值的子集

我想找到数组
y
x
的每个元素的索引

在上面的数组中,这将是

[1,3,0]
到目前为止,我一直在循环中一次找到一个索引:

idxs=[]
对于x中的val:
append(np.argwhere(y==val)[0,0])
但当我的阵列很大时,速度会很慢


有更有效的方法吗?

np.isin
np.argwhere

[np.argwhere(el==y)[0,0] for el in x]

np.isin
np.argwhere

[np.argwhere(el==y)[0,0] for el in x]
使用list.index()方法可以显著缩短时间

y = y.tolist()
indexes = [y.index(i) for i in x]

下面是一个快速计时结果

import numpy as np
import timeit

x = np.array([3, 1, 4])
y = np.array([4, 3, 2, 1])

total_time = timeit.timeit('[np.argwhere(y == i)[0, 0] for i in x]',
                           'from __main__ import ' + ', '.join(globals()), number=10000)
print("using argwhere = ", total_time)

total_time = timeit.timeit('[y.tolist().index(i) for i in x]',
                           'from __main__ import ' + ', '.join(globals()), number=10000)
print("using list index = ", total_time)

使用argwhere=0.271694822999616

使用list index=0.0523195809996505

使用list.index()方法可以显著缩短时间

y = y.tolist()
indexes = [y.index(i) for i in x]

下面是一个快速计时结果

import numpy as np
import timeit

x = np.array([3, 1, 4])
y = np.array([4, 3, 2, 1])

total_time = timeit.timeit('[np.argwhere(y == i)[0, 0] for i in x]',
                           'from __main__ import ' + ', '.join(globals()), number=10000)
print("using argwhere = ", total_time)

total_time = timeit.timeit('[y.tolist().index(i) for i in x]',
                           'from __main__ import ' + ', '.join(globals()), number=10000)
print("using list index = ", total_time)

使用argwhere=0.271694822999616


使用列表索引=0.0523195809996505

我希望保留索引的顺序,以便
all(y[idxs]==x)
应该是
True
。有没有办法修改您的解决方案来实现这一点?这可能会稍微慢一点,因为我们正在使用循环,但它的工作速度可能会比您的第一次尝试更快一些快速计时实验表明,它的速度大致相同。我希望保留索引的顺序,以便
all(y[idxs]==x)
应该是
True
。有没有办法修改您的解决方案来实现这一点?这可能会稍微慢一点,因为我们使用的是循环,但它的工作速度可能会比您第一次尝试的更快一些快速计时实验表明它的速度大致相同