繁体   English   中英

numpy:快速/简便的方法来获取值等于另一个数组的数组的索引?

[英]Numpy: fast/easy way to get indices of array whose value is equal to another array?

假设我有一个整数x的数组,我想执行以下操作:

  1. 获得x的唯一值的数组unique_x
  2. 构建一个数组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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM