Menu
CoddyTech

Counting Values

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 42 of 60.

This chapter turns raw tables into clean summaries, starting with the simplest question: how many of each? Six bakery orders, counted:

A bar chart of six bakery orders counted by item: bread 3, cake 2, pie 1, the tallest bar first

value_counts() does the counting:

orders = pd.DataFrame({"item": ["bread", "cake", "bread", "pie", "cake", "bread"]})
counts = orders["item"].value_counts()
print(counts)

This prints:

item
bread    3
cake     2
pie      1
Name: count, dtype: int64

One row per different value, most common first. counts.index[0] is the top value, counts.iloc[0] its count, and len(counts) the number of different values.

Counts are your first look at any column a model will learn from: what dominates, what is rare, what is a typo.

challenge icon

Challenge

Medium

A bike-share scheme kept its last 30 rentals in bikes.csv. The team wants a quick profile of a few columns, and the starter reads their names into columns.

For each column, in order, print one line: its name, how many different values it holds, and its most common value with that value's count.

For two columns of another file, the output looks like this:

color: 3 different values, most often red (12)
size: 4 different values, most often M (9)

Try it yourself

import pandas as pd

rentals = pd.read_csv("bikes.csv")

# The names of the columns to report
n = int(input())
columns = []
for i in range(n):
    columns.append(input())

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler