python - 在包含数字和对象的数组上使用 NumPy 函数
问题描述
我有一个类似数字的类,我在其中实现了sqrt
、exp
等方法,以便 NumPy 函数在它们位于ndarray
s 中时对其进行广播。
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 函数通过在每个对象上调用同名方法进行广播,但数字没有具有这些名称的方法。
我该如何解决这个问题?
解决方案
不确定效率,但作为一种解决方法,您可以使用创建的布尔索引map
,isinstance
然后将相同的操作应用于两个切片,更改不属于类的元素的类型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
,但不确定它是否适合您的要求
推荐阅读
- terraform - terraform 无法创建 eks_node 组
- python - 如何通过查询集(逐个对象)获取每个对象的总和
- c - 子进程中的命名信号量让我感到困惑
- excel - 为什么使用简单的 VBA 时会出现运行时错误“1004”?
- java - Emacs java缩进一个空格
- azure-devops - WorkItemMigrationConfig 处理器错误
- c# - 如何使用 LDAP 查询不同服务器上的 Active Directory
- node.js - 是否有为 express().listen() 保留的类型,如果没有,Typescript 可以从函数的返回值中提取它吗?
- arrays - TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“映射”
- java - JAVA 和字节数组