PageRenderTime 127ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 1ms

/pandas/core/generic.py

http://github.com/wesm/pandas
Python | 11070 lines | 11022 code | 12 blank | 36 comment | 45 complexity | 2c878bb09b63de04e2c88ceb91926ce0 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. # pylint: disable=W0231,E1101
  2. import collections
  3. from datetime import timedelta
  4. import functools
  5. import gc
  6. import json
  7. import operator
  8. from textwrap import dedent
  9. import warnings
  10. import weakref
  11. import numpy as np
  12. from pandas._libs import Timestamp, iNaT, properties
  13. import pandas.compat as compat
  14. from pandas.compat import (
  15. cPickle as pkl, isidentifier, lrange, lzip, map, set_function_name,
  16. string_types, to_str, zip)
  17. from pandas.compat.numpy import function as nv
  18. from pandas.errors import AbstractMethodError
  19. from pandas.util._decorators import (
  20. Appender, Substitution, rewrite_axis_style_signature)
  21. from pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs
  22. from pandas.core.dtypes.cast import maybe_promote, maybe_upcast_putmask
  23. from pandas.core.dtypes.common import (
  24. ensure_int64, ensure_object, is_bool, is_bool_dtype,
  25. is_datetime64_any_dtype, is_datetime64tz_dtype, is_dict_like,
  26. is_extension_array_dtype, is_integer, is_list_like, is_number,
  27. is_numeric_dtype, is_object_dtype, is_period_arraylike, is_re_compilable,
  28. is_scalar, is_timedelta64_dtype, pandas_dtype)
  29. from pandas.core.dtypes.generic import ABCDataFrame, ABCPanel, ABCSeries
  30. from pandas.core.dtypes.inference import is_hashable
  31. from pandas.core.dtypes.missing import isna, notna
  32. import pandas as pd
  33. from pandas.core import config, missing, nanops
  34. import pandas.core.algorithms as algos
  35. from pandas.core.base import PandasObject, SelectionMixin
  36. import pandas.core.common as com
  37. from pandas.core.index import (
  38. Index, InvalidIndexError, MultiIndex, RangeIndex, ensure_index)
  39. from pandas.core.indexes.datetimes import DatetimeIndex
  40. from pandas.core.indexes.period import Period, PeriodIndex
  41. import pandas.core.indexing as indexing
  42. from pandas.core.internals import BlockManager
  43. from pandas.core.ops import _align_method_FRAME
  44. from pandas.io.formats.format import DataFrameFormatter, format_percentiles
  45. from pandas.io.formats.printing import pprint_thing
  46. from pandas.tseries.frequencies import to_offset
  47. # goal is to be able to define the docs close to function, while still being
  48. # able to share
  49. _shared_docs = dict()
  50. _shared_doc_kwargs = dict(
  51. axes='keywords for axes', klass='NDFrame',
  52. axes_single_arg='int or labels for object',
  53. args_transpose='axes to permute (int or label for object)',
  54. optional_by="""
  55. by : str or list of str
  56. Name or list of names to sort by""")
  57. # sentinel value to use as kwarg in place of None when None has special meaning
  58. # and needs to be distinguished from a user explicitly passing None.
  59. sentinel = object()
  60. def _single_replace(self, to_replace, method, inplace, limit):
  61. """
  62. Replaces values in a Series using the fill method specified when no
  63. replacement value is given in the replace method
  64. """
  65. if self.ndim != 1:
  66. raise TypeError('cannot replace {0} with method {1} on a {2}'
  67. .format(to_replace, method, type(self).__name__))
  68. orig_dtype = self.dtype
  69. result = self if inplace else self.copy()
  70. fill_f = missing.get_fill_func(method)
  71. mask = missing.mask_missing(result.values, to_replace)
  72. values = fill_f(result.values, limit=limit, mask=mask)
  73. if values.dtype == orig_dtype and inplace:
  74. return
  75. result = pd.Series(values, index=self.index,
  76. dtype=self.dtype).__finalize__(self)
  77. if inplace:
  78. self._update_inplace(result._data)
  79. return
  80. return result
  81. class NDFrame(PandasObject, SelectionMixin):
  82. """
  83. N-dimensional analogue of DataFrame. Store multi-dimensional in a
  84. size-mutable, labeled data structure
  85. Parameters
  86. ----------
  87. data : BlockManager
  88. axes : list
  89. copy : boolean, default False
  90. """
  91. _internal_names = ['_data', '_cacher', '_item_cache', '_cache', '_is_copy',
  92. '_subtyp', '_name', '_index', '_default_kind',
  93. '_default_fill_value', '_metadata', '__array_struct__',
  94. '__array_interface__']
  95. _internal_names_set = set(_internal_names)
  96. _accessors = frozenset()
  97. _deprecations = frozenset(['as_blocks', 'blocks',
  98. 'convert_objects', 'is_copy'])
  99. _metadata = []
  100. _is_copy = None
  101. # dummy attribute so that datetime.__eq__(Series/DataFrame) defers
  102. # by returning NotImplemented
  103. timetuple = None
  104. # ----------------------------------------------------------------------
  105. # Constructors
  106. def __init__(self, data, axes=None, copy=False, dtype=None,
  107. fastpath=False):
  108. if not fastpath:
  109. if dtype is not None:
  110. data = data.astype(dtype)
  111. elif copy:
  112. data = data.copy()
  113. if axes is not None:
  114. for i, ax in enumerate(axes):
  115. data = data.reindex_axis(ax, axis=i)
  116. object.__setattr__(self, '_is_copy', None)
  117. object.__setattr__(self, '_data', data)
  118. object.__setattr__(self, '_item_cache', {})
  119. def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
  120. """ passed a manager and a axes dict """
  121. for a, axe in axes.items():
  122. if axe is not None:
  123. mgr = mgr.reindex_axis(axe,
  124. axis=self._get_block_manager_axis(a),
  125. copy=False)
  126. # make a copy if explicitly requested
  127. if copy:
  128. mgr = mgr.copy()
  129. if dtype is not None:
  130. # avoid further copies if we can
  131. if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype:
  132. mgr = mgr.astype(dtype=dtype)
  133. return mgr
  134. # ----------------------------------------------------------------------
  135. @property
  136. def is_copy(self):
  137. """
  138. Return the copy.
  139. """
  140. warnings.warn("Attribute 'is_copy' is deprecated and will be removed "
  141. "in a future version.", FutureWarning, stacklevel=2)
  142. return self._is_copy
  143. @is_copy.setter
  144. def is_copy(self, msg):
  145. warnings.warn("Attribute 'is_copy' is deprecated and will be removed "
  146. "in a future version.", FutureWarning, stacklevel=2)
  147. self._is_copy = msg
  148. def _validate_dtype(self, dtype):
  149. """ validate the passed dtype """
  150. if dtype is not None:
  151. dtype = pandas_dtype(dtype)
  152. # a compound dtype
  153. if dtype.kind == 'V':
  154. raise NotImplementedError("compound dtypes are not implemented"
  155. " in the {0} constructor"
  156. .format(self.__class__.__name__))
  157. return dtype
  158. # ----------------------------------------------------------------------
  159. # Construction
  160. @property
  161. def _constructor(self):
  162. """Used when a manipulation result has the same dimensions as the
  163. original.
  164. """
  165. raise AbstractMethodError(self)
  166. @property
  167. def _constructor_sliced(self):
  168. """Used when a manipulation result has one lower dimension(s) as the
  169. original, such as DataFrame single columns slicing.
  170. """
  171. raise AbstractMethodError(self)
  172. @property
  173. def _constructor_expanddim(self):
  174. """Used when a manipulation result has one higher dimension as the
  175. original, such as Series.to_frame() and DataFrame.to_panel()
  176. """
  177. raise NotImplementedError
  178. # ----------------------------------------------------------------------
  179. # Axis
  180. @classmethod
  181. def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None,
  182. slicers=None, axes_are_reversed=False, build_axes=True,
  183. ns=None, docs=None):
  184. """Provide axes setup for the major PandasObjects.
  185. Parameters
  186. ----------
  187. axes : the names of the axes in order (lowest to highest)
  188. info_axis_num : the axis of the selector dimension (int)
  189. stat_axis_num : the number of axis for the default stats (int)
  190. aliases : other names for a single axis (dict)
  191. slicers : how axes slice to others (dict)
  192. axes_are_reversed : boolean whether to treat passed axes as
  193. reversed (DataFrame)
  194. build_axes : setup the axis properties (default True)
  195. """
  196. cls._AXIS_ORDERS = axes
  197. cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)}
  198. cls._AXIS_LEN = len(axes)
  199. cls._AXIS_ALIASES = aliases or dict()
  200. cls._AXIS_IALIASES = {v: k for k, v in cls._AXIS_ALIASES.items()}
  201. cls._AXIS_NAMES = dict(enumerate(axes))
  202. cls._AXIS_SLICEMAP = slicers or None
  203. cls._AXIS_REVERSED = axes_are_reversed
  204. # typ
  205. setattr(cls, '_typ', cls.__name__.lower())
  206. # indexing support
  207. cls._ix = None
  208. if info_axis is not None:
  209. cls._info_axis_number = info_axis
  210. cls._info_axis_name = axes[info_axis]
  211. if stat_axis is not None:
  212. cls._stat_axis_number = stat_axis
  213. cls._stat_axis_name = axes[stat_axis]
  214. # setup the actual axis
  215. if build_axes:
  216. def set_axis(a, i):
  217. setattr(cls, a, properties.AxisProperty(i, docs.get(a, a)))
  218. cls._internal_names_set.add(a)
  219. if axes_are_reversed:
  220. m = cls._AXIS_LEN - 1
  221. for i, a in cls._AXIS_NAMES.items():
  222. set_axis(a, m - i)
  223. else:
  224. for i, a in cls._AXIS_NAMES.items():
  225. set_axis(a, i)
  226. assert not isinstance(ns, dict)
  227. def _construct_axes_dict(self, axes=None, **kwargs):
  228. """Return an axes dictionary for myself."""
  229. d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
  230. d.update(kwargs)
  231. return d
  232. @staticmethod
  233. def _construct_axes_dict_from(self, axes, **kwargs):
  234. """Return an axes dictionary for the passed axes."""
  235. d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)}
  236. d.update(kwargs)
  237. return d
  238. def _construct_axes_dict_for_slice(self, axes=None, **kwargs):
  239. """Return an axes dictionary for myself."""
  240. d = {self._AXIS_SLICEMAP[a]: self._get_axis(a)
  241. for a in (axes or self._AXIS_ORDERS)}
  242. d.update(kwargs)
  243. return d
  244. def _construct_axes_from_arguments(
  245. self, args, kwargs, require_all=False, sentinel=None):
  246. """Construct and returns axes if supplied in args/kwargs.
  247. If require_all, raise if all axis arguments are not supplied
  248. return a tuple of (axes, kwargs).
  249. sentinel specifies the default parameter when an axis is not
  250. supplied; useful to distinguish when a user explicitly passes None
  251. in scenarios where None has special meaning.
  252. """
  253. # construct the args
  254. args = list(args)
  255. for a in self._AXIS_ORDERS:
  256. # if we have an alias for this axis
  257. alias = self._AXIS_IALIASES.get(a)
  258. if alias is not None:
  259. if a in kwargs:
  260. if alias in kwargs:
  261. raise TypeError("arguments are mutually exclusive "
  262. "for [%s,%s]" % (a, alias))
  263. continue
  264. if alias in kwargs:
  265. kwargs[a] = kwargs.pop(alias)
  266. continue
  267. # look for a argument by position
  268. if a not in kwargs:
  269. try:
  270. kwargs[a] = args.pop(0)
  271. except IndexError:
  272. if require_all:
  273. raise TypeError("not enough/duplicate arguments "
  274. "specified!")
  275. axes = {a: kwargs.pop(a, sentinel) for a in self._AXIS_ORDERS}
  276. return axes, kwargs
  277. @classmethod
  278. def _from_axes(cls, data, axes, **kwargs):
  279. # for construction from BlockManager
  280. if isinstance(data, BlockManager):
  281. return cls(data, **kwargs)
  282. else:
  283. if cls._AXIS_REVERSED:
  284. axes = axes[::-1]
  285. d = cls._construct_axes_dict_from(cls, axes, copy=False)
  286. d.update(kwargs)
  287. return cls(data, **d)
  288. @classmethod
  289. def _get_axis_number(cls, axis):
  290. axis = cls._AXIS_ALIASES.get(axis, axis)
  291. if is_integer(axis):
  292. if axis in cls._AXIS_NAMES:
  293. return axis
  294. else:
  295. try:
  296. return cls._AXIS_NUMBERS[axis]
  297. except KeyError:
  298. pass
  299. raise ValueError('No axis named {0} for object type {1}'
  300. .format(axis, cls))
  301. @classmethod
  302. def _get_axis_name(cls, axis):
  303. axis = cls._AXIS_ALIASES.get(axis, axis)
  304. if isinstance(axis, string_types):
  305. if axis in cls._AXIS_NUMBERS:
  306. return axis
  307. else:
  308. try:
  309. return cls._AXIS_NAMES[axis]
  310. except KeyError:
  311. pass
  312. raise ValueError('No axis named {0} for object type {1}'
  313. .format(axis, cls))
  314. def _get_axis(self, axis):
  315. name = self._get_axis_name(axis)
  316. return getattr(self, name)
  317. @classmethod
  318. def _get_block_manager_axis(cls, axis):
  319. """Map the axis to the block_manager axis."""
  320. axis = cls._get_axis_number(axis)
  321. if cls._AXIS_REVERSED:
  322. m = cls._AXIS_LEN - 1
  323. return m - axis
  324. return axis
  325. def _get_axis_resolvers(self, axis):
  326. # index or columns
  327. axis_index = getattr(self, axis)
  328. d = dict()
  329. prefix = axis[0]
  330. for i, name in enumerate(axis_index.names):
  331. if name is not None:
  332. key = level = name
  333. else:
  334. # prefix with 'i' or 'c' depending on the input axis
  335. # e.g., you must do ilevel_0 for the 0th level of an unnamed
  336. # multiiindex
  337. key = '{prefix}level_{i}'.format(prefix=prefix, i=i)
  338. level = i
  339. level_values = axis_index.get_level_values(level)
  340. s = level_values.to_series()
  341. s.index = axis_index
  342. d[key] = s
  343. # put the index/columns itself in the dict
  344. if isinstance(axis_index, MultiIndex):
  345. dindex = axis_index
  346. else:
  347. dindex = axis_index.to_series()
  348. d[axis] = dindex
  349. return d
  350. def _get_index_resolvers(self):
  351. d = {}
  352. for axis_name in self._AXIS_ORDERS:
  353. d.update(self._get_axis_resolvers(axis_name))
  354. return d
  355. @property
  356. def _info_axis(self):
  357. return getattr(self, self._info_axis_name)
  358. @property
  359. def _stat_axis(self):
  360. return getattr(self, self._stat_axis_name)
  361. @property
  362. def shape(self):
  363. """
  364. Return a tuple of axis dimensions
  365. """
  366. return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)
  367. @property
  368. def axes(self):
  369. """
  370. Return index label(s) of the internal NDFrame
  371. """
  372. # we do it this way because if we have reversed axes, then
  373. # the block manager shows then reversed
  374. return [self._get_axis(a) for a in self._AXIS_ORDERS]
  375. @property
  376. def ndim(self):
  377. """
  378. Return an int representing the number of axes / array dimensions.
  379. Return 1 if Series. Otherwise return 2 if DataFrame.
  380. See Also
  381. --------
  382. ndarray.ndim : Number of array dimensions.
  383. Examples
  384. --------
  385. >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})
  386. >>> s.ndim
  387. 1
  388. >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
  389. >>> df.ndim
  390. 2
  391. """
  392. return self._data.ndim
  393. @property
  394. def size(self):
  395. """
  396. Return an int representing the number of elements in this object.
  397. Return the number of rows if Series. Otherwise return the number of
  398. rows times number of columns if DataFrame.
  399. See Also
  400. --------
  401. ndarray.size : Number of elements in the array.
  402. Examples
  403. --------
  404. >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})
  405. >>> s.size
  406. 3
  407. >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
  408. >>> df.size
  409. 4
  410. """
  411. return np.prod(self.shape)
  412. @property
  413. def _selected_obj(self):
  414. """ internal compat with SelectionMixin """
  415. return self
  416. @property
  417. def _obj_with_exclusions(self):
  418. """ internal compat with SelectionMixin """
  419. return self
  420. def _expand_axes(self, key):
  421. new_axes = []
  422. for k, ax in zip(key, self.axes):
  423. if k not in ax:
  424. if type(k) != ax.dtype.type:
  425. ax = ax.astype('O')
  426. new_axes.append(ax.insert(len(ax), k))
  427. else:
  428. new_axes.append(ax)
  429. return new_axes
  430. def set_axis(self, labels, axis=0, inplace=None):
  431. """
  432. Assign desired index to given axis.
  433. Indexes for column or row labels can be changed by assigning
  434. a list-like or Index.
  435. .. versionchanged:: 0.21.0
  436. The signature is now `labels` and `axis`, consistent with
  437. the rest of pandas API. Previously, the `axis` and `labels`
  438. arguments were respectively the first and second positional
  439. arguments.
  440. Parameters
  441. ----------
  442. labels : list-like, Index
  443. The values for the new index.
  444. axis : {0 or 'index', 1 or 'columns'}, default 0
  445. The axis to update. The value 0 identifies the rows, and 1
  446. identifies the columns.
  447. inplace : bool, default None
  448. Whether to return a new %(klass)s instance.
  449. .. warning::
  450. ``inplace=None`` currently falls back to to True, but in a
  451. future version, will default to False. Use inplace=True
  452. explicitly rather than relying on the default.
  453. Returns
  454. -------
  455. renamed : %(klass)s or None
  456. An object of same type as caller if inplace=False, None otherwise.
  457. See Also
  458. --------
  459. DataFrame.rename_axis : Alter the name of the index or columns.
  460. Examples
  461. --------
  462. **Series**
  463. >>> s = pd.Series([1, 2, 3])
  464. >>> s
  465. 0 1
  466. 1 2
  467. 2 3
  468. dtype: int64
  469. >>> s.set_axis(['a', 'b', 'c'], axis=0, inplace=False)
  470. a 1
  471. b 2
  472. c 3
  473. dtype: int64
  474. The original object is not modified.
  475. >>> s
  476. 0 1
  477. 1 2
  478. 2 3
  479. dtype: int64
  480. **DataFrame**
  481. >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
  482. Change the row labels.
  483. >>> df.set_axis(['a', 'b', 'c'], axis='index', inplace=False)
  484. A B
  485. a 1 4
  486. b 2 5
  487. c 3 6
  488. Change the column labels.
  489. >>> df.set_axis(['I', 'II'], axis='columns', inplace=False)
  490. I II
  491. 0 1 4
  492. 1 2 5
  493. 2 3 6
  494. Now, update the labels inplace.
  495. >>> df.set_axis(['i', 'ii'], axis='columns', inplace=True)
  496. >>> df
  497. i ii
  498. 0 1 4
  499. 1 2 5
  500. 2 3 6
  501. """
  502. if is_scalar(labels):
  503. warnings.warn(
  504. 'set_axis now takes "labels" as first argument, and '
  505. '"axis" as named parameter. The old form, with "axis" as '
  506. 'first parameter and \"labels\" as second, is still supported '
  507. 'but will be deprecated in a future version of pandas.',
  508. FutureWarning, stacklevel=2)
  509. labels, axis = axis, labels
  510. if inplace is None:
  511. warnings.warn(
  512. 'set_axis currently defaults to operating inplace.\nThis '
  513. 'will change in a future version of pandas, use '
  514. 'inplace=True to avoid this warning.',
  515. FutureWarning, stacklevel=2)
  516. inplace = True
  517. if inplace:
  518. setattr(self, self._get_axis_name(axis), labels)
  519. else:
  520. obj = self.copy()
  521. obj.set_axis(labels, axis=axis, inplace=True)
  522. return obj
  523. def _set_axis(self, axis, labels):
  524. self._data.set_axis(axis, labels)
  525. self._clear_item_cache()
  526. def transpose(self, *args, **kwargs):
  527. """
  528. Permute the dimensions of the %(klass)s
  529. Parameters
  530. ----------
  531. args : %(args_transpose)s
  532. copy : boolean, default False
  533. Make a copy of the underlying data. Mixed-dtype data will
  534. always result in a copy
  535. **kwargs
  536. Additional keyword arguments will be passed to the function.
  537. Returns
  538. -------
  539. y : same as input
  540. Examples
  541. --------
  542. >>> p.transpose(2, 0, 1)
  543. >>> p.transpose(2, 0, 1, copy=True)
  544. """
  545. # construct the args
  546. axes, kwargs = self._construct_axes_from_arguments(args, kwargs,
  547. require_all=True)
  548. axes_names = tuple(self._get_axis_name(axes[a])
  549. for a in self._AXIS_ORDERS)
  550. axes_numbers = tuple(self._get_axis_number(axes[a])
  551. for a in self._AXIS_ORDERS)
  552. # we must have unique axes
  553. if len(axes) != len(set(axes)):
  554. raise ValueError('Must specify %s unique axes' % self._AXIS_LEN)
  555. new_axes = self._construct_axes_dict_from(self, [self._get_axis(x)
  556. for x in axes_names])
  557. new_values = self.values.transpose(axes_numbers)
  558. if kwargs.pop('copy', None) or (len(args) and args[-1]):
  559. new_values = new_values.copy()
  560. nv.validate_transpose_for_generic(self, kwargs)
  561. return self._constructor(new_values, **new_axes).__finalize__(self)
  562. def swapaxes(self, axis1, axis2, copy=True):
  563. """
  564. Interchange axes and swap values axes appropriately.
  565. Returns
  566. -------
  567. y : same as input
  568. """
  569. i = self._get_axis_number(axis1)
  570. j = self._get_axis_number(axis2)
  571. if i == j:
  572. if copy:
  573. return self.copy()
  574. return self
  575. mapping = {i: j, j: i}
  576. new_axes = (self._get_axis(mapping.get(k, k))
  577. for k in range(self._AXIS_LEN))
  578. new_values = self.values.swapaxes(i, j)
  579. if copy:
  580. new_values = new_values.copy()
  581. return self._constructor(new_values, *new_axes).__finalize__(self)
  582. def droplevel(self, level, axis=0):
  583. """
  584. Return DataFrame with requested index / column level(s) removed.
  585. .. versionadded:: 0.24.0
  586. Parameters
  587. ----------
  588. level : int, str, or list-like
  589. If a string is given, must be the name of a level
  590. If list-like, elements must be names or positional indexes
  591. of levels.
  592. axis : {0 or 'index', 1 or 'columns'}, default 0
  593. Returns
  594. -------
  595. DataFrame.droplevel()
  596. Examples
  597. --------
  598. >>> df = pd.DataFrame([
  599. ... [1, 2, 3, 4],
  600. ... [5, 6, 7, 8],
  601. ... [9, 10, 11, 12]
  602. ... ]).set_index([0, 1]).rename_axis(['a', 'b'])
  603. >>> df.columns = pd.MultiIndex.from_tuples([
  604. ... ('c', 'e'), ('d', 'f')
  605. ... ], names=['level_1', 'level_2'])
  606. >>> df
  607. level_1 c d
  608. level_2 e f
  609. a b
  610. 1 2 3 4
  611. 5 6 7 8
  612. 9 10 11 12
  613. >>> df.droplevel('a')
  614. level_1 c d
  615. level_2 e f
  616. b
  617. 2 3 4
  618. 6 7 8
  619. 10 11 12
  620. >>> df.droplevel('level2', axis=1)
  621. level_1 c d
  622. a b
  623. 1 2 3 4
  624. 5 6 7 8
  625. 9 10 11 12
  626. """
  627. labels = self._get_axis(axis)
  628. new_labels = labels.droplevel(level)
  629. result = self.set_axis(new_labels, axis=axis, inplace=False)
  630. return result
  631. def pop(self, item):
  632. """
  633. Return item and drop from frame. Raise KeyError if not found.
  634. Parameters
  635. ----------
  636. item : str
  637. Label of column to be popped.
  638. Returns
  639. -------
  640. Series
  641. Examples
  642. --------
  643. >>> df = pd.DataFrame([('falcon', 'bird', 389.0),
  644. ... ('parrot', 'bird', 24.0),
  645. ... ('lion', 'mammal', 80.5),
  646. ... ('monkey','mammal', np.nan)],
  647. ... columns=('name', 'class', 'max_speed'))
  648. >>> df
  649. name class max_speed
  650. 0 falcon bird 389.0
  651. 1 parrot bird 24.0
  652. 2 lion mammal 80.5
  653. 3 monkey mammal NaN
  654. >>> df.pop('class')
  655. 0 bird
  656. 1 bird
  657. 2 mammal
  658. 3 mammal
  659. Name: class, dtype: object
  660. >>> df
  661. name max_speed
  662. 0 falcon 389.0
  663. 1 parrot 24.0
  664. 2 lion 80.5
  665. 3 monkey NaN
  666. """
  667. result = self[item]
  668. del self[item]
  669. try:
  670. result._reset_cacher()
  671. except AttributeError:
  672. pass
  673. return result
  674. def squeeze(self, axis=None):
  675. """
  676. Squeeze 1 dimensional axis objects into scalars.
  677. Series or DataFrames with a single element are squeezed to a scalar.
  678. DataFrames with a single column or a single row are squeezed to a
  679. Series. Otherwise the object is unchanged.
  680. This method is most useful when you don't know if your
  681. object is a Series or DataFrame, but you do know it has just a single
  682. column. In that case you can safely call `squeeze` to ensure you have a
  683. Series.
  684. Parameters
  685. ----------
  686. axis : {0 or 'index', 1 or 'columns', None}, default None
  687. A specific axis to squeeze. By default, all length-1 axes are
  688. squeezed.
  689. .. versionadded:: 0.20.0
  690. Returns
  691. -------
  692. DataFrame, Series, or scalar
  693. The projection after squeezing `axis` or all the axes.
  694. See Also
  695. --------
  696. Series.iloc : Integer-location based indexing for selecting scalars.
  697. DataFrame.iloc : Integer-location based indexing for selecting Series.
  698. Series.to_frame : Inverse of DataFrame.squeeze for a
  699. single-column DataFrame.
  700. Examples
  701. --------
  702. >>> primes = pd.Series([2, 3, 5, 7])
  703. Slicing might produce a Series with a single value:
  704. >>> even_primes = primes[primes % 2 == 0]
  705. >>> even_primes
  706. 0 2
  707. dtype: int64
  708. >>> even_primes.squeeze()
  709. 2
  710. Squeezing objects with more than one value in every axis does nothing:
  711. >>> odd_primes = primes[primes % 2 == 1]
  712. >>> odd_primes
  713. 1 3
  714. 2 5
  715. 3 7
  716. dtype: int64
  717. >>> odd_primes.squeeze()
  718. 1 3
  719. 2 5
  720. 3 7
  721. dtype: int64
  722. Squeezing is even more effective when used with DataFrames.
  723. >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
  724. >>> df
  725. a b
  726. 0 1 2
  727. 1 3 4
  728. Slicing a single column will produce a DataFrame with the columns
  729. having only one value:
  730. >>> df_a = df[['a']]
  731. >>> df_a
  732. a
  733. 0 1
  734. 1 3
  735. So the columns can be squeezed down, resulting in a Series:
  736. >>> df_a.squeeze('columns')
  737. 0 1
  738. 1 3
  739. Name: a, dtype: int64
  740. Slicing a single row from a single column will produce a single
  741. scalar DataFrame:
  742. >>> df_0a = df.loc[df.index < 1, ['a']]
  743. >>> df_0a
  744. a
  745. 0 1
  746. Squeezing the rows produces a single scalar Series:
  747. >>> df_0a.squeeze('rows')
  748. a 1
  749. Name: 0, dtype: int64
  750. Squeezing all axes wil project directly into a scalar:
  751. >>> df_0a.squeeze()
  752. 1
  753. """
  754. axis = (self._AXIS_NAMES if axis is None else
  755. (self._get_axis_number(axis),))
  756. try:
  757. return self.iloc[
  758. tuple(0 if i in axis and len(a) == 1 else slice(None)
  759. for i, a in enumerate(self.axes))]
  760. except Exception:
  761. return self
  762. def swaplevel(self, i=-2, j=-1, axis=0):
  763. """
  764. Swap levels i and j in a MultiIndex on a particular axis
  765. Parameters
  766. ----------
  767. i, j : int, str (can be mixed)
  768. Level of index to be swapped. Can pass level name as string.
  769. Returns
  770. -------
  771. swapped : same type as caller (new object)
  772. .. versionchanged:: 0.18.1
  773. The indexes ``i`` and ``j`` are now optional, and default to
  774. the two innermost levels of the index.
  775. """
  776. axis = self._get_axis_number(axis)
  777. result = self.copy()
  778. labels = result._data.axes[axis]
  779. result._data.set_axis(axis, labels.swaplevel(i, j))
  780. return result
  781. # ----------------------------------------------------------------------
  782. # Rename
  783. def rename(self, *args, **kwargs):
  784. """
  785. Alter axes input function or functions. Function / dict values must be
  786. unique (1-to-1). Labels not contained in a dict / Series will be left
  787. as-is. Extra labels listed don't throw an error. Alternatively, change
  788. ``Series.name`` with a scalar value (Series only).
  789. Parameters
  790. ----------
  791. %(axes)s : scalar, list-like, dict-like or function, optional
  792. Scalar or list-like will alter the ``Series.name`` attribute,
  793. and raise on DataFrame or Panel.
  794. dict-like or functions are transformations to apply to
  795. that axis' values
  796. copy : bool, default True
  797. Also copy underlying data.
  798. inplace : bool, default False
  799. Whether to return a new %(klass)s. If True then value of copy is
  800. ignored.
  801. level : int or level name, default None
  802. In case of a MultiIndex, only rename labels in the specified
  803. level.
  804. errors : {'ignore', 'raise'}, default 'ignore'
  805. If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
  806. or `columns` contains labels that are not present in the Index
  807. being transformed.
  808. If 'ignore', existing keys will be renamed and extra keys will be
  809. ignored.
  810. Returns
  811. -------
  812. renamed : %(klass)s (new object)
  813. Raises
  814. ------
  815. KeyError
  816. If any of the labels is not found in the selected axis and
  817. "errors='raise'".
  818. See Also
  819. --------
  820. NDFrame.rename_axis
  821. Examples
  822. --------
  823. >>> s = pd.Series([1, 2, 3])
  824. >>> s
  825. 0 1
  826. 1 2
  827. 2 3
  828. dtype: int64
  829. >>> s.rename("my_name") # scalar, changes Series.name
  830. 0 1
  831. 1 2
  832. 2 3
  833. Name: my_name, dtype: int64
  834. >>> s.rename(lambda x: x ** 2) # function, changes labels
  835. 0 1
  836. 1 2
  837. 4 3
  838. dtype: int64
  839. >>> s.rename({1: 3, 2: 5}) # mapping, changes labels
  840. 0 1
  841. 3 2
  842. 5 3
  843. dtype: int64
  844. Since ``DataFrame`` doesn't have a ``.name`` attribute,
  845. only mapping-type arguments are allowed.
  846. >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
  847. >>> df.rename(2)
  848. Traceback (most recent call last):
  849. ...
  850. TypeError: 'int' object is not callable
  851. ``DataFrame.rename`` supports two calling conventions
  852. * ``(index=index_mapper, columns=columns_mapper, ...)``
  853. * ``(mapper, axis={'index', 'columns'}, ...)``
  854. We *highly* recommend using keyword arguments to clarify your
  855. intent.
  856. >>> df.rename(index=str, columns={"A": "a", "B": "c"})
  857. a c
  858. 0 1 4
  859. 1 2 5
  860. 2 3 6
  861. >>> df.rename(index=str, columns={"A": "a", "C": "c"})
  862. a B
  863. 0 1 4
  864. 1 2 5
  865. 2 3 6
  866. Using axis-style parameters
  867. >>> df.rename(str.lower, axis='columns')
  868. a b
  869. 0 1 4
  870. 1 2 5
  871. 2 3 6
  872. >>> df.rename({1: 2, 2: 4}, axis='index')
  873. A B
  874. 0 1 4
  875. 2 2 5
  876. 4 3 6
  877. See the :ref:`user guide <basics.rename>` for more.
  878. """
  879. axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
  880. copy = kwargs.pop('copy', True)
  881. inplace = kwargs.pop('inplace', False)
  882. level = kwargs.pop('level', None)
  883. axis = kwargs.pop('axis', None)
  884. errors = kwargs.pop('errors', 'ignore')
  885. if axis is not None:
  886. # Validate the axis
  887. self._get_axis_number(axis)
  888. if kwargs:
  889. raise TypeError('rename() got an unexpected keyword '
  890. 'argument "{0}"'.format(list(kwargs.keys())[0]))
  891. if com.count_not_none(*axes.values()) == 0:
  892. raise TypeError('must pass an index to rename')
  893. self._consolidate_inplace()
  894. result = self if inplace else self.copy(deep=copy)
  895. # start in the axis order to eliminate too many copies
  896. for axis in lrange(self._AXIS_LEN):
  897. v = axes.get(self._AXIS_NAMES[axis])
  898. if v is None:
  899. continue
  900. f = com._get_rename_function(v)
  901. baxis = self._get_block_manager_axis(axis)
  902. if level is not None:
  903. level = self.axes[axis]._get_level_number(level)
  904. # GH 13473
  905. if not callable(v):
  906. indexer = self.axes[axis].get_indexer_for(v)
  907. if errors == 'raise' and len(indexer[indexer == -1]):
  908. missing_labels = [label for index, label in enumerate(v)
  909. if indexer[index] == -1]
  910. raise KeyError('{} not found in axis'
  911. .format(missing_labels))
  912. result._data = result._data.rename_axis(f, axis=baxis, copy=copy,
  913. level=level)
  914. result._clear_item_cache()
  915. if inplace:
  916. self._update_inplace(result._data)
  917. else:
  918. return result.__finalize__(self)
  919. @rewrite_axis_style_signature('mapper', [('copy', True),
  920. ('inplace', False)])
  921. def rename_axis(self, mapper=sentinel, **kwargs):
  922. """
  923. Set the name of the axis for the index or columns.
  924. Parameters
  925. ----------
  926. mapper : scalar, list-like, optional
  927. Value to set the axis name attribute.
  928. index, columns : scalar, list-like, dict-like or function, optional
  929. A scalar, list-like, dict-like or functions transformations to
  930. apply to that axis' values.
  931. Use either ``mapper`` and ``axis`` to
  932. specify the axis to target with ``mapper``, or ``index``
  933. and/or ``columns``.
  934. .. versionchanged:: 0.24.0
  935. axis : {0 or 'index', 1 or 'columns'}, default 0
  936. The axis to rename.
  937. copy : bool, default True
  938. Also copy underlying data.
  939. inplace : bool, default False
  940. Modifies the object directly, instead of creating a new Series
  941. or DataFrame.
  942. Returns
  943. -------
  944. Series, DataFrame, or None
  945. The same type as the caller or None if `inplace` is True.
  946. See Also
  947. --------
  948. Series.rename : Alter Series index labels or name.
  949. DataFrame.rename : Alter DataFrame index labels or name.
  950. Index.rename : Set new names on index.
  951. Notes
  952. -----
  953. Prior to version 0.21.0, ``rename_axis`` could also be used to change
  954. the axis *labels* by passing a mapping or scalar. This behavior is
  955. deprecated and will be removed in a future version. Use ``rename``
  956. instead.
  957. ``DataFrame.rename_axis`` supports two calling conventions
  958. * ``(index=index_mapper, columns=columns_mapper, ...)``
  959. * ``(mapper, axis={'index', 'columns'}, ...)``
  960. The first calling convention will only modify the names of
  961. the index and/or the names of the Index object that is the columns.
  962. In this case, the parameter ``copy`` is ignored.
  963. The second calling convention will modify the names of the
  964. the corresponding index if mapper is a list or a scalar.
  965. However, if mapper is dict-like or a function, it will use the
  966. deprecated behavior of modifying the axis *labels*.
  967. We *highly* recommend using keyword arguments to clarify your
  968. intent.
  969. Examples
  970. --------
  971. **Series**
  972. >>> s = pd.Series(["dog", "cat", "monkey"])
  973. >>> s
  974. 0 dog
  975. 1 cat
  976. 2 monkey
  977. dtype: object
  978. >>> s.rename_axis("animal")
  979. animal
  980. 0 dog
  981. 1 cat
  982. 2 monkey
  983. dtype: object
  984. **DataFrame**
  985. >>> df = pd.DataFrame({"num_legs": [4, 4, 2],
  986. ... "num_arms": [0, 0, 2]},
  987. ... ["dog", "cat", "monkey"])
  988. >>> df
  989. num_legs num_arms
  990. dog 4 0
  991. cat 4 0
  992. monkey 2 2
  993. >>> df = df.rename_axis("animal")
  994. >>> df
  995. num_legs num_arms
  996. animal
  997. dog 4 0
  998. cat 4 0
  999. monkey 2 2
  1000. >>> df = df.rename_axis("limbs", axis="columns")
  1001. >>> df
  1002. limbs num_legs num_arms
  1003. animal
  1004. dog 4 0
  1005. cat 4 0
  1006. monkey 2 2
  1007. **MultiIndex**
  1008. >>> df.index = pd.MultiIndex.from_product([['mammal'],
  1009. ... ['dog', 'cat', 'monkey']],
  1010. ... names=['type', 'name'])
  1011. >>> df
  1012. limbs num_legs num_arms
  1013. type name
  1014. mammal dog 4 0
  1015. cat 4 0
  1016. monkey 2 2
  1017. >>> df.rename_axis(index={'type': 'class'})
  1018. limbs num_legs num_arms
  1019. class name
  1020. mammal dog 4 0
  1021. cat 4 0
  1022. monkey 2 2
  1023. >>> df.rename_axis(columns=str.upper)
  1024. LIMBS num_legs num_arms
  1025. type name
  1026. mammal dog 4 0
  1027. cat 4 0
  1028. monkey 2 2
  1029. """
  1030. axes, kwargs = self._construct_axes_from_arguments(
  1031. (), kwargs, sentinel=sentinel)
  1032. copy = kwargs.pop('copy', True)
  1033. inplace = kwargs.pop('inplace', False)
  1034. axis = kwargs.pop('axis', 0)
  1035. if axis is not None:
  1036. axis = self._get_axis_number(axis)
  1037. if kwargs:
  1038. raise TypeError('rename_axis() got an unexpected keyword '
  1039. 'argument "{0}"'.format(list(kwargs.keys())[0]))
  1040. inplace = validate_bool_kwarg(inplace, 'inplace')
  1041. if (mapper is not sentinel):
  1042. # Use v0.23 behavior if a scalar or list
  1043. non_mapper = is_scalar(mapper) or (is_list_like(mapper) and not
  1044. is_dict_like(mapper))
  1045. if non_mapper:
  1046. return self._set_axis_name(mapper, axis=axis, inplace=inplace)
  1047. else:
  1048. # Deprecated (v0.21) behavior is if mapper is specified,
  1049. # and not a list or scalar, then call rename
  1050. msg = ("Using 'rename_axis' to alter labels is deprecated. "
  1051. "Use '.rename' instead")
  1052. warnings.warn(msg, FutureWarning, stacklevel=3)
  1053. axis = self._get_axis_name(axis)
  1054. d = {'copy': copy, 'inplace': inplace}
  1055. d[axis] = mapper
  1056. return self.rename(**d)
  1057. else:
  1058. # Use new behavior. Means that index and/or columns
  1059. # is specified
  1060. result = self if inplace else self.copy(deep=copy)
  1061. for axis in lrange(self._AXIS_LEN):
  1062. v = axes.get(self._AXIS_NAMES[axis])
  1063. if v is sentinel:
  1064. continue
  1065. non_mapper = is_scalar(v) or (is_list_like(v) and not
  1066. is_dict_like(v))
  1067. if non_mapper:
  1068. newnames = v
  1069. else:
  1070. f = com._get_rename_function(v)
  1071. curnames = self._get_axis(axis).names
  1072. newnames = [f(name) for name in curnames]
  1073. result._set_axis_name(newnames, axis=axis,
  1074. inplace=True)
  1075. if not inplace:
  1076. return result
  1077. def _set_axis_name(self, name, axis=0, inplace=False):
  1078. """
  1079. Set the name(s) of the axis.
  1080. Parameters
  1081. ----------
  1082. name : str or list of str
  1083. Name(s) to set.
  1084. axis : {0 or 'index', 1 or 'columns'}, default 0
  1085. The axis to set the label. The value 0 or 'index' specifies index,
  1086. and the value 1 or 'columns' specifies columns.
  1087. inplace : bool, default False
  1088. If `True`, do operation inplace and return None.
  1089. .. versionadded:: 0.21.0
  1090. Returns
  1091. -------
  1092. Series, DataFrame, or None
  1093. The same type as the caller or `None` if `inplace` is `True`.
  1094. See Also
  1095. --------
  1096. DataFrame.rename : Alter the axis labels of :class:`DataFrame`.
  1097. Series.rename : Alter the index labels or set the index name
  1098. of :class:`Series`.
  1099. Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`.
  1100. Examples
  1101. --------
  1102. >>> df = pd.DataFrame({"num_legs": [4, 4, 2]},
  1103. ... ["dog", "cat", "monkey"])
  1104. >>> df
  1105. num_legs
  1106. dog 4
  1107. cat 4
  1108. monkey 2
  1109. >>> df._set_axis_name("animal")
  1110. num_legs
  1111. animal
  1112. dog 4
  1113. cat 4
  1114. monkey 2
  1115. >>> df.index = pd.MultiIndex.from_product(
  1116. ... [["mammal"], ['dog', 'cat', 'monkey']])
  1117. >>> df._set_axis_name(["type", "name"])
  1118. legs
  1119. type name
  1120. mammal dog 4
  1121. cat 4
  1122. monkey 2
  1123. """
  1124. axis = self._get_axis_number(axis)
  1125. idx = self._get_axis(axis).set_names(name)
  1126. inplace = validate_bool_kwarg(inplace, 'inplace')
  1127. renamed = self if inplace else self.copy()
  1128. renamed.set_axis(idx, axis=axis, inplace=True)
  1129. if not inplace:
  1130. return renamed
  1131. # ----------------------------------------------------------------------
  1132. # Comparison Methods
  1133. def _indexed_same(self, other):
  1134. return all(self._get_axis(a).equals(other._get_axis(a))
  1135. for a in self._AXIS_ORDERS)
  1136. def equals(self, other):
  1137. """
  1138. Test whether two objects contain the same elements.
  1139. This function allows two Series or DataFrames to be compared against
  1140. each other to see if they have the same shape and elements. NaNs in
  1141. the same location are considered equal. The column headers do not
  1142. need to have the same type, but the elements within the columns must
  1143. be the same dtype.
  1144. Parameters
  1145. ----------
  1146. other : Series or DataFrame
  1147. The other Series or DataFrame to be compared with the first.
  1148. Returns
  1149. -------
  1150. bool
  1151. True if all elements are the same in both objects, False
  1152. otherwise.
  1153. See Also
  1154. --------
  1155. Series.eq : Compare two Series objects of the same length
  1156. and return a Series where each element is True if the element
  1157. in each Series is equal, False otherwise.
  1158. DataFrame.eq : Compare two DataFrame objects of the same shape and
  1159. return a DataFrame where each element is True if the respective
  1160. element in each DataFrame is equal, False otherwise.
  1161. assert_series_equal : Return True if left and right Series are equal,
  1162. False otherwise.
  1163. assert_frame_equal : Return True if left and right DataFrames are
  1164. equal, False otherwise.
  1165. numpy.array_equal : Return True if two arrays have the same shape
  1166. and elements, False otherwise.
  1167. Notes
  1168. -----
  1169. This function requires that the elements have the same dtype as their
  1170. respective elements in the other Series or DataFrame. However, the
  1171. column labels do not need to have the same type, as long as they are
  1172. still considered equal.
  1173. Examples
  1174. --------
  1175. >>> df = pd.DataFrame({1: [10], 2: [20]})
  1176. >>> df
  1177. 1 2
  1178. 0 10 20
  1179. DataFrames df and exactly_equal have the same types and values for
  1180. their elements and column labels, which will return True.
  1181. >>> exactly_equal = pd.DataFrame({1: [10], 2: [20]})
  1182. >>> exactly_equal
  1183. 1 2
  1184. 0 10 20
  1185. >>> df.equals(exactly_equal)
  1186. True
  1187. DataFrames df and different_column_type have the same element
  1188. types and values, but have different types for the column labels,
  1189. which will still return True.
  1190. >>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})
  1191. >>> different_column_type
  1192. 1.0 2.0
  1193. 0 10 20
  1194. >>> df.equals(different_column_type)
  1195. True
  1196. DataFrames df and different_data_type have different types for the
  1197. same values for their elements, and will return False even though
  1198. their column labels are the same values and types.
  1199. >>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})
  1200. >>> different_data_type
  1201. 1 2
  1202. 0 10.0 20.0
  1203. >>> df.equals(different_data_type)
  1204. False
  1205. """
  1206. if not isinstance(other, self._constructor):
  1207. return False
  1208. return self._data.equals(other._data)
  1209. # -------------------------------------------------------------------------
  1210. # Unary Methods
  1211. def __neg__(self):
  1212. values = com.values_from_object(self)
  1213. if is_bool_dtype(values):
  1214. arr = operator.inv(values)
  1215. elif (is_numeric_dtype(values) or is_timedelta64_dtype(values)
  1216. or is_object_dtype(values)):
  1217. arr = operator.neg(values)
  1218. else:
  1219. raise TypeError("Unary negative expects numeric dtype, not {}"
  1220. .format(values.dtype))
  1221. return self.__array_wrap__(arr)
  1222. def __pos__(self):
  1223. values = com.values_from_object(self)
  1224. if (is_bool_dtype(values) or is_period_arraylike(values)):
  1225. arr = values
  1226. elif (is_numeric_dtype(values) or is_timedelta64_dtype(values)
  1227. or is_object_dtype(values)):
  1228. arr = operator.pos(values)
  1229. else:
  1230. raise TypeError("Unary plus expects numeric dtype, not {}"
  1231. .format(values.dtype))
  1232. return self.__array_wrap__(arr)
  1233. def __invert__(self):
  1234. try:
  1235. arr = operator.inv(com.values_from_object(self))
  1236. return self.__array_wrap__(arr)
  1237. except Exception:
  1238. # inv fails with 0 len
  1239. if not np.prod(self.shape):
  1240. return self
  1241. raise
  1242. def __nonzero__(self):
  1243. raise ValueError("The truth value of a {0} is ambiguous. "
  1244. "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
  1245. .format(self.__class__.__name__))
  1246. __bool__ = __nonzero__
  1247. def bool(self):
  1248. """
  1249. Return the bool of a single element PandasObject.
  1250. This must be a boolean scalar value, either True or False. Raise a
  1251. ValueError if the PandasObject does not have exactly 1 element, or that
  1252. element is not boolean
  1253. """
  1254. v = self.squeeze()
  1255. if isinstance(v, (bool, np.bool_)):
  1256. return bool(v)
  1257. elif is_scalar(v):
  1258. raise ValueError("bool cannot act on a non-boolean single element "
  1259. "{0}".format(self.__class__.__name__))
  1260. self.__nonzero__()
  1261. def __abs__(self):
  1262. return self.abs()
  1263. def __round__(self, decimals=0):
  1264. return self.round(decimals)
  1265. # -------------------------------------------------------------------------
  1266. # Label or Level Combination Helpers
  1267. #
  1268. # A collection of helper methods for DataFrame/Series operations that
  1269. # accept a combination of column/index labels and levels. All such
  1270. # operations should utilize/extend these methods when possible so that we
  1271. # have consistent precedence and validation logic throughout the library.
  1272. def _is_level_reference(self, key, axis=0):
  1273. """
  1274. Test whether a key is a level reference for a given axis.
  1275. To be considered a level reference, `key` must be a string that:
  1276. - (axis=0): Matches the name of an index level and does NOT match
  1277. a column label.
  1278. - (axis=1): Matches the name of a column level and does NOT match
  1279. an index label.
  1280. Parameters
  1281. ----------
  1282. key : str
  1283. Potential level name for the given axis
  1284. axis : int, default 0
  1285. Axis that levels are associated with (0 for index, 1 for columns)
  1286. Returns
  1287. -------
  1288. is_level : bool
  1289. """
  1290. axis = self._get_axis_number(axis)
  1291. if self.ndim > 2:
  1292. raise NotImplementedError(
  1293. "_is_level_reference is not implemented for {type}"
  1294. .format(type=type(self)))
  1295. return (key is not None and
  1296. is_hashable(key) and
  1297. key in self.axes[axis].names and
  1298. not self._is_label_reference(key, axis=axis))
  1299. def _is_label_reference(self, key, axis=0):
  1300. """
  1301. Test whether a key is a label reference for a given axis.
  1302. To be considered a label reference, `key` must be a string that:
  1303. - (axis=0): Matches a column label
  1304. - (axis=1): Matches an index label
  1305. Parameters
  1306. ----------
  1307. key: str
  1308. Potential label name
  1309. axis: int, default 0
  1310. Axis perpendicular to the axis that labels are associated with
  1311. (0 means search for column labels, 1 means search for index labels)
  1312. Returns
  1313. -------
  1314. is_label: bool
  1315. """
  1316. if self.ndim > 2:
  1317. raise NotImplementedError(
  1318. "_is_label_reference is not implemented for {type}"
  1319. .format(type=type(self)))
  1320. axis = self._get_axis_number(axis)
  1321. other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis)
  1322. return (key is not None and
  1323. is_hashable(key) and
  1324. any(key in self.axes[ax] for ax in other_axes))
  1325. def _is_label_or_level_reference(self, key, axis=0):
  1326. """
  1327. Test whether a key is a label or level reference for a given axis.
  1328. To be considered either a label or a level reference, `key` must be a
  1329. string that:
  1330. - (axis=0): Matches a column label or an index level
  1331. - (axis=1): Matches an index label or a column level
  1332. Parameters
  1333. ----------
  1334. key: str
  1335. Potential label or level name
  1336. axis: int, default 0
  1337. Axis that levels are associated with (0 for index, 1 for columns)
  1338. Returns
  1339. -------
  1340. is_label_or_level: bool
  1341. """
  1342. if self.ndim > 2:
  1343. raise NotImplementedError(
  1344. "_is_label_or_level_reference is not implemented for {type}"
  1345. .format(type=type(self)))
  1346. return (self._is_level_reference(key, axis=axis) or
  1347. self._is_label_reference(key, axis=axis))
  1348. def _check_label_or_level_ambiguity(self, key, axis=0):
  1349. """
  1350. Check whether `key` is ambiguous.
  1351. By ambiguous, we mean that it matches both a level of the input
  1352. `axis` and a label of the other axis.
  1353. Parameters
  1354. ----------
  1355. key: str or object
  1356. label or level name
  1357. axis: int, default 0
  1358. Axis that levels are associated with (0 for index, 1 for columns)
  1359. Raises
  1360. ------
  1361. ValueError: `key` is ambiguous
  1362. """
  1363. if self.ndim > 2:
  1364. raise NotImplementedError(
  1365. "_check_label_or_level_ambiguity is not implemented for {type}"
  1366. .format(type=type(self)))
  1367. axis = self._get_axis_number(axis)
  1368. other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis)
  1369. if (key is not None and
  1370. is_hashable(key) and
  1371. key in self.axes[axis].names and
  1372. any(key in self.axes[ax] for ax in other_axes)):
  1373. # Build an informative and grammatical warning
  1374. level_article, level_type = (('an', 'index')
  1375. if axis == 0 else
  1376. ('a', 'column'))
  1377. label_article, label_type = (('a', 'column')
  1378. if axis == 0 else
  1379. ('an', 'index'))
  1380. msg = ("'{key}' is both {level_article} {level_type} level and "
  1381. "{label_article} {label_type} label, which is ambiguous."
  1382. ).format(key=key,
  1383. level_article=level_article,
  1384. level_type=level_type,
  1385. label_article=label_article,
  1386. label_type=label_type)
  1387. raise ValueError(msg)
  1388. def _get_label_or_level_values(self, key, axis=0):
  1389. """
  1390. Return a 1-D array of values associated with `key`, a label or level
  1391. from the given `axis`.
  1392. Retrieval logic:
  1393. - (axis=0): Return column values if `key` matches a column label.
  1394. Otherwise return index level values if `key` matches an index
  1395. level.
  1396. - (axis=1): Return row values if `key` matches an index label.
  1397. Otherwise return column level values if 'key' matches a column
  1398. level
  1399. Parameters
  1400. ----------
  1401. key: str
  1402. Label or level name.
  1403. axis: int, default 0
  1404. Axis that levels are associated with (0 for index, 1 for columns)
  1405. Returns
  1406. -------
  1407. values: np.ndarray
  1408. Raises
  1409. ------
  1410. KeyError
  1411. if `key` matches neither a label nor a level
  1412. ValueError
  1413. if `key` matches multiple labels
  1414. FutureWarning
  1415. if `key` is ambiguous. This will become an ambiguity error in a
  1416. future version
  1417. """
  1418. if self.ndim > 2:
  1419. raise NotImplementedError(
  1420. "_get_label_or_level_values is not implemented for {type}"
  1421. .format(type=type(self)))
  1422. axis = self._get_axis_number(axis)
  1423. other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis]
  1424. if self._is_label_reference(key, axis=axis):
  1425. self._check_label_or_level_ambiguity(key, axis=axis)
  1426. values = self.xs(key, axis=other_axes[0])._values
  1427. elif self._is_level_reference(key, axis=axis):
  1428. values = self.axes[axis].get_level_values(key)._values
  1429. else:
  1430. raise KeyError(key)
  1431. # Check for duplicates
  1432. if values.ndim > 1:
  1433. if other_axes and isinstance(
  1434. self._get_axis(other_axes[0]), MultiIndex):
  1435. multi_message = ('\n'
  1436. 'For a multi-index, the label must be a '
  1437. 'tuple with elements corresponding to '
  1438. 'each level.')
  1439. else:
  1440. multi_message = ''
  1441. label_axis_name = 'column' if axis == 0 else 'index'
  1442. raise ValueError(("The {label_axis_name} label '{key}' "
  1443. "is not unique.{multi_message}")
  1444. .format(key=key,
  1445. label_axis_name=label_axis_name,
  1446. multi_message=multi_message))
  1447. return values
  1448. def _drop_labels_or_levels(self, keys, axis=0):
  1449. """
  1450. Drop labels and/or levels for the given `axis`.
  1451. For each key in `keys`:
  1452. - (axis=0): If key matches a column label then drop the column.
  1453. Otherwise if key matches an index level then drop the level.
  1454. - (axis=1): If key matches an index label then drop the row.
  1455. Otherwise if key matches a column level then drop the level.
  1456. Parameters
  1457. ----------
  1458. keys: str or list of str
  1459. labels or levels to drop
  1460. axis: int, default 0
  1461. Axis that levels are associated with (0 for index, 1 for columns)
  1462. Returns
  1463. -------
  1464. dropped: DataFrame
  1465. Raises
  1466. ------
  1467. ValueError
  1468. if any `keys` match neither a label nor a level
  1469. """
  1470. if self.ndim > 2:
  1471. raise NotImplementedError(
  1472. "_drop_labels_or_levels is not implemented for {type}"
  1473. .format(type=type(self)))
  1474. axis = self._get_axis_number(axis)
  1475. # Validate keys
  1476. keys = com.maybe_make_list(keys)
  1477. invalid_keys = [k for k in keys if not
  1478. self._is_label_or_level_reference(k, axis=axis)]
  1479. if invalid_keys:
  1480. raise ValueError(("The following keys are not valid labels or "
  1481. "levels for axis {axis}: {invalid_keys}")
  1482. .format(axis=axis,
  1483. invalid_keys=invalid_keys))
  1484. # Compute levels and labels to drop
  1485. levels_to_drop = [k for k in keys
  1486. if self._is_level_reference(k, axis=axis)]
  1487. labels_to_drop = [k for k in keys
  1488. if not self._is_level_reference(k, axis=axis)]
  1489. # Perform copy upfront and then use inplace operations below.
  1490. # This ensures that we always perform exactly one copy.
  1491. # ``copy`` and/or ``inplace`` options could be added in the future.
  1492. dropped = self.copy()
  1493. if axis == 0:
  1494. # Handle dropping index levels
  1495. if levels_to_drop:
  1496. dropped.reset_index(levels_to_drop, drop=True, inplace=True)
  1497. # Handle dropping columns labels
  1498. if labels_to_drop:
  1499. dropped.drop(labels_to_drop, axis=1, inplace=True)
  1500. else:
  1501. # Handle dropping column levels
  1502. if levels_to_drop:
  1503. if isinstance(dropped.columns, MultiIndex):
  1504. # Drop the specified levels from the MultiIndex
  1505. dropped.columns = dropped.columns.droplevel(levels_to_drop)
  1506. else:
  1507. # Drop the last level of Index by replacing with
  1508. # a RangeIndex
  1509. dropped.columns = RangeIndex(dropped.columns.size)
  1510. # Handle dropping index labels
  1511. if labels_to_drop:
  1512. dropped.drop(labels_to_drop, axis=0, inplace=True)
  1513. return dropped
  1514. # ----------------------------------------------------------------------
  1515. # Iteration
  1516. def __hash__(self):
  1517. raise TypeError('{0!r} objects are mutable, thus they cannot be'
  1518. ' hashed'.format(self.__class__.__name__))
  1519. def __iter__(self):
  1520. """Iterate over info axis"""
  1521. return iter(self._info_axis)
  1522. # can we get a better explanation of this?
  1523. def keys(self):
  1524. """Get the 'info axis' (see Indexing for more)
  1525. This is index for Series, columns for DataFrame and major_axis for
  1526. Panel.
  1527. """
  1528. return self._info_axis
  1529. def iteritems(self):
  1530. """Iterate over (label, values) on info axis
  1531. This is index for Series, columns for DataFrame, major_axis for Panel,
  1532. and so on.
  1533. """
  1534. for h in self._info_axis:
  1535. yield h, self[h]
  1536. def __len__(self):
  1537. """Returns length of info axis"""
  1538. return len(self._info_axis)
  1539. def __contains__(self, key):
  1540. """True if the key is in the info axis"""
  1541. return key in self._info_axis
  1542. @property
  1543. def empty(self):
  1544. """
  1545. Indicator whether DataFrame is empty.
  1546. True if DataFrame is entirely empty (no items), meaning any of the
  1547. axes are of length 0.
  1548. Returns
  1549. -------
  1550. bool
  1551. If DataFrame is empty, return True, if not return False.
  1552. See Also
  1553. --------
  1554. Series.dropna
  1555. DataFrame.dropna
  1556. Notes
  1557. -----
  1558. If DataFrame contains only NaNs, it is still not considered empty. See
  1559. the example below.
  1560. Examples
  1561. --------
  1562. An example of an actual empty DataFrame. Notice the index is empty:
  1563. >>> df_empty = pd.DataFrame({'A' : []})
  1564. >>> df_empty
  1565. Empty DataFrame
  1566. Columns: [A]
  1567. Index: []
  1568. >>> df_empty.empty
  1569. True
  1570. If we only have NaNs in our DataFrame, it is not considered empty! We
  1571. will need to drop the NaNs to make the DataFrame empty:
  1572. >>> df = pd.DataFrame({'A' : [np.nan]})
  1573. >>> df
  1574. A
  1575. 0 NaN
  1576. >>> df.empty
  1577. False
  1578. >>> df.dropna().empty
  1579. True
  1580. """
  1581. return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS)
  1582. # ----------------------------------------------------------------------
  1583. # Array Interface
  1584. # This is also set in IndexOpsMixin
  1585. # GH#23114 Ensure ndarray.__op__(DataFrame) returns NotImplemented
  1586. __array_priority__ = 1000
  1587. def __array__(self, dtype=None):
  1588. return com.values_from_object(self)
  1589. def __array_wrap__(self, result, context=None):
  1590. d = self._construct_axes_dict(self._AXIS_ORDERS, copy=False)
  1591. return self._constructor(result, **d).__finalize__(self)
  1592. # ideally we would define this to avoid the getattr checks, but
  1593. # is slower
  1594. # @property
  1595. # def __array_interface__(self):
  1596. # """ provide numpy array interface method """
  1597. # values = self.values
  1598. # return dict(typestr=values.dtype.str,shape=values.shape,data=values)
  1599. def to_dense(self):
  1600. """
  1601. Return dense representation of NDFrame (as opposed to sparse).
  1602. """
  1603. # compat
  1604. return self
  1605. # ----------------------------------------------------------------------
  1606. # Picklability
  1607. def __getstate__(self):
  1608. meta = {k: getattr(self, k, None) for k in self._metadata}
  1609. return dict(_data=self._data, _typ=self._typ, _metadata=self._metadata,
  1610. **meta)
  1611. def __setstate__(self, state):
  1612. if isinstance(state, BlockManager):
  1613. self._data = state
  1614. elif isinstance(state, dict):
  1615. typ = state.get('_typ')
  1616. if typ is not None:
  1617. # set in the order of internal names
  1618. # to avoid definitional recursion
  1619. # e.g. say fill_value needing _data to be
  1620. # defined
  1621. meta = set(self._internal_names + self._metadata)
  1622. for k in list(meta):
  1623. if k in state:
  1624. v = state[k]
  1625. object.__setattr__(self, k, v)
  1626. for k, v in state.items():
  1627. if k not in meta:
  1628. object.__setattr__(self, k, v)
  1629. else:
  1630. self._unpickle_series_compat(state)
  1631. elif isinstance(state[0], dict):
  1632. if len(state) == 5:
  1633. self._unpickle_sparse_frame_compat(state)
  1634. else:
  1635. self._unpickle_frame_compat(state)
  1636. elif len(state) == 4:
  1637. self._unpickle_panel_compat(state)
  1638. elif len(state) == 2:
  1639. self._unpickle_series_compat(state)
  1640. else: # pragma: no cover
  1641. # old pickling format, for compatibility
  1642. self._unpickle_matrix_compat(state)
  1643. self._item_cache = {}
  1644. # ----------------------------------------------------------------------
  1645. # Rendering Methods
  1646. def __unicode__(self):
  1647. # unicode representation based upon iterating over self
  1648. # (since, by definition, `PandasContainers` are iterable)
  1649. prepr = '[%s]' % ','.join(map(pprint_thing, self))
  1650. return '%s(%s)' % (self.__class__.__name__, prepr)
  1651. def _repr_latex_(self):
  1652. """
  1653. Returns a LaTeX representation for a particular object.
  1654. Mainly for use with nbconvert (jupyter notebook conversion to pdf).
  1655. """
  1656. if config.get_option('display.latex.repr'):
  1657. return self.to_latex()
  1658. else:
  1659. return None
  1660. def _repr_data_resource_(self):
  1661. """
  1662. Not a real Jupyter special repr method, but we use the same
  1663. naming convention.
  1664. """
  1665. if config.get_option("display.html.table_schema"):
  1666. data = self.head(config.get_option('display.max_rows'))
  1667. payload = json.loads(data.to_json(orient='table'),
  1668. object_pairs_hook=collections.OrderedDict)
  1669. return payload
  1670. # ----------------------------------------------------------------------
  1671. # I/O Methods
  1672. _shared_docs['to_excel'] = """
  1673. Write %(klass)s to an Excel sheet.
  1674. To write a single %(klass)s to an Excel .xlsx file it is only necessary to
  1675. specify a target file name. To write to multiple sheets it is necessary to
  1676. create an `ExcelWriter` object with a target file name, and specify a sheet
  1677. in the file to write to.
  1678. Multiple sheets may be written to by specifying unique `sheet_name`.
  1679. With all data written to the file it is necessary to save the changes.
  1680. Note that creating an `ExcelWriter` object with a file name that already
  1681. exists will result in the contents of the existing file being erased.
  1682. Parameters
  1683. ----------
  1684. excel_writer : str or ExcelWriter object
  1685. File path or existing ExcelWriter.
  1686. sheet_name : str, default 'Sheet1'
  1687. Name of sheet which will contain DataFrame.
  1688. na_rep : str, default ''
  1689. Missing data representation.
  1690. float_format : str, optional
  1691. Format string for floating point numbers. For example
  1692. ``float_format="%%.2f"`` will format 0.1234 to 0.12.
  1693. columns : sequence or list of str, optional
  1694. Columns to write.
  1695. header : bool or list of str, default True
  1696. Write out the column names. If a list of string is given it is
  1697. assumed to be aliases for the column names.
  1698. index : bool, default True
  1699. Write row names (index).
  1700. index_label : str or sequence, optional
  1701. Column label for index column(s) if desired. If not specified, and
  1702. `header` and `index` are True, then the index names are used. A
  1703. sequence should be given if the DataFrame uses MultiIndex.
  1704. startrow : int, default 0
  1705. Upper left cell row to dump data frame.
  1706. startcol : int, default 0
  1707. Upper left cell column to dump data frame.
  1708. engine : str, optional
  1709. Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this
  1710. via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and
  1711. ``io.excel.xlsm.writer``.
  1712. merge_cells : bool, default True
  1713. Write MultiIndex and Hierarchical Rows as merged cells.
  1714. encoding : str, optional
  1715. Encoding of the resulting excel file. Only necessary for xlwt,
  1716. other writers support unicode natively.
  1717. inf_rep : str, default 'inf'
  1718. Representation for infinity (there is no native representation for
  1719. infinity in Excel).
  1720. verbose : bool, default True
  1721. Display more information in the error logs.
  1722. freeze_panes : tuple of int (length 2), optional
  1723. Specifies the one-based bottommost row and rightmost column that
  1724. is to be frozen.
  1725. .. versionadded:: 0.20.0.
  1726. See Also
  1727. --------
  1728. to_csv : Write DataFrame to a comma-separated values (csv) file.
  1729. ExcelWriter : Class for writing DataFrame objects into excel sheets.
  1730. read_excel : Read an Excel file into a pandas DataFrame.
  1731. read_csv : Read a comma-separated values (csv) file into DataFrame.
  1732. Notes
  1733. -----
  1734. For compatibility with :meth:`~DataFrame.to_csv`,
  1735. to_excel serializes lists and dicts to strings before writing.
  1736. Once a workbook has been saved it is not possible write further data
  1737. without rewriting the whole workbook.
  1738. Examples
  1739. --------
  1740. Create, write to and save a workbook:
  1741. >>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],
  1742. ... index=['row 1', 'row 2'],
  1743. ... columns=['col 1', 'col 2'])
  1744. >>> df1.to_excel("output.xlsx") # doctest: +SKIP
  1745. To specify the sheet name:
  1746. >>> df1.to_excel("output.xlsx",
  1747. ... sheet_name='Sheet_name_1') # doctest: +SKIP
  1748. If you wish to write to more than one sheet in the workbook, it is
  1749. necessary to specify an ExcelWriter object:
  1750. >>> df2 = df1.copy()
  1751. >>> with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP
  1752. ... df1.to_excel(writer, sheet_name='Sheet_name_1')
  1753. ... df2.to_excel(writer, sheet_name='Sheet_name_2')
  1754. To set the library that is used to write the Excel file,
  1755. you can pass the `engine` keyword (the default engine is
  1756. automatically chosen depending on the file extension):
  1757. >>> df1.to_excel('output1.xlsx', engine='xlsxwriter') # doctest: +SKIP
  1758. """
  1759. @Appender(_shared_docs["to_excel"] % dict(klass="object"))
  1760. def to_excel(self, excel_writer, sheet_name="Sheet1", na_rep="",
  1761. float_format=None, columns=None, header=True, index=True,
  1762. index_label=None, startrow=0, startcol=0, engine=None,
  1763. merge_cells=True, encoding=None, inf_rep="inf", verbose=True,
  1764. freeze_panes=None):
  1765. df = self if isinstance(self, ABCDataFrame) else self.to_frame()
  1766. from pandas.io.formats.excel import ExcelFormatter
  1767. formatter = ExcelFormatter(df, na_rep=na_rep, cols=columns,
  1768. header=header,
  1769. float_format=float_format, index=index,
  1770. index_label=index_label,
  1771. merge_cells=merge_cells,
  1772. inf_rep=inf_rep)
  1773. formatter.write(excel_writer, sheet_name=sheet_name, startrow=startrow,
  1774. startcol=startcol, freeze_panes=freeze_panes,
  1775. engine=engine)
  1776. def to_json(self, path_or_buf=None, orient=None, date_format=None,
  1777. double_precision=10, force_ascii=True, date_unit='ms',
  1778. default_handler=None, lines=False, compression='infer',
  1779. index=True):
  1780. """
  1781. Convert the object to a JSON string.
  1782. Note NaN's and None will be converted to null and datetime objects
  1783. will be converted to UNIX timestamps.
  1784. Parameters
  1785. ----------
  1786. path_or_buf : string or file handle, optional
  1787. File path or object. If not specified, the result is returned as
  1788. a string.
  1789. orient : string
  1790. Indication of expected JSON string format.
  1791. * Series
  1792. - default is 'index'
  1793. - allowed values are: {'split','records','index','table'}
  1794. * DataFrame
  1795. - default is 'columns'
  1796. - allowed values are:
  1797. {'split','records','index','columns','values','table'}
  1798. * The format of the JSON string
  1799. - 'split' : dict like {'index' -> [index],
  1800. 'columns' -> [columns], 'data' -> [values]}
  1801. - 'records' : list like
  1802. [{column -> value}, ... , {column -> value}]
  1803. - 'index' : dict like {index -> {column -> value}}
  1804. - 'columns' : dict like {column -> {index -> value}}
  1805. - 'values' : just the values array
  1806. - 'table' : dict like {'schema': {schema}, 'data': {data}}
  1807. describing the data, and the data component is
  1808. like ``orient='records'``.
  1809. .. versionchanged:: 0.20.0
  1810. date_format : {None, 'epoch', 'iso'}
  1811. Type of date conversion. 'epoch' = epoch milliseconds,
  1812. 'iso' = ISO8601. The default depends on the `orient`. For
  1813. ``orient='table'``, the default is 'iso'. For all other orients,
  1814. the default is 'epoch'.
  1815. double_precision : int, default 10
  1816. The number of decimal places to use when encoding
  1817. floating point values.
  1818. force_ascii : bool, default True
  1819. Force encoded string to be ASCII.
  1820. date_unit : string, default 'ms' (milliseconds)
  1821. The time unit to encode to, governs timestamp and ISO8601
  1822. precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,
  1823. microsecond, and nanosecond respectively.
  1824. default_handler : callable, default None
  1825. Handler to call if object cannot otherwise be converted to a
  1826. suitable format for JSON. Should receive a single argument which is
  1827. the object to convert and return a serialisable object.
  1828. lines : bool, default False
  1829. If 'orient' is 'records' write out line delimited json format. Will
  1830. throw ValueError if incorrect 'orient' since others are not list
  1831. like.
  1832. .. versionadded:: 0.19.0
  1833. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}
  1834. A string representing the compression to use in the output file,
  1835. only used when the first argument is a filename. By default, the
  1836. compression is inferred from the filename.
  1837. .. versionadded:: 0.21.0
  1838. .. versionchanged:: 0.24.0
  1839. 'infer' option added and set to default
  1840. index : bool, default True
  1841. Whether to include the index values in the JSON string. Not
  1842. including the index (``index=False``) is only supported when
  1843. orient is 'split' or 'table'.
  1844. .. versionadded:: 0.23.0
  1845. See Also
  1846. --------
  1847. read_json
  1848. Examples
  1849. --------
  1850. >>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],
  1851. ... index=['row 1', 'row 2'],
  1852. ... columns=['col 1', 'col 2'])
  1853. >>> df.to_json(orient='split')
  1854. '{"columns":["col 1","col 2"],
  1855. "index":["row 1","row 2"],
  1856. "data":[["a","b"],["c","d"]]}'
  1857. Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
  1858. Note that index labels are not preserved with this encoding.
  1859. >>> df.to_json(orient='records')
  1860. '[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
  1861. Encoding/decoding a Dataframe using ``'index'`` formatted JSON:
  1862. >>> df.to_json(orient='index')
  1863. '{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
  1864. Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:
  1865. >>> df.to_json(orient='columns')
  1866. '{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}'
  1867. Encoding/decoding a Dataframe using ``'values'`` formatted JSON:
  1868. >>> df.to_json(orient='values')
  1869. '[["a","b"],["c","d"]]'
  1870. Encoding with Table Schema
  1871. >>> df.to_json(orient='table')
  1872. '{"schema": {"fields": [{"name": "index", "type": "string"},
  1873. {"name": "col 1", "type": "string"},
  1874. {"name": "col 2", "type": "string"}],
  1875. "primaryKey": "index",
  1876. "pandas_version": "0.20.0"},
  1877. "data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
  1878. {"index": "row 2", "col 1": "c", "col 2": "d"}]}'
  1879. """
  1880. from pandas.io import json
  1881. if date_format is None and orient == 'table':
  1882. date_format = 'iso'
  1883. elif date_format is None:
  1884. date_format = 'epoch'
  1885. return json.to_json(path_or_buf=path_or_buf, obj=self, orient=orient,
  1886. date_format=date_format,
  1887. double_precision=double_precision,
  1888. force_ascii=force_ascii, date_unit=date_unit,
  1889. default_handler=default_handler,
  1890. lines=lines, compression=compression,
  1891. index=index)
  1892. def to_hdf(self, path_or_buf, key, **kwargs):
  1893. """
  1894. Write the contained data to an HDF5 file using HDFStore.
  1895. Hierarchical Data Format (HDF) is self-describing, allowing an
  1896. application to interpret the structure and contents of a file with
  1897. no outside information. One HDF file can hold a mix of related objects
  1898. which can be accessed as a group or as individual objects.
  1899. In order to add another DataFrame or Series to an existing HDF file
  1900. please use append mode and a different a key.
  1901. For more information see the :ref:`user guide <io.hdf5>`.
  1902. Parameters
  1903. ----------
  1904. path_or_buf : str or pandas.HDFStore
  1905. File path or HDFStore object.
  1906. key : str
  1907. Identifier for the group in the store.
  1908. mode : {'a', 'w', 'r+'}, default 'a'
  1909. Mode to open file:
  1910. - 'w': write, a new file is created (an existing file with
  1911. the same name would be deleted).
  1912. - 'a': append, an existing file is opened for reading and
  1913. writing, and if the file does not exist it is created.
  1914. - 'r+': similar to 'a', but the file must already exist.
  1915. format : {'fixed', 'table'}, default 'fixed'
  1916. Possible values:
  1917. - 'fixed': Fixed format. Fast writing/reading. Not-appendable,
  1918. nor searchable.
  1919. - 'table': Table format. Write as a PyTables Table structure
  1920. which may perform worse but allow more flexible operations
  1921. like searching / selecting subsets of the data.
  1922. append : bool, default False
  1923. For Table formats, append the input data to the existing.
  1924. data_columns : list of columns or True, optional
  1925. List of columns to create as indexed data columns for on-disk
  1926. queries, or True to use all columns. By default only the axes
  1927. of the object are indexed. See :ref:`io.hdf5-query-data-columns`.
  1928. Applicable only to format='table'.
  1929. complevel : {0-9}, optional
  1930. Specifies a compression level for data.
  1931. A value of 0 disables compression.
  1932. complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
  1933. Specifies the compression library to be used.
  1934. As of v0.20.2 these additional compressors for Blosc are supported
  1935. (default if no compressor specified: 'blosc:blosclz'):
  1936. {'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
  1937. 'blosc:zlib', 'blosc:zstd'}.
  1938. Specifying a compression library which is not available issues
  1939. a ValueError.
  1940. fletcher32 : bool, default False
  1941. If applying compression use the fletcher32 checksum.
  1942. dropna : bool, default False
  1943. If true, ALL nan rows will not be written to store.
  1944. errors : str, default 'strict'
  1945. Specifies how encoding and decoding errors are to be handled.
  1946. See the errors argument for :func:`open` for a full list
  1947. of options.
  1948. See Also
  1949. --------
  1950. DataFrame.read_hdf : Read from HDF file.
  1951. DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
  1952. DataFrame.to_sql : Write to a sql table.
  1953. DataFrame.to_feather : Write out feather-format for DataFrames.
  1954. DataFrame.to_csv : Write out to a csv file.
  1955. Examples
  1956. --------
  1957. >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
  1958. ... index=['a', 'b', 'c'])
  1959. >>> df.to_hdf('data.h5', key='df', mode='w')
  1960. We can add another object to the same file:
  1961. >>> s = pd.Series([1, 2, 3, 4])
  1962. >>> s.to_hdf('data.h5', key='s')
  1963. Reading from HDF file:
  1964. >>> pd.read_hdf('data.h5', 'df')
  1965. A B
  1966. a 1 4
  1967. b 2 5
  1968. c 3 6
  1969. >>> pd.read_hdf('data.h5', 's')
  1970. 0 1
  1971. 1 2
  1972. 2 3
  1973. 3 4
  1974. dtype: int64
  1975. Deleting file with data:
  1976. >>> import os
  1977. >>> os.remove('data.h5')
  1978. """
  1979. from pandas.io import pytables
  1980. return pytables.to_hdf(path_or_buf, key, self, **kwargs)
  1981. def to_msgpack(self, path_or_buf=None, encoding='utf-8', **kwargs):
  1982. """
  1983. Serialize object to input file path using msgpack format.
  1984. THIS IS AN EXPERIMENTAL LIBRARY and the storage format
  1985. may not be stable until a future release.
  1986. Parameters
  1987. ----------
  1988. path : string File path, buffer-like, or None
  1989. if None, return generated string
  1990. append : bool whether to append to an existing msgpack
  1991. (default is False)
  1992. compress : type of compressor (zlib or blosc), default to None (no
  1993. compression)
  1994. """
  1995. from pandas.io import packers
  1996. return packers.to_msgpack(path_or_buf, self, encoding=encoding,
  1997. **kwargs)
  1998. def to_sql(self, name, con, schema=None, if_exists='fail', index=True,
  1999. index_label=None, chunksize=None, dtype=None, method=None):
  2000. """
  2001. Write records stored in a DataFrame to a SQL database.
  2002. Databases supported by SQLAlchemy [1]_ are supported. Tables can be
  2003. newly created, appended to, or overwritten.
  2004. Parameters
  2005. ----------
  2006. name : string
  2007. Name of SQL table.
  2008. con : sqlalchemy.engine.Engine or sqlite3.Connection
  2009. Using SQLAlchemy makes it possible to use any DB supported by that
  2010. library. Legacy support is provided for sqlite3.Connection objects.
  2011. schema : string, optional
  2012. Specify the schema (if database flavor supports this). If None, use
  2013. default schema.
  2014. if_exists : {'fail', 'replace', 'append'}, default 'fail'
  2015. How to behave if the table already exists.
  2016. * fail: Raise a ValueError.
  2017. * replace: Drop the table before inserting new values.
  2018. * append: Insert new values to the existing table.
  2019. index : bool, default True
  2020. Write DataFrame index as a column. Uses `index_label` as the column
  2021. name in the table.
  2022. index_label : string or sequence, default None
  2023. Column label for index column(s). If None is given (default) and
  2024. `index` is True, then the index names are used.
  2025. A sequence should be given if the DataFrame uses MultiIndex.
  2026. chunksize : int, optional
  2027. Rows will be written in batches of this size at a time. By default,
  2028. all rows will be written at once.
  2029. dtype : dict, optional
  2030. Specifying the datatype for columns. The keys should be the column
  2031. names and the values should be the SQLAlchemy types or strings for
  2032. the sqlite3 legacy mode.
  2033. method : {None, 'multi', callable}, default None
  2034. Controls the SQL insertion clause used:
  2035. * None : Uses standard SQL ``INSERT`` clause (one per row).
  2036. * 'multi': Pass multiple values in a single ``INSERT`` clause.
  2037. * callable with signature ``(pd_table, conn, keys, data_iter)``.
  2038. Details and a sample callable implementation can be found in the
  2039. section :ref:`insert method <io.sql.method>`.
  2040. .. versionadded:: 0.24.0
  2041. Raises
  2042. ------
  2043. ValueError
  2044. When the table already exists and `if_exists` is 'fail' (the
  2045. default).
  2046. See Also
  2047. --------
  2048. read_sql : Read a DataFrame from a table.
  2049. Notes
  2050. -----
  2051. Timezone aware datetime columns will be written as
  2052. ``Timestamp with timezone`` type with SQLAlchemy if supported by the
  2053. database. Otherwise, the datetimes will be stored as timezone unaware
  2054. timestamps local to the original timezone.
  2055. .. versionadded:: 0.24.0
  2056. References
  2057. ----------
  2058. .. [1] http://docs.sqlalchemy.org
  2059. .. [2] https://www.python.org/dev/peps/pep-0249/
  2060. Examples
  2061. --------
  2062. Create an in-memory SQLite database.
  2063. >>> from sqlalchemy import create_engine
  2064. >>> engine = create_engine('sqlite://', echo=False)
  2065. Create a table from scratch with 3 rows.
  2066. >>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
  2067. >>> df
  2068. name
  2069. 0 User 1
  2070. 1 User 2
  2071. 2 User 3
  2072. >>> df.to_sql('users', con=engine)
  2073. >>> engine.execute("SELECT * FROM users").fetchall()
  2074. [(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]
  2075. >>> df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
  2076. >>> df1.to_sql('users', con=engine, if_exists='append')
  2077. >>> engine.execute("SELECT * FROM users").fetchall()
  2078. [(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
  2079. (0, 'User 4'), (1, 'User 5')]
  2080. Overwrite the table with just ``df1``.
  2081. >>> df1.to_sql('users', con=engine, if_exists='replace',
  2082. ... index_label='id')
  2083. >>> engine.execute("SELECT * FROM users").fetchall()
  2084. [(0, 'User 4'), (1, 'User 5')]
  2085. Specify the dtype (especially useful for integers with missing values).
  2086. Notice that while pandas is forced to store the data as floating point,
  2087. the database supports nullable integers. When fetching the data with
  2088. Python, we get back integer scalars.
  2089. >>> df = pd.DataFrame({"A": [1, None, 2]})
  2090. >>> df
  2091. A
  2092. 0 1.0
  2093. 1 NaN
  2094. 2 2.0
  2095. >>> from sqlalchemy.types import Integer
  2096. >>> df.to_sql('integers', con=engine, index=False,
  2097. ... dtype={"A": Integer()})
  2098. >>> engine.execute("SELECT * FROM integers").fetchall()
  2099. [(1,), (None,), (2,)]
  2100. """
  2101. from pandas.io import sql
  2102. sql.to_sql(self, name, con, schema=schema, if_exists=if_exists,
  2103. index=index, index_label=index_label, chunksize=chunksize,
  2104. dtype=dtype, method=method)
  2105. def to_pickle(self, path, compression='infer',
  2106. protocol=pkl.HIGHEST_PROTOCOL):
  2107. """
  2108. Pickle (serialize) object to file.
  2109. Parameters
  2110. ----------
  2111. path : str
  2112. File path where the pickled object will be stored.
  2113. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, \
  2114. default 'infer'
  2115. A string representing the compression to use in the output file. By
  2116. default, infers from the file extension in specified path.
  2117. .. versionadded:: 0.20.0
  2118. protocol : int
  2119. Int which indicates which protocol should be used by the pickler,
  2120. default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible
  2121. values for this parameter depend on the version of Python. For
  2122. Python 2.x, possible values are 0, 1, 2. For Python>=3.0, 3 is a
  2123. valid value. For Python >= 3.4, 4 is a valid value. A negative
  2124. value for the protocol parameter is equivalent to setting its value
  2125. to HIGHEST_PROTOCOL.
  2126. .. [1] https://docs.python.org/3/library/pickle.html
  2127. .. versionadded:: 0.21.0
  2128. See Also
  2129. --------
  2130. read_pickle : Load pickled pandas object (or any object) from file.
  2131. DataFrame.to_hdf : Write DataFrame to an HDF5 file.
  2132. DataFrame.to_sql : Write DataFrame to a SQL database.
  2133. DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
  2134. Examples
  2135. --------
  2136. >>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)})
  2137. >>> original_df
  2138. foo bar
  2139. 0 0 5
  2140. 1 1 6
  2141. 2 2 7
  2142. 3 3 8
  2143. 4 4 9
  2144. >>> original_df.to_pickle("./dummy.pkl")
  2145. >>> unpickled_df = pd.read_pickle("./dummy.pkl")
  2146. >>> unpickled_df
  2147. foo bar
  2148. 0 0 5
  2149. 1 1 6
  2150. 2 2 7
  2151. 3 3 8
  2152. 4 4 9
  2153. >>> import os
  2154. >>> os.remove("./dummy.pkl")
  2155. """
  2156. from pandas.io.pickle import to_pickle
  2157. return to_pickle(self, path, compression=compression,
  2158. protocol=protocol)
  2159. def to_clipboard(self, excel=True, sep=None, **kwargs):
  2160. r"""
  2161. Copy object to the system clipboard.
  2162. Write a text representation of object to the system clipboard.
  2163. This can be pasted into Excel, for example.
  2164. Parameters
  2165. ----------
  2166. excel : bool, default True
  2167. - True, use the provided separator, writing in a csv format for
  2168. allowing easy pasting into excel.
  2169. - False, write a string representation of the object to the
  2170. clipboard.
  2171. sep : str, default ``'\t'``
  2172. Field delimiter.
  2173. **kwargs
  2174. These parameters will be passed to DataFrame.to_csv.
  2175. See Also
  2176. --------
  2177. DataFrame.to_csv : Write a DataFrame to a comma-separated values
  2178. (csv) file.
  2179. read_clipboard : Read text from clipboard and pass to read_table.
  2180. Notes
  2181. -----
  2182. Requirements for your platform.
  2183. - Linux : `xclip`, or `xsel` (with `gtk` or `PyQt4` modules)
  2184. - Windows : none
  2185. - OS X : none
  2186. Examples
  2187. --------
  2188. Copy the contents of a DataFrame to the clipboard.
  2189. >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])
  2190. >>> df.to_clipboard(sep=',')
  2191. ... # Wrote the following to the system clipboard:
  2192. ... # ,A,B,C
  2193. ... # 0,1,2,3
  2194. ... # 1,4,5,6
  2195. We can omit the the index by passing the keyword `index` and setting
  2196. it to false.
  2197. >>> df.to_clipboard(sep=',', index=False)
  2198. ... # Wrote the following to the system clipboard:
  2199. ... # A,B,C
  2200. ... # 1,2,3
  2201. ... # 4,5,6
  2202. """
  2203. from pandas.io import clipboards
  2204. clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)
  2205. def to_xarray(self):
  2206. """
  2207. Return an xarray object from the pandas object.
  2208. Returns
  2209. -------
  2210. xarray.DataArray or xarray.Dataset
  2211. Data in the pandas structure converted to Dataset if the object is
  2212. a DataFrame, or a DataArray if the object is a Series.
  2213. See Also
  2214. --------
  2215. DataFrame.to_hdf : Write DataFrame to an HDF5 file.
  2216. DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
  2217. Notes
  2218. -----
  2219. See the `xarray docs <http://xarray.pydata.org/en/stable/>`__
  2220. Examples
  2221. --------
  2222. >>> df = pd.DataFrame([('falcon', 'bird', 389.0, 2),
  2223. ... ('parrot', 'bird', 24.0, 2),
  2224. ... ('lion', 'mammal', 80.5, 4),
  2225. ... ('monkey', 'mammal', np.nan, 4)],
  2226. ... columns=['name', 'class', 'max_speed',
  2227. ... 'num_legs'])
  2228. >>> df
  2229. name class max_speed num_legs
  2230. 0 falcon bird 389.0 2
  2231. 1 parrot bird 24.0 2
  2232. 2 lion mammal 80.5 4
  2233. 3 monkey mammal NaN 4
  2234. >>> df.to_xarray()
  2235. <xarray.Dataset>
  2236. Dimensions: (index: 4)
  2237. Coordinates:
  2238. * index (index) int64 0 1 2 3
  2239. Data variables:
  2240. name (index) object 'falcon' 'parrot' 'lion' 'monkey'
  2241. class (index) object 'bird' 'bird' 'mammal' 'mammal'
  2242. max_speed (index) float64 389.0 24.0 80.5 nan
  2243. num_legs (index) int64 2 2 4 4
  2244. >>> df['max_speed'].to_xarray()
  2245. <xarray.DataArray 'max_speed' (index: 4)>
  2246. array([389. , 24. , 80.5, nan])
  2247. Coordinates:
  2248. * index (index) int64 0 1 2 3
  2249. >>> dates = pd.to_datetime(['2018-01-01', '2018-01-01',
  2250. ... '2018-01-02', '2018-01-02'])
  2251. >>> df_multiindex = pd.DataFrame({'date': dates,
  2252. ... 'animal': ['falcon', 'parrot', 'falcon',
  2253. ... 'parrot'],
  2254. ... 'speed': [350, 18, 361, 15]}).set_index(['date',
  2255. ... 'animal'])
  2256. >>> df_multiindex
  2257. speed
  2258. date animal
  2259. 2018-01-01 falcon 350
  2260. parrot 18
  2261. 2018-01-02 falcon 361
  2262. parrot 15
  2263. >>> df_multiindex.to_xarray()
  2264. <xarray.Dataset>
  2265. Dimensions: (animal: 2, date: 2)
  2266. Coordinates:
  2267. * date (date) datetime64[ns] 2018-01-01 2018-01-02
  2268. * animal (animal) object 'falcon' 'parrot'
  2269. Data variables:
  2270. speed (date, animal) int64 350 18 361 15
  2271. """
  2272. try:
  2273. import xarray
  2274. except ImportError:
  2275. # Give a nice error message
  2276. raise ImportError("the xarray library is not installed\n"
  2277. "you can install via conda\n"
  2278. "conda install xarray\n"
  2279. "or via pip\n"
  2280. "pip install xarray\n")
  2281. if self.ndim == 1:
  2282. return xarray.DataArray.from_series(self)
  2283. elif self.ndim == 2:
  2284. return xarray.Dataset.from_dataframe(self)
  2285. # > 2 dims
  2286. coords = [(a, self._get_axis(a)) for a in self._AXIS_ORDERS]
  2287. return xarray.DataArray(self,
  2288. coords=coords,
  2289. )
  2290. def to_latex(self, buf=None, columns=None, col_space=None, header=True,
  2291. index=True, na_rep='NaN', formatters=None, float_format=None,
  2292. sparsify=None, index_names=True, bold_rows=False,
  2293. column_format=None, longtable=None, escape=None,
  2294. encoding=None, decimal='.', multicolumn=None,
  2295. multicolumn_format=None, multirow=None):
  2296. r"""
  2297. Render an object to a LaTeX tabular environment table.
  2298. Render an object to a tabular environment table. You can splice
  2299. this into a LaTeX document. Requires \usepackage{booktabs}.
  2300. .. versionchanged:: 0.20.2
  2301. Added to Series
  2302. Parameters
  2303. ----------
  2304. buf : file descriptor or None
  2305. Buffer to write to. If None, the output is returned as a string.
  2306. columns : list of label, optional
  2307. The subset of columns to write. Writes all columns by default.
  2308. col_space : int, optional
  2309. The minimum width of each column.
  2310. header : bool or list of str, default True
  2311. Write out the column names. If a list of strings is given,
  2312. it is assumed to be aliases for the column names.
  2313. index : bool, default True
  2314. Write row names (index).
  2315. na_rep : str, default 'NaN'
  2316. Missing data representation.
  2317. formatters : list of functions or dict of {str: function}, optional
  2318. Formatter functions to apply to columns' elements by position or
  2319. name. The result of each function must be a unicode string.
  2320. List must be of length equal to the number of columns.
  2321. float_format : str, optional
  2322. Format string for floating point numbers.
  2323. sparsify : bool, optional
  2324. Set to False for a DataFrame with a hierarchical index to print
  2325. every multiindex key at each row. By default, the value will be
  2326. read from the config module.
  2327. index_names : bool, default True
  2328. Prints the names of the indexes.
  2329. bold_rows : bool, default False
  2330. Make the row labels bold in the output.
  2331. column_format : str, optional
  2332. The columns format as specified in `LaTeX table format
  2333. <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3
  2334. columns. By default, 'l' will be used for all columns except
  2335. columns of numbers, which default to 'r'.
  2336. longtable : bool, optional
  2337. By default, the value will be read from the pandas config
  2338. module. Use a longtable environment instead of tabular. Requires
  2339. adding a \usepackage{longtable} to your LaTeX preamble.
  2340. escape : bool, optional
  2341. By default, the value will be read from the pandas config
  2342. module. When set to False prevents from escaping latex special
  2343. characters in column names.
  2344. encoding : str, optional
  2345. A string representing the encoding to use in the output file,
  2346. defaults to 'ascii' on Python 2 and 'utf-8' on Python 3.
  2347. decimal : str, default '.'
  2348. Character recognized as decimal separator, e.g. ',' in Europe.
  2349. .. versionadded:: 0.18.0
  2350. multicolumn : bool, default True
  2351. Use \multicolumn to enhance MultiIndex columns.
  2352. The default will be read from the config module.
  2353. .. versionadded:: 0.20.0
  2354. multicolumn_format : str, default 'l'
  2355. The alignment for multicolumns, similar to `column_format`
  2356. The default will be read from the config module.
  2357. .. versionadded:: 0.20.0
  2358. multirow : bool, default False
  2359. Use \multirow to enhance MultiIndex rows. Requires adding a
  2360. \usepackage{multirow} to your LaTeX preamble. Will print
  2361. centered labels (instead of top-aligned) across the contained
  2362. rows, separating groups via clines. The default will be read
  2363. from the pandas config module.
  2364. .. versionadded:: 0.20.0
  2365. Returns
  2366. -------
  2367. str or None
  2368. If buf is None, returns the resulting LateX format as a
  2369. string. Otherwise returns None.
  2370. See Also
  2371. --------
  2372. DataFrame.to_string : Render a DataFrame to a console-friendly
  2373. tabular output.
  2374. DataFrame.to_html : Render a DataFrame as an HTML table.
  2375. Examples
  2376. --------
  2377. >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
  2378. ... 'mask': ['red', 'purple'],
  2379. ... 'weapon': ['sai', 'bo staff']})
  2380. >>> df.to_latex(index=False) # doctest: +NORMALIZE_WHITESPACE
  2381. '\\begin{tabular}{lll}\n\\toprule\n name & mask & weapon
  2382. \\\\\n\\midrule\n Raphael & red & sai \\\\\n Donatello &
  2383. purple & bo staff \\\\\n\\bottomrule\n\\end{tabular}\n'
  2384. """
  2385. # Get defaults from the pandas config
  2386. if self.ndim == 1:
  2387. self = self.to_frame()
  2388. if longtable is None:
  2389. longtable = config.get_option("display.latex.longtable")
  2390. if escape is None:
  2391. escape = config.get_option("display.latex.escape")
  2392. if multicolumn is None:
  2393. multicolumn = config.get_option("display.latex.multicolumn")
  2394. if multicolumn_format is None:
  2395. multicolumn_format = config.get_option(
  2396. "display.latex.multicolumn_format")
  2397. if multirow is None:
  2398. multirow = config.get_option("display.latex.multirow")
  2399. formatter = DataFrameFormatter(self, buf=buf, columns=columns,
  2400. col_space=col_space, na_rep=na_rep,
  2401. header=header, index=index,
  2402. formatters=formatters,
  2403. float_format=float_format,
  2404. bold_rows=bold_rows,
  2405. sparsify=sparsify,
  2406. index_names=index_names,
  2407. escape=escape, decimal=decimal)
  2408. formatter.to_latex(column_format=column_format, longtable=longtable,
  2409. encoding=encoding, multicolumn=multicolumn,
  2410. multicolumn_format=multicolumn_format,
  2411. multirow=multirow)
  2412. if buf is None:
  2413. return formatter.buf.getvalue()
  2414. def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
  2415. columns=None, header=True, index=True, index_label=None,
  2416. mode='w', encoding=None, compression='infer', quoting=None,
  2417. quotechar='"', line_terminator=None, chunksize=None,
  2418. tupleize_cols=None, date_format=None, doublequote=True,
  2419. escapechar=None, decimal='.'):
  2420. r"""
  2421. Write object to a comma-separated values (csv) file.
  2422. .. versionchanged:: 0.24.0
  2423. The order of arguments for Series was changed.
  2424. Parameters
  2425. ----------
  2426. path_or_buf : str or file handle, default None
  2427. File path or object, if None is provided the result is returned as
  2428. a string. If a file object is passed it should be opened with
  2429. `newline=''`, disabling universal newlines.
  2430. .. versionchanged:: 0.24.0
  2431. Was previously named "path" for Series.
  2432. sep : str, default ','
  2433. String of length 1. Field delimiter for the output file.
  2434. na_rep : str, default ''
  2435. Missing data representation.
  2436. float_format : str, default None
  2437. Format string for floating point numbers.
  2438. columns : sequence, optional
  2439. Columns to write.
  2440. header : bool or list of str, default True
  2441. Write out the column names. If a list of strings is given it is
  2442. assumed to be aliases for the column names.
  2443. .. versionchanged:: 0.24.0
  2444. Previously defaulted to False for Series.
  2445. index : bool, default True
  2446. Write row names (index).
  2447. index_label : str or sequence, or False, default None
  2448. Column label for index column(s) if desired. If None is given, and
  2449. `header` and `index` are True, then the index names are used. A
  2450. sequence should be given if the object uses MultiIndex. If
  2451. False do not print fields for index names. Use index_label=False
  2452. for easier importing in R.
  2453. mode : str
  2454. Python write mode, default 'w'.
  2455. encoding : str, optional
  2456. A string representing the encoding to use in the output file,
  2457. defaults to 'ascii' on Python 2 and 'utf-8' on Python 3.
  2458. compression : str, default 'infer'
  2459. Compression mode among the following possible values: {'infer',
  2460. 'gzip', 'bz2', 'zip', 'xz', None}. If 'infer' and `path_or_buf`
  2461. is path-like, then detect compression from the following
  2462. extensions: '.gz', '.bz2', '.zip' or '.xz'. (otherwise no
  2463. compression).
  2464. .. versionchanged:: 0.24.0
  2465. 'infer' option added and set to default.
  2466. quoting : optional constant from csv module
  2467. Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format`
  2468. then floats are converted to strings and thus csv.QUOTE_NONNUMERIC
  2469. will treat them as non-numeric.
  2470. quotechar : str, default '\"'
  2471. String of length 1. Character used to quote fields.
  2472. line_terminator : str, optional
  2473. The newline character or character sequence to use in the output
  2474. file. Defaults to `os.linesep`, which depends on the OS in which
  2475. this method is called ('\n' for linux, '\r\n' for Windows, i.e.).
  2476. .. versionchanged:: 0.24.0
  2477. chunksize : int or None
  2478. Rows to write at a time.
  2479. tupleize_cols : bool, default False
  2480. Write MultiIndex columns as a list of tuples (if True) or in
  2481. the new, expanded format, where each MultiIndex column is a row
  2482. in the CSV (if False).
  2483. .. deprecated:: 0.21.0
  2484. This argument will be removed and will always write each row
  2485. of the multi-index as a separate row in the CSV file.
  2486. date_format : str, default None
  2487. Format string for datetime objects.
  2488. doublequote : bool, default True
  2489. Control quoting of `quotechar` inside a field.
  2490. escapechar : str, default None
  2491. String of length 1. Character used to escape `sep` and `quotechar`
  2492. when appropriate.
  2493. decimal : str, default '.'
  2494. Character recognized as decimal separator. E.g. use ',' for
  2495. European data.
  2496. Returns
  2497. -------
  2498. None or str
  2499. If path_or_buf is None, returns the resulting csv format as a
  2500. string. Otherwise returns None.
  2501. See Also
  2502. --------
  2503. read_csv : Load a CSV file into a DataFrame.
  2504. to_excel : Load an Excel file into a DataFrame.
  2505. Examples
  2506. --------
  2507. >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
  2508. ... 'mask': ['red', 'purple'],
  2509. ... 'weapon': ['sai', 'bo staff']})
  2510. >>> df.to_csv(index=False)
  2511. 'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
  2512. """
  2513. df = self if isinstance(self, ABCDataFrame) else self.to_frame()
  2514. if tupleize_cols is not None:
  2515. warnings.warn("The 'tupleize_cols' parameter is deprecated and "
  2516. "will be removed in a future version",
  2517. FutureWarning, stacklevel=2)
  2518. else:
  2519. tupleize_cols = False
  2520. from pandas.io.formats.csvs import CSVFormatter
  2521. formatter = CSVFormatter(df, path_or_buf,
  2522. line_terminator=line_terminator, sep=sep,
  2523. encoding=encoding,
  2524. compression=compression, quoting=quoting,
  2525. na_rep=na_rep, float_format=float_format,
  2526. cols=columns, header=header, index=index,
  2527. index_label=index_label, mode=mode,
  2528. chunksize=chunksize, quotechar=quotechar,
  2529. tupleize_cols=tupleize_cols,
  2530. date_format=date_format,
  2531. doublequote=doublequote,
  2532. escapechar=escapechar, decimal=decimal)
  2533. formatter.save()
  2534. if path_or_buf is None:
  2535. return formatter.path_or_buf.getvalue()
  2536. # ----------------------------------------------------------------------
  2537. # Fancy Indexing
  2538. @classmethod
  2539. def _create_indexer(cls, name, indexer):
  2540. """Create an indexer like _name in the class."""
  2541. if getattr(cls, name, None) is None:
  2542. _indexer = functools.partial(indexer, name)
  2543. setattr(cls, name, property(_indexer, doc=indexer.__doc__))
  2544. def get(self, key, default=None):
  2545. """
  2546. Get item from object for given key (DataFrame column, Panel slice,
  2547. etc.). Returns default value if not found.
  2548. Parameters
  2549. ----------
  2550. key : object
  2551. Returns
  2552. -------
  2553. value : same type as items contained in object
  2554. """
  2555. try:
  2556. return self[key]
  2557. except (KeyError, ValueError, IndexError):
  2558. return default
  2559. def __getitem__(self, item):
  2560. return self._get_item_cache(item)
  2561. def _get_item_cache(self, item):
  2562. """Return the cached item, item represents a label indexer."""
  2563. cache = self._item_cache
  2564. res = cache.get(item)
  2565. if res is None:
  2566. values = self._data.get(item)
  2567. res = self._box_item_values(item, values)
  2568. cache[item] = res
  2569. res._set_as_cached(item, self)
  2570. # for a chain
  2571. res._is_copy = self._is_copy
  2572. return res
  2573. def _set_as_cached(self, item, cacher):
  2574. """Set the _cacher attribute on the calling object with a weakref to
  2575. cacher.
  2576. """
  2577. self._cacher = (item, weakref.ref(cacher))
  2578. def _reset_cacher(self):
  2579. """Reset the cacher."""
  2580. if hasattr(self, '_cacher'):
  2581. del self._cacher
  2582. def _iget_item_cache(self, item):
  2583. """Return the cached item, item represents a positional indexer."""
  2584. ax = self._info_axis
  2585. if ax.is_unique:
  2586. lower = self._get_item_cache(ax[item])
  2587. else:
  2588. lower = self._take(item, axis=self._info_axis_number)
  2589. return lower
  2590. def _box_item_values(self, key, values):
  2591. raise AbstractMethodError(self)
  2592. def _maybe_cache_changed(self, item, value):
  2593. """The object has called back to us saying maybe it has changed.
  2594. """
  2595. self._data.set(item, value)
  2596. @property
  2597. def _is_cached(self):
  2598. """Return boolean indicating if self is cached or not."""
  2599. return getattr(self, '_cacher', None) is not None
  2600. def _get_cacher(self):
  2601. """return my cacher or None"""
  2602. cacher = getattr(self, '_cacher', None)
  2603. if cacher is not None:
  2604. cacher = cacher[1]()
  2605. return cacher
  2606. @property
  2607. def _is_view(self):
  2608. """Return boolean indicating if self is view of another array """
  2609. return self._data.is_view
  2610. def _maybe_update_cacher(self, clear=False, verify_is_copy=True):
  2611. """
  2612. See if we need to update our parent cacher if clear, then clear our
  2613. cache.
  2614. Parameters
  2615. ----------
  2616. clear : boolean, default False
  2617. clear the item cache
  2618. verify_is_copy : boolean, default True
  2619. provide is_copy checks
  2620. """
  2621. cacher = getattr(self, '_cacher', None)
  2622. if cacher is not None:
  2623. ref = cacher[1]()
  2624. # we are trying to reference a dead referant, hence
  2625. # a copy
  2626. if ref is None:
  2627. del self._cacher
  2628. else:
  2629. try:
  2630. ref._maybe_cache_changed(cacher[0], self)
  2631. except Exception:
  2632. pass
  2633. if verify_is_copy:
  2634. self._check_setitem_copy(stacklevel=5, t='referant')
  2635. if clear:
  2636. self._clear_item_cache()
  2637. def _clear_item_cache(self, i=None):
  2638. if i is not None:
  2639. self._item_cache.pop(i, None)
  2640. else:
  2641. self._item_cache.clear()
  2642. def _slice(self, slobj, axis=0, kind=None):
  2643. """
  2644. Construct a slice of this container.
  2645. kind parameter is maintained for compatibility with Series slicing.
  2646. """
  2647. axis = self._get_block_manager_axis(axis)
  2648. result = self._constructor(self._data.get_slice(slobj, axis=axis))
  2649. result = result.__finalize__(self)
  2650. # this could be a view
  2651. # but only in a single-dtyped view slicable case
  2652. is_copy = axis != 0 or result._is_view
  2653. result._set_is_copy(self, copy=is_copy)
  2654. return result
  2655. def _set_item(self, key, value):
  2656. self._data.set(key, value)
  2657. self._clear_item_cache()
  2658. def _set_is_copy(self, ref=None, copy=True):
  2659. if not copy:
  2660. self._is_copy = None
  2661. else:
  2662. if ref is not None:
  2663. self._is_copy = weakref.ref(ref)
  2664. else:
  2665. self._is_copy = None
  2666. def _check_is_chained_assignment_possible(self):
  2667. """
  2668. Check if we are a view, have a cacher, and are of mixed type.
  2669. If so, then force a setitem_copy check.
  2670. Should be called just near setting a value
  2671. Will return a boolean if it we are a view and are cached, but a
  2672. single-dtype meaning that the cacher should be updated following
  2673. setting.
  2674. """
  2675. if self._is_view and self._is_cached:
  2676. ref = self._get_cacher()
  2677. if ref is not None and ref._is_mixed_type:
  2678. self._check_setitem_copy(stacklevel=4, t='referant',
  2679. force=True)
  2680. return True
  2681. elif self._is_copy:
  2682. self._check_setitem_copy(stacklevel=4, t='referant')
  2683. return False
  2684. def _check_setitem_copy(self, stacklevel=4, t='setting', force=False):
  2685. """
  2686. Parameters
  2687. ----------
  2688. stacklevel : integer, default 4
  2689. the level to show of the stack when the error is output
  2690. t : string, the type of setting error
  2691. force : boolean, default False
  2692. if True, then force showing an error
  2693. validate if we are doing a settitem on a chained copy.
  2694. If you call this function, be sure to set the stacklevel such that the
  2695. user will see the error *at the level of setting*
  2696. It is technically possible to figure out that we are setting on
  2697. a copy even WITH a multi-dtyped pandas object. In other words, some
  2698. blocks may be views while other are not. Currently _is_view will ALWAYS
  2699. return False for multi-blocks to avoid having to handle this case.
  2700. df = DataFrame(np.arange(0,9), columns=['count'])
  2701. df['group'] = 'b'
  2702. # This technically need not raise SettingWithCopy if both are view
  2703. # (which is not # generally guaranteed but is usually True. However,
  2704. # this is in general not a good practice and we recommend using .loc.
  2705. df.iloc[0:5]['group'] = 'a'
  2706. """
  2707. if force or self._is_copy:
  2708. value = config.get_option('mode.chained_assignment')
  2709. if value is None:
  2710. return
  2711. # see if the copy is not actually referred; if so, then dissolve
  2712. # the copy weakref
  2713. try:
  2714. gc.collect(2)
  2715. if not gc.get_referents(self._is_copy()):
  2716. self._is_copy = None
  2717. return
  2718. except Exception:
  2719. pass
  2720. # we might be a false positive
  2721. try:
  2722. if self._is_copy().shape == self.shape:
  2723. self._is_copy = None
  2724. return
  2725. except Exception:
  2726. pass
  2727. # a custom message
  2728. if isinstance(self._is_copy, string_types):
  2729. t = self._is_copy
  2730. elif t == 'referant':
  2731. t = ("\n"
  2732. "A value is trying to be set on a copy of a slice from a "
  2733. "DataFrame\n\n"
  2734. "See the caveats in the documentation: "
  2735. "http://pandas.pydata.org/pandas-docs/stable/"
  2736. "indexing.html#indexing-view-versus-copy"
  2737. )
  2738. else:
  2739. t = ("\n"
  2740. "A value is trying to be set on a copy of a slice from a "
  2741. "DataFrame.\n"
  2742. "Try using .loc[row_indexer,col_indexer] = value "
  2743. "instead\n\nSee the caveats in the documentation: "
  2744. "http://pandas.pydata.org/pandas-docs/stable/"
  2745. "indexing.html#indexing-view-versus-copy"
  2746. )
  2747. if value == 'raise':
  2748. raise com.SettingWithCopyError(t)
  2749. elif value == 'warn':
  2750. warnings.warn(t, com.SettingWithCopyWarning,
  2751. stacklevel=stacklevel)
  2752. def __delitem__(self, key):
  2753. """
  2754. Delete item
  2755. """
  2756. deleted = False
  2757. maybe_shortcut = False
  2758. if hasattr(self, 'columns') and isinstance(self.columns, MultiIndex):
  2759. try:
  2760. maybe_shortcut = key not in self.columns._engine
  2761. except TypeError:
  2762. pass
  2763. if maybe_shortcut:
  2764. # Allow shorthand to delete all columns whose first len(key)
  2765. # elements match key:
  2766. if not isinstance(key, tuple):
  2767. key = (key, )
  2768. for col in self.columns:
  2769. if isinstance(col, tuple) and col[:len(key)] == key:
  2770. del self[col]
  2771. deleted = True
  2772. if not deleted:
  2773. # If the above loop ran and didn't delete anything because
  2774. # there was no match, this call should raise the appropriate
  2775. # exception:
  2776. self._data.delete(key)
  2777. # delete from the caches
  2778. try:
  2779. del self._item_cache[key]
  2780. except KeyError:
  2781. pass
  2782. def _take(self, indices, axis=0, is_copy=True):
  2783. """
  2784. Return the elements in the given *positional* indices along an axis.
  2785. This means that we are not indexing according to actual values in
  2786. the index attribute of the object. We are indexing according to the
  2787. actual position of the element in the object.
  2788. This is the internal version of ``.take()`` and will contain a wider
  2789. selection of parameters useful for internal use but not as suitable
  2790. for public usage.
  2791. Parameters
  2792. ----------
  2793. indices : array-like
  2794. An array of ints indicating which positions to take.
  2795. axis : int, default 0
  2796. The axis on which to select elements. "0" means that we are
  2797. selecting rows, "1" means that we are selecting columns, etc.
  2798. is_copy : bool, default True
  2799. Whether to return a copy of the original object or not.
  2800. Returns
  2801. -------
  2802. taken : same type as caller
  2803. An array-like containing the elements taken from the object.
  2804. See Also
  2805. --------
  2806. numpy.ndarray.take
  2807. numpy.take
  2808. """
  2809. self._consolidate_inplace()
  2810. new_data = self._data.take(indices,
  2811. axis=self._get_block_manager_axis(axis),
  2812. verify=True)
  2813. result = self._constructor(new_data).__finalize__(self)
  2814. # Maybe set copy if we didn't actually change the index.
  2815. if is_copy:
  2816. if not result._get_axis(axis).equals(self._get_axis(axis)):
  2817. result._set_is_copy(self)
  2818. return result
  2819. def take(self, indices, axis=0, convert=None, is_copy=True, **kwargs):
  2820. """
  2821. Return the elements in the given *positional* indices along an axis.
  2822. This means that we are not indexing according to actual values in
  2823. the index attribute of the object. We are indexing according to the
  2824. actual position of the element in the object.
  2825. Parameters
  2826. ----------
  2827. indices : array-like
  2828. An array of ints indicating which positions to take.
  2829. axis : {0 or 'index', 1 or 'columns', None}, default 0
  2830. The axis on which to select elements. ``0`` means that we are
  2831. selecting rows, ``1`` means that we are selecting columns.
  2832. convert : bool, default True
  2833. Whether to convert negative indices into positive ones.
  2834. For example, ``-1`` would map to the ``len(axis) - 1``.
  2835. The conversions are similar to the behavior of indexing a
  2836. regular Python list.
  2837. .. deprecated:: 0.21.0
  2838. In the future, negative indices will always be converted.
  2839. is_copy : bool, default True
  2840. Whether to return a copy of the original object or not.
  2841. **kwargs
  2842. For compatibility with :meth:`numpy.take`. Has no effect on the
  2843. output.
  2844. Returns
  2845. -------
  2846. taken : same type as caller
  2847. An array-like containing the elements taken from the object.
  2848. See Also
  2849. --------
  2850. DataFrame.loc : Select a subset of a DataFrame by labels.
  2851. DataFrame.iloc : Select a subset of a DataFrame by positions.
  2852. numpy.take : Take elements from an array along an axis.
  2853. Examples
  2854. --------
  2855. >>> df = pd.DataFrame([('falcon', 'bird', 389.0),
  2856. ... ('parrot', 'bird', 24.0),
  2857. ... ('lion', 'mammal', 80.5),
  2858. ... ('monkey', 'mammal', np.nan)],
  2859. ... columns=['name', 'class', 'max_speed'],
  2860. ... index=[0, 2, 3, 1])
  2861. >>> df
  2862. name class max_speed
  2863. 0 falcon bird 389.0
  2864. 2 parrot bird 24.0
  2865. 3 lion mammal 80.5
  2866. 1 monkey mammal NaN
  2867. Take elements at positions 0 and 3 along the axis 0 (default).
  2868. Note how the actual indices selected (0 and 1) do not correspond to
  2869. our selected indices 0 and 3. That's because we are selecting the 0th
  2870. and 3rd rows, not rows whose indices equal 0 and 3.
  2871. >>> df.take([0, 3])
  2872. name class max_speed
  2873. 0 falcon bird 389.0
  2874. 1 monkey mammal NaN
  2875. Take elements at indices 1 and 2 along the axis 1 (column selection).
  2876. >>> df.take([1, 2], axis=1)
  2877. class max_speed
  2878. 0 bird 389.0
  2879. 2 bird 24.0
  2880. 3 mammal 80.5
  2881. 1 mammal NaN
  2882. We may take elements using negative integers for positive indices,
  2883. starting from the end of the object, just like with Python lists.
  2884. >>> df.take([-1, -2])
  2885. name class max_speed
  2886. 1 monkey mammal NaN
  2887. 3 lion mammal 80.5
  2888. """
  2889. if convert is not None:
  2890. msg = ("The 'convert' parameter is deprecated "
  2891. "and will be removed in a future version.")
  2892. warnings.warn(msg, FutureWarning, stacklevel=2)
  2893. nv.validate_take(tuple(), kwargs)
  2894. return self._take(indices, axis=axis, is_copy=is_copy)
  2895. def xs(self, key, axis=0, level=None, drop_level=True):
  2896. """
  2897. Return cross-section from the Series/DataFrame.
  2898. This method takes a `key` argument to select data at a particular
  2899. level of a MultiIndex.
  2900. Parameters
  2901. ----------
  2902. key : label or tuple of label
  2903. Label contained in the index, or partially in a MultiIndex.
  2904. axis : {0 or 'index', 1 or 'columns'}, default 0
  2905. Axis to retrieve cross-section on.
  2906. level : object, defaults to first n levels (n=1 or len(key))
  2907. In case of a key partially contained in a MultiIndex, indicate
  2908. which levels are used. Levels can be referred by label or position.
  2909. drop_level : bool, default True
  2910. If False, returns object with same levels as self.
  2911. Returns
  2912. -------
  2913. Series or DataFrame
  2914. Cross-section from the original Series or DataFrame
  2915. corresponding to the selected index levels.
  2916. See Also
  2917. --------
  2918. DataFrame.loc : Access a group of rows and columns
  2919. by label(s) or a boolean array.
  2920. DataFrame.iloc : Purely integer-location based indexing
  2921. for selection by position.
  2922. Notes
  2923. -----
  2924. `xs` can not be used to set values.
  2925. MultiIndex Slicers is a generic way to get/set values on
  2926. any level or levels.
  2927. It is a superset of `xs` functionality, see
  2928. :ref:`MultiIndex Slicers <advanced.mi_slicers>`.
  2929. Examples
  2930. --------
  2931. >>> d = {'num_legs': [4, 4, 2, 2],
  2932. ... 'num_wings': [0, 0, 2, 2],
  2933. ... 'class': ['mammal', 'mammal', 'mammal', 'bird'],
  2934. ... 'animal': ['cat', 'dog', 'bat', 'penguin'],
  2935. ... 'locomotion': ['walks', 'walks', 'flies', 'walks']}
  2936. >>> df = pd.DataFrame(data=d)
  2937. >>> df = df.set_index(['class', 'animal', 'locomotion'])
  2938. >>> df
  2939. num_legs num_wings
  2940. class animal locomotion
  2941. mammal cat walks 4 0
  2942. dog walks 4 0
  2943. bat flies 2 2
  2944. bird penguin walks 2 2
  2945. Get values at specified index
  2946. >>> df.xs('mammal')
  2947. num_legs num_wings
  2948. animal locomotion
  2949. cat walks 4 0
  2950. dog walks 4 0
  2951. bat flies 2 2
  2952. Get values at several indexes
  2953. >>> df.xs(('mammal', 'dog'))
  2954. num_legs num_wings
  2955. locomotion
  2956. walks 4 0
  2957. Get values at specified index and level
  2958. >>> df.xs('cat', level=1)
  2959. num_legs num_wings
  2960. class locomotion
  2961. mammal walks 4 0
  2962. Get values at several indexes and levels
  2963. >>> df.xs(('bird', 'walks'),
  2964. ... level=[0, 'locomotion'])
  2965. num_legs num_wings
  2966. animal
  2967. penguin 2 2
  2968. Get values at specified column and axis
  2969. >>> df.xs('num_wings', axis=1)
  2970. class animal locomotion
  2971. mammal cat walks 0
  2972. dog walks 0
  2973. bat flies 2
  2974. bird penguin walks 2
  2975. Name: num_wings, dtype: int64
  2976. """
  2977. axis = self._get_axis_number(axis)
  2978. labels = self._get_axis(axis)
  2979. if level is not None:
  2980. loc, new_ax = labels.get_loc_level(key, level=level,
  2981. drop_level=drop_level)
  2982. # create the tuple of the indexer
  2983. indexer = [slice(None)] * self.ndim
  2984. indexer[axis] = loc
  2985. indexer = tuple(indexer)
  2986. result = self.iloc[indexer]
  2987. setattr(result, result._get_axis_name(axis), new_ax)
  2988. return result
  2989. if axis == 1:
  2990. return self[key]
  2991. self._consolidate_inplace()
  2992. index = self.index
  2993. if isinstance(index, MultiIndex):
  2994. loc, new_index = self.index.get_loc_level(key,
  2995. drop_level=drop_level)
  2996. else:
  2997. loc = self.index.get_loc(key)
  2998. if isinstance(loc, np.ndarray):
  2999. if loc.dtype == np.bool_:
  3000. inds, = loc.nonzero()
  3001. return self._take(inds, axis=axis)
  3002. else:
  3003. return self._take(loc, axis=axis)
  3004. if not is_scalar(loc):
  3005. new_index = self.index[loc]
  3006. if is_scalar(loc):
  3007. new_values = self._data.fast_xs(loc)
  3008. # may need to box a datelike-scalar
  3009. #
  3010. # if we encounter an array-like and we only have 1 dim
  3011. # that means that their are list/ndarrays inside the Series!
  3012. # so just return them (GH 6394)
  3013. if not is_list_like(new_values) or self.ndim == 1:
  3014. return com.maybe_box_datetimelike(new_values)
  3015. result = self._constructor_sliced(
  3016. new_values, index=self.columns,
  3017. name=self.index[loc], dtype=new_values.dtype)
  3018. else:
  3019. result = self.iloc[loc]
  3020. result.index = new_index
  3021. # this could be a view
  3022. # but only in a single-dtyped view slicable case
  3023. result._set_is_copy(self, copy=not result._is_view)
  3024. return result
  3025. _xs = xs
  3026. def select(self, crit, axis=0):
  3027. """
  3028. Return data corresponding to axis labels matching criteria.
  3029. .. deprecated:: 0.21.0
  3030. Use df.loc[df.index.map(crit)] to select via labels
  3031. Parameters
  3032. ----------
  3033. crit : function
  3034. To be called on each index (label). Should return True or False
  3035. axis : int
  3036. Returns
  3037. -------
  3038. selection : same type as caller
  3039. """
  3040. warnings.warn("'select' is deprecated and will be removed in a "
  3041. "future release. You can use "
  3042. ".loc[labels.map(crit)] as a replacement",
  3043. FutureWarning, stacklevel=2)
  3044. axis = self._get_axis_number(axis)
  3045. axis_name = self._get_axis_name(axis)
  3046. axis_values = self._get_axis(axis)
  3047. if len(axis_values) > 0:
  3048. new_axis = axis_values[
  3049. np.asarray([bool(crit(label)) for label in axis_values])]
  3050. else:
  3051. new_axis = axis_values
  3052. return self.reindex(**{axis_name: new_axis})
  3053. def reindex_like(self, other, method=None, copy=True, limit=None,
  3054. tolerance=None):
  3055. """
  3056. Return an object with matching indices as other object.
  3057. Conform the object to the same index on all axes. Optional
  3058. filling logic, placing NaN in locations having no value
  3059. in the previous index. A new object is produced unless the
  3060. new index is equivalent to the current one and copy=False.
  3061. Parameters
  3062. ----------
  3063. other : Object of the same data type
  3064. Its row and column indices are used to define the new indices
  3065. of this object.
  3066. method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}
  3067. Method to use for filling holes in reindexed DataFrame.
  3068. Please note: this is only applicable to DataFrames/Series with a
  3069. monotonically increasing/decreasing index.
  3070. * None (default): don't fill gaps
  3071. * pad / ffill: propagate last valid observation forward to next
  3072. valid
  3073. * backfill / bfill: use next valid observation to fill gap
  3074. * nearest: use nearest valid observations to fill gap
  3075. copy : bool, default True
  3076. Return a new object, even if the passed indexes are the same.
  3077. limit : int, default None
  3078. Maximum number of consecutive labels to fill for inexact matches.
  3079. tolerance : optional
  3080. Maximum distance between original and new labels for inexact
  3081. matches. The values of the index at the matching locations most
  3082. satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
  3083. Tolerance may be a scalar value, which applies the same tolerance
  3084. to all values, or list-like, which applies variable tolerance per
  3085. element. List-like includes list, tuple, array, Series, and must be
  3086. the same size as the index and its dtype must exactly match the
  3087. index's type.
  3088. .. versionadded:: 0.21.0 (list-like tolerance)
  3089. Returns
  3090. -------
  3091. Series or DataFrame
  3092. Same type as caller, but with changed indices on each axis.
  3093. See Also
  3094. --------
  3095. DataFrame.set_index : Set row labels.
  3096. DataFrame.reset_index : Remove row labels or move them to new columns.
  3097. DataFrame.reindex : Change to new indices or expand indices.
  3098. Notes
  3099. -----
  3100. Same as calling
  3101. ``.reindex(index=other.index, columns=other.columns,...)``.
  3102. Examples
  3103. --------
  3104. >>> df1 = pd.DataFrame([[24.3, 75.7, 'high'],
  3105. ... [31, 87.8, 'high'],
  3106. ... [22, 71.6, 'medium'],
  3107. ... [35, 95, 'medium']],
  3108. ... columns=['temp_celsius', 'temp_fahrenheit', 'windspeed'],
  3109. ... index=pd.date_range(start='2014-02-12',
  3110. ... end='2014-02-15', freq='D'))
  3111. >>> df1
  3112. temp_celsius temp_fahrenheit windspeed
  3113. 2014-02-12 24.3 75.7 high
  3114. 2014-02-13 31.0 87.8 high
  3115. 2014-02-14 22.0 71.6 medium
  3116. 2014-02-15 35.0 95.0 medium
  3117. >>> df2 = pd.DataFrame([[28, 'low'],
  3118. ... [30, 'low'],
  3119. ... [35.1, 'medium']],
  3120. ... columns=['temp_celsius', 'windspeed'],
  3121. ... index=pd.DatetimeIndex(['2014-02-12', '2014-02-13',
  3122. ... '2014-02-15']))
  3123. >>> df2
  3124. temp_celsius windspeed
  3125. 2014-02-12 28.0 low
  3126. 2014-02-13 30.0 low
  3127. 2014-02-15 35.1 medium
  3128. >>> df2.reindex_like(df1)
  3129. temp_celsius temp_fahrenheit windspeed
  3130. 2014-02-12 28.0 NaN low
  3131. 2014-02-13 30.0 NaN low
  3132. 2014-02-14 NaN NaN NaN
  3133. 2014-02-15 35.1 NaN medium
  3134. """
  3135. d = other._construct_axes_dict(axes=self._AXIS_ORDERS, method=method,
  3136. copy=copy, limit=limit,
  3137. tolerance=tolerance)
  3138. return self.reindex(**d)
  3139. def drop(self, labels=None, axis=0, index=None, columns=None, level=None,
  3140. inplace=False, errors='raise'):
  3141. inplace = validate_bool_kwarg(inplace, 'inplace')
  3142. if labels is not None:
  3143. if index is not None or columns is not None:
  3144. raise ValueError("Cannot specify both 'labels' and "
  3145. "'index'/'columns'")
  3146. axis_name = self._get_axis_name(axis)
  3147. axes = {axis_name: labels}
  3148. elif index is not None or columns is not None:
  3149. axes, _ = self._construct_axes_from_arguments((index, columns), {})
  3150. else:
  3151. raise ValueError("Need to specify at least one of 'labels', "
  3152. "'index' or 'columns'")
  3153. obj = self
  3154. for axis, labels in axes.items():
  3155. if labels is not None:
  3156. obj = obj._drop_axis(labels, axis, level=level, errors=errors)
  3157. if inplace:
  3158. self._update_inplace(obj)
  3159. else:
  3160. return obj
  3161. def _drop_axis(self, labels, axis, level=None, errors='raise'):
  3162. """
  3163. Drop labels from specified axis. Used in the ``drop`` method
  3164. internally.
  3165. Parameters
  3166. ----------
  3167. labels : single label or list-like
  3168. axis : int or axis name
  3169. level : int or level name, default None
  3170. For MultiIndex
  3171. errors : {'ignore', 'raise'}, default 'raise'
  3172. If 'ignore', suppress error and existing labels are dropped.
  3173. """
  3174. axis = self._get_axis_number(axis)
  3175. axis_name = self._get_axis_name(axis)
  3176. axis = self._get_axis(axis)
  3177. if axis.is_unique:
  3178. if level is not None:
  3179. if not isinstance(axis, MultiIndex):
  3180. raise AssertionError('axis must be a MultiIndex')
  3181. new_axis = axis.drop(labels, level=level, errors=errors)
  3182. else:
  3183. new_axis = axis.drop(labels, errors=errors)
  3184. result = self.reindex(**{axis_name: new_axis})
  3185. # Case for non-unique axis
  3186. else:
  3187. labels = ensure_object(com.index_labels_to_array(labels))
  3188. if level is not None:
  3189. if not isinstance(axis, MultiIndex):
  3190. raise AssertionError('axis must be a MultiIndex')
  3191. indexer = ~axis.get_level_values(level).isin(labels)
  3192. # GH 18561 MultiIndex.drop should raise if label is absent
  3193. if errors == 'raise' and indexer.all():
  3194. raise KeyError('{} not found in axis'.format(labels))
  3195. else:
  3196. indexer = ~axis.isin(labels)
  3197. # Check if label doesn't exist along axis
  3198. labels_missing = (axis.get_indexer_for(labels) == -1).any()
  3199. if errors == 'raise' and labels_missing:
  3200. raise KeyError('{} not found in axis'.format(labels))
  3201. slicer = [slice(None)] * self.ndim
  3202. slicer[self._get_axis_number(axis_name)] = indexer
  3203. result = self.loc[tuple(slicer)]
  3204. return result
  3205. def _update_inplace(self, result, verify_is_copy=True):
  3206. """
  3207. Replace self internals with result.
  3208. Parameters
  3209. ----------
  3210. verify_is_copy : boolean, default True
  3211. provide is_copy checks
  3212. """
  3213. # NOTE: This does *not* call __finalize__ and that's an explicit
  3214. # decision that we may revisit in the future.
  3215. self._reset_cache()
  3216. self._clear_item_cache()
  3217. self._data = getattr(result, '_data', result)
  3218. self._maybe_update_cacher(verify_is_copy=verify_is_copy)
  3219. def add_prefix(self, prefix):
  3220. """
  3221. Prefix labels with string `prefix`.
  3222. For Series, the row labels are prefixed.
  3223. For DataFrame, the column labels are prefixed.
  3224. Parameters
  3225. ----------
  3226. prefix : str
  3227. The string to add before each label.
  3228. Returns
  3229. -------
  3230. Series or DataFrame
  3231. New Series or DataFrame with updated labels.
  3232. See Also
  3233. --------
  3234. Series.add_suffix: Suffix row labels with string `suffix`.
  3235. DataFrame.add_suffix: Suffix column labels with string `suffix`.
  3236. Examples
  3237. --------
  3238. >>> s = pd.Series([1, 2, 3, 4])
  3239. >>> s
  3240. 0 1
  3241. 1 2
  3242. 2 3
  3243. 3 4
  3244. dtype: int64
  3245. >>> s.add_prefix('item_')
  3246. item_0 1
  3247. item_1 2
  3248. item_2 3
  3249. item_3 4
  3250. dtype: int64
  3251. >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
  3252. >>> df
  3253. A B
  3254. 0 1 3
  3255. 1 2 4
  3256. 2 3 5
  3257. 3 4 6
  3258. >>> df.add_prefix('col_')
  3259. col_A col_B
  3260. 0 1 3
  3261. 1 2 4
  3262. 2 3 5
  3263. 3 4 6
  3264. """
  3265. f = functools.partial('{prefix}{}'.format, prefix=prefix)
  3266. mapper = {self._info_axis_name: f}
  3267. return self.rename(**mapper)
  3268. def add_suffix(self, suffix):
  3269. """
  3270. Suffix labels with string `suffix`.
  3271. For Series, the row labels are suffixed.
  3272. For DataFrame, the column labels are suffixed.
  3273. Parameters
  3274. ----------
  3275. suffix : str
  3276. The string to add after each label.
  3277. Returns
  3278. -------
  3279. Series or DataFrame
  3280. New Series or DataFrame with updated labels.
  3281. See Also
  3282. --------
  3283. Series.add_prefix: Prefix row labels with string `prefix`.
  3284. DataFrame.add_prefix: Prefix column labels with string `prefix`.
  3285. Examples
  3286. --------
  3287. >>> s = pd.Series([1, 2, 3, 4])
  3288. >>> s
  3289. 0 1
  3290. 1 2
  3291. 2 3
  3292. 3 4
  3293. dtype: int64
  3294. >>> s.add_suffix('_item')
  3295. 0_item 1
  3296. 1_item 2
  3297. 2_item 3
  3298. 3_item 4
  3299. dtype: int64
  3300. >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
  3301. >>> df
  3302. A B
  3303. 0 1 3
  3304. 1 2 4
  3305. 2 3 5
  3306. 3 4 6
  3307. >>> df.add_suffix('_col')
  3308. A_col B_col
  3309. 0 1 3
  3310. 1 2 4
  3311. 2 3 5
  3312. 3 4 6
  3313. """
  3314. f = functools.partial('{}{suffix}'.format, suffix=suffix)
  3315. mapper = {self._info_axis_name: f}
  3316. return self.rename(**mapper)
  3317. def sort_values(self, by=None, axis=0, ascending=True, inplace=False,
  3318. kind='quicksort', na_position='last'):
  3319. """
  3320. Sort by the values along either axis.
  3321. Parameters
  3322. ----------%(optional_by)s
  3323. axis : %(axes_single_arg)s, default 0
  3324. Axis to be sorted.
  3325. ascending : bool or list of bool, default True
  3326. Sort ascending vs. descending. Specify list for multiple sort
  3327. orders. If this is a list of bools, must match the length of
  3328. the by.
  3329. inplace : bool, default False
  3330. If True, perform operation in-place.
  3331. kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
  3332. Choice of sorting algorithm. See also ndarray.np.sort for more
  3333. information. `mergesort` is the only stable algorithm. For
  3334. DataFrames, this option is only applied when sorting on a single
  3335. column or label.
  3336. na_position : {'first', 'last'}, default 'last'
  3337. Puts NaNs at the beginning if `first`; `last` puts NaNs at the
  3338. end.
  3339. Returns
  3340. -------
  3341. sorted_obj : DataFrame or None
  3342. DataFrame with sorted values if inplace=False, None otherwise.
  3343. Examples
  3344. --------
  3345. >>> df = pd.DataFrame({
  3346. ... 'col1': ['A', 'A', 'B', np.nan, 'D', 'C'],
  3347. ... 'col2': [2, 1, 9, 8, 7, 4],
  3348. ... 'col3': [0, 1, 9, 4, 2, 3],
  3349. ... })
  3350. >>> df
  3351. col1 col2 col3
  3352. 0 A 2 0
  3353. 1 A 1 1
  3354. 2 B 9 9
  3355. 3 NaN 8 4
  3356. 4 D 7 2
  3357. 5 C 4 3
  3358. Sort by col1
  3359. >>> df.sort_values(by=['col1'])
  3360. col1 col2 col3
  3361. 0 A 2 0
  3362. 1 A 1 1
  3363. 2 B 9 9
  3364. 5 C 4 3
  3365. 4 D 7 2
  3366. 3 NaN 8 4
  3367. Sort by multiple columns
  3368. >>> df.sort_values(by=['col1', 'col2'])
  3369. col1 col2 col3
  3370. 1 A 1 1
  3371. 0 A 2 0
  3372. 2 B 9 9
  3373. 5 C 4 3
  3374. 4 D 7 2
  3375. 3 NaN 8 4
  3376. Sort Descending
  3377. >>> df.sort_values(by='col1', ascending=False)
  3378. col1 col2 col3
  3379. 4 D 7 2
  3380. 5 C 4 3
  3381. 2 B 9 9
  3382. 0 A 2 0
  3383. 1 A 1 1
  3384. 3 NaN 8 4
  3385. Putting NAs first
  3386. >>> df.sort_values(by='col1', ascending=False, na_position='first')
  3387. col1 col2 col3
  3388. 3 NaN 8 4
  3389. 4 D 7 2
  3390. 5 C 4 3
  3391. 2 B 9 9
  3392. 0 A 2 0
  3393. 1 A 1 1
  3394. """
  3395. raise NotImplementedError("sort_values has not been implemented "
  3396. "on Panel or Panel4D objects.")
  3397. def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
  3398. kind='quicksort', na_position='last', sort_remaining=True):
  3399. """
  3400. Sort object by labels (along an axis).
  3401. Parameters
  3402. ----------
  3403. axis : {0 or 'index', 1 or 'columns'}, default 0
  3404. The axis along which to sort. The value 0 identifies the rows,
  3405. and 1 identifies the columns.
  3406. level : int or level name or list of ints or list of level names
  3407. If not None, sort on values in specified index level(s).
  3408. ascending : bool, default True
  3409. Sort ascending vs. descending.
  3410. inplace : bool, default False
  3411. If True, perform operation in-place.
  3412. kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
  3413. Choice of sorting algorithm. See also ndarray.np.sort for more
  3414. information. `mergesort` is the only stable algorithm. For
  3415. DataFrames, this option is only applied when sorting on a single
  3416. column or label.
  3417. na_position : {'first', 'last'}, default 'last'
  3418. Puts NaNs at the beginning if `first`; `last` puts NaNs at the end.
  3419. Not implemented for MultiIndex.
  3420. sort_remaining : bool, default True
  3421. If True and sorting by level and index is multilevel, sort by other
  3422. levels too (in order) after sorting by specified level.
  3423. Returns
  3424. -------
  3425. sorted_obj : DataFrame or None
  3426. DataFrame with sorted index if inplace=False, None otherwise.
  3427. """
  3428. inplace = validate_bool_kwarg(inplace, 'inplace')
  3429. axis = self._get_axis_number(axis)
  3430. axis_name = self._get_axis_name(axis)
  3431. labels = self._get_axis(axis)
  3432. if level is not None:
  3433. raise NotImplementedError("level is not implemented")
  3434. if inplace:
  3435. raise NotImplementedError("inplace is not implemented")
  3436. sort_index = labels.argsort()
  3437. if not ascending:
  3438. sort_index = sort_index[::-1]
  3439. new_axis = labels.take(sort_index)
  3440. return self.reindex(**{axis_name: new_axis})
  3441. def reindex(self, *args, **kwargs):
  3442. """
  3443. Conform %(klass)s to new index with optional filling logic, placing
  3444. NA/NaN in locations having no value in the previous index. A new object
  3445. is produced unless the new index is equivalent to the current one and
  3446. ``copy=False``.
  3447. Parameters
  3448. ----------
  3449. %(optional_labels)s
  3450. %(axes)s : array-like, optional
  3451. New labels / index to conform to, should be specified using
  3452. keywords. Preferably an Index object to avoid duplicating data
  3453. %(optional_axis)s
  3454. method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}
  3455. Method to use for filling holes in reindexed DataFrame.
  3456. Please note: this is only applicable to DataFrames/Series with a
  3457. monotonically increasing/decreasing index.
  3458. * None (default): don't fill gaps
  3459. * pad / ffill: propagate last valid observation forward to next
  3460. valid
  3461. * backfill / bfill: use next valid observation to fill gap
  3462. * nearest: use nearest valid observations to fill gap
  3463. copy : bool, default True
  3464. Return a new object, even if the passed indexes are the same.
  3465. level : int or name
  3466. Broadcast across a level, matching Index values on the
  3467. passed MultiIndex level.
  3468. fill_value : scalar, default np.NaN
  3469. Value to use for missing values. Defaults to NaN, but can be any
  3470. "compatible" value.
  3471. limit : int, default None
  3472. Maximum number of consecutive elements to forward or backward fill.
  3473. tolerance : optional
  3474. Maximum distance between original and new labels for inexact
  3475. matches. The values of the index at the matching locations most
  3476. satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
  3477. Tolerance may be a scalar value, which applies the same tolerance
  3478. to all values, or list-like, which applies variable tolerance per
  3479. element. List-like includes list, tuple, array, Series, and must be
  3480. the same size as the index and its dtype must exactly match the
  3481. index's type.
  3482. .. versionadded:: 0.21.0 (list-like tolerance)
  3483. Returns
  3484. -------
  3485. %(klass)s with changed index.
  3486. See Also
  3487. --------
  3488. DataFrame.set_index : Set row labels.
  3489. DataFrame.reset_index : Remove row labels or move them to new columns.
  3490. DataFrame.reindex_like : Change to same indices as other DataFrame.
  3491. Examples
  3492. --------
  3493. ``DataFrame.reindex`` supports two calling conventions
  3494. * ``(index=index_labels, columns=column_labels, ...)``
  3495. * ``(labels, axis={'index', 'columns'}, ...)``
  3496. We *highly* recommend using keyword arguments to clarify your
  3497. intent.
  3498. Create a dataframe with some fictional data.
  3499. >>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']
  3500. >>> df = pd.DataFrame({
  3501. ... 'http_status': [200,200,404,404,301],
  3502. ... 'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]},
  3503. ... index=index)
  3504. >>> df
  3505. http_status response_time
  3506. Firefox 200 0.04
  3507. Chrome 200 0.02
  3508. Safari 404 0.07
  3509. IE10 404 0.08
  3510. Konqueror 301 1.00
  3511. Create a new index and reindex the dataframe. By default
  3512. values in the new index that do not have corresponding
  3513. records in the dataframe are assigned ``NaN``.
  3514. >>> new_index= ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10',
  3515. ... 'Chrome']
  3516. >>> df.reindex(new_index)
  3517. http_status response_time
  3518. Safari 404.0 0.07
  3519. Iceweasel NaN NaN
  3520. Comodo Dragon NaN NaN
  3521. IE10 404.0 0.08
  3522. Chrome 200.0 0.02
  3523. We can fill in the missing values by passing a value to
  3524. the keyword ``fill_value``. Because the index is not monotonically
  3525. increasing or decreasing, we cannot use arguments to the keyword
  3526. ``method`` to fill the ``NaN`` values.
  3527. >>> df.reindex(new_index, fill_value=0)
  3528. http_status response_time
  3529. Safari 404 0.07
  3530. Iceweasel 0 0.00
  3531. Comodo Dragon 0 0.00
  3532. IE10 404 0.08
  3533. Chrome 200 0.02
  3534. >>> df.reindex(new_index, fill_value='missing')
  3535. http_status response_time
  3536. Safari 404 0.07
  3537. Iceweasel missing missing
  3538. Comodo Dragon missing missing
  3539. IE10 404 0.08
  3540. Chrome 200 0.02
  3541. We can also reindex the columns.
  3542. >>> df.reindex(columns=['http_status', 'user_agent'])
  3543. http_status user_agent
  3544. Firefox 200 NaN
  3545. Chrome 200 NaN
  3546. Safari 404 NaN
  3547. IE10 404 NaN
  3548. Konqueror 301 NaN
  3549. Or we can use "axis-style" keyword arguments
  3550. >>> df.reindex(['http_status', 'user_agent'], axis="columns")
  3551. http_status user_agent
  3552. Firefox 200 NaN
  3553. Chrome 200 NaN
  3554. Safari 404 NaN
  3555. IE10 404 NaN
  3556. Konqueror 301 NaN
  3557. To further illustrate the filling functionality in
  3558. ``reindex``, we will create a dataframe with a
  3559. monotonically increasing index (for example, a sequence
  3560. of dates).
  3561. >>> date_index = pd.date_range('1/1/2010', periods=6, freq='D')
  3562. >>> df2 = pd.DataFrame({"prices": [100, 101, np.nan, 100, 89, 88]},
  3563. ... index=date_index)
  3564. >>> df2
  3565. prices
  3566. 2010-01-01 100.0
  3567. 2010-01-02 101.0
  3568. 2010-01-03 NaN
  3569. 2010-01-04 100.0
  3570. 2010-01-05 89.0
  3571. 2010-01-06 88.0
  3572. Suppose we decide to expand the dataframe to cover a wider
  3573. date range.
  3574. >>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D')
  3575. >>> df2.reindex(date_index2)
  3576. prices
  3577. 2009-12-29 NaN
  3578. 2009-12-30 NaN
  3579. 2009-12-31 NaN
  3580. 2010-01-01 100.0
  3581. 2010-01-02 101.0
  3582. 2010-01-03 NaN
  3583. 2010-01-04 100.0
  3584. 2010-01-05 89.0
  3585. 2010-01-06 88.0
  3586. 2010-01-07 NaN
  3587. The index entries that did not have a value in the original data frame
  3588. (for example, '2009-12-29') are by default filled with ``NaN``.
  3589. If desired, we can fill in the missing values using one of several
  3590. options.
  3591. For example, to back-propagate the last valid value to fill the ``NaN``
  3592. values, pass ``bfill`` as an argument to the ``method`` keyword.
  3593. >>> df2.reindex(date_index2, method='bfill')
  3594. prices
  3595. 2009-12-29 100.0
  3596. 2009-12-30 100.0
  3597. 2009-12-31 100.0
  3598. 2010-01-01 100.0
  3599. 2010-01-02 101.0
  3600. 2010-01-03 NaN
  3601. 2010-01-04 100.0
  3602. 2010-01-05 89.0
  3603. 2010-01-06 88.0
  3604. 2010-01-07 NaN
  3605. Please note that the ``NaN`` value present in the original dataframe
  3606. (at index value 2010-01-03) will not be filled by any of the
  3607. value propagation schemes. This is because filling while reindexing
  3608. does not look at dataframe values, but only compares the original and
  3609. desired indexes. If you do want to fill in the ``NaN`` values present
  3610. in the original dataframe, use the ``fillna()`` method.
  3611. See the :ref:`user guide <basics.reindexing>` for more.
  3612. """
  3613. # TODO: Decide if we care about having different examples for different
  3614. # kinds
  3615. # construct the args
  3616. axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
  3617. method = missing.clean_reindex_fill_method(kwargs.pop('method', None))
  3618. level = kwargs.pop('level', None)
  3619. copy = kwargs.pop('copy', True)
  3620. limit = kwargs.pop('limit', None)
  3621. tolerance = kwargs.pop('tolerance', None)
  3622. fill_value = kwargs.pop('fill_value', None)
  3623. # Series.reindex doesn't use / need the axis kwarg
  3624. # We pop and ignore it here, to make writing Series/Frame generic code
  3625. # easier
  3626. kwargs.pop("axis", None)
  3627. if kwargs:
  3628. raise TypeError('reindex() got an unexpected keyword '
  3629. 'argument "{0}"'.format(list(kwargs.keys())[0]))
  3630. self._consolidate_inplace()
  3631. # if all axes that are requested to reindex are equal, then only copy
  3632. # if indicated must have index names equal here as well as values
  3633. if all(self._get_axis(axis).identical(ax)
  3634. for axis, ax in axes.items() if ax is not None):
  3635. if copy:
  3636. return self.copy()
  3637. return self
  3638. # check if we are a multi reindex
  3639. if self._needs_reindex_multi(axes, method, level):
  3640. try:
  3641. return self._reindex_multi(axes, copy, fill_value)
  3642. except Exception:
  3643. pass
  3644. # perform the reindex on the axes
  3645. return self._reindex_axes(axes, level, limit, tolerance, method,
  3646. fill_value, copy).__finalize__(self)
  3647. def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value,
  3648. copy):
  3649. """Perform the reindex for all the axes."""
  3650. obj = self
  3651. for a in self._AXIS_ORDERS:
  3652. labels = axes[a]
  3653. if labels is None:
  3654. continue
  3655. ax = self._get_axis(a)
  3656. new_index, indexer = ax.reindex(labels, level=level, limit=limit,
  3657. tolerance=tolerance, method=method)
  3658. axis = self._get_axis_number(a)
  3659. obj = obj._reindex_with_indexers({axis: [new_index, indexer]},
  3660. fill_value=fill_value,
  3661. copy=copy, allow_dups=False)
  3662. return obj
  3663. def _needs_reindex_multi(self, axes, method, level):
  3664. """Check if we do need a multi reindex."""
  3665. return ((com.count_not_none(*axes.values()) == self._AXIS_LEN) and
  3666. method is None and level is None and not self._is_mixed_type)
  3667. def _reindex_multi(self, axes, copy, fill_value):
  3668. return NotImplemented
  3669. _shared_docs['reindex_axis'] = ("""
  3670. Conform input object to new index.
  3671. .. deprecated:: 0.21.0
  3672. Use `reindex` instead.
  3673. By default, places NaN in locations having no value in the
  3674. previous index. A new object is produced unless the new index
  3675. is equivalent to the current one and copy=False.
  3676. Parameters
  3677. ----------
  3678. labels : array-like
  3679. New labels / index to conform to. Preferably an Index object to
  3680. avoid duplicating data.
  3681. axis : %(axes_single_arg)s
  3682. Indicate whether to use rows or columns.
  3683. method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}, optional
  3684. Method to use for filling holes in reindexed DataFrame:
  3685. * default: don't fill gaps.
  3686. * pad / ffill: propagate last valid observation forward to next
  3687. valid.
  3688. * backfill / bfill: use next valid observation to fill gap.
  3689. * nearest: use nearest valid observations to fill gap.
  3690. level : int or str
  3691. Broadcast across a level, matching Index values on the
  3692. passed MultiIndex level.
  3693. copy : bool, default True
  3694. Return a new object, even if the passed indexes are the same.
  3695. limit : int, optional
  3696. Maximum number of consecutive elements to forward or backward fill.
  3697. fill_value : float, default NaN
  3698. Value used to fill in locations having no value in the previous
  3699. index.
  3700. .. versionadded:: 0.21.0 (list-like tolerance)
  3701. Returns
  3702. -------
  3703. %(klass)s
  3704. Returns a new DataFrame object with new indices, unless the new
  3705. index is equivalent to the current one and copy=False.
  3706. See Also
  3707. --------
  3708. DataFrame.set_index : Set row labels.
  3709. DataFrame.reset_index : Remove row labels or move them to new columns.
  3710. DataFrame.reindex : Change to new indices or expand indices.
  3711. DataFrame.reindex_like : Change to same indices as other DataFrame.
  3712. Examples
  3713. --------
  3714. >>> df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
  3715. ... index=['dog', 'hawk'])
  3716. >>> df
  3717. num_legs num_wings
  3718. dog 4 0
  3719. hawk 2 2
  3720. >>> df.reindex(['num_wings', 'num_legs', 'num_heads'],
  3721. ... axis='columns')
  3722. num_wings num_legs num_heads
  3723. dog 0 4 NaN
  3724. hawk 2 2 NaN
  3725. """)
  3726. @Appender(_shared_docs['reindex_axis'] % _shared_doc_kwargs)
  3727. def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True,
  3728. limit=None, fill_value=None):
  3729. msg = ("'.reindex_axis' is deprecated and will be removed in a future "
  3730. "version. Use '.reindex' instead.")
  3731. self._consolidate_inplace()
  3732. axis_name = self._get_axis_name(axis)
  3733. axis_values = self._get_axis(axis_name)
  3734. method = missing.clean_reindex_fill_method(method)
  3735. warnings.warn(msg, FutureWarning, stacklevel=3)
  3736. new_index, indexer = axis_values.reindex(labels, method, level,
  3737. limit=limit)
  3738. return self._reindex_with_indexers({axis: [new_index, indexer]},
  3739. fill_value=fill_value, copy=copy)
  3740. def _reindex_with_indexers(self, reindexers, fill_value=None, copy=False,
  3741. allow_dups=False):
  3742. """allow_dups indicates an internal call here """
  3743. # reindex doing multiple operations on different axes if indicated
  3744. new_data = self._data
  3745. for axis in sorted(reindexers.keys()):
  3746. index, indexer = reindexers[axis]
  3747. baxis = self._get_block_manager_axis(axis)
  3748. if index is None:
  3749. continue
  3750. index = ensure_index(index)
  3751. if indexer is not None:
  3752. indexer = ensure_int64(indexer)
  3753. # TODO: speed up on homogeneous DataFrame objects
  3754. new_data = new_data.reindex_indexer(index, indexer, axis=baxis,
  3755. fill_value=fill_value,
  3756. allow_dups=allow_dups,
  3757. copy=copy)
  3758. if copy and new_data is self._data:
  3759. new_data = new_data.copy()
  3760. return self._constructor(new_data).__finalize__(self)
  3761. def filter(self, items=None, like=None, regex=None, axis=None):
  3762. """
  3763. Subset rows or columns of dataframe according to labels in
  3764. the specified index.
  3765. Note that this routine does not filter a dataframe on its
  3766. contents. The filter is applied to the labels of the index.
  3767. Parameters
  3768. ----------
  3769. items : list-like
  3770. Keep labels from axis which are in items.
  3771. like : string
  3772. Keep labels from axis for which "like in label == True".
  3773. regex : string (regular expression)
  3774. Keep labels from axis for which re.search(regex, label) == True.
  3775. axis : int or string axis name
  3776. The axis to filter on. By default this is the info axis,
  3777. 'index' for Series, 'columns' for DataFrame.
  3778. Returns
  3779. -------
  3780. same type as input object
  3781. See Also
  3782. --------
  3783. DataFrame.loc
  3784. Notes
  3785. -----
  3786. The ``items``, ``like``, and ``regex`` parameters are
  3787. enforced to be mutually exclusive.
  3788. ``axis`` defaults to the info axis that is used when indexing
  3789. with ``[]``.
  3790. Examples
  3791. --------
  3792. >>> df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6])),
  3793. ... index=['mouse', 'rabbit'],
  3794. ... columns=['one', 'two', 'three'])
  3795. >>> # select columns by name
  3796. >>> df.filter(items=['one', 'three'])
  3797. one three
  3798. mouse 1 3
  3799. rabbit 4 6
  3800. >>> # select columns by regular expression
  3801. >>> df.filter(regex='e$', axis=1)
  3802. one three
  3803. mouse 1 3
  3804. rabbit 4 6
  3805. >>> # select rows containing 'bbi'
  3806. >>> df.filter(like='bbi', axis=0)
  3807. one two three
  3808. rabbit 4 5 6
  3809. """
  3810. import re
  3811. nkw = com.count_not_none(items, like, regex)
  3812. if nkw > 1:
  3813. raise TypeError('Keyword arguments `items`, `like`, or `regex` '
  3814. 'are mutually exclusive')
  3815. if axis is None:
  3816. axis = self._info_axis_name
  3817. labels = self._get_axis(axis)
  3818. if items is not None:
  3819. name = self._get_axis_name(axis)
  3820. return self.reindex(
  3821. **{name: [r for r in items if r in labels]})
  3822. elif like:
  3823. def f(x):
  3824. return like in to_str(x)
  3825. values = labels.map(f)
  3826. return self.loc(axis=axis)[values]
  3827. elif regex:
  3828. def f(x):
  3829. return matcher.search(to_str(x)) is not None
  3830. matcher = re.compile(regex)
  3831. values = labels.map(f)
  3832. return self.loc(axis=axis)[values]
  3833. else:
  3834. raise TypeError('Must pass either `items`, `like`, or `regex`')
  3835. def head(self, n=5):
  3836. """
  3837. Return the first `n` rows.
  3838. This function returns the first `n` rows for the object based
  3839. on position. It is useful for quickly testing if your object
  3840. has the right type of data in it.
  3841. Parameters
  3842. ----------
  3843. n : int, default 5
  3844. Number of rows to select.
  3845. Returns
  3846. -------
  3847. obj_head : same type as caller
  3848. The first `n` rows of the caller object.
  3849. See Also
  3850. --------
  3851. DataFrame.tail: Returns the last `n` rows.
  3852. Examples
  3853. --------
  3854. >>> df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion',
  3855. ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']})
  3856. >>> df
  3857. animal
  3858. 0 alligator
  3859. 1 bee
  3860. 2 falcon
  3861. 3 lion
  3862. 4 monkey
  3863. 5 parrot
  3864. 6 shark
  3865. 7 whale
  3866. 8 zebra
  3867. Viewing the first 5 lines
  3868. >>> df.head()
  3869. animal
  3870. 0 alligator
  3871. 1 bee
  3872. 2 falcon
  3873. 3 lion
  3874. 4 monkey
  3875. Viewing the first `n` lines (three in this case)
  3876. >>> df.head(3)
  3877. animal
  3878. 0 alligator
  3879. 1 bee
  3880. 2 falcon
  3881. """
  3882. return self.iloc[:n]
  3883. def tail(self, n=5):
  3884. """
  3885. Return the last `n` rows.
  3886. This function returns last `n` rows from the object based on
  3887. position. It is useful for quickly verifying data, for example,
  3888. after sorting or appending rows.
  3889. Parameters
  3890. ----------
  3891. n : int, default 5
  3892. Number of rows to select.
  3893. Returns
  3894. -------
  3895. type of caller
  3896. The last `n` rows of the caller object.
  3897. See Also
  3898. --------
  3899. DataFrame.head : The first `n` rows of the caller object.
  3900. Examples
  3901. --------
  3902. >>> df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion',
  3903. ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']})
  3904. >>> df
  3905. animal
  3906. 0 alligator
  3907. 1 bee
  3908. 2 falcon
  3909. 3 lion
  3910. 4 monkey
  3911. 5 parrot
  3912. 6 shark
  3913. 7 whale
  3914. 8 zebra
  3915. Viewing the last 5 lines
  3916. >>> df.tail()
  3917. animal
  3918. 4 monkey
  3919. 5 parrot
  3920. 6 shark
  3921. 7 whale
  3922. 8 zebra
  3923. Viewing the last `n` lines (three in this case)
  3924. >>> df.tail(3)
  3925. animal
  3926. 6 shark
  3927. 7 whale
  3928. 8 zebra
  3929. """
  3930. if n == 0:
  3931. return self.iloc[0:0]
  3932. return self.iloc[-n:]
  3933. def sample(self, n=None, frac=None, replace=False, weights=None,
  3934. random_state=None, axis=None):
  3935. """
  3936. Return a random sample of items from an axis of object.
  3937. You can use `random_state` for reproducibility.
  3938. Parameters
  3939. ----------
  3940. n : int, optional
  3941. Number of items from axis to return. Cannot be used with `frac`.
  3942. Default = 1 if `frac` = None.
  3943. frac : float, optional
  3944. Fraction of axis items to return. Cannot be used with `n`.
  3945. replace : bool, default False
  3946. Sample with or without replacement.
  3947. weights : str or ndarray-like, optional
  3948. Default 'None' results in equal probability weighting.
  3949. If passed a Series, will align with target object on index. Index
  3950. values in weights not found in sampled object will be ignored and
  3951. index values in sampled object not in weights will be assigned
  3952. weights of zero.
  3953. If called on a DataFrame, will accept the name of a column
  3954. when axis = 0.
  3955. Unless weights are a Series, weights must be same length as axis
  3956. being sampled.
  3957. If weights do not sum to 1, they will be normalized to sum to 1.
  3958. Missing values in the weights column will be treated as zero.
  3959. Infinite values not allowed.
  3960. random_state : int or numpy.random.RandomState, optional
  3961. Seed for the random number generator (if int), or numpy RandomState
  3962. object.
  3963. axis : int or string, optional
  3964. Axis to sample. Accepts axis number or name. Default is stat axis
  3965. for given data type (0 for Series and DataFrames, 1 for Panels).
  3966. Returns
  3967. -------
  3968. Series or DataFrame
  3969. A new object of same type as caller containing `n` items randomly
  3970. sampled from the caller object.
  3971. See Also
  3972. --------
  3973. numpy.random.choice: Generates a random sample from a given 1-D numpy
  3974. array.
  3975. Examples
  3976. --------
  3977. >>> df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
  3978. ... 'num_wings': [2, 0, 0, 0],
  3979. ... 'num_specimen_seen': [10, 2, 1, 8]},
  3980. ... index=['falcon', 'dog', 'spider', 'fish'])
  3981. >>> df
  3982. num_legs num_wings num_specimen_seen
  3983. falcon 2 2 10
  3984. dog 4 0 2
  3985. spider 8 0 1
  3986. fish 0 0 8
  3987. Extract 3 random elements from the ``Series`` ``df['num_legs']``:
  3988. Note that we use `random_state` to ensure the reproducibility of
  3989. the examples.
  3990. >>> df['num_legs'].sample(n=3, random_state=1)
  3991. fish 0
  3992. spider 8
  3993. falcon 2
  3994. Name: num_legs, dtype: int64
  3995. A random 50% sample of the ``DataFrame`` with replacement:
  3996. >>> df.sample(frac=0.5, replace=True, random_state=1)
  3997. num_legs num_wings num_specimen_seen
  3998. dog 4 0 2
  3999. fish 0 0 8
  4000. Using a DataFrame column as weights. Rows with larger value in the
  4001. `num_specimen_seen` column are more likely to be sampled.
  4002. >>> df.sample(n=2, weights='num_specimen_seen', random_state=1)
  4003. num_legs num_wings num_specimen_seen
  4004. falcon 2 2 10
  4005. fish 0 0 8
  4006. """
  4007. if axis is None:
  4008. axis = self._stat_axis_number
  4009. axis = self._get_axis_number(axis)
  4010. axis_length = self.shape[axis]
  4011. # Process random_state argument
  4012. rs = com.random_state(random_state)
  4013. # Check weights for compliance
  4014. if weights is not None:
  4015. # If a series, align with frame
  4016. if isinstance(weights, pd.Series):
  4017. weights = weights.reindex(self.axes[axis])
  4018. # Strings acceptable if a dataframe and axis = 0
  4019. if isinstance(weights, string_types):
  4020. if isinstance(self, pd.DataFrame):
  4021. if axis == 0:
  4022. try:
  4023. weights = self[weights]
  4024. except KeyError:
  4025. raise KeyError("String passed to weights not a "
  4026. "valid column")
  4027. else:
  4028. raise ValueError("Strings can only be passed to "
  4029. "weights when sampling from rows on "
  4030. "a DataFrame")
  4031. else:
  4032. raise ValueError("Strings cannot be passed as weights "
  4033. "when sampling from a Series or Panel.")
  4034. weights = pd.Series(weights, dtype='float64')
  4035. if len(weights) != axis_length:
  4036. raise ValueError("Weights and axis to be sampled must be of "
  4037. "same length")
  4038. if (weights == np.inf).any() or (weights == -np.inf).any():
  4039. raise ValueError("weight vector may not include `inf` values")
  4040. if (weights < 0).any():
  4041. raise ValueError("weight vector many not include negative "
  4042. "values")
  4043. # If has nan, set to zero.
  4044. weights = weights.fillna(0)
  4045. # Renormalize if don't sum to 1
  4046. if weights.sum() != 1:
  4047. if weights.sum() != 0:
  4048. weights = weights / weights.sum()
  4049. else:
  4050. raise ValueError("Invalid weights: weights sum to zero")
  4051. weights = weights.values
  4052. # If no frac or n, default to n=1.
  4053. if n is None and frac is None:
  4054. n = 1
  4055. elif n is not None and frac is None and n % 1 != 0:
  4056. raise ValueError("Only integers accepted as `n` values")
  4057. elif n is None and frac is not None:
  4058. n = int(round(frac * axis_length))
  4059. elif n is not None and frac is not None:
  4060. raise ValueError('Please enter a value for `frac` OR `n`, not '
  4061. 'both')
  4062. # Check for negative sizes
  4063. if n < 0:
  4064. raise ValueError("A negative number of rows requested. Please "
  4065. "provide positive value.")
  4066. locs = rs.choice(axis_length, size=n, replace=replace, p=weights)
  4067. return self.take(locs, axis=axis, is_copy=False)
  4068. _shared_docs['pipe'] = (r"""
  4069. Apply func(self, \*args, \*\*kwargs).
  4070. Parameters
  4071. ----------
  4072. func : function
  4073. function to apply to the %(klass)s.
  4074. ``args``, and ``kwargs`` are passed into ``func``.
  4075. Alternatively a ``(callable, data_keyword)`` tuple where
  4076. ``data_keyword`` is a string indicating the keyword of
  4077. ``callable`` that expects the %(klass)s.
  4078. args : iterable, optional
  4079. positional arguments passed into ``func``.
  4080. kwargs : mapping, optional
  4081. a dictionary of keyword arguments passed into ``func``.
  4082. Returns
  4083. -------
  4084. object : the return type of ``func``.
  4085. See Also
  4086. --------
  4087. DataFrame.apply
  4088. DataFrame.applymap
  4089. Series.map
  4090. Notes
  4091. -----
  4092. Use ``.pipe`` when chaining together functions that expect
  4093. Series, DataFrames or GroupBy objects. Instead of writing
  4094. >>> f(g(h(df), arg1=a), arg2=b, arg3=c)
  4095. You can write
  4096. >>> (df.pipe(h)
  4097. ... .pipe(g, arg1=a)
  4098. ... .pipe(f, arg2=b, arg3=c)
  4099. ... )
  4100. If you have a function that takes the data as (say) the second
  4101. argument, pass a tuple indicating which keyword expects the
  4102. data. For example, suppose ``f`` takes its data as ``arg2``:
  4103. >>> (df.pipe(h)
  4104. ... .pipe(g, arg1=a)
  4105. ... .pipe((f, 'arg2'), arg1=a, arg3=c)
  4106. ... )
  4107. """)
  4108. @Appender(_shared_docs['pipe'] % _shared_doc_kwargs)
  4109. def pipe(self, func, *args, **kwargs):
  4110. return com._pipe(self, func, *args, **kwargs)
  4111. _shared_docs['aggregate'] = dedent("""
  4112. Aggregate using one or more operations over the specified axis.
  4113. %(versionadded)s
  4114. Parameters
  4115. ----------
  4116. func : function, str, list or dict
  4117. Function to use for aggregating the data. If a function, must either
  4118. work when passed a %(klass)s or when passed to %(klass)s.apply.
  4119. Accepted combinations are:
  4120. - function
  4121. - string function name
  4122. - list of functions and/or function names, e.g. ``[np.sum, 'mean']``
  4123. - dict of axis labels -> functions, function names or list of such.
  4124. %(axis)s
  4125. *args
  4126. Positional arguments to pass to `func`.
  4127. **kwargs
  4128. Keyword arguments to pass to `func`.
  4129. Returns
  4130. -------
  4131. scalar, Series or DataFrame
  4132. The return can be:
  4133. * scalar : when Series.agg is called with single function
  4134. * Series : when DataFrame.agg is called with a single function
  4135. * DataFrame : when DataFrame.agg is called with several functions
  4136. Return scalar, Series or DataFrame.
  4137. %(see_also)s
  4138. Notes
  4139. -----
  4140. `agg` is an alias for `aggregate`. Use the alias.
  4141. A passed user-defined-function will be passed a Series for evaluation.
  4142. %(examples)s""")
  4143. _shared_docs['transform'] = ("""
  4144. Call ``func`` on self producing a %(klass)s with transformed values
  4145. and that has the same axis length as self.
  4146. .. versionadded:: 0.20.0
  4147. Parameters
  4148. ----------
  4149. func : function, str, list or dict
  4150. Function to use for transforming the data. If a function, must either
  4151. work when passed a %(klass)s or when passed to %(klass)s.apply.
  4152. Accepted combinations are:
  4153. - function
  4154. - string function name
  4155. - list of functions and/or function names, e.g. ``[np.exp. 'sqrt']``
  4156. - dict of axis labels -> functions, function names or list of such.
  4157. %(axis)s
  4158. *args
  4159. Positional arguments to pass to `func`.
  4160. **kwargs
  4161. Keyword arguments to pass to `func`.
  4162. Returns
  4163. -------
  4164. %(klass)s
  4165. A %(klass)s that must have the same length as self.
  4166. Raises
  4167. ------
  4168. ValueError : If the returned %(klass)s has a different length than self.
  4169. See Also
  4170. --------
  4171. %(klass)s.agg : Only perform aggregating type operations.
  4172. %(klass)s.apply : Invoke function on a %(klass)s.
  4173. Examples
  4174. --------
  4175. >>> df = pd.DataFrame({'A': range(3), 'B': range(1, 4)})
  4176. >>> df
  4177. A B
  4178. 0 0 1
  4179. 1 1 2
  4180. 2 2 3
  4181. >>> df.transform(lambda x: x + 1)
  4182. A B
  4183. 0 1 2
  4184. 1 2 3
  4185. 2 3 4
  4186. Even though the resulting %(klass)s must have the same length as the
  4187. input %(klass)s, it is possible to provide several input functions:
  4188. >>> s = pd.Series(range(3))
  4189. >>> s
  4190. 0 0
  4191. 1 1
  4192. 2 2
  4193. dtype: int64
  4194. >>> s.transform([np.sqrt, np.exp])
  4195. sqrt exp
  4196. 0 0.000000 1.000000
  4197. 1 1.000000 2.718282
  4198. 2 1.414214 7.389056
  4199. """)
  4200. # ----------------------------------------------------------------------
  4201. # Attribute access
  4202. def __finalize__(self, other, method=None, **kwargs):
  4203. """
  4204. Propagate metadata from other to self.
  4205. Parameters
  4206. ----------
  4207. other : the object from which to get the attributes that we are going
  4208. to propagate
  4209. method : optional, a passed method name ; possibly to take different
  4210. types of propagation actions based on this
  4211. """
  4212. if isinstance(other, NDFrame):
  4213. for name in self._metadata:
  4214. object.__setattr__(self, name, getattr(other, name, None))
  4215. return self
  4216. def __getattr__(self, name):
  4217. """After regular attribute access, try looking up the name
  4218. This allows simpler access to columns for interactive use.
  4219. """
  4220. # Note: obj.x will always call obj.__getattribute__('x') prior to
  4221. # calling obj.__getattr__('x').
  4222. if (name in self._internal_names_set or name in self._metadata or
  4223. name in self._accessors):
  4224. return object.__getattribute__(self, name)
  4225. else:
  4226. if self._info_axis._can_hold_identifiers_and_holds_name(name):
  4227. return self[name]
  4228. return object.__getattribute__(self, name)
  4229. def __setattr__(self, name, value):
  4230. """After regular attribute access, try setting the name
  4231. This allows simpler access to columns for interactive use.
  4232. """
  4233. # first try regular attribute access via __getattribute__, so that
  4234. # e.g. ``obj.x`` and ``obj.x = 4`` will always reference/modify
  4235. # the same attribute.
  4236. try:
  4237. object.__getattribute__(self, name)
  4238. return object.__setattr__(self, name, value)
  4239. except AttributeError:
  4240. pass
  4241. # if this fails, go on to more involved attribute setting
  4242. # (note that this matches __getattr__, above).
  4243. if name in self._internal_names_set:
  4244. object.__setattr__(self, name, value)
  4245. elif name in self._metadata:
  4246. object.__setattr__(self, name, value)
  4247. else:
  4248. try:
  4249. existing = getattr(self, name)
  4250. if isinstance(existing, Index):
  4251. object.__setattr__(self, name, value)
  4252. elif name in self._info_axis:
  4253. self[name] = value
  4254. else:
  4255. object.__setattr__(self, name, value)
  4256. except (AttributeError, TypeError):
  4257. if isinstance(self, ABCDataFrame) and (is_list_like(value)):
  4258. warnings.warn("Pandas doesn't allow columns to be "
  4259. "created via a new attribute name - see "
  4260. "https://pandas.pydata.org/pandas-docs/"
  4261. "stable/indexing.html#attribute-access",
  4262. stacklevel=2)
  4263. object.__setattr__(self, name, value)
  4264. def _dir_additions(self):
  4265. """ add the string-like attributes from the info_axis.
  4266. If info_axis is a MultiIndex, it's first level values are used.
  4267. """
  4268. additions = {c for c in self._info_axis.unique(level=0)[:100]
  4269. if isinstance(c, string_types) and isidentifier(c)}
  4270. return super(NDFrame, self)._dir_additions().union(additions)
  4271. # ----------------------------------------------------------------------
  4272. # Getting and setting elements
  4273. # ----------------------------------------------------------------------
  4274. # Consolidation of internals
  4275. def _protect_consolidate(self, f):
  4276. """Consolidate _data -- if the blocks have changed, then clear the
  4277. cache
  4278. """
  4279. blocks_before = len(self._data.blocks)
  4280. result = f()
  4281. if len(self._data.blocks) != blocks_before:
  4282. self._clear_item_cache()
  4283. return result
  4284. def _consolidate_inplace(self):
  4285. """Consolidate data in place and return None"""
  4286. def f():
  4287. self._data = self._data.consolidate()
  4288. self._protect_consolidate(f)
  4289. def _consolidate(self, inplace=False):
  4290. """
  4291. Compute NDFrame with "consolidated" internals (data of each dtype
  4292. grouped together in a single ndarray).
  4293. Parameters
  4294. ----------
  4295. inplace : boolean, default False
  4296. If False return new object, otherwise modify existing object
  4297. Returns
  4298. -------
  4299. consolidated : same type as caller
  4300. """
  4301. inplace = validate_bool_kwarg(inplace, 'inplace')
  4302. if inplace:
  4303. self._consolidate_inplace()
  4304. else:
  4305. f = lambda: self._data.consolidate()
  4306. cons_data = self._protect_consolidate(f)
  4307. return self._constructor(cons_data).__finalize__(self)
  4308. @property
  4309. def _is_mixed_type(self):
  4310. f = lambda: self._data.is_mixed_type
  4311. return self._protect_consolidate(f)
  4312. @property
  4313. def _is_numeric_mixed_type(self):
  4314. f = lambda: self._data.is_numeric_mixed_type
  4315. return self._protect_consolidate(f)
  4316. @property
  4317. def _is_datelike_mixed_type(self):
  4318. f = lambda: self._data.is_datelike_mixed_type
  4319. return self._protect_consolidate(f)
  4320. def _check_inplace_setting(self, value):
  4321. """ check whether we allow in-place setting with this type of value """
  4322. if self._is_mixed_type:
  4323. if not self._is_numeric_mixed_type:
  4324. # allow an actual np.nan thru
  4325. try:
  4326. if np.isnan(value):
  4327. return True
  4328. except Exception:
  4329. pass
  4330. raise TypeError('Cannot do inplace boolean setting on '
  4331. 'mixed-types with a non np.nan value')
  4332. return True
  4333. def _get_numeric_data(self):
  4334. return self._constructor(
  4335. self._data.get_numeric_data()).__finalize__(self)
  4336. def _get_bool_data(self):
  4337. return self._constructor(self._data.get_bool_data()).__finalize__(self)
  4338. # ----------------------------------------------------------------------
  4339. # Internal Interface Methods
  4340. def as_matrix(self, columns=None):
  4341. """
  4342. Convert the frame to its Numpy-array representation.
  4343. .. deprecated:: 0.23.0
  4344. Use :meth:`DataFrame.values` instead.
  4345. Parameters
  4346. ----------
  4347. columns : list, optional, default:None
  4348. If None, return all columns, otherwise, returns specified columns.
  4349. Returns
  4350. -------
  4351. values : ndarray
  4352. If the caller is heterogeneous and contains booleans or objects,
  4353. the result will be of dtype=object. See Notes.
  4354. See Also
  4355. --------
  4356. DataFrame.values
  4357. Notes
  4358. -----
  4359. Return is NOT a Numpy-matrix, rather, a Numpy-array.
  4360. The dtype will be a lower-common-denominator dtype (implicit
  4361. upcasting); that is to say if the dtypes (even of numeric types)
  4362. are mixed, the one that accommodates all will be chosen. Use this
  4363. with care if you are not dealing with the blocks.
  4364. e.g. If the dtypes are float16 and float32, dtype will be upcast to
  4365. float32. If dtypes are int32 and uint8, dtype will be upcase to
  4366. int32. By numpy.find_common_type convention, mixing int64 and uint64
  4367. will result in a float64 dtype.
  4368. This method is provided for backwards compatibility. Generally,
  4369. it is recommended to use '.values'.
  4370. """
  4371. warnings.warn("Method .as_matrix will be removed in a future version. "
  4372. "Use .values instead.", FutureWarning, stacklevel=2)
  4373. self._consolidate_inplace()
  4374. return self._data.as_array(transpose=self._AXIS_REVERSED,
  4375. items=columns)
  4376. @property
  4377. def values(self):
  4378. """
  4379. Return a Numpy representation of the DataFrame.
  4380. .. warning::
  4381. We recommend using :meth:`DataFrame.to_numpy` instead.
  4382. Only the values in the DataFrame will be returned, the axes labels
  4383. will be removed.
  4384. Returns
  4385. -------
  4386. numpy.ndarray
  4387. The values of the DataFrame.
  4388. See Also
  4389. --------
  4390. DataFrame.to_numpy : Recommended alternative to this method.
  4391. DataFrame.index : Retrieve the index labels.
  4392. DataFrame.columns : Retrieving the column names.
  4393. Notes
  4394. -----
  4395. The dtype will be a lower-common-denominator dtype (implicit
  4396. upcasting); that is to say if the dtypes (even of numeric types)
  4397. are mixed, the one that accommodates all will be chosen. Use this
  4398. with care if you are not dealing with the blocks.
  4399. e.g. If the dtypes are float16 and float32, dtype will be upcast to
  4400. float32. If dtypes are int32 and uint8, dtype will be upcast to
  4401. int32. By :func:`numpy.find_common_type` convention, mixing int64
  4402. and uint64 will result in a float64 dtype.
  4403. Examples
  4404. --------
  4405. A DataFrame where all columns are the same type (e.g., int64) results
  4406. in an array of the same type.
  4407. >>> df = pd.DataFrame({'age': [ 3, 29],
  4408. ... 'height': [94, 170],
  4409. ... 'weight': [31, 115]})
  4410. >>> df
  4411. age height weight
  4412. 0 3 94 31
  4413. 1 29 170 115
  4414. >>> df.dtypes
  4415. age int64
  4416. height int64
  4417. weight int64
  4418. dtype: object
  4419. >>> df.values
  4420. array([[ 3, 94, 31],
  4421. [ 29, 170, 115]], dtype=int64)
  4422. A DataFrame with mixed type columns(e.g., str/object, int64, float32)
  4423. results in an ndarray of the broadest type that accommodates these
  4424. mixed types (e.g., object).
  4425. >>> df2 = pd.DataFrame([('parrot', 24.0, 'second'),
  4426. ... ('lion', 80.5, 1),
  4427. ... ('monkey', np.nan, None)],
  4428. ... columns=('name', 'max_speed', 'rank'))
  4429. >>> df2.dtypes
  4430. name object
  4431. max_speed float64
  4432. rank object
  4433. dtype: object
  4434. >>> df2.values
  4435. array([['parrot', 24.0, 'second'],
  4436. ['lion', 80.5, 1],
  4437. ['monkey', nan, None]], dtype=object)
  4438. """
  4439. self._consolidate_inplace()
  4440. return self._data.as_array(transpose=self._AXIS_REVERSED)
  4441. @property
  4442. def _values(self):
  4443. """internal implementation"""
  4444. return self.values
  4445. @property
  4446. def _get_values(self):
  4447. # compat
  4448. return self.values
  4449. def get_values(self):
  4450. """
  4451. Return an ndarray after converting sparse values to dense.
  4452. This is the same as ``.values`` for non-sparse data. For sparse
  4453. data contained in a `SparseArray`, the data are first
  4454. converted to a dense representation.
  4455. Returns
  4456. -------
  4457. numpy.ndarray
  4458. Numpy representation of DataFrame.
  4459. See Also
  4460. --------
  4461. values : Numpy representation of DataFrame.
  4462. SparseArray : Container for sparse data.
  4463. Examples
  4464. --------
  4465. >>> df = pd.DataFrame({'a': [1, 2], 'b': [True, False],
  4466. ... 'c': [1.0, 2.0]})
  4467. >>> df
  4468. a b c
  4469. 0 1 True 1.0
  4470. 1 2 False 2.0
  4471. >>> df.get_values()
  4472. array([[1, True, 1.0], [2, False, 2.0]], dtype=object)
  4473. >>> df = pd.DataFrame({"a": pd.SparseArray([1, None, None]),
  4474. ... "c": [1.0, 2.0, 3.0]})
  4475. >>> df
  4476. a c
  4477. 0 1.0 1.0
  4478. 1 NaN 2.0
  4479. 2 NaN 3.0
  4480. >>> df.get_values()
  4481. array([[ 1., 1.],
  4482. [nan, 2.],
  4483. [nan, 3.]])
  4484. """
  4485. return self.values
  4486. def get_dtype_counts(self):
  4487. """
  4488. Return counts of unique dtypes in this object.
  4489. Returns
  4490. -------
  4491. dtype : Series
  4492. Series with the count of columns with each dtype.
  4493. See Also
  4494. --------
  4495. dtypes : Return the dtypes in this object.
  4496. Examples
  4497. --------
  4498. >>> a = [['a', 1, 1.0], ['b', 2, 2.0], ['c', 3, 3.0]]
  4499. >>> df = pd.DataFrame(a, columns=['str', 'int', 'float'])
  4500. >>> df
  4501. str int float
  4502. 0 a 1 1.0
  4503. 1 b 2 2.0
  4504. 2 c 3 3.0
  4505. >>> df.get_dtype_counts()
  4506. float64 1
  4507. int64 1
  4508. object 1
  4509. dtype: int64
  4510. """
  4511. from pandas import Series
  4512. return Series(self._data.get_dtype_counts())
  4513. def get_ftype_counts(self):
  4514. """
  4515. Return counts of unique ftypes in this object.
  4516. .. deprecated:: 0.23.0
  4517. This is useful for SparseDataFrame or for DataFrames containing
  4518. sparse arrays.
  4519. Returns
  4520. -------
  4521. dtype : Series
  4522. Series with the count of columns with each type and
  4523. sparsity (dense/sparse).
  4524. See Also
  4525. --------
  4526. ftypes : Return ftypes (indication of sparse/dense and dtype) in
  4527. this object.
  4528. Examples
  4529. --------
  4530. >>> a = [['a', 1, 1.0], ['b', 2, 2.0], ['c', 3, 3.0]]
  4531. >>> df = pd.DataFrame(a, columns=['str', 'int', 'float'])
  4532. >>> df
  4533. str int float
  4534. 0 a 1 1.0
  4535. 1 b 2 2.0
  4536. 2 c 3 3.0
  4537. >>> df.get_ftype_counts() # doctest: +SKIP
  4538. float64:dense 1
  4539. int64:dense 1
  4540. object:dense 1
  4541. dtype: int64
  4542. """
  4543. warnings.warn("get_ftype_counts is deprecated and will "
  4544. "be removed in a future version",
  4545. FutureWarning, stacklevel=2)
  4546. from pandas import Series
  4547. return Series(self._data.get_ftype_counts())
  4548. @property
  4549. def dtypes(self):
  4550. """
  4551. Return the dtypes in the DataFrame.
  4552. This returns a Series with the data type of each column.
  4553. The result's index is the original DataFrame's columns. Columns
  4554. with mixed types are stored with the ``object`` dtype. See
  4555. :ref:`the User Guide <basics.dtypes>` for more.
  4556. Returns
  4557. -------
  4558. pandas.Series
  4559. The data type of each column.
  4560. See Also
  4561. --------
  4562. DataFrame.ftypes : Dtype and sparsity information.
  4563. Examples
  4564. --------
  4565. >>> df = pd.DataFrame({'float': [1.0],
  4566. ... 'int': [1],
  4567. ... 'datetime': [pd.Timestamp('20180310')],
  4568. ... 'string': ['foo']})
  4569. >>> df.dtypes
  4570. float float64
  4571. int int64
  4572. datetime datetime64[ns]
  4573. string object
  4574. dtype: object
  4575. """
  4576. from pandas import Series
  4577. return Series(self._data.get_dtypes(), index=self._info_axis,
  4578. dtype=np.object_)
  4579. @property
  4580. def ftypes(self):
  4581. """
  4582. Return the ftypes (indication of sparse/dense and dtype) in DataFrame.
  4583. This returns a Series with the data type of each column.
  4584. The result's index is the original DataFrame's columns. Columns
  4585. with mixed types are stored with the ``object`` dtype. See
  4586. :ref:`the User Guide <basics.dtypes>` for more.
  4587. Returns
  4588. -------
  4589. pandas.Series
  4590. The data type and indication of sparse/dense of each column.
  4591. See Also
  4592. --------
  4593. DataFrame.dtypes: Series with just dtype information.
  4594. SparseDataFrame : Container for sparse tabular data.
  4595. Notes
  4596. -----
  4597. Sparse data should have the same dtypes as its dense representation.
  4598. Examples
  4599. --------
  4600. >>> arr = np.random.RandomState(0).randn(100, 4)
  4601. >>> arr[arr < .8] = np.nan
  4602. >>> pd.DataFrame(arr).ftypes
  4603. 0 float64:dense
  4604. 1 float64:dense
  4605. 2 float64:dense
  4606. 3 float64:dense
  4607. dtype: object
  4608. >>> pd.SparseDataFrame(arr).ftypes
  4609. 0 float64:sparse
  4610. 1 float64:sparse
  4611. 2 float64:sparse
  4612. 3 float64:sparse
  4613. dtype: object
  4614. """
  4615. from pandas import Series
  4616. return Series(self._data.get_ftypes(), index=self._info_axis,
  4617. dtype=np.object_)
  4618. def as_blocks(self, copy=True):
  4619. """
  4620. Convert the frame to a dict of dtype -> Constructor Types that each has
  4621. a homogeneous dtype.
  4622. .. deprecated:: 0.21.0
  4623. NOTE: the dtypes of the blocks WILL BE PRESERVED HERE (unlike in
  4624. as_matrix)
  4625. Parameters
  4626. ----------
  4627. copy : boolean, default True
  4628. Returns
  4629. -------
  4630. values : a dict of dtype -> Constructor Types
  4631. """
  4632. warnings.warn("as_blocks is deprecated and will "
  4633. "be removed in a future version",
  4634. FutureWarning, stacklevel=2)
  4635. return self._to_dict_of_blocks(copy=copy)
  4636. @property
  4637. def blocks(self):
  4638. """
  4639. Internal property, property synonym for as_blocks().
  4640. .. deprecated:: 0.21.0
  4641. """
  4642. return self.as_blocks()
  4643. def _to_dict_of_blocks(self, copy=True):
  4644. """
  4645. Return a dict of dtype -> Constructor Types that
  4646. each is a homogeneous dtype.
  4647. Internal ONLY
  4648. """
  4649. return {k: self._constructor(v).__finalize__(self)
  4650. for k, v, in self._data.to_dict(copy=copy).items()}
  4651. def astype(self, dtype, copy=True, errors='raise', **kwargs):
  4652. """
  4653. Cast a pandas object to a specified dtype ``dtype``.
  4654. Parameters
  4655. ----------
  4656. dtype : data type, or dict of column name -> data type
  4657. Use a numpy.dtype or Python type to cast entire pandas object to
  4658. the same type. Alternatively, use {col: dtype, ...}, where col is a
  4659. column label and dtype is a numpy.dtype or Python type to cast one
  4660. or more of the DataFrame's columns to column-specific types.
  4661. copy : bool, default True
  4662. Return a copy when ``copy=True`` (be very careful setting
  4663. ``copy=False`` as changes to values then may propagate to other
  4664. pandas objects).
  4665. errors : {'raise', 'ignore'}, default 'raise'
  4666. Control raising of exceptions on invalid data for provided dtype.
  4667. - ``raise`` : allow exceptions to be raised
  4668. - ``ignore`` : suppress exceptions. On error return original object
  4669. .. versionadded:: 0.20.0
  4670. kwargs : keyword arguments to pass on to the constructor
  4671. Returns
  4672. -------
  4673. casted : same type as caller
  4674. See Also
  4675. --------
  4676. to_datetime : Convert argument to datetime.
  4677. to_timedelta : Convert argument to timedelta.
  4678. to_numeric : Convert argument to a numeric type.
  4679. numpy.ndarray.astype : Cast a numpy array to a specified type.
  4680. Examples
  4681. --------
  4682. >>> ser = pd.Series([1, 2], dtype='int32')
  4683. >>> ser
  4684. 0 1
  4685. 1 2
  4686. dtype: int32
  4687. >>> ser.astype('int64')
  4688. 0 1
  4689. 1 2
  4690. dtype: int64
  4691. Convert to categorical type:
  4692. >>> ser.astype('category')
  4693. 0 1
  4694. 1 2
  4695. dtype: category
  4696. Categories (2, int64): [1, 2]
  4697. Convert to ordered categorical type with custom ordering:
  4698. >>> cat_dtype = pd.api.types.CategoricalDtype(
  4699. ... categories=[2, 1], ordered=True)
  4700. >>> ser.astype(cat_dtype)
  4701. 0 1
  4702. 1 2
  4703. dtype: category
  4704. Categories (2, int64): [2 < 1]
  4705. Note that using ``copy=False`` and changing data on a new
  4706. pandas object may propagate changes:
  4707. >>> s1 = pd.Series([1,2])
  4708. >>> s2 = s1.astype('int64', copy=False)
  4709. >>> s2[0] = 10
  4710. >>> s1 # note that s1[0] has changed too
  4711. 0 10
  4712. 1 2
  4713. dtype: int64
  4714. """
  4715. if is_dict_like(dtype):
  4716. if self.ndim == 1: # i.e. Series
  4717. if len(dtype) > 1 or self.name not in dtype:
  4718. raise KeyError('Only the Series name can be used for '
  4719. 'the key in Series dtype mappings.')
  4720. new_type = dtype[self.name]
  4721. return self.astype(new_type, copy, errors, **kwargs)
  4722. elif self.ndim > 2:
  4723. raise NotImplementedError(
  4724. 'astype() only accepts a dtype arg of type dict when '
  4725. 'invoked on Series and DataFrames. A single dtype must be '
  4726. 'specified when invoked on a Panel.'
  4727. )
  4728. for col_name in dtype.keys():
  4729. if col_name not in self:
  4730. raise KeyError('Only a column name can be used for the '
  4731. 'key in a dtype mappings argument.')
  4732. results = []
  4733. for col_name, col in self.iteritems():
  4734. if col_name in dtype:
  4735. results.append(col.astype(dtype[col_name], copy=copy))
  4736. else:
  4737. results.append(results.append(col.copy() if copy else col))
  4738. elif is_extension_array_dtype(dtype) and self.ndim > 1:
  4739. # GH 18099/22869: columnwise conversion to extension dtype
  4740. # GH 24704: use iloc to handle duplicate column names
  4741. results = (self.iloc[:, i].astype(dtype, copy=copy)
  4742. for i in range(len(self.columns)))
  4743. else:
  4744. # else, only a single dtype is given
  4745. new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors,
  4746. **kwargs)
  4747. return self._constructor(new_data).__finalize__(self)
  4748. # GH 19920: retain column metadata after concat
  4749. result = pd.concat(results, axis=1, copy=False)
  4750. result.columns = self.columns
  4751. return result
  4752. def copy(self, deep=True):
  4753. """
  4754. Make a copy of this object's indices and data.
  4755. When ``deep=True`` (default), a new object will be created with a
  4756. copy of the calling object's data and indices. Modifications to
  4757. the data or indices of the copy will not be reflected in the
  4758. original object (see notes below).
  4759. When ``deep=False``, a new object will be created without copying
  4760. the calling object's data or index (only references to the data
  4761. and index are copied). Any changes to the data of the original
  4762. will be reflected in the shallow copy (and vice versa).
  4763. Parameters
  4764. ----------
  4765. deep : bool, default True
  4766. Make a deep copy, including a copy of the data and the indices.
  4767. With ``deep=False`` neither the indices nor the data are copied.
  4768. Returns
  4769. -------
  4770. copy : Series, DataFrame or Panel
  4771. Object type matches caller.
  4772. Notes
  4773. -----
  4774. When ``deep=True``, data is copied but actual Python objects
  4775. will not be copied recursively, only the reference to the object.
  4776. This is in contrast to `copy.deepcopy` in the Standard Library,
  4777. which recursively copies object data (see examples below).
  4778. While ``Index`` objects are copied when ``deep=True``, the underlying
  4779. numpy array is not copied for performance reasons. Since ``Index`` is
  4780. immutable, the underlying data can be safely shared and a copy
  4781. is not needed.
  4782. Examples
  4783. --------
  4784. >>> s = pd.Series([1, 2], index=["a", "b"])
  4785. >>> s
  4786. a 1
  4787. b 2
  4788. dtype: int64
  4789. >>> s_copy = s.copy()
  4790. >>> s_copy
  4791. a 1
  4792. b 2
  4793. dtype: int64
  4794. **Shallow copy versus default (deep) copy:**
  4795. >>> s = pd.Series([1, 2], index=["a", "b"])
  4796. >>> deep = s.copy()
  4797. >>> shallow = s.copy(deep=False)
  4798. Shallow copy shares data and index with original.
  4799. >>> s is shallow
  4800. False
  4801. >>> s.values is shallow.values and s.index is shallow.index
  4802. True
  4803. Deep copy has own copy of data and index.
  4804. >>> s is deep
  4805. False
  4806. >>> s.values is deep.values or s.index is deep.index
  4807. False
  4808. Updates to the data shared by shallow copy and original is reflected
  4809. in both; deep copy remains unchanged.
  4810. >>> s[0] = 3
  4811. >>> shallow[1] = 4
  4812. >>> s
  4813. a 3
  4814. b 4
  4815. dtype: int64
  4816. >>> shallow
  4817. a 3
  4818. b 4
  4819. dtype: int64
  4820. >>> deep
  4821. a 1
  4822. b 2
  4823. dtype: int64
  4824. Note that when copying an object containing Python objects, a deep copy
  4825. will copy the data, but will not do so recursively. Updating a nested
  4826. data object will be reflected in the deep copy.
  4827. >>> s = pd.Series([[1, 2], [3, 4]])
  4828. >>> deep = s.copy()
  4829. >>> s[0][0] = 10
  4830. >>> s
  4831. 0 [10, 2]
  4832. 1 [3, 4]
  4833. dtype: object
  4834. >>> deep
  4835. 0 [10, 2]
  4836. 1 [3, 4]
  4837. dtype: object
  4838. """
  4839. data = self._data.copy(deep=deep)
  4840. return self._constructor(data).__finalize__(self)
  4841. def __copy__(self, deep=True):
  4842. return self.copy(deep=deep)
  4843. def __deepcopy__(self, memo=None):
  4844. """
  4845. Parameters
  4846. ----------
  4847. memo, default None
  4848. Standard signature. Unused
  4849. """
  4850. if memo is None:
  4851. memo = {}
  4852. return self.copy(deep=True)
  4853. def _convert(self, datetime=False, numeric=False, timedelta=False,
  4854. coerce=False, copy=True):
  4855. """
  4856. Attempt to infer better dtype for object columns
  4857. Parameters
  4858. ----------
  4859. datetime : boolean, default False
  4860. If True, convert to date where possible.
  4861. numeric : boolean, default False
  4862. If True, attempt to convert to numbers (including strings), with
  4863. unconvertible values becoming NaN.
  4864. timedelta : boolean, default False
  4865. If True, convert to timedelta where possible.
  4866. coerce : boolean, default False
  4867. If True, force conversion with unconvertible values converted to
  4868. nulls (NaN or NaT)
  4869. copy : boolean, default True
  4870. If True, return a copy even if no copy is necessary (e.g. no
  4871. conversion was done). Note: This is meant for internal use, and
  4872. should not be confused with inplace.
  4873. Returns
  4874. -------
  4875. converted : same as input object
  4876. """
  4877. return self._constructor(
  4878. self._data.convert(datetime=datetime, numeric=numeric,
  4879. timedelta=timedelta, coerce=coerce,
  4880. copy=copy)).__finalize__(self)
  4881. def convert_objects(self, convert_dates=True, convert_numeric=False,
  4882. convert_timedeltas=True, copy=True):
  4883. """
  4884. Attempt to infer better dtype for object columns.
  4885. .. deprecated:: 0.21.0
  4886. Parameters
  4887. ----------
  4888. convert_dates : boolean, default True
  4889. If True, convert to date where possible. If 'coerce', force
  4890. conversion, with unconvertible values becoming NaT.
  4891. convert_numeric : boolean, default False
  4892. If True, attempt to coerce to numbers (including strings), with
  4893. unconvertible values becoming NaN.
  4894. convert_timedeltas : boolean, default True
  4895. If True, convert to timedelta where possible. If 'coerce', force
  4896. conversion, with unconvertible values becoming NaT.
  4897. copy : boolean, default True
  4898. If True, return a copy even if no copy is necessary (e.g. no
  4899. conversion was done). Note: This is meant for internal use, and
  4900. should not be confused with inplace.
  4901. Returns
  4902. -------
  4903. converted : same as input object
  4904. See Also
  4905. --------
  4906. to_datetime : Convert argument to datetime.
  4907. to_timedelta : Convert argument to timedelta.
  4908. to_numeric : Convert argument to numeric type.
  4909. """
  4910. msg = ("convert_objects is deprecated. To re-infer data dtypes for "
  4911. "object columns, use {klass}.infer_objects()\nFor all "
  4912. "other conversions use the data-type specific converters "
  4913. "pd.to_datetime, pd.to_timedelta and pd.to_numeric."
  4914. ).format(klass=self.__class__.__name__)
  4915. warnings.warn(msg, FutureWarning, stacklevel=2)
  4916. return self._constructor(
  4917. self._data.convert(convert_dates=convert_dates,
  4918. convert_numeric=convert_numeric,
  4919. convert_timedeltas=convert_timedeltas,
  4920. copy=copy)).__finalize__(self)
  4921. def infer_objects(self):
  4922. """
  4923. Attempt to infer better dtypes for object columns.
  4924. Attempts soft conversion of object-dtyped
  4925. columns, leaving non-object and unconvertible
  4926. columns unchanged. The inference rules are the
  4927. same as during normal Series/DataFrame construction.
  4928. .. versionadded:: 0.21.0
  4929. Returns
  4930. -------
  4931. converted : same type as input object
  4932. See Also
  4933. --------
  4934. to_datetime : Convert argument to datetime.
  4935. to_timedelta : Convert argument to timedelta.
  4936. to_numeric : Convert argument to numeric type.
  4937. Examples
  4938. --------
  4939. >>> df = pd.DataFrame({"A": ["a", 1, 2, 3]})
  4940. >>> df = df.iloc[1:]
  4941. >>> df
  4942. A
  4943. 1 1
  4944. 2 2
  4945. 3 3
  4946. >>> df.dtypes
  4947. A object
  4948. dtype: object
  4949. >>> df.infer_objects().dtypes
  4950. A int64
  4951. dtype: object
  4952. """
  4953. # numeric=False necessary to only soft convert;
  4954. # python objects will still be converted to
  4955. # native numpy numeric types
  4956. return self._constructor(
  4957. self._data.convert(datetime=True, numeric=False,
  4958. timedelta=True, coerce=False,
  4959. copy=True)).__finalize__(self)
  4960. # ----------------------------------------------------------------------
  4961. # Filling NA's
  4962. def fillna(self, value=None, method=None, axis=None, inplace=False,
  4963. limit=None, downcast=None):
  4964. """
  4965. Fill NA/NaN values using the specified method.
  4966. Parameters
  4967. ----------
  4968. value : scalar, dict, Series, or DataFrame
  4969. Value to use to fill holes (e.g. 0), alternately a
  4970. dict/Series/DataFrame of values specifying which value to use for
  4971. each index (for a Series) or column (for a DataFrame). Values not
  4972. in the dict/Series/DataFrame will not be filled. This value cannot
  4973. be a list.
  4974. method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
  4975. Method to use for filling holes in reindexed Series
  4976. pad / ffill: propagate last valid observation forward to next valid
  4977. backfill / bfill: use next valid observation to fill gap.
  4978. axis : %(axes_single_arg)s
  4979. Axis along which to fill missing values.
  4980. inplace : bool, default False
  4981. If True, fill in-place. Note: this will modify any
  4982. other views on this object (e.g., a no-copy slice for a column in a
  4983. DataFrame).
  4984. limit : int, default None
  4985. If method is specified, this is the maximum number of consecutive
  4986. NaN values to forward/backward fill. In other words, if there is
  4987. a gap with more than this number of consecutive NaNs, it will only
  4988. be partially filled. If method is not specified, this is the
  4989. maximum number of entries along the entire axis where NaNs will be
  4990. filled. Must be greater than 0 if not None.
  4991. downcast : dict, default is None
  4992. A dict of item->dtype of what to downcast if possible,
  4993. or the string 'infer' which will try to downcast to an appropriate
  4994. equal type (e.g. float64 to int64 if possible).
  4995. Returns
  4996. -------
  4997. %(klass)s
  4998. Object with missing values filled.
  4999. See Also
  5000. --------
  5001. interpolate : Fill NaN values using interpolation.
  5002. reindex : Conform object to new index.
  5003. asfreq : Convert TimeSeries to specified frequency.
  5004. Examples
  5005. --------
  5006. >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0],
  5007. ... [3, 4, np.nan, 1],
  5008. ... [np.nan, np.nan, np.nan, 5],
  5009. ... [np.nan, 3, np.nan, 4]],
  5010. ... columns=list('ABCD'))
  5011. >>> df
  5012. A B C D
  5013. 0 NaN 2.0 NaN 0
  5014. 1 3.0 4.0 NaN 1
  5015. 2 NaN NaN NaN 5
  5016. 3 NaN 3.0 NaN 4
  5017. Replace all NaN elements with 0s.
  5018. >>> df.fillna(0)
  5019. A B C D
  5020. 0 0.0 2.0 0.0 0
  5021. 1 3.0 4.0 0.0 1
  5022. 2 0.0 0.0 0.0 5
  5023. 3 0.0 3.0 0.0 4
  5024. We can also propagate non-null values forward or backward.
  5025. >>> df.fillna(method='ffill')
  5026. A B C D
  5027. 0 NaN 2.0 NaN 0
  5028. 1 3.0 4.0 NaN 1
  5029. 2 3.0 4.0 NaN 5
  5030. 3 3.0 3.0 NaN 4
  5031. Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1,
  5032. 2, and 3 respectively.
  5033. >>> values = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
  5034. >>> df.fillna(value=values)
  5035. A B C D
  5036. 0 0.0 2.0 2.0 0
  5037. 1 3.0 4.0 2.0 1
  5038. 2 0.0 1.0 2.0 5
  5039. 3 0.0 3.0 2.0 4
  5040. Only replace the first NaN element.
  5041. >>> df.fillna(value=values, limit=1)
  5042. A B C D
  5043. 0 0.0 2.0 2.0 0
  5044. 1 3.0 4.0 NaN 1
  5045. 2 NaN 1.0 NaN 5
  5046. 3 NaN 3.0 NaN 4
  5047. """
  5048. inplace = validate_bool_kwarg(inplace, 'inplace')
  5049. value, method = validate_fillna_kwargs(value, method)
  5050. self._consolidate_inplace()
  5051. # set the default here, so functions examining the signaure
  5052. # can detect if something was set (e.g. in groupby) (GH9221)
  5053. if axis is None:
  5054. axis = 0
  5055. axis = self._get_axis_number(axis)
  5056. from pandas import DataFrame
  5057. if value is None:
  5058. if self._is_mixed_type and axis == 1:
  5059. if inplace:
  5060. raise NotImplementedError()
  5061. result = self.T.fillna(method=method, limit=limit).T
  5062. # need to downcast here because of all of the transposes
  5063. result._data = result._data.downcast()
  5064. return result
  5065. # > 3d
  5066. if self.ndim > 3:
  5067. raise NotImplementedError('Cannot fillna with a method for > '
  5068. '3dims')
  5069. # 3d
  5070. elif self.ndim == 3:
  5071. # fill in 2d chunks
  5072. result = {col: s.fillna(method=method, value=value)
  5073. for col, s in self.iteritems()}
  5074. prelim_obj = self._constructor.from_dict(result)
  5075. new_obj = prelim_obj.__finalize__(self)
  5076. new_data = new_obj._data
  5077. else:
  5078. # 2d or less
  5079. new_data = self._data.interpolate(method=method, axis=axis,
  5080. limit=limit, inplace=inplace,
  5081. coerce=True,
  5082. downcast=downcast)
  5083. else:
  5084. if len(self._get_axis(axis)) == 0:
  5085. return self
  5086. if self.ndim == 1:
  5087. if isinstance(value, (dict, ABCSeries)):
  5088. from pandas import Series
  5089. value = Series(value)
  5090. elif not is_list_like(value):
  5091. pass
  5092. else:
  5093. raise TypeError('"value" parameter must be a scalar, dict '
  5094. 'or Series, but you passed a '
  5095. '"{0}"'.format(type(value).__name__))
  5096. new_data = self._data.fillna(value=value, limit=limit,
  5097. inplace=inplace,
  5098. downcast=downcast)
  5099. elif isinstance(value, (dict, ABCSeries)):
  5100. if axis == 1:
  5101. raise NotImplementedError('Currently only can fill '
  5102. 'with dict/Series column '
  5103. 'by column')
  5104. result = self if inplace else self.copy()
  5105. for k, v in compat.iteritems(value):
  5106. if k not in result:
  5107. continue
  5108. obj = result[k]
  5109. obj.fillna(v, limit=limit, inplace=True, downcast=downcast)
  5110. return result if not inplace else None
  5111. elif not is_list_like(value):
  5112. new_data = self._data.fillna(value=value, limit=limit,
  5113. inplace=inplace,
  5114. downcast=downcast)
  5115. elif isinstance(value, DataFrame) and self.ndim == 2:
  5116. new_data = self.where(self.notna(), value)
  5117. else:
  5118. raise ValueError("invalid fill value with a %s" % type(value))
  5119. if inplace:
  5120. self._update_inplace(new_data)
  5121. else:
  5122. return self._constructor(new_data).__finalize__(self)
  5123. def ffill(self, axis=None, inplace=False, limit=None, downcast=None):
  5124. """
  5125. Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``.
  5126. """
  5127. return self.fillna(method='ffill', axis=axis, inplace=inplace,
  5128. limit=limit, downcast=downcast)
  5129. def bfill(self, axis=None, inplace=False, limit=None, downcast=None):
  5130. """
  5131. Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``.
  5132. """
  5133. return self.fillna(method='bfill', axis=axis, inplace=inplace,
  5134. limit=limit, downcast=downcast)
  5135. _shared_docs['replace'] = ("""
  5136. Replace values given in `to_replace` with `value`.
  5137. Values of the %(klass)s are replaced with other values dynamically.
  5138. This differs from updating with ``.loc`` or ``.iloc``, which require
  5139. you to specify a location to update with some value.
  5140. Parameters
  5141. ----------
  5142. to_replace : str, regex, list, dict, Series, int, float, or None
  5143. How to find the values that will be replaced.
  5144. * numeric, str or regex:
  5145. - numeric: numeric values equal to `to_replace` will be
  5146. replaced with `value`
  5147. - str: string exactly matching `to_replace` will be replaced
  5148. with `value`
  5149. - regex: regexs matching `to_replace` will be replaced with
  5150. `value`
  5151. * list of str, regex, or numeric:
  5152. - First, if `to_replace` and `value` are both lists, they
  5153. **must** be the same length.
  5154. - Second, if ``regex=True`` then all of the strings in **both**
  5155. lists will be interpreted as regexs otherwise they will match
  5156. directly. This doesn't matter much for `value` since there
  5157. are only a few possible substitution regexes you can use.
  5158. - str, regex and numeric rules apply as above.
  5159. * dict:
  5160. - Dicts can be used to specify different replacement values
  5161. for different existing values. For example,
  5162. ``{'a': 'b', 'y': 'z'}`` replaces the value 'a' with 'b' and
  5163. 'y' with 'z'. To use a dict in this way the `value`
  5164. parameter should be `None`.
  5165. - For a DataFrame a dict can specify that different values
  5166. should be replaced in different columns. For example,
  5167. ``{'a': 1, 'b': 'z'}`` looks for the value 1 in column 'a'
  5168. and the value 'z' in column 'b' and replaces these values
  5169. with whatever is specified in `value`. The `value` parameter
  5170. should not be ``None`` in this case. You can treat this as a
  5171. special case of passing two lists except that you are
  5172. specifying the column to search in.
  5173. - For a DataFrame nested dictionaries, e.g.,
  5174. ``{'a': {'b': np.nan}}``, are read as follows: look in column
  5175. 'a' for the value 'b' and replace it with NaN. The `value`
  5176. parameter should be ``None`` to use a nested dict in this
  5177. way. You can nest regular expressions as well. Note that
  5178. column names (the top-level dictionary keys in a nested
  5179. dictionary) **cannot** be regular expressions.
  5180. * None:
  5181. - This means that the `regex` argument must be a string,
  5182. compiled regular expression, or list, dict, ndarray or
  5183. Series of such elements. If `value` is also ``None`` then
  5184. this **must** be a nested dictionary or Series.
  5185. See the examples section for examples of each of these.
  5186. value : scalar, dict, list, str, regex, default None
  5187. Value to replace any values matching `to_replace` with.
  5188. For a DataFrame a dict of values can be used to specify which
  5189. value to use for each column (columns not in the dict will not be
  5190. filled). Regular expressions, strings and lists or dicts of such
  5191. objects are also allowed.
  5192. inplace : bool, default False
  5193. If True, in place. Note: this will modify any
  5194. other views on this object (e.g. a column from a DataFrame).
  5195. Returns the caller if this is True.
  5196. limit : int, default None
  5197. Maximum size gap to forward or backward fill.
  5198. regex : bool or same types as `to_replace`, default False
  5199. Whether to interpret `to_replace` and/or `value` as regular
  5200. expressions. If this is ``True`` then `to_replace` *must* be a
  5201. string. Alternatively, this could be a regular expression or a
  5202. list, dict, or array of regular expressions in which case
  5203. `to_replace` must be ``None``.
  5204. method : {'pad', 'ffill', 'bfill', `None`}
  5205. The method to use when for replacement, when `to_replace` is a
  5206. scalar, list or tuple and `value` is ``None``.
  5207. .. versionchanged:: 0.23.0
  5208. Added to DataFrame.
  5209. Returns
  5210. -------
  5211. %(klass)s
  5212. Object after replacement.
  5213. Raises
  5214. ------
  5215. AssertionError
  5216. * If `regex` is not a ``bool`` and `to_replace` is not
  5217. ``None``.
  5218. TypeError
  5219. * If `to_replace` is a ``dict`` and `value` is not a ``list``,
  5220. ``dict``, ``ndarray``, or ``Series``
  5221. * If `to_replace` is ``None`` and `regex` is not compilable
  5222. into a regular expression or is a list, dict, ndarray, or
  5223. Series.
  5224. * When replacing multiple ``bool`` or ``datetime64`` objects and
  5225. the arguments to `to_replace` does not match the type of the
  5226. value being replaced
  5227. ValueError
  5228. * If a ``list`` or an ``ndarray`` is passed to `to_replace` and
  5229. `value` but they are not the same length.
  5230. See Also
  5231. --------
  5232. %(klass)s.fillna : Fill NA values.
  5233. %(klass)s.where : Replace values based on boolean condition.
  5234. Series.str.replace : Simple string replacement.
  5235. Notes
  5236. -----
  5237. * Regex substitution is performed under the hood with ``re.sub``. The
  5238. rules for substitution for ``re.sub`` are the same.
  5239. * Regular expressions will only substitute on strings, meaning you
  5240. cannot provide, for example, a regular expression matching floating
  5241. point numbers and expect the columns in your frame that have a
  5242. numeric dtype to be matched. However, if those floating point
  5243. numbers *are* strings, then you can do this.
  5244. * This method has *a lot* of options. You are encouraged to experiment
  5245. and play with this method to gain intuition about how it works.
  5246. * When dict is used as the `to_replace` value, it is like
  5247. key(s) in the dict are the to_replace part and
  5248. value(s) in the dict are the value parameter.
  5249. Examples
  5250. --------
  5251. **Scalar `to_replace` and `value`**
  5252. >>> s = pd.Series([0, 1, 2, 3, 4])
  5253. >>> s.replace(0, 5)
  5254. 0 5
  5255. 1 1
  5256. 2 2
  5257. 3 3
  5258. 4 4
  5259. dtype: int64
  5260. >>> df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
  5261. ... 'B': [5, 6, 7, 8, 9],
  5262. ... 'C': ['a', 'b', 'c', 'd', 'e']})
  5263. >>> df.replace(0, 5)
  5264. A B C
  5265. 0 5 5 a
  5266. 1 1 6 b
  5267. 2 2 7 c
  5268. 3 3 8 d
  5269. 4 4 9 e
  5270. **List-like `to_replace`**
  5271. >>> df.replace([0, 1, 2, 3], 4)
  5272. A B C
  5273. 0 4 5 a
  5274. 1 4 6 b
  5275. 2 4 7 c
  5276. 3 4 8 d
  5277. 4 4 9 e
  5278. >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])
  5279. A B C
  5280. 0 4 5 a
  5281. 1 3 6 b
  5282. 2 2 7 c
  5283. 3 1 8 d
  5284. 4 4 9 e
  5285. >>> s.replace([1, 2], method='bfill')
  5286. 0 0
  5287. 1 3
  5288. 2 3
  5289. 3 3
  5290. 4 4
  5291. dtype: int64
  5292. **dict-like `to_replace`**
  5293. >>> df.replace({0: 10, 1: 100})
  5294. A B C
  5295. 0 10 5 a
  5296. 1 100 6 b
  5297. 2 2 7 c
  5298. 3 3 8 d
  5299. 4 4 9 e
  5300. >>> df.replace({'A': 0, 'B': 5}, 100)
  5301. A B C
  5302. 0 100 100 a
  5303. 1 1 6 b
  5304. 2 2 7 c
  5305. 3 3 8 d
  5306. 4 4 9 e
  5307. >>> df.replace({'A': {0: 100, 4: 400}})
  5308. A B C
  5309. 0 100 5 a
  5310. 1 1 6 b
  5311. 2 2 7 c
  5312. 3 3 8 d
  5313. 4 400 9 e
  5314. **Regular expression `to_replace`**
  5315. >>> df = pd.DataFrame({'A': ['bat', 'foo', 'bait'],
  5316. ... 'B': ['abc', 'bar', 'xyz']})
  5317. >>> df.replace(to_replace=r'^ba.$', value='new', regex=True)
  5318. A B
  5319. 0 new abc
  5320. 1 foo new
  5321. 2 bait xyz
  5322. >>> df.replace({'A': r'^ba.$'}, {'A': 'new'}, regex=True)
  5323. A B
  5324. 0 new abc
  5325. 1 foo bar
  5326. 2 bait xyz
  5327. >>> df.replace(regex=r'^ba.$', value='new')
  5328. A B
  5329. 0 new abc
  5330. 1 foo new
  5331. 2 bait xyz
  5332. >>> df.replace(regex={r'^ba.$': 'new', 'foo': 'xyz'})
  5333. A B
  5334. 0 new abc
  5335. 1 xyz new
  5336. 2 bait xyz
  5337. >>> df.replace(regex=[r'^ba.$', 'foo'], value='new')
  5338. A B
  5339. 0 new abc
  5340. 1 new new
  5341. 2 bait xyz
  5342. Note that when replacing multiple ``bool`` or ``datetime64`` objects,
  5343. the data types in the `to_replace` parameter must match the data
  5344. type of the value being replaced:
  5345. >>> df = pd.DataFrame({'A': [True, False, True],
  5346. ... 'B': [False, True, False]})
  5347. >>> df.replace({'a string': 'new value', True: False}) # raises
  5348. Traceback (most recent call last):
  5349. ...
  5350. TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'
  5351. This raises a ``TypeError`` because one of the ``dict`` keys is not of
  5352. the correct type for replacement.
  5353. Compare the behavior of ``s.replace({'a': None})`` and
  5354. ``s.replace('a', None)`` to understand the peculiarities
  5355. of the `to_replace` parameter:
  5356. >>> s = pd.Series([10, 'a', 'a', 'b', 'a'])
  5357. When one uses a dict as the `to_replace` value, it is like the
  5358. value(s) in the dict are equal to the `value` parameter.
  5359. ``s.replace({'a': None})`` is equivalent to
  5360. ``s.replace(to_replace={'a': None}, value=None, method=None)``:
  5361. >>> s.replace({'a': None})
  5362. 0 10
  5363. 1 None
  5364. 2 None
  5365. 3 b
  5366. 4 None
  5367. dtype: object
  5368. When ``value=None`` and `to_replace` is a scalar, list or
  5369. tuple, `replace` uses the method parameter (default 'pad') to do the
  5370. replacement. So this is why the 'a' values are being replaced by 10
  5371. in rows 1 and 2 and 'b' in row 4 in this case.
  5372. The command ``s.replace('a', None)`` is actually equivalent to
  5373. ``s.replace(to_replace='a', value=None, method='pad')``:
  5374. >>> s.replace('a', None)
  5375. 0 10
  5376. 1 10
  5377. 2 10
  5378. 3 b
  5379. 4 b
  5380. dtype: object
  5381. """)
  5382. @Appender(_shared_docs['replace'] % _shared_doc_kwargs)
  5383. def replace(self, to_replace=None, value=None, inplace=False, limit=None,
  5384. regex=False, method='pad'):
  5385. inplace = validate_bool_kwarg(inplace, 'inplace')
  5386. if not is_bool(regex) and to_replace is not None:
  5387. raise AssertionError("'to_replace' must be 'None' if 'regex' is "
  5388. "not a bool")
  5389. self._consolidate_inplace()
  5390. if value is None:
  5391. # passing a single value that is scalar like
  5392. # when value is None (GH5319), for compat
  5393. if not is_dict_like(to_replace) and not is_dict_like(regex):
  5394. to_replace = [to_replace]
  5395. if isinstance(to_replace, (tuple, list)):
  5396. if isinstance(self, pd.DataFrame):
  5397. return self.apply(_single_replace,
  5398. args=(to_replace, method, inplace,
  5399. limit))
  5400. return _single_replace(self, to_replace, method, inplace,
  5401. limit)
  5402. if not is_dict_like(to_replace):
  5403. if not is_dict_like(regex):
  5404. raise TypeError('If "to_replace" and "value" are both None'
  5405. ' and "to_replace" is not a list, then '
  5406. 'regex must be a mapping')
  5407. to_replace = regex
  5408. regex = True
  5409. items = list(compat.iteritems(to_replace))
  5410. keys, values = lzip(*items) or ([], [])
  5411. are_mappings = [is_dict_like(v) for v in values]
  5412. if any(are_mappings):
  5413. if not all(are_mappings):
  5414. raise TypeError("If a nested mapping is passed, all values"
  5415. " of the top level mapping must be "
  5416. "mappings")
  5417. # passed a nested dict/Series
  5418. to_rep_dict = {}
  5419. value_dict = {}
  5420. for k, v in items:
  5421. keys, values = lzip(*v.items()) or ([], [])
  5422. if set(keys) & set(values):
  5423. raise ValueError("Replacement not allowed with "
  5424. "overlapping keys and values")
  5425. to_rep_dict[k] = list(keys)
  5426. value_dict[k] = list(values)
  5427. to_replace, value = to_rep_dict, value_dict
  5428. else:
  5429. to_replace, value = keys, values
  5430. return self.replace(to_replace, value, inplace=inplace,
  5431. limit=limit, regex=regex)
  5432. else:
  5433. # need a non-zero len on all axes
  5434. for a in self._AXIS_ORDERS:
  5435. if not len(self._get_axis(a)):
  5436. return self
  5437. new_data = self._data
  5438. if is_dict_like(to_replace):
  5439. if is_dict_like(value): # {'A' : NA} -> {'A' : 0}
  5440. res = self if inplace else self.copy()
  5441. for c, src in compat.iteritems(to_replace):
  5442. if c in value and c in self:
  5443. # object conversion is handled in
  5444. # series.replace which is called recursivelly
  5445. res[c] = res[c].replace(to_replace=src,
  5446. value=value[c],
  5447. inplace=False,
  5448. regex=regex)
  5449. return None if inplace else res
  5450. # {'A': NA} -> 0
  5451. elif not is_list_like(value):
  5452. keys = [(k, src) for k, src in compat.iteritems(to_replace)
  5453. if k in self]
  5454. keys_len = len(keys) - 1
  5455. for i, (k, src) in enumerate(keys):
  5456. convert = i == keys_len
  5457. new_data = new_data.replace(to_replace=src,
  5458. value=value,
  5459. filter=[k],
  5460. inplace=inplace,
  5461. regex=regex,
  5462. convert=convert)
  5463. else:
  5464. raise TypeError('value argument must be scalar, dict, or '
  5465. 'Series')
  5466. elif is_list_like(to_replace): # [NA, ''] -> [0, 'missing']
  5467. if is_list_like(value):
  5468. if len(to_replace) != len(value):
  5469. raise ValueError('Replacement lists must match '
  5470. 'in length. Expecting %d got %d ' %
  5471. (len(to_replace), len(value)))
  5472. new_data = self._data.replace_list(src_list=to_replace,
  5473. dest_list=value,
  5474. inplace=inplace,
  5475. regex=regex)
  5476. else: # [NA, ''] -> 0
  5477. new_data = self._data.replace(to_replace=to_replace,
  5478. value=value, inplace=inplace,
  5479. regex=regex)
  5480. elif to_replace is None:
  5481. if not (is_re_compilable(regex) or
  5482. is_list_like(regex) or is_dict_like(regex)):
  5483. raise TypeError("'regex' must be a string or a compiled "
  5484. "regular expression or a list or dict of "
  5485. "strings or regular expressions, you "
  5486. "passed a"
  5487. " {0!r}".format(type(regex).__name__))
  5488. return self.replace(regex, value, inplace=inplace, limit=limit,
  5489. regex=True)
  5490. else:
  5491. # dest iterable dict-like
  5492. if is_dict_like(value): # NA -> {'A' : 0, 'B' : -1}
  5493. new_data = self._data
  5494. for k, v in compat.iteritems(value):
  5495. if k in self:
  5496. new_data = new_data.replace(to_replace=to_replace,
  5497. value=v, filter=[k],
  5498. inplace=inplace,
  5499. regex=regex)
  5500. elif not is_list_like(value): # NA -> 0
  5501. new_data = self._data.replace(to_replace=to_replace,
  5502. value=value, inplace=inplace,
  5503. regex=regex)
  5504. else:
  5505. msg = ('Invalid "to_replace" type: '
  5506. '{0!r}').format(type(to_replace).__name__)
  5507. raise TypeError(msg) # pragma: no cover
  5508. if inplace:
  5509. self._update_inplace(new_data)
  5510. else:
  5511. return self._constructor(new_data).__finalize__(self)
  5512. _shared_docs['interpolate'] = """
  5513. Please note that only ``method='linear'`` is supported for
  5514. DataFrame/Series with a MultiIndex.
  5515. Parameters
  5516. ----------
  5517. method : str, default 'linear'
  5518. Interpolation technique to use. One of:
  5519. * 'linear': Ignore the index and treat the values as equally
  5520. spaced. This is the only method supported on MultiIndexes.
  5521. * 'time': Works on daily and higher resolution data to interpolate
  5522. given length of interval.
  5523. * 'index', 'values': use the actual numerical values of the index.
  5524. * 'pad': Fill in NaNs using existing values.
  5525. * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'spline',
  5526. 'barycentric', 'polynomial': Passed to
  5527. `scipy.interpolate.interp1d`. These methods use the numerical
  5528. values of the index. Both 'polynomial' and 'spline' require that
  5529. you also specify an `order` (int), e.g.
  5530. ``df.interpolate(method='polynomial', order=5)``.
  5531. * 'krogh', 'piecewise_polynomial', 'spline', 'pchip', 'akima':
  5532. Wrappers around the SciPy interpolation methods of similar
  5533. names. See `Notes`.
  5534. * 'from_derivatives': Refers to
  5535. `scipy.interpolate.BPoly.from_derivatives` which
  5536. replaces 'piecewise_polynomial' interpolation method in
  5537. scipy 0.18.
  5538. .. versionadded:: 0.18.1
  5539. Added support for the 'akima' method.
  5540. Added interpolate method 'from_derivatives' which replaces
  5541. 'piecewise_polynomial' in SciPy 0.18; backwards-compatible with
  5542. SciPy < 0.18
  5543. axis : {0 or 'index', 1 or 'columns', None}, default None
  5544. Axis to interpolate along.
  5545. limit : int, optional
  5546. Maximum number of consecutive NaNs to fill. Must be greater than
  5547. 0.
  5548. inplace : bool, default False
  5549. Update the data in place if possible.
  5550. limit_direction : {'forward', 'backward', 'both'}, default 'forward'
  5551. If limit is specified, consecutive NaNs will be filled in this
  5552. direction.
  5553. limit_area : {`None`, 'inside', 'outside'}, default None
  5554. If limit is specified, consecutive NaNs will be filled with this
  5555. restriction.
  5556. * ``None``: No fill restriction.
  5557. * 'inside': Only fill NaNs surrounded by valid values
  5558. (interpolate).
  5559. * 'outside': Only fill NaNs outside valid values (extrapolate).
  5560. .. versionadded:: 0.23.0
  5561. downcast : optional, 'infer' or None, defaults to None
  5562. Downcast dtypes if possible.
  5563. **kwargs
  5564. Keyword arguments to pass on to the interpolating function.
  5565. Returns
  5566. -------
  5567. Series or DataFrame
  5568. Returns the same object type as the caller, interpolated at
  5569. some or all ``NaN`` values.
  5570. See Also
  5571. --------
  5572. fillna : Fill missing values using different methods.
  5573. scipy.interpolate.Akima1DInterpolator : Piecewise cubic polynomials
  5574. (Akima interpolator).
  5575. scipy.interpolate.BPoly.from_derivatives : Piecewise polynomial in the
  5576. Bernstein basis.
  5577. scipy.interpolate.interp1d : Interpolate a 1-D function.
  5578. scipy.interpolate.KroghInterpolator : Interpolate polynomial (Krogh
  5579. interpolator).
  5580. scipy.interpolate.PchipInterpolator : PCHIP 1-d monotonic cubic
  5581. interpolation.
  5582. scipy.interpolate.CubicSpline : Cubic spline data interpolator.
  5583. Notes
  5584. -----
  5585. The 'krogh', 'piecewise_polynomial', 'spline', 'pchip' and 'akima'
  5586. methods are wrappers around the respective SciPy implementations of
  5587. similar names. These use the actual numerical values of the index.
  5588. For more information on their behavior, see the
  5589. `SciPy documentation
  5590. <http://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation>`__
  5591. and `SciPy tutorial
  5592. <http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html>`__.
  5593. Examples
  5594. --------
  5595. Filling in ``NaN`` in a :class:`~pandas.Series` via linear
  5596. interpolation.
  5597. >>> s = pd.Series([0, 1, np.nan, 3])
  5598. >>> s
  5599. 0 0.0
  5600. 1 1.0
  5601. 2 NaN
  5602. 3 3.0
  5603. dtype: float64
  5604. >>> s.interpolate()
  5605. 0 0.0
  5606. 1 1.0
  5607. 2 2.0
  5608. 3 3.0
  5609. dtype: float64
  5610. Filling in ``NaN`` in a Series by padding, but filling at most two
  5611. consecutive ``NaN`` at a time.
  5612. >>> s = pd.Series([np.nan, "single_one", np.nan,
  5613. ... "fill_two_more", np.nan, np.nan, np.nan,
  5614. ... 4.71, np.nan])
  5615. >>> s
  5616. 0 NaN
  5617. 1 single_one
  5618. 2 NaN
  5619. 3 fill_two_more
  5620. 4 NaN
  5621. 5 NaN
  5622. 6 NaN
  5623. 7 4.71
  5624. 8 NaN
  5625. dtype: object
  5626. >>> s.interpolate(method='pad', limit=2)
  5627. 0 NaN
  5628. 1 single_one
  5629. 2 single_one
  5630. 3 fill_two_more
  5631. 4 fill_two_more
  5632. 5 fill_two_more
  5633. 6 NaN
  5634. 7 4.71
  5635. 8 4.71
  5636. dtype: object
  5637. Filling in ``NaN`` in a Series via polynomial interpolation or splines:
  5638. Both 'polynomial' and 'spline' methods require that you also specify
  5639. an ``order`` (int).
  5640. >>> s = pd.Series([0, 2, np.nan, 8])
  5641. >>> s.interpolate(method='polynomial', order=2)
  5642. 0 0.000000
  5643. 1 2.000000
  5644. 2 4.666667
  5645. 3 8.000000
  5646. dtype: float64
  5647. Fill the DataFrame forward (that is, going down) along each column
  5648. using linear interpolation.
  5649. Note how the last entry in column 'a' is interpolated differently,
  5650. because there is no entry after it to use for interpolation.
  5651. Note how the first entry in column 'b' remains ``NaN``, because there
  5652. is no entry befofe it to use for interpolation.
  5653. >>> df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0),
  5654. ... (np.nan, 2.0, np.nan, np.nan),
  5655. ... (2.0, 3.0, np.nan, 9.0),
  5656. ... (np.nan, 4.0, -4.0, 16.0)],
  5657. ... columns=list('abcd'))
  5658. >>> df
  5659. a b c d
  5660. 0 0.0 NaN -1.0 1.0
  5661. 1 NaN 2.0 NaN NaN
  5662. 2 2.0 3.0 NaN 9.0
  5663. 3 NaN 4.0 -4.0 16.0
  5664. >>> df.interpolate(method='linear', limit_direction='forward', axis=0)
  5665. a b c d
  5666. 0 0.0 NaN -1.0 1.0
  5667. 1 1.0 2.0 -2.0 5.0
  5668. 2 2.0 3.0 -3.0 9.0
  5669. 3 2.0 4.0 -4.0 16.0
  5670. Using polynomial interpolation.
  5671. >>> df['d'].interpolate(method='polynomial', order=2)
  5672. 0 1.0
  5673. 1 4.0
  5674. 2 9.0
  5675. 3 16.0
  5676. Name: d, dtype: float64
  5677. """
  5678. @Appender(_shared_docs['interpolate'] % _shared_doc_kwargs)
  5679. def interpolate(self, method='linear', axis=0, limit=None, inplace=False,
  5680. limit_direction='forward', limit_area=None,
  5681. downcast=None, **kwargs):
  5682. """
  5683. Interpolate values according to different methods.
  5684. """
  5685. inplace = validate_bool_kwarg(inplace, 'inplace')
  5686. if self.ndim > 2:
  5687. raise NotImplementedError("Interpolate has not been implemented "
  5688. "on Panel and Panel 4D objects.")
  5689. if axis == 0:
  5690. ax = self._info_axis_name
  5691. _maybe_transposed_self = self
  5692. elif axis == 1:
  5693. _maybe_transposed_self = self.T
  5694. ax = 1
  5695. else:
  5696. _maybe_transposed_self = self
  5697. ax = _maybe_transposed_self._get_axis_number(ax)
  5698. if _maybe_transposed_self.ndim == 2:
  5699. alt_ax = 1 - ax
  5700. else:
  5701. alt_ax = ax
  5702. if (isinstance(_maybe_transposed_self.index, MultiIndex) and
  5703. method != 'linear'):
  5704. raise ValueError("Only `method=linear` interpolation is supported "
  5705. "on MultiIndexes.")
  5706. if _maybe_transposed_self._data.get_dtype_counts().get(
  5707. 'object') == len(_maybe_transposed_self.T):
  5708. raise TypeError("Cannot interpolate with all object-dtype columns "
  5709. "in the DataFrame. Try setting at least one "
  5710. "column to a numeric dtype.")
  5711. # create/use the index
  5712. if method == 'linear':
  5713. # prior default
  5714. index = np.arange(len(_maybe_transposed_self._get_axis(alt_ax)))
  5715. else:
  5716. index = _maybe_transposed_self._get_axis(alt_ax)
  5717. if isna(index).any():
  5718. raise NotImplementedError("Interpolation with NaNs in the index "
  5719. "has not been implemented. Try filling "
  5720. "those NaNs before interpolating.")
  5721. data = _maybe_transposed_self._data
  5722. new_data = data.interpolate(method=method, axis=ax, index=index,
  5723. values=_maybe_transposed_self, limit=limit,
  5724. limit_direction=limit_direction,
  5725. limit_area=limit_area,
  5726. inplace=inplace, downcast=downcast,
  5727. **kwargs)
  5728. if inplace:
  5729. if axis == 1:
  5730. new_data = self._constructor(new_data).T._data
  5731. self._update_inplace(new_data)
  5732. else:
  5733. res = self._constructor(new_data).__finalize__(self)
  5734. if axis == 1:
  5735. res = res.T
  5736. return res
  5737. # ----------------------------------------------------------------------
  5738. # Timeseries methods Methods
  5739. def asof(self, where, subset=None):
  5740. """
  5741. Return the last row(s) without any NaNs before `where`.
  5742. The last row (for each element in `where`, if list) without any
  5743. NaN is taken.
  5744. In case of a :class:`~pandas.DataFrame`, the last row without NaN
  5745. considering only the subset of columns (if not `None`)
  5746. .. versionadded:: 0.19.0 For DataFrame
  5747. If there is no good value, NaN is returned for a Series or
  5748. a Series of NaN values for a DataFrame
  5749. Parameters
  5750. ----------
  5751. where : date or array-like of dates
  5752. Date(s) before which the last row(s) are returned.
  5753. subset : str or array-like of str, default `None`
  5754. For DataFrame, if not `None`, only use these columns to
  5755. check for NaNs.
  5756. Returns
  5757. -------
  5758. scalar, Series, or DataFrame
  5759. The return can be:
  5760. * scalar : when `self` is a Series and `where` is a scalar
  5761. * Series: when `self` is a Series and `where` is an array-like,
  5762. or when `self` is a DataFrame and `where` is a scalar
  5763. * DataFrame : when `self` is a DataFrame and `where` is an
  5764. array-like
  5765. Return scalar, Series, or DataFrame.
  5766. See Also
  5767. --------
  5768. merge_asof : Perform an asof merge. Similar to left join.
  5769. Notes
  5770. -----
  5771. Dates are assumed to be sorted. Raises if this is not the case.
  5772. Examples
  5773. --------
  5774. A Series and a scalar `where`.
  5775. >>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40])
  5776. >>> s
  5777. 10 1.0
  5778. 20 2.0
  5779. 30 NaN
  5780. 40 4.0
  5781. dtype: float64
  5782. >>> s.asof(20)
  5783. 2.0
  5784. For a sequence `where`, a Series is returned. The first value is
  5785. NaN, because the first element of `where` is before the first
  5786. index value.
  5787. >>> s.asof([5, 20])
  5788. 5 NaN
  5789. 20 2.0
  5790. dtype: float64
  5791. Missing values are not considered. The following is ``2.0``, not
  5792. NaN, even though NaN is at the index location for ``30``.
  5793. >>> s.asof(30)
  5794. 2.0
  5795. Take all columns into consideration
  5796. >>> df = pd.DataFrame({'a': [10, 20, 30, 40, 50],
  5797. ... 'b': [None, None, None, None, 500]},
  5798. ... index=pd.DatetimeIndex(['2018-02-27 09:01:00',
  5799. ... '2018-02-27 09:02:00',
  5800. ... '2018-02-27 09:03:00',
  5801. ... '2018-02-27 09:04:00',
  5802. ... '2018-02-27 09:05:00']))
  5803. >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
  5804. ... '2018-02-27 09:04:30']))
  5805. a b
  5806. 2018-02-27 09:03:30 NaN NaN
  5807. 2018-02-27 09:04:30 NaN NaN
  5808. Take a single column into consideration
  5809. >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
  5810. ... '2018-02-27 09:04:30']),
  5811. ... subset=['a'])
  5812. a b
  5813. 2018-02-27 09:03:30 30.0 NaN
  5814. 2018-02-27 09:04:30 40.0 NaN
  5815. """
  5816. if isinstance(where, compat.string_types):
  5817. from pandas import to_datetime
  5818. where = to_datetime(where)
  5819. if not self.index.is_monotonic:
  5820. raise ValueError("asof requires a sorted index")
  5821. is_series = isinstance(self, ABCSeries)
  5822. if is_series:
  5823. if subset is not None:
  5824. raise ValueError("subset is not valid for Series")
  5825. elif self.ndim > 2:
  5826. raise NotImplementedError("asof is not implemented "
  5827. "for {type}".format(type=type(self)))
  5828. else:
  5829. if subset is None:
  5830. subset = self.columns
  5831. if not is_list_like(subset):
  5832. subset = [subset]
  5833. is_list = is_list_like(where)
  5834. if not is_list:
  5835. start = self.index[0]
  5836. if isinstance(self.index, PeriodIndex):
  5837. where = Period(where, freq=self.index.freq).ordinal
  5838. start = start.ordinal
  5839. if where < start:
  5840. if not is_series:
  5841. from pandas import Series
  5842. return Series(index=self.columns, name=where)
  5843. return np.nan
  5844. # It's always much faster to use a *while* loop here for
  5845. # Series than pre-computing all the NAs. However a
  5846. # *while* loop is extremely expensive for DataFrame
  5847. # so we later pre-compute all the NAs and use the same
  5848. # code path whether *where* is a scalar or list.
  5849. # See PR: https://github.com/pandas-dev/pandas/pull/14476
  5850. if is_series:
  5851. loc = self.index.searchsorted(where, side='right')
  5852. if loc > 0:
  5853. loc -= 1
  5854. values = self._values
  5855. while loc > 0 and isna(values[loc]):
  5856. loc -= 1
  5857. return values[loc]
  5858. if not isinstance(where, Index):
  5859. where = Index(where) if is_list else Index([where])
  5860. nulls = self.isna() if is_series else self[subset].isna().any(1)
  5861. if nulls.all():
  5862. if is_series:
  5863. return self._constructor(np.nan, index=where, name=self.name)
  5864. elif is_list:
  5865. from pandas import DataFrame
  5866. return DataFrame(np.nan, index=where, columns=self.columns)
  5867. else:
  5868. from pandas import Series
  5869. return Series(np.nan, index=self.columns, name=where[0])
  5870. locs = self.index.asof_locs(where, ~(nulls.values))
  5871. # mask the missing
  5872. missing = locs == -1
  5873. data = self.take(locs, is_copy=False)
  5874. data.index = where
  5875. data.loc[missing] = np.nan
  5876. return data if is_list else data.iloc[-1]
  5877. # ----------------------------------------------------------------------
  5878. # Action Methods
  5879. _shared_docs['isna'] = """
  5880. Detect missing values.
  5881. Return a boolean same-sized object indicating if the values are NA.
  5882. NA values, such as None or :attr:`numpy.NaN`, gets mapped to True
  5883. values.
  5884. Everything else gets mapped to False values. Characters such as empty
  5885. strings ``''`` or :attr:`numpy.inf` are not considered NA values
  5886. (unless you set ``pandas.options.mode.use_inf_as_na = True``).
  5887. Returns
  5888. -------
  5889. %(klass)s
  5890. Mask of bool values for each element in %(klass)s that
  5891. indicates whether an element is not an NA value.
  5892. See Also
  5893. --------
  5894. %(klass)s.isnull : Alias of isna.
  5895. %(klass)s.notna : Boolean inverse of isna.
  5896. %(klass)s.dropna : Omit axes labels with missing values.
  5897. isna : Top-level isna.
  5898. Examples
  5899. --------
  5900. Show which entries in a DataFrame are NA.
  5901. >>> df = pd.DataFrame({'age': [5, 6, np.NaN],
  5902. ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'),
  5903. ... pd.Timestamp('1940-04-25')],
  5904. ... 'name': ['Alfred', 'Batman', ''],
  5905. ... 'toy': [None, 'Batmobile', 'Joker']})
  5906. >>> df
  5907. age born name toy
  5908. 0 5.0 NaT Alfred None
  5909. 1 6.0 1939-05-27 Batman Batmobile
  5910. 2 NaN 1940-04-25 Joker
  5911. >>> df.isna()
  5912. age born name toy
  5913. 0 False True False True
  5914. 1 False False False False
  5915. 2 True False False False
  5916. Show which entries in a Series are NA.
  5917. >>> ser = pd.Series([5, 6, np.NaN])
  5918. >>> ser
  5919. 0 5.0
  5920. 1 6.0
  5921. 2 NaN
  5922. dtype: float64
  5923. >>> ser.isna()
  5924. 0 False
  5925. 1 False
  5926. 2 True
  5927. dtype: bool
  5928. """
  5929. @Appender(_shared_docs['isna'] % _shared_doc_kwargs)
  5930. def isna(self):
  5931. return isna(self).__finalize__(self)
  5932. @Appender(_shared_docs['isna'] % _shared_doc_kwargs)
  5933. def isnull(self):
  5934. return isna(self).__finalize__(self)
  5935. _shared_docs['notna'] = """
  5936. Detect existing (non-missing) values.
  5937. Return a boolean same-sized object indicating if the values are not NA.
  5938. Non-missing values get mapped to True. Characters such as empty
  5939. strings ``''`` or :attr:`numpy.inf` are not considered NA values
  5940. (unless you set ``pandas.options.mode.use_inf_as_na = True``).
  5941. NA values, such as None or :attr:`numpy.NaN`, get mapped to False
  5942. values.
  5943. Returns
  5944. -------
  5945. %(klass)s
  5946. Mask of bool values for each element in %(klass)s that
  5947. indicates whether an element is not an NA value.
  5948. See Also
  5949. --------
  5950. %(klass)s.notnull : Alias of notna.
  5951. %(klass)s.isna : Boolean inverse of notna.
  5952. %(klass)s.dropna : Omit axes labels with missing values.
  5953. notna : Top-level notna.
  5954. Examples
  5955. --------
  5956. Show which entries in a DataFrame are not NA.
  5957. >>> df = pd.DataFrame({'age': [5, 6, np.NaN],
  5958. ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'),
  5959. ... pd.Timestamp('1940-04-25')],
  5960. ... 'name': ['Alfred', 'Batman', ''],
  5961. ... 'toy': [None, 'Batmobile', 'Joker']})
  5962. >>> df
  5963. age born name toy
  5964. 0 5.0 NaT Alfred None
  5965. 1 6.0 1939-05-27 Batman Batmobile
  5966. 2 NaN 1940-04-25 Joker
  5967. >>> df.notna()
  5968. age born name toy
  5969. 0 True False True False
  5970. 1 True True True True
  5971. 2 False True True True
  5972. Show which entries in a Series are not NA.
  5973. >>> ser = pd.Series([5, 6, np.NaN])
  5974. >>> ser
  5975. 0 5.0
  5976. 1 6.0
  5977. 2 NaN
  5978. dtype: float64
  5979. >>> ser.notna()
  5980. 0 True
  5981. 1 True
  5982. 2 False
  5983. dtype: bool
  5984. """
  5985. @Appender(_shared_docs['notna'] % _shared_doc_kwargs)
  5986. def notna(self):
  5987. return notna(self).__finalize__(self)
  5988. @Appender(_shared_docs['notna'] % _shared_doc_kwargs)
  5989. def notnull(self):
  5990. return notna(self).__finalize__(self)
  5991. def _clip_with_scalar(self, lower, upper, inplace=False):
  5992. if ((lower is not None and np.any(isna(lower))) or
  5993. (upper is not None and np.any(isna(upper)))):
  5994. raise ValueError("Cannot use an NA value as a clip threshold")
  5995. result = self
  5996. mask = isna(self.values)
  5997. with np.errstate(all='ignore'):
  5998. if upper is not None:
  5999. subset = self.to_numpy() <= upper
  6000. result = result.where(subset, upper, axis=None, inplace=False)
  6001. if lower is not None:
  6002. subset = self.to_numpy() >= lower
  6003. result = result.where(subset, lower, axis=None, inplace=False)
  6004. if np.any(mask):
  6005. result[mask] = np.nan
  6006. if inplace:
  6007. self._update_inplace(result)
  6008. else:
  6009. return result
  6010. def _clip_with_one_bound(self, threshold, method, axis, inplace):
  6011. if axis is not None:
  6012. axis = self._get_axis_number(axis)
  6013. # method is self.le for upper bound and self.ge for lower bound
  6014. if is_scalar(threshold) and is_number(threshold):
  6015. if method.__name__ == 'le':
  6016. return self._clip_with_scalar(None, threshold, inplace=inplace)
  6017. return self._clip_with_scalar(threshold, None, inplace=inplace)
  6018. subset = method(threshold, axis=axis) | isna(self)
  6019. # GH #15390
  6020. # In order for where method to work, the threshold must
  6021. # be transformed to NDFrame from other array like structure.
  6022. if (not isinstance(threshold, ABCSeries)) and is_list_like(threshold):
  6023. if isinstance(self, ABCSeries):
  6024. threshold = pd.Series(threshold, index=self.index)
  6025. else:
  6026. threshold = _align_method_FRAME(self, threshold,
  6027. axis)
  6028. return self.where(subset, threshold, axis=axis, inplace=inplace)
  6029. def clip(self, lower=None, upper=None, axis=None, inplace=False,
  6030. *args, **kwargs):
  6031. """
  6032. Trim values at input threshold(s).
  6033. Assigns values outside boundary to boundary values. Thresholds
  6034. can be singular values or array like, and in the latter case
  6035. the clipping is performed element-wise in the specified axis.
  6036. Parameters
  6037. ----------
  6038. lower : float or array_like, default None
  6039. Minimum threshold value. All values below this
  6040. threshold will be set to it.
  6041. upper : float or array_like, default None
  6042. Maximum threshold value. All values above this
  6043. threshold will be set to it.
  6044. axis : int or str axis name, optional
  6045. Align object with lower and upper along the given axis.
  6046. inplace : bool, default False
  6047. Whether to perform the operation in place on the data.
  6048. .. versionadded:: 0.21.0
  6049. *args, **kwargs
  6050. Additional keywords have no effect but might be accepted
  6051. for compatibility with numpy.
  6052. Returns
  6053. -------
  6054. Series or DataFrame
  6055. Same type as calling object with the values outside the
  6056. clip boundaries replaced.
  6057. Examples
  6058. --------
  6059. >>> data = {'col_0': [9, -3, 0, -1, 5], 'col_1': [-2, -7, 6, 8, -5]}
  6060. >>> df = pd.DataFrame(data)
  6061. >>> df
  6062. col_0 col_1
  6063. 0 9 -2
  6064. 1 -3 -7
  6065. 2 0 6
  6066. 3 -1 8
  6067. 4 5 -5
  6068. Clips per column using lower and upper thresholds:
  6069. >>> df.clip(-4, 6)
  6070. col_0 col_1
  6071. 0 6 -2
  6072. 1 -3 -4
  6073. 2 0 6
  6074. 3 -1 6
  6075. 4 5 -4
  6076. Clips using specific lower and upper thresholds per column element:
  6077. >>> t = pd.Series([2, -4, -1, 6, 3])
  6078. >>> t
  6079. 0 2
  6080. 1 -4
  6081. 2 -1
  6082. 3 6
  6083. 4 3
  6084. dtype: int64
  6085. >>> df.clip(t, t + 4, axis=0)
  6086. col_0 col_1
  6087. 0 6 2
  6088. 1 -3 -4
  6089. 2 0 3
  6090. 3 6 8
  6091. 4 5 3
  6092. """
  6093. if isinstance(self, ABCPanel):
  6094. raise NotImplementedError("clip is not supported yet for panels")
  6095. inplace = validate_bool_kwarg(inplace, 'inplace')
  6096. axis = nv.validate_clip_with_axis(axis, args, kwargs)
  6097. if axis is not None:
  6098. axis = self._get_axis_number(axis)
  6099. # GH 17276
  6100. # numpy doesn't like NaN as a clip value
  6101. # so ignore
  6102. # GH 19992
  6103. # numpy doesn't drop a list-like bound containing NaN
  6104. if not is_list_like(lower) and np.any(pd.isnull(lower)):
  6105. lower = None
  6106. if not is_list_like(upper) and np.any(pd.isnull(upper)):
  6107. upper = None
  6108. # GH 2747 (arguments were reversed)
  6109. if lower is not None and upper is not None:
  6110. if is_scalar(lower) and is_scalar(upper):
  6111. lower, upper = min(lower, upper), max(lower, upper)
  6112. # fast-path for scalars
  6113. if ((lower is None or (is_scalar(lower) and is_number(lower))) and
  6114. (upper is None or (is_scalar(upper) and is_number(upper)))):
  6115. return self._clip_with_scalar(lower, upper, inplace=inplace)
  6116. result = self
  6117. if lower is not None:
  6118. result = result._clip_with_one_bound(lower, method=self.ge,
  6119. axis=axis, inplace=inplace)
  6120. if upper is not None:
  6121. if inplace:
  6122. result = self
  6123. result = result._clip_with_one_bound(upper, method=self.le,
  6124. axis=axis, inplace=inplace)
  6125. return result
  6126. def clip_upper(self, threshold, axis=None, inplace=False):
  6127. """
  6128. Trim values above a given threshold.
  6129. .. deprecated:: 0.24.0
  6130. Use clip(upper=threshold) instead.
  6131. Elements above the `threshold` will be changed to match the
  6132. `threshold` value(s). Threshold can be a single value or an array,
  6133. in the latter case it performs the truncation element-wise.
  6134. Parameters
  6135. ----------
  6136. threshold : numeric or array-like
  6137. Maximum value allowed. All values above threshold will be set to
  6138. this value.
  6139. * float : every value is compared to `threshold`.
  6140. * array-like : The shape of `threshold` should match the object
  6141. it's compared to. When `self` is a Series, `threshold` should be
  6142. the length. When `self` is a DataFrame, `threshold` should 2-D
  6143. and the same shape as `self` for ``axis=None``, or 1-D and the
  6144. same length as the axis being compared.
  6145. axis : {0 or 'index', 1 or 'columns'}, default 0
  6146. Align object with `threshold` along the given axis.
  6147. inplace : bool, default False
  6148. Whether to perform the operation in place on the data.
  6149. .. versionadded:: 0.21.0
  6150. Returns
  6151. -------
  6152. Series or DataFrame
  6153. Original data with values trimmed.
  6154. See Also
  6155. --------
  6156. Series.clip : General purpose method to trim Series values to given
  6157. threshold(s).
  6158. DataFrame.clip : General purpose method to trim DataFrame values to
  6159. given threshold(s).
  6160. Examples
  6161. --------
  6162. >>> s = pd.Series([1, 2, 3, 4, 5])
  6163. >>> s
  6164. 0 1
  6165. 1 2
  6166. 2 3
  6167. 3 4
  6168. 4 5
  6169. dtype: int64
  6170. >>> s.clip(upper=3)
  6171. 0 1
  6172. 1 2
  6173. 2 3
  6174. 3 3
  6175. 4 3
  6176. dtype: int64
  6177. >>> elemwise_thresholds = [5, 4, 3, 2, 1]
  6178. >>> elemwise_thresholds
  6179. [5, 4, 3, 2, 1]
  6180. >>> s.clip(upper=elemwise_thresholds)
  6181. 0 1
  6182. 1 2
  6183. 2 3
  6184. 3 2
  6185. 4 1
  6186. dtype: int64
  6187. """
  6188. warnings.warn('clip_upper(threshold) is deprecated, '
  6189. 'use clip(upper=threshold) instead',
  6190. FutureWarning, stacklevel=2)
  6191. return self._clip_with_one_bound(threshold, method=self.le,
  6192. axis=axis, inplace=inplace)
  6193. def clip_lower(self, threshold, axis=None, inplace=False):
  6194. """
  6195. Trim values below a given threshold.
  6196. .. deprecated:: 0.24.0
  6197. Use clip(lower=threshold) instead.
  6198. Elements below the `threshold` will be changed to match the
  6199. `threshold` value(s). Threshold can be a single value or an array,
  6200. in the latter case it performs the truncation element-wise.
  6201. Parameters
  6202. ----------
  6203. threshold : numeric or array-like
  6204. Minimum value allowed. All values below threshold will be set to
  6205. this value.
  6206. * float : every value is compared to `threshold`.
  6207. * array-like : The shape of `threshold` should match the object
  6208. it's compared to. When `self` is a Series, `threshold` should be
  6209. the length. When `self` is a DataFrame, `threshold` should 2-D
  6210. and the same shape as `self` for ``axis=None``, or 1-D and the
  6211. same length as the axis being compared.
  6212. axis : {0 or 'index', 1 or 'columns'}, default 0
  6213. Align `self` with `threshold` along the given axis.
  6214. inplace : bool, default False
  6215. Whether to perform the operation in place on the data.
  6216. .. versionadded:: 0.21.0
  6217. Returns
  6218. -------
  6219. Series or DataFrame
  6220. Original data with values trimmed.
  6221. See Also
  6222. --------
  6223. Series.clip : General purpose method to trim Series values to given
  6224. threshold(s).
  6225. DataFrame.clip : General purpose method to trim DataFrame values to
  6226. given threshold(s).
  6227. Examples
  6228. --------
  6229. Series single threshold clipping:
  6230. >>> s = pd.Series([5, 6, 7, 8, 9])
  6231. >>> s.clip(lower=8)
  6232. 0 8
  6233. 1 8
  6234. 2 8
  6235. 3 8
  6236. 4 9
  6237. dtype: int64
  6238. Series clipping element-wise using an array of thresholds. `threshold`
  6239. should be the same length as the Series.
  6240. >>> elemwise_thresholds = [4, 8, 7, 2, 5]
  6241. >>> s.clip(lower=elemwise_thresholds)
  6242. 0 5
  6243. 1 8
  6244. 2 7
  6245. 3 8
  6246. 4 9
  6247. dtype: int64
  6248. DataFrames can be compared to a scalar.
  6249. >>> df = pd.DataFrame({"A": [1, 3, 5], "B": [2, 4, 6]})
  6250. >>> df
  6251. A B
  6252. 0 1 2
  6253. 1 3 4
  6254. 2 5 6
  6255. >>> df.clip(lower=3)
  6256. A B
  6257. 0 3 3
  6258. 1 3 4
  6259. 2 5 6
  6260. Or to an array of values. By default, `threshold` should be the same
  6261. shape as the DataFrame.
  6262. >>> df.clip(lower=np.array([[3, 4], [2, 2], [6, 2]]))
  6263. A B
  6264. 0 3 4
  6265. 1 3 4
  6266. 2 6 6
  6267. Control how `threshold` is broadcast with `axis`. In this case
  6268. `threshold` should be the same length as the axis specified by
  6269. `axis`.
  6270. >>> df.clip(lower=[3, 3, 5], axis='index')
  6271. A B
  6272. 0 3 3
  6273. 1 3 4
  6274. 2 5 6
  6275. >>> df.clip(lower=[4, 5], axis='columns')
  6276. A B
  6277. 0 4 5
  6278. 1 4 5
  6279. 2 5 6
  6280. """
  6281. warnings.warn('clip_lower(threshold) is deprecated, '
  6282. 'use clip(lower=threshold) instead',
  6283. FutureWarning, stacklevel=2)
  6284. return self._clip_with_one_bound(threshold, method=self.ge,
  6285. axis=axis, inplace=inplace)
  6286. def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
  6287. group_keys=True, squeeze=False, observed=False, **kwargs):
  6288. """
  6289. Group DataFrame or Series using a mapper or by a Series of columns.
  6290. A groupby operation involves some combination of splitting the
  6291. object, applying a function, and combining the results. This can be
  6292. used to group large amounts of data and compute operations on these
  6293. groups.
  6294. Parameters
  6295. ----------
  6296. by : mapping, function, label, or list of labels
  6297. Used to determine the groups for the groupby.
  6298. If ``by`` is a function, it's called on each value of the object's
  6299. index. If a dict or Series is passed, the Series or dict VALUES
  6300. will be used to determine the groups (the Series' values are first
  6301. aligned; see ``.align()`` method). If an ndarray is passed, the
  6302. values are used as-is determine the groups. A label or list of
  6303. labels may be passed to group by the columns in ``self``. Notice
  6304. that a tuple is interpreted a (single) key.
  6305. axis : {0 or 'index', 1 or 'columns'}, default 0
  6306. Split along rows (0) or columns (1).
  6307. level : int, level name, or sequence of such, default None
  6308. If the axis is a MultiIndex (hierarchical), group by a particular
  6309. level or levels.
  6310. as_index : bool, default True
  6311. For aggregated output, return object with group labels as the
  6312. index. Only relevant for DataFrame input. as_index=False is
  6313. effectively "SQL-style" grouped output.
  6314. sort : bool, default True
  6315. Sort group keys. Get better performance by turning this off.
  6316. Note this does not influence the order of observations within each
  6317. group. Groupby preserves the order of rows within each group.
  6318. group_keys : bool, default True
  6319. When calling apply, add group keys to index to identify pieces.
  6320. squeeze : bool, default False
  6321. Reduce the dimensionality of the return type if possible,
  6322. otherwise return a consistent type.
  6323. observed : bool, default False
  6324. This only applies if any of the groupers are Categoricals.
  6325. If True: only show observed values for categorical groupers.
  6326. If False: show all values for categorical groupers.
  6327. .. versionadded:: 0.23.0
  6328. **kwargs
  6329. Optional, only accepts keyword argument 'mutated' and is passed
  6330. to groupby.
  6331. Returns
  6332. -------
  6333. DataFrameGroupBy or SeriesGroupBy
  6334. Depends on the calling object and returns groupby object that
  6335. contains information about the groups.
  6336. See Also
  6337. --------
  6338. resample : Convenience method for frequency conversion and resampling
  6339. of time series.
  6340. Notes
  6341. -----
  6342. See the `user guide
  6343. <http://pandas.pydata.org/pandas-docs/stable/groupby.html>`_ for more.
  6344. Examples
  6345. --------
  6346. >>> df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
  6347. ... 'Parrot', 'Parrot'],
  6348. ... 'Max Speed': [380., 370., 24., 26.]})
  6349. >>> df
  6350. Animal Max Speed
  6351. 0 Falcon 380.0
  6352. 1 Falcon 370.0
  6353. 2 Parrot 24.0
  6354. 3 Parrot 26.0
  6355. >>> df.groupby(['Animal']).mean()
  6356. Max Speed
  6357. Animal
  6358. Falcon 375.0
  6359. Parrot 25.0
  6360. **Hierarchical Indexes**
  6361. We can groupby different levels of a hierarchical index
  6362. using the `level` parameter:
  6363. >>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
  6364. ... ['Captive', 'Wild', 'Captive', 'Wild']]
  6365. >>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
  6366. >>> df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},
  6367. ... index=index)
  6368. >>> df
  6369. Max Speed
  6370. Animal Type
  6371. Falcon Captive 390.0
  6372. Wild 350.0
  6373. Parrot Captive 30.0
  6374. Wild 20.0
  6375. >>> df.groupby(level=0).mean()
  6376. Max Speed
  6377. Animal
  6378. Falcon 370.0
  6379. Parrot 25.0
  6380. >>> df.groupby(level=1).mean()
  6381. Max Speed
  6382. Type
  6383. Captive 210.0
  6384. Wild 185.0
  6385. """
  6386. from pandas.core.groupby.groupby import groupby
  6387. if level is None and by is None:
  6388. raise TypeError("You have to supply one of 'by' and 'level'")
  6389. axis = self._get_axis_number(axis)
  6390. return groupby(self, by=by, axis=axis, level=level, as_index=as_index,
  6391. sort=sort, group_keys=group_keys, squeeze=squeeze,
  6392. observed=observed, **kwargs)
  6393. def asfreq(self, freq, method=None, how=None, normalize=False,
  6394. fill_value=None):
  6395. """
  6396. Convert TimeSeries to specified frequency.
  6397. Optionally provide filling method to pad/backfill missing values.
  6398. Returns the original data conformed to a new index with the specified
  6399. frequency. ``resample`` is more appropriate if an operation, such as
  6400. summarization, is necessary to represent the data at the new frequency.
  6401. Parameters
  6402. ----------
  6403. freq : DateOffset object, or string
  6404. method : {'backfill'/'bfill', 'pad'/'ffill'}, default None
  6405. Method to use for filling holes in reindexed Series (note this
  6406. does not fill NaNs that already were present):
  6407. * 'pad' / 'ffill': propagate last valid observation forward to next
  6408. valid
  6409. * 'backfill' / 'bfill': use NEXT valid observation to fill
  6410. how : {'start', 'end'}, default end
  6411. For PeriodIndex only, see PeriodIndex.asfreq
  6412. normalize : bool, default False
  6413. Whether to reset output index to midnight
  6414. fill_value : scalar, optional
  6415. Value to use for missing values, applied during upsampling (note
  6416. this does not fill NaNs that already were present).
  6417. .. versionadded:: 0.20.0
  6418. Returns
  6419. -------
  6420. converted : same type as caller
  6421. See Also
  6422. --------
  6423. reindex
  6424. Notes
  6425. -----
  6426. To learn more about the frequency strings, please see `this link
  6427. <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
  6428. Examples
  6429. --------
  6430. Start by creating a series with 4 one minute timestamps.
  6431. >>> index = pd.date_range('1/1/2000', periods=4, freq='T')
  6432. >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)
  6433. >>> df = pd.DataFrame({'s':series})
  6434. >>> df
  6435. s
  6436. 2000-01-01 00:00:00 0.0
  6437. 2000-01-01 00:01:00 NaN
  6438. 2000-01-01 00:02:00 2.0
  6439. 2000-01-01 00:03:00 3.0
  6440. Upsample the series into 30 second bins.
  6441. >>> df.asfreq(freq='30S')
  6442. s
  6443. 2000-01-01 00:00:00 0.0
  6444. 2000-01-01 00:00:30 NaN
  6445. 2000-01-01 00:01:00 NaN
  6446. 2000-01-01 00:01:30 NaN
  6447. 2000-01-01 00:02:00 2.0
  6448. 2000-01-01 00:02:30 NaN
  6449. 2000-01-01 00:03:00 3.0
  6450. Upsample again, providing a ``fill value``.
  6451. >>> df.asfreq(freq='30S', fill_value=9.0)
  6452. s
  6453. 2000-01-01 00:00:00 0.0
  6454. 2000-01-01 00:00:30 9.0
  6455. 2000-01-01 00:01:00 NaN
  6456. 2000-01-01 00:01:30 9.0
  6457. 2000-01-01 00:02:00 2.0
  6458. 2000-01-01 00:02:30 9.0
  6459. 2000-01-01 00:03:00 3.0
  6460. Upsample again, providing a ``method``.
  6461. >>> df.asfreq(freq='30S', method='bfill')
  6462. s
  6463. 2000-01-01 00:00:00 0.0
  6464. 2000-01-01 00:00:30 NaN
  6465. 2000-01-01 00:01:00 NaN
  6466. 2000-01-01 00:01:30 2.0
  6467. 2000-01-01 00:02:00 2.0
  6468. 2000-01-01 00:02:30 3.0
  6469. 2000-01-01 00:03:00 3.0
  6470. """
  6471. from pandas.core.resample import asfreq
  6472. return asfreq(self, freq, method=method, how=how, normalize=normalize,
  6473. fill_value=fill_value)
  6474. def at_time(self, time, asof=False, axis=None):
  6475. """
  6476. Select values at particular time of day (e.g. 9:30AM).
  6477. Parameters
  6478. ----------
  6479. time : datetime.time or str
  6480. axis : {0 or 'index', 1 or 'columns'}, default 0
  6481. .. versionadded:: 0.24.0
  6482. Returns
  6483. -------
  6484. Series or DataFrame
  6485. Raises
  6486. ------
  6487. TypeError
  6488. If the index is not a :class:`DatetimeIndex`
  6489. See Also
  6490. --------
  6491. between_time : Select values between particular times of the day.
  6492. first : Select initial periods of time series based on a date offset.
  6493. last : Select final periods of time series based on a date offset.
  6494. DatetimeIndex.indexer_at_time : Get just the index locations for
  6495. values at particular time of the day.
  6496. Examples
  6497. --------
  6498. >>> i = pd.date_range('2018-04-09', periods=4, freq='12H')
  6499. >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
  6500. >>> ts
  6501. A
  6502. 2018-04-09 00:00:00 1
  6503. 2018-04-09 12:00:00 2
  6504. 2018-04-10 00:00:00 3
  6505. 2018-04-10 12:00:00 4
  6506. >>> ts.at_time('12:00')
  6507. A
  6508. 2018-04-09 12:00:00 2
  6509. 2018-04-10 12:00:00 4
  6510. """
  6511. if axis is None:
  6512. axis = self._stat_axis_number
  6513. axis = self._get_axis_number(axis)
  6514. index = self._get_axis(axis)
  6515. try:
  6516. indexer = index.indexer_at_time(time, asof=asof)
  6517. except AttributeError:
  6518. raise TypeError('Index must be DatetimeIndex')
  6519. return self._take(indexer, axis=axis)
  6520. def between_time(self, start_time, end_time, include_start=True,
  6521. include_end=True, axis=None):
  6522. """
  6523. Select values between particular times of the day (e.g., 9:00-9:30 AM).
  6524. By setting ``start_time`` to be later than ``end_time``,
  6525. you can get the times that are *not* between the two times.
  6526. Parameters
  6527. ----------
  6528. start_time : datetime.time or str
  6529. end_time : datetime.time or str
  6530. include_start : bool, default True
  6531. include_end : bool, default True
  6532. axis : {0 or 'index', 1 or 'columns'}, default 0
  6533. .. versionadded:: 0.24.0
  6534. Returns
  6535. -------
  6536. Series or DataFrame
  6537. Raises
  6538. ------
  6539. TypeError
  6540. If the index is not a :class:`DatetimeIndex`
  6541. See Also
  6542. --------
  6543. at_time : Select values at a particular time of the day.
  6544. first : Select initial periods of time series based on a date offset.
  6545. last : Select final periods of time series based on a date offset.
  6546. DatetimeIndex.indexer_between_time : Get just the index locations for
  6547. values between particular times of the day.
  6548. Examples
  6549. --------
  6550. >>> i = pd.date_range('2018-04-09', periods=4, freq='1D20min')
  6551. >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
  6552. >>> ts
  6553. A
  6554. 2018-04-09 00:00:00 1
  6555. 2018-04-10 00:20:00 2
  6556. 2018-04-11 00:40:00 3
  6557. 2018-04-12 01:00:00 4
  6558. >>> ts.between_time('0:15', '0:45')
  6559. A
  6560. 2018-04-10 00:20:00 2
  6561. 2018-04-11 00:40:00 3
  6562. You get the times that are *not* between two times by setting
  6563. ``start_time`` later than ``end_time``:
  6564. >>> ts.between_time('0:45', '0:15')
  6565. A
  6566. 2018-04-09 00:00:00 1
  6567. 2018-04-12 01:00:00 4
  6568. """
  6569. if axis is None:
  6570. axis = self._stat_axis_number
  6571. axis = self._get_axis_number(axis)
  6572. index = self._get_axis(axis)
  6573. try:
  6574. indexer = index.indexer_between_time(
  6575. start_time, end_time, include_start=include_start,
  6576. include_end=include_end)
  6577. except AttributeError:
  6578. raise TypeError('Index must be DatetimeIndex')
  6579. return self._take(indexer, axis=axis)
  6580. def resample(self, rule, how=None, axis=0, fill_method=None, closed=None,
  6581. label=None, convention='start', kind=None, loffset=None,
  6582. limit=None, base=0, on=None, level=None):
  6583. """
  6584. Resample time-series data.
  6585. Convenience method for frequency conversion and resampling of time
  6586. series. Object must have a datetime-like index (`DatetimeIndex`,
  6587. `PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values
  6588. to the `on` or `level` keyword.
  6589. Parameters
  6590. ----------
  6591. rule : str
  6592. The offset string or object representing target conversion.
  6593. how : str
  6594. Method for down/re-sampling, default to 'mean' for downsampling.
  6595. .. deprecated:: 0.18.0
  6596. The new syntax is ``.resample(...).mean()``, or
  6597. ``.resample(...).apply(<func>)``
  6598. axis : {0 or 'index', 1 or 'columns'}, default 0
  6599. Which axis to use for up- or down-sampling. For `Series` this
  6600. will default to 0, i.e. along the rows. Must be
  6601. `DatetimeIndex`, `TimedeltaIndex` or `PeriodIndex`.
  6602. fill_method : str, default None
  6603. Filling method for upsampling.
  6604. .. deprecated:: 0.18.0
  6605. The new syntax is ``.resample(...).<func>()``,
  6606. e.g. ``.resample(...).pad()``
  6607. closed : {'right', 'left'}, default None
  6608. Which side of bin interval is closed. The default is 'left'
  6609. for all frequency offsets except for 'M', 'A', 'Q', 'BM',
  6610. 'BA', 'BQ', and 'W' which all have a default of 'right'.
  6611. label : {'right', 'left'}, default None
  6612. Which bin edge label to label bucket with. The default is 'left'
  6613. for all frequency offsets except for 'M', 'A', 'Q', 'BM',
  6614. 'BA', 'BQ', and 'W' which all have a default of 'right'.
  6615. convention : {'start', 'end', 's', 'e'}, default 'start'
  6616. For `PeriodIndex` only, controls whether to use the start or
  6617. end of `rule`.
  6618. kind : {'timestamp', 'period'}, optional, default None
  6619. Pass 'timestamp' to convert the resulting index to a
  6620. `DateTimeIndex` or 'period' to convert it to a `PeriodIndex`.
  6621. By default the input representation is retained.
  6622. loffset : timedelta, default None
  6623. Adjust the resampled time labels.
  6624. limit : int, default None
  6625. Maximum size gap when reindexing with `fill_method`.
  6626. .. deprecated:: 0.18.0
  6627. base : int, default 0
  6628. For frequencies that evenly subdivide 1 day, the "origin" of the
  6629. aggregated intervals. For example, for '5min' frequency, base could
  6630. range from 0 through 4. Defaults to 0.
  6631. on : str, optional
  6632. For a DataFrame, column to use instead of index for resampling.
  6633. Column must be datetime-like.
  6634. .. versionadded:: 0.19.0
  6635. level : str or int, optional
  6636. For a MultiIndex, level (name or number) to use for
  6637. resampling. `level` must be datetime-like.
  6638. .. versionadded:: 0.19.0
  6639. Returns
  6640. -------
  6641. Resampler object
  6642. See Also
  6643. --------
  6644. groupby : Group by mapping, function, label, or list of labels.
  6645. Series.resample : Resample a Series.
  6646. DataFrame.resample: Resample a DataFrame.
  6647. Notes
  6648. -----
  6649. See the `user guide
  6650. <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling>`_
  6651. for more.
  6652. To learn more about the offset strings, please see `this link
  6653. <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
  6654. Examples
  6655. --------
  6656. Start by creating a series with 9 one minute timestamps.
  6657. >>> index = pd.date_range('1/1/2000', periods=9, freq='T')
  6658. >>> series = pd.Series(range(9), index=index)
  6659. >>> series
  6660. 2000-01-01 00:00:00 0
  6661. 2000-01-01 00:01:00 1
  6662. 2000-01-01 00:02:00 2
  6663. 2000-01-01 00:03:00 3
  6664. 2000-01-01 00:04:00 4
  6665. 2000-01-01 00:05:00 5
  6666. 2000-01-01 00:06:00 6
  6667. 2000-01-01 00:07:00 7
  6668. 2000-01-01 00:08:00 8
  6669. Freq: T, dtype: int64
  6670. Downsample the series into 3 minute bins and sum the values
  6671. of the timestamps falling into a bin.
  6672. >>> series.resample('3T').sum()
  6673. 2000-01-01 00:00:00 3
  6674. 2000-01-01 00:03:00 12
  6675. 2000-01-01 00:06:00 21
  6676. Freq: 3T, dtype: int64
  6677. Downsample the series into 3 minute bins as above, but label each
  6678. bin using the right edge instead of the left. Please note that the
  6679. value in the bucket used as the label is not included in the bucket,
  6680. which it labels. For example, in the original series the
  6681. bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed
  6682. value in the resampled bucket with the label ``2000-01-01 00:03:00``
  6683. does not include 3 (if it did, the summed value would be 6, not 3).
  6684. To include this value close the right side of the bin interval as
  6685. illustrated in the example below this one.
  6686. >>> series.resample('3T', label='right').sum()
  6687. 2000-01-01 00:03:00 3
  6688. 2000-01-01 00:06:00 12
  6689. 2000-01-01 00:09:00 21
  6690. Freq: 3T, dtype: int64
  6691. Downsample the series into 3 minute bins as above, but close the right
  6692. side of the bin interval.
  6693. >>> series.resample('3T', label='right', closed='right').sum()
  6694. 2000-01-01 00:00:00 0
  6695. 2000-01-01 00:03:00 6
  6696. 2000-01-01 00:06:00 15
  6697. 2000-01-01 00:09:00 15
  6698. Freq: 3T, dtype: int64
  6699. Upsample the series into 30 second bins.
  6700. >>> series.resample('30S').asfreq()[0:5] # Select first 5 rows
  6701. 2000-01-01 00:00:00 0.0
  6702. 2000-01-01 00:00:30 NaN
  6703. 2000-01-01 00:01:00 1.0
  6704. 2000-01-01 00:01:30 NaN
  6705. 2000-01-01 00:02:00 2.0
  6706. Freq: 30S, dtype: float64
  6707. Upsample the series into 30 second bins and fill the ``NaN``
  6708. values using the ``pad`` method.
  6709. >>> series.resample('30S').pad()[0:5]
  6710. 2000-01-01 00:00:00 0
  6711. 2000-01-01 00:00:30 0
  6712. 2000-01-01 00:01:00 1
  6713. 2000-01-01 00:01:30 1
  6714. 2000-01-01 00:02:00 2
  6715. Freq: 30S, dtype: int64
  6716. Upsample the series into 30 second bins and fill the
  6717. ``NaN`` values using the ``bfill`` method.
  6718. >>> series.resample('30S').bfill()[0:5]
  6719. 2000-01-01 00:00:00 0
  6720. 2000-01-01 00:00:30 1
  6721. 2000-01-01 00:01:00 1
  6722. 2000-01-01 00:01:30 2
  6723. 2000-01-01 00:02:00 2
  6724. Freq: 30S, dtype: int64
  6725. Pass a custom function via ``apply``
  6726. >>> def custom_resampler(array_like):
  6727. ... return np.sum(array_like) + 5
  6728. ...
  6729. >>> series.resample('3T').apply(custom_resampler)
  6730. 2000-01-01 00:00:00 8
  6731. 2000-01-01 00:03:00 17
  6732. 2000-01-01 00:06:00 26
  6733. Freq: 3T, dtype: int64
  6734. For a Series with a PeriodIndex, the keyword `convention` can be
  6735. used to control whether to use the start or end of `rule`.
  6736. Resample a year by quarter using 'start' `convention`. Values are
  6737. assigned to the first quarter of the period.
  6738. >>> s = pd.Series([1, 2], index=pd.period_range('2012-01-01',
  6739. ... freq='A',
  6740. ... periods=2))
  6741. >>> s
  6742. 2012 1
  6743. 2013 2
  6744. Freq: A-DEC, dtype: int64
  6745. >>> s.resample('Q', convention='start').asfreq()
  6746. 2012Q1 1.0
  6747. 2012Q2 NaN
  6748. 2012Q3 NaN
  6749. 2012Q4 NaN
  6750. 2013Q1 2.0
  6751. 2013Q2 NaN
  6752. 2013Q3 NaN
  6753. 2013Q4 NaN
  6754. Freq: Q-DEC, dtype: float64
  6755. Resample quarters by month using 'end' `convention`. Values are
  6756. assigned to the last month of the period.
  6757. >>> q = pd.Series([1, 2, 3, 4], index=pd.period_range('2018-01-01',
  6758. ... freq='Q',
  6759. ... periods=4))
  6760. >>> q
  6761. 2018Q1 1
  6762. 2018Q2 2
  6763. 2018Q3 3
  6764. 2018Q4 4
  6765. Freq: Q-DEC, dtype: int64
  6766. >>> q.resample('M', convention='end').asfreq()
  6767. 2018-03 1.0
  6768. 2018-04 NaN
  6769. 2018-05 NaN
  6770. 2018-06 2.0
  6771. 2018-07 NaN
  6772. 2018-08 NaN
  6773. 2018-09 3.0
  6774. 2018-10 NaN
  6775. 2018-11 NaN
  6776. 2018-12 4.0
  6777. Freq: M, dtype: float64
  6778. For DataFrame objects, the keyword `on` can be used to specify the
  6779. column instead of the index for resampling.
  6780. >>> d = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
  6781. ... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
  6782. >>> df = pd.DataFrame(d)
  6783. >>> df['week_starting'] = pd.date_range('01/01/2018',
  6784. ... periods=8,
  6785. ... freq='W')
  6786. >>> df
  6787. price volume week_starting
  6788. 0 10 50 2018-01-07
  6789. 1 11 60 2018-01-14
  6790. 2 9 40 2018-01-21
  6791. 3 13 100 2018-01-28
  6792. 4 14 50 2018-02-04
  6793. 5 18 100 2018-02-11
  6794. 6 17 40 2018-02-18
  6795. 7 19 50 2018-02-25
  6796. >>> df.resample('M', on='week_starting').mean()
  6797. price volume
  6798. week_starting
  6799. 2018-01-31 10.75 62.5
  6800. 2018-02-28 17.00 60.0
  6801. For a DataFrame with MultiIndex, the keyword `level` can be used to
  6802. specify on which level the resampling needs to take place.
  6803. >>> days = pd.date_range('1/1/2000', periods=4, freq='D')
  6804. >>> d2 = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
  6805. ... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
  6806. >>> df2 = pd.DataFrame(d2,
  6807. ... index=pd.MultiIndex.from_product([days,
  6808. ... ['morning',
  6809. ... 'afternoon']]
  6810. ... ))
  6811. >>> df2
  6812. price volume
  6813. 2000-01-01 morning 10 50
  6814. afternoon 11 60
  6815. 2000-01-02 morning 9 40
  6816. afternoon 13 100
  6817. 2000-01-03 morning 14 50
  6818. afternoon 18 100
  6819. 2000-01-04 morning 17 40
  6820. afternoon 19 50
  6821. >>> df2.resample('D', level=0).sum()
  6822. price volume
  6823. 2000-01-01 21 110
  6824. 2000-01-02 22 140
  6825. 2000-01-03 32 150
  6826. 2000-01-04 36 90
  6827. """
  6828. from pandas.core.resample import (resample,
  6829. _maybe_process_deprecations)
  6830. axis = self._get_axis_number(axis)
  6831. r = resample(self, freq=rule, label=label, closed=closed,
  6832. axis=axis, kind=kind, loffset=loffset,
  6833. convention=convention,
  6834. base=base, key=on, level=level)
  6835. return _maybe_process_deprecations(r,
  6836. how=how,
  6837. fill_method=fill_method,
  6838. limit=limit)
  6839. def first(self, offset):
  6840. """
  6841. Convenience method for subsetting initial periods of time series data
  6842. based on a date offset.
  6843. Parameters
  6844. ----------
  6845. offset : string, DateOffset, dateutil.relativedelta
  6846. Returns
  6847. -------
  6848. subset : same type as caller
  6849. Raises
  6850. ------
  6851. TypeError
  6852. If the index is not a :class:`DatetimeIndex`
  6853. See Also
  6854. --------
  6855. last : Select final periods of time series based on a date offset.
  6856. at_time : Select values at a particular time of the day.
  6857. between_time : Select values between particular times of the day.
  6858. Examples
  6859. --------
  6860. >>> i = pd.date_range('2018-04-09', periods=4, freq='2D')
  6861. >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)
  6862. >>> ts
  6863. A
  6864. 2018-04-09 1
  6865. 2018-04-11 2
  6866. 2018-04-13 3
  6867. 2018-04-15 4
  6868. Get the rows for the first 3 days:
  6869. >>> ts.first('3D')
  6870. A
  6871. 2018-04-09 1
  6872. 2018-04-11 2
  6873. Notice the data for 3 first calender days were returned, not the first
  6874. 3 days observed in the dataset, and therefore data for 2018-04-13 was
  6875. not returned.
  6876. """
  6877. if not isinstance(self.index, DatetimeIndex):
  6878. raise TypeError("'first' only supports a DatetimeIndex index")
  6879. if len(self.index) == 0:
  6880. return self
  6881. offset = to_offset(offset)
  6882. end_date = end = self.index[0] + offset
  6883. # Tick-like, e.g. 3 weeks
  6884. if not offset.isAnchored() and hasattr(offset, '_inc'):
  6885. if end_date in self.index:
  6886. end = self.index.searchsorted(end_date, side='left')
  6887. return self.iloc[:end]
  6888. return self.loc[:end]
  6889. def last(self, offset):
  6890. """
  6891. Convenience method for subsetting final periods of time series data
  6892. based on a date offset.
  6893. Parameters
  6894. ----------
  6895. offset : string, DateOffset, dateutil.relativedelta
  6896. Returns
  6897. -------
  6898. subset : same type as caller
  6899. Raises
  6900. ------
  6901. TypeError
  6902. If the index is not a :class:`DatetimeIndex`
  6903. See Also
  6904. --------
  6905. first : Select initial periods of time series based on a date offset.
  6906. at_time : Select values at a particular time of the day.
  6907. between_time : Select values between particular times of the day.
  6908. Examples
  6909. --------
  6910. >>> i = pd.date_range('2018-04-09', periods=4, freq='2D')
  6911. >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)
  6912. >>> ts
  6913. A
  6914. 2018-04-09 1
  6915. 2018-04-11 2
  6916. 2018-04-13 3
  6917. 2018-04-15 4
  6918. Get the rows for the last 3 days:
  6919. >>> ts.last('3D')
  6920. A
  6921. 2018-04-13 3
  6922. 2018-04-15 4
  6923. Notice the data for 3 last calender days were returned, not the last
  6924. 3 observed days in the dataset, and therefore data for 2018-04-11 was
  6925. not returned.
  6926. """
  6927. if not isinstance(self.index, DatetimeIndex):
  6928. raise TypeError("'last' only supports a DatetimeIndex index")
  6929. if len(self.index) == 0:
  6930. return self
  6931. offset = to_offset(offset)
  6932. start_date = self.index[-1] - offset
  6933. start = self.index.searchsorted(start_date, side='right')
  6934. return self.iloc[start:]
  6935. def rank(self, axis=0, method='average', numeric_only=None,
  6936. na_option='keep', ascending=True, pct=False):
  6937. """
  6938. Compute numerical data ranks (1 through n) along axis. Equal values are
  6939. assigned a rank that is the average of the ranks of those values.
  6940. Parameters
  6941. ----------
  6942. axis : {0 or 'index', 1 or 'columns'}, default 0
  6943. index to direct ranking
  6944. method : {'average', 'min', 'max', 'first', 'dense'}
  6945. * average: average rank of group
  6946. * min: lowest rank in group
  6947. * max: highest rank in group
  6948. * first: ranks assigned in order they appear in the array
  6949. * dense: like 'min', but rank always increases by 1 between groups
  6950. numeric_only : boolean, default None
  6951. Include only float, int, boolean data. Valid only for DataFrame or
  6952. Panel objects
  6953. na_option : {'keep', 'top', 'bottom'}
  6954. * keep: leave NA values where they are
  6955. * top: smallest rank if ascending
  6956. * bottom: smallest rank if descending
  6957. ascending : boolean, default True
  6958. False for ranks by high (1) to low (N)
  6959. pct : boolean, default False
  6960. Computes percentage rank of data
  6961. Returns
  6962. -------
  6963. ranks : same type as caller
  6964. """
  6965. axis = self._get_axis_number(axis)
  6966. if self.ndim > 2:
  6967. msg = "rank does not make sense when ndim > 2"
  6968. raise NotImplementedError(msg)
  6969. if na_option not in {'keep', 'top', 'bottom'}:
  6970. msg = "na_option must be one of 'keep', 'top', or 'bottom'"
  6971. raise ValueError(msg)
  6972. def ranker(data):
  6973. ranks = algos.rank(data.values, axis=axis, method=method,
  6974. ascending=ascending, na_option=na_option,
  6975. pct=pct)
  6976. ranks = self._constructor(ranks, **data._construct_axes_dict())
  6977. return ranks.__finalize__(self)
  6978. # if numeric_only is None, and we can't get anything, we try with
  6979. # numeric_only=True
  6980. if numeric_only is None:
  6981. try:
  6982. return ranker(self)
  6983. except TypeError:
  6984. numeric_only = True
  6985. if numeric_only:
  6986. data = self._get_numeric_data()
  6987. else:
  6988. data = self
  6989. return ranker(data)
  6990. _shared_docs['align'] = ("""
  6991. Align two objects on their axes with the
  6992. specified join method for each axis Index.
  6993. Parameters
  6994. ----------
  6995. other : DataFrame or Series
  6996. join : {'outer', 'inner', 'left', 'right'}, default 'outer'
  6997. axis : allowed axis of the other object, default None
  6998. Align on index (0), columns (1), or both (None)
  6999. level : int or level name, default None
  7000. Broadcast across a level, matching Index values on the
  7001. passed MultiIndex level
  7002. copy : boolean, default True
  7003. Always returns new objects. If copy=False and no reindexing is
  7004. required then original objects are returned.
  7005. fill_value : scalar, default np.NaN
  7006. Value to use for missing values. Defaults to NaN, but can be any
  7007. "compatible" value
  7008. method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
  7009. Method to use for filling holes in reindexed Series
  7010. pad / ffill: propagate last valid observation forward to next valid
  7011. backfill / bfill: use NEXT valid observation to fill gap
  7012. limit : int, default None
  7013. If method is specified, this is the maximum number of consecutive
  7014. NaN values to forward/backward fill. In other words, if there is
  7015. a gap with more than this number of consecutive NaNs, it will only
  7016. be partially filled. If method is not specified, this is the
  7017. maximum number of entries along the entire axis where NaNs will be
  7018. filled. Must be greater than 0 if not None.
  7019. fill_axis : %(axes_single_arg)s, default 0
  7020. Filling axis, method and limit
  7021. broadcast_axis : %(axes_single_arg)s, default None
  7022. Broadcast values along this axis, if aligning two objects of
  7023. different dimensions
  7024. Returns
  7025. -------
  7026. (left, right) : (%(klass)s, type of other)
  7027. Aligned objects.
  7028. """)
  7029. @Appender(_shared_docs['align'] % _shared_doc_kwargs)
  7030. def align(self, other, join='outer', axis=None, level=None, copy=True,
  7031. fill_value=None, method=None, limit=None, fill_axis=0,
  7032. broadcast_axis=None):
  7033. from pandas import DataFrame, Series
  7034. method = missing.clean_fill_method(method)
  7035. if broadcast_axis == 1 and self.ndim != other.ndim:
  7036. if isinstance(self, Series):
  7037. # this means other is a DataFrame, and we need to broadcast
  7038. # self
  7039. cons = self._constructor_expanddim
  7040. df = cons({c: self for c in other.columns},
  7041. **other._construct_axes_dict())
  7042. return df._align_frame(other, join=join, axis=axis,
  7043. level=level, copy=copy,
  7044. fill_value=fill_value, method=method,
  7045. limit=limit, fill_axis=fill_axis)
  7046. elif isinstance(other, Series):
  7047. # this means self is a DataFrame, and we need to broadcast
  7048. # other
  7049. cons = other._constructor_expanddim
  7050. df = cons({c: other for c in self.columns},
  7051. **self._construct_axes_dict())
  7052. return self._align_frame(df, join=join, axis=axis, level=level,
  7053. copy=copy, fill_value=fill_value,
  7054. method=method, limit=limit,
  7055. fill_axis=fill_axis)
  7056. if axis is not None:
  7057. axis = self._get_axis_number(axis)
  7058. if isinstance(other, DataFrame):
  7059. return self._align_frame(other, join=join, axis=axis, level=level,
  7060. copy=copy, fill_value=fill_value,
  7061. method=method, limit=limit,
  7062. fill_axis=fill_axis)
  7063. elif isinstance(other, Series):
  7064. return self._align_series(other, join=join, axis=axis, level=level,
  7065. copy=copy, fill_value=fill_value,
  7066. method=method, limit=limit,
  7067. fill_axis=fill_axis)
  7068. else: # pragma: no cover
  7069. raise TypeError('unsupported type: %s' % type(other))
  7070. def _align_frame(self, other, join='outer', axis=None, level=None,
  7071. copy=True, fill_value=None, method=None, limit=None,
  7072. fill_axis=0):
  7073. # defaults
  7074. join_index, join_columns = None, None
  7075. ilidx, iridx = None, None
  7076. clidx, cridx = None, None
  7077. is_series = isinstance(self, ABCSeries)
  7078. if axis is None or axis == 0:
  7079. if not self.index.equals(other.index):
  7080. join_index, ilidx, iridx = self.index.join(
  7081. other.index, how=join, level=level, return_indexers=True)
  7082. if axis is None or axis == 1:
  7083. if not is_series and not self.columns.equals(other.columns):
  7084. join_columns, clidx, cridx = self.columns.join(
  7085. other.columns, how=join, level=level, return_indexers=True)
  7086. if is_series:
  7087. reindexers = {0: [join_index, ilidx]}
  7088. else:
  7089. reindexers = {0: [join_index, ilidx], 1: [join_columns, clidx]}
  7090. left = self._reindex_with_indexers(reindexers, copy=copy,
  7091. fill_value=fill_value,
  7092. allow_dups=True)
  7093. # other must be always DataFrame
  7094. right = other._reindex_with_indexers({0: [join_index, iridx],
  7095. 1: [join_columns, cridx]},
  7096. copy=copy, fill_value=fill_value,
  7097. allow_dups=True)
  7098. if method is not None:
  7099. left = left.fillna(axis=fill_axis, method=method, limit=limit)
  7100. right = right.fillna(axis=fill_axis, method=method, limit=limit)
  7101. # if DatetimeIndex have different tz, convert to UTC
  7102. if is_datetime64tz_dtype(left.index):
  7103. if left.index.tz != right.index.tz:
  7104. if join_index is not None:
  7105. left.index = join_index
  7106. right.index = join_index
  7107. return left.__finalize__(self), right.__finalize__(other)
  7108. def _align_series(self, other, join='outer', axis=None, level=None,
  7109. copy=True, fill_value=None, method=None, limit=None,
  7110. fill_axis=0):
  7111. is_series = isinstance(self, ABCSeries)
  7112. # series/series compat, other must always be a Series
  7113. if is_series:
  7114. if axis:
  7115. raise ValueError('cannot align series to a series other than '
  7116. 'axis 0')
  7117. # equal
  7118. if self.index.equals(other.index):
  7119. join_index, lidx, ridx = None, None, None
  7120. else:
  7121. join_index, lidx, ridx = self.index.join(other.index, how=join,
  7122. level=level,
  7123. return_indexers=True)
  7124. left = self._reindex_indexer(join_index, lidx, copy)
  7125. right = other._reindex_indexer(join_index, ridx, copy)
  7126. else:
  7127. # one has > 1 ndim
  7128. fdata = self._data
  7129. if axis == 0:
  7130. join_index = self.index
  7131. lidx, ridx = None, None
  7132. if not self.index.equals(other.index):
  7133. join_index, lidx, ridx = self.index.join(
  7134. other.index, how=join, level=level,
  7135. return_indexers=True)
  7136. if lidx is not None:
  7137. fdata = fdata.reindex_indexer(join_index, lidx, axis=1)
  7138. elif axis == 1:
  7139. join_index = self.columns
  7140. lidx, ridx = None, None
  7141. if not self.columns.equals(other.index):
  7142. join_index, lidx, ridx = self.columns.join(
  7143. other.index, how=join, level=level,
  7144. return_indexers=True)
  7145. if lidx is not None:
  7146. fdata = fdata.reindex_indexer(join_index, lidx, axis=0)
  7147. else:
  7148. raise ValueError('Must specify axis=0 or 1')
  7149. if copy and fdata is self._data:
  7150. fdata = fdata.copy()
  7151. left = self._constructor(fdata)
  7152. if ridx is None:
  7153. right = other
  7154. else:
  7155. right = other.reindex(join_index, level=level)
  7156. # fill
  7157. fill_na = notna(fill_value) or (method is not None)
  7158. if fill_na:
  7159. left = left.fillna(fill_value, method=method, limit=limit,
  7160. axis=fill_axis)
  7161. right = right.fillna(fill_value, method=method, limit=limit)
  7162. # if DatetimeIndex have different tz, convert to UTC
  7163. if is_series or (not is_series and axis == 0):
  7164. if is_datetime64tz_dtype(left.index):
  7165. if left.index.tz != right.index.tz:
  7166. if join_index is not None:
  7167. left.index = join_index
  7168. right.index = join_index
  7169. return left.__finalize__(self), right.__finalize__(other)
  7170. def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
  7171. errors='raise', try_cast=False):
  7172. """
  7173. Equivalent to public method `where`, except that `other` is not
  7174. applied as a function even if callable. Used in __setitem__.
  7175. """
  7176. inplace = validate_bool_kwarg(inplace, 'inplace')
  7177. # align the cond to same shape as myself
  7178. cond = com.apply_if_callable(cond, self)
  7179. if isinstance(cond, NDFrame):
  7180. cond, _ = cond.align(self, join='right', broadcast_axis=1)
  7181. else:
  7182. if not hasattr(cond, 'shape'):
  7183. cond = np.asanyarray(cond)
  7184. if cond.shape != self.shape:
  7185. raise ValueError('Array conditional must be same shape as '
  7186. 'self')
  7187. cond = self._constructor(cond, **self._construct_axes_dict())
  7188. # make sure we are boolean
  7189. fill_value = bool(inplace)
  7190. cond = cond.fillna(fill_value)
  7191. msg = "Boolean array expected for the condition, not {dtype}"
  7192. if not isinstance(cond, pd.DataFrame):
  7193. # This is a single-dimensional object.
  7194. if not is_bool_dtype(cond):
  7195. raise ValueError(msg.format(dtype=cond.dtype))
  7196. elif not cond.empty:
  7197. for dt in cond.dtypes:
  7198. if not is_bool_dtype(dt):
  7199. raise ValueError(msg.format(dtype=dt))
  7200. cond = -cond if inplace else cond
  7201. # try to align with other
  7202. try_quick = True
  7203. if hasattr(other, 'align'):
  7204. # align with me
  7205. if other.ndim <= self.ndim:
  7206. _, other = self.align(other, join='left', axis=axis,
  7207. level=level, fill_value=np.nan)
  7208. # if we are NOT aligned, raise as we cannot where index
  7209. if (axis is None and
  7210. not all(other._get_axis(i).equals(ax)
  7211. for i, ax in enumerate(self.axes))):
  7212. raise InvalidIndexError
  7213. # slice me out of the other
  7214. else:
  7215. raise NotImplementedError("cannot align with a higher "
  7216. "dimensional NDFrame")
  7217. if isinstance(other, np.ndarray):
  7218. if other.shape != self.shape:
  7219. if self.ndim == 1:
  7220. icond = cond.values
  7221. # GH 2745 / GH 4192
  7222. # treat like a scalar
  7223. if len(other) == 1:
  7224. other = np.array(other[0])
  7225. # GH 3235
  7226. # match True cond to other
  7227. elif len(cond[icond]) == len(other):
  7228. # try to not change dtype at first (if try_quick)
  7229. if try_quick:
  7230. try:
  7231. new_other = com.values_from_object(self)
  7232. new_other = new_other.copy()
  7233. new_other[icond] = other
  7234. other = new_other
  7235. except Exception:
  7236. try_quick = False
  7237. # let's create a new (if we failed at the above
  7238. # or not try_quick
  7239. if not try_quick:
  7240. dtype, fill_value = maybe_promote(other.dtype)
  7241. new_other = np.empty(len(icond), dtype=dtype)
  7242. new_other.fill(fill_value)
  7243. maybe_upcast_putmask(new_other, icond, other)
  7244. other = new_other
  7245. else:
  7246. raise ValueError('Length of replacements must equal '
  7247. 'series length')
  7248. else:
  7249. raise ValueError('other must be the same shape as self '
  7250. 'when an ndarray')
  7251. # we are the same shape, so create an actual object for alignment
  7252. else:
  7253. other = self._constructor(other, **self._construct_axes_dict())
  7254. if axis is None:
  7255. axis = 0
  7256. if self.ndim == getattr(other, 'ndim', 0):
  7257. align = True
  7258. else:
  7259. align = (self._get_axis_number(axis) == 1)
  7260. block_axis = self._get_block_manager_axis(axis)
  7261. if inplace:
  7262. # we may have different type blocks come out of putmask, so
  7263. # reconstruct the block manager
  7264. self._check_inplace_setting(other)
  7265. new_data = self._data.putmask(mask=cond, new=other, align=align,
  7266. inplace=True, axis=block_axis,
  7267. transpose=self._AXIS_REVERSED)
  7268. self._update_inplace(new_data)
  7269. else:
  7270. new_data = self._data.where(other=other, cond=cond, align=align,
  7271. errors=errors,
  7272. try_cast=try_cast, axis=block_axis,
  7273. transpose=self._AXIS_REVERSED)
  7274. return self._constructor(new_data).__finalize__(self)
  7275. _shared_docs['where'] = ("""
  7276. Replace values where the condition is %(cond_rev)s.
  7277. Parameters
  7278. ----------
  7279. cond : boolean %(klass)s, array-like, or callable
  7280. Where `cond` is %(cond)s, keep the original value. Where
  7281. %(cond_rev)s, replace with corresponding value from `other`.
  7282. If `cond` is callable, it is computed on the %(klass)s and
  7283. should return boolean %(klass)s or array. The callable must
  7284. not change input %(klass)s (though pandas doesn't check it).
  7285. .. versionadded:: 0.18.1
  7286. A callable can be used as cond.
  7287. other : scalar, %(klass)s, or callable
  7288. Entries where `cond` is %(cond_rev)s are replaced with
  7289. corresponding value from `other`.
  7290. If other is callable, it is computed on the %(klass)s and
  7291. should return scalar or %(klass)s. The callable must not
  7292. change input %(klass)s (though pandas doesn't check it).
  7293. .. versionadded:: 0.18.1
  7294. A callable can be used as other.
  7295. inplace : boolean, default False
  7296. Whether to perform the operation in place on the data.
  7297. axis : int, default None
  7298. Alignment axis if needed.
  7299. level : int, default None
  7300. Alignment level if needed.
  7301. errors : str, {'raise', 'ignore'}, default `raise`
  7302. Note that currently this parameter won't affect
  7303. the results and will always coerce to a suitable dtype.
  7304. - `raise` : allow exceptions to be raised.
  7305. - `ignore` : suppress exceptions. On error return original object.
  7306. try_cast : boolean, default False
  7307. Try to cast the result back to the input type (if possible).
  7308. raise_on_error : boolean, default True
  7309. Whether to raise on invalid data types (e.g. trying to where on
  7310. strings).
  7311. .. deprecated:: 0.21.0
  7312. Use `errors`.
  7313. Returns
  7314. -------
  7315. wh : same type as caller
  7316. See Also
  7317. --------
  7318. :func:`DataFrame.%(name_other)s` : Return an object of same shape as
  7319. self.
  7320. Notes
  7321. -----
  7322. The %(name)s method is an application of the if-then idiom. For each
  7323. element in the calling DataFrame, if ``cond`` is ``%(cond)s`` the
  7324. element is used; otherwise the corresponding element from the DataFrame
  7325. ``other`` is used.
  7326. The signature for :func:`DataFrame.where` differs from
  7327. :func:`numpy.where`. Roughly ``df1.where(m, df2)`` is equivalent to
  7328. ``np.where(m, df1, df2)``.
  7329. For further details and examples see the ``%(name)s`` documentation in
  7330. :ref:`indexing <indexing.where_mask>`.
  7331. Examples
  7332. --------
  7333. >>> s = pd.Series(range(5))
  7334. >>> s.where(s > 0)
  7335. 0 NaN
  7336. 1 1.0
  7337. 2 2.0
  7338. 3 3.0
  7339. 4 4.0
  7340. dtype: float64
  7341. >>> s.mask(s > 0)
  7342. 0 0.0
  7343. 1 NaN
  7344. 2 NaN
  7345. 3 NaN
  7346. 4 NaN
  7347. dtype: float64
  7348. >>> s.where(s > 1, 10)
  7349. 0 10
  7350. 1 10
  7351. 2 2
  7352. 3 3
  7353. 4 4
  7354. dtype: int64
  7355. >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
  7356. >>> m = df %% 3 == 0
  7357. >>> df.where(m, -df)
  7358. A B
  7359. 0 0 -1
  7360. 1 -2 3
  7361. 2 -4 -5
  7362. 3 6 -7
  7363. 4 -8 9
  7364. >>> df.where(m, -df) == np.where(m, df, -df)
  7365. A B
  7366. 0 True True
  7367. 1 True True
  7368. 2 True True
  7369. 3 True True
  7370. 4 True True
  7371. >>> df.where(m, -df) == df.mask(~m, -df)
  7372. A B
  7373. 0 True True
  7374. 1 True True
  7375. 2 True True
  7376. 3 True True
  7377. 4 True True
  7378. """)
  7379. @Appender(_shared_docs['where'] % dict(_shared_doc_kwargs, cond="True",
  7380. cond_rev="False", name='where',
  7381. name_other='mask'))
  7382. def where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
  7383. errors='raise', try_cast=False, raise_on_error=None):
  7384. if raise_on_error is not None:
  7385. warnings.warn(
  7386. "raise_on_error is deprecated in "
  7387. "favor of errors='raise|ignore'",
  7388. FutureWarning, stacklevel=2)
  7389. if raise_on_error:
  7390. errors = 'raise'
  7391. else:
  7392. errors = 'ignore'
  7393. other = com.apply_if_callable(other, self)
  7394. return self._where(cond, other, inplace, axis, level,
  7395. errors=errors, try_cast=try_cast)
  7396. @Appender(_shared_docs['where'] % dict(_shared_doc_kwargs, cond="False",
  7397. cond_rev="True", name='mask',
  7398. name_other='where'))
  7399. def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None,
  7400. errors='raise', try_cast=False, raise_on_error=None):
  7401. if raise_on_error is not None:
  7402. warnings.warn(
  7403. "raise_on_error is deprecated in "
  7404. "favor of errors='raise|ignore'",
  7405. FutureWarning, stacklevel=2)
  7406. if raise_on_error:
  7407. errors = 'raise'
  7408. else:
  7409. errors = 'ignore'
  7410. inplace = validate_bool_kwarg(inplace, 'inplace')
  7411. cond = com.apply_if_callable(cond, self)
  7412. # see gh-21891
  7413. if not hasattr(cond, "__invert__"):
  7414. cond = np.array(cond)
  7415. return self.where(~cond, other=other, inplace=inplace, axis=axis,
  7416. level=level, try_cast=try_cast,
  7417. errors=errors)
  7418. _shared_docs['shift'] = ("""
  7419. Shift index by desired number of periods with an optional time `freq`.
  7420. When `freq` is not passed, shift the index without realigning the data.
  7421. If `freq` is passed (in this case, the index must be date or datetime,
  7422. or it will raise a `NotImplementedError`), the index will be
  7423. increased using the periods and the `freq`.
  7424. Parameters
  7425. ----------
  7426. periods : int
  7427. Number of periods to shift. Can be positive or negative.
  7428. freq : DateOffset, tseries.offsets, timedelta, or str, optional
  7429. Offset to use from the tseries module or time rule (e.g. 'EOM').
  7430. If `freq` is specified then the index values are shifted but the
  7431. data is not realigned. That is, use `freq` if you would like to
  7432. extend the index when shifting and preserve the original data.
  7433. axis : {0 or 'index', 1 or 'columns', None}, default None
  7434. Shift direction.
  7435. fill_value : object, optional
  7436. The scalar value to use for newly introduced missing values.
  7437. the default depends on the dtype of `self`.
  7438. For numeric data, ``np.nan`` is used.
  7439. For datetime, timedelta, or period data, etc. :attr:`NaT` is used.
  7440. For extension dtypes, ``self.dtype.na_value`` is used.
  7441. .. versionchanged:: 0.24.0
  7442. Returns
  7443. -------
  7444. %(klass)s
  7445. Copy of input object, shifted.
  7446. See Also
  7447. --------
  7448. Index.shift : Shift values of Index.
  7449. DatetimeIndex.shift : Shift values of DatetimeIndex.
  7450. PeriodIndex.shift : Shift values of PeriodIndex.
  7451. tshift : Shift the time index, using the index's frequency if
  7452. available.
  7453. Examples
  7454. --------
  7455. >>> df = pd.DataFrame({'Col1': [10, 20, 15, 30, 45],
  7456. ... 'Col2': [13, 23, 18, 33, 48],
  7457. ... 'Col3': [17, 27, 22, 37, 52]})
  7458. >>> df.shift(periods=3)
  7459. Col1 Col2 Col3
  7460. 0 NaN NaN NaN
  7461. 1 NaN NaN NaN
  7462. 2 NaN NaN NaN
  7463. 3 10.0 13.0 17.0
  7464. 4 20.0 23.0 27.0
  7465. >>> df.shift(periods=1, axis='columns')
  7466. Col1 Col2 Col3
  7467. 0 NaN 10.0 13.0
  7468. 1 NaN 20.0 23.0
  7469. 2 NaN 15.0 18.0
  7470. 3 NaN 30.0 33.0
  7471. 4 NaN 45.0 48.0
  7472. >>> df.shift(periods=3, fill_value=0)
  7473. Col1 Col2 Col3
  7474. 0 0 0 0
  7475. 1 0 0 0
  7476. 2 0 0 0
  7477. 3 10 13 17
  7478. 4 20 23 27
  7479. """)
  7480. @Appender(_shared_docs['shift'] % _shared_doc_kwargs)
  7481. def shift(self, periods=1, freq=None, axis=0, fill_value=None):
  7482. if periods == 0:
  7483. return self.copy()
  7484. block_axis = self._get_block_manager_axis(axis)
  7485. if freq is None:
  7486. new_data = self._data.shift(periods=periods, axis=block_axis,
  7487. fill_value=fill_value)
  7488. else:
  7489. return self.tshift(periods, freq)
  7490. return self._constructor(new_data).__finalize__(self)
  7491. def slice_shift(self, periods=1, axis=0):
  7492. """
  7493. Equivalent to `shift` without copying data. The shifted data will
  7494. not include the dropped periods and the shifted axis will be smaller
  7495. than the original.
  7496. Parameters
  7497. ----------
  7498. periods : int
  7499. Number of periods to move, can be positive or negative
  7500. Returns
  7501. -------
  7502. shifted : same type as caller
  7503. Notes
  7504. -----
  7505. While the `slice_shift` is faster than `shift`, you may pay for it
  7506. later during alignment.
  7507. """
  7508. if periods == 0:
  7509. return self
  7510. if periods > 0:
  7511. vslicer = slice(None, -periods)
  7512. islicer = slice(periods, None)
  7513. else:
  7514. vslicer = slice(-periods, None)
  7515. islicer = slice(None, periods)
  7516. new_obj = self._slice(vslicer, axis=axis)
  7517. shifted_axis = self._get_axis(axis)[islicer]
  7518. new_obj.set_axis(shifted_axis, axis=axis, inplace=True)
  7519. return new_obj.__finalize__(self)
  7520. def tshift(self, periods=1, freq=None, axis=0):
  7521. """
  7522. Shift the time index, using the index's frequency if available.
  7523. Parameters
  7524. ----------
  7525. periods : int
  7526. Number of periods to move, can be positive or negative
  7527. freq : DateOffset, timedelta, or time rule string, default None
  7528. Increment to use from the tseries module or time rule (e.g. 'EOM')
  7529. axis : int or basestring
  7530. Corresponds to the axis that contains the Index
  7531. Returns
  7532. -------
  7533. shifted : NDFrame
  7534. Notes
  7535. -----
  7536. If freq is not specified then tries to use the freq or inferred_freq
  7537. attributes of the index. If neither of those attributes exist, a
  7538. ValueError is thrown
  7539. """
  7540. index = self._get_axis(axis)
  7541. if freq is None:
  7542. freq = getattr(index, 'freq', None)
  7543. if freq is None:
  7544. freq = getattr(index, 'inferred_freq', None)
  7545. if freq is None:
  7546. msg = 'Freq was not given and was not set in the index'
  7547. raise ValueError(msg)
  7548. if periods == 0:
  7549. return self
  7550. if isinstance(freq, string_types):
  7551. freq = to_offset(freq)
  7552. block_axis = self._get_block_manager_axis(axis)
  7553. if isinstance(index, PeriodIndex):
  7554. orig_freq = to_offset(index.freq)
  7555. if freq == orig_freq:
  7556. new_data = self._data.copy()
  7557. new_data.axes[block_axis] = index.shift(periods)
  7558. else:
  7559. msg = ('Given freq %s does not match PeriodIndex freq %s' %
  7560. (freq.rule_code, orig_freq.rule_code))
  7561. raise ValueError(msg)
  7562. else:
  7563. new_data = self._data.copy()
  7564. new_data.axes[block_axis] = index.shift(periods, freq)
  7565. return self._constructor(new_data).__finalize__(self)
  7566. def truncate(self, before=None, after=None, axis=None, copy=True):
  7567. """
  7568. Truncate a Series or DataFrame before and after some index value.
  7569. This is a useful shorthand for boolean indexing based on index
  7570. values above or below certain thresholds.
  7571. Parameters
  7572. ----------
  7573. before : date, string, int
  7574. Truncate all rows before this index value.
  7575. after : date, string, int
  7576. Truncate all rows after this index value.
  7577. axis : {0 or 'index', 1 or 'columns'}, optional
  7578. Axis to truncate. Truncates the index (rows) by default.
  7579. copy : boolean, default is True,
  7580. Return a copy of the truncated section.
  7581. Returns
  7582. -------
  7583. type of caller
  7584. The truncated Series or DataFrame.
  7585. See Also
  7586. --------
  7587. DataFrame.loc : Select a subset of a DataFrame by label.
  7588. DataFrame.iloc : Select a subset of a DataFrame by position.
  7589. Notes
  7590. -----
  7591. If the index being truncated contains only datetime values,
  7592. `before` and `after` may be specified as strings instead of
  7593. Timestamps.
  7594. Examples
  7595. --------
  7596. >>> df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'],
  7597. ... 'B': ['f', 'g', 'h', 'i', 'j'],
  7598. ... 'C': ['k', 'l', 'm', 'n', 'o']},
  7599. ... index=[1, 2, 3, 4, 5])
  7600. >>> df
  7601. A B C
  7602. 1 a f k
  7603. 2 b g l
  7604. 3 c h m
  7605. 4 d i n
  7606. 5 e j o
  7607. >>> df.truncate(before=2, after=4)
  7608. A B C
  7609. 2 b g l
  7610. 3 c h m
  7611. 4 d i n
  7612. The columns of a DataFrame can be truncated.
  7613. >>> df.truncate(before="A", after="B", axis="columns")
  7614. A B
  7615. 1 a f
  7616. 2 b g
  7617. 3 c h
  7618. 4 d i
  7619. 5 e j
  7620. For Series, only rows can be truncated.
  7621. >>> df['A'].truncate(before=2, after=4)
  7622. 2 b
  7623. 3 c
  7624. 4 d
  7625. Name: A, dtype: object
  7626. The index values in ``truncate`` can be datetimes or string
  7627. dates.
  7628. >>> dates = pd.date_range('2016-01-01', '2016-02-01', freq='s')
  7629. >>> df = pd.DataFrame(index=dates, data={'A': 1})
  7630. >>> df.tail()
  7631. A
  7632. 2016-01-31 23:59:56 1
  7633. 2016-01-31 23:59:57 1
  7634. 2016-01-31 23:59:58 1
  7635. 2016-01-31 23:59:59 1
  7636. 2016-02-01 00:00:00 1
  7637. >>> df.truncate(before=pd.Timestamp('2016-01-05'),
  7638. ... after=pd.Timestamp('2016-01-10')).tail()
  7639. A
  7640. 2016-01-09 23:59:56 1
  7641. 2016-01-09 23:59:57 1
  7642. 2016-01-09 23:59:58 1
  7643. 2016-01-09 23:59:59 1
  7644. 2016-01-10 00:00:00 1
  7645. Because the index is a DatetimeIndex containing only dates, we can
  7646. specify `before` and `after` as strings. They will be coerced to
  7647. Timestamps before truncation.
  7648. >>> df.truncate('2016-01-05', '2016-01-10').tail()
  7649. A
  7650. 2016-01-09 23:59:56 1
  7651. 2016-01-09 23:59:57 1
  7652. 2016-01-09 23:59:58 1
  7653. 2016-01-09 23:59:59 1
  7654. 2016-01-10 00:00:00 1
  7655. Note that ``truncate`` assumes a 0 value for any unspecified time
  7656. component (midnight). This differs from partial string slicing, which
  7657. returns any partially matching dates.
  7658. >>> df.loc['2016-01-05':'2016-01-10', :].tail()
  7659. A
  7660. 2016-01-10 23:59:55 1
  7661. 2016-01-10 23:59:56 1
  7662. 2016-01-10 23:59:57 1
  7663. 2016-01-10 23:59:58 1
  7664. 2016-01-10 23:59:59 1
  7665. """
  7666. if axis is None:
  7667. axis = self._stat_axis_number
  7668. axis = self._get_axis_number(axis)
  7669. ax = self._get_axis(axis)
  7670. # GH 17935
  7671. # Check that index is sorted
  7672. if not ax.is_monotonic_increasing and not ax.is_monotonic_decreasing:
  7673. raise ValueError("truncate requires a sorted index")
  7674. # if we have a date index, convert to dates, otherwise
  7675. # treat like a slice
  7676. if ax.is_all_dates:
  7677. from pandas.core.tools.datetimes import to_datetime
  7678. before = to_datetime(before)
  7679. after = to_datetime(after)
  7680. if before is not None and after is not None:
  7681. if before > after:
  7682. raise ValueError('Truncate: %s must be after %s' %
  7683. (after, before))
  7684. slicer = [slice(None, None)] * self._AXIS_LEN
  7685. slicer[axis] = slice(before, after)
  7686. result = self.loc[tuple(slicer)]
  7687. if isinstance(ax, MultiIndex):
  7688. setattr(result, self._get_axis_name(axis),
  7689. ax.truncate(before, after))
  7690. if copy:
  7691. result = result.copy()
  7692. return result
  7693. def tz_convert(self, tz, axis=0, level=None, copy=True):
  7694. """
  7695. Convert tz-aware axis to target time zone.
  7696. Parameters
  7697. ----------
  7698. tz : string or pytz.timezone object
  7699. axis : the axis to convert
  7700. level : int, str, default None
  7701. If axis ia a MultiIndex, convert a specific level. Otherwise
  7702. must be None
  7703. copy : boolean, default True
  7704. Also make a copy of the underlying data
  7705. Returns
  7706. -------
  7707. Raises
  7708. ------
  7709. TypeError
  7710. If the axis is tz-naive.
  7711. """
  7712. axis = self._get_axis_number(axis)
  7713. ax = self._get_axis(axis)
  7714. def _tz_convert(ax, tz):
  7715. if not hasattr(ax, 'tz_convert'):
  7716. if len(ax) > 0:
  7717. ax_name = self._get_axis_name(axis)
  7718. raise TypeError('%s is not a valid DatetimeIndex or '
  7719. 'PeriodIndex' % ax_name)
  7720. else:
  7721. ax = DatetimeIndex([], tz=tz)
  7722. else:
  7723. ax = ax.tz_convert(tz)
  7724. return ax
  7725. # if a level is given it must be a MultiIndex level or
  7726. # equivalent to the axis name
  7727. if isinstance(ax, MultiIndex):
  7728. level = ax._get_level_number(level)
  7729. new_level = _tz_convert(ax.levels[level], tz)
  7730. ax = ax.set_levels(new_level, level=level)
  7731. else:
  7732. if level not in (None, 0, ax.name):
  7733. raise ValueError("The level {0} is not valid".format(level))
  7734. ax = _tz_convert(ax, tz)
  7735. result = self._constructor(self._data, copy=copy)
  7736. result = result.set_axis(ax, axis=axis, inplace=False)
  7737. return result.__finalize__(self)
  7738. def tz_localize(self, tz, axis=0, level=None, copy=True,
  7739. ambiguous='raise', nonexistent='raise'):
  7740. """
  7741. Localize tz-naive index of a Series or DataFrame to target time zone.
  7742. This operation localizes the Index. To localize the values in a
  7743. timezone-naive Series, use :meth:`Series.dt.tz_localize`.
  7744. Parameters
  7745. ----------
  7746. tz : string or pytz.timezone object
  7747. axis : the axis to localize
  7748. level : int, str, default None
  7749. If axis ia a MultiIndex, localize a specific level. Otherwise
  7750. must be None
  7751. copy : boolean, default True
  7752. Also make a copy of the underlying data
  7753. ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'
  7754. When clocks moved backward due to DST, ambiguous times may arise.
  7755. For example in Central European Time (UTC+01), when going from
  7756. 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at
  7757. 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the
  7758. `ambiguous` parameter dictates how ambiguous times should be
  7759. handled.
  7760. - 'infer' will attempt to infer fall dst-transition hours based on
  7761. order
  7762. - bool-ndarray where True signifies a DST time, False designates
  7763. a non-DST time (note that this flag is only applicable for
  7764. ambiguous times)
  7765. - 'NaT' will return NaT where there are ambiguous times
  7766. - 'raise' will raise an AmbiguousTimeError if there are ambiguous
  7767. times
  7768. nonexistent : str, default 'raise'
  7769. A nonexistent time does not exist in a particular timezone
  7770. where clocks moved forward due to DST. Valid values are:
  7771. - 'shift_forward' will shift the nonexistent time forward to the
  7772. closest existing time
  7773. - 'shift_backward' will shift the nonexistent time backward to the
  7774. closest existing time
  7775. - 'NaT' will return NaT where there are nonexistent times
  7776. - timedelta objects will shift nonexistent times by the timedelta
  7777. - 'raise' will raise an NonExistentTimeError if there are
  7778. nonexistent times
  7779. .. versionadded:: 0.24.0
  7780. Returns
  7781. -------
  7782. Series or DataFrame
  7783. Same type as the input.
  7784. Raises
  7785. ------
  7786. TypeError
  7787. If the TimeSeries is tz-aware and tz is not None.
  7788. Examples
  7789. --------
  7790. Localize local times:
  7791. >>> s = pd.Series([1],
  7792. ... index=pd.DatetimeIndex(['2018-09-15 01:30:00']))
  7793. >>> s.tz_localize('CET')
  7794. 2018-09-15 01:30:00+02:00 1
  7795. dtype: int64
  7796. Be careful with DST changes. When there is sequential data, pandas
  7797. can infer the DST time:
  7798. >>> s = pd.Series(range(7), index=pd.DatetimeIndex([
  7799. ... '2018-10-28 01:30:00',
  7800. ... '2018-10-28 02:00:00',
  7801. ... '2018-10-28 02:30:00',
  7802. ... '2018-10-28 02:00:00',
  7803. ... '2018-10-28 02:30:00',
  7804. ... '2018-10-28 03:00:00',
  7805. ... '2018-10-28 03:30:00']))
  7806. >>> s.tz_localize('CET', ambiguous='infer')
  7807. 2018-10-28 01:30:00+02:00 0
  7808. 2018-10-28 02:00:00+02:00 1
  7809. 2018-10-28 02:30:00+02:00 2
  7810. 2018-10-28 02:00:00+01:00 3
  7811. 2018-10-28 02:30:00+01:00 4
  7812. 2018-10-28 03:00:00+01:00 5
  7813. 2018-10-28 03:30:00+01:00 6
  7814. dtype: int64
  7815. In some cases, inferring the DST is impossible. In such cases, you can
  7816. pass an ndarray to the ambiguous parameter to set the DST explicitly
  7817. >>> s = pd.Series(range(3), index=pd.DatetimeIndex([
  7818. ... '2018-10-28 01:20:00',
  7819. ... '2018-10-28 02:36:00',
  7820. ... '2018-10-28 03:46:00']))
  7821. >>> s.tz_localize('CET', ambiguous=np.array([True, True, False]))
  7822. 2018-10-28 01:20:00+02:00 0
  7823. 2018-10-28 02:36:00+02:00 1
  7824. 2018-10-28 03:46:00+01:00 2
  7825. dtype: int64
  7826. If the DST transition causes nonexistent times, you can shift these
  7827. dates forward or backwards with a timedelta object or `'shift_forward'`
  7828. or `'shift_backwards'`.
  7829. >>> s = pd.Series(range(2), index=pd.DatetimeIndex([
  7830. ... '2015-03-29 02:30:00',
  7831. ... '2015-03-29 03:30:00']))
  7832. >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_forward')
  7833. 2015-03-29 03:00:00+02:00 0
  7834. 2015-03-29 03:30:00+02:00 1
  7835. dtype: int64
  7836. >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_backward')
  7837. 2015-03-29 01:59:59.999999999+01:00 0
  7838. 2015-03-29 03:30:00+02:00 1
  7839. dtype: int64
  7840. >>> s.tz_localize('Europe/Warsaw', nonexistent=pd.Timedelta('1H'))
  7841. 2015-03-29 03:30:00+02:00 0
  7842. 2015-03-29 03:30:00+02:00 1
  7843. dtype: int64
  7844. """
  7845. nonexistent_options = ('raise', 'NaT', 'shift_forward',
  7846. 'shift_backward')
  7847. if nonexistent not in nonexistent_options and not isinstance(
  7848. nonexistent, timedelta):
  7849. raise ValueError("The nonexistent argument must be one of 'raise',"
  7850. " 'NaT', 'shift_forward', 'shift_backward' or"
  7851. " a timedelta object")
  7852. axis = self._get_axis_number(axis)
  7853. ax = self._get_axis(axis)
  7854. def _tz_localize(ax, tz, ambiguous, nonexistent):
  7855. if not hasattr(ax, 'tz_localize'):
  7856. if len(ax) > 0:
  7857. ax_name = self._get_axis_name(axis)
  7858. raise TypeError('%s is not a valid DatetimeIndex or '
  7859. 'PeriodIndex' % ax_name)
  7860. else:
  7861. ax = DatetimeIndex([], tz=tz)
  7862. else:
  7863. ax = ax.tz_localize(
  7864. tz, ambiguous=ambiguous, nonexistent=nonexistent
  7865. )
  7866. return ax
  7867. # if a level is given it must be a MultiIndex level or
  7868. # equivalent to the axis name
  7869. if isinstance(ax, MultiIndex):
  7870. level = ax._get_level_number(level)
  7871. new_level = _tz_localize(
  7872. ax.levels[level], tz, ambiguous, nonexistent
  7873. )
  7874. ax = ax.set_levels(new_level, level=level)
  7875. else:
  7876. if level not in (None, 0, ax.name):
  7877. raise ValueError("The level {0} is not valid".format(level))
  7878. ax = _tz_localize(ax, tz, ambiguous, nonexistent)
  7879. result = self._constructor(self._data, copy=copy)
  7880. result = result.set_axis(ax, axis=axis, inplace=False)
  7881. return result.__finalize__(self)
  7882. # ----------------------------------------------------------------------
  7883. # Numeric Methods
  7884. def abs(self):
  7885. """
  7886. Return a Series/DataFrame with absolute numeric value of each element.
  7887. This function only applies to elements that are all numeric.
  7888. Returns
  7889. -------
  7890. abs
  7891. Series/DataFrame containing the absolute value of each element.
  7892. See Also
  7893. --------
  7894. numpy.absolute : Calculate the absolute value element-wise.
  7895. Notes
  7896. -----
  7897. For ``complex`` inputs, ``1.2 + 1j``, the absolute value is
  7898. :math:`\\sqrt{ a^2 + b^2 }`.
  7899. Examples
  7900. --------
  7901. Absolute numeric values in a Series.
  7902. >>> s = pd.Series([-1.10, 2, -3.33, 4])
  7903. >>> s.abs()
  7904. 0 1.10
  7905. 1 2.00
  7906. 2 3.33
  7907. 3 4.00
  7908. dtype: float64
  7909. Absolute numeric values in a Series with complex numbers.
  7910. >>> s = pd.Series([1.2 + 1j])
  7911. >>> s.abs()
  7912. 0 1.56205
  7913. dtype: float64
  7914. Absolute numeric values in a Series with a Timedelta element.
  7915. >>> s = pd.Series([pd.Timedelta('1 days')])
  7916. >>> s.abs()
  7917. 0 1 days
  7918. dtype: timedelta64[ns]
  7919. Select rows with data closest to certain value using argsort (from
  7920. `StackOverflow <https://stackoverflow.com/a/17758115>`__).
  7921. >>> df = pd.DataFrame({
  7922. ... 'a': [4, 5, 6, 7],
  7923. ... 'b': [10, 20, 30, 40],
  7924. ... 'c': [100, 50, -30, -50]
  7925. ... })
  7926. >>> df
  7927. a b c
  7928. 0 4 10 100
  7929. 1 5 20 50
  7930. 2 6 30 -30
  7931. 3 7 40 -50
  7932. >>> df.loc[(df.c - 43).abs().argsort()]
  7933. a b c
  7934. 1 5 20 50
  7935. 0 4 10 100
  7936. 2 6 30 -30
  7937. 3 7 40 -50
  7938. """
  7939. return np.abs(self)
  7940. def describe(self, percentiles=None, include=None, exclude=None):
  7941. """
  7942. Generate descriptive statistics that summarize the central tendency,
  7943. dispersion and shape of a dataset's distribution, excluding
  7944. ``NaN`` values.
  7945. Analyzes both numeric and object series, as well
  7946. as ``DataFrame`` column sets of mixed data types. The output
  7947. will vary depending on what is provided. Refer to the notes
  7948. below for more detail.
  7949. Parameters
  7950. ----------
  7951. percentiles : list-like of numbers, optional
  7952. The percentiles to include in the output. All should
  7953. fall between 0 and 1. The default is
  7954. ``[.25, .5, .75]``, which returns the 25th, 50th, and
  7955. 75th percentiles.
  7956. include : 'all', list-like of dtypes or None (default), optional
  7957. A white list of data types to include in the result. Ignored
  7958. for ``Series``. Here are the options:
  7959. - 'all' : All columns of the input will be included in the output.
  7960. - A list-like of dtypes : Limits the results to the
  7961. provided data types.
  7962. To limit the result to numeric types submit
  7963. ``numpy.number``. To limit it instead to object columns submit
  7964. the ``numpy.object`` data type. Strings
  7965. can also be used in the style of
  7966. ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To
  7967. select pandas categorical columns, use ``'category'``
  7968. - None (default) : The result will include all numeric columns.
  7969. exclude : list-like of dtypes or None (default), optional,
  7970. A black list of data types to omit from the result. Ignored
  7971. for ``Series``. Here are the options:
  7972. - A list-like of dtypes : Excludes the provided data types
  7973. from the result. To exclude numeric types submit
  7974. ``numpy.number``. To exclude object columns submit the data
  7975. type ``numpy.object``. Strings can also be used in the style of
  7976. ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To
  7977. exclude pandas categorical columns, use ``'category'``
  7978. - None (default) : The result will exclude nothing.
  7979. Returns
  7980. -------
  7981. Series or DataFrame
  7982. Summary statistics of the Series or Dataframe provided.
  7983. See Also
  7984. --------
  7985. DataFrame.count: Count number of non-NA/null observations.
  7986. DataFrame.max: Maximum of the values in the object.
  7987. DataFrame.min: Minimum of the values in the object.
  7988. DataFrame.mean: Mean of the values.
  7989. DataFrame.std: Standard deviation of the obersvations.
  7990. DataFrame.select_dtypes: Subset of a DataFrame including/excluding
  7991. columns based on their dtype.
  7992. Notes
  7993. -----
  7994. For numeric data, the result's index will include ``count``,
  7995. ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and
  7996. upper percentiles. By default the lower percentile is ``25`` and the
  7997. upper percentile is ``75``. The ``50`` percentile is the
  7998. same as the median.
  7999. For object data (e.g. strings or timestamps), the result's index
  8000. will include ``count``, ``unique``, ``top``, and ``freq``. The ``top``
  8001. is the most common value. The ``freq`` is the most common value's
  8002. frequency. Timestamps also include the ``first`` and ``last`` items.
  8003. If multiple object values have the highest count, then the
  8004. ``count`` and ``top`` results will be arbitrarily chosen from
  8005. among those with the highest count.
  8006. For mixed data types provided via a ``DataFrame``, the default is to
  8007. return only an analysis of numeric columns. If the dataframe consists
  8008. only of object and categorical data without any numeric columns, the
  8009. default is to return an analysis of both the object and categorical
  8010. columns. If ``include='all'`` is provided as an option, the result
  8011. will include a union of attributes of each type.
  8012. The `include` and `exclude` parameters can be used to limit
  8013. which columns in a ``DataFrame`` are analyzed for the output.
  8014. The parameters are ignored when analyzing a ``Series``.
  8015. Examples
  8016. --------
  8017. Describing a numeric ``Series``.
  8018. >>> s = pd.Series([1, 2, 3])
  8019. >>> s.describe()
  8020. count 3.0
  8021. mean 2.0
  8022. std 1.0
  8023. min 1.0
  8024. 25% 1.5
  8025. 50% 2.0
  8026. 75% 2.5
  8027. max 3.0
  8028. dtype: float64
  8029. Describing a categorical ``Series``.
  8030. >>> s = pd.Series(['a', 'a', 'b', 'c'])
  8031. >>> s.describe()
  8032. count 4
  8033. unique 3
  8034. top a
  8035. freq 2
  8036. dtype: object
  8037. Describing a timestamp ``Series``.
  8038. >>> s = pd.Series([
  8039. ... np.datetime64("2000-01-01"),
  8040. ... np.datetime64("2010-01-01"),
  8041. ... np.datetime64("2010-01-01")
  8042. ... ])
  8043. >>> s.describe()
  8044. count 3
  8045. unique 2
  8046. top 2010-01-01 00:00:00
  8047. freq 2
  8048. first 2000-01-01 00:00:00
  8049. last 2010-01-01 00:00:00
  8050. dtype: object
  8051. Describing a ``DataFrame``. By default only numeric fields
  8052. are returned.
  8053. >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']),
  8054. ... 'numeric': [1, 2, 3],
  8055. ... 'object': ['a', 'b', 'c']
  8056. ... })
  8057. >>> df.describe()
  8058. numeric
  8059. count 3.0
  8060. mean 2.0
  8061. std 1.0
  8062. min 1.0
  8063. 25% 1.5
  8064. 50% 2.0
  8065. 75% 2.5
  8066. max 3.0
  8067. Describing all columns of a ``DataFrame`` regardless of data type.
  8068. >>> df.describe(include='all')
  8069. categorical numeric object
  8070. count 3 3.0 3
  8071. unique 3 NaN 3
  8072. top f NaN c
  8073. freq 1 NaN 1
  8074. mean NaN 2.0 NaN
  8075. std NaN 1.0 NaN
  8076. min NaN 1.0 NaN
  8077. 25% NaN 1.5 NaN
  8078. 50% NaN 2.0 NaN
  8079. 75% NaN 2.5 NaN
  8080. max NaN 3.0 NaN
  8081. Describing a column from a ``DataFrame`` by accessing it as
  8082. an attribute.
  8083. >>> df.numeric.describe()
  8084. count 3.0
  8085. mean 2.0
  8086. std 1.0
  8087. min 1.0
  8088. 25% 1.5
  8089. 50% 2.0
  8090. 75% 2.5
  8091. max 3.0
  8092. Name: numeric, dtype: float64
  8093. Including only numeric columns in a ``DataFrame`` description.
  8094. >>> df.describe(include=[np.number])
  8095. numeric
  8096. count 3.0
  8097. mean 2.0
  8098. std 1.0
  8099. min 1.0
  8100. 25% 1.5
  8101. 50% 2.0
  8102. 75% 2.5
  8103. max 3.0
  8104. Including only string columns in a ``DataFrame`` description.
  8105. >>> df.describe(include=[np.object])
  8106. object
  8107. count 3
  8108. unique 3
  8109. top c
  8110. freq 1
  8111. Including only categorical columns from a ``DataFrame`` description.
  8112. >>> df.describe(include=['category'])
  8113. categorical
  8114. count 3
  8115. unique 3
  8116. top f
  8117. freq 1
  8118. Excluding numeric columns from a ``DataFrame`` description.
  8119. >>> df.describe(exclude=[np.number])
  8120. categorical object
  8121. count 3 3
  8122. unique 3 3
  8123. top f c
  8124. freq 1 1
  8125. Excluding object columns from a ``DataFrame`` description.
  8126. >>> df.describe(exclude=[np.object])
  8127. categorical numeric
  8128. count 3 3.0
  8129. unique 3 NaN
  8130. top f NaN
  8131. freq 1 NaN
  8132. mean NaN 2.0
  8133. std NaN 1.0
  8134. min NaN 1.0
  8135. 25% NaN 1.5
  8136. 50% NaN 2.0
  8137. 75% NaN 2.5
  8138. max NaN 3.0
  8139. """
  8140. if self.ndim >= 3:
  8141. msg = "describe is not implemented on Panel objects."
  8142. raise NotImplementedError(msg)
  8143. elif self.ndim == 2 and self.columns.size == 0:
  8144. raise ValueError("Cannot describe a DataFrame without columns")
  8145. if percentiles is not None:
  8146. # explicit conversion of `percentiles` to list
  8147. percentiles = list(percentiles)
  8148. # get them all to be in [0, 1]
  8149. self._check_percentile(percentiles)
  8150. # median should always be included
  8151. if 0.5 not in percentiles:
  8152. percentiles.append(0.5)
  8153. percentiles = np.asarray(percentiles)
  8154. else:
  8155. percentiles = np.array([0.25, 0.5, 0.75])
  8156. # sort and check for duplicates
  8157. unique_pcts = np.unique(percentiles)
  8158. if len(unique_pcts) < len(percentiles):
  8159. raise ValueError("percentiles cannot contain duplicates")
  8160. percentiles = unique_pcts
  8161. formatted_percentiles = format_percentiles(percentiles)
  8162. def describe_numeric_1d(series):
  8163. stat_index = (['count', 'mean', 'std', 'min'] +
  8164. formatted_percentiles + ['max'])
  8165. d = ([series.count(), series.mean(), series.std(), series.min()] +
  8166. series.quantile(percentiles).tolist() + [series.max()])
  8167. return pd.Series(d, index=stat_index, name=series.name)
  8168. def describe_categorical_1d(data):
  8169. names = ['count', 'unique']
  8170. objcounts = data.value_counts()
  8171. count_unique = len(objcounts[objcounts != 0])
  8172. result = [data.count(), count_unique]
  8173. if result[1] > 0:
  8174. top, freq = objcounts.index[0], objcounts.iloc[0]
  8175. if is_datetime64_any_dtype(data):
  8176. tz = data.dt.tz
  8177. asint = data.dropna().values.view('i8')
  8178. top = Timestamp(top)
  8179. if top.tzinfo is not None and tz is not None:
  8180. # Don't tz_localize(None) if key is already tz-aware
  8181. top = top.tz_convert(tz)
  8182. else:
  8183. top = top.tz_localize(tz)
  8184. names += ['top', 'freq', 'first', 'last']
  8185. result += [top, freq,
  8186. Timestamp(asint.min(), tz=tz),
  8187. Timestamp(asint.max(), tz=tz)]
  8188. else:
  8189. names += ['top', 'freq']
  8190. result += [top, freq]
  8191. return pd.Series(result, index=names, name=data.name)
  8192. def describe_1d(data):
  8193. if is_bool_dtype(data):
  8194. return describe_categorical_1d(data)
  8195. elif is_numeric_dtype(data):
  8196. return describe_numeric_1d(data)
  8197. elif is_timedelta64_dtype(data):
  8198. return describe_numeric_1d(data)
  8199. else:
  8200. return describe_categorical_1d(data)
  8201. if self.ndim == 1:
  8202. return describe_1d(self)
  8203. elif (include is None) and (exclude is None):
  8204. # when some numerics are found, keep only numerics
  8205. data = self.select_dtypes(include=[np.number])
  8206. if len(data.columns) == 0:
  8207. data = self
  8208. elif include == 'all':
  8209. if exclude is not None:
  8210. msg = "exclude must be None when include is 'all'"
  8211. raise ValueError(msg)
  8212. data = self
  8213. else:
  8214. data = self.select_dtypes(include=include, exclude=exclude)
  8215. ldesc = [describe_1d(s) for _, s in data.iteritems()]
  8216. # set a convenient order for rows
  8217. names = []
  8218. ldesc_indexes = sorted((x.index for x in ldesc), key=len)
  8219. for idxnames in ldesc_indexes:
  8220. for name in idxnames:
  8221. if name not in names:
  8222. names.append(name)
  8223. d = pd.concat(ldesc, join_axes=pd.Index([names]), axis=1)
  8224. d.columns = data.columns.copy()
  8225. return d
  8226. def _check_percentile(self, q):
  8227. """
  8228. Validate percentiles (used by describe and quantile).
  8229. """
  8230. msg = ("percentiles should all be in the interval [0, 1]. "
  8231. "Try {0} instead.")
  8232. q = np.asarray(q)
  8233. if q.ndim == 0:
  8234. if not 0 <= q <= 1:
  8235. raise ValueError(msg.format(q / 100.0))
  8236. else:
  8237. if not all(0 <= qs <= 1 for qs in q):
  8238. raise ValueError(msg.format(q / 100.0))
  8239. return q
  8240. _shared_docs['pct_change'] = """
  8241. Percentage change between the current and a prior element.
  8242. Computes the percentage change from the immediately previous row by
  8243. default. This is useful in comparing the percentage of change in a time
  8244. series of elements.
  8245. Parameters
  8246. ----------
  8247. periods : int, default 1
  8248. Periods to shift for forming percent change.
  8249. fill_method : str, default 'pad'
  8250. How to handle NAs before computing percent changes.
  8251. limit : int, default None
  8252. The number of consecutive NAs to fill before stopping.
  8253. freq : DateOffset, timedelta, or offset alias string, optional
  8254. Increment to use from time series API (e.g. 'M' or BDay()).
  8255. **kwargs
  8256. Additional keyword arguments are passed into
  8257. `DataFrame.shift` or `Series.shift`.
  8258. Returns
  8259. -------
  8260. chg : Series or DataFrame
  8261. The same type as the calling object.
  8262. See Also
  8263. --------
  8264. Series.diff : Compute the difference of two elements in a Series.
  8265. DataFrame.diff : Compute the difference of two elements in a DataFrame.
  8266. Series.shift : Shift the index by some number of periods.
  8267. DataFrame.shift : Shift the index by some number of periods.
  8268. Examples
  8269. --------
  8270. **Series**
  8271. >>> s = pd.Series([90, 91, 85])
  8272. >>> s
  8273. 0 90
  8274. 1 91
  8275. 2 85
  8276. dtype: int64
  8277. >>> s.pct_change()
  8278. 0 NaN
  8279. 1 0.011111
  8280. 2 -0.065934
  8281. dtype: float64
  8282. >>> s.pct_change(periods=2)
  8283. 0 NaN
  8284. 1 NaN
  8285. 2 -0.055556
  8286. dtype: float64
  8287. See the percentage change in a Series where filling NAs with last
  8288. valid observation forward to next valid.
  8289. >>> s = pd.Series([90, 91, None, 85])
  8290. >>> s
  8291. 0 90.0
  8292. 1 91.0
  8293. 2 NaN
  8294. 3 85.0
  8295. dtype: float64
  8296. >>> s.pct_change(fill_method='ffill')
  8297. 0 NaN
  8298. 1 0.011111
  8299. 2 0.000000
  8300. 3 -0.065934
  8301. dtype: float64
  8302. **DataFrame**
  8303. Percentage change in French franc, Deutsche Mark, and Italian lira from
  8304. 1980-01-01 to 1980-03-01.
  8305. >>> df = pd.DataFrame({
  8306. ... 'FR': [4.0405, 4.0963, 4.3149],
  8307. ... 'GR': [1.7246, 1.7482, 1.8519],
  8308. ... 'IT': [804.74, 810.01, 860.13]},
  8309. ... index=['1980-01-01', '1980-02-01', '1980-03-01'])
  8310. >>> df
  8311. FR GR IT
  8312. 1980-01-01 4.0405 1.7246 804.74
  8313. 1980-02-01 4.0963 1.7482 810.01
  8314. 1980-03-01 4.3149 1.8519 860.13
  8315. >>> df.pct_change()
  8316. FR GR IT
  8317. 1980-01-01 NaN NaN NaN
  8318. 1980-02-01 0.013810 0.013684 0.006549
  8319. 1980-03-01 0.053365 0.059318 0.061876
  8320. Percentage of change in GOOG and APPL stock volume. Shows computing
  8321. the percentage change between columns.
  8322. >>> df = pd.DataFrame({
  8323. ... '2016': [1769950, 30586265],
  8324. ... '2015': [1500923, 40912316],
  8325. ... '2014': [1371819, 41403351]},
  8326. ... index=['GOOG', 'APPL'])
  8327. >>> df
  8328. 2016 2015 2014
  8329. GOOG 1769950 1500923 1371819
  8330. APPL 30586265 40912316 41403351
  8331. >>> df.pct_change(axis='columns')
  8332. 2016 2015 2014
  8333. GOOG NaN -0.151997 -0.086016
  8334. APPL NaN 0.337604 0.012002
  8335. """
  8336. @Appender(_shared_docs['pct_change'] % _shared_doc_kwargs)
  8337. def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None,
  8338. **kwargs):
  8339. # TODO: Not sure if above is correct - need someone to confirm.
  8340. axis = self._get_axis_number(kwargs.pop('axis', self._stat_axis_name))
  8341. if fill_method is None:
  8342. data = self
  8343. else:
  8344. data = self.fillna(method=fill_method, limit=limit, axis=axis)
  8345. rs = (data.div(data.shift(periods=periods, freq=freq, axis=axis,
  8346. **kwargs)) - 1)
  8347. rs = rs.reindex_like(data)
  8348. if freq is None:
  8349. mask = isna(com.values_from_object(data))
  8350. np.putmask(rs.values, mask, np.nan)
  8351. return rs
  8352. def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwargs):
  8353. if axis is None:
  8354. raise ValueError("Must specify 'axis' when aggregating by level.")
  8355. grouped = self.groupby(level=level, axis=axis, sort=False)
  8356. if hasattr(grouped, name) and skipna:
  8357. return getattr(grouped, name)(**kwargs)
  8358. axis = self._get_axis_number(axis)
  8359. method = getattr(type(self), name)
  8360. applyf = lambda x: method(x, axis=axis, skipna=skipna, **kwargs)
  8361. return grouped.aggregate(applyf)
  8362. @classmethod
  8363. def _add_numeric_operations(cls):
  8364. """
  8365. Add the operations to the cls; evaluate the doc strings again
  8366. """
  8367. axis_descr, name, name2 = _doc_parms(cls)
  8368. cls.any = _make_logical_function(
  8369. cls, 'any', name, name2, axis_descr, _any_desc, nanops.nanany,
  8370. _any_see_also, _any_examples, empty_value=False)
  8371. cls.all = _make_logical_function(
  8372. cls, 'all', name, name2, axis_descr, _all_desc, nanops.nanall,
  8373. _all_see_also, _all_examples, empty_value=True)
  8374. @Substitution(desc="Return the mean absolute deviation of the values "
  8375. "for the requested axis.",
  8376. name1=name, name2=name2, axis_descr=axis_descr,
  8377. min_count='', see_also='', examples='')
  8378. @Appender(_num_doc)
  8379. def mad(self, axis=None, skipna=None, level=None):
  8380. if skipna is None:
  8381. skipna = True
  8382. if axis is None:
  8383. axis = self._stat_axis_number
  8384. if level is not None:
  8385. return self._agg_by_level('mad', axis=axis, level=level,
  8386. skipna=skipna)
  8387. data = self._get_numeric_data()
  8388. if axis == 0:
  8389. demeaned = data - data.mean(axis=0)
  8390. else:
  8391. demeaned = data.sub(data.mean(axis=1), axis=0)
  8392. return np.abs(demeaned).mean(axis=axis, skipna=skipna)
  8393. cls.mad = mad
  8394. cls.sem = _make_stat_function_ddof(
  8395. cls, 'sem', name, name2, axis_descr,
  8396. "Return unbiased standard error of the mean over requested "
  8397. "axis.\n\nNormalized by N-1 by default. This can be changed "
  8398. "using the ddof argument",
  8399. nanops.nansem)
  8400. cls.var = _make_stat_function_ddof(
  8401. cls, 'var', name, name2, axis_descr,
  8402. "Return unbiased variance over requested axis.\n\nNormalized by "
  8403. "N-1 by default. This can be changed using the ddof argument",
  8404. nanops.nanvar)
  8405. cls.std = _make_stat_function_ddof(
  8406. cls, 'std', name, name2, axis_descr,
  8407. "Return sample standard deviation over requested axis."
  8408. "\n\nNormalized by N-1 by default. This can be changed using the "
  8409. "ddof argument",
  8410. nanops.nanstd)
  8411. @Substitution(desc="Return the compound percentage of the values for "
  8412. "the requested axis.", name1=name, name2=name2,
  8413. axis_descr=axis_descr,
  8414. min_count='', see_also='', examples='')
  8415. @Appender(_num_doc)
  8416. def compound(self, axis=None, skipna=None, level=None):
  8417. if skipna is None:
  8418. skipna = True
  8419. return (1 + self).prod(axis=axis, skipna=skipna, level=level) - 1
  8420. cls.compound = compound
  8421. cls.cummin = _make_cum_function(
  8422. cls, 'cummin', name, name2, axis_descr, "minimum",
  8423. lambda y, axis: np.minimum.accumulate(y, axis), "min",
  8424. np.inf, np.nan, _cummin_examples)
  8425. cls.cumsum = _make_cum_function(
  8426. cls, 'cumsum', name, name2, axis_descr, "sum",
  8427. lambda y, axis: y.cumsum(axis), "sum", 0.,
  8428. np.nan, _cumsum_examples)
  8429. cls.cumprod = _make_cum_function(
  8430. cls, 'cumprod', name, name2, axis_descr, "product",
  8431. lambda y, axis: y.cumprod(axis), "prod", 1.,
  8432. np.nan, _cumprod_examples)
  8433. cls.cummax = _make_cum_function(
  8434. cls, 'cummax', name, name2, axis_descr, "maximum",
  8435. lambda y, axis: np.maximum.accumulate(y, axis), "max",
  8436. -np.inf, np.nan, _cummax_examples)
  8437. cls.sum = _make_min_count_stat_function(
  8438. cls, 'sum', name, name2, axis_descr,
  8439. """Return the sum of the values for the requested axis.\n
  8440. This is equivalent to the method ``numpy.sum``.""",
  8441. nanops.nansum, _stat_func_see_also, _sum_examples)
  8442. cls.mean = _make_stat_function(
  8443. cls, 'mean', name, name2, axis_descr,
  8444. 'Return the mean of the values for the requested axis.',
  8445. nanops.nanmean)
  8446. cls.skew = _make_stat_function(
  8447. cls, 'skew', name, name2, axis_descr,
  8448. 'Return unbiased skew over requested axis\nNormalized by N-1.',
  8449. nanops.nanskew)
  8450. cls.kurt = _make_stat_function(
  8451. cls, 'kurt', name, name2, axis_descr,
  8452. "Return unbiased kurtosis over requested axis using Fisher's "
  8453. "definition of\nkurtosis (kurtosis of normal == 0.0). Normalized "
  8454. "by N-1.",
  8455. nanops.nankurt)
  8456. cls.kurtosis = cls.kurt
  8457. cls.prod = _make_min_count_stat_function(
  8458. cls, 'prod', name, name2, axis_descr,
  8459. 'Return the product of the values for the requested axis.',
  8460. nanops.nanprod, examples=_prod_examples)
  8461. cls.product = cls.prod
  8462. cls.median = _make_stat_function(
  8463. cls, 'median', name, name2, axis_descr,
  8464. 'Return the median of the values for the requested axis.',
  8465. nanops.nanmedian)
  8466. cls.max = _make_stat_function(
  8467. cls, 'max', name, name2, axis_descr,
  8468. """Return the maximum of the values for the requested axis.\n
  8469. If you want the *index* of the maximum, use ``idxmax``. This is
  8470. the equivalent of the ``numpy.ndarray`` method ``argmax``.""",
  8471. nanops.nanmax, _stat_func_see_also, _max_examples)
  8472. cls.min = _make_stat_function(
  8473. cls, 'min', name, name2, axis_descr,
  8474. """Return the minimum of the values for the requested axis.\n
  8475. If you want the *index* of the minimum, use ``idxmin``. This is
  8476. the equivalent of the ``numpy.ndarray`` method ``argmin``.""",
  8477. nanops.nanmin, _stat_func_see_also, _min_examples)
  8478. @classmethod
  8479. def _add_series_only_operations(cls):
  8480. """
  8481. Add the series only operations to the cls; evaluate the doc
  8482. strings again.
  8483. """
  8484. axis_descr, name, name2 = _doc_parms(cls)
  8485. def nanptp(values, axis=0, skipna=True):
  8486. nmax = nanops.nanmax(values, axis, skipna)
  8487. nmin = nanops.nanmin(values, axis, skipna)
  8488. warnings.warn("Method .ptp is deprecated and will be removed "
  8489. "in a future version. Use numpy.ptp instead.",
  8490. FutureWarning, stacklevel=4)
  8491. return nmax - nmin
  8492. cls.ptp = _make_stat_function(
  8493. cls, 'ptp', name, name2, axis_descr,
  8494. """Return the difference between the maximum value and the
  8495. minimum value in the object. This is the equivalent of the
  8496. ``numpy.ndarray`` method ``ptp``.\n\n.. deprecated:: 0.24.0
  8497. Use numpy.ptp instead""",
  8498. nanptp)
  8499. @classmethod
  8500. def _add_series_or_dataframe_operations(cls):
  8501. """
  8502. Add the series or dataframe only operations to the cls; evaluate
  8503. the doc strings again.
  8504. """
  8505. from pandas.core import window as rwindow
  8506. @Appender(rwindow.rolling.__doc__)
  8507. def rolling(self, window, min_periods=None, center=False,
  8508. win_type=None, on=None, axis=0, closed=None):
  8509. axis = self._get_axis_number(axis)
  8510. return rwindow.rolling(self, window=window,
  8511. min_periods=min_periods,
  8512. center=center, win_type=win_type,
  8513. on=on, axis=axis, closed=closed)
  8514. cls.rolling = rolling
  8515. @Appender(rwindow.expanding.__doc__)
  8516. def expanding(self, min_periods=1, center=False, axis=0):
  8517. axis = self._get_axis_number(axis)
  8518. return rwindow.expanding(self, min_periods=min_periods,
  8519. center=center, axis=axis)
  8520. cls.expanding = expanding
  8521. @Appender(rwindow.ewm.__doc__)
  8522. def ewm(self, com=None, span=None, halflife=None, alpha=None,
  8523. min_periods=0, adjust=True, ignore_na=False,
  8524. axis=0):
  8525. axis = self._get_axis_number(axis)
  8526. return rwindow.ewm(self, com=com, span=span, halflife=halflife,
  8527. alpha=alpha, min_periods=min_periods,
  8528. adjust=adjust, ignore_na=ignore_na, axis=axis)
  8529. cls.ewm = ewm
  8530. @Appender(_shared_docs['transform'] % dict(axis="", **_shared_doc_kwargs))
  8531. def transform(self, func, *args, **kwargs):
  8532. result = self.agg(func, *args, **kwargs)
  8533. if is_scalar(result) or len(result) != len(self):
  8534. raise ValueError("transforms cannot produce "
  8535. "aggregated results")
  8536. return result
  8537. # ----------------------------------------------------------------------
  8538. # Misc methods
  8539. _shared_docs['valid_index'] = """
  8540. Return index for %(position)s non-NA/null value.
  8541. Returns
  8542. --------
  8543. scalar : type of index
  8544. Notes
  8545. --------
  8546. If all elements are non-NA/null, returns None.
  8547. Also returns None for empty %(klass)s.
  8548. """
  8549. def _find_valid_index(self, how):
  8550. """
  8551. Retrieves the index of the first valid value.
  8552. Parameters
  8553. ----------
  8554. how : {'first', 'last'}
  8555. Use this parameter to change between the first or last valid index.
  8556. Returns
  8557. -------
  8558. idx_first_valid : type of index
  8559. """
  8560. assert how in ['first', 'last']
  8561. if len(self) == 0: # early stop
  8562. return None
  8563. is_valid = ~self.isna()
  8564. if self.ndim == 2:
  8565. is_valid = is_valid.any(1) # reduce axis 1
  8566. if how == 'first':
  8567. idxpos = is_valid.values[::].argmax()
  8568. if how == 'last':
  8569. idxpos = len(self) - 1 - is_valid.values[::-1].argmax()
  8570. chk_notna = is_valid.iat[idxpos]
  8571. idx = self.index[idxpos]
  8572. if not chk_notna:
  8573. return None
  8574. return idx
  8575. @Appender(_shared_docs['valid_index'] % {'position': 'first',
  8576. 'klass': 'NDFrame'})
  8577. def first_valid_index(self):
  8578. return self._find_valid_index('first')
  8579. @Appender(_shared_docs['valid_index'] % {'position': 'last',
  8580. 'klass': 'NDFrame'})
  8581. def last_valid_index(self):
  8582. return self._find_valid_index('last')
  8583. def _doc_parms(cls):
  8584. """Return a tuple of the doc parms."""
  8585. axis_descr = "{%s}" % ', '.join("{0} ({1})".format(a, i)
  8586. for i, a in enumerate(cls._AXIS_ORDERS))
  8587. name = (cls._constructor_sliced.__name__
  8588. if cls._AXIS_LEN > 1 else 'scalar')
  8589. name2 = cls.__name__
  8590. return axis_descr, name, name2
  8591. _num_doc = """
  8592. %(desc)s
  8593. Parameters
  8594. ----------
  8595. axis : %(axis_descr)s
  8596. Axis for the function to be applied on.
  8597. skipna : bool, default True
  8598. Exclude NA/null values when computing the result.
  8599. level : int or level name, default None
  8600. If the axis is a MultiIndex (hierarchical), count along a
  8601. particular level, collapsing into a %(name1)s.
  8602. numeric_only : bool, default None
  8603. Include only float, int, boolean columns. If None, will attempt to use
  8604. everything, then use only numeric data. Not implemented for Series.
  8605. %(min_count)s\
  8606. **kwargs
  8607. Additional keyword arguments to be passed to the function.
  8608. Returns
  8609. -------
  8610. %(name1)s or %(name2)s (if level specified)\
  8611. %(see_also)s
  8612. %(examples)s\
  8613. """
  8614. _num_ddof_doc = """
  8615. %(desc)s
  8616. Parameters
  8617. ----------
  8618. axis : %(axis_descr)s
  8619. skipna : bool, default True
  8620. Exclude NA/null values. If an entire row/column is NA, the result
  8621. will be NA
  8622. level : int or level name, default None
  8623. If the axis is a MultiIndex (hierarchical), count along a
  8624. particular level, collapsing into a %(name1)s
  8625. ddof : int, default 1
  8626. Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
  8627. where N represents the number of elements.
  8628. numeric_only : bool, default None
  8629. Include only float, int, boolean columns. If None, will attempt to use
  8630. everything, then use only numeric data. Not implemented for Series.
  8631. Returns
  8632. -------
  8633. %(name1)s or %(name2)s (if level specified)\n"""
  8634. _bool_doc = """
  8635. %(desc)s
  8636. Parameters
  8637. ----------
  8638. axis : {0 or 'index', 1 or 'columns', None}, default 0
  8639. Indicate which axis or axes should be reduced.
  8640. * 0 / 'index' : reduce the index, return a Series whose index is the
  8641. original column labels.
  8642. * 1 / 'columns' : reduce the columns, return a Series whose index is the
  8643. original index.
  8644. * None : reduce all axes, return a scalar.
  8645. bool_only : bool, default None
  8646. Include only boolean columns. If None, will attempt to use everything,
  8647. then use only boolean data. Not implemented for Series.
  8648. skipna : bool, default True
  8649. Exclude NA/null values. If the entire row/column is NA and skipna is
  8650. True, then the result will be %(empty_value)s, as for an empty row/column.
  8651. If skipna is False, then NA are treated as True, because these are not
  8652. equal to zero.
  8653. level : int or level name, default None
  8654. If the axis is a MultiIndex (hierarchical), count along a
  8655. particular level, collapsing into a %(name1)s.
  8656. **kwargs : any, default None
  8657. Additional keywords have no effect but might be accepted for
  8658. compatibility with NumPy.
  8659. Returns
  8660. -------
  8661. %(name1)s or %(name2)s
  8662. If level is specified, then, %(name2)s is returned; otherwise, %(name1)s
  8663. is returned.
  8664. %(see_also)s
  8665. %(examples)s"""
  8666. _all_desc = """\
  8667. Return whether all elements are True, potentially over an axis.
  8668. Returns True unless there at least one element within a series or
  8669. along a Dataframe axis that is False or equivalent (e.g. zero or
  8670. empty)."""
  8671. _all_examples = """\
  8672. Examples
  8673. --------
  8674. **Series**
  8675. >>> pd.Series([True, True]).all()
  8676. True
  8677. >>> pd.Series([True, False]).all()
  8678. False
  8679. >>> pd.Series([]).all()
  8680. True
  8681. >>> pd.Series([np.nan]).all()
  8682. True
  8683. >>> pd.Series([np.nan]).all(skipna=False)
  8684. True
  8685. **DataFrames**
  8686. Create a dataframe from a dictionary.
  8687. >>> df = pd.DataFrame({'col1': [True, True], 'col2': [True, False]})
  8688. >>> df
  8689. col1 col2
  8690. 0 True True
  8691. 1 True False
  8692. Default behaviour checks if column-wise values all return True.
  8693. >>> df.all()
  8694. col1 True
  8695. col2 False
  8696. dtype: bool
  8697. Specify ``axis='columns'`` to check if row-wise values all return True.
  8698. >>> df.all(axis='columns')
  8699. 0 True
  8700. 1 False
  8701. dtype: bool
  8702. Or ``axis=None`` for whether every value is True.
  8703. >>> df.all(axis=None)
  8704. False
  8705. """
  8706. _all_see_also = """\
  8707. See Also
  8708. --------
  8709. Series.all : Return True if all elements are True.
  8710. DataFrame.any : Return True if one (or more) elements are True.
  8711. """
  8712. _cnum_doc = """
  8713. Return cumulative %(desc)s over a DataFrame or Series axis.
  8714. Returns a DataFrame or Series of the same size containing the cumulative
  8715. %(desc)s.
  8716. Parameters
  8717. ----------
  8718. axis : {0 or 'index', 1 or 'columns'}, default 0
  8719. The index or the name of the axis. 0 is equivalent to None or 'index'.
  8720. skipna : boolean, default True
  8721. Exclude NA/null values. If an entire row/column is NA, the result
  8722. will be NA.
  8723. *args, **kwargs :
  8724. Additional keywords have no effect but might be accepted for
  8725. compatibility with NumPy.
  8726. Returns
  8727. -------
  8728. %(name1)s or %(name2)s\n
  8729. See Also
  8730. --------
  8731. core.window.Expanding.%(accum_func_name)s : Similar functionality
  8732. but ignores ``NaN`` values.
  8733. %(name2)s.%(accum_func_name)s : Return the %(desc)s over
  8734. %(name2)s axis.
  8735. %(name2)s.cummax : Return cumulative maximum over %(name2)s axis.
  8736. %(name2)s.cummin : Return cumulative minimum over %(name2)s axis.
  8737. %(name2)s.cumsum : Return cumulative sum over %(name2)s axis.
  8738. %(name2)s.cumprod : Return cumulative product over %(name2)s axis.
  8739. %(examples)s"""
  8740. _cummin_examples = """\
  8741. Examples
  8742. --------
  8743. **Series**
  8744. >>> s = pd.Series([2, np.nan, 5, -1, 0])
  8745. >>> s
  8746. 0 2.0
  8747. 1 NaN
  8748. 2 5.0
  8749. 3 -1.0
  8750. 4 0.0
  8751. dtype: float64
  8752. By default, NA values are ignored.
  8753. >>> s.cummin()
  8754. 0 2.0
  8755. 1 NaN
  8756. 2 2.0
  8757. 3 -1.0
  8758. 4 -1.0
  8759. dtype: float64
  8760. To include NA values in the operation, use ``skipna=False``
  8761. >>> s.cummin(skipna=False)
  8762. 0 2.0
  8763. 1 NaN
  8764. 2 NaN
  8765. 3 NaN
  8766. 4 NaN
  8767. dtype: float64
  8768. **DataFrame**
  8769. >>> df = pd.DataFrame([[2.0, 1.0],
  8770. ... [3.0, np.nan],
  8771. ... [1.0, 0.0]],
  8772. ... columns=list('AB'))
  8773. >>> df
  8774. A B
  8775. 0 2.0 1.0
  8776. 1 3.0 NaN
  8777. 2 1.0 0.0
  8778. By default, iterates over rows and finds the minimum
  8779. in each column. This is equivalent to ``axis=None`` or ``axis='index'``.
  8780. >>> df.cummin()
  8781. A B
  8782. 0 2.0 1.0
  8783. 1 2.0 NaN
  8784. 2 1.0 0.0
  8785. To iterate over columns and find the minimum in each row,
  8786. use ``axis=1``
  8787. >>> df.cummin(axis=1)
  8788. A B
  8789. 0 2.0 1.0
  8790. 1 3.0 NaN
  8791. 2 1.0 0.0
  8792. """
  8793. _cumsum_examples = """\
  8794. Examples
  8795. --------
  8796. **Series**
  8797. >>> s = pd.Series([2, np.nan, 5, -1, 0])
  8798. >>> s
  8799. 0 2.0
  8800. 1 NaN
  8801. 2 5.0
  8802. 3 -1.0
  8803. 4 0.0
  8804. dtype: float64
  8805. By default, NA values are ignored.
  8806. >>> s.cumsum()
  8807. 0 2.0
  8808. 1 NaN
  8809. 2 7.0
  8810. 3 6.0
  8811. 4 6.0
  8812. dtype: float64
  8813. To include NA values in the operation, use ``skipna=False``
  8814. >>> s.cumsum(skipna=False)
  8815. 0 2.0
  8816. 1 NaN
  8817. 2 NaN
  8818. 3 NaN
  8819. 4 NaN
  8820. dtype: float64
  8821. **DataFrame**
  8822. >>> df = pd.DataFrame([[2.0, 1.0],
  8823. ... [3.0, np.nan],
  8824. ... [1.0, 0.0]],
  8825. ... columns=list('AB'))
  8826. >>> df
  8827. A B
  8828. 0 2.0 1.0
  8829. 1 3.0 NaN
  8830. 2 1.0 0.0
  8831. By default, iterates over rows and finds the sum
  8832. in each column. This is equivalent to ``axis=None`` or ``axis='index'``.
  8833. >>> df.cumsum()
  8834. A B
  8835. 0 2.0 1.0
  8836. 1 5.0 NaN
  8837. 2 6.0 1.0
  8838. To iterate over columns and find the sum in each row,
  8839. use ``axis=1``
  8840. >>> df.cumsum(axis=1)
  8841. A B
  8842. 0 2.0 3.0
  8843. 1 3.0 NaN
  8844. 2 1.0 1.0
  8845. """
  8846. _cumprod_examples = """\
  8847. Examples
  8848. --------
  8849. **Series**
  8850. >>> s = pd.Series([2, np.nan, 5, -1, 0])
  8851. >>> s
  8852. 0 2.0
  8853. 1 NaN
  8854. 2 5.0
  8855. 3 -1.0
  8856. 4 0.0
  8857. dtype: float64
  8858. By default, NA values are ignored.
  8859. >>> s.cumprod()
  8860. 0 2.0
  8861. 1 NaN
  8862. 2 10.0
  8863. 3 -10.0
  8864. 4 -0.0
  8865. dtype: float64
  8866. To include NA values in the operation, use ``skipna=False``
  8867. >>> s.cumprod(skipna=False)
  8868. 0 2.0
  8869. 1 NaN
  8870. 2 NaN
  8871. 3 NaN
  8872. 4 NaN
  8873. dtype: float64
  8874. **DataFrame**
  8875. >>> df = pd.DataFrame([[2.0, 1.0],
  8876. ... [3.0, np.nan],
  8877. ... [1.0, 0.0]],
  8878. ... columns=list('AB'))
  8879. >>> df
  8880. A B
  8881. 0 2.0 1.0
  8882. 1 3.0 NaN
  8883. 2 1.0 0.0
  8884. By default, iterates over rows and finds the product
  8885. in each column. This is equivalent to ``axis=None`` or ``axis='index'``.
  8886. >>> df.cumprod()
  8887. A B
  8888. 0 2.0 1.0
  8889. 1 6.0 NaN
  8890. 2 6.0 0.0
  8891. To iterate over columns and find the product in each row,
  8892. use ``axis=1``
  8893. >>> df.cumprod(axis=1)
  8894. A B
  8895. 0 2.0 2.0
  8896. 1 3.0 NaN
  8897. 2 1.0 0.0
  8898. """
  8899. _cummax_examples = """\
  8900. Examples
  8901. --------
  8902. **Series**
  8903. >>> s = pd.Series([2, np.nan, 5, -1, 0])
  8904. >>> s
  8905. 0 2.0
  8906. 1 NaN
  8907. 2 5.0
  8908. 3 -1.0
  8909. 4 0.0
  8910. dtype: float64
  8911. By default, NA values are ignored.
  8912. >>> s.cummax()
  8913. 0 2.0
  8914. 1 NaN
  8915. 2 5.0
  8916. 3 5.0
  8917. 4 5.0
  8918. dtype: float64
  8919. To include NA values in the operation, use ``skipna=False``
  8920. >>> s.cummax(skipna=False)
  8921. 0 2.0
  8922. 1 NaN
  8923. 2 NaN
  8924. 3 NaN
  8925. 4 NaN
  8926. dtype: float64
  8927. **DataFrame**
  8928. >>> df = pd.DataFrame([[2.0, 1.0],
  8929. ... [3.0, np.nan],
  8930. ... [1.0, 0.0]],
  8931. ... columns=list('AB'))
  8932. >>> df
  8933. A B
  8934. 0 2.0 1.0
  8935. 1 3.0 NaN
  8936. 2 1.0 0.0
  8937. By default, iterates over rows and finds the maximum
  8938. in each column. This is equivalent to ``axis=None`` or ``axis='index'``.
  8939. >>> df.cummax()
  8940. A B
  8941. 0 2.0 1.0
  8942. 1 3.0 NaN
  8943. 2 3.0 1.0
  8944. To iterate over columns and find the maximum in each row,
  8945. use ``axis=1``
  8946. >>> df.cummax(axis=1)
  8947. A B
  8948. 0 2.0 2.0
  8949. 1 3.0 NaN
  8950. 2 1.0 1.0
  8951. """
  8952. _any_see_also = """\
  8953. See Also
  8954. --------
  8955. numpy.any : Numpy version of this method.
  8956. Series.any : Return whether any element is True.
  8957. Series.all : Return whether all elements are True.
  8958. DataFrame.any : Return whether any element is True over requested axis.
  8959. DataFrame.all : Return whether all elements are True over requested axis.
  8960. """
  8961. _any_desc = """\
  8962. Return whether any element is True, potentially over an axis.
  8963. Returns False unless there at least one element within a series or
  8964. along a Dataframe axis that is True or equivalent (e.g. non-zero or
  8965. non-empty)."""
  8966. _any_examples = """\
  8967. Examples
  8968. --------
  8969. **Series**
  8970. For Series input, the output is a scalar indicating whether any element
  8971. is True.
  8972. >>> pd.Series([False, False]).any()
  8973. False
  8974. >>> pd.Series([True, False]).any()
  8975. True
  8976. >>> pd.Series([]).any()
  8977. False
  8978. >>> pd.Series([np.nan]).any()
  8979. False
  8980. >>> pd.Series([np.nan]).any(skipna=False)
  8981. True
  8982. **DataFrame**
  8983. Whether each column contains at least one True element (the default).
  8984. >>> df = pd.DataFrame({"A": [1, 2], "B": [0, 2], "C": [0, 0]})
  8985. >>> df
  8986. A B C
  8987. 0 1 0 0
  8988. 1 2 2 0
  8989. >>> df.any()
  8990. A True
  8991. B True
  8992. C False
  8993. dtype: bool
  8994. Aggregating over the columns.
  8995. >>> df = pd.DataFrame({"A": [True, False], "B": [1, 2]})
  8996. >>> df
  8997. A B
  8998. 0 True 1
  8999. 1 False 2
  9000. >>> df.any(axis='columns')
  9001. 0 True
  9002. 1 True
  9003. dtype: bool
  9004. >>> df = pd.DataFrame({"A": [True, False], "B": [1, 0]})
  9005. >>> df
  9006. A B
  9007. 0 True 1
  9008. 1 False 0
  9009. >>> df.any(axis='columns')
  9010. 0 True
  9011. 1 False
  9012. dtype: bool
  9013. Aggregating over the entire DataFrame with ``axis=None``.
  9014. >>> df.any(axis=None)
  9015. True
  9016. `any` for an empty DataFrame is an empty Series.
  9017. >>> pd.DataFrame([]).any()
  9018. Series([], dtype: bool)
  9019. """
  9020. _shared_docs['stat_func_example'] = """\
  9021. Examples
  9022. --------
  9023. >>> idx = pd.MultiIndex.from_arrays([
  9024. ... ['warm', 'warm', 'cold', 'cold'],
  9025. ... ['dog', 'falcon', 'fish', 'spider']],
  9026. ... names=['blooded', 'animal'])
  9027. >>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx)
  9028. >>> s
  9029. blooded animal
  9030. warm dog 4
  9031. falcon 2
  9032. cold fish 0
  9033. spider 8
  9034. Name: legs, dtype: int64
  9035. >>> s.{stat_func}()
  9036. {default_output}
  9037. {verb} using level names, as well as indices.
  9038. >>> s.{stat_func}(level='blooded')
  9039. blooded
  9040. warm {level_output_0}
  9041. cold {level_output_1}
  9042. Name: legs, dtype: int64
  9043. >>> s.{stat_func}(level=0)
  9044. blooded
  9045. warm {level_output_0}
  9046. cold {level_output_1}
  9047. Name: legs, dtype: int64
  9048. """
  9049. _sum_examples = _shared_docs['stat_func_example'].format(
  9050. stat_func='sum',
  9051. verb='Sum',
  9052. default_output=14,
  9053. level_output_0=6,
  9054. level_output_1=8)
  9055. _sum_examples += """
  9056. By default, the sum of an empty or all-NA Series is ``0``.
  9057. >>> pd.Series([]).sum() # min_count=0 is the default
  9058. 0.0
  9059. This can be controlled with the ``min_count`` parameter. For example, if
  9060. you'd like the sum of an empty series to be NaN, pass ``min_count=1``.
  9061. >>> pd.Series([]).sum(min_count=1)
  9062. nan
  9063. Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and
  9064. empty series identically.
  9065. >>> pd.Series([np.nan]).sum()
  9066. 0.0
  9067. >>> pd.Series([np.nan]).sum(min_count=1)
  9068. nan
  9069. """
  9070. _max_examples = _shared_docs['stat_func_example'].format(
  9071. stat_func='max',
  9072. verb='Max',
  9073. default_output=8,
  9074. level_output_0=4,
  9075. level_output_1=8)
  9076. _min_examples = _shared_docs['stat_func_example'].format(
  9077. stat_func='min',
  9078. verb='Min',
  9079. default_output=0,
  9080. level_output_0=2,
  9081. level_output_1=0)
  9082. _stat_func_see_also = """
  9083. See Also
  9084. --------
  9085. Series.sum : Return the sum.
  9086. Series.min : Return the minimum.
  9087. Series.max : Return the maximum.
  9088. Series.idxmin : Return the index of the minimum.
  9089. Series.idxmax : Return the index of the maximum.
  9090. DataFrame.sum : Return the sum over the requested axis.
  9091. DataFrame.min : Return the minimum over the requested axis.
  9092. DataFrame.max : Return the maximum over the requested axis.
  9093. DataFrame.idxmin : Return the index of the minimum over the requested axis.
  9094. DataFrame.idxmax : Return the index of the maximum over the requested axis.
  9095. """
  9096. _prod_examples = """\
  9097. Examples
  9098. --------
  9099. By default, the product of an empty or all-NA Series is ``1``
  9100. >>> pd.Series([]).prod()
  9101. 1.0
  9102. This can be controlled with the ``min_count`` parameter
  9103. >>> pd.Series([]).prod(min_count=1)
  9104. nan
  9105. Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and
  9106. empty series identically.
  9107. >>> pd.Series([np.nan]).prod()
  9108. 1.0
  9109. >>> pd.Series([np.nan]).prod(min_count=1)
  9110. nan
  9111. """
  9112. _min_count_stub = """\
  9113. min_count : int, default 0
  9114. The required number of valid values to perform the operation. If fewer than
  9115. ``min_count`` non-NA values are present the result will be NA.
  9116. .. versionadded :: 0.22.0
  9117. Added with the default being 0. This means the sum of an all-NA
  9118. or empty Series is 0, and the product of an all-NA or empty
  9119. Series is 1.
  9120. """
  9121. def _make_min_count_stat_function(cls, name, name1, name2, axis_descr, desc,
  9122. f, see_also='', examples=''):
  9123. @Substitution(desc=desc, name1=name1, name2=name2,
  9124. axis_descr=axis_descr, min_count=_min_count_stub,
  9125. see_also=see_also, examples=examples)
  9126. @Appender(_num_doc)
  9127. def stat_func(self, axis=None, skipna=None, level=None, numeric_only=None,
  9128. min_count=0,
  9129. **kwargs):
  9130. if name == 'sum':
  9131. nv.validate_sum(tuple(), kwargs)
  9132. elif name == 'prod':
  9133. nv.validate_prod(tuple(), kwargs)
  9134. else:
  9135. nv.validate_stat_func(tuple(), kwargs, fname=name)
  9136. if skipna is None:
  9137. skipna = True
  9138. if axis is None:
  9139. axis = self._stat_axis_number
  9140. if level is not None:
  9141. return self._agg_by_level(name, axis=axis, level=level,
  9142. skipna=skipna, min_count=min_count)
  9143. return self._reduce(f, name, axis=axis, skipna=skipna,
  9144. numeric_only=numeric_only, min_count=min_count)
  9145. return set_function_name(stat_func, name, cls)
  9146. def _make_stat_function(cls, name, name1, name2, axis_descr, desc, f,
  9147. see_also='', examples=''):
  9148. @Substitution(desc=desc, name1=name1, name2=name2,
  9149. axis_descr=axis_descr, min_count='', see_also=see_also,
  9150. examples=examples)
  9151. @Appender(_num_doc)
  9152. def stat_func(self, axis=None, skipna=None, level=None, numeric_only=None,
  9153. **kwargs):
  9154. if name == 'median':
  9155. nv.validate_median(tuple(), kwargs)
  9156. else:
  9157. nv.validate_stat_func(tuple(), kwargs, fname=name)
  9158. if skipna is None:
  9159. skipna = True
  9160. if axis is None:
  9161. axis = self._stat_axis_number
  9162. if level is not None:
  9163. return self._agg_by_level(name, axis=axis, level=level,
  9164. skipna=skipna)
  9165. return self._reduce(f, name, axis=axis, skipna=skipna,
  9166. numeric_only=numeric_only)
  9167. return set_function_name(stat_func, name, cls)
  9168. def _make_stat_function_ddof(cls, name, name1, name2, axis_descr, desc, f):
  9169. @Substitution(desc=desc, name1=name1, name2=name2,
  9170. axis_descr=axis_descr)
  9171. @Appender(_num_ddof_doc)
  9172. def stat_func(self, axis=None, skipna=None, level=None, ddof=1,
  9173. numeric_only=None, **kwargs):
  9174. nv.validate_stat_ddof_func(tuple(), kwargs, fname=name)
  9175. if skipna is None:
  9176. skipna = True
  9177. if axis is None:
  9178. axis = self._stat_axis_number
  9179. if level is not None:
  9180. return self._agg_by_level(name, axis=axis, level=level,
  9181. skipna=skipna, ddof=ddof)
  9182. return self._reduce(f, name, axis=axis, numeric_only=numeric_only,
  9183. skipna=skipna, ddof=ddof)
  9184. return set_function_name(stat_func, name, cls)
  9185. def _make_cum_function(cls, name, name1, name2, axis_descr, desc,
  9186. accum_func, accum_func_name, mask_a, mask_b, examples):
  9187. @Substitution(desc=desc, name1=name1, name2=name2,
  9188. axis_descr=axis_descr, accum_func_name=accum_func_name,
  9189. examples=examples)
  9190. @Appender(_cnum_doc)
  9191. def cum_func(self, axis=None, skipna=True, *args, **kwargs):
  9192. skipna = nv.validate_cum_func_with_skipna(skipna, args, kwargs, name)
  9193. if axis is None:
  9194. axis = self._stat_axis_number
  9195. else:
  9196. axis = self._get_axis_number(axis)
  9197. y = com.values_from_object(self).copy()
  9198. if (skipna and
  9199. issubclass(y.dtype.type, (np.datetime64, np.timedelta64))):
  9200. result = accum_func(y, axis)
  9201. mask = isna(self)
  9202. np.putmask(result, mask, iNaT)
  9203. elif skipna and not issubclass(y.dtype.type, (np.integer, np.bool_)):
  9204. mask = isna(self)
  9205. np.putmask(y, mask, mask_a)
  9206. result = accum_func(y, axis)
  9207. np.putmask(result, mask, mask_b)
  9208. else:
  9209. result = accum_func(y, axis)
  9210. d = self._construct_axes_dict()
  9211. d['copy'] = False
  9212. return self._constructor(result, **d).__finalize__(self)
  9213. return set_function_name(cum_func, name, cls)
  9214. def _make_logical_function(cls, name, name1, name2, axis_descr, desc, f,
  9215. see_also, examples, empty_value):
  9216. @Substitution(desc=desc, name1=name1, name2=name2,
  9217. axis_descr=axis_descr, see_also=see_also, examples=examples,
  9218. empty_value=empty_value)
  9219. @Appender(_bool_doc)
  9220. def logical_func(self, axis=0, bool_only=None, skipna=True, level=None,
  9221. **kwargs):
  9222. nv.validate_logical_func(tuple(), kwargs, fname=name)
  9223. if level is not None:
  9224. if bool_only is not None:
  9225. raise NotImplementedError("Option bool_only is not "
  9226. "implemented with option level.")
  9227. return self._agg_by_level(name, axis=axis, level=level,
  9228. skipna=skipna)
  9229. return self._reduce(f, name, axis=axis, skipna=skipna,
  9230. numeric_only=bool_only, filter_type='bool')
  9231. return set_function_name(logical_func, name, cls)
  9232. # install the indexes
  9233. for _name, _indexer in indexing.get_indexers_list():
  9234. NDFrame._create_indexer(_name, _indexer)