Python 3 numpy 在矩阵上使用整数除法,在向量上使用常规除法?

标签 python python-3.x numpy division integer-division

运行以下代码时:

from platform import python_version
print(python_version())
    
import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
x[1,:] = x[1,:] / 5
print(x)
y = np.array([1,2,3])
y = y / 5
print(y)

我得到以下输出:

3.8.6
[[1 2 3]
 [0 1 1]
 [7 8 9]]
[0.2 0.4 0.6]

为什么 numpy/python 在用标量除矩阵中的行时使用整数除法,而使用常规除法除单行?我认为 numpy 3 中的“/”除法总是规则的?

最佳答案

Why does numpy / python use integer division when dividing a row in a matrix by a scalar

事实并非如此 - 您所看到的症状是由于分配造成的。

>>> x = np.array([[1,2,3],[4,5,6],[7,8,9]])

除以整数会生成 float 数组,

>>> z = x[1,:] / 5
>>> z
array([0.8, 1. , 1.2])

但是将该数组分配给整数数组的切片会导致数据类型转换。

>>> x[1,:] = z
>>> x
array([[1, 2, 3],
       [0, 1, 1],
       [7, 8, 9]])
>>> z.dtype
dtype('float64')
>>> x.dtype
dtype('int32')
>>>

文档中提到了这一点 - Assigning values to indexed arrays

Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even exceptions (assigning complex to floats or ints):

关于Python 3 numpy 在矩阵上使用整数除法,在向量上使用常规除法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65168843/

相关文章:

Python 在数组/列表中查找数据索引,但有约束

python - brew install python3,但无法链接到python3

python - 将字符串响应转换为 json 或列表

python - 基于另一个数组提取部分数组的最有效方法

python - 提高 numpy 三角函数运算的性能

python - Jupyter 笔记本内核一直死机 - 内存不足?

python - 在Python中将文本文件读入二维列表,而不删除空格

Python _winapi 模块

python - 类型错误 : descriptor '__weakref__' doesn't apply to object from parent __str__ method

python-3.x - Pandas:GroupBy Shift 和 Cumulative Sum