填写2d numpy数组的给定索引之间的值 [英] Fill in values between given indices of 2d numpy array

查看:65
本文介绍了填写2d numpy数组的给定索引之间的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个numpy数组,

Given a numpy array,

a = np.zeros((10,10))

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

对于一组索引,例如:

start = [0,1,2,3,4,4,3,2,1,0]
end   = [9,8,7,6,5,5,6,7,8,9]

如何选择"起始索引和结束索引之间的所有值/范围并获得以下内容:

how do you get the "select" all the values/range between the start and end index and get the following:

result = [[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
          [1, 1, 0, 0, 0, 0, 0, 0, 1, 1],
          [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
          [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
          [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
          [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
          [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
          [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
          [1, 1, 0, 0, 0, 0, 0, 0, 1, 1],
          [1, 0, 0, 0, 0, 0, 0, 0, 0, 1]]

我的目标是选择"列的每个给定索引之间的所有值.

My goal is to 'select' the all the values between the each given indices of the columns.

我知道使用apply_along_axis可以解决问题,但是有更好或更优雅的解决方案吗?

I know that using apply_along_axis can do the trick, but is there a better or more elegant solution?

欢迎任何输入!

推荐答案

您可以使用

You can use broadcasting -

r = np.arange(10)[:,None]
out = ((start  <= r) & (r <= end)).astype(int)

这将创建一个形状为(10,len(start)的数组.因此,如果您需要实际填充一些已经初始化的数组filled_arr,请执行-

This would create an array of shape (10,len(start). Thus, if you need to actually fill some already initialized array filled_arr, do -

m,n = out.shape
filled_arr[:m,:n] = out

样品运行-

In [325]: start = [0,1,2,3,4,4,3,2,1,0]
     ...: end   = [9,8,7,6,5,5,6,7,8,9]
     ...: 

In [326]: r = np.arange(10)[:,None]

In [327]: ((start  <= r) & (r <= end)).astype(int)
Out[327]: 
array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 1, 0, 0, 0, 0, 0, 0, 1, 1],
       [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
       [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
       [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
       [1, 1, 0, 0, 0, 0, 0, 0, 1, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1]])

如果要将此掩码用作1s作为True的掩码,请跳过转换为int的操作.因此,(start <= r) & (r <= end)将作为掩码.

If you meant to use this as a mask with 1s as the True ones, skip the conversion to int. Thus, (start <= r) & (r <= end) would be the mask.

这篇关于填写2d numpy数组的给定索引之间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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