I have a numpy array which I want to convert from an object to complex. If I take that array as dtype string and convert it, there is no problem:
In[22]: bane
Out[22]: array(['1.000027337501943-7.331085223659654E-6j',
'1.0023086995640738-1.8228368353755985E-4j',
'-0.017014515914781394-0.2820013864855318j'],
dtype='|S41')
In [23]: bane.astype(dtype=complex)
Out[23]:
array([ 1.00002734 -7.33108522e-06j, 1.00230870 -1.82283684e-04j,
-0.01701452 -2.82001386e-01j])
But when it is dtype object and I try to convert it, I get an error that a float is required. Why is this?
In [24]: bane.astype(dtype=object)
Out[24]:
array(['1.000027337501943-7.331085223659654E-6j',
'1.0023086995640738-1.8228368353755985E-4j',
'-0.017014515914781394-0.2820013864855318j'], dtype=object)
In [25]: _.astype(dtype=complex)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-f5d89c8cc46c> in <module>()
----> 1 _.astype(dtype=complex)
TypeError: a float is required
To convert it, I use two calls to the astype method which seems clumsy:
bane_obj
Out[27]:
array(['1.000027337501943-7.331085223659654E-6j',
'1.0023086995640738-1.8228368353755985E-4j',
'-0.017014515914781394-0.2820013864855318j'], dtype=object)
In [28]: bane_obj.astype(dtype=str).astype(dtype=complex)
Out[28]:
array([ 1.00002734 -7.33108522e-06j, 1.00230870 -1.82283684e-04j,
-0.01701452 -2.82001386e-01j])
numpy
code the conversion is taking place. The string to complex conversion has probably worked for a long time, while the development of object dtypes is newer and ongoing. What is generating this sort of object array? – hpaulj Mar 14 at 1:09dtype=np.object
could contain literally any kind of Python object, so I think it's understandable that the numpy developeres have not bothered to implement every conceivable type conversion rule here. Chaining together an.astype(np.str).astype(np.complex)
actually seems seem like a quite reasonable workaround for what must be a very uncommon use-case. The real question in my mind is why you're having to deal with annp.object
array containing complex numbers in string format in the first place! – ali_m Mar 14 at 18:05DataFrame
were already strings to begin with. – ali_m Mar 14 at 23:28