简体   繁体   English

如何将 append arrays 转换为现有的.npy 文件

[英]How to append arrays to an existing .npy file

The goal of this program is to append a small data array of size [1,3] for each function call to an existing.npy file.该程序的目标是 append 为每个 function 调用现有的.npy 文件提供一个大小为 [1,3] 的小数据数组。 This.npy file will be used for subsequent analysis in some other program.这个.npy 文件将用于其他一些程序中的后续分析。 What's important is that it's populated with all the data arrays that were collected.重要的是它填充了收集到的所有数据 arrays。

So here's the general overview of what I'm trying to accomplish (all within a single class):因此,这是我要完成的工作的总体概述(全部在一个班级中):

  1. Load an existing.npy file as an ndarray that may or may not be empty将现有的.npy 文件加载为可能为空或不为空的 ndarray

  2. Create a function that appends an array to this existing file whenever called创建一个 function,在调用时将一个数组附加到这个现有文件

I've ran into several issues trying to accomplish this: Firstly, using np.load() doesn't work for an empty array, regardless of whether allow_pickles=True or allow_pickles=False.我在尝试完成此操作时遇到了几个问题:首先,使用 np.load() 不适用于空数组,无论是 allow_pickles=True 还是 allow_pickles=False。 Secondly, every time I try to make a function that achieves this, the data is never appended, but rather overwritten as far as I can tell.其次,每次我尝试制作实现此目标的 function 时,数据都不会被附加,而是据我所知被覆盖。

I have used different combinations of np.load() and np.save() for ndarrays.我为 ndarrays 使用了 np.load() 和 np.save() 的不同组合。 I've also tried append() for lists and then converting them into ndarrays.我还尝试了 append() 列表,然后将它们转换为 ndarrays。 Here's some sample code that I've tested in a Jupyter Notebook:这是我在 Jupyter Notebook 中测试过的一些示例代码:

import numpy as np

def appendArrayToFile(filename, array):
    np.save(filename,array)
    np.load(filename)
    return

appendArrayToFile('probedZdata.npy', np.array([1,2,3]))
appendArrayToFile('probedZdata.npy', np.array([4,5,6]))

print(np.load('probedZdata.npy'))

Instead of returning all of the arrays, it only returns the last one:它不返回所有 arrays,而是只返回最后一个:

[4, 5, 6]

How can I format this function such that I add an array to this file each time it's called?如何格式化此 function 以便每次调用该文件时都向该文件添加一个数组? The size of this file is mostly irrelevant as I would only be storing up to around 50, 3x1 sized arrays.该文件的大小几乎无关紧要,因为我最多只能存储大约 50 个 3x1 大小的 arrays。

You are overwriting the file.您正在覆盖文件。 You're not adding.你不加。

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

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