Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ Indexing
- Bug in assignment using a reverse slicer (:issue:`26939`)
- Bug in reindexing a :meth:`PeriodIndex` with another type of index that contained a `Period` (:issue:`28323`) (:issue:`28337`)
- Fix assignment of column via `.loc` with numpy non-ns datetime type (:issue:`27395`)
- Bug in :meth:`Float64Index.astype` where ``np.inf`` was not handled properly when casting to an integer dtype

Missing
^^^^^^^
Expand Down
9 changes: 5 additions & 4 deletions pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,12 +367,13 @@ def astype(self, dtype, copy=True):
"values are required for conversion"
).format(dtype=dtype)
raise TypeError(msg)
elif (
is_integer_dtype(dtype) and not is_extension_array_dtype(dtype)
) and self.hasnans:
elif is_integer_dtype(dtype) and not is_extension_array_dtype(dtype):
# TODO(jreback); this can change once we have an EA Index type
# GH 13149
raise ValueError("Cannot convert NA to integer")
if self.hasnans:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this re-use astype_nansafe? That should handle things, including the nullable-integer check.

raise ValueError("Cannot convert NA to integer")
elif not np.isfinite(self).all():
raise ValueError("Cannot convert infinity to integer")
return super().astype(dtype, copy=copy)

@Appender(_index_shared_docs["_convert_scalar_indexer"])
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/indexes/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,12 @@ def test_astype(self):
with pytest.raises(ValueError, match=msg):
i.astype(dtype)

def test_cannot_cast_inf_to_int(self):
idx = pd.Float64Index([1, 2, np.inf])

with pytest.raises(ValueError, match="Cannot convert infinity to integer"):
idx.astype(int)

def test_type_coercion_fail(self, any_int_dtype):
# see gh-15832
msg = "Trying to coerce float values to integers"
Expand Down