Skip to content

Enhance to_numeric to support hexadecimal, octal, and binary string inputs #59795

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 33 additions & 8 deletions pandas/core/tools/numeric.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations


from typing import (
TYPE_CHECKING,
Literal,
Expand Down Expand Up @@ -34,13 +35,25 @@
from pandas.core.arrays import BaseMaskedArray
from pandas.core.arrays.string_ import StringDtype

from pandas.core.dtypes.common import is_string_dtype

if TYPE_CHECKING:
from pandas._typing import (
DateTimeErrorChoices,
DtypeBackend,
npt,
)

def parse_numeric(value):
if isinstance(value, str):
try:
return int(value, 0) # Automatically detect radix
except ValueError:
try:
return float(value)
except ValueError:
return libmissing.NA
return value

def to_numeric(
arg,
Expand Down Expand Up @@ -161,6 +174,7 @@ def to_numeric(
2 3.0
dtype: Float32
"""

if downcast not in (None, "integer", "signed", "unsigned", "float"):
raise ValueError("invalid downcasting method provided")

Expand Down Expand Up @@ -215,14 +229,25 @@ def to_numeric(
else:
values = ensure_object(values)
coerce_numeric = errors != "raise"
values, new_mask = lib.maybe_convert_numeric( # type: ignore[call-overload]
values,
set(),
coerce_numeric=coerce_numeric,
convert_to_masked_nullable=dtype_backend is not lib.no_default
or isinstance(values_dtype, StringDtype)
and values_dtype.na_value is libmissing.NA,
)
parsed_values = []
new_mask = []

for idx, x in enumerate(values):
parsed_value = parse_numeric(x)
if libmissing.checknull(parsed_value):
if errors == 'raise':
raise ValueError(f"Unable to parse string '{x}' at position {idx}")
elif errors == 'coerce':
parsed_values.append(libmissing.NA)
new_mask.append(True)
continue
else:
parsed_values.append(parsed_value)
new_mask.append(False)

values = np.array(parsed_values, dtype=object)
new_mask = np.array(new_mask, dtype=bool)


if new_mask is not None:
# Remove unnecessary values, is expected later anyway and enables
Expand Down
Loading