[英]Creating a numpy.ndarray with elements consisting of subclassed numpy.ndarray's
我正在尝试创建一个numpy数组的子类numpy数组。 不幸的是,当我创建我的子类的新阵,numpy的自动upcasts我的数组中的元素numpy.ndarray
。
下面的代码显示了我想要做的事情。 dummy_class
继承自numpy.ndarray
并包含一些额外的功能(这对于手头的问题并不重要)。 我使用dummy_class
构造函数创建了两个新数组,并希望将每个子类数组放在一个新的numpy_ndarray
。 当有问题的数组被初始化时,子类化数组的类型会自动从dummy_class
向上 dummy_class
为numpy.ndarray
。 可以在下面找到重现问题的一些代码
import numpy
class dummy_class(numpy.ndarray):
def __new__(cls, data, some_attribute):
obj = numpy.asarray(data).view(cls)
obj.attribute = some_attribute
return obj
array_1 = dummy_class([1,2,3,4], "first dummy")
print type(array_1)
# <class '__main__.dummy_class'>
array_2 = dummy_class([1,2,3,4], "second dummy")
print type(array_2)
# <class '__main__.dummy_class'>
the_problem = numpy.array([array_1, array_2])
print type(the_problem)
# <type 'numpy.ndarray'>
print type(the_problem[0])
# <type 'numpy.ndarray'>
print type(the_problem[1])
# <type 'numpy.ndarray'>
这是使用任意Python对象填充NumPy数组的方法:
the_problem = np.empty(2, dtype='O')
the_problem[:] = [array_1, array_2]
我同意iluengo的说法,制作NumPy数组阵列并没有利用NumPy的优势,因为这样做需要外部NumPy数组是dtype object
。 对象数组需要与常规Python列表大约相同的内存量,需要比等效Python列表更多的时间来构建,计算速度不比等效的Python列表快。 也许他们唯一的优势是他们提供了使用NumPy数组索引语法的能力。
请参阅这里的numpy文档的官方示例。
我认为上面缺少的主要成分是__array_finalize__()
。
链接中提供的示例InfoArray()
正常工作正常,没有必须指定新创建的数组的dtype
作为参数:
shape1 = (2,3)
array_1 = InfoArray(shape1)
print type(array_1)
#<class '__main__.InfoArray'>
shape2 = (1,2)
array_2 = dummy_class(shape2)
the_problem = numpy.array([array_1, array_2])
print type(the_problem)
#<type 'numpy.ndarray'>
print type(the_problem[0])
#<class '__main__.InfoArray'>
此外,如果生成的聚合是一个非类型为object
的numpy
数组,那么将numpy数组子类化并将它们中的许多聚合成一个更大的数组(如the_problem
所报告的the_problem
是很有用的。
例如,假设array_1
和array_2
具有相同的形状:
shape = (2,3)
array_1 = InfoArray(shape)
array_2 = InfoArray(shape)
the_problem = numpy.array([array_1, array_2])
现在dtype
的the_problem
不是一个对象,并可以有效地计算例如作为分the_problem.min()
如果使用子类numpy
数组的列表,则无法执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.