Skip to main contentSkip to solution

Consider the following table:

PriyaRichaRohitSohamRiya
Maths8587847690
Science8676866692
Hindi9291836897
English9081907594

Which code represents the creation of a slice containing 'Priya' and 'Richa' marks in 'Maths' and 'Science' if the dataframe is represented using 'df' ?

(A). df.loc['Maths', 'Science', 'Priya' : 'Richa']

(B). df.loc['Maths' : 'Science', 'Priya', 'Richa']

(C). df.loc['Maths': 'Science', ['Priya', 'Richa']]

(D). df.loc[['Maths', 'Science'], ['Priya', 'Richa']]

Solution

✅ Correct Option: 2

(C) and (D) both work. In df.loc[rows, columns], the first argument selects rows and the second selects columns.

(C) 'Maths':'Science' is a label slice. Label slices in loc include both ends, and Maths and Science are adjacent rows, so exactly these two rows are selected. ['Priya', 'Richa'] is a list of column labels, which picks those two columns.

(D) Both the rows and the columns are given as lists of labels, so the result is the same 2 x 2 block.


(A) and (B): loc accepts only a row selector and a column selector. Passing three separate arguments raises an error (too many indexers).

In (A), 'Priya':'Richa' is a valid slice, but it is not the problem. The problem is that 'Maths', 'Science' and the slice are passed as three separate arguments.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question