How to Convert an Array of Strings to an Array of Floats in Numpy

How to convert an array of strings to an array of floats in numpy?

Well, if you're reading the data in as a list, just do np.array(map(float, list_of_strings)) (or equivalently, use a list comprehension). (In Python 3, you'll need to call list on the map return value if you use map, since map returns an iterator now.)

However, if it's already a numpy array of strings, there's a better way. Use astype().

import numpy as np
x = np.array(['1.1', '2.2', '3.3'])
y = x.astype(np.float)

Convert a list of strings to array of floats numpy Python

you can use:

x = map(lambda x: float(x), str.split(<line>, ',\t')

To describe this:

  1. split the line of string by tab (or whatever)
  2. feed the subsequent array into a map function, which applies the function in the first argument to every item in the second
  3. the first argument to the map function is a lambda function which simply takes a string in and returns a float

Convert the Strings and Integers of a NumPy Array into Floats

How about this:

import numpy as np

arr = np.array([10, '1.870,00'])

def custom_parse(x):
if isinstance(x, str):
new_str = x.replace('.', '').replace(',', '.')
return float(new_str)
else:
return float(x)

new_array = np.array(list(map(custom_parse, arr)))

print(new_array)

It's tricky because your string representation of a number isn't easy to cast as a float, so you'll probably have to parse it manually

converting a numpy string array to numpy float array

I think the issue is that in the line y = np.asarray(x, dtype=np.float32), the variable x is an array of length one containing multiple space-separated substrings that can each be converted to a float. However, the string itself cannot be converted to float.

You can try replacing that line with this:

y = np.asarray(x[0].split(), dtype=np.float32)

Input

{'A': array(['5.19494526e-02  1.17357977e-01  5.19494526e-02'], dtype='<U46')}

Output

{'A': array([0.05194945, 0.11735798, 0.05194945], dtype=float32)}

How to convert a 2D array of strings and numbers to a numpy float array?

Using genfromtext as suggested here is not possible with multi-dimensional arrays. On the other hand, you can apply genfromtext to each row of the 2D array using apply_along_axis as described here:

import numpy as np

x = np.array([[1, 2, 'tom'], [4, 'Manu', 6]])
print(np.apply_along_axis(np.genfromtxt, 1 ,x))

Which will give:

[[ 1.  2. nan]
[ 4. nan 6.]]

Convert list of strings to numpy array of floats

Just go the direct route. Remove the brackets, split on the spaces and convert to float before sending the result to numpy.array:

np.array([[float(i) for i in j[1:-1].split()] for j in A])

Test Code:

import numpy as np
A = ['[1 2 3 4 5 6 7]','[8 9 10 11 12 13 14]']
print(np.array([[float(i) for i in j[1:-1].split()] for j in A]))

Results:

[[  1.   2.   3.   4.   5.   6.   7.]
[ 8. 9. 10. 11. 12. 13. 14.]]

Converting a string array to floats with python

Your string looks like a python list, consider using eval() or pd.eval() to directly convert the string to a list before creating a dataframe.

pd.eval('[8.25, 13.6, 18.8, 24.0]')

Converting numpy string array to float: Bizarre?

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')


Related Topics



Leave a reply



Submit