How to create new variables in the pandas data frame

Creating a new variable in pandas data frame is an easy task! Either you can pass the values of that new column or you can generate the values of new columns based on the existing columns.

The code snippet shown below creates two new columns based on the Age column.

Sample output

creating new columns based on existing columns in pandas
creating new columns based on existing columns in pandas


Sometimes the logic to be applied for each value of an existing column may be a little complex to fit in one line, so we define a function for that and apply that function to each value of the column. The results are stored as a new column.

The code snippet shown below checks if the age of every person is greater than a given age or not, if yes, then that person is a senior employee otherwise a fresher!

The defined function takes two inputs, one first is the “inpAge”(the age of the person) and the “minAge” (the minimum age to be senior).

When you apply the “checkAge” function to the Age column with the help of apply() function, it calls the “checkAge” function once for each value of Age, which becomes the first input to the “checkAge” function, the second input is supplied in form of args tuple. If there are any more inputs, all of them will be supplied in the args tuple.

This produces a column result, we store it as “EmpType”, then assign it to the data frame as a new column.

Sample Output:

creating new columns based on existing column using a function in pandas
creating new columns based on an existing column using a function in pandas

Author Details
Lead Data Scientist
Farukh is an innovator in solving industry problems using Artificial intelligence. His expertise is backed with 10 years of industry experience. Being a senior data scientist he is responsible for designing the AI/ML solution to provide maximum gains for the clients. As a thought leader, his focus is on solving the key business problems of the CPG Industry. He has worked across different domains like Telecom, Insurance, and Logistics. He has worked with global tech leaders including Infosys, IBM, and Persistent systems. His passion to teach inspired him to create this website!

Leave a Reply!

Your email address will not be published. Required fields are marked *