如何选择具有给定起点索引的numpy数组中的元素 [英] How to select elements in numpy array with given starting point indices

查看:71
本文介绍了如何选择具有给定起点索引的numpy数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个像这样的矩阵:

For example, I have a matrix like this:

In [2]: a = np.arange(12).reshape(3, 4)

In [3]: a
Out[3]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

和起点索引数组:

In [4]: idx = np.array([1, 2, 0])

In [5]: idx
Out[5]: array([1, 2, 0])

是否有任何矢量化的方式来做这种事情:

Are there any vectorized ways to do such things:

for i in range(3):
    # The following are some usecases
    a[i, idx[i]:] = 0
    a[i, idx[i]-1:] = 0
    a[i, :idx[i]] = 0
    a[i, idx[i]:idx[i]+2] = 0

预期输出:

array([[ 0,  x,  x,  x],
       [ 4,  5,  x,  x],
       [ x,  x,  x,  x]])

x是占位符,指示我要选择的内容.

x is placeholder indicating what I'd like to select.

推荐答案

方法也适用于矩形矩阵.创建一个布尔型波谷波谷广播:

This aproach works for rectangular matrices too. Create a boolean mask trough broadcasting:

a = np.arange(12).reshape(3, 4)
idx = np.array([1, 2, 0])
mask=np.arange(a.shape[1]) >= idx[:,None]
mask
#array([[False,  True,  True,  True],
#       [False, False,  True,  True],
#       [ True,  True,  True,  True]], dtype=bool)

例如,使用您的占位符 -1,并设置a的值,其中mask等于该占位符:

Make your placeholder -1, for example, and set the values of a where mask is true equal to that placeholder:

x = -1
a[mask] = x
a
#array([[ 0, -1, -1, -1],
#       [ 4,  5, -1, -1],
#      [-1, -1, -1, -1]])

这篇关于如何选择具有给定起点索引的numpy数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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