如何用Python的pandas库显示表格的指定行数

177 阅读1分钟

题目

DataFrame: employees
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| employee_id | int    |
| name        | object |
| department  | object |
| salary      | int    |
+-------------+--------+

编写一个解决方案,显示这个 DataFrame 的 3 行。

示例 1:

输入:
DataFrame employees
+-------------+-----------+-----------------------+--------+
| employee_id | name      | department            | salary |
+-------------+-----------+-----------------------+--------+
| 3           | Bob       | Operations            | 48675  |
| 90          | Alice     | Sales                 | 11096  |
| 9           | Tatiana   | Engineering           | 33805  |
| 60          | Annabelle | InformationTechnology | 37678  |
| 49          | Jonathan  | HumanResources        | 23793  |
| 43          | Khaled    | Administration        | 40454  |
+-------------+-----------+-----------------------+--------+
输出:
+-------------+---------+-------------+--------+
| employee_id | name    | department  | salary |
+-------------+---------+-------------+--------+
| 3           | Bob     | Operations  | 48675  |
| 90          | Alice   | Sales       | 11096  |
| 9           | Tatiana | Engineering | 33805  |
+-------------+---------+-------------+--------+
解释:
只有前 3 行被显示。

解决方案

1、审题,理解题意

这个问题给定一个DataFrame: employees表,表中有若干行数据,要求我们返回前 3 行。

先来温习下什么是DataFrame?DataFrame: 类似于电子表格或 SQL 表格的二维表结构。每一行代表一个单独的记录,每一列代表一个不同的属性。它的大小可变,旨在处理不同类型的数据的混合。

2、解题思路

我们可以使用DataFrame 的head 方法,实现返回前 n 行。如果省略 n,则默认为返回前 5 行。这对于概括或快速查看大型数据集的开头非常有用。

3、代码实现

import pandas as pd

def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
    return employees.head(3)       #返回DataFrame表的前三行数据

4、执行结果

实际结果与预期结果相符,验证通过。

image-20231025063838651