Typeerror: Unhashable Type: ‘Numpy.Ndarray’ [Fixed]

The error message “TypeError: Unhashable Type: ‘Numpy.Ndarray'” typically occurs when you try to use a NumPy array as a key in a dictionary or as an element in a set. NumPy arrays are mutable objects, and by default, they are not hashable, meaning they cannot be used as keys in dictionaries or elements in sets because these data structures require their elements to be hashable.

To resolve this error, you can convert the NumPy array to a hashable type before using it as a key in a dictionary or as an element in a set. One common approach is to convert the NumPy array to a tuple, as tuples are immutable and hashable.

Here’s an example of how you can convert a NumPy array to a tuple before using it as a key in a dictionary:

Python
import numpy as np

# Example NumPy array
my_array = np.array([1, 2, 3])

# Convert NumPy array to tuple
array_tuple = tuple(my_array)

# Now you can use the tuple as a key in a dictionary
my_dict = {array_tuple: "value"}

print(my_dict)

In this example, tuple(my_array) converts the NumPy array my_array to a tuple array_tuple, which can then be used as a key in the dictionary my_dict.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart