dtype float'object'和'float'上算术的不同行为 [英] Different behavior of arithmetics on dtype float 'object' and 'float'

查看:218
本文介绍了dtype float'object'和'float'上算术的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我只是python的新秀(即使在编程方面也是如此),所以我的问题听起来很基础,但是我很难理解这一点.

Hi guys im just a rookie in python (even in programming) so my question might sound very basic but i have a hard time to understand this.

为什么对浮动对象"进行算术选择行为?

Why is the selective behavior on arithmetics on 'float object'?

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笔记本中的运行结果:

The image link is my run result in local jupyter notebook:

jupyter笔记本运行结果

jupyter notebook run result

欣赏有用的见解!谢谢

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

edit 050418 09:53 --add a link that i think is similar issue Numpy AttributeError: 'float' object has no attribute 'exp'

推荐答案

@Warren指出square委托"要相乘.我通过制作包含列表的对象数组来验证了这一点:

@Warren points out that square 'delegates' to multiply. I verified this by making an object array that includes a list:

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在数组的其余部分上起作用:

square works on the rest of the array:

In [526]: np.square(arr[:2])
Out[526]: array([array([0, 1, 4]), 9], dtype=object)

sqrt不适用于以下任何一项:

sqrt doesn't work on any of these:

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与自定义类一起工作:


I can make sqrt work with a custom class:

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)

这篇关于dtype float'object'和'float'上算术的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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