GH-48972: [Python] Add errors='coerce' parameter to pyarrow.compute.cast #48994
+315
−48
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.
Rationale for this change
Currently,
pyarrow.compute.cast()raises an exception when encountering values that cannot be cast to the target type. This PR adds anerrorsparameter (similar topandas.to_numeric(errors='coerce')) to allow gracefully handling cast failures by converting them to null values.What changes are included in this PR?
errorsparameter tocast()function with options'raise'(default) and'coerce'errors='coerce', setsCastOptions.null_on_error = Trueto produce nulls for invalid castsis_castable()meta-function to check element-wise castabilitytest_coerce_cast.pyAre these changes tested?
Yes, added extensive tests covering:
safeparameterarray.cast(),chunked_array.cast())Are there any user-facing changes?
Yes - new
errorsparameter forpyarrow.compute.cast()and newis_castable()function.is_castablefunction and/orerrors=coerceoption tocast#48972