Skip to content
Programs · Program 3-9

Q.Write the statement which will sort the marks in English in the DataFrame df based on Unit Test 3, in descending order.

Tripura TbseTextbookSubjective· 2mImportance★★★★★
30% · 16/53 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Filter df to the Unit Test 3 rows, then use .sort_values(by=['Eng'], ascending=False) to sort those rows by the Eng column from highest to lowest. sort_values()'s general form is DataFrame.sort_values(by, axis=0, ascending=True) — ascending=True is the default, which is why reversing the order needs ascending=False to be passed explicitly.

Step 1 — filter to Unit Test 3

dfUT3 = df[df.UT == 3]

Step 2 — sort by English marks, descending

print(dfUT3.sort_values(by=['Eng'], ascending=False))

Output:

     Name    UT  Maths  Science  S.St  Hindi  Eng
2    Raman    3    14      19      15    24   23
8    Ashravy  3    12      25      19    21   23
11   Mishti   3    17      18      20    25   20
5    Zuhaire  3    22      18      19    23   13

Reading the tie

Raman and Ashravy both scored 23 in English — a genuine tie. sort_values() is a stable sort, meaning it never reorders rows that compare equal; it simply preserves whichever order they were already in before sorting (their original row index: Raman = 2, Ashravy = 8). That's why Raman prints first here — not because of anything about Raman himself, but purely because his row came first in df to begin with.

Breaking a tie deliberately — the book's own follow-up example

If you do want to control how ties are broken rather than leave it to original row order, sort_values() accepts more than one column in by. The chapter demonstrates this on the same UT3 slice, sorting by Science first and using Hindi as the tie-breaker:

print(dfUT3.sort_values(by=['Science', 'Hindi']))
     Name    UT  Maths  Science  S.St  Hindi  Eng
5    Zuhaire  3    22      18      19    23   13
11   Mishti   3    17      18      20    25   20 …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.