使用numpy.loadtx加载包含float和string的文本文件

2024-04-30 01:26:22 发布

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

我有一个文本文件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' 'Iris-setosa'] ['4.9' '3.0' '1.4' '0.2' 'Iris-setosa'] ...]

我试过了

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)

Tags: numpytxtirisdatanpfloatwidthlength
2条回答

似乎把数字和文字放在一起给你带来了很多麻烦——如果你最终决定把它们分开,我的解决办法是:

values = np.loadtxt('data', delimiter=',', usecols=[0,1,2,3])
labels = np.loadtxt('data', delimiter=',', usecols=[4])

如果使用np.genfromtxt,则可以指定dtype=None,这将告诉genfromtxt智能地猜测每个列的数据类型。最方便的是,它免除了指定string列所需字节数的麻烦。(通过指定例如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

相关问题 更多 >