How to create a new column based on conditions in Python

Creating a new column based on conditions in Python is a very common task in data analysis. In Pandas, one way to achieve this is by using the apply() function along with a lambda function. A lambda function is a small anonymous function without a name. The basic syntax for using the apply() function along with a lambda function to create a new column is as follows:

 

df['new_column'] = df['existing_column'].apply(lambda x: 'value_if_true' if x condition_to_check else 'value_if_false')

 

You can specify any conditions that you would like to check using the usual comparison operators such as ==, >, <, >=, <=, !=. The apply() function applies this lambda function to each element in the existing column, and the new column is created with the output.

For example, let’s say you have a DataFrame called df with a column called age, and you want to create a new column called age_group that categorizes the ages into three different groups: ‘young’, ‘middle-aged’, and ‘old’. You could use the following code:

df['age_group'] = df['age'].apply(lambda x: 'young' if x <= 30 else 'middle-aged' if x <= 60 else 'old')

 

This code will create a new column called ‘age_group’ with categories based on the age of each person in the ‘age’ column.

Another way to do this is by using the numpy.where() method, this way you can create a new column based on the conditions.

 

df["new_column"] = np.where(df["existing_column"] < condition, "value_if_true", "value_if_false")

 

This way you don’t have to use a lambda function, and it can be more clear to understand.

Both ways are commonly used and can be useful depending on the context, choose the one that better suit your needs. Please let me know if you have any questions or if you need more explanations.

 

In this Learn through Codes example, you will learn: How to create a new column based on conditions in Python.

Essential Gigs