Informatics Practices · Ch 3 — Data Handling using Pandas – II
Calculating Maximum Values
Calculating Maximum Values
The max() method in Pandas returns the largest value from a DataFrame. It works on all data types — for numbers it gives the highest numeric value, and for strings it gives the alphabetically last name (like 'Zuhaire' coming after 'Raman').
When you call df.max() without any arguments, it calculates the maximum value for every column in the DataFrame, regardless of whether the column contains numbers or text. The output shows the maximum of each column in one result, with the data type of the entire result shown as dtype: object (because mixed types are involved).
If you only want the maximum values from numeric columns, use the numeric_only=True parameter:
print(df.max(numeric_only=True))
This returns only the columns that contain numbers (like UT, Maths, Science, S.St, Hindi, Eng), and the output's data type becomes dtype: int64 — a proper numeric type.
Finding maximum marks for a specific unit test
The textbook demonstrates this with Unit Test 2. First, you filter the DataFrame to keep only rows where UT == 2:
dfUT2 = df[df.UT == 2]
Then you apply max(numeric_only=True) on this filtered DataFrame:
print(dfUT2.max(numeric_only=True))
The output shows the highest marks obtained in each subject during Unit Test 2. For example, the maximum in Science was 22, in Hindi it was 25, and so on.
You can also combine both steps into a single line:
dfUT2 = df[df['UT'] == 2].max(numeric_only=True)
This is a compact way to filter and then immediately compute the maximum.
Row-wise vs column-wise maximum
By default, max() works column-wise — it finds the maximum value in each column. This is because the default axis is axis=0.
To find the maximum value for each row (i.e., the highest mark a student scored across all subjects), you set axis=1:
df.max(axis=1)
``` …
| Column | Max Value |
|---|---|
| Name | Zuhaire |
| UT | 3 |
| Maths | 24 |
| Science | 25 |
| S.St | 25 |
| Hindi | 25 |
| Column | Max Value |
|---|---|
| UT | 3 |
| Maths | 24 |
| Science | 25 |
| S.St | 25 |
| Hindi | 25 |
Write the statements to output the maximum marks obtained in each subject in Unit Test 2. This worked example filters the case-study DataFrame to a single unit test before taking the column-wise maximum, showing …
| Name | UT | Maths | Science | S.St | Hindi | Eng | |
|---|---|---|---|---|---|---|---|
| 1 | Raman | 2 | 21 | 20 | 17 | 22 | 24 |
| 4 | Zuhaire | 2 | 23 | 15 | 21 | 25 | 15 |
| 7 | Ashravy | 2 | 24 | 22 | 24 | 17 | 21 |
| Value | |
|---|---|
| UT | 2 |
| Maths | 24 |
| Science | 22 |
| S.St | 25 |
| Index | Max Value |
|---|---|
| 0 | 22 |
| 1 | 24 |
| 2 | 24 |
| 3 | 24 |
| 4 | 25 |
| 5 | 23 |
| 6 | 23 |
| 7 | 24 |
| 8 | 25 |
| 9 | 25 |