Fill Missing Data
EasyUpdated: Aug 2, 2025
Practice on:
Problem
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.
Examples
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.
## Solution
### Method 1 – Pandas fillna
#### Intuition
We can use the `fillna` method in pandas to replace missing values (NaN) in the `quantity` column with 0. This is a direct and efficient way to handle missing data in a DataFrame.
#### Approach
1. Use the `fillna` method on the `quantity` column to replace NaN with 0.
2. Return the updated DataFrame.
#### Code
{{< code_tabs >}}
##### MySQL
```sql
-- Not applicable for this problem as it is a pandas/DataFrame problem.
PostgreSQL
-- Not applicable for this problem as it is a pandas/DataFrame problem.
Python (pandas)
def fill_missing_data(products: 'pd.DataFrame') -> 'pd.DataFrame':
products['quantity'] = products['quantity'].fillna(0)
return products
Complexity
- ⏰ Time complexity:
O(n), where n is the number of rows in the DataFrame, as each value in the column is checked once. - 🧺 Space complexity:
O(1), as the operation is done in-place (except for the returned DataFrame reference).