通过使用另一个数组作为沿轴的切片索引来切片数组 [英] Slicing array by using another array as the slice indices along axis

查看:101
本文介绍了通过使用另一个数组作为沿轴的切片索引来切片数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个看起来像下面的数组:

Say I have an array that looks like the following:

arr = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]]

我还有另一个数组slicer = [1,3,2].我想将这些值应用为沿轴1的0轴上的切片索引.

And I have another array slicer = [1,3,2]. I want to apply these values as the slice index over axis 0 measure along axis 1.

这是行不通的(实际上没有办法指定其沿部分是ndarray中的轴1),但是假设我尝试了arr[:slicer, :]

This doesn't work (and in fact contains no way of specifying that the along part is axis 1 in an ndarray) but suppose I tried arr[:slicer, :]

我希望获得

out = [[1,   2,   3],
       [nan, 5,   6],
       [nan, 8, nan]]

是应用切片arr[:1, :]arr[:3, :]arr[:2, :],然后分别从第一列,第二列和第三列中进行选择,然后重新组合到上面的数组中,从而删除缺失值的组合.

which is the combination of applying the slice arr[:1, :], arr[:3, :], arr[:2, :] and then selecting from those the 1st, 2nd and 3rd columns respectively and reassembling into the array above, dropping missing values.

我想避免循环,并试图找到一种快速的矢量化解决方案

I want to avoid loops and trying to find a fast vectorised solution

推荐答案

对于此操作,您需要首先生成一个布尔索引掩码,该掩码标记要设置为nan的所有字段.通过广播,可以轻松地进行外部比较",从而产生所需的结果

For this operation you need to first generate a boolean index mask that marks all fields you want to set to nan. Broadcasting makes it easy to perform an "outer comparison" that yields the desired result

slicer = numpy.asarray([1, 3, 2])
mask = numpy.arange(3)[:, None] >= slicer
mask
# array([[False, False, False],
#        [ True, False, False],
#        [ True, False,  True]])

然后您可以简单地使用此掩码为data

You can then simply use this mask to index data

data = numpy.arange(1, 10, dtype=float).reshape(3, 3)
data[mask] = numpy.nan
data
# array([[ 1.,  2.,  3.],
#        [nan,  5.,  6.],
#        [nan,  8., nan]])

这篇关于通过使用另一个数组作为沿轴的切片索引来切片数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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