Name Test English Maths Hindi Science Sumit 1 67 87 75 88 Sumit 2 76 78 72 82 Jyoti 1 77 83 60 87 Jyoti 2 69 89 68 65 Nidhi 1 56 78 65 69 Nidhi 2 67 86 89 91
Which of the following statements will sort the values of the above DataFrame 'df' by Name?
| Name | Test | English | Maths | Hindi | Science |
|---|---|---|---|---|---|
| Sumit | 1 | 67 | 87 | 75 | 88 |
| Sumit | 2 | 76 | 78 | 72 | 82 |
| Jyoti | 1 | 77 | 83 | 60 | 87 |
| Jyoti | 2 | 69 | 89 | 68 | 65 |
| Nidhi | 1 | 56 | 78 | 65 | 69 |
| Nidhi | 2 | 67 | 86 | 89 | 91 |
Which of the following statements will sort the values of the above DataFrame 'df' by Name?
Solution
DataFrame.sort_values(by=..., axis=0) sorts the rows according to the values in the column given in by. Here by=['Name'] with axis=0 reorders the rows alphabetically by Name, giving Jyoti, Nidhi, then Sumit. The default is axis=0, so it can also be written df.sort_values(by='Name').
Option 1: axis=1 sorts the columns, not the rows, using the values in a row label. It does not sort the data by Name.
Options 2 and 4: df.sort() is not a valid method in current pandas. The correct method is sort_values(), and in is also a Python keyword, so it cannot be used as a parameter name.
Related questions:
2025: 21 May Shift 1
2025: 21 May Shift 1
2025: 30 May Shift 2