Numpy: TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'

Created on 11 Jul 2018  ·  2Comments  ·  Source: numpy/numpy

Using OS X 10.12 and using Version: 1.15.0rc2 of numpy. I'm seeing this error:

  File "temp.py", line 103, in computeMACD
    emaslow = ExpMovingAverage(x, slow)
  File "temp.py", line 93, in ExpMovingAverage
    a =  np.convolve(values, weights, mode='full')[:len(values)]
  File "/Users/x/xx/graph/lib/python3.6/site-packages/numpy/core/numeric.py", line 1045, in convolve
    return multiarray.correlate(a, v[::-1], mode)
TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'

I'm seeing this error when using this widely available code:

 def ExpMovingAverage(values, window):
     weights = np.exp(np.linspace(-1., 0., window))
     weights /= weights.sum()
     a =  np.convolve(values, weights, mode='full')[:len(values)]
     a[:window] = a[window]
     return a

My values are real stock prices, ['93.89', '89.89', '87.17', '90.57', '88.92', '90.46'...]. Window is 26. I'm not sure why so many people reference the above code that is not working for me. Any ideas what is wrong here?

Most helpful comment

Your data are strings. They should be numbers.

 ['93.89', '89.89', '87.17', '90.57', '88.92', '90.46'...]

should be

 [93.89, 89.89, 87.17, 90.57, 88.92, 90.46]

This is verified using

v = ['93.89', '89.89', '87.17', '90.57', '88.92', '90.46']*30
ExpMovingAverage(v,10)

TypeError: Cannot cast array data from dtype('float64') to 
dtype('<U32') according to the rule 'safe'

and

ExpMovingAverage(list(map(float,v)),10)

array([89.6938941 , 89.6938941 , 89.6938941 , 89.6938941 ...

All 2 comments

Your data are strings. They should be numbers.

 ['93.89', '89.89', '87.17', '90.57', '88.92', '90.46'...]

should be

 [93.89, 89.89, 87.17, 90.57, 88.92, 90.46]

This is verified using

v = ['93.89', '89.89', '87.17', '90.57', '88.92', '90.46']*30
ExpMovingAverage(v,10)

TypeError: Cannot cast array data from dtype('float64') to 
dtype('<U32') according to the rule 'safe'

and

ExpMovingAverage(list(map(float,v)),10)

array([89.6938941 , 89.6938941 , 89.6938941 , 89.6938941 ...

Thank you. This fixed my issue

Was this page helpful?
0 / 5 - 0 ratings