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

Difficulty: Easy


Problem Description

Write a solution to fill in the missing value as 0 in the quantity column of a DataFrame named products.


Key Insights

  • The quantity column may contain None values that need to be replaced.
  • The desired output is a DataFrame with 0 in place of any missing quantity values.

Space and Time Complexity

Time Complexity: O(n), where n is the number of rows in the DataFrame, as we need to iterate through each row to check and replace missing values.

Space Complexity: O(1), as we are modifying the existing DataFrame in place without using additional data structures proportional to the input size.


Solution

To solve this problem, we will use a DataFrame structure to represent the products. The main approach is to iterate through the quantity column and replace any None values with 0. This operation can be efficiently performed using built-in functions available in DataFrame libraries such as Pandas in Python.


Code Solutions

import pandas as pd

# Create the DataFrame with sample data
data = {
    'name': ['Wristwatch', 'WirelessEarbuds', 'GolfClubs', 'Printer'],
    'quantity': [None, None, 779, 849],
    'price': [135, 821, 9319, 3051]
}

products = pd.DataFrame(data)

# Fill missing values in the 'quantity' column with 0
products['quantity'] = products['quantity'].fillna(0)

# Display the updated DataFrame
print(products)
← Back to All Questions