Member-only story

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

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Analytics Vidhya
Analytics Vidhya

Published in Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Responses (1)

Write a response