2891 Method Chaining
Problem Statement
DataFrame animals
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
Explanation
Import Pandas
We start by importing the Pandas library, which provides data structures and operations for manipulating numerical tables and time series.
Define the Function
We define a function
findHeavyAnimals
that takes a single argumentanimals
, which is a DataFrame containing animal data.
Filtering and Sorting
We use the
[]
operator to filter the DataFrameanimals
based on the conditionanimals['weight'] > 100
.We then use the
sort_values
method to sort the filtered DataFrame by theweight
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 thename
column of the sorted DataFrame.
Return the Result
We return the names of animals that weigh strictly more than
100
kilograms, sorted by weight in descending order.
Last updated