Numpy - update values โ€‹โ€‹using a slice, given the value of the array

Suppose I have the following array

import numpy as np a = np.arange(0,36).reshape((6,6)).T [[ 0 6 12 18 24 30] [ 1 7 13 19 25 31] [ 2 8 14 20 26 32] [ 3 9 15 21 27 33] [ 4 10 16 22 28 34] [ 5 11 17 23 29 35]] for i in a[:,0]: a[i][i:] = 0 [[ 0 0 0 0 0 0] [ 1 0 0 0 0 0] [ 2 8 0 0 0 0] [ 3 9 15 0 0 0] [ 4 10 16 22 0 0] [ 5 11 17 23 29 0]] 

I want to know if I can update (destroy) values โ€‹โ€‹using the "first column" as an indicator of the beginning of a slice on axis = 1 and do it without using a loop.

Note that the values โ€‹โ€‹in the "first column" will not necessarily be in order, as shown in the example, so numpy.tril is not suitable for me. I know that the value in the "first column" will never be greater than the axis size = 1.

+1
python numpy pandas
source share
1 answer

How about something like that? Notice that I shuffled the first column.

 >>> a = np.arange(0,36).reshape((6,6)).T; a[2,0] = 4; a[4,0] = 2; >>> a array([[ 0, 6, 12, 18, 24, 30], [ 1, 7, 13, 19, 25, 31], [ 4, 8, 14, 20, 26, 32], [ 3, 9, 15, 21, 27, 33], [ 2, 10, 16, 22, 28, 34], [ 5, 11, 17, 23, 29, 35]]) >>> a[np.arange(a.shape[1])[None,:] >= a[:,0,None]] = 0 >>> a array([[ 0, 0, 0, 0, 0, 0], [ 1, 0, 0, 0, 0, 0], [ 4, 8, 14, 20, 0, 0], [ 3, 9, 15, 0, 0, 0], [ 2, 10, 0, 0, 0, 0], [ 5, 11, 17, 23, 29, 0]]) 
+1
source share

All Articles