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

PythonNumpy

Python Problem Overview


How to convert

["1.1", "2.2", "3.2"]

to

[1.1, 2.2, 3.2]

in NumPy?

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

Another option might be numpy.asarray:

import numpy as np
a = ["1.1", "2.2", "3.2"]
b = np.asarray(a, dtype=float)

print(a, type(a), type(a[0]))
print(b, type(b), type(b[0]))

resulting in:

['1.1', '2.2', '3.2'] <class 'list'> <class 'str'>
[1.1 2.2 3.2] <class 'numpy.ndarray'> <class 'numpy.float64'>

Solution 3 - Python

If you have (or create) a single string, you can use np.fromstring:

import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )

Note, x = ','.join(x) transforms the x array to string '1.1, 2.2, 3.2'. If you read a line from a txt file, each line will be already a string.

Solution 4 - Python

You can use this as well

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

Solution 5 - Python

You can use np.array() with dtype = float:

import numpy as np

x = ["1.1", "2.2", "3.2"]
y = np.array(x,dtype=float)

Output:

array([1.1, 2.2, 3.2])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMehView Question on Stackoverflow
Solution 1 - PythonJoe KingtonView Answer on Stackoverflow
Solution 2 - PythonHerpes Free EngineerView Answer on Stackoverflow
Solution 3 - PythonThomioView Answer on Stackoverflow
Solution 4 - Pythonpradeep bishtView Answer on Stackoverflow
Solution 5 - PythonMayank SoniView Answer on Stackoverflow