首页 > 解决方案 > 在包含数字和对象的数组上使用 NumPy 函数

问题描述

我有一个类似数字的类,我在其中实现了sqrtexp等方法,以便 NumPy 函数在它们位于ndarrays 中时对其进行广播。

class A:
    def sqrt(self):
        return 1.414

这在以下数组中完美地工作:

import numpy as np
print(np.sqrt([A(), A()]))  # [1.414 1.414]

显然,sqrt也适用于纯数字:

print(np.sqrt([4, 9]))  # [2. 3.]

但是,当数字和对象混合时,这不起作用:

print(np.sqrt([4, A()]))

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-38-0c4201337685> in <module>()
----> 1 print(np.sqrt([4, A()]))

AttributeError: 'int' object has no attribute 'sqrt'

发生这种情况是因为dtype异构数组的 isobject和 numpy 函数通过在每个对象上调用同名方法进行广播,但数字没有具有这些名称的方法。

我该如何解决这个问题?

标签: pythonnumpy

解决方案


不确定效率,但作为一种解决方法,您可以使用创建的布尔索引mapisinstance然后将相同的操作应用于两个切片,更改不属于类的元素的类型A以便能够使用该numpy方法。

ar = np.array([4, A(), A(), 9.])
ar_t = np.array(list(map(lambda x: isinstance(x, A), ar)))

ar[~ar_t] = np.sqrt(ar[~ar_t].astype(float)) 
ar[ar_t] = np.sqrt(ar[ar_t])

print(ar)
# array([2.0, 1.414, 1.414, 3.0], dtype=object)

注意:在 中astype,我使用过float,但不确定它是否适合您的要求


推荐阅读