Adding a Computed Column

~10 mincode completion

Write add_total(df) that adds a "total" column equal to price * quantity, and returns the DataFrame.

Examples

The new column holds price times quantity for each row

Input
add_total({"price": [2, 3], "quantity": [4, 5]})
Output
[8, 15]

A quantity of zero gives a total of zero, not a dropped row

Input
add_total({"price": [5, 5], "quantity": [0, 2]})
Output
[0, 10]

Hints

Hint 1

A list comprehension expresses this in one line.

Hint 2

A common slip here: added instead of multiplied.

Requirements

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

  • Return the DataFrame with the extra column.

Constraints

  • Standard library only, no imports required

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 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 add_total(df):
    """
    Add a "total" column of price * quantity.

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

    Returns:
        The DataFrame with the extra column.
    """
    # YOUR CODE HERE
    pass

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


def _totals(df):
    import pandas as pd
    return [float(v) for v in add_total(pd.DataFrame(df))["total"]]

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.