1

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.

1
  • 1
    Why does it need to be efficient? Commented Sep 26, 2021 at 17:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.