PageRenderTime 54ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/pandas/util/testing.py

http://github.com/wesm/pandas
Python | 2951 lines | 2771 code | 46 blank | 134 comment | 59 complexity | 5035c8a995786d15bedccd1987a65a0f MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. from __future__ import division
  2. from collections import Counter
  3. from contextlib import contextmanager
  4. from datetime import datetime
  5. from functools import wraps
  6. import locale
  7. import os
  8. import re
  9. from shutil import rmtree
  10. import string
  11. import subprocess
  12. import sys
  13. import tempfile
  14. import traceback
  15. import warnings
  16. import numpy as np
  17. from numpy.random import rand, randn
  18. from pandas._libs import testing as _testing
  19. import pandas.compat as compat
  20. from pandas.compat import (
  21. PY2, PY3, filter, httplib, lmap, lrange, lzip, map, raise_with_traceback,
  22. range, string_types, u, unichr, zip)
  23. from pandas.core.dtypes.common import (
  24. is_bool, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype,
  25. is_datetimelike_v_numeric, is_datetimelike_v_object,
  26. is_extension_array_dtype, is_interval_dtype, is_list_like, is_number,
  27. is_period_dtype, is_sequence, is_timedelta64_dtype, needs_i8_conversion)
  28. from pandas.core.dtypes.missing import array_equivalent
  29. import pandas as pd
  30. from pandas import (
  31. Categorical, CategoricalIndex, DataFrame, DatetimeIndex, Index,
  32. IntervalIndex, MultiIndex, RangeIndex, Series, bdate_range)
  33. from pandas.core.algorithms import take_1d
  34. from pandas.core.arrays import (
  35. DatetimeArray, ExtensionArray, IntervalArray, PeriodArray, TimedeltaArray,
  36. period_array)
  37. import pandas.core.common as com
  38. from pandas.io.common import urlopen
  39. from pandas.io.formats.printing import pprint_thing
  40. N = 30
  41. K = 4
  42. _RAISE_NETWORK_ERROR_DEFAULT = False
  43. # set testing_mode
  44. _testing_mode_warnings = (DeprecationWarning, compat.ResourceWarning)
  45. def set_testing_mode():
  46. # set the testing mode filters
  47. testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
  48. if 'deprecate' in testing_mode:
  49. warnings.simplefilter('always', _testing_mode_warnings)
  50. def reset_testing_mode():
  51. # reset the testing mode filters
  52. testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
  53. if 'deprecate' in testing_mode:
  54. warnings.simplefilter('ignore', _testing_mode_warnings)
  55. set_testing_mode()
  56. def reset_display_options():
  57. """
  58. Reset the display options for printing and representing objects.
  59. """
  60. pd.reset_option('^display.', silent=True)
  61. def round_trip_pickle(obj, path=None):
  62. """
  63. Pickle an object and then read it again.
  64. Parameters
  65. ----------
  66. obj : pandas object
  67. The object to pickle and then re-read.
  68. path : str, default None
  69. The path where the pickled object is written and then read.
  70. Returns
  71. -------
  72. round_trip_pickled_object : pandas object
  73. The original object that was pickled and then re-read.
  74. """
  75. if path is None:
  76. path = u('__{random_bytes}__.pickle'.format(random_bytes=rands(10)))
  77. with ensure_clean(path) as path:
  78. pd.to_pickle(obj, path)
  79. return pd.read_pickle(path)
  80. def round_trip_pathlib(writer, reader, path=None):
  81. """
  82. Write an object to file specified by a pathlib.Path and read it back
  83. Parameters
  84. ----------
  85. writer : callable bound to pandas object
  86. IO writing function (e.g. DataFrame.to_csv )
  87. reader : callable
  88. IO reading function (e.g. pd.read_csv )
  89. path : str, default None
  90. The path where the object is written and then read.
  91. Returns
  92. -------
  93. round_trip_object : pandas object
  94. The original object that was serialized and then re-read.
  95. """
  96. import pytest
  97. Path = pytest.importorskip('pathlib').Path
  98. if path is None:
  99. path = '___pathlib___'
  100. with ensure_clean(path) as path:
  101. writer(Path(path))
  102. obj = reader(Path(path))
  103. return obj
  104. def round_trip_localpath(writer, reader, path=None):
  105. """
  106. Write an object to file specified by a py.path LocalPath and read it back
  107. Parameters
  108. ----------
  109. writer : callable bound to pandas object
  110. IO writing function (e.g. DataFrame.to_csv )
  111. reader : callable
  112. IO reading function (e.g. pd.read_csv )
  113. path : str, default None
  114. The path where the object is written and then read.
  115. Returns
  116. -------
  117. round_trip_object : pandas object
  118. The original object that was serialized and then re-read.
  119. """
  120. import pytest
  121. LocalPath = pytest.importorskip('py.path').local
  122. if path is None:
  123. path = '___localpath___'
  124. with ensure_clean(path) as path:
  125. writer(LocalPath(path))
  126. obj = reader(LocalPath(path))
  127. return obj
  128. @contextmanager
  129. def decompress_file(path, compression):
  130. """
  131. Open a compressed file and return a file object
  132. Parameters
  133. ----------
  134. path : str
  135. The path where the file is read from
  136. compression : {'gzip', 'bz2', 'zip', 'xz', None}
  137. Name of the decompression to use
  138. Returns
  139. -------
  140. f : file object
  141. """
  142. if compression is None:
  143. f = open(path, 'rb')
  144. elif compression == 'gzip':
  145. import gzip
  146. f = gzip.open(path, 'rb')
  147. elif compression == 'bz2':
  148. import bz2
  149. f = bz2.BZ2File(path, 'rb')
  150. elif compression == 'xz':
  151. lzma = compat.import_lzma()
  152. f = lzma.LZMAFile(path, 'rb')
  153. elif compression == 'zip':
  154. import zipfile
  155. zip_file = zipfile.ZipFile(path)
  156. zip_names = zip_file.namelist()
  157. if len(zip_names) == 1:
  158. f = zip_file.open(zip_names.pop())
  159. else:
  160. raise ValueError('ZIP file {} error. Only one file per ZIP.'
  161. .format(path))
  162. else:
  163. msg = 'Unrecognized compression type: {}'.format(compression)
  164. raise ValueError(msg)
  165. try:
  166. yield f
  167. finally:
  168. f.close()
  169. if compression == "zip":
  170. zip_file.close()
  171. def write_to_compressed(compression, path, data, dest="test"):
  172. """
  173. Write data to a compressed file.
  174. Parameters
  175. ----------
  176. compression : {'gzip', 'bz2', 'zip', 'xz'}
  177. The compression type to use.
  178. path : str
  179. The file path to write the data.
  180. data : str
  181. The data to write.
  182. dest : str, default "test"
  183. The destination file (for ZIP only)
  184. Raises
  185. ------
  186. ValueError : An invalid compression value was passed in.
  187. """
  188. if compression == "zip":
  189. import zipfile
  190. compress_method = zipfile.ZipFile
  191. elif compression == "gzip":
  192. import gzip
  193. compress_method = gzip.GzipFile
  194. elif compression == "bz2":
  195. import bz2
  196. compress_method = bz2.BZ2File
  197. elif compression == "xz":
  198. lzma = compat.import_lzma()
  199. compress_method = lzma.LZMAFile
  200. else:
  201. msg = "Unrecognized compression type: {}".format(compression)
  202. raise ValueError(msg)
  203. if compression == "zip":
  204. mode = "w"
  205. args = (dest, data)
  206. method = "writestr"
  207. else:
  208. mode = "wb"
  209. args = (data,)
  210. method = "write"
  211. with compress_method(path, mode=mode) as f:
  212. getattr(f, method)(*args)
  213. def assert_almost_equal(left, right, check_dtype="equiv",
  214. check_less_precise=False, **kwargs):
  215. """
  216. Check that the left and right objects are approximately equal.
  217. By approximately equal, we refer to objects that are numbers or that
  218. contain numbers which may be equivalent to specific levels of precision.
  219. Parameters
  220. ----------
  221. left : object
  222. right : object
  223. check_dtype : bool / string {'equiv'}, default 'equiv'
  224. Check dtype if both a and b are the same type. If 'equiv' is passed in,
  225. then `RangeIndex` and `Int64Index` are also considered equivalent
  226. when doing type checking.
  227. check_less_precise : bool or int, default False
  228. Specify comparison precision. 5 digits (False) or 3 digits (True)
  229. after decimal points are compared. If int, then specify the number
  230. of digits to compare.
  231. When comparing two numbers, if the first number has magnitude less
  232. than 1e-5, we compare the two numbers directly and check whether
  233. they are equivalent within the specified precision. Otherwise, we
  234. compare the **ratio** of the second number to the first number and
  235. check whether it is equivalent to 1 within the specified precision.
  236. """
  237. if isinstance(left, pd.Index):
  238. return assert_index_equal(left, right,
  239. check_exact=False,
  240. exact=check_dtype,
  241. check_less_precise=check_less_precise,
  242. **kwargs)
  243. elif isinstance(left, pd.Series):
  244. return assert_series_equal(left, right,
  245. check_exact=False,
  246. check_dtype=check_dtype,
  247. check_less_precise=check_less_precise,
  248. **kwargs)
  249. elif isinstance(left, pd.DataFrame):
  250. return assert_frame_equal(left, right,
  251. check_exact=False,
  252. check_dtype=check_dtype,
  253. check_less_precise=check_less_precise,
  254. **kwargs)
  255. else:
  256. # Other sequences.
  257. if check_dtype:
  258. if is_number(left) and is_number(right):
  259. # Do not compare numeric classes, like np.float64 and float.
  260. pass
  261. elif is_bool(left) and is_bool(right):
  262. # Do not compare bool classes, like np.bool_ and bool.
  263. pass
  264. else:
  265. if (isinstance(left, np.ndarray) or
  266. isinstance(right, np.ndarray)):
  267. obj = "numpy array"
  268. else:
  269. obj = "Input"
  270. assert_class_equal(left, right, obj=obj)
  271. return _testing.assert_almost_equal(
  272. left, right,
  273. check_dtype=check_dtype,
  274. check_less_precise=check_less_precise,
  275. **kwargs)
  276. def _check_isinstance(left, right, cls):
  277. """
  278. Helper method for our assert_* methods that ensures that
  279. the two objects being compared have the right type before
  280. proceeding with the comparison.
  281. Parameters
  282. ----------
  283. left : The first object being compared.
  284. right : The second object being compared.
  285. cls : The class type to check against.
  286. Raises
  287. ------
  288. AssertionError : Either `left` or `right` is not an instance of `cls`.
  289. """
  290. err_msg = "{name} Expected type {exp_type}, found {act_type} instead"
  291. cls_name = cls.__name__
  292. if not isinstance(left, cls):
  293. raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
  294. act_type=type(left)))
  295. if not isinstance(right, cls):
  296. raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
  297. act_type=type(right)))
  298. def assert_dict_equal(left, right, compare_keys=True):
  299. _check_isinstance(left, right, dict)
  300. return _testing.assert_dict_equal(left, right, compare_keys=compare_keys)
  301. def randbool(size=(), p=0.5):
  302. return rand(*size) <= p
  303. RANDS_CHARS = np.array(list(string.ascii_letters + string.digits),
  304. dtype=(np.str_, 1))
  305. RANDU_CHARS = np.array(list(u("").join(map(unichr, lrange(1488, 1488 + 26))) +
  306. string.digits), dtype=(np.unicode_, 1))
  307. def rands_array(nchars, size, dtype='O'):
  308. """Generate an array of byte strings."""
  309. retval = (np.random.choice(RANDS_CHARS, size=nchars * np.prod(size))
  310. .view((np.str_, nchars)).reshape(size))
  311. if dtype is None:
  312. return retval
  313. else:
  314. return retval.astype(dtype)
  315. def randu_array(nchars, size, dtype='O'):
  316. """Generate an array of unicode strings."""
  317. retval = (np.random.choice(RANDU_CHARS, size=nchars * np.prod(size))
  318. .view((np.unicode_, nchars)).reshape(size))
  319. if dtype is None:
  320. return retval
  321. else:
  322. return retval.astype(dtype)
  323. def rands(nchars):
  324. """
  325. Generate one random byte string.
  326. See `rands_array` if you want to create an array of random strings.
  327. """
  328. return ''.join(np.random.choice(RANDS_CHARS, nchars))
  329. def randu(nchars):
  330. """
  331. Generate one random unicode string.
  332. See `randu_array` if you want to create an array of random unicode strings.
  333. """
  334. return ''.join(np.random.choice(RANDU_CHARS, nchars))
  335. def close(fignum=None):
  336. from matplotlib.pyplot import get_fignums, close as _close
  337. if fignum is None:
  338. for fignum in get_fignums():
  339. _close(fignum)
  340. else:
  341. _close(fignum)
  342. # -----------------------------------------------------------------------------
  343. # locale utilities
  344. def check_output(*popenargs, **kwargs):
  345. # shamelessly taken from Python 2.7 source
  346. r"""Run command with arguments and return its output as a byte string.
  347. If the exit code was non-zero it raises a CalledProcessError. The
  348. CalledProcessError object will have the return code in the returncode
  349. attribute and output in the output attribute.
  350. The arguments are the same as for the Popen constructor. Example:
  351. >>> check_output(["ls", "-l", "/dev/null"])
  352. 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
  353. The stdout argument is not allowed as it is used internally.
  354. To capture standard error in the result, use stderr=STDOUT.
  355. >>> check_output(["/bin/sh", "-c",
  356. ... "ls -l non_existent_file ; exit 0"],
  357. ... stderr=STDOUT)
  358. 'ls: non_existent_file: No such file or directory\n'
  359. """
  360. if 'stdout' in kwargs:
  361. raise ValueError('stdout argument not allowed, it will be overridden.')
  362. process = subprocess.Popen(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  363. *popenargs, **kwargs)
  364. output, unused_err = process.communicate()
  365. retcode = process.poll()
  366. if retcode:
  367. cmd = kwargs.get("args")
  368. if cmd is None:
  369. cmd = popenargs[0]
  370. raise subprocess.CalledProcessError(retcode, cmd, output=output)
  371. return output
  372. def _default_locale_getter():
  373. try:
  374. raw_locales = check_output(['locale -a'], shell=True)
  375. except subprocess.CalledProcessError as e:
  376. raise type(e)("{exception}, the 'locale -a' command cannot be found "
  377. "on your system".format(exception=e))
  378. return raw_locales
  379. def get_locales(prefix=None, normalize=True,
  380. locale_getter=_default_locale_getter):
  381. """Get all the locales that are available on the system.
  382. Parameters
  383. ----------
  384. prefix : str
  385. If not ``None`` then return only those locales with the prefix
  386. provided. For example to get all English language locales (those that
  387. start with ``"en"``), pass ``prefix="en"``.
  388. normalize : bool
  389. Call ``locale.normalize`` on the resulting list of available locales.
  390. If ``True``, only locales that can be set without throwing an
  391. ``Exception`` are returned.
  392. locale_getter : callable
  393. The function to use to retrieve the current locales. This should return
  394. a string with each locale separated by a newline character.
  395. Returns
  396. -------
  397. locales : list of strings
  398. A list of locale strings that can be set with ``locale.setlocale()``.
  399. For example::
  400. locale.setlocale(locale.LC_ALL, locale_string)
  401. On error will return None (no locale available, e.g. Windows)
  402. """
  403. try:
  404. raw_locales = locale_getter()
  405. except Exception:
  406. return None
  407. try:
  408. # raw_locales is "\n" separated list of locales
  409. # it may contain non-decodable parts, so split
  410. # extract what we can and then rejoin.
  411. raw_locales = raw_locales.split(b'\n')
  412. out_locales = []
  413. for x in raw_locales:
  414. if PY3:
  415. out_locales.append(str(
  416. x, encoding=pd.options.display.encoding))
  417. else:
  418. out_locales.append(str(x))
  419. except TypeError:
  420. pass
  421. if prefix is None:
  422. return _valid_locales(out_locales, normalize)
  423. pattern = re.compile('{prefix}.*'.format(prefix=prefix))
  424. found = pattern.findall('\n'.join(out_locales))
  425. return _valid_locales(found, normalize)
  426. @contextmanager
  427. def set_locale(new_locale, lc_var=locale.LC_ALL):
  428. """Context manager for temporarily setting a locale.
  429. Parameters
  430. ----------
  431. new_locale : str or tuple
  432. A string of the form <language_country>.<encoding>. For example to set
  433. the current locale to US English with a UTF8 encoding, you would pass
  434. "en_US.UTF-8".
  435. lc_var : int, default `locale.LC_ALL`
  436. The category of the locale being set.
  437. Notes
  438. -----
  439. This is useful when you want to run a particular block of code under a
  440. particular locale, without globally setting the locale. This probably isn't
  441. thread-safe.
  442. """
  443. current_locale = locale.getlocale()
  444. try:
  445. locale.setlocale(lc_var, new_locale)
  446. normalized_locale = locale.getlocale()
  447. if com._all_not_none(*normalized_locale):
  448. yield '.'.join(normalized_locale)
  449. else:
  450. yield new_locale
  451. finally:
  452. locale.setlocale(lc_var, current_locale)
  453. def can_set_locale(lc, lc_var=locale.LC_ALL):
  454. """
  455. Check to see if we can set a locale, and subsequently get the locale,
  456. without raising an Exception.
  457. Parameters
  458. ----------
  459. lc : str
  460. The locale to attempt to set.
  461. lc_var : int, default `locale.LC_ALL`
  462. The category of the locale being set.
  463. Returns
  464. -------
  465. is_valid : bool
  466. Whether the passed locale can be set
  467. """
  468. try:
  469. with set_locale(lc, lc_var=lc_var):
  470. pass
  471. except (ValueError,
  472. locale.Error): # horrible name for a Exception subclass
  473. return False
  474. else:
  475. return True
  476. def _valid_locales(locales, normalize):
  477. """Return a list of normalized locales that do not throw an ``Exception``
  478. when set.
  479. Parameters
  480. ----------
  481. locales : str
  482. A string where each locale is separated by a newline.
  483. normalize : bool
  484. Whether to call ``locale.normalize`` on each locale.
  485. Returns
  486. -------
  487. valid_locales : list
  488. A list of valid locales.
  489. """
  490. if normalize:
  491. normalizer = lambda x: locale.normalize(x.strip())
  492. else:
  493. normalizer = lambda x: x.strip()
  494. return list(filter(can_set_locale, map(normalizer, locales)))
  495. # -----------------------------------------------------------------------------
  496. # Stdout / stderr decorators
  497. @contextmanager
  498. def set_defaultencoding(encoding):
  499. """
  500. Set default encoding (as given by sys.getdefaultencoding()) to the given
  501. encoding; restore on exit.
  502. Parameters
  503. ----------
  504. encoding : str
  505. """
  506. if not PY2:
  507. raise ValueError("set_defaultencoding context is only available "
  508. "in Python 2.")
  509. orig = sys.getdefaultencoding()
  510. reload(sys) # noqa:F821
  511. sys.setdefaultencoding(encoding)
  512. try:
  513. yield
  514. finally:
  515. sys.setdefaultencoding(orig)
  516. # -----------------------------------------------------------------------------
  517. # contextmanager to ensure the file cleanup
  518. @contextmanager
  519. def ensure_clean(filename=None, return_filelike=False):
  520. """Gets a temporary path and agrees to remove on close.
  521. Parameters
  522. ----------
  523. filename : str (optional)
  524. if None, creates a temporary file which is then removed when out of
  525. scope. if passed, creates temporary file with filename as ending.
  526. return_filelike : bool (default False)
  527. if True, returns a file-like which is *always* cleaned. Necessary for
  528. savefig and other functions which want to append extensions.
  529. """
  530. filename = filename or ''
  531. fd = None
  532. if return_filelike:
  533. f = tempfile.TemporaryFile(suffix=filename)
  534. try:
  535. yield f
  536. finally:
  537. f.close()
  538. else:
  539. # don't generate tempfile if using a path with directory specified
  540. if len(os.path.dirname(filename)):
  541. raise ValueError("Can't pass a qualified name to ensure_clean()")
  542. try:
  543. fd, filename = tempfile.mkstemp(suffix=filename)
  544. except UnicodeEncodeError:
  545. import pytest
  546. pytest.skip('no unicode file names on this system')
  547. try:
  548. yield filename
  549. finally:
  550. try:
  551. os.close(fd)
  552. except Exception:
  553. print("Couldn't close file descriptor: {fdesc} (file: {fname})"
  554. .format(fdesc=fd, fname=filename))
  555. try:
  556. if os.path.exists(filename):
  557. os.remove(filename)
  558. except Exception as e:
  559. print("Exception on removing file: {error}".format(error=e))
  560. @contextmanager
  561. def ensure_clean_dir():
  562. """
  563. Get a temporary directory path and agrees to remove on close.
  564. Yields
  565. ------
  566. Temporary directory path
  567. """
  568. directory_name = tempfile.mkdtemp(suffix='')
  569. try:
  570. yield directory_name
  571. finally:
  572. try:
  573. rmtree(directory_name)
  574. except Exception:
  575. pass
  576. @contextmanager
  577. def ensure_safe_environment_variables():
  578. """
  579. Get a context manager to safely set environment variables
  580. All changes will be undone on close, hence environment variables set
  581. within this contextmanager will neither persist nor change global state.
  582. """
  583. saved_environ = dict(os.environ)
  584. try:
  585. yield
  586. finally:
  587. os.environ.clear()
  588. os.environ.update(saved_environ)
  589. # -----------------------------------------------------------------------------
  590. # Comparators
  591. def equalContents(arr1, arr2):
  592. """Checks if the set of unique elements of arr1 and arr2 are equivalent.
  593. """
  594. return frozenset(arr1) == frozenset(arr2)
  595. def assert_index_equal(left, right, exact='equiv', check_names=True,
  596. check_less_precise=False, check_exact=True,
  597. check_categorical=True, obj='Index'):
  598. """Check that left and right Index are equal.
  599. Parameters
  600. ----------
  601. left : Index
  602. right : Index
  603. exact : bool / string {'equiv'}, default 'equiv'
  604. Whether to check the Index class, dtype and inferred_type
  605. are identical. If 'equiv', then RangeIndex can be substituted for
  606. Int64Index as well.
  607. check_names : bool, default True
  608. Whether to check the names attribute.
  609. check_less_precise : bool or int, default False
  610. Specify comparison precision. Only used when check_exact is False.
  611. 5 digits (False) or 3 digits (True) after decimal points are compared.
  612. If int, then specify the digits to compare
  613. check_exact : bool, default True
  614. Whether to compare number exactly.
  615. check_categorical : bool, default True
  616. Whether to compare internal Categorical exactly.
  617. obj : str, default 'Index'
  618. Specify object name being compared, internally used to show appropriate
  619. assertion message
  620. """
  621. __tracebackhide__ = True
  622. def _check_types(l, r, obj='Index'):
  623. if exact:
  624. assert_class_equal(l, r, exact=exact, obj=obj)
  625. # Skip exact dtype checking when `check_categorical` is False
  626. if check_categorical:
  627. assert_attr_equal('dtype', l, r, obj=obj)
  628. # allow string-like to have different inferred_types
  629. if l.inferred_type in ('string', 'unicode'):
  630. assert r.inferred_type in ('string', 'unicode')
  631. else:
  632. assert_attr_equal('inferred_type', l, r, obj=obj)
  633. def _get_ilevel_values(index, level):
  634. # accept level number only
  635. unique = index.levels[level]
  636. labels = index.codes[level]
  637. filled = take_1d(unique.values, labels, fill_value=unique._na_value)
  638. values = unique._shallow_copy(filled, name=index.names[level])
  639. return values
  640. # instance validation
  641. _check_isinstance(left, right, Index)
  642. # class / dtype comparison
  643. _check_types(left, right, obj=obj)
  644. # level comparison
  645. if left.nlevels != right.nlevels:
  646. msg1 = '{obj} levels are different'.format(obj=obj)
  647. msg2 = '{nlevels}, {left}'.format(nlevels=left.nlevels, left=left)
  648. msg3 = '{nlevels}, {right}'.format(nlevels=right.nlevels, right=right)
  649. raise_assert_detail(obj, msg1, msg2, msg3)
  650. # length comparison
  651. if len(left) != len(right):
  652. msg1 = '{obj} length are different'.format(obj=obj)
  653. msg2 = '{length}, {left}'.format(length=len(left), left=left)
  654. msg3 = '{length}, {right}'.format(length=len(right), right=right)
  655. raise_assert_detail(obj, msg1, msg2, msg3)
  656. # MultiIndex special comparison for little-friendly error messages
  657. if left.nlevels > 1:
  658. for level in range(left.nlevels):
  659. # cannot use get_level_values here because it can change dtype
  660. llevel = _get_ilevel_values(left, level)
  661. rlevel = _get_ilevel_values(right, level)
  662. lobj = 'MultiIndex level [{level}]'.format(level=level)
  663. assert_index_equal(llevel, rlevel,
  664. exact=exact, check_names=check_names,
  665. check_less_precise=check_less_precise,
  666. check_exact=check_exact, obj=lobj)
  667. # get_level_values may change dtype
  668. _check_types(left.levels[level], right.levels[level], obj=obj)
  669. # skip exact index checking when `check_categorical` is False
  670. if check_exact and check_categorical:
  671. if not left.equals(right):
  672. diff = np.sum((left.values != right.values)
  673. .astype(int)) * 100.0 / len(left)
  674. msg = '{obj} values are different ({pct} %)'.format(
  675. obj=obj, pct=np.round(diff, 5))
  676. raise_assert_detail(obj, msg, left, right)
  677. else:
  678. _testing.assert_almost_equal(left.values, right.values,
  679. check_less_precise=check_less_precise,
  680. check_dtype=exact,
  681. obj=obj, lobj=left, robj=right)
  682. # metadata comparison
  683. if check_names:
  684. assert_attr_equal('names', left, right, obj=obj)
  685. if isinstance(left, pd.PeriodIndex) or isinstance(right, pd.PeriodIndex):
  686. assert_attr_equal('freq', left, right, obj=obj)
  687. if (isinstance(left, pd.IntervalIndex) or
  688. isinstance(right, pd.IntervalIndex)):
  689. assert_interval_array_equal(left.values, right.values)
  690. if check_categorical:
  691. if is_categorical_dtype(left) or is_categorical_dtype(right):
  692. assert_categorical_equal(left.values, right.values,
  693. obj='{obj} category'.format(obj=obj))
  694. def assert_class_equal(left, right, exact=True, obj='Input'):
  695. """checks classes are equal."""
  696. __tracebackhide__ = True
  697. def repr_class(x):
  698. if isinstance(x, Index):
  699. # return Index as it is to include values in the error message
  700. return x
  701. try:
  702. return x.__class__.__name__
  703. except AttributeError:
  704. return repr(type(x))
  705. if exact == 'equiv':
  706. if type(left) != type(right):
  707. # allow equivalence of Int64Index/RangeIndex
  708. types = {type(left).__name__, type(right).__name__}
  709. if len(types - {'Int64Index', 'RangeIndex'}):
  710. msg = '{obj} classes are not equivalent'.format(obj=obj)
  711. raise_assert_detail(obj, msg, repr_class(left),
  712. repr_class(right))
  713. elif exact:
  714. if type(left) != type(right):
  715. msg = '{obj} classes are different'.format(obj=obj)
  716. raise_assert_detail(obj, msg, repr_class(left),
  717. repr_class(right))
  718. def assert_attr_equal(attr, left, right, obj='Attributes'):
  719. """checks attributes are equal. Both objects must have attribute.
  720. Parameters
  721. ----------
  722. attr : str
  723. Attribute name being compared.
  724. left : object
  725. right : object
  726. obj : str, default 'Attributes'
  727. Specify object name being compared, internally used to show appropriate
  728. assertion message
  729. """
  730. __tracebackhide__ = True
  731. left_attr = getattr(left, attr)
  732. right_attr = getattr(right, attr)
  733. if left_attr is right_attr:
  734. return True
  735. elif (is_number(left_attr) and np.isnan(left_attr) and
  736. is_number(right_attr) and np.isnan(right_attr)):
  737. # np.nan
  738. return True
  739. try:
  740. result = left_attr == right_attr
  741. except TypeError:
  742. # datetimetz on rhs may raise TypeError
  743. result = False
  744. if not isinstance(result, bool):
  745. result = result.all()
  746. if result:
  747. return True
  748. else:
  749. msg = 'Attribute "{attr}" are different'.format(attr=attr)
  750. raise_assert_detail(obj, msg, left_attr, right_attr)
  751. def assert_is_valid_plot_return_object(objs):
  752. import matplotlib.pyplot as plt
  753. if isinstance(objs, (pd.Series, np.ndarray)):
  754. for el in objs.ravel():
  755. msg = ("one of 'objs' is not a matplotlib Axes instance, type "
  756. "encountered {name!r}").format(name=el.__class__.__name__)
  757. assert isinstance(el, (plt.Axes, dict)), msg
  758. else:
  759. assert isinstance(objs, (plt.Artist, tuple, dict)), (
  760. 'objs is neither an ndarray of Artist instances nor a '
  761. 'single Artist instance, tuple, or dict, "objs" is a {name!r}'
  762. .format(name=objs.__class__.__name__))
  763. def isiterable(obj):
  764. return hasattr(obj, '__iter__')
  765. def is_sorted(seq):
  766. if isinstance(seq, (Index, Series)):
  767. seq = seq.values
  768. # sorting does not change precisions
  769. return assert_numpy_array_equal(seq, np.sort(np.array(seq)))
  770. def assert_categorical_equal(left, right, check_dtype=True,
  771. check_category_order=True, obj='Categorical'):
  772. """Test that Categoricals are equivalent.
  773. Parameters
  774. ----------
  775. left : Categorical
  776. right : Categorical
  777. check_dtype : bool, default True
  778. Check that integer dtype of the codes are the same
  779. check_category_order : bool, default True
  780. Whether the order of the categories should be compared, which
  781. implies identical integer codes. If False, only the resulting
  782. values are compared. The ordered attribute is
  783. checked regardless.
  784. obj : str, default 'Categorical'
  785. Specify object name being compared, internally used to show appropriate
  786. assertion message
  787. """
  788. _check_isinstance(left, right, Categorical)
  789. if check_category_order:
  790. assert_index_equal(left.categories, right.categories,
  791. obj='{obj}.categories'.format(obj=obj))
  792. assert_numpy_array_equal(left.codes, right.codes,
  793. check_dtype=check_dtype,
  794. obj='{obj}.codes'.format(obj=obj))
  795. else:
  796. assert_index_equal(left.categories.sort_values(),
  797. right.categories.sort_values(),
  798. obj='{obj}.categories'.format(obj=obj))
  799. assert_index_equal(left.categories.take(left.codes),
  800. right.categories.take(right.codes),
  801. obj='{obj}.values'.format(obj=obj))
  802. assert_attr_equal('ordered', left, right, obj=obj)
  803. def assert_interval_array_equal(left, right, exact='equiv',
  804. obj='IntervalArray'):
  805. """Test that two IntervalArrays are equivalent.
  806. Parameters
  807. ----------
  808. left, right : IntervalArray
  809. The IntervalArrays to compare.
  810. exact : bool / string {'equiv'}, default 'equiv'
  811. Whether to check the Index class, dtype and inferred_type
  812. are identical. If 'equiv', then RangeIndex can be substituted for
  813. Int64Index as well.
  814. obj : str, default 'IntervalArray'
  815. Specify object name being compared, internally used to show appropriate
  816. assertion message
  817. """
  818. _check_isinstance(left, right, IntervalArray)
  819. assert_index_equal(left.left, right.left, exact=exact,
  820. obj='{obj}.left'.format(obj=obj))
  821. assert_index_equal(left.right, right.right, exact=exact,
  822. obj='{obj}.left'.format(obj=obj))
  823. assert_attr_equal('closed', left, right, obj=obj)
  824. def assert_period_array_equal(left, right, obj='PeriodArray'):
  825. _check_isinstance(left, right, PeriodArray)
  826. assert_numpy_array_equal(left._data, right._data,
  827. obj='{obj}.values'.format(obj=obj))
  828. assert_attr_equal('freq', left, right, obj=obj)
  829. def assert_datetime_array_equal(left, right, obj='DatetimeArray'):
  830. __tracebackhide__ = True
  831. _check_isinstance(left, right, DatetimeArray)
  832. assert_numpy_array_equal(left._data, right._data,
  833. obj='{obj}._data'.format(obj=obj))
  834. assert_attr_equal('freq', left, right, obj=obj)
  835. assert_attr_equal('tz', left, right, obj=obj)
  836. def assert_timedelta_array_equal(left, right, obj='TimedeltaArray'):
  837. __tracebackhide__ = True
  838. _check_isinstance(left, right, TimedeltaArray)
  839. assert_numpy_array_equal(left._data, right._data,
  840. obj='{obj}._data'.format(obj=obj))
  841. assert_attr_equal('freq', left, right, obj=obj)
  842. def raise_assert_detail(obj, message, left, right, diff=None):
  843. __tracebackhide__ = True
  844. if isinstance(left, np.ndarray):
  845. left = pprint_thing(left)
  846. elif is_categorical_dtype(left):
  847. left = repr(left)
  848. if PY2 and isinstance(left, string_types):
  849. # left needs to be printable in native text type in python2
  850. left = left.encode('utf-8')
  851. if isinstance(right, np.ndarray):
  852. right = pprint_thing(right)
  853. elif is_categorical_dtype(right):
  854. right = repr(right)
  855. if PY2 and isinstance(right, string_types):
  856. # right needs to be printable in native text type in python2
  857. right = right.encode('utf-8')
  858. msg = """{obj} are different
  859. {message}
  860. [left]: {left}
  861. [right]: {right}""".format(obj=obj, message=message, left=left, right=right)
  862. if diff is not None:
  863. msg += "\n[diff]: {diff}".format(diff=diff)
  864. raise AssertionError(msg)
  865. def assert_numpy_array_equal(left, right, strict_nan=False,
  866. check_dtype=True, err_msg=None,
  867. check_same=None, obj='numpy array'):
  868. """ Checks that 'np.ndarray' is equivalent
  869. Parameters
  870. ----------
  871. left : np.ndarray or iterable
  872. right : np.ndarray or iterable
  873. strict_nan : bool, default False
  874. If True, consider NaN and None to be different.
  875. check_dtype: bool, default True
  876. check dtype if both a and b are np.ndarray
  877. err_msg : str, default None
  878. If provided, used as assertion message
  879. check_same : None|'copy'|'same', default None
  880. Ensure left and right refer/do not refer to the same memory area
  881. obj : str, default 'numpy array'
  882. Specify object name being compared, internally used to show appropriate
  883. assertion message
  884. """
  885. __tracebackhide__ = True
  886. # instance validation
  887. # Show a detailed error message when classes are different
  888. assert_class_equal(left, right, obj=obj)
  889. # both classes must be an np.ndarray
  890. _check_isinstance(left, right, np.ndarray)
  891. def _get_base(obj):
  892. return obj.base if getattr(obj, 'base', None) is not None else obj
  893. left_base = _get_base(left)
  894. right_base = _get_base(right)
  895. if check_same == 'same':
  896. if left_base is not right_base:
  897. msg = "{left!r} is not {right!r}".format(
  898. left=left_base, right=right_base)
  899. raise AssertionError(msg)
  900. elif check_same == 'copy':
  901. if left_base is right_base:
  902. msg = "{left!r} is {right!r}".format(
  903. left=left_base, right=right_base)
  904. raise AssertionError(msg)
  905. def _raise(left, right, err_msg):
  906. if err_msg is None:
  907. if left.shape != right.shape:
  908. raise_assert_detail(obj, '{obj} shapes are different'
  909. .format(obj=obj), left.shape, right.shape)
  910. diff = 0
  911. for l, r in zip(left, right):
  912. # count up differences
  913. if not array_equivalent(l, r, strict_nan=strict_nan):
  914. diff += 1
  915. diff = diff * 100.0 / left.size
  916. msg = '{obj} values are different ({pct} %)'.format(
  917. obj=obj, pct=np.round(diff, 5))
  918. raise_assert_detail(obj, msg, left, right)
  919. raise AssertionError(err_msg)
  920. # compare shape and values
  921. if not array_equivalent(left, right, strict_nan=strict_nan):
  922. _raise(left, right, err_msg)
  923. if check_dtype:
  924. if isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
  925. assert_attr_equal('dtype', left, right, obj=obj)
  926. return True
  927. def assert_extension_array_equal(left, right, check_dtype=True,
  928. check_less_precise=False,
  929. check_exact=False):
  930. """Check that left and right ExtensionArrays are equal.
  931. Parameters
  932. ----------
  933. left, right : ExtensionArray
  934. The two arrays to compare
  935. check_dtype : bool, default True
  936. Whether to check if the ExtensionArray dtypes are identical.
  937. check_less_precise : bool or int, default False
  938. Specify comparison precision. Only used when check_exact is False.
  939. 5 digits (False) or 3 digits (True) after decimal points are compared.
  940. If int, then specify the digits to compare.
  941. check_exact : bool, default False
  942. Whether to compare number exactly.
  943. Notes
  944. -----
  945. Missing values are checked separately from valid values.
  946. A mask of missing values is computed for each and checked to match.
  947. The remaining all-valid values are cast to object dtype and checked.
  948. """
  949. assert isinstance(left, ExtensionArray), 'left is not an ExtensionArray'
  950. assert isinstance(right, ExtensionArray), 'right is not an ExtensionArray'
  951. if check_dtype:
  952. assert_attr_equal('dtype', left, right, obj='ExtensionArray')
  953. if hasattr(left, "asi8") and type(right) == type(left):
  954. # Avoid slow object-dtype comparisons
  955. assert_numpy_array_equal(left.asi8, right.asi8)
  956. return
  957. left_na = np.asarray(left.isna())
  958. right_na = np.asarray(right.isna())
  959. assert_numpy_array_equal(left_na, right_na, obj='ExtensionArray NA mask')
  960. left_valid = np.asarray(left[~left_na].astype(object))
  961. right_valid = np.asarray(right[~right_na].astype(object))
  962. if check_exact:
  963. assert_numpy_array_equal(left_valid, right_valid, obj='ExtensionArray')
  964. else:
  965. _testing.assert_almost_equal(left_valid, right_valid,
  966. check_dtype=check_dtype,
  967. check_less_precise=check_less_precise,
  968. obj='ExtensionArray')
  969. # This could be refactored to use the NDFrame.equals method
  970. def assert_series_equal(left, right, check_dtype=True,
  971. check_index_type='equiv',
  972. check_series_type=True,
  973. check_less_precise=False,
  974. check_names=True,
  975. check_exact=False,
  976. check_datetimelike_compat=False,
  977. check_categorical=True,
  978. obj='Series'):
  979. """Check that left and right Series are equal.
  980. Parameters
  981. ----------
  982. left : Series
  983. right : Series
  984. check_dtype : bool, default True
  985. Whether to check the Series dtype is identical.
  986. check_index_type : bool / string {'equiv'}, default 'equiv'
  987. Whether to check the Index class, dtype and inferred_type
  988. are identical.
  989. check_series_type : bool, default True
  990. Whether to check the Series class is identical.
  991. check_less_precise : bool or int, default False
  992. Specify comparison precision. Only used when check_exact is False.
  993. 5 digits (False) or 3 digits (True) after decimal points are compared.
  994. If int, then specify the digits to compare.
  995. check_names : bool, default True
  996. Whether to check the Series and Index names attribute.
  997. check_exact : bool, default False
  998. Whether to compare number exactly.
  999. check_datetimelike_compat : bool, default False
  1000. Compare datetime-like which is comparable ignoring dtype.
  1001. check_categorical : bool, default True
  1002. Whether to compare internal Categorical exactly.
  1003. obj : str, default 'Series'
  1004. Specify object name being compared, internally used to show appropriate
  1005. assertion message.
  1006. """
  1007. __tracebackhide__ = True
  1008. # instance validation
  1009. _check_isinstance(left, right, Series)
  1010. if check_series_type:
  1011. # ToDo: There are some tests using rhs is sparse
  1012. # lhs is dense. Should use assert_class_equal in future
  1013. assert isinstance(left, type(right))
  1014. # assert_class_equal(left, right, obj=obj)
  1015. # length comparison
  1016. if len(left) != len(right):
  1017. msg1 = '{len}, {left}'.format(len=len(left), left=left.index)
  1018. msg2 = '{len}, {right}'.format(len=len(right), right=right.index)
  1019. raise_assert_detail(obj, 'Series length are different', msg1, msg2)
  1020. # index comparison
  1021. assert_index_equal(left.index, right.index, exact=check_index_type,
  1022. check_names=check_names,
  1023. check_less_precise=check_less_precise,
  1024. check_exact=check_exact,
  1025. check_categorical=check_categorical,
  1026. obj='{obj}.index'.format(obj=obj))
  1027. if check_dtype:
  1028. # We want to skip exact dtype checking when `check_categorical`
  1029. # is False. We'll still raise if only one is a `Categorical`,
  1030. # regardless of `check_categorical`
  1031. if (is_categorical_dtype(left) and is_categorical_dtype(right) and
  1032. not check_categorical):
  1033. pass
  1034. else:
  1035. assert_attr_equal('dtype', left, right)
  1036. if check_exact:
  1037. assert_numpy_array_equal(left.get_values(), right.get_values(),
  1038. check_dtype=check_dtype,
  1039. obj='{obj}'.format(obj=obj),)
  1040. elif check_datetimelike_compat:
  1041. # we want to check only if we have compat dtypes
  1042. # e.g. integer and M|m are NOT compat, but we can simply check
  1043. # the values in that case
  1044. if (is_datetimelike_v_numeric(left, right) or
  1045. is_datetimelike_v_object(left, right) or
  1046. needs_i8_conversion(left) or
  1047. needs_i8_conversion(right)):
  1048. # datetimelike may have different objects (e.g. datetime.datetime
  1049. # vs Timestamp) but will compare equal
  1050. if not Index(left.values).equals(Index(right.values)):
  1051. msg = ('[datetimelike_compat=True] {left} is not equal to '
  1052. '{right}.').format(left=left.values, right=right.values)
  1053. raise AssertionError(msg)
  1054. else:
  1055. assert_numpy_array_equal(left.get_values(), right.get_values(),
  1056. check_dtype=check_dtype)
  1057. elif is_interval_dtype(left) or is_interval_dtype(right):
  1058. assert_interval_array_equal(left.array, right.array)
  1059. elif (is_extension_array_dtype(left.dtype) and
  1060. is_datetime64tz_dtype(left.dtype)):
  1061. # .values is an ndarray, but ._values is the ExtensionArray.
  1062. # TODO: Use .array
  1063. assert is_extension_array_dtype(right.dtype)
  1064. return assert_extension_array_equal(left._values, right._values)
  1065. elif (is_extension_array_dtype(left) and not is_categorical_dtype(left) and
  1066. is_extension_array_dtype(right) and not is_categorical_dtype(right)):
  1067. return assert_extension_array_equal(left.array, right.array)
  1068. else:
  1069. _testing.assert_almost_equal(left.get_values(), right.get_values(),
  1070. check_less_precise=check_less_precise,
  1071. check_dtype=check_dtype,
  1072. obj='{obj}'.format(obj=obj))
  1073. # metadata comparison
  1074. if check_names:
  1075. assert_attr_equal('name', left, right, obj=obj)
  1076. if check_categorical:
  1077. if is_categorical_dtype(left) or is_categorical_dtype(right):
  1078. assert_categorical_equal(left.values, right.values,
  1079. obj='{obj} category'.format(obj=obj))
  1080. # This could be refactored to use the NDFrame.equals method
  1081. def assert_frame_equal(left, right, check_dtype=True,
  1082. check_index_type='equiv',
  1083. check_column_type='equiv',
  1084. check_frame_type=True,
  1085. check_less_precise=False,
  1086. check_names=True,
  1087. by_blocks=False,
  1088. check_exact=False,
  1089. check_datetimelike_compat=False,
  1090. check_categorical=True,
  1091. check_like=False,
  1092. obj='DataFrame'):
  1093. """
  1094. Check that left and right DataFrame are equal.
  1095. This function is intended to compare two DataFrames and output any
  1096. differences. Is is mostly intended for use in unit tests.
  1097. Additional parameters allow varying the strictness of the
  1098. equality checks performed.
  1099. Parameters
  1100. ----------
  1101. left : DataFrame
  1102. First DataFrame to compare.
  1103. right : DataFrame
  1104. Second DataFrame to compare.
  1105. check_dtype : bool, default True
  1106. Whether to check the DataFrame dtype is identical.
  1107. check_index_type : bool / string {'equiv'}, default 'equiv'
  1108. Whether to check the Index class, dtype and inferred_type
  1109. are identical.
  1110. check_column_type : bool / string {'equiv'}, default 'equiv'
  1111. Whether to check the columns class, dtype and inferred_type
  1112. are identical. Is passed as the ``exact`` argument of
  1113. :func:`assert_index_equal`.
  1114. check_frame_type : bool, default True
  1115. Whether to check the DataFrame class is identical.
  1116. check_less_precise : bool or int, default False
  1117. Specify comparison precision. Only used when check_exact is False.
  1118. 5 digits (False) or 3 digits (True) after decimal points are compared.
  1119. If int, then specify the digits to compare.
  1120. check_names : bool, default True
  1121. Whether to check that the `names` attribute for both the `index`
  1122. and `column` attributes of the DataFrame is identical, i.e.
  1123. * left.index.names == right.index.names
  1124. * left.columns.names == right.columns.names
  1125. by_blocks : bool, default False
  1126. Specify how to compare internal data. If False, compare by columns.
  1127. If True, compare by blocks.
  1128. check_exact : bool, default False
  1129. Whether to compare number exactly.
  1130. check_datetimelike_compat : bool, default False
  1131. Compare datetime-like which is comparable ignoring dtype.
  1132. check_categorical : bool, default True
  1133. Whether to compare internal Categorical exactly.
  1134. check_like : bool, default False
  1135. If True, ignore the order of index & columns.
  1136. Note: index labels must match their respective rows
  1137. (same as in columns) - same labels must be with the same data.
  1138. obj : str, default 'DataFrame'
  1139. Specify object name being compared, internally used to show appropriate
  1140. assertion message.
  1141. See Also
  1142. --------
  1143. assert_series_equal : Equivalent method for asserting Series equality.
  1144. DataFrame.equals : Check DataFrame equality.
  1145. Examples
  1146. --------
  1147. This example shows comparing two DataFrames that are equal
  1148. but with columns of differing dtypes.
  1149. >>> from pandas.util.testing import assert_frame_equal
  1150. >>> df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
  1151. >>> df2 = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0]})
  1152. df1 equals itself.
  1153. >>> assert_frame_equal(df1, df1)
  1154. df1 differs from df2 as column 'b' is of a different type.
  1155. >>> assert_frame_equal(df1, df2)
  1156. Traceback (most recent call last):
  1157. AssertionError: Attributes are different
  1158. Attribute "dtype" are different
  1159. [left]: int64
  1160. [right]: float64
  1161. Ignore differing dtypes in columns with check_dtype.
  1162. >>> assert_frame_equal(df1, df2, check_dtype=False)
  1163. """
  1164. __tracebackhide__ = True
  1165. # instance validation
  1166. _check_isinstance(left, right, DataFrame)
  1167. if check_frame_type:
  1168. # ToDo: There are some tests using rhs is SparseDataFrame
  1169. # lhs is DataFrame. Should use assert_class_equal in future
  1170. assert isinstance(left, type(right))
  1171. # assert_class_equal(left, right, obj=obj)
  1172. # shape comparison
  1173. if left.shape != right.shape:
  1174. raise_assert_detail(obj,
  1175. 'DataFrame shape mismatch',
  1176. '{shape!r}'.format(shape=left.shape),
  1177. '{shape!r}'.format(shape=right.shape))
  1178. if check_like:
  1179. left, right = left.reindex_like(right), right
  1180. # index comparison
  1181. assert_index_equal(left.index, right.index, exact=check_index_type,
  1182. check_names=check_names,
  1183. check_less_precise=check_less_precise,
  1184. check_exact=check_exact,
  1185. check_categorical=check_categorical,
  1186. obj='…

Large files files are truncated, but you can click here to view the full file