Add Total and Percentage columns calculated from existing columns
Expt. No.15
Page No.30
Total and percentage columns
Aim
To write a Python program that creates a marks DataFrame for 5 students in 3 subjects and adds a Total and a Percentage column calculated from the existing columns.
Concepts used
Algorithm
- Create a DataFrame of 5 students with English, Maths and IP marks (out of 100 each).
- Total = English + Maths + IP (column arithmetic).
- Percentage = Total ÷ 3.
- Display the DataFrame.
Program
# Total and Percentage columns from existing columns import pandas as pd df = pd.DataFrame({"Name": ["Asha", "Rohan", "Ira", "Kabir", "Diya"], "English": [82, 67, 88, 74, 59], "Maths": [91, 58, 79, 85, 64], "IP": [95, 72, 90, 81, 70]})df["Total"] = df["English"] + df["Maths"] + df["IP"]df["Percentage"] = df["Total"] / 3print(df)
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python dataframe_total_percentage.py
Name English Maths IP Total Percentage
0 Asha 82 91 95 268 89.333333
1 Rohan 67 58 72 197 65.666667
2 Ira 88 79 90 257 85.666667
3 Kabir 74 85 81 240 80.000000
4 Diya 59 64 70 193 64.333333
✓ Printed by running this program, not typed by hand.
Result
The Total column was worked out for all 5 rows at once (e.g. Asha 82 + 91 + 95 = 268) and the Percentage column from it (Asha 89.33…), without any loop.
Viva voce: what the examiner may ask
01How is a column calculated from other columns?
With arithmetic on the columns, e.g. df["English"] + df["Maths"], which works row by row.
02Why is Percentage a float column?
Division with / gives decimal values.
03Where does a new column appear?
At the right end of the DataFrame.
Variations for the lab test
- Add a Result column: "Pass" where Percentage ≥ 33 (use Boolean indexing with loc).
- Add 5 grace marks to Maths for every student.
- Display only Name and Percentage.
! Common mistake Writing
df["Total"] = df["English"] + "Maths" + "IP" adds the text "Maths", not the column, and raises an error.