约束numpy自动将整数转换为浮点数(python 3.7) [英] Constrain numpy to automatically convert integers to floating-point numbers (python 3.7)

查看:148
本文介绍了约束numpy自动将整数转换为浮点数(python 3.7)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚犯了以下错误:

a = np.array([0,3,2, 1]) 
a[0] = .001

我期望将0替换为.001(并且numpy数组的dtype会自动从int切换为float).但是,print(a)返回:

I was expecting 0 to be replaced by .001 (and the dtype of my numpy array to automatically switch from int to float). However, print (a) returns:

array([0, 3, 2, 1])

  1. 有人可以解释为什么numpy这样做吗?我很困惑,因为将整数数组乘以浮点数会自动将dtype更改为float:

b = a*.1
print (b)
array([0. , 0.3, 0.2, 0.1])

  1. 是否有一种方法可以限制numpy来系统地将整数视为浮点数,以防止这种情况发生(并且无需首先使用.astype(float)来系统地转换numpy数组?

推荐答案

首先让我们看一下以下两个规则.这些是为python定义的:

First lets look at the following two rules. These are defined for python :

  1. 在分配中,x [0] = y,y被强制转换为x的dtype,而x的dtype不变.

  1. In assignment, x[0]=y , y is cast to dtype of x and the dtype of x is not changed.

如果float和int相乘,则结果为float.`在此处输入代码

In case of multiplication of float and int results in a float. `enter code here

在赋值时,x = y,x强制转换为y的dtype.

In assignment, x = y , x is cast to dtype of y.

当您执行 a = np.array([0,3,2,1])a [0] = .001

由于a [0]为int,因此根据规则1,a [0](以及a)的dtype保持不变.

since a[0] is int, by rule 1, dtype of a[0] (and also a) remains unchanged.

b = a * .1打印(b)数组的情况下([0.,0.3,0.2,0.1])

根据规则2,a * .1的结果为dtype float(即dtype(int * float)= float).并根据规则3,将b强制转换为float类型

By rule 2, the result of a*.1 is of dtype float (ie dtype(int * float) = float). and by rule 3, b is cast to type float

如@hpaulj所述,"a = np.array([1,2,3],float)最接近自动浮点数组表示法.– hpaulj 18小时前".但是,从本质上讲,这与必须使用.astype(float)

As @hpaulj mentioned, "a = np.array([1,2,3], float) is the closest to automatic float array notation. – hpaulj 18 hours ago". But ya, this is essentially the same as having to use .astype(float)

我无法理解您需要使用另一种方式的需求.您能否进一步详细说明为什么除了使用.astype(float)之外还想使用其他方式?

I cannot understand the need for a separate way that you require. Can you further detail why you'd like a way other than using .astype(float)?

这篇关于约束numpy自动将整数转换为浮点数(python 3.7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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