Reputation: 381
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
Upvotes: 8
Views: 17981
Reputation: 231605
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.
Upvotes: 14
Reputation: 917
Your variable a
is a numpy array with types int
and your variable b
is a numpy array with types float
. When add b
to a
it will try to convert these floats to integers which looses information. However, when you do it the other way around you cast an integer to a float, which is perfectly fine.
Upvotes: 3
Reputation: 311998
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)
Upvotes: 5