本文介绍了子类化 numpy 标量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 numpy.complex64 进行子类化,以便利用 numpy 存储数据的方式(连续的、交替的实部和虚部),但使用我自己的 __add__, __sub__, ... 例程.

I'm trying to subclass numpy.complex64 in order to make use of the way numpy stores the data, (contiguous, alternating real and imaginary part) but use my own __add__, __sub__, ... routines.

我的问题是,当我制作一个 numpy.ndarray 时,设置 dtype=mysubclass,我得到一个 numpy.ndarraydtype='numpy.complex64' 代替,这导致 numpy 不使用我自己的函数进行加法、减法等.

My problem is that when I make a numpy.ndarray, setting dtype=mysubclass, I get a numpy.ndarray with dtype='numpy.complex64' in stead, which results in numpy not using my own functions for additions, subtractions and so on.

示例:

import numpy as np
class mysubclass(np.complex64):
    pass

a = mysubclass(1+1j)
A = np.empty(2, dtype=mysubclass)

print type(a)
print repr(A)

输出:

<class '__main__.mysubclass'>
array([ -2.07782988e-20 +4.58546896e-41j,  -2.07782988e-20 +4.58546896e-41j], dtype=complex64)'

有人知道怎么做吗?

提前致谢 - 索伦

推荐答案

NumPy 类型系统仅设计为从 C 扩展而来,通过 PyArray_RegisterDataType 函数.可能可以使用 ctypes 从 Python 访问此功能,但我不推荐它;最好用 C 或 Cython 编写扩展,或者像 @seberg 描述的那样子类 ndarray.

The NumPy type system is only designed to be extended from C, via the PyArray_RegisterDataType function. It may be possible to access this functionality from Python using ctypes but I wouldn't recommend it; better to write an extension in C or Cython, or subclass ndarray as @seberg describes.

NumPy 源代码树中有一个简单的示例 dtype:newdtype_example/floatint.c.如果你喜欢 Pyrex,reference.pyx 在 pytables 源代码中可能值得一看.

There's a simple example dtype in the NumPy source tree: newdtype_example/floatint.c. If you're into Pyrex, reference.pyx in the pytables source may be worth a look.

这篇关于子类化 numpy 标量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:20