![](/img/trans.png)
[英]Slicing a Python list with a NumPy array of indices — any fast way?
[英]Numpy: fast/easy way to get indices of array whose value is equal to another array?
假设我有一个整数x
的数组,我想执行以下操作:
x
的唯一值的数组unique_x
y
,其中y[i]
是x[i]
值在unique_x
中的索引。 我设法做到这一点如下:
import numpy as np
unique_x = np.unique(x)
y = np.zeros_like(x)
for k, value in unique_x:
indices, = np.nonzero(x == value)
y[indices] = k
我的问题是:有没有办法仅使用numpy内置函数和一些切片呢? 我有一种感觉,如果使用numpy内置函数完成此循环,将不会像以前那样快。
如果np.unique()
完成了您想要的操作(仅返回每个元素的第一次出现;它不仅返回出现一次的那些元素),则可以使用return_index
参数:
In [1]: x = array([1, 1, 2, 3, 4, 4, 5, 6, 2, 1])
In [2]: unique_x, unique_indexes = np.unique(x, return_index=True)
In [3]: unique_x
Out[3]: array([1, 2, 3, 4, 5, 6])
In [4]: unique_indexes
Out[4]: array([0, 2, 3, 4, 6, 7])
( x
不需要排序,但unique_x
将是)。 另一方面,如果您希望从unique_x
重构x
所需的unique_x
,则可以使用return_inverse
参数,如return_inverse
所指出:
In [5]: unique_x, unique_inverse = np.unique(x, return_inverse=True)
In [6]: unique_inverse
Out[6]: array([0, 0, 1, 2, 3, 3, 4, 5, 1, 0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.