Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting numpy string array to float: Bizarre?

So, this should be a really straightforward thing but for whatever reason, nothing I'm doing to convert an array of strings to an array of floats is working.

I have a two column array, like so:

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 seem to do something, but when I double check:

type(myarray[9,1])

I get

<type> 'numpy.string_'>
like image 547
Olga Mu Avatar asked Mar 31 '13 22:03

Olga Mu


People also ask

How do you convert a string array to a float in Python?

The most Pythonic way to convert a list of strings to a list of floats is to use the list comprehension floats = [float(x) for x in strings] . It iterates over all elements in the list and converts each list element x to a float value using the float(x) built-in function.

Can NumPy array store strings and floats?

numpy arrays support only one type of data in the array. Changing the float to str is not a good idea as it will only result in values very close to the original value. Try using pandas, it support multiple data types in single column.

Can we convert string to float data type in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number.

How is it possible to cast an array into different data types like float?

Method 1 : Here, we can utilize the astype() function that is offered by NumPy. This function creates another copy of the initial array with the specified data type, float in this case, and we can then assign this copy to a specific identifier, which is convertedArray.


1 Answers

Numpy arrays must have one dtype unless it is structured. Since you have some strings in the array, they must all be strings.

If you wish to have a complex dtype, you may do so:

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

Note that a is now a 1d structured array, where each element is a tuple of 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')
like image 140
askewchan Avatar answered Sep 27 '22 22:09

askewchan