Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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'.