This video how to use the where() function in numpy and pandas to extract indices based on logical conditions and populate new columns of data based on elementwise logic. The np.where() function can perform a similar operation to the ifelse() function in R.

Code used in this Python Code Clip:

import numpy as np
import pandas as pd

import statsmodels.api as sm #(To access mtcars dataset)
mtcars = sm.datasets.get_rdataset(“mtcars”, “datasets”, cache=True).data

mtcars.head()

Extract indices that meet a condition

inds = np.where(mtcars.mpg > 22)

inds

Perform operations across an array or column based on a condition

np.where(mtcars.mpg > 22, # Condition
“High MPG”, # Value to set if condition is True
“Low MPG”) # Value to set if condition is False

Perform elementwise operations on an array or column

np.where(mtcars.mpg > 22, # Condition
mtcars.mpg, # Value to set if condition is True
mtcars.cyl) # Value to set if condition is False

► Subscribe: https://www.youtube.com/c/DataDaft?sub_confirmation=1

#python

How to Use where() in Numpy and Pandas (Python)
16.95 GEEK