'numpy.float64' object does not support item assignment

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

'numpy.float64' object does not support item assignment #

The Python "TypeError: 'numpy.float64' object does not support item assignment" occurs when we try to assign a value to a numpy float using square brackets. To solve the error, correct the assignment or the accessor, as we can't mutate a floating-point number.

typeerror numpy float64 object does not support item assignment

Here is an example of how the error occurs.

main.py
import numpy as np my_float = np.float64(1.1) # ⛔️ TypeError: 'numpy.float64' object does not support item assignment my_float[0] = 9

We tried to access the numpy float at index 0 and change the digit which caused the error.

If you mean to declare another floating-point number, simply declare a separate variable with a different name.

main.py
import numpy as np my_float = np.float64(1.1) my_other_float = np.float64(2.2)

Primitives like floats, integers and strings are immutable in Python, so chances are you meant to change a float value in an array or a list.

main.py
my_arr = np.array([1.1, 2.2, 3.3], dtype=np.float64) my_arr[0] = 9.9 print(my_arr) # 👉️ [9.9 2.2 3.3]

We changed the value of the list element at index 0.

Make sure you haven't declared a variable with the same name multiple times and you aren't reassigning a list to a float somewhere by mistake.

If you have two-dimensional array or lists, you have to access the list item at the correct index when updating it.

main.py
my_arr = np.array([[1.1], [2.2], [3.3]], dtype=np.float64) my_arr[0][0] = 9.9 # [[9.9] # [2.2] # [3.3]] print(my_arr)

We accessed the first nested array (index 0) and then updated the value of the first item in the nested array.

The Python "TypeError: 'float' object does not support item assignment" is caused when we try to mutate the value of a float.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
import numpy as np my_float = np.float64(1.1) print(type(my_float)) # 👉️ <class 'numpy.float64'> print(isinstance(my_float, np.float64)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Conclusion #

The Python "TypeError: 'numpy.float64' object does not support item assignment" occurs when we try to assign a value to a numpy float using square brackets. To solve the error, correct the assignment or the accessor, as we can't mutate a floating-point number.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.