asserters.py 49 KB

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