Skip to content

Commit c2c11ee

Browse files
committed
BUG: permit str dtype -> IntegerDtype conversions
Resolves #25472.
1 parent c021d33 commit c2c11ee

File tree

3 files changed

+18
-12
lines changed

3 files changed

+18
-12
lines changed

doc/source/whatsnew/v1.4.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,7 @@ Conversion
417417
^^^^^^^^^^
418418
- Bug in :class:`UInt64Index` constructor when passing a list containing both positive integers small enough to cast to int64 and integers too large too hold in int64 (:issue:`42201`)
419419
- Bug in :class:`Series` constructor returning 0 for missing values with dtype ``int64`` and ``False`` for dtype ``bool`` (:issue:`43017`, :issue:`43018`)
420+
- Bug in :class:`IntegerDtype` not allowing coercion from string dtype (:issue:`25472`)
420421
-
421422

422423
Strings

pandas/core/arrays/integer.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
is_integer_dtype,
3333
is_list_like,
3434
is_object_dtype,
35+
is_string_dtype,
3536
pandas_dtype,
3637
)
3738
from pandas.core.dtypes.missing import isna
@@ -124,12 +125,10 @@ def safe_cast(values, dtype, copy: bool):
124125
Safely cast the values to the dtype if they
125126
are equivalent, meaning floats must be equivalent to the
126127
ints.
127-
128128
"""
129129
try:
130130
return values.astype(dtype, casting="safe", copy=copy)
131131
except TypeError as err:
132-
133132
casted = values.astype(dtype, copy=copy)
134133
if (casted == values).all():
135134
return casted
@@ -143,7 +142,7 @@ def coerce_to_array(
143142
values, dtype, mask=None, copy: bool = False
144143
) -> tuple[np.ndarray, np.ndarray]:
145144
"""
146-
Coerce the input values array to numpy arrays with a mask
145+
Coerce the input values array to numpy arrays with a mask.
147146
148147
Parameters
149148
----------
@@ -187,7 +186,8 @@ def coerce_to_array(
187186
return values, mask
188187

189188
values = np.array(values, copy=copy)
190-
if is_object_dtype(values):
189+
inferred_type = None
190+
if is_object_dtype(values) or is_string_dtype(values):
191191
inferred_type = lib.infer_dtype(values, skipna=True)
192192
if inferred_type == "empty":
193193
values = np.empty(len(values))
@@ -198,6 +198,8 @@ def coerce_to_array(
198198
"mixed-integer",
199199
"integer-na",
200200
"mixed-integer-float",
201+
"string",
202+
"unicode",
201203
]:
202204
raise TypeError(f"{values.dtype} cannot be converted to an IntegerDtype")
203205

@@ -230,7 +232,10 @@ def coerce_to_array(
230232
if mask.any():
231233
values = values.copy()
232234
values[mask] = 1
233-
values = safe_cast(values, dtype, copy=False)
235+
if inferred_type in ("string", "unicode"):
236+
# casts from str are always safe since they raise
237+
# a ValueError if the str cannot be parsed into an int
238+
values = values.astype(dtype, copy=copy)
234239
else:
235240
values = safe_cast(values, dtype, copy=False)
236241

pandas/core/dtypes/common.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -143,14 +143,14 @@ def ensure_python_int(value: int | np.integer) -> int:
143143

144144

145145
def classes(*klasses) -> Callable:
146-
"""evaluate if the tipo is a subclass of the klasses"""
146+
"""Evaluate if the tipo is a subclass of the klasses."""
147147
return lambda tipo: issubclass(tipo, klasses)
148148

149149

150150
def classes_and_not_datetimelike(*klasses) -> Callable:
151151
"""
152-
evaluate if the tipo is a subclass of the klasses
153-
and not a datetimelike
152+
Evaluate if the tipo is a subclass of the klasses
153+
and not a datetimelike.
154154
"""
155155
return lambda tipo: (
156156
issubclass(tipo, klasses)
@@ -674,7 +674,7 @@ def is_integer_dtype(arr_or_dtype) -> bool:
674674
"""
675675
Check whether the provided array or dtype is of an integer dtype.
676676
677-
Unlike in `in_any_int_dtype`, timedelta64 instances will return False.
677+
Unlike in `is_any_int_dtype`, timedelta64 instances will return False.
678678
679679
The nullable Integer dtypes (e.g. pandas.Int64Dtype) are also considered
680680
as integer by this function.
@@ -726,7 +726,7 @@ def is_signed_integer_dtype(arr_or_dtype) -> bool:
726726
"""
727727
Check whether the provided array or dtype is of a signed integer dtype.
728728
729-
Unlike in `in_any_int_dtype`, timedelta64 instances will return False.
729+
Unlike in `is_any_int_dtype`, timedelta64 instances will return False.
730730
731731
The nullable Integer dtypes (e.g. pandas.Int64Dtype) are also considered
732732
as integer by this function.
@@ -1521,7 +1521,7 @@ def is_complex_dtype(arr_or_dtype) -> bool:
15211521

15221522
def _is_dtype(arr_or_dtype, condition) -> bool:
15231523
"""
1524-
Return a boolean if the condition is satisfied for the arr_or_dtype.
1524+
Return true if the condition is satisfied for the arr_or_dtype.
15251525
15261526
Parameters
15271527
----------
@@ -1580,7 +1580,7 @@ def get_dtype(arr_or_dtype) -> DtypeObj:
15801580

15811581
def _is_dtype_type(arr_or_dtype, condition) -> bool:
15821582
"""
1583-
Return a boolean if the condition is satisfied for the arr_or_dtype.
1583+
Return true if the condition is satisfied for the arr_or_dtype.
15841584
15851585
Parameters
15861586
----------

0 commit comments

Comments
 (0)