我怎么做np.保存为ndarray子类工作?

2024-04-26 15:11:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够将数组子类保存到npy文件中,并在以后恢复结果。在

比如:

>>> class MyArray(np.ndarray): pass
>>> data = MyArray(np.arange(10))
>>> np.save('fname', data)
>>> data2 = np.load('fname')
>>> assert isinstance(data2, MyArray)  # raises AssertionError

the docs说(强调我的):

The format explicitly does not need to:

  • [...]
  • Fully handle arbitrary subclasses of numpy.ndarray. Subclasses will be accepted for writing, but only the array data will be written out. A regular numpy.ndarray object will be created upon reading the file. The API can be used to build a format for a particular subclass, but that is out of scope for the general NPY format.

那么,是否可以使上述代码不引发断言错误?在


Tags: ofthetonumpyformatfordatanp
1条回答
网友
1楼 · 发布于 2024-04-26 15:11:55

我看不到np.save处理数组子类的证据。在

我试图用它保存一个np.matrix,但得到了一个ndarray。在

我试图保存一个np.ma数组,但得到了一个错误

NotImplementedError: MaskedArray.tofile() not implemented yet.

保存是由np.lib.npyio.format.write_array完成的

^{pr2}$

如果dtype是对象,则使用pickle.dump(array, fp ...)

否则它会array.tofile(fp)。^{cd9>处理缓冲区。在

我认为一个数组的pickle.dump最终使用了np.save,但我不记得是如何触发的。在

例如,pickle一个数组,并加载它:

In [657]: f=open('test','wb')
In [658]: pickle.Pickler(f).dump(x)
In [659]: f.close()
In [660]: np.load('test')
In [664]: f=open('test','rb')
In [665]: pickle.load(f)

这个pickle转储/加载序列适用于测试np.manp.matrix和{}的情况。所以这可能是你自己的子类需要探索的方向。在

numpy和{}上搜索时,我找到了{a1}。答案包括一个自定义的.__reduce__.__setstate__。在

相关问题 更多 >