Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

groupby and Aggregate

~12 mincode completion

groupby is the single most valuable thing pandas does. It splits the rows into groups, applies a calculation to each group, and puts the answers back together.

df.groupby("city")["price"].mean()

Read it in three parts:

  • groupby("city") split the rows by the value in the city column
  • ["price"] from each group, take the price column
  • .mean() and reduce it to one number
  • The result is a Series indexed by the group key. .reset_index() turns it back into a normal DataFrame with the key as a column, which is usually what you want next.

    Other aggregations work the same way: .sum(), .count(), .max(), .std(), and .agg(["mean", "count"]) for several at once.

    A detail worth knowing early: rows where the grouping key is NaN are dropped silently by default. If your group totals do not add up to the whole, that is usually why.

    Your task:

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

    Use groupby, then convert with .to_dict().

    Example Tests

    Each city gets the mean of its own rows

    Input: {"df":{"city":["a","a","b"],"price":[10,20,7]}}

    Expected: {"a":15,"b":7}

    A single city gives a single entry

    Input: {"df":{"city":["x","x"],"price":[4,6]}}

    Expected: {"x":5}

    Every city appears exactly once in the result

    Input: {"df":{"city":["a","b","c","a"],"price":[1,2,3,5]}}

    Expected: {"a":3,"b":2,"c":3}

    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…