dtype float'object'和'float'上算术的不同行为

发布于 2021-01-29 15:03:58

嗨,大家好,我只是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笔记本中的运行结果:

jupyter笔记本运行结果
在此处输入图片说明

赞赏有用的见解!谢谢


编辑050418 09:53-添加一个我认为是类似问题的链接 Numpy
AttributeError:’float’对象没有属性’exp’

关注者
0
被浏览
101
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    @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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看