Skip to content

BUG: NumericIndex.insert #43933

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 1 commit into from
Oct 9, 2021
Merged
Show file tree
Hide file tree
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
7 changes: 4 additions & 3 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6329,10 +6329,11 @@ def insert(self, loc: int, item) -> Index:

arr = np.asarray(self)

# Use Index constructor to ensure we get tuples cast correctly.
item = Index([item], dtype=self.dtype)._values
# Use constructor to ensure we get tuples cast correctly.
# Use self._constructor instead of Index to retain NumericIndex GH#43921
item = self._constructor([item], dtype=self.dtype)._values
idx = np.concatenate((arr[:loc], item, arr[loc:]))
return Index._with_infer(idx, name=self.name)
return self._constructor._with_infer(idx, name=self.name)

def drop(self, labels, errors: str_t = "raise") -> Index:
"""
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,13 +793,32 @@ def test_format(self, simple_index):
def test_numeric_compat(self):
pass # override Base method

def test_insert_non_na(self, simple_index):
# GH#43921 inserting an element that we know we can hold should
# not change dtype or type (except for RangeIndex)
index = simple_index

result = index.insert(0, index[0])

cls = type(index)
if cls is RangeIndex:
cls = Int64Index

expected = cls([index[0]] + list(index), dtype=index.dtype)
tm.assert_index_equal(result, expected)

def test_insert_na(self, nulls_fixture, simple_index):
# GH 18295 (test missing)
index = simple_index
na_val = nulls_fixture

if na_val is pd.NaT:
expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object)
elif type(index) is NumericIndex and index.dtype.kind == "f":
# GH#43921
expected = NumericIndex(
[index[0], np.nan] + list(index[1:]), dtype=index.dtype
)
else:
expected = Float64Index([index[0], np.nan] + list(index[1:]))

Expand Down