Consider the following table:
Priya Richa Rohit Soham Riya Maths 85 87 84 76 90 Science 86 76 86 66 92 Hindi 92 91 83 68 97 English 90 81 90 75 94
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']]
Consider the following table:
| Priya | Richa | Rohit | Soham | Riya | |
|---|---|---|---|---|---|
| Maths | 85 | 87 | 84 | 76 | 90 |
| Science | 86 | 76 | 86 | 66 | 92 |
| Hindi | 92 | 91 | 83 | 68 | 97 |
| English | 90 | 81 | 90 | 75 | 94 |
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
(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.
Related questions:
2025: 15 May Shift 2