2891 Method Chaining

Problem Statement

DataFrame animals

Column NameType

name

object

species

object

age

int

weight

int

Write a solution to list the names of animals that weigh strictly more than 100 kilograms.

Return the animals sorted by weight in descending order.

The result format is in the following example.

For the whole problem statement, please refer here.

Plans

  • Use pandas to handle the data.

  • Filter the DataFrame based on the weight condition.

  • Sort the filtered DataFrame by weight in descending order.

  • Return the names of animals that weigh strictly more than 100 kilograms, sorted by weight in descending order.

Solution

import pandas as pd

def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
    # Return the names of animals with a weight greater than 100, sorted by weight in descending order
    return animals[animals['weight'] > 100].sort_values(by='weight', ascending=False)[['name']]

Explanation

  1. Import Pandas

    • We start by importing the Pandas library, which provides data structures and operations for manipulating numerical tables and time series.

  2. Define the Function

    • We define a function findHeavyAnimals that takes a single argument animals, which is a DataFrame containing animal data.

  3. Filtering and Sorting

    • We use the [] operator to filter the DataFrame animals based on the condition animals['weight'] > 100.

    • We then use the sort_values method to sort the filtered DataFrame by the weight column in descending order.

    • The ascending=False argument specifies that we want to sort in descending order.

    • We use the [['name']] indexing to return only the name column of the sorted DataFrame.

  4. Return the Result

    • We return the names of animals that weigh strictly more than 100 kilograms, sorted by weight in descending order.

Last updated