我正在嘗試查看二維陣列中元素的頻率,如代碼中所示:
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'
uj5u.com熱心網友回復:
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]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464618.html
