Python 3 numpy 在矩阵上使用整数除法而在向量上使用正则除法?

Python 3 numpy uses integer division on matrices and regular division on vectors?

当运行如下代码:

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 中的“/”除法总是规则的?

这里的技巧是:

x[1,:] = x[1,:] / 5

根据 dtype 的 numpy 文档:https://numpy.org/doc/stable/reference/generated/numpy.dtype.html

A numpy array is homogeneous, and contains elements described by a dtype object

因此,当手动分配行时,它会考虑 dtype of x matrix,其类型为 dtype('int64')

如果您尝试手动将元素分配给 y 数组,同样的情况也会发生在您身上:

y = np.array([1,2,3])
y[1] = 0.5
print(y)
# this will print array([1, 0, 3])

Why does numpy / python use integer division when dividing a row in a matrix by a scalar while dividing a single row using regular division?

所以它是关于强制 np.array 本身的同质 dtype 而不是 dividing a row in a matrix,如下面的行所示:

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

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]])

除以一个整数产生一个浮点数数组,

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

但是将该数组分配给 整数数组 的一部分会导致 dtype 转换。

>>> 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):