Problem Description
Given a DataFrame named animals with columns name, species, age, and weight, return the names of animals that weigh strictly more than 100 kilograms. The result must be sorted by weight in descending order, and the solution must be written in one chained line of code.
Key Insights
- Use method chaining in Pandas to filter, sort, and select columns in one statement.
- First, filter the rows where weight > 100.
- Then, sort the filtered results by the weight column in descending order.
- Finally, select only the name column for the output.
Space and Time Complexity
Time Complexity: O(n log n) due to the sorting operation on n rows.
Space Complexity: O(n) for storing the filtered DataFrame containing animals that weigh more than 100.
Solution
We use Pandas method chaining to perform the operations in a single line. The process is:
- Filter the DataFrame (animals['weight'] > 100).
- Sort the filtered DataFrame by 'weight' in descending order.
- Select the 'name' column to generate the final result.