Skip to content

Informatics Practices · Ch 3 — Data Handling using Pandas – II

Calculating Sum of Values

3.2.3

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:

NameUTMathsScienceS.StHindiEng
0Raman12221182021
1Raman22120172224
2Raman31419152423

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
``` …
Table 3.9Output of df.sum() -- sum of values per column
ColumnSum
NameRamanRamanRamanZuhaireZuhaireZuhaireAshravyAsh...
UT24
Maths231
Science237
S.St245
Hindi262
Eng246

dtype: object …

DefinitionProgram 3-4

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 …