LeetCode 题解工作台

填充缺失值

DataFrame products +-------------+--------+ | Column Name | Type | +-------------+--------+ | name | object | | quantity | int | | price | int | +----…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · Fill Missing Data core interview pattern

bolt

答案摘要

import pandas as pd def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

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。
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
import pandas as pd


def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame:
    products['quantity'] = products['quantity'].fillna(0)
    return products
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

填充缺失值题解:Fill Missing Data core … | LeetCode #2887 简单