简体   繁体   English

将numpy索引应用于矩阵

[英]Apply numpy index to matrix

I have spent the last hour trying to figure this out 我花了最后一个小时试图解决这个问题

Suppose we have 假设我们有

import numpy as np
a = np.random.rand(5, 20) - 0.5
amin_index = np.argmin(np.abs(a), axis=1)
print(amin_index)
> [ 0 12  5 18  1] # or something similar

this does not work: 这不起作用:

a[amin_index]

So, in essence, I need to find the minima along a certain axis for the array np.abs(a), but then extract the values from the array a at these positions. 因此,从本质上讲,我需要沿着数组np.abs(a)的某个轴查找最小值,然后从这些位置的数组a中提取值。 How can I apply an index to just one axis? 如何将索引仅应用于一个轴?

Probably very simple, but I can't get it figured out. 可能非常简单,但我无法弄清楚。 Also, I can't use any loops since I have to do this for arrays with several million entries. 另外,我不能使用任何循环,因为我必须对具有数百万个条目的数组执行此操作。 thanks 😊 谢谢😊

是因为argmin返回每一行的列索引(其中axis=1 ),因此您需要访问这些特定列的每一行:

a[range(a.shape[0]), amin_index]

One way is to pass in the array of row indexes (eg [0,1,2,3,4] ) and the list of column indexes for the minimum in each corresponding row (your list amin_index ). 一种方法是传入行索引数组(例如[0,1,2,3,4] )和每个对应行中最小值的列索引列表(您的列表amin_index )。

This returns an array containing the value at [i, amin_index[i]] for each row i : 这将返回一个数组,其中包含每行i [i, amin_index[i]]处的值:

>>> a[np.arange(a.shape[0]), amin_index]
array([-0.0069325 ,  0.04268358, -0.00128002, -0.01185333, -0.00389487])

This is basic indexing (rather than advanced indexing), so the returned array is actually a view of a rather than a new array in memory. 这是基本索引(而不是高级索引),因此返回的数组实际上是内存中a而不是新数组的视图。

Why not simply do np.amin(np.abs(a), axis=1) , it's much simpler if you don't need the intermediate amin_index array via argmin? 为什么不简单地使用np.amin(np.abs(a), axis=1)呢? 如果您不需要通过amin_index的中间amin_index数组,它会简单得多?

Numpy's reference page is an excellent resource, see "Indexing". Numpy的参考页是一个很好的资源,请参阅“索引”。

Edits: Timing is always useful: 编辑:时间总是有用的:

In [3]: a=np.random.rand(4000, 4000)-.5

In [4]: %timeit np.amin(np.abs(a), axis=1)
10 loops, best of 3: 128 ms per loop

In [5]: %timeit a[np.arange(a.shape[0]), np.argmin(np.abs(a), axis=1)]
10 loops, best of 3: 135 ms per loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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