6

Is there a better way to create a multidimensional array in numpy using a FOR loop, rather than creating a list? This is the only method I could come up with:

import numpy as np

a = []
for x in range(1,6):
    for y in range(1,6):
        a.append([x,y])
a = np.array(a)
print(f'Type(a) = {type(a)}.  a = {a}')

EDIT: I tried doing something like this:

a = np.array([range(1,6),range(1,6)])
a.shape = (5,2)
print(f'Type(a) = {type(a)}.  a = {a}')

however, the output is not the same. I'm sure I'm missing something basic.

need_java
  • 127
  • 2
  • 4
  • 13

4 Answers4

3

You could preallocate the array before assigning the respective values:

a = np.empty(shape=(25, 2), dtype=int)
for x in range(1, 6):
    for y in range(1, 6):
        index = (x-1)*5+(y-1)
        a[index] = x, y
aasoo
  • 100
  • 1
  • 8
1

Did you had a look at numpy.ndindex? This could do the trick:

a = np.ndindex(6,6)

You could have some more information on Is there a Python equivalent of range(n) for multidimensional ranges?

1

You can replace double for-loop with itertools.product.

from itertools import product 
import numpy as np

np.array(list(product(range(1,6), range(1,6))))

For me creating array from list looks natural here. Don't know how to skip them in that case.

koPytok
  • 3,453
  • 1
  • 14
  • 29
0

Sometimes it is difficult to predict the total element number and shape at stage of selecting array elements due to some if statement inside a loop.

In this case, put all selected elements in flat array:

a = np.empty((0), int)
for x in range(1,6):  # x-coordinate
    for y in range(1,6):  # y-coordinate
        if x!=y:  # `if` statement
            a = np.append(a, [x, y])

Then, given the lengths of one array dimension (in our case there are 2 coordinates) one can use -1 for the unknown dimension:

a.shape = (-1, 2)
a
array([[1, 2],
       [1, 3],
       [1, 4],
       [1, 5],
       [2, 1],
       [2, 3],
       [2, 4],
       [2, 5],
       [3, 1],
       [3, 2],
       [3, 4],
       [3, 5],
       [4, 1],
       [4, 2],
       [4, 3],
       [4, 5],
       [5, 1],
       [5, 2],
       [5, 3],
       [5, 4]])
Yerbol Sapar
  • 31
  • 1
  • 8