python - 获取另一个 numpy 数组中一个 numpy 数组的索引

标签 python numpy numpy-ndarray

我正在尝试获取另一个 numpy 数组内的 numpy 数组的索引,例如,我有

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

x 包含在 y 中,所以我想要得到的是索引 idx x 数组在 y 数组上的顺序相同,所以这里是 idx = array([2, 0, 5])这样我们就有 np.array_equal(y[idx] ,x)产量True , 我尝试使用 np.argwhere(np.in1d(y,x)) ,但显然我没有得到相同的顺序,我知道我总是可以使用列表理解 idx = [ list(y).index(el) for el in x] ,但我更喜欢使用 numpy。 有什么想法吗?

最佳答案

来自Is there a NumPy function to return the first index of something in an array?

>>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
>>> nonzero(t == 8)
(array([6, 8, 9]),)
>>> nonzero(t == 8)[0][0]
6

因此请根据您的情况进行调整:

lst=[]
for item in x:
    lst.append( list(nonzero(y == item)) )

关于python - 获取另一个 numpy 数组中一个 numpy 数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56682344/

相关文章:

python - 使用变量进行切片时如何使用单冒号?

Python多线程,如何使用多个核心?

python - 地理坐标(纬度/经度)上的抖动功能

python - 从数组中删除随机选择的元素

python - 如何切片列数未知的numpy数组?

python - 如何使用列的值将 2 个 numpy ndarray 合并到 ndarray 上?

python - 在 GAE(日历 API)的 Python 中解析来自 InsertCalendar 的原子响应

python - append 两个 pandas 数据帧时, bool 值将转换为 float

python - 将 Pandas Dataframe 行中的所有值相乘

python - 在 numpy 数组中传播最大值