[英]Fill in values between given indices of 2d numpy array
Given a numpy array, 给定一个numpy数组,
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]]
And for a set of indices, eg: 对于一组指数,例如:
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. 我的目标是“选择”列的每个给定索引之间的所有值。
I know that using apply_along_axis
can do the trick, but is there a better or more elegant solution? 我知道使用apply_along_axis
可以解决问题,但是有更好或更优雅的解决方案吗?
Any inputs are welcomed!! 欢迎任何投入!!
You can use broadcasting
- 你可以使用broadcasting
-
r = np.arange(10)[:,None]
out = ((start <= r) & (r <= end)).astype(int)
This would create an array of shape (10,len(start)
. Thus, if you need to actually fill some already initialized array filled_arr
, do - 这将创建一个形状数组(10,len(start)
。因此,如果你需要实际填充一些已初始化的数组filled_arr
,请执行 -
m,n = out.shape
filled_arr[:m,:n] = out
Sample run - 样品运行 -
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]])
If you meant to use this as a mask with 1s
as the True
ones, skip the conversion to int
. 如果您打算将此作为掩码使用1s
作为True
,请跳过转换为int
。 Thus, (start <= r) & (r <= end)
would be the mask. 因此, (start <= r) & (r <= end)
将是掩码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.