I am using a package that is fetching values from a csv file for me. If I print out the result I get ['0.12' '0.23']
. I checked the type, which is <class 'numpy.ndarray'>
I want to convert it to a numpy array like [0.12, 0.23]
. I tried np.asarray(variabel)
but that did not resolve the problem.
Solution
import numpy as np
array = array.astype(np.float)
# If you are just initializing array you can do this
ar= np.array(your_list,dtype=np.float)
It might help to know how the csv
was read. But for what ever reason it appears to have created a numpy
array with a string dtype
:
In [106]: data = np.array(['0.12', '0.23'])
In [107]: data
Out[107]: array(['0.12', '0.23'], dtype='<U4')
In [108]: print(data)
['0.12' '0.23']
The str
formatting of such an array omits the comma, the repr
display keeps it.
A list equivalent also displays with comma:
In [109]: data.tolist()
Out[109]: ['0.12', '0.23']
We call this a numpy array, but technically it is of class numpy.ndarray
In [110]: type(data)
Out[110]: numpy.ndarray
It can be converted to an array of floats with:
In [111]: data.astype(float)
Out[111]: array([0.12, 0.23])
It is still a ndarray
, just the dtype
is different. You may need to read more in the numpy
docs about dtype
.
The error:
If I want to calculate with it it gives me an error TypeError: only size-1 arrays can be converted to Python scalars
has a different source. data
has 2 elements. You don't show the code that generates this error, but often we see this in plotting calls. The parameter is supposed to be a single number (often an integer), where as your array, even with a numeric dtype
) is two numbers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.