We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Fill Missing Data

Number: 3070

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a DataFrame named products with columns: name, quantity, and price, the task is to fill any missing value in the quantity column with 0.


Key Insights

  • The focus is on identifying rows where the quantity is missing.
  • Replacing missing values with a default value (0) is a common data-cleaning step.
  • The problem can be solved using simple iteration or built-in functions available in many data-processing libraries.

Space and Time Complexity

Time Complexity: O(n), where n is the number of rows in the DataFrame. Space Complexity: O(1) in-place update if modifying the existing DataFrame, otherwise O(n) if creating a new copy.


Solution

The solution involves scanning through the products data and checking the quantity column for missing values (e.g., None in Python or null in JavaScript/Java). When a missing value is found, it is replaced with 0. In languages like Python with pandas, this can be achieved concisely using the fillna function. In other languages, you typically iterate over each record of a list or array and update the quantity field if it is missing. The approach makes use of simple conditional checking and direct assignment.


Code Solutions

import pandas as pd

def fill_missing_data(products: pd.DataFrame) -> pd.DataFrame:
    # Use fillna to replace missing values in the 'quantity' column with 0
    products['quantity'] = products['quantity'].fillna(0)
    return products

# Example usage:
# products_df = pd.DataFrame({
#     'name': ['Wristwatch', 'WirelessEarbuds', 'GolfClubs', 'Printer'],
#     'quantity': [None, None, 779, 849],
#     'price': [135, 821, 9319, 3051]
# })
# result = fill_missing_data(products_df)
# print(result)
← Back to All Questions