Skip to main content

Select Data from a DataFrame

Problem Description​

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

Examples​

Example 1:

Input:

+------------+---------+-----+
| student_id | name | age |
+------------+---------+-----+
| 101 | Ulysses | 13 |
| 53 | William | 10 |
| 128 | Henry | 6 |
| 3 | Henry | 11 |
+------------+---------+-----+

Output:

+---------+-----+
| name | age |
+---------+-----+
| Ulysses | 13 |
+---------+-----+

Intuition​

We can use the loc method of the DataFrame to select the rows where the student_id is 101 and then select the columns "name" and "age".

Solution Code​

Written by @Abhay:)
import pandas as pd

def selectData(students: pd.DataFrame) -> pd.DataFrame:
return students.loc[students['student_id'] == 101, ["name", "age"]]

References​