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()

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

inds

np.where(mtcars.mpg ＞ 22, # Condition

“High MPG”, # Value to set if condition is True

“Low MPG”) # Value to set if condition is False

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

16.95 GEEK