Search code examples
pythonarraysnumpytypeerrorunique

TypeError: unhashable type: 'numpy.ndarray'


From an array with three columns, 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.

above = {1, 5, 10}
data = np.arange(9).reshape(-1, 3)
energies = np.hsplit(data, 3)[0]
slice = set(energies) & above

The above comes back with:

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    slice = set(energies) & above
TypeError: unhashable type: 'numpy.ndarray'

How do I resolve this error?


Solution

  • 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.)