的Python:指数使用冒号运算符中的任意维数组 [英] Python: Index an array using the colon operator in an arbitrary dimension

查看:476
本文介绍了的Python:指数使用冒号运算符中的任意维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy的第二阵列。我的任务的简化版本,是从沿每个轴采取的向量。为了说明:

I have a numpy nd array. A simplified version of my task is to take a vector from along each axis. To illustrate:

import numpy
x = numpy.array(range(24)).reshape((2,3,4))
x0 = x[0,0,:]
x1 = x[0,:,0]
x2 = x[:,0,0]

但是我不一定知道尺寸x将具有的数目。因此,面临的挑战是如何将冒号:索引操作符在变量的位置。这样有什么语法的一个例子可能看起来像:

However I do not necessarily know the number of dimensions x will have. So the challenge is how to place the colon : indexing operator in a variable location. An example of what such syntax could look like:

n = x.ndim
ind = list(np.zeros(n))
dim = 0
ind[dim] = ':'
y = x[ind]

y = indexer.index(x,ind)

对于某些模块索引。我可以写,但我喜欢这种感觉必须已经解决了,我不能谁愿意做这唯一的一个。在MATLAB中,例如,你可以使用的subsref()函数做到这一点。

for some module indexer. I could write it, but I feel like this must already be solved, I can't be the only one who wants to do this. In MATLAB, for example, you can do this with the subsref() function.

在是否蟒蛇/ numpy的/其他模块的任何结构存在?

Does any such construct exist in python / numpy / other module?

推荐答案

由于从 numpy的提出的有关的索引可以使用的 内置功能和元组串联创建变量指标。

As suggested from numpy's documentation about indexing you can use the slice built-in function and tuple concatenation to create variable indexes.

在事实上在标简直就是一个片的文字符号文字

In fact the : in the subscript is simply the literal notation for a slice literal.

在特定的等同于片(无)(其中,本身就是等于片(无,无,无)这里的参数是启动停止)。

In particular : is equivalent to slice(None) (which, itself, is equivalent to slice(None, None, None) where the arguments are start, stop and step).

例如:

a[(0,) * N + (slice(None),)]

相当于:

a[0, 0, ..., 0, :]   # with N zeros

:对于片符号只能直接下标内部使用。例如,这将失败:

The : notation for slices can only be used directly inside a subscript. For example this fails:

In [10]: a[(0,0,:)]
  File "<ipython-input-10-f41b33bd742f>", line 1
    a[(0,0,:)]
           ^
SyntaxError: invalid syntax

要允许任意尺寸的阵列中提取切片你可以写一个简单的功能,如:

To allow extracting a slice from an array of arbitrary dimensions you can write a simple function such as:

def make_index(num_dimension, slice_pos):
    zeros = [0] * num_dimension
    zeros[slice_pos] = slice(None)
    return tuple(zeros)

和使用它作为:

In [3]: a = np.array(range(24)).reshape((2, 3, 4))

In [4]: a[make_index(3, 2)]
Out[4]: array([0, 1, 2, 3])

In [5]: a[make_index(3, 1)]
Out[5]: array([0, 4, 8])

In [6]: a[make_index(3, 0)]
Out[6]: array([ 0, 12])

您可以概括 make_index 做任何事情。要记住的重要一点是,它应该在年底,返回包含无论是整数或元组

You can generalize make_index to do any kind of things. The important thing to remember is that it should, in the end, return a tuple containing either integers or slices.

这篇关于的Python:指数使用冒号运算符中的任意维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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