Home > Enterprise >  Efficient way to fill a 1D numpy array of variable length with random numbers in different ranges
Efficient way to fill a 1D numpy array of variable length with random numbers in different ranges

Time:09-27

I need to fill a length n 1D numpy array with random numbers from the ranges [1,2,...,n], [2,3,...,n], [3,4,...,n], ..., [n-1,n] and [n] respectively. I am looking for a vectorize solution to this problem. Thanks very much in advance.

CodePudding user response:

You could use numpy.random.randint, for this:

import numpy as np

n = 10
res = np.random.randint(np.arange(0, n), n)
print(res)

Output

[3 3 2 6 6 7 6 8 9 9]

From the documentation:

Generate a 1 by 3 array with 3 different lower bounds

np.random.randint([1, 5, 7], 10)
array([9, 8, 7]) # random

The more up-to-date alternative is to use integers:

import numpy as np

n = 10
rng = np.random.default_rng()
res = rng.integers(np.arange(0, n), n)

print(res)

Note: The examples above start from 0, choose the intervals that suit best your problem.

  • Related