TypeError: unhashable type: 'numpy.ndarray'
The error message TypeError: unhashable type: numpy.ndarray indicates that you are attempting to use a NumPy
Hashability
In Python, hashable objects such as integers, booleans, strings, or tuples remain unchanged throughout their lifetime. This property enables Python to assign a unique hash value to each object, which is crucial for dictionaries to ensure unique keys and sets to maintain unique values.
Hashable data types | Non-Hashable Data Types |
Integer | List |
Boolean | Dictionary |
String | Set |
Tuple | NumPy ndarray |
Code
Here's an example showing various types of objects, illustrating the distinction between hashable and non-hashable objects. The code aims to determine whether various data types are hashable or not.
import numpy as np# Hashable objectshashable_integer = 42hashable_string = 'Hello, Educative!'hashable_tuple = (1, 2, 3)print(hash(hashable_integer))print(hash(hashable_string))print(hash(hashable_tuple))#Non-hashable objectsnon_hashable_arr = np.array([1,2,3,4])non_hashable_list = [1, 2, 3]non_hashable_dict = {'name': 'John', 'age': 25}non_hashable_set = {1, 2, 3}print(hash(non_hashable_arr))
Lines 4ā10: The code defines hashable objects (integer, string, tuple) and displays their hash values using the
hash()function.Lines 12ā18: When trying to compute the hash of a non-hashable object like a NumPy array, a
TypeErroris raised due to NumPy arrays' , making them ineligible for hashing.mutability Mutable objects are those that can be modified or changed after they are created.
Fixing the TypeError: unhashable type
The error arises when we use a NumPy array when data structures expect hashable types. It becomes necessary to convert the NumPy array into hashable types.
In the subsequent discussion, we will explore various scenarios where this error can occur and provide solutions to resolve it effectively.
Using a NumPy ndarray as a key in the dictionary
In Python, dictionary keys must be hashable. The error will appear when attempting to use a NumPy ndarray as a key in a Python dictionary.
Faulty code
The code snippet provided aims to verify whether an ndarray can be used as a key in a dictionary. It tests the feasibility of using an ndarray as a dictionary key.
import numpy as np# Creating an ndarrayarr = np.array([1, 2, 3])# Creating a dictionary with the ndarray as a keymy_dict = {arr: 'Value'}print(my_dict) # Output: {array([1, 2, 3]): 'Value'}
The code attempts to use an ndarray as a key in a dictionary assignment. However, it raises an error because ndarrays are not hashable. To resolve the error, you can convert the ndarray to a hashable type, such as a tuple.
Fixed code
To resolve the TypeError: unhashable type: numpy.ndarray error, you can modify the code by converting the NumPy ndarray to a hashable type, like a tuple. The provided code snippet resolves the issue.
import numpy as np# Creating a NumPy ndarrayarr = np.array([1, 2, 3])# Converting the ndarray to a tupletuple_arr = tuple(arr)# Creating a dictionary with the tuple as a keymy_dict = {tuple_arr: 'Value'}print(my_dict) # Output: {(1, 2, 3): 'Value'}
Line 7: The NumPy ndarray
arris converted to a tupletuple_arrusing thetuple()constructor to resolve the issueLines 10ā12: Subsequently, the dictionary
my_dictis created with the tuple as the key, ensuring error-free assignment, which converts the object into a hashable data type.
Including NumPy ndarray within a set
In Python, the elements of the set must be hashable. When attempting to use a NumPy ndarray as a set element, the error will appear.
Faulty Code
The code snippet provided aims to show whether an ndarray can be used as an element of a set or not.
import numpy as np# Creating a NumPy ndarrayarr = np.array([[1, 2, 3],[4,5,6]])# Creating a set and adding the tuplemy_set = set()my_set.add(arr)print(my_set) # Output:TypeError: unhashable type: 'numpy.ndarray'
The error occurs because, again, the NumPy ndarray is not in hashable type, so we will again use a tuple to convert the array into hashable type.
Fixed Code
To address the issue, we can convert the NumPy ndarray into a hashable type. The provided code snippet utilizes a map function to transform each 1D array into a tuple, making it a hashable type. This conversion helps in resolving the problem.
import numpy as np# Creating a NumPy ndarrayarr = np.array([[1, 2, 3],[4,5,6]])# Converting the ndarray to a tupletuple_arr = tuple(map(tuple, arr))my_set = set()my_set.add(tuple_arr)print(my_set) # set([((1, 2, 3), (4, 5, 6))])
Line 7: We convert the ndarray
arrto a tuple by using themap()function in combination with thetuple()constructor. Themap()function applies thetuple()function to each row of the ndarray, resulting in a new iterable containing tuples.Lines 10ā13: A set named
my_setis created, and thetuple_arrvariable that holds the converted tuples is added to the set using theadd()method. We will no longer see an error because the array was converted to a hashable type.
Conclusion
The error TypeError: unhashable type: 'numpy.ndarray' occurs when attempting to perform operations such as using an ndarray as a dictionary key or adding an ndarray object to a set.
In various scenarios, it is common to convert a 1D array into a tuple when encountering similar errors. For 2D arrays, we can convert each 1D array individually to tuples to mitigate the error.
Free Resources