pandas: Several aggregations per group

Model groupby().agg(["size", "count", "sum", "mean", "min", "max"]), and see how missing values affect each.

What to build

A program that summarises each group several ways.

Requirements

  • For each key in sorted order print KEY: size=S count=C sum=T mean=M min=A max=B, with sum, mean, min and max to two decimals.
  • Values may be NaN (missing). Missing values count towards size only. A group with no present values has sum 0.00 and NaN for mean, min and max.

Input

Line 1: n. Then n lines KEY VALUE.

Output

One line per key.

Constraints

1 ≤ n ≤ 500.

Example

Input:

6
Dhaka 30
Paris 50
Dhaka 20
Lima 10
Paris 25
Dhaka NaN

Output:

Dhaka: size=3 count=2 sum=50.00 mean=25.00 min=20.00 max=30.00
Lima: size=1 count=1 sum=10.00 mean=10.00 min=10.00 max=10.00
Paris: size=2 count=2 sum=75.00 mean=37.50 min=25.00 max=50.00

Why it works

Each aggregation is a separate pass over a group's values with the missing ones skipped, except size, which only counts rows; an empty sum is 0 by definition, while an average or an extreme of nothing does not exist.

Examples

Example 1 · Input
6
Dhaka 30
Paris 50
Dhaka 20
Lima 10
Paris 25
Dhaka NaN
Expected output
Dhaka: size=3 count=2 sum=50.00 mean=25.00 min=20.00 max=30.00
Lima: size=1 count=1 sum=10.00 mean=10.00 min=10.00 max=10.00
Paris: size=2 count=2 sum=75.00 mean=37.50 min=25.00 max=50.00
Example 2 · Input
2
a NaN
a NaN
Expected output
a: size=2 count=0 sum=0.00 mean=NaN min=NaN max=NaN

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

Hints

Hint 1

Collect each group's values, keeping NaN as a gap; size counts all of them, count only the numbers.

Hint 2

With no values present, sum is 0 and mean, min and max are NaN.

Solution

Show one correct solution (try it yourself first)
n = int(input())
groups = {}
for _ in range(n):
    key, value = input().split()
    groups.setdefault(key, []).append(None if value == "NaN" else float(value))
for key in sorted(groups):
    values = groups[key]
    present = [v for v in values if v is not None]
    if present:
        mean = f"{sum(present) / len(present):.2f}"
        lo, hi = f"{min(present):.2f}", f"{max(present):.2f}"
    else:
        mean = lo = hi = "NaN"
    print(f"{key}: size={len(values)} count={len(present)} sum={sum(present):.2f} mean={mean} min={lo} max={hi}")

Lesson: groupby: split, apply, combine →