0
can add int to float but can't add float to int
import numpy as np a = np.full((2,3),3, dtype=int) print(a) print(a.dtype.name) #int32 b = np.random.random((2,3)) print(b) #float64 print(b.dtype.name) b += a #this works print(b) a += b #this doesnt work print(a) #error message TypeError Traceback (most recent call last) <ipython-input-44-ab0d7ebed8b7> in <module> 10 print(b) 11 ---> 12 a += b 13 print(a) 14 TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int32') with casting rule 'same_kind' """ I don't understand, I can add int to float but can't do the reverse """
5 ответов
+ 1
They may look similar, but they are treated differently.
"The += operator preserves the type of the array. In other words, an array of integers remains an array of integers.
[...] On the other hand, a=a+b creates a brand new array for the sum, and rebinds a to point to this new array".
https://stackoverflow.com/a/10740003
+ 1
Diego Understood thanks
0
a = a+b
0
this is because Python implicitly (behind the scenes) converts the int to a float whenever a float is used in the code.
just like / (division) makes an int a float. 9+3=12 but 9/3=3.0
this “secret” conversion doesn’t work the other way around.