填写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.