如何在numpy中将字符串数组转换为浮点数数组? [英] How to convert an array of strings to an array of floats in numpy?

查看:1884
本文介绍了如何在numpy中将字符串数组转换为浮点数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换

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

[1.1, 2.2, 3.2]

在NumPy中?

推荐答案

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

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

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

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)

这篇关于如何在numpy中将字符串数组转换为浮点数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆