1

I got a question so I was trying to create a 3D array containing multiple 2D array with different range of values, for example I can do this:

import numpy as np

np.random.seed(1)

arr = np.random.randint(1, 10, size = (2,2)) #Random 2D array with range of values (1, 10)
arr2 = np.random.randint(11, 20, size = (2,2)) #Random 2D array with range of values (11, 20)
...

and then create the 3D array by this

newarr = np.array([arr, arr2, ...])

I try doing this:

import numpy as np

np.random.seed(1)

n = 3

aux = []

for i in range (n):
    if i == 0:
        aux.append(rng4.randint(1, 10, size = (2, 2)))
    elif i == 1:
        aux.append(rng4.randint(11, 20, size = (2, 2)))
    elif i == 2:
        aux.append(rng4.randint(21, 30, size = (2, 2)))

newarr = np.array(aux)

The output is what I want but in either case if I want another range of values I need to "add" manually a new elif to give another range, is there a way I can do this? Thank you!

1 Answer 1

1

It is a trivial loop programming exercise:

newarr = np.empty(shape=(2, 2, n))
for i in range (n):
    newarr[:,:,i] = rng4.randint(i * 10 + 1, i * 10 + 10,
                                 size = (2, 2))
Sign up to request clarification or add additional context in comments.

1 Comment

The second edit was great! This last one the output it's a 3D array with shape (2, 2, 3) not exactly what I need, but the other one help me! Thank you!

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.