如何转换
["1.1", "2.2", "3.2"]
Run Code Online (Sandbox Code Playgroud)
至
[1.1, 2.2, 3.2]
Run Code Online (Sandbox Code Playgroud)
在NumPy?
Joe*_*ton 156
好吧,如果您以列表形式阅读数据,只需np.array(map(float, list_of_strings))(或等效地使用列表推导).(在Python 3,你需要调用list的map,如果你使用的返回值map,因为map现在返回一个迭代器).
但是,如果它已经是一个numpy字符串数组,那么有一种更好的方法.使用astype().
import numpy as np
x = np.array(['1.1', '2.2', '3.3'])
y = x.astype(np.float)
Run Code Online (Sandbox Code Playgroud)
另一种选择可能是numpy.asarray:
import numpy as np
a = ["1.1", "2.2", "3.2"]
b = np.asarray(a, dtype=np.float64, order='C')
Run Code Online (Sandbox Code Playgroud)
对于 Python 2*:
print a, type(a), type(a[0])
print b, type(b), type(b[0])
Run Code Online (Sandbox Code Playgroud)
导致:
['1.1', '2.2', '3.2'] <type 'list'> <type 'str'>
[1.1 2.2 3.2] <type 'numpy.ndarray'> <type 'numpy.float64'>
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以np.array()使用dtype = float:
import numpy as np
x = ["1.1", "2.2", "3.2"]
y = np.array(x,dtype=float)
Run Code Online (Sandbox Code Playgroud)
输出:
array([1.1, 2.2, 3.2])
Run Code Online (Sandbox Code Playgroud)
小智 5
你也可以使用这个
import numpy as np
x=np.array(['1.1', '2.2', '3.3'])
x=np.asfarray(x,float)
Run Code Online (Sandbox Code Playgroud)
如果您有(或创建)单个字符串,则可以使用np.fromstring:
import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )
Run Code Online (Sandbox Code Playgroud)
注意,x = ','.join(x)将 x 数组转换为 string '1.1, 2.2, 3.2'。如果您从 txt 文件中读取一行,则每一行都将是一个字符串。