索引可变维数的ndarray [英] Indexing ndarray of variable number of dimensions

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

问题描述

我有一个numpy ndarray的实例,但是它的大小可变。

I have an instance of numpy ndarray, but of a variable size.

import numpy as np
dimensions = (4, 4, 4)
myarray = np.zeros(shape = dimensions)

在这种情况下,我得到一个立方形状的数组,如果我想索引一块 myarray 我可以使用 myarray [: ] [:] [0] 因为我知道有3个维度(我使用3对 [] )。

In this case, I get a "cubic" shape of the array and if I want to index a slice of myarray I can use myarray[:][:][0] because I know there are 3 dimensions (I use 3 pairs of []).

如果是4维,我会使用 myarray [:] [:] [:] [0] 。但是由于维度的数量可能会发生变化,我不能用这种方式对其进行硬编码。

In case of 4 dimensions, I would use myarray[:][:][:][0]. But since the number of dimensions may change, I cannot hard-code it this way.

如何根据维数来索引这样一个数组?看起来像一个简单的问题,虽然不能想到任何解决方案。

How can I index a slice of such an array depending on the number of dimensions? Seems like a simple problem, cannot think of any solution though.

推荐答案

你索引 myarray 设置1个括号,而不是多个:

You index myarray with 1 bracket set, not multiple ones:

myarray[:,:,:,i]
myarray[:,2,:,:]
myarray[...,3]
myarray[...,3,:]

您需要的每个维度的一个 ... 代表多个 - 提供 numpy 可以清楚地识别号码。

One : for each dimension that you want all of. ... stands in for multiple : - provided numpy can clearly identify the number.

可以省略尾随,当然除非使用 ...

Trailing : can be omitted, except of course when using ....

take 可以以相同的方式使用;它接受参数:

take can be used in the same way; it accepts an axis parameter:

np.take(myarray, i, axis=3)

您还可以将索引构建为元组,例如

You can also construct the indexing as a tuple, e.g.

ind = [slice(None)]*4
ind[2] = 3
myarray[tuple(ind)]
# same as myarray[:,:,3,:]
# myarray.take(3, axis=2)

np.apply_along_axis 执行这种索引方式。

例如

In [274]: myarray=np.ones((2,3,4,5))

In [275]: myarray[:,:,3,:].shape
Out[275]: (2, 3, 5)

In [276]: myarray.take(3,axis=2).shape
Out[276]: (2, 3, 5)

In [277]: ind=[slice(None)]*4; ind[2]=3

In [278]: ind
Out[278]: [slice(None, None, None), slice(None, None, None), 3, slice(None, None, None)]

In [279]: myarray[tuple(ind)].shape
Out[279]: (2, 3, 5)

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

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