我记录了一年多的传感器数据。数据存储在十二个块中,每个块有1000列,每个〜1000000行。我已经编写了一个脚本将这些块连接到一个大文件,但是在执行的大约一半时间内,我得到了MemoryError
。 (我正在具有约70 GB可用RAM的计算机上运行此程序。)
import gc
from os import listdir
import pandas as pd
path = "/slices02/hdf/"
slices = listdir(path)
res = pd.DataFrame()
for sl in slices:
temp = pd.read_hdf(path + f"{sl}")
res = pd.concat([res, temp], sort=False, axis=1)
del temp
gc.collect()
res.fillna(method="ffill", inplace=True)
res.to_hdf(path + "sensor_data_cpl.hdf", "online", mode="w")
我也曾尝试摆弄HDFStore
,因此不必将所有数据都加载到内存中(请参阅Merging two tables with millions of rows in Python),但我无法弄清楚在我的情况下如何工作。 / p>
答案 0 :(得分:1)
当您将csv作为熊猫DataFrame读入时,该过程最终将占用所需内存的两倍(由于类型猜测和所有熊猫试图提供的自动填充东西)。
几种解决方法:
使用块。我发现您的数据已经成块,但是可能太大了,因此您可以使用chunk_size
或pandas.read_hdf
的{{1}}参数
提供pandas.read_csv
以避免类型猜测和混合类型(例如:一列具有混合类型的null值的字符串),它将与dtypes
参数一起使用。
如果这还不够,您将不得不使用分布式技术,例如pyspark,dask,modin甚至是pandarallel
答案 1 :(得分:0)
当您有大量数据时,请避免创建临时数据帧,因为它们也会占用内存。尝试一次通过:
folder = "/slices02/hdf/"
files = [os.path.join(folder, file) for file in os.listdir(folder)]
res = pd.concat((pd.read_csv(file) for file in files), sort=False)
看看它如何为您工作。