Informatics Practices · Ch 3 — Data Handling using Pandas – II
Calculating Sum of Values
Calculating Sum of Values
The sum() method in Pandas is used to calculate totals from a DataFrame. When called on the entire DataFrame without any column filter, it returns the sum of every column — including text columns. This is rarely useful, because concatenating strings is not a meaningful total.
For example, calling df.sum() on a DataFrame that contains both student names and marks will produce output like this.
The Name column shows all the name strings joined together, and the UT column (which likely contains unit test numbers) is also summed as a number. The dtype: object at the end tells you the result is a mix of types — not a clean numeric total.
To get a meaningful sum, you must specify the column you want. The syntax is straightforward:
df['Maths'].sum()
This returns the total marks in Mathematics across all students — in the example, 231.
If you need the total marks for a particular student, you first filter the DataFrame to that student's rows, then sum the relevant subject columns. The textbook demonstrates this with Raman.
dfRaman = df[df['Name'] == 'Raman']
print("Marks obtained by Raman in each test are:\n", dfRaman)
The output shows three rows — one for each unit test Raman appeared in:
| Name | UT | Maths | Science | S.St | Hindi | Eng | |
|---|---|---|---|---|---|---|---|
| 0 | Raman | 1 | 22 | 21 | 18 | 20 | 21 |
| 1 | Raman | 2 | 21 | 20 | 17 | 22 | 24 |
| 2 | Raman | 3 | 14 | 19 | 15 | 24 | 23 |
Now, to get Raman's total marks in each subject across all three tests, you select only the subject columns and call sum():
dfRaman[['Maths','Science','S.St','Hindi','Eng']].sum()
The result is a Series showing the column-wise totals:
Maths 57
Science 60
S.St 50
Hindi 66
Eng 68
dtype: int64
If instead you want Raman's total marks per unit test (i.e., row-wise totals), you use sum(axis=1). The axis=1 tells Pandas to sum across columns (horizontally) for each row.
dfRaman[['Maths','Science','S.St','Hindi','Eng']].sum(axis=1)
Output:
0 102
1 104
2 95
dtype: int64
``` …
| Column | Sum |
|---|---|
| Name | RamanRamanRamanZuhaireZuhaireZuhaireAshravyAsh... |
| UT | 24 |
| Maths | 231 |
| Science | 237 |
| S.St | 245 |
| Hindi | 262 |
| Eng | 246 |
dtype: object …
Write the python statement to print the total marks secured by Raman in each subject. This demonstrates sum() on a name-filtered DataFrame, both column-wise (per subject) and row-wi …