pandas where by value code example

Example 1: only keep rows of a dataframe based on a column value

df.loc[df['column_name'] == some_value]

Example 2: pandas where

# replaces values with other where condition is False
DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False)

import pandas as pd 
df = pd.DataFrame({'values':[1,2,3,4]})

df.where(df['values'] % 2 == 0, -1) # output : [-1, 2, -3, 4]

Example 3: selecting a specific value and corrersponding value in df python

#To select rows whose column value equals a scalar, some_value, use ==:df.loc[df['favorite_color'] == 'yellow']