如何解决如何从1000个CSV文件中创建一个比我的RAM大得多的Numpy数组?
我要添加1000个CSV文件,并创建一个大的numpy数组。问题是numpy数组比我的RAM大得多。有没有一种方法可以在不将整个阵列都放入RAM的情况下一次写入一点磁盘?
还有没有办法一次只从磁盘读取阵列的特定部分?
解决方法
在处理numpy和大数组时,有几种方法取决于您需要处理的数据。
最简单的答案是使用更少的数据。如果您的数据包含大量重复元素,则经常可以使用scipy中的sparse array,因为这两个库已高度集成。
另一个答案(IMO:您的问题的正确解决方案)是使用memory mapped array。这将使numpy仅在需要时才加载ram所需的部分,并将其余部分保留在磁盘上。包含数据的文件可以是使用多种方法创建的简单二进制文件,但是可以处理此问题的内置python模块是struct
。追加更多数据就像在追加模式下打开文件并写入更多字节的数据一样简单。确保在每次将更多数据写入文件时都重新创建对内存映射数组的所有引用,以使信息新鲜。
最后就是压缩。 Numpy可以使用savez_compressed
压缩数组,然后可以使用numpy.load
打开它。重要的是,压缩的numpy文件无法映射到内存,而必须完全加载到内存中。一次加载一列也许可以使您处于阈值以下,但这可以类似地应用于其他减少内存使用的方法。 Numpy的内置压缩技术只会节省磁盘空间,而不会节省内存。可能还存在其他执行某种流式压缩的库,但这超出了我的回答范围。
以下是将二进制数据放入文件,然后将其作为内存映射数组打开的示例:
import numpy as np
#open a file for data of a single column
with open('column_data.dat','wb') as f:
#for 1024 "csv files"
for _ in range(1024):
csv_data = np.random.rand(1024).astype(np.float) #represents one column of data
f.write(csv_data.tobytes())
#open the array as a memory-mapped file
column_mmap = np.memmap('column_data.dat',dtype=np.float)
#read some data
print(np.mean(column_mmap[0:1024]))
#write some data
column_mmap[0:512] = .5
#deletion closes the memory-mapped file and flush changes to disk.
# del isn't specifically needed as python will garbage collect objects no
# longer accessable. If for example you intend to read the entire array,# you will need to periodically make sure the array gets deleted and re-created
# or the entire thing will end up in memory again. This could be done with a
# function that loads and operates on part of the array,then when the function
# returns and the memory-mapped array local to the function goes out of scope,# it will be garbage collected. Calling such a function would not cause a
# build-up of memory usage.
del column_mmap
#write some more data to the array (not while the mmap is open)
with open('column_data.dat','ab') as f:
#for 1024 "csv files"
for _ in range(1024):
csv_data = np.random.rand(1024).astype(np.float) #represents one column of data
f.write(csv_data.tobytes())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。