Pandas: How to Find Max Value Across Multiple Columns


You can use the following methods to find the max value across multiple columns in a pandas DataFrame:

Method 1: Find Max Value Across Multiple Columns

df[['col1', 'col2', 'col3']].max(axis=1)

Method 2: Add New Column Containing Max Value Across Multiple Columns

df['new_col'] = df[['col1', 'col2', 'col3']].max(axis=1)

The following examples show how to use each of these methods in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
                   'points': [28, 17, 19, 14, 23, 26, 5],
                   'rebounds': [5, 6, 4, 7, 14, 12, 9],
                   'assists': [10, 13, 7, 8, 4, 5, 8]})

#view DataFrame
print(df)

  player  points  rebounds  assists
0      A      28         5       10
1      B      17         6       13
2      C      19         4        7
3      D      14         7        8
4      E      23        14        4
5      F      26        12        5
6      G       5         9        8

Example 1: Find Max Value Across Multiple Columns

The following code shows how to find the max value in each row across the points and rebounds columns:

#find max value across points and rebounds columns
df[['points', 'rebounds']].max(axis=1)

0    28
1    17
2    19
3    14
4    23
5    26
6     9
dtype: int64

Here’s how to interpret the output:

  • The max value across the points and rebounds columns for the first row was 28.
  • The max value across the points and rebounds columns for the second row was 17.
  • The max value across the points and rebounds columns for the third row was 19.

And so on.

Example 2: Add New Column Containing Max Value Across Multiple Columns

The following code shows how to add a new column to the DataFrame that contains the max value in each row across the points and rebounds columns:

#add new column that contains max value across points and rebounds columns
df['max_points_rebs'] = df[['points', 'rebounds']].max(axis=1)

#view updated DataFrame
print(df)

  player  points  rebounds  assists  max_points_rebs
0      A      28         5       10               28
1      B      17         6       13               17
2      C      19         4        7               19
3      D      14         7        8               14
4      E      23        14        4               23
5      F      26        12        5               26
6      G       5         9        8                9

The new column titled max_points_rebs now contains the max value across the points and rebounds columns for each row in the DataFrame.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

Pandas: How to Move Column to Front of DataFrame
Pandas: How to Check if Column Contains String
Pandas: How to Add Empty Column to DataFrame

Leave a Reply

Your email address will not be published.