返回介绍

solution / 2800-2899 / 2891.Method Chaining / README_EN

发布于 2024-06-17 01:02:59 字数 2334 浏览 0 评论 0 收藏 0

2891. Method Chaining

中文文档

Description

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?

Solutions

Solution 1

import pandas as pd


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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文