tattybojangler
tattybojangler

Reputation: 1073

Storing arrays in Python for loop

Let's say I have a function (called numpyarrayfunction) that outputs an array every time I run it. I would like to run the function multiple times and store the resulting arrays. Obviously, the current method that I am using to do this -

numpyarray = np.zeros((5))
for i in range(5):
    numpyarray[i] = numpyarrayfunction

generates an error message since I am trying to store an array within an array.

Eventually, what I would like to do is to take the average of the numbers that are in the arrays, and then take the average of these averages. But for the moment, it would be useful to just know how to store the arrays!

Thank you for your help!

Upvotes: 3

Views: 29766

Answers (2)

Josh Karpel
Josh Karpel

Reputation: 2145

As comments and other answers have already laid out, a good way to do this is to store the arrays being returned by numpyarrayfunction in a normal Python list.

If you want everything to be in a single numpy array (for, say, memory efficiency or computation speed), and the arrays returned by numpyarrayfunction are of a fixed length n, you could make numpyarray multidimensional:

numpyarray = np.empty((5, n))
for i in range(5):
    numpyarray[i, :] = numpyarrayfunction

Then you could do np.average(numpyarray, axis = 1) to average over the second axis, which would give you back a one-dimensional array with the average of each array you got from numpyarrayfunction. np.average(numpyarray) would be the average over all the elements, or np.average(np.average(numpyarray, axis = 1)) if you really want the average value of the averages.

More on numpy array indexing.

Upvotes: 5

rnorris
rnorris

Reputation: 2082

I initially misread what was going on inside the for loop there. The reason you're getting an error is because numpy arrays will only store numeric types by default, and numpyarrayfunction is returning a non-numeric value (from the name, probably another numpy array). If that function already returns a full numpy array, then you can do something more like this:

arrays = []
for i in range(5):
  arrays.append(numpyarrayfunction(args))

Then, you can take the average like so:

avgarray = np.zeros((len(arrays[0])))
for array in arrays:
  avgarray += array
avgarray = avgarray/len(arrays)

Upvotes: 3

Related Questions