如何在numpy中将字符串数组转换为浮点数组?

2024-03-29 09:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

如何转换

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

[1.1, 2.2, 3.2]

在纽比?


3条回答

好吧,如果您是以列表的形式读取中的数据,那么只需np.array(map(float, list_of_strings))(或者等效地,使用列表理解)。(在Python 3中,如果使用map,则需要对map返回值调用list,因为map现在返回迭代器。)

但是,如果它已经是一个numpy字符串数组,那么有更好的方法。使用astype()

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

你也可以用这个

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

如果有(或创建)单个字符串,则可以使用np.fromstring

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

注意,x = ','.join(x)将x数组转换为字符串'1.1, 2.2, 3.2'。如果从txt文件中读取一行,则每一行都已经是一个字符串。

相关问题 更多 >