Skip to content

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

Calculating Quartile

3.2.8

Calculating Quartile

The quantile() method on a DataFrame is the tool for calculating quartiles. A quartile divides a sorted dataset into four equal parts. The method takes a parameter q that specifies which quartile you want. The first quartile (Q1) corresponds to q = 0.25 — it marks the value below which 25% of the data falls. The second quartile (Q2) is the median, given by q = 0.50. The third quartile (Q3) is q = 0.75, below which 75% of the data lies.

If you call df.quantile() with no argument, it defaults to q = 0.5 and returns the median of every numeric column. For example, on a DataFrame df containing marks for five subjects, df.quantile() would output the median marks for Maths, Science, S.St, Hindi, and English.

To get a specific quartile, pass the q parameter. df.quantile(q=0.25) gives the first quartile for each column. df.quantile(q=0.75) gives the third quartile. The output is a Series with the column names as the index and the quartile value as the data, labelled with the q value you used.

You can also pass a list of quartiles to q to get multiple quartiles at once. For instance, dfSubject.quantile([0.25, 0.75]) returns a DataFrame where the rows are labelled 0.25 and 0.75, and the columns are the subject names. Each cell contains the corresponding quartile value for that subject.

Note

The quantile() method works only on numeric columns. If your DataFrame contains non-numeric data, those columns are ignored unless you explicitly select a subset of numeric columns first. …

Table 3.14Output of df.quantile() -- default (0.5, median)
ColumnValue
UT2.0
Maths20.5
Science19.5
S.St20.0
Hindi22.5
Eng21.5
Table 3.15Output of df.quantile(q=.25) -- first quartile
ColumnValue
UT1.00
Maths16.50
Science18.00
S.St18.75
Hindi20.75
Eng19.75
Table 3.16Output of df.quantile(q=.75) -- third quartile
ColumnValue
UT3.00
Maths22.25
Science21.25
S.St22.50
Hindi24.00
Eng23.00
DefinitionProgram 3-8

Write the statement to display the first and third quartiles of all subjects. This applies quantile([.25, .75]) across multiple subject columns at once, returning both quarti …