5

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
  • 109
  • 2
  • 4
  • 13
  • What is your expected output? – Georgy Jan 05 '18 at 15:30
  • Possible duplicate of [Numpy: cartesian product of x and y array points into single array of 2D points](https://stackoverflow.com/questions/11144513/numpy-cartesian-product-of-x-and-y-array-points-into-single-array-of-2d-points) – Georgy Jan 05 '18 at 16:08
  • Do you understand what that 2nd try did? Even it didn't produce what you want, it's important to understand that expression. – hpaulj Jan 05 '18 at 18:21

3 Answers3

2

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
  • 80
  • 1
  • 8
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,163
  • 1
  • 10
  • 26
0

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?