Behebung von numpy TypeError: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
English
Deutsch
Problem:
Du versuchst, eine einfache arithmetische Operation auf einem NumPy-Array durchzuführen, aber du siehst eine Fehlermeldung wie
numpy_cast_error_output.txt
TypeError: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'Lösung
Du versuchst, einen float von einem int64-Array zu subtrahieren. Dies funktioniert nicht mit Operatoren wie += oder -=
Beispiel:
numpy_cast_error_example.py
import numpy as np
data = np.asarray([1, 2, 3, 4], dtype=np.int64) # Dies ist ein int-Array!
print(data - 5) # Dies funktioniert
print(data - 5.0) # Dies funktioniert as well
# Dies löst aus: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
data -= 5.0Option 1 (bevorzugt):
Verwende - anstelle von -=: Anstelle von data -= 5.0 verwende data = data - 5.0
Option 2:
Daten explizit zu float casten (oder den ersten dtype deiner Fehlermeldung):
numpy_cast_fix_option2.py
data = data.astype('float64')
# Dies funktioniert nun
data -= 5.0Diese Option ist nicht bevorzugt, da sie die Verwendung des korrekten Datentyps erfordert. Die erste Option funktioniert ohne Berücksichtigung des tatsächlichen Datentyps.
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow