Home > OS >  Transform numpy array to incorporate inside arrays
Transform numpy array to incorporate inside arrays

Time:08-02

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.

CodePudding user response:

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())

CodePudding user response:

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))
  • Related