Skip to content

REF: use _validate_fill_value in Index.insert #38102

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

Merged
merged 16 commits into from
Dec 13, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
Next Next commit
BUG: NumericIndex.insert(0, False) casting to int
  • Loading branch information
jbrockmendel committed Nov 24, 2020
commit 214820d7c6979e10219f432598ea892ee39e9caf
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,7 @@ Indexing
- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using listlike indexer that contains elements that are in the index's ``categories`` but not in the index itself failing to raise ``KeyError`` (:issue:`37901`)
- Bug in :meth:`DataFrame.iloc` and :meth:`Series.iloc` aligning objects in ``__setitem__`` (:issue:`22046`)
- Bug in :meth:`DataFrame.loc` did not raise ``KeyError`` when missing combination was given with ``slice(None)`` for remaining levels (:issue:`19556`)
- Bug on inserting a boolean label into a :class:`DataFrame` with a numeric :class:`Index` columns incorrectly casting to integer (:issue:`36319`)

Missing
^^^^^^^
Expand Down
17 changes: 10 additions & 7 deletions pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@ def _validate_fill_value(self, value):
raise TypeError
elif isinstance(value, str) or lib.is_complex(value):
raise TypeError
elif is_scalar(value) and isna(value):
if is_valid_nat_for_dtype(value, self.dtype):
value = self._na_value
else:
# NaT, np.datetime64("NaT"), np.timedelta64("NaT")
raise TypeError

return value

Expand Down Expand Up @@ -162,13 +168,10 @@ def _is_all_dates(self) -> bool:

@doc(Index.insert)
def insert(self, loc: int, item):
# treat NA values as nans:
if is_scalar(item) and isna(item):
if is_valid_nat_for_dtype(item, self.dtype):
item = self._na_value
else:
# NaT, np.datetime64("NaT"), np.timedelta64("NaT")
return self.astype(object).insert(loc, item)
try:
item = self._validate_fill_value(item)
except TypeError:
return self.astype(object).insert(loc, item)

return super().insert(loc, item)

Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/frame/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,20 @@ def test_setitem_complete_column_with_array(self):
)
tm.assert_frame_equal(df, expected)

@pytest.mark.parametrize("dtype", ["f8", "i8", "u8"])
def test_setitem_bool_with_numeric_index(self, dtype):
# GH#36319
cols = Index([1, 2, 3], dtype=dtype)
df = DataFrame(np.random.randn(3, 3), columns=cols)

df[False] = ["a", "b", "c"]

expected_cols = Index([1, 2, 3, False], dtype=object)
if dtype == "f8":
expected_cols = Index([1.0, 2.0, 3.0, False], dtype=object)

tm.assert_index_equal(df.columns, expected_cols)


class TestDataFrameSetItemSlicing:
def test_setitem_slice_position(self):
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexing/test_coercion.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ def test_insert_index_object(self, insert, coerced_val, coerced_dtype):
[
(1, 1, np.int64),
(1.1, 1.1, np.float64),
(False, 0, np.int64),
(False, False, object), # GH#36319
("x", "x", object),
],
)
Expand All @@ -409,7 +409,7 @@ def test_insert_index_int64(self, insert, coerced_val, coerced_dtype):
[
(1, 1.0, np.float64),
(1.1, 1.1, np.float64),
(False, 0.0, np.float64),
(False, False, object), # GH#36319
("x", "x", object),
],
)
Expand Down