## 问题：如何将字符串数组转换为numpy中的浮点数组？

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

``[1.1, 2.2, 3.2]``

How to convert

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

to

``````[1.1, 2.2, 3.2]
``````

in NumPy?

## 回答 0

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

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

## 回答 1

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

You can use this as well

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

## 回答 2

``````import numpy as np
a = ["1.1", "2.2", "3.2"]
b = np.asarray(a, dtype=np.float64, order='C')``````

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

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

Another option might be numpy.asarray:

``````import numpy as np
a = ["1.1", "2.2", "3.2"]
b = np.asarray(a, dtype=np.float64, order='C')
``````

For Python 2*:

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

resulting in:

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

## 回答 3

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

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.