2891. Method Chaining
DataFrame animals
Column Name | Type |
---|---|
name | object |
species | object |
age | int |
weight | int |
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:
name | species | age | weight |
---|---|---|---|
Tatiana | Snake | 98 | 464 |
Khaled | Giraffe | 50 | 41 |
Alex | Leopard | 6 | 328 |
Jonathan | Monkey | 45 | 463 |
Stefan | Bear | 100 | 50 |
Tommy | Panda | 26 | 349 |
Output:
name |
---|
Tatiana |
Jonathan |
Tommy |
Alex |
Explanation:
All animals weighing more than
should be included in the results table. Tatiana's weight is
, Jonathan's weight is , Tommy's weight is , and Alex's weight is . 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 functionfindHeavyAnimals
takes one parameter,animals
, which is expected to be a pandas DataFrame. The type hintpd.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 DataFrameanimals
to include only the rows where the value in the 'weight' column is greater than 100. The result is stored in theheavy_animals
DataFrame.sorted_animals = heavy_animals.sort_values(by='weight', ascending=False)
: Thesort_values
method is used to sort theheavy_animals
DataFrame by the 'weight' column in descending order. Theascending=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 thesorted_animals
DataFrame. This DataFrame contains the names of animals that weigh more than 100 kilograms, sorted by weight in descending order.