Skip to content

Commit c021d33

Browse files
authored
PERF: Index.insert (pandas-dev#43953)
1 parent aeebff4 commit c021d33

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

pandas/core/indexes/base.py

+16-5
Original file line numberDiff line numberDiff line change
@@ -6337,13 +6337,24 @@ def insert(self, loc: int, item) -> Index:
63376337
dtype = self._find_common_type_compat(item)
63386338
return self.astype(dtype).insert(loc, item)
63396339

6340-
arr = np.asarray(self)
6340+
arr = self._values
6341+
6342+
if arr.dtype != object or not isinstance(
6343+
item, (tuple, np.datetime64, np.timedelta64)
6344+
):
6345+
# with object-dtype we need to worry about numpy incorrectly casting
6346+
# dt64/td64 to integer, also about treating tuples as sequences
6347+
# special-casing dt64/td64 https://github.com/numpy/numpy/issues/12550
6348+
casted = arr.dtype.type(item)
6349+
new_values = np.insert(arr, loc, casted)
6350+
6351+
else:
6352+
new_values = np.insert(arr, loc, None)
6353+
new_values[loc] = item
63416354

6342-
# Use constructor to ensure we get tuples cast correctly.
63436355
# Use self._constructor instead of Index to retain NumericIndex GH#43921
6344-
item = self._constructor([item], dtype=self.dtype)._values
6345-
idx = np.concatenate((arr[:loc], item, arr[loc:]))
6346-
return self._constructor._with_infer(idx, name=self.name)
6356+
# TODO(2.0) can use Index instead of self._constructor
6357+
return self._constructor._with_infer(new_values, name=self.name)
63476358

63486359
def drop(self, labels, errors: str_t = "raise") -> Index:
63496360
"""

0 commit comments

Comments
 (0)