gpt4 book ai didi

Python:以逗号作为小数点分隔符加载数据

转载 作者:行者123 更新时间:2023-12-02 01:18:10 24 4
gpt4 key购买 nike

enter image description here我有一些非常大的 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 标准 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 ,特别是如果你需要一个二维数组。

关于Python:以逗号作为小数点分隔符加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41589830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com