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 exerciseMore exercises in Analysis
- Rolling average
- Month over month growth
- Running total
- Rank with ties
- Change from the previous period
- Monthly totals with resample
- Quartile bins with qcut
- Age bands with cut
- Classify with apply
- Running total per group
- Top two orders per region
- Monthly totals with to_period
- Days since the previous order
- Dense rank within a group
- First order per customer
- Drawdown from the running high