-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2891-MethodChaining.py
More file actions
59 lines (54 loc) · 2.02 KB
/
2891-MethodChaining.py
File metadata and controls
59 lines (54 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# 2891. Method Chaining
# DataFrame animals
# +-------------+--------+
# | Column Name | Type |
# +-------------+--------+
# | 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.
# Example 1:
# Input:
# DataFrame animals:
# +----------+---------+-----+--------+
# | 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 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.
# In Pandas, method chaining enables us to perform operations on a DataFrame without breaking up each operation into a separate line or creating multiple temporary variables.
# Can you complete this task in just one line of code using method chaining?
import pandas as pd
def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
return animals[animals["weight"] > 100].sort_values(by='weight',ascending=False)[["name"]]
if __name__ == "__main__":
l = [
["Tatiana","Snake",98,464],
["Khaled","Giraffe",50,41],
["Alex","Leopard",6,328],
["Jonathan","Monkey",45,463],
["Stefan","Bear",100,50],
["Tommy","Panda",26,349],
]
print(findHeavyAnimals(pd.DataFrame(l,columns=["name","species","age","weight"])))