np.where()

noun

say it: “EN-PEE WAIR” /ˌɛnˈpi ˈwɛr/

A NumPy function that looks at a True or False answer for each row and gives that row one value when it's True and another when it's False.

What does np.where() do?

np.where() is a NumPy function that gives each row one of two values: the first where a condition is True, the second where it's False. It's how a new column gets an either-or value, such as a sale price or the normal price.

import numpy as np
import pandas as pd
products = pd.DataFrame({"price": [100.0, 60.0], "on_sale": [True, False]})
products["sale_price"] = np.where(products["on_sale"], products["price"] * 0.8, products["price"])
print(products["sale_price"].tolist())   # [80.0, 60.0]

In a sentence

  • “np.where() gave every sale item 20% off and left the rest at full price.”
  • “The status column came from np.where(): late when the delivery took over 45 minutes, on time otherwise.”

Level: Journeyman · More Python terms at this level

Updated