pythonnumpy-random

Can't assign the "sum of np.random.normal" in a element of array


I am trying to produce random number by random.normal and take the summary of them. Then, I tried to assgin the value to each element in the array sum. I made a zero array (float type) by np.zeros and then assign the value in following way.
I attempted to utilize numpy and matlibplot.pyplot as libraries to do this.
My code:

np.random.seed(0)
sum=np.zeros(10,dtype=float)
for i in np.arange(1,11):
    X = np.random.normal(size=(10,1))
    Y=np.sum(X,axis=1)
    sum[i-1]=Y
print(sum)

When I conduct this code on Google Colab, following errors happened.

TypeError                                 Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-14-33fba8ac5d90> in <module>
      6     X = np.random.normal(size=(10,1))
      7     Y=np.sum(X,axis=1)
----> 8     sum[i-1]=Y
      9 print(sum)

ValueError: setting an array element with a sequence.

Could you please tell me how to solve this error?


Solution

  • The X array you create has a size of 10 x 1. When you do a numpy sum, the axis you select is 0-based, so you are doing a sum over the "1" dimension (the second dimension) and getting an array that is still 10 x 1 for Y.

    To fix it, you want to either set the axis to 0

    X = np.random.normal(size=(10,1))
    Y = np.sum(X,axis=0)
    

    or just omit the axis argument entirely to return a scalar instead of a size-1 array

    X = np.random.normal(size=(10,1))
    Y = np.sum(X)
    

    As a side note, using sum as a variable name is not recommended since that is the name of a built-in python method and can cause errors if you later try to use the built-in sum function - but this isn't the root of the problem here.