Categories
Python Answers

How to create new column based on values from other columns or apply a function of multiple columns, row-wise with Python Pandas?

Spread the love

Sometimes, we want to create new column based on values from other columns or apply a function of multiple columns, row-wise with Python Pandas.

In this article, we’ll look at how to create new column based on values from other columns or apply a function of multiple columns, row-wise with Python Pandas.

How to create new column based on values from other columns or apply a function of multiple columns, row-wise with Python Pandas?

To create new column based on values from other columns or apply a function of multiple columns, row-wise with Python Pandas, we can use the data frame apply method.

For instance, we write

import pandas as pd

df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
df['c'] = df.apply(lambda row: row.a + row.b, axis=1)

to call df.apply with a function that adds the value from columns a and b row-wise and assign the values to column c.

Conclusion

To create new column based on values from other columns or apply a function of multiple columns, row-wise with Python Pandas, we can use the data frame apply method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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