索引到numpy的mgrid [英] indexing into numpy's mgrid

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

问题描述

我使用 numpy.mgrid 生成坐标索引数组

I use numpy.mgrid to generate "coordinate index arrays"

y, x = np.mgrid[0:3, 0:2]
print x
array([[0, 1],
       [0, 1],
       [0, 1]])

在很多情况下,我会对这些数组进行一些切片(例如 x [0,:] )并丢弃其余数据。有时,这些切片比原始数组小得多,原始数组的计算成本很高(即 np.mgrid [0:512,0:512,0:512] )。 Numpy是否为np.mgrid [0:512,0:512,0:512] 中的coord提供了等价 [coord [view]数组?

In many situations, I take some slice through these arrays (e.g. x[0, :]) and discard the rest of the data. Sometimes, these slices are much smaller than the original arrays, which are expensive to compute (i.e. np.mgrid[0:512, 0:512, 0:512]). Does numpy provide an equivalent to [coord[view] for coord in np.mgrid[0:512, 0:512, 0:512] that doesn't generate large intermediate arrays?

我意识到解决方案对于切片 [0,:] 来说是微不足道的,但我正在寻找一般解决方案,处理索引numpy数组的任何有效方法

I realize the solution is trivial for the slice [0,:], but I'm looking for a general solution that handles any valid way to index numpy arrays

编辑

有些人要求提供 view 的具体示例。理想情况下,我希望有一个通用的解决方案来处理索引ndarray的任何有效方法。以下是上述3x2数组的一些具体示例:

Some have asked for specific examples for what view might look like. Ideally, I'm hoping for a general solution that handles any valid way to index a ndarray. Here are a few specific examples for the 3x2 array above:

1) view =(1,slice(None,None,2))

2) view =(np.array([0,1]),np.array([0, 1]))

3) view = np.array([[False,False],[False, True],[False,False]])

我正在寻找像

def mgrid_with_view(array_shape, view)
    ...

返回相当于 [o [view] for o in np.indices(array_shape)] ,无需不必要的计算或内存。

That returns the equivalent of [o[view] for o in np.indices(array_shape)] without unnecessary computation or memory.

推荐答案

正如HYRY所说,我相信你要避免的是创建完整数组。 mgrid 创建一个完整数组,但是如果你使用:

As HYRY mentioned, I believe what you want to avoid is creating the full arrays. mgrid creates a full array, however if you use:

x, y = np.broadcast_arrays(*np.ogrid[0:2,0:3])

x y 占用更多内存然后 np.arange(0,2)(和 np.arange(0,3)),同时表现得好像是一个完整的数组。如果需要单个大型结果数组,则应该单独切片这些数组,然后将它们连接起来。 (np.broadcast_arrays返回一个数组元组而不是数组)

x and y take up no more memory then np.arange(0,2) (and np.arange(0,3)), while acting as if each was a full array. If you require a single large result array, you should probably slice these arrays individually and then concatenate them. (np.broadcast_arrays returns a tuple of arrays instead of an array)

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

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