2 回答

TA贡献1719条经验 获得超6个赞
经典的方式是这样的:
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 np
textfile = np.loadtxt("test.txt")
print(textfile[0][0])
更新 2: IndexError:数组的索引太多
import csv
import numpy as np #missing
data = [] #create a empty array
with 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 np
textfile = np.loadtxt("test.txt")
print(textfile[:,0])

TA贡献1802条经验 获得超6个赞
逐行读取文件并将每个文件保存在列表中相当于制作一个字符串列表:
In [98]: txt='''0 1.2 2 3.1
...: 20 21.2 22 23
...: 30 31 32 33.01'''.splitlines()
In [99]: txt
Out[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]:
[['0', '1.2', '2', '3.1'],
['20', '21.2', '22', '23'],
['30', '31', '32', '33.01']]
In [102]: np.array([line.split() for line in txt], dtype=float)
Out[102]:
array([[ 0. , 1.2 , 2. , 3.1 ],
[20. , 21.2 , 22. , 23. ],
[30. , 31. , 32. , 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]:
array([[ 0. , 1.2 , 2. , 3.1 ],
[20. , 21.2 , 22. , 23. ],
[30. , 31. , 32. , 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]: col1
Out[111]: array([ 1.2, 21.2, 31. ])
In [112]: col1.reshape(3,1)
Out[112]:
array([[ 1.2],
[21.2],
[31. ]])
让我们逐行构建数组:
In [116]: data = []
In [117]: for line in txt:
...: arr = np.array(line.split(), dtype=float)
...: print(arr.shape)
...: data.append(arr)
...: print(data)
...:
...:
(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. , 31. , 32. , 33.01])]
data 现在是数组列表:
In [118]: data
Out[118]:
[array([0. , 1.2, 2. , 3.1]),
array([20. , 21.2, 22. , 23. ]),
array([30. , 31. , 32. , 33.01])]
将这些数组连接成一个数组:
In [119]: np.array(data)
Out[119]:
array([[ 0. , 1.2 , 2. , 3.1 ],
[20. , 21.2 , 22. , 23. ],
[30. , 31. , 32. , 33.01]])
(这样做后检查形状。如果单个数组的形状不同,则结果将不是二维数组;而是一维数组数组,更接近于原始数组列表。)
添加回答
举报