Start learning free

LESSON 17 OF 165 · MACHINE LEARNING: PANDAS

Count What's in a Column in Python

Practice

A column like city repeats the same few values again and again. The first question about it is often: which values are there, and how many rows have each? value_counts() answers it. Called on a column, it gives back each different value once, with the number of rows that have it, the biggest count first.

Here it is on a small column of T-shirt sizes:

sizes = pd.Series(["M", "S", "M", "L", "M", "S"])
print(sizes.value_counts().to_string())
print(sizes.nunique())
M    3
S    2
L    1
3

Two more tools. value_counts(normalize=True) gives back shares instead of counts: each count divided by the number of rows, so the shares add up to 1 (here M gets 0.5, S about 0.333 and L about 0.167). And nunique() gives back one plain number: how many different values the column has (here 3). .to_string() turns a Series into plain text, one value per line.

Your starting code reads customers.csv and cleans the city column the way you did in the last lesson, so " cluj " and "Cluj" count as one city and the 9 blank cities become "Unknown". Your program must print this (the first line of each count is the name of the column that was counted):

city
Cluj       52
Madrid     51
Rome       50
Lyon       48
Porto      46
Berlin     44
Unknown     9
newsletter
no     0.557
yes    0.443
Cities: 7

Your task: below the cleaning line, count the customers of each city and print the counts, print the shares of the newsletter answers rounded to 3 decimals, then print Cities: and how many different cities there are.


Assignment
Follow the Coding Tutorial to count the cities with value_counts, the newsletter answers as shares with normalize=True, and the different cities with nunique.


Hint
All three work on one column, like df["city"]. value_counts gives back a Series, so print it with .to_string(); round the shares with .round(3) first. nunique gives back a plain number, so print it as it is.


STEP 1 OF 5
    Ctrl + Enter to check

    Pd Value Counts in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free