问题
I have just made the following mistake:
a = np.array([0,3,2, 1])
a[0] = .001
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])
- Can somebody explain why numpy is doing that? I am confused because multiplying my array of integers by a floating point number will automatically change dtype to float:
b = a*.1 print (b) array([0. , 0.3, 0.2, 0.1])
- Is there a way to constrain numpy to systematically treat integers as floating-point numbers, in order to prevent this (and without systematically converting my numpy arrays in the first place using .astype(float)?
回答1:
First lets look at the following two rules. These are defined for python :
In assignment, x[0]=y , y is cast to dtype of x and the dtype of x is not changed.
In case of multiplication of float and int results in a float. `enter code here
In assignment, x = y , x is cast to dtype of y.
When you do a = np.array([0,3,2, 1]) a[0] = .001
since a[0] is int, by rule 1, dtype of a[0] (and also a) remains unchanged.
While in case of b = a*.1 print (b) array([0. , 0.3, 0.2, 0.1])
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
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)
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)?
来源:https://stackoverflow.com/questions/62969789/constrain-numpy-to-automatically-convert-integers-to-floating-point-numbers-pyt