Counter in Python
Counters is the best thing that has happened to Python when you think as a Data analyst.
Counters can be used as an alternative to a lot of things in python(mainly dictionaries). But rather than telling you when to use it and when not to, I will just tell you what can Counters help you do.
You decide when do you want to use it. :)
- To use Counters you have to import it from collections module
from collections import Counter
Note : Collections module has some really cool stuff like defaultdict, deque, ordereddict etc. Check it out here.
- You can define a counter and add data to it like below.
from collections import Counter
e=Counter('red green orange red yellow red'.split())
Note: when you check the type of "e" declared above you will get the expected "class 'collections.Counter'"
>>> type(e)
<class 'collections.Counter'>
- Now when you print the variable "e", you will see that the data in it is grouped already like below
>>> print(e)
Counter({'red': 3, 'green': 1, 'orange': 1, 'yellow': 1})
- It is important to note that Counter are used as an alternative for dictionaries in data science due to the ease of counting data using them, like above.
- You can fetch the most common data that the counter object holds like below. The below command fetches the two most common sets of data the counter object holds.
>>> e.most_common(2)
[('red', 3), ('green', 1)]
- What if you want all the data without being paired like the {element: no. of occurrences} ? That is taken care of as well.
>>> list(e.elements())
['red', 'red', 'red', 'green', 'orange', 'yellow']
Note : In the above output, the order of elements entred is not retained, but the data has been grouped as red, green, orange and yellow.
- Also, there might come a point when you want only the unique elements. That is covered as well.
>>> list(e)
['red', 'green', 'orange', 'yellow']
- Maybe you might also want a list with just the occurance count of each element. Check below code snippet then.
>>> list(e.values()) [3, 1, 1, 1]
- And if you want it like a dictionary with {key:value} pair, then here you go !
>>> list(e.items())
[('red', 3), ('green', 1), ('orange', 1), ('yellow', 1)]
Although everything has good and bad, I have not come across any bads of Counters. Would be more than happy if anyone could mention some.
Hope this helps.
Quality Engineering Strategist | AI in Testing | COE | Sales | Presales | Test Automation Architect
7 年Ramraj Sekar - Immediate Joiner
SRE & Performance Architect | Honeywell
7 年Thanks. Akshay for the Article..