1

I have a multidimensional numpy array of dtype object, which was filled with other arrays. As an example, here is a code reproducing that behavior:

arr = np.empty((3,4,2,1), dtype=object)
for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        for k in range(arr.shape[2]):
            for l in range(arr.shape[3]):
                arr[i, j, k, l] = np.random.random(10)

Since all the inside arrays have the same size, I would like in this example to "incorporate" the last level into the array and make it an array of size (3,4,2,1,10). I cannot really change the above code, so what I am looking for is a clean way (few lines, possibly without for loops) to generate this new array once created.

Thank you.

2 Answers 2

1

If I understood well your problem you could use random.random_sample() which should give the same result:

arr = np.random.random_sample((3, 4, 2, 1, 10))

After edit the solution is arr = np.array(arr.tolist())

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

4 Comments

Thank you for your answer. The code to create this loop is locked and I do not have access to it, I just have access to the created array. Therefore, I am looking for a way to modify the already existing array instead of creating a new one in a more clever way.
Oh okay, I'll try to think of something else then!
np.array(arr.tolist()) should be good !
It works exactly how it should, thank you! Can you edit your answer so that I can flag it as the correct answer?
0

Just by adding a new for loop :

arr = np.empty((3,4,2,1,10), dtype=object)
for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        for k in range(arr.shape[2]):
            for l in range(arr.shape[3]):
                for m in range(arr.shape[4]):
                    arr[i, j, k, l, m] = np.random.randint(10) 

However, you can one line this code with an optimized numpy function, every random function from numpy has a size parameter to build a array with random number with a particular shape :

arr = np.random.random((3,4,2,1,10))

EDIT :

You can flatten the array, replace every single number by a 1D array of length 10 and then reshape it to your desired shape :

import numpy as np
arr = np.empty((3,4,2,1), dtype=object)
for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        for k in range(arr.shape[2]):
            for l in range(arr.shape[3]):
                arr[i, j, k, l] = np.random.randint(10)
   
flat_arr = arr.flatten()
for i in range(len(flat_arr)):
    flat_arr[i] = np.random.randint(0, high=10, size=(10))
res_arr = flat_arr.reshape((3,4,2,1))

2 Comments

Thank you for your answer. Unfortunately, I cannot change the loop. I can only modify it once created.
I've edited my post according to your constraint

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.