numpy-convertible类可以从序列内部正确转换为ndarray吗? [英] Numpy-convertible class that correctly converts to ndarray from inside a sequence?

查看:92
本文介绍了numpy-convertible类可以从序列内部正确转换为ndarray吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

__array__方法允许自定义类型自动转换为numpy.例如,

The __array__ method allows a custom type to automatically convert to numpy. E.g.,

>>> class Convertible:
...  def __array__(self):
...    return np.zeros(7)
>>> np.array(Convertible())
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.])

不幸的是,如果自定义类型出现在序列中,则__array__不起作用:

Unfortunately, __array__ doesn't work if the custom type occurs inside a sequence:

>>> np.array([Convertible(), Convertible()])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: float() argument must be a string or a number, not 'Convertible'

有没有一种方法可以修复Convertible,以便用np.arrayConvertible对象的序列转换为numpy与转换每个对象然后转换所得的ndarrays的序列相同?

Is there a way to fix Convertible so that converting a sequence of Convertible objects to numpy with np.array is the same as converting each one and then converting the sequence of resulting ndarrays?

推荐答案

它必须是一个序列.

numpy.array 录入

数组,任何暴露数组接口的对象,其__array__方法返回数组的对象或任何(嵌套的)序列.

An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.

Convertible实例上调用numpy.array时,您遇到的是对象的__array__方法返回数组的对象"的情况.当您在敞篷车"列表上调用它时,您遇到的是任何(嵌套的)序列"情况.在确定新数组的dtype时,类型推断逻辑似乎正在采用您定义的__array__方法,但是在那之后,由于您的对象不提供序列协议,因此NumPy假定您的对象应直接转换为int

When you call numpy.array on a Convertible instance, you're hitting the "an object whose __array__ method returns an array" case. When you call it on a list of Convertibles, you're hitting the "any (nested) sequence" case. The type inference logic appears to be picking up the __array__ method you defined when determining the dtype of the new array, but after that, since your objects don't provide the sequence protocol, NumPy assumes your objects should be converted to ints directly.

实现__len____getitem__,您应该能够将[Convertible(), Convertible()]转换为数组.但是,当您执行此操作时,NumPy将使用而不是__array__来使用序列协议,这将涉及比您可能想要的更多的Python方法调用.如果要防止这种情况,除了直接numpy.array调用外,您还必须执行其他操作.

Implement __len__ and __getitem__, and you should be able to convert [Convertible(), Convertible()] to an array. NumPy is going to use the sequence protocol instead of __array__ when you do that, though, which is going to involve more Python method calls than you probably wanted. You'd have to do something other than a direct numpy.array call if you want to prevent that.

这篇关于numpy-convertible类可以从序列内部正确转换为ndarray吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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