2887. 填充缺失值
2887. 填充缺失值
题目
DataFrame products
+-------------+--------+ | Column Name | Type | +-------------+--------+ | name | object | | quantity | int | | price | int | +-------------+--------+
Write a solution to fill in the missing value as 0 in the quantity column.
The result format is in the following example.
Example 1:
Input:
+-----------------+----------+-------+ | name | quantity | price | +-----------------+----------+-------+ | Wristwatch | None | 135 | | WirelessEarbuds | None | 821 | | GolfClubs | 779 | 9319 | | Printer | 849 | 3051 | +-----------------+----------+-------+Output:
+-----------------+----------+-------+ | name | quantity | price | +-----------------+----------+-------+ | Wristwatch | 0 | 135 | | WirelessEarbuds | 0 | 821 | | GolfClubs | 779 | 9319 | | Printer | 849 | 3051 | +-----------------+----------+-------+Explanation:
The quantity for Wristwatch and WirelessEarbuds are filled by 0.
题目大意
DataFrame products
+-------------+--------+ | Column Name | Type | +-------------+--------+ | name | object | | quantity | int | | price | int | +-------------+--------+
编写一个解决方案,在 quantity 列中将缺失的值填充为 0。
返回结果如下示例所示。
示例 1:
输入:
+-----------------+----------+-------+ | name | quantity | price | +-----------------+----------+-------+ | Wristwatch | None | 135 | | WirelessEarbuds | None | 821 | | GolfClubs | 779 | 9319 | | Printer | 849 | 3051 | +-----------------+----------+-------+输出:
+-----------------+----------+-------+ | name | quantity | price | +-----------------+----------+-------+ | Wristwatch | 0 | 135 | | WirelessEarbuds | 0 | 821 | | GolfClubs | 779 | 9319 | | Printer | 849 | 3051 | +-----------------+----------+-------+解释:
Toaster 和 Headphones 的数量被填充为 0。
解题思路
- 在 Pandas 中,可以使用
fillna()来指定用某个特定值填充缺失数据。 - 使用
products['quantity'].fillna(0, inplace=True)将quantity列中的所有NaN值填充为 0。 inplace=True表示直接在原数据框上修改,而不是返回修改后的副本。如果不想修改原数据框,可以去掉。- 处理完缺失值后,返回更新后的 DataFrame。
复杂度分析
- 时间复杂度:
O(n),其中n是 DataFrame 的行数,fillna()需要遍历所有的行,检查每个值是否是缺失值 (NaN)。 - 空间复杂度:
O(1),使用了inplace=True,因此fillna()操作直接修改原 DataFrame,没有额外的空间开销。
代码
import pandas as pd
def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame:
# 使用 fillna() 填充缺失值(NaN),填充值为 0
products['quantity'].fillna(0, inplace=True)
# 返回更新后的 DataFrame
return products
