5 Ways to Apply If-Else Conditional Statements in Pandas
Revisiting Pandas Basics and Honing Your Data Wrangling Skills
Creating a new column or modifying an existing column in a Pandas data frame — based on a set of if-else
conditions — is probably one of the most frequently encountered problems among all different types of data wrangling tasks. In this post, I’d like to share with you my notepad which summarizes the 5 popular ways of applying if-else
conditional statements in Pandas dataframes with handy and practical code snippets. For simplicity, I created a small sample dataset and will use it for demonstration purposes throughout the tutorial.
Let’s say we have a pandas dataframe as shown below. The column ‘visits_30days’ shows how many times a customer visited a website in the last 30 days. We want to create a new column that either categorizes these customers into ‘non-visitor’ or ‘visitor’ (a binary categorization) or categorizes them into multiple buckets such as ‘0 visits’, ‘1–5 visits’, ‘6-10 visits’, etc. We’ll name this new column ‘visits_category’.