python中的numpy多维数组的非相邻切片 [英] non adjacent slicing of numpy multidimensional array in python

查看:348
本文介绍了python中的numpy多维数组的非相邻切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组:

a = np.random.uniform(1,10,(2,4,2,3,10,10))

对于维度4-6,我有3个列表,其中包含用于对数组'a'的该维度进行切片的索引

For dimensions 4-6, I have 3 lists which contain the indexes for slicing that dimension of array 'a'

dim4 = [0,2]
dim5 = [3,5,9]
dim6 = [1,2,7,8]

如何对数组'a'进行切片,以便得到:

How do I slice out array 'a' such that i get:

b = a[0,:,0,dim4,dim5,dim6]

所以b应该是一个形状为(4,2,3,4)的数组,并包含来自a相应维度的元素.当我尝试上面的代码时,我收到一条错误消息,提示无法针对轴4-6一起广播不同的形状,但是如果我要这样做:

So b should be an array with shape (4,2,3,4), and containing elements from the corresponding dimensions of a. When I try the code above, I get an error saying that different shapes can't be broadcast together for axis 4-6, but if I were to do:

b = a[0,:,0:2,0:3,0:4]

然后,即使切片列表的长度都不同,它也可以工作.那么,如何对具有非相邻索引的多维数组进行切片呢?

then it does work, even though the slicing lists all have different lengths. So how do you slice multidimensional arrays with non adjacent indexes?

推荐答案

您可以使用numpy.ix_函数来构造复杂的索引.它采用一个array_like序列,并根据它们创建一个开放式网格".文档字符串中的示例非常清楚:

You can use the numpy.ix_ function to construct complex indexing like this. It takes a sequence of array_like, and makes an "open mesh" from them. The example from the docstring is pretty clear:

使用ix_可以快速构建索引数组,该数组将建立索引 叉积. a[np.ix_([1,3],[2,5])]返回数组 [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

因此,为了您的数据,您会这样做:

So, for your data, you'd do:

>>> indices = np.ix_((0,), np.arange(a.shape[1]), (0,), dim4, dim5, dim6)
>>> a[indices].shape
(1, 4, 1, 2, 3, 4)

使用np.squeeze摆脱尺寸为1的尺寸:

Get rid of the size-1 dimensions with np.squeeze:

>>> np.squeeze(a[indices]).shape
(4, 2, 3, 4)

这篇关于python中的numpy多维数组的非相邻切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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