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


Question

How to convert

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

to

[1.1, 2.2, 3.2]

in NumPy?

1
101
6/12/2018 10:19:49 AM

Accepted Answer

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)
150
6/30/2017 4:59:04 PM

You can use this as well

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon