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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3877209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:08:29  来源:igfitidea点击:

How to convert an array of strings to an array of floats in numpy?

pythonnumpy

提问by Meh

How to convert

如何转换

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

to

[1.1, 2.2, 3.2]

in NumPy?

在 NumPy 中?

采纳答案by Joe Kington

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 liston the mapreturn value if you use map, since mapreturns an iterator now.)

好吧,如果您将数据作为列表读取,只需执行np.array(map(float, list_of_strings))(或等效地,使用列表理解)。(在Python 3,你需要调用listmap,如果你使用的返回值map,因为map现在返回一个迭代器)。

However, if it's already a numpy array of strings, there's a better way. Use astype().

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

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

回答by pradeep bisht

You can use this as well

你也可以使用这个

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

回答by Thomio

If you have (or create) a single string, you can use np.fromstring:

如果您有(或创建)单个字符串,则可以使用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.

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

回答by Herpes Free Engineer

Another option might be numpy.asarray:

另一种选择可能是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*:

对于 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'>