How to fix numpy TypeError: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
Problem:
You are trying to do a simple arithmetic operation on a NumPy array but you see an error message like
TypeError: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
Solution
You are trying to substract a float
from an int64
array. This does not work with operators like +=
or -=
Example:
import numpy as np
data = np.asarray([1, 2, 3, 4], dtype=np.int64) # This is an int array!
print(data - 5) # This works
print(data - 5.0) # This works as well
# This raises: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
data -= 5.0
Option 1 (preferred):
Use -
instead of -=
: Instead of data -= 5.0
use data = data - 5.0
Option 2:
Explicitly cast data to float
(or the first dtype
of your error message):
data = data.astype('float64')
# Now this works
data -= 5.0
This option is not preferred since doing it requires using the correct datatype. The first option works without regarding the actual datatype.
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow