groupby and Aggregate

~12 mincode completion

Write mean_by_city(df) that returns the mean price for each city, as a dictionary mapping city name to mean price.

Use , then convert with .to_dict().

Examples

Each city gets the mean of its own rows

Input
mean_by_city({"city": ["a", "a", "b"], "price": [10, 20, 7]})
Output
{"a": 15, "b": 7}

A single city gives a single entry

Input
mean_by_city({"city": ["x", "x"], "price": [4, 6]})
Output
{"x": 5}

Every city appears exactly once in the result

Input
mean_by_city({"city": ["a", "b", "c", "a"], "price": [1, 2, 3, 5]})
Output
{"a": 3, "b": 2, "c": 3}

Hints

Hint 1

Work directly with the arguments and return the result rather than printing it.

Hint 2

Reach for mean rather than sum.

Requirements

  • : a DataFrame with "city" and "price" columns

  • Return a dict mapping city -> mean price.

Constraints

  • Standard library only, no imports required

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~12 min

8 employers weight this skill

2 big tech firms, 2 frontier labs, 1 AI product company, 1 defense company, 1 enterprise vendor, 1 quant fund. Top match scores 63.

Python
import pandas as pd

def mean_by_city(df):
    """
    Average price per city.

    Args:
        df: a DataFrame with "city" and "price" columns

    Returns:
        A dict mapping city -> mean price.
    """
    # YOUR CODE HERE
    pass

def _run(df):
    import pandas as pd
    return mean_by_city(pd.DataFrame(df))

Run your code to see results

⌘↵ runs against the visible tests

Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.