Hits: 189
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.
Comparing Different Machine Learning Algorithms in Python for Classification (FREE)
Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.
Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners