pd shah
pd shah

Reputation: 1406

numpy optimize way(remove loops)

I want to use this code on very huge array. this code take long time to execute and it is not efficient. is there any way to remove loop and convert this code to optimum way?

>>> import numpy as np
>>> x=np.random.randint(10, size=(4,5,3))
>>> x
array([[[3, 2, 6],
        [4, 6, 6],
        [3, 7, 9],
        [6, 4, 2],
        [9, 0, 1]],

       [[9, 0, 4],
        [1, 8, 9],
        [6, 8, 1],
        [9, 4, 5],
        [1, 5, 2]],

       [[6, 1, 6],
        [1, 8, 8],
        [3, 8, 3],
        [7, 1, 0],
        [7, 7, 0]],

       [[5, 6, 6],
        [8, 3, 1],
        [0, 5, 4],
        [6, 1, 2],
        [5, 6, 1]]])
>>> y=[]
>>> for i in range(x.shape[1]):
    for j in range(x.shape[2]):
        y.append(x[:, i, j].tolist())


>>> y
[[3, 9, 6, 5], [2, 0, 1, 6], [6, 4, 6, 6], [4, 1, 1, 8], [6, 8, 8, 3], [6, 9, 8, 1], [3, 6, 3, 0], [7, 8, 8, 5], [9, 1, 3, 4], [6, 9, 7, 6], [4, 4, 1, 1], [2, 5, 0, 2], [9, 1, 7, 5], [0, 5, 7, 6], [1, 2, 0, 1]]

Upvotes: 0

Views: 97

Answers (2)

Dorian
Dorian

Reputation: 1488

yes, either use np.reshape(x, shape) or try it with np.ndarray.flatten(x, order='F') (F for Fortran style, column first, according to your example).

read the documentation to find out which parameters fit the best. IMHO, I think ndarray.flatten is the better and more elegant option for you here. However, depending on your exact wanted solution, you might have to reshape the array first.

Upvotes: 2

Divakar
Divakar

Reputation: 221574

You could permute axes with np.transpose and then reshape to 2D -

y = x.transpose(1,2,0).reshape(-1,x.shape[0])

Append with .tolist() for list output.

Upvotes: 2

Related Questions