@@ -2916,15 +2916,23 @@ def union(self, other, sort=None):
2916
2916
self ._assert_can_do_setop (other )
2917
2917
other , result_name = self ._convert_can_do_setop (other )
2918
2918
2919
- if isinstance (self .dtype , CategoricalDtype ) and isinstance (
2920
- other .dtype , CategoricalDtype
2921
- ):
2922
- both_categories = self .categories # type: ignore[attr-defined]
2923
- # if ordered and unordered, we set categories to be unordered
2924
- ordered = False if self .ordered != other .ordered else None # type: ignore[attr-defined]
2925
- if len (self .categories ) != len (other .categories ) or any ( # type: ignore[attr-defined]
2926
- self .categories != other .categories # type: ignore[attr-defined]
2919
+ if self .dtype != other .dtype :
2920
+ if (
2921
+ isinstance (self , ABCMultiIndex )
2922
+ and not is_object_dtype (_unpack_nested_dtype (other ))
2923
+ and len (other ) > 0
2924
+ ):
2925
+ raise NotImplementedError (
2926
+ "Can only union MultiIndex with MultiIndex or Index of tuples, "
2927
+ "try mi.to_flat_index().union(other) instead."
2928
+ )
2929
+
2930
+ if isinstance (self , ABCCategoricalIndex ) and isinstance (
2931
+ other , ABCCategoricalIndex
2927
2932
):
2933
+ both_categories = self .categories
2934
+ # if ordered and unordered, we set categories to be unordered
2935
+ ordered = False if self .ordered != other .ordered else None
2928
2936
if ordered is False :
2929
2937
both_categories = union_categoricals (
2930
2938
[self .as_unordered (), other .as_unordered ()], # type: ignore[attr-defined]
@@ -2934,20 +2942,11 @@ def union(self, other, sort=None):
2934
2942
both_categories = union_categoricals (
2935
2943
[self , other ], sort_categories = True
2936
2944
).categories
2937
- # Convert both indexes to have the same categories
2938
- self = self .set_categories (both_categories , ordered = ordered ) # type: ignore[attr-defined]
2939
- other = other .set_categories (both_categories , ordered = ordered )
2945
+ # Convert both indexes to have the same categories
2946
+ self = self .set_categories (both_categories , ordered = ordered ) # type: ignore[attr-defined]
2947
+ other = other .set_categories (both_categories , ordered = ordered ) # type: ignore[attr-defined]
2948
+ return self .union (other , sort = sort )
2940
2949
2941
- elif self .dtype != other .dtype :
2942
- if (
2943
- isinstance (self , ABCMultiIndex )
2944
- and not is_object_dtype (_unpack_nested_dtype (other ))
2945
- and len (other ) > 0
2946
- ):
2947
- raise NotImplementedError (
2948
- "Can only union MultiIndex with MultiIndex or Index of tuples, "
2949
- "try mi.to_flat_index().union(other) instead."
2950
- )
2951
2950
self , other = self ._dti_setop_align_tzs (other , "union" )
2952
2951
2953
2952
dtype = self ._find_common_type_compat (other )
0 commit comments