猿问

以数组形式读取.txt文件并获取Python中指定索引的值

我有一个大的 .txt 数据文件,格式类似于(所有数字):


0 1.2 2 3.1

20 21.2 22 23

30 31 32 33.01

例如,我想将此矩阵的第二列导入到变量中。这是我写的代码。首先,我将所有矩阵作为字符串导入到一个变量中,并将其转换为一个数组,在此处命名为“data”。然后,想要访问 data[1][1] 或 data[:][1] 但是,它给出了以下错误


IndexError:数组的索引太多


知道错误是什么或完成工作的有效方法是什么?非常感谢


import csv

data=[]

with open('test.txt', 'r') as f:

  reader = csv.reader(f, delimiter=' ', skipinitialspace=True)

   for line in f:

      if line.endswith('\n'):

          line=line[:-1] 


      data=np.asarray(line)  

      print(data)


慕的地10843
浏览 244回答 2
2回答

慕侠2389804

经典的方式是这样的:with open('test.txt') as txt:    array2d = [[float(digit) for digit in line.split()] for line in txt]print(array2d[:][0])我认为性能明智的 numpy 应该更快:/更新:对于 numpy,您可以使用该loadtxt功能。import numpy as nptextfile = np.loadtxt("test.txt")print(textfile[0][0])更新 2: IndexError:数组的索引太多import csv import numpy as np #missingdata = [] #create a empty arraywith open('test.txt', 'r') as f: #opens the textfile in readmode and stores in f    reader = csv.reader(f, delimiter=' ', skipinitialspace=True) #creating a reader instance but never used    for line in f: #loop for each line in file            if line.endswith('\n'): #if the file ends with a new line                line = line[:-1] #set to last line            data = np.asarray(line) # here is one bigger mistake you overwrite the data array with just one line            print(data) #print out this one line所以你只能得到存储在数据数组中的最后一行。注意:没有办法确定一行的长度,所以你必须读入文件。你不能跳到这个特定的行,有一些方法可以提高性能,所以请告诉我们你的文件有多大或预期的速度是什么样的。更新3:获取列import numpy as nptextfile = np.loadtxt("test.txt")print(textfile[:,0])

呼啦一阵风

逐行读取文件并将每个文件保存在列表中相当于制作一个字符串列表:In [98]: txt='''0 1.2 2 3.1&nbsp; &nbsp; ...: 20 21.2 22 23&nbsp; &nbsp; ...: 30 31 32 33.01'''.splitlines()In [99]: txtOut[99]: ['0 1.2 2 3.1', '20 21.2 22 23', '30 31 32 33.01']从中制作一个数组只会产生一个一维字符串数组。不能索引为二维数值数组:In [100]: np.array(txt)Out[100]: array(['0 1.2 2 3.1', '20 21.2 22 23', '30 31 32 33.01'], dtype='<U14')如果您首先将行拆分为子字符串:In [101]: [line.split() for line in txt]Out[101]:&nbsp;[['0', '1.2', '2', '3.1'],&nbsp;['20', '21.2', '22', '23'],&nbsp;['30', '31', '32', '33.01']]In [102]: np.array([line.split() for line in txt], dtype=float)Out[102]:&nbsp;array([[ 0.&nbsp; ,&nbsp; 1.2 ,&nbsp; 2.&nbsp; ,&nbsp; 3.1 ],&nbsp; &nbsp; &nbsp; &nbsp;[20.&nbsp; , 21.2 , 22.&nbsp; , 23.&nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp;[30.&nbsp; , 31.&nbsp; , 32.&nbsp; , 33.01]])这是一个二维数组。我们可以从该数组中选择一列。但请注意,结果是一个一维数组:In [104]: np.array([line.split() for line in txt], dtype=float)[:,1]Out[104]: array([ 1.2, 21.2, 31. ])不要担心这是一个“行”或“列”。我们可以将形状更改为 (1,3) 或 (3,1),但在大多数情况下numpy,一维形状 (3,) 也一样好。numpy有很好的csv装载机(实际上有两个):In [105]: np.genfromtxt(txt)Out[105]:&nbsp;array([[ 0.&nbsp; ,&nbsp; 1.2 ,&nbsp; 2.&nbsp; ,&nbsp; 3.1 ],&nbsp; &nbsp; &nbsp; &nbsp;[20.&nbsp; , 21.2 , 22.&nbsp; , 23.&nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp;[30.&nbsp; , 31.&nbsp; , 32.&nbsp; , 33.01]])通常genfromtxt给定一个文件名,但它可以正常工作任何输入行的内容,例如txt列表。如果你只对一列感兴趣,你可以用usecols(有更多可能的参数)来指定它:In [106]: np.genfromtxt(txt, usecols=1)Out[106]: array([ 1.2, 21.2, 31. ])genfromtxt不是最快的装载机。如果您需要更高的速度,我们通常建议pandas加载。pandas对引号和缺失值有一些更巧妙的处理,但您似乎不需要在这里。 numpy用户似乎并不怎么使用该csv模块;它可能只是不需要。如果你真的必须有一个column vector,这里是如何使用reshape:In [110]: col1 = np.genfromtxt(txt, usecols=1)In [111]: col1Out[111]: array([ 1.2, 21.2, 31. ])In [112]: col1.reshape(3,1)Out[112]:&nbsp;array([[ 1.2],&nbsp; &nbsp; &nbsp; &nbsp;[21.2],&nbsp; &nbsp; &nbsp; &nbsp;[31. ]])让我们逐行构建数组:In [116]: data = []In [117]: for line in txt:&nbsp; &nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;arr = np.array(line.split(), dtype=float)&nbsp; &nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;print(arr.shape)&nbsp; &nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;data.append(arr)&nbsp; &nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;print(data)&nbsp; &nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;(4,)[array([0. , 1.2, 2. , 3.1])](4,)[array([0. , 1.2, 2. , 3.1]), array([20. , 21.2, 22. , 23. ])](4,)[array([0. , 1.2, 2. , 3.1]), array([20. , 21.2, 22. , 23. ]), array([30.&nbsp; , 31.&nbsp; , 32.&nbsp; , 33.01])]data 现在是数组列表:In [118]: dataOut[118]:&nbsp;[array([0. , 1.2, 2. , 3.1]),&nbsp;array([20. , 21.2, 22. , 23. ]),&nbsp;array([30.&nbsp; , 31.&nbsp; , 32.&nbsp; , 33.01])]将这些数组连接成一个数组:In [119]: np.array(data)Out[119]:&nbsp;array([[ 0.&nbsp; ,&nbsp; 1.2 ,&nbsp; 2.&nbsp; ,&nbsp; 3.1 ],&nbsp; &nbsp; &nbsp; &nbsp;[20.&nbsp; , 21.2 , 22.&nbsp; , 23.&nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp;[30.&nbsp; , 31.&nbsp; , 32.&nbsp; , 33.01]])(这样做后检查形状。如果单个数组的形状不同,则结果将不是二维数组;而是一维数组数组,更接近于原始数组列表。)
随时随地看视频慕课网APP

相关分类

Python
我要回答