如何搭配numpy的切片列表索引? [英] How to mix numpy slices to list of indices?

查看:171
本文介绍了如何搭配numpy的切片列表索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 numpy.array ,名为电网,与形状:

I have a numpy.array, called grid, with shape:

grid.shape = [N, M_1, M_2, ..., M_N]

的N,M_1,M_2,值......,M_N只初始化后知道​​的。

The values of N, M_1, M_2, ..., M_N are known only after initialization.

在这个例子中,假设N = 3和M_1 = 20,M_2 = 17,M_3 = 9:

For this example, let's say N=3 and M_1 = 20, M_2 = 17, M_3 = 9:

grid = np.arange(3*20*17*9).reshape(3, 20, 17, 9)

我想遍历这个数组,如下:

I am trying to loop over this array, as follows:

for indices, val in np.ndenumerate(grid[0]):
    print indices
    _some_func_with_N_arguments(*grid[:, indices])

目前的第一次迭代,指数=(0,0,0)和

At the first iteration, indices = (0, 0, 0) and:

grid[:, indices] # array with shape 3,3,17,9

而我想这是只有三个元素的数组,很像:

whereas I want it to be an array of three elements only, much like:

grid[:, indices[0], indices[1], indices[2]] # array([   0, 3060, 6120])

这,但是我无法实现像在上述行,因为我不知道先验是什么指数的长度

我使用Python 2.7版,而是一个版本无关的实现是欢迎: - )

I am using python 2.7, but a version-agnostic implementation is welcome :-)

推荐答案

您可以添加片(无)手动索引元组:

You can add slice(None) to the index tuple manually:

>>> grid.shape
(3, 20, 17, 9)
>>> indices
(19, 16, 8)
>>> grid[:,19,16,8]
array([3059, 6119, 9179])
>>> grid[(slice(None),) + indices]
array([3059, 6119, 9179])

请参阅此处文档中更多。

这篇关于如何搭配numpy的切片列表索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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