TypeError: unhashable type: 'numpy.ndarray', Counter rows

TypeError: unhashable type: 'numpy.ndarray', Counter rows

我正在尝试查看二维数组中元素的频率,如代码所示:

a = np.array([22,33,22,55])
b = np.array([66,77,66,99])

x = np.column_stack((a,b))

print(collections.Counter(x))

预期结果:({(22, 66): 2, (33, 77): 1, (55, 99): 1})

但我得到:

 File "/Users/Documents/dos.py", line 8, in <module>
     print(collections.Counter(x))
 File "/opt/anaconda3/lib/python3.8/collections/__init__.py", line 552, in __init__
     self.update(iterable, **kwds)
 File "/opt/anaconda3/lib/python3.8/collections/__init__.py", line 637, in update
     _count_elements(self, iterable)
TypeError: unhashable type: 'numpy.ndarray'
In [146]: a = np.array([22,33,22,55])
     ...: b = np.array([66,77,66,99])
     ...: 
     ...: x = np.column_stack((a,b))
     ...: 
In [147]: x
Out[147]: 
array([[22, 66],
       [33, 77],
       [22, 66],
       [55, 99]])
In [148]: from collections import Counter

创建元组列表:(元组可散列)

In [149]: xl = [tuple(row) for row in x]
In [150]: xl
Out[150]: [(22, 66), (33, 77), (22, 66), (55, 99)]

现在计数器工作:

In [151]: Counter(xl)
Out[151]: Counter({(22, 66): 2, (33, 77): 1, (55, 99): 1})

numpys自己的unique也有效

In [154]: np.unique(x, axis=0, return_counts=True)
Out[154]: 
(array([[22, 66],
        [33, 77],
        [55, 99]]),
 array([2, 1, 1]))