【发布时间】:2019-09-27 12:11:31
【问题描述】:
我正在尝试将 4.47GB 的 CSV 文件加载到内存映射的 NumPy 数组中。在具有 85GB RAM 的 GCP 机器上,大约需要 .这样做需要 500 秒,结果是 1.03GB 数组。
问题在于它在上传文件到阵列的过程中消耗了多达 26GB 的 RAM。有没有办法修改以下代码,以便在上传过程中消耗更少的 RAM(如果可能的话,时间)?
import tempfile, numpy as np
def create_memmap_ndarray_from_csv(csv_file): # load int8 csv file to int8 memory-mapped numpy array
with open(csv_file, "r") as f:
rows = len(f.readlines())
with open(csv_file, "r") as f:
cols = len(f.readline().split(','))
memmap_file = tempfile.NamedTemporaryFile(prefix='ndarray', suffix='.memmap')
arr_int8_mm = np.memmap(memmap_file, dtype=np.int8, mode='w+', shape=(rows,cols))
arr_int8_mm = np.loadtxt(csv_file, dtype=np.int8, delimiter=',')
return arr_int8_mm
【问题讨论】:
-
使用
loadtxt加载csv 后,使用np.save(filename, array)将文件存储为二进制.npy文件。然后您可以使用np.load(filename, mmap_mode='r')加载文件,您将拥有内存消耗最少的 memmap 数组。 -
您似乎不了解 Python 变量赋值。使用
A = fn(),首先运行fn(),创建它需要的任何东西。结果被分配给A(并丢弃之前分配给A的任何东西)。在您的代码中arr_int8_mm是loadtxt创建的数组,而不是memmap。 -
loadtxt逐行读取文件,收集列表列表(实际上是您的readlines和split)。最后,它从结果中创建一个数组。可以想象,您自己的阅读器可以一次拆分一行,并将结果数组写入memmap的一行。