【问题标题】:Python: load data with comma as decimal separatorPython:使用逗号作为小数分隔符加载数据
【发布时间】:2017-05-26 04:22:21
【问题描述】:

我有一些非常大的 txt 文件(大约 1.5 GB),我想将它们作为数组加载到 Python 中。问题是在此数据中,逗号用作小数分隔符。对于较小的文件,我想出了这个解决方案:

import numpy as np
data= np.loadtxt(file, dtype=np.str, delimiter='\t', skiprows=1)
        data = np.char.replace(data, ',', '.')
        data = np.char.replace(data, '\'', '')
        data = np.char.replace(data, 'b', '').astype(np.float64)

但是对于大文件,Python 会遇到内存错误。还有其他更节省内存的方法来加载这些数据吗?

【问题讨论】:

标签: python


【解决方案1】:

np.loadtxt(file, dtype=np.str, delimiter='\t', skiprows=1) 的问题在于它使用 python 对象(字符串)而不是float64,这样内存效率非常低。你可以使用 pandas read_table

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html#pandas.read_table

读取您的文件并设置 decimal=',' 以更改默认行为。这将允许无缝读取字符串并将其转换为浮点数。加载熊猫数据框后,使用 df.values 获取一个 numpy 数组。 如果它仍然对您的内存太大,请使用块

http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking

如果仍然没有成功,请尝试使用 np.float32 格式,它可以进一步减少内存占用。

【讨论】:

    【解决方案2】:

    您应该尝试自己解析它,对每一行进行迭代(因此隐式使用不会将所有文件读入内存的生成器)。 此外,对于这种大小的数据,我会使用 python 标准 array 库,它使用与 c 数组类似的内存。也就是说,内存中的一个值紧挨着另一个(numpy 数组在内存使用方面也非常有效)。

    import array
    
    def convert(s): 
      # The function that converts the string to float
      s = s.strip().replace(',', '.')
      return float(s)
    
    data = array.array('d') #an array of type double (float of 64 bits)
    
    with open(filename, 'r') as f:
        for l in f: 
            strnumbers = l.split('\t')
            data.extend( (convert(s) for s in strnumbers if s!='') )
            #A generator expression here. 
    

    我确信可以编写类似的代码(具有类似的内存占用),将 array.array 替换为 numpy.array,特别是如果您需要二维数组。

    【讨论】:

      【解决方案3】:

      您的 1.5 GB 文件可能需要超过 1.5 GB 的 RAM

      试着把它分成几行

      更多信息:

      http://stupidpythonideas.blogspot.ch/2014/09/why-does-my-100mb-file-take-2gb-of.html#!/2014/09/why-does-my-100mb-file-take-2gb-of.html

      【讨论】:

        猜你喜欢
        • 2014-07-16
        • 1970-01-01
        • 1970-01-01
        • 2020-10-14
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 1970-01-01
        • 2016-02-10
        相关资源
        最近更新 更多