I’m trying to view the frequency of the elements in a 2d array as in the code:
JavaScript
x
7
1
a = np.array([22,33,22,55])
2
b = np.array([66,77,66,99])
3
4
x = np.column_stack((a,b))
5
6
print(collections.Counter(x))
7
Expected result: ({(22, 66): 2, (33, 77): 1, (55, 99): 1})
But I get:
JavaScript
1
8
1
File "/Users/Documents/dos.py", line 8, in <module>
2
print(collections.Counter(x))
3
File "/opt/anaconda3/lib/python3.8/collections/__init__.py", line 552, in __init__
4
self.update(iterable, **kwds)
5
File "/opt/anaconda3/lib/python3.8/collections/__init__.py", line 637, in update
6
_count_elements(self, iterable)
7
TypeError: unhashable type: 'numpy.ndarray'
8
Advertisement
Answer
JavaScript
1
13
13
1
In [146]: a = np.array([22,33,22,55])
2
b = np.array([66,77,66,99]) :
3
:
4
x = np.column_stack((a,b)) :
5
:
6
In [147]: x
7
Out[147]:
8
array([[22, 66],
9
[33, 77],
10
[22, 66],
11
[55, 99]])
12
In [148]: from collections import Counter
13
Create a list of tuples: (tuples are hashable)
JavaScript
1
4
1
In [149]: xl = [tuple(row) for row in x]
2
In [150]: xl
3
Out[150]: [(22, 66), (33, 77), (22, 66), (55, 99)]
4
Now Counter works:
JavaScript
1
3
1
In [151]: Counter(xl)
2
Out[151]: Counter({(22, 66): 2, (33, 77): 1, (55, 99): 1})
3
numpys
own unique
also works
JavaScript
1
7
1
In [154]: np.unique(x, axis=0, return_counts=True)
2
Out[154]:
3
(array([[22, 66],
4
[33, 77],
5
[55, 99]]),
6
array([2, 1, 1]))
7