Converting a numpy string array to float: Bizarre?

So this should be very simple, but for some reason, nothing I do to convert an array of strings to an array of floats doesn't work.

I have an array of two columns, for example:

Name Value Bob 4.56 Sam 5.22 Amy 1.22 

I try this:

 for row in myarray[1:,]: row[1]=float(row[1]) 

And this:

 for row in myarray[1:,]: row[1]=row[1].astype(1) 

And this:

 myarray[1:,1] = map(float, myarray[1:,1]) 

And they all do something, but when I check twice:

 type(myarray[9,1]) 

I get

 <type> 'numpy.string_'> 
+4
source share
2 answers

Numpy arrays must have one dtype if it is not structured. Since you have multiple lines in an array, they should all be lines.

If you want to have a complex dtype , you can do this:

 import numpy as np a = np.array([('Bob','4.56'), ('Sam','5.22'),('Amy', '1.22')], dtype = [('name','S3'),('val',float)]) 

Note that a now a 1d structured array , where each element is a dtype type dtype .

You can access the values ​​using their field name:

 In [21]: a = np.array([('Bob','4.56'), ('Sam','5.22'),('Amy', '1.22')], ...: dtype = [('name','S3'),('val',float)]) In [22]: a Out[22]: array([('Bob', 4.56), ('Sam', 5.22), ('Amy', 1.22)], dtype=[('name', 'S3'), ('val', '<f8')]) In [23]: a['val'] Out[23]: array([ 4.56, 5.22, 1.22]) In [24]: a['name'] Out[24]: array(['Bob', 'Sam', 'Amy'], dtype='|S3') 
+6
source

The type of objects in the numpy array is determined when this array is initialized. If you want to change this later, you must specify the array, not the objects inside this array.

 myNewArray = myArray.asType(float) 

Note. Perhaps overlaying down, for a downward transition you need the astype method. For more information see:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html http://docs.scipy.org/doc/numpy/reference/generated/numpy.chararray.astype.html

0
source

All Articles