Python 正在将txt文件数据加载到numpy数组/出现错误
我正在尝试将txt文件数据加载到numpy数组中。它抛出以下错误:Python 正在将txt文件数据加载到numpy数组/出现错误,python,arrays,numpy,text,Python,Arrays,Numpy,Text,我正在尝试将txt文件数据加载到numpy数组中。它抛出以下错误: ValueError: could not convert string to float: '6,50,36' 我试图上传到数组中的txt文件如下(这是完整文件): 我做了一些研究,认为“np.loadtxt()”是将此txt加载到数组中的一个简单解决方案,因此这是我迄今为止尝试的: import numpy as np from numpy import loadtxt f = open('DataNumbers.txt
ValueError: could not convert string to float: '6,50,36'
我试图上传到数组中的txt文件如下(这是完整文件):
我做了一些研究,认为“np.loadtxt()”是将此txt加载到数组中的一个简单解决方案,因此这是我迄今为止尝试的:
import numpy as np
from numpy import loadtxt
f = open('DataNumbers.txt','r')
data_array = float(np.loadtxt(f)) # I thought using 'float' would work for this issue
我想知道这不起作用的原因是否是因为该文件在txt文件的第一行36后面包含两个空格
如何从加载到数组中的txt文件中获取此数据并消除此错误
谢谢你的帮助
In [498]: f = open('stack53641413.txt','r')
In [501]: alist = [[int(x) for x in line.split(',')] for line in f]
In [502]: alist
Out[502]:
[[6, 50, 36],
[2, 0, 1, 3, 0, 1],
[1, 2, 1, 2, 1, 2],
[2, 1, 2, 1, 0, 1],
[0, 2, 0, 2, 2, 3],
[0, 3, 3, 3, 1, 4],
[2, 3, 2, 3, 1, 3]]
In [504]: np.array(alist[1:])
Out[504]:
array([[2, 0, 1, 3, 0, 1],
[1, 2, 1, 2, 1, 2],
[2, 1, 2, 1, 0, 1],
[0, 2, 0, 2, 2, 3],
[0, 3, 3, 3, 1, 4],
[2, 3, 2, 3, 1, 3]])
您如何处理alist[0]
是您的事
loadtxt
跳过困难的第一行:
In [507]: np.loadtxt(f, dtype='int', delimiter=',',skiprows=1)
Out[507]:
array([[2, 0, 1, 3, 0, 1],
[1, 2, 1, 2, 1, 2],
[2, 1, 2, 1, 0, 1],
[0, 2, 0, 2, 2, 3],
[0, 3, 3, 3, 1, 4],
[2, 3, 2, 3, 1, 3]])
查看
loadtxt
(或genfromtxt
)的文档。注意分隔符
,使用COLS
,数据类型
,和skipheader
(或其任何名称)。初始线路短路将导致故障。你可能想跳过它。记住,结果应该是一个列数一致的2d数组。loadtxt
使用时,每行返回一个字符串float
仅适用于表示一个数字的一个字符串。您可以自己一行一行地读取文件,但随后必须在分隔符上拆分文件,将结果字符串列表转换为数字列表,并将其合并。这不难。第一行有3列,其余的有6列!你想跳过第一排吗??!!是的@KhalilAlHooti,这不是我的原始文件
In [507]: np.loadtxt(f, dtype='int', delimiter=',',skiprows=1)
Out[507]:
array([[2, 0, 1, 3, 0, 1],
[1, 2, 1, 2, 1, 2],
[2, 1, 2, 1, 0, 1],
[0, 2, 0, 2, 2, 3],
[0, 3, 3, 3, 1, 4],
[2, 3, 2, 3, 1, 3]])