LeetCode 题解工作台
重命名列
DataFrame students +-------------+--------+ | Column Name | Type | +-------------+--------+ | id | int | | first | object | | last | object | | age | …
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Rename Columns core interview pattern
答案摘要
import pandas as pd def renameColumns(students: pd.DataFrame) -> pd.DataFrame:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Rename Columns core interview pattern 题型思路
题目描述
DataFrame students
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| id | int |
| first | object |
| last | object |
| age | int |
+-------------+--------+
编写一个解决方案,按以下方式重命名列:
id重命名为student_idfirst重命名为first_namelast重命名为last_nameage重命名为age_in_years
返回结果格式如下示例所示。
示例 1:
输入: +----+---------+----------+-----+ | id | first | last | age | +----+---------+----------+-----+ | 1 | Mason | King | 6 | | 2 | Ava | Wright | 7 | | 3 | Taylor | Hall | 16 | | 4 | Georgia | Thompson | 18 | | 5 | Thomas | Moore | 10 | +----+---------+----------+-----+ 输出: +------------+------------+-----------+--------------+ | student_id | first_name | last_name | age_in_years | +------------+------------+-----------+--------------+ | 1 | Mason | King | 6 | | 2 | Ava | Wright | 7 | | 3 | Taylor | Hall | 16 | | 4 | Georgia | Thompson | 18 | | 5 | Thomas | Moore | 10 | +------------+------------+-----------+--------------+ 解释: 列名已相应更换。
解题思路
方法一
import pandas as pd
def renameColumns(students: pd.DataFrame) -> pd.DataFrame:
students.rename(
columns={
'id': 'student_id',
'first': 'first_name',
'last': 'last_name',
'age': 'age_in_years',
},
inplace=True,
)
return students
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate's ability to use pandas effectively.
- question_mark
Efficiency in solving column renaming problems.
- question_mark
Awareness of built-in function optimization in pandas.
常见陷阱
外企场景- error
Forgetting to apply the `inplace=True` parameter, which would return a new DataFrame instead of modifying the original.
- error
Incorrectly specifying the dictionary, leading to mismatched or missed renames.
- error
Not handling edge cases like missing columns in the renaming dictionary.
进阶变体
外企场景- arrow_right_alt
Renaming columns with more complex transformations or additional data formatting.
- arrow_right_alt
Performing renaming on columns with special characters or spaces.
- arrow_right_alt
Renaming multiple columns in a single step, handling potential conflicts.