LeetCode 题解工作台

数据选取

DataFrame students +-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | +----…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · Select Data core interview pattern

bolt

答案摘要

import pandas as pd def selectData(students: pd.DataFrame) -> pd.DataFrame:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Select Data core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

DataFrame students
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| student_id  | int    |
| name        | object |
| age         | int    |
+-------------+--------+

编写一个解决方案,选择 student_id = 101 的学生的 name 和 age 并输出。

返回结果格式如下示例所示。

 

示例 1:

输入:
+------------+---------+-----+
| student_id | name    | age |
+------------+---------+-----+
| 101        | Ulysses | 13  |
| 53         | William | 10  |
| 128        | Henry   | 6   |
| 3          | Henry   | 11  |
+------------+---------+-----+
输出:
+---------+-----+
| name    | age | 
+---------+-----+
| Ulysses | 13  |
+---------+-----+
解释:
学生 Ulysses 的 student_id = 101,所以我们输出了他的 name 和 age。
lightbulb

解题思路

方法一

1
2
3
4
5
6
import pandas as pd


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

复杂度分析

指标
时间complexity depends on the method used; filtering a single row is generally O(n) in table size. Space complexity is minimal since only one row and two columns are selected.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect precise row filtering using the student_id column.

  • question_mark

    Check for column-specific selection to ensure only name and age are returned.

  • question_mark

    Notice if the candidate avoids unnecessary full-table selection or extra columns.

warning

常见陷阱

外企场景
  • error

    Selecting all columns instead of only name and age, returning more data than needed.

  • error

    Using incorrect conditions, e.g., filtering with the wrong student_id.

  • error

    Returning multiple rows when the query should only produce one row for student_id 101.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Select multiple students by providing a list of student_ids instead of a single ID.

  • arrow_right_alt

    Retrieve additional columns such as grade while still filtering by student_id.

  • arrow_right_alt

    Filter by conditions other than student_id, such as age greater than a certain value.

help

常见问题

外企场景

数据选取题解:Select Data core interv… | LeetCode #2880 简单