Skip to content
Advertisement

Create array with random numbers that contains only 1 non zero value in a row

Like in a topic, I want to generate an random array of shape (2x2x2) where each row can contains only one non zero value like

x = [[[1 0]
      [0 3]]

      [7 0]
      [0 0]]]

not

x = [[[1 6]
      [0 3]]

      [7 4]
      [2 3]]]

I tried with typical way:

np.random.seed(42)
x = np.random.randint(0, 10, (2, 2, 2))

Advertisement

Answer

I would suggest doing the following to achieve your result. You want an array filled with all zeros, except for one element in each row.

  1. So create an array with all zeros.
  2. For each row pick a random index.
  3. Set the value at the random index to a random value.

Here’s a snippet that does it for you:

import random
import numpy as np

# init array with 0's
x = np.zeros((2, 2, 2))

# loop over all rows
for i in range(len(x)):
    for j in range(len(x[i])):
        # pick a row index that will not be 0
        rand_row_index = random.randint(0, 1)
        # set that index to a random value
        x[i][j][rand_row_index] = random.randint(0, 10)
Advertisement