Nate Gardner
Nate Gardner

Reputation: 1717

Python: create frequency table from 2D list

Starting with data formatted like this:

data = [[0,1],[2,3],[0,1],[0,2]]

I would like to represent every value once with its frequency:

output = [[[0,1],2],[[2,3],1],[[0,2],1]]

I've found many solutions to this problem for 1D lists, but they don't seem to work for 2D.

Upvotes: 1

Views: 609

Answers (1)

Kasravnd
Kasravnd

Reputation: 107297

It's what that collections.Counter() is for:

>>> from collections import Counter
>>> 
>>> Counter(map(tuple,data))
Counter({(0, 1): 2, (2, 3): 1, (0, 2): 1})
>>> Counter(map(tuple,data)).items()
[((0, 1), 2), ((2, 3), 1), ((0, 2), 1)]

Note that since list objects are not hashable you can not use them as the dictionary keys.So you need to convert them to tuple which is a hashable object.

Upvotes: 1

Related Questions