LeetCode 题解工作台
改变数据类型
DataFrame students +-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | | gra…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Change Data Type core interview pattern
答案摘要
import pandas as pd def changeDatatype(students: pd.DataFrame) -> pd.DataFrame:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Change Data Type core interview pattern 题型思路
题目描述
DataFrame students
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| student_id | int |
| name | object |
| age | int |
| grade | float |
+-------------+--------+
编写一个解决方案来纠正以下错误:
grade 列被存储为浮点数,将它转换为整数。
返回结果格式如下示例所示。
示例 1:
输入: DataFrame students: +------------+------+-----+-------+ | student_id | name | age | grade | +------------+------+-----+-------+ | 1 | Ava | 6 | 73.0 | | 2 | Kate | 15 | 87.0 | +------------+------+-----+-------+ 输出: +------------+------+-----+-------+ | student_id | name | age | grade | +------------+------+-----+-------+ | 1 | Ava | 6 | 73 | | 2 | Kate | 15 | 87 | +------------+------+-----+-------+ 解释: grade 列的数据类型已转换为整数。
解题思路
方法一
import pandas as pd
def changeDatatype(students: pd.DataFrame) -> pd.DataFrame:
students['grade'] = students['grade'].astype(int)
return students
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | and space complexity depend on DataFrame size; conversion is linear in the number of rows for each column. Multiple columns converted at once may slightly increase memory overhead but remains efficient for typical interview datasets. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Pay attention if candidates attempt type conversion with loops instead of vectorized pandas methods.
- question_mark
Look for correct handling of floating-point values to integers without rounding errors.
- question_mark
Watch if candidates validate the final DataFrame structure and dtypes after conversion.
常见陷阱
外企场景- error
Forgetting to convert all specified columns, leaving some floats unchanged.
- error
Using loops instead of pandas vectorized operations, which is slower and error-prone.
- error
Not verifying the output format, causing mismatches with expected result.
进阶变体
外企场景- arrow_right_alt
Converting multiple columns with different target types simultaneously.
- arrow_right_alt
Handling missing or NaN values in numeric columns during type conversion.
- arrow_right_alt
Converting categorical columns to object or category types for memory optimization.