You can use the following basic syntax to find the max value in each row of a pandas DataFrame:
df['max'] = df.max(axis=1)
This particular syntax creates a new column called max that contains the max value in each row of the DataFrame.
The following example shows how to use this syntax in practice.
Example: Find the Max Value in Each Row in Pandas
Suppose we have the following pandas DataFrame:
import pandas as pd
import numpy as np
#create DataFrame
df = pd.DataFrame({'points': [4, np.nan, 10, 2, 15, np.nan, 7, 22],
'rebounds': [np.nan, 3, 9, 7, 6, 8, 14, 10],
'assists': [10, 9, 4, 4, 3, 7, 10, 11]})
#view DataFrame
print(df)
points rebounds assists
0 4.0 NaN 10
1 NaN 3.0 9
2 10.0 9.0 4
3 2.0 7.0 4
4 15.0 6.0 3
5 NaN 8.0 7
6 7.0 14.0 10
7 22.0 10.0 11
We can use the following syntax to create a new column called max that contains the max value in each row:
#create new column that contains max value of each row
df['max'] = df.max(axis=1)
#view updated DataFrame
print(df)
points rebounds assists max
0 4.0 NaN 10 10.0
1 NaN 3.0 9 9.0
2 10.0 9.0 4 10.0
3 2.0 7.0 4 7.0
4 15.0 6.0 3 15.0
5 NaN 8.0 7 8.0
6 7.0 14.0 10 14.0
7 22.0 10.0 11 22.0
The new column called max contains the max value in each row.
For example, we can see:
- The max value in the first row is 10.
- The max value in the second row is 9.
- The max value in the third row is 10.
And so on.
Also notice that the max() function automatically ignores NaN values when determining the max value in each row.
You can also find the max value in each row for only specific columns.
For example, you can use the following syntax to find the max value in each row and only consider the points and rebounds columns:
#add new column that contains max value of each row for points and rebounds columns
df['max'] = df[['points', 'rebounds']].max(axis=1)
#view updated DataFrame
print(df)
points rebounds assists max
0 4.0 NaN 10 4.0
1 NaN 3.0 9 3.0
2 10.0 9.0 4 10.0
3 2.0 7.0 4 7.0
4 15.0 6.0 3 15.0
5 NaN 8.0 7 8.0
6 7.0 14.0 10 14.0
7 22.0 10.0 11 22.0
The column called max now contains the max value in each row for the points and rebounds columns only.
Note: You can find the complete documentation for the pandas max() function here.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
Pandas: How to Find Max Value Across Multiple Columns
Pandas: Return Row with Max Value in Particular Column
Pandas: How to Replace inf with Max Value