dtype float'object'和'float'上算术的不同行为
嗨,大家好,我只是python的新秀(即使在编程方面也是如此),所以我的问题听起来很基本,但我很难理解这一点。
为什么对“浮动对象”进行算术选择行为?
import numpy as np
a = np.random.normal(size=10)
a = np.abs(a)
b = np.array(a, dtype=object)
np.square(a) # this works
np.square(b) # this works
np.sqrt(a) # this works
np.sqrt(b) # AttributeError: 'float' object has no attribute 'sqrt'
图像链接是我在本地jupyter笔记本中的运行结果:
赞赏有用的见解!谢谢
编辑050418 09:53-添加一个我认为是类似问题的链接 Numpy
AttributeError:’float’对象没有属性’exp’
-
@Warren指出
square
“代表”相乘。我通过制作包含列表的对象数组来验证了这一点:In [524]: arr = np.array([np.arange(3), 3, [3,4]]) In [525]: np.square(arr) TypeError: can't multiply sequence by non-int of type 'list'
square
适用于数组的其余部分:In [526]: np.square(arr[:2]) Out[526]: array([array([0, 1, 4]), 9], dtype=object)
sqrt
不适用于以下任何一项:In [527]: np.sqrt(arr) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-527-b58949107b3d> in <module>() ----> 1 np.sqrt(arr) AttributeError: 'numpy.ndarray' object has no attribute 'sqrt'
我可以
sqrt
使用自定义类进行工作:class Foo(float): def sqrt(self): return self**0.5 In [539]: arr = np.array([Foo(3), Foo(2)], object) In [540]: np.square(arr) Out[540]: array([9.0, 4.0], dtype=object) In [541]: np.sqrt(arr) Out[541]: array([1.7320508075688772, 1.4142135623730951], dtype=object)