用数组切片多维numpy数组 [英] slicing multi-dimensional numpy arrays with arrays

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

问题描述

我有一个 ~286 x 181 x 360 的 numpy 数组(我们称之为测试),需要从中提取一个 3-D 数组.三个维度所需的范围定义为其他 numpy 数组(a_dim、b_dim 和 c_dim)(最终基于用户输入).天真地,我曾希望我能够做类似 big_array[a_dim,b_dim,c_dim] 的事情.当 b_dim 和 c_dim 只包含一个值(这恰好发生在我的主要测试用例中)时,运行愉快,但当它们大于 1 时不起作用.

回溯(最近一次调用最后一次):文件<pyshell#541>",第 1 行,在 <module> 中测试[a_dim,b_dim,c_dim]ValueError:形状不匹配:对象不能广播到单个形状

为了简化,给定以下 4 个数组:

test=arange(125).reshape((5,5,5))a_dim=[0,1]b_dim=[1,2]c_dim=[2,3]

我想从上面的组合中得到的输出是:

array([[[ 7, 8],[12, 13]],[[32, 33],[37, 38]]])

或者,一个 3D 数组,包含在 a_dim、b_dim 和 c_dim 中定义的所有行、列和条带(或任何您想称为第三维的东西).我已经尝试为此使用 ix_,但显然我看到的示例中遗漏了一些内容:

<预><代码>>>>测试[ix_((a_dim,b_dim,c_dim))]回溯(最近一次调用最后一次):文件<pyshell#517>",第 1 行,在 <module> 中测试[ix_((a_dim,b_dim,c_dim))]文件C:\Python27\lib\site-packages\numpy\lib\index_tricks.py",第 73 行,在 ix_引发 ValueError,交叉索引必须是一维的"ValueError:交叉索引必须是一维的

有什么建议吗?谢谢!

解决方案

如此接近——只需删除对 numpy.ix_() 的调用中的一对括号:

<预><代码>>>>测试[ix_(a_dim,b_dim,c_dim)]数组([[[ 7, 8],[12, 13]],[[32, 33],[37, 38]]])

I have a numpy array (we'll call it test) of ~286 x 181 x 360, and need to extract a 3-D array from it. The ranges needed for the three dimensions are defined as other numpy arrays (a_dim, b_dim, and c_dim) (based ultimately on user input). Naively, I had hoped I'd be able to do something like big_array[a_dim,b_dim,c_dim]. That ran happily when the b_dim and c_dim contained only a single value (which happened to occur in my main test case), but doesn't work when they're bigger than 1.

Traceback (most recent call last):
  File "<pyshell#541>", line 1, in <module>
    test[a_dim,b_dim,c_dim]
ValueError: shape mismatch: objects cannot be broadcast to a single shape

To simplify, given the following 4 arrays:

test=arange(125).reshape((5,5,5))
a_dim=[0,1]
b_dim=[1,2]
c_dim=[2,3]

What I'd like to get as output from that combination above is:

array([[[ 7,  8],
        [12, 13]],

       [[32, 33],
        [37, 38]]])

Or, a 3D array containing the all of the rows, columns, and bands (or whatever you'd like to call a third dimension) that are defined in a_dim, b_dim, and c_dim. I've tried using ix_ for this, but am clearly missing something from the examples I've seen:

>>> test[ix_((a_dim,b_dim,c_dim))]

Traceback (most recent call last):
  File "<pyshell#517>", line 1, in <module>
    test[ix_((a_dim,b_dim,c_dim))]
  File "C:\Python27\lib\site-packages\numpy\lib\index_tricks.py", line 73, in ix_
    raise ValueError, "Cross index must be 1 dimensional"
ValueError: Cross index must be 1 dimensional

Any suggestions? Thanks!

解决方案

So close -- just remove one pair of parens in the call to numpy.ix_():

>>> test[ix_(a_dim,b_dim,c_dim)]
array([[[ 7,  8],
        [12, 13]],

       [[32, 33],
        [37, 38]]])

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

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