shared_docs.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. from __future__ import annotations
  2. _shared_docs: dict[str, str] = {}
  3. _shared_docs[
  4. "aggregate"
  5. ] = """
  6. Aggregate using one or more operations over the specified axis.
  7. Parameters
  8. ----------
  9. func : function, str, list or dict
  10. Function to use for aggregating the data. If a function, must either
  11. work when passed a {klass} or when passed to {klass}.apply.
  12. Accepted combinations are:
  13. - function
  14. - string function name
  15. - list of functions and/or function names, e.g. ``[np.sum, 'mean']``
  16. - dict of axis labels -> functions, function names or list of such.
  17. {axis}
  18. *args
  19. Positional arguments to pass to `func`.
  20. **kwargs
  21. Keyword arguments to pass to `func`.
  22. Returns
  23. -------
  24. scalar, Series or DataFrame
  25. The return can be:
  26. * scalar : when Series.agg is called with single function
  27. * Series : when DataFrame.agg is called with a single function
  28. * DataFrame : when DataFrame.agg is called with several functions
  29. Return scalar, Series or DataFrame.
  30. {see_also}
  31. Notes
  32. -----
  33. `agg` is an alias for `aggregate`. Use the alias.
  34. Functions that mutate the passed object can produce unexpected
  35. behavior or errors and are not supported. See :ref:`gotchas.udf-mutation`
  36. for more details.
  37. A passed user-defined-function will be passed a Series for evaluation.
  38. {examples}"""
  39. _shared_docs[
  40. "compare"
  41. ] = """
  42. Compare to another {klass} and show the differences.
  43. .. versionadded:: 1.1.0
  44. Parameters
  45. ----------
  46. other : {klass}
  47. Object to compare with.
  48. align_axis : {{0 or 'index', 1 or 'columns'}}, default 1
  49. Determine which axis to align the comparison on.
  50. * 0, or 'index' : Resulting differences are stacked vertically
  51. with rows drawn alternately from self and other.
  52. * 1, or 'columns' : Resulting differences are aligned horizontally
  53. with columns drawn alternately from self and other.
  54. keep_shape : bool, default False
  55. If true, all rows and columns are kept.
  56. Otherwise, only the ones with different values are kept.
  57. keep_equal : bool, default False
  58. If true, the result keeps values that are equal.
  59. Otherwise, equal values are shown as NaNs.
  60. result_names : tuple, default ('self', 'other')
  61. Set the dataframes names in the comparison.
  62. .. versionadded:: 1.5.0
  63. """
  64. _shared_docs[
  65. "groupby"
  66. ] = """
  67. Group %(klass)s using a mapper or by a Series of columns.
  68. A groupby operation involves some combination of splitting the
  69. object, applying a function, and combining the results. This can be
  70. used to group large amounts of data and compute operations on these
  71. groups.
  72. Parameters
  73. ----------
  74. by : mapping, function, label, pd.Grouper or list of such
  75. Used to determine the groups for the groupby.
  76. If ``by`` is a function, it's called on each value of the object's
  77. index. If a dict or Series is passed, the Series or dict VALUES
  78. will be used to determine the groups (the Series' values are first
  79. aligned; see ``.align()`` method). If a list or ndarray of length
  80. equal to the selected axis is passed (see the `groupby user guide
  81. <https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#splitting-an-object-into-groups>`_),
  82. the values are used as-is to determine the groups. A label or list
  83. of labels may be passed to group by the columns in ``self``.
  84. Notice that a tuple is interpreted as a (single) key.
  85. axis : {0 or 'index', 1 or 'columns'}, default 0
  86. Split along rows (0) or columns (1). For `Series` this parameter
  87. is unused and defaults to 0.
  88. level : int, level name, or sequence of such, default None
  89. If the axis is a MultiIndex (hierarchical), group by a particular
  90. level or levels. Do not specify both ``by`` and ``level``.
  91. as_index : bool, default True
  92. For aggregated output, return object with group labels as the
  93. index. Only relevant for DataFrame input. as_index=False is
  94. effectively "SQL-style" grouped output.
  95. sort : bool, default True
  96. Sort group keys. Get better performance by turning this off.
  97. Note this does not influence the order of observations within each
  98. group. Groupby preserves the order of rows within each group.
  99. .. versionchanged:: 2.0.0
  100. Specifying ``sort=False`` with an ordered categorical grouper will no
  101. longer sort the values.
  102. group_keys : bool, default True
  103. When calling apply and the ``by`` argument produces a like-indexed
  104. (i.e. :ref:`a transform <groupby.transform>`) result, add group keys to
  105. index to identify pieces. By default group keys are not included
  106. when the result's index (and column) labels match the inputs, and
  107. are included otherwise.
  108. .. versionchanged:: 1.5.0
  109. Warns that ``group_keys`` will no longer be ignored when the
  110. result from ``apply`` is a like-indexed Series or DataFrame.
  111. Specify ``group_keys`` explicitly to include the group keys or
  112. not.
  113. .. versionchanged:: 2.0.0
  114. ``group_keys`` now defaults to ``True``.
  115. observed : bool, default False
  116. This only applies if any of the groupers are Categoricals.
  117. If True: only show observed values for categorical groupers.
  118. If False: show all values for categorical groupers.
  119. dropna : bool, default True
  120. If True, and if group keys contain NA values, NA values together
  121. with row/column will be dropped.
  122. If False, NA values will also be treated as the key in groups.
  123. .. versionadded:: 1.1.0
  124. Returns
  125. -------
  126. %(klass)sGroupBy
  127. Returns a groupby object that contains information about the groups.
  128. See Also
  129. --------
  130. resample : Convenience method for frequency conversion and resampling
  131. of time series.
  132. Notes
  133. -----
  134. See the `user guide
  135. <https://pandas.pydata.org/pandas-docs/stable/groupby.html>`__ for more
  136. detailed usage and examples, including splitting an object into groups,
  137. iterating through groups, selecting a group, aggregation, and more.
  138. """
  139. _shared_docs[
  140. "melt"
  141. ] = """
  142. Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.
  143. This function is useful to massage a DataFrame into a format where one
  144. or more columns are identifier variables (`id_vars`), while all other
  145. columns, considered measured variables (`value_vars`), are "unpivoted" to
  146. the row axis, leaving just two non-identifier columns, 'variable' and
  147. 'value'.
  148. Parameters
  149. ----------
  150. id_vars : tuple, list, or ndarray, optional
  151. Column(s) to use as identifier variables.
  152. value_vars : tuple, list, or ndarray, optional
  153. Column(s) to unpivot. If not specified, uses all columns that
  154. are not set as `id_vars`.
  155. var_name : scalar
  156. Name to use for the 'variable' column. If None it uses
  157. ``frame.columns.name`` or 'variable'.
  158. value_name : scalar, default 'value'
  159. Name to use for the 'value' column.
  160. col_level : int or str, optional
  161. If columns are a MultiIndex then use this level to melt.
  162. ignore_index : bool, default True
  163. If True, original index is ignored. If False, the original index is retained.
  164. Index labels will be repeated as necessary.
  165. .. versionadded:: 1.1.0
  166. Returns
  167. -------
  168. DataFrame
  169. Unpivoted DataFrame.
  170. See Also
  171. --------
  172. %(other)s : Identical method.
  173. pivot_table : Create a spreadsheet-style pivot table as a DataFrame.
  174. DataFrame.pivot : Return reshaped DataFrame organized
  175. by given index / column values.
  176. DataFrame.explode : Explode a DataFrame from list-like
  177. columns to long format.
  178. Notes
  179. -----
  180. Reference :ref:`the user guide <reshaping.melt>` for more examples.
  181. Examples
  182. --------
  183. >>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},
  184. ... 'B': {0: 1, 1: 3, 2: 5},
  185. ... 'C': {0: 2, 1: 4, 2: 6}})
  186. >>> df
  187. A B C
  188. 0 a 1 2
  189. 1 b 3 4
  190. 2 c 5 6
  191. >>> %(caller)sid_vars=['A'], value_vars=['B'])
  192. A variable value
  193. 0 a B 1
  194. 1 b B 3
  195. 2 c B 5
  196. >>> %(caller)sid_vars=['A'], value_vars=['B', 'C'])
  197. A variable value
  198. 0 a B 1
  199. 1 b B 3
  200. 2 c B 5
  201. 3 a C 2
  202. 4 b C 4
  203. 5 c C 6
  204. The names of 'variable' and 'value' columns can be customized:
  205. >>> %(caller)sid_vars=['A'], value_vars=['B'],
  206. ... var_name='myVarname', value_name='myValname')
  207. A myVarname myValname
  208. 0 a B 1
  209. 1 b B 3
  210. 2 c B 5
  211. Original index values can be kept around:
  212. >>> %(caller)sid_vars=['A'], value_vars=['B', 'C'], ignore_index=False)
  213. A variable value
  214. 0 a B 1
  215. 1 b B 3
  216. 2 c B 5
  217. 0 a C 2
  218. 1 b C 4
  219. 2 c C 6
  220. If you have multi-index columns:
  221. >>> df.columns = [list('ABC'), list('DEF')]
  222. >>> df
  223. A B C
  224. D E F
  225. 0 a 1 2
  226. 1 b 3 4
  227. 2 c 5 6
  228. >>> %(caller)scol_level=0, id_vars=['A'], value_vars=['B'])
  229. A variable value
  230. 0 a B 1
  231. 1 b B 3
  232. 2 c B 5
  233. >>> %(caller)sid_vars=[('A', 'D')], value_vars=[('B', 'E')])
  234. (A, D) variable_0 variable_1 value
  235. 0 a B E 1
  236. 1 b B E 3
  237. 2 c B E 5
  238. """
  239. _shared_docs[
  240. "transform"
  241. ] = """
  242. Call ``func`` on self producing a {klass} with the same axis shape as self.
  243. Parameters
  244. ----------
  245. func : function, str, list-like or dict-like
  246. Function to use for transforming the data. If a function, must either
  247. work when passed a {klass} or when passed to {klass}.apply. If func
  248. is both list-like and dict-like, dict-like behavior takes precedence.
  249. Accepted combinations are:
  250. - function
  251. - string function name
  252. - list-like of functions and/or function names, e.g. ``[np.exp, 'sqrt']``
  253. - dict-like of axis labels -> functions, function names or list-like of such.
  254. {axis}
  255. *args
  256. Positional arguments to pass to `func`.
  257. **kwargs
  258. Keyword arguments to pass to `func`.
  259. Returns
  260. -------
  261. {klass}
  262. A {klass} that must have the same length as self.
  263. Raises
  264. ------
  265. ValueError : If the returned {klass} has a different length than self.
  266. See Also
  267. --------
  268. {klass}.agg : Only perform aggregating type operations.
  269. {klass}.apply : Invoke function on a {klass}.
  270. Notes
  271. -----
  272. Functions that mutate the passed object can produce unexpected
  273. behavior or errors and are not supported. See :ref:`gotchas.udf-mutation`
  274. for more details.
  275. Examples
  276. --------
  277. >>> df = pd.DataFrame({{'A': range(3), 'B': range(1, 4)}})
  278. >>> df
  279. A B
  280. 0 0 1
  281. 1 1 2
  282. 2 2 3
  283. >>> df.transform(lambda x: x + 1)
  284. A B
  285. 0 1 2
  286. 1 2 3
  287. 2 3 4
  288. Even though the resulting {klass} must have the same length as the
  289. input {klass}, it is possible to provide several input functions:
  290. >>> s = pd.Series(range(3))
  291. >>> s
  292. 0 0
  293. 1 1
  294. 2 2
  295. dtype: int64
  296. >>> s.transform([np.sqrt, np.exp])
  297. sqrt exp
  298. 0 0.000000 1.000000
  299. 1 1.000000 2.718282
  300. 2 1.414214 7.389056
  301. You can call transform on a GroupBy object:
  302. >>> df = pd.DataFrame({{
  303. ... "Date": [
  304. ... "2015-05-08", "2015-05-07", "2015-05-06", "2015-05-05",
  305. ... "2015-05-08", "2015-05-07", "2015-05-06", "2015-05-05"],
  306. ... "Data": [5, 8, 6, 1, 50, 100, 60, 120],
  307. ... }})
  308. >>> df
  309. Date Data
  310. 0 2015-05-08 5
  311. 1 2015-05-07 8
  312. 2 2015-05-06 6
  313. 3 2015-05-05 1
  314. 4 2015-05-08 50
  315. 5 2015-05-07 100
  316. 6 2015-05-06 60
  317. 7 2015-05-05 120
  318. >>> df.groupby('Date')['Data'].transform('sum')
  319. 0 55
  320. 1 108
  321. 2 66
  322. 3 121
  323. 4 55
  324. 5 108
  325. 6 66
  326. 7 121
  327. Name: Data, dtype: int64
  328. >>> df = pd.DataFrame({{
  329. ... "c": [1, 1, 1, 2, 2, 2, 2],
  330. ... "type": ["m", "n", "o", "m", "m", "n", "n"]
  331. ... }})
  332. >>> df
  333. c type
  334. 0 1 m
  335. 1 1 n
  336. 2 1 o
  337. 3 2 m
  338. 4 2 m
  339. 5 2 n
  340. 6 2 n
  341. >>> df['size'] = df.groupby('c')['type'].transform(len)
  342. >>> df
  343. c type size
  344. 0 1 m 3
  345. 1 1 n 3
  346. 2 1 o 3
  347. 3 2 m 4
  348. 4 2 m 4
  349. 5 2 n 4
  350. 6 2 n 4
  351. """
  352. _shared_docs[
  353. "storage_options"
  354. ] = """storage_options : dict, optional
  355. Extra options that make sense for a particular storage connection, e.g.
  356. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
  357. are forwarded to ``urllib.request.Request`` as header options. For other
  358. URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
  359. forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
  360. details, and for more examples on storage options refer `here
  361. <https://pandas.pydata.org/docs/user_guide/io.html?
  362. highlight=storage_options#reading-writing-remote-files>`_."""
  363. _shared_docs[
  364. "compression_options"
  365. ] = """compression : str or dict, default 'infer'
  366. For on-the-fly compression of the output data. If 'infer' and '%s' is
  367. path-like, then detect compression from the following extensions: '.gz',
  368. '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
  369. (otherwise no compression).
  370. Set to ``None`` for no compression.
  371. Can also be a dict with key ``'method'`` set
  372. to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'tar'``} and other
  373. key-value pairs are forwarded to
  374. ``zipfile.ZipFile``, ``gzip.GzipFile``,
  375. ``bz2.BZ2File``, ``zstandard.ZstdCompressor`` or
  376. ``tarfile.TarFile``, respectively.
  377. As an example, the following could be passed for faster compression and to create
  378. a reproducible gzip archive:
  379. ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.
  380. .. versionadded:: 1.5.0
  381. Added support for `.tar` files."""
  382. _shared_docs[
  383. "decompression_options"
  384. ] = """compression : str or dict, default 'infer'
  385. For on-the-fly decompression of on-disk data. If 'infer' and '%s' is
  386. path-like, then detect compression from the following extensions: '.gz',
  387. '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
  388. (otherwise no compression).
  389. If using 'zip' or 'tar', the ZIP file must contain only one data file to be read in.
  390. Set to ``None`` for no decompression.
  391. Can also be a dict with key ``'method'`` set
  392. to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'tar'``} and other
  393. key-value pairs are forwarded to
  394. ``zipfile.ZipFile``, ``gzip.GzipFile``,
  395. ``bz2.BZ2File``, ``zstandard.ZstdDecompressor`` or
  396. ``tarfile.TarFile``, respectively.
  397. As an example, the following could be passed for Zstandard decompression using a
  398. custom compression dictionary:
  399. ``compression={'method': 'zstd', 'dict_data': my_compression_dict}``.
  400. .. versionadded:: 1.5.0
  401. Added support for `.tar` files."""
  402. _shared_docs[
  403. "replace"
  404. ] = """
  405. Replace values given in `to_replace` with `value`.
  406. Values of the {klass} are replaced with other values dynamically.
  407. {replace_iloc}
  408. Parameters
  409. ----------
  410. to_replace : str, regex, list, dict, Series, int, float, or None
  411. How to find the values that will be replaced.
  412. * numeric, str or regex:
  413. - numeric: numeric values equal to `to_replace` will be
  414. replaced with `value`
  415. - str: string exactly matching `to_replace` will be replaced
  416. with `value`
  417. - regex: regexs matching `to_replace` will be replaced with
  418. `value`
  419. * list of str, regex, or numeric:
  420. - First, if `to_replace` and `value` are both lists, they
  421. **must** be the same length.
  422. - Second, if ``regex=True`` then all of the strings in **both**
  423. lists will be interpreted as regexs otherwise they will match
  424. directly. This doesn't matter much for `value` since there
  425. are only a few possible substitution regexes you can use.
  426. - str, regex and numeric rules apply as above.
  427. * dict:
  428. - Dicts can be used to specify different replacement values
  429. for different existing values. For example,
  430. ``{{'a': 'b', 'y': 'z'}}`` replaces the value 'a' with 'b' and
  431. 'y' with 'z'. To use a dict in this way, the optional `value`
  432. parameter should not be given.
  433. - For a DataFrame a dict can specify that different values
  434. should be replaced in different columns. For example,
  435. ``{{'a': 1, 'b': 'z'}}`` looks for the value 1 in column 'a'
  436. and the value 'z' in column 'b' and replaces these values
  437. with whatever is specified in `value`. The `value` parameter
  438. should not be ``None`` in this case. You can treat this as a
  439. special case of passing two lists except that you are
  440. specifying the column to search in.
  441. - For a DataFrame nested dictionaries, e.g.,
  442. ``{{'a': {{'b': np.nan}}}}``, are read as follows: look in column
  443. 'a' for the value 'b' and replace it with NaN. The optional `value`
  444. parameter should not be specified to use a nested dict in this
  445. way. You can nest regular expressions as well. Note that
  446. column names (the top-level dictionary keys in a nested
  447. dictionary) **cannot** be regular expressions.
  448. * None:
  449. - This means that the `regex` argument must be a string,
  450. compiled regular expression, or list, dict, ndarray or
  451. Series of such elements. If `value` is also ``None`` then
  452. this **must** be a nested dictionary or Series.
  453. See the examples section for examples of each of these.
  454. value : scalar, dict, list, str, regex, default None
  455. Value to replace any values matching `to_replace` with.
  456. For a DataFrame a dict of values can be used to specify which
  457. value to use for each column (columns not in the dict will not be
  458. filled). Regular expressions, strings and lists or dicts of such
  459. objects are also allowed.
  460. {inplace}
  461. limit : int, default None
  462. Maximum size gap to forward or backward fill.
  463. regex : bool or same types as `to_replace`, default False
  464. Whether to interpret `to_replace` and/or `value` as regular
  465. expressions. If this is ``True`` then `to_replace` *must* be a
  466. string. Alternatively, this could be a regular expression or a
  467. list, dict, or array of regular expressions in which case
  468. `to_replace` must be ``None``.
  469. method : {{'pad', 'ffill', 'bfill'}}
  470. The method to use when for replacement, when `to_replace` is a
  471. scalar, list or tuple and `value` is ``None``.
  472. Returns
  473. -------
  474. {klass}
  475. Object after replacement.
  476. Raises
  477. ------
  478. AssertionError
  479. * If `regex` is not a ``bool`` and `to_replace` is not
  480. ``None``.
  481. TypeError
  482. * If `to_replace` is not a scalar, array-like, ``dict``, or ``None``
  483. * If `to_replace` is a ``dict`` and `value` is not a ``list``,
  484. ``dict``, ``ndarray``, or ``Series``
  485. * If `to_replace` is ``None`` and `regex` is not compilable
  486. into a regular expression or is a list, dict, ndarray, or
  487. Series.
  488. * When replacing multiple ``bool`` or ``datetime64`` objects and
  489. the arguments to `to_replace` does not match the type of the
  490. value being replaced
  491. ValueError
  492. * If a ``list`` or an ``ndarray`` is passed to `to_replace` and
  493. `value` but they are not the same length.
  494. See Also
  495. --------
  496. {klass}.fillna : Fill NA values.
  497. {klass}.where : Replace values based on boolean condition.
  498. Series.str.replace : Simple string replacement.
  499. Notes
  500. -----
  501. * Regex substitution is performed under the hood with ``re.sub``. The
  502. rules for substitution for ``re.sub`` are the same.
  503. * Regular expressions will only substitute on strings, meaning you
  504. cannot provide, for example, a regular expression matching floating
  505. point numbers and expect the columns in your frame that have a
  506. numeric dtype to be matched. However, if those floating point
  507. numbers *are* strings, then you can do this.
  508. * This method has *a lot* of options. You are encouraged to experiment
  509. and play with this method to gain intuition about how it works.
  510. * When dict is used as the `to_replace` value, it is like
  511. key(s) in the dict are the to_replace part and
  512. value(s) in the dict are the value parameter.
  513. Examples
  514. --------
  515. **Scalar `to_replace` and `value`**
  516. >>> s = pd.Series([1, 2, 3, 4, 5])
  517. >>> s.replace(1, 5)
  518. 0 5
  519. 1 2
  520. 2 3
  521. 3 4
  522. 4 5
  523. dtype: int64
  524. >>> df = pd.DataFrame({{'A': [0, 1, 2, 3, 4],
  525. ... 'B': [5, 6, 7, 8, 9],
  526. ... 'C': ['a', 'b', 'c', 'd', 'e']}})
  527. >>> df.replace(0, 5)
  528. A B C
  529. 0 5 5 a
  530. 1 1 6 b
  531. 2 2 7 c
  532. 3 3 8 d
  533. 4 4 9 e
  534. **List-like `to_replace`**
  535. >>> df.replace([0, 1, 2, 3], 4)
  536. A B C
  537. 0 4 5 a
  538. 1 4 6 b
  539. 2 4 7 c
  540. 3 4 8 d
  541. 4 4 9 e
  542. >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])
  543. A B C
  544. 0 4 5 a
  545. 1 3 6 b
  546. 2 2 7 c
  547. 3 1 8 d
  548. 4 4 9 e
  549. >>> s.replace([1, 2], method='bfill')
  550. 0 3
  551. 1 3
  552. 2 3
  553. 3 4
  554. 4 5
  555. dtype: int64
  556. **dict-like `to_replace`**
  557. >>> df.replace({{0: 10, 1: 100}})
  558. A B C
  559. 0 10 5 a
  560. 1 100 6 b
  561. 2 2 7 c
  562. 3 3 8 d
  563. 4 4 9 e
  564. >>> df.replace({{'A': 0, 'B': 5}}, 100)
  565. A B C
  566. 0 100 100 a
  567. 1 1 6 b
  568. 2 2 7 c
  569. 3 3 8 d
  570. 4 4 9 e
  571. >>> df.replace({{'A': {{0: 100, 4: 400}}}})
  572. A B C
  573. 0 100 5 a
  574. 1 1 6 b
  575. 2 2 7 c
  576. 3 3 8 d
  577. 4 400 9 e
  578. **Regular expression `to_replace`**
  579. >>> df = pd.DataFrame({{'A': ['bat', 'foo', 'bait'],
  580. ... 'B': ['abc', 'bar', 'xyz']}})
  581. >>> df.replace(to_replace=r'^ba.$', value='new', regex=True)
  582. A B
  583. 0 new abc
  584. 1 foo new
  585. 2 bait xyz
  586. >>> df.replace({{'A': r'^ba.$'}}, {{'A': 'new'}}, regex=True)
  587. A B
  588. 0 new abc
  589. 1 foo bar
  590. 2 bait xyz
  591. >>> df.replace(regex=r'^ba.$', value='new')
  592. A B
  593. 0 new abc
  594. 1 foo new
  595. 2 bait xyz
  596. >>> df.replace(regex={{r'^ba.$': 'new', 'foo': 'xyz'}})
  597. A B
  598. 0 new abc
  599. 1 xyz new
  600. 2 bait xyz
  601. >>> df.replace(regex=[r'^ba.$', 'foo'], value='new')
  602. A B
  603. 0 new abc
  604. 1 new new
  605. 2 bait xyz
  606. Compare the behavior of ``s.replace({{'a': None}})`` and
  607. ``s.replace('a', None)`` to understand the peculiarities
  608. of the `to_replace` parameter:
  609. >>> s = pd.Series([10, 'a', 'a', 'b', 'a'])
  610. When one uses a dict as the `to_replace` value, it is like the
  611. value(s) in the dict are equal to the `value` parameter.
  612. ``s.replace({{'a': None}})`` is equivalent to
  613. ``s.replace(to_replace={{'a': None}}, value=None, method=None)``:
  614. >>> s.replace({{'a': None}})
  615. 0 10
  616. 1 None
  617. 2 None
  618. 3 b
  619. 4 None
  620. dtype: object
  621. When ``value`` is not explicitly passed and `to_replace` is a scalar, list
  622. or tuple, `replace` uses the method parameter (default 'pad') to do the
  623. replacement. So this is why the 'a' values are being replaced by 10
  624. in rows 1 and 2 and 'b' in row 4 in this case.
  625. >>> s.replace('a')
  626. 0 10
  627. 1 10
  628. 2 10
  629. 3 b
  630. 4 b
  631. dtype: object
  632. On the other hand, if ``None`` is explicitly passed for ``value``, it will
  633. be respected:
  634. >>> s.replace('a', None)
  635. 0 10
  636. 1 None
  637. 2 None
  638. 3 b
  639. 4 None
  640. dtype: object
  641. .. versionchanged:: 1.4.0
  642. Previously the explicit ``None`` was silently ignored.
  643. """
  644. _shared_docs[
  645. "idxmin"
  646. ] = """
  647. Return index of first occurrence of minimum over requested axis.
  648. NA/null values are excluded.
  649. Parameters
  650. ----------
  651. axis : {{0 or 'index', 1 or 'columns'}}, default 0
  652. The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
  653. skipna : bool, default True
  654. Exclude NA/null values. If an entire row/column is NA, the result
  655. will be NA.
  656. numeric_only : bool, default {numeric_only_default}
  657. Include only `float`, `int` or `boolean` data.
  658. .. versionadded:: 1.5.0
  659. Returns
  660. -------
  661. Series
  662. Indexes of minima along the specified axis.
  663. Raises
  664. ------
  665. ValueError
  666. * If the row/column is empty
  667. See Also
  668. --------
  669. Series.idxmin : Return index of the minimum element.
  670. Notes
  671. -----
  672. This method is the DataFrame version of ``ndarray.argmin``.
  673. Examples
  674. --------
  675. Consider a dataset containing food consumption in Argentina.
  676. >>> df = pd.DataFrame({{'consumption': [10.51, 103.11, 55.48],
  677. ... 'co2_emissions': [37.2, 19.66, 1712]}},
  678. ... index=['Pork', 'Wheat Products', 'Beef'])
  679. >>> df
  680. consumption co2_emissions
  681. Pork 10.51 37.20
  682. Wheat Products 103.11 19.66
  683. Beef 55.48 1712.00
  684. By default, it returns the index for the minimum value in each column.
  685. >>> df.idxmin()
  686. consumption Pork
  687. co2_emissions Wheat Products
  688. dtype: object
  689. To return the index for the minimum value in each row, use ``axis="columns"``.
  690. >>> df.idxmin(axis="columns")
  691. Pork consumption
  692. Wheat Products co2_emissions
  693. Beef consumption
  694. dtype: object
  695. """
  696. _shared_docs[
  697. "idxmax"
  698. ] = """
  699. Return index of first occurrence of maximum over requested axis.
  700. NA/null values are excluded.
  701. Parameters
  702. ----------
  703. axis : {{0 or 'index', 1 or 'columns'}}, default 0
  704. The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
  705. skipna : bool, default True
  706. Exclude NA/null values. If an entire row/column is NA, the result
  707. will be NA.
  708. numeric_only : bool, default {numeric_only_default}
  709. Include only `float`, `int` or `boolean` data.
  710. .. versionadded:: 1.5.0
  711. Returns
  712. -------
  713. Series
  714. Indexes of maxima along the specified axis.
  715. Raises
  716. ------
  717. ValueError
  718. * If the row/column is empty
  719. See Also
  720. --------
  721. Series.idxmax : Return index of the maximum element.
  722. Notes
  723. -----
  724. This method is the DataFrame version of ``ndarray.argmax``.
  725. Examples
  726. --------
  727. Consider a dataset containing food consumption in Argentina.
  728. >>> df = pd.DataFrame({{'consumption': [10.51, 103.11, 55.48],
  729. ... 'co2_emissions': [37.2, 19.66, 1712]}},
  730. ... index=['Pork', 'Wheat Products', 'Beef'])
  731. >>> df
  732. consumption co2_emissions
  733. Pork 10.51 37.20
  734. Wheat Products 103.11 19.66
  735. Beef 55.48 1712.00
  736. By default, it returns the index for the maximum value in each column.
  737. >>> df.idxmax()
  738. consumption Wheat Products
  739. co2_emissions Beef
  740. dtype: object
  741. To return the index for the maximum value in each row, use ``axis="columns"``.
  742. >>> df.idxmax(axis="columns")
  743. Pork co2_emissions
  744. Wheat Products consumption
  745. Beef co2_emissions
  746. dtype: object
  747. """