python2中numpy的切片操作 [英] slice operation for numpy in python2

查看:96
本文介绍了python2中numpy的切片操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 numpy 数组 X :

array([[ 0.13263767,  0.23149757,  0.57097612],
       [ 0.49629958,  0.67507182,  0.6758823 ]])

还有一个索引数组 Y :

array([1, 2, 1])

我可以使用 X [0:,Y] X 的第一行编制索引,它将输出:

I could use X[0:,Y] to index the first row of X, and it will output the:

array([ 0.23149757,  0.57097612,  0.23149757])

我的问题是,如果我有一个具有2维的索引数组 Z :

my question is, if I have an index array Z with 2 dimensions:

array([[1, 2, 1],
       [0, 1, 2]])

我想使用 Z 的第一行来索引 X 的第一行,使用 Z 的第二行来索引 X 的第二行( Z X 具有相同的行). 因此,一种方法是按以下方式使用命令:

I would like to use first row to of Z to index the first row of X, and second row of Z to index the second row of X (Z and X have the same rows). So one way is to use command as follow:

Row_0 = X[0:, Z[0]]
Row_1 = X[1:, Z[1]]

我想知道是否有一种简单的方法可以做到这一点. 谢谢

I was wondering if there is a simple way to do this. Thanks

推荐答案

您可以使用花式索引来实现:

You can use fancy indexing to achieve that:

>>> X[[[0], [1]], Z]
array([[ 0.23149757,  0.57097612,  0.23149757],
       [ 0.49629958,  0.67507182,  0.6758823 ]])

诀窍在于,索引第一个维度的数组必须与索引第二个维度的数组一起广播.在这种情况下:

The trick is that the array indexing the first dimension must broadcast with the one indexing the second one. In this case:

>>> np.array([[0], [1]]).shape
(2, 1)
>>> Z.shape
(2, 3)

因此,返回值将具有广播形状,(2, 3),其索引从第一个维度的第一个数组中获取,而从第二个维度的第二个数组中获取.

So the return will be of the broadcast shape, (2, 3) with indices taken from the first array for the first dimension, and from the second array for the second dimension.

对于更一般的情况,您可以获得与以下相同的结果:

For more general cases, you can get the same result as:

>>> X[np.arange(Z.shape[0])[:, None], Z]
array([[ 0.23149757,  0.57097612,  0.23149757],
       [ 0.49629958,  0.67507182,  0.6758823 ]])

这篇关于python2中numpy的切片操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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