【问题标题】:Constrain numpy to automatically convert integers to floating-point numbers (python 3.7)约束 numpy 自动将整数转换为浮点数(python 3.7)
【发布时间】:2020-11-08 04:38:52
【问题描述】:

我刚刚犯了以下错误:

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

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

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 数组?

【问题讨论】:

  • 在分配中,a[i]=b b 被强制转换为匹配 aa dtype 无法更改(就地)。从大局来看,这样更安全。您的 b 是一个新数组。
  • a = np.array([1,2,3], float) 是最接近自动浮点数组表示法。

标签: numpy floating-point int dtype


【解决方案1】:

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

  1. 在赋值中,x[0]=y,y 被强制转换为 x 的 dtype,x 的 dtype 没有改变。

  2. 如果 float 和 int 相乘会产生一个浮点数。 `在此输入代码

  3. 在赋值中,x = y,x 被转换为 y 的 dtype。

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

由于 a[0] 是 int,根据规则 1,a[0](以及 a)的 dtype 保持不变。

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

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

正如@hpaulj 提到的,“a = np.array([1,2,3], float) 是最接近自动浮点数组表示法的。- hpaulj 18 小时前”。但是,这与必须使用 .astype(float) 基本相同

我无法理解您需要一种单独的方式。您能否进一步详细说明为什么您想要使用 .astype(float) 以外的其他方式?

【讨论】:

    猜你喜欢
    • 2020-05-14
    • 2019-05-10
    • 1970-01-01
    • 2017-10-14
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多