Search code examples
pythonnumpyruntime-error

TypeError: numpy.float64 object is not iterable


Error I got when running the Python script: How to solved TypeError: 'numpy.float64' object is not iterable

Code Used

arr = np.array([[3, 4, 5], [5, 6, 7], [2, 3, 4]])


total = sum(sum(arr))

mean = sum(sum(arr))/(3*3)

for i in arr :
    vr= i - mean
    for med in vr**2 :             
        print(sum(med))

Solution

  • med is a number (float) and hence you cannot take the sum of it (its sum is itself). Also, the main point of using Numpy is to avoid loop and do array calculations at once. Something like this:

    arr = np.array([[3, 4, 5], [5, 6, 7], [2, 3, 4]])
    
    total = arr.sum()
    mean = total/arr.size #equivalent of total=arr.mean()
    vr = ((arr - mean)**2).sum() #equivalent of var=np.var(arr)*arr.size