asserters.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  1. from __future__ import annotations
  2. import operator
  3. from typing import (
  4. TYPE_CHECKING,
  5. Literal,
  6. NoReturn,
  7. cast,
  8. )
  9. import numpy as np
  10. from pandas._libs import lib
  11. from pandas._libs.missing import is_matching_na
  12. from pandas._libs.sparse import SparseIndex
  13. import pandas._libs.testing as _testing
  14. from pandas._libs.tslibs.np_datetime import compare_mismatched_resolutions
  15. from pandas.core.dtypes.common import (
  16. is_bool,
  17. is_float_dtype,
  18. is_integer_dtype,
  19. is_number,
  20. is_numeric_dtype,
  21. needs_i8_conversion,
  22. )
  23. from pandas.core.dtypes.dtypes import (
  24. CategoricalDtype,
  25. DatetimeTZDtype,
  26. ExtensionDtype,
  27. NumpyEADtype,
  28. )
  29. from pandas.core.dtypes.missing import array_equivalent
  30. import pandas as pd
  31. from pandas import (
  32. Categorical,
  33. DataFrame,
  34. DatetimeIndex,
  35. Index,
  36. IntervalDtype,
  37. IntervalIndex,
  38. MultiIndex,
  39. PeriodIndex,
  40. RangeIndex,
  41. Series,
  42. TimedeltaIndex,
  43. )
  44. from pandas.core.arrays import (
  45. DatetimeArray,
  46. ExtensionArray,
  47. IntervalArray,
  48. PeriodArray,
  49. TimedeltaArray,
  50. )
  51. from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
  52. from pandas.core.arrays.string_ import StringDtype
  53. from pandas.core.indexes.api import safe_sort_index
  54. from pandas.io.formats.printing import pprint_thing
  55. if TYPE_CHECKING:
  56. from pandas._typing import DtypeObj
  57. def assert_almost_equal(
  58. left,
  59. right,
  60. check_dtype: bool | Literal["equiv"] = "equiv",
  61. rtol: float = 1.0e-5,
  62. atol: float = 1.0e-8,
  63. **kwargs,
  64. ) -> None:
  65. """
  66. Check that the left and right objects are approximately equal.
  67. By approximately equal, we refer to objects that are numbers or that
  68. contain numbers which may be equivalent to specific levels of precision.
  69. Parameters
  70. ----------
  71. left : object
  72. right : object
  73. check_dtype : bool or {'equiv'}, default 'equiv'
  74. Check dtype if both a and b are the same type. If 'equiv' is passed in,
  75. then `RangeIndex` and `Index` with int64 dtype are also considered
  76. equivalent when doing type checking.
  77. rtol : float, default 1e-5
  78. Relative tolerance.
  79. atol : float, default 1e-8
  80. Absolute tolerance.
  81. """
  82. if isinstance(left, Index):
  83. assert_index_equal(
  84. left,
  85. right,
  86. check_exact=False,
  87. exact=check_dtype,
  88. rtol=rtol,
  89. atol=atol,
  90. **kwargs,
  91. )
  92. elif isinstance(left, Series):
  93. assert_series_equal(
  94. left,
  95. right,
  96. check_exact=False,
  97. check_dtype=check_dtype,
  98. rtol=rtol,
  99. atol=atol,
  100. **kwargs,
  101. )
  102. elif isinstance(left, DataFrame):
  103. assert_frame_equal(
  104. left,
  105. right,
  106. check_exact=False,
  107. check_dtype=check_dtype,
  108. rtol=rtol,
  109. atol=atol,
  110. **kwargs,
  111. )
  112. else:
  113. # Other sequences.
  114. if check_dtype:
  115. if is_number(left) and is_number(right):
  116. # Do not compare numeric classes, like np.float64 and float.
  117. pass
  118. elif is_bool(left) and is_bool(right):
  119. # Do not compare bool classes, like np.bool_ and bool.
  120. pass
  121. else:
  122. if isinstance(left, np.ndarray) or isinstance(right, np.ndarray):
  123. obj = "numpy array"
  124. else:
  125. obj = "Input"
  126. assert_class_equal(left, right, obj=obj)
  127. # if we have "equiv", this becomes True
  128. _testing.assert_almost_equal(
  129. left, right, check_dtype=bool(check_dtype), rtol=rtol, atol=atol, **kwargs
  130. )
  131. def _check_isinstance(left, right, cls) -> None:
  132. """
  133. Helper method for our assert_* methods that ensures that
  134. the two objects being compared have the right type before
  135. proceeding with the comparison.
  136. Parameters
  137. ----------
  138. left : The first object being compared.
  139. right : The second object being compared.
  140. cls : The class type to check against.
  141. Raises
  142. ------
  143. AssertionError : Either `left` or `right` is not an instance of `cls`.
  144. """
  145. cls_name = cls.__name__
  146. if not isinstance(left, cls):
  147. raise AssertionError(
  148. f"{cls_name} Expected type {cls}, found {type(left)} instead"
  149. )
  150. if not isinstance(right, cls):
  151. raise AssertionError(
  152. f"{cls_name} Expected type {cls}, found {type(right)} instead"
  153. )
  154. def assert_dict_equal(left, right, compare_keys: bool = True) -> None:
  155. _check_isinstance(left, right, dict)
  156. _testing.assert_dict_equal(left, right, compare_keys=compare_keys)
  157. def assert_index_equal(
  158. left: Index,
  159. right: Index,
  160. exact: bool | str = "equiv",
  161. check_names: bool = True,
  162. check_exact: bool = True,
  163. check_categorical: bool = True,
  164. check_order: bool = True,
  165. rtol: float = 1.0e-5,
  166. atol: float = 1.0e-8,
  167. obj: str = "Index",
  168. ) -> None:
  169. """
  170. Check that left and right Index are equal.
  171. Parameters
  172. ----------
  173. left : Index
  174. right : Index
  175. exact : bool or {'equiv'}, default 'equiv'
  176. Whether to check the Index class, dtype and inferred_type
  177. are identical. If 'equiv', then RangeIndex can be substituted for
  178. Index with an int64 dtype as well.
  179. check_names : bool, default True
  180. Whether to check the names attribute.
  181. check_exact : bool, default True
  182. Whether to compare number exactly.
  183. check_categorical : bool, default True
  184. Whether to compare internal Categorical exactly.
  185. check_order : bool, default True
  186. Whether to compare the order of index entries as well as their values.
  187. If True, both indexes must contain the same elements, in the same order.
  188. If False, both indexes must contain the same elements, but in any order.
  189. rtol : float, default 1e-5
  190. Relative tolerance. Only used when check_exact is False.
  191. atol : float, default 1e-8
  192. Absolute tolerance. Only used when check_exact is False.
  193. obj : str, default 'Index'
  194. Specify object name being compared, internally used to show appropriate
  195. assertion message.
  196. Examples
  197. --------
  198. >>> from pandas import testing as tm
  199. >>> a = pd.Index([1, 2, 3])
  200. >>> b = pd.Index([1, 2, 3])
  201. >>> tm.assert_index_equal(a, b)
  202. """
  203. __tracebackhide__ = True
  204. def _check_types(left, right, obj: str = "Index") -> None:
  205. if not exact:
  206. return
  207. assert_class_equal(left, right, exact=exact, obj=obj)
  208. assert_attr_equal("inferred_type", left, right, obj=obj)
  209. # Skip exact dtype checking when `check_categorical` is False
  210. if isinstance(left.dtype, CategoricalDtype) and isinstance(
  211. right.dtype, CategoricalDtype
  212. ):
  213. if check_categorical:
  214. assert_attr_equal("dtype", left, right, obj=obj)
  215. assert_index_equal(left.categories, right.categories, exact=exact)
  216. return
  217. assert_attr_equal("dtype", left, right, obj=obj)
  218. # instance validation
  219. _check_isinstance(left, right, Index)
  220. # class / dtype comparison
  221. _check_types(left, right, obj=obj)
  222. # level comparison
  223. if left.nlevels != right.nlevels:
  224. msg1 = f"{obj} levels are different"
  225. msg2 = f"{left.nlevels}, {left}"
  226. msg3 = f"{right.nlevels}, {right}"
  227. raise_assert_detail(obj, msg1, msg2, msg3)
  228. # length comparison
  229. if len(left) != len(right):
  230. msg1 = f"{obj} length are different"
  231. msg2 = f"{len(left)}, {left}"
  232. msg3 = f"{len(right)}, {right}"
  233. raise_assert_detail(obj, msg1, msg2, msg3)
  234. # If order doesn't matter then sort the index entries
  235. if not check_order:
  236. left = safe_sort_index(left)
  237. right = safe_sort_index(right)
  238. # MultiIndex special comparison for little-friendly error messages
  239. if isinstance(left, MultiIndex):
  240. right = cast(MultiIndex, right)
  241. for level in range(left.nlevels):
  242. lobj = f"MultiIndex level [{level}]"
  243. try:
  244. # try comparison on levels/codes to avoid densifying MultiIndex
  245. assert_index_equal(
  246. left.levels[level],
  247. right.levels[level],
  248. exact=exact,
  249. check_names=check_names,
  250. check_exact=check_exact,
  251. check_categorical=check_categorical,
  252. rtol=rtol,
  253. atol=atol,
  254. obj=lobj,
  255. )
  256. assert_numpy_array_equal(left.codes[level], right.codes[level])
  257. except AssertionError:
  258. llevel = left.get_level_values(level)
  259. rlevel = right.get_level_values(level)
  260. assert_index_equal(
  261. llevel,
  262. rlevel,
  263. exact=exact,
  264. check_names=check_names,
  265. check_exact=check_exact,
  266. check_categorical=check_categorical,
  267. rtol=rtol,
  268. atol=atol,
  269. obj=lobj,
  270. )
  271. # get_level_values may change dtype
  272. _check_types(left.levels[level], right.levels[level], obj=obj)
  273. # skip exact index checking when `check_categorical` is False
  274. elif check_exact and check_categorical:
  275. if not left.equals(right):
  276. mismatch = left._values != right._values
  277. if not isinstance(mismatch, np.ndarray):
  278. mismatch = cast("ExtensionArray", mismatch).fillna(True)
  279. diff = np.sum(mismatch.astype(int)) * 100.0 / len(left)
  280. msg = f"{obj} values are different ({np.round(diff, 5)} %)"
  281. raise_assert_detail(obj, msg, left, right)
  282. else:
  283. # if we have "equiv", this becomes True
  284. exact_bool = bool(exact)
  285. _testing.assert_almost_equal(
  286. left.values,
  287. right.values,
  288. rtol=rtol,
  289. atol=atol,
  290. check_dtype=exact_bool,
  291. obj=obj,
  292. lobj=left,
  293. robj=right,
  294. )
  295. # metadata comparison
  296. if check_names:
  297. assert_attr_equal("names", left, right, obj=obj)
  298. if isinstance(left, PeriodIndex) or isinstance(right, PeriodIndex):
  299. assert_attr_equal("dtype", left, right, obj=obj)
  300. if isinstance(left, IntervalIndex) or isinstance(right, IntervalIndex):
  301. assert_interval_array_equal(left._values, right._values)
  302. if check_categorical:
  303. if isinstance(left.dtype, CategoricalDtype) or isinstance(
  304. right.dtype, CategoricalDtype
  305. ):
  306. assert_categorical_equal(left._values, right._values, obj=f"{obj} category")
  307. def assert_class_equal(
  308. left, right, exact: bool | str = True, obj: str = "Input"
  309. ) -> None:
  310. """
  311. Checks classes are equal.
  312. """
  313. __tracebackhide__ = True
  314. def repr_class(x):
  315. if isinstance(x, Index):
  316. # return Index as it is to include values in the error message
  317. return x
  318. return type(x).__name__
  319. def is_class_equiv(idx: Index) -> bool:
  320. """Classes that are a RangeIndex (sub-)instance or exactly an `Index` .
  321. This only checks class equivalence. There is a separate check that the
  322. dtype is int64.
  323. """
  324. return type(idx) is Index or isinstance(idx, RangeIndex)
  325. if type(left) == type(right):
  326. return
  327. if exact == "equiv":
  328. if is_class_equiv(left) and is_class_equiv(right):
  329. return
  330. msg = f"{obj} classes are different"
  331. raise_assert_detail(obj, msg, repr_class(left), repr_class(right))
  332. def assert_attr_equal(attr: str, left, right, obj: str = "Attributes") -> None:
  333. """
  334. Check attributes are equal. Both objects must have attribute.
  335. Parameters
  336. ----------
  337. attr : str
  338. Attribute name being compared.
  339. left : object
  340. right : object
  341. obj : str, default 'Attributes'
  342. Specify object name being compared, internally used to show appropriate
  343. assertion message
  344. """
  345. __tracebackhide__ = True
  346. left_attr = getattr(left, attr)
  347. right_attr = getattr(right, attr)
  348. if left_attr is right_attr or is_matching_na(left_attr, right_attr):
  349. # e.g. both np.nan, both NaT, both pd.NA, ...
  350. return None
  351. try:
  352. result = left_attr == right_attr
  353. except TypeError:
  354. # datetimetz on rhs may raise TypeError
  355. result = False
  356. if (left_attr is pd.NA) ^ (right_attr is pd.NA):
  357. result = False
  358. elif not isinstance(result, bool):
  359. result = result.all()
  360. if not result:
  361. msg = f'Attribute "{attr}" are different'
  362. raise_assert_detail(obj, msg, left_attr, right_attr)
  363. return None
  364. def assert_is_valid_plot_return_object(objs) -> None:
  365. from matplotlib.artist import Artist
  366. from matplotlib.axes import Axes
  367. if isinstance(objs, (Series, np.ndarray)):
  368. if isinstance(objs, Series):
  369. objs = objs._values
  370. for el in objs.ravel():
  371. msg = (
  372. "one of 'objs' is not a matplotlib Axes instance, "
  373. f"type encountered {repr(type(el).__name__)}"
  374. )
  375. assert isinstance(el, (Axes, dict)), msg
  376. else:
  377. msg = (
  378. "objs is neither an ndarray of Artist instances nor a single "
  379. "ArtistArtist instance, tuple, or dict, 'objs' is a "
  380. f"{repr(type(objs).__name__)}"
  381. )
  382. assert isinstance(objs, (Artist, tuple, dict)), msg
  383. def assert_is_sorted(seq) -> None:
  384. """Assert that the sequence is sorted."""
  385. if isinstance(seq, (Index, Series)):
  386. seq = seq.values
  387. # sorting does not change precisions
  388. if isinstance(seq, np.ndarray):
  389. assert_numpy_array_equal(seq, np.sort(np.array(seq)))
  390. else:
  391. assert_extension_array_equal(seq, seq[seq.argsort()])
  392. def assert_categorical_equal(
  393. left,
  394. right,
  395. check_dtype: bool = True,
  396. check_category_order: bool = True,
  397. obj: str = "Categorical",
  398. ) -> None:
  399. """
  400. Test that Categoricals are equivalent.
  401. Parameters
  402. ----------
  403. left : Categorical
  404. right : Categorical
  405. check_dtype : bool, default True
  406. Check that integer dtype of the codes are the same.
  407. check_category_order : bool, default True
  408. Whether the order of the categories should be compared, which
  409. implies identical integer codes. If False, only the resulting
  410. values are compared. The ordered attribute is
  411. checked regardless.
  412. obj : str, default 'Categorical'
  413. Specify object name being compared, internally used to show appropriate
  414. assertion message.
  415. """
  416. _check_isinstance(left, right, Categorical)
  417. exact: bool | str
  418. if isinstance(left.categories, RangeIndex) or isinstance(
  419. right.categories, RangeIndex
  420. ):
  421. exact = "equiv"
  422. else:
  423. # We still want to require exact matches for Index
  424. exact = True
  425. if check_category_order:
  426. assert_index_equal(
  427. left.categories, right.categories, obj=f"{obj}.categories", exact=exact
  428. )
  429. assert_numpy_array_equal(
  430. left.codes, right.codes, check_dtype=check_dtype, obj=f"{obj}.codes"
  431. )
  432. else:
  433. try:
  434. lc = left.categories.sort_values()
  435. rc = right.categories.sort_values()
  436. except TypeError:
  437. # e.g. '<' not supported between instances of 'int' and 'str'
  438. lc, rc = left.categories, right.categories
  439. assert_index_equal(lc, rc, obj=f"{obj}.categories", exact=exact)
  440. assert_index_equal(
  441. left.categories.take(left.codes),
  442. right.categories.take(right.codes),
  443. obj=f"{obj}.values",
  444. exact=exact,
  445. )
  446. assert_attr_equal("ordered", left, right, obj=obj)
  447. def assert_interval_array_equal(
  448. left, right, exact: bool | Literal["equiv"] = "equiv", obj: str = "IntervalArray"
  449. ) -> None:
  450. """
  451. Test that two IntervalArrays are equivalent.
  452. Parameters
  453. ----------
  454. left, right : IntervalArray
  455. The IntervalArrays to compare.
  456. exact : bool or {'equiv'}, default 'equiv'
  457. Whether to check the Index class, dtype and inferred_type
  458. are identical. If 'equiv', then RangeIndex can be substituted for
  459. Index with an int64 dtype as well.
  460. obj : str, default 'IntervalArray'
  461. Specify object name being compared, internally used to show appropriate
  462. assertion message
  463. """
  464. _check_isinstance(left, right, IntervalArray)
  465. kwargs = {}
  466. if left._left.dtype.kind in "mM":
  467. # We have a DatetimeArray or TimedeltaArray
  468. kwargs["check_freq"] = False
  469. assert_equal(left._left, right._left, obj=f"{obj}.left", **kwargs)
  470. assert_equal(left._right, right._right, obj=f"{obj}.left", **kwargs)
  471. assert_attr_equal("closed", left, right, obj=obj)
  472. def assert_period_array_equal(left, right, obj: str = "PeriodArray") -> None:
  473. _check_isinstance(left, right, PeriodArray)
  474. assert_numpy_array_equal(left._ndarray, right._ndarray, obj=f"{obj}._ndarray")
  475. assert_attr_equal("dtype", left, right, obj=obj)
  476. def assert_datetime_array_equal(
  477. left, right, obj: str = "DatetimeArray", check_freq: bool = True
  478. ) -> None:
  479. __tracebackhide__ = True
  480. _check_isinstance(left, right, DatetimeArray)
  481. assert_numpy_array_equal(left._ndarray, right._ndarray, obj=f"{obj}._ndarray")
  482. if check_freq:
  483. assert_attr_equal("freq", left, right, obj=obj)
  484. assert_attr_equal("tz", left, right, obj=obj)
  485. def assert_timedelta_array_equal(
  486. left, right, obj: str = "TimedeltaArray", check_freq: bool = True
  487. ) -> None:
  488. __tracebackhide__ = True
  489. _check_isinstance(left, right, TimedeltaArray)
  490. assert_numpy_array_equal(left._ndarray, right._ndarray, obj=f"{obj}._ndarray")
  491. if check_freq:
  492. assert_attr_equal("freq", left, right, obj=obj)
  493. def raise_assert_detail(
  494. obj, message, left, right, diff=None, first_diff=None, index_values=None
  495. ) -> NoReturn:
  496. __tracebackhide__ = True
  497. msg = f"""{obj} are different
  498. {message}"""
  499. if isinstance(index_values, Index):
  500. index_values = np.asarray(index_values)
  501. if isinstance(index_values, np.ndarray):
  502. msg += f"\n[index]: {pprint_thing(index_values)}"
  503. if isinstance(left, np.ndarray):
  504. left = pprint_thing(left)
  505. elif isinstance(left, (CategoricalDtype, NumpyEADtype)):
  506. left = repr(left)
  507. elif isinstance(left, StringDtype):
  508. # TODO(infer_string) this special case could be avoided if we have
  509. # a more informative repr https://github.com/pandas-dev/pandas/issues/59342
  510. left = f"StringDtype(storage={left.storage}, na_value={left.na_value})"
  511. if isinstance(right, np.ndarray):
  512. right = pprint_thing(right)
  513. elif isinstance(right, (CategoricalDtype, NumpyEADtype)):
  514. right = repr(right)
  515. elif isinstance(right, StringDtype):
  516. right = f"StringDtype(storage={right.storage}, na_value={right.na_value})"
  517. msg += f"""
  518. [left]: {left}
  519. [right]: {right}"""
  520. if diff is not None:
  521. msg += f"\n[diff]: {diff}"
  522. if first_diff is not None:
  523. msg += f"\n{first_diff}"
  524. raise AssertionError(msg)
  525. def assert_numpy_array_equal(
  526. left,
  527. right,
  528. strict_nan: bool = False,
  529. check_dtype: bool | Literal["equiv"] = True,
  530. err_msg=None,
  531. check_same=None,
  532. obj: str = "numpy array",
  533. index_values=None,
  534. ) -> None:
  535. """
  536. Check that 'np.ndarray' is equivalent.
  537. Parameters
  538. ----------
  539. left, right : numpy.ndarray or iterable
  540. The two arrays to be compared.
  541. strict_nan : bool, default False
  542. If True, consider NaN and None to be different.
  543. check_dtype : bool, default True
  544. Check dtype if both a and b are np.ndarray.
  545. err_msg : str, default None
  546. If provided, used as assertion message.
  547. check_same : None|'copy'|'same', default None
  548. Ensure left and right refer/do not refer to the same memory area.
  549. obj : str, default 'numpy array'
  550. Specify object name being compared, internally used to show appropriate
  551. assertion message.
  552. index_values : Index | numpy.ndarray, default None
  553. optional index (shared by both left and right), used in output.
  554. """
  555. __tracebackhide__ = True
  556. # instance validation
  557. # Show a detailed error message when classes are different
  558. assert_class_equal(left, right, obj=obj)
  559. # both classes must be an np.ndarray
  560. _check_isinstance(left, right, np.ndarray)
  561. def _get_base(obj):
  562. return obj.base if getattr(obj, "base", None) is not None else obj
  563. left_base = _get_base(left)
  564. right_base = _get_base(right)
  565. if check_same == "same":
  566. if left_base is not right_base:
  567. raise AssertionError(f"{repr(left_base)} is not {repr(right_base)}")
  568. elif check_same == "copy":
  569. if left_base is right_base:
  570. raise AssertionError(f"{repr(left_base)} is {repr(right_base)}")
  571. def _raise(left, right, err_msg) -> NoReturn:
  572. if err_msg is None:
  573. if left.shape != right.shape:
  574. raise_assert_detail(
  575. obj, f"{obj} shapes are different", left.shape, right.shape
  576. )
  577. diff = 0
  578. for left_arr, right_arr in zip(left, right):
  579. # count up differences
  580. if not array_equivalent(left_arr, right_arr, strict_nan=strict_nan):
  581. diff += 1
  582. diff = diff * 100.0 / left.size
  583. msg = f"{obj} values are different ({np.round(diff, 5)} %)"
  584. raise_assert_detail(obj, msg, left, right, index_values=index_values)
  585. raise AssertionError(err_msg)
  586. # compare shape and values
  587. if not array_equivalent(left, right, strict_nan=strict_nan):
  588. _raise(left, right, err_msg)
  589. if check_dtype:
  590. if isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
  591. assert_attr_equal("dtype", left, right, obj=obj)
  592. def assert_extension_array_equal(
  593. left,
  594. right,
  595. check_dtype: bool | Literal["equiv"] = True,
  596. index_values=None,
  597. check_exact: bool | lib.NoDefault = lib.no_default,
  598. rtol: float | lib.NoDefault = lib.no_default,
  599. atol: float | lib.NoDefault = lib.no_default,
  600. obj: str = "ExtensionArray",
  601. ) -> None:
  602. """
  603. Check that left and right ExtensionArrays are equal.
  604. Parameters
  605. ----------
  606. left, right : ExtensionArray
  607. The two arrays to compare.
  608. check_dtype : bool, default True
  609. Whether to check if the ExtensionArray dtypes are identical.
  610. index_values : Index | numpy.ndarray, default None
  611. Optional index (shared by both left and right), used in output.
  612. check_exact : bool, default False
  613. Whether to compare number exactly.
  614. .. versionchanged:: 2.2.0
  615. Defaults to True for integer dtypes if none of
  616. ``check_exact``, ``rtol`` and ``atol`` are specified.
  617. rtol : float, default 1e-5
  618. Relative tolerance. Only used when check_exact is False.
  619. atol : float, default 1e-8
  620. Absolute tolerance. Only used when check_exact is False.
  621. obj : str, default 'ExtensionArray'
  622. Specify object name being compared, internally used to show appropriate
  623. assertion message.
  624. .. versionadded:: 2.0.0
  625. Notes
  626. -----
  627. Missing values are checked separately from valid values.
  628. A mask of missing values is computed for each and checked to match.
  629. The remaining all-valid values are cast to object dtype and checked.
  630. Examples
  631. --------
  632. >>> from pandas import testing as tm
  633. >>> a = pd.Series([1, 2, 3, 4])
  634. >>> b, c = a.array, a.array
  635. >>> tm.assert_extension_array_equal(b, c)
  636. """
  637. if (
  638. check_exact is lib.no_default
  639. and rtol is lib.no_default
  640. and atol is lib.no_default
  641. ):
  642. check_exact = (
  643. is_numeric_dtype(left.dtype)
  644. and not is_float_dtype(left.dtype)
  645. or is_numeric_dtype(right.dtype)
  646. and not is_float_dtype(right.dtype)
  647. )
  648. elif check_exact is lib.no_default:
  649. check_exact = False
  650. rtol = rtol if rtol is not lib.no_default else 1.0e-5
  651. atol = atol if atol is not lib.no_default else 1.0e-8
  652. assert isinstance(left, ExtensionArray), "left is not an ExtensionArray"
  653. assert isinstance(right, ExtensionArray), "right is not an ExtensionArray"
  654. if check_dtype:
  655. assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}")
  656. if (
  657. isinstance(left, DatetimeLikeArrayMixin)
  658. and isinstance(right, DatetimeLikeArrayMixin)
  659. and type(right) == type(left)
  660. ):
  661. # GH 52449
  662. if not check_dtype and left.dtype.kind in "mM":
  663. if not isinstance(left.dtype, np.dtype):
  664. l_unit = cast(DatetimeTZDtype, left.dtype).unit
  665. else:
  666. l_unit = np.datetime_data(left.dtype)[0]
  667. if not isinstance(right.dtype, np.dtype):
  668. r_unit = cast(DatetimeTZDtype, right.dtype).unit
  669. else:
  670. r_unit = np.datetime_data(right.dtype)[0]
  671. if (
  672. l_unit != r_unit
  673. and compare_mismatched_resolutions(
  674. left._ndarray, right._ndarray, operator.eq
  675. ).all()
  676. ):
  677. return
  678. # Avoid slow object-dtype comparisons
  679. # np.asarray for case where we have a np.MaskedArray
  680. assert_numpy_array_equal(
  681. np.asarray(left.asi8),
  682. np.asarray(right.asi8),
  683. index_values=index_values,
  684. obj=obj,
  685. )
  686. return
  687. left_na = np.asarray(left.isna())
  688. right_na = np.asarray(right.isna())
  689. assert_numpy_array_equal(
  690. left_na, right_na, obj=f"{obj} NA mask", index_values=index_values
  691. )
  692. # Specifically for StringArrayNumpySemantics, validate here we have a valid array
  693. if (
  694. isinstance(left.dtype, StringDtype)
  695. and left.dtype.storage == "python"
  696. and left.dtype.na_value is np.nan
  697. ):
  698. assert np.all(
  699. [np.isnan(val) for val in left._ndarray[left_na]] # type: ignore[attr-defined]
  700. ), "wrong missing value sentinels"
  701. if (
  702. isinstance(right.dtype, StringDtype)
  703. and right.dtype.storage == "python"
  704. and right.dtype.na_value is np.nan
  705. ):
  706. assert np.all(
  707. [np.isnan(val) for val in right._ndarray[right_na]] # type: ignore[attr-defined]
  708. ), "wrong missing value sentinels"
  709. left_valid = left[~left_na].to_numpy(dtype=object)
  710. right_valid = right[~right_na].to_numpy(dtype=object)
  711. if check_exact:
  712. assert_numpy_array_equal(
  713. left_valid, right_valid, obj=obj, index_values=index_values
  714. )
  715. else:
  716. _testing.assert_almost_equal(
  717. left_valid,
  718. right_valid,
  719. check_dtype=bool(check_dtype),
  720. rtol=rtol,
  721. atol=atol,
  722. obj=obj,
  723. index_values=index_values,
  724. )
  725. # This could be refactored to use the NDFrame.equals method
  726. def assert_series_equal(
  727. left,
  728. right,
  729. check_dtype: bool | Literal["equiv"] = True,
  730. check_index_type: bool | Literal["equiv"] = "equiv",
  731. check_series_type: bool = True,
  732. check_names: bool = True,
  733. check_exact: bool | lib.NoDefault = lib.no_default,
  734. check_datetimelike_compat: bool = False,
  735. check_categorical: bool = True,
  736. check_category_order: bool = True,
  737. check_freq: bool = True,
  738. check_flags: bool = True,
  739. rtol: float | lib.NoDefault = lib.no_default,
  740. atol: float | lib.NoDefault = lib.no_default,
  741. obj: str = "Series",
  742. *,
  743. check_index: bool = True,
  744. check_like: bool = False,
  745. ) -> None:
  746. """
  747. Check that left and right Series are equal.
  748. Parameters
  749. ----------
  750. left : Series
  751. right : Series
  752. check_dtype : bool, default True
  753. Whether to check the Series dtype is identical.
  754. check_index_type : bool or {'equiv'}, default 'equiv'
  755. Whether to check the Index class, dtype and inferred_type
  756. are identical.
  757. check_series_type : bool, default True
  758. Whether to check the Series class is identical.
  759. check_names : bool, default True
  760. Whether to check the Series and Index names attribute.
  761. check_exact : bool, default False
  762. Whether to compare number exactly.
  763. .. versionchanged:: 2.2.0
  764. Defaults to True for integer dtypes if none of
  765. ``check_exact``, ``rtol`` and ``atol`` are specified.
  766. check_datetimelike_compat : bool, default False
  767. Compare datetime-like which is comparable ignoring dtype.
  768. check_categorical : bool, default True
  769. Whether to compare internal Categorical exactly.
  770. check_category_order : bool, default True
  771. Whether to compare category order of internal Categoricals.
  772. check_freq : bool, default True
  773. Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex.
  774. check_flags : bool, default True
  775. Whether to check the `flags` attribute.
  776. rtol : float, default 1e-5
  777. Relative tolerance. Only used when check_exact is False.
  778. atol : float, default 1e-8
  779. Absolute tolerance. Only used when check_exact is False.
  780. obj : str, default 'Series'
  781. Specify object name being compared, internally used to show appropriate
  782. assertion message.
  783. check_index : bool, default True
  784. Whether to check index equivalence. If False, then compare only values.
  785. .. versionadded:: 1.3.0
  786. check_like : bool, default False
  787. If True, ignore the order of the index. Must be False if check_index is False.
  788. Note: same labels must be with the same data.
  789. .. versionadded:: 1.5.0
  790. Examples
  791. --------
  792. >>> from pandas import testing as tm
  793. >>> a = pd.Series([1, 2, 3, 4])
  794. >>> b = pd.Series([1, 2, 3, 4])
  795. >>> tm.assert_series_equal(a, b)
  796. """
  797. __tracebackhide__ = True
  798. check_exact_index = False if check_exact is lib.no_default else check_exact
  799. if (
  800. check_exact is lib.no_default
  801. and rtol is lib.no_default
  802. and atol is lib.no_default
  803. ):
  804. check_exact = (
  805. is_numeric_dtype(left.dtype)
  806. and not is_float_dtype(left.dtype)
  807. or is_numeric_dtype(right.dtype)
  808. and not is_float_dtype(right.dtype)
  809. )
  810. elif check_exact is lib.no_default:
  811. check_exact = False
  812. rtol = rtol if rtol is not lib.no_default else 1.0e-5
  813. atol = atol if atol is not lib.no_default else 1.0e-8
  814. if not check_index and check_like:
  815. raise ValueError("check_like must be False if check_index is False")
  816. # instance validation
  817. _check_isinstance(left, right, Series)
  818. if check_series_type:
  819. assert_class_equal(left, right, obj=obj)
  820. # length comparison
  821. if len(left) != len(right):
  822. msg1 = f"{len(left)}, {left.index}"
  823. msg2 = f"{len(right)}, {right.index}"
  824. raise_assert_detail(obj, "Series length are different", msg1, msg2)
  825. if check_flags:
  826. assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}"
  827. if check_index:
  828. # GH #38183
  829. assert_index_equal(
  830. left.index,
  831. right.index,
  832. exact=check_index_type,
  833. check_names=check_names,
  834. check_exact=check_exact_index,
  835. check_categorical=check_categorical,
  836. check_order=not check_like,
  837. rtol=rtol,
  838. atol=atol,
  839. obj=f"{obj}.index",
  840. )
  841. if check_like:
  842. left = left.reindex_like(right)
  843. if check_freq and isinstance(left.index, (DatetimeIndex, TimedeltaIndex)):
  844. lidx = left.index
  845. ridx = right.index
  846. assert lidx.freq == ridx.freq, (lidx.freq, ridx.freq)
  847. if check_dtype:
  848. # We want to skip exact dtype checking when `check_categorical`
  849. # is False. We'll still raise if only one is a `Categorical`,
  850. # regardless of `check_categorical`
  851. if (
  852. isinstance(left.dtype, CategoricalDtype)
  853. and isinstance(right.dtype, CategoricalDtype)
  854. and not check_categorical
  855. ):
  856. pass
  857. else:
  858. assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}")
  859. if check_exact:
  860. left_values = left._values
  861. right_values = right._values
  862. # Only check exact if dtype is numeric
  863. if isinstance(left_values, ExtensionArray) and isinstance(
  864. right_values, ExtensionArray
  865. ):
  866. assert_extension_array_equal(
  867. left_values,
  868. right_values,
  869. check_dtype=check_dtype,
  870. index_values=left.index,
  871. obj=str(obj),
  872. )
  873. else:
  874. # convert both to NumPy if not, check_dtype would raise earlier
  875. lv, rv = left_values, right_values
  876. if isinstance(left_values, ExtensionArray):
  877. lv = left_values.to_numpy()
  878. if isinstance(right_values, ExtensionArray):
  879. rv = right_values.to_numpy()
  880. assert_numpy_array_equal(
  881. lv,
  882. rv,
  883. check_dtype=check_dtype,
  884. obj=str(obj),
  885. index_values=left.index,
  886. )
  887. elif check_datetimelike_compat and (
  888. needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype)
  889. ):
  890. # we want to check only if we have compat dtypes
  891. # e.g. integer and M|m are NOT compat, but we can simply check
  892. # the values in that case
  893. # datetimelike may have different objects (e.g. datetime.datetime
  894. # vs Timestamp) but will compare equal
  895. if not Index(left._values).equals(Index(right._values)):
  896. msg = (
  897. f"[datetimelike_compat=True] {left._values} "
  898. f"is not equal to {right._values}."
  899. )
  900. raise AssertionError(msg)
  901. elif isinstance(left.dtype, IntervalDtype) and isinstance(
  902. right.dtype, IntervalDtype
  903. ):
  904. assert_interval_array_equal(left.array, right.array)
  905. elif isinstance(left.dtype, CategoricalDtype) or isinstance(
  906. right.dtype, CategoricalDtype
  907. ):
  908. _testing.assert_almost_equal(
  909. left._values,
  910. right._values,
  911. rtol=rtol,
  912. atol=atol,
  913. check_dtype=bool(check_dtype),
  914. obj=str(obj),
  915. index_values=left.index,
  916. )
  917. elif isinstance(left.dtype, ExtensionDtype) and isinstance(
  918. right.dtype, ExtensionDtype
  919. ):
  920. assert_extension_array_equal(
  921. left._values,
  922. right._values,
  923. rtol=rtol,
  924. atol=atol,
  925. check_dtype=check_dtype,
  926. index_values=left.index,
  927. obj=str(obj),
  928. )
  929. elif is_extension_array_dtype_and_needs_i8_conversion(
  930. left.dtype, right.dtype
  931. ) or is_extension_array_dtype_and_needs_i8_conversion(right.dtype, left.dtype):
  932. assert_extension_array_equal(
  933. left._values,
  934. right._values,
  935. check_dtype=check_dtype,
  936. index_values=left.index,
  937. obj=str(obj),
  938. )
  939. elif needs_i8_conversion(left.dtype) and needs_i8_conversion(right.dtype):
  940. # DatetimeArray or TimedeltaArray
  941. assert_extension_array_equal(
  942. left._values,
  943. right._values,
  944. check_dtype=check_dtype,
  945. index_values=left.index,
  946. obj=str(obj),
  947. )
  948. else:
  949. _testing.assert_almost_equal(
  950. left._values,
  951. right._values,
  952. rtol=rtol,
  953. atol=atol,
  954. check_dtype=bool(check_dtype),
  955. obj=str(obj),
  956. index_values=left.index,
  957. )
  958. # metadata comparison
  959. if check_names:
  960. assert_attr_equal("name", left, right, obj=obj)
  961. if check_categorical:
  962. if isinstance(left.dtype, CategoricalDtype) or isinstance(
  963. right.dtype, CategoricalDtype
  964. ):
  965. assert_categorical_equal(
  966. left._values,
  967. right._values,
  968. obj=f"{obj} category",
  969. check_category_order=check_category_order,
  970. )
  971. # This could be refactored to use the NDFrame.equals method
  972. def assert_frame_equal(
  973. left,
  974. right,
  975. check_dtype: bool | Literal["equiv"] = True,
  976. check_index_type: bool | Literal["equiv"] = "equiv",
  977. check_column_type: bool | Literal["equiv"] = "equiv",
  978. check_frame_type: bool = True,
  979. check_names: bool = True,
  980. by_blocks: bool = False,
  981. check_exact: bool | lib.NoDefault = lib.no_default,
  982. check_datetimelike_compat: bool = False,
  983. check_categorical: bool = True,
  984. check_like: bool = False,
  985. check_freq: bool = True,
  986. check_flags: bool = True,
  987. rtol: float | lib.NoDefault = lib.no_default,
  988. atol: float | lib.NoDefault = lib.no_default,
  989. obj: str = "DataFrame",
  990. ) -> None:
  991. """
  992. Check that left and right DataFrame are equal.
  993. This function is intended to compare two DataFrames and output any
  994. differences. It is mostly intended for use in unit tests.
  995. Additional parameters allow varying the strictness of the
  996. equality checks performed.
  997. Parameters
  998. ----------
  999. left : DataFrame
  1000. First DataFrame to compare.
  1001. right : DataFrame
  1002. Second DataFrame to compare.
  1003. check_dtype : bool, default True
  1004. Whether to check the DataFrame dtype is identical.
  1005. check_index_type : bool or {'equiv'}, default 'equiv'
  1006. Whether to check the Index class, dtype and inferred_type
  1007. are identical.
  1008. check_column_type : bool or {'equiv'}, default 'equiv'
  1009. Whether to check the columns class, dtype and inferred_type
  1010. are identical. Is passed as the ``exact`` argument of
  1011. :func:`assert_index_equal`.
  1012. check_frame_type : bool, default True
  1013. Whether to check the DataFrame class is identical.
  1014. check_names : bool, default True
  1015. Whether to check that the `names` attribute for both the `index`
  1016. and `column` attributes of the DataFrame is identical.
  1017. by_blocks : bool, default False
  1018. Specify how to compare internal data. If False, compare by columns.
  1019. If True, compare by blocks.
  1020. check_exact : bool, default False
  1021. Whether to compare number exactly.
  1022. .. versionchanged:: 2.2.0
  1023. Defaults to True for integer dtypes if none of
  1024. ``check_exact``, ``rtol`` and ``atol`` are specified.
  1025. check_datetimelike_compat : bool, default False
  1026. Compare datetime-like which is comparable ignoring dtype.
  1027. check_categorical : bool, default True
  1028. Whether to compare internal Categorical exactly.
  1029. check_like : bool, default False
  1030. If True, ignore the order of index & columns.
  1031. Note: index labels must match their respective rows
  1032. (same as in columns) - same labels must be with the same data.
  1033. check_freq : bool, default True
  1034. Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex.
  1035. check_flags : bool, default True
  1036. Whether to check the `flags` attribute.
  1037. rtol : float, default 1e-5
  1038. Relative tolerance. Only used when check_exact is False.
  1039. atol : float, default 1e-8
  1040. Absolute tolerance. Only used when check_exact is False.
  1041. obj : str, default 'DataFrame'
  1042. Specify object name being compared, internally used to show appropriate
  1043. assertion message.
  1044. See Also
  1045. --------
  1046. assert_series_equal : Equivalent method for asserting Series equality.
  1047. DataFrame.equals : Check DataFrame equality.
  1048. Examples
  1049. --------
  1050. This example shows comparing two DataFrames that are equal
  1051. but with columns of differing dtypes.
  1052. >>> from pandas.testing import assert_frame_equal
  1053. >>> df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
  1054. >>> df2 = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0]})
  1055. df1 equals itself.
  1056. >>> assert_frame_equal(df1, df1)
  1057. df1 differs from df2 as column 'b' is of a different type.
  1058. >>> assert_frame_equal(df1, df2)
  1059. Traceback (most recent call last):
  1060. ...
  1061. AssertionError: Attributes of DataFrame.iloc[:, 1] (column name="b") are different
  1062. Attribute "dtype" are different
  1063. [left]: int64
  1064. [right]: float64
  1065. Ignore differing dtypes in columns with check_dtype.
  1066. >>> assert_frame_equal(df1, df2, check_dtype=False)
  1067. """
  1068. __tracebackhide__ = True
  1069. _rtol = rtol if rtol is not lib.no_default else 1.0e-5
  1070. _atol = atol if atol is not lib.no_default else 1.0e-8
  1071. _check_exact = check_exact if check_exact is not lib.no_default else False
  1072. # instance validation
  1073. _check_isinstance(left, right, DataFrame)
  1074. if check_frame_type:
  1075. assert isinstance(left, type(right))
  1076. # assert_class_equal(left, right, obj=obj)
  1077. # shape comparison
  1078. if left.shape != right.shape:
  1079. raise_assert_detail(
  1080. obj, f"{obj} shape mismatch", f"{repr(left.shape)}", f"{repr(right.shape)}"
  1081. )
  1082. if check_flags:
  1083. assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}"
  1084. # index comparison
  1085. assert_index_equal(
  1086. left.index,
  1087. right.index,
  1088. exact=check_index_type,
  1089. check_names=check_names,
  1090. check_exact=_check_exact,
  1091. check_categorical=check_categorical,
  1092. check_order=not check_like,
  1093. rtol=_rtol,
  1094. atol=_atol,
  1095. obj=f"{obj}.index",
  1096. )
  1097. # column comparison
  1098. assert_index_equal(
  1099. left.columns,
  1100. right.columns,
  1101. exact=check_column_type,
  1102. check_names=check_names,
  1103. check_exact=_check_exact,
  1104. check_categorical=check_categorical,
  1105. check_order=not check_like,
  1106. rtol=_rtol,
  1107. atol=_atol,
  1108. obj=f"{obj}.columns",
  1109. )
  1110. if check_like:
  1111. left = left.reindex_like(right)
  1112. # compare by blocks
  1113. if by_blocks:
  1114. rblocks = right._to_dict_of_blocks()
  1115. lblocks = left._to_dict_of_blocks()
  1116. for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
  1117. assert dtype in lblocks
  1118. assert dtype in rblocks
  1119. assert_frame_equal(
  1120. lblocks[dtype], rblocks[dtype], check_dtype=check_dtype, obj=obj
  1121. )
  1122. # compare by columns
  1123. else:
  1124. for i, col in enumerate(left.columns):
  1125. # We have already checked that columns match, so we can do
  1126. # fast location-based lookups
  1127. lcol = left._ixs(i, axis=1)
  1128. rcol = right._ixs(i, axis=1)
  1129. # GH #38183
  1130. # use check_index=False, because we do not want to run
  1131. # assert_index_equal for each column,
  1132. # as we already checked it for the whole dataframe before.
  1133. assert_series_equal(
  1134. lcol,
  1135. rcol,
  1136. check_dtype=check_dtype,
  1137. check_index_type=check_index_type,
  1138. check_exact=check_exact,
  1139. check_names=check_names,
  1140. check_datetimelike_compat=check_datetimelike_compat,
  1141. check_categorical=check_categorical,
  1142. check_freq=check_freq,
  1143. obj=f'{obj}.iloc[:, {i}] (column name="{col}")',
  1144. rtol=rtol,
  1145. atol=atol,
  1146. check_index=False,
  1147. check_flags=False,
  1148. )
  1149. def assert_equal(left, right, **kwargs) -> None:
  1150. """
  1151. Wrapper for tm.assert_*_equal to dispatch to the appropriate test function.
  1152. Parameters
  1153. ----------
  1154. left, right : Index, Series, DataFrame, ExtensionArray, or np.ndarray
  1155. The two items to be compared.
  1156. **kwargs
  1157. All keyword arguments are passed through to the underlying assert method.
  1158. """
  1159. __tracebackhide__ = True
  1160. if isinstance(left, Index):
  1161. assert_index_equal(left, right, **kwargs)
  1162. if isinstance(left, (DatetimeIndex, TimedeltaIndex)):
  1163. assert left.freq == right.freq, (left.freq, right.freq)
  1164. elif isinstance(left, Series):
  1165. assert_series_equal(left, right, **kwargs)
  1166. elif isinstance(left, DataFrame):
  1167. assert_frame_equal(left, right, **kwargs)
  1168. elif isinstance(left, IntervalArray):
  1169. assert_interval_array_equal(left, right, **kwargs)
  1170. elif isinstance(left, PeriodArray):
  1171. assert_period_array_equal(left, right, **kwargs)
  1172. elif isinstance(left, DatetimeArray):
  1173. assert_datetime_array_equal(left, right, **kwargs)
  1174. elif isinstance(left, TimedeltaArray):
  1175. assert_timedelta_array_equal(left, right, **kwargs)
  1176. elif isinstance(left, ExtensionArray):
  1177. assert_extension_array_equal(left, right, **kwargs)
  1178. elif isinstance(left, np.ndarray):
  1179. assert_numpy_array_equal(left, right, **kwargs)
  1180. elif isinstance(left, str):
  1181. assert kwargs == {}
  1182. assert left == right
  1183. else:
  1184. assert kwargs == {}
  1185. assert_almost_equal(left, right)
  1186. def assert_sp_array_equal(left, right) -> None:
  1187. """
  1188. Check that the left and right SparseArray are equal.
  1189. Parameters
  1190. ----------
  1191. left : SparseArray
  1192. right : SparseArray
  1193. """
  1194. _check_isinstance(left, right, pd.arrays.SparseArray)
  1195. assert_numpy_array_equal(left.sp_values, right.sp_values)
  1196. # SparseIndex comparison
  1197. assert isinstance(left.sp_index, SparseIndex)
  1198. assert isinstance(right.sp_index, SparseIndex)
  1199. left_index = left.sp_index
  1200. right_index = right.sp_index
  1201. if not left_index.equals(right_index):
  1202. raise_assert_detail(
  1203. "SparseArray.index", "index are not equal", left_index, right_index
  1204. )
  1205. else:
  1206. # Just ensure a
  1207. pass
  1208. assert_attr_equal("fill_value", left, right)
  1209. assert_attr_equal("dtype", left, right)
  1210. assert_numpy_array_equal(left.to_dense(), right.to_dense())
  1211. def assert_contains_all(iterable, dic) -> None:
  1212. for k in iterable:
  1213. assert k in dic, f"Did not contain item: {repr(k)}"
  1214. def assert_copy(iter1, iter2, **eql_kwargs) -> None:
  1215. """
  1216. iter1, iter2: iterables that produce elements
  1217. comparable with assert_almost_equal
  1218. Checks that the elements are equal, but not
  1219. the same object. (Does not check that items
  1220. in sequences are also not the same object)
  1221. """
  1222. for elem1, elem2 in zip(iter1, iter2):
  1223. assert_almost_equal(elem1, elem2, **eql_kwargs)
  1224. msg = (
  1225. f"Expected object {repr(type(elem1))} and object {repr(type(elem2))} to be "
  1226. "different objects, but they were the same object."
  1227. )
  1228. assert elem1 is not elem2, msg
  1229. def is_extension_array_dtype_and_needs_i8_conversion(
  1230. left_dtype: DtypeObj, right_dtype: DtypeObj
  1231. ) -> bool:
  1232. """
  1233. Checks that we have the combination of an ExtensionArraydtype and
  1234. a dtype that should be converted to int64
  1235. Returns
  1236. -------
  1237. bool
  1238. Related to issue #37609
  1239. """
  1240. return isinstance(left_dtype, ExtensionDtype) and needs_i8_conversion(right_dtype)
  1241. def assert_indexing_slices_equivalent(ser: Series, l_slc: slice, i_slc: slice) -> None:
  1242. """
  1243. Check that ser.iloc[i_slc] matches ser.loc[l_slc] and, if applicable,
  1244. ser[l_slc].
  1245. """
  1246. expected = ser.iloc[i_slc]
  1247. assert_series_equal(ser.loc[l_slc], expected)
  1248. if not is_integer_dtype(ser.index):
  1249. # For integer indices, .loc and plain getitem are position-based.
  1250. assert_series_equal(ser[l_slc], expected)
  1251. def assert_metadata_equivalent(
  1252. left: DataFrame | Series, right: DataFrame | Series | None = None
  1253. ) -> None:
  1254. """
  1255. Check that ._metadata attributes are equivalent.
  1256. """
  1257. for attr in left._metadata:
  1258. val = getattr(left, attr, None)
  1259. if right is None:
  1260. assert val is None
  1261. else:
  1262. assert val == getattr(right, attr, None)