LeetCode 题解工作台

改变数据类型

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

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · Change Data Type core interview pattern

bolt

答案摘要

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

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

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 列的数据类型已转换为整数。
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
import pandas as pd


def changeDatatype(students: pd.DataFrame) -> pd.DataFrame:
    students['grade'] = students['grade'].astype(int)
    return students
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

改变数据类型题解:Change Data Type core i… | LeetCode #2886 简单