test_setops.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. import numpy as np
  2. import pytest
  3. import pandas as pd
  4. from pandas import (
  5. CategoricalIndex,
  6. DataFrame,
  7. Index,
  8. IntervalIndex,
  9. MultiIndex,
  10. Series,
  11. )
  12. import pandas._testing as tm
  13. from pandas.api.types import (
  14. is_float_dtype,
  15. is_unsigned_integer_dtype,
  16. )
  17. @pytest.mark.parametrize("case", [0.5, "xxx"])
  18. @pytest.mark.parametrize(
  19. "method", ["intersection", "union", "difference", "symmetric_difference"]
  20. )
  21. def test_set_ops_error_cases(idx, case, sort, method):
  22. # non-iterable input
  23. msg = "Input must be Index or array-like"
  24. with pytest.raises(TypeError, match=msg):
  25. getattr(idx, method)(case, sort=sort)
  26. @pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list])
  27. def test_intersection_base(idx, sort, klass):
  28. first = idx[2::-1] # first 3 elements reversed
  29. second = idx[:5]
  30. if klass is not MultiIndex:
  31. second = klass(second.values)
  32. intersect = first.intersection(second, sort=sort)
  33. if sort is None:
  34. expected = first.sort_values()
  35. else:
  36. expected = first
  37. tm.assert_index_equal(intersect, expected)
  38. msg = "other must be a MultiIndex or a list of tuples"
  39. with pytest.raises(TypeError, match=msg):
  40. first.intersection([1, 2, 3], sort=sort)
  41. @pytest.mark.arm_slow
  42. @pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list])
  43. def test_union_base(idx, sort, klass):
  44. first = idx[::-1]
  45. second = idx[:5]
  46. if klass is not MultiIndex:
  47. second = klass(second.values)
  48. union = first.union(second, sort=sort)
  49. if sort is None:
  50. expected = first.sort_values()
  51. else:
  52. expected = first
  53. tm.assert_index_equal(union, expected)
  54. msg = "other must be a MultiIndex or a list of tuples"
  55. with pytest.raises(TypeError, match=msg):
  56. first.union([1, 2, 3], sort=sort)
  57. def test_difference_base(idx, sort):
  58. second = idx[4:]
  59. answer = idx[:4]
  60. result = idx.difference(second, sort=sort)
  61. if sort is None:
  62. answer = answer.sort_values()
  63. assert result.equals(answer)
  64. tm.assert_index_equal(result, answer)
  65. # GH 10149
  66. cases = [klass(second.values) for klass in [np.array, Series, list]]
  67. for case in cases:
  68. result = idx.difference(case, sort=sort)
  69. tm.assert_index_equal(result, answer)
  70. msg = "other must be a MultiIndex or a list of tuples"
  71. with pytest.raises(TypeError, match=msg):
  72. idx.difference([1, 2, 3], sort=sort)
  73. def test_symmetric_difference(idx, sort):
  74. first = idx[1:]
  75. second = idx[:-1]
  76. answer = idx[[-1, 0]]
  77. result = first.symmetric_difference(second, sort=sort)
  78. if sort is None:
  79. answer = answer.sort_values()
  80. tm.assert_index_equal(result, answer)
  81. # GH 10149
  82. cases = [klass(second.values) for klass in [np.array, Series, list]]
  83. for case in cases:
  84. result = first.symmetric_difference(case, sort=sort)
  85. tm.assert_index_equal(result, answer)
  86. msg = "other must be a MultiIndex or a list of tuples"
  87. with pytest.raises(TypeError, match=msg):
  88. first.symmetric_difference([1, 2, 3], sort=sort)
  89. def test_multiindex_symmetric_difference():
  90. # GH 13490
  91. idx = MultiIndex.from_product([["a", "b"], ["A", "B"]], names=["a", "b"])
  92. result = idx.symmetric_difference(idx)
  93. assert result.names == idx.names
  94. idx2 = idx.copy().rename(["A", "B"])
  95. result = idx.symmetric_difference(idx2)
  96. assert result.names == [None, None]
  97. def test_empty(idx):
  98. # GH 15270
  99. assert not idx.empty
  100. assert idx[:0].empty
  101. def test_difference(idx, sort):
  102. first = idx
  103. result = first.difference(idx[-3:], sort=sort)
  104. vals = idx[:-3].values
  105. if sort is None:
  106. vals = sorted(vals)
  107. expected = MultiIndex.from_tuples(vals, sortorder=0, names=idx.names)
  108. assert isinstance(result, MultiIndex)
  109. assert result.equals(expected)
  110. assert result.names == idx.names
  111. tm.assert_index_equal(result, expected)
  112. # empty difference: reflexive
  113. result = idx.difference(idx, sort=sort)
  114. expected = idx[:0]
  115. assert result.equals(expected)
  116. assert result.names == idx.names
  117. # empty difference: superset
  118. result = idx[-3:].difference(idx, sort=sort)
  119. expected = idx[:0]
  120. assert result.equals(expected)
  121. assert result.names == idx.names
  122. # empty difference: degenerate
  123. result = idx[:0].difference(idx, sort=sort)
  124. expected = idx[:0]
  125. assert result.equals(expected)
  126. assert result.names == idx.names
  127. # names not the same
  128. chunklet = idx[-3:]
  129. chunklet.names = ["foo", "baz"]
  130. result = first.difference(chunklet, sort=sort)
  131. assert result.names == (None, None)
  132. # empty, but non-equal
  133. result = idx.difference(idx.sortlevel(1)[0], sort=sort)
  134. assert len(result) == 0
  135. # raise Exception called with non-MultiIndex
  136. result = first.difference(first.values, sort=sort)
  137. assert result.equals(first[:0])
  138. # name from empty array
  139. result = first.difference([], sort=sort)
  140. assert first.equals(result)
  141. assert first.names == result.names
  142. # name from non-empty array
  143. result = first.difference([("foo", "one")], sort=sort)
  144. expected = MultiIndex.from_tuples(
  145. [("bar", "one"), ("baz", "two"), ("foo", "two"), ("qux", "one"), ("qux", "two")]
  146. )
  147. expected.names = first.names
  148. assert first.names == result.names
  149. msg = "other must be a MultiIndex or a list of tuples"
  150. with pytest.raises(TypeError, match=msg):
  151. first.difference([1, 2, 3, 4, 5], sort=sort)
  152. def test_difference_sort_special():
  153. # GH-24959
  154. idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
  155. # sort=None, the default
  156. result = idx.difference([])
  157. tm.assert_index_equal(result, idx)
  158. def test_difference_sort_special_true():
  159. # TODO(GH#25151): decide on True behaviour
  160. idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
  161. result = idx.difference([], sort=True)
  162. expected = MultiIndex.from_product([[0, 1], ["a", "b"]])
  163. tm.assert_index_equal(result, expected)
  164. def test_difference_sort_incomparable():
  165. # GH-24959
  166. idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]])
  167. other = MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]])
  168. # sort=None, the default
  169. msg = "sort order is undefined for incomparable objects"
  170. with tm.assert_produces_warning(RuntimeWarning, match=msg):
  171. result = idx.difference(other)
  172. tm.assert_index_equal(result, idx)
  173. # sort=False
  174. result = idx.difference(other, sort=False)
  175. tm.assert_index_equal(result, idx)
  176. def test_difference_sort_incomparable_true():
  177. idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]])
  178. other = MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]])
  179. # TODO: this is raising in constructing a Categorical when calling
  180. # algos.safe_sort. Should we catch and re-raise with a better message?
  181. msg = "'values' is not ordered, please explicitly specify the categories order "
  182. with pytest.raises(TypeError, match=msg):
  183. idx.difference(other, sort=True)
  184. def test_union(idx, sort):
  185. piece1 = idx[:5][::-1]
  186. piece2 = idx[3:]
  187. the_union = piece1.union(piece2, sort=sort)
  188. if sort is None:
  189. tm.assert_index_equal(the_union, idx.sort_values())
  190. assert tm.equalContents(the_union, idx)
  191. # corner case, pass self or empty thing:
  192. the_union = idx.union(idx, sort=sort)
  193. tm.assert_index_equal(the_union, idx)
  194. the_union = idx.union(idx[:0], sort=sort)
  195. tm.assert_index_equal(the_union, idx)
  196. tuples = idx.values
  197. result = idx[:4].union(tuples[4:], sort=sort)
  198. if sort is None:
  199. tm.equalContents(result, idx)
  200. else:
  201. assert result.equals(idx)
  202. def test_union_with_regular_index(idx):
  203. other = Index(["A", "B", "C"])
  204. result = other.union(idx)
  205. assert ("foo", "one") in result
  206. assert "B" in result
  207. msg = "The values in the array are unorderable"
  208. with tm.assert_produces_warning(RuntimeWarning, match=msg):
  209. result2 = idx.union(other)
  210. # This is more consistent now, if sorting fails then we don't sort at all
  211. # in the MultiIndex case.
  212. assert not result.equals(result2)
  213. def test_intersection(idx, sort):
  214. piece1 = idx[:5][::-1]
  215. piece2 = idx[3:]
  216. the_int = piece1.intersection(piece2, sort=sort)
  217. if sort is None:
  218. tm.assert_index_equal(the_int, idx[3:5])
  219. assert tm.equalContents(the_int, idx[3:5])
  220. # corner case, pass self
  221. the_int = idx.intersection(idx, sort=sort)
  222. tm.assert_index_equal(the_int, idx)
  223. # empty intersection: disjoint
  224. empty = idx[:2].intersection(idx[2:], sort=sort)
  225. expected = idx[:0]
  226. assert empty.equals(expected)
  227. tuples = idx.values
  228. result = idx.intersection(tuples)
  229. assert result.equals(idx)
  230. @pytest.mark.parametrize(
  231. "method", ["intersection", "union", "difference", "symmetric_difference"]
  232. )
  233. def test_setop_with_categorical(idx, sort, method):
  234. other = idx.to_flat_index().astype("category")
  235. res_names = [None] * idx.nlevels
  236. result = getattr(idx, method)(other, sort=sort)
  237. expected = getattr(idx, method)(idx, sort=sort).rename(res_names)
  238. tm.assert_index_equal(result, expected)
  239. result = getattr(idx, method)(other[:5], sort=sort)
  240. expected = getattr(idx, method)(idx[:5], sort=sort).rename(res_names)
  241. tm.assert_index_equal(result, expected)
  242. def test_intersection_non_object(idx, sort):
  243. other = Index(range(3), name="foo")
  244. result = idx.intersection(other, sort=sort)
  245. expected = MultiIndex(levels=idx.levels, codes=[[]] * idx.nlevels, names=None)
  246. tm.assert_index_equal(result, expected, exact=True)
  247. # if we pass a length-0 ndarray (i.e. no name, we retain our idx.name)
  248. result = idx.intersection(np.asarray(other)[:0], sort=sort)
  249. expected = MultiIndex(levels=idx.levels, codes=[[]] * idx.nlevels, names=idx.names)
  250. tm.assert_index_equal(result, expected, exact=True)
  251. msg = "other must be a MultiIndex or a list of tuples"
  252. with pytest.raises(TypeError, match=msg):
  253. # With non-zero length non-index, we try and fail to convert to tuples
  254. idx.intersection(np.asarray(other), sort=sort)
  255. def test_intersect_equal_sort():
  256. # GH-24959
  257. idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
  258. tm.assert_index_equal(idx.intersection(idx, sort=False), idx)
  259. tm.assert_index_equal(idx.intersection(idx, sort=None), idx)
  260. def test_intersect_equal_sort_true():
  261. idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
  262. expected = MultiIndex.from_product([[0, 1], ["a", "b"]])
  263. result = idx.intersection(idx, sort=True)
  264. tm.assert_index_equal(result, expected)
  265. @pytest.mark.parametrize("slice_", [slice(None), slice(0)])
  266. def test_union_sort_other_empty(slice_):
  267. # https://github.com/pandas-dev/pandas/issues/24959
  268. idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
  269. # default, sort=None
  270. other = idx[slice_]
  271. tm.assert_index_equal(idx.union(other), idx)
  272. tm.assert_index_equal(other.union(idx), idx)
  273. # sort=False
  274. tm.assert_index_equal(idx.union(other, sort=False), idx)
  275. def test_union_sort_other_empty_sort():
  276. # TODO(GH#25151): decide on True behaviour
  277. # # sort=True
  278. idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
  279. other = idx[:0]
  280. result = idx.union(other, sort=True)
  281. expected = MultiIndex.from_product([[0, 1], ["a", "b"]])
  282. tm.assert_index_equal(result, expected)
  283. def test_union_sort_other_incomparable():
  284. # https://github.com/pandas-dev/pandas/issues/24959
  285. idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]])
  286. # default, sort=None
  287. with tm.assert_produces_warning(RuntimeWarning):
  288. result = idx.union(idx[:1])
  289. tm.assert_index_equal(result, idx)
  290. # sort=False
  291. result = idx.union(idx[:1], sort=False)
  292. tm.assert_index_equal(result, idx)
  293. def test_union_sort_other_incomparable_sort():
  294. idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]])
  295. msg = "'<' not supported between instances of 'Timestamp' and 'int'"
  296. with pytest.raises(TypeError, match=msg):
  297. idx.union(idx[:1], sort=True)
  298. def test_union_non_object_dtype_raises():
  299. # GH#32646 raise NotImplementedError instead of less-informative error
  300. mi = MultiIndex.from_product([["a", "b"], [1, 2]])
  301. idx = mi.levels[1]
  302. msg = "Can only union MultiIndex with MultiIndex or Index of tuples"
  303. with pytest.raises(NotImplementedError, match=msg):
  304. mi.union(idx)
  305. def test_union_empty_self_different_names():
  306. # GH#38423
  307. mi = MultiIndex.from_arrays([[]])
  308. mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
  309. result = mi.union(mi2)
  310. expected = MultiIndex.from_arrays([[1, 2], [3, 4]])
  311. tm.assert_index_equal(result, expected)
  312. def test_union_multiindex_empty_rangeindex():
  313. # GH#41234
  314. mi = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
  315. ri = pd.RangeIndex(0)
  316. result_left = mi.union(ri)
  317. tm.assert_index_equal(mi, result_left, check_names=False)
  318. result_right = ri.union(mi)
  319. tm.assert_index_equal(mi, result_right, check_names=False)
  320. @pytest.mark.parametrize(
  321. "method", ["union", "intersection", "difference", "symmetric_difference"]
  322. )
  323. def test_setops_sort_validation(method):
  324. idx1 = MultiIndex.from_product([["a", "b"], [1, 2]])
  325. idx2 = MultiIndex.from_product([["b", "c"], [1, 2]])
  326. with pytest.raises(ValueError, match="The 'sort' keyword only takes"):
  327. getattr(idx1, method)(idx2, sort=2)
  328. # sort=True is supported as of GH#?
  329. getattr(idx1, method)(idx2, sort=True)
  330. @pytest.mark.parametrize("val", [pd.NA, 100])
  331. def test_difference_keep_ea_dtypes(any_numeric_ea_dtype, val):
  332. # GH#48606
  333. midx = MultiIndex.from_arrays(
  334. [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None]
  335. )
  336. midx2 = MultiIndex.from_arrays(
  337. [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]]
  338. )
  339. result = midx.difference(midx2)
  340. expected = MultiIndex.from_arrays([Series([1], dtype=any_numeric_ea_dtype), [2]])
  341. tm.assert_index_equal(result, expected)
  342. result = midx.difference(midx.sort_values(ascending=False))
  343. expected = MultiIndex.from_arrays(
  344. [Series([], dtype=any_numeric_ea_dtype), Series([], dtype=np.int64)],
  345. names=["a", None],
  346. )
  347. tm.assert_index_equal(result, expected)
  348. @pytest.mark.parametrize("val", [pd.NA, 5])
  349. def test_symmetric_difference_keeping_ea_dtype(any_numeric_ea_dtype, val):
  350. # GH#48607
  351. midx = MultiIndex.from_arrays(
  352. [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None]
  353. )
  354. midx2 = MultiIndex.from_arrays(
  355. [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]]
  356. )
  357. result = midx.symmetric_difference(midx2)
  358. expected = MultiIndex.from_arrays(
  359. [Series([1, 1, val], dtype=any_numeric_ea_dtype), [1, 2, 3]]
  360. )
  361. tm.assert_index_equal(result, expected)
  362. @pytest.mark.parametrize(
  363. ("tuples", "exp_tuples"),
  364. [
  365. ([("val1", "test1")], [("val1", "test1")]),
  366. ([("val1", "test1"), ("val1", "test1")], [("val1", "test1")]),
  367. (
  368. [("val2", "test2"), ("val1", "test1")],
  369. [("val2", "test2"), ("val1", "test1")],
  370. ),
  371. ],
  372. )
  373. def test_intersect_with_duplicates(tuples, exp_tuples):
  374. # GH#36915
  375. left = MultiIndex.from_tuples(tuples, names=["first", "second"])
  376. right = MultiIndex.from_tuples(
  377. [("val1", "test1"), ("val1", "test1"), ("val2", "test2")],
  378. names=["first", "second"],
  379. )
  380. result = left.intersection(right)
  381. expected = MultiIndex.from_tuples(exp_tuples, names=["first", "second"])
  382. tm.assert_index_equal(result, expected)
  383. @pytest.mark.parametrize(
  384. "data, names, expected",
  385. [
  386. ((1,), None, [None, None]),
  387. ((1,), ["a"], [None, None]),
  388. ((1,), ["b"], [None, None]),
  389. ((1, 2), ["c", "d"], [None, None]),
  390. ((1, 2), ["b", "a"], [None, None]),
  391. ((1, 2, 3), ["a", "b", "c"], [None, None]),
  392. ((1, 2), ["a", "c"], ["a", None]),
  393. ((1, 2), ["c", "b"], [None, "b"]),
  394. ((1, 2), ["a", "b"], ["a", "b"]),
  395. ((1, 2), [None, "b"], [None, "b"]),
  396. ],
  397. )
  398. def test_maybe_match_names(data, names, expected):
  399. # GH#38323
  400. mi = MultiIndex.from_tuples([], names=["a", "b"])
  401. mi2 = MultiIndex.from_tuples([data], names=names)
  402. result = mi._maybe_match_names(mi2)
  403. assert result == expected
  404. def test_intersection_equal_different_names():
  405. # GH#30302
  406. mi1 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["c", "b"])
  407. mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
  408. result = mi1.intersection(mi2)
  409. expected = MultiIndex.from_arrays([[1, 2], [3, 4]], names=[None, "b"])
  410. tm.assert_index_equal(result, expected)
  411. def test_intersection_different_names():
  412. # GH#38323
  413. mi = MultiIndex.from_arrays([[1], [3]], names=["c", "b"])
  414. mi2 = MultiIndex.from_arrays([[1], [3]])
  415. result = mi.intersection(mi2)
  416. tm.assert_index_equal(result, mi2)
  417. def test_intersection_with_missing_values_on_both_sides(nulls_fixture):
  418. # GH#38623
  419. mi1 = MultiIndex.from_arrays([[3, nulls_fixture, 4, nulls_fixture], [1, 2, 4, 2]])
  420. mi2 = MultiIndex.from_arrays([[3, nulls_fixture, 3], [1, 2, 4]])
  421. result = mi1.intersection(mi2)
  422. expected = MultiIndex.from_arrays([[3, nulls_fixture], [1, 2]])
  423. tm.assert_index_equal(result, expected)
  424. def test_union_with_missing_values_on_both_sides(nulls_fixture):
  425. # GH#38623
  426. mi1 = MultiIndex.from_arrays([[1, nulls_fixture]])
  427. mi2 = MultiIndex.from_arrays([[1, nulls_fixture, 3]])
  428. result = mi1.union(mi2)
  429. expected = MultiIndex.from_arrays([[1, 3, nulls_fixture]])
  430. tm.assert_index_equal(result, expected)
  431. @pytest.mark.parametrize("dtype", ["float64", "Float64"])
  432. @pytest.mark.parametrize("sort", [None, False])
  433. def test_union_nan_got_duplicated(dtype, sort):
  434. # GH#38977, GH#49010
  435. mi1 = MultiIndex.from_arrays([pd.array([1.0, np.nan], dtype=dtype), [2, 3]])
  436. mi2 = MultiIndex.from_arrays([pd.array([1.0, np.nan, 3.0], dtype=dtype), [2, 3, 4]])
  437. result = mi1.union(mi2, sort=sort)
  438. if sort is None:
  439. expected = MultiIndex.from_arrays(
  440. [pd.array([1.0, 3.0, np.nan], dtype=dtype), [2, 4, 3]]
  441. )
  442. else:
  443. expected = mi2
  444. tm.assert_index_equal(result, expected)
  445. @pytest.mark.parametrize("val", [4, 1])
  446. def test_union_keep_ea_dtype(any_numeric_ea_dtype, val):
  447. # GH#48505
  448. arr1 = Series([val, 2], dtype=any_numeric_ea_dtype)
  449. arr2 = Series([2, 1], dtype=any_numeric_ea_dtype)
  450. midx = MultiIndex.from_arrays([arr1, [1, 2]], names=["a", None])
  451. midx2 = MultiIndex.from_arrays([arr2, [2, 1]])
  452. result = midx.union(midx2)
  453. if val == 4:
  454. expected = MultiIndex.from_arrays(
  455. [Series([1, 2, 4], dtype=any_numeric_ea_dtype), [1, 2, 1]]
  456. )
  457. else:
  458. expected = MultiIndex.from_arrays(
  459. [Series([1, 2], dtype=any_numeric_ea_dtype), [1, 2]]
  460. )
  461. tm.assert_index_equal(result, expected)
  462. @pytest.mark.parametrize("dupe_val", [3, pd.NA])
  463. def test_union_with_duplicates_keep_ea_dtype(dupe_val, any_numeric_ea_dtype):
  464. # GH48900
  465. mi1 = MultiIndex.from_arrays(
  466. [
  467. Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype),
  468. Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype),
  469. ]
  470. )
  471. mi2 = MultiIndex.from_arrays(
  472. [
  473. Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),
  474. Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),
  475. ]
  476. )
  477. result = mi1.union(mi2)
  478. expected = MultiIndex.from_arrays(
  479. [
  480. Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),
  481. Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),
  482. ]
  483. )
  484. tm.assert_index_equal(result, expected)
  485. def test_union_duplicates(index, request):
  486. # GH#38977
  487. if index.empty or isinstance(index, (IntervalIndex, CategoricalIndex)):
  488. # No duplicates in empty indexes
  489. return
  490. values = index.unique().values.tolist()
  491. mi1 = MultiIndex.from_arrays([values, [1] * len(values)])
  492. mi2 = MultiIndex.from_arrays([[values[0]] + values, [1] * (len(values) + 1)])
  493. result = mi2.union(mi1)
  494. expected = mi2.sort_values()
  495. tm.assert_index_equal(result, expected)
  496. if (
  497. is_unsigned_integer_dtype(mi2.levels[0])
  498. and (mi2.get_level_values(0) < 2**63).all()
  499. ):
  500. # GH#47294 - union uses lib.fast_zip, converting data to Python integers
  501. # and loses type information. Result is then unsigned only when values are
  502. # sufficiently large to require unsigned dtype. This happens only if other
  503. # has dups or one of both have missing values
  504. expected = expected.set_levels(
  505. [expected.levels[0].astype(np.int64), expected.levels[1]]
  506. )
  507. elif is_float_dtype(mi2.levels[0]):
  508. # mi2 has duplicates witch is a different path than above, Fix that path
  509. # to use correct float dtype?
  510. expected = expected.set_levels(
  511. [expected.levels[0].astype(float), expected.levels[1]]
  512. )
  513. result = mi1.union(mi2)
  514. tm.assert_index_equal(result, expected)
  515. def test_union_keep_dtype_precision(any_real_numeric_dtype):
  516. # GH#48498
  517. arr1 = Series([4, 1, 1], dtype=any_real_numeric_dtype)
  518. arr2 = Series([1, 4], dtype=any_real_numeric_dtype)
  519. midx = MultiIndex.from_arrays([arr1, [2, 1, 1]], names=["a", None])
  520. midx2 = MultiIndex.from_arrays([arr2, [1, 2]], names=["a", None])
  521. result = midx.union(midx2)
  522. expected = MultiIndex.from_arrays(
  523. ([Series([1, 1, 4], dtype=any_real_numeric_dtype), [1, 1, 2]]),
  524. names=["a", None],
  525. )
  526. tm.assert_index_equal(result, expected)
  527. def test_union_keep_ea_dtype_with_na(any_numeric_ea_dtype):
  528. # GH#48498
  529. arr1 = Series([4, pd.NA], dtype=any_numeric_ea_dtype)
  530. arr2 = Series([1, pd.NA], dtype=any_numeric_ea_dtype)
  531. midx = MultiIndex.from_arrays([arr1, [2, 1]], names=["a", None])
  532. midx2 = MultiIndex.from_arrays([arr2, [1, 2]])
  533. result = midx.union(midx2)
  534. expected = MultiIndex.from_arrays(
  535. [Series([1, 4, pd.NA, pd.NA], dtype=any_numeric_ea_dtype), [1, 2, 1, 2]]
  536. )
  537. tm.assert_index_equal(result, expected)
  538. @pytest.mark.parametrize(
  539. "levels1, levels2, codes1, codes2, names",
  540. [
  541. (
  542. [["a", "b", "c"], [0, ""]],
  543. [["c", "d", "b"], [""]],
  544. [[0, 1, 2], [1, 1, 1]],
  545. [[0, 1, 2], [0, 0, 0]],
  546. ["name1", "name2"],
  547. ),
  548. ],
  549. )
  550. def test_intersection_lexsort_depth(levels1, levels2, codes1, codes2, names):
  551. # GH#25169
  552. mi1 = MultiIndex(levels=levels1, codes=codes1, names=names)
  553. mi2 = MultiIndex(levels=levels2, codes=codes2, names=names)
  554. mi_int = mi1.intersection(mi2)
  555. assert mi_int._lexsort_depth == 2
  556. @pytest.mark.parametrize(
  557. "a",
  558. [pd.Categorical(["a", "b"], categories=["a", "b"]), ["a", "b"]],
  559. )
  560. @pytest.mark.parametrize(
  561. "b",
  562. [
  563. pd.Categorical(["a", "b"], categories=["b", "a"], ordered=True),
  564. pd.Categorical(["a", "b"], categories=["b", "a"]),
  565. ],
  566. )
  567. def test_intersection_with_non_lex_sorted_categories(a, b):
  568. # GH#49974
  569. other = ["1", "2"]
  570. df1 = DataFrame({"x": a, "y": other})
  571. df2 = DataFrame({"x": b, "y": other})
  572. expected = MultiIndex.from_arrays([a, other], names=["x", "y"])
  573. res1 = MultiIndex.from_frame(df1).intersection(
  574. MultiIndex.from_frame(df2.sort_values(["x", "y"]))
  575. )
  576. res2 = MultiIndex.from_frame(df1).intersection(MultiIndex.from_frame(df2))
  577. res3 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection(
  578. MultiIndex.from_frame(df2)
  579. )
  580. res4 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection(
  581. MultiIndex.from_frame(df2.sort_values(["x", "y"]))
  582. )
  583. tm.assert_index_equal(res1, expected)
  584. tm.assert_index_equal(res2, expected)
  585. tm.assert_index_equal(res3, expected)
  586. tm.assert_index_equal(res4, expected)
  587. @pytest.mark.parametrize("val", [pd.NA, 100])
  588. def test_intersection_keep_ea_dtypes(val, any_numeric_ea_dtype):
  589. # GH#48604
  590. midx = MultiIndex.from_arrays(
  591. [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None]
  592. )
  593. midx2 = MultiIndex.from_arrays(
  594. [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]]
  595. )
  596. result = midx.intersection(midx2)
  597. expected = MultiIndex.from_arrays([Series([2], dtype=any_numeric_ea_dtype), [1]])
  598. tm.assert_index_equal(result, expected)
  599. def test_union_with_na_when_constructing_dataframe():
  600. # GH43222
  601. series1 = Series((1,), index=MultiIndex.from_tuples(((None, None),)))
  602. series2 = Series((10, 20), index=MultiIndex.from_tuples(((None, None), ("a", "b"))))
  603. result = DataFrame([series1, series2])
  604. expected = DataFrame({(np.nan, np.nan): [1.0, 10.0], ("a", "b"): [np.nan, 20.0]})
  605. tm.assert_frame_equal(result, expected)