2

Currently, I'm doing this:

myDict = {}
for in range(10):
    myDict[i] = np.ones(8)

What's I'd like at the end is a square array, where ideally I don't have to define the all the geometry up front.

I tried this:

myArray = np.array([])
for i in range(10):
    myArray[i] = np.ones(8)

but it doesn't let me index.

What's the cleanest way to do this?

cjm2671
  • 18,348
  • 31
  • 102
  • 161

3 Answers3

1

For me one of the cleanest way is to append to list and then cast to numpy array

myArray = []
for i in range(10):
      myArray.append(np.ones(8))
myArray=np.array(myArray)    

the alternative is to use numpy.zeros() to get array with wanted shape and then append values using indexing

userkk
  • 121
  • 4
1

According to this post, there's two roughly equally efficient methods:

The first, and simplest, is to append numpy arrays to a normal Python list in a loop, and call np.concatenate once at the end

Allocate a large zero array at the start (if you know the dimensions) and index into it like so:

myArray = np.zeros((10, 8))
for i in range(10):
    myArray[i,:] = np.ones(8)

The second approach may be easier to port to eventually port to C or vectorize further.

kcsquared
  • 5,244
  • 1
  • 11
  • 36
0

I'd say the most efficient approach is:

myArray = np.array([np.ones(8) for i in range(10)])
Bialomazur
  • 1,122
  • 2
  • 7
  • 18