Pandas: How to change value based on condition

Jack Dong
Analytics Vidhya
Published in
3 min readOct 17, 2021

--

The values in a DataFrame column can be changed based on a conditional expression. In this tutorial, we will go through several ways in which you create Pandas conditional columns.

Loading a Sample DataFrame

import pandas as pddata = {'Stock': ['AAPL', 'IBM', 'MSFT', 'WMT'],
'Price': [144.8, 141.61, 304.21, 139.5],
'PE': [25, 21, 39, 16],
'TradingExchange': ['NASDAQ', 'NYSE', 'NASDAQ', 'NYSE']}
df = pd.DataFrame(data)print(df)

Method1: Using Pandas loc to Create Conditional Column

Pandas’ loc can create a boolean mask, based on condition. It can either just be selecting rows and columns, or it can be used to filter dataframes.

Syntax

example_df.loc[example_df["column_name1"] condition, "column_name2"] = value
  • column_name1 is the column to evaluate;
  • column_name2 is the column to create or change, it could be the same as column_name1

--

--