NaN and None in Pandas - Time & Space Complexity
We want to understand how the time needed to handle missing data in pandas changes as the data grows.
Specifically, how operations involving NaN and None values scale with the size of the data.
Analyze the time complexity of the following code snippet.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'A': [1, 2, None, 4, np.nan],
'B': [np.nan, 2, 3, None, 5]
})
# Check for missing values
missing = df.isna()
# Fill missing values
filled = df.fillna(0)
This code creates a DataFrame with missing values, checks which values are missing, and fills them with zero.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: pandas checks each cell to see if it is NaN or None.
- How many times: Once for every cell in the DataFrame (rows x columns).
As the number of rows and columns grows, the number of cells to check grows too.
| Input Size (n cells) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the number of cells; doubling cells doubles the work.
Time Complexity: O(n)
This means the time to check or fill missing values grows in a straight line with the number of cells.
[X] Wrong: "Checking for missing values is instant no matter how big the data is."
[OK] Correct: Each cell must be checked, so bigger data means more work and more time.
Understanding how missing data operations scale helps you write efficient data cleaning code, a key skill in data science roles.
"What if we only check for missing values in one column instead of the whole DataFrame? How would the time complexity change?"
Practice
NaN and None represent in a pandas DataFrame?Solution
Step 1: Understand the role of NaN and None in pandas
BothNaNandNoneare used to mark missing or null data in pandas DataFrames.Step 2: Differentiate from other DataFrame elements
They do not represent valid data, headers, or indexes but indicate absence of data.Final Answer:
Missing or null data values -> Option AQuick Check:
NaN and None = Missing data [OK]
- Thinking NaN is a valid number
- Confusing None with column names
- Assuming NaN is an index label
df?Solution
Step 1: Recall pandas functions for missing data
The correct function to check for missing values isisna(), which returns a boolean DataFrame indicating missing entries.Step 2: Identify incorrect options
notna()returns a boolean DataFrame indicating non-missing entries;isnan()andismissing()do not exist in pandas.Final Answer:
df.isna() -> Option AQuick Check:
Use isna() to find missing values [OK]
- Using non-existent df.isnan()
- Using df.notna() which checks non-missing values
- Trying df.ismissing() which is invalid
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': [1, np.nan, 3], 'B': [None, 2, 3]})
result = df.isna().sum().to_dict()What is the value of
result?Solution
Step 1: Identify missing values in each column
Column 'A' has onenp.nan(missing), column 'B' has oneNone(missing).Step 2: Use isna() and sum() to count missing per column
df.isna()marks missing as True,sum()counts Trues per column, resulting in {'A': 1, 'B': 1}.Final Answer:
{'A': 1, 'B': 1} -> Option DQuick Check:
Count missing with isna().sum() = {'A':1,'B':1} [OK]
- Ignoring None as missing in column B
- Confusing sum() to count non-missing
- Assuming np.nan and None are treated differently here
import pandas as pd
df = pd.DataFrame({'X': [1, None, 3]})
df['X'] = df['X'].fillna(0)
print(df)What is the output?
Solution
Step 1: Identify missing value in column 'X'
The second row hasNone, which pandas treats as missing (NaN).Step 2: Use fillna(0) to replace missing with zero
Thefillna(0)replaces the missing value with 0, so the DataFrame becomes 1, 0, 3.Final Answer:
X 0 1 1 0 2 3 -> Option CQuick Check:
fillna(0) replaces None with 0 [OK]
- Expecting None to remain after fillna
- Confusing fillna with dropna
- Assuming fillna changes non-missing values
df with columns 'A' and 'B' containing some NaN and None values. You want to replace all missing values in 'A' with the mean of 'A' and all missing values in 'B' with the string 'missing'. Which code correctly does this?Solution
Step 1: Replace missing in 'A' with its mean
Usedf['A'].fillna(df['A'].mean())and assign back to 'A' to update the column.Step 2: Replace missing in 'B' with 'missing'
Usedf['B'].fillna('missing')and assign back to 'B' to update that column.Step 3: Check other options for correctness
df.fillna({'A': df['A'].mean(), 'B': 'missing'}) does not assign back, so changes are not saved; df['A'].fillna(df['A'].mean()) df['B'].fillna('missing') also misses assignment; df.fillna(df.mean()) df['B'] = df['B'].fillna('missing') tries to fill numeric mean for all columns which fails for 'B'.Final Answer:
df['A'] = df['A'].fillna(df['A'].mean()) df['B'] = df['B'].fillna('missing') -> Option BQuick Check:
Assign fillna results back to columns [OK]
- Not assigning fillna result back to DataFrame
- Using fillna without specifying columns
- Trying to fill numeric mean into string column
Ready to prove it?
Pass the test and this pattern moves unknown
