Create a matrix with x zeros and the rest

I would like to be able to quickly create a matrix in which the first few (variable number) cells in the row are 0 and the rest are units.

Suppose we need a 3x4 matrix.

I created the matrix first like everyone else:

ones = np.ones([4,3])

Then imagine that we have an array that declares how many leading zeros are:

arr = np.array([2,1,3,0]) # first row has 2 zeroes, second row 1 zero, etc

Required Result:

array([[0, 0, 1],
       [0, 1, 1],
       [0, 0, 0],
       [1, 1, 1]])

Obviously, this can also be done in the reverse order, but I would consider an approach where 1 is the default value and the zeros will be replaced.

What would be the best way to avoid some dumb loop?

+4
source share
2 answers

. n - . len(arr).

In [29]: n = 5

In [30]: arr = np.array([1, 2, 3, 0, 3])

In [31]: (np.arange(n) >= arr[:, np.newaxis]).astype(int)
Out[31]: 
array([[0, 1, 1, 1, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [1, 1, 1, 1, 1],
       [0, 0, 0, 1, 1]])

, . -, m n-m? np.arange [0, 1,..., n-1] `:

In [35]: n
Out[35]: 5

In [36]: np.arange(n)
Out[36]: array([0, 1, 2, 3, 4])

m:

In [37]: m = 2

In [38]: np.arange(n) >= m
Out[38]: array([False, False,  True,  True,  True], dtype=bool)

; m False, - True. , 0s 1s:

In [39]: (np.arange(n) >= m).astype(int)
Out[39]: array([0, 0, 1, 1, 1])

m ( arr), broadcasting; .

, arr[:, np.newaxis] :

In [40]: arr
Out[40]: array([1, 2, 3, 0, 3])

In [41]: arr[:, np.newaxis]
Out[41]: 
array([[1],
       [2],
       [3],
       [0],
       [3]])

arr[:, np.newaxis] arr 2- (5, 1). (arr.reshape(-1, 1) .) , np.arange(n) (1- n), :

In [42]: np.arange(n) >= arr[:, np.newaxis]
Out[42]: 
array([[False,  True,  True,  True,  True],
       [False, False,  True,  True,  True],
       [False, False, False,  True,  True],
       [ True,  True,  True,  True,  True],
       [False, False, False,  True,  True]], dtype=bool)

@RogerFan , , >=.

int :

In [43]: (np.arange(n) >= arr[:, np.newaxis]).astype(int)
Out[43]: 
array([[0, 1, 1, 1, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [1, 1, 1, 1, 1],
       [0, 0, 0, 1, 1]])
+6

, ( mask_indices), :

>>> n = 3
>>> zeros = [2, 1, 3, 0]
>>> numpy.array([[0] * zeros[i] + [1]*(n - zeros[i]) for i in range(len(zeros))])
array([[0, 0, 1],
       [0, 1, 1],
       [0, 0, 0],
       [1, 1, 1]])
>>>

: , [0] [1], .

+1

All Articles