We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Select Data

Difficulty: Easy


Problem Description

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


Key Insights

  • The task requires filtering data based on a specific condition (student_id = 101).
  • We need to return only specific columns (name and age) from the resulting filtered data.
  • This is a straightforward query operation commonly used in data manipulation tasks.

Space and Time Complexity

Time Complexity: O(n), where n is the number of rows in the DataFrame, as we may need to check each row to find the matching student_id. Space Complexity: O(1), as we are not using any additional data structures that scale with input size.


Solution

The solution involves querying the DataFrame to filter for the row where student_id is 101. We then select the name and age columns from this filtered row. The primary data structure used here is a DataFrame, which allows for efficient querying and manipulation of tabular data.


Code Solutions

import pandas as pd

# Sample DataFrame creation
students = pd.DataFrame({
    'student_id': [101, 53, 128, 3],
    'name': ['Ulysses', 'William', 'Henry', 'Henry'],
    'age': [13, 10, 6, 11]
})

# Filter the DataFrame for student_id = 101
result = students[students['student_id'] == 101][['name', 'age']]

# Display the result
print(result)
← Back to All Questions