pandas: value_counts and its options

Model Series.value_counts with its normalize and dropna options.

What to build

A program that counts the values of a column.

Requirements

  • Options are given as words: normalize and/or dropna=False (or none). Empty values are missing: they are not counted, unless dropna=False, when they count as NaN.
  • Print VALUE: C lines, most common first; equal counts in alphabetical order (NaN sorts as the text "NaN"). With normalize, print each fraction of the counted values with three decimals instead of C.

Input

Line 1: the options. Line 2: the values, separated by commas (empty between two commas is missing).

Output

One line per distinct value.

Constraints

1 to 200 values.

Example

Input:

none
Dhaka,London,Dhaka,,Paris,Dhaka,London

Output:

Dhaka: 3
London: 2
Paris: 1

Why it works

Counting groups equal values, and dividing by how many values were counted turns counts into shares; whether a gap is counted changes both, which is why dropna matters here too.

Examples

Example 1 · Input
none
Dhaka,London,Dhaka,,Paris,Dhaka,London
Expected output
Dhaka: 3
London: 2
Paris: 1
Example 2 · Input
normalize dropna=False
a,,b,a
Expected output
a: 0.500
NaN: 0.250
b: 0.250

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Count with a dictionary, skipping empty values unless dropna=False is asked for.

Hint 2

normalize divides each count by the number of values counted.

Solution

Show one correct solution (try it yourself first)
options = input().split()
values = input().split(",")
keep_na = "dropna=False" in options
counted = [v if v != "" else "NaN" for v in values if v != "" or keep_na]
counts = {}
for v in counted:
    counts[v] = counts.get(v, 0) + 1
for v, c in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):
    print(f"{v}: {c / len(counted):.3f}" if "normalize" in options else f"{v}: {c}")

Lesson: Sorting, ranking and counting →