This article will illustrate two methods that you can use to create a new column based on the value of another column within a Pandas DataFrame.

Sample DataFrame.

In this tutorial, we will use an example DataFrame as shown below:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/06/echo/word-image-183962-1.png" data-lazy- height="684" src="data:image/svg xml,” width=”476″>

Using Pandas Apply Function

The first and most practical way of adding a new column based on another is using the Pandas apply function.

Suppose we want to return the rating of a movie as a percentage, we can do:

def percentage(x):

return (x / 10) * 100

df[‘%_rating’] = df.imdb_rating.apply(percentage)

df

In the example above, we define a function that takes the current rating, divided by 10, and multiplies it by 100.

We then create a new column called ‘%_rating’ and pass the user-defined function as a parameter to the apply() function.

This should return the new DataFrame as shown:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/06/echo/word-image-183962-2.png" data-lazy- height="679" src="data:image/svg xml,” width=”539″>

Using Element-Wise Operation

We can also create a new column using an element-wise operation instead of the apply function.

An example is illustrated below:

df[‘%_rating’] = (df[‘imdb_rating’] / 10) * 100

df

The code above should return:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/06/echo/word-image-183962-3.png" data-lazy- height="681" src="data:image/svg xml,” width=”531″>

Conclusion

This article illustrated two main methods of creating a new column based on a value from another column in Pandas.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/06/echo/john-150×150.png62a2a3e682804.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list