How to change entire row/column to the same value in a matrix

Question:

So I have this 3d array

x = np.zeros((9, 9))

Output:

[[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]]

and I want to change all of row x and column y into 1

Desired output:

[[0 0 0 0 0 1 0 0 0]
 [0 0 0 0 0 1 0 0 0]
 [0 0 0 0 0 1 0 0 0]
 [1 1 1 1 1 1 1 1 1]
 [0 0 0 0 0 1 0 0 0]
 [0 0 0 0 0 1 0 0 0]
 [0 0 0 0 0 1 0 0 0]
 [0 0 0 0 0 1 0 0 0]
 [0 0 0 0 0 1 0 0 0]]

I am doing this on a 3d array with Booleans instead of 0s and 1s but I assume that the answers would be the same.

Asked By: Lucas Gutheim

||

Answers:

So first index is for the rows, and second index is for the columns. In your example, if you want to set row n to 1 just do the following:

x[n] = 1

I hope this helps.

Answered By: Quentin Bracq

Use indexing with broadcasting:

x[n] = 1

# or
x[n, :] = 1

Example:

x[3] = 1

# x
array([[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],
       [1, 1, 1, 1, 1, 1, 1, 1, 1],
       [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]])

For the second dimension:

x[:, n] = 1

Generic way for the last dimension:

x[..., n] = 1
Answered By: mozway