使用另一个数组索引numpy数组 [英] Index a numpy array with another array
问题描述
我觉得很傻,因为这是一件很简单的事情,但我在这里或其他任何地方都找不到答案。
I feel silly, because this is such a simple thing, but I haven't found the answer either here or anywhere else.
有没有直截了当的方法用另一个索引一个numpy数组?
Is there no straightforward way of indexing a numpy array with another?
说我有一个2D数组
>> A = np.asarray([[1, 2], [3, 4], [5, 6], [7, 8]])
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
如果我想访问元素[3,1]我输入
if I want to access element [3,1] I type
>> A[3,1]
8
现在,我说这个索引存储在一个数组中
Now, say I store this index in an array
>> ind = np.array([3,1])
这次尝试使用索引:
>> A[ind]
array([[7, 8],
[3, 4]])
结果不是A [3,1]
the result is not A[3,1]
问题是:有数组A和ind,获取A的最简单方法是什么[3,1]
The question is: having arrays A and ind, what is the simplest way to obtain A[3,1]?
推荐答案
只需使用元组:
>>> A[(3, 1)]
8
>>> A[tuple(ind)]
8
A [ ]
实际调用特殊方法 __ getitem __
:
>>> A.__getitem__((3, 1))
8
并使用逗号创建一个元组:
and using a comma creates a tuple:
>>> 3, 1
(3, 1)
将这两个基本的Python原则放在一起可以解决你的问题问题。
Putting these two basic Python principles together solves your problem.
如果您不需要NumPy数组功能,可以将索引存储在元组中。
You can store your index in a tuple in the first place, if you don't need NumPy array features for it.
这篇关于使用另一个数组索引numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!