Informatics Practices · Ch 3 — Data Handling using Pandas – II
Calculating Median
Calculating Median
The median() function in Pandas returns the middle value of a dataset. For a DataFrame, calling .median() gives you the median of each numeric column individually. It works only on numeric data — if a column contains text or mixed types, it will be ignored or raise an error.
When you run print(df.median()), the output shows the median for every column that contains numbers. For example, if your DataFrame has columns for UT, Maths, Science, S.St, Hindi, and Eng, the output might look like the table below.
Notice that the median of the UT column is 2.5 — this is because the UT column contains values like 1 and 2, and with an even number of rows, the median is the average of the two middle values.
To find the median of a specific subject, say Mathematics, you first extract that column as a Series: dfMaths = df['Maths']. But if you want the median marks in Mathematics only for UT1, you need to filter the data. The textbook shows a step-by-step approach:
- Get the Maths column:
dfMaths = df['Maths'] - Filter rows where UT equals 1:
dfMathsUT1 = dfMaths[df.UT == 1] - Print the filtered data to see the actual marks:
print("Displaying the marks scored in Mathematics in UT1\n", dfMathsUT1) - Compute the median of this filtered Series:
dfMathMedian = dfMathsUT1.median() - Print the result:
print("Displaying the median of Mathematics in UT1\n", dfMathMedian)
The output for the example given is:
Displaying the marks of UT1, subject Mathematics
0 22
3 20
6 23
9 15
Name: Maths, dtype: int64
Displaying the median of Mathematics in UT1
21.0
The textbook explains that here the number of values is even (four marks: 22, 20, 23, 15). When sorted, the two middle values are 20 and 22. The median is the average of these two: (20 + 22) / 2 = 21.0.
The median is not affected by extreme values (outliers) the way the mean is. This makes it a more robust measure of central tendency when data has unusually high or low scores. …
| Column | Median |
|---|---|
| UT | 2.5 |
| Maths | 19.0 |
| Science | 20.0 |
| S.St | 19.5 |
| Hindi | 21.5 |
Write the statements to print the median marks of mathematics in UT1. This shows median() on a single filtered column, and works through why an even count of values makes the median the …