【问题标题】:Efficient way of reading large txt file in python在python中读取大txt文件的有效方法
【发布时间】:2019-11-14 15:25:52
【问题描述】:

我正在尝试打开一个包含 4605227 行 (305 MB) 的 txt 文件

我之前的做法是:

data = np.loadtxt('file.txt', delimiter='\t', dtype=str, skiprows=1)

df = pd.DataFrame(data, columns=["a", "b", "c", "d", "e", "f", "g", "h", "i"])

df = df.astype(dtype={"a": "int64", "h": "int64", "i": "int64"})

但它用尽了大部分可用内存 ~10GB 并且没有完成。 有没有更快的方法来读取这个 txt 文件并创建一个 pandas 数据框?

谢谢!

编辑: 现在解决了,谢谢。为什么 np.loadtxtx() 这么慢?

【问题讨论】:

  • df = pd.read_csv9('file.txt', delimiter='\t', dtype=str, skiprows=1) 会发生什么?
  • stackoverflow.com/questions/25962114/…,标签问题中的6gb文件
  • 同意@QuangHoang 305 MB 应该可以直接用 pandas 读取

标签: python python-3.x pandas numpy


【解决方案1】:

您可以直接将其作为 Pandas DataFrame 读取,而不是使用 numpy 读取。例如,使用 pandas.read_csv 函数,例如:

df = pd.read_csv('file.txt', delimiter='\t', usecols=["a", "b", "c", "d", "e", "f", "g", "h", "i"])

【讨论】:

  • 谢谢,我没有意识到 read_csv 允许制表符分隔。但是我收到此错误:TypeError: parser_f() got an unexpected keyword argument 'columns'
  • 因为该参数不称为columns,而是usecols(如Matt 链接的文档中所示)
【解决方案2】:

方法一:

您可以按块读取文件,此外还有一个缓冲区大小,您可以在 readline 中提及并且您可以读取。

inputFile = open('inputTextFile','r')
buffer_line = inputFile.readlines(BUFFERSIZE)
while buffer_line:
    #logic goes here

方法二:

您也可以使用 nmap 模块,下面是解释用法的链接。

导入地图

with open("hello.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)
    # read content via standard file methods
    print(mm.readline())  # prints b"Hello Python!\n"
    # read content via slice notation
    print(mm[:5])  # prints b"Hello"
    # update content using slice notation;
    # note that new content must have same size
    mm[6:] = b" world!\n"
    # ... and read again using standard file methods
    mm.seek(0)
    print(mm.readline())  # prints b"Hello  world!\n"
    # close the map
    mm.close()

https://docs.python.org/3/library/mmap.html

【讨论】:

    【解决方案3】:

    您可以将其作为 Pandas DataFrame 直接读取。例如

    import pandas as pd
    pd.read_csv(path)
    

    如果你想更快地阅读,可以使用 modin:

    import modin.pandas as pd
    pd.read_csv(path)
    

    https://github.com/modin-project/modin

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      相关资源
      最近更新 更多