Skip to content

Commit 69e2cc5

Browse files
jbrockmendeljreback
authored andcommitted
Implement PeriodIndex.difference without object-dtype cast (#30697)
1 parent 51ce777 commit 69e2cc5

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

pandas/_testing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -619,7 +619,7 @@ def _get_ilevel_values(index, level):
619619
# accept level number only
620620
unique = index.levels[level]
621621
level_codes = index.codes[level]
622-
filled = take_1d(unique.values, level_codes, fill_value=unique._na_value)
622+
filled = take_1d(unique._values, level_codes, fill_value=unique._na_value)
623623
values = unique._shallow_copy(filled, name=index.names[level])
624624
return values
625625

pandas/core/indexes/period.py

+31-7
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
is_float_dtype,
1818
is_integer,
1919
is_integer_dtype,
20+
is_object_dtype,
2021
pandas_dtype,
2122
)
2223

@@ -588,13 +589,13 @@ def get_indexer_non_unique(self, target):
588589
return ensure_platform_int(indexer), missing
589590

590591
def _get_unique_index(self, dropna=False):
591-
"""
592-
wrap Index._get_unique_index to handle NaT
593-
"""
594-
res = super()._get_unique_index(dropna=dropna)
595-
if dropna:
596-
res = res.dropna()
597-
return res
592+
if self.is_unique and not dropna:
593+
return self
594+
595+
result = self._data.unique()
596+
if dropna and self.hasnans:
597+
result = result[~result.isna()]
598+
return self._shallow_copy(result)
598599

599600
def get_loc(self, key, method=None, tolerance=None):
600601
"""
@@ -809,6 +810,29 @@ def intersection(self, other, sort=False):
809810
result = self._shallow_copy(np.asarray(i8result, dtype=np.int64), name=res_name)
810811
return result
811812

813+
def difference(self, other, sort=None):
814+
self._validate_sort_keyword(sort)
815+
self._assert_can_do_setop(other)
816+
res_name = get_op_result_name(self, other)
817+
other = ensure_index(other)
818+
819+
if self.equals(other):
820+
# pass an empty PeriodArray with the appropriate dtype
821+
return self._shallow_copy(self._data[:0])
822+
823+
if is_object_dtype(other):
824+
return self.astype(object).difference(other).astype(self.dtype)
825+
826+
elif not is_dtype_equal(self.dtype, other.dtype):
827+
return self
828+
829+
i8self = Int64Index._simple_new(self.asi8)
830+
i8other = Int64Index._simple_new(other.asi8)
831+
i8result = i8self.difference(i8other, sort=sort)
832+
833+
result = self._shallow_copy(np.asarray(i8result, dtype=np.int64), name=res_name)
834+
return result
835+
812836
# ------------------------------------------------------------------------
813837

814838
def _apply_meta(self, rawarr):

0 commit comments

Comments
 (0)