numpy数组中的自定义数据类型 [英] Custom data types in numpy arrays

查看:364
本文介绍了numpy数组中的自定义数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个numpy数组,该数组将填充我制作的特定类的对象.我想初始化数组,使其仅包含该类的对象.例如,这是我想做的事,如果我做这件事会发生什么.

I'm creating a numpy array which is to be filled with objects of a particular class I've made. I'd like to initialize the array such that it will only ever contain objects of that class. For example, here's what I'd like to do, and what happens if I do it.

class Kernel:
    pass

>>> L = np.empty(4,dtype=Kernel)

TypeError: data type not understood

我可以这样做:

>>> L = np.empty(4,dtype=object)

,然后将L的每个元素分配为Kernel对象(或任何其他类型的对象).但是,从编程的角度(类型检查)和数学的角度(对函数集进行操作)的角度来看,如果我能够拥有一个Kernel数组,那将是如此的整洁.

and then assign each element of L as a Kernel object (or any other type of object). It would be so neat were I able to have an array of Kernels, though, from both a programming point of view (type checking) and a mathematical one (operations on sets of functions).

我是否可以使用任意类指定numpy数组的数据类型?

Is there any way for me to specify the data type of a numpy array using an arbitrary class?

推荐答案

如果您的内核类具有可预测的成员数据量,则可以为其定义dtype而不是类.例如如果它由9个浮点数和一个int参数化,则可以

If your Kernel class has a predictable amount of member data, then you could define a dtype for it instead of a class. e.g. if it's parameterized by 9 floats and an int, you could do

kerneldt = np.dtype([('myintname', np.int32), ('myfloats', np.float64, 9)])
arr = np.empty(dims, dtype=kerneldt)

每次要操作单个内核的方法时,都必须进行强制转换才能将它们转换为Kernel类的对象,但这是将实际数据存储在NumPy数组中的一种方法.如果只想存储一个引用,则对象dtype是最好的选择,而不必将ndarray子类化.

You'll have to do some coercion to turn them into objects of class Kernel every time you want to manipulate methods of a single kernel but that's one way to store the actual data in a NumPy array. If you want to only store a reference, then the object dtype is the best you can do without subclassing ndarray.

这篇关于numpy数组中的自定义数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆