不能在numpy数组上使用/= [英] Can't use /= on numpy array

查看:170
本文介绍了不能在numpy数组上使用/=的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

numpy数组上,为什么可以成功使用/ 2:

On a numpy array, why is it I can successfully use / 2:

>>> a=np.array([2, 4, 6])
>>> a = a / 2
>>> a
array([ 1.,  2.,  3.])

但是我不能使用a /= 2吗?

>>> a=np.array([2, 4, 6])
>>> a /= 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: No loop matching the specified signature and casting
was found for ufunc true_divide

我看过 numpy问题6464 ,但从阅读中看不懂并且链接的发行版说明了此操作无效的原因.

I've seen numpy Issue 6464, but don't understand from reading it and the linked release notes the reason this doesn't work.

有什么方法可以使/=正常工作?

Is there any way to get /= to work as expected?

推荐答案

正如注释中指出的,从int(这是创建a的方式)到float(是/的重用)的变化.使用/=时不允许使用.要修复" adtype,只需从头开始是浮点数即可:

As pointed out in the comment, the change from int (which is how a is created) to float (which is the reuslt of /) is not allowed when using /=. To "fix" this the dtype of a just has to be a float from the beginning:

a=np.array([2, 4, 6], dtype=np.float64)
a/=2
print(str(a))
>>>array([1., 2., 3.])

这篇关于不能在numpy数组上使用/=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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