⚡️ Speed up function fillna
by 4,315%
#100
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 4,315% (43.15x) speedup for
fillna
insrc/numpy_pandas/dataframe_operations.py
⏱️ Runtime :
93.2 milliseconds
→2.11 milliseconds
(best of149
runs)📝 Explanation and details
The optimized code achieves a 43x speedup by replacing an inefficient row-by-row loop with vectorized pandas operations. Here are the key optimizations:
1. Eliminated Expensive Row-by-Row Operations
for i in range(len(df))
withdf.iloc[i][column]
andresult.iloc[i, col_idx] = value
inside the looppd.isna(df[column])
once and usesresult.iloc[mask.values, col_idx] = value
for batch assignment2. Moved Column Index Lookup Outside Loop
df.columns.get_loc(column)
inside the assignment (3,460 times in profiling)col_idx
once before the conditional logic3. Added Short-Circuit Logic
if mask.any():
to skip assignment entirely when no NaN values are presentPerformance Impact by Test Case:
The optimization leverages pandas' internal C implementations for boolean indexing and bulk assignment, which are orders of magnitude faster than Python's interpreted row-by-row operations. This is especially effective for the typical use case of filling multiple missing values in larger datasets.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-fillna-mfejxgdn
and push.