Skip to content

2891. Method Chaining

DataFrame animals

Column NameType
nameobject
speciesobject
ageint
weightint

Instructions

  • 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.

Example

Input:

namespeciesageweight
TatianaSnake98464
KhaledGiraffe5041
AlexLeopard6328
JonathanMonkey45463
StefanBear10050
TommyPanda26349

Output:

name
Tatiana
Jonathan
Tommy
Alex

Explanation:

All animals weighing more than 100 should be included in the results table.

Tatiana's weight is 464, Jonathan's weight is 463, Tommy's weight is 349, and Alex's weight is 328.

The results should be sorted in descending order of weight.

Submissions

python
import pandas as pd

def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
    heavy_animals = animals[animals['weight'] > 100]
    sorted_animals = heavy_animals.sort_values(by='weight', ascending=False)
    return sorted_animals[['name']]

Explanation

Python (Pandas)
Submitted by @noeyislearning
  • import pandas as pd: This line imports the pandas library, which is a powerful tool for data manipulation and analysis in Python, and aliases it as pd.
  • def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:: The function findHeavyAnimals takes one parameter, animals, which is expected to be a pandas DataFrame. The type hint pd.DataFrame is used for both the parameter and the return type, indicating that the function accepts a DataFrame as input and returns a DataFrame.
  • heavy_animals = animals[animals['weight'] > 100]: This line filters the input DataFrame animals to include only the rows where the value in the 'weight' column is greater than 100. The result is stored in the heavy_animals DataFrame.
  • sorted_animals = heavy_animals.sort_values(by='weight', ascending=False): The sort_values method is used to sort the heavy_animals DataFrame by the 'weight' column in descending order. The ascending=False argument specifies that the sorting should be done in descending order.
  • return sorted_animals[['name']]: The function returns a DataFrame containing only the 'name' column of the sorted_animals DataFrame. This DataFrame contains the names of animals that weigh more than 100 kilograms, sorted by weight in descending order.