ENH: Add safe_divide method to DataFrame and Series #62525
Closed
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.
Safe Divide Feature Implementation
Overview
This contribution adds a new
safe_divide
method to bothDataFrame
andSeries
classes in pandas, addressing a common pain point in data analysis workflows where division by zero frequently occurs.Problem Solved
Division by zero is a frequent issue in data analysis, especially when:
The current pandas division operations (
/
,truediv
,div
) raise exceptions when encountering division by zero, forcing users to write verbose workarounds or handle exceptions manually.Solution
The
safe_divide
method provides three modes for handling division by zero:'warn'
(default): Issues a warning and returnsinf
for division by zero'raise'
: Raises aZeroDivisionError
for division by zero (similar to current behavior)'ignore'
: Returnsinf
for division by zero without any warningFeatures
DataFrame.safe_divide()
axis
,level
,fill_value
)Series.safe_divide()
Usage Examples
Implementation Details
Files Modified
pandas/core/frame.py
- Addedsafe_divide
method to DataFrame classpandas/core/series.py
- Addedsafe_divide
method to Series classpandas/tests/frame/test_arithmetic.py
- Added comprehensive DataFrame testspandas/tests/series/test_arithmetic.py
- Added comprehensive Series testsKey Features
Test Coverage
Benefits
Impact
This feature addresses a significant pain point in pandas usage, particularly for:
The implementation is production-ready with comprehensive testing and follows pandas development best practices.