why I'm getting TypeError
for a += b
but it works fine for b += a
for below code
import numpy as np
a = np.ones((2,3), dtype=int)
b = np.random.random((2,3))
a += b
Report the whole TypeError!
----> 3 a += b
TypeError: Cannot cast ufunc add output from dtype('float64') to
dtype('int64') with casting rule 'same_kind'
a
is integer dtype, right? b
is float. Add a float and integer and the result is a float. But a+=...
is expected to put that float into a
, the integer array. numpy
does not want to do that.
But this is fine:
In [3]: a = a + b
In [4]: a
Out[4]:
array([[1.01407496, 1.96122364, 1.91447533],
[1.68130058, 1.99773138, 1.50043386]])
The original integer array, a
has now been replaced by a float array. That's a Python level assignment, where as a+=...
attempts to modify the original a
array (in-place). The distinction is important.
The error message will give you a hint:
TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int32') with casting rule 'same_kind'
a
is an array of int32
s and b
is an array of float64
s. Adding an int32
and a float64
(nevermind which comes first), will produce a float64
. This value cannot be stored in a
, but can be stored in b
.
If you define a
to use dtype=float
, a+=b
would be perfectly legal:
a = np.ones((2,3), dtype=float)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With