2880 Select Data

Problem Statement

DataFrame students

Column NameType

student_id

int

name

object

age

int

Write a solution to select the name and age of the student with student_id = 101.

The result format is in the following example.

For the whole problem statement, please refer here.

Plans

  • Retrieve the student data from the DataFrame students.

  • Apply a filter to select the row where student_id is equal to 101.

  • Select only the name and age columns from the filtered data.

  • Return the resulting DataFrame.

Solution

import pandas as pd

def selectData(students: pd.DataFrame) -> pd.DataFrame:
    # Select the name and age of the student with student_id 101
    return students[students['student_id'] == 101][['name', 'age']]

Explanation

  1. Import Pandas

    • We start by importing the Pandas library, which provides data structures and operations for manipulating numerical tables and time series.

  2. Define the Function

    • We define a function selectData that takes a single argument students, which is a DataFrame containing student data.

  3. Filtering Data

    • We filter the DataFrame students using the condition students['student_id'] == 101.

    • This results in a new DataFrame filtered_students which contains only rows with a student_id equal to 101.

  4. Selecting Specific Columns

    • From the filtered DataFrame, we extract only the name and age columns by using double brackets: [['name', 'age']].

  5. Return the Result

    • The function returns the DataFrame containing the name and age of the student with student_id 101.

Last updated