We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Method Chaining

Number: 3063

Difficulty: Easy

Paid? No

Companies: N/A


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:

  1. Filter the DataFrame (animals['weight'] > 100).
  2. Sort the filtered DataFrame by 'weight' in descending order.
  3. Select the 'name' column to generate the final result.

Code Solutions

# Filter animals with weight > 100, sort by weight descending, then select the "name" column.
result = animals[animals['weight'] > 100].sort_values('weight', ascending=False)[['name']]
# 'animals[animals['weight'] > 100]' filters rows with weight greater than 100.
# '.sort_values('weight', ascending=False)' sorts the filtered rows by weight in descending order.
# '[['name']]' selects only the "name" column from the sorted DataFrame.
← Back to All Questions