gpt4 book ai didi

python - 使用 numpy.loadtxt 加载包含 float 和字符串的文本文件

转载 作者:IT老高 更新时间:2023-10-28 20:30:26 25 4
gpt4 key购买 nike

我有一个文本文件,data.txt,其中包含:

5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
5.8,2.7,4.1,1.0,Iris-versicolor
6.2,2.2,4.5,1.5,Iris-versicolor
6.4,3.1,5.5,1.8,Iris-virginica
6.0,3.0,4.8,1.8,Iris-virginica

如何使用 numpy.loadtxt() 加载这些数据,以便在加载后得到一个 NumPy 数组,例如 [['5.1' '3.5' '1.4' '0.2' '鸢尾花'] ['4.9' '3.0' '1.4' '0.2' '鸢尾花'] ...]?

我试过了

np.loadtxt(open("data.txt"), 'r',
dtype={
'names': (
'sepal length', 'sepal width', 'petal length',
'petal width', 'label'),
'formats': (
np.float, np.float, np.float, np.float, np.str)},
delimiter= ',', skiprows=0)

最佳答案

如果您使用 np.genfromtxt ,您可以指定 dtype=None,这将告诉 genfromtxt 智能猜测每一列的 dtype。最方便的是,它减轻了您指定字符串列所需字节数的负担。 (通过指定例如 np.str 来省略字节数是行不通的。)

In [58]: np.genfromtxt('data.txt', delimiter=',', dtype=None, names=('sepal length', 'sepal width', 'petal length', 'petal width', 'label'))
Out[58]:
array([(5.1, 3.5, 1.4, 0.2, 'Iris-setosa'),
(4.9, 3.0, 1.4, 0.2, 'Iris-setosa'),
(5.8, 2.7, 4.1, 1.0, 'Iris-versicolor'),
(6.2, 2.2, 4.5, 1.5, 'Iris-versicolor'),
(6.4, 3.1, 5.5, 1.8, 'Iris-virginica'),
(6.0, 3.0, 4.8, 1.8, 'Iris-virginica')],
dtype=[('sepal_length', '<f8'), ('sepal_width', '<f8'), ('petal_length', '<f8'), ('petal_width', '<f8'), ('label', 'S15')])

如果您确实想使用 np.loadtxt,然后以最少的更改来修复您的代码,您可以使用:

np.loadtxt("data.txt",
dtype={'names': ('sepal length', 'sepal width', 'petal length', 'petal width', 'label'),
'formats': (np.float, np.float, np.float, np.float, '|S15')},
delimiter=',', skiprows=0)

主要区别只是将 np.str 更改为 |S15(一个 15 字节的字符串)。

还要注意open("data.txt"), 'r' 应该是 open("data.txt", 'r')。但是由于 np.loadtxt 可以接受文件名,所以你根本不需要使用 open

关于python - 使用 numpy.loadtxt 加载包含 float 和字符串的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23546349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com