Skip to content

Python interview practice/Python Data Analyst

Clean numeric text before aggregation

Mediumpandas · missing-values · aggregation

The problem

Use pandas to calculate the mean of numeric input values. Invalid strings and null are missing; return null when no numeric observation remains.

Function: def numeric_mean(values):

Example input (a JSON list of arguments): [["2", "bad", null, "4"]]
Expected output: 3.0

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. Coerce invalid strings and missing values to NaN, then average observed numeric values.
  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 numeric_mean(values):
    import pandas as pd
    s=pd.to_numeric(pd.Series(values,dtype='object'),errors='coerce').dropna()
    return float(s.mean()) if len(s) else None

Why it works

Coerce invalid strings and missing values to NaN, then average observed numeric values. An entirely missing series returns null rather than inventing a zero-valued observation.

Complexity: O(n) time / O(n) series space.

Time: O(n) time · Space: O(n) series 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.