Create Pandas column with the max of two calculated values from other columns

Viewed 1971

I want to create a column with the maximum value between 2 values calculated from other columns of the data frame.

import pandas as pd
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})

df['Max Col'] = max(df['A']*3, df['B']+df['A'])


ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

The desired outcome is a new df column ['Max Col'] with the maximum value of the above calculations.

I know there is the long solution of creating two new columns with the calculations and then apply .max(axis=1). I am looking for a straight solution.

Thanks.

3 Answers

Use np.maximum:

df['max'] =np.maximum(df['A']*3, df['B']+df['A'])

Output:

   A  B  max
0  1 -2    3
1  2  8   10
2  3  1    9
import pandas as pd
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
# map the max function to a zip of your calculations
df['max'] = list(map(max, zip(df['A']*3, df['B']+df['A'])))
print(df)

   A  B  max
0  1 -2    3
1  2  8   10
2  3  1    9

You can use the apply method -

df['max'] = df.apply(lambda x: max(x['A']*3, x['A'] + x['B']), axis=1)
Related