我有代码:
A = np.array([[1,2,3,4],
[1,3,2,4],
[1,5,1,2],
[1,2,2,1],
[2,1,1,3]])
A[1:4,2] = A[1:4,2] - [2.3,2.2,2.1]
这会将子列修改为仍然是整数数组,但是如果我这样做:
x = np.array([[3,3,3,3],[2,2,2,2]])
y = np.array([[2.2,2.1,2.1,2.1],[1.2,1.2,0.2,0.3]])
z = x-y
那么它是一个存储在z中的浮点数,这是什么解释?内铸件是如何工作的?谢谢!
另外,声明 A = A.astype(float) 是最好的解决方案吗?有没有更好/推荐的方法?
答案 0 :(得分:0)
从 Data Types 开始,Numpy 尝试以与 Python 相同的方式保留操作数的类型。如果您正在使用整数进行运算,结果是整数(比如求和),则结果为整数。如果您将它与浮点数混合,结果将是浮点数。
a=3
print(type(a)) # <class 'int'>
b=2.9
print(type(b)) # <class 'float'>
print(type(a-b)) # <class 'float'>
numpy 也是一样。您还可以使用 astype
方法投射结果。同样在数组创建过程中,您可以使用 dtype
参数指定类型
a = np.array([1, 2])
print(a.dtype) # int64
b = np.array([1.1, 2.2])
print(b.dtype) # float64
print((b-a).dtype) # float64
c = (b-a).astype('int64')
print(c.dtype) # int64
d = np.array([1.1, 2.2], dtype='int64')
print(d.dtype) # int64