Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: unhashable type: 'numpy.ndarray'

Tags:

python

numpy

From a text file containing three columns of data I want to be able to just take a slice of data from all three columns where the values in the first column are equal to the values defined in above. I then want to put the slice of data into a new array called slice (I am using Python 2.7)

above = range(18000, 18060, 5)

data = np.loadtxt(open('data.txt'), delimiter=None)

energies = (np.hsplit(data, 3))[0]

slice = set(energies)&set(above)

The above comes back with:

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    set(energies)&set(above)
TypeError: unhashable type: 'numpy.ndarray
like image 562
user1171835 Avatar asked Jan 26 '12 17:01

user1171835


People also ask

How do I fix Unhashable type NumPy Ndarray?

We can solve this by adding each array element instead of the array object into the set. This should add all the elements of the array to the set.

What does Unhashable type NumPy Ndarray mean?

by Suf | Programming, Python, Tips. The error TypeError: unhashable type: 'numpy. ndarray' occurs when trying to get a hash of a NumPy ndarray. For example, using an ndarray as a key in a Python dictionary because you can only use hashable data types as a key.

How do I fix TypeError Unhashable type list?

The Python "TypeError: unhashable type: 'list'" occurs when we use a list as a key in a dictionary or an element in a set. To solve the error, convert the list to a tuple, e.g. tuple(my_list) as list objects are mutable and unhashable.

What is Unhashable error in Python?

What are Unhashable Type Errors in Python? Unhashable type errors appear in a Python program when a data type that is not hashable is used in code that requires hashable data. An example of this is using an element in a set or a list as the key of a dictionary.


2 Answers

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])

instead.

(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

like image 61
DSM Avatar answered Oct 08 '22 20:10

DSM


numpy.ndarray can contain any type of element, e.g. int, float, string etc. Check the type an do a conversion if neccessary.

like image 5
Joni Avatar answered Oct 08 '22 19:10

Joni