2879 Display the First Three Rows

Problem Statement

DataFrame employees

Column NameType

employee_id

int

name

object

department

object

salary

int

Write a solution to display the first 3 rows of this DataFrame.

For the whole problem statement, please refer here.

Plans

  • Review the columns and data types in the employees DataFrame.

  • Utilize a method to obtain only the top three entries of the DataFrame.

  • Ensure the output is in the correct DataFrame format.

Solution

import pandas as pd

def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
    
    # Return the first three rows of the dataframe
    return employees.head(3)

Explanation

  1. Import the Pandas Library

    • We begin by importing the Pandas library, which is essential for handling DataFrame structures in Python.

  2. Function Definition

    • We define a function named selectFirstRows that takes one parameter, employees, which is expected to be a DataFrame.

  3. Get the First Three Rows

    • Inside the function, we use the head() method provided by Pandas. This method returns the first n rows of the DataFrame, where n is specified as an argument (in this case, 3). This allows us to easily obtain the top three rows from the employees DataFrame.

  4. Return the Result

    • The function returns the first three rows of the DataFrame as the output.

Last updated