Skip to content

Python interview practice/Python Data Analyst

Total selected columns

Easypandas · aggregation · missing-values

The problem

Return the total of each listed column as a float. Missing values are skipped; a column with no values totals 0.

Function: def column_totals(rows,columns):

Example input (a JSON list of arguments): [[{"a": 1, "b": 2.5}, {"a": 3, "b": null}], ["a", "b"]]
Expected output: {"a": 4.0, "b": 2.5}

Inputs satisfy the problem statement. Sequences contain at most 200 elements unless a smaller bound is stated. Use JSON values and the supplied function signature.

Hints

  1. Build the DataFrame with the requested columns so a missing column or an empty input still gives a result.
  2. Check the supplied examples, empty/boundary cases and the stated answer policy before optimizing.

Worked answer

Try it yourself first. When you are ready, open the answer below.

Show the Python answer
def column_totals(rows,columns):
    import pandas as pd
    totals=pd.DataFrame(rows,columns=columns).apply(pd.to_numeric).sum()
    return {column:float(totals[column]) for column in columns}

Why it works

Build the DataFrame with the requested columns so a missing column or an empty input still gives a result. pandas sum() skips missing values by default, and the total of an empty column is 0.

Complexity: O(n * c) time / O(n * c) space.

Time: O(n * c) time · Space: O(n * c) space

Run your own solution

Inside your account you write the code in the browser, run it against hidden test cases and save your attempt. Access covers every track, including the rest of Python Data Analyst.

See access and price

More free Python Data Analyst questions

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.