PageRenderTime 69ms CodeModel.GetById 21ms RepoModel.GetById 0ms 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
  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='{obj}.index'.format(obj=obj))
  1187. # column comparison
  1188. assert_index_equal(left.columns, right.columns, exact=check_column_type,
  1189. check_names=check_names,
  1190. check_less_precise=check_less_precise,
  1191. check_exact=check_exact,
  1192. check_categorical=check_categorical,
  1193. obj='{obj}.columns'.format(obj=obj))
  1194. # compare by blocks
  1195. if by_blocks:
  1196. rblocks = right._to_dict_of_blocks()
  1197. lblocks = left._to_dict_of_blocks()
  1198. for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
  1199. assert dtype in lblocks
  1200. assert dtype in rblocks
  1201. assert_frame_equal(lblocks[dtype], rblocks[dtype],
  1202. check_dtype=check_dtype, obj='DataFrame.blocks')
  1203. # compare by columns
  1204. else:
  1205. for i, col in enumerate(left.columns):
  1206. assert col in right
  1207. lcol = left.iloc[:, i]
  1208. rcol = right.iloc[:, i]
  1209. assert_series_equal(
  1210. lcol, rcol, check_dtype=check_dtype,
  1211. check_index_type=check_index_type,
  1212. check_less_precise=check_less_precise,
  1213. check_exact=check_exact, check_names=check_names,
  1214. check_datetimelike_compat=check_datetimelike_compat,
  1215. check_categorical=check_categorical,
  1216. obj='DataFrame.iloc[:, {idx}]'.format(idx=i))
  1217. def assert_equal(left, right, **kwargs):
  1218. """
  1219. Wrapper for tm.assert_*_equal to dispatch to the appropriate test function.
  1220. Parameters
  1221. ----------
  1222. left : Index, Series, DataFrame, ExtensionArray, or np.ndarray
  1223. right : Index, Series, DataFrame, ExtensionArray, or np.ndarray
  1224. **kwargs
  1225. """
  1226. __tracebackhide__ = True
  1227. if isinstance(left, pd.Index):
  1228. assert_index_equal(left, right, **kwargs)
  1229. elif isinstance(left, pd.Series):
  1230. assert_series_equal(left, right, **kwargs)
  1231. elif isinstance(left, pd.DataFrame):
  1232. assert_frame_equal(left, right, **kwargs)
  1233. elif isinstance(left, IntervalArray):
  1234. assert_interval_array_equal(left, right, **kwargs)
  1235. elif isinstance(left, PeriodArray):
  1236. assert_period_array_equal(left, right, **kwargs)
  1237. elif isinstance(left, DatetimeArray):
  1238. assert_datetime_array_equal(left, right, **kwargs)
  1239. elif isinstance(left, TimedeltaArray):
  1240. assert_timedelta_array_equal(left, right, **kwargs)
  1241. elif isinstance(left, ExtensionArray):
  1242. assert_extension_array_equal(left, right, **kwargs)
  1243. elif isinstance(left, np.ndarray):
  1244. assert_numpy_array_equal(left, right, **kwargs)
  1245. else:
  1246. raise NotImplementedError(type(left))
  1247. def box_expected(expected, box_cls, transpose=True):
  1248. """
  1249. Helper function to wrap the expected output of a test in a given box_class.
  1250. Parameters
  1251. ----------
  1252. expected : np.ndarray, Index, Series
  1253. box_cls : {Index, Series, DataFrame}
  1254. Returns
  1255. -------
  1256. subclass of box_cls
  1257. """
  1258. if box_cls is pd.Index:
  1259. expected = pd.Index(expected)
  1260. elif box_cls is pd.Series:
  1261. expected = pd.Series(expected)
  1262. elif box_cls is pd.DataFrame:
  1263. expected = pd.Series(expected).to_frame()
  1264. if transpose:
  1265. # for vector operations, we we need a DataFrame to be a single-row,
  1266. # not a single-column, in order to operate against non-DataFrame
  1267. # vectors of the same length.
  1268. expected = expected.T
  1269. elif box_cls is PeriodArray:
  1270. # the PeriodArray constructor is not as flexible as period_array
  1271. expected = period_array(expected)
  1272. elif box_cls is DatetimeArray:
  1273. expected = DatetimeArray(expected)
  1274. elif box_cls is TimedeltaArray:
  1275. expected = TimedeltaArray(expected)
  1276. elif box_cls is np.ndarray:
  1277. expected = np.array(expected)
  1278. elif box_cls is to_array:
  1279. expected = to_array(expected)
  1280. else:
  1281. raise NotImplementedError(box_cls)
  1282. return expected
  1283. def to_array(obj):
  1284. # temporary implementation until we get pd.array in place
  1285. if is_period_dtype(obj):
  1286. return period_array(obj)
  1287. elif is_datetime64_dtype(obj) or is_datetime64tz_dtype(obj):
  1288. return DatetimeArray._from_sequence(obj)
  1289. elif is_timedelta64_dtype(obj):
  1290. return TimedeltaArray._from_sequence(obj)
  1291. else:
  1292. return np.array(obj)
  1293. # -----------------------------------------------------------------------------
  1294. # Sparse
  1295. def assert_sp_array_equal(left, right, check_dtype=True, check_kind=True,
  1296. check_fill_value=True,
  1297. consolidate_block_indices=False):
  1298. """Check that the left and right SparseArray are equal.
  1299. Parameters
  1300. ----------
  1301. left : SparseArray
  1302. right : SparseArray
  1303. check_dtype : bool, default True
  1304. Whether to check the data dtype is identical.
  1305. check_kind : bool, default True
  1306. Whether to just the kind of the sparse index for each column.
  1307. check_fill_value : bool, default True
  1308. Whether to check that left.fill_value matches right.fill_value
  1309. consolidate_block_indices : bool, default False
  1310. Whether to consolidate contiguous blocks for sparse arrays with
  1311. a BlockIndex. Some operations, e.g. concat, will end up with
  1312. block indices that could be consolidated. Setting this to true will
  1313. create a new BlockIndex for that array, with consolidated
  1314. block indices.
  1315. """
  1316. _check_isinstance(left, right, pd.SparseArray)
  1317. assert_numpy_array_equal(left.sp_values, right.sp_values,
  1318. check_dtype=check_dtype)
  1319. # SparseIndex comparison
  1320. assert isinstance(left.sp_index, pd._libs.sparse.SparseIndex)
  1321. assert isinstance(right.sp_index, pd._libs.sparse.SparseIndex)
  1322. if not check_kind:
  1323. left_index = left.sp_index.to_block_index()
  1324. right_index = right.sp_index.to_block_index()
  1325. else:
  1326. left_index = left.sp_index
  1327. right_index = right.sp_index
  1328. if consolidate_block_indices and left.kind == 'block':
  1329. # we'll probably remove this hack...
  1330. left_index = left_index.to_int_index().to_block_index()
  1331. right_index = right_index.to_int_index().to_block_index()
  1332. if not left_index.equals(right_index):
  1333. raise_assert_detail('SparseArray.index', 'index are not equal',
  1334. left_index, right_index)
  1335. else:
  1336. # Just ensure a
  1337. pass
  1338. if check_fill_value:
  1339. assert_attr_equal('fill_value', left, right)
  1340. if check_dtype:
  1341. assert_attr_equal('dtype', left, right)
  1342. assert_numpy_array_equal(left.values, right.values,
  1343. check_dtype=check_dtype)
  1344. def assert_sp_series_equal(left, right, check_dtype=True, exact_indices=True,
  1345. check_series_type=True, check_names=True,
  1346. check_kind=True,
  1347. check_fill_value=True,
  1348. consolidate_block_indices=False,
  1349. obj='SparseSeries'):
  1350. """Check that the left and right SparseSeries are equal.
  1351. Parameters
  1352. ----------
  1353. left : SparseSeries
  1354. right : SparseSeries
  1355. check_dtype : bool, default True
  1356. Whether to check the Series dtype is identical.
  1357. exact_indices : bool, default True
  1358. check_series_type : bool, default True
  1359. Whether to check the SparseSeries class is identical.
  1360. check_names : bool, default True
  1361. Whether to check the SparseSeries name attribute.
  1362. check_kind : bool, default True
  1363. Whether to just the kind of the sparse index for each column.
  1364. check_fill_value : bool, default True
  1365. Whether to check that left.fill_value matches right.fill_value
  1366. consolidate_block_indices : bool, default False
  1367. Whether to consolidate contiguous blocks for sparse arrays with
  1368. a BlockIndex. Some operations, e.g. concat, will end up with
  1369. block indices that could be consolidated. Setting this to true will
  1370. create a new BlockIndex for that array, with consolidated
  1371. block indices.
  1372. obj : str, default 'SparseSeries'
  1373. Specify the object name being compared, internally used to show
  1374. the appropriate assertion message.
  1375. """
  1376. _check_isinstance(left, right, pd.SparseSeries)
  1377. if check_series_type:
  1378. assert_class_equal(left, right, obj=obj)
  1379. assert_index_equal(left.index, right.index,
  1380. obj='{obj}.index'.format(obj=obj))
  1381. assert_sp_array_equal(left.values, right.values,
  1382. check_kind=check_kind,
  1383. check_fill_value=check_fill_value,
  1384. consolidate_block_indices=consolidate_block_indices)
  1385. if check_names:
  1386. assert_attr_equal('name', left, right)
  1387. if check_dtype:
  1388. assert_attr_equal('dtype', left, right)
  1389. assert_numpy_array_equal(np.asarray(left.values),
  1390. np.asarray(right.values))
  1391. def assert_sp_frame_equal(left, right, check_dtype=True, exact_indices=True,
  1392. check_frame_type=True, check_kind=True,
  1393. check_fill_value=True,
  1394. consolidate_block_indices=False,
  1395. obj='SparseDataFrame'):
  1396. """Check that the left and right SparseDataFrame are equal.
  1397. Parameters
  1398. ----------
  1399. left : SparseDataFrame
  1400. right : SparseDataFrame
  1401. check_dtype : bool, default True
  1402. Whether to check the Series dtype is identical.
  1403. exact_indices : bool, default True
  1404. SparseSeries SparseIndex objects must be exactly the same,
  1405. otherwise just compare dense representations.
  1406. check_frame_type : bool, default True
  1407. Whether to check the SparseDataFrame class is identical.
  1408. check_kind : bool, default True
  1409. Whether to just the kind of the sparse index for each column.
  1410. check_fill_value : bool, default True
  1411. Whether to check that left.fill_value matches right.fill_value
  1412. consolidate_block_indices : bool, default False
  1413. Whether to consolidate contiguous blocks for sparse arrays with
  1414. a BlockIndex. Some operations, e.g. concat, will end up with
  1415. block indices that could be consolidated. Setting this to true will
  1416. create a new BlockIndex for that array, with consolidated
  1417. block indices.
  1418. obj : str, default 'SparseDataFrame'
  1419. Specify the object name being compared, internally used to show
  1420. the appropriate assertion message.
  1421. """
  1422. _check_isinstance(left, right, pd.SparseDataFrame)
  1423. if check_frame_type:
  1424. assert_class_equal(left, right, obj=obj)
  1425. assert_index_equal(left.index, right.index,
  1426. obj='{obj}.index'.format(obj=obj))
  1427. assert_index_equal(left.columns, right.columns,
  1428. obj='{obj}.columns'.format(obj=obj))
  1429. if check_fill_value:
  1430. assert_attr_equal('default_fill_value', left, right, obj=obj)
  1431. for col, series in compat.iteritems(left):
  1432. assert (col in right)
  1433. # trade-off?
  1434. if exact_indices:
  1435. assert_sp_series_equal(
  1436. series, right[col],
  1437. check_dtype=check_dtype,
  1438. check_kind=check_kind,
  1439. check_fill_value=check_fill_value,
  1440. consolidate_block_indices=consolidate_block_indices
  1441. )
  1442. else:
  1443. assert_series_equal(series.to_dense(), right[col].to_dense(),
  1444. check_dtype=check_dtype)
  1445. # do I care?
  1446. # assert(left.default_kind == right.default_kind)
  1447. for col in right:
  1448. assert (col in left)
  1449. # -----------------------------------------------------------------------------
  1450. # Others
  1451. def assert_contains_all(iterable, dic):
  1452. for k in iterable:
  1453. assert k in dic, "Did not contain item: '{key!r}'".format(key=k)
  1454. def assert_copy(iter1, iter2, **eql_kwargs):
  1455. """
  1456. iter1, iter2: iterables that produce elements
  1457. comparable with assert_almost_equal
  1458. Checks that the elements are equal, but not
  1459. the same object. (Does not check that items
  1460. in sequences are also not the same object)
  1461. """
  1462. for elem1, elem2 in zip(iter1, iter2):
  1463. assert_almost_equal(elem1, elem2, **eql_kwargs)
  1464. msg = ("Expected object {obj1!r} and object {obj2!r} to be "
  1465. "different objects, but they were the same object."
  1466. ).format(obj1=type(elem1), obj2=type(elem2))
  1467. assert elem1 is not elem2, msg
  1468. def getCols(k):
  1469. return string.ascii_uppercase[:k]
  1470. # make index
  1471. def makeStringIndex(k=10, name=None):
  1472. return Index(rands_array(nchars=10, size=k), name=name)
  1473. def makeUnicodeIndex(k=10, name=None):
  1474. return Index(randu_array(nchars=10, size=k), name=name)
  1475. def makeCategoricalIndex(k=10, n=3, name=None, **kwargs):
  1476. """ make a length k index or n categories """
  1477. x = rands_array(nchars=4, size=n)
  1478. return CategoricalIndex(np.random.choice(x, k), name=name, **kwargs)
  1479. def makeIntervalIndex(k=10, name=None, **kwargs):
  1480. """ make a length k IntervalIndex """
  1481. x = np.linspace(0, 100, num=(k + 1))
  1482. return IntervalIndex.from_breaks(x, name=name, **kwargs)
  1483. def makeBoolIndex(k=10, name=None):
  1484. if k == 1:
  1485. return Index([True], name=name)
  1486. elif k == 2:
  1487. return Index([False, True], name=name)
  1488. return Index([False, True] + [False] * (k - 2), name=name)
  1489. def makeIntIndex(k=10, name=None):
  1490. return Index(lrange(k), name=name)
  1491. def makeUIntIndex(k=10, name=None):
  1492. return Index([2**63 + i for i in lrange(k)], name=name)
  1493. def makeRangeIndex(k=10, name=None, **kwargs):
  1494. return RangeIndex(0, k, 1, name=name, **kwargs)
  1495. def makeFloatIndex(k=10, name=None):
  1496. values = sorted(np.random.random_sample(k)) - np.random.random_sample(1)
  1497. return Index(values * (10 ** np.random.randint(0, 9)), name=name)
  1498. def makeDateIndex(k=10, freq='B', name=None, **kwargs):
  1499. dt = datetime(2000, 1, 1)
  1500. dr = bdate_range(dt, periods=k, freq=freq, name=name)
  1501. return DatetimeIndex(dr, name=name, **kwargs)
  1502. def makeTimedeltaIndex(k=10, freq='D', name=None, **kwargs):
  1503. return pd.timedelta_range(start='1 day', periods=k, freq=freq,
  1504. name=name, **kwargs)
  1505. def makePeriodIndex(k=10, name=None, **kwargs):
  1506. dt = datetime(2000, 1, 1)
  1507. dr = pd.period_range(start=dt, periods=k, freq='B', name=name, **kwargs)
  1508. return dr
  1509. def makeMultiIndex(k=10, names=None, **kwargs):
  1510. return MultiIndex.from_product(
  1511. (('foo', 'bar'), (1, 2)), names=names, **kwargs)
  1512. def all_index_generator(k=10):
  1513. """Generator which can be iterated over to get instances of all the various
  1514. index classes.
  1515. Parameters
  1516. ----------
  1517. k: length of each of the index instances
  1518. """
  1519. all_make_index_funcs = [makeIntIndex, makeFloatIndex, makeStringIndex,
  1520. makeUnicodeIndex, makeDateIndex, makePeriodIndex,
  1521. makeTimedeltaIndex, makeBoolIndex, makeRangeIndex,
  1522. makeIntervalIndex,
  1523. makeCategoricalIndex]
  1524. for make_index_func in all_make_index_funcs:
  1525. yield make_index_func(k=k)
  1526. def index_subclass_makers_generator():
  1527. make_index_funcs = [
  1528. makeDateIndex, makePeriodIndex,
  1529. makeTimedeltaIndex, makeRangeIndex,
  1530. makeIntervalIndex, makeCategoricalIndex,
  1531. makeMultiIndex
  1532. ]
  1533. for make_index_func in make_index_funcs:
  1534. yield make_index_func
  1535. def all_timeseries_index_generator(k=10):
  1536. """Generator which can be iterated over to get instances of all the classes
  1537. which represent time-seires.
  1538. Parameters
  1539. ----------
  1540. k: length of each of the index instances
  1541. """
  1542. make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex]
  1543. for make_index_func in make_index_funcs:
  1544. yield make_index_func(k=k)
  1545. # make series
  1546. def makeFloatSeries(name=None):
  1547. index = makeStringIndex(N)
  1548. return Series(randn(N), index=index, name=name)
  1549. def makeStringSeries(name=None):
  1550. index = makeStringIndex(N)
  1551. return Series(randn(N), index=index, name=name)
  1552. def makeObjectSeries(name=None):
  1553. dateIndex = makeDateIndex(N)
  1554. dateIndex = Index(dateIndex, dtype=object)
  1555. index = makeStringIndex(N)
  1556. return Series(dateIndex, index=index, name=name)
  1557. def getSeriesData():
  1558. index = makeStringIndex(N)
  1559. return {c: Series(randn(N), index=index) for c in getCols(K)}
  1560. def makeTimeSeries(nper=None, freq='B', name=None):
  1561. if nper is None:
  1562. nper = N
  1563. return Series(randn(nper), index=makeDateIndex(nper, freq=freq), name=name)
  1564. def makePeriodSeries(nper=None, name=None):
  1565. if nper is None:
  1566. nper = N
  1567. return Series(randn(nper), index=makePeriodIndex(nper), name=name)
  1568. def getTimeSeriesData(nper=None, freq='B'):
  1569. return {c: makeTimeSeries(nper, freq) for c in getCols(K)}
  1570. def getPeriodData(nper=None):
  1571. return {c: makePeriodSeries(nper) for c in getCols(K)}
  1572. # make frame
  1573. def makeTimeDataFrame(nper=None, freq='B'):
  1574. data = getTimeSeriesData(nper, freq)
  1575. return DataFrame(data)
  1576. def makeDataFrame():
  1577. data = getSeriesData()
  1578. return DataFrame(data)
  1579. def getMixedTypeDict():
  1580. index = Index(['a', 'b', 'c', 'd', 'e'])
  1581. data = {
  1582. 'A': [0., 1., 2., 3., 4.],
  1583. 'B': [0., 1., 0., 1., 0.],
  1584. 'C': ['foo1', 'foo2', 'foo3', 'foo4', 'foo5'],
  1585. 'D': bdate_range('1/1/2009', periods=5)
  1586. }
  1587. return index, data
  1588. def makeMixedDataFrame():
  1589. return DataFrame(getMixedTypeDict()[1])
  1590. def makePeriodFrame(nper=None):
  1591. data = getPeriodData(nper)
  1592. return DataFrame(data)
  1593. def makeCustomIndex(nentries, nlevels, prefix='#', names=False, ndupe_l=None,
  1594. idx_type=None):
  1595. """Create an index/multindex with given dimensions, levels, names, etc'
  1596. nentries - number of entries in index
  1597. nlevels - number of levels (> 1 produces multindex)
  1598. prefix - a string prefix for labels
  1599. names - (Optional), bool or list of strings. if True will use default
  1600. names, if false will use no names, if a list is given, the name of
  1601. each level in the index will be taken from the list.
  1602. ndupe_l - (Optional), list of ints, the number of rows for which the
  1603. label will repeated at the corresponding level, you can specify just
  1604. the first few, the rest will use the default ndupe_l of 1.
  1605. len(ndupe_l) <= nlevels.
  1606. idx_type - "i"/"f"/"s"/"u"/"dt"/"p"/"td".
  1607. If idx_type is not None, `idx_nlevels` must be 1.
  1608. "i"/"f" creates an integer/float index,
  1609. "s"/"u" creates a string/unicode index
  1610. "dt" create a datetime index.
  1611. "td" create a datetime index.
  1612. if unspecified, string labels will be generated.
  1613. """
  1614. if ndupe_l is None:
  1615. ndupe_l = [1] * nlevels
  1616. assert (is_sequence(ndupe_l) and len(ndupe_l) <= nlevels)
  1617. assert (names is None or names is False or
  1618. names is True or len(names) is nlevels)
  1619. assert idx_type is None or (idx_type in ('i', 'f', 's', 'u',
  1620. 'dt', 'p', 'td')
  1621. and nlevels == 1)
  1622. if names is True:
  1623. # build default names
  1624. names = [prefix + str(i) for i in range(nlevels)]
  1625. if names is False:
  1626. # pass None to index constructor for no name
  1627. names = None
  1628. # make singelton case uniform
  1629. if isinstance(names, compat.string_types) and nlevels == 1:
  1630. names = [names]
  1631. # specific 1D index type requested?
  1632. idx_func = dict(i=makeIntIndex, f=makeFloatIndex,
  1633. s=makeStringIndex, u=makeUnicodeIndex,
  1634. dt=makeDateIndex, td=makeTimedeltaIndex,
  1635. p=makePeriodIndex).get(idx_type)
  1636. if idx_func:
  1637. idx = idx_func(nentries)
  1638. # but we need to fill in the name
  1639. if names:
  1640. idx.name = names[0]
  1641. return idx
  1642. elif idx_type is not None:
  1643. raise ValueError('"{idx_type}" is not a legal value for `idx_type`, '
  1644. 'use "i"/"f"/"s"/"u"/"dt/"p"/"td".'
  1645. .format(idx_type=idx_type))
  1646. if len(ndupe_l) < nlevels:
  1647. ndupe_l.extend([1] * (nlevels - len(ndupe_l)))
  1648. assert len(ndupe_l) == nlevels
  1649. assert all(x > 0 for x in ndupe_l)
  1650. tuples = []
  1651. for i in range(nlevels):
  1652. def keyfunc(x):
  1653. import re
  1654. numeric_tuple = re.sub(r"[^\d_]_?", "", x).split("_")
  1655. return lmap(int, numeric_tuple)
  1656. # build a list of lists to create the index from
  1657. div_factor = nentries // ndupe_l[i] + 1
  1658. cnt = Counter()
  1659. for j in range(div_factor):
  1660. label = '{prefix}_l{i}_g{j}'.format(prefix=prefix, i=i, j=j)
  1661. cnt[label] = ndupe_l[i]
  1662. # cute Counter trick
  1663. result = list(sorted(cnt.elements(), key=keyfunc))[:nentries]
  1664. tuples.append(result)
  1665. tuples = lzip(*tuples)
  1666. # convert tuples to index
  1667. if nentries == 1:
  1668. # we have a single level of tuples, i.e. a regular Index
  1669. index = Index(tuples[0], name=names[0])
  1670. elif nlevels == 1:
  1671. name = None if names is None else names[0]
  1672. index = Index((x[0] for x in tuples), name=name)
  1673. else:
  1674. index = MultiIndex.from_tuples(tuples, names=names)
  1675. return index
  1676. def makeCustomDataframe(nrows, ncols, c_idx_names=True, r_idx_names=True,
  1677. c_idx_nlevels=1, r_idx_nlevels=1, data_gen_f=None,
  1678. c_ndupe_l=None, r_ndupe_l=None, dtype=None,
  1679. c_idx_type=None, r_idx_type=None):
  1680. """
  1681. nrows, ncols - number of data rows/cols
  1682. c_idx_names, idx_names - False/True/list of strings, yields No names ,
  1683. default names or uses the provided names for the levels of the
  1684. corresponding index. You can provide a single string when
  1685. c_idx_nlevels ==1.
  1686. c_idx_nlevels - number of levels in columns index. > 1 will yield MultiIndex
  1687. r_idx_nlevels - number of levels in rows index. > 1 will yield MultiIndex
  1688. data_gen_f - a function f(row,col) which return the data value
  1689. at that position, the default generator used yields values of the form
  1690. "RxCy" based on position.
  1691. c_ndupe_l, r_ndupe_l - list of integers, determines the number
  1692. of duplicates for each label at a given level of the corresponding
  1693. index. The default `None` value produces a multiplicity of 1 across
  1694. all levels, i.e. a unique index. Will accept a partial list of length
  1695. N < idx_nlevels, for just the first N levels. If ndupe doesn't divide
  1696. nrows/ncol, the last label might have lower multiplicity.
  1697. dtype - passed to the DataFrame constructor as is, in case you wish to
  1698. have more control in conjuncion with a custom `data_gen_f`
  1699. r_idx_type, c_idx_type - "i"/"f"/"s"/"u"/"dt"/"td".
  1700. If idx_type is not None, `idx_nlevels` must be 1.
  1701. "i"/"f" creates an integer/float index,
  1702. "s"/"u" creates a string/unicode index
  1703. "dt" create a datetime index.
  1704. "td" create a timedelta index.
  1705. if unspecified, string labels will be generated.
  1706. Examples:
  1707. # 5 row, 3 columns, default names on both, single index on both axis
  1708. >> makeCustomDataframe(5,3)
  1709. # make the data a random int between 1 and 100
  1710. >> mkdf(5,3,data_gen_f=lambda r,c:randint(1,100))
  1711. # 2-level multiindex on rows with each label duplicated
  1712. # twice on first level, default names on both axis, single
  1713. # index on both axis
  1714. >> a=makeCustomDataframe(5,3,r_idx_nlevels=2,r_ndupe_l=[2])
  1715. # DatetimeIndex on row, index with unicode labels on columns
  1716. # no names on either axis
  1717. >> a=makeCustomDataframe(5,3,c_idx_names=False,r_idx_names=False,
  1718. r_idx_type="dt",c_idx_type="u")
  1719. # 4-level multindex on rows with names provided, 2-level multindex
  1720. # on columns with default labels and default names.
  1721. >> a=makeCustomDataframe(5,3,r_idx_nlevels=4,
  1722. r_idx_names=["FEE","FI","FO","FAM"],
  1723. c_idx_nlevels=2)
  1724. >> a=mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4)
  1725. """
  1726. assert c_idx_nlevels > 0
  1727. assert r_idx_nlevels > 0
  1728. assert r_idx_type is None or (r_idx_type in ('i', 'f', 's',
  1729. 'u', 'dt', 'p', 'td')
  1730. and r_idx_nlevels == 1)
  1731. assert c_idx_type is None or (c_idx_type in ('i', 'f', 's',
  1732. 'u', 'dt', 'p', 'td')
  1733. and c_idx_nlevels == 1)
  1734. columns = makeCustomIndex(ncols, nlevels=c_idx_nlevels, prefix='C',
  1735. names=c_idx_names, ndupe_l=c_ndupe_l,
  1736. idx_type=c_idx_type)
  1737. index = makeCustomIndex(nrows, nlevels=r_idx_nlevels, prefix='R',
  1738. names=r_idx_names, ndupe_l=r_ndupe_l,
  1739. idx_type=r_idx_type)
  1740. # by default, generate data based on location
  1741. if data_gen_f is None:
  1742. data_gen_f = lambda r, c: "R{rows}C{cols}".format(rows=r, cols=c)
  1743. data = [[data_gen_f(r, c) for c in range(ncols)] for r in range(nrows)]
  1744. return DataFrame(data, index, columns, dtype=dtype)
  1745. def _create_missing_idx(nrows, ncols, density, random_state=None):
  1746. if random_state is None:
  1747. random_state = np.random
  1748. else:
  1749. random_state = np.random.RandomState(random_state)
  1750. # below is cribbed from scipy.sparse
  1751. size = int(np.round((1 - density) * nrows * ncols))
  1752. # generate a few more to ensure unique values
  1753. min_rows = 5
  1754. fac = 1.02
  1755. extra_size = min(size + min_rows, fac * size)
  1756. def _gen_unique_rand(rng, _extra_size):
  1757. ind = rng.rand(int(_extra_size))
  1758. return np.unique(np.floor(ind * nrows * ncols))[:size]
  1759. ind = _gen_unique_rand(random_state, extra_size)
  1760. while ind.size < size:
  1761. extra_size *= 1.05
  1762. ind = _gen_unique_rand(random_state, extra_size)
  1763. j = np.floor(ind * 1. / nrows).astype(int)
  1764. i = (ind - j * nrows).astype(int)
  1765. return i.tolist(), j.tolist()
  1766. def makeMissingCustomDataframe(nrows, ncols, density=.9, random_state=None,
  1767. c_idx_names=True, r_idx_names=True,
  1768. c_idx_nlevels=1, r_idx_nlevels=1,
  1769. data_gen_f=None,
  1770. c_ndupe_l=None, r_ndupe_l=None, dtype=None,
  1771. c_idx_type=None, r_idx_type=None):
  1772. """
  1773. Parameters
  1774. ----------
  1775. Density : float, optional
  1776. Float in (0, 1) that gives the percentage of non-missing numbers in
  1777. the DataFrame.
  1778. random_state : {np.random.RandomState, int}, optional
  1779. Random number generator or random seed.
  1780. See makeCustomDataframe for descriptions of the rest of the parameters.
  1781. """
  1782. df = makeCustomDataframe(nrows, ncols, c_idx_names=c_idx_names,
  1783. r_idx_names=r_idx_names,
  1784. c_idx_nlevels=c_idx_nlevels,
  1785. r_idx_nlevels=r_idx_nlevels,
  1786. data_gen_f=data_gen_f,
  1787. c_ndupe_l=c_ndupe_l, r_ndupe_l=r_ndupe_l,
  1788. dtype=dtype, c_idx_type=c_idx_type,
  1789. r_idx_type=r_idx_type)
  1790. i, j = _create_missing_idx(nrows, ncols, density, random_state)
  1791. df.values[i, j] = np.nan
  1792. return df
  1793. def makeMissingDataframe(density=.9, random_state=None):
  1794. df = makeDataFrame()
  1795. i, j = _create_missing_idx(*df.shape, density=density,
  1796. random_state=random_state)
  1797. df.values[i, j] = np.nan
  1798. return df
  1799. class TestSubDict(dict):
  1800. def __init__(self, *args, **kwargs):
  1801. dict.__init__(self, *args, **kwargs)
  1802. def optional_args(decorator):
  1803. """allows a decorator to take optional positional and keyword arguments.
  1804. Assumes that taking a single, callable, positional argument means that
  1805. it is decorating a function, i.e. something like this::
  1806. @my_decorator
  1807. def function(): pass
  1808. Calls decorator with decorator(f, *args, **kwargs)"""
  1809. @wraps(decorator)
  1810. def wrapper(*args, **kwargs):
  1811. def dec(f):
  1812. return decorator(f, *args, **kwargs)
  1813. is_decorating = not kwargs and len(args) == 1 and callable(args[0])
  1814. if is_decorating:
  1815. f = args[0]
  1816. args = []
  1817. return dec(f)
  1818. else:
  1819. return dec
  1820. return wrapper
  1821. # skip tests on exceptions with this message
  1822. _network_error_messages = (
  1823. # 'urlopen error timed out',
  1824. # 'timeout: timed out',
  1825. # 'socket.timeout: timed out',
  1826. 'timed out',
  1827. 'Server Hangup',
  1828. 'HTTP Error 503: Service Unavailable',
  1829. '502: Proxy Error',
  1830. 'HTTP Error 502: internal error',
  1831. 'HTTP Error 502',
  1832. 'HTTP Error 503',
  1833. 'HTTP Error 403',
  1834. 'HTTP Error 400',
  1835. 'Temporary failure in name resolution',
  1836. 'Name or service not known',
  1837. 'Connection refused',
  1838. 'certificate verify',
  1839. )
  1840. # or this e.errno/e.reason.errno
  1841. _network_errno_vals = (
  1842. 101, # Network is unreachable
  1843. 111, # Connection refused
  1844. 110, # Connection timed out
  1845. 104, # Connection reset Error
  1846. 54, # Connection reset by peer
  1847. 60, # urllib.error.URLError: [Errno 60] Connection timed out
  1848. )
  1849. # Both of the above shouldn't mask real issues such as 404's
  1850. # or refused connections (changed DNS).
  1851. # But some tests (test_data yahoo) contact incredibly flakey
  1852. # servers.
  1853. # and conditionally raise on these exception types
  1854. _network_error_classes = (IOError, httplib.HTTPException)
  1855. if PY3:
  1856. _network_error_classes += (TimeoutError,) # noqa
  1857. def can_connect(url, error_classes=_network_error_classes):
  1858. """Try to connect to the given url. True if succeeds, False if IOError
  1859. raised
  1860. Parameters
  1861. ----------
  1862. url : basestring
  1863. The URL to try to connect to
  1864. Returns
  1865. -------
  1866. connectable : bool
  1867. Return True if no IOError (unable to connect) or URLError (bad url) was
  1868. raised
  1869. """
  1870. try:
  1871. with urlopen(url):
  1872. pass
  1873. except error_classes:
  1874. return False
  1875. else:
  1876. return True
  1877. @optional_args
  1878. def network(t, url="http://www.google.com",
  1879. raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT,
  1880. check_before_test=False,
  1881. error_classes=_network_error_classes,
  1882. skip_errnos=_network_errno_vals,
  1883. _skip_on_messages=_network_error_messages,
  1884. ):
  1885. """
  1886. Label a test as requiring network connection and, if an error is
  1887. encountered, only raise if it does not find a network connection.
  1888. In comparison to ``network``, this assumes an added contract to your test:
  1889. you must assert that, under normal conditions, your test will ONLY fail if
  1890. it does not have network connectivity.
  1891. You can call this in 3 ways: as a standard decorator, with keyword
  1892. arguments, or with a positional argument that is the url to check.
  1893. Parameters
  1894. ----------
  1895. t : callable
  1896. The test requiring network connectivity.
  1897. url : path
  1898. The url to test via ``pandas.io.common.urlopen`` to check
  1899. for connectivity. Defaults to 'http://www.google.com'.
  1900. raise_on_error : bool
  1901. If True, never catches errors.
  1902. check_before_test : bool
  1903. If True, checks connectivity before running the test case.
  1904. error_classes : tuple or Exception
  1905. error classes to ignore. If not in ``error_classes``, raises the error.
  1906. defaults to IOError. Be careful about changing the error classes here.
  1907. skip_errnos : iterable of int
  1908. Any exception that has .errno or .reason.erno set to one
  1909. of these values will be skipped with an appropriate
  1910. message.
  1911. _skip_on_messages: iterable of string
  1912. any exception e for which one of the strings is
  1913. a substring of str(e) will be skipped with an appropriate
  1914. message. Intended to suppress errors where an errno isn't available.
  1915. Notes
  1916. -----
  1917. * ``raise_on_error`` supercedes ``check_before_test``
  1918. Returns
  1919. -------
  1920. t : callable
  1921. The decorated test ``t``, with checks for connectivity errors.
  1922. Example
  1923. -------
  1924. Tests decorated with @network will fail if it's possible to make a network
  1925. connection to another URL (defaults to google.com)::
  1926. >>> from pandas.util.testing import network
  1927. >>> from pandas.io.common import urlopen
  1928. >>> @network
  1929. ... def test_network():
  1930. ... with urlopen("rabbit://bonanza.com"):
  1931. ... pass
  1932. Traceback
  1933. ...
  1934. URLError: <urlopen error unknown url type: rabit>
  1935. You can specify alternative URLs::
  1936. >>> @network("http://www.yahoo.com")
  1937. ... def test_something_with_yahoo():
  1938. ... raise IOError("Failure Message")
  1939. >>> test_something_with_yahoo()
  1940. Traceback (most recent call last):
  1941. ...
  1942. IOError: Failure Message
  1943. If you set check_before_test, it will check the url first and not run the
  1944. test on failure::
  1945. >>> @network("failing://url.blaher", check_before_test=True)
  1946. ... def test_something():
  1947. ... print("I ran!")
  1948. ... raise ValueError("Failure")
  1949. >>> test_something()
  1950. Traceback (most recent call last):
  1951. ...
  1952. Errors not related to networking will always be raised.
  1953. """
  1954. from pytest import skip
  1955. t.network = True
  1956. @compat.wraps(t)
  1957. def wrapper(*args, **kwargs):
  1958. if check_before_test and not raise_on_error:
  1959. if not can_connect(url, error_classes):
  1960. skip()
  1961. try:
  1962. return t(*args, **kwargs)
  1963. except Exception as e:
  1964. errno = getattr(e, 'errno', None)
  1965. if not errno and hasattr(errno, "reason"):
  1966. errno = getattr(e.reason, 'errno', None)
  1967. if errno in skip_errnos:
  1968. skip("Skipping test due to known errno"
  1969. " and error {error}".format(error=e))
  1970. try:
  1971. e_str = traceback.format_exc(e)
  1972. except Exception:
  1973. e_str = str(e)
  1974. if any(m.lower() in e_str.lower() for m in _skip_on_messages):
  1975. skip("Skipping test because exception "
  1976. "message is known and error {error}".format(error=e))
  1977. if not isinstance(e, error_classes):
  1978. raise
  1979. if raise_on_error or can_connect(url, error_classes):
  1980. raise
  1981. else:
  1982. skip("Skipping test due to lack of connectivity"
  1983. " and error {error}".format(error=e))
  1984. return wrapper
  1985. with_connectivity_check = network
  1986. def assert_raises_regex(_exception, _regexp, _callable=None,
  1987. *args, **kwargs):
  1988. r"""
  1989. Check that the specified Exception is raised and that the error message
  1990. matches a given regular expression pattern. This may be a regular
  1991. expression object or a string containing a regular expression suitable
  1992. for use by `re.search()`. This is a port of the `assertRaisesRegexp`
  1993. function from unittest in Python 2.7.
  1994. .. deprecated:: 0.24.0
  1995. Use `pytest.raises` instead.
  1996. Examples
  1997. --------
  1998. >>> assert_raises_regex(ValueError, 'invalid literal for.*XYZ', int, 'XYZ')
  1999. >>> import re
  2000. >>> assert_raises_regex(ValueError, re.compile('literal'), int, 'XYZ')
  2001. If an exception of a different type is raised, it bubbles up.
  2002. >>> assert_raises_regex(TypeError, 'literal', int, 'XYZ')
  2003. Traceback (most recent call last):
  2004. ...
  2005. ValueError: invalid literal for int() with base 10: 'XYZ'
  2006. >>> dct = dict()
  2007. >>> assert_raises_regex(KeyError, 'pear', dct.__getitem__, 'apple')
  2008. Traceback (most recent call last):
  2009. ...
  2010. AssertionError: "pear" does not match "'apple'"
  2011. You can also use this in a with statement.
  2012. >>> with assert_raises_regex(TypeError, r'unsupported operand type\(s\)'):
  2013. ... 1 + {}
  2014. >>> with assert_raises_regex(TypeError, 'banana'):
  2015. ... 'apple'[0] = 'b'
  2016. Traceback (most recent call last):
  2017. ...
  2018. AssertionError: "banana" does not match "'str' object does not support \
  2019. item assignment"
  2020. """
  2021. warnings.warn(("assert_raises_regex has been deprecated and will "
  2022. "be removed in the next release. Please use "
  2023. "`pytest.raises` instead."), FutureWarning, stacklevel=2)
  2024. manager = _AssertRaisesContextmanager(exception=_exception, regexp=_regexp)
  2025. if _callable is not None:
  2026. with manager:
  2027. _callable(*args, **kwargs)
  2028. else:
  2029. return manager
  2030. class _AssertRaisesContextmanager(object):
  2031. """
  2032. Context manager behind `assert_raises_regex`.
  2033. """
  2034. def __init__(self, exception, regexp=None):
  2035. """
  2036. Initialize an _AssertRaisesContextManager instance.
  2037. Parameters
  2038. ----------
  2039. exception : class
  2040. The expected Exception class.
  2041. regexp : str, default None
  2042. The regex to compare against the Exception message.
  2043. """
  2044. self.exception = exception
  2045. if regexp is not None and not hasattr(regexp, "search"):
  2046. regexp = re.compile(regexp, re.DOTALL)
  2047. self.regexp = regexp
  2048. def __enter__(self):
  2049. return self
  2050. def __exit__(self, exc_type, exc_value, trace_back):
  2051. expected = self.exception
  2052. if not exc_type:
  2053. exp_name = getattr(expected, "__name__", str(expected))
  2054. raise AssertionError("{name} not raised.".format(name=exp_name))
  2055. return self.exception_matches(exc_type, exc_value, trace_back)
  2056. def exception_matches(self, exc_type, exc_value, trace_back):
  2057. """
  2058. Check that the Exception raised matches the expected Exception
  2059. and expected error message regular expression.
  2060. Parameters
  2061. ----------
  2062. exc_type : class
  2063. The type of Exception raised.
  2064. exc_value : Exception
  2065. The instance of `exc_type` raised.
  2066. trace_back : stack trace object
  2067. The traceback object associated with `exc_value`.
  2068. Returns
  2069. -------
  2070. is_matched : bool
  2071. Whether or not the Exception raised matches the expected
  2072. Exception class and expected error message regular expression.
  2073. Raises
  2074. ------
  2075. AssertionError : The error message provided does not match
  2076. the expected error message regular expression.
  2077. """
  2078. if issubclass(exc_type, self.exception):
  2079. if self.regexp is not None:
  2080. val = str(exc_value)
  2081. if not self.regexp.search(val):
  2082. msg = '"{pat}" does not match "{val}"'.format(
  2083. pat=self.regexp.pattern, val=val)
  2084. e = AssertionError(msg)
  2085. raise_with_traceback(e, trace_back)
  2086. return True
  2087. else:
  2088. # Failed, so allow Exception to bubble up.
  2089. return False
  2090. @contextmanager
  2091. def assert_produces_warning(expected_warning=Warning, filter_level="always",
  2092. clear=None, check_stacklevel=True):
  2093. """
  2094. Context manager for running code expected to either raise a specific
  2095. warning, or not raise any warnings. Verifies that the code raises the
  2096. expected warning, and that it does not raise any other unexpected
  2097. warnings. It is basically a wrapper around ``warnings.catch_warnings``.
  2098. Parameters
  2099. ----------
  2100. expected_warning : {Warning, False, None}, default Warning
  2101. The type of Exception raised. ``exception.Warning`` is the base
  2102. class for all warnings. To check that no warning is returned,
  2103. specify ``False`` or ``None``.
  2104. filter_level : str, default "always"
  2105. Specifies whether warnings are ignored, displayed, or turned
  2106. into errors.
  2107. Valid values are:
  2108. * "error" - turns matching warnings into exceptions
  2109. * "ignore" - discard the warning
  2110. * "always" - always emit a warning
  2111. * "default" - print the warning the first time it is generated
  2112. from each location
  2113. * "module" - print the warning the first time it is generated
  2114. from each module
  2115. * "once" - print the warning the first time it is generated
  2116. clear : str, default None
  2117. If not ``None`` then remove any previously raised warnings from
  2118. the ``__warningsregistry__`` to ensure that no warning messages are
  2119. suppressed by this context manager. If ``None`` is specified,
  2120. the ``__warningsregistry__`` keeps track of which warnings have been
  2121. shown, and does not show them again.
  2122. check_stacklevel : bool, default True
  2123. If True, displays the line that called the function containing
  2124. the warning to show were the function is called. Otherwise, the
  2125. line that implements the function is displayed.
  2126. Examples
  2127. --------
  2128. >>> import warnings
  2129. >>> with assert_produces_warning():
  2130. ... warnings.warn(UserWarning())
  2131. ...
  2132. >>> with assert_produces_warning(False):
  2133. ... warnings.warn(RuntimeWarning())
  2134. ...
  2135. Traceback (most recent call last):
  2136. ...
  2137. AssertionError: Caused unexpected warning(s): ['RuntimeWarning'].
  2138. >>> with assert_produces_warning(UserWarning):
  2139. ... warnings.warn(RuntimeWarning())
  2140. Traceback (most recent call last):
  2141. ...
  2142. AssertionError: Did not see expected warning of class 'UserWarning'.
  2143. ..warn:: This is *not* thread-safe.
  2144. """
  2145. __tracebackhide__ = True
  2146. with warnings.catch_warnings(record=True) as w:
  2147. if clear is not None:
  2148. # make sure that we are clearing these warnings
  2149. # if they have happened before
  2150. # to guarantee that we will catch them
  2151. if not is_list_like(clear):
  2152. clear = [clear]
  2153. for m in clear:
  2154. try:
  2155. m.__warningregistry__.clear()
  2156. except Exception:
  2157. pass
  2158. saw_warning = False
  2159. warnings.simplefilter(filter_level)
  2160. yield w
  2161. extra_warnings = []
  2162. for actual_warning in w:
  2163. if (expected_warning and issubclass(actual_warning.category,
  2164. expected_warning)):
  2165. saw_warning = True
  2166. if check_stacklevel and issubclass(actual_warning.category,
  2167. (FutureWarning,
  2168. DeprecationWarning)):
  2169. from inspect import getframeinfo, stack
  2170. caller = getframeinfo(stack()[2][0])
  2171. msg = ("Warning not set with correct stacklevel. "
  2172. "File where warning is raised: {actual} != "
  2173. "{caller}. Warning message: {message}"
  2174. ).format(actual=actual_warning.filename,
  2175. caller=caller.filename,
  2176. message=actual_warning.message)
  2177. assert actual_warning.filename == caller.filename, msg
  2178. else:
  2179. extra_warnings.append((actual_warning.category.__name__,
  2180. actual_warning.message,
  2181. actual_warning.filename,
  2182. actual_warning.lineno))
  2183. if expected_warning:
  2184. msg = "Did not see expected warning of class {name!r}.".format(
  2185. name=expected_warning.__name__)
  2186. assert saw_warning, msg
  2187. assert not extra_warnings, ("Caused unexpected warning(s): {extra!r}."
  2188. ).format(extra=extra_warnings)
  2189. class RNGContext(object):
  2190. """
  2191. Context manager to set the numpy random number generator speed. Returns
  2192. to the original value upon exiting the context manager.
  2193. Parameters
  2194. ----------
  2195. seed : int
  2196. Seed for numpy.random.seed
  2197. Examples
  2198. --------
  2199. with RNGContext(42):
  2200. np.random.randn()
  2201. """
  2202. def __init__(self, seed):
  2203. self.seed = seed
  2204. def __enter__(self):
  2205. self.start_state = np.random.get_state()
  2206. np.random.seed(self.seed)
  2207. def __exit__(self, exc_type, exc_value, traceback):
  2208. np.random.set_state(self.start_state)
  2209. @contextmanager
  2210. def with_csv_dialect(name, **kwargs):
  2211. """
  2212. Context manager to temporarily register a CSV dialect for parsing CSV.
  2213. Parameters
  2214. ----------
  2215. name : str
  2216. The name of the dialect.
  2217. kwargs : mapping
  2218. The parameters for the dialect.
  2219. Raises
  2220. ------
  2221. ValueError : the name of the dialect conflicts with a builtin one.
  2222. See Also
  2223. --------
  2224. csv : Python's CSV library.
  2225. """
  2226. import csv
  2227. _BUILTIN_DIALECTS = {"excel", "excel-tab", "unix"}
  2228. if name in _BUILTIN_DIALECTS:
  2229. raise ValueError("Cannot override builtin dialect.")
  2230. csv.register_dialect(name, **kwargs)
  2231. yield
  2232. csv.unregister_dialect(name)
  2233. @contextmanager
  2234. def use_numexpr(use, min_elements=None):
  2235. from pandas.core.computation import expressions as expr
  2236. if min_elements is None:
  2237. min_elements = expr._MIN_ELEMENTS
  2238. olduse = expr._USE_NUMEXPR
  2239. oldmin = expr._MIN_ELEMENTS
  2240. expr.set_use_numexpr(use)
  2241. expr._MIN_ELEMENTS = min_elements
  2242. yield
  2243. expr._MIN_ELEMENTS = oldmin
  2244. expr.set_use_numexpr(olduse)
  2245. def test_parallel(num_threads=2, kwargs_list=None):
  2246. """Decorator to run the same function multiple times in parallel.
  2247. Parameters
  2248. ----------
  2249. num_threads : int, optional
  2250. The number of times the function is run in parallel.
  2251. kwargs_list : list of dicts, optional
  2252. The list of kwargs to update original
  2253. function kwargs on different threads.
  2254. Notes
  2255. -----
  2256. This decorator does not pass the return value of the decorated function.
  2257. Original from scikit-image:
  2258. https://github.com/scikit-image/scikit-image/pull/1519
  2259. """
  2260. assert num_threads > 0
  2261. has_kwargs_list = kwargs_list is not None
  2262. if has_kwargs_list:
  2263. assert len(kwargs_list) == num_threads
  2264. import threading
  2265. def wrapper(func):
  2266. @wraps(func)
  2267. def inner(*args, **kwargs):
  2268. if has_kwargs_list:
  2269. update_kwargs = lambda i: dict(kwargs, **kwargs_list[i])
  2270. else:
  2271. update_kwargs = lambda i: kwargs
  2272. threads = []
  2273. for i in range(num_threads):
  2274. updated_kwargs = update_kwargs(i)
  2275. thread = threading.Thread(target=func, args=args,
  2276. kwargs=updated_kwargs)
  2277. threads.append(thread)
  2278. for thread in threads:
  2279. thread.start()
  2280. for thread in threads:
  2281. thread.join()
  2282. return inner
  2283. return wrapper
  2284. class SubclassedSeries(Series):
  2285. _metadata = ['testattr', 'name']
  2286. @property
  2287. def _constructor(self):
  2288. return SubclassedSeries
  2289. @property
  2290. def _constructor_expanddim(self):
  2291. return SubclassedDataFrame
  2292. class SubclassedDataFrame(DataFrame):
  2293. _metadata = ['testattr']
  2294. @property
  2295. def _constructor(self):
  2296. return SubclassedDataFrame
  2297. @property
  2298. def _constructor_sliced(self):
  2299. return SubclassedSeries
  2300. class SubclassedSparseSeries(pd.SparseSeries):
  2301. _metadata = ['testattr']
  2302. @property
  2303. def _constructor(self):
  2304. return SubclassedSparseSeries
  2305. @property
  2306. def _constructor_expanddim(self):
  2307. return SubclassedSparseDataFrame
  2308. class SubclassedSparseDataFrame(pd.SparseDataFrame):
  2309. _metadata = ['testattr']
  2310. @property
  2311. def _constructor(self):
  2312. return SubclassedSparseDataFrame
  2313. @property
  2314. def _constructor_sliced(self):
  2315. return SubclassedSparseSeries
  2316. class SubclassedCategorical(Categorical):
  2317. @property
  2318. def _constructor(self):
  2319. return SubclassedCategorical
  2320. @contextmanager
  2321. def set_timezone(tz):
  2322. """Context manager for temporarily setting a timezone.
  2323. Parameters
  2324. ----------
  2325. tz : str
  2326. A string representing a valid timezone.
  2327. Examples
  2328. --------
  2329. >>> from datetime import datetime
  2330. >>> from dateutil.tz import tzlocal
  2331. >>> tzlocal().tzname(datetime.now())
  2332. 'IST'
  2333. >>> with set_timezone('US/Eastern'):
  2334. ... tzlocal().tzname(datetime.now())
  2335. ...
  2336. 'EDT'
  2337. """
  2338. import os
  2339. import time
  2340. def setTZ(tz):
  2341. if tz is None:
  2342. try:
  2343. del os.environ['TZ']
  2344. except KeyError:
  2345. pass
  2346. else:
  2347. os.environ['TZ'] = tz
  2348. time.tzset()
  2349. orig_tz = os.environ.get('TZ')
  2350. setTZ(tz)
  2351. try:
  2352. yield
  2353. finally:
  2354. setTZ(orig_tz)
  2355. def _make_skipna_wrapper(alternative, skipna_alternative=None):
  2356. """Create a function for calling on an array.
  2357. Parameters
  2358. ----------
  2359. alternative : function
  2360. The function to be called on the array with no NaNs.
  2361. Only used when 'skipna_alternative' is None.
  2362. skipna_alternative : function
  2363. The function to be called on the original array
  2364. Returns
  2365. -------
  2366. skipna_wrapper : function
  2367. """
  2368. if skipna_alternative:
  2369. def skipna_wrapper(x):
  2370. return skipna_alternative(x.values)
  2371. else:
  2372. def skipna_wrapper(x):
  2373. nona = x.dropna()
  2374. if len(nona) == 0:
  2375. return np.nan
  2376. return alternative(nona)
  2377. return skipna_wrapper
  2378. def convert_rows_list_to_csv_str(rows_list):
  2379. """
  2380. Convert list of CSV rows to single CSV-formatted string for current OS.
  2381. This method is used for creating expected value of to_csv() method.
  2382. Parameters
  2383. ----------
  2384. rows_list : list
  2385. The list of string. Each element represents the row of csv.
  2386. Returns
  2387. -------
  2388. expected : string
  2389. Expected output of to_csv() in current OS
  2390. """
  2391. sep = os.linesep
  2392. expected = sep.join(rows_list) + sep
  2393. return expected