1. What is the collections library?
The Python library collections implements specialized container datatypes providing alternatives to Python's general purpose built in containers, dict, list, set, and tuple.
The Counter method provide dict subclass for counting hashable objects. When we pass a string or list to the Counter constructor as a factor, an object is returned that tells us how many times each character appears in the string or list.
The Counter class in the collections module extends Python's basic data structure, dictonary, so we can reuse the API provided by the dictionary as it is.
2. How to use Counter?
Step 1 : Import Library
from collections import Counter
Step 2 : Put the input data into method
counter = Counter(["A", "B", "A"])
Step 3 : Check the result stored in variable
counter
# result will be same as following :
# Coutner({"A" : 2, "B" : 1})
3. Compare two ways of making frequency table
We can also make frequency table using dictionary. To make frequency table with dictionary, we increment value by 1 when we meet same value.
def freq_fueltype1():
# Make empty dictionary table
fuel_freq = {}
# Extract fueltype from data and make frequency
fuel_idx = Cars_header.index('fueltype')
for rows in Cars_rows:
fueltype = rows[fuel_idx]
if fueltype not in fuel_freq:
fuel_freq[fueltype] = 1
else :
fuel_freq[fueltype] += 1
return fuel_freq
def freq_fueltype2():
from collections import Counter
fuel_idx = Cars_header.index('fueltype')
fueltype = [row[fuel_idx] for row in Cars_rows]
fuel_freq = Counter(fueltype)
return fuel_freq
def make_table_from_dict(table_):
from beautifultable import BeautifulTable
table = BeautifulTable(maxwidth = 130)
table.column_headers = ['fuel_type', 'counts']
for key, value in table_.items():
table.append_row([key, value])
print(table)
# Make frequency table using dictionary
make_table_from_dict(freq_fueltype1())
# Make frequency table using Counter method
make_table_from_dict(freq_fueltype2())
We can find that freq_fueltype2 works well in make_table_from_dict function. It's because the Counter class in the collections module extends Python's basic data structure, dictonary.
Source from : https://docs.python.org/3/library/collections.html
'Language > Python' 카테고리의 다른 글
[OOP] Creating Fraction Class using OOP (1) | 2022.09.30 |
---|---|
[Syntax] Meaning of dot Notation (0) | 2022.09.26 |
[chardet] Encoding and Representing Text (0) | 2022.09.22 |
[csv] Read files (0) | 2022.09.22 |
[folium] Visualization Map on Python (0) | 2022.09.18 |