Counter

from collections import Counter

# Sample list
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

# Creating a Counter
counter = Counter(data)

print(counter)
Counter({4: 4, 3: 3, 2: 2, 1: 1})
from collections import Counter

# Sample string
text = "data science bootcamp"

# Creating a Counter
counter = Counter(text)

print(counter)
Counter({'a': 3, 'c': 3, 't': 2, ' ': 2, 'e': 2, 'o': 2, 'd': 1, 's': 1, 'i': 1, 'n': 1, 'b': 1, 'm': 1, 'p': 1})
from collections import Counter

# Sample data
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

# Creating a Counter
counter = Counter(data)

# Get the 2 most common elements
most_common_elements = counter.most_common(2)

print(most_common_elements)
[(4, 4), (3, 3)]
from collections import Counter

# Initial data
data = [1, 2, 2, 3, 3, 3]

# Creating a Counter
counter = Counter(data)

# Data to update with
update_data = [2, 3, 4, 4]

# Updating the counter
counter.update(update_data)

print(counter)
Counter({3: 4, 2: 3, 4: 2, 1: 1})
from collections import Counter

# Initial data
data = [1, 2, 2, 3, 3, 3]

# Creating a Counter
counter = Counter(data)

# Data to subtract
subtract_data = [2, 3, 4]

# Subtracting from the counter
counter.subtract(subtract_data)

print(counter)
Counter({3: 2, 1: 1, 2: 1, 4: -1})
from collections import Counter

# Sample data
data = [1, 2, 2, 3, 3, 3]

# Creating a Counter
counter = Counter(data)

# Getting elements
elements = list(counter.elements())

print(elements)
[1, 2, 2, 3, 3, 3]
from collections import Counter

# Sample data
counter1 = Counter([1, 2, 2, 3])
counter2 = Counter([2, 3, 3, 4])

# Addition
print(counter1 + counter2)

# Subtraction
print(counter1 - counter2)

# Intersection (minimum of corresponding counts)
print(counter1 & counter2)

# Union (maximum of corresponding counts)
print(counter1 | counter2)
Counter({2: 3, 3: 3, 1: 1, 4: 1})
Counter({1: 1, 2: 1})
Counter({2: 1, 3: 1})
Counter({2: 2, 3: 2, 1: 1, 4: 1})
from collections import Counter
import re

# Sample text
text = "Data science is an inter-disciplinary field that uses scientific methods, processes, algorithms and systems to extract knowledge and insights from structured and unstructured data."

# Clean and split the text into words
words = re.findall(r'\w+', text.lower()) 

# Creating a Counter
counter = Counter(words)

# Most common words
print(counter.most_common(5))
[('and', 3), ('data', 2), ('science', 1), ('is', 1), ('an', 1)]
from collections import Counter

# Sample dataset: list of tuples (ID, category)
dataset = [
    (1, 'A'),
    (2, 'B'),
    (3, 'A'),
    (4, 'A'),
    (5, 'B'),
    (6, 'C')
]

# Extract categories
categories = [category for _, category in dataset]

# Creating a Counter
category_counter = Counter(categories)

print(category_counter)
Counter({'A': 3, 'B': 2, 'C': 1})