【问题标题】:How to handle large files in python?如何在python中处理大文件?
【发布时间】:2015-08-19 18:37:32
【问题描述】:

我是 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的对应代码是什么?或者,还有其他解决方案吗?

【问题讨论】:

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


    【解决方案1】:

    如果你打算使用 numpy,那么我建议使用ndarrays,而不是列表。您可以使用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 中有更详细的描述。

    【讨论】:

      猜你喜欢
      • 2014-05-22
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2012-08-17
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多