0

how to conver a numpy nd array to a list of (n-1)d withou loop

assume we have a array 3d numpy array

 arr3d = np.random.randint(1, 100, size=7 * 3 * 6).reshape((7, 3, 6))

with loop (slow solution):

arr_what_i_want= []
for i in range(7):
    arr2d = arr3d[i]
    arr_what_i_want.append([arr2d])
    pass

how to get the "arr_what_i_want" without loop?

guzuomuse
  • 11
  • 4
  • `arr.tolist()` is the only compiled method for making a list from an array. Everything else involves a python level iteration. After all elements of a list are references to python objects. – hpaulj Oct 19 '21 at 06:22

2 Answers2

0

Make a list of the first dimension:

arr_what_i_want = [*arr3d]

or

arr_what_i_want = list(arr3d)
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

Let me take a guess at this:

arr3d = np.random.randint(1, 100, size=7 * 3 * 6).reshape((7, 3, 6))
arr2d = arr3d.reshape(arr3d.shape[0], (arr3d.shape[1]*arr3d.shape[2]))
print(arr2d)

Output:
[[68 29 30 22 13 93 93 91 8 82 34 48 41 83 72 75 25 38]
[12 43 4 76 21 1 26 26 84 10 76 42 49 66 40 22 31 13]
[64 84 83 28 33 30 97 11 95 37 61 42 18 31 3 16 67 86]
[94 73 2 26 23 94 69 49 40 39 60 79 84 39 57 94 76 16]
[83 5 65 23 42 49 48 84 82 55 12 69 19 18 51 4 49 81]
[48 56 73 51 63 88 31 57 12 92 6 25 98 46 67 38 73 60]
[42 8 47 13 76 40 71 54 99 58 47 93 2 56 38 9 73 36]]

Gedas Miksenas
  • 959
  • 7
  • 15