LeetCode 题解工作台
填充缺失值
DataFrame products +-------------+--------+ | Column Name | Type | +-------------+--------+ | name | object | | quantity | int | | price | int | +----…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Fill Missing Data core interview pattern
答案摘要
import pandas as pd def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Fill Missing Data core interview pattern 题型思路
题目描述
DataFrame products
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| name | object |
| quantity | int |
| price | int |
+-------------+--------+
编写一个解决方案,在 quantity 列中将缺失的值填充为 0。
返回结果如下示例所示。
示例 1:
输入: +-----------------+----------+-------+ | name | quantity | price | +-----------------+----------+-------+ | Wristwatch | 32 | 135 | | WirelessEarbuds | None | 821 | | GolfClubs | None | 9319 | | Printer | 849 | 3051 | +-----------------+----------+-------+ 输出: +-----------------+----------+-------+ | name | quantity | price | +-----------------+----------+-------+ | Wristwatch | 32 | 135 | | WirelessEarbuds | 0 | 821 | | GolfClubs | 0 | 9319 | | Printer | 849 | 3051 | +-----------------+----------+-------+ 解释: Toaster 和 Headphones 的数量被填充为 0。
解题思路
方法一
import pandas as pd
def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame:
products['quantity'] = products['quantity'].fillna(0)
return products
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates knowledge of pandas and its functions for data cleaning.
- question_mark
The candidate can explain the trade-offs between using built-in functions and manual iteration for handling missing data.
- question_mark
The candidate showcases an understanding of dataset handling, especially in data cleaning tasks commonly encountered in data-related interviews.
常见陷阱
外企场景- error
Overcomplicating the problem by using manual iteration when pandas fillna() is more efficient.
- error
Failing to handle missing data appropriately by not filling missing values in a consistent and correct way.
- error
Not considering edge cases, such as if the entire column or dataset contains missing values.
进阶变体
外企场景- arrow_right_alt
Fill missing data with a specific value instead of zero.
- arrow_right_alt
Handle missing data for multiple columns, not just 'quantity'.
- arrow_right_alt
Implement the solution using different data structures such as lists or dictionaries.