简体   繁体   English

如何使用numpy.savez将带有子数组的数组保存到单独的.npy文件中

[英]How to use numpy.savez to save array with subarrays into separate .npy files

I have just recently started using numpy and was wondering some things. 我刚刚开始使用numpy并且想知道一些事情。 I have a numpy array that looks like this after splitting it: 分裂后我有一个看起来像这样的numpy数组:

[array([1,2,3]),
array([4,5,6])]

I want to use numpy.savez to save the main array into the .npz archive with each subarray in its own .npy file. 我想使用numpy.savez将主数组保存到.npz存档中,每个子数组都放在自己的.npy文件中。

I thought using this: 我想用这个:

numpy.savez('dataFile', mainArray)

would work but it only creates the archive with a single .npy file called arr_0.npy. 可以工作,但它只使用一个名为arr_0.npy的.npy文件创建存档。

Is there a way to do something like this? 有没有办法做这样的事情? and if so is there a way so that I can use any array with any number of subarrays with that method. 如果是这样,我可以使用任何数组的子阵列与该方法。 To get these arrays I am reading from a .bin file that could contain any number of elements that would split into any number of arrays. 为了获得这些数组,我从一个.bin文件中读取,该文件可能包含任意数量的元素,这些元素将分成任意数量的数组。 This is why I'm having a hard time. 这就是我遇到困难的原因。

Is there a way to add files to an already created .npz file? 有没有办法将文件添加到已创建的.npz文件中?

After doing more research I came upon the answer to my main question. 经过更多的研究后,我找到了主要问题的答案。 I found out that you can use the *arg to loop through the list of arrays to add them. 我发现你可以使用* arg循环遍历数组列表来添加它们。

I changed the code to 我将代码更改为

numpy.savez('test', *[mainArray[x] for x in rang(len(mainArray))])

This gave me the solution i was looking for. 这给了我正在寻找的解决方案。 Thank you for your help. 谢谢您的帮助。

If you want to save the subarrays in your main array, then you probably need to use save manually, ie 如果要将子阵列保存在主阵列中,则可能需要手动使用save ,即

mainArray = [np.array([1,2,3]), np.array([4,5,6])]
for i in range(len(mainArray)):
    np.save('dataFile_%i'%i, mainArray[i] )

Or you can use savez to save subarrays separately and load them later. 或者您可以使用savez单独保存子savez并稍后加载它们。

mainArray = [np.array([1,2,3]), np.array([4,5,6])]
np.savez('dataFile', mainArray[0], mainArray[1])

npzfile = np.load('dataFile.npz')
npzfile['arr_0']
npzfile['arr_1']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM