简体   繁体   中英

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:

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 .

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 += (ix[:,None] <= np.arange(ncols))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM