Pandasdrill

Level 5: Analysis Exercise 77 of 102

Label rows with np.where

A pandas exercise from Pandasdrill. Solve it with a Python editor in your browser running real pandas, and it is checked the moment you submit.

The task

Add a column `status` to `acct` that says "overdrawn" when the balance is below 0 and "ok" otherwise. A balance of exactly 0 is ok. Return the whole DataFrame with the new column. numpy is available as `np`.

What this exercise teaches

np.where is a vectorized if/else: it evaluates the condition for the whole column at once, which is much faster than apply with a Python function on a large table. For more than two outcomes, np.select or pd.cut do the same job.

A hint if you get stuck

np.where(condition, value_if_true, value_if_false) checks the condition for every row and picks one of the two values.

Try it now, free, no account needed

Your first 8 exercises on Pandasdrill are free. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro unlocks every exercise, timed mode and the certificate.

Open this exercise

More exercises in Analysis