@@ -2245,18 +2245,34 @@ def _get_reconciled_name_object(self, other):
2245
2245
return self ._shallow_copy (name = name )
2246
2246
return self
2247
2247
2248
- def union (self , other , sort = True ):
2248
+ def union (self , other , sort = None ):
2249
2249
"""
2250
2250
Form the union of two Index objects.
2251
2251
2252
2252
Parameters
2253
2253
----------
2254
2254
other : Index or array-like
2255
- sort : bool, default True
2256
- Sort the resulting index if possible
2255
+ sort : bool or None, default None
2256
+ Whether to sort the resulting Index.
2257
+
2258
+ * None : Sort the result, except when
2259
+
2260
+ 1. `self` and `other` are equal.
2261
+ 2. `self` or `other` has length 0.
2262
+ 3. Some values in `self` or `other` cannot be compared.
2263
+ A RuntimeWarning is issued in this case.
2264
+
2265
+ * True : sort the result. A TypeError is raised when the
2266
+ values cannot be compared.
2267
+ * False : do not sort the result.
2257
2268
2258
2269
.. versionadded:: 0.24.0
2259
2270
2271
+ .. versionchanged:: 0.24.0
2272
+
2273
+ Changed the default `sort` to None, matching the
2274
+ behavior of pandas 0.23.4 and earlier.
2275
+
2260
2276
Returns
2261
2277
-------
2262
2278
union : Index
@@ -2273,10 +2289,16 @@ def union(self, other, sort=True):
2273
2289
other = ensure_index (other )
2274
2290
2275
2291
if len (other ) == 0 or self .equals (other ):
2276
- return self ._get_reconciled_name_object (other )
2292
+ result = self ._get_reconciled_name_object (other )
2293
+ if sort :
2294
+ result = result .sort_values ()
2295
+ return result
2277
2296
2278
2297
if len (self ) == 0 :
2279
- return other ._get_reconciled_name_object (self )
2298
+ result = other ._get_reconciled_name_object (self )
2299
+ if sort :
2300
+ result = result .sort_values ()
2301
+ return result
2280
2302
2281
2303
# TODO: is_dtype_union_equal is a hack around
2282
2304
# 1. buggy set ops with duplicates (GH #13432)
@@ -2319,13 +2341,16 @@ def union(self, other, sort=True):
2319
2341
else :
2320
2342
result = lvals
2321
2343
2322
- if sort :
2344
+ if sort is None :
2323
2345
try :
2324
2346
result = sorting .safe_sort (result )
2325
2347
except TypeError as e :
2326
2348
warnings .warn ("{}, sort order is undefined for "
2327
2349
"incomparable objects" .format (e ),
2328
2350
RuntimeWarning , stacklevel = 3 )
2351
+ elif sort :
2352
+ # raise if not sortable.
2353
+ result = sorting .safe_sort (result )
2329
2354
2330
2355
# for subclasses
2331
2356
return self ._wrap_setop_result (other , result )
0 commit comments