numpy ndarray高级索引 [英] numpy ndarray advanced indexing

查看:72
本文介绍了numpy ndarray高级索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3维的ndarray. 如何从第一轴选择索引0和1,同时从第二轴选择索引0和3,从第三轴选择索引1?

I have ndarray of 3 dimension. How do I select index 0 and 1 from first axis while selecting index 0 and 3 from second axis and index 1 from third axis?

我试图使用索引[(0,1),(1,3),1],它产生的结果与我认为的结果完全不同.

I tried to use index [(0,1), (1, 3), 1], which produces a result completely different than what I thought it would produce.

这里有两个问题. [(0,1),(1,3),1]会做什么? 以及如何正确创建解决我的原始问题的索引.

So two questions here. What does [(0,1), (1, 3), 1] do? And how to correctly create an index that solve my original question.

a = np.arange(30).reshape(3, 5, 2)
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5],
        [ 6,  7],
        [ 8,  9]],

       [[10, 11],
        [12, 13],
        [14, 15],
        [16, 17],
        [18, 19]],

       [[20, 21],
        [22, 23],
        [24, 25],
        [26, 27],
        [28, 29]]])

a[0, (1, 3), 1]  # produces array([3, 7])
a[(0,1), (1, 3), 1] # produces array([ 3, 17])

```

推荐答案

在对执行方式进行索引时,NumPy不会将其解释为选择每个维度的索引.取而代之的是,NumPy互相广播参数:

When you index the way you're doing it, NumPy doesn't interpret it as selecting those indices of each dimension. Instead, NumPy broadcasts the arguments against each other:

a[(0,1), (1, 3), 1] -> a[array([0, 1]), array([1, 3]), array([1, 1])]

,然后在a[i, j, k][x] == a[i[x], j[x], k[x]]处创建结果数组.

and then creates a result array where a[i, j, k][x] == a[i[x], j[x], k[x]].

要获得所需的行为,您需要重塑传递的参数,以便相互广播会产生形状为(2, 2)的数组,而不是形状为(2,)的数组.这意味着第一个参数的形状为(2, 1),第二个参数的形状为(1, 2)(2,),第三个参数的形状很好. numpy.ix_ 可以使此操作更容易,但不支持标量参数. a[np.ix_([0, 1], [1, 3], [1])]会执行您期望的a[[0, 1], [1, 3], [1]]所要做的事情,但是要获得a[[0, 1], [1, 3], 1]所期望的形状,您的选择会更加混乱:

To get the behavior you're looking for, you need to reshape the arguments you're passing, so that broadcasting them against each other produces an array of shape (2, 2) instead of shape (2,). This means the first argument needs shape (2, 1), the second argument needs to have shape (1, 2) or (2,), and the third argument's shape is fine. numpy.ix_ can make this easier, but it doesn't support scalar arguments. a[np.ix_([0, 1], [1, 3], [1])] does what you would have expected a[[0, 1], [1, 3], [1]] to do, but to get the shape you would have expected from a[[0, 1], [1, 3], 1], your options are messier:

>>> a[np.ix_([0, 1], [1, 3], [1])]
array([[[ 3],
        [ 7]],

       [[13],
        [17]]])
>>> a[np.ix_([0, 1], [1, 3]) + (1,)]
array([[ 3,  7],
       [13, 17]])
>>> a[np.ix_([0, 1], [1, 3], [1])][:, :, 0]
array([[ 3,  7],
       [13, 17]])

这篇关于numpy ndarray高级索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆