如何在python中处理大文件?

时间:2015-06-04 23:28:46

标签: arrays list file python-3.x numpy

我是python的新手。我问了另一个问题How to arrange three lists in such a way that the sum of corresponding elements if greater then appear first?现在问题出现了:

我正在处理一个大文本文件,其中有419040行和6列包含浮点数。其中我采用前3列来生成这三个列表。所以我实际使用的列表每个都有419040个条目。当我运行python代码将三列提取到三个列表时,python shell没有响应,我怀疑为此有大量条目,我使用了这段代码:

file=open("file_location","r")
a=[]
b=[]
c=[]
for lines in file:
    x=lines.split(" ")
    a.append(float(x[0]))
    b.append(float(x[1]))
    c.append(float(x[2]))

注意:对于小文件,此代码运行正常。 为了避免这个问题,我使用以下代码:

import numpy as np
a = []
b = []
c = []
a,b,c = np.genfromtxt('file_location',usecols = [0,1,2], unpack=True)

因此,当我运行上一个问题的答案中给出的代码时,同样的问题正在发生。那么使用numpy的相应代码是什么?或者,任何其他解决方案?

1 个答案:

答案 0 :(得分:1)

如果你要使用numpy,那么我建议使用ndarray s而不是列表。您可以使用loadtxt,因为您不必处理丢失的数据。我认为它会更快。

a = np.loadtxt('file.txt', usecols=(0, 1, 2))

a现在是一个二维数组,存储为np.ndarray数据类型。它应该看起来像:

>>> a
array([[  1,  20, 400],
       [  5,  30, 500],
       [  3,  50, 100],
       [  2,  40, 300],
       [  4,  10, 200]])

但是,您现在需要重新执行上一个问题中的操作,但使用的是numpy数组而不是列表。这可以很容易地实现:

>>> b = a.sum(axis=1)
>>> b
Out[21]: array([535, 421, 342, 214, 153])
>>> i = np.argsort(b)[::-1]
>>> i
Out[26]: array([0, 1, 2, 3, 4])
>>> a[i, :]
Out[27]: 
array([[  5,  30, 500],
       [  1,  20, 400],
       [  2,  40, 300],
       [  4,  10, 200],
       [  3,  50, 100]])

更详细地描述了所涉及的步骤here