[英]Slicing 2d array from values in 1d array onwards
Having an arbitrary 2d array, say of zeros, and an array of indices: 具有一个任意的二维数组,例如零,以及一个索引数组:
z = np.zeros((5,5))
ix = np.array([1,4,2,3,0])
How could I add a 1
from the columns specified by a 1d array onwards, in order to obtain: 如何从1d数组指定的列开始添加
1
,以获得:
array([[0, 1, 1, 1, 1],
[0, 0, 0, 0, 1],
[0, 0, 1, 1, 1],
[0, 0, 0, 1, 1],
[1, 1, 1, 1, 1]])
I have not been able to find a simple way of doing so using numpy
. 我无法找到一种使用
numpy
的简单方法。
One way would be - 一种方法是-
In [50]: ncols = 5
In [51]: (ix[:,None] <= np.arange(ncols)).view('i1')
Out[51]:
array([[0, 1, 1, 1, 1],
[0, 0, 0, 0, 1],
[0, 0, 1, 1, 1],
[0, 0, 0, 1, 1],
[1, 1, 1, 1, 1]], dtype=int8)
If you have to add to an existing array z
- 如果必须添加到现有数组
z
z += (ix[:,None] <= np.arange(ncols))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.