Ask Your Question
3

What is the method to perform a function on several columns of a data frame simultaneously?

asked 2021-10-26 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-05-12 15:00:00 +0000

devzero gravatar image

The method to perform a function on several columns in a data frame simultaneously is to use the apply() function with the axis parameter set to 1. This applies the function to each row of the data frame.

For example, to calculate the sum of two columns A and B of a data frame, you can write:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

df['sum'] = df.apply(lambda row: row['A'] + row['B'], axis=1)

print(df)

Output:

   A  B  sum
0  1  4    5
1  2  5    7
2  3  6    9

Here, the lambda function takes each row of the data frame and applies the sum function to the columns A and B, and stores the result in a new column 'sum'.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-26 11:00:00 +0000

Seen: 14 times

Last updated: May 12 '21