如何连接许多numpy数组?

时间:2017-04-13 13:37:40

标签: python arrays numpy

我试图连接许多numpy数组,我把每个数组放在一个文件中,实际上我有很多文件的问题,内存不能支持创建一个大数组Data_Array = np.zeros((1000000,7000)),在哪里我将把我的所有文件。所以,我在这个问题Combining NumPy arrays中发现我可以使用np.concatenate

file1= np.load('file1_Path.npy')
file2= np.load('file2_Path.npy')
file3= np.load('file3_Path.npy')
file4= np.load('file4_Path.npy')
dataArray=np.concatenate((file1, file2, file3, file4), axis=0)
test= dataArray.shape
print(test)
print (dataArray)
print (dataArray.shape)
plt.plot(dataArray.T)
plt.show() 

这种方式给了我一个非常好的结果,但现在,我需要将file1, file2, file3, file4替换为我的文件夹的路径:

import matplotlib.pyplot as plt 
import numpy as np
import glob
import os, sys
fpath ="Path_To_Big_File"
npyfilespath =r'Path_To_Many_Numpy_Files'  
os.chdir(npyfilespath)
npfiles= glob.glob("*.npy")
npfiles.sort()
for i,npfile in enumerate(npfiles):
    dataArray=np.concatenate(npfile, axis=0)
np.save(fpath, all_arrays)

它给了我这个错误:

np.concatenate(npfile, axis=0)

ValueError: zero-dimensional arrays cannot be concatenated 

请您帮助我使这个方法np.concatenate有效吗?

1 个答案:

答案 0 :(得分:0)

如果您希望使用大型数组,只需使用np.memmap而不是将数据加载到内存中。 memmap的优点是数据在必要时始终保存到磁盘。例如,您可以通过以下方式创建内存映射数组:

import numpy as np

a=np.memmap('myFile',dtype=np.int,mode='w+',shape=(1000000,8000))

然后您可以使用' a'作为一个普通的numpy数组。 那么限制是你的硬盘!这会在硬盘上创建一个您可以稍后阅读的文件。您只需将模式更改为' r'并从数组中读取数据。 有关memmap的更多信息:https://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html

为了从形状的npy文件(1,8000)填充该数组,只需写:

for i,npFile in enumerate(npfFiles):
  a[i,:]=np.load(npFile)
a.flush()

flush方法确保所有内容都写在磁盘上