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

查看:22
本文介绍了如何将字符串数组转换为 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天全站免登陆