`` where `k` is the level in a MultiIndex
+
+ * Blank cells include ``blank``
+ * Data cells include ``data``
+ * Trimmed cells include ``col_trim`` or ``row_trim``.
+
+ Any, or all, or these classes can be renamed by using the ``css_class_names``
+ argument in ``Styler.set_table_classes``, giving a value such as
+ *{"row": "MY_ROW_CLASS", "col_trim": "", "row_trim": ""}*.
+
+ Examples
+ --------
+ >>> df = pd.DataFrame([[1.0, 2.0, 3.0], [4, 5, 6]], index=['a', 'b'],
+ ... columns=['A', 'B', 'C'])
+ >>> pd.io.formats.style.Styler(df, precision=2,
+ ... caption="My table") # doctest: +SKIP
+
+ Please see:
+ `Table Visualization <../../user_guide/style.ipynb>`_ for more examples.
+ """
+
+ def __init__(
+ self,
+ data: DataFrame | Series,
+ precision: int | None = None,
+ table_styles: CSSStyles | None = None,
+ uuid: str | None = None,
+ caption: str | tuple | list | None = None,
+ table_attributes: str | None = None,
+ cell_ids: bool = True,
+ na_rep: str | None = None,
+ uuid_len: int = 5,
+ decimal: str | None = None,
+ thousands: str | None = None,
+ escape: str | None = None,
+ formatter: ExtFormatter | None = None,
+ ) -> None:
+ super().__init__(
+ data=data,
+ uuid=uuid,
+ uuid_len=uuid_len,
+ table_styles=table_styles,
+ table_attributes=table_attributes,
+ caption=caption,
+ cell_ids=cell_ids,
+ precision=precision,
+ )
+
+ # validate ordered args
+ thousands = thousands or get_option("styler.format.thousands")
+ decimal = decimal or get_option("styler.format.decimal")
+ na_rep = na_rep or get_option("styler.format.na_rep")
+ escape = escape or get_option("styler.format.escape")
+ formatter = formatter or get_option("styler.format.formatter")
+ # precision is handled by superclass as default for performance
+
+ self.format(
+ formatter=formatter,
+ precision=precision,
+ na_rep=na_rep,
+ escape=escape,
+ decimal=decimal,
+ thousands=thousands,
+ )
+
+ def concat(self, other: Styler) -> Styler:
+ """
+ Append another Styler to combine the output into a single table.
+
+ .. versionadded:: 1.5.0
+
+ Parameters
+ ----------
+ other : Styler
+ The other Styler object which has already been styled and formatted. The
+ data for this Styler must have the same columns as the original, and the
+ number of index levels must also be the same to render correctly.
+
+ Returns
+ -------
+ Styler
+
+ Notes
+ -----
+ The purpose of this method is to extend existing styled dataframes with other
+ metrics that may be useful but may not conform to the original's structure.
+ For example adding a sub total row, or displaying metrics such as means,
+ variance or counts.
+
+ Styles that are applied using the ``apply``, ``map``, ``apply_index``
+ and ``map_index``, and formatting applied with ``format`` and
+ ``format_index`` will be preserved.
+
+ .. warning::
+ Only the output methods ``to_html``, ``to_string`` and ``to_latex``
+ currently work with concatenated Stylers.
+
+ Other output methods, including ``to_excel``, **do not** work with
+ concatenated Stylers.
+
+ The following should be noted:
+
+ - ``table_styles``, ``table_attributes``, ``caption`` and ``uuid`` are all
+ inherited from the original Styler and not ``other``.
+ - hidden columns and hidden index levels will be inherited from the
+ original Styler
+ - ``css`` will be inherited from the original Styler, and the value of
+ keys ``data``, ``row_heading`` and ``row`` will be prepended with
+ ``foot0_``. If more concats are chained, their styles will be prepended
+ with ``foot1_``, ''foot_2'', etc., and if a concatenated style have
+ another concatanated style, the second style will be prepended with
+ ``foot{parent}_foot{child}_``.
+
+ A common use case is to concatenate user defined functions with
+ ``DataFrame.agg`` or with described statistics via ``DataFrame.describe``.
+ See examples.
+
+ Examples
+ --------
+ A common use case is adding totals rows, or otherwise, via methods calculated
+ in ``DataFrame.agg``.
+
+ >>> df = pd.DataFrame([[4, 6], [1, 9], [3, 4], [5, 5], [9, 6]],
+ ... columns=["Mike", "Jim"],
+ ... index=["Mon", "Tue", "Wed", "Thurs", "Fri"])
+ >>> styler = df.style.concat(df.agg(["sum"]).style) # doctest: +SKIP
+
+ .. figure:: ../../_static/style/footer_simple.png
+
+ Since the concatenated object is a Styler the existing functionality can be
+ used to conditionally format it as well as the original.
+
+ >>> descriptors = df.agg(["sum", "mean", lambda s: s.dtype])
+ >>> descriptors.index = ["Total", "Average", "dtype"]
+ >>> other = (descriptors.style
+ ... .highlight_max(axis=1, subset=(["Total", "Average"], slice(None)))
+ ... .format(subset=("Average", slice(None)), precision=2, decimal=",")
+ ... .map(lambda v: "font-weight: bold;"))
+ >>> styler = (df.style
+ ... .highlight_max(color="salmon")
+ ... .set_table_styles([{"selector": ".foot_row0",
+ ... "props": "border-top: 1px solid black;"}]))
+ >>> styler.concat(other) # doctest: +SKIP
+
+ .. figure:: ../../_static/style/footer_extended.png
+
+ When ``other`` has fewer index levels than the original Styler it is possible
+ to extend the index in ``other``, with placeholder levels.
+
+ >>> df = pd.DataFrame([[1], [2]],
+ ... index=pd.MultiIndex.from_product([[0], [1, 2]]))
+ >>> descriptors = df.agg(["sum"])
+ >>> descriptors.index = pd.MultiIndex.from_product([[""], descriptors.index])
+ >>> df.style.concat(descriptors.style) # doctest: +SKIP
+ """
+ if not isinstance(other, Styler):
+ raise TypeError("`other` must be of type `Styler`")
+ if not self.data.columns.equals(other.data.columns):
+ raise ValueError("`other.data` must have same columns as `Styler.data`")
+ if not self.data.index.nlevels == other.data.index.nlevels:
+ raise ValueError(
+ "number of index levels must be same in `other` "
+ "as in `Styler`. See documentation for suggestions."
+ )
+ self.concatenated.append(other)
+ return self
+
+ def _repr_html_(self) -> str | None:
+ """
+ Hooks into Jupyter notebook rich display system, which calls _repr_html_ by
+ default if an object is returned at the end of a cell.
+ """
+ if get_option("styler.render.repr") == "html":
+ return self.to_html()
+ return None
+
+ def _repr_latex_(self) -> str | None:
+ if get_option("styler.render.repr") == "latex":
+ return self.to_latex()
+ return None
+
+ def set_tooltips(
+ self,
+ ttips: DataFrame,
+ props: CSSProperties | None = None,
+ css_class: str | None = None,
+ ) -> Styler:
+ """
+ Set the DataFrame of strings on ``Styler`` generating ``:hover`` tooltips.
+
+ These string based tooltips are only applicable to ```` HTML elements,
+ and cannot be used for column or index headers.
+
+ .. versionadded:: 1.3.0
+
+ Parameters
+ ----------
+ ttips : DataFrame
+ DataFrame containing strings that will be translated to tooltips, mapped
+ by identical column and index values that must exist on the underlying
+ Styler data. None, NaN values, and empty strings will be ignored and
+ not affect the rendered HTML.
+ props : list-like or str, optional
+ List of (attr, value) tuples or a valid CSS string. If ``None`` adopts
+ the internal default values described in notes.
+ css_class : str, optional
+ Name of the tooltip class used in CSS, should conform to HTML standards.
+ Only useful if integrating tooltips with external CSS. If ``None`` uses the
+ internal default value 'pd-t'.
+
+ Returns
+ -------
+ Styler
+
+ Notes
+ -----
+ Tooltips are created by adding ` ` to each data cell
+ and then manipulating the table level CSS to attach pseudo hover and pseudo
+ after selectors to produce the required the results.
+
+ The default properties for the tooltip CSS class are:
+
+ - visibility: hidden
+ - position: absolute
+ - z-index: 1
+ - background-color: black
+ - color: white
+ - transform: translate(-20px, -20px)
+
+ The property 'visibility: hidden;' is a key prerequisite to the hover
+ functionality, and should always be included in any manual properties
+ specification, using the ``props`` argument.
+
+ Tooltips are not designed to be efficient, and can add large amounts of
+ additional HTML for larger tables, since they also require that ``cell_ids``
+ is forced to `True`.
+
+ Examples
+ --------
+ Basic application
+
+ >>> df = pd.DataFrame(data=[[0, 1], [2, 3]])
+ >>> ttips = pd.DataFrame(
+ ... data=[["Min", ""], [np.nan, "Max"]], columns=df.columns, index=df.index
+ ... )
+ >>> s = df.style.set_tooltips(ttips).to_html()
+
+ Optionally controlling the tooltip visual display
+
+ >>> df.style.set_tooltips(ttips, css_class='tt-add', props=[
+ ... ('visibility', 'hidden'),
+ ... ('position', 'absolute'),
+ ... ('z-index', 1)]) # doctest: +SKIP
+ >>> df.style.set_tooltips(ttips, css_class='tt-add',
+ ... props='visibility:hidden; position:absolute; z-index:1;')
+ ... # doctest: +SKIP
+ """
+ if not self.cell_ids:
+ # tooltips not optimised for individual cell check. requires reasonable
+ # redesign and more extensive code for a feature that might be rarely used.
+ raise NotImplementedError(
+ "Tooltips can only render with 'cell_ids' is True."
+ )
+ if not ttips.index.is_unique or not ttips.columns.is_unique:
+ raise KeyError(
+ "Tooltips render only if `ttips` has unique index and columns."
+ )
+ if self.tooltips is None: # create a default instance if necessary
+ self.tooltips = Tooltips()
+ self.tooltips.tt_data = ttips
+ if props:
+ self.tooltips.class_properties = props
+ if css_class:
+ self.tooltips.class_name = css_class
+
+ return self
+
+ @doc(
+ NDFrame.to_excel,
+ klass="Styler",
+ storage_options=_shared_docs["storage_options"],
+ storage_options_versionadded="1.5.0",
+ )
+ def to_excel(
+ self,
+ excel_writer: FilePath | WriteExcelBuffer | ExcelWriter,
+ sheet_name: str = "Sheet1",
+ na_rep: str = "",
+ float_format: str | None = None,
+ columns: Sequence[Hashable] | None = None,
+ header: Sequence[Hashable] | bool = True,
+ index: bool = True,
+ index_label: IndexLabel | None = None,
+ startrow: int = 0,
+ startcol: int = 0,
+ engine: str | None = None,
+ merge_cells: bool = True,
+ encoding: str | None = None,
+ inf_rep: str = "inf",
+ verbose: bool = True,
+ freeze_panes: tuple[int, int] | None = None,
+ storage_options: StorageOptions | None = None,
+ ) -> None:
+ from pandas.io.formats.excel import ExcelFormatter
+
+ formatter = ExcelFormatter(
+ self,
+ na_rep=na_rep,
+ cols=columns,
+ header=header,
+ float_format=float_format,
+ index=index,
+ index_label=index_label,
+ merge_cells=merge_cells,
+ inf_rep=inf_rep,
+ )
+ formatter.write(
+ excel_writer,
+ sheet_name=sheet_name,
+ startrow=startrow,
+ startcol=startcol,
+ freeze_panes=freeze_panes,
+ engine=engine,
+ storage_options=storage_options,
+ )
+
+ @overload
+ def to_latex(
+ self,
+ buf: FilePath | WriteBuffer[str],
+ *,
+ column_format: str | None = ...,
+ position: str | None = ...,
+ position_float: str | None = ...,
+ hrules: bool | None = ...,
+ clines: str | None = ...,
+ label: str | None = ...,
+ caption: str | tuple | None = ...,
+ sparse_index: bool | None = ...,
+ sparse_columns: bool | None = ...,
+ multirow_align: str | None = ...,
+ multicol_align: str | None = ...,
+ siunitx: bool = ...,
+ environment: str | None = ...,
+ encoding: str | None = ...,
+ convert_css: bool = ...,
+ ) -> None:
+ ...
+
+ @overload
+ def to_latex(
+ self,
+ buf: None = ...,
+ *,
+ column_format: str | None = ...,
+ position: str | None = ...,
+ position_float: str | None = ...,
+ hrules: bool | None = ...,
+ clines: str | None = ...,
+ label: str | None = ...,
+ caption: str | tuple | None = ...,
+ sparse_index: bool | None = ...,
+ sparse_columns: bool | None = ...,
+ multirow_align: str | None = ...,
+ multicol_align: str | None = ...,
+ siunitx: bool = ...,
+ environment: str | None = ...,
+ encoding: str | None = ...,
+ convert_css: bool = ...,
+ ) -> str:
+ ...
+
+ def to_latex(
+ self,
+ buf: FilePath | WriteBuffer[str] | None = None,
+ *,
+ column_format: str | None = None,
+ position: str | None = None,
+ position_float: str | None = None,
+ hrules: bool | None = None,
+ clines: str | None = None,
+ label: str | None = None,
+ caption: str | tuple | None = None,
+ sparse_index: bool | None = None,
+ sparse_columns: bool | None = None,
+ multirow_align: str | None = None,
+ multicol_align: str | None = None,
+ siunitx: bool = False,
+ environment: str | None = None,
+ encoding: str | None = None,
+ convert_css: bool = False,
+ ) -> str | None:
+ r"""
+ Write Styler to a file, buffer or string in LaTeX format.
+
+ .. versionadded:: 1.3.0
+
+ Parameters
+ ----------
+ buf : str, path object, file-like object, or None, default None
+ String, path object (implementing ``os.PathLike[str]``), or file-like
+ object implementing a string ``write()`` function. If None, the result is
+ returned as a string.
+ column_format : str, optional
+ The LaTeX column specification placed in location:
+
+ \\begin{tabular}{}
+
+ Defaults to 'l' for index and
+ non-numeric data columns, and, for numeric data columns,
+ to 'r' by default, or 'S' if ``siunitx`` is ``True``.
+ position : str, optional
+ The LaTeX positional argument (e.g. 'h!') for tables, placed in location:
+
+ ``\\begin{table}[]``.
+ position_float : {"centering", "raggedleft", "raggedright"}, optional
+ The LaTeX float command placed in location:
+
+ \\begin{table}[]
+
+ \\
+
+ Cannot be used if ``environment`` is "longtable".
+ hrules : bool
+ Set to `True` to add \\toprule, \\midrule and \\bottomrule from the
+ {booktabs} LaTeX package.
+ Defaults to ``pandas.options.styler.latex.hrules``, which is `False`.
+
+ .. versionchanged:: 1.4.0
+ clines : str, optional
+ Use to control adding \\cline commands for the index labels separation.
+ Possible values are:
+
+ - `None`: no cline commands are added (default).
+ - `"all;data"`: a cline is added for every index value extending the
+ width of the table, including data entries.
+ - `"all;index"`: as above with lines extending only the width of the
+ index entries.
+ - `"skip-last;data"`: a cline is added for each index value except the
+ last level (which is never sparsified), extending the widtn of the
+ table.
+ - `"skip-last;index"`: as above with lines extending only the width of the
+ index entries.
+
+ .. versionadded:: 1.4.0
+ label : str, optional
+ The LaTeX label included as: \\label{}.
+ This is used with \\ref{} in the main .tex file.
+ caption : str, tuple, optional
+ If string, the LaTeX table caption included as: \\caption{}.
+ If tuple, i.e ("full caption", "short caption"), the caption included
+ as: \\caption[]{}.
+ sparse_index : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each row.
+ Defaults to ``pandas.options.styler.sparse.index``, which is `True`.
+ sparse_columns : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each
+ column. Defaults to ``pandas.options.styler.sparse.columns``, which
+ is `True`.
+ multirow_align : {"c", "t", "b", "naive"}, optional
+ If sparsifying hierarchical MultiIndexes whether to align text centrally,
+ at the top or bottom using the multirow package. If not given defaults to
+ ``pandas.options.styler.latex.multirow_align``, which is `"c"`.
+ If "naive" is given renders without multirow.
+
+ .. versionchanged:: 1.4.0
+ multicol_align : {"r", "c", "l", "naive-l", "naive-r"}, optional
+ If sparsifying hierarchical MultiIndex columns whether to align text at
+ the left, centrally, or at the right. If not given defaults to
+ ``pandas.options.styler.latex.multicol_align``, which is "r".
+ If a naive option is given renders without multicol.
+ Pipe decorators can also be added to non-naive values to draw vertical
+ rules, e.g. "\|r" will draw a rule on the left side of right aligned merged
+ cells.
+
+ .. versionchanged:: 1.4.0
+ siunitx : bool, default False
+ Set to ``True`` to structure LaTeX compatible with the {siunitx} package.
+ environment : str, optional
+ If given, the environment that will replace 'table' in ``\\begin{table}``.
+ If 'longtable' is specified then a more suitable template is
+ rendered. If not given defaults to
+ ``pandas.options.styler.latex.environment``, which is `None`.
+
+ .. versionadded:: 1.4.0
+ encoding : str, optional
+ Character encoding setting. Defaults
+ to ``pandas.options.styler.render.encoding``, which is "utf-8".
+ convert_css : bool, default False
+ Convert simple cell-styles from CSS to LaTeX format. Any CSS not found in
+ conversion table is dropped. A style can be forced by adding option
+ `--latex`. See notes.
+
+ Returns
+ -------
+ str or None
+ If `buf` is None, returns the result as a string. Otherwise returns `None`.
+
+ See Also
+ --------
+ Styler.format: Format the text display value of cells.
+
+ Notes
+ -----
+ **Latex Packages**
+
+ For the following features we recommend the following LaTeX inclusions:
+
+ ===================== ==========================================================
+ Feature Inclusion
+ ===================== ==========================================================
+ sparse columns none: included within default {tabular} environment
+ sparse rows \\usepackage{multirow}
+ hrules \\usepackage{booktabs}
+ colors \\usepackage[table]{xcolor}
+ siunitx \\usepackage{siunitx}
+ bold (with siunitx) | \\usepackage{etoolbox}
+ | \\robustify\\bfseries
+ | \\sisetup{detect-all = true} *(within {document})*
+ italic (with siunitx) | \\usepackage{etoolbox}
+ | \\robustify\\itshape
+ | \\sisetup{detect-all = true} *(within {document})*
+ environment \\usepackage{longtable} if arg is "longtable"
+ | or any other relevant environment package
+ hyperlinks \\usepackage{hyperref}
+ ===================== ==========================================================
+
+ **Cell Styles**
+
+ LaTeX styling can only be rendered if the accompanying styling functions have
+ been constructed with appropriate LaTeX commands. All styling
+ functionality is built around the concept of a CSS ``(, )``
+ pair (see `Table Visualization <../../user_guide/style.ipynb>`_), and this
+ should be replaced by a LaTeX
+ ``(, )`` approach. Each cell will be styled individually
+ using nested LaTeX commands with their accompanied options.
+
+ For example the following code will highlight and bold a cell in HTML-CSS:
+
+ >>> df = pd.DataFrame([[1,2], [3,4]])
+ >>> s = df.style.highlight_max(axis=None,
+ ... props='background-color:red; font-weight:bold;')
+ >>> s.to_html() # doctest: +SKIP
+
+ The equivalent using LaTeX only commands is the following:
+
+ >>> s = df.style.highlight_max(axis=None,
+ ... props='cellcolor:{red}; bfseries: ;')
+ >>> s.to_latex() # doctest: +SKIP
+
+ Internally these structured LaTeX ``(, )`` pairs
+ are translated to the
+ ``display_value`` with the default structure:
+ ``\ ``.
+ Where there are multiple commands the latter is nested recursively, so that
+ the above example highlighted cell is rendered as
+ ``\cellcolor{red} \bfseries 4``.
+
+ Occasionally this format does not suit the applied command, or
+ combination of LaTeX packages that is in use, so additional flags can be
+ added to the ````, within the tuple, to result in different
+ positions of required braces (the **default** being the same as ``--nowrap``):
+
+ =================================== ============================================
+ Tuple Format Output Structure
+ =================================== ============================================
+ (,) \\
+ (, ``--nowrap``) \\
+ (, ``--rwrap``) \\{}
+ (, ``--wrap``) {\\ }
+ (, ``--lwrap``) {\\}
+ (, ``--dwrap``) {\\}{}
+ =================================== ============================================
+
+ For example the `textbf` command for font-weight
+ should always be used with `--rwrap` so ``('textbf', '--rwrap')`` will render a
+ working cell, wrapped with braces, as ``\textbf{}``.
+
+ A more comprehensive example is as follows:
+
+ >>> df = pd.DataFrame([[1, 2.2, "dogs"], [3, 4.4, "cats"], [2, 6.6, "cows"]],
+ ... index=["ix1", "ix2", "ix3"],
+ ... columns=["Integers", "Floats", "Strings"])
+ >>> s = df.style.highlight_max(
+ ... props='cellcolor:[HTML]{FFFF00}; color:{red};'
+ ... 'textit:--rwrap; textbf:--rwrap;'
+ ... )
+ >>> s.to_latex() # doctest: +SKIP
+
+ .. figure:: ../../_static/style/latex_1.png
+
+ **Table Styles**
+
+ Internally Styler uses its ``table_styles`` object to parse the
+ ``column_format``, ``position``, ``position_float``, and ``label``
+ input arguments. These arguments are added to table styles in the format:
+
+ .. code-block:: python
+
+ set_table_styles([
+ {"selector": "column_format", "props": f":{column_format};"},
+ {"selector": "position", "props": f":{position};"},
+ {"selector": "position_float", "props": f":{position_float};"},
+ {"selector": "label", "props": f":{{{label.replace(':','§')}}};"}
+ ], overwrite=False)
+
+ Exception is made for the ``hrules`` argument which, in fact, controls all three
+ commands: ``toprule``, ``bottomrule`` and ``midrule`` simultaneously. Instead of
+ setting ``hrules`` to ``True``, it is also possible to set each
+ individual rule definition, by manually setting the ``table_styles``,
+ for example below we set a regular ``toprule``, set an ``hline`` for
+ ``bottomrule`` and exclude the ``midrule``:
+
+ .. code-block:: python
+
+ set_table_styles([
+ {'selector': 'toprule', 'props': ':toprule;'},
+ {'selector': 'bottomrule', 'props': ':hline;'},
+ ], overwrite=False)
+
+ If other ``commands`` are added to table styles they will be detected, and
+ positioned immediately above the '\\begin{tabular}' command. For example to
+ add odd and even row coloring, from the {colortbl} package, in format
+ ``\rowcolors{1}{pink}{red}``, use:
+
+ .. code-block:: python
+
+ set_table_styles([
+ {'selector': 'rowcolors', 'props': ':{1}{pink}{red};'}
+ ], overwrite=False)
+
+ A more comprehensive example using these arguments is as follows:
+
+ >>> df.columns = pd.MultiIndex.from_tuples([
+ ... ("Numeric", "Integers"),
+ ... ("Numeric", "Floats"),
+ ... ("Non-Numeric", "Strings")
+ ... ])
+ >>> df.index = pd.MultiIndex.from_tuples([
+ ... ("L0", "ix1"), ("L0", "ix2"), ("L1", "ix3")
+ ... ])
+ >>> s = df.style.highlight_max(
+ ... props='cellcolor:[HTML]{FFFF00}; color:{red}; itshape:; bfseries:;'
+ ... )
+ >>> s.to_latex(
+ ... column_format="rrrrr", position="h", position_float="centering",
+ ... hrules=True, label="table:5", caption="Styled LaTeX Table",
+ ... multirow_align="t", multicol_align="r"
+ ... ) # doctest: +SKIP
+
+ .. figure:: ../../_static/style/latex_2.png
+
+ **Formatting**
+
+ To format values :meth:`Styler.format` should be used prior to calling
+ `Styler.to_latex`, as well as other methods such as :meth:`Styler.hide`
+ for example:
+
+ >>> s.clear()
+ >>> s.table_styles = []
+ >>> s.caption = None
+ >>> s.format({
+ ... ("Numeric", "Integers"): '\${}',
+ ... ("Numeric", "Floats"): '{:.3f}',
+ ... ("Non-Numeric", "Strings"): str.upper
+ ... }) # doctest: +SKIP
+ Numeric Non-Numeric
+ Integers Floats Strings
+ L0 ix1 $1 2.200 DOGS
+ ix2 $3 4.400 CATS
+ L1 ix3 $2 6.600 COWS
+
+ >>> s.to_latex() # doctest: +SKIP
+ \begin{tabular}{llrrl}
+ {} & {} & \multicolumn{2}{r}{Numeric} & {Non-Numeric} \\
+ {} & {} & {Integers} & {Floats} & {Strings} \\
+ \multirow[c]{2}{*}{L0} & ix1 & \\$1 & 2.200 & DOGS \\
+ & ix2 & \$3 & 4.400 & CATS \\
+ L1 & ix3 & \$2 & 6.600 & COWS \\
+ \end{tabular}
+
+ **CSS Conversion**
+
+ This method can convert a Styler constructured with HTML-CSS to LaTeX using
+ the following limited conversions.
+
+ ================== ==================== ============= ==========================
+ CSS Attribute CSS value LaTeX Command LaTeX Options
+ ================== ==================== ============= ==========================
+ font-weight | bold | bfseries
+ | bolder | bfseries
+ font-style | italic | itshape
+ | oblique | slshape
+ background-color | red cellcolor | {red}--lwrap
+ | #fe01ea | [HTML]{FE01EA}--lwrap
+ | #f0e | [HTML]{FF00EE}--lwrap
+ | rgb(128,255,0) | [rgb]{0.5,1,0}--lwrap
+ | rgba(128,0,0,0.5) | [rgb]{0.5,0,0}--lwrap
+ | rgb(25%,255,50%) | [rgb]{0.25,1,0.5}--lwrap
+ color | red color | {red}
+ | #fe01ea | [HTML]{FE01EA}
+ | #f0e | [HTML]{FF00EE}
+ | rgb(128,255,0) | [rgb]{0.5,1,0}
+ | rgba(128,0,0,0.5) | [rgb]{0.5,0,0}
+ | rgb(25%,255,50%) | [rgb]{0.25,1,0.5}
+ ================== ==================== ============= ==========================
+
+ It is also possible to add user-defined LaTeX only styles to a HTML-CSS Styler
+ using the ``--latex`` flag, and to add LaTeX parsing options that the
+ converter will detect within a CSS-comment.
+
+ >>> df = pd.DataFrame([[1]])
+ >>> df.style.set_properties(
+ ... **{"font-weight": "bold /* --dwrap */", "Huge": "--latex--rwrap"}
+ ... ).to_latex(convert_css=True) # doctest: +SKIP
+ \begin{tabular}{lr}
+ {} & {0} \\
+ 0 & {\bfseries}{\Huge{1}} \\
+ \end{tabular}
+
+ Examples
+ --------
+ Below we give a complete step by step example adding some advanced features
+ and noting some common gotchas.
+
+ First we create the DataFrame and Styler as usual, including MultiIndex rows
+ and columns, which allow for more advanced formatting options:
+
+ >>> cidx = pd.MultiIndex.from_arrays([
+ ... ["Equity", "Equity", "Equity", "Equity",
+ ... "Stats", "Stats", "Stats", "Stats", "Rating"],
+ ... ["Energy", "Energy", "Consumer", "Consumer", "", "", "", "", ""],
+ ... ["BP", "Shell", "H&M", "Unilever",
+ ... "Std Dev", "Variance", "52w High", "52w Low", ""]
+ ... ])
+ >>> iidx = pd.MultiIndex.from_arrays([
+ ... ["Equity", "Equity", "Equity", "Equity"],
+ ... ["Energy", "Energy", "Consumer", "Consumer"],
+ ... ["BP", "Shell", "H&M", "Unilever"]
+ ... ])
+ >>> styler = pd.DataFrame([
+ ... [1, 0.8, 0.66, 0.72, 32.1678, 32.1678**2, 335.12, 240.89, "Buy"],
+ ... [0.8, 1.0, 0.69, 0.79, 1.876, 1.876**2, 14.12, 19.78, "Hold"],
+ ... [0.66, 0.69, 1.0, 0.86, 7, 7**2, 210.9, 140.6, "Buy"],
+ ... [0.72, 0.79, 0.86, 1.0, 213.76, 213.76**2, 2807, 3678, "Sell"],
+ ... ], columns=cidx, index=iidx).style
+
+ Second we will format the display and, since our table is quite wide, will
+ hide the repeated level-0 of the index:
+
+ >>> (styler.format(subset="Equity", precision=2)
+ ... .format(subset="Stats", precision=1, thousands=",")
+ ... .format(subset="Rating", formatter=str.upper)
+ ... .format_index(escape="latex", axis=1)
+ ... .format_index(escape="latex", axis=0)
+ ... .hide(level=0, axis=0)) # doctest: +SKIP
+
+ Note that one of the string entries of the index and column headers is "H&M".
+ Without applying the `escape="latex"` option to the `format_index` method the
+ resultant LaTeX will fail to render, and the error returned is quite
+ difficult to debug. Using the appropriate escape the "&" is converted to "\\&".
+
+ Thirdly we will apply some (CSS-HTML) styles to our object. We will use a
+ builtin method and also define our own method to highlight the stock
+ recommendation:
+
+ >>> def rating_color(v):
+ ... if v == "Buy": color = "#33ff85"
+ ... elif v == "Sell": color = "#ff5933"
+ ... else: color = "#ffdd33"
+ ... return f"color: {color}; font-weight: bold;"
+ >>> (styler.background_gradient(cmap="inferno", subset="Equity", vmin=0, vmax=1)
+ ... .map(rating_color, subset="Rating")) # doctest: +SKIP
+
+ All the above styles will work with HTML (see below) and LaTeX upon conversion:
+
+ .. figure:: ../../_static/style/latex_stocks_html.png
+
+ However, we finally want to add one LaTeX only style
+ (from the {graphicx} package), that is not easy to convert from CSS and
+ pandas does not support it. Notice the `--latex` flag used here,
+ as well as `--rwrap` to ensure this is formatted correctly and
+ not ignored upon conversion.
+
+ >>> styler.map_index(
+ ... lambda v: "rotatebox:{45}--rwrap--latex;", level=2, axis=1
+ ... ) # doctest: +SKIP
+
+ Finally we render our LaTeX adding in other options as required:
+
+ >>> styler.to_latex(
+ ... caption="Selected stock correlation and simple statistics.",
+ ... clines="skip-last;data",
+ ... convert_css=True,
+ ... position_float="centering",
+ ... multicol_align="|c|",
+ ... hrules=True,
+ ... ) # doctest: +SKIP
+ \begin{table}
+ \centering
+ \caption{Selected stock correlation and simple statistics.}
+ \begin{tabular}{llrrrrrrrrl}
+ \toprule
+ & & \multicolumn{4}{|c|}{Equity} & \multicolumn{4}{|c|}{Stats} & Rating \\
+ & & \multicolumn{2}{|c|}{Energy} & \multicolumn{2}{|c|}{Consumer} &
+ \multicolumn{4}{|c|}{} & \\
+ & & \rotatebox{45}{BP} & \rotatebox{45}{Shell} & \rotatebox{45}{H\&M} &
+ \rotatebox{45}{Unilever} & \rotatebox{45}{Std Dev} & \rotatebox{45}{Variance} &
+ \rotatebox{45}{52w High} & \rotatebox{45}{52w Low} & \rotatebox{45}{} \\
+ \midrule
+ \multirow[c]{2}{*}{Energy} & BP & {\cellcolor[HTML]{FCFFA4}}
+ \color[HTML]{000000} 1.00 & {\cellcolor[HTML]{FCA50A}} \color[HTML]{000000}
+ 0.80 & {\cellcolor[HTML]{EB6628}} \color[HTML]{F1F1F1} 0.66 &
+ {\cellcolor[HTML]{F68013}} \color[HTML]{F1F1F1} 0.72 & 32.2 & 1,034.8 & 335.1
+ & 240.9 & \color[HTML]{33FF85} \bfseries BUY \\
+ & Shell & {\cellcolor[HTML]{FCA50A}} \color[HTML]{000000} 0.80 &
+ {\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 &
+ {\cellcolor[HTML]{F1731D}} \color[HTML]{F1F1F1} 0.69 &
+ {\cellcolor[HTML]{FCA108}} \color[HTML]{000000} 0.79 & 1.9 & 3.5 & 14.1 &
+ 19.8 & \color[HTML]{FFDD33} \bfseries HOLD \\
+ \cline{1-11}
+ \multirow[c]{2}{*}{Consumer} & H\&M & {\cellcolor[HTML]{EB6628}}
+ \color[HTML]{F1F1F1} 0.66 & {\cellcolor[HTML]{F1731D}} \color[HTML]{F1F1F1}
+ 0.69 & {\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 &
+ {\cellcolor[HTML]{FAC42A}} \color[HTML]{000000} 0.86 & 7.0 & 49.0 & 210.9 &
+ 140.6 & \color[HTML]{33FF85} \bfseries BUY \\
+ & Unilever & {\cellcolor[HTML]{F68013}} \color[HTML]{F1F1F1} 0.72 &
+ {\cellcolor[HTML]{FCA108}} \color[HTML]{000000} 0.79 &
+ {\cellcolor[HTML]{FAC42A}} \color[HTML]{000000} 0.86 &
+ {\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 & 213.8 & 45,693.3 &
+ 2,807.0 & 3,678.0 & \color[HTML]{FF5933} \bfseries SELL \\
+ \cline{1-11}
+ \bottomrule
+ \end{tabular}
+ \end{table}
+
+ .. figure:: ../../_static/style/latex_stocks.png
+ """
+ obj = self._copy(deepcopy=True) # manipulate table_styles on obj, not self
+
+ table_selectors = (
+ [style["selector"] for style in self.table_styles]
+ if self.table_styles is not None
+ else []
+ )
+
+ if column_format is not None:
+ # add more recent setting to table_styles
+ obj.set_table_styles(
+ [{"selector": "column_format", "props": f":{column_format}"}],
+ overwrite=False,
+ )
+ elif "column_format" in table_selectors:
+ pass # adopt what has been previously set in table_styles
+ else:
+ # create a default: set float, complex, int cols to 'r' ('S'), index to 'l'
+ _original_columns = self.data.columns
+ self.data.columns = RangeIndex(stop=len(self.data.columns))
+ numeric_cols = self.data._get_numeric_data().columns.to_list()
+ self.data.columns = _original_columns
+ column_format = ""
+ for level in range(self.index.nlevels):
+ column_format += "" if self.hide_index_[level] else "l"
+ for ci, _ in enumerate(self.data.columns):
+ if ci not in self.hidden_columns:
+ column_format += (
+ ("r" if not siunitx else "S") if ci in numeric_cols else "l"
+ )
+ obj.set_table_styles(
+ [{"selector": "column_format", "props": f":{column_format}"}],
+ overwrite=False,
+ )
+
+ if position:
+ obj.set_table_styles(
+ [{"selector": "position", "props": f":{position}"}],
+ overwrite=False,
+ )
+
+ if position_float:
+ if environment == "longtable":
+ raise ValueError(
+ "`position_float` cannot be used in 'longtable' `environment`"
+ )
+ if position_float not in ["raggedright", "raggedleft", "centering"]:
+ raise ValueError(
+ f"`position_float` should be one of "
+ f"'raggedright', 'raggedleft', 'centering', "
+ f"got: '{position_float}'"
+ )
+ obj.set_table_styles(
+ [{"selector": "position_float", "props": f":{position_float}"}],
+ overwrite=False,
+ )
+
+ hrules = get_option("styler.latex.hrules") if hrules is None else hrules
+ if hrules:
+ obj.set_table_styles(
+ [
+ {"selector": "toprule", "props": ":toprule"},
+ {"selector": "midrule", "props": ":midrule"},
+ {"selector": "bottomrule", "props": ":bottomrule"},
+ ],
+ overwrite=False,
+ )
+
+ if label:
+ obj.set_table_styles(
+ [{"selector": "label", "props": f":{{{label.replace(':', '§')}}}"}],
+ overwrite=False,
+ )
+
+ if caption:
+ obj.set_caption(caption)
+
+ if sparse_index is None:
+ sparse_index = get_option("styler.sparse.index")
+ if sparse_columns is None:
+ sparse_columns = get_option("styler.sparse.columns")
+ environment = environment or get_option("styler.latex.environment")
+ multicol_align = multicol_align or get_option("styler.latex.multicol_align")
+ multirow_align = multirow_align or get_option("styler.latex.multirow_align")
+ latex = obj._render_latex(
+ sparse_index=sparse_index,
+ sparse_columns=sparse_columns,
+ multirow_align=multirow_align,
+ multicol_align=multicol_align,
+ environment=environment,
+ convert_css=convert_css,
+ siunitx=siunitx,
+ clines=clines,
+ )
+
+ encoding = (
+ (encoding or get_option("styler.render.encoding"))
+ if isinstance(buf, str) # i.e. a filepath
+ else encoding
+ )
+ return save_to_buffer(latex, buf=buf, encoding=encoding)
+
+ @overload
+ def to_html(
+ self,
+ buf: FilePath | WriteBuffer[str],
+ *,
+ table_uuid: str | None = ...,
+ table_attributes: str | None = ...,
+ sparse_index: bool | None = ...,
+ sparse_columns: bool | None = ...,
+ bold_headers: bool = ...,
+ caption: str | None = ...,
+ max_rows: int | None = ...,
+ max_columns: int | None = ...,
+ encoding: str | None = ...,
+ doctype_html: bool = ...,
+ exclude_styles: bool = ...,
+ **kwargs,
+ ) -> None:
+ ...
+
+ @overload
+ def to_html(
+ self,
+ buf: None = ...,
+ *,
+ table_uuid: str | None = ...,
+ table_attributes: str | None = ...,
+ sparse_index: bool | None = ...,
+ sparse_columns: bool | None = ...,
+ bold_headers: bool = ...,
+ caption: str | None = ...,
+ max_rows: int | None = ...,
+ max_columns: int | None = ...,
+ encoding: str | None = ...,
+ doctype_html: bool = ...,
+ exclude_styles: bool = ...,
+ **kwargs,
+ ) -> str:
+ ...
+
+ @Substitution(buf=buffering_args, encoding=encoding_args)
+ def to_html(
+ self,
+ buf: FilePath | WriteBuffer[str] | None = None,
+ *,
+ table_uuid: str | None = None,
+ table_attributes: str | None = None,
+ sparse_index: bool | None = None,
+ sparse_columns: bool | None = None,
+ bold_headers: bool = False,
+ caption: str | None = None,
+ max_rows: int | None = None,
+ max_columns: int | None = None,
+ encoding: str | None = None,
+ doctype_html: bool = False,
+ exclude_styles: bool = False,
+ **kwargs,
+ ) -> str | None:
+ """
+ Write Styler to a file, buffer or string in HTML-CSS format.
+
+ .. versionadded:: 1.3.0
+
+ Parameters
+ ----------
+ %(buf)s
+ table_uuid : str, optional
+ Id attribute assigned to the HTML element in the format:
+
+ ````
+
+ If not given uses Styler's initially assigned value.
+ table_attributes : str, optional
+ Attributes to assign within the `` HTML element in the format:
+
+ `` >``
+
+ If not given defaults to Styler's preexisting value.
+ sparse_index : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each row.
+ Defaults to ``pandas.options.styler.sparse.index`` value.
+
+ .. versionadded:: 1.4.0
+ sparse_columns : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each
+ column. Defaults to ``pandas.options.styler.sparse.columns`` value.
+
+ .. versionadded:: 1.4.0
+ bold_headers : bool, optional
+ Adds "font-weight: bold;" as a CSS property to table style header cells.
+
+ .. versionadded:: 1.4.0
+ caption : str, optional
+ Set, or overwrite, the caption on Styler before rendering.
+
+ .. versionadded:: 1.4.0
+ max_rows : int, optional
+ The maximum number of rows that will be rendered. Defaults to
+ ``pandas.options.styler.render.max_rows/max_columns``.
+
+ .. versionadded:: 1.4.0
+ max_columns : int, optional
+ The maximum number of columns that will be rendered. Defaults to
+ ``pandas.options.styler.render.max_columns``, which is None.
+
+ Rows and columns may be reduced if the number of total elements is
+ large. This value is set to ``pandas.options.styler.render.max_elements``,
+ which is 262144 (18 bit browser rendering).
+
+ .. versionadded:: 1.4.0
+ %(encoding)s
+ doctype_html : bool, default False
+ Whether to output a fully structured HTML file including all
+ HTML elements, or just the core ``
+
+
+
+
+ A
+ B
+
+ ...
+ """
+ obj = self._copy(deepcopy=True) # manipulate table_styles on obj, not self
+
+ if table_uuid:
+ obj.set_uuid(table_uuid)
+
+ if table_attributes:
+ obj.set_table_attributes(table_attributes)
+
+ if sparse_index is None:
+ sparse_index = get_option("styler.sparse.index")
+ if sparse_columns is None:
+ sparse_columns = get_option("styler.sparse.columns")
+
+ if bold_headers:
+ obj.set_table_styles(
+ [{"selector": "th", "props": "font-weight: bold;"}], overwrite=False
+ )
+
+ if caption is not None:
+ obj.set_caption(caption)
+
+ # Build HTML string..
+ html = obj._render_html(
+ sparse_index=sparse_index,
+ sparse_columns=sparse_columns,
+ max_rows=max_rows,
+ max_cols=max_columns,
+ exclude_styles=exclude_styles,
+ encoding=encoding or get_option("styler.render.encoding"),
+ doctype_html=doctype_html,
+ **kwargs,
+ )
+
+ return save_to_buffer(
+ html, buf=buf, encoding=(encoding if buf is not None else None)
+ )
+
+ @overload
+ def to_string(
+ self,
+ buf: FilePath | WriteBuffer[str],
+ *,
+ encoding: str | None = ...,
+ sparse_index: bool | None = ...,
+ sparse_columns: bool | None = ...,
+ max_rows: int | None = ...,
+ max_columns: int | None = ...,
+ delimiter: str = ...,
+ ) -> None:
+ ...
+
+ @overload
+ def to_string(
+ self,
+ buf: None = ...,
+ *,
+ encoding: str | None = ...,
+ sparse_index: bool | None = ...,
+ sparse_columns: bool | None = ...,
+ max_rows: int | None = ...,
+ max_columns: int | None = ...,
+ delimiter: str = ...,
+ ) -> str:
+ ...
+
+ @Substitution(buf=buffering_args, encoding=encoding_args)
+ def to_string(
+ self,
+ buf: FilePath | WriteBuffer[str] | None = None,
+ *,
+ encoding: str | None = None,
+ sparse_index: bool | None = None,
+ sparse_columns: bool | None = None,
+ max_rows: int | None = None,
+ max_columns: int | None = None,
+ delimiter: str = " ",
+ ) -> str | None:
+ """
+ Write Styler to a file, buffer or string in text format.
+
+ .. versionadded:: 1.5.0
+
+ Parameters
+ ----------
+ %(buf)s
+ %(encoding)s
+ sparse_index : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each row.
+ Defaults to ``pandas.options.styler.sparse.index`` value.
+ sparse_columns : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each
+ column. Defaults to ``pandas.options.styler.sparse.columns`` value.
+ max_rows : int, optional
+ The maximum number of rows that will be rendered. Defaults to
+ ``pandas.options.styler.render.max_rows``, which is None.
+ max_columns : int, optional
+ The maximum number of columns that will be rendered. Defaults to
+ ``pandas.options.styler.render.max_columns``, which is None.
+
+ Rows and columns may be reduced if the number of total elements is
+ large. This value is set to ``pandas.options.styler.render.max_elements``,
+ which is 262144 (18 bit browser rendering).
+ delimiter : str, default single space
+ The separator between data elements.
+
+ Returns
+ -------
+ str or None
+ If `buf` is None, returns the result as a string. Otherwise returns `None`.
+
+ Examples
+ --------
+ >>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
+ >>> df.style.to_string()
+ ' A B\\n0 1 3\\n1 2 4\\n'
+ """
+ obj = self._copy(deepcopy=True)
+
+ if sparse_index is None:
+ sparse_index = get_option("styler.sparse.index")
+ if sparse_columns is None:
+ sparse_columns = get_option("styler.sparse.columns")
+
+ text = obj._render_string(
+ sparse_columns=sparse_columns,
+ sparse_index=sparse_index,
+ max_rows=max_rows,
+ max_cols=max_columns,
+ delimiter=delimiter,
+ )
+ return save_to_buffer(
+ text, buf=buf, encoding=(encoding if buf is not None else None)
+ )
+
+ def set_td_classes(self, classes: DataFrame) -> Styler:
+ """
+ Set the ``class`` attribute of ```` HTML elements.
+
+ Parameters
+ ----------
+ classes : DataFrame
+ DataFrame containing strings that will be translated to CSS classes,
+ mapped by identical column and index key values that must exist on the
+ underlying Styler data. None, NaN values, and empty strings will
+ be ignored and not affect the rendered HTML.
+
+ Returns
+ -------
+ Styler
+
+ See Also
+ --------
+ Styler.set_table_styles: Set the table styles included within the ``'
+ ''
+ ' '
+ ' 0 '
+ ' '
+ ' '
+ ' 1 '
+ ' '
+ '
'
+ """
+ if not classes.index.is_unique or not classes.columns.is_unique:
+ raise KeyError(
+ "Classes render only if `classes` has unique index and columns."
+ )
+ classes = classes.reindex_like(self.data)
+
+ for r, row_tup in enumerate(classes.itertuples()):
+ for c, value in enumerate(row_tup[1:]):
+ if not (pd.isna(value) or value == ""):
+ self.cell_context[(r, c)] = str(value)
+
+ return self
+
+ def _update_ctx(self, attrs: DataFrame) -> None:
+ """
+ Update the state of the ``Styler`` for data cells.
+
+ Collects a mapping of {index_label: [('', ''), ..]}.
+
+ Parameters
+ ----------
+ attrs : DataFrame
+ should contain strings of ': ;: '
+ Whitespace shouldn't matter and the final trailing ';' shouldn't
+ matter.
+ """
+ if not self.index.is_unique or not self.columns.is_unique:
+ raise KeyError(
+ "`Styler.apply` and `.map` are not compatible "
+ "with non-unique index or columns."
+ )
+
+ for cn in attrs.columns:
+ j = self.columns.get_loc(cn)
+ ser = attrs[cn]
+ for rn, c in ser.items():
+ if not c or pd.isna(c):
+ continue
+ css_list = maybe_convert_css_to_tuples(c)
+ i = self.index.get_loc(rn)
+ self.ctx[(i, j)].extend(css_list)
+
+ def _update_ctx_header(self, attrs: DataFrame, axis: AxisInt) -> None:
+ """
+ Update the state of the ``Styler`` for header cells.
+
+ Collects a mapping of {index_label: [('', ''), ..]}.
+
+ Parameters
+ ----------
+ attrs : Series
+ Should contain strings of ': ;: ', and an
+ integer index.
+ Whitespace shouldn't matter and the final trailing ';' shouldn't
+ matter.
+ axis : int
+ Identifies whether the ctx object being updated is the index or columns
+ """
+ for j in attrs.columns:
+ ser = attrs[j]
+ for i, c in ser.items():
+ if not c:
+ continue
+ css_list = maybe_convert_css_to_tuples(c)
+ if axis == 0:
+ self.ctx_index[(i, j)].extend(css_list)
+ else:
+ self.ctx_columns[(j, i)].extend(css_list)
+
+ def _copy(self, deepcopy: bool = False) -> Styler:
+ """
+ Copies a Styler, allowing for deepcopy or shallow copy
+
+ Copying a Styler aims to recreate a new Styler object which contains the same
+ data and styles as the original.
+
+ Data dependent attributes [copied and NOT exported]:
+ - formatting (._display_funcs)
+ - hidden index values or column values (.hidden_rows, .hidden_columns)
+ - tooltips
+ - cell_context (cell css classes)
+ - ctx (cell css styles)
+ - caption
+ - concatenated stylers
+
+ Non-data dependent attributes [copied and exported]:
+ - css
+ - hidden index state and hidden columns state (.hide_index_, .hide_columns_)
+ - table_attributes
+ - table_styles
+ - applied styles (_todo)
+
+ """
+ # GH 40675, 52728
+ styler = type(self)(
+ self.data, # populates attributes 'data', 'columns', 'index' as shallow
+ )
+ shallow = [ # simple string or boolean immutables
+ "hide_index_",
+ "hide_columns_",
+ "hide_column_names",
+ "hide_index_names",
+ "table_attributes",
+ "cell_ids",
+ "caption",
+ "uuid",
+ "uuid_len",
+ "template_latex", # also copy templates if these have been customised
+ "template_html_style",
+ "template_html_table",
+ "template_html",
+ ]
+ deep = [ # nested lists or dicts
+ "css",
+ "concatenated",
+ "_display_funcs",
+ "_display_funcs_index",
+ "_display_funcs_columns",
+ "hidden_rows",
+ "hidden_columns",
+ "ctx",
+ "ctx_index",
+ "ctx_columns",
+ "cell_context",
+ "_todo",
+ "table_styles",
+ "tooltips",
+ ]
+
+ for attr in shallow:
+ setattr(styler, attr, getattr(self, attr))
+
+ for attr in deep:
+ val = getattr(self, attr)
+ setattr(styler, attr, copy.deepcopy(val) if deepcopy else val)
+
+ return styler
+
+ def __copy__(self) -> Styler:
+ return self._copy(deepcopy=False)
+
+ def __deepcopy__(self, memo) -> Styler:
+ return self._copy(deepcopy=True)
+
+ def clear(self) -> None:
+ """
+ Reset the ``Styler``, removing any previously applied styles.
+
+ Returns None.
+
+ Examples
+ --------
+ >>> df = pd.DataFrame({'A': [1, 2], 'B': [3, np.nan]})
+
+ After any added style:
+
+ >>> df.style.highlight_null(color='yellow') # doctest: +SKIP
+
+ Remove it with:
+
+ >>> df.style.clear() # doctest: +SKIP
+
+ Please see:
+ `Table Visualization <../../user_guide/style.ipynb>`_ for more examples.
+ """
+ # create default GH 40675
+ clean_copy = Styler(self.data, uuid=self.uuid)
+ clean_attrs = [a for a in clean_copy.__dict__ if not callable(a)]
+ self_attrs = [a for a in self.__dict__ if not callable(a)] # maybe more attrs
+ for attr in clean_attrs:
+ setattr(self, attr, getattr(clean_copy, attr))
+ for attr in set(self_attrs).difference(clean_attrs):
+ delattr(self, attr)
+
+ def _apply(
+ self,
+ func: Callable,
+ axis: Axis | None = 0,
+ subset: Subset | None = None,
+ **kwargs,
+ ) -> Styler:
+ subset = slice(None) if subset is None else subset
+ subset = non_reducing_slice(subset)
+ data = self.data.loc[subset]
+ if data.empty:
+ result = DataFrame()
+ elif axis is None:
+ result = func(data, **kwargs)
+ if not isinstance(result, DataFrame):
+ if not isinstance(result, np.ndarray):
+ raise TypeError(
+ f"Function {repr(func)} must return a DataFrame or ndarray "
+ f"when passed to `Styler.apply` with axis=None"
+ )
+ if data.shape != result.shape:
+ raise ValueError(
+ f"Function {repr(func)} returned ndarray with wrong shape.\n"
+ f"Result has shape: {result.shape}\n"
+ f"Expected shape: {data.shape}"
+ )
+ result = DataFrame(result, index=data.index, columns=data.columns)
+ else:
+ axis = self.data._get_axis_number(axis)
+ if axis == 0:
+ result = data.apply(func, axis=0, **kwargs)
+ else:
+ result = data.T.apply(func, axis=0, **kwargs).T # see GH 42005
+
+ if isinstance(result, Series):
+ raise ValueError(
+ f"Function {repr(func)} resulted in the apply method collapsing to a "
+ f"Series.\nUsually, this is the result of the function returning a "
+ f"single value, instead of list-like."
+ )
+ msg = (
+ f"Function {repr(func)} created invalid {{0}} labels.\nUsually, this is "
+ f"the result of the function returning a "
+ f"{'Series' if axis is not None else 'DataFrame'} which contains invalid "
+ f"labels, or returning an incorrectly shaped, list-like object which "
+ f"cannot be mapped to labels, possibly due to applying the function along "
+ f"the wrong axis.\n"
+ f"Result {{0}} has shape: {{1}}\n"
+ f"Expected {{0}} shape: {{2}}"
+ )
+ if not all(result.index.isin(data.index)):
+ raise ValueError(msg.format("index", result.index.shape, data.index.shape))
+ if not all(result.columns.isin(data.columns)):
+ raise ValueError(
+ msg.format("columns", result.columns.shape, data.columns.shape)
+ )
+ self._update_ctx(result)
+ return self
+
+ @Substitution(subset=subset_args)
+ def apply(
+ self,
+ func: Callable,
+ axis: Axis | None = 0,
+ subset: Subset | None = None,
+ **kwargs,
+ ) -> Styler:
+ """
+ Apply a CSS-styling function column-wise, row-wise, or table-wise.
+
+ Updates the HTML representation with the result.
+
+ Parameters
+ ----------
+ func : function
+ ``func`` should take a Series if ``axis`` in [0,1] and return a list-like
+ object of same length, or a Series, not necessarily of same length, with
+ valid index labels considering ``subset``.
+ ``func`` should take a DataFrame if ``axis`` is ``None`` and return either
+ an ndarray with the same shape or a DataFrame, not necessarily of the same
+ shape, with valid index and columns labels considering ``subset``.
+
+ .. versionchanged:: 1.3.0
+
+ .. versionchanged:: 1.4.0
+
+ axis : {0 or 'index', 1 or 'columns', None}, default 0
+ Apply to each column (``axis=0`` or ``'index'``), to each row
+ (``axis=1`` or ``'columns'``), or to the entire DataFrame at once
+ with ``axis=None``.
+ %(subset)s
+ **kwargs : dict
+ Pass along to ``func``.
+
+ Returns
+ -------
+ Styler
+
+ See Also
+ --------
+ Styler.map_index: Apply a CSS-styling function to headers elementwise.
+ Styler.apply_index: Apply a CSS-styling function to headers level-wise.
+ Styler.map: Apply a CSS-styling function elementwise.
+
+ Notes
+ -----
+ The elements of the output of ``func`` should be CSS styles as strings, in the
+ format 'attribute: value; attribute2: value2; ...' or,
+ if nothing is to be applied to that element, an empty string or ``None``.
+
+ This is similar to ``DataFrame.apply``, except that ``axis=None``
+ applies the function to the entire DataFrame at once,
+ rather than column-wise or row-wise.
+
+ Examples
+ --------
+ >>> def highlight_max(x, color):
+ ... return np.where(x == np.nanmax(x.to_numpy()), f"color: {color};", None)
+ >>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
+ >>> df.style.apply(highlight_max, color='red') # doctest: +SKIP
+ >>> df.style.apply(highlight_max, color='blue', axis=1) # doctest: +SKIP
+ >>> df.style.apply(highlight_max, color='green', axis=None) # doctest: +SKIP
+
+ Using ``subset`` to restrict application to a single column or multiple columns
+
+ >>> df.style.apply(highlight_max, color='red', subset="A")
+ ... # doctest: +SKIP
+ >>> df.style.apply(highlight_max, color='red', subset=["A", "B"])
+ ... # doctest: +SKIP
+
+ Using a 2d input to ``subset`` to select rows in addition to columns
+
+ >>> df.style.apply(highlight_max, color='red', subset=([0, 1, 2], slice(None)))
+ ... # doctest: +SKIP
+ >>> df.style.apply(highlight_max, color='red', subset=(slice(0, 5, 2), "A"))
+ ... # doctest: +SKIP
+
+ Using a function which returns a Series / DataFrame of unequal length but
+ containing valid index labels
+
+ >>> df = pd.DataFrame([[1, 2], [3, 4], [4, 6]], index=["A1", "A2", "Total"])
+ >>> total_style = pd.Series("font-weight: bold;", index=["Total"])
+ >>> df.style.apply(lambda s: total_style) # doctest: +SKIP
+
+ See `Table Visualization <../../user_guide/style.ipynb>`_ user guide for
+ more details.
+ """
+ self._todo.append(
+ (lambda instance: getattr(instance, "_apply"), (func, axis, subset), kwargs)
+ )
+ return self
+
+ def _apply_index(
+ self,
+ func: Callable,
+ axis: Axis = 0,
+ level: Level | list[Level] | None = None,
+ method: str = "apply",
+ **kwargs,
+ ) -> Styler:
+ axis = self.data._get_axis_number(axis)
+ obj = self.index if axis == 0 else self.columns
+
+ levels_ = refactor_levels(level, obj)
+ data = DataFrame(obj.to_list()).loc[:, levels_]
+
+ if method == "apply":
+ result = data.apply(func, axis=0, **kwargs)
+ elif method == "map":
+ result = data.map(func, **kwargs)
+
+ self._update_ctx_header(result, axis)
+ return self
+
+ @doc(
+ this="apply",
+ wise="level-wise",
+ alt="map",
+ altwise="elementwise",
+ func="take a Series and return a string array of the same length",
+ input_note="the index as a Series, if an Index, or a level of a MultiIndex",
+ output_note="an identically sized array of CSS styles as strings",
+ var="s",
+ ret='np.where(s == "B", "background-color: yellow;", "")',
+ ret2='["background-color: yellow;" if "x" in v else "" for v in s]',
+ )
+ def apply_index(
+ self,
+ func: Callable,
+ axis: AxisInt | str = 0,
+ level: Level | list[Level] | None = None,
+ **kwargs,
+ ) -> Styler:
+ """
+ Apply a CSS-styling function to the index or column headers, {wise}.
+
+ Updates the HTML representation with the result.
+
+ .. versionadded:: 1.4.0
+
+ .. versionadded:: 2.1.0
+ Styler.applymap_index was deprecated and renamed to Styler.map_index.
+
+ Parameters
+ ----------
+ func : function
+ ``func`` should {func}.
+ axis : {{0, 1, "index", "columns"}}
+ The headers over which to apply the function.
+ level : int, str, list, optional
+ If index is MultiIndex the level(s) over which to apply the function.
+ **kwargs : dict
+ Pass along to ``func``.
+
+ Returns
+ -------
+ Styler
+
+ See Also
+ --------
+ Styler.{alt}_index: Apply a CSS-styling function to headers {altwise}.
+ Styler.apply: Apply a CSS-styling function column-wise, row-wise, or table-wise.
+ Styler.map: Apply a CSS-styling function elementwise.
+
+ Notes
+ -----
+ Each input to ``func`` will be {input_note}. The output of ``func`` should be
+ {output_note}, in the format 'attribute: value; attribute2: value2; ...'
+ or, if nothing is to be applied to that element, an empty string or ``None``.
+
+ Examples
+ --------
+ Basic usage to conditionally highlight values in the index.
+
+ >>> df = pd.DataFrame([[1,2], [3,4]], index=["A", "B"])
+ >>> def color_b(s):
+ ... return {ret}
+ >>> df.style.{this}_index(color_b) # doctest: +SKIP
+
+ .. figure:: ../../_static/style/appmaphead1.png
+
+ Selectively applying to specific levels of MultiIndex columns.
+
+ >>> midx = pd.MultiIndex.from_product([['ix', 'jy'], [0, 1], ['x3', 'z4']])
+ >>> df = pd.DataFrame([np.arange(8)], columns=midx)
+ >>> def highlight_x({var}):
+ ... return {ret2}
+ >>> df.style.{this}_index(highlight_x, axis="columns", level=[0, 2])
+ ... # doctest: +SKIP
+
+ .. figure:: ../../_static/style/appmaphead2.png
+ """
+ self._todo.append(
+ (
+ lambda instance: getattr(instance, "_apply_index"),
+ (func, axis, level, "apply"),
+ kwargs,
+ )
+ )
+ return self
+
+ @doc(
+ apply_index,
+ this="map",
+ wise="elementwise",
+ alt="apply",
+ altwise="level-wise",
+ func="take a scalar and return a string",
+ input_note="an index value, if an Index, or a level value of a MultiIndex",
+ output_note="CSS styles as a string",
+ var="v",
+ ret='"background-color: yellow;" if v == "B" else None',
+ ret2='"background-color: yellow;" if "x" in v else None',
+ )
+ def map_index(
+ self,
+ func: Callable,
+ axis: AxisInt | str = 0,
+ level: Level | list[Level] | None = None,
+ **kwargs,
+ ) -> Styler:
+ self._todo.append(
+ (
+ lambda instance: getattr(instance, "_apply_index"),
+ (func, axis, level, "map"),
+ kwargs,
+ )
+ )
+ return self
+
+ def applymap_index(
+ self,
+ func: Callable,
+ axis: AxisInt | str = 0,
+ level: Level | list[Level] | None = None,
+ **kwargs,
+ ) -> Styler:
+ """
+ Apply a CSS-styling function to the index or column headers, elementwise.
+
+ .. deprecated:: 2.1.0
+
+ Styler.applymap_index has been deprecated. Use Styler.map_index instead.
+
+ Parameters
+ ----------
+ func : function
+ ``func`` should take a scalar and return a string.
+ axis : {{0, 1, "index", "columns"}}
+ The headers over which to apply the function.
+ level : int, str, list, optional
+ If index is MultiIndex the level(s) over which to apply the function.
+ **kwargs : dict
+ Pass along to ``func``.
+
+ Returns
+ -------
+ Styler
+ """
+ warnings.warn(
+ "Styler.applymap_index has been deprecated. Use Styler.map_index instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return self.map_index(func, axis, level, **kwargs)
+
+ def _map(self, func: Callable, subset: Subset | None = None, **kwargs) -> Styler:
+ func = partial(func, **kwargs) # map doesn't take kwargs?
+ if subset is None:
+ subset = IndexSlice[:]
+ subset = non_reducing_slice(subset)
+ result = self.data.loc[subset].map(func)
+ self._update_ctx(result)
+ return self
+
+ @Substitution(subset=subset_args)
+ def map(self, func: Callable, subset: Subset | None = None, **kwargs) -> Styler:
+ """
+ Apply a CSS-styling function elementwise.
+
+ Updates the HTML representation with the result.
+
+ Parameters
+ ----------
+ func : function
+ ``func`` should take a scalar and return a string.
+ %(subset)s
+ **kwargs : dict
+ Pass along to ``func``.
+
+ Returns
+ -------
+ Styler
+
+ See Also
+ --------
+ Styler.map_index: Apply a CSS-styling function to headers elementwise.
+ Styler.apply_index: Apply a CSS-styling function to headers level-wise.
+ Styler.apply: Apply a CSS-styling function column-wise, row-wise, or table-wise.
+
+ Notes
+ -----
+ The elements of the output of ``func`` should be CSS styles as strings, in the
+ format 'attribute: value; attribute2: value2; ...' or,
+ if nothing is to be applied to that element, an empty string or ``None``.
+
+ Examples
+ --------
+ >>> def color_negative(v, color):
+ ... return f"color: {color};" if v < 0 else None
+ >>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
+ >>> df.style.map(color_negative, color='red') # doctest: +SKIP
+
+ Using ``subset`` to restrict application to a single column or multiple columns
+
+ >>> df.style.map(color_negative, color='red', subset="A")
+ ... # doctest: +SKIP
+ >>> df.style.map(color_negative, color='red', subset=["A", "B"])
+ ... # doctest: +SKIP
+
+ Using a 2d input to ``subset`` to select rows in addition to columns
+
+ >>> df.style.map(color_negative, color='red',
+ ... subset=([0,1,2], slice(None))) # doctest: +SKIP
+ >>> df.style.map(color_negative, color='red', subset=(slice(0,5,2), "A"))
+ ... # doctest: +SKIP
+
+ See `Table Visualization <../../user_guide/style.ipynb>`_ user guide for
+ more details.
+ """
+ self._todo.append(
+ (lambda instance: getattr(instance, "_map"), (func, subset), kwargs)
+ )
+ return self
+
+ @Substitution(subset=subset_args)
+ def applymap(
+ self, func: Callable, subset: Subset | None = None, **kwargs
+ ) -> Styler:
+ """
+ Apply a CSS-styling function elementwise.
+
+ .. deprecated:: 2.1.0
+
+ Styler.applymap has been deprecated. Use Styler.map instead.
+
+ Parameters
+ ----------
+ func : function
+ ``func`` should take a scalar and return a string.
+ %(subset)s
+ **kwargs : dict
+ Pass along to ``func``.
+
+ Returns
+ -------
+ Styler
+ """
+ warnings.warn(
+ "Styler.applymap has been deprecated. Use Styler.map instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return self.map(func, subset, **kwargs)
+
+ def set_table_attributes(self, attributes: str) -> Styler:
+ """
+ Set the table attributes added to the ```` HTML element.
+
+ These are items in addition to automatic (by default) ``id`` attribute.
+
+ Parameters
+ ----------
+ attributes : str
+
+ Returns
+ -------
+ Styler
+
+ See Also
+ --------
+ Styler.set_table_styles: Set the table styles included within the `` block
+
+ Parameters
+ ----------
+ sparsify_index : bool
+ Whether index_headers section will add rowspan attributes (>1) to elements.
+
+ Returns
+ -------
+ body : list
+ The associated HTML elements needed for template rendering.
+ """
+ rlabels = self.data.index.tolist()
+ if not isinstance(self.data.index, MultiIndex):
+ rlabels = [[x] for x in rlabels]
+
+ body: list = []
+ visible_row_count: int = 0
+ for r, row_tup in [
+ z for z in enumerate(self.data.itertuples()) if z[0] not in self.hidden_rows
+ ]:
+ visible_row_count += 1
+ if self._check_trim(
+ visible_row_count,
+ max_rows,
+ body,
+ "row",
+ ):
+ break
+
+ body_row = self._generate_body_row(
+ (r, row_tup, rlabels), max_cols, idx_lengths
+ )
+ body.append(body_row)
+ return body
+
+ def _check_trim(
+ self,
+ count: int,
+ max: int,
+ obj: list,
+ element: str,
+ css: str | None = None,
+ value: str = "...",
+ ) -> bool:
+ """
+ Indicates whether to break render loops and append a trimming indicator
+
+ Parameters
+ ----------
+ count : int
+ The loop count of previous visible items.
+ max : int
+ The allowable rendered items in the loop.
+ obj : list
+ The current render collection of the rendered items.
+ element : str
+ The type of element to append in the case a trimming indicator is needed.
+ css : str, optional
+ The css to add to the trimming indicator element.
+ value : str, optional
+ The value of the elements display if necessary.
+
+ Returns
+ -------
+ result : bool
+ Whether a trimming element was required and appended.
+ """
+ if count > max:
+ if element == "row":
+ obj.append(self._generate_trimmed_row(max))
+ else:
+ obj.append(_element(element, css, value, True, attributes=""))
+ return True
+ return False
+
+ def _generate_trimmed_row(self, max_cols: int) -> list:
+ """
+ When a render has too many rows we generate a trimming row containing "..."
+
+ Parameters
+ ----------
+ max_cols : int
+ Number of permissible columns
+
+ Returns
+ -------
+ list of elements
+ """
+ index_headers = [
+ _element(
+ "th",
+ (
+ f"{self.css['row_heading']} {self.css['level']}{c} "
+ f"{self.css['row_trim']}"
+ ),
+ "...",
+ not self.hide_index_[c],
+ attributes="",
+ )
+ for c in range(self.data.index.nlevels)
+ ]
+
+ data: list = []
+ visible_col_count: int = 0
+ for c, _ in enumerate(self.columns):
+ data_element_visible = c not in self.hidden_columns
+ if data_element_visible:
+ visible_col_count += 1
+ if self._check_trim(
+ visible_col_count,
+ max_cols,
+ data,
+ "td",
+ f"{self.css['data']} {self.css['row_trim']} {self.css['col_trim']}",
+ ):
+ break
+
+ data.append(
+ _element(
+ "td",
+ f"{self.css['data']} {self.css['col']}{c} {self.css['row_trim']}",
+ "...",
+ data_element_visible,
+ attributes="",
+ )
+ )
+
+ return index_headers + data
+
+ def _generate_body_row(
+ self,
+ iter: tuple,
+ max_cols: int,
+ idx_lengths: dict,
+ ):
+ """
+ Generate a regular row for the body section of appropriate format.
+
+ +--------------------------------------------+---------------------------+
+ | index_header_0 ... index_header_n | data_by_column ... |
+ +--------------------------------------------+---------------------------+
+
+ Parameters
+ ----------
+ iter : tuple
+ Iterable from outer scope: row number, row data tuple, row index labels.
+ max_cols : int
+ Number of permissible columns.
+ idx_lengths : dict
+ A map of the sparsification structure of the index
+
+ Returns
+ -------
+ list of elements
+ """
+ r, row_tup, rlabels = iter
+
+ index_headers = []
+ for c, value in enumerate(rlabels[r]):
+ header_element_visible = (
+ _is_visible(r, c, idx_lengths) and not self.hide_index_[c]
+ )
+ header_element = _element(
+ "th",
+ (
+ f"{self.css['row_heading']} {self.css['level']}{c} "
+ f"{self.css['row']}{r}"
+ ),
+ value,
+ header_element_visible,
+ display_value=self._display_funcs_index[(r, c)](value),
+ attributes=(
+ f'rowspan="{idx_lengths.get((c, r), 0)}"'
+ if idx_lengths.get((c, r), 0) > 1
+ else ""
+ ),
+ )
+
+ if self.cell_ids:
+ header_element[
+ "id"
+ ] = f"{self.css['level']}{c}_{self.css['row']}{r}" # id is given
+ if (
+ header_element_visible
+ and (r, c) in self.ctx_index
+ and self.ctx_index[r, c]
+ ):
+ # always add id if a style is specified
+ header_element["id"] = f"{self.css['level']}{c}_{self.css['row']}{r}"
+ self.cellstyle_map_index[tuple(self.ctx_index[r, c])].append(
+ f"{self.css['level']}{c}_{self.css['row']}{r}"
+ )
+
+ index_headers.append(header_element)
+
+ data: list = []
+ visible_col_count: int = 0
+ for c, value in enumerate(row_tup[1:]):
+ data_element_visible = (
+ c not in self.hidden_columns and r not in self.hidden_rows
+ )
+ if data_element_visible:
+ visible_col_count += 1
+ if self._check_trim(
+ visible_col_count,
+ max_cols,
+ data,
+ "td",
+ f"{self.css['data']} {self.css['row']}{r} {self.css['col_trim']}",
+ ):
+ break
+
+ # add custom classes from cell context
+ cls = ""
+ if (r, c) in self.cell_context:
+ cls = " " + self.cell_context[r, c]
+
+ data_element = _element(
+ "td",
+ (
+ f"{self.css['data']} {self.css['row']}{r} "
+ f"{self.css['col']}{c}{cls}"
+ ),
+ value,
+ data_element_visible,
+ attributes="",
+ display_value=self._display_funcs[(r, c)](value),
+ )
+
+ if self.cell_ids:
+ data_element["id"] = f"{self.css['row']}{r}_{self.css['col']}{c}"
+ if data_element_visible and (r, c) in self.ctx and self.ctx[r, c]:
+ # always add id if needed due to specified style
+ data_element["id"] = f"{self.css['row']}{r}_{self.css['col']}{c}"
+ self.cellstyle_map[tuple(self.ctx[r, c])].append(
+ f"{self.css['row']}{r}_{self.css['col']}{c}"
+ )
+
+ data.append(data_element)
+
+ return index_headers + data
+
+ def _translate_latex(self, d: dict, clines: str | None) -> None:
+ r"""
+ Post-process the default render dict for the LaTeX template format.
+
+ Processing items included are:
+ - Remove hidden columns from the non-headers part of the body.
+ - Place cellstyles directly in td cells rather than use cellstyle_map.
+ - Remove hidden indexes or reinsert missing th elements if part of multiindex
+ or multirow sparsification (so that \multirow and \multicol work correctly).
+ """
+ index_levels = self.index.nlevels
+ visible_index_level_n = index_levels - sum(self.hide_index_)
+ d["head"] = [
+ [
+ {**col, "cellstyle": self.ctx_columns[r, c - visible_index_level_n]}
+ for c, col in enumerate(row)
+ if col["is_visible"]
+ ]
+ for r, row in enumerate(d["head"])
+ ]
+
+ def _concatenated_visible_rows(obj, n, row_indices):
+ """
+ Extract all visible row indices recursively from concatenated stylers.
+ """
+ row_indices.extend(
+ [r + n for r in range(len(obj.index)) if r not in obj.hidden_rows]
+ )
+ n += len(obj.index)
+ for concatenated in obj.concatenated:
+ n = _concatenated_visible_rows(concatenated, n, row_indices)
+ return n
+
+ def concatenated_visible_rows(obj):
+ row_indices: list[int] = []
+ _concatenated_visible_rows(obj, 0, row_indices)
+ # TODO try to consolidate the concat visible rows
+ # methods to a single function / recursion for simplicity
+ return row_indices
+
+ body = []
+ for r, row in zip(concatenated_visible_rows(self), d["body"]):
+ # note: cannot enumerate d["body"] because rows were dropped if hidden
+ # during _translate_body so must zip to acquire the true r-index associated
+ # with the ctx obj which contains the cell styles.
+ if all(self.hide_index_):
+ row_body_headers = []
+ else:
+ row_body_headers = [
+ {
+ **col,
+ "display_value": col["display_value"]
+ if col["is_visible"]
+ else "",
+ "cellstyle": self.ctx_index[r, c],
+ }
+ for c, col in enumerate(row[:index_levels])
+ if (col["type"] == "th" and not self.hide_index_[c])
+ ]
+
+ row_body_cells = [
+ {**col, "cellstyle": self.ctx[r, c]}
+ for c, col in enumerate(row[index_levels:])
+ if (col["is_visible"] and col["type"] == "td")
+ ]
+
+ body.append(row_body_headers + row_body_cells)
+ d["body"] = body
+
+ # clines are determined from info on index_lengths and hidden_rows and input
+ # to a dict defining which row clines should be added in the template.
+ if clines not in [
+ None,
+ "all;data",
+ "all;index",
+ "skip-last;data",
+ "skip-last;index",
+ ]:
+ raise ValueError(
+ f"`clines` value of {clines} is invalid. Should either be None or one "
+ f"of 'all;data', 'all;index', 'skip-last;data', 'skip-last;index'."
+ )
+ if clines is not None:
+ data_len = len(row_body_cells) if "data" in clines and d["body"] else 0
+
+ d["clines"] = defaultdict(list)
+ visible_row_indexes: list[int] = [
+ r for r in range(len(self.data.index)) if r not in self.hidden_rows
+ ]
+ visible_index_levels: list[int] = [
+ i for i in range(index_levels) if not self.hide_index_[i]
+ ]
+ for rn, r in enumerate(visible_row_indexes):
+ for lvln, lvl in enumerate(visible_index_levels):
+ if lvl == index_levels - 1 and "skip-last" in clines:
+ continue
+ idx_len = d["index_lengths"].get((lvl, r), None)
+ if idx_len is not None: # i.e. not a sparsified entry
+ d["clines"][rn + idx_len].append(
+ f"\\cline{{{lvln+1}-{len(visible_index_levels)+data_len}}}"
+ )
+
+ def format(
+ self,
+ formatter: ExtFormatter | None = None,
+ subset: Subset | None = None,
+ na_rep: str | None = None,
+ precision: int | None = None,
+ decimal: str = ".",
+ thousands: str | None = None,
+ escape: str | None = None,
+ hyperlinks: str | None = None,
+ ) -> StylerRenderer:
+ r"""
+ Format the text display value of cells.
+
+ Parameters
+ ----------
+ formatter : str, callable, dict or None
+ Object to define how values are displayed. See notes.
+ subset : label, array-like, IndexSlice, optional
+ A valid 2d input to `DataFrame.loc[]`, or, in the case of a 1d input
+ or single key, to `DataFrame.loc[:, ]` where the columns are
+ prioritised, to limit ``data`` to *before* applying the function.
+ na_rep : str, optional
+ Representation for missing values.
+ If ``na_rep`` is None, no special formatting is applied.
+ precision : int, optional
+ Floating point precision to use for display purposes, if not determined by
+ the specified ``formatter``.
+
+ .. versionadded:: 1.3.0
+
+ decimal : str, default "."
+ Character used as decimal separator for floats, complex and integers.
+
+ .. versionadded:: 1.3.0
+
+ thousands : str, optional, default None
+ Character used as thousands separator for floats, complex and integers.
+
+ .. versionadded:: 1.3.0
+
+ escape : str, optional
+ Use 'html' to replace the characters ``&``, ``<``, ``>``, ``'``, and ``"``
+ in cell display string with HTML-safe sequences.
+ Use 'latex' to replace the characters ``&``, ``%``, ``$``, ``#``, ``_``,
+ ``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with
+ LaTeX-safe sequences.
+ Use 'latex-math' to replace the characters the same way as in 'latex' mode,
+ except for math substrings, which either are surrounded
+ by two characters ``$`` or start with the character ``\(`` and
+ end with ``\)``. Escaping is done before ``formatter``.
+
+ .. versionadded:: 1.3.0
+
+ hyperlinks : {"html", "latex"}, optional
+ Convert string patterns containing https://, http://, ftp:// or www. to
+ HTML tags as clickable URL hyperlinks if "html", or LaTeX \href
+ commands if "latex".
+
+ .. versionadded:: 1.4.0
+
+ Returns
+ -------
+ Styler
+
+ See Also
+ --------
+ Styler.format_index: Format the text display value of index labels.
+
+ Notes
+ -----
+ This method assigns a formatting function, ``formatter``, to each cell in the
+ DataFrame. If ``formatter`` is ``None``, then the default formatter is used.
+ If a callable then that function should take a data value as input and return
+ a displayable representation, such as a string. If ``formatter`` is
+ given as a string this is assumed to be a valid Python format specification
+ and is wrapped to a callable as ``string.format(x)``. If a ``dict`` is given,
+ keys should correspond to column names, and values should be string or
+ callable, as above.
+
+ The default formatter currently expresses floats and complex numbers with the
+ pandas display precision unless using the ``precision`` argument here. The
+ default formatter does not adjust the representation of missing values unless
+ the ``na_rep`` argument is used.
+
+ The ``subset`` argument defines which region to apply the formatting function
+ to. If the ``formatter`` argument is given in dict form but does not include
+ all columns within the subset then these columns will have the default formatter
+ applied. Any columns in the formatter dict excluded from the subset will
+ be ignored.
+
+ When using a ``formatter`` string the dtypes must be compatible, otherwise a
+ `ValueError` will be raised.
+
+ When instantiating a Styler, default formatting can be applied be setting the
+ ``pandas.options``:
+
+ - ``styler.format.formatter``: default None.
+ - ``styler.format.na_rep``: default None.
+ - ``styler.format.precision``: default 6.
+ - ``styler.format.decimal``: default ".".
+ - ``styler.format.thousands``: default None.
+ - ``styler.format.escape``: default None.
+
+ .. warning::
+ `Styler.format` is ignored when using the output format `Styler.to_excel`,
+ since Excel and Python have inherrently different formatting structures.
+ However, it is possible to use the `number-format` pseudo CSS attribute
+ to force Excel permissible formatting. See examples.
+
+ Examples
+ --------
+ Using ``na_rep`` and ``precision`` with the default ``formatter``
+
+ >>> df = pd.DataFrame([[np.nan, 1.0, 'A'], [2.0, np.nan, 3.0]])
+ >>> df.style.format(na_rep='MISS', precision=3) # doctest: +SKIP
+ 0 1 2
+ 0 MISS 1.000 A
+ 1 2.000 MISS 3.000
+
+ Using a ``formatter`` specification on consistent column dtypes
+
+ >>> df.style.format('{:.2f}', na_rep='MISS', subset=[0,1]) # doctest: +SKIP
+ 0 1 2
+ 0 MISS 1.00 A
+ 1 2.00 MISS 3.000000
+
+ Using the default ``formatter`` for unspecified columns
+
+ >>> df.style.format({0: '{:.2f}', 1: '£ {:.1f}'}, na_rep='MISS', precision=1)
+ ... # doctest: +SKIP
+ 0 1 2
+ 0 MISS £ 1.0 A
+ 1 2.00 MISS 3.0
+
+ Multiple ``na_rep`` or ``precision`` specifications under the default
+ ``formatter``.
+
+ >>> (df.style.format(na_rep='MISS', precision=1, subset=[0])
+ ... .format(na_rep='PASS', precision=2, subset=[1, 2])) # doctest: +SKIP
+ 0 1 2
+ 0 MISS 1.00 A
+ 1 2.0 PASS 3.00
+
+ Using a callable ``formatter`` function.
+
+ >>> func = lambda s: 'STRING' if isinstance(s, str) else 'FLOAT'
+ >>> df.style.format({0: '{:.1f}', 2: func}, precision=4, na_rep='MISS')
+ ... # doctest: +SKIP
+ 0 1 2
+ 0 MISS 1.0000 STRING
+ 1 2.0 MISS FLOAT
+
+ Using a ``formatter`` with HTML ``escape`` and ``na_rep``.
+
+ >>> df = pd.DataFrame([['
', '"A&B"', None]])
+ >>> s = df.style.format(
+ ... ' {0} ', escape="html", na_rep="NA"
+ ... )
+ >>> s.to_html() # doctest: +SKIP
+ ...
+ <div></div>
+ "A&B"
+ NA
+ ...
+
+ Using a ``formatter`` with ``escape`` in 'latex' mode.
+
+ >>> df = pd.DataFrame([["123"], ["~ ^"], ["$%#"]])
+ >>> df.style.format("\\textbf{{{}}}", escape="latex").to_latex()
+ ... # doctest: +SKIP
+ \begin{tabular}{ll}
+ & 0 \\
+ 0 & \textbf{123} \\
+ 1 & \textbf{\textasciitilde \space \textasciicircum } \\
+ 2 & \textbf{\$\%\#} \\
+ \end{tabular}
+
+ Applying ``escape`` in 'latex-math' mode. In the example below
+ we enter math mode using the character ``$``.
+
+ >>> df = pd.DataFrame([[r"$\sum_{i=1}^{10} a_i$ a~b $\alpha \
+ ... = \frac{\beta}{\zeta^2}$"], ["%#^ $ \$x^2 $"]])
+ >>> df.style.format(escape="latex-math").to_latex()
+ ... # doctest: +SKIP
+ \begin{tabular}{ll}
+ & 0 \\
+ 0 & $\sum_{i=1}^{10} a_i$ a\textasciitilde b $\alpha = \frac{\beta}{\zeta^2}$ \\
+ 1 & \%\#\textasciicircum \space $ \$x^2 $ \\
+ \end{tabular}
+
+ We can use the character ``\(`` to enter math mode and the character ``\)``
+ to close math mode.
+
+ >>> df = pd.DataFrame([[r"\(\sum_{i=1}^{10} a_i\) a~b \(\alpha \
+ ... = \frac{\beta}{\zeta^2}\)"], ["%#^ \( \$x^2 \)"]])
+ >>> df.style.format(escape="latex-math").to_latex()
+ ... # doctest: +SKIP
+ \begin{tabular}{ll}
+ & 0 \\
+ 0 & \(\sum_{i=1}^{10} a_i\) a\textasciitilde b \(\alpha
+ = \frac{\beta}{\zeta^2}\) \\
+ 1 & \%\#\textasciicircum \space \( \$x^2 \) \\
+ \end{tabular}
+
+ If we have in one DataFrame cell a combination of both shorthands
+ for math formulas, the shorthand with the sign ``$`` will be applied.
+
+ >>> df = pd.DataFrame([[r"\( x^2 \) $x^2$"], \
+ ... [r"$\frac{\beta}{\zeta}$ \(\frac{\beta}{\zeta}\)"]])
+ >>> df.style.format(escape="latex-math").to_latex()
+ ... # doctest: +SKIP
+ \begin{tabular}{ll}
+ & 0 \\
+ 0 & \textbackslash ( x\textasciicircum 2 \textbackslash ) $x^2$ \\
+ 1 & $\frac{\beta}{\zeta}$ \textbackslash (\textbackslash
+ frac\{\textbackslash beta\}\{\textbackslash zeta\}\textbackslash ) \\
+ \end{tabular}
+
+ Pandas defines a `number-format` pseudo CSS attribute instead of the `.format`
+ method to create `to_excel` permissible formatting. Note that semi-colons are
+ CSS protected characters but used as separators in Excel's format string.
+ Replace semi-colons with the section separator character (ASCII-245) when
+ defining the formatting here.
+
+ >>> df = pd.DataFrame({"A": [1, 0, -1]})
+ >>> pseudo_css = "number-format: 0§[Red](0)§-§@;"
+ >>> filename = "formatted_file.xlsx"
+ >>> df.style.map(lambda v: pseudo_css).to_excel(filename) # doctest: +SKIP
+
+ .. figure:: ../../_static/style/format_excel_css.png
+ """
+ if all(
+ (
+ formatter is None,
+ subset is None,
+ precision is None,
+ decimal == ".",
+ thousands is None,
+ na_rep is None,
+ escape is None,
+ hyperlinks is None,
+ )
+ ):
+ self._display_funcs.clear()
+ return self # clear the formatter / revert to default and avoid looping
+
+ subset = slice(None) if subset is None else subset
+ subset = non_reducing_slice(subset)
+ data = self.data.loc[subset]
+
+ if not isinstance(formatter, dict):
+ formatter = {col: formatter for col in data.columns}
+
+ cis = self.columns.get_indexer_for(data.columns)
+ ris = self.index.get_indexer_for(data.index)
+ for ci in cis:
+ format_func = _maybe_wrap_formatter(
+ formatter.get(self.columns[ci]),
+ na_rep=na_rep,
+ precision=precision,
+ decimal=decimal,
+ thousands=thousands,
+ escape=escape,
+ hyperlinks=hyperlinks,
+ )
+ for ri in ris:
+ self._display_funcs[(ri, ci)] = format_func
+
+ return self
+
+ def format_index(
+ self,
+ formatter: ExtFormatter | None = None,
+ axis: Axis = 0,
+ level: Level | list[Level] | None = None,
+ na_rep: str | None = None,
+ precision: int | None = None,
+ decimal: str = ".",
+ thousands: str | None = None,
+ escape: str | None = None,
+ hyperlinks: str | None = None,
+ ) -> StylerRenderer:
+ r"""
+ Format the text display value of index labels or column headers.
+
+ .. versionadded:: 1.4.0
+
+ Parameters
+ ----------
+ formatter : str, callable, dict or None
+ Object to define how values are displayed. See notes.
+ axis : {0, "index", 1, "columns"}
+ Whether to apply the formatter to the index or column headers.
+ level : int, str, list
+ The level(s) over which to apply the generic formatter.
+ na_rep : str, optional
+ Representation for missing values.
+ If ``na_rep`` is None, no special formatting is applied.
+ precision : int, optional
+ Floating point precision to use for display purposes, if not determined by
+ the specified ``formatter``.
+ decimal : str, default "."
+ Character used as decimal separator for floats, complex and integers.
+ thousands : str, optional, default None
+ Character used as thousands separator for floats, complex and integers.
+ escape : str, optional
+ Use 'html' to replace the characters ``&``, ``<``, ``>``, ``'``, and ``"``
+ in cell display string with HTML-safe sequences.
+ Use 'latex' to replace the characters ``&``, ``%``, ``$``, ``#``, ``_``,
+ ``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with
+ LaTeX-safe sequences.
+ Escaping is done before ``formatter``.
+ hyperlinks : {"html", "latex"}, optional
+ Convert string patterns containing https://, http://, ftp:// or www. to
+ HTML tags as clickable URL hyperlinks if "html", or LaTeX \href
+ commands if "latex".
+
+ Returns
+ -------
+ Styler
+
+ See Also
+ --------
+ Styler.format: Format the text display value of data cells.
+
+ Notes
+ -----
+ This method assigns a formatting function, ``formatter``, to each level label
+ in the DataFrame's index or column headers. If ``formatter`` is ``None``,
+ then the default formatter is used.
+ If a callable then that function should take a label value as input and return
+ a displayable representation, such as a string. If ``formatter`` is
+ given as a string this is assumed to be a valid Python format specification
+ and is wrapped to a callable as ``string.format(x)``. If a ``dict`` is given,
+ keys should correspond to MultiIndex level numbers or names, and values should
+ be string or callable, as above.
+
+ The default formatter currently expresses floats and complex numbers with the
+ pandas display precision unless using the ``precision`` argument here. The
+ default formatter does not adjust the representation of missing values unless
+ the ``na_rep`` argument is used.
+
+ The ``level`` argument defines which levels of a MultiIndex to apply the
+ method to. If the ``formatter`` argument is given in dict form but does
+ not include all levels within the level argument then these unspecified levels
+ will have the default formatter applied. Any levels in the formatter dict
+ specifically excluded from the level argument will be ignored.
+
+ When using a ``formatter`` string the dtypes must be compatible, otherwise a
+ `ValueError` will be raised.
+
+ .. warning::
+ `Styler.format_index` is ignored when using the output format
+ `Styler.to_excel`, since Excel and Python have inherrently different
+ formatting structures.
+ However, it is possible to use the `number-format` pseudo CSS attribute
+ to force Excel permissible formatting. See documentation for `Styler.format`.
+
+ Examples
+ --------
+ Using ``na_rep`` and ``precision`` with the default ``formatter``
+
+ >>> df = pd.DataFrame([[1, 2, 3]], columns=[2.0, np.nan, 4.0])
+ >>> df.style.format_index(axis=1, na_rep='MISS', precision=3) # doctest: +SKIP
+ 2.000 MISS 4.000
+ 0 1 2 3
+
+ Using a ``formatter`` specification on consistent dtypes in a level
+
+ >>> df.style.format_index('{:.2f}', axis=1, na_rep='MISS') # doctest: +SKIP
+ 2.00 MISS 4.00
+ 0 1 2 3
+
+ Using the default ``formatter`` for unspecified levels
+
+ >>> df = pd.DataFrame([[1, 2, 3]],
+ ... columns=pd.MultiIndex.from_arrays([["a", "a", "b"],[2, np.nan, 4]]))
+ >>> df.style.format_index({0: lambda v: v.upper()}, axis=1, precision=1)
+ ... # doctest: +SKIP
+ A B
+ 2.0 nan 4.0
+ 0 1 2 3
+
+ Using a callable ``formatter`` function.
+
+ >>> func = lambda s: 'STRING' if isinstance(s, str) else 'FLOAT'
+ >>> df.style.format_index(func, axis=1, na_rep='MISS')
+ ... # doctest: +SKIP
+ STRING STRING
+ FLOAT MISS FLOAT
+ 0 1 2 3
+
+ Using a ``formatter`` with HTML ``escape`` and ``na_rep``.
+
+ >>> df = pd.DataFrame([[1, 2, 3]], columns=['"A"', 'A&B', None])
+ >>> s = df.style.format_index('$ {0}', axis=1, escape="html", na_rep="NA")
+ ... # doctest: +SKIP
+ $ "A"
+ $ A&B
+ NA
+ ...
+
+ Using a ``formatter`` with LaTeX ``escape``.
+
+ >>> df = pd.DataFrame([[1, 2, 3]], columns=["123", "~", "$%#"])
+ >>> df.style.format_index("\\textbf{{{}}}", escape="latex", axis=1).to_latex()
+ ... # doctest: +SKIP
+ \begin{tabular}{lrrr}
+ {} & {\textbf{123}} & {\textbf{\textasciitilde }} & {\textbf{\$\%\#}} \\
+ 0 & 1 & 2 & 3 \\
+ \end{tabular}
+ """
+ axis = self.data._get_axis_number(axis)
+ if axis == 0:
+ display_funcs_, obj = self._display_funcs_index, self.index
+ else:
+ display_funcs_, obj = self._display_funcs_columns, self.columns
+ levels_ = refactor_levels(level, obj)
+
+ if all(
+ (
+ formatter is None,
+ level is None,
+ precision is None,
+ decimal == ".",
+ thousands is None,
+ na_rep is None,
+ escape is None,
+ hyperlinks is None,
+ )
+ ):
+ display_funcs_.clear()
+ return self # clear the formatter / revert to default and avoid looping
+
+ if not isinstance(formatter, dict):
+ formatter = {level: formatter for level in levels_}
+ else:
+ formatter = {
+ obj._get_level_number(level): formatter_
+ for level, formatter_ in formatter.items()
+ }
+
+ for lvl in levels_:
+ format_func = _maybe_wrap_formatter(
+ formatter.get(lvl),
+ na_rep=na_rep,
+ precision=precision,
+ decimal=decimal,
+ thousands=thousands,
+ escape=escape,
+ hyperlinks=hyperlinks,
+ )
+
+ for idx in [(i, lvl) if axis == 0 else (lvl, i) for i in range(len(obj))]:
+ display_funcs_[idx] = format_func
+
+ return self
+
+ def relabel_index(
+ self,
+ labels: Sequence | Index,
+ axis: Axis = 0,
+ level: Level | list[Level] | None = None,
+ ) -> StylerRenderer:
+ r"""
+ Relabel the index, or column header, keys to display a set of specified values.
+
+ .. versionadded:: 1.5.0
+
+ Parameters
+ ----------
+ labels : list-like or Index
+ New labels to display. Must have same length as the underlying values not
+ hidden.
+ axis : {"index", 0, "columns", 1}
+ Apply to the index or columns.
+ level : int, str, list, optional
+ The level(s) over which to apply the new labels. If `None` will apply
+ to all levels of an Index or MultiIndex which are not hidden.
+
+ Returns
+ -------
+ Styler
+
+ See Also
+ --------
+ Styler.format_index: Format the text display value of index or column headers.
+ Styler.hide: Hide the index, column headers, or specified data from display.
+
+ Notes
+ -----
+ As part of Styler, this method allows the display of an index to be
+ completely user-specified without affecting the underlying DataFrame data,
+ index, or column headers. This means that the flexibility of indexing is
+ maintained whilst the final display is customisable.
+
+ Since Styler is designed to be progressively constructed with method chaining,
+ this method is adapted to react to the **currently specified hidden elements**.
+ This is useful because it means one does not have to specify all the new
+ labels if the majority of an index, or column headers, have already been hidden.
+ The following produce equivalent display (note the length of ``labels`` in
+ each case).
+
+ .. code-block:: python
+
+ # relabel first, then hide
+ df = pd.DataFrame({"col": ["a", "b", "c"]})
+ df.style.relabel_index(["A", "B", "C"]).hide([0,1])
+ # hide first, then relabel
+ df = pd.DataFrame({"col": ["a", "b", "c"]})
+ df.style.hide([0,1]).relabel_index(["C"])
+
+ This method should be used, rather than :meth:`Styler.format_index`, in one of
+ the following cases (see examples):
+
+ - A specified set of labels are required which are not a function of the
+ underlying index keys.
+ - The function of the underlying index keys requires a counter variable,
+ such as those available upon enumeration.
+
+ Examples
+ --------
+ Basic use
+
+ >>> df = pd.DataFrame({"col": ["a", "b", "c"]})
+ >>> df.style.relabel_index(["A", "B", "C"]) # doctest: +SKIP
+ col
+ A a
+ B b
+ C c
+
+ Chaining with pre-hidden elements
+
+ >>> df.style.hide([0,1]).relabel_index(["C"]) # doctest: +SKIP
+ col
+ C c
+
+ Using a MultiIndex
+
+ >>> midx = pd.MultiIndex.from_product([[0, 1], [0, 1], [0, 1]])
+ >>> df = pd.DataFrame({"col": list(range(8))}, index=midx)
+ >>> styler = df.style # doctest: +SKIP
+ col
+ 0 0 0 0
+ 1 1
+ 1 0 2
+ 1 3
+ 1 0 0 4
+ 1 5
+ 1 0 6
+ 1 7
+ >>> styler.hide((midx.get_level_values(0)==0)|(midx.get_level_values(1)==0))
+ ... # doctest: +SKIP
+ >>> styler.hide(level=[0,1]) # doctest: +SKIP
+ >>> styler.relabel_index(["binary6", "binary7"]) # doctest: +SKIP
+ col
+ binary6 6
+ binary7 7
+
+ We can also achieve the above by indexing first and then re-labeling
+
+ >>> styler = df.loc[[(1,1,0), (1,1,1)]].style
+ >>> styler.hide(level=[0,1]).relabel_index(["binary6", "binary7"])
+ ... # doctest: +SKIP
+ col
+ binary6 6
+ binary7 7
+
+ Defining a formatting function which uses an enumeration counter. Also note
+ that the value of the index key is passed in the case of string labels so it
+ can also be inserted into the label, using curly brackets (or double curly
+ brackets if the string if pre-formatted),
+
+ >>> df = pd.DataFrame({"samples": np.random.rand(10)})
+ >>> styler = df.loc[np.random.randint(0,10,3)].style
+ >>> styler.relabel_index([f"sample{i+1} ({{}})" for i in range(3)])
+ ... # doctest: +SKIP
+ samples
+ sample1 (5) 0.315811
+ sample2 (0) 0.495941
+ sample3 (2) 0.067946
+ """
+ axis = self.data._get_axis_number(axis)
+ if axis == 0:
+ display_funcs_, obj = self._display_funcs_index, self.index
+ hidden_labels, hidden_lvls = self.hidden_rows, self.hide_index_
+ else:
+ display_funcs_, obj = self._display_funcs_columns, self.columns
+ hidden_labels, hidden_lvls = self.hidden_columns, self.hide_columns_
+ visible_len = len(obj) - len(set(hidden_labels))
+ if len(labels) != visible_len:
+ raise ValueError(
+ "``labels`` must be of length equal to the number of "
+ f"visible labels along ``axis`` ({visible_len})."
+ )
+
+ if level is None:
+ level = [i for i in range(obj.nlevels) if not hidden_lvls[i]]
+ levels_ = refactor_levels(level, obj)
+
+ def alias_(x, value):
+ if isinstance(value, str):
+ return value.format(x)
+ return value
+
+ for ai, i in enumerate([i for i in range(len(obj)) if i not in hidden_labels]):
+ if len(levels_) == 1:
+ idx = (i, levels_[0]) if axis == 0 else (levels_[0], i)
+ display_funcs_[idx] = partial(alias_, value=labels[ai])
+ else:
+ for aj, lvl in enumerate(levels_):
+ idx = (i, lvl) if axis == 0 else (lvl, i)
+ display_funcs_[idx] = partial(alias_, value=labels[ai][aj])
+
+ return self
+
+
+def _element(
+ html_element: str,
+ html_class: str | None,
+ value: Any,
+ is_visible: bool,
+ **kwargs,
+) -> dict:
+ """
+ Template to return container with information for a or element.
+ """
+ if "display_value" not in kwargs:
+ kwargs["display_value"] = value
+ return {
+ "type": html_element,
+ "value": value,
+ "class": html_class,
+ "is_visible": is_visible,
+ **kwargs,
+ }
+
+
+def _get_trimming_maximums(
+ rn,
+ cn,
+ max_elements,
+ max_rows=None,
+ max_cols=None,
+ scaling_factor: float = 0.8,
+) -> tuple[int, int]:
+ """
+ Recursively reduce the number of rows and columns to satisfy max elements.
+
+ Parameters
+ ----------
+ rn, cn : int
+ The number of input rows / columns
+ max_elements : int
+ The number of allowable elements
+ max_rows, max_cols : int, optional
+ Directly specify an initial maximum rows or columns before compression.
+ scaling_factor : float
+ Factor at which to reduce the number of rows / columns to fit.
+
+ Returns
+ -------
+ rn, cn : tuple
+ New rn and cn values that satisfy the max_elements constraint
+ """
+
+ def scale_down(rn, cn):
+ if cn >= rn:
+ return rn, int(cn * scaling_factor)
+ else:
+ return int(rn * scaling_factor), cn
+
+ if max_rows:
+ rn = max_rows if rn > max_rows else rn
+ if max_cols:
+ cn = max_cols if cn > max_cols else cn
+
+ while rn * cn > max_elements:
+ rn, cn = scale_down(rn, cn)
+
+ return rn, cn
+
+
+def _get_level_lengths(
+ index: Index,
+ sparsify: bool,
+ max_index: int,
+ hidden_elements: Sequence[int] | None = None,
+):
+ """
+ Given an index, find the level length for each element.
+
+ Parameters
+ ----------
+ index : Index
+ Index or columns to determine lengths of each element
+ sparsify : bool
+ Whether to hide or show each distinct element in a MultiIndex
+ max_index : int
+ The maximum number of elements to analyse along the index due to trimming
+ hidden_elements : sequence of int
+ Index positions of elements hidden from display in the index affecting
+ length
+
+ Returns
+ -------
+ Dict :
+ Result is a dictionary of (level, initial_position): span
+ """
+ if isinstance(index, MultiIndex):
+ levels = index.format(sparsify=lib.no_default, adjoin=False)
+ else:
+ levels = index.format()
+
+ if hidden_elements is None:
+ hidden_elements = []
+
+ lengths = {}
+ if not isinstance(index, MultiIndex):
+ for i, value in enumerate(levels):
+ if i not in hidden_elements:
+ lengths[(0, i)] = 1
+ return lengths
+
+ for i, lvl in enumerate(levels):
+ visible_row_count = 0 # used to break loop due to display trimming
+ for j, row in enumerate(lvl):
+ if visible_row_count > max_index:
+ break
+ if not sparsify:
+ # then lengths will always equal 1 since no aggregation.
+ if j not in hidden_elements:
+ lengths[(i, j)] = 1
+ visible_row_count += 1
+ elif (row is not lib.no_default) and (j not in hidden_elements):
+ # this element has not been sparsified so must be the start of section
+ last_label = j
+ lengths[(i, last_label)] = 1
+ visible_row_count += 1
+ elif row is not lib.no_default:
+ # even if the above is hidden, keep track of it in case length > 1 and
+ # later elements are visible
+ last_label = j
+ lengths[(i, last_label)] = 0
+ elif j not in hidden_elements:
+ # then element must be part of sparsified section and is visible
+ visible_row_count += 1
+ if visible_row_count > max_index:
+ break # do not add a length since the render trim limit reached
+ if lengths[(i, last_label)] == 0:
+ # if previous iteration was first-of-section but hidden then offset
+ last_label = j
+ lengths[(i, last_label)] = 1
+ else:
+ # else add to previous iteration
+ lengths[(i, last_label)] += 1
+
+ non_zero_lengths = {
+ element: length for element, length in lengths.items() if length >= 1
+ }
+
+ return non_zero_lengths
+
+
+def _is_visible(idx_row, idx_col, lengths) -> bool:
+ """
+ Index -> {(idx_row, idx_col): bool}).
+ """
+ return (idx_col, idx_row) in lengths
+
+
+def format_table_styles(styles: CSSStyles) -> CSSStyles:
+ """
+ looks for multiple CSS selectors and separates them:
+ [{'selector': 'td, th', 'props': 'a:v;'}]
+ ---> [{'selector': 'td', 'props': 'a:v;'},
+ {'selector': 'th', 'props': 'a:v;'}]
+ """
+ return [
+ {"selector": selector, "props": css_dict["props"]}
+ for css_dict in styles
+ for selector in css_dict["selector"].split(",")
+ ]
+
+
+def _default_formatter(x: Any, precision: int, thousands: bool = False) -> Any:
+ """
+ Format the display of a value
+
+ Parameters
+ ----------
+ x : Any
+ Input variable to be formatted
+ precision : Int
+ Floating point precision used if ``x`` is float or complex.
+ thousands : bool, default False
+ Whether to group digits with thousands separated with ",".
+
+ Returns
+ -------
+ value : Any
+ Matches input type, or string if input is float or complex or int with sep.
+ """
+ if is_float(x) or is_complex(x):
+ return f"{x:,.{precision}f}" if thousands else f"{x:.{precision}f}"
+ elif is_integer(x):
+ return f"{x:,}" if thousands else str(x)
+ return x
+
+
+def _wrap_decimal_thousands(
+ formatter: Callable, decimal: str, thousands: str | None
+) -> Callable:
+ """
+ Takes a string formatting function and wraps logic to deal with thousands and
+ decimal parameters, in the case that they are non-standard and that the input
+ is a (float, complex, int).
+ """
+
+ def wrapper(x):
+ if is_float(x) or is_integer(x) or is_complex(x):
+ if decimal != "." and thousands is not None and thousands != ",":
+ return (
+ formatter(x)
+ .replace(",", "§_§-") # rare string to avoid "," <-> "." clash.
+ .replace(".", decimal)
+ .replace("§_§-", thousands)
+ )
+ elif decimal != "." and (thousands is None or thousands == ","):
+ return formatter(x).replace(".", decimal)
+ elif decimal == "." and thousands is not None and thousands != ",":
+ return formatter(x).replace(",", thousands)
+ return formatter(x)
+
+ return wrapper
+
+
+def _str_escape(x, escape):
+ """if escaping: only use on str, else return input"""
+ if isinstance(x, str):
+ if escape == "html":
+ return escape_html(x)
+ elif escape == "latex":
+ return _escape_latex(x)
+ elif escape == "latex-math":
+ return _escape_latex_math(x)
+ else:
+ raise ValueError(
+ f"`escape` only permitted in {{'html', 'latex', 'latex-math'}}, \
+got {escape}"
+ )
+ return x
+
+
+def _render_href(x, format):
+ """uses regex to detect a common URL pattern and converts to href tag in format."""
+ if isinstance(x, str):
+ if format == "html":
+ href = '{0} '
+ elif format == "latex":
+ href = r"\href{{{0}}}{{{0}}}"
+ else:
+ raise ValueError("``hyperlinks`` format can only be 'html' or 'latex'")
+ pat = r"((http|ftp)s?:\/\/|www.)[\w/\-?=%.:@]+\.[\w/\-&?=%.,':;~!@#$*()\[\]]+"
+ return re.sub(pat, lambda m: href.format(m.group(0)), x)
+ return x
+
+
+def _maybe_wrap_formatter(
+ formatter: BaseFormatter | None = None,
+ na_rep: str | None = None,
+ precision: int | None = None,
+ decimal: str = ".",
+ thousands: str | None = None,
+ escape: str | None = None,
+ hyperlinks: str | None = None,
+) -> Callable:
+ """
+ Allows formatters to be expressed as str, callable or None, where None returns
+ a default formatting function. wraps with na_rep, and precision where they are
+ available.
+ """
+ # Get initial func from input string, input callable, or from default factory
+ if isinstance(formatter, str):
+ func_0 = lambda x: formatter.format(x)
+ elif callable(formatter):
+ func_0 = formatter
+ elif formatter is None:
+ precision = (
+ get_option("styler.format.precision") if precision is None else precision
+ )
+ func_0 = partial(
+ _default_formatter, precision=precision, thousands=(thousands is not None)
+ )
+ else:
+ raise TypeError(f"'formatter' expected str or callable, got {type(formatter)}")
+
+ # Replace chars if escaping
+ if escape is not None:
+ func_1 = lambda x: func_0(_str_escape(x, escape=escape))
+ else:
+ func_1 = func_0
+
+ # Replace decimals and thousands if non-standard inputs detected
+ if decimal != "." or (thousands is not None and thousands != ","):
+ func_2 = _wrap_decimal_thousands(func_1, decimal=decimal, thousands=thousands)
+ else:
+ func_2 = func_1
+
+ # Render links
+ if hyperlinks is not None:
+ func_3 = lambda x: func_2(_render_href(x, format=hyperlinks))
+ else:
+ func_3 = func_2
+
+ # Replace missing values if na_rep
+ if na_rep is None:
+ return func_3
+ else:
+ return lambda x: na_rep if (isna(x) is True) else func_3(x)
+
+
+def non_reducing_slice(slice_: Subset):
+ """
+ Ensure that a slice doesn't reduce to a Series or Scalar.
+
+ Any user-passed `subset` should have this called on it
+ to make sure we're always working with DataFrames.
+ """
+ # default to column slice, like DataFrame
+ # ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
+ kinds = (ABCSeries, np.ndarray, Index, list, str)
+ if isinstance(slice_, kinds):
+ slice_ = IndexSlice[:, slice_]
+
+ def pred(part) -> bool:
+ """
+ Returns
+ -------
+ bool
+ True if slice does *not* reduce,
+ False if `part` is a tuple.
+ """
+ # true when slice does *not* reduce, False when part is a tuple,
+ # i.e. MultiIndex slice
+ if isinstance(part, tuple):
+ # GH#39421 check for sub-slice:
+ return any((isinstance(s, slice) or is_list_like(s)) for s in part)
+ else:
+ return isinstance(part, slice) or is_list_like(part)
+
+ if not is_list_like(slice_):
+ if not isinstance(slice_, slice):
+ # a 1-d slice, like df.loc[1]
+ slice_ = [[slice_]]
+ else:
+ # slice(a, b, c)
+ slice_ = [slice_] # to tuplize later
+ else:
+ # error: Item "slice" of "Union[slice, Sequence[Any]]" has no attribute
+ # "__iter__" (not iterable) -> is specifically list_like in conditional
+ slice_ = [p if pred(p) else [p] for p in slice_] # type: ignore[union-attr]
+ return tuple(slice_)
+
+
+def maybe_convert_css_to_tuples(style: CSSProperties) -> CSSList:
+ """
+ Convert css-string to sequence of tuples format if needed.
+ 'color:red; border:1px solid black;' -> [('color', 'red'),
+ ('border','1px solid red')]
+ """
+ if isinstance(style, str):
+ s = style.split(";")
+ try:
+ return [
+ (x.split(":")[0].strip(), x.split(":")[1].strip())
+ for x in s
+ if x.strip() != ""
+ ]
+ except IndexError:
+ raise ValueError(
+ "Styles supplied as string must follow CSS rule formats, "
+ f"for example 'attr: val;'. '{style}' was given."
+ )
+ return style
+
+
+def refactor_levels(
+ level: Level | list[Level] | None,
+ obj: Index,
+) -> list[int]:
+ """
+ Returns a consistent levels arg for use in ``hide_index`` or ``hide_columns``.
+
+ Parameters
+ ----------
+ level : int, str, list
+ Original ``level`` arg supplied to above methods.
+ obj:
+ Either ``self.index`` or ``self.columns``
+
+ Returns
+ -------
+ list : refactored arg with a list of levels to hide
+ """
+ if level is None:
+ levels_: list[int] = list(range(obj.nlevels))
+ elif isinstance(level, int):
+ levels_ = [level]
+ elif isinstance(level, str):
+ levels_ = [obj._get_level_number(level)]
+ elif isinstance(level, list):
+ levels_ = [
+ obj._get_level_number(lev) if not isinstance(lev, int) else lev
+ for lev in level
+ ]
+ else:
+ raise ValueError("`level` must be of type `int`, `str` or list of such")
+ return levels_
+
+
+class Tooltips:
+ """
+ An extension to ``Styler`` that allows for and manipulates tooltips on hover
+ of ```` cells in the HTML result.
+
+ Parameters
+ ----------
+ css_name: str, default "pd-t"
+ Name of the CSS class that controls visualisation of tooltips.
+ css_props: list-like, default; see Notes
+ List of (attr, value) tuples defining properties of the CSS class.
+ tooltips: DataFrame, default empty
+ DataFrame of strings aligned with underlying Styler data for tooltip
+ display.
+
+ Notes
+ -----
+ The default properties for the tooltip CSS class are:
+
+ - visibility: hidden
+ - position: absolute
+ - z-index: 1
+ - background-color: black
+ - color: white
+ - transform: translate(-20px, -20px)
+
+ Hidden visibility is a key prerequisite to the hover functionality, and should
+ always be included in any manual properties specification.
+ """
+
+ def __init__(
+ self,
+ css_props: CSSProperties = [
+ ("visibility", "hidden"),
+ ("position", "absolute"),
+ ("z-index", 1),
+ ("background-color", "black"),
+ ("color", "white"),
+ ("transform", "translate(-20px, -20px)"),
+ ],
+ css_name: str = "pd-t",
+ tooltips: DataFrame = DataFrame(),
+ ) -> None:
+ self.class_name = css_name
+ self.class_properties = css_props
+ self.tt_data = tooltips
+ self.table_styles: CSSStyles = []
+
+ @property
+ def _class_styles(self):
+ """
+ Combine the ``_Tooltips`` CSS class name and CSS properties to the format
+ required to extend the underlying ``Styler`` `table_styles` to allow
+ tooltips to render in HTML.
+
+ Returns
+ -------
+ styles : List
+ """
+ return [
+ {
+ "selector": f".{self.class_name}",
+ "props": maybe_convert_css_to_tuples(self.class_properties),
+ }
+ ]
+
+ def _pseudo_css(self, uuid: str, name: str, row: int, col: int, text: str):
+ """
+ For every table data-cell that has a valid tooltip (not None, NaN or
+ empty string) must create two pseudo CSS entries for the specific
+ element id which are added to overall table styles:
+ an on hover visibility change and a content change
+ dependent upon the user's chosen display string.
+
+ For example:
+ [{"selector": "T__row1_col1:hover .pd-t",
+ "props": [("visibility", "visible")]},
+ {"selector": "T__row1_col1 .pd-t::after",
+ "props": [("content", "Some Valid Text String")]}]
+
+ Parameters
+ ----------
+ uuid: str
+ The uuid of the Styler instance
+ name: str
+ The css-name of the class used for styling tooltips
+ row : int
+ The row index of the specified tooltip string data
+ col : int
+ The col index of the specified tooltip string data
+ text : str
+ The textual content of the tooltip to be displayed in HTML.
+
+ Returns
+ -------
+ pseudo_css : List
+ """
+ selector_id = "#T_" + uuid + "_row" + str(row) + "_col" + str(col)
+ return [
+ {
+ "selector": selector_id + f":hover .{name}",
+ "props": [("visibility", "visible")],
+ },
+ {
+ "selector": selector_id + f" .{name}::after",
+ "props": [("content", f'"{text}"')],
+ },
+ ]
+
+ def _translate(self, styler: StylerRenderer, d: dict):
+ """
+ Mutate the render dictionary to allow for tooltips:
+
+ - Add ```` HTML element to each data cells ``display_value``. Ignores
+ headers.
+ - Add table level CSS styles to control pseudo classes.
+
+ Parameters
+ ----------
+ styler_data : DataFrame
+ Underlying ``Styler`` DataFrame used for reindexing.
+ uuid : str
+ The underlying ``Styler`` uuid for CSS id.
+ d : dict
+ The dictionary prior to final render
+
+ Returns
+ -------
+ render_dict : Dict
+ """
+ self.tt_data = self.tt_data.reindex_like(styler.data)
+ if self.tt_data.empty:
+ return d
+
+ name = self.class_name
+ mask = (self.tt_data.isna()) | (self.tt_data.eq("")) # empty string = no ttip
+ self.table_styles = [
+ style
+ for sublist in [
+ self._pseudo_css(styler.uuid, name, i, j, str(self.tt_data.iloc[i, j]))
+ for i in range(len(self.tt_data.index))
+ for j in range(len(self.tt_data.columns))
+ if not (
+ mask.iloc[i, j]
+ or i in styler.hidden_rows
+ or j in styler.hidden_columns
+ )
+ ]
+ for style in sublist
+ ]
+
+ if self.table_styles:
+ # add span class to every cell only if at least 1 non-empty tooltip
+ for row in d["body"]:
+ for item in row:
+ if item["type"] == "td":
+ item["display_value"] = (
+ str(item["display_value"])
+ + f' '
+ )
+ d["table_styles"].extend(self._class_styles)
+ d["table_styles"].extend(self.table_styles)
+
+ return d
+
+
+def _parse_latex_table_wrapping(table_styles: CSSStyles, caption: str | None) -> bool:
+ """
+ Indicate whether LaTeX {tabular} should be wrapped with a {table} environment.
+
+ Parses the `table_styles` and detects any selectors which must be included outside
+ of {tabular}, i.e. indicating that wrapping must occur, and therefore return True,
+ or if a caption exists and requires similar.
+ """
+ IGNORED_WRAPPERS = ["toprule", "midrule", "bottomrule", "column_format"]
+ # ignored selectors are included with {tabular} so do not need wrapping
+ return (
+ table_styles is not None
+ and any(d["selector"] not in IGNORED_WRAPPERS for d in table_styles)
+ ) or caption is not None
+
+
+def _parse_latex_table_styles(table_styles: CSSStyles, selector: str) -> str | None:
+ """
+ Return the first 'props' 'value' from ``tables_styles`` identified by ``selector``.
+
+ Examples
+ --------
+ >>> table_styles = [{'selector': 'foo', 'props': [('attr','value')]},
+ ... {'selector': 'bar', 'props': [('attr', 'overwritten')]},
+ ... {'selector': 'bar', 'props': [('a1', 'baz'), ('a2', 'ignore')]}]
+ >>> _parse_latex_table_styles(table_styles, selector='bar')
+ 'baz'
+
+ Notes
+ -----
+ The replacement of "§" with ":" is to avoid the CSS problem where ":" has structural
+ significance and cannot be used in LaTeX labels, but is often required by them.
+ """
+ for style in table_styles[::-1]: # in reverse for most recently applied style
+ if style["selector"] == selector:
+ return str(style["props"][0][1]).replace("§", ":")
+ return None
+
+
+def _parse_latex_cell_styles(
+ latex_styles: CSSList, display_value: str, convert_css: bool = False
+) -> str:
+ r"""
+ Mutate the ``display_value`` string including LaTeX commands from ``latex_styles``.
+
+ This method builds a recursive latex chain of commands based on the
+ CSSList input, nested around ``display_value``.
+
+ If a CSS style is given as ('', '') this is translated to
+ '\{display_value}', and this value is treated as the
+ display value for the next iteration.
+
+ The most recent style forms the inner component, for example for styles:
+ `[('c1', 'o1'), ('c2', 'o2')]` this returns: `\c1o1{\c2o2{display_value}}`
+
+ Sometimes latex commands have to be wrapped with curly braces in different ways:
+ We create some parsing flags to identify the different behaviours:
+
+ - `--rwrap` : `\{}`
+ - `--wrap` : `{\ }`
+ - `--nowrap` : `\ `
+ - `--lwrap` : `{\} `
+ - `--dwrap` : `{\}{}`
+
+ For example for styles:
+ `[('c1', 'o1--wrap'), ('c2', 'o2')]` this returns: `{\c1o1 \c2o2{display_value}}
+ """
+ if convert_css:
+ latex_styles = _parse_latex_css_conversion(latex_styles)
+ for command, options in latex_styles[::-1]: # in reverse for most recent style
+ formatter = {
+ "--wrap": f"{{\\{command}--to_parse {display_value}}}",
+ "--nowrap": f"\\{command}--to_parse {display_value}",
+ "--lwrap": f"{{\\{command}--to_parse}} {display_value}",
+ "--rwrap": f"\\{command}--to_parse{{{display_value}}}",
+ "--dwrap": f"{{\\{command}--to_parse}}{{{display_value}}}",
+ }
+ display_value = f"\\{command}{options} {display_value}"
+ for arg in ["--nowrap", "--wrap", "--lwrap", "--rwrap", "--dwrap"]:
+ if arg in str(options):
+ display_value = formatter[arg].replace(
+ "--to_parse", _parse_latex_options_strip(value=options, arg=arg)
+ )
+ break # only ever one purposeful entry
+ return display_value
+
+
+def _parse_latex_header_span(
+ cell: dict[str, Any],
+ multirow_align: str,
+ multicol_align: str,
+ wrap: bool = False,
+ convert_css: bool = False,
+) -> str:
+ r"""
+ Refactor the cell `display_value` if a 'colspan' or 'rowspan' attribute is present.
+
+ 'rowspan' and 'colspan' do not occur simultaneouly. If they are detected then
+ the `display_value` is altered to a LaTeX `multirow` or `multicol` command
+ respectively, with the appropriate cell-span.
+
+ ``wrap`` is used to enclose the `display_value` in braces which is needed for
+ column headers using an siunitx package.
+
+ Requires the package {multirow}, whereas multicol support is usually built in
+ to the {tabular} environment.
+
+ Examples
+ --------
+ >>> cell = {'cellstyle': '', 'display_value':'text', 'attributes': 'colspan="3"'}
+ >>> _parse_latex_header_span(cell, 't', 'c')
+ '\\multicolumn{3}{c}{text}'
+ """
+ display_val = _parse_latex_cell_styles(
+ cell["cellstyle"], cell["display_value"], convert_css
+ )
+ if "attributes" in cell:
+ attrs = cell["attributes"]
+ if 'colspan="' in attrs:
+ colspan = attrs[attrs.find('colspan="') + 9 :] # len('colspan="') = 9
+ colspan = int(colspan[: colspan.find('"')])
+ if "naive-l" == multicol_align:
+ out = f"{{{display_val}}}" if wrap else f"{display_val}"
+ blanks = " & {}" if wrap else " &"
+ return out + blanks * (colspan - 1)
+ elif "naive-r" == multicol_align:
+ out = f"{{{display_val}}}" if wrap else f"{display_val}"
+ blanks = "{} & " if wrap else "& "
+ return blanks * (colspan - 1) + out
+ return f"\\multicolumn{{{colspan}}}{{{multicol_align}}}{{{display_val}}}"
+ elif 'rowspan="' in attrs:
+ if multirow_align == "naive":
+ return display_val
+ rowspan = attrs[attrs.find('rowspan="') + 9 :]
+ rowspan = int(rowspan[: rowspan.find('"')])
+ return f"\\multirow[{multirow_align}]{{{rowspan}}}{{*}}{{{display_val}}}"
+ if wrap:
+ return f"{{{display_val}}}"
+ else:
+ return display_val
+
+
+def _parse_latex_options_strip(value: str | float, arg: str) -> str:
+ """
+ Strip a css_value which may have latex wrapping arguments, css comment identifiers,
+ and whitespaces, to a valid string for latex options parsing.
+
+ For example: 'red /* --wrap */ ' --> 'red'
+ """
+ return str(value).replace(arg, "").replace("/*", "").replace("*/", "").strip()
+
+
+def _parse_latex_css_conversion(styles: CSSList) -> CSSList:
+ """
+ Convert CSS (attribute,value) pairs to equivalent LaTeX (command,options) pairs.
+
+ Ignore conversion if tagged with `--latex` option, skipped if no conversion found.
+ """
+
+ def font_weight(value, arg):
+ if value in ("bold", "bolder"):
+ return "bfseries", f"{arg}"
+ return None
+
+ def font_style(value, arg):
+ if value == "italic":
+ return "itshape", f"{arg}"
+ if value == "oblique":
+ return "slshape", f"{arg}"
+ return None
+
+ def color(value, user_arg, command, comm_arg):
+ """
+ CSS colors have 5 formats to process:
+
+ - 6 digit hex code: "#ff23ee" --> [HTML]{FF23EE}
+ - 3 digit hex code: "#f0e" --> [HTML]{FF00EE}
+ - rgba: rgba(128, 255, 0, 0.5) --> [rgb]{0.502, 1.000, 0.000}
+ - rgb: rgb(128, 255, 0,) --> [rbg]{0.502, 1.000, 0.000}
+ - string: red --> {red}
+
+ Additionally rgb or rgba can be expressed in % which is also parsed.
+ """
+ arg = user_arg if user_arg != "" else comm_arg
+
+ if value[0] == "#" and len(value) == 7: # color is hex code
+ return command, f"[HTML]{{{value[1:].upper()}}}{arg}"
+ if value[0] == "#" and len(value) == 4: # color is short hex code
+ val = f"{value[1].upper()*2}{value[2].upper()*2}{value[3].upper()*2}"
+ return command, f"[HTML]{{{val}}}{arg}"
+ elif value[:3] == "rgb": # color is rgb or rgba
+ r = re.findall("(?<=\\()[0-9\\s%]+(?=,)", value)[0].strip()
+ r = float(r[:-1]) / 100 if "%" in r else int(r) / 255
+ g = re.findall("(?<=,)[0-9\\s%]+(?=,)", value)[0].strip()
+ g = float(g[:-1]) / 100 if "%" in g else int(g) / 255
+ if value[3] == "a": # color is rgba
+ b = re.findall("(?<=,)[0-9\\s%]+(?=,)", value)[1].strip()
+ else: # color is rgb
+ b = re.findall("(?<=,)[0-9\\s%]+(?=\\))", value)[0].strip()
+ b = float(b[:-1]) / 100 if "%" in b else int(b) / 255
+ return command, f"[rgb]{{{r:.3f}, {g:.3f}, {b:.3f}}}{arg}"
+ else:
+ return command, f"{{{value}}}{arg}" # color is likely string-named
+
+ CONVERTED_ATTRIBUTES: dict[str, Callable] = {
+ "font-weight": font_weight,
+ "background-color": partial(color, command="cellcolor", comm_arg="--lwrap"),
+ "color": partial(color, command="color", comm_arg=""),
+ "font-style": font_style,
+ }
+
+ latex_styles: CSSList = []
+ for attribute, value in styles:
+ if isinstance(value, str) and "--latex" in value:
+ # return the style without conversion but drop '--latex'
+ latex_styles.append((attribute, value.replace("--latex", "")))
+ if attribute in CONVERTED_ATTRIBUTES:
+ arg = ""
+ for x in ["--wrap", "--nowrap", "--lwrap", "--dwrap", "--rwrap"]:
+ if x in str(value):
+ arg, value = x, _parse_latex_options_strip(value, x)
+ break
+ latex_style = CONVERTED_ATTRIBUTES[attribute](value, arg)
+ if latex_style is not None:
+ latex_styles.extend([latex_style])
+ return latex_styles
+
+
+def _escape_latex(s):
+ r"""
+ Replace the characters ``&``, ``%``, ``$``, ``#``, ``_``, ``{``, ``}``,
+ ``~``, ``^``, and ``\`` in the string with LaTeX-safe sequences.
+
+ Use this if you need to display text that might contain such characters in LaTeX.
+
+ Parameters
+ ----------
+ s : str
+ Input to be escaped
+
+ Return
+ ------
+ str :
+ Escaped string
+ """
+ return (
+ s.replace("\\", "ab2§=§8yz") # rare string for final conversion: avoid \\ clash
+ .replace("ab2§=§8yz ", "ab2§=§8yz\\space ") # since \backslash gobbles spaces
+ .replace("&", "\\&")
+ .replace("%", "\\%")
+ .replace("$", "\\$")
+ .replace("#", "\\#")
+ .replace("_", "\\_")
+ .replace("{", "\\{")
+ .replace("}", "\\}")
+ .replace("~ ", "~\\space ") # since \textasciitilde gobbles spaces
+ .replace("~", "\\textasciitilde ")
+ .replace("^ ", "^\\space ") # since \textasciicircum gobbles spaces
+ .replace("^", "\\textasciicircum ")
+ .replace("ab2§=§8yz", "\\textbackslash ")
+ )
+
+
+def _math_mode_with_dollar(s):
+ r"""
+ All characters in LaTeX math mode are preserved.
+
+ The substrings in LaTeX math mode, which start with
+ the character ``$`` and end with ``$``, are preserved
+ without escaping. Otherwise regular LaTeX escaping applies.
+
+ Parameters
+ ----------
+ s : str
+ Input to be escaped
+
+ Return
+ ------
+ str :
+ Escaped string
+ """
+ s = s.replace(r"\$", r"rt8§=§7wz")
+ pattern = re.compile(r"\$.*?\$")
+ pos = 0
+ ps = pattern.search(s, pos)
+ res = []
+ while ps:
+ res.append(_escape_latex(s[pos : ps.span()[0]]))
+ res.append(ps.group())
+ pos = ps.span()[1]
+ ps = pattern.search(s, pos)
+
+ res.append(_escape_latex(s[pos : len(s)]))
+ return "".join(res).replace(r"rt8§=§7wz", r"\$")
+
+
+def _math_mode_with_parentheses(s):
+ r"""
+ All characters in LaTeX math mode are preserved.
+
+ The substrings in LaTeX math mode, which start with
+ the character ``\(`` and end with ``\)``, are preserved
+ without escaping. Otherwise regular LaTeX escaping applies.
+
+ Parameters
+ ----------
+ s : str
+ Input to be escaped
+
+ Return
+ ------
+ str :
+ Escaped string
+ """
+ s = s.replace(r"\(", r"LEFT§=§6yzLEFT").replace(r"\)", r"RIGHTab5§=§RIGHT")
+ res = []
+ for item in re.split(r"LEFT§=§6yz|ab5§=§RIGHT", s):
+ if item.startswith("LEFT") and item.endswith("RIGHT"):
+ res.append(item.replace("LEFT", r"\(").replace("RIGHT", r"\)"))
+ elif "LEFT" in item and "RIGHT" in item:
+ res.append(
+ _escape_latex(item).replace("LEFT", r"\(").replace("RIGHT", r"\)")
+ )
+ else:
+ res.append(
+ _escape_latex(item)
+ .replace("LEFT", r"\textbackslash (")
+ .replace("RIGHT", r"\textbackslash )")
+ )
+ return "".join(res)
+
+
+def _escape_latex_math(s):
+ r"""
+ All characters in LaTeX math mode are preserved.
+
+ The substrings in LaTeX math mode, which either are surrounded
+ by two characters ``$`` or start with the character ``\(`` and end with ``\)``,
+ are preserved without escaping. Otherwise regular LaTeX escaping applies.
+
+ Parameters
+ ----------
+ s : str
+ Input to be escaped
+
+ Return
+ ------
+ str :
+ Escaped string
+ """
+ s = s.replace(r"\$", r"rt8§=§7wz")
+ ps_d = re.compile(r"\$.*?\$").search(s, 0)
+ ps_p = re.compile(r"\(.*?\)").search(s, 0)
+ mode = []
+ if ps_d:
+ mode.append(ps_d.span()[0])
+ if ps_p:
+ mode.append(ps_p.span()[0])
+ if len(mode) == 0:
+ return _escape_latex(s.replace(r"rt8§=§7wz", r"\$"))
+ if s[mode[0]] == r"$":
+ return _math_mode_with_dollar(s.replace(r"rt8§=§7wz", r"\$"))
+ if s[mode[0] - 1 : mode[0] + 1] == r"\(":
+ return _math_mode_with_parentheses(s.replace(r"rt8§=§7wz", r"\$"))
+ else:
+ return _escape_latex(s.replace(r"rt8§=§7wz", r"\$"))
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/html.tpl b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/html.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..8c63be3ad788a8abddf3588b2b9dd6d6126f5df3
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/html.tpl
@@ -0,0 +1,16 @@
+{# Update the html_style/table_structure.html documentation too #}
+{% if doctype_html %}
+
+
+
+
+{% if not exclude_styles %}{% include html_style_tpl %}{% endif %}
+
+
+{% include html_table_tpl %}
+
+
+{% elif not doctype_html %}
+{% if not exclude_styles %}{% include html_style_tpl %}{% endif %}
+{% include html_table_tpl %}
+{% endif %}
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/html_style.tpl b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/html_style.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..5c3fcd97f51bbec263399922579420dfa9ceef9c
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/html_style.tpl
@@ -0,0 +1,26 @@
+{%- block before_style -%}{%- endblock before_style -%}
+{% block style %}
+
+{% endblock style %}
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/html_table.tpl b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/html_table.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..17118d2bb21ccd185780d44c83a5242b12bd2a0d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/html_table.tpl
@@ -0,0 +1,63 @@
+{% block before_table %}{% endblock before_table %}
+{% block table %}
+{% if exclude_styles %}
+
+{% else %}
+
+{% endif %}
+{% block caption %}
+{% if caption and caption is string %}
+ {{caption}}
+{% elif caption and caption is sequence %}
+ {{caption[0]}}
+{% endif %}
+{% endblock caption %}
+{% block thead %}
+
+{% block before_head_rows %}{% endblock %}
+{% for r in head %}
+{% block head_tr scoped %}
+
+{% if exclude_styles %}
+{% for c in r %}
+{% if c.is_visible != False %}
+ <{{c.type}} {{c.attributes}}>{{c.display_value}}{{c.type}}>
+{% endif %}
+{% endfor %}
+{% else %}
+{% for c in r %}
+{% if c.is_visible != False %}
+ <{{c.type}} {%- if c.id is defined %} id="T_{{uuid}}_{{c.id}}" {%- endif %} class="{{c.class}}" {{c.attributes}}>{{c.display_value}}{{c.type}}>
+{% endif %}
+{% endfor %}
+{% endif %}
+
+{% endblock head_tr %}
+{% endfor %}
+{% block after_head_rows %}{% endblock %}
+
+{% endblock thead %}
+{% block tbody %}
+
+{% block before_rows %}{% endblock before_rows %}
+{% for r in body %}
+{% block tr scoped %}
+
+{% if exclude_styles %}
+{% for c in r %}{% if c.is_visible != False %}
+ <{{c.type}} {{c.attributes}}>{{c.display_value}}{{c.type}}>
+{% endif %}{% endfor %}
+{% else %}
+{% for c in r %}{% if c.is_visible != False %}
+ <{{c.type}} {%- if c.id is defined %} id="T_{{uuid}}_{{c.id}}" {%- endif %} class="{{c.class}}" {{c.attributes}}>{{c.display_value}}{{c.type}}>
+{% endif %}{% endfor %}
+{% endif %}
+
+{% endblock tr %}
+{% endfor %}
+{% block after_rows %}{% endblock after_rows %}
+
+{% endblock tbody %}
+
+{% endblock table %}
+{% block after_table %}{% endblock after_table %}
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/latex.tpl b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/latex.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..ae341bbc29823489d9d15e354fae0ce2e10a046d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/latex.tpl
@@ -0,0 +1,5 @@
+{% if environment == "longtable" %}
+{% include "latex_longtable.tpl" %}
+{% else %}
+{% include "latex_table.tpl" %}
+{% endif %}
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/latex_longtable.tpl b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/latex_longtable.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..b97843eeb918da1b12f6f2edd585c8e42d6b7bb5
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/latex_longtable.tpl
@@ -0,0 +1,82 @@
+\begin{longtable}
+{%- set position = parse_table(table_styles, 'position') %}
+{%- if position is not none %}
+[{{position}}]
+{%- endif %}
+{%- set column_format = parse_table(table_styles, 'column_format') %}
+{% raw %}{{% endraw %}{{column_format}}{% raw %}}{% endraw %}
+
+{% for style in table_styles %}
+{% if style['selector'] not in ['position', 'position_float', 'caption', 'toprule', 'midrule', 'bottomrule', 'column_format', 'label'] %}
+\{{style['selector']}}{{parse_table(table_styles, style['selector'])}}
+{% endif %}
+{% endfor %}
+{% if caption and caption is string %}
+\caption{% raw %}{{% endraw %}{{caption}}{% raw %}}{% endraw %}
+{%- set label = parse_table(table_styles, 'label') %}
+{%- if label is not none %}
+ \label{{label}}
+{%- endif %} \\
+{% elif caption and caption is sequence %}
+\caption[{{caption[1]}}]{% raw %}{{% endraw %}{{caption[0]}}{% raw %}}{% endraw %}
+{%- set label = parse_table(table_styles, 'label') %}
+{%- if label is not none %}
+ \label{{label}}
+{%- endif %} \\
+{% else %}
+{%- set label = parse_table(table_styles, 'label') %}
+{%- if label is not none %}
+\label{{label}} \\
+{% endif %}
+{% endif %}
+{% set toprule = parse_table(table_styles, 'toprule') %}
+{% if toprule is not none %}
+\{{toprule}}
+{% endif %}
+{% for row in head %}
+{% for c in row %}{%- if not loop.first %} & {% endif %}{{parse_header(c, multirow_align, multicol_align, siunitx)}}{% endfor %} \\
+{% endfor %}
+{% set midrule = parse_table(table_styles, 'midrule') %}
+{% if midrule is not none %}
+\{{midrule}}
+{% endif %}
+\endfirsthead
+{% if caption and caption is string %}
+\caption[]{% raw %}{{% endraw %}{{caption}}{% raw %}}{% endraw %} \\
+{% elif caption and caption is sequence %}
+\caption[]{% raw %}{{% endraw %}{{caption[0]}}{% raw %}}{% endraw %} \\
+{% endif %}
+{% if toprule is not none %}
+\{{toprule}}
+{% endif %}
+{% for row in head %}
+{% for c in row %}{%- if not loop.first %} & {% endif %}{{parse_header(c, multirow_align, multicol_align, siunitx)}}{% endfor %} \\
+{% endfor %}
+{% if midrule is not none %}
+\{{midrule}}
+{% endif %}
+\endhead
+{% if midrule is not none %}
+\{{midrule}}
+{% endif %}
+\multicolumn{% raw %}{{% endraw %}{{body[0]|length}}{% raw %}}{% endraw %}{r}{Continued on next page} \\
+{% if midrule is not none %}
+\{{midrule}}
+{% endif %}
+\endfoot
+{% set bottomrule = parse_table(table_styles, 'bottomrule') %}
+{% if bottomrule is not none %}
+\{{bottomrule}}
+{% endif %}
+\endlastfoot
+{% for row in body %}
+{% for c in row %}{% if not loop.first %} & {% endif %}
+ {%- if c.type == 'th' %}{{parse_header(c, multirow_align, multicol_align)}}{% else %}{{parse_cell(c.cellstyle, c.display_value, convert_css)}}{% endif %}
+{%- endfor %} \\
+{% if clines and clines[loop.index] | length > 0 %}
+ {%- for cline in clines[loop.index] %}{% if not loop.first %} {% endif %}{{ cline }}{% endfor %}
+
+{% endif %}
+{% endfor %}
+\end{longtable}
+{% raw %}{% endraw %}
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/latex_table.tpl b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/latex_table.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..7858cb4c945534a4d21cd4474460fd1abcf01f82
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/latex_table.tpl
@@ -0,0 +1,57 @@
+{% if environment or parse_wrap(table_styles, caption) %}
+\begin{% raw %}{{% endraw %}{{environment if environment else "table"}}{% raw %}}{% endraw %}
+{%- set position = parse_table(table_styles, 'position') %}
+{%- if position is not none %}
+[{{position}}]
+{%- endif %}
+
+{% set position_float = parse_table(table_styles, 'position_float') %}
+{% if position_float is not none%}
+\{{position_float}}
+{% endif %}
+{% if caption and caption is string %}
+\caption{% raw %}{{% endraw %}{{caption}}{% raw %}}{% endraw %}
+
+{% elif caption and caption is sequence %}
+\caption[{{caption[1]}}]{% raw %}{{% endraw %}{{caption[0]}}{% raw %}}{% endraw %}
+
+{% endif %}
+{% for style in table_styles %}
+{% if style['selector'] not in ['position', 'position_float', 'caption', 'toprule', 'midrule', 'bottomrule', 'column_format'] %}
+\{{style['selector']}}{{parse_table(table_styles, style['selector'])}}
+{% endif %}
+{% endfor %}
+{% endif %}
+\begin{tabular}
+{%- set column_format = parse_table(table_styles, 'column_format') %}
+{% raw %}{{% endraw %}{{column_format}}{% raw %}}{% endraw %}
+
+{% set toprule = parse_table(table_styles, 'toprule') %}
+{% if toprule is not none %}
+\{{toprule}}
+{% endif %}
+{% for row in head %}
+{% for c in row %}{%- if not loop.first %} & {% endif %}{{parse_header(c, multirow_align, multicol_align, siunitx, convert_css)}}{% endfor %} \\
+{% endfor %}
+{% set midrule = parse_table(table_styles, 'midrule') %}
+{% if midrule is not none %}
+\{{midrule}}
+{% endif %}
+{% for row in body %}
+{% for c in row %}{% if not loop.first %} & {% endif %}
+ {%- if c.type == 'th' %}{{parse_header(c, multirow_align, multicol_align, False, convert_css)}}{% else %}{{parse_cell(c.cellstyle, c.display_value, convert_css)}}{% endif %}
+{%- endfor %} \\
+{% if clines and clines[loop.index] | length > 0 %}
+ {%- for cline in clines[loop.index] %}{% if not loop.first %} {% endif %}{{ cline }}{% endfor %}
+
+{% endif %}
+{% endfor %}
+{% set bottomrule = parse_table(table_styles, 'bottomrule') %}
+{% if bottomrule is not none %}
+\{{bottomrule}}
+{% endif %}
+\end{tabular}
+{% if environment or parse_wrap(table_styles, caption) %}
+\end{% raw %}{{% endraw %}{{environment if environment else "table"}}{% raw %}}{% endraw %}
+
+{% endif %}
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/string.tpl b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/string.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..06aeb2b4e413c61a912b535056c19c794d4b9c85
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/templates/string.tpl
@@ -0,0 +1,12 @@
+{% for r in head %}
+{% for c in r %}{% if c["is_visible"] %}
+{{ c["display_value"] }}{% if not loop.last %}{{ delimiter }}{% endif %}
+{% endif %}{% endfor %}
+
+{% endfor %}
+{% for r in body %}
+{% for c in r %}{% if c["is_visible"] %}
+{{ c["display_value"] }}{% if not loop.last %}{{ delimiter }}{% endif %}
+{% endif %}{% endfor %}
+
+{% endfor %}
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/xml.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/xml.py
new file mode 100644
index 0000000000000000000000000000000000000000..76b938755755aaef7f2a15da3ee223ce719df958
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/formats/xml.py
@@ -0,0 +1,536 @@
+"""
+:mod:`pandas.io.formats.xml` is a module for formatting data in XML.
+"""
+from __future__ import annotations
+
+import codecs
+import io
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from pandas.errors import AbstractMethodError
+from pandas.util._decorators import doc
+
+from pandas.core.dtypes.common import is_list_like
+from pandas.core.dtypes.missing import isna
+
+from pandas.core.shared_docs import _shared_docs
+
+from pandas.io.common import get_handle
+from pandas.io.xml import (
+ get_data_from_filepath,
+ preprocess_data,
+)
+
+if TYPE_CHECKING:
+ from pandas._typing import (
+ CompressionOptions,
+ FilePath,
+ ReadBuffer,
+ StorageOptions,
+ WriteBuffer,
+ )
+
+ from pandas import DataFrame
+
+
+@doc(
+ storage_options=_shared_docs["storage_options"],
+ compression_options=_shared_docs["compression_options"] % "path_or_buffer",
+)
+class BaseXMLFormatter:
+ """
+ Subclass for formatting data in XML.
+
+ Parameters
+ ----------
+ path_or_buffer : str or file-like
+ This can be either a string of raw XML, a valid URL,
+ file or file-like object.
+
+ index : bool
+ Whether to include index in xml document.
+
+ row_name : str
+ Name for root of xml document. Default is 'data'.
+
+ root_name : str
+ Name for row elements of xml document. Default is 'row'.
+
+ na_rep : str
+ Missing data representation.
+
+ attrs_cols : list
+ List of columns to write as attributes in row element.
+
+ elem_cols : list
+ List of columns to write as children in row element.
+
+ namespaces : dict
+ The namespaces to define in XML document as dicts with key
+ being namespace and value the URI.
+
+ prefix : str
+ The prefix for each element in XML document including root.
+
+ encoding : str
+ Encoding of xml object or document.
+
+ xml_declaration : bool
+ Whether to include xml declaration at top line item in xml.
+
+ pretty_print : bool
+ Whether to write xml document with line breaks and indentation.
+
+ stylesheet : str or file-like
+ A URL, file, file-like object, or a raw string containing XSLT.
+
+ {compression_options}
+
+ .. versionchanged:: 1.4.0 Zstandard support.
+
+ {storage_options}
+
+ See also
+ --------
+ pandas.io.formats.xml.EtreeXMLFormatter
+ pandas.io.formats.xml.LxmlXMLFormatter
+
+ """
+
+ def __init__(
+ self,
+ frame: DataFrame,
+ path_or_buffer: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None,
+ index: bool = True,
+ root_name: str | None = "data",
+ row_name: str | None = "row",
+ na_rep: str | None = None,
+ attr_cols: list[str] | None = None,
+ elem_cols: list[str] | None = None,
+ namespaces: dict[str | None, str] | None = None,
+ prefix: str | None = None,
+ encoding: str = "utf-8",
+ xml_declaration: bool | None = True,
+ pretty_print: bool | None = True,
+ stylesheet: FilePath | ReadBuffer[str] | ReadBuffer[bytes] | None = None,
+ compression: CompressionOptions = "infer",
+ storage_options: StorageOptions | None = None,
+ ) -> None:
+ self.frame = frame
+ self.path_or_buffer = path_or_buffer
+ self.index = index
+ self.root_name = root_name
+ self.row_name = row_name
+ self.na_rep = na_rep
+ self.attr_cols = attr_cols
+ self.elem_cols = elem_cols
+ self.namespaces = namespaces
+ self.prefix = prefix
+ self.encoding = encoding
+ self.xml_declaration = xml_declaration
+ self.pretty_print = pretty_print
+ self.stylesheet = stylesheet
+ self.compression: CompressionOptions = compression
+ self.storage_options = storage_options
+
+ self.orig_cols = self.frame.columns.tolist()
+ self.frame_dicts = self.process_dataframe()
+
+ self.validate_columns()
+ self.validate_encoding()
+ self.prefix_uri = self.get_prefix_uri()
+ self.handle_indexes()
+
+ def build_tree(self) -> bytes:
+ """
+ Build tree from data.
+
+ This method initializes the root and builds attributes and elements
+ with optional namespaces.
+ """
+ raise AbstractMethodError(self)
+
+ def validate_columns(self) -> None:
+ """
+ Validate elems_cols and attrs_cols.
+
+ This method will check if columns is list-like.
+
+ Raises
+ ------
+ ValueError
+ * If value is not a list and less then length of nodes.
+ """
+ if self.attr_cols and not is_list_like(self.attr_cols):
+ raise TypeError(
+ f"{type(self.attr_cols).__name__} is not a valid type for attr_cols"
+ )
+
+ if self.elem_cols and not is_list_like(self.elem_cols):
+ raise TypeError(
+ f"{type(self.elem_cols).__name__} is not a valid type for elem_cols"
+ )
+
+ def validate_encoding(self) -> None:
+ """
+ Validate encoding.
+
+ This method will check if encoding is among listed under codecs.
+
+ Raises
+ ------
+ LookupError
+ * If encoding is not available in codecs.
+ """
+
+ codecs.lookup(self.encoding)
+
+ def process_dataframe(self) -> dict[int | str, dict[str, Any]]:
+ """
+ Adjust Data Frame to fit xml output.
+
+ This method will adjust underlying data frame for xml output,
+ including optionally replacing missing values and including indexes.
+ """
+
+ df = self.frame
+
+ if self.index:
+ df = df.reset_index()
+
+ if self.na_rep is not None:
+ df = df.fillna(self.na_rep)
+
+ return df.to_dict(orient="index")
+
+ def handle_indexes(self) -> None:
+ """
+ Handle indexes.
+
+ This method will add indexes into attr_cols or elem_cols.
+ """
+
+ if not self.index:
+ return
+
+ first_key = next(iter(self.frame_dicts))
+ indexes: list[str] = [
+ x for x in self.frame_dicts[first_key].keys() if x not in self.orig_cols
+ ]
+
+ if self.attr_cols:
+ self.attr_cols = indexes + self.attr_cols
+
+ if self.elem_cols:
+ self.elem_cols = indexes + self.elem_cols
+
+ def get_prefix_uri(self) -> str:
+ """
+ Get uri of namespace prefix.
+
+ This method retrieves corresponding URI to prefix in namespaces.
+
+ Raises
+ ------
+ KeyError
+ *If prefix is not included in namespace dict.
+ """
+
+ raise AbstractMethodError(self)
+
+ def other_namespaces(self) -> dict:
+ """
+ Define other namespaces.
+
+ This method will build dictionary of namespaces attributes
+ for root element, conditionally with optional namespaces and
+ prefix.
+ """
+
+ nmsp_dict: dict[str, str] = {}
+ if self.namespaces:
+ nmsp_dict = {
+ f"xmlns{p if p=='' else f':{p}'}": n
+ for p, n in self.namespaces.items()
+ if n != self.prefix_uri[1:-1]
+ }
+
+ return nmsp_dict
+
+ def build_attribs(self, d: dict[str, Any], elem_row: Any) -> Any:
+ """
+ Create attributes of row.
+
+ This method adds attributes using attr_cols to row element and
+ works with tuples for multindex or hierarchical columns.
+ """
+
+ if not self.attr_cols:
+ return elem_row
+
+ for col in self.attr_cols:
+ attr_name = self._get_flat_col_name(col)
+ try:
+ if not isna(d[col]):
+ elem_row.attrib[attr_name] = str(d[col])
+ except KeyError:
+ raise KeyError(f"no valid column, {col}")
+ return elem_row
+
+ def _get_flat_col_name(self, col: str | tuple) -> str:
+ flat_col = col
+ if isinstance(col, tuple):
+ flat_col = (
+ "".join([str(c) for c in col]).strip()
+ if "" in col
+ else "_".join([str(c) for c in col]).strip()
+ )
+ return f"{self.prefix_uri}{flat_col}"
+
+ def build_elems(self, d: dict[str, Any], elem_row: Any) -> None:
+ """
+ Create child elements of row.
+
+ This method adds child elements using elem_cols to row element and
+ works with tuples for multindex or hierarchical columns.
+ """
+
+ raise AbstractMethodError(self)
+
+ def _build_elems(self, sub_element_cls, d: dict[str, Any], elem_row: Any) -> None:
+ if not self.elem_cols:
+ return
+
+ for col in self.elem_cols:
+ elem_name = self._get_flat_col_name(col)
+ try:
+ val = None if isna(d[col]) or d[col] == "" else str(d[col])
+ sub_element_cls(elem_row, elem_name).text = val
+ except KeyError:
+ raise KeyError(f"no valid column, {col}")
+
+ def write_output(self) -> str | None:
+ xml_doc = self.build_tree()
+
+ if self.path_or_buffer is not None:
+ with get_handle(
+ self.path_or_buffer,
+ "wb",
+ compression=self.compression,
+ storage_options=self.storage_options,
+ is_text=False,
+ ) as handles:
+ handles.handle.write(xml_doc)
+ return None
+
+ else:
+ return xml_doc.decode(self.encoding).rstrip()
+
+
+class EtreeXMLFormatter(BaseXMLFormatter):
+ """
+ Class for formatting data in xml using Python standard library
+ modules: `xml.etree.ElementTree` and `xml.dom.minidom`.
+ """
+
+ def build_tree(self) -> bytes:
+ from xml.etree.ElementTree import (
+ Element,
+ SubElement,
+ tostring,
+ )
+
+ self.root = Element(
+ f"{self.prefix_uri}{self.root_name}", attrib=self.other_namespaces()
+ )
+
+ for d in self.frame_dicts.values():
+ elem_row = SubElement(self.root, f"{self.prefix_uri}{self.row_name}")
+
+ if not self.attr_cols and not self.elem_cols:
+ self.elem_cols = list(d.keys())
+ self.build_elems(d, elem_row)
+
+ else:
+ elem_row = self.build_attribs(d, elem_row)
+ self.build_elems(d, elem_row)
+
+ self.out_xml = tostring(
+ self.root,
+ method="xml",
+ encoding=self.encoding,
+ xml_declaration=self.xml_declaration,
+ )
+
+ if self.pretty_print:
+ self.out_xml = self.prettify_tree()
+
+ if self.stylesheet is not None:
+ raise ValueError(
+ "To use stylesheet, you need lxml installed and selected as parser."
+ )
+
+ return self.out_xml
+
+ def get_prefix_uri(self) -> str:
+ from xml.etree.ElementTree import register_namespace
+
+ uri = ""
+ if self.namespaces:
+ for p, n in self.namespaces.items():
+ if isinstance(p, str) and isinstance(n, str):
+ register_namespace(p, n)
+ if self.prefix:
+ try:
+ uri = f"{{{self.namespaces[self.prefix]}}}"
+ except KeyError:
+ raise KeyError(f"{self.prefix} is not included in namespaces")
+ elif "" in self.namespaces:
+ uri = f'{{{self.namespaces[""]}}}'
+ else:
+ uri = ""
+
+ return uri
+
+ def build_elems(self, d: dict[str, Any], elem_row: Any) -> None:
+ from xml.etree.ElementTree import SubElement
+
+ self._build_elems(SubElement, d, elem_row)
+
+ def prettify_tree(self) -> bytes:
+ """
+ Output tree for pretty print format.
+
+ This method will pretty print xml with line breaks and indentation.
+ """
+
+ from xml.dom.minidom import parseString
+
+ dom = parseString(self.out_xml)
+
+ return dom.toprettyxml(indent=" ", encoding=self.encoding)
+
+
+class LxmlXMLFormatter(BaseXMLFormatter):
+ """
+ Class for formatting data in xml using Python standard library
+ modules: `xml.etree.ElementTree` and `xml.dom.minidom`.
+ """
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+
+ self.convert_empty_str_key()
+
+ def build_tree(self) -> bytes:
+ """
+ Build tree from data.
+
+ This method initializes the root and builds attributes and elements
+ with optional namespaces.
+ """
+ from lxml.etree import (
+ Element,
+ SubElement,
+ tostring,
+ )
+
+ self.root = Element(f"{self.prefix_uri}{self.root_name}", nsmap=self.namespaces)
+
+ for d in self.frame_dicts.values():
+ elem_row = SubElement(self.root, f"{self.prefix_uri}{self.row_name}")
+
+ if not self.attr_cols and not self.elem_cols:
+ self.elem_cols = list(d.keys())
+ self.build_elems(d, elem_row)
+
+ else:
+ elem_row = self.build_attribs(d, elem_row)
+ self.build_elems(d, elem_row)
+
+ self.out_xml = tostring(
+ self.root,
+ pretty_print=self.pretty_print,
+ method="xml",
+ encoding=self.encoding,
+ xml_declaration=self.xml_declaration,
+ )
+
+ if self.stylesheet is not None:
+ self.out_xml = self.transform_doc()
+
+ return self.out_xml
+
+ def convert_empty_str_key(self) -> None:
+ """
+ Replace zero-length string in `namespaces`.
+
+ This method will replace '' with None to align to `lxml`
+ requirement that empty string prefixes are not allowed.
+ """
+
+ if self.namespaces and "" in self.namespaces.keys():
+ self.namespaces[None] = self.namespaces.pop("", "default")
+
+ def get_prefix_uri(self) -> str:
+ uri = ""
+ if self.namespaces:
+ if self.prefix:
+ try:
+ uri = f"{{{self.namespaces[self.prefix]}}}"
+ except KeyError:
+ raise KeyError(f"{self.prefix} is not included in namespaces")
+ elif "" in self.namespaces:
+ uri = f'{{{self.namespaces[""]}}}'
+ else:
+ uri = ""
+
+ return uri
+
+ def build_elems(self, d: dict[str, Any], elem_row: Any) -> None:
+ from lxml.etree import SubElement
+
+ self._build_elems(SubElement, d, elem_row)
+
+ def transform_doc(self) -> bytes:
+ """
+ Parse stylesheet from file or buffer and run it.
+
+ This method will parse stylesheet object into tree for parsing
+ conditionally by its specific object type, then transforms
+ original tree with XSLT script.
+ """
+ from lxml.etree import (
+ XSLT,
+ XMLParser,
+ fromstring,
+ parse,
+ )
+
+ style_doc = self.stylesheet
+ assert style_doc is not None # is ensured by caller
+
+ handle_data = get_data_from_filepath(
+ filepath_or_buffer=style_doc,
+ encoding=self.encoding,
+ compression=self.compression,
+ storage_options=self.storage_options,
+ )
+
+ with preprocess_data(handle_data) as xml_data:
+ curr_parser = XMLParser(encoding=self.encoding)
+
+ if isinstance(xml_data, io.StringIO):
+ xsl_doc = fromstring(
+ xml_data.getvalue().encode(self.encoding), parser=curr_parser
+ )
+ else:
+ xsl_doc = parse(xml_data, parser=curr_parser)
+
+ transformer = XSLT(xsl_doc)
+ new_doc = transformer(self.root)
+
+ return bytes(new_doc)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff19cf6e9d4cccbeeda07fbaca7f23e37a45924b
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__init__.py
@@ -0,0 +1,15 @@
+from pandas.io.json._json import (
+ read_json,
+ to_json,
+ ujson_dumps as dumps,
+ ujson_loads as loads,
+)
+from pandas.io.json._table_schema import build_table_schema
+
+__all__ = [
+ "dumps",
+ "loads",
+ "read_json",
+ "to_json",
+ "build_table_schema",
+]
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c11832cdd2afb624ccb723bff5c708891a7ce9eb
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/__init__.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/_json.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/_json.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39131d83cd832b5abc9e484870db0d37ab627386
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/_json.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/_normalize.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/_normalize.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1443694db1b62f9c49d5aafcbcfbc627b3ee214
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/_normalize.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/_table_schema.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/_table_schema.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9a884e52efddf18792cc1041d754fda073b0ac2
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/__pycache__/_table_schema.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/_json.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/_json.py
new file mode 100644
index 0000000000000000000000000000000000000000..58979a29c97d37ab36b0695699f3c5b1817cddb9
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/_json.py
@@ -0,0 +1,1465 @@
+from __future__ import annotations
+
+from abc import (
+ ABC,
+ abstractmethod,
+)
+from collections import abc
+from io import StringIO
+from itertools import islice
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Generic,
+ Literal,
+ TypeVar,
+ overload,
+)
+import warnings
+
+import numpy as np
+
+from pandas._libs import lib
+from pandas._libs.json import (
+ ujson_dumps,
+ ujson_loads,
+)
+from pandas._libs.tslibs import iNaT
+from pandas.compat._optional import import_optional_dependency
+from pandas.errors import AbstractMethodError
+from pandas.util._decorators import doc
+from pandas.util._exceptions import find_stack_level
+from pandas.util._validators import check_dtype_backend
+
+from pandas.core.dtypes.common import ensure_str
+from pandas.core.dtypes.dtypes import PeriodDtype
+from pandas.core.dtypes.generic import ABCIndex
+
+from pandas import (
+ ArrowDtype,
+ DataFrame,
+ MultiIndex,
+ Series,
+ isna,
+ notna,
+ to_datetime,
+)
+from pandas.core.reshape.concat import concat
+from pandas.core.shared_docs import _shared_docs
+
+from pandas.io.common import (
+ IOHandles,
+ dedup_names,
+ extension_to_compression,
+ file_exists,
+ get_handle,
+ is_fsspec_url,
+ is_potential_multi_index,
+ is_url,
+ stringify_path,
+)
+from pandas.io.json._normalize import convert_to_line_delimits
+from pandas.io.json._table_schema import (
+ build_table_schema,
+ parse_table_schema,
+)
+from pandas.io.parsers.readers import validate_integer
+
+if TYPE_CHECKING:
+ from collections.abc import (
+ Hashable,
+ Mapping,
+ )
+ from types import TracebackType
+
+ from pandas._typing import (
+ CompressionOptions,
+ DtypeArg,
+ DtypeBackend,
+ FilePath,
+ IndexLabel,
+ JSONEngine,
+ JSONSerializable,
+ ReadBuffer,
+ StorageOptions,
+ WriteBuffer,
+ )
+
+ from pandas.core.generic import NDFrame
+
+FrameSeriesStrT = TypeVar("FrameSeriesStrT", bound=Literal["frame", "series"])
+
+
+# interface to/from
+@overload
+def to_json(
+ path_or_buf: FilePath | WriteBuffer[str] | WriteBuffer[bytes],
+ obj: NDFrame,
+ orient: str | None = ...,
+ date_format: str = ...,
+ double_precision: int = ...,
+ force_ascii: bool = ...,
+ date_unit: str = ...,
+ default_handler: Callable[[Any], JSONSerializable] | None = ...,
+ lines: bool = ...,
+ compression: CompressionOptions = ...,
+ index: bool | None = ...,
+ indent: int = ...,
+ storage_options: StorageOptions = ...,
+ mode: Literal["a", "w"] = ...,
+) -> None:
+ ...
+
+
+@overload
+def to_json(
+ path_or_buf: None,
+ obj: NDFrame,
+ orient: str | None = ...,
+ date_format: str = ...,
+ double_precision: int = ...,
+ force_ascii: bool = ...,
+ date_unit: str = ...,
+ default_handler: Callable[[Any], JSONSerializable] | None = ...,
+ lines: bool = ...,
+ compression: CompressionOptions = ...,
+ index: bool | None = ...,
+ indent: int = ...,
+ storage_options: StorageOptions = ...,
+ mode: Literal["a", "w"] = ...,
+) -> str:
+ ...
+
+
+def to_json(
+ path_or_buf: FilePath | WriteBuffer[str] | WriteBuffer[bytes] | None,
+ obj: NDFrame,
+ orient: str | None = None,
+ date_format: str = "epoch",
+ double_precision: int = 10,
+ force_ascii: bool = True,
+ date_unit: str = "ms",
+ default_handler: Callable[[Any], JSONSerializable] | None = None,
+ lines: bool = False,
+ compression: CompressionOptions = "infer",
+ index: bool | None = None,
+ indent: int = 0,
+ storage_options: StorageOptions | None = None,
+ mode: Literal["a", "w"] = "w",
+) -> str | None:
+ if orient in ["records", "values"] and index is True:
+ raise ValueError(
+ "'index=True' is only valid when 'orient' is 'split', 'table', "
+ "'index', or 'columns'."
+ )
+ elif orient in ["index", "columns"] and index is False:
+ raise ValueError(
+ "'index=False' is only valid when 'orient' is 'split', 'table', "
+ "'records', or 'values'."
+ )
+ elif index is None:
+ # will be ignored for orient='records' and 'values'
+ index = True
+
+ if lines and orient != "records":
+ raise ValueError("'lines' keyword only valid when 'orient' is records")
+
+ if mode not in ["a", "w"]:
+ msg = (
+ f"mode={mode} is not a valid option."
+ "Only 'w' and 'a' are currently supported."
+ )
+ raise ValueError(msg)
+
+ if mode == "a" and (not lines or orient != "records"):
+ msg = (
+ "mode='a' (append) is only supported when"
+ "lines is True and orient is 'records'"
+ )
+ raise ValueError(msg)
+
+ if orient == "table" and isinstance(obj, Series):
+ obj = obj.to_frame(name=obj.name or "values")
+
+ writer: type[Writer]
+ if orient == "table" and isinstance(obj, DataFrame):
+ writer = JSONTableWriter
+ elif isinstance(obj, Series):
+ writer = SeriesWriter
+ elif isinstance(obj, DataFrame):
+ writer = FrameWriter
+ else:
+ raise NotImplementedError("'obj' should be a Series or a DataFrame")
+
+ s = writer(
+ obj,
+ orient=orient,
+ date_format=date_format,
+ double_precision=double_precision,
+ ensure_ascii=force_ascii,
+ date_unit=date_unit,
+ default_handler=default_handler,
+ index=index,
+ indent=indent,
+ ).write()
+
+ if lines:
+ s = convert_to_line_delimits(s)
+
+ if path_or_buf is not None:
+ # apply compression and byte/text conversion
+ with get_handle(
+ path_or_buf, mode, compression=compression, storage_options=storage_options
+ ) as handles:
+ handles.handle.write(s)
+ else:
+ return s
+ return None
+
+
+class Writer(ABC):
+ _default_orient: str
+
+ def __init__(
+ self,
+ obj: NDFrame,
+ orient: str | None,
+ date_format: str,
+ double_precision: int,
+ ensure_ascii: bool,
+ date_unit: str,
+ index: bool,
+ default_handler: Callable[[Any], JSONSerializable] | None = None,
+ indent: int = 0,
+ ) -> None:
+ self.obj = obj
+
+ if orient is None:
+ orient = self._default_orient
+
+ self.orient = orient
+ self.date_format = date_format
+ self.double_precision = double_precision
+ self.ensure_ascii = ensure_ascii
+ self.date_unit = date_unit
+ self.default_handler = default_handler
+ self.index = index
+ self.indent = indent
+
+ self.is_copy = None
+ self._format_axes()
+
+ def _format_axes(self):
+ raise AbstractMethodError(self)
+
+ def write(self) -> str:
+ iso_dates = self.date_format == "iso"
+ return ujson_dumps(
+ self.obj_to_write,
+ orient=self.orient,
+ double_precision=self.double_precision,
+ ensure_ascii=self.ensure_ascii,
+ date_unit=self.date_unit,
+ iso_dates=iso_dates,
+ default_handler=self.default_handler,
+ indent=self.indent,
+ )
+
+ @property
+ @abstractmethod
+ def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
+ """Object to write in JSON format."""
+
+
+class SeriesWriter(Writer):
+ _default_orient = "index"
+
+ @property
+ def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
+ if not self.index and self.orient == "split":
+ return {"name": self.obj.name, "data": self.obj.values}
+ else:
+ return self.obj
+
+ def _format_axes(self):
+ if not self.obj.index.is_unique and self.orient == "index":
+ raise ValueError(f"Series index must be unique for orient='{self.orient}'")
+
+
+class FrameWriter(Writer):
+ _default_orient = "columns"
+
+ @property
+ def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
+ if not self.index and self.orient == "split":
+ obj_to_write = self.obj.to_dict(orient="split")
+ del obj_to_write["index"]
+ else:
+ obj_to_write = self.obj
+ return obj_to_write
+
+ def _format_axes(self):
+ """
+ Try to format axes if they are datelike.
+ """
+ if not self.obj.index.is_unique and self.orient in ("index", "columns"):
+ raise ValueError(
+ f"DataFrame index must be unique for orient='{self.orient}'."
+ )
+ if not self.obj.columns.is_unique and self.orient in (
+ "index",
+ "columns",
+ "records",
+ ):
+ raise ValueError(
+ f"DataFrame columns must be unique for orient='{self.orient}'."
+ )
+
+
+class JSONTableWriter(FrameWriter):
+ _default_orient = "records"
+
+ def __init__(
+ self,
+ obj,
+ orient: str | None,
+ date_format: str,
+ double_precision: int,
+ ensure_ascii: bool,
+ date_unit: str,
+ index: bool,
+ default_handler: Callable[[Any], JSONSerializable] | None = None,
+ indent: int = 0,
+ ) -> None:
+ """
+ Adds a `schema` attribute with the Table Schema, resets
+ the index (can't do in caller, because the schema inference needs
+ to know what the index is, forces orient to records, and forces
+ date_format to 'iso'.
+ """
+ super().__init__(
+ obj,
+ orient,
+ date_format,
+ double_precision,
+ ensure_ascii,
+ date_unit,
+ index,
+ default_handler=default_handler,
+ indent=indent,
+ )
+
+ if date_format != "iso":
+ msg = (
+ "Trying to write with `orient='table'` and "
+ f"`date_format='{date_format}'`. Table Schema requires dates "
+ "to be formatted with `date_format='iso'`"
+ )
+ raise ValueError(msg)
+
+ self.schema = build_table_schema(obj, index=self.index)
+
+ # NotImplemented on a column MultiIndex
+ if obj.ndim == 2 and isinstance(obj.columns, MultiIndex):
+ raise NotImplementedError(
+ "orient='table' is not supported for MultiIndex columns"
+ )
+
+ # TODO: Do this timedelta properly in objToJSON.c See GH #15137
+ if (
+ (obj.ndim == 1)
+ and (obj.name in set(obj.index.names))
+ or len(obj.columns.intersection(obj.index.names))
+ ):
+ msg = "Overlapping names between the index and columns"
+ raise ValueError(msg)
+
+ obj = obj.copy()
+ timedeltas = obj.select_dtypes(include=["timedelta"]).columns
+ if len(timedeltas):
+ obj[timedeltas] = obj[timedeltas].map(lambda x: x.isoformat())
+ # Convert PeriodIndex to datetimes before serializing
+ if isinstance(obj.index.dtype, PeriodDtype):
+ obj.index = obj.index.to_timestamp()
+
+ # exclude index from obj if index=False
+ if not self.index:
+ self.obj = obj.reset_index(drop=True)
+ else:
+ self.obj = obj.reset_index(drop=False)
+ self.date_format = "iso"
+ self.orient = "records"
+ self.index = index
+
+ @property
+ def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
+ return {"schema": self.schema, "data": self.obj}
+
+
+@overload
+def read_json(
+ path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes],
+ *,
+ orient: str | None = ...,
+ typ: Literal["frame"] = ...,
+ dtype: DtypeArg | None = ...,
+ convert_axes: bool | None = ...,
+ convert_dates: bool | list[str] = ...,
+ keep_default_dates: bool = ...,
+ precise_float: bool = ...,
+ date_unit: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ lines: bool = ...,
+ chunksize: int,
+ compression: CompressionOptions = ...,
+ nrows: int | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+ engine: JSONEngine = ...,
+) -> JsonReader[Literal["frame"]]:
+ ...
+
+
+@overload
+def read_json(
+ path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes],
+ *,
+ orient: str | None = ...,
+ typ: Literal["series"],
+ dtype: DtypeArg | None = ...,
+ convert_axes: bool | None = ...,
+ convert_dates: bool | list[str] = ...,
+ keep_default_dates: bool = ...,
+ precise_float: bool = ...,
+ date_unit: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ lines: bool = ...,
+ chunksize: int,
+ compression: CompressionOptions = ...,
+ nrows: int | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+ engine: JSONEngine = ...,
+) -> JsonReader[Literal["series"]]:
+ ...
+
+
+@overload
+def read_json(
+ path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes],
+ *,
+ orient: str | None = ...,
+ typ: Literal["series"],
+ dtype: DtypeArg | None = ...,
+ convert_axes: bool | None = ...,
+ convert_dates: bool | list[str] = ...,
+ keep_default_dates: bool = ...,
+ precise_float: bool = ...,
+ date_unit: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ lines: bool = ...,
+ chunksize: None = ...,
+ compression: CompressionOptions = ...,
+ nrows: int | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+ engine: JSONEngine = ...,
+) -> Series:
+ ...
+
+
+@overload
+def read_json(
+ path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes],
+ *,
+ orient: str | None = ...,
+ typ: Literal["frame"] = ...,
+ dtype: DtypeArg | None = ...,
+ convert_axes: bool | None = ...,
+ convert_dates: bool | list[str] = ...,
+ keep_default_dates: bool = ...,
+ precise_float: bool = ...,
+ date_unit: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ lines: bool = ...,
+ chunksize: None = ...,
+ compression: CompressionOptions = ...,
+ nrows: int | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+ engine: JSONEngine = ...,
+) -> DataFrame:
+ ...
+
+
+@doc(
+ storage_options=_shared_docs["storage_options"],
+ decompression_options=_shared_docs["decompression_options"] % "path_or_buf",
+)
+def read_json(
+ path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes],
+ *,
+ orient: str | None = None,
+ typ: Literal["frame", "series"] = "frame",
+ dtype: DtypeArg | None = None,
+ convert_axes: bool | None = None,
+ convert_dates: bool | list[str] = True,
+ keep_default_dates: bool = True,
+ precise_float: bool = False,
+ date_unit: str | None = None,
+ encoding: str | None = None,
+ encoding_errors: str | None = "strict",
+ lines: bool = False,
+ chunksize: int | None = None,
+ compression: CompressionOptions = "infer",
+ nrows: int | None = None,
+ storage_options: StorageOptions | None = None,
+ dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
+ engine: JSONEngine = "ujson",
+) -> DataFrame | Series | JsonReader:
+ """
+ Convert a JSON string to pandas object.
+
+ Parameters
+ ----------
+ path_or_buf : a valid JSON str, path object or file-like object
+ Any valid string path is acceptable. The string could be a URL. Valid
+ URL schemes include http, ftp, s3, and file. For file URLs, a host is
+ expected. A local file could be:
+ ``file://localhost/path/to/table.json``.
+
+ If you want to pass in a path object, pandas accepts any
+ ``os.PathLike``.
+
+ By file-like object, we refer to objects with a ``read()`` method,
+ such as a file handle (e.g. via builtin ``open`` function)
+ or ``StringIO``.
+
+ .. deprecated:: 2.1.0
+ Passing json literal strings is deprecated.
+
+ orient : str, optional
+ Indication of expected JSON string format.
+ Compatible JSON strings can be produced by ``to_json()`` with a
+ corresponding orient value.
+ The set of possible orients is:
+
+ - ``'split'`` : dict like
+ ``{{index -> [index], columns -> [columns], data -> [values]}}``
+ - ``'records'`` : list like
+ ``[{{column -> value}}, ... , {{column -> value}}]``
+ - ``'index'`` : dict like ``{{index -> {{column -> value}}}}``
+ - ``'columns'`` : dict like ``{{column -> {{index -> value}}}}``
+ - ``'values'`` : just the values array
+ - ``'table'`` : dict like ``{{'schema': {{schema}}, 'data': {{data}}}}``
+
+ The allowed and default values depend on the value
+ of the `typ` parameter.
+
+ * when ``typ == 'series'``,
+
+ - allowed orients are ``{{'split','records','index'}}``
+ - default is ``'index'``
+ - The Series index must be unique for orient ``'index'``.
+
+ * when ``typ == 'frame'``,
+
+ - allowed orients are ``{{'split','records','index',
+ 'columns','values', 'table'}}``
+ - default is ``'columns'``
+ - The DataFrame index must be unique for orients ``'index'`` and
+ ``'columns'``.
+ - The DataFrame columns must be unique for orients ``'index'``,
+ ``'columns'``, and ``'records'``.
+
+ typ : {{'frame', 'series'}}, default 'frame'
+ The type of object to recover.
+
+ dtype : bool or dict, default None
+ If True, infer dtypes; if a dict of column to dtype, then use those;
+ if False, then don't infer dtypes at all, applies only to the data.
+
+ For all ``orient`` values except ``'table'``, default is True.
+
+ convert_axes : bool, default None
+ Try to convert the axes to the proper dtypes.
+
+ For all ``orient`` values except ``'table'``, default is True.
+
+ convert_dates : bool or list of str, default True
+ If True then default datelike columns may be converted (depending on
+ keep_default_dates).
+ If False, no dates will be converted.
+ If a list of column names, then those columns will be converted and
+ default datelike columns may also be converted (depending on
+ keep_default_dates).
+
+ keep_default_dates : bool, default True
+ If parsing dates (convert_dates is not False), then try to parse the
+ default datelike columns.
+ A column label is datelike if
+
+ * it ends with ``'_at'``,
+
+ * it ends with ``'_time'``,
+
+ * it begins with ``'timestamp'``,
+
+ * it is ``'modified'``, or
+
+ * it is ``'date'``.
+
+ precise_float : bool, default False
+ Set to enable usage of higher precision (strtod) function when
+ decoding string to double values. Default (False) is to use fast but
+ less precise builtin functionality.
+
+ date_unit : str, default None
+ The timestamp unit to detect if converting dates. The default behaviour
+ is to try and detect the correct precision, but if this is not desired
+ then pass one of 's', 'ms', 'us' or 'ns' to force parsing only seconds,
+ milliseconds, microseconds or nanoseconds respectively.
+
+ encoding : str, default is 'utf-8'
+ The encoding to use to decode py3 bytes.
+
+ encoding_errors : str, optional, default "strict"
+ How encoding errors are treated. `List of possible values
+ `_ .
+
+ .. versionadded:: 1.3.0
+
+ lines : bool, default False
+ Read the file as a json object per line.
+
+ chunksize : int, optional
+ Return JsonReader object for iteration.
+ See the `line-delimited json docs
+ `_
+ for more information on ``chunksize``.
+ This can only be passed if `lines=True`.
+ If this is None, the file will be read into memory all at once.
+
+ .. versionchanged:: 1.2
+
+ ``JsonReader`` is a context manager.
+
+ {decompression_options}
+
+ .. versionchanged:: 1.4.0 Zstandard support.
+
+ nrows : int, optional
+ The number of lines from the line-delimited jsonfile that has to be read.
+ This can only be passed if `lines=True`.
+ If this is None, all the rows will be returned.
+
+ {storage_options}
+
+ .. versionadded:: 1.2.0
+
+ dtype_backend : {{'numpy_nullable', 'pyarrow'}}, default 'numpy_nullable'
+ Back-end data type applied to the resultant :class:`DataFrame`
+ (still experimental). Behaviour is as follows:
+
+ * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
+ (default).
+ * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
+ DataFrame.
+
+ .. versionadded:: 2.0
+
+ engine : {{"ujson", "pyarrow"}}, default "ujson"
+ Parser engine to use. The ``"pyarrow"`` engine is only available when
+ ``lines=True``.
+
+ .. versionadded:: 2.0
+
+ Returns
+ -------
+ Series, DataFrame, or pandas.api.typing.JsonReader
+ A JsonReader is returned when ``chunksize`` is not ``0`` or ``None``.
+ Otherwise, the type returned depends on the value of ``typ``.
+
+ See Also
+ --------
+ DataFrame.to_json : Convert a DataFrame to a JSON string.
+ Series.to_json : Convert a Series to a JSON string.
+ json_normalize : Normalize semi-structured JSON data into a flat table.
+
+ Notes
+ -----
+ Specific to ``orient='table'``, if a :class:`DataFrame` with a literal
+ :class:`Index` name of `index` gets written with :func:`to_json`, the
+ subsequent read operation will incorrectly set the :class:`Index` name to
+ ``None``. This is because `index` is also used by :func:`DataFrame.to_json`
+ to denote a missing :class:`Index` name, and the subsequent
+ :func:`read_json` operation cannot distinguish between the two. The same
+ limitation is encountered with a :class:`MultiIndex` and any names
+ beginning with ``'level_'``.
+
+ Examples
+ --------
+ >>> from io import StringIO
+ >>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],
+ ... index=['row 1', 'row 2'],
+ ... columns=['col 1', 'col 2'])
+
+ Encoding/decoding a Dataframe using ``'split'`` formatted JSON:
+
+ >>> df.to_json(orient='split')
+ '\
+{{\
+"columns":["col 1","col 2"],\
+"index":["row 1","row 2"],\
+"data":[["a","b"],["c","d"]]\
+}}\
+'
+ >>> pd.read_json(StringIO(_), orient='split')
+ col 1 col 2
+ row 1 a b
+ row 2 c d
+
+ Encoding/decoding a Dataframe using ``'index'`` formatted JSON:
+
+ >>> df.to_json(orient='index')
+ '{{"row 1":{{"col 1":"a","col 2":"b"}},"row 2":{{"col 1":"c","col 2":"d"}}}}'
+
+ >>> pd.read_json(StringIO(_), orient='index')
+ col 1 col 2
+ row 1 a b
+ row 2 c d
+
+ Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
+ Note that index labels are not preserved with this encoding.
+
+ >>> df.to_json(orient='records')
+ '[{{"col 1":"a","col 2":"b"}},{{"col 1":"c","col 2":"d"}}]'
+ >>> pd.read_json(StringIO(_), orient='records')
+ col 1 col 2
+ 0 a b
+ 1 c d
+
+ Encoding with Table Schema
+
+ >>> df.to_json(orient='table')
+ '\
+{{"schema":{{"fields":[\
+{{"name":"index","type":"string"}},\
+{{"name":"col 1","type":"string"}},\
+{{"name":"col 2","type":"string"}}],\
+"primaryKey":["index"],\
+"pandas_version":"1.4.0"}},\
+"data":[\
+{{"index":"row 1","col 1":"a","col 2":"b"}},\
+{{"index":"row 2","col 1":"c","col 2":"d"}}]\
+}}\
+'
+ """
+ if orient == "table" and dtype:
+ raise ValueError("cannot pass both dtype and orient='table'")
+ if orient == "table" and convert_axes:
+ raise ValueError("cannot pass both convert_axes and orient='table'")
+
+ check_dtype_backend(dtype_backend)
+
+ if dtype is None and orient != "table":
+ # error: Incompatible types in assignment (expression has type "bool", variable
+ # has type "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float],
+ # Type[int], Type[complex], Type[bool], Type[object], Dict[Hashable,
+ # Union[ExtensionDtype, Union[str, dtype[Any]], Type[str], Type[float],
+ # Type[int], Type[complex], Type[bool], Type[object]]], None]")
+ dtype = True # type: ignore[assignment]
+ if convert_axes is None and orient != "table":
+ convert_axes = True
+
+ json_reader = JsonReader(
+ path_or_buf,
+ orient=orient,
+ typ=typ,
+ dtype=dtype,
+ convert_axes=convert_axes,
+ convert_dates=convert_dates,
+ keep_default_dates=keep_default_dates,
+ precise_float=precise_float,
+ date_unit=date_unit,
+ encoding=encoding,
+ lines=lines,
+ chunksize=chunksize,
+ compression=compression,
+ nrows=nrows,
+ storage_options=storage_options,
+ encoding_errors=encoding_errors,
+ dtype_backend=dtype_backend,
+ engine=engine,
+ )
+
+ if chunksize:
+ return json_reader
+ else:
+ return json_reader.read()
+
+
+class JsonReader(abc.Iterator, Generic[FrameSeriesStrT]):
+ """
+ JsonReader provides an interface for reading in a JSON file.
+
+ If initialized with ``lines=True`` and ``chunksize``, can be iterated over
+ ``chunksize`` lines at a time. Otherwise, calling ``read`` reads in the
+ whole document.
+ """
+
+ def __init__(
+ self,
+ filepath_or_buffer,
+ orient,
+ typ: FrameSeriesStrT,
+ dtype,
+ convert_axes: bool | None,
+ convert_dates,
+ keep_default_dates: bool,
+ precise_float: bool,
+ date_unit,
+ encoding,
+ lines: bool,
+ chunksize: int | None,
+ compression: CompressionOptions,
+ nrows: int | None,
+ storage_options: StorageOptions | None = None,
+ encoding_errors: str | None = "strict",
+ dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
+ engine: JSONEngine = "ujson",
+ ) -> None:
+ self.orient = orient
+ self.typ = typ
+ self.dtype = dtype
+ self.convert_axes = convert_axes
+ self.convert_dates = convert_dates
+ self.keep_default_dates = keep_default_dates
+ self.precise_float = precise_float
+ self.date_unit = date_unit
+ self.encoding = encoding
+ self.engine = engine
+ self.compression = compression
+ self.storage_options = storage_options
+ self.lines = lines
+ self.chunksize = chunksize
+ self.nrows_seen = 0
+ self.nrows = nrows
+ self.encoding_errors = encoding_errors
+ self.handles: IOHandles[str] | None = None
+ self.dtype_backend = dtype_backend
+
+ if self.engine not in {"pyarrow", "ujson"}:
+ raise ValueError(
+ f"The engine type {self.engine} is currently not supported."
+ )
+ if self.chunksize is not None:
+ self.chunksize = validate_integer("chunksize", self.chunksize, 1)
+ if not self.lines:
+ raise ValueError("chunksize can only be passed if lines=True")
+ if self.engine == "pyarrow":
+ raise ValueError(
+ "currently pyarrow engine doesn't support chunksize parameter"
+ )
+ if self.nrows is not None:
+ self.nrows = validate_integer("nrows", self.nrows, 0)
+ if not self.lines:
+ raise ValueError("nrows can only be passed if lines=True")
+ if (
+ isinstance(filepath_or_buffer, str)
+ and not self.lines
+ and "\n" in filepath_or_buffer
+ ):
+ warnings.warn(
+ "Passing literal json to 'read_json' is deprecated and "
+ "will be removed in a future version. To read from a "
+ "literal string, wrap it in a 'StringIO' object.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ if self.engine == "pyarrow":
+ if not self.lines:
+ raise ValueError(
+ "currently pyarrow engine only supports "
+ "the line-delimited JSON format"
+ )
+ self.data = filepath_or_buffer
+ elif self.engine == "ujson":
+ data = self._get_data_from_filepath(filepath_or_buffer)
+ self.data = self._preprocess_data(data)
+
+ def _preprocess_data(self, data):
+ """
+ At this point, the data either has a `read` attribute (e.g. a file
+ object or a StringIO) or is a string that is a JSON document.
+
+ If self.chunksize, we prepare the data for the `__next__` method.
+ Otherwise, we read it into memory for the `read` method.
+ """
+ if hasattr(data, "read") and not (self.chunksize or self.nrows):
+ with self:
+ data = data.read()
+ if not hasattr(data, "read") and (self.chunksize or self.nrows):
+ data = StringIO(data)
+
+ return data
+
+ def _get_data_from_filepath(self, filepath_or_buffer):
+ """
+ The function read_json accepts three input types:
+ 1. filepath (string-like)
+ 2. file-like object (e.g. open file object, StringIO)
+ 3. JSON string
+
+ This method turns (1) into (2) to simplify the rest of the processing.
+ It returns input types (2) and (3) unchanged.
+
+ It raises FileNotFoundError if the input is a string ending in
+ one of .json, .json.gz, .json.bz2, etc. but no such file exists.
+ """
+ # if it is a string but the file does not exist, it might be a JSON string
+ filepath_or_buffer = stringify_path(filepath_or_buffer)
+ if (
+ not isinstance(filepath_or_buffer, str)
+ or is_url(filepath_or_buffer)
+ or is_fsspec_url(filepath_or_buffer)
+ or file_exists(filepath_or_buffer)
+ ):
+ self.handles = get_handle(
+ filepath_or_buffer,
+ "r",
+ encoding=self.encoding,
+ compression=self.compression,
+ storage_options=self.storage_options,
+ errors=self.encoding_errors,
+ )
+ filepath_or_buffer = self.handles.handle
+ elif (
+ isinstance(filepath_or_buffer, str)
+ and filepath_or_buffer.lower().endswith(
+ (".json",) + tuple(f".json{c}" for c in extension_to_compression)
+ )
+ and not file_exists(filepath_or_buffer)
+ ):
+ raise FileNotFoundError(f"File {filepath_or_buffer} does not exist")
+ else:
+ warnings.warn(
+ "Passing literal json to 'read_json' is deprecated and "
+ "will be removed in a future version. To read from a "
+ "literal string, wrap it in a 'StringIO' object.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return filepath_or_buffer
+
+ def _combine_lines(self, lines) -> str:
+ """
+ Combines a list of JSON objects into one JSON object.
+ """
+ return (
+ f'[{",".join([line for line in (line.strip() for line in lines) if line])}]'
+ )
+
+ @overload
+ def read(self: JsonReader[Literal["frame"]]) -> DataFrame:
+ ...
+
+ @overload
+ def read(self: JsonReader[Literal["series"]]) -> Series:
+ ...
+
+ @overload
+ def read(self: JsonReader[Literal["frame", "series"]]) -> DataFrame | Series:
+ ...
+
+ def read(self) -> DataFrame | Series:
+ """
+ Read the whole JSON input into a pandas object.
+ """
+ obj: DataFrame | Series
+ with self:
+ if self.engine == "pyarrow":
+ pyarrow_json = import_optional_dependency("pyarrow.json")
+ pa_table = pyarrow_json.read_json(self.data)
+
+ mapping: type[ArrowDtype] | None | Callable
+ if self.dtype_backend == "pyarrow":
+ mapping = ArrowDtype
+ elif self.dtype_backend == "numpy_nullable":
+ from pandas.io._util import _arrow_dtype_mapping
+
+ mapping = _arrow_dtype_mapping().get
+ else:
+ mapping = None
+
+ return pa_table.to_pandas(types_mapper=mapping)
+ elif self.engine == "ujson":
+ if self.lines:
+ if self.chunksize:
+ obj = concat(self)
+ elif self.nrows:
+ lines = list(islice(self.data, self.nrows))
+ lines_json = self._combine_lines(lines)
+ obj = self._get_object_parser(lines_json)
+ else:
+ data = ensure_str(self.data)
+ data_lines = data.split("\n")
+ obj = self._get_object_parser(self._combine_lines(data_lines))
+ else:
+ obj = self._get_object_parser(self.data)
+ if self.dtype_backend is not lib.no_default:
+ return obj.convert_dtypes(
+ infer_objects=False, dtype_backend=self.dtype_backend
+ )
+ else:
+ return obj
+
+ def _get_object_parser(self, json) -> DataFrame | Series:
+ """
+ Parses a json document into a pandas object.
+ """
+ typ = self.typ
+ dtype = self.dtype
+ kwargs = {
+ "orient": self.orient,
+ "dtype": self.dtype,
+ "convert_axes": self.convert_axes,
+ "convert_dates": self.convert_dates,
+ "keep_default_dates": self.keep_default_dates,
+ "precise_float": self.precise_float,
+ "date_unit": self.date_unit,
+ "dtype_backend": self.dtype_backend,
+ }
+ obj = None
+ if typ == "frame":
+ obj = FrameParser(json, **kwargs).parse()
+
+ if typ == "series" or obj is None:
+ if not isinstance(dtype, bool):
+ kwargs["dtype"] = dtype
+ obj = SeriesParser(json, **kwargs).parse()
+
+ return obj
+
+ def close(self) -> None:
+ """
+ If we opened a stream earlier, in _get_data_from_filepath, we should
+ close it.
+
+ If an open stream or file was passed, we leave it open.
+ """
+ if self.handles is not None:
+ self.handles.close()
+
+ def __iter__(self: JsonReader[FrameSeriesStrT]) -> JsonReader[FrameSeriesStrT]:
+ return self
+
+ @overload
+ def __next__(self: JsonReader[Literal["frame"]]) -> DataFrame:
+ ...
+
+ @overload
+ def __next__(self: JsonReader[Literal["series"]]) -> Series:
+ ...
+
+ @overload
+ def __next__(self: JsonReader[Literal["frame", "series"]]) -> DataFrame | Series:
+ ...
+
+ def __next__(self) -> DataFrame | Series:
+ if self.nrows and self.nrows_seen >= self.nrows:
+ self.close()
+ raise StopIteration
+
+ lines = list(islice(self.data, self.chunksize))
+ if not lines:
+ self.close()
+ raise StopIteration
+
+ try:
+ lines_json = self._combine_lines(lines)
+ obj = self._get_object_parser(lines_json)
+
+ # Make sure that the returned objects have the right index.
+ obj.index = range(self.nrows_seen, self.nrows_seen + len(obj))
+ self.nrows_seen += len(obj)
+ except Exception as ex:
+ self.close()
+ raise ex
+
+ if self.dtype_backend is not lib.no_default:
+ return obj.convert_dtypes(
+ infer_objects=False, dtype_backend=self.dtype_backend
+ )
+ else:
+ return obj
+
+ def __enter__(self) -> JsonReader[FrameSeriesStrT]:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ self.close()
+
+
+class Parser:
+ _split_keys: tuple[str, ...]
+ _default_orient: str
+
+ _STAMP_UNITS = ("s", "ms", "us", "ns")
+ _MIN_STAMPS = {
+ "s": 31536000,
+ "ms": 31536000000,
+ "us": 31536000000000,
+ "ns": 31536000000000000,
+ }
+
+ def __init__(
+ self,
+ json,
+ orient,
+ dtype: DtypeArg | None = None,
+ convert_axes: bool = True,
+ convert_dates: bool | list[str] = True,
+ keep_default_dates: bool = False,
+ precise_float: bool = False,
+ date_unit=None,
+ dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
+ ) -> None:
+ self.json = json
+
+ if orient is None:
+ orient = self._default_orient
+
+ self.orient = orient
+
+ self.dtype = dtype
+
+ if date_unit is not None:
+ date_unit = date_unit.lower()
+ if date_unit not in self._STAMP_UNITS:
+ raise ValueError(f"date_unit must be one of {self._STAMP_UNITS}")
+ self.min_stamp = self._MIN_STAMPS[date_unit]
+ else:
+ self.min_stamp = self._MIN_STAMPS["s"]
+
+ self.precise_float = precise_float
+ self.convert_axes = convert_axes
+ self.convert_dates = convert_dates
+ self.date_unit = date_unit
+ self.keep_default_dates = keep_default_dates
+ self.obj: DataFrame | Series | None = None
+ self.dtype_backend = dtype_backend
+
+ def check_keys_split(self, decoded) -> None:
+ """
+ Checks that dict has only the appropriate keys for orient='split'.
+ """
+ bad_keys = set(decoded.keys()).difference(set(self._split_keys))
+ if bad_keys:
+ bad_keys_joined = ", ".join(bad_keys)
+ raise ValueError(f"JSON data had unexpected key(s): {bad_keys_joined}")
+
+ def parse(self):
+ self._parse()
+
+ if self.obj is None:
+ return None
+ if self.convert_axes:
+ self._convert_axes()
+ self._try_convert_types()
+ return self.obj
+
+ def _parse(self):
+ raise AbstractMethodError(self)
+
+ def _convert_axes(self) -> None:
+ """
+ Try to convert axes.
+ """
+ obj = self.obj
+ assert obj is not None # for mypy
+ for axis_name in obj._AXIS_ORDERS:
+ new_axis, result = self._try_convert_data(
+ name=axis_name,
+ data=obj._get_axis(axis_name),
+ use_dtypes=False,
+ convert_dates=True,
+ )
+ if result:
+ setattr(self.obj, axis_name, new_axis)
+
+ def _try_convert_types(self):
+ raise AbstractMethodError(self)
+
+ def _try_convert_data(
+ self,
+ name: Hashable,
+ data,
+ use_dtypes: bool = True,
+ convert_dates: bool | list[str] = True,
+ ):
+ """
+ Try to parse a ndarray like into a column by inferring dtype.
+ """
+ # don't try to coerce, unless a force conversion
+ if use_dtypes:
+ if not self.dtype:
+ if all(notna(data)):
+ return data, False
+ return data.fillna(np.nan), True
+
+ elif self.dtype is True:
+ pass
+ else:
+ # dtype to force
+ dtype = (
+ self.dtype.get(name) if isinstance(self.dtype, dict) else self.dtype
+ )
+ if dtype is not None:
+ try:
+ return data.astype(dtype), True
+ except (TypeError, ValueError):
+ return data, False
+
+ if convert_dates:
+ new_data, result = self._try_convert_to_date(data)
+ if result:
+ return new_data, True
+
+ if self.dtype_backend is not lib.no_default and not isinstance(data, ABCIndex):
+ # Fall through for conversion later on
+ return data, True
+ elif data.dtype == "object":
+ # try float
+ try:
+ data = data.astype("float64")
+ except (TypeError, ValueError):
+ pass
+
+ if data.dtype.kind == "f":
+ if data.dtype != "float64":
+ # coerce floats to 64
+ try:
+ data = data.astype("float64")
+ except (TypeError, ValueError):
+ pass
+
+ # don't coerce 0-len data
+ if len(data) and data.dtype in ("float", "object"):
+ # coerce ints if we can
+ try:
+ new_data = data.astype("int64")
+ if (new_data == data).all():
+ data = new_data
+ except (TypeError, ValueError, OverflowError):
+ pass
+
+ # coerce ints to 64
+ if data.dtype == "int":
+ # coerce floats to 64
+ try:
+ data = data.astype("int64")
+ except (TypeError, ValueError):
+ pass
+
+ # if we have an index, we want to preserve dtypes
+ if name == "index" and len(data):
+ if self.orient == "split":
+ return data, False
+
+ return data, True
+
+ def _try_convert_to_date(self, data):
+ """
+ Try to parse a ndarray like into a date column.
+
+ Try to coerce object in epoch/iso formats and integer/float in epoch
+ formats. Return a boolean if parsing was successful.
+ """
+ # no conversion on empty
+ if not len(data):
+ return data, False
+
+ new_data = data
+ if new_data.dtype == "object":
+ try:
+ new_data = data.astype("int64")
+ except OverflowError:
+ return data, False
+ except (TypeError, ValueError):
+ pass
+
+ # ignore numbers that are out of range
+ if issubclass(new_data.dtype.type, np.number):
+ in_range = (
+ isna(new_data._values)
+ | (new_data > self.min_stamp)
+ | (new_data._values == iNaT)
+ )
+ if not in_range.all():
+ return data, False
+
+ date_units = (self.date_unit,) if self.date_unit else self._STAMP_UNITS
+ for date_unit in date_units:
+ try:
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ ".*parsing datetimes with mixed time "
+ "zones will raise an error",
+ category=FutureWarning,
+ )
+ new_data = to_datetime(new_data, errors="raise", unit=date_unit)
+ except (ValueError, OverflowError, TypeError):
+ continue
+ return new_data, True
+ return data, False
+
+ def _try_convert_dates(self):
+ raise AbstractMethodError(self)
+
+
+class SeriesParser(Parser):
+ _default_orient = "index"
+ _split_keys = ("name", "index", "data")
+
+ def _parse(self) -> None:
+ data = ujson_loads(self.json, precise_float=self.precise_float)
+
+ if self.orient == "split":
+ decoded = {str(k): v for k, v in data.items()}
+ self.check_keys_split(decoded)
+ self.obj = Series(**decoded)
+ else:
+ self.obj = Series(data)
+
+ def _try_convert_types(self) -> None:
+ if self.obj is None:
+ return
+ obj, result = self._try_convert_data(
+ "data", self.obj, convert_dates=self.convert_dates
+ )
+ if result:
+ self.obj = obj
+
+
+class FrameParser(Parser):
+ _default_orient = "columns"
+ _split_keys = ("columns", "index", "data")
+
+ def _parse(self) -> None:
+ json = self.json
+ orient = self.orient
+
+ if orient == "columns":
+ self.obj = DataFrame(
+ ujson_loads(json, precise_float=self.precise_float), dtype=None
+ )
+ elif orient == "split":
+ decoded = {
+ str(k): v
+ for k, v in ujson_loads(json, precise_float=self.precise_float).items()
+ }
+ self.check_keys_split(decoded)
+ orig_names = [
+ (tuple(col) if isinstance(col, list) else col)
+ for col in decoded["columns"]
+ ]
+ decoded["columns"] = dedup_names(
+ orig_names,
+ is_potential_multi_index(orig_names, None),
+ )
+ self.obj = DataFrame(dtype=None, **decoded)
+ elif orient == "index":
+ self.obj = DataFrame.from_dict(
+ ujson_loads(json, precise_float=self.precise_float),
+ dtype=None,
+ orient="index",
+ )
+ elif orient == "table":
+ self.obj = parse_table_schema(json, precise_float=self.precise_float)
+ else:
+ self.obj = DataFrame(
+ ujson_loads(json, precise_float=self.precise_float), dtype=None
+ )
+
+ def _process_converter(self, f, filt=None) -> None:
+ """
+ Take a conversion function and possibly recreate the frame.
+ """
+ if filt is None:
+ filt = lambda col, c: True
+
+ obj = self.obj
+ assert obj is not None # for mypy
+
+ needs_new_obj = False
+ new_obj = {}
+ for i, (col, c) in enumerate(obj.items()):
+ if filt(col, c):
+ new_data, result = f(col, c)
+ if result:
+ c = new_data
+ needs_new_obj = True
+ new_obj[i] = c
+
+ if needs_new_obj:
+ # possibly handle dup columns
+ new_frame = DataFrame(new_obj, index=obj.index)
+ new_frame.columns = obj.columns
+ self.obj = new_frame
+
+ def _try_convert_types(self) -> None:
+ if self.obj is None:
+ return
+ if self.convert_dates:
+ self._try_convert_dates()
+
+ self._process_converter(
+ lambda col, c: self._try_convert_data(col, c, convert_dates=False)
+ )
+
+ def _try_convert_dates(self) -> None:
+ if self.obj is None:
+ return
+
+ # our columns to parse
+ convert_dates_list_bool = self.convert_dates
+ if isinstance(convert_dates_list_bool, bool):
+ convert_dates_list_bool = []
+ convert_dates = set(convert_dates_list_bool)
+
+ def is_ok(col) -> bool:
+ """
+ Return if this col is ok to try for a date parse.
+ """
+ if not isinstance(col, str):
+ return False
+
+ col_lower = col.lower()
+ if (
+ col_lower.endswith(("_at", "_time"))
+ or col_lower == "modified"
+ or col_lower == "date"
+ or col_lower == "datetime"
+ or col_lower.startswith("timestamp")
+ ):
+ return True
+ return False
+
+ self._process_converter(
+ lambda col, c: self._try_convert_to_date(c),
+ lambda col, c: (
+ (self.keep_default_dates and is_ok(col)) or col in convert_dates
+ ),
+ )
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/_normalize.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/_normalize.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1e2210f9d8940a0931b07e1631350089140ff95
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/_normalize.py
@@ -0,0 +1,544 @@
+# ---------------------------------------------------------------------
+# JSON normalization routines
+from __future__ import annotations
+
+from collections import (
+ abc,
+ defaultdict,
+)
+import copy
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ DefaultDict,
+)
+
+import numpy as np
+
+from pandas._libs.writers import convert_json_to_lines
+
+import pandas as pd
+from pandas import DataFrame
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from pandas._typing import (
+ IgnoreRaise,
+ Scalar,
+ )
+
+
+def convert_to_line_delimits(s: str) -> str:
+ """
+ Helper function that converts JSON lists to line delimited JSON.
+ """
+ # Determine we have a JSON list to turn to lines otherwise just return the
+ # json object, only lists can
+ if not s[0] == "[" and s[-1] == "]":
+ return s
+ s = s[1:-1]
+
+ return convert_json_to_lines(s)
+
+
+def nested_to_record(
+ ds,
+ prefix: str = "",
+ sep: str = ".",
+ level: int = 0,
+ max_level: int | None = None,
+):
+ """
+ A simplified json_normalize
+
+ Converts a nested dict into a flat dict ("record"), unlike json_normalize,
+ it does not attempt to extract a subset of the data.
+
+ Parameters
+ ----------
+ ds : dict or list of dicts
+ prefix: the prefix, optional, default: ""
+ sep : str, default '.'
+ Nested records will generate names separated by sep,
+ e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar
+ level: int, optional, default: 0
+ The number of levels in the json string.
+
+ max_level: int, optional, default: None
+ The max depth to normalize.
+
+ Returns
+ -------
+ d - dict or list of dicts, matching `ds`
+
+ Examples
+ --------
+ >>> nested_to_record(
+ ... dict(flat1=1, dict1=dict(c=1, d=2), nested=dict(e=dict(c=1, d=2), d=2))
+ ... )
+ {\
+'flat1': 1, \
+'dict1.c': 1, \
+'dict1.d': 2, \
+'nested.e.c': 1, \
+'nested.e.d': 2, \
+'nested.d': 2\
+}
+ """
+ singleton = False
+ if isinstance(ds, dict):
+ ds = [ds]
+ singleton = True
+ new_ds = []
+ for d in ds:
+ new_d = copy.deepcopy(d)
+ for k, v in d.items():
+ # each key gets renamed with prefix
+ if not isinstance(k, str):
+ k = str(k)
+ if level == 0:
+ newkey = k
+ else:
+ newkey = prefix + sep + k
+
+ # flatten if type is dict and
+ # current dict level < maximum level provided and
+ # only dicts gets recurse-flattened
+ # only at level>1 do we rename the rest of the keys
+ if not isinstance(v, dict) or (
+ max_level is not None and level >= max_level
+ ):
+ if level != 0: # so we skip copying for top level, common case
+ v = new_d.pop(k)
+ new_d[newkey] = v
+ continue
+
+ v = new_d.pop(k)
+ new_d.update(nested_to_record(v, newkey, sep, level + 1, max_level))
+ new_ds.append(new_d)
+
+ if singleton:
+ return new_ds[0]
+ return new_ds
+
+
+def _normalise_json(
+ data: Any,
+ key_string: str,
+ normalized_dict: dict[str, Any],
+ separator: str,
+) -> dict[str, Any]:
+ """
+ Main recursive function
+ Designed for the most basic use case of pd.json_normalize(data)
+ intended as a performance improvement, see #15621
+
+ Parameters
+ ----------
+ data : Any
+ Type dependent on types contained within nested Json
+ key_string : str
+ New key (with separator(s) in) for data
+ normalized_dict : dict
+ The new normalized/flattened Json dict
+ separator : str, default '.'
+ Nested records will generate names separated by sep,
+ e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar
+ """
+ if isinstance(data, dict):
+ for key, value in data.items():
+ new_key = f"{key_string}{separator}{key}"
+
+ if not key_string:
+ new_key = new_key.removeprefix(separator)
+
+ _normalise_json(
+ data=value,
+ key_string=new_key,
+ normalized_dict=normalized_dict,
+ separator=separator,
+ )
+ else:
+ normalized_dict[key_string] = data
+ return normalized_dict
+
+
+def _normalise_json_ordered(data: dict[str, Any], separator: str) -> dict[str, Any]:
+ """
+ Order the top level keys and then recursively go to depth
+
+ Parameters
+ ----------
+ data : dict or list of dicts
+ separator : str, default '.'
+ Nested records will generate names separated by sep,
+ e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar
+
+ Returns
+ -------
+ dict or list of dicts, matching `normalised_json_object`
+ """
+ top_dict_ = {k: v for k, v in data.items() if not isinstance(v, dict)}
+ nested_dict_ = _normalise_json(
+ data={k: v for k, v in data.items() if isinstance(v, dict)},
+ key_string="",
+ normalized_dict={},
+ separator=separator,
+ )
+ return {**top_dict_, **nested_dict_}
+
+
+def _simple_json_normalize(
+ ds: dict | list[dict],
+ sep: str = ".",
+) -> dict | list[dict] | Any:
+ """
+ A optimized basic json_normalize
+
+ Converts a nested dict into a flat dict ("record"), unlike
+ json_normalize and nested_to_record it doesn't do anything clever.
+ But for the most basic use cases it enhances performance.
+ E.g. pd.json_normalize(data)
+
+ Parameters
+ ----------
+ ds : dict or list of dicts
+ sep : str, default '.'
+ Nested records will generate names separated by sep,
+ e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar
+
+ Returns
+ -------
+ frame : DataFrame
+ d - dict or list of dicts, matching `normalised_json_object`
+
+ Examples
+ --------
+ >>> _simple_json_normalize(
+ ... {
+ ... "flat1": 1,
+ ... "dict1": {"c": 1, "d": 2},
+ ... "nested": {"e": {"c": 1, "d": 2}, "d": 2},
+ ... }
+ ... )
+ {\
+'flat1': 1, \
+'dict1.c': 1, \
+'dict1.d': 2, \
+'nested.e.c': 1, \
+'nested.e.d': 2, \
+'nested.d': 2\
+}
+
+ """
+ normalised_json_object = {}
+ # expect a dictionary, as most jsons are. However, lists are perfectly valid
+ if isinstance(ds, dict):
+ normalised_json_object = _normalise_json_ordered(data=ds, separator=sep)
+ elif isinstance(ds, list):
+ normalised_json_list = [_simple_json_normalize(row, sep=sep) for row in ds]
+ return normalised_json_list
+ return normalised_json_object
+
+
+def json_normalize(
+ data: dict | list[dict],
+ record_path: str | list | None = None,
+ meta: str | list[str | list[str]] | None = None,
+ meta_prefix: str | None = None,
+ record_prefix: str | None = None,
+ errors: IgnoreRaise = "raise",
+ sep: str = ".",
+ max_level: int | None = None,
+) -> DataFrame:
+ """
+ Normalize semi-structured JSON data into a flat table.
+
+ Parameters
+ ----------
+ data : dict or list of dicts
+ Unserialized JSON objects.
+ record_path : str or list of str, default None
+ Path in each object to list of records. If not passed, data will be
+ assumed to be an array of records.
+ meta : list of paths (str or list of str), default None
+ Fields to use as metadata for each record in resulting table.
+ meta_prefix : str, default None
+ If True, prefix records with dotted (?) path, e.g. foo.bar.field if
+ meta is ['foo', 'bar'].
+ record_prefix : str, default None
+ If True, prefix records with dotted (?) path, e.g. foo.bar.field if
+ path to records is ['foo', 'bar'].
+ errors : {'raise', 'ignore'}, default 'raise'
+ Configures error handling.
+
+ * 'ignore' : will ignore KeyError if keys listed in meta are not
+ always present.
+ * 'raise' : will raise KeyError if keys listed in meta are not
+ always present.
+ sep : str, default '.'
+ Nested records will generate names separated by sep.
+ e.g., for sep='.', {'foo': {'bar': 0}} -> foo.bar.
+ max_level : int, default None
+ Max number of levels(depth of dict) to normalize.
+ if None, normalizes all levels.
+
+ Returns
+ -------
+ frame : DataFrame
+ Normalize semi-structured JSON data into a flat table.
+
+ Examples
+ --------
+ >>> data = [
+ ... {"id": 1, "name": {"first": "Coleen", "last": "Volk"}},
+ ... {"name": {"given": "Mark", "family": "Regner"}},
+ ... {"id": 2, "name": "Faye Raker"},
+ ... ]
+ >>> pd.json_normalize(data)
+ id name.first name.last name.given name.family name
+ 0 1.0 Coleen Volk NaN NaN NaN
+ 1 NaN NaN NaN Mark Regner NaN
+ 2 2.0 NaN NaN NaN NaN Faye Raker
+
+ >>> data = [
+ ... {
+ ... "id": 1,
+ ... "name": "Cole Volk",
+ ... "fitness": {"height": 130, "weight": 60},
+ ... },
+ ... {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}},
+ ... {
+ ... "id": 2,
+ ... "name": "Faye Raker",
+ ... "fitness": {"height": 130, "weight": 60},
+ ... },
+ ... ]
+ >>> pd.json_normalize(data, max_level=0)
+ id name fitness
+ 0 1.0 Cole Volk {'height': 130, 'weight': 60}
+ 1 NaN Mark Reg {'height': 130, 'weight': 60}
+ 2 2.0 Faye Raker {'height': 130, 'weight': 60}
+
+ Normalizes nested data up to level 1.
+
+ >>> data = [
+ ... {
+ ... "id": 1,
+ ... "name": "Cole Volk",
+ ... "fitness": {"height": 130, "weight": 60},
+ ... },
+ ... {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}},
+ ... {
+ ... "id": 2,
+ ... "name": "Faye Raker",
+ ... "fitness": {"height": 130, "weight": 60},
+ ... },
+ ... ]
+ >>> pd.json_normalize(data, max_level=1)
+ id name fitness.height fitness.weight
+ 0 1.0 Cole Volk 130 60
+ 1 NaN Mark Reg 130 60
+ 2 2.0 Faye Raker 130 60
+
+ >>> data = [
+ ... {
+ ... "state": "Florida",
+ ... "shortname": "FL",
+ ... "info": {"governor": "Rick Scott"},
+ ... "counties": [
+ ... {"name": "Dade", "population": 12345},
+ ... {"name": "Broward", "population": 40000},
+ ... {"name": "Palm Beach", "population": 60000},
+ ... ],
+ ... },
+ ... {
+ ... "state": "Ohio",
+ ... "shortname": "OH",
+ ... "info": {"governor": "John Kasich"},
+ ... "counties": [
+ ... {"name": "Summit", "population": 1234},
+ ... {"name": "Cuyahoga", "population": 1337},
+ ... ],
+ ... },
+ ... ]
+ >>> result = pd.json_normalize(
+ ... data, "counties", ["state", "shortname", ["info", "governor"]]
+ ... )
+ >>> result
+ name population state shortname info.governor
+ 0 Dade 12345 Florida FL Rick Scott
+ 1 Broward 40000 Florida FL Rick Scott
+ 2 Palm Beach 60000 Florida FL Rick Scott
+ 3 Summit 1234 Ohio OH John Kasich
+ 4 Cuyahoga 1337 Ohio OH John Kasich
+
+ >>> data = {"A": [1, 2]}
+ >>> pd.json_normalize(data, "A", record_prefix="Prefix.")
+ Prefix.0
+ 0 1
+ 1 2
+
+ Returns normalized data with columns prefixed with the given string.
+ """
+
+ def _pull_field(
+ js: dict[str, Any], spec: list | str, extract_record: bool = False
+ ) -> Scalar | Iterable:
+ """Internal function to pull field"""
+ result = js
+ try:
+ if isinstance(spec, list):
+ for field in spec:
+ if result is None:
+ raise KeyError(field)
+ result = result[field]
+ else:
+ result = result[spec]
+ except KeyError as e:
+ if extract_record:
+ raise KeyError(
+ f"Key {e} not found. If specifying a record_path, all elements of "
+ f"data should have the path."
+ ) from e
+ if errors == "ignore":
+ return np.nan
+ else:
+ raise KeyError(
+ f"Key {e} not found. To replace missing values of {e} with "
+ f"np.nan, pass in errors='ignore'"
+ ) from e
+
+ return result
+
+ def _pull_records(js: dict[str, Any], spec: list | str) -> list:
+ """
+ Internal function to pull field for records, and similar to
+ _pull_field, but require to return list. And will raise error
+ if has non iterable value.
+ """
+ result = _pull_field(js, spec, extract_record=True)
+
+ # GH 31507 GH 30145, GH 26284 if result is not list, raise TypeError if not
+ # null, otherwise return an empty list
+ if not isinstance(result, list):
+ if pd.isnull(result):
+ result = []
+ else:
+ raise TypeError(
+ f"{js} has non list value {result} for path {spec}. "
+ "Must be list or null."
+ )
+ return result
+
+ if isinstance(data, list) and not data:
+ return DataFrame()
+ elif isinstance(data, dict):
+ # A bit of a hackjob
+ data = [data]
+ elif isinstance(data, abc.Iterable) and not isinstance(data, str):
+ # GH35923 Fix pd.json_normalize to not skip the first element of a
+ # generator input
+ data = list(data)
+ else:
+ raise NotImplementedError
+
+ # check to see if a simple recursive function is possible to
+ # improve performance (see #15621) but only for cases such
+ # as pd.Dataframe(data) or pd.Dataframe(data, sep)
+ if (
+ record_path is None
+ and meta is None
+ and meta_prefix is None
+ and record_prefix is None
+ and max_level is None
+ ):
+ return DataFrame(_simple_json_normalize(data, sep=sep))
+
+ if record_path is None:
+ if any([isinstance(x, dict) for x in y.values()] for y in data):
+ # naive normalization, this is idempotent for flat records
+ # and potentially will inflate the data considerably for
+ # deeply nested structures:
+ # {VeryLong: { b: 1,c:2}} -> {VeryLong.b:1 ,VeryLong.c:@}
+ #
+ # TODO: handle record value which are lists, at least error
+ # reasonably
+ data = nested_to_record(data, sep=sep, max_level=max_level)
+ return DataFrame(data)
+ elif not isinstance(record_path, list):
+ record_path = [record_path]
+
+ if meta is None:
+ meta = []
+ elif not isinstance(meta, list):
+ meta = [meta]
+
+ _meta = [m if isinstance(m, list) else [m] for m in meta]
+
+ # Disastrously inefficient for now
+ records: list = []
+ lengths = []
+
+ meta_vals: DefaultDict = defaultdict(list)
+ meta_keys = [sep.join(val) for val in _meta]
+
+ def _recursive_extract(data, path, seen_meta, level: int = 0) -> None:
+ if isinstance(data, dict):
+ data = [data]
+ if len(path) > 1:
+ for obj in data:
+ for val, key in zip(_meta, meta_keys):
+ if level + 1 == len(val):
+ seen_meta[key] = _pull_field(obj, val[-1])
+
+ _recursive_extract(obj[path[0]], path[1:], seen_meta, level=level + 1)
+ else:
+ for obj in data:
+ recs = _pull_records(obj, path[0])
+ recs = [
+ nested_to_record(r, sep=sep, max_level=max_level)
+ if isinstance(r, dict)
+ else r
+ for r in recs
+ ]
+
+ # For repeating the metadata later
+ lengths.append(len(recs))
+ for val, key in zip(_meta, meta_keys):
+ if level + 1 > len(val):
+ meta_val = seen_meta[key]
+ else:
+ meta_val = _pull_field(obj, val[level:])
+ meta_vals[key].append(meta_val)
+ records.extend(recs)
+
+ _recursive_extract(data, record_path, {}, level=0)
+
+ result = DataFrame(records)
+
+ if record_prefix is not None:
+ result = result.rename(columns=lambda x: f"{record_prefix}{x}")
+
+ # Data types, a problem
+ for k, v in meta_vals.items():
+ if meta_prefix is not None:
+ k = meta_prefix + k
+
+ if k in result:
+ raise ValueError(
+ f"Conflicting metadata name {k}, need distinguishing prefix "
+ )
+ # GH 37782
+
+ values = np.array(v, dtype=object)
+
+ if values.ndim > 1:
+ # GH 37782
+ values = np.empty((len(v),), dtype=object)
+ for i, v in enumerate(v):
+ values[i] = v
+
+ result[k] = values.repeat(lengths)
+ return result
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/_table_schema.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/_table_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f2291ba7a0c317a17b0161d42e6f4d915a16a6e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/json/_table_schema.py
@@ -0,0 +1,382 @@
+"""
+Table Schema builders
+
+https://specs.frictionlessdata.io/table-schema/
+"""
+from __future__ import annotations
+
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ cast,
+)
+import warnings
+
+from pandas._libs import lib
+from pandas._libs.json import ujson_loads
+from pandas._libs.tslibs import timezones
+from pandas.util._exceptions import find_stack_level
+
+from pandas.core.dtypes.base import _registry as registry
+from pandas.core.dtypes.common import (
+ is_bool_dtype,
+ is_integer_dtype,
+ is_numeric_dtype,
+ is_string_dtype,
+)
+from pandas.core.dtypes.dtypes import (
+ CategoricalDtype,
+ DatetimeTZDtype,
+ ExtensionDtype,
+ PeriodDtype,
+)
+
+from pandas import DataFrame
+import pandas.core.common as com
+
+if TYPE_CHECKING:
+ from pandas._typing import (
+ DtypeObj,
+ JSONSerializable,
+ )
+
+ from pandas import Series
+ from pandas.core.indexes.multi import MultiIndex
+
+
+TABLE_SCHEMA_VERSION = "1.4.0"
+
+
+def as_json_table_type(x: DtypeObj) -> str:
+ """
+ Convert a NumPy / pandas type to its corresponding json_table.
+
+ Parameters
+ ----------
+ x : np.dtype or ExtensionDtype
+
+ Returns
+ -------
+ str
+ the Table Schema data types
+
+ Notes
+ -----
+ This table shows the relationship between NumPy / pandas dtypes,
+ and Table Schema dtypes.
+
+ ============== =================
+ Pandas type Table Schema type
+ ============== =================
+ int64 integer
+ float64 number
+ bool boolean
+ datetime64[ns] datetime
+ timedelta64[ns] duration
+ object str
+ categorical any
+ =============== =================
+ """
+ if is_integer_dtype(x):
+ return "integer"
+ elif is_bool_dtype(x):
+ return "boolean"
+ elif is_numeric_dtype(x):
+ return "number"
+ elif lib.is_np_dtype(x, "M") or isinstance(x, (DatetimeTZDtype, PeriodDtype)):
+ return "datetime"
+ elif lib.is_np_dtype(x, "m"):
+ return "duration"
+ elif isinstance(x, ExtensionDtype):
+ return "any"
+ elif is_string_dtype(x):
+ return "string"
+ else:
+ return "any"
+
+
+def set_default_names(data):
+ """Sets index names to 'index' for regular, or 'level_x' for Multi"""
+ if com.all_not_none(*data.index.names):
+ nms = data.index.names
+ if len(nms) == 1 and data.index.name == "index":
+ warnings.warn(
+ "Index name of 'index' is not round-trippable.",
+ stacklevel=find_stack_level(),
+ )
+ elif len(nms) > 1 and any(x.startswith("level_") for x in nms):
+ warnings.warn(
+ "Index names beginning with 'level_' are not round-trippable.",
+ stacklevel=find_stack_level(),
+ )
+ return data
+
+ data = data.copy()
+ if data.index.nlevels > 1:
+ data.index.names = com.fill_missing_names(data.index.names)
+ else:
+ data.index.name = data.index.name or "index"
+ return data
+
+
+def convert_pandas_type_to_json_field(arr) -> dict[str, JSONSerializable]:
+ dtype = arr.dtype
+ name: JSONSerializable
+ if arr.name is None:
+ name = "values"
+ else:
+ name = arr.name
+ field: dict[str, JSONSerializable] = {
+ "name": name,
+ "type": as_json_table_type(dtype),
+ }
+
+ if isinstance(dtype, CategoricalDtype):
+ cats = dtype.categories
+ ordered = dtype.ordered
+
+ field["constraints"] = {"enum": list(cats)}
+ field["ordered"] = ordered
+ elif isinstance(dtype, PeriodDtype):
+ field["freq"] = dtype.freq.freqstr
+ elif isinstance(dtype, DatetimeTZDtype):
+ if timezones.is_utc(dtype.tz):
+ # timezone.utc has no "zone" attr
+ field["tz"] = "UTC"
+ else:
+ # error: "tzinfo" has no attribute "zone"
+ field["tz"] = dtype.tz.zone # type: ignore[attr-defined]
+ elif isinstance(dtype, ExtensionDtype):
+ field["extDtype"] = dtype.name
+ return field
+
+
+def convert_json_field_to_pandas_type(field) -> str | CategoricalDtype:
+ """
+ Converts a JSON field descriptor into its corresponding NumPy / pandas type
+
+ Parameters
+ ----------
+ field
+ A JSON field descriptor
+
+ Returns
+ -------
+ dtype
+
+ Raises
+ ------
+ ValueError
+ If the type of the provided field is unknown or currently unsupported
+
+ Examples
+ --------
+ >>> convert_json_field_to_pandas_type({"name": "an_int", "type": "integer"})
+ 'int64'
+
+ >>> convert_json_field_to_pandas_type(
+ ... {
+ ... "name": "a_categorical",
+ ... "type": "any",
+ ... "constraints": {"enum": ["a", "b", "c"]},
+ ... "ordered": True,
+ ... }
+ ... )
+ CategoricalDtype(categories=['a', 'b', 'c'], ordered=True, categories_dtype=object)
+
+ >>> convert_json_field_to_pandas_type({"name": "a_datetime", "type": "datetime"})
+ 'datetime64[ns]'
+
+ >>> convert_json_field_to_pandas_type(
+ ... {"name": "a_datetime_with_tz", "type": "datetime", "tz": "US/Central"}
+ ... )
+ 'datetime64[ns, US/Central]'
+ """
+ typ = field["type"]
+ if typ == "string":
+ return "object"
+ elif typ == "integer":
+ return field.get("extDtype", "int64")
+ elif typ == "number":
+ return field.get("extDtype", "float64")
+ elif typ == "boolean":
+ return field.get("extDtype", "bool")
+ elif typ == "duration":
+ return "timedelta64"
+ elif typ == "datetime":
+ if field.get("tz"):
+ return f"datetime64[ns, {field['tz']}]"
+ elif field.get("freq"):
+ # GH#47747 using datetime over period to minimize the change surface
+ return f"period[{field['freq']}]"
+ else:
+ return "datetime64[ns]"
+ elif typ == "any":
+ if "constraints" in field and "ordered" in field:
+ return CategoricalDtype(
+ categories=field["constraints"]["enum"], ordered=field["ordered"]
+ )
+ elif "extDtype" in field:
+ return registry.find(field["extDtype"])
+ else:
+ return "object"
+
+ raise ValueError(f"Unsupported or invalid field type: {typ}")
+
+
+def build_table_schema(
+ data: DataFrame | Series,
+ index: bool = True,
+ primary_key: bool | None = None,
+ version: bool = True,
+) -> dict[str, JSONSerializable]:
+ """
+ Create a Table schema from ``data``.
+
+ Parameters
+ ----------
+ data : Series, DataFrame
+ index : bool, default True
+ Whether to include ``data.index`` in the schema.
+ primary_key : bool or None, default True
+ Column names to designate as the primary key.
+ The default `None` will set `'primaryKey'` to the index
+ level or levels if the index is unique.
+ version : bool, default True
+ Whether to include a field `pandas_version` with the version
+ of pandas that last revised the table schema. This version
+ can be different from the installed pandas version.
+
+ Returns
+ -------
+ dict
+
+ Notes
+ -----
+ See `Table Schema
+ `__ for
+ conversion types.
+ Timedeltas as converted to ISO8601 duration format with
+ 9 decimal places after the seconds field for nanosecond precision.
+
+ Categoricals are converted to the `any` dtype, and use the `enum` field
+ constraint to list the allowed values. The `ordered` attribute is included
+ in an `ordered` field.
+
+ Examples
+ --------
+ >>> from pandas.io.json._table_schema import build_table_schema
+ >>> df = pd.DataFrame(
+ ... {'A': [1, 2, 3],
+ ... 'B': ['a', 'b', 'c'],
+ ... 'C': pd.date_range('2016-01-01', freq='d', periods=3),
+ ... }, index=pd.Index(range(3), name='idx'))
+ >>> build_table_schema(df)
+ {'fields': \
+[{'name': 'idx', 'type': 'integer'}, \
+{'name': 'A', 'type': 'integer'}, \
+{'name': 'B', 'type': 'string'}, \
+{'name': 'C', 'type': 'datetime'}], \
+'primaryKey': ['idx'], \
+'pandas_version': '1.4.0'}
+ """
+ if index is True:
+ data = set_default_names(data)
+
+ schema: dict[str, Any] = {}
+ fields = []
+
+ if index:
+ if data.index.nlevels > 1:
+ data.index = cast("MultiIndex", data.index)
+ for level, name in zip(data.index.levels, data.index.names):
+ new_field = convert_pandas_type_to_json_field(level)
+ new_field["name"] = name
+ fields.append(new_field)
+ else:
+ fields.append(convert_pandas_type_to_json_field(data.index))
+
+ if data.ndim > 1:
+ for column, s in data.items():
+ fields.append(convert_pandas_type_to_json_field(s))
+ else:
+ fields.append(convert_pandas_type_to_json_field(data))
+
+ schema["fields"] = fields
+ if index and data.index.is_unique and primary_key is None:
+ if data.index.nlevels == 1:
+ schema["primaryKey"] = [data.index.name]
+ else:
+ schema["primaryKey"] = data.index.names
+ elif primary_key is not None:
+ schema["primaryKey"] = primary_key
+
+ if version:
+ schema["pandas_version"] = TABLE_SCHEMA_VERSION
+ return schema
+
+
+def parse_table_schema(json, precise_float: bool) -> DataFrame:
+ """
+ Builds a DataFrame from a given schema
+
+ Parameters
+ ----------
+ json :
+ A JSON table schema
+ precise_float : bool
+ Flag controlling precision when decoding string to double values, as
+ dictated by ``read_json``
+
+ Returns
+ -------
+ df : DataFrame
+
+ Raises
+ ------
+ NotImplementedError
+ If the JSON table schema contains either timezone or timedelta data
+
+ Notes
+ -----
+ Because :func:`DataFrame.to_json` uses the string 'index' to denote a
+ name-less :class:`Index`, this function sets the name of the returned
+ :class:`DataFrame` to ``None`` when said string is encountered with a
+ normal :class:`Index`. For a :class:`MultiIndex`, the same limitation
+ applies to any strings beginning with 'level_'. Therefore, an
+ :class:`Index` name of 'index' and :class:`MultiIndex` names starting
+ with 'level_' are not supported.
+
+ See Also
+ --------
+ build_table_schema : Inverse function.
+ pandas.read_json
+ """
+ table = ujson_loads(json, precise_float=precise_float)
+ col_order = [field["name"] for field in table["schema"]["fields"]]
+ df = DataFrame(table["data"], columns=col_order)[col_order]
+
+ dtypes = {
+ field["name"]: convert_json_field_to_pandas_type(field)
+ for field in table["schema"]["fields"]
+ }
+
+ # No ISO constructor for Timedelta as of yet, so need to raise
+ if "timedelta64" in dtypes.values():
+ raise NotImplementedError(
+ 'table="orient" can not yet read ISO-formatted Timedelta data'
+ )
+
+ df = df.astype(dtypes)
+
+ if "primaryKey" in table["schema"]:
+ df = df.set_index(table["schema"]["primaryKey"])
+ if len(df.index.names) == 1:
+ if df.index.name == "index":
+ df.index.name = None
+ else:
+ df.index.names = [
+ None if x.startswith("level_") else x for x in df.index.names
+ ]
+
+ return df
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff11968db15f0f7c6057a46c252a91daee7b9cd9
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__init__.py
@@ -0,0 +1,9 @@
+from pandas.io.parsers.readers import (
+ TextFileReader,
+ TextParser,
+ read_csv,
+ read_fwf,
+ read_table,
+)
+
+__all__ = ["TextFileReader", "TextParser", "read_csv", "read_fwf", "read_table"]
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37d34513ca8b037a348f3a8a112a90d519160b7c
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/__init__.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ce42e6e8fcb7f8cd766725e0e88cdbaec5dff28
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/base_parser.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/base_parser.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a26145a0d2e86bdeac1f2409265ab514ac142f68
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/base_parser.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b86561d14eff52d9d877ae4723afb66bc0776bcb
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/python_parser.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/python_parser.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29d114254d079d4d1fd2ce3d4423c6274ee4e1e8
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/python_parser.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/readers.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/readers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a7e43cd709030b02ded5aace87e5e2c20bdfcc7
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/__pycache__/readers.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/arrow_parser_wrapper.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/arrow_parser_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..71bfb00a95b507c392eb5bc3e49ae63bebe98829
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/arrow_parser_wrapper.py
@@ -0,0 +1,227 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from pandas._config import using_pyarrow_string_dtype
+
+from pandas._libs import lib
+from pandas.compat._optional import import_optional_dependency
+
+from pandas.core.dtypes.inference import is_integer
+
+import pandas as pd
+from pandas import DataFrame
+
+from pandas.io._util import (
+ _arrow_dtype_mapping,
+ arrow_string_types_mapper,
+)
+from pandas.io.parsers.base_parser import ParserBase
+
+if TYPE_CHECKING:
+ from pandas._typing import ReadBuffer
+
+
+class ArrowParserWrapper(ParserBase):
+ """
+ Wrapper for the pyarrow engine for read_csv()
+ """
+
+ def __init__(self, src: ReadBuffer[bytes], **kwds) -> None:
+ super().__init__(kwds)
+ self.kwds = kwds
+ self.src = src
+
+ self._parse_kwds()
+
+ def _parse_kwds(self):
+ """
+ Validates keywords before passing to pyarrow.
+ """
+ encoding: str | None = self.kwds.get("encoding")
+ self.encoding = "utf-8" if encoding is None else encoding
+
+ na_values = self.kwds["na_values"]
+ if isinstance(na_values, dict):
+ raise ValueError(
+ "The pyarrow engine doesn't support passing a dict for na_values"
+ )
+ self.na_values = list(self.kwds["na_values"])
+
+ def _get_pyarrow_options(self) -> None:
+ """
+ Rename some arguments to pass to pyarrow
+ """
+ mapping = {
+ "usecols": "include_columns",
+ "na_values": "null_values",
+ "escapechar": "escape_char",
+ "skip_blank_lines": "ignore_empty_lines",
+ "decimal": "decimal_point",
+ }
+ for pandas_name, pyarrow_name in mapping.items():
+ if pandas_name in self.kwds and self.kwds.get(pandas_name) is not None:
+ self.kwds[pyarrow_name] = self.kwds.pop(pandas_name)
+
+ # Date format handling
+ # If we get a string, we need to convert it into a list for pyarrow
+ # If we get a dict, we want to parse those separately
+ date_format = self.date_format
+ if isinstance(date_format, str):
+ date_format = [date_format]
+ else:
+ # In case of dict, we don't want to propagate through, so
+ # just set to pyarrow default of None
+
+ # Ideally, in future we disable pyarrow dtype inference (read in as string)
+ # to prevent misreads.
+ date_format = None
+ self.kwds["timestamp_parsers"] = date_format
+
+ self.parse_options = {
+ option_name: option_value
+ for option_name, option_value in self.kwds.items()
+ if option_value is not None
+ and option_name
+ in ("delimiter", "quote_char", "escape_char", "ignore_empty_lines")
+ }
+ self.convert_options = {
+ option_name: option_value
+ for option_name, option_value in self.kwds.items()
+ if option_value is not None
+ and option_name
+ in (
+ "include_columns",
+ "null_values",
+ "true_values",
+ "false_values",
+ "decimal_point",
+ "timestamp_parsers",
+ )
+ }
+ self.convert_options["strings_can_be_null"] = "" in self.kwds["null_values"]
+ self.read_options = {
+ "autogenerate_column_names": self.header is None,
+ "skip_rows": self.header
+ if self.header is not None
+ else self.kwds["skiprows"],
+ "encoding": self.encoding,
+ }
+
+ def _finalize_pandas_output(self, frame: DataFrame) -> DataFrame:
+ """
+ Processes data read in based on kwargs.
+
+ Parameters
+ ----------
+ frame: DataFrame
+ The DataFrame to process.
+
+ Returns
+ -------
+ DataFrame
+ The processed DataFrame.
+ """
+ num_cols = len(frame.columns)
+ multi_index_named = True
+ if self.header is None:
+ if self.names is None:
+ if self.header is None:
+ self.names = range(num_cols)
+ if len(self.names) != num_cols:
+ # usecols is passed through to pyarrow, we only handle index col here
+ # The only way self.names is not the same length as number of cols is
+ # if we have int index_col. We should just pad the names(they will get
+ # removed anyways) to expected length then.
+ self.names = list(range(num_cols - len(self.names))) + self.names
+ multi_index_named = False
+ frame.columns = self.names
+ # we only need the frame not the names
+ _, frame = self._do_date_conversions(frame.columns, frame)
+ if self.index_col is not None:
+ index_to_set = self.index_col.copy()
+ for i, item in enumerate(self.index_col):
+ if is_integer(item):
+ index_to_set[i] = frame.columns[item]
+ # String case
+ elif item not in frame.columns:
+ raise ValueError(f"Index {item} invalid")
+
+ # Process dtype for index_col and drop from dtypes
+ if self.dtype is not None:
+ key, new_dtype = (
+ (item, self.dtype.get(item))
+ if self.dtype.get(item) is not None
+ else (frame.columns[item], self.dtype.get(frame.columns[item]))
+ )
+ if new_dtype is not None:
+ frame[key] = frame[key].astype(new_dtype)
+ del self.dtype[key]
+
+ frame.set_index(index_to_set, drop=True, inplace=True)
+ # Clear names if headerless and no name given
+ if self.header is None and not multi_index_named:
+ frame.index.names = [None] * len(frame.index.names)
+
+ if self.dtype is not None:
+ # Ignore non-existent columns from dtype mapping
+ # like other parsers do
+ if isinstance(self.dtype, dict):
+ self.dtype = {k: v for k, v in self.dtype.items() if k in frame.columns}
+ try:
+ frame = frame.astype(self.dtype)
+ except TypeError as e:
+ # GH#44901 reraise to keep api consistent
+ raise ValueError(e)
+ return frame
+
+ def read(self) -> DataFrame:
+ """
+ Reads the contents of a CSV file into a DataFrame and
+ processes it according to the kwargs passed in the
+ constructor.
+
+ Returns
+ -------
+ DataFrame
+ The DataFrame created from the CSV file.
+ """
+ pa = import_optional_dependency("pyarrow")
+ pyarrow_csv = import_optional_dependency("pyarrow.csv")
+ self._get_pyarrow_options()
+
+ table = pyarrow_csv.read_csv(
+ self.src,
+ read_options=pyarrow_csv.ReadOptions(**self.read_options),
+ parse_options=pyarrow_csv.ParseOptions(**self.parse_options),
+ convert_options=pyarrow_csv.ConvertOptions(**self.convert_options),
+ )
+
+ dtype_backend = self.kwds["dtype_backend"]
+
+ # Convert all pa.null() cols -> float64 (non nullable)
+ # else Int64 (nullable case, see below)
+ if dtype_backend is lib.no_default:
+ new_schema = table.schema
+ new_type = pa.float64()
+ for i, arrow_type in enumerate(table.schema.types):
+ if pa.types.is_null(arrow_type):
+ new_schema = new_schema.set(
+ i, new_schema.field(i).with_type(new_type)
+ )
+
+ table = table.cast(new_schema)
+
+ if dtype_backend == "pyarrow":
+ frame = table.to_pandas(types_mapper=pd.ArrowDtype)
+ elif dtype_backend == "numpy_nullable":
+ # Modify the default mapping to also
+ # map null to Int64 (to match other engines)
+ dtype_mapping = _arrow_dtype_mapping()
+ dtype_mapping[pa.null()] = pd.Int64Dtype()
+ frame = table.to_pandas(types_mapper=dtype_mapping.get)
+ elif using_pyarrow_string_dtype():
+ frame = table.to_pandas(types_mapper=arrow_string_types_mapper())
+ else:
+ frame = table.to_pandas()
+ return self._finalize_pandas_output(frame)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/base_parser.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/base_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b1daa96782a094d8f377266935b94db035edf70
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/base_parser.py
@@ -0,0 +1,1426 @@
+from __future__ import annotations
+
+from collections import defaultdict
+from copy import copy
+import csv
+import datetime
+from enum import Enum
+import itertools
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ cast,
+ final,
+ overload,
+)
+import warnings
+
+import numpy as np
+
+from pandas._libs import (
+ lib,
+ parsers,
+)
+import pandas._libs.ops as libops
+from pandas._libs.parsers import STR_NA_VALUES
+from pandas._libs.tslibs import parsing
+from pandas.compat._optional import import_optional_dependency
+from pandas.errors import (
+ ParserError,
+ ParserWarning,
+)
+from pandas.util._exceptions import find_stack_level
+
+from pandas.core.dtypes.astype import astype_array
+from pandas.core.dtypes.common import (
+ ensure_object,
+ is_bool_dtype,
+ is_dict_like,
+ is_extension_array_dtype,
+ is_float_dtype,
+ is_integer,
+ is_integer_dtype,
+ is_list_like,
+ is_object_dtype,
+ is_scalar,
+ is_string_dtype,
+ pandas_dtype,
+)
+from pandas.core.dtypes.dtypes import (
+ CategoricalDtype,
+ ExtensionDtype,
+)
+from pandas.core.dtypes.missing import isna
+
+from pandas import (
+ ArrowDtype,
+ DataFrame,
+ DatetimeIndex,
+ StringDtype,
+ concat,
+)
+from pandas.core import algorithms
+from pandas.core.arrays import (
+ ArrowExtensionArray,
+ BooleanArray,
+ Categorical,
+ ExtensionArray,
+ FloatingArray,
+ IntegerArray,
+)
+from pandas.core.arrays.boolean import BooleanDtype
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+ default_index,
+ ensure_index_from_sequences,
+)
+from pandas.core.series import Series
+from pandas.core.tools import datetimes as tools
+
+from pandas.io.common import is_potential_multi_index
+
+if TYPE_CHECKING:
+ from collections.abc import (
+ Hashable,
+ Iterable,
+ Mapping,
+ Sequence,
+ )
+
+ from pandas._typing import (
+ ArrayLike,
+ DtypeArg,
+ DtypeObj,
+ Scalar,
+ )
+
+
+class ParserBase:
+ class BadLineHandleMethod(Enum):
+ ERROR = 0
+ WARN = 1
+ SKIP = 2
+
+ _implicit_index: bool
+ _first_chunk: bool
+ keep_default_na: bool
+ dayfirst: bool
+ cache_dates: bool
+ keep_date_col: bool
+ usecols_dtype: str | None
+
+ def __init__(self, kwds) -> None:
+ self._implicit_index = False
+
+ self.names = kwds.get("names")
+ self.orig_names: Sequence[Hashable] | None = None
+
+ self.index_col = kwds.get("index_col", None)
+ self.unnamed_cols: set = set()
+ self.index_names: Sequence[Hashable] | None = None
+ self.col_names: Sequence[Hashable] | None = None
+
+ self.parse_dates = _validate_parse_dates_arg(kwds.pop("parse_dates", False))
+ self._parse_date_cols: Iterable = []
+ self.date_parser = kwds.pop("date_parser", lib.no_default)
+ self.date_format = kwds.pop("date_format", None)
+ self.dayfirst = kwds.pop("dayfirst", False)
+ self.keep_date_col = kwds.pop("keep_date_col", False)
+
+ self.na_values = kwds.get("na_values")
+ self.na_fvalues = kwds.get("na_fvalues")
+ self.na_filter = kwds.get("na_filter", False)
+ self.keep_default_na = kwds.get("keep_default_na", True)
+
+ self.dtype = copy(kwds.get("dtype", None))
+ self.converters = kwds.get("converters")
+ self.dtype_backend = kwds.get("dtype_backend")
+
+ self.true_values = kwds.get("true_values")
+ self.false_values = kwds.get("false_values")
+ self.cache_dates = kwds.pop("cache_dates", True)
+
+ self._date_conv = _make_date_converter(
+ date_parser=self.date_parser,
+ date_format=self.date_format,
+ dayfirst=self.dayfirst,
+ cache_dates=self.cache_dates,
+ )
+
+ # validate header options for mi
+ self.header = kwds.get("header")
+ if is_list_like(self.header, allow_sets=False):
+ if kwds.get("usecols"):
+ raise ValueError(
+ "cannot specify usecols when specifying a multi-index header"
+ )
+ if kwds.get("names"):
+ raise ValueError(
+ "cannot specify names when specifying a multi-index header"
+ )
+
+ # validate index_col that only contains integers
+ if self.index_col is not None:
+ # In this case we can pin down index_col as list[int]
+ if is_integer(self.index_col):
+ self.index_col = [self.index_col]
+ elif not (
+ is_list_like(self.index_col, allow_sets=False)
+ and all(map(is_integer, self.index_col))
+ ):
+ raise ValueError(
+ "index_col must only contain row numbers "
+ "when specifying a multi-index header"
+ )
+ else:
+ self.index_col = list(self.index_col)
+
+ self._name_processed = False
+
+ self._first_chunk = True
+
+ self.usecols, self.usecols_dtype = self._validate_usecols_arg(kwds["usecols"])
+
+ # Fallback to error to pass a sketchy test(test_override_set_noconvert_columns)
+ # Normally, this arg would get pre-processed earlier on
+ self.on_bad_lines = kwds.get("on_bad_lines", self.BadLineHandleMethod.ERROR)
+
+ def _validate_parse_dates_presence(self, columns: Sequence[Hashable]) -> Iterable:
+ """
+ Check if parse_dates are in columns.
+
+ If user has provided names for parse_dates, check if those columns
+ are available.
+
+ Parameters
+ ----------
+ columns : list
+ List of names of the dataframe.
+
+ Returns
+ -------
+ The names of the columns which will get parsed later if a dict or list
+ is given as specification.
+
+ Raises
+ ------
+ ValueError
+ If column to parse_date is not in dataframe.
+
+ """
+ cols_needed: Iterable
+ if is_dict_like(self.parse_dates):
+ cols_needed = itertools.chain(*self.parse_dates.values())
+ elif is_list_like(self.parse_dates):
+ # a column in parse_dates could be represented
+ # ColReference = Union[int, str]
+ # DateGroups = List[ColReference]
+ # ParseDates = Union[DateGroups, List[DateGroups],
+ # Dict[ColReference, DateGroups]]
+ cols_needed = itertools.chain.from_iterable(
+ col if is_list_like(col) and not isinstance(col, tuple) else [col]
+ for col in self.parse_dates
+ )
+ else:
+ cols_needed = []
+
+ cols_needed = list(cols_needed)
+
+ # get only columns that are references using names (str), not by index
+ missing_cols = ", ".join(
+ sorted(
+ {
+ col
+ for col in cols_needed
+ if isinstance(col, str) and col not in columns
+ }
+ )
+ )
+ if missing_cols:
+ raise ValueError(
+ f"Missing column provided to 'parse_dates': '{missing_cols}'"
+ )
+ # Convert positions to actual column names
+ return [
+ col if (isinstance(col, str) or col in columns) else columns[col]
+ for col in cols_needed
+ ]
+
+ def close(self) -> None:
+ pass
+
+ @final
+ @property
+ def _has_complex_date_col(self) -> bool:
+ return isinstance(self.parse_dates, dict) or (
+ isinstance(self.parse_dates, list)
+ and len(self.parse_dates) > 0
+ and isinstance(self.parse_dates[0], list)
+ )
+
+ @final
+ def _should_parse_dates(self, i: int) -> bool:
+ if lib.is_bool(self.parse_dates):
+ return bool(self.parse_dates)
+ else:
+ if self.index_names is not None:
+ name = self.index_names[i]
+ else:
+ name = None
+ j = i if self.index_col is None else self.index_col[i]
+
+ return (j in self.parse_dates) or (
+ name is not None and name in self.parse_dates
+ )
+
+ @final
+ def _extract_multi_indexer_columns(
+ self,
+ header,
+ index_names: Sequence[Hashable] | None,
+ passed_names: bool = False,
+ ) -> tuple[
+ Sequence[Hashable], Sequence[Hashable] | None, Sequence[Hashable] | None, bool
+ ]:
+ """
+ Extract and return the names, index_names, col_names if the column
+ names are a MultiIndex.
+
+ Parameters
+ ----------
+ header: list of lists
+ The header rows
+ index_names: list, optional
+ The names of the future index
+ passed_names: bool, default False
+ A flag specifying if names where passed
+
+ """
+ if len(header) < 2:
+ return header[0], index_names, None, passed_names
+
+ # the names are the tuples of the header that are not the index cols
+ # 0 is the name of the index, assuming index_col is a list of column
+ # numbers
+ ic = self.index_col
+ if ic is None:
+ ic = []
+
+ if not isinstance(ic, (list, tuple, np.ndarray)):
+ ic = [ic]
+ sic = set(ic)
+
+ # clean the index_names
+ index_names = header.pop(-1)
+ index_names, _, _ = self._clean_index_names(index_names, self.index_col)
+
+ # extract the columns
+ field_count = len(header[0])
+
+ # check if header lengths are equal
+ if not all(len(header_iter) == field_count for header_iter in header[1:]):
+ raise ParserError("Header rows must have an equal number of columns.")
+
+ def extract(r):
+ return tuple(r[i] for i in range(field_count) if i not in sic)
+
+ columns = list(zip(*(extract(r) for r in header)))
+ names = columns.copy()
+ for single_ic in sorted(ic):
+ names.insert(single_ic, single_ic)
+
+ # Clean the column names (if we have an index_col).
+ if len(ic):
+ col_names = [
+ r[ic[0]]
+ if ((r[ic[0]] is not None) and r[ic[0]] not in self.unnamed_cols)
+ else None
+ for r in header
+ ]
+ else:
+ col_names = [None] * len(header)
+
+ passed_names = True
+
+ return names, index_names, col_names, passed_names
+
+ @final
+ def _maybe_make_multi_index_columns(
+ self,
+ columns: Sequence[Hashable],
+ col_names: Sequence[Hashable] | None = None,
+ ) -> Sequence[Hashable] | MultiIndex:
+ # possibly create a column mi here
+ if is_potential_multi_index(columns):
+ list_columns = cast(list[tuple], columns)
+ return MultiIndex.from_tuples(list_columns, names=col_names)
+ return columns
+
+ @final
+ def _make_index(
+ self, data, alldata, columns, indexnamerow: list[Scalar] | None = None
+ ) -> tuple[Index | None, Sequence[Hashable] | MultiIndex]:
+ index: Index | None
+ if not is_index_col(self.index_col) or not self.index_col:
+ index = None
+
+ elif not self._has_complex_date_col:
+ simple_index = self._get_simple_index(alldata, columns)
+ index = self._agg_index(simple_index)
+ elif self._has_complex_date_col:
+ if not self._name_processed:
+ (self.index_names, _, self.index_col) = self._clean_index_names(
+ list(columns), self.index_col
+ )
+ self._name_processed = True
+ date_index = self._get_complex_date_index(data, columns)
+ index = self._agg_index(date_index, try_parse_dates=False)
+
+ # add names for the index
+ if indexnamerow:
+ coffset = len(indexnamerow) - len(columns)
+ assert index is not None
+ index = index.set_names(indexnamerow[:coffset])
+
+ # maybe create a mi on the columns
+ columns = self._maybe_make_multi_index_columns(columns, self.col_names)
+
+ return index, columns
+
+ @final
+ def _get_simple_index(self, data, columns):
+ def ix(col):
+ if not isinstance(col, str):
+ return col
+ raise ValueError(f"Index {col} invalid")
+
+ to_remove = []
+ index = []
+ for idx in self.index_col:
+ i = ix(idx)
+ to_remove.append(i)
+ index.append(data[i])
+
+ # remove index items from content and columns, don't pop in
+ # loop
+ for i in sorted(to_remove, reverse=True):
+ data.pop(i)
+ if not self._implicit_index:
+ columns.pop(i)
+
+ return index
+
+ @final
+ def _get_complex_date_index(self, data, col_names):
+ def _get_name(icol):
+ if isinstance(icol, str):
+ return icol
+
+ if col_names is None:
+ raise ValueError(f"Must supply column order to use {icol!s} as index")
+
+ for i, c in enumerate(col_names):
+ if i == icol:
+ return c
+
+ to_remove = []
+ index = []
+ for idx in self.index_col:
+ name = _get_name(idx)
+ to_remove.append(name)
+ index.append(data[name])
+
+ # remove index items from content and columns, don't pop in
+ # loop
+ for c in sorted(to_remove, reverse=True):
+ data.pop(c)
+ col_names.remove(c)
+
+ return index
+
+ @final
+ def _clean_mapping(self, mapping):
+ """converts col numbers to names"""
+ if not isinstance(mapping, dict):
+ return mapping
+ clean = {}
+ # for mypy
+ assert self.orig_names is not None
+
+ for col, v in mapping.items():
+ if isinstance(col, int) and col not in self.orig_names:
+ col = self.orig_names[col]
+ clean[col] = v
+ if isinstance(mapping, defaultdict):
+ remaining_cols = set(self.orig_names) - set(clean.keys())
+ clean.update({col: mapping[col] for col in remaining_cols})
+ return clean
+
+ @final
+ def _agg_index(self, index, try_parse_dates: bool = True) -> Index:
+ arrays = []
+ converters = self._clean_mapping(self.converters)
+
+ for i, arr in enumerate(index):
+ if try_parse_dates and self._should_parse_dates(i):
+ arr = self._date_conv(
+ arr,
+ col=self.index_names[i] if self.index_names is not None else None,
+ )
+
+ if self.na_filter:
+ col_na_values = self.na_values
+ col_na_fvalues = self.na_fvalues
+ else:
+ col_na_values = set()
+ col_na_fvalues = set()
+
+ if isinstance(self.na_values, dict):
+ assert self.index_names is not None
+ col_name = self.index_names[i]
+ if col_name is not None:
+ col_na_values, col_na_fvalues = _get_na_values(
+ col_name, self.na_values, self.na_fvalues, self.keep_default_na
+ )
+
+ clean_dtypes = self._clean_mapping(self.dtype)
+
+ cast_type = None
+ index_converter = False
+ if self.index_names is not None:
+ if isinstance(clean_dtypes, dict):
+ cast_type = clean_dtypes.get(self.index_names[i], None)
+
+ if isinstance(converters, dict):
+ index_converter = converters.get(self.index_names[i]) is not None
+
+ try_num_bool = not (
+ cast_type and is_string_dtype(cast_type) or index_converter
+ )
+
+ arr, _ = self._infer_types(
+ arr, col_na_values | col_na_fvalues, cast_type is None, try_num_bool
+ )
+ arrays.append(arr)
+
+ names = self.index_names
+ index = ensure_index_from_sequences(arrays, names)
+
+ return index
+
+ @final
+ def _convert_to_ndarrays(
+ self,
+ dct: Mapping,
+ na_values,
+ na_fvalues,
+ verbose: bool = False,
+ converters=None,
+ dtypes=None,
+ ):
+ result = {}
+ for c, values in dct.items():
+ conv_f = None if converters is None else converters.get(c, None)
+ if isinstance(dtypes, dict):
+ cast_type = dtypes.get(c, None)
+ else:
+ # single dtype or None
+ cast_type = dtypes
+
+ if self.na_filter:
+ col_na_values, col_na_fvalues = _get_na_values(
+ c, na_values, na_fvalues, self.keep_default_na
+ )
+ else:
+ col_na_values, col_na_fvalues = set(), set()
+
+ if c in self._parse_date_cols:
+ # GH#26203 Do not convert columns which get converted to dates
+ # but replace nans to ensure to_datetime works
+ mask = algorithms.isin(values, set(col_na_values) | col_na_fvalues)
+ np.putmask(values, mask, np.nan)
+ result[c] = values
+ continue
+
+ if conv_f is not None:
+ # conv_f applied to data before inference
+ if cast_type is not None:
+ warnings.warn(
+ (
+ "Both a converter and dtype were specified "
+ f"for column {c} - only the converter will be used."
+ ),
+ ParserWarning,
+ stacklevel=find_stack_level(),
+ )
+
+ try:
+ values = lib.map_infer(values, conv_f)
+ except ValueError:
+ mask = algorithms.isin(values, list(na_values)).view(np.uint8)
+ values = lib.map_infer_mask(values, conv_f, mask)
+
+ cvals, na_count = self._infer_types(
+ values,
+ set(col_na_values) | col_na_fvalues,
+ cast_type is None,
+ try_num_bool=False,
+ )
+ else:
+ is_ea = is_extension_array_dtype(cast_type)
+ is_str_or_ea_dtype = is_ea or is_string_dtype(cast_type)
+ # skip inference if specified dtype is object
+ # or casting to an EA
+ try_num_bool = not (cast_type and is_str_or_ea_dtype)
+
+ # general type inference and conversion
+ cvals, na_count = self._infer_types(
+ values,
+ set(col_na_values) | col_na_fvalues,
+ cast_type is None,
+ try_num_bool,
+ )
+
+ # type specified in dtype param or cast_type is an EA
+ if cast_type is not None:
+ cast_type = pandas_dtype(cast_type)
+ if cast_type and (cvals.dtype != cast_type or is_ea):
+ if not is_ea and na_count > 0:
+ if is_bool_dtype(cast_type):
+ raise ValueError(f"Bool column has NA values in column {c}")
+ cvals = self._cast_types(cvals, cast_type, c)
+
+ result[c] = cvals
+ if verbose and na_count:
+ print(f"Filled {na_count} NA values in column {c!s}")
+ return result
+
+ @final
+ def _set_noconvert_dtype_columns(
+ self, col_indices: list[int], names: Sequence[Hashable]
+ ) -> set[int]:
+ """
+ Set the columns that should not undergo dtype conversions.
+
+ Currently, any column that is involved with date parsing will not
+ undergo such conversions. If usecols is specified, the positions of the columns
+ not to cast is relative to the usecols not to all columns.
+
+ Parameters
+ ----------
+ col_indices: The indices specifying order and positions of the columns
+ names: The column names which order is corresponding with the order
+ of col_indices
+
+ Returns
+ -------
+ A set of integers containing the positions of the columns not to convert.
+ """
+ usecols: list[int] | list[str] | None
+ noconvert_columns = set()
+ if self.usecols_dtype == "integer":
+ # A set of integers will be converted to a list in
+ # the correct order every single time.
+ usecols = sorted(self.usecols)
+ elif callable(self.usecols) or self.usecols_dtype not in ("empty", None):
+ # The names attribute should have the correct columns
+ # in the proper order for indexing with parse_dates.
+ usecols = col_indices
+ else:
+ # Usecols is empty.
+ usecols = None
+
+ def _set(x) -> int:
+ if usecols is not None and is_integer(x):
+ x = usecols[x]
+
+ if not is_integer(x):
+ x = col_indices[names.index(x)]
+
+ return x
+
+ if isinstance(self.parse_dates, list):
+ for val in self.parse_dates:
+ if isinstance(val, list):
+ for k in val:
+ noconvert_columns.add(_set(k))
+ else:
+ noconvert_columns.add(_set(val))
+
+ elif isinstance(self.parse_dates, dict):
+ for val in self.parse_dates.values():
+ if isinstance(val, list):
+ for k in val:
+ noconvert_columns.add(_set(k))
+ else:
+ noconvert_columns.add(_set(val))
+
+ elif self.parse_dates:
+ if isinstance(self.index_col, list):
+ for k in self.index_col:
+ noconvert_columns.add(_set(k))
+ elif self.index_col is not None:
+ noconvert_columns.add(_set(self.index_col))
+
+ return noconvert_columns
+
+ @final
+ def _infer_types(
+ self, values, na_values, no_dtype_specified, try_num_bool: bool = True
+ ) -> tuple[ArrayLike, int]:
+ """
+ Infer types of values, possibly casting
+
+ Parameters
+ ----------
+ values : ndarray
+ na_values : set
+ no_dtype_specified: Specifies if we want to cast explicitly
+ try_num_bool : bool, default try
+ try to cast values to numeric (first preference) or boolean
+
+ Returns
+ -------
+ converted : ndarray or ExtensionArray
+ na_count : int
+ """
+ na_count = 0
+ if issubclass(values.dtype.type, (np.number, np.bool_)):
+ # If our array has numeric dtype, we don't have to check for strings in isin
+ na_values = np.array([val for val in na_values if not isinstance(val, str)])
+ mask = algorithms.isin(values, na_values)
+ na_count = mask.astype("uint8", copy=False).sum()
+ if na_count > 0:
+ if is_integer_dtype(values):
+ values = values.astype(np.float64)
+ np.putmask(values, mask, np.nan)
+ return values, na_count
+
+ dtype_backend = self.dtype_backend
+ non_default_dtype_backend = (
+ no_dtype_specified and dtype_backend is not lib.no_default
+ )
+ result: ArrayLike
+
+ if try_num_bool and is_object_dtype(values.dtype):
+ # exclude e.g DatetimeIndex here
+ try:
+ result, result_mask = lib.maybe_convert_numeric(
+ values,
+ na_values,
+ False,
+ convert_to_masked_nullable=non_default_dtype_backend, # type: ignore[arg-type] # noqa: E501
+ )
+ except (ValueError, TypeError):
+ # e.g. encountering datetime string gets ValueError
+ # TypeError can be raised in floatify
+ na_count = parsers.sanitize_objects(values, na_values)
+ result = values
+ else:
+ if non_default_dtype_backend:
+ if result_mask is None:
+ result_mask = np.zeros(result.shape, dtype=np.bool_)
+
+ if result_mask.all():
+ result = IntegerArray(
+ np.ones(result_mask.shape, dtype=np.int64), result_mask
+ )
+ elif is_integer_dtype(result):
+ result = IntegerArray(result, result_mask)
+ elif is_bool_dtype(result):
+ result = BooleanArray(result, result_mask)
+ elif is_float_dtype(result):
+ result = FloatingArray(result, result_mask)
+
+ na_count = result_mask.sum()
+ else:
+ na_count = isna(result).sum()
+ else:
+ result = values
+ if values.dtype == np.object_:
+ na_count = parsers.sanitize_objects(values, na_values)
+
+ if result.dtype == np.object_ and try_num_bool:
+ result, bool_mask = libops.maybe_convert_bool(
+ np.asarray(values),
+ true_values=self.true_values,
+ false_values=self.false_values,
+ convert_to_masked_nullable=non_default_dtype_backend, # type: ignore[arg-type] # noqa: E501
+ )
+ if result.dtype == np.bool_ and non_default_dtype_backend:
+ if bool_mask is None:
+ bool_mask = np.zeros(result.shape, dtype=np.bool_)
+ result = BooleanArray(result, bool_mask)
+ elif result.dtype == np.object_ and non_default_dtype_backend:
+ # read_excel sends array of datetime objects
+ if not lib.is_datetime_array(result, skipna=True):
+ result = StringDtype().construct_array_type()._from_sequence(values)
+
+ if dtype_backend == "pyarrow":
+ pa = import_optional_dependency("pyarrow")
+ if isinstance(result, np.ndarray):
+ result = ArrowExtensionArray(pa.array(result, from_pandas=True))
+ else:
+ # ExtensionArray
+ result = ArrowExtensionArray(
+ pa.array(result.to_numpy(), from_pandas=True)
+ )
+
+ return result, na_count
+
+ @final
+ def _cast_types(self, values: ArrayLike, cast_type: DtypeObj, column) -> ArrayLike:
+ """
+ Cast values to specified type
+
+ Parameters
+ ----------
+ values : ndarray or ExtensionArray
+ cast_type : np.dtype or ExtensionDtype
+ dtype to cast values to
+ column : string
+ column name - used only for error reporting
+
+ Returns
+ -------
+ converted : ndarray or ExtensionArray
+ """
+ if isinstance(cast_type, CategoricalDtype):
+ known_cats = cast_type.categories is not None
+
+ if not is_object_dtype(values.dtype) and not known_cats:
+ # TODO: this is for consistency with
+ # c-parser which parses all categories
+ # as strings
+ values = lib.ensure_string_array(
+ values, skipna=False, convert_na_value=False
+ )
+
+ cats = Index(values).unique().dropna()
+ values = Categorical._from_inferred_categories(
+ cats, cats.get_indexer(values), cast_type, true_values=self.true_values
+ )
+
+ # use the EA's implementation of casting
+ elif isinstance(cast_type, ExtensionDtype):
+ array_type = cast_type.construct_array_type()
+ try:
+ if isinstance(cast_type, BooleanDtype):
+ # error: Unexpected keyword argument "true_values" for
+ # "_from_sequence_of_strings" of "ExtensionArray"
+ return array_type._from_sequence_of_strings( # type: ignore[call-arg] # noqa: E501
+ values,
+ dtype=cast_type,
+ true_values=self.true_values,
+ false_values=self.false_values,
+ )
+ else:
+ return array_type._from_sequence_of_strings(values, dtype=cast_type)
+ except NotImplementedError as err:
+ raise NotImplementedError(
+ f"Extension Array: {array_type} must implement "
+ "_from_sequence_of_strings in order to be used in parser methods"
+ ) from err
+
+ elif isinstance(values, ExtensionArray):
+ values = values.astype(cast_type, copy=False)
+ elif issubclass(cast_type.type, str):
+ # TODO: why skipna=True here and False above? some tests depend
+ # on it here, but nothing fails if we change it above
+ # (as no tests get there as of 2022-12-06)
+ values = lib.ensure_string_array(
+ values, skipna=True, convert_na_value=False
+ )
+ else:
+ try:
+ values = astype_array(values, cast_type, copy=True)
+ except ValueError as err:
+ raise ValueError(
+ f"Unable to convert column {column} to type {cast_type}"
+ ) from err
+ return values
+
+ @overload
+ def _do_date_conversions(
+ self,
+ names: Index,
+ data: DataFrame,
+ ) -> tuple[Sequence[Hashable] | Index, DataFrame]:
+ ...
+
+ @overload
+ def _do_date_conversions(
+ self,
+ names: Sequence[Hashable],
+ data: Mapping[Hashable, ArrayLike],
+ ) -> tuple[Sequence[Hashable], Mapping[Hashable, ArrayLike]]:
+ ...
+
+ @final
+ def _do_date_conversions(
+ self,
+ names: Sequence[Hashable] | Index,
+ data: Mapping[Hashable, ArrayLike] | DataFrame,
+ ) -> tuple[Sequence[Hashable] | Index, Mapping[Hashable, ArrayLike] | DataFrame]:
+ # returns data, columns
+
+ if self.parse_dates is not None:
+ data, names = _process_date_conversion(
+ data,
+ self._date_conv,
+ self.parse_dates,
+ self.index_col,
+ self.index_names,
+ names,
+ keep_date_col=self.keep_date_col,
+ dtype_backend=self.dtype_backend,
+ )
+
+ return names, data
+
+ @final
+ def _check_data_length(
+ self,
+ columns: Sequence[Hashable],
+ data: Sequence[ArrayLike],
+ ) -> None:
+ """Checks if length of data is equal to length of column names.
+
+ One set of trailing commas is allowed. self.index_col not False
+ results in a ParserError previously when lengths do not match.
+
+ Parameters
+ ----------
+ columns: list of column names
+ data: list of array-likes containing the data column-wise.
+ """
+ if not self.index_col and len(columns) != len(data) and columns:
+ empty_str = is_object_dtype(data[-1]) and data[-1] == ""
+ # error: No overload variant of "__ror__" of "ndarray" matches
+ # argument type "ExtensionArray"
+ empty_str_or_na = empty_str | isna(data[-1]) # type: ignore[operator]
+ if len(columns) == len(data) - 1 and np.all(empty_str_or_na):
+ return
+ warnings.warn(
+ "Length of header or names does not match length of data. This leads "
+ "to a loss of data with index_col=False.",
+ ParserWarning,
+ stacklevel=find_stack_level(),
+ )
+
+ @overload
+ def _evaluate_usecols(
+ self,
+ usecols: set[int] | Callable[[Hashable], object],
+ names: Sequence[Hashable],
+ ) -> set[int]:
+ ...
+
+ @overload
+ def _evaluate_usecols(
+ self, usecols: set[str], names: Sequence[Hashable]
+ ) -> set[str]:
+ ...
+
+ @final
+ def _evaluate_usecols(
+ self,
+ usecols: Callable[[Hashable], object] | set[str] | set[int],
+ names: Sequence[Hashable],
+ ) -> set[str] | set[int]:
+ """
+ Check whether or not the 'usecols' parameter
+ is a callable. If so, enumerates the 'names'
+ parameter and returns a set of indices for
+ each entry in 'names' that evaluates to True.
+ If not a callable, returns 'usecols'.
+ """
+ if callable(usecols):
+ return {i for i, name in enumerate(names) if usecols(name)}
+ return usecols
+
+ @final
+ def _validate_usecols_names(self, usecols, names: Sequence):
+ """
+ Validates that all usecols are present in a given
+ list of names. If not, raise a ValueError that
+ shows what usecols are missing.
+
+ Parameters
+ ----------
+ usecols : iterable of usecols
+ The columns to validate are present in names.
+ names : iterable of names
+ The column names to check against.
+
+ Returns
+ -------
+ usecols : iterable of usecols
+ The `usecols` parameter if the validation succeeds.
+
+ Raises
+ ------
+ ValueError : Columns were missing. Error message will list them.
+ """
+ missing = [c for c in usecols if c not in names]
+ if len(missing) > 0:
+ raise ValueError(
+ f"Usecols do not match columns, columns expected but not found: "
+ f"{missing}"
+ )
+
+ return usecols
+
+ @final
+ def _validate_usecols_arg(self, usecols):
+ """
+ Validate the 'usecols' parameter.
+
+ Checks whether or not the 'usecols' parameter contains all integers
+ (column selection by index), strings (column by name) or is a callable.
+ Raises a ValueError if that is not the case.
+
+ Parameters
+ ----------
+ usecols : list-like, callable, or None
+ List of columns to use when parsing or a callable that can be used
+ to filter a list of table columns.
+
+ Returns
+ -------
+ usecols_tuple : tuple
+ A tuple of (verified_usecols, usecols_dtype).
+
+ 'verified_usecols' is either a set if an array-like is passed in or
+ 'usecols' if a callable or None is passed in.
+
+ 'usecols_dtype` is the inferred dtype of 'usecols' if an array-like
+ is passed in or None if a callable or None is passed in.
+ """
+ msg = (
+ "'usecols' must either be list-like of all strings, all unicode, "
+ "all integers or a callable."
+ )
+ if usecols is not None:
+ if callable(usecols):
+ return usecols, None
+
+ if not is_list_like(usecols):
+ # see gh-20529
+ #
+ # Ensure it is iterable container but not string.
+ raise ValueError(msg)
+
+ usecols_dtype = lib.infer_dtype(usecols, skipna=False)
+
+ if usecols_dtype not in ("empty", "integer", "string"):
+ raise ValueError(msg)
+
+ usecols = set(usecols)
+
+ return usecols, usecols_dtype
+ return usecols, None
+
+ @final
+ def _clean_index_names(self, columns, index_col) -> tuple[list | None, list, list]:
+ if not is_index_col(index_col):
+ return None, columns, index_col
+
+ columns = list(columns)
+
+ # In case of no rows and multiindex columns we have to set index_names to
+ # list of Nones GH#38292
+ if not columns:
+ return [None] * len(index_col), columns, index_col
+
+ cp_cols = list(columns)
+ index_names: list[str | int | None] = []
+
+ # don't mutate
+ index_col = list(index_col)
+
+ for i, c in enumerate(index_col):
+ if isinstance(c, str):
+ index_names.append(c)
+ for j, name in enumerate(cp_cols):
+ if name == c:
+ index_col[i] = j
+ columns.remove(name)
+ break
+ else:
+ name = cp_cols[c]
+ columns.remove(name)
+ index_names.append(name)
+
+ # Only clean index names that were placeholders.
+ for i, name in enumerate(index_names):
+ if isinstance(name, str) and name in self.unnamed_cols:
+ index_names[i] = None
+
+ return index_names, columns, index_col
+
+ @final
+ def _get_empty_meta(self, columns, dtype: DtypeArg | None = None):
+ columns = list(columns)
+
+ index_col = self.index_col
+ index_names = self.index_names
+
+ # Convert `dtype` to a defaultdict of some kind.
+ # This will enable us to write `dtype[col_name]`
+ # without worrying about KeyError issues later on.
+ dtype_dict: defaultdict[Hashable, Any]
+ if not is_dict_like(dtype):
+ # if dtype == None, default will be object.
+ default_dtype = dtype or object
+ dtype_dict = defaultdict(lambda: default_dtype)
+ else:
+ dtype = cast(dict, dtype)
+ dtype_dict = defaultdict(
+ lambda: object,
+ {columns[k] if is_integer(k) else k: v for k, v in dtype.items()},
+ )
+
+ # Even though we have no data, the "index" of the empty DataFrame
+ # could for example still be an empty MultiIndex. Thus, we need to
+ # check whether we have any index columns specified, via either:
+ #
+ # 1) index_col (column indices)
+ # 2) index_names (column names)
+ #
+ # Both must be non-null to ensure a successful construction. Otherwise,
+ # we have to create a generic empty Index.
+ index: Index
+ if (index_col is None or index_col is False) or index_names is None:
+ index = default_index(0)
+ else:
+ data = [Series([], dtype=dtype_dict[name]) for name in index_names]
+ index = ensure_index_from_sequences(data, names=index_names)
+ index_col.sort()
+
+ for i, n in enumerate(index_col):
+ columns.pop(n - i)
+
+ col_dict = {
+ col_name: Series([], dtype=dtype_dict[col_name]) for col_name in columns
+ }
+
+ return index, columns, col_dict
+
+
+def _make_date_converter(
+ date_parser=lib.no_default,
+ dayfirst: bool = False,
+ cache_dates: bool = True,
+ date_format: dict[Hashable, str] | str | None = None,
+):
+ if date_parser is not lib.no_default:
+ warnings.warn(
+ "The argument 'date_parser' is deprecated and will "
+ "be removed in a future version. "
+ "Please use 'date_format' instead, or read your data in as 'object' dtype "
+ "and then call 'to_datetime'.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ if date_parser is not lib.no_default and date_format is not None:
+ raise TypeError("Cannot use both 'date_parser' and 'date_format'")
+
+ def unpack_if_single_element(arg):
+ # NumPy 1.25 deprecation: https://github.com/numpy/numpy/pull/10615
+ if isinstance(arg, np.ndarray) and arg.ndim == 1 and len(arg) == 1:
+ return arg[0]
+ return arg
+
+ def converter(*date_cols, col: Hashable):
+ if len(date_cols) == 1 and date_cols[0].dtype.kind in "Mm":
+ return date_cols[0]
+
+ if date_parser is lib.no_default:
+ strs = parsing.concat_date_cols(date_cols)
+ date_fmt = (
+ date_format.get(col) if isinstance(date_format, dict) else date_format
+ )
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ ".*parsing datetimes with mixed time zones will raise an error",
+ category=FutureWarning,
+ )
+ result = tools.to_datetime(
+ ensure_object(strs),
+ format=date_fmt,
+ utc=False,
+ dayfirst=dayfirst,
+ errors="ignore",
+ cache=cache_dates,
+ )
+ if isinstance(result, DatetimeIndex):
+ arr = result.to_numpy()
+ arr.flags.writeable = True
+ return arr
+ return result._values
+ else:
+ try:
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ ".*parsing datetimes with mixed time zones "
+ "will raise an error",
+ category=FutureWarning,
+ )
+ result = tools.to_datetime(
+ date_parser(
+ *(unpack_if_single_element(arg) for arg in date_cols)
+ ),
+ errors="ignore",
+ cache=cache_dates,
+ )
+ if isinstance(result, datetime.datetime):
+ raise Exception("scalar parser")
+ return result
+ except Exception:
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ ".*parsing datetimes with mixed time zones "
+ "will raise an error",
+ category=FutureWarning,
+ )
+ return tools.to_datetime(
+ parsing.try_parse_dates(
+ parsing.concat_date_cols(date_cols),
+ parser=date_parser,
+ ),
+ errors="ignore",
+ )
+
+ return converter
+
+
+parser_defaults = {
+ "delimiter": None,
+ "escapechar": None,
+ "quotechar": '"',
+ "quoting": csv.QUOTE_MINIMAL,
+ "doublequote": True,
+ "skipinitialspace": False,
+ "lineterminator": None,
+ "header": "infer",
+ "index_col": None,
+ "names": None,
+ "skiprows": None,
+ "skipfooter": 0,
+ "nrows": None,
+ "na_values": None,
+ "keep_default_na": True,
+ "true_values": None,
+ "false_values": None,
+ "converters": None,
+ "dtype": None,
+ "cache_dates": True,
+ "thousands": None,
+ "comment": None,
+ "decimal": ".",
+ # 'engine': 'c',
+ "parse_dates": False,
+ "keep_date_col": False,
+ "dayfirst": False,
+ "date_parser": lib.no_default,
+ "date_format": None,
+ "usecols": None,
+ # 'iterator': False,
+ "chunksize": None,
+ "verbose": False,
+ "encoding": None,
+ "compression": None,
+ "skip_blank_lines": True,
+ "encoding_errors": "strict",
+ "on_bad_lines": ParserBase.BadLineHandleMethod.ERROR,
+ "dtype_backend": lib.no_default,
+}
+
+
+def _process_date_conversion(
+ data_dict,
+ converter: Callable,
+ parse_spec,
+ index_col,
+ index_names,
+ columns,
+ keep_date_col: bool = False,
+ dtype_backend=lib.no_default,
+):
+ def _isindex(colspec):
+ return (isinstance(index_col, list) and colspec in index_col) or (
+ isinstance(index_names, list) and colspec in index_names
+ )
+
+ new_cols = []
+ new_data = {}
+
+ orig_names = columns
+ columns = list(columns)
+
+ date_cols = set()
+
+ if parse_spec is None or isinstance(parse_spec, bool):
+ return data_dict, columns
+
+ if isinstance(parse_spec, list):
+ # list of column lists
+ for colspec in parse_spec:
+ if is_scalar(colspec) or isinstance(colspec, tuple):
+ if isinstance(colspec, int) and colspec not in data_dict:
+ colspec = orig_names[colspec]
+ if _isindex(colspec):
+ continue
+ elif dtype_backend == "pyarrow":
+ import pyarrow as pa
+
+ dtype = data_dict[colspec].dtype
+ if isinstance(dtype, ArrowDtype) and (
+ pa.types.is_timestamp(dtype.pyarrow_dtype)
+ or pa.types.is_date(dtype.pyarrow_dtype)
+ ):
+ continue
+
+ # Pyarrow engine returns Series which we need to convert to
+ # numpy array before converter, its a no-op for other parsers
+ data_dict[colspec] = converter(
+ np.asarray(data_dict[colspec]), col=colspec
+ )
+ else:
+ new_name, col, old_names = _try_convert_dates(
+ converter, colspec, data_dict, orig_names
+ )
+ if new_name in data_dict:
+ raise ValueError(f"New date column already in dict {new_name}")
+ new_data[new_name] = col
+ new_cols.append(new_name)
+ date_cols.update(old_names)
+
+ elif isinstance(parse_spec, dict):
+ # dict of new name to column list
+ for new_name, colspec in parse_spec.items():
+ if new_name in data_dict:
+ raise ValueError(f"Date column {new_name} already in dict")
+
+ _, col, old_names = _try_convert_dates(
+ converter,
+ colspec,
+ data_dict,
+ orig_names,
+ target_name=new_name,
+ )
+
+ new_data[new_name] = col
+
+ # If original column can be converted to date we keep the converted values
+ # This can only happen if values are from single column
+ if len(colspec) == 1:
+ new_data[colspec[0]] = col
+
+ new_cols.append(new_name)
+ date_cols.update(old_names)
+
+ if isinstance(data_dict, DataFrame):
+ data_dict = concat([DataFrame(new_data), data_dict], axis=1, copy=False)
+ else:
+ data_dict.update(new_data)
+ new_cols.extend(columns)
+
+ if not keep_date_col:
+ for c in list(date_cols):
+ data_dict.pop(c)
+ new_cols.remove(c)
+
+ return data_dict, new_cols
+
+
+def _try_convert_dates(
+ parser: Callable, colspec, data_dict, columns, target_name: str | None = None
+):
+ colset = set(columns)
+ colnames = []
+
+ for c in colspec:
+ if c in colset:
+ colnames.append(c)
+ elif isinstance(c, int) and c not in columns:
+ colnames.append(columns[c])
+ else:
+ colnames.append(c)
+
+ new_name: tuple | str
+ if all(isinstance(x, tuple) for x in colnames):
+ new_name = tuple(map("_".join, zip(*colnames)))
+ else:
+ new_name = "_".join([str(x) for x in colnames])
+ to_parse = [np.asarray(data_dict[c]) for c in colnames if c in data_dict]
+
+ new_col = parser(*to_parse, col=new_name if target_name is None else target_name)
+ return new_name, new_col, colnames
+
+
+def _get_na_values(col, na_values, na_fvalues, keep_default_na: bool):
+ """
+ Get the NaN values for a given column.
+
+ Parameters
+ ----------
+ col : str
+ The name of the column.
+ na_values : array-like, dict
+ The object listing the NaN values as strings.
+ na_fvalues : array-like, dict
+ The object listing the NaN values as floats.
+ keep_default_na : bool
+ If `na_values` is a dict, and the column is not mapped in the
+ dictionary, whether to return the default NaN values or the empty set.
+
+ Returns
+ -------
+ nan_tuple : A length-two tuple composed of
+
+ 1) na_values : the string NaN values for that column.
+ 2) na_fvalues : the float NaN values for that column.
+ """
+ if isinstance(na_values, dict):
+ if col in na_values:
+ return na_values[col], na_fvalues[col]
+ else:
+ if keep_default_na:
+ return STR_NA_VALUES, set()
+
+ return set(), set()
+ else:
+ return na_values, na_fvalues
+
+
+def _validate_parse_dates_arg(parse_dates):
+ """
+ Check whether or not the 'parse_dates' parameter
+ is a non-boolean scalar. Raises a ValueError if
+ that is the case.
+ """
+ msg = (
+ "Only booleans, lists, and dictionaries are accepted "
+ "for the 'parse_dates' parameter"
+ )
+
+ if not (
+ parse_dates is None
+ or lib.is_bool(parse_dates)
+ or isinstance(parse_dates, (list, dict))
+ ):
+ raise TypeError(msg)
+
+ return parse_dates
+
+
+def is_index_col(col) -> bool:
+ return col is not None and col is not False
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/c_parser_wrapper.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/c_parser_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..0cd788c5e57399597e3fe4ee1b1bf2af4bffd74b
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/c_parser_wrapper.py
@@ -0,0 +1,410 @@
+from __future__ import annotations
+
+from collections import defaultdict
+from typing import TYPE_CHECKING
+import warnings
+
+import numpy as np
+
+from pandas._libs import (
+ lib,
+ parsers,
+)
+from pandas.compat._optional import import_optional_dependency
+from pandas.errors import DtypeWarning
+from pandas.util._exceptions import find_stack_level
+
+from pandas.core.dtypes.common import pandas_dtype
+from pandas.core.dtypes.concat import (
+ concat_compat,
+ union_categoricals,
+)
+from pandas.core.dtypes.dtypes import CategoricalDtype
+
+from pandas.core.indexes.api import ensure_index_from_sequences
+
+from pandas.io.common import (
+ dedup_names,
+ is_potential_multi_index,
+)
+from pandas.io.parsers.base_parser import (
+ ParserBase,
+ ParserError,
+ is_index_col,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import (
+ Hashable,
+ Mapping,
+ Sequence,
+ )
+
+ from pandas._typing import (
+ ArrayLike,
+ DtypeArg,
+ DtypeObj,
+ ReadCsvBuffer,
+ )
+
+ from pandas import (
+ Index,
+ MultiIndex,
+ )
+
+
+class CParserWrapper(ParserBase):
+ low_memory: bool
+ _reader: parsers.TextReader
+
+ def __init__(self, src: ReadCsvBuffer[str], **kwds) -> None:
+ super().__init__(kwds)
+ self.kwds = kwds
+ kwds = kwds.copy()
+
+ self.low_memory = kwds.pop("low_memory", False)
+
+ # #2442
+ # error: Cannot determine type of 'index_col'
+ kwds["allow_leading_cols"] = (
+ self.index_col is not False # type: ignore[has-type]
+ )
+
+ # GH20529, validate usecol arg before TextReader
+ kwds["usecols"] = self.usecols
+
+ # Have to pass int, would break tests using TextReader directly otherwise :(
+ kwds["on_bad_lines"] = self.on_bad_lines.value
+
+ for key in (
+ "storage_options",
+ "encoding",
+ "memory_map",
+ "compression",
+ ):
+ kwds.pop(key, None)
+
+ kwds["dtype"] = ensure_dtype_objs(kwds.get("dtype", None))
+ if "dtype_backend" not in kwds or kwds["dtype_backend"] is lib.no_default:
+ kwds["dtype_backend"] = "numpy"
+ if kwds["dtype_backend"] == "pyarrow":
+ # Fail here loudly instead of in cython after reading
+ import_optional_dependency("pyarrow")
+ self._reader = parsers.TextReader(src, **kwds)
+
+ self.unnamed_cols = self._reader.unnamed_cols
+
+ # error: Cannot determine type of 'names'
+ passed_names = self.names is None # type: ignore[has-type]
+
+ if self._reader.header is None:
+ self.names = None
+ else:
+ # error: Cannot determine type of 'names'
+ # error: Cannot determine type of 'index_names'
+ (
+ self.names, # type: ignore[has-type]
+ self.index_names,
+ self.col_names,
+ passed_names,
+ ) = self._extract_multi_indexer_columns(
+ self._reader.header,
+ self.index_names, # type: ignore[has-type]
+ passed_names,
+ )
+
+ # error: Cannot determine type of 'names'
+ if self.names is None: # type: ignore[has-type]
+ self.names = list(range(self._reader.table_width))
+
+ # gh-9755
+ #
+ # need to set orig_names here first
+ # so that proper indexing can be done
+ # with _set_noconvert_columns
+ #
+ # once names has been filtered, we will
+ # then set orig_names again to names
+ # error: Cannot determine type of 'names'
+ self.orig_names = self.names[:] # type: ignore[has-type]
+
+ if self.usecols:
+ usecols = self._evaluate_usecols(self.usecols, self.orig_names)
+
+ # GH 14671
+ # assert for mypy, orig_names is List or None, None would error in issubset
+ assert self.orig_names is not None
+ if self.usecols_dtype == "string" and not set(usecols).issubset(
+ self.orig_names
+ ):
+ self._validate_usecols_names(usecols, self.orig_names)
+
+ # error: Cannot determine type of 'names'
+ if len(self.names) > len(usecols): # type: ignore[has-type]
+ # error: Cannot determine type of 'names'
+ self.names = [ # type: ignore[has-type]
+ n
+ # error: Cannot determine type of 'names'
+ for i, n in enumerate(self.names) # type: ignore[has-type]
+ if (i in usecols or n in usecols)
+ ]
+
+ # error: Cannot determine type of 'names'
+ if len(self.names) < len(usecols): # type: ignore[has-type]
+ # error: Cannot determine type of 'names'
+ self._validate_usecols_names(
+ usecols,
+ self.names, # type: ignore[has-type]
+ )
+
+ # error: Cannot determine type of 'names'
+ self._validate_parse_dates_presence(self.names) # type: ignore[has-type]
+ self._set_noconvert_columns()
+
+ # error: Cannot determine type of 'names'
+ self.orig_names = self.names # type: ignore[has-type]
+
+ if not self._has_complex_date_col:
+ # error: Cannot determine type of 'index_col'
+ if self._reader.leading_cols == 0 and is_index_col(
+ self.index_col # type: ignore[has-type]
+ ):
+ self._name_processed = True
+ (
+ index_names,
+ # error: Cannot determine type of 'names'
+ self.names, # type: ignore[has-type]
+ self.index_col,
+ ) = self._clean_index_names(
+ # error: Cannot determine type of 'names'
+ self.names, # type: ignore[has-type]
+ # error: Cannot determine type of 'index_col'
+ self.index_col, # type: ignore[has-type]
+ )
+
+ if self.index_names is None:
+ self.index_names = index_names
+
+ if self._reader.header is None and not passed_names:
+ assert self.index_names is not None
+ self.index_names = [None] * len(self.index_names)
+
+ self._implicit_index = self._reader.leading_cols > 0
+
+ def close(self) -> None:
+ # close handles opened by C parser
+ try:
+ self._reader.close()
+ except ValueError:
+ pass
+
+ def _set_noconvert_columns(self) -> None:
+ """
+ Set the columns that should not undergo dtype conversions.
+
+ Currently, any column that is involved with date parsing will not
+ undergo such conversions.
+ """
+ assert self.orig_names is not None
+ # error: Cannot determine type of 'names'
+
+ # much faster than using orig_names.index(x) xref GH#44106
+ names_dict = {x: i for i, x in enumerate(self.orig_names)}
+ col_indices = [names_dict[x] for x in self.names] # type: ignore[has-type]
+ # error: Cannot determine type of 'names'
+ noconvert_columns = self._set_noconvert_dtype_columns(
+ col_indices,
+ self.names, # type: ignore[has-type]
+ )
+ for col in noconvert_columns:
+ self._reader.set_noconvert(col)
+
+ def read(
+ self,
+ nrows: int | None = None,
+ ) -> tuple[
+ Index | MultiIndex | None,
+ Sequence[Hashable] | MultiIndex,
+ Mapping[Hashable, ArrayLike],
+ ]:
+ index: Index | MultiIndex | None
+ column_names: Sequence[Hashable] | MultiIndex
+ try:
+ if self.low_memory:
+ chunks = self._reader.read_low_memory(nrows)
+ # destructive to chunks
+ data = _concatenate_chunks(chunks)
+
+ else:
+ data = self._reader.read(nrows)
+ except StopIteration:
+ if self._first_chunk:
+ self._first_chunk = False
+ names = dedup_names(
+ self.orig_names,
+ is_potential_multi_index(self.orig_names, self.index_col),
+ )
+ index, columns, col_dict = self._get_empty_meta(
+ names,
+ dtype=self.dtype,
+ )
+ columns = self._maybe_make_multi_index_columns(columns, self.col_names)
+
+ if self.usecols is not None:
+ columns = self._filter_usecols(columns)
+
+ col_dict = {k: v for k, v in col_dict.items() if k in columns}
+
+ return index, columns, col_dict
+
+ else:
+ self.close()
+ raise
+
+ # Done with first read, next time raise StopIteration
+ self._first_chunk = False
+
+ # error: Cannot determine type of 'names'
+ names = self.names # type: ignore[has-type]
+
+ if self._reader.leading_cols:
+ if self._has_complex_date_col:
+ raise NotImplementedError("file structure not yet supported")
+
+ # implicit index, no index names
+ arrays = []
+
+ if self.index_col and self._reader.leading_cols != len(self.index_col):
+ raise ParserError(
+ "Could not construct index. Requested to use "
+ f"{len(self.index_col)} number of columns, but "
+ f"{self._reader.leading_cols} left to parse."
+ )
+
+ for i in range(self._reader.leading_cols):
+ if self.index_col is None:
+ values = data.pop(i)
+ else:
+ values = data.pop(self.index_col[i])
+
+ values = self._maybe_parse_dates(values, i, try_parse_dates=True)
+ arrays.append(values)
+
+ index = ensure_index_from_sequences(arrays)
+
+ if self.usecols is not None:
+ names = self._filter_usecols(names)
+
+ names = dedup_names(names, is_potential_multi_index(names, self.index_col))
+
+ # rename dict keys
+ data_tups = sorted(data.items())
+ data = {k: v for k, (i, v) in zip(names, data_tups)}
+
+ column_names, date_data = self._do_date_conversions(names, data)
+
+ # maybe create a mi on the columns
+ column_names = self._maybe_make_multi_index_columns(
+ column_names, self.col_names
+ )
+
+ else:
+ # rename dict keys
+ data_tups = sorted(data.items())
+
+ # ugh, mutation
+
+ # assert for mypy, orig_names is List or None, None would error in list(...)
+ assert self.orig_names is not None
+ names = list(self.orig_names)
+ names = dedup_names(names, is_potential_multi_index(names, self.index_col))
+
+ if self.usecols is not None:
+ names = self._filter_usecols(names)
+
+ # columns as list
+ alldata = [x[1] for x in data_tups]
+ if self.usecols is None:
+ self._check_data_length(names, alldata)
+
+ data = {k: v for k, (i, v) in zip(names, data_tups)}
+
+ names, date_data = self._do_date_conversions(names, data)
+ index, column_names = self._make_index(date_data, alldata, names)
+
+ return index, column_names, date_data
+
+ def _filter_usecols(self, names: Sequence[Hashable]) -> Sequence[Hashable]:
+ # hackish
+ usecols = self._evaluate_usecols(self.usecols, names)
+ if usecols is not None and len(names) != len(usecols):
+ names = [
+ name for i, name in enumerate(names) if i in usecols or name in usecols
+ ]
+ return names
+
+ def _maybe_parse_dates(self, values, index: int, try_parse_dates: bool = True):
+ if try_parse_dates and self._should_parse_dates(index):
+ values = self._date_conv(
+ values,
+ col=self.index_names[index] if self.index_names is not None else None,
+ )
+ return values
+
+
+def _concatenate_chunks(chunks: list[dict[int, ArrayLike]]) -> dict:
+ """
+ Concatenate chunks of data read with low_memory=True.
+
+ The tricky part is handling Categoricals, where different chunks
+ may have different inferred categories.
+ """
+ names = list(chunks[0].keys())
+ warning_columns = []
+
+ result: dict = {}
+ for name in names:
+ arrs = [chunk.pop(name) for chunk in chunks]
+ # Check each arr for consistent types.
+ dtypes = {a.dtype for a in arrs}
+ non_cat_dtypes = {x for x in dtypes if not isinstance(x, CategoricalDtype)}
+
+ dtype = dtypes.pop()
+ if isinstance(dtype, CategoricalDtype):
+ result[name] = union_categoricals(arrs, sort_categories=False)
+ else:
+ result[name] = concat_compat(arrs)
+ if len(non_cat_dtypes) > 1 and result[name].dtype == np.dtype(object):
+ warning_columns.append(str(name))
+
+ if warning_columns:
+ warning_names = ",".join(warning_columns)
+ warning_message = " ".join(
+ [
+ f"Columns ({warning_names}) have mixed types. "
+ f"Specify dtype option on import or set low_memory=False."
+ ]
+ )
+ warnings.warn(warning_message, DtypeWarning, stacklevel=find_stack_level())
+ return result
+
+
+def ensure_dtype_objs(
+ dtype: DtypeArg | dict[Hashable, DtypeArg] | None
+) -> DtypeObj | dict[Hashable, DtypeObj] | None:
+ """
+ Ensure we have either None, a dtype object, or a dictionary mapping to
+ dtype objects.
+ """
+ if isinstance(dtype, defaultdict):
+ # "None" not callable [misc]
+ default_dtype = pandas_dtype(dtype.default_factory()) # type: ignore[misc]
+ dtype_converted: defaultdict = defaultdict(lambda: default_dtype)
+ for key in dtype.keys():
+ dtype_converted[key] = pandas_dtype(dtype[key])
+ return dtype_converted
+ elif isinstance(dtype, dict):
+ return {k: pandas_dtype(dtype[k]) for k in dtype}
+ elif dtype is not None:
+ return pandas_dtype(dtype)
+ return dtype
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/python_parser.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/python_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..6846ea2b196b8d1e7dcd1e1e6286e21b413d3237
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/python_parser.py
@@ -0,0 +1,1382 @@
+from __future__ import annotations
+
+from collections import (
+ abc,
+ defaultdict,
+)
+from collections.abc import (
+ Hashable,
+ Iterator,
+ Mapping,
+ Sequence,
+)
+import csv
+from io import StringIO
+import re
+import sys
+from typing import (
+ IO,
+ TYPE_CHECKING,
+ DefaultDict,
+ Literal,
+ cast,
+)
+
+import numpy as np
+
+from pandas._libs import lib
+from pandas.errors import (
+ EmptyDataError,
+ ParserError,
+)
+from pandas.util._decorators import cache_readonly
+
+from pandas.core.dtypes.common import (
+ is_bool_dtype,
+ is_integer,
+ is_numeric_dtype,
+)
+from pandas.core.dtypes.inference import is_dict_like
+
+from pandas.io.common import (
+ dedup_names,
+ is_potential_multi_index,
+)
+from pandas.io.parsers.base_parser import (
+ ParserBase,
+ parser_defaults,
+)
+
+if TYPE_CHECKING:
+ from pandas._typing import (
+ ArrayLike,
+ ReadCsvBuffer,
+ Scalar,
+ )
+
+ from pandas import (
+ Index,
+ MultiIndex,
+ )
+
+# BOM character (byte order mark)
+# This exists at the beginning of a file to indicate endianness
+# of a file (stream). Unfortunately, this marker screws up parsing,
+# so we need to remove it if we see it.
+_BOM = "\ufeff"
+
+
+class PythonParser(ParserBase):
+ _no_thousands_columns: set[int]
+
+ def __init__(self, f: ReadCsvBuffer[str] | list, **kwds) -> None:
+ """
+ Workhorse function for processing nested list into DataFrame
+ """
+ super().__init__(kwds)
+
+ self.data: Iterator[str] | None = None
+ self.buf: list = []
+ self.pos = 0
+ self.line_pos = 0
+
+ self.skiprows = kwds["skiprows"]
+
+ if callable(self.skiprows):
+ self.skipfunc = self.skiprows
+ else:
+ self.skipfunc = lambda x: x in self.skiprows
+
+ self.skipfooter = _validate_skipfooter_arg(kwds["skipfooter"])
+ self.delimiter = kwds["delimiter"]
+
+ self.quotechar = kwds["quotechar"]
+ if isinstance(self.quotechar, str):
+ self.quotechar = str(self.quotechar)
+
+ self.escapechar = kwds["escapechar"]
+ self.doublequote = kwds["doublequote"]
+ self.skipinitialspace = kwds["skipinitialspace"]
+ self.lineterminator = kwds["lineterminator"]
+ self.quoting = kwds["quoting"]
+ self.skip_blank_lines = kwds["skip_blank_lines"]
+
+ self.has_index_names = False
+ if "has_index_names" in kwds:
+ self.has_index_names = kwds["has_index_names"]
+
+ self.verbose = kwds["verbose"]
+
+ self.thousands = kwds["thousands"]
+ self.decimal = kwds["decimal"]
+
+ self.comment = kwds["comment"]
+
+ # Set self.data to something that can read lines.
+ if isinstance(f, list):
+ # read_excel: f is a list
+ self.data = cast(Iterator[str], f)
+ else:
+ assert hasattr(f, "readline")
+ self.data = self._make_reader(f)
+
+ # Get columns in two steps: infer from data, then
+ # infer column indices from self.usecols if it is specified.
+ self._col_indices: list[int] | None = None
+ columns: list[list[Scalar | None]]
+ (
+ columns,
+ self.num_original_columns,
+ self.unnamed_cols,
+ ) = self._infer_columns()
+
+ # Now self.columns has the set of columns that we will process.
+ # The original set is stored in self.original_columns.
+ # error: Cannot determine type of 'index_names'
+ (
+ self.columns,
+ self.index_names,
+ self.col_names,
+ _,
+ ) = self._extract_multi_indexer_columns(
+ columns,
+ self.index_names, # type: ignore[has-type]
+ )
+
+ # get popped off for index
+ self.orig_names: list[Hashable] = list(self.columns)
+
+ # needs to be cleaned/refactored
+ # multiple date column thing turning into a real spaghetti factory
+
+ if not self._has_complex_date_col:
+ (index_names, self.orig_names, self.columns) = self._get_index_name()
+ self._name_processed = True
+ if self.index_names is None:
+ self.index_names = index_names
+
+ if self._col_indices is None:
+ self._col_indices = list(range(len(self.columns)))
+
+ self._parse_date_cols = self._validate_parse_dates_presence(self.columns)
+ self._no_thousands_columns = self._set_no_thousand_columns()
+
+ if len(self.decimal) != 1:
+ raise ValueError("Only length-1 decimal markers supported")
+
+ @cache_readonly
+ def num(self) -> re.Pattern:
+ decimal = re.escape(self.decimal)
+ if self.thousands is None:
+ regex = rf"^[\-\+]?[0-9]*({decimal}[0-9]*)?([0-9]?(E|e)\-?[0-9]+)?$"
+ else:
+ thousands = re.escape(self.thousands)
+ regex = (
+ rf"^[\-\+]?([0-9]+{thousands}|[0-9])*({decimal}[0-9]*)?"
+ rf"([0-9]?(E|e)\-?[0-9]+)?$"
+ )
+ return re.compile(regex)
+
+ def _make_reader(self, f: IO[str] | ReadCsvBuffer[str]):
+ sep = self.delimiter
+
+ if sep is None or len(sep) == 1:
+ if self.lineterminator:
+ raise ValueError(
+ "Custom line terminators not supported in python parser (yet)"
+ )
+
+ class MyDialect(csv.Dialect):
+ delimiter = self.delimiter
+ quotechar = self.quotechar
+ escapechar = self.escapechar
+ doublequote = self.doublequote
+ skipinitialspace = self.skipinitialspace
+ quoting = self.quoting
+ lineterminator = "\n"
+
+ dia = MyDialect
+
+ if sep is not None:
+ dia.delimiter = sep
+ else:
+ # attempt to sniff the delimiter from the first valid line,
+ # i.e. no comment line and not in skiprows
+ line = f.readline()
+ lines = self._check_comments([[line]])[0]
+ while self.skipfunc(self.pos) or not lines:
+ self.pos += 1
+ line = f.readline()
+ lines = self._check_comments([[line]])[0]
+ lines_str = cast(list[str], lines)
+
+ # since `line` was a string, lines will be a list containing
+ # only a single string
+ line = lines_str[0]
+
+ self.pos += 1
+ self.line_pos += 1
+ sniffed = csv.Sniffer().sniff(line)
+ dia.delimiter = sniffed.delimiter
+
+ # Note: encoding is irrelevant here
+ line_rdr = csv.reader(StringIO(line), dialect=dia)
+ self.buf.extend(list(line_rdr))
+
+ # Note: encoding is irrelevant here
+ reader = csv.reader(f, dialect=dia, strict=True)
+
+ else:
+
+ def _read():
+ line = f.readline()
+ pat = re.compile(sep)
+
+ yield pat.split(line.strip())
+
+ for line in f:
+ yield pat.split(line.strip())
+
+ reader = _read()
+
+ return reader
+
+ def read(
+ self, rows: int | None = None
+ ) -> tuple[
+ Index | None, Sequence[Hashable] | MultiIndex, Mapping[Hashable, ArrayLike]
+ ]:
+ try:
+ content = self._get_lines(rows)
+ except StopIteration:
+ if self._first_chunk:
+ content = []
+ else:
+ self.close()
+ raise
+
+ # done with first read, next time raise StopIteration
+ self._first_chunk = False
+
+ columns: Sequence[Hashable] = list(self.orig_names)
+ if not len(content): # pragma: no cover
+ # DataFrame with the right metadata, even though it's length 0
+ # error: Cannot determine type of 'index_col'
+ names = dedup_names(
+ self.orig_names,
+ is_potential_multi_index(
+ self.orig_names,
+ self.index_col, # type: ignore[has-type]
+ ),
+ )
+ index, columns, col_dict = self._get_empty_meta(
+ names,
+ self.dtype,
+ )
+ conv_columns = self._maybe_make_multi_index_columns(columns, self.col_names)
+ return index, conv_columns, col_dict
+
+ # handle new style for names in index
+ count_empty_content_vals = count_empty_vals(content[0])
+ indexnamerow = None
+ if self.has_index_names and count_empty_content_vals == len(columns):
+ indexnamerow = content[0]
+ content = content[1:]
+
+ alldata = self._rows_to_cols(content)
+ data, columns = self._exclude_implicit_index(alldata)
+
+ conv_data = self._convert_data(data)
+ columns, conv_data = self._do_date_conversions(columns, conv_data)
+
+ index, result_columns = self._make_index(
+ conv_data, alldata, columns, indexnamerow
+ )
+
+ return index, result_columns, conv_data
+
+ def _exclude_implicit_index(
+ self,
+ alldata: list[np.ndarray],
+ ) -> tuple[Mapping[Hashable, np.ndarray], Sequence[Hashable]]:
+ # error: Cannot determine type of 'index_col'
+ names = dedup_names(
+ self.orig_names,
+ is_potential_multi_index(
+ self.orig_names,
+ self.index_col, # type: ignore[has-type]
+ ),
+ )
+
+ offset = 0
+ if self._implicit_index:
+ # error: Cannot determine type of 'index_col'
+ offset = len(self.index_col) # type: ignore[has-type]
+
+ len_alldata = len(alldata)
+ self._check_data_length(names, alldata)
+
+ return {
+ name: alldata[i + offset] for i, name in enumerate(names) if i < len_alldata
+ }, names
+
+ # legacy
+ def get_chunk(
+ self, size: int | None = None
+ ) -> tuple[
+ Index | None, Sequence[Hashable] | MultiIndex, Mapping[Hashable, ArrayLike]
+ ]:
+ if size is None:
+ # error: "PythonParser" has no attribute "chunksize"
+ size = self.chunksize # type: ignore[attr-defined]
+ return self.read(rows=size)
+
+ def _convert_data(
+ self,
+ data: Mapping[Hashable, np.ndarray],
+ ) -> Mapping[Hashable, ArrayLike]:
+ # apply converters
+ clean_conv = self._clean_mapping(self.converters)
+ clean_dtypes = self._clean_mapping(self.dtype)
+
+ # Apply NA values.
+ clean_na_values = {}
+ clean_na_fvalues = {}
+
+ if isinstance(self.na_values, dict):
+ for col in self.na_values:
+ na_value = self.na_values[col]
+ na_fvalue = self.na_fvalues[col]
+
+ if isinstance(col, int) and col not in self.orig_names:
+ col = self.orig_names[col]
+
+ clean_na_values[col] = na_value
+ clean_na_fvalues[col] = na_fvalue
+ else:
+ clean_na_values = self.na_values
+ clean_na_fvalues = self.na_fvalues
+
+ return self._convert_to_ndarrays(
+ data,
+ clean_na_values,
+ clean_na_fvalues,
+ self.verbose,
+ clean_conv,
+ clean_dtypes,
+ )
+
+ @cache_readonly
+ def _have_mi_columns(self) -> bool:
+ if self.header is None:
+ return False
+
+ header = self.header
+ if isinstance(header, (list, tuple, np.ndarray)):
+ return len(header) > 1
+ else:
+ return False
+
+ def _infer_columns(
+ self,
+ ) -> tuple[list[list[Scalar | None]], int, set[Scalar | None]]:
+ names = self.names
+ num_original_columns = 0
+ clear_buffer = True
+ unnamed_cols: set[Scalar | None] = set()
+
+ if self.header is not None:
+ header = self.header
+ have_mi_columns = self._have_mi_columns
+
+ if isinstance(header, (list, tuple, np.ndarray)):
+ # we have a mi columns, so read an extra line
+ if have_mi_columns:
+ header = list(header) + [header[-1] + 1]
+ else:
+ header = [header]
+
+ columns: list[list[Scalar | None]] = []
+ for level, hr in enumerate(header):
+ try:
+ line = self._buffered_line()
+
+ while self.line_pos <= hr:
+ line = self._next_line()
+
+ except StopIteration as err:
+ if 0 < self.line_pos <= hr and (
+ not have_mi_columns or hr != header[-1]
+ ):
+ # If no rows we want to raise a different message and if
+ # we have mi columns, the last line is not part of the header
+ joi = list(map(str, header[:-1] if have_mi_columns else header))
+ msg = f"[{','.join(joi)}], len of {len(joi)}, "
+ raise ValueError(
+ f"Passed header={msg}"
+ f"but only {self.line_pos} lines in file"
+ ) from err
+
+ # We have an empty file, so check
+ # if columns are provided. That will
+ # serve as the 'line' for parsing
+ if have_mi_columns and hr > 0:
+ if clear_buffer:
+ self._clear_buffer()
+ columns.append([None] * len(columns[-1]))
+ return columns, num_original_columns, unnamed_cols
+
+ if not self.names:
+ raise EmptyDataError("No columns to parse from file") from err
+
+ line = self.names[:]
+
+ this_columns: list[Scalar | None] = []
+ this_unnamed_cols = []
+
+ for i, c in enumerate(line):
+ if c == "":
+ if have_mi_columns:
+ col_name = f"Unnamed: {i}_level_{level}"
+ else:
+ col_name = f"Unnamed: {i}"
+
+ this_unnamed_cols.append(i)
+ this_columns.append(col_name)
+ else:
+ this_columns.append(c)
+
+ if not have_mi_columns:
+ counts: DefaultDict = defaultdict(int)
+ # Ensure that regular columns are used before unnamed ones
+ # to keep given names and mangle unnamed columns
+ col_loop_order = [
+ i
+ for i in range(len(this_columns))
+ if i not in this_unnamed_cols
+ ] + this_unnamed_cols
+
+ # TODO: Use pandas.io.common.dedup_names instead (see #50371)
+ for i in col_loop_order:
+ col = this_columns[i]
+ old_col = col
+ cur_count = counts[col]
+
+ if cur_count > 0:
+ while cur_count > 0:
+ counts[old_col] = cur_count + 1
+ col = f"{old_col}.{cur_count}"
+ if col in this_columns:
+ cur_count += 1
+ else:
+ cur_count = counts[col]
+
+ if (
+ self.dtype is not None
+ and is_dict_like(self.dtype)
+ and self.dtype.get(old_col) is not None
+ and self.dtype.get(col) is None
+ ):
+ self.dtype.update({col: self.dtype.get(old_col)})
+ this_columns[i] = col
+ counts[col] = cur_count + 1
+ elif have_mi_columns:
+ # if we have grabbed an extra line, but its not in our
+ # format so save in the buffer, and create an blank extra
+ # line for the rest of the parsing code
+ if hr == header[-1]:
+ lc = len(this_columns)
+ # error: Cannot determine type of 'index_col'
+ sic = self.index_col # type: ignore[has-type]
+ ic = len(sic) if sic is not None else 0
+ unnamed_count = len(this_unnamed_cols)
+
+ # if wrong number of blanks or no index, not our format
+ if (lc != unnamed_count and lc - ic > unnamed_count) or ic == 0:
+ clear_buffer = False
+ this_columns = [None] * lc
+ self.buf = [self.buf[-1]]
+
+ columns.append(this_columns)
+ unnamed_cols.update({this_columns[i] for i in this_unnamed_cols})
+
+ if len(columns) == 1:
+ num_original_columns = len(this_columns)
+
+ if clear_buffer:
+ self._clear_buffer()
+
+ first_line: list[Scalar] | None
+ if names is not None:
+ # Read first row after header to check if data are longer
+ try:
+ first_line = self._next_line()
+ except StopIteration:
+ first_line = None
+
+ len_first_data_row = 0 if first_line is None else len(first_line)
+
+ if len(names) > len(columns[0]) and len(names) > len_first_data_row:
+ raise ValueError(
+ "Number of passed names did not match "
+ "number of header fields in the file"
+ )
+ if len(columns) > 1:
+ raise TypeError("Cannot pass names with multi-index columns")
+
+ if self.usecols is not None:
+ # Set _use_cols. We don't store columns because they are
+ # overwritten.
+ self._handle_usecols(columns, names, num_original_columns)
+ else:
+ num_original_columns = len(names)
+ if self._col_indices is not None and len(names) != len(
+ self._col_indices
+ ):
+ columns = [[names[i] for i in sorted(self._col_indices)]]
+ else:
+ columns = [names]
+ else:
+ columns = self._handle_usecols(
+ columns, columns[0], num_original_columns
+ )
+ else:
+ ncols = len(self._header_line)
+ num_original_columns = ncols
+
+ if not names:
+ columns = [list(range(ncols))]
+ columns = self._handle_usecols(columns, columns[0], ncols)
+ elif self.usecols is None or len(names) >= ncols:
+ columns = self._handle_usecols([names], names, ncols)
+ num_original_columns = len(names)
+ elif not callable(self.usecols) and len(names) != len(self.usecols):
+ raise ValueError(
+ "Number of passed names did not match number of "
+ "header fields in the file"
+ )
+ else:
+ # Ignore output but set used columns.
+ columns = [names]
+ self._handle_usecols(columns, columns[0], ncols)
+
+ return columns, num_original_columns, unnamed_cols
+
+ @cache_readonly
+ def _header_line(self):
+ # Store line for reuse in _get_index_name
+ if self.header is not None:
+ return None
+
+ try:
+ line = self._buffered_line()
+ except StopIteration as err:
+ if not self.names:
+ raise EmptyDataError("No columns to parse from file") from err
+
+ line = self.names[:]
+ return line
+
+ def _handle_usecols(
+ self,
+ columns: list[list[Scalar | None]],
+ usecols_key: list[Scalar | None],
+ num_original_columns: int,
+ ) -> list[list[Scalar | None]]:
+ """
+ Sets self._col_indices
+
+ usecols_key is used if there are string usecols.
+ """
+ col_indices: set[int] | list[int]
+ if self.usecols is not None:
+ if callable(self.usecols):
+ col_indices = self._evaluate_usecols(self.usecols, usecols_key)
+ elif any(isinstance(u, str) for u in self.usecols):
+ if len(columns) > 1:
+ raise ValueError(
+ "If using multiple headers, usecols must be integers."
+ )
+ col_indices = []
+
+ for col in self.usecols:
+ if isinstance(col, str):
+ try:
+ col_indices.append(usecols_key.index(col))
+ except ValueError:
+ self._validate_usecols_names(self.usecols, usecols_key)
+ else:
+ col_indices.append(col)
+ else:
+ missing_usecols = [
+ col for col in self.usecols if col >= num_original_columns
+ ]
+ if missing_usecols:
+ raise ParserError(
+ "Defining usecols without of bounds indices is not allowed. "
+ f"{missing_usecols} are out of bounds.",
+ )
+ col_indices = self.usecols
+
+ columns = [
+ [n for i, n in enumerate(column) if i in col_indices]
+ for column in columns
+ ]
+ self._col_indices = sorted(col_indices)
+ return columns
+
+ def _buffered_line(self) -> list[Scalar]:
+ """
+ Return a line from buffer, filling buffer if required.
+ """
+ if len(self.buf) > 0:
+ return self.buf[0]
+ else:
+ return self._next_line()
+
+ def _check_for_bom(self, first_row: list[Scalar]) -> list[Scalar]:
+ """
+ Checks whether the file begins with the BOM character.
+ If it does, remove it. In addition, if there is quoting
+ in the field subsequent to the BOM, remove it as well
+ because it technically takes place at the beginning of
+ the name, not the middle of it.
+ """
+ # first_row will be a list, so we need to check
+ # that that list is not empty before proceeding.
+ if not first_row:
+ return first_row
+
+ # The first element of this row is the one that could have the
+ # BOM that we want to remove. Check that the first element is a
+ # string before proceeding.
+ if not isinstance(first_row[0], str):
+ return first_row
+
+ # Check that the string is not empty, as that would
+ # obviously not have a BOM at the start of it.
+ if not first_row[0]:
+ return first_row
+
+ # Since the string is non-empty, check that it does
+ # in fact begin with a BOM.
+ first_elt = first_row[0][0]
+ if first_elt != _BOM:
+ return first_row
+
+ first_row_bom = first_row[0]
+ new_row: str
+
+ if len(first_row_bom) > 1 and first_row_bom[1] == self.quotechar:
+ start = 2
+ quote = first_row_bom[1]
+ end = first_row_bom[2:].index(quote) + 2
+
+ # Extract the data between the quotation marks
+ new_row = first_row_bom[start:end]
+
+ # Extract any remaining data after the second
+ # quotation mark.
+ if len(first_row_bom) > end + 1:
+ new_row += first_row_bom[end + 1 :]
+
+ else:
+ # No quotation so just remove BOM from first element
+ new_row = first_row_bom[1:]
+
+ new_row_list: list[Scalar] = [new_row]
+ return new_row_list + first_row[1:]
+
+ def _is_line_empty(self, line: list[Scalar]) -> bool:
+ """
+ Check if a line is empty or not.
+
+ Parameters
+ ----------
+ line : str, array-like
+ The line of data to check.
+
+ Returns
+ -------
+ boolean : Whether or not the line is empty.
+ """
+ return not line or all(not x for x in line)
+
+ def _next_line(self) -> list[Scalar]:
+ if isinstance(self.data, list):
+ while self.skipfunc(self.pos):
+ if self.pos >= len(self.data):
+ break
+ self.pos += 1
+
+ while True:
+ try:
+ line = self._check_comments([self.data[self.pos]])[0]
+ self.pos += 1
+ # either uncommented or blank to begin with
+ if not self.skip_blank_lines and (
+ self._is_line_empty(self.data[self.pos - 1]) or line
+ ):
+ break
+ if self.skip_blank_lines:
+ ret = self._remove_empty_lines([line])
+ if ret:
+ line = ret[0]
+ break
+ except IndexError:
+ raise StopIteration
+ else:
+ while self.skipfunc(self.pos):
+ self.pos += 1
+ # assert for mypy, data is Iterator[str] or None, would error in next
+ assert self.data is not None
+ next(self.data)
+
+ while True:
+ orig_line = self._next_iter_line(row_num=self.pos + 1)
+ self.pos += 1
+
+ if orig_line is not None:
+ line = self._check_comments([orig_line])[0]
+
+ if self.skip_blank_lines:
+ ret = self._remove_empty_lines([line])
+
+ if ret:
+ line = ret[0]
+ break
+ elif self._is_line_empty(orig_line) or line:
+ break
+
+ # This was the first line of the file,
+ # which could contain the BOM at the
+ # beginning of it.
+ if self.pos == 1:
+ line = self._check_for_bom(line)
+
+ self.line_pos += 1
+ self.buf.append(line)
+ return line
+
+ def _alert_malformed(self, msg: str, row_num: int) -> None:
+ """
+ Alert a user about a malformed row, depending on value of
+ `self.on_bad_lines` enum.
+
+ If `self.on_bad_lines` is ERROR, the alert will be `ParserError`.
+ If `self.on_bad_lines` is WARN, the alert will be printed out.
+
+ Parameters
+ ----------
+ msg: str
+ The error message to display.
+ row_num: int
+ The row number where the parsing error occurred.
+ Because this row number is displayed, we 1-index,
+ even though we 0-index internally.
+ """
+ if self.on_bad_lines == self.BadLineHandleMethod.ERROR:
+ raise ParserError(msg)
+ if self.on_bad_lines == self.BadLineHandleMethod.WARN:
+ base = f"Skipping line {row_num}: "
+ sys.stderr.write(base + msg + "\n")
+
+ def _next_iter_line(self, row_num: int) -> list[Scalar] | None:
+ """
+ Wrapper around iterating through `self.data` (CSV source).
+
+ When a CSV error is raised, we check for specific
+ error messages that allow us to customize the
+ error message displayed to the user.
+
+ Parameters
+ ----------
+ row_num: int
+ The row number of the line being parsed.
+ """
+ try:
+ # assert for mypy, data is Iterator[str] or None, would error in next
+ assert self.data is not None
+ line = next(self.data)
+ # for mypy
+ assert isinstance(line, list)
+ return line
+ except csv.Error as e:
+ if self.on_bad_lines in (
+ self.BadLineHandleMethod.ERROR,
+ self.BadLineHandleMethod.WARN,
+ ):
+ msg = str(e)
+
+ if "NULL byte" in msg or "line contains NUL" in msg:
+ msg = (
+ "NULL byte detected. This byte "
+ "cannot be processed in Python's "
+ "native csv library at the moment, "
+ "so please pass in engine='c' instead"
+ )
+
+ if self.skipfooter > 0:
+ reason = (
+ "Error could possibly be due to "
+ "parsing errors in the skipped footer rows "
+ "(the skipfooter keyword is only applied "
+ "after Python's csv library has parsed "
+ "all rows)."
+ )
+ msg += ". " + reason
+
+ self._alert_malformed(msg, row_num)
+ return None
+
+ def _check_comments(self, lines: list[list[Scalar]]) -> list[list[Scalar]]:
+ if self.comment is None:
+ return lines
+ ret = []
+ for line in lines:
+ rl = []
+ for x in line:
+ if (
+ not isinstance(x, str)
+ or self.comment not in x
+ or x in self.na_values
+ ):
+ rl.append(x)
+ else:
+ x = x[: x.find(self.comment)]
+ if len(x) > 0:
+ rl.append(x)
+ break
+ ret.append(rl)
+ return ret
+
+ def _remove_empty_lines(self, lines: list[list[Scalar]]) -> list[list[Scalar]]:
+ """
+ Iterate through the lines and remove any that are
+ either empty or contain only one whitespace value
+
+ Parameters
+ ----------
+ lines : list of list of Scalars
+ The array of lines that we are to filter.
+
+ Returns
+ -------
+ filtered_lines : list of list of Scalars
+ The same array of lines with the "empty" ones removed.
+ """
+ # Remove empty lines and lines with only one whitespace value
+ ret = [
+ line
+ for line in lines
+ if (
+ len(line) > 1
+ or len(line) == 1
+ and (not isinstance(line[0], str) or line[0].strip())
+ )
+ ]
+ return ret
+
+ def _check_thousands(self, lines: list[list[Scalar]]) -> list[list[Scalar]]:
+ if self.thousands is None:
+ return lines
+
+ return self._search_replace_num_columns(
+ lines=lines, search=self.thousands, replace=""
+ )
+
+ def _search_replace_num_columns(
+ self, lines: list[list[Scalar]], search: str, replace: str
+ ) -> list[list[Scalar]]:
+ ret = []
+ for line in lines:
+ rl = []
+ for i, x in enumerate(line):
+ if (
+ not isinstance(x, str)
+ or search not in x
+ or i in self._no_thousands_columns
+ or not self.num.search(x.strip())
+ ):
+ rl.append(x)
+ else:
+ rl.append(x.replace(search, replace))
+ ret.append(rl)
+ return ret
+
+ def _check_decimal(self, lines: list[list[Scalar]]) -> list[list[Scalar]]:
+ if self.decimal == parser_defaults["decimal"]:
+ return lines
+
+ return self._search_replace_num_columns(
+ lines=lines, search=self.decimal, replace="."
+ )
+
+ def _clear_buffer(self) -> None:
+ self.buf = []
+
+ def _get_index_name(
+ self,
+ ) -> tuple[Sequence[Hashable] | None, list[Hashable], list[Hashable]]:
+ """
+ Try several cases to get lines:
+
+ 0) There are headers on row 0 and row 1 and their
+ total summed lengths equals the length of the next line.
+ Treat row 0 as columns and row 1 as indices
+ 1) Look for implicit index: there are more columns
+ on row 1 than row 0. If this is true, assume that row
+ 1 lists index columns and row 0 lists normal columns.
+ 2) Get index from the columns if it was listed.
+ """
+ columns: Sequence[Hashable] = self.orig_names
+ orig_names = list(columns)
+ columns = list(columns)
+
+ line: list[Scalar] | None
+ if self._header_line is not None:
+ line = self._header_line
+ else:
+ try:
+ line = self._next_line()
+ except StopIteration:
+ line = None
+
+ next_line: list[Scalar] | None
+ try:
+ next_line = self._next_line()
+ except StopIteration:
+ next_line = None
+
+ # implicitly index_col=0 b/c 1 fewer column names
+ implicit_first_cols = 0
+ if line is not None:
+ # leave it 0, #2442
+ # Case 1
+ # error: Cannot determine type of 'index_col'
+ index_col = self.index_col # type: ignore[has-type]
+ if index_col is not False:
+ implicit_first_cols = len(line) - self.num_original_columns
+
+ # Case 0
+ if (
+ next_line is not None
+ and self.header is not None
+ and index_col is not False
+ ):
+ if len(next_line) == len(line) + self.num_original_columns:
+ # column and index names on diff rows
+ self.index_col = list(range(len(line)))
+ self.buf = self.buf[1:]
+
+ for c in reversed(line):
+ columns.insert(0, c)
+
+ # Update list of original names to include all indices.
+ orig_names = list(columns)
+ self.num_original_columns = len(columns)
+ return line, orig_names, columns
+
+ if implicit_first_cols > 0:
+ # Case 1
+ self._implicit_index = True
+ if self.index_col is None:
+ self.index_col = list(range(implicit_first_cols))
+
+ index_name = None
+
+ else:
+ # Case 2
+ (index_name, _, self.index_col) = self._clean_index_names(
+ columns, self.index_col
+ )
+
+ return index_name, orig_names, columns
+
+ def _rows_to_cols(self, content: list[list[Scalar]]) -> list[np.ndarray]:
+ col_len = self.num_original_columns
+
+ if self._implicit_index:
+ col_len += len(self.index_col)
+
+ max_len = max(len(row) for row in content)
+
+ # Check that there are no rows with too many
+ # elements in their row (rows with too few
+ # elements are padded with NaN).
+ # error: Non-overlapping identity check (left operand type: "List[int]",
+ # right operand type: "Literal[False]")
+ if (
+ max_len > col_len
+ and self.index_col is not False # type: ignore[comparison-overlap]
+ and self.usecols is None
+ ):
+ footers = self.skipfooter if self.skipfooter else 0
+ bad_lines = []
+
+ iter_content = enumerate(content)
+ content_len = len(content)
+ content = []
+
+ for i, _content in iter_content:
+ actual_len = len(_content)
+
+ if actual_len > col_len:
+ if callable(self.on_bad_lines):
+ new_l = self.on_bad_lines(_content)
+ if new_l is not None:
+ content.append(new_l)
+ elif self.on_bad_lines in (
+ self.BadLineHandleMethod.ERROR,
+ self.BadLineHandleMethod.WARN,
+ ):
+ row_num = self.pos - (content_len - i + footers)
+ bad_lines.append((row_num, actual_len))
+
+ if self.on_bad_lines == self.BadLineHandleMethod.ERROR:
+ break
+ else:
+ content.append(_content)
+
+ for row_num, actual_len in bad_lines:
+ msg = (
+ f"Expected {col_len} fields in line {row_num + 1}, saw "
+ f"{actual_len}"
+ )
+ if (
+ self.delimiter
+ and len(self.delimiter) > 1
+ and self.quoting != csv.QUOTE_NONE
+ ):
+ # see gh-13374
+ reason = (
+ "Error could possibly be due to quotes being "
+ "ignored when a multi-char delimiter is used."
+ )
+ msg += ". " + reason
+
+ self._alert_malformed(msg, row_num + 1)
+
+ # see gh-13320
+ zipped_content = list(lib.to_object_array(content, min_width=col_len).T)
+
+ if self.usecols:
+ assert self._col_indices is not None
+ col_indices = self._col_indices
+
+ if self._implicit_index:
+ zipped_content = [
+ a
+ for i, a in enumerate(zipped_content)
+ if (
+ i < len(self.index_col)
+ or i - len(self.index_col) in col_indices
+ )
+ ]
+ else:
+ zipped_content = [
+ a for i, a in enumerate(zipped_content) if i in col_indices
+ ]
+ return zipped_content
+
+ def _get_lines(self, rows: int | None = None) -> list[list[Scalar]]:
+ lines = self.buf
+ new_rows = None
+
+ # already fetched some number
+ if rows is not None:
+ # we already have the lines in the buffer
+ if len(self.buf) >= rows:
+ new_rows, self.buf = self.buf[:rows], self.buf[rows:]
+
+ # need some lines
+ else:
+ rows -= len(self.buf)
+
+ if new_rows is None:
+ if isinstance(self.data, list):
+ if self.pos > len(self.data):
+ raise StopIteration
+ if rows is None:
+ new_rows = self.data[self.pos :]
+ new_pos = len(self.data)
+ else:
+ new_rows = self.data[self.pos : self.pos + rows]
+ new_pos = self.pos + rows
+
+ new_rows = self._remove_skipped_rows(new_rows)
+ lines.extend(new_rows)
+ self.pos = new_pos
+
+ else:
+ new_rows = []
+ try:
+ if rows is not None:
+ rows_to_skip = 0
+ if self.skiprows is not None and self.pos is not None:
+ # Only read additional rows if pos is in skiprows
+ rows_to_skip = len(
+ set(self.skiprows) - set(range(self.pos))
+ )
+
+ for _ in range(rows + rows_to_skip):
+ # assert for mypy, data is Iterator[str] or None, would
+ # error in next
+ assert self.data is not None
+ new_rows.append(next(self.data))
+
+ len_new_rows = len(new_rows)
+ new_rows = self._remove_skipped_rows(new_rows)
+ lines.extend(new_rows)
+ else:
+ rows = 0
+
+ while True:
+ new_row = self._next_iter_line(row_num=self.pos + rows + 1)
+ rows += 1
+
+ if new_row is not None:
+ new_rows.append(new_row)
+ len_new_rows = len(new_rows)
+
+ except StopIteration:
+ len_new_rows = len(new_rows)
+ new_rows = self._remove_skipped_rows(new_rows)
+ lines.extend(new_rows)
+ if len(lines) == 0:
+ raise
+ self.pos += len_new_rows
+
+ self.buf = []
+ else:
+ lines = new_rows
+
+ if self.skipfooter:
+ lines = lines[: -self.skipfooter]
+
+ lines = self._check_comments(lines)
+ if self.skip_blank_lines:
+ lines = self._remove_empty_lines(lines)
+ lines = self._check_thousands(lines)
+ return self._check_decimal(lines)
+
+ def _remove_skipped_rows(self, new_rows: list[list[Scalar]]) -> list[list[Scalar]]:
+ if self.skiprows:
+ return [
+ row for i, row in enumerate(new_rows) if not self.skipfunc(i + self.pos)
+ ]
+ return new_rows
+
+ def _set_no_thousand_columns(self) -> set[int]:
+ no_thousands_columns: set[int] = set()
+ if self.columns and self.parse_dates:
+ assert self._col_indices is not None
+ no_thousands_columns = self._set_noconvert_dtype_columns(
+ self._col_indices, self.columns
+ )
+ if self.columns and self.dtype:
+ assert self._col_indices is not None
+ for i, col in zip(self._col_indices, self.columns):
+ if not isinstance(self.dtype, dict) and not is_numeric_dtype(
+ self.dtype
+ ):
+ no_thousands_columns.add(i)
+ if (
+ isinstance(self.dtype, dict)
+ and col in self.dtype
+ and (
+ not is_numeric_dtype(self.dtype[col])
+ or is_bool_dtype(self.dtype[col])
+ )
+ ):
+ no_thousands_columns.add(i)
+ return no_thousands_columns
+
+
+class FixedWidthReader(abc.Iterator):
+ """
+ A reader of fixed-width lines.
+ """
+
+ def __init__(
+ self,
+ f: IO[str] | ReadCsvBuffer[str],
+ colspecs: list[tuple[int, int]] | Literal["infer"],
+ delimiter: str | None,
+ comment: str | None,
+ skiprows: set[int] | None = None,
+ infer_nrows: int = 100,
+ ) -> None:
+ self.f = f
+ self.buffer: Iterator | None = None
+ self.delimiter = "\r\n" + delimiter if delimiter else "\n\r\t "
+ self.comment = comment
+ if colspecs == "infer":
+ self.colspecs = self.detect_colspecs(
+ infer_nrows=infer_nrows, skiprows=skiprows
+ )
+ else:
+ self.colspecs = colspecs
+
+ if not isinstance(self.colspecs, (tuple, list)):
+ raise TypeError(
+ "column specifications must be a list or tuple, "
+ f"input was a {type(colspecs).__name__}"
+ )
+
+ for colspec in self.colspecs:
+ if not (
+ isinstance(colspec, (tuple, list))
+ and len(colspec) == 2
+ and isinstance(colspec[0], (int, np.integer, type(None)))
+ and isinstance(colspec[1], (int, np.integer, type(None)))
+ ):
+ raise TypeError(
+ "Each column specification must be "
+ "2 element tuple or list of integers"
+ )
+
+ def get_rows(self, infer_nrows: int, skiprows: set[int] | None = None) -> list[str]:
+ """
+ Read rows from self.f, skipping as specified.
+
+ We distinguish buffer_rows (the first <= infer_nrows
+ lines) from the rows returned to detect_colspecs
+ because it's simpler to leave the other locations
+ with skiprows logic alone than to modify them to
+ deal with the fact we skipped some rows here as
+ well.
+
+ Parameters
+ ----------
+ infer_nrows : int
+ Number of rows to read from self.f, not counting
+ rows that are skipped.
+ skiprows: set, optional
+ Indices of rows to skip.
+
+ Returns
+ -------
+ detect_rows : list of str
+ A list containing the rows to read.
+
+ """
+ if skiprows is None:
+ skiprows = set()
+ buffer_rows = []
+ detect_rows = []
+ for i, row in enumerate(self.f):
+ if i not in skiprows:
+ detect_rows.append(row)
+ buffer_rows.append(row)
+ if len(detect_rows) >= infer_nrows:
+ break
+ self.buffer = iter(buffer_rows)
+ return detect_rows
+
+ def detect_colspecs(
+ self, infer_nrows: int = 100, skiprows: set[int] | None = None
+ ) -> list[tuple[int, int]]:
+ # Regex escape the delimiters
+ delimiters = "".join([rf"\{x}" for x in self.delimiter])
+ pattern = re.compile(f"([^{delimiters}]+)")
+ rows = self.get_rows(infer_nrows, skiprows)
+ if not rows:
+ raise EmptyDataError("No rows from which to infer column width")
+ max_len = max(map(len, rows))
+ mask = np.zeros(max_len + 1, dtype=int)
+ if self.comment is not None:
+ rows = [row.partition(self.comment)[0] for row in rows]
+ for row in rows:
+ for m in pattern.finditer(row):
+ mask[m.start() : m.end()] = 1
+ shifted = np.roll(mask, 1)
+ shifted[0] = 0
+ edges = np.where((mask ^ shifted) == 1)[0]
+ edge_pairs = list(zip(edges[::2], edges[1::2]))
+ return edge_pairs
+
+ def __next__(self) -> list[str]:
+ # Argument 1 to "next" has incompatible type "Union[IO[str],
+ # ReadCsvBuffer[str]]"; expected "SupportsNext[str]"
+ if self.buffer is not None:
+ try:
+ line = next(self.buffer)
+ except StopIteration:
+ self.buffer = None
+ line = next(self.f) # type: ignore[arg-type]
+ else:
+ line = next(self.f) # type: ignore[arg-type]
+ # Note: 'colspecs' is a sequence of half-open intervals.
+ return [line[from_:to].strip(self.delimiter) for (from_, to) in self.colspecs]
+
+
+class FixedWidthFieldParser(PythonParser):
+ """
+ Specialization that Converts fixed-width fields into DataFrames.
+ See PythonParser for details.
+ """
+
+ def __init__(self, f: ReadCsvBuffer[str], **kwds) -> None:
+ # Support iterators, convert to a list.
+ self.colspecs = kwds.pop("colspecs")
+ self.infer_nrows = kwds.pop("infer_nrows")
+ PythonParser.__init__(self, f, **kwds)
+
+ def _make_reader(self, f: IO[str] | ReadCsvBuffer[str]) -> FixedWidthReader:
+ return FixedWidthReader(
+ f,
+ self.colspecs,
+ self.delimiter,
+ self.comment,
+ self.skiprows,
+ self.infer_nrows,
+ )
+
+ def _remove_empty_lines(self, lines: list[list[Scalar]]) -> list[list[Scalar]]:
+ """
+ Returns the list of lines without the empty ones. With fixed-width
+ fields, empty lines become arrays of empty strings.
+
+ See PythonParser._remove_empty_lines.
+ """
+ return [
+ line
+ for line in lines
+ if any(not isinstance(e, str) or e.strip() for e in line)
+ ]
+
+
+def count_empty_vals(vals) -> int:
+ return sum(1 for v in vals if v == "" or v is None)
+
+
+def _validate_skipfooter_arg(skipfooter: int) -> int:
+ """
+ Validate the 'skipfooter' parameter.
+
+ Checks whether 'skipfooter' is a non-negative integer.
+ Raises a ValueError if that is not the case.
+
+ Parameters
+ ----------
+ skipfooter : non-negative integer
+ The number of rows to skip at the end of the file.
+
+ Returns
+ -------
+ validated_skipfooter : non-negative integer
+ The original input if the validation succeeds.
+
+ Raises
+ ------
+ ValueError : 'skipfooter' was not a non-negative integer.
+ """
+ if not is_integer(skipfooter):
+ raise ValueError("skipfooter must be an integer")
+
+ if skipfooter < 0:
+ raise ValueError("skipfooter cannot be negative")
+
+ # Incompatible return value type (got "Union[int, integer[Any]]", expected "int")
+ return skipfooter # type: ignore[return-value]
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/readers.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/readers.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fad2b779ab2868f38f3805b0d86c15bf102beab
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/parsers/readers.py
@@ -0,0 +1,2171 @@
+"""
+Module contains tools for processing files into DataFrames or other objects
+
+GH#48849 provides a convenient way of deprecating keyword arguments
+"""
+from __future__ import annotations
+
+from collections import abc
+import csv
+import sys
+from textwrap import fill
+from typing import (
+ IO,
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Literal,
+ NamedTuple,
+ TypedDict,
+ overload,
+)
+import warnings
+
+import numpy as np
+
+from pandas._libs import lib
+from pandas._libs.parsers import STR_NA_VALUES
+from pandas.errors import (
+ AbstractMethodError,
+ ParserWarning,
+)
+from pandas.util._decorators import Appender
+from pandas.util._exceptions import find_stack_level
+from pandas.util._validators import check_dtype_backend
+
+from pandas.core.dtypes.common import (
+ is_file_like,
+ is_float,
+ is_integer,
+ is_list_like,
+)
+
+from pandas.core.frame import DataFrame
+from pandas.core.indexes.api import RangeIndex
+from pandas.core.shared_docs import _shared_docs
+
+from pandas.io.common import (
+ IOHandles,
+ get_handle,
+ stringify_path,
+ validate_header_arg,
+)
+from pandas.io.parsers.arrow_parser_wrapper import ArrowParserWrapper
+from pandas.io.parsers.base_parser import (
+ ParserBase,
+ is_index_col,
+ parser_defaults,
+)
+from pandas.io.parsers.c_parser_wrapper import CParserWrapper
+from pandas.io.parsers.python_parser import (
+ FixedWidthFieldParser,
+ PythonParser,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import (
+ Hashable,
+ Mapping,
+ Sequence,
+ )
+ from types import TracebackType
+
+ from pandas._typing import (
+ CompressionOptions,
+ CSVEngine,
+ DtypeArg,
+ DtypeBackend,
+ FilePath,
+ HashableT,
+ IndexLabel,
+ ReadCsvBuffer,
+ StorageOptions,
+ )
+_doc_read_csv_and_table = (
+ r"""
+{summary}
+
+Also supports optionally iterating or breaking of the file
+into chunks.
+
+Additional help can be found in the online docs for
+`IO Tools `_.
+
+Parameters
+----------
+filepath_or_buffer : str, path object or file-like object
+ Any valid string path is acceptable. The string could be a URL. Valid
+ URL schemes include http, ftp, s3, gs, and file. For file URLs, a host is
+ expected. A local file could be: file://localhost/path/to/table.csv.
+
+ If you want to pass in a path object, pandas accepts any ``os.PathLike``.
+
+ By file-like object, we refer to objects with a ``read()`` method, such as
+ a file handle (e.g. via builtin ``open`` function) or ``StringIO``.
+sep : str, default {_default_sep}
+ Character or regex pattern to treat as the delimiter. If ``sep=None``, the
+ C engine cannot automatically detect
+ the separator, but the Python parsing engine can, meaning the latter will
+ be used and automatically detect the separator from only the first valid
+ row of the file by Python's builtin sniffer tool, ``csv.Sniffer``.
+ In addition, separators longer than 1 character and different from
+ ``'\s+'`` will be interpreted as regular expressions and will also force
+ the use of the Python parsing engine. Note that regex delimiters are prone
+ to ignoring quoted data. Regex example: ``'\r\t'``.
+delimiter : str, optional
+ Alias for ``sep``.
+header : int, Sequence of int, 'infer' or None, default 'infer'
+ Row number(s) containing column labels and marking the start of the
+ data (zero-indexed). Default behavior is to infer the column names: if no ``names``
+ are passed the behavior is identical to ``header=0`` and column
+ names are inferred from the first line of the file, if column
+ names are passed explicitly to ``names`` then the behavior is identical to
+ ``header=None``. Explicitly pass ``header=0`` to be able to
+ replace existing names. The header can be a list of integers that
+ specify row locations for a :class:`~pandas.MultiIndex` on the columns
+ e.g. ``[0, 1, 3]``. Intervening rows that are not specified will be
+ skipped (e.g. 2 in this example is skipped). Note that this
+ parameter ignores commented lines and empty lines if
+ ``skip_blank_lines=True``, so ``header=0`` denotes the first line of
+ data rather than the first line of the file.
+names : Sequence of Hashable, optional
+ Sequence of column labels to apply. If the file contains a header row,
+ then you should explicitly pass ``header=0`` to override the column names.
+ Duplicates in this list are not allowed.
+index_col : Hashable, Sequence of Hashable or False, optional
+ Column(s) to use as row label(s), denoted either by column labels or column
+ indices. If a sequence of labels or indices is given, :class:`~pandas.MultiIndex`
+ will be formed for the row labels.
+
+ Note: ``index_col=False`` can be used to force pandas to *not* use the first
+ column as the index, e.g., when you have a malformed file with delimiters at
+ the end of each line.
+usecols : list of Hashable or Callable, optional
+ Subset of columns to select, denoted either by column labels or column indices.
+ If list-like, all elements must either
+ be positional (i.e. integer indices into the document columns) or strings
+ that correspond to column names provided either by the user in ``names`` or
+ inferred from the document header row(s). If ``names`` are given, the document
+ header row(s) are not taken into account. For example, a valid list-like
+ ``usecols`` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``.
+ Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``.
+ To instantiate a :class:`~pandas.DataFrame` from ``data`` with element order
+ preserved use ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]``
+ for columns in ``['foo', 'bar']`` order or
+ ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]``
+ for ``['bar', 'foo']`` order.
+
+ If callable, the callable function will be evaluated against the column
+ names, returning names where the callable function evaluates to ``True``. An
+ example of a valid callable argument would be ``lambda x: x.upper() in
+ ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster
+ parsing time and lower memory usage.
+dtype : dtype or dict of {{Hashable : dtype}}, optional
+ Data type(s) to apply to either the whole dataset or individual columns.
+ E.g., ``{{'a': np.float64, 'b': np.int32, 'c': 'Int64'}}``
+ Use ``str`` or ``object`` together with suitable ``na_values`` settings
+ to preserve and not interpret ``dtype``.
+ If ``converters`` are specified, they will be applied INSTEAD
+ of ``dtype`` conversion.
+
+ .. versionadded:: 1.5.0
+
+ Support for ``defaultdict`` was added. Specify a ``defaultdict`` as input where
+ the default determines the ``dtype`` of the columns which are not explicitly
+ listed.
+engine : {{'c', 'python', 'pyarrow'}}, optional
+ Parser engine to use. The C and pyarrow engines are faster, while the python engine
+ is currently more feature-complete. Multithreading is currently only supported by
+ the pyarrow engine.
+
+ .. versionadded:: 1.4.0
+
+ The 'pyarrow' engine was added as an *experimental* engine, and some features
+ are unsupported, or may not work correctly, with this engine.
+converters : dict of {{Hashable : Callable}}, optional
+ Functions for converting values in specified columns. Keys can either
+ be column labels or column indices.
+true_values : list, optional
+ Values to consider as ``True`` in addition to case-insensitive variants of 'True'.
+false_values : list, optional
+ Values to consider as ``False`` in addition to case-insensitive variants of 'False'.
+skipinitialspace : bool, default False
+ Skip spaces after delimiter.
+skiprows : int, list of int or Callable, optional
+ Line numbers to skip (0-indexed) or number of lines to skip (``int``)
+ at the start of the file.
+
+ If callable, the callable function will be evaluated against the row
+ indices, returning ``True`` if the row should be skipped and ``False`` otherwise.
+ An example of a valid callable argument would be ``lambda x: x in [0, 2]``.
+skipfooter : int, default 0
+ Number of lines at bottom of file to skip (Unsupported with ``engine='c'``).
+nrows : int, optional
+ Number of rows of file to read. Useful for reading pieces of large files.
+na_values : Hashable, Iterable of Hashable or dict of {{Hashable : Iterable}}, optional
+ Additional strings to recognize as ``NA``/``NaN``. If ``dict`` passed, specific
+ per-column ``NA`` values. By default the following values are interpreted as
+ ``NaN``: " """
+ + fill('", "'.join(sorted(STR_NA_VALUES)), 70, subsequent_indent=" ")
+ + """ ".
+
+keep_default_na : bool, default True
+ Whether or not to include the default ``NaN`` values when parsing the data.
+ Depending on whether ``na_values`` is passed in, the behavior is as follows:
+
+ * If ``keep_default_na`` is ``True``, and ``na_values`` are specified, ``na_values``
+ is appended to the default ``NaN`` values used for parsing.
+ * If ``keep_default_na`` is ``True``, and ``na_values`` are not specified, only
+ the default ``NaN`` values are used for parsing.
+ * If ``keep_default_na`` is ``False``, and ``na_values`` are specified, only
+ the ``NaN`` values specified ``na_values`` are used for parsing.
+ * If ``keep_default_na`` is ``False``, and ``na_values`` are not specified, no
+ strings will be parsed as ``NaN``.
+
+ Note that if ``na_filter`` is passed in as ``False``, the ``keep_default_na`` and
+ ``na_values`` parameters will be ignored.
+na_filter : bool, default True
+ Detect missing value markers (empty strings and the value of ``na_values``). In
+ data without any ``NA`` values, passing ``na_filter=False`` can improve the
+ performance of reading a large file.
+verbose : bool, default False
+ Indicate number of ``NA`` values placed in non-numeric columns.
+skip_blank_lines : bool, default True
+ If ``True``, skip over blank lines rather than interpreting as ``NaN`` values.
+parse_dates : bool, list of Hashable, list of lists or dict of {{Hashable : list}}, \
+default False
+ The behavior is as follows:
+
+ * ``bool``. If ``True`` -> try parsing the index.
+ * ``list`` of ``int`` or names. e.g. If ``[1, 2, 3]`` -> try parsing columns 1, 2, 3
+ each as a separate date column.
+ * ``list`` of ``list``. e.g. If ``[[1, 3]]`` -> combine columns 1 and 3 and parse
+ as a single date column.
+ * ``dict``, e.g. ``{{'foo' : [1, 3]}}`` -> parse columns 1, 3 as date and call
+ result 'foo'
+
+ If a column or index cannot be represented as an array of ``datetime``,
+ say because of an unparsable value or a mixture of timezones, the column
+ or index will be returned unaltered as an ``object`` data type. For
+ non-standard ``datetime`` parsing, use :func:`~pandas.to_datetime` after
+ :func:`~pandas.read_csv`.
+
+ Note: A fast-path exists for iso8601-formatted dates.
+infer_datetime_format : bool, default False
+ If ``True`` and ``parse_dates`` is enabled, pandas will attempt to infer the
+ format of the ``datetime`` strings in the columns, and if it can be inferred,
+ switch to a faster method of parsing them. In some cases this can increase
+ the parsing speed by 5-10x.
+
+ .. deprecated:: 2.0.0
+ A strict version of this argument is now the default, passing it has no effect.
+
+keep_date_col : bool, default False
+ If ``True`` and ``parse_dates`` specifies combining multiple columns then
+ keep the original columns.
+date_parser : Callable, optional
+ Function to use for converting a sequence of string columns to an array of
+ ``datetime`` instances. The default uses ``dateutil.parser.parser`` to do the
+ conversion. pandas will try to call ``date_parser`` in three different ways,
+ advancing to the next if an exception occurs: 1) Pass one or more arrays
+ (as defined by ``parse_dates``) as arguments; 2) concatenate (row-wise) the
+ string values from the columns defined by ``parse_dates`` into a single array
+ and pass that; and 3) call ``date_parser`` once for each row using one or
+ more strings (corresponding to the columns defined by ``parse_dates``) as
+ arguments.
+
+ .. deprecated:: 2.0.0
+ Use ``date_format`` instead, or read in as ``object`` and then apply
+ :func:`~pandas.to_datetime` as-needed.
+date_format : str or dict of column -> format, optional
+ Format to use for parsing dates when used in conjunction with ``parse_dates``.
+ For anything more complex, please read in as ``object`` and then apply
+ :func:`~pandas.to_datetime` as-needed.
+
+ .. versionadded:: 2.0.0
+dayfirst : bool, default False
+ DD/MM format dates, international and European format.
+cache_dates : bool, default True
+ If ``True``, use a cache of unique, converted dates to apply the ``datetime``
+ conversion. May produce significant speed-up when parsing duplicate
+ date strings, especially ones with timezone offsets.
+
+iterator : bool, default False
+ Return ``TextFileReader`` object for iteration or getting chunks with
+ ``get_chunk()``.
+
+ .. versionchanged:: 1.2
+
+ ``TextFileReader`` is a context manager.
+chunksize : int, optional
+ Number of lines to read from the file per chunk. Passing a value will cause the
+ function to return a ``TextFileReader`` object for iteration.
+ See the `IO Tools docs
+ `_
+ for more information on ``iterator`` and ``chunksize``.
+
+ .. versionchanged:: 1.2
+
+ ``TextFileReader`` is a context manager.
+{decompression_options}
+
+ .. versionchanged:: 1.4.0 Zstandard support.
+
+thousands : str (length 1), optional
+ Character acting as the thousands separator in numerical values.
+decimal : str (length 1), default '.'
+ Character to recognize as decimal point (e.g., use ',' for European data).
+lineterminator : str (length 1), optional
+ Character used to denote a line break. Only valid with C parser.
+quotechar : str (length 1), optional
+ Character used to denote the start and end of a quoted item. Quoted
+ items can include the ``delimiter`` and it will be ignored.
+quoting : {{0 or csv.QUOTE_MINIMAL, 1 or csv.QUOTE_ALL, 2 or csv.QUOTE_NONNUMERIC, \
+3 or csv.QUOTE_NONE}}, default csv.QUOTE_MINIMAL
+ Control field quoting behavior per ``csv.QUOTE_*`` constants. Default is
+ ``csv.QUOTE_MINIMAL`` (i.e., 0) which implies that only fields containing special
+ characters are quoted (e.g., characters defined in ``quotechar``, ``delimiter``,
+ or ``lineterminator``.
+doublequote : bool, default True
+ When ``quotechar`` is specified and ``quoting`` is not ``QUOTE_NONE``, indicate
+ whether or not to interpret two consecutive ``quotechar`` elements INSIDE a
+ field as a single ``quotechar`` element.
+escapechar : str (length 1), optional
+ Character used to escape other characters.
+comment : str (length 1), optional
+ Character indicating that the remainder of line should not be parsed.
+ If found at the beginning
+ of a line, the line will be ignored altogether. This parameter must be a
+ single character. Like empty lines (as long as ``skip_blank_lines=True``),
+ fully commented lines are ignored by the parameter ``header`` but not by
+ ``skiprows``. For example, if ``comment='#'``, parsing
+ ``#empty\\na,b,c\\n1,2,3`` with ``header=0`` will result in ``'a,b,c'`` being
+ treated as the header.
+encoding : str, optional, default 'utf-8'
+ Encoding to use for UTF when reading/writing (ex. ``'utf-8'``). `List of Python
+ standard encodings
+ `_ .
+
+ .. versionchanged:: 1.2
+
+ When ``encoding`` is ``None``, ``errors='replace'`` is passed to
+ ``open()``. Otherwise, ``errors='strict'`` is passed to ``open()``.
+ This behavior was previously only the case for ``engine='python'``.
+
+ .. versionchanged:: 1.3.0
+
+ ``encoding_errors`` is a new argument. ``encoding`` has no longer an
+ influence on how encoding errors are handled.
+
+encoding_errors : str, optional, default 'strict'
+ How encoding errors are treated. `List of possible values
+ `_ .
+
+ .. versionadded:: 1.3.0
+
+dialect : str or csv.Dialect, optional
+ If provided, this parameter will override values (default or not) for the
+ following parameters: ``delimiter``, ``doublequote``, ``escapechar``,
+ ``skipinitialspace``, ``quotechar``, and ``quoting``. If it is necessary to
+ override values, a ``ParserWarning`` will be issued. See ``csv.Dialect``
+ documentation for more details.
+on_bad_lines : {{'error', 'warn', 'skip'}} or Callable, default 'error'
+ Specifies what to do upon encountering a bad line (a line with too many fields).
+ Allowed values are :
+
+ - ``'error'``, raise an Exception when a bad line is encountered.
+ - ``'warn'``, raise a warning when a bad line is encountered and skip that line.
+ - ``'skip'``, skip bad lines without raising or warning when they are encountered.
+
+ .. versionadded:: 1.3.0
+
+ .. versionadded:: 1.4.0
+
+ - Callable, function with signature
+ ``(bad_line: list[str]) -> list[str] | None`` that will process a single
+ bad line. ``bad_line`` is a list of strings split by the ``sep``.
+ If the function returns ``None``, the bad line will be ignored.
+ If the function returns a new ``list`` of strings with more elements than
+ expected, a ``ParserWarning`` will be emitted while dropping extra elements.
+ Only supported when ``engine='python'``
+
+delim_whitespace : bool, default False
+ Specifies whether or not whitespace (e.g. ``' '`` or ``'\\t'``) will be
+ used as the ``sep`` delimiter. Equivalent to setting ``sep='\\s+'``. If this option
+ is set to ``True``, nothing should be passed in for the ``delimiter``
+ parameter.
+low_memory : bool, default True
+ Internally process the file in chunks, resulting in lower memory use
+ while parsing, but possibly mixed type inference. To ensure no mixed
+ types either set ``False``, or specify the type with the ``dtype`` parameter.
+ Note that the entire file is read into a single :class:`~pandas.DataFrame`
+ regardless, use the ``chunksize`` or ``iterator`` parameter to return the data in
+ chunks. (Only valid with C parser).
+memory_map : bool, default False
+ If a filepath is provided for ``filepath_or_buffer``, map the file object
+ directly onto memory and access the data directly from there. Using this
+ option can improve performance because there is no longer any I/O overhead.
+float_precision : {{'high', 'legacy', 'round_trip'}}, optional
+ Specifies which converter the C engine should use for floating-point
+ values. The options are ``None`` or ``'high'`` for the ordinary converter,
+ ``'legacy'`` for the original lower precision pandas converter, and
+ ``'round_trip'`` for the round-trip converter.
+
+ .. versionchanged:: 1.2
+
+{storage_options}
+
+ .. versionadded:: 1.2
+
+dtype_backend : {{'numpy_nullable', 'pyarrow'}}, default 'numpy_nullable'
+ Back-end data type applied to the resultant :class:`DataFrame`
+ (still experimental). Behaviour is as follows:
+
+ * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
+ (default).
+ * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
+ DataFrame.
+
+ .. versionadded:: 2.0
+
+Returns
+-------
+DataFrame or TextFileReader
+ A comma-separated values (csv) file is returned as two-dimensional
+ data structure with labeled axes.
+
+See Also
+--------
+DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.
+{see_also_func_name} : {see_also_func_summary}
+read_fwf : Read a table of fixed-width formatted lines into DataFrame.
+
+Examples
+--------
+>>> pd.{func_name}('data.csv') # doctest: +SKIP
+"""
+)
+
+
+class _C_Parser_Defaults(TypedDict):
+ delim_whitespace: Literal[False]
+ na_filter: Literal[True]
+ low_memory: Literal[True]
+ memory_map: Literal[False]
+ float_precision: None
+
+
+_c_parser_defaults: _C_Parser_Defaults = {
+ "delim_whitespace": False,
+ "na_filter": True,
+ "low_memory": True,
+ "memory_map": False,
+ "float_precision": None,
+}
+
+
+class _Fwf_Defaults(TypedDict):
+ colspecs: Literal["infer"]
+ infer_nrows: Literal[100]
+ widths: None
+
+
+_fwf_defaults: _Fwf_Defaults = {"colspecs": "infer", "infer_nrows": 100, "widths": None}
+_c_unsupported = {"skipfooter"}
+_python_unsupported = {"low_memory", "float_precision"}
+_pyarrow_unsupported = {
+ "skipfooter",
+ "float_precision",
+ "chunksize",
+ "comment",
+ "nrows",
+ "thousands",
+ "memory_map",
+ "dialect",
+ "on_bad_lines",
+ "delim_whitespace",
+ "quoting",
+ "lineterminator",
+ "converters",
+ "iterator",
+ "dayfirst",
+ "verbose",
+ "skipinitialspace",
+ "low_memory",
+}
+
+
+class _DeprecationConfig(NamedTuple):
+ default_value: Any
+ msg: str | None
+
+
+@overload
+def validate_integer(name: str, val: None, min_val: int = ...) -> None:
+ ...
+
+
+@overload
+def validate_integer(name: str, val: float, min_val: int = ...) -> int:
+ ...
+
+
+@overload
+def validate_integer(name: str, val: int | None, min_val: int = ...) -> int | None:
+ ...
+
+
+def validate_integer(
+ name: str, val: int | float | None, min_val: int = 0
+) -> int | None:
+ """
+ Checks whether the 'name' parameter for parsing is either
+ an integer OR float that can SAFELY be cast to an integer
+ without losing accuracy. Raises a ValueError if that is
+ not the case.
+
+ Parameters
+ ----------
+ name : str
+ Parameter name (used for error reporting)
+ val : int or float
+ The value to check
+ min_val : int
+ Minimum allowed value (val < min_val will result in a ValueError)
+ """
+ if val is None:
+ return val
+
+ msg = f"'{name:s}' must be an integer >={min_val:d}"
+ if is_float(val):
+ if int(val) != val:
+ raise ValueError(msg)
+ val = int(val)
+ elif not (is_integer(val) and val >= min_val):
+ raise ValueError(msg)
+
+ return int(val)
+
+
+def _validate_names(names: Sequence[Hashable] | None) -> None:
+ """
+ Raise ValueError if the `names` parameter contains duplicates or has an
+ invalid data type.
+
+ Parameters
+ ----------
+ names : array-like or None
+ An array containing a list of the names used for the output DataFrame.
+
+ Raises
+ ------
+ ValueError
+ If names are not unique or are not ordered (e.g. set).
+ """
+ if names is not None:
+ if len(names) != len(set(names)):
+ raise ValueError("Duplicate names are not allowed.")
+ if not (
+ is_list_like(names, allow_sets=False) or isinstance(names, abc.KeysView)
+ ):
+ raise ValueError("Names should be an ordered collection.")
+
+
+def _read(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], kwds
+) -> DataFrame | TextFileReader:
+ """Generic reader of line files."""
+ # if we pass a date_parser and parse_dates=False, we should not parse the
+ # dates GH#44366
+ if kwds.get("parse_dates", None) is None:
+ if (
+ kwds.get("date_parser", lib.no_default) is lib.no_default
+ and kwds.get("date_format", None) is None
+ ):
+ kwds["parse_dates"] = False
+ else:
+ kwds["parse_dates"] = True
+
+ # Extract some of the arguments (pass chunksize on).
+ iterator = kwds.get("iterator", False)
+ chunksize = kwds.get("chunksize", None)
+ if kwds.get("engine") == "pyarrow":
+ if iterator:
+ raise ValueError(
+ "The 'iterator' option is not supported with the 'pyarrow' engine"
+ )
+
+ if chunksize is not None:
+ raise ValueError(
+ "The 'chunksize' option is not supported with the 'pyarrow' engine"
+ )
+ else:
+ chunksize = validate_integer("chunksize", chunksize, 1)
+
+ nrows = kwds.get("nrows", None)
+
+ # Check for duplicates in names.
+ _validate_names(kwds.get("names", None))
+
+ # Create the parser.
+ parser = TextFileReader(filepath_or_buffer, **kwds)
+
+ if chunksize or iterator:
+ return parser
+
+ with parser:
+ return parser.read(nrows)
+
+
+# iterator=True -> TextFileReader
+@overload
+def read_csv(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = ...,
+ delimiter: str | None | lib.NoDefault = ...,
+ header: int | Sequence[int] | None | Literal["infer"] = ...,
+ names: Sequence[Hashable] | None | lib.NoDefault = ...,
+ index_col: IndexLabel | Literal[False] | None = ...,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: CSVEngine | None = ...,
+ converters: Mapping[Hashable, Callable] | None = ...,
+ true_values: list | None = ...,
+ false_values: list | None = ...,
+ skipinitialspace: bool = ...,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = ...,
+ skipfooter: int = ...,
+ nrows: int | None = ...,
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ skip_blank_lines: bool = ...,
+ parse_dates: bool | Sequence[Hashable] | None = ...,
+ infer_datetime_format: bool | lib.NoDefault = ...,
+ keep_date_col: bool = ...,
+ date_parser: Callable | lib.NoDefault = ...,
+ date_format: str | None = ...,
+ dayfirst: bool = ...,
+ cache_dates: bool = ...,
+ iterator: Literal[True],
+ chunksize: int | None = ...,
+ compression: CompressionOptions = ...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ lineterminator: str | None = ...,
+ quotechar: str = ...,
+ quoting: int = ...,
+ doublequote: bool = ...,
+ escapechar: str | None = ...,
+ comment: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ dialect: str | csv.Dialect | None = ...,
+ on_bad_lines=...,
+ delim_whitespace: bool = ...,
+ low_memory: bool = ...,
+ memory_map: bool = ...,
+ float_precision: Literal["high", "legacy"] | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+) -> TextFileReader:
+ ...
+
+
+# chunksize=int -> TextFileReader
+@overload
+def read_csv(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = ...,
+ delimiter: str | None | lib.NoDefault = ...,
+ header: int | Sequence[int] | None | Literal["infer"] = ...,
+ names: Sequence[Hashable] | None | lib.NoDefault = ...,
+ index_col: IndexLabel | Literal[False] | None = ...,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: CSVEngine | None = ...,
+ converters: Mapping[Hashable, Callable] | None = ...,
+ true_values: list | None = ...,
+ false_values: list | None = ...,
+ skipinitialspace: bool = ...,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = ...,
+ skipfooter: int = ...,
+ nrows: int | None = ...,
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ skip_blank_lines: bool = ...,
+ parse_dates: bool | Sequence[Hashable] | None = ...,
+ infer_datetime_format: bool | lib.NoDefault = ...,
+ keep_date_col: bool = ...,
+ date_parser: Callable | lib.NoDefault = ...,
+ date_format: str | None = ...,
+ dayfirst: bool = ...,
+ cache_dates: bool = ...,
+ iterator: bool = ...,
+ chunksize: int,
+ compression: CompressionOptions = ...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ lineterminator: str | None = ...,
+ quotechar: str = ...,
+ quoting: int = ...,
+ doublequote: bool = ...,
+ escapechar: str | None = ...,
+ comment: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ dialect: str | csv.Dialect | None = ...,
+ on_bad_lines=...,
+ delim_whitespace: bool = ...,
+ low_memory: bool = ...,
+ memory_map: bool = ...,
+ float_precision: Literal["high", "legacy"] | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+) -> TextFileReader:
+ ...
+
+
+# default case -> DataFrame
+@overload
+def read_csv(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = ...,
+ delimiter: str | None | lib.NoDefault = ...,
+ header: int | Sequence[int] | None | Literal["infer"] = ...,
+ names: Sequence[Hashable] | None | lib.NoDefault = ...,
+ index_col: IndexLabel | Literal[False] | None = ...,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: CSVEngine | None = ...,
+ converters: Mapping[Hashable, Callable] | None = ...,
+ true_values: list | None = ...,
+ false_values: list | None = ...,
+ skipinitialspace: bool = ...,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = ...,
+ skipfooter: int = ...,
+ nrows: int | None = ...,
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ skip_blank_lines: bool = ...,
+ parse_dates: bool | Sequence[Hashable] | None = ...,
+ infer_datetime_format: bool | lib.NoDefault = ...,
+ keep_date_col: bool = ...,
+ date_parser: Callable | lib.NoDefault = ...,
+ date_format: str | None = ...,
+ dayfirst: bool = ...,
+ cache_dates: bool = ...,
+ iterator: Literal[False] = ...,
+ chunksize: None = ...,
+ compression: CompressionOptions = ...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ lineterminator: str | None = ...,
+ quotechar: str = ...,
+ quoting: int = ...,
+ doublequote: bool = ...,
+ escapechar: str | None = ...,
+ comment: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ dialect: str | csv.Dialect | None = ...,
+ on_bad_lines=...,
+ delim_whitespace: bool = ...,
+ low_memory: bool = ...,
+ memory_map: bool = ...,
+ float_precision: Literal["high", "legacy"] | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+) -> DataFrame:
+ ...
+
+
+# Unions -> DataFrame | TextFileReader
+@overload
+def read_csv(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = ...,
+ delimiter: str | None | lib.NoDefault = ...,
+ header: int | Sequence[int] | None | Literal["infer"] = ...,
+ names: Sequence[Hashable] | None | lib.NoDefault = ...,
+ index_col: IndexLabel | Literal[False] | None = ...,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: CSVEngine | None = ...,
+ converters: Mapping[Hashable, Callable] | None = ...,
+ true_values: list | None = ...,
+ false_values: list | None = ...,
+ skipinitialspace: bool = ...,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = ...,
+ skipfooter: int = ...,
+ nrows: int | None = ...,
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ skip_blank_lines: bool = ...,
+ parse_dates: bool | Sequence[Hashable] | None = ...,
+ infer_datetime_format: bool | lib.NoDefault = ...,
+ keep_date_col: bool = ...,
+ date_parser: Callable | lib.NoDefault = ...,
+ date_format: str | None = ...,
+ dayfirst: bool = ...,
+ cache_dates: bool = ...,
+ iterator: bool = ...,
+ chunksize: int | None = ...,
+ compression: CompressionOptions = ...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ lineterminator: str | None = ...,
+ quotechar: str = ...,
+ quoting: int = ...,
+ doublequote: bool = ...,
+ escapechar: str | None = ...,
+ comment: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ dialect: str | csv.Dialect | None = ...,
+ on_bad_lines=...,
+ delim_whitespace: bool = ...,
+ low_memory: bool = ...,
+ memory_map: bool = ...,
+ float_precision: Literal["high", "legacy"] | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+) -> DataFrame | TextFileReader:
+ ...
+
+
+@Appender(
+ _doc_read_csv_and_table.format(
+ func_name="read_csv",
+ summary="Read a comma-separated values (csv) file into DataFrame.",
+ see_also_func_name="read_table",
+ see_also_func_summary="Read general delimited file into DataFrame.",
+ _default_sep="','",
+ storage_options=_shared_docs["storage_options"],
+ decompression_options=_shared_docs["decompression_options"]
+ % "filepath_or_buffer",
+ )
+)
+def read_csv(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = lib.no_default,
+ delimiter: str | None | lib.NoDefault = None,
+ # Column and Index Locations and Names
+ header: int | Sequence[int] | None | Literal["infer"] = "infer",
+ names: Sequence[Hashable] | None | lib.NoDefault = lib.no_default,
+ index_col: IndexLabel | Literal[False] | None = None,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = None,
+ # General Parsing Configuration
+ dtype: DtypeArg | None = None,
+ engine: CSVEngine | None = None,
+ converters: Mapping[Hashable, Callable] | None = None,
+ true_values: list | None = None,
+ false_values: list | None = None,
+ skipinitialspace: bool = False,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = None,
+ skipfooter: int = 0,
+ nrows: int | None = None,
+ # NA and Missing Data Handling
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
+ keep_default_na: bool = True,
+ na_filter: bool = True,
+ verbose: bool = False,
+ skip_blank_lines: bool = True,
+ # Datetime Handling
+ parse_dates: bool | Sequence[Hashable] | None = None,
+ infer_datetime_format: bool | lib.NoDefault = lib.no_default,
+ keep_date_col: bool = False,
+ date_parser: Callable | lib.NoDefault = lib.no_default,
+ date_format: str | None = None,
+ dayfirst: bool = False,
+ cache_dates: bool = True,
+ # Iteration
+ iterator: bool = False,
+ chunksize: int | None = None,
+ # Quoting, Compression, and File Format
+ compression: CompressionOptions = "infer",
+ thousands: str | None = None,
+ decimal: str = ".",
+ lineterminator: str | None = None,
+ quotechar: str = '"',
+ quoting: int = csv.QUOTE_MINIMAL,
+ doublequote: bool = True,
+ escapechar: str | None = None,
+ comment: str | None = None,
+ encoding: str | None = None,
+ encoding_errors: str | None = "strict",
+ dialect: str | csv.Dialect | None = None,
+ # Error Handling
+ on_bad_lines: str = "error",
+ # Internal
+ delim_whitespace: bool = False,
+ low_memory: bool = _c_parser_defaults["low_memory"],
+ memory_map: bool = False,
+ float_precision: Literal["high", "legacy"] | None = None,
+ storage_options: StorageOptions | None = None,
+ dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
+) -> DataFrame | TextFileReader:
+ if infer_datetime_format is not lib.no_default:
+ warnings.warn(
+ "The argument 'infer_datetime_format' is deprecated and will "
+ "be removed in a future version. "
+ "A strict version of it is now the default, see "
+ "https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. "
+ "You can safely remove this argument.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ # locals() should never be modified
+ kwds = locals().copy()
+ del kwds["filepath_or_buffer"]
+ del kwds["sep"]
+
+ kwds_defaults = _refine_defaults_read(
+ dialect,
+ delimiter,
+ delim_whitespace,
+ engine,
+ sep,
+ on_bad_lines,
+ names,
+ defaults={"delimiter": ","},
+ dtype_backend=dtype_backend,
+ )
+ kwds.update(kwds_defaults)
+
+ return _read(filepath_or_buffer, kwds)
+
+
+# iterator=True -> TextFileReader
+@overload
+def read_table(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = ...,
+ delimiter: str | None | lib.NoDefault = ...,
+ header: int | Sequence[int] | None | Literal["infer"] = ...,
+ names: Sequence[Hashable] | None | lib.NoDefault = ...,
+ index_col: IndexLabel | Literal[False] | None = ...,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: CSVEngine | None = ...,
+ converters: Mapping[Hashable, Callable] | None = ...,
+ true_values: list | None = ...,
+ false_values: list | None = ...,
+ skipinitialspace: bool = ...,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = ...,
+ skipfooter: int = ...,
+ nrows: int | None = ...,
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ skip_blank_lines: bool = ...,
+ parse_dates: bool | Sequence[Hashable] = ...,
+ infer_datetime_format: bool | lib.NoDefault = ...,
+ keep_date_col: bool = ...,
+ date_parser: Callable | lib.NoDefault = ...,
+ date_format: str | None = ...,
+ dayfirst: bool = ...,
+ cache_dates: bool = ...,
+ iterator: Literal[True],
+ chunksize: int | None = ...,
+ compression: CompressionOptions = ...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ lineterminator: str | None = ...,
+ quotechar: str = ...,
+ quoting: int = ...,
+ doublequote: bool = ...,
+ escapechar: str | None = ...,
+ comment: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ dialect: str | csv.Dialect | None = ...,
+ on_bad_lines=...,
+ delim_whitespace: bool = ...,
+ low_memory: bool = ...,
+ memory_map: bool = ...,
+ float_precision: str | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+) -> TextFileReader:
+ ...
+
+
+# chunksize=int -> TextFileReader
+@overload
+def read_table(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = ...,
+ delimiter: str | None | lib.NoDefault = ...,
+ header: int | Sequence[int] | None | Literal["infer"] = ...,
+ names: Sequence[Hashable] | None | lib.NoDefault = ...,
+ index_col: IndexLabel | Literal[False] | None = ...,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: CSVEngine | None = ...,
+ converters: Mapping[Hashable, Callable] | None = ...,
+ true_values: list | None = ...,
+ false_values: list | None = ...,
+ skipinitialspace: bool = ...,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = ...,
+ skipfooter: int = ...,
+ nrows: int | None = ...,
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ skip_blank_lines: bool = ...,
+ parse_dates: bool | Sequence[Hashable] = ...,
+ infer_datetime_format: bool | lib.NoDefault = ...,
+ keep_date_col: bool = ...,
+ date_parser: Callable | lib.NoDefault = ...,
+ date_format: str | None = ...,
+ dayfirst: bool = ...,
+ cache_dates: bool = ...,
+ iterator: bool = ...,
+ chunksize: int,
+ compression: CompressionOptions = ...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ lineterminator: str | None = ...,
+ quotechar: str = ...,
+ quoting: int = ...,
+ doublequote: bool = ...,
+ escapechar: str | None = ...,
+ comment: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ dialect: str | csv.Dialect | None = ...,
+ on_bad_lines=...,
+ delim_whitespace: bool = ...,
+ low_memory: bool = ...,
+ memory_map: bool = ...,
+ float_precision: str | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+) -> TextFileReader:
+ ...
+
+
+# default -> DataFrame
+@overload
+def read_table(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = ...,
+ delimiter: str | None | lib.NoDefault = ...,
+ header: int | Sequence[int] | None | Literal["infer"] = ...,
+ names: Sequence[Hashable] | None | lib.NoDefault = ...,
+ index_col: IndexLabel | Literal[False] | None = ...,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: CSVEngine | None = ...,
+ converters: Mapping[Hashable, Callable] | None = ...,
+ true_values: list | None = ...,
+ false_values: list | None = ...,
+ skipinitialspace: bool = ...,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = ...,
+ skipfooter: int = ...,
+ nrows: int | None = ...,
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ skip_blank_lines: bool = ...,
+ parse_dates: bool | Sequence[Hashable] = ...,
+ infer_datetime_format: bool | lib.NoDefault = ...,
+ keep_date_col: bool = ...,
+ date_parser: Callable | lib.NoDefault = ...,
+ date_format: str | None = ...,
+ dayfirst: bool = ...,
+ cache_dates: bool = ...,
+ iterator: Literal[False] = ...,
+ chunksize: None = ...,
+ compression: CompressionOptions = ...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ lineterminator: str | None = ...,
+ quotechar: str = ...,
+ quoting: int = ...,
+ doublequote: bool = ...,
+ escapechar: str | None = ...,
+ comment: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ dialect: str | csv.Dialect | None = ...,
+ on_bad_lines=...,
+ delim_whitespace: bool = ...,
+ low_memory: bool = ...,
+ memory_map: bool = ...,
+ float_precision: str | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+) -> DataFrame:
+ ...
+
+
+# Unions -> DataFrame | TextFileReader
+@overload
+def read_table(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = ...,
+ delimiter: str | None | lib.NoDefault = ...,
+ header: int | Sequence[int] | None | Literal["infer"] = ...,
+ names: Sequence[Hashable] | None | lib.NoDefault = ...,
+ index_col: IndexLabel | Literal[False] | None = ...,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: CSVEngine | None = ...,
+ converters: Mapping[Hashable, Callable] | None = ...,
+ true_values: list | None = ...,
+ false_values: list | None = ...,
+ skipinitialspace: bool = ...,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = ...,
+ skipfooter: int = ...,
+ nrows: int | None = ...,
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ skip_blank_lines: bool = ...,
+ parse_dates: bool | Sequence[Hashable] = ...,
+ infer_datetime_format: bool | lib.NoDefault = ...,
+ keep_date_col: bool = ...,
+ date_parser: Callable | lib.NoDefault = ...,
+ date_format: str | None = ...,
+ dayfirst: bool = ...,
+ cache_dates: bool = ...,
+ iterator: bool = ...,
+ chunksize: int | None = ...,
+ compression: CompressionOptions = ...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ lineterminator: str | None = ...,
+ quotechar: str = ...,
+ quoting: int = ...,
+ doublequote: bool = ...,
+ escapechar: str | None = ...,
+ comment: str | None = ...,
+ encoding: str | None = ...,
+ encoding_errors: str | None = ...,
+ dialect: str | csv.Dialect | None = ...,
+ on_bad_lines=...,
+ delim_whitespace: bool = ...,
+ low_memory: bool = ...,
+ memory_map: bool = ...,
+ float_precision: str | None = ...,
+ storage_options: StorageOptions = ...,
+ dtype_backend: DtypeBackend | lib.NoDefault = ...,
+) -> DataFrame | TextFileReader:
+ ...
+
+
+@Appender(
+ _doc_read_csv_and_table.format(
+ func_name="read_table",
+ summary="Read general delimited file into DataFrame.",
+ see_also_func_name="read_csv",
+ see_also_func_summary=(
+ "Read a comma-separated values (csv) file into DataFrame."
+ ),
+ _default_sep=r"'\\t' (tab-stop)",
+ storage_options=_shared_docs["storage_options"],
+ decompression_options=_shared_docs["decompression_options"]
+ % "filepath_or_buffer",
+ )
+)
+def read_table(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ sep: str | None | lib.NoDefault = lib.no_default,
+ delimiter: str | None | lib.NoDefault = None,
+ # Column and Index Locations and Names
+ header: int | Sequence[int] | None | Literal["infer"] = "infer",
+ names: Sequence[Hashable] | None | lib.NoDefault = lib.no_default,
+ index_col: IndexLabel | Literal[False] | None = None,
+ usecols: list[HashableT] | Callable[[Hashable], bool] | None = None,
+ # General Parsing Configuration
+ dtype: DtypeArg | None = None,
+ engine: CSVEngine | None = None,
+ converters: Mapping[Hashable, Callable] | None = None,
+ true_values: list | None = None,
+ false_values: list | None = None,
+ skipinitialspace: bool = False,
+ skiprows: list[int] | int | Callable[[Hashable], bool] | None = None,
+ skipfooter: int = 0,
+ nrows: int | None = None,
+ # NA and Missing Data Handling
+ na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
+ keep_default_na: bool = True,
+ na_filter: bool = True,
+ verbose: bool = False,
+ skip_blank_lines: bool = True,
+ # Datetime Handling
+ parse_dates: bool | Sequence[Hashable] = False,
+ infer_datetime_format: bool | lib.NoDefault = lib.no_default,
+ keep_date_col: bool = False,
+ date_parser: Callable | lib.NoDefault = lib.no_default,
+ date_format: str | None = None,
+ dayfirst: bool = False,
+ cache_dates: bool = True,
+ # Iteration
+ iterator: bool = False,
+ chunksize: int | None = None,
+ # Quoting, Compression, and File Format
+ compression: CompressionOptions = "infer",
+ thousands: str | None = None,
+ decimal: str = ".",
+ lineterminator: str | None = None,
+ quotechar: str = '"',
+ quoting: int = csv.QUOTE_MINIMAL,
+ doublequote: bool = True,
+ escapechar: str | None = None,
+ comment: str | None = None,
+ encoding: str | None = None,
+ encoding_errors: str | None = "strict",
+ dialect: str | csv.Dialect | None = None,
+ # Error Handling
+ on_bad_lines: str = "error",
+ # Internal
+ delim_whitespace: bool = False,
+ low_memory: bool = _c_parser_defaults["low_memory"],
+ memory_map: bool = False,
+ float_precision: str | None = None,
+ storage_options: StorageOptions | None = None,
+ dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
+) -> DataFrame | TextFileReader:
+ if infer_datetime_format is not lib.no_default:
+ warnings.warn(
+ "The argument 'infer_datetime_format' is deprecated and will "
+ "be removed in a future version. "
+ "A strict version of it is now the default, see "
+ "https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. "
+ "You can safely remove this argument.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+
+ # locals() should never be modified
+ kwds = locals().copy()
+ del kwds["filepath_or_buffer"]
+ del kwds["sep"]
+
+ kwds_defaults = _refine_defaults_read(
+ dialect,
+ delimiter,
+ delim_whitespace,
+ engine,
+ sep,
+ on_bad_lines,
+ names,
+ defaults={"delimiter": "\t"},
+ dtype_backend=dtype_backend,
+ )
+ kwds.update(kwds_defaults)
+
+ return _read(filepath_or_buffer, kwds)
+
+
+def read_fwf(
+ filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
+ *,
+ colspecs: Sequence[tuple[int, int]] | str | None = "infer",
+ widths: Sequence[int] | None = None,
+ infer_nrows: int = 100,
+ dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
+ **kwds,
+) -> DataFrame | TextFileReader:
+ r"""
+ Read a table of fixed-width formatted lines into DataFrame.
+
+ Also supports optionally iterating or breaking of the file
+ into chunks.
+
+ Additional help can be found in the `online docs for IO Tools
+ `_.
+
+ Parameters
+ ----------
+ filepath_or_buffer : str, path object, or file-like object
+ String, path object (implementing ``os.PathLike[str]``), or file-like
+ object implementing a text ``read()`` function.The string could be a URL.
+ Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is
+ expected. A local file could be:
+ ``file://localhost/path/to/table.csv``.
+ colspecs : list of tuple (int, int) or 'infer'. optional
+ A list of tuples giving the extents of the fixed-width
+ fields of each line as half-open intervals (i.e., [from, to[ ).
+ String value 'infer' can be used to instruct the parser to try
+ detecting the column specifications from the first 100 rows of
+ the data which are not being skipped via skiprows (default='infer').
+ widths : list of int, optional
+ A list of field widths which can be used instead of 'colspecs' if
+ the intervals are contiguous.
+ infer_nrows : int, default 100
+ The number of rows to consider when letting the parser determine the
+ `colspecs`.
+ dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable'
+ Back-end data type applied to the resultant :class:`DataFrame`
+ (still experimental). Behaviour is as follows:
+
+ * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
+ (default).
+ * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
+ DataFrame.
+
+ .. versionadded:: 2.0
+
+ **kwds : optional
+ Optional keyword arguments can be passed to ``TextFileReader``.
+
+ Returns
+ -------
+ DataFrame or TextFileReader
+ A comma-separated values (csv) file is returned as two-dimensional
+ data structure with labeled axes.
+
+ See Also
+ --------
+ DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.
+ read_csv : Read a comma-separated values (csv) file into DataFrame.
+
+ Examples
+ --------
+ >>> pd.read_fwf('data.csv') # doctest: +SKIP
+ """
+ # Check input arguments.
+ if colspecs is None and widths is None:
+ raise ValueError("Must specify either colspecs or widths")
+ if colspecs not in (None, "infer") and widths is not None:
+ raise ValueError("You must specify only one of 'widths' and 'colspecs'")
+
+ # Compute 'colspecs' from 'widths', if specified.
+ if widths is not None:
+ colspecs, col = [], 0
+ for w in widths:
+ colspecs.append((col, col + w))
+ col += w
+
+ # for mypy
+ assert colspecs is not None
+
+ # GH#40830
+ # Ensure length of `colspecs` matches length of `names`
+ names = kwds.get("names")
+ if names is not None:
+ if len(names) != len(colspecs) and colspecs != "infer":
+ # need to check len(index_col) as it might contain
+ # unnamed indices, in which case it's name is not required
+ len_index = 0
+ if kwds.get("index_col") is not None:
+ index_col: Any = kwds.get("index_col")
+ if index_col is not False:
+ if not is_list_like(index_col):
+ len_index = 1
+ else:
+ len_index = len(index_col)
+ if kwds.get("usecols") is None and len(names) + len_index != len(colspecs):
+ # If usecols is used colspec may be longer than names
+ raise ValueError("Length of colspecs must match length of names")
+
+ kwds["colspecs"] = colspecs
+ kwds["infer_nrows"] = infer_nrows
+ kwds["engine"] = "python-fwf"
+
+ check_dtype_backend(dtype_backend)
+ kwds["dtype_backend"] = dtype_backend
+ return _read(filepath_or_buffer, kwds)
+
+
+class TextFileReader(abc.Iterator):
+ """
+
+ Passed dialect overrides any of the related parser options
+
+ """
+
+ def __init__(
+ self,
+ f: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str] | list,
+ engine: CSVEngine | None = None,
+ **kwds,
+ ) -> None:
+ if engine is not None:
+ engine_specified = True
+ else:
+ engine = "python"
+ engine_specified = False
+ self.engine = engine
+ self._engine_specified = kwds.get("engine_specified", engine_specified)
+
+ _validate_skipfooter(kwds)
+
+ dialect = _extract_dialect(kwds)
+ if dialect is not None:
+ if engine == "pyarrow":
+ raise ValueError(
+ "The 'dialect' option is not supported with the 'pyarrow' engine"
+ )
+ kwds = _merge_with_dialect_properties(dialect, kwds)
+
+ if kwds.get("header", "infer") == "infer":
+ kwds["header"] = 0 if kwds.get("names") is None else None
+
+ self.orig_options = kwds
+
+ # miscellanea
+ self._currow = 0
+
+ options = self._get_options_with_defaults(engine)
+ options["storage_options"] = kwds.get("storage_options", None)
+
+ self.chunksize = options.pop("chunksize", None)
+ self.nrows = options.pop("nrows", None)
+
+ self._check_file_or_buffer(f, engine)
+ self.options, self.engine = self._clean_options(options, engine)
+
+ if "has_index_names" in kwds:
+ self.options["has_index_names"] = kwds["has_index_names"]
+
+ self.handles: IOHandles | None = None
+ self._engine = self._make_engine(f, self.engine)
+
+ def close(self) -> None:
+ if self.handles is not None:
+ self.handles.close()
+ self._engine.close()
+
+ def _get_options_with_defaults(self, engine: CSVEngine) -> dict[str, Any]:
+ kwds = self.orig_options
+
+ options = {}
+ default: object | None
+
+ for argname, default in parser_defaults.items():
+ value = kwds.get(argname, default)
+
+ # see gh-12935
+ if (
+ engine == "pyarrow"
+ and argname in _pyarrow_unsupported
+ and value != default
+ and value != getattr(value, "value", default)
+ ):
+ raise ValueError(
+ f"The {repr(argname)} option is not supported with the "
+ f"'pyarrow' engine"
+ )
+ options[argname] = value
+
+ for argname, default in _c_parser_defaults.items():
+ if argname in kwds:
+ value = kwds[argname]
+
+ if engine != "c" and value != default:
+ # TODO: Refactor this logic, its pretty convoluted
+ if "python" in engine and argname not in _python_unsupported:
+ pass
+ elif "pyarrow" in engine and argname not in _pyarrow_unsupported:
+ pass
+ else:
+ raise ValueError(
+ f"The {repr(argname)} option is not supported with the "
+ f"{repr(engine)} engine"
+ )
+ else:
+ value = default
+ options[argname] = value
+
+ if engine == "python-fwf":
+ for argname, default in _fwf_defaults.items():
+ options[argname] = kwds.get(argname, default)
+
+ return options
+
+ def _check_file_or_buffer(self, f, engine: CSVEngine) -> None:
+ # see gh-16530
+ if is_file_like(f) and engine != "c" and not hasattr(f, "__iter__"):
+ # The C engine doesn't need the file-like to have the "__iter__"
+ # attribute. However, the Python engine needs "__iter__(...)"
+ # when iterating through such an object, meaning it
+ # needs to have that attribute
+ raise ValueError(
+ "The 'python' engine cannot iterate through this file buffer."
+ )
+
+ def _clean_options(
+ self, options: dict[str, Any], engine: CSVEngine
+ ) -> tuple[dict[str, Any], CSVEngine]:
+ result = options.copy()
+
+ fallback_reason = None
+
+ # C engine not supported yet
+ if engine == "c":
+ if options["skipfooter"] > 0:
+ fallback_reason = "the 'c' engine does not support skipfooter"
+ engine = "python"
+
+ sep = options["delimiter"]
+ delim_whitespace = options["delim_whitespace"]
+
+ if sep is None and not delim_whitespace:
+ if engine in ("c", "pyarrow"):
+ fallback_reason = (
+ f"the '{engine}' engine does not support "
+ "sep=None with delim_whitespace=False"
+ )
+ engine = "python"
+ elif sep is not None and len(sep) > 1:
+ if engine == "c" and sep == r"\s+":
+ result["delim_whitespace"] = True
+ del result["delimiter"]
+ elif engine not in ("python", "python-fwf"):
+ # wait until regex engine integrated
+ fallback_reason = (
+ f"the '{engine}' engine does not support "
+ "regex separators (separators > 1 char and "
+ r"different from '\s+' are interpreted as regex)"
+ )
+ engine = "python"
+ elif delim_whitespace:
+ if "python" in engine:
+ result["delimiter"] = r"\s+"
+ elif sep is not None:
+ encodeable = True
+ encoding = sys.getfilesystemencoding() or "utf-8"
+ try:
+ if len(sep.encode(encoding)) > 1:
+ encodeable = False
+ except UnicodeDecodeError:
+ encodeable = False
+ if not encodeable and engine not in ("python", "python-fwf"):
+ fallback_reason = (
+ f"the separator encoded in {encoding} "
+ f"is > 1 char long, and the '{engine}' engine "
+ "does not support such separators"
+ )
+ engine = "python"
+
+ quotechar = options["quotechar"]
+ if quotechar is not None and isinstance(quotechar, (str, bytes)):
+ if (
+ len(quotechar) == 1
+ and ord(quotechar) > 127
+ and engine not in ("python", "python-fwf")
+ ):
+ fallback_reason = (
+ "ord(quotechar) > 127, meaning the "
+ "quotechar is larger than one byte, "
+ f"and the '{engine}' engine does not support such quotechars"
+ )
+ engine = "python"
+
+ if fallback_reason and self._engine_specified:
+ raise ValueError(fallback_reason)
+
+ if engine == "c":
+ for arg in _c_unsupported:
+ del result[arg]
+
+ if "python" in engine:
+ for arg in _python_unsupported:
+ if fallback_reason and result[arg] != _c_parser_defaults.get(arg):
+ raise ValueError(
+ "Falling back to the 'python' engine because "
+ f"{fallback_reason}, but this causes {repr(arg)} to be "
+ "ignored as it is not supported by the 'python' engine."
+ )
+ del result[arg]
+
+ if fallback_reason:
+ warnings.warn(
+ (
+ "Falling back to the 'python' engine because "
+ f"{fallback_reason}; you can avoid this warning by specifying "
+ "engine='python'."
+ ),
+ ParserWarning,
+ stacklevel=find_stack_level(),
+ )
+
+ index_col = options["index_col"]
+ names = options["names"]
+ converters = options["converters"]
+ na_values = options["na_values"]
+ skiprows = options["skiprows"]
+
+ validate_header_arg(options["header"])
+
+ if index_col is True:
+ raise ValueError("The value of index_col couldn't be 'True'")
+ if is_index_col(index_col):
+ if not isinstance(index_col, (list, tuple, np.ndarray)):
+ index_col = [index_col]
+ result["index_col"] = index_col
+
+ names = list(names) if names is not None else names
+
+ # type conversion-related
+ if converters is not None:
+ if not isinstance(converters, dict):
+ raise TypeError(
+ "Type converters must be a dict or subclass, "
+ f"input was a {type(converters).__name__}"
+ )
+ else:
+ converters = {}
+
+ # Converting values to NA
+ keep_default_na = options["keep_default_na"]
+ na_values, na_fvalues = _clean_na_values(na_values, keep_default_na)
+
+ # handle skiprows; this is internally handled by the
+ # c-engine, so only need for python and pyarrow parsers
+ if engine == "pyarrow":
+ if not is_integer(skiprows) and skiprows is not None:
+ # pyarrow expects skiprows to be passed as an integer
+ raise ValueError(
+ "skiprows argument must be an integer when using "
+ "engine='pyarrow'"
+ )
+ else:
+ if is_integer(skiprows):
+ skiprows = list(range(skiprows))
+ if skiprows is None:
+ skiprows = set()
+ elif not callable(skiprows):
+ skiprows = set(skiprows)
+
+ # put stuff back
+ result["names"] = names
+ result["converters"] = converters
+ result["na_values"] = na_values
+ result["na_fvalues"] = na_fvalues
+ result["skiprows"] = skiprows
+
+ return result, engine
+
+ def __next__(self) -> DataFrame:
+ try:
+ return self.get_chunk()
+ except StopIteration:
+ self.close()
+ raise
+
+ def _make_engine(
+ self,
+ f: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str] | list | IO,
+ engine: CSVEngine = "c",
+ ) -> ParserBase:
+ mapping: dict[str, type[ParserBase]] = {
+ "c": CParserWrapper,
+ "python": PythonParser,
+ "pyarrow": ArrowParserWrapper,
+ "python-fwf": FixedWidthFieldParser,
+ }
+ if engine not in mapping:
+ raise ValueError(
+ f"Unknown engine: {engine} (valid options are {mapping.keys()})"
+ )
+ if not isinstance(f, list):
+ # open file here
+ is_text = True
+ mode = "r"
+ if engine == "pyarrow":
+ is_text = False
+ mode = "rb"
+ elif (
+ engine == "c"
+ and self.options.get("encoding", "utf-8") == "utf-8"
+ and isinstance(stringify_path(f), str)
+ ):
+ # c engine can decode utf-8 bytes, adding TextIOWrapper makes
+ # the c-engine especially for memory_map=True far slower
+ is_text = False
+ if "b" not in mode:
+ mode += "b"
+ self.handles = get_handle(
+ f,
+ mode,
+ encoding=self.options.get("encoding", None),
+ compression=self.options.get("compression", None),
+ memory_map=self.options.get("memory_map", False),
+ is_text=is_text,
+ errors=self.options.get("encoding_errors", "strict"),
+ storage_options=self.options.get("storage_options", None),
+ )
+ assert self.handles is not None
+ f = self.handles.handle
+
+ elif engine != "python":
+ msg = f"Invalid file path or buffer object type: {type(f)}"
+ raise ValueError(msg)
+
+ try:
+ return mapping[engine](f, **self.options)
+ except Exception:
+ if self.handles is not None:
+ self.handles.close()
+ raise
+
+ def _failover_to_python(self) -> None:
+ raise AbstractMethodError(self)
+
+ def read(self, nrows: int | None = None) -> DataFrame:
+ if self.engine == "pyarrow":
+ try:
+ # error: "ParserBase" has no attribute "read"
+ df = self._engine.read() # type: ignore[attr-defined]
+ except Exception:
+ self.close()
+ raise
+ else:
+ nrows = validate_integer("nrows", nrows)
+ try:
+ # error: "ParserBase" has no attribute "read"
+ (
+ index,
+ columns,
+ col_dict,
+ ) = self._engine.read( # type: ignore[attr-defined]
+ nrows
+ )
+ except Exception:
+ self.close()
+ raise
+
+ if index is None:
+ if col_dict:
+ # Any column is actually fine:
+ new_rows = len(next(iter(col_dict.values())))
+ index = RangeIndex(self._currow, self._currow + new_rows)
+ else:
+ new_rows = 0
+ else:
+ new_rows = len(index)
+
+ df = DataFrame(col_dict, columns=columns, index=index)
+
+ self._currow += new_rows
+ return df
+
+ def get_chunk(self, size: int | None = None) -> DataFrame:
+ if size is None:
+ size = self.chunksize
+ if self.nrows is not None:
+ if self._currow >= self.nrows:
+ raise StopIteration
+ size = min(size, self.nrows - self._currow)
+ return self.read(nrows=size)
+
+ def __enter__(self) -> TextFileReader:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ self.close()
+
+
+def TextParser(*args, **kwds) -> TextFileReader:
+ """
+ Converts lists of lists/tuples into DataFrames with proper type inference
+ and optional (e.g. string to datetime) conversion. Also enables iterating
+ lazily over chunks of large files
+
+ Parameters
+ ----------
+ data : file-like object or list
+ delimiter : separator character to use
+ dialect : str or csv.Dialect instance, optional
+ Ignored if delimiter is longer than 1 character
+ names : sequence, default
+ header : int, default 0
+ Row to use to parse column labels. Defaults to the first row. Prior
+ rows will be discarded
+ index_col : int or list, optional
+ Column or columns to use as the (possibly hierarchical) index
+ has_index_names: bool, default False
+ True if the cols defined in index_col have an index name and are
+ not in the header.
+ na_values : scalar, str, list-like, or dict, optional
+ Additional strings to recognize as NA/NaN.
+ keep_default_na : bool, default True
+ thousands : str, optional
+ Thousands separator
+ comment : str, optional
+ Comment out remainder of line
+ parse_dates : bool, default False
+ keep_date_col : bool, default False
+ date_parser : function, optional
+
+ .. deprecated:: 2.0.0
+ date_format : str or dict of column -> format, default ``None``
+
+ .. versionadded:: 2.0.0
+ skiprows : list of integers
+ Row numbers to skip
+ skipfooter : int
+ Number of line at bottom of file to skip
+ converters : dict, optional
+ Dict of functions for converting values in certain columns. Keys can
+ either be integers or column labels, values are functions that take one
+ input argument, the cell (not column) content, and return the
+ transformed content.
+ encoding : str, optional
+ Encoding to use for UTF when reading/writing (ex. 'utf-8')
+ float_precision : str, optional
+ Specifies which converter the C engine should use for floating-point
+ values. The options are `None` or `high` for the ordinary converter,
+ `legacy` for the original lower precision pandas converter, and
+ `round_trip` for the round-trip converter.
+
+ .. versionchanged:: 1.2
+ """
+ kwds["engine"] = "python"
+ return TextFileReader(*args, **kwds)
+
+
+def _clean_na_values(na_values, keep_default_na: bool = True):
+ na_fvalues: set | dict
+ if na_values is None:
+ if keep_default_na:
+ na_values = STR_NA_VALUES
+ else:
+ na_values = set()
+ na_fvalues = set()
+ elif isinstance(na_values, dict):
+ old_na_values = na_values.copy()
+ na_values = {} # Prevent aliasing.
+
+ # Convert the values in the na_values dictionary
+ # into array-likes for further use. This is also
+ # where we append the default NaN values, provided
+ # that `keep_default_na=True`.
+ for k, v in old_na_values.items():
+ if not is_list_like(v):
+ v = [v]
+
+ if keep_default_na:
+ v = set(v) | STR_NA_VALUES
+
+ na_values[k] = v
+ na_fvalues = {k: _floatify_na_values(v) for k, v in na_values.items()}
+ else:
+ if not is_list_like(na_values):
+ na_values = [na_values]
+ na_values = _stringify_na_values(na_values)
+ if keep_default_na:
+ na_values = na_values | STR_NA_VALUES
+
+ na_fvalues = _floatify_na_values(na_values)
+
+ return na_values, na_fvalues
+
+
+def _floatify_na_values(na_values):
+ # create float versions of the na_values
+ result = set()
+ for v in na_values:
+ try:
+ v = float(v)
+ if not np.isnan(v):
+ result.add(v)
+ except (TypeError, ValueError, OverflowError):
+ pass
+ return result
+
+
+def _stringify_na_values(na_values):
+ """return a stringified and numeric for these values"""
+ result: list[str | float] = []
+ for x in na_values:
+ result.append(str(x))
+ result.append(x)
+ try:
+ v = float(x)
+
+ # we are like 999 here
+ if v == int(v):
+ v = int(v)
+ result.append(f"{v}.0")
+ result.append(str(v))
+
+ result.append(v)
+ except (TypeError, ValueError, OverflowError):
+ pass
+ try:
+ result.append(int(x))
+ except (TypeError, ValueError, OverflowError):
+ pass
+ return set(result)
+
+
+def _refine_defaults_read(
+ dialect: str | csv.Dialect | None,
+ delimiter: str | None | lib.NoDefault,
+ delim_whitespace: bool,
+ engine: CSVEngine | None,
+ sep: str | None | lib.NoDefault,
+ on_bad_lines: str | Callable,
+ names: Sequence[Hashable] | None | lib.NoDefault,
+ defaults: dict[str, Any],
+ dtype_backend: DtypeBackend | lib.NoDefault,
+):
+ """Validate/refine default values of input parameters of read_csv, read_table.
+
+ Parameters
+ ----------
+ dialect : str or csv.Dialect
+ If provided, this parameter will override values (default or not) for the
+ following parameters: `delimiter`, `doublequote`, `escapechar`,
+ `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to
+ override values, a ParserWarning will be issued. See csv.Dialect
+ documentation for more details.
+ delimiter : str or object
+ Alias for sep.
+ delim_whitespace : bool
+ Specifies whether or not whitespace (e.g. ``' '`` or ``'\t'``) will be
+ used as the sep. Equivalent to setting ``sep='\\s+'``. If this option
+ is set to True, nothing should be passed in for the ``delimiter``
+ parameter.
+ engine : {{'c', 'python'}}
+ Parser engine to use. The C engine is faster while the python engine is
+ currently more feature-complete.
+ sep : str or object
+ A delimiter provided by the user (str) or a sentinel value, i.e.
+ pandas._libs.lib.no_default.
+ on_bad_lines : str, callable
+ An option for handling bad lines or a sentinel value(None).
+ names : array-like, optional
+ List of column names to use. If the file contains a header row,
+ then you should explicitly pass ``header=0`` to override the column names.
+ Duplicates in this list are not allowed.
+ defaults: dict
+ Default values of input parameters.
+
+ Returns
+ -------
+ kwds : dict
+ Input parameters with correct values.
+
+ Raises
+ ------
+ ValueError :
+ If a delimiter was specified with ``sep`` (or ``delimiter``) and
+ ``delim_whitespace=True``.
+ """
+ # fix types for sep, delimiter to Union(str, Any)
+ delim_default = defaults["delimiter"]
+ kwds: dict[str, Any] = {}
+ # gh-23761
+ #
+ # When a dialect is passed, it overrides any of the overlapping
+ # parameters passed in directly. We don't want to warn if the
+ # default parameters were passed in (since it probably means
+ # that the user didn't pass them in explicitly in the first place).
+ #
+ # "delimiter" is the annoying corner case because we alias it to
+ # "sep" before doing comparison to the dialect values later on.
+ # Thus, we need a flag to indicate that we need to "override"
+ # the comparison to dialect values by checking if default values
+ # for BOTH "delimiter" and "sep" were provided.
+ if dialect is not None:
+ kwds["sep_override"] = delimiter is None and (
+ sep is lib.no_default or sep == delim_default
+ )
+
+ if delimiter and (sep is not lib.no_default):
+ raise ValueError("Specified a sep and a delimiter; you can only specify one.")
+
+ kwds["names"] = None if names is lib.no_default else names
+
+ # Alias sep -> delimiter.
+ if delimiter is None:
+ delimiter = sep
+
+ if delim_whitespace and (delimiter is not lib.no_default):
+ raise ValueError(
+ "Specified a delimiter with both sep and "
+ "delim_whitespace=True; you can only specify one."
+ )
+
+ if delimiter == "\n":
+ raise ValueError(
+ r"Specified \n as separator or delimiter. This forces the python engine "
+ "which does not accept a line terminator. Hence it is not allowed to use "
+ "the line terminator as separator.",
+ )
+
+ if delimiter is lib.no_default:
+ # assign default separator value
+ kwds["delimiter"] = delim_default
+ else:
+ kwds["delimiter"] = delimiter
+
+ if engine is not None:
+ kwds["engine_specified"] = True
+ else:
+ kwds["engine"] = "c"
+ kwds["engine_specified"] = False
+
+ if on_bad_lines == "error":
+ kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.ERROR
+ elif on_bad_lines == "warn":
+ kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.WARN
+ elif on_bad_lines == "skip":
+ kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.SKIP
+ elif callable(on_bad_lines):
+ if engine != "python":
+ raise ValueError(
+ "on_bad_line can only be a callable function if engine='python'"
+ )
+ kwds["on_bad_lines"] = on_bad_lines
+ else:
+ raise ValueError(f"Argument {on_bad_lines} is invalid for on_bad_lines")
+
+ check_dtype_backend(dtype_backend)
+
+ kwds["dtype_backend"] = dtype_backend
+
+ return kwds
+
+
+def _extract_dialect(kwds: dict[str, Any]) -> csv.Dialect | None:
+ """
+ Extract concrete csv dialect instance.
+
+ Returns
+ -------
+ csv.Dialect or None
+ """
+ if kwds.get("dialect") is None:
+ return None
+
+ dialect = kwds["dialect"]
+ if dialect in csv.list_dialects():
+ dialect = csv.get_dialect(dialect)
+
+ _validate_dialect(dialect)
+
+ return dialect
+
+
+MANDATORY_DIALECT_ATTRS = (
+ "delimiter",
+ "doublequote",
+ "escapechar",
+ "skipinitialspace",
+ "quotechar",
+ "quoting",
+)
+
+
+def _validate_dialect(dialect: csv.Dialect) -> None:
+ """
+ Validate csv dialect instance.
+
+ Raises
+ ------
+ ValueError
+ If incorrect dialect is provided.
+ """
+ for param in MANDATORY_DIALECT_ATTRS:
+ if not hasattr(dialect, param):
+ raise ValueError(f"Invalid dialect {dialect} provided")
+
+
+def _merge_with_dialect_properties(
+ dialect: csv.Dialect,
+ defaults: dict[str, Any],
+) -> dict[str, Any]:
+ """
+ Merge default kwargs in TextFileReader with dialect parameters.
+
+ Parameters
+ ----------
+ dialect : csv.Dialect
+ Concrete csv dialect. See csv.Dialect documentation for more details.
+ defaults : dict
+ Keyword arguments passed to TextFileReader.
+
+ Returns
+ -------
+ kwds : dict
+ Updated keyword arguments, merged with dialect parameters.
+ """
+ kwds = defaults.copy()
+
+ for param in MANDATORY_DIALECT_ATTRS:
+ dialect_val = getattr(dialect, param)
+
+ parser_default = parser_defaults[param]
+ provided = kwds.get(param, parser_default)
+
+ # Messages for conflicting values between the dialect
+ # instance and the actual parameters provided.
+ conflict_msgs = []
+
+ # Don't warn if the default parameter was passed in,
+ # even if it conflicts with the dialect (gh-23761).
+ if provided not in (parser_default, dialect_val):
+ msg = (
+ f"Conflicting values for '{param}': '{provided}' was "
+ f"provided, but the dialect specifies '{dialect_val}'. "
+ "Using the dialect-specified value."
+ )
+
+ # Annoying corner case for not warning about
+ # conflicts between dialect and delimiter parameter.
+ # Refer to the outer "_read_" function for more info.
+ if not (param == "delimiter" and kwds.pop("sep_override", False)):
+ conflict_msgs.append(msg)
+
+ if conflict_msgs:
+ warnings.warn(
+ "\n\n".join(conflict_msgs), ParserWarning, stacklevel=find_stack_level()
+ )
+ kwds[param] = dialect_val
+ return kwds
+
+
+def _validate_skipfooter(kwds: dict[str, Any]) -> None:
+ """
+ Check whether skipfooter is compatible with other kwargs in TextFileReader.
+
+ Parameters
+ ----------
+ kwds : dict
+ Keyword arguments passed to TextFileReader.
+
+ Raises
+ ------
+ ValueError
+ If skipfooter is not compatible with other parameters.
+ """
+ if kwds.get("skipfooter"):
+ if kwds.get("iterator") or kwds.get("chunksize"):
+ raise ValueError("'skipfooter' not supported for iteration")
+ if kwds.get("nrows"):
+ raise ValueError("'skipfooter' not supported with 'nrows'")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..317730745b6e3a0278a48b7bb810cf43e718e787
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__init__.py
@@ -0,0 +1,3 @@
+from pandas.io.sas.sasreader import read_sas
+
+__all__ = ["read_sas"]
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89eb152d6bcb0af3a7179a3cd2cb47be8c841570
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/__init__.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sas7bdat.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sas7bdat.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b74d26c1ce96f0b891a2d5b7de47bac9b0fc4a14
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sas7bdat.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sas_constants.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sas_constants.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e534bbc80a506102bc11935e49e4bd888c1fd222
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sas_constants.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sas_xport.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sas_xport.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29e0ea0bdea73d6b9bb37e91c4fb7786a59e7402
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sas_xport.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sasreader.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sasreader.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f80e3f9726b8a579745e8c5e2df83b5010b0f8ab
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/__pycache__/sasreader.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sas7bdat.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sas7bdat.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1fb21db8e706bf8e1f57e12ad463dc28db809b1
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sas7bdat.py
@@ -0,0 +1,752 @@
+"""
+Read SAS7BDAT files
+
+Based on code written by Jared Hobbs:
+ https://bitbucket.org/jaredhobbs/sas7bdat
+
+See also:
+ https://github.com/BioStatMatt/sas7bdat
+
+Partial documentation of the file format:
+ https://cran.r-project.org/package=sas7bdat/vignettes/sas7bdat.pdf
+
+Reference for binary data compression:
+ http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/CUJ/1992/9210/ross/ross.htm
+"""
+from __future__ import annotations
+
+from collections import abc
+from datetime import (
+ datetime,
+ timedelta,
+)
+import sys
+from typing import (
+ TYPE_CHECKING,
+ cast,
+)
+
+import numpy as np
+
+from pandas._libs.byteswap import (
+ read_double_with_byteswap,
+ read_float_with_byteswap,
+ read_uint16_with_byteswap,
+ read_uint32_with_byteswap,
+ read_uint64_with_byteswap,
+)
+from pandas._libs.sas import (
+ Parser,
+ get_subheader_index,
+)
+from pandas.errors import (
+ EmptyDataError,
+ OutOfBoundsDatetime,
+)
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ isna,
+)
+
+from pandas.io.common import get_handle
+import pandas.io.sas.sas_constants as const
+from pandas.io.sas.sasreader import ReaderBase
+
+if TYPE_CHECKING:
+ from pandas._typing import (
+ CompressionOptions,
+ FilePath,
+ ReadBuffer,
+ )
+
+
+def _parse_datetime(sas_datetime: float, unit: str):
+ if isna(sas_datetime):
+ return pd.NaT
+
+ if unit == "s":
+ return datetime(1960, 1, 1) + timedelta(seconds=sas_datetime)
+
+ elif unit == "d":
+ return datetime(1960, 1, 1) + timedelta(days=sas_datetime)
+
+ else:
+ raise ValueError("unit must be 'd' or 's'")
+
+
+def _convert_datetimes(sas_datetimes: pd.Series, unit: str) -> pd.Series:
+ """
+ Convert to Timestamp if possible, otherwise to datetime.datetime.
+ SAS float64 lacks precision for more than ms resolution so the fit
+ to datetime.datetime is ok.
+
+ Parameters
+ ----------
+ sas_datetimes : {Series, Sequence[float]}
+ Dates or datetimes in SAS
+ unit : {str}
+ "d" if the floats represent dates, "s" for datetimes
+
+ Returns
+ -------
+ Series
+ Series of datetime64 dtype or datetime.datetime.
+ """
+ try:
+ return pd.to_datetime(sas_datetimes, unit=unit, origin="1960-01-01")
+ except OutOfBoundsDatetime:
+ s_series = sas_datetimes.apply(_parse_datetime, unit=unit)
+ s_series = cast(pd.Series, s_series)
+ return s_series
+
+
+class _Column:
+ col_id: int
+ name: str | bytes
+ label: str | bytes
+ format: str | bytes
+ ctype: bytes
+ length: int
+
+ def __init__(
+ self,
+ col_id: int,
+ # These can be bytes when convert_header_text is False
+ name: str | bytes,
+ label: str | bytes,
+ format: str | bytes,
+ ctype: bytes,
+ length: int,
+ ) -> None:
+ self.col_id = col_id
+ self.name = name
+ self.label = label
+ self.format = format
+ self.ctype = ctype
+ self.length = length
+
+
+# SAS7BDAT represents a SAS data file in SAS7BDAT format.
+class SAS7BDATReader(ReaderBase, abc.Iterator):
+ """
+ Read SAS files in SAS7BDAT format.
+
+ Parameters
+ ----------
+ path_or_buf : path name or buffer
+ Name of SAS file or file-like object pointing to SAS file
+ contents.
+ index : column identifier, defaults to None
+ Column to use as index.
+ convert_dates : bool, defaults to True
+ Attempt to convert dates to Pandas datetime values. Note that
+ some rarely used SAS date formats may be unsupported.
+ blank_missing : bool, defaults to True
+ Convert empty strings to missing values (SAS uses blanks to
+ indicate missing character variables).
+ chunksize : int, defaults to None
+ Return SAS7BDATReader object for iterations, returns chunks
+ with given number of lines.
+ encoding : str, 'infer', defaults to None
+ String encoding acc. to Python standard encodings,
+ encoding='infer' tries to detect the encoding from the file header,
+ encoding=None will leave the data in binary format.
+ convert_text : bool, defaults to True
+ If False, text variables are left as raw bytes.
+ convert_header_text : bool, defaults to True
+ If False, header text, including column names, are left as raw
+ bytes.
+ """
+
+ _int_length: int
+ _cached_page: bytes | None
+
+ def __init__(
+ self,
+ path_or_buf: FilePath | ReadBuffer[bytes],
+ index=None,
+ convert_dates: bool = True,
+ blank_missing: bool = True,
+ chunksize: int | None = None,
+ encoding: str | None = None,
+ convert_text: bool = True,
+ convert_header_text: bool = True,
+ compression: CompressionOptions = "infer",
+ ) -> None:
+ self.index = index
+ self.convert_dates = convert_dates
+ self.blank_missing = blank_missing
+ self.chunksize = chunksize
+ self.encoding = encoding
+ self.convert_text = convert_text
+ self.convert_header_text = convert_header_text
+
+ self.default_encoding = "latin-1"
+ self.compression = b""
+ self.column_names_raw: list[bytes] = []
+ self.column_names: list[str | bytes] = []
+ self.column_formats: list[str | bytes] = []
+ self.columns: list[_Column] = []
+
+ self._current_page_data_subheader_pointers: list[tuple[int, int]] = []
+ self._cached_page = None
+ self._column_data_lengths: list[int] = []
+ self._column_data_offsets: list[int] = []
+ self._column_types: list[bytes] = []
+
+ self._current_row_in_file_index = 0
+ self._current_row_on_page_index = 0
+ self._current_row_in_file_index = 0
+
+ self.handles = get_handle(
+ path_or_buf, "rb", is_text=False, compression=compression
+ )
+
+ self._path_or_buf = self.handles.handle
+
+ # Same order as const.SASIndex
+ self._subheader_processors = [
+ self._process_rowsize_subheader,
+ self._process_columnsize_subheader,
+ self._process_subheader_counts,
+ self._process_columntext_subheader,
+ self._process_columnname_subheader,
+ self._process_columnattributes_subheader,
+ self._process_format_subheader,
+ self._process_columnlist_subheader,
+ None, # Data
+ ]
+
+ try:
+ self._get_properties()
+ self._parse_metadata()
+ except Exception:
+ self.close()
+ raise
+
+ def column_data_lengths(self) -> np.ndarray:
+ """Return a numpy int64 array of the column data lengths"""
+ return np.asarray(self._column_data_lengths, dtype=np.int64)
+
+ def column_data_offsets(self) -> np.ndarray:
+ """Return a numpy int64 array of the column offsets"""
+ return np.asarray(self._column_data_offsets, dtype=np.int64)
+
+ def column_types(self) -> np.ndarray:
+ """
+ Returns a numpy character array of the column types:
+ s (string) or d (double)
+ """
+ return np.asarray(self._column_types, dtype=np.dtype("S1"))
+
+ def close(self) -> None:
+ self.handles.close()
+
+ def _get_properties(self) -> None:
+ # Check magic number
+ self._path_or_buf.seek(0)
+ self._cached_page = self._path_or_buf.read(288)
+ if self._cached_page[0 : len(const.magic)] != const.magic:
+ raise ValueError("magic number mismatch (not a SAS file?)")
+
+ # Get alignment information
+ buf = self._read_bytes(const.align_1_offset, const.align_1_length)
+ if buf == const.u64_byte_checker_value:
+ self.U64 = True
+ self._int_length = 8
+ self._page_bit_offset = const.page_bit_offset_x64
+ self._subheader_pointer_length = const.subheader_pointer_length_x64
+ else:
+ self.U64 = False
+ self._page_bit_offset = const.page_bit_offset_x86
+ self._subheader_pointer_length = const.subheader_pointer_length_x86
+ self._int_length = 4
+ buf = self._read_bytes(const.align_2_offset, const.align_2_length)
+ if buf == const.align_1_checker_value:
+ align1 = const.align_2_value
+ else:
+ align1 = 0
+
+ # Get endianness information
+ buf = self._read_bytes(const.endianness_offset, const.endianness_length)
+ if buf == b"\x01":
+ self.byte_order = "<"
+ self.need_byteswap = sys.byteorder == "big"
+ else:
+ self.byte_order = ">"
+ self.need_byteswap = sys.byteorder == "little"
+
+ # Get encoding information
+ buf = self._read_bytes(const.encoding_offset, const.encoding_length)[0]
+ if buf in const.encoding_names:
+ self.inferred_encoding = const.encoding_names[buf]
+ if self.encoding == "infer":
+ self.encoding = self.inferred_encoding
+ else:
+ self.inferred_encoding = f"unknown (code={buf})"
+
+ # Timestamp is epoch 01/01/1960
+ epoch = datetime(1960, 1, 1)
+ x = self._read_float(
+ const.date_created_offset + align1, const.date_created_length
+ )
+ self.date_created = epoch + pd.to_timedelta(x, unit="s")
+ x = self._read_float(
+ const.date_modified_offset + align1, const.date_modified_length
+ )
+ self.date_modified = epoch + pd.to_timedelta(x, unit="s")
+
+ self.header_length = self._read_uint(
+ const.header_size_offset + align1, const.header_size_length
+ )
+
+ # Read the rest of the header into cached_page.
+ buf = self._path_or_buf.read(self.header_length - 288)
+ self._cached_page += buf
+ # error: Argument 1 to "len" has incompatible type "Optional[bytes]";
+ # expected "Sized"
+ if len(self._cached_page) != self.header_length: # type: ignore[arg-type]
+ raise ValueError("The SAS7BDAT file appears to be truncated.")
+
+ self._page_length = self._read_uint(
+ const.page_size_offset + align1, const.page_size_length
+ )
+
+ def __next__(self) -> DataFrame:
+ da = self.read(nrows=self.chunksize or 1)
+ if da.empty:
+ self.close()
+ raise StopIteration
+ return da
+
+ # Read a single float of the given width (4 or 8).
+ def _read_float(self, offset: int, width: int):
+ assert self._cached_page is not None
+ if width == 4:
+ return read_float_with_byteswap(
+ self._cached_page, offset, self.need_byteswap
+ )
+ elif width == 8:
+ return read_double_with_byteswap(
+ self._cached_page, offset, self.need_byteswap
+ )
+ else:
+ self.close()
+ raise ValueError("invalid float width")
+
+ # Read a single unsigned integer of the given width (1, 2, 4 or 8).
+ def _read_uint(self, offset: int, width: int) -> int:
+ assert self._cached_page is not None
+ if width == 1:
+ return self._read_bytes(offset, 1)[0]
+ elif width == 2:
+ return read_uint16_with_byteswap(
+ self._cached_page, offset, self.need_byteswap
+ )
+ elif width == 4:
+ return read_uint32_with_byteswap(
+ self._cached_page, offset, self.need_byteswap
+ )
+ elif width == 8:
+ return read_uint64_with_byteswap(
+ self._cached_page, offset, self.need_byteswap
+ )
+ else:
+ self.close()
+ raise ValueError("invalid int width")
+
+ def _read_bytes(self, offset: int, length: int):
+ assert self._cached_page is not None
+ if offset + length > len(self._cached_page):
+ self.close()
+ raise ValueError("The cached page is too small.")
+ return self._cached_page[offset : offset + length]
+
+ def _read_and_convert_header_text(self, offset: int, length: int) -> str | bytes:
+ return self._convert_header_text(
+ self._read_bytes(offset, length).rstrip(b"\x00 ")
+ )
+
+ def _parse_metadata(self) -> None:
+ done = False
+ while not done:
+ self._cached_page = self._path_or_buf.read(self._page_length)
+ if len(self._cached_page) <= 0:
+ break
+ if len(self._cached_page) != self._page_length:
+ raise ValueError("Failed to read a meta data page from the SAS file.")
+ done = self._process_page_meta()
+
+ def _process_page_meta(self) -> bool:
+ self._read_page_header()
+ pt = const.page_meta_types + [const.page_amd_type, const.page_mix_type]
+ if self._current_page_type in pt:
+ self._process_page_metadata()
+ is_data_page = self._current_page_type == const.page_data_type
+ is_mix_page = self._current_page_type == const.page_mix_type
+ return bool(
+ is_data_page
+ or is_mix_page
+ or self._current_page_data_subheader_pointers != []
+ )
+
+ def _read_page_header(self) -> None:
+ bit_offset = self._page_bit_offset
+ tx = const.page_type_offset + bit_offset
+ self._current_page_type = (
+ self._read_uint(tx, const.page_type_length) & const.page_type_mask2
+ )
+ tx = const.block_count_offset + bit_offset
+ self._current_page_block_count = self._read_uint(tx, const.block_count_length)
+ tx = const.subheader_count_offset + bit_offset
+ self._current_page_subheaders_count = self._read_uint(
+ tx, const.subheader_count_length
+ )
+
+ def _process_page_metadata(self) -> None:
+ bit_offset = self._page_bit_offset
+
+ for i in range(self._current_page_subheaders_count):
+ offset = const.subheader_pointers_offset + bit_offset
+ total_offset = offset + self._subheader_pointer_length * i
+
+ subheader_offset = self._read_uint(total_offset, self._int_length)
+ total_offset += self._int_length
+
+ subheader_length = self._read_uint(total_offset, self._int_length)
+ total_offset += self._int_length
+
+ subheader_compression = self._read_uint(total_offset, 1)
+ total_offset += 1
+
+ subheader_type = self._read_uint(total_offset, 1)
+
+ if (
+ subheader_length == 0
+ or subheader_compression == const.truncated_subheader_id
+ ):
+ continue
+
+ subheader_signature = self._read_bytes(subheader_offset, self._int_length)
+ subheader_index = get_subheader_index(subheader_signature)
+ subheader_processor = self._subheader_processors[subheader_index]
+
+ if subheader_processor is None:
+ f1 = subheader_compression in (const.compressed_subheader_id, 0)
+ f2 = subheader_type == const.compressed_subheader_type
+ if self.compression and f1 and f2:
+ self._current_page_data_subheader_pointers.append(
+ (subheader_offset, subheader_length)
+ )
+ else:
+ self.close()
+ raise ValueError(
+ f"Unknown subheader signature {subheader_signature}"
+ )
+ else:
+ subheader_processor(subheader_offset, subheader_length)
+
+ def _process_rowsize_subheader(self, offset: int, length: int) -> None:
+ int_len = self._int_length
+ lcs_offset = offset
+ lcp_offset = offset
+ if self.U64:
+ lcs_offset += 682
+ lcp_offset += 706
+ else:
+ lcs_offset += 354
+ lcp_offset += 378
+
+ self.row_length = self._read_uint(
+ offset + const.row_length_offset_multiplier * int_len,
+ int_len,
+ )
+ self.row_count = self._read_uint(
+ offset + const.row_count_offset_multiplier * int_len,
+ int_len,
+ )
+ self.col_count_p1 = self._read_uint(
+ offset + const.col_count_p1_multiplier * int_len, int_len
+ )
+ self.col_count_p2 = self._read_uint(
+ offset + const.col_count_p2_multiplier * int_len, int_len
+ )
+ mx = const.row_count_on_mix_page_offset_multiplier * int_len
+ self._mix_page_row_count = self._read_uint(offset + mx, int_len)
+ self._lcs = self._read_uint(lcs_offset, 2)
+ self._lcp = self._read_uint(lcp_offset, 2)
+
+ def _process_columnsize_subheader(self, offset: int, length: int) -> None:
+ int_len = self._int_length
+ offset += int_len
+ self.column_count = self._read_uint(offset, int_len)
+ if self.col_count_p1 + self.col_count_p2 != self.column_count:
+ print(
+ f"Warning: column count mismatch ({self.col_count_p1} + "
+ f"{self.col_count_p2} != {self.column_count})\n"
+ )
+
+ # Unknown purpose
+ def _process_subheader_counts(self, offset: int, length: int) -> None:
+ pass
+
+ def _process_columntext_subheader(self, offset: int, length: int) -> None:
+ offset += self._int_length
+ text_block_size = self._read_uint(offset, const.text_block_size_length)
+
+ buf = self._read_bytes(offset, text_block_size)
+ cname_raw = buf[0:text_block_size].rstrip(b"\x00 ")
+ self.column_names_raw.append(cname_raw)
+
+ if len(self.column_names_raw) == 1:
+ compression_literal = b""
+ for cl in const.compression_literals:
+ if cl in cname_raw:
+ compression_literal = cl
+ self.compression = compression_literal
+ offset -= self._int_length
+
+ offset1 = offset + 16
+ if self.U64:
+ offset1 += 4
+
+ buf = self._read_bytes(offset1, self._lcp)
+ compression_literal = buf.rstrip(b"\x00")
+ if compression_literal == b"":
+ self._lcs = 0
+ offset1 = offset + 32
+ if self.U64:
+ offset1 += 4
+ buf = self._read_bytes(offset1, self._lcp)
+ self.creator_proc = buf[0 : self._lcp]
+ elif compression_literal == const.rle_compression:
+ offset1 = offset + 40
+ if self.U64:
+ offset1 += 4
+ buf = self._read_bytes(offset1, self._lcp)
+ self.creator_proc = buf[0 : self._lcp]
+ elif self._lcs > 0:
+ self._lcp = 0
+ offset1 = offset + 16
+ if self.U64:
+ offset1 += 4
+ buf = self._read_bytes(offset1, self._lcs)
+ self.creator_proc = buf[0 : self._lcp]
+ if hasattr(self, "creator_proc"):
+ self.creator_proc = self._convert_header_text(self.creator_proc)
+
+ def _process_columnname_subheader(self, offset: int, length: int) -> None:
+ int_len = self._int_length
+ offset += int_len
+ column_name_pointers_count = (length - 2 * int_len - 12) // 8
+ for i in range(column_name_pointers_count):
+ text_subheader = (
+ offset
+ + const.column_name_pointer_length * (i + 1)
+ + const.column_name_text_subheader_offset
+ )
+ col_name_offset = (
+ offset
+ + const.column_name_pointer_length * (i + 1)
+ + const.column_name_offset_offset
+ )
+ col_name_length = (
+ offset
+ + const.column_name_pointer_length * (i + 1)
+ + const.column_name_length_offset
+ )
+
+ idx = self._read_uint(
+ text_subheader, const.column_name_text_subheader_length
+ )
+ col_offset = self._read_uint(
+ col_name_offset, const.column_name_offset_length
+ )
+ col_len = self._read_uint(col_name_length, const.column_name_length_length)
+
+ name_raw = self.column_names_raw[idx]
+ cname = name_raw[col_offset : col_offset + col_len]
+ self.column_names.append(self._convert_header_text(cname))
+
+ def _process_columnattributes_subheader(self, offset: int, length: int) -> None:
+ int_len = self._int_length
+ column_attributes_vectors_count = (length - 2 * int_len - 12) // (int_len + 8)
+ for i in range(column_attributes_vectors_count):
+ col_data_offset = (
+ offset + int_len + const.column_data_offset_offset + i * (int_len + 8)
+ )
+ col_data_len = (
+ offset
+ + 2 * int_len
+ + const.column_data_length_offset
+ + i * (int_len + 8)
+ )
+ col_types = (
+ offset + 2 * int_len + const.column_type_offset + i * (int_len + 8)
+ )
+
+ x = self._read_uint(col_data_offset, int_len)
+ self._column_data_offsets.append(x)
+
+ x = self._read_uint(col_data_len, const.column_data_length_length)
+ self._column_data_lengths.append(x)
+
+ x = self._read_uint(col_types, const.column_type_length)
+ self._column_types.append(b"d" if x == 1 else b"s")
+
+ def _process_columnlist_subheader(self, offset: int, length: int) -> None:
+ # unknown purpose
+ pass
+
+ def _process_format_subheader(self, offset: int, length: int) -> None:
+ int_len = self._int_length
+ text_subheader_format = (
+ offset + const.column_format_text_subheader_index_offset + 3 * int_len
+ )
+ col_format_offset = offset + const.column_format_offset_offset + 3 * int_len
+ col_format_len = offset + const.column_format_length_offset + 3 * int_len
+ text_subheader_label = (
+ offset + const.column_label_text_subheader_index_offset + 3 * int_len
+ )
+ col_label_offset = offset + const.column_label_offset_offset + 3 * int_len
+ col_label_len = offset + const.column_label_length_offset + 3 * int_len
+
+ x = self._read_uint(
+ text_subheader_format, const.column_format_text_subheader_index_length
+ )
+ format_idx = min(x, len(self.column_names_raw) - 1)
+
+ format_start = self._read_uint(
+ col_format_offset, const.column_format_offset_length
+ )
+ format_len = self._read_uint(col_format_len, const.column_format_length_length)
+
+ label_idx = self._read_uint(
+ text_subheader_label, const.column_label_text_subheader_index_length
+ )
+ label_idx = min(label_idx, len(self.column_names_raw) - 1)
+
+ label_start = self._read_uint(
+ col_label_offset, const.column_label_offset_length
+ )
+ label_len = self._read_uint(col_label_len, const.column_label_length_length)
+
+ label_names = self.column_names_raw[label_idx]
+ column_label = self._convert_header_text(
+ label_names[label_start : label_start + label_len]
+ )
+ format_names = self.column_names_raw[format_idx]
+ column_format = self._convert_header_text(
+ format_names[format_start : format_start + format_len]
+ )
+ current_column_number = len(self.columns)
+
+ col = _Column(
+ current_column_number,
+ self.column_names[current_column_number],
+ column_label,
+ column_format,
+ self._column_types[current_column_number],
+ self._column_data_lengths[current_column_number],
+ )
+
+ self.column_formats.append(column_format)
+ self.columns.append(col)
+
+ def read(self, nrows: int | None = None) -> DataFrame:
+ if (nrows is None) and (self.chunksize is not None):
+ nrows = self.chunksize
+ elif nrows is None:
+ nrows = self.row_count
+
+ if len(self._column_types) == 0:
+ self.close()
+ raise EmptyDataError("No columns to parse from file")
+
+ if nrows > 0 and self._current_row_in_file_index >= self.row_count:
+ return DataFrame()
+
+ nrows = min(nrows, self.row_count - self._current_row_in_file_index)
+
+ nd = self._column_types.count(b"d")
+ ns = self._column_types.count(b"s")
+
+ self._string_chunk = np.empty((ns, nrows), dtype=object)
+ self._byte_chunk = np.zeros((nd, 8 * nrows), dtype=np.uint8)
+
+ self._current_row_in_chunk_index = 0
+ p = Parser(self)
+ p.read(nrows)
+
+ rslt = self._chunk_to_dataframe()
+ if self.index is not None:
+ rslt = rslt.set_index(self.index)
+
+ return rslt
+
+ def _read_next_page(self):
+ self._current_page_data_subheader_pointers = []
+ self._cached_page = self._path_or_buf.read(self._page_length)
+ if len(self._cached_page) <= 0:
+ return True
+ elif len(self._cached_page) != self._page_length:
+ self.close()
+ msg = (
+ "failed to read complete page from file (read "
+ f"{len(self._cached_page):d} of {self._page_length:d} bytes)"
+ )
+ raise ValueError(msg)
+
+ self._read_page_header()
+ if self._current_page_type in const.page_meta_types:
+ self._process_page_metadata()
+
+ if self._current_page_type not in const.page_meta_types + [
+ const.page_data_type,
+ const.page_mix_type,
+ ]:
+ return self._read_next_page()
+
+ return False
+
+ def _chunk_to_dataframe(self) -> DataFrame:
+ n = self._current_row_in_chunk_index
+ m = self._current_row_in_file_index
+ ix = range(m - n, m)
+ rslt = {}
+
+ js, jb = 0, 0
+ for j in range(self.column_count):
+ name = self.column_names[j]
+
+ if self._column_types[j] == b"d":
+ col_arr = self._byte_chunk[jb, :].view(dtype=self.byte_order + "d")
+ rslt[name] = pd.Series(col_arr, dtype=np.float64, index=ix)
+ if self.convert_dates:
+ if self.column_formats[j] in const.sas_date_formats:
+ rslt[name] = _convert_datetimes(rslt[name], "d")
+ elif self.column_formats[j] in const.sas_datetime_formats:
+ rslt[name] = _convert_datetimes(rslt[name], "s")
+ jb += 1
+ elif self._column_types[j] == b"s":
+ rslt[name] = pd.Series(self._string_chunk[js, :], index=ix)
+ if self.convert_text and (self.encoding is not None):
+ rslt[name] = self._decode_string(rslt[name].str)
+ js += 1
+ else:
+ self.close()
+ raise ValueError(f"unknown column type {repr(self._column_types[j])}")
+
+ df = DataFrame(rslt, columns=self.column_names, index=ix, copy=False)
+ return df
+
+ def _decode_string(self, b):
+ return b.decode(self.encoding or self.default_encoding)
+
+ def _convert_header_text(self, b: bytes) -> str | bytes:
+ if self.convert_header_text:
+ return self._decode_string(b)
+ else:
+ return b
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sas_constants.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sas_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..62c17bd03927e5f852af708e6b9ef6cf7e74d57c
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sas_constants.py
@@ -0,0 +1,310 @@
+from __future__ import annotations
+
+from typing import Final
+
+magic: Final = (
+ b"\x00\x00\x00\x00\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00\xc2\xea\x81\x60"
+ b"\xb3\x14\x11\xcf\xbd\x92\x08\x00"
+ b"\x09\xc7\x31\x8c\x18\x1f\x10\x11"
+)
+
+align_1_checker_value: Final = b"3"
+align_1_offset: Final = 32
+align_1_length: Final = 1
+align_1_value: Final = 4
+u64_byte_checker_value: Final = b"3"
+align_2_offset: Final = 35
+align_2_length: Final = 1
+align_2_value: Final = 4
+endianness_offset: Final = 37
+endianness_length: Final = 1
+platform_offset: Final = 39
+platform_length: Final = 1
+encoding_offset: Final = 70
+encoding_length: Final = 1
+dataset_offset: Final = 92
+dataset_length: Final = 64
+file_type_offset: Final = 156
+file_type_length: Final = 8
+date_created_offset: Final = 164
+date_created_length: Final = 8
+date_modified_offset: Final = 172
+date_modified_length: Final = 8
+header_size_offset: Final = 196
+header_size_length: Final = 4
+page_size_offset: Final = 200
+page_size_length: Final = 4
+page_count_offset: Final = 204
+page_count_length: Final = 4
+sas_release_offset: Final = 216
+sas_release_length: Final = 8
+sas_server_type_offset: Final = 224
+sas_server_type_length: Final = 16
+os_version_number_offset: Final = 240
+os_version_number_length: Final = 16
+os_maker_offset: Final = 256
+os_maker_length: Final = 16
+os_name_offset: Final = 272
+os_name_length: Final = 16
+page_bit_offset_x86: Final = 16
+page_bit_offset_x64: Final = 32
+subheader_pointer_length_x86: Final = 12
+subheader_pointer_length_x64: Final = 24
+page_type_offset: Final = 0
+page_type_length: Final = 2
+block_count_offset: Final = 2
+block_count_length: Final = 2
+subheader_count_offset: Final = 4
+subheader_count_length: Final = 2
+page_type_mask: Final = 0x0F00
+# Keep "page_comp_type" bits
+page_type_mask2: Final = 0xF000 | page_type_mask
+page_meta_type: Final = 0x0000
+page_data_type: Final = 0x0100
+page_mix_type: Final = 0x0200
+page_amd_type: Final = 0x0400
+page_meta2_type: Final = 0x4000
+page_comp_type: Final = 0x9000
+page_meta_types: Final = [page_meta_type, page_meta2_type]
+subheader_pointers_offset: Final = 8
+truncated_subheader_id: Final = 1
+compressed_subheader_id: Final = 4
+compressed_subheader_type: Final = 1
+text_block_size_length: Final = 2
+row_length_offset_multiplier: Final = 5
+row_count_offset_multiplier: Final = 6
+col_count_p1_multiplier: Final = 9
+col_count_p2_multiplier: Final = 10
+row_count_on_mix_page_offset_multiplier: Final = 15
+column_name_pointer_length: Final = 8
+column_name_text_subheader_offset: Final = 0
+column_name_text_subheader_length: Final = 2
+column_name_offset_offset: Final = 2
+column_name_offset_length: Final = 2
+column_name_length_offset: Final = 4
+column_name_length_length: Final = 2
+column_data_offset_offset: Final = 8
+column_data_length_offset: Final = 8
+column_data_length_length: Final = 4
+column_type_offset: Final = 14
+column_type_length: Final = 1
+column_format_text_subheader_index_offset: Final = 22
+column_format_text_subheader_index_length: Final = 2
+column_format_offset_offset: Final = 24
+column_format_offset_length: Final = 2
+column_format_length_offset: Final = 26
+column_format_length_length: Final = 2
+column_label_text_subheader_index_offset: Final = 28
+column_label_text_subheader_index_length: Final = 2
+column_label_offset_offset: Final = 30
+column_label_offset_length: Final = 2
+column_label_length_offset: Final = 32
+column_label_length_length: Final = 2
+rle_compression: Final = b"SASYZCRL"
+rdc_compression: Final = b"SASYZCR2"
+
+compression_literals: Final = [rle_compression, rdc_compression]
+
+# Incomplete list of encodings, using SAS nomenclature:
+# https://support.sas.com/documentation/onlinedoc/dfdmstudio/2.6/dmpdmsug/Content/dfU_Encodings_SAS.html
+# corresponding to the Python documentation of standard encodings
+# https://docs.python.org/3/library/codecs.html#standard-encodings
+encoding_names: Final = {
+ 20: "utf-8",
+ 29: "latin1",
+ 30: "latin2",
+ 31: "latin3",
+ 32: "latin4",
+ 33: "cyrillic",
+ 34: "arabic",
+ 35: "greek",
+ 36: "hebrew",
+ 37: "latin5",
+ 38: "latin6",
+ 39: "cp874",
+ 40: "latin9",
+ 41: "cp437",
+ 42: "cp850",
+ 43: "cp852",
+ 44: "cp857",
+ 45: "cp858",
+ 46: "cp862",
+ 47: "cp864",
+ 48: "cp865",
+ 49: "cp866",
+ 50: "cp869",
+ 51: "cp874",
+ # 52: "", # not found
+ # 53: "", # not found
+ # 54: "", # not found
+ 55: "cp720",
+ 56: "cp737",
+ 57: "cp775",
+ 58: "cp860",
+ 59: "cp863",
+ 60: "cp1250",
+ 61: "cp1251",
+ 62: "cp1252",
+ 63: "cp1253",
+ 64: "cp1254",
+ 65: "cp1255",
+ 66: "cp1256",
+ 67: "cp1257",
+ 68: "cp1258",
+ 118: "cp950",
+ # 119: "", # not found
+ 123: "big5",
+ 125: "gb2312",
+ 126: "cp936",
+ 134: "euc_jp",
+ 136: "cp932",
+ 138: "shift_jis",
+ 140: "euc-kr",
+ 141: "cp949",
+ 227: "latin8",
+ # 228: "", # not found
+ # 229: "" # not found
+}
+
+
+class SASIndex:
+ row_size_index: Final = 0
+ column_size_index: Final = 1
+ subheader_counts_index: Final = 2
+ column_text_index: Final = 3
+ column_name_index: Final = 4
+ column_attributes_index: Final = 5
+ format_and_label_index: Final = 6
+ column_list_index: Final = 7
+ data_subheader_index: Final = 8
+
+
+subheader_signature_to_index: Final = {
+ b"\xF7\xF7\xF7\xF7": SASIndex.row_size_index,
+ b"\x00\x00\x00\x00\xF7\xF7\xF7\xF7": SASIndex.row_size_index,
+ b"\xF7\xF7\xF7\xF7\x00\x00\x00\x00": SASIndex.row_size_index,
+ b"\xF7\xF7\xF7\xF7\xFF\xFF\xFB\xFE": SASIndex.row_size_index,
+ b"\xF6\xF6\xF6\xF6": SASIndex.column_size_index,
+ b"\x00\x00\x00\x00\xF6\xF6\xF6\xF6": SASIndex.column_size_index,
+ b"\xF6\xF6\xF6\xF6\x00\x00\x00\x00": SASIndex.column_size_index,
+ b"\xF6\xF6\xF6\xF6\xFF\xFF\xFB\xFE": SASIndex.column_size_index,
+ b"\x00\xFC\xFF\xFF": SASIndex.subheader_counts_index,
+ b"\xFF\xFF\xFC\x00": SASIndex.subheader_counts_index,
+ b"\x00\xFC\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.subheader_counts_index,
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFC\x00": SASIndex.subheader_counts_index,
+ b"\xFD\xFF\xFF\xFF": SASIndex.column_text_index,
+ b"\xFF\xFF\xFF\xFD": SASIndex.column_text_index,
+ b"\xFD\xFF\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.column_text_index,
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFD": SASIndex.column_text_index,
+ b"\xFF\xFF\xFF\xFF": SASIndex.column_name_index,
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.column_name_index,
+ b"\xFC\xFF\xFF\xFF": SASIndex.column_attributes_index,
+ b"\xFF\xFF\xFF\xFC": SASIndex.column_attributes_index,
+ b"\xFC\xFF\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.column_attributes_index,
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC": SASIndex.column_attributes_index,
+ b"\xFE\xFB\xFF\xFF": SASIndex.format_and_label_index,
+ b"\xFF\xFF\xFB\xFE": SASIndex.format_and_label_index,
+ b"\xFE\xFB\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.format_and_label_index,
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFB\xFE": SASIndex.format_and_label_index,
+ b"\xFE\xFF\xFF\xFF": SASIndex.column_list_index,
+ b"\xFF\xFF\xFF\xFE": SASIndex.column_list_index,
+ b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.column_list_index,
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE": SASIndex.column_list_index,
+}
+
+
+# List of frequently used SAS date and datetime formats
+# http://support.sas.com/documentation/cdl/en/etsug/60372/HTML/default/viewer.htm#etsug_intervals_sect009.htm
+# https://github.com/epam/parso/blob/master/src/main/java/com/epam/parso/impl/SasFileConstants.java
+sas_date_formats: Final = (
+ "DATE",
+ "DAY",
+ "DDMMYY",
+ "DOWNAME",
+ "JULDAY",
+ "JULIAN",
+ "MMDDYY",
+ "MMYY",
+ "MMYYC",
+ "MMYYD",
+ "MMYYP",
+ "MMYYS",
+ "MMYYN",
+ "MONNAME",
+ "MONTH",
+ "MONYY",
+ "QTR",
+ "QTRR",
+ "NENGO",
+ "WEEKDATE",
+ "WEEKDATX",
+ "WEEKDAY",
+ "WEEKV",
+ "WORDDATE",
+ "WORDDATX",
+ "YEAR",
+ "YYMM",
+ "YYMMC",
+ "YYMMD",
+ "YYMMP",
+ "YYMMS",
+ "YYMMN",
+ "YYMON",
+ "YYMMDD",
+ "YYQ",
+ "YYQC",
+ "YYQD",
+ "YYQP",
+ "YYQS",
+ "YYQN",
+ "YYQR",
+ "YYQRC",
+ "YYQRD",
+ "YYQRP",
+ "YYQRS",
+ "YYQRN",
+ "YYMMDDP",
+ "YYMMDDC",
+ "E8601DA",
+ "YYMMDDN",
+ "MMDDYYC",
+ "MMDDYYS",
+ "MMDDYYD",
+ "YYMMDDS",
+ "B8601DA",
+ "DDMMYYN",
+ "YYMMDDD",
+ "DDMMYYB",
+ "DDMMYYP",
+ "MMDDYYP",
+ "YYMMDDB",
+ "MMDDYYN",
+ "DDMMYYC",
+ "DDMMYYD",
+ "DDMMYYS",
+ "MINGUO",
+)
+
+sas_datetime_formats: Final = (
+ "DATETIME",
+ "DTWKDATX",
+ "B8601DN",
+ "B8601DT",
+ "B8601DX",
+ "B8601DZ",
+ "B8601LX",
+ "E8601DN",
+ "E8601DT",
+ "E8601DX",
+ "E8601DZ",
+ "E8601LX",
+ "DATEAMPM",
+ "DTDATE",
+ "DTMONYY",
+ "DTMONYY",
+ "DTWKDATX",
+ "DTYEAR",
+ "TOD",
+ "MDYAMPM",
+)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sas_xport.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sas_xport.py
new file mode 100644
index 0000000000000000000000000000000000000000..e68f4789f0a06ee8c6a30be47fbadc9b0ba5a12a
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sas_xport.py
@@ -0,0 +1,508 @@
+"""
+Read a SAS XPort format file into a Pandas DataFrame.
+
+Based on code from Jack Cushman (github.com/jcushman/xport).
+
+The file format is defined here:
+
+https://support.sas.com/content/dam/SAS/support/en/technical-papers/record-layout-of-a-sas-version-5-or-6-data-set-in-sas-transport-xport-format.pdf
+"""
+from __future__ import annotations
+
+from collections import abc
+from datetime import datetime
+import struct
+from typing import TYPE_CHECKING
+import warnings
+
+import numpy as np
+
+from pandas.util._decorators import Appender
+from pandas.util._exceptions import find_stack_level
+
+import pandas as pd
+
+from pandas.io.common import get_handle
+from pandas.io.sas.sasreader import ReaderBase
+
+if TYPE_CHECKING:
+ from pandas._typing import (
+ CompressionOptions,
+ DatetimeNaTType,
+ FilePath,
+ ReadBuffer,
+ )
+_correct_line1 = (
+ "HEADER RECORD*******LIBRARY HEADER RECORD!!!!!!!"
+ "000000000000000000000000000000 "
+)
+_correct_header1 = (
+ "HEADER RECORD*******MEMBER HEADER RECORD!!!!!!!000000000000000001600000000"
+)
+_correct_header2 = (
+ "HEADER RECORD*******DSCRPTR HEADER RECORD!!!!!!!"
+ "000000000000000000000000000000 "
+)
+_correct_obs_header = (
+ "HEADER RECORD*******OBS HEADER RECORD!!!!!!!"
+ "000000000000000000000000000000 "
+)
+_fieldkeys = [
+ "ntype",
+ "nhfun",
+ "field_length",
+ "nvar0",
+ "name",
+ "label",
+ "nform",
+ "nfl",
+ "num_decimals",
+ "nfj",
+ "nfill",
+ "niform",
+ "nifl",
+ "nifd",
+ "npos",
+ "_",
+]
+
+
+_base_params_doc = """\
+Parameters
+----------
+filepath_or_buffer : str or file-like object
+ Path to SAS file or object implementing binary read method."""
+
+_params2_doc = """\
+index : identifier of index column
+ Identifier of column that should be used as index of the DataFrame.
+encoding : str
+ Encoding for text data.
+chunksize : int
+ Read file `chunksize` lines at a time, returns iterator."""
+
+_format_params_doc = """\
+format : str
+ File format, only `xport` is currently supported."""
+
+_iterator_doc = """\
+iterator : bool, default False
+ Return XportReader object for reading file incrementally."""
+
+
+_read_sas_doc = f"""Read a SAS file into a DataFrame.
+
+{_base_params_doc}
+{_format_params_doc}
+{_params2_doc}
+{_iterator_doc}
+
+Returns
+-------
+DataFrame or XportReader
+
+Examples
+--------
+Read a SAS Xport file:
+
+>>> df = pd.read_sas('filename.XPT')
+
+Read a Xport file in 10,000 line chunks:
+
+>>> itr = pd.read_sas('filename.XPT', chunksize=10000)
+>>> for chunk in itr:
+>>> do_something(chunk)
+
+"""
+
+_xport_reader_doc = f"""\
+Class for reading SAS Xport files.
+
+{_base_params_doc}
+{_params2_doc}
+
+Attributes
+----------
+member_info : list
+ Contains information about the file
+fields : list
+ Contains information about the variables in the file
+"""
+
+_read_method_doc = """\
+Read observations from SAS Xport file, returning as data frame.
+
+Parameters
+----------
+nrows : int
+ Number of rows to read from data file; if None, read whole
+ file.
+
+Returns
+-------
+A DataFrame.
+"""
+
+
+def _parse_date(datestr: str) -> DatetimeNaTType:
+ """Given a date in xport format, return Python date."""
+ try:
+ # e.g. "16FEB11:10:07:55"
+ return datetime.strptime(datestr, "%d%b%y:%H:%M:%S")
+ except ValueError:
+ return pd.NaT
+
+
+def _split_line(s: str, parts):
+ """
+ Parameters
+ ----------
+ s: str
+ Fixed-length string to split
+ parts: list of (name, length) pairs
+ Used to break up string, name '_' will be filtered from output.
+
+ Returns
+ -------
+ Dict of name:contents of string at given location.
+ """
+ out = {}
+ start = 0
+ for name, length in parts:
+ out[name] = s[start : start + length].strip()
+ start += length
+ del out["_"]
+ return out
+
+
+def _handle_truncated_float_vec(vec, nbytes):
+ # This feature is not well documented, but some SAS XPORT files
+ # have 2-7 byte "truncated" floats. To read these truncated
+ # floats, pad them with zeros on the right to make 8 byte floats.
+ #
+ # References:
+ # https://github.com/jcushman/xport/pull/3
+ # The R "foreign" library
+
+ if nbytes != 8:
+ vec1 = np.zeros(len(vec), np.dtype("S8"))
+ dtype = np.dtype(f"S{nbytes},S{8 - nbytes}")
+ vec2 = vec1.view(dtype=dtype)
+ vec2["f0"] = vec
+ return vec2
+
+ return vec
+
+
+def _parse_float_vec(vec):
+ """
+ Parse a vector of float values representing IBM 8 byte floats into
+ native 8 byte floats.
+ """
+ dtype = np.dtype(">u4,>u4")
+ vec1 = vec.view(dtype=dtype)
+ xport1 = vec1["f0"]
+ xport2 = vec1["f1"]
+
+ # Start by setting first half of ieee number to first half of IBM
+ # number sans exponent
+ ieee1 = xport1 & 0x00FFFFFF
+
+ # The fraction bit to the left of the binary point in the ieee
+ # format was set and the number was shifted 0, 1, 2, or 3
+ # places. This will tell us how to adjust the ibm exponent to be a
+ # power of 2 ieee exponent and how to shift the fraction bits to
+ # restore the correct magnitude.
+ shift = np.zeros(len(vec), dtype=np.uint8)
+ shift[np.where(xport1 & 0x00200000)] = 1
+ shift[np.where(xport1 & 0x00400000)] = 2
+ shift[np.where(xport1 & 0x00800000)] = 3
+
+ # shift the ieee number down the correct number of places then
+ # set the second half of the ieee number to be the second half
+ # of the ibm number shifted appropriately, ored with the bits
+ # from the first half that would have been shifted in if we
+ # could shift a double. All we are worried about are the low
+ # order 3 bits of the first half since we're only shifting by
+ # 1, 2, or 3.
+ ieee1 >>= shift
+ ieee2 = (xport2 >> shift) | ((xport1 & 0x00000007) << (29 + (3 - shift)))
+
+ # clear the 1 bit to the left of the binary point
+ ieee1 &= 0xFFEFFFFF
+
+ # set the exponent of the ieee number to be the actual exponent
+ # plus the shift count + 1023. Or this into the first half of the
+ # ieee number. The ibm exponent is excess 64 but is adjusted by 65
+ # since during conversion to ibm format the exponent is
+ # incremented by 1 and the fraction bits left 4 positions to the
+ # right of the radix point. (had to add >> 24 because C treats &
+ # 0x7f as 0x7f000000 and Python doesn't)
+ ieee1 |= ((((((xport1 >> 24) & 0x7F) - 65) << 2) + shift + 1023) << 20) | (
+ xport1 & 0x80000000
+ )
+
+ ieee = np.empty((len(ieee1),), dtype=">u4,>u4")
+ ieee["f0"] = ieee1
+ ieee["f1"] = ieee2
+ ieee = ieee.view(dtype=">f8")
+ ieee = ieee.astype("f8")
+
+ return ieee
+
+
+class XportReader(ReaderBase, abc.Iterator):
+ __doc__ = _xport_reader_doc
+
+ def __init__(
+ self,
+ filepath_or_buffer: FilePath | ReadBuffer[bytes],
+ index=None,
+ encoding: str | None = "ISO-8859-1",
+ chunksize: int | None = None,
+ compression: CompressionOptions = "infer",
+ ) -> None:
+ self._encoding = encoding
+ self._lines_read = 0
+ self._index = index
+ self._chunksize = chunksize
+
+ self.handles = get_handle(
+ filepath_or_buffer,
+ "rb",
+ encoding=encoding,
+ is_text=False,
+ compression=compression,
+ )
+ self.filepath_or_buffer = self.handles.handle
+
+ try:
+ self._read_header()
+ except Exception:
+ self.close()
+ raise
+
+ def close(self) -> None:
+ self.handles.close()
+
+ def _get_row(self):
+ return self.filepath_or_buffer.read(80).decode()
+
+ def _read_header(self):
+ self.filepath_or_buffer.seek(0)
+
+ # read file header
+ line1 = self._get_row()
+ if line1 != _correct_line1:
+ if "**COMPRESSED**" in line1:
+ # this was created with the PROC CPORT method and can't be read
+ # https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/movefile/p1bm6aqp3fw4uin1hucwh718f6kp.htm
+ raise ValueError(
+ "Header record indicates a CPORT file, which is not readable."
+ )
+ raise ValueError("Header record is not an XPORT file.")
+
+ line2 = self._get_row()
+ fif = [["prefix", 24], ["version", 8], ["OS", 8], ["_", 24], ["created", 16]]
+ file_info = _split_line(line2, fif)
+ if file_info["prefix"] != "SAS SAS SASLIB":
+ raise ValueError("Header record has invalid prefix.")
+ file_info["created"] = _parse_date(file_info["created"])
+ self.file_info = file_info
+
+ line3 = self._get_row()
+ file_info["modified"] = _parse_date(line3[:16])
+
+ # read member header
+ header1 = self._get_row()
+ header2 = self._get_row()
+ headflag1 = header1.startswith(_correct_header1)
+ headflag2 = header2 == _correct_header2
+ if not (headflag1 and headflag2):
+ raise ValueError("Member header not found")
+ # usually 140, could be 135
+ fieldnamelength = int(header1[-5:-2])
+
+ # member info
+ mem = [
+ ["prefix", 8],
+ ["set_name", 8],
+ ["sasdata", 8],
+ ["version", 8],
+ ["OS", 8],
+ ["_", 24],
+ ["created", 16],
+ ]
+ member_info = _split_line(self._get_row(), mem)
+ mem = [["modified", 16], ["_", 16], ["label", 40], ["type", 8]]
+ member_info.update(_split_line(self._get_row(), mem))
+ member_info["modified"] = _parse_date(member_info["modified"])
+ member_info["created"] = _parse_date(member_info["created"])
+ self.member_info = member_info
+
+ # read field names
+ types = {1: "numeric", 2: "char"}
+ fieldcount = int(self._get_row()[54:58])
+ datalength = fieldnamelength * fieldcount
+ # round up to nearest 80
+ if datalength % 80:
+ datalength += 80 - datalength % 80
+ fielddata = self.filepath_or_buffer.read(datalength)
+ fields = []
+ obs_length = 0
+ while len(fielddata) >= fieldnamelength:
+ # pull data for one field
+ fieldbytes, fielddata = (
+ fielddata[:fieldnamelength],
+ fielddata[fieldnamelength:],
+ )
+
+ # rest at end gets ignored, so if field is short, pad out
+ # to match struct pattern below
+ fieldbytes = fieldbytes.ljust(140)
+
+ fieldstruct = struct.unpack(">hhhh8s40s8shhh2s8shhl52s", fieldbytes)
+ field = dict(zip(_fieldkeys, fieldstruct))
+ del field["_"]
+ field["ntype"] = types[field["ntype"]]
+ fl = field["field_length"]
+ if field["ntype"] == "numeric" and ((fl < 2) or (fl > 8)):
+ msg = f"Floating field width {fl} is not between 2 and 8."
+ raise TypeError(msg)
+
+ for k, v in field.items():
+ try:
+ field[k] = v.strip()
+ except AttributeError:
+ pass
+
+ obs_length += field["field_length"]
+ fields += [field]
+
+ header = self._get_row()
+ if not header == _correct_obs_header:
+ raise ValueError("Observation header not found.")
+
+ self.fields = fields
+ self.record_length = obs_length
+ self.record_start = self.filepath_or_buffer.tell()
+
+ self.nobs = self._record_count()
+ self.columns = [x["name"].decode() for x in self.fields]
+
+ # Setup the dtype.
+ dtypel = [
+ ("s" + str(i), "S" + str(field["field_length"]))
+ for i, field in enumerate(self.fields)
+ ]
+ dtype = np.dtype(dtypel)
+ self._dtype = dtype
+
+ def __next__(self) -> pd.DataFrame:
+ return self.read(nrows=self._chunksize or 1)
+
+ def _record_count(self) -> int:
+ """
+ Get number of records in file.
+
+ This is maybe suboptimal because we have to seek to the end of
+ the file.
+
+ Side effect: returns file position to record_start.
+ """
+ self.filepath_or_buffer.seek(0, 2)
+ total_records_length = self.filepath_or_buffer.tell() - self.record_start
+
+ if total_records_length % 80 != 0:
+ warnings.warn(
+ "xport file may be corrupted.",
+ stacklevel=find_stack_level(),
+ )
+
+ if self.record_length > 80:
+ self.filepath_or_buffer.seek(self.record_start)
+ return total_records_length // self.record_length
+
+ self.filepath_or_buffer.seek(-80, 2)
+ last_card_bytes = self.filepath_or_buffer.read(80)
+ last_card = np.frombuffer(last_card_bytes, dtype=np.uint64)
+
+ # 8 byte blank
+ ix = np.flatnonzero(last_card == 2314885530818453536)
+
+ if len(ix) == 0:
+ tail_pad = 0
+ else:
+ tail_pad = 8 * len(ix)
+
+ self.filepath_or_buffer.seek(self.record_start)
+
+ return (total_records_length - tail_pad) // self.record_length
+
+ def get_chunk(self, size: int | None = None) -> pd.DataFrame:
+ """
+ Reads lines from Xport file and returns as dataframe
+
+ Parameters
+ ----------
+ size : int, defaults to None
+ Number of lines to read. If None, reads whole file.
+
+ Returns
+ -------
+ DataFrame
+ """
+ if size is None:
+ size = self._chunksize
+ return self.read(nrows=size)
+
+ def _missing_double(self, vec):
+ v = vec.view(dtype="u1,u1,u2,u4")
+ miss = (v["f1"] == 0) & (v["f2"] == 0) & (v["f3"] == 0)
+ miss1 = (
+ ((v["f0"] >= 0x41) & (v["f0"] <= 0x5A))
+ | (v["f0"] == 0x5F)
+ | (v["f0"] == 0x2E)
+ )
+ miss &= miss1
+ return miss
+
+ @Appender(_read_method_doc)
+ def read(self, nrows: int | None = None) -> pd.DataFrame:
+ if nrows is None:
+ nrows = self.nobs
+
+ read_lines = min(nrows, self.nobs - self._lines_read)
+ read_len = read_lines * self.record_length
+ if read_len <= 0:
+ self.close()
+ raise StopIteration
+ raw = self.filepath_or_buffer.read(read_len)
+ data = np.frombuffer(raw, dtype=self._dtype, count=read_lines)
+
+ df_data = {}
+ for j, x in enumerate(self.columns):
+ vec = data["s" + str(j)]
+ ntype = self.fields[j]["ntype"]
+ if ntype == "numeric":
+ vec = _handle_truncated_float_vec(vec, self.fields[j]["field_length"])
+ miss = self._missing_double(vec)
+ v = _parse_float_vec(vec)
+ v[miss] = np.nan
+ elif self.fields[j]["ntype"] == "char":
+ v = [y.rstrip() for y in vec]
+
+ if self._encoding is not None:
+ v = [y.decode(self._encoding) for y in v]
+
+ df_data.update({x: v})
+ df = pd.DataFrame(df_data)
+
+ if self._index is None:
+ df.index = pd.Index(range(self._lines_read, self._lines_read + read_lines))
+ else:
+ df = df.set_index(self._index)
+
+ self._lines_read += read_lines
+
+ return df
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sasreader.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sasreader.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fdfd214c452c69db615b4eb18e22143a63ee49c
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/io/sas/sasreader.py
@@ -0,0 +1,180 @@
+"""
+Read SAS sas7bdat or xport files.
+"""
+from __future__ import annotations
+
+from typing import (
+ TYPE_CHECKING,
+ Protocol,
+ overload,
+)
+
+from pandas.util._decorators import doc
+
+from pandas.core.shared_docs import _shared_docs
+
+from pandas.io.common import stringify_path
+
+if TYPE_CHECKING:
+ from collections.abc import Hashable
+ from types import TracebackType
+
+ from pandas._typing import (
+ CompressionOptions,
+ FilePath,
+ ReadBuffer,
+ )
+
+ from pandas import DataFrame
+
+
+class ReaderBase(Protocol):
+ """
+ Protocol for XportReader and SAS7BDATReader classes.
+ """
+
+ def read(self, nrows: int | None = None) -> DataFrame:
+ ...
+
+ def close(self) -> None:
+ ...
+
+ def __enter__(self) -> ReaderBase:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ self.close()
+
+
+@overload
+def read_sas(
+ filepath_or_buffer: FilePath | ReadBuffer[bytes],
+ *,
+ format: str | None = ...,
+ index: Hashable | None = ...,
+ encoding: str | None = ...,
+ chunksize: int = ...,
+ iterator: bool = ...,
+ compression: CompressionOptions = ...,
+) -> ReaderBase:
+ ...
+
+
+@overload
+def read_sas(
+ filepath_or_buffer: FilePath | ReadBuffer[bytes],
+ *,
+ format: str | None = ...,
+ index: Hashable | None = ...,
+ encoding: str | None = ...,
+ chunksize: None = ...,
+ iterator: bool = ...,
+ compression: CompressionOptions = ...,
+) -> DataFrame | ReaderBase:
+ ...
+
+
+@doc(decompression_options=_shared_docs["decompression_options"] % "filepath_or_buffer")
+def read_sas(
+ filepath_or_buffer: FilePath | ReadBuffer[bytes],
+ *,
+ format: str | None = None,
+ index: Hashable | None = None,
+ encoding: str | None = None,
+ chunksize: int | None = None,
+ iterator: bool = False,
+ compression: CompressionOptions = "infer",
+) -> DataFrame | ReaderBase:
+ """
+ Read SAS files stored as either XPORT or SAS7BDAT format files.
+
+ Parameters
+ ----------
+ filepath_or_buffer : str, path object, or file-like object
+ String, path object (implementing ``os.PathLike[str]``), or file-like
+ object implementing a binary ``read()`` function. The string could be a URL.
+ Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is
+ expected. A local file could be:
+ ``file://localhost/path/to/table.sas7bdat``.
+ format : str {{'xport', 'sas7bdat'}} or None
+ If None, file format is inferred from file extension. If 'xport' or
+ 'sas7bdat', uses the corresponding format.
+ index : identifier of index column, defaults to None
+ Identifier of column that should be used as index of the DataFrame.
+ encoding : str, default is None
+ Encoding for text data. If None, text data are stored as raw bytes.
+ chunksize : int
+ Read file `chunksize` lines at a time, returns iterator.
+
+ .. versionchanged:: 1.2
+
+ ``TextFileReader`` is a context manager.
+ iterator : bool, defaults to False
+ If True, returns an iterator for reading the file incrementally.
+
+ .. versionchanged:: 1.2
+
+ ``TextFileReader`` is a context manager.
+ {decompression_options}
+
+ Returns
+ -------
+ DataFrame if iterator=False and chunksize=None, else SAS7BDATReader
+ or XportReader
+
+ Examples
+ --------
+ >>> df = pd.read_sas("sas_data.sas7bdat") # doctest: +SKIP
+ """
+ if format is None:
+ buffer_error_msg = (
+ "If this is a buffer object rather "
+ "than a string name, you must specify a format string"
+ )
+ filepath_or_buffer = stringify_path(filepath_or_buffer)
+ if not isinstance(filepath_or_buffer, str):
+ raise ValueError(buffer_error_msg)
+ fname = filepath_or_buffer.lower()
+ if ".xpt" in fname:
+ format = "xport"
+ elif ".sas7bdat" in fname:
+ format = "sas7bdat"
+ else:
+ raise ValueError(
+ f"unable to infer format of SAS file from filename: {repr(fname)}"
+ )
+
+ reader: ReaderBase
+ if format.lower() == "xport":
+ from pandas.io.sas.sas_xport import XportReader
+
+ reader = XportReader(
+ filepath_or_buffer,
+ index=index,
+ encoding=encoding,
+ chunksize=chunksize,
+ compression=compression,
+ )
+ elif format.lower() == "sas7bdat":
+ from pandas.io.sas.sas7bdat import SAS7BDATReader
+
+ reader = SAS7BDATReader(
+ filepath_or_buffer,
+ index=index,
+ encoding=encoding,
+ chunksize=chunksize,
+ compression=compression,
+ )
+ else:
+ raise ValueError("unknown SAS format")
+
+ if iterator or chunksize:
+ return reader
+
+ with reader:
+ return reader.read()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa717b5c36b9cc2fe724d7625e67a75ccfbe7bef
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/__init__.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_aggregation.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_aggregation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..492729f3c1969bd194e864506513932b3dc14cd1
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_aggregation.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_algos.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_algos.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1a947e7791f1c5385cccc60f97e4a7ad52f4345
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_algos.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4fc787eed3a2e880bac86d115399326c2d18d31ee0b7c39e4179de6b68f1adbb
+size 130049
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_common.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_common.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b7ea2c201f7d279d563f91dcd4e493b5d9062f7
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_common.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_downstream.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_downstream.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4030e01306fec1798560bacb89e3eb9ee585341
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_downstream.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_errors.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_errors.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c129a2526a71f4c4337cd9ca41b5a3f68765de2a
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_errors.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_expressions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_expressions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f47b8a6b4609758fc906e36e64f1f22d94ad5c10
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_expressions.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_flags.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_flags.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5bb58601963dbfac7593462afaba04be692acb3d
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_flags.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_multilevel.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_multilevel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..abf1032d37a0f2df059453f142eeaeaf6f2b0804
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_multilevel.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_nanops.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_nanops.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b2816b19d5af034fed8e239f64640d0e66dfc9e3
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_nanops.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_optional_dependency.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_optional_dependency.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bacb25b81ba5d0e05b1abe3b8222ea0de8cc94f0
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_optional_dependency.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c911e0905182f362b345d4cd922256aa0a40c2e1
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_sorting.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_sorting.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1fea99e598a8d5da018775360e2efaedb7c96ad
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_sorting.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_take.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_take.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78f5e6618601993ad64a46fcfdc6d2a2f1b49579
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/__pycache__/test_take.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/api/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/api/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/api/test_api.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/api/test_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..60bcb97aaa3642be064bcacd130edf2084c4a55c
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/api/test_api.py
@@ -0,0 +1,383 @@
+from __future__ import annotations
+
+import pytest
+
+import pandas as pd
+from pandas import api
+import pandas._testing as tm
+from pandas.api import (
+ extensions as api_extensions,
+ indexers as api_indexers,
+ interchange as api_interchange,
+ types as api_types,
+ typing as api_typing,
+)
+
+
+class Base:
+ def check(self, namespace, expected, ignored=None):
+ # see which names are in the namespace, minus optional
+ # ignored ones
+ # compare vs the expected
+
+ result = sorted(
+ f for f in dir(namespace) if not f.startswith("__") and f != "annotations"
+ )
+ if ignored is not None:
+ result = sorted(set(result) - set(ignored))
+
+ expected = sorted(expected)
+ tm.assert_almost_equal(result, expected)
+
+
+class TestPDApi(Base):
+ # these are optionally imported based on testing
+ # & need to be ignored
+ ignored = ["tests", "locale", "conftest", "_version_meson"]
+
+ # top-level sub-packages
+ public_lib = [
+ "api",
+ "arrays",
+ "options",
+ "test",
+ "testing",
+ "errors",
+ "plotting",
+ "io",
+ "tseries",
+ ]
+ private_lib = ["compat", "core", "pandas", "util", "_built_with_meson"]
+
+ # misc
+ misc = ["IndexSlice", "NaT", "NA"]
+
+ # top-level classes
+ classes = [
+ "ArrowDtype",
+ "Categorical",
+ "CategoricalIndex",
+ "DataFrame",
+ "DateOffset",
+ "DatetimeIndex",
+ "ExcelFile",
+ "ExcelWriter",
+ "Flags",
+ "Grouper",
+ "HDFStore",
+ "Index",
+ "MultiIndex",
+ "Period",
+ "PeriodIndex",
+ "RangeIndex",
+ "Series",
+ "SparseDtype",
+ "StringDtype",
+ "Timedelta",
+ "TimedeltaIndex",
+ "Timestamp",
+ "Interval",
+ "IntervalIndex",
+ "CategoricalDtype",
+ "PeriodDtype",
+ "IntervalDtype",
+ "DatetimeTZDtype",
+ "BooleanDtype",
+ "Int8Dtype",
+ "Int16Dtype",
+ "Int32Dtype",
+ "Int64Dtype",
+ "UInt8Dtype",
+ "UInt16Dtype",
+ "UInt32Dtype",
+ "UInt64Dtype",
+ "Float32Dtype",
+ "Float64Dtype",
+ "NamedAgg",
+ ]
+
+ # these are already deprecated; awaiting removal
+ deprecated_classes: list[str] = []
+
+ # external modules exposed in pandas namespace
+ modules: list[str] = []
+
+ # top-level functions
+ funcs = [
+ "array",
+ "bdate_range",
+ "concat",
+ "crosstab",
+ "cut",
+ "date_range",
+ "interval_range",
+ "eval",
+ "factorize",
+ "get_dummies",
+ "from_dummies",
+ "infer_freq",
+ "isna",
+ "isnull",
+ "lreshape",
+ "melt",
+ "notna",
+ "notnull",
+ "offsets",
+ "merge",
+ "merge_ordered",
+ "merge_asof",
+ "period_range",
+ "pivot",
+ "pivot_table",
+ "qcut",
+ "show_versions",
+ "timedelta_range",
+ "unique",
+ "value_counts",
+ "wide_to_long",
+ ]
+
+ # top-level option funcs
+ funcs_option = [
+ "reset_option",
+ "describe_option",
+ "get_option",
+ "option_context",
+ "set_option",
+ "set_eng_float_format",
+ ]
+
+ # top-level read_* funcs
+ funcs_read = [
+ "read_clipboard",
+ "read_csv",
+ "read_excel",
+ "read_fwf",
+ "read_gbq",
+ "read_hdf",
+ "read_html",
+ "read_xml",
+ "read_json",
+ "read_pickle",
+ "read_sas",
+ "read_sql",
+ "read_sql_query",
+ "read_sql_table",
+ "read_stata",
+ "read_table",
+ "read_feather",
+ "read_parquet",
+ "read_orc",
+ "read_spss",
+ ]
+
+ # top-level json funcs
+ funcs_json = ["json_normalize"]
+
+ # top-level to_* funcs
+ funcs_to = ["to_datetime", "to_numeric", "to_pickle", "to_timedelta"]
+
+ # top-level to deprecate in the future
+ deprecated_funcs_in_future: list[str] = []
+
+ # these are already deprecated; awaiting removal
+ deprecated_funcs: list[str] = []
+
+ # private modules in pandas namespace
+ private_modules = [
+ "_config",
+ "_libs",
+ "_is_numpy_dev",
+ "_pandas_datetime_CAPI",
+ "_pandas_parser_CAPI",
+ "_testing",
+ "_typing",
+ ]
+ if not pd._built_with_meson:
+ private_modules.append("_version")
+
+ def test_api(self):
+ checkthese = (
+ self.public_lib
+ + self.private_lib
+ + self.misc
+ + self.modules
+ + self.classes
+ + self.funcs
+ + self.funcs_option
+ + self.funcs_read
+ + self.funcs_json
+ + self.funcs_to
+ + self.private_modules
+ )
+ self.check(namespace=pd, expected=checkthese, ignored=self.ignored)
+
+ def test_api_all(self):
+ expected = set(
+ self.public_lib
+ + self.misc
+ + self.modules
+ + self.classes
+ + self.funcs
+ + self.funcs_option
+ + self.funcs_read
+ + self.funcs_json
+ + self.funcs_to
+ ) - set(self.deprecated_classes)
+ actual = set(pd.__all__)
+
+ extraneous = actual - expected
+ assert not extraneous
+
+ missing = expected - actual
+ assert not missing
+
+ def test_depr(self):
+ deprecated_list = (
+ self.deprecated_classes
+ + self.deprecated_funcs
+ + self.deprecated_funcs_in_future
+ )
+ for depr in deprecated_list:
+ with tm.assert_produces_warning(FutureWarning):
+ _ = getattr(pd, depr)
+
+
+class TestApi(Base):
+ allowed_api_dirs = [
+ "types",
+ "extensions",
+ "indexers",
+ "interchange",
+ "typing",
+ ]
+ allowed_typing = [
+ "DataFrameGroupBy",
+ "DatetimeIndexResamplerGroupby",
+ "Expanding",
+ "ExpandingGroupby",
+ "ExponentialMovingWindow",
+ "ExponentialMovingWindowGroupby",
+ "JsonReader",
+ "NaTType",
+ "NAType",
+ "PeriodIndexResamplerGroupby",
+ "Resampler",
+ "Rolling",
+ "RollingGroupby",
+ "SeriesGroupBy",
+ "StataReader",
+ "TimedeltaIndexResamplerGroupby",
+ "TimeGrouper",
+ "Window",
+ ]
+ allowed_api_types = [
+ "is_any_real_numeric_dtype",
+ "is_array_like",
+ "is_bool",
+ "is_bool_dtype",
+ "is_categorical_dtype",
+ "is_complex",
+ "is_complex_dtype",
+ "is_datetime64_any_dtype",
+ "is_datetime64_dtype",
+ "is_datetime64_ns_dtype",
+ "is_datetime64tz_dtype",
+ "is_dict_like",
+ "is_dtype_equal",
+ "is_extension_array_dtype",
+ "is_file_like",
+ "is_float",
+ "is_float_dtype",
+ "is_hashable",
+ "is_int64_dtype",
+ "is_integer",
+ "is_integer_dtype",
+ "is_interval",
+ "is_interval_dtype",
+ "is_iterator",
+ "is_list_like",
+ "is_named_tuple",
+ "is_number",
+ "is_numeric_dtype",
+ "is_object_dtype",
+ "is_period_dtype",
+ "is_re",
+ "is_re_compilable",
+ "is_scalar",
+ "is_signed_integer_dtype",
+ "is_sparse",
+ "is_string_dtype",
+ "is_timedelta64_dtype",
+ "is_timedelta64_ns_dtype",
+ "is_unsigned_integer_dtype",
+ "pandas_dtype",
+ "infer_dtype",
+ "union_categoricals",
+ "CategoricalDtype",
+ "DatetimeTZDtype",
+ "IntervalDtype",
+ "PeriodDtype",
+ ]
+ allowed_api_interchange = ["from_dataframe", "DataFrame"]
+ allowed_api_indexers = [
+ "check_array_indexer",
+ "BaseIndexer",
+ "FixedForwardWindowIndexer",
+ "VariableOffsetWindowIndexer",
+ ]
+ allowed_api_extensions = [
+ "no_default",
+ "ExtensionDtype",
+ "register_extension_dtype",
+ "register_dataframe_accessor",
+ "register_index_accessor",
+ "register_series_accessor",
+ "take",
+ "ExtensionArray",
+ "ExtensionScalarOpsMixin",
+ ]
+
+ def test_api(self):
+ self.check(api, self.allowed_api_dirs)
+
+ def test_api_typing(self):
+ self.check(api_typing, self.allowed_typing)
+
+ def test_api_types(self):
+ self.check(api_types, self.allowed_api_types)
+
+ def test_api_interchange(self):
+ self.check(api_interchange, self.allowed_api_interchange)
+
+ def test_api_indexers(self):
+ self.check(api_indexers, self.allowed_api_indexers)
+
+ def test_api_extensions(self):
+ self.check(api_extensions, self.allowed_api_extensions)
+
+
+class TestTesting(Base):
+ funcs = [
+ "assert_frame_equal",
+ "assert_series_equal",
+ "assert_index_equal",
+ "assert_extension_array_equal",
+ ]
+
+ def test_testing(self):
+ from pandas import testing
+
+ self.check(testing, self.funcs)
+
+ def test_util_in_top_level(self):
+ with pytest.raises(AttributeError, match="foo"):
+ pd.util.foo
+
+
+def test_pandas_array_alias():
+ msg = "PandasArray has been renamed NumpyExtensionArray"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = pd.arrays.PandasArray
+
+ assert res is pd.arrays.NumpyExtensionArray
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/api/test_types.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/api/test_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbaa6e7e18bcaa9a574b741b5361818f1be01ecf
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/api/test_types.py
@@ -0,0 +1,62 @@
+from __future__ import annotations
+
+import pandas._testing as tm
+from pandas.api import types
+from pandas.tests.api.test_api import Base
+
+
+class TestTypes(Base):
+ allowed = [
+ "is_any_real_numeric_dtype",
+ "is_bool",
+ "is_bool_dtype",
+ "is_categorical_dtype",
+ "is_complex",
+ "is_complex_dtype",
+ "is_datetime64_any_dtype",
+ "is_datetime64_dtype",
+ "is_datetime64_ns_dtype",
+ "is_datetime64tz_dtype",
+ "is_dtype_equal",
+ "is_float",
+ "is_float_dtype",
+ "is_int64_dtype",
+ "is_integer",
+ "is_integer_dtype",
+ "is_number",
+ "is_numeric_dtype",
+ "is_object_dtype",
+ "is_scalar",
+ "is_sparse",
+ "is_string_dtype",
+ "is_signed_integer_dtype",
+ "is_timedelta64_dtype",
+ "is_timedelta64_ns_dtype",
+ "is_unsigned_integer_dtype",
+ "is_period_dtype",
+ "is_interval",
+ "is_interval_dtype",
+ "is_re",
+ "is_re_compilable",
+ "is_dict_like",
+ "is_iterator",
+ "is_file_like",
+ "is_list_like",
+ "is_hashable",
+ "is_array_like",
+ "is_named_tuple",
+ "pandas_dtype",
+ "union_categoricals",
+ "infer_dtype",
+ "is_extension_array_dtype",
+ ]
+ deprecated: list[str] = []
+ dtypes = ["CategoricalDtype", "DatetimeTZDtype", "PeriodDtype", "IntervalDtype"]
+
+ def test_types(self):
+ self.check(types, self.allowed + self.dtypes + self.deprecated)
+
+ def test_deprecated_from_api_types(self):
+ for t in self.deprecated:
+ with tm.assert_produces_warning(FutureWarning):
+ getattr(types, t)(1)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4d153df54059ca2a82f336e19afb4297eb218a2
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/common.py
@@ -0,0 +1,7 @@
+from pandas.core.groupby.base import transformation_kernels
+
+# There is no Series.cumcount or DataFrame.cumcount
+series_transform_kernels = [
+ x for x in sorted(transformation_kernels) if x != "cumcount"
+]
+frame_transform_kernels = [x for x in sorted(transformation_kernels) if x != "cumcount"]
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..b68c6235cb0b8e219ff73619a079ea227b932482
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/conftest.py
@@ -0,0 +1,18 @@
+import numpy as np
+import pytest
+
+from pandas import DataFrame
+
+
+@pytest.fixture
+def int_frame_const_col():
+ """
+ Fixture for DataFrame of ints which are constant per column
+
+ Columns are ['A', 'B', 'C'], with values (per column): [1, 2, 3]
+ """
+ df = DataFrame(
+ np.tile(np.arange(3, dtype="int64"), 6).reshape(6, -1) + 1,
+ columns=["A", "B", "C"],
+ )
+ return df
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_frame_apply.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_frame_apply.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a3f73a68374bf96960b5cc8125dcd7effc4d147
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_frame_apply.py
@@ -0,0 +1,1634 @@
+from datetime import datetime
+import warnings
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.dtypes import CategoricalDtype
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.tests.frame.common import zip_frames
+
+
+def test_apply(float_frame):
+ with np.errstate(all="ignore"):
+ # ufunc
+ result = np.sqrt(float_frame["A"])
+ expected = float_frame.apply(np.sqrt)["A"]
+ tm.assert_series_equal(result, expected)
+
+ # aggregator
+ result = float_frame.apply(np.mean)["A"]
+ expected = np.mean(float_frame["A"])
+ assert result == expected
+
+ d = float_frame.index[0]
+ result = float_frame.apply(np.mean, axis=1)
+ expected = np.mean(float_frame.xs(d))
+ assert result[d] == expected
+ assert result.index is float_frame.index
+
+
+@pytest.mark.parametrize("axis", [0, 1])
+def test_apply_args(float_frame, axis):
+ result = float_frame.apply(lambda x, y: x + y, axis, args=(1,))
+ expected = float_frame + 1
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_categorical_func():
+ # GH 9573
+ df = DataFrame({"c0": ["A", "A", "B", "B"], "c1": ["C", "C", "D", "D"]})
+ result = df.apply(lambda ts: ts.astype("category"))
+
+ assert result.shape == (4, 2)
+ assert isinstance(result["c0"].dtype, CategoricalDtype)
+ assert isinstance(result["c1"].dtype, CategoricalDtype)
+
+
+def test_apply_axis1_with_ea():
+ # GH#36785
+ expected = DataFrame({"A": [Timestamp("2013-01-01", tz="UTC")]})
+ result = expected.apply(lambda x: x, axis=1)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, dtype",
+ [(1, None), (1, CategoricalDtype([1])), (Timestamp("2013-01-01", tz="UTC"), None)],
+)
+def test_agg_axis1_duplicate_index(data, dtype):
+ # GH 42380
+ expected = DataFrame([[data], [data]], index=["a", "a"], dtype=dtype)
+ result = expected.agg(lambda x: x, axis=1)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_mixed_datetimelike():
+ # mixed datetimelike
+ # GH 7778
+ expected = DataFrame(
+ {
+ "A": date_range("20130101", periods=3),
+ "B": pd.to_timedelta(np.arange(3), unit="s"),
+ }
+ )
+ result = expected.apply(lambda x: x, axis=1)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", [np.sqrt, np.mean])
+def test_apply_empty(func):
+ # empty
+ empty_frame = DataFrame()
+
+ result = empty_frame.apply(func)
+ assert result.empty
+
+
+def test_apply_float_frame(float_frame):
+ no_rows = float_frame[:0]
+ result = no_rows.apply(lambda x: x.mean())
+ expected = Series(np.nan, index=float_frame.columns)
+ tm.assert_series_equal(result, expected)
+
+ no_cols = float_frame.loc[:, []]
+ result = no_cols.apply(lambda x: x.mean(), axis=1)
+ expected = Series(np.nan, index=float_frame.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_empty_except_index():
+ # GH 2476
+ expected = DataFrame(index=["a"])
+ result = expected.apply(lambda x: x["a"], axis=1)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_with_reduce_empty():
+ # reduce with an empty DataFrame
+ empty_frame = DataFrame()
+
+ x = []
+ result = empty_frame.apply(x.append, axis=1, result_type="expand")
+ tm.assert_frame_equal(result, empty_frame)
+ result = empty_frame.apply(x.append, axis=1, result_type="reduce")
+ expected = Series([], dtype=np.float64)
+ tm.assert_series_equal(result, expected)
+
+ empty_with_cols = DataFrame(columns=["a", "b", "c"])
+ result = empty_with_cols.apply(x.append, axis=1, result_type="expand")
+ tm.assert_frame_equal(result, empty_with_cols)
+ result = empty_with_cols.apply(x.append, axis=1, result_type="reduce")
+ expected = Series([], dtype=np.float64)
+ tm.assert_series_equal(result, expected)
+
+ # Ensure that x.append hasn't been called
+ assert x == []
+
+
+@pytest.mark.parametrize("func", ["sum", "prod", "any", "all"])
+def test_apply_funcs_over_empty(func):
+ # GH 28213
+ df = DataFrame(columns=["a", "b", "c"])
+
+ result = df.apply(getattr(np, func))
+ expected = getattr(df, func)()
+ if func in ("sum", "prod"):
+ expected = expected.astype(float)
+ tm.assert_series_equal(result, expected)
+
+
+def test_nunique_empty():
+ # GH 28213
+ df = DataFrame(columns=["a", "b", "c"])
+
+ result = df.nunique()
+ expected = Series(0, index=df.columns)
+ tm.assert_series_equal(result, expected)
+
+ result = df.T.nunique()
+ expected = Series([], dtype=np.float64)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_standard_nonunique():
+ df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=["a", "a", "c"])
+
+ result = df.apply(lambda s: s[0], axis=1)
+ expected = Series([1, 4, 7], ["a", "a", "c"])
+ tm.assert_series_equal(result, expected)
+
+ result = df.T.apply(lambda s: s[0], axis=0)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_broadcast_scalars(float_frame):
+ # scalars
+ result = float_frame.apply(np.mean, result_type="broadcast")
+ expected = DataFrame([float_frame.mean()], index=float_frame.index)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_broadcast_scalars_axis1(float_frame):
+ result = float_frame.apply(np.mean, axis=1, result_type="broadcast")
+ m = float_frame.mean(axis=1)
+ expected = DataFrame({c: m for c in float_frame.columns})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_broadcast_lists_columns(float_frame):
+ # lists
+ result = float_frame.apply(
+ lambda x: list(range(len(float_frame.columns))),
+ axis=1,
+ result_type="broadcast",
+ )
+ m = list(range(len(float_frame.columns)))
+ expected = DataFrame(
+ [m] * len(float_frame.index),
+ dtype="float64",
+ index=float_frame.index,
+ columns=float_frame.columns,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_broadcast_lists_index(float_frame):
+ result = float_frame.apply(
+ lambda x: list(range(len(float_frame.index))), result_type="broadcast"
+ )
+ m = list(range(len(float_frame.index)))
+ expected = DataFrame(
+ {c: m for c in float_frame.columns},
+ dtype="float64",
+ index=float_frame.index,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_broadcast_list_lambda_func(int_frame_const_col):
+ # preserve columns
+ df = int_frame_const_col
+ result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="broadcast")
+ tm.assert_frame_equal(result, df)
+
+
+def test_apply_broadcast_series_lambda_func(int_frame_const_col):
+ df = int_frame_const_col
+ result = df.apply(
+ lambda x: Series([1, 2, 3], index=list("abc")),
+ axis=1,
+ result_type="broadcast",
+ )
+ expected = df.copy()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("axis", [0, 1])
+def test_apply_raw_float_frame(float_frame, axis):
+ def _assert_raw(x):
+ assert isinstance(x, np.ndarray)
+ assert x.ndim == 1
+
+ float_frame.apply(_assert_raw, axis=axis, raw=True)
+
+
+@pytest.mark.parametrize("axis", [0, 1])
+def test_apply_raw_float_frame_lambda(float_frame, axis):
+ result = float_frame.apply(np.mean, axis=axis, raw=True)
+ expected = float_frame.apply(lambda x: x.values.mean(), axis=axis)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_raw_float_frame_no_reduction(float_frame):
+ # no reduction
+ result = float_frame.apply(lambda x: x * 2, raw=True)
+ expected = float_frame * 2
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("axis", [0, 1])
+def test_apply_raw_mixed_type_frame(mixed_type_frame, axis):
+ def _assert_raw(x):
+ assert isinstance(x, np.ndarray)
+ assert x.ndim == 1
+
+ # Mixed dtype (GH-32423)
+ mixed_type_frame.apply(_assert_raw, axis=axis, raw=True)
+
+
+def test_apply_axis1(float_frame):
+ d = float_frame.index[0]
+ result = float_frame.apply(np.mean, axis=1)[d]
+ expected = np.mean(float_frame.xs(d))
+ assert result == expected
+
+
+def test_apply_mixed_dtype_corner():
+ df = DataFrame({"A": ["foo"], "B": [1.0]})
+ result = df[:0].apply(np.mean, axis=1)
+ # the result here is actually kind of ambiguous, should it be a Series
+ # or a DataFrame?
+ expected = Series(np.nan, index=pd.Index([], dtype="int64"))
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_mixed_dtype_corner_indexing():
+ df = DataFrame({"A": ["foo"], "B": [1.0]})
+ result = df.apply(lambda x: x["A"], axis=1)
+ expected = Series(["foo"], index=[0])
+ tm.assert_series_equal(result, expected)
+
+ result = df.apply(lambda x: x["B"], axis=1)
+ expected = Series([1.0], index=[0])
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.filterwarnings("ignore::RuntimeWarning")
+@pytest.mark.parametrize("ax", ["index", "columns"])
+@pytest.mark.parametrize(
+ "func", [lambda x: x, lambda x: x.mean()], ids=["identity", "mean"]
+)
+@pytest.mark.parametrize("raw", [True, False])
+@pytest.mark.parametrize("axis", [0, 1])
+def test_apply_empty_infer_type(ax, func, raw, axis):
+ df = DataFrame(**{ax: ["a", "b", "c"]})
+
+ with np.errstate(all="ignore"):
+ test_res = func(np.array([], dtype="f8"))
+ is_reduction = not isinstance(test_res, np.ndarray)
+
+ result = df.apply(func, axis=axis, raw=raw)
+ if is_reduction:
+ agg_axis = df._get_agg_axis(axis)
+ assert isinstance(result, Series)
+ assert result.index is agg_axis
+ else:
+ assert isinstance(result, DataFrame)
+
+
+def test_apply_empty_infer_type_broadcast():
+ no_cols = DataFrame(index=["a", "b", "c"])
+ result = no_cols.apply(lambda x: x.mean(), result_type="broadcast")
+ assert isinstance(result, DataFrame)
+
+
+def test_apply_with_args_kwds_add_some(float_frame):
+ def add_some(x, howmuch=0):
+ return x + howmuch
+
+ result = float_frame.apply(add_some, howmuch=2)
+ expected = float_frame.apply(lambda x: x + 2)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_with_args_kwds_agg_and_add(float_frame):
+ def agg_and_add(x, howmuch=0):
+ return x.mean() + howmuch
+
+ result = float_frame.apply(agg_and_add, howmuch=2)
+ expected = float_frame.apply(lambda x: x.mean() + 2)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_with_args_kwds_subtract_and_divide(float_frame):
+ def subtract_and_divide(x, sub, divide=1):
+ return (x - sub) / divide
+
+ result = float_frame.apply(subtract_and_divide, args=(2,), divide=2)
+ expected = float_frame.apply(lambda x: (x - 2.0) / 2.0)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_yield_list(float_frame):
+ result = float_frame.apply(list)
+ tm.assert_frame_equal(result, float_frame)
+
+
+def test_apply_reduce_Series(float_frame):
+ float_frame.iloc[::2, float_frame.columns.get_loc("A")] = np.nan
+ expected = float_frame.mean(1)
+ result = float_frame.apply(np.mean, axis=1)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_reduce_to_dict():
+ # GH 25196 37544
+ data = DataFrame([[1, 2], [3, 4]], columns=["c0", "c1"], index=["i0", "i1"])
+
+ result = data.apply(dict, axis=0)
+ expected = Series([{"i0": 1, "i1": 3}, {"i0": 2, "i1": 4}], index=data.columns)
+ tm.assert_series_equal(result, expected)
+
+ result = data.apply(dict, axis=1)
+ expected = Series([{"c0": 1, "c1": 2}, {"c0": 3, "c1": 4}], index=data.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_differently_indexed():
+ df = DataFrame(np.random.default_rng(2).standard_normal((20, 10)))
+
+ result = df.apply(Series.describe, axis=0)
+ expected = DataFrame({i: v.describe() for i, v in df.items()}, columns=df.columns)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.apply(Series.describe, axis=1)
+ expected = DataFrame({i: v.describe() for i, v in df.T.items()}, columns=df.index).T
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_bug():
+ # GH 6125
+ positions = DataFrame(
+ [
+ [1, "ABC0", 50],
+ [1, "YUM0", 20],
+ [1, "DEF0", 20],
+ [2, "ABC1", 50],
+ [2, "YUM1", 20],
+ [2, "DEF1", 20],
+ ],
+ columns=["a", "market", "position"],
+ )
+
+ def f(r):
+ return r["market"]
+
+ expected = positions.apply(f, axis=1)
+
+ positions = DataFrame(
+ [
+ [datetime(2013, 1, 1), "ABC0", 50],
+ [datetime(2013, 1, 2), "YUM0", 20],
+ [datetime(2013, 1, 3), "DEF0", 20],
+ [datetime(2013, 1, 4), "ABC1", 50],
+ [datetime(2013, 1, 5), "YUM1", 20],
+ [datetime(2013, 1, 6), "DEF1", 20],
+ ],
+ columns=["a", "market", "position"],
+ )
+ result = positions.apply(f, axis=1)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_convert_objects():
+ expected = DataFrame(
+ {
+ "A": [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ "foo",
+ "foo",
+ "foo",
+ ],
+ "B": [
+ "one",
+ "one",
+ "one",
+ "two",
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "two",
+ "one",
+ ],
+ "C": [
+ "dull",
+ "dull",
+ "shiny",
+ "dull",
+ "dull",
+ "shiny",
+ "shiny",
+ "dull",
+ "shiny",
+ "shiny",
+ "shiny",
+ ],
+ "D": np.random.default_rng(2).standard_normal(11),
+ "E": np.random.default_rng(2).standard_normal(11),
+ "F": np.random.default_rng(2).standard_normal(11),
+ }
+ )
+
+ result = expected.apply(lambda x: x, axis=1)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_attach_name(float_frame):
+ result = float_frame.apply(lambda x: x.name)
+ expected = Series(float_frame.columns, index=float_frame.columns)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_attach_name_axis1(float_frame):
+ result = float_frame.apply(lambda x: x.name, axis=1)
+ expected = Series(float_frame.index, index=float_frame.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_attach_name_non_reduction(float_frame):
+ # non-reductions
+ result = float_frame.apply(lambda x: np.repeat(x.name, len(x)))
+ expected = DataFrame(
+ np.tile(float_frame.columns, (len(float_frame.index), 1)),
+ index=float_frame.index,
+ columns=float_frame.columns,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_attach_name_non_reduction_axis1(float_frame):
+ result = float_frame.apply(lambda x: np.repeat(x.name, len(x)), axis=1)
+ expected = Series(
+ np.repeat(t[0], len(float_frame.columns)) for t in float_frame.itertuples()
+ )
+ expected.index = float_frame.index
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_multi_index():
+ index = MultiIndex.from_arrays([["a", "a", "b"], ["c", "d", "d"]])
+ s = DataFrame([[1, 2], [3, 4], [5, 6]], index=index, columns=["col1", "col2"])
+ result = s.apply(lambda x: Series({"min": min(x), "max": max(x)}), 1)
+ expected = DataFrame([[1, 2], [3, 4], [5, 6]], index=index, columns=["min", "max"])
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+
+@pytest.mark.parametrize(
+ "df, dicts",
+ [
+ [
+ DataFrame([["foo", "bar"], ["spam", "eggs"]]),
+ Series([{0: "foo", 1: "spam"}, {0: "bar", 1: "eggs"}]),
+ ],
+ [DataFrame([[0, 1], [2, 3]]), Series([{0: 0, 1: 2}, {0: 1, 1: 3}])],
+ ],
+)
+def test_apply_dict(df, dicts):
+ # GH 8735
+ fn = lambda x: x.to_dict()
+ reduce_true = df.apply(fn, result_type="reduce")
+ reduce_false = df.apply(fn, result_type="expand")
+ reduce_none = df.apply(fn)
+
+ tm.assert_series_equal(reduce_true, dicts)
+ tm.assert_frame_equal(reduce_false, df)
+ tm.assert_series_equal(reduce_none, dicts)
+
+
+def test_apply_non_numpy_dtype():
+ # GH 12244
+ df = DataFrame({"dt": date_range("2015-01-01", periods=3, tz="Europe/Brussels")})
+ result = df.apply(lambda x: x)
+ tm.assert_frame_equal(result, df)
+
+ result = df.apply(lambda x: x + pd.Timedelta("1day"))
+ expected = DataFrame(
+ {"dt": date_range("2015-01-02", periods=3, tz="Europe/Brussels")}
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_non_numpy_dtype_category():
+ df = DataFrame({"dt": ["a", "b", "c", "a"]}, dtype="category")
+ result = df.apply(lambda x: x)
+ tm.assert_frame_equal(result, df)
+
+
+def test_apply_dup_names_multi_agg():
+ # GH 21063
+ df = DataFrame([[0, 1], [2, 3]], columns=["a", "a"])
+ expected = DataFrame([[0, 1]], columns=["a", "a"], index=["min"])
+ result = df.agg(["min"])
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("op", ["apply", "agg"])
+def test_apply_nested_result_axis_1(op):
+ # GH 13820
+ def apply_list(row):
+ return [2 * row["A"], 2 * row["C"], 2 * row["B"]]
+
+ df = DataFrame(np.zeros((4, 4)), columns=list("ABCD"))
+ result = getattr(df, op)(apply_list, axis=1)
+ expected = Series(
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_noreduction_tzaware_object():
+ # https://github.com/pandas-dev/pandas/issues/31505
+ expected = DataFrame(
+ {"foo": [Timestamp("2020", tz="UTC")]}, dtype="datetime64[ns, UTC]"
+ )
+ result = expected.apply(lambda x: x)
+ tm.assert_frame_equal(result, expected)
+ result = expected.apply(lambda x: x.copy())
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_function_runs_once():
+ # https://github.com/pandas-dev/pandas/issues/30815
+
+ df = DataFrame({"a": [1, 2, 3]})
+ names = [] # Save row names function is applied to
+
+ def reducing_function(row):
+ names.append(row.name)
+
+ def non_reducing_function(row):
+ names.append(row.name)
+ return row
+
+ for func in [reducing_function, non_reducing_function]:
+ del names[:]
+
+ df.apply(func, axis=1)
+ assert names == list(df.index)
+
+
+def test_apply_raw_function_runs_once():
+ # https://github.com/pandas-dev/pandas/issues/34506
+
+ df = DataFrame({"a": [1, 2, 3]})
+ values = [] # Save row values function is applied to
+
+ def reducing_function(row):
+ values.extend(row)
+
+ def non_reducing_function(row):
+ values.extend(row)
+ return row
+
+ for func in [reducing_function, non_reducing_function]:
+ del values[:]
+
+ df.apply(func, raw=True, axis=1)
+ assert values == list(df.a.to_list())
+
+
+def test_apply_with_byte_string():
+ # GH 34529
+ df = DataFrame(np.array([b"abcd", b"efgh"]), columns=["col"])
+ expected = DataFrame(np.array([b"abcd", b"efgh"]), columns=["col"], dtype=object)
+ # After we make the apply we expect a dataframe just
+ # like the original but with the object datatype
+ result = df.apply(lambda x: x.astype("object"))
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("val", ["asd", 12, None, np.nan])
+def test_apply_category_equalness(val):
+ # Check if categorical comparisons on apply, GH 21239
+ df_values = ["asd", None, 12, "asd", "cde", np.nan]
+ df = DataFrame({"a": df_values}, dtype="category")
+
+ result = df.a.apply(lambda x: x == val)
+ expected = Series(
+ [np.nan if pd.isnull(x) else x == val for x in df_values], name="a"
+ )
+ tm.assert_series_equal(result, expected)
+
+
+# the user has supplied an opaque UDF where
+# they are transforming the input that requires
+# us to infer the output
+
+
+def test_infer_row_shape():
+ # GH 17437
+ # if row shape is changing, infer it
+ df = DataFrame(np.random.default_rng(2).random((10, 2)))
+ result = df.apply(np.fft.fft, axis=0).shape
+ assert result == (10, 2)
+
+ result = df.apply(np.fft.rfft, axis=0).shape
+ assert result == (6, 2)
+
+
+@pytest.mark.parametrize(
+ "ops, by_row, expected",
+ [
+ ({"a": lambda x: x + 1}, "compat", DataFrame({"a": [2, 3]})),
+ ({"a": lambda x: x + 1}, False, DataFrame({"a": [2, 3]})),
+ ({"a": lambda x: x.sum()}, "compat", Series({"a": 3})),
+ ({"a": lambda x: x.sum()}, False, Series({"a": 3})),
+ (
+ {"a": ["sum", np.sum, lambda x: x.sum()]},
+ "compat",
+ DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", ""]),
+ ),
+ (
+ {"a": ["sum", np.sum, lambda x: x.sum()]},
+ False,
+ DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", ""]),
+ ),
+ ({"a": lambda x: 1}, "compat", DataFrame({"a": [1, 1]})),
+ ({"a": lambda x: 1}, False, Series({"a": 1})),
+ ],
+)
+def test_dictlike_lambda(ops, by_row, expected):
+ # GH53601
+ df = DataFrame({"a": [1, 2]})
+ result = df.apply(ops, by_row=by_row)
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops",
+ [
+ {"a": lambda x: x + 1},
+ {"a": lambda x: x.sum()},
+ {"a": ["sum", np.sum, lambda x: x.sum()]},
+ {"a": lambda x: 1},
+ ],
+)
+def test_dictlike_lambda_raises(ops):
+ # GH53601
+ df = DataFrame({"a": [1, 2]})
+ with pytest.raises(ValueError, match="by_row=True not allowed"):
+ df.apply(ops, by_row=True)
+
+
+def test_with_dictlike_columns():
+ # GH 17602
+ df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"])
+ result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1)
+ expected = Series([{"s": 3} for t in df.itertuples()])
+ tm.assert_series_equal(result, expected)
+
+ df["tm"] = [
+ Timestamp("2017-05-01 00:00:00"),
+ Timestamp("2017-05-02 00:00:00"),
+ ]
+ result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1)
+ tm.assert_series_equal(result, expected)
+
+ # compose a series
+ result = (df["a"] + df["b"]).apply(lambda x: {"s": x})
+ expected = Series([{"s": 3}, {"s": 3}])
+ tm.assert_series_equal(result, expected)
+
+
+def test_with_dictlike_columns_with_datetime():
+ # GH 18775
+ df = DataFrame()
+ df["author"] = ["X", "Y", "Z"]
+ df["publisher"] = ["BBC", "NBC", "N24"]
+ df["date"] = pd.to_datetime(
+ ["17-10-2010 07:15:30", "13-05-2011 08:20:35", "15-01-2013 09:09:09"],
+ dayfirst=True,
+ )
+ result = df.apply(lambda x: {}, axis=1)
+ expected = Series([{}, {}, {}])
+ tm.assert_series_equal(result, expected)
+
+
+def test_with_dictlike_columns_with_infer():
+ # GH 17602
+ df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"])
+ result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1, result_type="expand")
+ expected = DataFrame({"s": [3, 3]})
+ tm.assert_frame_equal(result, expected)
+
+ df["tm"] = [
+ Timestamp("2017-05-01 00:00:00"),
+ Timestamp("2017-05-02 00:00:00"),
+ ]
+ result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1, result_type="expand")
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops, by_row, expected",
+ [
+ ([lambda x: x + 1], "compat", DataFrame({("a", ""): [2, 3]})),
+ ([lambda x: x + 1], False, DataFrame({("a", ""): [2, 3]})),
+ ([lambda x: x.sum()], "compat", DataFrame({"a": [3]}, index=[""])),
+ ([lambda x: x.sum()], False, DataFrame({"a": [3]}, index=[""])),
+ (
+ ["sum", np.sum, lambda x: x.sum()],
+ "compat",
+ DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", ""]),
+ ),
+ (
+ ["sum", np.sum, lambda x: x.sum()],
+ False,
+ DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", ""]),
+ ),
+ (
+ [lambda x: x + 1, lambda x: 3],
+ "compat",
+ DataFrame([[2, 3], [3, 3]], columns=[["a", "a"], ["", ""]]),
+ ),
+ (
+ [lambda x: 2, lambda x: 3],
+ False,
+ DataFrame({"a": [2, 3]}, ["", ""]),
+ ),
+ ],
+)
+def test_listlike_lambda(ops, by_row, expected):
+ # GH53601
+ df = DataFrame({"a": [1, 2]})
+ result = df.apply(ops, by_row=by_row)
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops",
+ [
+ [lambda x: x + 1],
+ [lambda x: x.sum()],
+ ["sum", np.sum, lambda x: x.sum()],
+ [lambda x: x + 1, lambda x: 3],
+ ],
+)
+def test_listlike_lambda_raises(ops):
+ # GH53601
+ df = DataFrame({"a": [1, 2]})
+ with pytest.raises(ValueError, match="by_row=True not allowed"):
+ df.apply(ops, by_row=True)
+
+
+def test_with_listlike_columns():
+ # GH 17348
+ df = DataFrame(
+ {
+ "a": Series(np.random.default_rng(2).standard_normal(4)),
+ "b": ["a", "list", "of", "words"],
+ "ts": date_range("2016-10-01", periods=4, freq="H"),
+ }
+ )
+
+ result = df[["a", "b"]].apply(tuple, axis=1)
+ expected = Series([t[1:] for t in df[["a", "b"]].itertuples()])
+ tm.assert_series_equal(result, expected)
+
+ result = df[["a", "ts"]].apply(tuple, axis=1)
+ expected = Series([t[1:] for t in df[["a", "ts"]].itertuples()])
+ tm.assert_series_equal(result, expected)
+
+
+def test_with_listlike_columns_returning_list():
+ # GH 18919
+ df = DataFrame({"x": Series([["a", "b"], ["q"]]), "y": Series([["z"], ["q", "t"]])})
+ df.index = MultiIndex.from_tuples([("i0", "j0"), ("i1", "j1")])
+
+ result = df.apply(lambda row: [el for el in row["x"] if el in row["y"]], axis=1)
+ expected = Series([[], ["q"]], index=df.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_infer_output_shape_columns():
+ # GH 18573
+
+ df = DataFrame(
+ {
+ "number": [1.0, 2.0],
+ "string": ["foo", "bar"],
+ "datetime": [
+ Timestamp("2017-11-29 03:30:00"),
+ Timestamp("2017-11-29 03:45:00"),
+ ],
+ }
+ )
+ result = df.apply(lambda row: (row.number, row.string), axis=1)
+ expected = Series([(t.number, t.string) for t in df.itertuples()])
+ tm.assert_series_equal(result, expected)
+
+
+def test_infer_output_shape_listlike_columns():
+ # GH 16353
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 3)), columns=["A", "B", "C"]
+ )
+
+ result = df.apply(lambda x: [1, 2, 3], axis=1)
+ expected = Series([[1, 2, 3] for t in df.itertuples()])
+ tm.assert_series_equal(result, expected)
+
+ result = df.apply(lambda x: [1, 2], axis=1)
+ expected = Series([[1, 2] for t in df.itertuples()])
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("val", [1, 2])
+def test_infer_output_shape_listlike_columns_np_func(val):
+ # GH 17970
+ df = DataFrame({"a": [1, 2, 3]}, index=list("abc"))
+
+ result = df.apply(lambda row: np.ones(val), axis=1)
+ expected = Series([np.ones(val) for t in df.itertuples()], index=df.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_infer_output_shape_listlike_columns_with_timestamp():
+ # GH 17892
+ df = DataFrame(
+ {
+ "a": [
+ Timestamp("2010-02-01"),
+ Timestamp("2010-02-04"),
+ Timestamp("2010-02-05"),
+ Timestamp("2010-02-06"),
+ ],
+ "b": [9, 5, 4, 3],
+ "c": [5, 3, 4, 2],
+ "d": [1, 2, 3, 4],
+ }
+ )
+
+ def fun(x):
+ return (1, 2)
+
+ result = df.apply(fun, axis=1)
+ expected = Series([(1, 2) for t in df.itertuples()])
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("lst", [[1, 2, 3], [1, 2]])
+def test_consistent_coerce_for_shapes(lst):
+ # we want column names to NOT be propagated
+ # just because the shape matches the input shape
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 3)), columns=["A", "B", "C"]
+ )
+
+ result = df.apply(lambda x: lst, axis=1)
+ expected = Series([lst for t in df.itertuples()])
+ tm.assert_series_equal(result, expected)
+
+
+def test_consistent_names(int_frame_const_col):
+ # if a Series is returned, we should use the resulting index names
+ df = int_frame_const_col
+
+ result = df.apply(
+ lambda x: Series([1, 2, 3], index=["test", "other", "cols"]), axis=1
+ )
+ expected = int_frame_const_col.rename(
+ columns={"A": "test", "B": "other", "C": "cols"}
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.apply(lambda x: Series([1, 2], index=["test", "other"]), axis=1)
+ expected = expected[["test", "other"]]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_result_type(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
+
+ result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="expand")
+ expected = df.copy()
+ expected.columns = [0, 1, 2]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_result_type_shorter_list(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
+ result = df.apply(lambda x: [1, 2], axis=1, result_type="expand")
+ expected = df[["A", "B"]].copy()
+ expected.columns = [0, 1]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_result_type_broadcast(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
+ # broadcast result
+ result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="broadcast")
+ expected = df.copy()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_result_type_broadcast_series_func(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
+ columns = ["other", "col", "names"]
+ result = df.apply(
+ lambda x: Series([1, 2, 3], index=columns), axis=1, result_type="broadcast"
+ )
+ expected = df.copy()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_result_type_series_result(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
+ # series result
+ result = df.apply(lambda x: Series([1, 2, 3], index=x.index), axis=1)
+ expected = df.copy()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_result_type_series_result_other_index(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
+ # series result with other index
+ columns = ["other", "col", "names"]
+ result = df.apply(lambda x: Series([1, 2, 3], index=columns), axis=1)
+ expected = df.copy()
+ expected.columns = columns
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "box",
+ [lambda x: list(x), lambda x: tuple(x), lambda x: np.array(x, dtype="int64")],
+ ids=["list", "tuple", "array"],
+)
+def test_consistency_for_boxed(box, int_frame_const_col):
+ # passing an array or list should not affect the output shape
+ df = int_frame_const_col
+
+ result = df.apply(lambda x: box([1, 2]), axis=1)
+ expected = Series([box([1, 2]) for t in df.itertuples()])
+ tm.assert_series_equal(result, expected)
+
+ result = df.apply(lambda x: box([1, 2]), axis=1, result_type="expand")
+ expected = int_frame_const_col[["A", "B"]].rename(columns={"A": 0, "B": 1})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_agg_transform(axis, float_frame):
+ other_axis = 1 if axis in {0, "index"} else 0
+
+ with np.errstate(all="ignore"):
+ f_abs = np.abs(float_frame)
+ f_sqrt = np.sqrt(float_frame)
+
+ # ufunc
+ expected = f_sqrt.copy()
+ result = float_frame.apply(np.sqrt, axis=axis)
+ tm.assert_frame_equal(result, expected)
+
+ # list-like
+ result = float_frame.apply([np.sqrt], axis=axis)
+ expected = f_sqrt.copy()
+ if axis in {0, "index"}:
+ expected.columns = MultiIndex.from_product([float_frame.columns, ["sqrt"]])
+ else:
+ expected.index = MultiIndex.from_product([float_frame.index, ["sqrt"]])
+ tm.assert_frame_equal(result, expected)
+
+ # multiple items in list
+ # these are in the order as if we are applying both
+ # functions per series and then concatting
+ result = float_frame.apply([np.abs, np.sqrt], axis=axis)
+ expected = zip_frames([f_abs, f_sqrt], axis=other_axis)
+ if axis in {0, "index"}:
+ expected.columns = MultiIndex.from_product(
+ [float_frame.columns, ["absolute", "sqrt"]]
+ )
+ else:
+ expected.index = MultiIndex.from_product(
+ [float_frame.index, ["absolute", "sqrt"]]
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_demo():
+ # demonstration tests
+ df = DataFrame({"A": range(5), "B": 5})
+
+ result = df.agg(["min", "max"])
+ expected = DataFrame(
+ {"A": [0, 4], "B": [5, 5]}, columns=["A", "B"], index=["min", "max"]
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_demo_dict_agg():
+ # demonstration tests
+ df = DataFrame({"A": range(5), "B": 5})
+ result = df.agg({"A": ["min", "max"], "B": ["sum", "max"]})
+ expected = DataFrame(
+ {"A": [4.0, 0.0, np.nan], "B": [5.0, np.nan, 25.0]},
+ columns=["A", "B"],
+ index=["max", "min", "sum"],
+ )
+ tm.assert_frame_equal(result.reindex_like(expected), expected)
+
+
+def test_agg_with_name_as_column_name():
+ # GH 36212 - Column name is "name"
+ data = {"name": ["foo", "bar"]}
+ df = DataFrame(data)
+
+ # result's name should be None
+ result = df.agg({"name": "count"})
+ expected = Series({"name": 2})
+ tm.assert_series_equal(result, expected)
+
+ # Check if name is still preserved when aggregating series instead
+ result = df["name"].agg({"name": "count"})
+ expected = Series({"name": 2}, name="name")
+ tm.assert_series_equal(result, expected)
+
+
+def test_agg_multiple_mixed():
+ # GH 20909
+ mdf = DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": [1.0, 2.0, 3.0],
+ "C": ["foo", "bar", "baz"],
+ }
+ )
+ expected = DataFrame(
+ {
+ "A": [1, 6],
+ "B": [1.0, 6.0],
+ "C": ["bar", "foobarbaz"],
+ },
+ index=["min", "sum"],
+ )
+ # sorted index
+ result = mdf.agg(["min", "sum"])
+ tm.assert_frame_equal(result, expected)
+
+ result = mdf[["C", "B", "A"]].agg(["sum", "min"])
+ # GH40420: the result of .agg should have an index that is sorted
+ # according to the arguments provided to agg.
+ expected = expected[["C", "B", "A"]].reindex(["sum", "min"])
+ tm.assert_frame_equal(result, expected)
+
+
+def test_agg_multiple_mixed_raises():
+ # GH 20909
+ mdf = DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": [1.0, 2.0, 3.0],
+ "C": ["foo", "bar", "baz"],
+ "D": date_range("20130101", periods=3),
+ }
+ )
+
+ # sorted index
+ msg = "does not support reduction"
+ with pytest.raises(TypeError, match=msg):
+ mdf.agg(["min", "sum"])
+
+ with pytest.raises(TypeError, match=msg):
+ mdf[["D", "C", "B", "A"]].agg(["sum", "min"])
+
+
+def test_agg_reduce(axis, float_frame):
+ other_axis = 1 if axis in {0, "index"} else 0
+ name1, name2 = float_frame.axes[other_axis].unique()[:2].sort_values()
+
+ # all reducers
+ expected = pd.concat(
+ [
+ float_frame.mean(axis=axis),
+ float_frame.max(axis=axis),
+ float_frame.sum(axis=axis),
+ ],
+ axis=1,
+ )
+ expected.columns = ["mean", "max", "sum"]
+ expected = expected.T if axis in {0, "index"} else expected
+
+ result = float_frame.agg(["mean", "max", "sum"], axis=axis)
+ tm.assert_frame_equal(result, expected)
+
+ # dict input with scalars
+ func = {name1: "mean", name2: "sum"}
+ result = float_frame.agg(func, axis=axis)
+ expected = Series(
+ [
+ float_frame.loc(other_axis)[name1].mean(),
+ float_frame.loc(other_axis)[name2].sum(),
+ ],
+ index=[name1, name2],
+ )
+ tm.assert_series_equal(result, expected)
+
+ # dict input with lists
+ func = {name1: ["mean"], name2: ["sum"]}
+ result = float_frame.agg(func, axis=axis)
+ expected = DataFrame(
+ {
+ name1: Series([float_frame.loc(other_axis)[name1].mean()], index=["mean"]),
+ name2: Series([float_frame.loc(other_axis)[name2].sum()], index=["sum"]),
+ }
+ )
+ expected = expected.T if axis in {1, "columns"} else expected
+ tm.assert_frame_equal(result, expected)
+
+ # dict input with lists with multiple
+ func = {name1: ["mean", "sum"], name2: ["sum", "max"]}
+ result = float_frame.agg(func, axis=axis)
+ expected = pd.concat(
+ {
+ name1: Series(
+ [
+ float_frame.loc(other_axis)[name1].mean(),
+ float_frame.loc(other_axis)[name1].sum(),
+ ],
+ index=["mean", "sum"],
+ ),
+ name2: Series(
+ [
+ float_frame.loc(other_axis)[name2].sum(),
+ float_frame.loc(other_axis)[name2].max(),
+ ],
+ index=["sum", "max"],
+ ),
+ },
+ axis=1,
+ )
+ expected = expected.T if axis in {1, "columns"} else expected
+ tm.assert_frame_equal(result, expected)
+
+
+def test_nuiscance_columns():
+ # GH 15015
+ df = DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": [1.0, 2.0, 3.0],
+ "C": ["foo", "bar", "baz"],
+ "D": date_range("20130101", periods=3),
+ }
+ )
+
+ result = df.agg("min")
+ expected = Series([1, 1.0, "bar", Timestamp("20130101")], index=df.columns)
+ tm.assert_series_equal(result, expected)
+
+ result = df.agg(["min"])
+ expected = DataFrame(
+ [[1, 1.0, "bar", Timestamp("20130101")]],
+ index=["min"],
+ columns=df.columns,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ msg = "does not support reduction"
+ with pytest.raises(TypeError, match=msg):
+ df.agg("sum")
+
+ result = df[["A", "B", "C"]].agg("sum")
+ expected = Series([6, 6.0, "foobarbaz"], index=["A", "B", "C"])
+ tm.assert_series_equal(result, expected)
+
+ msg = "does not support reduction"
+ with pytest.raises(TypeError, match=msg):
+ df.agg(["sum"])
+
+
+@pytest.mark.parametrize("how", ["agg", "apply"])
+def test_non_callable_aggregates(how):
+ # GH 16405
+ # 'size' is a property of frame/series
+ # validate that this is working
+ # GH 39116 - expand to apply
+ df = DataFrame(
+ {"A": [None, 2, 3], "B": [1.0, np.nan, 3.0], "C": ["foo", None, "bar"]}
+ )
+
+ # Function aggregate
+ result = getattr(df, how)({"A": "count"})
+ expected = Series({"A": 2})
+
+ tm.assert_series_equal(result, expected)
+
+ # Non-function aggregate
+ result = getattr(df, how)({"A": "size"})
+ expected = Series({"A": 3})
+
+ tm.assert_series_equal(result, expected)
+
+ # Mix function and non-function aggs
+ result1 = getattr(df, how)(["count", "size"])
+ result2 = getattr(df, how)(
+ {"A": ["count", "size"], "B": ["count", "size"], "C": ["count", "size"]}
+ )
+ expected = DataFrame(
+ {
+ "A": {"count": 2, "size": 3},
+ "B": {"count": 2, "size": 3},
+ "C": {"count": 2, "size": 3},
+ }
+ )
+
+ tm.assert_frame_equal(result1, result2, check_like=True)
+ tm.assert_frame_equal(result2, expected, check_like=True)
+
+ # Just functional string arg is same as calling df.arg()
+ result = getattr(df, how)("count")
+ expected = df.count()
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("how", ["agg", "apply"])
+def test_size_as_str(how, axis):
+ # GH 39934
+ df = DataFrame(
+ {"A": [None, 2, 3], "B": [1.0, np.nan, 3.0], "C": ["foo", None, "bar"]}
+ )
+ # Just a string attribute arg same as calling df.arg
+ # on the columns
+ result = getattr(df, how)("size", axis=axis)
+ if axis in (0, "index"):
+ expected = Series(df.shape[0], index=df.columns)
+ else:
+ expected = Series(df.shape[1], index=df.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_agg_listlike_result():
+ # GH-29587 user defined function returning list-likes
+ df = DataFrame({"A": [2, 2, 3], "B": [1.5, np.nan, 1.5], "C": ["foo", None, "bar"]})
+
+ def func(group_col):
+ return list(group_col.dropna().unique())
+
+ result = df.agg(func)
+ expected = Series([[2, 3], [1.5], ["foo", "bar"]], index=["A", "B", "C"])
+ tm.assert_series_equal(result, expected)
+
+ result = df.agg([func])
+ expected = expected.to_frame("func").T
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize(
+ "args, kwargs",
+ [
+ ((1, 2, 3), {}),
+ ((8, 7, 15), {}),
+ ((1, 2), {}),
+ ((1,), {"b": 2}),
+ ((), {"a": 1, "b": 2}),
+ ((), {"a": 2, "b": 1}),
+ ((), {"a": 1, "b": 2, "c": 3}),
+ ],
+)
+def test_agg_args_kwargs(axis, args, kwargs):
+ def f(x, a, b, c=3):
+ return x.sum() + (a + b) / c
+
+ df = DataFrame([[1, 2], [3, 4]])
+
+ if axis == 0:
+ expected = Series([5.0, 7.0])
+ else:
+ expected = Series([4.0, 8.0])
+
+ result = df.agg(f, axis, *args, **kwargs)
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("num_cols", [2, 3, 5])
+def test_frequency_is_original(num_cols):
+ # GH 22150
+ index = pd.DatetimeIndex(["1950-06-30", "1952-10-24", "1953-05-29"])
+ original = index.copy()
+ df = DataFrame(1, index=index, columns=range(num_cols))
+ df.apply(lambda x: x)
+ assert index.freq == original.freq
+
+
+def test_apply_datetime_tz_issue():
+ # GH 29052
+
+ timestamps = [
+ Timestamp("2019-03-15 12:34:31.909000+0000", tz="UTC"),
+ Timestamp("2019-03-15 12:34:34.359000+0000", tz="UTC"),
+ Timestamp("2019-03-15 12:34:34.660000+0000", tz="UTC"),
+ ]
+ df = DataFrame(data=[0, 1, 2], index=timestamps)
+ result = df.apply(lambda x: x.name, axis=1)
+ expected = Series(index=timestamps, data=timestamps)
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("df", [DataFrame({"A": ["a", None], "B": ["c", "d"]})])
+@pytest.mark.parametrize("method", ["min", "max", "sum"])
+def test_mixed_column_raises(df, method):
+ # GH 16832
+ if method == "sum":
+ msg = r'can only concatenate str \(not "int"\) to str'
+ else:
+ msg = "not supported between instances of 'str' and 'float'"
+ with pytest.raises(TypeError, match=msg):
+ getattr(df, method)()
+
+
+@pytest.mark.parametrize("col", [1, 1.0, True, "a", np.nan])
+def test_apply_dtype(col):
+ # GH 31466
+ df = DataFrame([[1.0, col]], columns=["a", "b"])
+ result = df.apply(lambda x: x.dtype)
+ expected = df.dtypes
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_mutating(using_array_manager, using_copy_on_write):
+ # GH#35462 case where applied func pins a new BlockManager to a row
+ df = DataFrame({"a": range(100), "b": range(100, 200)})
+ df_orig = df.copy()
+
+ def func(row):
+ mgr = row._mgr
+ row.loc["a"] += 1
+ assert row._mgr is not mgr
+ return row
+
+ expected = df.copy()
+ expected["a"] += 1
+
+ result = df.apply(func, axis=1)
+
+ tm.assert_frame_equal(result, expected)
+ if using_copy_on_write or using_array_manager:
+ # INFO(CoW) With copy on write, mutating a viewing row doesn't mutate the parent
+ # INFO(ArrayManager) With BlockManager, the row is a view and mutated in place,
+ # with ArrayManager the row is not a view, and thus not mutated in place
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ tm.assert_frame_equal(df, result)
+
+
+def test_apply_empty_list_reduce():
+ # GH#35683 get columns correct
+ df = DataFrame([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], columns=["a", "b"])
+
+ result = df.apply(lambda x: [], result_type="reduce")
+ expected = Series({"a": [], "b": []}, dtype=object)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_no_suffix_index():
+ # GH36189
+ pdf = DataFrame([[4, 9]] * 3, columns=["A", "B"])
+ result = pdf.apply(["sum", lambda x: x.sum(), lambda x: x.sum()])
+ expected = DataFrame(
+ {"A": [12, 12, 12], "B": [27, 27, 27]}, index=["sum", "", ""]
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_raw_returns_string():
+ # https://github.com/pandas-dev/pandas/issues/35940
+ df = DataFrame({"A": ["aa", "bbb"]})
+ result = df.apply(lambda x: x[0], axis=1, raw=True)
+ expected = Series(["aa", "bbb"])
+ tm.assert_series_equal(result, expected)
+
+
+def test_aggregation_func_column_order():
+ # GH40420: the result of .agg should have an index that is sorted
+ # according to the arguments provided to agg.
+ df = DataFrame(
+ [
+ (1, 0, 0),
+ (2, 0, 0),
+ (3, 0, 0),
+ (4, 5, 4),
+ (5, 6, 6),
+ (6, 7, 7),
+ ],
+ columns=("att1", "att2", "att3"),
+ )
+
+ def sum_div2(s):
+ return s.sum() / 2
+
+ aggs = ["sum", sum_div2, "count", "min"]
+ result = df.agg(aggs)
+ expected = DataFrame(
+ {
+ "att1": [21.0, 10.5, 6.0, 1.0],
+ "att2": [18.0, 9.0, 6.0, 0.0],
+ "att3": [17.0, 8.5, 6.0, 0.0],
+ },
+ index=["sum", "sum_div2", "count", "min"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_getitem_axis_1():
+ # GH 13427
+ df = DataFrame({"a": [0, 1, 2], "b": [1, 2, 3]})
+ result = df[["a", "a"]].apply(lambda x: x.iloc[0] + x.iloc[1], axis=1)
+ expected = Series([0, 2, 4])
+ tm.assert_series_equal(result, expected)
+
+
+def test_nuisance_depr_passes_through_warnings():
+ # GH 43740
+ # DataFrame.agg with list-likes may emit warnings for both individual
+ # args and for entire columns, but we only want to emit once. We
+ # catch and suppress the warnings for individual args, but need to make
+ # sure if some other warnings were raised, they get passed through to
+ # the user.
+
+ def expected_warning(x):
+ warnings.warn("Hello, World!")
+ return x.sum()
+
+ df = DataFrame({"a": [1, 2, 3]})
+ with tm.assert_produces_warning(UserWarning, match="Hello, World!"):
+ df.agg([expected_warning])
+
+
+def test_apply_type():
+ # GH 46719
+ df = DataFrame(
+ {"col1": [3, "string", float], "col2": [0.25, datetime(2020, 1, 1), np.nan]},
+ index=["a", "b", "c"],
+ )
+
+ # axis=0
+ result = df.apply(type, axis=0)
+ expected = Series({"col1": Series, "col2": Series})
+ tm.assert_series_equal(result, expected)
+
+ # axis=1
+ result = df.apply(type, axis=1)
+ expected = Series({"a": Series, "b": Series, "c": Series})
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_on_empty_dataframe():
+ # GH 39111
+ df = DataFrame({"a": [1, 2], "b": [3, 0]})
+ result = df.head(0).apply(lambda x: max(x["a"], x["b"]), axis=1)
+ expected = Series([], dtype=np.float64)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_return_list():
+ df = DataFrame({"a": [1, 2], "b": [2, 3]})
+ result = df.apply(lambda x: [x.values])
+ expected = DataFrame({"a": [[1, 2]], "b": [[2, 3]]})
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "test, constant",
+ [
+ ({"a": [1, 2, 3], "b": [1, 1, 1]}, {"a": [1, 2, 3], "b": [1]}),
+ ({"a": [2, 2, 2], "b": [1, 1, 1]}, {"a": [2], "b": [1]}),
+ ],
+)
+def test_unique_agg_type_is_series(test, constant):
+ # GH#22558
+ df1 = DataFrame(test)
+ expected = Series(data=constant, index=["a", "b"], dtype="object")
+ aggregation = {"a": "unique", "b": "unique"}
+
+ result = df1.agg(aggregation)
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_any_apply_keyword_non_zero_axis_regression():
+ # https://github.com/pandas-dev/pandas/issues/48656
+ df = DataFrame({"A": [1, 2, 0], "B": [0, 2, 0], "C": [0, 0, 0]})
+ expected = Series([True, True, False])
+ tm.assert_series_equal(df.any(axis=1), expected)
+
+ result = df.apply("any", axis=1)
+ tm.assert_series_equal(result, expected)
+
+ result = df.apply("any", 1)
+ tm.assert_series_equal(result, expected)
+
+
+def test_agg_mapping_func_deprecated():
+ # GH 53325
+ df = DataFrame({"x": [1, 2, 3]})
+
+ def foo1(x, a=1, c=0):
+ return x + a + c
+
+ def foo2(x, b=2, c=0):
+ return x + b + c
+
+ # single func already takes the vectorized path
+ result = df.agg(foo1, 0, 3, c=4)
+ expected = df + 7
+ tm.assert_frame_equal(result, expected)
+
+ msg = "using .+ in Series.agg cannot aggregate and"
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.agg([foo1, foo2], 0, 3, c=4)
+ expected = DataFrame(
+ [[8, 8], [9, 9], [10, 10]], columns=[["x", "x"], ["foo1", "foo2"]]
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # TODO: the result below is wrong, should be fixed (GH53325)
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.agg({"x": foo1}, 0, 3, c=4)
+ expected = DataFrame([2, 3, 4], columns=["x"])
+ tm.assert_frame_equal(result, expected)
+
+
+def test_agg_std():
+ df = DataFrame(np.arange(6).reshape(3, 2), columns=["A", "B"])
+
+ with tm.assert_produces_warning(FutureWarning, match="using DataFrame.std"):
+ result = df.agg(np.std)
+ expected = Series({"A": 2.0, "B": 2.0}, dtype=float)
+ tm.assert_series_equal(result, expected)
+
+ with tm.assert_produces_warning(FutureWarning, match="using Series.std"):
+ result = df.agg([np.std])
+ expected = DataFrame({"A": 2.0, "B": 2.0}, index=["std"])
+ tm.assert_frame_equal(result, expected)
+
+
+def test_agg_dist_like_and_nonunique_columns():
+ # GH#51099
+ df = DataFrame(
+ {"A": [None, 2, 3], "B": [1.0, np.nan, 3.0], "C": ["foo", None, "bar"]}
+ )
+ df.columns = ["A", "A", "C"]
+
+ result = df.agg({"A": "count"})
+ expected = df["A"].count()
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_frame_apply_relabeling.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_frame_apply_relabeling.py
new file mode 100644
index 0000000000000000000000000000000000000000..723bdd349c0cb8a8f3fe73ded665b6d22260ffb5
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_frame_apply_relabeling.py
@@ -0,0 +1,113 @@
+import numpy as np
+import pytest
+
+from pandas.compat.numpy import np_version_gte1p25
+
+import pandas as pd
+import pandas._testing as tm
+
+
+def test_agg_relabel():
+ # GH 26513
+ df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})
+
+ # simplest case with one column, one func
+ result = df.agg(foo=("B", "sum"))
+ expected = pd.DataFrame({"B": [10]}, index=pd.Index(["foo"]))
+ tm.assert_frame_equal(result, expected)
+
+ # test on same column with different methods
+ result = df.agg(foo=("B", "sum"), bar=("B", "min"))
+ expected = pd.DataFrame({"B": [10, 1]}, index=pd.Index(["foo", "bar"]))
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_agg_relabel_multi_columns_multi_methods():
+ # GH 26513, test on multiple columns with multiple methods
+ df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})
+ result = df.agg(
+ foo=("A", "sum"),
+ bar=("B", "mean"),
+ cat=("A", "min"),
+ dat=("B", "max"),
+ f=("A", "max"),
+ g=("C", "min"),
+ )
+ expected = pd.DataFrame(
+ {
+ "A": [6.0, np.nan, 1.0, np.nan, 2.0, np.nan],
+ "B": [np.nan, 2.5, np.nan, 4.0, np.nan, np.nan],
+ "C": [np.nan, np.nan, np.nan, np.nan, np.nan, 3.0],
+ },
+ index=pd.Index(["foo", "bar", "cat", "dat", "f", "g"]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.xfail(np_version_gte1p25, reason="name of min now equals name of np.min")
+def test_agg_relabel_partial_functions():
+ # GH 26513, test on partial, functools or more complex cases
+ df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})
+ msg = "using Series.[mean|min]"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.agg(foo=("A", np.mean), bar=("A", "mean"), cat=("A", min))
+ expected = pd.DataFrame(
+ {"A": [1.5, 1.5, 1.0]}, index=pd.Index(["foo", "bar", "cat"])
+ )
+ tm.assert_frame_equal(result, expected)
+
+ msg = "using Series.[mean|min|max|sum]"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.agg(
+ foo=("A", min),
+ bar=("A", np.min),
+ cat=("B", max),
+ dat=("C", "min"),
+ f=("B", np.sum),
+ kk=("B", lambda x: min(x)),
+ )
+ expected = pd.DataFrame(
+ {
+ "A": [1.0, 1.0, np.nan, np.nan, np.nan, np.nan],
+ "B": [np.nan, np.nan, 4.0, np.nan, 10.0, 1.0],
+ "C": [np.nan, np.nan, np.nan, 3.0, np.nan, np.nan],
+ },
+ index=pd.Index(["foo", "bar", "cat", "dat", "f", "kk"]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_agg_namedtuple():
+ # GH 26513
+ df = pd.DataFrame({"A": [0, 1], "B": [1, 2]})
+ result = df.agg(
+ foo=pd.NamedAgg("B", "sum"),
+ bar=pd.NamedAgg("B", "min"),
+ cat=pd.NamedAgg(column="B", aggfunc="count"),
+ fft=pd.NamedAgg("B", aggfunc="max"),
+ )
+
+ expected = pd.DataFrame(
+ {"B": [3, 1, 2, 2]}, index=pd.Index(["foo", "bar", "cat", "fft"])
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.agg(
+ foo=pd.NamedAgg("A", "min"),
+ bar=pd.NamedAgg(column="B", aggfunc="max"),
+ cat=pd.NamedAgg(column="A", aggfunc="max"),
+ )
+ expected = pd.DataFrame(
+ {"A": [0.0, np.nan, 1.0], "B": [np.nan, 2.0, np.nan]},
+ index=pd.Index(["foo", "bar", "cat"]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_reconstruct_func():
+ # GH 28472, test to ensure reconstruct_func isn't moved;
+ # This method is used by other libraries (e.g. dask)
+ result = pd.core.apply.reconstruct_func("min")
+ expected = (False, "min", None, None)
+ tm.assert_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_frame_transform.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_frame_transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d57515882aed6c83535780a575b095d5f9b7489
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_frame_transform.py
@@ -0,0 +1,264 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
+import pandas._testing as tm
+from pandas.tests.apply.common import frame_transform_kernels
+from pandas.tests.frame.common import zip_frames
+
+
+def unpack_obj(obj, klass, axis):
+ """
+ Helper to ensure we have the right type of object for a test parametrized
+ over frame_or_series.
+ """
+ if klass is not DataFrame:
+ obj = obj["A"]
+ if axis != 0:
+ pytest.skip(f"Test is only for DataFrame with axis={axis}")
+ return obj
+
+
+def test_transform_ufunc(axis, float_frame, frame_or_series):
+ # GH 35964
+ obj = unpack_obj(float_frame, frame_or_series, axis)
+
+ with np.errstate(all="ignore"):
+ f_sqrt = np.sqrt(obj)
+
+ # ufunc
+ result = obj.transform(np.sqrt, axis=axis)
+ expected = f_sqrt
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops, names",
+ [
+ ([np.sqrt], ["sqrt"]),
+ ([np.abs, np.sqrt], ["absolute", "sqrt"]),
+ (np.array([np.sqrt]), ["sqrt"]),
+ (np.array([np.abs, np.sqrt]), ["absolute", "sqrt"]),
+ ],
+)
+def test_transform_listlike(axis, float_frame, ops, names):
+ # GH 35964
+ other_axis = 1 if axis in {0, "index"} else 0
+ with np.errstate(all="ignore"):
+ expected = zip_frames([op(float_frame) for op in ops], axis=other_axis)
+ if axis in {0, "index"}:
+ expected.columns = MultiIndex.from_product([float_frame.columns, names])
+ else:
+ expected.index = MultiIndex.from_product([float_frame.index, names])
+ result = float_frame.transform(ops, axis=axis)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("ops", [[], np.array([])])
+def test_transform_empty_listlike(float_frame, ops, frame_or_series):
+ obj = unpack_obj(float_frame, frame_or_series, 0)
+
+ with pytest.raises(ValueError, match="No transform functions were provided"):
+ obj.transform(ops)
+
+
+def test_transform_listlike_func_with_args():
+ # GH 50624
+ df = DataFrame({"x": [1, 2, 3]})
+
+ def foo1(x, a=1, c=0):
+ return x + a + c
+
+ def foo2(x, b=2, c=0):
+ return x + b + c
+
+ msg = r"foo1\(\) got an unexpected keyword argument 'b'"
+ with pytest.raises(TypeError, match=msg):
+ df.transform([foo1, foo2], 0, 3, b=3, c=4)
+
+ result = df.transform([foo1, foo2], 0, 3, c=4)
+ expected = DataFrame(
+ [[8, 8], [9, 9], [10, 10]],
+ columns=MultiIndex.from_tuples([("x", "foo1"), ("x", "foo2")]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("box", [dict, Series])
+def test_transform_dictlike(axis, float_frame, box):
+ # GH 35964
+ if axis in (0, "index"):
+ e = float_frame.columns[0]
+ expected = float_frame[[e]].transform(np.abs)
+ else:
+ e = float_frame.index[0]
+ expected = float_frame.iloc[[0]].transform(np.abs)
+ result = float_frame.transform(box({e: np.abs}), axis=axis)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_transform_dictlike_mixed():
+ # GH 40018 - mix of lists and non-lists in values of a dictionary
+ df = DataFrame({"a": [1, 2], "b": [1, 4], "c": [1, 4]})
+ result = df.transform({"b": ["sqrt", "abs"], "c": "sqrt"})
+ expected = DataFrame(
+ [[1.0, 1, 1.0], [2.0, 4, 2.0]],
+ columns=MultiIndex([("b", "c"), ("sqrt", "abs")], [(0, 0, 1), (0, 1, 0)]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops",
+ [
+ {},
+ {"A": []},
+ {"A": [], "B": "cumsum"},
+ {"A": "cumsum", "B": []},
+ {"A": [], "B": ["cumsum"]},
+ {"A": ["cumsum"], "B": []},
+ ],
+)
+def test_transform_empty_dictlike(float_frame, ops, frame_or_series):
+ obj = unpack_obj(float_frame, frame_or_series, 0)
+
+ with pytest.raises(ValueError, match="No transform functions were provided"):
+ obj.transform(ops)
+
+
+@pytest.mark.parametrize("use_apply", [True, False])
+def test_transform_udf(axis, float_frame, use_apply, frame_or_series):
+ # GH 35964
+ obj = unpack_obj(float_frame, frame_or_series, axis)
+
+ # transform uses UDF either via apply or passing the entire DataFrame
+ def func(x):
+ # transform is using apply iff x is not a DataFrame
+ if use_apply == isinstance(x, frame_or_series):
+ # Force transform to fallback
+ raise ValueError
+ return x + 1
+
+ result = obj.transform(func, axis=axis)
+ expected = obj + 1
+ tm.assert_equal(result, expected)
+
+
+wont_fail = ["ffill", "bfill", "fillna", "pad", "backfill", "shift"]
+frame_kernels_raise = [x for x in frame_transform_kernels if x not in wont_fail]
+
+
+@pytest.mark.parametrize("op", [*frame_kernels_raise, lambda x: x + 1])
+def test_transform_bad_dtype(op, frame_or_series, request):
+ # GH 35964
+ if op == "ngroup":
+ request.node.add_marker(
+ pytest.mark.xfail(raises=ValueError, reason="ngroup not valid for NDFrame")
+ )
+
+ obj = DataFrame({"A": 3 * [object]}) # DataFrame that will fail on most transforms
+ obj = tm.get_obj(obj, frame_or_series)
+ error = TypeError
+ msg = "|".join(
+ [
+ "not supported between instances of 'type' and 'type'",
+ "unsupported operand type",
+ ]
+ )
+
+ with pytest.raises(error, match=msg):
+ obj.transform(op)
+ with pytest.raises(error, match=msg):
+ obj.transform([op])
+ with pytest.raises(error, match=msg):
+ obj.transform({"A": op})
+ with pytest.raises(error, match=msg):
+ obj.transform({"A": [op]})
+
+
+@pytest.mark.parametrize("op", frame_kernels_raise)
+def test_transform_failure_typeerror(request, op):
+ # GH 35964
+
+ if op == "ngroup":
+ request.node.add_marker(
+ pytest.mark.xfail(raises=ValueError, reason="ngroup not valid for NDFrame")
+ )
+
+ # Using object makes most transform kernels fail
+ df = DataFrame({"A": 3 * [object], "B": [1, 2, 3]})
+ error = TypeError
+ msg = "|".join(
+ [
+ "not supported between instances of 'type' and 'type'",
+ "unsupported operand type",
+ ]
+ )
+
+ with pytest.raises(error, match=msg):
+ df.transform([op])
+
+ with pytest.raises(error, match=msg):
+ df.transform({"A": op, "B": op})
+
+ with pytest.raises(error, match=msg):
+ df.transform({"A": [op], "B": [op]})
+
+ with pytest.raises(error, match=msg):
+ df.transform({"A": [op, "shift"], "B": [op]})
+
+
+def test_transform_failure_valueerror():
+ # GH 40211
+ def op(x):
+ if np.sum(np.sum(x)) < 10:
+ raise ValueError
+ return x
+
+ df = DataFrame({"A": [1, 2, 3], "B": [400, 500, 600]})
+ msg = "Transform function failed"
+
+ with pytest.raises(ValueError, match=msg):
+ df.transform([op])
+
+ with pytest.raises(ValueError, match=msg):
+ df.transform({"A": op, "B": op})
+
+ with pytest.raises(ValueError, match=msg):
+ df.transform({"A": [op], "B": [op]})
+
+ with pytest.raises(ValueError, match=msg):
+ df.transform({"A": [op, "shift"], "B": [op]})
+
+
+@pytest.mark.parametrize("use_apply", [True, False])
+def test_transform_passes_args(use_apply, frame_or_series):
+ # GH 35964
+ # transform uses UDF either via apply or passing the entire DataFrame
+ expected_args = [1, 2]
+ expected_kwargs = {"c": 3}
+
+ def f(x, a, b, c):
+ # transform is using apply iff x is not a DataFrame
+ if use_apply == isinstance(x, frame_or_series):
+ # Force transform to fallback
+ raise ValueError
+ assert [a, b] == expected_args
+ assert c == expected_kwargs["c"]
+ return x
+
+ frame_or_series([1]).transform(f, 0, *expected_args, **expected_kwargs)
+
+
+def test_transform_empty_dataframe():
+ # https://github.com/pandas-dev/pandas/issues/39636
+ df = DataFrame([], columns=["col1", "col2"])
+ result = df.transform(lambda x: x + 10)
+ tm.assert_frame_equal(result, df)
+
+ result = df["col1"].transform(lambda x: x + 10)
+ tm.assert_series_equal(result, df["col1"])
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_invalid_arg.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_invalid_arg.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3d9de5e78afb88a7f14b8ab6c8f45d8ab80fbbf
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_invalid_arg.py
@@ -0,0 +1,352 @@
+# Tests specifically aimed at detecting bad arguments.
+# This file is organized by reason for exception.
+# 1. always invalid argument values
+# 2. missing column(s)
+# 3. incompatible ops/dtype/args/kwargs
+# 4. invalid result shape/type
+# If your test does not fit into one of these categories, add to this list.
+
+from itertools import chain
+import re
+
+import numpy as np
+import pytest
+
+from pandas.errors import SpecificationError
+
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+ notna,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize("result_type", ["foo", 1])
+def test_result_type_error(result_type, int_frame_const_col):
+ # allowed result_type
+ df = int_frame_const_col
+
+ msg = (
+ "invalid value for result_type, must be one of "
+ "{None, 'reduce', 'broadcast', 'expand'}"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.apply(lambda x: [1, 2, 3], axis=1, result_type=result_type)
+
+
+def test_apply_invalid_axis_value():
+ df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=["a", "a", "c"])
+ msg = "No axis named 2 for object type DataFrame"
+ with pytest.raises(ValueError, match=msg):
+ df.apply(lambda x: x, 2)
+
+
+def test_agg_raises():
+ # GH 26513
+ df = DataFrame({"A": [0, 1], "B": [1, 2]})
+ msg = "Must provide"
+
+ with pytest.raises(TypeError, match=msg):
+ df.agg()
+
+
+def test_map_with_invalid_na_action_raises():
+ # https://github.com/pandas-dev/pandas/issues/32815
+ s = Series([1, 2, 3])
+ msg = "na_action must either be 'ignore' or None"
+ with pytest.raises(ValueError, match=msg):
+ s.map(lambda x: x, na_action="____")
+
+
+@pytest.mark.parametrize("input_na_action", ["____", True])
+def test_map_arg_is_dict_with_invalid_na_action_raises(input_na_action):
+ # https://github.com/pandas-dev/pandas/issues/46588
+ s = Series([1, 2, 3])
+ msg = f"na_action must either be 'ignore' or None, {input_na_action} was passed"
+ with pytest.raises(ValueError, match=msg):
+ s.map({1: 2}, na_action=input_na_action)
+
+
+@pytest.mark.parametrize("method", ["apply", "agg", "transform"])
+@pytest.mark.parametrize("func", [{"A": {"B": "sum"}}, {"A": {"B": ["sum"]}}])
+def test_nested_renamer(frame_or_series, method, func):
+ # GH 35964
+ obj = frame_or_series({"A": [1]})
+ match = "nested renamer is not supported"
+ with pytest.raises(SpecificationError, match=match):
+ getattr(obj, method)(func)
+
+
+@pytest.mark.parametrize(
+ "renamer",
+ [{"foo": ["min", "max"]}, {"foo": ["min", "max"], "bar": ["sum", "mean"]}],
+)
+def test_series_nested_renamer(renamer):
+ s = Series(range(6), dtype="int64", name="series")
+ msg = "nested renamer is not supported"
+ with pytest.raises(SpecificationError, match=msg):
+ s.agg(renamer)
+
+
+def test_apply_dict_depr():
+ tsdf = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 3)),
+ columns=["A", "B", "C"],
+ index=date_range("1/1/2000", periods=10),
+ )
+ msg = "nested renamer is not supported"
+ with pytest.raises(SpecificationError, match=msg):
+ tsdf.A.agg({"foo": ["sum", "mean"]})
+
+
+@pytest.mark.parametrize("method", ["agg", "transform"])
+def test_dict_nested_renaming_depr(method):
+ df = DataFrame({"A": range(5), "B": 5})
+
+ # nested renaming
+ msg = r"nested renamer is not supported"
+ with pytest.raises(SpecificationError, match=msg):
+ getattr(df, method)({"A": {"foo": "min"}, "B": {"bar": "max"}})
+
+
+@pytest.mark.parametrize("method", ["apply", "agg", "transform"])
+@pytest.mark.parametrize("func", [{"B": "sum"}, {"B": ["sum"]}])
+def test_missing_column(method, func):
+ # GH 40004
+ obj = DataFrame({"A": [1]})
+ match = re.escape("Column(s) ['B'] do not exist")
+ with pytest.raises(KeyError, match=match):
+ getattr(obj, method)(func)
+
+
+def test_transform_mixed_column_name_dtypes():
+ # GH39025
+ df = DataFrame({"a": ["1"]})
+ msg = r"Column\(s\) \[1, 'b'\] do not exist"
+ with pytest.raises(KeyError, match=msg):
+ df.transform({"a": int, 1: str, "b": int})
+
+
+@pytest.mark.parametrize(
+ "how, args", [("pct_change", ()), ("nsmallest", (1, ["a", "b"])), ("tail", 1)]
+)
+def test_apply_str_axis_1_raises(how, args):
+ # GH 39211 - some ops don't support axis=1
+ df = DataFrame({"a": [1, 2], "b": [3, 4]})
+ msg = f"Operation {how} does not support axis=1"
+ with pytest.raises(ValueError, match=msg):
+ df.apply(how, axis=1, args=args)
+
+
+def test_transform_axis_1_raises():
+ # GH 35964
+ msg = "No axis named 1 for object type Series"
+ with pytest.raises(ValueError, match=msg):
+ Series([1]).transform("sum", axis=1)
+
+
+def test_apply_modify_traceback():
+ data = DataFrame(
+ {
+ "A": [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ "foo",
+ "foo",
+ "foo",
+ ],
+ "B": [
+ "one",
+ "one",
+ "one",
+ "two",
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "two",
+ "one",
+ ],
+ "C": [
+ "dull",
+ "dull",
+ "shiny",
+ "dull",
+ "dull",
+ "shiny",
+ "shiny",
+ "dull",
+ "shiny",
+ "shiny",
+ "shiny",
+ ],
+ "D": np.random.default_rng(2).standard_normal(11),
+ "E": np.random.default_rng(2).standard_normal(11),
+ "F": np.random.default_rng(2).standard_normal(11),
+ }
+ )
+
+ data.loc[4, "C"] = np.nan
+
+ def transform(row):
+ if row["C"].startswith("shin") and row["A"] == "foo":
+ row["D"] = 7
+ return row
+
+ def transform2(row):
+ if notna(row["C"]) and row["C"].startswith("shin") and row["A"] == "foo":
+ row["D"] = 7
+ return row
+
+ msg = "'float' object has no attribute 'startswith'"
+ with pytest.raises(AttributeError, match=msg):
+ data.apply(transform, axis=1)
+
+
+@pytest.mark.parametrize(
+ "df, func, expected",
+ tm.get_cython_table_params(
+ DataFrame([["a", "b"], ["b", "a"]]), [["cumprod", TypeError]]
+ ),
+)
+def test_agg_cython_table_raises_frame(df, func, expected, axis):
+ # GH 21224
+ msg = "can't multiply sequence by non-int of type 'str'"
+ warn = None if isinstance(func, str) else FutureWarning
+ with pytest.raises(expected, match=msg):
+ with tm.assert_produces_warning(warn, match="using DataFrame.cumprod"):
+ df.agg(func, axis=axis)
+
+
+@pytest.mark.parametrize(
+ "series, func, expected",
+ chain(
+ tm.get_cython_table_params(
+ Series("a b c".split()),
+ [
+ ("mean", TypeError), # mean raises TypeError
+ ("prod", TypeError),
+ ("std", TypeError),
+ ("var", TypeError),
+ ("median", TypeError),
+ ("cumprod", TypeError),
+ ],
+ )
+ ),
+)
+def test_agg_cython_table_raises_series(series, func, expected):
+ # GH21224
+ msg = r"[Cc]ould not convert|can't multiply sequence by non-int of type"
+ if func == "median" or func is np.nanmedian or func is np.median:
+ msg = r"Cannot convert \['a' 'b' 'c'\] to numeric"
+ warn = None if isinstance(func, str) else FutureWarning
+
+ with pytest.raises(expected, match=msg):
+ # e.g. Series('a b'.split()).cumprod() will raise
+ with tm.assert_produces_warning(warn, match="is currently using Series.*"):
+ series.agg(func)
+
+
+def test_agg_none_to_type():
+ # GH 40543
+ df = DataFrame({"a": [None]})
+ msg = re.escape("int() argument must be a string")
+ with pytest.raises(TypeError, match=msg):
+ df.agg({"a": lambda x: int(x.iloc[0])})
+
+
+def test_transform_none_to_type():
+ # GH#34377
+ df = DataFrame({"a": [None]})
+ msg = "argument must be a"
+ with pytest.raises(TypeError, match=msg):
+ df.transform({"a": lambda x: int(x.iloc[0])})
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ lambda x: np.array([1, 2]).reshape(-1, 2),
+ lambda x: [1, 2],
+ lambda x: Series([1, 2]),
+ ],
+)
+def test_apply_broadcast_error(int_frame_const_col, func):
+ df = int_frame_const_col
+
+ # > 1 ndim
+ msg = "too many dims to broadcast|cannot broadcast result"
+ with pytest.raises(ValueError, match=msg):
+ df.apply(func, axis=1, result_type="broadcast")
+
+
+def test_transform_and_agg_err_agg(axis, float_frame):
+ # cannot both transform and agg
+ msg = "cannot combine transform and aggregation operations"
+ with pytest.raises(ValueError, match=msg):
+ with np.errstate(all="ignore"):
+ float_frame.agg(["max", "sqrt"], axis=axis)
+
+
+@pytest.mark.filterwarnings("ignore::FutureWarning") # GH53325
+@pytest.mark.parametrize(
+ "func, msg",
+ [
+ (["sqrt", "max"], "cannot combine transform and aggregation"),
+ (
+ {"foo": np.sqrt, "bar": "sum"},
+ "cannot perform both aggregation and transformation",
+ ),
+ ],
+)
+def test_transform_and_agg_err_series(string_series, func, msg):
+ # we are trying to transform with an aggregator
+ with pytest.raises(ValueError, match=msg):
+ with np.errstate(all="ignore"):
+ string_series.agg(func)
+
+
+@pytest.mark.parametrize("func", [["max", "min"], ["max", "sqrt"]])
+def test_transform_wont_agg_frame(axis, float_frame, func):
+ # GH 35964
+ # cannot both transform and agg
+ msg = "Function did not transform"
+ with pytest.raises(ValueError, match=msg):
+ float_frame.transform(func, axis=axis)
+
+
+@pytest.mark.parametrize("func", [["min", "max"], ["sqrt", "max"]])
+def test_transform_wont_agg_series(string_series, func):
+ # GH 35964
+ # we are trying to transform with an aggregator
+ msg = "Function did not transform"
+
+ warn = RuntimeWarning if func[0] == "sqrt" else None
+ warn_msg = "invalid value encountered in sqrt"
+ with pytest.raises(ValueError, match=msg):
+ with tm.assert_produces_warning(warn, match=warn_msg, check_stacklevel=False):
+ string_series.transform(func)
+
+
+@pytest.mark.parametrize(
+ "op_wrapper", [lambda x: x, lambda x: [x], lambda x: {"A": x}, lambda x: {"A": [x]}]
+)
+def test_transform_reducer_raises(all_reductions, frame_or_series, op_wrapper):
+ # GH 35964
+ op = op_wrapper(all_reductions)
+
+ obj = DataFrame({"A": [1, 2, 3]})
+ obj = tm.get_obj(obj, frame_or_series)
+
+ msg = "Function did not transform"
+ with pytest.raises(ValueError, match=msg):
+ obj.transform(op)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_series_apply.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_series_apply.py
new file mode 100644
index 0000000000000000000000000000000000000000..aeb6a01eb587a0a75111c4f438672cc331498732
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_series_apply.py
@@ -0,0 +1,689 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ concat,
+ timedelta_range,
+)
+import pandas._testing as tm
+from pandas.tests.apply.common import series_transform_kernels
+
+
+@pytest.fixture(params=[False, "compat"])
+def by_row(request):
+ return request.param
+
+
+def test_series_map_box_timedelta(by_row):
+ # GH#11349
+ ser = Series(timedelta_range("1 day 1 s", periods=3, freq="h"))
+
+ def f(x):
+ return x.total_seconds() if by_row else x.dt.total_seconds()
+
+ result = ser.apply(f, by_row=by_row)
+
+ expected = ser.map(lambda x: x.total_seconds())
+ tm.assert_series_equal(result, expected)
+
+ expected = Series([86401.0, 90001.0, 93601.0])
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply(datetime_series, by_row):
+ result = datetime_series.apply(np.sqrt, by_row=by_row)
+ with np.errstate(all="ignore"):
+ expected = np.sqrt(datetime_series)
+ tm.assert_series_equal(result, expected)
+
+ # element-wise apply (ufunc)
+ result = datetime_series.apply(np.exp, by_row=by_row)
+ expected = np.exp(datetime_series)
+ tm.assert_series_equal(result, expected)
+
+ # empty series
+ s = Series(dtype=object, name="foo", index=Index([], name="bar"))
+ rs = s.apply(lambda x: x, by_row=by_row)
+ tm.assert_series_equal(s, rs)
+
+ # check all metadata (GH 9322)
+ assert s is not rs
+ assert s.index is rs.index
+ assert s.dtype == rs.dtype
+ assert s.name == rs.name
+
+ # index but no data
+ s = Series(index=[1, 2, 3], dtype=np.float64)
+ rs = s.apply(lambda x: x, by_row=by_row)
+ tm.assert_series_equal(s, rs)
+
+
+def test_apply_map_same_length_inference_bug():
+ s = Series([1, 2])
+
+ def f(x):
+ return (x, x + 1)
+
+ result = s.apply(f, by_row="compat")
+ expected = s.map(f)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("convert_dtype", [True, False])
+def test_apply_convert_dtype_deprecated(convert_dtype):
+ ser = Series(np.random.default_rng(2).standard_normal(10))
+
+ def func(x):
+ return x if x > 0 else np.nan
+
+ with tm.assert_produces_warning(FutureWarning):
+ ser.apply(func, convert_dtype=convert_dtype, by_row="compat")
+
+
+def test_apply_args():
+ s = Series(["foo,bar"])
+
+ result = s.apply(str.split, args=(",",))
+ assert result[0] == ["foo", "bar"]
+ assert isinstance(result[0], list)
+
+
+@pytest.mark.parametrize(
+ "args, kwargs, increment",
+ [((), {}, 0), ((), {"a": 1}, 1), ((2, 3), {}, 32), ((1,), {"c": 2}, 201)],
+)
+def test_agg_args(args, kwargs, increment):
+ # GH 43357
+ def f(x, a=0, b=0, c=0):
+ return x + a + 10 * b + 100 * c
+
+ s = Series([1, 2])
+ msg = (
+ "in Series.agg cannot aggregate and has been deprecated. "
+ "Use Series.transform to keep behavior unchanged."
+ )
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = s.agg(f, 0, *args, **kwargs)
+ expected = s + increment
+ tm.assert_series_equal(result, expected)
+
+
+def test_agg_mapping_func_deprecated():
+ # GH 53325
+ s = Series([1, 2, 3])
+
+ def foo1(x, a=1, c=0):
+ return x + a + c
+
+ def foo2(x, b=2, c=0):
+ return x + b + c
+
+ msg = "using .+ in Series.agg cannot aggregate and"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ s.agg(foo1, 0, 3, c=4)
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ s.agg([foo1, foo2], 0, 3, c=4)
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ s.agg({"a": foo1, "b": foo2}, 0, 3, c=4)
+
+
+def test_series_apply_map_box_timestamps(by_row):
+ # GH#2689, GH#2627
+ ser = Series(pd.date_range("1/1/2000", periods=10))
+
+ def func(x):
+ return (x.hour, x.day, x.month)
+
+ if not by_row:
+ msg = "Series' object has no attribute 'hour'"
+ with pytest.raises(AttributeError, match=msg):
+ ser.apply(func, by_row=by_row)
+ return
+
+ result = ser.apply(func, by_row=by_row)
+ expected = ser.map(func)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_box():
+ # ufunc will not be boxed. Same test cases as the test_map_box
+ vals = [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")]
+ s = Series(vals)
+ assert s.dtype == "datetime64[ns]"
+ # boxed value must be Timestamp instance
+ res = s.apply(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}", by_row="compat")
+ exp = Series(["Timestamp_1_None", "Timestamp_2_None"])
+ tm.assert_series_equal(res, exp)
+
+ vals = [
+ pd.Timestamp("2011-01-01", tz="US/Eastern"),
+ pd.Timestamp("2011-01-02", tz="US/Eastern"),
+ ]
+ s = Series(vals)
+ assert s.dtype == "datetime64[ns, US/Eastern]"
+ res = s.apply(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}", by_row="compat")
+ exp = Series(["Timestamp_1_US/Eastern", "Timestamp_2_US/Eastern"])
+ tm.assert_series_equal(res, exp)
+
+ # timedelta
+ vals = [pd.Timedelta("1 days"), pd.Timedelta("2 days")]
+ s = Series(vals)
+ assert s.dtype == "timedelta64[ns]"
+ res = s.apply(lambda x: f"{type(x).__name__}_{x.days}", by_row="compat")
+ exp = Series(["Timedelta_1", "Timedelta_2"])
+ tm.assert_series_equal(res, exp)
+
+ # period
+ vals = [pd.Period("2011-01-01", freq="M"), pd.Period("2011-01-02", freq="M")]
+ s = Series(vals)
+ assert s.dtype == "Period[M]"
+ res = s.apply(lambda x: f"{type(x).__name__}_{x.freqstr}", by_row="compat")
+ exp = Series(["Period_M", "Period_M"])
+ tm.assert_series_equal(res, exp)
+
+
+def test_apply_datetimetz(by_row):
+ values = pd.date_range("2011-01-01", "2011-01-02", freq="H").tz_localize(
+ "Asia/Tokyo"
+ )
+ s = Series(values, name="XX")
+
+ result = s.apply(lambda x: x + pd.offsets.Day(), by_row=by_row)
+ exp_values = pd.date_range("2011-01-02", "2011-01-03", freq="H").tz_localize(
+ "Asia/Tokyo"
+ )
+ exp = Series(exp_values, name="XX")
+ tm.assert_series_equal(result, exp)
+
+ result = s.apply(lambda x: x.hour if by_row else x.dt.hour, by_row=by_row)
+ exp = Series(list(range(24)) + [0], name="XX", dtype="int64" if by_row else "int32")
+ tm.assert_series_equal(result, exp)
+
+ # not vectorized
+ def f(x):
+ return str(x.tz) if by_row else str(x.dt.tz)
+
+ result = s.apply(f, by_row=by_row)
+ if by_row:
+ exp = Series(["Asia/Tokyo"] * 25, name="XX")
+ tm.assert_series_equal(result, exp)
+ else:
+ result == "Asia/Tokyo"
+
+
+def test_apply_categorical(by_row):
+ values = pd.Categorical(list("ABBABCD"), categories=list("DCBA"), ordered=True)
+ ser = Series(values, name="XX", index=list("abcdefg"))
+
+ if not by_row:
+ msg = "Series' object has no attribute 'lower"
+ with pytest.raises(AttributeError, match=msg):
+ ser.apply(lambda x: x.lower(), by_row=by_row)
+ assert ser.apply(lambda x: "A", by_row=by_row) == "A"
+ return
+
+ result = ser.apply(lambda x: x.lower(), by_row=by_row)
+
+ # should be categorical dtype when the number of categories are
+ # the same
+ values = pd.Categorical(list("abbabcd"), categories=list("dcba"), ordered=True)
+ exp = Series(values, name="XX", index=list("abcdefg"))
+ tm.assert_series_equal(result, exp)
+ tm.assert_categorical_equal(result.values, exp.values)
+
+ result = ser.apply(lambda x: "A")
+ exp = Series(["A"] * 7, name="XX", index=list("abcdefg"))
+ tm.assert_series_equal(result, exp)
+ assert result.dtype == object
+
+
+@pytest.mark.parametrize("series", [["1-1", "1-1", np.nan], ["1-1", "1-2", np.nan]])
+def test_apply_categorical_with_nan_values(series, by_row):
+ # GH 20714 bug fixed in: GH 24275
+ s = Series(series, dtype="category")
+ if not by_row:
+ msg = "'Series' object has no attribute 'split'"
+ with pytest.raises(AttributeError, match=msg):
+ s.apply(lambda x: x.split("-")[0], by_row=by_row)
+ return
+
+ result = s.apply(lambda x: x.split("-")[0], by_row=by_row)
+ result = result.astype(object)
+ expected = Series(["1", "1", np.nan], dtype="category")
+ expected = expected.astype(object)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_empty_integer_series_with_datetime_index(by_row):
+ # GH 21245
+ s = Series([], index=pd.date_range(start="2018-01-01", periods=0), dtype=int)
+ result = s.apply(lambda x: x, by_row=by_row)
+ tm.assert_series_equal(result, s)
+
+
+def test_apply_dataframe_iloc():
+ uintDF = DataFrame(np.uint64([1, 2, 3, 4, 5]), columns=["Numbers"])
+ indexDF = DataFrame([2, 3, 2, 1, 2], columns=["Indices"])
+
+ def retrieve(targetRow, targetDF):
+ val = targetDF["Numbers"].iloc[targetRow]
+ return val
+
+ result = indexDF["Indices"].apply(retrieve, args=(uintDF,))
+ expected = Series([3, 4, 3, 2, 3], name="Indices", dtype="uint64")
+ tm.assert_series_equal(result, expected)
+
+
+def test_transform(string_series, by_row):
+ # transforming functions
+
+ with np.errstate(all="ignore"):
+ f_sqrt = np.sqrt(string_series)
+ f_abs = np.abs(string_series)
+
+ # ufunc
+ result = string_series.apply(np.sqrt, by_row=by_row)
+ expected = f_sqrt.copy()
+ tm.assert_series_equal(result, expected)
+
+ # list-like
+ result = string_series.apply([np.sqrt], by_row=by_row)
+ expected = f_sqrt.to_frame().copy()
+ expected.columns = ["sqrt"]
+ tm.assert_frame_equal(result, expected)
+
+ result = string_series.apply(["sqrt"], by_row=by_row)
+ tm.assert_frame_equal(result, expected)
+
+ # multiple items in list
+ # these are in the order as if we are applying both functions per
+ # series and then concatting
+ expected = concat([f_sqrt, f_abs], axis=1)
+ expected.columns = ["sqrt", "absolute"]
+ result = string_series.apply([np.sqrt, np.abs], by_row=by_row)
+ tm.assert_frame_equal(result, expected)
+
+ # dict, provide renaming
+ expected = concat([f_sqrt, f_abs], axis=1)
+ expected.columns = ["foo", "bar"]
+ expected = expected.unstack().rename("series")
+
+ result = string_series.apply({"foo": np.sqrt, "bar": np.abs}, by_row=by_row)
+ tm.assert_series_equal(result.reindex_like(expected), expected)
+
+
+@pytest.mark.parametrize("op", series_transform_kernels)
+def test_transform_partial_failure(op, request):
+ # GH 35964
+ if op in ("ffill", "bfill", "pad", "backfill", "shift"):
+ request.node.add_marker(
+ pytest.mark.xfail(reason=f"{op} is successful on any dtype")
+ )
+
+ # Using object makes most transform kernels fail
+ ser = Series(3 * [object])
+
+ if op in ("fillna", "ngroup"):
+ error = ValueError
+ msg = "Transform function failed"
+ else:
+ error = TypeError
+ msg = "|".join(
+ [
+ "not supported between instances of 'type' and 'type'",
+ "unsupported operand type",
+ ]
+ )
+
+ with pytest.raises(error, match=msg):
+ ser.transform([op, "shift"])
+
+ with pytest.raises(error, match=msg):
+ ser.transform({"A": op, "B": "shift"})
+
+ with pytest.raises(error, match=msg):
+ ser.transform({"A": [op], "B": ["shift"]})
+
+ with pytest.raises(error, match=msg):
+ ser.transform({"A": [op, "shift"], "B": [op]})
+
+
+def test_transform_partial_failure_valueerror():
+ # GH 40211
+ def noop(x):
+ return x
+
+ def raising_op(_):
+ raise ValueError
+
+ ser = Series(3 * [object])
+ msg = "Transform function failed"
+
+ with pytest.raises(ValueError, match=msg):
+ ser.transform([noop, raising_op])
+
+ with pytest.raises(ValueError, match=msg):
+ ser.transform({"A": raising_op, "B": noop})
+
+ with pytest.raises(ValueError, match=msg):
+ ser.transform({"A": [raising_op], "B": [noop]})
+
+ with pytest.raises(ValueError, match=msg):
+ ser.transform({"A": [noop, raising_op], "B": [noop]})
+
+
+def test_demo():
+ # demonstration tests
+ s = Series(range(6), dtype="int64", name="series")
+
+ result = s.agg(["min", "max"])
+ expected = Series([0, 5], index=["min", "max"], name="series")
+ tm.assert_series_equal(result, expected)
+
+ result = s.agg({"foo": "min"})
+ expected = Series([0], index=["foo"], name="series")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", [str, lambda x: str(x)])
+def test_apply_map_evaluate_lambdas_the_same(string_series, func, by_row):
+ # test that we are evaluating row-by-row first if by_row="compat"
+ # else vectorized evaluation
+ result = string_series.apply(func, by_row=by_row)
+
+ if by_row:
+ expected = string_series.map(func)
+ tm.assert_series_equal(result, expected)
+ else:
+ assert result == str(string_series)
+
+
+def test_agg_evaluate_lambdas(string_series):
+ # GH53325
+ # in the future, the result will be a Series class.
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = string_series.agg(lambda x: type(x))
+ assert isinstance(result, Series) and len(result) == len(string_series)
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = string_series.agg(type)
+ assert isinstance(result, Series) and len(result) == len(string_series)
+
+
+@pytest.mark.parametrize("op_name", ["agg", "apply"])
+def test_with_nested_series(datetime_series, op_name):
+ # GH 2316
+ # .agg with a reducer and a transform, what to do
+ msg = "cannot aggregate"
+ warning = FutureWarning if op_name == "agg" else None
+ with tm.assert_produces_warning(warning, match=msg):
+ # GH52123
+ result = getattr(datetime_series, op_name)(
+ lambda x: Series([x, x**2], index=["x", "x^2"])
+ )
+ expected = DataFrame({"x": datetime_series, "x^2": datetime_series**2})
+ tm.assert_frame_equal(result, expected)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = datetime_series.agg(lambda x: Series([x, x**2], index=["x", "x^2"]))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_replicate_describe(string_series):
+ # this also tests a result set that is all scalars
+ expected = string_series.describe()
+ result = string_series.apply(
+ {
+ "count": "count",
+ "mean": "mean",
+ "std": "std",
+ "min": "min",
+ "25%": lambda x: x.quantile(0.25),
+ "50%": "median",
+ "75%": lambda x: x.quantile(0.75),
+ "max": "max",
+ },
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_reduce(string_series):
+ # reductions with named functions
+ result = string_series.agg(["sum", "mean"])
+ expected = Series(
+ [string_series.sum(), string_series.mean()],
+ ["sum", "mean"],
+ name=string_series.name,
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "how, kwds",
+ [("agg", {}), ("apply", {"by_row": "compat"}), ("apply", {"by_row": False})],
+)
+def test_non_callable_aggregates(how, kwds):
+ # test agg using non-callable series attributes
+ # GH 39116 - expand to apply
+ s = Series([1, 2, None])
+
+ # Calling agg w/ just a string arg same as calling s.arg
+ result = getattr(s, how)("size", **kwds)
+ expected = s.size
+ assert result == expected
+
+ # test when mixed w/ callable reducers
+ result = getattr(s, how)(["size", "count", "mean"], **kwds)
+ expected = Series({"size": 3.0, "count": 2.0, "mean": 1.5})
+ tm.assert_series_equal(result, expected)
+
+ result = getattr(s, how)({"size": "size", "count": "count", "mean": "mean"}, **kwds)
+ tm.assert_series_equal(result, expected)
+
+
+def test_series_apply_no_suffix_index(by_row):
+ # GH36189
+ s = Series([4] * 3)
+ result = s.apply(["sum", lambda x: x.sum(), lambda x: x.sum()], by_row=by_row)
+ expected = Series([12, 12, 12], index=["sum", "", ""])
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "dti,exp",
+ [
+ (
+ Series([1, 2], index=pd.DatetimeIndex([0, 31536000000])),
+ DataFrame(np.repeat([[1, 2]], 2, axis=0), dtype="int64"),
+ ),
+ (
+ tm.makeTimeSeries(nper=30),
+ DataFrame(np.repeat([[1, 2]], 30, axis=0), dtype="int64"),
+ ),
+ ],
+)
+@pytest.mark.parametrize("aware", [True, False])
+def test_apply_series_on_date_time_index_aware_series(dti, exp, aware):
+ # GH 25959
+ # Calling apply on a localized time series should not cause an error
+ if aware:
+ index = dti.tz_localize("UTC").index
+ else:
+ index = dti.index
+ result = Series(index).apply(lambda x: Series([1, 2]))
+ tm.assert_frame_equal(result, exp)
+
+
+@pytest.mark.parametrize(
+ "by_row, expected", [("compat", Series(np.ones(30), dtype="int64")), (False, 1)]
+)
+def test_apply_scalar_on_date_time_index_aware_series(by_row, expected):
+ # GH 25959
+ # Calling apply on a localized time series should not cause an error
+ series = tm.makeTimeSeries(nper=30).tz_localize("UTC")
+ result = Series(series.index).apply(lambda x: 1, by_row=by_row)
+ tm.assert_equal(result, expected)
+
+
+def test_apply_to_timedelta(by_row):
+ list_of_valid_strings = ["00:00:01", "00:00:02"]
+ a = pd.to_timedelta(list_of_valid_strings)
+ b = Series(list_of_valid_strings).apply(pd.to_timedelta, by_row=by_row)
+ tm.assert_series_equal(Series(a), b)
+
+ list_of_strings = ["00:00:01", np.nan, pd.NaT, pd.NaT]
+
+ a = pd.to_timedelta(list_of_strings)
+ ser = Series(list_of_strings)
+ b = ser.apply(pd.to_timedelta, by_row=by_row)
+ tm.assert_series_equal(Series(a), b)
+
+
+@pytest.mark.parametrize(
+ "ops, names",
+ [
+ ([np.sum], ["sum"]),
+ ([np.sum, np.mean], ["sum", "mean"]),
+ (np.array([np.sum]), ["sum"]),
+ (np.array([np.sum, np.mean]), ["sum", "mean"]),
+ ],
+)
+@pytest.mark.parametrize(
+ "how, kwargs",
+ [["agg", {}], ["apply", {"by_row": "compat"}], ["apply", {"by_row": False}]],
+)
+def test_apply_listlike_reducer(string_series, ops, names, how, kwargs):
+ # GH 39140
+ expected = Series({name: op(string_series) for name, op in zip(names, ops)})
+ expected.name = "series"
+ warn = FutureWarning if how == "agg" else None
+ msg = f"using Series.[{'|'.join(names)}]"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = getattr(string_series, how)(ops, **kwargs)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops",
+ [
+ {"A": np.sum},
+ {"A": np.sum, "B": np.mean},
+ Series({"A": np.sum}),
+ Series({"A": np.sum, "B": np.mean}),
+ ],
+)
+@pytest.mark.parametrize(
+ "how, kwargs",
+ [["agg", {}], ["apply", {"by_row": "compat"}], ["apply", {"by_row": False}]],
+)
+def test_apply_dictlike_reducer(string_series, ops, how, kwargs, by_row):
+ # GH 39140
+ expected = Series({name: op(string_series) for name, op in ops.items()})
+ expected.name = string_series.name
+ warn = FutureWarning if how == "agg" else None
+ msg = "using Series.[sum|mean]"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = getattr(string_series, how)(ops, **kwargs)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops, names",
+ [
+ ([np.sqrt], ["sqrt"]),
+ ([np.abs, np.sqrt], ["absolute", "sqrt"]),
+ (np.array([np.sqrt]), ["sqrt"]),
+ (np.array([np.abs, np.sqrt]), ["absolute", "sqrt"]),
+ ],
+)
+def test_apply_listlike_transformer(string_series, ops, names, by_row):
+ # GH 39140
+ with np.errstate(all="ignore"):
+ expected = concat([op(string_series) for op in ops], axis=1)
+ expected.columns = names
+ result = string_series.apply(ops, by_row=by_row)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops, expected",
+ [
+ ([lambda x: x], DataFrame({"": [1, 2, 3]})),
+ ([lambda x: x.sum()], Series([6], index=[""])),
+ ],
+)
+def test_apply_listlike_lambda(ops, expected, by_row):
+ # GH53400
+ ser = Series([1, 2, 3])
+ result = ser.apply(ops, by_row=by_row)
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops",
+ [
+ {"A": np.sqrt},
+ {"A": np.sqrt, "B": np.exp},
+ Series({"A": np.sqrt}),
+ Series({"A": np.sqrt, "B": np.exp}),
+ ],
+)
+def test_apply_dictlike_transformer(string_series, ops, by_row):
+ # GH 39140
+ with np.errstate(all="ignore"):
+ expected = concat({name: op(string_series) for name, op in ops.items()})
+ expected.name = string_series.name
+ result = string_series.apply(ops, by_row=by_row)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops, expected",
+ [
+ (
+ {"a": lambda x: x},
+ Series([1, 2, 3], index=MultiIndex.from_arrays([["a"] * 3, range(3)])),
+ ),
+ ({"a": lambda x: x.sum()}, Series([6], index=["a"])),
+ ],
+)
+def test_apply_dictlike_lambda(ops, by_row, expected):
+ # GH53400
+ ser = Series([1, 2, 3])
+ result = ser.apply(ops, by_row=by_row)
+ tm.assert_equal(result, expected)
+
+
+def test_apply_retains_column_name(by_row):
+ # GH 16380
+ df = DataFrame({"x": range(3)}, Index(range(3), name="x"))
+ result = df.x.apply(lambda x: Series(range(x + 1), Index(range(x + 1), name="y")))
+ expected = DataFrame(
+ [[0.0, np.nan, np.nan], [0.0, 1.0, np.nan], [0.0, 1.0, 2.0]],
+ columns=Index(range(3), name="y"),
+ index=Index(range(3), name="x"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_type():
+ # GH 46719
+ s = Series([3, "string", float], index=["a", "b", "c"])
+ result = s.apply(type)
+ expected = Series([int, str, type], index=["a", "b", "c"])
+ tm.assert_series_equal(result, expected)
+
+
+def test_series_apply_unpack_nested_data():
+ # GH#55189
+ ser = Series([[1, 2, 3], [4, 5, 6, 7]])
+ result = ser.apply(lambda x: Series(x))
+ expected = DataFrame({0: [1.0, 4.0], 1: [2.0, 5.0], 2: [3.0, 6.0], 3: [np.nan, 7]})
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_series_apply_relabeling.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_series_apply_relabeling.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdfa054f91c9b67261d715cd7812a53d1b2d4b2f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_series_apply_relabeling.py
@@ -0,0 +1,39 @@
+import pandas as pd
+import pandas._testing as tm
+
+
+def test_relabel_no_duplicated_method():
+ # this is to test there is no duplicated method used in agg
+ df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4]})
+
+ result = df["A"].agg(foo="sum")
+ expected = df["A"].agg({"foo": "sum"})
+ tm.assert_series_equal(result, expected)
+
+ result = df["B"].agg(foo="min", bar="max")
+ expected = df["B"].agg({"foo": "min", "bar": "max"})
+ tm.assert_series_equal(result, expected)
+
+ msg = "using Series.[sum|min|max]"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df["B"].agg(foo=sum, bar=min, cat="max")
+ msg = "using Series.[sum|min|max]"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = df["B"].agg({"foo": sum, "bar": min, "cat": "max"})
+ tm.assert_series_equal(result, expected)
+
+
+def test_relabel_duplicated_method():
+ # this is to test with nested renaming, duplicated method can be used
+ # if they are assigned with different new names
+ df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4]})
+
+ result = df["A"].agg(foo="sum", bar="sum")
+ expected = pd.Series([6, 6], index=["foo", "bar"], name="A")
+ tm.assert_series_equal(result, expected)
+
+ msg = "using Series.min"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df["B"].agg(foo=min, bar="min")
+ expected = pd.Series([1, 1], index=["foo", "bar"], name="B")
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_series_transform.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_series_transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..82592c4711ece5a7f4b6d421d743e1adbd78c345
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_series_transform.py
@@ -0,0 +1,84 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ concat,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize(
+ "args, kwargs, increment",
+ [((), {}, 0), ((), {"a": 1}, 1), ((2, 3), {}, 32), ((1,), {"c": 2}, 201)],
+)
+def test_agg_args(args, kwargs, increment):
+ # GH 43357
+ def f(x, a=0, b=0, c=0):
+ return x + a + 10 * b + 100 * c
+
+ s = Series([1, 2])
+ result = s.transform(f, 0, *args, **kwargs)
+ expected = s + increment
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ops, names",
+ [
+ ([np.sqrt], ["sqrt"]),
+ ([np.abs, np.sqrt], ["absolute", "sqrt"]),
+ (np.array([np.sqrt]), ["sqrt"]),
+ (np.array([np.abs, np.sqrt]), ["absolute", "sqrt"]),
+ ],
+)
+def test_transform_listlike(string_series, ops, names):
+ # GH 35964
+ with np.errstate(all="ignore"):
+ expected = concat([op(string_series) for op in ops], axis=1)
+ expected.columns = names
+ result = string_series.transform(ops)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_transform_listlike_func_with_args():
+ # GH 50624
+
+ s = Series([1, 2, 3])
+
+ def foo1(x, a=1, c=0):
+ return x + a + c
+
+ def foo2(x, b=2, c=0):
+ return x + b + c
+
+ msg = r"foo1\(\) got an unexpected keyword argument 'b'"
+ with pytest.raises(TypeError, match=msg):
+ s.transform([foo1, foo2], 0, 3, b=3, c=4)
+
+ result = s.transform([foo1, foo2], 0, 3, c=4)
+ expected = DataFrame({"foo1": [8, 9, 10], "foo2": [8, 9, 10]})
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("box", [dict, Series])
+def test_transform_dictlike(string_series, box):
+ # GH 35964
+ with np.errstate(all="ignore"):
+ expected = concat([np.sqrt(string_series), np.abs(string_series)], axis=1)
+ expected.columns = ["foo", "bar"]
+ result = string_series.transform(box({"foo": np.sqrt, "bar": np.abs}))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_transform_dictlike_mixed():
+ # GH 40018 - mix of lists and non-lists in values of a dictionary
+ df = Series([1, 4])
+ result = df.transform({"b": ["sqrt", "abs"], "c": "sqrt"})
+ expected = DataFrame(
+ [[1.0, 1, 1.0], [2.0, 4, 2.0]],
+ columns=MultiIndex([("b", "c"), ("sqrt", "abs")], [(0, 0, 1), (0, 1, 0)]),
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_str.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_str.py
new file mode 100644
index 0000000000000000000000000000000000000000..363d0285cabbc854ae6d824ffcff68dc6ef61a84
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/apply/test_str.py
@@ -0,0 +1,314 @@
+from itertools import chain
+import operator
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.common import is_number
+
+from pandas import (
+ DataFrame,
+ Series,
+)
+import pandas._testing as tm
+from pandas.tests.apply.common import (
+ frame_transform_kernels,
+ series_transform_kernels,
+)
+
+
+@pytest.mark.parametrize("func", ["sum", "mean", "min", "max", "std"])
+@pytest.mark.parametrize(
+ "args,kwds",
+ [
+ pytest.param([], {}, id="no_args_or_kwds"),
+ pytest.param([1], {}, id="axis_from_args"),
+ pytest.param([], {"axis": 1}, id="axis_from_kwds"),
+ pytest.param([], {"numeric_only": True}, id="optional_kwds"),
+ pytest.param([1, True], {"numeric_only": True}, id="args_and_kwds"),
+ ],
+)
+@pytest.mark.parametrize("how", ["agg", "apply"])
+def test_apply_with_string_funcs(request, float_frame, func, args, kwds, how):
+ if len(args) > 1 and how == "agg":
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=TypeError,
+ reason="agg/apply signature mismatch - agg passes 2nd "
+ "argument to func",
+ )
+ )
+ result = getattr(float_frame, how)(func, *args, **kwds)
+ expected = getattr(float_frame, func)(*args, **kwds)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("arg", ["sum", "mean", "min", "max", "std"])
+def test_with_string_args(datetime_series, arg):
+ result = datetime_series.apply(arg)
+ expected = getattr(datetime_series, arg)()
+ assert result == expected
+
+
+@pytest.mark.parametrize("op", ["mean", "median", "std", "var"])
+@pytest.mark.parametrize("how", ["agg", "apply"])
+def test_apply_np_reducer(op, how):
+ # GH 39116
+ float_frame = DataFrame({"a": [1, 2], "b": [3, 4]})
+ result = getattr(float_frame, how)(op)
+ # pandas ddof defaults to 1, numpy to 0
+ kwargs = {"ddof": 1} if op in ("std", "var") else {}
+ expected = Series(
+ getattr(np, op)(float_frame, axis=0, **kwargs), index=float_frame.columns
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "op", ["abs", "ceil", "cos", "cumsum", "exp", "log", "sqrt", "square"]
+)
+@pytest.mark.parametrize("how", ["transform", "apply"])
+def test_apply_np_transformer(float_frame, op, how):
+ # GH 39116
+
+ # float_frame will _usually_ have negative values, which will
+ # trigger the warning here, but let's put one in just to be sure
+ float_frame.iloc[0, 0] = -1.0
+ warn = None
+ if op in ["log", "sqrt"]:
+ warn = RuntimeWarning
+
+ with tm.assert_produces_warning(warn, check_stacklevel=False):
+ # float_frame fixture is defined in conftest.py, so we don't check the
+ # stacklevel as otherwise the test would fail.
+ result = getattr(float_frame, how)(op)
+ expected = getattr(np, op)(float_frame)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "series, func, expected",
+ chain(
+ tm.get_cython_table_params(
+ Series(dtype=np.float64),
+ [
+ ("sum", 0),
+ ("max", np.nan),
+ ("min", np.nan),
+ ("all", True),
+ ("any", False),
+ ("mean", np.nan),
+ ("prod", 1),
+ ("std", np.nan),
+ ("var", np.nan),
+ ("median", np.nan),
+ ],
+ ),
+ tm.get_cython_table_params(
+ Series([np.nan, 1, 2, 3]),
+ [
+ ("sum", 6),
+ ("max", 3),
+ ("min", 1),
+ ("all", True),
+ ("any", True),
+ ("mean", 2),
+ ("prod", 6),
+ ("std", 1),
+ ("var", 1),
+ ("median", 2),
+ ],
+ ),
+ tm.get_cython_table_params(
+ Series("a b c".split()),
+ [
+ ("sum", "abc"),
+ ("max", "c"),
+ ("min", "a"),
+ ("all", True),
+ ("any", True),
+ ],
+ ),
+ ),
+)
+def test_agg_cython_table_series(series, func, expected):
+ # GH21224
+ # test reducing functions in
+ # pandas.core.base.SelectionMixin._cython_table
+ warn = None if isinstance(func, str) else FutureWarning
+ with tm.assert_produces_warning(warn, match="is currently using Series.*"):
+ result = series.agg(func)
+ if is_number(expected):
+ assert np.isclose(result, expected, equal_nan=True)
+ else:
+ assert result == expected
+
+
+@pytest.mark.parametrize(
+ "series, func, expected",
+ chain(
+ tm.get_cython_table_params(
+ Series(dtype=np.float64),
+ [
+ ("cumprod", Series([], dtype=np.float64)),
+ ("cumsum", Series([], dtype=np.float64)),
+ ],
+ ),
+ tm.get_cython_table_params(
+ Series([np.nan, 1, 2, 3]),
+ [
+ ("cumprod", Series([np.nan, 1, 2, 6])),
+ ("cumsum", Series([np.nan, 1, 3, 6])),
+ ],
+ ),
+ tm.get_cython_table_params(
+ Series("a b c".split()), [("cumsum", Series(["a", "ab", "abc"]))]
+ ),
+ ),
+)
+def test_agg_cython_table_transform_series(series, func, expected):
+ # GH21224
+ # test transforming functions in
+ # pandas.core.base.SelectionMixin._cython_table (cumprod, cumsum)
+ warn = None if isinstance(func, str) else FutureWarning
+ with tm.assert_produces_warning(warn, match="is currently using Series.*"):
+ result = series.agg(func)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "df, func, expected",
+ chain(
+ tm.get_cython_table_params(
+ DataFrame(),
+ [
+ ("sum", Series(dtype="float64")),
+ ("max", Series(dtype="float64")),
+ ("min", Series(dtype="float64")),
+ ("all", Series(dtype=bool)),
+ ("any", Series(dtype=bool)),
+ ("mean", Series(dtype="float64")),
+ ("prod", Series(dtype="float64")),
+ ("std", Series(dtype="float64")),
+ ("var", Series(dtype="float64")),
+ ("median", Series(dtype="float64")),
+ ],
+ ),
+ tm.get_cython_table_params(
+ DataFrame([[np.nan, 1], [1, 2]]),
+ [
+ ("sum", Series([1.0, 3])),
+ ("max", Series([1.0, 2])),
+ ("min", Series([1.0, 1])),
+ ("all", Series([True, True])),
+ ("any", Series([True, True])),
+ ("mean", Series([1, 1.5])),
+ ("prod", Series([1.0, 2])),
+ ("std", Series([np.nan, 0.707107])),
+ ("var", Series([np.nan, 0.5])),
+ ("median", Series([1, 1.5])),
+ ],
+ ),
+ ),
+)
+def test_agg_cython_table_frame(df, func, expected, axis):
+ # GH 21224
+ # test reducing functions in
+ # pandas.core.base.SelectionMixin._cython_table
+ warn = None if isinstance(func, str) else FutureWarning
+ with tm.assert_produces_warning(warn, match="is currently using DataFrame.*"):
+ # GH#53425
+ result = df.agg(func, axis=axis)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "df, func, expected",
+ chain(
+ tm.get_cython_table_params(
+ DataFrame(), [("cumprod", DataFrame()), ("cumsum", DataFrame())]
+ ),
+ tm.get_cython_table_params(
+ DataFrame([[np.nan, 1], [1, 2]]),
+ [
+ ("cumprod", DataFrame([[np.nan, 1], [1, 2]])),
+ ("cumsum", DataFrame([[np.nan, 1], [1, 3]])),
+ ],
+ ),
+ ),
+)
+def test_agg_cython_table_transform_frame(df, func, expected, axis):
+ # GH 21224
+ # test transforming functions in
+ # pandas.core.base.SelectionMixin._cython_table (cumprod, cumsum)
+ if axis in ("columns", 1):
+ # operating blockwise doesn't let us preserve dtypes
+ expected = expected.astype("float64")
+
+ warn = None if isinstance(func, str) else FutureWarning
+ with tm.assert_produces_warning(warn, match="is currently using DataFrame.*"):
+ # GH#53425
+ result = df.agg(func, axis=axis)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("op", series_transform_kernels)
+def test_transform_groupby_kernel_series(request, string_series, op):
+ # GH 35964
+ if op == "ngroup":
+ request.node.add_marker(
+ pytest.mark.xfail(raises=ValueError, reason="ngroup not valid for NDFrame")
+ )
+ args = [0.0] if op == "fillna" else []
+ ones = np.ones(string_series.shape[0])
+ expected = string_series.groupby(ones).transform(op, *args)
+ result = string_series.transform(op, 0, *args)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("op", frame_transform_kernels)
+def test_transform_groupby_kernel_frame(request, axis, float_frame, op):
+ if op == "ngroup":
+ request.node.add_marker(
+ pytest.mark.xfail(raises=ValueError, reason="ngroup not valid for NDFrame")
+ )
+
+ # GH 35964
+
+ args = [0.0] if op == "fillna" else []
+ if axis in (0, "index"):
+ ones = np.ones(float_frame.shape[0])
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ else:
+ ones = np.ones(float_frame.shape[1])
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = float_frame.groupby(ones, axis=axis)
+ expected = gb.transform(op, *args)
+ result = float_frame.transform(op, axis, *args)
+ tm.assert_frame_equal(result, expected)
+
+ # same thing, but ensuring we have multiple blocks
+ assert "E" not in float_frame.columns
+ float_frame["E"] = float_frame["A"].copy()
+ assert len(float_frame._mgr.arrays) > 1
+
+ if axis in (0, "index"):
+ ones = np.ones(float_frame.shape[0])
+ else:
+ ones = np.ones(float_frame.shape[1])
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb2 = float_frame.groupby(ones, axis=axis)
+ expected2 = gb2.transform(op, *args)
+ result2 = float_frame.transform(op, axis, *args)
+ tm.assert_frame_equal(result2, expected2)
+
+
+@pytest.mark.parametrize("method", ["abs", "shift", "pct_change", "cumsum", "rank"])
+def test_transform_method_name(method):
+ # GH 19760
+ df = DataFrame({"A": [-1, 2]})
+ result = df.transform(method)
+ expected = operator.methodcaller(method)(df)
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..b608df1554154f4723a0147ea02c04c780839c65
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/common.py
@@ -0,0 +1,155 @@
+"""
+Assertion helpers for arithmetic tests.
+"""
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ array,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ BooleanArray,
+ NumpyExtensionArray,
+)
+
+
+def assert_cannot_add(left, right, msg="cannot add"):
+ """
+ Helper to assert that left and right cannot be added.
+
+ Parameters
+ ----------
+ left : object
+ right : object
+ msg : str, default "cannot add"
+ """
+ with pytest.raises(TypeError, match=msg):
+ left + right
+ with pytest.raises(TypeError, match=msg):
+ right + left
+
+
+def assert_invalid_addsub_type(left, right, msg=None):
+ """
+ Helper to assert that left and right can be neither added nor subtracted.
+
+ Parameters
+ ----------
+ left : object
+ right : object
+ msg : str or None, default None
+ """
+ with pytest.raises(TypeError, match=msg):
+ left + right
+ with pytest.raises(TypeError, match=msg):
+ right + left
+ with pytest.raises(TypeError, match=msg):
+ left - right
+ with pytest.raises(TypeError, match=msg):
+ right - left
+
+
+def get_upcast_box(left, right, is_cmp: bool = False):
+ """
+ Get the box to use for 'expected' in an arithmetic or comparison operation.
+
+ Parameters
+ left : Any
+ right : Any
+ is_cmp : bool, default False
+ Whether the operation is a comparison method.
+ """
+
+ if isinstance(left, DataFrame) or isinstance(right, DataFrame):
+ return DataFrame
+ if isinstance(left, Series) or isinstance(right, Series):
+ if is_cmp and isinstance(left, Index):
+ # Index does not defer for comparisons
+ return np.array
+ return Series
+ if isinstance(left, Index) or isinstance(right, Index):
+ if is_cmp:
+ return np.array
+ return Index
+ return tm.to_array
+
+
+def assert_invalid_comparison(left, right, box):
+ """
+ Assert that comparison operations with mismatched types behave correctly.
+
+ Parameters
+ ----------
+ left : np.ndarray, ExtensionArray, Index, or Series
+ right : object
+ box : {pd.DataFrame, pd.Series, pd.Index, pd.array, tm.to_array}
+ """
+ # Not for tznaive-tzaware comparison
+
+ # Note: not quite the same as how we do this for tm.box_expected
+ xbox = box if box not in [Index, array] else np.array
+
+ def xbox2(x):
+ # Eventually we'd like this to be tighter, but for now we'll
+ # just exclude NumpyExtensionArray[bool]
+ if isinstance(x, NumpyExtensionArray):
+ return x._ndarray
+ if isinstance(x, BooleanArray):
+ # NB: we are assuming no pd.NAs for now
+ return x.astype(bool)
+ return x
+
+ # rev_box: box to use for reversed comparisons
+ rev_box = xbox
+ if isinstance(right, Index) and isinstance(left, Series):
+ rev_box = np.array
+
+ result = xbox2(left == right)
+ expected = xbox(np.zeros(result.shape, dtype=np.bool_))
+
+ tm.assert_equal(result, expected)
+
+ result = xbox2(right == left)
+ tm.assert_equal(result, rev_box(expected))
+
+ result = xbox2(left != right)
+ tm.assert_equal(result, ~expected)
+
+ result = xbox2(right != left)
+ tm.assert_equal(result, rev_box(~expected))
+
+ msg = "|".join(
+ [
+ "Invalid comparison between",
+ "Cannot compare type",
+ "not supported between",
+ "invalid type promotion",
+ (
+ # GH#36706 npdev 1.20.0 2020-09-28
+ r"The DTypes and "
+ r" do not have a common DType. "
+ "For example they cannot be stored in a single array unless the "
+ "dtype is `object`."
+ ),
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ left < right
+ with pytest.raises(TypeError, match=msg):
+ left <= right
+ with pytest.raises(TypeError, match=msg):
+ left > right
+ with pytest.raises(TypeError, match=msg):
+ left >= right
+ with pytest.raises(TypeError, match=msg):
+ right < left
+ with pytest.raises(TypeError, match=msg):
+ right <= left
+ with pytest.raises(TypeError, match=msg):
+ right > left
+ with pytest.raises(TypeError, match=msg):
+ right >= left
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dd5169202ba475d22e343da97bd7f97f03b48a5
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/conftest.py
@@ -0,0 +1,228 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ Index,
+ RangeIndex,
+)
+import pandas._testing as tm
+from pandas.core.computation import expressions as expr
+
+
+@pytest.fixture(autouse=True, params=[0, 1000000], ids=["numexpr", "python"])
+def switch_numexpr_min_elements(request):
+ _MIN_ELEMENTS = expr._MIN_ELEMENTS
+ expr._MIN_ELEMENTS = request.param
+ yield request.param
+ expr._MIN_ELEMENTS = _MIN_ELEMENTS
+
+
+# ------------------------------------------------------------------
+
+
+# doctest with +SKIP for one fixture fails during setup with
+# 'DoctestItem' object has no attribute 'callspec'
+# due to switch_numexpr_min_elements fixture
+@pytest.fixture(params=[1, np.array(1, dtype=np.int64)])
+def one(request):
+ """
+ Several variants of integer value 1. The zero-dim integer array
+ behaves like an integer.
+
+ This fixture can be used to check that datetimelike indexes handle
+ addition and subtraction of integers and zero-dimensional arrays
+ of integers.
+
+ Examples
+ --------
+ dti = pd.date_range('2016-01-01', periods=2, freq='H')
+ dti
+ DatetimeIndex(['2016-01-01 00:00:00', '2016-01-01 01:00:00'],
+ dtype='datetime64[ns]', freq='H')
+ dti + one
+ DatetimeIndex(['2016-01-01 01:00:00', '2016-01-01 02:00:00'],
+ dtype='datetime64[ns]', freq='H')
+ """
+ return request.param
+
+
+zeros = [
+ box_cls([0] * 5, dtype=dtype)
+ for box_cls in [Index, np.array, pd.array]
+ for dtype in [np.int64, np.uint64, np.float64]
+]
+zeros.extend([box_cls([-0.0] * 5, dtype=np.float64) for box_cls in [Index, np.array]])
+zeros.extend([np.array(0, dtype=dtype) for dtype in [np.int64, np.uint64, np.float64]])
+zeros.extend([np.array(-0.0, dtype=np.float64)])
+zeros.extend([0, 0.0, -0.0])
+
+
+# doctest with +SKIP for zero fixture fails during setup with
+# 'DoctestItem' object has no attribute 'callspec'
+# due to switch_numexpr_min_elements fixture
+@pytest.fixture(params=zeros)
+def zero(request):
+ """
+ Several types of scalar zeros and length 5 vectors of zeros.
+
+ This fixture can be used to check that numeric-dtype indexes handle
+ division by any zero numeric-dtype.
+
+ Uses vector of length 5 for broadcasting with `numeric_idx` fixture,
+ which creates numeric-dtype vectors also of length 5.
+
+ Examples
+ --------
+ arr = RangeIndex(5)
+ arr / zeros
+ Index([nan, inf, inf, inf, inf], dtype='float64')
+ """
+ return request.param
+
+
+# ------------------------------------------------------------------
+# Vector Fixtures
+
+
+@pytest.fixture(
+ params=[
+ # TODO: add more dtypes here
+ Index(np.arange(5, dtype="float64")),
+ Index(np.arange(5, dtype="int64")),
+ Index(np.arange(5, dtype="uint64")),
+ RangeIndex(5),
+ ],
+ ids=lambda x: type(x).__name__,
+)
+def numeric_idx(request):
+ """
+ Several types of numeric-dtypes Index objects
+ """
+ return request.param
+
+
+# ------------------------------------------------------------------
+# Scalar Fixtures
+
+
+@pytest.fixture(
+ params=[
+ pd.Timedelta("10m7s").to_pytimedelta(),
+ pd.Timedelta("10m7s"),
+ pd.Timedelta("10m7s").to_timedelta64(),
+ ],
+ ids=lambda x: type(x).__name__,
+)
+def scalar_td(request):
+ """
+ Several variants of Timedelta scalars representing 10 minutes and 7 seconds.
+ """
+ return request.param
+
+
+@pytest.fixture(
+ params=[
+ pd.offsets.Day(3),
+ pd.offsets.Hour(72),
+ pd.Timedelta(days=3).to_pytimedelta(),
+ pd.Timedelta("72:00:00"),
+ np.timedelta64(3, "D"),
+ np.timedelta64(72, "h"),
+ ],
+ ids=lambda x: type(x).__name__,
+)
+def three_days(request):
+ """
+ Several timedelta-like and DateOffset objects that each represent
+ a 3-day timedelta
+ """
+ return request.param
+
+
+@pytest.fixture(
+ params=[
+ pd.offsets.Hour(2),
+ pd.offsets.Minute(120),
+ pd.Timedelta(hours=2).to_pytimedelta(),
+ pd.Timedelta(seconds=2 * 3600),
+ np.timedelta64(2, "h"),
+ np.timedelta64(120, "m"),
+ ],
+ ids=lambda x: type(x).__name__,
+)
+def two_hours(request):
+ """
+ Several timedelta-like and DateOffset objects that each represent
+ a 2-hour timedelta
+ """
+ return request.param
+
+
+_common_mismatch = [
+ pd.offsets.YearBegin(2),
+ pd.offsets.MonthBegin(1),
+ pd.offsets.Minute(),
+]
+
+
+@pytest.fixture(
+ params=[
+ pd.Timedelta(minutes=30).to_pytimedelta(),
+ np.timedelta64(30, "s"),
+ pd.Timedelta(seconds=30),
+ ]
+ + _common_mismatch
+)
+def not_hourly(request):
+ """
+ Several timedelta-like and DateOffset instances that are _not_
+ compatible with Hourly frequencies.
+ """
+ return request.param
+
+
+@pytest.fixture(
+ params=[
+ np.timedelta64(4, "h"),
+ pd.Timedelta(hours=23).to_pytimedelta(),
+ pd.Timedelta("23:00:00"),
+ ]
+ + _common_mismatch
+)
+def not_daily(request):
+ """
+ Several timedelta-like and DateOffset instances that are _not_
+ compatible with Daily frequencies.
+ """
+ return request.param
+
+
+@pytest.fixture(
+ params=[
+ np.timedelta64(365, "D"),
+ pd.Timedelta(days=365).to_pytimedelta(),
+ pd.Timedelta(days=365),
+ ]
+ + _common_mismatch
+)
+def mismatched_freq(request):
+ """
+ Several timedelta-like and DateOffset instances that are _not_
+ compatible with Monthly or Annual frequencies.
+ """
+ return request.param
+
+
+# ------------------------------------------------------------------
+
+
+@pytest.fixture(
+ params=[Index, pd.Series, tm.to_array, np.array, list], ids=lambda x: x.__name__
+)
+def box_1d_array(request):
+ """
+ Fixture to test behavior for Index, Series, tm.to_array, numpy Array and list
+ classes
+ """
+ return request.param
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_array_ops.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_array_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c347d965bbf7353a6a4e81ca955341f8041b6de
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_array_ops.py
@@ -0,0 +1,39 @@
+import operator
+
+import numpy as np
+import pytest
+
+import pandas._testing as tm
+from pandas.core.ops.array_ops import (
+ comparison_op,
+ na_logical_op,
+)
+
+
+def test_na_logical_op_2d():
+ left = np.arange(8).reshape(4, 2)
+ right = left.astype(object)
+ right[0, 0] = np.nan
+
+ # Check that we fall back to the vec_binop branch
+ with pytest.raises(TypeError, match="unsupported operand type"):
+ operator.or_(left, right)
+
+ result = na_logical_op(left, right, operator.or_)
+ expected = right
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_object_comparison_2d():
+ left = np.arange(9).reshape(3, 3).astype(object)
+ right = left.T
+
+ result = comparison_op(left, right, operator.eq)
+ expected = np.eye(3).astype(bool)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # Ensure that cython doesn't raise on non-writeable arg, which
+ # we can get from np.broadcast_to
+ right.flags.writeable = False
+ result = comparison_op(left, right, operator.ne)
+ tm.assert_numpy_array_equal(result, ~expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_categorical.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_categorical.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6f3a13ce670596a12ca10b9e8d02d69d63c96fb
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_categorical.py
@@ -0,0 +1,25 @@
+import numpy as np
+
+from pandas import (
+ Categorical,
+ Series,
+)
+import pandas._testing as tm
+
+
+class TestCategoricalComparisons:
+ def test_categorical_nan_equality(self):
+ cat = Series(Categorical(["a", "b", "c", np.nan]))
+ expected = Series([True, True, True, False])
+ result = cat == cat
+ tm.assert_series_equal(result, expected)
+
+ def test_categorical_tuple_equality(self):
+ # GH 18050
+ ser = Series([(0, 0), (0, 1), (0, 0), (1, 0), (1, 1)])
+ expected = Series([True, False, True, False, False])
+ result = ser == (0, 0)
+ tm.assert_series_equal(result, expected)
+
+ result = ser.astype("category") == (0, 0)
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_datetime64.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_datetime64.py
new file mode 100644
index 0000000000000000000000000000000000000000..34b526bf9740817f7847511144de5aea00ee2d46
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_datetime64.py
@@ -0,0 +1,2470 @@
+# Arithmetic tests for DataFrame/Series/Index/Array classes that should
+# behave identically.
+# Specifically for datetime64 and datetime64tz dtypes
+from datetime import (
+ datetime,
+ time,
+ timedelta,
+)
+from itertools import (
+ product,
+ starmap,
+)
+import operator
+
+import numpy as np
+import pytest
+import pytz
+
+from pandas._libs.tslibs.conversion import localize_pydatetime
+from pandas._libs.tslibs.offsets import shift_months
+from pandas.errors import PerformanceWarning
+
+import pandas as pd
+from pandas import (
+ DateOffset,
+ DatetimeIndex,
+ NaT,
+ Period,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.core import roperator
+from pandas.tests.arithmetic.common import (
+ assert_cannot_add,
+ assert_invalid_addsub_type,
+ assert_invalid_comparison,
+ get_upcast_box,
+)
+
+# ------------------------------------------------------------------
+# Comparisons
+
+
+class TestDatetime64ArrayLikeComparisons:
+ # Comparison tests for datetime64 vectors fully parametrized over
+ # DataFrame/Series/DatetimeIndex/DatetimeArray. Ideally all comparison
+ # tests will eventually end up here.
+
+ def test_compare_zerodim(self, tz_naive_fixture, box_with_array):
+ # Test comparison with zero-dimensional array is unboxed
+ tz = tz_naive_fixture
+ box = box_with_array
+ dti = date_range("20130101", periods=3, tz=tz)
+
+ other = np.array(dti.to_numpy()[0])
+
+ dtarr = tm.box_expected(dti, box)
+ xbox = get_upcast_box(dtarr, other, True)
+ result = dtarr <= other
+ expected = np.array([True, False, False])
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ "foo",
+ -1,
+ 99,
+ 4.0,
+ object(),
+ timedelta(days=2),
+ # GH#19800, GH#19301 datetime.date comparison raises to
+ # match DatetimeIndex/Timestamp. This also matches the behavior
+ # of stdlib datetime.datetime
+ datetime(2001, 1, 1).date(),
+ # GH#19301 None and NaN are *not* cast to NaT for comparisons
+ None,
+ np.nan,
+ ],
+ )
+ def test_dt64arr_cmp_scalar_invalid(self, other, tz_naive_fixture, box_with_array):
+ # GH#22074, GH#15966
+ tz = tz_naive_fixture
+
+ rng = date_range("1/1/2000", periods=10, tz=tz)
+ dtarr = tm.box_expected(rng, box_with_array)
+ assert_invalid_comparison(dtarr, other, box_with_array)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ # GH#4968 invalid date/int comparisons
+ list(range(10)),
+ np.arange(10),
+ np.arange(10).astype(np.float32),
+ np.arange(10).astype(object),
+ pd.timedelta_range("1ns", periods=10).array,
+ np.array(pd.timedelta_range("1ns", periods=10)),
+ list(pd.timedelta_range("1ns", periods=10)),
+ pd.timedelta_range("1 Day", periods=10).astype(object),
+ pd.period_range("1971-01-01", freq="D", periods=10).array,
+ pd.period_range("1971-01-01", freq="D", periods=10).astype(object),
+ ],
+ )
+ def test_dt64arr_cmp_arraylike_invalid(
+ self, other, tz_naive_fixture, box_with_array
+ ):
+ tz = tz_naive_fixture
+
+ dta = date_range("1970-01-01", freq="ns", periods=10, tz=tz)._data
+ obj = tm.box_expected(dta, box_with_array)
+ assert_invalid_comparison(obj, other, box_with_array)
+
+ def test_dt64arr_cmp_mixed_invalid(self, tz_naive_fixture):
+ tz = tz_naive_fixture
+
+ dta = date_range("1970-01-01", freq="h", periods=5, tz=tz)._data
+
+ other = np.array([0, 1, 2, dta[3], Timedelta(days=1)])
+ result = dta == other
+ expected = np.array([False, False, False, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = dta != other
+ tm.assert_numpy_array_equal(result, ~expected)
+
+ msg = "Invalid comparison between|Cannot compare type|not supported between"
+ with pytest.raises(TypeError, match=msg):
+ dta < other
+ with pytest.raises(TypeError, match=msg):
+ dta > other
+ with pytest.raises(TypeError, match=msg):
+ dta <= other
+ with pytest.raises(TypeError, match=msg):
+ dta >= other
+
+ def test_dt64arr_nat_comparison(self, tz_naive_fixture, box_with_array):
+ # GH#22242, GH#22163 DataFrame considered NaT == ts incorrectly
+ tz = tz_naive_fixture
+ box = box_with_array
+
+ ts = Timestamp("2021-01-01", tz=tz)
+ ser = Series([ts, NaT])
+
+ obj = tm.box_expected(ser, box)
+ xbox = get_upcast_box(obj, ts, True)
+
+ expected = Series([True, False], dtype=np.bool_)
+ expected = tm.box_expected(expected, xbox)
+
+ result = obj == ts
+ tm.assert_equal(result, expected)
+
+
+class TestDatetime64SeriesComparison:
+ # TODO: moved from tests.series.test_operators; needs cleanup
+
+ @pytest.mark.parametrize(
+ "pair",
+ [
+ (
+ [Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")],
+ [NaT, NaT, Timestamp("2011-01-03")],
+ ),
+ (
+ [Timedelta("1 days"), NaT, Timedelta("3 days")],
+ [NaT, NaT, Timedelta("3 days")],
+ ),
+ (
+ [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")],
+ [NaT, NaT, Period("2011-03", freq="M")],
+ ),
+ ],
+ )
+ @pytest.mark.parametrize("reverse", [True, False])
+ @pytest.mark.parametrize("dtype", [None, object])
+ @pytest.mark.parametrize(
+ "op, expected",
+ [
+ (operator.eq, Series([False, False, True])),
+ (operator.ne, Series([True, True, False])),
+ (operator.lt, Series([False, False, False])),
+ (operator.gt, Series([False, False, False])),
+ (operator.ge, Series([False, False, True])),
+ (operator.le, Series([False, False, True])),
+ ],
+ )
+ def test_nat_comparisons(
+ self,
+ dtype,
+ index_or_series,
+ reverse,
+ pair,
+ op,
+ expected,
+ ):
+ box = index_or_series
+ lhs, rhs = pair
+ if reverse:
+ # add lhs / rhs switched data
+ lhs, rhs = rhs, lhs
+
+ left = Series(lhs, dtype=dtype)
+ right = box(rhs, dtype=dtype)
+
+ result = op(left, right)
+
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "data",
+ [
+ [Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")],
+ [Timedelta("1 days"), NaT, Timedelta("3 days")],
+ [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")],
+ ],
+ )
+ @pytest.mark.parametrize("dtype", [None, object])
+ def test_nat_comparisons_scalar(self, dtype, data, box_with_array):
+ box = box_with_array
+
+ left = Series(data, dtype=dtype)
+ left = tm.box_expected(left, box)
+ xbox = get_upcast_box(left, NaT, True)
+
+ expected = [False, False, False]
+ expected = tm.box_expected(expected, xbox)
+ if box is pd.array and dtype is object:
+ expected = pd.array(expected, dtype="bool")
+
+ tm.assert_equal(left == NaT, expected)
+ tm.assert_equal(NaT == left, expected)
+
+ expected = [True, True, True]
+ expected = tm.box_expected(expected, xbox)
+ if box is pd.array and dtype is object:
+ expected = pd.array(expected, dtype="bool")
+ tm.assert_equal(left != NaT, expected)
+ tm.assert_equal(NaT != left, expected)
+
+ expected = [False, False, False]
+ expected = tm.box_expected(expected, xbox)
+ if box is pd.array and dtype is object:
+ expected = pd.array(expected, dtype="bool")
+ tm.assert_equal(left < NaT, expected)
+ tm.assert_equal(NaT > left, expected)
+ tm.assert_equal(left <= NaT, expected)
+ tm.assert_equal(NaT >= left, expected)
+
+ tm.assert_equal(left > NaT, expected)
+ tm.assert_equal(NaT < left, expected)
+ tm.assert_equal(left >= NaT, expected)
+ tm.assert_equal(NaT <= left, expected)
+
+ @pytest.mark.parametrize("val", [datetime(2000, 1, 4), datetime(2000, 1, 5)])
+ def test_series_comparison_scalars(self, val):
+ series = Series(date_range("1/1/2000", periods=10))
+
+ result = series > val
+ expected = Series([x > val for x in series])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "left,right", [("lt", "gt"), ("le", "ge"), ("eq", "eq"), ("ne", "ne")]
+ )
+ def test_timestamp_compare_series(self, left, right):
+ # see gh-4982
+ # Make sure we can compare Timestamps on the right AND left hand side.
+ ser = Series(date_range("20010101", periods=10), name="dates")
+ s_nat = ser.copy(deep=True)
+
+ ser[0] = Timestamp("nat")
+ ser[3] = Timestamp("nat")
+
+ left_f = getattr(operator, left)
+ right_f = getattr(operator, right)
+
+ # No NaT
+ expected = left_f(ser, Timestamp("20010109"))
+ result = right_f(Timestamp("20010109"), ser)
+ tm.assert_series_equal(result, expected)
+
+ # NaT
+ expected = left_f(ser, Timestamp("nat"))
+ result = right_f(Timestamp("nat"), ser)
+ tm.assert_series_equal(result, expected)
+
+ # Compare to Timestamp with series containing NaT
+ expected = left_f(s_nat, Timestamp("20010109"))
+ result = right_f(Timestamp("20010109"), s_nat)
+ tm.assert_series_equal(result, expected)
+
+ # Compare to NaT with series containing NaT
+ expected = left_f(s_nat, NaT)
+ result = right_f(NaT, s_nat)
+ tm.assert_series_equal(result, expected)
+
+ def test_dt64arr_timestamp_equality(self, box_with_array):
+ # GH#11034
+ box = box_with_array
+
+ ser = Series([Timestamp("2000-01-29 01:59:00"), Timestamp("2000-01-30"), NaT])
+ ser = tm.box_expected(ser, box)
+ xbox = get_upcast_box(ser, ser, True)
+
+ result = ser != ser
+ expected = tm.box_expected([False, False, True], xbox)
+ tm.assert_equal(result, expected)
+
+ if box is pd.DataFrame:
+ # alignment for frame vs series comparisons deprecated
+ # in GH#46795 enforced 2.0
+ with pytest.raises(ValueError, match="not aligned"):
+ ser != ser[0]
+
+ else:
+ result = ser != ser[0]
+ expected = tm.box_expected([False, True, True], xbox)
+ tm.assert_equal(result, expected)
+
+ if box is pd.DataFrame:
+ # alignment for frame vs series comparisons deprecated
+ # in GH#46795 enforced 2.0
+ with pytest.raises(ValueError, match="not aligned"):
+ ser != ser[2]
+ else:
+ result = ser != ser[2]
+ expected = tm.box_expected([True, True, True], xbox)
+ tm.assert_equal(result, expected)
+
+ result = ser == ser
+ expected = tm.box_expected([True, True, False], xbox)
+ tm.assert_equal(result, expected)
+
+ if box is pd.DataFrame:
+ # alignment for frame vs series comparisons deprecated
+ # in GH#46795 enforced 2.0
+ with pytest.raises(ValueError, match="not aligned"):
+ ser == ser[0]
+ else:
+ result = ser == ser[0]
+ expected = tm.box_expected([True, False, False], xbox)
+ tm.assert_equal(result, expected)
+
+ if box is pd.DataFrame:
+ # alignment for frame vs series comparisons deprecated
+ # in GH#46795 enforced 2.0
+ with pytest.raises(ValueError, match="not aligned"):
+ ser == ser[2]
+ else:
+ result = ser == ser[2]
+ expected = tm.box_expected([False, False, False], xbox)
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "datetimelike",
+ [
+ Timestamp("20130101"),
+ datetime(2013, 1, 1),
+ np.datetime64("2013-01-01T00:00", "ns"),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "op,expected",
+ [
+ (operator.lt, [True, False, False, False]),
+ (operator.le, [True, True, False, False]),
+ (operator.eq, [False, True, False, False]),
+ (operator.gt, [False, False, False, True]),
+ ],
+ )
+ def test_dt64_compare_datetime_scalar(self, datetimelike, op, expected):
+ # GH#17965, test for ability to compare datetime64[ns] columns
+ # to datetimelike
+ ser = Series(
+ [
+ Timestamp("20120101"),
+ Timestamp("20130101"),
+ np.nan,
+ Timestamp("20130103"),
+ ],
+ name="A",
+ )
+ result = op(ser, datetimelike)
+ expected = Series(expected, name="A")
+ tm.assert_series_equal(result, expected)
+
+
+class TestDatetimeIndexComparisons:
+ # TODO: moved from tests.indexes.test_base; parametrize and de-duplicate
+ def test_comparators(self, comparison_op):
+ index = tm.makeDateIndex(100)
+ element = index[len(index) // 2]
+ element = Timestamp(element).to_datetime64()
+
+ arr = np.array(index)
+ arr_result = comparison_op(arr, element)
+ index_result = comparison_op(index, element)
+
+ assert isinstance(index_result, np.ndarray)
+ tm.assert_numpy_array_equal(arr_result, index_result)
+
+ @pytest.mark.parametrize(
+ "other",
+ [datetime(2016, 1, 1), Timestamp("2016-01-01"), np.datetime64("2016-01-01")],
+ )
+ def test_dti_cmp_datetimelike(self, other, tz_naive_fixture):
+ tz = tz_naive_fixture
+ dti = date_range("2016-01-01", periods=2, tz=tz)
+ if tz is not None:
+ if isinstance(other, np.datetime64):
+ pytest.skip("no tzaware version available")
+ other = localize_pydatetime(other, dti.tzinfo)
+
+ result = dti == other
+ expected = np.array([True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = dti > other
+ expected = np.array([False, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = dti >= other
+ expected = np.array([True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = dti < other
+ expected = np.array([False, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = dti <= other
+ expected = np.array([True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", [None, object])
+ def test_dti_cmp_nat(self, dtype, box_with_array):
+ left = DatetimeIndex([Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")])
+ right = DatetimeIndex([NaT, NaT, Timestamp("2011-01-03")])
+
+ left = tm.box_expected(left, box_with_array)
+ right = tm.box_expected(right, box_with_array)
+ xbox = get_upcast_box(left, right, True)
+
+ lhs, rhs = left, right
+ if dtype is object:
+ lhs, rhs = left.astype(object), right.astype(object)
+
+ result = rhs == lhs
+ expected = np.array([False, False, True])
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(result, expected)
+
+ result = lhs != rhs
+ expected = np.array([True, True, False])
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(result, expected)
+
+ expected = np.array([False, False, False])
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(lhs == NaT, expected)
+ tm.assert_equal(NaT == rhs, expected)
+
+ expected = np.array([True, True, True])
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(lhs != NaT, expected)
+ tm.assert_equal(NaT != lhs, expected)
+
+ expected = np.array([False, False, False])
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(lhs < NaT, expected)
+ tm.assert_equal(NaT > lhs, expected)
+
+ def test_dti_cmp_nat_behaves_like_float_cmp_nan(self):
+ fidx1 = pd.Index([1.0, np.nan, 3.0, np.nan, 5.0, 7.0])
+ fidx2 = pd.Index([2.0, 3.0, np.nan, np.nan, 6.0, 7.0])
+
+ didx1 = DatetimeIndex(
+ ["2014-01-01", NaT, "2014-03-01", NaT, "2014-05-01", "2014-07-01"]
+ )
+ didx2 = DatetimeIndex(
+ ["2014-02-01", "2014-03-01", NaT, NaT, "2014-06-01", "2014-07-01"]
+ )
+ darr = np.array(
+ [
+ np.datetime64("2014-02-01 00:00"),
+ np.datetime64("2014-03-01 00:00"),
+ np.datetime64("nat"),
+ np.datetime64("nat"),
+ np.datetime64("2014-06-01 00:00"),
+ np.datetime64("2014-07-01 00:00"),
+ ]
+ )
+
+ cases = [(fidx1, fidx2), (didx1, didx2), (didx1, darr)]
+
+ # Check pd.NaT is handles as the same as np.nan
+ with tm.assert_produces_warning(None):
+ for idx1, idx2 in cases:
+ result = idx1 < idx2
+ expected = np.array([True, False, False, False, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx2 > idx1
+ expected = np.array([True, False, False, False, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 <= idx2
+ expected = np.array([True, False, False, False, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx2 >= idx1
+ expected = np.array([True, False, False, False, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 == idx2
+ expected = np.array([False, False, False, False, False, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 != idx2
+ expected = np.array([True, True, True, True, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ with tm.assert_produces_warning(None):
+ for idx1, val in [(fidx1, np.nan), (didx1, NaT)]:
+ result = idx1 < val
+ expected = np.array([False, False, False, False, False, False])
+ tm.assert_numpy_array_equal(result, expected)
+ result = idx1 > val
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 <= val
+ tm.assert_numpy_array_equal(result, expected)
+ result = idx1 >= val
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 == val
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 != val
+ expected = np.array([True, True, True, True, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ # Check pd.NaT is handles as the same as np.nan
+ with tm.assert_produces_warning(None):
+ for idx1, val in [(fidx1, 3), (didx1, datetime(2014, 3, 1))]:
+ result = idx1 < val
+ expected = np.array([True, False, False, False, False, False])
+ tm.assert_numpy_array_equal(result, expected)
+ result = idx1 > val
+ expected = np.array([False, False, False, False, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 <= val
+ expected = np.array([True, False, True, False, False, False])
+ tm.assert_numpy_array_equal(result, expected)
+ result = idx1 >= val
+ expected = np.array([False, False, True, False, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 == val
+ expected = np.array([False, False, True, False, False, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 != val
+ expected = np.array([True, True, False, True, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_comparison_tzawareness_compat(self, comparison_op, box_with_array):
+ # GH#18162
+ op = comparison_op
+ box = box_with_array
+
+ dr = date_range("2016-01-01", periods=6)
+ dz = dr.tz_localize("US/Pacific")
+
+ dr = tm.box_expected(dr, box)
+ dz = tm.box_expected(dz, box)
+
+ if box is pd.DataFrame:
+ tolist = lambda x: x.astype(object).values.tolist()[0]
+ else:
+ tolist = list
+
+ if op not in [operator.eq, operator.ne]:
+ msg = (
+ r"Invalid comparison between dtype=datetime64\[ns.*\] "
+ "and (Timestamp|DatetimeArray|list|ndarray)"
+ )
+ with pytest.raises(TypeError, match=msg):
+ op(dr, dz)
+
+ with pytest.raises(TypeError, match=msg):
+ op(dr, tolist(dz))
+ with pytest.raises(TypeError, match=msg):
+ op(dr, np.array(tolist(dz), dtype=object))
+ with pytest.raises(TypeError, match=msg):
+ op(dz, dr)
+
+ with pytest.raises(TypeError, match=msg):
+ op(dz, tolist(dr))
+ with pytest.raises(TypeError, match=msg):
+ op(dz, np.array(tolist(dr), dtype=object))
+
+ # The aware==aware and naive==naive comparisons should *not* raise
+ assert np.all(dr == dr)
+ assert np.all(dr == tolist(dr))
+ assert np.all(tolist(dr) == dr)
+ assert np.all(np.array(tolist(dr), dtype=object) == dr)
+ assert np.all(dr == np.array(tolist(dr), dtype=object))
+
+ assert np.all(dz == dz)
+ assert np.all(dz == tolist(dz))
+ assert np.all(tolist(dz) == dz)
+ assert np.all(np.array(tolist(dz), dtype=object) == dz)
+ assert np.all(dz == np.array(tolist(dz), dtype=object))
+
+ def test_comparison_tzawareness_compat_scalars(self, comparison_op, box_with_array):
+ # GH#18162
+ op = comparison_op
+
+ dr = date_range("2016-01-01", periods=6)
+ dz = dr.tz_localize("US/Pacific")
+
+ dr = tm.box_expected(dr, box_with_array)
+ dz = tm.box_expected(dz, box_with_array)
+
+ # Check comparisons against scalar Timestamps
+ ts = Timestamp("2000-03-14 01:59")
+ ts_tz = Timestamp("2000-03-14 01:59", tz="Europe/Amsterdam")
+
+ assert np.all(dr > ts)
+ msg = r"Invalid comparison between dtype=datetime64\[ns.*\] and Timestamp"
+ if op not in [operator.eq, operator.ne]:
+ with pytest.raises(TypeError, match=msg):
+ op(dr, ts_tz)
+
+ assert np.all(dz > ts_tz)
+ if op not in [operator.eq, operator.ne]:
+ with pytest.raises(TypeError, match=msg):
+ op(dz, ts)
+
+ if op not in [operator.eq, operator.ne]:
+ # GH#12601: Check comparison against Timestamps and DatetimeIndex
+ with pytest.raises(TypeError, match=msg):
+ op(ts, dz)
+
+ @pytest.mark.parametrize(
+ "other",
+ [datetime(2016, 1, 1), Timestamp("2016-01-01"), np.datetime64("2016-01-01")],
+ )
+ # Bug in NumPy? https://github.com/numpy/numpy/issues/13841
+ # Raising in __eq__ will fallback to NumPy, which warns, fails,
+ # then re-raises the original exception. So we just need to ignore.
+ @pytest.mark.filterwarnings("ignore:elementwise comp:DeprecationWarning")
+ def test_scalar_comparison_tzawareness(
+ self, comparison_op, other, tz_aware_fixture, box_with_array
+ ):
+ op = comparison_op
+ tz = tz_aware_fixture
+ dti = date_range("2016-01-01", periods=2, tz=tz)
+
+ dtarr = tm.box_expected(dti, box_with_array)
+ xbox = get_upcast_box(dtarr, other, True)
+ if op in [operator.eq, operator.ne]:
+ exbool = op is operator.ne
+ expected = np.array([exbool, exbool], dtype=bool)
+ expected = tm.box_expected(expected, xbox)
+
+ result = op(dtarr, other)
+ tm.assert_equal(result, expected)
+
+ result = op(other, dtarr)
+ tm.assert_equal(result, expected)
+ else:
+ msg = (
+ r"Invalid comparison between dtype=datetime64\[ns, .*\] "
+ f"and {type(other).__name__}"
+ )
+ with pytest.raises(TypeError, match=msg):
+ op(dtarr, other)
+ with pytest.raises(TypeError, match=msg):
+ op(other, dtarr)
+
+ def test_nat_comparison_tzawareness(self, comparison_op):
+ # GH#19276
+ # tzaware DatetimeIndex should not raise when compared to NaT
+ op = comparison_op
+
+ dti = DatetimeIndex(
+ ["2014-01-01", NaT, "2014-03-01", NaT, "2014-05-01", "2014-07-01"]
+ )
+ expected = np.array([op == operator.ne] * len(dti))
+ result = op(dti, NaT)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = op(dti.tz_localize("US/Pacific"), NaT)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_dti_cmp_str(self, tz_naive_fixture):
+ # GH#22074
+ # regardless of tz, we expect these comparisons are valid
+ tz = tz_naive_fixture
+ rng = date_range("1/1/2000", periods=10, tz=tz)
+ other = "1/1/2000"
+
+ result = rng == other
+ expected = np.array([True] + [False] * 9)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = rng != other
+ expected = np.array([False] + [True] * 9)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = rng < other
+ expected = np.array([False] * 10)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = rng <= other
+ expected = np.array([True] + [False] * 9)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = rng > other
+ expected = np.array([False] + [True] * 9)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = rng >= other
+ expected = np.array([True] * 10)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_dti_cmp_list(self):
+ rng = date_range("1/1/2000", periods=10)
+
+ result = rng == list(rng)
+ expected = rng == rng
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ pd.timedelta_range("1D", periods=10),
+ pd.timedelta_range("1D", periods=10).to_series(),
+ pd.timedelta_range("1D", periods=10).asi8.view("m8[ns]"),
+ ],
+ ids=lambda x: type(x).__name__,
+ )
+ def test_dti_cmp_tdi_tzawareness(self, other):
+ # GH#22074
+ # reversion test that we _don't_ call _assert_tzawareness_compat
+ # when comparing against TimedeltaIndex
+ dti = date_range("2000-01-01", periods=10, tz="Asia/Tokyo")
+
+ result = dti == other
+ expected = np.array([False] * 10)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = dti != other
+ expected = np.array([True] * 10)
+ tm.assert_numpy_array_equal(result, expected)
+ msg = "Invalid comparison between"
+ with pytest.raises(TypeError, match=msg):
+ dti < other
+ with pytest.raises(TypeError, match=msg):
+ dti <= other
+ with pytest.raises(TypeError, match=msg):
+ dti > other
+ with pytest.raises(TypeError, match=msg):
+ dti >= other
+
+ def test_dti_cmp_object_dtype(self):
+ # GH#22074
+ dti = date_range("2000-01-01", periods=10, tz="Asia/Tokyo")
+
+ other = dti.astype("O")
+
+ result = dti == other
+ expected = np.array([True] * 10)
+ tm.assert_numpy_array_equal(result, expected)
+
+ other = dti.tz_localize(None)
+ result = dti != other
+ tm.assert_numpy_array_equal(result, expected)
+
+ other = np.array(list(dti[:5]) + [Timedelta(days=1)] * 5)
+ result = dti == other
+ expected = np.array([True] * 5 + [False] * 5)
+ tm.assert_numpy_array_equal(result, expected)
+ msg = ">=' not supported between instances of 'Timestamp' and 'Timedelta'"
+ with pytest.raises(TypeError, match=msg):
+ dti >= other
+
+
+# ------------------------------------------------------------------
+# Arithmetic
+
+
+class TestDatetime64Arithmetic:
+ # This class is intended for "finished" tests that are fully parametrized
+ # over DataFrame/Series/Index/DatetimeArray
+
+ # -------------------------------------------------------------
+ # Addition/Subtraction of timedelta-like
+
+ @pytest.mark.arm_slow
+ def test_dt64arr_add_timedeltalike_scalar(
+ self, tz_naive_fixture, two_hours, box_with_array
+ ):
+ # GH#22005, GH#22163 check DataFrame doesn't raise TypeError
+ tz = tz_naive_fixture
+
+ rng = date_range("2000-01-01", "2000-02-01", tz=tz)
+ expected = date_range("2000-01-01 02:00", "2000-02-01 02:00", tz=tz)
+
+ rng = tm.box_expected(rng, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = rng + two_hours
+ tm.assert_equal(result, expected)
+
+ result = two_hours + rng
+ tm.assert_equal(result, expected)
+
+ rng += two_hours
+ tm.assert_equal(rng, expected)
+
+ def test_dt64arr_sub_timedeltalike_scalar(
+ self, tz_naive_fixture, two_hours, box_with_array
+ ):
+ tz = tz_naive_fixture
+
+ rng = date_range("2000-01-01", "2000-02-01", tz=tz)
+ expected = date_range("1999-12-31 22:00", "2000-01-31 22:00", tz=tz)
+
+ rng = tm.box_expected(rng, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = rng - two_hours
+ tm.assert_equal(result, expected)
+
+ rng -= two_hours
+ tm.assert_equal(rng, expected)
+
+ def test_dt64_array_sub_dt_with_different_timezone(self, box_with_array):
+ t1 = date_range("20130101", periods=3).tz_localize("US/Eastern")
+ t1 = tm.box_expected(t1, box_with_array)
+ t2 = Timestamp("20130101").tz_localize("CET")
+ tnaive = Timestamp(20130101)
+
+ result = t1 - t2
+ expected = TimedeltaIndex(
+ ["0 days 06:00:00", "1 days 06:00:00", "2 days 06:00:00"]
+ )
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ result = t2 - t1
+ expected = TimedeltaIndex(
+ ["-1 days +18:00:00", "-2 days +18:00:00", "-3 days +18:00:00"]
+ )
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
+ with pytest.raises(TypeError, match=msg):
+ t1 - tnaive
+
+ with pytest.raises(TypeError, match=msg):
+ tnaive - t1
+
+ def test_dt64_array_sub_dt64_array_with_different_timezone(self, box_with_array):
+ t1 = date_range("20130101", periods=3).tz_localize("US/Eastern")
+ t1 = tm.box_expected(t1, box_with_array)
+ t2 = date_range("20130101", periods=3).tz_localize("CET")
+ t2 = tm.box_expected(t2, box_with_array)
+ tnaive = date_range("20130101", periods=3)
+
+ result = t1 - t2
+ expected = TimedeltaIndex(
+ ["0 days 06:00:00", "0 days 06:00:00", "0 days 06:00:00"]
+ )
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ result = t2 - t1
+ expected = TimedeltaIndex(
+ ["-1 days +18:00:00", "-1 days +18:00:00", "-1 days +18:00:00"]
+ )
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
+ with pytest.raises(TypeError, match=msg):
+ t1 - tnaive
+
+ with pytest.raises(TypeError, match=msg):
+ tnaive - t1
+
+ def test_dt64arr_add_sub_td64_nat(self, box_with_array, tz_naive_fixture):
+ # GH#23320 special handling for timedelta64("NaT")
+ tz = tz_naive_fixture
+
+ dti = date_range("1994-04-01", periods=9, tz=tz, freq="QS")
+ other = np.timedelta64("NaT")
+ expected = DatetimeIndex(["NaT"] * 9, tz=tz)
+
+ obj = tm.box_expected(dti, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = obj + other
+ tm.assert_equal(result, expected)
+ result = other + obj
+ tm.assert_equal(result, expected)
+ result = obj - other
+ tm.assert_equal(result, expected)
+ msg = "cannot subtract"
+ with pytest.raises(TypeError, match=msg):
+ other - obj
+
+ def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array):
+ tz = tz_naive_fixture
+ dti = date_range("2016-01-01", periods=3, tz=tz)
+ tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"])
+ tdarr = tdi.values
+
+ expected = date_range("2015-12-31", "2016-01-02", periods=3, tz=tz)
+
+ dtarr = tm.box_expected(dti, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = dtarr + tdarr
+ tm.assert_equal(result, expected)
+ result = tdarr + dtarr
+ tm.assert_equal(result, expected)
+
+ expected = date_range("2016-01-02", "2016-01-04", periods=3, tz=tz)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = dtarr - tdarr
+ tm.assert_equal(result, expected)
+ msg = "cannot subtract|(bad|unsupported) operand type for unary"
+ with pytest.raises(TypeError, match=msg):
+ tdarr - dtarr
+
+ # -----------------------------------------------------------------
+ # Subtraction of datetime-like scalars
+
+ @pytest.mark.parametrize(
+ "ts",
+ [
+ Timestamp("2013-01-01"),
+ Timestamp("2013-01-01").to_pydatetime(),
+ Timestamp("2013-01-01").to_datetime64(),
+ # GH#7996, GH#22163 ensure non-nano datetime64 is converted to nano
+ # for DataFrame operation
+ np.datetime64("2013-01-01", "D"),
+ ],
+ )
+ def test_dt64arr_sub_dtscalar(self, box_with_array, ts):
+ # GH#8554, GH#22163 DataFrame op should _not_ return dt64 dtype
+ idx = date_range("2013-01-01", periods=3)._with_freq(None)
+ idx = tm.box_expected(idx, box_with_array)
+
+ expected = TimedeltaIndex(["0 Days", "1 Day", "2 Days"])
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = idx - ts
+ tm.assert_equal(result, expected)
+
+ result = ts - idx
+ tm.assert_equal(result, -expected)
+ tm.assert_equal(result, -expected)
+
+ def test_dt64arr_sub_timestamp_tzaware(self, box_with_array):
+ ser = date_range("2014-03-17", periods=2, freq="D", tz="US/Eastern")
+ ser = ser._with_freq(None)
+ ts = ser[0]
+
+ ser = tm.box_expected(ser, box_with_array)
+
+ delta_series = Series([np.timedelta64(0, "D"), np.timedelta64(1, "D")])
+ expected = tm.box_expected(delta_series, box_with_array)
+
+ tm.assert_equal(ser - ts, expected)
+ tm.assert_equal(ts - ser, -expected)
+
+ def test_dt64arr_sub_NaT(self, box_with_array):
+ # GH#18808
+ dti = DatetimeIndex([NaT, Timestamp("19900315")])
+ ser = tm.box_expected(dti, box_with_array)
+
+ result = ser - NaT
+ expected = Series([NaT, NaT], dtype="timedelta64[ns]")
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ dti_tz = dti.tz_localize("Asia/Tokyo")
+ ser_tz = tm.box_expected(dti_tz, box_with_array)
+
+ result = ser_tz - NaT
+ expected = Series([NaT, NaT], dtype="timedelta64[ns]")
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ # -------------------------------------------------------------
+ # Subtraction of datetime-like array-like
+
+ def test_dt64arr_sub_dt64object_array(self, box_with_array, tz_naive_fixture):
+ dti = date_range("2016-01-01", periods=3, tz=tz_naive_fixture)
+ expected = dti - dti
+
+ obj = tm.box_expected(dti, box_with_array)
+ expected = tm.box_expected(expected, box_with_array).astype(object)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = obj - obj.astype(object)
+ tm.assert_equal(result, expected)
+
+ def test_dt64arr_naive_sub_dt64ndarray(self, box_with_array):
+ dti = date_range("2016-01-01", periods=3, tz=None)
+ dt64vals = dti.values
+
+ dtarr = tm.box_expected(dti, box_with_array)
+
+ expected = dtarr - dtarr
+ result = dtarr - dt64vals
+ tm.assert_equal(result, expected)
+ result = dt64vals - dtarr
+ tm.assert_equal(result, expected)
+
+ def test_dt64arr_aware_sub_dt64ndarray_raises(
+ self, tz_aware_fixture, box_with_array
+ ):
+ tz = tz_aware_fixture
+ dti = date_range("2016-01-01", periods=3, tz=tz)
+ dt64vals = dti.values
+
+ dtarr = tm.box_expected(dti, box_with_array)
+ msg = "Cannot subtract tz-naive and tz-aware datetime"
+ with pytest.raises(TypeError, match=msg):
+ dtarr - dt64vals
+ with pytest.raises(TypeError, match=msg):
+ dt64vals - dtarr
+
+ # -------------------------------------------------------------
+ # Addition of datetime-like others (invalid)
+
+ def test_dt64arr_add_dtlike_raises(self, tz_naive_fixture, box_with_array):
+ # GH#22163 ensure DataFrame doesn't cast Timestamp to i8
+ # GH#9631
+ tz = tz_naive_fixture
+
+ dti = date_range("2016-01-01", periods=3, tz=tz)
+ if tz is None:
+ dti2 = dti.tz_localize("US/Eastern")
+ else:
+ dti2 = dti.tz_localize(None)
+ dtarr = tm.box_expected(dti, box_with_array)
+
+ assert_cannot_add(dtarr, dti.values)
+ assert_cannot_add(dtarr, dti)
+ assert_cannot_add(dtarr, dtarr)
+ assert_cannot_add(dtarr, dti[0])
+ assert_cannot_add(dtarr, dti[0].to_pydatetime())
+ assert_cannot_add(dtarr, dti[0].to_datetime64())
+ assert_cannot_add(dtarr, dti2[0])
+ assert_cannot_add(dtarr, dti2[0].to_pydatetime())
+ assert_cannot_add(dtarr, np.datetime64("2011-01-01", "D"))
+
+ # -------------------------------------------------------------
+ # Other Invalid Addition/Subtraction
+
+ # Note: freq here includes both Tick and non-Tick offsets; this is
+ # relevant because historically integer-addition was allowed if we had
+ # a freq.
+ @pytest.mark.parametrize("freq", ["H", "D", "W", "M", "MS", "Q", "B", None])
+ @pytest.mark.parametrize("dtype", [None, "uint8"])
+ def test_dt64arr_addsub_intlike(
+ self, request, dtype, box_with_array, freq, tz_naive_fixture
+ ):
+ # GH#19959, GH#19123, GH#19012
+ tz = tz_naive_fixture
+ if box_with_array is pd.DataFrame:
+ request.node.add_marker(
+ pytest.mark.xfail(raises=ValueError, reason="Axis alignment fails")
+ )
+
+ if freq is None:
+ dti = DatetimeIndex(["NaT", "2017-04-05 06:07:08"], tz=tz)
+ else:
+ dti = date_range("2016-01-01", periods=2, freq=freq, tz=tz)
+
+ obj = box_with_array(dti)
+ other = np.array([4, -1])
+ if dtype is not None:
+ other = other.astype(dtype)
+
+ msg = "|".join(
+ [
+ "Addition/subtraction of integers",
+ "cannot subtract DatetimeArray from",
+ # IntegerArray
+ "can only perform ops with numeric values",
+ "unsupported operand type.*Categorical",
+ r"unsupported operand type\(s\) for -: 'int' and 'Timestamp'",
+ ]
+ )
+ assert_invalid_addsub_type(obj, 1, msg)
+ assert_invalid_addsub_type(obj, np.int64(2), msg)
+ assert_invalid_addsub_type(obj, np.array(3, dtype=np.int64), msg)
+ assert_invalid_addsub_type(obj, other, msg)
+ assert_invalid_addsub_type(obj, np.array(other), msg)
+ assert_invalid_addsub_type(obj, pd.array(other), msg)
+ assert_invalid_addsub_type(obj, pd.Categorical(other), msg)
+ assert_invalid_addsub_type(obj, pd.Index(other), msg)
+ assert_invalid_addsub_type(obj, Series(other), msg)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ 3.14,
+ np.array([2.0, 3.0]),
+ # GH#13078 datetime +/- Period is invalid
+ Period("2011-01-01", freq="D"),
+ # https://github.com/pandas-dev/pandas/issues/10329
+ time(1, 2, 3),
+ ],
+ )
+ @pytest.mark.parametrize("dti_freq", [None, "D"])
+ def test_dt64arr_add_sub_invalid(self, dti_freq, other, box_with_array):
+ dti = DatetimeIndex(["2011-01-01", "2011-01-02"], freq=dti_freq)
+ dtarr = tm.box_expected(dti, box_with_array)
+ msg = "|".join(
+ [
+ "unsupported operand type",
+ "cannot (add|subtract)",
+ "cannot use operands with types",
+ "ufunc '?(add|subtract)'? cannot use operands with types",
+ "Concatenation operation is not implemented for NumPy arrays",
+ ]
+ )
+ assert_invalid_addsub_type(dtarr, other, msg)
+
+ @pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "H"])
+ @pytest.mark.parametrize("dti_freq", [None, "D"])
+ def test_dt64arr_add_sub_parr(
+ self, dti_freq, pi_freq, box_with_array, box_with_array2
+ ):
+ # GH#20049 subtracting PeriodIndex should raise TypeError
+ dti = DatetimeIndex(["2011-01-01", "2011-01-02"], freq=dti_freq)
+ pi = dti.to_period(pi_freq)
+
+ dtarr = tm.box_expected(dti, box_with_array)
+ parr = tm.box_expected(pi, box_with_array2)
+ msg = "|".join(
+ [
+ "cannot (add|subtract)",
+ "unsupported operand",
+ "descriptor.*requires",
+ "ufunc.*cannot use operands",
+ ]
+ )
+ assert_invalid_addsub_type(dtarr, parr, msg)
+
+ @pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning")
+ def test_dt64arr_addsub_time_objects_raises(self, box_with_array, tz_naive_fixture):
+ # https://github.com/pandas-dev/pandas/issues/10329
+
+ tz = tz_naive_fixture
+
+ obj1 = date_range("2012-01-01", periods=3, tz=tz)
+ obj2 = [time(i, i, i) for i in range(3)]
+
+ obj1 = tm.box_expected(obj1, box_with_array)
+ obj2 = tm.box_expected(obj2, box_with_array)
+
+ msg = "|".join(
+ [
+ "unsupported operand",
+ "cannot subtract DatetimeArray from ndarray",
+ ]
+ )
+ # pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
+ # applied to Series or DatetimeIndex
+ # we aren't testing that here, so ignore.
+ assert_invalid_addsub_type(obj1, obj2, msg=msg)
+
+ # -------------------------------------------------------------
+ # Other invalid operations
+
+ @pytest.mark.parametrize(
+ "dt64_series",
+ [
+ Series([Timestamp("19900315"), Timestamp("19900315")]),
+ Series([NaT, Timestamp("19900315")]),
+ Series([NaT, NaT], dtype="datetime64[ns]"),
+ ],
+ )
+ @pytest.mark.parametrize("one", [1, 1.0, np.array(1)])
+ def test_dt64_mul_div_numeric_invalid(self, one, dt64_series, box_with_array):
+ obj = tm.box_expected(dt64_series, box_with_array)
+
+ msg = "cannot perform .* with this index type"
+
+ # multiplication
+ with pytest.raises(TypeError, match=msg):
+ obj * one
+ with pytest.raises(TypeError, match=msg):
+ one * obj
+
+ # division
+ with pytest.raises(TypeError, match=msg):
+ obj / one
+ with pytest.raises(TypeError, match=msg):
+ one / obj
+
+
+class TestDatetime64DateOffsetArithmetic:
+ # -------------------------------------------------------------
+ # Tick DateOffsets
+
+ # TODO: parametrize over timezone?
+ def test_dt64arr_series_add_tick_DateOffset(self, box_with_array):
+ # GH#4532
+ # operate with pd.offsets
+ ser = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")])
+ expected = Series(
+ [Timestamp("20130101 9:01:05"), Timestamp("20130101 9:02:05")]
+ )
+
+ ser = tm.box_expected(ser, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = ser + pd.offsets.Second(5)
+ tm.assert_equal(result, expected)
+
+ result2 = pd.offsets.Second(5) + ser
+ tm.assert_equal(result2, expected)
+
+ def test_dt64arr_series_sub_tick_DateOffset(self, box_with_array):
+ # GH#4532
+ # operate with pd.offsets
+ ser = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")])
+ expected = Series(
+ [Timestamp("20130101 9:00:55"), Timestamp("20130101 9:01:55")]
+ )
+
+ ser = tm.box_expected(ser, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = ser - pd.offsets.Second(5)
+ tm.assert_equal(result, expected)
+
+ result2 = -pd.offsets.Second(5) + ser
+ tm.assert_equal(result2, expected)
+ msg = "(bad|unsupported) operand type for unary"
+ with pytest.raises(TypeError, match=msg):
+ pd.offsets.Second(5) - ser
+
+ @pytest.mark.parametrize(
+ "cls_name", ["Day", "Hour", "Minute", "Second", "Milli", "Micro", "Nano"]
+ )
+ def test_dt64arr_add_sub_tick_DateOffset_smoke(self, cls_name, box_with_array):
+ # GH#4532
+ # smoke tests for valid DateOffsets
+ ser = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")])
+ ser = tm.box_expected(ser, box_with_array)
+
+ offset_cls = getattr(pd.offsets, cls_name)
+ ser + offset_cls(5)
+ offset_cls(5) + ser
+ ser - offset_cls(5)
+
+ def test_dti_add_tick_tzaware(self, tz_aware_fixture, box_with_array):
+ # GH#21610, GH#22163 ensure DataFrame doesn't return object-dtype
+ tz = tz_aware_fixture
+ if tz == "US/Pacific":
+ dates = date_range("2012-11-01", periods=3, tz=tz)
+ offset = dates + pd.offsets.Hour(5)
+ assert dates[0] + pd.offsets.Hour(5) == offset[0]
+
+ dates = date_range("2010-11-01 00:00", periods=3, tz=tz, freq="H")
+ expected = DatetimeIndex(
+ ["2010-11-01 05:00", "2010-11-01 06:00", "2010-11-01 07:00"],
+ freq="H",
+ tz=tz,
+ )
+
+ dates = tm.box_expected(dates, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ for scalar in [pd.offsets.Hour(5), np.timedelta64(5, "h"), timedelta(hours=5)]:
+ offset = dates + scalar
+ tm.assert_equal(offset, expected)
+ offset = scalar + dates
+ tm.assert_equal(offset, expected)
+
+ roundtrip = offset - scalar
+ tm.assert_equal(roundtrip, dates)
+
+ msg = "|".join(
+ ["bad operand type for unary -", "cannot subtract DatetimeArray"]
+ )
+ with pytest.raises(TypeError, match=msg):
+ scalar - dates
+
+ # -------------------------------------------------------------
+ # RelativeDelta DateOffsets
+
+ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array):
+ # GH#10699
+ vec = DatetimeIndex(
+ [
+ Timestamp("2000-01-05 00:15:00"),
+ Timestamp("2000-01-31 00:23:00"),
+ Timestamp("2000-01-01"),
+ Timestamp("2000-03-31"),
+ Timestamp("2000-02-29"),
+ Timestamp("2000-12-31"),
+ Timestamp("2000-05-15"),
+ Timestamp("2001-06-15"),
+ ]
+ )
+ vec = tm.box_expected(vec, box_with_array)
+ vec_items = vec.iloc[0] if box_with_array is pd.DataFrame else vec
+
+ # DateOffset relativedelta fastpath
+ relative_kwargs = [
+ ("years", 2),
+ ("months", 5),
+ ("days", 3),
+ ("hours", 5),
+ ("minutes", 10),
+ ("seconds", 2),
+ ("microseconds", 5),
+ ]
+ for i, (unit, value) in enumerate(relative_kwargs):
+ off = DateOffset(**{unit: value})
+
+ expected = DatetimeIndex([x + off for x in vec_items])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(expected, vec + off)
+
+ expected = DatetimeIndex([x - off for x in vec_items])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(expected, vec - off)
+
+ off = DateOffset(**dict(relative_kwargs[: i + 1]))
+
+ expected = DatetimeIndex([x + off for x in vec_items])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(expected, vec + off)
+
+ expected = DatetimeIndex([x - off for x in vec_items])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(expected, vec - off)
+ msg = "(bad|unsupported) operand type for unary"
+ with pytest.raises(TypeError, match=msg):
+ off - vec
+
+ # -------------------------------------------------------------
+ # Non-Tick, Non-RelativeDelta DateOffsets
+
+ # TODO: redundant with test_dt64arr_add_sub_DateOffset? that includes
+ # tz-aware cases which this does not
+ @pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning")
+ @pytest.mark.parametrize(
+ "cls_and_kwargs",
+ [
+ "YearBegin",
+ ("YearBegin", {"month": 5}),
+ "YearEnd",
+ ("YearEnd", {"month": 5}),
+ "MonthBegin",
+ "MonthEnd",
+ "SemiMonthEnd",
+ "SemiMonthBegin",
+ "Week",
+ ("Week", {"weekday": 3}),
+ "Week",
+ ("Week", {"weekday": 6}),
+ "BusinessDay",
+ "BDay",
+ "QuarterEnd",
+ "QuarterBegin",
+ "CustomBusinessDay",
+ "CDay",
+ "CBMonthEnd",
+ "CBMonthBegin",
+ "BMonthBegin",
+ "BMonthEnd",
+ "BusinessHour",
+ "BYearBegin",
+ "BYearEnd",
+ "BQuarterBegin",
+ ("LastWeekOfMonth", {"weekday": 2}),
+ (
+ "FY5253Quarter",
+ {
+ "qtr_with_extra_week": 1,
+ "startingMonth": 1,
+ "weekday": 2,
+ "variation": "nearest",
+ },
+ ),
+ ("FY5253", {"weekday": 0, "startingMonth": 2, "variation": "nearest"}),
+ ("WeekOfMonth", {"weekday": 2, "week": 2}),
+ "Easter",
+ ("DateOffset", {"day": 4}),
+ ("DateOffset", {"month": 5}),
+ ],
+ )
+ @pytest.mark.parametrize("normalize", [True, False])
+ @pytest.mark.parametrize("n", [0, 5])
+ def test_dt64arr_add_sub_DateOffsets(
+ self, box_with_array, n, normalize, cls_and_kwargs
+ ):
+ # GH#10699
+ # assert vectorized operation matches pointwise operations
+
+ if isinstance(cls_and_kwargs, tuple):
+ # If cls_name param is a tuple, then 2nd entry is kwargs for
+ # the offset constructor
+ cls_name, kwargs = cls_and_kwargs
+ else:
+ cls_name = cls_and_kwargs
+ kwargs = {}
+
+ if n == 0 and cls_name in [
+ "WeekOfMonth",
+ "LastWeekOfMonth",
+ "FY5253Quarter",
+ "FY5253",
+ ]:
+ # passing n = 0 is invalid for these offset classes
+ return
+
+ vec = DatetimeIndex(
+ [
+ Timestamp("2000-01-05 00:15:00"),
+ Timestamp("2000-01-31 00:23:00"),
+ Timestamp("2000-01-01"),
+ Timestamp("2000-03-31"),
+ Timestamp("2000-02-29"),
+ Timestamp("2000-12-31"),
+ Timestamp("2000-05-15"),
+ Timestamp("2001-06-15"),
+ ]
+ )
+ vec = tm.box_expected(vec, box_with_array)
+ vec_items = vec.iloc[0] if box_with_array is pd.DataFrame else vec
+
+ offset_cls = getattr(pd.offsets, cls_name)
+
+ # pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
+ # applied to Series or DatetimeIndex
+ # we aren't testing that here, so ignore.
+
+ offset = offset_cls(n, normalize=normalize, **kwargs)
+
+ expected = DatetimeIndex([x + offset for x in vec_items])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(expected, vec + offset)
+
+ expected = DatetimeIndex([x - offset for x in vec_items])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(expected, vec - offset)
+
+ expected = DatetimeIndex([offset + x for x in vec_items])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(expected, offset + vec)
+ msg = "(bad|unsupported) operand type for unary"
+ with pytest.raises(TypeError, match=msg):
+ offset - vec
+
+ def test_dt64arr_add_sub_DateOffset(self, box_with_array):
+ # GH#10699
+ s = date_range("2000-01-01", "2000-01-31", name="a")
+ s = tm.box_expected(s, box_with_array)
+ result = s + DateOffset(years=1)
+ result2 = DateOffset(years=1) + s
+ exp = date_range("2001-01-01", "2001-01-31", name="a")._with_freq(None)
+ exp = tm.box_expected(exp, box_with_array)
+ tm.assert_equal(result, exp)
+ tm.assert_equal(result2, exp)
+
+ result = s - DateOffset(years=1)
+ exp = date_range("1999-01-01", "1999-01-31", name="a")._with_freq(None)
+ exp = tm.box_expected(exp, box_with_array)
+ tm.assert_equal(result, exp)
+
+ s = DatetimeIndex(
+ [
+ Timestamp("2000-01-15 00:15:00", tz="US/Central"),
+ Timestamp("2000-02-15", tz="US/Central"),
+ ],
+ name="a",
+ )
+ s = tm.box_expected(s, box_with_array)
+ result = s + pd.offsets.Day()
+ result2 = pd.offsets.Day() + s
+ exp = DatetimeIndex(
+ [
+ Timestamp("2000-01-16 00:15:00", tz="US/Central"),
+ Timestamp("2000-02-16", tz="US/Central"),
+ ],
+ name="a",
+ )
+ exp = tm.box_expected(exp, box_with_array)
+ tm.assert_equal(result, exp)
+ tm.assert_equal(result2, exp)
+
+ s = DatetimeIndex(
+ [
+ Timestamp("2000-01-15 00:15:00", tz="US/Central"),
+ Timestamp("2000-02-15", tz="US/Central"),
+ ],
+ name="a",
+ )
+ s = tm.box_expected(s, box_with_array)
+ result = s + pd.offsets.MonthEnd()
+ result2 = pd.offsets.MonthEnd() + s
+ exp = DatetimeIndex(
+ [
+ Timestamp("2000-01-31 00:15:00", tz="US/Central"),
+ Timestamp("2000-02-29", tz="US/Central"),
+ ],
+ name="a",
+ )
+ exp = tm.box_expected(exp, box_with_array)
+ tm.assert_equal(result, exp)
+ tm.assert_equal(result2, exp)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)]),
+ np.array([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()]),
+ np.array( # matching offsets
+ [pd.offsets.DateOffset(years=1), pd.offsets.DateOffset(years=1)]
+ ),
+ ],
+ )
+ @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub])
+ def test_dt64arr_add_sub_offset_array(
+ self, tz_naive_fixture, box_with_array, op, other
+ ):
+ # GH#18849
+ # GH#10699 array of offsets
+
+ tz = tz_naive_fixture
+ dti = date_range("2017-01-01", periods=2, tz=tz)
+ dtarr = tm.box_expected(dti, box_with_array)
+
+ expected = DatetimeIndex([op(dti[n], other[n]) for n in range(len(dti))])
+ expected = tm.box_expected(expected, box_with_array).astype(object)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res = op(dtarr, other)
+ tm.assert_equal(res, expected)
+
+ # Same thing but boxing other
+ other = tm.box_expected(other, box_with_array)
+ if box_with_array is pd.array and op is roperator.radd:
+ # We expect a NumpyExtensionArray, not ndarray[object] here
+ expected = pd.array(expected, dtype=object)
+ with tm.assert_produces_warning(PerformanceWarning):
+ res = op(dtarr, other)
+ tm.assert_equal(res, expected)
+
+ @pytest.mark.parametrize(
+ "op, offset, exp, exp_freq",
+ [
+ (
+ "__add__",
+ DateOffset(months=3, days=10),
+ [
+ Timestamp("2014-04-11"),
+ Timestamp("2015-04-11"),
+ Timestamp("2016-04-11"),
+ Timestamp("2017-04-11"),
+ ],
+ None,
+ ),
+ (
+ "__add__",
+ DateOffset(months=3),
+ [
+ Timestamp("2014-04-01"),
+ Timestamp("2015-04-01"),
+ Timestamp("2016-04-01"),
+ Timestamp("2017-04-01"),
+ ],
+ "AS-APR",
+ ),
+ (
+ "__sub__",
+ DateOffset(months=3, days=10),
+ [
+ Timestamp("2013-09-21"),
+ Timestamp("2014-09-21"),
+ Timestamp("2015-09-21"),
+ Timestamp("2016-09-21"),
+ ],
+ None,
+ ),
+ (
+ "__sub__",
+ DateOffset(months=3),
+ [
+ Timestamp("2013-10-01"),
+ Timestamp("2014-10-01"),
+ Timestamp("2015-10-01"),
+ Timestamp("2016-10-01"),
+ ],
+ "AS-OCT",
+ ),
+ ],
+ )
+ def test_dti_add_sub_nonzero_mth_offset(
+ self, op, offset, exp, exp_freq, tz_aware_fixture, box_with_array
+ ):
+ # GH 26258
+ tz = tz_aware_fixture
+ date = date_range(start="01 Jan 2014", end="01 Jan 2017", freq="AS", tz=tz)
+ date = tm.box_expected(date, box_with_array, False)
+ mth = getattr(date, op)
+ result = mth(offset)
+
+ expected = DatetimeIndex(exp, tz=tz)
+ expected = tm.box_expected(expected, box_with_array, False)
+ tm.assert_equal(result, expected)
+
+
+class TestDatetime64OverflowHandling:
+ # TODO: box + de-duplicate
+
+ def test_dt64_overflow_masking(self, box_with_array):
+ # GH#25317
+ left = Series([Timestamp("1969-12-31")])
+ right = Series([NaT])
+
+ left = tm.box_expected(left, box_with_array)
+ right = tm.box_expected(right, box_with_array)
+
+ expected = TimedeltaIndex([NaT])
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = left - right
+ tm.assert_equal(result, expected)
+
+ def test_dt64_series_arith_overflow(self):
+ # GH#12534, fixed by GH#19024
+ dt = Timestamp("1700-01-31")
+ td = Timedelta("20000 Days")
+ dti = date_range("1949-09-30", freq="100Y", periods=4)
+ ser = Series(dti)
+ msg = "Overflow in int64 addition"
+ with pytest.raises(OverflowError, match=msg):
+ ser - dt
+ with pytest.raises(OverflowError, match=msg):
+ dt - ser
+ with pytest.raises(OverflowError, match=msg):
+ ser + td
+ with pytest.raises(OverflowError, match=msg):
+ td + ser
+
+ ser.iloc[-1] = NaT
+ expected = Series(
+ ["2004-10-03", "2104-10-04", "2204-10-04", "NaT"], dtype="datetime64[ns]"
+ )
+ res = ser + td
+ tm.assert_series_equal(res, expected)
+ res = td + ser
+ tm.assert_series_equal(res, expected)
+
+ ser.iloc[1:] = NaT
+ expected = Series(["91279 Days", "NaT", "NaT", "NaT"], dtype="timedelta64[ns]")
+ res = ser - dt
+ tm.assert_series_equal(res, expected)
+ res = dt - ser
+ tm.assert_series_equal(res, -expected)
+
+ def test_datetimeindex_sub_timestamp_overflow(self):
+ dtimax = pd.to_datetime(["2021-12-28 17:19", Timestamp.max])
+ dtimin = pd.to_datetime(["2021-12-28 17:19", Timestamp.min])
+
+ tsneg = Timestamp("1950-01-01").as_unit("ns")
+ ts_neg_variants = [
+ tsneg,
+ tsneg.to_pydatetime(),
+ tsneg.to_datetime64().astype("datetime64[ns]"),
+ tsneg.to_datetime64().astype("datetime64[D]"),
+ ]
+
+ tspos = Timestamp("1980-01-01").as_unit("ns")
+ ts_pos_variants = [
+ tspos,
+ tspos.to_pydatetime(),
+ tspos.to_datetime64().astype("datetime64[ns]"),
+ tspos.to_datetime64().astype("datetime64[D]"),
+ ]
+ msg = "Overflow in int64 addition"
+ for variant in ts_neg_variants:
+ with pytest.raises(OverflowError, match=msg):
+ dtimax - variant
+
+ expected = Timestamp.max._value - tspos._value
+ for variant in ts_pos_variants:
+ res = dtimax - variant
+ assert res[1]._value == expected
+
+ expected = Timestamp.min._value - tsneg._value
+ for variant in ts_neg_variants:
+ res = dtimin - variant
+ assert res[1]._value == expected
+
+ for variant in ts_pos_variants:
+ with pytest.raises(OverflowError, match=msg):
+ dtimin - variant
+
+ def test_datetimeindex_sub_datetimeindex_overflow(self):
+ # GH#22492, GH#22508
+ dtimax = pd.to_datetime(["2021-12-28 17:19", Timestamp.max])
+ dtimin = pd.to_datetime(["2021-12-28 17:19", Timestamp.min])
+
+ ts_neg = pd.to_datetime(["1950-01-01", "1950-01-01"])
+ ts_pos = pd.to_datetime(["1980-01-01", "1980-01-01"])
+
+ # General tests
+ expected = Timestamp.max._value - ts_pos[1]._value
+ result = dtimax - ts_pos
+ assert result[1]._value == expected
+
+ expected = Timestamp.min._value - ts_neg[1]._value
+ result = dtimin - ts_neg
+ assert result[1]._value == expected
+ msg = "Overflow in int64 addition"
+ with pytest.raises(OverflowError, match=msg):
+ dtimax - ts_neg
+
+ with pytest.raises(OverflowError, match=msg):
+ dtimin - ts_pos
+
+ # Edge cases
+ tmin = pd.to_datetime([Timestamp.min])
+ t1 = tmin + Timedelta.max + Timedelta("1us")
+ with pytest.raises(OverflowError, match=msg):
+ t1 - tmin
+
+ tmax = pd.to_datetime([Timestamp.max])
+ t2 = tmax + Timedelta.min - Timedelta("1us")
+ with pytest.raises(OverflowError, match=msg):
+ tmax - t2
+
+
+class TestTimestampSeriesArithmetic:
+ def test_empty_series_add_sub(self, box_with_array):
+ # GH#13844
+ a = Series(dtype="M8[ns]")
+ b = Series(dtype="m8[ns]")
+ a = box_with_array(a)
+ b = box_with_array(b)
+ tm.assert_equal(a, a + b)
+ tm.assert_equal(a, a - b)
+ tm.assert_equal(a, b + a)
+ msg = "cannot subtract"
+ with pytest.raises(TypeError, match=msg):
+ b - a
+
+ def test_operators_datetimelike(self):
+ # ## timedelta64 ###
+ td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
+ td1.iloc[2] = np.nan
+
+ # ## datetime64 ###
+ dt1 = Series(
+ [
+ Timestamp("20111230"),
+ Timestamp("20120101"),
+ Timestamp("20120103"),
+ ]
+ )
+ dt1.iloc[2] = np.nan
+ dt2 = Series(
+ [
+ Timestamp("20111231"),
+ Timestamp("20120102"),
+ Timestamp("20120104"),
+ ]
+ )
+ dt1 - dt2
+ dt2 - dt1
+
+ # datetime64 with timetimedelta
+ dt1 + td1
+ td1 + dt1
+ dt1 - td1
+
+ # timetimedelta with datetime64
+ td1 + dt1
+ dt1 + td1
+
+ def test_dt64ser_sub_datetime_dtype(self):
+ ts = Timestamp(datetime(1993, 1, 7, 13, 30, 00))
+ dt = datetime(1993, 6, 22, 13, 30)
+ ser = Series([ts])
+ result = pd.to_timedelta(np.abs(ser - dt))
+ assert result.dtype == "timedelta64[ns]"
+
+ # -------------------------------------------------------------
+ # TODO: This next block of tests came from tests.series.test_operators,
+ # needs to be de-duplicated and parametrized over `box` classes
+
+ @pytest.mark.parametrize(
+ "left, right, op_fail",
+ [
+ [
+ [Timestamp("20111230"), Timestamp("20120101"), NaT],
+ [Timestamp("20111231"), Timestamp("20120102"), Timestamp("20120104")],
+ ["__sub__", "__rsub__"],
+ ],
+ [
+ [Timestamp("20111230"), Timestamp("20120101"), NaT],
+ [timedelta(minutes=5, seconds=3), timedelta(minutes=5, seconds=3), NaT],
+ ["__add__", "__radd__", "__sub__"],
+ ],
+ [
+ [
+ Timestamp("20111230", tz="US/Eastern"),
+ Timestamp("20111230", tz="US/Eastern"),
+ NaT,
+ ],
+ [timedelta(minutes=5, seconds=3), NaT, timedelta(minutes=5, seconds=3)],
+ ["__add__", "__radd__", "__sub__"],
+ ],
+ ],
+ )
+ def test_operators_datetimelike_invalid(
+ self, left, right, op_fail, all_arithmetic_operators
+ ):
+ # these are all TypeError ops
+ op_str = all_arithmetic_operators
+ arg1 = Series(left)
+ arg2 = Series(right)
+ # check that we are getting a TypeError
+ # with 'operate' (from core/ops.py) for the ops that are not
+ # defined
+ op = getattr(arg1, op_str, None)
+ # Previously, _validate_for_numeric_binop in core/indexes/base.py
+ # did this for us.
+ if op_str not in op_fail:
+ with pytest.raises(
+ TypeError, match="operate|[cC]annot|unsupported operand"
+ ):
+ op(arg2)
+ else:
+ # Smoke test
+ op(arg2)
+
+ def test_sub_single_tz(self):
+ # GH#12290
+ s1 = Series([Timestamp("2016-02-10", tz="America/Sao_Paulo")])
+ s2 = Series([Timestamp("2016-02-08", tz="America/Sao_Paulo")])
+ result = s1 - s2
+ expected = Series([Timedelta("2days")])
+ tm.assert_series_equal(result, expected)
+ result = s2 - s1
+ expected = Series([Timedelta("-2days")])
+ tm.assert_series_equal(result, expected)
+
+ def test_dt64tz_series_sub_dtitz(self):
+ # GH#19071 subtracting tzaware DatetimeIndex from tzaware Series
+ # (with same tz) raises, fixed by #19024
+ dti = date_range("1999-09-30", periods=10, tz="US/Pacific")
+ ser = Series(dti)
+ expected = Series(TimedeltaIndex(["0days"] * 10))
+
+ res = dti - ser
+ tm.assert_series_equal(res, expected)
+ res = ser - dti
+ tm.assert_series_equal(res, expected)
+
+ def test_sub_datetime_compat(self):
+ # see GH#14088
+ s = Series([datetime(2016, 8, 23, 12, tzinfo=pytz.utc), NaT])
+ dt = datetime(2016, 8, 22, 12, tzinfo=pytz.utc)
+ exp = Series([Timedelta("1 days"), NaT])
+ tm.assert_series_equal(s - dt, exp)
+ tm.assert_series_equal(s - Timestamp(dt), exp)
+
+ def test_dt64_series_add_mixed_tick_DateOffset(self):
+ # GH#4532
+ # operate with pd.offsets
+ s = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")])
+
+ result = s + pd.offsets.Milli(5)
+ result2 = pd.offsets.Milli(5) + s
+ expected = Series(
+ [Timestamp("20130101 9:01:00.005"), Timestamp("20130101 9:02:00.005")]
+ )
+ tm.assert_series_equal(result, expected)
+ tm.assert_series_equal(result2, expected)
+
+ result = s + pd.offsets.Minute(5) + pd.offsets.Milli(5)
+ expected = Series(
+ [Timestamp("20130101 9:06:00.005"), Timestamp("20130101 9:07:00.005")]
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_datetime64_ops_nat(self):
+ # GH#11349
+ datetime_series = Series([NaT, Timestamp("19900315")])
+ nat_series_dtype_timestamp = Series([NaT, NaT], dtype="datetime64[ns]")
+ single_nat_dtype_datetime = Series([NaT], dtype="datetime64[ns]")
+
+ # subtraction
+ tm.assert_series_equal(-NaT + datetime_series, nat_series_dtype_timestamp)
+ msg = "bad operand type for unary -: 'DatetimeArray'"
+ with pytest.raises(TypeError, match=msg):
+ -single_nat_dtype_datetime + datetime_series
+
+ tm.assert_series_equal(
+ -NaT + nat_series_dtype_timestamp, nat_series_dtype_timestamp
+ )
+ with pytest.raises(TypeError, match=msg):
+ -single_nat_dtype_datetime + nat_series_dtype_timestamp
+
+ # addition
+ tm.assert_series_equal(
+ nat_series_dtype_timestamp + NaT, nat_series_dtype_timestamp
+ )
+ tm.assert_series_equal(
+ NaT + nat_series_dtype_timestamp, nat_series_dtype_timestamp
+ )
+
+ tm.assert_series_equal(
+ nat_series_dtype_timestamp + NaT, nat_series_dtype_timestamp
+ )
+ tm.assert_series_equal(
+ NaT + nat_series_dtype_timestamp, nat_series_dtype_timestamp
+ )
+
+ # -------------------------------------------------------------
+ # Timezone-Centric Tests
+
+ def test_operators_datetimelike_with_timezones(self):
+ tz = "US/Eastern"
+ dt1 = Series(date_range("2000-01-01 09:00:00", periods=5, tz=tz), name="foo")
+ dt2 = dt1.copy()
+ dt2.iloc[2] = np.nan
+
+ td1 = Series(pd.timedelta_range("1 days 1 min", periods=5, freq="H"))
+ td2 = td1.copy()
+ td2.iloc[1] = np.nan
+ assert td2._values.freq is None
+
+ result = dt1 + td1[0]
+ exp = (dt1.dt.tz_localize(None) + td1[0]).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+
+ result = dt2 + td2[0]
+ exp = (dt2.dt.tz_localize(None) + td2[0]).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+
+ # odd numpy behavior with scalar timedeltas
+ result = td1[0] + dt1
+ exp = (dt1.dt.tz_localize(None) + td1[0]).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+
+ result = td2[0] + dt2
+ exp = (dt2.dt.tz_localize(None) + td2[0]).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+
+ result = dt1 - td1[0]
+ exp = (dt1.dt.tz_localize(None) - td1[0]).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+ msg = "(bad|unsupported) operand type for unary"
+ with pytest.raises(TypeError, match=msg):
+ td1[0] - dt1
+
+ result = dt2 - td2[0]
+ exp = (dt2.dt.tz_localize(None) - td2[0]).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+ with pytest.raises(TypeError, match=msg):
+ td2[0] - dt2
+
+ result = dt1 + td1
+ exp = (dt1.dt.tz_localize(None) + td1).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+
+ result = dt2 + td2
+ exp = (dt2.dt.tz_localize(None) + td2).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+
+ result = dt1 - td1
+ exp = (dt1.dt.tz_localize(None) - td1).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+
+ result = dt2 - td2
+ exp = (dt2.dt.tz_localize(None) - td2).dt.tz_localize(tz)
+ tm.assert_series_equal(result, exp)
+ msg = "cannot (add|subtract)"
+ with pytest.raises(TypeError, match=msg):
+ td1 - dt1
+ with pytest.raises(TypeError, match=msg):
+ td2 - dt2
+
+
+class TestDatetimeIndexArithmetic:
+ # -------------------------------------------------------------
+ # Binary operations DatetimeIndex and TimedeltaIndex/array
+
+ def test_dti_add_tdi(self, tz_naive_fixture):
+ # GH#17558
+ tz = tz_naive_fixture
+ dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
+ tdi = pd.timedelta_range("0 days", periods=10)
+ expected = date_range("2017-01-01", periods=10, tz=tz)
+ expected = expected._with_freq(None)
+
+ # add with TimedeltaIndex
+ result = dti + tdi
+ tm.assert_index_equal(result, expected)
+
+ result = tdi + dti
+ tm.assert_index_equal(result, expected)
+
+ # add with timedelta64 array
+ result = dti + tdi.values
+ tm.assert_index_equal(result, expected)
+
+ result = tdi.values + dti
+ tm.assert_index_equal(result, expected)
+
+ def test_dti_iadd_tdi(self, tz_naive_fixture):
+ # GH#17558
+ tz = tz_naive_fixture
+ dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
+ tdi = pd.timedelta_range("0 days", periods=10)
+ expected = date_range("2017-01-01", periods=10, tz=tz)
+ expected = expected._with_freq(None)
+
+ # iadd with TimedeltaIndex
+ result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
+ result += tdi
+ tm.assert_index_equal(result, expected)
+
+ result = pd.timedelta_range("0 days", periods=10)
+ result += dti
+ tm.assert_index_equal(result, expected)
+
+ # iadd with timedelta64 array
+ result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
+ result += tdi.values
+ tm.assert_index_equal(result, expected)
+
+ result = pd.timedelta_range("0 days", periods=10)
+ result += dti
+ tm.assert_index_equal(result, expected)
+
+ def test_dti_sub_tdi(self, tz_naive_fixture):
+ # GH#17558
+ tz = tz_naive_fixture
+ dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
+ tdi = pd.timedelta_range("0 days", periods=10)
+ expected = date_range("2017-01-01", periods=10, tz=tz, freq="-1D")
+ expected = expected._with_freq(None)
+
+ # sub with TimedeltaIndex
+ result = dti - tdi
+ tm.assert_index_equal(result, expected)
+
+ msg = "cannot subtract .*TimedeltaArray"
+ with pytest.raises(TypeError, match=msg):
+ tdi - dti
+
+ # sub with timedelta64 array
+ result = dti - tdi.values
+ tm.assert_index_equal(result, expected)
+
+ msg = "cannot subtract a datelike from a TimedeltaArray"
+ with pytest.raises(TypeError, match=msg):
+ tdi.values - dti
+
+ def test_dti_isub_tdi(self, tz_naive_fixture):
+ # GH#17558
+ tz = tz_naive_fixture
+ dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
+ tdi = pd.timedelta_range("0 days", periods=10)
+ expected = date_range("2017-01-01", periods=10, tz=tz, freq="-1D")
+ expected = expected._with_freq(None)
+
+ # isub with TimedeltaIndex
+ result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
+ result -= tdi
+ tm.assert_index_equal(result, expected)
+
+ # DTA.__isub__ GH#43904
+ dta = dti._data.copy()
+ dta -= tdi
+ tm.assert_datetime_array_equal(dta, expected._data)
+
+ out = dti._data.copy()
+ np.subtract(out, tdi, out=out)
+ tm.assert_datetime_array_equal(out, expected._data)
+
+ msg = "cannot subtract a datelike from a TimedeltaArray"
+ with pytest.raises(TypeError, match=msg):
+ tdi -= dti
+
+ # isub with timedelta64 array
+ result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
+ result -= tdi.values
+ tm.assert_index_equal(result, expected)
+
+ with pytest.raises(TypeError, match=msg):
+ tdi.values -= dti
+
+ with pytest.raises(TypeError, match=msg):
+ tdi._values -= dti
+
+ # -------------------------------------------------------------
+ # Binary Operations DatetimeIndex and datetime-like
+ # TODO: A couple other tests belong in this section. Move them in
+ # A PR where there isn't already a giant diff.
+
+ # -------------------------------------------------------------
+
+ def test_dta_add_sub_index(self, tz_naive_fixture):
+ # Check that DatetimeArray defers to Index classes
+ dti = date_range("20130101", periods=3, tz=tz_naive_fixture)
+ dta = dti.array
+ result = dta - dti
+ expected = dti - dti
+ tm.assert_index_equal(result, expected)
+
+ tdi = result
+ result = dta + tdi
+ expected = dti + tdi
+ tm.assert_index_equal(result, expected)
+
+ result = dta - tdi
+ expected = dti - tdi
+ tm.assert_index_equal(result, expected)
+
+ def test_sub_dti_dti(self):
+ # previously performed setop (deprecated in 0.16.0), now changed to
+ # return subtraction -> TimeDeltaIndex (GH ...)
+
+ dti = date_range("20130101", periods=3)
+ dti_tz = date_range("20130101", periods=3).tz_localize("US/Eastern")
+ expected = TimedeltaIndex([0, 0, 0])
+
+ result = dti - dti
+ tm.assert_index_equal(result, expected)
+
+ result = dti_tz - dti_tz
+ tm.assert_index_equal(result, expected)
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
+ with pytest.raises(TypeError, match=msg):
+ dti_tz - dti
+
+ with pytest.raises(TypeError, match=msg):
+ dti - dti_tz
+
+ # isub
+ dti -= dti
+ tm.assert_index_equal(dti, expected)
+
+ # different length raises ValueError
+ dti1 = date_range("20130101", periods=3)
+ dti2 = date_range("20130101", periods=4)
+ msg = "cannot add indices of unequal length"
+ with pytest.raises(ValueError, match=msg):
+ dti1 - dti2
+
+ # NaN propagation
+ dti1 = DatetimeIndex(["2012-01-01", np.nan, "2012-01-03"])
+ dti2 = DatetimeIndex(["2012-01-02", "2012-01-03", np.nan])
+ expected = TimedeltaIndex(["1 days", np.nan, np.nan])
+ result = dti2 - dti1
+ tm.assert_index_equal(result, expected)
+
+ # -------------------------------------------------------------------
+ # TODO: Most of this block is moved from series or frame tests, needs
+ # cleanup, box-parametrization, and de-duplication
+
+ @pytest.mark.parametrize("op", [operator.add, operator.sub])
+ def test_timedelta64_equal_timedelta_supported_ops(self, op, box_with_array):
+ ser = Series(
+ [
+ Timestamp("20130301"),
+ Timestamp("20130228 23:00:00"),
+ Timestamp("20130228 22:00:00"),
+ Timestamp("20130228 21:00:00"),
+ ]
+ )
+ obj = box_with_array(ser)
+
+ intervals = ["D", "h", "m", "s", "us"]
+
+ def timedelta64(*args):
+ # see casting notes in NumPy gh-12927
+ return np.sum(list(starmap(np.timedelta64, zip(args, intervals))))
+
+ for d, h, m, s, us in product(*([range(2)] * 5)):
+ nptd = timedelta64(d, h, m, s, us)
+ pytd = timedelta(days=d, hours=h, minutes=m, seconds=s, microseconds=us)
+ lhs = op(obj, nptd)
+ rhs = op(obj, pytd)
+
+ tm.assert_equal(lhs, rhs)
+
+ def test_ops_nat_mixed_datetime64_timedelta64(self):
+ # GH#11349
+ timedelta_series = Series([NaT, Timedelta("1s")])
+ datetime_series = Series([NaT, Timestamp("19900315")])
+ nat_series_dtype_timedelta = Series([NaT, NaT], dtype="timedelta64[ns]")
+ nat_series_dtype_timestamp = Series([NaT, NaT], dtype="datetime64[ns]")
+ single_nat_dtype_datetime = Series([NaT], dtype="datetime64[ns]")
+ single_nat_dtype_timedelta = Series([NaT], dtype="timedelta64[ns]")
+
+ # subtraction
+ tm.assert_series_equal(
+ datetime_series - single_nat_dtype_datetime, nat_series_dtype_timedelta
+ )
+
+ tm.assert_series_equal(
+ datetime_series - single_nat_dtype_timedelta, nat_series_dtype_timestamp
+ )
+ tm.assert_series_equal(
+ -single_nat_dtype_timedelta + datetime_series, nat_series_dtype_timestamp
+ )
+
+ # without a Series wrapping the NaT, it is ambiguous
+ # whether it is a datetime64 or timedelta64
+ # defaults to interpreting it as timedelta64
+ tm.assert_series_equal(
+ nat_series_dtype_timestamp - single_nat_dtype_datetime,
+ nat_series_dtype_timedelta,
+ )
+
+ tm.assert_series_equal(
+ nat_series_dtype_timestamp - single_nat_dtype_timedelta,
+ nat_series_dtype_timestamp,
+ )
+ tm.assert_series_equal(
+ -single_nat_dtype_timedelta + nat_series_dtype_timestamp,
+ nat_series_dtype_timestamp,
+ )
+ msg = "cannot subtract a datelike"
+ with pytest.raises(TypeError, match=msg):
+ timedelta_series - single_nat_dtype_datetime
+
+ # addition
+ tm.assert_series_equal(
+ nat_series_dtype_timestamp + single_nat_dtype_timedelta,
+ nat_series_dtype_timestamp,
+ )
+ tm.assert_series_equal(
+ single_nat_dtype_timedelta + nat_series_dtype_timestamp,
+ nat_series_dtype_timestamp,
+ )
+
+ tm.assert_series_equal(
+ nat_series_dtype_timestamp + single_nat_dtype_timedelta,
+ nat_series_dtype_timestamp,
+ )
+ tm.assert_series_equal(
+ single_nat_dtype_timedelta + nat_series_dtype_timestamp,
+ nat_series_dtype_timestamp,
+ )
+
+ tm.assert_series_equal(
+ nat_series_dtype_timedelta + single_nat_dtype_datetime,
+ nat_series_dtype_timestamp,
+ )
+ tm.assert_series_equal(
+ single_nat_dtype_datetime + nat_series_dtype_timedelta,
+ nat_series_dtype_timestamp,
+ )
+
+ def test_ufunc_coercions(self):
+ idx = date_range("2011-01-01", periods=3, freq="2D", name="x")
+
+ delta = np.timedelta64(1, "D")
+ exp = date_range("2011-01-02", periods=3, freq="2D", name="x")
+ for result in [idx + delta, np.add(idx, delta)]:
+ assert isinstance(result, DatetimeIndex)
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "2D"
+
+ exp = date_range("2010-12-31", periods=3, freq="2D", name="x")
+
+ for result in [idx - delta, np.subtract(idx, delta)]:
+ assert isinstance(result, DatetimeIndex)
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "2D"
+
+ # When adding/subtracting an ndarray (which has no .freq), the result
+ # does not infer freq
+ idx = idx._with_freq(None)
+ delta = np.array(
+ [np.timedelta64(1, "D"), np.timedelta64(2, "D"), np.timedelta64(3, "D")]
+ )
+ exp = DatetimeIndex(["2011-01-02", "2011-01-05", "2011-01-08"], name="x")
+
+ for result in [idx + delta, np.add(idx, delta)]:
+ tm.assert_index_equal(result, exp)
+ assert result.freq == exp.freq
+
+ exp = DatetimeIndex(["2010-12-31", "2011-01-01", "2011-01-02"], name="x")
+ for result in [idx - delta, np.subtract(idx, delta)]:
+ assert isinstance(result, DatetimeIndex)
+ tm.assert_index_equal(result, exp)
+ assert result.freq == exp.freq
+
+ def test_dti_add_series(self, tz_naive_fixture, names):
+ # GH#13905
+ tz = tz_naive_fixture
+ index = DatetimeIndex(
+ ["2016-06-28 05:30", "2016-06-28 05:31"], tz=tz, name=names[0]
+ )
+ ser = Series([Timedelta(seconds=5)] * 2, index=index, name=names[1])
+ expected = Series(index + Timedelta(seconds=5), index=index, name=names[2])
+
+ # passing name arg isn't enough when names[2] is None
+ expected.name = names[2]
+ assert expected.dtype == index.dtype
+ result = ser + index
+ tm.assert_series_equal(result, expected)
+ result2 = index + ser
+ tm.assert_series_equal(result2, expected)
+
+ expected = index + Timedelta(seconds=5)
+ result3 = ser.values + index
+ tm.assert_index_equal(result3, expected)
+ result4 = index + ser.values
+ tm.assert_index_equal(result4, expected)
+
+ @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub])
+ def test_dti_addsub_offset_arraylike(
+ self, tz_naive_fixture, names, op, index_or_series
+ ):
+ # GH#18849, GH#19744
+ other_box = index_or_series
+
+ tz = tz_naive_fixture
+ dti = date_range("2017-01-01", periods=2, tz=tz, name=names[0])
+ other = other_box([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)], name=names[1])
+
+ xbox = get_upcast_box(dti, other)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res = op(dti, other)
+
+ expected = DatetimeIndex(
+ [op(dti[n], other[n]) for n in range(len(dti))], name=names[2], freq="infer"
+ )
+ expected = tm.box_expected(expected, xbox).astype(object)
+ tm.assert_equal(res, expected)
+
+ @pytest.mark.parametrize("other_box", [pd.Index, np.array])
+ def test_dti_addsub_object_arraylike(
+ self, tz_naive_fixture, box_with_array, other_box
+ ):
+ tz = tz_naive_fixture
+
+ dti = date_range("2017-01-01", periods=2, tz=tz)
+ dtarr = tm.box_expected(dti, box_with_array)
+ other = other_box([pd.offsets.MonthEnd(), Timedelta(days=4)])
+ xbox = get_upcast_box(dtarr, other)
+
+ expected = DatetimeIndex(["2017-01-31", "2017-01-06"], tz=tz_naive_fixture)
+ expected = tm.box_expected(expected, xbox).astype(object)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = dtarr + other
+ tm.assert_equal(result, expected)
+
+ expected = DatetimeIndex(["2016-12-31", "2016-12-29"], tz=tz_naive_fixture)
+ expected = tm.box_expected(expected, xbox).astype(object)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = dtarr - other
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize("years", [-1, 0, 1])
+@pytest.mark.parametrize("months", [-2, 0, 2])
+def test_shift_months(years, months):
+ dti = DatetimeIndex(
+ [
+ Timestamp("2000-01-05 00:15:00"),
+ Timestamp("2000-01-31 00:23:00"),
+ Timestamp("2000-01-01"),
+ Timestamp("2000-02-29"),
+ Timestamp("2000-12-31"),
+ ]
+ )
+ actual = DatetimeIndex(shift_months(dti.asi8, years * 12 + months))
+
+ raw = [x + pd.offsets.DateOffset(years=years, months=months) for x in dti]
+ expected = DatetimeIndex(raw)
+ tm.assert_index_equal(actual, expected)
+
+
+def test_dt64arr_addsub_object_dtype_2d():
+ # block-wise DataFrame operations will require operating on 2D
+ # DatetimeArray/TimedeltaArray, so check that specifically.
+ dti = date_range("1994-02-13", freq="2W", periods=4)
+ dta = dti._data.reshape((4, 1))
+
+ other = np.array([[pd.offsets.Day(n)] for n in range(4)])
+ assert other.shape == dta.shape
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = dta + other
+ with tm.assert_produces_warning(PerformanceWarning):
+ expected = (dta[:, 0] + other[:, 0]).reshape(-1, 1)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ # Case where we expect to get a TimedeltaArray back
+ result2 = dta - dta.astype(object)
+
+ assert result2.shape == (4, 1)
+ assert all(td._value == 0 for td in result2.ravel())
+
+
+def test_non_nano_dt64_addsub_np_nat_scalars():
+ # GH 52295
+ ser = Series([1233242342344, 232432434324, 332434242344], dtype="datetime64[ms]")
+ result = ser - np.datetime64("nat", "ms")
+ expected = Series([NaT] * 3, dtype="timedelta64[ms]")
+ tm.assert_series_equal(result, expected)
+
+ result = ser + np.timedelta64("nat", "ms")
+ expected = Series([NaT] * 3, dtype="datetime64[ms]")
+ tm.assert_series_equal(result, expected)
+
+
+def test_non_nano_dt64_addsub_np_nat_scalars_unitless():
+ # GH 52295
+ # TODO: Can we default to the ser unit?
+ ser = Series([1233242342344, 232432434324, 332434242344], dtype="datetime64[ms]")
+ result = ser - np.datetime64("nat")
+ expected = Series([NaT] * 3, dtype="timedelta64[ns]")
+ tm.assert_series_equal(result, expected)
+
+ result = ser + np.timedelta64("nat")
+ expected = Series([NaT] * 3, dtype="datetime64[ns]")
+ tm.assert_series_equal(result, expected)
+
+
+def test_non_nano_dt64_addsub_np_nat_scalars_unsupported_unit():
+ # GH 52295
+ ser = Series([12332, 23243, 33243], dtype="datetime64[s]")
+ result = ser - np.datetime64("nat", "D")
+ expected = Series([NaT] * 3, dtype="timedelta64[s]")
+ tm.assert_series_equal(result, expected)
+
+ result = ser + np.timedelta64("nat", "D")
+ expected = Series([NaT] * 3, dtype="datetime64[s]")
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_interval.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_interval.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e316cf419cb0d3be489f474a9c6d889e668e7c9
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_interval.py
@@ -0,0 +1,306 @@
+import operator
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.common import is_list_like
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ Index,
+ Interval,
+ IntervalIndex,
+ Period,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+ period_range,
+ timedelta_range,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ BooleanArray,
+ IntervalArray,
+)
+from pandas.tests.arithmetic.common import get_upcast_box
+
+
+@pytest.fixture(
+ params=[
+ (Index([0, 2, 4, 4]), Index([1, 3, 5, 8])),
+ (Index([0.0, 1.0, 2.0, np.nan]), Index([1.0, 2.0, 3.0, np.nan])),
+ (
+ timedelta_range("0 days", periods=3).insert(3, pd.NaT),
+ timedelta_range("1 day", periods=3).insert(3, pd.NaT),
+ ),
+ (
+ date_range("20170101", periods=3).insert(3, pd.NaT),
+ date_range("20170102", periods=3).insert(3, pd.NaT),
+ ),
+ (
+ date_range("20170101", periods=3, tz="US/Eastern").insert(3, pd.NaT),
+ date_range("20170102", periods=3, tz="US/Eastern").insert(3, pd.NaT),
+ ),
+ ],
+ ids=lambda x: str(x[0].dtype),
+)
+def left_right_dtypes(request):
+ """
+ Fixture for building an IntervalArray from various dtypes
+ """
+ return request.param
+
+
+@pytest.fixture
+def interval_array(left_right_dtypes):
+ """
+ Fixture to generate an IntervalArray of various dtypes containing NA if possible
+ """
+ left, right = left_right_dtypes
+ return IntervalArray.from_arrays(left, right)
+
+
+def create_categorical_intervals(left, right, closed="right"):
+ return Categorical(IntervalIndex.from_arrays(left, right, closed))
+
+
+def create_series_intervals(left, right, closed="right"):
+ return Series(IntervalArray.from_arrays(left, right, closed))
+
+
+def create_series_categorical_intervals(left, right, closed="right"):
+ return Series(Categorical(IntervalIndex.from_arrays(left, right, closed)))
+
+
+class TestComparison:
+ @pytest.fixture(params=[operator.eq, operator.ne])
+ def op(self, request):
+ return request.param
+
+ @pytest.fixture(
+ params=[
+ IntervalArray.from_arrays,
+ IntervalIndex.from_arrays,
+ create_categorical_intervals,
+ create_series_intervals,
+ create_series_categorical_intervals,
+ ],
+ ids=[
+ "IntervalArray",
+ "IntervalIndex",
+ "Categorical[Interval]",
+ "Series[Interval]",
+ "Series[Categorical[Interval]]",
+ ],
+ )
+ def interval_constructor(self, request):
+ """
+ Fixture for all pandas native interval constructors.
+ To be used as the LHS of IntervalArray comparisons.
+ """
+ return request.param
+
+ def elementwise_comparison(self, op, interval_array, other):
+ """
+ Helper that performs elementwise comparisons between `array` and `other`
+ """
+ other = other if is_list_like(other) else [other] * len(interval_array)
+ expected = np.array([op(x, y) for x, y in zip(interval_array, other)])
+ if isinstance(other, Series):
+ return Series(expected, index=other.index)
+ return expected
+
+ def test_compare_scalar_interval(self, op, interval_array):
+ # matches first interval
+ other = interval_array[0]
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # matches on a single endpoint but not both
+ other = Interval(interval_array.left[0], interval_array.right[1])
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed):
+ interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
+ other = Interval(0, 1, closed=other_closed)
+
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_compare_scalar_na(self, op, interval_array, nulls_fixture, box_with_array):
+ box = box_with_array
+ obj = tm.box_expected(interval_array, box)
+ result = op(obj, nulls_fixture)
+
+ if nulls_fixture is pd.NA:
+ # GH#31882
+ exp = np.ones(interval_array.shape, dtype=bool)
+ expected = BooleanArray(exp, exp)
+ else:
+ expected = self.elementwise_comparison(op, interval_array, nulls_fixture)
+
+ if not (box is Index and nulls_fixture is pd.NA):
+ # don't cast expected from BooleanArray to ndarray[object]
+ xbox = get_upcast_box(obj, nulls_fixture, True)
+ expected = tm.box_expected(expected, xbox)
+
+ tm.assert_equal(result, expected)
+
+ rev = op(nulls_fixture, obj)
+ tm.assert_equal(rev, expected)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ 0,
+ 1.0,
+ True,
+ "foo",
+ Timestamp("2017-01-01"),
+ Timestamp("2017-01-01", tz="US/Eastern"),
+ Timedelta("0 days"),
+ Period("2017-01-01", "D"),
+ ],
+ )
+ def test_compare_scalar_other(self, op, interval_array, other):
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_compare_list_like_interval(self, op, interval_array, interval_constructor):
+ # same endpoints
+ other = interval_constructor(interval_array.left, interval_array.right)
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_equal(result, expected)
+
+ # different endpoints
+ other = interval_constructor(
+ interval_array.left[::-1], interval_array.right[::-1]
+ )
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_equal(result, expected)
+
+ # all nan endpoints
+ other = interval_constructor([np.nan] * 4, [np.nan] * 4)
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_equal(result, expected)
+
+ def test_compare_list_like_interval_mixed_closed(
+ self, op, interval_constructor, closed, other_closed
+ ):
+ interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
+ other = interval_constructor(range(2), range(1, 3), closed=other_closed)
+
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ (
+ Interval(0, 1),
+ Interval(Timedelta("1 day"), Timedelta("2 days")),
+ Interval(4, 5, "both"),
+ Interval(10, 20, "neither"),
+ ),
+ (0, 1.5, Timestamp("20170103"), np.nan),
+ (
+ Timestamp("20170102", tz="US/Eastern"),
+ Timedelta("2 days"),
+ "baz",
+ pd.NaT,
+ ),
+ ],
+ )
+ def test_compare_list_like_object(self, op, interval_array, other):
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_compare_list_like_nan(self, op, interval_array, nulls_fixture):
+ other = [nulls_fixture] * 4
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ np.arange(4, dtype="int64"),
+ np.arange(4, dtype="float64"),
+ date_range("2017-01-01", periods=4),
+ date_range("2017-01-01", periods=4, tz="US/Eastern"),
+ timedelta_range("0 days", periods=4),
+ period_range("2017-01-01", periods=4, freq="D"),
+ Categorical(list("abab")),
+ Categorical(date_range("2017-01-01", periods=4)),
+ pd.array(list("abcd")),
+ pd.array(["foo", 3.14, None, object()], dtype=object),
+ ],
+ ids=lambda x: str(x.dtype),
+ )
+ def test_compare_list_like_other(self, op, interval_array, other):
+ result = op(interval_array, other)
+ expected = self.elementwise_comparison(op, interval_array, other)
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("length", [1, 3, 5])
+ @pytest.mark.parametrize("other_constructor", [IntervalArray, list])
+ def test_compare_length_mismatch_errors(self, op, other_constructor, length):
+ interval_array = IntervalArray.from_arrays(range(4), range(1, 5))
+ other = other_constructor([Interval(0, 1)] * length)
+ with pytest.raises(ValueError, match="Lengths must match to compare"):
+ op(interval_array, other)
+
+ @pytest.mark.parametrize(
+ "constructor, expected_type, assert_func",
+ [
+ (IntervalIndex, np.array, tm.assert_numpy_array_equal),
+ (Series, Series, tm.assert_series_equal),
+ ],
+ )
+ def test_index_series_compat(self, op, constructor, expected_type, assert_func):
+ # IntervalIndex/Series that rely on IntervalArray for comparisons
+ breaks = range(4)
+ index = constructor(IntervalIndex.from_breaks(breaks))
+
+ # scalar comparisons
+ other = index[0]
+ result = op(index, other)
+ expected = expected_type(self.elementwise_comparison(op, index, other))
+ assert_func(result, expected)
+
+ other = breaks[0]
+ result = op(index, other)
+ expected = expected_type(self.elementwise_comparison(op, index, other))
+ assert_func(result, expected)
+
+ # list-like comparisons
+ other = IntervalArray.from_breaks(breaks)
+ result = op(index, other)
+ expected = expected_type(self.elementwise_comparison(op, index, other))
+ assert_func(result, expected)
+
+ other = [index[0], breaks[0], "foo"]
+ result = op(index, other)
+ expected = expected_type(self.elementwise_comparison(op, index, other))
+ assert_func(result, expected)
+
+ @pytest.mark.parametrize("scalars", ["a", False, 1, 1.0, None])
+ def test_comparison_operations(self, scalars):
+ # GH #28981
+ expected = Series([False, False])
+ s = Series([Interval(0, 1), Interval(1, 2)], dtype="interval")
+ result = s == scalars
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_numeric.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_numeric.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa17c24fffb262729740a9c30ead31fa2ac9ca17
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_numeric.py
@@ -0,0 +1,1490 @@
+# Arithmetic tests for DataFrame/Series/Index/Array classes that should
+# behave identically.
+# Specifically for numeric dtypes
+from __future__ import annotations
+
+from collections import abc
+from datetime import timedelta
+from decimal import Decimal
+import operator
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ Index,
+ RangeIndex,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ array,
+)
+import pandas._testing as tm
+from pandas.core import ops
+from pandas.core.computation import expressions as expr
+from pandas.tests.arithmetic.common import (
+ assert_invalid_addsub_type,
+ assert_invalid_comparison,
+)
+
+
+@pytest.fixture(params=[Index, Series, tm.to_array])
+def box_pandas_1d_array(request):
+ """
+ Fixture to test behavior for Index, Series and tm.to_array classes
+ """
+ return request.param
+
+
+def adjust_negative_zero(zero, expected):
+ """
+ Helper to adjust the expected result if we are dividing by -0.0
+ as opposed to 0.0
+ """
+ if np.signbit(np.array(zero)).any():
+ # All entries in the `zero` fixture should be either
+ # all-negative or no-negative.
+ assert np.signbit(np.array(zero)).all()
+
+ expected *= -1
+
+ return expected
+
+
+def compare_op(series, other, op):
+ left = np.abs(series) if op in (ops.rpow, operator.pow) else series
+ right = np.abs(other) if op in (ops.rpow, operator.pow) else other
+
+ cython_or_numpy = op(left, right)
+ python = left.combine(right, op)
+ if isinstance(other, Series) and not other.index.equals(series.index):
+ python.index = python.index._with_freq(None)
+ tm.assert_series_equal(cython_or_numpy, python)
+
+
+# TODO: remove this kludge once mypy stops giving false positives here
+# List comprehension has incompatible type List[PandasObject]; expected List[RangeIndex]
+# See GH#29725
+_ldtypes = ["i1", "i2", "i4", "i8", "u1", "u2", "u4", "u8", "f2", "f4", "f8"]
+lefts: list[Index | Series] = [RangeIndex(10, 40, 10)]
+lefts.extend([Series([10, 20, 30], dtype=dtype) for dtype in _ldtypes])
+lefts.extend([Index([10, 20, 30], dtype=dtype) for dtype in _ldtypes if dtype != "f2"])
+
+# ------------------------------------------------------------------
+# Comparisons
+
+
+class TestNumericComparisons:
+ def test_operator_series_comparison_zerorank(self):
+ # GH#13006
+ result = np.float64(0) > Series([1, 2, 3])
+ expected = 0.0 > Series([1, 2, 3])
+ tm.assert_series_equal(result, expected)
+ result = Series([1, 2, 3]) < np.float64(0)
+ expected = Series([1, 2, 3]) < 0.0
+ tm.assert_series_equal(result, expected)
+ result = np.array([0, 1, 2])[0] > Series([0, 1, 2])
+ expected = 0.0 > Series([1, 2, 3])
+ tm.assert_series_equal(result, expected)
+
+ def test_df_numeric_cmp_dt64_raises(self, box_with_array, fixed_now_ts):
+ # GH#8932, GH#22163
+ ts = fixed_now_ts
+ obj = np.array(range(5))
+ obj = tm.box_expected(obj, box_with_array)
+
+ assert_invalid_comparison(obj, ts, box_with_array)
+
+ def test_compare_invalid(self):
+ # GH#8058
+ # ops testing
+ a = Series(np.random.default_rng(2).standard_normal(5), name=0)
+ b = Series(np.random.default_rng(2).standard_normal(5))
+ b.name = pd.Timestamp("2000-01-01")
+ tm.assert_series_equal(a / b, 1 / (b / a))
+
+ def test_numeric_cmp_string_numexpr_path(self, box_with_array, monkeypatch):
+ # GH#36377, GH#35700
+ box = box_with_array
+ xbox = box if box is not Index else np.ndarray
+
+ obj = Series(np.random.default_rng(2).standard_normal(51))
+ obj = tm.box_expected(obj, box, transpose=False)
+ with monkeypatch.context() as m:
+ m.setattr(expr, "_MIN_ELEMENTS", 50)
+ result = obj == "a"
+
+ expected = Series(np.zeros(51, dtype=bool))
+ expected = tm.box_expected(expected, xbox, transpose=False)
+ tm.assert_equal(result, expected)
+
+ with monkeypatch.context() as m:
+ m.setattr(expr, "_MIN_ELEMENTS", 50)
+ result = obj != "a"
+ tm.assert_equal(result, ~expected)
+
+ msg = "Invalid comparison between dtype=float64 and str"
+ with pytest.raises(TypeError, match=msg):
+ obj < "a"
+
+
+# ------------------------------------------------------------------
+# Numeric dtypes Arithmetic with Datetime/Timedelta Scalar
+
+
+class TestNumericArraylikeArithmeticWithDatetimeLike:
+ @pytest.mark.parametrize("box_cls", [np.array, Index, Series])
+ @pytest.mark.parametrize(
+ "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype)
+ )
+ def test_mul_td64arr(self, left, box_cls):
+ # GH#22390
+ right = np.array([1, 2, 3], dtype="m8[s]")
+ right = box_cls(right)
+
+ expected = TimedeltaIndex(["10s", "40s", "90s"], dtype=right.dtype)
+
+ if isinstance(left, Series) or box_cls is Series:
+ expected = Series(expected)
+ assert expected.dtype == right.dtype
+
+ result = left * right
+ tm.assert_equal(result, expected)
+
+ result = right * left
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("box_cls", [np.array, Index, Series])
+ @pytest.mark.parametrize(
+ "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype)
+ )
+ def test_div_td64arr(self, left, box_cls):
+ # GH#22390
+ right = np.array([10, 40, 90], dtype="m8[s]")
+ right = box_cls(right)
+
+ expected = TimedeltaIndex(["1s", "2s", "3s"], dtype=right.dtype)
+ if isinstance(left, Series) or box_cls is Series:
+ expected = Series(expected)
+ assert expected.dtype == right.dtype
+
+ result = right / left
+ tm.assert_equal(result, expected)
+
+ result = right // left
+ tm.assert_equal(result, expected)
+
+ # (true_) needed for min-versions build 2022-12-26
+ msg = "ufunc '(true_)?divide' cannot use operands with types"
+ with pytest.raises(TypeError, match=msg):
+ left / right
+
+ msg = "ufunc 'floor_divide' cannot use operands with types"
+ with pytest.raises(TypeError, match=msg):
+ left // right
+
+ # TODO: also test Tick objects;
+ # see test_numeric_arr_rdiv_tdscalar for note on these failing
+ @pytest.mark.parametrize(
+ "scalar_td",
+ [
+ Timedelta(days=1),
+ Timedelta(days=1).to_timedelta64(),
+ Timedelta(days=1).to_pytimedelta(),
+ Timedelta(days=1).to_timedelta64().astype("timedelta64[s]"),
+ Timedelta(days=1).to_timedelta64().astype("timedelta64[ms]"),
+ ],
+ ids=lambda x: type(x).__name__,
+ )
+ def test_numeric_arr_mul_tdscalar(self, scalar_td, numeric_idx, box_with_array):
+ # GH#19333
+ box = box_with_array
+ index = numeric_idx
+ expected = TimedeltaIndex([Timedelta(days=n) for n in range(len(index))])
+ if isinstance(scalar_td, np.timedelta64):
+ dtype = scalar_td.dtype
+ expected = expected.astype(dtype)
+ elif type(scalar_td) is timedelta:
+ expected = expected.astype("m8[us]")
+
+ index = tm.box_expected(index, box)
+ expected = tm.box_expected(expected, box)
+
+ result = index * scalar_td
+ tm.assert_equal(result, expected)
+
+ commute = scalar_td * index
+ tm.assert_equal(commute, expected)
+
+ @pytest.mark.parametrize(
+ "scalar_td",
+ [
+ Timedelta(days=1),
+ Timedelta(days=1).to_timedelta64(),
+ Timedelta(days=1).to_pytimedelta(),
+ ],
+ ids=lambda x: type(x).__name__,
+ )
+ @pytest.mark.parametrize("dtype", [np.int64, np.float64])
+ def test_numeric_arr_mul_tdscalar_numexpr_path(
+ self, dtype, scalar_td, box_with_array
+ ):
+ # GH#44772 for the float64 case
+ box = box_with_array
+
+ arr_i8 = np.arange(2 * 10**4).astype(np.int64, copy=False)
+ arr = arr_i8.astype(dtype, copy=False)
+ obj = tm.box_expected(arr, box, transpose=False)
+
+ expected = arr_i8.view("timedelta64[D]").astype("timedelta64[ns]")
+ if type(scalar_td) is timedelta:
+ expected = expected.astype("timedelta64[us]")
+
+ expected = tm.box_expected(expected, box, transpose=False)
+
+ result = obj * scalar_td
+ tm.assert_equal(result, expected)
+
+ result = scalar_td * obj
+ tm.assert_equal(result, expected)
+
+ def test_numeric_arr_rdiv_tdscalar(self, three_days, numeric_idx, box_with_array):
+ box = box_with_array
+
+ index = numeric_idx[1:3]
+
+ expected = TimedeltaIndex(["3 Days", "36 Hours"])
+ if isinstance(three_days, np.timedelta64):
+ dtype = three_days.dtype
+ if dtype < np.dtype("m8[s]"):
+ # i.e. resolution is lower -> use lowest supported resolution
+ dtype = np.dtype("m8[s]")
+ expected = expected.astype(dtype)
+ elif type(three_days) is timedelta:
+ expected = expected.astype("m8[us]")
+
+ index = tm.box_expected(index, box)
+ expected = tm.box_expected(expected, box)
+
+ result = three_days / index
+ tm.assert_equal(result, expected)
+
+ msg = "cannot use operands with types dtype"
+ with pytest.raises(TypeError, match=msg):
+ index / three_days
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ Timedelta(hours=31),
+ Timedelta(hours=31).to_pytimedelta(),
+ Timedelta(hours=31).to_timedelta64(),
+ Timedelta(hours=31).to_timedelta64().astype("m8[h]"),
+ np.timedelta64("NaT"),
+ np.timedelta64("NaT", "D"),
+ pd.offsets.Minute(3),
+ pd.offsets.Second(0),
+ # GH#28080 numeric+datetimelike should raise; Timestamp used
+ # to raise NullFrequencyError but that behavior was removed in 1.0
+ pd.Timestamp("2021-01-01", tz="Asia/Tokyo"),
+ pd.Timestamp("2021-01-01"),
+ pd.Timestamp("2021-01-01").to_pydatetime(),
+ pd.Timestamp("2021-01-01", tz="UTC").to_pydatetime(),
+ pd.Timestamp("2021-01-01").to_datetime64(),
+ np.datetime64("NaT", "ns"),
+ pd.NaT,
+ ],
+ ids=repr,
+ )
+ def test_add_sub_datetimedeltalike_invalid(
+ self, numeric_idx, other, box_with_array
+ ):
+ box = box_with_array
+
+ left = tm.box_expected(numeric_idx, box)
+ msg = "|".join(
+ [
+ "unsupported operand type",
+ "Addition/subtraction of integers and integer-arrays",
+ "Instead of adding/subtracting",
+ "cannot use operands with types dtype",
+ "Concatenation operation is not implemented for NumPy arrays",
+ "Cannot (add|subtract) NaT (to|from) ndarray",
+ # pd.array vs np.datetime64 case
+ r"operand type\(s\) all returned NotImplemented from __array_ufunc__",
+ "can only perform ops with numeric values",
+ "cannot subtract DatetimeArray from ndarray",
+ # pd.Timedelta(1) + Index([0, 1, 2])
+ "Cannot add or subtract Timedelta from integers",
+ ]
+ )
+ assert_invalid_addsub_type(left, other, msg)
+
+
+# ------------------------------------------------------------------
+# Arithmetic
+
+
+class TestDivisionByZero:
+ def test_div_zero(self, zero, numeric_idx):
+ idx = numeric_idx
+
+ expected = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64)
+ # We only adjust for Index, because Series does not yet apply
+ # the adjustment correctly.
+ expected2 = adjust_negative_zero(zero, expected)
+
+ result = idx / zero
+ tm.assert_index_equal(result, expected2)
+ ser_compat = Series(idx).astype("i8") / np.array(zero).astype("i8")
+ tm.assert_series_equal(ser_compat, Series(expected))
+
+ def test_floordiv_zero(self, zero, numeric_idx):
+ idx = numeric_idx
+
+ expected = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64)
+ # We only adjust for Index, because Series does not yet apply
+ # the adjustment correctly.
+ expected2 = adjust_negative_zero(zero, expected)
+
+ result = idx // zero
+ tm.assert_index_equal(result, expected2)
+ ser_compat = Series(idx).astype("i8") // np.array(zero).astype("i8")
+ tm.assert_series_equal(ser_compat, Series(expected))
+
+ def test_mod_zero(self, zero, numeric_idx):
+ idx = numeric_idx
+
+ expected = Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64)
+ result = idx % zero
+ tm.assert_index_equal(result, expected)
+ ser_compat = Series(idx).astype("i8") % np.array(zero).astype("i8")
+ tm.assert_series_equal(ser_compat, Series(result))
+
+ def test_divmod_zero(self, zero, numeric_idx):
+ idx = numeric_idx
+
+ exleft = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64)
+ exright = Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64)
+ exleft = adjust_negative_zero(zero, exleft)
+
+ result = divmod(idx, zero)
+ tm.assert_index_equal(result[0], exleft)
+ tm.assert_index_equal(result[1], exright)
+
+ @pytest.mark.parametrize("op", [operator.truediv, operator.floordiv])
+ def test_div_negative_zero(self, zero, numeric_idx, op):
+ # Check that -1 / -0.0 returns np.inf, not -np.inf
+ if numeric_idx.dtype == np.uint64:
+ pytest.skip(f"Not relevant for {numeric_idx.dtype}")
+ idx = numeric_idx - 3
+
+ expected = Index([-np.inf, -np.inf, -np.inf, np.nan, np.inf], dtype=np.float64)
+ expected = adjust_negative_zero(zero, expected)
+
+ result = op(idx, zero)
+ tm.assert_index_equal(result, expected)
+
+ # ------------------------------------------------------------------
+
+ @pytest.mark.parametrize("dtype1", [np.int64, np.float64, np.uint64])
+ def test_ser_div_ser(
+ self,
+ switch_numexpr_min_elements,
+ dtype1,
+ any_real_numpy_dtype,
+ ):
+ # no longer do integer div for any ops, but deal with the 0's
+ dtype2 = any_real_numpy_dtype
+
+ first = Series([3, 4, 5, 8], name="first").astype(dtype1)
+ second = Series([0, 0, 0, 3], name="second").astype(dtype2)
+
+ with np.errstate(all="ignore"):
+ expected = Series(
+ first.values.astype(np.float64) / second.values,
+ dtype="float64",
+ name=None,
+ )
+ expected.iloc[0:3] = np.inf
+ if first.dtype == "int64" and second.dtype == "float32":
+ # when using numexpr, the casting rules are slightly different
+ # and int64/float32 combo results in float32 instead of float64
+ if expr.USE_NUMEXPR and switch_numexpr_min_elements == 0:
+ expected = expected.astype("float32")
+
+ result = first / second
+ tm.assert_series_equal(result, expected)
+ assert not result.equals(second / first)
+
+ @pytest.mark.parametrize("dtype1", [np.int64, np.float64, np.uint64])
+ def test_ser_divmod_zero(self, dtype1, any_real_numpy_dtype):
+ # GH#26987
+ dtype2 = any_real_numpy_dtype
+ left = Series([1, 1]).astype(dtype1)
+ right = Series([0, 2]).astype(dtype2)
+
+ # GH#27321 pandas convention is to set 1 // 0 to np.inf, as opposed
+ # to numpy which sets to np.nan; patch `expected[0]` below
+ expected = left // right, left % right
+ expected = list(expected)
+ expected[0] = expected[0].astype(np.float64)
+ expected[0][0] = np.inf
+ result = divmod(left, right)
+
+ tm.assert_series_equal(result[0], expected[0])
+ tm.assert_series_equal(result[1], expected[1])
+
+ # rdivmod case
+ result = divmod(left.values, right)
+ tm.assert_series_equal(result[0], expected[0])
+ tm.assert_series_equal(result[1], expected[1])
+
+ def test_ser_divmod_inf(self):
+ left = Series([np.inf, 1.0])
+ right = Series([np.inf, 2.0])
+
+ expected = left // right, left % right
+ result = divmod(left, right)
+
+ tm.assert_series_equal(result[0], expected[0])
+ tm.assert_series_equal(result[1], expected[1])
+
+ # rdivmod case
+ result = divmod(left.values, right)
+ tm.assert_series_equal(result[0], expected[0])
+ tm.assert_series_equal(result[1], expected[1])
+
+ def test_rdiv_zero_compat(self):
+ # GH#8674
+ zero_array = np.array([0] * 5)
+ data = np.random.default_rng(2).standard_normal(5)
+ expected = Series([0.0] * 5)
+
+ result = zero_array / Series(data)
+ tm.assert_series_equal(result, expected)
+
+ result = Series(zero_array) / data
+ tm.assert_series_equal(result, expected)
+
+ result = Series(zero_array) / Series(data)
+ tm.assert_series_equal(result, expected)
+
+ def test_div_zero_inf_signs(self):
+ # GH#9144, inf signing
+ ser = Series([-1, 0, 1], name="first")
+ expected = Series([-np.inf, np.nan, np.inf], name="first")
+
+ result = ser / 0
+ tm.assert_series_equal(result, expected)
+
+ def test_rdiv_zero(self):
+ # GH#9144
+ ser = Series([-1, 0, 1], name="first")
+ expected = Series([0.0, np.nan, 0.0], name="first")
+
+ result = 0 / ser
+ tm.assert_series_equal(result, expected)
+
+ def test_floordiv_div(self):
+ # GH#9144
+ ser = Series([-1, 0, 1], name="first")
+
+ result = ser // 0
+ expected = Series([-np.inf, np.nan, np.inf], name="first")
+ tm.assert_series_equal(result, expected)
+
+ def test_df_div_zero_df(self):
+ # integer div, but deal with the 0's (GH#9144)
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
+ result = df / df
+
+ first = Series([1.0, 1.0, 1.0, 1.0])
+ second = Series([np.nan, np.nan, np.nan, 1])
+ expected = pd.DataFrame({"first": first, "second": second})
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_div_zero_array(self):
+ # integer div, but deal with the 0's (GH#9144)
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
+
+ first = Series([1.0, 1.0, 1.0, 1.0])
+ second = Series([np.nan, np.nan, np.nan, 1])
+ expected = pd.DataFrame({"first": first, "second": second})
+
+ with np.errstate(all="ignore"):
+ arr = df.values.astype("float") / df.values
+ result = pd.DataFrame(arr, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_div_zero_int(self):
+ # integer div, but deal with the 0's (GH#9144)
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
+
+ result = df / 0
+ expected = pd.DataFrame(np.inf, index=df.index, columns=df.columns)
+ expected.iloc[0:3, 1] = np.nan
+ tm.assert_frame_equal(result, expected)
+
+ # numpy has a slightly different (wrong) treatment
+ with np.errstate(all="ignore"):
+ arr = df.values.astype("float64") / 0
+ result2 = pd.DataFrame(arr, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(result2, expected)
+
+ def test_df_div_zero_series_does_not_commute(self):
+ # integer div, but deal with the 0's (GH#9144)
+ df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
+ ser = df[0]
+ res = ser / df
+ res2 = df / ser
+ assert not res.fillna(0).equals(res2.fillna(0))
+
+ # ------------------------------------------------------------------
+ # Mod By Zero
+
+ def test_df_mod_zero_df(self, using_array_manager):
+ # GH#3590, modulo as ints
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
+ # this is technically wrong, as the integer portion is coerced to float
+ first = Series([0, 0, 0, 0])
+ if not using_array_manager:
+ # INFO(ArrayManager) BlockManager doesn't preserve dtype per column
+ # while ArrayManager performs op column-wisedoes and thus preserves
+ # dtype if possible
+ first = first.astype("float64")
+ second = Series([np.nan, np.nan, np.nan, 0])
+ expected = pd.DataFrame({"first": first, "second": second})
+ result = df % df
+ tm.assert_frame_equal(result, expected)
+
+ # GH#38939 If we dont pass copy=False, df is consolidated and
+ # result["first"] is float64 instead of int64
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]}, copy=False)
+ first = Series([0, 0, 0, 0], dtype="int64")
+ second = Series([np.nan, np.nan, np.nan, 0])
+ expected = pd.DataFrame({"first": first, "second": second})
+ result = df % df
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_mod_zero_array(self):
+ # GH#3590, modulo as ints
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
+
+ # this is technically wrong, as the integer portion is coerced to float
+ # ###
+ first = Series([0, 0, 0, 0], dtype="float64")
+ second = Series([np.nan, np.nan, np.nan, 0])
+ expected = pd.DataFrame({"first": first, "second": second})
+
+ # numpy has a slightly different (wrong) treatment
+ with np.errstate(all="ignore"):
+ arr = df.values % df.values
+ result2 = pd.DataFrame(arr, index=df.index, columns=df.columns, dtype="float64")
+ result2.iloc[0:3, 1] = np.nan
+ tm.assert_frame_equal(result2, expected)
+
+ def test_df_mod_zero_int(self):
+ # GH#3590, modulo as ints
+ df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
+
+ result = df % 0
+ expected = pd.DataFrame(np.nan, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(result, expected)
+
+ # numpy has a slightly different (wrong) treatment
+ with np.errstate(all="ignore"):
+ arr = df.values.astype("float64") % 0
+ result2 = pd.DataFrame(arr, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(result2, expected)
+
+ def test_df_mod_zero_series_does_not_commute(self):
+ # GH#3590, modulo as ints
+ # not commutative with series
+ df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
+ ser = df[0]
+ res = ser % df
+ res2 = df % ser
+ assert not res.fillna(0).equals(res2.fillna(0))
+
+
+class TestMultiplicationDivision:
+ # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__
+ # for non-timestamp/timedelta/period dtypes
+
+ def test_divide_decimal(self, box_with_array):
+ # resolves issue GH#9787
+ box = box_with_array
+ ser = Series([Decimal(10)])
+ expected = Series([Decimal(5)])
+
+ ser = tm.box_expected(ser, box)
+ expected = tm.box_expected(expected, box)
+
+ result = ser / Decimal(2)
+
+ tm.assert_equal(result, expected)
+
+ result = ser // Decimal(2)
+ tm.assert_equal(result, expected)
+
+ def test_div_equiv_binop(self):
+ # Test Series.div as well as Series.__div__
+ # float/integer issue
+ # GH#7785
+ first = Series([1, 0], name="first")
+ second = Series([-0.01, -0.02], name="second")
+ expected = Series([-0.01, -np.inf])
+
+ result = second.div(first)
+ tm.assert_series_equal(result, expected, check_names=False)
+
+ result = second / first
+ tm.assert_series_equal(result, expected)
+
+ def test_div_int(self, numeric_idx):
+ idx = numeric_idx
+ result = idx / 1
+ expected = idx.astype("float64")
+ tm.assert_index_equal(result, expected)
+
+ result = idx / 2
+ expected = Index(idx.values / 2)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("op", [operator.mul, ops.rmul, operator.floordiv])
+ def test_mul_int_identity(self, op, numeric_idx, box_with_array):
+ idx = numeric_idx
+ idx = tm.box_expected(idx, box_with_array)
+
+ result = op(idx, 1)
+ tm.assert_equal(result, idx)
+
+ def test_mul_int_array(self, numeric_idx):
+ idx = numeric_idx
+ didx = idx * idx
+
+ result = idx * np.array(5, dtype="int64")
+ tm.assert_index_equal(result, idx * 5)
+
+ arr_dtype = "uint64" if idx.dtype == np.uint64 else "int64"
+ result = idx * np.arange(5, dtype=arr_dtype)
+ tm.assert_index_equal(result, didx)
+
+ def test_mul_int_series(self, numeric_idx):
+ idx = numeric_idx
+ didx = idx * idx
+
+ arr_dtype = "uint64" if idx.dtype == np.uint64 else "int64"
+ result = idx * Series(np.arange(5, dtype=arr_dtype))
+ tm.assert_series_equal(result, Series(didx))
+
+ def test_mul_float_series(self, numeric_idx):
+ idx = numeric_idx
+ rng5 = np.arange(5, dtype="float64")
+
+ result = idx * Series(rng5 + 0.1)
+ expected = Series(rng5 * (rng5 + 0.1))
+ tm.assert_series_equal(result, expected)
+
+ def test_mul_index(self, numeric_idx):
+ idx = numeric_idx
+
+ result = idx * idx
+ tm.assert_index_equal(result, idx**2)
+
+ def test_mul_datelike_raises(self, numeric_idx):
+ idx = numeric_idx
+ msg = "cannot perform __rmul__ with this index type"
+ with pytest.raises(TypeError, match=msg):
+ idx * pd.date_range("20130101", periods=5)
+
+ def test_mul_size_mismatch_raises(self, numeric_idx):
+ idx = numeric_idx
+ msg = "operands could not be broadcast together"
+ with pytest.raises(ValueError, match=msg):
+ idx * idx[0:3]
+ with pytest.raises(ValueError, match=msg):
+ idx * np.array([1, 2])
+
+ @pytest.mark.parametrize("op", [operator.pow, ops.rpow])
+ def test_pow_float(self, op, numeric_idx, box_with_array):
+ # test power calculations both ways, GH#14973
+ box = box_with_array
+ idx = numeric_idx
+ expected = Index(op(idx.values, 2.0))
+
+ idx = tm.box_expected(idx, box)
+ expected = tm.box_expected(expected, box)
+
+ result = op(idx, 2.0)
+ tm.assert_equal(result, expected)
+
+ def test_modulo(self, numeric_idx, box_with_array):
+ # GH#9244
+ box = box_with_array
+ idx = numeric_idx
+ expected = Index(idx.values % 2)
+
+ idx = tm.box_expected(idx, box)
+ expected = tm.box_expected(expected, box)
+
+ result = idx % 2
+ tm.assert_equal(result, expected)
+
+ def test_divmod_scalar(self, numeric_idx):
+ idx = numeric_idx
+
+ result = divmod(idx, 2)
+ with np.errstate(all="ignore"):
+ div, mod = divmod(idx.values, 2)
+
+ expected = Index(div), Index(mod)
+ for r, e in zip(result, expected):
+ tm.assert_index_equal(r, e)
+
+ def test_divmod_ndarray(self, numeric_idx):
+ idx = numeric_idx
+ other = np.ones(idx.values.shape, dtype=idx.values.dtype) * 2
+
+ result = divmod(idx, other)
+ with np.errstate(all="ignore"):
+ div, mod = divmod(idx.values, other)
+
+ expected = Index(div), Index(mod)
+ for r, e in zip(result, expected):
+ tm.assert_index_equal(r, e)
+
+ def test_divmod_series(self, numeric_idx):
+ idx = numeric_idx
+ other = np.ones(idx.values.shape, dtype=idx.values.dtype) * 2
+
+ result = divmod(idx, Series(other))
+ with np.errstate(all="ignore"):
+ div, mod = divmod(idx.values, other)
+
+ expected = Series(div), Series(mod)
+ for r, e in zip(result, expected):
+ tm.assert_series_equal(r, e)
+
+ @pytest.mark.parametrize("other", [np.nan, 7, -23, 2.718, -3.14, np.inf])
+ def test_ops_np_scalar(self, other):
+ vals = np.random.default_rng(2).standard_normal((5, 3))
+ f = lambda x: pd.DataFrame(
+ x, index=list("ABCDE"), columns=["jim", "joe", "jolie"]
+ )
+
+ df = f(vals)
+
+ tm.assert_frame_equal(df / np.array(other), f(vals / other))
+ tm.assert_frame_equal(np.array(other) * df, f(vals * other))
+ tm.assert_frame_equal(df + np.array(other), f(vals + other))
+ tm.assert_frame_equal(np.array(other) - df, f(other - vals))
+
+ # TODO: This came from series.test.test_operators, needs cleanup
+ def test_operators_frame(self):
+ # rpow does not work with DataFrame
+ ts = tm.makeTimeSeries()
+ ts.name = "ts"
+
+ df = pd.DataFrame({"A": ts})
+
+ tm.assert_series_equal(ts + ts, ts + df["A"], check_names=False)
+ tm.assert_series_equal(ts**ts, ts ** df["A"], check_names=False)
+ tm.assert_series_equal(ts < ts, ts < df["A"], check_names=False)
+ tm.assert_series_equal(ts / ts, ts / df["A"], check_names=False)
+
+ # TODO: this came from tests.series.test_analytics, needs cleanup and
+ # de-duplication with test_modulo above
+ def test_modulo2(self):
+ with np.errstate(all="ignore"):
+ # GH#3590, modulo as ints
+ p = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
+ result = p["first"] % p["second"]
+ expected = Series(p["first"].values % p["second"].values, dtype="float64")
+ expected.iloc[0:3] = np.nan
+ tm.assert_series_equal(result, expected)
+
+ result = p["first"] % 0
+ expected = Series(np.nan, index=p.index, name="first")
+ tm.assert_series_equal(result, expected)
+
+ p = p.astype("float64")
+ result = p["first"] % p["second"]
+ expected = Series(p["first"].values % p["second"].values)
+ tm.assert_series_equal(result, expected)
+
+ p = p.astype("float64")
+ result = p["first"] % p["second"]
+ result2 = p["second"] % p["first"]
+ assert not result.equals(result2)
+
+ def test_modulo_zero_int(self):
+ # GH#9144
+ with np.errstate(all="ignore"):
+ s = Series([0, 1])
+
+ result = s % 0
+ expected = Series([np.nan, np.nan])
+ tm.assert_series_equal(result, expected)
+
+ result = 0 % s
+ expected = Series([np.nan, 0.0])
+ tm.assert_series_equal(result, expected)
+
+
+class TestAdditionSubtraction:
+ # __add__, __sub__, __radd__, __rsub__, __iadd__, __isub__
+ # for non-timestamp/timedelta/period dtypes
+
+ @pytest.mark.parametrize(
+ "first, second, expected",
+ [
+ (
+ Series([1, 2, 3], index=list("ABC"), name="x"),
+ Series([2, 2, 2], index=list("ABD"), name="x"),
+ Series([3.0, 4.0, np.nan, np.nan], index=list("ABCD"), name="x"),
+ ),
+ (
+ Series([1, 2, 3], index=list("ABC"), name="x"),
+ Series([2, 2, 2, 2], index=list("ABCD"), name="x"),
+ Series([3, 4, 5, np.nan], index=list("ABCD"), name="x"),
+ ),
+ ],
+ )
+ def test_add_series(self, first, second, expected):
+ # GH#1134
+ tm.assert_series_equal(first + second, expected)
+ tm.assert_series_equal(second + first, expected)
+
+ @pytest.mark.parametrize(
+ "first, second, expected",
+ [
+ (
+ pd.DataFrame({"x": [1, 2, 3]}, index=list("ABC")),
+ pd.DataFrame({"x": [2, 2, 2]}, index=list("ABD")),
+ pd.DataFrame({"x": [3.0, 4.0, np.nan, np.nan]}, index=list("ABCD")),
+ ),
+ (
+ pd.DataFrame({"x": [1, 2, 3]}, index=list("ABC")),
+ pd.DataFrame({"x": [2, 2, 2, 2]}, index=list("ABCD")),
+ pd.DataFrame({"x": [3, 4, 5, np.nan]}, index=list("ABCD")),
+ ),
+ ],
+ )
+ def test_add_frames(self, first, second, expected):
+ # GH#1134
+ tm.assert_frame_equal(first + second, expected)
+ tm.assert_frame_equal(second + first, expected)
+
+ # TODO: This came from series.test.test_operators, needs cleanup
+ def test_series_frame_radd_bug(self, fixed_now_ts):
+ # GH#353
+ vals = Series(tm.makeStringIndex())
+ result = "foo_" + vals
+ expected = vals.map(lambda x: "foo_" + x)
+ tm.assert_series_equal(result, expected)
+
+ frame = pd.DataFrame({"vals": vals})
+ result = "foo_" + frame
+ expected = pd.DataFrame({"vals": vals.map(lambda x: "foo_" + x)})
+ tm.assert_frame_equal(result, expected)
+
+ ts = tm.makeTimeSeries()
+ ts.name = "ts"
+
+ # really raise this time
+ fix_now = fixed_now_ts.to_pydatetime()
+ msg = "|".join(
+ [
+ "unsupported operand type",
+ # wrong error message, see https://github.com/numpy/numpy/issues/18832
+ "Concatenation operation",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ fix_now + ts
+
+ with pytest.raises(TypeError, match=msg):
+ ts + fix_now
+
+ # TODO: This came from series.test.test_operators, needs cleanup
+ def test_datetime64_with_index(self):
+ # arithmetic integer ops with an index
+ ser = Series(np.random.default_rng(2).standard_normal(5))
+ expected = ser - ser.index.to_series()
+ result = ser - ser.index
+ tm.assert_series_equal(result, expected)
+
+ # GH#4629
+ # arithmetic datetime64 ops with an index
+ ser = Series(
+ pd.date_range("20130101", periods=5),
+ index=pd.date_range("20130101", periods=5),
+ )
+ expected = ser - ser.index.to_series()
+ result = ser - ser.index
+ tm.assert_series_equal(result, expected)
+
+ msg = "cannot subtract PeriodArray from DatetimeArray"
+ with pytest.raises(TypeError, match=msg):
+ # GH#18850
+ result = ser - ser.index.to_period()
+
+ df = pd.DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)),
+ index=pd.date_range("20130101", periods=5),
+ )
+ df["date"] = pd.Timestamp("20130102")
+ df["expected"] = df["date"] - df.index.to_series()
+ df["result"] = df["date"] - df.index
+ tm.assert_series_equal(df["result"], df["expected"], check_names=False)
+
+ # TODO: taken from tests.frame.test_operators, needs cleanup
+ def test_frame_operators(self, float_frame):
+ frame = float_frame
+
+ garbage = np.random.default_rng(2).random(4)
+ colSeries = Series(garbage, index=np.array(frame.columns))
+
+ idSum = frame + frame
+ seriesSum = frame + colSeries
+
+ for col, series in idSum.items():
+ for idx, val in series.items():
+ origVal = frame[col][idx] * 2
+ if not np.isnan(val):
+ assert val == origVal
+ else:
+ assert np.isnan(origVal)
+
+ for col, series in seriesSum.items():
+ for idx, val in series.items():
+ origVal = frame[col][idx] + colSeries[col]
+ if not np.isnan(val):
+ assert val == origVal
+ else:
+ assert np.isnan(origVal)
+
+ def test_frame_operators_col_align(self, float_frame):
+ frame2 = pd.DataFrame(float_frame, columns=["D", "C", "B", "A"])
+ added = frame2 + frame2
+ expected = frame2 * 2
+ tm.assert_frame_equal(added, expected)
+
+ def test_frame_operators_none_to_nan(self):
+ df = pd.DataFrame({"a": ["a", None, "b"]})
+ tm.assert_frame_equal(df + df, pd.DataFrame({"a": ["aa", np.nan, "bb"]}))
+
+ @pytest.mark.parametrize("dtype", ("float", "int64"))
+ def test_frame_operators_empty_like(self, dtype):
+ # Test for issue #10181
+ frames = [
+ pd.DataFrame(dtype=dtype),
+ pd.DataFrame(columns=["A"], dtype=dtype),
+ pd.DataFrame(index=[0], dtype=dtype),
+ ]
+ for df in frames:
+ assert (df + df).equals(df)
+ tm.assert_frame_equal(df + df, df)
+
+ @pytest.mark.parametrize(
+ "func",
+ [lambda x: x * 2, lambda x: x[::2], lambda x: 5],
+ ids=["multiply", "slice", "constant"],
+ )
+ def test_series_operators_arithmetic(self, all_arithmetic_functions, func):
+ op = all_arithmetic_functions
+ series = tm.makeTimeSeries().rename("ts")
+ other = func(series)
+ compare_op(series, other, op)
+
+ @pytest.mark.parametrize(
+ "func", [lambda x: x + 1, lambda x: 5], ids=["add", "constant"]
+ )
+ def test_series_operators_compare(self, comparison_op, func):
+ op = comparison_op
+ series = tm.makeTimeSeries().rename("ts")
+ other = func(series)
+ compare_op(series, other, op)
+
+ @pytest.mark.parametrize(
+ "func",
+ [lambda x: x * 2, lambda x: x[::2], lambda x: 5],
+ ids=["multiply", "slice", "constant"],
+ )
+ def test_divmod(self, func):
+ series = tm.makeTimeSeries().rename("ts")
+ other = func(series)
+ results = divmod(series, other)
+ if isinstance(other, abc.Iterable) and len(series) != len(other):
+ # if the lengths don't match, this is the test where we use
+ # `tser[::2]`. Pad every other value in `other_np` with nan.
+ other_np = []
+ for n in other:
+ other_np.append(n)
+ other_np.append(np.nan)
+ else:
+ other_np = other
+ other_np = np.asarray(other_np)
+ with np.errstate(all="ignore"):
+ expecteds = divmod(series.values, np.asarray(other_np))
+
+ for result, expected in zip(results, expecteds):
+ # check the values, name, and index separately
+ tm.assert_almost_equal(np.asarray(result), expected)
+
+ assert result.name == series.name
+ tm.assert_index_equal(result.index, series.index._with_freq(None))
+
+ def test_series_divmod_zero(self):
+ # Check that divmod uses pandas convention for division by zero,
+ # which does not match numpy.
+ # pandas convention has
+ # 1/0 == np.inf
+ # -1/0 == -np.inf
+ # 1/-0.0 == -np.inf
+ # -1/-0.0 == np.inf
+ tser = tm.makeTimeSeries().rename("ts")
+ other = tser * 0
+
+ result = divmod(tser, other)
+ exp1 = Series([np.inf] * len(tser), index=tser.index, name="ts")
+ exp2 = Series([np.nan] * len(tser), index=tser.index, name="ts")
+ tm.assert_series_equal(result[0], exp1)
+ tm.assert_series_equal(result[1], exp2)
+
+
+class TestUFuncCompat:
+ # TODO: add more dtypes
+ @pytest.mark.parametrize("holder", [Index, RangeIndex, Series])
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
+ def test_ufunc_compat(self, holder, dtype):
+ box = Series if holder is Series else Index
+
+ if holder is RangeIndex:
+ if dtype != np.int64:
+ pytest.skip(f"dtype {dtype} not relevant for RangeIndex")
+ idx = RangeIndex(0, 5, name="foo")
+ else:
+ idx = holder(np.arange(5, dtype=dtype), name="foo")
+ result = np.sin(idx)
+ expected = box(np.sin(np.arange(5, dtype=dtype)), name="foo")
+ tm.assert_equal(result, expected)
+
+ # TODO: add more dtypes
+ @pytest.mark.parametrize("holder", [Index, Series])
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
+ def test_ufunc_coercions(self, holder, dtype):
+ idx = holder([1, 2, 3, 4, 5], dtype=dtype, name="x")
+ box = Series if holder is Series else Index
+
+ result = np.sqrt(idx)
+ assert result.dtype == "f8" and isinstance(result, box)
+ exp = Index(np.sqrt(np.array([1, 2, 3, 4, 5], dtype=np.float64)), name="x")
+ exp = tm.box_expected(exp, box)
+ tm.assert_equal(result, exp)
+
+ result = np.divide(idx, 2.0)
+ assert result.dtype == "f8" and isinstance(result, box)
+ exp = Index([0.5, 1.0, 1.5, 2.0, 2.5], dtype=np.float64, name="x")
+ exp = tm.box_expected(exp, box)
+ tm.assert_equal(result, exp)
+
+ # _evaluate_numeric_binop
+ result = idx + 2.0
+ assert result.dtype == "f8" and isinstance(result, box)
+ exp = Index([3.0, 4.0, 5.0, 6.0, 7.0], dtype=np.float64, name="x")
+ exp = tm.box_expected(exp, box)
+ tm.assert_equal(result, exp)
+
+ result = idx - 2.0
+ assert result.dtype == "f8" and isinstance(result, box)
+ exp = Index([-1.0, 0.0, 1.0, 2.0, 3.0], dtype=np.float64, name="x")
+ exp = tm.box_expected(exp, box)
+ tm.assert_equal(result, exp)
+
+ result = idx * 1.0
+ assert result.dtype == "f8" and isinstance(result, box)
+ exp = Index([1.0, 2.0, 3.0, 4.0, 5.0], dtype=np.float64, name="x")
+ exp = tm.box_expected(exp, box)
+ tm.assert_equal(result, exp)
+
+ result = idx / 2.0
+ assert result.dtype == "f8" and isinstance(result, box)
+ exp = Index([0.5, 1.0, 1.5, 2.0, 2.5], dtype=np.float64, name="x")
+ exp = tm.box_expected(exp, box)
+ tm.assert_equal(result, exp)
+
+ # TODO: add more dtypes
+ @pytest.mark.parametrize("holder", [Index, Series])
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
+ def test_ufunc_multiple_return_values(self, holder, dtype):
+ obj = holder([1, 2, 3], dtype=dtype, name="x")
+ box = Series if holder is Series else Index
+
+ result = np.modf(obj)
+ assert isinstance(result, tuple)
+ exp1 = Index([0.0, 0.0, 0.0], dtype=np.float64, name="x")
+ exp2 = Index([1.0, 2.0, 3.0], dtype=np.float64, name="x")
+ tm.assert_equal(result[0], tm.box_expected(exp1, box))
+ tm.assert_equal(result[1], tm.box_expected(exp2, box))
+
+ def test_ufunc_at(self):
+ s = Series([0, 1, 2], index=[1, 2, 3], name="x")
+ np.add.at(s, [0, 2], 10)
+ expected = Series([10, 1, 12], index=[1, 2, 3], name="x")
+ tm.assert_series_equal(s, expected)
+
+
+class TestObjectDtypeEquivalence:
+ # Tests that arithmetic operations match operations executed elementwise
+
+ @pytest.mark.parametrize("dtype", [None, object])
+ def test_numarr_with_dtype_add_nan(self, dtype, box_with_array):
+ box = box_with_array
+ ser = Series([1, 2, 3], dtype=dtype)
+ expected = Series([np.nan, np.nan, np.nan], dtype=dtype)
+
+ ser = tm.box_expected(ser, box)
+ expected = tm.box_expected(expected, box)
+
+ result = np.nan + ser
+ tm.assert_equal(result, expected)
+
+ result = ser + np.nan
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", [None, object])
+ def test_numarr_with_dtype_add_int(self, dtype, box_with_array):
+ box = box_with_array
+ ser = Series([1, 2, 3], dtype=dtype)
+ expected = Series([2, 3, 4], dtype=dtype)
+
+ ser = tm.box_expected(ser, box)
+ expected = tm.box_expected(expected, box)
+
+ result = 1 + ser
+ tm.assert_equal(result, expected)
+
+ result = ser + 1
+ tm.assert_equal(result, expected)
+
+ # TODO: moved from tests.series.test_operators; needs cleanup
+ @pytest.mark.parametrize(
+ "op",
+ [operator.add, operator.sub, operator.mul, operator.truediv, operator.floordiv],
+ )
+ def test_operators_reverse_object(self, op):
+ # GH#56
+ arr = Series(
+ np.random.default_rng(2).standard_normal(10),
+ index=np.arange(10),
+ dtype=object,
+ )
+
+ result = op(1.0, arr)
+ expected = op(1.0, arr.astype(float))
+ tm.assert_series_equal(result.astype(float), expected)
+
+
+class TestNumericArithmeticUnsorted:
+ # Tests in this class have been moved from type-specific test modules
+ # but not yet sorted, parametrized, and de-duplicated
+ @pytest.mark.parametrize(
+ "op",
+ [
+ operator.add,
+ operator.sub,
+ operator.mul,
+ operator.floordiv,
+ operator.truediv,
+ ],
+ )
+ @pytest.mark.parametrize(
+ "idx1",
+ [
+ RangeIndex(0, 10, 1),
+ RangeIndex(0, 20, 2),
+ RangeIndex(-10, 10, 2),
+ RangeIndex(5, -5, -1),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "idx2",
+ [
+ RangeIndex(0, 10, 1),
+ RangeIndex(0, 20, 2),
+ RangeIndex(-10, 10, 2),
+ RangeIndex(5, -5, -1),
+ ],
+ )
+ def test_binops_index(self, op, idx1, idx2):
+ idx1 = idx1._rename("foo")
+ idx2 = idx2._rename("bar")
+ result = op(idx1, idx2)
+ expected = op(Index(idx1.to_numpy()), Index(idx2.to_numpy()))
+ tm.assert_index_equal(result, expected, exact="equiv")
+
+ @pytest.mark.parametrize(
+ "op",
+ [
+ operator.add,
+ operator.sub,
+ operator.mul,
+ operator.floordiv,
+ operator.truediv,
+ ],
+ )
+ @pytest.mark.parametrize(
+ "idx",
+ [
+ RangeIndex(0, 10, 1),
+ RangeIndex(0, 20, 2),
+ RangeIndex(-10, 10, 2),
+ RangeIndex(5, -5, -1),
+ ],
+ )
+ @pytest.mark.parametrize("scalar", [-1, 1, 2])
+ def test_binops_index_scalar(self, op, idx, scalar):
+ result = op(idx, scalar)
+ expected = op(Index(idx.to_numpy()), scalar)
+ tm.assert_index_equal(result, expected, exact="equiv")
+
+ @pytest.mark.parametrize("idx1", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)])
+ @pytest.mark.parametrize("idx2", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)])
+ def test_binops_index_pow(self, idx1, idx2):
+ # numpy does not allow powers of negative integers so test separately
+ # https://github.com/numpy/numpy/pull/8127
+ idx1 = idx1._rename("foo")
+ idx2 = idx2._rename("bar")
+ result = pow(idx1, idx2)
+ expected = pow(Index(idx1.to_numpy()), Index(idx2.to_numpy()))
+ tm.assert_index_equal(result, expected, exact="equiv")
+
+ @pytest.mark.parametrize("idx", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)])
+ @pytest.mark.parametrize("scalar", [1, 2])
+ def test_binops_index_scalar_pow(self, idx, scalar):
+ # numpy does not allow powers of negative integers so test separately
+ # https://github.com/numpy/numpy/pull/8127
+ result = pow(idx, scalar)
+ expected = pow(Index(idx.to_numpy()), scalar)
+ tm.assert_index_equal(result, expected, exact="equiv")
+
+ # TODO: divmod?
+ @pytest.mark.parametrize(
+ "op",
+ [
+ operator.add,
+ operator.sub,
+ operator.mul,
+ operator.floordiv,
+ operator.truediv,
+ operator.pow,
+ operator.mod,
+ ],
+ )
+ def test_arithmetic_with_frame_or_series(self, op):
+ # check that we return NotImplemented when operating with Series
+ # or DataFrame
+ index = RangeIndex(5)
+ other = Series(np.random.default_rng(2).standard_normal(5))
+
+ expected = op(Series(index), other)
+ result = op(index, other)
+ tm.assert_series_equal(result, expected)
+
+ other = pd.DataFrame(np.random.default_rng(2).standard_normal((2, 5)))
+ expected = op(pd.DataFrame([index, index]), other)
+ result = op(index, other)
+ tm.assert_frame_equal(result, expected)
+
+ def test_numeric_compat2(self):
+ # validate that we are handling the RangeIndex overrides to numeric ops
+ # and returning RangeIndex where possible
+
+ idx = RangeIndex(0, 10, 2)
+
+ result = idx * 2
+ expected = RangeIndex(0, 20, 4)
+ tm.assert_index_equal(result, expected, exact=True)
+
+ result = idx + 2
+ expected = RangeIndex(2, 12, 2)
+ tm.assert_index_equal(result, expected, exact=True)
+
+ result = idx - 2
+ expected = RangeIndex(-2, 8, 2)
+ tm.assert_index_equal(result, expected, exact=True)
+
+ result = idx / 2
+ expected = RangeIndex(0, 5, 1).astype("float64")
+ tm.assert_index_equal(result, expected, exact=True)
+
+ result = idx / 4
+ expected = RangeIndex(0, 10, 2) / 4
+ tm.assert_index_equal(result, expected, exact=True)
+
+ result = idx // 1
+ expected = idx
+ tm.assert_index_equal(result, expected, exact=True)
+
+ # __mul__
+ result = idx * idx
+ expected = Index(idx.values * idx.values)
+ tm.assert_index_equal(result, expected, exact=True)
+
+ # __pow__
+ idx = RangeIndex(0, 1000, 2)
+ result = idx**2
+ expected = Index(idx._values) ** 2
+ tm.assert_index_equal(Index(result.values), expected, exact=True)
+
+ @pytest.mark.parametrize(
+ "idx, div, expected",
+ [
+ # TODO: add more dtypes
+ (RangeIndex(0, 1000, 2), 2, RangeIndex(0, 500, 1)),
+ (RangeIndex(-99, -201, -3), -3, RangeIndex(33, 67, 1)),
+ (
+ RangeIndex(0, 1000, 1),
+ 2,
+ Index(RangeIndex(0, 1000, 1)._values) // 2,
+ ),
+ (
+ RangeIndex(0, 100, 1),
+ 2.0,
+ Index(RangeIndex(0, 100, 1)._values) // 2.0,
+ ),
+ (RangeIndex(0), 50, RangeIndex(0)),
+ (RangeIndex(2, 4, 2), 3, RangeIndex(0, 1, 1)),
+ (RangeIndex(-5, -10, -6), 4, RangeIndex(-2, -1, 1)),
+ (RangeIndex(-100, -200, 3), 2, RangeIndex(0)),
+ ],
+ )
+ def test_numeric_compat2_floordiv(self, idx, div, expected):
+ # __floordiv__
+ tm.assert_index_equal(idx // div, expected, exact=True)
+
+ @pytest.mark.parametrize("dtype", [np.int64, np.float64])
+ @pytest.mark.parametrize("delta", [1, 0, -1])
+ def test_addsub_arithmetic(self, dtype, delta):
+ # GH#8142
+ delta = dtype(delta)
+ index = Index([10, 11, 12], dtype=dtype)
+ result = index + delta
+ expected = Index(index.values + delta, dtype=dtype)
+ tm.assert_index_equal(result, expected)
+
+ # this subtraction used to fail
+ result = index - delta
+ expected = Index(index.values - delta, dtype=dtype)
+ tm.assert_index_equal(result, expected)
+
+ tm.assert_index_equal(index + index, 2 * index)
+ tm.assert_index_equal(index - index, 0 * index)
+ assert not (index - index).empty
+
+
+def test_fill_value_inf_masking():
+ # GH #27464 make sure we mask 0/1 with Inf and not NaN
+ df = pd.DataFrame({"A": [0, 1, 2], "B": [1.1, None, 1.1]})
+
+ other = pd.DataFrame({"A": [1.1, 1.2, 1.3]}, index=[0, 2, 3])
+
+ result = df.rfloordiv(other, fill_value=1)
+
+ expected = pd.DataFrame(
+ {"A": [np.inf, 1.0, 0.0, 1.0], "B": [0.0, np.nan, 0.0, np.nan]}
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_dataframe_div_silenced():
+ # GH#26793
+ pdf1 = pd.DataFrame(
+ {
+ "A": np.arange(10),
+ "B": [np.nan, 1, 2, 3, 4] * 2,
+ "C": [np.nan] * 10,
+ "D": np.arange(10),
+ },
+ index=list("abcdefghij"),
+ columns=list("ABCD"),
+ )
+ pdf2 = pd.DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)),
+ index=list("abcdefghjk"),
+ columns=list("ABCX"),
+ )
+ with tm.assert_produces_warning(None):
+ pdf1.div(pdf2, fill_value=0)
+
+
+@pytest.mark.parametrize(
+ "data, expected_data",
+ [([0, 1, 2], [0, 2, 4])],
+)
+def test_integer_array_add_list_like(
+ box_pandas_1d_array, box_1d_array, data, expected_data
+):
+ # GH22606 Verify operators with IntegerArray and list-likes
+ arr = array(data, dtype="Int64")
+ container = box_pandas_1d_array(arr)
+ left = container + box_1d_array(data)
+ right = box_1d_array(data) + container
+
+ if Series in [box_1d_array, box_pandas_1d_array]:
+ cls = Series
+ elif Index in [box_1d_array, box_pandas_1d_array]:
+ cls = Index
+ else:
+ cls = array
+
+ expected = cls(expected_data, dtype="Int64")
+
+ tm.assert_equal(left, expected)
+ tm.assert_equal(right, expected)
+
+
+def test_sub_multiindex_swapped_levels():
+ # GH 9952
+ df = pd.DataFrame(
+ {"a": np.random.default_rng(2).standard_normal(6)},
+ index=pd.MultiIndex.from_product(
+ [["a", "b"], [0, 1, 2]], names=["levA", "levB"]
+ ),
+ )
+ df2 = df.copy()
+ df2.index = df2.index.swaplevel(0, 1)
+ result = df - df2
+ expected = pd.DataFrame([0.0] * 6, columns=["a"], index=df.index)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("power", [1, 2, 5])
+@pytest.mark.parametrize("string_size", [0, 1, 2, 5])
+def test_empty_str_comparison(power, string_size):
+ # GH 37348
+ a = np.array(range(10**power))
+ right = pd.DataFrame(a, dtype=np.int64)
+ left = " " * string_size
+
+ result = right == left
+ expected = pd.DataFrame(np.zeros(right.shape, dtype=bool))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_series_add_sub_with_UInt64():
+ # GH 22023
+ series1 = Series([1, 2, 3])
+ series2 = Series([2, 1, 3], dtype="UInt64")
+
+ result = series1 + series2
+ expected = Series([3, 3, 6], dtype="Float64")
+ tm.assert_series_equal(result, expected)
+
+ result = series1 - series2
+ expected = Series([-1, 1, 0], dtype="Float64")
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_object.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_object.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ffbf1a38e8451928d1ac2b97328faf23103a08d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_object.py
@@ -0,0 +1,399 @@
+# Arithmetic tests for DataFrame/Series/Index/Array classes that should
+# behave identically.
+# Specifically for object dtype
+import datetime
+from decimal import Decimal
+import operator
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ Series,
+ Timestamp,
+)
+import pandas._testing as tm
+from pandas.core import ops
+
+# ------------------------------------------------------------------
+# Comparisons
+
+
+class TestObjectComparisons:
+ def test_comparison_object_numeric_nas(self, comparison_op):
+ ser = Series(np.random.default_rng(2).standard_normal(10), dtype=object)
+ shifted = ser.shift(2)
+
+ func = comparison_op
+
+ result = func(ser, shifted)
+ expected = func(ser.astype(float), shifted.astype(float))
+ tm.assert_series_equal(result, expected)
+
+ def test_object_comparisons(self):
+ ser = Series(["a", "b", np.nan, "c", "a"])
+
+ result = ser == "a"
+ expected = Series([True, False, False, False, True])
+ tm.assert_series_equal(result, expected)
+
+ result = ser < "a"
+ expected = Series([False, False, False, False, False])
+ tm.assert_series_equal(result, expected)
+
+ result = ser != "a"
+ expected = -(ser == "a")
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", [None, object])
+ def test_more_na_comparisons(self, dtype):
+ left = Series(["a", np.nan, "c"], dtype=dtype)
+ right = Series(["a", np.nan, "d"], dtype=dtype)
+
+ result = left == right
+ expected = Series([True, False, False])
+ tm.assert_series_equal(result, expected)
+
+ result = left != right
+ expected = Series([False, True, True])
+ tm.assert_series_equal(result, expected)
+
+ result = left == np.nan
+ expected = Series([False, False, False])
+ tm.assert_series_equal(result, expected)
+
+ result = left != np.nan
+ expected = Series([True, True, True])
+ tm.assert_series_equal(result, expected)
+
+
+# ------------------------------------------------------------------
+# Arithmetic
+
+
+class TestArithmetic:
+ def test_add_period_to_array_of_offset(self):
+ # GH#50162
+ per = pd.Period("2012-1-1", freq="D")
+ pi = pd.period_range("2012-1-1", periods=10, freq="D")
+ idx = per - pi
+
+ expected = pd.Index([x + per for x in idx], dtype=object)
+ result = idx + per
+ tm.assert_index_equal(result, expected)
+
+ result = per + idx
+ tm.assert_index_equal(result, expected)
+
+ # TODO: parametrize
+ def test_pow_ops_object(self):
+ # GH#22922
+ # pow is weird with masking & 1, so testing here
+ a = Series([1, np.nan, 1, np.nan], dtype=object)
+ b = Series([1, np.nan, np.nan, 1], dtype=object)
+ result = a**b
+ expected = Series(a.values**b.values, dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ result = b**a
+ expected = Series(b.values**a.values, dtype=object)
+
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("op", [operator.add, ops.radd])
+ @pytest.mark.parametrize("other", ["category", "Int64"])
+ def test_add_extension_scalar(self, other, box_with_array, op):
+ # GH#22378
+ # Check that scalars satisfying is_extension_array_dtype(obj)
+ # do not incorrectly try to dispatch to an ExtensionArray operation
+
+ arr = Series(["a", "b", "c"])
+ expected = Series([op(x, other) for x in arr])
+
+ arr = tm.box_expected(arr, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = op(arr, other)
+ tm.assert_equal(result, expected)
+
+ def test_objarr_add_str(self, box_with_array):
+ ser = Series(["x", np.nan, "x"])
+ expected = Series(["xa", np.nan, "xa"])
+
+ ser = tm.box_expected(ser, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = ser + "a"
+ tm.assert_equal(result, expected)
+
+ def test_objarr_radd_str(self, box_with_array):
+ ser = Series(["x", np.nan, "x"])
+ expected = Series(["ax", np.nan, "ax"])
+
+ ser = tm.box_expected(ser, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = "a" + ser
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "data",
+ [
+ [1, 2, 3],
+ [1.1, 2.2, 3.3],
+ [Timestamp("2011-01-01"), Timestamp("2011-01-02"), pd.NaT],
+ ["x", "y", 1],
+ ],
+ )
+ @pytest.mark.parametrize("dtype", [None, object])
+ def test_objarr_radd_str_invalid(self, dtype, data, box_with_array):
+ ser = Series(data, dtype=dtype)
+
+ ser = tm.box_expected(ser, box_with_array)
+ msg = "|".join(
+ [
+ "can only concatenate str",
+ "did not contain a loop with signature matching types",
+ "unsupported operand type",
+ "must be str",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ "foo_" + ser
+
+ @pytest.mark.parametrize("op", [operator.add, ops.radd, operator.sub, ops.rsub])
+ def test_objarr_add_invalid(self, op, box_with_array):
+ # invalid ops
+ box = box_with_array
+
+ obj_ser = tm.makeObjectSeries()
+ obj_ser.name = "objects"
+
+ obj_ser = tm.box_expected(obj_ser, box)
+ msg = "|".join(
+ ["can only concatenate str", "unsupported operand type", "must be str"]
+ )
+ with pytest.raises(Exception, match=msg):
+ op(obj_ser, 1)
+ with pytest.raises(Exception, match=msg):
+ op(obj_ser, np.array(1, dtype=np.int64))
+
+ # TODO: Moved from tests.series.test_operators; needs cleanup
+ def test_operators_na_handling(self):
+ ser = Series(["foo", "bar", "baz", np.nan])
+ result = "prefix_" + ser
+ expected = Series(["prefix_foo", "prefix_bar", "prefix_baz", np.nan])
+ tm.assert_series_equal(result, expected)
+
+ result = ser + "_suffix"
+ expected = Series(["foo_suffix", "bar_suffix", "baz_suffix", np.nan])
+ tm.assert_series_equal(result, expected)
+
+ # TODO: parametrize over box
+ @pytest.mark.parametrize("dtype", [None, object])
+ def test_series_with_dtype_radd_timedelta(self, dtype):
+ # note this test is _not_ aimed at timedelta64-dtyped Series
+ # as of 2.0 we retain object dtype when ser.dtype == object
+ ser = Series(
+ [pd.Timedelta("1 days"), pd.Timedelta("2 days"), pd.Timedelta("3 days")],
+ dtype=dtype,
+ )
+ expected = Series(
+ [pd.Timedelta("4 days"), pd.Timedelta("5 days"), pd.Timedelta("6 days")],
+ dtype=dtype,
+ )
+
+ result = pd.Timedelta("3 days") + ser
+ tm.assert_series_equal(result, expected)
+
+ result = ser + pd.Timedelta("3 days")
+ tm.assert_series_equal(result, expected)
+
+ # TODO: cleanup & parametrize over box
+ def test_mixed_timezone_series_ops_object(self):
+ # GH#13043
+ ser = Series(
+ [
+ Timestamp("2015-01-01", tz="US/Eastern"),
+ Timestamp("2015-01-01", tz="Asia/Tokyo"),
+ ],
+ name="xxx",
+ )
+ assert ser.dtype == object
+
+ exp = Series(
+ [
+ Timestamp("2015-01-02", tz="US/Eastern"),
+ Timestamp("2015-01-02", tz="Asia/Tokyo"),
+ ],
+ name="xxx",
+ )
+ tm.assert_series_equal(ser + pd.Timedelta("1 days"), exp)
+ tm.assert_series_equal(pd.Timedelta("1 days") + ser, exp)
+
+ # object series & object series
+ ser2 = Series(
+ [
+ Timestamp("2015-01-03", tz="US/Eastern"),
+ Timestamp("2015-01-05", tz="Asia/Tokyo"),
+ ],
+ name="xxx",
+ )
+ assert ser2.dtype == object
+ exp = Series(
+ [pd.Timedelta("2 days"), pd.Timedelta("4 days")], name="xxx", dtype=object
+ )
+ tm.assert_series_equal(ser2 - ser, exp)
+ tm.assert_series_equal(ser - ser2, -exp)
+
+ ser = Series(
+ [pd.Timedelta("01:00:00"), pd.Timedelta("02:00:00")],
+ name="xxx",
+ dtype=object,
+ )
+ assert ser.dtype == object
+
+ exp = Series(
+ [pd.Timedelta("01:30:00"), pd.Timedelta("02:30:00")],
+ name="xxx",
+ dtype=object,
+ )
+ tm.assert_series_equal(ser + pd.Timedelta("00:30:00"), exp)
+ tm.assert_series_equal(pd.Timedelta("00:30:00") + ser, exp)
+
+ # TODO: cleanup & parametrize over box
+ def test_iadd_preserves_name(self):
+ # GH#17067, GH#19723 __iadd__ and __isub__ should preserve index name
+ ser = Series([1, 2, 3])
+ ser.index.name = "foo"
+
+ ser.index += 1
+ assert ser.index.name == "foo"
+
+ ser.index -= 1
+ assert ser.index.name == "foo"
+
+ def test_add_string(self):
+ # from bug report
+ index = pd.Index(["a", "b", "c"])
+ index2 = index + "foo"
+
+ assert "a" not in index2
+ assert "afoo" in index2
+
+ def test_iadd_string(self):
+ index = pd.Index(["a", "b", "c"])
+ # doesn't fail test unless there is a check before `+=`
+ assert "a" in index
+
+ index += "_x"
+ assert "a_x" in index
+
+ def test_add(self):
+ index = tm.makeStringIndex(100)
+ expected = pd.Index(index.values * 2)
+ tm.assert_index_equal(index + index, expected)
+ tm.assert_index_equal(index + index.tolist(), expected)
+ tm.assert_index_equal(index.tolist() + index, expected)
+
+ # test add and radd
+ index = pd.Index(list("abc"))
+ expected = pd.Index(["a1", "b1", "c1"])
+ tm.assert_index_equal(index + "1", expected)
+ expected = pd.Index(["1a", "1b", "1c"])
+ tm.assert_index_equal("1" + index, expected)
+
+ def test_sub_fail(self):
+ index = tm.makeStringIndex(100)
+
+ msg = "unsupported operand type|Cannot broadcast"
+ with pytest.raises(TypeError, match=msg):
+ index - "a"
+ with pytest.raises(TypeError, match=msg):
+ index - index
+ with pytest.raises(TypeError, match=msg):
+ index - index.tolist()
+ with pytest.raises(TypeError, match=msg):
+ index.tolist() - index
+
+ def test_sub_object(self):
+ # GH#19369
+ index = pd.Index([Decimal(1), Decimal(2)])
+ expected = pd.Index([Decimal(0), Decimal(1)])
+
+ result = index - Decimal(1)
+ tm.assert_index_equal(result, expected)
+
+ result = index - pd.Index([Decimal(1), Decimal(1)])
+ tm.assert_index_equal(result, expected)
+
+ msg = "unsupported operand type"
+ with pytest.raises(TypeError, match=msg):
+ index - "foo"
+
+ with pytest.raises(TypeError, match=msg):
+ index - np.array([2, "foo"], dtype=object)
+
+ def test_rsub_object(self, fixed_now_ts):
+ # GH#19369
+ index = pd.Index([Decimal(1), Decimal(2)])
+ expected = pd.Index([Decimal(1), Decimal(0)])
+
+ result = Decimal(2) - index
+ tm.assert_index_equal(result, expected)
+
+ result = np.array([Decimal(2), Decimal(2)]) - index
+ tm.assert_index_equal(result, expected)
+
+ msg = "unsupported operand type"
+ with pytest.raises(TypeError, match=msg):
+ "foo" - index
+
+ with pytest.raises(TypeError, match=msg):
+ np.array([True, fixed_now_ts]) - index
+
+
+class MyIndex(pd.Index):
+ # Simple index subclass that tracks ops calls.
+
+ _calls: int
+
+ @classmethod
+ def _simple_new(cls, values, name=None, dtype=None):
+ result = object.__new__(cls)
+ result._data = values
+ result._name = name
+ result._calls = 0
+ result._reset_identity()
+
+ return result
+
+ def __add__(self, other):
+ self._calls += 1
+ return self._simple_new(self._data)
+
+ def __radd__(self, other):
+ return self.__add__(other)
+
+
+@pytest.mark.parametrize(
+ "other",
+ [
+ [datetime.timedelta(1), datetime.timedelta(2)],
+ [datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 2)],
+ [pd.Period("2000"), pd.Period("2001")],
+ ["a", "b"],
+ ],
+ ids=["timedelta", "datetime", "period", "object"],
+)
+def test_index_ops_defer_to_unknown_subclasses(other):
+ # https://github.com/pandas-dev/pandas/issues/31109
+ values = np.array(
+ [datetime.date(2000, 1, 1), datetime.date(2000, 1, 2)], dtype=object
+ )
+ a = MyIndex._simple_new(values)
+ other = pd.Index(other)
+ result = other + a
+ assert isinstance(result, MyIndex)
+ assert a._calls == 1
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_period.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_period.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a079ae7795e61d75ba9aee4cc99c0e9c40da8b0
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_period.py
@@ -0,0 +1,1600 @@
+# Arithmetic tests for DataFrame/Series/Index/Array classes that should
+# behave identically.
+# Specifically for Period dtype
+import operator
+
+import numpy as np
+import pytest
+
+from pandas._libs.tslibs import (
+ IncompatibleFrequency,
+ Period,
+ Timestamp,
+ to_offset,
+)
+from pandas.errors import PerformanceWarning
+
+import pandas as pd
+from pandas import (
+ PeriodIndex,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ period_range,
+)
+import pandas._testing as tm
+from pandas.core import ops
+from pandas.core.arrays import TimedeltaArray
+from pandas.tests.arithmetic.common import (
+ assert_invalid_addsub_type,
+ assert_invalid_comparison,
+ get_upcast_box,
+)
+
+# ------------------------------------------------------------------
+# Comparisons
+
+
+class TestPeriodArrayLikeComparisons:
+ # Comparison tests for PeriodDtype vectors fully parametrized over
+ # DataFrame/Series/PeriodIndex/PeriodArray. Ideally all comparison
+ # tests will eventually end up here.
+
+ @pytest.mark.parametrize("other", ["2017", Period("2017", freq="D")])
+ def test_eq_scalar(self, other, box_with_array):
+ idx = PeriodIndex(["2017", "2017", "2018"], freq="D")
+ idx = tm.box_expected(idx, box_with_array)
+ xbox = get_upcast_box(idx, other, True)
+
+ expected = np.array([True, True, False])
+ expected = tm.box_expected(expected, xbox)
+
+ result = idx == other
+
+ tm.assert_equal(result, expected)
+
+ def test_compare_zerodim(self, box_with_array):
+ # GH#26689 make sure we unbox zero-dimensional arrays
+
+ pi = period_range("2000", periods=4)
+ other = np.array(pi.to_numpy()[0])
+
+ pi = tm.box_expected(pi, box_with_array)
+ xbox = get_upcast_box(pi, other, True)
+
+ result = pi <= other
+ expected = np.array([True, False, False, False])
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "scalar",
+ [
+ "foo",
+ Timestamp("2021-01-01"),
+ Timedelta(days=4),
+ 9,
+ 9.5,
+ 2000, # specifically don't consider 2000 to match Period("2000", "D")
+ False,
+ None,
+ ],
+ )
+ def test_compare_invalid_scalar(self, box_with_array, scalar):
+ # GH#28980
+ # comparison with scalar that cannot be interpreted as a Period
+ pi = period_range("2000", periods=4)
+ parr = tm.box_expected(pi, box_with_array)
+ assert_invalid_comparison(parr, scalar, box_with_array)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ pd.date_range("2000", periods=4).array,
+ pd.timedelta_range("1D", periods=4).array,
+ np.arange(4),
+ np.arange(4).astype(np.float64),
+ list(range(4)),
+ # match Period semantics by not treating integers as Periods
+ [2000, 2001, 2002, 2003],
+ np.arange(2000, 2004),
+ np.arange(2000, 2004).astype(object),
+ pd.Index([2000, 2001, 2002, 2003]),
+ ],
+ )
+ def test_compare_invalid_listlike(self, box_with_array, other):
+ pi = period_range("2000", periods=4)
+ parr = tm.box_expected(pi, box_with_array)
+ assert_invalid_comparison(parr, other, box_with_array)
+
+ @pytest.mark.parametrize("other_box", [list, np.array, lambda x: x.astype(object)])
+ def test_compare_object_dtype(self, box_with_array, other_box):
+ pi = period_range("2000", periods=5)
+ parr = tm.box_expected(pi, box_with_array)
+
+ other = other_box(pi)
+ xbox = get_upcast_box(parr, other, True)
+
+ expected = np.array([True, True, True, True, True])
+ expected = tm.box_expected(expected, xbox)
+
+ result = parr == other
+ tm.assert_equal(result, expected)
+ result = parr <= other
+ tm.assert_equal(result, expected)
+ result = parr >= other
+ tm.assert_equal(result, expected)
+
+ result = parr != other
+ tm.assert_equal(result, ~expected)
+ result = parr < other
+ tm.assert_equal(result, ~expected)
+ result = parr > other
+ tm.assert_equal(result, ~expected)
+
+ other = other_box(pi[::-1])
+
+ expected = np.array([False, False, True, False, False])
+ expected = tm.box_expected(expected, xbox)
+ result = parr == other
+ tm.assert_equal(result, expected)
+
+ expected = np.array([True, True, True, False, False])
+ expected = tm.box_expected(expected, xbox)
+ result = parr <= other
+ tm.assert_equal(result, expected)
+
+ expected = np.array([False, False, True, True, True])
+ expected = tm.box_expected(expected, xbox)
+ result = parr >= other
+ tm.assert_equal(result, expected)
+
+ expected = np.array([True, True, False, True, True])
+ expected = tm.box_expected(expected, xbox)
+ result = parr != other
+ tm.assert_equal(result, expected)
+
+ expected = np.array([True, True, False, False, False])
+ expected = tm.box_expected(expected, xbox)
+ result = parr < other
+ tm.assert_equal(result, expected)
+
+ expected = np.array([False, False, False, True, True])
+ expected = tm.box_expected(expected, xbox)
+ result = parr > other
+ tm.assert_equal(result, expected)
+
+
+class TestPeriodIndexComparisons:
+ # TODO: parameterize over boxes
+
+ def test_pi_cmp_period(self):
+ idx = period_range("2007-01", periods=20, freq="M")
+ per = idx[10]
+
+ result = idx < per
+ exp = idx.values < idx.values[10]
+ tm.assert_numpy_array_equal(result, exp)
+
+ # Tests Period.__richcmp__ against ndarray[object, ndim=2]
+ result = idx.values.reshape(10, 2) < per
+ tm.assert_numpy_array_equal(result, exp.reshape(10, 2))
+
+ # Tests Period.__richcmp__ against ndarray[object, ndim=0]
+ result = idx < np.array(per)
+ tm.assert_numpy_array_equal(result, exp)
+
+ # TODO: moved from test_datetime64; de-duplicate with version below
+ def test_parr_cmp_period_scalar2(self, box_with_array):
+ pi = period_range("2000-01-01", periods=10, freq="D")
+
+ val = pi[3]
+ expected = [x > val for x in pi]
+
+ ser = tm.box_expected(pi, box_with_array)
+ xbox = get_upcast_box(ser, val, True)
+
+ expected = tm.box_expected(expected, xbox)
+ result = ser > val
+ tm.assert_equal(result, expected)
+
+ val = pi[5]
+ result = ser > val
+ expected = [x > val for x in pi]
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
+ def test_parr_cmp_period_scalar(self, freq, box_with_array):
+ # GH#13200
+ base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq)
+ base = tm.box_expected(base, box_with_array)
+ per = Period("2011-02", freq=freq)
+ xbox = get_upcast_box(base, per, True)
+
+ exp = np.array([False, True, False, False])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base == per, exp)
+ tm.assert_equal(per == base, exp)
+
+ exp = np.array([True, False, True, True])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base != per, exp)
+ tm.assert_equal(per != base, exp)
+
+ exp = np.array([False, False, True, True])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base > per, exp)
+ tm.assert_equal(per < base, exp)
+
+ exp = np.array([True, False, False, False])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base < per, exp)
+ tm.assert_equal(per > base, exp)
+
+ exp = np.array([False, True, True, True])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base >= per, exp)
+ tm.assert_equal(per <= base, exp)
+
+ exp = np.array([True, True, False, False])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base <= per, exp)
+ tm.assert_equal(per >= base, exp)
+
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
+ def test_parr_cmp_pi(self, freq, box_with_array):
+ # GH#13200
+ base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq)
+ base = tm.box_expected(base, box_with_array)
+
+ # TODO: could also box idx?
+ idx = PeriodIndex(["2011-02", "2011-01", "2011-03", "2011-05"], freq=freq)
+
+ xbox = get_upcast_box(base, idx, True)
+
+ exp = np.array([False, False, True, False])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base == idx, exp)
+
+ exp = np.array([True, True, False, True])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base != idx, exp)
+
+ exp = np.array([False, True, False, False])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base > idx, exp)
+
+ exp = np.array([True, False, False, True])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base < idx, exp)
+
+ exp = np.array([False, True, True, False])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base >= idx, exp)
+
+ exp = np.array([True, False, True, True])
+ exp = tm.box_expected(exp, xbox)
+ tm.assert_equal(base <= idx, exp)
+
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
+ def test_parr_cmp_pi_mismatched_freq(self, freq, box_with_array):
+ # GH#13200
+ # different base freq
+ base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq)
+ base = tm.box_expected(base, box_with_array)
+
+ msg = rf"Invalid comparison between dtype=period\[{freq}\] and Period"
+ with pytest.raises(TypeError, match=msg):
+ base <= Period("2011", freq="A")
+
+ with pytest.raises(TypeError, match=msg):
+ Period("2011", freq="A") >= base
+
+ # TODO: Could parametrize over boxes for idx?
+ idx = PeriodIndex(["2011", "2012", "2013", "2014"], freq="A")
+ rev_msg = r"Invalid comparison between dtype=period\[A-DEC\] and PeriodArray"
+ idx_msg = rev_msg if box_with_array in [tm.to_array, pd.array] else msg
+ with pytest.raises(TypeError, match=idx_msg):
+ base <= idx
+
+ # Different frequency
+ msg = rf"Invalid comparison between dtype=period\[{freq}\] and Period"
+ with pytest.raises(TypeError, match=msg):
+ base <= Period("2011", freq="4M")
+
+ with pytest.raises(TypeError, match=msg):
+ Period("2011", freq="4M") >= base
+
+ idx = PeriodIndex(["2011", "2012", "2013", "2014"], freq="4M")
+ rev_msg = r"Invalid comparison between dtype=period\[4M\] and PeriodArray"
+ idx_msg = rev_msg if box_with_array in [tm.to_array, pd.array] else msg
+ with pytest.raises(TypeError, match=idx_msg):
+ base <= idx
+
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
+ def test_pi_cmp_nat(self, freq):
+ idx1 = PeriodIndex(["2011-01", "2011-02", "NaT", "2011-05"], freq=freq)
+ per = idx1[1]
+
+ result = idx1 > per
+ exp = np.array([False, False, False, True])
+ tm.assert_numpy_array_equal(result, exp)
+ result = per < idx1
+ tm.assert_numpy_array_equal(result, exp)
+
+ result = idx1 == pd.NaT
+ exp = np.array([False, False, False, False])
+ tm.assert_numpy_array_equal(result, exp)
+ result = pd.NaT == idx1
+ tm.assert_numpy_array_equal(result, exp)
+
+ result = idx1 != pd.NaT
+ exp = np.array([True, True, True, True])
+ tm.assert_numpy_array_equal(result, exp)
+ result = pd.NaT != idx1
+ tm.assert_numpy_array_equal(result, exp)
+
+ idx2 = PeriodIndex(["2011-02", "2011-01", "2011-04", "NaT"], freq=freq)
+ result = idx1 < idx2
+ exp = np.array([True, False, False, False])
+ tm.assert_numpy_array_equal(result, exp)
+
+ result = idx1 == idx2
+ exp = np.array([False, False, False, False])
+ tm.assert_numpy_array_equal(result, exp)
+
+ result = idx1 != idx2
+ exp = np.array([True, True, True, True])
+ tm.assert_numpy_array_equal(result, exp)
+
+ result = idx1 == idx1
+ exp = np.array([True, True, False, True])
+ tm.assert_numpy_array_equal(result, exp)
+
+ result = idx1 != idx1
+ exp = np.array([False, False, True, False])
+ tm.assert_numpy_array_equal(result, exp)
+
+ @pytest.mark.parametrize("freq", ["M", "2M", "3M"])
+ def test_pi_cmp_nat_mismatched_freq_raises(self, freq):
+ idx1 = PeriodIndex(["2011-01", "2011-02", "NaT", "2011-05"], freq=freq)
+
+ diff = PeriodIndex(["2011-02", "2011-01", "2011-04", "NaT"], freq="4M")
+ msg = rf"Invalid comparison between dtype=period\[{freq}\] and PeriodArray"
+ with pytest.raises(TypeError, match=msg):
+ idx1 > diff
+
+ result = idx1 == diff
+ expected = np.array([False, False, False, False], dtype=bool)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # TODO: De-duplicate with test_pi_cmp_nat
+ @pytest.mark.parametrize("dtype", [object, None])
+ def test_comp_nat(self, dtype):
+ left = PeriodIndex([Period("2011-01-01"), pd.NaT, Period("2011-01-03")])
+ right = PeriodIndex([pd.NaT, pd.NaT, Period("2011-01-03")])
+
+ if dtype is not None:
+ left = left.astype(dtype)
+ right = right.astype(dtype)
+
+ result = left == right
+ expected = np.array([False, False, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = left != right
+ expected = np.array([True, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ expected = np.array([False, False, False])
+ tm.assert_numpy_array_equal(left == pd.NaT, expected)
+ tm.assert_numpy_array_equal(pd.NaT == right, expected)
+
+ expected = np.array([True, True, True])
+ tm.assert_numpy_array_equal(left != pd.NaT, expected)
+ tm.assert_numpy_array_equal(pd.NaT != left, expected)
+
+ expected = np.array([False, False, False])
+ tm.assert_numpy_array_equal(left < pd.NaT, expected)
+ tm.assert_numpy_array_equal(pd.NaT > left, expected)
+
+
+class TestPeriodSeriesComparisons:
+ def test_cmp_series_period_series_mixed_freq(self):
+ # GH#13200
+ base = Series(
+ [
+ Period("2011", freq="A"),
+ Period("2011-02", freq="M"),
+ Period("2013", freq="A"),
+ Period("2011-04", freq="M"),
+ ]
+ )
+
+ ser = Series(
+ [
+ Period("2012", freq="A"),
+ Period("2011-01", freq="M"),
+ Period("2013", freq="A"),
+ Period("2011-05", freq="M"),
+ ]
+ )
+
+ exp = Series([False, False, True, False])
+ tm.assert_series_equal(base == ser, exp)
+
+ exp = Series([True, True, False, True])
+ tm.assert_series_equal(base != ser, exp)
+
+ exp = Series([False, True, False, False])
+ tm.assert_series_equal(base > ser, exp)
+
+ exp = Series([True, False, False, True])
+ tm.assert_series_equal(base < ser, exp)
+
+ exp = Series([False, True, True, False])
+ tm.assert_series_equal(base >= ser, exp)
+
+ exp = Series([True, False, True, True])
+ tm.assert_series_equal(base <= ser, exp)
+
+
+class TestPeriodIndexSeriesComparisonConsistency:
+ """Test PeriodIndex and Period Series Ops consistency"""
+
+ # TODO: needs parametrization+de-duplication
+
+ def _check(self, values, func, expected):
+ # Test PeriodIndex and Period Series Ops consistency
+
+ idx = PeriodIndex(values)
+ result = func(idx)
+
+ # check that we don't pass an unwanted type to tm.assert_equal
+ assert isinstance(expected, (pd.Index, np.ndarray))
+ tm.assert_equal(result, expected)
+
+ s = Series(values)
+ result = func(s)
+
+ exp = Series(expected, name=values.name)
+ tm.assert_series_equal(result, exp)
+
+ def test_pi_comp_period(self):
+ idx = PeriodIndex(
+ ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
+ )
+ per = idx[2]
+
+ f = lambda x: x == per
+ exp = np.array([False, False, True, False], dtype=np.bool_)
+ self._check(idx, f, exp)
+ f = lambda x: per == x
+ self._check(idx, f, exp)
+
+ f = lambda x: x != per
+ exp = np.array([True, True, False, True], dtype=np.bool_)
+ self._check(idx, f, exp)
+ f = lambda x: per != x
+ self._check(idx, f, exp)
+
+ f = lambda x: per >= x
+ exp = np.array([True, True, True, False], dtype=np.bool_)
+ self._check(idx, f, exp)
+
+ f = lambda x: x > per
+ exp = np.array([False, False, False, True], dtype=np.bool_)
+ self._check(idx, f, exp)
+
+ f = lambda x: per >= x
+ exp = np.array([True, True, True, False], dtype=np.bool_)
+ self._check(idx, f, exp)
+
+ def test_pi_comp_period_nat(self):
+ idx = PeriodIndex(
+ ["2011-01", "NaT", "2011-03", "2011-04"], freq="M", name="idx"
+ )
+ per = idx[2]
+
+ f = lambda x: x == per
+ exp = np.array([False, False, True, False], dtype=np.bool_)
+ self._check(idx, f, exp)
+ f = lambda x: per == x
+ self._check(idx, f, exp)
+
+ f = lambda x: x == pd.NaT
+ exp = np.array([False, False, False, False], dtype=np.bool_)
+ self._check(idx, f, exp)
+ f = lambda x: pd.NaT == x
+ self._check(idx, f, exp)
+
+ f = lambda x: x != per
+ exp = np.array([True, True, False, True], dtype=np.bool_)
+ self._check(idx, f, exp)
+ f = lambda x: per != x
+ self._check(idx, f, exp)
+
+ f = lambda x: x != pd.NaT
+ exp = np.array([True, True, True, True], dtype=np.bool_)
+ self._check(idx, f, exp)
+ f = lambda x: pd.NaT != x
+ self._check(idx, f, exp)
+
+ f = lambda x: per >= x
+ exp = np.array([True, False, True, False], dtype=np.bool_)
+ self._check(idx, f, exp)
+
+ f = lambda x: x < per
+ exp = np.array([True, False, False, False], dtype=np.bool_)
+ self._check(idx, f, exp)
+
+ f = lambda x: x > pd.NaT
+ exp = np.array([False, False, False, False], dtype=np.bool_)
+ self._check(idx, f, exp)
+
+ f = lambda x: pd.NaT >= x
+ exp = np.array([False, False, False, False], dtype=np.bool_)
+ self._check(idx, f, exp)
+
+
+# ------------------------------------------------------------------
+# Arithmetic
+
+
+class TestPeriodFrameArithmetic:
+ def test_ops_frame_period(self):
+ # GH#13043
+ df = pd.DataFrame(
+ {
+ "A": [Period("2015-01", freq="M"), Period("2015-02", freq="M")],
+ "B": [Period("2014-01", freq="M"), Period("2014-02", freq="M")],
+ }
+ )
+ assert df["A"].dtype == "Period[M]"
+ assert df["B"].dtype == "Period[M]"
+
+ p = Period("2015-03", freq="M")
+ off = p.freq
+ # dtype will be object because of original dtype
+ exp = pd.DataFrame(
+ {
+ "A": np.array([2 * off, 1 * off], dtype=object),
+ "B": np.array([14 * off, 13 * off], dtype=object),
+ }
+ )
+ tm.assert_frame_equal(p - df, exp)
+ tm.assert_frame_equal(df - p, -1 * exp)
+
+ df2 = pd.DataFrame(
+ {
+ "A": [Period("2015-05", freq="M"), Period("2015-06", freq="M")],
+ "B": [Period("2015-05", freq="M"), Period("2015-06", freq="M")],
+ }
+ )
+ assert df2["A"].dtype == "Period[M]"
+ assert df2["B"].dtype == "Period[M]"
+
+ exp = pd.DataFrame(
+ {
+ "A": np.array([4 * off, 4 * off], dtype=object),
+ "B": np.array([16 * off, 16 * off], dtype=object),
+ }
+ )
+ tm.assert_frame_equal(df2 - df, exp)
+ tm.assert_frame_equal(df - df2, -1 * exp)
+
+
+class TestPeriodIndexArithmetic:
+ # ---------------------------------------------------------------
+ # __add__/__sub__ with PeriodIndex
+ # PeriodIndex + other is defined for integers and timedelta-like others
+ # PeriodIndex - other is defined for integers, timedelta-like others,
+ # and PeriodIndex (with matching freq)
+
+ def test_parr_add_iadd_parr_raises(self, box_with_array):
+ rng = period_range("1/1/2000", freq="D", periods=5)
+ other = period_range("1/6/2000", freq="D", periods=5)
+ # TODO: parametrize over boxes for other?
+
+ rng = tm.box_expected(rng, box_with_array)
+ # An earlier implementation of PeriodIndex addition performed
+ # a set operation (union). This has since been changed to
+ # raise a TypeError. See GH#14164 and GH#13077 for historical
+ # reference.
+ msg = r"unsupported operand type\(s\) for \+: .* and .*"
+ with pytest.raises(TypeError, match=msg):
+ rng + other
+
+ with pytest.raises(TypeError, match=msg):
+ rng += other
+
+ def test_pi_sub_isub_pi(self):
+ # GH#20049
+ # For historical reference see GH#14164, GH#13077.
+ # PeriodIndex subtraction originally performed set difference,
+ # then changed to raise TypeError before being implemented in GH#20049
+ rng = period_range("1/1/2000", freq="D", periods=5)
+ other = period_range("1/6/2000", freq="D", periods=5)
+
+ off = rng.freq
+ expected = pd.Index([-5 * off] * 5)
+ result = rng - other
+ tm.assert_index_equal(result, expected)
+
+ rng -= other
+ tm.assert_index_equal(rng, expected)
+
+ def test_pi_sub_pi_with_nat(self):
+ rng = period_range("1/1/2000", freq="D", periods=5)
+ other = rng[1:].insert(0, pd.NaT)
+ assert other[1:].equals(rng[1:])
+
+ result = rng - other
+ off = rng.freq
+ expected = pd.Index([pd.NaT, 0 * off, 0 * off, 0 * off, 0 * off])
+ tm.assert_index_equal(result, expected)
+
+ def test_parr_sub_pi_mismatched_freq(self, box_with_array, box_with_array2):
+ rng = period_range("1/1/2000", freq="D", periods=5)
+ other = period_range("1/6/2000", freq="H", periods=5)
+
+ rng = tm.box_expected(rng, box_with_array)
+ other = tm.box_expected(other, box_with_array2)
+ msg = r"Input has different freq=[HD] from PeriodArray\(freq=[DH]\)"
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng - other
+
+ @pytest.mark.parametrize("n", [1, 2, 3, 4])
+ def test_sub_n_gt_1_ticks(self, tick_classes, n):
+ # GH 23878
+ p1_d = "19910905"
+ p2_d = "19920406"
+ p1 = PeriodIndex([p1_d], freq=tick_classes(n))
+ p2 = PeriodIndex([p2_d], freq=tick_classes(n))
+
+ expected = PeriodIndex([p2_d], freq=p2.freq.base) - PeriodIndex(
+ [p1_d], freq=p1.freq.base
+ )
+
+ tm.assert_index_equal((p2 - p1), expected)
+
+ @pytest.mark.parametrize("n", [1, 2, 3, 4])
+ @pytest.mark.parametrize(
+ "offset, kwd_name",
+ [
+ (pd.offsets.YearEnd, "month"),
+ (pd.offsets.QuarterEnd, "startingMonth"),
+ (pd.offsets.MonthEnd, None),
+ (pd.offsets.Week, "weekday"),
+ ],
+ )
+ def test_sub_n_gt_1_offsets(self, offset, kwd_name, n):
+ # GH 23878
+ kwds = {kwd_name: 3} if kwd_name is not None else {}
+ p1_d = "19910905"
+ p2_d = "19920406"
+ freq = offset(n, normalize=False, **kwds)
+ p1 = PeriodIndex([p1_d], freq=freq)
+ p2 = PeriodIndex([p2_d], freq=freq)
+
+ result = p2 - p1
+ expected = PeriodIndex([p2_d], freq=freq.base) - PeriodIndex(
+ [p1_d], freq=freq.base
+ )
+
+ tm.assert_index_equal(result, expected)
+
+ # -------------------------------------------------------------
+ # Invalid Operations
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ # datetime scalars
+ Timestamp("2016-01-01"),
+ Timestamp("2016-01-01").to_pydatetime(),
+ Timestamp("2016-01-01").to_datetime64(),
+ # datetime-like arrays
+ pd.date_range("2016-01-01", periods=3, freq="H"),
+ pd.date_range("2016-01-01", periods=3, tz="Europe/Brussels"),
+ pd.date_range("2016-01-01", periods=3, freq="S")._data,
+ pd.date_range("2016-01-01", periods=3, tz="Asia/Tokyo")._data,
+ # Miscellaneous invalid types
+ 3.14,
+ np.array([2.0, 3.0, 4.0]),
+ ],
+ )
+ def test_parr_add_sub_invalid(self, other, box_with_array):
+ # GH#23215
+ rng = period_range("1/1/2000", freq="D", periods=3)
+ rng = tm.box_expected(rng, box_with_array)
+
+ msg = "|".join(
+ [
+ r"(:?cannot add PeriodArray and .*)",
+ r"(:?cannot subtract .* from (:?a\s)?.*)",
+ r"(:?unsupported operand type\(s\) for \+: .* and .*)",
+ r"unsupported operand type\(s\) for [+-]: .* and .*",
+ ]
+ )
+ assert_invalid_addsub_type(rng, other, msg)
+ with pytest.raises(TypeError, match=msg):
+ rng + other
+ with pytest.raises(TypeError, match=msg):
+ other + rng
+ with pytest.raises(TypeError, match=msg):
+ rng - other
+ with pytest.raises(TypeError, match=msg):
+ other - rng
+
+ # -----------------------------------------------------------------
+ # __add__/__sub__ with ndarray[datetime64] and ndarray[timedelta64]
+
+ def test_pi_add_sub_td64_array_non_tick_raises(self):
+ rng = period_range("1/1/2000", freq="Q", periods=3)
+ tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"])
+ tdarr = tdi.values
+
+ msg = r"Cannot add or subtract timedelta64\[ns\] dtype from period\[Q-DEC\]"
+ with pytest.raises(TypeError, match=msg):
+ rng + tdarr
+ with pytest.raises(TypeError, match=msg):
+ tdarr + rng
+
+ with pytest.raises(TypeError, match=msg):
+ rng - tdarr
+ msg = r"cannot subtract PeriodArray from TimedeltaArray"
+ with pytest.raises(TypeError, match=msg):
+ tdarr - rng
+
+ def test_pi_add_sub_td64_array_tick(self):
+ # PeriodIndex + Timedelta-like is allowed only with
+ # tick-like frequencies
+ rng = period_range("1/1/2000", freq="90D", periods=3)
+ tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"])
+ tdarr = tdi.values
+
+ expected = period_range("12/31/1999", freq="90D", periods=3)
+ result = rng + tdi
+ tm.assert_index_equal(result, expected)
+ result = rng + tdarr
+ tm.assert_index_equal(result, expected)
+ result = tdi + rng
+ tm.assert_index_equal(result, expected)
+ result = tdarr + rng
+ tm.assert_index_equal(result, expected)
+
+ expected = period_range("1/2/2000", freq="90D", periods=3)
+
+ result = rng - tdi
+ tm.assert_index_equal(result, expected)
+ result = rng - tdarr
+ tm.assert_index_equal(result, expected)
+
+ msg = r"cannot subtract .* from .*"
+ with pytest.raises(TypeError, match=msg):
+ tdarr - rng
+
+ with pytest.raises(TypeError, match=msg):
+ tdi - rng
+
+ @pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "H"])
+ @pytest.mark.parametrize("tdi_freq", [None, "H"])
+ def test_parr_sub_td64array(self, box_with_array, tdi_freq, pi_freq):
+ box = box_with_array
+ xbox = box if box not in [pd.array, tm.to_array] else pd.Index
+
+ tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq)
+ dti = Timestamp("2018-03-07 17:16:40") + tdi
+ pi = dti.to_period(pi_freq)
+
+ # TODO: parametrize over box for pi?
+ td64obj = tm.box_expected(tdi, box)
+
+ if pi_freq == "H":
+ result = pi - td64obj
+ expected = (pi.to_timestamp("S") - tdi).to_period(pi_freq)
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(result, expected)
+
+ # Subtract from scalar
+ result = pi[0] - td64obj
+ expected = (pi[0].to_timestamp("S") - tdi).to_period(pi_freq)
+ expected = tm.box_expected(expected, box)
+ tm.assert_equal(result, expected)
+
+ elif pi_freq == "D":
+ # Tick, but non-compatible
+ msg = (
+ "Cannot add/subtract timedelta-like from PeriodArray that is "
+ "not an integer multiple of the PeriodArray's freq."
+ )
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ pi - td64obj
+
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ pi[0] - td64obj
+
+ else:
+ # With non-Tick freq, we could not add timedelta64 array regardless
+ # of what its resolution is
+ msg = "Cannot add or subtract timedelta64"
+ with pytest.raises(TypeError, match=msg):
+ pi - td64obj
+ with pytest.raises(TypeError, match=msg):
+ pi[0] - td64obj
+
+ # -----------------------------------------------------------------
+ # operations with array/Index of DateOffset objects
+
+ @pytest.mark.parametrize("box", [np.array, pd.Index])
+ def test_pi_add_offset_array(self, box):
+ # GH#18849
+ pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")])
+ offs = box(
+ [
+ pd.offsets.QuarterEnd(n=1, startingMonth=12),
+ pd.offsets.QuarterEnd(n=-2, startingMonth=12),
+ ]
+ )
+ expected = PeriodIndex([Period("2015Q2"), Period("2015Q4")]).astype(object)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res = pi + offs
+ tm.assert_index_equal(res, expected)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res2 = offs + pi
+ tm.assert_index_equal(res2, expected)
+
+ unanchored = np.array([pd.offsets.Hour(n=1), pd.offsets.Minute(n=-2)])
+ # addition/subtraction ops with incompatible offsets should issue
+ # a PerformanceWarning and _then_ raise a TypeError.
+ msg = r"Input cannot be converted to Period\(freq=Q-DEC\)"
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ with tm.assert_produces_warning(PerformanceWarning):
+ pi + unanchored
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ with tm.assert_produces_warning(PerformanceWarning):
+ unanchored + pi
+
+ @pytest.mark.parametrize("box", [np.array, pd.Index])
+ def test_pi_sub_offset_array(self, box):
+ # GH#18824
+ pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")])
+ other = box(
+ [
+ pd.offsets.QuarterEnd(n=1, startingMonth=12),
+ pd.offsets.QuarterEnd(n=-2, startingMonth=12),
+ ]
+ )
+
+ expected = PeriodIndex([pi[n] - other[n] for n in range(len(pi))])
+ expected = expected.astype(object)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res = pi - other
+ tm.assert_index_equal(res, expected)
+
+ anchored = box([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])
+
+ # addition/subtraction ops with anchored offsets should issue
+ # a PerformanceWarning and _then_ raise a TypeError.
+ msg = r"Input has different freq=-1M from Period\(freq=Q-DEC\)"
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ with tm.assert_produces_warning(PerformanceWarning):
+ pi - anchored
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ with tm.assert_produces_warning(PerformanceWarning):
+ anchored - pi
+
+ def test_pi_add_iadd_int(self, one):
+ # Variants of `one` for #19012
+ rng = period_range("2000-01-01 09:00", freq="H", periods=10)
+ result = rng + one
+ expected = period_range("2000-01-01 10:00", freq="H", periods=10)
+ tm.assert_index_equal(result, expected)
+ rng += one
+ tm.assert_index_equal(rng, expected)
+
+ def test_pi_sub_isub_int(self, one):
+ """
+ PeriodIndex.__sub__ and __isub__ with several representations of
+ the integer 1, e.g. int, np.int64, np.uint8, ...
+ """
+ rng = period_range("2000-01-01 09:00", freq="H", periods=10)
+ result = rng - one
+ expected = period_range("2000-01-01 08:00", freq="H", periods=10)
+ tm.assert_index_equal(result, expected)
+ rng -= one
+ tm.assert_index_equal(rng, expected)
+
+ @pytest.mark.parametrize("five", [5, np.array(5, dtype=np.int64)])
+ def test_pi_sub_intlike(self, five):
+ rng = period_range("2007-01", periods=50)
+
+ result = rng - five
+ exp = rng + (-five)
+ tm.assert_index_equal(result, exp)
+
+ def test_pi_add_sub_int_array_freqn_gt1(self):
+ # GH#47209 test adding array of ints when freq.n > 1 matches
+ # scalar behavior
+ pi = period_range("2016-01-01", periods=10, freq="2D")
+ arr = np.arange(10)
+ result = pi + arr
+ expected = pd.Index([x + y for x, y in zip(pi, arr)])
+ tm.assert_index_equal(result, expected)
+
+ result = pi - arr
+ expected = pd.Index([x - y for x, y in zip(pi, arr)])
+ tm.assert_index_equal(result, expected)
+
+ def test_pi_sub_isub_offset(self):
+ # offset
+ # DateOffset
+ rng = period_range("2014", "2024", freq="A")
+ result = rng - pd.offsets.YearEnd(5)
+ expected = period_range("2009", "2019", freq="A")
+ tm.assert_index_equal(result, expected)
+ rng -= pd.offsets.YearEnd(5)
+ tm.assert_index_equal(rng, expected)
+
+ rng = period_range("2014-01", "2016-12", freq="M")
+ result = rng - pd.offsets.MonthEnd(5)
+ expected = period_range("2013-08", "2016-07", freq="M")
+ tm.assert_index_equal(result, expected)
+
+ rng -= pd.offsets.MonthEnd(5)
+ tm.assert_index_equal(rng, expected)
+
+ @pytest.mark.parametrize("transpose", [True, False])
+ def test_pi_add_offset_n_gt1(self, box_with_array, transpose):
+ # GH#23215
+ # add offset to PeriodIndex with freq.n > 1
+
+ per = Period("2016-01", freq="2M")
+ pi = PeriodIndex([per])
+
+ expected = PeriodIndex(["2016-03"], freq="2M")
+
+ pi = tm.box_expected(pi, box_with_array, transpose=transpose)
+ expected = tm.box_expected(expected, box_with_array, transpose=transpose)
+
+ result = pi + per.freq
+ tm.assert_equal(result, expected)
+
+ result = per.freq + pi
+ tm.assert_equal(result, expected)
+
+ def test_pi_add_offset_n_gt1_not_divisible(self, box_with_array):
+ # GH#23215
+ # PeriodIndex with freq.n > 1 add offset with offset.n % freq.n != 0
+ pi = PeriodIndex(["2016-01"], freq="2M")
+ expected = PeriodIndex(["2016-04"], freq="2M")
+
+ pi = tm.box_expected(pi, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = pi + to_offset("3M")
+ tm.assert_equal(result, expected)
+
+ result = to_offset("3M") + pi
+ tm.assert_equal(result, expected)
+
+ # ---------------------------------------------------------------
+ # __add__/__sub__ with integer arrays
+
+ @pytest.mark.parametrize("int_holder", [np.array, pd.Index])
+ @pytest.mark.parametrize("op", [operator.add, ops.radd])
+ def test_pi_add_intarray(self, int_holder, op):
+ # GH#19959
+ pi = PeriodIndex([Period("2015Q1"), Period("NaT")])
+ other = int_holder([4, -1])
+
+ result = op(pi, other)
+ expected = PeriodIndex([Period("2016Q1"), Period("NaT")])
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("int_holder", [np.array, pd.Index])
+ def test_pi_sub_intarray(self, int_holder):
+ # GH#19959
+ pi = PeriodIndex([Period("2015Q1"), Period("NaT")])
+ other = int_holder([4, -1])
+
+ result = pi - other
+ expected = PeriodIndex([Period("2014Q1"), Period("NaT")])
+ tm.assert_index_equal(result, expected)
+
+ msg = r"bad operand type for unary -: 'PeriodArray'"
+ with pytest.raises(TypeError, match=msg):
+ other - pi
+
+ # ---------------------------------------------------------------
+ # Timedelta-like (timedelta, timedelta64, Timedelta, Tick)
+ # TODO: Some of these are misnomers because of non-Tick DateOffsets
+
+ def test_parr_add_timedeltalike_minute_gt1(self, three_days, box_with_array):
+ # GH#23031 adding a time-delta-like offset to a PeriodArray that has
+ # minute frequency with n != 1. A more general case is tested below
+ # in test_pi_add_timedeltalike_tick_gt1, but here we write out the
+ # expected result more explicitly.
+ other = three_days
+ rng = period_range("2014-05-01", periods=3, freq="2D")
+ rng = tm.box_expected(rng, box_with_array)
+
+ expected = PeriodIndex(["2014-05-04", "2014-05-06", "2014-05-08"], freq="2D")
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = rng + other
+ tm.assert_equal(result, expected)
+
+ result = other + rng
+ tm.assert_equal(result, expected)
+
+ # subtraction
+ expected = PeriodIndex(["2014-04-28", "2014-04-30", "2014-05-02"], freq="2D")
+ expected = tm.box_expected(expected, box_with_array)
+ result = rng - other
+ tm.assert_equal(result, expected)
+
+ msg = "|".join(
+ [
+ r"bad operand type for unary -: 'PeriodArray'",
+ r"cannot subtract PeriodArray from timedelta64\[[hD]\]",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ other - rng
+
+ @pytest.mark.parametrize("freqstr", ["5ns", "5us", "5ms", "5s", "5T", "5h", "5d"])
+ def test_parr_add_timedeltalike_tick_gt1(self, three_days, freqstr, box_with_array):
+ # GH#23031 adding a time-delta-like offset to a PeriodArray that has
+ # tick-like frequency with n != 1
+ other = three_days
+ rng = period_range("2014-05-01", periods=6, freq=freqstr)
+ first = rng[0]
+ rng = tm.box_expected(rng, box_with_array)
+
+ expected = period_range(first + other, periods=6, freq=freqstr)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = rng + other
+ tm.assert_equal(result, expected)
+
+ result = other + rng
+ tm.assert_equal(result, expected)
+
+ # subtraction
+ expected = period_range(first - other, periods=6, freq=freqstr)
+ expected = tm.box_expected(expected, box_with_array)
+ result = rng - other
+ tm.assert_equal(result, expected)
+ msg = "|".join(
+ [
+ r"bad operand type for unary -: 'PeriodArray'",
+ r"cannot subtract PeriodArray from timedelta64\[[hD]\]",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ other - rng
+
+ def test_pi_add_iadd_timedeltalike_daily(self, three_days):
+ # Tick
+ other = three_days
+ rng = period_range("2014-05-01", "2014-05-15", freq="D")
+ expected = period_range("2014-05-04", "2014-05-18", freq="D")
+
+ result = rng + other
+ tm.assert_index_equal(result, expected)
+
+ rng += other
+ tm.assert_index_equal(rng, expected)
+
+ def test_pi_sub_isub_timedeltalike_daily(self, three_days):
+ # Tick-like 3 Days
+ other = three_days
+ rng = period_range("2014-05-01", "2014-05-15", freq="D")
+ expected = period_range("2014-04-28", "2014-05-12", freq="D")
+
+ result = rng - other
+ tm.assert_index_equal(result, expected)
+
+ rng -= other
+ tm.assert_index_equal(rng, expected)
+
+ def test_parr_add_sub_timedeltalike_freq_mismatch_daily(
+ self, not_daily, box_with_array
+ ):
+ other = not_daily
+ rng = period_range("2014-05-01", "2014-05-15", freq="D")
+ rng = tm.box_expected(rng, box_with_array)
+
+ msg = "|".join(
+ [
+ # non-timedelta-like DateOffset
+ "Input has different freq(=.+)? from Period.*?\\(freq=D\\)",
+ # timedelta/td64/Timedelta but not a multiple of 24H
+ "Cannot add/subtract timedelta-like from PeriodArray that is "
+ "not an integer multiple of the PeriodArray's freq.",
+ ]
+ )
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng + other
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng += other
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng - other
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng -= other
+
+ def test_pi_add_iadd_timedeltalike_hourly(self, two_hours):
+ other = two_hours
+ rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="H")
+ expected = period_range("2014-01-01 12:00", "2014-01-05 12:00", freq="H")
+
+ result = rng + other
+ tm.assert_index_equal(result, expected)
+
+ rng += other
+ tm.assert_index_equal(rng, expected)
+
+ def test_parr_add_timedeltalike_mismatched_freq_hourly(
+ self, not_hourly, box_with_array
+ ):
+ other = not_hourly
+ rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="H")
+ rng = tm.box_expected(rng, box_with_array)
+ msg = "|".join(
+ [
+ # non-timedelta-like DateOffset
+ "Input has different freq(=.+)? from Period.*?\\(freq=H\\)",
+ # timedelta/td64/Timedelta but not a multiple of 24H
+ "Cannot add/subtract timedelta-like from PeriodArray that is "
+ "not an integer multiple of the PeriodArray's freq.",
+ ]
+ )
+
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng + other
+
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng += other
+
+ def test_pi_sub_isub_timedeltalike_hourly(self, two_hours):
+ other = two_hours
+ rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="H")
+ expected = period_range("2014-01-01 08:00", "2014-01-05 08:00", freq="H")
+
+ result = rng - other
+ tm.assert_index_equal(result, expected)
+
+ rng -= other
+ tm.assert_index_equal(rng, expected)
+
+ def test_add_iadd_timedeltalike_annual(self):
+ # offset
+ # DateOffset
+ rng = period_range("2014", "2024", freq="A")
+ result = rng + pd.offsets.YearEnd(5)
+ expected = period_range("2019", "2029", freq="A")
+ tm.assert_index_equal(result, expected)
+ rng += pd.offsets.YearEnd(5)
+ tm.assert_index_equal(rng, expected)
+
+ def test_pi_add_sub_timedeltalike_freq_mismatch_annual(self, mismatched_freq):
+ other = mismatched_freq
+ rng = period_range("2014", "2024", freq="A")
+ msg = "Input has different freq(=.+)? from Period.*?\\(freq=A-DEC\\)"
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng + other
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng += other
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng - other
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng -= other
+
+ def test_pi_add_iadd_timedeltalike_M(self):
+ rng = period_range("2014-01", "2016-12", freq="M")
+ expected = period_range("2014-06", "2017-05", freq="M")
+
+ result = rng + pd.offsets.MonthEnd(5)
+ tm.assert_index_equal(result, expected)
+
+ rng += pd.offsets.MonthEnd(5)
+ tm.assert_index_equal(rng, expected)
+
+ def test_pi_add_sub_timedeltalike_freq_mismatch_monthly(self, mismatched_freq):
+ other = mismatched_freq
+ rng = period_range("2014-01", "2016-12", freq="M")
+ msg = "Input has different freq(=.+)? from Period.*?\\(freq=M\\)"
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng + other
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng += other
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng - other
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ rng -= other
+
+ @pytest.mark.parametrize("transpose", [True, False])
+ def test_parr_add_sub_td64_nat(self, box_with_array, transpose):
+ # GH#23320 special handling for timedelta64("NaT")
+ pi = period_range("1994-04-01", periods=9, freq="19D")
+ other = np.timedelta64("NaT")
+ expected = PeriodIndex(["NaT"] * 9, freq="19D")
+
+ obj = tm.box_expected(pi, box_with_array, transpose=transpose)
+ expected = tm.box_expected(expected, box_with_array, transpose=transpose)
+
+ result = obj + other
+ tm.assert_equal(result, expected)
+ result = other + obj
+ tm.assert_equal(result, expected)
+ result = obj - other
+ tm.assert_equal(result, expected)
+ msg = r"cannot subtract .* from .*"
+ with pytest.raises(TypeError, match=msg):
+ other - obj
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ np.array(["NaT"] * 9, dtype="m8[ns]"),
+ TimedeltaArray._from_sequence(["NaT"] * 9),
+ ],
+ )
+ def test_parr_add_sub_tdt64_nat_array(self, box_with_array, other):
+ pi = period_range("1994-04-01", periods=9, freq="19D")
+ expected = PeriodIndex(["NaT"] * 9, freq="19D")
+
+ obj = tm.box_expected(pi, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = obj + other
+ tm.assert_equal(result, expected)
+ result = other + obj
+ tm.assert_equal(result, expected)
+ result = obj - other
+ tm.assert_equal(result, expected)
+ msg = r"cannot subtract .* from .*"
+ with pytest.raises(TypeError, match=msg):
+ other - obj
+
+ # some but not *all* NaT
+ other = other.copy()
+ other[0] = np.timedelta64(0, "ns")
+ expected = PeriodIndex([pi[0]] + ["NaT"] * 8, freq="19D")
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = obj + other
+ tm.assert_equal(result, expected)
+ result = other + obj
+ tm.assert_equal(result, expected)
+ result = obj - other
+ tm.assert_equal(result, expected)
+ with pytest.raises(TypeError, match=msg):
+ other - obj
+
+ # ---------------------------------------------------------------
+ # Unsorted
+
+ def test_parr_add_sub_index(self):
+ # Check that PeriodArray defers to Index on arithmetic ops
+ pi = period_range("2000-12-31", periods=3)
+ parr = pi.array
+
+ result = parr - pi
+ expected = pi - pi
+ tm.assert_index_equal(result, expected)
+
+ def test_parr_add_sub_object_array(self):
+ pi = period_range("2000-12-31", periods=3, freq="D")
+ parr = pi.array
+
+ other = np.array([Timedelta(days=1), pd.offsets.Day(2), 3])
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = parr + other
+
+ expected = PeriodIndex(
+ ["2001-01-01", "2001-01-03", "2001-01-05"], freq="D"
+ )._data.astype(object)
+ tm.assert_equal(result, expected)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = parr - other
+
+ expected = PeriodIndex(["2000-12-30"] * 3, freq="D")._data.astype(object)
+ tm.assert_equal(result, expected)
+
+
+class TestPeriodSeriesArithmetic:
+ def test_parr_add_timedeltalike_scalar(self, three_days, box_with_array):
+ # GH#13043
+ ser = Series(
+ [Period("2015-01-01", freq="D"), Period("2015-01-02", freq="D")],
+ name="xxx",
+ )
+ assert ser.dtype == "Period[D]"
+
+ expected = Series(
+ [Period("2015-01-04", freq="D"), Period("2015-01-05", freq="D")],
+ name="xxx",
+ )
+
+ obj = tm.box_expected(ser, box_with_array)
+ if box_with_array is pd.DataFrame:
+ assert (obj.dtypes == "Period[D]").all()
+
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = obj + three_days
+ tm.assert_equal(result, expected)
+
+ result = three_days + obj
+ tm.assert_equal(result, expected)
+
+ def test_ops_series_period(self):
+ # GH#13043
+ ser = Series(
+ [Period("2015-01-01", freq="D"), Period("2015-01-02", freq="D")],
+ name="xxx",
+ )
+ assert ser.dtype == "Period[D]"
+
+ per = Period("2015-01-10", freq="D")
+ off = per.freq
+ # dtype will be object because of original dtype
+ expected = Series([9 * off, 8 * off], name="xxx", dtype=object)
+ tm.assert_series_equal(per - ser, expected)
+ tm.assert_series_equal(ser - per, -1 * expected)
+
+ s2 = Series(
+ [Period("2015-01-05", freq="D"), Period("2015-01-04", freq="D")],
+ name="xxx",
+ )
+ assert s2.dtype == "Period[D]"
+
+ expected = Series([4 * off, 2 * off], name="xxx", dtype=object)
+ tm.assert_series_equal(s2 - ser, expected)
+ tm.assert_series_equal(ser - s2, -1 * expected)
+
+
+class TestPeriodIndexSeriesMethods:
+ """Test PeriodIndex and Period Series Ops consistency"""
+
+ def _check(self, values, func, expected):
+ idx = PeriodIndex(values)
+ result = func(idx)
+ tm.assert_equal(result, expected)
+
+ ser = Series(values)
+ result = func(ser)
+
+ exp = Series(expected, name=values.name)
+ tm.assert_series_equal(result, exp)
+
+ def test_pi_ops(self):
+ idx = PeriodIndex(
+ ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
+ )
+
+ expected = PeriodIndex(
+ ["2011-03", "2011-04", "2011-05", "2011-06"], freq="M", name="idx"
+ )
+
+ self._check(idx, lambda x: x + 2, expected)
+ self._check(idx, lambda x: 2 + x, expected)
+
+ self._check(idx + 2, lambda x: x - 2, idx)
+
+ result = idx - Period("2011-01", freq="M")
+ off = idx.freq
+ exp = pd.Index([0 * off, 1 * off, 2 * off, 3 * off], name="idx")
+ tm.assert_index_equal(result, exp)
+
+ result = Period("2011-01", freq="M") - idx
+ exp = pd.Index([0 * off, -1 * off, -2 * off, -3 * off], name="idx")
+ tm.assert_index_equal(result, exp)
+
+ @pytest.mark.parametrize("ng", ["str", 1.5])
+ @pytest.mark.parametrize(
+ "func",
+ [
+ lambda obj, ng: obj + ng,
+ lambda obj, ng: ng + obj,
+ lambda obj, ng: obj - ng,
+ lambda obj, ng: ng - obj,
+ lambda obj, ng: np.add(obj, ng),
+ lambda obj, ng: np.add(ng, obj),
+ lambda obj, ng: np.subtract(obj, ng),
+ lambda obj, ng: np.subtract(ng, obj),
+ ],
+ )
+ def test_parr_ops_errors(self, ng, func, box_with_array):
+ idx = PeriodIndex(
+ ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
+ )
+ obj = tm.box_expected(idx, box_with_array)
+ msg = "|".join(
+ [
+ r"unsupported operand type\(s\)",
+ "can only concatenate",
+ r"must be str",
+ "object to str implicitly",
+ ]
+ )
+
+ with pytest.raises(TypeError, match=msg):
+ func(obj, ng)
+
+ def test_pi_ops_nat(self):
+ idx = PeriodIndex(
+ ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx"
+ )
+ expected = PeriodIndex(
+ ["2011-03", "2011-04", "NaT", "2011-06"], freq="M", name="idx"
+ )
+
+ self._check(idx, lambda x: x + 2, expected)
+ self._check(idx, lambda x: 2 + x, expected)
+ self._check(idx, lambda x: np.add(x, 2), expected)
+
+ self._check(idx + 2, lambda x: x - 2, idx)
+ self._check(idx + 2, lambda x: np.subtract(x, 2), idx)
+
+ # freq with mult
+ idx = PeriodIndex(
+ ["2011-01", "2011-02", "NaT", "2011-04"], freq="2M", name="idx"
+ )
+ expected = PeriodIndex(
+ ["2011-07", "2011-08", "NaT", "2011-10"], freq="2M", name="idx"
+ )
+
+ self._check(idx, lambda x: x + 3, expected)
+ self._check(idx, lambda x: 3 + x, expected)
+ self._check(idx, lambda x: np.add(x, 3), expected)
+
+ self._check(idx + 3, lambda x: x - 3, idx)
+ self._check(idx + 3, lambda x: np.subtract(x, 3), idx)
+
+ def test_pi_ops_array_int(self):
+ idx = PeriodIndex(
+ ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx"
+ )
+ f = lambda x: x + np.array([1, 2, 3, 4])
+ exp = PeriodIndex(
+ ["2011-02", "2011-04", "NaT", "2011-08"], freq="M", name="idx"
+ )
+ self._check(idx, f, exp)
+
+ f = lambda x: np.add(x, np.array([4, -1, 1, 2]))
+ exp = PeriodIndex(
+ ["2011-05", "2011-01", "NaT", "2011-06"], freq="M", name="idx"
+ )
+ self._check(idx, f, exp)
+
+ f = lambda x: x - np.array([1, 2, 3, 4])
+ exp = PeriodIndex(
+ ["2010-12", "2010-12", "NaT", "2010-12"], freq="M", name="idx"
+ )
+ self._check(idx, f, exp)
+
+ f = lambda x: np.subtract(x, np.array([3, 2, 3, -2]))
+ exp = PeriodIndex(
+ ["2010-10", "2010-12", "NaT", "2011-06"], freq="M", name="idx"
+ )
+ self._check(idx, f, exp)
+
+ def test_pi_ops_offset(self):
+ idx = PeriodIndex(
+ ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01"],
+ freq="D",
+ name="idx",
+ )
+ f = lambda x: x + pd.offsets.Day()
+ exp = PeriodIndex(
+ ["2011-01-02", "2011-02-02", "2011-03-02", "2011-04-02"],
+ freq="D",
+ name="idx",
+ )
+ self._check(idx, f, exp)
+
+ f = lambda x: x + pd.offsets.Day(2)
+ exp = PeriodIndex(
+ ["2011-01-03", "2011-02-03", "2011-03-03", "2011-04-03"],
+ freq="D",
+ name="idx",
+ )
+ self._check(idx, f, exp)
+
+ f = lambda x: x - pd.offsets.Day(2)
+ exp = PeriodIndex(
+ ["2010-12-30", "2011-01-30", "2011-02-27", "2011-03-30"],
+ freq="D",
+ name="idx",
+ )
+ self._check(idx, f, exp)
+
+ def test_pi_offset_errors(self):
+ idx = PeriodIndex(
+ ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01"],
+ freq="D",
+ name="idx",
+ )
+ ser = Series(idx)
+
+ msg = (
+ "Cannot add/subtract timedelta-like from PeriodArray that is not "
+ "an integer multiple of the PeriodArray's freq"
+ )
+ for obj in [idx, ser]:
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ obj + pd.offsets.Hour(2)
+
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ pd.offsets.Hour(2) + obj
+
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ obj - pd.offsets.Hour(2)
+
+ def test_pi_sub_period(self):
+ # GH#13071
+ idx = PeriodIndex(
+ ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
+ )
+
+ result = idx - Period("2012-01", freq="M")
+ off = idx.freq
+ exp = pd.Index([-12 * off, -11 * off, -10 * off, -9 * off], name="idx")
+ tm.assert_index_equal(result, exp)
+
+ result = np.subtract(idx, Period("2012-01", freq="M"))
+ tm.assert_index_equal(result, exp)
+
+ result = Period("2012-01", freq="M") - idx
+ exp = pd.Index([12 * off, 11 * off, 10 * off, 9 * off], name="idx")
+ tm.assert_index_equal(result, exp)
+
+ result = np.subtract(Period("2012-01", freq="M"), idx)
+ tm.assert_index_equal(result, exp)
+
+ exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx")
+ result = idx - Period("NaT", freq="M")
+ tm.assert_index_equal(result, exp)
+ assert result.freq == exp.freq
+
+ result = Period("NaT", freq="M") - idx
+ tm.assert_index_equal(result, exp)
+ assert result.freq == exp.freq
+
+ def test_pi_sub_pdnat(self):
+ # GH#13071, GH#19389
+ idx = PeriodIndex(
+ ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx"
+ )
+ exp = TimedeltaIndex([pd.NaT] * 4, name="idx")
+ tm.assert_index_equal(pd.NaT - idx, exp)
+ tm.assert_index_equal(idx - pd.NaT, exp)
+
+ def test_pi_sub_period_nat(self):
+ # GH#13071
+ idx = PeriodIndex(
+ ["2011-01", "NaT", "2011-03", "2011-04"], freq="M", name="idx"
+ )
+
+ result = idx - Period("2012-01", freq="M")
+ off = idx.freq
+ exp = pd.Index([-12 * off, pd.NaT, -10 * off, -9 * off], name="idx")
+ tm.assert_index_equal(result, exp)
+
+ result = Period("2012-01", freq="M") - idx
+ exp = pd.Index([12 * off, pd.NaT, 10 * off, 9 * off], name="idx")
+ tm.assert_index_equal(result, exp)
+
+ exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx")
+ tm.assert_index_equal(idx - Period("NaT", freq="M"), exp)
+ tm.assert_index_equal(Period("NaT", freq="M") - idx, exp)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_timedelta64.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_timedelta64.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d237b3ac4a31e3f9308e49a837f33f7f559a967
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arithmetic/test_timedelta64.py
@@ -0,0 +1,2174 @@
+# Arithmetic tests for DataFrame/Series/Index/Array classes that should
+# behave identically.
+from datetime import (
+ datetime,
+ timedelta,
+)
+
+import numpy as np
+import pytest
+
+from pandas.errors import (
+ OutOfBoundsDatetime,
+ PerformanceWarning,
+)
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ NaT,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ Timestamp,
+ offsets,
+ timedelta_range,
+)
+import pandas._testing as tm
+from pandas.core.arrays import NumpyExtensionArray
+from pandas.tests.arithmetic.common import (
+ assert_invalid_addsub_type,
+ assert_invalid_comparison,
+ get_upcast_box,
+)
+
+
+def assert_dtype(obj, expected_dtype):
+ """
+ Helper to check the dtype for a Series, Index, or single-column DataFrame.
+ """
+ dtype = tm.get_dtype(obj)
+
+ assert dtype == expected_dtype
+
+
+def get_expected_name(box, names):
+ if box is DataFrame:
+ # Since we are operating with a DataFrame and a non-DataFrame,
+ # the non-DataFrame is cast to Series and its name ignored.
+ exname = names[0]
+ elif box in [tm.to_array, pd.array]:
+ exname = names[1]
+ else:
+ exname = names[2]
+ return exname
+
+
+# ------------------------------------------------------------------
+# Timedelta64[ns] dtype Comparisons
+
+
+class TestTimedelta64ArrayLikeComparisons:
+ # Comparison tests for timedelta64[ns] vectors fully parametrized over
+ # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all comparison
+ # tests will eventually end up here.
+
+ def test_compare_timedelta64_zerodim(self, box_with_array):
+ # GH#26689 should unbox when comparing with zerodim array
+ box = box_with_array
+ xbox = box_with_array if box_with_array not in [Index, pd.array] else np.ndarray
+
+ tdi = timedelta_range("2H", periods=4)
+ other = np.array(tdi.to_numpy()[0])
+
+ tdi = tm.box_expected(tdi, box)
+ res = tdi <= other
+ expected = np.array([True, False, False, False])
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(res, expected)
+
+ @pytest.mark.parametrize(
+ "td_scalar",
+ [
+ timedelta(days=1),
+ Timedelta(days=1),
+ Timedelta(days=1).to_timedelta64(),
+ offsets.Hour(24),
+ ],
+ )
+ def test_compare_timedeltalike_scalar(self, box_with_array, td_scalar):
+ # regression test for GH#5963
+ box = box_with_array
+ xbox = box if box not in [Index, pd.array] else np.ndarray
+
+ ser = Series([timedelta(days=1), timedelta(days=2)])
+ ser = tm.box_expected(ser, box)
+ actual = ser > td_scalar
+ expected = Series([False, True])
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(actual, expected)
+
+ @pytest.mark.parametrize(
+ "invalid",
+ [
+ 345600000000000,
+ "a",
+ Timestamp("2021-01-01"),
+ Timestamp("2021-01-01").now("UTC"),
+ Timestamp("2021-01-01").now().to_datetime64(),
+ Timestamp("2021-01-01").now().to_pydatetime(),
+ Timestamp("2021-01-01").date(),
+ np.array(4), # zero-dim mismatched dtype
+ ],
+ )
+ def test_td64_comparisons_invalid(self, box_with_array, invalid):
+ # GH#13624 for str
+ box = box_with_array
+
+ rng = timedelta_range("1 days", periods=10)
+ obj = tm.box_expected(rng, box)
+
+ assert_invalid_comparison(obj, invalid, box)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ list(range(10)),
+ np.arange(10),
+ np.arange(10).astype(np.float32),
+ np.arange(10).astype(object),
+ pd.date_range("1970-01-01", periods=10, tz="UTC").array,
+ np.array(pd.date_range("1970-01-01", periods=10)),
+ list(pd.date_range("1970-01-01", periods=10)),
+ pd.date_range("1970-01-01", periods=10).astype(object),
+ pd.period_range("1971-01-01", freq="D", periods=10).array,
+ pd.period_range("1971-01-01", freq="D", periods=10).astype(object),
+ ],
+ )
+ def test_td64arr_cmp_arraylike_invalid(self, other, box_with_array):
+ # We don't parametrize this over box_with_array because listlike
+ # other plays poorly with assert_invalid_comparison reversed checks
+
+ rng = timedelta_range("1 days", periods=10)._data
+ rng = tm.box_expected(rng, box_with_array)
+ assert_invalid_comparison(rng, other, box_with_array)
+
+ def test_td64arr_cmp_mixed_invalid(self):
+ rng = timedelta_range("1 days", periods=5)._data
+ other = np.array([0, 1, 2, rng[3], Timestamp("2021-01-01")])
+
+ result = rng == other
+ expected = np.array([False, False, False, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = rng != other
+ tm.assert_numpy_array_equal(result, ~expected)
+
+ msg = "Invalid comparison between|Cannot compare type|not supported between"
+ with pytest.raises(TypeError, match=msg):
+ rng < other
+ with pytest.raises(TypeError, match=msg):
+ rng > other
+ with pytest.raises(TypeError, match=msg):
+ rng <= other
+ with pytest.raises(TypeError, match=msg):
+ rng >= other
+
+
+class TestTimedelta64ArrayComparisons:
+ # TODO: All of these need to be parametrized over box
+
+ @pytest.mark.parametrize("dtype", [None, object])
+ def test_comp_nat(self, dtype):
+ left = TimedeltaIndex([Timedelta("1 days"), NaT, Timedelta("3 days")])
+ right = TimedeltaIndex([NaT, NaT, Timedelta("3 days")])
+
+ lhs, rhs = left, right
+ if dtype is object:
+ lhs, rhs = left.astype(object), right.astype(object)
+
+ result = rhs == lhs
+ expected = np.array([False, False, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = rhs != lhs
+ expected = np.array([True, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ expected = np.array([False, False, False])
+ tm.assert_numpy_array_equal(lhs == NaT, expected)
+ tm.assert_numpy_array_equal(NaT == rhs, expected)
+
+ expected = np.array([True, True, True])
+ tm.assert_numpy_array_equal(lhs != NaT, expected)
+ tm.assert_numpy_array_equal(NaT != lhs, expected)
+
+ expected = np.array([False, False, False])
+ tm.assert_numpy_array_equal(lhs < NaT, expected)
+ tm.assert_numpy_array_equal(NaT > lhs, expected)
+
+ @pytest.mark.parametrize(
+ "idx2",
+ [
+ TimedeltaIndex(
+ ["2 day", "2 day", NaT, NaT, "1 day 00:00:02", "5 days 00:00:03"]
+ ),
+ np.array(
+ [
+ np.timedelta64(2, "D"),
+ np.timedelta64(2, "D"),
+ np.timedelta64("nat"),
+ np.timedelta64("nat"),
+ np.timedelta64(1, "D") + np.timedelta64(2, "s"),
+ np.timedelta64(5, "D") + np.timedelta64(3, "s"),
+ ]
+ ),
+ ],
+ )
+ def test_comparisons_nat(self, idx2):
+ idx1 = TimedeltaIndex(
+ [
+ "1 day",
+ NaT,
+ "1 day 00:00:01",
+ NaT,
+ "1 day 00:00:01",
+ "5 day 00:00:03",
+ ]
+ )
+ # Check pd.NaT is handles as the same as np.nan
+ result = idx1 < idx2
+ expected = np.array([True, False, False, False, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx2 > idx1
+ expected = np.array([True, False, False, False, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 <= idx2
+ expected = np.array([True, False, False, False, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx2 >= idx1
+ expected = np.array([True, False, False, False, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 == idx2
+ expected = np.array([False, False, False, False, False, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx1 != idx2
+ expected = np.array([True, True, True, True, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ # TODO: better name
+ def test_comparisons_coverage(self):
+ rng = timedelta_range("1 days", periods=10)
+
+ result = rng < rng[3]
+ expected = np.array([True, True, True] + [False] * 7)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = rng == list(rng)
+ exp = rng == rng
+ tm.assert_numpy_array_equal(result, exp)
+
+
+# ------------------------------------------------------------------
+# Timedelta64[ns] dtype Arithmetic Operations
+
+
+class TestTimedelta64ArithmeticUnsorted:
+ # Tests moved from type-specific test files but not
+ # yet sorted/parametrized/de-duplicated
+
+ def test_ufunc_coercions(self):
+ # normal ops are also tested in tseries/test_timedeltas.py
+ idx = TimedeltaIndex(["2H", "4H", "6H", "8H", "10H"], freq="2H", name="x")
+
+ for result in [idx * 2, np.multiply(idx, 2)]:
+ assert isinstance(result, TimedeltaIndex)
+ exp = TimedeltaIndex(["4H", "8H", "12H", "16H", "20H"], freq="4H", name="x")
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "4H"
+
+ for result in [idx / 2, np.divide(idx, 2)]:
+ assert isinstance(result, TimedeltaIndex)
+ exp = TimedeltaIndex(["1H", "2H", "3H", "4H", "5H"], freq="H", name="x")
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "H"
+
+ for result in [-idx, np.negative(idx)]:
+ assert isinstance(result, TimedeltaIndex)
+ exp = TimedeltaIndex(
+ ["-2H", "-4H", "-6H", "-8H", "-10H"], freq="-2H", name="x"
+ )
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "-2H"
+
+ idx = TimedeltaIndex(["-2H", "-1H", "0H", "1H", "2H"], freq="H", name="x")
+ for result in [abs(idx), np.absolute(idx)]:
+ assert isinstance(result, TimedeltaIndex)
+ exp = TimedeltaIndex(["2H", "1H", "0H", "1H", "2H"], freq=None, name="x")
+ tm.assert_index_equal(result, exp)
+ assert result.freq is None
+
+ def test_subtraction_ops(self):
+ # with datetimes/timedelta and tdi/dti
+ tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
+ dti = pd.date_range("20130101", periods=3, name="bar")
+ td = Timedelta("1 days")
+ dt = Timestamp("20130101")
+
+ msg = "cannot subtract a datelike from a TimedeltaArray"
+ with pytest.raises(TypeError, match=msg):
+ tdi - dt
+ with pytest.raises(TypeError, match=msg):
+ tdi - dti
+
+ msg = r"unsupported operand type\(s\) for -"
+ with pytest.raises(TypeError, match=msg):
+ td - dt
+
+ msg = "(bad|unsupported) operand type for unary"
+ with pytest.raises(TypeError, match=msg):
+ td - dti
+
+ result = dt - dti
+ expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"], name="bar")
+ tm.assert_index_equal(result, expected)
+
+ result = dti - dt
+ expected = TimedeltaIndex(["0 days", "1 days", "2 days"], name="bar")
+ tm.assert_index_equal(result, expected)
+
+ result = tdi - td
+ expected = TimedeltaIndex(["0 days", NaT, "1 days"], name="foo")
+ tm.assert_index_equal(result, expected, check_names=False)
+
+ result = td - tdi
+ expected = TimedeltaIndex(["0 days", NaT, "-1 days"], name="foo")
+ tm.assert_index_equal(result, expected, check_names=False)
+
+ result = dti - td
+ expected = DatetimeIndex(
+ ["20121231", "20130101", "20130102"], freq="D", name="bar"
+ )
+ tm.assert_index_equal(result, expected, check_names=False)
+
+ result = dt - tdi
+ expected = DatetimeIndex(["20121231", NaT, "20121230"], name="foo")
+ tm.assert_index_equal(result, expected)
+
+ def test_subtraction_ops_with_tz(self, box_with_array):
+ # check that dt/dti subtraction ops with tz are validated
+ dti = pd.date_range("20130101", periods=3)
+ dti = tm.box_expected(dti, box_with_array)
+ ts = Timestamp("20130101")
+ dt = ts.to_pydatetime()
+ dti_tz = pd.date_range("20130101", periods=3).tz_localize("US/Eastern")
+ dti_tz = tm.box_expected(dti_tz, box_with_array)
+ ts_tz = Timestamp("20130101").tz_localize("US/Eastern")
+ ts_tz2 = Timestamp("20130101").tz_localize("CET")
+ dt_tz = ts_tz.to_pydatetime()
+ td = Timedelta("1 days")
+
+ def _check(result, expected):
+ assert result == expected
+ assert isinstance(result, Timedelta)
+
+ # scalars
+ result = ts - ts
+ expected = Timedelta("0 days")
+ _check(result, expected)
+
+ result = dt_tz - ts_tz
+ expected = Timedelta("0 days")
+ _check(result, expected)
+
+ result = ts_tz - dt_tz
+ expected = Timedelta("0 days")
+ _check(result, expected)
+
+ # tz mismatches
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects."
+ with pytest.raises(TypeError, match=msg):
+ dt_tz - ts
+ msg = "can't subtract offset-naive and offset-aware datetimes"
+ with pytest.raises(TypeError, match=msg):
+ dt_tz - dt
+ msg = "can't subtract offset-naive and offset-aware datetimes"
+ with pytest.raises(TypeError, match=msg):
+ dt - dt_tz
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects."
+ with pytest.raises(TypeError, match=msg):
+ ts - dt_tz
+ with pytest.raises(TypeError, match=msg):
+ ts_tz2 - ts
+ with pytest.raises(TypeError, match=msg):
+ ts_tz2 - dt
+
+ msg = "Cannot subtract tz-naive and tz-aware"
+ # with dti
+ with pytest.raises(TypeError, match=msg):
+ dti - ts_tz
+ with pytest.raises(TypeError, match=msg):
+ dti_tz - ts
+
+ result = dti_tz - dt_tz
+ expected = TimedeltaIndex(["0 days", "1 days", "2 days"])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ result = dt_tz - dti_tz
+ expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ result = dti_tz - ts_tz
+ expected = TimedeltaIndex(["0 days", "1 days", "2 days"])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ result = ts_tz - dti_tz
+ expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"])
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ result = td - td
+ expected = Timedelta("0 days")
+ _check(result, expected)
+
+ result = dti_tz - td
+ expected = DatetimeIndex(["20121231", "20130101", "20130102"], tz="US/Eastern")
+ expected = tm.box_expected(expected, box_with_array)
+ tm.assert_equal(result, expected)
+
+ def test_dti_tdi_numeric_ops(self):
+ # These are normally union/diff set-like ops
+ tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
+ dti = pd.date_range("20130101", periods=3, name="bar")
+
+ result = tdi - tdi
+ expected = TimedeltaIndex(["0 days", NaT, "0 days"], name="foo")
+ tm.assert_index_equal(result, expected)
+
+ result = tdi + tdi
+ expected = TimedeltaIndex(["2 days", NaT, "4 days"], name="foo")
+ tm.assert_index_equal(result, expected)
+
+ result = dti - tdi # name will be reset
+ expected = DatetimeIndex(["20121231", NaT, "20130101"])
+ tm.assert_index_equal(result, expected)
+
+ def test_addition_ops(self):
+ # with datetimes/timedelta and tdi/dti
+ tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
+ dti = pd.date_range("20130101", periods=3, name="bar")
+ td = Timedelta("1 days")
+ dt = Timestamp("20130101")
+
+ result = tdi + dt
+ expected = DatetimeIndex(["20130102", NaT, "20130103"], name="foo")
+ tm.assert_index_equal(result, expected)
+
+ result = dt + tdi
+ expected = DatetimeIndex(["20130102", NaT, "20130103"], name="foo")
+ tm.assert_index_equal(result, expected)
+
+ result = td + tdi
+ expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo")
+ tm.assert_index_equal(result, expected)
+
+ result = tdi + td
+ expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo")
+ tm.assert_index_equal(result, expected)
+
+ # unequal length
+ msg = "cannot add indices of unequal length"
+ with pytest.raises(ValueError, match=msg):
+ tdi + dti[0:1]
+ with pytest.raises(ValueError, match=msg):
+ tdi[0:1] + dti
+
+ # random indexes
+ msg = "Addition/subtraction of integers and integer-arrays"
+ with pytest.raises(TypeError, match=msg):
+ tdi + Index([1, 2, 3], dtype=np.int64)
+
+ # this is a union!
+ # pytest.raises(TypeError, lambda : Index([1,2,3]) + tdi)
+
+ result = tdi + dti # name will be reset
+ expected = DatetimeIndex(["20130102", NaT, "20130105"])
+ tm.assert_index_equal(result, expected)
+
+ result = dti + tdi # name will be reset
+ expected = DatetimeIndex(["20130102", NaT, "20130105"])
+ tm.assert_index_equal(result, expected)
+
+ result = dt + td
+ expected = Timestamp("20130102")
+ assert result == expected
+
+ result = td + dt
+ expected = Timestamp("20130102")
+ assert result == expected
+
+ # TODO: Needs more informative name, probably split up into
+ # more targeted tests
+ @pytest.mark.parametrize("freq", ["D", "B"])
+ def test_timedelta(self, freq):
+ index = pd.date_range("1/1/2000", periods=50, freq=freq)
+
+ shifted = index + timedelta(1)
+ back = shifted + timedelta(-1)
+ back = back._with_freq("infer")
+ tm.assert_index_equal(index, back)
+
+ if freq == "D":
+ expected = pd.tseries.offsets.Day(1)
+ assert index.freq == expected
+ assert shifted.freq == expected
+ assert back.freq == expected
+ else: # freq == 'B'
+ assert index.freq == pd.tseries.offsets.BusinessDay(1)
+ assert shifted.freq is None
+ assert back.freq == pd.tseries.offsets.BusinessDay(1)
+
+ result = index - timedelta(1)
+ expected = index + timedelta(-1)
+ tm.assert_index_equal(result, expected)
+
+ def test_timedelta_tick_arithmetic(self):
+ # GH#4134, buggy with timedeltas
+ rng = pd.date_range("2013", "2014")
+ s = Series(rng)
+ result1 = rng - offsets.Hour(1)
+ result2 = DatetimeIndex(s - np.timedelta64(100000000))
+ result3 = rng - np.timedelta64(100000000)
+ result4 = DatetimeIndex(s - offsets.Hour(1))
+
+ assert result1.freq == rng.freq
+ result1 = result1._with_freq(None)
+ tm.assert_index_equal(result1, result4)
+
+ assert result3.freq == rng.freq
+ result3 = result3._with_freq(None)
+ tm.assert_index_equal(result2, result3)
+
+ def test_tda_add_sub_index(self):
+ # Check that TimedeltaArray defers to Index on arithmetic ops
+ tdi = TimedeltaIndex(["1 days", NaT, "2 days"])
+ tda = tdi.array
+
+ dti = pd.date_range("1999-12-31", periods=3, freq="D")
+
+ result = tda + dti
+ expected = tdi + dti
+ tm.assert_index_equal(result, expected)
+
+ result = tda + tdi
+ expected = tdi + tdi
+ tm.assert_index_equal(result, expected)
+
+ result = tda - tdi
+ expected = tdi - tdi
+ tm.assert_index_equal(result, expected)
+
+ def test_tda_add_dt64_object_array(self, box_with_array, tz_naive_fixture):
+ # Result should be cast back to DatetimeArray
+ box = box_with_array
+
+ dti = pd.date_range("2016-01-01", periods=3, tz=tz_naive_fixture)
+ dti = dti._with_freq(None)
+ tdi = dti - dti
+
+ obj = tm.box_expected(tdi, box)
+ other = tm.box_expected(dti, box)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = obj + other.astype(object)
+ tm.assert_equal(result, other.astype(object))
+
+ # -------------------------------------------------------------
+ # Binary operations TimedeltaIndex and timedelta-like
+
+ def test_tdi_iadd_timedeltalike(self, two_hours, box_with_array):
+ # only test adding/sub offsets as + is now numeric
+ rng = timedelta_range("1 days", "10 days")
+ expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D")
+
+ rng = tm.box_expected(rng, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ orig_rng = rng
+ rng += two_hours
+ tm.assert_equal(rng, expected)
+ if box_with_array is not Index:
+ # Check that operation is actually inplace
+ tm.assert_equal(orig_rng, expected)
+
+ def test_tdi_isub_timedeltalike(self, two_hours, box_with_array):
+ # only test adding/sub offsets as - is now numeric
+ rng = timedelta_range("1 days", "10 days")
+ expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00")
+
+ rng = tm.box_expected(rng, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ orig_rng = rng
+ rng -= two_hours
+ tm.assert_equal(rng, expected)
+ if box_with_array is not Index:
+ # Check that operation is actually inplace
+ tm.assert_equal(orig_rng, expected)
+
+ # -------------------------------------------------------------
+
+ def test_tdi_ops_attributes(self):
+ rng = timedelta_range("2 days", periods=5, freq="2D", name="x")
+
+ result = rng + 1 * rng.freq
+ exp = timedelta_range("4 days", periods=5, freq="2D", name="x")
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "2D"
+
+ result = rng - 2 * rng.freq
+ exp = timedelta_range("-2 days", periods=5, freq="2D", name="x")
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "2D"
+
+ result = rng * 2
+ exp = timedelta_range("4 days", periods=5, freq="4D", name="x")
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "4D"
+
+ result = rng / 2
+ exp = timedelta_range("1 days", periods=5, freq="D", name="x")
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "D"
+
+ result = -rng
+ exp = timedelta_range("-2 days", periods=5, freq="-2D", name="x")
+ tm.assert_index_equal(result, exp)
+ assert result.freq == "-2D"
+
+ rng = timedelta_range("-2 days", periods=5, freq="D", name="x")
+
+ result = abs(rng)
+ exp = TimedeltaIndex(
+ ["2 days", "1 days", "0 days", "1 days", "2 days"], name="x"
+ )
+ tm.assert_index_equal(result, exp)
+ assert result.freq is None
+
+
+class TestAddSubNaTMasking:
+ # TODO: parametrize over boxes
+
+ @pytest.mark.parametrize("str_ts", ["1950-01-01", "1980-01-01"])
+ def test_tdarr_add_timestamp_nat_masking(self, box_with_array, str_ts):
+ # GH#17991 checking for overflow-masking with NaT
+ tdinat = pd.to_timedelta(["24658 days 11:15:00", "NaT"])
+ tdobj = tm.box_expected(tdinat, box_with_array)
+
+ ts = Timestamp(str_ts)
+ ts_variants = [
+ ts,
+ ts.to_pydatetime(),
+ ts.to_datetime64().astype("datetime64[ns]"),
+ ts.to_datetime64().astype("datetime64[D]"),
+ ]
+
+ for variant in ts_variants:
+ res = tdobj + variant
+ if box_with_array is DataFrame:
+ assert res.iloc[1, 1] is NaT
+ else:
+ assert res[1] is NaT
+
+ def test_tdi_add_overflow(self):
+ # See GH#14068
+ # preliminary test scalar analogue of vectorized tests below
+ # TODO: Make raised error message more informative and test
+ with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"):
+ pd.to_timedelta(106580, "D") + Timestamp("2000")
+ with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"):
+ Timestamp("2000") + pd.to_timedelta(106580, "D")
+
+ _NaT = NaT._value + 1
+ msg = "Overflow in int64 addition"
+ with pytest.raises(OverflowError, match=msg):
+ pd.to_timedelta([106580], "D") + Timestamp("2000")
+ with pytest.raises(OverflowError, match=msg):
+ Timestamp("2000") + pd.to_timedelta([106580], "D")
+ with pytest.raises(OverflowError, match=msg):
+ pd.to_timedelta([_NaT]) - Timedelta("1 days")
+ with pytest.raises(OverflowError, match=msg):
+ pd.to_timedelta(["5 days", _NaT]) - Timedelta("1 days")
+ with pytest.raises(OverflowError, match=msg):
+ (
+ pd.to_timedelta([_NaT, "5 days", "1 hours"])
+ - pd.to_timedelta(["7 seconds", _NaT, "4 hours"])
+ )
+
+ # These should not overflow!
+ exp = TimedeltaIndex([NaT])
+ result = pd.to_timedelta([NaT]) - Timedelta("1 days")
+ tm.assert_index_equal(result, exp)
+
+ exp = TimedeltaIndex(["4 days", NaT])
+ result = pd.to_timedelta(["5 days", NaT]) - Timedelta("1 days")
+ tm.assert_index_equal(result, exp)
+
+ exp = TimedeltaIndex([NaT, NaT, "5 hours"])
+ result = pd.to_timedelta([NaT, "5 days", "1 hours"]) + pd.to_timedelta(
+ ["7 seconds", NaT, "4 hours"]
+ )
+ tm.assert_index_equal(result, exp)
+
+
+class TestTimedeltaArraylikeAddSubOps:
+ # Tests for timedelta64[ns] __add__, __sub__, __radd__, __rsub__
+
+ def test_sub_nat_retain_unit(self):
+ ser = pd.to_timedelta(Series(["00:00:01"])).astype("m8[s]")
+
+ result = ser - NaT
+ expected = Series([NaT], dtype="m8[s]")
+ tm.assert_series_equal(result, expected)
+
+ # TODO: moved from tests.indexes.timedeltas.test_arithmetic; needs
+ # parametrization+de-duplication
+ def test_timedelta_ops_with_missing_values(self):
+ # setup
+ s1 = pd.to_timedelta(Series(["00:00:01"]))
+ s2 = pd.to_timedelta(Series(["00:00:02"]))
+
+ msg = r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]"
+ with pytest.raises(TypeError, match=msg):
+ # Passing datetime64-dtype data to TimedeltaIndex is no longer
+ # supported GH#29794
+ pd.to_timedelta(Series([NaT])) # TODO: belongs elsewhere?
+
+ sn = pd.to_timedelta(Series([NaT], dtype="m8[ns]"))
+
+ df1 = DataFrame(["00:00:01"]).apply(pd.to_timedelta)
+ df2 = DataFrame(["00:00:02"]).apply(pd.to_timedelta)
+ with pytest.raises(TypeError, match=msg):
+ # Passing datetime64-dtype data to TimedeltaIndex is no longer
+ # supported GH#29794
+ DataFrame([NaT]).apply(pd.to_timedelta) # TODO: belongs elsewhere?
+
+ dfn = DataFrame([NaT._value]).apply(pd.to_timedelta)
+
+ scalar1 = pd.to_timedelta("00:00:01")
+ scalar2 = pd.to_timedelta("00:00:02")
+ timedelta_NaT = pd.to_timedelta("NaT")
+
+ actual = scalar1 + scalar1
+ assert actual == scalar2
+ actual = scalar2 - scalar1
+ assert actual == scalar1
+
+ actual = s1 + s1
+ tm.assert_series_equal(actual, s2)
+ actual = s2 - s1
+ tm.assert_series_equal(actual, s1)
+
+ actual = s1 + scalar1
+ tm.assert_series_equal(actual, s2)
+ actual = scalar1 + s1
+ tm.assert_series_equal(actual, s2)
+ actual = s2 - scalar1
+ tm.assert_series_equal(actual, s1)
+ actual = -scalar1 + s2
+ tm.assert_series_equal(actual, s1)
+
+ actual = s1 + timedelta_NaT
+ tm.assert_series_equal(actual, sn)
+ actual = timedelta_NaT + s1
+ tm.assert_series_equal(actual, sn)
+ actual = s1 - timedelta_NaT
+ tm.assert_series_equal(actual, sn)
+ actual = -timedelta_NaT + s1
+ tm.assert_series_equal(actual, sn)
+
+ msg = "unsupported operand type"
+ with pytest.raises(TypeError, match=msg):
+ s1 + np.nan
+ with pytest.raises(TypeError, match=msg):
+ np.nan + s1
+ with pytest.raises(TypeError, match=msg):
+ s1 - np.nan
+ with pytest.raises(TypeError, match=msg):
+ -np.nan + s1
+
+ actual = s1 + NaT
+ tm.assert_series_equal(actual, sn)
+ actual = s2 - NaT
+ tm.assert_series_equal(actual, sn)
+
+ actual = s1 + df1
+ tm.assert_frame_equal(actual, df2)
+ actual = s2 - df1
+ tm.assert_frame_equal(actual, df1)
+ actual = df1 + s1
+ tm.assert_frame_equal(actual, df2)
+ actual = df2 - s1
+ tm.assert_frame_equal(actual, df1)
+
+ actual = df1 + df1
+ tm.assert_frame_equal(actual, df2)
+ actual = df2 - df1
+ tm.assert_frame_equal(actual, df1)
+
+ actual = df1 + scalar1
+ tm.assert_frame_equal(actual, df2)
+ actual = df2 - scalar1
+ tm.assert_frame_equal(actual, df1)
+
+ actual = df1 + timedelta_NaT
+ tm.assert_frame_equal(actual, dfn)
+ actual = df1 - timedelta_NaT
+ tm.assert_frame_equal(actual, dfn)
+
+ msg = "cannot subtract a datelike from|unsupported operand type"
+ with pytest.raises(TypeError, match=msg):
+ df1 + np.nan
+ with pytest.raises(TypeError, match=msg):
+ df1 - np.nan
+
+ actual = df1 + NaT # NaT is datetime, not timedelta
+ tm.assert_frame_equal(actual, dfn)
+ actual = df1 - NaT
+ tm.assert_frame_equal(actual, dfn)
+
+ # TODO: moved from tests.series.test_operators, needs splitting, cleanup,
+ # de-duplication, box-parametrization...
+ def test_operators_timedelta64(self):
+ # series ops
+ v1 = pd.date_range("2012-1-1", periods=3, freq="D")
+ v2 = pd.date_range("2012-1-2", periods=3, freq="D")
+ rs = Series(v2) - Series(v1)
+ xp = Series(1e9 * 3600 * 24, rs.index).astype("int64").astype("timedelta64[ns]")
+ tm.assert_series_equal(rs, xp)
+ assert rs.dtype == "timedelta64[ns]"
+
+ df = DataFrame({"A": v1})
+ td = Series([timedelta(days=i) for i in range(3)])
+ assert td.dtype == "timedelta64[ns]"
+
+ # series on the rhs
+ result = df["A"] - df["A"].shift()
+ assert result.dtype == "timedelta64[ns]"
+
+ result = df["A"] + td
+ assert result.dtype == "M8[ns]"
+
+ # scalar Timestamp on rhs
+ maxa = df["A"].max()
+ assert isinstance(maxa, Timestamp)
+
+ resultb = df["A"] - df["A"].max()
+ assert resultb.dtype == "timedelta64[ns]"
+
+ # timestamp on lhs
+ result = resultb + df["A"]
+ values = [Timestamp("20111230"), Timestamp("20120101"), Timestamp("20120103")]
+ expected = Series(values, name="A")
+ tm.assert_series_equal(result, expected)
+
+ # datetimes on rhs
+ result = df["A"] - datetime(2001, 1, 1)
+ expected = Series([timedelta(days=4017 + i) for i in range(3)], name="A")
+ tm.assert_series_equal(result, expected)
+ assert result.dtype == "m8[ns]"
+
+ d = datetime(2001, 1, 1, 3, 4)
+ resulta = df["A"] - d
+ assert resulta.dtype == "m8[ns]"
+
+ # roundtrip
+ resultb = resulta + d
+ tm.assert_series_equal(df["A"], resultb)
+
+ # timedeltas on rhs
+ td = timedelta(days=1)
+ resulta = df["A"] + td
+ resultb = resulta - td
+ tm.assert_series_equal(resultb, df["A"])
+ assert resultb.dtype == "M8[ns]"
+
+ # roundtrip
+ td = timedelta(minutes=5, seconds=3)
+ resulta = df["A"] + td
+ resultb = resulta - td
+ tm.assert_series_equal(df["A"], resultb)
+ assert resultb.dtype == "M8[ns]"
+
+ # inplace
+ value = rs[2] + np.timedelta64(timedelta(minutes=5, seconds=1))
+ rs[2] += np.timedelta64(timedelta(minutes=5, seconds=1))
+ assert rs[2] == value
+
+ def test_timedelta64_ops_nat(self):
+ # GH 11349
+ timedelta_series = Series([NaT, Timedelta("1s")])
+ nat_series_dtype_timedelta = Series([NaT, NaT], dtype="timedelta64[ns]")
+ single_nat_dtype_timedelta = Series([NaT], dtype="timedelta64[ns]")
+
+ # subtraction
+ tm.assert_series_equal(timedelta_series - NaT, nat_series_dtype_timedelta)
+ tm.assert_series_equal(-NaT + timedelta_series, nat_series_dtype_timedelta)
+
+ tm.assert_series_equal(
+ timedelta_series - single_nat_dtype_timedelta, nat_series_dtype_timedelta
+ )
+ tm.assert_series_equal(
+ -single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta
+ )
+
+ # addition
+ tm.assert_series_equal(
+ nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta
+ )
+ tm.assert_series_equal(
+ NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta
+ )
+
+ tm.assert_series_equal(
+ nat_series_dtype_timedelta + single_nat_dtype_timedelta,
+ nat_series_dtype_timedelta,
+ )
+ tm.assert_series_equal(
+ single_nat_dtype_timedelta + nat_series_dtype_timedelta,
+ nat_series_dtype_timedelta,
+ )
+
+ tm.assert_series_equal(timedelta_series + NaT, nat_series_dtype_timedelta)
+ tm.assert_series_equal(NaT + timedelta_series, nat_series_dtype_timedelta)
+
+ tm.assert_series_equal(
+ timedelta_series + single_nat_dtype_timedelta, nat_series_dtype_timedelta
+ )
+ tm.assert_series_equal(
+ single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta
+ )
+
+ tm.assert_series_equal(
+ nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta
+ )
+ tm.assert_series_equal(
+ NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta
+ )
+
+ tm.assert_series_equal(
+ nat_series_dtype_timedelta + single_nat_dtype_timedelta,
+ nat_series_dtype_timedelta,
+ )
+ tm.assert_series_equal(
+ single_nat_dtype_timedelta + nat_series_dtype_timedelta,
+ nat_series_dtype_timedelta,
+ )
+
+ # multiplication
+ tm.assert_series_equal(
+ nat_series_dtype_timedelta * 1.0, nat_series_dtype_timedelta
+ )
+ tm.assert_series_equal(
+ 1.0 * nat_series_dtype_timedelta, nat_series_dtype_timedelta
+ )
+
+ tm.assert_series_equal(timedelta_series * 1, timedelta_series)
+ tm.assert_series_equal(1 * timedelta_series, timedelta_series)
+
+ tm.assert_series_equal(timedelta_series * 1.5, Series([NaT, Timedelta("1.5s")]))
+ tm.assert_series_equal(1.5 * timedelta_series, Series([NaT, Timedelta("1.5s")]))
+
+ tm.assert_series_equal(timedelta_series * np.nan, nat_series_dtype_timedelta)
+ tm.assert_series_equal(np.nan * timedelta_series, nat_series_dtype_timedelta)
+
+ # division
+ tm.assert_series_equal(timedelta_series / 2, Series([NaT, Timedelta("0.5s")]))
+ tm.assert_series_equal(timedelta_series / 2.0, Series([NaT, Timedelta("0.5s")]))
+ tm.assert_series_equal(timedelta_series / np.nan, nat_series_dtype_timedelta)
+
+ # -------------------------------------------------------------
+ # Binary operations td64 arraylike and datetime-like
+
+ @pytest.mark.parametrize("cls", [Timestamp, datetime, np.datetime64])
+ def test_td64arr_add_sub_datetimelike_scalar(
+ self, cls, box_with_array, tz_naive_fixture
+ ):
+ # GH#11925, GH#29558, GH#23215
+ tz = tz_naive_fixture
+
+ dt_scalar = Timestamp("2012-01-01", tz=tz)
+ if cls is datetime:
+ ts = dt_scalar.to_pydatetime()
+ elif cls is np.datetime64:
+ if tz_naive_fixture is not None:
+ pytest.skip(f"{cls} doesn support {tz_naive_fixture}")
+ ts = dt_scalar.to_datetime64()
+ else:
+ ts = dt_scalar
+
+ tdi = timedelta_range("1 day", periods=3)
+ expected = pd.date_range("2012-01-02", periods=3, tz=tz)
+
+ tdarr = tm.box_expected(tdi, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ tm.assert_equal(ts + tdarr, expected)
+ tm.assert_equal(tdarr + ts, expected)
+
+ expected2 = pd.date_range("2011-12-31", periods=3, freq="-1D", tz=tz)
+ expected2 = tm.box_expected(expected2, box_with_array)
+
+ tm.assert_equal(ts - tdarr, expected2)
+ tm.assert_equal(ts + (-tdarr), expected2)
+
+ msg = "cannot subtract a datelike"
+ with pytest.raises(TypeError, match=msg):
+ tdarr - ts
+
+ def test_td64arr_add_datetime64_nat(self, box_with_array):
+ # GH#23215
+ other = np.datetime64("NaT")
+
+ tdi = timedelta_range("1 day", periods=3)
+ expected = DatetimeIndex(["NaT", "NaT", "NaT"])
+
+ tdser = tm.box_expected(tdi, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ tm.assert_equal(tdser + other, expected)
+ tm.assert_equal(other + tdser, expected)
+
+ def test_td64arr_sub_dt64_array(self, box_with_array):
+ dti = pd.date_range("2016-01-01", periods=3)
+ tdi = TimedeltaIndex(["-1 Day"] * 3)
+ dtarr = dti.values
+ expected = DatetimeIndex(dtarr) - tdi
+
+ tdi = tm.box_expected(tdi, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ msg = "cannot subtract a datelike from"
+ with pytest.raises(TypeError, match=msg):
+ tdi - dtarr
+
+ # TimedeltaIndex.__rsub__
+ result = dtarr - tdi
+ tm.assert_equal(result, expected)
+
+ def test_td64arr_add_dt64_array(self, box_with_array):
+ dti = pd.date_range("2016-01-01", periods=3)
+ tdi = TimedeltaIndex(["-1 Day"] * 3)
+ dtarr = dti.values
+ expected = DatetimeIndex(dtarr) + tdi
+
+ tdi = tm.box_expected(tdi, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = tdi + dtarr
+ tm.assert_equal(result, expected)
+ result = dtarr + tdi
+ tm.assert_equal(result, expected)
+
+ # ------------------------------------------------------------------
+ # Invalid __add__/__sub__ operations
+
+ @pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "H"])
+ @pytest.mark.parametrize("tdi_freq", [None, "H"])
+ def test_td64arr_sub_periodlike(
+ self, box_with_array, box_with_array2, tdi_freq, pi_freq
+ ):
+ # GH#20049 subtracting PeriodIndex should raise TypeError
+ tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq)
+ dti = Timestamp("2018-03-07 17:16:40") + tdi
+ pi = dti.to_period(pi_freq)
+ per = pi[0]
+
+ tdi = tm.box_expected(tdi, box_with_array)
+ pi = tm.box_expected(pi, box_with_array2)
+ msg = "cannot subtract|unsupported operand type"
+ with pytest.raises(TypeError, match=msg):
+ tdi - pi
+
+ # GH#13078 subtraction of Period scalar not supported
+ with pytest.raises(TypeError, match=msg):
+ tdi - per
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ # GH#12624 for str case
+ "a",
+ # GH#19123
+ 1,
+ 1.5,
+ np.array(2),
+ ],
+ )
+ def test_td64arr_addsub_numeric_scalar_invalid(self, box_with_array, other):
+ # vector-like others are tested in test_td64arr_add_sub_numeric_arr_invalid
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
+ tdarr = tm.box_expected(tdser, box_with_array)
+
+ assert_invalid_addsub_type(tdarr, other)
+
+ @pytest.mark.parametrize(
+ "vec",
+ [
+ np.array([1, 2, 3]),
+ Index([1, 2, 3]),
+ Series([1, 2, 3]),
+ DataFrame([[1, 2, 3]]),
+ ],
+ ids=lambda x: type(x).__name__,
+ )
+ def test_td64arr_addsub_numeric_arr_invalid(
+ self, box_with_array, vec, any_real_numpy_dtype
+ ):
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
+ tdarr = tm.box_expected(tdser, box_with_array)
+
+ vector = vec.astype(any_real_numpy_dtype)
+ assert_invalid_addsub_type(tdarr, vector)
+
+ def test_td64arr_add_sub_int(self, box_with_array, one):
+ # Variants of `one` for #19012, deprecated GH#22535
+ rng = timedelta_range("1 days 09:00:00", freq="H", periods=10)
+ tdarr = tm.box_expected(rng, box_with_array)
+
+ msg = "Addition/subtraction of integers"
+ assert_invalid_addsub_type(tdarr, one, msg)
+
+ # TODO: get inplace ops into assert_invalid_addsub_type
+ with pytest.raises(TypeError, match=msg):
+ tdarr += one
+ with pytest.raises(TypeError, match=msg):
+ tdarr -= one
+
+ def test_td64arr_add_sub_integer_array(self, box_with_array):
+ # GH#19959, deprecated GH#22535
+ # GH#22696 for DataFrame case, check that we don't dispatch to numpy
+ # implementation, which treats int64 as m8[ns]
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+
+ rng = timedelta_range("1 days 09:00:00", freq="H", periods=3)
+ tdarr = tm.box_expected(rng, box)
+ other = tm.box_expected([4, 3, 2], xbox)
+
+ msg = "Addition/subtraction of integers and integer-arrays"
+ assert_invalid_addsub_type(tdarr, other, msg)
+
+ def test_td64arr_addsub_integer_array_no_freq(self, box_with_array):
+ # GH#19959
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+
+ tdi = TimedeltaIndex(["1 Day", "NaT", "3 Hours"])
+ tdarr = tm.box_expected(tdi, box)
+ other = tm.box_expected([14, -1, 16], xbox)
+
+ msg = "Addition/subtraction of integers"
+ assert_invalid_addsub_type(tdarr, other, msg)
+
+ # ------------------------------------------------------------------
+ # Operations with timedelta-like others
+
+ def test_td64arr_add_sub_td64_array(self, box_with_array):
+ box = box_with_array
+ dti = pd.date_range("2016-01-01", periods=3)
+ tdi = dti - dti.shift(1)
+ tdarr = tdi.values
+
+ expected = 2 * tdi
+ tdi = tm.box_expected(tdi, box)
+ expected = tm.box_expected(expected, box)
+
+ result = tdi + tdarr
+ tm.assert_equal(result, expected)
+ result = tdarr + tdi
+ tm.assert_equal(result, expected)
+
+ expected_sub = 0 * tdi
+ result = tdi - tdarr
+ tm.assert_equal(result, expected_sub)
+ result = tdarr - tdi
+ tm.assert_equal(result, expected_sub)
+
+ def test_td64arr_add_sub_tdi(self, box_with_array, names):
+ # GH#17250 make sure result dtype is correct
+ # GH#19043 make sure names are propagated correctly
+ box = box_with_array
+ exname = get_expected_name(box, names)
+
+ tdi = TimedeltaIndex(["0 days", "1 day"], name=names[1])
+ tdi = np.array(tdi) if box in [tm.to_array, pd.array] else tdi
+ ser = Series([Timedelta(hours=3), Timedelta(hours=4)], name=names[0])
+ expected = Series([Timedelta(hours=3), Timedelta(days=1, hours=4)], name=exname)
+
+ ser = tm.box_expected(ser, box)
+ expected = tm.box_expected(expected, box)
+
+ result = tdi + ser
+ tm.assert_equal(result, expected)
+ assert_dtype(result, "timedelta64[ns]")
+
+ result = ser + tdi
+ tm.assert_equal(result, expected)
+ assert_dtype(result, "timedelta64[ns]")
+
+ expected = Series(
+ [Timedelta(hours=-3), Timedelta(days=1, hours=-4)], name=exname
+ )
+ expected = tm.box_expected(expected, box)
+
+ result = tdi - ser
+ tm.assert_equal(result, expected)
+ assert_dtype(result, "timedelta64[ns]")
+
+ result = ser - tdi
+ tm.assert_equal(result, -expected)
+ assert_dtype(result, "timedelta64[ns]")
+
+ @pytest.mark.parametrize("tdnat", [np.timedelta64("NaT"), NaT])
+ def test_td64arr_add_sub_td64_nat(self, box_with_array, tdnat):
+ # GH#18808, GH#23320 special handling for timedelta64("NaT")
+ box = box_with_array
+ tdi = TimedeltaIndex([NaT, Timedelta("1s")])
+ expected = TimedeltaIndex(["NaT"] * 2)
+
+ obj = tm.box_expected(tdi, box)
+ expected = tm.box_expected(expected, box)
+
+ result = obj + tdnat
+ tm.assert_equal(result, expected)
+ result = tdnat + obj
+ tm.assert_equal(result, expected)
+ result = obj - tdnat
+ tm.assert_equal(result, expected)
+ result = tdnat - obj
+ tm.assert_equal(result, expected)
+
+ def test_td64arr_add_timedeltalike(self, two_hours, box_with_array):
+ # only test adding/sub offsets as + is now numeric
+ # GH#10699 for Tick cases
+ box = box_with_array
+ rng = timedelta_range("1 days", "10 days")
+ expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D")
+ rng = tm.box_expected(rng, box)
+ expected = tm.box_expected(expected, box)
+
+ result = rng + two_hours
+ tm.assert_equal(result, expected)
+
+ result = two_hours + rng
+ tm.assert_equal(result, expected)
+
+ def test_td64arr_sub_timedeltalike(self, two_hours, box_with_array):
+ # only test adding/sub offsets as - is now numeric
+ # GH#10699 for Tick cases
+ box = box_with_array
+ rng = timedelta_range("1 days", "10 days")
+ expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00")
+
+ rng = tm.box_expected(rng, box)
+ expected = tm.box_expected(expected, box)
+
+ result = rng - two_hours
+ tm.assert_equal(result, expected)
+
+ result = two_hours - rng
+ tm.assert_equal(result, -expected)
+
+ # ------------------------------------------------------------------
+ # __add__/__sub__ with DateOffsets and arrays of DateOffsets
+
+ def test_td64arr_add_sub_offset_index(self, names, box_with_array):
+ # GH#18849, GH#19744
+ box = box_with_array
+ exname = get_expected_name(box, names)
+
+ tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0])
+ other = Index([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1])
+ other = np.array(other) if box in [tm.to_array, pd.array] else other
+
+ expected = TimedeltaIndex(
+ [tdi[n] + other[n] for n in range(len(tdi))], freq="infer", name=exname
+ )
+ expected_sub = TimedeltaIndex(
+ [tdi[n] - other[n] for n in range(len(tdi))], freq="infer", name=exname
+ )
+
+ tdi = tm.box_expected(tdi, box)
+ expected = tm.box_expected(expected, box).astype(object, copy=False)
+ expected_sub = tm.box_expected(expected_sub, box).astype(object, copy=False)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res = tdi + other
+ tm.assert_equal(res, expected)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res2 = other + tdi
+ tm.assert_equal(res2, expected)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res_sub = tdi - other
+ tm.assert_equal(res_sub, expected_sub)
+
+ def test_td64arr_add_sub_offset_array(self, box_with_array):
+ # GH#18849, GH#18824
+ box = box_with_array
+ tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"])
+ other = np.array([offsets.Hour(n=1), offsets.Minute(n=-2)])
+
+ expected = TimedeltaIndex(
+ [tdi[n] + other[n] for n in range(len(tdi))], freq="infer"
+ )
+ expected_sub = TimedeltaIndex(
+ [tdi[n] - other[n] for n in range(len(tdi))], freq="infer"
+ )
+
+ tdi = tm.box_expected(tdi, box)
+ expected = tm.box_expected(expected, box).astype(object)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res = tdi + other
+ tm.assert_equal(res, expected)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res2 = other + tdi
+ tm.assert_equal(res2, expected)
+
+ expected_sub = tm.box_expected(expected_sub, box_with_array).astype(object)
+ with tm.assert_produces_warning(PerformanceWarning):
+ res_sub = tdi - other
+ tm.assert_equal(res_sub, expected_sub)
+
+ def test_td64arr_with_offset_series(self, names, box_with_array):
+ # GH#18849
+ box = box_with_array
+ box2 = Series if box in [Index, tm.to_array, pd.array] else box
+ exname = get_expected_name(box, names)
+
+ tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0])
+ other = Series([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1])
+
+ expected_add = Series(
+ [tdi[n] + other[n] for n in range(len(tdi))], name=exname, dtype=object
+ )
+ obj = tm.box_expected(tdi, box)
+ expected_add = tm.box_expected(expected_add, box2).astype(object)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res = obj + other
+ tm.assert_equal(res, expected_add)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res2 = other + obj
+ tm.assert_equal(res2, expected_add)
+
+ expected_sub = Series(
+ [tdi[n] - other[n] for n in range(len(tdi))], name=exname, dtype=object
+ )
+ expected_sub = tm.box_expected(expected_sub, box2).astype(object)
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ res3 = obj - other
+ tm.assert_equal(res3, expected_sub)
+
+ @pytest.mark.parametrize("obox", [np.array, Index, Series])
+ def test_td64arr_addsub_anchored_offset_arraylike(self, obox, box_with_array):
+ # GH#18824
+ tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"])
+ tdi = tm.box_expected(tdi, box_with_array)
+
+ anchored = obox([offsets.MonthEnd(), offsets.Day(n=2)])
+
+ # addition/subtraction ops with anchored offsets should issue
+ # a PerformanceWarning and _then_ raise a TypeError.
+ msg = "has incorrect type|cannot add the type MonthEnd"
+ with pytest.raises(TypeError, match=msg):
+ with tm.assert_produces_warning(PerformanceWarning):
+ tdi + anchored
+ with pytest.raises(TypeError, match=msg):
+ with tm.assert_produces_warning(PerformanceWarning):
+ anchored + tdi
+ with pytest.raises(TypeError, match=msg):
+ with tm.assert_produces_warning(PerformanceWarning):
+ tdi - anchored
+ with pytest.raises(TypeError, match=msg):
+ with tm.assert_produces_warning(PerformanceWarning):
+ anchored - tdi
+
+ # ------------------------------------------------------------------
+ # Unsorted
+
+ def test_td64arr_add_sub_object_array(self, box_with_array):
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+
+ tdi = timedelta_range("1 day", periods=3, freq="D")
+ tdarr = tm.box_expected(tdi, box)
+
+ other = np.array([Timedelta(days=1), offsets.Day(2), Timestamp("2000-01-04")])
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = tdarr + other
+
+ expected = Index(
+ [Timedelta(days=2), Timedelta(days=4), Timestamp("2000-01-07")]
+ )
+ expected = tm.box_expected(expected, xbox).astype(object)
+ tm.assert_equal(result, expected)
+
+ msg = "unsupported operand type|cannot subtract a datelike"
+ with pytest.raises(TypeError, match=msg):
+ with tm.assert_produces_warning(PerformanceWarning):
+ tdarr - other
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = other - tdarr
+
+ expected = Index([Timedelta(0), Timedelta(0), Timestamp("2000-01-01")])
+ expected = tm.box_expected(expected, xbox).astype(object)
+ tm.assert_equal(result, expected)
+
+
+class TestTimedeltaArraylikeMulDivOps:
+ # Tests for timedelta64[ns]
+ # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__
+
+ # ------------------------------------------------------------------
+ # Multiplication
+ # organized with scalar others first, then array-like
+
+ def test_td64arr_mul_int(self, box_with_array):
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
+ idx = tm.box_expected(idx, box_with_array)
+
+ result = idx * 1
+ tm.assert_equal(result, idx)
+
+ result = 1 * idx
+ tm.assert_equal(result, idx)
+
+ def test_td64arr_mul_tdlike_scalar_raises(self, two_hours, box_with_array):
+ rng = timedelta_range("1 days", "10 days", name="foo")
+ rng = tm.box_expected(rng, box_with_array)
+ msg = "argument must be an integer|cannot use operands with types dtype"
+ with pytest.raises(TypeError, match=msg):
+ rng * two_hours
+
+ def test_tdi_mul_int_array_zerodim(self, box_with_array):
+ rng5 = np.arange(5, dtype="int64")
+ idx = TimedeltaIndex(rng5)
+ expected = TimedeltaIndex(rng5 * 5)
+
+ idx = tm.box_expected(idx, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = idx * np.array(5, dtype="int64")
+ tm.assert_equal(result, expected)
+
+ def test_tdi_mul_int_array(self, box_with_array):
+ rng5 = np.arange(5, dtype="int64")
+ idx = TimedeltaIndex(rng5)
+ expected = TimedeltaIndex(rng5**2)
+
+ idx = tm.box_expected(idx, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = idx * rng5
+ tm.assert_equal(result, expected)
+
+ def test_tdi_mul_int_series(self, box_with_array):
+ box = box_with_array
+ xbox = Series if box in [Index, tm.to_array, pd.array] else box
+
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
+ expected = TimedeltaIndex(np.arange(5, dtype="int64") ** 2)
+
+ idx = tm.box_expected(idx, box)
+ expected = tm.box_expected(expected, xbox)
+
+ result = idx * Series(np.arange(5, dtype="int64"))
+ tm.assert_equal(result, expected)
+
+ def test_tdi_mul_float_series(self, box_with_array):
+ box = box_with_array
+ xbox = Series if box in [Index, tm.to_array, pd.array] else box
+
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
+ idx = tm.box_expected(idx, box)
+
+ rng5f = np.arange(5, dtype="float64")
+ expected = TimedeltaIndex(rng5f * (rng5f + 1.0))
+ expected = tm.box_expected(expected, xbox)
+
+ result = idx * Series(rng5f + 1.0)
+ tm.assert_equal(result, expected)
+
+ # TODO: Put Series/DataFrame in others?
+ @pytest.mark.parametrize(
+ "other",
+ [
+ np.arange(1, 11),
+ Index(np.arange(1, 11), np.int64),
+ Index(range(1, 11), np.uint64),
+ Index(range(1, 11), np.float64),
+ pd.RangeIndex(1, 11),
+ ],
+ ids=lambda x: type(x).__name__,
+ )
+ def test_tdi_rmul_arraylike(self, other, box_with_array):
+ box = box_with_array
+
+ tdi = TimedeltaIndex(["1 Day"] * 10)
+ expected = timedelta_range("1 days", "10 days")._with_freq(None)
+
+ tdi = tm.box_expected(tdi, box)
+ xbox = get_upcast_box(tdi, other)
+
+ expected = tm.box_expected(expected, xbox)
+
+ result = other * tdi
+ tm.assert_equal(result, expected)
+ commute = tdi * other
+ tm.assert_equal(commute, expected)
+
+ # ------------------------------------------------------------------
+ # __div__, __rdiv__
+
+ def test_td64arr_div_nat_invalid(self, box_with_array):
+ # don't allow division by NaT (maybe could in the future)
+ rng = timedelta_range("1 days", "10 days", name="foo")
+ rng = tm.box_expected(rng, box_with_array)
+
+ with pytest.raises(TypeError, match="unsupported operand type"):
+ rng / NaT
+ with pytest.raises(TypeError, match="Cannot divide NaTType by"):
+ NaT / rng
+
+ dt64nat = np.datetime64("NaT", "ns")
+ msg = "|".join(
+ [
+ # 'divide' on npdev as of 2021-12-18
+ "ufunc '(true_divide|divide)' cannot use operands",
+ "cannot perform __r?truediv__",
+ "Cannot divide datetime64 by TimedeltaArray",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ rng / dt64nat
+ with pytest.raises(TypeError, match=msg):
+ dt64nat / rng
+
+ def test_td64arr_div_td64nat(self, box_with_array):
+ # GH#23829
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+
+ rng = timedelta_range("1 days", "10 days")
+ rng = tm.box_expected(rng, box)
+
+ other = np.timedelta64("NaT")
+
+ expected = np.array([np.nan] * 10)
+ expected = tm.box_expected(expected, xbox)
+
+ result = rng / other
+ tm.assert_equal(result, expected)
+
+ result = other / rng
+ tm.assert_equal(result, expected)
+
+ def test_td64arr_div_int(self, box_with_array):
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
+ idx = tm.box_expected(idx, box_with_array)
+
+ result = idx / 1
+ tm.assert_equal(result, idx)
+
+ with pytest.raises(TypeError, match="Cannot divide"):
+ # GH#23829
+ 1 / idx
+
+ def test_td64arr_div_tdlike_scalar(self, two_hours, box_with_array):
+ # GH#20088, GH#22163 ensure DataFrame returns correct dtype
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+
+ rng = timedelta_range("1 days", "10 days", name="foo")
+ expected = Index((np.arange(10) + 1) * 12, dtype=np.float64, name="foo")
+
+ rng = tm.box_expected(rng, box)
+ expected = tm.box_expected(expected, xbox)
+
+ result = rng / two_hours
+ tm.assert_equal(result, expected)
+
+ result = two_hours / rng
+ expected = 1 / expected
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("m", [1, 3, 10])
+ @pytest.mark.parametrize("unit", ["D", "h", "m", "s", "ms", "us", "ns"])
+ def test_td64arr_div_td64_scalar(self, m, unit, box_with_array):
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+
+ ser = Series([Timedelta(days=59)] * 3)
+ ser[2] = np.nan
+ flat = ser
+ ser = tm.box_expected(ser, box)
+
+ # op
+ expected = Series([x / np.timedelta64(m, unit) for x in flat])
+ expected = tm.box_expected(expected, xbox)
+ result = ser / np.timedelta64(m, unit)
+ tm.assert_equal(result, expected)
+
+ # reverse op
+ expected = Series([Timedelta(np.timedelta64(m, unit)) / x for x in flat])
+ expected = tm.box_expected(expected, xbox)
+ result = np.timedelta64(m, unit) / ser
+ tm.assert_equal(result, expected)
+
+ def test_td64arr_div_tdlike_scalar_with_nat(self, two_hours, box_with_array):
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+
+ rng = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
+ expected = Index([12, np.nan, 24], dtype=np.float64, name="foo")
+
+ rng = tm.box_expected(rng, box)
+ expected = tm.box_expected(expected, xbox)
+
+ result = rng / two_hours
+ tm.assert_equal(result, expected)
+
+ result = two_hours / rng
+ expected = 1 / expected
+ tm.assert_equal(result, expected)
+
+ def test_td64arr_div_td64_ndarray(self, box_with_array):
+ # GH#22631
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+
+ rng = TimedeltaIndex(["1 days", NaT, "2 days"])
+ expected = Index([12, np.nan, 24], dtype=np.float64)
+
+ rng = tm.box_expected(rng, box)
+ expected = tm.box_expected(expected, xbox)
+
+ other = np.array([2, 4, 2], dtype="m8[h]")
+ result = rng / other
+ tm.assert_equal(result, expected)
+
+ result = rng / tm.box_expected(other, box)
+ tm.assert_equal(result, expected)
+
+ result = rng / other.astype(object)
+ tm.assert_equal(result, expected.astype(object))
+
+ result = rng / list(other)
+ tm.assert_equal(result, expected)
+
+ # reversed op
+ expected = 1 / expected
+ result = other / rng
+ tm.assert_equal(result, expected)
+
+ result = tm.box_expected(other, box) / rng
+ tm.assert_equal(result, expected)
+
+ result = other.astype(object) / rng
+ tm.assert_equal(result, expected)
+
+ result = list(other) / rng
+ tm.assert_equal(result, expected)
+
+ def test_tdarr_div_length_mismatch(self, box_with_array):
+ rng = TimedeltaIndex(["1 days", NaT, "2 days"])
+ mismatched = [1, 2, 3, 4]
+
+ rng = tm.box_expected(rng, box_with_array)
+ msg = "Cannot divide vectors|Unable to coerce to Series"
+ for obj in [mismatched, mismatched[:2]]:
+ # one shorter, one longer
+ for other in [obj, np.array(obj), Index(obj)]:
+ with pytest.raises(ValueError, match=msg):
+ rng / other
+ with pytest.raises(ValueError, match=msg):
+ other / rng
+
+ def test_td64_div_object_mixed_result(self, box_with_array):
+ # Case where we having a NaT in the result inseat of timedelta64("NaT")
+ # is misleading
+ orig = timedelta_range("1 Day", periods=3).insert(1, NaT)
+ tdi = tm.box_expected(orig, box_with_array, transpose=False)
+
+ other = np.array([orig[0], 1.5, 2.0, orig[2]], dtype=object)
+ other = tm.box_expected(other, box_with_array, transpose=False)
+
+ res = tdi / other
+
+ expected = Index([1.0, np.timedelta64("NaT", "ns"), orig[0], 1.5], dtype=object)
+ expected = tm.box_expected(expected, box_with_array, transpose=False)
+ if isinstance(expected, NumpyExtensionArray):
+ expected = expected.to_numpy()
+ tm.assert_equal(res, expected)
+ if box_with_array is DataFrame:
+ # We have a np.timedelta64(NaT), not pd.NaT
+ assert isinstance(res.iloc[1, 0], np.timedelta64)
+
+ res = tdi // other
+
+ expected = Index([1, np.timedelta64("NaT", "ns"), orig[0], 1], dtype=object)
+ expected = tm.box_expected(expected, box_with_array, transpose=False)
+ if isinstance(expected, NumpyExtensionArray):
+ expected = expected.to_numpy()
+ tm.assert_equal(res, expected)
+ if box_with_array is DataFrame:
+ # We have a np.timedelta64(NaT), not pd.NaT
+ assert isinstance(res.iloc[1, 0], np.timedelta64)
+
+ # ------------------------------------------------------------------
+ # __floordiv__, __rfloordiv__
+
+ def test_td64arr_floordiv_td64arr_with_nat(
+ self, box_with_array, using_array_manager
+ ):
+ # GH#35529
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+
+ left = Series([1000, 222330, 30], dtype="timedelta64[ns]")
+ right = Series([1000, 222330, None], dtype="timedelta64[ns]")
+
+ left = tm.box_expected(left, box)
+ right = tm.box_expected(right, box)
+
+ expected = np.array([1.0, 1.0, np.nan], dtype=np.float64)
+ expected = tm.box_expected(expected, xbox)
+ if box is DataFrame and using_array_manager:
+ # INFO(ArrayManager) floordiv returns integer, and ArrayManager
+ # performs ops column-wise and thus preserves int64 dtype for
+ # columns without missing values
+ expected[[0, 1]] = expected[[0, 1]].astype("int64")
+
+ with tm.maybe_produces_warning(
+ RuntimeWarning, box is pd.array, check_stacklevel=False
+ ):
+ result = left // right
+
+ tm.assert_equal(result, expected)
+
+ # case that goes through __rfloordiv__ with arraylike
+ with tm.maybe_produces_warning(
+ RuntimeWarning, box is pd.array, check_stacklevel=False
+ ):
+ result = np.asarray(left) // right
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning")
+ def test_td64arr_floordiv_tdscalar(self, box_with_array, scalar_td):
+ # GH#18831, GH#19125
+ box = box_with_array
+ xbox = np.ndarray if box is pd.array else box
+ td = Timedelta("5m3s") # i.e. (scalar_td - 1sec) / 2
+
+ td1 = Series([td, td, NaT], dtype="m8[ns]")
+ td1 = tm.box_expected(td1, box, transpose=False)
+
+ expected = Series([0, 0, np.nan])
+ expected = tm.box_expected(expected, xbox, transpose=False)
+
+ result = td1 // scalar_td
+ tm.assert_equal(result, expected)
+
+ # Reversed op
+ expected = Series([2, 2, np.nan])
+ expected = tm.box_expected(expected, xbox, transpose=False)
+
+ result = scalar_td // td1
+ tm.assert_equal(result, expected)
+
+ # same thing buts let's be explicit about calling __rfloordiv__
+ result = td1.__rfloordiv__(scalar_td)
+ tm.assert_equal(result, expected)
+
+ def test_td64arr_floordiv_int(self, box_with_array):
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
+ idx = tm.box_expected(idx, box_with_array)
+ result = idx // 1
+ tm.assert_equal(result, idx)
+
+ pattern = "floor_divide cannot use operands|Cannot divide int by Timedelta*"
+ with pytest.raises(TypeError, match=pattern):
+ 1 // idx
+
+ # ------------------------------------------------------------------
+ # mod, divmod
+ # TODO: operations with timedelta-like arrays, numeric arrays,
+ # reversed ops
+
+ def test_td64arr_mod_tdscalar(self, box_with_array, three_days):
+ tdi = timedelta_range("1 Day", "9 days")
+ tdarr = tm.box_expected(tdi, box_with_array)
+
+ expected = TimedeltaIndex(["1 Day", "2 Days", "0 Days"] * 3)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = tdarr % three_days
+ tm.assert_equal(result, expected)
+
+ warn = None
+ if box_with_array is DataFrame and isinstance(three_days, pd.DateOffset):
+ warn = PerformanceWarning
+ # TODO: making expected be object here a result of DataFrame.__divmod__
+ # being defined in a naive way that does not dispatch to the underlying
+ # array's __divmod__
+ expected = expected.astype(object)
+
+ with tm.assert_produces_warning(warn):
+ result = divmod(tdarr, three_days)
+
+ tm.assert_equal(result[1], expected)
+ tm.assert_equal(result[0], tdarr // three_days)
+
+ def test_td64arr_mod_int(self, box_with_array):
+ tdi = timedelta_range("1 ns", "10 ns", periods=10)
+ tdarr = tm.box_expected(tdi, box_with_array)
+
+ expected = TimedeltaIndex(["1 ns", "0 ns"] * 5)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = tdarr % 2
+ tm.assert_equal(result, expected)
+
+ msg = "Cannot divide int by"
+ with pytest.raises(TypeError, match=msg):
+ 2 % tdarr
+
+ result = divmod(tdarr, 2)
+ tm.assert_equal(result[1], expected)
+ tm.assert_equal(result[0], tdarr // 2)
+
+ def test_td64arr_rmod_tdscalar(self, box_with_array, three_days):
+ tdi = timedelta_range("1 Day", "9 days")
+ tdarr = tm.box_expected(tdi, box_with_array)
+
+ expected = ["0 Days", "1 Day", "0 Days"] + ["3 Days"] * 6
+ expected = TimedeltaIndex(expected)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = three_days % tdarr
+ tm.assert_equal(result, expected)
+
+ result = divmod(three_days, tdarr)
+ tm.assert_equal(result[1], expected)
+ tm.assert_equal(result[0], three_days // tdarr)
+
+ # ------------------------------------------------------------------
+ # Operations with invalid others
+
+ def test_td64arr_mul_tdscalar_invalid(self, box_with_array, scalar_td):
+ td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
+ td1.iloc[2] = np.nan
+
+ td1 = tm.box_expected(td1, box_with_array)
+
+ # check that we are getting a TypeError
+ # with 'operate' (from core/ops.py) for the ops that are not
+ # defined
+ pattern = "operate|unsupported|cannot|not supported"
+ with pytest.raises(TypeError, match=pattern):
+ td1 * scalar_td
+ with pytest.raises(TypeError, match=pattern):
+ scalar_td * td1
+
+ def test_td64arr_mul_too_short_raises(self, box_with_array):
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
+ idx = tm.box_expected(idx, box_with_array)
+ msg = "|".join(
+ [
+ "cannot use operands with types dtype",
+ "Cannot multiply with unequal lengths",
+ "Unable to coerce to Series",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ # length check before dtype check
+ idx * idx[:3]
+ with pytest.raises(ValueError, match=msg):
+ idx * np.array([1, 2])
+
+ def test_td64arr_mul_td64arr_raises(self, box_with_array):
+ idx = TimedeltaIndex(np.arange(5, dtype="int64"))
+ idx = tm.box_expected(idx, box_with_array)
+ msg = "cannot use operands with types dtype"
+ with pytest.raises(TypeError, match=msg):
+ idx * idx
+
+ # ------------------------------------------------------------------
+ # Operations with numeric others
+
+ def test_td64arr_mul_numeric_scalar(self, box_with_array, one):
+ # GH#4521
+ # divide/multiply by integers
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
+ expected = Series(["-59 Days", "-59 Days", "NaT"], dtype="timedelta64[ns]")
+
+ tdser = tm.box_expected(tdser, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = tdser * (-one)
+ tm.assert_equal(result, expected)
+ result = (-one) * tdser
+ tm.assert_equal(result, expected)
+
+ expected = Series(["118 Days", "118 Days", "NaT"], dtype="timedelta64[ns]")
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = tdser * (2 * one)
+ tm.assert_equal(result, expected)
+ result = (2 * one) * tdser
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)])
+ def test_td64arr_div_numeric_scalar(self, box_with_array, two):
+ # GH#4521
+ # divide/multiply by integers
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
+ expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]")
+
+ tdser = tm.box_expected(tdser, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = tdser / two
+ tm.assert_equal(result, expected)
+
+ with pytest.raises(TypeError, match="Cannot divide"):
+ two / tdser
+
+ @pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)])
+ def test_td64arr_floordiv_numeric_scalar(self, box_with_array, two):
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
+ expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]")
+
+ tdser = tm.box_expected(tdser, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = tdser // two
+ tm.assert_equal(result, expected)
+
+ with pytest.raises(TypeError, match="Cannot divide"):
+ two // tdser
+
+ @pytest.mark.parametrize(
+ "vector",
+ [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
+ ids=lambda x: type(x).__name__,
+ )
+ def test_td64arr_rmul_numeric_array(
+ self,
+ box_with_array,
+ vector,
+ any_real_numpy_dtype,
+ ):
+ # GH#4521
+ # divide/multiply by integers
+
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
+ vector = vector.astype(any_real_numpy_dtype)
+
+ expected = Series(["1180 Days", "1770 Days", "NaT"], dtype="timedelta64[ns]")
+
+ tdser = tm.box_expected(tdser, box_with_array)
+ xbox = get_upcast_box(tdser, vector)
+
+ expected = tm.box_expected(expected, xbox)
+
+ result = tdser * vector
+ tm.assert_equal(result, expected)
+
+ result = vector * tdser
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "vector",
+ [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
+ ids=lambda x: type(x).__name__,
+ )
+ def test_td64arr_div_numeric_array(
+ self, box_with_array, vector, any_real_numpy_dtype
+ ):
+ # GH#4521
+ # divide/multiply by integers
+
+ tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
+ vector = vector.astype(any_real_numpy_dtype)
+
+ expected = Series(["2.95D", "1D 23H 12m", "NaT"], dtype="timedelta64[ns]")
+
+ tdser = tm.box_expected(tdser, box_with_array)
+ xbox = get_upcast_box(tdser, vector)
+ expected = tm.box_expected(expected, xbox)
+
+ result = tdser / vector
+ tm.assert_equal(result, expected)
+
+ pattern = "|".join(
+ [
+ "true_divide'? cannot use operands",
+ "cannot perform __div__",
+ "cannot perform __truediv__",
+ "unsupported operand",
+ "Cannot divide",
+ "ufunc 'divide' cannot use operands with types",
+ ]
+ )
+ with pytest.raises(TypeError, match=pattern):
+ vector / tdser
+
+ result = tdser / vector.astype(object)
+ if box_with_array is DataFrame:
+ expected = [tdser.iloc[0, n] / vector[n] for n in range(len(vector))]
+ expected = tm.box_expected(expected, xbox).astype(object)
+ # We specifically expect timedelta64("NaT") here, not pd.NA
+ msg = "The 'downcast' keyword in fillna"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected[2] = expected[2].fillna(
+ np.timedelta64("NaT", "ns"), downcast=False
+ )
+ else:
+ expected = [tdser[n] / vector[n] for n in range(len(tdser))]
+ expected = [
+ x if x is not NaT else np.timedelta64("NaT", "ns") for x in expected
+ ]
+ if xbox is tm.to_array:
+ expected = tm.to_array(expected).astype(object)
+ else:
+ expected = xbox(expected, dtype=object)
+
+ tm.assert_equal(result, expected)
+
+ with pytest.raises(TypeError, match=pattern):
+ vector.astype(object) / tdser
+
+ def test_td64arr_mul_int_series(self, box_with_array, names):
+ # GH#19042 test for correct name attachment
+ box = box_with_array
+ exname = get_expected_name(box, names)
+
+ tdi = TimedeltaIndex(
+ ["0days", "1day", "2days", "3days", "4days"], name=names[0]
+ )
+ # TODO: Should we be parametrizing over types for `ser` too?
+ ser = Series([0, 1, 2, 3, 4], dtype=np.int64, name=names[1])
+
+ expected = Series(
+ ["0days", "1day", "4days", "9days", "16days"],
+ dtype="timedelta64[ns]",
+ name=exname,
+ )
+
+ tdi = tm.box_expected(tdi, box)
+ xbox = get_upcast_box(tdi, ser)
+
+ expected = tm.box_expected(expected, xbox)
+
+ result = ser * tdi
+ tm.assert_equal(result, expected)
+
+ result = tdi * ser
+ tm.assert_equal(result, expected)
+
+ # TODO: Should we be parametrizing over types for `ser` too?
+ def test_float_series_rdiv_td64arr(self, box_with_array, names):
+ # GH#19042 test for correct name attachment
+ box = box_with_array
+ tdi = TimedeltaIndex(
+ ["0days", "1day", "2days", "3days", "4days"], name=names[0]
+ )
+ ser = Series([1.5, 3, 4.5, 6, 7.5], dtype=np.float64, name=names[1])
+
+ xname = names[2] if box not in [tm.to_array, pd.array] else names[1]
+ expected = Series(
+ [tdi[n] / ser[n] for n in range(len(ser))],
+ dtype="timedelta64[ns]",
+ name=xname,
+ )
+
+ tdi = tm.box_expected(tdi, box)
+ xbox = get_upcast_box(tdi, ser)
+ expected = tm.box_expected(expected, xbox)
+
+ result = ser.__rtruediv__(tdi)
+ if box is DataFrame:
+ assert result is NotImplemented
+ else:
+ tm.assert_equal(result, expected)
+
+ def test_td64arr_all_nat_div_object_dtype_numeric(self, box_with_array):
+ # GH#39750 make sure we infer the result as td64
+ tdi = TimedeltaIndex([NaT, NaT])
+
+ left = tm.box_expected(tdi, box_with_array)
+ right = np.array([2, 2.0], dtype=object)
+
+ tdnat = np.timedelta64("NaT", "ns")
+ expected = Index([tdnat] * 2, dtype=object)
+ if box_with_array is not Index:
+ expected = tm.box_expected(expected, box_with_array).astype(object)
+ if box_with_array in [Series, DataFrame]:
+ msg = "The 'downcast' keyword in fillna is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = expected.fillna(tdnat, downcast=False) # GH#18463
+
+ result = left / right
+ tm.assert_equal(result, expected)
+
+ result = left // right
+ tm.assert_equal(result, expected)
+
+
+class TestTimedelta64ArrayLikeArithmetic:
+ # Arithmetic tests for timedelta64[ns] vectors fully parametrized over
+ # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all arithmetic
+ # tests will eventually end up here.
+
+ def test_td64arr_pow_invalid(self, scalar_td, box_with_array):
+ td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
+ td1.iloc[2] = np.nan
+
+ td1 = tm.box_expected(td1, box_with_array)
+
+ # check that we are getting a TypeError
+ # with 'operate' (from core/ops.py) for the ops that are not
+ # defined
+ pattern = "operate|unsupported|cannot|not supported"
+ with pytest.raises(TypeError, match=pattern):
+ scalar_td**td1
+
+ with pytest.raises(TypeError, match=pattern):
+ td1**scalar_td
+
+
+def test_add_timestamp_to_timedelta():
+ # GH: 35897
+ timestamp = Timestamp("2021-01-01")
+ result = timestamp + timedelta_range("0s", "1s", periods=31)
+ expected = DatetimeIndex(
+ [
+ timestamp
+ + (
+ pd.to_timedelta("0.033333333s") * i
+ + pd.to_timedelta("0.000000001s") * divmod(i, 3)[0]
+ )
+ for i in range(31)
+ ]
+ )
+ tm.assert_index_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/masked_shared.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/masked_shared.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e74402263cf9c119ec344c5da48dd8598970f69
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/masked_shared.py
@@ -0,0 +1,154 @@
+"""
+Tests shared by MaskedArray subclasses.
+"""
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.tests.extension.base import BaseOpsUtil
+
+
+class ComparisonOps(BaseOpsUtil):
+ def _compare_other(self, data, op, other):
+ # array
+ result = pd.Series(op(data, other))
+ expected = pd.Series(op(data._data, other), dtype="boolean")
+
+ # fill the nan locations
+ expected[data._mask] = pd.NA
+
+ tm.assert_series_equal(result, expected)
+
+ # series
+ ser = pd.Series(data)
+ result = op(ser, other)
+
+ # Set nullable dtype here to avoid upcasting when setting to pd.NA below
+ expected = op(pd.Series(data._data), other).astype("boolean")
+
+ # fill the nan locations
+ expected[data._mask] = pd.NA
+
+ tm.assert_series_equal(result, expected)
+
+ # subclass will override to parametrize 'other'
+ def test_scalar(self, other, comparison_op, dtype):
+ op = comparison_op
+ left = pd.array([1, 0, None], dtype=dtype)
+
+ result = op(left, other)
+
+ if other is pd.NA:
+ expected = pd.array([None, None, None], dtype="boolean")
+ else:
+ values = op(left._data, other)
+ expected = pd.arrays.BooleanArray(values, left._mask, copy=True)
+ tm.assert_extension_array_equal(result, expected)
+
+ # ensure we haven't mutated anything inplace
+ result[0] = pd.NA
+ tm.assert_extension_array_equal(left, pd.array([1, 0, None], dtype=dtype))
+
+
+class NumericOps:
+ # Shared by IntegerArray and FloatingArray, not BooleanArray
+
+ def test_searchsorted_nan(self, dtype):
+ # The base class casts to object dtype, for which searchsorted returns
+ # 0 from the left and 10 from the right.
+ arr = pd.array(range(10), dtype=dtype)
+
+ assert arr.searchsorted(np.nan, side="left") == 10
+ assert arr.searchsorted(np.nan, side="right") == 10
+
+ def test_no_shared_mask(self, data):
+ result = data + 1
+ assert not tm.shares_memory(result, data)
+
+ def test_array(self, comparison_op, dtype):
+ op = comparison_op
+
+ left = pd.array([0, 1, 2, None, None, None], dtype=dtype)
+ right = pd.array([0, 1, None, 0, 1, None], dtype=dtype)
+
+ result = op(left, right)
+ values = op(left._data, right._data)
+ mask = left._mask | right._mask
+
+ expected = pd.arrays.BooleanArray(values, mask)
+ tm.assert_extension_array_equal(result, expected)
+
+ # ensure we haven't mutated anything inplace
+ result[0] = pd.NA
+ tm.assert_extension_array_equal(
+ left, pd.array([0, 1, 2, None, None, None], dtype=dtype)
+ )
+ tm.assert_extension_array_equal(
+ right, pd.array([0, 1, None, 0, 1, None], dtype=dtype)
+ )
+
+ def test_compare_with_booleanarray(self, comparison_op, dtype):
+ op = comparison_op
+
+ left = pd.array([True, False, None] * 3, dtype="boolean")
+ right = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype=dtype)
+ other = pd.array([False] * 3 + [True] * 3 + [None] * 3, dtype="boolean")
+
+ expected = op(left, other)
+ result = op(left, right)
+ tm.assert_extension_array_equal(result, expected)
+
+ # reversed op
+ expected = op(other, left)
+ result = op(right, left)
+ tm.assert_extension_array_equal(result, expected)
+
+ def test_compare_to_string(self, dtype):
+ # GH#28930
+ ser = pd.Series([1, None], dtype=dtype)
+ result = ser == "a"
+ expected = pd.Series([False, pd.NA], dtype="boolean")
+
+ tm.assert_series_equal(result, expected)
+
+ def test_ufunc_with_out(self, dtype):
+ arr = pd.array([1, 2, 3], dtype=dtype)
+ arr2 = pd.array([1, 2, pd.NA], dtype=dtype)
+
+ mask = arr == arr
+ mask2 = arr2 == arr2
+
+ result = np.zeros(3, dtype=bool)
+ result |= mask
+ # If MaskedArray.__array_ufunc__ handled "out" appropriately,
+ # `result` should still be an ndarray.
+ assert isinstance(result, np.ndarray)
+ assert result.all()
+
+ # result |= mask worked because mask could be cast losslessly to
+ # boolean ndarray. mask2 can't, so this raises
+ result = np.zeros(3, dtype=bool)
+ msg = "Specify an appropriate 'na_value' for this dtype"
+ with pytest.raises(ValueError, match=msg):
+ result |= mask2
+
+ # addition
+ res = np.add(arr, arr2)
+ expected = pd.array([2, 4, pd.NA], dtype=dtype)
+ tm.assert_extension_array_equal(res, expected)
+
+ # when passing out=arr, we will modify 'arr' inplace.
+ res = np.add(arr, arr2, out=arr)
+ assert res is arr
+ tm.assert_extension_array_equal(res, expected)
+ tm.assert_extension_array_equal(arr, expected)
+
+ def test_mul_td64_array(self, dtype):
+ # GH#45622
+ arr = pd.array([1, 2, pd.NA], dtype=dtype)
+ other = np.arange(3, dtype=np.int64).view("m8[ns]")
+
+ result = arr * other
+ expected = pd.array([pd.Timedelta(0), pd.Timedelta(2), pd.NaT])
+ tm.assert_extension_array_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_array.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..2746cd91963a0087f23902a601667e49a3f8b0be
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_array.py
@@ -0,0 +1,446 @@
+import datetime
+import decimal
+import re
+
+import numpy as np
+import pytest
+import pytz
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.api.extensions import register_extension_dtype
+from pandas.arrays import (
+ BooleanArray,
+ DatetimeArray,
+ FloatingArray,
+ IntegerArray,
+ IntervalArray,
+ SparseArray,
+ TimedeltaArray,
+)
+from pandas.core.arrays import (
+ NumpyExtensionArray,
+ period_array,
+)
+from pandas.tests.extension.decimal import (
+ DecimalArray,
+ DecimalDtype,
+ to_decimal,
+)
+
+
+@pytest.mark.parametrize("dtype_unit", ["M8[h]", "M8[m]", "m8[h]", "M8[m]"])
+def test_dt64_array(dtype_unit):
+ # PR 53817
+ dtype_var = np.dtype(dtype_unit)
+ msg = (
+ r"datetime64 and timedelta64 dtype resolutions other than "
+ r"'s', 'ms', 'us', and 'ns' are deprecated. "
+ r"In future releases passing unsupported resolutions will "
+ r"raise an exception."
+ )
+ with tm.assert_produces_warning(FutureWarning, match=re.escape(msg)):
+ pd.array([], dtype=dtype_var)
+
+
+@pytest.mark.parametrize(
+ "data, dtype, expected",
+ [
+ # Basic NumPy defaults.
+ ([], None, FloatingArray._from_sequence([])),
+ ([1, 2], None, IntegerArray._from_sequence([1, 2])),
+ ([1, 2], object, NumpyExtensionArray(np.array([1, 2], dtype=object))),
+ (
+ [1, 2],
+ np.dtype("float32"),
+ NumpyExtensionArray(np.array([1.0, 2.0], dtype=np.dtype("float32"))),
+ ),
+ (
+ np.array([], dtype=object),
+ None,
+ NumpyExtensionArray(np.array([], dtype=object)),
+ ),
+ (np.array([1, 2], dtype="int64"), None, IntegerArray._from_sequence([1, 2])),
+ (
+ np.array([1.0, 2.0], dtype="float64"),
+ None,
+ FloatingArray._from_sequence([1.0, 2.0]),
+ ),
+ # String alias passes through to NumPy
+ ([1, 2], "float32", NumpyExtensionArray(np.array([1, 2], dtype="float32"))),
+ ([1, 2], "int64", NumpyExtensionArray(np.array([1, 2], dtype=np.int64))),
+ # GH#44715 FloatingArray does not support float16, so fall
+ # back to NumpyExtensionArray
+ (
+ np.array([1, 2], dtype=np.float16),
+ None,
+ NumpyExtensionArray(np.array([1, 2], dtype=np.float16)),
+ ),
+ # idempotency with e.g. pd.array(pd.array([1, 2], dtype="int64"))
+ (
+ NumpyExtensionArray(np.array([1, 2], dtype=np.int32)),
+ None,
+ NumpyExtensionArray(np.array([1, 2], dtype=np.int32)),
+ ),
+ # Period alias
+ (
+ [pd.Period("2000", "D"), pd.Period("2001", "D")],
+ "Period[D]",
+ period_array(["2000", "2001"], freq="D"),
+ ),
+ # Period dtype
+ (
+ [pd.Period("2000", "D")],
+ pd.PeriodDtype("D"),
+ period_array(["2000"], freq="D"),
+ ),
+ # Datetime (naive)
+ (
+ [1, 2],
+ np.dtype("datetime64[ns]"),
+ DatetimeArray._from_sequence(np.array([1, 2], dtype="datetime64[ns]")),
+ ),
+ (
+ [1, 2],
+ np.dtype("datetime64[s]"),
+ DatetimeArray._from_sequence(np.array([1, 2], dtype="datetime64[s]")),
+ ),
+ (
+ np.array([1, 2], dtype="datetime64[ns]"),
+ None,
+ DatetimeArray._from_sequence(np.array([1, 2], dtype="datetime64[ns]")),
+ ),
+ (
+ pd.DatetimeIndex(["2000", "2001"]),
+ np.dtype("datetime64[ns]"),
+ DatetimeArray._from_sequence(["2000", "2001"]),
+ ),
+ (
+ pd.DatetimeIndex(["2000", "2001"]),
+ None,
+ DatetimeArray._from_sequence(["2000", "2001"]),
+ ),
+ (
+ ["2000", "2001"],
+ np.dtype("datetime64[ns]"),
+ DatetimeArray._from_sequence(["2000", "2001"]),
+ ),
+ # Datetime (tz-aware)
+ (
+ ["2000", "2001"],
+ pd.DatetimeTZDtype(tz="CET"),
+ DatetimeArray._from_sequence(
+ ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz="CET")
+ ),
+ ),
+ # Timedelta
+ (
+ ["1H", "2H"],
+ np.dtype("timedelta64[ns]"),
+ TimedeltaArray._from_sequence(["1H", "2H"]),
+ ),
+ (
+ pd.TimedeltaIndex(["1H", "2H"]),
+ np.dtype("timedelta64[ns]"),
+ TimedeltaArray._from_sequence(["1H", "2H"]),
+ ),
+ (
+ np.array([1, 2], dtype="m8[s]"),
+ np.dtype("timedelta64[s]"),
+ TimedeltaArray._from_sequence(np.array([1, 2], dtype="m8[s]")),
+ ),
+ (
+ pd.TimedeltaIndex(["1H", "2H"]),
+ None,
+ TimedeltaArray._from_sequence(["1H", "2H"]),
+ ),
+ (
+ # preserve non-nano, i.e. don't cast to NumpyExtensionArray
+ TimedeltaArray._simple_new(
+ np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
+ ),
+ None,
+ TimedeltaArray._simple_new(
+ np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
+ ),
+ ),
+ (
+ # preserve non-nano, i.e. don't cast to NumpyExtensionArray
+ TimedeltaArray._simple_new(
+ np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
+ ),
+ np.dtype("m8[s]"),
+ TimedeltaArray._simple_new(
+ np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
+ ),
+ ),
+ # Category
+ (["a", "b"], "category", pd.Categorical(["a", "b"])),
+ (
+ ["a", "b"],
+ pd.CategoricalDtype(None, ordered=True),
+ pd.Categorical(["a", "b"], ordered=True),
+ ),
+ # Interval
+ (
+ [pd.Interval(1, 2), pd.Interval(3, 4)],
+ "interval",
+ IntervalArray.from_tuples([(1, 2), (3, 4)]),
+ ),
+ # Sparse
+ ([0, 1], "Sparse[int64]", SparseArray([0, 1], dtype="int64")),
+ # IntegerNA
+ ([1, None], "Int16", pd.array([1, None], dtype="Int16")),
+ (
+ pd.Series([1, 2]),
+ None,
+ NumpyExtensionArray(np.array([1, 2], dtype=np.int64)),
+ ),
+ # String
+ (
+ ["a", None],
+ "string",
+ pd.StringDtype().construct_array_type()._from_sequence(["a", None]),
+ ),
+ (
+ ["a", None],
+ pd.StringDtype(),
+ pd.StringDtype().construct_array_type()._from_sequence(["a", None]),
+ ),
+ # Boolean
+ ([True, None], "boolean", BooleanArray._from_sequence([True, None])),
+ ([True, None], pd.BooleanDtype(), BooleanArray._from_sequence([True, None])),
+ # Index
+ (pd.Index([1, 2]), None, NumpyExtensionArray(np.array([1, 2], dtype=np.int64))),
+ # Series[EA] returns the EA
+ (
+ pd.Series(pd.Categorical(["a", "b"], categories=["a", "b", "c"])),
+ None,
+ pd.Categorical(["a", "b"], categories=["a", "b", "c"]),
+ ),
+ # "3rd party" EAs work
+ ([decimal.Decimal(0), decimal.Decimal(1)], "decimal", to_decimal([0, 1])),
+ # pass an ExtensionArray, but a different dtype
+ (
+ period_array(["2000", "2001"], freq="D"),
+ "category",
+ pd.Categorical([pd.Period("2000", "D"), pd.Period("2001", "D")]),
+ ),
+ ],
+)
+def test_array(data, dtype, expected):
+ result = pd.array(data, dtype=dtype)
+ tm.assert_equal(result, expected)
+
+
+def test_array_copy():
+ a = np.array([1, 2])
+ # default is to copy
+ b = pd.array(a, dtype=a.dtype)
+ assert not tm.shares_memory(a, b)
+
+ # copy=True
+ b = pd.array(a, dtype=a.dtype, copy=True)
+ assert not tm.shares_memory(a, b)
+
+ # copy=False
+ b = pd.array(a, dtype=a.dtype, copy=False)
+ assert tm.shares_memory(a, b)
+
+
+cet = pytz.timezone("CET")
+
+
+@pytest.mark.parametrize(
+ "data, expected",
+ [
+ # period
+ (
+ [pd.Period("2000", "D"), pd.Period("2001", "D")],
+ period_array(["2000", "2001"], freq="D"),
+ ),
+ # interval
+ ([pd.Interval(0, 1), pd.Interval(1, 2)], IntervalArray.from_breaks([0, 1, 2])),
+ # datetime
+ (
+ [pd.Timestamp("2000"), pd.Timestamp("2001")],
+ DatetimeArray._from_sequence(["2000", "2001"]),
+ ),
+ (
+ [datetime.datetime(2000, 1, 1), datetime.datetime(2001, 1, 1)],
+ DatetimeArray._from_sequence(["2000", "2001"]),
+ ),
+ (
+ np.array([1, 2], dtype="M8[ns]"),
+ DatetimeArray(np.array([1, 2], dtype="M8[ns]")),
+ ),
+ (
+ np.array([1, 2], dtype="M8[us]"),
+ DatetimeArray._simple_new(
+ np.array([1, 2], dtype="M8[us]"), dtype=np.dtype("M8[us]")
+ ),
+ ),
+ # datetimetz
+ (
+ [pd.Timestamp("2000", tz="CET"), pd.Timestamp("2001", tz="CET")],
+ DatetimeArray._from_sequence(
+ ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz="CET")
+ ),
+ ),
+ (
+ [
+ datetime.datetime(2000, 1, 1, tzinfo=cet),
+ datetime.datetime(2001, 1, 1, tzinfo=cet),
+ ],
+ DatetimeArray._from_sequence(
+ ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz=cet)
+ ),
+ ),
+ # timedelta
+ (
+ [pd.Timedelta("1H"), pd.Timedelta("2H")],
+ TimedeltaArray._from_sequence(["1H", "2H"]),
+ ),
+ (
+ np.array([1, 2], dtype="m8[ns]"),
+ TimedeltaArray(np.array([1, 2], dtype="m8[ns]")),
+ ),
+ (
+ np.array([1, 2], dtype="m8[us]"),
+ TimedeltaArray(np.array([1, 2], dtype="m8[us]")),
+ ),
+ # integer
+ ([1, 2], IntegerArray._from_sequence([1, 2])),
+ ([1, None], IntegerArray._from_sequence([1, None])),
+ ([1, pd.NA], IntegerArray._from_sequence([1, pd.NA])),
+ ([1, np.nan], IntegerArray._from_sequence([1, np.nan])),
+ # float
+ ([0.1, 0.2], FloatingArray._from_sequence([0.1, 0.2])),
+ ([0.1, None], FloatingArray._from_sequence([0.1, pd.NA])),
+ ([0.1, np.nan], FloatingArray._from_sequence([0.1, pd.NA])),
+ ([0.1, pd.NA], FloatingArray._from_sequence([0.1, pd.NA])),
+ # integer-like float
+ ([1.0, 2.0], FloatingArray._from_sequence([1.0, 2.0])),
+ ([1.0, None], FloatingArray._from_sequence([1.0, pd.NA])),
+ ([1.0, np.nan], FloatingArray._from_sequence([1.0, pd.NA])),
+ ([1.0, pd.NA], FloatingArray._from_sequence([1.0, pd.NA])),
+ # mixed-integer-float
+ ([1, 2.0], FloatingArray._from_sequence([1.0, 2.0])),
+ ([1, np.nan, 2.0], FloatingArray._from_sequence([1.0, None, 2.0])),
+ # string
+ (
+ ["a", "b"],
+ pd.StringDtype().construct_array_type()._from_sequence(["a", "b"]),
+ ),
+ (
+ ["a", None],
+ pd.StringDtype().construct_array_type()._from_sequence(["a", None]),
+ ),
+ # Boolean
+ ([True, False], BooleanArray._from_sequence([True, False])),
+ ([True, None], BooleanArray._from_sequence([True, None])),
+ ],
+)
+def test_array_inference(data, expected):
+ result = pd.array(data)
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ # mix of frequencies
+ [pd.Period("2000", "D"), pd.Period("2001", "A")],
+ # mix of closed
+ [pd.Interval(0, 1, closed="left"), pd.Interval(1, 2, closed="right")],
+ # Mix of timezones
+ [pd.Timestamp("2000", tz="CET"), pd.Timestamp("2000", tz="UTC")],
+ # Mix of tz-aware and tz-naive
+ [pd.Timestamp("2000", tz="CET"), pd.Timestamp("2000")],
+ np.array([pd.Timestamp("2000"), pd.Timestamp("2000", tz="CET")]),
+ ],
+)
+def test_array_inference_fails(data):
+ result = pd.array(data)
+ expected = NumpyExtensionArray(np.array(data, dtype=object))
+ tm.assert_extension_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("data", [np.array(0)])
+def test_nd_raises(data):
+ with pytest.raises(ValueError, match="NumpyExtensionArray must be 1-dimensional"):
+ pd.array(data, dtype="int64")
+
+
+def test_scalar_raises():
+ with pytest.raises(ValueError, match="Cannot pass scalar '1'"):
+ pd.array(1)
+
+
+def test_dataframe_raises():
+ # GH#51167 don't accidentally cast to StringArray by doing inference on columns
+ df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
+ msg = "Cannot pass DataFrame to 'pandas.array'"
+ with pytest.raises(TypeError, match=msg):
+ pd.array(df)
+
+
+def test_bounds_check():
+ # GH21796
+ with pytest.raises(
+ TypeError, match=r"cannot safely cast non-equivalent int(32|64) to uint16"
+ ):
+ pd.array([-1, 2, 3], dtype="UInt16")
+
+
+# ---------------------------------------------------------------------------
+# A couple dummy classes to ensure that Series and Indexes are unboxed before
+# getting to the EA classes.
+
+
+@register_extension_dtype
+class DecimalDtype2(DecimalDtype):
+ name = "decimal2"
+
+ @classmethod
+ def construct_array_type(cls):
+ """
+ Return the array type associated with this dtype.
+
+ Returns
+ -------
+ type
+ """
+ return DecimalArray2
+
+
+class DecimalArray2(DecimalArray):
+ @classmethod
+ def _from_sequence(cls, scalars, dtype=None, copy=False):
+ if isinstance(scalars, (pd.Series, pd.Index)):
+ raise TypeError("scalars should not be of type pd.Series or pd.Index")
+
+ return super()._from_sequence(scalars, dtype=dtype, copy=copy)
+
+
+def test_array_unboxes(index_or_series):
+ box = index_or_series
+
+ data = box([decimal.Decimal("1"), decimal.Decimal("2")])
+ # make sure it works
+ with pytest.raises(
+ TypeError, match="scalars should not be of type pd.Series or pd.Index"
+ ):
+ DecimalArray2._from_sequence(data)
+
+ result = pd.array(data, dtype="decimal2")
+ expected = DecimalArray2._from_sequence(data.values)
+ tm.assert_equal(result, expected)
+
+
+def test_array_to_numpy_na():
+ # GH#40638
+ arr = pd.array([pd.NA, 1], dtype="string")
+ result = arr.to_numpy(na_value=True, dtype=bool)
+ expected = np.array([True, True])
+ tm.assert_numpy_array_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_datetimelike.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_datetimelike.py
new file mode 100644
index 0000000000000000000000000000000000000000..96aab94b24ddd6716a11b684a569f3cdfaf5a5e8
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_datetimelike.py
@@ -0,0 +1,1335 @@
+from __future__ import annotations
+
+import re
+import warnings
+
+import numpy as np
+import pytest
+
+from pandas._libs import (
+ NaT,
+ OutOfBoundsDatetime,
+ Timestamp,
+)
+
+import pandas as pd
+from pandas import (
+ DatetimeIndex,
+ Period,
+ PeriodIndex,
+ TimedeltaIndex,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ DatetimeArray,
+ NumpyExtensionArray,
+ PeriodArray,
+ TimedeltaArray,
+)
+from pandas.core.arrays.datetimes import _sequence_to_dt64ns
+from pandas.core.arrays.timedeltas import sequence_to_td64ns
+
+
+# TODO: more freq variants
+@pytest.fixture(params=["D", "B", "W", "M", "Q", "Y"])
+def freqstr(request):
+ """Fixture returning parametrized frequency in string format."""
+ return request.param
+
+
+@pytest.fixture
+def period_index(freqstr):
+ """
+ A fixture to provide PeriodIndex objects with different frequencies.
+
+ Most PeriodArray behavior is already tested in PeriodIndex tests,
+ so here we just test that the PeriodArray behavior matches
+ the PeriodIndex behavior.
+ """
+ # TODO: non-monotone indexes; NaTs, different start dates
+ with warnings.catch_warnings():
+ # suppress deprecation of Period[B]
+ warnings.filterwarnings(
+ "ignore", message="Period with BDay freq", category=FutureWarning
+ )
+ pi = pd.period_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr)
+ return pi
+
+
+@pytest.fixture
+def datetime_index(freqstr):
+ """
+ A fixture to provide DatetimeIndex objects with different frequencies.
+
+ Most DatetimeArray behavior is already tested in DatetimeIndex tests,
+ so here we just test that the DatetimeArray behavior matches
+ the DatetimeIndex behavior.
+ """
+ # TODO: non-monotone indexes; NaTs, different start dates, timezones
+ dti = pd.date_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr)
+ return dti
+
+
+@pytest.fixture
+def timedelta_index():
+ """
+ A fixture to provide TimedeltaIndex objects with different frequencies.
+ Most TimedeltaArray behavior is already tested in TimedeltaIndex tests,
+ so here we just test that the TimedeltaArray behavior matches
+ the TimedeltaIndex behavior.
+ """
+ # TODO: flesh this out
+ return TimedeltaIndex(["1 Day", "3 Hours", "NaT"])
+
+
+class SharedTests:
+ index_cls: type[DatetimeIndex | PeriodIndex | TimedeltaIndex]
+
+ @pytest.fixture
+ def arr1d(self):
+ """Fixture returning DatetimeArray with daily frequency."""
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ arr = self.array_cls(data, freq="D")
+ return arr
+
+ def test_compare_len1_raises(self, arr1d):
+ # make sure we raise when comparing with different lengths, specific
+ # to the case where one has length-1, which numpy would broadcast
+ arr = arr1d
+ idx = self.index_cls(arr)
+
+ with pytest.raises(ValueError, match="Lengths must match"):
+ arr == arr[:1]
+
+ # test the index classes while we're at it, GH#23078
+ with pytest.raises(ValueError, match="Lengths must match"):
+ idx <= idx[[0]]
+
+ @pytest.mark.parametrize(
+ "result",
+ [
+ pd.date_range("2020", periods=3),
+ pd.date_range("2020", periods=3, tz="UTC"),
+ pd.timedelta_range("0 days", periods=3),
+ pd.period_range("2020Q1", periods=3, freq="Q"),
+ ],
+ )
+ def test_compare_with_Categorical(self, result):
+ expected = pd.Categorical(result)
+ assert all(result == expected)
+ assert not any(result != expected)
+
+ @pytest.mark.parametrize("reverse", [True, False])
+ @pytest.mark.parametrize("as_index", [True, False])
+ def test_compare_categorical_dtype(self, arr1d, as_index, reverse, ordered):
+ other = pd.Categorical(arr1d, ordered=ordered)
+ if as_index:
+ other = pd.CategoricalIndex(other)
+
+ left, right = arr1d, other
+ if reverse:
+ left, right = right, left
+
+ ones = np.ones(arr1d.shape, dtype=bool)
+ zeros = ~ones
+
+ result = left == right
+ tm.assert_numpy_array_equal(result, ones)
+
+ result = left != right
+ tm.assert_numpy_array_equal(result, zeros)
+
+ if not reverse and not as_index:
+ # Otherwise Categorical raises TypeError bc it is not ordered
+ # TODO: we should probably get the same behavior regardless?
+ result = left < right
+ tm.assert_numpy_array_equal(result, zeros)
+
+ result = left <= right
+ tm.assert_numpy_array_equal(result, ones)
+
+ result = left > right
+ tm.assert_numpy_array_equal(result, zeros)
+
+ result = left >= right
+ tm.assert_numpy_array_equal(result, ones)
+
+ def test_take(self):
+ data = np.arange(100, dtype="i8") * 24 * 3600 * 10**9
+ np.random.default_rng(2).shuffle(data)
+
+ if self.array_cls is PeriodArray:
+ arr = PeriodArray(data, dtype="period[D]")
+ else:
+ arr = self.array_cls(data)
+ idx = self.index_cls._simple_new(arr)
+
+ takers = [1, 4, 94]
+ result = arr.take(takers)
+ expected = idx.take(takers)
+
+ tm.assert_index_equal(self.index_cls(result), expected)
+
+ takers = np.array([1, 4, 94])
+ result = arr.take(takers)
+ expected = idx.take(takers)
+
+ tm.assert_index_equal(self.index_cls(result), expected)
+
+ @pytest.mark.parametrize("fill_value", [2, 2.0, Timestamp(2021, 1, 1, 12).time])
+ def test_take_fill_raises(self, fill_value, arr1d):
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
+ arr1d.take([0, 1], allow_fill=True, fill_value=fill_value)
+
+ def test_take_fill(self, arr1d):
+ np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+
+ arr = arr1d # self.array_cls(data, freq="D")
+
+ result = arr.take([-1, 1], allow_fill=True, fill_value=None)
+ assert result[0] is NaT
+
+ result = arr.take([-1, 1], allow_fill=True, fill_value=np.nan)
+ assert result[0] is NaT
+
+ result = arr.take([-1, 1], allow_fill=True, fill_value=NaT)
+ assert result[0] is NaT
+
+ @pytest.mark.filterwarnings(
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
+ )
+ def test_take_fill_str(self, arr1d):
+ # Cast str fill_value matching other fill_value-taking methods
+ result = arr1d.take([-1, 1], allow_fill=True, fill_value=str(arr1d[-1]))
+ expected = arr1d[[-1, 1]]
+ tm.assert_equal(result, expected)
+
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
+ arr1d.take([-1, 1], allow_fill=True, fill_value="foo")
+
+ def test_concat_same_type(self, arr1d):
+ arr = arr1d
+ idx = self.index_cls(arr)
+ idx = idx.insert(0, NaT)
+ arr = self.array_cls(idx)
+
+ result = arr._concat_same_type([arr[:-1], arr[1:], arr])
+ arr2 = arr.astype(object)
+ expected = self.index_cls(np.concatenate([arr2[:-1], arr2[1:], arr2]), None)
+
+ tm.assert_index_equal(self.index_cls(result), expected)
+
+ def test_unbox_scalar(self, arr1d):
+ result = arr1d._unbox_scalar(arr1d[0])
+ expected = arr1d._ndarray.dtype.type
+ assert isinstance(result, expected)
+
+ result = arr1d._unbox_scalar(NaT)
+ assert isinstance(result, expected)
+
+ msg = f"'value' should be a {self.scalar_type.__name__}."
+ with pytest.raises(ValueError, match=msg):
+ arr1d._unbox_scalar("foo")
+
+ def test_check_compatible_with(self, arr1d):
+ arr1d._check_compatible_with(arr1d[0])
+ arr1d._check_compatible_with(arr1d[:1])
+ arr1d._check_compatible_with(NaT)
+
+ def test_scalar_from_string(self, arr1d):
+ result = arr1d._scalar_from_string(str(arr1d[0]))
+ assert result == arr1d[0]
+
+ def test_reduce_invalid(self, arr1d):
+ msg = "does not support reduction 'not a method'"
+ with pytest.raises(TypeError, match=msg):
+ arr1d._reduce("not a method")
+
+ @pytest.mark.parametrize("method", ["pad", "backfill"])
+ def test_fillna_method_doesnt_change_orig(self, method):
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ if self.array_cls is PeriodArray:
+ arr = self.array_cls(data, dtype="period[D]")
+ else:
+ arr = self.array_cls(data)
+ arr[4] = NaT
+
+ fill_value = arr[3] if method == "pad" else arr[5]
+
+ result = arr._pad_or_backfill(method=method)
+ assert result[4] == fill_value
+
+ # check that the original was not changed
+ assert arr[4] is NaT
+
+ def test_searchsorted(self):
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ if self.array_cls is PeriodArray:
+ arr = self.array_cls(data, dtype="period[D]")
+ else:
+ arr = self.array_cls(data)
+
+ # scalar
+ result = arr.searchsorted(arr[1])
+ assert result == 1
+
+ result = arr.searchsorted(arr[2], side="right")
+ assert result == 3
+
+ # own-type
+ result = arr.searchsorted(arr[1:3])
+ expected = np.array([1, 2], dtype=np.intp)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = arr.searchsorted(arr[1:3], side="right")
+ expected = np.array([2, 3], dtype=np.intp)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # GH#29884 match numpy convention on whether NaT goes
+ # at the end or the beginning
+ result = arr.searchsorted(NaT)
+ assert result == 10
+
+ @pytest.mark.parametrize("box", [None, "index", "series"])
+ def test_searchsorted_castable_strings(self, arr1d, box, string_storage):
+ arr = arr1d
+ if box is None:
+ pass
+ elif box == "index":
+ # Test the equivalent Index.searchsorted method while we're here
+ arr = self.index_cls(arr)
+ else:
+ # Test the equivalent Series.searchsorted method while we're here
+ arr = pd.Series(arr)
+
+ # scalar
+ result = arr.searchsorted(str(arr[1]))
+ assert result == 1
+
+ result = arr.searchsorted(str(arr[2]), side="right")
+ assert result == 3
+
+ result = arr.searchsorted([str(x) for x in arr[1:3]])
+ expected = np.array([1, 2], dtype=np.intp)
+ tm.assert_numpy_array_equal(result, expected)
+
+ with pytest.raises(
+ TypeError,
+ match=re.escape(
+ f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', "
+ "or array of those. Got 'str' instead."
+ ),
+ ):
+ arr.searchsorted("foo")
+
+ if string_storage == "python":
+ arr_type = "StringArray"
+ elif string_storage == "pyarrow":
+ arr_type = "ArrowStringArray"
+ else:
+ arr_type = "ArrowStringArrayNumpySemantics"
+
+ with pd.option_context("string_storage", string_storage):
+ with pytest.raises(
+ TypeError,
+ match=re.escape(
+ f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', "
+ f"or array of those. Got '{arr_type}' instead."
+ ),
+ ):
+ arr.searchsorted([str(arr[1]), "baz"])
+
+ def test_getitem_near_implementation_bounds(self):
+ # We only check tz-naive for DTA bc the bounds are slightly different
+ # for other tzs
+ i8vals = np.asarray([NaT._value + n for n in range(1, 5)], dtype="i8")
+ if self.array_cls is PeriodArray:
+ arr = self.array_cls(i8vals, dtype="period[ns]")
+ else:
+ arr = self.array_cls(i8vals, freq="ns")
+ arr[0] # should not raise OutOfBoundsDatetime
+
+ index = pd.Index(arr)
+ index[0] # should not raise OutOfBoundsDatetime
+
+ ser = pd.Series(arr)
+ ser[0] # should not raise OutOfBoundsDatetime
+
+ def test_getitem_2d(self, arr1d):
+ # 2d slicing on a 1D array
+ expected = type(arr1d)(arr1d._ndarray[:, np.newaxis], dtype=arr1d.dtype)
+ result = arr1d[:, np.newaxis]
+ tm.assert_equal(result, expected)
+
+ # Lookup on a 2D array
+ arr2d = expected
+ expected = type(arr2d)(arr2d._ndarray[:3, 0], dtype=arr2d.dtype)
+ result = arr2d[:3, 0]
+ tm.assert_equal(result, expected)
+
+ # Scalar lookup
+ result = arr2d[-1, 0]
+ expected = arr1d[-1]
+ assert result == expected
+
+ def test_iter_2d(self, arr1d):
+ data2d = arr1d._ndarray[:3, np.newaxis]
+ arr2d = type(arr1d)._simple_new(data2d, dtype=arr1d.dtype)
+ result = list(arr2d)
+ assert len(result) == 3
+ for x in result:
+ assert isinstance(x, type(arr1d))
+ assert x.ndim == 1
+ assert x.dtype == arr1d.dtype
+
+ def test_repr_2d(self, arr1d):
+ data2d = arr1d._ndarray[:3, np.newaxis]
+ arr2d = type(arr1d)._simple_new(data2d, dtype=arr1d.dtype)
+
+ result = repr(arr2d)
+
+ if isinstance(arr2d, TimedeltaArray):
+ expected = (
+ f"<{type(arr2d).__name__}>\n"
+ "[\n"
+ f"['{arr1d[0]._repr_base()}'],\n"
+ f"['{arr1d[1]._repr_base()}'],\n"
+ f"['{arr1d[2]._repr_base()}']\n"
+ "]\n"
+ f"Shape: (3, 1), dtype: {arr1d.dtype}"
+ )
+ else:
+ expected = (
+ f"<{type(arr2d).__name__}>\n"
+ "[\n"
+ f"['{arr1d[0]}'],\n"
+ f"['{arr1d[1]}'],\n"
+ f"['{arr1d[2]}']\n"
+ "]\n"
+ f"Shape: (3, 1), dtype: {arr1d.dtype}"
+ )
+
+ assert result == expected
+
+ def test_setitem(self):
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ if self.array_cls is PeriodArray:
+ arr = self.array_cls(data, dtype="period[D]")
+ else:
+ arr = self.array_cls(data, freq="D")
+
+ arr[0] = arr[1]
+ expected = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ expected[0] = expected[1]
+
+ tm.assert_numpy_array_equal(arr.asi8, expected)
+
+ arr[:2] = arr[-2:]
+ expected[:2] = expected[-2:]
+ tm.assert_numpy_array_equal(arr.asi8, expected)
+
+ @pytest.mark.parametrize(
+ "box",
+ [
+ pd.Index,
+ pd.Series,
+ np.array,
+ list,
+ NumpyExtensionArray,
+ ],
+ )
+ def test_setitem_object_dtype(self, box, arr1d):
+ expected = arr1d.copy()[::-1]
+ if expected.dtype.kind in ["m", "M"]:
+ expected = expected._with_freq(None)
+
+ vals = expected
+ if box is list:
+ vals = list(vals)
+ elif box is np.array:
+ # if we do np.array(x).astype(object) then dt64 and td64 cast to ints
+ vals = np.array(vals.astype(object))
+ elif box is NumpyExtensionArray:
+ vals = box(np.asarray(vals, dtype=object))
+ else:
+ vals = box(vals).astype(object)
+
+ arr1d[:] = vals
+
+ tm.assert_equal(arr1d, expected)
+
+ def test_setitem_strs(self, arr1d):
+ # Check that we parse strs in both scalar and listlike
+
+ # Setting list-like of strs
+ expected = arr1d.copy()
+ expected[[0, 1]] = arr1d[-2:]
+
+ result = arr1d.copy()
+ result[:2] = [str(x) for x in arr1d[-2:]]
+ tm.assert_equal(result, expected)
+
+ # Same thing but now for just a scalar str
+ expected = arr1d.copy()
+ expected[0] = arr1d[-1]
+
+ result = arr1d.copy()
+ result[0] = str(arr1d[-1])
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("as_index", [True, False])
+ def test_setitem_categorical(self, arr1d, as_index):
+ expected = arr1d.copy()[::-1]
+ if not isinstance(expected, PeriodArray):
+ expected = expected._with_freq(None)
+
+ cat = pd.Categorical(arr1d)
+ if as_index:
+ cat = pd.CategoricalIndex(cat)
+
+ arr1d[:] = cat[::-1]
+
+ tm.assert_equal(arr1d, expected)
+
+ def test_setitem_raises(self, arr1d):
+ arr = arr1d[:10]
+ val = arr[0]
+
+ with pytest.raises(IndexError, match="index 12 is out of bounds"):
+ arr[12] = val
+
+ with pytest.raises(TypeError, match="value should be a.* 'object'"):
+ arr[0] = object()
+
+ msg = "cannot set using a list-like indexer with a different length"
+ with pytest.raises(ValueError, match=msg):
+ # GH#36339
+ arr[[]] = [arr[1]]
+
+ msg = "cannot set using a slice indexer with a different length than"
+ with pytest.raises(ValueError, match=msg):
+ # GH#36339
+ arr[1:1] = arr[:3]
+
+ @pytest.mark.parametrize("box", [list, np.array, pd.Index, pd.Series])
+ def test_setitem_numeric_raises(self, arr1d, box):
+ # We dont case e.g. int64 to our own dtype for setitem
+
+ msg = (
+ f"value should be a '{arr1d._scalar_type.__name__}', "
+ "'NaT', or array of those. Got"
+ )
+ with pytest.raises(TypeError, match=msg):
+ arr1d[:2] = box([0, 1])
+
+ with pytest.raises(TypeError, match=msg):
+ arr1d[:2] = box([0.0, 1.0])
+
+ def test_inplace_arithmetic(self):
+ # GH#24115 check that iadd and isub are actually in-place
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ if self.array_cls is PeriodArray:
+ arr = self.array_cls(data, dtype="period[D]")
+ else:
+ arr = self.array_cls(data, freq="D")
+
+ expected = arr + pd.Timedelta(days=1)
+ arr += pd.Timedelta(days=1)
+ tm.assert_equal(arr, expected)
+
+ expected = arr - pd.Timedelta(days=1)
+ arr -= pd.Timedelta(days=1)
+ tm.assert_equal(arr, expected)
+
+ def test_shift_fill_int_deprecated(self, arr1d):
+ # GH#31971, enforced in 2.0
+ with pytest.raises(TypeError, match="value should be a"):
+ arr1d.shift(1, fill_value=1)
+
+ def test_median(self, arr1d):
+ arr = arr1d
+ if len(arr) % 2 == 0:
+ # make it easier to define `expected`
+ arr = arr[:-1]
+
+ expected = arr[len(arr) // 2]
+
+ result = arr.median()
+ assert type(result) is type(expected)
+ assert result == expected
+
+ arr[len(arr) // 2] = NaT
+ if not isinstance(expected, Period):
+ expected = arr[len(arr) // 2 - 1 : len(arr) // 2 + 2].mean()
+
+ assert arr.median(skipna=False) is NaT
+
+ result = arr.median()
+ assert type(result) is type(expected)
+ assert result == expected
+
+ assert arr[:0].median() is NaT
+ assert arr[:0].median(skipna=False) is NaT
+
+ # 2d Case
+ arr2 = arr.reshape(-1, 1)
+
+ result = arr2.median(axis=None)
+ assert type(result) is type(expected)
+ assert result == expected
+
+ assert arr2.median(axis=None, skipna=False) is NaT
+
+ result = arr2.median(axis=0)
+ expected2 = type(arr)._from_sequence([expected], dtype=arr.dtype)
+ tm.assert_equal(result, expected2)
+
+ result = arr2.median(axis=0, skipna=False)
+ expected2 = type(arr)._from_sequence([NaT], dtype=arr.dtype)
+ tm.assert_equal(result, expected2)
+
+ result = arr2.median(axis=1)
+ tm.assert_equal(result, arr)
+
+ result = arr2.median(axis=1, skipna=False)
+ tm.assert_equal(result, arr)
+
+ def test_from_integer_array(self):
+ arr = np.array([1, 2, 3], dtype=np.int64)
+ expected = self.array_cls(arr, dtype=self.example_dtype)
+
+ data = pd.array(arr, dtype="Int64")
+ result = self.array_cls(data, dtype=self.example_dtype)
+
+ tm.assert_extension_array_equal(result, expected)
+
+
+class TestDatetimeArray(SharedTests):
+ index_cls = DatetimeIndex
+ array_cls = DatetimeArray
+ scalar_type = Timestamp
+ example_dtype = "M8[ns]"
+
+ @pytest.fixture
+ def arr1d(self, tz_naive_fixture, freqstr):
+ """
+ Fixture returning DatetimeArray with parametrized frequency and
+ timezones
+ """
+ tz = tz_naive_fixture
+ dti = pd.date_range("2016-01-01 01:01:00", periods=5, freq=freqstr, tz=tz)
+ dta = dti._data
+ return dta
+
+ def test_round(self, arr1d):
+ # GH#24064
+ dti = self.index_cls(arr1d)
+
+ result = dti.round(freq="2T")
+ expected = dti - pd.Timedelta(minutes=1)
+ expected = expected._with_freq(None)
+ tm.assert_index_equal(result, expected)
+
+ dta = dti._data
+ result = dta.round(freq="2T")
+ expected = expected._data._with_freq(None)
+ tm.assert_datetime_array_equal(result, expected)
+
+ def test_array_interface(self, datetime_index):
+ arr = DatetimeArray(datetime_index)
+
+ # default asarray gives the same underlying data (for tz naive)
+ result = np.asarray(arr)
+ expected = arr._ndarray
+ assert result is expected
+ tm.assert_numpy_array_equal(result, expected)
+ result = np.array(arr, copy=False)
+ assert result is expected
+ tm.assert_numpy_array_equal(result, expected)
+
+ # specifying M8[ns] gives the same result as default
+ result = np.asarray(arr, dtype="datetime64[ns]")
+ expected = arr._ndarray
+ assert result is expected
+ tm.assert_numpy_array_equal(result, expected)
+ result = np.array(arr, dtype="datetime64[ns]", copy=False)
+ assert result is expected
+ tm.assert_numpy_array_equal(result, expected)
+ result = np.array(arr, dtype="datetime64[ns]")
+ assert result is not expected
+ tm.assert_numpy_array_equal(result, expected)
+
+ # to object dtype
+ result = np.asarray(arr, dtype=object)
+ expected = np.array(list(arr), dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # to other dtype always copies
+ result = np.asarray(arr, dtype="int64")
+ assert result is not arr.asi8
+ assert not np.may_share_memory(arr, result)
+ expected = arr.asi8.copy()
+ tm.assert_numpy_array_equal(result, expected)
+
+ # other dtypes handled by numpy
+ for dtype in ["float64", str]:
+ result = np.asarray(arr, dtype=dtype)
+ expected = np.asarray(arr).astype(dtype)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_array_object_dtype(self, arr1d):
+ # GH#23524
+ arr = arr1d
+ dti = self.index_cls(arr1d)
+
+ expected = np.array(list(dti))
+
+ result = np.array(arr, dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # also test the DatetimeIndex method while we're at it
+ result = np.array(dti, dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_array_tz(self, arr1d):
+ # GH#23524
+ arr = arr1d
+ dti = self.index_cls(arr1d)
+
+ expected = dti.asi8.view("M8[ns]")
+ result = np.array(arr, dtype="M8[ns]")
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.array(arr, dtype="datetime64[ns]")
+ tm.assert_numpy_array_equal(result, expected)
+
+ # check that we are not making copies when setting copy=False
+ result = np.array(arr, dtype="M8[ns]", copy=False)
+ assert result.base is expected.base
+ assert result.base is not None
+ result = np.array(arr, dtype="datetime64[ns]", copy=False)
+ assert result.base is expected.base
+ assert result.base is not None
+
+ def test_array_i8_dtype(self, arr1d):
+ arr = arr1d
+ dti = self.index_cls(arr1d)
+
+ expected = dti.asi8
+ result = np.array(arr, dtype="i8")
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.array(arr, dtype=np.int64)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # check that we are still making copies when setting copy=False
+ result = np.array(arr, dtype="i8", copy=False)
+ assert result.base is not expected.base
+ assert result.base is None
+
+ def test_from_array_keeps_base(self):
+ # Ensure that DatetimeArray._ndarray.base isn't lost.
+ arr = np.array(["2000-01-01", "2000-01-02"], dtype="M8[ns]")
+ dta = DatetimeArray(arr)
+
+ assert dta._ndarray is arr
+ dta = DatetimeArray(arr[:0])
+ assert dta._ndarray.base is arr
+
+ def test_from_dti(self, arr1d):
+ arr = arr1d
+ dti = self.index_cls(arr1d)
+ assert list(dti) == list(arr)
+
+ # Check that Index.__new__ knows what to do with DatetimeArray
+ dti2 = pd.Index(arr)
+ assert isinstance(dti2, DatetimeIndex)
+ assert list(dti2) == list(arr)
+
+ def test_astype_object(self, arr1d):
+ arr = arr1d
+ dti = self.index_cls(arr1d)
+
+ asobj = arr.astype("O")
+ assert isinstance(asobj, np.ndarray)
+ assert asobj.dtype == "O"
+ assert list(asobj) == list(dti)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_to_period(self, datetime_index, freqstr):
+ dti = datetime_index
+ arr = DatetimeArray(dti)
+
+ expected = dti.to_period(freq=freqstr)
+ result = arr.to_period(freq=freqstr)
+ assert isinstance(result, PeriodArray)
+
+ tm.assert_equal(result, expected._data)
+
+ def test_to_period_2d(self, arr1d):
+ arr2d = arr1d.reshape(1, -1)
+
+ warn = None if arr1d.tz is None else UserWarning
+ with tm.assert_produces_warning(warn):
+ result = arr2d.to_period("D")
+ expected = arr1d.to_period("D").reshape(1, -1)
+ tm.assert_period_array_equal(result, expected)
+
+ @pytest.mark.parametrize("propname", DatetimeArray._bool_ops)
+ def test_bool_properties(self, arr1d, propname):
+ # in this case _bool_ops is just `is_leap_year`
+ dti = self.index_cls(arr1d)
+ arr = arr1d
+ assert dti.freq == arr.freq
+
+ result = getattr(arr, propname)
+ expected = np.array(getattr(dti, propname), dtype=result.dtype)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("propname", DatetimeArray._field_ops)
+ def test_int_properties(self, arr1d, propname):
+ dti = self.index_cls(arr1d)
+ arr = arr1d
+
+ result = getattr(arr, propname)
+ expected = np.array(getattr(dti, propname), dtype=result.dtype)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_take_fill_valid(self, arr1d, fixed_now_ts):
+ arr = arr1d
+ dti = self.index_cls(arr1d)
+
+ now = fixed_now_ts.tz_localize(dti.tz)
+ result = arr.take([-1, 1], allow_fill=True, fill_value=now)
+ assert result[0] == now
+
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
+ # fill_value Timedelta invalid
+ arr.take([-1, 1], allow_fill=True, fill_value=now - now)
+
+ with pytest.raises(TypeError, match=msg):
+ # fill_value Period invalid
+ arr.take([-1, 1], allow_fill=True, fill_value=Period("2014Q1"))
+
+ tz = None if dti.tz is not None else "US/Eastern"
+ now = fixed_now_ts.tz_localize(tz)
+ msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
+ with pytest.raises(TypeError, match=msg):
+ # Timestamp with mismatched tz-awareness
+ arr.take([-1, 1], allow_fill=True, fill_value=now)
+
+ value = NaT._value
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
+ # require NaT, not iNaT, as it could be confused with an integer
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
+
+ value = np.timedelta64("NaT", "ns")
+ with pytest.raises(TypeError, match=msg):
+ # require appropriate-dtype if we have a NA value
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
+
+ if arr.tz is not None:
+ # GH#37356
+ # Assuming here that arr1d fixture does not include Australia/Melbourne
+ value = fixed_now_ts.tz_localize("Australia/Melbourne")
+ result = arr.take([-1, 1], allow_fill=True, fill_value=value)
+
+ expected = arr.take(
+ [-1, 1],
+ allow_fill=True,
+ fill_value=value.tz_convert(arr.dtype.tz),
+ )
+ tm.assert_equal(result, expected)
+
+ def test_concat_same_type_invalid(self, arr1d):
+ # different timezones
+ arr = arr1d
+
+ if arr.tz is None:
+ other = arr.tz_localize("UTC")
+ else:
+ other = arr.tz_localize(None)
+
+ with pytest.raises(ValueError, match="to_concat must have the same"):
+ arr._concat_same_type([arr, other])
+
+ def test_concat_same_type_different_freq(self):
+ # we *can* concatenate DTI with different freqs.
+ a = DatetimeArray(pd.date_range("2000", periods=2, freq="D", tz="US/Central"))
+ b = DatetimeArray(pd.date_range("2000", periods=2, freq="H", tz="US/Central"))
+ result = DatetimeArray._concat_same_type([a, b])
+ expected = DatetimeArray(
+ pd.to_datetime(
+ [
+ "2000-01-01 00:00:00",
+ "2000-01-02 00:00:00",
+ "2000-01-01 00:00:00",
+ "2000-01-01 01:00:00",
+ ]
+ ).tz_localize("US/Central")
+ )
+
+ tm.assert_datetime_array_equal(result, expected)
+
+ def test_strftime(self, arr1d):
+ arr = arr1d
+
+ result = arr.strftime("%Y %b")
+ expected = np.array([ts.strftime("%Y %b") for ts in arr], dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_strftime_nat(self):
+ # GH 29578
+ arr = DatetimeArray(DatetimeIndex(["2019-01-01", NaT]))
+
+ result = arr.strftime("%Y-%m-%d")
+ expected = np.array(["2019-01-01", np.nan], dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+class TestTimedeltaArray(SharedTests):
+ index_cls = TimedeltaIndex
+ array_cls = TimedeltaArray
+ scalar_type = pd.Timedelta
+ example_dtype = "m8[ns]"
+
+ def test_from_tdi(self):
+ tdi = TimedeltaIndex(["1 Day", "3 Hours"])
+ arr = TimedeltaArray(tdi)
+ assert list(arr) == list(tdi)
+
+ # Check that Index.__new__ knows what to do with TimedeltaArray
+ tdi2 = pd.Index(arr)
+ assert isinstance(tdi2, TimedeltaIndex)
+ assert list(tdi2) == list(arr)
+
+ def test_astype_object(self):
+ tdi = TimedeltaIndex(["1 Day", "3 Hours"])
+ arr = TimedeltaArray(tdi)
+ asobj = arr.astype("O")
+ assert isinstance(asobj, np.ndarray)
+ assert asobj.dtype == "O"
+ assert list(asobj) == list(tdi)
+
+ def test_to_pytimedelta(self, timedelta_index):
+ tdi = timedelta_index
+ arr = TimedeltaArray(tdi)
+
+ expected = tdi.to_pytimedelta()
+ result = arr.to_pytimedelta()
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_total_seconds(self, timedelta_index):
+ tdi = timedelta_index
+ arr = TimedeltaArray(tdi)
+
+ expected = tdi.total_seconds()
+ result = arr.total_seconds()
+
+ tm.assert_numpy_array_equal(result, expected.values)
+
+ @pytest.mark.parametrize("propname", TimedeltaArray._field_ops)
+ def test_int_properties(self, timedelta_index, propname):
+ tdi = timedelta_index
+ arr = TimedeltaArray(tdi)
+
+ result = getattr(arr, propname)
+ expected = np.array(getattr(tdi, propname), dtype=result.dtype)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_array_interface(self, timedelta_index):
+ arr = TimedeltaArray(timedelta_index)
+
+ # default asarray gives the same underlying data
+ result = np.asarray(arr)
+ expected = arr._ndarray
+ assert result is expected
+ tm.assert_numpy_array_equal(result, expected)
+ result = np.array(arr, copy=False)
+ assert result is expected
+ tm.assert_numpy_array_equal(result, expected)
+
+ # specifying m8[ns] gives the same result as default
+ result = np.asarray(arr, dtype="timedelta64[ns]")
+ expected = arr._ndarray
+ assert result is expected
+ tm.assert_numpy_array_equal(result, expected)
+ result = np.array(arr, dtype="timedelta64[ns]", copy=False)
+ assert result is expected
+ tm.assert_numpy_array_equal(result, expected)
+ result = np.array(arr, dtype="timedelta64[ns]")
+ assert result is not expected
+ tm.assert_numpy_array_equal(result, expected)
+
+ # to object dtype
+ result = np.asarray(arr, dtype=object)
+ expected = np.array(list(arr), dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # to other dtype always copies
+ result = np.asarray(arr, dtype="int64")
+ assert result is not arr.asi8
+ assert not np.may_share_memory(arr, result)
+ expected = arr.asi8.copy()
+ tm.assert_numpy_array_equal(result, expected)
+
+ # other dtypes handled by numpy
+ for dtype in ["float64", str]:
+ result = np.asarray(arr, dtype=dtype)
+ expected = np.asarray(arr).astype(dtype)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_take_fill_valid(self, timedelta_index, fixed_now_ts):
+ tdi = timedelta_index
+ arr = TimedeltaArray(tdi)
+
+ td1 = pd.Timedelta(days=1)
+ result = arr.take([-1, 1], allow_fill=True, fill_value=td1)
+ assert result[0] == td1
+
+ value = fixed_now_ts
+ msg = f"value should be a '{arr._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
+ # fill_value Timestamp invalid
+ arr.take([0, 1], allow_fill=True, fill_value=value)
+
+ value = fixed_now_ts.to_period("D")
+ with pytest.raises(TypeError, match=msg):
+ # fill_value Period invalid
+ arr.take([0, 1], allow_fill=True, fill_value=value)
+
+ value = np.datetime64("NaT", "ns")
+ with pytest.raises(TypeError, match=msg):
+ # require appropriate-dtype if we have a NA value
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
+
+
+@pytest.mark.filterwarnings(r"ignore:Period with BDay freq is deprecated:FutureWarning")
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+class TestPeriodArray(SharedTests):
+ index_cls = PeriodIndex
+ array_cls = PeriodArray
+ scalar_type = Period
+ example_dtype = PeriodIndex([], freq="W").dtype
+
+ @pytest.fixture
+ def arr1d(self, period_index):
+ """
+ Fixture returning DatetimeArray from parametrized PeriodIndex objects
+ """
+ return period_index._data
+
+ def test_from_pi(self, arr1d):
+ pi = self.index_cls(arr1d)
+ arr = arr1d
+ assert list(arr) == list(pi)
+
+ # Check that Index.__new__ knows what to do with PeriodArray
+ pi2 = pd.Index(arr)
+ assert isinstance(pi2, PeriodIndex)
+ assert list(pi2) == list(arr)
+
+ def test_astype_object(self, arr1d):
+ pi = self.index_cls(arr1d)
+ arr = arr1d
+ asobj = arr.astype("O")
+ assert isinstance(asobj, np.ndarray)
+ assert asobj.dtype == "O"
+ assert list(asobj) == list(pi)
+
+ def test_take_fill_valid(self, arr1d):
+ arr = arr1d
+
+ value = NaT._value
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
+ # require NaT, not iNaT, as it could be confused with an integer
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
+
+ value = np.timedelta64("NaT", "ns")
+ with pytest.raises(TypeError, match=msg):
+ # require appropriate-dtype if we have a NA value
+ arr.take([-1, 1], allow_fill=True, fill_value=value)
+
+ @pytest.mark.parametrize("how", ["S", "E"])
+ def test_to_timestamp(self, how, arr1d):
+ pi = self.index_cls(arr1d)
+ arr = arr1d
+
+ expected = DatetimeArray(pi.to_timestamp(how=how))
+ result = arr.to_timestamp(how=how)
+ assert isinstance(result, DatetimeArray)
+
+ tm.assert_equal(result, expected)
+
+ def test_to_timestamp_roundtrip_bday(self):
+ # Case where infer_freq inside would choose "D" instead of "B"
+ dta = pd.date_range("2021-10-18", periods=3, freq="B")._data
+ parr = dta.to_period()
+ result = parr.to_timestamp()
+ assert result.freq == "B"
+ tm.assert_extension_array_equal(result, dta)
+
+ dta2 = dta[::2]
+ parr2 = dta2.to_period()
+ result2 = parr2.to_timestamp()
+ assert result2.freq == "2B"
+ tm.assert_extension_array_equal(result2, dta2)
+
+ parr3 = dta.to_period("2B")
+ result3 = parr3.to_timestamp()
+ assert result3.freq == "B"
+ tm.assert_extension_array_equal(result3, dta)
+
+ def test_to_timestamp_out_of_bounds(self):
+ # GH#19643 previously overflowed silently
+ pi = pd.period_range("1500", freq="Y", periods=3)
+ msg = "Out of bounds nanosecond timestamp: 1500-01-01 00:00:00"
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
+ pi.to_timestamp()
+
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
+ pi._data.to_timestamp()
+
+ @pytest.mark.parametrize("propname", PeriodArray._bool_ops)
+ def test_bool_properties(self, arr1d, propname):
+ # in this case _bool_ops is just `is_leap_year`
+ pi = self.index_cls(arr1d)
+ arr = arr1d
+
+ result = getattr(arr, propname)
+ expected = np.array(getattr(pi, propname))
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("propname", PeriodArray._field_ops)
+ def test_int_properties(self, arr1d, propname):
+ pi = self.index_cls(arr1d)
+ arr = arr1d
+
+ result = getattr(arr, propname)
+ expected = np.array(getattr(pi, propname))
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_array_interface(self, arr1d):
+ arr = arr1d
+
+ # default asarray gives objects
+ result = np.asarray(arr)
+ expected = np.array(list(arr), dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # to object dtype (same as default)
+ result = np.asarray(arr, dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.asarray(arr, dtype="int64")
+ tm.assert_numpy_array_equal(result, arr.asi8)
+
+ # to other dtypes
+ msg = r"float\(\) argument must be a string or a( real)? number, not 'Period'"
+ with pytest.raises(TypeError, match=msg):
+ np.asarray(arr, dtype="float64")
+
+ result = np.asarray(arr, dtype="S20")
+ expected = np.asarray(arr).astype("S20")
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_strftime(self, arr1d):
+ arr = arr1d
+
+ result = arr.strftime("%Y")
+ expected = np.array([per.strftime("%Y") for per in arr], dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_strftime_nat(self):
+ # GH 29578
+ arr = PeriodArray(PeriodIndex(["2019-01-01", NaT], dtype="period[D]"))
+
+ result = arr.strftime("%Y-%m-%d")
+ expected = np.array(["2019-01-01", np.nan], dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "arr,casting_nats",
+ [
+ (
+ TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
+ (NaT, np.timedelta64("NaT", "ns")),
+ ),
+ (
+ pd.date_range("2000-01-01", periods=3, freq="D")._data,
+ (NaT, np.datetime64("NaT", "ns")),
+ ),
+ (pd.period_range("2000-01-01", periods=3, freq="D")._data, (NaT,)),
+ ],
+ ids=lambda x: type(x).__name__,
+)
+def test_casting_nat_setitem_array(arr, casting_nats):
+ expected = type(arr)._from_sequence([NaT, arr[1], arr[2]])
+
+ for nat in casting_nats:
+ arr = arr.copy()
+ arr[0] = nat
+ tm.assert_equal(arr, expected)
+
+
+@pytest.mark.parametrize(
+ "arr,non_casting_nats",
+ [
+ (
+ TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
+ (np.datetime64("NaT", "ns"), NaT._value),
+ ),
+ (
+ pd.date_range("2000-01-01", periods=3, freq="D")._data,
+ (np.timedelta64("NaT", "ns"), NaT._value),
+ ),
+ (
+ pd.period_range("2000-01-01", periods=3, freq="D")._data,
+ (np.datetime64("NaT", "ns"), np.timedelta64("NaT", "ns"), NaT._value),
+ ),
+ ],
+ ids=lambda x: type(x).__name__,
+)
+def test_invalid_nat_setitem_array(arr, non_casting_nats):
+ msg = (
+ "value should be a '(Timestamp|Timedelta|Period)', 'NaT', or array of those. "
+ "Got '(timedelta64|datetime64|int)' instead."
+ )
+
+ for nat in non_casting_nats:
+ with pytest.raises(TypeError, match=msg):
+ arr[0] = nat
+
+
+@pytest.mark.parametrize(
+ "arr",
+ [
+ pd.date_range("2000", periods=4).array,
+ pd.timedelta_range("2000", periods=4).array,
+ ],
+)
+def test_to_numpy_extra(arr):
+ arr[0] = NaT
+ original = arr.copy()
+
+ result = arr.to_numpy()
+ assert np.isnan(result[0])
+
+ result = arr.to_numpy(dtype="int64")
+ assert result[0] == -9223372036854775808
+
+ result = arr.to_numpy(dtype="int64", na_value=0)
+ assert result[0] == 0
+
+ result = arr.to_numpy(na_value=arr[1].to_numpy())
+ assert result[0] == result[1]
+
+ result = arr.to_numpy(na_value=arr[1].to_numpy(copy=False))
+ assert result[0] == result[1]
+
+ tm.assert_equal(arr, original)
+
+
+@pytest.mark.parametrize("as_index", [True, False])
+@pytest.mark.parametrize(
+ "values",
+ [
+ pd.to_datetime(["2020-01-01", "2020-02-01"]),
+ TimedeltaIndex([1, 2], unit="D"),
+ PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"),
+ ],
+)
+@pytest.mark.parametrize(
+ "klass",
+ [
+ list,
+ np.array,
+ pd.array,
+ pd.Series,
+ pd.Index,
+ pd.Categorical,
+ pd.CategoricalIndex,
+ ],
+)
+def test_searchsorted_datetimelike_with_listlike(values, klass, as_index):
+ # https://github.com/pandas-dev/pandas/issues/32762
+ if not as_index:
+ values = values._data
+
+ result = values.searchsorted(klass(values))
+ expected = np.array([0, 1], dtype=result.dtype)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "values",
+ [
+ pd.to_datetime(["2020-01-01", "2020-02-01"]),
+ TimedeltaIndex([1, 2], unit="D"),
+ PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"),
+ ],
+)
+@pytest.mark.parametrize(
+ "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2]
+)
+def test_searchsorted_datetimelike_with_listlike_invalid_dtype(values, arg):
+ # https://github.com/pandas-dev/pandas/issues/32762
+ msg = "[Unexpected type|Cannot compare]"
+ with pytest.raises(TypeError, match=msg):
+ values.searchsorted(arg)
+
+
+@pytest.mark.parametrize("klass", [list, tuple, np.array, pd.Series])
+def test_period_index_construction_from_strings(klass):
+ # https://github.com/pandas-dev/pandas/issues/26109
+ strings = ["2020Q1", "2020Q2"] * 2
+ data = klass(strings)
+ result = PeriodIndex(data, freq="Q")
+ expected = PeriodIndex([Period(s) for s in strings])
+ tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
+def test_from_pandas_array(dtype):
+ # GH#24615
+ data = np.array([1, 2, 3], dtype=dtype)
+ arr = NumpyExtensionArray(data)
+
+ cls = {"M8[ns]": DatetimeArray, "m8[ns]": TimedeltaArray}[dtype]
+
+ result = cls(arr)
+ expected = cls(data)
+ tm.assert_extension_array_equal(result, expected)
+
+ result = cls._from_sequence(arr)
+ expected = cls._from_sequence(data)
+ tm.assert_extension_array_equal(result, expected)
+
+ func = {"M8[ns]": _sequence_to_dt64ns, "m8[ns]": sequence_to_td64ns}[dtype]
+ result = func(arr)[0]
+ expected = func(data)[0]
+ tm.assert_equal(result, expected)
+
+ func = {"M8[ns]": pd.to_datetime, "m8[ns]": pd.to_timedelta}[dtype]
+ result = func(arr).array
+ expected = func(data).array
+ tm.assert_equal(result, expected)
+
+ # Let's check the Indexes while we're here
+ idx_cls = {"M8[ns]": DatetimeIndex, "m8[ns]": TimedeltaIndex}[dtype]
+ result = idx_cls(arr)
+ expected = idx_cls(data)
+ tm.assert_index_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_datetimes.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_datetimes.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2d68a79f32d4c7b80013300c254c2ae73fff8bf
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_datetimes.py
@@ -0,0 +1,760 @@
+"""
+Tests for DatetimeArray
+"""
+from __future__ import annotations
+
+from datetime import timedelta
+import operator
+
+try:
+ from zoneinfo import ZoneInfo
+except ImportError:
+ # Cannot assign to a type
+ ZoneInfo = None # type: ignore[misc, assignment]
+
+import numpy as np
+import pytest
+
+from pandas._libs.tslibs import (
+ npy_unit_to_abbrev,
+ tz_compare,
+)
+
+from pandas.core.dtypes.dtypes import DatetimeTZDtype
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import (
+ DatetimeArray,
+ TimedeltaArray,
+)
+
+
+class TestNonNano:
+ @pytest.fixture(params=["s", "ms", "us"])
+ def unit(self, request):
+ """Fixture returning parametrized time units"""
+ return request.param
+
+ @pytest.fixture
+ def dtype(self, unit, tz_naive_fixture):
+ tz = tz_naive_fixture
+ if tz is None:
+ return np.dtype(f"datetime64[{unit}]")
+ else:
+ return DatetimeTZDtype(unit=unit, tz=tz)
+
+ @pytest.fixture
+ def dta_dti(self, unit, dtype):
+ tz = getattr(dtype, "tz", None)
+
+ dti = pd.date_range("2016-01-01", periods=55, freq="D", tz=tz)
+ if tz is None:
+ arr = np.asarray(dti).astype(f"M8[{unit}]")
+ else:
+ arr = np.asarray(dti.tz_convert("UTC").tz_localize(None)).astype(
+ f"M8[{unit}]"
+ )
+
+ dta = DatetimeArray._simple_new(arr, dtype=dtype)
+ return dta, dti
+
+ @pytest.fixture
+ def dta(self, dta_dti):
+ dta, dti = dta_dti
+ return dta
+
+ def test_non_nano(self, unit, dtype):
+ arr = np.arange(5, dtype=np.int64).view(f"M8[{unit}]")
+ dta = DatetimeArray._simple_new(arr, dtype=dtype)
+
+ assert dta.dtype == dtype
+ assert dta[0].unit == unit
+ assert tz_compare(dta.tz, dta[0].tz)
+ assert (dta[0] == dta[:1]).all()
+
+ @pytest.mark.parametrize(
+ "field", DatetimeArray._field_ops + DatetimeArray._bool_ops
+ )
+ def test_fields(self, unit, field, dtype, dta_dti):
+ dta, dti = dta_dti
+
+ assert (dti == dta).all()
+
+ res = getattr(dta, field)
+ expected = getattr(dti._data, field)
+ tm.assert_numpy_array_equal(res, expected)
+
+ def test_normalize(self, unit):
+ dti = pd.date_range("2016-01-01 06:00:00", periods=55, freq="D")
+ arr = np.asarray(dti).astype(f"M8[{unit}]")
+
+ dta = DatetimeArray._simple_new(arr, dtype=arr.dtype)
+
+ assert not dta.is_normalized
+
+ # TODO: simplify once we can just .astype to other unit
+ exp = np.asarray(dti.normalize()).astype(f"M8[{unit}]")
+ expected = DatetimeArray._simple_new(exp, dtype=exp.dtype)
+
+ res = dta.normalize()
+ tm.assert_extension_array_equal(res, expected)
+
+ def test_simple_new_requires_match(self, unit):
+ arr = np.arange(5, dtype=np.int64).view(f"M8[{unit}]")
+ dtype = DatetimeTZDtype(unit, "UTC")
+
+ dta = DatetimeArray._simple_new(arr, dtype=dtype)
+ assert dta.dtype == dtype
+
+ wrong = DatetimeTZDtype("ns", "UTC")
+ with pytest.raises(AssertionError, match=""):
+ DatetimeArray._simple_new(arr, dtype=wrong)
+
+ def test_std_non_nano(self, unit):
+ dti = pd.date_range("2016-01-01", periods=55, freq="D")
+ arr = np.asarray(dti).astype(f"M8[{unit}]")
+
+ dta = DatetimeArray._simple_new(arr, dtype=arr.dtype)
+
+ # we should match the nano-reso std, but floored to our reso.
+ res = dta.std()
+ assert res._creso == dta._creso
+ assert res == dti.std().floor(unit)
+
+ @pytest.mark.filterwarnings("ignore:Converting to PeriodArray.*:UserWarning")
+ def test_to_period(self, dta_dti):
+ dta, dti = dta_dti
+ result = dta.to_period("D")
+ expected = dti._data.to_period("D")
+
+ tm.assert_extension_array_equal(result, expected)
+
+ def test_iter(self, dta):
+ res = next(iter(dta))
+ expected = dta[0]
+
+ assert type(res) is pd.Timestamp
+ assert res._value == expected._value
+ assert res._creso == expected._creso
+ assert res == expected
+
+ def test_astype_object(self, dta):
+ result = dta.astype(object)
+ assert all(x._creso == dta._creso for x in result)
+ assert all(x == y for x, y in zip(result, dta))
+
+ def test_to_pydatetime(self, dta_dti):
+ dta, dti = dta_dti
+
+ result = dta.to_pydatetime()
+ expected = dti.to_pydatetime()
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("meth", ["time", "timetz", "date"])
+ def test_time_date(self, dta_dti, meth):
+ dta, dti = dta_dti
+
+ result = getattr(dta, meth)
+ expected = getattr(dti, meth)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_format_native_types(self, unit, dtype, dta_dti):
+ # In this case we should get the same formatted values with our nano
+ # version dti._data as we do with the non-nano dta
+ dta, dti = dta_dti
+
+ res = dta._format_native_types()
+ exp = dti._data._format_native_types()
+ tm.assert_numpy_array_equal(res, exp)
+
+ def test_repr(self, dta_dti, unit):
+ dta, dti = dta_dti
+
+ assert repr(dta) == repr(dti._data).replace("[ns", f"[{unit}")
+
+ # TODO: tests with td64
+ def test_compare_mismatched_resolutions(self, comparison_op):
+ # comparison that numpy gets wrong bc of silent overflows
+ op = comparison_op
+
+ iinfo = np.iinfo(np.int64)
+ vals = np.array([iinfo.min, iinfo.min + 1, iinfo.max], dtype=np.int64)
+
+ # Construct so that arr2[1] < arr[1] < arr[2] < arr2[2]
+ arr = np.array(vals).view("M8[ns]")
+ arr2 = arr.view("M8[s]")
+
+ left = DatetimeArray._simple_new(arr, dtype=arr.dtype)
+ right = DatetimeArray._simple_new(arr2, dtype=arr2.dtype)
+
+ if comparison_op is operator.eq:
+ expected = np.array([False, False, False])
+ elif comparison_op is operator.ne:
+ expected = np.array([True, True, True])
+ elif comparison_op in [operator.lt, operator.le]:
+ expected = np.array([False, False, True])
+ else:
+ expected = np.array([False, True, False])
+
+ result = op(left, right)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = op(left[1], right)
+ tm.assert_numpy_array_equal(result, expected)
+
+ if op not in [operator.eq, operator.ne]:
+ # check that numpy still gets this wrong; if it is fixed we may be
+ # able to remove compare_mismatched_resolutions
+ np_res = op(left._ndarray, right._ndarray)
+ tm.assert_numpy_array_equal(np_res[1:], ~expected[1:])
+
+ def test_add_mismatched_reso_doesnt_downcast(self):
+ # https://github.com/pandas-dev/pandas/pull/48748#issuecomment-1260181008
+ td = pd.Timedelta(microseconds=1)
+ dti = pd.date_range("2016-01-01", periods=3) - td
+ dta = dti._data.as_unit("us")
+
+ res = dta + td.as_unit("us")
+ # even though the result is an even number of days
+ # (so we _could_ downcast to unit="s"), we do not.
+ assert res.unit == "us"
+
+ @pytest.mark.parametrize(
+ "scalar",
+ [
+ timedelta(hours=2),
+ pd.Timedelta(hours=2),
+ np.timedelta64(2, "h"),
+ np.timedelta64(2 * 3600 * 1000, "ms"),
+ pd.offsets.Minute(120),
+ pd.offsets.Hour(2),
+ ],
+ )
+ def test_add_timedeltalike_scalar_mismatched_reso(self, dta_dti, scalar):
+ dta, dti = dta_dti
+
+ td = pd.Timedelta(scalar)
+ exp_reso = max(dta._creso, td._creso)
+ exp_unit = npy_unit_to_abbrev(exp_reso)
+
+ expected = (dti + td)._data.as_unit(exp_unit)
+ result = dta + scalar
+ tm.assert_extension_array_equal(result, expected)
+
+ result = scalar + dta
+ tm.assert_extension_array_equal(result, expected)
+
+ expected = (dti - td)._data.as_unit(exp_unit)
+ result = dta - scalar
+ tm.assert_extension_array_equal(result, expected)
+
+ def test_sub_datetimelike_scalar_mismatch(self):
+ dti = pd.date_range("2016-01-01", periods=3)
+ dta = dti._data.as_unit("us")
+
+ ts = dta[0].as_unit("s")
+
+ result = dta - ts
+ expected = (dti - dti[0])._data.as_unit("us")
+ assert result.dtype == "m8[us]"
+ tm.assert_extension_array_equal(result, expected)
+
+ def test_sub_datetime64_reso_mismatch(self):
+ dti = pd.date_range("2016-01-01", periods=3)
+ left = dti._data.as_unit("s")
+ right = left.as_unit("ms")
+
+ result = left - right
+ exp_values = np.array([0, 0, 0], dtype="m8[ms]")
+ expected = TimedeltaArray._simple_new(
+ exp_values,
+ dtype=exp_values.dtype,
+ )
+ tm.assert_extension_array_equal(result, expected)
+ result2 = right - left
+ tm.assert_extension_array_equal(result2, expected)
+
+
+class TestDatetimeArrayComparisons:
+ # TODO: merge this into tests/arithmetic/test_datetime64 once it is
+ # sufficiently robust
+
+ def test_cmp_dt64_arraylike_tznaive(self, comparison_op):
+ # arbitrary tz-naive DatetimeIndex
+ op = comparison_op
+
+ dti = pd.date_range("2016-01-1", freq="MS", periods=9, tz=None)
+ arr = DatetimeArray(dti)
+ assert arr.freq == dti.freq
+ assert arr.tz == dti.tz
+
+ right = dti
+
+ expected = np.ones(len(arr), dtype=bool)
+ if comparison_op.__name__ in ["ne", "gt", "lt"]:
+ # for these the comparisons should be all-False
+ expected = ~expected
+
+ result = op(arr, arr)
+ tm.assert_numpy_array_equal(result, expected)
+ for other in [
+ right,
+ np.array(right),
+ list(right),
+ tuple(right),
+ right.astype(object),
+ ]:
+ result = op(arr, other)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = op(other, arr)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+class TestDatetimeArray:
+ def test_astype_non_nano_tznaive(self):
+ dti = pd.date_range("2016-01-01", periods=3)
+
+ res = dti.astype("M8[s]")
+ assert res.dtype == "M8[s]"
+
+ dta = dti._data
+ res = dta.astype("M8[s]")
+ assert res.dtype == "M8[s]"
+ assert isinstance(res, pd.core.arrays.DatetimeArray) # used to be ndarray
+
+ def test_astype_non_nano_tzaware(self):
+ dti = pd.date_range("2016-01-01", periods=3, tz="UTC")
+
+ res = dti.astype("M8[s, US/Pacific]")
+ assert res.dtype == "M8[s, US/Pacific]"
+
+ dta = dti._data
+ res = dta.astype("M8[s, US/Pacific]")
+ assert res.dtype == "M8[s, US/Pacific]"
+
+ # from non-nano to non-nano, preserving reso
+ res2 = res.astype("M8[s, UTC]")
+ assert res2.dtype == "M8[s, UTC]"
+ assert not tm.shares_memory(res2, res)
+
+ res3 = res.astype("M8[s, UTC]", copy=False)
+ assert res2.dtype == "M8[s, UTC]"
+ assert tm.shares_memory(res3, res)
+
+ def test_astype_to_same(self):
+ arr = DatetimeArray._from_sequence(
+ ["2000"], dtype=DatetimeTZDtype(tz="US/Central")
+ )
+ result = arr.astype(DatetimeTZDtype(tz="US/Central"), copy=False)
+ assert result is arr
+
+ @pytest.mark.parametrize("dtype", ["datetime64[ns]", "datetime64[ns, UTC]"])
+ @pytest.mark.parametrize(
+ "other", ["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, CET]"]
+ )
+ def test_astype_copies(self, dtype, other):
+ # https://github.com/pandas-dev/pandas/pull/32490
+ ser = pd.Series([1, 2], dtype=dtype)
+ orig = ser.copy()
+
+ err = False
+ if (dtype == "datetime64[ns]") ^ (other == "datetime64[ns]"):
+ # deprecated in favor of tz_localize
+ err = True
+
+ if err:
+ if dtype == "datetime64[ns]":
+ msg = "Use obj.tz_localize instead or series.dt.tz_localize instead"
+ else:
+ msg = "from timezone-aware dtype to timezone-naive dtype"
+ with pytest.raises(TypeError, match=msg):
+ ser.astype(other)
+ else:
+ t = ser.astype(other)
+ t[:] = pd.NaT
+ tm.assert_series_equal(ser, orig)
+
+ @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
+ def test_astype_int(self, dtype):
+ arr = DatetimeArray._from_sequence([pd.Timestamp("2000"), pd.Timestamp("2001")])
+
+ if np.dtype(dtype) != np.int64:
+ with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):
+ arr.astype(dtype)
+ return
+
+ result = arr.astype(dtype)
+ expected = arr._ndarray.view("i8")
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_astype_to_sparse_dt64(self):
+ # GH#50082
+ dti = pd.date_range("2016-01-01", periods=4)
+ dta = dti._data
+ result = dta.astype("Sparse[datetime64[ns]]")
+
+ assert result.dtype == "Sparse[datetime64[ns]]"
+ assert (result == dta).all()
+
+ def test_tz_setter_raises(self):
+ arr = DatetimeArray._from_sequence(
+ ["2000"], dtype=DatetimeTZDtype(tz="US/Central")
+ )
+ with pytest.raises(AttributeError, match="tz_localize"):
+ arr.tz = "UTC"
+
+ def test_setitem_str_impute_tz(self, tz_naive_fixture):
+ # Like for getitem, if we are passed a naive-like string, we impute
+ # our own timezone.
+ tz = tz_naive_fixture
+
+ data = np.array([1, 2, 3], dtype="M8[ns]")
+ dtype = data.dtype if tz is None else DatetimeTZDtype(tz=tz)
+ arr = DatetimeArray(data, dtype=dtype)
+ expected = arr.copy()
+
+ ts = pd.Timestamp("2020-09-08 16:50").tz_localize(tz)
+ setter = str(ts.tz_localize(None))
+
+ # Setting a scalar tznaive string
+ expected[0] = ts
+ arr[0] = setter
+ tm.assert_equal(arr, expected)
+
+ # Setting a listlike of tznaive strings
+ expected[1] = ts
+ arr[:2] = [setter, setter]
+ tm.assert_equal(arr, expected)
+
+ def test_setitem_different_tz_raises(self):
+ # pre-2.0 we required exact tz match, in 2.0 we require only
+ # tzawareness-match
+ data = np.array([1, 2, 3], dtype="M8[ns]")
+ arr = DatetimeArray(data, copy=False, dtype=DatetimeTZDtype(tz="US/Central"))
+ with pytest.raises(TypeError, match="Cannot compare tz-naive and tz-aware"):
+ arr[0] = pd.Timestamp("2000")
+
+ ts = pd.Timestamp("2000", tz="US/Eastern")
+ arr[0] = ts
+ assert arr[0] == ts.tz_convert("US/Central")
+
+ def test_setitem_clears_freq(self):
+ a = DatetimeArray(pd.date_range("2000", periods=2, freq="D", tz="US/Central"))
+ a[0] = pd.Timestamp("2000", tz="US/Central")
+ assert a.freq is None
+
+ @pytest.mark.parametrize(
+ "obj",
+ [
+ pd.Timestamp("2021-01-01"),
+ pd.Timestamp("2021-01-01").to_datetime64(),
+ pd.Timestamp("2021-01-01").to_pydatetime(),
+ ],
+ )
+ def test_setitem_objects(self, obj):
+ # make sure we accept datetime64 and datetime in addition to Timestamp
+ dti = pd.date_range("2000", periods=2, freq="D")
+ arr = dti._data
+
+ arr[0] = obj
+ assert arr[0] == obj
+
+ def test_repeat_preserves_tz(self):
+ dti = pd.date_range("2000", periods=2, freq="D", tz="US/Central")
+ arr = DatetimeArray(dti)
+
+ repeated = arr.repeat([1, 1])
+
+ # preserves tz and values, but not freq
+ expected = DatetimeArray(arr.asi8, freq=None, dtype=arr.dtype)
+ tm.assert_equal(repeated, expected)
+
+ def test_value_counts_preserves_tz(self):
+ dti = pd.date_range("2000", periods=2, freq="D", tz="US/Central")
+ arr = DatetimeArray(dti).repeat([4, 3])
+
+ result = arr.value_counts()
+
+ # Note: not tm.assert_index_equal, since `freq`s do not match
+ assert result.index.equals(dti)
+
+ arr[-2] = pd.NaT
+ result = arr.value_counts(dropna=False)
+ expected = pd.Series([4, 2, 1], index=[dti[0], dti[1], pd.NaT], name="count")
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("method", ["pad", "backfill"])
+ def test_fillna_preserves_tz(self, method):
+ dti = pd.date_range("2000-01-01", periods=5, freq="D", tz="US/Central")
+ arr = DatetimeArray(dti, copy=True)
+ arr[2] = pd.NaT
+
+ fill_val = dti[1] if method == "pad" else dti[3]
+ expected = DatetimeArray._from_sequence(
+ [dti[0], dti[1], fill_val, dti[3], dti[4]],
+ dtype=DatetimeTZDtype(tz="US/Central"),
+ )
+
+ result = arr._pad_or_backfill(method=method)
+ tm.assert_extension_array_equal(result, expected)
+
+ # assert that arr and dti were not modified in-place
+ assert arr[2] is pd.NaT
+ assert dti[2] == pd.Timestamp("2000-01-03", tz="US/Central")
+
+ def test_fillna_2d(self):
+ dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
+ dta = dti._data.reshape(3, 2).copy()
+ dta[0, 1] = pd.NaT
+ dta[1, 0] = pd.NaT
+
+ res1 = dta._pad_or_backfill(method="pad")
+ expected1 = dta.copy()
+ expected1[1, 0] = dta[0, 0]
+ tm.assert_extension_array_equal(res1, expected1)
+
+ res2 = dta._pad_or_backfill(method="backfill")
+ expected2 = dta.copy()
+ expected2 = dta.copy()
+ expected2[1, 0] = dta[2, 0]
+ expected2[0, 1] = dta[1, 1]
+ tm.assert_extension_array_equal(res2, expected2)
+
+ # with different ordering for underlying ndarray; behavior should
+ # be unchanged
+ dta2 = dta._from_backing_data(dta._ndarray.copy(order="F"))
+ assert dta2._ndarray.flags["F_CONTIGUOUS"]
+ assert not dta2._ndarray.flags["C_CONTIGUOUS"]
+ tm.assert_extension_array_equal(dta, dta2)
+
+ res3 = dta2._pad_or_backfill(method="pad")
+ tm.assert_extension_array_equal(res3, expected1)
+
+ res4 = dta2._pad_or_backfill(method="backfill")
+ tm.assert_extension_array_equal(res4, expected2)
+
+ # test the DataFrame method while we're here
+ df = pd.DataFrame(dta)
+ res = df.ffill()
+ expected = pd.DataFrame(expected1)
+ tm.assert_frame_equal(res, expected)
+
+ res = df.bfill()
+ expected = pd.DataFrame(expected2)
+ tm.assert_frame_equal(res, expected)
+
+ def test_array_interface_tz(self):
+ tz = "US/Central"
+ data = DatetimeArray(pd.date_range("2017", periods=2, tz=tz))
+ result = np.asarray(data)
+
+ expected = np.array(
+ [
+ pd.Timestamp("2017-01-01T00:00:00", tz=tz),
+ pd.Timestamp("2017-01-02T00:00:00", tz=tz),
+ ],
+ dtype=object,
+ )
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.asarray(data, dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.asarray(data, dtype="M8[ns]")
+
+ expected = np.array(
+ ["2017-01-01T06:00:00", "2017-01-02T06:00:00"], dtype="M8[ns]"
+ )
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_array_interface(self):
+ data = DatetimeArray(pd.date_range("2017", periods=2))
+ expected = np.array(
+ ["2017-01-01T00:00:00", "2017-01-02T00:00:00"], dtype="datetime64[ns]"
+ )
+
+ result = np.asarray(data)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.asarray(data, dtype=object)
+ expected = np.array(
+ [pd.Timestamp("2017-01-01T00:00:00"), pd.Timestamp("2017-01-02T00:00:00")],
+ dtype=object,
+ )
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("index", [True, False])
+ def test_searchsorted_different_tz(self, index):
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ arr = DatetimeArray(data, freq="D").tz_localize("Asia/Tokyo")
+ if index:
+ arr = pd.Index(arr)
+
+ expected = arr.searchsorted(arr[2])
+ result = arr.searchsorted(arr[2].tz_convert("UTC"))
+ assert result == expected
+
+ expected = arr.searchsorted(arr[2:6])
+ result = arr.searchsorted(arr[2:6].tz_convert("UTC"))
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("index", [True, False])
+ def test_searchsorted_tzawareness_compat(self, index):
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ arr = DatetimeArray(data, freq="D")
+ if index:
+ arr = pd.Index(arr)
+
+ mismatch = arr.tz_localize("Asia/Tokyo")
+
+ msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
+ with pytest.raises(TypeError, match=msg):
+ arr.searchsorted(mismatch[0])
+ with pytest.raises(TypeError, match=msg):
+ arr.searchsorted(mismatch)
+
+ with pytest.raises(TypeError, match=msg):
+ mismatch.searchsorted(arr[0])
+ with pytest.raises(TypeError, match=msg):
+ mismatch.searchsorted(arr)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ 1,
+ np.int64(1),
+ 1.0,
+ np.timedelta64("NaT"),
+ pd.Timedelta(days=2),
+ "invalid",
+ np.arange(10, dtype="i8") * 24 * 3600 * 10**9,
+ np.arange(10).view("timedelta64[ns]") * 24 * 3600 * 10**9,
+ pd.Timestamp("2021-01-01").to_period("D"),
+ ],
+ )
+ @pytest.mark.parametrize("index", [True, False])
+ def test_searchsorted_invalid_types(self, other, index):
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ arr = DatetimeArray(data, freq="D")
+ if index:
+ arr = pd.Index(arr)
+
+ msg = "|".join(
+ [
+ "searchsorted requires compatible dtype or scalar",
+ "value should be a 'Timestamp', 'NaT', or array of those. Got",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ arr.searchsorted(other)
+
+ def test_shift_fill_value(self):
+ dti = pd.date_range("2016-01-01", periods=3)
+
+ dta = dti._data
+ expected = DatetimeArray(np.roll(dta._ndarray, 1))
+
+ fv = dta[-1]
+ for fill_value in [fv, fv.to_pydatetime(), fv.to_datetime64()]:
+ result = dta.shift(1, fill_value=fill_value)
+ tm.assert_datetime_array_equal(result, expected)
+
+ dta = dta.tz_localize("UTC")
+ expected = expected.tz_localize("UTC")
+ fv = dta[-1]
+ for fill_value in [fv, fv.to_pydatetime()]:
+ result = dta.shift(1, fill_value=fill_value)
+ tm.assert_datetime_array_equal(result, expected)
+
+ def test_shift_value_tzawareness_mismatch(self):
+ dti = pd.date_range("2016-01-01", periods=3)
+
+ dta = dti._data
+
+ fv = dta[-1].tz_localize("UTC")
+ for invalid in [fv, fv.to_pydatetime()]:
+ with pytest.raises(TypeError, match="Cannot compare"):
+ dta.shift(1, fill_value=invalid)
+
+ dta = dta.tz_localize("UTC")
+ fv = dta[-1].tz_localize(None)
+ for invalid in [fv, fv.to_pydatetime(), fv.to_datetime64()]:
+ with pytest.raises(TypeError, match="Cannot compare"):
+ dta.shift(1, fill_value=invalid)
+
+ def test_shift_requires_tzmatch(self):
+ # pre-2.0 we required exact tz match, in 2.0 we require just
+ # matching tzawareness
+ dti = pd.date_range("2016-01-01", periods=3, tz="UTC")
+ dta = dti._data
+
+ fill_value = pd.Timestamp("2020-10-18 18:44", tz="US/Pacific")
+
+ result = dta.shift(1, fill_value=fill_value)
+ expected = dta.shift(1, fill_value=fill_value.tz_convert("UTC"))
+ tm.assert_equal(result, expected)
+
+ def test_tz_localize_t2d(self):
+ dti = pd.date_range("1994-05-12", periods=12, tz="US/Pacific")
+ dta = dti._data.reshape(3, 4)
+ result = dta.tz_localize(None)
+
+ expected = dta.ravel().tz_localize(None).reshape(dta.shape)
+ tm.assert_datetime_array_equal(result, expected)
+
+ roundtrip = expected.tz_localize("US/Pacific")
+ tm.assert_datetime_array_equal(roundtrip, dta)
+
+ easts = ["US/Eastern", "dateutil/US/Eastern"]
+ if ZoneInfo is not None:
+ try:
+ tz = ZoneInfo("US/Eastern")
+ except KeyError:
+ # no tzdata
+ pass
+ else:
+ # Argument 1 to "append" of "list" has incompatible type "ZoneInfo";
+ # expected "str"
+ easts.append(tz) # type: ignore[arg-type]
+
+ @pytest.mark.parametrize("tz", easts)
+ def test_iter_zoneinfo_fold(self, tz):
+ # GH#49684
+ utc_vals = np.array(
+ [1320552000, 1320555600, 1320559200, 1320562800], dtype=np.int64
+ )
+ utc_vals *= 1_000_000_000
+
+ dta = DatetimeArray(utc_vals).tz_localize("UTC").tz_convert(tz)
+
+ left = dta[2]
+ right = list(dta)[2]
+ assert str(left) == str(right)
+ # previously there was a bug where with non-pytz right would be
+ # Timestamp('2011-11-06 01:00:00-0400', tz='US/Eastern')
+ # while left would be
+ # Timestamp('2011-11-06 01:00:00-0500', tz='US/Eastern')
+ # The .value's would match (so they would compare as equal),
+ # but the folds would not
+ assert left.utcoffset() == right.utcoffset()
+
+ # The same bug in ints_to_pydatetime affected .astype, so we test
+ # that here.
+ right2 = dta.astype(object)[2]
+ assert str(left) == str(right2)
+ assert left.utcoffset() == right2.utcoffset()
+
+
+def test_factorize_sort_without_freq():
+ dta = DatetimeArray._from_sequence([0, 2, 1])
+
+ msg = r"call pd.factorize\(obj, sort=True\) instead"
+ with pytest.raises(NotImplementedError, match=msg):
+ dta.factorize(sort=True)
+
+ # Do TimedeltaArray while we're here
+ tda = dta - dta[0]
+ with pytest.raises(NotImplementedError, match=msg):
+ tda.factorize(sort=True)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_ndarray_backed.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_ndarray_backed.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fe7cc9b03e8a6cef04558958ed949a0239a96cc
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_ndarray_backed.py
@@ -0,0 +1,75 @@
+"""
+Tests for subclasses of NDArrayBackedExtensionArray
+"""
+import numpy as np
+
+from pandas import (
+ CategoricalIndex,
+ date_range,
+)
+from pandas.core.arrays import (
+ Categorical,
+ DatetimeArray,
+ NumpyExtensionArray,
+ TimedeltaArray,
+)
+
+
+class TestEmpty:
+ def test_empty_categorical(self):
+ ci = CategoricalIndex(["a", "b", "c"], ordered=True)
+ dtype = ci.dtype
+
+ # case with int8 codes
+ shape = (4,)
+ result = Categorical._empty(shape, dtype=dtype)
+ assert isinstance(result, Categorical)
+ assert result.shape == shape
+ assert result._ndarray.dtype == np.int8
+
+ # case where repr would segfault if we didn't override base implementation
+ result = Categorical._empty((4096,), dtype=dtype)
+ assert isinstance(result, Categorical)
+ assert result.shape == (4096,)
+ assert result._ndarray.dtype == np.int8
+ repr(result)
+
+ # case with int16 codes
+ ci = CategoricalIndex(list(range(512)) * 4, ordered=False)
+ dtype = ci.dtype
+ result = Categorical._empty(shape, dtype=dtype)
+ assert isinstance(result, Categorical)
+ assert result.shape == shape
+ assert result._ndarray.dtype == np.int16
+
+ def test_empty_dt64tz(self):
+ dti = date_range("2016-01-01", periods=2, tz="Asia/Tokyo")
+ dtype = dti.dtype
+
+ shape = (0,)
+ result = DatetimeArray._empty(shape, dtype=dtype)
+ assert result.dtype == dtype
+ assert isinstance(result, DatetimeArray)
+ assert result.shape == shape
+
+ def test_empty_dt64(self):
+ shape = (3, 9)
+ result = DatetimeArray._empty(shape, dtype="datetime64[ns]")
+ assert isinstance(result, DatetimeArray)
+ assert result.shape == shape
+
+ def test_empty_td64(self):
+ shape = (3, 9)
+ result = TimedeltaArray._empty(shape, dtype="m8[ns]")
+ assert isinstance(result, TimedeltaArray)
+ assert result.shape == shape
+
+ def test_empty_pandas_array(self):
+ arr = NumpyExtensionArray(np.array([1, 2]))
+ dtype = arr.dtype
+
+ shape = (3, 9)
+ result = NumpyExtensionArray._empty(shape, dtype=dtype)
+ assert isinstance(result, NumpyExtensionArray)
+ assert result.dtype == dtype
+ assert result.shape == shape
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_period.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_period.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1e954bc2ebe2d0a917550ef75afee1c003bae3e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_period.py
@@ -0,0 +1,184 @@
+import numpy as np
+import pytest
+
+from pandas._libs.tslibs import iNaT
+from pandas._libs.tslibs.period import IncompatibleFrequency
+
+from pandas.core.dtypes.base import _registry as registry
+from pandas.core.dtypes.dtypes import PeriodDtype
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import PeriodArray
+
+# ----------------------------------------------------------------------------
+# Dtype
+
+
+def test_registered():
+ assert PeriodDtype in registry.dtypes
+ result = registry.find("Period[D]")
+ expected = PeriodDtype("D")
+ assert result == expected
+
+
+# ----------------------------------------------------------------------------
+# period_array
+
+
+def test_asi8():
+ result = PeriodArray._from_sequence(["2000", "2001", None], dtype="period[D]").asi8
+ expected = np.array([10957, 11323, iNaT])
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_take_raises():
+ arr = PeriodArray._from_sequence(["2000", "2001"], dtype="period[D]")
+ with pytest.raises(IncompatibleFrequency, match="freq"):
+ arr.take([0, -1], allow_fill=True, fill_value=pd.Period("2000", freq="W"))
+
+ msg = "value should be a 'Period' or 'NaT'. Got 'str' instead"
+ with pytest.raises(TypeError, match=msg):
+ arr.take([0, -1], allow_fill=True, fill_value="foo")
+
+
+def test_fillna_raises():
+ arr = PeriodArray._from_sequence(["2000", "2001", "2002"], dtype="period[D]")
+ with pytest.raises(ValueError, match="Length"):
+ arr.fillna(arr[:2])
+
+
+def test_fillna_copies():
+ arr = PeriodArray._from_sequence(["2000", "2001", "2002"], dtype="period[D]")
+ result = arr.fillna(pd.Period("2000", "D"))
+ assert result is not arr
+
+
+# ----------------------------------------------------------------------------
+# setitem
+
+
+@pytest.mark.parametrize(
+ "key, value, expected",
+ [
+ ([0], pd.Period("2000", "D"), [10957, 1, 2]),
+ ([0], None, [iNaT, 1, 2]),
+ ([0], np.nan, [iNaT, 1, 2]),
+ ([0, 1, 2], pd.Period("2000", "D"), [10957] * 3),
+ (
+ [0, 1, 2],
+ [pd.Period("2000", "D"), pd.Period("2001", "D"), pd.Period("2002", "D")],
+ [10957, 11323, 11688],
+ ),
+ ],
+)
+def test_setitem(key, value, expected):
+ arr = PeriodArray(np.arange(3), dtype="period[D]")
+ expected = PeriodArray(expected, dtype="period[D]")
+ arr[key] = value
+ tm.assert_period_array_equal(arr, expected)
+
+
+def test_setitem_raises_incompatible_freq():
+ arr = PeriodArray(np.arange(3), dtype="period[D]")
+ with pytest.raises(IncompatibleFrequency, match="freq"):
+ arr[0] = pd.Period("2000", freq="A")
+
+ other = PeriodArray._from_sequence(["2000", "2001"], dtype="period[A]")
+ with pytest.raises(IncompatibleFrequency, match="freq"):
+ arr[[0, 1]] = other
+
+
+def test_setitem_raises_length():
+ arr = PeriodArray(np.arange(3), dtype="period[D]")
+ with pytest.raises(ValueError, match="length"):
+ arr[[0, 1]] = [pd.Period("2000", freq="D")]
+
+
+def test_setitem_raises_type():
+ arr = PeriodArray(np.arange(3), dtype="period[D]")
+ with pytest.raises(TypeError, match="int"):
+ arr[0] = 1
+
+
+# ----------------------------------------------------------------------------
+# Ops
+
+
+def test_sub_period():
+ arr = PeriodArray._from_sequence(["2000", "2001"], dtype="period[D]")
+ other = pd.Period("2000", freq="M")
+ with pytest.raises(IncompatibleFrequency, match="freq"):
+ arr - other
+
+
+def test_sub_period_overflow():
+ # GH#47538
+ dti = pd.date_range("1677-09-22", periods=2, freq="D")
+ pi = dti.to_period("ns")
+
+ per = pd.Period._from_ordinal(10**14, pi.freq)
+
+ with pytest.raises(OverflowError, match="Overflow in int64 addition"):
+ pi - per
+
+ with pytest.raises(OverflowError, match="Overflow in int64 addition"):
+ per - pi
+
+
+# ----------------------------------------------------------------------------
+# Methods
+
+
+@pytest.mark.parametrize(
+ "other",
+ [
+ pd.Period("2000", freq="H"),
+ PeriodArray._from_sequence(["2000", "2001", "2000"], dtype="period[H]"),
+ ],
+)
+def test_where_different_freq_raises(other):
+ # GH#45768 The PeriodArray method raises, the Series method coerces
+ ser = pd.Series(
+ PeriodArray._from_sequence(["2000", "2001", "2002"], dtype="period[D]")
+ )
+ cond = np.array([True, False, True])
+
+ with pytest.raises(IncompatibleFrequency, match="freq"):
+ ser.array._where(cond, other)
+
+ res = ser.where(cond, other)
+ expected = ser.astype(object).where(cond, other)
+ tm.assert_series_equal(res, expected)
+
+
+# ----------------------------------------------------------------------------
+# Printing
+
+
+def test_repr_small():
+ arr = PeriodArray._from_sequence(["2000", "2001"], dtype="period[D]")
+ result = str(arr)
+ expected = (
+ "\n['2000-01-01', '2001-01-01']\nLength: 2, dtype: period[D]"
+ )
+ assert result == expected
+
+
+def test_repr_large():
+ arr = PeriodArray._from_sequence(["2000", "2001"] * 500, dtype="period[D]")
+ result = str(arr)
+ expected = (
+ "\n"
+ "['2000-01-01', '2001-01-01', '2000-01-01', '2001-01-01', "
+ "'2000-01-01',\n"
+ " '2001-01-01', '2000-01-01', '2001-01-01', '2000-01-01', "
+ "'2001-01-01',\n"
+ " ...\n"
+ " '2000-01-01', '2001-01-01', '2000-01-01', '2001-01-01', "
+ "'2000-01-01',\n"
+ " '2001-01-01', '2000-01-01', '2001-01-01', '2000-01-01', "
+ "'2001-01-01']\n"
+ "Length: 1000, dtype: period[D]"
+ )
+ assert result == expected
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_timedeltas.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_timedeltas.py
new file mode 100644
index 0000000000000000000000000000000000000000..1043c2ee6c9b6ff7f3ec2d43b9c2f7dba392e7fd
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/arrays/test_timedeltas.py
@@ -0,0 +1,311 @@
+from datetime import timedelta
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import Timedelta
+import pandas._testing as tm
+from pandas.core.arrays import (
+ DatetimeArray,
+ TimedeltaArray,
+)
+
+
+class TestNonNano:
+ @pytest.fixture(params=["s", "ms", "us"])
+ def unit(self, request):
+ return request.param
+
+ @pytest.fixture
+ def tda(self, unit):
+ arr = np.arange(5, dtype=np.int64).view(f"m8[{unit}]")
+ return TimedeltaArray._simple_new(arr, dtype=arr.dtype)
+
+ def test_non_nano(self, unit):
+ arr = np.arange(5, dtype=np.int64).view(f"m8[{unit}]")
+ tda = TimedeltaArray._simple_new(arr, dtype=arr.dtype)
+
+ assert tda.dtype == arr.dtype
+ assert tda[0].unit == unit
+
+ def test_as_unit_raises(self, tda):
+ # GH#50616
+ with pytest.raises(ValueError, match="Supported units"):
+ tda.as_unit("D")
+
+ tdi = pd.Index(tda)
+ with pytest.raises(ValueError, match="Supported units"):
+ tdi.as_unit("D")
+
+ @pytest.mark.parametrize("field", TimedeltaArray._field_ops)
+ def test_fields(self, tda, field):
+ as_nano = tda._ndarray.astype("m8[ns]")
+ tda_nano = TimedeltaArray._simple_new(as_nano, dtype=as_nano.dtype)
+
+ result = getattr(tda, field)
+ expected = getattr(tda_nano, field)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_to_pytimedelta(self, tda):
+ as_nano = tda._ndarray.astype("m8[ns]")
+ tda_nano = TimedeltaArray._simple_new(as_nano, dtype=as_nano.dtype)
+
+ result = tda.to_pytimedelta()
+ expected = tda_nano.to_pytimedelta()
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_total_seconds(self, unit, tda):
+ as_nano = tda._ndarray.astype("m8[ns]")
+ tda_nano = TimedeltaArray._simple_new(as_nano, dtype=as_nano.dtype)
+
+ result = tda.total_seconds()
+ expected = tda_nano.total_seconds()
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_timedelta_array_total_seconds(self):
+ # GH34290
+ expected = Timedelta("2 min").total_seconds()
+
+ result = pd.array([Timedelta("2 min")]).total_seconds()[0]
+ assert result == expected
+
+ def test_total_seconds_nanoseconds(self):
+ # issue #48521
+ start_time = pd.Series(["2145-11-02 06:00:00"]).astype("datetime64[ns]")
+ end_time = pd.Series(["2145-11-02 07:06:00"]).astype("datetime64[ns]")
+ expected = (end_time - start_time).values / np.timedelta64(1, "s")
+ result = (end_time - start_time).dt.total_seconds().values
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "nat", [np.datetime64("NaT", "ns"), np.datetime64("NaT", "us")]
+ )
+ def test_add_nat_datetimelike_scalar(self, nat, tda):
+ result = tda + nat
+ assert isinstance(result, DatetimeArray)
+ assert result._creso == tda._creso
+ assert result.isna().all()
+
+ result = nat + tda
+ assert isinstance(result, DatetimeArray)
+ assert result._creso == tda._creso
+ assert result.isna().all()
+
+ def test_add_pdnat(self, tda):
+ result = tda + pd.NaT
+ assert isinstance(result, TimedeltaArray)
+ assert result._creso == tda._creso
+ assert result.isna().all()
+
+ result = pd.NaT + tda
+ assert isinstance(result, TimedeltaArray)
+ assert result._creso == tda._creso
+ assert result.isna().all()
+
+ # TODO: 2022-07-11 this is the only test that gets to DTA.tz_convert
+ # or tz_localize with non-nano; implement tests specific to that.
+ def test_add_datetimelike_scalar(self, tda, tz_naive_fixture):
+ ts = pd.Timestamp("2016-01-01", tz=tz_naive_fixture).as_unit("ns")
+
+ expected = tda.as_unit("ns") + ts
+ res = tda + ts
+ tm.assert_extension_array_equal(res, expected)
+ res = ts + tda
+ tm.assert_extension_array_equal(res, expected)
+
+ ts += Timedelta(1) # case where we can't cast losslessly
+
+ exp_values = tda._ndarray + ts.asm8
+ expected = (
+ DatetimeArray._simple_new(exp_values, dtype=exp_values.dtype)
+ .tz_localize("UTC")
+ .tz_convert(ts.tz)
+ )
+
+ result = tda + ts
+ tm.assert_extension_array_equal(result, expected)
+
+ result = ts + tda
+ tm.assert_extension_array_equal(result, expected)
+
+ def test_mul_scalar(self, tda):
+ other = 2
+ result = tda * other
+ expected = TimedeltaArray._simple_new(tda._ndarray * other, dtype=tda.dtype)
+ tm.assert_extension_array_equal(result, expected)
+ assert result._creso == tda._creso
+
+ def test_mul_listlike(self, tda):
+ other = np.arange(len(tda))
+ result = tda * other
+ expected = TimedeltaArray._simple_new(tda._ndarray * other, dtype=tda.dtype)
+ tm.assert_extension_array_equal(result, expected)
+ assert result._creso == tda._creso
+
+ def test_mul_listlike_object(self, tda):
+ other = np.arange(len(tda))
+ result = tda * other.astype(object)
+ expected = TimedeltaArray._simple_new(tda._ndarray * other, dtype=tda.dtype)
+ tm.assert_extension_array_equal(result, expected)
+ assert result._creso == tda._creso
+
+ def test_div_numeric_scalar(self, tda):
+ other = 2
+ result = tda / other
+ expected = TimedeltaArray._simple_new(tda._ndarray / other, dtype=tda.dtype)
+ tm.assert_extension_array_equal(result, expected)
+ assert result._creso == tda._creso
+
+ def test_div_td_scalar(self, tda):
+ other = timedelta(seconds=1)
+ result = tda / other
+ expected = tda._ndarray / np.timedelta64(1, "s")
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_div_numeric_array(self, tda):
+ other = np.arange(len(tda))
+ result = tda / other
+ expected = TimedeltaArray._simple_new(tda._ndarray / other, dtype=tda.dtype)
+ tm.assert_extension_array_equal(result, expected)
+ assert result._creso == tda._creso
+
+ def test_div_td_array(self, tda):
+ other = tda._ndarray + tda._ndarray[-1]
+ result = tda / other
+ expected = tda._ndarray / other
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_add_timedeltaarraylike(self, tda):
+ tda_nano = tda.astype("m8[ns]")
+
+ expected = tda_nano * 2
+ res = tda_nano + tda
+ tm.assert_extension_array_equal(res, expected)
+ res = tda + tda_nano
+ tm.assert_extension_array_equal(res, expected)
+
+ expected = tda_nano * 0
+ res = tda - tda_nano
+ tm.assert_extension_array_equal(res, expected)
+
+ res = tda_nano - tda
+ tm.assert_extension_array_equal(res, expected)
+
+
+class TestTimedeltaArray:
+ @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
+ def test_astype_int(self, dtype):
+ arr = TimedeltaArray._from_sequence([Timedelta("1H"), Timedelta("2H")])
+
+ if np.dtype(dtype) != np.int64:
+ with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):
+ arr.astype(dtype)
+ return
+
+ result = arr.astype(dtype)
+ expected = arr._ndarray.view("i8")
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_setitem_clears_freq(self):
+ a = TimedeltaArray(pd.timedelta_range("1H", periods=2, freq="H"))
+ a[0] = Timedelta("1H")
+ assert a.freq is None
+
+ @pytest.mark.parametrize(
+ "obj",
+ [
+ Timedelta(seconds=1),
+ Timedelta(seconds=1).to_timedelta64(),
+ Timedelta(seconds=1).to_pytimedelta(),
+ ],
+ )
+ def test_setitem_objects(self, obj):
+ # make sure we accept timedelta64 and timedelta in addition to Timedelta
+ tdi = pd.timedelta_range("2 Days", periods=4, freq="H")
+ arr = TimedeltaArray(tdi, freq=tdi.freq)
+
+ arr[0] = obj
+ assert arr[0] == Timedelta(seconds=1)
+
+ @pytest.mark.parametrize(
+ "other",
+ [
+ 1,
+ np.int64(1),
+ 1.0,
+ np.datetime64("NaT"),
+ pd.Timestamp("2021-01-01"),
+ "invalid",
+ np.arange(10, dtype="i8") * 24 * 3600 * 10**9,
+ (np.arange(10) * 24 * 3600 * 10**9).view("datetime64[ns]"),
+ pd.Timestamp("2021-01-01").to_period("D"),
+ ],
+ )
+ @pytest.mark.parametrize("index", [True, False])
+ def test_searchsorted_invalid_types(self, other, index):
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
+ arr = TimedeltaArray(data, freq="D")
+ if index:
+ arr = pd.Index(arr)
+
+ msg = "|".join(
+ [
+ "searchsorted requires compatible dtype or scalar",
+ "value should be a 'Timedelta', 'NaT', or array of those. Got",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ arr.searchsorted(other)
+
+
+class TestUnaryOps:
+ def test_abs(self):
+ vals = np.array([-3600 * 10**9, "NaT", 7200 * 10**9], dtype="m8[ns]")
+ arr = TimedeltaArray(vals)
+
+ evals = np.array([3600 * 10**9, "NaT", 7200 * 10**9], dtype="m8[ns]")
+ expected = TimedeltaArray(evals)
+
+ result = abs(arr)
+ tm.assert_timedelta_array_equal(result, expected)
+
+ result2 = np.abs(arr)
+ tm.assert_timedelta_array_equal(result2, expected)
+
+ def test_pos(self):
+ vals = np.array([-3600 * 10**9, "NaT", 7200 * 10**9], dtype="m8[ns]")
+ arr = TimedeltaArray(vals)
+
+ result = +arr
+ tm.assert_timedelta_array_equal(result, arr)
+ assert not tm.shares_memory(result, arr)
+
+ result2 = np.positive(arr)
+ tm.assert_timedelta_array_equal(result2, arr)
+ assert not tm.shares_memory(result2, arr)
+
+ def test_neg(self):
+ vals = np.array([-3600 * 10**9, "NaT", 7200 * 10**9], dtype="m8[ns]")
+ arr = TimedeltaArray(vals)
+
+ evals = np.array([3600 * 10**9, "NaT", -7200 * 10**9], dtype="m8[ns]")
+ expected = TimedeltaArray(evals)
+
+ result = -arr
+ tm.assert_timedelta_array_equal(result, expected)
+
+ result2 = np.negative(arr)
+ tm.assert_timedelta_array_equal(result2, expected)
+
+ def test_neg_freq(self):
+ tdi = pd.timedelta_range("2 Days", periods=4, freq="H")
+ arr = TimedeltaArray(tdi, freq=tdi.freq)
+
+ expected = TimedeltaArray(-tdi._data, freq=-tdi.freq)
+
+ result = -arr
+ tm.assert_timedelta_array_equal(result, expected)
+
+ result2 = np.negative(arr)
+ tm.assert_timedelta_array_equal(result2, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad0b394105742ca5de92a03a3da2c569c38da469
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/common.py
@@ -0,0 +1,9 @@
+from typing import Any
+
+from pandas import Index
+
+
+def allow_na_ops(obj: Any) -> bool:
+ """Whether to skip test cases including NaN"""
+ is_bool_index = isinstance(obj, Index) and obj.inferred_type == "boolean"
+ return not is_bool_index and obj._can_hold_na
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_constructors.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_constructors.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e954891c2d982cd0bacf7396813e1cc865b8f0b
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_constructors.py
@@ -0,0 +1,174 @@
+from datetime import datetime
+import sys
+
+import numpy as np
+import pytest
+
+from pandas.compat import PYPY
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
+import pandas._testing as tm
+from pandas.core.accessor import PandasDelegate
+from pandas.core.base import (
+ NoNewAttributesMixin,
+ PandasObject,
+)
+
+
+def series_via_frame_from_dict(x, **kwargs):
+ return DataFrame({"a": x}, **kwargs)["a"]
+
+
+def series_via_frame_from_scalar(x, **kwargs):
+ return DataFrame(x, **kwargs)[0]
+
+
+@pytest.fixture(
+ params=[
+ Series,
+ series_via_frame_from_dict,
+ series_via_frame_from_scalar,
+ Index,
+ ],
+ ids=["Series", "DataFrame-dict", "DataFrame-array", "Index"],
+)
+def constructor(request):
+ return request.param
+
+
+class TestPandasDelegate:
+ class Delegator:
+ _properties = ["prop"]
+ _methods = ["test_method"]
+
+ def _set_prop(self, value):
+ self.prop = value
+
+ def _get_prop(self):
+ return self.prop
+
+ prop = property(_get_prop, _set_prop, doc="foo property")
+
+ def test_method(self, *args, **kwargs):
+ """a test method"""
+
+ class Delegate(PandasDelegate, PandasObject):
+ def __init__(self, obj) -> None:
+ self.obj = obj
+
+ def test_invalid_delegation(self):
+ # these show that in order for the delegation to work
+ # the _delegate_* methods need to be overridden to not raise
+ # a TypeError
+
+ self.Delegate._add_delegate_accessors(
+ delegate=self.Delegator,
+ accessors=self.Delegator._properties,
+ typ="property",
+ )
+ self.Delegate._add_delegate_accessors(
+ delegate=self.Delegator, accessors=self.Delegator._methods, typ="method"
+ )
+
+ delegate = self.Delegate(self.Delegator())
+
+ msg = "You cannot access the property prop"
+ with pytest.raises(TypeError, match=msg):
+ delegate.prop
+
+ msg = "The property prop cannot be set"
+ with pytest.raises(TypeError, match=msg):
+ delegate.prop = 5
+
+ msg = "You cannot access the property prop"
+ with pytest.raises(TypeError, match=msg):
+ delegate.prop
+
+ @pytest.mark.skipif(PYPY, reason="not relevant for PyPy")
+ def test_memory_usage(self):
+ # Delegate does not implement memory_usage.
+ # Check that we fall back to in-built `__sizeof__`
+ # GH 12924
+ delegate = self.Delegate(self.Delegator())
+ sys.getsizeof(delegate)
+
+
+class TestNoNewAttributesMixin:
+ def test_mixin(self):
+ class T(NoNewAttributesMixin):
+ pass
+
+ t = T()
+ assert not hasattr(t, "__frozen")
+
+ t.a = "test"
+ assert t.a == "test"
+
+ t._freeze()
+ assert "__frozen" in dir(t)
+ assert getattr(t, "__frozen")
+ msg = "You cannot add any new attribute"
+ with pytest.raises(AttributeError, match=msg):
+ t.b = "test"
+
+ assert not hasattr(t, "b")
+
+
+class TestConstruction:
+ # test certain constructor behaviours on dtype inference across Series,
+ # Index and DataFrame
+
+ @pytest.mark.parametrize(
+ "a",
+ [
+ np.array(["2263-01-01"], dtype="datetime64[D]"),
+ np.array([datetime(2263, 1, 1)], dtype=object),
+ np.array([np.datetime64("2263-01-01", "D")], dtype=object),
+ np.array(["2263-01-01"], dtype=object),
+ ],
+ ids=[
+ "datetime64[D]",
+ "object-datetime.datetime",
+ "object-numpy-scalar",
+ "object-string",
+ ],
+ )
+ def test_constructor_datetime_outofbound(self, a, constructor):
+ # GH-26853 (+ bug GH-26206 out of bound non-ns unit)
+
+ # No dtype specified (dtype inference)
+ # datetime64[non-ns] raise error, other cases result in object dtype
+ # and preserve original data
+ if a.dtype.kind == "M":
+ # Can't fit in nanosecond bounds -> get the nearest supported unit
+ result = constructor(a)
+ assert result.dtype == "M8[s]"
+ else:
+ result = constructor(a)
+ assert result.dtype == "object"
+ tm.assert_numpy_array_equal(result.to_numpy(), a)
+
+ # Explicit dtype specified
+ # Forced conversion fails for all -> all cases raise error
+ msg = "Out of bounds|Out of bounds .* present at position 0"
+ with pytest.raises(pd.errors.OutOfBoundsDatetime, match=msg):
+ constructor(a, dtype="datetime64[ns]")
+
+ def test_constructor_datetime_nonns(self, constructor):
+ arr = np.array(["2020-01-01T00:00:00.000000"], dtype="datetime64[us]")
+ dta = pd.core.arrays.DatetimeArray._simple_new(arr, dtype=arr.dtype)
+ expected = constructor(dta)
+ assert expected.dtype == arr.dtype
+
+ result = constructor(arr)
+ tm.assert_equal(result, expected)
+
+ # https://github.com/pandas-dev/pandas/issues/34843
+ arr.flags.writeable = False
+ result = constructor(arr)
+ tm.assert_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_conversion.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b9618bfb2abf3eb103b79e7812370195d4288e9
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_conversion.py
@@ -0,0 +1,547 @@
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.dtypes import DatetimeTZDtype
+
+import pandas as pd
+from pandas import (
+ CategoricalIndex,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ DatetimeArray,
+ IntervalArray,
+ NumpyExtensionArray,
+ PeriodArray,
+ SparseArray,
+ TimedeltaArray,
+)
+
+
+class TestToIterable:
+ # test that we convert an iterable to python types
+
+ dtypes = [
+ ("int8", int),
+ ("int16", int),
+ ("int32", int),
+ ("int64", int),
+ ("uint8", int),
+ ("uint16", int),
+ ("uint32", int),
+ ("uint64", int),
+ ("float16", float),
+ ("float32", float),
+ ("float64", float),
+ ("datetime64[ns]", Timestamp),
+ ("datetime64[ns, US/Eastern]", Timestamp),
+ ("timedelta64[ns]", Timedelta),
+ ]
+
+ @pytest.mark.parametrize("dtype, rdtype", dtypes)
+ @pytest.mark.parametrize(
+ "method",
+ [
+ lambda x: x.tolist(),
+ lambda x: x.to_list(),
+ lambda x: list(x),
+ lambda x: list(x.__iter__()),
+ ],
+ ids=["tolist", "to_list", "list", "iter"],
+ )
+ def test_iterable(self, index_or_series, method, dtype, rdtype):
+ # gh-10904
+ # gh-13258
+ # coerce iteration to underlying python / pandas types
+ typ = index_or_series
+ if dtype == "float16" and issubclass(typ, pd.Index):
+ with pytest.raises(NotImplementedError, match="float16 indexes are not "):
+ typ([1], dtype=dtype)
+ return
+ s = typ([1], dtype=dtype)
+ result = method(s)[0]
+ assert isinstance(result, rdtype)
+
+ @pytest.mark.parametrize(
+ "dtype, rdtype, obj",
+ [
+ ("object", object, "a"),
+ ("object", int, 1),
+ ("category", object, "a"),
+ ("category", int, 1),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "method",
+ [
+ lambda x: x.tolist(),
+ lambda x: x.to_list(),
+ lambda x: list(x),
+ lambda x: list(x.__iter__()),
+ ],
+ ids=["tolist", "to_list", "list", "iter"],
+ )
+ def test_iterable_object_and_category(
+ self, index_or_series, method, dtype, rdtype, obj
+ ):
+ # gh-10904
+ # gh-13258
+ # coerce iteration to underlying python / pandas types
+ typ = index_or_series
+ s = typ([obj], dtype=dtype)
+ result = method(s)[0]
+ assert isinstance(result, rdtype)
+
+ @pytest.mark.parametrize("dtype, rdtype", dtypes)
+ def test_iterable_items(self, dtype, rdtype):
+ # gh-13258
+ # test if items yields the correct boxed scalars
+ # this only applies to series
+ s = Series([1], dtype=dtype)
+ _, result = next(iter(s.items()))
+ assert isinstance(result, rdtype)
+
+ _, result = next(iter(s.items()))
+ assert isinstance(result, rdtype)
+
+ @pytest.mark.parametrize(
+ "dtype, rdtype", dtypes + [("object", int), ("category", int)]
+ )
+ def test_iterable_map(self, index_or_series, dtype, rdtype):
+ # gh-13236
+ # coerce iteration to underlying python / pandas types
+ typ = index_or_series
+ if dtype == "float16" and issubclass(typ, pd.Index):
+ with pytest.raises(NotImplementedError, match="float16 indexes are not "):
+ typ([1], dtype=dtype)
+ return
+ s = typ([1], dtype=dtype)
+ result = s.map(type)[0]
+ if not isinstance(rdtype, tuple):
+ rdtype = (rdtype,)
+ assert result in rdtype
+
+ @pytest.mark.parametrize(
+ "method",
+ [
+ lambda x: x.tolist(),
+ lambda x: x.to_list(),
+ lambda x: list(x),
+ lambda x: list(x.__iter__()),
+ ],
+ ids=["tolist", "to_list", "list", "iter"],
+ )
+ def test_categorial_datetimelike(self, method):
+ i = CategoricalIndex([Timestamp("1999-12-31"), Timestamp("2000-12-31")])
+
+ result = method(i)[0]
+ assert isinstance(result, Timestamp)
+
+ def test_iter_box(self):
+ vals = [Timestamp("2011-01-01"), Timestamp("2011-01-02")]
+ s = Series(vals)
+ assert s.dtype == "datetime64[ns]"
+ for res, exp in zip(s, vals):
+ assert isinstance(res, Timestamp)
+ assert res.tz is None
+ assert res == exp
+
+ vals = [
+ Timestamp("2011-01-01", tz="US/Eastern"),
+ Timestamp("2011-01-02", tz="US/Eastern"),
+ ]
+ s = Series(vals)
+
+ assert s.dtype == "datetime64[ns, US/Eastern]"
+ for res, exp in zip(s, vals):
+ assert isinstance(res, Timestamp)
+ assert res.tz == exp.tz
+ assert res == exp
+
+ # timedelta
+ vals = [Timedelta("1 days"), Timedelta("2 days")]
+ s = Series(vals)
+ assert s.dtype == "timedelta64[ns]"
+ for res, exp in zip(s, vals):
+ assert isinstance(res, Timedelta)
+ assert res == exp
+
+ # period
+ vals = [pd.Period("2011-01-01", freq="M"), pd.Period("2011-01-02", freq="M")]
+ s = Series(vals)
+ assert s.dtype == "Period[M]"
+ for res, exp in zip(s, vals):
+ assert isinstance(res, pd.Period)
+ assert res.freq == "M"
+ assert res == exp
+
+
+@pytest.mark.parametrize(
+ "arr, expected_type, dtype",
+ [
+ (np.array([0, 1], dtype=np.int64), np.ndarray, "int64"),
+ (np.array(["a", "b"]), np.ndarray, "object"),
+ (pd.Categorical(["a", "b"]), pd.Categorical, "category"),
+ (
+ pd.DatetimeIndex(["2017", "2018"], tz="US/Central"),
+ DatetimeArray,
+ "datetime64[ns, US/Central]",
+ ),
+ (
+ pd.PeriodIndex([2018, 2019], freq="A"),
+ PeriodArray,
+ pd.core.dtypes.dtypes.PeriodDtype("A-DEC"),
+ ),
+ (pd.IntervalIndex.from_breaks([0, 1, 2]), IntervalArray, "interval"),
+ (
+ pd.DatetimeIndex(["2017", "2018"]),
+ DatetimeArray,
+ "datetime64[ns]",
+ ),
+ (
+ pd.TimedeltaIndex([10**10]),
+ TimedeltaArray,
+ "m8[ns]",
+ ),
+ ],
+)
+def test_values_consistent(arr, expected_type, dtype):
+ l_values = Series(arr)._values
+ r_values = pd.Index(arr)._values
+ assert type(l_values) is expected_type
+ assert type(l_values) is type(r_values)
+
+ tm.assert_equal(l_values, r_values)
+
+
+@pytest.mark.parametrize("arr", [np.array([1, 2, 3])])
+def test_numpy_array(arr):
+ ser = Series(arr)
+ result = ser.array
+ expected = NumpyExtensionArray(arr)
+ tm.assert_extension_array_equal(result, expected)
+
+
+def test_numpy_array_all_dtypes(any_numpy_dtype):
+ ser = Series(dtype=any_numpy_dtype)
+ result = ser.array
+ if np.dtype(any_numpy_dtype).kind == "M":
+ assert isinstance(result, DatetimeArray)
+ elif np.dtype(any_numpy_dtype).kind == "m":
+ assert isinstance(result, TimedeltaArray)
+ else:
+ assert isinstance(result, NumpyExtensionArray)
+
+
+@pytest.mark.parametrize(
+ "arr, attr",
+ [
+ (pd.Categorical(["a", "b"]), "_codes"),
+ (PeriodArray._from_sequence(["2000", "2001"], dtype="period[D]"), "_ndarray"),
+ (pd.array([0, np.nan], dtype="Int64"), "_data"),
+ (IntervalArray.from_breaks([0, 1]), "_left"),
+ (SparseArray([0, 1]), "_sparse_values"),
+ (DatetimeArray(np.array([1, 2], dtype="datetime64[ns]")), "_ndarray"),
+ # tz-aware Datetime
+ (
+ DatetimeArray(
+ np.array(
+ ["2000-01-01T12:00:00", "2000-01-02T12:00:00"], dtype="M8[ns]"
+ ),
+ dtype=DatetimeTZDtype(tz="US/Central"),
+ ),
+ "_ndarray",
+ ),
+ ],
+)
+def test_array(arr, attr, index_or_series, request):
+ box = index_or_series
+
+ result = box(arr, copy=False).array
+
+ if attr:
+ arr = getattr(arr, attr)
+ result = getattr(result, attr)
+
+ assert result is arr
+
+
+def test_array_multiindex_raises():
+ idx = pd.MultiIndex.from_product([["A"], ["a", "b"]])
+ msg = "MultiIndex has no single backing array"
+ with pytest.raises(ValueError, match=msg):
+ idx.array
+
+
+@pytest.mark.parametrize(
+ "arr, expected",
+ [
+ (np.array([1, 2], dtype=np.int64), np.array([1, 2], dtype=np.int64)),
+ (pd.Categorical(["a", "b"]), np.array(["a", "b"], dtype=object)),
+ (
+ pd.core.arrays.period_array(["2000", "2001"], freq="D"),
+ np.array([pd.Period("2000", freq="D"), pd.Period("2001", freq="D")]),
+ ),
+ (pd.array([0, np.nan], dtype="Int64"), np.array([0, pd.NA], dtype=object)),
+ (
+ IntervalArray.from_breaks([0, 1, 2]),
+ np.array([pd.Interval(0, 1), pd.Interval(1, 2)], dtype=object),
+ ),
+ (SparseArray([0, 1]), np.array([0, 1], dtype=np.int64)),
+ # tz-naive datetime
+ (
+ DatetimeArray(np.array(["2000", "2001"], dtype="M8[ns]")),
+ np.array(["2000", "2001"], dtype="M8[ns]"),
+ ),
+ # tz-aware stays tz`-aware
+ (
+ DatetimeArray(
+ np.array(
+ ["2000-01-01T06:00:00", "2000-01-02T06:00:00"], dtype="M8[ns]"
+ ),
+ dtype=DatetimeTZDtype(tz="US/Central"),
+ ),
+ np.array(
+ [
+ Timestamp("2000-01-01", tz="US/Central"),
+ Timestamp("2000-01-02", tz="US/Central"),
+ ]
+ ),
+ ),
+ # Timedelta
+ (
+ TimedeltaArray(np.array([0, 3600000000000], dtype="i8"), freq="H"),
+ np.array([0, 3600000000000], dtype="m8[ns]"),
+ ),
+ # GH#26406 tz is preserved in Categorical[dt64tz]
+ (
+ pd.Categorical(date_range("2016-01-01", periods=2, tz="US/Pacific")),
+ np.array(
+ [
+ Timestamp("2016-01-01", tz="US/Pacific"),
+ Timestamp("2016-01-02", tz="US/Pacific"),
+ ]
+ ),
+ ),
+ ],
+)
+def test_to_numpy(arr, expected, index_or_series_or_array, request):
+ box = index_or_series_or_array
+
+ with tm.assert_produces_warning(None):
+ thing = box(arr)
+
+ if arr.dtype.name == "int64" and box is pd.array:
+ mark = pytest.mark.xfail(reason="thing is Int64 and to_numpy() returns object")
+ request.node.add_marker(mark)
+
+ result = thing.to_numpy()
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.asarray(thing)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("as_series", [True, False])
+@pytest.mark.parametrize(
+ "arr", [np.array([1, 2, 3], dtype="int64"), np.array(["a", "b", "c"], dtype=object)]
+)
+def test_to_numpy_copy(arr, as_series):
+ obj = pd.Index(arr, copy=False)
+ if as_series:
+ obj = Series(obj.values, copy=False)
+
+ # no copy by default
+ result = obj.to_numpy()
+ assert np.shares_memory(arr, result) is True
+
+ result = obj.to_numpy(copy=False)
+ assert np.shares_memory(arr, result) is True
+
+ # copy=True
+ result = obj.to_numpy(copy=True)
+ assert np.shares_memory(arr, result) is False
+
+
+@pytest.mark.parametrize("as_series", [True, False])
+def test_to_numpy_dtype(as_series):
+ tz = "US/Eastern"
+ obj = pd.DatetimeIndex(["2000", "2001"], tz=tz)
+ if as_series:
+ obj = Series(obj)
+
+ # preserve tz by default
+ result = obj.to_numpy()
+ expected = np.array(
+ [Timestamp("2000", tz=tz), Timestamp("2001", tz=tz)], dtype=object
+ )
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = obj.to_numpy(dtype="object")
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = obj.to_numpy(dtype="M8[ns]")
+ expected = np.array(["2000-01-01T05", "2001-01-01T05"], dtype="M8[ns]")
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "values, dtype, na_value, expected",
+ [
+ ([1, 2, None], "float64", 0, [1.0, 2.0, 0.0]),
+ (
+ [Timestamp("2000"), Timestamp("2000"), pd.NaT],
+ None,
+ Timestamp("2000"),
+ [np.datetime64("2000-01-01T00:00:00.000000000")] * 3,
+ ),
+ ],
+)
+def test_to_numpy_na_value_numpy_dtype(
+ index_or_series, values, dtype, na_value, expected
+):
+ obj = index_or_series(values)
+ result = obj.to_numpy(dtype=dtype, na_value=na_value)
+ expected = np.array(expected)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, multiindex, dtype, na_value, expected",
+ [
+ (
+ [1, 2, None, 4],
+ [(0, "a"), (0, "b"), (1, "b"), (1, "c")],
+ float,
+ None,
+ [1.0, 2.0, np.nan, 4.0],
+ ),
+ (
+ [1, 2, None, 4],
+ [(0, "a"), (0, "b"), (1, "b"), (1, "c")],
+ float,
+ np.nan,
+ [1.0, 2.0, np.nan, 4.0],
+ ),
+ (
+ [1.0, 2.0, np.nan, 4.0],
+ [("a", 0), ("a", 1), ("a", 2), ("b", 0)],
+ int,
+ 0,
+ [1, 2, 0, 4],
+ ),
+ (
+ [Timestamp("2000"), Timestamp("2000"), pd.NaT],
+ [(0, Timestamp("2021")), (0, Timestamp("2022")), (1, Timestamp("2000"))],
+ None,
+ Timestamp("2000"),
+ [np.datetime64("2000-01-01T00:00:00.000000000")] * 3,
+ ),
+ ],
+)
+def test_to_numpy_multiindex_series_na_value(
+ data, multiindex, dtype, na_value, expected
+):
+ index = pd.MultiIndex.from_tuples(multiindex)
+ series = Series(data, index=index)
+ result = series.to_numpy(dtype=dtype, na_value=na_value)
+ expected = np.array(expected)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_to_numpy_kwargs_raises():
+ # numpy
+ s = Series([1, 2, 3])
+ msg = r"to_numpy\(\) got an unexpected keyword argument 'foo'"
+ with pytest.raises(TypeError, match=msg):
+ s.to_numpy(foo=True)
+
+ # extension
+ s = Series([1, 2, 3], dtype="Int64")
+ with pytest.raises(TypeError, match=msg):
+ s.to_numpy(foo=True)
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ {"a": [1, 2, 3], "b": [1, 2, None]},
+ {"a": np.array([1, 2, 3]), "b": np.array([1, 2, np.nan])},
+ {"a": pd.array([1, 2, 3]), "b": pd.array([1, 2, None])},
+ ],
+)
+@pytest.mark.parametrize("dtype, na_value", [(float, np.nan), (object, None)])
+def test_to_numpy_dataframe_na_value(data, dtype, na_value):
+ # https://github.com/pandas-dev/pandas/issues/33820
+ df = pd.DataFrame(data)
+ result = df.to_numpy(dtype=dtype, na_value=na_value)
+ expected = np.array([[1, 1], [2, 2], [3, na_value]], dtype=dtype)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, expected",
+ [
+ (
+ {"a": pd.array([1, 2, None])},
+ np.array([[1.0], [2.0], [np.nan]], dtype=float),
+ ),
+ (
+ {"a": [1, 2, 3], "b": [1, 2, 3]},
+ np.array([[1, 1], [2, 2], [3, 3]], dtype=float),
+ ),
+ ],
+)
+def test_to_numpy_dataframe_single_block(data, expected):
+ # https://github.com/pandas-dev/pandas/issues/33820
+ df = pd.DataFrame(data)
+ result = df.to_numpy(dtype=float, na_value=np.nan)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_to_numpy_dataframe_single_block_no_mutate():
+ # https://github.com/pandas-dev/pandas/issues/33820
+ result = pd.DataFrame(np.array([1.0, 2.0, np.nan]))
+ expected = pd.DataFrame(np.array([1.0, 2.0, np.nan]))
+ result.to_numpy(na_value=0.0)
+ tm.assert_frame_equal(result, expected)
+
+
+class TestAsArray:
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
+ def test_asarray_object_dt64(self, tz):
+ ser = Series(date_range("2000", periods=2, tz=tz))
+
+ with tm.assert_produces_warning(None):
+ # Future behavior (for tzaware case) with no warning
+ result = np.asarray(ser, dtype=object)
+
+ expected = np.array(
+ [Timestamp("2000-01-01", tz=tz), Timestamp("2000-01-02", tz=tz)]
+ )
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_asarray_tz_naive(self):
+ # This shouldn't produce a warning.
+ ser = Series(date_range("2000", periods=2))
+ expected = np.array(["2000-01-01", "2000-01-02"], dtype="M8[ns]")
+ result = np.asarray(ser)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_asarray_tz_aware(self):
+ tz = "US/Central"
+ ser = Series(date_range("2000", periods=2, tz=tz))
+ expected = np.array(["2000-01-01T06", "2000-01-02T06"], dtype="M8[ns]")
+ result = np.asarray(ser, dtype="datetime64[ns]")
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ # Old behavior with no warning
+ result = np.asarray(ser, dtype="M8[ns]")
+
+ tm.assert_numpy_array_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_fillna.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_fillna.py
new file mode 100644
index 0000000000000000000000000000000000000000..7300d3013305a7ca08312ae85cc42ae8950acf23
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_fillna.py
@@ -0,0 +1,60 @@
+"""
+Though Index.fillna and Series.fillna has separate impl,
+test here to confirm these works as the same
+"""
+
+import numpy as np
+import pytest
+
+from pandas import MultiIndex
+import pandas._testing as tm
+from pandas.tests.base.common import allow_na_ops
+
+
+def test_fillna(index_or_series_obj):
+ # GH 11343
+ obj = index_or_series_obj
+
+ if isinstance(obj, MultiIndex):
+ msg = "isna is not defined for MultiIndex"
+ with pytest.raises(NotImplementedError, match=msg):
+ obj.fillna(0)
+ return
+
+ # values will not be changed
+ fill_value = obj.values[0] if len(obj) > 0 else 0
+ result = obj.fillna(fill_value)
+
+ tm.assert_equal(obj, result)
+
+ # check shallow_copied
+ assert obj is not result
+
+
+@pytest.mark.parametrize("null_obj", [np.nan, None])
+def test_fillna_null(null_obj, index_or_series_obj):
+ # GH 11343
+ obj = index_or_series_obj
+ klass = type(obj)
+
+ if not allow_na_ops(obj):
+ pytest.skip(f"{klass} doesn't allow for NA operations")
+ elif len(obj) < 1:
+ pytest.skip("Test doesn't make sense on empty data")
+ elif isinstance(obj, MultiIndex):
+ pytest.skip(f"MultiIndex can't hold '{null_obj}'")
+
+ values = obj._values
+ fill_value = values[0]
+ expected = values.copy()
+ values[0:2] = null_obj
+ expected[0:2] = fill_value
+
+ expected = klass(expected)
+ obj = klass(values)
+
+ result = obj.fillna(fill_value)
+ tm.assert_equal(result, expected)
+
+ # check shallow_copied
+ assert obj is not result
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_misc.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ca53c40104491f914c1813895a20d246284aa59
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_misc.py
@@ -0,0 +1,184 @@
+import sys
+
+import numpy as np
+import pytest
+
+from pandas.compat import PYPY
+
+from pandas.core.dtypes.common import (
+ is_dtype_equal,
+ is_object_dtype,
+)
+
+import pandas as pd
+from pandas import (
+ Index,
+ Series,
+)
+import pandas._testing as tm
+
+
+def test_isnull_notnull_docstrings():
+ # GH#41855 make sure its clear these are aliases
+ doc = pd.DataFrame.notnull.__doc__
+ assert doc.startswith("\nDataFrame.notnull is an alias for DataFrame.notna.\n")
+ doc = pd.DataFrame.isnull.__doc__
+ assert doc.startswith("\nDataFrame.isnull is an alias for DataFrame.isna.\n")
+
+ doc = Series.notnull.__doc__
+ assert doc.startswith("\nSeries.notnull is an alias for Series.notna.\n")
+ doc = Series.isnull.__doc__
+ assert doc.startswith("\nSeries.isnull is an alias for Series.isna.\n")
+
+
+@pytest.mark.parametrize(
+ "op_name, op",
+ [
+ ("add", "+"),
+ ("sub", "-"),
+ ("mul", "*"),
+ ("mod", "%"),
+ ("pow", "**"),
+ ("truediv", "/"),
+ ("floordiv", "//"),
+ ],
+)
+def test_binary_ops_docstring(frame_or_series, op_name, op):
+ # not using the all_arithmetic_functions fixture with _get_opstr
+ # as _get_opstr is used internally in the dynamic implementation of the docstring
+ klass = frame_or_series
+
+ operand1 = klass.__name__.lower()
+ operand2 = "other"
+ expected_str = " ".join([operand1, op, operand2])
+ assert expected_str in getattr(klass, op_name).__doc__
+
+ # reverse version of the binary ops
+ expected_str = " ".join([operand2, op, operand1])
+ assert expected_str in getattr(klass, "r" + op_name).__doc__
+
+
+def test_ndarray_compat_properties(index_or_series_obj):
+ obj = index_or_series_obj
+
+ # Check that we work.
+ for p in ["shape", "dtype", "T", "nbytes"]:
+ assert getattr(obj, p, None) is not None
+
+ # deprecated properties
+ for p in ["strides", "itemsize", "base", "data"]:
+ assert not hasattr(obj, p)
+
+ msg = "can only convert an array of size 1 to a Python scalar"
+ with pytest.raises(ValueError, match=msg):
+ obj.item() # len > 1
+
+ assert obj.ndim == 1
+ assert obj.size == len(obj)
+
+ assert Index([1]).item() == 1
+ assert Series([1]).item() == 1
+
+
+@pytest.mark.skipif(PYPY, reason="not relevant for PyPy")
+def test_memory_usage(index_or_series_memory_obj):
+ obj = index_or_series_memory_obj
+ # Clear index caches so that len(obj) == 0 report 0 memory usage
+ if isinstance(obj, Series):
+ is_ser = True
+ obj.index._engine.clear_mapping()
+ else:
+ is_ser = False
+ obj._engine.clear_mapping()
+
+ res = obj.memory_usage()
+ res_deep = obj.memory_usage(deep=True)
+
+ is_object = is_object_dtype(obj) or (is_ser and is_object_dtype(obj.index))
+ is_categorical = isinstance(obj.dtype, pd.CategoricalDtype) or (
+ is_ser and isinstance(obj.index.dtype, pd.CategoricalDtype)
+ )
+ is_object_string = is_dtype_equal(obj, "string[python]") or (
+ is_ser and is_dtype_equal(obj.index.dtype, "string[python]")
+ )
+
+ if len(obj) == 0:
+ expected = 0
+ assert res_deep == res == expected
+ elif is_object or is_categorical or is_object_string:
+ # only deep will pick them up
+ assert res_deep > res
+ else:
+ assert res == res_deep
+
+ # sys.getsizeof will call the .memory_usage with
+ # deep=True, and add on some GC overhead
+ diff = res_deep - sys.getsizeof(obj)
+ assert abs(diff) < 100
+
+
+def test_memory_usage_components_series(series_with_simple_index):
+ series = series_with_simple_index
+ total_usage = series.memory_usage(index=True)
+ non_index_usage = series.memory_usage(index=False)
+ index_usage = series.index.memory_usage()
+ assert total_usage == non_index_usage + index_usage
+
+
+@pytest.mark.parametrize("dtype", tm.NARROW_NP_DTYPES)
+def test_memory_usage_components_narrow_series(dtype):
+ series = tm.make_rand_series(name="a", dtype=dtype)
+ total_usage = series.memory_usage(index=True)
+ non_index_usage = series.memory_usage(index=False)
+ index_usage = series.index.memory_usage()
+ assert total_usage == non_index_usage + index_usage
+
+
+def test_searchsorted(request, index_or_series_obj):
+ # numpy.searchsorted calls obj.searchsorted under the hood.
+ # See gh-12238
+ obj = index_or_series_obj
+
+ if isinstance(obj, pd.MultiIndex):
+ # See gh-14833
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="np.searchsorted doesn't work on pd.MultiIndex: GH 14833"
+ )
+ )
+ elif obj.dtype.kind == "c" and isinstance(obj, Index):
+ # TODO: Should Series cases also raise? Looks like they use numpy
+ # comparison semantics https://github.com/numpy/numpy/issues/15981
+ mark = pytest.mark.xfail(reason="complex objects are not comparable")
+ request.node.add_marker(mark)
+
+ max_obj = max(obj, default=0)
+ index = np.searchsorted(obj, max_obj)
+ assert 0 <= index <= len(obj)
+
+ index = np.searchsorted(obj, max_obj, sorter=range(len(obj)))
+ assert 0 <= index <= len(obj)
+
+
+def test_access_by_position(index_flat):
+ index = index_flat
+
+ if len(index) == 0:
+ pytest.skip("Test doesn't make sense on empty data")
+
+ series = Series(index)
+ assert index[0] == series.iloc[0]
+ assert index[5] == series.iloc[5]
+ assert index[-1] == series.iloc[-1]
+
+ size = len(index)
+ assert index[-1] == index[size - 1]
+
+ msg = f"index {size} is out of bounds for axis 0 with size {size}"
+ if is_dtype_equal(index.dtype, "string[pyarrow]"):
+ msg = "index out of bounds"
+ with pytest.raises(IndexError, match=msg):
+ index[size]
+ msg = "single positional indexer is out-of-bounds"
+ with pytest.raises(IndexError, match=msg):
+ series.iloc[size]
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_transpose.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_transpose.py
new file mode 100644
index 0000000000000000000000000000000000000000..246f33d27476cb419620fb8571984619785f9b62
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_transpose.py
@@ -0,0 +1,56 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ CategoricalDtype,
+ DataFrame,
+)
+import pandas._testing as tm
+
+
+def test_transpose(index_or_series_obj):
+ obj = index_or_series_obj
+ tm.assert_equal(obj.transpose(), obj)
+
+
+def test_transpose_non_default_axes(index_or_series_obj):
+ msg = "the 'axes' parameter is not supported"
+ obj = index_or_series_obj
+ with pytest.raises(ValueError, match=msg):
+ obj.transpose(1)
+ with pytest.raises(ValueError, match=msg):
+ obj.transpose(axes=1)
+
+
+def test_numpy_transpose(index_or_series_obj):
+ msg = "the 'axes' parameter is not supported"
+ obj = index_or_series_obj
+ tm.assert_equal(np.transpose(obj), obj)
+
+ with pytest.raises(ValueError, match=msg):
+ np.transpose(obj, axes=1)
+
+
+@pytest.mark.parametrize(
+ "data, transposed_data, index, columns, dtype",
+ [
+ ([[1], [2]], [[1, 2]], ["a", "a"], ["b"], int),
+ ([[1], [2]], [[1, 2]], ["a", "a"], ["b"], CategoricalDtype([1, 2])),
+ ([[1, 2]], [[1], [2]], ["b"], ["a", "a"], int),
+ ([[1, 2]], [[1], [2]], ["b"], ["a", "a"], CategoricalDtype([1, 2])),
+ ([[1, 2], [3, 4]], [[1, 3], [2, 4]], ["a", "a"], ["b", "b"], int),
+ (
+ [[1, 2], [3, 4]],
+ [[1, 3], [2, 4]],
+ ["a", "a"],
+ ["b", "b"],
+ CategoricalDtype([1, 2, 3, 4]),
+ ),
+ ],
+)
+def test_duplicate_labels(data, transposed_data, index, columns, dtype):
+ # GH 42380
+ df = DataFrame(data, index=index, columns=columns, dtype=dtype)
+ result = df.T
+ expected = DataFrame(transposed_data, index=columns, columns=index, dtype=dtype)
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_unique.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_unique.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c845d8f24d0142047ddcf7581f98666e4b42362
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_unique.py
@@ -0,0 +1,121 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.tests.base.common import allow_na_ops
+
+
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+def test_unique(index_or_series_obj):
+ obj = index_or_series_obj
+ obj = np.repeat(obj, range(1, len(obj) + 1))
+ result = obj.unique()
+
+ # dict.fromkeys preserves the order
+ unique_values = list(dict.fromkeys(obj.values))
+ if isinstance(obj, pd.MultiIndex):
+ expected = pd.MultiIndex.from_tuples(unique_values)
+ expected.names = obj.names
+ tm.assert_index_equal(result, expected, exact=True)
+ elif isinstance(obj, pd.Index):
+ expected = pd.Index(unique_values, dtype=obj.dtype)
+ if isinstance(obj.dtype, pd.DatetimeTZDtype):
+ expected = expected.normalize()
+ tm.assert_index_equal(result, expected, exact=True)
+ else:
+ expected = np.array(unique_values)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+@pytest.mark.parametrize("null_obj", [np.nan, None])
+def test_unique_null(null_obj, index_or_series_obj):
+ obj = index_or_series_obj
+
+ if not allow_na_ops(obj):
+ pytest.skip("type doesn't allow for NA operations")
+ elif len(obj) < 1:
+ pytest.skip("Test doesn't make sense on empty data")
+ elif isinstance(obj, pd.MultiIndex):
+ pytest.skip(f"MultiIndex can't hold '{null_obj}'")
+
+ values = obj._values
+ values[0:2] = null_obj
+
+ klass = type(obj)
+ repeated_values = np.repeat(values, range(1, len(values) + 1))
+ obj = klass(repeated_values, dtype=obj.dtype)
+ result = obj.unique()
+
+ unique_values_raw = dict.fromkeys(obj.values)
+ # because np.nan == np.nan is False, but None == None is True
+ # np.nan would be duplicated, whereas None wouldn't
+ unique_values_not_null = [val for val in unique_values_raw if not pd.isnull(val)]
+ unique_values = [null_obj] + unique_values_not_null
+
+ if isinstance(obj, pd.Index):
+ expected = pd.Index(unique_values, dtype=obj.dtype)
+ if isinstance(obj.dtype, pd.DatetimeTZDtype):
+ result = result.normalize()
+ expected = expected.normalize()
+ tm.assert_index_equal(result, expected, exact=True)
+ else:
+ expected = np.array(unique_values, dtype=obj.dtype)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_nunique(index_or_series_obj):
+ obj = index_or_series_obj
+ obj = np.repeat(obj, range(1, len(obj) + 1))
+ expected = len(obj.unique())
+ assert obj.nunique(dropna=False) == expected
+
+
+@pytest.mark.parametrize("null_obj", [np.nan, None])
+def test_nunique_null(null_obj, index_or_series_obj):
+ obj = index_or_series_obj
+
+ if not allow_na_ops(obj):
+ pytest.skip("type doesn't allow for NA operations")
+ elif isinstance(obj, pd.MultiIndex):
+ pytest.skip(f"MultiIndex can't hold '{null_obj}'")
+
+ values = obj._values
+ values[0:2] = null_obj
+
+ klass = type(obj)
+ repeated_values = np.repeat(values, range(1, len(values) + 1))
+ obj = klass(repeated_values, dtype=obj.dtype)
+
+ if isinstance(obj, pd.CategoricalIndex):
+ assert obj.nunique() == len(obj.categories)
+ assert obj.nunique(dropna=False) == len(obj.categories) + 1
+ else:
+ num_unique_values = len(obj.unique())
+ assert obj.nunique() == max(0, num_unique_values - 1)
+ assert obj.nunique(dropna=False) == max(0, num_unique_values)
+
+
+@pytest.mark.single_cpu
+def test_unique_bad_unicode(index_or_series):
+ # regression test for #34550
+ uval = "\ud83d" # smiley emoji
+
+ obj = index_or_series([uval] * 2)
+ result = obj.unique()
+
+ if isinstance(obj, pd.Index):
+ expected = pd.Index(["\ud83d"], dtype=object)
+ tm.assert_index_equal(result, expected, exact=True)
+ else:
+ expected = np.array(["\ud83d"], dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("dropna", [True, False])
+def test_nunique_dropna(dropna):
+ # GH37566
+ ser = pd.Series(["yes", "yes", pd.NA, np.nan, None, pd.NaT])
+ res = ser.nunique(dropna)
+ assert res == 1 if dropna else 5
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_value_counts.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_value_counts.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cdfb7fe41e9214b4b161bbf4744915723bd941e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/base/test_value_counts.py
@@ -0,0 +1,322 @@
+import collections
+from datetime import timedelta
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DatetimeIndex,
+ Index,
+ Interval,
+ IntervalIndex,
+ MultiIndex,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+)
+import pandas._testing as tm
+from pandas.tests.base.common import allow_na_ops
+
+
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+def test_value_counts(index_or_series_obj):
+ obj = index_or_series_obj
+ obj = np.repeat(obj, range(1, len(obj) + 1))
+ result = obj.value_counts()
+
+ counter = collections.Counter(obj)
+ expected = Series(dict(counter.most_common()), dtype=np.int64, name="count")
+
+ if obj.dtype != np.float16:
+ expected.index = expected.index.astype(obj.dtype)
+ else:
+ with pytest.raises(NotImplementedError, match="float16 indexes are not "):
+ expected.index.astype(obj.dtype)
+ return
+ if isinstance(expected.index, MultiIndex):
+ expected.index.names = obj.names
+ else:
+ expected.index.name = obj.name
+
+ if not isinstance(result.dtype, np.dtype):
+ if getattr(obj.dtype, "storage", "") == "pyarrow":
+ expected = expected.astype("int64[pyarrow]")
+ else:
+ # i.e IntegerDtype
+ expected = expected.astype("Int64")
+
+ # TODO(GH#32514): Order of entries with the same count is inconsistent
+ # on CI (gh-32449)
+ if obj.duplicated().any():
+ result = result.sort_index()
+ expected = expected.sort_index()
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("null_obj", [np.nan, None])
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+def test_value_counts_null(null_obj, index_or_series_obj):
+ orig = index_or_series_obj
+ obj = orig.copy()
+
+ if not allow_na_ops(obj):
+ pytest.skip("type doesn't allow for NA operations")
+ elif len(obj) < 1:
+ pytest.skip("Test doesn't make sense on empty data")
+ elif isinstance(orig, MultiIndex):
+ pytest.skip(f"MultiIndex can't hold '{null_obj}'")
+
+ values = obj._values
+ values[0:2] = null_obj
+
+ klass = type(obj)
+ repeated_values = np.repeat(values, range(1, len(values) + 1))
+ obj = klass(repeated_values, dtype=obj.dtype)
+
+ # because np.nan == np.nan is False, but None == None is True
+ # np.nan would be duplicated, whereas None wouldn't
+ counter = collections.Counter(obj.dropna())
+ expected = Series(dict(counter.most_common()), dtype=np.int64, name="count")
+
+ if obj.dtype != np.float16:
+ expected.index = expected.index.astype(obj.dtype)
+ else:
+ with pytest.raises(NotImplementedError, match="float16 indexes are not "):
+ expected.index.astype(obj.dtype)
+ return
+ expected.index.name = obj.name
+
+ result = obj.value_counts()
+ if obj.duplicated().any():
+ # TODO(GH#32514):
+ # Order of entries with the same count is inconsistent on CI (gh-32449)
+ expected = expected.sort_index()
+ result = result.sort_index()
+
+ if not isinstance(result.dtype, np.dtype):
+ if getattr(obj.dtype, "storage", "") == "pyarrow":
+ expected = expected.astype("int64[pyarrow]")
+ else:
+ # i.e IntegerDtype
+ expected = expected.astype("Int64")
+ tm.assert_series_equal(result, expected)
+
+ expected[null_obj] = 3
+
+ result = obj.value_counts(dropna=False)
+ if obj.duplicated().any():
+ # TODO(GH#32514):
+ # Order of entries with the same count is inconsistent on CI (gh-32449)
+ expected = expected.sort_index()
+ result = result.sort_index()
+ tm.assert_series_equal(result, expected)
+
+
+def test_value_counts_inferred(index_or_series):
+ klass = index_or_series
+ s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"]
+ s = klass(s_values)
+ expected = Series([4, 3, 2, 1], index=["b", "a", "d", "c"], name="count")
+ tm.assert_series_equal(s.value_counts(), expected)
+
+ if isinstance(s, Index):
+ exp = Index(np.unique(np.array(s_values, dtype=np.object_)))
+ tm.assert_index_equal(s.unique(), exp)
+ else:
+ exp = np.unique(np.array(s_values, dtype=np.object_))
+ tm.assert_numpy_array_equal(s.unique(), exp)
+
+ assert s.nunique() == 4
+ # don't sort, have to sort after the fact as not sorting is
+ # platform-dep
+ hist = s.value_counts(sort=False).sort_values()
+ expected = Series([3, 1, 4, 2], index=list("acbd"), name="count").sort_values()
+ tm.assert_series_equal(hist, expected)
+
+ # sort ascending
+ hist = s.value_counts(ascending=True)
+ expected = Series([1, 2, 3, 4], index=list("cdab"), name="count")
+ tm.assert_series_equal(hist, expected)
+
+ # relative histogram.
+ hist = s.value_counts(normalize=True)
+ expected = Series(
+ [0.4, 0.3, 0.2, 0.1], index=["b", "a", "d", "c"], name="proportion"
+ )
+ tm.assert_series_equal(hist, expected)
+
+
+def test_value_counts_bins(index_or_series):
+ klass = index_or_series
+ s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"]
+ s = klass(s_values)
+
+ # bins
+ msg = "bins argument only works with numeric data"
+ with pytest.raises(TypeError, match=msg):
+ s.value_counts(bins=1)
+
+ s1 = Series([1, 1, 2, 3])
+ res1 = s1.value_counts(bins=1)
+ exp1 = Series({Interval(0.997, 3.0): 4}, name="count")
+ tm.assert_series_equal(res1, exp1)
+ res1n = s1.value_counts(bins=1, normalize=True)
+ exp1n = Series({Interval(0.997, 3.0): 1.0}, name="proportion")
+ tm.assert_series_equal(res1n, exp1n)
+
+ if isinstance(s1, Index):
+ tm.assert_index_equal(s1.unique(), Index([1, 2, 3]))
+ else:
+ exp = np.array([1, 2, 3], dtype=np.int64)
+ tm.assert_numpy_array_equal(s1.unique(), exp)
+
+ assert s1.nunique() == 3
+
+ # these return the same
+ res4 = s1.value_counts(bins=4, dropna=True)
+ intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])
+ exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 1, 3, 2]), name="count")
+ tm.assert_series_equal(res4, exp4)
+
+ res4 = s1.value_counts(bins=4, dropna=False)
+ intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])
+ exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 1, 3, 2]), name="count")
+ tm.assert_series_equal(res4, exp4)
+
+ res4n = s1.value_counts(bins=4, normalize=True)
+ exp4n = Series(
+ [0.5, 0.25, 0.25, 0], index=intervals.take([0, 1, 3, 2]), name="proportion"
+ )
+ tm.assert_series_equal(res4n, exp4n)
+
+ # handle NA's properly
+ s_values = ["a", "b", "b", "b", np.nan, np.nan, "d", "d", "a", "a", "b"]
+ s = klass(s_values)
+ expected = Series([4, 3, 2], index=["b", "a", "d"], name="count")
+ tm.assert_series_equal(s.value_counts(), expected)
+
+ if isinstance(s, Index):
+ exp = Index(["a", "b", np.nan, "d"])
+ tm.assert_index_equal(s.unique(), exp)
+ else:
+ exp = np.array(["a", "b", np.nan, "d"], dtype=object)
+ tm.assert_numpy_array_equal(s.unique(), exp)
+ assert s.nunique() == 3
+
+ s = klass({}) if klass is dict else klass({}, dtype=object)
+ expected = Series([], dtype=np.int64, name="count")
+ tm.assert_series_equal(s.value_counts(), expected, check_index_type=False)
+ # returned dtype differs depending on original
+ if isinstance(s, Index):
+ tm.assert_index_equal(s.unique(), Index([]), exact=False)
+ else:
+ tm.assert_numpy_array_equal(s.unique(), np.array([]), check_dtype=False)
+
+ assert s.nunique() == 0
+
+
+def test_value_counts_datetime64(index_or_series):
+ klass = index_or_series
+
+ # GH 3002, datetime64[ns]
+ # don't test names though
+ df = pd.DataFrame(
+ {
+ "person_id": ["xxyyzz", "xxyyzz", "xxyyzz", "xxyyww", "foofoo", "foofoo"],
+ "dt": pd.to_datetime(
+ [
+ "2010-01-01",
+ "2010-01-01",
+ "2010-01-01",
+ "2009-01-01",
+ "2008-09-09",
+ "2008-09-09",
+ ]
+ ),
+ "food": ["PIE", "GUM", "EGG", "EGG", "PIE", "GUM"],
+ }
+ )
+
+ s = klass(df["dt"].copy())
+ s.name = None
+ idx = pd.to_datetime(
+ ["2010-01-01 00:00:00", "2008-09-09 00:00:00", "2009-01-01 00:00:00"]
+ )
+ expected_s = Series([3, 2, 1], index=idx, name="count")
+ tm.assert_series_equal(s.value_counts(), expected_s)
+
+ expected = pd.array(
+ np.array(
+ ["2010-01-01 00:00:00", "2009-01-01 00:00:00", "2008-09-09 00:00:00"],
+ dtype="datetime64[ns]",
+ )
+ )
+ if isinstance(s, Index):
+ tm.assert_index_equal(s.unique(), DatetimeIndex(expected))
+ else:
+ tm.assert_extension_array_equal(s.unique(), expected)
+
+ assert s.nunique() == 3
+
+ # with NaT
+ s = df["dt"].copy()
+ s = klass(list(s.values) + [pd.NaT] * 4)
+
+ result = s.value_counts()
+ assert result.index.dtype == "datetime64[ns]"
+ tm.assert_series_equal(result, expected_s)
+
+ result = s.value_counts(dropna=False)
+ expected_s = pd.concat(
+ [Series([4], index=DatetimeIndex([pd.NaT]), name="count"), expected_s]
+ )
+ tm.assert_series_equal(result, expected_s)
+
+ assert s.dtype == "datetime64[ns]"
+ unique = s.unique()
+ assert unique.dtype == "datetime64[ns]"
+
+ # numpy_array_equal cannot compare pd.NaT
+ if isinstance(s, Index):
+ exp_idx = DatetimeIndex(expected.tolist() + [pd.NaT])
+ tm.assert_index_equal(unique, exp_idx)
+ else:
+ tm.assert_extension_array_equal(unique[:3], expected)
+ assert pd.isna(unique[3])
+
+ assert s.nunique() == 3
+ assert s.nunique(dropna=False) == 4
+
+ # timedelta64[ns]
+ td = df.dt - df.dt + timedelta(1)
+ td = klass(td, name="dt")
+
+ result = td.value_counts()
+ expected_s = Series([6], index=Index([Timedelta("1day")], name="dt"), name="count")
+ tm.assert_series_equal(result, expected_s)
+
+ expected = TimedeltaIndex(["1 days"], name="dt")
+ if isinstance(td, Index):
+ tm.assert_index_equal(td.unique(), expected)
+ else:
+ tm.assert_extension_array_equal(td.unique(), expected._values)
+
+ td2 = timedelta(1) + (df.dt - df.dt)
+ td2 = klass(td2, name="dt")
+ result2 = td2.value_counts()
+ tm.assert_series_equal(result2, expected_s)
+
+
+@pytest.mark.parametrize("dropna", [True, False])
+def test_value_counts_with_nan(dropna, index_or_series):
+ # GH31944
+ klass = index_or_series
+ values = [True, pd.NA, np.nan]
+ obj = klass(values)
+ res = obj.value_counts(dropna=dropna)
+ if dropna is True:
+ expected = Series([1], index=Index([True], dtype=obj.dtype), name="count")
+ else:
+ expected = Series([1, 1, 1], index=[True, pd.NA, np.nan], name="count")
+ tm.assert_series_equal(res, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/computation/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/computation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/computation/test_compat.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/computation/test_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..856a5b3a22a95d35cc577050f52d762b065e3ddf
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/computation/test_compat.py
@@ -0,0 +1,32 @@
+import pytest
+
+from pandas.compat._optional import VERSIONS
+
+import pandas as pd
+from pandas.core.computation import expr
+from pandas.core.computation.engines import ENGINES
+from pandas.util.version import Version
+
+
+def test_compat():
+ # test we have compat with our version of numexpr
+
+ from pandas.core.computation.check import NUMEXPR_INSTALLED
+
+ ne = pytest.importorskip("numexpr")
+
+ ver = ne.__version__
+ if Version(ver) < Version(VERSIONS["numexpr"]):
+ assert not NUMEXPR_INSTALLED
+ else:
+ assert NUMEXPR_INSTALLED
+
+
+@pytest.mark.parametrize("engine", ENGINES)
+@pytest.mark.parametrize("parser", expr.PARSERS)
+def test_invalid_numexpr_version(engine, parser):
+ if engine == "numexpr":
+ pytest.importorskip("numexpr")
+ a, b = 1, 2 # noqa: F841
+ res = pd.eval("a + b", engine=engine, parser=parser)
+ assert res == 3
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/computation/test_eval.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/computation/test_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c630e29ea8e69a0222cded143640e53250090a3
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/computation/test_eval.py
@@ -0,0 +1,1927 @@
+from __future__ import annotations
+
+from functools import reduce
+from itertools import product
+import operator
+
+import numpy as np
+import pytest
+
+from pandas.compat import PY312
+from pandas.errors import (
+ NumExprClobberingError,
+ PerformanceWarning,
+ UndefinedVariableError,
+)
+import pandas.util._test_decorators as td
+
+from pandas.core.dtypes.common import (
+ is_bool,
+ is_float,
+ is_list_like,
+ is_scalar,
+)
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.core.computation import (
+ expr,
+ pytables,
+)
+from pandas.core.computation.engines import ENGINES
+from pandas.core.computation.expr import (
+ BaseExprVisitor,
+ PandasExprVisitor,
+ PythonExprVisitor,
+)
+from pandas.core.computation.expressions import (
+ NUMEXPR_INSTALLED,
+ USE_NUMEXPR,
+)
+from pandas.core.computation.ops import (
+ ARITH_OPS_SYMS,
+ SPECIAL_CASE_ARITH_OPS_SYMS,
+ _binary_math_ops,
+ _binary_ops_dict,
+ _unary_math_ops,
+)
+from pandas.core.computation.scope import DEFAULT_GLOBALS
+
+
+@pytest.fixture(
+ params=(
+ pytest.param(
+ engine,
+ marks=[
+ pytest.mark.skipif(
+ engine == "numexpr" and not USE_NUMEXPR,
+ reason=f"numexpr enabled->{USE_NUMEXPR}, "
+ f"installed->{NUMEXPR_INSTALLED}",
+ ),
+ td.skip_if_no_ne,
+ ],
+ )
+ for engine in ENGINES
+ )
+)
+def engine(request):
+ return request.param
+
+
+@pytest.fixture(params=expr.PARSERS)
+def parser(request):
+ return request.param
+
+
+def _eval_single_bin(lhs, cmp1, rhs, engine):
+ c = _binary_ops_dict[cmp1]
+ if ENGINES[engine].has_neg_frac:
+ try:
+ return c(lhs, rhs)
+ except ValueError as e:
+ if str(e).startswith(
+ "negative number cannot be raised to a fractional power"
+ ):
+ return np.nan
+ raise
+ return c(lhs, rhs)
+
+
+# TODO: using range(5) here is a kludge
+@pytest.fixture(
+ params=list(range(5)),
+ ids=["DataFrame", "Series", "SeriesNaN", "DataFrameNaN", "float"],
+)
+def lhs(request):
+ nan_df1 = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
+ nan_df1[nan_df1 > 0.5] = np.nan
+
+ opts = (
+ DataFrame(np.random.default_rng(2).standard_normal((10, 5))),
+ Series(np.random.default_rng(2).standard_normal(5)),
+ Series([1, 2, np.nan, np.nan, 5]),
+ nan_df1,
+ np.random.default_rng(2).standard_normal(),
+ )
+ return opts[request.param]
+
+
+rhs = lhs
+midhs = lhs
+
+
+class TestEval:
+ @pytest.mark.parametrize(
+ "cmp1",
+ ["!=", "==", "<=", ">=", "<", ">"],
+ ids=["ne", "eq", "le", "ge", "lt", "gt"],
+ )
+ @pytest.mark.parametrize("cmp2", [">", "<"], ids=["gt", "lt"])
+ @pytest.mark.parametrize("binop", expr.BOOL_OPS_SYMS)
+ def test_complex_cmp_ops(self, cmp1, cmp2, binop, lhs, rhs, engine, parser):
+ if parser == "python" and binop in ["and", "or"]:
+ msg = "'BoolOp' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)"
+ pd.eval(ex, engine=engine, parser=parser)
+ return
+
+ lhs_new = _eval_single_bin(lhs, cmp1, rhs, engine)
+ rhs_new = _eval_single_bin(lhs, cmp2, rhs, engine)
+ expected = _eval_single_bin(lhs_new, binop, rhs_new, engine)
+
+ ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)"
+ result = pd.eval(ex, engine=engine, parser=parser)
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("cmp_op", expr.CMP_OPS_SYMS)
+ def test_simple_cmp_ops(self, cmp_op, lhs, rhs, engine, parser):
+ lhs = lhs < 0
+ rhs = rhs < 0
+
+ if parser == "python" and cmp_op in ["in", "not in"]:
+ msg = "'(In|NotIn)' nodes are not implemented"
+
+ with pytest.raises(NotImplementedError, match=msg):
+ ex = f"lhs {cmp_op} rhs"
+ pd.eval(ex, engine=engine, parser=parser)
+ return
+
+ ex = f"lhs {cmp_op} rhs"
+ msg = "|".join(
+ [
+ r"only list-like( or dict-like)? objects are allowed to be "
+ r"passed to (DataFrame\.)?isin\(\), you passed a "
+ r"(`|')bool(`|')",
+ "argument of type 'bool' is not iterable",
+ ]
+ )
+ if cmp_op in ("in", "not in") and not is_list_like(rhs):
+ with pytest.raises(TypeError, match=msg):
+ pd.eval(
+ ex,
+ engine=engine,
+ parser=parser,
+ local_dict={"lhs": lhs, "rhs": rhs},
+ )
+ else:
+ expected = _eval_single_bin(lhs, cmp_op, rhs, engine)
+ result = pd.eval(ex, engine=engine, parser=parser)
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("op", expr.CMP_OPS_SYMS)
+ def test_compound_invert_op(self, op, lhs, rhs, request, engine, parser):
+ if parser == "python" and op in ["in", "not in"]:
+ msg = "'(In|NotIn)' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ ex = f"~(lhs {op} rhs)"
+ pd.eval(ex, engine=engine, parser=parser)
+ return
+
+ if (
+ is_float(lhs)
+ and not is_float(rhs)
+ and op in ["in", "not in"]
+ and engine == "python"
+ and parser == "pandas"
+ ):
+ mark = pytest.mark.xfail(
+ reason="Looks like expected is negative, unclear whether "
+ "expected is incorrect or result is incorrect"
+ )
+ request.node.add_marker(mark)
+ skip_these = ["in", "not in"]
+ ex = f"~(lhs {op} rhs)"
+
+ msg = "|".join(
+ [
+ r"only list-like( or dict-like)? objects are allowed to be "
+ r"passed to (DataFrame\.)?isin\(\), you passed a "
+ r"(`|')float(`|')",
+ "argument of type 'float' is not iterable",
+ ]
+ )
+ if is_scalar(rhs) and op in skip_these:
+ with pytest.raises(TypeError, match=msg):
+ pd.eval(
+ ex,
+ engine=engine,
+ parser=parser,
+ local_dict={"lhs": lhs, "rhs": rhs},
+ )
+ else:
+ # compound
+ if is_scalar(lhs) and is_scalar(rhs):
+ lhs, rhs = (np.array([x]) for x in (lhs, rhs))
+ expected = _eval_single_bin(lhs, op, rhs, engine)
+ if is_scalar(expected):
+ expected = not expected
+ else:
+ expected = ~expected
+ result = pd.eval(ex, engine=engine, parser=parser)
+ tm.assert_almost_equal(expected, result)
+
+ @pytest.mark.parametrize("cmp1", ["<", ">"])
+ @pytest.mark.parametrize("cmp2", ["<", ">"])
+ def test_chained_cmp_op(self, cmp1, cmp2, lhs, midhs, rhs, engine, parser):
+ mid = midhs
+ if parser == "python":
+ ex1 = f"lhs {cmp1} mid {cmp2} rhs"
+ msg = "'BoolOp' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(ex1, engine=engine, parser=parser)
+ return
+
+ lhs_new = _eval_single_bin(lhs, cmp1, mid, engine)
+ rhs_new = _eval_single_bin(mid, cmp2, rhs, engine)
+
+ if lhs_new is not None and rhs_new is not None:
+ ex1 = f"lhs {cmp1} mid {cmp2} rhs"
+ ex2 = f"lhs {cmp1} mid and mid {cmp2} rhs"
+ ex3 = f"(lhs {cmp1} mid) & (mid {cmp2} rhs)"
+ expected = _eval_single_bin(lhs_new, "&", rhs_new, engine)
+
+ for ex in (ex1, ex2, ex3):
+ result = pd.eval(ex, engine=engine, parser=parser)
+
+ tm.assert_almost_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "arith1", sorted(set(ARITH_OPS_SYMS).difference(SPECIAL_CASE_ARITH_OPS_SYMS))
+ )
+ def test_binary_arith_ops(self, arith1, lhs, rhs, engine, parser):
+ ex = f"lhs {arith1} rhs"
+ result = pd.eval(ex, engine=engine, parser=parser)
+ expected = _eval_single_bin(lhs, arith1, rhs, engine)
+
+ tm.assert_almost_equal(result, expected)
+ ex = f"lhs {arith1} rhs {arith1} rhs"
+ result = pd.eval(ex, engine=engine, parser=parser)
+ nlhs = _eval_single_bin(lhs, arith1, rhs, engine)
+ try:
+ nlhs, ghs = nlhs.align(rhs)
+ except (ValueError, TypeError, AttributeError):
+ # ValueError: series frame or frame series align
+ # TypeError, AttributeError: series or frame with scalar align
+ return
+ else:
+ if engine == "numexpr":
+ import numexpr as ne
+
+ # direct numpy comparison
+ expected = ne.evaluate(f"nlhs {arith1} ghs")
+ # Update assert statement due to unreliable numerical
+ # precision component (GH37328)
+ # TODO: update testing code so that assert_almost_equal statement
+ # can be replaced again by the assert_numpy_array_equal statement
+ tm.assert_almost_equal(result.values, expected)
+ else:
+ expected = eval(f"nlhs {arith1} ghs")
+ tm.assert_almost_equal(result, expected)
+
+ # modulus, pow, and floor division require special casing
+
+ def test_modulus(self, lhs, rhs, engine, parser):
+ ex = r"lhs % rhs"
+ result = pd.eval(ex, engine=engine, parser=parser)
+ expected = lhs % rhs
+ tm.assert_almost_equal(result, expected)
+
+ if engine == "numexpr":
+ import numexpr as ne
+
+ expected = ne.evaluate(r"expected % rhs")
+ if isinstance(result, (DataFrame, Series)):
+ tm.assert_almost_equal(result.values, expected)
+ else:
+ tm.assert_almost_equal(result, expected.item())
+ else:
+ expected = _eval_single_bin(expected, "%", rhs, engine)
+ tm.assert_almost_equal(result, expected)
+
+ def test_floor_division(self, lhs, rhs, engine, parser):
+ ex = "lhs // rhs"
+
+ if engine == "python":
+ res = pd.eval(ex, engine=engine, parser=parser)
+ expected = lhs // rhs
+ tm.assert_equal(res, expected)
+ else:
+ msg = (
+ r"unsupported operand type\(s\) for //: 'VariableNode' and "
+ "'VariableNode'"
+ )
+ with pytest.raises(TypeError, match=msg):
+ pd.eval(
+ ex,
+ local_dict={"lhs": lhs, "rhs": rhs},
+ engine=engine,
+ parser=parser,
+ )
+
+ @td.skip_if_windows
+ def test_pow(self, lhs, rhs, engine, parser):
+ # odd failure on win32 platform, so skip
+ ex = "lhs ** rhs"
+ expected = _eval_single_bin(lhs, "**", rhs, engine)
+ result = pd.eval(ex, engine=engine, parser=parser)
+
+ if (
+ is_scalar(lhs)
+ and is_scalar(rhs)
+ and isinstance(expected, (complex, np.complexfloating))
+ and np.isnan(result)
+ ):
+ msg = "(DataFrame.columns|numpy array) are different"
+ with pytest.raises(AssertionError, match=msg):
+ tm.assert_numpy_array_equal(result, expected)
+ else:
+ tm.assert_almost_equal(result, expected)
+
+ ex = "(lhs ** rhs) ** rhs"
+ result = pd.eval(ex, engine=engine, parser=parser)
+
+ middle = _eval_single_bin(lhs, "**", rhs, engine)
+ expected = _eval_single_bin(middle, "**", rhs, engine)
+ tm.assert_almost_equal(result, expected)
+
+ def test_check_single_invert_op(self, lhs, engine, parser):
+ # simple
+ try:
+ elb = lhs.astype(bool)
+ except AttributeError:
+ elb = np.array([bool(lhs)])
+ expected = ~elb
+ result = pd.eval("~elb", engine=engine, parser=parser)
+ tm.assert_almost_equal(expected, result)
+
+ def test_frame_invert(self, engine, parser):
+ expr = "~lhs"
+
+ # ~ ##
+ # frame
+ # float always raises
+ lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)))
+ if engine == "numexpr":
+ msg = "couldn't find matching opcode for 'invert_dd'"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(expr, engine=engine, parser=parser)
+ else:
+ msg = "ufunc 'invert' not supported for the input types"
+ with pytest.raises(TypeError, match=msg):
+ pd.eval(expr, engine=engine, parser=parser)
+
+ # int raises on numexpr
+ lhs = DataFrame(np.random.default_rng(2).integers(5, size=(5, 2)))
+ if engine == "numexpr":
+ msg = "couldn't find matching opcode for 'invert"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(expr, engine=engine, parser=parser)
+ else:
+ expect = ~lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_frame_equal(expect, result)
+
+ # bool always works
+ lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5)
+ expect = ~lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_frame_equal(expect, result)
+
+ # object raises
+ lhs = DataFrame(
+ {"b": ["a", 1, 2.0], "c": np.random.default_rng(2).standard_normal(3) > 0.5}
+ )
+ if engine == "numexpr":
+ with pytest.raises(ValueError, match="unknown type object"):
+ pd.eval(expr, engine=engine, parser=parser)
+ else:
+ msg = "bad operand type for unary ~: 'str'"
+ with pytest.raises(TypeError, match=msg):
+ pd.eval(expr, engine=engine, parser=parser)
+
+ def test_series_invert(self, engine, parser):
+ # ~ ####
+ expr = "~lhs"
+
+ # series
+ # float raises
+ lhs = Series(np.random.default_rng(2).standard_normal(5))
+ if engine == "numexpr":
+ msg = "couldn't find matching opcode for 'invert_dd'"
+ with pytest.raises(NotImplementedError, match=msg):
+ result = pd.eval(expr, engine=engine, parser=parser)
+ else:
+ msg = "ufunc 'invert' not supported for the input types"
+ with pytest.raises(TypeError, match=msg):
+ pd.eval(expr, engine=engine, parser=parser)
+
+ # int raises on numexpr
+ lhs = Series(np.random.default_rng(2).integers(5, size=5))
+ if engine == "numexpr":
+ msg = "couldn't find matching opcode for 'invert"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(expr, engine=engine, parser=parser)
+ else:
+ expect = ~lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_series_equal(expect, result)
+
+ # bool
+ lhs = Series(np.random.default_rng(2).standard_normal(5) > 0.5)
+ expect = ~lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_series_equal(expect, result)
+
+ # float
+ # int
+ # bool
+
+ # object
+ lhs = Series(["a", 1, 2.0])
+ if engine == "numexpr":
+ with pytest.raises(ValueError, match="unknown type object"):
+ pd.eval(expr, engine=engine, parser=parser)
+ else:
+ msg = "bad operand type for unary ~: 'str'"
+ with pytest.raises(TypeError, match=msg):
+ pd.eval(expr, engine=engine, parser=parser)
+
+ def test_frame_negate(self, engine, parser):
+ expr = "-lhs"
+
+ # float
+ lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)))
+ expect = -lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_frame_equal(expect, result)
+
+ # int
+ lhs = DataFrame(np.random.default_rng(2).integers(5, size=(5, 2)))
+ expect = -lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_frame_equal(expect, result)
+
+ # bool doesn't work with numexpr but works elsewhere
+ lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5)
+ if engine == "numexpr":
+ msg = "couldn't find matching opcode for 'neg_bb'"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(expr, engine=engine, parser=parser)
+ else:
+ expect = -lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_frame_equal(expect, result)
+
+ def test_series_negate(self, engine, parser):
+ expr = "-lhs"
+
+ # float
+ lhs = Series(np.random.default_rng(2).standard_normal(5))
+ expect = -lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_series_equal(expect, result)
+
+ # int
+ lhs = Series(np.random.default_rng(2).integers(5, size=5))
+ expect = -lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_series_equal(expect, result)
+
+ # bool doesn't work with numexpr but works elsewhere
+ lhs = Series(np.random.default_rng(2).standard_normal(5) > 0.5)
+ if engine == "numexpr":
+ msg = "couldn't find matching opcode for 'neg_bb'"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(expr, engine=engine, parser=parser)
+ else:
+ expect = -lhs
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_series_equal(expect, result)
+
+ @pytest.mark.parametrize(
+ "lhs",
+ [
+ # Float
+ DataFrame(np.random.default_rng(2).standard_normal((5, 2))),
+ # Int
+ DataFrame(np.random.default_rng(2).integers(5, size=(5, 2))),
+ # bool doesn't work with numexpr but works elsewhere
+ DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5),
+ ],
+ )
+ def test_frame_pos(self, lhs, engine, parser):
+ expr = "+lhs"
+ expect = lhs
+
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_frame_equal(expect, result)
+
+ @pytest.mark.parametrize(
+ "lhs",
+ [
+ # Float
+ Series(np.random.default_rng(2).standard_normal(5)),
+ # Int
+ Series(np.random.default_rng(2).integers(5, size=5)),
+ # bool doesn't work with numexpr but works elsewhere
+ Series(np.random.default_rng(2).standard_normal(5) > 0.5),
+ ],
+ )
+ def test_series_pos(self, lhs, engine, parser):
+ expr = "+lhs"
+ expect = lhs
+
+ result = pd.eval(expr, engine=engine, parser=parser)
+ tm.assert_series_equal(expect, result)
+
+ def test_scalar_unary(self, engine, parser):
+ msg = "bad operand type for unary ~: 'float'"
+ with pytest.raises(TypeError, match=msg):
+ pd.eval("~1.0", engine=engine, parser=parser)
+
+ assert pd.eval("-1.0", parser=parser, engine=engine) == -1.0
+ assert pd.eval("+1.0", parser=parser, engine=engine) == +1.0
+ assert pd.eval("~1", parser=parser, engine=engine) == ~1
+ assert pd.eval("-1", parser=parser, engine=engine) == -1
+ assert pd.eval("+1", parser=parser, engine=engine) == +1
+ assert pd.eval("~True", parser=parser, engine=engine) == ~True
+ assert pd.eval("~False", parser=parser, engine=engine) == ~False
+ assert pd.eval("-True", parser=parser, engine=engine) == -True
+ assert pd.eval("-False", parser=parser, engine=engine) == -False
+ assert pd.eval("+True", parser=parser, engine=engine) == +True
+ assert pd.eval("+False", parser=parser, engine=engine) == +False
+
+ def test_unary_in_array(self):
+ # GH 11235
+ # TODO: 2022-01-29: result return list with numexpr 2.7.3 in CI
+ # but cannot reproduce locally
+ result = np.array(
+ pd.eval("[-True, True, +True, -False, False, +False, -37, 37, ~37, +37]"),
+ dtype=np.object_,
+ )
+ expected = np.array(
+ [
+ -True,
+ True,
+ +True,
+ -False,
+ False,
+ +False,
+ -37,
+ 37,
+ ~37,
+ +37,
+ ],
+ dtype=np.object_,
+ )
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64])
+ @pytest.mark.parametrize("expr", ["x < -0.1", "-5 > x"])
+ def test_float_comparison_bin_op(self, dtype, expr):
+ # GH 16363
+ df = DataFrame({"x": np.array([0], dtype=dtype)})
+ res = df.eval(expr)
+ assert res.values == np.array([False])
+
+ def test_unary_in_function(self):
+ # GH 46471
+ df = DataFrame({"x": [0, 1, np.nan]})
+
+ result = df.eval("x.fillna(-1)")
+ expected = df.x.fillna(-1)
+ # column name becomes None if using numexpr
+ # only check names when the engine is not numexpr
+ tm.assert_series_equal(result, expected, check_names=not USE_NUMEXPR)
+
+ result = df.eval("x.shift(1, fill_value=-1)")
+ expected = df.x.shift(1, fill_value=-1)
+ tm.assert_series_equal(result, expected, check_names=not USE_NUMEXPR)
+
+ @pytest.mark.parametrize(
+ "ex",
+ (
+ "1 or 2",
+ "1 and 2",
+ "a and b",
+ "a or b",
+ "1 or 2 and (3 + 2) > 3",
+ "2 * x > 2 or 1 and 2",
+ "2 * df > 3 and 1 or a",
+ ),
+ )
+ def test_disallow_scalar_bool_ops(self, ex, engine, parser):
+ x, a, b = np.random.default_rng(2).standard_normal(3), 1, 2 # noqa: F841
+ df = DataFrame(np.random.default_rng(2).standard_normal((3, 2))) # noqa: F841
+
+ msg = "cannot evaluate scalar only bool ops|'BoolOp' nodes are not"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(ex, engine=engine, parser=parser)
+
+ def test_identical(self, engine, parser):
+ # see gh-10546
+ x = 1
+ result = pd.eval("x", engine=engine, parser=parser)
+ assert result == 1
+ assert is_scalar(result)
+
+ x = 1.5
+ result = pd.eval("x", engine=engine, parser=parser)
+ assert result == 1.5
+ assert is_scalar(result)
+
+ x = False
+ result = pd.eval("x", engine=engine, parser=parser)
+ assert not result
+ assert is_bool(result)
+ assert is_scalar(result)
+
+ x = np.array([1])
+ result = pd.eval("x", engine=engine, parser=parser)
+ tm.assert_numpy_array_equal(result, np.array([1]))
+ assert result.shape == (1,)
+
+ x = np.array([1.5])
+ result = pd.eval("x", engine=engine, parser=parser)
+ tm.assert_numpy_array_equal(result, np.array([1.5]))
+ assert result.shape == (1,)
+
+ x = np.array([False]) # noqa: F841
+ result = pd.eval("x", engine=engine, parser=parser)
+ tm.assert_numpy_array_equal(result, np.array([False]))
+ assert result.shape == (1,)
+
+ def test_line_continuation(self, engine, parser):
+ # GH 11149
+ exp = """1 + 2 * \
+ 5 - 1 + 2 """
+ result = pd.eval(exp, engine=engine, parser=parser)
+ assert result == 12
+
+ def test_float_truncation(self, engine, parser):
+ # GH 14241
+ exp = "1000000000.006"
+ result = pd.eval(exp, engine=engine, parser=parser)
+ expected = np.float64(exp)
+ assert result == expected
+
+ df = DataFrame({"A": [1000000000.0009, 1000000000.0011, 1000000000.0015]})
+ cutoff = 1000000000.0006
+ result = df.query(f"A < {cutoff:.4f}")
+ assert result.empty
+
+ cutoff = 1000000000.0010
+ result = df.query(f"A > {cutoff:.4f}")
+ expected = df.loc[[1, 2], :]
+ tm.assert_frame_equal(expected, result)
+
+ exact = 1000000000.0011
+ result = df.query(f"A == {exact:.4f}")
+ expected = df.loc[[1], :]
+ tm.assert_frame_equal(expected, result)
+
+ def test_disallow_python_keywords(self):
+ # GH 18221
+ df = DataFrame([[0, 0, 0]], columns=["foo", "bar", "class"])
+ msg = "Python keyword not valid identifier in numexpr query"
+ with pytest.raises(SyntaxError, match=msg):
+ df.query("class == 0")
+
+ df = DataFrame()
+ df.index.name = "lambda"
+ with pytest.raises(SyntaxError, match=msg):
+ df.query("lambda == 0")
+
+ def test_true_false_logic(self):
+ # GH 25823
+ # This behavior is deprecated in Python 3.12
+ with tm.maybe_produces_warning(
+ DeprecationWarning, PY312, check_stacklevel=False
+ ):
+ assert pd.eval("not True") == -2
+ assert pd.eval("not False") == -1
+ assert pd.eval("True and not True") == 0
+
+ def test_and_logic_string_match(self):
+ # GH 25823
+ event = Series({"a": "hello"})
+ assert pd.eval(f"{event.str.match('hello').a}")
+ assert pd.eval(f"{event.str.match('hello').a and event.str.match('hello').a}")
+
+
+f = lambda *args, **kwargs: np.random.default_rng(2).standard_normal()
+
+
+# -------------------------------------
+# gh-12388: Typecasting rules consistency with python
+
+
+class TestTypeCasting:
+ @pytest.mark.parametrize("op", ["+", "-", "*", "**", "/"])
+ # maybe someday... numexpr has too many upcasting rules now
+ # chain(*(np.core.sctypes[x] for x in ['uint', 'int', 'float']))
+ @pytest.mark.parametrize("dt", [np.float32, np.float64])
+ @pytest.mark.parametrize("left_right", [("df", "3"), ("3", "df")])
+ def test_binop_typecasting(self, engine, parser, op, dt, left_right):
+ df = tm.makeCustomDataframe(5, 3, data_gen_f=f, dtype=dt)
+ left, right = left_right
+ s = f"{left} {op} {right}"
+ res = pd.eval(s, engine=engine, parser=parser)
+ assert df.values.dtype == dt
+ assert res.values.dtype == dt
+ tm.assert_frame_equal(res, eval(s))
+
+
+# -------------------------------------
+# Basic and complex alignment
+
+
+def should_warn(*args):
+ not_mono = not any(map(operator.attrgetter("is_monotonic_increasing"), args))
+ only_one_dt = reduce(
+ operator.xor, (issubclass(x.dtype.type, np.datetime64) for x in args)
+ )
+ return not_mono and only_one_dt
+
+
+class TestAlignment:
+ index_types = ["i", "s", "dt"]
+ lhs_index_types = index_types + ["s"] # 'p'
+
+ def test_align_nested_unary_op(self, engine, parser):
+ s = "df * ~2"
+ df = tm.makeCustomDataframe(5, 3, data_gen_f=f)
+ res = pd.eval(s, engine=engine, parser=parser)
+ tm.assert_frame_equal(res, df * ~2)
+
+ @pytest.mark.filterwarnings("always::RuntimeWarning")
+ @pytest.mark.parametrize("lr_idx_type", lhs_index_types)
+ @pytest.mark.parametrize("rr_idx_type", index_types)
+ @pytest.mark.parametrize("c_idx_type", index_types)
+ def test_basic_frame_alignment(
+ self, engine, parser, lr_idx_type, rr_idx_type, c_idx_type
+ ):
+ df = tm.makeCustomDataframe(
+ 10, 10, data_gen_f=f, r_idx_type=lr_idx_type, c_idx_type=c_idx_type
+ )
+ df2 = tm.makeCustomDataframe(
+ 20, 10, data_gen_f=f, r_idx_type=rr_idx_type, c_idx_type=c_idx_type
+ )
+ # only warns if not monotonic and not sortable
+ if should_warn(df.index, df2.index):
+ with tm.assert_produces_warning(RuntimeWarning):
+ res = pd.eval("df + df2", engine=engine, parser=parser)
+ else:
+ res = pd.eval("df + df2", engine=engine, parser=parser)
+ tm.assert_frame_equal(res, df + df2)
+
+ @pytest.mark.parametrize("r_idx_type", lhs_index_types)
+ @pytest.mark.parametrize("c_idx_type", lhs_index_types)
+ def test_frame_comparison(self, engine, parser, r_idx_type, c_idx_type):
+ df = tm.makeCustomDataframe(
+ 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type
+ )
+ res = pd.eval("df < 2", engine=engine, parser=parser)
+ tm.assert_frame_equal(res, df < 2)
+
+ df3 = DataFrame(
+ np.random.default_rng(2).standard_normal(df.shape),
+ index=df.index,
+ columns=df.columns,
+ )
+ res = pd.eval("df < df3", engine=engine, parser=parser)
+ tm.assert_frame_equal(res, df < df3)
+
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
+ @pytest.mark.parametrize("r1", lhs_index_types)
+ @pytest.mark.parametrize("c1", index_types)
+ @pytest.mark.parametrize("r2", index_types)
+ @pytest.mark.parametrize("c2", index_types)
+ def test_medium_complex_frame_alignment(self, engine, parser, r1, c1, r2, c2):
+ df = tm.makeCustomDataframe(3, 2, data_gen_f=f, r_idx_type=r1, c_idx_type=c1)
+ df2 = tm.makeCustomDataframe(4, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2)
+ df3 = tm.makeCustomDataframe(5, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2)
+ if should_warn(df.index, df2.index, df3.index):
+ with tm.assert_produces_warning(RuntimeWarning):
+ res = pd.eval("df + df2 + df3", engine=engine, parser=parser)
+ else:
+ res = pd.eval("df + df2 + df3", engine=engine, parser=parser)
+ tm.assert_frame_equal(res, df + df2 + df3)
+
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
+ @pytest.mark.parametrize("index_name", ["index", "columns"])
+ @pytest.mark.parametrize("c_idx_type", index_types)
+ @pytest.mark.parametrize("r_idx_type", lhs_index_types)
+ def test_basic_frame_series_alignment(
+ self, engine, parser, index_name, r_idx_type, c_idx_type
+ ):
+ df = tm.makeCustomDataframe(
+ 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type
+ )
+ index = getattr(df, index_name)
+ s = Series(np.random.default_rng(2).standard_normal(5), index[:5])
+
+ if should_warn(df.index, s.index):
+ with tm.assert_produces_warning(RuntimeWarning):
+ res = pd.eval("df + s", engine=engine, parser=parser)
+ else:
+ res = pd.eval("df + s", engine=engine, parser=parser)
+
+ if r_idx_type == "dt" or c_idx_type == "dt":
+ expected = df.add(s) if engine == "numexpr" else df + s
+ else:
+ expected = df + s
+ tm.assert_frame_equal(res, expected)
+
+ @pytest.mark.parametrize("index_name", ["index", "columns"])
+ @pytest.mark.parametrize(
+ "r_idx_type, c_idx_type",
+ list(product(["i", "s"], ["i", "s"])) + [("dt", "dt")],
+ )
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
+ def test_basic_series_frame_alignment(
+ self, request, engine, parser, index_name, r_idx_type, c_idx_type
+ ):
+ if (
+ engine == "numexpr"
+ and parser in ("pandas", "python")
+ and index_name == "index"
+ and r_idx_type == "i"
+ and c_idx_type == "s"
+ ):
+ reason = (
+ f"Flaky column ordering when engine={engine}, "
+ f"parser={parser}, index_name={index_name}, "
+ f"r_idx_type={r_idx_type}, c_idx_type={c_idx_type}"
+ )
+ request.node.add_marker(pytest.mark.xfail(reason=reason, strict=False))
+ df = tm.makeCustomDataframe(
+ 10, 7, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type
+ )
+ index = getattr(df, index_name)
+ s = Series(np.random.default_rng(2).standard_normal(5), index[:5])
+ if should_warn(s.index, df.index):
+ with tm.assert_produces_warning(RuntimeWarning):
+ res = pd.eval("s + df", engine=engine, parser=parser)
+ else:
+ res = pd.eval("s + df", engine=engine, parser=parser)
+
+ if r_idx_type == "dt" or c_idx_type == "dt":
+ expected = df.add(s) if engine == "numexpr" else s + df
+ else:
+ expected = s + df
+ tm.assert_frame_equal(res, expected)
+
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
+ @pytest.mark.parametrize("c_idx_type", index_types)
+ @pytest.mark.parametrize("r_idx_type", lhs_index_types)
+ @pytest.mark.parametrize("index_name", ["index", "columns"])
+ @pytest.mark.parametrize("op", ["+", "*"])
+ def test_series_frame_commutativity(
+ self, engine, parser, index_name, op, r_idx_type, c_idx_type
+ ):
+ df = tm.makeCustomDataframe(
+ 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type
+ )
+ index = getattr(df, index_name)
+ s = Series(np.random.default_rng(2).standard_normal(5), index[:5])
+
+ lhs = f"s {op} df"
+ rhs = f"df {op} s"
+ if should_warn(df.index, s.index):
+ with tm.assert_produces_warning(RuntimeWarning):
+ a = pd.eval(lhs, engine=engine, parser=parser)
+ with tm.assert_produces_warning(RuntimeWarning):
+ b = pd.eval(rhs, engine=engine, parser=parser)
+ else:
+ a = pd.eval(lhs, engine=engine, parser=parser)
+ b = pd.eval(rhs, engine=engine, parser=parser)
+
+ if r_idx_type != "dt" and c_idx_type != "dt":
+ if engine == "numexpr":
+ tm.assert_frame_equal(a, b)
+
+ @pytest.mark.filterwarnings("always::RuntimeWarning")
+ @pytest.mark.parametrize("r1", lhs_index_types)
+ @pytest.mark.parametrize("c1", index_types)
+ @pytest.mark.parametrize("r2", index_types)
+ @pytest.mark.parametrize("c2", index_types)
+ def test_complex_series_frame_alignment(self, engine, parser, r1, c1, r2, c2):
+ n = 3
+ m1 = 5
+ m2 = 2 * m1
+
+ index_name = np.random.default_rng(2).choice(["index", "columns"])
+ obj_name = np.random.default_rng(2).choice(["df", "df2"])
+
+ df = tm.makeCustomDataframe(m1, n, data_gen_f=f, r_idx_type=r1, c_idx_type=c1)
+ df2 = tm.makeCustomDataframe(m2, n, data_gen_f=f, r_idx_type=r2, c_idx_type=c2)
+ index = getattr(locals().get(obj_name), index_name)
+ ser = Series(np.random.default_rng(2).standard_normal(n), index[:n])
+
+ if r2 == "dt" or c2 == "dt":
+ if engine == "numexpr":
+ expected2 = df2.add(ser)
+ else:
+ expected2 = df2 + ser
+ else:
+ expected2 = df2 + ser
+
+ if r1 == "dt" or c1 == "dt":
+ if engine == "numexpr":
+ expected = expected2.add(df)
+ else:
+ expected = expected2 + df
+ else:
+ expected = expected2 + df
+
+ if should_warn(df2.index, ser.index, df.index):
+ with tm.assert_produces_warning(RuntimeWarning):
+ res = pd.eval("df2 + ser + df", engine=engine, parser=parser)
+ else:
+ res = pd.eval("df2 + ser + df", engine=engine, parser=parser)
+ assert res.shape == expected.shape
+ tm.assert_frame_equal(res, expected)
+
+ def test_performance_warning_for_poor_alignment(self, engine, parser):
+ df = DataFrame(np.random.default_rng(2).standard_normal((1000, 10)))
+ s = Series(np.random.default_rng(2).standard_normal(10000))
+ if engine == "numexpr":
+ seen = PerformanceWarning
+ else:
+ seen = False
+
+ with tm.assert_produces_warning(seen):
+ pd.eval("df + s", engine=engine, parser=parser)
+
+ s = Series(np.random.default_rng(2).standard_normal(1000))
+ with tm.assert_produces_warning(False):
+ pd.eval("df + s", engine=engine, parser=parser)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 10000)))
+ s = Series(np.random.default_rng(2).standard_normal(10000))
+ with tm.assert_produces_warning(False):
+ pd.eval("df + s", engine=engine, parser=parser)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 10)))
+ s = Series(np.random.default_rng(2).standard_normal(10000))
+
+ is_python_engine = engine == "python"
+
+ if not is_python_engine:
+ wrn = PerformanceWarning
+ else:
+ wrn = False
+
+ with tm.assert_produces_warning(wrn) as w:
+ pd.eval("df + s", engine=engine, parser=parser)
+
+ if not is_python_engine:
+ assert len(w) == 1
+ msg = str(w[0].message)
+ logged = np.log10(s.size - df.shape[1])
+ expected = (
+ f"Alignment difference on axis 1 is larger "
+ f"than an order of magnitude on term 'df', "
+ f"by more than {logged:.4g}; performance may suffer."
+ )
+ assert msg == expected
+
+
+# ------------------------------------
+# Slightly more complex ops
+
+
+class TestOperations:
+ def eval(self, *args, **kwargs):
+ kwargs["level"] = kwargs.pop("level", 0) + 1
+ return pd.eval(*args, **kwargs)
+
+ def test_simple_arith_ops(self, engine, parser):
+ exclude_arith = []
+ if parser == "python":
+ exclude_arith = ["in", "not in"]
+
+ arith_ops = [
+ op
+ for op in expr.ARITH_OPS_SYMS + expr.CMP_OPS_SYMS
+ if op not in exclude_arith
+ ]
+
+ ops = (op for op in arith_ops if op != "//")
+
+ for op in ops:
+ ex = f"1 {op} 1"
+ ex2 = f"x {op} 1"
+ ex3 = f"1 {op} (x + 1)"
+
+ if op in ("in", "not in"):
+ msg = "argument of type 'int' is not iterable"
+ with pytest.raises(TypeError, match=msg):
+ pd.eval(ex, engine=engine, parser=parser)
+ else:
+ expec = _eval_single_bin(1, op, 1, engine)
+ x = self.eval(ex, engine=engine, parser=parser)
+ assert x == expec
+
+ expec = _eval_single_bin(x, op, 1, engine)
+ y = self.eval(ex2, local_dict={"x": x}, engine=engine, parser=parser)
+ assert y == expec
+
+ expec = _eval_single_bin(1, op, x + 1, engine)
+ y = self.eval(ex3, local_dict={"x": x}, engine=engine, parser=parser)
+ assert y == expec
+
+ @pytest.mark.parametrize("rhs", [True, False])
+ @pytest.mark.parametrize("lhs", [True, False])
+ @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS)
+ def test_simple_bool_ops(self, rhs, lhs, op):
+ ex = f"{lhs} {op} {rhs}"
+
+ if parser == "python" and op in ["and", "or"]:
+ msg = "'BoolOp' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ self.eval(ex)
+ return
+
+ res = self.eval(ex)
+ exp = eval(ex)
+ assert res == exp
+
+ @pytest.mark.parametrize("rhs", [True, False])
+ @pytest.mark.parametrize("lhs", [True, False])
+ @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS)
+ def test_bool_ops_with_constants(self, rhs, lhs, op):
+ ex = f"{lhs} {op} {rhs}"
+
+ if parser == "python" and op in ["and", "or"]:
+ msg = "'BoolOp' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ self.eval(ex)
+ return
+
+ res = self.eval(ex)
+ exp = eval(ex)
+ assert res == exp
+
+ def test_4d_ndarray_fails(self):
+ x = np.random.default_rng(2).standard_normal((3, 4, 5, 6))
+ y = Series(np.random.default_rng(2).standard_normal(10))
+ msg = "N-dimensional objects, where N > 2, are not supported with eval"
+ with pytest.raises(NotImplementedError, match=msg):
+ self.eval("x + y", local_dict={"x": x, "y": y})
+
+ def test_constant(self):
+ x = self.eval("1")
+ assert x == 1
+
+ def test_single_variable(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+ df2 = self.eval("df", local_dict={"df": df})
+ tm.assert_frame_equal(df, df2)
+
+ def test_failing_subscript_with_name_error(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) # noqa: F841
+ with pytest.raises(NameError, match="name 'x' is not defined"):
+ self.eval("df[x > 2] > 2")
+
+ def test_lhs_expression_subscript(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ result = self.eval("(df + 1)[df > 2]", local_dict={"df": df})
+ expected = (df + 1)[df > 2]
+ tm.assert_frame_equal(result, expected)
+
+ def test_attr_expression(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)), columns=list("abc")
+ )
+ expr1 = "df.a < df.b"
+ expec1 = df.a < df.b
+ expr2 = "df.a + df.b + df.c"
+ expec2 = df.a + df.b + df.c
+ expr3 = "df.a + df.b + df.c[df.b < 0]"
+ expec3 = df.a + df.b + df.c[df.b < 0]
+ exprs = expr1, expr2, expr3
+ expecs = expec1, expec2, expec3
+ for e, expec in zip(exprs, expecs):
+ tm.assert_series_equal(expec, self.eval(e, local_dict={"df": df}))
+
+ def test_assignment_fails(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)), columns=list("abc")
+ )
+ df2 = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ expr1 = "df = df2"
+ msg = "cannot assign without a target object"
+ with pytest.raises(ValueError, match=msg):
+ self.eval(expr1, local_dict={"df": df, "df2": df2})
+
+ def test_assignment_column_multiple_raise(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+ # multiple assignees
+ with pytest.raises(SyntaxError, match="invalid syntax"):
+ df.eval("d c = a + b")
+
+ def test_assignment_column_invalid_assign(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+ # invalid assignees
+ msg = "left hand side of an assignment must be a single name"
+ with pytest.raises(SyntaxError, match=msg):
+ df.eval("d,c = a + b")
+
+ def test_assignment_column_invalid_assign_function_call(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+ msg = "cannot assign to function call"
+ with pytest.raises(SyntaxError, match=msg):
+ df.eval('Timestamp("20131001") = a + b')
+
+ def test_assignment_single_assign_existing(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+ # single assignment - existing variable
+ expected = df.copy()
+ expected["a"] = expected["a"] + expected["b"]
+ df.eval("a = a + b", inplace=True)
+ tm.assert_frame_equal(df, expected)
+
+ def test_assignment_single_assign_new(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+ # single assignment - new variable
+ expected = df.copy()
+ expected["c"] = expected["a"] + expected["b"]
+ df.eval("c = a + b", inplace=True)
+ tm.assert_frame_equal(df, expected)
+
+ def test_assignment_single_assign_local_overlap(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+ df = df.copy()
+ a = 1 # noqa: F841
+ df.eval("a = 1 + b", inplace=True)
+
+ expected = df.copy()
+ expected["a"] = 1 + expected["b"]
+ tm.assert_frame_equal(df, expected)
+
+ def test_assignment_single_assign_name(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+
+ a = 1 # noqa: F841
+ old_a = df.a.copy()
+ df.eval("a = a + b", inplace=True)
+ result = old_a + df.b
+ tm.assert_series_equal(result, df.a, check_names=False)
+ assert result.name is None
+
+ def test_assignment_multiple_raises(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+ # multiple assignment
+ df.eval("c = a + b", inplace=True)
+ msg = "can only assign a single expression"
+ with pytest.raises(SyntaxError, match=msg):
+ df.eval("c = a = b")
+
+ def test_assignment_explicit(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+ # explicit targets
+ self.eval("c = df.a + df.b", local_dict={"df": df}, target=df, inplace=True)
+ expected = df.copy()
+ expected["c"] = expected["a"] + expected["b"]
+ tm.assert_frame_equal(df, expected)
+
+ def test_column_in(self):
+ # GH 11235
+ df = DataFrame({"a": [11], "b": [-32]})
+ result = df.eval("a in [11, -32]")
+ expected = Series([True])
+ # TODO: 2022-01-29: Name check failed with numexpr 2.7.3 in CI
+ # but cannot reproduce locally
+ tm.assert_series_equal(result, expected, check_names=False)
+
+ @pytest.mark.xfail(reason="Unknown: Omitted test_ in name prior.")
+ def test_assignment_not_inplace(self):
+ # see gh-9297
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")
+ )
+
+ actual = df.eval("c = a + b", inplace=False)
+ assert actual is not None
+
+ expected = df.copy()
+ expected["c"] = expected["a"] + expected["b"]
+ tm.assert_frame_equal(df, expected)
+
+ def test_multi_line_expression(self):
+ # GH 11149
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ expected = df.copy()
+
+ expected["c"] = expected["a"] + expected["b"]
+ expected["d"] = expected["c"] + expected["b"]
+ answer = df.eval(
+ """
+ c = a + b
+ d = c + b""",
+ inplace=True,
+ )
+ tm.assert_frame_equal(expected, df)
+ assert answer is None
+
+ expected["a"] = expected["a"] - 1
+ expected["e"] = expected["a"] + 2
+ answer = df.eval(
+ """
+ a = a - 1
+ e = a + 2""",
+ inplace=True,
+ )
+ tm.assert_frame_equal(expected, df)
+ assert answer is None
+
+ # multi-line not valid if not all assignments
+ msg = "Multi-line expressions are only valid if all expressions contain"
+ with pytest.raises(ValueError, match=msg):
+ df.eval(
+ """
+ a = b + 2
+ b - 2""",
+ inplace=False,
+ )
+
+ def test_multi_line_expression_not_inplace(self):
+ # GH 11149
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ expected = df.copy()
+
+ expected["c"] = expected["a"] + expected["b"]
+ expected["d"] = expected["c"] + expected["b"]
+ df = df.eval(
+ """
+ c = a + b
+ d = c + b""",
+ inplace=False,
+ )
+ tm.assert_frame_equal(expected, df)
+
+ expected["a"] = expected["a"] - 1
+ expected["e"] = expected["a"] + 2
+ df = df.eval(
+ """
+ a = a - 1
+ e = a + 2""",
+ inplace=False,
+ )
+ tm.assert_frame_equal(expected, df)
+
+ def test_multi_line_expression_local_variable(self):
+ # GH 15342
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ expected = df.copy()
+
+ local_var = 7
+ expected["c"] = expected["a"] * local_var
+ expected["d"] = expected["c"] + local_var
+ answer = df.eval(
+ """
+ c = a * @local_var
+ d = c + @local_var
+ """,
+ inplace=True,
+ )
+ tm.assert_frame_equal(expected, df)
+ assert answer is None
+
+ def test_multi_line_expression_callable_local_variable(self):
+ # 26426
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+
+ def local_func(a, b):
+ return b
+
+ expected = df.copy()
+ expected["c"] = expected["a"] * local_func(1, 7)
+ expected["d"] = expected["c"] + local_func(1, 7)
+ answer = df.eval(
+ """
+ c = a * @local_func(1, 7)
+ d = c + @local_func(1, 7)
+ """,
+ inplace=True,
+ )
+ tm.assert_frame_equal(expected, df)
+ assert answer is None
+
+ def test_multi_line_expression_callable_local_variable_with_kwargs(self):
+ # 26426
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+
+ def local_func(a, b):
+ return b
+
+ expected = df.copy()
+ expected["c"] = expected["a"] * local_func(b=7, a=1)
+ expected["d"] = expected["c"] + local_func(b=7, a=1)
+ answer = df.eval(
+ """
+ c = a * @local_func(b=7, a=1)
+ d = c + @local_func(b=7, a=1)
+ """,
+ inplace=True,
+ )
+ tm.assert_frame_equal(expected, df)
+ assert answer is None
+
+ def test_assignment_in_query(self):
+ # GH 8664
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df_orig = df.copy()
+ msg = "cannot assign without a target object"
+ with pytest.raises(ValueError, match=msg):
+ df.query("a = 1")
+ tm.assert_frame_equal(df, df_orig)
+
+ def test_query_inplace(self):
+ # see gh-11149
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ expected = df.copy()
+ expected = expected[expected["a"] == 2]
+ df.query("a == 2", inplace=True)
+ tm.assert_frame_equal(expected, df)
+
+ df = {}
+ expected = {"a": 3}
+
+ self.eval("a = 1 + 2", target=df, inplace=True)
+ tm.assert_dict_equal(df, expected)
+
+ @pytest.mark.parametrize("invalid_target", [1, "cat", [1, 2], np.array([]), (1, 3)])
+ def test_cannot_item_assign(self, invalid_target):
+ msg = "Cannot assign expression output to target"
+ expression = "a = 1 + 2"
+
+ with pytest.raises(ValueError, match=msg):
+ self.eval(expression, target=invalid_target, inplace=True)
+
+ if hasattr(invalid_target, "copy"):
+ with pytest.raises(ValueError, match=msg):
+ self.eval(expression, target=invalid_target, inplace=False)
+
+ @pytest.mark.parametrize("invalid_target", [1, "cat", (1, 3)])
+ def test_cannot_copy_item(self, invalid_target):
+ msg = "Cannot return a copy of the target"
+ expression = "a = 1 + 2"
+
+ with pytest.raises(ValueError, match=msg):
+ self.eval(expression, target=invalid_target, inplace=False)
+
+ @pytest.mark.parametrize("target", [1, "cat", [1, 2], np.array([]), (1, 3), {1: 2}])
+ def test_inplace_no_assignment(self, target):
+ expression = "1 + 2"
+
+ assert self.eval(expression, target=target, inplace=False) == 3
+
+ msg = "Cannot operate inplace if there is no assignment"
+ with pytest.raises(ValueError, match=msg):
+ self.eval(expression, target=target, inplace=True)
+
+ def test_basic_period_index_boolean_expression(self):
+ df = tm.makeCustomDataframe(2, 2, data_gen_f=f, c_idx_type="p", r_idx_type="i")
+
+ e = df < 2
+ r = self.eval("df < 2", local_dict={"df": df})
+ x = df < 2
+
+ tm.assert_frame_equal(r, e)
+ tm.assert_frame_equal(x, e)
+
+ def test_basic_period_index_subscript_expression(self):
+ df = tm.makeCustomDataframe(2, 2, data_gen_f=f, c_idx_type="p", r_idx_type="i")
+ r = self.eval("df[df < 2 + 3]", local_dict={"df": df})
+ e = df[df < 2 + 3]
+ tm.assert_frame_equal(r, e)
+
+ def test_nested_period_index_subscript_expression(self):
+ df = tm.makeCustomDataframe(2, 2, data_gen_f=f, c_idx_type="p", r_idx_type="i")
+ r = self.eval("df[df[df < 2] < 2] + df * 2", local_dict={"df": df})
+ e = df[df[df < 2] < 2] + df * 2
+ tm.assert_frame_equal(r, e)
+
+ def test_date_boolean(self, engine, parser):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ df["dates1"] = date_range("1/1/2012", periods=5)
+ res = self.eval(
+ "df.dates1 < 20130101",
+ local_dict={"df": df},
+ engine=engine,
+ parser=parser,
+ )
+ expec = df.dates1 < "20130101"
+ tm.assert_series_equal(res, expec, check_names=False)
+
+ def test_simple_in_ops(self, engine, parser):
+ if parser != "python":
+ res = pd.eval("1 in [1, 2]", engine=engine, parser=parser)
+ assert res
+
+ res = pd.eval("2 in (1, 2)", engine=engine, parser=parser)
+ assert res
+
+ res = pd.eval("3 in (1, 2)", engine=engine, parser=parser)
+ assert not res
+
+ res = pd.eval("3 not in (1, 2)", engine=engine, parser=parser)
+ assert res
+
+ res = pd.eval("[3] not in (1, 2)", engine=engine, parser=parser)
+ assert res
+
+ res = pd.eval("[3] in ([3], 2)", engine=engine, parser=parser)
+ assert res
+
+ res = pd.eval("[[3]] in [[[3]], 2]", engine=engine, parser=parser)
+ assert res
+
+ res = pd.eval("(3,) in [(3,), 2]", engine=engine, parser=parser)
+ assert res
+
+ res = pd.eval("(3,) not in [(3,), 2]", engine=engine, parser=parser)
+ assert not res
+
+ res = pd.eval("[(3,)] in [[(3,)], 2]", engine=engine, parser=parser)
+ assert res
+ else:
+ msg = "'In' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval("1 in [1, 2]", engine=engine, parser=parser)
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval("2 in (1, 2)", engine=engine, parser=parser)
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval("3 in (1, 2)", engine=engine, parser=parser)
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval("[(3,)] in (1, 2, [(3,)])", engine=engine, parser=parser)
+ msg = "'NotIn' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval("3 not in (1, 2)", engine=engine, parser=parser)
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval("[3] not in (1, 2, [[3]])", engine=engine, parser=parser)
+
+ def test_check_many_exprs(self, engine, parser):
+ a = 1 # noqa: F841
+ expr = " * ".join("a" * 33)
+ expected = 1
+ res = pd.eval(expr, engine=engine, parser=parser)
+ assert res == expected
+
+ @pytest.mark.parametrize(
+ "expr",
+ [
+ "df > 2 and df > 3",
+ "df > 2 or df > 3",
+ "not df > 2",
+ ],
+ )
+ def test_fails_and_or_not(self, expr, engine, parser):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ if parser == "python":
+ msg = "'BoolOp' nodes are not implemented"
+ if "not" in expr:
+ msg = "'Not' nodes are not implemented"
+
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(
+ expr,
+ local_dict={"df": df},
+ parser=parser,
+ engine=engine,
+ )
+ else:
+ # smoke-test, should not raise
+ pd.eval(
+ expr,
+ local_dict={"df": df},
+ parser=parser,
+ engine=engine,
+ )
+
+ @pytest.mark.parametrize("char", ["|", "&"])
+ def test_fails_ampersand_pipe(self, char, engine, parser):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) # noqa: F841
+ ex = f"(df + 2)[df > 1] > 0 {char} (df > 0)"
+ if parser == "python":
+ msg = "cannot evaluate scalar only bool ops"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(ex, parser=parser, engine=engine)
+ else:
+ # smoke-test, should not raise
+ pd.eval(ex, parser=parser, engine=engine)
+
+
+class TestMath:
+ def eval(self, *args, **kwargs):
+ kwargs["level"] = kwargs.pop("level", 0) + 1
+ return pd.eval(*args, **kwargs)
+
+ @pytest.mark.skipif(
+ not NUMEXPR_INSTALLED, reason="Unary ops only implemented for numexpr"
+ )
+ @pytest.mark.parametrize("fn", _unary_math_ops)
+ def test_unary_functions(self, fn):
+ df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)})
+ a = df.a
+
+ expr = f"{fn}(a)"
+ got = self.eval(expr)
+ with np.errstate(all="ignore"):
+ expect = getattr(np, fn)(a)
+ tm.assert_series_equal(got, expect, check_names=False)
+
+ @pytest.mark.parametrize("fn", _binary_math_ops)
+ def test_binary_functions(self, fn):
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(10),
+ "b": np.random.default_rng(2).standard_normal(10),
+ }
+ )
+ a = df.a
+ b = df.b
+
+ expr = f"{fn}(a, b)"
+ got = self.eval(expr)
+ with np.errstate(all="ignore"):
+ expect = getattr(np, fn)(a, b)
+ tm.assert_almost_equal(got, expect, check_names=False)
+
+ def test_df_use_case(self, engine, parser):
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(10),
+ "b": np.random.default_rng(2).standard_normal(10),
+ }
+ )
+ df.eval(
+ "e = arctan2(sin(a), b)",
+ engine=engine,
+ parser=parser,
+ inplace=True,
+ )
+ got = df.e
+ expect = np.arctan2(np.sin(df.a), df.b)
+ tm.assert_series_equal(got, expect, check_names=False)
+
+ def test_df_arithmetic_subexpression(self, engine, parser):
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(10),
+ "b": np.random.default_rng(2).standard_normal(10),
+ }
+ )
+ df.eval("e = sin(a + b)", engine=engine, parser=parser, inplace=True)
+ got = df.e
+ expect = np.sin(df.a + df.b)
+ tm.assert_series_equal(got, expect, check_names=False)
+
+ @pytest.mark.parametrize(
+ "dtype, expect_dtype",
+ [
+ (np.int32, np.float64),
+ (np.int64, np.float64),
+ (np.float32, np.float32),
+ (np.float64, np.float64),
+ pytest.param(np.complex128, np.complex128, marks=td.skip_if_windows),
+ ],
+ )
+ def test_result_types(self, dtype, expect_dtype, engine, parser):
+ # xref https://github.com/pandas-dev/pandas/issues/12293
+ # this fails on Windows, apparently a floating point precision issue
+
+ # Did not test complex64 because DataFrame is converting it to
+ # complex128. Due to https://github.com/pandas-dev/pandas/issues/10952
+ df = DataFrame(
+ {"a": np.random.default_rng(2).standard_normal(10).astype(dtype)}
+ )
+ assert df.a.dtype == dtype
+ df.eval("b = sin(a)", engine=engine, parser=parser, inplace=True)
+ got = df.b
+ expect = np.sin(df.a)
+ assert expect.dtype == got.dtype
+ assert expect_dtype == got.dtype
+ tm.assert_series_equal(got, expect, check_names=False)
+
+ def test_undefined_func(self, engine, parser):
+ df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)})
+ msg = '"mysin" is not a supported function'
+
+ with pytest.raises(ValueError, match=msg):
+ df.eval("mysin(a)", engine=engine, parser=parser)
+
+ def test_keyword_arg(self, engine, parser):
+ df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)})
+ msg = 'Function "sin" does not support keyword arguments'
+
+ with pytest.raises(TypeError, match=msg):
+ df.eval("sin(x=a)", engine=engine, parser=parser)
+
+
+_var_s = np.random.default_rng(2).standard_normal(10)
+
+
+class TestScope:
+ def test_global_scope(self, engine, parser):
+ e = "_var_s * 2"
+ tm.assert_numpy_array_equal(
+ _var_s * 2, pd.eval(e, engine=engine, parser=parser)
+ )
+
+ def test_no_new_locals(self, engine, parser):
+ x = 1
+ lcls = locals().copy()
+ pd.eval("x + 1", local_dict=lcls, engine=engine, parser=parser)
+ lcls2 = locals().copy()
+ lcls2.pop("lcls")
+ assert lcls == lcls2
+
+ def test_no_new_globals(self, engine, parser):
+ x = 1 # noqa: F841
+ gbls = globals().copy()
+ pd.eval("x + 1", engine=engine, parser=parser)
+ gbls2 = globals().copy()
+ assert gbls == gbls2
+
+ def test_empty_locals(self, engine, parser):
+ # GH 47084
+ x = 1 # noqa: F841
+ msg = "name 'x' is not defined"
+ with pytest.raises(UndefinedVariableError, match=msg):
+ pd.eval("x + 1", engine=engine, parser=parser, local_dict={})
+
+ def test_empty_globals(self, engine, parser):
+ # GH 47084
+ msg = "name '_var_s' is not defined"
+ e = "_var_s * 2"
+ with pytest.raises(UndefinedVariableError, match=msg):
+ pd.eval(e, engine=engine, parser=parser, global_dict={})
+
+
+@td.skip_if_no_ne
+def test_invalid_engine():
+ msg = "Invalid engine 'asdf' passed"
+ with pytest.raises(KeyError, match=msg):
+ pd.eval("x + y", local_dict={"x": 1, "y": 2}, engine="asdf")
+
+
+@td.skip_if_no_ne
+@pytest.mark.parametrize(
+ ("use_numexpr", "expected"),
+ (
+ (True, "numexpr"),
+ (False, "python"),
+ ),
+)
+def test_numexpr_option_respected(use_numexpr, expected):
+ # GH 32556
+ from pandas.core.computation.eval import _check_engine
+
+ with pd.option_context("compute.use_numexpr", use_numexpr):
+ result = _check_engine(None)
+ assert result == expected
+
+
+@td.skip_if_no_ne
+def test_numexpr_option_incompatible_op():
+ # GH 32556
+ with pd.option_context("compute.use_numexpr", False):
+ df = DataFrame(
+ {"A": [True, False, True, False, None, None], "B": [1, 2, 3, 4, 5, 6]}
+ )
+ result = df.query("A.isnull()")
+ expected = DataFrame({"A": [None, None], "B": [5, 6]}, index=[4, 5])
+ tm.assert_frame_equal(result, expected)
+
+
+@td.skip_if_no_ne
+def test_invalid_parser():
+ msg = "Invalid parser 'asdf' passed"
+ with pytest.raises(KeyError, match=msg):
+ pd.eval("x + y", local_dict={"x": 1, "y": 2}, parser="asdf")
+
+
+_parsers: dict[str, type[BaseExprVisitor]] = {
+ "python": PythonExprVisitor,
+ "pytables": pytables.PyTablesExprVisitor,
+ "pandas": PandasExprVisitor,
+}
+
+
+@pytest.mark.parametrize("engine", ENGINES)
+@pytest.mark.parametrize("parser", _parsers)
+def test_disallowed_nodes(engine, parser):
+ VisitorClass = _parsers[parser]
+ inst = VisitorClass("x + 1", engine, parser)
+
+ for ops in VisitorClass.unsupported_nodes:
+ msg = "nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ getattr(inst, ops)()
+
+
+def test_syntax_error_exprs(engine, parser):
+ e = "s +"
+ with pytest.raises(SyntaxError, match="invalid syntax"):
+ pd.eval(e, engine=engine, parser=parser)
+
+
+def test_name_error_exprs(engine, parser):
+ e = "s + t"
+ msg = "name 's' is not defined"
+ with pytest.raises(NameError, match=msg):
+ pd.eval(e, engine=engine, parser=parser)
+
+
+@pytest.mark.parametrize("express", ["a + @b", "@a + b", "@a + @b"])
+def test_invalid_local_variable_reference(engine, parser, express):
+ a, b = 1, 2 # noqa: F841
+
+ if parser != "pandas":
+ with pytest.raises(SyntaxError, match="The '@' prefix is only"):
+ pd.eval(express, engine=engine, parser=parser)
+ else:
+ with pytest.raises(SyntaxError, match="The '@' prefix is not"):
+ pd.eval(express, engine=engine, parser=parser)
+
+
+def test_numexpr_builtin_raises(engine, parser):
+ sin, dotted_line = 1, 2
+ if engine == "numexpr":
+ msg = "Variables in expression .+"
+ with pytest.raises(NumExprClobberingError, match=msg):
+ pd.eval("sin + dotted_line", engine=engine, parser=parser)
+ else:
+ res = pd.eval("sin + dotted_line", engine=engine, parser=parser)
+ assert res == sin + dotted_line
+
+
+def test_bad_resolver_raises(engine, parser):
+ cannot_resolve = 42, 3.0
+ with pytest.raises(TypeError, match="Resolver of type .+"):
+ pd.eval("1 + 2", resolvers=cannot_resolve, engine=engine, parser=parser)
+
+
+def test_empty_string_raises(engine, parser):
+ # GH 13139
+ with pytest.raises(ValueError, match="expr cannot be an empty string"):
+ pd.eval("", engine=engine, parser=parser)
+
+
+def test_more_than_one_expression_raises(engine, parser):
+ with pytest.raises(SyntaxError, match="only a single expression is allowed"):
+ pd.eval("1 + 1; 2 + 2", engine=engine, parser=parser)
+
+
+@pytest.mark.parametrize("cmp", ("and", "or"))
+@pytest.mark.parametrize("lhs", (int, float))
+@pytest.mark.parametrize("rhs", (int, float))
+def test_bool_ops_fails_on_scalars(lhs, cmp, rhs, engine, parser):
+ gen = {
+ int: lambda: np.random.default_rng(2).integers(10),
+ float: np.random.default_rng(2).standard_normal,
+ }
+
+ mid = gen[lhs]() # noqa: F841
+ lhs = gen[lhs]()
+ rhs = gen[rhs]()
+
+ ex1 = f"lhs {cmp} mid {cmp} rhs"
+ ex2 = f"lhs {cmp} mid and mid {cmp} rhs"
+ ex3 = f"(lhs {cmp} mid) & (mid {cmp} rhs)"
+ for ex in (ex1, ex2, ex3):
+ msg = "cannot evaluate scalar only bool ops|'BoolOp' nodes are not"
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.eval(ex, engine=engine, parser=parser)
+
+
+@pytest.mark.parametrize(
+ "other",
+ [
+ "'x'",
+ "...",
+ ],
+)
+def test_equals_various(other):
+ df = DataFrame({"A": ["a", "b", "c"]})
+ result = df.eval(f"A == {other}")
+ expected = Series([False, False, False], name="A")
+ if USE_NUMEXPR:
+ # https://github.com/pandas-dev/pandas/issues/10239
+ # lose name with numexpr engine. Remove when that's fixed.
+ expected.name = None
+ tm.assert_series_equal(result, expected)
+
+
+def test_inf(engine, parser):
+ s = "inf + 1"
+ expected = np.inf
+ result = pd.eval(s, engine=engine, parser=parser)
+ assert result == expected
+
+
+@pytest.mark.parametrize("column", ["Temp(°C)", "Capacitance(μF)"])
+def test_query_token(engine, column):
+ # See: https://github.com/pandas-dev/pandas/pull/42826
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=[column, "b"]
+ )
+ expected = df[df[column] > 5]
+ query_string = f"`{column}` > 5"
+ result = df.query(query_string, engine=engine)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_negate_lt_eq_le(engine, parser):
+ df = DataFrame([[0, 10], [1, 20]], columns=["cat", "count"])
+ expected = df[~(df.cat > 0)]
+
+ result = df.query("~(cat > 0)", engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expected)
+
+ if parser == "python":
+ msg = "'Not' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ df.query("not (cat > 0)", engine=engine, parser=parser)
+ else:
+ result = df.query("not (cat > 0)", engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "column",
+ DEFAULT_GLOBALS.keys(),
+)
+def test_eval_no_support_column_name(request, column):
+ # GH 44603
+ if column in ["True", "False", "inf", "Inf"]:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=KeyError,
+ reason=f"GH 47859 DataFrame eval not supported with {column}",
+ )
+ )
+
+ df = DataFrame(
+ np.random.default_rng(2).integers(0, 100, size=(10, 2)),
+ columns=[column, "col1"],
+ )
+ expected = df[df[column] > 6]
+ result = df.query(f"{column}>6")
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_set_inplace(using_copy_on_write):
+ # https://github.com/pandas-dev/pandas/issues/47449
+ # Ensure we don't only update the DataFrame inplace, but also the actual
+ # column values, such that references to this column also get updated
+ df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result_view = df[:]
+ ser = df["A"]
+ df.eval("A = B + C", inplace=True)
+ expected = DataFrame({"A": [11, 13, 15], "B": [4, 5, 6], "C": [7, 8, 9]})
+ tm.assert_frame_equal(df, expected)
+ if not using_copy_on_write:
+ tm.assert_series_equal(ser, expected["A"])
+ tm.assert_series_equal(result_view["A"], expected["A"])
+ else:
+ expected = Series([1, 2, 3], name="A")
+ tm.assert_series_equal(ser, expected)
+ tm.assert_series_equal(result_view["A"], expected)
+
+
+class TestValidate:
+ @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
+ def test_validate_bool_args(self, value):
+ msg = 'For argument "inplace" expected type bool, received type'
+ with pytest.raises(ValueError, match=msg):
+ pd.eval("2+2", inplace=value)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/config/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/config/test_config.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/config/test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..f49ae942423992f6dbb209e8f931f091e900ba12
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/config/test_config.py
@@ -0,0 +1,437 @@
+import pytest
+
+from pandas._config import config as cf
+from pandas._config.config import OptionError
+
+import pandas as pd
+import pandas._testing as tm
+
+
+class TestConfig:
+ @pytest.fixture(autouse=True)
+ def clean_config(self, monkeypatch):
+ with monkeypatch.context() as m:
+ m.setattr(cf, "_global_config", {})
+ m.setattr(cf, "options", cf.DictWrapper(cf._global_config))
+ m.setattr(cf, "_deprecated_options", {})
+ m.setattr(cf, "_registered_options", {})
+
+ # Our test fixture in conftest.py sets "chained_assignment"
+ # to "raise" only after all test methods have been setup.
+ # However, after this setup, there is no longer any
+ # "chained_assignment" option, so re-register it.
+ cf.register_option("chained_assignment", "raise")
+ yield
+
+ def test_api(self):
+ # the pandas object exposes the user API
+ assert hasattr(pd, "get_option")
+ assert hasattr(pd, "set_option")
+ assert hasattr(pd, "reset_option")
+ assert hasattr(pd, "describe_option")
+
+ def test_is_one_of_factory(self):
+ v = cf.is_one_of_factory([None, 12])
+
+ v(12)
+ v(None)
+ msg = r"Value must be one of None\|12"
+ with pytest.raises(ValueError, match=msg):
+ v(1.1)
+
+ def test_register_option(self):
+ cf.register_option("a", 1, "doc")
+
+ # can't register an already registered option
+ msg = "Option 'a' has already been registered"
+ with pytest.raises(OptionError, match=msg):
+ cf.register_option("a", 1, "doc")
+
+ # can't register an already registered option
+ msg = "Path prefix to option 'a' is already an option"
+ with pytest.raises(OptionError, match=msg):
+ cf.register_option("a.b.c.d1", 1, "doc")
+ with pytest.raises(OptionError, match=msg):
+ cf.register_option("a.b.c.d2", 1, "doc")
+
+ # no python keywords
+ msg = "for is a python keyword"
+ with pytest.raises(ValueError, match=msg):
+ cf.register_option("for", 0)
+ with pytest.raises(ValueError, match=msg):
+ cf.register_option("a.for.b", 0)
+ # must be valid identifier (ensure attribute access works)
+ msg = "oh my goddess! is not a valid identifier"
+ with pytest.raises(ValueError, match=msg):
+ cf.register_option("Oh my Goddess!", 0)
+
+ # we can register options several levels deep
+ # without predefining the intermediate steps
+ # and we can define differently named options
+ # in the same namespace
+ cf.register_option("k.b.c.d1", 1, "doc")
+ cf.register_option("k.b.c.d2", 1, "doc")
+
+ def test_describe_option(self):
+ cf.register_option("a", 1, "doc")
+ cf.register_option("b", 1, "doc2")
+ cf.deprecate_option("b")
+
+ cf.register_option("c.d.e1", 1, "doc3")
+ cf.register_option("c.d.e2", 1, "doc4")
+ cf.register_option("f", 1)
+ cf.register_option("g.h", 1)
+ cf.register_option("k", 2)
+ cf.deprecate_option("g.h", rkey="k")
+ cf.register_option("l", "foo")
+
+ # non-existent keys raise KeyError
+ msg = r"No such keys\(s\)"
+ with pytest.raises(OptionError, match=msg):
+ cf.describe_option("no.such.key")
+
+ # we can get the description for any key we registered
+ assert "doc" in cf.describe_option("a", _print_desc=False)
+ assert "doc2" in cf.describe_option("b", _print_desc=False)
+ assert "precated" in cf.describe_option("b", _print_desc=False)
+ assert "doc3" in cf.describe_option("c.d.e1", _print_desc=False)
+ assert "doc4" in cf.describe_option("c.d.e2", _print_desc=False)
+
+ # if no doc is specified we get a default message
+ # saying "description not available"
+ assert "available" in cf.describe_option("f", _print_desc=False)
+ assert "available" in cf.describe_option("g.h", _print_desc=False)
+ assert "precated" in cf.describe_option("g.h", _print_desc=False)
+ assert "k" in cf.describe_option("g.h", _print_desc=False)
+
+ # default is reported
+ assert "foo" in cf.describe_option("l", _print_desc=False)
+ # current value is reported
+ assert "bar" not in cf.describe_option("l", _print_desc=False)
+ cf.set_option("l", "bar")
+ assert "bar" in cf.describe_option("l", _print_desc=False)
+
+ def test_case_insensitive(self):
+ cf.register_option("KanBAN", 1, "doc")
+
+ assert "doc" in cf.describe_option("kanbaN", _print_desc=False)
+ assert cf.get_option("kanBaN") == 1
+ cf.set_option("KanBan", 2)
+ assert cf.get_option("kAnBaN") == 2
+
+ # gets of non-existent keys fail
+ msg = r"No such keys\(s\): 'no_such_option'"
+ with pytest.raises(OptionError, match=msg):
+ cf.get_option("no_such_option")
+ cf.deprecate_option("KanBan")
+
+ assert cf._is_deprecated("kAnBaN")
+
+ def test_get_option(self):
+ cf.register_option("a", 1, "doc")
+ cf.register_option("b.c", "hullo", "doc2")
+ cf.register_option("b.b", None, "doc2")
+
+ # gets of existing keys succeed
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b.c") == "hullo"
+ assert cf.get_option("b.b") is None
+
+ # gets of non-existent keys fail
+ msg = r"No such keys\(s\): 'no_such_option'"
+ with pytest.raises(OptionError, match=msg):
+ cf.get_option("no_such_option")
+
+ def test_set_option(self):
+ cf.register_option("a", 1, "doc")
+ cf.register_option("b.c", "hullo", "doc2")
+ cf.register_option("b.b", None, "doc2")
+
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b.c") == "hullo"
+ assert cf.get_option("b.b") is None
+
+ cf.set_option("a", 2)
+ cf.set_option("b.c", "wurld")
+ cf.set_option("b.b", 1.1)
+
+ assert cf.get_option("a") == 2
+ assert cf.get_option("b.c") == "wurld"
+ assert cf.get_option("b.b") == 1.1
+
+ msg = r"No such keys\(s\): 'no.such.key'"
+ with pytest.raises(OptionError, match=msg):
+ cf.set_option("no.such.key", None)
+
+ def test_set_option_empty_args(self):
+ msg = "Must provide an even number of non-keyword arguments"
+ with pytest.raises(ValueError, match=msg):
+ cf.set_option()
+
+ def test_set_option_uneven_args(self):
+ msg = "Must provide an even number of non-keyword arguments"
+ with pytest.raises(ValueError, match=msg):
+ cf.set_option("a.b", 2, "b.c")
+
+ def test_set_option_invalid_single_argument_type(self):
+ msg = "Must provide an even number of non-keyword arguments"
+ with pytest.raises(ValueError, match=msg):
+ cf.set_option(2)
+
+ def test_set_option_multiple(self):
+ cf.register_option("a", 1, "doc")
+ cf.register_option("b.c", "hullo", "doc2")
+ cf.register_option("b.b", None, "doc2")
+
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b.c") == "hullo"
+ assert cf.get_option("b.b") is None
+
+ cf.set_option("a", "2", "b.c", None, "b.b", 10.0)
+
+ assert cf.get_option("a") == "2"
+ assert cf.get_option("b.c") is None
+ assert cf.get_option("b.b") == 10.0
+
+ def test_validation(self):
+ cf.register_option("a", 1, "doc", validator=cf.is_int)
+ cf.register_option("d", 1, "doc", validator=cf.is_nonnegative_int)
+ cf.register_option("b.c", "hullo", "doc2", validator=cf.is_text)
+
+ msg = "Value must have type ''"
+ with pytest.raises(ValueError, match=msg):
+ cf.register_option("a.b.c.d2", "NO", "doc", validator=cf.is_int)
+
+ cf.set_option("a", 2) # int is_int
+ cf.set_option("b.c", "wurld") # str is_str
+ cf.set_option("d", 2)
+ cf.set_option("d", None) # non-negative int can be None
+
+ # None not is_int
+ with pytest.raises(ValueError, match=msg):
+ cf.set_option("a", None)
+ with pytest.raises(ValueError, match=msg):
+ cf.set_option("a", "ab")
+
+ msg = "Value must be a nonnegative integer or None"
+ with pytest.raises(ValueError, match=msg):
+ cf.register_option("a.b.c.d3", "NO", "doc", validator=cf.is_nonnegative_int)
+ with pytest.raises(ValueError, match=msg):
+ cf.register_option("a.b.c.d3", -2, "doc", validator=cf.is_nonnegative_int)
+
+ msg = r"Value must be an instance of \|"
+ with pytest.raises(ValueError, match=msg):
+ cf.set_option("b.c", 1)
+
+ validator = cf.is_one_of_factory([None, cf.is_callable])
+ cf.register_option("b", lambda: None, "doc", validator=validator)
+ # pylint: disable-next=consider-using-f-string
+ cf.set_option("b", "%.1f".format) # Formatter is callable
+ cf.set_option("b", None) # Formatter is none (default)
+ with pytest.raises(ValueError, match="Value must be a callable"):
+ cf.set_option("b", "%.1f")
+
+ def test_reset_option(self):
+ cf.register_option("a", 1, "doc", validator=cf.is_int)
+ cf.register_option("b.c", "hullo", "doc2", validator=cf.is_str)
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b.c") == "hullo"
+
+ cf.set_option("a", 2)
+ cf.set_option("b.c", "wurld")
+ assert cf.get_option("a") == 2
+ assert cf.get_option("b.c") == "wurld"
+
+ cf.reset_option("a")
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b.c") == "wurld"
+ cf.reset_option("b.c")
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b.c") == "hullo"
+
+ def test_reset_option_all(self):
+ cf.register_option("a", 1, "doc", validator=cf.is_int)
+ cf.register_option("b.c", "hullo", "doc2", validator=cf.is_str)
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b.c") == "hullo"
+
+ cf.set_option("a", 2)
+ cf.set_option("b.c", "wurld")
+ assert cf.get_option("a") == 2
+ assert cf.get_option("b.c") == "wurld"
+
+ cf.reset_option("all")
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b.c") == "hullo"
+
+ def test_deprecate_option(self):
+ # we can deprecate non-existent options
+ cf.deprecate_option("foo")
+
+ assert cf._is_deprecated("foo")
+ with tm.assert_produces_warning(FutureWarning, match="deprecated"):
+ with pytest.raises(KeyError, match="No such keys.s.: 'foo'"):
+ cf.get_option("foo")
+
+ cf.register_option("a", 1, "doc", validator=cf.is_int)
+ cf.register_option("b.c", "hullo", "doc2")
+ cf.register_option("foo", "hullo", "doc2")
+
+ cf.deprecate_option("a", removal_ver="nifty_ver")
+ with tm.assert_produces_warning(FutureWarning, match="eprecated.*nifty_ver"):
+ cf.get_option("a")
+
+ msg = "Option 'a' has already been defined as deprecated"
+ with pytest.raises(OptionError, match=msg):
+ cf.deprecate_option("a")
+
+ cf.deprecate_option("b.c", "zounds!")
+ with tm.assert_produces_warning(FutureWarning, match="zounds!"):
+ cf.get_option("b.c")
+
+ # test rerouting keys
+ cf.register_option("d.a", "foo", "doc2")
+ cf.register_option("d.dep", "bar", "doc2")
+ assert cf.get_option("d.a") == "foo"
+ assert cf.get_option("d.dep") == "bar"
+
+ cf.deprecate_option("d.dep", rkey="d.a") # reroute d.dep to d.a
+ with tm.assert_produces_warning(FutureWarning, match="eprecated"):
+ assert cf.get_option("d.dep") == "foo"
+
+ with tm.assert_produces_warning(FutureWarning, match="eprecated"):
+ cf.set_option("d.dep", "baz") # should overwrite "d.a"
+
+ with tm.assert_produces_warning(FutureWarning, match="eprecated"):
+ assert cf.get_option("d.dep") == "baz"
+
+ def test_config_prefix(self):
+ with cf.config_prefix("base"):
+ cf.register_option("a", 1, "doc1")
+ cf.register_option("b", 2, "doc2")
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b") == 2
+
+ cf.set_option("a", 3)
+ cf.set_option("b", 4)
+ assert cf.get_option("a") == 3
+ assert cf.get_option("b") == 4
+
+ assert cf.get_option("base.a") == 3
+ assert cf.get_option("base.b") == 4
+ assert "doc1" in cf.describe_option("base.a", _print_desc=False)
+ assert "doc2" in cf.describe_option("base.b", _print_desc=False)
+
+ cf.reset_option("base.a")
+ cf.reset_option("base.b")
+
+ with cf.config_prefix("base"):
+ assert cf.get_option("a") == 1
+ assert cf.get_option("b") == 2
+
+ def test_callback(self):
+ k = [None]
+ v = [None]
+
+ def callback(key):
+ k.append(key)
+ v.append(cf.get_option(key))
+
+ cf.register_option("d.a", "foo", cb=callback)
+ cf.register_option("d.b", "foo", cb=callback)
+
+ del k[-1], v[-1]
+ cf.set_option("d.a", "fooz")
+ assert k[-1] == "d.a"
+ assert v[-1] == "fooz"
+
+ del k[-1], v[-1]
+ cf.set_option("d.b", "boo")
+ assert k[-1] == "d.b"
+ assert v[-1] == "boo"
+
+ del k[-1], v[-1]
+ cf.reset_option("d.b")
+ assert k[-1] == "d.b"
+
+ def test_set_ContextManager(self):
+ def eq(val):
+ assert cf.get_option("a") == val
+
+ cf.register_option("a", 0)
+ eq(0)
+ with cf.option_context("a", 15):
+ eq(15)
+ with cf.option_context("a", 25):
+ eq(25)
+ eq(15)
+ eq(0)
+
+ cf.set_option("a", 17)
+ eq(17)
+
+ # Test that option_context can be used as a decorator too (#34253).
+ @cf.option_context("a", 123)
+ def f():
+ eq(123)
+
+ f()
+
+ def test_attribute_access(self):
+ holder = []
+
+ def f3(key):
+ holder.append(True)
+
+ cf.register_option("a", 0)
+ cf.register_option("c", 0, cb=f3)
+ options = cf.options
+
+ assert options.a == 0
+ with cf.option_context("a", 15):
+ assert options.a == 15
+
+ options.a = 500
+ assert cf.get_option("a") == 500
+
+ cf.reset_option("a")
+ assert options.a == cf.get_option("a", 0)
+
+ msg = "You can only set the value of existing options"
+ with pytest.raises(OptionError, match=msg):
+ options.b = 1
+ with pytest.raises(OptionError, match=msg):
+ options.display = 1
+
+ # make sure callback kicks when using this form of setting
+ options.c = 1
+ assert len(holder) == 1
+
+ def test_option_context_scope(self):
+ # Ensure that creating a context does not affect the existing
+ # environment as it is supposed to be used with the `with` statement.
+ # See https://github.com/pandas-dev/pandas/issues/8514
+
+ original_value = 60
+ context_value = 10
+ option_name = "a"
+
+ cf.register_option(option_name, original_value)
+
+ # Ensure creating contexts didn't affect the current context.
+ ctx = cf.option_context(option_name, context_value)
+ assert cf.get_option(option_name) == original_value
+
+ # Ensure the correct value is available inside the context.
+ with ctx:
+ assert cf.get_option(option_name) == context_value
+
+ # Ensure the current context is reset
+ assert cf.get_option(option_name) == original_value
+
+ def test_dictwrapper_getattr(self):
+ options = cf.options
+ # GH 19789
+ with pytest.raises(OptionError, match="No such option"):
+ options.bananas
+ assert not hasattr(options, "bananas")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/config/test_localization.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/config/test_localization.py
new file mode 100644
index 0000000000000000000000000000000000000000..3907f557d1075536e46d12f219dc9b0c3f3f32c1
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/config/test_localization.py
@@ -0,0 +1,156 @@
+import codecs
+import locale
+import os
+
+import pytest
+
+from pandas._config.localization import (
+ can_set_locale,
+ get_locales,
+ set_locale,
+)
+
+from pandas.compat import ISMUSL
+
+import pandas as pd
+
+_all_locales = get_locales()
+_current_locale = locale.setlocale(locale.LC_ALL) # getlocale() is wrong, see GH#46595
+
+# Don't run any of these tests if we have no locales.
+pytestmark = pytest.mark.skipif(not _all_locales, reason="Need locales")
+
+_skip_if_only_one_locale = pytest.mark.skipif(
+ len(_all_locales) <= 1, reason="Need multiple locales for meaningful test"
+)
+
+
+def _get_current_locale(lc_var: int = locale.LC_ALL) -> str:
+ # getlocale is not always compliant with setlocale, use setlocale. GH#46595
+ return locale.setlocale(lc_var)
+
+
+@pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))
+def test_can_set_current_locale(lc_var):
+ # Can set the current locale
+ before_locale = _get_current_locale(lc_var)
+ assert can_set_locale(before_locale, lc_var=lc_var)
+ after_locale = _get_current_locale(lc_var)
+ assert before_locale == after_locale
+
+
+@pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))
+def test_can_set_locale_valid_set(lc_var):
+ # Can set the default locale.
+ before_locale = _get_current_locale(lc_var)
+ assert can_set_locale("", lc_var=lc_var)
+ after_locale = _get_current_locale(lc_var)
+ assert before_locale == after_locale
+
+
+@pytest.mark.parametrize(
+ "lc_var",
+ (
+ locale.LC_ALL,
+ locale.LC_CTYPE,
+ pytest.param(
+ locale.LC_TIME,
+ marks=pytest.mark.skipif(
+ ISMUSL, reason="MUSL allows setting invalid LC_TIME."
+ ),
+ ),
+ ),
+)
+def test_can_set_locale_invalid_set(lc_var):
+ # Cannot set an invalid locale.
+ before_locale = _get_current_locale(lc_var)
+ assert not can_set_locale("non-existent_locale", lc_var=lc_var)
+ after_locale = _get_current_locale(lc_var)
+ assert before_locale == after_locale
+
+
+@pytest.mark.parametrize(
+ "lang,enc",
+ [
+ ("it_CH", "UTF-8"),
+ ("en_US", "ascii"),
+ ("zh_CN", "GB2312"),
+ ("it_IT", "ISO-8859-1"),
+ ],
+)
+@pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))
+def test_can_set_locale_no_leak(lang, enc, lc_var):
+ # Test that can_set_locale does not leak even when returning False. See GH#46595
+ before_locale = _get_current_locale(lc_var)
+ can_set_locale((lang, enc), locale.LC_ALL)
+ after_locale = _get_current_locale(lc_var)
+ assert before_locale == after_locale
+
+
+def test_can_set_locale_invalid_get(monkeypatch):
+ # see GH#22129
+ # In some cases, an invalid locale can be set,
+ # but a subsequent getlocale() raises a ValueError.
+
+ def mock_get_locale():
+ raise ValueError()
+
+ with monkeypatch.context() as m:
+ m.setattr(locale, "getlocale", mock_get_locale)
+ assert not can_set_locale("")
+
+
+def test_get_locales_at_least_one():
+ # see GH#9744
+ assert len(_all_locales) > 0
+
+
+@_skip_if_only_one_locale
+def test_get_locales_prefix():
+ first_locale = _all_locales[0]
+ assert len(get_locales(prefix=first_locale[:2])) > 0
+
+
+@_skip_if_only_one_locale
+@pytest.mark.parametrize(
+ "lang,enc",
+ [
+ ("it_CH", "UTF-8"),
+ ("en_US", "ascii"),
+ ("zh_CN", "GB2312"),
+ ("it_IT", "ISO-8859-1"),
+ ],
+)
+def test_set_locale(lang, enc):
+ before_locale = _get_current_locale()
+
+ enc = codecs.lookup(enc).name
+ new_locale = lang, enc
+
+ if not can_set_locale(new_locale):
+ msg = "unsupported locale setting"
+
+ with pytest.raises(locale.Error, match=msg):
+ with set_locale(new_locale):
+ pass
+ else:
+ with set_locale(new_locale) as normalized_locale:
+ new_lang, new_enc = normalized_locale.split(".")
+ new_enc = codecs.lookup(enc).name
+
+ normalized_locale = new_lang, new_enc
+ assert normalized_locale == new_locale
+
+ # Once we exit the "with" statement, locale should be back to what it was.
+ after_locale = _get_current_locale()
+ assert before_locale == after_locale
+
+
+def test_encoding_detected():
+ system_locale = os.environ.get("LC_ALL")
+ system_encoding = system_locale.split(".")[-1] if system_locale else "utf-8"
+
+ assert (
+ codecs.lookup(pd.options.display.encoding).name
+ == codecs.lookup(system_encoding).name
+ )
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/construction/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/construction/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/construction/test_extract_array.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/construction/test_extract_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..4dd3eda8c995ce022e9d46b907323e79bcd679f8
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/construction/test_extract_array.py
@@ -0,0 +1,18 @@
+from pandas import Index
+import pandas._testing as tm
+from pandas.core.construction import extract_array
+
+
+def test_extract_array_rangeindex():
+ ri = Index(range(5))
+
+ expected = ri._values
+ res = extract_array(ri, extract_numpy=True, extract_range=True)
+ tm.assert_numpy_array_equal(res, expected)
+ res = extract_array(ri, extract_numpy=False, extract_range=True)
+ tm.assert_numpy_array_equal(res, expected)
+
+ res = extract_array(ri, extract_numpy=True, extract_range=False)
+ tm.assert_index_equal(res, ri)
+ res = extract_array(ri, extract_numpy=False, extract_range=False)
+ tm.assert_index_equal(res, ri)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_array.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..62a6a3374e61235e1e0cf0936944cc9aaa5a91dd
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_array.py
@@ -0,0 +1,185 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+# -----------------------------------------------------------------------------
+# Copy/view behaviour for accessing underlying array of Series/DataFrame
+
+
+@pytest.mark.parametrize(
+ "method",
+ [lambda ser: ser.values, lambda ser: np.asarray(ser)],
+ ids=["values", "asarray"],
+)
+def test_series_values(using_copy_on_write, method):
+ ser = Series([1, 2, 3], name="name")
+ ser_orig = ser.copy()
+
+ arr = method(ser)
+
+ if using_copy_on_write:
+ # .values still gives a view but is read-only
+ assert np.shares_memory(arr, get_array(ser, "name"))
+ assert arr.flags.writeable is False
+
+ # mutating series through arr therefore doesn't work
+ with pytest.raises(ValueError, match="read-only"):
+ arr[0] = 0
+ tm.assert_series_equal(ser, ser_orig)
+
+ # mutating the series itself still works
+ ser.iloc[0] = 0
+ assert ser.values[0] == 0
+ else:
+ assert arr.flags.writeable is True
+ arr[0] = 0
+ assert ser.iloc[0] == 0
+
+
+@pytest.mark.parametrize(
+ "method",
+ [lambda df: df.values, lambda df: np.asarray(df)],
+ ids=["values", "asarray"],
+)
+def test_dataframe_values(using_copy_on_write, using_array_manager, method):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df_orig = df.copy()
+
+ arr = method(df)
+
+ if using_copy_on_write:
+ # .values still gives a view but is read-only
+ assert np.shares_memory(arr, get_array(df, "a"))
+ assert arr.flags.writeable is False
+
+ # mutating series through arr therefore doesn't work
+ with pytest.raises(ValueError, match="read-only"):
+ arr[0, 0] = 0
+ tm.assert_frame_equal(df, df_orig)
+
+ # mutating the series itself still works
+ df.iloc[0, 0] = 0
+ assert df.values[0, 0] == 0
+ else:
+ assert arr.flags.writeable is True
+ arr[0, 0] = 0
+ if not using_array_manager:
+ assert df.iloc[0, 0] == 0
+ else:
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_series_to_numpy(using_copy_on_write):
+ ser = Series([1, 2, 3], name="name")
+ ser_orig = ser.copy()
+
+ # default: copy=False, no dtype or NAs
+ arr = ser.to_numpy()
+ if using_copy_on_write:
+ # to_numpy still gives a view but is read-only
+ assert np.shares_memory(arr, get_array(ser, "name"))
+ assert arr.flags.writeable is False
+
+ # mutating series through arr therefore doesn't work
+ with pytest.raises(ValueError, match="read-only"):
+ arr[0] = 0
+ tm.assert_series_equal(ser, ser_orig)
+
+ # mutating the series itself still works
+ ser.iloc[0] = 0
+ assert ser.values[0] == 0
+ else:
+ assert arr.flags.writeable is True
+ arr[0] = 0
+ assert ser.iloc[0] == 0
+
+ # specify copy=False gives a writeable array
+ ser = Series([1, 2, 3], name="name")
+ arr = ser.to_numpy(copy=True)
+ assert not np.shares_memory(arr, get_array(ser, "name"))
+ assert arr.flags.writeable is True
+
+ # specifying a dtype that already causes a copy also gives a writeable array
+ ser = Series([1, 2, 3], name="name")
+ arr = ser.to_numpy(dtype="float64")
+ assert not np.shares_memory(arr, get_array(ser, "name"))
+ assert arr.flags.writeable is True
+
+
+@pytest.mark.parametrize("order", ["F", "C"])
+def test_ravel_read_only(using_copy_on_write, order):
+ ser = Series([1, 2, 3])
+ arr = ser.ravel(order=order)
+ if using_copy_on_write:
+ assert arr.flags.writeable is False
+ assert np.shares_memory(get_array(ser), arr)
+
+
+def test_series_array_ea_dtypes(using_copy_on_write):
+ ser = Series([1, 2, 3], dtype="Int64")
+ arr = np.asarray(ser, dtype="int64")
+ assert np.shares_memory(arr, get_array(ser))
+ if using_copy_on_write:
+ assert arr.flags.writeable is False
+ else:
+ assert arr.flags.writeable is True
+
+ arr = np.asarray(ser)
+ assert not np.shares_memory(arr, get_array(ser))
+ assert arr.flags.writeable is True
+
+
+def test_dataframe_array_ea_dtypes(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3]}, dtype="Int64")
+ arr = np.asarray(df, dtype="int64")
+ # TODO: This should be able to share memory, but we are roundtripping
+ # through object
+ assert not np.shares_memory(arr, get_array(df, "a"))
+ assert arr.flags.writeable is True
+
+ arr = np.asarray(df)
+ if using_copy_on_write:
+ # TODO(CoW): This should be True
+ assert arr.flags.writeable is False
+ else:
+ assert arr.flags.writeable is True
+
+
+def test_dataframe_array_string_dtype(using_copy_on_write, using_array_manager):
+ df = DataFrame({"a": ["a", "b"]}, dtype="string")
+ arr = np.asarray(df)
+ if not using_array_manager:
+ assert np.shares_memory(arr, get_array(df, "a"))
+ if using_copy_on_write:
+ assert arr.flags.writeable is False
+ else:
+ assert arr.flags.writeable is True
+
+
+def test_dataframe_multiple_numpy_dtypes():
+ df = DataFrame({"a": [1, 2, 3], "b": 1.5})
+ arr = np.asarray(df)
+ assert not np.shares_memory(arr, get_array(df, "a"))
+ assert arr.flags.writeable is True
+
+
+def test_values_is_ea(using_copy_on_write):
+ df = DataFrame({"a": date_range("2012-01-01", periods=3)})
+ arr = np.asarray(df)
+ if using_copy_on_write:
+ assert arr.flags.writeable is False
+ else:
+ assert arr.flags.writeable is True
+
+
+def test_empty_dataframe():
+ df = DataFrame()
+ arr = np.asarray(df)
+ assert arr.flags.writeable is True
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_astype.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_astype.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b751ad452ec4c23b4cfc60c316f794262cfe91e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_astype.py
@@ -0,0 +1,250 @@
+import numpy as np
+import pytest
+
+from pandas.compat import pa_version_under7p0
+from pandas.compat.pyarrow import pa_version_under12p0
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+
+def test_astype_single_dtype(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": 1.5})
+ df_orig = df.copy()
+ df2 = df.astype("float64")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column/block
+ df2.iloc[0, 2] = 5.5
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ tm.assert_frame_equal(df, df_orig)
+
+ # mutating parent also doesn't update result
+ df2 = df.astype("float64")
+ df.iloc[0, 2] = 5.5
+ tm.assert_frame_equal(df2, df_orig.astype("float64"))
+
+
+@pytest.mark.parametrize("dtype", ["int64", "Int64"])
+@pytest.mark.parametrize("new_dtype", ["int64", "Int64", "int64[pyarrow]"])
+def test_astype_avoids_copy(using_copy_on_write, dtype, new_dtype):
+ if new_dtype == "int64[pyarrow]" and pa_version_under7p0:
+ pytest.skip("pyarrow not installed")
+ df = DataFrame({"a": [1, 2, 3]}, dtype=dtype)
+ df_orig = df.copy()
+ df2 = df.astype(new_dtype)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column/block
+ df2.iloc[0, 0] = 10
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+ # mutating parent also doesn't update result
+ df2 = df.astype(new_dtype)
+ df.iloc[0, 0] = 100
+ tm.assert_frame_equal(df2, df_orig.astype(new_dtype))
+
+
+@pytest.mark.parametrize("dtype", ["float64", "int32", "Int32", "int32[pyarrow]"])
+def test_astype_different_target_dtype(using_copy_on_write, dtype):
+ if dtype == "int32[pyarrow]" and pa_version_under7p0:
+ pytest.skip("pyarrow not installed")
+ df = DataFrame({"a": [1, 2, 3]})
+ df_orig = df.copy()
+ df2 = df.astype(dtype)
+
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ if using_copy_on_write:
+ assert df2._mgr._has_no_reference(0)
+
+ df2.iloc[0, 0] = 5
+ tm.assert_frame_equal(df, df_orig)
+
+ # mutating parent also doesn't update result
+ df2 = df.astype(dtype)
+ df.iloc[0, 0] = 100
+ tm.assert_frame_equal(df2, df_orig.astype(dtype))
+
+
+@td.skip_array_manager_invalid_test
+def test_astype_numpy_to_ea():
+ ser = Series([1, 2, 3])
+ with pd.option_context("mode.copy_on_write", True):
+ result = ser.astype("Int64")
+ assert np.shares_memory(get_array(ser), get_array(result))
+
+
+@pytest.mark.parametrize(
+ "dtype, new_dtype", [("object", "string"), ("string", "object")]
+)
+def test_astype_string_and_object(using_copy_on_write, dtype, new_dtype):
+ df = DataFrame({"a": ["a", "b", "c"]}, dtype=dtype)
+ df_orig = df.copy()
+ df2 = df.astype(new_dtype)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df2.iloc[0, 0] = "x"
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "dtype, new_dtype", [("object", "string"), ("string", "object")]
+)
+def test_astype_string_and_object_update_original(
+ using_copy_on_write, dtype, new_dtype
+):
+ df = DataFrame({"a": ["a", "b", "c"]}, dtype=dtype)
+ df2 = df.astype(new_dtype)
+ df_orig = df2.copy()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df.iloc[0, 0] = "x"
+ tm.assert_frame_equal(df2, df_orig)
+
+
+def test_astype_dict_dtypes(using_copy_on_write):
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": Series([1.5, 1.5, 1.5], dtype="float64")}
+ )
+ df_orig = df.copy()
+ df2 = df.astype({"a": "float64", "c": "float64"})
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column/block
+ df2.iloc[0, 2] = 5.5
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+
+ df2.iloc[0, 1] = 10
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_astype_different_datetime_resos(using_copy_on_write):
+ df = DataFrame({"a": date_range("2019-12-31", periods=2, freq="D")})
+ result = df.astype("datetime64[ms]")
+
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+ if using_copy_on_write:
+ assert result._mgr._has_no_reference(0)
+
+
+def test_astype_different_timezones(using_copy_on_write):
+ df = DataFrame(
+ {"a": date_range("2019-12-31", periods=5, freq="D", tz="US/Pacific")}
+ )
+ result = df.astype("datetime64[ns, Europe/Berlin]")
+ if using_copy_on_write:
+ assert not result._mgr._has_no_reference(0)
+ assert np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+
+
+def test_astype_different_timezones_different_reso(using_copy_on_write):
+ df = DataFrame(
+ {"a": date_range("2019-12-31", periods=5, freq="D", tz="US/Pacific")}
+ )
+ result = df.astype("datetime64[ms, Europe/Berlin]")
+ if using_copy_on_write:
+ assert result._mgr._has_no_reference(0)
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+
+
+@pytest.mark.skipif(pa_version_under7p0, reason="pyarrow not installed")
+def test_astype_arrow_timestamp(using_copy_on_write):
+ df = DataFrame(
+ {
+ "a": [
+ Timestamp("2020-01-01 01:01:01.000001"),
+ Timestamp("2020-01-01 01:01:01.000001"),
+ ]
+ },
+ dtype="M8[ns]",
+ )
+ result = df.astype("timestamp[ns][pyarrow]")
+ if using_copy_on_write:
+ assert not result._mgr._has_no_reference(0)
+ if pa_version_under12p0:
+ assert not np.shares_memory(
+ get_array(df, "a"), get_array(result, "a")._pa_array
+ )
+ else:
+ assert np.shares_memory(
+ get_array(df, "a"), get_array(result, "a")._pa_array
+ )
+
+
+def test_convert_dtypes_infer_objects(using_copy_on_write):
+ ser = Series(["a", "b", "c"])
+ ser_orig = ser.copy()
+ result = ser.convert_dtypes(
+ convert_integer=False,
+ convert_boolean=False,
+ convert_floating=False,
+ convert_string=False,
+ )
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(ser), get_array(result))
+ else:
+ assert not np.shares_memory(get_array(ser), get_array(result))
+
+ result.iloc[0] = "x"
+ tm.assert_series_equal(ser, ser_orig)
+
+
+def test_convert_dtypes(using_copy_on_write):
+ df = DataFrame({"a": ["a", "b"], "b": [1, 2], "c": [1.5, 2.5], "d": [True, False]})
+ df_orig = df.copy()
+ df2 = df.convert_dtypes()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ assert np.shares_memory(get_array(df2, "d"), get_array(df, "d"))
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ assert not np.shares_memory(get_array(df2, "d"), get_array(df, "d"))
+
+ df2.iloc[0, 0] = "x"
+ tm.assert_frame_equal(df, df_orig)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_clip.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a27a0633a4aa86139dbf02852835c605652821f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_clip.py
@@ -0,0 +1,83 @@
+import numpy as np
+
+from pandas import DataFrame
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+
+def test_clip_inplace_reference(using_copy_on_write):
+ df = DataFrame({"a": [1.5, 2, 3]})
+ df_copy = df.copy()
+ arr_a = get_array(df, "a")
+ view = df[:]
+ df.clip(lower=2, inplace=True)
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), arr_a)
+ assert df._mgr._has_no_reference(0)
+ assert view._mgr._has_no_reference(0)
+ tm.assert_frame_equal(df_copy, view)
+ else:
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+
+
+def test_clip_inplace_reference_no_op(using_copy_on_write):
+ df = DataFrame({"a": [1.5, 2, 3]})
+ df_copy = df.copy()
+ arr_a = get_array(df, "a")
+ view = df[:]
+ df.clip(lower=0, inplace=True)
+
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+
+ if using_copy_on_write:
+ assert not df._mgr._has_no_reference(0)
+ assert not view._mgr._has_no_reference(0)
+ tm.assert_frame_equal(df_copy, view)
+
+
+def test_clip_inplace(using_copy_on_write):
+ df = DataFrame({"a": [1.5, 2, 3]})
+ arr_a = get_array(df, "a")
+ df.clip(lower=2, inplace=True)
+
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+
+
+def test_clip(using_copy_on_write):
+ df = DataFrame({"a": [1.5, 2, 3]})
+ df_orig = df.copy()
+ df2 = df.clip(lower=2)
+
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ tm.assert_frame_equal(df_orig, df)
+
+
+def test_clip_no_op(using_copy_on_write):
+ df = DataFrame({"a": [1.5, 2, 3]})
+ df2 = df.clip(lower=0)
+
+ if using_copy_on_write:
+ assert not df._mgr._has_no_reference(0)
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+
+def test_clip_chained_inplace(using_copy_on_write):
+ df = DataFrame({"a": [1, 4, 2], "b": 1})
+ df_orig = df.copy()
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["a"].clip(1, 2, inplace=True)
+ tm.assert_frame_equal(df, df_orig)
+
+ with tm.raises_chained_assignment_error():
+ df[["a"]].clip(1, 2, inplace=True)
+ tm.assert_frame_equal(df, df_orig)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_constructors.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_constructors.py
new file mode 100644
index 0000000000000000000000000000000000000000..af7e759902f9f22d5dee533d7bea1b95d6ece5c6
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_constructors.py
@@ -0,0 +1,354 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ Period,
+ PeriodIndex,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ Timestamp,
+)
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+# -----------------------------------------------------------------------------
+# Copy/view behaviour for Series / DataFrame constructors
+
+
+@pytest.mark.parametrize("dtype", [None, "int64"])
+def test_series_from_series(dtype, using_copy_on_write):
+ # Case: constructing a Series from another Series object follows CoW rules:
+ # a new object is returned and thus mutations are not propagated
+ ser = Series([1, 2, 3], name="name")
+
+ # default is copy=False -> new Series is a shallow copy / view of original
+ result = Series(ser, dtype=dtype)
+
+ # the shallow copy still shares memory
+ assert np.shares_memory(get_array(ser), get_array(result))
+
+ if using_copy_on_write:
+ assert result._mgr.blocks[0].refs.has_reference()
+
+ if using_copy_on_write:
+ # mutating new series copy doesn't mutate original
+ result.iloc[0] = 0
+ assert ser.iloc[0] == 1
+ # mutating triggered a copy-on-write -> no longer shares memory
+ assert not np.shares_memory(get_array(ser), get_array(result))
+ else:
+ # mutating shallow copy does mutate original
+ result.iloc[0] = 0
+ assert ser.iloc[0] == 0
+ # and still shares memory
+ assert np.shares_memory(get_array(ser), get_array(result))
+
+ # the same when modifying the parent
+ result = Series(ser, dtype=dtype)
+
+ if using_copy_on_write:
+ # mutating original doesn't mutate new series
+ ser.iloc[0] = 0
+ assert result.iloc[0] == 1
+ else:
+ # mutating original does mutate shallow copy
+ ser.iloc[0] = 0
+ assert result.iloc[0] == 0
+
+
+def test_series_from_series_with_reindex(using_copy_on_write):
+ # Case: constructing a Series from another Series with specifying an index
+ # that potentially requires a reindex of the values
+ ser = Series([1, 2, 3], name="name")
+
+ # passing an index that doesn't actually require a reindex of the values
+ # -> without CoW we get an actual mutating view
+ for index in [
+ ser.index,
+ ser.index.copy(),
+ list(ser.index),
+ ser.index.rename("idx"),
+ ]:
+ result = Series(ser, index=index)
+ assert np.shares_memory(ser.values, result.values)
+ result.iloc[0] = 0
+ if using_copy_on_write:
+ assert ser.iloc[0] == 1
+ else:
+ assert ser.iloc[0] == 0
+
+ # ensure that if an actual reindex is needed, we don't have any refs
+ # (mutating the result wouldn't trigger CoW)
+ result = Series(ser, index=[0, 1, 2, 3])
+ assert not np.shares_memory(ser.values, result.values)
+ if using_copy_on_write:
+ assert not result._mgr.blocks[0].refs.has_reference()
+
+
+@pytest.mark.parametrize("fastpath", [False, True])
+@pytest.mark.parametrize("dtype", [None, "int64"])
+@pytest.mark.parametrize("idx", [None, pd.RangeIndex(start=0, stop=3, step=1)])
+@pytest.mark.parametrize(
+ "arr", [np.array([1, 2, 3], dtype="int64"), pd.array([1, 2, 3], dtype="Int64")]
+)
+def test_series_from_array(using_copy_on_write, idx, dtype, fastpath, arr):
+ if idx is None or dtype is not None:
+ fastpath = False
+ ser = Series(arr, dtype=dtype, index=idx, fastpath=fastpath)
+ ser_orig = ser.copy()
+ data = getattr(arr, "_data", arr)
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(ser), data)
+ else:
+ assert np.shares_memory(get_array(ser), data)
+
+ arr[0] = 100
+ if using_copy_on_write:
+ tm.assert_series_equal(ser, ser_orig)
+ else:
+ expected = Series([100, 2, 3], dtype=dtype if dtype is not None else arr.dtype)
+ tm.assert_series_equal(ser, expected)
+
+
+@pytest.mark.parametrize("copy", [True, False, None])
+def test_series_from_array_different_dtype(using_copy_on_write, copy):
+ arr = np.array([1, 2, 3], dtype="int64")
+ ser = Series(arr, dtype="int32", copy=copy)
+ assert not np.shares_memory(get_array(ser), arr)
+
+
+@pytest.mark.parametrize(
+ "idx",
+ [
+ Index([1, 2]),
+ DatetimeIndex([Timestamp("2019-12-31"), Timestamp("2020-12-31")]),
+ PeriodIndex([Period("2019-12-31"), Period("2020-12-31")]),
+ TimedeltaIndex([Timedelta("1 days"), Timedelta("2 days")]),
+ ],
+)
+def test_series_from_index(using_copy_on_write, idx):
+ ser = Series(idx)
+ expected = idx.copy(deep=True)
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(ser), get_array(idx))
+ assert not ser._mgr._has_no_reference(0)
+ else:
+ assert not np.shares_memory(get_array(ser), get_array(idx))
+ ser.iloc[0] = ser.iloc[1]
+ tm.assert_index_equal(idx, expected)
+
+
+def test_series_from_index_different_dtypes(using_copy_on_write):
+ idx = Index([1, 2, 3], dtype="int64")
+ ser = Series(idx, dtype="int32")
+ assert not np.shares_memory(get_array(ser), get_array(idx))
+ if using_copy_on_write:
+ assert ser._mgr._has_no_reference(0)
+
+
+@pytest.mark.parametrize("fastpath", [False, True])
+@pytest.mark.parametrize("dtype", [None, "int64"])
+@pytest.mark.parametrize("idx", [None, pd.RangeIndex(start=0, stop=3, step=1)])
+def test_series_from_block_manager(using_copy_on_write, idx, dtype, fastpath):
+ ser = Series([1, 2, 3], dtype="int64")
+ ser_orig = ser.copy()
+ ser2 = Series(ser._mgr, dtype=dtype, fastpath=fastpath, index=idx)
+ assert np.shares_memory(get_array(ser), get_array(ser2))
+ if using_copy_on_write:
+ assert not ser2._mgr._has_no_reference(0)
+
+ ser2.iloc[0] = 100
+ if using_copy_on_write:
+ tm.assert_series_equal(ser, ser_orig)
+ else:
+ expected = Series([100, 2, 3])
+ tm.assert_series_equal(ser, expected)
+
+
+def test_series_from_block_manager_different_dtype(using_copy_on_write):
+ ser = Series([1, 2, 3], dtype="int64")
+ ser2 = Series(ser._mgr, dtype="int32")
+ assert not np.shares_memory(get_array(ser), get_array(ser2))
+ if using_copy_on_write:
+ assert ser2._mgr._has_no_reference(0)
+
+
+@pytest.mark.parametrize("func", [lambda x: x, lambda x: x._mgr])
+@pytest.mark.parametrize("columns", [None, ["a"]])
+def test_dataframe_constructor_mgr_or_df(using_copy_on_write, columns, func):
+ df = DataFrame({"a": [1, 2, 3]})
+ df_orig = df.copy()
+
+ new_df = DataFrame(func(df))
+
+ assert np.shares_memory(get_array(df, "a"), get_array(new_df, "a"))
+ new_df.iloc[0] = 100
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), get_array(new_df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert np.shares_memory(get_array(df, "a"), get_array(new_df, "a"))
+ tm.assert_frame_equal(df, new_df)
+
+
+@pytest.mark.parametrize("dtype", [None, "int64", "Int64"])
+@pytest.mark.parametrize("index", [None, [0, 1, 2]])
+@pytest.mark.parametrize("columns", [None, ["a", "b"], ["a", "b", "c"]])
+def test_dataframe_from_dict_of_series(
+ request, using_copy_on_write, columns, index, dtype
+):
+ # Case: constructing a DataFrame from Series objects with copy=False
+ # has to do a lazy following CoW rules
+ # (the default for DataFrame(dict) is still to copy to ensure consolidation)
+ s1 = Series([1, 2, 3])
+ s2 = Series([4, 5, 6])
+ s1_orig = s1.copy()
+ expected = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6]}, index=index, columns=columns, dtype=dtype
+ )
+
+ result = DataFrame(
+ {"a": s1, "b": s2}, index=index, columns=columns, dtype=dtype, copy=False
+ )
+
+ # the shallow copy still shares memory
+ assert np.shares_memory(get_array(result, "a"), get_array(s1))
+
+ # mutating the new dataframe doesn't mutate original
+ result.iloc[0, 0] = 10
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(s1))
+ tm.assert_series_equal(s1, s1_orig)
+ else:
+ assert s1.iloc[0] == 10
+
+ # the same when modifying the parent series
+ s1 = Series([1, 2, 3])
+ s2 = Series([4, 5, 6])
+ result = DataFrame(
+ {"a": s1, "b": s2}, index=index, columns=columns, dtype=dtype, copy=False
+ )
+ s1.iloc[0] = 10
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(s1))
+ tm.assert_frame_equal(result, expected)
+ else:
+ assert result.iloc[0, 0] == 10
+
+
+@pytest.mark.parametrize("dtype", [None, "int64"])
+def test_dataframe_from_dict_of_series_with_reindex(dtype):
+ # Case: constructing a DataFrame from Series objects with copy=False
+ # and passing an index that requires an actual (no-view) reindex -> need
+ # to ensure the result doesn't have refs set up to unnecessarily trigger
+ # a copy on write
+ s1 = Series([1, 2, 3])
+ s2 = Series([4, 5, 6])
+ df = DataFrame({"a": s1, "b": s2}, index=[1, 2, 3], dtype=dtype, copy=False)
+
+ # df should own its memory, so mutating shouldn't trigger a copy
+ arr_before = get_array(df, "a")
+ assert not np.shares_memory(arr_before, get_array(s1))
+ df.iloc[0, 0] = 100
+ arr_after = get_array(df, "a")
+ assert np.shares_memory(arr_before, arr_after)
+
+
+@pytest.mark.parametrize("cons", [Series, Index])
+@pytest.mark.parametrize(
+ "data, dtype", [([1, 2], None), ([1, 2], "int64"), (["a", "b"], None)]
+)
+def test_dataframe_from_series_or_index(using_copy_on_write, data, dtype, cons):
+ obj = cons(data, dtype=dtype)
+ obj_orig = obj.copy()
+ df = DataFrame(obj, dtype=dtype)
+ assert np.shares_memory(get_array(obj), get_array(df, 0))
+ if using_copy_on_write:
+ assert not df._mgr._has_no_reference(0)
+
+ df.iloc[0, 0] = data[-1]
+ if using_copy_on_write:
+ tm.assert_equal(obj, obj_orig)
+
+
+@pytest.mark.parametrize("cons", [Series, Index])
+def test_dataframe_from_series_or_index_different_dtype(using_copy_on_write, cons):
+ obj = cons([1, 2], dtype="int64")
+ df = DataFrame(obj, dtype="int32")
+ assert not np.shares_memory(get_array(obj), get_array(df, 0))
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+
+
+def test_dataframe_from_series_infer_datetime(using_copy_on_write):
+ ser = Series([Timestamp("2019-12-31"), Timestamp("2020-12-31")], dtype=object)
+ df = DataFrame(ser)
+ assert not np.shares_memory(get_array(ser), get_array(df, 0))
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+
+
+@pytest.mark.parametrize("index", [None, [0, 1, 2]])
+def test_dataframe_from_dict_of_series_with_dtype(index):
+ # Variant of above, but now passing a dtype that causes a copy
+ # -> need to ensure the result doesn't have refs set up to unnecessarily
+ # trigger a copy on write
+ s1 = Series([1.0, 2.0, 3.0])
+ s2 = Series([4, 5, 6])
+ df = DataFrame({"a": s1, "b": s2}, index=index, dtype="int64", copy=False)
+
+ # df should own its memory, so mutating shouldn't trigger a copy
+ arr_before = get_array(df, "a")
+ assert not np.shares_memory(arr_before, get_array(s1))
+ df.iloc[0, 0] = 100
+ arr_after = get_array(df, "a")
+ assert np.shares_memory(arr_before, arr_after)
+
+
+@pytest.mark.parametrize("copy", [False, None, True])
+def test_frame_from_numpy_array(using_copy_on_write, copy, using_array_manager):
+ arr = np.array([[1, 2], [3, 4]])
+ df = DataFrame(arr, copy=copy)
+
+ if (
+ using_copy_on_write
+ and copy is not False
+ or copy is True
+ or (using_array_manager and copy is None)
+ ):
+ assert not np.shares_memory(get_array(df, 0), arr)
+ else:
+ assert np.shares_memory(get_array(df, 0), arr)
+
+
+def test_dataframe_from_records_with_dataframe(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3]})
+ df_orig = df.copy()
+ with tm.assert_produces_warning(FutureWarning):
+ df2 = DataFrame.from_records(df)
+ if using_copy_on_write:
+ assert not df._mgr._has_no_reference(0)
+ assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ df2.iloc[0, 0] = 100
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ tm.assert_frame_equal(df, df2)
+
+
+def test_frame_from_dict_of_index(using_copy_on_write):
+ idx = Index([1, 2, 3])
+ expected = idx.copy(deep=True)
+ df = DataFrame({"a": idx}, copy=False)
+ assert np.shares_memory(get_array(df, "a"), idx._values)
+ if using_copy_on_write:
+ assert not df._mgr._has_no_reference(0)
+
+ df.iloc[0, 0] = 100
+ tm.assert_index_equal(idx, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_core_functionalities.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_core_functionalities.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c177465d2fa400ca71ab3abf34b6ab8e98578cb
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_core_functionalities.py
@@ -0,0 +1,100 @@
+import numpy as np
+import pytest
+
+from pandas import DataFrame
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+
+def test_assigning_to_same_variable_removes_references(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3]})
+ df = df.reset_index()
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(1)
+ arr = get_array(df, "a")
+ df.iloc[0, 1] = 100 # Write into a
+
+ assert np.shares_memory(arr, get_array(df, "a"))
+
+
+def test_setitem_dont_track_unnecessary_references(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 1})
+
+ df["b"] = 100
+ arr = get_array(df, "a")
+ # We split the block in setitem, if we are not careful the new blocks will
+ # reference each other triggering a copy
+ df.iloc[0, 0] = 100
+ assert np.shares_memory(arr, get_array(df, "a"))
+
+
+def test_setitem_with_view_copies(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 1})
+ view = df[:]
+ expected = df.copy()
+
+ df["b"] = 100
+ arr = get_array(df, "a")
+ df.iloc[0, 0] = 100 # Check that we correctly track reference
+ if using_copy_on_write:
+ assert not np.shares_memory(arr, get_array(df, "a"))
+ tm.assert_frame_equal(view, expected)
+
+
+def test_setitem_with_view_invalidated_does_not_copy(using_copy_on_write, request):
+ df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 1})
+ view = df[:]
+
+ df["b"] = 100
+ arr = get_array(df, "a")
+ view = None # noqa: F841
+ df.iloc[0, 0] = 100
+ if using_copy_on_write:
+ # Setitem split the block. Since the old block shared data with view
+ # all the new blocks are referencing view and each other. When view
+ # goes out of scope, they don't share data with any other block,
+ # so we should not trigger a copy
+ mark = pytest.mark.xfail(
+ reason="blk.delete does not track references correctly"
+ )
+ request.node.add_marker(mark)
+ assert np.shares_memory(arr, get_array(df, "a"))
+
+
+def test_out_of_scope(using_copy_on_write):
+ def func():
+ df = DataFrame({"a": [1, 2], "b": 1.5, "c": 1})
+ # create some subset
+ result = df[["a", "b"]]
+ return result
+
+ result = func()
+ if using_copy_on_write:
+ assert not result._mgr.blocks[0].refs.has_reference()
+ assert not result._mgr.blocks[1].refs.has_reference()
+
+
+def test_delete(using_copy_on_write):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 3)), columns=["a", "b", "c"]
+ )
+ del df["b"]
+ if using_copy_on_write:
+ assert not df._mgr.blocks[0].refs.has_reference()
+ assert not df._mgr.blocks[1].refs.has_reference()
+
+ df = df[["a"]]
+ if using_copy_on_write:
+ assert not df._mgr.blocks[0].refs.has_reference()
+
+
+def test_delete_reference(using_copy_on_write):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 3)), columns=["a", "b", "c"]
+ )
+ x = df[:]
+ del df["b"]
+ if using_copy_on_write:
+ assert df._mgr.blocks[0].refs.has_reference()
+ assert df._mgr.blocks[1].refs.has_reference()
+ assert x._mgr.blocks[0].refs.has_reference()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_functions.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..56e4b186350f2719978d6ca3803154033c8e08af
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_functions.py
@@ -0,0 +1,396 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ concat,
+ merge,
+)
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+
+def test_concat_frames(using_copy_on_write):
+ df = DataFrame({"b": ["a"] * 3})
+ df2 = DataFrame({"a": ["a"] * 3})
+ df_orig = df.copy()
+ result = concat([df, df2], axis=1)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
+ else:
+ assert not np.shares_memory(get_array(result, "b"), get_array(df, "b"))
+ assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
+
+ result.iloc[0, 0] = "d"
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
+
+ result.iloc[0, 1] = "d"
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_concat_frames_updating_input(using_copy_on_write):
+ df = DataFrame({"b": ["a"] * 3})
+ df2 = DataFrame({"a": ["a"] * 3})
+ result = concat([df, df2], axis=1)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
+ else:
+ assert not np.shares_memory(get_array(result, "b"), get_array(df, "b"))
+ assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
+
+ expected = result.copy()
+ df.iloc[0, 0] = "d"
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
+
+ df2.iloc[0, 0] = "d"
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_concat_series(using_copy_on_write):
+ ser = Series([1, 2], name="a")
+ ser2 = Series([3, 4], name="b")
+ ser_orig = ser.copy()
+ ser2_orig = ser2.copy()
+ result = concat([ser, ser2], axis=1)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), ser.values)
+ assert np.shares_memory(get_array(result, "b"), ser2.values)
+ else:
+ assert not np.shares_memory(get_array(result, "a"), ser.values)
+ assert not np.shares_memory(get_array(result, "b"), ser2.values)
+
+ result.iloc[0, 0] = 100
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), ser.values)
+ assert np.shares_memory(get_array(result, "b"), ser2.values)
+
+ result.iloc[0, 1] = 1000
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "b"), ser2.values)
+ tm.assert_series_equal(ser, ser_orig)
+ tm.assert_series_equal(ser2, ser2_orig)
+
+
+def test_concat_frames_chained(using_copy_on_write):
+ df1 = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
+ df2 = DataFrame({"c": [4, 5, 6]})
+ df3 = DataFrame({"d": [4, 5, 6]})
+ result = concat([concat([df1, df2], axis=1), df3], axis=1)
+ expected = result.copy()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert np.shares_memory(get_array(result, "c"), get_array(df2, "c"))
+ assert np.shares_memory(get_array(result, "d"), get_array(df3, "d"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert not np.shares_memory(get_array(result, "c"), get_array(df2, "c"))
+ assert not np.shares_memory(get_array(result, "d"), get_array(df3, "d"))
+
+ df1.iloc[0, 0] = 100
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_concat_series_chained(using_copy_on_write):
+ ser1 = Series([1, 2, 3], name="a")
+ ser2 = Series([4, 5, 6], name="c")
+ ser3 = Series([4, 5, 6], name="d")
+ result = concat([concat([ser1, ser2], axis=1), ser3], axis=1)
+ expected = result.copy()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(ser1, "a"))
+ assert np.shares_memory(get_array(result, "c"), get_array(ser2, "c"))
+ assert np.shares_memory(get_array(result, "d"), get_array(ser3, "d"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(ser1, "a"))
+ assert not np.shares_memory(get_array(result, "c"), get_array(ser2, "c"))
+ assert not np.shares_memory(get_array(result, "d"), get_array(ser3, "d"))
+
+ ser1.iloc[0] = 100
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(ser1, "a"))
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_concat_series_updating_input(using_copy_on_write):
+ ser = Series([1, 2], name="a")
+ ser2 = Series([3, 4], name="b")
+ expected = DataFrame({"a": [1, 2], "b": [3, 4]})
+ result = concat([ser, ser2], axis=1)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(ser, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(ser2, "b"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(ser, "a"))
+ assert not np.shares_memory(get_array(result, "b"), get_array(ser2, "b"))
+
+ ser.iloc[0] = 100
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(ser, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(ser2, "b"))
+ tm.assert_frame_equal(result, expected)
+
+ ser2.iloc[0] = 1000
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "b"), get_array(ser2, "b"))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_concat_mixed_series_frame(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "c": 1})
+ ser = Series([4, 5, 6], name="d")
+ result = concat([df, ser], axis=1)
+ expected = result.copy()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ assert np.shares_memory(get_array(result, "c"), get_array(df, "c"))
+ assert np.shares_memory(get_array(result, "d"), get_array(ser, "d"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ assert not np.shares_memory(get_array(result, "c"), get_array(df, "c"))
+ assert not np.shares_memory(get_array(result, "d"), get_array(ser, "d"))
+
+ ser.iloc[0] = 100
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "d"), get_array(ser, "d"))
+
+ df.iloc[0, 0] = 100
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("copy", [True, None, False])
+def test_concat_copy_keyword(using_copy_on_write, copy):
+ df = DataFrame({"a": [1, 2]})
+ df2 = DataFrame({"b": [1.5, 2.5]})
+
+ result = concat([df, df2], axis=1, copy=copy)
+
+ if using_copy_on_write or copy is False:
+ assert np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+ assert np.shares_memory(get_array(df2, "b"), get_array(result, "b"))
+ else:
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+ assert not np.shares_memory(get_array(df2, "b"), get_array(result, "b"))
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ lambda df1, df2, **kwargs: df1.merge(df2, **kwargs),
+ lambda df1, df2, **kwargs: merge(df1, df2, **kwargs),
+ ],
+)
+def test_merge_on_key(using_copy_on_write, func):
+ df1 = DataFrame({"key": ["a", "b", "c"], "a": [1, 2, 3]})
+ df2 = DataFrame({"key": ["a", "b", "c"], "b": [4, 5, 6]})
+ df1_orig = df1.copy()
+ df2_orig = df2.copy()
+
+ result = func(df1, df2, on="key")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+ assert np.shares_memory(get_array(result, "key"), get_array(df1, "key"))
+ assert not np.shares_memory(get_array(result, "key"), get_array(df2, "key"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+
+ result.iloc[0, 1] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+
+ result.iloc[0, 2] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+ tm.assert_frame_equal(df1, df1_orig)
+ tm.assert_frame_equal(df2, df2_orig)
+
+
+def test_merge_on_index(using_copy_on_write):
+ df1 = DataFrame({"a": [1, 2, 3]})
+ df2 = DataFrame({"b": [4, 5, 6]})
+ df1_orig = df1.copy()
+ df2_orig = df2.copy()
+
+ result = merge(df1, df2, left_index=True, right_index=True)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+
+ result.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+
+ result.iloc[0, 1] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+ tm.assert_frame_equal(df1, df1_orig)
+ tm.assert_frame_equal(df2, df2_orig)
+
+
+@pytest.mark.parametrize(
+ "func, how",
+ [
+ (lambda df1, df2, **kwargs: merge(df2, df1, on="key", **kwargs), "right"),
+ (lambda df1, df2, **kwargs: merge(df1, df2, on="key", **kwargs), "left"),
+ ],
+)
+def test_merge_on_key_enlarging_one(using_copy_on_write, func, how):
+ df1 = DataFrame({"key": ["a", "b", "c"], "a": [1, 2, 3]})
+ df2 = DataFrame({"key": ["a", "b"], "b": [4, 5]})
+ df1_orig = df1.copy()
+ df2_orig = df2.copy()
+
+ result = func(df1, df2, how=how)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+ assert df2._mgr._has_no_reference(1)
+ assert df2._mgr._has_no_reference(0)
+ assert np.shares_memory(get_array(result, "key"), get_array(df1, "key")) is (
+ how == "left"
+ )
+ assert not np.shares_memory(get_array(result, "key"), get_array(df2, "key"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+
+ if how == "left":
+ result.iloc[0, 1] = 0
+ else:
+ result.iloc[0, 2] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ tm.assert_frame_equal(df1, df1_orig)
+ tm.assert_frame_equal(df2, df2_orig)
+
+
+@pytest.mark.parametrize("copy", [True, None, False])
+def test_merge_copy_keyword(using_copy_on_write, copy):
+ df = DataFrame({"a": [1, 2]})
+ df2 = DataFrame({"b": [3, 4.5]})
+
+ result = df.merge(df2, copy=copy, left_index=True, right_index=True)
+
+ if using_copy_on_write or copy is False:
+ assert np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+ assert np.shares_memory(get_array(df2, "b"), get_array(result, "b"))
+ else:
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+ assert not np.shares_memory(get_array(df2, "b"), get_array(result, "b"))
+
+
+def test_join_on_key(using_copy_on_write):
+ df_index = Index(["a", "b", "c"], name="key")
+
+ df1 = DataFrame({"a": [1, 2, 3]}, index=df_index.copy(deep=True))
+ df2 = DataFrame({"b": [4, 5, 6]}, index=df_index.copy(deep=True))
+
+ df1_orig = df1.copy()
+ df2_orig = df2.copy()
+
+ result = df1.join(df2, on="key")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+ assert np.shares_memory(get_array(result.index), get_array(df1.index))
+ assert not np.shares_memory(get_array(result.index), get_array(df2.index))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+
+ result.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+
+ result.iloc[0, 1] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b"))
+
+ tm.assert_frame_equal(df1, df1_orig)
+ tm.assert_frame_equal(df2, df2_orig)
+
+
+def test_join_multiple_dataframes_on_key(using_copy_on_write):
+ df_index = Index(["a", "b", "c"], name="key")
+
+ df1 = DataFrame({"a": [1, 2, 3]}, index=df_index.copy(deep=True))
+ dfs_list = [
+ DataFrame({"b": [4, 5, 6]}, index=df_index.copy(deep=True)),
+ DataFrame({"c": [7, 8, 9]}, index=df_index.copy(deep=True)),
+ ]
+
+ df1_orig = df1.copy()
+ dfs_list_orig = [df.copy() for df in dfs_list]
+
+ result = df1.join(dfs_list)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b"))
+ assert np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c"))
+ assert np.shares_memory(get_array(result.index), get_array(df1.index))
+ assert not np.shares_memory(
+ get_array(result.index), get_array(dfs_list[0].index)
+ )
+ assert not np.shares_memory(
+ get_array(result.index), get_array(dfs_list[1].index)
+ )
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert not np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b"))
+ assert not np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c"))
+
+ result.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a"))
+ assert np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b"))
+ assert np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c"))
+
+ result.iloc[0, 1] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b"))
+ assert np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c"))
+
+ result.iloc[0, 2] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c"))
+
+ tm.assert_frame_equal(df1, df1_orig)
+ for df, df_orig in zip(dfs_list, dfs_list_orig):
+ tm.assert_frame_equal(df, df_orig)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_indexing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_indexing.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebb25bd5c57d3ca8f3b9a469eea57acf54248fc0
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_indexing.py
@@ -0,0 +1,1119 @@
+import numpy as np
+import pytest
+
+from pandas.errors import SettingWithCopyWarning
+
+from pandas.core.dtypes.common import is_float_dtype
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+)
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+
+@pytest.fixture(params=["numpy", "nullable"])
+def backend(request):
+ if request.param == "numpy":
+
+ def make_dataframe(*args, **kwargs):
+ return DataFrame(*args, **kwargs)
+
+ def make_series(*args, **kwargs):
+ return Series(*args, **kwargs)
+
+ elif request.param == "nullable":
+
+ def make_dataframe(*args, **kwargs):
+ df = DataFrame(*args, **kwargs)
+ df_nullable = df.convert_dtypes()
+ # convert_dtypes will try to cast float to int if there is no loss in
+ # precision -> undo that change
+ for col in df.columns:
+ if is_float_dtype(df[col].dtype) and not is_float_dtype(
+ df_nullable[col].dtype
+ ):
+ df_nullable[col] = df_nullable[col].astype("Float64")
+ # copy final result to ensure we start with a fully self-owning DataFrame
+ return df_nullable.copy()
+
+ def make_series(*args, **kwargs):
+ ser = Series(*args, **kwargs)
+ return ser.convert_dtypes().copy()
+
+ return request.param, make_dataframe, make_series
+
+
+# -----------------------------------------------------------------------------
+# Indexing operations taking subset + modifying the subset/parent
+
+
+def test_subset_column_selection(backend, using_copy_on_write):
+ # Case: taking a subset of the columns of a DataFrame
+ # + afterwards modifying the subset
+ _, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+
+ subset = df[["a", "c"]]
+
+ if using_copy_on_write:
+ # the subset shares memory ...
+ assert np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
+ # ... but uses CoW when being modified
+ subset.iloc[0, 0] = 0
+ else:
+ assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
+ # INFO this no longer raise warning since pandas 1.4
+ # with pd.option_context("chained_assignment", "warn"):
+ # with tm.assert_produces_warning(SettingWithCopyWarning):
+ subset.iloc[0, 0] = 0
+
+ assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
+
+ expected = DataFrame({"a": [0, 2, 3], "c": [0.1, 0.2, 0.3]})
+ tm.assert_frame_equal(subset, expected)
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_subset_column_selection_modify_parent(backend, using_copy_on_write):
+ # Case: taking a subset of the columns of a DataFrame
+ # + afterwards modifying the parent
+ _, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+
+ subset = df[["a", "c"]]
+
+ if using_copy_on_write:
+ # the subset shares memory ...
+ assert np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
+ # ... but parent uses CoW parent when it is modified
+ df.iloc[0, 0] = 0
+
+ assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
+ if using_copy_on_write:
+ # different column/block still shares memory
+ assert np.shares_memory(get_array(subset, "c"), get_array(df, "c"))
+
+ expected = DataFrame({"a": [1, 2, 3], "c": [0.1, 0.2, 0.3]})
+ tm.assert_frame_equal(subset, expected)
+
+
+def test_subset_row_slice(backend, using_copy_on_write):
+ # Case: taking a subset of the rows of a DataFrame using a slice
+ # + afterwards modifying the subset
+ _, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+
+ subset = df[1:3]
+ subset._mgr._verify_integrity()
+
+ assert np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
+
+ if using_copy_on_write:
+ subset.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
+
+ else:
+ # INFO this no longer raise warning since pandas 1.4
+ # with pd.option_context("chained_assignment", "warn"):
+ # with tm.assert_produces_warning(SettingWithCopyWarning):
+ subset.iloc[0, 0] = 0
+
+ subset._mgr._verify_integrity()
+
+ expected = DataFrame({"a": [0, 3], "b": [5, 6], "c": [0.2, 0.3]}, index=range(1, 3))
+ tm.assert_frame_equal(subset, expected)
+ if using_copy_on_write:
+ # original parent dataframe is not modified (CoW)
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ # original parent dataframe is actually updated
+ df_orig.iloc[1, 0] = 0
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
+)
+def test_subset_column_slice(backend, using_copy_on_write, using_array_manager, dtype):
+ # Case: taking a subset of the columns of a DataFrame using a slice
+ # + afterwards modifying the subset
+ dtype_backend, DataFrame, _ = backend
+ single_block = (
+ dtype == "int64" and dtype_backend == "numpy"
+ ) and not using_array_manager
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
+ )
+ df_orig = df.copy()
+
+ subset = df.iloc[:, 1:]
+ subset._mgr._verify_integrity()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(subset, "b"), get_array(df, "b"))
+
+ subset.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(subset, "b"), get_array(df, "b"))
+
+ else:
+ # we only get a warning in case of a single block
+ warn = SettingWithCopyWarning if single_block else None
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(warn):
+ subset.iloc[0, 0] = 0
+
+ expected = DataFrame({"b": [0, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)})
+ tm.assert_frame_equal(subset, expected)
+ # original parent dataframe is not modified (also not for BlockManager case,
+ # except for single block)
+ if not using_copy_on_write and (using_array_manager or single_block):
+ df_orig.iloc[0, 1] = 0
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
+)
+@pytest.mark.parametrize(
+ "row_indexer",
+ [slice(1, 2), np.array([False, True, True]), np.array([1, 2])],
+ ids=["slice", "mask", "array"],
+)
+@pytest.mark.parametrize(
+ "column_indexer",
+ [slice("b", "c"), np.array([False, True, True]), ["b", "c"]],
+ ids=["slice", "mask", "array"],
+)
+def test_subset_loc_rows_columns(
+ backend,
+ dtype,
+ row_indexer,
+ column_indexer,
+ using_array_manager,
+ using_copy_on_write,
+):
+ # Case: taking a subset of the rows+columns of a DataFrame using .loc
+ # + afterwards modifying the subset
+ # Generic test for several combinations of row/column indexers, not all
+ # of those could actually return a view / need CoW (so this test is not
+ # checking memory sharing, only ensuring subsequent mutation doesn't
+ # affect the parent dataframe)
+ dtype_backend, DataFrame, _ = backend
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
+ )
+ df_orig = df.copy()
+
+ subset = df.loc[row_indexer, column_indexer]
+
+ # modifying the subset never modifies the parent
+ subset.iloc[0, 0] = 0
+
+ expected = DataFrame(
+ {"b": [0, 6], "c": np.array([8, 9], dtype=dtype)}, index=range(1, 3)
+ )
+ tm.assert_frame_equal(subset, expected)
+ # a few corner cases _do_ actually modify the parent (with both row and column
+ # slice, and in case of ArrayManager or BlockManager with single block)
+ if (
+ isinstance(row_indexer, slice)
+ and isinstance(column_indexer, slice)
+ and (
+ using_array_manager
+ or (
+ dtype == "int64"
+ and dtype_backend == "numpy"
+ and not using_copy_on_write
+ )
+ )
+ ):
+ df_orig.iloc[1, 1] = 0
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
+)
+@pytest.mark.parametrize(
+ "row_indexer",
+ [slice(1, 3), np.array([False, True, True]), np.array([1, 2])],
+ ids=["slice", "mask", "array"],
+)
+@pytest.mark.parametrize(
+ "column_indexer",
+ [slice(1, 3), np.array([False, True, True]), [1, 2]],
+ ids=["slice", "mask", "array"],
+)
+def test_subset_iloc_rows_columns(
+ backend,
+ dtype,
+ row_indexer,
+ column_indexer,
+ using_array_manager,
+ using_copy_on_write,
+):
+ # Case: taking a subset of the rows+columns of a DataFrame using .iloc
+ # + afterwards modifying the subset
+ # Generic test for several combinations of row/column indexers, not all
+ # of those could actually return a view / need CoW (so this test is not
+ # checking memory sharing, only ensuring subsequent mutation doesn't
+ # affect the parent dataframe)
+ dtype_backend, DataFrame, _ = backend
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
+ )
+ df_orig = df.copy()
+
+ subset = df.iloc[row_indexer, column_indexer]
+
+ # modifying the subset never modifies the parent
+ subset.iloc[0, 0] = 0
+
+ expected = DataFrame(
+ {"b": [0, 6], "c": np.array([8, 9], dtype=dtype)}, index=range(1, 3)
+ )
+ tm.assert_frame_equal(subset, expected)
+ # a few corner cases _do_ actually modify the parent (with both row and column
+ # slice, and in case of ArrayManager or BlockManager with single block)
+ if (
+ isinstance(row_indexer, slice)
+ and isinstance(column_indexer, slice)
+ and (
+ using_array_manager
+ or (
+ dtype == "int64"
+ and dtype_backend == "numpy"
+ and not using_copy_on_write
+ )
+ )
+ ):
+ df_orig.iloc[1, 1] = 0
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "indexer",
+ [slice(0, 2), np.array([True, True, False]), np.array([0, 1])],
+ ids=["slice", "mask", "array"],
+)
+def test_subset_set_with_row_indexer(backend, indexer_si, indexer, using_copy_on_write):
+ # Case: setting values with a row indexer on a viewing subset
+ # subset[indexer] = value and subset.iloc[indexer] = value
+ _, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3, 4], "b": [4, 5, 6, 7], "c": [0.1, 0.2, 0.3, 0.4]})
+ df_orig = df.copy()
+ subset = df[1:4]
+
+ if (
+ indexer_si is tm.setitem
+ and isinstance(indexer, np.ndarray)
+ and indexer.dtype == "int"
+ ):
+ pytest.skip("setitem with labels selects on columns")
+
+ if using_copy_on_write:
+ indexer_si(subset)[indexer] = 0
+ else:
+ # INFO iloc no longer raises warning since pandas 1.4
+ warn = SettingWithCopyWarning if indexer_si is tm.setitem else None
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(warn):
+ indexer_si(subset)[indexer] = 0
+
+ expected = DataFrame(
+ {"a": [0, 0, 4], "b": [0, 0, 7], "c": [0.0, 0.0, 0.4]}, index=range(1, 4)
+ )
+ tm.assert_frame_equal(subset, expected)
+ if using_copy_on_write:
+ # original parent dataframe is not modified (CoW)
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ # original parent dataframe is actually updated
+ df_orig[1:3] = 0
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_subset_set_with_mask(backend, using_copy_on_write):
+ # Case: setting values with a mask on a viewing subset: subset[mask] = value
+ _, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3, 4], "b": [4, 5, 6, 7], "c": [0.1, 0.2, 0.3, 0.4]})
+ df_orig = df.copy()
+ subset = df[1:4]
+
+ mask = subset > 3
+
+ if using_copy_on_write:
+ subset[mask] = 0
+ else:
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(SettingWithCopyWarning):
+ subset[mask] = 0
+
+ expected = DataFrame(
+ {"a": [2, 3, 0], "b": [0, 0, 0], "c": [0.20, 0.3, 0.4]}, index=range(1, 4)
+ )
+ tm.assert_frame_equal(subset, expected)
+ if using_copy_on_write:
+ # original parent dataframe is not modified (CoW)
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ # original parent dataframe is actually updated
+ df_orig.loc[3, "a"] = 0
+ df_orig.loc[1:3, "b"] = 0
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_subset_set_column(backend, using_copy_on_write):
+ # Case: setting a single column on a viewing subset -> subset[col] = value
+ dtype_backend, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ subset = df[1:3]
+
+ if dtype_backend == "numpy":
+ arr = np.array([10, 11], dtype="int64")
+ else:
+ arr = pd.array([10, 11], dtype="Int64")
+
+ if using_copy_on_write:
+ subset["a"] = arr
+ else:
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(SettingWithCopyWarning):
+ subset["a"] = arr
+
+ subset._mgr._verify_integrity()
+ expected = DataFrame(
+ {"a": [10, 11], "b": [5, 6], "c": [0.2, 0.3]}, index=range(1, 3)
+ )
+ tm.assert_frame_equal(subset, expected)
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
+)
+def test_subset_set_column_with_loc(
+ backend, using_copy_on_write, using_array_manager, dtype
+):
+ # Case: setting a single column with loc on a viewing subset
+ # -> subset.loc[:, col] = value
+ _, DataFrame, _ = backend
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
+ )
+ df_orig = df.copy()
+ subset = df[1:3]
+
+ if using_copy_on_write:
+ subset.loc[:, "a"] = np.array([10, 11], dtype="int64")
+ else:
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(
+ None,
+ raise_on_extra_warnings=not using_array_manager,
+ ):
+ subset.loc[:, "a"] = np.array([10, 11], dtype="int64")
+
+ subset._mgr._verify_integrity()
+ expected = DataFrame(
+ {"a": [10, 11], "b": [5, 6], "c": np.array([8, 9], dtype=dtype)},
+ index=range(1, 3),
+ )
+ tm.assert_frame_equal(subset, expected)
+ if using_copy_on_write:
+ # original parent dataframe is not modified (CoW)
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ # original parent dataframe is actually updated
+ df_orig.loc[1:3, "a"] = np.array([10, 11], dtype="int64")
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_subset_set_column_with_loc2(backend, using_copy_on_write, using_array_manager):
+ # Case: setting a single column with loc on a viewing subset
+ # -> subset.loc[:, col] = value
+ # separate test for case of DataFrame of a single column -> takes a separate
+ # code path
+ _, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3]})
+ df_orig = df.copy()
+ subset = df[1:3]
+
+ if using_copy_on_write:
+ subset.loc[:, "a"] = 0
+ else:
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(
+ None,
+ raise_on_extra_warnings=not using_array_manager,
+ ):
+ subset.loc[:, "a"] = 0
+
+ subset._mgr._verify_integrity()
+ expected = DataFrame({"a": [0, 0]}, index=range(1, 3))
+ tm.assert_frame_equal(subset, expected)
+ if using_copy_on_write:
+ # original parent dataframe is not modified (CoW)
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ # original parent dataframe is actually updated
+ df_orig.loc[1:3, "a"] = 0
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
+)
+def test_subset_set_columns(backend, using_copy_on_write, dtype):
+ # Case: setting multiple columns on a viewing subset
+ # -> subset[[col1, col2]] = value
+ dtype_backend, DataFrame, _ = backend
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
+ )
+ df_orig = df.copy()
+ subset = df[1:3]
+
+ if using_copy_on_write:
+ subset[["a", "c"]] = 0
+ else:
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(SettingWithCopyWarning):
+ subset[["a", "c"]] = 0
+
+ subset._mgr._verify_integrity()
+ if using_copy_on_write:
+ # first and third column should certainly have no references anymore
+ assert all(subset._mgr._has_no_reference(i) for i in [0, 2])
+ expected = DataFrame({"a": [0, 0], "b": [5, 6], "c": [0, 0]}, index=range(1, 3))
+ if dtype_backend == "nullable":
+ # there is not yet a global option, so overriding a column by setting a scalar
+ # defaults to numpy dtype even if original column was nullable
+ expected["a"] = expected["a"].astype("int64")
+ expected["c"] = expected["c"].astype("int64")
+
+ tm.assert_frame_equal(subset, expected)
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "indexer",
+ [slice("a", "b"), np.array([True, True, False]), ["a", "b"]],
+ ids=["slice", "mask", "array"],
+)
+def test_subset_set_with_column_indexer(backend, indexer, using_copy_on_write):
+ # Case: setting multiple columns with a column indexer on a viewing subset
+ # -> subset.loc[:, [col1, col2]] = value
+ _, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]})
+ df_orig = df.copy()
+ subset = df[1:3]
+
+ if using_copy_on_write:
+ subset.loc[:, indexer] = 0
+ else:
+ with pd.option_context("chained_assignment", "warn"):
+ # As of 2.0, this setitem attempts (successfully) to set values
+ # inplace, so the assignment is not chained.
+ subset.loc[:, indexer] = 0
+
+ subset._mgr._verify_integrity()
+ expected = DataFrame({"a": [0, 0], "b": [0.0, 0.0], "c": [5, 6]}, index=range(1, 3))
+ tm.assert_frame_equal(subset, expected)
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ # pre-2.0, in the mixed case with BlockManager, only column "a"
+ # would be mutated in the parent frame. this changed with the
+ # enforcement of GH#45333
+ df_orig.loc[1:2, ["a", "b"]] = 0
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ lambda df: df[["a", "b"]][0:2],
+ lambda df: df[0:2][["a", "b"]],
+ lambda df: df[["a", "b"]].iloc[0:2],
+ lambda df: df[["a", "b"]].loc[0:1],
+ lambda df: df[0:2].iloc[:, 0:2],
+ lambda df: df[0:2].loc[:, "a":"b"], # type: ignore[misc]
+ ],
+ ids=[
+ "row-getitem-slice",
+ "column-getitem",
+ "row-iloc-slice",
+ "row-loc-slice",
+ "column-iloc-slice",
+ "column-loc-slice",
+ ],
+)
+@pytest.mark.parametrize(
+ "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
+)
+def test_subset_chained_getitem(
+ request, backend, method, dtype, using_copy_on_write, using_array_manager
+):
+ # Case: creating a subset using multiple, chained getitem calls using views
+ # still needs to guarantee proper CoW behaviour
+ _, DataFrame, _ = backend
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
+ )
+ df_orig = df.copy()
+
+ # when not using CoW, it depends on whether we have a single block or not
+ # and whether we are slicing the columns -> in that case we have a view
+ test_callspec = request.node.callspec.id
+ if not using_array_manager:
+ subset_is_view = test_callspec in (
+ "numpy-single-block-column-iloc-slice",
+ "numpy-single-block-column-loc-slice",
+ )
+ else:
+ # with ArrayManager, it doesn't matter whether we have
+ # single vs mixed block or numpy vs nullable dtypes
+ subset_is_view = test_callspec.endswith(
+ ("column-iloc-slice", "column-loc-slice")
+ )
+
+ # modify subset -> don't modify parent
+ subset = method(df)
+ subset.iloc[0, 0] = 0
+ if using_copy_on_write or (not subset_is_view):
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert df.iloc[0, 0] == 0
+
+ # modify parent -> don't modify subset
+ subset = method(df)
+ df.iloc[0, 0] = 0
+ expected = DataFrame({"a": [1, 2], "b": [4, 5]})
+ if using_copy_on_write or not subset_is_view:
+ tm.assert_frame_equal(subset, expected)
+ else:
+ assert subset.iloc[0, 0] == 0
+
+
+@pytest.mark.parametrize(
+ "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
+)
+def test_subset_chained_getitem_column(backend, dtype, using_copy_on_write):
+ # Case: creating a subset using multiple, chained getitem calls using views
+ # still needs to guarantee proper CoW behaviour
+ _, DataFrame, Series = backend
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
+ )
+ df_orig = df.copy()
+
+ # modify subset -> don't modify parent
+ subset = df[:]["a"][0:2]
+ df._clear_item_cache()
+ subset.iloc[0] = 0
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert df.iloc[0, 0] == 0
+
+ # modify parent -> don't modify subset
+ subset = df[:]["a"][0:2]
+ df._clear_item_cache()
+ df.iloc[0, 0] = 0
+ expected = Series([1, 2], name="a")
+ if using_copy_on_write:
+ tm.assert_series_equal(subset, expected)
+ else:
+ assert subset.iloc[0] == 0
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ lambda s: s["a":"c"]["a":"b"], # type: ignore[misc]
+ lambda s: s.iloc[0:3].iloc[0:2],
+ lambda s: s.loc["a":"c"].loc["a":"b"], # type: ignore[misc]
+ lambda s: s.loc["a":"c"] # type: ignore[misc]
+ .iloc[0:3]
+ .iloc[0:2]
+ .loc["a":"b"] # type: ignore[misc]
+ .iloc[0:1],
+ ],
+ ids=["getitem", "iloc", "loc", "long-chain"],
+)
+def test_subset_chained_getitem_series(backend, method, using_copy_on_write):
+ # Case: creating a subset using multiple, chained getitem calls using views
+ # still needs to guarantee proper CoW behaviour
+ _, _, Series = backend
+ s = Series([1, 2, 3], index=["a", "b", "c"])
+ s_orig = s.copy()
+
+ # modify subset -> don't modify parent
+ subset = method(s)
+ subset.iloc[0] = 0
+ if using_copy_on_write:
+ tm.assert_series_equal(s, s_orig)
+ else:
+ assert s.iloc[0] == 0
+
+ # modify parent -> don't modify subset
+ subset = s.iloc[0:3].iloc[0:2]
+ s.iloc[0] = 0
+ expected = Series([1, 2], index=["a", "b"])
+ if using_copy_on_write:
+ tm.assert_series_equal(subset, expected)
+ else:
+ assert subset.iloc[0] == 0
+
+
+def test_subset_chained_single_block_row(using_copy_on_write, using_array_manager):
+ # not parametrizing this for dtype backend, since this explicitly tests single block
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})
+ df_orig = df.copy()
+
+ # modify subset -> don't modify parent
+ subset = df[:].iloc[0].iloc[0:2]
+ subset.iloc[0] = 0
+ if using_copy_on_write or using_array_manager:
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert df.iloc[0, 0] == 0
+
+ # modify parent -> don't modify subset
+ subset = df[:].iloc[0].iloc[0:2]
+ df.iloc[0, 0] = 0
+ expected = Series([1, 4], index=["a", "b"], name=0)
+ if using_copy_on_write or using_array_manager:
+ tm.assert_series_equal(subset, expected)
+ else:
+ assert subset.iloc[0] == 0
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ lambda df: df[:],
+ lambda df: df.loc[:, :],
+ lambda df: df.loc[:],
+ lambda df: df.iloc[:, :],
+ lambda df: df.iloc[:],
+ ],
+ ids=["getitem", "loc", "loc-rows", "iloc", "iloc-rows"],
+)
+def test_null_slice(backend, method, using_copy_on_write):
+ # Case: also all variants of indexing with a null slice (:) should return
+ # new objects to ensure we correctly use CoW for the results
+ _, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})
+ df_orig = df.copy()
+
+ df2 = method(df)
+
+ # we always return new objects (shallow copy), regardless of CoW or not
+ assert df2 is not df
+
+ # and those trigger CoW when mutated
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert df.iloc[0, 0] == 0
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ lambda s: s[:],
+ lambda s: s.loc[:],
+ lambda s: s.iloc[:],
+ ],
+ ids=["getitem", "loc", "iloc"],
+)
+def test_null_slice_series(backend, method, using_copy_on_write):
+ _, _, Series = backend
+ s = Series([1, 2, 3], index=["a", "b", "c"])
+ s_orig = s.copy()
+
+ s2 = method(s)
+
+ # we always return new objects, regardless of CoW or not
+ assert s2 is not s
+
+ # and those trigger CoW when mutated
+ s2.iloc[0] = 0
+ if using_copy_on_write:
+ tm.assert_series_equal(s, s_orig)
+ else:
+ assert s.iloc[0] == 0
+
+
+# TODO add more tests modifying the parent
+
+
+# -----------------------------------------------------------------------------
+# Series -- Indexing operations taking subset + modifying the subset/parent
+
+
+def test_series_getitem_slice(backend, using_copy_on_write):
+ # Case: taking a slice of a Series + afterwards modifying the subset
+ _, _, Series = backend
+ s = Series([1, 2, 3], index=["a", "b", "c"])
+ s_orig = s.copy()
+
+ subset = s[:]
+ assert np.shares_memory(get_array(subset), get_array(s))
+
+ subset.iloc[0] = 0
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(subset), get_array(s))
+
+ expected = Series([0, 2, 3], index=["a", "b", "c"])
+ tm.assert_series_equal(subset, expected)
+
+ if using_copy_on_write:
+ # original parent series is not modified (CoW)
+ tm.assert_series_equal(s, s_orig)
+ else:
+ # original parent series is actually updated
+ assert s.iloc[0] == 0
+
+
+@pytest.mark.parametrize(
+ "indexer",
+ [slice(0, 2), np.array([True, True, False]), np.array([0, 1])],
+ ids=["slice", "mask", "array"],
+)
+def test_series_subset_set_with_indexer(
+ backend, indexer_si, indexer, using_copy_on_write
+):
+ # Case: setting values in a viewing Series with an indexer
+ _, _, Series = backend
+ s = Series([1, 2, 3], index=["a", "b", "c"])
+ s_orig = s.copy()
+ subset = s[:]
+
+ warn = None
+ msg = "Series.__setitem__ treating keys as positions is deprecated"
+ if (
+ indexer_si is tm.setitem
+ and isinstance(indexer, np.ndarray)
+ and indexer.dtype.kind == "i"
+ ):
+ warn = FutureWarning
+
+ with tm.assert_produces_warning(warn, match=msg):
+ indexer_si(subset)[indexer] = 0
+ expected = Series([0, 0, 3], index=["a", "b", "c"])
+ tm.assert_series_equal(subset, expected)
+
+ if using_copy_on_write:
+ tm.assert_series_equal(s, s_orig)
+ else:
+ tm.assert_series_equal(s, expected)
+
+
+# -----------------------------------------------------------------------------
+# del operator
+
+
+def test_del_frame(backend, using_copy_on_write):
+ # Case: deleting a column with `del` on a viewing child dataframe should
+ # not modify parent + update the references
+ _, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df[:]
+
+ assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ del df2["b"]
+
+ assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ tm.assert_frame_equal(df, df_orig)
+ tm.assert_frame_equal(df2, df_orig[["a", "c"]])
+ df2._mgr._verify_integrity()
+
+ df.loc[0, "b"] = 200
+ assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ df_orig = df.copy()
+
+ df2.loc[0, "a"] = 100
+ if using_copy_on_write:
+ # modifying child after deleting a column still doesn't update parent
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert df.loc[0, "a"] == 100
+
+
+def test_del_series(backend):
+ _, _, Series = backend
+ s = Series([1, 2, 3], index=["a", "b", "c"])
+ s_orig = s.copy()
+ s2 = s[:]
+
+ assert np.shares_memory(get_array(s), get_array(s2))
+
+ del s2["a"]
+
+ assert not np.shares_memory(get_array(s), get_array(s2))
+ tm.assert_series_equal(s, s_orig)
+ tm.assert_series_equal(s2, s_orig[["b", "c"]])
+
+ # modifying s2 doesn't need copy on write (due to `del`, s2 is backed by new array)
+ values = s2.values
+ s2.loc["b"] = 100
+ assert values[0] == 100
+
+
+# -----------------------------------------------------------------------------
+# Accessing column as Series
+
+
+def test_column_as_series(backend, using_copy_on_write, using_array_manager):
+ # Case: selecting a single column now also uses Copy-on-Write
+ dtype_backend, DataFrame, Series = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+
+ s = df["a"]
+
+ assert np.shares_memory(get_array(s, "a"), get_array(df, "a"))
+
+ if using_copy_on_write or using_array_manager:
+ s[0] = 0
+ else:
+ warn = SettingWithCopyWarning if dtype_backend == "numpy" else None
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(warn):
+ s[0] = 0
+
+ expected = Series([0, 2, 3], name="a")
+ tm.assert_series_equal(s, expected)
+ if using_copy_on_write:
+ # assert not np.shares_memory(s.values, get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+ # ensure cached series on getitem is not the changed series
+ tm.assert_series_equal(df["a"], df_orig["a"])
+ else:
+ df_orig.iloc[0, 0] = 0
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_column_as_series_set_with_upcast(
+ backend, using_copy_on_write, using_array_manager
+):
+ # Case: selecting a single column now also uses Copy-on-Write -> when
+ # setting a value causes an upcast, we don't need to update the parent
+ # DataFrame through the cache mechanism
+ dtype_backend, DataFrame, Series = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+
+ s = df["a"]
+ if dtype_backend == "nullable":
+ with pytest.raises(TypeError, match="Invalid value"):
+ s[0] = "foo"
+ expected = Series([1, 2, 3], name="a")
+ elif using_copy_on_write or using_array_manager:
+ with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
+ s[0] = "foo"
+ expected = Series(["foo", 2, 3], dtype=object, name="a")
+ else:
+ with pd.option_context("chained_assignment", "warn"):
+ msg = "|".join(
+ [
+ "A value is trying to be set on a copy of a slice from a DataFrame",
+ "Setting an item of incompatible dtype is deprecated",
+ ]
+ )
+ with tm.assert_produces_warning(
+ (SettingWithCopyWarning, FutureWarning), match=msg
+ ):
+ s[0] = "foo"
+ expected = Series(["foo", 2, 3], dtype=object, name="a")
+
+ tm.assert_series_equal(s, expected)
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+ # ensure cached series on getitem is not the changed series
+ tm.assert_series_equal(df["a"], df_orig["a"])
+ else:
+ df_orig["a"] = expected
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ lambda df: df["a"],
+ lambda df: df.loc[:, "a"],
+ lambda df: df.iloc[:, 0],
+ ],
+ ids=["getitem", "loc", "iloc"],
+)
+def test_column_as_series_no_item_cache(
+ request, backend, method, using_copy_on_write, using_array_manager
+):
+ # Case: selecting a single column (which now also uses Copy-on-Write to protect
+ # the view) should always give a new object (i.e. not make use of a cache)
+ dtype_backend, DataFrame, _ = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+
+ s1 = method(df)
+ s2 = method(df)
+
+ is_iloc = "iloc" in request.node.name
+ if using_copy_on_write or is_iloc:
+ assert s1 is not s2
+ else:
+ assert s1 is s2
+
+ if using_copy_on_write or using_array_manager:
+ s1.iloc[0] = 0
+ else:
+ warn = SettingWithCopyWarning if dtype_backend == "numpy" else None
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(warn):
+ s1.iloc[0] = 0
+
+ if using_copy_on_write:
+ tm.assert_series_equal(s2, df_orig["a"])
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert s2.iloc[0] == 0
+
+
+# TODO add tests for other indexing methods on the Series
+
+
+def test_dataframe_add_column_from_series(backend, using_copy_on_write):
+ # Case: adding a new column to a DataFrame from an existing column/series
+ # -> delays copy under CoW
+ _, DataFrame, Series = backend
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
+
+ s = Series([10, 11, 12])
+ df["new"] = s
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "new"), get_array(s))
+ else:
+ assert not np.shares_memory(get_array(df, "new"), get_array(s))
+
+ # editing series -> doesn't modify column in frame
+ s[0] = 0
+ expected = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "new": [10, 11, 12]})
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.parametrize("val", [100, "a"])
+@pytest.mark.parametrize(
+ "indexer_func, indexer",
+ [
+ (tm.loc, (0, "a")),
+ (tm.iloc, (0, 0)),
+ (tm.loc, ([0], "a")),
+ (tm.iloc, ([0], 0)),
+ (tm.loc, (slice(None), "a")),
+ (tm.iloc, (slice(None), 0)),
+ ],
+)
+@pytest.mark.parametrize(
+ "col", [[0.1, 0.2, 0.3], [7, 8, 9]], ids=["mixed-block", "single-block"]
+)
+def test_set_value_copy_only_necessary_column(
+ using_copy_on_write, indexer_func, indexer, val, col
+):
+ # When setting inplace, only copy column that is modified instead of the whole
+ # block (by splitting the block)
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": col})
+ df_orig = df.copy()
+ view = df[:]
+
+ if val == "a" and indexer[0] != slice(None):
+ with tm.assert_produces_warning(
+ FutureWarning, match="Setting an item of incompatible dtype is deprecated"
+ ):
+ indexer_func(df)[indexer] = val
+ else:
+ indexer_func(df)[indexer] = val
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "b"), get_array(view, "b"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(view, "a"))
+ tm.assert_frame_equal(view, df_orig)
+ else:
+ assert np.shares_memory(get_array(df, "c"), get_array(view, "c"))
+ if val == "a":
+ assert not np.shares_memory(get_array(df, "a"), get_array(view, "a"))
+ else:
+ assert np.shares_memory(get_array(df, "a"), get_array(view, "a"))
+
+
+def test_series_midx_slice(using_copy_on_write):
+ ser = Series([1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]]))
+ result = ser[1]
+ assert np.shares_memory(get_array(ser), get_array(result))
+ result.iloc[0] = 100
+ if using_copy_on_write:
+ expected = Series(
+ [1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]])
+ )
+ tm.assert_series_equal(ser, expected)
+
+
+def test_getitem_midx_slice(using_copy_on_write, using_array_manager):
+ df = DataFrame({("a", "x"): [1, 2], ("a", "y"): 1, ("b", "x"): 2})
+ df_orig = df.copy()
+ new_df = df[("a",)]
+
+ if using_copy_on_write:
+ assert not new_df._mgr._has_no_reference(0)
+
+ if not using_array_manager:
+ assert np.shares_memory(get_array(df, ("a", "x")), get_array(new_df, "x"))
+ if using_copy_on_write:
+ new_df.iloc[0, 0] = 100
+ tm.assert_frame_equal(df_orig, df)
+
+
+def test_series_midx_tuples_slice(using_copy_on_write):
+ ser = Series(
+ [1, 2, 3],
+ index=pd.MultiIndex.from_tuples([((1, 2), 3), ((1, 2), 4), ((2, 3), 4)]),
+ )
+ result = ser[(1, 2)]
+ assert np.shares_memory(get_array(ser), get_array(result))
+ result.iloc[0] = 100
+ if using_copy_on_write:
+ expected = Series(
+ [1, 2, 3],
+ index=pd.MultiIndex.from_tuples([((1, 2), 3), ((1, 2), 4), ((2, 3), 4)]),
+ )
+ tm.assert_series_equal(ser, expected)
+
+
+def test_loc_enlarging_with_dataframe(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3]})
+ rhs = DataFrame({"b": [1, 2, 3], "c": [4, 5, 6]})
+ rhs_orig = rhs.copy()
+ df.loc[:, ["b", "c"]] = rhs
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "b"), get_array(rhs, "b"))
+ assert np.shares_memory(get_array(df, "c"), get_array(rhs, "c"))
+ assert not df._mgr._has_no_reference(1)
+ else:
+ assert not np.shares_memory(get_array(df, "b"), get_array(rhs, "b"))
+
+ df.iloc[0, 1] = 100
+ tm.assert_frame_equal(rhs, rhs_orig)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_internals.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_internals.py
new file mode 100644
index 0000000000000000000000000000000000000000..a727331307d7e9086144aa8d27f70ffa83973620
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_internals.py
@@ -0,0 +1,151 @@
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import DataFrame
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+
+@td.skip_array_manager_invalid_test
+def test_consolidate(using_copy_on_write):
+ # create unconsolidated DataFrame
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
+ df["c"] = [4, 5, 6]
+
+ # take a viewing subset
+ subset = df[:]
+
+ # each block of subset references a block of df
+ assert all(blk.refs.has_reference() for blk in subset._mgr.blocks)
+
+ # consolidate the two int64 blocks
+ subset._consolidate_inplace()
+
+ # the float64 block still references the parent one because it still a view
+ assert subset._mgr.blocks[0].refs.has_reference()
+ # equivalent of assert np.shares_memory(df["b"].values, subset["b"].values)
+ # but avoids caching df["b"]
+ assert np.shares_memory(get_array(df, "b"), get_array(subset, "b"))
+
+ # the new consolidated int64 block does not reference another
+ assert not subset._mgr.blocks[1].refs.has_reference()
+
+ # the parent dataframe now also only is linked for the float column
+ assert not df._mgr.blocks[0].refs.has_reference()
+ assert df._mgr.blocks[1].refs.has_reference()
+ assert not df._mgr.blocks[2].refs.has_reference()
+
+ # and modifying subset still doesn't modify parent
+ if using_copy_on_write:
+ subset.iloc[0, 1] = 0.0
+ assert not df._mgr.blocks[1].refs.has_reference()
+ assert df.loc[0, "b"] == 0.1
+
+
+@pytest.mark.single_cpu
+@td.skip_array_manager_invalid_test
+def test_switch_options():
+ # ensure we can switch the value of the option within one session
+ # (assuming data is constructed after switching)
+
+ # using the option_context to ensure we set back to global option value
+ # after running the test
+ with pd.option_context("mode.copy_on_write", False):
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
+ subset = df[:]
+ subset.iloc[0, 0] = 0
+ # df updated with CoW disabled
+ assert df.iloc[0, 0] == 0
+
+ pd.options.mode.copy_on_write = True
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
+ subset = df[:]
+ subset.iloc[0, 0] = 0
+ # df not updated with CoW enabled
+ assert df.iloc[0, 0] == 1
+
+ pd.options.mode.copy_on_write = False
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
+ subset = df[:]
+ subset.iloc[0, 0] = 0
+ # df updated with CoW disabled
+ assert df.iloc[0, 0] == 0
+
+
+@td.skip_array_manager_invalid_test
+@pytest.mark.parametrize("dtype", [np.intp, np.int8])
+@pytest.mark.parametrize(
+ "locs, arr",
+ [
+ ([0], np.array([-1, -2, -3])),
+ ([1], np.array([-1, -2, -3])),
+ ([5], np.array([-1, -2, -3])),
+ ([0, 1], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ([0, 2], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ([0, 1, 2], np.array([[-1, -2, -3], [-4, -5, -6], [-4, -5, -6]]).T),
+ ([1, 2], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ([1, 3], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ([1, 3], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ],
+)
+def test_iset_splits_blocks_inplace(using_copy_on_write, locs, arr, dtype):
+ # Nothing currently calls iset with
+ # more than 1 loc with inplace=True (only happens with inplace=False)
+ # but ensure that it works
+ df = DataFrame(
+ {
+ "a": [1, 2, 3],
+ "b": [4, 5, 6],
+ "c": [7, 8, 9],
+ "d": [10, 11, 12],
+ "e": [13, 14, 15],
+ "f": ["a", "b", "c"],
+ },
+ )
+ arr = arr.astype(dtype)
+ df_orig = df.copy()
+ df2 = df.copy(deep=None) # Trigger a CoW (if enabled, otherwise makes copy)
+ df2._mgr.iset(locs, arr, inplace=True)
+
+ tm.assert_frame_equal(df, df_orig)
+
+ if using_copy_on_write:
+ for i, col in enumerate(df.columns):
+ if i not in locs:
+ assert np.shares_memory(get_array(df, col), get_array(df2, col))
+ else:
+ for col in df.columns:
+ assert not np.shares_memory(get_array(df, col), get_array(df2, col))
+
+
+def test_exponential_backoff():
+ # GH#55518
+ df = DataFrame({"a": [1, 2, 3]})
+ for i in range(490):
+ df.copy(deep=False)
+
+ assert len(df._mgr.blocks[0].refs.referenced_blocks) == 491
+
+ df = DataFrame({"a": [1, 2, 3]})
+ dfs = [df.copy(deep=False) for i in range(510)]
+
+ for i in range(20):
+ df.copy(deep=False)
+ assert len(df._mgr.blocks[0].refs.referenced_blocks) == 531
+ assert df._mgr.blocks[0].refs.clear_counter == 1000
+
+ for i in range(500):
+ df.copy(deep=False)
+
+ # Don't reduce since we still have over 500 objects alive
+ assert df._mgr.blocks[0].refs.clear_counter == 1000
+
+ dfs = dfs[:300]
+ for i in range(500):
+ df.copy(deep=False)
+
+ # Reduce since there are less than 500 objects alive
+ assert df._mgr.blocks[0].refs.clear_counter == 500
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_interp_fillna.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_interp_fillna.py
new file mode 100644
index 0000000000000000000000000000000000000000..5507e81d04e2a11c921306c505d462130e211baa
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_interp_fillna.py
@@ -0,0 +1,377 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ NA,
+ ArrowDtype,
+ DataFrame,
+ Interval,
+ NaT,
+ Series,
+ Timestamp,
+ interval_range,
+)
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+
+@pytest.mark.parametrize("method", ["pad", "nearest", "linear"])
+def test_interpolate_no_op(using_copy_on_write, method):
+ df = DataFrame({"a": [1, 2]})
+ df_orig = df.copy()
+
+ warn = None
+ if method == "pad":
+ warn = FutureWarning
+ msg = "DataFrame.interpolate with method=pad is deprecated"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = df.interpolate(method=method)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+
+ result.iloc[0, 0] = 100
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize("func", ["ffill", "bfill"])
+def test_interp_fill_functions(using_copy_on_write, func):
+ # Check that these takes the same code paths as interpolate
+ df = DataFrame({"a": [1, 2]})
+ df_orig = df.copy()
+
+ result = getattr(df, func)()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+
+ result.iloc[0, 0] = 100
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize("func", ["ffill", "bfill"])
+@pytest.mark.parametrize(
+ "vals", [[1, np.nan, 2], [Timestamp("2019-12-31"), NaT, Timestamp("2020-12-31")]]
+)
+def test_interpolate_triggers_copy(using_copy_on_write, vals, func):
+ df = DataFrame({"a": vals})
+ result = getattr(df, func)()
+
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ if using_copy_on_write:
+ # Check that we don't have references when triggering a copy
+ assert result._mgr._has_no_reference(0)
+
+
+@pytest.mark.parametrize(
+ "vals", [[1, np.nan, 2], [Timestamp("2019-12-31"), NaT, Timestamp("2020-12-31")]]
+)
+def test_interpolate_inplace_no_reference_no_copy(using_copy_on_write, vals):
+ df = DataFrame({"a": vals})
+ arr = get_array(df, "a")
+ df.interpolate(method="linear", inplace=True)
+
+ assert np.shares_memory(arr, get_array(df, "a"))
+ if using_copy_on_write:
+ # Check that we don't have references when triggering a copy
+ assert df._mgr._has_no_reference(0)
+
+
+@pytest.mark.parametrize(
+ "vals", [[1, np.nan, 2], [Timestamp("2019-12-31"), NaT, Timestamp("2020-12-31")]]
+)
+def test_interpolate_inplace_with_refs(using_copy_on_write, vals):
+ df = DataFrame({"a": [1, np.nan, 2]})
+ df_orig = df.copy()
+ arr = get_array(df, "a")
+ view = df[:]
+ df.interpolate(method="linear", inplace=True)
+
+ if using_copy_on_write:
+ # Check that copy was triggered in interpolate and that we don't
+ # have any references left
+ assert not np.shares_memory(arr, get_array(df, "a"))
+ tm.assert_frame_equal(df_orig, view)
+ assert df._mgr._has_no_reference(0)
+ assert view._mgr._has_no_reference(0)
+ else:
+ assert np.shares_memory(arr, get_array(df, "a"))
+
+
+def test_interpolate_cleaned_fill_method(using_copy_on_write):
+ # Check that "method is set to None" case works correctly
+ df = DataFrame({"a": ["a", np.nan, "c"], "b": 1})
+ df_orig = df.copy()
+
+ msg = "DataFrame.interpolate with object dtype"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.interpolate(method="linear")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+
+ result.iloc[0, 0] = Timestamp("2021-12-31")
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_interpolate_object_convert_no_op(using_copy_on_write):
+ df = DataFrame({"a": ["a", "b", "c"], "b": 1})
+ arr_a = get_array(df, "a")
+ msg = "DataFrame.interpolate with method=pad is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.interpolate(method="pad", inplace=True)
+
+ # Now CoW makes a copy, it should not!
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ assert np.shares_memory(arr_a, get_array(df, "a"))
+
+
+def test_interpolate_object_convert_copies(using_copy_on_write):
+ df = DataFrame({"a": Series([1, 2], dtype=object), "b": 1})
+ arr_a = get_array(df, "a")
+ msg = "DataFrame.interpolate with method=pad is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.interpolate(method="pad", inplace=True)
+
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ assert not np.shares_memory(arr_a, get_array(df, "a"))
+
+
+def test_interpolate_downcast(using_copy_on_write):
+ df = DataFrame({"a": [1, np.nan, 2.5], "b": 1})
+ arr_a = get_array(df, "a")
+ msg = "DataFrame.interpolate with method=pad is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.interpolate(method="pad", inplace=True, downcast="infer")
+
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ assert np.shares_memory(arr_a, get_array(df, "a"))
+
+
+def test_interpolate_downcast_reference_triggers_copy(using_copy_on_write):
+ df = DataFrame({"a": [1, np.nan, 2.5], "b": 1})
+ df_orig = df.copy()
+ arr_a = get_array(df, "a")
+ view = df[:]
+ msg = "DataFrame.interpolate with method=pad is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.interpolate(method="pad", inplace=True, downcast="infer")
+
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ assert not np.shares_memory(arr_a, get_array(df, "a"))
+ tm.assert_frame_equal(df_orig, view)
+ else:
+ tm.assert_frame_equal(df, view)
+
+
+def test_fillna(using_copy_on_write):
+ df = DataFrame({"a": [1.5, np.nan], "b": 1})
+ df_orig = df.copy()
+
+ df2 = df.fillna(5.5)
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ else:
+ assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+
+ df2.iloc[0, 1] = 100
+ tm.assert_frame_equal(df_orig, df)
+
+
+def test_fillna_dict(using_copy_on_write):
+ df = DataFrame({"a": [1.5, np.nan], "b": 1})
+ df_orig = df.copy()
+
+ df2 = df.fillna({"a": 100.5})
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ else:
+ assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+
+ df2.iloc[0, 1] = 100
+ tm.assert_frame_equal(df_orig, df)
+
+
+@pytest.mark.parametrize("downcast", [None, False])
+def test_fillna_inplace(using_copy_on_write, downcast):
+ df = DataFrame({"a": [1.5, np.nan], "b": 1})
+ arr_a = get_array(df, "a")
+ arr_b = get_array(df, "b")
+
+ msg = "The 'downcast' keyword in fillna is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.fillna(5.5, inplace=True, downcast=downcast)
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+ assert np.shares_memory(get_array(df, "b"), arr_b)
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ assert df._mgr._has_no_reference(1)
+
+
+def test_fillna_inplace_reference(using_copy_on_write):
+ df = DataFrame({"a": [1.5, np.nan], "b": 1})
+ df_orig = df.copy()
+ arr_a = get_array(df, "a")
+ arr_b = get_array(df, "b")
+ view = df[:]
+
+ df.fillna(5.5, inplace=True)
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), arr_a)
+ assert np.shares_memory(get_array(df, "b"), arr_b)
+ assert view._mgr._has_no_reference(0)
+ assert df._mgr._has_no_reference(0)
+ tm.assert_frame_equal(view, df_orig)
+ else:
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+ assert np.shares_memory(get_array(df, "b"), arr_b)
+ expected = DataFrame({"a": [1.5, 5.5], "b": 1})
+ tm.assert_frame_equal(df, expected)
+
+
+def test_fillna_interval_inplace_reference(using_copy_on_write):
+ # Set dtype explicitly to avoid implicit cast when setting nan
+ ser = Series(
+ interval_range(start=0, end=5), name="a", dtype="interval[float64, right]"
+ )
+ ser.iloc[1] = np.nan
+
+ ser_orig = ser.copy()
+ view = ser[:]
+ ser.fillna(value=Interval(left=0, right=5), inplace=True)
+
+ if using_copy_on_write:
+ assert not np.shares_memory(
+ get_array(ser, "a").left.values, get_array(view, "a").left.values
+ )
+ tm.assert_series_equal(view, ser_orig)
+ else:
+ assert np.shares_memory(
+ get_array(ser, "a").left.values, get_array(view, "a").left.values
+ )
+
+
+def test_fillna_series_empty_arg(using_copy_on_write):
+ ser = Series([1, np.nan, 2])
+ ser_orig = ser.copy()
+ result = ser.fillna({})
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(ser), get_array(result))
+ else:
+ assert not np.shares_memory(get_array(ser), get_array(result))
+
+ ser.iloc[0] = 100.5
+ tm.assert_series_equal(ser_orig, result)
+
+
+def test_fillna_series_empty_arg_inplace(using_copy_on_write):
+ ser = Series([1, np.nan, 2])
+ arr = get_array(ser)
+ ser.fillna({}, inplace=True)
+
+ assert np.shares_memory(get_array(ser), arr)
+ if using_copy_on_write:
+ assert ser._mgr._has_no_reference(0)
+
+
+def test_fillna_ea_noop_shares_memory(
+ using_copy_on_write, any_numeric_ea_and_arrow_dtype
+):
+ df = DataFrame({"a": [1, NA, 3], "b": 1}, dtype=any_numeric_ea_and_arrow_dtype)
+ df_orig = df.copy()
+ df2 = df.fillna(100)
+
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ assert not df2._mgr._has_no_reference(1)
+ elif isinstance(df.dtypes.iloc[0], ArrowDtype):
+ # arrow is immutable, so no-ops do not need to copy underlying array
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ else:
+ assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+
+ tm.assert_frame_equal(df_orig, df)
+
+ df2.iloc[0, 1] = 100
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ assert df2._mgr._has_no_reference(1)
+ assert df._mgr._has_no_reference(1)
+ tm.assert_frame_equal(df_orig, df)
+
+
+def test_fillna_inplace_ea_noop_shares_memory(
+ using_copy_on_write, any_numeric_ea_and_arrow_dtype
+):
+ df = DataFrame({"a": [1, NA, 3], "b": 1}, dtype=any_numeric_ea_and_arrow_dtype)
+ df_orig = df.copy()
+ view = df[:]
+ df.fillna(100, inplace=True)
+
+ if isinstance(df["a"].dtype, ArrowDtype) or using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), get_array(view, "a"))
+ else:
+ # MaskedArray can actually respect inplace=True
+ assert np.shares_memory(get_array(df, "a"), get_array(view, "a"))
+
+ assert np.shares_memory(get_array(df, "b"), get_array(view, "b"))
+ if using_copy_on_write:
+ assert not df._mgr._has_no_reference(1)
+ assert not view._mgr._has_no_reference(1)
+
+ df.iloc[0, 1] = 100
+ if isinstance(df["a"].dtype, ArrowDtype) or using_copy_on_write:
+ tm.assert_frame_equal(df_orig, view)
+ else:
+ # we actually have a view
+ tm.assert_frame_equal(df, view)
+
+
+def test_fillna_chained_assignment(using_copy_on_write):
+ df = DataFrame({"a": [1, np.nan, 2], "b": 1})
+ df_orig = df.copy()
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["a"].fillna(100, inplace=True)
+ tm.assert_frame_equal(df, df_orig)
+
+ with tm.raises_chained_assignment_error():
+ df[["a"]].fillna(100, inplace=True)
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize("func", ["interpolate", "ffill", "bfill"])
+def test_interpolate_chained_assignment(using_copy_on_write, func):
+ df = DataFrame({"a": [1, np.nan, 2], "b": 1})
+ df_orig = df.copy()
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ getattr(df["a"], func)(inplace=True)
+ tm.assert_frame_equal(df, df_orig)
+
+ with tm.raises_chained_assignment_error():
+ getattr(df[["a"]], func)(inplace=True)
+ tm.assert_frame_equal(df, df_orig)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_methods.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe1be2d8b6a0ae961e250c9266185ae7dab8ee89
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_methods.py
@@ -0,0 +1,1935 @@
+import numpy as np
+import pytest
+
+from pandas.errors import SettingWithCopyWarning
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Period,
+ Series,
+ Timestamp,
+ date_range,
+ period_range,
+)
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+
+def test_copy(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_copy = df.copy()
+
+ # the deep copy by defaults takes a shallow copy of the Index
+ assert df_copy.index is not df.index
+ assert df_copy.columns is not df.columns
+ assert df_copy.index.is_(df.index)
+ assert df_copy.columns.is_(df.columns)
+
+ # the deep copy doesn't share memory
+ assert not np.shares_memory(get_array(df_copy, "a"), get_array(df, "a"))
+ if using_copy_on_write:
+ assert not df_copy._mgr.blocks[0].refs.has_reference()
+ assert not df_copy._mgr.blocks[1].refs.has_reference()
+
+ # mutating copy doesn't mutate original
+ df_copy.iloc[0, 0] = 0
+ assert df.iloc[0, 0] == 1
+
+
+def test_copy_shallow(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_copy = df.copy(deep=False)
+
+ # the shallow copy also makes a shallow copy of the index
+ if using_copy_on_write:
+ assert df_copy.index is not df.index
+ assert df_copy.columns is not df.columns
+ assert df_copy.index.is_(df.index)
+ assert df_copy.columns.is_(df.columns)
+ else:
+ assert df_copy.index is df.index
+ assert df_copy.columns is df.columns
+
+ # the shallow copy still shares memory
+ assert np.shares_memory(get_array(df_copy, "a"), get_array(df, "a"))
+ if using_copy_on_write:
+ assert df_copy._mgr.blocks[0].refs.has_reference()
+ assert df_copy._mgr.blocks[1].refs.has_reference()
+
+ if using_copy_on_write:
+ # mutating shallow copy doesn't mutate original
+ df_copy.iloc[0, 0] = 0
+ assert df.iloc[0, 0] == 1
+ # mutating triggered a copy-on-write -> no longer shares memory
+ assert not np.shares_memory(get_array(df_copy, "a"), get_array(df, "a"))
+ # but still shares memory for the other columns/blocks
+ assert np.shares_memory(get_array(df_copy, "c"), get_array(df, "c"))
+ else:
+ # mutating shallow copy does mutate original
+ df_copy.iloc[0, 0] = 0
+ assert df.iloc[0, 0] == 0
+ # and still shares memory
+ assert np.shares_memory(get_array(df_copy, "a"), get_array(df, "a"))
+
+
+@pytest.mark.parametrize("copy", [True, None, False])
+@pytest.mark.parametrize(
+ "method",
+ [
+ lambda df, copy: df.rename(columns=str.lower, copy=copy),
+ lambda df, copy: df.reindex(columns=["a", "c"], copy=copy),
+ lambda df, copy: df.reindex_like(df, copy=copy),
+ lambda df, copy: df.align(df, copy=copy)[0],
+ lambda df, copy: df.set_axis(["a", "b", "c"], axis="index", copy=copy),
+ lambda df, copy: df.rename_axis(index="test", copy=copy),
+ lambda df, copy: df.rename_axis(columns="test", copy=copy),
+ lambda df, copy: df.astype({"b": "int64"}, copy=copy),
+ # lambda df, copy: df.swaplevel(0, 0, copy=copy),
+ lambda df, copy: df.swapaxes(0, 0, copy=copy),
+ lambda df, copy: df.truncate(0, 5, copy=copy),
+ lambda df, copy: df.infer_objects(copy=copy),
+ lambda df, copy: df.to_timestamp(copy=copy),
+ lambda df, copy: df.to_period(freq="D", copy=copy),
+ lambda df, copy: df.tz_localize("US/Central", copy=copy),
+ lambda df, copy: df.tz_convert("US/Central", copy=copy),
+ lambda df, copy: df.set_flags(allows_duplicate_labels=False, copy=copy),
+ ],
+ ids=[
+ "rename",
+ "reindex",
+ "reindex_like",
+ "align",
+ "set_axis",
+ "rename_axis0",
+ "rename_axis1",
+ "astype",
+ # "swaplevel", # only series
+ "swapaxes",
+ "truncate",
+ "infer_objects",
+ "to_timestamp",
+ "to_period",
+ "tz_localize",
+ "tz_convert",
+ "set_flags",
+ ],
+)
+def test_methods_copy_keyword(
+ request, method, copy, using_copy_on_write, using_array_manager
+):
+ index = None
+ if "to_timestamp" in request.node.callspec.id:
+ index = period_range("2012-01-01", freq="D", periods=3)
+ elif "to_period" in request.node.callspec.id:
+ index = date_range("2012-01-01", freq="D", periods=3)
+ elif "tz_localize" in request.node.callspec.id:
+ index = date_range("2012-01-01", freq="D", periods=3)
+ elif "tz_convert" in request.node.callspec.id:
+ index = date_range("2012-01-01", freq="D", periods=3, tz="Europe/Brussels")
+
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}, index=index)
+
+ if "swapaxes" in request.node.callspec.id:
+ msg = "'DataFrame.swapaxes' is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df2 = method(df, copy=copy)
+ else:
+ df2 = method(df, copy=copy)
+
+ share_memory = using_copy_on_write or copy is False
+
+ if request.node.callspec.id.startswith("reindex-"):
+ # TODO copy=False without CoW still returns a copy in this case
+ if not using_copy_on_write and not using_array_manager and copy is False:
+ share_memory = False
+
+ if share_memory:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+
+@pytest.mark.parametrize("copy", [True, None, False])
+@pytest.mark.parametrize(
+ "method",
+ [
+ lambda ser, copy: ser.rename(index={0: 100}, copy=copy),
+ lambda ser, copy: ser.rename(None, copy=copy),
+ lambda ser, copy: ser.reindex(index=ser.index, copy=copy),
+ lambda ser, copy: ser.reindex_like(ser, copy=copy),
+ lambda ser, copy: ser.align(ser, copy=copy)[0],
+ lambda ser, copy: ser.set_axis(["a", "b", "c"], axis="index", copy=copy),
+ lambda ser, copy: ser.rename_axis(index="test", copy=copy),
+ lambda ser, copy: ser.astype("int64", copy=copy),
+ lambda ser, copy: ser.swaplevel(0, 1, copy=copy),
+ lambda ser, copy: ser.swapaxes(0, 0, copy=copy),
+ lambda ser, copy: ser.truncate(0, 5, copy=copy),
+ lambda ser, copy: ser.infer_objects(copy=copy),
+ lambda ser, copy: ser.to_timestamp(copy=copy),
+ lambda ser, copy: ser.to_period(freq="D", copy=copy),
+ lambda ser, copy: ser.tz_localize("US/Central", copy=copy),
+ lambda ser, copy: ser.tz_convert("US/Central", copy=copy),
+ lambda ser, copy: ser.set_flags(allows_duplicate_labels=False, copy=copy),
+ ],
+ ids=[
+ "rename (dict)",
+ "rename",
+ "reindex",
+ "reindex_like",
+ "align",
+ "set_axis",
+ "rename_axis0",
+ "astype",
+ "swaplevel",
+ "swapaxes",
+ "truncate",
+ "infer_objects",
+ "to_timestamp",
+ "to_period",
+ "tz_localize",
+ "tz_convert",
+ "set_flags",
+ ],
+)
+def test_methods_series_copy_keyword(request, method, copy, using_copy_on_write):
+ index = None
+ if "to_timestamp" in request.node.callspec.id:
+ index = period_range("2012-01-01", freq="D", periods=3)
+ elif "to_period" in request.node.callspec.id:
+ index = date_range("2012-01-01", freq="D", periods=3)
+ elif "tz_localize" in request.node.callspec.id:
+ index = date_range("2012-01-01", freq="D", periods=3)
+ elif "tz_convert" in request.node.callspec.id:
+ index = date_range("2012-01-01", freq="D", periods=3, tz="Europe/Brussels")
+ elif "swaplevel" in request.node.callspec.id:
+ index = MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]])
+
+ ser = Series([1, 2, 3], index=index)
+
+ if "swapaxes" in request.node.callspec.id:
+ msg = "'Series.swapaxes' is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ ser2 = method(ser, copy=copy)
+ else:
+ ser2 = method(ser, copy=copy)
+
+ share_memory = using_copy_on_write or copy is False
+
+ if share_memory:
+ assert np.shares_memory(get_array(ser2), get_array(ser))
+ else:
+ assert not np.shares_memory(get_array(ser2), get_array(ser))
+
+
+@pytest.mark.parametrize("copy", [True, None, False])
+def test_transpose_copy_keyword(using_copy_on_write, copy, using_array_manager):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ result = df.transpose(copy=copy)
+ share_memory = using_copy_on_write or copy is False or copy is None
+ share_memory = share_memory and not using_array_manager
+
+ if share_memory:
+ assert np.shares_memory(get_array(df, "a"), get_array(result, 0))
+ else:
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, 0))
+
+
+# -----------------------------------------------------------------------------
+# DataFrame methods returning new DataFrame using shallow copy
+
+
+def test_reset_index(using_copy_on_write):
+ # Case: resetting the index (i.e. adding a new column) + mutating the
+ # resulting dataframe
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}, index=[10, 11, 12]
+ )
+ df_orig = df.copy()
+ df2 = df.reset_index()
+ df2._mgr._verify_integrity()
+
+ if using_copy_on_write:
+ # still shares memory (df2 is a shallow copy)
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ # mutating df2 triggers a copy-on-write for that column / block
+ df2.iloc[0, 2] = 0
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize("index", [pd.RangeIndex(0, 2), Index([1, 2])])
+def test_reset_index_series_drop(using_copy_on_write, index):
+ ser = Series([1, 2], index=index)
+ ser_orig = ser.copy()
+ ser2 = ser.reset_index(drop=True)
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(ser), get_array(ser2))
+ assert not ser._mgr._has_no_reference(0)
+ else:
+ assert not np.shares_memory(get_array(ser), get_array(ser2))
+
+ ser2.iloc[0] = 100
+ tm.assert_series_equal(ser, ser_orig)
+
+
+def test_rename_columns(using_copy_on_write):
+ # Case: renaming columns returns a new dataframe
+ # + afterwards modifying the result
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.rename(columns=str.upper)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "A"), get_array(df, "a"))
+ df2.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(df2, "A"), get_array(df, "a"))
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "C"), get_array(df, "c"))
+ expected = DataFrame({"A": [0, 2, 3], "B": [4, 5, 6], "C": [0.1, 0.2, 0.3]})
+ tm.assert_frame_equal(df2, expected)
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_rename_columns_modify_parent(using_copy_on_write):
+ # Case: renaming columns returns a new dataframe
+ # + afterwards modifying the original (parent) dataframe
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df2 = df.rename(columns=str.upper)
+ df2_orig = df2.copy()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "A"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "A"), get_array(df, "a"))
+ df.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(df2, "A"), get_array(df, "a"))
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "C"), get_array(df, "c"))
+ expected = DataFrame({"a": [0, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ tm.assert_frame_equal(df, expected)
+ tm.assert_frame_equal(df2, df2_orig)
+
+
+def test_pipe(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": 1.5})
+ df_orig = df.copy()
+
+ def testfunc(df):
+ return df
+
+ df2 = df.pipe(testfunc)
+
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ expected = DataFrame({"a": [0, 2, 3], "b": 1.5})
+ tm.assert_frame_equal(df, expected)
+
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+
+
+def test_pipe_modify_df(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": 1.5})
+ df_orig = df.copy()
+
+ def testfunc(df):
+ df.iloc[0, 0] = 100
+ return df
+
+ df2 = df.pipe(testfunc)
+
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ expected = DataFrame({"a": [100, 2, 3], "b": 1.5})
+ tm.assert_frame_equal(df, expected)
+
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+
+
+def test_reindex_columns(using_copy_on_write):
+ # Case: reindexing the column returns a new dataframe
+ # + afterwards modifying the result
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.reindex(columns=["a", "c"])
+
+ if using_copy_on_write:
+ # still shares memory (df2 is a shallow copy)
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ # mutating df2 triggers a copy-on-write for that column
+ df2.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "index",
+ [
+ lambda idx: idx,
+ lambda idx: idx.view(),
+ lambda idx: idx.copy(),
+ lambda idx: list(idx),
+ ],
+ ids=["identical", "view", "copy", "values"],
+)
+def test_reindex_rows(index, using_copy_on_write):
+ # Case: reindexing the rows with an index that matches the current index
+ # can use a shallow copy
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.reindex(index=index(df.index))
+
+ if using_copy_on_write:
+ # still shares memory (df2 is a shallow copy)
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ # mutating df2 triggers a copy-on-write for that column
+ df2.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_drop_on_column(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.drop(columns="a")
+ df2._mgr._verify_integrity()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ else:
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ df2.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_select_dtypes(using_copy_on_write):
+ # Case: selecting columns using `select_dtypes()` returns a new dataframe
+ # + afterwards modifying the result
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.select_dtypes("int64")
+ df2._mgr._verify_integrity()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column/block
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "filter_kwargs", [{"items": ["a"]}, {"like": "a"}, {"regex": "a"}]
+)
+def test_filter(using_copy_on_write, filter_kwargs):
+ # Case: selecting columns using `filter()` returns a new dataframe
+ # + afterwards modifying the result
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.filter(**filter_kwargs)
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column/block
+ if using_copy_on_write:
+ df2.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_shift_no_op(using_copy_on_write):
+ df = DataFrame(
+ [[1, 2], [3, 4], [5, 6]],
+ index=date_range("2020-01-01", "2020-01-03"),
+ columns=["a", "b"],
+ )
+ df_orig = df.copy()
+ df2 = df.shift(periods=0)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ tm.assert_frame_equal(df2, df_orig)
+
+
+def test_shift_index(using_copy_on_write):
+ df = DataFrame(
+ [[1, 2], [3, 4], [5, 6]],
+ index=date_range("2020-01-01", "2020-01-03"),
+ columns=["a", "b"],
+ )
+ df2 = df.shift(periods=1, axis=0)
+
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+
+def test_shift_rows_freq(using_copy_on_write):
+ df = DataFrame(
+ [[1, 2], [3, 4], [5, 6]],
+ index=date_range("2020-01-01", "2020-01-03"),
+ columns=["a", "b"],
+ )
+ df_orig = df.copy()
+ df_orig.index = date_range("2020-01-02", "2020-01-04")
+ df2 = df.shift(periods=1, freq="1D")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ tm.assert_frame_equal(df2, df_orig)
+
+
+def test_shift_columns(using_copy_on_write):
+ df = DataFrame(
+ [[1, 2], [3, 4], [5, 6]], columns=date_range("2020-01-01", "2020-01-02")
+ )
+ df2 = df.shift(periods=1, axis=1)
+
+ assert np.shares_memory(get_array(df2, "2020-01-02"), get_array(df, "2020-01-01"))
+ df.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(
+ get_array(df2, "2020-01-02"), get_array(df, "2020-01-01")
+ )
+ expected = DataFrame(
+ [[np.nan, 1], [np.nan, 3], [np.nan, 5]],
+ columns=date_range("2020-01-01", "2020-01-02"),
+ )
+ tm.assert_frame_equal(df2, expected)
+
+
+def test_pop(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ view_original = df[:]
+ result = df.pop("a")
+
+ assert np.shares_memory(result.values, get_array(view_original, "a"))
+ assert np.shares_memory(get_array(df, "b"), get_array(view_original, "b"))
+
+ if using_copy_on_write:
+ result.iloc[0] = 0
+ assert not np.shares_memory(result.values, get_array(view_original, "a"))
+ df.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "b"), get_array(view_original, "b"))
+ tm.assert_frame_equal(view_original, df_orig)
+ else:
+ expected = DataFrame({"a": [1, 2, 3], "b": [0, 5, 6], "c": [0.1, 0.2, 0.3]})
+ tm.assert_frame_equal(view_original, expected)
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ lambda x, y: x.align(y),
+ lambda x, y: x.align(y.a, axis=0),
+ lambda x, y: x.align(y.a.iloc[slice(0, 1)], axis=1),
+ ],
+)
+def test_align_frame(using_copy_on_write, func):
+ df = DataFrame({"a": [1, 2, 3], "b": "a"})
+ df_orig = df.copy()
+ df_changed = df[["b", "a"]].copy()
+ df2, _ = func(df, df_changed)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_align_series(using_copy_on_write):
+ ser = Series([1, 2])
+ ser_orig = ser.copy()
+ ser_other = ser.copy()
+ ser2, ser_other_result = ser.align(ser_other)
+
+ if using_copy_on_write:
+ assert np.shares_memory(ser2.values, ser.values)
+ assert np.shares_memory(ser_other_result.values, ser_other.values)
+ else:
+ assert not np.shares_memory(ser2.values, ser.values)
+ assert not np.shares_memory(ser_other_result.values, ser_other.values)
+
+ ser2.iloc[0] = 0
+ ser_other_result.iloc[0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(ser2.values, ser.values)
+ assert not np.shares_memory(ser_other_result.values, ser_other.values)
+ tm.assert_series_equal(ser, ser_orig)
+ tm.assert_series_equal(ser_other, ser_orig)
+
+
+def test_align_copy_false(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df_orig = df.copy()
+ df2, df3 = df.align(df, copy=False)
+
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ if using_copy_on_write:
+ df2.loc[0, "a"] = 0
+ tm.assert_frame_equal(df, df_orig) # Original is unchanged
+
+ df3.loc[0, "a"] = 0
+ tm.assert_frame_equal(df, df_orig) # Original is unchanged
+
+
+def test_align_with_series_copy_false(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ ser = Series([1, 2, 3], name="x")
+ ser_orig = ser.copy()
+ df_orig = df.copy()
+ df2, ser2 = df.align(ser, copy=False, axis=0)
+
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ assert np.shares_memory(get_array(ser, "x"), get_array(ser2, "x"))
+
+ if using_copy_on_write:
+ df2.loc[0, "a"] = 0
+ tm.assert_frame_equal(df, df_orig) # Original is unchanged
+
+ ser2.loc[0] = 0
+ tm.assert_series_equal(ser, ser_orig) # Original is unchanged
+
+
+def test_to_frame(using_copy_on_write):
+ # Case: converting a Series to a DataFrame with to_frame
+ ser = Series([1, 2, 3])
+ ser_orig = ser.copy()
+
+ df = ser[:].to_frame()
+
+ # currently this always returns a "view"
+ assert np.shares_memory(ser.values, get_array(df, 0))
+
+ df.iloc[0, 0] = 0
+
+ if using_copy_on_write:
+ # mutating df triggers a copy-on-write for that column
+ assert not np.shares_memory(ser.values, get_array(df, 0))
+ tm.assert_series_equal(ser, ser_orig)
+ else:
+ # but currently select_dtypes() actually returns a view -> mutates parent
+ expected = ser_orig.copy()
+ expected.iloc[0] = 0
+ tm.assert_series_equal(ser, expected)
+
+ # modify original series -> don't modify dataframe
+ df = ser[:].to_frame()
+ ser.iloc[0] = 0
+
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, ser_orig.to_frame())
+ else:
+ expected = ser_orig.copy().to_frame()
+ expected.iloc[0, 0] = 0
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.parametrize("ax", ["index", "columns"])
+def test_swapaxes_noop(using_copy_on_write, ax):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df_orig = df.copy()
+ msg = "'DataFrame.swapaxes' is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df2 = df.swapaxes(ax, ax)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column/block
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_swapaxes_single_block(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, index=["x", "y", "z"])
+ df_orig = df.copy()
+ msg = "'DataFrame.swapaxes' is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df2 = df.swapaxes("index", "columns")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "x"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "x"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column/block
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "x"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_swapaxes_read_only_array():
+ df = DataFrame({"a": [1, 2], "b": 3})
+ msg = "'DataFrame.swapaxes' is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df = df.swapaxes(axis1="index", axis2="columns")
+ df.iloc[0, 0] = 100
+ expected = DataFrame({0: [100, 3], 1: [2, 3]}, index=["a", "b"])
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.parametrize(
+ "method, idx",
+ [
+ (lambda df: df.copy(deep=False).copy(deep=False), 0),
+ (lambda df: df.reset_index().reset_index(), 2),
+ (lambda df: df.rename(columns=str.upper).rename(columns=str.lower), 0),
+ (lambda df: df.copy(deep=False).select_dtypes(include="number"), 0),
+ ],
+ ids=["shallow-copy", "reset_index", "rename", "select_dtypes"],
+)
+def test_chained_methods(request, method, idx, using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+
+ # when not using CoW, only the copy() variant actually gives a view
+ df2_is_view = not using_copy_on_write and request.node.callspec.id == "shallow-copy"
+
+ # modify df2 -> don't modify df
+ df2 = method(df)
+ df2.iloc[0, idx] = 0
+ if not df2_is_view:
+ tm.assert_frame_equal(df, df_orig)
+
+ # modify df -> don't modify df2
+ df2 = method(df)
+ df.iloc[0, 0] = 0
+ if not df2_is_view:
+ tm.assert_frame_equal(df2.iloc[:, idx:], df_orig)
+
+
+@pytest.mark.parametrize("obj", [Series([1, 2], name="a"), DataFrame({"a": [1, 2]})])
+def test_to_timestamp(using_copy_on_write, obj):
+ obj.index = Index([Period("2012-1-1", freq="D"), Period("2012-1-2", freq="D")])
+
+ obj_orig = obj.copy()
+ obj2 = obj.to_timestamp()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a"))
+ else:
+ assert not np.shares_memory(get_array(obj2, "a"), get_array(obj, "a"))
+
+ # mutating obj2 triggers a copy-on-write for that column / block
+ obj2.iloc[0] = 0
+ assert not np.shares_memory(get_array(obj2, "a"), get_array(obj, "a"))
+ tm.assert_equal(obj, obj_orig)
+
+
+@pytest.mark.parametrize("obj", [Series([1, 2], name="a"), DataFrame({"a": [1, 2]})])
+def test_to_period(using_copy_on_write, obj):
+ obj.index = Index([Timestamp("2019-12-31"), Timestamp("2020-12-31")])
+
+ obj_orig = obj.copy()
+ obj2 = obj.to_period(freq="Y")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a"))
+ else:
+ assert not np.shares_memory(get_array(obj2, "a"), get_array(obj, "a"))
+
+ # mutating obj2 triggers a copy-on-write for that column / block
+ obj2.iloc[0] = 0
+ assert not np.shares_memory(get_array(obj2, "a"), get_array(obj, "a"))
+ tm.assert_equal(obj, obj_orig)
+
+
+def test_set_index(using_copy_on_write):
+ # GH 49473
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.set_index("a")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ else:
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+
+ # mutating df2 triggers a copy-on-write for that column / block
+ df2.iloc[0, 1] = 0
+ assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_set_index_mutating_parent_does_not_mutate_index():
+ df = DataFrame({"a": [1, 2, 3], "b": 1})
+ result = df.set_index("a")
+ expected = result.copy()
+
+ df.iloc[0, 0] = 100
+ tm.assert_frame_equal(result, expected)
+
+
+def test_add_prefix(using_copy_on_write):
+ # GH 49473
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.add_prefix("CoW_")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "CoW_a"), get_array(df, "a"))
+ df2.iloc[0, 0] = 0
+
+ assert not np.shares_memory(get_array(df2, "CoW_a"), get_array(df, "a"))
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "CoW_c"), get_array(df, "c"))
+ expected = DataFrame(
+ {"CoW_a": [0, 2, 3], "CoW_b": [4, 5, 6], "CoW_c": [0.1, 0.2, 0.3]}
+ )
+ tm.assert_frame_equal(df2, expected)
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_add_suffix(using_copy_on_write):
+ # GH 49473
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.add_suffix("_CoW")
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a_CoW"), get_array(df, "a"))
+ df2.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(df2, "a_CoW"), get_array(df, "a"))
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "c_CoW"), get_array(df, "c"))
+ expected = DataFrame(
+ {"a_CoW": [0, 2, 3], "b_CoW": [4, 5, 6], "c_CoW": [0.1, 0.2, 0.3]}
+ )
+ tm.assert_frame_equal(df2, expected)
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize("axis, val", [(0, 5.5), (1, np.nan)])
+def test_dropna(using_copy_on_write, axis, val):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, val, 6], "c": "d"})
+ df_orig = df.copy()
+ df2 = df.dropna(axis=axis)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize("val", [5, 5.5])
+def test_dropna_series(using_copy_on_write, val):
+ ser = Series([1, val, 4])
+ ser_orig = ser.copy()
+ ser2 = ser.dropna()
+
+ if using_copy_on_write:
+ assert np.shares_memory(ser2.values, ser.values)
+ else:
+ assert not np.shares_memory(ser2.values, ser.values)
+
+ ser2.iloc[0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(ser2.values, ser.values)
+ tm.assert_series_equal(ser, ser_orig)
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ lambda df: df.head(),
+ lambda df: df.head(2),
+ lambda df: df.tail(),
+ lambda df: df.tail(3),
+ ],
+)
+def test_head_tail(method, using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = method(df)
+ df2._mgr._verify_integrity()
+
+ if using_copy_on_write:
+ # We are explicitly deviating for CoW here to make an eager copy (avoids
+ # tracking references for very cheap ops)
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+
+ # modify df2 to trigger CoW for that block
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ # without CoW enabled, head and tail return views. Mutating df2 also mutates df.
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ df2.iloc[0, 0] = 1
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_infer_objects(using_copy_on_write):
+ df = DataFrame({"a": [1, 2], "b": "c", "c": 1, "d": "x"})
+ df_orig = df.copy()
+ df2 = df.infer_objects()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+
+ df2.iloc[0, 0] = 0
+ df2.iloc[0, 1] = "d"
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_infer_objects_no_reference(using_copy_on_write):
+ df = DataFrame(
+ {
+ "a": [1, 2],
+ "b": "c",
+ "c": 1,
+ "d": Series(
+ [Timestamp("2019-12-31"), Timestamp("2020-12-31")], dtype="object"
+ ),
+ "e": "b",
+ }
+ )
+ df = df.infer_objects()
+
+ arr_a = get_array(df, "a")
+ arr_b = get_array(df, "b")
+ arr_d = get_array(df, "d")
+
+ df.iloc[0, 0] = 0
+ df.iloc[0, 1] = "d"
+ df.iloc[0, 3] = Timestamp("2018-12-31")
+ if using_copy_on_write:
+ assert np.shares_memory(arr_a, get_array(df, "a"))
+ # TODO(CoW): Block splitting causes references here
+ assert not np.shares_memory(arr_b, get_array(df, "b"))
+ assert np.shares_memory(arr_d, get_array(df, "d"))
+
+
+def test_infer_objects_reference(using_copy_on_write):
+ df = DataFrame(
+ {
+ "a": [1, 2],
+ "b": "c",
+ "c": 1,
+ "d": Series(
+ [Timestamp("2019-12-31"), Timestamp("2020-12-31")], dtype="object"
+ ),
+ }
+ )
+ view = df[:] # noqa: F841
+ df = df.infer_objects()
+
+ arr_a = get_array(df, "a")
+ arr_b = get_array(df, "b")
+ arr_d = get_array(df, "d")
+
+ df.iloc[0, 0] = 0
+ df.iloc[0, 1] = "d"
+ df.iloc[0, 3] = Timestamp("2018-12-31")
+ if using_copy_on_write:
+ assert not np.shares_memory(arr_a, get_array(df, "a"))
+ assert not np.shares_memory(arr_b, get_array(df, "b"))
+ assert np.shares_memory(arr_d, get_array(df, "d"))
+
+
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"before": "a", "after": "b", "axis": 1},
+ {"before": 0, "after": 1, "axis": 0},
+ ],
+)
+def test_truncate(using_copy_on_write, kwargs):
+ df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 2})
+ df_orig = df.copy()
+ df2 = df.truncate(**kwargs)
+ df2._mgr._verify_integrity()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize("method", ["assign", "drop_duplicates"])
+def test_assign_drop_duplicates(using_copy_on_write, method):
+ df = DataFrame({"a": [1, 2, 3]})
+ df_orig = df.copy()
+ df2 = getattr(df, method)()
+ df2._mgr._verify_integrity()
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize("obj", [Series([1, 2]), DataFrame({"a": [1, 2]})])
+def test_take(using_copy_on_write, obj):
+ # Check that no copy is made when we take all rows in original order
+ obj_orig = obj.copy()
+ obj2 = obj.take([0, 1])
+
+ if using_copy_on_write:
+ assert np.shares_memory(obj2.values, obj.values)
+ else:
+ assert not np.shares_memory(obj2.values, obj.values)
+
+ obj2.iloc[0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(obj2.values, obj.values)
+ tm.assert_equal(obj, obj_orig)
+
+
+@pytest.mark.parametrize("obj", [Series([1, 2]), DataFrame({"a": [1, 2]})])
+def test_between_time(using_copy_on_write, obj):
+ obj.index = date_range("2018-04-09", periods=2, freq="1D20min")
+ obj_orig = obj.copy()
+ obj2 = obj.between_time("0:00", "1:00")
+
+ if using_copy_on_write:
+ assert np.shares_memory(obj2.values, obj.values)
+ else:
+ assert not np.shares_memory(obj2.values, obj.values)
+
+ obj2.iloc[0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(obj2.values, obj.values)
+ tm.assert_equal(obj, obj_orig)
+
+
+def test_reindex_like(using_copy_on_write):
+ df = DataFrame({"a": [1, 2], "b": "a"})
+ other = DataFrame({"b": "a", "a": [1, 2]})
+
+ df_orig = df.copy()
+ df2 = df.reindex_like(other)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df2.iloc[0, 1] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_sort_index(using_copy_on_write):
+ # GH 49473
+ ser = Series([1, 2, 3])
+ ser_orig = ser.copy()
+ ser2 = ser.sort_index()
+
+ if using_copy_on_write:
+ assert np.shares_memory(ser.values, ser2.values)
+ else:
+ assert not np.shares_memory(ser.values, ser2.values)
+
+ # mutating ser triggers a copy-on-write for the column / block
+ ser2.iloc[0] = 0
+ assert not np.shares_memory(ser2.values, ser.values)
+ tm.assert_series_equal(ser, ser_orig)
+
+
+@pytest.mark.parametrize(
+ "obj, kwargs",
+ [(Series([1, 2, 3], name="a"), {}), (DataFrame({"a": [1, 2, 3]}), {"by": "a"})],
+)
+def test_sort_values(using_copy_on_write, obj, kwargs):
+ obj_orig = obj.copy()
+ obj2 = obj.sort_values(**kwargs)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a"))
+ else:
+ assert not np.shares_memory(get_array(obj2, "a"), get_array(obj, "a"))
+
+ # mutating df triggers a copy-on-write for the column / block
+ obj2.iloc[0] = 0
+ assert not np.shares_memory(get_array(obj2, "a"), get_array(obj, "a"))
+ tm.assert_equal(obj, obj_orig)
+
+
+@pytest.mark.parametrize(
+ "obj, kwargs",
+ [(Series([1, 2, 3], name="a"), {}), (DataFrame({"a": [1, 2, 3]}), {"by": "a"})],
+)
+def test_sort_values_inplace(using_copy_on_write, obj, kwargs, using_array_manager):
+ obj_orig = obj.copy()
+ view = obj[:]
+ obj.sort_values(inplace=True, **kwargs)
+
+ assert np.shares_memory(get_array(obj, "a"), get_array(view, "a"))
+
+ # mutating obj triggers a copy-on-write for the column / block
+ obj.iloc[0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(obj, "a"), get_array(view, "a"))
+ tm.assert_equal(view, obj_orig)
+ else:
+ assert np.shares_memory(get_array(obj, "a"), get_array(view, "a"))
+
+
+@pytest.mark.parametrize("decimals", [-1, 0, 1])
+def test_round(using_copy_on_write, decimals):
+ df = DataFrame({"a": [1, 2], "b": "c"})
+ df_orig = df.copy()
+ df2 = df.round(decimals=decimals)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ # TODO: Make inplace by using out parameter of ndarray.round?
+ if decimals >= 0:
+ # Ensure lazy copy if no-op
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+
+ df2.iloc[0, 1] = "d"
+ df2.iloc[0, 0] = 4
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_reorder_levels(using_copy_on_write):
+ index = MultiIndex.from_tuples(
+ [(1, 1), (1, 2), (2, 1), (2, 2)], names=["one", "two"]
+ )
+ df = DataFrame({"a": [1, 2, 3, 4]}, index=index)
+ df_orig = df.copy()
+ df2 = df.reorder_levels(order=["two", "one"])
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_series_reorder_levels(using_copy_on_write):
+ index = MultiIndex.from_tuples(
+ [(1, 1), (1, 2), (2, 1), (2, 2)], names=["one", "two"]
+ )
+ ser = Series([1, 2, 3, 4], index=index)
+ ser_orig = ser.copy()
+ ser2 = ser.reorder_levels(order=["two", "one"])
+
+ if using_copy_on_write:
+ assert np.shares_memory(ser2.values, ser.values)
+ else:
+ assert not np.shares_memory(ser2.values, ser.values)
+
+ ser2.iloc[0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(ser2.values, ser.values)
+ tm.assert_series_equal(ser, ser_orig)
+
+
+@pytest.mark.parametrize("obj", [Series([1, 2, 3]), DataFrame({"a": [1, 2, 3]})])
+def test_swaplevel(using_copy_on_write, obj):
+ index = MultiIndex.from_tuples([(1, 1), (1, 2), (2, 1)], names=["one", "two"])
+ obj.index = index
+ obj_orig = obj.copy()
+ obj2 = obj.swaplevel()
+
+ if using_copy_on_write:
+ assert np.shares_memory(obj2.values, obj.values)
+ else:
+ assert not np.shares_memory(obj2.values, obj.values)
+
+ obj2.iloc[0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(obj2.values, obj.values)
+ tm.assert_equal(obj, obj_orig)
+
+
+def test_frame_set_axis(using_copy_on_write):
+ # GH 49473
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
+ df_orig = df.copy()
+ df2 = df.set_axis(["a", "b", "c"], axis="index")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column / block
+ df2.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_series_set_axis(using_copy_on_write):
+ # GH 49473
+ ser = Series([1, 2, 3])
+ ser_orig = ser.copy()
+ ser2 = ser.set_axis(["a", "b", "c"], axis="index")
+
+ if using_copy_on_write:
+ assert np.shares_memory(ser, ser2)
+ else:
+ assert not np.shares_memory(ser, ser2)
+
+ # mutating ser triggers a copy-on-write for the column / block
+ ser2.iloc[0] = 0
+ assert not np.shares_memory(ser2, ser)
+ tm.assert_series_equal(ser, ser_orig)
+
+
+def test_set_flags(using_copy_on_write):
+ ser = Series([1, 2, 3])
+ ser_orig = ser.copy()
+ ser2 = ser.set_flags(allows_duplicate_labels=False)
+
+ assert np.shares_memory(ser, ser2)
+
+ # mutating ser triggers a copy-on-write for the column / block
+ ser2.iloc[0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(ser2, ser)
+ tm.assert_series_equal(ser, ser_orig)
+ else:
+ assert np.shares_memory(ser2, ser)
+ expected = Series([0, 2, 3])
+ tm.assert_series_equal(ser, expected)
+
+
+@pytest.mark.parametrize("kwargs", [{"mapper": "test"}, {"index": "test"}])
+def test_rename_axis(using_copy_on_write, kwargs):
+ df = DataFrame({"a": [1, 2, 3, 4]}, index=Index([1, 2, 3, 4], name="a"))
+ df_orig = df.copy()
+ df2 = df.rename_axis(**kwargs)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df2.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize(
+ "func, tz", [("tz_convert", "Europe/Berlin"), ("tz_localize", None)]
+)
+def test_tz_convert_localize(using_copy_on_write, func, tz):
+ # GH 49473
+ ser = Series(
+ [1, 2], index=date_range(start="2014-08-01 09:00", freq="H", periods=2, tz=tz)
+ )
+ ser_orig = ser.copy()
+ ser2 = getattr(ser, func)("US/Central")
+
+ if using_copy_on_write:
+ assert np.shares_memory(ser.values, ser2.values)
+ else:
+ assert not np.shares_memory(ser.values, ser2.values)
+
+ # mutating ser triggers a copy-on-write for the column / block
+ ser2.iloc[0] = 0
+ assert not np.shares_memory(ser2.values, ser.values)
+ tm.assert_series_equal(ser, ser_orig)
+
+
+def test_droplevel(using_copy_on_write):
+ # GH 49473
+ index = MultiIndex.from_tuples([(1, 1), (1, 2), (2, 1)], names=["one", "two"])
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}, index=index)
+ df_orig = df.copy()
+ df2 = df.droplevel(0)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column / block
+ df2.iloc[0, 0] = 0
+
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
+
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_squeeze(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3]})
+ df_orig = df.copy()
+ series = df.squeeze()
+
+ # Should share memory regardless of CoW since squeeze is just an iloc
+ assert np.shares_memory(series.values, get_array(df, "a"))
+
+ # mutating squeezed df triggers a copy-on-write for that column/block
+ series.iloc[0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(series.values, get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ # Without CoW the original will be modified
+ assert np.shares_memory(series.values, get_array(df, "a"))
+ assert df.loc[0, "a"] == 0
+
+
+def test_items(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})
+ df_orig = df.copy()
+
+ # Test this twice, since the second time, the item cache will be
+ # triggered, and we want to make sure it still works then.
+ for i in range(2):
+ for name, ser in df.items():
+ assert np.shares_memory(get_array(ser, name), get_array(df, name))
+
+ # mutating df triggers a copy-on-write for that column / block
+ ser.iloc[0] = 0
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(ser, name), get_array(df, name))
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ # Original frame will be modified
+ assert df.loc[0, name] == 0
+
+
+@pytest.mark.parametrize("dtype", ["int64", "Int64"])
+def test_putmask(using_copy_on_write, dtype):
+ df = DataFrame({"a": [1, 2], "b": 1, "c": 2}, dtype=dtype)
+ view = df[:]
+ df_orig = df.copy()
+ df[df == df] = 5
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(view, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(view, df_orig)
+ else:
+ # Without CoW the original will be modified
+ assert np.shares_memory(get_array(view, "a"), get_array(df, "a"))
+ assert view.iloc[0, 0] == 5
+
+
+@pytest.mark.parametrize("dtype", ["int64", "Int64"])
+def test_putmask_no_reference(using_copy_on_write, dtype):
+ df = DataFrame({"a": [1, 2], "b": 1, "c": 2}, dtype=dtype)
+ arr_a = get_array(df, "a")
+ df[df == df] = 5
+
+ if using_copy_on_write:
+ assert np.shares_memory(arr_a, get_array(df, "a"))
+
+
+@pytest.mark.parametrize("dtype", ["float64", "Float64"])
+def test_putmask_aligns_rhs_no_reference(using_copy_on_write, dtype):
+ df = DataFrame({"a": [1.5, 2], "b": 1.5}, dtype=dtype)
+ arr_a = get_array(df, "a")
+ df[df == df] = DataFrame({"a": [5.5, 5]})
+
+ if using_copy_on_write:
+ assert np.shares_memory(arr_a, get_array(df, "a"))
+
+
+@pytest.mark.parametrize(
+ "val, exp, warn", [(5.5, True, FutureWarning), (5, False, None)]
+)
+def test_putmask_dont_copy_some_blocks(using_copy_on_write, val, exp, warn):
+ df = DataFrame({"a": [1, 2], "b": 1, "c": 1.5})
+ view = df[:]
+ df_orig = df.copy()
+ indexer = DataFrame(
+ [[True, False, False], [True, False, False]], columns=list("abc")
+ )
+ with tm.assert_produces_warning(warn, match="incompatible dtype"):
+ df[indexer] = val
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(view, "a"), get_array(df, "a"))
+ # TODO(CoW): Could split blocks to avoid copying the whole block
+ assert np.shares_memory(get_array(view, "b"), get_array(df, "b")) is exp
+ assert np.shares_memory(get_array(view, "c"), get_array(df, "c"))
+ assert df._mgr._has_no_reference(1) is not exp
+ assert not df._mgr._has_no_reference(2)
+ tm.assert_frame_equal(view, df_orig)
+ elif val == 5:
+ # Without CoW the original will be modified, the other case upcasts, e.g. copy
+ assert np.shares_memory(get_array(view, "a"), get_array(df, "a"))
+ assert np.shares_memory(get_array(view, "c"), get_array(df, "c"))
+ assert view.iloc[0, 0] == 5
+
+
+@pytest.mark.parametrize("dtype", ["int64", "Int64"])
+@pytest.mark.parametrize(
+ "func",
+ [
+ lambda ser: ser.where(ser > 0, 10),
+ lambda ser: ser.mask(ser <= 0, 10),
+ ],
+)
+def test_where_mask_noop(using_copy_on_write, dtype, func):
+ ser = Series([1, 2, 3], dtype=dtype)
+ ser_orig = ser.copy()
+
+ result = func(ser)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(ser), get_array(result))
+ else:
+ assert not np.shares_memory(get_array(ser), get_array(result))
+
+ result.iloc[0] = 10
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(ser), get_array(result))
+ tm.assert_series_equal(ser, ser_orig)
+
+
+@pytest.mark.parametrize("dtype", ["int64", "Int64"])
+@pytest.mark.parametrize(
+ "func",
+ [
+ lambda ser: ser.where(ser < 0, 10),
+ lambda ser: ser.mask(ser >= 0, 10),
+ ],
+)
+def test_where_mask(using_copy_on_write, dtype, func):
+ ser = Series([1, 2, 3], dtype=dtype)
+ ser_orig = ser.copy()
+
+ result = func(ser)
+
+ assert not np.shares_memory(get_array(ser), get_array(result))
+ tm.assert_series_equal(ser, ser_orig)
+
+
+@pytest.mark.parametrize("dtype, val", [("int64", 10.5), ("Int64", 10)])
+@pytest.mark.parametrize(
+ "func",
+ [
+ lambda df, val: df.where(df < 0, val),
+ lambda df, val: df.mask(df >= 0, val),
+ ],
+)
+def test_where_mask_noop_on_single_column(using_copy_on_write, dtype, val, func):
+ df = DataFrame({"a": [1, 2, 3], "b": [-4, -5, -6]}, dtype=dtype)
+ df_orig = df.copy()
+
+ result = func(df, val)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "b"), get_array(result, "b"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+ else:
+ assert not np.shares_memory(get_array(df, "b"), get_array(result, "b"))
+
+ result.iloc[0, 1] = 10
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "b"), get_array(result, "b"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+@pytest.mark.parametrize("func", ["mask", "where"])
+def test_chained_where_mask(using_copy_on_write, func):
+ df = DataFrame({"a": [1, 4, 2], "b": 1})
+ df_orig = df.copy()
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ getattr(df["a"], func)(df["a"] > 2, 5, inplace=True)
+ tm.assert_frame_equal(df, df_orig)
+
+ with tm.raises_chained_assignment_error():
+ getattr(df[["a"]], func)(df["a"] > 2, 5, inplace=True)
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_asfreq_noop(using_copy_on_write):
+ df = DataFrame(
+ {"a": [0.0, None, 2.0, 3.0]},
+ index=date_range("1/1/2000", periods=4, freq="T"),
+ )
+ df_orig = df.copy()
+ df2 = df.asfreq(freq="T")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ # mutating df2 triggers a copy-on-write for that column / block
+ df2.iloc[0, 0] = 0
+
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_iterrows(using_copy_on_write):
+ df = DataFrame({"a": 0, "b": 1}, index=[1, 2, 3])
+ df_orig = df.copy()
+
+ for _, sub in df.iterrows():
+ sub.iloc[0] = 100
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_interpolate_creates_copy(using_copy_on_write):
+ # GH#51126
+ df = DataFrame({"a": [1.5, np.nan, 3]})
+ view = df[:]
+ expected = df.copy()
+
+ df.ffill(inplace=True)
+ df.iloc[0, 0] = 100.5
+
+ if using_copy_on_write:
+ tm.assert_frame_equal(view, expected)
+ else:
+ expected = DataFrame({"a": [100.5, 1.5, 3]})
+ tm.assert_frame_equal(view, expected)
+
+
+def test_isetitem(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})
+ df_orig = df.copy()
+ df2 = df.copy(deep=None) # Trigger a CoW
+ df2.isetitem(1, np.array([-1, -2, -3])) # This is inplace
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ else:
+ assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ df2.loc[0, "a"] = 0
+ tm.assert_frame_equal(df, df_orig) # Original is unchanged
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ else:
+ assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+
+
+@pytest.mark.parametrize(
+ "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
+)
+def test_isetitem_series(using_copy_on_write, dtype):
+ df = DataFrame({"a": [1, 2, 3], "b": np.array([4, 5, 6], dtype=dtype)})
+ ser = Series([7, 8, 9])
+ ser_orig = ser.copy()
+ df.isetitem(0, ser)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "a"), get_array(ser))
+ assert not df._mgr._has_no_reference(0)
+
+ # mutating dataframe doesn't update series
+ df.loc[0, "a"] = 0
+ tm.assert_series_equal(ser, ser_orig)
+
+ # mutating series doesn't update dataframe
+ df = DataFrame({"a": [1, 2, 3], "b": np.array([4, 5, 6], dtype=dtype)})
+ ser = Series([7, 8, 9])
+ df.isetitem(0, ser)
+
+ ser.loc[0] = 0
+ expected = DataFrame({"a": [7, 8, 9], "b": np.array([4, 5, 6], dtype=dtype)})
+ tm.assert_frame_equal(df, expected)
+
+
+def test_isetitem_frame(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 2})
+ rhs = DataFrame({"a": [4, 5, 6], "b": 2})
+ df.isetitem([0, 1], rhs)
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "a"), get_array(rhs, "a"))
+ assert np.shares_memory(get_array(df, "b"), get_array(rhs, "b"))
+ assert not df._mgr._has_no_reference(0)
+ else:
+ assert not np.shares_memory(get_array(df, "a"), get_array(rhs, "a"))
+ assert not np.shares_memory(get_array(df, "b"), get_array(rhs, "b"))
+ expected = df.copy()
+ rhs.iloc[0, 0] = 100
+ rhs.iloc[0, 1] = 100
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.parametrize("key", ["a", ["a"]])
+def test_get(using_copy_on_write, key):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df_orig = df.copy()
+
+ result = df.get(key)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ result.iloc[0] = 0
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ # for non-CoW it depends on whether we got a Series or DataFrame if it
+ # is a view or copy or triggers a warning or not
+ warn = SettingWithCopyWarning if isinstance(key, list) else None
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(warn):
+ result.iloc[0] = 0
+
+ if isinstance(key, list):
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert df.iloc[0, 0] == 0
+
+
+@pytest.mark.parametrize("axis, key", [(0, 0), (1, "a")])
+@pytest.mark.parametrize(
+ "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
+)
+def test_xs(using_copy_on_write, using_array_manager, axis, key, dtype):
+ single_block = (dtype == "int64") and not using_array_manager
+ is_view = single_block or (using_array_manager and axis == 1)
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
+ )
+ df_orig = df.copy()
+
+ result = df.xs(key, axis=axis)
+
+ if axis == 1 or single_block:
+ assert np.shares_memory(get_array(df, "a"), get_array(result))
+ elif using_copy_on_write:
+ assert result._mgr._has_no_reference(0)
+
+ if using_copy_on_write or is_view:
+ result.iloc[0] = 0
+ else:
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(SettingWithCopyWarning):
+ result.iloc[0] = 0
+
+ if using_copy_on_write or (not single_block and axis == 0):
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert df.iloc[0, 0] == 0
+
+
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize("key, level", [("l1", 0), (2, 1)])
+def test_xs_multiindex(using_copy_on_write, using_array_manager, key, level, axis):
+ arr = np.arange(18).reshape(6, 3)
+ index = MultiIndex.from_product([["l1", "l2"], [1, 2, 3]], names=["lev1", "lev2"])
+ df = DataFrame(arr, index=index, columns=list("abc"))
+ if axis == 1:
+ df = df.transpose().copy()
+ df_orig = df.copy()
+
+ result = df.xs(key, level=level, axis=axis)
+
+ if level == 0:
+ assert np.shares_memory(
+ get_array(df, df.columns[0]), get_array(result, result.columns[0])
+ )
+
+ warn = (
+ SettingWithCopyWarning
+ if not using_copy_on_write and not using_array_manager
+ else None
+ )
+ with pd.option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(warn):
+ result.iloc[0, 0] = 0
+
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_update_frame(using_copy_on_write):
+ df1 = DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]})
+ df2 = DataFrame({"b": [100.0]}, index=[1])
+ df1_orig = df1.copy()
+ view = df1[:]
+
+ df1.update(df2)
+
+ expected = DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 100.0, 6.0]})
+ tm.assert_frame_equal(df1, expected)
+ if using_copy_on_write:
+ # df1 is updated, but its view not
+ tm.assert_frame_equal(view, df1_orig)
+ assert np.shares_memory(get_array(df1, "a"), get_array(view, "a"))
+ assert not np.shares_memory(get_array(df1, "b"), get_array(view, "b"))
+ else:
+ tm.assert_frame_equal(view, expected)
+
+
+def test_update_series(using_copy_on_write):
+ ser1 = Series([1.0, 2.0, 3.0])
+ ser2 = Series([100.0], index=[1])
+ ser1_orig = ser1.copy()
+ view = ser1[:]
+
+ ser1.update(ser2)
+
+ expected = Series([1.0, 100.0, 3.0])
+ tm.assert_series_equal(ser1, expected)
+ if using_copy_on_write:
+ # ser1 is updated, but its view not
+ tm.assert_series_equal(view, ser1_orig)
+ else:
+ tm.assert_series_equal(view, expected)
+
+
+def test_update_chained_assignment(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3]})
+ ser2 = Series([100.0], index=[1])
+ df_orig = df.copy()
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["a"].update(ser2)
+ tm.assert_frame_equal(df, df_orig)
+
+ with tm.raises_chained_assignment_error():
+ df[["a"]].update(ser2.to_frame())
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_inplace_arithmetic_series():
+ ser = Series([1, 2, 3])
+ data = get_array(ser)
+ ser *= 2
+ assert np.shares_memory(get_array(ser), data)
+ tm.assert_numpy_array_equal(data, get_array(ser))
+
+
+def test_inplace_arithmetic_series_with_reference(using_copy_on_write):
+ ser = Series([1, 2, 3])
+ ser_orig = ser.copy()
+ view = ser[:]
+ ser *= 2
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(ser), get_array(view))
+ tm.assert_series_equal(ser_orig, view)
+ else:
+ assert np.shares_memory(get_array(ser), get_array(view))
+
+
+@pytest.mark.parametrize("copy", [True, False])
+def test_transpose(using_copy_on_write, copy, using_array_manager):
+ df = DataFrame({"a": [1, 2, 3], "b": 1})
+ df_orig = df.copy()
+ result = df.transpose(copy=copy)
+
+ if not copy and not using_array_manager or using_copy_on_write:
+ assert np.shares_memory(get_array(df, "a"), get_array(result, 0))
+ else:
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, 0))
+
+ result.iloc[0, 0] = 100
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_transpose_different_dtypes(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": 1.5})
+ df_orig = df.copy()
+ result = df.T
+
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, 0))
+ result.iloc[0, 0] = 100
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_transpose_ea_single_column(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3]}, dtype="Int64")
+ result = df.T
+
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, 0))
+
+
+def test_transform_frame(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": 1})
+ df_orig = df.copy()
+
+ def func(ser):
+ ser.iloc[0] = 100
+ return ser
+
+ df.transform(func)
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_transform_series(using_copy_on_write):
+ ser = Series([1, 2, 3])
+ ser_orig = ser.copy()
+
+ def func(ser):
+ ser.iloc[0] = 100
+ return ser
+
+ ser.transform(func)
+ if using_copy_on_write:
+ tm.assert_series_equal(ser, ser_orig)
+
+
+def test_count_read_only_array():
+ df = DataFrame({"a": [1, 2], "b": 3})
+ result = df.count()
+ result.iloc[0] = 100
+ expected = Series([100, 2], index=["a", "b"])
+ tm.assert_series_equal(result, expected)
+
+
+def test_series_view(using_copy_on_write):
+ ser = Series([1, 2, 3])
+ ser_orig = ser.copy()
+
+ ser2 = ser.view()
+ assert np.shares_memory(get_array(ser), get_array(ser2))
+ if using_copy_on_write:
+ assert not ser2._mgr._has_no_reference(0)
+
+ ser2.iloc[0] = 100
+
+ if using_copy_on_write:
+ tm.assert_series_equal(ser_orig, ser)
+ else:
+ expected = Series([100, 2, 3])
+ tm.assert_series_equal(ser, expected)
+
+
+def test_insert_series(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3]})
+ ser = Series([1, 2, 3])
+ ser_orig = ser.copy()
+ df.insert(loc=1, value=ser, column="b")
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(ser), get_array(df, "b"))
+ assert not df._mgr._has_no_reference(1)
+ else:
+ assert not np.shares_memory(get_array(ser), get_array(df, "b"))
+
+ df.iloc[0, 1] = 100
+ tm.assert_series_equal(ser, ser_orig)
+
+
+def test_eval(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": 1})
+ df_orig = df.copy()
+
+ result = df.eval("c = a+b")
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+ else:
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+
+ result.iloc[0, 0] = 100
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_eval_inplace(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": 1})
+ df_orig = df.copy()
+ df_view = df[:]
+
+ df.eval("c = a+b", inplace=True)
+ assert np.shares_memory(get_array(df, "a"), get_array(df_view, "a"))
+
+ df.iloc[0, 0] = 100
+ if using_copy_on_write:
+ tm.assert_frame_equal(df_view, df_orig)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_replace.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_replace.py
new file mode 100644
index 0000000000000000000000000000000000000000..085f355dc4377b267f9cb8d65b8a3632ba0e5b05
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_replace.py
@@ -0,0 +1,432 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ Categorical,
+ DataFrame,
+)
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+
+@pytest.mark.parametrize(
+ "replace_kwargs",
+ [
+ {"to_replace": {"a": 1, "b": 4}, "value": -1},
+ # Test CoW splits blocks to avoid copying unchanged columns
+ {"to_replace": {"a": 1}, "value": -1},
+ {"to_replace": {"b": 4}, "value": -1},
+ {"to_replace": {"b": {4: 1}}},
+ # TODO: Add these in a further optimization
+ # We would need to see which columns got replaced in the mask
+ # which could be expensive
+ # {"to_replace": {"b": 1}},
+ # 1
+ ],
+)
+def test_replace(using_copy_on_write, replace_kwargs):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": ["foo", "bar", "baz"]})
+ df_orig = df.copy()
+
+ df_replaced = df.replace(**replace_kwargs)
+
+ if using_copy_on_write:
+ if (df_replaced["b"] == df["b"]).all():
+ assert np.shares_memory(get_array(df_replaced, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(df_replaced, "c"), get_array(df, "c"))
+
+ # mutating squeezed df triggers a copy-on-write for that column/block
+ df_replaced.loc[0, "c"] = -1
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df_replaced, "c"), get_array(df, "c"))
+
+ if "a" in replace_kwargs["to_replace"]:
+ arr = get_array(df_replaced, "a")
+ df_replaced.loc[0, "a"] = 100
+ assert np.shares_memory(get_array(df_replaced, "a"), arr)
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_replace_regex_inplace_refs(using_copy_on_write):
+ df = DataFrame({"a": ["aaa", "bbb"]})
+ df_orig = df.copy()
+ view = df[:]
+ arr = get_array(df, "a")
+ df.replace(to_replace=r"^a.*$", value="new", inplace=True, regex=True)
+ if using_copy_on_write:
+ assert not np.shares_memory(arr, get_array(df, "a"))
+ assert df._mgr._has_no_reference(0)
+ tm.assert_frame_equal(view, df_orig)
+ else:
+ assert np.shares_memory(arr, get_array(df, "a"))
+
+
+def test_replace_regex_inplace(using_copy_on_write):
+ df = DataFrame({"a": ["aaa", "bbb"]})
+ arr = get_array(df, "a")
+ df.replace(to_replace=r"^a.*$", value="new", inplace=True, regex=True)
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ assert np.shares_memory(arr, get_array(df, "a"))
+
+ df_orig = df.copy()
+ df2 = df.replace(to_replace=r"^b.*$", value="new", regex=True)
+ tm.assert_frame_equal(df_orig, df)
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+
+def test_replace_regex_inplace_no_op(using_copy_on_write):
+ df = DataFrame({"a": [1, 2]})
+ arr = get_array(df, "a")
+ df.replace(to_replace=r"^a.$", value="new", inplace=True, regex=True)
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ assert np.shares_memory(arr, get_array(df, "a"))
+
+ df_orig = df.copy()
+ df2 = df.replace(to_replace=r"^x.$", value="new", regex=True)
+ tm.assert_frame_equal(df_orig, df)
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+
+def test_replace_mask_all_false_second_block(using_copy_on_write):
+ df = DataFrame({"a": [1.5, 2, 3], "b": 100.5, "c": 1, "d": 2})
+ df_orig = df.copy()
+
+ df2 = df.replace(to_replace=1.5, value=55.5)
+
+ if using_copy_on_write:
+ # TODO: Block splitting would allow us to avoid copying b
+ assert np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ else:
+ assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ df2.loc[0, "c"] = 1
+ tm.assert_frame_equal(df, df_orig) # Original is unchanged
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ # TODO: This should split and not copy the whole block
+ # assert np.shares_memory(get_array(df, "d"), get_array(df2, "d"))
+
+
+def test_replace_coerce_single_column(using_copy_on_write, using_array_manager):
+ df = DataFrame({"a": [1.5, 2, 3], "b": 100.5})
+ df_orig = df.copy()
+
+ df2 = df.replace(to_replace=1.5, value="a")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ elif not using_array_manager:
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ if using_copy_on_write:
+ df2.loc[0, "b"] = 0.5
+ tm.assert_frame_equal(df, df_orig) # Original is unchanged
+ assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+
+
+def test_replace_to_replace_wrong_dtype(using_copy_on_write):
+ df = DataFrame({"a": [1.5, 2, 3], "b": 100.5})
+ df_orig = df.copy()
+
+ df2 = df.replace(to_replace="xxx", value=1.5)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ else:
+ assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ df2.loc[0, "b"] = 0.5
+ tm.assert_frame_equal(df, df_orig) # Original is unchanged
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+
+
+def test_replace_list_categorical(using_copy_on_write):
+ df = DataFrame({"a": ["a", "b", "c"]}, dtype="category")
+ arr = get_array(df, "a")
+ df.replace(["c"], value="a", inplace=True)
+ assert np.shares_memory(arr.codes, get_array(df, "a").codes)
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+
+ df_orig = df.copy()
+ df2 = df.replace(["b"], value="a")
+ assert not np.shares_memory(arr.codes, get_array(df2, "a").codes)
+
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_replace_list_inplace_refs_categorical(using_copy_on_write):
+ df = DataFrame({"a": ["a", "b", "c"]}, dtype="category")
+ view = df[:]
+ df_orig = df.copy()
+ df.replace(["c"], value="a", inplace=True)
+ if using_copy_on_write:
+ assert not np.shares_memory(
+ get_array(view, "a").codes, get_array(df, "a").codes
+ )
+ tm.assert_frame_equal(df_orig, view)
+ else:
+ # This could be inplace
+ assert not np.shares_memory(
+ get_array(view, "a").codes, get_array(df, "a").codes
+ )
+
+
+@pytest.mark.parametrize("to_replace", [1.5, [1.5], []])
+def test_replace_inplace(using_copy_on_write, to_replace):
+ df = DataFrame({"a": [1.5, 2, 3]})
+ arr_a = get_array(df, "a")
+ df.replace(to_replace=1.5, value=15.5, inplace=True)
+
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+
+
+@pytest.mark.parametrize("to_replace", [1.5, [1.5]])
+def test_replace_inplace_reference(using_copy_on_write, to_replace):
+ df = DataFrame({"a": [1.5, 2, 3]})
+ arr_a = get_array(df, "a")
+ view = df[:]
+ df.replace(to_replace=to_replace, value=15.5, inplace=True)
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), arr_a)
+ assert df._mgr._has_no_reference(0)
+ assert view._mgr._has_no_reference(0)
+ else:
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+
+
+@pytest.mark.parametrize("to_replace", ["a", 100.5])
+def test_replace_inplace_reference_no_op(using_copy_on_write, to_replace):
+ df = DataFrame({"a": [1.5, 2, 3]})
+ arr_a = get_array(df, "a")
+ view = df[:]
+ df.replace(to_replace=to_replace, value=15.5, inplace=True)
+
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+ if using_copy_on_write:
+ assert not df._mgr._has_no_reference(0)
+ assert not view._mgr._has_no_reference(0)
+
+
+@pytest.mark.parametrize("to_replace", [1, [1]])
+@pytest.mark.parametrize("val", [1, 1.5])
+def test_replace_categorical_inplace_reference(using_copy_on_write, val, to_replace):
+ df = DataFrame({"a": Categorical([1, 2, 3])})
+ df_orig = df.copy()
+ arr_a = get_array(df, "a")
+ view = df[:]
+ df.replace(to_replace=to_replace, value=val, inplace=True)
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a").codes, arr_a.codes)
+ assert df._mgr._has_no_reference(0)
+ assert view._mgr._has_no_reference(0)
+ tm.assert_frame_equal(view, df_orig)
+ else:
+ assert np.shares_memory(get_array(df, "a").codes, arr_a.codes)
+
+
+@pytest.mark.parametrize("val", [1, 1.5])
+def test_replace_categorical_inplace(using_copy_on_write, val):
+ df = DataFrame({"a": Categorical([1, 2, 3])})
+ arr_a = get_array(df, "a")
+ df.replace(to_replace=1, value=val, inplace=True)
+
+ assert np.shares_memory(get_array(df, "a").codes, arr_a.codes)
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+
+ expected = DataFrame({"a": Categorical([val, 2, 3])})
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.parametrize("val", [1, 1.5])
+def test_replace_categorical(using_copy_on_write, val):
+ df = DataFrame({"a": Categorical([1, 2, 3])})
+ df_orig = df.copy()
+ df2 = df.replace(to_replace=1, value=val)
+
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ assert df2._mgr._has_no_reference(0)
+ assert not np.shares_memory(get_array(df, "a").codes, get_array(df2, "a").codes)
+ tm.assert_frame_equal(df, df_orig)
+
+ arr_a = get_array(df2, "a").codes
+ df2.iloc[0, 0] = 2.0
+ assert np.shares_memory(get_array(df2, "a").codes, arr_a)
+
+
+@pytest.mark.parametrize("method", ["where", "mask"])
+def test_masking_inplace(using_copy_on_write, method):
+ df = DataFrame({"a": [1.5, 2, 3]})
+ df_orig = df.copy()
+ arr_a = get_array(df, "a")
+ view = df[:]
+
+ method = getattr(df, method)
+ method(df["a"] > 1.6, -1, inplace=True)
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), arr_a)
+ assert df._mgr._has_no_reference(0)
+ assert view._mgr._has_no_reference(0)
+ tm.assert_frame_equal(view, df_orig)
+ else:
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+
+
+def test_replace_empty_list(using_copy_on_write):
+ df = DataFrame({"a": [1, 2]})
+
+ df2 = df.replace([], [])
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ assert not df._mgr._has_no_reference(0)
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ arr_a = get_array(df, "a")
+ df.replace([], [])
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "a"), arr_a)
+ assert not df._mgr._has_no_reference(0)
+ assert not df2._mgr._has_no_reference(0)
+
+
+@pytest.mark.parametrize("value", ["d", None])
+def test_replace_object_list_inplace(using_copy_on_write, value):
+ df = DataFrame({"a": ["a", "b", "c"]})
+ arr = get_array(df, "a")
+ df.replace(["c"], value, inplace=True)
+ if using_copy_on_write or value is None:
+ assert np.shares_memory(arr, get_array(df, "a"))
+ else:
+ # This could be inplace
+ assert not np.shares_memory(arr, get_array(df, "a"))
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+
+
+def test_replace_list_multiple_elements_inplace(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3]})
+ arr = get_array(df, "a")
+ df.replace([1, 2], 4, inplace=True)
+ if using_copy_on_write:
+ assert np.shares_memory(arr, get_array(df, "a"))
+ assert df._mgr._has_no_reference(0)
+ else:
+ assert np.shares_memory(arr, get_array(df, "a"))
+
+
+def test_replace_list_none(using_copy_on_write):
+ df = DataFrame({"a": ["a", "b", "c"]})
+
+ df_orig = df.copy()
+ df2 = df.replace(["b"], value=None)
+ tm.assert_frame_equal(df, df_orig)
+
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+
+def test_replace_list_none_inplace_refs(using_copy_on_write):
+ df = DataFrame({"a": ["a", "b", "c"]})
+ arr = get_array(df, "a")
+ df_orig = df.copy()
+ view = df[:]
+ df.replace(["a"], value=None, inplace=True)
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
+ assert not np.shares_memory(arr, get_array(df, "a"))
+ tm.assert_frame_equal(df_orig, view)
+ else:
+ assert np.shares_memory(arr, get_array(df, "a"))
+
+
+def test_replace_columnwise_no_op_inplace(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]})
+ view = df[:]
+ df_orig = df.copy()
+ df.replace({"a": 10}, 100, inplace=True)
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(view, "a"), get_array(df, "a"))
+ df.iloc[0, 0] = 100
+ tm.assert_frame_equal(view, df_orig)
+
+
+def test_replace_columnwise_no_op(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]})
+ df_orig = df.copy()
+ df2 = df.replace({"a": 10}, 100)
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ df2.iloc[0, 0] = 100
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_replace_chained_assignment(using_copy_on_write):
+ df = DataFrame({"a": [1, np.nan, 2], "b": 1})
+ df_orig = df.copy()
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["a"].replace(1, 100, inplace=True)
+ tm.assert_frame_equal(df, df_orig)
+
+ with tm.raises_chained_assignment_error():
+ df[["a"]].replace(1, 100, inplace=True)
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_replace_listlike(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]})
+ df_orig = df.copy()
+
+ result = df.replace([200, 201], [11, 11])
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+
+ result.iloc[0, 0] = 100
+ tm.assert_frame_equal(df, df)
+
+ result = df.replace([200, 2], [10, 10])
+ assert not np.shares_memory(get_array(df, "a"), get_array(result, "a"))
+ tm.assert_frame_equal(df, df_orig)
+
+
+def test_replace_listlike_inplace(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]})
+ arr = get_array(df, "a")
+ df.replace([200, 2], [10, 11], inplace=True)
+ assert np.shares_memory(get_array(df, "a"), arr)
+
+ view = df[:]
+ df_orig = df.copy()
+ df.replace([200, 3], [10, 11], inplace=True)
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), arr)
+ tm.assert_frame_equal(view, df_orig)
+ else:
+ assert np.shares_memory(get_array(df, "a"), arr)
+ tm.assert_frame_equal(df, view)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_setitem.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_setitem.py
new file mode 100644
index 0000000000000000000000000000000000000000..5016b57bdd0b7fe25c1c6602bfbf91228a5c12d3
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_setitem.py
@@ -0,0 +1,142 @@
+import numpy as np
+
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ RangeIndex,
+ Series,
+)
+import pandas._testing as tm
+from pandas.tests.copy_view.util import get_array
+
+# -----------------------------------------------------------------------------
+# Copy/view behaviour for the values that are set in a DataFrame
+
+
+def test_set_column_with_array():
+ # Case: setting an array as a new column (df[col] = arr) copies that data
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ arr = np.array([1, 2, 3], dtype="int64")
+
+ df["c"] = arr
+
+ # the array data is copied
+ assert not np.shares_memory(get_array(df, "c"), arr)
+ # and thus modifying the array does not modify the DataFrame
+ arr[0] = 0
+ tm.assert_series_equal(df["c"], Series([1, 2, 3], name="c"))
+
+
+def test_set_column_with_series(using_copy_on_write):
+ # Case: setting a series as a new column (df[col] = s) copies that data
+ # (with delayed copy with CoW)
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ ser = Series([1, 2, 3])
+
+ df["c"] = ser
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "c"), get_array(ser))
+ else:
+ # the series data is copied
+ assert not np.shares_memory(get_array(df, "c"), get_array(ser))
+
+ # and modifying the series does not modify the DataFrame
+ ser.iloc[0] = 0
+ assert ser.iloc[0] == 0
+ tm.assert_series_equal(df["c"], Series([1, 2, 3], name="c"))
+
+
+def test_set_column_with_index(using_copy_on_write):
+ # Case: setting an index as a new column (df[col] = idx) copies that data
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ idx = Index([1, 2, 3])
+
+ df["c"] = idx
+
+ # the index data is copied
+ assert not np.shares_memory(get_array(df, "c"), idx.values)
+
+ idx = RangeIndex(1, 4)
+ arr = idx.values
+
+ df["d"] = idx
+
+ assert not np.shares_memory(get_array(df, "d"), arr)
+
+
+def test_set_columns_with_dataframe(using_copy_on_write):
+ # Case: setting a DataFrame as new columns copies that data
+ # (with delayed copy with CoW)
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df2 = DataFrame({"c": [7, 8, 9], "d": [10, 11, 12]})
+
+ df[["c", "d"]] = df2
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ else:
+ # the data is copied
+ assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+
+ # and modifying the set DataFrame does not modify the original DataFrame
+ df2.iloc[0, 0] = 0
+ tm.assert_series_equal(df["c"], Series([7, 8, 9], name="c"))
+
+
+def test_setitem_series_no_copy(using_copy_on_write):
+ # Case: setting a Series as column into a DataFrame can delay copying that data
+ df = DataFrame({"a": [1, 2, 3]})
+ rhs = Series([4, 5, 6])
+ rhs_orig = rhs.copy()
+
+ # adding a new column
+ df["b"] = rhs
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(rhs), get_array(df, "b"))
+
+ df.iloc[0, 1] = 100
+ tm.assert_series_equal(rhs, rhs_orig)
+
+
+def test_setitem_series_no_copy_single_block(using_copy_on_write):
+ # Overwriting an existing column that is a single block
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
+ rhs = Series([4, 5, 6])
+ rhs_orig = rhs.copy()
+
+ df["a"] = rhs
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(rhs), get_array(df, "a"))
+
+ df.iloc[0, 0] = 100
+ tm.assert_series_equal(rhs, rhs_orig)
+
+
+def test_setitem_series_no_copy_split_block(using_copy_on_write):
+ # Overwriting an existing column that is part of a larger block
+ df = DataFrame({"a": [1, 2, 3], "b": 1})
+ rhs = Series([4, 5, 6])
+ rhs_orig = rhs.copy()
+
+ df["b"] = rhs
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(rhs), get_array(df, "b"))
+
+ df.iloc[0, 1] = 100
+ tm.assert_series_equal(rhs, rhs_orig)
+
+
+def test_setitem_series_column_midx_broadcasting(using_copy_on_write):
+ # Setting a Series to multiple columns will repeat the data
+ # (currently copying the data eagerly)
+ df = DataFrame(
+ [[1, 2, 3], [3, 4, 5]],
+ columns=MultiIndex.from_arrays([["a", "a", "b"], [1, 2, 3]]),
+ )
+ rhs = Series([10, 11])
+ df["a"] = rhs
+ assert not np.shares_memory(get_array(rhs), df._get_column_array(0))
+ if using_copy_on_write:
+ assert df._mgr._has_no_reference(0)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_util.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff55330d70b28c5459a4c0915dd93c8640a91add
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/test_util.py
@@ -0,0 +1,14 @@
+import numpy as np
+
+from pandas import DataFrame
+from pandas.tests.copy_view.util import get_array
+
+
+def test_get_array_numpy():
+ df = DataFrame({"a": [1, 2, 3]})
+ assert np.shares_memory(get_array(df, "a"), get_array(df, "a"))
+
+
+def test_get_array_masked():
+ df = DataFrame({"a": [1, 2, 3]}, dtype="Int64")
+ assert np.shares_memory(get_array(df, "a"), get_array(df, "a"))
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/util.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..969334424936559767b0bca87093acfec52f9763
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/util.py
@@ -0,0 +1,30 @@
+from pandas import (
+ Categorical,
+ Index,
+ Series,
+)
+from pandas.core.arrays import BaseMaskedArray
+
+
+def get_array(obj, col=None):
+ """
+ Helper method to get array for a DataFrame column or a Series.
+
+ Equivalent of df[col].values, but without going through normal getitem,
+ which triggers tracking references / CoW (and we might be testing that
+ this is done by some other operation).
+ """
+ if isinstance(obj, Index):
+ arr = obj._values
+ elif isinstance(obj, Series) and (col is None or obj.name == col):
+ arr = obj._values
+ else:
+ assert col is not None
+ icol = obj.columns.get_loc(col)
+ assert isinstance(icol, int)
+ arr = obj._get_column_array(icol)
+ if isinstance(arr, BaseMaskedArray):
+ return arr._data
+ elif isinstance(arr, Categorical):
+ return arr
+ return getattr(arr, "_ndarray", arr)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/test_common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/test_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..165bf61302145d2cb50fca4493d4fd16b4c9acf6
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/test_common.py
@@ -0,0 +1,790 @@
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+from pandas.core.dtypes.astype import astype_array
+import pandas.core.dtypes.common as com
+from pandas.core.dtypes.dtypes import (
+ CategoricalDtype,
+ CategoricalDtypeType,
+ DatetimeTZDtype,
+ ExtensionDtype,
+ IntervalDtype,
+ PeriodDtype,
+)
+from pandas.core.dtypes.missing import isna
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.api.types import pandas_dtype
+from pandas.arrays import SparseArray
+
+
+# EA & Actual Dtypes
+def to_ea_dtypes(dtypes):
+ """convert list of string dtypes to EA dtype"""
+ return [getattr(pd, dt + "Dtype") for dt in dtypes]
+
+
+def to_numpy_dtypes(dtypes):
+ """convert list of string dtypes to numpy dtype"""
+ return [getattr(np, dt) for dt in dtypes if isinstance(dt, str)]
+
+
+class TestNumpyEADtype:
+ # Passing invalid dtype, both as a string or object, must raise TypeError
+ # Per issue GH15520
+ @pytest.mark.parametrize("box", [pd.Timestamp, "pd.Timestamp", list])
+ def test_invalid_dtype_error(self, box):
+ with pytest.raises(TypeError, match="not understood"):
+ com.pandas_dtype(box)
+
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ object,
+ "float64",
+ np.object_,
+ np.dtype("object"),
+ "O",
+ np.float64,
+ float,
+ np.dtype("float64"),
+ "object_",
+ ],
+ )
+ def test_pandas_dtype_valid(self, dtype):
+ assert com.pandas_dtype(dtype) == dtype
+
+ @pytest.mark.parametrize(
+ "dtype", ["M8[ns]", "m8[ns]", "object", "float64", "int64"]
+ )
+ def test_numpy_dtype(self, dtype):
+ assert com.pandas_dtype(dtype) == np.dtype(dtype)
+
+ def test_numpy_string_dtype(self):
+ # do not parse freq-like string as period dtype
+ assert com.pandas_dtype("U") == np.dtype("U")
+ assert com.pandas_dtype("S") == np.dtype("S")
+
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "datetime64[ns, US/Eastern]",
+ "datetime64[ns, Asia/Tokyo]",
+ "datetime64[ns, UTC]",
+ # GH#33885 check that the M8 alias is understood
+ "M8[ns, US/Eastern]",
+ "M8[ns, Asia/Tokyo]",
+ "M8[ns, UTC]",
+ ],
+ )
+ def test_datetimetz_dtype(self, dtype):
+ assert com.pandas_dtype(dtype) == DatetimeTZDtype.construct_from_string(dtype)
+ assert com.pandas_dtype(dtype) == dtype
+
+ def test_categorical_dtype(self):
+ assert com.pandas_dtype("category") == CategoricalDtype()
+
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "period[D]",
+ "period[3M]",
+ "period[U]",
+ "Period[D]",
+ "Period[3M]",
+ "Period[U]",
+ ],
+ )
+ def test_period_dtype(self, dtype):
+ assert com.pandas_dtype(dtype) is not PeriodDtype(dtype)
+ assert com.pandas_dtype(dtype) == PeriodDtype(dtype)
+ assert com.pandas_dtype(dtype) == dtype
+
+
+dtypes = {
+ "datetime_tz": com.pandas_dtype("datetime64[ns, US/Eastern]"),
+ "datetime": com.pandas_dtype("datetime64[ns]"),
+ "timedelta": com.pandas_dtype("timedelta64[ns]"),
+ "period": PeriodDtype("D"),
+ "integer": np.dtype(np.int64),
+ "float": np.dtype(np.float64),
+ "object": np.dtype(object),
+ "category": com.pandas_dtype("category"),
+ "string": pd.StringDtype(),
+}
+
+
+@pytest.mark.parametrize("name1,dtype1", list(dtypes.items()), ids=lambda x: str(x))
+@pytest.mark.parametrize("name2,dtype2", list(dtypes.items()), ids=lambda x: str(x))
+def test_dtype_equal(name1, dtype1, name2, dtype2):
+ # match equal to self, but not equal to other
+ assert com.is_dtype_equal(dtype1, dtype1)
+ if name1 != name2:
+ assert not com.is_dtype_equal(dtype1, dtype2)
+
+
+@pytest.mark.parametrize("name,dtype", list(dtypes.items()), ids=lambda x: str(x))
+def test_pyarrow_string_import_error(name, dtype):
+ # GH-44276
+ assert not com.is_dtype_equal(dtype, "string[pyarrow]")
+
+
+@pytest.mark.parametrize(
+ "dtype1,dtype2",
+ [
+ (np.int8, np.int64),
+ (np.int16, np.int64),
+ (np.int32, np.int64),
+ (np.float32, np.float64),
+ (PeriodDtype("D"), PeriodDtype("2D")), # PeriodType
+ (
+ com.pandas_dtype("datetime64[ns, US/Eastern]"),
+ com.pandas_dtype("datetime64[ns, CET]"),
+ ), # Datetime
+ (None, None), # gh-15941: no exception should be raised.
+ ],
+)
+def test_dtype_equal_strict(dtype1, dtype2):
+ assert not com.is_dtype_equal(dtype1, dtype2)
+
+
+def get_is_dtype_funcs():
+ """
+ Get all functions in pandas.core.dtypes.common that
+ begin with 'is_' and end with 'dtype'
+
+ """
+ fnames = [f for f in dir(com) if (f.startswith("is_") and f.endswith("dtype"))]
+ fnames.remove("is_string_or_object_np_dtype") # fastpath requires np.dtype obj
+ return [getattr(com, fname) for fname in fnames]
+
+
+@pytest.mark.filterwarnings("ignore:is_categorical_dtype is deprecated:FutureWarning")
+@pytest.mark.parametrize("func", get_is_dtype_funcs(), ids=lambda x: x.__name__)
+def test_get_dtype_error_catch(func):
+ # see gh-15941
+ #
+ # No exception should be raised.
+
+ msg = f"{func.__name__} is deprecated"
+ warn = None
+ if (
+ func is com.is_int64_dtype
+ or func is com.is_interval_dtype
+ or func is com.is_datetime64tz_dtype
+ or func is com.is_categorical_dtype
+ or func is com.is_period_dtype
+ ):
+ warn = FutureWarning
+
+ with tm.assert_produces_warning(warn, match=msg):
+ assert not func(None)
+
+
+def test_is_object():
+ assert com.is_object_dtype(object)
+ assert com.is_object_dtype(np.array([], dtype=object))
+
+ assert not com.is_object_dtype(int)
+ assert not com.is_object_dtype(np.array([], dtype=int))
+ assert not com.is_object_dtype([1, 2, 3])
+
+
+@pytest.mark.parametrize(
+ "check_scipy", [False, pytest.param(True, marks=td.skip_if_no_scipy)]
+)
+def test_is_sparse(check_scipy):
+ msg = "is_sparse is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert com.is_sparse(SparseArray([1, 2, 3]))
+
+ assert not com.is_sparse(np.array([1, 2, 3]))
+
+ if check_scipy:
+ import scipy.sparse
+
+ assert not com.is_sparse(scipy.sparse.bsr_matrix([1, 2, 3]))
+
+
+def test_is_scipy_sparse():
+ sp_sparse = pytest.importorskip("scipy.sparse")
+
+ assert com.is_scipy_sparse(sp_sparse.bsr_matrix([1, 2, 3]))
+
+ assert not com.is_scipy_sparse(SparseArray([1, 2, 3]))
+
+
+def test_is_datetime64_dtype():
+ assert not com.is_datetime64_dtype(object)
+ assert not com.is_datetime64_dtype([1, 2, 3])
+ assert not com.is_datetime64_dtype(np.array([], dtype=int))
+
+ assert com.is_datetime64_dtype(np.datetime64)
+ assert com.is_datetime64_dtype(np.array([], dtype=np.datetime64))
+
+
+def test_is_datetime64tz_dtype():
+ msg = "is_datetime64tz_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert not com.is_datetime64tz_dtype(object)
+ assert not com.is_datetime64tz_dtype([1, 2, 3])
+ assert not com.is_datetime64tz_dtype(pd.DatetimeIndex([1, 2, 3]))
+ assert com.is_datetime64tz_dtype(pd.DatetimeIndex(["2000"], tz="US/Eastern"))
+
+
+def test_custom_ea_kind_M_not_datetime64tz():
+ # GH 34986
+ class NotTZDtype(ExtensionDtype):
+ @property
+ def kind(self) -> str:
+ return "M"
+
+ not_tz_dtype = NotTZDtype()
+ msg = "is_datetime64tz_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert not com.is_datetime64tz_dtype(not_tz_dtype)
+ assert not com.needs_i8_conversion(not_tz_dtype)
+
+
+def test_is_timedelta64_dtype():
+ assert not com.is_timedelta64_dtype(object)
+ assert not com.is_timedelta64_dtype(None)
+ assert not com.is_timedelta64_dtype([1, 2, 3])
+ assert not com.is_timedelta64_dtype(np.array([], dtype=np.datetime64))
+ assert not com.is_timedelta64_dtype("0 days")
+ assert not com.is_timedelta64_dtype("0 days 00:00:00")
+ assert not com.is_timedelta64_dtype(["0 days 00:00:00"])
+ assert not com.is_timedelta64_dtype("NO DATE")
+
+ assert com.is_timedelta64_dtype(np.timedelta64)
+ assert com.is_timedelta64_dtype(pd.Series([], dtype="timedelta64[ns]"))
+ assert com.is_timedelta64_dtype(pd.to_timedelta(["0 days", "1 days"]))
+
+
+def test_is_period_dtype():
+ msg = "is_period_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert not com.is_period_dtype(object)
+ assert not com.is_period_dtype([1, 2, 3])
+ assert not com.is_period_dtype(pd.Period("2017-01-01"))
+
+ assert com.is_period_dtype(PeriodDtype(freq="D"))
+ assert com.is_period_dtype(pd.PeriodIndex([], freq="A"))
+
+
+def test_is_interval_dtype():
+ msg = "is_interval_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert not com.is_interval_dtype(object)
+ assert not com.is_interval_dtype([1, 2, 3])
+
+ assert com.is_interval_dtype(IntervalDtype())
+
+ interval = pd.Interval(1, 2, closed="right")
+ assert not com.is_interval_dtype(interval)
+ assert com.is_interval_dtype(pd.IntervalIndex([interval]))
+
+
+def test_is_categorical_dtype():
+ msg = "is_categorical_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert not com.is_categorical_dtype(object)
+ assert not com.is_categorical_dtype([1, 2, 3])
+
+ assert com.is_categorical_dtype(CategoricalDtype())
+ assert com.is_categorical_dtype(pd.Categorical([1, 2, 3]))
+ assert com.is_categorical_dtype(pd.CategoricalIndex([1, 2, 3]))
+
+
+def test_is_string_dtype():
+ assert not com.is_string_dtype(int)
+ assert not com.is_string_dtype(pd.Series([1, 2]))
+
+ assert com.is_string_dtype(str)
+ assert com.is_string_dtype(object)
+ assert com.is_string_dtype(np.array(["a", "b"]))
+ assert com.is_string_dtype(pd.StringDtype())
+
+
+@pytest.mark.parametrize(
+ "data",
+ [[(0, 1), (1, 1)], pd.Categorical([1, 2, 3]), np.array([1, 2], dtype=object)],
+)
+def test_is_string_dtype_arraylike_with_object_elements_not_strings(data):
+ # GH 15585
+ assert not com.is_string_dtype(pd.Series(data))
+
+
+def test_is_string_dtype_nullable(nullable_string_dtype):
+ assert com.is_string_dtype(pd.array(["a", "b"], dtype=nullable_string_dtype))
+
+
+integer_dtypes: list = []
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ integer_dtypes
+ + [pd.Series([1, 2])]
+ + tm.ALL_INT_NUMPY_DTYPES
+ + to_numpy_dtypes(tm.ALL_INT_NUMPY_DTYPES)
+ + tm.ALL_INT_EA_DTYPES
+ + to_ea_dtypes(tm.ALL_INT_EA_DTYPES),
+)
+def test_is_integer_dtype(dtype):
+ assert com.is_integer_dtype(dtype)
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ str,
+ float,
+ np.datetime64,
+ np.timedelta64,
+ pd.Index([1, 2.0]),
+ np.array(["a", "b"]),
+ np.array([], dtype=np.timedelta64),
+ ],
+)
+def test_is_not_integer_dtype(dtype):
+ assert not com.is_integer_dtype(dtype)
+
+
+signed_integer_dtypes: list = []
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ signed_integer_dtypes
+ + [pd.Series([1, 2])]
+ + tm.SIGNED_INT_NUMPY_DTYPES
+ + to_numpy_dtypes(tm.SIGNED_INT_NUMPY_DTYPES)
+ + tm.SIGNED_INT_EA_DTYPES
+ + to_ea_dtypes(tm.SIGNED_INT_EA_DTYPES),
+)
+def test_is_signed_integer_dtype(dtype):
+ assert com.is_integer_dtype(dtype)
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ str,
+ float,
+ np.datetime64,
+ np.timedelta64,
+ pd.Index([1, 2.0]),
+ np.array(["a", "b"]),
+ np.array([], dtype=np.timedelta64),
+ ]
+ + tm.UNSIGNED_INT_NUMPY_DTYPES
+ + to_numpy_dtypes(tm.UNSIGNED_INT_NUMPY_DTYPES)
+ + tm.UNSIGNED_INT_EA_DTYPES
+ + to_ea_dtypes(tm.UNSIGNED_INT_EA_DTYPES),
+)
+def test_is_not_signed_integer_dtype(dtype):
+ assert not com.is_signed_integer_dtype(dtype)
+
+
+unsigned_integer_dtypes: list = []
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ unsigned_integer_dtypes
+ + [pd.Series([1, 2], dtype=np.uint32)]
+ + tm.UNSIGNED_INT_NUMPY_DTYPES
+ + to_numpy_dtypes(tm.UNSIGNED_INT_NUMPY_DTYPES)
+ + tm.UNSIGNED_INT_EA_DTYPES
+ + to_ea_dtypes(tm.UNSIGNED_INT_EA_DTYPES),
+)
+def test_is_unsigned_integer_dtype(dtype):
+ assert com.is_unsigned_integer_dtype(dtype)
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ str,
+ float,
+ np.datetime64,
+ np.timedelta64,
+ pd.Index([1, 2.0]),
+ np.array(["a", "b"]),
+ np.array([], dtype=np.timedelta64),
+ ]
+ + tm.SIGNED_INT_NUMPY_DTYPES
+ + to_numpy_dtypes(tm.SIGNED_INT_NUMPY_DTYPES)
+ + tm.SIGNED_INT_EA_DTYPES
+ + to_ea_dtypes(tm.SIGNED_INT_EA_DTYPES),
+)
+def test_is_not_unsigned_integer_dtype(dtype):
+ assert not com.is_unsigned_integer_dtype(dtype)
+
+
+@pytest.mark.parametrize(
+ "dtype", [np.int64, np.array([1, 2], dtype=np.int64), "Int64", pd.Int64Dtype]
+)
+def test_is_int64_dtype(dtype):
+ msg = "is_int64_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert com.is_int64_dtype(dtype)
+
+
+def test_type_comparison_with_numeric_ea_dtype(any_numeric_ea_dtype):
+ # GH#43038
+ assert pandas_dtype(any_numeric_ea_dtype) == any_numeric_ea_dtype
+
+
+def test_type_comparison_with_real_numpy_dtype(any_real_numpy_dtype):
+ # GH#43038
+ assert pandas_dtype(any_real_numpy_dtype) == any_real_numpy_dtype
+
+
+def test_type_comparison_with_signed_int_ea_dtype_and_signed_int_numpy_dtype(
+ any_signed_int_ea_dtype, any_signed_int_numpy_dtype
+):
+ # GH#43038
+ assert not pandas_dtype(any_signed_int_ea_dtype) == any_signed_int_numpy_dtype
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ str,
+ float,
+ np.int32,
+ np.uint64,
+ pd.Index([1, 2.0]),
+ np.array(["a", "b"]),
+ np.array([1, 2], dtype=np.uint32),
+ "int8",
+ "Int8",
+ pd.Int8Dtype,
+ ],
+)
+def test_is_not_int64_dtype(dtype):
+ msg = "is_int64_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert not com.is_int64_dtype(dtype)
+
+
+def test_is_datetime64_any_dtype():
+ assert not com.is_datetime64_any_dtype(int)
+ assert not com.is_datetime64_any_dtype(str)
+ assert not com.is_datetime64_any_dtype(np.array([1, 2]))
+ assert not com.is_datetime64_any_dtype(np.array(["a", "b"]))
+
+ assert com.is_datetime64_any_dtype(np.datetime64)
+ assert com.is_datetime64_any_dtype(np.array([], dtype=np.datetime64))
+ assert com.is_datetime64_any_dtype(DatetimeTZDtype("ns", "US/Eastern"))
+ assert com.is_datetime64_any_dtype(
+ pd.DatetimeIndex([1, 2, 3], dtype="datetime64[ns]")
+ )
+
+
+def test_is_datetime64_ns_dtype():
+ assert not com.is_datetime64_ns_dtype(int)
+ assert not com.is_datetime64_ns_dtype(str)
+ assert not com.is_datetime64_ns_dtype(np.datetime64)
+ assert not com.is_datetime64_ns_dtype(np.array([1, 2]))
+ assert not com.is_datetime64_ns_dtype(np.array(["a", "b"]))
+ assert not com.is_datetime64_ns_dtype(np.array([], dtype=np.datetime64))
+
+ # This datetime array has the wrong unit (ps instead of ns)
+ assert not com.is_datetime64_ns_dtype(np.array([], dtype="datetime64[ps]"))
+
+ assert com.is_datetime64_ns_dtype(DatetimeTZDtype("ns", "US/Eastern"))
+ assert com.is_datetime64_ns_dtype(
+ pd.DatetimeIndex([1, 2, 3], dtype=np.dtype("datetime64[ns]"))
+ )
+
+ # non-nano dt64tz
+ assert not com.is_datetime64_ns_dtype(DatetimeTZDtype("us", "US/Eastern"))
+
+
+def test_is_timedelta64_ns_dtype():
+ assert not com.is_timedelta64_ns_dtype(np.dtype("m8[ps]"))
+ assert not com.is_timedelta64_ns_dtype(np.array([1, 2], dtype=np.timedelta64))
+
+ assert com.is_timedelta64_ns_dtype(np.dtype("m8[ns]"))
+ assert com.is_timedelta64_ns_dtype(np.array([1, 2], dtype="m8[ns]"))
+
+
+def test_is_numeric_v_string_like():
+ assert not com.is_numeric_v_string_like(np.array([1]), 1)
+ assert not com.is_numeric_v_string_like(np.array([1]), np.array([2]))
+ assert not com.is_numeric_v_string_like(np.array(["foo"]), np.array(["foo"]))
+
+ assert com.is_numeric_v_string_like(np.array([1]), "foo")
+ assert com.is_numeric_v_string_like(np.array([1, 2]), np.array(["foo"]))
+ assert com.is_numeric_v_string_like(np.array(["foo"]), np.array([1, 2]))
+
+
+def test_needs_i8_conversion():
+ assert not com.needs_i8_conversion(str)
+ assert not com.needs_i8_conversion(np.int64)
+ assert not com.needs_i8_conversion(pd.Series([1, 2]))
+ assert not com.needs_i8_conversion(np.array(["a", "b"]))
+
+ assert not com.needs_i8_conversion(np.datetime64)
+ assert com.needs_i8_conversion(np.dtype(np.datetime64))
+ assert not com.needs_i8_conversion(pd.Series([], dtype="timedelta64[ns]"))
+ assert com.needs_i8_conversion(pd.Series([], dtype="timedelta64[ns]").dtype)
+ assert not com.needs_i8_conversion(pd.DatetimeIndex(["2000"], tz="US/Eastern"))
+ assert com.needs_i8_conversion(pd.DatetimeIndex(["2000"], tz="US/Eastern").dtype)
+
+
+def test_is_numeric_dtype():
+ assert not com.is_numeric_dtype(str)
+ assert not com.is_numeric_dtype(np.datetime64)
+ assert not com.is_numeric_dtype(np.timedelta64)
+ assert not com.is_numeric_dtype(np.array(["a", "b"]))
+ assert not com.is_numeric_dtype(np.array([], dtype=np.timedelta64))
+
+ assert com.is_numeric_dtype(int)
+ assert com.is_numeric_dtype(float)
+ assert com.is_numeric_dtype(np.uint64)
+ assert com.is_numeric_dtype(pd.Series([1, 2]))
+ assert com.is_numeric_dtype(pd.Index([1, 2.0]))
+
+ class MyNumericDType(ExtensionDtype):
+ @property
+ def type(self):
+ return str
+
+ @property
+ def name(self):
+ raise NotImplementedError
+
+ @classmethod
+ def construct_array_type(cls):
+ raise NotImplementedError
+
+ def _is_numeric(self) -> bool:
+ return True
+
+ assert com.is_numeric_dtype(MyNumericDType())
+
+
+def test_is_any_real_numeric_dtype():
+ assert not com.is_any_real_numeric_dtype(str)
+ assert not com.is_any_real_numeric_dtype(bool)
+ assert not com.is_any_real_numeric_dtype(complex)
+ assert not com.is_any_real_numeric_dtype(object)
+ assert not com.is_any_real_numeric_dtype(np.datetime64)
+ assert not com.is_any_real_numeric_dtype(np.array(["a", "b", complex(1, 2)]))
+ assert not com.is_any_real_numeric_dtype(pd.DataFrame([complex(1, 2), True]))
+
+ assert com.is_any_real_numeric_dtype(int)
+ assert com.is_any_real_numeric_dtype(float)
+ assert com.is_any_real_numeric_dtype(np.array([1, 2.5]))
+
+
+def test_is_float_dtype():
+ assert not com.is_float_dtype(str)
+ assert not com.is_float_dtype(int)
+ assert not com.is_float_dtype(pd.Series([1, 2]))
+ assert not com.is_float_dtype(np.array(["a", "b"]))
+
+ assert com.is_float_dtype(float)
+ assert com.is_float_dtype(pd.Index([1, 2.0]))
+
+
+def test_is_bool_dtype():
+ assert not com.is_bool_dtype(int)
+ assert not com.is_bool_dtype(str)
+ assert not com.is_bool_dtype(pd.Series([1, 2]))
+ assert not com.is_bool_dtype(pd.Series(["a", "b"], dtype="category"))
+ assert not com.is_bool_dtype(np.array(["a", "b"]))
+ assert not com.is_bool_dtype(pd.Index(["a", "b"]))
+ assert not com.is_bool_dtype("Int64")
+
+ assert com.is_bool_dtype(bool)
+ assert com.is_bool_dtype(np.bool_)
+ assert com.is_bool_dtype(pd.Series([True, False], dtype="category"))
+ assert com.is_bool_dtype(np.array([True, False]))
+ assert com.is_bool_dtype(pd.Index([True, False]))
+
+ assert com.is_bool_dtype(pd.BooleanDtype())
+ assert com.is_bool_dtype(pd.array([True, False, None], dtype="boolean"))
+ assert com.is_bool_dtype("boolean")
+
+
+def test_is_bool_dtype_numpy_error():
+ # GH39010
+ assert not com.is_bool_dtype("0 - Name")
+
+
+@pytest.mark.parametrize(
+ "check_scipy", [False, pytest.param(True, marks=td.skip_if_no_scipy)]
+)
+def test_is_extension_array_dtype(check_scipy):
+ assert not com.is_extension_array_dtype([1, 2, 3])
+ assert not com.is_extension_array_dtype(np.array([1, 2, 3]))
+ assert not com.is_extension_array_dtype(pd.DatetimeIndex([1, 2, 3]))
+
+ cat = pd.Categorical([1, 2, 3])
+ assert com.is_extension_array_dtype(cat)
+ assert com.is_extension_array_dtype(pd.Series(cat))
+ assert com.is_extension_array_dtype(SparseArray([1, 2, 3]))
+ assert com.is_extension_array_dtype(pd.DatetimeIndex(["2000"], tz="US/Eastern"))
+
+ dtype = DatetimeTZDtype("ns", tz="US/Eastern")
+ s = pd.Series([], dtype=dtype)
+ assert com.is_extension_array_dtype(s)
+
+ if check_scipy:
+ import scipy.sparse
+
+ assert not com.is_extension_array_dtype(scipy.sparse.bsr_matrix([1, 2, 3]))
+
+
+def test_is_complex_dtype():
+ assert not com.is_complex_dtype(int)
+ assert not com.is_complex_dtype(str)
+ assert not com.is_complex_dtype(pd.Series([1, 2]))
+ assert not com.is_complex_dtype(np.array(["a", "b"]))
+
+ assert com.is_complex_dtype(np.complex128)
+ assert com.is_complex_dtype(complex)
+ assert com.is_complex_dtype(np.array([1 + 1j, 5]))
+
+
+@pytest.mark.parametrize(
+ "input_param,result",
+ [
+ (int, np.dtype(int)),
+ ("int32", np.dtype("int32")),
+ (float, np.dtype(float)),
+ ("float64", np.dtype("float64")),
+ (np.dtype("float64"), np.dtype("float64")),
+ (str, np.dtype(str)),
+ (pd.Series([1, 2], dtype=np.dtype("int16")), np.dtype("int16")),
+ (pd.Series(["a", "b"]), np.dtype(object)),
+ (pd.Index([1, 2]), np.dtype("int64")),
+ (pd.Index(["a", "b"]), np.dtype(object)),
+ ("category", "category"),
+ (pd.Categorical(["a", "b"]).dtype, CategoricalDtype(["a", "b"])),
+ (pd.Categorical(["a", "b"]), CategoricalDtype(["a", "b"])),
+ (pd.CategoricalIndex(["a", "b"]).dtype, CategoricalDtype(["a", "b"])),
+ (pd.CategoricalIndex(["a", "b"]), CategoricalDtype(["a", "b"])),
+ (CategoricalDtype(), CategoricalDtype()),
+ (pd.DatetimeIndex([1, 2]), np.dtype("=M8[ns]")),
+ (pd.DatetimeIndex([1, 2]).dtype, np.dtype("=M8[ns]")),
+ (" df.two.sum()
+
+ with tm.assert_produces_warning(None):
+ # successfully modify column in place
+ # this should not raise a warning
+ df.one += 1
+ assert df.one.iloc[0] == 2
+
+ with tm.assert_produces_warning(None):
+ # successfully add an attribute to a series
+ # this should not raise a warning
+ df.two.not_an_index = [1, 2]
+
+ with tm.assert_produces_warning(UserWarning):
+ # warn when setting column to nonexistent name
+ df.four = df.two + 2
+ assert df.four.sum() > df.two.sum()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/test_inference.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/test_inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..df7c787d2b9bf49d71ed87a522bdea91d5812b97
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/test_inference.py
@@ -0,0 +1,1985 @@
+"""
+These the test the public routines exposed in types/common.py
+related to inference and not otherwise tested in types/test_common.py
+
+"""
+import collections
+from collections import namedtuple
+from collections.abc import Iterator
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
+from decimal import Decimal
+from fractions import Fraction
+from io import StringIO
+import itertools
+from numbers import Number
+import re
+import sys
+from typing import (
+ Generic,
+ TypeVar,
+)
+
+import numpy as np
+import pytest
+import pytz
+
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+ ops as libops,
+)
+
+from pandas.core.dtypes import inference
+from pandas.core.dtypes.common import (
+ ensure_int32,
+ is_bool,
+ is_complex,
+ is_datetime64_any_dtype,
+ is_datetime64_dtype,
+ is_datetime64_ns_dtype,
+ is_datetime64tz_dtype,
+ is_float,
+ is_integer,
+ is_number,
+ is_scalar,
+ is_scipy_sparse,
+ is_timedelta64_dtype,
+ is_timedelta64_ns_dtype,
+)
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DataFrame,
+ DateOffset,
+ DatetimeIndex,
+ Index,
+ Interval,
+ Period,
+ PeriodIndex,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ Timestamp,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ BooleanArray,
+ FloatingArray,
+ IntegerArray,
+)
+
+
+@pytest.fixture(params=[True, False], ids=str)
+def coerce(request):
+ return request.param
+
+
+class MockNumpyLikeArray:
+ """
+ A class which is numpy-like (e.g. Pint's Quantity) but not actually numpy
+
+ The key is that it is not actually a numpy array so
+ ``util.is_array(mock_numpy_like_array_instance)`` returns ``False``. Other
+ important properties are that the class defines a :meth:`__iter__` method
+ (so that ``isinstance(abc.Iterable)`` returns ``True``) and has a
+ :meth:`ndim` property, as pandas special-cases 0-dimensional arrays in some
+ cases.
+
+ We expect pandas to behave with respect to such duck arrays exactly as
+ with real numpy arrays. In particular, a 0-dimensional duck array is *NOT*
+ a scalar (`is_scalar(np.array(1)) == False`), but it is not list-like either.
+ """
+
+ def __init__(self, values) -> None:
+ self._values = values
+
+ def __iter__(self) -> Iterator:
+ iter_values = iter(self._values)
+
+ def it_outer():
+ yield from iter_values
+
+ return it_outer()
+
+ def __len__(self) -> int:
+ return len(self._values)
+
+ def __array__(self, t=None):
+ return np.asarray(self._values, dtype=t)
+
+ @property
+ def ndim(self):
+ return self._values.ndim
+
+ @property
+ def dtype(self):
+ return self._values.dtype
+
+ @property
+ def size(self):
+ return self._values.size
+
+ @property
+ def shape(self):
+ return self._values.shape
+
+
+# collect all objects to be tested for list-like-ness; use tuples of objects,
+# whether they are list-like or not (special casing for sets), and their ID
+ll_params = [
+ ([1], True, "list"),
+ ([], True, "list-empty"),
+ ((1,), True, "tuple"),
+ ((), True, "tuple-empty"),
+ ({"a": 1}, True, "dict"),
+ ({}, True, "dict-empty"),
+ ({"a", 1}, "set", "set"),
+ (set(), "set", "set-empty"),
+ (frozenset({"a", 1}), "set", "frozenset"),
+ (frozenset(), "set", "frozenset-empty"),
+ (iter([1, 2]), True, "iterator"),
+ (iter([]), True, "iterator-empty"),
+ ((x for x in [1, 2]), True, "generator"),
+ ((_ for _ in []), True, "generator-empty"),
+ (Series([1]), True, "Series"),
+ (Series([], dtype=object), True, "Series-empty"),
+ # Series.str will still raise a TypeError if iterated
+ (Series(["a"]).str, True, "StringMethods"),
+ (Series([], dtype="O").str, True, "StringMethods-empty"),
+ (Index([1]), True, "Index"),
+ (Index([]), True, "Index-empty"),
+ (DataFrame([[1]]), True, "DataFrame"),
+ (DataFrame(), True, "DataFrame-empty"),
+ (np.ndarray((2,) * 1), True, "ndarray-1d"),
+ (np.array([]), True, "ndarray-1d-empty"),
+ (np.ndarray((2,) * 2), True, "ndarray-2d"),
+ (np.array([[]]), True, "ndarray-2d-empty"),
+ (np.ndarray((2,) * 3), True, "ndarray-3d"),
+ (np.array([[[]]]), True, "ndarray-3d-empty"),
+ (np.ndarray((2,) * 4), True, "ndarray-4d"),
+ (np.array([[[[]]]]), True, "ndarray-4d-empty"),
+ (np.array(2), False, "ndarray-0d"),
+ (MockNumpyLikeArray(np.ndarray((2,) * 1)), True, "duck-ndarray-1d"),
+ (MockNumpyLikeArray(np.array([])), True, "duck-ndarray-1d-empty"),
+ (MockNumpyLikeArray(np.ndarray((2,) * 2)), True, "duck-ndarray-2d"),
+ (MockNumpyLikeArray(np.array([[]])), True, "duck-ndarray-2d-empty"),
+ (MockNumpyLikeArray(np.ndarray((2,) * 3)), True, "duck-ndarray-3d"),
+ (MockNumpyLikeArray(np.array([[[]]])), True, "duck-ndarray-3d-empty"),
+ (MockNumpyLikeArray(np.ndarray((2,) * 4)), True, "duck-ndarray-4d"),
+ (MockNumpyLikeArray(np.array([[[[]]]])), True, "duck-ndarray-4d-empty"),
+ (MockNumpyLikeArray(np.array(2)), False, "duck-ndarray-0d"),
+ (1, False, "int"),
+ (b"123", False, "bytes"),
+ (b"", False, "bytes-empty"),
+ ("123", False, "string"),
+ ("", False, "string-empty"),
+ (str, False, "string-type"),
+ (object(), False, "object"),
+ (np.nan, False, "NaN"),
+ (None, False, "None"),
+]
+objs, expected, ids = zip(*ll_params)
+
+
+@pytest.fixture(params=zip(objs, expected), ids=ids)
+def maybe_list_like(request):
+ return request.param
+
+
+def test_is_list_like(maybe_list_like):
+ obj, expected = maybe_list_like
+ expected = True if expected == "set" else expected
+ assert inference.is_list_like(obj) == expected
+
+
+def test_is_list_like_disallow_sets(maybe_list_like):
+ obj, expected = maybe_list_like
+ expected = False if expected == "set" else expected
+ assert inference.is_list_like(obj, allow_sets=False) == expected
+
+
+def test_is_list_like_recursion():
+ # GH 33721
+ # interpreter would crash with SIGABRT
+ def list_like():
+ inference.is_list_like([])
+ list_like()
+
+ rec_limit = sys.getrecursionlimit()
+ try:
+ # Limit to avoid stack overflow on Windows CI
+ sys.setrecursionlimit(100)
+ with tm.external_error_raised(RecursionError):
+ list_like()
+ finally:
+ sys.setrecursionlimit(rec_limit)
+
+
+def test_is_list_like_iter_is_none():
+ # GH 43373
+ # is_list_like was yielding false positives with __iter__ == None
+ class NotListLike:
+ def __getitem__(self, item):
+ return self
+
+ __iter__ = None
+
+ assert not inference.is_list_like(NotListLike())
+
+
+def test_is_list_like_generic():
+ # GH 49649
+ # is_list_like was yielding false positives for Generic classes in python 3.11
+ T = TypeVar("T")
+
+ class MyDataFrame(DataFrame, Generic[T]):
+ ...
+
+ tstc = MyDataFrame[int]
+ tst = MyDataFrame[int]({"x": [1, 2, 3]})
+
+ assert not inference.is_list_like(tstc)
+ assert isinstance(tst, DataFrame)
+ assert inference.is_list_like(tst)
+
+
+def test_is_sequence():
+ is_seq = inference.is_sequence
+ assert is_seq((1, 2))
+ assert is_seq([1, 2])
+ assert not is_seq("abcd")
+ assert not is_seq(np.int64)
+
+ class A:
+ def __getitem__(self, item):
+ return 1
+
+ assert not is_seq(A())
+
+
+def test_is_array_like():
+ assert inference.is_array_like(Series([], dtype=object))
+ assert inference.is_array_like(Series([1, 2]))
+ assert inference.is_array_like(np.array(["a", "b"]))
+ assert inference.is_array_like(Index(["2016-01-01"]))
+ assert inference.is_array_like(np.array([2, 3]))
+ assert inference.is_array_like(MockNumpyLikeArray(np.array([2, 3])))
+
+ class DtypeList(list):
+ dtype = "special"
+
+ assert inference.is_array_like(DtypeList())
+
+ assert not inference.is_array_like([1, 2, 3])
+ assert not inference.is_array_like(())
+ assert not inference.is_array_like("foo")
+ assert not inference.is_array_like(123)
+
+
+@pytest.mark.parametrize(
+ "inner",
+ [
+ [],
+ [1],
+ (1,),
+ (1, 2),
+ {"a": 1},
+ {1, "a"},
+ Series([1]),
+ Series([], dtype=object),
+ Series(["a"]).str,
+ (x for x in range(5)),
+ ],
+)
+@pytest.mark.parametrize("outer", [list, Series, np.array, tuple])
+def test_is_nested_list_like_passes(inner, outer):
+ result = outer([inner for _ in range(5)])
+ assert inference.is_list_like(result)
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ "abc",
+ [],
+ [1],
+ (1,),
+ ["a"],
+ "a",
+ {"a"},
+ [1, 2, 3],
+ Series([1]),
+ DataFrame({"A": [1]}),
+ ([1, 2] for _ in range(5)),
+ ],
+)
+def test_is_nested_list_like_fails(obj):
+ assert not inference.is_nested_list_like(obj)
+
+
+@pytest.mark.parametrize("ll", [{}, {"A": 1}, Series([1]), collections.defaultdict()])
+def test_is_dict_like_passes(ll):
+ assert inference.is_dict_like(ll)
+
+
+@pytest.mark.parametrize(
+ "ll",
+ [
+ "1",
+ 1,
+ [1, 2],
+ (1, 2),
+ range(2),
+ Index([1]),
+ dict,
+ collections.defaultdict,
+ Series,
+ ],
+)
+def test_is_dict_like_fails(ll):
+ assert not inference.is_dict_like(ll)
+
+
+@pytest.mark.parametrize("has_keys", [True, False])
+@pytest.mark.parametrize("has_getitem", [True, False])
+@pytest.mark.parametrize("has_contains", [True, False])
+def test_is_dict_like_duck_type(has_keys, has_getitem, has_contains):
+ class DictLike:
+ def __init__(self, d) -> None:
+ self.d = d
+
+ if has_keys:
+
+ def keys(self):
+ return self.d.keys()
+
+ if has_getitem:
+
+ def __getitem__(self, key):
+ return self.d.__getitem__(key)
+
+ if has_contains:
+
+ def __contains__(self, key) -> bool:
+ return self.d.__contains__(key)
+
+ d = DictLike({1: 2})
+ result = inference.is_dict_like(d)
+ expected = has_keys and has_getitem and has_contains
+
+ assert result is expected
+
+
+def test_is_file_like():
+ class MockFile:
+ pass
+
+ is_file = inference.is_file_like
+
+ data = StringIO("data")
+ assert is_file(data)
+
+ # No read / write attributes
+ # No iterator attributes
+ m = MockFile()
+ assert not is_file(m)
+
+ MockFile.write = lambda self: 0
+
+ # Write attribute but not an iterator
+ m = MockFile()
+ assert not is_file(m)
+
+ # gh-16530: Valid iterator just means we have the
+ # __iter__ attribute for our purposes.
+ MockFile.__iter__ = lambda self: self
+
+ # Valid write-only file
+ m = MockFile()
+ assert is_file(m)
+
+ del MockFile.write
+ MockFile.read = lambda self: 0
+
+ # Valid read-only file
+ m = MockFile()
+ assert is_file(m)
+
+ # Iterator but no read / write attributes
+ data = [1, 2, 3]
+ assert not is_file(data)
+
+
+test_tuple = collections.namedtuple("test_tuple", ["a", "b", "c"])
+
+
+@pytest.mark.parametrize("ll", [test_tuple(1, 2, 3)])
+def test_is_names_tuple_passes(ll):
+ assert inference.is_named_tuple(ll)
+
+
+@pytest.mark.parametrize("ll", [(1, 2, 3), "a", Series({"pi": 3.14})])
+def test_is_names_tuple_fails(ll):
+ assert not inference.is_named_tuple(ll)
+
+
+def test_is_hashable():
+ # all new-style classes are hashable by default
+ class HashableClass:
+ pass
+
+ class UnhashableClass1:
+ __hash__ = None
+
+ class UnhashableClass2:
+ def __hash__(self):
+ raise TypeError("Not hashable")
+
+ hashable = (1, 3.14, np.float64(3.14), "a", (), (1,), HashableClass())
+ not_hashable = ([], UnhashableClass1())
+ abc_hashable_not_really_hashable = (([],), UnhashableClass2())
+
+ for i in hashable:
+ assert inference.is_hashable(i)
+ for i in not_hashable:
+ assert not inference.is_hashable(i)
+ for i in abc_hashable_not_really_hashable:
+ assert not inference.is_hashable(i)
+
+ # numpy.array is no longer collections.abc.Hashable as of
+ # https://github.com/numpy/numpy/pull/5326, just test
+ # is_hashable()
+ assert not inference.is_hashable(np.array([]))
+
+
+@pytest.mark.parametrize("ll", [re.compile("ad")])
+def test_is_re_passes(ll):
+ assert inference.is_re(ll)
+
+
+@pytest.mark.parametrize("ll", ["x", 2, 3, object()])
+def test_is_re_fails(ll):
+ assert not inference.is_re(ll)
+
+
+@pytest.mark.parametrize(
+ "ll", [r"a", "x", r"asdf", re.compile("adsf"), r"\u2233\s*", re.compile(r"")]
+)
+def test_is_recompilable_passes(ll):
+ assert inference.is_re_compilable(ll)
+
+
+@pytest.mark.parametrize("ll", [1, [], object()])
+def test_is_recompilable_fails(ll):
+ assert not inference.is_re_compilable(ll)
+
+
+class TestInference:
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array(list("abc"), dtype="S1"),
+ np.array(list("abc"), dtype="S1").astype(object),
+ [b"a", np.nan, b"c"],
+ ],
+ )
+ def test_infer_dtype_bytes(self, arr):
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "bytes"
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (float("inf"), True),
+ (np.inf, True),
+ (-np.inf, False),
+ (1, False),
+ ("a", False),
+ ],
+ )
+ def test_isposinf_scalar(self, value, expected):
+ # GH 11352
+ result = libmissing.isposinf_scalar(value)
+ assert result is expected
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (float("-inf"), True),
+ (-np.inf, True),
+ (np.inf, False),
+ (1, False),
+ ("a", False),
+ ],
+ )
+ def test_isneginf_scalar(self, value, expected):
+ result = libmissing.isneginf_scalar(value)
+ assert result is expected
+
+ @pytest.mark.parametrize(
+ "convert_to_masked_nullable, exp",
+ [
+ (
+ True,
+ BooleanArray(
+ np.array([True, False], dtype="bool"), np.array([False, True])
+ ),
+ ),
+ (False, np.array([True, np.nan], dtype="object")),
+ ],
+ )
+ def test_maybe_convert_nullable_boolean(self, convert_to_masked_nullable, exp):
+ # GH 40687
+ arr = np.array([True, np.nan], dtype=object)
+ result = libops.maybe_convert_bool(
+ arr, set(), convert_to_masked_nullable=convert_to_masked_nullable
+ )
+ if convert_to_masked_nullable:
+ tm.assert_extension_array_equal(BooleanArray(*result), exp)
+ else:
+ result = result[0]
+ tm.assert_numpy_array_equal(result, exp)
+
+ @pytest.mark.parametrize("convert_to_masked_nullable", [True, False])
+ @pytest.mark.parametrize("coerce_numeric", [True, False])
+ @pytest.mark.parametrize(
+ "infinity", ["inf", "inF", "iNf", "Inf", "iNF", "InF", "INf", "INF"]
+ )
+ @pytest.mark.parametrize("prefix", ["", "-", "+"])
+ def test_maybe_convert_numeric_infinities(
+ self, coerce_numeric, infinity, prefix, convert_to_masked_nullable
+ ):
+ # see gh-13274
+ result, _ = lib.maybe_convert_numeric(
+ np.array([prefix + infinity], dtype=object),
+ na_values={"", "NULL", "nan"},
+ coerce_numeric=coerce_numeric,
+ convert_to_masked_nullable=convert_to_masked_nullable,
+ )
+ expected = np.array([np.inf if prefix in ["", "+"] else -np.inf])
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("convert_to_masked_nullable", [True, False])
+ def test_maybe_convert_numeric_infinities_raises(self, convert_to_masked_nullable):
+ msg = "Unable to parse string"
+ with pytest.raises(ValueError, match=msg):
+ lib.maybe_convert_numeric(
+ np.array(["foo_inf"], dtype=object),
+ na_values={"", "NULL", "nan"},
+ coerce_numeric=False,
+ convert_to_masked_nullable=convert_to_masked_nullable,
+ )
+
+ @pytest.mark.parametrize("convert_to_masked_nullable", [True, False])
+ def test_maybe_convert_numeric_post_floatify_nan(
+ self, coerce, convert_to_masked_nullable
+ ):
+ # see gh-13314
+ data = np.array(["1.200", "-999.000", "4.500"], dtype=object)
+ expected = np.array([1.2, np.nan, 4.5], dtype=np.float64)
+ nan_values = {-999, -999.0}
+
+ out = lib.maybe_convert_numeric(
+ data,
+ nan_values,
+ coerce,
+ convert_to_masked_nullable=convert_to_masked_nullable,
+ )
+ if convert_to_masked_nullable:
+ expected = FloatingArray(expected, np.isnan(expected))
+ tm.assert_extension_array_equal(expected, FloatingArray(*out))
+ else:
+ out = out[0]
+ tm.assert_numpy_array_equal(out, expected)
+
+ def test_convert_infs(self):
+ arr = np.array(["inf", "inf", "inf"], dtype="O")
+ result, _ = lib.maybe_convert_numeric(arr, set(), False)
+ assert result.dtype == np.float64
+
+ arr = np.array(["-inf", "-inf", "-inf"], dtype="O")
+ result, _ = lib.maybe_convert_numeric(arr, set(), False)
+ assert result.dtype == np.float64
+
+ def test_scientific_no_exponent(self):
+ # See PR 12215
+ arr = np.array(["42E", "2E", "99e", "6e"], dtype="O")
+ result, _ = lib.maybe_convert_numeric(arr, set(), False, True)
+ assert np.all(np.isnan(result))
+
+ def test_convert_non_hashable(self):
+ # GH13324
+ # make sure that we are handing non-hashables
+ arr = np.array([[10.0, 2], 1.0, "apple"], dtype=object)
+ result, _ = lib.maybe_convert_numeric(arr, set(), False, True)
+ tm.assert_numpy_array_equal(result, np.array([np.nan, 1.0, np.nan]))
+
+ def test_convert_numeric_uint64(self):
+ arr = np.array([2**63], dtype=object)
+ exp = np.array([2**63], dtype=np.uint64)
+ tm.assert_numpy_array_equal(lib.maybe_convert_numeric(arr, set())[0], exp)
+
+ arr = np.array([str(2**63)], dtype=object)
+ exp = np.array([2**63], dtype=np.uint64)
+ tm.assert_numpy_array_equal(lib.maybe_convert_numeric(arr, set())[0], exp)
+
+ arr = np.array([np.uint64(2**63)], dtype=object)
+ exp = np.array([2**63], dtype=np.uint64)
+ tm.assert_numpy_array_equal(lib.maybe_convert_numeric(arr, set())[0], exp)
+
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array([2**63, np.nan], dtype=object),
+ np.array([str(2**63), np.nan], dtype=object),
+ np.array([np.nan, 2**63], dtype=object),
+ np.array([np.nan, str(2**63)], dtype=object),
+ ],
+ )
+ def test_convert_numeric_uint64_nan(self, coerce, arr):
+ expected = arr.astype(float) if coerce else arr.copy()
+ result, _ = lib.maybe_convert_numeric(arr, set(), coerce_numeric=coerce)
+ tm.assert_almost_equal(result, expected)
+
+ @pytest.mark.parametrize("convert_to_masked_nullable", [True, False])
+ def test_convert_numeric_uint64_nan_values(
+ self, coerce, convert_to_masked_nullable
+ ):
+ arr = np.array([2**63, 2**63 + 1], dtype=object)
+ na_values = {2**63}
+
+ expected = (
+ np.array([np.nan, 2**63 + 1], dtype=float) if coerce else arr.copy()
+ )
+ result = lib.maybe_convert_numeric(
+ arr,
+ na_values,
+ coerce_numeric=coerce,
+ convert_to_masked_nullable=convert_to_masked_nullable,
+ )
+ if convert_to_masked_nullable and coerce:
+ expected = IntegerArray(
+ np.array([0, 2**63 + 1], dtype="u8"),
+ np.array([True, False], dtype="bool"),
+ )
+ result = IntegerArray(*result)
+ else:
+ result = result[0] # discard mask
+ tm.assert_almost_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "case",
+ [
+ np.array([2**63, -1], dtype=object),
+ np.array([str(2**63), -1], dtype=object),
+ np.array([str(2**63), str(-1)], dtype=object),
+ np.array([-1, 2**63], dtype=object),
+ np.array([-1, str(2**63)], dtype=object),
+ np.array([str(-1), str(2**63)], dtype=object),
+ ],
+ )
+ @pytest.mark.parametrize("convert_to_masked_nullable", [True, False])
+ def test_convert_numeric_int64_uint64(
+ self, case, coerce, convert_to_masked_nullable
+ ):
+ expected = case.astype(float) if coerce else case.copy()
+ result, _ = lib.maybe_convert_numeric(
+ case,
+ set(),
+ coerce_numeric=coerce,
+ convert_to_masked_nullable=convert_to_masked_nullable,
+ )
+
+ tm.assert_almost_equal(result, expected)
+
+ @pytest.mark.parametrize("convert_to_masked_nullable", [True, False])
+ def test_convert_numeric_string_uint64(self, convert_to_masked_nullable):
+ # GH32394
+ result = lib.maybe_convert_numeric(
+ np.array(["uint64"], dtype=object),
+ set(),
+ coerce_numeric=True,
+ convert_to_masked_nullable=convert_to_masked_nullable,
+ )
+ if convert_to_masked_nullable:
+ result = FloatingArray(*result)
+ else:
+ result = result[0]
+ assert np.isnan(result)
+
+ @pytest.mark.parametrize("value", [-(2**63) - 1, 2**64])
+ def test_convert_int_overflow(self, value):
+ # see gh-18584
+ arr = np.array([value], dtype=object)
+ result = lib.maybe_convert_objects(arr)
+ tm.assert_numpy_array_equal(arr, result)
+
+ @pytest.mark.parametrize("val", [None, np.nan, float("nan")])
+ @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
+ def test_maybe_convert_objects_nat_inference(self, val, dtype):
+ dtype = np.dtype(dtype)
+ vals = np.array([pd.NaT, val], dtype=object)
+ result = lib.maybe_convert_objects(
+ vals,
+ convert_non_numeric=True,
+ dtype_if_all_nat=dtype,
+ )
+ assert result.dtype == dtype
+ assert np.isnat(result).all()
+
+ result = lib.maybe_convert_objects(
+ vals[::-1],
+ convert_non_numeric=True,
+ dtype_if_all_nat=dtype,
+ )
+ assert result.dtype == dtype
+ assert np.isnat(result).all()
+
+ @pytest.mark.parametrize(
+ "value, expected_dtype",
+ [
+ # see gh-4471
+ ([2**63], np.uint64),
+ # NumPy bug: can't compare uint64 to int64, as that
+ # results in both casting to float64, so we should
+ # make sure that this function is robust against it
+ ([np.uint64(2**63)], np.uint64),
+ ([2, -1], np.int64),
+ ([2**63, -1], object),
+ # GH#47294
+ ([np.uint8(1)], np.uint8),
+ ([np.uint16(1)], np.uint16),
+ ([np.uint32(1)], np.uint32),
+ ([np.uint64(1)], np.uint64),
+ ([np.uint8(2), np.uint16(1)], np.uint16),
+ ([np.uint32(2), np.uint16(1)], np.uint32),
+ ([np.uint32(2), -1], object),
+ ([np.uint32(2), 1], np.uint64),
+ ([np.uint32(2), np.int32(1)], object),
+ ],
+ )
+ def test_maybe_convert_objects_uint(self, value, expected_dtype):
+ arr = np.array(value, dtype=object)
+ exp = np.array(value, dtype=expected_dtype)
+ tm.assert_numpy_array_equal(lib.maybe_convert_objects(arr), exp)
+
+ def test_maybe_convert_objects_datetime(self):
+ # GH27438
+ arr = np.array(
+ [np.datetime64("2000-01-01"), np.timedelta64(1, "s")], dtype=object
+ )
+ exp = arr.copy()
+ out = lib.maybe_convert_objects(arr, convert_non_numeric=True)
+ tm.assert_numpy_array_equal(out, exp)
+
+ arr = np.array([pd.NaT, np.timedelta64(1, "s")], dtype=object)
+ exp = np.array([np.timedelta64("NaT"), np.timedelta64(1, "s")], dtype="m8[ns]")
+ out = lib.maybe_convert_objects(arr, convert_non_numeric=True)
+ tm.assert_numpy_array_equal(out, exp)
+
+ # with convert_non_numeric=True, the nan is a valid NA value for td64
+ arr = np.array([np.timedelta64(1, "s"), np.nan], dtype=object)
+ exp = exp[::-1]
+ out = lib.maybe_convert_objects(arr, convert_non_numeric=True)
+ tm.assert_numpy_array_equal(out, exp)
+
+ def test_maybe_convert_objects_dtype_if_all_nat(self):
+ arr = np.array([pd.NaT, pd.NaT], dtype=object)
+ out = lib.maybe_convert_objects(arr, convert_non_numeric=True)
+ # no dtype_if_all_nat passed -> we dont guess
+ tm.assert_numpy_array_equal(out, arr)
+
+ out = lib.maybe_convert_objects(
+ arr,
+ convert_non_numeric=True,
+ dtype_if_all_nat=np.dtype("timedelta64[ns]"),
+ )
+ exp = np.array(["NaT", "NaT"], dtype="timedelta64[ns]")
+ tm.assert_numpy_array_equal(out, exp)
+
+ out = lib.maybe_convert_objects(
+ arr,
+ convert_non_numeric=True,
+ dtype_if_all_nat=np.dtype("datetime64[ns]"),
+ )
+ exp = np.array(["NaT", "NaT"], dtype="datetime64[ns]")
+ tm.assert_numpy_array_equal(out, exp)
+
+ def test_maybe_convert_objects_dtype_if_all_nat_invalid(self):
+ # we accept datetime64[ns], timedelta64[ns], and EADtype
+ arr = np.array([pd.NaT, pd.NaT], dtype=object)
+
+ with pytest.raises(ValueError, match="int64"):
+ lib.maybe_convert_objects(
+ arr,
+ convert_non_numeric=True,
+ dtype_if_all_nat=np.dtype("int64"),
+ )
+
+ @pytest.mark.parametrize("dtype", ["datetime64[ns]", "timedelta64[ns]"])
+ def test_maybe_convert_objects_datetime_overflow_safe(self, dtype):
+ stamp = datetime(2363, 10, 4) # Enterprise-D launch date
+ if dtype == "timedelta64[ns]":
+ stamp = stamp - datetime(1970, 1, 1)
+ arr = np.array([stamp], dtype=object)
+
+ out = lib.maybe_convert_objects(arr, convert_non_numeric=True)
+ # no OutOfBoundsDatetime/OutOfBoundsTimedeltas
+ tm.assert_numpy_array_equal(out, arr)
+
+ def test_maybe_convert_objects_mixed_datetimes(self):
+ ts = Timestamp("now")
+ vals = [ts, ts.to_pydatetime(), ts.to_datetime64(), pd.NaT, np.nan, None]
+
+ for data in itertools.permutations(vals):
+ data = np.array(list(data), dtype=object)
+ expected = DatetimeIndex(data)._data._ndarray
+ result = lib.maybe_convert_objects(data, convert_non_numeric=True)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_maybe_convert_objects_timedelta64_nat(self):
+ obj = np.timedelta64("NaT", "ns")
+ arr = np.array([obj], dtype=object)
+ assert arr[0] is obj
+
+ result = lib.maybe_convert_objects(arr, convert_non_numeric=True)
+
+ expected = np.array([obj], dtype="m8[ns]")
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "exp",
+ [
+ IntegerArray(np.array([2, 0], dtype="i8"), np.array([False, True])),
+ IntegerArray(np.array([2, 0], dtype="int64"), np.array([False, True])),
+ ],
+ )
+ def test_maybe_convert_objects_nullable_integer(self, exp):
+ # GH27335
+ arr = np.array([2, np.nan], dtype=object)
+ result = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True)
+
+ tm.assert_extension_array_equal(result, exp)
+
+ @pytest.mark.parametrize(
+ "dtype, val", [("int64", 1), ("uint64", np.iinfo(np.int64).max + 1)]
+ )
+ def test_maybe_convert_objects_nullable_none(self, dtype, val):
+ # GH#50043
+ arr = np.array([val, None, 3], dtype="object")
+ result = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True)
+ expected = IntegerArray(
+ np.array([val, 0, 3], dtype=dtype), np.array([False, True, False])
+ )
+ tm.assert_extension_array_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "convert_to_masked_nullable, exp",
+ [
+ (True, IntegerArray(np.array([2, 0], dtype="i8"), np.array([False, True]))),
+ (False, np.array([2, np.nan], dtype="float64")),
+ ],
+ )
+ def test_maybe_convert_numeric_nullable_integer(
+ self, convert_to_masked_nullable, exp
+ ):
+ # GH 40687
+ arr = np.array([2, np.nan], dtype=object)
+ result = lib.maybe_convert_numeric(
+ arr, set(), convert_to_masked_nullable=convert_to_masked_nullable
+ )
+ if convert_to_masked_nullable:
+ result = IntegerArray(*result)
+ tm.assert_extension_array_equal(result, exp)
+ else:
+ result = result[0]
+ tm.assert_numpy_array_equal(result, exp)
+
+ @pytest.mark.parametrize(
+ "convert_to_masked_nullable, exp",
+ [
+ (
+ True,
+ FloatingArray(
+ np.array([2.0, 0.0], dtype="float64"), np.array([False, True])
+ ),
+ ),
+ (False, np.array([2.0, np.nan], dtype="float64")),
+ ],
+ )
+ def test_maybe_convert_numeric_floating_array(
+ self, convert_to_masked_nullable, exp
+ ):
+ # GH 40687
+ arr = np.array([2.0, np.nan], dtype=object)
+ result = lib.maybe_convert_numeric(
+ arr, set(), convert_to_masked_nullable=convert_to_masked_nullable
+ )
+ if convert_to_masked_nullable:
+ tm.assert_extension_array_equal(FloatingArray(*result), exp)
+ else:
+ result = result[0]
+ tm.assert_numpy_array_equal(result, exp)
+
+ def test_maybe_convert_objects_bool_nan(self):
+ # GH32146
+ ind = Index([True, False, np.nan], dtype=object)
+ exp = np.array([True, False, np.nan], dtype=object)
+ out = lib.maybe_convert_objects(ind.values, safe=1)
+ tm.assert_numpy_array_equal(out, exp)
+
+ def test_maybe_convert_objects_nullable_boolean(self):
+ # GH50047
+ arr = np.array([True, False], dtype=object)
+ exp = np.array([True, False])
+ out = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True)
+ tm.assert_numpy_array_equal(out, exp)
+
+ arr = np.array([True, False, pd.NaT], dtype=object)
+ exp = np.array([True, False, pd.NaT], dtype=object)
+ out = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True)
+ tm.assert_numpy_array_equal(out, exp)
+
+ @pytest.mark.parametrize("val", [None, np.nan])
+ def test_maybe_convert_objects_nullable_boolean_na(self, val):
+ # GH50047
+ arr = np.array([True, False, val], dtype=object)
+ exp = BooleanArray(
+ np.array([True, False, False]), np.array([False, False, True])
+ )
+ out = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True)
+ tm.assert_extension_array_equal(out, exp)
+
+ @pytest.mark.parametrize(
+ "data0",
+ [
+ True,
+ 1,
+ 1.0,
+ 1.0 + 1.0j,
+ np.int8(1),
+ np.int16(1),
+ np.int32(1),
+ np.int64(1),
+ np.float16(1),
+ np.float32(1),
+ np.float64(1),
+ np.complex64(1),
+ np.complex128(1),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "data1",
+ [
+ True,
+ 1,
+ 1.0,
+ 1.0 + 1.0j,
+ np.int8(1),
+ np.int16(1),
+ np.int32(1),
+ np.int64(1),
+ np.float16(1),
+ np.float32(1),
+ np.float64(1),
+ np.complex64(1),
+ np.complex128(1),
+ ],
+ )
+ def test_maybe_convert_objects_itemsize(self, data0, data1):
+ # GH 40908
+ data = [data0, data1]
+ arr = np.array(data, dtype="object")
+
+ common_kind = np.result_type(type(data0), type(data1)).kind
+ kind0 = "python" if not hasattr(data0, "dtype") else data0.dtype.kind
+ kind1 = "python" if not hasattr(data1, "dtype") else data1.dtype.kind
+ if kind0 != "python" and kind1 != "python":
+ kind = common_kind
+ itemsize = max(data0.dtype.itemsize, data1.dtype.itemsize)
+ elif is_bool(data0) or is_bool(data1):
+ kind = "bool" if (is_bool(data0) and is_bool(data1)) else "object"
+ itemsize = ""
+ elif is_complex(data0) or is_complex(data1):
+ kind = common_kind
+ itemsize = 16
+ else:
+ kind = common_kind
+ itemsize = 8
+
+ expected = np.array(data, dtype=f"{kind}{itemsize}")
+ result = lib.maybe_convert_objects(arr)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_mixed_dtypes_remain_object_array(self):
+ # GH14956
+ arr = np.array([datetime(2015, 1, 1, tzinfo=pytz.utc), 1], dtype=object)
+ result = lib.maybe_convert_objects(arr, convert_non_numeric=True)
+ tm.assert_numpy_array_equal(result, arr)
+
+ @pytest.mark.parametrize(
+ "idx",
+ [
+ pd.IntervalIndex.from_breaks(range(5), closed="both"),
+ pd.period_range("2016-01-01", periods=3, freq="D"),
+ ],
+ )
+ def test_maybe_convert_objects_ea(self, idx):
+ result = lib.maybe_convert_objects(
+ np.array(idx, dtype=object),
+ convert_non_numeric=True,
+ )
+ tm.assert_extension_array_equal(result, idx._data)
+
+
+class TestTypeInference:
+ # Dummy class used for testing with Python objects
+ class Dummy:
+ pass
+
+ def test_inferred_dtype_fixture(self, any_skipna_inferred_dtype):
+ # see pandas/conftest.py
+ inferred_dtype, values = any_skipna_inferred_dtype
+
+ # make sure the inferred dtype of the fixture is as requested
+ assert inferred_dtype == lib.infer_dtype(values, skipna=True)
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_length_zero(self, skipna):
+ result = lib.infer_dtype(np.array([], dtype="i4"), skipna=skipna)
+ assert result == "integer"
+
+ result = lib.infer_dtype([], skipna=skipna)
+ assert result == "empty"
+
+ # GH 18004
+ arr = np.array([np.array([], dtype=object), np.array([], dtype=object)])
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == "empty"
+
+ def test_integers(self):
+ arr = np.array([1, 2, 3, np.int64(4), np.int32(5)], dtype="O")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "integer"
+
+ arr = np.array([1, 2, 3, np.int64(4), np.int32(5), "foo"], dtype="O")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "mixed-integer"
+
+ arr = np.array([1, 2, 3, 4, 5], dtype="i4")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "integer"
+
+ @pytest.mark.parametrize(
+ "arr, skipna",
+ [
+ (np.array([1, 2, np.nan, np.nan, 3], dtype="O"), False),
+ (np.array([1, 2, np.nan, np.nan, 3], dtype="O"), True),
+ (np.array([1, 2, 3, np.int64(4), np.int32(5), np.nan], dtype="O"), False),
+ (np.array([1, 2, 3, np.int64(4), np.int32(5), np.nan], dtype="O"), True),
+ ],
+ )
+ def test_integer_na(self, arr, skipna):
+ # GH 27392
+ result = lib.infer_dtype(arr, skipna=skipna)
+ expected = "integer" if skipna else "integer-na"
+ assert result == expected
+
+ def test_infer_dtype_skipna_default(self):
+ # infer_dtype `skipna` default deprecated in GH#24050,
+ # changed to True in GH#29876
+ arr = np.array([1, 2, 3, np.nan], dtype=object)
+
+ result = lib.infer_dtype(arr)
+ assert result == "integer"
+
+ def test_bools(self):
+ arr = np.array([True, False, True, True, True], dtype="O")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "boolean"
+
+ arr = np.array([np.bool_(True), np.bool_(False)], dtype="O")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "boolean"
+
+ arr = np.array([True, False, True, "foo"], dtype="O")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "mixed"
+
+ arr = np.array([True, False, True], dtype=bool)
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "boolean"
+
+ arr = np.array([True, np.nan, False], dtype="O")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "boolean"
+
+ result = lib.infer_dtype(arr, skipna=False)
+ assert result == "mixed"
+
+ def test_floats(self):
+ arr = np.array([1.0, 2.0, 3.0, np.float64(4), np.float32(5)], dtype="O")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "floating"
+
+ arr = np.array([1, 2, 3, np.float64(4), np.float32(5), "foo"], dtype="O")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "mixed-integer"
+
+ arr = np.array([1, 2, 3, 4, 5], dtype="f4")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "floating"
+
+ arr = np.array([1, 2, 3, 4, 5], dtype="f8")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "floating"
+
+ def test_decimals(self):
+ # GH15690
+ arr = np.array([Decimal(1), Decimal(2), Decimal(3)])
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "decimal"
+
+ arr = np.array([1.0, 2.0, Decimal(3)])
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "mixed"
+
+ result = lib.infer_dtype(arr[::-1], skipna=True)
+ assert result == "mixed"
+
+ arr = np.array([Decimal(1), Decimal("NaN"), Decimal(3)])
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "decimal"
+
+ arr = np.array([Decimal(1), np.nan, Decimal(3)], dtype="O")
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "decimal"
+
+ # complex is compatible with nan, so skipna has no effect
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_complex(self, skipna):
+ # gets cast to complex on array construction
+ arr = np.array([1.0, 2.0, 1 + 1j])
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == "complex"
+
+ arr = np.array([1.0, 2.0, 1 + 1j], dtype="O")
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == "mixed"
+
+ result = lib.infer_dtype(arr[::-1], skipna=skipna)
+ assert result == "mixed"
+
+ # gets cast to complex on array construction
+ arr = np.array([1, np.nan, 1 + 1j])
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == "complex"
+
+ arr = np.array([1.0, np.nan, 1 + 1j], dtype="O")
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == "mixed"
+
+ # complex with nans stays complex
+ arr = np.array([1 + 1j, np.nan, 3 + 3j], dtype="O")
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == "complex"
+
+ # test smaller complex dtype; will pass through _try_infer_map fastpath
+ arr = np.array([1 + 1j, np.nan, 3 + 3j], dtype=np.complex64)
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == "complex"
+
+ def test_string(self):
+ pass
+
+ def test_unicode(self):
+ arr = ["a", np.nan, "c"]
+ result = lib.infer_dtype(arr, skipna=False)
+ # This currently returns "mixed", but it's not clear that's optimal.
+ # This could also return "string" or "mixed-string"
+ assert result == "mixed"
+
+ # even though we use skipna, we are only skipping those NAs that are
+ # considered matching by is_string_array
+ arr = ["a", np.nan, "c"]
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "string"
+
+ arr = ["a", pd.NA, "c"]
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "string"
+
+ arr = ["a", pd.NaT, "c"]
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "mixed"
+
+ arr = ["a", "c"]
+ result = lib.infer_dtype(arr, skipna=False)
+ assert result == "string"
+
+ @pytest.mark.parametrize(
+ "dtype, missing, skipna, expected",
+ [
+ (float, np.nan, False, "floating"),
+ (float, np.nan, True, "floating"),
+ (object, np.nan, False, "floating"),
+ (object, np.nan, True, "empty"),
+ (object, None, False, "mixed"),
+ (object, None, True, "empty"),
+ ],
+ )
+ @pytest.mark.parametrize("box", [Series, np.array])
+ def test_object_empty(self, box, missing, dtype, skipna, expected):
+ # GH 23421
+ arr = box([missing, missing], dtype=dtype)
+
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == expected
+
+ def test_datetime(self):
+ dates = [datetime(2012, 1, x) for x in range(1, 20)]
+ index = Index(dates)
+ assert index.inferred_type == "datetime64"
+
+ def test_infer_dtype_datetime64(self):
+ arr = np.array(
+ [np.datetime64("2011-01-01"), np.datetime64("2011-01-01")], dtype=object
+ )
+ assert lib.infer_dtype(arr, skipna=True) == "datetime64"
+
+ @pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
+ def test_infer_dtype_datetime64_with_na(self, na_value):
+ # starts with nan
+ arr = np.array([na_value, np.datetime64("2011-01-02")])
+ assert lib.infer_dtype(arr, skipna=True) == "datetime64"
+
+ arr = np.array([na_value, np.datetime64("2011-01-02"), na_value])
+ assert lib.infer_dtype(arr, skipna=True) == "datetime64"
+
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array(
+ [np.timedelta64("nat"), np.datetime64("2011-01-02")], dtype=object
+ ),
+ np.array(
+ [np.datetime64("2011-01-02"), np.timedelta64("nat")], dtype=object
+ ),
+ np.array([np.datetime64("2011-01-01"), Timestamp("2011-01-02")]),
+ np.array([Timestamp("2011-01-02"), np.datetime64("2011-01-01")]),
+ np.array([np.nan, Timestamp("2011-01-02"), 1.1]),
+ np.array([np.nan, "2011-01-01", Timestamp("2011-01-02")], dtype=object),
+ np.array([np.datetime64("nat"), np.timedelta64(1, "D")], dtype=object),
+ np.array([np.timedelta64(1, "D"), np.datetime64("nat")], dtype=object),
+ ],
+ )
+ def test_infer_datetimelike_dtype_mixed(self, arr):
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ def test_infer_dtype_mixed_integer(self):
+ arr = np.array([np.nan, Timestamp("2011-01-02"), 1])
+ assert lib.infer_dtype(arr, skipna=True) == "mixed-integer"
+
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array([Timestamp("2011-01-01"), Timestamp("2011-01-02")]),
+ np.array([datetime(2011, 1, 1), datetime(2012, 2, 1)]),
+ np.array([datetime(2011, 1, 1), Timestamp("2011-01-02")]),
+ ],
+ )
+ def test_infer_dtype_datetime(self, arr):
+ assert lib.infer_dtype(arr, skipna=True) == "datetime"
+
+ @pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
+ @pytest.mark.parametrize(
+ "time_stamp", [Timestamp("2011-01-01"), datetime(2011, 1, 1)]
+ )
+ def test_infer_dtype_datetime_with_na(self, na_value, time_stamp):
+ # starts with nan
+ arr = np.array([na_value, time_stamp])
+ assert lib.infer_dtype(arr, skipna=True) == "datetime"
+
+ arr = np.array([na_value, time_stamp, na_value])
+ assert lib.infer_dtype(arr, skipna=True) == "datetime"
+
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array([Timedelta("1 days"), Timedelta("2 days")]),
+ np.array([np.timedelta64(1, "D"), np.timedelta64(2, "D")], dtype=object),
+ np.array([timedelta(1), timedelta(2)]),
+ ],
+ )
+ def test_infer_dtype_timedelta(self, arr):
+ assert lib.infer_dtype(arr, skipna=True) == "timedelta"
+
+ @pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
+ @pytest.mark.parametrize(
+ "delta", [Timedelta("1 days"), np.timedelta64(1, "D"), timedelta(1)]
+ )
+ def test_infer_dtype_timedelta_with_na(self, na_value, delta):
+ # starts with nan
+ arr = np.array([na_value, delta])
+ assert lib.infer_dtype(arr, skipna=True) == "timedelta"
+
+ arr = np.array([na_value, delta, na_value])
+ assert lib.infer_dtype(arr, skipna=True) == "timedelta"
+
+ def test_infer_dtype_period(self):
+ # GH 13664
+ arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="D")])
+ assert lib.infer_dtype(arr, skipna=True) == "period"
+
+ # non-homogeneous freqs -> mixed
+ arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="M")])
+ assert lib.infer_dtype(arr, skipna=True) == "mixed"
+
+ @pytest.mark.parametrize("klass", [pd.array, Series, Index])
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_infer_dtype_period_array(self, klass, skipna):
+ # https://github.com/pandas-dev/pandas/issues/23553
+ values = klass(
+ [
+ Period("2011-01-01", freq="D"),
+ Period("2011-01-02", freq="D"),
+ pd.NaT,
+ ]
+ )
+ assert lib.infer_dtype(values, skipna=skipna) == "period"
+
+ # periods but mixed freq
+ values = klass(
+ [
+ Period("2011-01-01", freq="D"),
+ Period("2011-01-02", freq="M"),
+ pd.NaT,
+ ]
+ )
+ # with pd.array this becomes NumpyExtensionArray which ends up
+ # as "unknown-array"
+ exp = "unknown-array" if klass is pd.array else "mixed"
+ assert lib.infer_dtype(values, skipna=skipna) == exp
+
+ def test_infer_dtype_period_mixed(self):
+ arr = np.array(
+ [Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object
+ )
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ arr = np.array(
+ [np.datetime64("nat"), Period("2011-01", freq="M")], dtype=object
+ )
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ @pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
+ def test_infer_dtype_period_with_na(self, na_value):
+ # starts with nan
+ arr = np.array([na_value, Period("2011-01", freq="D")])
+ assert lib.infer_dtype(arr, skipna=True) == "period"
+
+ arr = np.array([na_value, Period("2011-01", freq="D"), na_value])
+ assert lib.infer_dtype(arr, skipna=True) == "period"
+
+ def test_infer_dtype_all_nan_nat_like(self):
+ arr = np.array([np.nan, np.nan])
+ assert lib.infer_dtype(arr, skipna=True) == "floating"
+
+ # nan and None mix are result in mixed
+ arr = np.array([np.nan, np.nan, None])
+ assert lib.infer_dtype(arr, skipna=True) == "empty"
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ arr = np.array([None, np.nan, np.nan])
+ assert lib.infer_dtype(arr, skipna=True) == "empty"
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ # pd.NaT
+ arr = np.array([pd.NaT])
+ assert lib.infer_dtype(arr, skipna=False) == "datetime"
+
+ arr = np.array([pd.NaT, np.nan])
+ assert lib.infer_dtype(arr, skipna=False) == "datetime"
+
+ arr = np.array([np.nan, pd.NaT])
+ assert lib.infer_dtype(arr, skipna=False) == "datetime"
+
+ arr = np.array([np.nan, pd.NaT, np.nan])
+ assert lib.infer_dtype(arr, skipna=False) == "datetime"
+
+ arr = np.array([None, pd.NaT, None])
+ assert lib.infer_dtype(arr, skipna=False) == "datetime"
+
+ # np.datetime64(nat)
+ arr = np.array([np.datetime64("nat")])
+ assert lib.infer_dtype(arr, skipna=False) == "datetime64"
+
+ for n in [np.nan, pd.NaT, None]:
+ arr = np.array([n, np.datetime64("nat"), n])
+ assert lib.infer_dtype(arr, skipna=False) == "datetime64"
+
+ arr = np.array([pd.NaT, n, np.datetime64("nat"), n])
+ assert lib.infer_dtype(arr, skipna=False) == "datetime64"
+
+ arr = np.array([np.timedelta64("nat")], dtype=object)
+ assert lib.infer_dtype(arr, skipna=False) == "timedelta"
+
+ for n in [np.nan, pd.NaT, None]:
+ arr = np.array([n, np.timedelta64("nat"), n])
+ assert lib.infer_dtype(arr, skipna=False) == "timedelta"
+
+ arr = np.array([pd.NaT, n, np.timedelta64("nat"), n])
+ assert lib.infer_dtype(arr, skipna=False) == "timedelta"
+
+ # datetime / timedelta mixed
+ arr = np.array([pd.NaT, np.datetime64("nat"), np.timedelta64("nat"), np.nan])
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ arr = np.array([np.timedelta64("nat"), np.datetime64("nat")], dtype=object)
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ def test_is_datetimelike_array_all_nan_nat_like(self):
+ arr = np.array([np.nan, pd.NaT, np.datetime64("nat")])
+ assert lib.is_datetime_array(arr)
+ assert lib.is_datetime64_array(arr)
+ assert not lib.is_timedelta_or_timedelta64_array(arr)
+
+ arr = np.array([np.nan, pd.NaT, np.timedelta64("nat")])
+ assert not lib.is_datetime_array(arr)
+ assert not lib.is_datetime64_array(arr)
+ assert lib.is_timedelta_or_timedelta64_array(arr)
+
+ arr = np.array([np.nan, pd.NaT, np.datetime64("nat"), np.timedelta64("nat")])
+ assert not lib.is_datetime_array(arr)
+ assert not lib.is_datetime64_array(arr)
+ assert not lib.is_timedelta_or_timedelta64_array(arr)
+
+ arr = np.array([np.nan, pd.NaT])
+ assert lib.is_datetime_array(arr)
+ assert lib.is_datetime64_array(arr)
+ assert lib.is_timedelta_or_timedelta64_array(arr)
+
+ arr = np.array([np.nan, np.nan], dtype=object)
+ assert not lib.is_datetime_array(arr)
+ assert not lib.is_datetime64_array(arr)
+ assert not lib.is_timedelta_or_timedelta64_array(arr)
+
+ assert lib.is_datetime_with_singletz_array(
+ np.array(
+ [
+ Timestamp("20130101", tz="US/Eastern"),
+ Timestamp("20130102", tz="US/Eastern"),
+ ],
+ dtype=object,
+ )
+ )
+ assert not lib.is_datetime_with_singletz_array(
+ np.array(
+ [
+ Timestamp("20130101", tz="US/Eastern"),
+ Timestamp("20130102", tz="CET"),
+ ],
+ dtype=object,
+ )
+ )
+
+ @pytest.mark.parametrize(
+ "func",
+ [
+ "is_datetime_array",
+ "is_datetime64_array",
+ "is_bool_array",
+ "is_timedelta_or_timedelta64_array",
+ "is_date_array",
+ "is_time_array",
+ "is_interval_array",
+ ],
+ )
+ def test_other_dtypes_for_array(self, func):
+ func = getattr(lib, func)
+ arr = np.array(["foo", "bar"])
+ assert not func(arr)
+ assert not func(arr.reshape(2, 1))
+
+ arr = np.array([1, 2])
+ assert not func(arr)
+ assert not func(arr.reshape(2, 1))
+
+ def test_date(self):
+ dates = [date(2012, 1, day) for day in range(1, 20)]
+ index = Index(dates)
+ assert index.inferred_type == "date"
+
+ dates = [date(2012, 1, day) for day in range(1, 20)] + [np.nan]
+ result = lib.infer_dtype(dates, skipna=False)
+ assert result == "mixed"
+
+ result = lib.infer_dtype(dates, skipna=True)
+ assert result == "date"
+
+ @pytest.mark.parametrize(
+ "values",
+ [
+ [date(2020, 1, 1), Timestamp("2020-01-01")],
+ [Timestamp("2020-01-01"), date(2020, 1, 1)],
+ [date(2020, 1, 1), pd.NaT],
+ [pd.NaT, date(2020, 1, 1)],
+ ],
+ )
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_infer_dtype_date_order_invariant(self, values, skipna):
+ # https://github.com/pandas-dev/pandas/issues/33741
+ result = lib.infer_dtype(values, skipna=skipna)
+ assert result == "date"
+
+ def test_is_numeric_array(self):
+ assert lib.is_float_array(np.array([1, 2.0]))
+ assert lib.is_float_array(np.array([1, 2.0, np.nan]))
+ assert not lib.is_float_array(np.array([1, 2]))
+
+ assert lib.is_integer_array(np.array([1, 2]))
+ assert not lib.is_integer_array(np.array([1, 2.0]))
+
+ def test_is_string_array(self):
+ # We should only be accepting pd.NA, np.nan,
+ # other floating point nans e.g. float('nan')]
+ # when skipna is True.
+ assert lib.is_string_array(np.array(["foo", "bar"]))
+ assert not lib.is_string_array(
+ np.array(["foo", "bar", pd.NA], dtype=object), skipna=False
+ )
+ assert lib.is_string_array(
+ np.array(["foo", "bar", pd.NA], dtype=object), skipna=True
+ )
+ # we allow NaN/None in the StringArray constructor, so its allowed here
+ assert lib.is_string_array(
+ np.array(["foo", "bar", None], dtype=object), skipna=True
+ )
+ assert lib.is_string_array(
+ np.array(["foo", "bar", np.nan], dtype=object), skipna=True
+ )
+ # But not e.g. datetimelike or Decimal NAs
+ assert not lib.is_string_array(
+ np.array(["foo", "bar", pd.NaT], dtype=object), skipna=True
+ )
+ assert not lib.is_string_array(
+ np.array(["foo", "bar", np.datetime64("NaT")], dtype=object), skipna=True
+ )
+ assert not lib.is_string_array(
+ np.array(["foo", "bar", Decimal("NaN")], dtype=object), skipna=True
+ )
+
+ assert not lib.is_string_array(
+ np.array(["foo", "bar", None], dtype=object), skipna=False
+ )
+ assert not lib.is_string_array(
+ np.array(["foo", "bar", np.nan], dtype=object), skipna=False
+ )
+ assert not lib.is_string_array(np.array([1, 2]))
+
+ def test_to_object_array_tuples(self):
+ r = (5, 6)
+ values = [r]
+ lib.to_object_array_tuples(values)
+
+ # make sure record array works
+ record = namedtuple("record", "x y")
+ r = record(5, 6)
+ values = [r]
+ lib.to_object_array_tuples(values)
+
+ def test_object(self):
+ # GH 7431
+ # cannot infer more than this as only a single element
+ arr = np.array([None], dtype="O")
+ result = lib.infer_dtype(arr, skipna=False)
+ assert result == "mixed"
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "empty"
+
+ def test_to_object_array_width(self):
+ # see gh-13320
+ rows = [[1, 2, 3], [4, 5, 6]]
+
+ expected = np.array(rows, dtype=object)
+ out = lib.to_object_array(rows)
+ tm.assert_numpy_array_equal(out, expected)
+
+ expected = np.array(rows, dtype=object)
+ out = lib.to_object_array(rows, min_width=1)
+ tm.assert_numpy_array_equal(out, expected)
+
+ expected = np.array(
+ [[1, 2, 3, None, None], [4, 5, 6, None, None]], dtype=object
+ )
+ out = lib.to_object_array(rows, min_width=5)
+ tm.assert_numpy_array_equal(out, expected)
+
+ def test_is_period(self):
+ assert lib.is_period(Period("2011-01", freq="M"))
+ assert not lib.is_period(PeriodIndex(["2011-01"], freq="M"))
+ assert not lib.is_period(Timestamp("2011-01"))
+ assert not lib.is_period(1)
+ assert not lib.is_period(np.nan)
+
+ def test_categorical(self):
+ # GH 8974
+ arr = Categorical(list("abc"))
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "categorical"
+
+ result = lib.infer_dtype(Series(arr), skipna=True)
+ assert result == "categorical"
+
+ arr = Categorical(list("abc"), categories=["cegfab"], ordered=True)
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "categorical"
+
+ result = lib.infer_dtype(Series(arr), skipna=True)
+ assert result == "categorical"
+
+ @pytest.mark.parametrize("asobject", [True, False])
+ def test_interval(self, asobject):
+ idx = pd.IntervalIndex.from_breaks(range(5), closed="both")
+ if asobject:
+ idx = idx.astype(object)
+
+ inferred = lib.infer_dtype(idx, skipna=False)
+ assert inferred == "interval"
+
+ inferred = lib.infer_dtype(idx._data, skipna=False)
+ assert inferred == "interval"
+
+ inferred = lib.infer_dtype(Series(idx, dtype=idx.dtype), skipna=False)
+ assert inferred == "interval"
+
+ @pytest.mark.parametrize("value", [Timestamp(0), Timedelta(0), 0, 0.0])
+ def test_interval_mismatched_closed(self, value):
+ first = Interval(value, value, closed="left")
+ second = Interval(value, value, closed="right")
+
+ # if closed match, we should infer "interval"
+ arr = np.array([first, first], dtype=object)
+ assert lib.infer_dtype(arr, skipna=False) == "interval"
+
+ # if closed dont match, we should _not_ get "interval"
+ arr2 = np.array([first, second], dtype=object)
+ assert lib.infer_dtype(arr2, skipna=False) == "mixed"
+
+ def test_interval_mismatched_subtype(self):
+ first = Interval(0, 1, closed="left")
+ second = Interval(Timestamp(0), Timestamp(1), closed="left")
+ third = Interval(Timedelta(0), Timedelta(1), closed="left")
+
+ arr = np.array([first, second])
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ arr = np.array([second, third])
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ arr = np.array([first, third])
+ assert lib.infer_dtype(arr, skipna=False) == "mixed"
+
+ # float vs int subdtype are compatible
+ flt_interval = Interval(1.5, 2.5, closed="left")
+ arr = np.array([first, flt_interval], dtype=object)
+ assert lib.infer_dtype(arr, skipna=False) == "interval"
+
+ @pytest.mark.parametrize("klass", [pd.array, Series])
+ @pytest.mark.parametrize("skipna", [True, False])
+ @pytest.mark.parametrize("data", [["a", "b", "c"], ["a", "b", pd.NA]])
+ def test_string_dtype(self, data, skipna, klass, nullable_string_dtype):
+ # StringArray
+ val = klass(data, dtype=nullable_string_dtype)
+ inferred = lib.infer_dtype(val, skipna=skipna)
+ assert inferred == "string"
+
+ @pytest.mark.parametrize("klass", [pd.array, Series])
+ @pytest.mark.parametrize("skipna", [True, False])
+ @pytest.mark.parametrize("data", [[True, False, True], [True, False, pd.NA]])
+ def test_boolean_dtype(self, data, skipna, klass):
+ # BooleanArray
+ val = klass(data, dtype="boolean")
+ inferred = lib.infer_dtype(val, skipna=skipna)
+ assert inferred == "boolean"
+
+
+class TestNumberScalar:
+ def test_is_number(self):
+ assert is_number(True)
+ assert is_number(1)
+ assert is_number(1.1)
+ assert is_number(1 + 3j)
+ assert is_number(np.int64(1))
+ assert is_number(np.float64(1.1))
+ assert is_number(np.complex128(1 + 3j))
+ assert is_number(np.nan)
+
+ assert not is_number(None)
+ assert not is_number("x")
+ assert not is_number(datetime(2011, 1, 1))
+ assert not is_number(np.datetime64("2011-01-01"))
+ assert not is_number(Timestamp("2011-01-01"))
+ assert not is_number(Timestamp("2011-01-01", tz="US/Eastern"))
+ assert not is_number(timedelta(1000))
+ assert not is_number(Timedelta("1 days"))
+
+ # questionable
+ assert not is_number(np.bool_(False))
+ assert is_number(np.timedelta64(1, "D"))
+
+ def test_is_bool(self):
+ assert is_bool(True)
+ assert is_bool(False)
+ assert is_bool(np.bool_(False))
+
+ assert not is_bool(1)
+ assert not is_bool(1.1)
+ assert not is_bool(1 + 3j)
+ assert not is_bool(np.int64(1))
+ assert not is_bool(np.float64(1.1))
+ assert not is_bool(np.complex128(1 + 3j))
+ assert not is_bool(np.nan)
+ assert not is_bool(None)
+ assert not is_bool("x")
+ assert not is_bool(datetime(2011, 1, 1))
+ assert not is_bool(np.datetime64("2011-01-01"))
+ assert not is_bool(Timestamp("2011-01-01"))
+ assert not is_bool(Timestamp("2011-01-01", tz="US/Eastern"))
+ assert not is_bool(timedelta(1000))
+ assert not is_bool(np.timedelta64(1, "D"))
+ assert not is_bool(Timedelta("1 days"))
+
+ def test_is_integer(self):
+ assert is_integer(1)
+ assert is_integer(np.int64(1))
+
+ assert not is_integer(True)
+ assert not is_integer(1.1)
+ assert not is_integer(1 + 3j)
+ assert not is_integer(False)
+ assert not is_integer(np.bool_(False))
+ assert not is_integer(np.float64(1.1))
+ assert not is_integer(np.complex128(1 + 3j))
+ assert not is_integer(np.nan)
+ assert not is_integer(None)
+ assert not is_integer("x")
+ assert not is_integer(datetime(2011, 1, 1))
+ assert not is_integer(np.datetime64("2011-01-01"))
+ assert not is_integer(Timestamp("2011-01-01"))
+ assert not is_integer(Timestamp("2011-01-01", tz="US/Eastern"))
+ assert not is_integer(timedelta(1000))
+ assert not is_integer(Timedelta("1 days"))
+ assert not is_integer(np.timedelta64(1, "D"))
+
+ def test_is_float(self):
+ assert is_float(1.1)
+ assert is_float(np.float64(1.1))
+ assert is_float(np.nan)
+
+ assert not is_float(True)
+ assert not is_float(1)
+ assert not is_float(1 + 3j)
+ assert not is_float(False)
+ assert not is_float(np.bool_(False))
+ assert not is_float(np.int64(1))
+ assert not is_float(np.complex128(1 + 3j))
+ assert not is_float(None)
+ assert not is_float("x")
+ assert not is_float(datetime(2011, 1, 1))
+ assert not is_float(np.datetime64("2011-01-01"))
+ assert not is_float(Timestamp("2011-01-01"))
+ assert not is_float(Timestamp("2011-01-01", tz="US/Eastern"))
+ assert not is_float(timedelta(1000))
+ assert not is_float(np.timedelta64(1, "D"))
+ assert not is_float(Timedelta("1 days"))
+
+ def test_is_datetime_dtypes(self):
+ ts = pd.date_range("20130101", periods=3)
+ tsa = pd.date_range("20130101", periods=3, tz="US/Eastern")
+
+ msg = "is_datetime64tz_dtype is deprecated"
+
+ assert is_datetime64_dtype("datetime64")
+ assert is_datetime64_dtype("datetime64[ns]")
+ assert is_datetime64_dtype(ts)
+ assert not is_datetime64_dtype(tsa)
+
+ assert not is_datetime64_ns_dtype("datetime64")
+ assert is_datetime64_ns_dtype("datetime64[ns]")
+ assert is_datetime64_ns_dtype(ts)
+ assert is_datetime64_ns_dtype(tsa)
+
+ assert is_datetime64_any_dtype("datetime64")
+ assert is_datetime64_any_dtype("datetime64[ns]")
+ assert is_datetime64_any_dtype(ts)
+ assert is_datetime64_any_dtype(tsa)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert not is_datetime64tz_dtype("datetime64")
+ assert not is_datetime64tz_dtype("datetime64[ns]")
+ assert not is_datetime64tz_dtype(ts)
+ assert is_datetime64tz_dtype(tsa)
+
+ @pytest.mark.parametrize("tz", ["US/Eastern", "UTC"])
+ def test_is_datetime_dtypes_with_tz(self, tz):
+ dtype = f"datetime64[ns, {tz}]"
+ assert not is_datetime64_dtype(dtype)
+
+ msg = "is_datetime64tz_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert is_datetime64tz_dtype(dtype)
+ assert is_datetime64_ns_dtype(dtype)
+ assert is_datetime64_any_dtype(dtype)
+
+ def test_is_timedelta(self):
+ assert is_timedelta64_dtype("timedelta64")
+ assert is_timedelta64_dtype("timedelta64[ns]")
+ assert not is_timedelta64_ns_dtype("timedelta64")
+ assert is_timedelta64_ns_dtype("timedelta64[ns]")
+
+ tdi = TimedeltaIndex([1e14, 2e14], dtype="timedelta64[ns]")
+ assert is_timedelta64_dtype(tdi)
+ assert is_timedelta64_ns_dtype(tdi)
+ assert is_timedelta64_ns_dtype(tdi.astype("timedelta64[ns]"))
+
+ assert not is_timedelta64_ns_dtype(Index([], dtype=np.float64))
+ assert not is_timedelta64_ns_dtype(Index([], dtype=np.int64))
+
+
+class TestIsScalar:
+ def test_is_scalar_builtin_scalars(self):
+ assert is_scalar(None)
+ assert is_scalar(True)
+ assert is_scalar(False)
+ assert is_scalar(Fraction())
+ assert is_scalar(0.0)
+ assert is_scalar(1)
+ assert is_scalar(complex(2))
+ assert is_scalar(float("NaN"))
+ assert is_scalar(np.nan)
+ assert is_scalar("foobar")
+ assert is_scalar(b"foobar")
+ assert is_scalar(datetime(2014, 1, 1))
+ assert is_scalar(date(2014, 1, 1))
+ assert is_scalar(time(12, 0))
+ assert is_scalar(timedelta(hours=1))
+ assert is_scalar(pd.NaT)
+ assert is_scalar(pd.NA)
+
+ def test_is_scalar_builtin_nonscalars(self):
+ assert not is_scalar({})
+ assert not is_scalar([])
+ assert not is_scalar([1])
+ assert not is_scalar(())
+ assert not is_scalar((1,))
+ assert not is_scalar(slice(None))
+ assert not is_scalar(Ellipsis)
+
+ def test_is_scalar_numpy_array_scalars(self):
+ assert is_scalar(np.int64(1))
+ assert is_scalar(np.float64(1.0))
+ assert is_scalar(np.int32(1))
+ assert is_scalar(np.complex64(2))
+ assert is_scalar(np.object_("foobar"))
+ assert is_scalar(np.str_("foobar"))
+ assert is_scalar(np.bytes_(b"foobar"))
+ assert is_scalar(np.datetime64("2014-01-01"))
+ assert is_scalar(np.timedelta64(1, "h"))
+
+ @pytest.mark.parametrize(
+ "zerodim",
+ [
+ np.array(1),
+ np.array("foobar"),
+ np.array(np.datetime64("2014-01-01")),
+ np.array(np.timedelta64(1, "h")),
+ np.array(np.datetime64("NaT")),
+ ],
+ )
+ def test_is_scalar_numpy_zerodim_arrays(self, zerodim):
+ assert not is_scalar(zerodim)
+ assert is_scalar(lib.item_from_zerodim(zerodim))
+
+ @pytest.mark.parametrize("arr", [np.array([]), np.array([[]])])
+ def test_is_scalar_numpy_arrays(self, arr):
+ assert not is_scalar(arr)
+ assert not is_scalar(MockNumpyLikeArray(arr))
+
+ def test_is_scalar_pandas_scalars(self):
+ assert is_scalar(Timestamp("2014-01-01"))
+ assert is_scalar(Timedelta(hours=1))
+ assert is_scalar(Period("2014-01-01"))
+ assert is_scalar(Interval(left=0, right=1))
+ assert is_scalar(DateOffset(days=1))
+ assert is_scalar(pd.offsets.Minute(3))
+
+ def test_is_scalar_pandas_containers(self):
+ assert not is_scalar(Series(dtype=object))
+ assert not is_scalar(Series([1]))
+ assert not is_scalar(DataFrame())
+ assert not is_scalar(DataFrame([[1]]))
+ assert not is_scalar(Index([]))
+ assert not is_scalar(Index([1]))
+ assert not is_scalar(Categorical([]))
+ assert not is_scalar(DatetimeIndex([])._data)
+ assert not is_scalar(TimedeltaIndex([])._data)
+ assert not is_scalar(DatetimeIndex([])._data.to_period("D"))
+ assert not is_scalar(pd.array([1, 2, 3]))
+
+ def test_is_scalar_number(self):
+ # Number() is not recognied by PyNumber_Check, so by extension
+ # is not recognized by is_scalar, but instances of non-abstract
+ # subclasses are.
+
+ class Numeric(Number):
+ def __init__(self, value) -> None:
+ self.value = value
+
+ def __int__(self) -> int:
+ return self.value
+
+ num = Numeric(1)
+ assert is_scalar(num)
+
+
+@pytest.mark.parametrize("unit", ["ms", "us", "ns"])
+def test_datetimeindex_from_empty_datetime64_array(unit):
+ idx = DatetimeIndex(np.array([], dtype=f"datetime64[{unit}]"))
+ assert len(idx) == 0
+
+
+def test_nan_to_nat_conversions():
+ df = DataFrame(
+ {"A": np.asarray(range(10), dtype="float64"), "B": Timestamp("20010101")}
+ )
+ df.iloc[3:6, :] = np.nan
+ result = df.loc[4, "B"]
+ assert result is pd.NaT
+
+ s = df["B"].copy()
+ s[8:9] = np.nan
+ assert s[8] is pd.NaT
+
+
+@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning")
+def test_is_scipy_sparse(spmatrix):
+ pytest.importorskip("scipy")
+ assert is_scipy_sparse(spmatrix([[0, 1]]))
+ assert not is_scipy_sparse(np.array([1]))
+
+
+def test_ensure_int32():
+ values = np.arange(10, dtype=np.int32)
+ result = ensure_int32(values)
+ assert result.dtype == np.int32
+
+ values = np.arange(10, dtype=np.int64)
+ result = ensure_int32(values)
+ assert result.dtype == np.int32
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/test_missing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/test_missing.py
new file mode 100644
index 0000000000000000000000000000000000000000..451ac2afd1d9110622171f858d52b36d1d53110a
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/test_missing.py
@@ -0,0 +1,908 @@
+from contextlib import nullcontext
+from datetime import datetime
+from decimal import Decimal
+
+import numpy as np
+import pytest
+
+from pandas._config import config as cf
+
+from pandas._libs import missing as libmissing
+from pandas._libs.tslibs import iNaT
+from pandas.compat.numpy import np_version_gte1p25
+
+from pandas.core.dtypes.common import (
+ is_float,
+ is_scalar,
+ pandas_dtype,
+)
+from pandas.core.dtypes.dtypes import (
+ CategoricalDtype,
+ DatetimeTZDtype,
+ IntervalDtype,
+ PeriodDtype,
+)
+from pandas.core.dtypes.missing import (
+ array_equivalent,
+ is_valid_na_for_dtype,
+ isna,
+ isnull,
+ na_value_for_dtype,
+ notna,
+ notnull,
+)
+
+import pandas as pd
+from pandas import (
+ DatetimeIndex,
+ Index,
+ NaT,
+ Series,
+ TimedeltaIndex,
+ date_range,
+)
+import pandas._testing as tm
+
+fix_now = pd.Timestamp("2021-01-01")
+fix_utcnow = pd.Timestamp("2021-01-01", tz="UTC")
+
+
+@pytest.mark.parametrize("notna_f", [notna, notnull])
+def test_notna_notnull(notna_f):
+ assert notna_f(1.0)
+ assert not notna_f(None)
+ assert not notna_f(np.nan)
+
+ msg = "use_inf_as_na option is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ with cf.option_context("mode.use_inf_as_na", False):
+ assert notna_f(np.inf)
+ assert notna_f(-np.inf)
+
+ arr = np.array([1.5, np.inf, 3.5, -np.inf])
+ result = notna_f(arr)
+ assert result.all()
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ with cf.option_context("mode.use_inf_as_na", True):
+ assert not notna_f(np.inf)
+ assert not notna_f(-np.inf)
+
+ arr = np.array([1.5, np.inf, 3.5, -np.inf])
+ result = notna_f(arr)
+ assert result.sum() == 2
+
+
+@pytest.mark.parametrize("null_func", [notna, notnull, isna, isnull])
+@pytest.mark.parametrize(
+ "ser",
+ [
+ tm.makeFloatSeries(),
+ tm.makeStringSeries(),
+ tm.makeObjectSeries(),
+ tm.makeTimeSeries(),
+ tm.makePeriodSeries(),
+ ],
+)
+def test_null_check_is_series(null_func, ser):
+ msg = "use_inf_as_na option is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ with cf.option_context("mode.use_inf_as_na", False):
+ assert isinstance(null_func(ser), Series)
+
+
+class TestIsNA:
+ def test_0d_array(self):
+ assert isna(np.array(np.nan))
+ assert not isna(np.array(0.0))
+ assert not isna(np.array(0))
+ # test object dtype
+ assert isna(np.array(np.nan, dtype=object))
+ assert not isna(np.array(0.0, dtype=object))
+ assert not isna(np.array(0, dtype=object))
+
+ @pytest.mark.parametrize("shape", [(4, 0), (4,)])
+ def test_empty_object(self, shape):
+ arr = np.empty(shape=shape, dtype=object)
+ result = isna(arr)
+ expected = np.ones(shape=shape, dtype=bool)
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("isna_f", [isna, isnull])
+ def test_isna_isnull(self, isna_f):
+ assert not isna_f(1.0)
+ assert isna_f(None)
+ assert isna_f(np.nan)
+ assert float("nan")
+ assert not isna_f(np.inf)
+ assert not isna_f(-np.inf)
+
+ # type
+ assert not isna_f(type(Series(dtype=object)))
+ assert not isna_f(type(Series(dtype=np.float64)))
+ assert not isna_f(type(pd.DataFrame()))
+
+ @pytest.mark.parametrize("isna_f", [isna, isnull])
+ @pytest.mark.parametrize(
+ "df",
+ [
+ tm.makeTimeDataFrame(),
+ tm.makePeriodFrame(),
+ tm.makeMixedDataFrame(),
+ ],
+ )
+ def test_isna_isnull_frame(self, isna_f, df):
+ # frame
+ result = isna_f(df)
+ expected = df.apply(isna_f)
+ tm.assert_frame_equal(result, expected)
+
+ def test_isna_lists(self):
+ result = isna([[False]])
+ exp = np.array([[False]])
+ tm.assert_numpy_array_equal(result, exp)
+
+ result = isna([[1], [2]])
+ exp = np.array([[False], [False]])
+ tm.assert_numpy_array_equal(result, exp)
+
+ # list of strings / unicode
+ result = isna(["foo", "bar"])
+ exp = np.array([False, False])
+ tm.assert_numpy_array_equal(result, exp)
+
+ result = isna(["foo", "bar"])
+ exp = np.array([False, False])
+ tm.assert_numpy_array_equal(result, exp)
+
+ # GH20675
+ result = isna([np.nan, "world"])
+ exp = np.array([True, False])
+ tm.assert_numpy_array_equal(result, exp)
+
+ def test_isna_nat(self):
+ result = isna([NaT])
+ exp = np.array([True])
+ tm.assert_numpy_array_equal(result, exp)
+
+ result = isna(np.array([NaT], dtype=object))
+ exp = np.array([True])
+ tm.assert_numpy_array_equal(result, exp)
+
+ def test_isna_numpy_nat(self):
+ arr = np.array(
+ [
+ NaT,
+ np.datetime64("NaT"),
+ np.timedelta64("NaT"),
+ np.datetime64("NaT", "s"),
+ ]
+ )
+ result = isna(arr)
+ expected = np.array([True] * 4)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_isna_datetime(self):
+ assert not isna(datetime.now())
+ assert notna(datetime.now())
+
+ idx = date_range("1/1/1990", periods=20)
+ exp = np.ones(len(idx), dtype=bool)
+ tm.assert_numpy_array_equal(notna(idx), exp)
+
+ idx = np.asarray(idx)
+ idx[0] = iNaT
+ idx = DatetimeIndex(idx)
+ mask = isna(idx)
+ assert mask[0]
+ exp = np.array([True] + [False] * (len(idx) - 1), dtype=bool)
+ tm.assert_numpy_array_equal(mask, exp)
+
+ # GH 9129
+ pidx = idx.to_period(freq="M")
+ mask = isna(pidx)
+ assert mask[0]
+ exp = np.array([True] + [False] * (len(idx) - 1), dtype=bool)
+ tm.assert_numpy_array_equal(mask, exp)
+
+ mask = isna(pidx[1:])
+ exp = np.zeros(len(mask), dtype=bool)
+ tm.assert_numpy_array_equal(mask, exp)
+
+ def test_isna_old_datetimelike(self):
+ # isna_old should work for dt64tz, td64, and period, not just tznaive
+ dti = date_range("2016-01-01", periods=3)
+ dta = dti._data
+ dta[-1] = NaT
+ expected = np.array([False, False, True], dtype=bool)
+
+ objs = [dta, dta.tz_localize("US/Eastern"), dta - dta, dta.to_period("D")]
+
+ for obj in objs:
+ msg = "use_inf_as_na option is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ with cf.option_context("mode.use_inf_as_na", True):
+ result = isna(obj)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (np.complex128(np.nan), True),
+ (np.float64(1), False),
+ (np.array([1, 1 + 0j, np.nan, 3]), np.array([False, False, True, False])),
+ (
+ np.array([1, 1 + 0j, np.nan, 3], dtype=object),
+ np.array([False, False, True, False]),
+ ),
+ (
+ np.array([1, 1 + 0j, np.nan, 3]).astype(object),
+ np.array([False, False, True, False]),
+ ),
+ ],
+ )
+ def test_complex(self, value, expected):
+ result = isna(value)
+ if is_scalar(result):
+ assert result is expected
+ else:
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_datetime_other_units(self):
+ idx = DatetimeIndex(["2011-01-01", "NaT", "2011-01-02"])
+ exp = np.array([False, True, False])
+ tm.assert_numpy_array_equal(isna(idx), exp)
+ tm.assert_numpy_array_equal(notna(idx), ~exp)
+ tm.assert_numpy_array_equal(isna(idx.values), exp)
+ tm.assert_numpy_array_equal(notna(idx.values), ~exp)
+
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "datetime64[D]",
+ "datetime64[h]",
+ "datetime64[m]",
+ "datetime64[s]",
+ "datetime64[ms]",
+ "datetime64[us]",
+ "datetime64[ns]",
+ ],
+ )
+ def test_datetime_other_units_astype(self, dtype):
+ idx = DatetimeIndex(["2011-01-01", "NaT", "2011-01-02"])
+ values = idx.values.astype(dtype)
+
+ exp = np.array([False, True, False])
+ tm.assert_numpy_array_equal(isna(values), exp)
+ tm.assert_numpy_array_equal(notna(values), ~exp)
+
+ exp = Series([False, True, False])
+ s = Series(values)
+ tm.assert_series_equal(isna(s), exp)
+ tm.assert_series_equal(notna(s), ~exp)
+ s = Series(values, dtype=object)
+ tm.assert_series_equal(isna(s), exp)
+ tm.assert_series_equal(notna(s), ~exp)
+
+ def test_timedelta_other_units(self):
+ idx = TimedeltaIndex(["1 days", "NaT", "2 days"])
+ exp = np.array([False, True, False])
+ tm.assert_numpy_array_equal(isna(idx), exp)
+ tm.assert_numpy_array_equal(notna(idx), ~exp)
+ tm.assert_numpy_array_equal(isna(idx.values), exp)
+ tm.assert_numpy_array_equal(notna(idx.values), ~exp)
+
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "timedelta64[D]",
+ "timedelta64[h]",
+ "timedelta64[m]",
+ "timedelta64[s]",
+ "timedelta64[ms]",
+ "timedelta64[us]",
+ "timedelta64[ns]",
+ ],
+ )
+ def test_timedelta_other_units_dtype(self, dtype):
+ idx = TimedeltaIndex(["1 days", "NaT", "2 days"])
+ values = idx.values.astype(dtype)
+
+ exp = np.array([False, True, False])
+ tm.assert_numpy_array_equal(isna(values), exp)
+ tm.assert_numpy_array_equal(notna(values), ~exp)
+
+ exp = Series([False, True, False])
+ s = Series(values)
+ tm.assert_series_equal(isna(s), exp)
+ tm.assert_series_equal(notna(s), ~exp)
+ s = Series(values, dtype=object)
+ tm.assert_series_equal(isna(s), exp)
+ tm.assert_series_equal(notna(s), ~exp)
+
+ def test_period(self):
+ idx = pd.PeriodIndex(["2011-01", "NaT", "2012-01"], freq="M")
+ exp = np.array([False, True, False])
+ tm.assert_numpy_array_equal(isna(idx), exp)
+ tm.assert_numpy_array_equal(notna(idx), ~exp)
+
+ exp = Series([False, True, False])
+ s = Series(idx)
+ tm.assert_series_equal(isna(s), exp)
+ tm.assert_series_equal(notna(s), ~exp)
+ s = Series(idx, dtype=object)
+ tm.assert_series_equal(isna(s), exp)
+ tm.assert_series_equal(notna(s), ~exp)
+
+ def test_decimal(self):
+ # scalars GH#23530
+ a = Decimal(1.0)
+ assert isna(a) is False
+ assert notna(a) is True
+
+ b = Decimal("NaN")
+ assert isna(b) is True
+ assert notna(b) is False
+
+ # array
+ arr = np.array([a, b])
+ expected = np.array([False, True])
+ result = isna(arr)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = notna(arr)
+ tm.assert_numpy_array_equal(result, ~expected)
+
+ # series
+ ser = Series(arr)
+ expected = Series(expected)
+ result = isna(ser)
+ tm.assert_series_equal(result, expected)
+
+ result = notna(ser)
+ tm.assert_series_equal(result, ~expected)
+
+ # index
+ idx = Index(arr)
+ expected = np.array([False, True])
+ result = isna(idx)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = notna(idx)
+ tm.assert_numpy_array_equal(result, ~expected)
+
+
+@pytest.mark.parametrize("dtype_equal", [True, False])
+def test_array_equivalent(dtype_equal):
+ assert array_equivalent(
+ np.array([np.nan, np.nan]), np.array([np.nan, np.nan]), dtype_equal=dtype_equal
+ )
+ assert array_equivalent(
+ np.array([np.nan, 1, np.nan]),
+ np.array([np.nan, 1, np.nan]),
+ dtype_equal=dtype_equal,
+ )
+ assert array_equivalent(
+ np.array([np.nan, None], dtype="object"),
+ np.array([np.nan, None], dtype="object"),
+ dtype_equal=dtype_equal,
+ )
+ # Check the handling of nested arrays in array_equivalent_object
+ assert array_equivalent(
+ np.array([np.array([np.nan, None], dtype="object"), None], dtype="object"),
+ np.array([np.array([np.nan, None], dtype="object"), None], dtype="object"),
+ dtype_equal=dtype_equal,
+ )
+ assert array_equivalent(
+ np.array([np.nan, 1 + 1j], dtype="complex"),
+ np.array([np.nan, 1 + 1j], dtype="complex"),
+ dtype_equal=dtype_equal,
+ )
+ assert not array_equivalent(
+ np.array([np.nan, 1 + 1j], dtype="complex"),
+ np.array([np.nan, 1 + 2j], dtype="complex"),
+ dtype_equal=dtype_equal,
+ )
+ assert not array_equivalent(
+ np.array([np.nan, 1, np.nan]),
+ np.array([np.nan, 2, np.nan]),
+ dtype_equal=dtype_equal,
+ )
+ assert not array_equivalent(
+ np.array(["a", "b", "c", "d"]), np.array(["e", "e"]), dtype_equal=dtype_equal
+ )
+ assert array_equivalent(
+ Index([0, np.nan]), Index([0, np.nan]), dtype_equal=dtype_equal
+ )
+ assert not array_equivalent(
+ Index([0, np.nan]), Index([1, np.nan]), dtype_equal=dtype_equal
+ )
+ assert array_equivalent(
+ DatetimeIndex([0, np.nan]), DatetimeIndex([0, np.nan]), dtype_equal=dtype_equal
+ )
+ assert not array_equivalent(
+ DatetimeIndex([0, np.nan]), DatetimeIndex([1, np.nan]), dtype_equal=dtype_equal
+ )
+ assert array_equivalent(
+ TimedeltaIndex([0, np.nan]),
+ TimedeltaIndex([0, np.nan]),
+ dtype_equal=dtype_equal,
+ )
+ assert not array_equivalent(
+ TimedeltaIndex([0, np.nan]),
+ TimedeltaIndex([1, np.nan]),
+ dtype_equal=dtype_equal,
+ )
+
+ dti1 = DatetimeIndex([0, np.nan], tz="US/Eastern")
+ dti2 = DatetimeIndex([0, np.nan], tz="CET")
+ dti3 = DatetimeIndex([1, np.nan], tz="US/Eastern")
+
+ assert array_equivalent(
+ dti1,
+ dti1,
+ dtype_equal=dtype_equal,
+ )
+ assert not array_equivalent(
+ dti1,
+ dti3,
+ dtype_equal=dtype_equal,
+ )
+ # The rest are not dtype_equal
+ assert not array_equivalent(DatetimeIndex([0, np.nan]), dti1)
+ assert array_equivalent(
+ dti2,
+ dti1,
+ )
+
+ assert not array_equivalent(DatetimeIndex([0, np.nan]), TimedeltaIndex([0, np.nan]))
+
+
+@pytest.mark.parametrize(
+ "val", [1, 1.1, 1 + 1j, True, "abc", [1, 2], (1, 2), {1, 2}, {"a": 1}, None]
+)
+def test_array_equivalent_series(val):
+ arr = np.array([1, 2])
+ msg = "elementwise comparison failed"
+ cm = (
+ # stacklevel is chosen to make sense when called from .equals
+ tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False)
+ if isinstance(val, str) and not np_version_gte1p25
+ else nullcontext()
+ )
+ with cm:
+ assert not array_equivalent(Series([arr, arr]), Series([arr, val]))
+
+
+def test_array_equivalent_array_mismatched_shape():
+ # to trigger the motivating bug, the first N elements of the arrays need
+ # to match
+ first = np.array([1, 2, 3])
+ second = np.array([1, 2])
+
+ left = Series([first, "a"], dtype=object)
+ right = Series([second, "a"], dtype=object)
+ assert not array_equivalent(left, right)
+
+
+def test_array_equivalent_array_mismatched_dtype():
+ # same shape, different dtype can still be equivalent
+ first = np.array([1, 2], dtype=np.float64)
+ second = np.array([1, 2])
+
+ left = Series([first, "a"], dtype=object)
+ right = Series([second, "a"], dtype=object)
+ assert array_equivalent(left, right)
+
+
+def test_array_equivalent_different_dtype_but_equal():
+ # Unclear if this is exposed anywhere in the public-facing API
+ assert array_equivalent(np.array([1, 2]), np.array([1.0, 2.0]))
+
+
+@pytest.mark.parametrize(
+ "lvalue, rvalue",
+ [
+ # There are 3 variants for each of lvalue and rvalue. We include all
+ # three for the tz-naive `now` and exclude the datetim64 variant
+ # for utcnow because it drops tzinfo.
+ (fix_now, fix_utcnow),
+ (fix_now.to_datetime64(), fix_utcnow),
+ (fix_now.to_pydatetime(), fix_utcnow),
+ (fix_now, fix_utcnow),
+ (fix_now.to_datetime64(), fix_utcnow.to_pydatetime()),
+ (fix_now.to_pydatetime(), fix_utcnow.to_pydatetime()),
+ ],
+)
+def test_array_equivalent_tzawareness(lvalue, rvalue):
+ # we shouldn't raise if comparing tzaware and tznaive datetimes
+ left = np.array([lvalue], dtype=object)
+ right = np.array([rvalue], dtype=object)
+
+ assert not array_equivalent(left, right, strict_nan=True)
+ assert not array_equivalent(left, right, strict_nan=False)
+
+
+def test_array_equivalent_compat():
+ # see gh-13388
+ m = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)])
+ n = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)])
+ assert array_equivalent(m, n, strict_nan=True)
+ assert array_equivalent(m, n, strict_nan=False)
+
+ m = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)])
+ n = np.array([(1, 2), (4, 3)], dtype=[("a", int), ("b", float)])
+ assert not array_equivalent(m, n, strict_nan=True)
+ assert not array_equivalent(m, n, strict_nan=False)
+
+ m = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)])
+ n = np.array([(1, 2), (3, 4)], dtype=[("b", int), ("a", float)])
+ assert not array_equivalent(m, n, strict_nan=True)
+ assert not array_equivalent(m, n, strict_nan=False)
+
+
+@pytest.mark.parametrize("dtype", ["O", "S", "U"])
+def test_array_equivalent_str(dtype):
+ assert array_equivalent(
+ np.array(["A", "B"], dtype=dtype), np.array(["A", "B"], dtype=dtype)
+ )
+ assert not array_equivalent(
+ np.array(["A", "B"], dtype=dtype), np.array(["A", "X"], dtype=dtype)
+ )
+
+
+@pytest.mark.parametrize(
+ "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False]
+)
+def test_array_equivalent_nested(strict_nan):
+ # reached in groupby aggregations, make sure we use np.any when checking
+ # if the comparison is truthy
+ left = np.array([np.array([50, 70, 90]), np.array([20, 30])], dtype=object)
+ right = np.array([np.array([50, 70, 90]), np.array([20, 30])], dtype=object)
+
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ left = np.empty(2, dtype=object)
+ left[:] = [np.array([50, 70, 90]), np.array([20, 30, 40])]
+ right = np.empty(2, dtype=object)
+ right[:] = [np.array([50, 70, 90]), np.array([20, 30, 40])]
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ left = np.array([np.array([50, 50, 50]), np.array([40, 40])], dtype=object)
+ right = np.array([50, 40])
+ assert not array_equivalent(left, right, strict_nan=strict_nan)
+
+
+@pytest.mark.filterwarnings("ignore:elementwise comparison failed:DeprecationWarning")
+@pytest.mark.parametrize(
+ "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False]
+)
+def test_array_equivalent_nested2(strict_nan):
+ # more than one level of nesting
+ left = np.array(
+ [
+ np.array([np.array([50, 70]), np.array([90])], dtype=object),
+ np.array([np.array([20, 30])], dtype=object),
+ ],
+ dtype=object,
+ )
+ right = np.array(
+ [
+ np.array([np.array([50, 70]), np.array([90])], dtype=object),
+ np.array([np.array([20, 30])], dtype=object),
+ ],
+ dtype=object,
+ )
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ left = np.array([np.array([np.array([50, 50, 50])], dtype=object)], dtype=object)
+ right = np.array([50])
+ assert not array_equivalent(left, right, strict_nan=strict_nan)
+
+
+@pytest.mark.parametrize(
+ "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False]
+)
+def test_array_equivalent_nested_list(strict_nan):
+ left = np.array([[50, 70, 90], [20, 30]], dtype=object)
+ right = np.array([[50, 70, 90], [20, 30]], dtype=object)
+
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ left = np.array([[50, 50, 50], [40, 40]], dtype=object)
+ right = np.array([50, 40])
+ assert not array_equivalent(left, right, strict_nan=strict_nan)
+
+
+@pytest.mark.filterwarnings("ignore:elementwise comparison failed:DeprecationWarning")
+@pytest.mark.xfail(reason="failing")
+@pytest.mark.parametrize("strict_nan", [True, False])
+def test_array_equivalent_nested_mixed_list(strict_nan):
+ # mixed arrays / lists in left and right
+ # https://github.com/pandas-dev/pandas/issues/50360
+ left = np.array([np.array([1, 2, 3]), np.array([4, 5])], dtype=object)
+ right = np.array([[1, 2, 3], [4, 5]], dtype=object)
+
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ # multiple levels of nesting
+ left = np.array(
+ [
+ np.array([np.array([1, 2, 3]), np.array([4, 5])], dtype=object),
+ np.array([np.array([6]), np.array([7, 8]), np.array([9])], dtype=object),
+ ],
+ dtype=object,
+ )
+ right = np.array([[[1, 2, 3], [4, 5]], [[6], [7, 8], [9]]], dtype=object)
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ # same-length lists
+ subarr = np.empty(2, dtype=object)
+ subarr[:] = [
+ np.array([None, "b"], dtype=object),
+ np.array(["c", "d"], dtype=object),
+ ]
+ left = np.array([subarr, None], dtype=object)
+ right = np.array([[[None, "b"], ["c", "d"]], None], dtype=object)
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+
+@pytest.mark.xfail(reason="failing")
+@pytest.mark.parametrize("strict_nan", [True, False])
+def test_array_equivalent_nested_dicts(strict_nan):
+ left = np.array([{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object)
+ right = np.array(
+ [{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object
+ )
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ right2 = np.array([{"f1": 1, "f2": ["a", "b"]}], dtype=object)
+ assert array_equivalent(left, right2, strict_nan=strict_nan)
+ assert not array_equivalent(left, right2[::-1], strict_nan=strict_nan)
+
+
+def test_array_equivalent_index_with_tuples():
+ # GH#48446
+ idx1 = Index(np.array([(pd.NA, 4), (1, 1)], dtype="object"))
+ idx2 = Index(np.array([(1, 1), (pd.NA, 4)], dtype="object"))
+ assert not array_equivalent(idx1, idx2)
+ assert not idx1.equals(idx2)
+ assert not array_equivalent(idx2, idx1)
+ assert not idx2.equals(idx1)
+
+ idx1 = Index(np.array([(4, pd.NA), (1, 1)], dtype="object"))
+ idx2 = Index(np.array([(1, 1), (4, pd.NA)], dtype="object"))
+ assert not array_equivalent(idx1, idx2)
+ assert not idx1.equals(idx2)
+ assert not array_equivalent(idx2, idx1)
+ assert not idx2.equals(idx1)
+
+
+@pytest.mark.parametrize(
+ "dtype, na_value",
+ [
+ # Datetime-like
+ (np.dtype("M8[ns]"), np.datetime64("NaT", "ns")),
+ (np.dtype("m8[ns]"), np.timedelta64("NaT", "ns")),
+ (DatetimeTZDtype.construct_from_string("datetime64[ns, US/Eastern]"), NaT),
+ (PeriodDtype("M"), NaT),
+ # Integer
+ ("u1", 0),
+ ("u2", 0),
+ ("u4", 0),
+ ("u8", 0),
+ ("i1", 0),
+ ("i2", 0),
+ ("i4", 0),
+ ("i8", 0),
+ # Bool
+ ("bool", False),
+ # Float
+ ("f2", np.nan),
+ ("f4", np.nan),
+ ("f8", np.nan),
+ # Object
+ ("O", np.nan),
+ # Interval
+ (IntervalDtype(), np.nan),
+ ],
+)
+def test_na_value_for_dtype(dtype, na_value):
+ result = na_value_for_dtype(pandas_dtype(dtype))
+ # identify check doesn't work for datetime64/timedelta64("NaT") bc they
+ # are not singletons
+ assert result is na_value or (
+ isna(result) and isna(na_value) and type(result) is type(na_value)
+ )
+
+
+class TestNAObj:
+ def _check_behavior(self, arr, expected):
+ result = libmissing.isnaobj(arr)
+ tm.assert_numpy_array_equal(result, expected)
+ result = libmissing.isnaobj(arr, inf_as_na=True)
+ tm.assert_numpy_array_equal(result, expected)
+
+ arr = np.atleast_2d(arr)
+ expected = np.atleast_2d(expected)
+
+ result = libmissing.isnaobj(arr)
+ tm.assert_numpy_array_equal(result, expected)
+ result = libmissing.isnaobj(arr, inf_as_na=True)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # Test fortran order
+ arr = arr.copy(order="F")
+ result = libmissing.isnaobj(arr)
+ tm.assert_numpy_array_equal(result, expected)
+ result = libmissing.isnaobj(arr, inf_as_na=True)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_basic(self):
+ arr = np.array([1, None, "foo", -5.1, NaT, np.nan])
+ expected = np.array([False, True, False, False, True, True])
+
+ self._check_behavior(arr, expected)
+
+ def test_non_obj_dtype(self):
+ arr = np.array([1, 3, np.nan, 5], dtype=float)
+ expected = np.array([False, False, True, False])
+
+ self._check_behavior(arr, expected)
+
+ def test_empty_arr(self):
+ arr = np.array([])
+ expected = np.array([], dtype=bool)
+
+ self._check_behavior(arr, expected)
+
+ def test_empty_str_inp(self):
+ arr = np.array([""]) # empty but not na
+ expected = np.array([False])
+
+ self._check_behavior(arr, expected)
+
+ def test_empty_like(self):
+ # see gh-13717: no segfaults!
+ arr = np.empty_like([None])
+ expected = np.array([True])
+
+ self._check_behavior(arr, expected)
+
+
+m8_units = ["as", "ps", "ns", "us", "ms", "s", "m", "h", "D", "W", "M", "Y"]
+
+na_vals = (
+ [
+ None,
+ NaT,
+ float("NaN"),
+ complex("NaN"),
+ np.nan,
+ np.float64("NaN"),
+ np.float32("NaN"),
+ np.complex64(np.nan),
+ np.complex128(np.nan),
+ np.datetime64("NaT"),
+ np.timedelta64("NaT"),
+ ]
+ + [np.datetime64("NaT", unit) for unit in m8_units]
+ + [np.timedelta64("NaT", unit) for unit in m8_units]
+)
+
+inf_vals = [
+ float("inf"),
+ float("-inf"),
+ complex("inf"),
+ complex("-inf"),
+ np.inf,
+ -np.inf,
+]
+
+int_na_vals = [
+ # Values that match iNaT, which we treat as null in specific cases
+ np.int64(NaT._value),
+ int(NaT._value),
+]
+
+sometimes_na_vals = [Decimal("NaN")]
+
+never_na_vals = [
+ # float/complex values that when viewed as int64 match iNaT
+ -0.0,
+ np.float64("-0.0"),
+ -0j,
+ np.complex64(-0j),
+]
+
+
+class TestLibMissing:
+ @pytest.mark.parametrize("func", [libmissing.checknull, isna])
+ @pytest.mark.parametrize(
+ "value", na_vals + sometimes_na_vals # type: ignore[operator]
+ )
+ def test_checknull_na_vals(self, func, value):
+ assert func(value)
+
+ @pytest.mark.parametrize("func", [libmissing.checknull, isna])
+ @pytest.mark.parametrize("value", inf_vals)
+ def test_checknull_inf_vals(self, func, value):
+ assert not func(value)
+
+ @pytest.mark.parametrize("func", [libmissing.checknull, isna])
+ @pytest.mark.parametrize("value", int_na_vals)
+ def test_checknull_intna_vals(self, func, value):
+ assert not func(value)
+
+ @pytest.mark.parametrize("func", [libmissing.checknull, isna])
+ @pytest.mark.parametrize("value", never_na_vals)
+ def test_checknull_never_na_vals(self, func, value):
+ assert not func(value)
+
+ @pytest.mark.parametrize(
+ "value", na_vals + sometimes_na_vals # type: ignore[operator]
+ )
+ def test_checknull_old_na_vals(self, value):
+ assert libmissing.checknull(value, inf_as_na=True)
+
+ @pytest.mark.parametrize("value", inf_vals)
+ def test_checknull_old_inf_vals(self, value):
+ assert libmissing.checknull(value, inf_as_na=True)
+
+ @pytest.mark.parametrize("value", int_na_vals)
+ def test_checknull_old_intna_vals(self, value):
+ assert not libmissing.checknull(value, inf_as_na=True)
+
+ @pytest.mark.parametrize("value", int_na_vals)
+ def test_checknull_old_never_na_vals(self, value):
+ assert not libmissing.checknull(value, inf_as_na=True)
+
+ def test_is_matching_na(self, nulls_fixture, nulls_fixture2):
+ left = nulls_fixture
+ right = nulls_fixture2
+
+ assert libmissing.is_matching_na(left, left)
+
+ if left is right:
+ assert libmissing.is_matching_na(left, right)
+ elif is_float(left) and is_float(right):
+ # np.nan vs float("NaN") we consider as matching
+ assert libmissing.is_matching_na(left, right)
+ elif type(left) is type(right):
+ # e.g. both Decimal("NaN")
+ assert libmissing.is_matching_na(left, right)
+ else:
+ assert not libmissing.is_matching_na(left, right)
+
+ def test_is_matching_na_nan_matches_none(self):
+ assert not libmissing.is_matching_na(None, np.nan)
+ assert not libmissing.is_matching_na(np.nan, None)
+
+ assert libmissing.is_matching_na(None, np.nan, nan_matches_none=True)
+ assert libmissing.is_matching_na(np.nan, None, nan_matches_none=True)
+
+
+class TestIsValidNAForDtype:
+ def test_is_valid_na_for_dtype_interval(self):
+ dtype = IntervalDtype("int64", "left")
+ assert not is_valid_na_for_dtype(NaT, dtype)
+
+ dtype = IntervalDtype("datetime64[ns]", "both")
+ assert not is_valid_na_for_dtype(NaT, dtype)
+
+ def test_is_valid_na_for_dtype_categorical(self):
+ dtype = CategoricalDtype(categories=[0, 1, 2])
+ assert is_valid_na_for_dtype(np.nan, dtype)
+
+ assert not is_valid_na_for_dtype(NaT, dtype)
+ assert not is_valid_na_for_dtype(np.datetime64("NaT", "ns"), dtype)
+ assert not is_valid_na_for_dtype(np.timedelta64("NaT", "ns"), dtype)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b7945b15ed83be7ad8093dcbb6ccb7e9bcd4e72
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/conftest.py
@@ -0,0 +1,221 @@
+import operator
+
+import pytest
+
+from pandas import (
+ Series,
+ options,
+)
+
+
+@pytest.fixture
+def dtype():
+ """A fixture providing the ExtensionDtype to validate."""
+ raise NotImplementedError
+
+
+@pytest.fixture
+def data():
+ """
+ Length-100 array for this type.
+
+ * data[0] and data[1] should both be non missing
+ * data[0] and data[1] should not be equal
+ """
+ raise NotImplementedError
+
+
+@pytest.fixture
+def data_for_twos(dtype):
+ """
+ Length-100 array in which all the elements are two.
+
+ Call pytest.skip in your fixture if the dtype does not support divmod.
+ """
+ if not (dtype._is_numeric or dtype.kind == "m"):
+ # Object-dtypes may want to allow this, but for the most part
+ # only numeric and timedelta-like dtypes will need to implement this.
+ pytest.skip("Not a numeric dtype")
+
+ raise NotImplementedError
+
+
+@pytest.fixture
+def data_missing():
+ """Length-2 array with [NA, Valid]"""
+ raise NotImplementedError
+
+
+@pytest.fixture(params=["data", "data_missing"])
+def all_data(request, data, data_missing):
+ """Parametrized fixture giving 'data' and 'data_missing'"""
+ if request.param == "data":
+ return data
+ elif request.param == "data_missing":
+ return data_missing
+
+
+@pytest.fixture
+def data_repeated(data):
+ """
+ Generate many datasets.
+
+ Parameters
+ ----------
+ data : fixture implementing `data`
+
+ Returns
+ -------
+ Callable[[int], Generator]:
+ A callable that takes a `count` argument and
+ returns a generator yielding `count` datasets.
+ """
+
+ def gen(count):
+ for _ in range(count):
+ yield data
+
+ return gen
+
+
+@pytest.fixture
+def data_for_sorting():
+ """
+ Length-3 array with a known sort order.
+
+ This should be three items [B, C, A] with
+ A < B < C
+
+ For boolean dtypes (for which there are only 2 values available),
+ set B=C=True
+ """
+ raise NotImplementedError
+
+
+@pytest.fixture
+def data_missing_for_sorting():
+ """
+ Length-3 array with a known sort order.
+
+ This should be three items [B, NA, A] with
+ A < B and NA missing.
+ """
+ raise NotImplementedError
+
+
+@pytest.fixture
+def na_cmp():
+ """
+ Binary operator for comparing NA values.
+
+ Should return a function of two arguments that returns
+ True if both arguments are (scalar) NA for your type.
+
+ By default, uses ``operator.is_``
+ """
+ return operator.is_
+
+
+@pytest.fixture
+def na_value(dtype):
+ """The scalar missing value for this type. Default dtype.na_value"""
+ return dtype.na_value
+
+
+@pytest.fixture
+def data_for_grouping():
+ """
+ Data for factorization, grouping, and unique tests.
+
+ Expected to be like [B, B, NA, NA, A, A, B, C]
+
+ Where A < B < C and NA is missing.
+
+ If a dtype has _is_boolean = True, i.e. only 2 unique non-NA entries,
+ then set C=B.
+ """
+ raise NotImplementedError
+
+
+@pytest.fixture(params=[True, False])
+def box_in_series(request):
+ """Whether to box the data in a Series"""
+ return request.param
+
+
+@pytest.fixture(
+ params=[
+ lambda x: 1,
+ lambda x: [1] * len(x),
+ lambda x: Series([1] * len(x)),
+ lambda x: x,
+ ],
+ ids=["scalar", "list", "series", "object"],
+)
+def groupby_apply_op(request):
+ """
+ Functions to test groupby.apply().
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def as_frame(request):
+ """
+ Boolean fixture to support Series and Series.to_frame() comparison testing.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def as_series(request):
+ """
+ Boolean fixture to support arr and Series(arr) comparison testing.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def use_numpy(request):
+ """
+ Boolean fixture to support comparison testing of ExtensionDtype array
+ and numpy array.
+ """
+ return request.param
+
+
+@pytest.fixture(params=["ffill", "bfill"])
+def fillna_method(request):
+ """
+ Parametrized fixture giving method parameters 'ffill' and 'bfill' for
+ Series.fillna(method=) testing.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def as_array(request):
+ """
+ Boolean fixture to support ExtensionDtype _from_sequence method testing.
+ """
+ return request.param
+
+
+@pytest.fixture
+def invalid_scalar(data):
+ """
+ A scalar that *cannot* be held by this ExtensionArray.
+
+ The default should work for most subclasses, but is not guaranteed.
+
+ If the array can hold any item (i.e. object dtype), then use pytest.skip.
+ """
+ return object.__new__(object)
+
+
+@pytest.fixture
+def using_copy_on_write() -> bool:
+ """
+ Fixture to check if Copy-on-Write is enabled.
+ """
+ return options.mode.copy_on_write and options.mode.data_manager == "block"
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_arrow.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_arrow.py
new file mode 100644
index 0000000000000000000000000000000000000000..61474aa94d1c8f0ab7d41c9e7f43b3e5099258c8
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_arrow.py
@@ -0,0 +1,3102 @@
+"""
+This file contains a minimal set of tests for compliance with the extension
+array interface test suite, and should contain no other tests.
+The test suite for the full functionality of the array is located in
+`pandas/tests/arrays/`.
+The tests in this file are inherited from the BaseExtensionTests, and only
+minimal tweaks should be applied to get the tests passing (by overwriting a
+parent method).
+Additional tests should either be added to one of the BaseExtensionTests
+classes (if they are relevant for the extension interface for all dtypes), or
+be added to the array-specific tests in `pandas/tests/arrays/`.
+"""
+from __future__ import annotations
+
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
+from decimal import Decimal
+from io import (
+ BytesIO,
+ StringIO,
+)
+import operator
+import pickle
+import re
+
+import numpy as np
+import pytest
+
+from pandas._libs import lib
+from pandas._libs.tslibs import timezones
+from pandas.compat import (
+ PY311,
+ is_ci_environment,
+ is_platform_windows,
+ pa_version_under7p0,
+ pa_version_under8p0,
+ pa_version_under9p0,
+ pa_version_under11p0,
+ pa_version_under13p0,
+ pa_version_under14p0,
+)
+
+from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
+ CategoricalDtypeType,
+)
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.api.extensions import no_default
+from pandas.api.types import (
+ is_bool_dtype,
+ is_float_dtype,
+ is_integer_dtype,
+ is_numeric_dtype,
+ is_signed_integer_dtype,
+ is_string_dtype,
+ is_unsigned_integer_dtype,
+)
+from pandas.tests.extension import base
+
+pa = pytest.importorskip("pyarrow", minversion="7.0.0")
+
+from pandas.core.arrays.arrow.array import ArrowExtensionArray
+from pandas.core.arrays.arrow.extension_types import ArrowPeriodType
+
+
+def _require_timezone_database(request):
+ if is_platform_windows() and is_ci_environment():
+ mark = pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason=(
+ "TODO: Set ARROW_TIMEZONE_DATABASE environment variable "
+ "on CI to path to the tzdata for pyarrow."
+ ),
+ )
+ request.node.add_marker(mark)
+
+
+@pytest.fixture(params=tm.ALL_PYARROW_DTYPES, ids=str)
+def dtype(request):
+ return ArrowDtype(pyarrow_dtype=request.param)
+
+
+@pytest.fixture
+def data(dtype):
+ pa_dtype = dtype.pyarrow_dtype
+ if pa.types.is_boolean(pa_dtype):
+ data = [True, False] * 4 + [None] + [True, False] * 44 + [None] + [True, False]
+ elif pa.types.is_floating(pa_dtype):
+ data = [1.0, 0.0] * 4 + [None] + [-2.0, -1.0] * 44 + [None] + [0.5, 99.5]
+ elif pa.types.is_signed_integer(pa_dtype):
+ data = [1, 0] * 4 + [None] + [-2, -1] * 44 + [None] + [1, 99]
+ elif pa.types.is_unsigned_integer(pa_dtype):
+ data = [1, 0] * 4 + [None] + [2, 1] * 44 + [None] + [1, 99]
+ elif pa.types.is_decimal(pa_dtype):
+ data = (
+ [Decimal("1"), Decimal("0.0")] * 4
+ + [None]
+ + [Decimal("-2.0"), Decimal("-1.0")] * 44
+ + [None]
+ + [Decimal("0.5"), Decimal("33.123")]
+ )
+ elif pa.types.is_date(pa_dtype):
+ data = (
+ [date(2022, 1, 1), date(1999, 12, 31)] * 4
+ + [None]
+ + [date(2022, 1, 1), date(2022, 1, 1)] * 44
+ + [None]
+ + [date(1999, 12, 31), date(1999, 12, 31)]
+ )
+ elif pa.types.is_timestamp(pa_dtype):
+ data = (
+ [datetime(2020, 1, 1, 1, 1, 1, 1), datetime(1999, 1, 1, 1, 1, 1, 1)] * 4
+ + [None]
+ + [datetime(2020, 1, 1, 1), datetime(1999, 1, 1, 1)] * 44
+ + [None]
+ + [datetime(2020, 1, 1), datetime(1999, 1, 1)]
+ )
+ elif pa.types.is_duration(pa_dtype):
+ data = (
+ [timedelta(1), timedelta(1, 1)] * 4
+ + [None]
+ + [timedelta(-1), timedelta(0)] * 44
+ + [None]
+ + [timedelta(-10), timedelta(10)]
+ )
+ elif pa.types.is_time(pa_dtype):
+ data = (
+ [time(12, 0), time(0, 12)] * 4
+ + [None]
+ + [time(0, 0), time(1, 1)] * 44
+ + [None]
+ + [time(0, 5), time(5, 0)]
+ )
+ elif pa.types.is_string(pa_dtype):
+ data = ["a", "b"] * 4 + [None] + ["1", "2"] * 44 + [None] + ["!", ">"]
+ elif pa.types.is_binary(pa_dtype):
+ data = [b"a", b"b"] * 4 + [None] + [b"1", b"2"] * 44 + [None] + [b"!", b">"]
+ else:
+ raise NotImplementedError
+ return pd.array(data, dtype=dtype)
+
+
+@pytest.fixture
+def data_missing(data):
+ """Length-2 array with [NA, Valid]"""
+ return type(data)._from_sequence([None, data[0]], dtype=data.dtype)
+
+
+@pytest.fixture(params=["data", "data_missing"])
+def all_data(request, data, data_missing):
+ """Parametrized fixture returning 'data' or 'data_missing' integer arrays.
+
+ Used to test dtype conversion with and without missing values.
+ """
+ if request.param == "data":
+ return data
+ elif request.param == "data_missing":
+ return data_missing
+
+
+@pytest.fixture
+def data_for_grouping(dtype):
+ """
+ Data for factorization, grouping, and unique tests.
+
+ Expected to be like [B, B, NA, NA, A, A, B, C]
+
+ Where A < B < C and NA is missing
+ """
+ pa_dtype = dtype.pyarrow_dtype
+ if pa.types.is_boolean(pa_dtype):
+ A = False
+ B = True
+ C = True
+ elif pa.types.is_floating(pa_dtype):
+ A = -1.1
+ B = 0.0
+ C = 1.1
+ elif pa.types.is_signed_integer(pa_dtype):
+ A = -1
+ B = 0
+ C = 1
+ elif pa.types.is_unsigned_integer(pa_dtype):
+ A = 0
+ B = 1
+ C = 10
+ elif pa.types.is_date(pa_dtype):
+ A = date(1999, 12, 31)
+ B = date(2010, 1, 1)
+ C = date(2022, 1, 1)
+ elif pa.types.is_timestamp(pa_dtype):
+ A = datetime(1999, 1, 1, 1, 1, 1, 1)
+ B = datetime(2020, 1, 1)
+ C = datetime(2020, 1, 1, 1)
+ elif pa.types.is_duration(pa_dtype):
+ A = timedelta(-1)
+ B = timedelta(0)
+ C = timedelta(1, 4)
+ elif pa.types.is_time(pa_dtype):
+ A = time(0, 0)
+ B = time(0, 12)
+ C = time(12, 12)
+ elif pa.types.is_string(pa_dtype):
+ A = "a"
+ B = "b"
+ C = "c"
+ elif pa.types.is_binary(pa_dtype):
+ A = b"a"
+ B = b"b"
+ C = b"c"
+ elif pa.types.is_decimal(pa_dtype):
+ A = Decimal("-1.1")
+ B = Decimal("0.0")
+ C = Decimal("1.1")
+ else:
+ raise NotImplementedError
+ return pd.array([B, B, None, None, A, A, B, C], dtype=dtype)
+
+
+@pytest.fixture
+def data_for_sorting(data_for_grouping):
+ """
+ Length-3 array with a known sort order.
+
+ This should be three items [B, C, A] with
+ A < B < C
+ """
+ return type(data_for_grouping)._from_sequence(
+ [data_for_grouping[0], data_for_grouping[7], data_for_grouping[4]],
+ dtype=data_for_grouping.dtype,
+ )
+
+
+@pytest.fixture
+def data_missing_for_sorting(data_for_grouping):
+ """
+ Length-3 array with a known sort order.
+
+ This should be three items [B, NA, A] with
+ A < B and NA missing.
+ """
+ return type(data_for_grouping)._from_sequence(
+ [data_for_grouping[0], data_for_grouping[2], data_for_grouping[4]],
+ dtype=data_for_grouping.dtype,
+ )
+
+
+@pytest.fixture
+def data_for_twos(data):
+ """Length-100 array in which all the elements are two."""
+ pa_dtype = data.dtype.pyarrow_dtype
+ if (
+ pa.types.is_integer(pa_dtype)
+ or pa.types.is_floating(pa_dtype)
+ or pa.types.is_decimal(pa_dtype)
+ or pa.types.is_duration(pa_dtype)
+ ):
+ return pd.array([2] * 100, dtype=data.dtype)
+ # tests will be xfailed where 2 is not a valid scalar for pa_dtype
+ return data
+ # TODO: skip otherwise?
+
+
+class TestBaseCasting(base.BaseCastingTests):
+ def test_astype_str(self, data, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+ if pa.types.is_binary(pa_dtype):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"For {pa_dtype} .astype(str) decodes.",
+ )
+ )
+ super().test_astype_str(data)
+
+
+class TestConstructors(base.BaseConstructorsTests):
+ def test_from_dtype(self, data, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+ if pa.types.is_string(pa_dtype) or pa.types.is_decimal(pa_dtype):
+ if pa.types.is_string(pa_dtype):
+ reason = "ArrowDtype(pa.string()) != StringDtype('pyarrow')"
+ else:
+ reason = f"pyarrow.type_for_alias cannot infer {pa_dtype}"
+
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=reason,
+ )
+ )
+ super().test_from_dtype(data)
+
+ def test_from_sequence_pa_array(self, data):
+ # https://github.com/pandas-dev/pandas/pull/47034#discussion_r955500784
+ # data._pa_array = pa.ChunkedArray
+ result = type(data)._from_sequence(data._pa_array)
+ tm.assert_extension_array_equal(result, data)
+ assert isinstance(result._pa_array, pa.ChunkedArray)
+
+ result = type(data)._from_sequence(data._pa_array.combine_chunks())
+ tm.assert_extension_array_equal(result, data)
+ assert isinstance(result._pa_array, pa.ChunkedArray)
+
+ def test_from_sequence_pa_array_notimplemented(self, request):
+ with pytest.raises(NotImplementedError, match="Converting strings to"):
+ ArrowExtensionArray._from_sequence_of_strings(
+ ["12-1"], dtype=pa.month_day_nano_interval()
+ )
+
+ def test_from_sequence_of_strings_pa_array(self, data, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+ if pa.types.is_time64(pa_dtype) and pa_dtype.equals("time64[ns]") and not PY311:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="Nanosecond time parsing not supported.",
+ )
+ )
+ elif pa_version_under11p0 and (
+ pa.types.is_duration(pa_dtype) or pa.types.is_decimal(pa_dtype)
+ ):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowNotImplementedError,
+ reason=f"pyarrow doesn't support parsing {pa_dtype}",
+ )
+ )
+ elif pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None:
+ _require_timezone_database(request)
+
+ pa_array = data._pa_array.cast(pa.string())
+ result = type(data)._from_sequence_of_strings(pa_array, dtype=data.dtype)
+ tm.assert_extension_array_equal(result, data)
+
+ pa_array = pa_array.combine_chunks()
+ result = type(data)._from_sequence_of_strings(pa_array, dtype=data.dtype)
+ tm.assert_extension_array_equal(result, data)
+
+
+class TestGetitemTests(base.BaseGetitemTests):
+ pass
+
+
+class TestBaseAccumulateTests(base.BaseAccumulateTests):
+ def check_accumulate(self, ser, op_name, skipna):
+ result = getattr(ser, op_name)(skipna=skipna)
+
+ pa_type = ser.dtype.pyarrow_dtype
+ if pa.types.is_temporal(pa_type):
+ # Just check that we match the integer behavior.
+ if pa_type.bit_width == 32:
+ int_type = "int32[pyarrow]"
+ else:
+ int_type = "int64[pyarrow]"
+ ser = ser.astype(int_type)
+ result = result.astype(int_type)
+
+ result = result.astype("Float64")
+ expected = getattr(ser.astype("Float64"), op_name)(skipna=skipna)
+ tm.assert_series_equal(result, expected, check_dtype=False)
+
+ def _supports_accumulation(self, ser: pd.Series, op_name: str) -> bool:
+ # error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no
+ # attribute "pyarrow_dtype"
+ pa_type = ser.dtype.pyarrow_dtype # type: ignore[union-attr]
+
+ if (
+ pa.types.is_string(pa_type)
+ or pa.types.is_binary(pa_type)
+ or pa.types.is_decimal(pa_type)
+ ):
+ if op_name in ["cumsum", "cumprod", "cummax", "cummin"]:
+ return False
+ elif pa.types.is_boolean(pa_type):
+ if op_name in ["cumprod", "cummax", "cummin"]:
+ return False
+ elif pa.types.is_temporal(pa_type):
+ if op_name == "cumsum" and not pa.types.is_duration(pa_type):
+ return False
+ elif op_name == "cumprod":
+ return False
+ return True
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_accumulate_series(self, data, all_numeric_accumulations, skipna, request):
+ pa_type = data.dtype.pyarrow_dtype
+ op_name = all_numeric_accumulations
+ ser = pd.Series(data)
+
+ if not self._supports_accumulation(ser, op_name):
+ # The base class test will check that we raise
+ return super().test_accumulate_series(
+ data, all_numeric_accumulations, skipna
+ )
+
+ if pa_version_under9p0 or (
+ pa_version_under13p0 and all_numeric_accumulations != "cumsum"
+ ):
+ # xfailing takes a long time to run because pytest
+ # renders the exception messages even when not showing them
+ opt = request.config.option
+ if opt.markexpr and "not slow" in opt.markexpr:
+ pytest.skip(
+ f"{all_numeric_accumulations} not implemented for pyarrow < 9"
+ )
+ mark = pytest.mark.xfail(
+ reason=f"{all_numeric_accumulations} not implemented for pyarrow < 9"
+ )
+ request.node.add_marker(mark)
+
+ elif all_numeric_accumulations == "cumsum" and (
+ pa.types.is_boolean(pa_type) or pa.types.is_decimal(pa_type)
+ ):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"{all_numeric_accumulations} not implemented for {pa_type}",
+ raises=NotImplementedError,
+ )
+ )
+
+ self.check_accumulate(ser, op_name, skipna)
+
+
+class TestReduce(base.BaseReduceTests):
+ def _supports_reduction(self, obj, op_name: str) -> bool:
+ dtype = tm.get_dtype(obj)
+ # error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has
+ # no attribute "pyarrow_dtype"
+ pa_dtype = dtype.pyarrow_dtype # type: ignore[union-attr]
+ if pa.types.is_temporal(pa_dtype) and op_name in [
+ "sum",
+ "var",
+ "skew",
+ "kurt",
+ "prod",
+ ]:
+ if pa.types.is_duration(pa_dtype) and op_name in ["sum"]:
+ # summing timedeltas is one case that *is* well-defined
+ pass
+ else:
+ return False
+ elif (
+ pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
+ ) and op_name in [
+ "sum",
+ "mean",
+ "median",
+ "prod",
+ "std",
+ "sem",
+ "var",
+ "skew",
+ "kurt",
+ ]:
+ return False
+
+ if (
+ pa.types.is_temporal(pa_dtype)
+ and not pa.types.is_duration(pa_dtype)
+ and op_name in ["any", "all"]
+ ):
+ # xref GH#34479 we support this in our non-pyarrow datetime64 dtypes,
+ # but it isn't obvious we _should_. For now, we keep the pyarrow
+ # behavior which does not support this.
+ return False
+
+ return True
+
+ def check_reduce(self, ser, op_name, skipna):
+ pa_dtype = ser.dtype.pyarrow_dtype
+ if op_name == "count":
+ result = getattr(ser, op_name)()
+ else:
+ result = getattr(ser, op_name)(skipna=skipna)
+
+ if pa.types.is_integer(pa_dtype) or pa.types.is_floating(pa_dtype):
+ ser = ser.astype("Float64")
+ # TODO: in the opposite case, aren't we testing... nothing?
+ if op_name == "count":
+ expected = getattr(ser, op_name)()
+ else:
+ expected = getattr(ser, op_name)(skipna=skipna)
+ tm.assert_almost_equal(result, expected)
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, request):
+ dtype = data.dtype
+ pa_dtype = dtype.pyarrow_dtype
+
+ xfail_mark = pytest.mark.xfail(
+ raises=TypeError,
+ reason=(
+ f"{all_numeric_reductions} is not implemented in "
+ f"pyarrow={pa.__version__} for {pa_dtype}"
+ ),
+ )
+ if all_numeric_reductions in {"skew", "kurt"} and (
+ dtype._is_numeric or dtype.kind == "b"
+ ):
+ request.node.add_marker(xfail_mark)
+ elif (
+ all_numeric_reductions in {"var", "std", "median"}
+ and pa_version_under7p0
+ and pa.types.is_decimal(pa_dtype)
+ ):
+ request.node.add_marker(xfail_mark)
+ elif (
+ all_numeric_reductions == "sem"
+ and pa_version_under8p0
+ and (dtype._is_numeric or pa.types.is_temporal(pa_dtype))
+ ):
+ request.node.add_marker(xfail_mark)
+
+ elif pa.types.is_boolean(pa_dtype) and all_numeric_reductions in {
+ "sem",
+ "std",
+ "var",
+ "median",
+ }:
+ request.node.add_marker(xfail_mark)
+ super().test_reduce_series_numeric(data, all_numeric_reductions, skipna)
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_reduce_series_boolean(
+ self, data, all_boolean_reductions, skipna, na_value, request
+ ):
+ pa_dtype = data.dtype.pyarrow_dtype
+ xfail_mark = pytest.mark.xfail(
+ raises=TypeError,
+ reason=(
+ f"{all_boolean_reductions} is not implemented in "
+ f"pyarrow={pa.__version__} for {pa_dtype}"
+ ),
+ )
+ if pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype):
+ # We *might* want to make this behave like the non-pyarrow cases,
+ # but have not yet decided.
+ request.node.add_marker(xfail_mark)
+
+ return super().test_reduce_series_boolean(data, all_boolean_reductions, skipna)
+
+ def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool):
+ if op_name in ["max", "min"]:
+ cmp_dtype = arr.dtype
+ elif arr.dtype.name == "decimal128(7, 3)[pyarrow]":
+ if op_name not in ["median", "var", "std"]:
+ cmp_dtype = arr.dtype
+ else:
+ cmp_dtype = "float64[pyarrow]"
+ elif op_name in ["median", "var", "std", "mean", "skew"]:
+ cmp_dtype = "float64[pyarrow]"
+ else:
+ cmp_dtype = {
+ "i": "int64[pyarrow]",
+ "u": "uint64[pyarrow]",
+ "f": "float64[pyarrow]",
+ }[arr.dtype.kind]
+ return cmp_dtype
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_reduce_frame(self, data, all_numeric_reductions, skipna, request):
+ op_name = all_numeric_reductions
+ if op_name == "skew":
+ if data.dtype._is_numeric:
+ mark = pytest.mark.xfail(reason="skew not implemented")
+ request.node.add_marker(mark)
+ return super().test_reduce_frame(data, all_numeric_reductions, skipna)
+
+ @pytest.mark.parametrize("typ", ["int64", "uint64", "float64"])
+ def test_median_not_approximate(self, typ):
+ # GH 52679
+ result = pd.Series([1, 2], dtype=f"{typ}[pyarrow]").median()
+ assert result == 1.5
+
+
+class TestBaseGroupby(base.BaseGroupbyTests):
+ def test_in_numeric_groupby(self, data_for_grouping):
+ dtype = data_for_grouping.dtype
+ if is_string_dtype(dtype):
+ df = pd.DataFrame(
+ {
+ "A": [1, 1, 2, 2, 3, 3, 1, 4],
+ "B": data_for_grouping,
+ "C": [1, 1, 1, 1, 1, 1, 1, 1],
+ }
+ )
+
+ expected = pd.Index(["C"])
+ msg = re.escape(f"agg function failed [how->sum,dtype->{dtype}")
+ with pytest.raises(TypeError, match=msg):
+ df.groupby("A").sum()
+ result = df.groupby("A").sum(numeric_only=True).columns
+ tm.assert_index_equal(result, expected)
+ else:
+ super().test_in_numeric_groupby(data_for_grouping)
+
+
+class TestBaseDtype(base.BaseDtypeTests):
+ def test_construct_from_string_own_name(self, dtype, request):
+ pa_dtype = dtype.pyarrow_dtype
+ if pa.types.is_decimal(pa_dtype):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=NotImplementedError,
+ reason=f"pyarrow.type_for_alias cannot infer {pa_dtype}",
+ )
+ )
+
+ if pa.types.is_string(pa_dtype):
+ # We still support StringDtype('pyarrow') over ArrowDtype(pa.string())
+ msg = r"string\[pyarrow\] should be constructed by StringDtype"
+ with pytest.raises(TypeError, match=msg):
+ dtype.construct_from_string(dtype.name)
+
+ return
+
+ super().test_construct_from_string_own_name(dtype)
+
+ def test_is_dtype_from_name(self, dtype, request):
+ pa_dtype = dtype.pyarrow_dtype
+ if pa.types.is_string(pa_dtype):
+ # We still support StringDtype('pyarrow') over ArrowDtype(pa.string())
+ assert not type(dtype).is_dtype(dtype.name)
+ else:
+ if pa.types.is_decimal(pa_dtype):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=NotImplementedError,
+ reason=f"pyarrow.type_for_alias cannot infer {pa_dtype}",
+ )
+ )
+ super().test_is_dtype_from_name(dtype)
+
+ def test_construct_from_string_another_type_raises(self, dtype):
+ msg = r"'another_type' must end with '\[pyarrow\]'"
+ with pytest.raises(TypeError, match=msg):
+ type(dtype).construct_from_string("another_type")
+
+ def test_get_common_dtype(self, dtype, request):
+ pa_dtype = dtype.pyarrow_dtype
+ if (
+ pa.types.is_date(pa_dtype)
+ or pa.types.is_time(pa_dtype)
+ or (pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None)
+ or pa.types.is_binary(pa_dtype)
+ or pa.types.is_decimal(pa_dtype)
+ ):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=(
+ f"{pa_dtype} does not have associated numpy "
+ f"dtype findable by find_common_type"
+ )
+ )
+ )
+ super().test_get_common_dtype(dtype)
+
+ def test_is_not_string_type(self, dtype):
+ pa_dtype = dtype.pyarrow_dtype
+ if pa.types.is_string(pa_dtype):
+ assert is_string_dtype(dtype)
+ else:
+ super().test_is_not_string_type(dtype)
+
+
+class TestBaseIndex(base.BaseIndexTests):
+ pass
+
+
+class TestBaseInterface(base.BaseInterfaceTests):
+ @pytest.mark.xfail(
+ reason="GH 45419: pyarrow.ChunkedArray does not support views.", run=False
+ )
+ def test_view(self, data):
+ super().test_view(data)
+
+
+class TestBaseMissing(base.BaseMissingTests):
+ def test_fillna_no_op_returns_copy(self, data):
+ data = data[~data.isna()]
+
+ valid = data[0]
+ result = data.fillna(valid)
+ assert result is not data
+ tm.assert_extension_array_equal(result, data)
+
+ result = data.fillna(method="backfill")
+ assert result is not data
+ tm.assert_extension_array_equal(result, data)
+
+
+class TestBasePrinting(base.BasePrintingTests):
+ pass
+
+
+class TestBaseReshaping(base.BaseReshapingTests):
+ @pytest.mark.xfail(
+ reason="GH 45419: pyarrow.ChunkedArray does not support views", run=False
+ )
+ def test_transpose(self, data):
+ super().test_transpose(data)
+
+
+class TestBaseSetitem(base.BaseSetitemTests):
+ @pytest.mark.xfail(
+ reason="GH 45419: pyarrow.ChunkedArray does not support views", run=False
+ )
+ def test_setitem_preserves_views(self, data):
+ super().test_setitem_preserves_views(data)
+
+
+class TestBaseParsing(base.BaseParsingTests):
+ @pytest.mark.parametrize("dtype_backend", ["pyarrow", no_default])
+ @pytest.mark.parametrize("engine", ["c", "python"])
+ def test_EA_types(self, engine, data, dtype_backend, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+ if pa.types.is_decimal(pa_dtype):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=NotImplementedError,
+ reason=f"Parameterized types {pa_dtype} not supported.",
+ )
+ )
+ elif pa.types.is_timestamp(pa_dtype) and pa_dtype.unit in ("us", "ns"):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=ValueError,
+ reason="https://github.com/pandas-dev/pandas/issues/49767",
+ )
+ )
+ elif pa.types.is_binary(pa_dtype):
+ request.node.add_marker(
+ pytest.mark.xfail(reason="CSV parsers don't correctly handle binary")
+ )
+ df = pd.DataFrame({"with_dtype": pd.Series(data, dtype=str(data.dtype))})
+ csv_output = df.to_csv(index=False, na_rep=np.nan)
+ if pa.types.is_binary(pa_dtype):
+ csv_output = BytesIO(csv_output)
+ else:
+ csv_output = StringIO(csv_output)
+ result = pd.read_csv(
+ csv_output,
+ dtype={"with_dtype": str(data.dtype)},
+ engine=engine,
+ dtype_backend=dtype_backend,
+ )
+ expected = df
+ tm.assert_frame_equal(result, expected)
+
+
+class TestBaseUnaryOps(base.BaseUnaryOpsTests):
+ def test_invert(self, data, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+ if not (pa.types.is_boolean(pa_dtype) or pa.types.is_integer(pa_dtype)):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowNotImplementedError,
+ reason=f"pyarrow.compute.invert does support {pa_dtype}",
+ )
+ )
+ super().test_invert(data)
+
+
+class TestBaseMethods(base.BaseMethodsTests):
+ @pytest.mark.parametrize("periods", [1, -2])
+ def test_diff(self, data, periods, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+ if pa.types.is_unsigned_integer(pa_dtype) and periods == 1:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason=(
+ f"diff with {pa_dtype} and periods={periods} will overflow"
+ ),
+ )
+ )
+ super().test_diff(data, periods)
+
+ def test_value_counts_returns_pyarrow_int64(self, data):
+ # GH 51462
+ data = data[:10]
+ result = data.value_counts()
+ assert result.dtype == ArrowDtype(pa.int64())
+
+ def test_argmin_argmax(
+ self, data_for_sorting, data_missing_for_sorting, na_value, request
+ ):
+ pa_dtype = data_for_sorting.dtype.pyarrow_dtype
+ if pa.types.is_decimal(pa_dtype) and pa_version_under7p0:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"No pyarrow kernel for {pa_dtype}",
+ raises=pa.ArrowNotImplementedError,
+ )
+ )
+ super().test_argmin_argmax(data_for_sorting, data_missing_for_sorting, na_value)
+
+ @pytest.mark.parametrize(
+ "op_name, skipna, expected",
+ [
+ ("idxmax", True, 0),
+ ("idxmin", True, 2),
+ ("argmax", True, 0),
+ ("argmin", True, 2),
+ ("idxmax", False, np.nan),
+ ("idxmin", False, np.nan),
+ ("argmax", False, -1),
+ ("argmin", False, -1),
+ ],
+ )
+ def test_argreduce_series(
+ self, data_missing_for_sorting, op_name, skipna, expected, request
+ ):
+ pa_dtype = data_missing_for_sorting.dtype.pyarrow_dtype
+ if pa.types.is_decimal(pa_dtype) and pa_version_under7p0 and skipna:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"No pyarrow kernel for {pa_dtype}",
+ raises=pa.ArrowNotImplementedError,
+ )
+ )
+ super().test_argreduce_series(
+ data_missing_for_sorting, op_name, skipna, expected
+ )
+
+ _combine_le_expected_dtype = "bool[pyarrow]"
+
+
+class TestBaseArithmeticOps(base.BaseArithmeticOpsTests):
+ divmod_exc = NotImplementedError
+
+ def get_op_from_name(self, op_name):
+ short_opname = op_name.strip("_")
+ if short_opname == "rtruediv":
+ # use the numpy version that won't raise on division by zero
+
+ def rtruediv(x, y):
+ return np.divide(y, x)
+
+ return rtruediv
+ elif short_opname == "rfloordiv":
+ return lambda x, y: np.floor_divide(y, x)
+
+ return tm.get_op_from_name(op_name)
+
+ def _cast_pointwise_result(self, op_name: str, obj, other, pointwise_result):
+ # BaseOpsUtil._combine can upcast expected dtype
+ # (because it generates expected on python scalars)
+ # while ArrowExtensionArray maintains original type
+ expected = pointwise_result
+
+ was_frame = False
+ if isinstance(expected, pd.DataFrame):
+ was_frame = True
+ expected_data = expected.iloc[:, 0]
+ original_dtype = obj.iloc[:, 0].dtype
+ else:
+ expected_data = expected
+ original_dtype = obj.dtype
+
+ orig_pa_type = original_dtype.pyarrow_dtype
+ if not was_frame and isinstance(other, pd.Series):
+ # i.e. test_arith_series_with_array
+ if not (
+ pa.types.is_floating(orig_pa_type)
+ or (
+ pa.types.is_integer(orig_pa_type)
+ and op_name not in ["__truediv__", "__rtruediv__"]
+ )
+ or pa.types.is_duration(orig_pa_type)
+ or pa.types.is_timestamp(orig_pa_type)
+ or pa.types.is_date(orig_pa_type)
+ or pa.types.is_decimal(orig_pa_type)
+ ):
+ # base class _combine always returns int64, while
+ # ArrowExtensionArray does not upcast
+ return expected
+ elif not (
+ (op_name == "__floordiv__" and pa.types.is_integer(orig_pa_type))
+ or pa.types.is_duration(orig_pa_type)
+ or pa.types.is_timestamp(orig_pa_type)
+ or pa.types.is_date(orig_pa_type)
+ or pa.types.is_decimal(orig_pa_type)
+ ):
+ # base class _combine always returns int64, while
+ # ArrowExtensionArray does not upcast
+ return expected
+
+ pa_expected = pa.array(expected_data._values)
+
+ if pa.types.is_duration(pa_expected.type):
+ if pa.types.is_date(orig_pa_type):
+ if pa.types.is_date64(orig_pa_type):
+ # TODO: why is this different vs date32?
+ unit = "ms"
+ else:
+ unit = "s"
+ else:
+ # pyarrow sees sequence of datetime/timedelta objects and defaults
+ # to "us" but the non-pointwise op retains unit
+ # timestamp or duration
+ unit = orig_pa_type.unit
+ if type(other) in [datetime, timedelta] and unit in ["s", "ms"]:
+ # pydatetime/pytimedelta objects have microsecond reso, so we
+ # take the higher reso of the original and microsecond. Note
+ # this matches what we would do with DatetimeArray/TimedeltaArray
+ unit = "us"
+
+ pa_expected = pa_expected.cast(f"duration[{unit}]")
+
+ elif pa.types.is_decimal(pa_expected.type) and pa.types.is_decimal(
+ orig_pa_type
+ ):
+ # decimal precision can resize in the result type depending on data
+ # just compare the float values
+ alt = getattr(obj, op_name)(other)
+ alt_dtype = tm.get_dtype(alt)
+ assert isinstance(alt_dtype, ArrowDtype)
+ if op_name == "__pow__" and isinstance(other, Decimal):
+ # TODO: would it make more sense to retain Decimal here?
+ alt_dtype = ArrowDtype(pa.float64())
+ elif (
+ op_name == "__pow__"
+ and isinstance(other, pd.Series)
+ and other.dtype == original_dtype
+ ):
+ # TODO: would it make more sense to retain Decimal here?
+ alt_dtype = ArrowDtype(pa.float64())
+ else:
+ assert pa.types.is_decimal(alt_dtype.pyarrow_dtype)
+ return expected.astype(alt_dtype)
+
+ else:
+ pa_expected = pa_expected.cast(orig_pa_type)
+
+ pd_expected = type(expected_data._values)(pa_expected)
+ if was_frame:
+ expected = pd.DataFrame(
+ pd_expected, index=expected.index, columns=expected.columns
+ )
+ else:
+ expected = pd.Series(pd_expected)
+ return expected
+
+ def _is_temporal_supported(self, opname, pa_dtype):
+ return not pa_version_under8p0 and (
+ (
+ opname in ("__add__", "__radd__")
+ or (
+ opname
+ in ("__truediv__", "__rtruediv__", "__floordiv__", "__rfloordiv__")
+ and not pa_version_under14p0
+ )
+ )
+ and pa.types.is_duration(pa_dtype)
+ or opname in ("__sub__", "__rsub__")
+ and pa.types.is_temporal(pa_dtype)
+ )
+
+ def _get_expected_exception(
+ self, op_name: str, obj, other
+ ) -> type[Exception] | None:
+ if op_name in ("__divmod__", "__rdivmod__"):
+ return self.divmod_exc
+
+ dtype = tm.get_dtype(obj)
+ # error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no
+ # attribute "pyarrow_dtype"
+ pa_dtype = dtype.pyarrow_dtype # type: ignore[union-attr]
+
+ arrow_temporal_supported = self._is_temporal_supported(op_name, pa_dtype)
+ if op_name in {
+ "__mod__",
+ "__rmod__",
+ }:
+ exc = NotImplementedError
+ elif arrow_temporal_supported:
+ exc = None
+ elif op_name in ["__add__", "__radd__"] and (
+ pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
+ ):
+ exc = None
+ elif not (
+ pa.types.is_floating(pa_dtype)
+ or pa.types.is_integer(pa_dtype)
+ or pa.types.is_decimal(pa_dtype)
+ ):
+ # TODO: in many of these cases, e.g. non-duration temporal,
+ # these will *never* be allowed. Would it make more sense to
+ # re-raise as TypeError, more consistent with non-pyarrow cases?
+ exc = pa.ArrowNotImplementedError
+ else:
+ exc = None
+ return exc
+
+ def _get_arith_xfail_marker(self, opname, pa_dtype):
+ mark = None
+
+ arrow_temporal_supported = self._is_temporal_supported(opname, pa_dtype)
+
+ if (
+ opname == "__rpow__"
+ and (
+ pa.types.is_floating(pa_dtype)
+ or pa.types.is_integer(pa_dtype)
+ or pa.types.is_decimal(pa_dtype)
+ )
+ and not pa_version_under7p0
+ ):
+ mark = pytest.mark.xfail(
+ reason=(
+ f"GH#29997: 1**pandas.NA == 1 while 1**pyarrow.NA == NULL "
+ f"for {pa_dtype}"
+ )
+ )
+ elif arrow_temporal_supported and (
+ pa.types.is_time(pa_dtype)
+ or (
+ opname
+ in ("__truediv__", "__rtruediv__", "__floordiv__", "__rfloordiv__")
+ and pa.types.is_duration(pa_dtype)
+ )
+ ):
+ mark = pytest.mark.xfail(
+ raises=TypeError,
+ reason=(
+ f"{opname} not supported between"
+ f"pd.NA and {pa_dtype} Python scalar"
+ ),
+ )
+ elif (
+ opname == "__rfloordiv__"
+ and (pa.types.is_integer(pa_dtype) or pa.types.is_decimal(pa_dtype))
+ and not pa_version_under7p0
+ ):
+ mark = pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason="divide by 0",
+ )
+ elif (
+ opname == "__rtruediv__"
+ and pa.types.is_decimal(pa_dtype)
+ and not pa_version_under7p0
+ ):
+ mark = pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason="divide by 0",
+ )
+ elif (
+ opname == "__pow__"
+ and pa.types.is_decimal(pa_dtype)
+ and pa_version_under7p0
+ ):
+ mark = pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason="Invalid decimal function: power_checked",
+ )
+
+ return mark
+
+ def test_arith_series_with_scalar(self, data, all_arithmetic_operators, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+
+ if all_arithmetic_operators == "__rmod__" and (
+ pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
+ ):
+ pytest.skip("Skip testing Python string formatting")
+
+ mark = self._get_arith_xfail_marker(all_arithmetic_operators, pa_dtype)
+ if mark is not None:
+ request.node.add_marker(mark)
+
+ super().test_arith_series_with_scalar(data, all_arithmetic_operators)
+
+ def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+
+ if all_arithmetic_operators == "__rmod__" and (
+ pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
+ ):
+ pytest.skip("Skip testing Python string formatting")
+
+ mark = self._get_arith_xfail_marker(all_arithmetic_operators, pa_dtype)
+ if mark is not None:
+ request.node.add_marker(mark)
+
+ super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
+
+ def test_arith_series_with_array(self, data, all_arithmetic_operators, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+
+ if (
+ all_arithmetic_operators
+ in (
+ "__sub__",
+ "__rsub__",
+ )
+ and pa.types.is_unsigned_integer(pa_dtype)
+ and not pa_version_under7p0
+ ):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason=(
+ f"Implemented pyarrow.compute.subtract_checked "
+ f"which raises on overflow for {pa_dtype}"
+ ),
+ )
+ )
+
+ mark = self._get_arith_xfail_marker(all_arithmetic_operators, pa_dtype)
+ if mark is not None:
+ request.node.add_marker(mark)
+
+ op_name = all_arithmetic_operators
+ ser = pd.Series(data)
+ # pd.Series([ser.iloc[0]] * len(ser)) may not return ArrowExtensionArray
+ # since ser.iloc[0] is a python scalar
+ other = pd.Series(pd.array([ser.iloc[0]] * len(ser), dtype=data.dtype))
+
+ self.check_opname(ser, op_name, other)
+
+ def test_add_series_with_extension_array(self, data, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+
+ if pa_dtype.equals("int8"):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason=f"raises on overflow for {pa_dtype}",
+ )
+ )
+ super().test_add_series_with_extension_array(data)
+
+
+class TestBaseComparisonOps(base.BaseComparisonOpsTests):
+ def test_compare_array(self, data, comparison_op, na_value):
+ ser = pd.Series(data)
+ # pd.Series([ser.iloc[0]] * len(ser)) may not return ArrowExtensionArray
+ # since ser.iloc[0] is a python scalar
+ other = pd.Series(pd.array([ser.iloc[0]] * len(ser), dtype=data.dtype))
+ if comparison_op.__name__ in ["eq", "ne"]:
+ # comparison should match point-wise comparisons
+ result = comparison_op(ser, other)
+ # Series.combine does not calculate the NA mask correctly
+ # when comparing over an array
+ assert result[8] is na_value
+ assert result[97] is na_value
+ expected = ser.combine(other, comparison_op)
+ expected[8] = na_value
+ expected[97] = na_value
+ tm.assert_series_equal(result, expected)
+
+ else:
+ return super().test_compare_array(data, comparison_op)
+
+ def test_invalid_other_comp(self, data, comparison_op):
+ # GH 48833
+ with pytest.raises(
+ NotImplementedError, match=".* not implemented for "
+ ):
+ comparison_op(data, object())
+
+ @pytest.mark.parametrize("masked_dtype", ["boolean", "Int64", "Float64"])
+ def test_comp_masked_numpy(self, masked_dtype, comparison_op):
+ # GH 52625
+ data = [1, 0, None]
+ ser_masked = pd.Series(data, dtype=masked_dtype)
+ ser_pa = pd.Series(data, dtype=f"{masked_dtype.lower()}[pyarrow]")
+ result = comparison_op(ser_pa, ser_masked)
+ if comparison_op in [operator.lt, operator.gt, operator.ne]:
+ exp = [False, False, None]
+ else:
+ exp = [True, True, None]
+ expected = pd.Series(exp, dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+class TestLogicalOps:
+ """Various Series and DataFrame logical ops methods."""
+
+ def test_kleene_or(self):
+ a = pd.Series([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean[pyarrow]")
+ b = pd.Series([True, False, None] * 3, dtype="boolean[pyarrow]")
+ result = a | b
+ expected = pd.Series(
+ [True, True, True, True, False, None, True, None, None],
+ dtype="boolean[pyarrow]",
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = b | a
+ tm.assert_series_equal(result, expected)
+
+ # ensure we haven't mutated anything inplace
+ tm.assert_series_equal(
+ a,
+ pd.Series([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean[pyarrow]"),
+ )
+ tm.assert_series_equal(
+ b, pd.Series([True, False, None] * 3, dtype="boolean[pyarrow]")
+ )
+
+ @pytest.mark.parametrize(
+ "other, expected",
+ [
+ (None, [True, None, None]),
+ (pd.NA, [True, None, None]),
+ (True, [True, True, True]),
+ (np.bool_(True), [True, True, True]),
+ (False, [True, False, None]),
+ (np.bool_(False), [True, False, None]),
+ ],
+ )
+ def test_kleene_or_scalar(self, other, expected):
+ a = pd.Series([True, False, None], dtype="boolean[pyarrow]")
+ result = a | other
+ expected = pd.Series(expected, dtype="boolean[pyarrow]")
+ tm.assert_series_equal(result, expected)
+
+ result = other | a
+ tm.assert_series_equal(result, expected)
+
+ # ensure we haven't mutated anything inplace
+ tm.assert_series_equal(
+ a, pd.Series([True, False, None], dtype="boolean[pyarrow]")
+ )
+
+ def test_kleene_and(self):
+ a = pd.Series([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean[pyarrow]")
+ b = pd.Series([True, False, None] * 3, dtype="boolean[pyarrow]")
+ result = a & b
+ expected = pd.Series(
+ [True, False, None, False, False, False, None, False, None],
+ dtype="boolean[pyarrow]",
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = b & a
+ tm.assert_series_equal(result, expected)
+
+ # ensure we haven't mutated anything inplace
+ tm.assert_series_equal(
+ a,
+ pd.Series([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean[pyarrow]"),
+ )
+ tm.assert_series_equal(
+ b, pd.Series([True, False, None] * 3, dtype="boolean[pyarrow]")
+ )
+
+ @pytest.mark.parametrize(
+ "other, expected",
+ [
+ (None, [None, False, None]),
+ (pd.NA, [None, False, None]),
+ (True, [True, False, None]),
+ (False, [False, False, False]),
+ (np.bool_(True), [True, False, None]),
+ (np.bool_(False), [False, False, False]),
+ ],
+ )
+ def test_kleene_and_scalar(self, other, expected):
+ a = pd.Series([True, False, None], dtype="boolean[pyarrow]")
+ result = a & other
+ expected = pd.Series(expected, dtype="boolean[pyarrow]")
+ tm.assert_series_equal(result, expected)
+
+ result = other & a
+ tm.assert_series_equal(result, expected)
+
+ # ensure we haven't mutated anything inplace
+ tm.assert_series_equal(
+ a, pd.Series([True, False, None], dtype="boolean[pyarrow]")
+ )
+
+ def test_kleene_xor(self):
+ a = pd.Series([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean[pyarrow]")
+ b = pd.Series([True, False, None] * 3, dtype="boolean[pyarrow]")
+ result = a ^ b
+ expected = pd.Series(
+ [False, True, None, True, False, None, None, None, None],
+ dtype="boolean[pyarrow]",
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = b ^ a
+ tm.assert_series_equal(result, expected)
+
+ # ensure we haven't mutated anything inplace
+ tm.assert_series_equal(
+ a,
+ pd.Series([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean[pyarrow]"),
+ )
+ tm.assert_series_equal(
+ b, pd.Series([True, False, None] * 3, dtype="boolean[pyarrow]")
+ )
+
+ @pytest.mark.parametrize(
+ "other, expected",
+ [
+ (None, [None, None, None]),
+ (pd.NA, [None, None, None]),
+ (True, [False, True, None]),
+ (np.bool_(True), [False, True, None]),
+ (np.bool_(False), [True, False, None]),
+ ],
+ )
+ def test_kleene_xor_scalar(self, other, expected):
+ a = pd.Series([True, False, None], dtype="boolean[pyarrow]")
+ result = a ^ other
+ expected = pd.Series(expected, dtype="boolean[pyarrow]")
+ tm.assert_series_equal(result, expected)
+
+ result = other ^ a
+ tm.assert_series_equal(result, expected)
+
+ # ensure we haven't mutated anything inplace
+ tm.assert_series_equal(
+ a, pd.Series([True, False, None], dtype="boolean[pyarrow]")
+ )
+
+ @pytest.mark.parametrize(
+ "op, exp",
+ [
+ ["__and__", True],
+ ["__or__", True],
+ ["__xor__", False],
+ ],
+ )
+ def test_logical_masked_numpy(self, op, exp):
+ # GH 52625
+ data = [True, False, None]
+ ser_masked = pd.Series(data, dtype="boolean")
+ ser_pa = pd.Series(data, dtype="boolean[pyarrow]")
+ result = getattr(ser_pa, op)(ser_masked)
+ expected = pd.Series([exp, False, None], dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("pa_type", tm.ALL_INT_PYARROW_DTYPES)
+def test_bitwise(pa_type):
+ # GH 54495
+ dtype = ArrowDtype(pa_type)
+ left = pd.Series([1, None, 3, 4], dtype=dtype)
+ right = pd.Series([None, 3, 5, 4], dtype=dtype)
+
+ result = left | right
+ expected = pd.Series([None, None, 3 | 5, 4 | 4], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+ result = left & right
+ expected = pd.Series([None, None, 3 & 5, 4 & 4], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+ result = left ^ right
+ expected = pd.Series([None, None, 3 ^ 5, 4 ^ 4], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+ result = ~left
+ expected = ~(left.fillna(0).to_numpy())
+ expected = pd.Series(expected, dtype=dtype).mask(left.isnull())
+ tm.assert_series_equal(result, expected)
+
+
+def test_arrowdtype_construct_from_string_type_with_unsupported_parameters():
+ with pytest.raises(NotImplementedError, match="Passing pyarrow type"):
+ ArrowDtype.construct_from_string("not_a_real_dype[s, tz=UTC][pyarrow]")
+
+ with pytest.raises(NotImplementedError, match="Passing pyarrow type"):
+ ArrowDtype.construct_from_string("decimal(7, 2)[pyarrow]")
+
+
+def test_arrowdtype_construct_from_string_supports_dt64tz():
+ # as of GH#50689, timestamptz is supported
+ dtype = ArrowDtype.construct_from_string("timestamp[s, tz=UTC][pyarrow]")
+ expected = ArrowDtype(pa.timestamp("s", "UTC"))
+ assert dtype == expected
+
+
+def test_arrowdtype_construct_from_string_type_only_one_pyarrow():
+ # GH#51225
+ invalid = "int64[pyarrow]foobar[pyarrow]"
+ msg = (
+ r"Passing pyarrow type specific parameters \(\[pyarrow\]\) in the "
+ r"string is not supported\."
+ )
+ with pytest.raises(NotImplementedError, match=msg):
+ pd.Series(range(3), dtype=invalid)
+
+
+@pytest.mark.parametrize(
+ "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"]
+)
+@pytest.mark.parametrize("quantile", [0.5, [0.5, 0.5]])
+def test_quantile(data, interpolation, quantile, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+
+ data = data.take([0, 0, 0])
+ ser = pd.Series(data)
+
+ if (
+ pa.types.is_string(pa_dtype)
+ or pa.types.is_binary(pa_dtype)
+ or pa.types.is_boolean(pa_dtype)
+ ):
+ # For string, bytes, and bool, we don't *expect* to have quantile work
+ # Note this matches the non-pyarrow behavior
+ if pa_version_under7p0:
+ msg = r"Function quantile has no kernel matching input types \(.*\)"
+ else:
+ msg = r"Function 'quantile' has no kernel matching input types \(.*\)"
+ with pytest.raises(pa.ArrowNotImplementedError, match=msg):
+ ser.quantile(q=quantile, interpolation=interpolation)
+ return
+
+ if (
+ pa.types.is_integer(pa_dtype)
+ or pa.types.is_floating(pa_dtype)
+ or (pa.types.is_decimal(pa_dtype) and not pa_version_under7p0)
+ ):
+ pass
+ elif pa.types.is_temporal(data._pa_array.type):
+ pass
+ else:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowNotImplementedError,
+ reason=f"quantile not supported by pyarrow for {pa_dtype}",
+ )
+ )
+ data = data.take([0, 0, 0])
+ ser = pd.Series(data)
+ result = ser.quantile(q=quantile, interpolation=interpolation)
+
+ if pa.types.is_timestamp(pa_dtype) and interpolation not in ["lower", "higher"]:
+ # rounding error will make the check below fail
+ # (e.g. '2020-01-01 01:01:01.000001' vs '2020-01-01 01:01:01.000001024'),
+ # so we'll check for now that we match the numpy analogue
+ if pa_dtype.tz:
+ pd_dtype = f"M8[{pa_dtype.unit}, {pa_dtype.tz}]"
+ else:
+ pd_dtype = f"M8[{pa_dtype.unit}]"
+ ser_np = ser.astype(pd_dtype)
+
+ expected = ser_np.quantile(q=quantile, interpolation=interpolation)
+ if quantile == 0.5:
+ if pa_dtype.unit == "us":
+ expected = expected.to_pydatetime(warn=False)
+ assert result == expected
+ else:
+ if pa_dtype.unit == "us":
+ expected = expected.dt.floor("us")
+ tm.assert_series_equal(result, expected.astype(data.dtype))
+ return
+
+ if quantile == 0.5:
+ assert result == data[0]
+ else:
+ # Just check the values
+ expected = pd.Series(data.take([0, 0]), index=[0.5, 0.5])
+ if (
+ pa.types.is_integer(pa_dtype)
+ or pa.types.is_floating(pa_dtype)
+ or pa.types.is_decimal(pa_dtype)
+ ):
+ expected = expected.astype("float64[pyarrow]")
+ result = result.astype("float64[pyarrow]")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "take_idx, exp_idx",
+ [[[0, 0, 2, 2, 4, 4], [4, 0]], [[0, 0, 0, 2, 4, 4], [0]]],
+ ids=["multi_mode", "single_mode"],
+)
+def test_mode_dropna_true(data_for_grouping, take_idx, exp_idx):
+ data = data_for_grouping.take(take_idx)
+ ser = pd.Series(data)
+ result = ser.mode(dropna=True)
+ expected = pd.Series(data_for_grouping.take(exp_idx))
+ tm.assert_series_equal(result, expected)
+
+
+def test_mode_dropna_false_mode_na(data):
+ # GH 50982
+ more_nans = pd.Series([None, None, data[0]], dtype=data.dtype)
+ result = more_nans.mode(dropna=False)
+ expected = pd.Series([None], dtype=data.dtype)
+ tm.assert_series_equal(result, expected)
+
+ expected = pd.Series([data[0], None], dtype=data.dtype)
+ result = expected.mode(dropna=False)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "arrow_dtype, expected_type",
+ [
+ [pa.binary(), bytes],
+ [pa.binary(16), bytes],
+ [pa.large_binary(), bytes],
+ [pa.large_string(), str],
+ [pa.list_(pa.int64()), list],
+ [pa.large_list(pa.int64()), list],
+ [pa.map_(pa.string(), pa.int64()), list],
+ [pa.struct([("f1", pa.int8()), ("f2", pa.string())]), dict],
+ [pa.dictionary(pa.int64(), pa.int64()), CategoricalDtypeType],
+ ],
+)
+def test_arrow_dtype_type(arrow_dtype, expected_type):
+ # GH 51845
+ # TODO: Redundant with test_getitem_scalar once arrow_dtype exists in data fixture
+ assert ArrowDtype(arrow_dtype).type == expected_type
+
+
+def test_is_bool_dtype():
+ # GH 22667
+ data = ArrowExtensionArray(pa.array([True, False, True]))
+ assert is_bool_dtype(data)
+ assert pd.core.common.is_bool_indexer(data)
+ s = pd.Series(range(len(data)))
+ result = s[data]
+ expected = s[np.asarray(data)]
+ tm.assert_series_equal(result, expected)
+
+
+def test_is_numeric_dtype(data):
+ # GH 50563
+ pa_type = data.dtype.pyarrow_dtype
+ if (
+ pa.types.is_floating(pa_type)
+ or pa.types.is_integer(pa_type)
+ or pa.types.is_decimal(pa_type)
+ ):
+ assert is_numeric_dtype(data)
+ else:
+ assert not is_numeric_dtype(data)
+
+
+def test_is_integer_dtype(data):
+ # GH 50667
+ pa_type = data.dtype.pyarrow_dtype
+ if pa.types.is_integer(pa_type):
+ assert is_integer_dtype(data)
+ else:
+ assert not is_integer_dtype(data)
+
+
+def test_is_signed_integer_dtype(data):
+ pa_type = data.dtype.pyarrow_dtype
+ if pa.types.is_signed_integer(pa_type):
+ assert is_signed_integer_dtype(data)
+ else:
+ assert not is_signed_integer_dtype(data)
+
+
+def test_is_unsigned_integer_dtype(data):
+ pa_type = data.dtype.pyarrow_dtype
+ if pa.types.is_unsigned_integer(pa_type):
+ assert is_unsigned_integer_dtype(data)
+ else:
+ assert not is_unsigned_integer_dtype(data)
+
+
+def test_is_float_dtype(data):
+ pa_type = data.dtype.pyarrow_dtype
+ if pa.types.is_floating(pa_type):
+ assert is_float_dtype(data)
+ else:
+ assert not is_float_dtype(data)
+
+
+def test_pickle_roundtrip(data):
+ # GH 42600
+ expected = pd.Series(data)
+ expected_sliced = expected.head(2)
+ full_pickled = pickle.dumps(expected)
+ sliced_pickled = pickle.dumps(expected_sliced)
+
+ assert len(full_pickled) > len(sliced_pickled)
+
+ result = pickle.loads(full_pickled)
+ tm.assert_series_equal(result, expected)
+
+ result_sliced = pickle.loads(sliced_pickled)
+ tm.assert_series_equal(result_sliced, expected_sliced)
+
+
+def test_astype_from_non_pyarrow(data):
+ # GH49795
+ pd_array = data._pa_array.to_pandas().array
+ result = pd_array.astype(data.dtype)
+ assert not isinstance(pd_array.dtype, ArrowDtype)
+ assert isinstance(result.dtype, ArrowDtype)
+ tm.assert_extension_array_equal(result, data)
+
+
+def test_astype_float_from_non_pyarrow_str():
+ # GH50430
+ ser = pd.Series(["1.0"])
+ result = ser.astype("float64[pyarrow]")
+ expected = pd.Series([1.0], dtype="float64[pyarrow]")
+ tm.assert_series_equal(result, expected)
+
+
+def test_to_numpy_with_defaults(data):
+ # GH49973
+ result = data.to_numpy()
+
+ pa_type = data._pa_array.type
+ if (
+ pa.types.is_duration(pa_type)
+ or pa.types.is_timestamp(pa_type)
+ or pa.types.is_date(pa_type)
+ ):
+ expected = np.array(list(data))
+ else:
+ expected = np.array(data._pa_array)
+
+ if data._hasna:
+ expected = expected.astype(object)
+ expected[pd.isna(data)] = pd.NA
+
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_to_numpy_int_with_na():
+ # GH51227: ensure to_numpy does not convert int to float
+ data = [1, None]
+ arr = pd.array(data, dtype="int64[pyarrow]")
+ result = arr.to_numpy()
+ expected = np.array([1, pd.NA], dtype=object)
+ assert isinstance(result[0], int)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("na_val, exp", [(lib.no_default, np.nan), (1, 1)])
+def test_to_numpy_null_array(na_val, exp):
+ # GH#52443
+ arr = pd.array([pd.NA, pd.NA], dtype="null[pyarrow]")
+ result = arr.to_numpy(dtype="float64", na_value=na_val)
+ expected = np.array([exp] * 2, dtype="float64")
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_to_numpy_null_array_no_dtype():
+ # GH#52443
+ arr = pd.array([pd.NA, pd.NA], dtype="null[pyarrow]")
+ result = arr.to_numpy(dtype=None)
+ expected = np.array([pd.NA] * 2, dtype="object")
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_setitem_null_slice(data):
+ # GH50248
+ orig = data.copy()
+
+ result = orig.copy()
+ result[:] = data[0]
+ expected = ArrowExtensionArray._from_sequence(
+ [data[0]] * len(data),
+ dtype=data._pa_array.type,
+ )
+ tm.assert_extension_array_equal(result, expected)
+
+ result = orig.copy()
+ result[:] = data[::-1]
+ expected = data[::-1]
+ tm.assert_extension_array_equal(result, expected)
+
+ result = orig.copy()
+ result[:] = data.tolist()
+ expected = data
+ tm.assert_extension_array_equal(result, expected)
+
+
+def test_setitem_invalid_dtype(data):
+ # GH50248
+ pa_type = data._pa_array.type
+ if pa.types.is_string(pa_type) or pa.types.is_binary(pa_type):
+ fill_value = 123
+ err = TypeError
+ msg = "Invalid value '123' for dtype"
+ elif (
+ pa.types.is_integer(pa_type)
+ or pa.types.is_floating(pa_type)
+ or pa.types.is_boolean(pa_type)
+ ):
+ fill_value = "foo"
+ err = pa.ArrowInvalid
+ msg = "Could not convert"
+ else:
+ fill_value = "foo"
+ err = TypeError
+ msg = "Invalid value 'foo' for dtype"
+ with pytest.raises(err, match=msg):
+ data[:] = fill_value
+
+
+@pytest.mark.skipif(pa_version_under8p0, reason="returns object with 7.0")
+def test_from_arrow_respecting_given_dtype():
+ date_array = pa.array(
+ [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31")], type=pa.date32()
+ )
+ result = date_array.to_pandas(
+ types_mapper={pa.date32(): ArrowDtype(pa.date64())}.get
+ )
+ expected = pd.Series(
+ [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31")],
+ dtype=ArrowDtype(pa.date64()),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.skipif(pa_version_under8p0, reason="doesn't raise with 7")
+def test_from_arrow_respecting_given_dtype_unsafe():
+ array = pa.array([1.5, 2.5], type=pa.float64())
+ with pytest.raises(pa.ArrowInvalid, match="Float value 1.5 was truncated"):
+ array.to_pandas(types_mapper={pa.float64(): ArrowDtype(pa.int64())}.get)
+
+
+def test_round():
+ dtype = "float64[pyarrow]"
+
+ ser = pd.Series([0.0, 1.23, 2.56, pd.NA], dtype=dtype)
+ result = ser.round(1)
+ expected = pd.Series([0.0, 1.2, 2.6, pd.NA], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+ ser = pd.Series([123.4, pd.NA, 56.78], dtype=dtype)
+ result = ser.round(-1)
+ expected = pd.Series([120.0, pd.NA, 60.0], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_searchsorted_with_na_raises(data_for_sorting, as_series):
+ # GH50447
+ b, c, a = data_for_sorting
+ arr = data_for_sorting.take([2, 0, 1]) # to get [a, b, c]
+ arr[-1] = pd.NA
+
+ if as_series:
+ arr = pd.Series(arr)
+
+ msg = (
+ "searchsorted requires array to be sorted, "
+ "which is impossible with NAs present."
+ )
+ with pytest.raises(ValueError, match=msg):
+ arr.searchsorted(b)
+
+
+def test_sort_values_dictionary():
+ df = pd.DataFrame(
+ {
+ "a": pd.Series(
+ ["x", "y"], dtype=ArrowDtype(pa.dictionary(pa.int32(), pa.string()))
+ ),
+ "b": [1, 2],
+ },
+ )
+ expected = df.copy()
+ result = df.sort_values(by=["a", "b"])
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("pat", ["abc", "a[a-z]{2}"])
+def test_str_count(pat):
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.count(pat)
+ expected = pd.Series([1, None], dtype=ArrowDtype(pa.int32()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_count_flags_unsupported():
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ with pytest.raises(NotImplementedError, match="count not"):
+ ser.str.count("abc", flags=1)
+
+
+@pytest.mark.parametrize(
+ "side, str_func", [["left", "rjust"], ["right", "ljust"], ["both", "center"]]
+)
+def test_str_pad(side, str_func):
+ ser = pd.Series(["a", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.pad(width=3, side=side, fillchar="x")
+ expected = pd.Series(
+ [getattr("a", str_func)(3, "x"), None], dtype=ArrowDtype(pa.string())
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_pad_invalid_side():
+ ser = pd.Series(["a", None], dtype=ArrowDtype(pa.string()))
+ with pytest.raises(ValueError, match="Invalid side: foo"):
+ ser.str.pad(3, "foo", "x")
+
+
+@pytest.mark.parametrize(
+ "pat, case, na, regex, exp",
+ [
+ ["ab", False, None, False, [True, None]],
+ ["Ab", True, None, False, [False, None]],
+ ["ab", False, True, False, [True, True]],
+ ["a[a-z]{1}", False, None, True, [True, None]],
+ ["A[a-z]{1}", True, None, True, [False, None]],
+ ],
+)
+def test_str_contains(pat, case, na, regex, exp):
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.contains(pat, case=case, na=na, regex=regex)
+ expected = pd.Series(exp, dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_contains_flags_unsupported():
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ with pytest.raises(NotImplementedError, match="contains not"):
+ ser.str.contains("a", flags=1)
+
+
+@pytest.mark.parametrize(
+ "side, pat, na, exp",
+ [
+ ["startswith", "ab", None, [True, None]],
+ ["startswith", "b", False, [False, False]],
+ ["endswith", "b", True, [False, True]],
+ ["endswith", "bc", None, [True, None]],
+ ],
+)
+def test_str_start_ends_with(side, pat, na, exp):
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ result = getattr(ser.str, side)(pat, na=na)
+ expected = pd.Series(exp, dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "arg_name, arg",
+ [["pat", re.compile("b")], ["repl", str], ["case", False], ["flags", 1]],
+)
+def test_str_replace_unsupported(arg_name, arg):
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ kwargs = {"pat": "b", "repl": "x", "regex": True}
+ kwargs[arg_name] = arg
+ with pytest.raises(NotImplementedError, match="replace is not supported"):
+ ser.str.replace(**kwargs)
+
+
+@pytest.mark.parametrize(
+ "pat, repl, n, regex, exp",
+ [
+ ["a", "x", -1, False, ["xbxc", None]],
+ ["a", "x", 1, False, ["xbac", None]],
+ ["[a-b]", "x", -1, True, ["xxxc", None]],
+ ],
+)
+def test_str_replace(pat, repl, n, regex, exp):
+ ser = pd.Series(["abac", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.replace(pat, repl, n=n, regex=regex)
+ expected = pd.Series(exp, dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_repeat_unsupported():
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ with pytest.raises(NotImplementedError, match="repeat is not"):
+ ser.str.repeat([1, 2])
+
+
+@pytest.mark.xfail(
+ pa_version_under7p0,
+ reason="Unsupported for pyarrow < 7",
+ raises=NotImplementedError,
+)
+def test_str_repeat():
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.repeat(2)
+ expected = pd.Series(["abcabc", None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pat, case, na, exp",
+ [
+ ["ab", False, None, [True, None]],
+ ["Ab", True, None, [False, None]],
+ ["bc", True, None, [False, None]],
+ ["ab", False, True, [True, True]],
+ ["a[a-z]{1}", False, None, [True, None]],
+ ["A[a-z]{1}", True, None, [False, None]],
+ ],
+)
+def test_str_match(pat, case, na, exp):
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.match(pat, case=case, na=na)
+ expected = pd.Series(exp, dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pat, case, na, exp",
+ [
+ ["abc", False, None, [True, None]],
+ ["Abc", True, None, [False, None]],
+ ["bc", True, None, [False, None]],
+ ["ab", False, True, [True, True]],
+ ["a[a-z]{2}", False, None, [True, None]],
+ ["A[a-z]{1}", True, None, [False, None]],
+ ],
+)
+def test_str_fullmatch(pat, case, na, exp):
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.match(pat, case=case, na=na)
+ expected = pd.Series(exp, dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "sub, start, end, exp, exp_typ",
+ [["ab", 0, None, [0, None], pa.int32()], ["bc", 1, 3, [2, None], pa.int64()]],
+)
+def test_str_find(sub, start, end, exp, exp_typ):
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.find(sub, start=start, end=end)
+ expected = pd.Series(exp, dtype=ArrowDtype(exp_typ))
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_find_notimplemented():
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ with pytest.raises(NotImplementedError, match="find not implemented"):
+ ser.str.find("ab", start=1)
+
+
+@pytest.mark.parametrize(
+ "i, exp",
+ [
+ [1, ["b", "e", None]],
+ [-1, ["c", "e", None]],
+ [2, ["c", None, None]],
+ [-3, ["a", None, None]],
+ [4, [None, None, None]],
+ ],
+)
+def test_str_get(i, exp):
+ ser = pd.Series(["abc", "de", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.get(i)
+ expected = pd.Series(exp, dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.xfail(
+ reason="TODO: StringMethods._validate should support Arrow list types",
+ raises=AttributeError,
+)
+def test_str_join():
+ ser = pd.Series(ArrowExtensionArray(pa.array([list("abc"), list("123"), None])))
+ result = ser.str.join("=")
+ expected = pd.Series(["a=b=c", "1=2=3", None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_join_string_type():
+ ser = pd.Series(ArrowExtensionArray(pa.array(["abc", "123", None])))
+ result = ser.str.join("=")
+ expected = pd.Series(["a=b=c", "1=2=3", None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "start, stop, step, exp",
+ [
+ [None, 2, None, ["ab", None]],
+ [None, 2, 1, ["ab", None]],
+ [1, 3, 1, ["bc", None]],
+ ],
+)
+def test_str_slice(start, stop, step, exp):
+ ser = pd.Series(["abcd", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.slice(start, stop, step)
+ expected = pd.Series(exp, dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "start, stop, repl, exp",
+ [
+ [1, 2, "x", ["axcd", None]],
+ [None, 2, "x", ["xcd", None]],
+ [None, 2, None, ["cd", None]],
+ ],
+)
+def test_str_slice_replace(start, stop, repl, exp):
+ ser = pd.Series(["abcd", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.slice_replace(start, stop, repl)
+ expected = pd.Series(exp, dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "value, method, exp",
+ [
+ ["a1c", "isalnum", True],
+ ["!|,", "isalnum", False],
+ ["aaa", "isalpha", True],
+ ["!!!", "isalpha", False],
+ ["٠", "isdecimal", True], # noqa: RUF001
+ ["~!", "isdecimal", False],
+ ["2", "isdigit", True],
+ ["~", "isdigit", False],
+ ["aaa", "islower", True],
+ ["aaA", "islower", False],
+ ["123", "isnumeric", True],
+ ["11I", "isnumeric", False],
+ [" ", "isspace", True],
+ ["", "isspace", False],
+ ["The That", "istitle", True],
+ ["the That", "istitle", False],
+ ["AAA", "isupper", True],
+ ["AAc", "isupper", False],
+ ],
+)
+def test_str_is_functions(value, method, exp):
+ ser = pd.Series([value, None], dtype=ArrowDtype(pa.string()))
+ result = getattr(ser.str, method)()
+ expected = pd.Series([exp, None], dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "method, exp",
+ [
+ ["capitalize", "Abc def"],
+ ["title", "Abc Def"],
+ ["swapcase", "AbC Def"],
+ ["lower", "abc def"],
+ ["upper", "ABC DEF"],
+ ["casefold", "abc def"],
+ ],
+)
+def test_str_transform_functions(method, exp):
+ ser = pd.Series(["aBc dEF", None], dtype=ArrowDtype(pa.string()))
+ result = getattr(ser.str, method)()
+ expected = pd.Series([exp, None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_len():
+ ser = pd.Series(["abcd", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.len()
+ expected = pd.Series([4, None], dtype=ArrowDtype(pa.int32()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "method, to_strip, val",
+ [
+ ["strip", None, " abc "],
+ ["strip", "x", "xabcx"],
+ ["lstrip", None, " abc"],
+ ["lstrip", "x", "xabc"],
+ ["rstrip", None, "abc "],
+ ["rstrip", "x", "abcx"],
+ ],
+)
+def test_str_strip(method, to_strip, val):
+ ser = pd.Series([val, None], dtype=ArrowDtype(pa.string()))
+ result = getattr(ser.str, method)(to_strip=to_strip)
+ expected = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("val", ["abc123", "abc"])
+def test_str_removesuffix(val):
+ ser = pd.Series([val, None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.removesuffix("123")
+ expected = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("val", ["123abc", "abc"])
+def test_str_removeprefix(val):
+ ser = pd.Series([val, None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.removeprefix("123")
+ expected = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("errors", ["ignore", "strict"])
+@pytest.mark.parametrize(
+ "encoding, exp",
+ [
+ ["utf8", b"abc"],
+ ["utf32", b"\xff\xfe\x00\x00a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00"],
+ ],
+)
+def test_str_encode(errors, encoding, exp):
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.encode(encoding, errors)
+ expected = pd.Series([exp, None], dtype=ArrowDtype(pa.binary()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("flags", [0, 2])
+def test_str_findall(flags):
+ ser = pd.Series(["abc", "efg", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.findall("b", flags=flags)
+ expected = pd.Series([["b"], [], None], dtype=ArrowDtype(pa.list_(pa.string())))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["index", "rindex"])
+@pytest.mark.parametrize(
+ "start, end",
+ [
+ [0, None],
+ [1, 4],
+ ],
+)
+def test_str_r_index(method, start, end):
+ ser = pd.Series(["abcba", None], dtype=ArrowDtype(pa.string()))
+ result = getattr(ser.str, method)("c", start, end)
+ expected = pd.Series([2, None], dtype=ArrowDtype(pa.int64()))
+ tm.assert_series_equal(result, expected)
+
+ with pytest.raises(ValueError, match="substring not found"):
+ getattr(ser.str, method)("foo", start, end)
+
+
+@pytest.mark.parametrize("form", ["NFC", "NFKC"])
+def test_str_normalize(form):
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.normalize(form)
+ expected = ser.copy()
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "start, end",
+ [
+ [0, None],
+ [1, 4],
+ ],
+)
+def test_str_rfind(start, end):
+ ser = pd.Series(["abcba", "foo", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.rfind("c", start, end)
+ expected = pd.Series([2, -1, None], dtype=ArrowDtype(pa.int64()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_translate():
+ ser = pd.Series(["abcba", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.translate({97: "b"})
+ expected = pd.Series(["bbcbb", None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_wrap():
+ ser = pd.Series(["abcba", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.wrap(3)
+ expected = pd.Series(["abc\nba", None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_get_dummies():
+ ser = pd.Series(["a|b", None, "a|c"], dtype=ArrowDtype(pa.string()))
+ result = ser.str.get_dummies()
+ expected = pd.DataFrame(
+ [[True, True, False], [False, False, False], [True, False, True]],
+ dtype=ArrowDtype(pa.bool_()),
+ columns=["a", "b", "c"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_str_partition():
+ ser = pd.Series(["abcba", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.partition("b")
+ expected = pd.DataFrame(
+ [["a", "b", "cba"], [None, None, None]], dtype=ArrowDtype(pa.string())
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = ser.str.partition("b", expand=False)
+ expected = pd.Series(ArrowExtensionArray(pa.array([["a", "b", "cba"], None])))
+ tm.assert_series_equal(result, expected)
+
+ result = ser.str.rpartition("b")
+ expected = pd.DataFrame(
+ [["abc", "b", "a"], [None, None, None]], dtype=ArrowDtype(pa.string())
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = ser.str.rpartition("b", expand=False)
+ expected = pd.Series(ArrowExtensionArray(pa.array([["abc", "b", "a"], None])))
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_split():
+ # GH 52401
+ ser = pd.Series(["a1cbcb", "a2cbcb", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.split("c")
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([["a1", "b", "b"], ["a2", "b", "b"], None]))
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = ser.str.split("c", n=1)
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([["a1", "bcb"], ["a2", "bcb"], None]))
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = ser.str.split("[1-2]", regex=True)
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([["a", "cbcb"], ["a", "cbcb"], None]))
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = ser.str.split("[1-2]", regex=True, expand=True)
+ expected = pd.DataFrame(
+ {
+ 0: ArrowExtensionArray(pa.array(["a", "a", None])),
+ 1: ArrowExtensionArray(pa.array(["cbcb", "cbcb", None])),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = ser.str.split("1", expand=True)
+ expected = pd.DataFrame(
+ {
+ 0: ArrowExtensionArray(pa.array(["a", "a2cbcb", None])),
+ 1: ArrowExtensionArray(pa.array(["cbcb", None, None])),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_str_rsplit():
+ # GH 52401
+ ser = pd.Series(["a1cbcb", "a2cbcb", None], dtype=ArrowDtype(pa.string()))
+ result = ser.str.rsplit("c")
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([["a1", "b", "b"], ["a2", "b", "b"], None]))
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = ser.str.rsplit("c", n=1)
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([["a1cb", "b"], ["a2cb", "b"], None]))
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = ser.str.rsplit("c", n=1, expand=True)
+ expected = pd.DataFrame(
+ {
+ 0: ArrowExtensionArray(pa.array(["a1cb", "a2cb", None])),
+ 1: ArrowExtensionArray(pa.array(["b", "b", None])),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = ser.str.rsplit("1", expand=True)
+ expected = pd.DataFrame(
+ {
+ 0: ArrowExtensionArray(pa.array(["a", "a2cbcb", None])),
+ 1: ArrowExtensionArray(pa.array(["cbcb", None, None])),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_str_unsupported_extract():
+ ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ with pytest.raises(
+ NotImplementedError, match="str.extract not supported with pd.ArrowDtype"
+ ):
+ ser.str.extract(r"[ab](\d)")
+
+
+@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
+def test_duration_from_strings_with_nat(unit):
+ # GH51175
+ strings = ["1000", "NaT"]
+ pa_type = pa.duration(unit)
+ result = ArrowExtensionArray._from_sequence_of_strings(strings, dtype=pa_type)
+ expected = ArrowExtensionArray(pa.array([1000, None], type=pa_type))
+ tm.assert_extension_array_equal(result, expected)
+
+
+def test_unsupported_dt(data):
+ pa_dtype = data.dtype.pyarrow_dtype
+ if not pa.types.is_temporal(pa_dtype):
+ with pytest.raises(
+ AttributeError, match="Can only use .dt accessor with datetimelike values"
+ ):
+ pd.Series(data).dt
+
+
+@pytest.mark.parametrize(
+ "prop, expected",
+ [
+ ["year", 2023],
+ ["day", 2],
+ ["day_of_week", 0],
+ ["dayofweek", 0],
+ ["weekday", 0],
+ ["day_of_year", 2],
+ ["dayofyear", 2],
+ ["hour", 3],
+ ["minute", 4],
+ pytest.param(
+ "is_leap_year",
+ False,
+ marks=pytest.mark.xfail(
+ pa_version_under8p0,
+ raises=NotImplementedError,
+ reason="is_leap_year not implemented for pyarrow < 8.0",
+ ),
+ ),
+ ["microsecond", 5],
+ ["month", 1],
+ ["nanosecond", 6],
+ ["quarter", 1],
+ ["second", 7],
+ ["date", date(2023, 1, 2)],
+ ["time", time(3, 4, 7, 5)],
+ ],
+)
+def test_dt_properties(prop, expected):
+ ser = pd.Series(
+ [
+ pd.Timestamp(
+ year=2023,
+ month=1,
+ day=2,
+ hour=3,
+ minute=4,
+ second=7,
+ microsecond=5,
+ nanosecond=6,
+ ),
+ None,
+ ],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ result = getattr(ser.dt, prop)
+ exp_type = None
+ if isinstance(expected, date):
+ exp_type = pa.date32()
+ elif isinstance(expected, time):
+ exp_type = pa.time64("ns")
+ expected = pd.Series(ArrowExtensionArray(pa.array([expected, None], type=exp_type)))
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_is_month_start_end():
+ ser = pd.Series(
+ [
+ datetime(year=2023, month=12, day=2, hour=3),
+ datetime(year=2023, month=1, day=1, hour=3),
+ datetime(year=2023, month=3, day=31, hour=3),
+ None,
+ ],
+ dtype=ArrowDtype(pa.timestamp("us")),
+ )
+ result = ser.dt.is_month_start
+ expected = pd.Series([False, True, False, None], dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+ result = ser.dt.is_month_end
+ expected = pd.Series([False, False, True, None], dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_is_year_start_end():
+ ser = pd.Series(
+ [
+ datetime(year=2023, month=12, day=31, hour=3),
+ datetime(year=2023, month=1, day=1, hour=3),
+ datetime(year=2023, month=3, day=31, hour=3),
+ None,
+ ],
+ dtype=ArrowDtype(pa.timestamp("us")),
+ )
+ result = ser.dt.is_year_start
+ expected = pd.Series([False, True, False, None], dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+ result = ser.dt.is_year_end
+ expected = pd.Series([True, False, False, None], dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_is_quarter_start_end():
+ ser = pd.Series(
+ [
+ datetime(year=2023, month=11, day=30, hour=3),
+ datetime(year=2023, month=1, day=1, hour=3),
+ datetime(year=2023, month=3, day=31, hour=3),
+ None,
+ ],
+ dtype=ArrowDtype(pa.timestamp("us")),
+ )
+ result = ser.dt.is_quarter_start
+ expected = pd.Series([False, True, False, None], dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+ result = ser.dt.is_quarter_end
+ expected = pd.Series([False, False, True, None], dtype=ArrowDtype(pa.bool_()))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["days_in_month", "daysinmonth"])
+def test_dt_days_in_month(method):
+ ser = pd.Series(
+ [
+ datetime(year=2023, month=3, day=30, hour=3),
+ datetime(year=2023, month=4, day=1, hour=3),
+ datetime(year=2023, month=2, day=3, hour=3),
+ None,
+ ],
+ dtype=ArrowDtype(pa.timestamp("us")),
+ )
+ result = getattr(ser.dt, method)
+ expected = pd.Series([31, 30, 28, None], dtype=ArrowDtype(pa.int64()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_normalize():
+ ser = pd.Series(
+ [
+ datetime(year=2023, month=3, day=30),
+ datetime(year=2023, month=4, day=1, hour=3),
+ datetime(year=2023, month=2, day=3, hour=23, minute=59, second=59),
+ None,
+ ],
+ dtype=ArrowDtype(pa.timestamp("us")),
+ )
+ result = ser.dt.normalize()
+ expected = pd.Series(
+ [
+ datetime(year=2023, month=3, day=30),
+ datetime(year=2023, month=4, day=1),
+ datetime(year=2023, month=2, day=3),
+ None,
+ ],
+ dtype=ArrowDtype(pa.timestamp("us")),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("unit", ["us", "ns"])
+def test_dt_time_preserve_unit(unit):
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp(unit)),
+ )
+ assert ser.dt.unit == unit
+
+ result = ser.dt.time
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([time(3, 0), None], type=pa.time64(unit)))
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("tz", [None, "UTC", "US/Pacific"])
+def test_dt_tz(tz):
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns", tz=tz)),
+ )
+ result = ser.dt.tz
+ assert result == timezones.maybe_get_tz(tz)
+
+
+def test_dt_isocalendar():
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ result = ser.dt.isocalendar()
+ expected = pd.DataFrame(
+ [[2023, 1, 1], [0, 0, 0]],
+ columns=["year", "week", "day"],
+ dtype="int64[pyarrow]",
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "method, exp", [["day_name", "Sunday"], ["month_name", "January"]]
+)
+def test_dt_day_month_name(method, exp, request):
+ # GH 52388
+ _require_timezone_database(request)
+
+ ser = pd.Series([datetime(2023, 1, 1), None], dtype=ArrowDtype(pa.timestamp("ms")))
+ result = getattr(ser.dt, method)()
+ expected = pd.Series([exp, None], dtype=ArrowDtype(pa.string()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_strftime(request):
+ _require_timezone_database(request)
+
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ result = ser.dt.strftime("%Y-%m-%dT%H:%M:%S")
+ expected = pd.Series(
+ ["2023-01-02T03:00:00.000000000", None], dtype=ArrowDtype(pa.string())
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["ceil", "floor", "round"])
+def test_dt_roundlike_tz_options_not_supported(method):
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ with pytest.raises(NotImplementedError, match="ambiguous is not supported."):
+ getattr(ser.dt, method)("1H", ambiguous="NaT")
+
+ with pytest.raises(NotImplementedError, match="nonexistent is not supported."):
+ getattr(ser.dt, method)("1H", nonexistent="NaT")
+
+
+@pytest.mark.parametrize("method", ["ceil", "floor", "round"])
+def test_dt_roundlike_unsupported_freq(method):
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ with pytest.raises(ValueError, match="freq='1B' is not supported"):
+ getattr(ser.dt, method)("1B")
+
+ with pytest.raises(ValueError, match="Must specify a valid frequency: None"):
+ getattr(ser.dt, method)(None)
+
+
+@pytest.mark.xfail(
+ pa_version_under7p0, reason="Methods not supported for pyarrow < 7.0"
+)
+@pytest.mark.parametrize("freq", ["D", "H", "T", "S", "L", "U", "N"])
+@pytest.mark.parametrize("method", ["ceil", "floor", "round"])
+def test_dt_ceil_year_floor(freq, method):
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=1), None],
+ )
+ pa_dtype = ArrowDtype(pa.timestamp("ns"))
+ expected = getattr(ser.dt, method)(f"1{freq}").astype(pa_dtype)
+ result = getattr(ser.astype(pa_dtype).dt, method)(f"1{freq}")
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_to_pydatetime():
+ # GH 51859
+ data = [datetime(2022, 1, 1), datetime(2023, 1, 1)]
+ ser = pd.Series(data, dtype=ArrowDtype(pa.timestamp("ns")))
+
+ msg = "The behavior of ArrowTemporalProperties.to_pydatetime is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = ser.dt.to_pydatetime()
+ expected = np.array(data, dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+ assert all(type(res) is datetime for res in result)
+
+ msg = "The behavior of DatetimeProperties.to_pydatetime is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = ser.astype("datetime64[ns]").dt.to_pydatetime()
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("date_type", [32, 64])
+def test_dt_to_pydatetime_date_error(date_type):
+ # GH 52812
+ ser = pd.Series(
+ [date(2022, 12, 31)],
+ dtype=ArrowDtype(getattr(pa, f"date{date_type}")()),
+ )
+ msg = "The behavior of ArrowTemporalProperties.to_pydatetime is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ with pytest.raises(ValueError, match="to_pydatetime cannot be called with"):
+ ser.dt.to_pydatetime()
+
+
+def test_dt_tz_localize_unsupported_tz_options():
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ with pytest.raises(NotImplementedError, match="ambiguous='NaT' is not supported"):
+ ser.dt.tz_localize("UTC", ambiguous="NaT")
+
+ with pytest.raises(NotImplementedError, match="nonexistent='NaT' is not supported"):
+ ser.dt.tz_localize("UTC", nonexistent="NaT")
+
+
+def test_dt_tz_localize_none():
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns", tz="US/Pacific")),
+ )
+ result = ser.dt.tz_localize(None)
+ expected = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("unit", ["us", "ns"])
+def test_dt_tz_localize(unit, request):
+ _require_timezone_database(request)
+
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp(unit)),
+ )
+ result = ser.dt.tz_localize("US/Pacific")
+ exp_data = pa.array(
+ [datetime(year=2023, month=1, day=2, hour=3), None], type=pa.timestamp(unit)
+ )
+ exp_data = pa.compute.assume_timezone(exp_data, "US/Pacific")
+ expected = pd.Series(ArrowExtensionArray(exp_data))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "nonexistent, exp_date",
+ [
+ ["shift_forward", datetime(year=2023, month=3, day=12, hour=3)],
+ ["shift_backward", pd.Timestamp("2023-03-12 01:59:59.999999999")],
+ ],
+)
+def test_dt_tz_localize_nonexistent(nonexistent, exp_date, request):
+ _require_timezone_database(request)
+
+ ser = pd.Series(
+ [datetime(year=2023, month=3, day=12, hour=2, minute=30), None],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ result = ser.dt.tz_localize("US/Pacific", nonexistent=nonexistent)
+ exp_data = pa.array([exp_date, None], type=pa.timestamp("ns"))
+ exp_data = pa.compute.assume_timezone(exp_data, "US/Pacific")
+ expected = pd.Series(ArrowExtensionArray(exp_data))
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_tz_convert_not_tz_raises():
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ with pytest.raises(TypeError, match="Cannot convert tz-naive timestamps"):
+ ser.dt.tz_convert("UTC")
+
+
+def test_dt_tz_convert_none():
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns", "US/Pacific")),
+ )
+ result = ser.dt.tz_convert(None)
+ expected = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp("ns")),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("unit", ["us", "ns"])
+def test_dt_tz_convert(unit):
+ ser = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp(unit, "US/Pacific")),
+ )
+ result = ser.dt.tz_convert("US/Eastern")
+ expected = pd.Series(
+ [datetime(year=2023, month=1, day=2, hour=3), None],
+ dtype=ArrowDtype(pa.timestamp(unit, "US/Eastern")),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("skipna", [True, False])
+def test_boolean_reduce_series_all_null(all_boolean_reductions, skipna):
+ # GH51624
+ ser = pd.Series([None], dtype="float64[pyarrow]")
+ result = getattr(ser, all_boolean_reductions)(skipna=skipna)
+ if skipna:
+ expected = all_boolean_reductions == "all"
+ else:
+ expected = pd.NA
+ assert result is expected
+
+
+def test_from_sequence_of_strings_boolean():
+ true_strings = ["true", "TRUE", "True", "1", "1.0"]
+ false_strings = ["false", "FALSE", "False", "0", "0.0"]
+ nulls = [None]
+ strings = true_strings + false_strings + nulls
+ bools = (
+ [True] * len(true_strings) + [False] * len(false_strings) + [None] * len(nulls)
+ )
+
+ result = ArrowExtensionArray._from_sequence_of_strings(strings, dtype=pa.bool_())
+ expected = pd.array(bools, dtype="boolean[pyarrow]")
+ tm.assert_extension_array_equal(result, expected)
+
+ strings = ["True", "foo"]
+ with pytest.raises(pa.ArrowInvalid, match="Failed to parse"):
+ ArrowExtensionArray._from_sequence_of_strings(strings, dtype=pa.bool_())
+
+
+def test_concat_empty_arrow_backed_series(dtype):
+ # GH#51734
+ ser = pd.Series([], dtype=dtype)
+ expected = ser.copy()
+ result = pd.concat([ser[np.array([], dtype=np.bool_)]])
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["string", "string[pyarrow]"])
+def test_series_from_string_array(dtype):
+ arr = pa.array("the quick brown fox".split())
+ ser = pd.Series(arr, dtype=dtype)
+ expected = pd.Series(ArrowExtensionArray(arr), dtype=dtype)
+ tm.assert_series_equal(ser, expected)
+
+
+# _data was renamed to _pa_data
+class OldArrowExtensionArray(ArrowExtensionArray):
+ def __getstate__(self):
+ state = super().__getstate__()
+ state["_data"] = state.pop("_pa_array")
+ return state
+
+
+def test_pickle_old_arrowextensionarray():
+ data = pa.array([1])
+ expected = OldArrowExtensionArray(data)
+ result = pickle.loads(pickle.dumps(expected))
+ tm.assert_extension_array_equal(result, expected)
+ assert result._pa_array == pa.chunked_array(data)
+ assert not hasattr(result, "_data")
+
+
+def test_setitem_boolean_replace_with_mask_segfault():
+ # GH#52059
+ N = 145_000
+ arr = ArrowExtensionArray(pa.chunked_array([np.ones((N,), dtype=np.bool_)]))
+ expected = arr.copy()
+ arr[np.zeros((N,), dtype=np.bool_)] = False
+ assert arr._pa_array == expected._pa_array
+
+
+@pytest.mark.parametrize(
+ "data, arrow_dtype",
+ [
+ ([b"a", b"b"], pa.large_binary()),
+ (["a", "b"], pa.large_string()),
+ ],
+)
+def test_conversion_large_dtypes_from_numpy_array(data, arrow_dtype):
+ dtype = ArrowDtype(arrow_dtype)
+ result = pd.array(np.array(data), dtype=dtype)
+ expected = pd.array(data, dtype=dtype)
+ tm.assert_extension_array_equal(result, expected)
+
+
+def test_concat_null_array():
+ df = pd.DataFrame({"a": [None, None]}, dtype=ArrowDtype(pa.null()))
+ df2 = pd.DataFrame({"a": [0, 1]}, dtype="int64[pyarrow]")
+
+ result = pd.concat([df, df2], ignore_index=True)
+ expected = pd.DataFrame({"a": [None, None, 0, 1]}, dtype="int64[pyarrow]")
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("pa_type", tm.ALL_INT_PYARROW_DTYPES + tm.FLOAT_PYARROW_DTYPES)
+def test_describe_numeric_data(pa_type):
+ # GH 52470
+ data = pd.Series([1, 2, 3], dtype=ArrowDtype(pa_type))
+ result = data.describe()
+ expected = pd.Series(
+ [3, 2, 1, 1, 1.5, 2.0, 2.5, 3],
+ dtype=ArrowDtype(pa.float64()),
+ index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("pa_type", tm.TIMEDELTA_PYARROW_DTYPES)
+def test_describe_timedelta_data(pa_type):
+ # GH53001
+ data = pd.Series(range(1, 10), dtype=ArrowDtype(pa_type))
+ result = data.describe()
+ expected = pd.Series(
+ [9] + pd.to_timedelta([5, 2, 1, 3, 5, 7, 9], unit=pa_type.unit).tolist(),
+ dtype=object,
+ index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("pa_type", tm.DATETIME_PYARROW_DTYPES)
+def test_describe_datetime_data(pa_type):
+ # GH53001
+ data = pd.Series(range(1, 10), dtype=ArrowDtype(pa_type))
+ result = data.describe()
+ expected = pd.Series(
+ [9]
+ + [
+ pd.Timestamp(v, tz=pa_type.tz, unit=pa_type.unit)
+ for v in [5, 1, 3, 5, 7, 9]
+ ],
+ dtype=object,
+ index=["count", "mean", "min", "25%", "50%", "75%", "max"],
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_quantile_temporal(pa_type):
+ # GH52678
+ data = [1, 2, 3]
+ ser = pd.Series(data, dtype=ArrowDtype(pa_type))
+ result = ser.quantile(0.1)
+ expected = ser[0]
+ assert result == expected
+
+
+def test_date32_repr():
+ # GH48238
+ arrow_dt = pa.array([date.fromisoformat("2020-01-01")], type=pa.date32())
+ ser = pd.Series(arrow_dt, dtype=ArrowDtype(arrow_dt.type))
+ assert repr(ser) == "0 2020-01-01\ndtype: date32[day][pyarrow]"
+
+
+@pytest.mark.xfail(
+ pa_version_under8p0,
+ reason="Function 'add_checked' has no kernel matching input types",
+ raises=pa.ArrowNotImplementedError,
+)
+def test_duration_overflow_from_ndarray_containing_nat():
+ # GH52843
+ data_ts = pd.to_datetime([1, None])
+ data_td = pd.to_timedelta([1, None])
+ ser_ts = pd.Series(data_ts, dtype=ArrowDtype(pa.timestamp("ns")))
+ ser_td = pd.Series(data_td, dtype=ArrowDtype(pa.duration("ns")))
+ result = ser_ts + ser_td
+ expected = pd.Series([2, None], dtype=ArrowDtype(pa.timestamp("ns")))
+ tm.assert_series_equal(result, expected)
+
+
+def test_infer_dtype_pyarrow_dtype(data, request):
+ res = lib.infer_dtype(data)
+ assert res != "unknown-array"
+
+ if data._hasna and res in ["floating", "datetime64", "timedelta64"]:
+ mark = pytest.mark.xfail(
+ reason="in infer_dtype pd.NA is not ignored in these cases "
+ "even with skipna=True in the list(data) check below"
+ )
+ request.node.add_marker(mark)
+
+ assert res == lib.infer_dtype(list(data), skipna=True)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_from_sequence_temporal(pa_type):
+ # GH 53171
+ val = 3
+ unit = pa_type.unit
+ if pa.types.is_duration(pa_type):
+ seq = [pd.Timedelta(val, unit=unit).as_unit(unit)]
+ else:
+ seq = [pd.Timestamp(val, unit=unit, tz=pa_type.tz).as_unit(unit)]
+
+ result = ArrowExtensionArray._from_sequence(seq, dtype=pa_type)
+ expected = ArrowExtensionArray(pa.array([val], type=pa_type))
+ tm.assert_extension_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_setitem_temporal(pa_type):
+ # GH 53171
+ unit = pa_type.unit
+ if pa.types.is_duration(pa_type):
+ val = pd.Timedelta(1, unit=unit).as_unit(unit)
+ else:
+ val = pd.Timestamp(1, unit=unit, tz=pa_type.tz).as_unit(unit)
+
+ arr = ArrowExtensionArray(pa.array([1, 2, 3], type=pa_type))
+
+ result = arr.copy()
+ result[:] = val
+ expected = ArrowExtensionArray(pa.array([1, 1, 1], type=pa_type))
+ tm.assert_extension_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_arithmetic_temporal(pa_type, request):
+ # GH 53171
+ if pa_version_under8p0 and pa.types.is_duration(pa_type):
+ mark = pytest.mark.xfail(
+ raises=pa.ArrowNotImplementedError,
+ reason="Function 'subtract_checked' has no kernel matching input types",
+ )
+ request.node.add_marker(mark)
+
+ arr = ArrowExtensionArray(pa.array([1, 2, 3], type=pa_type))
+ unit = pa_type.unit
+ result = arr - pd.Timedelta(1, unit=unit).as_unit(unit)
+ expected = ArrowExtensionArray(pa.array([0, 1, 2], type=pa_type))
+ tm.assert_extension_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_comparison_temporal(pa_type):
+ # GH 53171
+ unit = pa_type.unit
+ if pa.types.is_duration(pa_type):
+ val = pd.Timedelta(1, unit=unit).as_unit(unit)
+ else:
+ val = pd.Timestamp(1, unit=unit, tz=pa_type.tz).as_unit(unit)
+
+ arr = ArrowExtensionArray(pa.array([1, 2, 3], type=pa_type))
+
+ result = arr > val
+ expected = ArrowExtensionArray(pa.array([False, True, True], type=pa.bool_()))
+ tm.assert_extension_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_getitem_temporal(pa_type):
+ # GH 53326
+ arr = ArrowExtensionArray(pa.array([1, 2, 3], type=pa_type))
+ result = arr[1]
+ if pa.types.is_duration(pa_type):
+ expected = pd.Timedelta(2, unit=pa_type.unit).as_unit(pa_type.unit)
+ assert isinstance(result, pd.Timedelta)
+ else:
+ expected = pd.Timestamp(2, unit=pa_type.unit, tz=pa_type.tz).as_unit(
+ pa_type.unit
+ )
+ assert isinstance(result, pd.Timestamp)
+ assert result.unit == expected.unit
+ assert result == expected
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_iter_temporal(pa_type):
+ # GH 53326
+ arr = ArrowExtensionArray(pa.array([1, None], type=pa_type))
+ result = list(arr)
+ if pa.types.is_duration(pa_type):
+ expected = [
+ pd.Timedelta(1, unit=pa_type.unit).as_unit(pa_type.unit),
+ pd.NA,
+ ]
+ assert isinstance(result[0], pd.Timedelta)
+ else:
+ expected = [
+ pd.Timestamp(1, unit=pa_type.unit, tz=pa_type.tz).as_unit(pa_type.unit),
+ pd.NA,
+ ]
+ assert isinstance(result[0], pd.Timestamp)
+ assert result[0].unit == expected[0].unit
+ assert result == expected
+
+
+def test_groupby_series_size_returns_pa_int(data):
+ # GH 54132
+ ser = pd.Series(data[:3], index=["a", "a", "b"])
+ result = ser.groupby(level=0).size()
+ expected = pd.Series([2, 1], dtype="int64[pyarrow]", index=["a", "b"])
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_to_numpy_temporal(pa_type):
+ # GH 53326
+ arr = ArrowExtensionArray(pa.array([1, None], type=pa_type))
+ result = arr.to_numpy()
+ if pa.types.is_duration(pa_type):
+ expected = [
+ pd.Timedelta(1, unit=pa_type.unit).as_unit(pa_type.unit),
+ pd.NA,
+ ]
+ assert isinstance(result[0], pd.Timedelta)
+ else:
+ expected = [
+ pd.Timestamp(1, unit=pa_type.unit, tz=pa_type.tz).as_unit(pa_type.unit),
+ pd.NA,
+ ]
+ assert isinstance(result[0], pd.Timestamp)
+ expected = np.array(expected, dtype=object)
+ assert result[0].unit == expected[0].unit
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_groupby_count_return_arrow_dtype(data_missing):
+ df = pd.DataFrame({"A": [1, 1], "B": data_missing, "C": data_missing})
+ result = df.groupby("A").count()
+ expected = pd.DataFrame(
+ [[1, 1]],
+ index=pd.Index([1], name="A"),
+ columns=["B", "C"],
+ dtype="int64[pyarrow]",
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_fixed_size_list():
+ # GH#55000
+ ser = pd.Series(
+ [[1, 2], [3, 4]], dtype=ArrowDtype(pa.list_(pa.int64(), list_size=2))
+ )
+ result = ser.dtype.type
+ assert result == list
+
+
+def test_arrowextensiondtype_dataframe_repr():
+ # GH 54062
+ df = pd.DataFrame(
+ pd.period_range("2012", periods=3),
+ columns=["col"],
+ dtype=ArrowDtype(ArrowPeriodType("D")),
+ )
+ result = repr(df)
+ # TODO: repr value may not be expected; address how
+ # pyarrow.ExtensionType values are displayed
+ expected = " col\n0 15340\n1 15341\n2 15342"
+ assert result == expected
+
+
+@pytest.mark.parametrize("pa_type", tm.TIMEDELTA_PYARROW_DTYPES)
+def test_duration_fillna_numpy(pa_type):
+ # GH 54707
+ ser1 = pd.Series([None, 2], dtype=ArrowDtype(pa_type))
+ ser2 = pd.Series(np.array([1, 3], dtype=f"m8[{pa_type.unit}]"))
+ result = ser1.fillna(ser2)
+ expected = pd.Series([1, 2], dtype=ArrowDtype(pa_type))
+ tm.assert_series_equal(result, expected)
+
+
+def test_comparison_not_propagating_arrow_error():
+ # GH#54944
+ a = pd.Series([1 << 63], dtype="uint64[pyarrow]")
+ b = pd.Series([None], dtype="int64[pyarrow]")
+ with pytest.raises(pa.lib.ArrowInvalid, match="Integer value"):
+ a < b
+
+
+def test_factorize_chunked_dictionary():
+ # GH 54844
+ pa_array = pa.chunked_array(
+ [pa.array(["a"]).dictionary_encode(), pa.array(["b"]).dictionary_encode()]
+ )
+ ser = pd.Series(ArrowExtensionArray(pa_array))
+ res_indices, res_uniques = ser.factorize()
+ exp_indicies = np.array([0, 1], dtype=np.intp)
+ exp_uniques = pd.Index(ArrowExtensionArray(pa_array.combine_chunks()))
+ tm.assert_numpy_array_equal(res_indices, exp_indicies)
+ tm.assert_index_equal(res_uniques, exp_uniques)
+
+
+def test_arrow_floordiv():
+ # GH 55561
+ a = pd.Series([-7], dtype="int64[pyarrow]")
+ b = pd.Series([4], dtype="int64[pyarrow]")
+ expected = pd.Series([-2], dtype="int64[pyarrow]")
+ result = a // b
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_categorical.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_categorical.py
new file mode 100644
index 0000000000000000000000000000000000000000..33e5c9ad72982c2b6e8da9f485850b0b9619e0aa
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_categorical.py
@@ -0,0 +1,232 @@
+"""
+This file contains a minimal set of tests for compliance with the extension
+array interface test suite, and should contain no other tests.
+The test suite for the full functionality of the array is located in
+`pandas/tests/arrays/`.
+
+The tests in this file are inherited from the BaseExtensionTests, and only
+minimal tweaks should be applied to get the tests passing (by overwriting a
+parent method).
+
+Additional tests should either be added to one of the BaseExtensionTests
+classes (if they are relevant for the extension interface for all dtypes), or
+be added to the array-specific tests in `pandas/tests/arrays/`.
+
+"""
+import string
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import Categorical
+import pandas._testing as tm
+from pandas.api.types import CategoricalDtype
+from pandas.tests.extension import base
+
+
+def make_data():
+ while True:
+ values = np.random.default_rng(2).choice(list(string.ascii_letters), size=100)
+ # ensure we meet the requirements
+ # 1. first two not null
+ # 2. first and second are different
+ if values[0] != values[1]:
+ break
+ return values
+
+
+@pytest.fixture
+def dtype():
+ return CategoricalDtype()
+
+
+@pytest.fixture
+def data():
+ """Length-100 array for this type.
+
+ * data[0] and data[1] should both be non missing
+ * data[0] and data[1] should not be equal
+ """
+ return Categorical(make_data())
+
+
+@pytest.fixture
+def data_missing():
+ """Length 2 array with [NA, Valid]"""
+ return Categorical([np.nan, "A"])
+
+
+@pytest.fixture
+def data_for_sorting():
+ return Categorical(["A", "B", "C"], categories=["C", "A", "B"], ordered=True)
+
+
+@pytest.fixture
+def data_missing_for_sorting():
+ return Categorical(["A", None, "B"], categories=["B", "A"], ordered=True)
+
+
+@pytest.fixture
+def data_for_grouping():
+ return Categorical(["a", "a", None, None, "b", "b", "a", "c"])
+
+
+class TestDtype(base.BaseDtypeTests):
+ pass
+
+
+class TestInterface(base.BaseInterfaceTests):
+ @pytest.mark.xfail(reason="Memory usage doesn't match")
+ def test_memory_usage(self, data):
+ # TODO: Is this deliberate?
+ super().test_memory_usage(data)
+
+ def test_contains(self, data, data_missing):
+ # GH-37867
+ # na value handling in Categorical.__contains__ is deprecated.
+ # See base.BaseInterFaceTests.test_contains for more details.
+
+ na_value = data.dtype.na_value
+ # ensure data without missing values
+ data = data[~data.isna()]
+
+ # first elements are non-missing
+ assert data[0] in data
+ assert data_missing[0] in data_missing
+
+ # check the presence of na_value
+ assert na_value in data_missing
+ assert na_value not in data
+
+ # Categoricals can contain other nan-likes than na_value
+ for na_value_obj in tm.NULL_OBJECTS:
+ if na_value_obj is na_value:
+ continue
+ assert na_value_obj not in data
+ assert na_value_obj in data_missing # this line differs from super method
+
+
+class TestConstructors(base.BaseConstructorsTests):
+ def test_empty(self, dtype):
+ cls = dtype.construct_array_type()
+ result = cls._empty((4,), dtype=dtype)
+
+ assert isinstance(result, cls)
+ # the dtype we passed is not initialized, so will not match the
+ # dtype on our result.
+ assert result.dtype == CategoricalDtype([])
+
+
+class TestReshaping(base.BaseReshapingTests):
+ pass
+
+
+class TestGetitem(base.BaseGetitemTests):
+ @pytest.mark.skip(reason="Backwards compatibility")
+ def test_getitem_scalar(self, data):
+ # CategoricalDtype.type isn't "correct" since it should
+ # be a parent of the elements (object). But don't want
+ # to break things by changing.
+ super().test_getitem_scalar(data)
+
+
+class TestSetitem(base.BaseSetitemTests):
+ pass
+
+
+class TestIndex(base.BaseIndexTests):
+ pass
+
+
+class TestMissing(base.BaseMissingTests):
+ pass
+
+
+class TestReduce(base.BaseReduceTests):
+ pass
+
+
+class TestAccumulate(base.BaseAccumulateTests):
+ pass
+
+
+class TestMethods(base.BaseMethodsTests):
+ @pytest.mark.xfail(reason="Unobserved categories included")
+ def test_value_counts(self, all_data, dropna):
+ return super().test_value_counts(all_data, dropna)
+
+ def test_combine_add(self, data_repeated):
+ # GH 20825
+ # When adding categoricals in combine, result is a string
+ orig_data1, orig_data2 = data_repeated(2)
+ s1 = pd.Series(orig_data1)
+ s2 = pd.Series(orig_data2)
+ result = s1.combine(s2, lambda x1, x2: x1 + x2)
+ expected = pd.Series(
+ [a + b for (a, b) in zip(list(orig_data1), list(orig_data2))]
+ )
+ tm.assert_series_equal(result, expected)
+
+ val = s1.iloc[0]
+ result = s1.combine(val, lambda x1, x2: x1 + x2)
+ expected = pd.Series([a + val for a in list(orig_data1)])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("na_action", [None, "ignore"])
+ def test_map(self, data, na_action):
+ result = data.map(lambda x: x, na_action=na_action)
+ tm.assert_extension_array_equal(result, data)
+
+
+class TestCasting(base.BaseCastingTests):
+ pass
+
+
+class TestArithmeticOps(base.BaseArithmeticOpsTests):
+ def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request):
+ # frame & scalar
+ op_name = all_arithmetic_operators
+ if op_name == "__rmod__":
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="rmod never called when string is first argument"
+ )
+ )
+ super().test_arith_frame_with_scalar(data, op_name)
+
+ def test_arith_series_with_scalar(self, data, all_arithmetic_operators, request):
+ op_name = all_arithmetic_operators
+ if op_name == "__rmod__":
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="rmod never called when string is first argument"
+ )
+ )
+ super().test_arith_series_with_scalar(data, op_name)
+
+
+class TestComparisonOps(base.BaseComparisonOpsTests):
+ def _compare_other(self, s, data, op, other):
+ op_name = f"__{op.__name__}__"
+ if op_name not in ["__eq__", "__ne__"]:
+ msg = "Unordered Categoricals can only compare equality or not"
+ with pytest.raises(TypeError, match=msg):
+ op(data, other)
+ else:
+ return super()._compare_other(s, data, op, other)
+
+
+class TestParsing(base.BaseParsingTests):
+ pass
+
+
+class Test2DCompat(base.NDArrayBacked2DTests):
+ def test_repr_2d(self, data):
+ # Categorical __repr__ doesn't include "Categorical", so we need
+ # to special-case
+ res = repr(data.reshape(1, -1))
+ assert res.count("\nCategories") == 1
+
+ res = repr(data.reshape(-1, 1))
+ assert res.count("\nCategories") == 1
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d8523f344d46132c5263f8130d70f9e8c8197df
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_common.py
@@ -0,0 +1,103 @@
+import numpy as np
+import pytest
+
+from pandas.core.dtypes import dtypes
+from pandas.core.dtypes.common import is_extension_array_dtype
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import ExtensionArray
+
+
+class DummyDtype(dtypes.ExtensionDtype):
+ pass
+
+
+class DummyArray(ExtensionArray):
+ def __init__(self, data) -> None:
+ self.data = data
+
+ def __array__(self, dtype):
+ return self.data
+
+ @property
+ def dtype(self):
+ return DummyDtype()
+
+ def astype(self, dtype, copy=True):
+ # we don't support anything but a single dtype
+ if isinstance(dtype, DummyDtype):
+ if copy:
+ return type(self)(self.data)
+ return self
+
+ return np.array(self, dtype=dtype, copy=copy)
+
+
+class TestExtensionArrayDtype:
+ @pytest.mark.parametrize(
+ "values",
+ [
+ pd.Categorical([]),
+ pd.Categorical([]).dtype,
+ pd.Series(pd.Categorical([])),
+ DummyDtype(),
+ DummyArray(np.array([1, 2])),
+ ],
+ )
+ def test_is_extension_array_dtype(self, values):
+ assert is_extension_array_dtype(values)
+
+ @pytest.mark.parametrize("values", [np.array([]), pd.Series(np.array([]))])
+ def test_is_not_extension_array_dtype(self, values):
+ assert not is_extension_array_dtype(values)
+
+
+def test_astype():
+ arr = DummyArray(np.array([1, 2, 3]))
+ expected = np.array([1, 2, 3], dtype=object)
+
+ result = arr.astype(object)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = arr.astype("object")
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_astype_no_copy():
+ arr = DummyArray(np.array([1, 2, 3], dtype=np.int64))
+ result = arr.astype(arr.dtype, copy=False)
+
+ assert arr is result
+
+ result = arr.astype(arr.dtype)
+ assert arr is not result
+
+
+@pytest.mark.parametrize("dtype", [dtypes.CategoricalDtype(), dtypes.IntervalDtype()])
+def test_is_extension_array_dtype(dtype):
+ assert isinstance(dtype, dtypes.ExtensionDtype)
+ assert is_extension_array_dtype(dtype)
+
+
+class CapturingStringArray(pd.arrays.StringArray):
+ """Extend StringArray to capture arguments to __getitem__"""
+
+ def __getitem__(self, item):
+ self.last_item_arg = item
+ return super().__getitem__(item)
+
+
+def test_ellipsis_index():
+ # GH#42430 1D slices over extension types turn into N-dimensional slices
+ # over ExtensionArrays
+ df = pd.DataFrame(
+ {"col1": CapturingStringArray(np.array(["hello", "world"], dtype=object))}
+ )
+ _ = df.iloc[:1]
+
+ # String comparison because there's no native way to compare slices.
+ # Before the fix for GH#42430, last_item_arg would get set to the 2D slice
+ # (Ellipsis, slice(None, 1, None))
+ out = df["col1"].array.last_item_arg
+ assert str(out) == "slice(None, 1, None)"
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_datetime.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_datetime.py
new file mode 100644
index 0000000000000000000000000000000000000000..97773d0d40a570887e8aa783cf7a5b8aba5aab83
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_datetime.py
@@ -0,0 +1,159 @@
+"""
+This file contains a minimal set of tests for compliance with the extension
+array interface test suite, and should contain no other tests.
+The test suite for the full functionality of the array is located in
+`pandas/tests/arrays/`.
+
+The tests in this file are inherited from the BaseExtensionTests, and only
+minimal tweaks should be applied to get the tests passing (by overwriting a
+parent method).
+
+Additional tests should either be added to one of the BaseExtensionTests
+classes (if they are relevant for the extension interface for all dtypes), or
+be added to the array-specific tests in `pandas/tests/arrays/`.
+
+"""
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.dtypes import DatetimeTZDtype
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import DatetimeArray
+from pandas.tests.extension import base
+
+
+@pytest.fixture(params=["US/Central"])
+def dtype(request):
+ return DatetimeTZDtype(unit="ns", tz=request.param)
+
+
+@pytest.fixture
+def data(dtype):
+ data = DatetimeArray(pd.date_range("2000", periods=100, tz=dtype.tz), dtype=dtype)
+ return data
+
+
+@pytest.fixture
+def data_missing(dtype):
+ return DatetimeArray(
+ np.array(["NaT", "2000-01-01"], dtype="datetime64[ns]"), dtype=dtype
+ )
+
+
+@pytest.fixture
+def data_for_sorting(dtype):
+ a = pd.Timestamp("2000-01-01")
+ b = pd.Timestamp("2000-01-02")
+ c = pd.Timestamp("2000-01-03")
+ return DatetimeArray(np.array([b, c, a], dtype="datetime64[ns]"), dtype=dtype)
+
+
+@pytest.fixture
+def data_missing_for_sorting(dtype):
+ a = pd.Timestamp("2000-01-01")
+ b = pd.Timestamp("2000-01-02")
+ return DatetimeArray(np.array([b, "NaT", a], dtype="datetime64[ns]"), dtype=dtype)
+
+
+@pytest.fixture
+def data_for_grouping(dtype):
+ """
+ Expected to be like [B, B, NA, NA, A, A, B, C]
+
+ Where A < B < C and NA is missing
+ """
+ a = pd.Timestamp("2000-01-01")
+ b = pd.Timestamp("2000-01-02")
+ c = pd.Timestamp("2000-01-03")
+ na = "NaT"
+ return DatetimeArray(
+ np.array([b, b, na, na, a, a, b, c], dtype="datetime64[ns]"), dtype=dtype
+ )
+
+
+@pytest.fixture
+def na_cmp():
+ def cmp(a, b):
+ return a is pd.NaT and a is b
+
+ return cmp
+
+
+# ----------------------------------------------------------------------------
+class BaseDatetimeTests:
+ pass
+
+
+# ----------------------------------------------------------------------------
+# Tests
+class TestDatetimeDtype(BaseDatetimeTests, base.BaseDtypeTests):
+ pass
+
+
+class TestConstructors(BaseDatetimeTests, base.BaseConstructorsTests):
+ def test_series_constructor(self, data):
+ # Series construction drops any .freq attr
+ data = data._with_freq(None)
+ super().test_series_constructor(data)
+
+
+class TestGetitem(BaseDatetimeTests, base.BaseGetitemTests):
+ pass
+
+
+class TestIndex(base.BaseIndexTests):
+ pass
+
+
+class TestMethods(BaseDatetimeTests, base.BaseMethodsTests):
+ @pytest.mark.parametrize("na_action", [None, "ignore"])
+ def test_map(self, data, na_action):
+ result = data.map(lambda x: x, na_action=na_action)
+ tm.assert_extension_array_equal(result, data)
+
+
+class TestInterface(BaseDatetimeTests, base.BaseInterfaceTests):
+ pass
+
+
+class TestArithmeticOps(BaseDatetimeTests, base.BaseArithmeticOpsTests):
+ implements = {"__sub__", "__rsub__"}
+
+ def _get_expected_exception(self, op_name, obj, other):
+ if op_name in self.implements:
+ return None
+ return super()._get_expected_exception(op_name, obj, other)
+
+
+class TestCasting(BaseDatetimeTests, base.BaseCastingTests):
+ pass
+
+
+class TestComparisonOps(BaseDatetimeTests, base.BaseComparisonOpsTests):
+ pass
+
+
+class TestMissing(BaseDatetimeTests, base.BaseMissingTests):
+ pass
+
+
+class TestReshaping(BaseDatetimeTests, base.BaseReshapingTests):
+ pass
+
+
+class TestSetitem(BaseDatetimeTests, base.BaseSetitemTests):
+ pass
+
+
+class TestGroupby(BaseDatetimeTests, base.BaseGroupbyTests):
+ pass
+
+
+class TestPrinting(BaseDatetimeTests, base.BasePrintingTests):
+ pass
+
+
+class Test2DCompat(BaseDatetimeTests, base.NDArrayBacked2DTests):
+ pass
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_extension.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_extension.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ed626cd5108081eff7156275f439ececdf28241
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_extension.py
@@ -0,0 +1,26 @@
+"""
+Tests for behavior if an author does *not* implement EA methods.
+"""
+import numpy as np
+import pytest
+
+from pandas.core.arrays import ExtensionArray
+
+
+class MyEA(ExtensionArray):
+ def __init__(self, values) -> None:
+ self._values = values
+
+
+@pytest.fixture
+def data():
+ arr = np.arange(10)
+ return MyEA(arr)
+
+
+class TestExtensionArray:
+ def test_errors(self, data, all_arithmetic_operators):
+ # invalid ops
+ op_name = all_arithmetic_operators
+ with pytest.raises(AttributeError):
+ getattr(data, op_name)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_interval.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_interval.py
new file mode 100644
index 0000000000000000000000000000000000000000..66b25abb559617aca167448a59004e23ef5f355c
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_interval.py
@@ -0,0 +1,103 @@
+"""
+This file contains a minimal set of tests for compliance with the extension
+array interface test suite, and should contain no other tests.
+The test suite for the full functionality of the array is located in
+`pandas/tests/arrays/`.
+
+The tests in this file are inherited from the BaseExtensionTests, and only
+minimal tweaks should be applied to get the tests passing (by overwriting a
+parent method).
+
+Additional tests should either be added to one of the BaseExtensionTests
+classes (if they are relevant for the extension interface for all dtypes), or
+be added to the array-specific tests in `pandas/tests/arrays/`.
+
+"""
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.dtypes import IntervalDtype
+
+from pandas import Interval
+from pandas.core.arrays import IntervalArray
+from pandas.tests.extension import base
+
+
+def make_data():
+ N = 100
+ left_array = np.random.default_rng(2).uniform(size=N).cumsum()
+ right_array = left_array + np.random.default_rng(2).uniform(size=N)
+ return [Interval(left, right) for left, right in zip(left_array, right_array)]
+
+
+@pytest.fixture
+def dtype():
+ return IntervalDtype()
+
+
+@pytest.fixture
+def data():
+ """Length-100 PeriodArray for semantics test."""
+ return IntervalArray(make_data())
+
+
+@pytest.fixture
+def data_missing():
+ """Length 2 array with [NA, Valid]"""
+ return IntervalArray.from_tuples([None, (0, 1)])
+
+
+@pytest.fixture
+def data_for_twos():
+ pytest.skip("Not a numeric dtype")
+
+
+@pytest.fixture
+def data_for_sorting():
+ return IntervalArray.from_tuples([(1, 2), (2, 3), (0, 1)])
+
+
+@pytest.fixture
+def data_missing_for_sorting():
+ return IntervalArray.from_tuples([(1, 2), None, (0, 1)])
+
+
+@pytest.fixture
+def data_for_grouping():
+ a = (0, 1)
+ b = (1, 2)
+ c = (2, 3)
+ return IntervalArray.from_tuples([b, b, None, None, a, a, b, c])
+
+
+class TestIntervalArray(base.ExtensionTests):
+ divmod_exc = TypeError
+
+ def _supports_reduction(self, obj, op_name: str) -> bool:
+ return op_name in ["min", "max"]
+
+ @pytest.mark.xfail(
+ reason="Raises with incorrect message bc it disallows *all* listlikes "
+ "instead of just wrong-length listlikes"
+ )
+ def test_fillna_length_mismatch(self, data_missing):
+ super().test_fillna_length_mismatch(data_missing)
+
+ @pytest.mark.parametrize("engine", ["c", "python"])
+ def test_EA_types(self, engine, data):
+ expected_msg = r".*must implement _from_sequence_of_strings.*"
+ with pytest.raises(NotImplementedError, match=expected_msg):
+ super().test_EA_types(engine, data)
+
+ @pytest.mark.xfail(
+ reason="Looks like the test (incorrectly) implicitly assumes int/bool dtype"
+ )
+ def test_invert(self, data):
+ super().test_invert(data)
+
+
+# TODO: either belongs in tests.arrays.interval or move into base tests.
+def test_fillna_non_scalar_raises(data_missing):
+ msg = "can only insert Interval objects and NA into an IntervalArray"
+ with pytest.raises(TypeError, match=msg):
+ data_missing.fillna([1, 1])
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_masked.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_masked.py
new file mode 100644
index 0000000000000000000000000000000000000000..588a2fb58d9be246180e51e0f60483e9d5e42aff
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_masked.py
@@ -0,0 +1,452 @@
+"""
+This file contains a minimal set of tests for compliance with the extension
+array interface test suite, and should contain no other tests.
+The test suite for the full functionality of the array is located in
+`pandas/tests/arrays/`.
+
+The tests in this file are inherited from the BaseExtensionTests, and only
+minimal tweaks should be applied to get the tests passing (by overwriting a
+parent method).
+
+Additional tests should either be added to one of the BaseExtensionTests
+classes (if they are relevant for the extension interface for all dtypes), or
+be added to the array-specific tests in `pandas/tests/arrays/`.
+
+"""
+import numpy as np
+import pytest
+
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
+from pandas.compat.numpy import np_version_gt2
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays.boolean import BooleanDtype
+from pandas.core.arrays.floating import (
+ Float32Dtype,
+ Float64Dtype,
+)
+from pandas.core.arrays.integer import (
+ Int8Dtype,
+ Int16Dtype,
+ Int32Dtype,
+ Int64Dtype,
+ UInt8Dtype,
+ UInt16Dtype,
+ UInt32Dtype,
+ UInt64Dtype,
+)
+from pandas.tests.extension import base
+
+is_windows_or_32bit = (is_platform_windows() and not np_version_gt2) or not IS64
+
+pytestmark = [
+ pytest.mark.filterwarnings(
+ "ignore:invalid value encountered in divide:RuntimeWarning"
+ ),
+ pytest.mark.filterwarnings("ignore:Mean of empty slice:RuntimeWarning"),
+ # overflow only relevant for Floating dtype cases cases
+ pytest.mark.filterwarnings("ignore:overflow encountered in reduce:RuntimeWarning"),
+]
+
+
+def make_data():
+ return list(range(1, 9)) + [pd.NA] + list(range(10, 98)) + [pd.NA] + [99, 100]
+
+
+def make_float_data():
+ return (
+ list(np.arange(0.1, 0.9, 0.1))
+ + [pd.NA]
+ + list(np.arange(1, 9.8, 0.1))
+ + [pd.NA]
+ + [9.9, 10.0]
+ )
+
+
+def make_bool_data():
+ return [True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False]
+
+
+@pytest.fixture(
+ params=[
+ Int8Dtype,
+ Int16Dtype,
+ Int32Dtype,
+ Int64Dtype,
+ UInt8Dtype,
+ UInt16Dtype,
+ UInt32Dtype,
+ UInt64Dtype,
+ Float32Dtype,
+ Float64Dtype,
+ BooleanDtype,
+ ]
+)
+def dtype(request):
+ return request.param()
+
+
+@pytest.fixture
+def data(dtype):
+ if dtype.kind == "f":
+ data = make_float_data()
+ elif dtype.kind == "b":
+ data = make_bool_data()
+ else:
+ data = make_data()
+ return pd.array(data, dtype=dtype)
+
+
+@pytest.fixture
+def data_for_twos(dtype):
+ if dtype.kind == "b":
+ return pd.array(np.ones(100), dtype=dtype)
+ return pd.array(np.ones(100) * 2, dtype=dtype)
+
+
+@pytest.fixture
+def data_missing(dtype):
+ if dtype.kind == "f":
+ return pd.array([pd.NA, 0.1], dtype=dtype)
+ elif dtype.kind == "b":
+ return pd.array([np.nan, True], dtype=dtype)
+ return pd.array([pd.NA, 1], dtype=dtype)
+
+
+@pytest.fixture
+def data_for_sorting(dtype):
+ if dtype.kind == "f":
+ return pd.array([0.1, 0.2, 0.0], dtype=dtype)
+ elif dtype.kind == "b":
+ return pd.array([True, True, False], dtype=dtype)
+ return pd.array([1, 2, 0], dtype=dtype)
+
+
+@pytest.fixture
+def data_missing_for_sorting(dtype):
+ if dtype.kind == "f":
+ return pd.array([0.1, pd.NA, 0.0], dtype=dtype)
+ elif dtype.kind == "b":
+ return pd.array([True, np.nan, False], dtype=dtype)
+ return pd.array([1, pd.NA, 0], dtype=dtype)
+
+
+@pytest.fixture
+def na_cmp():
+ # we are pd.NA
+ return lambda x, y: x is pd.NA and y is pd.NA
+
+
+@pytest.fixture
+def data_for_grouping(dtype):
+ if dtype.kind == "f":
+ b = 0.1
+ a = 0.0
+ c = 0.2
+ elif dtype.kind == "b":
+ b = True
+ a = False
+ c = b
+ else:
+ b = 1
+ a = 0
+ c = 2
+
+ na = pd.NA
+ return pd.array([b, b, na, na, a, a, b, c], dtype=dtype)
+
+
+class TestDtype(base.BaseDtypeTests):
+ pass
+
+
+class TestArithmeticOps(base.BaseArithmeticOpsTests):
+ def _get_expected_exception(self, op_name, obj, other):
+ try:
+ dtype = tm.get_dtype(obj)
+ except AttributeError:
+ # passed arguments reversed
+ dtype = tm.get_dtype(other)
+
+ if dtype.kind == "b":
+ if op_name.strip("_").lstrip("r") in ["pow", "truediv", "floordiv"]:
+ # match behavior with non-masked bool dtype
+ return NotImplementedError
+ elif op_name in ["__sub__", "__rsub__"]:
+ # exception message would include "numpy boolean subtract""
+ return TypeError
+ return None
+ return super()._get_expected_exception(op_name, obj, other)
+
+ def _cast_pointwise_result(self, op_name: str, obj, other, pointwise_result):
+ sdtype = tm.get_dtype(obj)
+ expected = pointwise_result
+
+ if sdtype.kind in "iu":
+ if op_name in ("__rtruediv__", "__truediv__", "__div__"):
+ expected = expected.fillna(np.nan).astype("Float64")
+ else:
+ # combine method result in 'biggest' (int64) dtype
+ expected = expected.astype(sdtype)
+ elif sdtype.kind == "b":
+ if op_name in (
+ "__floordiv__",
+ "__rfloordiv__",
+ "__pow__",
+ "__rpow__",
+ "__mod__",
+ "__rmod__",
+ ):
+ # combine keeps boolean type
+ expected = expected.astype("Int8")
+
+ elif op_name in ("__truediv__", "__rtruediv__"):
+ # combine with bools does not generate the correct result
+ # (numpy behaviour for div is to regard the bools as numeric)
+ op = self.get_op_from_name(op_name)
+ expected = self._combine(obj.astype(float), other, op)
+ expected = expected.astype("Float64")
+
+ if op_name == "__rpow__":
+ # for rpow, combine does not propagate NaN
+ result = getattr(obj, op_name)(other)
+ expected[result.isna()] = np.nan
+ else:
+ # combine method result in 'biggest' (float64) dtype
+ expected = expected.astype(sdtype)
+ return expected
+
+ series_scalar_exc = None
+ series_array_exc = None
+ frame_scalar_exc = None
+ divmod_exc = None
+
+ def test_divmod_series_array(self, data, data_for_twos, request):
+ if data.dtype.kind == "b":
+ mark = pytest.mark.xfail(
+ reason="Inconsistency between floordiv and divmod; we raise for "
+ "floordiv but not for divmod. This matches what we do for "
+ "non-masked bool dtype."
+ )
+ request.node.add_marker(mark)
+ super().test_divmod_series_array(data, data_for_twos)
+
+
+class TestComparisonOps(base.BaseComparisonOpsTests):
+ series_scalar_exc = None
+ series_array_exc = None
+ frame_scalar_exc = None
+
+ def _cast_pointwise_result(self, op_name: str, obj, other, pointwise_result):
+ return pointwise_result.astype("boolean")
+
+
+class TestInterface(base.BaseInterfaceTests):
+ pass
+
+
+class TestConstructors(base.BaseConstructorsTests):
+ pass
+
+
+class TestReshaping(base.BaseReshapingTests):
+ pass
+
+ # for test_concat_mixed_dtypes test
+ # concat of an Integer and Int coerces to object dtype
+ # TODO(jreback) once integrated this would
+
+
+class TestGetitem(base.BaseGetitemTests):
+ pass
+
+
+class TestSetitem(base.BaseSetitemTests):
+ pass
+
+
+class TestIndex(base.BaseIndexTests):
+ pass
+
+
+class TestMissing(base.BaseMissingTests):
+ pass
+
+
+class TestMethods(base.BaseMethodsTests):
+ def test_combine_le(self, data_repeated):
+ # TODO: patching self is a bad pattern here
+ orig_data1, orig_data2 = data_repeated(2)
+ if orig_data1.dtype.kind == "b":
+ self._combine_le_expected_dtype = "boolean"
+ else:
+ # TODO: can we make this boolean?
+ self._combine_le_expected_dtype = object
+ super().test_combine_le(data_repeated)
+
+
+class TestCasting(base.BaseCastingTests):
+ pass
+
+
+class TestGroupby(base.BaseGroupbyTests):
+ pass
+
+
+class TestReduce(base.BaseReduceTests):
+ def _supports_reduction(self, obj, op_name: str) -> bool:
+ if op_name in ["any", "all"] and tm.get_dtype(obj).kind != "b":
+ pytest.skip(reason="Tested in tests/reductions/test_reductions.py")
+ return True
+
+ def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool):
+ # overwrite to ensure pd.NA is tested instead of np.nan
+ # https://github.com/pandas-dev/pandas/issues/30958
+
+ cmp_dtype = "int64"
+ if ser.dtype.kind == "f":
+ # Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]" has
+ # no attribute "numpy_dtype"
+ cmp_dtype = ser.dtype.numpy_dtype # type: ignore[union-attr]
+ elif ser.dtype.kind == "b":
+ if op_name in ["min", "max"]:
+ cmp_dtype = "bool"
+
+ if op_name == "count":
+ result = getattr(ser, op_name)()
+ expected = getattr(ser.dropna().astype(cmp_dtype), op_name)()
+ else:
+ result = getattr(ser, op_name)(skipna=skipna)
+ expected = getattr(ser.dropna().astype(cmp_dtype), op_name)(skipna=skipna)
+ if not skipna and ser.isna().any() and op_name not in ["any", "all"]:
+ expected = pd.NA
+ tm.assert_almost_equal(result, expected)
+
+ def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool):
+ if tm.is_float_dtype(arr.dtype):
+ cmp_dtype = arr.dtype.name
+ elif op_name in ["mean", "median", "var", "std", "skew"]:
+ cmp_dtype = "Float64"
+ elif op_name in ["max", "min"]:
+ cmp_dtype = arr.dtype.name
+ elif arr.dtype in ["Int64", "UInt64"]:
+ cmp_dtype = arr.dtype.name
+ elif tm.is_signed_integer_dtype(arr.dtype):
+ # TODO: Why does Window Numpy 2.0 dtype depend on skipna?
+ cmp_dtype = (
+ "Int32"
+ if (is_platform_windows() and (not np_version_gt2 or not skipna))
+ or not IS64
+ else "Int64"
+ )
+ elif tm.is_unsigned_integer_dtype(arr.dtype):
+ cmp_dtype = (
+ "UInt32"
+ if (is_platform_windows() and (not np_version_gt2 or not skipna))
+ or not IS64
+ else "UInt64"
+ )
+ elif arr.dtype.kind == "b":
+ if op_name in ["mean", "median", "var", "std", "skew"]:
+ cmp_dtype = "Float64"
+ elif op_name in ["min", "max"]:
+ cmp_dtype = "boolean"
+ elif op_name in ["sum", "prod"]:
+ cmp_dtype = (
+ "Int32"
+ if (is_platform_windows() and (not np_version_gt2 or not skipna))
+ or not IS64
+ else "Int64"
+ )
+ else:
+ raise TypeError("not supposed to reach this")
+ else:
+ raise TypeError("not supposed to reach this")
+ return cmp_dtype
+
+
+class TestAccumulation(base.BaseAccumulateTests):
+ def _supports_accumulation(self, ser: pd.Series, op_name: str) -> bool:
+ return True
+
+ def check_accumulate(self, ser: pd.Series, op_name: str, skipna: bool):
+ # overwrite to ensure pd.NA is tested instead of np.nan
+ # https://github.com/pandas-dev/pandas/issues/30958
+ length = 64
+ if is_windows_or_32bit:
+ # Item "ExtensionDtype" of "Union[dtype[Any], ExtensionDtype]" has
+ # no attribute "itemsize"
+ if not ser.dtype.itemsize == 8: # type: ignore[union-attr]
+ length = 32
+
+ if ser.dtype.name.startswith("U"):
+ expected_dtype = f"UInt{length}"
+ elif ser.dtype.name.startswith("I"):
+ expected_dtype = f"Int{length}"
+ elif ser.dtype.name.startswith("F"):
+ # Incompatible types in assignment (expression has type
+ # "Union[dtype[Any], ExtensionDtype]", variable has type "str")
+ expected_dtype = ser.dtype # type: ignore[assignment]
+ elif ser.dtype.kind == "b":
+ if op_name in ("cummin", "cummax"):
+ expected_dtype = "boolean"
+ else:
+ expected_dtype = f"Int{length}"
+
+ if op_name == "cumsum":
+ result = getattr(ser, op_name)(skipna=skipna)
+ expected = pd.Series(
+ pd.array(
+ getattr(ser.astype("float64"), op_name)(skipna=skipna),
+ dtype=expected_dtype,
+ )
+ )
+ tm.assert_series_equal(result, expected)
+ elif op_name in ["cummax", "cummin"]:
+ result = getattr(ser, op_name)(skipna=skipna)
+ expected = pd.Series(
+ pd.array(
+ getattr(ser.astype("float64"), op_name)(skipna=skipna),
+ dtype=ser.dtype,
+ )
+ )
+ tm.assert_series_equal(result, expected)
+ elif op_name == "cumprod":
+ result = getattr(ser[:12], op_name)(skipna=skipna)
+ expected = pd.Series(
+ pd.array(
+ getattr(ser[:12].astype("float64"), op_name)(skipna=skipna),
+ dtype=expected_dtype,
+ )
+ )
+ tm.assert_series_equal(result, expected)
+
+ else:
+ raise NotImplementedError(f"{op_name} not supported")
+
+
+class TestUnaryOps(base.BaseUnaryOpsTests):
+ def test_invert(self, data, request):
+ if data.dtype.kind == "f":
+ mark = pytest.mark.xfail(
+ reason="Looks like the base class test implicitly assumes "
+ "boolean/integer dtypes"
+ )
+ request.node.add_marker(mark)
+ super().test_invert(data)
+
+
+class TestPrinting(base.BasePrintingTests):
+ pass
+
+
+class TestParsing(base.BaseParsingTests):
+ pass
+
+
+class Test2DCompat(base.Dim2CompatTests):
+ pass
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_numpy.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..a54729de57a97c3bc46de5aab1f6495afc5b922f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_numpy.py
@@ -0,0 +1,437 @@
+"""
+This file contains a minimal set of tests for compliance with the extension
+array interface test suite, and should contain no other tests.
+The test suite for the full functionality of the array is located in
+`pandas/tests/arrays/`.
+
+The tests in this file are inherited from the BaseExtensionTests, and only
+minimal tweaks should be applied to get the tests passing (by overwriting a
+parent method).
+
+Additional tests should either be added to one of the BaseExtensionTests
+classes (if they are relevant for the extension interface for all dtypes), or
+be added to the array-specific tests in `pandas/tests/arrays/`.
+
+Note: we do not bother with base.BaseIndexTests because NumpyExtensionArray
+will never be held in an Index.
+"""
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.cast import can_hold_element
+from pandas.core.dtypes.dtypes import NumpyEADtype
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.api.types import is_object_dtype
+from pandas.core.arrays.numpy_ import NumpyExtensionArray
+from pandas.core.internals import blocks
+from pandas.tests.extension import base
+
+
+def _can_hold_element_patched(obj, element) -> bool:
+ if isinstance(element, NumpyExtensionArray):
+ element = element.to_numpy()
+ return can_hold_element(obj, element)
+
+
+orig_assert_attr_equal = tm.assert_attr_equal
+
+
+def _assert_attr_equal(attr: str, left, right, obj: str = "Attributes"):
+ """
+ patch tm.assert_attr_equal so NumpyEADtype("object") is closed enough to
+ np.dtype("object")
+ """
+ if attr == "dtype":
+ lattr = getattr(left, "dtype", None)
+ rattr = getattr(right, "dtype", None)
+ if isinstance(lattr, NumpyEADtype) and not isinstance(rattr, NumpyEADtype):
+ left = left.astype(lattr.numpy_dtype)
+ elif isinstance(rattr, NumpyEADtype) and not isinstance(lattr, NumpyEADtype):
+ right = right.astype(rattr.numpy_dtype)
+
+ orig_assert_attr_equal(attr, left, right, obj)
+
+
+@pytest.fixture(params=["float", "object"])
+def dtype(request):
+ return NumpyEADtype(np.dtype(request.param))
+
+
+@pytest.fixture
+def allow_in_pandas(monkeypatch):
+ """
+ A monkeypatch to tells pandas to let us in.
+
+ By default, passing a NumpyExtensionArray to an index / series / frame
+ constructor will unbox that NumpyExtensionArray to an ndarray, and treat
+ it as a non-EA column. We don't want people using EAs without
+ reason.
+
+ The mechanism for this is a check against ABCNumpyExtensionArray
+ in each constructor.
+
+ But, for testing, we need to allow them in pandas. So we patch
+ the _typ of NumpyExtensionArray, so that we evade the ABCNumpyExtensionArray
+ check.
+ """
+ with monkeypatch.context() as m:
+ m.setattr(NumpyExtensionArray, "_typ", "extension")
+ m.setattr(blocks, "can_hold_element", _can_hold_element_patched)
+ m.setattr(tm.asserters, "assert_attr_equal", _assert_attr_equal)
+ yield
+
+
+@pytest.fixture
+def data(allow_in_pandas, dtype):
+ if dtype.numpy_dtype == "object":
+ return pd.Series([(i,) for i in range(100)]).array
+ return NumpyExtensionArray(np.arange(1, 101, dtype=dtype._dtype))
+
+
+@pytest.fixture
+def data_missing(allow_in_pandas, dtype):
+ if dtype.numpy_dtype == "object":
+ return NumpyExtensionArray(np.array([np.nan, (1,)], dtype=object))
+ return NumpyExtensionArray(np.array([np.nan, 1.0]))
+
+
+@pytest.fixture
+def na_cmp():
+ def cmp(a, b):
+ return np.isnan(a) and np.isnan(b)
+
+ return cmp
+
+
+@pytest.fixture
+def data_for_sorting(allow_in_pandas, dtype):
+ """Length-3 array with a known sort order.
+
+ This should be three items [B, C, A] with
+ A < B < C
+ """
+ if dtype.numpy_dtype == "object":
+ # Use an empty tuple for first element, then remove,
+ # to disable np.array's shape inference.
+ return NumpyExtensionArray(np.array([(), (2,), (3,), (1,)], dtype=object)[1:])
+ return NumpyExtensionArray(np.array([1, 2, 0]))
+
+
+@pytest.fixture
+def data_missing_for_sorting(allow_in_pandas, dtype):
+ """Length-3 array with a known sort order.
+
+ This should be three items [B, NA, A] with
+ A < B and NA missing.
+ """
+ if dtype.numpy_dtype == "object":
+ return NumpyExtensionArray(np.array([(1,), np.nan, (0,)], dtype=object))
+ return NumpyExtensionArray(np.array([1, np.nan, 0]))
+
+
+@pytest.fixture
+def data_for_grouping(allow_in_pandas, dtype):
+ """Data for factorization, grouping, and unique tests.
+
+ Expected to be like [B, B, NA, NA, A, A, B, C]
+
+ Where A < B < C and NA is missing
+ """
+ if dtype.numpy_dtype == "object":
+ a, b, c = (1,), (2,), (3,)
+ else:
+ a, b, c = np.arange(3)
+ return NumpyExtensionArray(
+ np.array([b, b, np.nan, np.nan, a, a, b, c], dtype=dtype.numpy_dtype)
+ )
+
+
+@pytest.fixture
+def data_for_twos(dtype):
+ if dtype.kind == "O":
+ pytest.skip("Not a numeric dtype")
+ arr = np.ones(100) * 2
+ return NumpyExtensionArray._from_sequence(arr, dtype=dtype)
+
+
+@pytest.fixture
+def skip_numpy_object(dtype, request):
+ """
+ Tests for NumpyExtensionArray with nested data. Users typically won't create
+ these objects via `pd.array`, but they can show up through `.array`
+ on a Series with nested data. Many of the base tests fail, as they aren't
+ appropriate for nested data.
+
+ This fixture allows these tests to be skipped when used as a usefixtures
+ marker to either an individual test or a test class.
+ """
+ if dtype == "object":
+ mark = pytest.mark.xfail(reason="Fails for object dtype")
+ request.node.add_marker(mark)
+
+
+skip_nested = pytest.mark.usefixtures("skip_numpy_object")
+
+
+class BaseNumPyTests:
+ pass
+
+
+class TestCasting(BaseNumPyTests, base.BaseCastingTests):
+ pass
+
+
+class TestConstructors(BaseNumPyTests, base.BaseConstructorsTests):
+ @pytest.mark.skip(reason="We don't register our dtype")
+ # We don't want to register. This test should probably be split in two.
+ def test_from_dtype(self, data):
+ pass
+
+ @skip_nested
+ def test_series_constructor_scalar_with_index(self, data, dtype):
+ # ValueError: Length of passed values is 1, index implies 3.
+ super().test_series_constructor_scalar_with_index(data, dtype)
+
+
+class TestDtype(BaseNumPyTests, base.BaseDtypeTests):
+ def test_check_dtype(self, data, request):
+ if data.dtype.numpy_dtype == "object":
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"NumpyExtensionArray expectedly clashes with a "
+ f"NumPy name: {data.dtype.numpy_dtype}"
+ )
+ )
+ super().test_check_dtype(data)
+
+ def test_is_not_object_type(self, dtype, request):
+ if dtype.numpy_dtype == "object":
+ # Different from BaseDtypeTests.test_is_not_object_type
+ # because NumpyEADtype(object) is an object type
+ assert is_object_dtype(dtype)
+ else:
+ super().test_is_not_object_type(dtype)
+
+
+class TestGetitem(BaseNumPyTests, base.BaseGetitemTests):
+ @skip_nested
+ def test_getitem_scalar(self, data):
+ # AssertionError
+ super().test_getitem_scalar(data)
+
+
+class TestGroupby(BaseNumPyTests, base.BaseGroupbyTests):
+ pass
+
+
+class TestInterface(BaseNumPyTests, base.BaseInterfaceTests):
+ @skip_nested
+ def test_array_interface(self, data):
+ # NumPy array shape inference
+ super().test_array_interface(data)
+
+
+class TestMethods(BaseNumPyTests, base.BaseMethodsTests):
+ @skip_nested
+ def test_shift_fill_value(self, data):
+ # np.array shape inference. Shift implementation fails.
+ super().test_shift_fill_value(data)
+
+ @skip_nested
+ def test_fillna_copy_frame(self, data_missing):
+ # The "scalar" for this array isn't a scalar.
+ super().test_fillna_copy_frame(data_missing)
+
+ @skip_nested
+ def test_fillna_copy_series(self, data_missing):
+ # The "scalar" for this array isn't a scalar.
+ super().test_fillna_copy_series(data_missing)
+
+ @skip_nested
+ def test_searchsorted(self, data_for_sorting, as_series):
+ # Test setup fails.
+ super().test_searchsorted(data_for_sorting, as_series)
+
+ @pytest.mark.xfail(reason="NumpyExtensionArray.diff may fail on dtype")
+ def test_diff(self, data, periods):
+ return super().test_diff(data, periods)
+
+ def test_insert(self, data, request):
+ if data.dtype.numpy_dtype == object:
+ mark = pytest.mark.xfail(reason="Dimension mismatch in np.concatenate")
+ request.node.add_marker(mark)
+
+ super().test_insert(data)
+
+ @skip_nested
+ def test_insert_invalid(self, data, invalid_scalar):
+ # NumpyExtensionArray[object] can hold anything, so skip
+ super().test_insert_invalid(data, invalid_scalar)
+
+
+class TestArithmetics(BaseNumPyTests, base.BaseArithmeticOpsTests):
+ divmod_exc = None
+ series_scalar_exc = None
+ frame_scalar_exc = None
+ series_array_exc = None
+
+ @skip_nested
+ def test_divmod(self, data):
+ super().test_divmod(data)
+
+ @skip_nested
+ def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
+ super().test_arith_series_with_scalar(data, all_arithmetic_operators)
+
+ def test_arith_series_with_array(self, data, all_arithmetic_operators, request):
+ opname = all_arithmetic_operators
+ if data.dtype.numpy_dtype == object and opname not in ["__add__", "__radd__"]:
+ mark = pytest.mark.xfail(reason="Fails for object dtype")
+ request.node.add_marker(mark)
+ super().test_arith_series_with_array(data, all_arithmetic_operators)
+
+ @skip_nested
+ def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
+ super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
+
+
+class TestPrinting(BaseNumPyTests, base.BasePrintingTests):
+ pass
+
+
+class TestReduce(BaseNumPyTests, base.BaseReduceTests):
+ def _supports_reduction(self, obj, op_name: str) -> bool:
+ if tm.get_dtype(obj).kind == "O":
+ return op_name in ["sum", "min", "max", "any", "all"]
+ return True
+
+ def check_reduce(self, s, op_name, skipna):
+ res_op = getattr(s, op_name)
+ # avoid coercing int -> float. Just cast to the actual numpy type.
+ exp_op = getattr(s.astype(s.dtype._dtype), op_name)
+ if op_name == "count":
+ result = res_op()
+ expected = exp_op()
+ else:
+ result = res_op(skipna=skipna)
+ expected = exp_op(skipna=skipna)
+ tm.assert_almost_equal(result, expected)
+
+ @pytest.mark.skip("tests not written yet")
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_reduce_frame(self, data, all_numeric_reductions, skipna):
+ pass
+
+
+class TestMissing(BaseNumPyTests, base.BaseMissingTests):
+ @skip_nested
+ def test_fillna_series(self, data_missing):
+ # Non-scalar "scalar" values.
+ super().test_fillna_series(data_missing)
+
+ @skip_nested
+ def test_fillna_frame(self, data_missing):
+ # Non-scalar "scalar" values.
+ super().test_fillna_frame(data_missing)
+
+
+class TestReshaping(BaseNumPyTests, base.BaseReshapingTests):
+ pass
+
+
+class TestSetitem(BaseNumPyTests, base.BaseSetitemTests):
+ @skip_nested
+ def test_setitem_invalid(self, data, invalid_scalar):
+ # object dtype can hold anything, so doesn't raise
+ super().test_setitem_invalid(data, invalid_scalar)
+
+ @skip_nested
+ def test_setitem_sequence_broadcasts(self, data, box_in_series):
+ # ValueError: cannot set using a list-like indexer with a different
+ # length than the value
+ super().test_setitem_sequence_broadcasts(data, box_in_series)
+
+ @skip_nested
+ @pytest.mark.parametrize("setter", ["loc", None])
+ def test_setitem_mask_broadcast(self, data, setter):
+ # ValueError: cannot set using a list-like indexer with a different
+ # length than the value
+ super().test_setitem_mask_broadcast(data, setter)
+
+ @skip_nested
+ def test_setitem_scalar_key_sequence_raise(self, data):
+ # Failed: DID NOT RAISE
+ super().test_setitem_scalar_key_sequence_raise(data)
+
+ # TODO: there is some issue with NumpyExtensionArray, therefore,
+ # skip the setitem test for now, and fix it later (GH 31446)
+
+ @skip_nested
+ @pytest.mark.parametrize(
+ "mask",
+ [
+ np.array([True, True, True, False, False]),
+ pd.array([True, True, True, False, False], dtype="boolean"),
+ ],
+ ids=["numpy-array", "boolean-array"],
+ )
+ def test_setitem_mask(self, data, mask, box_in_series):
+ super().test_setitem_mask(data, mask, box_in_series)
+
+ @skip_nested
+ @pytest.mark.parametrize(
+ "idx",
+ [[0, 1, 2], pd.array([0, 1, 2], dtype="Int64"), np.array([0, 1, 2])],
+ ids=["list", "integer-array", "numpy-array"],
+ )
+ def test_setitem_integer_array(self, data, idx, box_in_series):
+ super().test_setitem_integer_array(data, idx, box_in_series)
+
+ @pytest.mark.parametrize(
+ "idx, box_in_series",
+ [
+ ([0, 1, 2, pd.NA], False),
+ pytest.param([0, 1, 2, pd.NA], True, marks=pytest.mark.xfail),
+ (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
+ (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
+ ],
+ ids=["list-False", "list-True", "integer-array-False", "integer-array-True"],
+ )
+ def test_setitem_integer_with_missing_raises(self, data, idx, box_in_series):
+ super().test_setitem_integer_with_missing_raises(data, idx, box_in_series)
+
+ @skip_nested
+ def test_setitem_slice(self, data, box_in_series):
+ super().test_setitem_slice(data, box_in_series)
+
+ @skip_nested
+ def test_setitem_loc_iloc_slice(self, data):
+ super().test_setitem_loc_iloc_slice(data)
+
+ def test_setitem_with_expansion_dataframe_column(self, data, full_indexer):
+ # https://github.com/pandas-dev/pandas/issues/32395
+ df = expected = pd.DataFrame({"data": pd.Series(data)})
+ result = pd.DataFrame(index=df.index)
+
+ # because result has object dtype, the attempt to do setting inplace
+ # is successful, and object dtype is retained
+ key = full_indexer(df)
+ result.loc[key, "data"] = df["data"]
+
+ # base class method has expected = df; NumpyExtensionArray behaves oddly because
+ # we patch _typ for these tests.
+ if data.dtype.numpy_dtype != object:
+ if not isinstance(key, slice) or key != slice(None):
+ expected = pd.DataFrame({"data": data.to_numpy()})
+ tm.assert_frame_equal(result, expected)
+
+
+@skip_nested
+class TestParsing(BaseNumPyTests, base.BaseParsingTests):
+ pass
+
+
+class Test2DCompat(BaseNumPyTests, base.NDArrayBacked2DTests):
+ pass
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_period.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_period.py
new file mode 100644
index 0000000000000000000000000000000000000000..63297c20daa97f1122eb696f75e5e12027d8dcbe
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_period.py
@@ -0,0 +1,143 @@
+"""
+This file contains a minimal set of tests for compliance with the extension
+array interface test suite, and should contain no other tests.
+The test suite for the full functionality of the array is located in
+`pandas/tests/arrays/`.
+
+The tests in this file are inherited from the BaseExtensionTests, and only
+minimal tweaks should be applied to get the tests passing (by overwriting a
+parent method).
+
+Additional tests should either be added to one of the BaseExtensionTests
+classes (if they are relevant for the extension interface for all dtypes), or
+be added to the array-specific tests in `pandas/tests/arrays/`.
+
+"""
+import numpy as np
+import pytest
+
+from pandas._libs import iNaT
+from pandas.compat import is_platform_windows
+from pandas.compat.numpy import np_version_gte1p24
+
+from pandas.core.dtypes.dtypes import PeriodDtype
+
+import pandas._testing as tm
+from pandas.core.arrays import PeriodArray
+from pandas.tests.extension import base
+
+
+@pytest.fixture(params=["D", "2D"])
+def dtype(request):
+ return PeriodDtype(freq=request.param)
+
+
+@pytest.fixture
+def data(dtype):
+ return PeriodArray(np.arange(1970, 2070), dtype=dtype)
+
+
+@pytest.fixture
+def data_for_sorting(dtype):
+ return PeriodArray([2018, 2019, 2017], dtype=dtype)
+
+
+@pytest.fixture
+def data_missing(dtype):
+ return PeriodArray([iNaT, 2017], dtype=dtype)
+
+
+@pytest.fixture
+def data_missing_for_sorting(dtype):
+ return PeriodArray([2018, iNaT, 2017], dtype=dtype)
+
+
+@pytest.fixture
+def data_for_grouping(dtype):
+ B = 2018
+ NA = iNaT
+ A = 2017
+ C = 2019
+ return PeriodArray([B, B, NA, NA, A, A, B, C], dtype=dtype)
+
+
+class BasePeriodTests:
+ pass
+
+
+class TestPeriodDtype(BasePeriodTests, base.BaseDtypeTests):
+ pass
+
+
+class TestConstructors(BasePeriodTests, base.BaseConstructorsTests):
+ pass
+
+
+class TestGetitem(BasePeriodTests, base.BaseGetitemTests):
+ pass
+
+
+class TestIndex(base.BaseIndexTests):
+ pass
+
+
+class TestMethods(BasePeriodTests, base.BaseMethodsTests):
+ @pytest.mark.parametrize("periods", [1, -2])
+ def test_diff(self, data, periods):
+ if is_platform_windows() and np_version_gte1p24:
+ with tm.assert_produces_warning(RuntimeWarning, check_stacklevel=False):
+ super().test_diff(data, periods)
+ else:
+ super().test_diff(data, periods)
+
+ @pytest.mark.parametrize("na_action", [None, "ignore"])
+ def test_map(self, data, na_action):
+ result = data.map(lambda x: x, na_action=na_action)
+ tm.assert_extension_array_equal(result, data)
+
+
+class TestInterface(BasePeriodTests, base.BaseInterfaceTests):
+ pass
+
+
+class TestArithmeticOps(BasePeriodTests, base.BaseArithmeticOpsTests):
+ def _get_expected_exception(self, op_name, obj, other):
+ if op_name in ("__sub__", "__rsub__"):
+ return None
+ return super()._get_expected_exception(op_name, obj, other)
+
+
+class TestCasting(BasePeriodTests, base.BaseCastingTests):
+ pass
+
+
+class TestComparisonOps(BasePeriodTests, base.BaseComparisonOpsTests):
+ pass
+
+
+class TestMissing(BasePeriodTests, base.BaseMissingTests):
+ pass
+
+
+class TestReshaping(BasePeriodTests, base.BaseReshapingTests):
+ pass
+
+
+class TestSetitem(BasePeriodTests, base.BaseSetitemTests):
+ pass
+
+
+class TestGroupby(BasePeriodTests, base.BaseGroupbyTests):
+ pass
+
+
+class TestPrinting(BasePeriodTests, base.BasePrintingTests):
+ pass
+
+
+class TestParsing(BasePeriodTests, base.BaseParsingTests):
+ pass
+
+
+class Test2DCompat(BasePeriodTests, base.NDArrayBacked2DTests):
+ pass
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_sparse.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..01448a2f83f7565e9a70a591cf72a5821ea133d5
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_sparse.py
@@ -0,0 +1,450 @@
+"""
+This file contains a minimal set of tests for compliance with the extension
+array interface test suite, and should contain no other tests.
+The test suite for the full functionality of the array is located in
+`pandas/tests/arrays/`.
+
+The tests in this file are inherited from the BaseExtensionTests, and only
+minimal tweaks should be applied to get the tests passing (by overwriting a
+parent method).
+
+Additional tests should either be added to one of the BaseExtensionTests
+classes (if they are relevant for the extension interface for all dtypes), or
+be added to the array-specific tests in `pandas/tests/arrays/`.
+
+"""
+
+import numpy as np
+import pytest
+
+from pandas.errors import PerformanceWarning
+
+import pandas as pd
+from pandas import SparseDtype
+import pandas._testing as tm
+from pandas.arrays import SparseArray
+from pandas.tests.extension import base
+
+
+def make_data(fill_value):
+ rng = np.random.default_rng(2)
+ if np.isnan(fill_value):
+ data = rng.uniform(size=100)
+ else:
+ data = rng.integers(1, 100, size=100, dtype=int)
+ if data[0] == data[1]:
+ data[0] += 1
+
+ data[2::3] = fill_value
+ return data
+
+
+@pytest.fixture
+def dtype():
+ return SparseDtype()
+
+
+@pytest.fixture(params=[0, np.nan])
+def data(request):
+ """Length-100 PeriodArray for semantics test."""
+ res = SparseArray(make_data(request.param), fill_value=request.param)
+ return res
+
+
+@pytest.fixture
+def data_for_twos():
+ return SparseArray(np.ones(100) * 2)
+
+
+@pytest.fixture(params=[0, np.nan])
+def data_missing(request):
+ """Length 2 array with [NA, Valid]"""
+ return SparseArray([np.nan, 1], fill_value=request.param)
+
+
+@pytest.fixture(params=[0, np.nan])
+def data_repeated(request):
+ """Return different versions of data for count times"""
+
+ def gen(count):
+ for _ in range(count):
+ yield SparseArray(make_data(request.param), fill_value=request.param)
+
+ yield gen
+
+
+@pytest.fixture(params=[0, np.nan])
+def data_for_sorting(request):
+ return SparseArray([2, 3, 1], fill_value=request.param)
+
+
+@pytest.fixture(params=[0, np.nan])
+def data_missing_for_sorting(request):
+ return SparseArray([2, np.nan, 1], fill_value=request.param)
+
+
+@pytest.fixture
+def na_cmp():
+ return lambda left, right: pd.isna(left) and pd.isna(right)
+
+
+@pytest.fixture(params=[0, np.nan])
+def data_for_grouping(request):
+ return SparseArray([1, 1, np.nan, np.nan, 2, 2, 1, 3], fill_value=request.param)
+
+
+@pytest.fixture(params=[0, np.nan])
+def data_for_compare(request):
+ return SparseArray([0, 0, np.nan, -2, -1, 4, 2, 3, 0, 0], fill_value=request.param)
+
+
+class BaseSparseTests:
+ def _check_unsupported(self, data):
+ if data.dtype == SparseDtype(int, 0):
+ pytest.skip("Can't store nan in int array.")
+
+
+class TestDtype(BaseSparseTests, base.BaseDtypeTests):
+ def test_array_type_with_arg(self, data, dtype):
+ assert dtype.construct_array_type() is SparseArray
+
+
+class TestInterface(BaseSparseTests, base.BaseInterfaceTests):
+ pass
+
+
+class TestConstructors(BaseSparseTests, base.BaseConstructorsTests):
+ pass
+
+
+class TestReshaping(BaseSparseTests, base.BaseReshapingTests):
+ def test_concat_mixed_dtypes(self, data):
+ # https://github.com/pandas-dev/pandas/issues/20762
+ # This should be the same, aside from concat([sparse, float])
+ df1 = pd.DataFrame({"A": data[:3]})
+ df2 = pd.DataFrame({"A": [1, 2, 3]})
+ df3 = pd.DataFrame({"A": ["a", "b", "c"]}).astype("category")
+ dfs = [df1, df2, df3]
+
+ # dataframes
+ result = pd.concat(dfs)
+ expected = pd.concat(
+ [x.apply(lambda s: np.asarray(s).astype(object)) for x in dfs]
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "columns",
+ [
+ ["A", "B"],
+ pd.MultiIndex.from_tuples(
+ [("A", "a"), ("A", "b")], names=["outer", "inner"]
+ ),
+ ],
+ )
+ @pytest.mark.parametrize("future_stack", [True, False])
+ def test_stack(self, data, columns, future_stack):
+ super().test_stack(data, columns, future_stack)
+
+ def test_concat_columns(self, data, na_value):
+ self._check_unsupported(data)
+ super().test_concat_columns(data, na_value)
+
+ def test_concat_extension_arrays_copy_false(self, data, na_value):
+ self._check_unsupported(data)
+ super().test_concat_extension_arrays_copy_false(data, na_value)
+
+ def test_align(self, data, na_value):
+ self._check_unsupported(data)
+ super().test_align(data, na_value)
+
+ def test_align_frame(self, data, na_value):
+ self._check_unsupported(data)
+ super().test_align_frame(data, na_value)
+
+ def test_align_series_frame(self, data, na_value):
+ self._check_unsupported(data)
+ super().test_align_series_frame(data, na_value)
+
+ def test_merge(self, data, na_value):
+ self._check_unsupported(data)
+ super().test_merge(data, na_value)
+
+
+class TestGetitem(BaseSparseTests, base.BaseGetitemTests):
+ def test_get(self, data):
+ ser = pd.Series(data, index=[2 * i for i in range(len(data))])
+ if np.isnan(ser.values.fill_value):
+ assert np.isnan(ser.get(4)) and np.isnan(ser.iloc[2])
+ else:
+ assert ser.get(4) == ser.iloc[2]
+ assert ser.get(2) == ser.iloc[1]
+
+ def test_reindex(self, data, na_value):
+ self._check_unsupported(data)
+ super().test_reindex(data, na_value)
+
+
+class TestSetitem(BaseSparseTests, base.BaseSetitemTests):
+ pass
+
+
+class TestIndex(base.BaseIndexTests):
+ pass
+
+
+class TestMissing(BaseSparseTests, base.BaseMissingTests):
+ def test_isna(self, data_missing):
+ sarr = SparseArray(data_missing)
+ expected_dtype = SparseDtype(bool, pd.isna(data_missing.dtype.fill_value))
+ expected = SparseArray([True, False], dtype=expected_dtype)
+ result = sarr.isna()
+ tm.assert_sp_array_equal(result, expected)
+
+ # test isna for arr without na
+ sarr = sarr.fillna(0)
+ expected_dtype = SparseDtype(bool, pd.isna(data_missing.dtype.fill_value))
+ expected = SparseArray([False, False], fill_value=False, dtype=expected_dtype)
+ tm.assert_equal(sarr.isna(), expected)
+
+ def test_fillna_limit_backfill(self, data_missing):
+ warns = (PerformanceWarning, FutureWarning)
+ with tm.assert_produces_warning(warns, check_stacklevel=False):
+ super().test_fillna_limit_backfill(data_missing)
+
+ def test_fillna_no_op_returns_copy(self, data, request):
+ if np.isnan(data.fill_value):
+ request.node.add_marker(
+ pytest.mark.xfail(reason="returns array with different fill value")
+ )
+ super().test_fillna_no_op_returns_copy(data)
+
+ @pytest.mark.xfail(reason="Unsupported")
+ def test_fillna_series(self):
+ # this one looks doable.
+ super().test_fillna_series()
+
+ def test_fillna_frame(self, data_missing):
+ # Have to override to specify that fill_value will change.
+ fill_value = data_missing[1]
+
+ result = pd.DataFrame({"A": data_missing, "B": [1, 2]}).fillna(fill_value)
+
+ if pd.isna(data_missing.fill_value):
+ dtype = SparseDtype(data_missing.dtype, fill_value)
+ else:
+ dtype = data_missing.dtype
+
+ expected = pd.DataFrame(
+ {
+ "A": data_missing._from_sequence([fill_value, fill_value], dtype=dtype),
+ "B": [1, 2],
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+class TestMethods(BaseSparseTests, base.BaseMethodsTests):
+ _combine_le_expected_dtype = "Sparse[bool]"
+
+ def test_fillna_copy_frame(self, data_missing, using_copy_on_write):
+ arr = data_missing.take([1, 1])
+ df = pd.DataFrame({"A": arr}, copy=False)
+
+ filled_val = df.iloc[0, 0]
+ result = df.fillna(filled_val)
+
+ if hasattr(df._mgr, "blocks"):
+ if using_copy_on_write:
+ assert df.values.base is result.values.base
+ else:
+ assert df.values.base is not result.values.base
+ assert df.A._values.to_dense() is arr.to_dense()
+
+ def test_fillna_copy_series(self, data_missing, using_copy_on_write):
+ arr = data_missing.take([1, 1])
+ ser = pd.Series(arr, copy=False)
+
+ filled_val = ser[0]
+ result = ser.fillna(filled_val)
+
+ if using_copy_on_write:
+ assert ser._values is result._values
+
+ else:
+ assert ser._values is not result._values
+ assert ser._values.to_dense() is arr.to_dense()
+
+ @pytest.mark.xfail(reason="Not Applicable")
+ def test_fillna_length_mismatch(self, data_missing):
+ super().test_fillna_length_mismatch(data_missing)
+
+ def test_where_series(self, data, na_value):
+ assert data[0] != data[1]
+ cls = type(data)
+ a, b = data[:2]
+
+ ser = pd.Series(cls._from_sequence([a, a, b, b], dtype=data.dtype))
+
+ cond = np.array([True, True, False, False])
+ result = ser.where(cond)
+
+ new_dtype = SparseDtype("float", 0.0)
+ expected = pd.Series(
+ cls._from_sequence([a, a, na_value, na_value], dtype=new_dtype)
+ )
+ tm.assert_series_equal(result, expected)
+
+ other = cls._from_sequence([a, b, a, b], dtype=data.dtype)
+ cond = np.array([True, False, True, True])
+ result = ser.where(cond, other)
+ expected = pd.Series(cls._from_sequence([a, b, b, b], dtype=data.dtype))
+ tm.assert_series_equal(result, expected)
+
+ def test_searchsorted(self, data_for_sorting, as_series):
+ with tm.assert_produces_warning(PerformanceWarning, check_stacklevel=False):
+ super().test_searchsorted(data_for_sorting, as_series)
+
+ def test_shift_0_periods(self, data):
+ # GH#33856 shifting with periods=0 should return a copy, not same obj
+ result = data.shift(0)
+
+ data._sparse_values[0] = data._sparse_values[1]
+ assert result._sparse_values[0] != result._sparse_values[1]
+
+ @pytest.mark.parametrize("method", ["argmax", "argmin"])
+ def test_argmin_argmax_all_na(self, method, data, na_value):
+ # overriding because Sparse[int64, 0] cannot handle na_value
+ self._check_unsupported(data)
+ super().test_argmin_argmax_all_na(method, data, na_value)
+
+ @pytest.mark.parametrize("box", [pd.array, pd.Series, pd.DataFrame])
+ def test_equals(self, data, na_value, as_series, box):
+ self._check_unsupported(data)
+ super().test_equals(data, na_value, as_series, box)
+
+ @pytest.mark.parametrize(
+ "func, na_action, expected",
+ [
+ (lambda x: x, None, SparseArray([1.0, np.nan])),
+ (lambda x: x, "ignore", SparseArray([1.0, np.nan])),
+ (str, None, SparseArray(["1.0", "nan"], fill_value="nan")),
+ (str, "ignore", SparseArray(["1.0", np.nan])),
+ ],
+ )
+ def test_map(self, func, na_action, expected):
+ # GH52096
+ data = SparseArray([1, np.nan])
+ result = data.map(func, na_action=na_action)
+ tm.assert_extension_array_equal(result, expected)
+
+ @pytest.mark.parametrize("na_action", [None, "ignore"])
+ def test_map_raises(self, data, na_action):
+ # GH52096
+ msg = "fill value in the sparse values not supported"
+ with pytest.raises(ValueError, match=msg):
+ data.map(lambda x: np.nan, na_action=na_action)
+
+
+class TestCasting(BaseSparseTests, base.BaseCastingTests):
+ @pytest.mark.xfail(raises=TypeError, reason="no sparse StringDtype")
+ def test_astype_string(self, data):
+ super().test_astype_string(data)
+
+
+class TestArithmeticOps(BaseSparseTests, base.BaseArithmeticOpsTests):
+ series_scalar_exc = None
+ frame_scalar_exc = None
+ divmod_exc = None
+ series_array_exc = None
+
+ def _skip_if_different_combine(self, data):
+ if data.fill_value == 0:
+ # arith ops call on dtype.fill_value so that the sparsity
+ # is maintained. Combine can't be called on a dtype in
+ # general, so we can't make the expected. This is tested elsewhere
+ pytest.skip("Incorrected expected from Series.combine and tested elsewhere")
+
+ def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
+ self._skip_if_different_combine(data)
+ super().test_arith_series_with_scalar(data, all_arithmetic_operators)
+
+ def test_arith_series_with_array(self, data, all_arithmetic_operators):
+ self._skip_if_different_combine(data)
+ super().test_arith_series_with_array(data, all_arithmetic_operators)
+
+ def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request):
+ if data.dtype.fill_value != 0:
+ pass
+ elif all_arithmetic_operators.strip("_") not in [
+ "mul",
+ "rmul",
+ "floordiv",
+ "rfloordiv",
+ "pow",
+ "mod",
+ "rmod",
+ ]:
+ mark = pytest.mark.xfail(reason="result dtype.fill_value mismatch")
+ request.node.add_marker(mark)
+ super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
+
+
+class TestComparisonOps(BaseSparseTests):
+ def _compare_other(self, data_for_compare: SparseArray, comparison_op, other):
+ op = comparison_op
+
+ result = op(data_for_compare, other)
+ assert isinstance(result, SparseArray)
+ assert result.dtype.subtype == np.bool_
+
+ if isinstance(other, SparseArray):
+ fill_value = op(data_for_compare.fill_value, other.fill_value)
+ else:
+ fill_value = np.all(
+ op(np.asarray(data_for_compare.fill_value), np.asarray(other))
+ )
+
+ expected = SparseArray(
+ op(data_for_compare.to_dense(), np.asarray(other)),
+ fill_value=fill_value,
+ dtype=np.bool_,
+ )
+ tm.assert_sp_array_equal(result, expected)
+
+ def test_scalar(self, data_for_compare: SparseArray, comparison_op):
+ self._compare_other(data_for_compare, comparison_op, 0)
+ self._compare_other(data_for_compare, comparison_op, 1)
+ self._compare_other(data_for_compare, comparison_op, -1)
+ self._compare_other(data_for_compare, comparison_op, np.nan)
+
+ @pytest.mark.xfail(reason="Wrong indices")
+ def test_array(self, data_for_compare: SparseArray, comparison_op):
+ arr = np.linspace(-4, 5, 10)
+ self._compare_other(data_for_compare, comparison_op, arr)
+
+ @pytest.mark.xfail(reason="Wrong indices")
+ def test_sparse_array(self, data_for_compare: SparseArray, comparison_op):
+ arr = data_for_compare + 1
+ self._compare_other(data_for_compare, comparison_op, arr)
+ arr = data_for_compare * 2
+ self._compare_other(data_for_compare, comparison_op, arr)
+
+
+class TestPrinting(BaseSparseTests, base.BasePrintingTests):
+ @pytest.mark.xfail(reason="Different repr")
+ def test_array_repr(self, data, size):
+ super().test_array_repr(data, size)
+
+
+class TestParsing(BaseSparseTests, base.BaseParsingTests):
+ @pytest.mark.parametrize("engine", ["c", "python"])
+ def test_EA_types(self, engine, data):
+ expected_msg = r".*must implement _from_sequence_of_strings.*"
+ with pytest.raises(NotImplementedError, match=expected_msg):
+ super().test_EA_types(engine, data)
+
+
+class TestNoNumericAccumulations(base.BaseAccumulateTests):
+ pass
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_string.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_string.py
new file mode 100644
index 0000000000000000000000000000000000000000..5176289994033f52c095a9894e679411c2a96fdb
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/extension/test_string.py
@@ -0,0 +1,239 @@
+"""
+This file contains a minimal set of tests for compliance with the extension
+array interface test suite, and should contain no other tests.
+The test suite for the full functionality of the array is located in
+`pandas/tests/arrays/`.
+
+The tests in this file are inherited from the BaseExtensionTests, and only
+minimal tweaks should be applied to get the tests passing (by overwriting a
+parent method).
+
+Additional tests should either be added to one of the BaseExtensionTests
+classes (if they are relevant for the extension interface for all dtypes), or
+be added to the array-specific tests in `pandas/tests/arrays/`.
+
+"""
+import string
+
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.api.types import is_string_dtype
+from pandas.core.arrays import ArrowStringArray
+from pandas.core.arrays.string_ import StringDtype
+from pandas.tests.extension import base
+
+
+def split_array(arr):
+ if arr.dtype.storage != "pyarrow":
+ pytest.skip("only applicable for pyarrow chunked array n/a")
+
+ def _split_array(arr):
+ import pyarrow as pa
+
+ arrow_array = arr._pa_array
+ split = len(arrow_array) // 2
+ arrow_array = pa.chunked_array(
+ [*arrow_array[:split].chunks, *arrow_array[split:].chunks]
+ )
+ assert arrow_array.num_chunks == 2
+ return type(arr)(arrow_array)
+
+ return _split_array(arr)
+
+
+@pytest.fixture(params=[True, False])
+def chunked(request):
+ return request.param
+
+
+@pytest.fixture
+def dtype(string_storage):
+ return StringDtype(storage=string_storage)
+
+
+@pytest.fixture
+def data(dtype, chunked):
+ strings = np.random.default_rng(2).choice(list(string.ascii_letters), size=100)
+ while strings[0] == strings[1]:
+ strings = np.random.default_rng(2).choice(list(string.ascii_letters), size=100)
+
+ arr = dtype.construct_array_type()._from_sequence(strings)
+ return split_array(arr) if chunked else arr
+
+
+@pytest.fixture
+def data_missing(dtype, chunked):
+ """Length 2 array with [NA, Valid]"""
+ arr = dtype.construct_array_type()._from_sequence([pd.NA, "A"])
+ return split_array(arr) if chunked else arr
+
+
+@pytest.fixture
+def data_for_sorting(dtype, chunked):
+ arr = dtype.construct_array_type()._from_sequence(["B", "C", "A"])
+ return split_array(arr) if chunked else arr
+
+
+@pytest.fixture
+def data_missing_for_sorting(dtype, chunked):
+ arr = dtype.construct_array_type()._from_sequence(["B", pd.NA, "A"])
+ return split_array(arr) if chunked else arr
+
+
+@pytest.fixture
+def data_for_grouping(dtype, chunked):
+ arr = dtype.construct_array_type()._from_sequence(
+ ["B", "B", pd.NA, pd.NA, "A", "A", "B", "C"]
+ )
+ return split_array(arr) if chunked else arr
+
+
+class TestDtype(base.BaseDtypeTests):
+ def test_eq_with_str(self, dtype):
+ assert dtype == f"string[{dtype.storage}]"
+ super().test_eq_with_str(dtype)
+
+ def test_is_not_string_type(self, dtype):
+ # Different from BaseDtypeTests.test_is_not_string_type
+ # because StringDtype is a string type
+ assert is_string_dtype(dtype)
+
+
+class TestInterface(base.BaseInterfaceTests):
+ def test_view(self, data, request, arrow_string_storage):
+ if data.dtype.storage in arrow_string_storage:
+ pytest.skip(reason="2D support not implemented for ArrowStringArray")
+ super().test_view(data)
+
+
+class TestConstructors(base.BaseConstructorsTests):
+ def test_from_dtype(self, data):
+ # base test uses string representation of dtype
+ pass
+
+
+class TestReshaping(base.BaseReshapingTests):
+ def test_transpose(self, data, request, arrow_string_storage):
+ if data.dtype.storage in arrow_string_storage:
+ pytest.skip(reason="2D support not implemented for ArrowStringArray")
+ super().test_transpose(data)
+
+
+class TestGetitem(base.BaseGetitemTests):
+ pass
+
+
+class TestSetitem(base.BaseSetitemTests):
+ def test_setitem_preserves_views(self, data, request, arrow_string_storage):
+ if data.dtype.storage in arrow_string_storage:
+ pytest.skip(reason="2D support not implemented for ArrowStringArray")
+ super().test_setitem_preserves_views(data)
+
+
+class TestIndex(base.BaseIndexTests):
+ pass
+
+
+class TestMissing(base.BaseMissingTests):
+ def test_dropna_array(self, data_missing):
+ result = data_missing.dropna()
+ expected = data_missing[[1]]
+ tm.assert_extension_array_equal(result, expected)
+
+ def test_fillna_no_op_returns_copy(self, data):
+ data = data[~data.isna()]
+
+ valid = data[0]
+ result = data.fillna(valid)
+ assert result is not data
+ tm.assert_extension_array_equal(result, data)
+
+ result = data.fillna(method="backfill")
+ assert result is not data
+ tm.assert_extension_array_equal(result, data)
+
+
+class TestReduce(base.BaseReduceTests):
+ def _supports_reduction(self, ser: pd.Series, op_name: str) -> bool:
+ return (
+ ser.dtype.storage == "pyarrow_numpy" # type: ignore[union-attr]
+ and op_name in ("any", "all")
+ )
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna):
+ op_name = all_numeric_reductions
+
+ if op_name in ["min", "max"]:
+ return None
+
+ ser = pd.Series(data)
+ with pytest.raises(TypeError):
+ getattr(ser, op_name)(skipna=skipna)
+
+
+class TestMethods(base.BaseMethodsTests):
+ pass
+
+
+class TestCasting(base.BaseCastingTests):
+ pass
+
+
+class TestComparisonOps(base.BaseComparisonOpsTests):
+ def _cast_pointwise_result(self, op_name: str, obj, other, pointwise_result):
+ dtype = tm.get_dtype(obj)
+ # error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no
+ # attribute "storage"
+ if dtype.storage == "pyarrow": # type: ignore[union-attr]
+ cast_to = "boolean[pyarrow]"
+ elif dtype.storage == "pyarrow_numpy": # type: ignore[union-attr]
+ cast_to = np.bool_ # type: ignore[assignment]
+ else:
+ cast_to = "boolean"
+ return pointwise_result.astype(cast_to)
+
+ def test_compare_scalar(self, data, comparison_op):
+ ser = pd.Series(data)
+ self._compare_other(ser, data, comparison_op, "abc")
+
+
+class TestParsing(base.BaseParsingTests):
+ pass
+
+
+class TestPrinting(base.BasePrintingTests):
+ pass
+
+
+class TestGroupBy(base.BaseGroupbyTests):
+ @pytest.mark.filterwarnings("ignore:Falling back:pandas.errors.PerformanceWarning")
+ def test_groupby_extension_apply(self, data_for_grouping, groupby_apply_op):
+ super().test_groupby_extension_apply(data_for_grouping, groupby_apply_op)
+
+
+class Test2DCompat(base.Dim2CompatTests):
+ @pytest.fixture(autouse=True)
+ def arrow_not_supported(self, data, request):
+ if isinstance(data, ArrowStringArray):
+ pytest.skip(reason="2D support not implemented for ArrowStringArray")
+
+
+def test_searchsorted_with_na_raises(data_for_sorting, as_series):
+ # GH50447
+ b, c, a = data_for_sorting
+ arr = data_for_sorting.take([2, 0, 1]) # to get [a, b, c]
+ arr[-1] = pd.NA
+
+ if as_series:
+ arr = pd.Series(arr)
+
+ msg = (
+ "searchsorted requires array to be sorted, "
+ "which is impossible with NAs present."
+ )
+ with pytest.raises(ValueError, match=msg):
+ arr.searchsorted(b)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc41d7907a240f0dd9dc19e0ae1296bee86be421
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/common.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from pandas import (
+ DataFrame,
+ concat,
+)
+
+if TYPE_CHECKING:
+ from pandas._typing import AxisInt
+
+
+def _check_mixed_float(df, dtype=None):
+ # float16 are most likely to be upcasted to float32
+ dtypes = {"A": "float32", "B": "float32", "C": "float16", "D": "float64"}
+ if isinstance(dtype, str):
+ dtypes = {k: dtype for k, v in dtypes.items()}
+ elif isinstance(dtype, dict):
+ dtypes.update(dtype)
+ if dtypes.get("A"):
+ assert df.dtypes["A"] == dtypes["A"]
+ if dtypes.get("B"):
+ assert df.dtypes["B"] == dtypes["B"]
+ if dtypes.get("C"):
+ assert df.dtypes["C"] == dtypes["C"]
+ if dtypes.get("D"):
+ assert df.dtypes["D"] == dtypes["D"]
+
+
+def _check_mixed_int(df, dtype=None):
+ dtypes = {"A": "int32", "B": "uint64", "C": "uint8", "D": "int64"}
+ if isinstance(dtype, str):
+ dtypes = {k: dtype for k, v in dtypes.items()}
+ elif isinstance(dtype, dict):
+ dtypes.update(dtype)
+ if dtypes.get("A"):
+ assert df.dtypes["A"] == dtypes["A"]
+ if dtypes.get("B"):
+ assert df.dtypes["B"] == dtypes["B"]
+ if dtypes.get("C"):
+ assert df.dtypes["C"] == dtypes["C"]
+ if dtypes.get("D"):
+ assert df.dtypes["D"] == dtypes["D"]
+
+
+def zip_frames(frames: list[DataFrame], axis: AxisInt = 1) -> DataFrame:
+ """
+ take a list of frames, zip them together under the
+ assumption that these all have the first frames' index/columns.
+
+ Returns
+ -------
+ new_frame : DataFrame
+ """
+ if axis == 1:
+ columns = frames[0].columns
+ zipped = [f.loc[:, c] for c in columns for f in frames]
+ return concat(zipped, axis=1)
+ else:
+ index = frames[0].index
+ zipped = [f.loc[i, :] for i in index for f in frames]
+ return DataFrame(zipped)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb2df0b82e5f422a305d1a7b5ce9a1ba8f3bf7a1
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/conftest.py
@@ -0,0 +1,261 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ NaT,
+ date_range,
+)
+import pandas._testing as tm
+
+
+@pytest.fixture
+def float_frame_with_na():
+ """
+ Fixture for DataFrame of floats with index of unique strings
+
+ Columns are ['A', 'B', 'C', 'D']; some entries are missing
+
+ A B C D
+ ABwBzA0ljw -1.128865 -0.897161 0.046603 0.274997
+ DJiRzmbyQF 0.728869 0.233502 0.722431 -0.890872
+ neMgPD5UBF 0.486072 -1.027393 -0.031553 1.449522
+ 0yWA4n8VeX -1.937191 -1.142531 0.805215 -0.462018
+ 3slYUbbqU1 0.153260 1.164691 1.489795 -0.545826
+ soujjZ0A08 NaN NaN NaN NaN
+ 7W6NLGsjB9 NaN NaN NaN NaN
+ ... ... ... ... ...
+ uhfeaNkCR1 -0.231210 -0.340472 0.244717 -0.901590
+ n6p7GYuBIV -0.419052 1.922721 -0.125361 -0.727717
+ ZhzAeY6p1y 1.234374 -1.425359 -0.827038 -0.633189
+ uWdPsORyUh 0.046738 -0.980445 -1.102965 0.605503
+ 3DJA6aN590 -0.091018 -1.684734 -1.100900 0.215947
+ 2GBPAzdbMk -2.883405 -1.021071 1.209877 1.633083
+ sHadBoyVHw -2.223032 -0.326384 0.258931 0.245517
+
+ [30 rows x 4 columns]
+ """
+ df = DataFrame(tm.getSeriesData())
+ # set some NAs
+ df.iloc[5:10] = np.nan
+ df.iloc[15:20, -2:] = np.nan
+ return df
+
+
+@pytest.fixture
+def bool_frame_with_na():
+ """
+ Fixture for DataFrame of booleans with index of unique strings
+
+ Columns are ['A', 'B', 'C', 'D']; some entries are missing
+
+ A B C D
+ zBZxY2IDGd False False False False
+ IhBWBMWllt False True True True
+ ctjdvZSR6R True False True True
+ AVTujptmxb False True False True
+ G9lrImrSWq False False False True
+ sFFwdIUfz2 NaN NaN NaN NaN
+ s15ptEJnRb NaN NaN NaN NaN
+ ... ... ... ... ...
+ UW41KkDyZ4 True True False False
+ l9l6XkOdqV True False False False
+ X2MeZfzDYA False True False False
+ xWkIKU7vfX False True False True
+ QOhL6VmpGU False False False True
+ 22PwkRJdat False True False False
+ kfboQ3VeIK True False True False
+
+ [30 rows x 4 columns]
+ """
+ df = DataFrame(tm.getSeriesData()) > 0
+ df = df.astype(object)
+ # set some NAs
+ df.iloc[5:10] = np.nan
+ df.iloc[15:20, -2:] = np.nan
+
+ # For `any` tests we need to have at least one True before the first NaN
+ # in each column
+ for i in range(4):
+ df.iloc[i, i] = True
+ return df
+
+
+@pytest.fixture
+def float_string_frame():
+ """
+ Fixture for DataFrame of floats and strings with index of unique strings
+
+ Columns are ['A', 'B', 'C', 'D', 'foo'].
+
+ A B C D foo
+ w3orJvq07g -1.594062 -1.084273 -1.252457 0.356460 bar
+ PeukuVdmz2 0.109855 -0.955086 -0.809485 0.409747 bar
+ ahp2KvwiM8 -1.533729 -0.142519 -0.154666 1.302623 bar
+ 3WSJ7BUCGd 2.484964 0.213829 0.034778 -2.327831 bar
+ khdAmufk0U -0.193480 -0.743518 -0.077987 0.153646 bar
+ LE2DZiFlrE -0.193566 -1.343194 -0.107321 0.959978 bar
+ HJXSJhVn7b 0.142590 1.257603 -0.659409 -0.223844 bar
+ ... ... ... ... ... ...
+ 9a1Vypttgw -1.316394 1.601354 0.173596 1.213196 bar
+ h5d1gVFbEy 0.609475 1.106738 -0.155271 0.294630 bar
+ mK9LsTQG92 1.303613 0.857040 -1.019153 0.369468 bar
+ oOLksd9gKH 0.558219 -0.134491 -0.289869 -0.951033 bar
+ 9jgoOjKyHg 0.058270 -0.496110 -0.413212 -0.852659 bar
+ jZLDHclHAO 0.096298 1.267510 0.549206 -0.005235 bar
+ lR0nxDp1C2 -2.119350 -0.794384 0.544118 0.145849 bar
+
+ [30 rows x 5 columns]
+ """
+ df = DataFrame(tm.getSeriesData())
+ df["foo"] = "bar"
+ return df
+
+
+@pytest.fixture
+def mixed_float_frame():
+ """
+ Fixture for DataFrame of different float types with index of unique strings
+
+ Columns are ['A', 'B', 'C', 'D'].
+
+ A B C D
+ GI7bbDaEZe -0.237908 -0.246225 -0.468506 0.752993
+ KGp9mFepzA -1.140809 -0.644046 -1.225586 0.801588
+ VeVYLAb1l2 -1.154013 -1.677615 0.690430 -0.003731
+ kmPME4WKhO 0.979578 0.998274 -0.776367 0.897607
+ CPyopdXTiz 0.048119 -0.257174 0.836426 0.111266
+ 0kJZQndAj0 0.274357 -0.281135 -0.344238 0.834541
+ tqdwQsaHG8 -0.979716 -0.519897 0.582031 0.144710
+ ... ... ... ... ...
+ 7FhZTWILQj -2.906357 1.261039 -0.780273 -0.537237
+ 4pUDPM4eGq -2.042512 -0.464382 -0.382080 1.132612
+ B8dUgUzwTi -1.506637 -0.364435 1.087891 0.297653
+ hErlVYjVv9 1.477453 -0.495515 -0.713867 1.438427
+ 1BKN3o7YLs 0.127535 -0.349812 -0.881836 0.489827
+ 9S4Ekn7zga 1.445518 -2.095149 0.031982 0.373204
+ xN1dNn6OV6 1.425017 -0.983995 -0.363281 -0.224502
+
+ [30 rows x 4 columns]
+ """
+ df = DataFrame(tm.getSeriesData())
+ df.A = df.A.astype("float32")
+ df.B = df.B.astype("float32")
+ df.C = df.C.astype("float16")
+ df.D = df.D.astype("float64")
+ return df
+
+
+@pytest.fixture
+def mixed_int_frame():
+ """
+ Fixture for DataFrame of different int types with index of unique strings
+
+ Columns are ['A', 'B', 'C', 'D'].
+
+ A B C D
+ mUrCZ67juP 0 1 2 2
+ rw99ACYaKS 0 1 0 0
+ 7QsEcpaaVU 0 1 1 1
+ xkrimI2pcE 0 1 0 0
+ dz01SuzoS8 0 1 255 255
+ ccQkqOHX75 -1 1 0 0
+ DN0iXaoDLd 0 1 0 0
+ ... .. .. ... ...
+ Dfb141wAaQ 1 1 254 254
+ IPD8eQOVu5 0 1 0 0
+ CcaKulsCmv 0 1 0 0
+ rIBa8gu7E5 0 1 0 0
+ RP6peZmh5o 0 1 1 1
+ NMb9pipQWQ 0 1 0 0
+ PqgbJEzjib 0 1 3 3
+
+ [30 rows x 4 columns]
+ """
+ df = DataFrame({k: v.astype(int) for k, v in tm.getSeriesData().items()})
+ df.A = df.A.astype("int32")
+ df.B = np.ones(len(df.B), dtype="uint64")
+ df.C = df.C.astype("uint8")
+ df.D = df.C.astype("int64")
+ return df
+
+
+@pytest.fixture
+def timezone_frame():
+ """
+ Fixture for DataFrame of date_range Series with different time zones
+
+ Columns are ['A', 'B', 'C']; some entries are missing
+
+ A B C
+ 0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00
+ 1 2013-01-02 NaT NaT
+ 2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00
+ """
+ df = DataFrame(
+ {
+ "A": date_range("20130101", periods=3),
+ "B": date_range("20130101", periods=3, tz="US/Eastern"),
+ "C": date_range("20130101", periods=3, tz="CET"),
+ }
+ )
+ df.iloc[1, 1] = NaT
+ df.iloc[1, 2] = NaT
+ return df
+
+
+@pytest.fixture
+def uint64_frame():
+ """
+ Fixture for DataFrame with uint64 values
+
+ Columns are ['A', 'B']
+ """
+ return DataFrame(
+ {"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]}, dtype=np.uint64
+ )
+
+
+@pytest.fixture
+def simple_frame():
+ """
+ Fixture for simple 3x3 DataFrame
+
+ Columns are ['one', 'two', 'three'], index is ['a', 'b', 'c'].
+
+ one two three
+ a 1.0 2.0 3.0
+ b 4.0 5.0 6.0
+ c 7.0 8.0 9.0
+ """
+ arr = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
+
+ return DataFrame(arr, columns=["one", "two", "three"], index=["a", "b", "c"])
+
+
+@pytest.fixture
+def frame_of_index_cols():
+ """
+ Fixture for DataFrame of columns that can be used for indexing
+
+ Columns are ['A', 'B', 'C', 'D', 'E', ('tuple', 'as', 'label')];
+ 'A' & 'B' contain duplicates (but are jointly unique), the rest are unique.
+
+ A B C D E (tuple, as, label)
+ 0 foo one a 0.608477 -0.012500 -1.664297
+ 1 foo two b -0.633460 0.249614 -0.364411
+ 2 foo three c 0.615256 2.154968 -0.834666
+ 3 bar one d 0.234246 1.085675 0.718445
+ 4 bar two e 0.533841 -0.005702 -3.533912
+ """
+ df = DataFrame(
+ {
+ "A": ["foo", "foo", "foo", "bar", "bar"],
+ "B": ["one", "two", "three", "one", "two"],
+ "C": ["a", "b", "c", "d", "e"],
+ "D": np.random.default_rng(2).standard_normal(5),
+ "E": np.random.default_rng(2).standard_normal(5),
+ ("tuple", "as", "label"): np.random.default_rng(2).standard_normal(5),
+ }
+ )
+ return df
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_alter_axes.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_alter_axes.py
new file mode 100644
index 0000000000000000000000000000000000000000..c68171ab254c7c8582a206a8e9b44b3845c47efc
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_alter_axes.py
@@ -0,0 +1,30 @@
+from datetime import datetime
+
+import pytz
+
+from pandas import DataFrame
+import pandas._testing as tm
+
+
+class TestDataFrameAlterAxes:
+ # Tests for setting index/columns attributes directly (i.e. __setattr__)
+
+ def test_set_axis_setattr_index(self):
+ # GH 6785
+ # set the index manually
+
+ df = DataFrame([{"ts": datetime(2014, 4, 1, tzinfo=pytz.utc), "foo": 1}])
+ expected = df.set_index("ts")
+ df.index = df["ts"]
+ df.pop("ts")
+ tm.assert_frame_equal(df, expected)
+
+ # Renaming
+
+ def test_assign_columns(self, float_frame):
+ float_frame["hi"] = "there"
+
+ df = float_frame.copy()
+ df.columns = ["foo", "bar", "baz", "quux", "foo2"]
+ tm.assert_series_equal(float_frame["C"], df["baz"], check_names=False)
+ tm.assert_series_equal(float_frame["hi"], df["foo2"], check_names=False)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_api.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa7aa8964a059879102df997318bd446d6eac3f8
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_api.py
@@ -0,0 +1,377 @@
+from copy import deepcopy
+import inspect
+import pydoc
+
+import numpy as np
+import pytest
+
+from pandas._config.config import option_context
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+ timedelta_range,
+)
+import pandas._testing as tm
+
+
+class TestDataFrameMisc:
+ def test_getitem_pop_assign_name(self, float_frame):
+ s = float_frame["A"]
+ assert s.name == "A"
+
+ s = float_frame.pop("A")
+ assert s.name == "A"
+
+ s = float_frame.loc[:, "B"]
+ assert s.name == "B"
+
+ s2 = s.loc[:]
+ assert s2.name == "B"
+
+ def test_get_axis(self, float_frame):
+ f = float_frame
+ assert f._get_axis_number(0) == 0
+ assert f._get_axis_number(1) == 1
+ assert f._get_axis_number("index") == 0
+ assert f._get_axis_number("rows") == 0
+ assert f._get_axis_number("columns") == 1
+
+ assert f._get_axis_name(0) == "index"
+ assert f._get_axis_name(1) == "columns"
+ assert f._get_axis_name("index") == "index"
+ assert f._get_axis_name("rows") == "index"
+ assert f._get_axis_name("columns") == "columns"
+
+ assert f._get_axis(0) is f.index
+ assert f._get_axis(1) is f.columns
+
+ with pytest.raises(ValueError, match="No axis named"):
+ f._get_axis_number(2)
+
+ with pytest.raises(ValueError, match="No axis.*foo"):
+ f._get_axis_name("foo")
+
+ with pytest.raises(ValueError, match="No axis.*None"):
+ f._get_axis_name(None)
+
+ with pytest.raises(ValueError, match="No axis named"):
+ f._get_axis_number(None)
+
+ def test_column_contains_raises(self, float_frame):
+ with pytest.raises(TypeError, match="unhashable type: 'Index'"):
+ float_frame.columns in float_frame
+
+ def test_tab_completion(self):
+ # DataFrame whose columns are identifiers shall have them in __dir__.
+ df = DataFrame([list("abcd"), list("efgh")], columns=list("ABCD"))
+ for key in list("ABCD"):
+ assert key in dir(df)
+ assert isinstance(df.__getitem__("A"), Series)
+
+ # DataFrame whose first-level columns are identifiers shall have
+ # them in __dir__.
+ df = DataFrame(
+ [list("abcd"), list("efgh")],
+ columns=pd.MultiIndex.from_tuples(list(zip("ABCD", "EFGH"))),
+ )
+ for key in list("ABCD"):
+ assert key in dir(df)
+ for key in list("EFGH"):
+ assert key not in dir(df)
+ assert isinstance(df.__getitem__("A"), DataFrame)
+
+ def test_display_max_dir_items(self):
+ # display.max_dir_items increaes the number of columns that are in __dir__.
+ columns = ["a" + str(i) for i in range(420)]
+ values = [range(420), range(420)]
+ df = DataFrame(values, columns=columns)
+
+ # The default value for display.max_dir_items is 100
+ assert "a99" in dir(df)
+ assert "a100" not in dir(df)
+
+ with option_context("display.max_dir_items", 300):
+ df = DataFrame(values, columns=columns)
+ assert "a299" in dir(df)
+ assert "a300" not in dir(df)
+
+ with option_context("display.max_dir_items", None):
+ df = DataFrame(values, columns=columns)
+ assert "a419" in dir(df)
+
+ def test_not_hashable(self):
+ empty_frame = DataFrame()
+
+ df = DataFrame([1])
+ msg = "unhashable type: 'DataFrame'"
+ with pytest.raises(TypeError, match=msg):
+ hash(df)
+ with pytest.raises(TypeError, match=msg):
+ hash(empty_frame)
+
+ def test_column_name_contains_unicode_surrogate(self):
+ # GH 25509
+ colname = "\ud83d"
+ df = DataFrame({colname: []})
+ # this should not crash
+ assert colname not in dir(df)
+ assert df.columns[0] == colname
+
+ def test_new_empty_index(self):
+ df1 = DataFrame(np.random.default_rng(2).standard_normal((0, 3)))
+ df2 = DataFrame(np.random.default_rng(2).standard_normal((0, 3)))
+ df1.index.name = "foo"
+ assert df2.index.name is None
+
+ def test_get_agg_axis(self, float_frame):
+ cols = float_frame._get_agg_axis(0)
+ assert cols is float_frame.columns
+
+ idx = float_frame._get_agg_axis(1)
+ assert idx is float_frame.index
+
+ msg = r"Axis must be 0 or 1 \(got 2\)"
+ with pytest.raises(ValueError, match=msg):
+ float_frame._get_agg_axis(2)
+
+ def test_empty(self, float_frame, float_string_frame):
+ empty_frame = DataFrame()
+ assert empty_frame.empty
+
+ assert not float_frame.empty
+ assert not float_string_frame.empty
+
+ # corner case
+ df = DataFrame({"A": [1.0, 2.0, 3.0], "B": ["a", "b", "c"]}, index=np.arange(3))
+ del df["A"]
+ assert not df.empty
+
+ def test_len(self, float_frame):
+ assert len(float_frame) == len(float_frame.index)
+
+ # single block corner case
+ arr = float_frame[["A", "B"]].values
+ expected = float_frame.reindex(columns=["A", "B"]).values
+ tm.assert_almost_equal(arr, expected)
+
+ def test_axis_aliases(self, float_frame):
+ f = float_frame
+
+ # reg name
+ expected = f.sum(axis=0)
+ result = f.sum(axis="index")
+ tm.assert_series_equal(result, expected)
+
+ expected = f.sum(axis=1)
+ result = f.sum(axis="columns")
+ tm.assert_series_equal(result, expected)
+
+ def test_class_axis(self):
+ # GH 18147
+ # no exception and no empty docstring
+ assert pydoc.getdoc(DataFrame.index)
+ assert pydoc.getdoc(DataFrame.columns)
+
+ def test_series_put_names(self, float_string_frame):
+ series = float_string_frame._series
+ for k, v in series.items():
+ assert v.name == k
+
+ def test_empty_nonzero(self):
+ df = DataFrame([1, 2, 3])
+ assert not df.empty
+ df = DataFrame(index=[1], columns=[1])
+ assert not df.empty
+ df = DataFrame(index=["a", "b"], columns=["c", "d"]).dropna()
+ assert df.empty
+ assert df.T.empty
+
+ @pytest.mark.parametrize(
+ "df",
+ [
+ DataFrame(),
+ DataFrame(index=[1]),
+ DataFrame(columns=[1]),
+ DataFrame({1: []}),
+ ],
+ )
+ def test_empty_like(self, df):
+ assert df.empty
+ assert df.T.empty
+
+ def test_with_datetimelikes(self):
+ df = DataFrame(
+ {
+ "A": date_range("20130101", periods=10),
+ "B": timedelta_range("1 day", periods=10),
+ }
+ )
+ t = df.T
+
+ result = t.dtypes.value_counts()
+ expected = Series({np.dtype("object"): 10}, name="count")
+ tm.assert_series_equal(result, expected)
+
+ def test_deepcopy(self, float_frame):
+ cp = deepcopy(float_frame)
+ series = cp["A"]
+ series[:] = 10
+ for idx, value in series.items():
+ assert float_frame["A"][idx] != value
+
+ def test_inplace_return_self(self):
+ # GH 1893
+
+ data = DataFrame(
+ {"a": ["foo", "bar", "baz", "qux"], "b": [0, 0, 1, 1], "c": [1, 2, 3, 4]}
+ )
+
+ def _check_f(base, f):
+ result = f(base)
+ assert result is None
+
+ # -----DataFrame-----
+
+ # set_index
+ f = lambda x: x.set_index("a", inplace=True)
+ _check_f(data.copy(), f)
+
+ # reset_index
+ f = lambda x: x.reset_index(inplace=True)
+ _check_f(data.set_index("a"), f)
+
+ # drop_duplicates
+ f = lambda x: x.drop_duplicates(inplace=True)
+ _check_f(data.copy(), f)
+
+ # sort
+ f = lambda x: x.sort_values("b", inplace=True)
+ _check_f(data.copy(), f)
+
+ # sort_index
+ f = lambda x: x.sort_index(inplace=True)
+ _check_f(data.copy(), f)
+
+ # fillna
+ f = lambda x: x.fillna(0, inplace=True)
+ _check_f(data.copy(), f)
+
+ # replace
+ f = lambda x: x.replace(1, 0, inplace=True)
+ _check_f(data.copy(), f)
+
+ # rename
+ f = lambda x: x.rename({1: "foo"}, inplace=True)
+ _check_f(data.copy(), f)
+
+ # -----Series-----
+ d = data.copy()["c"]
+
+ # reset_index
+ f = lambda x: x.reset_index(inplace=True, drop=True)
+ _check_f(data.set_index("a")["c"], f)
+
+ # fillna
+ f = lambda x: x.fillna(0, inplace=True)
+ _check_f(d.copy(), f)
+
+ # replace
+ f = lambda x: x.replace(1, 0, inplace=True)
+ _check_f(d.copy(), f)
+
+ # rename
+ f = lambda x: x.rename({1: "foo"}, inplace=True)
+ _check_f(d.copy(), f)
+
+ def test_tab_complete_warning(self, ip, frame_or_series):
+ # GH 16409
+ pytest.importorskip("IPython", minversion="6.0.0")
+ from IPython.core.completer import provisionalcompleter
+
+ if frame_or_series is DataFrame:
+ code = "from pandas import DataFrame; obj = DataFrame()"
+ else:
+ code = "from pandas import Series; obj = Series(dtype=object)"
+
+ ip.run_cell(code)
+ # GH 31324 newer jedi version raises Deprecation warning;
+ # appears resolved 2021-02-02
+ with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
+ with provisionalcompleter("ignore"):
+ list(ip.Completer.completions("obj.", 1))
+
+ def test_attrs(self):
+ df = DataFrame({"A": [2, 3]})
+ assert df.attrs == {}
+ df.attrs["version"] = 1
+
+ result = df.rename(columns=str)
+ assert result.attrs == {"version": 1}
+
+ @pytest.mark.parametrize("allows_duplicate_labels", [True, False, None])
+ def test_set_flags(
+ self, allows_duplicate_labels, frame_or_series, using_copy_on_write
+ ):
+ obj = DataFrame({"A": [1, 2]})
+ key = (0, 0)
+ if frame_or_series is Series:
+ obj = obj["A"]
+ key = 0
+
+ result = obj.set_flags(allows_duplicate_labels=allows_duplicate_labels)
+
+ if allows_duplicate_labels is None:
+ # We don't update when it's not provided
+ assert result.flags.allows_duplicate_labels is True
+ else:
+ assert result.flags.allows_duplicate_labels is allows_duplicate_labels
+
+ # We made a copy
+ assert obj is not result
+
+ # We didn't mutate obj
+ assert obj.flags.allows_duplicate_labels is True
+
+ # But we didn't copy data
+ if frame_or_series is Series:
+ assert np.may_share_memory(obj.values, result.values)
+ else:
+ assert np.may_share_memory(obj["A"].values, result["A"].values)
+
+ result.iloc[key] = 0
+ if using_copy_on_write:
+ assert obj.iloc[key] == 1
+ else:
+ assert obj.iloc[key] == 0
+ # set back to 1 for test below
+ result.iloc[key] = 1
+
+ # Now we do copy.
+ result = obj.set_flags(
+ copy=True, allows_duplicate_labels=allows_duplicate_labels
+ )
+ result.iloc[key] = 10
+ assert obj.iloc[key] == 1
+
+ def test_constructor_expanddim(self):
+ # GH#33628 accessing _constructor_expanddim should not raise NotImplementedError
+ # GH38782 pandas has no container higher than DataFrame (two-dim), so
+ # DataFrame._constructor_expand_dim, doesn't make sense, so is removed.
+ df = DataFrame()
+
+ msg = "'DataFrame' object has no attribute '_constructor_expanddim'"
+ with pytest.raises(AttributeError, match=msg):
+ df._constructor_expanddim(np.arange(27).reshape(3, 3, 3))
+
+ def test_inspect_getmembers(self):
+ # GH38740
+ pytest.importorskip("jinja2")
+ df = DataFrame()
+ msg = "DataFrame._data is deprecated"
+ with tm.assert_produces_warning(
+ DeprecationWarning, match=msg, check_stacklevel=False
+ ):
+ inspect.getmembers(df)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_arithmetic.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_arithmetic.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5a8feb7a89d31b8f4c20f3d21aca946547e739a
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_arithmetic.py
@@ -0,0 +1,2129 @@
+from collections import deque
+from datetime import (
+ datetime,
+ timezone,
+)
+from enum import Enum
+import functools
+import operator
+import re
+
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
+import pandas._testing as tm
+from pandas.core.computation import expressions as expr
+from pandas.core.computation.expressions import _MIN_ELEMENTS
+from pandas.tests.frame.common import (
+ _check_mixed_float,
+ _check_mixed_int,
+)
+from pandas.util.version import Version
+
+
+@pytest.fixture(autouse=True, params=[0, 1000000], ids=["numexpr", "python"])
+def switch_numexpr_min_elements(request):
+ _MIN_ELEMENTS = expr._MIN_ELEMENTS
+ expr._MIN_ELEMENTS = request.param
+ yield request.param
+ expr._MIN_ELEMENTS = _MIN_ELEMENTS
+
+
+class DummyElement:
+ def __init__(self, value, dtype) -> None:
+ self.value = value
+ self.dtype = np.dtype(dtype)
+
+ def __array__(self):
+ return np.array(self.value, dtype=self.dtype)
+
+ def __str__(self) -> str:
+ return f"DummyElement({self.value}, {self.dtype})"
+
+ def __repr__(self) -> str:
+ return str(self)
+
+ def astype(self, dtype, copy=False):
+ self.dtype = dtype
+ return self
+
+ def view(self, dtype):
+ return type(self)(self.value.view(dtype), dtype)
+
+ def any(self, axis=None):
+ return bool(self.value)
+
+
+# -------------------------------------------------------------------
+# Comparisons
+
+
+class TestFrameComparisons:
+ # Specifically _not_ flex-comparisons
+
+ def test_comparison_with_categorical_dtype(self):
+ # GH#12564
+
+ df = DataFrame({"A": ["foo", "bar", "baz"]})
+ exp = DataFrame({"A": [True, False, False]})
+
+ res = df == "foo"
+ tm.assert_frame_equal(res, exp)
+
+ # casting to categorical shouldn't affect the result
+ df["A"] = df["A"].astype("category")
+
+ res = df == "foo"
+ tm.assert_frame_equal(res, exp)
+
+ def test_frame_in_list(self):
+ # GH#12689 this should raise at the DataFrame level, not blocks
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)), columns=list("ABCD")
+ )
+ msg = "The truth value of a DataFrame is ambiguous"
+ with pytest.raises(ValueError, match=msg):
+ df in [None]
+
+ @pytest.mark.parametrize(
+ "arg, arg2",
+ [
+ [
+ {
+ "a": np.random.default_rng(2).integers(10, size=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ {
+ "a": np.random.default_rng(2).integers(10, size=10),
+ "b": np.random.default_rng(2).integers(10, size=10),
+ },
+ ],
+ [
+ {
+ "a": np.random.default_rng(2).integers(10, size=10),
+ "b": np.random.default_rng(2).integers(10, size=10),
+ },
+ {
+ "a": np.random.default_rng(2).integers(10, size=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ ],
+ [
+ {
+ "a": pd.date_range("20010101", periods=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ {
+ "a": np.random.default_rng(2).integers(10, size=10),
+ "b": np.random.default_rng(2).integers(10, size=10),
+ },
+ ],
+ [
+ {
+ "a": np.random.default_rng(2).integers(10, size=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ {
+ "a": pd.date_range("20010101", periods=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ ],
+ ],
+ )
+ def test_comparison_invalid(self, arg, arg2):
+ # GH4968
+ # invalid date/int comparisons
+ x = DataFrame(arg)
+ y = DataFrame(arg2)
+ # we expect the result to match Series comparisons for
+ # == and !=, inequalities should raise
+ result = x == y
+ expected = DataFrame(
+ {col: x[col] == y[col] for col in x.columns},
+ index=x.index,
+ columns=x.columns,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = x != y
+ expected = DataFrame(
+ {col: x[col] != y[col] for col in x.columns},
+ index=x.index,
+ columns=x.columns,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ msgs = [
+ r"Invalid comparison between dtype=datetime64\[ns\] and ndarray",
+ "invalid type promotion",
+ (
+ # npdev 1.20.0
+ r"The DTypes and "
+ r" do not have a common DType."
+ ),
+ ]
+ msg = "|".join(msgs)
+ with pytest.raises(TypeError, match=msg):
+ x >= y
+ with pytest.raises(TypeError, match=msg):
+ x > y
+ with pytest.raises(TypeError, match=msg):
+ x < y
+ with pytest.raises(TypeError, match=msg):
+ x <= y
+
+ @pytest.mark.parametrize(
+ "left, right",
+ [
+ ("gt", "lt"),
+ ("lt", "gt"),
+ ("ge", "le"),
+ ("le", "ge"),
+ ("eq", "eq"),
+ ("ne", "ne"),
+ ],
+ )
+ def test_timestamp_compare(self, left, right):
+ # make sure we can compare Timestamps on the right AND left hand side
+ # GH#4982
+ df = DataFrame(
+ {
+ "dates1": pd.date_range("20010101", periods=10),
+ "dates2": pd.date_range("20010102", periods=10),
+ "intcol": np.random.default_rng(2).integers(1000000000, size=10),
+ "floatcol": np.random.default_rng(2).standard_normal(10),
+ "stringcol": [chr(100 + i) for i in range(10)],
+ }
+ )
+ df.loc[np.random.default_rng(2).random(len(df)) > 0.5, "dates2"] = pd.NaT
+ left_f = getattr(operator, left)
+ right_f = getattr(operator, right)
+
+ # no nats
+ if left in ["eq", "ne"]:
+ expected = left_f(df, pd.Timestamp("20010109"))
+ result = right_f(pd.Timestamp("20010109"), df)
+ tm.assert_frame_equal(result, expected)
+ else:
+ msg = (
+ "'(<|>)=?' not supported between "
+ "instances of 'numpy.ndarray' and 'Timestamp'"
+ )
+ with pytest.raises(TypeError, match=msg):
+ left_f(df, pd.Timestamp("20010109"))
+ with pytest.raises(TypeError, match=msg):
+ right_f(pd.Timestamp("20010109"), df)
+ # nats
+ if left in ["eq", "ne"]:
+ expected = left_f(df, pd.Timestamp("nat"))
+ result = right_f(pd.Timestamp("nat"), df)
+ tm.assert_frame_equal(result, expected)
+ else:
+ msg = (
+ "'(<|>)=?' not supported between "
+ "instances of 'numpy.ndarray' and 'NaTType'"
+ )
+ with pytest.raises(TypeError, match=msg):
+ left_f(df, pd.Timestamp("nat"))
+ with pytest.raises(TypeError, match=msg):
+ right_f(pd.Timestamp("nat"), df)
+
+ def test_mixed_comparison(self):
+ # GH#13128, GH#22163 != datetime64 vs non-dt64 should be False,
+ # not raise TypeError
+ # (this appears to be fixed before GH#22163, not sure when)
+ df = DataFrame([["1989-08-01", 1], ["1989-08-01", 2]])
+ other = DataFrame([["a", "b"], ["c", "d"]])
+
+ result = df == other
+ assert not result.any().any()
+
+ result = df != other
+ assert result.all().all()
+
+ def test_df_boolean_comparison_error(self):
+ # GH#4576, GH#22880
+ # comparing DataFrame against list/tuple with len(obj) matching
+ # len(df.columns) is supported as of GH#22800
+ df = DataFrame(np.arange(6).reshape((3, 2)))
+
+ expected = DataFrame([[False, False], [True, False], [False, False]])
+
+ result = df == (2, 2)
+ tm.assert_frame_equal(result, expected)
+
+ result = df == [2, 2]
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_float_none_comparison(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((8, 3)),
+ index=range(8),
+ columns=["A", "B", "C"],
+ )
+
+ result = df.__eq__(None)
+ assert not result.any().any()
+
+ def test_df_string_comparison(self):
+ df = DataFrame([{"a": 1, "b": "foo"}, {"a": 2, "b": "bar"}])
+ mask_a = df.a > 1
+ tm.assert_frame_equal(df[mask_a], df.loc[1:1, :])
+ tm.assert_frame_equal(df[-mask_a], df.loc[0:0, :])
+
+ mask_b = df.b == "foo"
+ tm.assert_frame_equal(df[mask_b], df.loc[0:0, :])
+ tm.assert_frame_equal(df[-mask_b], df.loc[1:1, :])
+
+
+class TestFrameFlexComparisons:
+ # TODO: test_bool_flex_frame needs a better name
+ @pytest.mark.parametrize("op", ["eq", "ne", "gt", "lt", "ge", "le"])
+ def test_bool_flex_frame(self, op):
+ data = np.random.default_rng(2).standard_normal((5, 3))
+ other_data = np.random.default_rng(2).standard_normal((5, 3))
+ df = DataFrame(data)
+ other = DataFrame(other_data)
+ ndim_5 = np.ones(df.shape + (1, 3))
+
+ # DataFrame
+ assert df.eq(df).values.all()
+ assert not df.ne(df).values.any()
+ f = getattr(df, op)
+ o = getattr(operator, op)
+ # No NAs
+ tm.assert_frame_equal(f(other), o(df, other))
+ # Unaligned
+ part_o = other.loc[3:, 1:].copy()
+ rs = f(part_o)
+ xp = o(df, part_o.reindex(index=df.index, columns=df.columns))
+ tm.assert_frame_equal(rs, xp)
+ # ndarray
+ tm.assert_frame_equal(f(other.values), o(df, other.values))
+ # scalar
+ tm.assert_frame_equal(f(0), o(df, 0))
+ # NAs
+ msg = "Unable to coerce to Series/DataFrame"
+ tm.assert_frame_equal(f(np.nan), o(df, np.nan))
+ with pytest.raises(ValueError, match=msg):
+ f(ndim_5)
+
+ @pytest.mark.parametrize("box", [np.array, Series])
+ def test_bool_flex_series(self, box):
+ # Series
+ # list/tuple
+ data = np.random.default_rng(2).standard_normal((5, 3))
+ df = DataFrame(data)
+ idx_ser = box(np.random.default_rng(2).standard_normal(5))
+ col_ser = box(np.random.default_rng(2).standard_normal(3))
+
+ idx_eq = df.eq(idx_ser, axis=0)
+ col_eq = df.eq(col_ser)
+ idx_ne = df.ne(idx_ser, axis=0)
+ col_ne = df.ne(col_ser)
+ tm.assert_frame_equal(col_eq, df == Series(col_ser))
+ tm.assert_frame_equal(col_eq, -col_ne)
+ tm.assert_frame_equal(idx_eq, -idx_ne)
+ tm.assert_frame_equal(idx_eq, df.T.eq(idx_ser).T)
+ tm.assert_frame_equal(col_eq, df.eq(list(col_ser)))
+ tm.assert_frame_equal(idx_eq, df.eq(Series(idx_ser), axis=0))
+ tm.assert_frame_equal(idx_eq, df.eq(list(idx_ser), axis=0))
+
+ idx_gt = df.gt(idx_ser, axis=0)
+ col_gt = df.gt(col_ser)
+ idx_le = df.le(idx_ser, axis=0)
+ col_le = df.le(col_ser)
+
+ tm.assert_frame_equal(col_gt, df > Series(col_ser))
+ tm.assert_frame_equal(col_gt, -col_le)
+ tm.assert_frame_equal(idx_gt, -idx_le)
+ tm.assert_frame_equal(idx_gt, df.T.gt(idx_ser).T)
+
+ idx_ge = df.ge(idx_ser, axis=0)
+ col_ge = df.ge(col_ser)
+ idx_lt = df.lt(idx_ser, axis=0)
+ col_lt = df.lt(col_ser)
+ tm.assert_frame_equal(col_ge, df >= Series(col_ser))
+ tm.assert_frame_equal(col_ge, -col_lt)
+ tm.assert_frame_equal(idx_ge, -idx_lt)
+ tm.assert_frame_equal(idx_ge, df.T.ge(idx_ser).T)
+
+ idx_ser = Series(np.random.default_rng(2).standard_normal(5))
+ col_ser = Series(np.random.default_rng(2).standard_normal(3))
+
+ def test_bool_flex_frame_na(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ # NA
+ df.loc[0, 0] = np.nan
+ rs = df.eq(df)
+ assert not rs.loc[0, 0]
+ rs = df.ne(df)
+ assert rs.loc[0, 0]
+ rs = df.gt(df)
+ assert not rs.loc[0, 0]
+ rs = df.lt(df)
+ assert not rs.loc[0, 0]
+ rs = df.ge(df)
+ assert not rs.loc[0, 0]
+ rs = df.le(df)
+ assert not rs.loc[0, 0]
+
+ def test_bool_flex_frame_complex_dtype(self):
+ # complex
+ arr = np.array([np.nan, 1, 6, np.nan])
+ arr2 = np.array([2j, np.nan, 7, None])
+ df = DataFrame({"a": arr})
+ df2 = DataFrame({"a": arr2})
+
+ msg = "|".join(
+ [
+ "'>' not supported between instances of '.*' and 'complex'",
+ r"unorderable types: .*complex\(\)", # PY35
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ # inequalities are not well-defined for complex numbers
+ df.gt(df2)
+ with pytest.raises(TypeError, match=msg):
+ # regression test that we get the same behavior for Series
+ df["a"].gt(df2["a"])
+ with pytest.raises(TypeError, match=msg):
+ # Check that we match numpy behavior here
+ df.values > df2.values
+
+ rs = df.ne(df2)
+ assert rs.values.all()
+
+ arr3 = np.array([2j, np.nan, None])
+ df3 = DataFrame({"a": arr3})
+
+ with pytest.raises(TypeError, match=msg):
+ # inequalities are not well-defined for complex numbers
+ df3.gt(2j)
+ with pytest.raises(TypeError, match=msg):
+ # regression test that we get the same behavior for Series
+ df3["a"].gt(2j)
+ with pytest.raises(TypeError, match=msg):
+ # Check that we match numpy behavior here
+ df3.values > 2j
+
+ def test_bool_flex_frame_object_dtype(self):
+ # corner, dtype=object
+ df1 = DataFrame({"col": ["foo", np.nan, "bar"]})
+ df2 = DataFrame({"col": ["foo", datetime.now(), "bar"]})
+ result = df1.ne(df2)
+ exp = DataFrame({"col": [False, True, False]})
+ tm.assert_frame_equal(result, exp)
+
+ def test_flex_comparison_nat(self):
+ # GH 15697, GH 22163 df.eq(pd.NaT) should behave like df == pd.NaT,
+ # and _definitely_ not be NaN
+ df = DataFrame([pd.NaT])
+
+ result = df == pd.NaT
+ # result.iloc[0, 0] is a np.bool_ object
+ assert result.iloc[0, 0].item() is False
+
+ result = df.eq(pd.NaT)
+ assert result.iloc[0, 0].item() is False
+
+ result = df != pd.NaT
+ assert result.iloc[0, 0].item() is True
+
+ result = df.ne(pd.NaT)
+ assert result.iloc[0, 0].item() is True
+
+ @pytest.mark.parametrize("opname", ["eq", "ne", "gt", "lt", "ge", "le"])
+ def test_df_flex_cmp_constant_return_types(self, opname):
+ # GH 15077, non-empty DataFrame
+ df = DataFrame({"x": [1, 2, 3], "y": [1.0, 2.0, 3.0]})
+ const = 2
+
+ result = getattr(df, opname)(const).dtypes.value_counts()
+ tm.assert_series_equal(
+ result, Series([2], index=[np.dtype(bool)], name="count")
+ )
+
+ @pytest.mark.parametrize("opname", ["eq", "ne", "gt", "lt", "ge", "le"])
+ def test_df_flex_cmp_constant_return_types_empty(self, opname):
+ # GH 15077 empty DataFrame
+ df = DataFrame({"x": [1, 2, 3], "y": [1.0, 2.0, 3.0]})
+ const = 2
+
+ empty = df.iloc[:0]
+ result = getattr(empty, opname)(const).dtypes.value_counts()
+ tm.assert_series_equal(
+ result, Series([2], index=[np.dtype(bool)], name="count")
+ )
+
+ def test_df_flex_cmp_ea_dtype_with_ndarray_series(self):
+ ii = pd.IntervalIndex.from_breaks([1, 2, 3])
+ df = DataFrame({"A": ii, "B": ii})
+
+ ser = Series([0, 0])
+ res = df.eq(ser, axis=0)
+
+ expected = DataFrame({"A": [False, False], "B": [False, False]})
+ tm.assert_frame_equal(res, expected)
+
+ ser2 = Series([1, 2], index=["A", "B"])
+ res2 = df.eq(ser2, axis=1)
+ tm.assert_frame_equal(res2, expected)
+
+
+# -------------------------------------------------------------------
+# Arithmetic
+
+
+class TestFrameFlexArithmetic:
+ def test_floordiv_axis0(self):
+ # make sure we df.floordiv(ser, axis=0) matches column-wise result
+ arr = np.arange(3)
+ ser = Series(arr)
+ df = DataFrame({"A": ser, "B": ser})
+
+ result = df.floordiv(ser, axis=0)
+
+ expected = DataFrame({col: df[col] // ser for col in df.columns})
+
+ tm.assert_frame_equal(result, expected)
+
+ result2 = df.floordiv(ser.values, axis=0)
+ tm.assert_frame_equal(result2, expected)
+
+ @pytest.mark.parametrize("opname", ["floordiv", "pow"])
+ def test_floordiv_axis0_numexpr_path(self, opname, request):
+ # case that goes through numexpr and has to fall back to masked_arith_op
+ ne = pytest.importorskip("numexpr")
+ if (
+ Version(ne.__version__) >= Version("2.8.7")
+ and opname == "pow"
+ and "python" in request.node.callspec.id
+ ):
+ request.node.add_marker(
+ pytest.mark.xfail(reason="https://github.com/pydata/numexpr/issues/454")
+ )
+
+ op = getattr(operator, opname)
+
+ arr = np.arange(_MIN_ELEMENTS + 100).reshape(_MIN_ELEMENTS // 100 + 1, -1) * 100
+ df = DataFrame(arr)
+ df["C"] = 1.0
+
+ ser = df[0]
+ result = getattr(df, opname)(ser, axis=0)
+
+ expected = DataFrame({col: op(df[col], ser) for col in df.columns})
+ tm.assert_frame_equal(result, expected)
+
+ result2 = getattr(df, opname)(ser.values, axis=0)
+ tm.assert_frame_equal(result2, expected)
+
+ def test_df_add_td64_columnwise(self):
+ # GH 22534 Check that column-wise addition broadcasts correctly
+ dti = pd.date_range("2016-01-01", periods=10)
+ tdi = pd.timedelta_range("1", periods=10)
+ tser = Series(tdi)
+ df = DataFrame({0: dti, 1: tdi})
+
+ result = df.add(tser, axis=0)
+ expected = DataFrame({0: dti + tdi, 1: tdi + tdi})
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_add_flex_filled_mixed_dtypes(self):
+ # GH 19611
+ dti = pd.date_range("2016-01-01", periods=3)
+ ser = Series(["1 Day", "NaT", "2 Days"], dtype="timedelta64[ns]")
+ df = DataFrame({"A": dti, "B": ser})
+ other = DataFrame({"A": ser, "B": ser})
+ fill = pd.Timedelta(days=1).to_timedelta64()
+ result = df.add(other, fill_value=fill)
+
+ expected = DataFrame(
+ {
+ "A": Series(
+ ["2016-01-02", "2016-01-03", "2016-01-05"], dtype="datetime64[ns]"
+ ),
+ "B": ser * 2,
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_arith_flex_frame(
+ self, all_arithmetic_operators, float_frame, mixed_float_frame
+ ):
+ # one instance of parametrized fixture
+ op = all_arithmetic_operators
+
+ def f(x, y):
+ # r-versions not in operator-stdlib; get op without "r" and invert
+ if op.startswith("__r"):
+ return getattr(operator, op.replace("__r", "__"))(y, x)
+ return getattr(operator, op)(x, y)
+
+ result = getattr(float_frame, op)(2 * float_frame)
+ expected = f(float_frame, 2 * float_frame)
+ tm.assert_frame_equal(result, expected)
+
+ # vs mix float
+ result = getattr(mixed_float_frame, op)(2 * mixed_float_frame)
+ expected = f(mixed_float_frame, 2 * mixed_float_frame)
+ tm.assert_frame_equal(result, expected)
+ _check_mixed_float(result, dtype={"C": None})
+
+ @pytest.mark.parametrize("op", ["__add__", "__sub__", "__mul__"])
+ def test_arith_flex_frame_mixed(
+ self,
+ op,
+ int_frame,
+ mixed_int_frame,
+ mixed_float_frame,
+ switch_numexpr_min_elements,
+ ):
+ f = getattr(operator, op)
+
+ # vs mix int
+ result = getattr(mixed_int_frame, op)(2 + mixed_int_frame)
+ expected = f(mixed_int_frame, 2 + mixed_int_frame)
+
+ # no overflow in the uint
+ dtype = None
+ if op in ["__sub__"]:
+ dtype = {"B": "uint64", "C": None}
+ elif op in ["__add__", "__mul__"]:
+ dtype = {"C": None}
+ if expr.USE_NUMEXPR and switch_numexpr_min_elements == 0:
+ # when using numexpr, the casting rules are slightly different:
+ # in the `2 + mixed_int_frame` operation, int32 column becomes
+ # and int64 column (not preserving dtype in operation with Python
+ # scalar), and then the int32/int64 combo results in int64 result
+ dtype["A"] = (2 + mixed_int_frame)["A"].dtype
+ tm.assert_frame_equal(result, expected)
+ _check_mixed_int(result, dtype=dtype)
+
+ # vs mix float
+ result = getattr(mixed_float_frame, op)(2 * mixed_float_frame)
+ expected = f(mixed_float_frame, 2 * mixed_float_frame)
+ tm.assert_frame_equal(result, expected)
+ _check_mixed_float(result, dtype={"C": None})
+
+ # vs plain int
+ result = getattr(int_frame, op)(2 * int_frame)
+ expected = f(int_frame, 2 * int_frame)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dim", range(3, 6))
+ def test_arith_flex_frame_raise(self, all_arithmetic_operators, float_frame, dim):
+ # one instance of parametrized fixture
+ op = all_arithmetic_operators
+
+ # Check that arrays with dim >= 3 raise
+ arr = np.ones((1,) * dim)
+ msg = "Unable to coerce to Series/DataFrame"
+ with pytest.raises(ValueError, match=msg):
+ getattr(float_frame, op)(arr)
+
+ def test_arith_flex_frame_corner(self, float_frame):
+ const_add = float_frame.add(1)
+ tm.assert_frame_equal(const_add, float_frame + 1)
+
+ # corner cases
+ result = float_frame.add(float_frame[:0])
+ tm.assert_frame_equal(result, float_frame * np.nan)
+
+ result = float_frame[:0].add(float_frame)
+ tm.assert_frame_equal(result, float_frame * np.nan)
+
+ with pytest.raises(NotImplementedError, match="fill_value"):
+ float_frame.add(float_frame.iloc[0], fill_value=3)
+
+ with pytest.raises(NotImplementedError, match="fill_value"):
+ float_frame.add(float_frame.iloc[0], axis="index", fill_value=3)
+
+ @pytest.mark.parametrize("op", ["add", "sub", "mul", "mod"])
+ def test_arith_flex_series_ops(self, simple_frame, op):
+ # after arithmetic refactor, add truediv here
+ df = simple_frame
+
+ row = df.xs("a")
+ col = df["two"]
+ f = getattr(df, op)
+ op = getattr(operator, op)
+ tm.assert_frame_equal(f(row), op(df, row))
+ tm.assert_frame_equal(f(col, axis=0), op(df.T, col).T)
+
+ def test_arith_flex_series(self, simple_frame):
+ df = simple_frame
+
+ row = df.xs("a")
+ col = df["two"]
+ # special case for some reason
+ tm.assert_frame_equal(df.add(row, axis=None), df + row)
+
+ # cases which will be refactored after big arithmetic refactor
+ tm.assert_frame_equal(df.div(row), df / row)
+ tm.assert_frame_equal(df.div(col, axis=0), (df.T / col).T)
+
+ @pytest.mark.parametrize("dtype", ["int64", "float64"])
+ def test_arith_flex_series_broadcasting(self, dtype):
+ # broadcasting issue in GH 7325
+ df = DataFrame(np.arange(3 * 2).reshape((3, 2)), dtype=dtype)
+ expected = DataFrame([[np.nan, np.inf], [1.0, 1.5], [1.0, 1.25]])
+ result = df.div(df[0], axis="index")
+ tm.assert_frame_equal(result, expected)
+
+ def test_arith_flex_zero_len_raises(self):
+ # GH 19522 passing fill_value to frame flex arith methods should
+ # raise even in the zero-length special cases
+ ser_len0 = Series([], dtype=object)
+ df_len0 = DataFrame(columns=["A", "B"])
+ df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
+
+ with pytest.raises(NotImplementedError, match="fill_value"):
+ df.add(ser_len0, fill_value="E")
+
+ with pytest.raises(NotImplementedError, match="fill_value"):
+ df_len0.sub(df["A"], axis=None, fill_value=3)
+
+ def test_flex_add_scalar_fill_value(self):
+ # GH#12723
+ dat = np.array([0, 1, np.nan, 3, 4, 5], dtype="float")
+ df = DataFrame({"foo": dat}, index=range(6))
+
+ exp = df.fillna(0).add(2)
+ res = df.add(2, fill_value=0)
+ tm.assert_frame_equal(res, exp)
+
+ def test_sub_alignment_with_duplicate_index(self):
+ # GH#5185 dup aligning operations should work
+ df1 = DataFrame([1, 2, 3, 4, 5], index=[1, 2, 1, 2, 3])
+ df2 = DataFrame([1, 2, 3], index=[1, 2, 3])
+ expected = DataFrame([0, 2, 0, 2, 2], index=[1, 1, 2, 2, 3])
+ result = df1.sub(df2)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("op", ["__add__", "__mul__", "__sub__", "__truediv__"])
+ def test_arithmetic_with_duplicate_columns(self, op):
+ # operations
+ df = DataFrame({"A": np.arange(10), "B": np.random.default_rng(2).random(10)})
+ expected = getattr(df, op)(df)
+ expected.columns = ["A", "A"]
+ df.columns = ["A", "A"]
+ result = getattr(df, op)(df)
+ tm.assert_frame_equal(result, expected)
+ str(result)
+ result.dtypes
+
+ @pytest.mark.parametrize("level", [0, None])
+ def test_broadcast_multiindex(self, level):
+ # GH34388
+ df1 = DataFrame({"A": [0, 1, 2], "B": [1, 2, 3]})
+ df1.columns = df1.columns.set_names("L1")
+
+ df2 = DataFrame({("A", "C"): [0, 0, 0], ("A", "D"): [0, 0, 0]})
+ df2.columns = df2.columns.set_names(["L1", "L2"])
+
+ result = df1.add(df2, level=level)
+ expected = DataFrame({("A", "C"): [0, 1, 2], ("A", "D"): [0, 1, 2]})
+ expected.columns = expected.columns.set_names(["L1", "L2"])
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_frame_multiindex_operations(self):
+ # GH 43321
+ df = DataFrame(
+ {2010: [1, 2, 3], 2020: [3, 4, 5]},
+ index=MultiIndex.from_product(
+ [["a"], ["b"], [0, 1, 2]], names=["scen", "mod", "id"]
+ ),
+ )
+
+ series = Series(
+ [0.4],
+ index=MultiIndex.from_product([["b"], ["a"]], names=["mod", "scen"]),
+ )
+
+ expected = DataFrame(
+ {2010: [1.4, 2.4, 3.4], 2020: [3.4, 4.4, 5.4]},
+ index=MultiIndex.from_product(
+ [["a"], ["b"], [0, 1, 2]], names=["scen", "mod", "id"]
+ ),
+ )
+ result = df.add(series, axis=0)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_frame_multiindex_operations_series_index_to_frame_index(self):
+ # GH 43321
+ df = DataFrame(
+ {2010: [1], 2020: [3]},
+ index=MultiIndex.from_product([["a"], ["b"]], names=["scen", "mod"]),
+ )
+
+ series = Series(
+ [10.0, 20.0, 30.0],
+ index=MultiIndex.from_product(
+ [["a"], ["b"], [0, 1, 2]], names=["scen", "mod", "id"]
+ ),
+ )
+
+ expected = DataFrame(
+ {2010: [11.0, 21, 31.0], 2020: [13.0, 23.0, 33.0]},
+ index=MultiIndex.from_product(
+ [["a"], ["b"], [0, 1, 2]], names=["scen", "mod", "id"]
+ ),
+ )
+ result = df.add(series, axis=0)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_frame_multiindex_operations_no_align(self):
+ df = DataFrame(
+ {2010: [1, 2, 3], 2020: [3, 4, 5]},
+ index=MultiIndex.from_product(
+ [["a"], ["b"], [0, 1, 2]], names=["scen", "mod", "id"]
+ ),
+ )
+
+ series = Series(
+ [0.4],
+ index=MultiIndex.from_product([["c"], ["a"]], names=["mod", "scen"]),
+ )
+
+ expected = DataFrame(
+ {2010: np.nan, 2020: np.nan},
+ index=MultiIndex.from_tuples(
+ [
+ ("a", "b", 0),
+ ("a", "b", 1),
+ ("a", "b", 2),
+ ("a", "c", np.nan),
+ ],
+ names=["scen", "mod", "id"],
+ ),
+ )
+ result = df.add(series, axis=0)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_frame_multiindex_operations_part_align(self):
+ df = DataFrame(
+ {2010: [1, 2, 3], 2020: [3, 4, 5]},
+ index=MultiIndex.from_tuples(
+ [
+ ("a", "b", 0),
+ ("a", "b", 1),
+ ("a", "c", 2),
+ ],
+ names=["scen", "mod", "id"],
+ ),
+ )
+
+ series = Series(
+ [0.4],
+ index=MultiIndex.from_product([["b"], ["a"]], names=["mod", "scen"]),
+ )
+
+ expected = DataFrame(
+ {2010: [1.4, 2.4, np.nan], 2020: [3.4, 4.4, np.nan]},
+ index=MultiIndex.from_tuples(
+ [
+ ("a", "b", 0),
+ ("a", "b", 1),
+ ("a", "c", 2),
+ ],
+ names=["scen", "mod", "id"],
+ ),
+ )
+ result = df.add(series, axis=0)
+
+ tm.assert_frame_equal(result, expected)
+
+
+class TestFrameArithmetic:
+ def test_td64_op_nat_casting(self):
+ # Make sure we don't accidentally treat timedelta64(NaT) as datetime64
+ # when calling dispatch_to_series in DataFrame arithmetic
+ ser = Series(["NaT", "NaT"], dtype="timedelta64[ns]")
+ df = DataFrame([[1, 2], [3, 4]])
+
+ result = df * ser
+ expected = DataFrame({0: ser, 1: ser})
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_add_2d_array_rowlike_broadcasts(self):
+ # GH#23000
+ arr = np.arange(6).reshape(3, 2)
+ df = DataFrame(arr, columns=[True, False], index=["A", "B", "C"])
+
+ rowlike = arr[[1], :] # shape --> (1, ncols)
+ assert rowlike.shape == (1, df.shape[1])
+
+ expected = DataFrame(
+ [[2, 4], [4, 6], [6, 8]],
+ columns=df.columns,
+ index=df.index,
+ # specify dtype explicitly to avoid failing
+ # on 32bit builds
+ dtype=arr.dtype,
+ )
+ result = df + rowlike
+ tm.assert_frame_equal(result, expected)
+ result = rowlike + df
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_add_2d_array_collike_broadcasts(self):
+ # GH#23000
+ arr = np.arange(6).reshape(3, 2)
+ df = DataFrame(arr, columns=[True, False], index=["A", "B", "C"])
+
+ collike = arr[:, [1]] # shape --> (nrows, 1)
+ assert collike.shape == (df.shape[0], 1)
+
+ expected = DataFrame(
+ [[1, 2], [5, 6], [9, 10]],
+ columns=df.columns,
+ index=df.index,
+ # specify dtype explicitly to avoid failing
+ # on 32bit builds
+ dtype=arr.dtype,
+ )
+ result = df + collike
+ tm.assert_frame_equal(result, expected)
+ result = collike + df
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_arith_2d_array_rowlike_broadcasts(
+ self, request, all_arithmetic_operators, using_array_manager
+ ):
+ # GH#23000
+ opname = all_arithmetic_operators
+
+ if using_array_manager and opname in ("__rmod__", "__rfloordiv__"):
+ # TODO(ArrayManager) decide on dtypes
+ td.mark_array_manager_not_yet_implemented(request)
+
+ arr = np.arange(6).reshape(3, 2)
+ df = DataFrame(arr, columns=[True, False], index=["A", "B", "C"])
+
+ rowlike = arr[[1], :] # shape --> (1, ncols)
+ assert rowlike.shape == (1, df.shape[1])
+
+ exvals = [
+ getattr(df.loc["A"], opname)(rowlike.squeeze()),
+ getattr(df.loc["B"], opname)(rowlike.squeeze()),
+ getattr(df.loc["C"], opname)(rowlike.squeeze()),
+ ]
+
+ expected = DataFrame(exvals, columns=df.columns, index=df.index)
+
+ result = getattr(df, opname)(rowlike)
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_arith_2d_array_collike_broadcasts(
+ self, request, all_arithmetic_operators, using_array_manager
+ ):
+ # GH#23000
+ opname = all_arithmetic_operators
+
+ if using_array_manager and opname in ("__rmod__", "__rfloordiv__"):
+ # TODO(ArrayManager) decide on dtypes
+ td.mark_array_manager_not_yet_implemented(request)
+
+ arr = np.arange(6).reshape(3, 2)
+ df = DataFrame(arr, columns=[True, False], index=["A", "B", "C"])
+
+ collike = arr[:, [1]] # shape --> (nrows, 1)
+ assert collike.shape == (df.shape[0], 1)
+
+ exvals = {
+ True: getattr(df[True], opname)(collike.squeeze()),
+ False: getattr(df[False], opname)(collike.squeeze()),
+ }
+
+ dtype = None
+ if opname in ["__rmod__", "__rfloordiv__"]:
+ # Series ops may return mixed int/float dtypes in cases where
+ # DataFrame op will return all-float. So we upcast `expected`
+ dtype = np.common_type(*(x.values for x in exvals.values()))
+
+ expected = DataFrame(exvals, columns=df.columns, index=df.index, dtype=dtype)
+
+ result = getattr(df, opname)(collike)
+ tm.assert_frame_equal(result, expected)
+
+ def test_df_bool_mul_int(self):
+ # GH 22047, GH 22163 multiplication by 1 should result in int dtype,
+ # not object dtype
+ df = DataFrame([[False, True], [False, False]])
+ result = df * 1
+
+ # On appveyor this comes back as np.int32 instead of np.int64,
+ # so we check dtype.kind instead of just dtype
+ kinds = result.dtypes.apply(lambda x: x.kind)
+ assert (kinds == "i").all()
+
+ result = 1 * df
+ kinds = result.dtypes.apply(lambda x: x.kind)
+ assert (kinds == "i").all()
+
+ def test_arith_mixed(self):
+ left = DataFrame({"A": ["a", "b", "c"], "B": [1, 2, 3]})
+
+ result = left + left
+ expected = DataFrame({"A": ["aa", "bb", "cc"], "B": [2, 4, 6]})
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("col", ["A", "B"])
+ def test_arith_getitem_commute(self, all_arithmetic_functions, col):
+ df = DataFrame({"A": [1.1, 3.3], "B": [2.5, -3.9]})
+ result = all_arithmetic_functions(df, 1)[col]
+ expected = all_arithmetic_functions(df[col], 1)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "values", [[1, 2], (1, 2), np.array([1, 2]), range(1, 3), deque([1, 2])]
+ )
+ def test_arith_alignment_non_pandas_object(self, values):
+ # GH#17901
+ df = DataFrame({"A": [1, 1], "B": [1, 1]})
+ expected = DataFrame({"A": [2, 2], "B": [3, 3]})
+ result = df + values
+ tm.assert_frame_equal(result, expected)
+
+ def test_arith_non_pandas_object(self):
+ df = DataFrame(
+ np.arange(1, 10, dtype="f8").reshape(3, 3),
+ columns=["one", "two", "three"],
+ index=["a", "b", "c"],
+ )
+
+ val1 = df.xs("a").values
+ added = DataFrame(df.values + val1, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(df + val1, added)
+
+ added = DataFrame((df.values.T + val1).T, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(df.add(val1, axis=0), added)
+
+ val2 = list(df["two"])
+
+ added = DataFrame(df.values + val2, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(df + val2, added)
+
+ added = DataFrame((df.values.T + val2).T, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(df.add(val2, axis="index"), added)
+
+ val3 = np.random.default_rng(2).random(df.shape)
+ added = DataFrame(df.values + val3, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(df.add(val3), added)
+
+ def test_operations_with_interval_categories_index(self, all_arithmetic_operators):
+ # GH#27415
+ op = all_arithmetic_operators
+ ind = pd.CategoricalIndex(pd.interval_range(start=0.0, end=2.0))
+ data = [1, 2]
+ df = DataFrame([data], columns=ind)
+ num = 10
+ result = getattr(df, op)(num)
+ expected = DataFrame([[getattr(n, op)(num) for n in data]], columns=ind)
+ tm.assert_frame_equal(result, expected)
+
+ def test_frame_with_frame_reindex(self):
+ # GH#31623
+ df = DataFrame(
+ {
+ "foo": [pd.Timestamp("2019"), pd.Timestamp("2020")],
+ "bar": [pd.Timestamp("2018"), pd.Timestamp("2021")],
+ },
+ columns=["foo", "bar"],
+ )
+ df2 = df[["foo"]]
+
+ result = df - df2
+
+ expected = DataFrame(
+ {"foo": [pd.Timedelta(0), pd.Timedelta(0)], "bar": [np.nan, np.nan]},
+ columns=["bar", "foo"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "value, dtype",
+ [
+ (1, "i8"),
+ (1.0, "f8"),
+ (2**63, "f8"),
+ (1j, "complex128"),
+ (2**63, "complex128"),
+ (True, "bool"),
+ (np.timedelta64(20, "ns"), " b
+ tm.assert_frame_equal(result, expected)
+
+ result = df.values > b
+ tm.assert_numpy_array_equal(result, expected.values)
+
+ msg1d = "Unable to coerce to Series, length must be 2: given 3"
+ msg2d = "Unable to coerce to DataFrame, shape must be"
+ msg2db = "operands could not be broadcast together with shapes"
+ with pytest.raises(ValueError, match=msg1d):
+ # wrong shape
+ df > lst
+
+ with pytest.raises(ValueError, match=msg1d):
+ # wrong shape
+ df > tup
+
+ # broadcasts like ndarray (GH#23000)
+ result = df > b_r
+ tm.assert_frame_equal(result, expected)
+
+ result = df.values > b_r
+ tm.assert_numpy_array_equal(result, expected.values)
+
+ with pytest.raises(ValueError, match=msg2d):
+ df > b_c
+
+ with pytest.raises(ValueError, match=msg2db):
+ df.values > b_c
+
+ # ==
+ expected = DataFrame([[False, False], [True, False], [False, False]])
+ result = df == b
+ tm.assert_frame_equal(result, expected)
+
+ with pytest.raises(ValueError, match=msg1d):
+ df == lst
+
+ with pytest.raises(ValueError, match=msg1d):
+ df == tup
+
+ # broadcasts like ndarray (GH#23000)
+ result = df == b_r
+ tm.assert_frame_equal(result, expected)
+
+ result = df.values == b_r
+ tm.assert_numpy_array_equal(result, expected.values)
+
+ with pytest.raises(ValueError, match=msg2d):
+ df == b_c
+
+ assert df.values.shape != b_c.shape
+
+ # with alignment
+ df = DataFrame(
+ np.arange(6).reshape((3, 2)), columns=list("AB"), index=list("abc")
+ )
+ expected.index = df.index
+ expected.columns = df.columns
+
+ with pytest.raises(ValueError, match=msg1d):
+ df == lst
+
+ with pytest.raises(ValueError, match=msg1d):
+ df == tup
+
+ def test_inplace_ops_alignment(self):
+ # inplace ops / ops alignment
+ # GH 8511
+
+ columns = list("abcdefg")
+ X_orig = DataFrame(
+ np.arange(10 * len(columns)).reshape(-1, len(columns)),
+ columns=columns,
+ index=range(10),
+ )
+ Z = 100 * X_orig.iloc[:, 1:-1].copy()
+ block1 = list("bedcf")
+ subs = list("bcdef")
+
+ # add
+ X = X_orig.copy()
+ result1 = (X[block1] + Z).reindex(columns=subs)
+
+ X[block1] += Z
+ result2 = X.reindex(columns=subs)
+
+ X = X_orig.copy()
+ result3 = (X[block1] + Z[block1]).reindex(columns=subs)
+
+ X[block1] += Z[block1]
+ result4 = X.reindex(columns=subs)
+
+ tm.assert_frame_equal(result1, result2)
+ tm.assert_frame_equal(result1, result3)
+ tm.assert_frame_equal(result1, result4)
+
+ # sub
+ X = X_orig.copy()
+ result1 = (X[block1] - Z).reindex(columns=subs)
+
+ X[block1] -= Z
+ result2 = X.reindex(columns=subs)
+
+ X = X_orig.copy()
+ result3 = (X[block1] - Z[block1]).reindex(columns=subs)
+
+ X[block1] -= Z[block1]
+ result4 = X.reindex(columns=subs)
+
+ tm.assert_frame_equal(result1, result2)
+ tm.assert_frame_equal(result1, result3)
+ tm.assert_frame_equal(result1, result4)
+
+ def test_inplace_ops_identity(self):
+ # GH 5104
+ # make sure that we are actually changing the object
+ s_orig = Series([1, 2, 3])
+ df_orig = DataFrame(
+ np.random.default_rng(2).integers(0, 5, size=10).reshape(-1, 5)
+ )
+
+ # no dtype change
+ s = s_orig.copy()
+ s2 = s
+ s += 1
+ tm.assert_series_equal(s, s2)
+ tm.assert_series_equal(s_orig + 1, s)
+ assert s is s2
+ assert s._mgr is s2._mgr
+
+ df = df_orig.copy()
+ df2 = df
+ df += 1
+ tm.assert_frame_equal(df, df2)
+ tm.assert_frame_equal(df_orig + 1, df)
+ assert df is df2
+ assert df._mgr is df2._mgr
+
+ # dtype change
+ s = s_orig.copy()
+ s2 = s
+ s += 1.5
+ tm.assert_series_equal(s, s2)
+ tm.assert_series_equal(s_orig + 1.5, s)
+
+ df = df_orig.copy()
+ df2 = df
+ df += 1.5
+ tm.assert_frame_equal(df, df2)
+ tm.assert_frame_equal(df_orig + 1.5, df)
+ assert df is df2
+ assert df._mgr is df2._mgr
+
+ # mixed dtype
+ arr = np.random.default_rng(2).integers(0, 10, size=5)
+ df_orig = DataFrame({"A": arr.copy(), "B": "foo"})
+ df = df_orig.copy()
+ df2 = df
+ df["A"] += 1
+ expected = DataFrame({"A": arr.copy() + 1, "B": "foo"})
+ tm.assert_frame_equal(df, expected)
+ tm.assert_frame_equal(df2, expected)
+ assert df._mgr is df2._mgr
+
+ df = df_orig.copy()
+ df2 = df
+ df["A"] += 1.5
+ expected = DataFrame({"A": arr.copy() + 1.5, "B": "foo"})
+ tm.assert_frame_equal(df, expected)
+ tm.assert_frame_equal(df2, expected)
+ assert df._mgr is df2._mgr
+
+ @pytest.mark.parametrize(
+ "op",
+ [
+ "add",
+ "and",
+ pytest.param(
+ "div",
+ marks=pytest.mark.xfail(
+ raises=AttributeError, reason="__idiv__ not implemented"
+ ),
+ ),
+ "floordiv",
+ "mod",
+ "mul",
+ "or",
+ "pow",
+ "sub",
+ "truediv",
+ "xor",
+ ],
+ )
+ def test_inplace_ops_identity2(self, op):
+ df = DataFrame({"a": [1.0, 2.0, 3.0], "b": [1, 2, 3]})
+
+ operand = 2
+ if op in ("and", "or", "xor"):
+ # cannot use floats for boolean ops
+ df["a"] = [True, False, True]
+
+ df_copy = df.copy()
+ iop = f"__i{op}__"
+ op = f"__{op}__"
+
+ # no id change and value is correct
+ getattr(df, iop)(operand)
+ expected = getattr(df_copy, op)(operand)
+ tm.assert_frame_equal(df, expected)
+ expected = id(df)
+ assert id(df) == expected
+
+ @pytest.mark.parametrize(
+ "val",
+ [
+ [1, 2, 3],
+ (1, 2, 3),
+ np.array([1, 2, 3], dtype=np.int64),
+ range(1, 4),
+ ],
+ )
+ def test_alignment_non_pandas(self, val):
+ index = ["A", "B", "C"]
+ columns = ["X", "Y", "Z"]
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ index=index,
+ columns=columns,
+ )
+
+ align = DataFrame._align_for_op
+
+ expected = DataFrame({"X": val, "Y": val, "Z": val}, index=df.index)
+ tm.assert_frame_equal(align(df, val, axis=0)[1], expected)
+
+ expected = DataFrame(
+ {"X": [1, 1, 1], "Y": [2, 2, 2], "Z": [3, 3, 3]}, index=df.index
+ )
+ tm.assert_frame_equal(align(df, val, axis=1)[1], expected)
+
+ @pytest.mark.parametrize("val", [[1, 2], (1, 2), np.array([1, 2]), range(1, 3)])
+ def test_alignment_non_pandas_length_mismatch(self, val):
+ index = ["A", "B", "C"]
+ columns = ["X", "Y", "Z"]
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ index=index,
+ columns=columns,
+ )
+
+ align = DataFrame._align_for_op
+ # length mismatch
+ msg = "Unable to coerce to Series, length must be 3: given 2"
+ with pytest.raises(ValueError, match=msg):
+ align(df, val, axis=0)
+
+ with pytest.raises(ValueError, match=msg):
+ align(df, val, axis=1)
+
+ def test_alignment_non_pandas_index_columns(self):
+ index = ["A", "B", "C"]
+ columns = ["X", "Y", "Z"]
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ index=index,
+ columns=columns,
+ )
+
+ align = DataFrame._align_for_op
+ val = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ tm.assert_frame_equal(
+ align(df, val, axis=0)[1],
+ DataFrame(val, index=df.index, columns=df.columns),
+ )
+ tm.assert_frame_equal(
+ align(df, val, axis=1)[1],
+ DataFrame(val, index=df.index, columns=df.columns),
+ )
+
+ # shape mismatch
+ msg = "Unable to coerce to DataFrame, shape must be"
+ val = np.array([[1, 2, 3], [4, 5, 6]])
+ with pytest.raises(ValueError, match=msg):
+ align(df, val, axis=0)
+
+ with pytest.raises(ValueError, match=msg):
+ align(df, val, axis=1)
+
+ val = np.zeros((3, 3, 3))
+ msg = re.escape(
+ "Unable to coerce to Series/DataFrame, dimension must be <= 2: (3, 3, 3)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ align(df, val, axis=0)
+ with pytest.raises(ValueError, match=msg):
+ align(df, val, axis=1)
+
+ def test_no_warning(self, all_arithmetic_operators):
+ df = DataFrame({"A": [0.0, 0.0], "B": [0.0, None]})
+ b = df["B"]
+ with tm.assert_produces_warning(None):
+ getattr(df, all_arithmetic_operators)(b)
+
+ def test_dunder_methods_binary(self, all_arithmetic_operators):
+ # GH#??? frame.__foo__ should only accept one argument
+ df = DataFrame({"A": [0.0, 0.0], "B": [0.0, None]})
+ b = df["B"]
+ with pytest.raises(TypeError, match="takes 2 positional arguments"):
+ getattr(df, all_arithmetic_operators)(b, 0)
+
+ def test_align_int_fill_bug(self):
+ # GH#910
+ X = np.arange(10 * 10, dtype="float64").reshape(10, 10)
+ Y = np.ones((10, 1), dtype=int)
+
+ df1 = DataFrame(X)
+ df1["0.X"] = Y.squeeze()
+
+ df2 = df1.astype(float)
+
+ result = df1 - df1.mean()
+ expected = df2 - df2.mean()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_pow_with_realignment():
+ # GH#32685 pow has special semantics for operating with null values
+ left = DataFrame({"A": [0, 1, 2]})
+ right = DataFrame(index=[0, 1, 2])
+
+ result = left**right
+ expected = DataFrame({"A": [np.nan, 1.0, np.nan]})
+ tm.assert_frame_equal(result, expected)
+
+
+# TODO: move to tests.arithmetic and parametrize
+def test_pow_nan_with_zero():
+ left = DataFrame({"A": [np.nan, np.nan, np.nan]})
+ right = DataFrame({"A": [0, 0, 0]})
+
+ expected = DataFrame({"A": [1.0, 1.0, 1.0]})
+
+ result = left**right
+ tm.assert_frame_equal(result, expected)
+
+ result = left["A"] ** right["A"]
+ tm.assert_series_equal(result, expected["A"])
+
+
+def test_dataframe_series_extension_dtypes():
+ # https://github.com/pandas-dev/pandas/issues/34311
+ df = DataFrame(
+ np.random.default_rng(2).integers(0, 100, (10, 3)), columns=["a", "b", "c"]
+ )
+ ser = Series([1, 2, 3], index=["a", "b", "c"])
+
+ expected = df.to_numpy("int64") + ser.to_numpy("int64").reshape(-1, 3)
+ expected = DataFrame(expected, columns=df.columns, dtype="Int64")
+
+ df_ea = df.astype("Int64")
+ result = df_ea + ser
+ tm.assert_frame_equal(result, expected)
+ result = df_ea + ser.astype("Int64")
+ tm.assert_frame_equal(result, expected)
+
+
+def test_dataframe_blockwise_slicelike():
+ # GH#34367
+ arr = np.random.default_rng(2).integers(0, 1000, (100, 10))
+ df1 = DataFrame(arr)
+ # Explicit cast to float to avoid implicit cast when setting nan
+ df2 = df1.copy().astype({1: "float", 3: "float", 7: "float"})
+ df2.iloc[0, [1, 3, 7]] = np.nan
+
+ # Explicit cast to float to avoid implicit cast when setting nan
+ df3 = df1.copy().astype({5: "float"})
+ df3.iloc[0, [5]] = np.nan
+
+ # Explicit cast to float to avoid implicit cast when setting nan
+ df4 = df1.copy().astype({2: "float", 3: "float", 4: "float"})
+ df4.iloc[0, np.arange(2, 5)] = np.nan
+ # Explicit cast to float to avoid implicit cast when setting nan
+ df5 = df1.copy().astype({4: "float", 5: "float", 6: "float"})
+ df5.iloc[0, np.arange(4, 7)] = np.nan
+
+ for left, right in [(df1, df2), (df2, df3), (df4, df5)]:
+ res = left + right
+
+ expected = DataFrame({i: left[i] + right[i] for i in left.columns})
+ tm.assert_frame_equal(res, expected)
+
+
+@pytest.mark.parametrize(
+ "df, col_dtype",
+ [
+ (DataFrame([[1.0, 2.0], [4.0, 5.0]], columns=list("ab")), "float64"),
+ (DataFrame([[1.0, "b"], [4.0, "b"]], columns=list("ab")), "object"),
+ ],
+)
+def test_dataframe_operation_with_non_numeric_types(df, col_dtype):
+ # GH #22663
+ expected = DataFrame([[0.0, np.nan], [3.0, np.nan]], columns=list("ab"))
+ expected = expected.astype({"b": col_dtype})
+ result = df + Series([-1.0], index=list("a"))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_arith_reindex_with_duplicates():
+ # https://github.com/pandas-dev/pandas/issues/35194
+ df1 = DataFrame(data=[[0]], columns=["second"])
+ df2 = DataFrame(data=[[0, 0, 0]], columns=["first", "second", "second"])
+ result = df1 + df2
+ expected = DataFrame([[np.nan, 0, 0]], columns=["first", "second", "second"])
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("to_add", [[Series([1, 1])], [Series([1, 1]), Series([1, 1])]])
+def test_arith_list_of_arraylike_raise(to_add):
+ # GH 36702. Raise when trying to add list of array-like to DataFrame
+ df = DataFrame({"x": [1, 2], "y": [1, 2]})
+
+ msg = f"Unable to coerce list of {type(to_add[0])} to Series/DataFrame"
+ with pytest.raises(ValueError, match=msg):
+ df + to_add
+ with pytest.raises(ValueError, match=msg):
+ to_add + df
+
+
+def test_inplace_arithmetic_series_update(using_copy_on_write):
+ # https://github.com/pandas-dev/pandas/issues/36373
+ df = DataFrame({"A": [1, 2, 3]})
+ df_orig = df.copy()
+ series = df["A"]
+ vals = series._values
+
+ series += 1
+ if using_copy_on_write:
+ assert series._values is not vals
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ assert series._values is vals
+
+ expected = DataFrame({"A": [2, 3, 4]})
+ tm.assert_frame_equal(df, expected)
+
+
+def test_arithmetic_multiindex_align():
+ """
+ Regression test for: https://github.com/pandas-dev/pandas/issues/33765
+ """
+ df1 = DataFrame(
+ [[1]],
+ index=["a"],
+ columns=MultiIndex.from_product([[0], [1]], names=["a", "b"]),
+ )
+ df2 = DataFrame([[1]], index=["a"], columns=Index([0], name="a"))
+ expected = DataFrame(
+ [[0]],
+ index=["a"],
+ columns=MultiIndex.from_product([[0], [1]], names=["a", "b"]),
+ )
+ result = df1 - df2
+ tm.assert_frame_equal(result, expected)
+
+
+def test_bool_frame_mult_float():
+ # GH 18549
+ df = DataFrame(True, list("ab"), list("cd"))
+ result = df * 1.0
+ expected = DataFrame(np.ones((2, 2)), list("ab"), list("cd"))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_frame_sub_nullable_int(any_int_ea_dtype):
+ # GH 32822
+ series1 = Series([1, 2, None], dtype=any_int_ea_dtype)
+ series2 = Series([1, 2, 3], dtype=any_int_ea_dtype)
+ expected = DataFrame([0, 0, None], dtype=any_int_ea_dtype)
+ result = series1.to_frame() - series2.to_frame()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.filterwarnings(
+ "ignore:Passing a BlockManager|Passing a SingleBlockManager:DeprecationWarning"
+)
+def test_frame_op_subclass_nonclass_constructor():
+ # GH#43201 subclass._constructor is a function, not the subclass itself
+
+ class SubclassedSeries(Series):
+ @property
+ def _constructor(self):
+ return SubclassedSeries
+
+ @property
+ def _constructor_expanddim(self):
+ return SubclassedDataFrame
+
+ class SubclassedDataFrame(DataFrame):
+ _metadata = ["my_extra_data"]
+
+ def __init__(self, my_extra_data, *args, **kwargs) -> None:
+ self.my_extra_data = my_extra_data
+ super().__init__(*args, **kwargs)
+
+ @property
+ def _constructor(self):
+ return functools.partial(type(self), self.my_extra_data)
+
+ @property
+ def _constructor_sliced(self):
+ return SubclassedSeries
+
+ sdf = SubclassedDataFrame("some_data", {"A": [1, 2, 3], "B": [4, 5, 6]})
+ result = sdf * 2
+ expected = SubclassedDataFrame("some_data", {"A": [2, 4, 6], "B": [8, 10, 12]})
+ tm.assert_frame_equal(result, expected)
+
+ result = sdf + sdf
+ tm.assert_frame_equal(result, expected)
+
+
+def test_enum_column_equality():
+ Cols = Enum("Cols", "col1 col2")
+
+ q1 = DataFrame({Cols.col1: [1, 2, 3]})
+ q2 = DataFrame({Cols.col1: [1, 2, 3]})
+
+ result = q1[Cols.col1] == q2[Cols.col1]
+ expected = Series([True, True, True], name=Cols.col1)
+
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_block_internals.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_block_internals.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e8d92e832d01d2871530df0763b41e05d10e9dc
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_block_internals.py
@@ -0,0 +1,449 @@
+from datetime import (
+ datetime,
+ timedelta,
+)
+import itertools
+
+import numpy as np
+import pytest
+
+from pandas.errors import PerformanceWarning
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+ Timestamp,
+ date_range,
+ option_context,
+)
+import pandas._testing as tm
+from pandas.core.internals.blocks import NumpyBlock
+
+# Segregated collection of methods that require the BlockManager internal data
+# structure
+
+
+# TODO(ArrayManager) check which of those tests need to be rewritten to test the
+# equivalent for ArrayManager
+pytestmark = td.skip_array_manager_invalid_test
+
+
+class TestDataFrameBlockInternals:
+ def test_setitem_invalidates_datetime_index_freq(self):
+ # GH#24096 altering a datetime64tz column inplace invalidates the
+ # `freq` attribute on the underlying DatetimeIndex
+
+ dti = date_range("20130101", periods=3, tz="US/Eastern")
+ ts = dti[1]
+
+ df = DataFrame({"B": dti})
+ assert df["B"]._values.freq is None
+
+ df.iloc[1, 0] = pd.NaT
+ assert df["B"]._values.freq is None
+
+ # check that the DatetimeIndex was not altered in place
+ assert dti.freq == "D"
+ assert dti[1] == ts
+
+ def test_cast_internals(self, float_frame):
+ casted = DataFrame(float_frame._mgr, dtype=int)
+ expected = DataFrame(float_frame._series, dtype=int)
+ tm.assert_frame_equal(casted, expected)
+
+ casted = DataFrame(float_frame._mgr, dtype=np.int32)
+ expected = DataFrame(float_frame._series, dtype=np.int32)
+ tm.assert_frame_equal(casted, expected)
+
+ def test_consolidate(self, float_frame):
+ float_frame["E"] = 7.0
+ consolidated = float_frame._consolidate()
+ assert len(consolidated._mgr.blocks) == 1
+
+ # Ensure copy, do I want this?
+ recons = consolidated._consolidate()
+ assert recons is not consolidated
+ tm.assert_frame_equal(recons, consolidated)
+
+ float_frame["F"] = 8.0
+ assert len(float_frame._mgr.blocks) == 3
+
+ return_value = float_frame._consolidate_inplace()
+ assert return_value is None
+ assert len(float_frame._mgr.blocks) == 1
+
+ def test_consolidate_inplace(self, float_frame):
+ # triggers in-place consolidation
+ for letter in range(ord("A"), ord("Z")):
+ float_frame[chr(letter)] = chr(letter)
+
+ def test_modify_values(self, float_frame, using_copy_on_write):
+ if using_copy_on_write:
+ with pytest.raises(ValueError, match="read-only"):
+ float_frame.values[5] = 5
+ assert (float_frame.values[5] != 5).all()
+ return
+
+ float_frame.values[5] = 5
+ assert (float_frame.values[5] == 5).all()
+
+ # unconsolidated
+ float_frame["E"] = 7.0
+ col = float_frame["E"]
+ float_frame.values[6] = 6
+ # as of 2.0 .values does not consolidate, so subsequent calls to .values
+ # does not share data
+ assert not (float_frame.values[6] == 6).all()
+
+ assert (col == 7).all()
+
+ def test_boolean_set_uncons(self, float_frame):
+ float_frame["E"] = 7.0
+
+ expected = float_frame.values.copy()
+ expected[expected > 1] = 2
+
+ float_frame[float_frame > 1] = 2
+ tm.assert_almost_equal(expected, float_frame.values)
+
+ def test_constructor_with_convert(self):
+ # this is actually mostly a test of lib.maybe_convert_objects
+ # #2845
+ df = DataFrame({"A": [2**63 - 1]})
+ result = df["A"]
+ expected = Series(np.asarray([2**63 - 1], np.int64), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [2**63]})
+ result = df["A"]
+ expected = Series(np.asarray([2**63], np.uint64), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [datetime(2005, 1, 1), True]})
+ result = df["A"]
+ expected = Series(
+ np.asarray([datetime(2005, 1, 1), True], np.object_), name="A"
+ )
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [None, 1]})
+ result = df["A"]
+ expected = Series(np.asarray([np.nan, 1], np.float64), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [1.0, 2]})
+ result = df["A"]
+ expected = Series(np.asarray([1.0, 2], np.float64), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [1.0 + 2.0j, 3]})
+ result = df["A"]
+ expected = Series(np.asarray([1.0 + 2.0j, 3], np.complex128), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [1.0 + 2.0j, 3.0]})
+ result = df["A"]
+ expected = Series(np.asarray([1.0 + 2.0j, 3.0], np.complex128), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [1.0 + 2.0j, True]})
+ result = df["A"]
+ expected = Series(np.asarray([1.0 + 2.0j, True], np.object_), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [1.0, None]})
+ result = df["A"]
+ expected = Series(np.asarray([1.0, np.nan], np.float64), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [1.0 + 2.0j, None]})
+ result = df["A"]
+ expected = Series(np.asarray([1.0 + 2.0j, np.nan], np.complex128), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [2.0, 1, True, None]})
+ result = df["A"]
+ expected = Series(np.asarray([2.0, 1, True, None], np.object_), name="A")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"A": [2.0, 1, datetime(2006, 1, 1), None]})
+ result = df["A"]
+ expected = Series(
+ np.asarray([2.0, 1, datetime(2006, 1, 1), None], np.object_), name="A"
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_construction_with_mixed(self, float_string_frame):
+ # test construction edge cases with mixed types
+
+ # f7u12, this does not work without extensive workaround
+ data = [
+ [datetime(2001, 1, 5), np.nan, datetime(2001, 1, 2)],
+ [datetime(2000, 1, 2), datetime(2000, 1, 3), datetime(2000, 1, 1)],
+ ]
+ df = DataFrame(data)
+
+ # check dtypes
+ result = df.dtypes
+ expected = Series({"datetime64[us]": 3})
+
+ # mixed-type frames
+ float_string_frame["datetime"] = datetime.now()
+ float_string_frame["timedelta"] = timedelta(days=1, seconds=1)
+ assert float_string_frame["datetime"].dtype == "M8[us]"
+ assert float_string_frame["timedelta"].dtype == "m8[us]"
+ result = float_string_frame.dtypes
+ expected = Series(
+ [np.dtype("float64")] * 4
+ + [
+ np.dtype("object"),
+ np.dtype("datetime64[us]"),
+ np.dtype("timedelta64[us]"),
+ ],
+ index=list("ABCD") + ["foo", "datetime", "timedelta"],
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_construction_with_conversions(self):
+ # convert from a numpy array of non-ns timedelta64; as of 2.0 this does
+ # *not* convert
+ arr = np.array([1, 2, 3], dtype="timedelta64[s]")
+ df = DataFrame(index=range(3))
+ df["A"] = arr
+ expected = DataFrame(
+ {"A": pd.timedelta_range("00:00:01", periods=3, freq="s")}, index=range(3)
+ )
+ tm.assert_numpy_array_equal(df["A"].to_numpy(), arr)
+
+ expected = DataFrame(
+ {
+ "dt1": Timestamp("20130101"),
+ "dt2": date_range("20130101", periods=3).astype("M8[s]"),
+ # 'dt3' : date_range('20130101 00:00:01',periods=3,freq='s'),
+ # FIXME: don't leave commented-out
+ },
+ index=range(3),
+ )
+ assert expected.dtypes["dt1"] == "M8[s]"
+ assert expected.dtypes["dt2"] == "M8[s]"
+
+ df = DataFrame(index=range(3))
+ df["dt1"] = np.datetime64("2013-01-01")
+ df["dt2"] = np.array(
+ ["2013-01-01", "2013-01-02", "2013-01-03"], dtype="datetime64[D]"
+ )
+
+ # df['dt3'] = np.array(['2013-01-01 00:00:01','2013-01-01
+ # 00:00:02','2013-01-01 00:00:03'],dtype='datetime64[s]')
+ # FIXME: don't leave commented-out
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_compound_dtypes(self):
+ # GH 5191
+ # compound dtypes should raise not-implementederror
+
+ def f(dtype):
+ data = list(itertools.repeat((datetime(2001, 1, 1), "aa", 20), 9))
+ return DataFrame(data=data, columns=["A", "B", "C"], dtype=dtype)
+
+ msg = "compound dtypes are not implemented in the DataFrame constructor"
+ with pytest.raises(NotImplementedError, match=msg):
+ f([("A", "datetime64[h]"), ("B", "str"), ("C", "int32")])
+
+ # pre-2.0 these used to work (though results may be unexpected)
+ with pytest.raises(TypeError, match="argument must be"):
+ f("int64")
+ with pytest.raises(TypeError, match="argument must be"):
+ f("float64")
+
+ # 10822
+ msg = "^Unknown datetime string format, unable to parse: aa, at position 0$"
+ with pytest.raises(ValueError, match=msg):
+ f("M8[ns]")
+
+ def test_pickle(self, float_string_frame, timezone_frame):
+ empty_frame = DataFrame()
+
+ unpickled = tm.round_trip_pickle(float_string_frame)
+ tm.assert_frame_equal(float_string_frame, unpickled)
+
+ # buglet
+ float_string_frame._mgr.ndim
+
+ # empty
+ unpickled = tm.round_trip_pickle(empty_frame)
+ repr(unpickled)
+
+ # tz frame
+ unpickled = tm.round_trip_pickle(timezone_frame)
+ tm.assert_frame_equal(timezone_frame, unpickled)
+
+ def test_consolidate_datetime64(self):
+ # numpy vstack bug
+
+ df = DataFrame(
+ {
+ "starting": pd.to_datetime(
+ [
+ "2012-06-21 00:00",
+ "2012-06-23 07:00",
+ "2012-06-23 16:30",
+ "2012-06-25 08:00",
+ "2012-06-26 12:00",
+ ]
+ ),
+ "ending": pd.to_datetime(
+ [
+ "2012-06-23 07:00",
+ "2012-06-23 16:30",
+ "2012-06-25 08:00",
+ "2012-06-26 12:00",
+ "2012-06-27 08:00",
+ ]
+ ),
+ "measure": [77, 65, 77, 0, 77],
+ }
+ )
+
+ ser_starting = df.starting
+ ser_starting.index = ser_starting.values
+ ser_starting = ser_starting.tz_localize("US/Eastern")
+ ser_starting = ser_starting.tz_convert("UTC")
+ ser_starting.index.name = "starting"
+
+ ser_ending = df.ending
+ ser_ending.index = ser_ending.values
+ ser_ending = ser_ending.tz_localize("US/Eastern")
+ ser_ending = ser_ending.tz_convert("UTC")
+ ser_ending.index.name = "ending"
+
+ df.starting = ser_starting.index
+ df.ending = ser_ending.index
+
+ tm.assert_index_equal(pd.DatetimeIndex(df.starting), ser_starting.index)
+ tm.assert_index_equal(pd.DatetimeIndex(df.ending), ser_ending.index)
+
+ def test_is_mixed_type(self, float_frame, float_string_frame):
+ assert not float_frame._is_mixed_type
+ assert float_string_frame._is_mixed_type
+
+ def test_stale_cached_series_bug_473(self, using_copy_on_write):
+ # this is chained, but ok
+ with option_context("chained_assignment", None):
+ Y = DataFrame(
+ np.random.default_rng(2).random((4, 4)),
+ index=("a", "b", "c", "d"),
+ columns=("e", "f", "g", "h"),
+ )
+ repr(Y)
+ Y["e"] = Y["e"].astype("object")
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ Y["g"]["c"] = np.nan
+ else:
+ Y["g"]["c"] = np.nan
+ repr(Y)
+ Y.sum()
+ Y["g"].sum()
+ if using_copy_on_write:
+ assert not pd.isna(Y["g"]["c"])
+ else:
+ assert pd.isna(Y["g"]["c"])
+
+ def test_strange_column_corruption_issue(self, using_copy_on_write):
+ # TODO(wesm): Unclear how exactly this is related to internal matters
+ df = DataFrame(index=[0, 1])
+ df[0] = np.nan
+ wasCol = {}
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ for i, dt in enumerate(df.index):
+ for col in range(100, 200):
+ if col not in wasCol:
+ wasCol[col] = 1
+ df[col] = np.nan
+ if using_copy_on_write:
+ df.loc[dt, col] = i
+ else:
+ df[col][dt] = i
+
+ myid = 100
+
+ first = len(df.loc[pd.isna(df[myid]), [myid]])
+ second = len(df.loc[pd.isna(df[myid]), [myid]])
+ assert first == second == 0
+
+ def test_constructor_no_pandas_array(self):
+ # Ensure that NumpyExtensionArray isn't allowed inside Series
+ # See https://github.com/pandas-dev/pandas/issues/23995 for more.
+ arr = Series([1, 2, 3]).array
+ result = DataFrame({"A": arr})
+ expected = DataFrame({"A": [1, 2, 3]})
+ tm.assert_frame_equal(result, expected)
+ assert isinstance(result._mgr.blocks[0], NumpyBlock)
+ assert result._mgr.blocks[0].is_numeric
+
+ def test_add_column_with_pandas_array(self):
+ # GH 26390
+ df = DataFrame({"a": [1, 2, 3, 4], "b": ["a", "b", "c", "d"]})
+ df["c"] = pd.arrays.NumpyExtensionArray(np.array([1, 2, None, 3], dtype=object))
+ df2 = DataFrame(
+ {
+ "a": [1, 2, 3, 4],
+ "b": ["a", "b", "c", "d"],
+ "c": pd.arrays.NumpyExtensionArray(
+ np.array([1, 2, None, 3], dtype=object)
+ ),
+ }
+ )
+ assert type(df["c"]._mgr.blocks[0]) == NumpyBlock
+ assert df["c"]._mgr.blocks[0].is_object
+ assert type(df2["c"]._mgr.blocks[0]) == NumpyBlock
+ assert df2["c"]._mgr.blocks[0].is_object
+ tm.assert_frame_equal(df, df2)
+
+
+def test_update_inplace_sets_valid_block_values(using_copy_on_write):
+ # https://github.com/pandas-dev/pandas/issues/33457
+ df = DataFrame({"a": Series([1, 2, None], dtype="category")})
+
+ # inplace update of a single column
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["a"].fillna(1, inplace=True)
+ else:
+ df["a"].fillna(1, inplace=True)
+
+ # check we haven't put a Series into any block.values
+ assert isinstance(df._mgr.blocks[0].values, Categorical)
+
+ if not using_copy_on_write:
+ # smoketest for OP bug from GH#35731
+ assert df.isnull().sum().sum() == 0
+
+
+def test_nonconsolidated_item_cache_take():
+ # https://github.com/pandas-dev/pandas/issues/35521
+
+ # create non-consolidated dataframe with object dtype columns
+ df = DataFrame()
+ df["col1"] = Series(["a"], dtype=object)
+ df["col2"] = Series([0], dtype=object)
+
+ # access column (item cache)
+ df["col1"] == "A"
+ # take operation
+ # (regression was that this consolidated but didn't reset item cache,
+ # resulting in an invalid cache and the .at operation not working properly)
+ df[df["col2"] == 0]
+
+ # now setting value should update actual dataframe
+ df.at[0, "col1"] = "A"
+
+ expected = DataFrame({"col1": ["A"], "col2": [0]}, dtype=object)
+ tm.assert_frame_equal(df, expected)
+ assert df.at[0, "col1"] == "A"
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_constructors.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_constructors.py
new file mode 100644
index 0000000000000000000000000000000000000000..a291b906d671010dfbb188b096460fa361d4b225
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_constructors.py
@@ -0,0 +1,3290 @@
+import array
+from collections import (
+ OrderedDict,
+ abc,
+ defaultdict,
+ namedtuple,
+)
+from collections.abc import Iterator
+from dataclasses import make_dataclass
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
+import functools
+import re
+
+import numpy as np
+from numpy import ma
+from numpy.ma import mrecords
+import pytest
+import pytz
+
+from pandas._libs import lib
+from pandas.errors import IntCastingNaNError
+import pandas.util._test_decorators as td
+
+from pandas.core.dtypes.common import is_integer_dtype
+from pandas.core.dtypes.dtypes import (
+ DatetimeTZDtype,
+ IntervalDtype,
+ NumpyEADtype,
+ PeriodDtype,
+)
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ Interval,
+ MultiIndex,
+ Period,
+ RangeIndex,
+ Series,
+ Timedelta,
+ Timestamp,
+ cut,
+ date_range,
+ isna,
+)
+import pandas._testing as tm
+from pandas.arrays import (
+ DatetimeArray,
+ IntervalArray,
+ PeriodArray,
+ SparseArray,
+ TimedeltaArray,
+)
+
+MIXED_FLOAT_DTYPES = ["float16", "float32", "float64"]
+MIXED_INT_DTYPES = [
+ "uint8",
+ "uint16",
+ "uint32",
+ "uint64",
+ "int8",
+ "int16",
+ "int32",
+ "int64",
+]
+
+
+class TestDataFrameConstructors:
+ def test_constructor_from_ndarray_with_str_dtype(self):
+ # If we don't ravel/reshape around ensure_str_array, we end up
+ # with an array of strings each of which is e.g. "[0 1 2]"
+ arr = np.arange(12).reshape(4, 3)
+ df = DataFrame(arr, dtype=str)
+ expected = DataFrame(arr.astype(str))
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_from_2d_datetimearray(self, using_array_manager):
+ dti = date_range("2016-01-01", periods=6, tz="US/Pacific")
+ dta = dti._data.reshape(3, 2)
+
+ df = DataFrame(dta)
+ expected = DataFrame({0: dta[:, 0], 1: dta[:, 1]})
+ tm.assert_frame_equal(df, expected)
+ if not using_array_manager:
+ # GH#44724 big performance hit if we de-consolidate
+ assert len(df._mgr.blocks) == 1
+
+ def test_constructor_dict_with_tzaware_scalar(self):
+ # GH#42505
+ dt = Timestamp("2019-11-03 01:00:00-0700").tz_convert("America/Los_Angeles")
+ dt = dt.as_unit("ns")
+
+ df = DataFrame({"dt": dt}, index=[0])
+ expected = DataFrame({"dt": [dt]})
+ tm.assert_frame_equal(df, expected)
+
+ # Non-homogeneous
+ df = DataFrame({"dt": dt, "value": [1]})
+ expected = DataFrame({"dt": [dt], "value": [1]})
+ tm.assert_frame_equal(df, expected)
+
+ def test_construct_ndarray_with_nas_and_int_dtype(self):
+ # GH#26919 match Series by not casting np.nan to meaningless int
+ arr = np.array([[1, np.nan], [2, 3]])
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
+ with pytest.raises(IntCastingNaNError, match=msg):
+ DataFrame(arr, dtype="i8")
+
+ # check this matches Series behavior
+ with pytest.raises(IntCastingNaNError, match=msg):
+ Series(arr[0], dtype="i8", name=0)
+
+ def test_construct_from_list_of_datetimes(self):
+ df = DataFrame([datetime.now(), datetime.now()])
+ assert df[0].dtype == np.dtype("M8[ns]")
+
+ def test_constructor_from_tzaware_datetimeindex(self):
+ # don't cast a DatetimeIndex WITH a tz, leave as object
+ # GH#6032
+ naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B")
+ idx = naive.tz_localize("US/Pacific")
+
+ expected = Series(np.array(idx.tolist(), dtype="object"), name="B")
+ assert expected.dtype == idx.dtype
+
+ # convert index to series
+ result = Series(idx)
+ tm.assert_series_equal(result, expected)
+
+ def test_columns_with_leading_underscore_work_with_to_dict(self):
+ col_underscore = "_b"
+ df = DataFrame({"a": [1, 2], col_underscore: [3, 4]})
+ d = df.to_dict(orient="records")
+
+ ref_d = [{"a": 1, col_underscore: 3}, {"a": 2, col_underscore: 4}]
+
+ assert ref_d == d
+
+ def test_columns_with_leading_number_and_underscore_work_with_to_dict(self):
+ col_with_num = "1_b"
+ df = DataFrame({"a": [1, 2], col_with_num: [3, 4]})
+ d = df.to_dict(orient="records")
+
+ ref_d = [{"a": 1, col_with_num: 3}, {"a": 2, col_with_num: 4}]
+
+ assert ref_d == d
+
+ def test_array_of_dt64_nat_with_td64dtype_raises(self, frame_or_series):
+ # GH#39462
+ nat = np.datetime64("NaT", "ns")
+ arr = np.array([nat], dtype=object)
+ if frame_or_series is DataFrame:
+ arr = arr.reshape(1, 1)
+
+ msg = "Invalid type for timedelta scalar: "
+ with pytest.raises(TypeError, match=msg):
+ frame_or_series(arr, dtype="m8[ns]")
+
+ @pytest.mark.parametrize("kind", ["m", "M"])
+ def test_datetimelike_values_with_object_dtype(self, kind, frame_or_series):
+ # with dtype=object, we should cast dt64 values to Timestamps, not pydatetimes
+ if kind == "M":
+ dtype = "M8[ns]"
+ scalar_type = Timestamp
+ else:
+ dtype = "m8[ns]"
+ scalar_type = Timedelta
+
+ arr = np.arange(6, dtype="i8").view(dtype).reshape(3, 2)
+ if frame_or_series is Series:
+ arr = arr[:, 0]
+
+ obj = frame_or_series(arr, dtype=object)
+ assert obj._mgr.arrays[0].dtype == object
+ assert isinstance(obj._mgr.arrays[0].ravel()[0], scalar_type)
+
+ # go through a different path in internals.construction
+ obj = frame_or_series(frame_or_series(arr), dtype=object)
+ assert obj._mgr.arrays[0].dtype == object
+ assert isinstance(obj._mgr.arrays[0].ravel()[0], scalar_type)
+
+ obj = frame_or_series(frame_or_series(arr), dtype=NumpyEADtype(object))
+ assert obj._mgr.arrays[0].dtype == object
+ assert isinstance(obj._mgr.arrays[0].ravel()[0], scalar_type)
+
+ if frame_or_series is DataFrame:
+ # other paths through internals.construction
+ sers = [Series(x) for x in arr]
+ obj = frame_or_series(sers, dtype=object)
+ assert obj._mgr.arrays[0].dtype == object
+ assert isinstance(obj._mgr.arrays[0].ravel()[0], scalar_type)
+
+ def test_series_with_name_not_matching_column(self):
+ # GH#9232
+ x = Series(range(5), name=1)
+ y = Series(range(5), name=0)
+
+ result = DataFrame(x, columns=[0])
+ expected = DataFrame([], columns=[0])
+ tm.assert_frame_equal(result, expected)
+
+ result = DataFrame(y, columns=[1])
+ expected = DataFrame([], columns=[1])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "constructor",
+ [
+ lambda: DataFrame(),
+ lambda: DataFrame(None),
+ lambda: DataFrame(()),
+ lambda: DataFrame([]),
+ lambda: DataFrame(_ for _ in []),
+ lambda: DataFrame(range(0)),
+ lambda: DataFrame(data=None),
+ lambda: DataFrame(data=()),
+ lambda: DataFrame(data=[]),
+ lambda: DataFrame(data=(_ for _ in [])),
+ lambda: DataFrame(data=range(0)),
+ ],
+ )
+ def test_empty_constructor(self, constructor):
+ expected = DataFrame()
+ result = constructor()
+ assert len(result.index) == 0
+ assert len(result.columns) == 0
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "constructor",
+ [
+ lambda: DataFrame({}),
+ lambda: DataFrame(data={}),
+ ],
+ )
+ def test_empty_constructor_object_index(self, constructor):
+ expected = DataFrame(index=RangeIndex(0), columns=RangeIndex(0))
+ result = constructor()
+ assert len(result.index) == 0
+ assert len(result.columns) == 0
+ tm.assert_frame_equal(result, expected, check_index_type=True)
+
+ @pytest.mark.parametrize(
+ "emptylike,expected_index,expected_columns",
+ [
+ ([[]], RangeIndex(1), RangeIndex(0)),
+ ([[], []], RangeIndex(2), RangeIndex(0)),
+ ([(_ for _ in [])], RangeIndex(1), RangeIndex(0)),
+ ],
+ )
+ def test_emptylike_constructor(self, emptylike, expected_index, expected_columns):
+ expected = DataFrame(index=expected_index, columns=expected_columns)
+ result = DataFrame(emptylike)
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_mixed(self, float_string_frame):
+ assert float_string_frame["foo"].dtype == np.object_
+
+ def test_constructor_cast_failure(self):
+ # as of 2.0, we raise if we can't respect "dtype", previously we
+ # silently ignored
+ msg = "could not convert string to float"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame({"a": ["a", "b", "c"]}, dtype=np.float64)
+
+ # GH 3010, constructing with odd arrays
+ df = DataFrame(np.ones((4, 2)))
+
+ # this is ok
+ df["foo"] = np.ones((4, 2)).tolist()
+
+ # this is not ok
+ msg = "Expected a 1D array, got an array with shape \\(4, 2\\)"
+ with pytest.raises(ValueError, match=msg):
+ df["test"] = np.ones((4, 2))
+
+ # this is ok
+ df["foo2"] = np.ones((4, 2)).tolist()
+
+ def test_constructor_dtype_copy(self):
+ orig_df = DataFrame({"col1": [1.0], "col2": [2.0], "col3": [3.0]})
+
+ new_df = DataFrame(orig_df, dtype=float, copy=True)
+
+ new_df["col1"] = 200.0
+ assert orig_df["col1"][0] == 1.0
+
+ def test_constructor_dtype_nocast_view_dataframe(self, using_copy_on_write):
+ df = DataFrame([[1, 2]])
+ should_be_view = DataFrame(df, dtype=df[0].dtype)
+ if using_copy_on_write:
+ should_be_view.iloc[0, 0] = 99
+ assert df.values[0, 0] == 1
+ else:
+ should_be_view[0][0] = 99
+ assert df.values[0, 0] == 99
+
+ def test_constructor_dtype_nocast_view_2d_array(
+ self, using_array_manager, using_copy_on_write
+ ):
+ df = DataFrame([[1, 2], [3, 4]], dtype="int64")
+ if not using_array_manager and not using_copy_on_write:
+ should_be_view = DataFrame(df.values, dtype=df[0].dtype)
+ should_be_view[0][0] = 97
+ assert df.values[0, 0] == 97
+ else:
+ # INFO(ArrayManager) DataFrame(ndarray) doesn't necessarily preserve
+ # a view on the array to ensure contiguous 1D arrays
+ df2 = DataFrame(df.values, dtype=df[0].dtype)
+ assert df2._mgr.arrays[0].flags.c_contiguous
+
+ @td.skip_array_manager_invalid_test
+ def test_1d_object_array_does_not_copy(self):
+ # https://github.com/pandas-dev/pandas/issues/39272
+ arr = np.array(["a", "b"], dtype="object")
+ df = DataFrame(arr, copy=False)
+ assert np.shares_memory(df.values, arr)
+
+ @td.skip_array_manager_invalid_test
+ def test_2d_object_array_does_not_copy(self):
+ # https://github.com/pandas-dev/pandas/issues/39272
+ arr = np.array([["a", "b"], ["c", "d"]], dtype="object")
+ df = DataFrame(arr, copy=False)
+ assert np.shares_memory(df.values, arr)
+
+ def test_constructor_dtype_list_data(self):
+ df = DataFrame([[1, "2"], [None, "a"]], dtype=object)
+ assert df.loc[1, 0] is None
+ assert df.loc[0, 1] == "2"
+
+ def test_constructor_list_of_2d_raises(self):
+ # https://github.com/pandas-dev/pandas/issues/32289
+ a = DataFrame()
+ b = np.empty((0, 0))
+ with pytest.raises(ValueError, match=r"shape=\(1, 0, 0\)"):
+ DataFrame([a])
+
+ with pytest.raises(ValueError, match=r"shape=\(1, 0, 0\)"):
+ DataFrame([b])
+
+ a = DataFrame({"A": [1, 2]})
+ with pytest.raises(ValueError, match=r"shape=\(2, 2, 1\)"):
+ DataFrame([a, a])
+
+ @pytest.mark.parametrize(
+ "typ, ad",
+ [
+ # mixed floating and integer coexist in the same frame
+ ["float", {}],
+ # add lots of types
+ ["float", {"A": 1, "B": "foo", "C": "bar"}],
+ # GH 622
+ ["int", {}],
+ ],
+ )
+ def test_constructor_mixed_dtypes(self, typ, ad):
+ if typ == "int":
+ dtypes = MIXED_INT_DTYPES
+ arrays = [
+ np.array(np.random.default_rng(2).random(10), dtype=d) for d in dtypes
+ ]
+ elif typ == "float":
+ dtypes = MIXED_FLOAT_DTYPES
+ arrays = [
+ np.array(np.random.default_rng(2).integers(10, size=10), dtype=d)
+ for d in dtypes
+ ]
+
+ for d, a in zip(dtypes, arrays):
+ assert a.dtype == d
+ ad.update(dict(zip(dtypes, arrays)))
+ df = DataFrame(ad)
+
+ dtypes = MIXED_FLOAT_DTYPES + MIXED_INT_DTYPES
+ for d in dtypes:
+ if d in df:
+ assert df.dtypes[d] == d
+
+ def test_constructor_complex_dtypes(self):
+ # GH10952
+ a = np.random.default_rng(2).random(10).astype(np.complex64)
+ b = np.random.default_rng(2).random(10).astype(np.complex128)
+
+ df = DataFrame({"a": a, "b": b})
+ assert a.dtype == df.a.dtype
+ assert b.dtype == df.b.dtype
+
+ def test_constructor_dtype_str_na_values(self, string_dtype):
+ # https://github.com/pandas-dev/pandas/issues/21083
+ df = DataFrame({"A": ["x", None]}, dtype=string_dtype)
+ result = df.isna()
+ expected = DataFrame({"A": [False, True]})
+ tm.assert_frame_equal(result, expected)
+ assert df.iloc[1, 0] is None
+
+ df = DataFrame({"A": ["x", np.nan]}, dtype=string_dtype)
+ assert np.isnan(df.iloc[1, 0])
+
+ def test_constructor_rec(self, float_frame):
+ rec = float_frame.to_records(index=False)
+ rec.dtype.names = list(rec.dtype.names)[::-1]
+
+ index = float_frame.index
+
+ df = DataFrame(rec)
+ tm.assert_index_equal(df.columns, Index(rec.dtype.names))
+
+ df2 = DataFrame(rec, index=index)
+ tm.assert_index_equal(df2.columns, Index(rec.dtype.names))
+ tm.assert_index_equal(df2.index, index)
+
+ # case with columns != the ones we would infer from the data
+ rng = np.arange(len(rec))[::-1]
+ df3 = DataFrame(rec, index=rng, columns=["C", "B"])
+ expected = DataFrame(rec, index=rng).reindex(columns=["C", "B"])
+ tm.assert_frame_equal(df3, expected)
+
+ def test_constructor_bool(self):
+ df = DataFrame({0: np.ones(10, dtype=bool), 1: np.zeros(10, dtype=bool)})
+ assert df.values.dtype == np.bool_
+
+ def test_constructor_overflow_int64(self):
+ # see gh-14881
+ values = np.array([2**64 - i for i in range(1, 10)], dtype=np.uint64)
+
+ result = DataFrame({"a": values})
+ assert result["a"].dtype == np.uint64
+
+ # see gh-2355
+ data_scores = [
+ (6311132704823138710, 273),
+ (2685045978526272070, 23),
+ (8921811264899370420, 45),
+ (17019687244989530680, 270),
+ (9930107427299601010, 273),
+ ]
+ dtype = [("uid", "u8"), ("score", "u8")]
+ data = np.zeros((len(data_scores),), dtype=dtype)
+ data[:] = data_scores
+ df_crawls = DataFrame(data)
+ assert df_crawls["uid"].dtype == np.uint64
+
+ @pytest.mark.parametrize(
+ "values",
+ [
+ np.array([2**64], dtype=object),
+ np.array([2**65]),
+ [2**64 + 1],
+ np.array([-(2**63) - 4], dtype=object),
+ np.array([-(2**64) - 1]),
+ [-(2**65) - 2],
+ ],
+ )
+ def test_constructor_int_overflow(self, values):
+ # see gh-18584
+ value = values[0]
+ result = DataFrame(values)
+
+ assert result[0].dtype == object
+ assert result[0][0] == value
+
+ @pytest.mark.parametrize(
+ "values",
+ [
+ np.array([1], dtype=np.uint16),
+ np.array([1], dtype=np.uint32),
+ np.array([1], dtype=np.uint64),
+ [np.uint16(1)],
+ [np.uint32(1)],
+ [np.uint64(1)],
+ ],
+ )
+ def test_constructor_numpy_uints(self, values):
+ # GH#47294
+ value = values[0]
+ result = DataFrame(values)
+
+ assert result[0].dtype == value.dtype
+ assert result[0][0] == value
+
+ def test_constructor_ordereddict(self):
+ nitems = 100
+ nums = list(range(nitems))
+ np.random.default_rng(2).shuffle(nums)
+ expected = [f"A{i:d}" for i in nums]
+ df = DataFrame(OrderedDict(zip(expected, [[0]] * nitems)))
+ assert expected == list(df.columns)
+
+ def test_constructor_dict(self):
+ datetime_series = tm.makeTimeSeries(nper=30)
+ # test expects index shifted by 5
+ datetime_series_short = tm.makeTimeSeries(nper=30)[5:]
+
+ frame = DataFrame({"col1": datetime_series, "col2": datetime_series_short})
+
+ # col2 is padded with NaN
+ assert len(datetime_series) == 30
+ assert len(datetime_series_short) == 25
+
+ tm.assert_series_equal(frame["col1"], datetime_series.rename("col1"))
+
+ exp = Series(
+ np.concatenate([[np.nan] * 5, datetime_series_short.values]),
+ index=datetime_series.index,
+ name="col2",
+ )
+ tm.assert_series_equal(exp, frame["col2"])
+
+ frame = DataFrame(
+ {"col1": datetime_series, "col2": datetime_series_short},
+ columns=["col2", "col3", "col4"],
+ )
+
+ assert len(frame) == len(datetime_series_short)
+ assert "col1" not in frame
+ assert isna(frame["col3"]).all()
+
+ # Corner cases
+ assert len(DataFrame()) == 0
+
+ # mix dict and array, wrong size - no spec for which error should raise
+ # first
+ msg = "Mixing dicts with non-Series may lead to ambiguous ordering."
+ with pytest.raises(ValueError, match=msg):
+ DataFrame({"A": {"a": "a", "b": "b"}, "B": ["a", "b", "c"]})
+
+ def test_constructor_dict_length1(self):
+ # Length-one dict micro-optimization
+ frame = DataFrame({"A": {"1": 1, "2": 2}})
+ tm.assert_index_equal(frame.index, Index(["1", "2"]))
+
+ def test_constructor_dict_with_index(self):
+ # empty dict plus index
+ idx = Index([0, 1, 2])
+ frame = DataFrame({}, index=idx)
+ assert frame.index is idx
+
+ def test_constructor_dict_with_index_and_columns(self):
+ # empty dict with index and columns
+ idx = Index([0, 1, 2])
+ frame = DataFrame({}, index=idx, columns=idx)
+ assert frame.index is idx
+ assert frame.columns is idx
+ assert len(frame._series) == 3
+
+ def test_constructor_dict_of_empty_lists(self):
+ # with dict of empty list and Series
+ frame = DataFrame({"A": [], "B": []}, columns=["A", "B"])
+ tm.assert_index_equal(frame.index, RangeIndex(0), exact=True)
+
+ def test_constructor_dict_with_none(self):
+ # GH 14381
+ # Dict with None value
+ frame_none = DataFrame({"a": None}, index=[0])
+ frame_none_list = DataFrame({"a": [None]}, index=[0])
+ assert frame_none._get_value(0, "a") is None
+ assert frame_none_list._get_value(0, "a") is None
+ tm.assert_frame_equal(frame_none, frame_none_list)
+
+ def test_constructor_dict_errors(self):
+ # GH10856
+ # dict with scalar values should raise error, even if columns passed
+ msg = "If using all scalar values, you must pass an index"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame({"a": 0.7})
+
+ with pytest.raises(ValueError, match=msg):
+ DataFrame({"a": 0.7}, columns=["a"])
+
+ @pytest.mark.parametrize("scalar", [2, np.nan, None, "D"])
+ def test_constructor_invalid_items_unused(self, scalar):
+ # No error if invalid (scalar) value is in fact not used:
+ result = DataFrame({"a": scalar}, columns=["b"])
+ expected = DataFrame(columns=["b"])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("value", [2, np.nan, None, float("nan")])
+ def test_constructor_dict_nan_key(self, value):
+ # GH 18455
+ cols = [1, value, 3]
+ idx = ["a", value]
+ values = [[0, 3], [1, 4], [2, 5]]
+ data = {cols[c]: Series(values[c], index=idx) for c in range(3)}
+ result = DataFrame(data).sort_values(1).sort_values("a", axis=1)
+ expected = DataFrame(
+ np.arange(6, dtype="int64").reshape(2, 3), index=idx, columns=cols
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = DataFrame(data, index=idx).sort_values("a", axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = DataFrame(data, index=idx, columns=cols)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("value", [np.nan, None, float("nan")])
+ def test_constructor_dict_nan_tuple_key(self, value):
+ # GH 18455
+ cols = Index([(11, 21), (value, 22), (13, value)])
+ idx = Index([("a", value), (value, 2)])
+ values = [[0, 3], [1, 4], [2, 5]]
+ data = {cols[c]: Series(values[c], index=idx) for c in range(3)}
+ result = DataFrame(data).sort_values((11, 21)).sort_values(("a", value), axis=1)
+ expected = DataFrame(
+ np.arange(6, dtype="int64").reshape(2, 3), index=idx, columns=cols
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = DataFrame(data, index=idx).sort_values(("a", value), axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = DataFrame(data, index=idx, columns=cols)
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_dict_order_insertion(self):
+ datetime_series = tm.makeTimeSeries(nper=30)
+ datetime_series_short = tm.makeTimeSeries(nper=25)
+
+ # GH19018
+ # initialization ordering: by insertion order if python>= 3.6
+ d = {"b": datetime_series_short, "a": datetime_series}
+ frame = DataFrame(data=d)
+ expected = DataFrame(data=d, columns=list("ba"))
+ tm.assert_frame_equal(frame, expected)
+
+ def test_constructor_dict_nan_key_and_columns(self):
+ # GH 16894
+ result = DataFrame({np.nan: [1, 2], 2: [2, 3]}, columns=[np.nan, 2])
+ expected = DataFrame([[1, 2], [2, 3]], columns=[np.nan, 2])
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_multi_index(self):
+ # GH 4078
+ # construction error with mi and all-nan frame
+ tuples = [(2, 3), (3, 3), (3, 3)]
+ mi = MultiIndex.from_tuples(tuples)
+ df = DataFrame(index=mi, columns=mi)
+ assert isna(df).values.ravel().all()
+
+ tuples = [(3, 3), (2, 3), (3, 3)]
+ mi = MultiIndex.from_tuples(tuples)
+ df = DataFrame(index=mi, columns=mi)
+ assert isna(df).values.ravel().all()
+
+ def test_constructor_2d_index(self):
+ # GH 25416
+ # handling of 2d index in construction
+ df = DataFrame([[1]], columns=[[1]], index=[1, 2])
+ expected = DataFrame(
+ [1, 1],
+ index=Index([1, 2], dtype="int64"),
+ columns=MultiIndex(levels=[[1]], codes=[[0]]),
+ )
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame([[1]], columns=[[1]], index=[[1, 2]])
+ expected = DataFrame(
+ [1, 1],
+ index=MultiIndex(levels=[[1, 2]], codes=[[0, 1]]),
+ columns=MultiIndex(levels=[[1]], codes=[[0]]),
+ )
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_error_msgs(self):
+ msg = "Empty data passed with indices specified."
+ # passing an empty array with columns specified.
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(np.empty(0), index=[1])
+
+ msg = "Mixing dicts with non-Series may lead to ambiguous ordering."
+ # mix dict and array, wrong size
+ with pytest.raises(ValueError, match=msg):
+ DataFrame({"A": {"a": "a", "b": "b"}, "B": ["a", "b", "c"]})
+
+ # wrong size ndarray, GH 3105
+ msg = r"Shape of passed values is \(4, 3\), indices imply \(3, 3\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(
+ np.arange(12).reshape((4, 3)),
+ columns=["foo", "bar", "baz"],
+ index=date_range("2000-01-01", periods=3),
+ )
+
+ arr = np.array([[4, 5, 6]])
+ msg = r"Shape of passed values is \(1, 3\), indices imply \(1, 4\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(index=[0], columns=range(0, 4), data=arr)
+
+ arr = np.array([4, 5, 6])
+ msg = r"Shape of passed values is \(3, 1\), indices imply \(1, 4\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(index=[0], columns=range(0, 4), data=arr)
+
+ # higher dim raise exception
+ with pytest.raises(ValueError, match="Must pass 2-d input"):
+ DataFrame(np.zeros((3, 3, 3)), columns=["A", "B", "C"], index=[1])
+
+ # wrong size axis labels
+ msg = r"Shape of passed values is \(2, 3\), indices imply \(1, 3\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(
+ np.random.default_rng(2).random((2, 3)),
+ columns=["A", "B", "C"],
+ index=[1],
+ )
+
+ msg = r"Shape of passed values is \(2, 3\), indices imply \(2, 2\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(
+ np.random.default_rng(2).random((2, 3)),
+ columns=["A", "B"],
+ index=[1, 2],
+ )
+
+ # gh-26429
+ msg = "2 columns passed, passed data had 10 columns"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame((range(10), range(10, 20)), columns=("ones", "twos"))
+
+ msg = "If using all scalar values, you must pass an index"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame({"a": False, "b": True})
+
+ def test_constructor_subclass_dict(self, dict_subclass):
+ # Test for passing dict subclass to constructor
+ data = {
+ "col1": dict_subclass((x, 10.0 * x) for x in range(10)),
+ "col2": dict_subclass((x, 20.0 * x) for x in range(10)),
+ }
+ df = DataFrame(data)
+ refdf = DataFrame({col: dict(val.items()) for col, val in data.items()})
+ tm.assert_frame_equal(refdf, df)
+
+ data = dict_subclass(data.items())
+ df = DataFrame(data)
+ tm.assert_frame_equal(refdf, df)
+
+ def test_constructor_defaultdict(self, float_frame):
+ # try with defaultdict
+ data = {}
+ float_frame.loc[: float_frame.index[10], "B"] = np.nan
+
+ for k, v in float_frame.items():
+ dct = defaultdict(dict)
+ dct.update(v.to_dict())
+ data[k] = dct
+ frame = DataFrame(data)
+ expected = frame.reindex(index=float_frame.index)
+ tm.assert_frame_equal(float_frame, expected)
+
+ def test_constructor_dict_block(self):
+ expected = np.array([[4.0, 3.0, 2.0, 1.0]])
+ df = DataFrame(
+ {"d": [4.0], "c": [3.0], "b": [2.0], "a": [1.0]},
+ columns=["d", "c", "b", "a"],
+ )
+ tm.assert_numpy_array_equal(df.values, expected)
+
+ def test_constructor_dict_cast(self):
+ # cast float tests
+ test_data = {"A": {"1": 1, "2": 2}, "B": {"1": "1", "2": "2", "3": "3"}}
+ frame = DataFrame(test_data, dtype=float)
+ assert len(frame) == 3
+ assert frame["B"].dtype == np.float64
+ assert frame["A"].dtype == np.float64
+
+ frame = DataFrame(test_data)
+ assert len(frame) == 3
+ assert frame["B"].dtype == np.object_
+ assert frame["A"].dtype == np.float64
+
+ def test_constructor_dict_cast2(self):
+ # can't cast to float
+ test_data = {
+ "A": dict(zip(range(20), tm.makeStringIndex(20))),
+ "B": dict(zip(range(15), np.random.default_rng(2).standard_normal(15))),
+ }
+ with pytest.raises(ValueError, match="could not convert string"):
+ DataFrame(test_data, dtype=float)
+
+ def test_constructor_dict_dont_upcast(self):
+ d = {"Col1": {"Row1": "A String", "Row2": np.nan}}
+ df = DataFrame(d)
+ assert isinstance(df["Col1"]["Row2"], float)
+
+ def test_constructor_dict_dont_upcast2(self):
+ dm = DataFrame([[1, 2], ["a", "b"]], index=[1, 2], columns=[1, 2])
+ assert isinstance(dm[1][1], int)
+
+ def test_constructor_dict_of_tuples(self):
+ # GH #1491
+ data = {"a": (1, 2, 3), "b": (4, 5, 6)}
+
+ result = DataFrame(data)
+ expected = DataFrame({k: list(v) for k, v in data.items()})
+ tm.assert_frame_equal(result, expected, check_dtype=False)
+
+ def test_constructor_dict_of_ranges(self):
+ # GH 26356
+ data = {"a": range(3), "b": range(3, 6)}
+
+ result = DataFrame(data)
+ expected = DataFrame({"a": [0, 1, 2], "b": [3, 4, 5]})
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_dict_of_iterators(self):
+ # GH 26349
+ data = {"a": iter(range(3)), "b": reversed(range(3))}
+
+ result = DataFrame(data)
+ expected = DataFrame({"a": [0, 1, 2], "b": [2, 1, 0]})
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_dict_of_generators(self):
+ # GH 26349
+ data = {"a": (i for i in (range(3))), "b": (i for i in reversed(range(3)))}
+ result = DataFrame(data)
+ expected = DataFrame({"a": [0, 1, 2], "b": [2, 1, 0]})
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_dict_multiindex(self):
+ d = {
+ ("a", "a"): {("i", "i"): 0, ("i", "j"): 1, ("j", "i"): 2},
+ ("b", "a"): {("i", "i"): 6, ("i", "j"): 5, ("j", "i"): 4},
+ ("b", "c"): {("i", "i"): 7, ("i", "j"): 8, ("j", "i"): 9},
+ }
+ _d = sorted(d.items())
+ df = DataFrame(d)
+ expected = DataFrame(
+ [x[1] for x in _d], index=MultiIndex.from_tuples([x[0] for x in _d])
+ ).T
+ expected.index = MultiIndex.from_tuples(expected.index)
+ tm.assert_frame_equal(
+ df,
+ expected,
+ )
+
+ d["z"] = {"y": 123.0, ("i", "i"): 111, ("i", "j"): 111, ("j", "i"): 111}
+ _d.insert(0, ("z", d["z"]))
+ expected = DataFrame(
+ [x[1] for x in _d], index=Index([x[0] for x in _d], tupleize_cols=False)
+ ).T
+ expected.index = Index(expected.index, tupleize_cols=False)
+ df = DataFrame(d)
+ df = df.reindex(columns=expected.columns, index=expected.index)
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_dict_datetime64_index(self):
+ # GH 10160
+ dates_as_str = ["1984-02-19", "1988-11-06", "1989-12-03", "1990-03-15"]
+
+ def create_data(constructor):
+ return {i: {constructor(s): 2 * i} for i, s in enumerate(dates_as_str)}
+
+ data_datetime64 = create_data(np.datetime64)
+ data_datetime = create_data(lambda x: datetime.strptime(x, "%Y-%m-%d"))
+ data_Timestamp = create_data(Timestamp)
+
+ expected = DataFrame(
+ [
+ {0: 0, 1: None, 2: None, 3: None},
+ {0: None, 1: 2, 2: None, 3: None},
+ {0: None, 1: None, 2: 4, 3: None},
+ {0: None, 1: None, 2: None, 3: 6},
+ ],
+ index=[Timestamp(dt) for dt in dates_as_str],
+ )
+
+ result_datetime64 = DataFrame(data_datetime64)
+ result_datetime = DataFrame(data_datetime)
+ result_Timestamp = DataFrame(data_Timestamp)
+ tm.assert_frame_equal(result_datetime64, expected)
+ tm.assert_frame_equal(result_datetime, expected)
+ tm.assert_frame_equal(result_Timestamp, expected)
+
+ @pytest.mark.parametrize(
+ "klass,name",
+ [
+ (lambda x: np.timedelta64(x, "D"), "timedelta64"),
+ (lambda x: timedelta(days=x), "pytimedelta"),
+ (lambda x: Timedelta(x, "D"), "Timedelta[ns]"),
+ (lambda x: Timedelta(x, "D").as_unit("s"), "Timedelta[s]"),
+ ],
+ )
+ def test_constructor_dict_timedelta64_index(self, klass, name):
+ # GH 10160
+ td_as_int = [1, 2, 3, 4]
+
+ data = {i: {klass(s): 2 * i} for i, s in enumerate(td_as_int)}
+
+ expected = DataFrame(
+ [
+ {0: 0, 1: None, 2: None, 3: None},
+ {0: None, 1: 2, 2: None, 3: None},
+ {0: None, 1: None, 2: 4, 3: None},
+ {0: None, 1: None, 2: None, 3: 6},
+ ],
+ index=[Timedelta(td, "D") for td in td_as_int],
+ )
+
+ result = DataFrame(data)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_period_dict(self):
+ # PeriodIndex
+ a = pd.PeriodIndex(["2012-01", "NaT", "2012-04"], freq="M")
+ b = pd.PeriodIndex(["2012-02-01", "2012-03-01", "NaT"], freq="D")
+ df = DataFrame({"a": a, "b": b})
+ assert df["a"].dtype == a.dtype
+ assert df["b"].dtype == b.dtype
+
+ # list of periods
+ df = DataFrame({"a": a.astype(object).tolist(), "b": b.astype(object).tolist()})
+ assert df["a"].dtype == a.dtype
+ assert df["b"].dtype == b.dtype
+
+ def test_constructor_dict_extension_scalar(self, ea_scalar_and_dtype):
+ ea_scalar, ea_dtype = ea_scalar_and_dtype
+ df = DataFrame({"a": ea_scalar}, index=[0])
+ assert df["a"].dtype == ea_dtype
+
+ expected = DataFrame(index=[0], columns=["a"], data=ea_scalar)
+
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize(
+ "data,dtype",
+ [
+ (Period("2020-01"), PeriodDtype("M")),
+ (Interval(left=0, right=5), IntervalDtype("int64", "right")),
+ (
+ Timestamp("2011-01-01", tz="US/Eastern"),
+ DatetimeTZDtype(unit="s", tz="US/Eastern"),
+ ),
+ ],
+ )
+ def test_constructor_extension_scalar_data(self, data, dtype):
+ # GH 34832
+ df = DataFrame(index=[0, 1], columns=["a", "b"], data=data)
+
+ assert df["a"].dtype == dtype
+ assert df["b"].dtype == dtype
+
+ arr = pd.array([data] * 2, dtype=dtype)
+ expected = DataFrame({"a": arr, "b": arr})
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_nested_dict_frame_constructor(self):
+ rng = pd.period_range("1/1/2000", periods=5)
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)), columns=rng)
+
+ data = {}
+ for col in df.columns:
+ for row in df.index:
+ data.setdefault(col, {})[row] = df._get_value(row, col)
+
+ result = DataFrame(data, columns=rng)
+ tm.assert_frame_equal(result, df)
+
+ data = {}
+ for col in df.columns:
+ for row in df.index:
+ data.setdefault(row, {})[col] = df._get_value(row, col)
+
+ result = DataFrame(data, index=rng).T
+ tm.assert_frame_equal(result, df)
+
+ def _check_basic_constructor(self, empty):
+ # mat: 2d matrix with shape (3, 2) to input. empty - makes sized
+ # objects
+ mat = empty((2, 3), dtype=float)
+ # 2-D input
+ frame = DataFrame(mat, columns=["A", "B", "C"], index=[1, 2])
+
+ assert len(frame.index) == 2
+ assert len(frame.columns) == 3
+
+ # 1-D input
+ frame = DataFrame(empty((3,)), columns=["A"], index=[1, 2, 3])
+ assert len(frame.index) == 3
+ assert len(frame.columns) == 1
+
+ if empty is not np.ones:
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
+ with pytest.raises(IntCastingNaNError, match=msg):
+ DataFrame(mat, columns=["A", "B", "C"], index=[1, 2], dtype=np.int64)
+ return
+ else:
+ frame = DataFrame(
+ mat, columns=["A", "B", "C"], index=[1, 2], dtype=np.int64
+ )
+ assert frame.values.dtype == np.int64
+
+ # wrong size axis labels
+ msg = r"Shape of passed values is \(2, 3\), indices imply \(1, 3\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(mat, columns=["A", "B", "C"], index=[1])
+ msg = r"Shape of passed values is \(2, 3\), indices imply \(2, 2\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(mat, columns=["A", "B"], index=[1, 2])
+
+ # higher dim raise exception
+ with pytest.raises(ValueError, match="Must pass 2-d input"):
+ DataFrame(empty((3, 3, 3)), columns=["A", "B", "C"], index=[1])
+
+ # automatic labeling
+ frame = DataFrame(mat)
+ tm.assert_index_equal(frame.index, Index(range(2)), exact=True)
+ tm.assert_index_equal(frame.columns, Index(range(3)), exact=True)
+
+ frame = DataFrame(mat, index=[1, 2])
+ tm.assert_index_equal(frame.columns, Index(range(3)), exact=True)
+
+ frame = DataFrame(mat, columns=["A", "B", "C"])
+ tm.assert_index_equal(frame.index, Index(range(2)), exact=True)
+
+ # 0-length axis
+ frame = DataFrame(empty((0, 3)))
+ assert len(frame.index) == 0
+
+ frame = DataFrame(empty((3, 0)))
+ assert len(frame.columns) == 0
+
+ def test_constructor_ndarray(self):
+ self._check_basic_constructor(np.ones)
+
+ frame = DataFrame(["foo", "bar"], index=[0, 1], columns=["A"])
+ assert len(frame) == 2
+
+ def test_constructor_maskedarray(self):
+ self._check_basic_constructor(ma.masked_all)
+
+ # Check non-masked values
+ mat = ma.masked_all((2, 3), dtype=float)
+ mat[0, 0] = 1.0
+ mat[1, 2] = 2.0
+ frame = DataFrame(mat, columns=["A", "B", "C"], index=[1, 2])
+ assert 1.0 == frame["A"][1]
+ assert 2.0 == frame["C"][2]
+
+ # what is this even checking??
+ mat = ma.masked_all((2, 3), dtype=float)
+ frame = DataFrame(mat, columns=["A", "B", "C"], index=[1, 2])
+ assert np.all(~np.asarray(frame == frame))
+
+ @pytest.mark.filterwarnings(
+ "ignore:elementwise comparison failed:DeprecationWarning"
+ )
+ def test_constructor_maskedarray_nonfloat(self):
+ # masked int promoted to float
+ mat = ma.masked_all((2, 3), dtype=int)
+ # 2-D input
+ frame = DataFrame(mat, columns=["A", "B", "C"], index=[1, 2])
+
+ assert len(frame.index) == 2
+ assert len(frame.columns) == 3
+ assert np.all(~np.asarray(frame == frame))
+
+ # cast type
+ frame = DataFrame(mat, columns=["A", "B", "C"], index=[1, 2], dtype=np.float64)
+ assert frame.values.dtype == np.float64
+
+ # Check non-masked values
+ mat2 = ma.copy(mat)
+ mat2[0, 0] = 1
+ mat2[1, 2] = 2
+ frame = DataFrame(mat2, columns=["A", "B", "C"], index=[1, 2])
+ assert 1 == frame["A"][1]
+ assert 2 == frame["C"][2]
+
+ # masked np.datetime64 stays (use NaT as null)
+ mat = ma.masked_all((2, 3), dtype="M8[ns]")
+ # 2-D input
+ frame = DataFrame(mat, columns=["A", "B", "C"], index=[1, 2])
+
+ assert len(frame.index) == 2
+ assert len(frame.columns) == 3
+ assert isna(frame).values.all()
+
+ # cast type
+ msg = r"datetime64\[ns\] values and dtype=int64 is not supported"
+ with pytest.raises(TypeError, match=msg):
+ DataFrame(mat, columns=["A", "B", "C"], index=[1, 2], dtype=np.int64)
+
+ # Check non-masked values
+ mat2 = ma.copy(mat)
+ mat2[0, 0] = 1
+ mat2[1, 2] = 2
+ frame = DataFrame(mat2, columns=["A", "B", "C"], index=[1, 2])
+ assert 1 == frame["A"].view("i8")[1]
+ assert 2 == frame["C"].view("i8")[2]
+
+ # masked bool promoted to object
+ mat = ma.masked_all((2, 3), dtype=bool)
+ # 2-D input
+ frame = DataFrame(mat, columns=["A", "B", "C"], index=[1, 2])
+
+ assert len(frame.index) == 2
+ assert len(frame.columns) == 3
+ assert np.all(~np.asarray(frame == frame))
+
+ # cast type
+ frame = DataFrame(mat, columns=["A", "B", "C"], index=[1, 2], dtype=object)
+ assert frame.values.dtype == object
+
+ # Check non-masked values
+ mat2 = ma.copy(mat)
+ mat2[0, 0] = True
+ mat2[1, 2] = False
+ frame = DataFrame(mat2, columns=["A", "B", "C"], index=[1, 2])
+ assert frame["A"][1] is True
+ assert frame["C"][2] is False
+
+ def test_constructor_maskedarray_hardened(self):
+ # Check numpy masked arrays with hard masks -- from GH24574
+ mat_hard = ma.masked_all((2, 2), dtype=float).harden_mask()
+ result = DataFrame(mat_hard, columns=["A", "B"], index=[1, 2])
+ expected = DataFrame(
+ {"A": [np.nan, np.nan], "B": [np.nan, np.nan]},
+ columns=["A", "B"],
+ index=[1, 2],
+ dtype=float,
+ )
+ tm.assert_frame_equal(result, expected)
+ # Check case where mask is hard but no data are masked
+ mat_hard = ma.ones((2, 2), dtype=float).harden_mask()
+ result = DataFrame(mat_hard, columns=["A", "B"], index=[1, 2])
+ expected = DataFrame(
+ {"A": [1.0, 1.0], "B": [1.0, 1.0]},
+ columns=["A", "B"],
+ index=[1, 2],
+ dtype=float,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_maskedrecarray_dtype(self):
+ # Ensure constructor honors dtype
+ data = np.ma.array(
+ np.ma.zeros(5, dtype=[("date", " None:
+ self._lst = lst
+
+ def __getitem__(self, n):
+ return self._lst.__getitem__(n)
+
+ def __len__(self) -> int:
+ return self._lst.__len__()
+
+ lst_containers = [DummyContainer([1, "a"]), DummyContainer([2, "b"])]
+ columns = ["num", "str"]
+ result = DataFrame(lst_containers, columns=columns)
+ expected = DataFrame([[1, "a"], [2, "b"]], columns=columns)
+ tm.assert_frame_equal(result, expected, check_dtype=False)
+
+ def test_constructor_stdlib_array(self):
+ # GH 4297
+ # support Array
+ result = DataFrame({"A": array.array("i", range(10))})
+ expected = DataFrame({"A": list(range(10))})
+ tm.assert_frame_equal(result, expected, check_dtype=False)
+
+ expected = DataFrame([list(range(10)), list(range(10))])
+ result = DataFrame([array.array("i", range(10)), array.array("i", range(10))])
+ tm.assert_frame_equal(result, expected, check_dtype=False)
+
+ def test_constructor_range(self):
+ # GH26342
+ result = DataFrame(range(10))
+ expected = DataFrame(list(range(10)))
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_of_ranges(self):
+ result = DataFrame([range(10), range(10)])
+ expected = DataFrame([list(range(10)), list(range(10))])
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_iterable(self):
+ # GH 21987
+ class Iter:
+ def __iter__(self) -> Iterator:
+ for i in range(10):
+ yield [1, 2, 3]
+
+ expected = DataFrame([[1, 2, 3]] * 10)
+ result = DataFrame(Iter())
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_iterator(self):
+ result = DataFrame(iter(range(10)))
+ expected = DataFrame(list(range(10)))
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_of_iterators(self):
+ result = DataFrame([iter(range(10)), iter(range(10))])
+ expected = DataFrame([list(range(10)), list(range(10))])
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_generator(self):
+ # related #2305
+
+ gen1 = (i for i in range(10))
+ gen2 = (i for i in range(10))
+
+ expected = DataFrame([list(range(10)), list(range(10))])
+ result = DataFrame([gen1, gen2])
+ tm.assert_frame_equal(result, expected)
+
+ gen = ([i, "a"] for i in range(10))
+ result = DataFrame(gen)
+ expected = DataFrame({0: range(10), 1: "a"})
+ tm.assert_frame_equal(result, expected, check_dtype=False)
+
+ def test_constructor_list_of_dicts(self):
+ result = DataFrame([{}])
+ expected = DataFrame(index=RangeIndex(1), columns=[])
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_ordered_dict_nested_preserve_order(self):
+ # see gh-18166
+ nested1 = OrderedDict([("b", 1), ("a", 2)])
+ nested2 = OrderedDict([("b", 2), ("a", 5)])
+ data = OrderedDict([("col2", nested1), ("col1", nested2)])
+ result = DataFrame(data)
+ data = {"col2": [1, 2], "col1": [2, 5]}
+ expected = DataFrame(data=data, index=["b", "a"])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dict_type", [dict, OrderedDict])
+ def test_constructor_ordered_dict_preserve_order(self, dict_type):
+ # see gh-13304
+ expected = DataFrame([[2, 1]], columns=["b", "a"])
+
+ data = dict_type()
+ data["b"] = [2]
+ data["a"] = [1]
+
+ result = DataFrame(data)
+ tm.assert_frame_equal(result, expected)
+
+ data = dict_type()
+ data["b"] = 2
+ data["a"] = 1
+
+ result = DataFrame([data])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dict_type", [dict, OrderedDict])
+ def test_constructor_ordered_dict_conflicting_orders(self, dict_type):
+ # the first dict element sets the ordering for the DataFrame,
+ # even if there are conflicting orders from subsequent ones
+ row_one = dict_type()
+ row_one["b"] = 2
+ row_one["a"] = 1
+
+ row_two = dict_type()
+ row_two["a"] = 1
+ row_two["b"] = 2
+
+ row_three = {"b": 2, "a": 1}
+
+ expected = DataFrame([[2, 1], [2, 1]], columns=["b", "a"])
+ result = DataFrame([row_one, row_two])
+ tm.assert_frame_equal(result, expected)
+
+ expected = DataFrame([[2, 1], [2, 1], [2, 1]], columns=["b", "a"])
+ result = DataFrame([row_one, row_two, row_three])
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_of_series_aligned_index(self):
+ series = [Series(i, index=["b", "a", "c"], name=str(i)) for i in range(3)]
+ result = DataFrame(series)
+ expected = DataFrame(
+ {"b": [0, 1, 2], "a": [0, 1, 2], "c": [0, 1, 2]},
+ columns=["b", "a", "c"],
+ index=["0", "1", "2"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_of_derived_dicts(self):
+ class CustomDict(dict):
+ pass
+
+ d = {"a": 1.5, "b": 3}
+
+ data_custom = [CustomDict(d)]
+ data = [d]
+
+ result_custom = DataFrame(data_custom)
+ result = DataFrame(data)
+ tm.assert_frame_equal(result, result_custom)
+
+ def test_constructor_ragged(self):
+ data = {
+ "A": np.random.default_rng(2).standard_normal(10),
+ "B": np.random.default_rng(2).standard_normal(8),
+ }
+ with pytest.raises(ValueError, match="All arrays must be of the same length"):
+ DataFrame(data)
+
+ def test_constructor_scalar(self):
+ idx = Index(range(3))
+ df = DataFrame({"a": 0}, index=idx)
+ expected = DataFrame({"a": [0, 0, 0]}, index=idx)
+ tm.assert_frame_equal(df, expected, check_dtype=False)
+
+ def test_constructor_Series_copy_bug(self, float_frame):
+ df = DataFrame(float_frame["A"], index=float_frame.index, columns=["A"])
+ df.copy()
+
+ def test_constructor_mixed_dict_and_Series(self):
+ data = {}
+ data["A"] = {"foo": 1, "bar": 2, "baz": 3}
+ data["B"] = Series([4, 3, 2, 1], index=["bar", "qux", "baz", "foo"])
+
+ result = DataFrame(data)
+ assert result.index.is_monotonic_increasing
+
+ # ordering ambiguous, raise exception
+ with pytest.raises(ValueError, match="ambiguous ordering"):
+ DataFrame({"A": ["a", "b"], "B": {"a": "a", "b": "b"}})
+
+ # this is OK though
+ result = DataFrame({"A": ["a", "b"], "B": Series(["a", "b"], index=["a", "b"])})
+ expected = DataFrame({"A": ["a", "b"], "B": ["a", "b"]}, index=["a", "b"])
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_mixed_type_rows(self):
+ # Issue 25075
+ data = [[1, 2], (3, 4)]
+ result = DataFrame(data)
+ expected = DataFrame([[1, 2], [3, 4]])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "tuples,lists",
+ [
+ ((), []),
+ ((()), []),
+ (((), ()), [(), ()]),
+ (((), ()), [[], []]),
+ (([], []), [[], []]),
+ (([1], [2]), [[1], [2]]), # GH 32776
+ (([1, 2, 3], [4, 5, 6]), [[1, 2, 3], [4, 5, 6]]),
+ ],
+ )
+ def test_constructor_tuple(self, tuples, lists):
+ # GH 25691
+ result = DataFrame(tuples)
+ expected = DataFrame(lists)
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_of_tuples(self):
+ result = DataFrame({"A": [(1, 2), (3, 4)]})
+ expected = DataFrame({"A": Series([(1, 2), (3, 4)])})
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_of_namedtuples(self):
+ # GH11181
+ named_tuple = namedtuple("Pandas", list("ab"))
+ tuples = [named_tuple(1, 3), named_tuple(2, 4)]
+ expected = DataFrame({"a": [1, 2], "b": [3, 4]})
+ result = DataFrame(tuples)
+ tm.assert_frame_equal(result, expected)
+
+ # with columns
+ expected = DataFrame({"y": [1, 2], "z": [3, 4]})
+ result = DataFrame(tuples, columns=["y", "z"])
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_of_dataclasses(self):
+ # GH21910
+ Point = make_dataclass("Point", [("x", int), ("y", int)])
+
+ data = [Point(0, 3), Point(1, 3)]
+ expected = DataFrame({"x": [0, 1], "y": [3, 3]})
+ result = DataFrame(data)
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_of_dataclasses_with_varying_types(self):
+ # GH21910
+ # varying types
+ Point = make_dataclass("Point", [("x", int), ("y", int)])
+ HLine = make_dataclass("HLine", [("x0", int), ("x1", int), ("y", int)])
+
+ data = [Point(0, 3), HLine(1, 3, 3)]
+
+ expected = DataFrame(
+ {"x": [0, np.nan], "y": [3, 3], "x0": [np.nan, 1], "x1": [np.nan, 3]}
+ )
+ result = DataFrame(data)
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_of_dataclasses_error_thrown(self):
+ # GH21910
+ Point = make_dataclass("Point", [("x", int), ("y", int)])
+
+ # expect TypeError
+ msg = "asdict() should be called on dataclass instances"
+ with pytest.raises(TypeError, match=re.escape(msg)):
+ DataFrame([Point(0, 0), {"x": 1, "y": 0}])
+
+ def test_constructor_list_of_dict_order(self):
+ # GH10056
+ data = [
+ {"First": 1, "Second": 4, "Third": 7, "Fourth": 10},
+ {"Second": 5, "First": 2, "Fourth": 11, "Third": 8},
+ {"Second": 6, "First": 3, "Fourth": 12, "Third": 9, "YYY": 14, "XXX": 13},
+ ]
+ expected = DataFrame(
+ {
+ "First": [1, 2, 3],
+ "Second": [4, 5, 6],
+ "Third": [7, 8, 9],
+ "Fourth": [10, 11, 12],
+ "YYY": [None, None, 14],
+ "XXX": [None, None, 13],
+ }
+ )
+ result = DataFrame(data)
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_Series_named(self):
+ a = Series([1, 2, 3], index=["a", "b", "c"], name="x")
+ df = DataFrame(a)
+ assert df.columns[0] == "x"
+ tm.assert_index_equal(df.index, a.index)
+
+ # ndarray like
+ arr = np.random.default_rng(2).standard_normal(10)
+ s = Series(arr, name="x")
+ df = DataFrame(s)
+ expected = DataFrame({"x": s})
+ tm.assert_frame_equal(df, expected)
+
+ s = Series(arr, index=range(3, 13))
+ df = DataFrame(s)
+ expected = DataFrame({0: s})
+ tm.assert_frame_equal(df, expected)
+
+ msg = r"Shape of passed values is \(10, 1\), indices imply \(10, 2\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(s, columns=[1, 2])
+
+ # #2234
+ a = Series([], name="x", dtype=object)
+ df = DataFrame(a)
+ assert df.columns[0] == "x"
+
+ # series with name and w/o
+ s1 = Series(arr, name="x")
+ df = DataFrame([s1, arr]).T
+ expected = DataFrame({"x": s1, "Unnamed 0": arr}, columns=["x", "Unnamed 0"])
+ tm.assert_frame_equal(df, expected)
+
+ # this is a bit non-intuitive here; the series collapse down to arrays
+ df = DataFrame([arr, s1]).T
+ expected = DataFrame({1: s1, 0: arr}, columns=[0, 1])
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_Series_named_and_columns(self):
+ # GH 9232 validation
+
+ s0 = Series(range(5), name=0)
+ s1 = Series(range(5), name=1)
+
+ # matching name and column gives standard frame
+ tm.assert_frame_equal(DataFrame(s0, columns=[0]), s0.to_frame())
+ tm.assert_frame_equal(DataFrame(s1, columns=[1]), s1.to_frame())
+
+ # non-matching produces empty frame
+ assert DataFrame(s0, columns=[1]).empty
+ assert DataFrame(s1, columns=[0]).empty
+
+ def test_constructor_Series_differently_indexed(self):
+ # name
+ s1 = Series([1, 2, 3], index=["a", "b", "c"], name="x")
+
+ # no name
+ s2 = Series([1, 2, 3], index=["a", "b", "c"])
+
+ other_index = Index(["a", "b"])
+
+ df1 = DataFrame(s1, index=other_index)
+ exp1 = DataFrame(s1.reindex(other_index))
+ assert df1.columns[0] == "x"
+ tm.assert_frame_equal(df1, exp1)
+
+ df2 = DataFrame(s2, index=other_index)
+ exp2 = DataFrame(s2.reindex(other_index))
+ assert df2.columns[0] == 0
+ tm.assert_index_equal(df2.index, other_index)
+ tm.assert_frame_equal(df2, exp2)
+
+ @pytest.mark.parametrize(
+ "name_in1,name_in2,name_in3,name_out",
+ [
+ ("idx", "idx", "idx", "idx"),
+ ("idx", "idx", None, None),
+ ("idx", None, None, None),
+ ("idx1", "idx2", None, None),
+ ("idx1", "idx1", "idx2", None),
+ ("idx1", "idx2", "idx3", None),
+ (None, None, None, None),
+ ],
+ )
+ def test_constructor_index_names(self, name_in1, name_in2, name_in3, name_out):
+ # GH13475
+ indices = [
+ Index(["a", "b", "c"], name=name_in1),
+ Index(["b", "c", "d"], name=name_in2),
+ Index(["c", "d", "e"], name=name_in3),
+ ]
+ series = {
+ c: Series([0, 1, 2], index=i) for i, c in zip(indices, ["x", "y", "z"])
+ }
+ result = DataFrame(series)
+
+ exp_ind = Index(["a", "b", "c", "d", "e"], name=name_out)
+ expected = DataFrame(
+ {
+ "x": [0, 1, 2, np.nan, np.nan],
+ "y": [np.nan, 0, 1, 2, np.nan],
+ "z": [np.nan, np.nan, 0, 1, 2],
+ },
+ index=exp_ind,
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_manager_resize(self, float_frame):
+ index = list(float_frame.index[:5])
+ columns = list(float_frame.columns[:3])
+
+ result = DataFrame(float_frame._mgr, index=index, columns=columns)
+ tm.assert_index_equal(result.index, Index(index))
+ tm.assert_index_equal(result.columns, Index(columns))
+
+ def test_constructor_mix_series_nonseries(self, float_frame):
+ df = DataFrame(
+ {"A": float_frame["A"], "B": list(float_frame["B"])}, columns=["A", "B"]
+ )
+ tm.assert_frame_equal(df, float_frame.loc[:, ["A", "B"]])
+
+ msg = "does not match index length"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame({"A": float_frame["A"], "B": list(float_frame["B"])[:-2]})
+
+ def test_constructor_miscast_na_int_dtype(self):
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
+
+ with pytest.raises(IntCastingNaNError, match=msg):
+ DataFrame([[np.nan, 1], [1, 0]], dtype=np.int64)
+
+ def test_constructor_column_duplicates(self):
+ # it works! #2079
+ df = DataFrame([[8, 5]], columns=["a", "a"])
+ edf = DataFrame([[8, 5]])
+ edf.columns = ["a", "a"]
+
+ tm.assert_frame_equal(df, edf)
+
+ idf = DataFrame.from_records([(8, 5)], columns=["a", "a"])
+
+ tm.assert_frame_equal(idf, edf)
+
+ def test_constructor_empty_with_string_dtype(self):
+ # GH 9428
+ expected = DataFrame(index=[0, 1], columns=[0, 1], dtype=object)
+
+ df = DataFrame(index=[0, 1], columns=[0, 1], dtype=str)
+ tm.assert_frame_equal(df, expected)
+ df = DataFrame(index=[0, 1], columns=[0, 1], dtype=np.str_)
+ tm.assert_frame_equal(df, expected)
+ df = DataFrame(index=[0, 1], columns=[0, 1], dtype="U5")
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_empty_with_string_extension(self, nullable_string_dtype):
+ # GH 34915
+ expected = DataFrame(columns=["c1"], dtype=nullable_string_dtype)
+ df = DataFrame(columns=["c1"], dtype=nullable_string_dtype)
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_single_value(self):
+ # expecting single value upcasting here
+ df = DataFrame(0.0, index=[1, 2, 3], columns=["a", "b", "c"])
+ tm.assert_frame_equal(
+ df, DataFrame(np.zeros(df.shape).astype("float64"), df.index, df.columns)
+ )
+
+ df = DataFrame(0, index=[1, 2, 3], columns=["a", "b", "c"])
+ tm.assert_frame_equal(
+ df, DataFrame(np.zeros(df.shape).astype("int64"), df.index, df.columns)
+ )
+
+ df = DataFrame("a", index=[1, 2], columns=["a", "c"])
+ tm.assert_frame_equal(
+ df,
+ DataFrame(
+ np.array([["a", "a"], ["a", "a"]], dtype=object),
+ index=[1, 2],
+ columns=["a", "c"],
+ ),
+ )
+
+ msg = "DataFrame constructor not properly called!"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame("a", [1, 2])
+ with pytest.raises(ValueError, match=msg):
+ DataFrame("a", columns=["a", "c"])
+
+ msg = "incompatible data and dtype"
+ with pytest.raises(TypeError, match=msg):
+ DataFrame("a", [1, 2], ["a", "c"], float)
+
+ def test_constructor_with_datetimes(self):
+ intname = np.dtype(int).name
+ floatname = np.dtype(np.float64).name
+ objectname = np.dtype(np.object_).name
+
+ # single item
+ df = DataFrame(
+ {
+ "A": 1,
+ "B": "foo",
+ "C": "bar",
+ "D": Timestamp("20010101"),
+ "E": datetime(2001, 1, 2, 0, 0),
+ },
+ index=np.arange(10),
+ )
+ result = df.dtypes
+ expected = Series(
+ [np.dtype("int64")]
+ + [np.dtype(objectname)] * 2
+ + [np.dtype("M8[s]"), np.dtype("M8[us]")],
+ index=list("ABCDE"),
+ )
+ tm.assert_series_equal(result, expected)
+
+ # check with ndarray construction ndim==0 (e.g. we are passing a ndim 0
+ # ndarray with a dtype specified)
+ df = DataFrame(
+ {
+ "a": 1.0,
+ "b": 2,
+ "c": "foo",
+ floatname: np.array(1.0, dtype=floatname),
+ intname: np.array(1, dtype=intname),
+ },
+ index=np.arange(10),
+ )
+ result = df.dtypes
+ expected = Series(
+ [np.dtype("float64")]
+ + [np.dtype("int64")]
+ + [np.dtype("object")]
+ + [np.dtype("float64")]
+ + [np.dtype(intname)],
+ index=["a", "b", "c", floatname, intname],
+ )
+ tm.assert_series_equal(result, expected)
+
+ # check with ndarray construction ndim>0
+ df = DataFrame(
+ {
+ "a": 1.0,
+ "b": 2,
+ "c": "foo",
+ floatname: np.array([1.0] * 10, dtype=floatname),
+ intname: np.array([1] * 10, dtype=intname),
+ },
+ index=np.arange(10),
+ )
+ result = df.dtypes
+ expected = Series(
+ [np.dtype("float64")]
+ + [np.dtype("int64")]
+ + [np.dtype("object")]
+ + [np.dtype("float64")]
+ + [np.dtype(intname)],
+ index=["a", "b", "c", floatname, intname],
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_with_datetimes1(self):
+ # GH 2809
+ ind = date_range(start="2000-01-01", freq="D", periods=10)
+ datetimes = [ts.to_pydatetime() for ts in ind]
+ datetime_s = Series(datetimes)
+ assert datetime_s.dtype == "M8[ns]"
+
+ def test_constructor_with_datetimes2(self):
+ # GH 2810
+ ind = date_range(start="2000-01-01", freq="D", periods=10)
+ datetimes = [ts.to_pydatetime() for ts in ind]
+ dates = [ts.date() for ts in ind]
+ df = DataFrame(datetimes, columns=["datetimes"])
+ df["dates"] = dates
+ result = df.dtypes
+ expected = Series(
+ [np.dtype("datetime64[ns]"), np.dtype("object")],
+ index=["datetimes", "dates"],
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_with_datetimes3(self):
+ # GH 7594
+ # don't coerce tz-aware
+ tz = pytz.timezone("US/Eastern")
+ dt = tz.localize(datetime(2012, 1, 1))
+
+ df = DataFrame({"End Date": dt}, index=[0])
+ assert df.iat[0, 0] == dt
+ tm.assert_series_equal(
+ df.dtypes, Series({"End Date": "datetime64[us, US/Eastern]"})
+ )
+
+ df = DataFrame([{"End Date": dt}])
+ assert df.iat[0, 0] == dt
+ tm.assert_series_equal(
+ df.dtypes, Series({"End Date": "datetime64[ns, US/Eastern]"})
+ )
+
+ def test_constructor_with_datetimes4(self):
+ # tz-aware (UTC and other tz's)
+ # GH 8411
+ dr = date_range("20130101", periods=3)
+ df = DataFrame({"value": dr})
+ assert df.iat[0, 0].tz is None
+ dr = date_range("20130101", periods=3, tz="UTC")
+ df = DataFrame({"value": dr})
+ assert str(df.iat[0, 0].tz) == "UTC"
+ dr = date_range("20130101", periods=3, tz="US/Eastern")
+ df = DataFrame({"value": dr})
+ assert str(df.iat[0, 0].tz) == "US/Eastern"
+
+ def test_constructor_with_datetimes5(self):
+ # GH 7822
+ # preserver an index with a tz on dict construction
+ i = date_range("1/1/2011", periods=5, freq="10s", tz="US/Eastern")
+
+ expected = DataFrame({"a": i.to_series().reset_index(drop=True)})
+ df = DataFrame()
+ df["a"] = i
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame({"a": i})
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_with_datetimes6(self):
+ # multiples
+ i = date_range("1/1/2011", periods=5, freq="10s", tz="US/Eastern")
+ i_no_tz = date_range("1/1/2011", periods=5, freq="10s")
+ df = DataFrame({"a": i, "b": i_no_tz})
+ expected = DataFrame({"a": i.to_series().reset_index(drop=True), "b": i_no_tz})
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array([None, None, None, None, datetime.now(), None]),
+ np.array([None, None, datetime.now(), None]),
+ [[np.datetime64("NaT")], [None]],
+ [[np.datetime64("NaT")], [pd.NaT]],
+ [[None], [np.datetime64("NaT")]],
+ [[None], [pd.NaT]],
+ [[pd.NaT], [np.datetime64("NaT")]],
+ [[pd.NaT], [None]],
+ ],
+ )
+ def test_constructor_datetimes_with_nulls(self, arr):
+ # gh-15869, GH#11220
+ result = DataFrame(arr).dtypes
+ expected = Series([np.dtype("datetime64[ns]")])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("order", ["K", "A", "C", "F"])
+ @pytest.mark.parametrize(
+ "unit",
+ ["M", "D", "h", "m", "s", "ms", "us", "ns"],
+ )
+ def test_constructor_datetimes_non_ns(self, order, unit):
+ dtype = f"datetime64[{unit}]"
+ na = np.array(
+ [
+ ["2015-01-01", "2015-01-02", "2015-01-03"],
+ ["2017-01-01", "2017-01-02", "2017-02-03"],
+ ],
+ dtype=dtype,
+ order=order,
+ )
+ df = DataFrame(na)
+ expected = DataFrame(na.astype("M8[ns]"))
+ if unit in ["M", "D", "h", "m"]:
+ with pytest.raises(TypeError, match="Cannot cast"):
+ expected.astype(dtype)
+
+ # instead the constructor casts to the closest supported reso, i.e. "s"
+ expected = expected.astype("datetime64[s]")
+ else:
+ expected = expected.astype(dtype=dtype)
+
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("order", ["K", "A", "C", "F"])
+ @pytest.mark.parametrize(
+ "unit",
+ [
+ "D",
+ "h",
+ "m",
+ "s",
+ "ms",
+ "us",
+ "ns",
+ ],
+ )
+ def test_constructor_timedelta_non_ns(self, order, unit):
+ dtype = f"timedelta64[{unit}]"
+ na = np.array(
+ [
+ [np.timedelta64(1, "D"), np.timedelta64(2, "D")],
+ [np.timedelta64(4, "D"), np.timedelta64(5, "D")],
+ ],
+ dtype=dtype,
+ order=order,
+ )
+ df = DataFrame(na)
+ if unit in ["D", "h", "m"]:
+ # we get the nearest supported unit, i.e. "s"
+ exp_unit = "s"
+ else:
+ exp_unit = unit
+ exp_dtype = np.dtype(f"m8[{exp_unit}]")
+ expected = DataFrame(
+ [
+ [Timedelta(1, "D"), Timedelta(2, "D")],
+ [Timedelta(4, "D"), Timedelta(5, "D")],
+ ],
+ dtype=exp_dtype,
+ )
+ # TODO(2.0): ideally we should get the same 'expected' without passing
+ # dtype=exp_dtype.
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_for_list_with_dtypes(self):
+ # test list of lists/ndarrays
+ df = DataFrame([np.arange(5) for x in range(5)])
+ result = df.dtypes
+ expected = Series([np.dtype("int")] * 5)
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame([np.array(np.arange(5), dtype="int32") for x in range(5)])
+ result = df.dtypes
+ expected = Series([np.dtype("int32")] * 5)
+ tm.assert_series_equal(result, expected)
+
+ # overflow issue? (we always expected int64 upcasting here)
+ df = DataFrame({"a": [2**31, 2**31 + 1]})
+ assert df.dtypes.iloc[0] == np.dtype("int64")
+
+ # GH #2751 (construction with no index specified), make sure we cast to
+ # platform values
+ df = DataFrame([1, 2])
+ assert df.dtypes.iloc[0] == np.dtype("int64")
+
+ df = DataFrame([1.0, 2.0])
+ assert df.dtypes.iloc[0] == np.dtype("float64")
+
+ df = DataFrame({"a": [1, 2]})
+ assert df.dtypes.iloc[0] == np.dtype("int64")
+
+ df = DataFrame({"a": [1.0, 2.0]})
+ assert df.dtypes.iloc[0] == np.dtype("float64")
+
+ df = DataFrame({"a": 1}, index=range(3))
+ assert df.dtypes.iloc[0] == np.dtype("int64")
+
+ df = DataFrame({"a": 1.0}, index=range(3))
+ assert df.dtypes.iloc[0] == np.dtype("float64")
+
+ # with object list
+ df = DataFrame(
+ {
+ "a": [1, 2, 4, 7],
+ "b": [1.2, 2.3, 5.1, 6.3],
+ "c": list("abcd"),
+ "d": [datetime(2000, 1, 1) for i in range(4)],
+ "e": [1.0, 2, 4.0, 7],
+ }
+ )
+ result = df.dtypes
+ expected = Series(
+ [
+ np.dtype("int64"),
+ np.dtype("float64"),
+ np.dtype("object"),
+ np.dtype("datetime64[ns]"),
+ np.dtype("float64"),
+ ],
+ index=list("abcde"),
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_frame_copy(self, float_frame):
+ cop = DataFrame(float_frame, copy=True)
+ cop["A"] = 5
+ assert (cop["A"] == 5).all()
+ assert not (float_frame["A"] == 5).all()
+
+ def test_constructor_frame_shallow_copy(self, float_frame):
+ # constructing a DataFrame from DataFrame with copy=False should still
+ # give a "shallow" copy (share data, not attributes)
+ # https://github.com/pandas-dev/pandas/issues/49523
+ orig = float_frame.copy()
+ cop = DataFrame(float_frame)
+ assert cop._mgr is not float_frame._mgr
+ # Overwriting index of copy doesn't change original
+ cop.index = np.arange(len(cop))
+ tm.assert_frame_equal(float_frame, orig)
+
+ def test_constructor_ndarray_copy(
+ self, float_frame, using_array_manager, using_copy_on_write
+ ):
+ if not using_array_manager:
+ arr = float_frame.values.copy()
+ df = DataFrame(arr)
+
+ arr[5] = 5
+ if using_copy_on_write:
+ assert not (df.values[5] == 5).all()
+ else:
+ assert (df.values[5] == 5).all()
+
+ df = DataFrame(arr, copy=True)
+ arr[6] = 6
+ assert not (df.values[6] == 6).all()
+ else:
+ arr = float_frame.values.copy()
+ # default: copy to ensure contiguous arrays
+ df = DataFrame(arr)
+ assert df._mgr.arrays[0].flags.c_contiguous
+ arr[0, 0] = 100
+ assert df.iloc[0, 0] != 100
+
+ # manually specify copy=False
+ df = DataFrame(arr, copy=False)
+ assert not df._mgr.arrays[0].flags.c_contiguous
+ arr[0, 0] = 1000
+ assert df.iloc[0, 0] == 1000
+
+ def test_constructor_series_copy(self, float_frame):
+ series = float_frame._series
+
+ df = DataFrame({"A": series["A"]}, copy=True)
+ # TODO can be replaced with `df.loc[:, "A"] = 5` after deprecation about
+ # inplace mutation is enforced
+ df.loc[df.index[0] : df.index[-1], "A"] = 5
+
+ assert not (series["A"] == 5).all()
+
+ @pytest.mark.parametrize(
+ "df",
+ [
+ DataFrame([[1, 2, 3], [4, 5, 6]], index=[1, np.nan]),
+ DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1.1, 2.2, np.nan]),
+ DataFrame([[0, 1, 2, 3], [4, 5, 6, 7]], columns=[np.nan, 1.1, 2.2, np.nan]),
+ DataFrame(
+ [[0.0, 1, 2, 3.0], [4, 5, 6, 7]], columns=[np.nan, 1.1, 2.2, np.nan]
+ ),
+ DataFrame([[0.0, 1, 2, 3.0], [4, 5, 6, 7]], columns=[np.nan, 1, 2, 2]),
+ ],
+ )
+ def test_constructor_with_nas(self, df):
+ # GH 5016
+ # na's in indices
+ # GH 21428 (non-unique columns)
+
+ for i in range(len(df.columns)):
+ df.iloc[:, i]
+
+ indexer = np.arange(len(df.columns))[isna(df.columns)]
+
+ # No NaN found -> error
+ if len(indexer) == 0:
+ with pytest.raises(KeyError, match="^nan$"):
+ df.loc[:, np.nan]
+ # single nan should result in Series
+ elif len(indexer) == 1:
+ tm.assert_series_equal(df.iloc[:, indexer[0]], df.loc[:, np.nan])
+ # multiple nans should result in DataFrame
+ else:
+ tm.assert_frame_equal(df.iloc[:, indexer], df.loc[:, np.nan])
+
+ def test_constructor_lists_to_object_dtype(self):
+ # from #1074
+ d = DataFrame({"a": [np.nan, False]})
+ assert d["a"].dtype == np.object_
+ assert not d["a"][1]
+
+ def test_constructor_ndarray_categorical_dtype(self):
+ cat = Categorical(["A", "B", "C"])
+ arr = np.array(cat).reshape(-1, 1)
+ arr = np.broadcast_to(arr, (3, 4))
+
+ result = DataFrame(arr, dtype=cat.dtype)
+
+ expected = DataFrame({0: cat, 1: cat, 2: cat, 3: cat})
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_categorical(self):
+ # GH8626
+
+ # dict creation
+ df = DataFrame({"A": list("abc")}, dtype="category")
+ expected = Series(list("abc"), dtype="category", name="A")
+ tm.assert_series_equal(df["A"], expected)
+
+ # to_frame
+ s = Series(list("abc"), dtype="category")
+ result = s.to_frame()
+ expected = Series(list("abc"), dtype="category", name=0)
+ tm.assert_series_equal(result[0], expected)
+ result = s.to_frame(name="foo")
+ expected = Series(list("abc"), dtype="category", name="foo")
+ tm.assert_series_equal(result["foo"], expected)
+
+ # list-like creation
+ df = DataFrame(list("abc"), dtype="category")
+ expected = Series(list("abc"), dtype="category", name=0)
+ tm.assert_series_equal(df[0], expected)
+
+ def test_construct_from_1item_list_of_categorical(self):
+ # pre-2.0 this behaved as DataFrame({0: cat}), in 2.0 we remove
+ # Categorical special case
+ # ndim != 1
+ cat = Categorical(list("abc"))
+ df = DataFrame([cat])
+ expected = DataFrame([cat.astype(object)])
+ tm.assert_frame_equal(df, expected)
+
+ def test_construct_from_list_of_categoricals(self):
+ # pre-2.0 this behaved as DataFrame({0: cat}), in 2.0 we remove
+ # Categorical special case
+
+ df = DataFrame([Categorical(list("abc")), Categorical(list("abd"))])
+ expected = DataFrame([["a", "b", "c"], ["a", "b", "d"]])
+ tm.assert_frame_equal(df, expected)
+
+ def test_from_nested_listlike_mixed_types(self):
+ # pre-2.0 this behaved as DataFrame({0: cat}), in 2.0 we remove
+ # Categorical special case
+ # mixed
+ df = DataFrame([Categorical(list("abc")), list("def")])
+ expected = DataFrame([["a", "b", "c"], ["d", "e", "f"]])
+ tm.assert_frame_equal(df, expected)
+
+ def test_construct_from_listlikes_mismatched_lengths(self):
+ df = DataFrame([Categorical(list("abc")), Categorical(list("abdefg"))])
+ expected = DataFrame([list("abc"), list("abdefg")])
+ tm.assert_frame_equal(df, expected)
+
+ def test_constructor_categorical_series(self):
+ items = [1, 2, 3, 1]
+ exp = Series(items).astype("category")
+ res = Series(items, dtype="category")
+ tm.assert_series_equal(res, exp)
+
+ items = ["a", "b", "c", "a"]
+ exp = Series(items).astype("category")
+ res = Series(items, dtype="category")
+ tm.assert_series_equal(res, exp)
+
+ # insert into frame with different index
+ # GH 8076
+ index = date_range("20000101", periods=3)
+ expected = Series(
+ Categorical(values=[np.nan, np.nan, np.nan], categories=["a", "b", "c"])
+ )
+ expected.index = index
+
+ expected = DataFrame({"x": expected})
+ df = DataFrame({"x": Series(["a", "b", "c"], dtype="category")}, index=index)
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize(
+ "dtype",
+ tm.ALL_NUMERIC_DTYPES
+ + tm.DATETIME64_DTYPES
+ + tm.TIMEDELTA64_DTYPES
+ + tm.BOOL_DTYPES,
+ )
+ def test_check_dtype_empty_numeric_column(self, dtype):
+ # GH24386: Ensure dtypes are set correctly for an empty DataFrame.
+ # Empty DataFrame is generated via dictionary data with non-overlapping columns.
+ data = DataFrame({"a": [1, 2]}, columns=["b"], dtype=dtype)
+
+ assert data.b.dtype == dtype
+
+ @pytest.mark.parametrize(
+ "dtype", tm.STRING_DTYPES + tm.BYTES_DTYPES + tm.OBJECT_DTYPES
+ )
+ def test_check_dtype_empty_string_column(self, request, dtype, using_array_manager):
+ # GH24386: Ensure dtypes are set correctly for an empty DataFrame.
+ # Empty DataFrame is generated via dictionary data with non-overlapping columns.
+ data = DataFrame({"a": [1, 2]}, columns=["b"], dtype=dtype)
+
+ if using_array_manager and dtype in tm.BYTES_DTYPES:
+ # TODO(ArrayManager) astype to bytes dtypes does not yet give object dtype
+ td.mark_array_manager_not_yet_implemented(request)
+
+ assert data.b.dtype.name == "object"
+
+ def test_to_frame_with_falsey_names(self):
+ # GH 16114
+ result = Series(name=0, dtype=object).to_frame().dtypes
+ expected = Series({0: object})
+ tm.assert_series_equal(result, expected)
+
+ result = DataFrame(Series(name=0, dtype=object)).dtypes
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.arm_slow
+ @pytest.mark.parametrize("dtype", [None, "uint8", "category"])
+ def test_constructor_range_dtype(self, dtype):
+ expected = DataFrame({"A": [0, 1, 2, 3, 4]}, dtype=dtype or "int64")
+
+ # GH 26342
+ result = DataFrame(range(5), columns=["A"], dtype=dtype)
+ tm.assert_frame_equal(result, expected)
+
+ # GH 16804
+ result = DataFrame({"A": range(5)}, dtype=dtype)
+ tm.assert_frame_equal(result, expected)
+
+ def test_frame_from_list_subclass(self):
+ # GH21226
+ class List(list):
+ pass
+
+ expected = DataFrame([[1, 2, 3], [4, 5, 6]])
+ result = DataFrame(List([List([1, 2, 3]), List([4, 5, 6])]))
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "extension_arr",
+ [
+ Categorical(list("aabbc")),
+ SparseArray([1, np.nan, np.nan, np.nan]),
+ IntervalArray([Interval(0, 1), Interval(1, 5)]),
+ PeriodArray(pd.period_range(start="1/1/2017", end="1/1/2018", freq="M")),
+ ],
+ )
+ def test_constructor_with_extension_array(self, extension_arr):
+ # GH11363
+ expected = DataFrame(Series(extension_arr))
+ result = DataFrame(extension_arr)
+ tm.assert_frame_equal(result, expected)
+
+ def test_datetime_date_tuple_columns_from_dict(self):
+ # GH 10863
+ v = date.today()
+ tup = v, v
+ result = DataFrame({tup: Series(range(3), index=range(3))}, columns=[tup])
+ expected = DataFrame([0, 1, 2], columns=Index(Series([tup])))
+ tm.assert_frame_equal(result, expected)
+
+ def test_construct_with_two_categoricalindex_series(self):
+ # GH 14600
+ s1 = Series([39, 6, 4], index=CategoricalIndex(["female", "male", "unknown"]))
+ s2 = Series(
+ [2, 152, 2, 242, 150],
+ index=CategoricalIndex(["f", "female", "m", "male", "unknown"]),
+ )
+ result = DataFrame([s1, s2])
+ expected = DataFrame(
+ np.array([[39, 6, 4, np.nan, np.nan], [152.0, 242.0, 150.0, 2.0, 2.0]]),
+ columns=["female", "male", "unknown", "f", "m"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_series_nonexact_categoricalindex(self):
+ # GH 42424
+ ser = Series(range(0, 100))
+ ser1 = cut(ser, 10).value_counts().head(5)
+ ser2 = cut(ser, 10).value_counts().tail(5)
+ result = DataFrame({"1": ser1, "2": ser2})
+ index = CategoricalIndex(
+ [
+ Interval(-0.099, 9.9, closed="right"),
+ Interval(9.9, 19.8, closed="right"),
+ Interval(19.8, 29.7, closed="right"),
+ Interval(29.7, 39.6, closed="right"),
+ Interval(39.6, 49.5, closed="right"),
+ Interval(49.5, 59.4, closed="right"),
+ Interval(59.4, 69.3, closed="right"),
+ Interval(69.3, 79.2, closed="right"),
+ Interval(79.2, 89.1, closed="right"),
+ Interval(89.1, 99, closed="right"),
+ ],
+ ordered=True,
+ )
+ expected = DataFrame(
+ {"1": [10] * 5 + [np.nan] * 5, "2": [np.nan] * 5 + [10] * 5}, index=index
+ )
+ tm.assert_frame_equal(expected, result)
+
+ def test_from_M8_structured(self):
+ dates = [(datetime(2012, 9, 9, 0, 0), datetime(2012, 9, 8, 15, 10))]
+ arr = np.array(dates, dtype=[("Date", "M8[us]"), ("Forecasting", "M8[us]")])
+ df = DataFrame(arr)
+
+ assert df["Date"][0] == dates[0][0]
+ assert df["Forecasting"][0] == dates[0][1]
+
+ s = Series(arr["Date"])
+ assert isinstance(s[0], Timestamp)
+ assert s[0] == dates[0][0]
+
+ def test_from_datetime_subclass(self):
+ # GH21142 Verify whether Datetime subclasses are also of dtype datetime
+ class DatetimeSubclass(datetime):
+ pass
+
+ data = DataFrame({"datetime": [DatetimeSubclass(2020, 1, 1, 1, 1)]})
+ assert data.datetime.dtype == "datetime64[ns]"
+
+ def test_with_mismatched_index_length_raises(self):
+ # GH#33437
+ dti = date_range("2016-01-01", periods=3, tz="US/Pacific")
+ msg = "Shape of passed values|Passed arrays should have the same length"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(dti, index=range(4))
+
+ def test_frame_ctor_datetime64_column(self):
+ rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s")
+ dates = np.asarray(rng)
+
+ df = DataFrame(
+ {"A": np.random.default_rng(2).standard_normal(len(rng)), "B": dates}
+ )
+ assert np.issubdtype(df["B"].dtype, np.dtype("M8[ns]"))
+
+ def test_dataframe_constructor_infer_multiindex(self):
+ index_lists = [["a", "a", "b", "b"], ["x", "y", "x", "y"]]
+
+ multi = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=[np.array(x) for x in index_lists],
+ )
+ assert isinstance(multi.index, MultiIndex)
+ assert not isinstance(multi.columns, MultiIndex)
+
+ multi = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)), columns=index_lists
+ )
+ assert isinstance(multi.columns, MultiIndex)
+
+ @pytest.mark.parametrize(
+ "input_vals",
+ [
+ ([1, 2]),
+ (["1", "2"]),
+ (list(date_range("1/1/2011", periods=2, freq="H"))),
+ (list(date_range("1/1/2011", periods=2, freq="H", tz="US/Eastern"))),
+ ([Interval(left=0, right=5)]),
+ ],
+ )
+ def test_constructor_list_str(self, input_vals, string_dtype):
+ # GH#16605
+ # Ensure that data elements are converted to strings when
+ # dtype is str, 'str', or 'U'
+
+ result = DataFrame({"A": input_vals}, dtype=string_dtype)
+ expected = DataFrame({"A": input_vals}).astype({"A": string_dtype})
+ tm.assert_frame_equal(result, expected)
+
+ def test_constructor_list_str_na(self, string_dtype):
+ result = DataFrame({"A": [1.0, 2.0, None]}, dtype=string_dtype)
+ expected = DataFrame({"A": ["1.0", "2.0", None]}, dtype=object)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("copy", [False, True])
+ def test_dict_nocopy(
+ self,
+ request,
+ copy,
+ any_numeric_ea_dtype,
+ any_numpy_dtype,
+ using_array_manager,
+ using_copy_on_write,
+ ):
+ if (
+ using_array_manager
+ and not copy
+ and any_numpy_dtype not in tm.STRING_DTYPES + tm.BYTES_DTYPES
+ ):
+ # TODO(ArrayManager) properly honor copy keyword for dict input
+ td.mark_array_manager_not_yet_implemented(request)
+
+ a = np.array([1, 2], dtype=any_numpy_dtype)
+ b = np.array([3, 4], dtype=any_numpy_dtype)
+ if b.dtype.kind in ["S", "U"]:
+ # These get cast, making the checks below more cumbersome
+ pytest.skip(f"{b.dtype} get cast, making the checks below more cumbersome")
+
+ c = pd.array([1, 2], dtype=any_numeric_ea_dtype)
+ c_orig = c.copy()
+ df = DataFrame({"a": a, "b": b, "c": c}, copy=copy)
+
+ def get_base(obj):
+ if isinstance(obj, np.ndarray):
+ return obj.base
+ elif isinstance(obj.dtype, np.dtype):
+ # i.e. DatetimeArray, TimedeltaArray
+ return obj._ndarray.base
+ else:
+ raise TypeError
+
+ def check_views(c_only: bool = False):
+ # written to work for either BlockManager or ArrayManager
+
+ # Check that the underlying data behind df["c"] is still `c`
+ # after setting with iloc. Since we don't know which entry in
+ # df._mgr.arrays corresponds to df["c"], we just check that exactly
+ # one of these arrays is `c`. GH#38939
+ assert sum(x is c for x in df._mgr.arrays) == 1
+ if c_only:
+ # If we ever stop consolidating in setitem_with_indexer,
+ # this will become unnecessary.
+ return
+
+ assert (
+ sum(
+ get_base(x) is a
+ for x in df._mgr.arrays
+ if isinstance(x.dtype, np.dtype)
+ )
+ == 1
+ )
+ assert (
+ sum(
+ get_base(x) is b
+ for x in df._mgr.arrays
+ if isinstance(x.dtype, np.dtype)
+ )
+ == 1
+ )
+
+ if not copy:
+ # constructor preserves views
+ check_views()
+
+ # TODO: most of the rest of this test belongs in indexing tests
+ if lib.is_np_dtype(df.dtypes.iloc[0], "fciuO"):
+ warn = None
+ else:
+ warn = FutureWarning
+ with tm.assert_produces_warning(warn, match="incompatible dtype"):
+ df.iloc[0, 0] = 0
+ df.iloc[0, 1] = 0
+ if not copy:
+ check_views(True)
+
+ # FIXME(GH#35417): until GH#35417, iloc.setitem into EA values does not preserve
+ # view, so we have to check in the other direction
+ df.iloc[:, 2] = pd.array([45, 46], dtype=c.dtype)
+ assert df.dtypes.iloc[2] == c.dtype
+ if not copy and not using_copy_on_write:
+ check_views(True)
+
+ if copy:
+ if a.dtype.kind == "M":
+ assert a[0] == a.dtype.type(1, "ns")
+ assert b[0] == b.dtype.type(3, "ns")
+ else:
+ assert a[0] == a.dtype.type(1)
+ assert b[0] == b.dtype.type(3)
+ # FIXME(GH#35417): enable after GH#35417
+ assert c[0] == c_orig[0] # i.e. df.iloc[0, 2]=45 did *not* update c
+ elif not using_copy_on_write:
+ # TODO: we can call check_views if we stop consolidating
+ # in setitem_with_indexer
+ assert c[0] == 45 # i.e. df.iloc[0, 2]=45 *did* update c
+ # TODO: we can check b[0] == 0 if we stop consolidating in
+ # setitem_with_indexer (except for datetimelike?)
+
+ def test_construct_from_dict_ea_series(self):
+ # GH#53744 - default of copy=True should also apply for Series with
+ # extension dtype
+ ser = Series([1, 2, 3], dtype="Int64")
+ df = DataFrame({"a": ser})
+ assert not np.shares_memory(ser.values._data, df["a"].values._data)
+
+ def test_from_series_with_name_with_columns(self):
+ # GH 7893
+ result = DataFrame(Series(1, name="foo"), columns=["bar"])
+ expected = DataFrame(columns=["bar"])
+ tm.assert_frame_equal(result, expected)
+
+ def test_nested_list_columns(self):
+ # GH 14467
+ result = DataFrame(
+ [[1, 2, 3], [4, 5, 6]], columns=[["A", "A", "A"], ["a", "b", "c"]]
+ )
+ expected = DataFrame(
+ [[1, 2, 3], [4, 5, 6]],
+ columns=MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("A", "c")]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_from_2d_object_array_of_periods_or_intervals(self):
+ # Period analogue to GH#26825
+ pi = pd.period_range("2016-04-05", periods=3)
+ data = pi._data.astype(object).reshape(1, -1)
+ df = DataFrame(data)
+ assert df.shape == (1, 3)
+ assert (df.dtypes == pi.dtype).all()
+ assert (df == pi).all().all()
+
+ ii = pd.IntervalIndex.from_breaks([3, 4, 5, 6])
+ data2 = ii._data.astype(object).reshape(1, -1)
+ df2 = DataFrame(data2)
+ assert df2.shape == (1, 3)
+ assert (df2.dtypes == ii.dtype).all()
+ assert (df2 == ii).all().all()
+
+ # mixed
+ data3 = np.r_[data, data2, data, data2].T
+ df3 = DataFrame(data3)
+ expected = DataFrame({0: pi, 1: ii, 2: pi, 3: ii})
+ tm.assert_frame_equal(df3, expected)
+
+ @pytest.mark.parametrize(
+ "col_a, col_b",
+ [
+ ([[1], [2]], np.array([[1], [2]])),
+ (np.array([[1], [2]]), [[1], [2]]),
+ (np.array([[1], [2]]), np.array([[1], [2]])),
+ ],
+ )
+ def test_error_from_2darray(self, col_a, col_b):
+ msg = "Per-column arrays must each be 1-dimensional"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame({"a": col_a, "b": col_b})
+
+ def test_from_dict_with_missing_copy_false(self):
+ # GH#45369 filled columns should not be views of one another
+ df = DataFrame(index=[1, 2, 3], columns=["a", "b", "c"], copy=False)
+ assert not np.shares_memory(df["a"]._values, df["b"]._values)
+
+ df.iloc[0, 0] = 0
+ expected = DataFrame(
+ {
+ "a": [0, np.nan, np.nan],
+ "b": [np.nan, np.nan, np.nan],
+ "c": [np.nan, np.nan, np.nan],
+ },
+ index=[1, 2, 3],
+ dtype=object,
+ )
+ tm.assert_frame_equal(df, expected)
+
+ def test_construction_empty_array_multi_column_raises(self):
+ # GH#46822
+ msg = r"Shape of passed values is \(0, 1\), indices imply \(0, 2\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(data=np.array([]), columns=["a", "b"])
+
+ def test_construct_with_strings_and_none(self):
+ # GH#32218
+ df = DataFrame(["1", "2", None], columns=["a"], dtype="str")
+ expected = DataFrame({"a": ["1", "2", None]}, dtype="str")
+ tm.assert_frame_equal(df, expected)
+
+ def test_frame_string_inference(self):
+ # GH#54430
+ pytest.importorskip("pyarrow")
+ dtype = "string[pyarrow_numpy]"
+ expected = DataFrame(
+ {"a": ["a", "b"]}, dtype=dtype, columns=Index(["a"], dtype=dtype)
+ )
+ with pd.option_context("future.infer_string", True):
+ df = DataFrame({"a": ["a", "b"]})
+ tm.assert_frame_equal(df, expected)
+
+ expected = DataFrame(
+ {"a": ["a", "b"]},
+ dtype=dtype,
+ columns=Index(["a"], dtype=dtype),
+ index=Index(["x", "y"], dtype=dtype),
+ )
+ with pd.option_context("future.infer_string", True):
+ df = DataFrame({"a": ["a", "b"]}, index=["x", "y"])
+ tm.assert_frame_equal(df, expected)
+
+ expected = DataFrame(
+ {"a": ["a", 1]}, dtype="object", columns=Index(["a"], dtype=dtype)
+ )
+ with pd.option_context("future.infer_string", True):
+ df = DataFrame({"a": ["a", 1]})
+ tm.assert_frame_equal(df, expected)
+
+ expected = DataFrame(
+ {"a": ["a", "b"]}, dtype="object", columns=Index(["a"], dtype=dtype)
+ )
+ with pd.option_context("future.infer_string", True):
+ df = DataFrame({"a": ["a", "b"]}, dtype="object")
+ tm.assert_frame_equal(df, expected)
+
+ def test_frame_string_inference_array_string_dtype(self):
+ # GH#54496
+ pytest.importorskip("pyarrow")
+ dtype = "string[pyarrow_numpy]"
+ expected = DataFrame(
+ {"a": ["a", "b"]}, dtype=dtype, columns=Index(["a"], dtype=dtype)
+ )
+ with pd.option_context("future.infer_string", True):
+ df = DataFrame({"a": np.array(["a", "b"])})
+ tm.assert_frame_equal(df, expected)
+
+ expected = DataFrame({0: ["a", "b"], 1: ["c", "d"]}, dtype=dtype)
+ with pd.option_context("future.infer_string", True):
+ df = DataFrame(np.array([["a", "c"], ["b", "d"]]))
+ tm.assert_frame_equal(df, expected)
+
+ expected = DataFrame(
+ {"a": ["a", "b"], "b": ["c", "d"]},
+ dtype=dtype,
+ columns=Index(["a", "b"], dtype=dtype),
+ )
+ with pd.option_context("future.infer_string", True):
+ df = DataFrame(np.array([["a", "c"], ["b", "d"]]), columns=["a", "b"])
+ tm.assert_frame_equal(df, expected)
+
+ def test_frame_string_inference_block_dim(self):
+ # GH#55363
+ pytest.importorskip("pyarrow")
+ with pd.option_context("future.infer_string", True):
+ df = DataFrame(np.array([["hello", "goodbye"], ["hello", "Hello"]]))
+ assert df._mgr.blocks[0].ndim == 2
+
+
+class TestDataFrameConstructorIndexInference:
+ def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self):
+ rng1 = pd.period_range("1/1/1999", "1/1/2012", freq="M")
+ s1 = Series(np.random.default_rng(2).standard_normal(len(rng1)), rng1)
+
+ rng2 = pd.period_range("1/1/1980", "12/1/2001", freq="M")
+ s2 = Series(np.random.default_rng(2).standard_normal(len(rng2)), rng2)
+ df = DataFrame({"s1": s1, "s2": s2})
+
+ exp = pd.period_range("1/1/1980", "1/1/2012", freq="M")
+ tm.assert_index_equal(df.index, exp)
+
+ def test_frame_from_dict_with_mixed_tzaware_indexes(self):
+ # GH#44091
+ dti = date_range("2016-01-01", periods=3)
+
+ ser1 = Series(range(3), index=dti)
+ ser2 = Series(range(3), index=dti.tz_localize("UTC"))
+ ser3 = Series(range(3), index=dti.tz_localize("US/Central"))
+ ser4 = Series(range(3))
+
+ # no tz-naive, but we do have mixed tzs and a non-DTI
+ df1 = DataFrame({"A": ser2, "B": ser3, "C": ser4})
+ exp_index = Index(
+ list(ser2.index) + list(ser3.index) + list(ser4.index), dtype=object
+ )
+ tm.assert_index_equal(df1.index, exp_index)
+
+ df2 = DataFrame({"A": ser2, "C": ser4, "B": ser3})
+ exp_index3 = Index(
+ list(ser2.index) + list(ser4.index) + list(ser3.index), dtype=object
+ )
+ tm.assert_index_equal(df2.index, exp_index3)
+
+ df3 = DataFrame({"B": ser3, "A": ser2, "C": ser4})
+ exp_index3 = Index(
+ list(ser3.index) + list(ser2.index) + list(ser4.index), dtype=object
+ )
+ tm.assert_index_equal(df3.index, exp_index3)
+
+ df4 = DataFrame({"C": ser4, "B": ser3, "A": ser2})
+ exp_index4 = Index(
+ list(ser4.index) + list(ser3.index) + list(ser2.index), dtype=object
+ )
+ tm.assert_index_equal(df4.index, exp_index4)
+
+ # TODO: not clear if these raising is desired (no extant tests),
+ # but this is de facto behavior 2021-12-22
+ msg = "Cannot join tz-naive with tz-aware DatetimeIndex"
+ with pytest.raises(TypeError, match=msg):
+ DataFrame({"A": ser2, "B": ser3, "C": ser4, "D": ser1})
+ with pytest.raises(TypeError, match=msg):
+ DataFrame({"A": ser2, "B": ser3, "D": ser1})
+ with pytest.raises(TypeError, match=msg):
+ DataFrame({"D": ser1, "A": ser2, "B": ser3})
+
+ @pytest.mark.parametrize(
+ "key_val, col_vals, col_type",
+ [
+ ["3", ["3", "4"], "utf8"],
+ [3, [3, 4], "int8"],
+ ],
+ )
+ def test_dict_data_arrow_column_expansion(self, key_val, col_vals, col_type):
+ # GH 53617
+ pa = pytest.importorskip("pyarrow")
+ cols = pd.arrays.ArrowExtensionArray(
+ pa.array(col_vals, type=pa.dictionary(pa.int8(), getattr(pa, col_type)()))
+ )
+ result = DataFrame({key_val: [1, 2]}, columns=cols)
+ expected = DataFrame([[1, np.nan], [2, np.nan]], columns=cols)
+ expected.iloc[:, 1] = expected.iloc[:, 1].astype(object)
+ tm.assert_frame_equal(result, expected)
+
+
+class TestDataFrameConstructorWithDtypeCoercion:
+ def test_floating_values_integer_dtype(self):
+ # GH#40110 make DataFrame behavior with arraylike floating data and
+ # inty dtype match Series behavior
+
+ arr = np.random.default_rng(2).standard_normal((10, 5))
+
+ # GH#49599 in 2.0 we raise instead of either
+ # a) silently ignoring dtype and returningfloat (the old Series behavior) or
+ # b) rounding (the old DataFrame behavior)
+ msg = "Trying to coerce float values to integers"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(arr, dtype="i8")
+
+ df = DataFrame(arr.round(), dtype="i8")
+ assert (df.dtypes == "i8").all()
+
+ # with NaNs, we go through a different path with a different warning
+ arr[0, 0] = np.nan
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
+ with pytest.raises(IntCastingNaNError, match=msg):
+ DataFrame(arr, dtype="i8")
+ with pytest.raises(IntCastingNaNError, match=msg):
+ Series(arr[0], dtype="i8")
+ # The future (raising) behavior matches what we would get via astype:
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
+ with pytest.raises(IntCastingNaNError, match=msg):
+ DataFrame(arr).astype("i8")
+ with pytest.raises(IntCastingNaNError, match=msg):
+ Series(arr[0]).astype("i8")
+
+
+class TestDataFrameConstructorWithDatetimeTZ:
+ @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"])
+ def test_construction_preserves_tzaware_dtypes(self, tz):
+ # after GH#7822
+ # these retain the timezones on dict construction
+ dr = date_range("2011/1/1", "2012/1/1", freq="W-FRI")
+ dr_tz = dr.tz_localize(tz)
+ df = DataFrame({"A": "foo", "B": dr_tz}, index=dr)
+ tz_expected = DatetimeTZDtype("ns", dr_tz.tzinfo)
+ assert df["B"].dtype == tz_expected
+
+ # GH#2810 (with timezones)
+ datetimes_naive = [ts.to_pydatetime() for ts in dr]
+ datetimes_with_tz = [ts.to_pydatetime() for ts in dr_tz]
+ df = DataFrame({"dr": dr})
+ df["dr_tz"] = dr_tz
+ df["datetimes_naive"] = datetimes_naive
+ df["datetimes_with_tz"] = datetimes_with_tz
+ result = df.dtypes
+ expected = Series(
+ [
+ np.dtype("datetime64[ns]"),
+ DatetimeTZDtype(tz=tz),
+ np.dtype("datetime64[ns]"),
+ DatetimeTZDtype(tz=tz),
+ ],
+ index=["dr", "dr_tz", "datetimes_naive", "datetimes_with_tz"],
+ )
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("pydt", [True, False])
+ def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture, pydt):
+ # GH#25843, GH#41555, GH#33401
+ tz = tz_aware_fixture
+ ts = Timestamp("2019", tz=tz)
+ if pydt:
+ ts = ts.to_pydatetime()
+
+ msg = (
+ "Cannot convert timezone-aware data to timezone-naive dtype. "
+ r"Use pd.Series\(values\).dt.tz_localize\(None\) instead."
+ )
+ with pytest.raises(ValueError, match=msg):
+ DataFrame({0: [ts]}, dtype="datetime64[ns]")
+
+ msg2 = "Cannot unbox tzaware Timestamp to tznaive dtype"
+ with pytest.raises(TypeError, match=msg2):
+ DataFrame({0: ts}, index=[0], dtype="datetime64[ns]")
+
+ with pytest.raises(ValueError, match=msg):
+ DataFrame([ts], dtype="datetime64[ns]")
+
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(np.array([ts], dtype=object), dtype="datetime64[ns]")
+
+ with pytest.raises(TypeError, match=msg2):
+ DataFrame(ts, index=[0], columns=[0], dtype="datetime64[ns]")
+
+ with pytest.raises(ValueError, match=msg):
+ DataFrame([Series([ts])], dtype="datetime64[ns]")
+
+ with pytest.raises(ValueError, match=msg):
+ DataFrame([[ts]], columns=[0], dtype="datetime64[ns]")
+
+ def test_from_dict(self):
+ # 8260
+ # support datetime64 with tz
+
+ idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo")
+ dr = date_range("20130110", periods=3)
+
+ # construction
+ df = DataFrame({"A": idx, "B": dr})
+ assert df["A"].dtype, "M8[ns, US/Eastern"
+ assert df["A"].name == "A"
+ tm.assert_series_equal(df["A"], Series(idx, name="A"))
+ tm.assert_series_equal(df["B"], Series(dr, name="B"))
+
+ def test_from_index(self):
+ # from index
+ idx2 = date_range("20130101", periods=3, tz="US/Eastern", name="foo")
+ df2 = DataFrame(idx2)
+ tm.assert_series_equal(df2["foo"], Series(idx2, name="foo"))
+ df2 = DataFrame(Series(idx2))
+ tm.assert_series_equal(df2["foo"], Series(idx2, name="foo"))
+
+ idx2 = date_range("20130101", periods=3, tz="US/Eastern")
+ df2 = DataFrame(idx2)
+ tm.assert_series_equal(df2[0], Series(idx2, name=0))
+ df2 = DataFrame(Series(idx2))
+ tm.assert_series_equal(df2[0], Series(idx2, name=0))
+
+ def test_frame_dict_constructor_datetime64_1680(self):
+ dr = date_range("1/1/2012", periods=10)
+ s = Series(dr, index=dr)
+
+ # it works!
+ DataFrame({"a": "foo", "b": s}, index=dr)
+ DataFrame({"a": "foo", "b": s.values}, index=dr)
+
+ def test_frame_datetime64_mixed_index_ctor_1681(self):
+ dr = date_range("2011/1/1", "2012/1/1", freq="W-FRI")
+ ts = Series(dr)
+
+ # it works!
+ d = DataFrame({"A": "foo", "B": ts}, index=dr)
+ assert d["B"].isna().all()
+
+ def test_frame_timeseries_column(self):
+ # GH19157
+ dr = date_range(start="20130101T10:00:00", periods=3, freq="T", tz="US/Eastern")
+ result = DataFrame(dr, columns=["timestamps"])
+ expected = DataFrame(
+ {
+ "timestamps": [
+ Timestamp("20130101T10:00:00", tz="US/Eastern"),
+ Timestamp("20130101T10:01:00", tz="US/Eastern"),
+ Timestamp("20130101T10:02:00", tz="US/Eastern"),
+ ]
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_nested_dict_construction(self):
+ # GH22227
+ columns = ["Nevada", "Ohio"]
+ pop = {
+ "Nevada": {2001: 2.4, 2002: 2.9},
+ "Ohio": {2000: 1.5, 2001: 1.7, 2002: 3.6},
+ }
+ result = DataFrame(pop, index=[2001, 2002, 2003], columns=columns)
+ expected = DataFrame(
+ [(2.4, 1.7), (2.9, 3.6), (np.nan, np.nan)],
+ columns=columns,
+ index=Index([2001, 2002, 2003]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_from_tzaware_object_array(self):
+ # GH#26825 2D object array of tzaware timestamps should not raise
+ dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")
+ data = dti._data.astype(object).reshape(1, -1)
+ df = DataFrame(data)
+ assert df.shape == (1, 3)
+ assert (df.dtypes == dti.dtype).all()
+ assert (df == dti).all().all()
+
+ def test_from_tzaware_mixed_object_array(self):
+ # GH#26825
+ arr = np.array(
+ [
+ [
+ Timestamp("2013-01-01 00:00:00"),
+ Timestamp("2013-01-02 00:00:00"),
+ Timestamp("2013-01-03 00:00:00"),
+ ],
+ [
+ Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),
+ pd.NaT,
+ Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),
+ ],
+ [
+ Timestamp("2013-01-01 00:00:00+0100", tz="CET"),
+ pd.NaT,
+ Timestamp("2013-01-03 00:00:00+0100", tz="CET"),
+ ],
+ ],
+ dtype=object,
+ ).T
+ res = DataFrame(arr, columns=["A", "B", "C"])
+
+ expected_dtypes = [
+ "datetime64[ns]",
+ "datetime64[ns, US/Eastern]",
+ "datetime64[ns, CET]",
+ ]
+ assert (res.dtypes == expected_dtypes).all()
+
+ def test_from_2d_ndarray_with_dtype(self):
+ # GH#12513
+ array_dim2 = np.arange(10).reshape((5, 2))
+ df = DataFrame(array_dim2, dtype="datetime64[ns, UTC]")
+
+ expected = DataFrame(array_dim2).astype("datetime64[ns, UTC]")
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("typ", [set, frozenset])
+ def test_construction_from_set_raises(self, typ):
+ # https://github.com/pandas-dev/pandas/issues/32582
+ values = typ({1, 2, 3})
+ msg = f"'{typ.__name__}' type is unordered"
+ with pytest.raises(TypeError, match=msg):
+ DataFrame({"a": values})
+
+ with pytest.raises(TypeError, match=msg):
+ Series(values)
+
+ def test_construction_from_ndarray_datetimelike(self):
+ # ensure the underlying arrays are properly wrapped as EA when
+ # constructed from 2D ndarray
+ arr = np.arange(0, 12, dtype="datetime64[ns]").reshape(4, 3)
+ df = DataFrame(arr)
+ assert all(isinstance(arr, DatetimeArray) for arr in df._mgr.arrays)
+
+ def test_construction_from_ndarray_with_eadtype_mismatched_columns(self):
+ arr = np.random.default_rng(2).standard_normal((10, 2))
+ dtype = pd.array([2.0]).dtype
+ msg = r"len\(arrays\) must match len\(columns\)"
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(arr, columns=["foo"], dtype=dtype)
+
+ arr2 = pd.array([2.0, 3.0, 4.0])
+ with pytest.raises(ValueError, match=msg):
+ DataFrame(arr2, columns=["foo", "bar"])
+
+ def test_columns_indexes_raise_on_sets(self):
+ # GH 47215
+ data = [[1, 2, 3], [4, 5, 6]]
+ with pytest.raises(ValueError, match="index cannot be a set"):
+ DataFrame(data, index={"a", "b"})
+ with pytest.raises(ValueError, match="columns cannot be a set"):
+ DataFrame(data, columns={"a", "b", "c"})
+
+
+def get1(obj): # TODO: make a helper in tm?
+ if isinstance(obj, Series):
+ return obj.iloc[0]
+ else:
+ return obj.iloc[0, 0]
+
+
+class TestFromScalar:
+ @pytest.fixture(params=[list, dict, None])
+ def box(self, request):
+ return request.param
+
+ @pytest.fixture
+ def constructor(self, frame_or_series, box):
+ extra = {"index": range(2)}
+ if frame_or_series is DataFrame:
+ extra["columns"] = ["A"]
+
+ if box is None:
+ return functools.partial(frame_or_series, **extra)
+
+ elif box is dict:
+ if frame_or_series is Series:
+ return lambda x, **kwargs: frame_or_series(
+ {0: x, 1: x}, **extra, **kwargs
+ )
+ else:
+ return lambda x, **kwargs: frame_or_series({"A": x}, **extra, **kwargs)
+ elif frame_or_series is Series:
+ return lambda x, **kwargs: frame_or_series([x, x], **extra, **kwargs)
+ else:
+ return lambda x, **kwargs: frame_or_series({"A": [x, x]}, **extra, **kwargs)
+
+ @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
+ def test_from_nat_scalar(self, dtype, constructor):
+ obj = constructor(pd.NaT, dtype=dtype)
+ assert np.all(obj.dtypes == dtype)
+ assert np.all(obj.isna())
+
+ def test_from_timedelta_scalar_preserves_nanos(self, constructor):
+ td = Timedelta(1)
+
+ obj = constructor(td, dtype="m8[ns]")
+ assert get1(obj) == td
+
+ def test_from_timestamp_scalar_preserves_nanos(self, constructor, fixed_now_ts):
+ ts = fixed_now_ts + Timedelta(1)
+
+ obj = constructor(ts, dtype="M8[ns]")
+ assert get1(obj) == ts
+
+ def test_from_timedelta64_scalar_object(self, constructor):
+ td = Timedelta(1)
+ td64 = td.to_timedelta64()
+
+ obj = constructor(td64, dtype=object)
+ assert isinstance(get1(obj), np.timedelta64)
+
+ @pytest.mark.parametrize("cls", [np.datetime64, np.timedelta64])
+ def test_from_scalar_datetimelike_mismatched(self, constructor, cls):
+ scalar = cls("NaT", "ns")
+ dtype = {np.datetime64: "m8[ns]", np.timedelta64: "M8[ns]"}[cls]
+
+ if cls is np.datetime64:
+ msg1 = r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]"
+ else:
+ msg1 = r"dtype timedelta64\[ns\] cannot be converted to datetime64\[ns\]"
+ msg = "|".join(["Cannot cast", msg1])
+
+ with pytest.raises(TypeError, match=msg):
+ constructor(scalar, dtype=dtype)
+
+ scalar = cls(4, "ns")
+ with pytest.raises(TypeError, match=msg):
+ constructor(scalar, dtype=dtype)
+
+ @pytest.mark.parametrize("cls", [datetime, np.datetime64])
+ def test_from_out_of_bounds_ns_datetime(
+ self, constructor, cls, request, box, frame_or_series
+ ):
+ # scalar that won't fit in nanosecond dt64, but will fit in microsecond
+ if box is list or (frame_or_series is Series and box is dict):
+ mark = pytest.mark.xfail(
+ reason="Timestamp constructor has been updated to cast dt64 to "
+ "non-nano, but DatetimeArray._from_sequence has not",
+ strict=True,
+ )
+ request.node.add_marker(mark)
+
+ scalar = datetime(9999, 1, 1)
+ exp_dtype = "M8[us]" # pydatetime objects default to this reso
+
+ if cls is np.datetime64:
+ scalar = np.datetime64(scalar, "D")
+ exp_dtype = "M8[s]" # closest reso to input
+ result = constructor(scalar)
+
+ item = get1(result)
+ dtype = tm.get_dtype(result)
+
+ assert type(item) is Timestamp
+ assert item.asm8.dtype == exp_dtype
+ assert dtype == exp_dtype
+
+ def test_out_of_s_bounds_datetime64(self, constructor):
+ scalar = np.datetime64(np.iinfo(np.int64).max, "D")
+ result = constructor(scalar)
+ item = get1(result)
+ assert type(item) is np.datetime64
+ dtype = tm.get_dtype(result)
+ assert dtype == object
+
+ @pytest.mark.parametrize("cls", [timedelta, np.timedelta64])
+ def test_from_out_of_bounds_ns_timedelta(
+ self, constructor, cls, request, box, frame_or_series
+ ):
+ # scalar that won't fit in nanosecond td64, but will fit in microsecond
+ if box is list or (frame_or_series is Series and box is dict):
+ mark = pytest.mark.xfail(
+ reason="TimedeltaArray constructor has been updated to cast td64 "
+ "to non-nano, but TimedeltaArray._from_sequence has not",
+ strict=True,
+ )
+ request.node.add_marker(mark)
+
+ scalar = datetime(9999, 1, 1) - datetime(1970, 1, 1)
+ exp_dtype = "m8[us]" # smallest reso that fits
+ if cls is np.timedelta64:
+ scalar = np.timedelta64(scalar, "D")
+ exp_dtype = "m8[s]" # closest reso to input
+ result = constructor(scalar)
+
+ item = get1(result)
+ dtype = tm.get_dtype(result)
+
+ assert type(item) is Timedelta
+ assert item.asm8.dtype == exp_dtype
+ assert dtype == exp_dtype
+
+ @pytest.mark.parametrize("cls", [np.datetime64, np.timedelta64])
+ def test_out_of_s_bounds_timedelta64(self, constructor, cls):
+ scalar = cls(np.iinfo(np.int64).max, "D")
+ result = constructor(scalar)
+ item = get1(result)
+ assert type(item) is cls
+ dtype = tm.get_dtype(result)
+ assert dtype == object
+
+ def test_tzaware_data_tznaive_dtype(self, constructor, box, frame_or_series):
+ tz = "US/Eastern"
+ ts = Timestamp("2019", tz=tz)
+
+ if box is None or (frame_or_series is DataFrame and box is dict):
+ msg = "Cannot unbox tzaware Timestamp to tznaive dtype"
+ err = TypeError
+ else:
+ msg = (
+ "Cannot convert timezone-aware data to timezone-naive dtype. "
+ r"Use pd.Series\(values\).dt.tz_localize\(None\) instead."
+ )
+ err = ValueError
+
+ with pytest.raises(err, match=msg):
+ constructor(ts, dtype="M8[ns]")
+
+
+# TODO: better location for this test?
+class TestAllowNonNano:
+ # Until 2.0, we do not preserve non-nano dt64/td64 when passed as ndarray,
+ # but do preserve it when passed as DTA/TDA
+
+ @pytest.fixture(params=[True, False])
+ def as_td(self, request):
+ return request.param
+
+ @pytest.fixture
+ def arr(self, as_td):
+ values = np.arange(5).astype(np.int64).view("M8[s]")
+ if as_td:
+ values = values - values[0]
+ return TimedeltaArray._simple_new(values, dtype=values.dtype)
+ else:
+ return DatetimeArray._simple_new(values, dtype=values.dtype)
+
+ def test_index_allow_non_nano(self, arr):
+ idx = Index(arr)
+ assert idx.dtype == arr.dtype
+
+ def test_dti_tdi_allow_non_nano(self, arr, as_td):
+ if as_td:
+ idx = pd.TimedeltaIndex(arr)
+ else:
+ idx = DatetimeIndex(arr)
+ assert idx.dtype == arr.dtype
+
+ def test_series_allow_non_nano(self, arr):
+ ser = Series(arr)
+ assert ser.dtype == arr.dtype
+
+ def test_frame_allow_non_nano(self, arr):
+ df = DataFrame(arr)
+ assert df.dtypes[0] == arr.dtype
+
+ def test_frame_from_dict_allow_non_nano(self, arr):
+ df = DataFrame({0: arr})
+ assert df.dtypes[0] == arr.dtype
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_cumulative.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_cumulative.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bd9c426123159fcfcf6bf5289fd08a60dfd91b2
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_cumulative.py
@@ -0,0 +1,81 @@
+"""
+Tests for DataFrame cumulative operations
+
+See also
+--------
+tests.series.test_cumulative
+"""
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Series,
+)
+import pandas._testing as tm
+
+
+class TestDataFrameCumulativeOps:
+ # ---------------------------------------------------------------------
+ # Cumulative Operations - cumsum, cummax, ...
+
+ def test_cumulative_ops_smoke(self):
+ # it works
+ df = DataFrame({"A": np.arange(20)}, index=np.arange(20))
+ df.cummax()
+ df.cummin()
+ df.cumsum()
+
+ dm = DataFrame(np.arange(20).reshape(4, 5), index=range(4), columns=range(5))
+ # TODO(wesm): do something with this?
+ dm.cumsum()
+
+ def test_cumprod_smoke(self, datetime_frame):
+ datetime_frame.iloc[5:10, 0] = np.nan
+ datetime_frame.iloc[10:15, 1] = np.nan
+ datetime_frame.iloc[15:, 2] = np.nan
+
+ # ints
+ df = datetime_frame.fillna(0).astype(int)
+ df.cumprod(0)
+ df.cumprod(1)
+
+ # ints32
+ df = datetime_frame.fillna(0).astype(np.int32)
+ df.cumprod(0)
+ df.cumprod(1)
+
+ @pytest.mark.parametrize("method", ["cumsum", "cumprod", "cummin", "cummax"])
+ def test_cumulative_ops_match_series_apply(self, datetime_frame, method):
+ datetime_frame.iloc[5:10, 0] = np.nan
+ datetime_frame.iloc[10:15, 1] = np.nan
+ datetime_frame.iloc[15:, 2] = np.nan
+
+ # axis = 0
+ result = getattr(datetime_frame, method)()
+ expected = datetime_frame.apply(getattr(Series, method))
+ tm.assert_frame_equal(result, expected)
+
+ # axis = 1
+ result = getattr(datetime_frame, method)(axis=1)
+ expected = datetime_frame.apply(getattr(Series, method), axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ # fix issue TODO: GH ref?
+ assert np.shape(result) == np.shape(datetime_frame)
+
+ def test_cumsum_preserve_dtypes(self):
+ # GH#19296 dont incorrectly upcast to object
+ df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3.0], "C": [True, False, False]})
+
+ result = df.cumsum()
+
+ expected = DataFrame(
+ {
+ "A": Series([1, 3, 6], dtype=np.int64),
+ "B": Series([1, 3, 6], dtype=np.float64),
+ "C": df["C"].cumsum(),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_iteration.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_iteration.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bc26bff41767d4ec0b9ddc1ec403a34548f242e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_iteration.py
@@ -0,0 +1,162 @@
+import datetime
+
+import numpy as np
+
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
+
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+
+
+class TestIteration:
+ def test_keys(self, float_frame):
+ assert float_frame.keys() is float_frame.columns
+
+ def test_iteritems(self):
+ df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])
+ for k, v in df.items():
+ assert isinstance(v, DataFrame._constructor_sliced)
+
+ def test_items(self):
+ # GH#17213, GH#13918
+ cols = ["a", "b", "c"]
+ df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=cols)
+ for c, (k, v) in zip(cols, df.items()):
+ assert c == k
+ assert isinstance(v, Series)
+ assert (df[k] == v).all()
+
+ def test_items_names(self, float_string_frame):
+ for k, v in float_string_frame.items():
+ assert v.name == k
+
+ def test_iter(self, float_frame):
+ assert tm.equalContents(list(float_frame), float_frame.columns)
+
+ def test_iterrows(self, float_frame, float_string_frame):
+ for k, v in float_frame.iterrows():
+ exp = float_frame.loc[k]
+ tm.assert_series_equal(v, exp)
+
+ for k, v in float_string_frame.iterrows():
+ exp = float_string_frame.loc[k]
+ tm.assert_series_equal(v, exp)
+
+ def test_iterrows_iso8601(self):
+ # GH#19671
+ s = DataFrame(
+ {
+ "non_iso8601": ["M1701", "M1802", "M1903", "M2004"],
+ "iso8601": date_range("2000-01-01", periods=4, freq="M"),
+ }
+ )
+ for k, v in s.iterrows():
+ exp = s.loc[k]
+ tm.assert_series_equal(v, exp)
+
+ def test_iterrows_corner(self):
+ # GH#12222
+ df = DataFrame(
+ {
+ "a": [datetime.datetime(2015, 1, 1)],
+ "b": [None],
+ "c": [None],
+ "d": [""],
+ "e": [[]],
+ "f": [set()],
+ "g": [{}],
+ }
+ )
+ expected = Series(
+ [datetime.datetime(2015, 1, 1), None, None, "", [], set(), {}],
+ index=list("abcdefg"),
+ name=0,
+ dtype="object",
+ )
+ _, result = next(df.iterrows())
+ tm.assert_series_equal(result, expected)
+
+ def test_itertuples(self, float_frame):
+ for i, tup in enumerate(float_frame.itertuples()):
+ ser = DataFrame._constructor_sliced(tup[1:])
+ ser.name = tup[0]
+ expected = float_frame.iloc[i, :].reset_index(drop=True)
+ tm.assert_series_equal(ser, expected)
+
+ df = DataFrame(
+ {"floats": np.random.default_rng(2).standard_normal(5), "ints": range(5)},
+ columns=["floats", "ints"],
+ )
+
+ for tup in df.itertuples(index=False):
+ assert isinstance(tup[1], int)
+
+ df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]})
+ dfaa = df[["a", "a"]]
+
+ assert list(dfaa.itertuples()) == [(0, 1, 1), (1, 2, 2), (2, 3, 3)]
+
+ # repr with int on 32-bit/windows
+ if not (is_platform_windows() or not IS64):
+ assert (
+ repr(list(df.itertuples(name=None)))
+ == "[(0, 1, 4), (1, 2, 5), (2, 3, 6)]"
+ )
+
+ tup = next(df.itertuples(name="TestName"))
+ assert tup._fields == ("Index", "a", "b")
+ assert (tup.Index, tup.a, tup.b) == tup
+ assert type(tup).__name__ == "TestName"
+
+ df.columns = ["def", "return"]
+ tup2 = next(df.itertuples(name="TestName"))
+ assert tup2 == (0, 1, 4)
+ assert tup2._fields == ("Index", "_1", "_2")
+
+ df3 = DataFrame({"f" + str(i): [i] for i in range(1024)})
+ # will raise SyntaxError if trying to create namedtuple
+ tup3 = next(df3.itertuples())
+ assert isinstance(tup3, tuple)
+ assert hasattr(tup3, "_fields")
+
+ # GH#28282
+ df_254_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(254)}])
+ result_254_columns = next(df_254_columns.itertuples(index=False))
+ assert isinstance(result_254_columns, tuple)
+ assert hasattr(result_254_columns, "_fields")
+
+ df_255_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(255)}])
+ result_255_columns = next(df_255_columns.itertuples(index=False))
+ assert isinstance(result_255_columns, tuple)
+ assert hasattr(result_255_columns, "_fields")
+
+ def test_sequence_like_with_categorical(self):
+ # GH#7839
+ # make sure can iterate
+ df = DataFrame(
+ {"id": [1, 2, 3, 4, 5, 6], "raw_grade": ["a", "b", "b", "a", "a", "e"]}
+ )
+ df["grade"] = Categorical(df["raw_grade"])
+
+ # basic sequencing testing
+ result = list(df.grade.values)
+ expected = np.array(df.grade.values).tolist()
+ tm.assert_almost_equal(result, expected)
+
+ # iteration
+ for t in df.itertuples(index=False):
+ str(t)
+
+ for row, s in df.iterrows():
+ str(s)
+
+ for c, col in df.items():
+ str(col)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_logical_ops.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_logical_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cc3b67e7ac029d3f42256f700db7e75894c5e1a
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_logical_ops.py
@@ -0,0 +1,211 @@
+import operator
+import re
+
+import numpy as np
+import pytest
+
+from pandas import (
+ CategoricalIndex,
+ DataFrame,
+ Interval,
+ Series,
+ isnull,
+)
+import pandas._testing as tm
+
+
+class TestDataFrameLogicalOperators:
+ # &, |, ^
+
+ @pytest.mark.parametrize(
+ "left, right, op, expected",
+ [
+ (
+ [True, False, np.nan],
+ [True, False, True],
+ operator.and_,
+ [True, False, False],
+ ),
+ (
+ [True, False, True],
+ [True, False, np.nan],
+ operator.and_,
+ [True, False, False],
+ ),
+ (
+ [True, False, np.nan],
+ [True, False, True],
+ operator.or_,
+ [True, False, False],
+ ),
+ (
+ [True, False, True],
+ [True, False, np.nan],
+ operator.or_,
+ [True, False, True],
+ ),
+ ],
+ )
+ def test_logical_operators_nans(self, left, right, op, expected, frame_or_series):
+ # GH#13896
+ result = op(frame_or_series(left), frame_or_series(right))
+ expected = frame_or_series(expected)
+
+ tm.assert_equal(result, expected)
+
+ def test_logical_ops_empty_frame(self):
+ # GH#5808
+ # empty frames, non-mixed dtype
+ df = DataFrame(index=[1])
+
+ result = df & df
+ tm.assert_frame_equal(result, df)
+
+ result = df | df
+ tm.assert_frame_equal(result, df)
+
+ df2 = DataFrame(index=[1, 2])
+ result = df & df2
+ tm.assert_frame_equal(result, df2)
+
+ dfa = DataFrame(index=[1], columns=["A"])
+
+ result = dfa & dfa
+ expected = DataFrame(False, index=[1], columns=["A"])
+ tm.assert_frame_equal(result, expected)
+
+ def test_logical_ops_bool_frame(self):
+ # GH#5808
+ df1a_bool = DataFrame(True, index=[1], columns=["A"])
+
+ result = df1a_bool & df1a_bool
+ tm.assert_frame_equal(result, df1a_bool)
+
+ result = df1a_bool | df1a_bool
+ tm.assert_frame_equal(result, df1a_bool)
+
+ def test_logical_ops_int_frame(self):
+ # GH#5808
+ df1a_int = DataFrame(1, index=[1], columns=["A"])
+ df1a_bool = DataFrame(True, index=[1], columns=["A"])
+
+ result = df1a_int | df1a_bool
+ tm.assert_frame_equal(result, df1a_bool)
+
+ # Check that this matches Series behavior
+ res_ser = df1a_int["A"] | df1a_bool["A"]
+ tm.assert_series_equal(res_ser, df1a_bool["A"])
+
+ def test_logical_ops_invalid(self):
+ # GH#5808
+
+ df1 = DataFrame(1.0, index=[1], columns=["A"])
+ df2 = DataFrame(True, index=[1], columns=["A"])
+ msg = re.escape("unsupported operand type(s) for |: 'float' and 'bool'")
+ with pytest.raises(TypeError, match=msg):
+ df1 | df2
+
+ df1 = DataFrame("foo", index=[1], columns=["A"])
+ df2 = DataFrame(True, index=[1], columns=["A"])
+ msg = re.escape("unsupported operand type(s) for |: 'str' and 'bool'")
+ with pytest.raises(TypeError, match=msg):
+ df1 | df2
+
+ def test_logical_operators(self):
+ def _check_bin_op(op):
+ result = op(df1, df2)
+ expected = DataFrame(
+ op(df1.values, df2.values), index=df1.index, columns=df1.columns
+ )
+ assert result.values.dtype == np.bool_
+ tm.assert_frame_equal(result, expected)
+
+ def _check_unary_op(op):
+ result = op(df1)
+ expected = DataFrame(op(df1.values), index=df1.index, columns=df1.columns)
+ assert result.values.dtype == np.bool_
+ tm.assert_frame_equal(result, expected)
+
+ df1 = {
+ "a": {"a": True, "b": False, "c": False, "d": True, "e": True},
+ "b": {"a": False, "b": True, "c": False, "d": False, "e": False},
+ "c": {"a": False, "b": False, "c": True, "d": False, "e": False},
+ "d": {"a": True, "b": False, "c": False, "d": True, "e": True},
+ "e": {"a": True, "b": False, "c": False, "d": True, "e": True},
+ }
+
+ df2 = {
+ "a": {"a": True, "b": False, "c": True, "d": False, "e": False},
+ "b": {"a": False, "b": True, "c": False, "d": False, "e": False},
+ "c": {"a": True, "b": False, "c": True, "d": False, "e": False},
+ "d": {"a": False, "b": False, "c": False, "d": True, "e": False},
+ "e": {"a": False, "b": False, "c": False, "d": False, "e": True},
+ }
+
+ df1 = DataFrame(df1)
+ df2 = DataFrame(df2)
+
+ _check_bin_op(operator.and_)
+ _check_bin_op(operator.or_)
+ _check_bin_op(operator.xor)
+
+ _check_unary_op(operator.inv) # TODO: belongs elsewhere
+
+ def test_logical_with_nas(self):
+ d = DataFrame({"a": [np.nan, False], "b": [True, True]})
+
+ # GH4947
+ # bool comparisons should return bool
+ result = d["a"] | d["b"]
+ expected = Series([False, True])
+ tm.assert_series_equal(result, expected)
+
+ # GH4604, automatic casting here
+ result = d["a"].fillna(False) | d["b"]
+ expected = Series([True, True])
+ tm.assert_series_equal(result, expected)
+
+ msg = "The 'downcast' keyword in fillna is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = d["a"].fillna(False, downcast=False) | d["b"]
+ expected = Series([True, True])
+ tm.assert_series_equal(result, expected)
+
+ def test_logical_ops_categorical_columns(self):
+ # GH#38367
+ intervals = [Interval(1, 2), Interval(3, 4)]
+ data = DataFrame(
+ [[1, np.nan], [2, np.nan]],
+ columns=CategoricalIndex(
+ intervals, categories=intervals + [Interval(5, 6)]
+ ),
+ )
+ mask = DataFrame(
+ [[False, False], [False, False]], columns=data.columns, dtype=bool
+ )
+ result = mask | isnull(data)
+ expected = DataFrame(
+ [[False, True], [False, True]],
+ columns=CategoricalIndex(
+ intervals, categories=intervals + [Interval(5, 6)]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_int_dtype_different_index_not_bool(self):
+ # GH 52500
+ df1 = DataFrame([1, 2, 3], index=[10, 11, 23], columns=["a"])
+ df2 = DataFrame([10, 20, 30], index=[11, 10, 23], columns=["a"])
+ result = np.bitwise_xor(df1, df2)
+ expected = DataFrame([21, 8, 29], index=[10, 11, 23], columns=["a"])
+ tm.assert_frame_equal(result, expected)
+
+ result = df1 ^ df2
+ tm.assert_frame_equal(result, expected)
+
+ def test_different_dtypes_different_index_raises(self):
+ # GH 52538
+ df1 = DataFrame([1, 2], index=["a", "b"])
+ df2 = DataFrame([3, 4], index=["b", "c"])
+ with pytest.raises(TypeError, match="unsupported operand type"):
+ df1 & df2
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_nonunique_indexes.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_nonunique_indexes.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f0d5ad5488c0a069a8495942062c781b9d44606
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_nonunique_indexes.py
@@ -0,0 +1,350 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+
+
+def check(result, expected=None):
+ if expected is not None:
+ tm.assert_frame_equal(result, expected)
+ result.dtypes
+ str(result)
+
+
+class TestDataFrameNonuniqueIndexes:
+ def test_setattr_columns_vs_construct_with_columns(self):
+ # assignment
+ # GH 3687
+ arr = np.random.default_rng(2).standard_normal((3, 2))
+ idx = list(range(2))
+ df = DataFrame(arr, columns=["A", "A"])
+ df.columns = idx
+ expected = DataFrame(arr, columns=idx)
+ check(df, expected)
+
+ def test_setattr_columns_vs_construct_with_columns_datetimeindx(self):
+ idx = date_range("20130101", periods=4, freq="Q-NOV")
+ df = DataFrame(
+ [[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], columns=["a", "a", "a", "a"]
+ )
+ df.columns = idx
+ expected = DataFrame([[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], columns=idx)
+ check(df, expected)
+
+ def test_insert_with_duplicate_columns(self):
+ # insert
+ df = DataFrame(
+ [[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]],
+ columns=["foo", "bar", "foo", "hello"],
+ )
+ df["string"] = "bah"
+ expected = DataFrame(
+ [[1, 1, 1, 5, "bah"], [1, 1, 2, 5, "bah"], [2, 1, 3, 5, "bah"]],
+ columns=["foo", "bar", "foo", "hello", "string"],
+ )
+ check(df, expected)
+ with pytest.raises(ValueError, match="Length of value"):
+ df.insert(0, "AnotherColumn", range(len(df.index) - 1))
+
+ # insert same dtype
+ df["foo2"] = 3
+ expected = DataFrame(
+ [[1, 1, 1, 5, "bah", 3], [1, 1, 2, 5, "bah", 3], [2, 1, 3, 5, "bah", 3]],
+ columns=["foo", "bar", "foo", "hello", "string", "foo2"],
+ )
+ check(df, expected)
+
+ # set (non-dup)
+ df["foo2"] = 4
+ expected = DataFrame(
+ [[1, 1, 1, 5, "bah", 4], [1, 1, 2, 5, "bah", 4], [2, 1, 3, 5, "bah", 4]],
+ columns=["foo", "bar", "foo", "hello", "string", "foo2"],
+ )
+ check(df, expected)
+ df["foo2"] = 3
+
+ # delete (non dup)
+ del df["bar"]
+ expected = DataFrame(
+ [[1, 1, 5, "bah", 3], [1, 2, 5, "bah", 3], [2, 3, 5, "bah", 3]],
+ columns=["foo", "foo", "hello", "string", "foo2"],
+ )
+ check(df, expected)
+
+ # try to delete again (its not consolidated)
+ del df["hello"]
+ expected = DataFrame(
+ [[1, 1, "bah", 3], [1, 2, "bah", 3], [2, 3, "bah", 3]],
+ columns=["foo", "foo", "string", "foo2"],
+ )
+ check(df, expected)
+
+ # consolidate
+ df = df._consolidate()
+ expected = DataFrame(
+ [[1, 1, "bah", 3], [1, 2, "bah", 3], [2, 3, "bah", 3]],
+ columns=["foo", "foo", "string", "foo2"],
+ )
+ check(df, expected)
+
+ # insert
+ df.insert(2, "new_col", 5.0)
+ expected = DataFrame(
+ [[1, 1, 5.0, "bah", 3], [1, 2, 5.0, "bah", 3], [2, 3, 5.0, "bah", 3]],
+ columns=["foo", "foo", "new_col", "string", "foo2"],
+ )
+ check(df, expected)
+
+ # insert a dup
+ with pytest.raises(ValueError, match="cannot insert"):
+ df.insert(2, "new_col", 4.0)
+
+ df.insert(2, "new_col", 4.0, allow_duplicates=True)
+ expected = DataFrame(
+ [
+ [1, 1, 4.0, 5.0, "bah", 3],
+ [1, 2, 4.0, 5.0, "bah", 3],
+ [2, 3, 4.0, 5.0, "bah", 3],
+ ],
+ columns=["foo", "foo", "new_col", "new_col", "string", "foo2"],
+ )
+ check(df, expected)
+
+ # delete (dup)
+ del df["foo"]
+ expected = DataFrame(
+ [[4.0, 5.0, "bah", 3], [4.0, 5.0, "bah", 3], [4.0, 5.0, "bah", 3]],
+ columns=["new_col", "new_col", "string", "foo2"],
+ )
+ tm.assert_frame_equal(df, expected)
+
+ def test_dup_across_dtypes(self):
+ # dup across dtypes
+ df = DataFrame(
+ [[1, 1, 1.0, 5], [1, 1, 2.0, 5], [2, 1, 3.0, 5]],
+ columns=["foo", "bar", "foo", "hello"],
+ )
+ check(df)
+
+ df["foo2"] = 7.0
+ expected = DataFrame(
+ [[1, 1, 1.0, 5, 7.0], [1, 1, 2.0, 5, 7.0], [2, 1, 3.0, 5, 7.0]],
+ columns=["foo", "bar", "foo", "hello", "foo2"],
+ )
+ check(df, expected)
+
+ result = df["foo"]
+ expected = DataFrame([[1, 1.0], [1, 2.0], [2, 3.0]], columns=["foo", "foo"])
+ check(result, expected)
+
+ # multiple replacements
+ df["foo"] = "string"
+ expected = DataFrame(
+ [
+ ["string", 1, "string", 5, 7.0],
+ ["string", 1, "string", 5, 7.0],
+ ["string", 1, "string", 5, 7.0],
+ ],
+ columns=["foo", "bar", "foo", "hello", "foo2"],
+ )
+ check(df, expected)
+
+ del df["foo"]
+ expected = DataFrame(
+ [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "hello", "foo2"]
+ )
+ check(df, expected)
+
+ def test_column_dups_indexes(self):
+ # check column dups with index equal and not equal to df's index
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)),
+ index=["a", "b", "c", "d", "e"],
+ columns=["A", "B", "A"],
+ )
+ for index in [df.index, pd.Index(list("edcba"))]:
+ this_df = df.copy()
+ expected_ser = Series(index.values, index=this_df.index)
+ expected_df = DataFrame(
+ {"A": expected_ser, "B": this_df["B"]},
+ columns=["A", "B", "A"],
+ )
+ this_df["A"] = index
+ check(this_df, expected_df)
+
+ def test_changing_dtypes_with_duplicate_columns(self):
+ # multiple assignments that change dtypes
+ # the location indexer is a slice
+ # GH 6120
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=["that", "that"]
+ )
+ expected = DataFrame(1.0, index=range(5), columns=["that", "that"])
+
+ df["that"] = 1.0
+ check(df, expected)
+
+ df = DataFrame(
+ np.random.default_rng(2).random((5, 2)), columns=["that", "that"]
+ )
+ expected = DataFrame(1, index=range(5), columns=["that", "that"])
+
+ df["that"] = 1
+ check(df, expected)
+
+ def test_dup_columns_comparisons(self):
+ # equality
+ df1 = DataFrame([[1, 2], [2, np.nan], [3, 4], [4, 4]], columns=["A", "B"])
+ df2 = DataFrame([[0, 1], [2, 4], [2, np.nan], [4, 5]], columns=["A", "A"])
+
+ # not-comparing like-labelled
+ msg = (
+ r"Can only compare identically-labeled \(both index and columns\) "
+ "DataFrame objects"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df1 == df2
+
+ df1r = df1.reindex_like(df2)
+ result = df1r == df2
+ expected = DataFrame(
+ [[False, True], [True, False], [False, False], [True, False]],
+ columns=["A", "A"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_mixed_column_selection(self):
+ # mixed column selection
+ # GH 5639
+ dfbool = DataFrame(
+ {
+ "one": Series([True, True, False], index=["a", "b", "c"]),
+ "two": Series([False, False, True, False], index=["a", "b", "c", "d"]),
+ "three": Series([False, True, True, True], index=["a", "b", "c", "d"]),
+ }
+ )
+ expected = pd.concat([dfbool["one"], dfbool["three"], dfbool["one"]], axis=1)
+ result = dfbool[["one", "three", "one"]]
+ check(result, expected)
+
+ def test_multi_axis_dups(self):
+ # multi-axis dups
+ # GH 6121
+ df = DataFrame(
+ np.arange(25.0).reshape(5, 5),
+ index=["a", "b", "c", "d", "e"],
+ columns=["A", "B", "C", "D", "E"],
+ )
+ z = df[["A", "C", "A"]].copy()
+ expected = z.loc[["a", "c", "a"]]
+
+ df = DataFrame(
+ np.arange(25.0).reshape(5, 5),
+ index=["a", "b", "c", "d", "e"],
+ columns=["A", "B", "C", "D", "E"],
+ )
+ z = df[["A", "C", "A"]]
+ result = z.loc[["a", "c", "a"]]
+ check(result, expected)
+
+ def test_columns_with_dups(self):
+ # GH 3468 related
+
+ # basic
+ df = DataFrame([[1, 2]], columns=["a", "a"])
+ df.columns = ["a", "a.1"]
+ str(df)
+ expected = DataFrame([[1, 2]], columns=["a", "a.1"])
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame([[1, 2, 3]], columns=["b", "a", "a"])
+ df.columns = ["b", "a", "a.1"]
+ str(df)
+ expected = DataFrame([[1, 2, 3]], columns=["b", "a", "a.1"])
+ tm.assert_frame_equal(df, expected)
+
+ def test_columns_with_dup_index(self):
+ # with a dup index
+ df = DataFrame([[1, 2]], columns=["a", "a"])
+ df.columns = ["b", "b"]
+ str(df)
+ expected = DataFrame([[1, 2]], columns=["b", "b"])
+ tm.assert_frame_equal(df, expected)
+
+ def test_multi_dtype(self):
+ # multi-dtype
+ df = DataFrame(
+ [[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]],
+ columns=["a", "a", "b", "b", "d", "c", "c"],
+ )
+ df.columns = list("ABCDEFG")
+ str(df)
+ expected = DataFrame(
+ [[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("ABCDEFG")
+ )
+ tm.assert_frame_equal(df, expected)
+
+ def test_multi_dtype2(self):
+ df = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a", "a", "a"])
+ df.columns = ["a", "a.1", "a.2", "a.3"]
+ str(df)
+ expected = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a.1", "a.2", "a.3"])
+ tm.assert_frame_equal(df, expected)
+
+ def test_dups_across_blocks(self, using_array_manager):
+ # dups across blocks
+ df_float = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 3)), dtype="float64"
+ )
+ df_int = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 3)).astype("int64")
+ )
+ df_bool = DataFrame(True, index=df_float.index, columns=df_float.columns)
+ df_object = DataFrame("foo", index=df_float.index, columns=df_float.columns)
+ df_dt = DataFrame(
+ pd.Timestamp("20010101"), index=df_float.index, columns=df_float.columns
+ )
+ df = pd.concat([df_float, df_int, df_bool, df_object, df_dt], axis=1)
+
+ if not using_array_manager:
+ assert len(df._mgr.blknos) == len(df.columns)
+ assert len(df._mgr.blklocs) == len(df.columns)
+
+ # testing iloc
+ for i in range(len(df.columns)):
+ df.iloc[:, i]
+
+ def test_dup_columns_across_dtype(self):
+ # dup columns across dtype GH 2079/2194
+ vals = [[1, -1, 2.0], [2, -2, 3.0]]
+ rs = DataFrame(vals, columns=["A", "A", "B"])
+ xp = DataFrame(vals)
+ xp.columns = ["A", "A", "B"]
+ tm.assert_frame_equal(rs, xp)
+
+ def test_set_value_by_index(self):
+ # See gh-12344
+ warn = None
+ msg = "will attempt to set the values inplace"
+
+ df = DataFrame(np.arange(9).reshape(3, 3).T)
+ df.columns = list("AAA")
+ expected = df.iloc[:, 2]
+
+ with tm.assert_produces_warning(warn, match=msg):
+ df.iloc[:, 0] = 3
+ tm.assert_series_equal(df.iloc[:, 2], expected)
+
+ df = DataFrame(np.arange(9).reshape(3, 3).T)
+ df.columns = [2, float(2), str(2)]
+ expected = df.iloc[:, 1]
+
+ with tm.assert_produces_warning(warn, match=msg):
+ df.iloc[:, 0] = 3
+ tm.assert_series_equal(df.iloc[:, 1], expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_npfuncs.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_npfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..afb53bf2de93aa591ca9d7b99af185bc0c4083ee
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_npfuncs.py
@@ -0,0 +1,89 @@
+"""
+Tests for np.foo applied to DataFrame, not necessarily ufuncs.
+"""
+import numpy as np
+
+from pandas import (
+ Categorical,
+ DataFrame,
+)
+import pandas._testing as tm
+
+
+class TestAsArray:
+ def test_asarray_homogeneous(self):
+ df = DataFrame({"A": Categorical([1, 2]), "B": Categorical([1, 2])})
+ result = np.asarray(df)
+ # may change from object in the future
+ expected = np.array([[1, 1], [2, 2]], dtype="object")
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_np_sqrt(self, float_frame):
+ with np.errstate(all="ignore"):
+ result = np.sqrt(float_frame)
+ assert isinstance(result, type(float_frame))
+ assert result.index.is_(float_frame.index)
+ assert result.columns.is_(float_frame.columns)
+
+ tm.assert_frame_equal(result, float_frame.apply(np.sqrt))
+
+ def test_sum_deprecated_axis_behavior(self):
+ # GH#52042 deprecated behavior of df.sum(axis=None), which gets
+ # called when we do np.sum(df)
+
+ arr = np.random.default_rng(2).standard_normal((4, 3))
+ df = DataFrame(arr)
+
+ msg = "The behavior of DataFrame.sum with axis=None is deprecated"
+ with tm.assert_produces_warning(
+ FutureWarning, match=msg, check_stacklevel=False
+ ):
+ res = np.sum(df)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = df.sum(axis=None)
+ tm.assert_series_equal(res, expected)
+
+ def test_np_ravel(self):
+ # GH26247
+ arr = np.array(
+ [
+ [0.11197053, 0.44361564, -0.92589452],
+ [0.05883648, -0.00948922, -0.26469934],
+ ]
+ )
+
+ result = np.ravel([DataFrame(batch.reshape(1, 3)) for batch in arr])
+ expected = np.array(
+ [
+ 0.11197053,
+ 0.44361564,
+ -0.92589452,
+ 0.05883648,
+ -0.00948922,
+ -0.26469934,
+ ]
+ )
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.ravel(DataFrame(arr[0].reshape(1, 3), columns=["x1", "x2", "x3"]))
+ expected = np.array([0.11197053, 0.44361564, -0.92589452])
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.ravel(
+ [
+ DataFrame(batch.reshape(1, 3), columns=["x1", "x2", "x3"])
+ for batch in arr
+ ]
+ )
+ expected = np.array(
+ [
+ 0.11197053,
+ 0.44361564,
+ -0.92589452,
+ 0.05883648,
+ -0.00948922,
+ -0.26469934,
+ ]
+ )
+ tm.assert_numpy_array_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_query_eval.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_query_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..72e8236159bda32b40a549c2fa23312274315b08
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_query_eval.py
@@ -0,0 +1,1406 @@
+import operator
+
+import numpy as np
+import pytest
+
+from pandas.errors import (
+ NumExprClobberingError,
+ UndefinedVariableError,
+)
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.core.computation.check import NUMEXPR_INSTALLED
+
+
+@pytest.fixture(params=["python", "pandas"], ids=lambda x: x)
+def parser(request):
+ return request.param
+
+
+@pytest.fixture(
+ params=["python", pytest.param("numexpr", marks=td.skip_if_no_ne)], ids=lambda x: x
+)
+def engine(request):
+ return request.param
+
+
+def skip_if_no_pandas_parser(parser):
+ if parser != "pandas":
+ pytest.skip(f"cannot evaluate with parser {repr(parser)}")
+
+
+class TestCompat:
+ @pytest.fixture
+ def df(self):
+ return DataFrame({"A": [1, 2, 3]})
+
+ @pytest.fixture
+ def expected1(self, df):
+ return df[df.A > 0]
+
+ @pytest.fixture
+ def expected2(self, df):
+ return df.A + 1
+
+ def test_query_default(self, df, expected1, expected2):
+ # GH 12749
+ # this should always work, whether NUMEXPR_INSTALLED or not
+ result = df.query("A>0")
+ tm.assert_frame_equal(result, expected1)
+ result = df.eval("A+1")
+ tm.assert_series_equal(result, expected2, check_names=False)
+
+ def test_query_None(self, df, expected1, expected2):
+ result = df.query("A>0", engine=None)
+ tm.assert_frame_equal(result, expected1)
+ result = df.eval("A+1", engine=None)
+ tm.assert_series_equal(result, expected2, check_names=False)
+
+ def test_query_python(self, df, expected1, expected2):
+ result = df.query("A>0", engine="python")
+ tm.assert_frame_equal(result, expected1)
+ result = df.eval("A+1", engine="python")
+ tm.assert_series_equal(result, expected2, check_names=False)
+
+ def test_query_numexpr(self, df, expected1, expected2):
+ if NUMEXPR_INSTALLED:
+ result = df.query("A>0", engine="numexpr")
+ tm.assert_frame_equal(result, expected1)
+ result = df.eval("A+1", engine="numexpr")
+ tm.assert_series_equal(result, expected2, check_names=False)
+ else:
+ msg = (
+ r"'numexpr' is not installed or an unsupported version. "
+ r"Cannot use engine='numexpr' for query/eval if 'numexpr' is "
+ r"not installed"
+ )
+ with pytest.raises(ImportError, match=msg):
+ df.query("A>0", engine="numexpr")
+ with pytest.raises(ImportError, match=msg):
+ df.eval("A+1", engine="numexpr")
+
+
+class TestDataFrameEval:
+ # smaller hits python, larger hits numexpr
+ @pytest.mark.parametrize("n", [4, 4000])
+ @pytest.mark.parametrize(
+ "op_str,op,rop",
+ [
+ ("+", "__add__", "__radd__"),
+ ("-", "__sub__", "__rsub__"),
+ ("*", "__mul__", "__rmul__"),
+ ("/", "__truediv__", "__rtruediv__"),
+ ],
+ )
+ def test_ops(self, op_str, op, rop, n):
+ # tst ops and reversed ops in evaluation
+ # GH7198
+
+ df = DataFrame(1, index=range(n), columns=list("abcd"))
+ df.iloc[0] = 2
+ m = df.mean()
+
+ base = DataFrame( # noqa: F841
+ np.tile(m.values, n).reshape(n, -1), columns=list("abcd")
+ )
+
+ expected = eval(f"base {op_str} df")
+
+ # ops as strings
+ result = eval(f"m {op_str} df")
+ tm.assert_frame_equal(result, expected)
+
+ # these are commutative
+ if op in ["+", "*"]:
+ result = getattr(df, op)(m)
+ tm.assert_frame_equal(result, expected)
+
+ # these are not
+ elif op in ["-", "/"]:
+ result = getattr(df, rop)(m)
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_sub_numexpr_path(self):
+ # GH7192: Note we need a large number of rows to ensure this
+ # goes through the numexpr path
+ df = DataFrame({"A": np.random.default_rng(2).standard_normal(25000)})
+ df.iloc[0:5] = np.nan
+ expected = 1 - np.isnan(df.iloc[0:25])
+ result = (1 - np.isnan(df)).iloc[0:25]
+ tm.assert_frame_equal(result, expected)
+
+ def test_query_non_str(self):
+ # GH 11485
+ df = DataFrame({"A": [1, 2, 3], "B": ["a", "b", "b"]})
+
+ msg = "expr must be a string to be evaluated"
+ with pytest.raises(ValueError, match=msg):
+ df.query(lambda x: x.B == "b")
+
+ with pytest.raises(ValueError, match=msg):
+ df.query(111)
+
+ def test_query_empty_string(self):
+ # GH 13139
+ df = DataFrame({"A": [1, 2, 3]})
+
+ msg = "expr cannot be an empty string"
+ with pytest.raises(ValueError, match=msg):
+ df.query("")
+
+ def test_eval_resolvers_as_list(self):
+ # GH 14095
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)), columns=list("ab")
+ )
+ dict1 = {"a": 1}
+ dict2 = {"b": 2}
+ assert df.eval("a + b", resolvers=[dict1, dict2]) == dict1["a"] + dict2["b"]
+ assert pd.eval("a + b", resolvers=[dict1, dict2]) == dict1["a"] + dict2["b"]
+
+ def test_eval_resolvers_combined(self):
+ # GH 34966
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)), columns=list("ab")
+ )
+ dict1 = {"c": 2}
+
+ # Both input and default index/column resolvers should be usable
+ result = df.eval("a + b * c", resolvers=[dict1])
+
+ expected = df["a"] + df["b"] * dict1["c"]
+ tm.assert_series_equal(result, expected)
+
+ def test_eval_object_dtype_binop(self):
+ # GH#24883
+ df = DataFrame({"a1": ["Y", "N"]})
+ res = df.eval("c = ((a1 == 'Y') & True)")
+ expected = DataFrame({"a1": ["Y", "N"], "c": [True, False]})
+ tm.assert_frame_equal(res, expected)
+
+
+class TestDataFrameQueryWithMultiIndex:
+ def test_query_with_named_multiindex(self, parser, engine):
+ skip_if_no_pandas_parser(parser)
+ a = np.random.default_rng(2).choice(["red", "green"], size=10)
+ b = np.random.default_rng(2).choice(["eggs", "ham"], size=10)
+ index = MultiIndex.from_arrays([a, b], names=["color", "food"])
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)), index=index)
+ ind = Series(
+ df.index.get_level_values("color").values, index=index, name="color"
+ )
+
+ # equality
+ res1 = df.query('color == "red"', parser=parser, engine=engine)
+ res2 = df.query('"red" == color', parser=parser, engine=engine)
+ exp = df[ind == "red"]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # inequality
+ res1 = df.query('color != "red"', parser=parser, engine=engine)
+ res2 = df.query('"red" != color', parser=parser, engine=engine)
+ exp = df[ind != "red"]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # list equality (really just set membership)
+ res1 = df.query('color == ["red"]', parser=parser, engine=engine)
+ res2 = df.query('["red"] == color', parser=parser, engine=engine)
+ exp = df[ind.isin(["red"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ res1 = df.query('color != ["red"]', parser=parser, engine=engine)
+ res2 = df.query('["red"] != color', parser=parser, engine=engine)
+ exp = df[~ind.isin(["red"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # in/not in ops
+ res1 = df.query('["red"] in color', parser=parser, engine=engine)
+ res2 = df.query('"red" in color', parser=parser, engine=engine)
+ exp = df[ind.isin(["red"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ res1 = df.query('["red"] not in color', parser=parser, engine=engine)
+ res2 = df.query('"red" not in color', parser=parser, engine=engine)
+ exp = df[~ind.isin(["red"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ def test_query_with_unnamed_multiindex(self, parser, engine):
+ skip_if_no_pandas_parser(parser)
+ a = np.random.default_rng(2).choice(["red", "green"], size=10)
+ b = np.random.default_rng(2).choice(["eggs", "ham"], size=10)
+ index = MultiIndex.from_arrays([a, b])
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)), index=index)
+ ind = Series(df.index.get_level_values(0).values, index=index)
+
+ res1 = df.query('ilevel_0 == "red"', parser=parser, engine=engine)
+ res2 = df.query('"red" == ilevel_0', parser=parser, engine=engine)
+ exp = df[ind == "red"]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # inequality
+ res1 = df.query('ilevel_0 != "red"', parser=parser, engine=engine)
+ res2 = df.query('"red" != ilevel_0', parser=parser, engine=engine)
+ exp = df[ind != "red"]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # list equality (really just set membership)
+ res1 = df.query('ilevel_0 == ["red"]', parser=parser, engine=engine)
+ res2 = df.query('["red"] == ilevel_0', parser=parser, engine=engine)
+ exp = df[ind.isin(["red"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ res1 = df.query('ilevel_0 != ["red"]', parser=parser, engine=engine)
+ res2 = df.query('["red"] != ilevel_0', parser=parser, engine=engine)
+ exp = df[~ind.isin(["red"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # in/not in ops
+ res1 = df.query('["red"] in ilevel_0', parser=parser, engine=engine)
+ res2 = df.query('"red" in ilevel_0', parser=parser, engine=engine)
+ exp = df[ind.isin(["red"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ res1 = df.query('["red"] not in ilevel_0', parser=parser, engine=engine)
+ res2 = df.query('"red" not in ilevel_0', parser=parser, engine=engine)
+ exp = df[~ind.isin(["red"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # ## LEVEL 1
+ ind = Series(df.index.get_level_values(1).values, index=index)
+ res1 = df.query('ilevel_1 == "eggs"', parser=parser, engine=engine)
+ res2 = df.query('"eggs" == ilevel_1', parser=parser, engine=engine)
+ exp = df[ind == "eggs"]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # inequality
+ res1 = df.query('ilevel_1 != "eggs"', parser=parser, engine=engine)
+ res2 = df.query('"eggs" != ilevel_1', parser=parser, engine=engine)
+ exp = df[ind != "eggs"]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # list equality (really just set membership)
+ res1 = df.query('ilevel_1 == ["eggs"]', parser=parser, engine=engine)
+ res2 = df.query('["eggs"] == ilevel_1', parser=parser, engine=engine)
+ exp = df[ind.isin(["eggs"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ res1 = df.query('ilevel_1 != ["eggs"]', parser=parser, engine=engine)
+ res2 = df.query('["eggs"] != ilevel_1', parser=parser, engine=engine)
+ exp = df[~ind.isin(["eggs"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ # in/not in ops
+ res1 = df.query('["eggs"] in ilevel_1', parser=parser, engine=engine)
+ res2 = df.query('"eggs" in ilevel_1', parser=parser, engine=engine)
+ exp = df[ind.isin(["eggs"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ res1 = df.query('["eggs"] not in ilevel_1', parser=parser, engine=engine)
+ res2 = df.query('"eggs" not in ilevel_1', parser=parser, engine=engine)
+ exp = df[~ind.isin(["eggs"])]
+ tm.assert_frame_equal(res1, exp)
+ tm.assert_frame_equal(res2, exp)
+
+ def test_query_with_partially_named_multiindex(self, parser, engine):
+ skip_if_no_pandas_parser(parser)
+ a = np.random.default_rng(2).choice(["red", "green"], size=10)
+ b = np.arange(10)
+ index = MultiIndex.from_arrays([a, b])
+ index.names = [None, "rating"]
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)), index=index)
+ res = df.query("rating == 1", parser=parser, engine=engine)
+ ind = Series(
+ df.index.get_level_values("rating").values, index=index, name="rating"
+ )
+ exp = df[ind == 1]
+ tm.assert_frame_equal(res, exp)
+
+ res = df.query("rating != 1", parser=parser, engine=engine)
+ ind = Series(
+ df.index.get_level_values("rating").values, index=index, name="rating"
+ )
+ exp = df[ind != 1]
+ tm.assert_frame_equal(res, exp)
+
+ res = df.query('ilevel_0 == "red"', parser=parser, engine=engine)
+ ind = Series(df.index.get_level_values(0).values, index=index)
+ exp = df[ind == "red"]
+ tm.assert_frame_equal(res, exp)
+
+ res = df.query('ilevel_0 != "red"', parser=parser, engine=engine)
+ ind = Series(df.index.get_level_values(0).values, index=index)
+ exp = df[ind != "red"]
+ tm.assert_frame_equal(res, exp)
+
+ def test_query_multiindex_get_index_resolvers(self):
+ df = tm.makeCustomDataframe(
+ 10, 3, r_idx_nlevels=2, r_idx_names=["spam", "eggs"]
+ )
+ resolvers = df._get_index_resolvers()
+
+ def to_series(mi, level):
+ level_values = mi.get_level_values(level)
+ s = level_values.to_series()
+ s.index = mi
+ return s
+
+ col_series = df.columns.to_series()
+ expected = {
+ "index": df.index,
+ "columns": col_series,
+ "spam": to_series(df.index, "spam"),
+ "eggs": to_series(df.index, "eggs"),
+ "C0": col_series,
+ }
+ for k, v in resolvers.items():
+ if isinstance(v, Index):
+ assert v.is_(expected[k])
+ elif isinstance(v, Series):
+ tm.assert_series_equal(v, expected[k])
+ else:
+ raise AssertionError("object must be a Series or Index")
+
+
+@td.skip_if_no_ne
+class TestDataFrameQueryNumExprPandas:
+ @pytest.fixture
+ def engine(self):
+ return "numexpr"
+
+ @pytest.fixture
+ def parser(self):
+ return "pandas"
+
+ def test_date_query_with_attribute_access(self, engine, parser):
+ skip_if_no_pandas_parser(parser)
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ df["dates1"] = date_range("1/1/2012", periods=5)
+ df["dates2"] = date_range("1/1/2013", periods=5)
+ df["dates3"] = date_range("1/1/2014", periods=5)
+ res = df.query(
+ "@df.dates1 < 20130101 < @df.dates3", engine=engine, parser=parser
+ )
+ expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_query_no_attribute_access(self, engine, parser):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ df["dates1"] = date_range("1/1/2012", periods=5)
+ df["dates2"] = date_range("1/1/2013", periods=5)
+ df["dates3"] = date_range("1/1/2014", periods=5)
+ res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser)
+ expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_query_with_NaT(self, engine, parser):
+ n = 10
+ df = DataFrame(np.random.default_rng(2).standard_normal((n, 3)))
+ df["dates1"] = date_range("1/1/2012", periods=n)
+ df["dates2"] = date_range("1/1/2013", periods=n)
+ df["dates3"] = date_range("1/1/2014", periods=n)
+ df.loc[np.random.default_rng(2).random(n) > 0.5, "dates1"] = pd.NaT
+ df.loc[np.random.default_rng(2).random(n) > 0.5, "dates3"] = pd.NaT
+ res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser)
+ expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_index_query(self, engine, parser):
+ n = 10
+ df = DataFrame(np.random.default_rng(2).standard_normal((n, 3)))
+ df["dates1"] = date_range("1/1/2012", periods=n)
+ df["dates3"] = date_range("1/1/2014", periods=n)
+ return_value = df.set_index("dates1", inplace=True, drop=True)
+ assert return_value is None
+ res = df.query("index < 20130101 < dates3", engine=engine, parser=parser)
+ expec = df[(df.index < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_index_query_with_NaT(self, engine, parser):
+ n = 10
+ # Cast to object to avoid implicit cast when setting entry to pd.NaT below
+ df = DataFrame(np.random.default_rng(2).standard_normal((n, 3))).astype(
+ {0: object}
+ )
+ df["dates1"] = date_range("1/1/2012", periods=n)
+ df["dates3"] = date_range("1/1/2014", periods=n)
+ df.iloc[0, 0] = pd.NaT
+ return_value = df.set_index("dates1", inplace=True, drop=True)
+ assert return_value is None
+ res = df.query("index < 20130101 < dates3", engine=engine, parser=parser)
+ expec = df[(df.index < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_index_query_with_NaT_duplicates(self, engine, parser):
+ n = 10
+ d = {}
+ d["dates1"] = date_range("1/1/2012", periods=n)
+ d["dates3"] = date_range("1/1/2014", periods=n)
+ df = DataFrame(d)
+ df.loc[np.random.default_rng(2).random(n) > 0.5, "dates1"] = pd.NaT
+ return_value = df.set_index("dates1", inplace=True, drop=True)
+ assert return_value is None
+ res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser)
+ expec = df[(df.index.to_series() < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_query_with_non_date(self, engine, parser):
+ n = 10
+ df = DataFrame(
+ {"dates": date_range("1/1/2012", periods=n), "nondate": np.arange(n)}
+ )
+
+ result = df.query("dates == nondate", parser=parser, engine=engine)
+ assert len(result) == 0
+
+ result = df.query("dates != nondate", parser=parser, engine=engine)
+ tm.assert_frame_equal(result, df)
+
+ msg = r"Invalid comparison between dtype=datetime64\[ns\] and ndarray"
+ for op in ["<", ">", "<=", ">="]:
+ with pytest.raises(TypeError, match=msg):
+ df.query(f"dates {op} nondate", parser=parser, engine=engine)
+
+ def test_query_syntax_error(self, engine, parser):
+ df = DataFrame({"i": range(10), "+": range(3, 13), "r": range(4, 14)})
+ msg = "invalid syntax"
+ with pytest.raises(SyntaxError, match=msg):
+ df.query("i - +", engine=engine, parser=parser)
+
+ def test_query_scope(self, engine, parser):
+ skip_if_no_pandas_parser(parser)
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((20, 2)), columns=list("ab")
+ )
+
+ a, b = 1, 2 # noqa: F841
+ res = df.query("a > b", engine=engine, parser=parser)
+ expected = df[df.a > df.b]
+ tm.assert_frame_equal(res, expected)
+
+ res = df.query("@a > b", engine=engine, parser=parser)
+ expected = df[a > df.b]
+ tm.assert_frame_equal(res, expected)
+
+ # no local variable c
+ with pytest.raises(
+ UndefinedVariableError, match="local variable 'c' is not defined"
+ ):
+ df.query("@a > b > @c", engine=engine, parser=parser)
+
+ # no column named 'c'
+ with pytest.raises(UndefinedVariableError, match="name 'c' is not defined"):
+ df.query("@a > b > c", engine=engine, parser=parser)
+
+ def test_query_doesnt_pickup_local(self, engine, parser):
+ n = m = 10
+ df = DataFrame(
+ np.random.default_rng(2).integers(m, size=(n, 3)), columns=list("abc")
+ )
+
+ # we don't pick up the local 'sin'
+ with pytest.raises(UndefinedVariableError, match="name 'sin' is not defined"):
+ df.query("sin > 5", engine=engine, parser=parser)
+
+ def test_query_builtin(self, engine, parser):
+ n = m = 10
+ df = DataFrame(
+ np.random.default_rng(2).integers(m, size=(n, 3)), columns=list("abc")
+ )
+
+ df.index.name = "sin"
+ msg = "Variables in expression.+"
+ with pytest.raises(NumExprClobberingError, match=msg):
+ df.query("sin > 5", engine=engine, parser=parser)
+
+ def test_query(self, engine, parser):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 3)), columns=["a", "b", "c"]
+ )
+
+ tm.assert_frame_equal(
+ df.query("a < b", engine=engine, parser=parser), df[df.a < df.b]
+ )
+ tm.assert_frame_equal(
+ df.query("a + b > b * c", engine=engine, parser=parser),
+ df[df.a + df.b > df.b * df.c],
+ )
+
+ def test_query_index_with_name(self, engine, parser):
+ df = DataFrame(
+ np.random.default_rng(2).integers(10, size=(10, 3)),
+ index=Index(range(10), name="blob"),
+ columns=["a", "b", "c"],
+ )
+ res = df.query("(blob < 5) & (a < b)", engine=engine, parser=parser)
+ expec = df[(df.index < 5) & (df.a < df.b)]
+ tm.assert_frame_equal(res, expec)
+
+ res = df.query("blob < b", engine=engine, parser=parser)
+ expec = df[df.index < df.b]
+
+ tm.assert_frame_equal(res, expec)
+
+ def test_query_index_without_name(self, engine, parser):
+ df = DataFrame(
+ np.random.default_rng(2).integers(10, size=(10, 3)),
+ index=range(10),
+ columns=["a", "b", "c"],
+ )
+
+ # "index" should refer to the index
+ res = df.query("index < b", engine=engine, parser=parser)
+ expec = df[df.index < df.b]
+ tm.assert_frame_equal(res, expec)
+
+ # test against a scalar
+ res = df.query("index < 5", engine=engine, parser=parser)
+ expec = df[df.index < 5]
+ tm.assert_frame_equal(res, expec)
+
+ def test_nested_scope(self, engine, parser):
+ skip_if_no_pandas_parser(parser)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ df2 = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ expected = df[(df > 0) & (df2 > 0)]
+
+ result = df.query("(@df > 0) & (@df2 > 0)", engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expected)
+
+ result = pd.eval("df[df > 0 and df2 > 0]", engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expected)
+
+ result = pd.eval(
+ "df[df > 0 and df2 > 0 and df[df > 0] > 0]", engine=engine, parser=parser
+ )
+ expected = df[(df > 0) & (df2 > 0) & (df[df > 0] > 0)]
+ tm.assert_frame_equal(result, expected)
+
+ result = pd.eval("df[(df>0) & (df2>0)]", engine=engine, parser=parser)
+ expected = df.query("(@df>0) & (@df2>0)", engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expected)
+
+ def test_nested_raises_on_local_self_reference(self, engine, parser):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+
+ # can't reference ourself b/c we're a local so @ is necessary
+ with pytest.raises(UndefinedVariableError, match="name 'df' is not defined"):
+ df.query("df > 0", engine=engine, parser=parser)
+
+ def test_local_syntax(self, engine, parser):
+ skip_if_no_pandas_parser(parser)
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((100, 10)),
+ columns=list("abcdefghij"),
+ )
+ b = 1
+ expect = df[df.a < b]
+ result = df.query("a < @b", engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expect)
+
+ expect = df[df.a < df.b]
+ result = df.query("a < b", engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expect)
+
+ def test_chained_cmp_and_in(self, engine, parser):
+ skip_if_no_pandas_parser(parser)
+ cols = list("abc")
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((100, len(cols))), columns=cols
+ )
+ res = df.query(
+ "a < b < c and a not in b not in c", engine=engine, parser=parser
+ )
+ ind = (df.a < df.b) & (df.b < df.c) & ~df.b.isin(df.a) & ~df.c.isin(df.b)
+ expec = df[ind]
+ tm.assert_frame_equal(res, expec)
+
+ def test_local_variable_with_in(self, engine, parser):
+ skip_if_no_pandas_parser(parser)
+ a = Series(np.random.default_rng(2).integers(3, size=15), name="a")
+ b = Series(np.random.default_rng(2).integers(10, size=15), name="b")
+ df = DataFrame({"a": a, "b": b})
+
+ expected = df.loc[(df.b - 1).isin(a)]
+ result = df.query("b - 1 in a", engine=engine, parser=parser)
+ tm.assert_frame_equal(expected, result)
+
+ b = Series(np.random.default_rng(2).integers(10, size=15), name="b")
+ expected = df.loc[(b - 1).isin(a)]
+ result = df.query("@b - 1 in a", engine=engine, parser=parser)
+ tm.assert_frame_equal(expected, result)
+
+ def test_at_inside_string(self, engine, parser):
+ skip_if_no_pandas_parser(parser)
+ c = 1 # noqa: F841
+ df = DataFrame({"a": ["a", "a", "b", "b", "@c", "@c"]})
+ result = df.query('a == "@c"', engine=engine, parser=parser)
+ expected = df[df.a == "@c"]
+ tm.assert_frame_equal(result, expected)
+
+ def test_query_undefined_local(self):
+ engine, parser = self.engine, self.parser
+ skip_if_no_pandas_parser(parser)
+
+ df = DataFrame(np.random.default_rng(2).random((10, 2)), columns=list("ab"))
+ with pytest.raises(
+ UndefinedVariableError, match="local variable 'c' is not defined"
+ ):
+ df.query("a == @c", engine=engine, parser=parser)
+
+ def test_index_resolvers_come_after_columns_with_the_same_name(
+ self, engine, parser
+ ):
+ n = 1 # noqa: F841
+ a = np.r_[20:101:20]
+
+ df = DataFrame(
+ {"index": a, "b": np.random.default_rng(2).standard_normal(a.size)}
+ )
+ df.index.name = "index"
+ result = df.query("index > 5", engine=engine, parser=parser)
+ expected = df[df["index"] > 5]
+ tm.assert_frame_equal(result, expected)
+
+ df = DataFrame(
+ {"index": a, "b": np.random.default_rng(2).standard_normal(a.size)}
+ )
+ result = df.query("ilevel_0 > 5", engine=engine, parser=parser)
+ expected = df.loc[df.index[df.index > 5]]
+ tm.assert_frame_equal(result, expected)
+
+ df = DataFrame({"a": a, "b": np.random.default_rng(2).standard_normal(a.size)})
+ df.index.name = "a"
+ result = df.query("a > 5", engine=engine, parser=parser)
+ expected = df[df.a > 5]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.query("index > 5", engine=engine, parser=parser)
+ expected = df.loc[df.index[df.index > 5]]
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("op, f", [["==", operator.eq], ["!=", operator.ne]])
+ def test_inf(self, op, f, engine, parser):
+ n = 10
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).random(n),
+ "b": np.random.default_rng(2).random(n),
+ }
+ )
+ df.loc[::2, 0] = np.inf
+ q = f"a {op} inf"
+ expected = df[f(df.a, np.inf)]
+ result = df.query(q, engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expected)
+
+ def test_check_tz_aware_index_query(self, tz_aware_fixture):
+ # https://github.com/pandas-dev/pandas/issues/29463
+ tz = tz_aware_fixture
+ df_index = date_range(
+ start="2019-01-01", freq="1d", periods=10, tz=tz, name="time"
+ )
+ expected = DataFrame(index=df_index)
+ df = DataFrame(index=df_index)
+ result = df.query('"2018-01-03 00:00:00+00" < time')
+ tm.assert_frame_equal(result, expected)
+
+ expected = DataFrame(df_index)
+ result = df.reset_index().query('"2018-01-03 00:00:00+00" < time')
+ tm.assert_frame_equal(result, expected)
+
+ def test_method_calls_in_query(self, engine, parser):
+ # https://github.com/pandas-dev/pandas/issues/22435
+ n = 10
+ df = DataFrame(
+ {
+ "a": 2 * np.random.default_rng(2).random(n),
+ "b": np.random.default_rng(2).random(n),
+ }
+ )
+ expected = df[df["a"].astype("int") == 0]
+ result = df.query("a.astype('int') == 0", engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expected)
+
+ df = DataFrame(
+ {
+ "a": np.where(
+ np.random.default_rng(2).random(n) < 0.5,
+ np.nan,
+ np.random.default_rng(2).standard_normal(n),
+ ),
+ "b": np.random.default_rng(2).standard_normal(n),
+ }
+ )
+ expected = df[df["a"].notnull()]
+ result = df.query("a.notnull()", engine=engine, parser=parser)
+ tm.assert_frame_equal(result, expected)
+
+
+@td.skip_if_no_ne
+class TestDataFrameQueryNumExprPython(TestDataFrameQueryNumExprPandas):
+ @pytest.fixture
+ def engine(self):
+ return "numexpr"
+
+ @pytest.fixture
+ def parser(self):
+ return "python"
+
+ def test_date_query_no_attribute_access(self, engine, parser):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ df["dates1"] = date_range("1/1/2012", periods=5)
+ df["dates2"] = date_range("1/1/2013", periods=5)
+ df["dates3"] = date_range("1/1/2014", periods=5)
+ res = df.query(
+ "(dates1 < 20130101) & (20130101 < dates3)", engine=engine, parser=parser
+ )
+ expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_query_with_NaT(self, engine, parser):
+ n = 10
+ df = DataFrame(np.random.default_rng(2).standard_normal((n, 3)))
+ df["dates1"] = date_range("1/1/2012", periods=n)
+ df["dates2"] = date_range("1/1/2013", periods=n)
+ df["dates3"] = date_range("1/1/2014", periods=n)
+ df.loc[np.random.default_rng(2).random(n) > 0.5, "dates1"] = pd.NaT
+ df.loc[np.random.default_rng(2).random(n) > 0.5, "dates3"] = pd.NaT
+ res = df.query(
+ "(dates1 < 20130101) & (20130101 < dates3)", engine=engine, parser=parser
+ )
+ expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_index_query(self, engine, parser):
+ n = 10
+ df = DataFrame(np.random.default_rng(2).standard_normal((n, 3)))
+ df["dates1"] = date_range("1/1/2012", periods=n)
+ df["dates3"] = date_range("1/1/2014", periods=n)
+ return_value = df.set_index("dates1", inplace=True, drop=True)
+ assert return_value is None
+ res = df.query(
+ "(index < 20130101) & (20130101 < dates3)", engine=engine, parser=parser
+ )
+ expec = df[(df.index < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_index_query_with_NaT(self, engine, parser):
+ n = 10
+ # Cast to object to avoid implicit cast when setting entry to pd.NaT below
+ df = DataFrame(np.random.default_rng(2).standard_normal((n, 3))).astype(
+ {0: object}
+ )
+ df["dates1"] = date_range("1/1/2012", periods=n)
+ df["dates3"] = date_range("1/1/2014", periods=n)
+ df.iloc[0, 0] = pd.NaT
+ return_value = df.set_index("dates1", inplace=True, drop=True)
+ assert return_value is None
+ res = df.query(
+ "(index < 20130101) & (20130101 < dates3)", engine=engine, parser=parser
+ )
+ expec = df[(df.index < "20130101") & ("20130101" < df.dates3)]
+ tm.assert_frame_equal(res, expec)
+
+ def test_date_index_query_with_NaT_duplicates(self, engine, parser):
+ n = 10
+ df = DataFrame(np.random.default_rng(2).standard_normal((n, 3)))
+ df["dates1"] = date_range("1/1/2012", periods=n)
+ df["dates3"] = date_range("1/1/2014", periods=n)
+ df.loc[np.random.default_rng(2).random(n) > 0.5, "dates1"] = pd.NaT
+ return_value = df.set_index("dates1", inplace=True, drop=True)
+ assert return_value is None
+ msg = r"'BoolOp' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ df.query("index < 20130101 < dates3", engine=engine, parser=parser)
+
+ def test_nested_scope(self, engine, parser):
+ # smoke test
+ x = 1 # noqa: F841
+ result = pd.eval("x + 1", engine=engine, parser=parser)
+ assert result == 2
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ df2 = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+
+ # don't have the pandas parser
+ msg = r"The '@' prefix is only supported by the pandas parser"
+ with pytest.raises(SyntaxError, match=msg):
+ df.query("(@df>0) & (@df2>0)", engine=engine, parser=parser)
+
+ with pytest.raises(UndefinedVariableError, match="name 'df' is not defined"):
+ df.query("(df>0) & (df2>0)", engine=engine, parser=parser)
+
+ expected = df[(df > 0) & (df2 > 0)]
+ result = pd.eval("df[(df > 0) & (df2 > 0)]", engine=engine, parser=parser)
+ tm.assert_frame_equal(expected, result)
+
+ expected = df[(df > 0) & (df2 > 0) & (df[df > 0] > 0)]
+ result = pd.eval(
+ "df[(df > 0) & (df2 > 0) & (df[df > 0] > 0)]", engine=engine, parser=parser
+ )
+ tm.assert_frame_equal(expected, result)
+
+ def test_query_numexpr_with_min_and_max_columns(self):
+ df = DataFrame({"min": [1, 2, 3], "max": [4, 5, 6]})
+ regex_to_match = (
+ r"Variables in expression \"\(min\) == \(1\)\" "
+ r"overlap with builtins: \('min'\)"
+ )
+ with pytest.raises(NumExprClobberingError, match=regex_to_match):
+ df.query("min == 1")
+
+ regex_to_match = (
+ r"Variables in expression \"\(max\) == \(1\)\" "
+ r"overlap with builtins: \('max'\)"
+ )
+ with pytest.raises(NumExprClobberingError, match=regex_to_match):
+ df.query("max == 1")
+
+
+class TestDataFrameQueryPythonPandas(TestDataFrameQueryNumExprPandas):
+ @pytest.fixture
+ def engine(self):
+ return "python"
+
+ @pytest.fixture
+ def parser(self):
+ return "pandas"
+
+ def test_query_builtin(self, engine, parser):
+ n = m = 10
+ df = DataFrame(
+ np.random.default_rng(2).integers(m, size=(n, 3)), columns=list("abc")
+ )
+
+ df.index.name = "sin"
+ expected = df[df.index > 5]
+ result = df.query("sin > 5", engine=engine, parser=parser)
+ tm.assert_frame_equal(expected, result)
+
+
+class TestDataFrameQueryPythonPython(TestDataFrameQueryNumExprPython):
+ @pytest.fixture
+ def engine(self):
+ return "python"
+
+ @pytest.fixture
+ def parser(self):
+ return "python"
+
+ def test_query_builtin(self, engine, parser):
+ n = m = 10
+ df = DataFrame(
+ np.random.default_rng(2).integers(m, size=(n, 3)), columns=list("abc")
+ )
+
+ df.index.name = "sin"
+ expected = df[df.index > 5]
+ result = df.query("sin > 5", engine=engine, parser=parser)
+ tm.assert_frame_equal(expected, result)
+
+
+class TestDataFrameQueryStrings:
+ def test_str_query_method(self, parser, engine):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 1)), columns=["b"])
+ df["strings"] = Series(list("aabbccddee"))
+ expect = df[df.strings == "a"]
+
+ if parser != "pandas":
+ col = "strings"
+ lst = '"a"'
+
+ lhs = [col] * 2 + [lst] * 2
+ rhs = lhs[::-1]
+
+ eq, ne = "==", "!="
+ ops = 2 * ([eq] + [ne])
+ msg = r"'(Not)?In' nodes are not implemented"
+
+ for lhs, op, rhs in zip(lhs, ops, rhs):
+ ex = f"{lhs} {op} {rhs}"
+ with pytest.raises(NotImplementedError, match=msg):
+ df.query(
+ ex,
+ engine=engine,
+ parser=parser,
+ local_dict={"strings": df.strings},
+ )
+ else:
+ res = df.query('"a" == strings', engine=engine, parser=parser)
+ tm.assert_frame_equal(res, expect)
+
+ res = df.query('strings == "a"', engine=engine, parser=parser)
+ tm.assert_frame_equal(res, expect)
+ tm.assert_frame_equal(res, df[df.strings.isin(["a"])])
+
+ expect = df[df.strings != "a"]
+ res = df.query('strings != "a"', engine=engine, parser=parser)
+ tm.assert_frame_equal(res, expect)
+
+ res = df.query('"a" != strings', engine=engine, parser=parser)
+ tm.assert_frame_equal(res, expect)
+ tm.assert_frame_equal(res, df[~df.strings.isin(["a"])])
+
+ def test_str_list_query_method(self, parser, engine):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 1)), columns=["b"])
+ df["strings"] = Series(list("aabbccddee"))
+ expect = df[df.strings.isin(["a", "b"])]
+
+ if parser != "pandas":
+ col = "strings"
+ lst = '["a", "b"]'
+
+ lhs = [col] * 2 + [lst] * 2
+ rhs = lhs[::-1]
+
+ eq, ne = "==", "!="
+ ops = 2 * ([eq] + [ne])
+ msg = r"'(Not)?In' nodes are not implemented"
+
+ for lhs, op, rhs in zip(lhs, ops, rhs):
+ ex = f"{lhs} {op} {rhs}"
+ with pytest.raises(NotImplementedError, match=msg):
+ df.query(ex, engine=engine, parser=parser)
+ else:
+ res = df.query('strings == ["a", "b"]', engine=engine, parser=parser)
+ tm.assert_frame_equal(res, expect)
+
+ res = df.query('["a", "b"] == strings', engine=engine, parser=parser)
+ tm.assert_frame_equal(res, expect)
+
+ expect = df[~df.strings.isin(["a", "b"])]
+
+ res = df.query('strings != ["a", "b"]', engine=engine, parser=parser)
+ tm.assert_frame_equal(res, expect)
+
+ res = df.query('["a", "b"] != strings', engine=engine, parser=parser)
+ tm.assert_frame_equal(res, expect)
+
+ def test_query_with_string_columns(self, parser, engine):
+ df = DataFrame(
+ {
+ "a": list("aaaabbbbcccc"),
+ "b": list("aabbccddeeff"),
+ "c": np.random.default_rng(2).integers(5, size=12),
+ "d": np.random.default_rng(2).integers(9, size=12),
+ }
+ )
+ if parser == "pandas":
+ res = df.query("a in b", parser=parser, engine=engine)
+ expec = df[df.a.isin(df.b)]
+ tm.assert_frame_equal(res, expec)
+
+ res = df.query("a in b and c < d", parser=parser, engine=engine)
+ expec = df[df.a.isin(df.b) & (df.c < df.d)]
+ tm.assert_frame_equal(res, expec)
+ else:
+ msg = r"'(Not)?In' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ df.query("a in b", parser=parser, engine=engine)
+
+ msg = r"'BoolOp' nodes are not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ df.query("a in b and c < d", parser=parser, engine=engine)
+
+ def test_object_array_eq_ne(self, parser, engine):
+ df = DataFrame(
+ {
+ "a": list("aaaabbbbcccc"),
+ "b": list("aabbccddeeff"),
+ "c": np.random.default_rng(2).integers(5, size=12),
+ "d": np.random.default_rng(2).integers(9, size=12),
+ }
+ )
+ res = df.query("a == b", parser=parser, engine=engine)
+ exp = df[df.a == df.b]
+ tm.assert_frame_equal(res, exp)
+
+ res = df.query("a != b", parser=parser, engine=engine)
+ exp = df[df.a != df.b]
+ tm.assert_frame_equal(res, exp)
+
+ def test_query_with_nested_strings(self, parser, engine):
+ skip_if_no_pandas_parser(parser)
+ events = [
+ f"page {n} {act}" for n in range(1, 4) for act in ["load", "exit"]
+ ] * 2
+ stamps1 = date_range("2014-01-01 0:00:01", freq="30s", periods=6)
+ stamps2 = date_range("2014-02-01 1:00:01", freq="30s", periods=6)
+ df = DataFrame(
+ {
+ "id": np.arange(1, 7).repeat(2),
+ "event": events,
+ "timestamp": stamps1.append(stamps2),
+ }
+ )
+
+ expected = df[df.event == '"page 1 load"']
+ res = df.query("""'"page 1 load"' in event""", parser=parser, engine=engine)
+ tm.assert_frame_equal(expected, res)
+
+ def test_query_with_nested_special_character(self, parser, engine):
+ skip_if_no_pandas_parser(parser)
+ df = DataFrame({"a": ["a", "b", "test & test"], "b": [1, 2, 3]})
+ res = df.query('a == "test & test"', parser=parser, engine=engine)
+ expec = df[df.a == "test & test"]
+ tm.assert_frame_equal(res, expec)
+
+ @pytest.mark.parametrize(
+ "op, func",
+ [
+ ["<", operator.lt],
+ [">", operator.gt],
+ ["<=", operator.le],
+ [">=", operator.ge],
+ ],
+ )
+ def test_query_lex_compare_strings(self, parser, engine, op, func):
+ a = Series(np.random.default_rng(2).choice(list("abcde"), 20))
+ b = Series(np.arange(a.size))
+ df = DataFrame({"X": a, "Y": b})
+
+ res = df.query(f'X {op} "d"', engine=engine, parser=parser)
+ expected = df[func(df.X, "d")]
+ tm.assert_frame_equal(res, expected)
+
+ def test_query_single_element_booleans(self, parser, engine):
+ columns = "bid", "bidsize", "ask", "asksize"
+ data = np.random.default_rng(2).integers(2, size=(1, len(columns))).astype(bool)
+ df = DataFrame(data, columns=columns)
+ res = df.query("bid & ask", engine=engine, parser=parser)
+ expected = df[df.bid & df.ask]
+ tm.assert_frame_equal(res, expected)
+
+ def test_query_string_scalar_variable(self, parser, engine):
+ skip_if_no_pandas_parser(parser)
+ df = DataFrame(
+ {
+ "Symbol": ["BUD US", "BUD US", "IBM US", "IBM US"],
+ "Price": [109.70, 109.72, 183.30, 183.35],
+ }
+ )
+ e = df[df.Symbol == "BUD US"]
+ symb = "BUD US" # noqa: F841
+ r = df.query("Symbol == @symb", parser=parser, engine=engine)
+ tm.assert_frame_equal(e, r)
+
+ @pytest.mark.parametrize(
+ "in_list",
+ [
+ [None, "asdf", "ghjk"],
+ ["asdf", None, "ghjk"],
+ ["asdf", "ghjk", None],
+ [None, None, "asdf"],
+ ["asdf", None, None],
+ [None, None, None],
+ ],
+ )
+ def test_query_string_null_elements(self, in_list):
+ # GITHUB ISSUE #31516
+ parser = "pandas"
+ engine = "python"
+ expected = {i: value for i, value in enumerate(in_list) if value == "asdf"}
+
+ df_expected = DataFrame({"a": expected}, dtype="string")
+ df_expected.index = df_expected.index.astype("int64")
+ df = DataFrame({"a": in_list}, dtype="string")
+ res1 = df.query("a == 'asdf'", parser=parser, engine=engine)
+ res2 = df[df["a"] == "asdf"]
+ res3 = df.query("a <= 'asdf'", parser=parser, engine=engine)
+ tm.assert_frame_equal(res1, df_expected)
+ tm.assert_frame_equal(res1, res2)
+ tm.assert_frame_equal(res1, res3)
+ tm.assert_frame_equal(res2, res3)
+
+
+class TestDataFrameEvalWithFrame:
+ @pytest.fixture
+ def frame(self):
+ return DataFrame(
+ np.random.default_rng(2).standard_normal((10, 3)), columns=list("abc")
+ )
+
+ def test_simple_expr(self, frame, parser, engine):
+ res = frame.eval("a + b", engine=engine, parser=parser)
+ expect = frame.a + frame.b
+ tm.assert_series_equal(res, expect)
+
+ def test_bool_arith_expr(self, frame, parser, engine):
+ res = frame.eval("a[a < 1] + b", engine=engine, parser=parser)
+ expect = frame.a[frame.a < 1] + frame.b
+ tm.assert_series_equal(res, expect)
+
+ @pytest.mark.parametrize("op", ["+", "-", "*", "/"])
+ def test_invalid_type_for_operator_raises(self, parser, engine, op):
+ df = DataFrame({"a": [1, 2], "b": ["c", "d"]})
+ msg = r"unsupported operand type\(s\) for .+: '.+' and '.+'"
+
+ with pytest.raises(TypeError, match=msg):
+ df.eval(f"a {op} b", engine=engine, parser=parser)
+
+
+class TestDataFrameQueryBacktickQuoting:
+ @pytest.fixture
+ def df(self):
+ """
+ Yields a dataframe with strings that may or may not need escaping
+ by backticks. The last two columns cannot be escaped by backticks
+ and should raise a ValueError.
+ """
+ yield DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B B": [3, 2, 1],
+ "C C": [4, 5, 6],
+ "C C": [7, 4, 3],
+ "C_C": [8, 9, 10],
+ "D_D D": [11, 1, 101],
+ "E.E": [6, 3, 5],
+ "F-F": [8, 1, 10],
+ "1e1": [2, 4, 8],
+ "def": [10, 11, 2],
+ "A (x)": [4, 1, 3],
+ "B(x)": [1, 1, 5],
+ "B (x)": [2, 7, 4],
+ " &^ :!€$?(} > <++*'' ": [2, 5, 6],
+ "": [10, 11, 1],
+ " A": [4, 7, 9],
+ " ": [1, 2, 1],
+ "it's": [6, 3, 1],
+ "that's": [9, 1, 8],
+ "☺": [8, 7, 6],
+ "foo#bar": [2, 4, 5],
+ 1: [5, 7, 9],
+ }
+ )
+
+ def test_single_backtick_variable_query(self, df):
+ res = df.query("1 < `B B`")
+ expect = df[1 < df["B B"]]
+ tm.assert_frame_equal(res, expect)
+
+ def test_two_backtick_variables_query(self, df):
+ res = df.query("1 < `B B` and 4 < `C C`")
+ expect = df[(1 < df["B B"]) & (4 < df["C C"])]
+ tm.assert_frame_equal(res, expect)
+
+ def test_single_backtick_variable_expr(self, df):
+ res = df.eval("A + `B B`")
+ expect = df["A"] + df["B B"]
+ tm.assert_series_equal(res, expect)
+
+ def test_two_backtick_variables_expr(self, df):
+ res = df.eval("`B B` + `C C`")
+ expect = df["B B"] + df["C C"]
+ tm.assert_series_equal(res, expect)
+
+ def test_already_underscore_variable(self, df):
+ res = df.eval("`C_C` + A")
+ expect = df["C_C"] + df["A"]
+ tm.assert_series_equal(res, expect)
+
+ def test_same_name_but_underscores(self, df):
+ res = df.eval("C_C + `C C`")
+ expect = df["C_C"] + df["C C"]
+ tm.assert_series_equal(res, expect)
+
+ def test_mixed_underscores_and_spaces(self, df):
+ res = df.eval("A + `D_D D`")
+ expect = df["A"] + df["D_D D"]
+ tm.assert_series_equal(res, expect)
+
+ def test_backtick_quote_name_with_no_spaces(self, df):
+ res = df.eval("A + `C_C`")
+ expect = df["A"] + df["C_C"]
+ tm.assert_series_equal(res, expect)
+
+ def test_special_characters(self, df):
+ res = df.eval("`E.E` + `F-F` - A")
+ expect = df["E.E"] + df["F-F"] - df["A"]
+ tm.assert_series_equal(res, expect)
+
+ def test_start_with_digit(self, df):
+ res = df.eval("A + `1e1`")
+ expect = df["A"] + df["1e1"]
+ tm.assert_series_equal(res, expect)
+
+ def test_keyword(self, df):
+ res = df.eval("A + `def`")
+ expect = df["A"] + df["def"]
+ tm.assert_series_equal(res, expect)
+
+ def test_unneeded_quoting(self, df):
+ res = df.query("`A` > 2")
+ expect = df[df["A"] > 2]
+ tm.assert_frame_equal(res, expect)
+
+ def test_parenthesis(self, df):
+ res = df.query("`A (x)` > 2")
+ expect = df[df["A (x)"] > 2]
+ tm.assert_frame_equal(res, expect)
+
+ def test_empty_string(self, df):
+ res = df.query("`` > 5")
+ expect = df[df[""] > 5]
+ tm.assert_frame_equal(res, expect)
+
+ def test_multiple_spaces(self, df):
+ res = df.query("`C C` > 5")
+ expect = df[df["C C"] > 5]
+ tm.assert_frame_equal(res, expect)
+
+ def test_start_with_spaces(self, df):
+ res = df.eval("` A` + ` `")
+ expect = df[" A"] + df[" "]
+ tm.assert_series_equal(res, expect)
+
+ def test_lots_of_operators_string(self, df):
+ res = df.query("` &^ :!€$?(} > <++*'' ` > 4")
+ expect = df[df[" &^ :!€$?(} > <++*'' "] > 4]
+ tm.assert_frame_equal(res, expect)
+
+ def test_missing_attribute(self, df):
+ message = "module 'pandas' has no attribute 'thing'"
+ with pytest.raises(AttributeError, match=message):
+ df.eval("@pd.thing")
+
+ def test_failing_quote(self, df):
+ msg = r"(Could not convert ).*( to a valid Python identifier.)"
+ with pytest.raises(SyntaxError, match=msg):
+ df.query("`it's` > `that's`")
+
+ def test_failing_character_outside_range(self, df):
+ msg = r"(Could not convert ).*( to a valid Python identifier.)"
+ with pytest.raises(SyntaxError, match=msg):
+ df.query("`☺` > 4")
+
+ def test_failing_hashtag(self, df):
+ msg = "Failed to parse backticks"
+ with pytest.raises(SyntaxError, match=msg):
+ df.query("`foo#bar` > 4")
+
+ def test_call_non_named_expression(self, df):
+ """
+ Only attributes and variables ('named functions') can be called.
+ .__call__() is not an allowed attribute because that would allow
+ calling anything.
+ https://github.com/pandas-dev/pandas/pull/32460
+ """
+
+ def func(*_):
+ return 1
+
+ funcs = [func] # noqa: F841
+
+ df.eval("@func()")
+
+ with pytest.raises(TypeError, match="Only named functions are supported"):
+ df.eval("@funcs[0]()")
+
+ with pytest.raises(TypeError, match="Only named functions are supported"):
+ df.eval("@funcs[0].__call__()")
+
+ def test_ea_dtypes(self, any_numeric_ea_and_arrow_dtype):
+ # GH#29618
+ df = DataFrame(
+ [[1, 2], [3, 4]], columns=["a", "b"], dtype=any_numeric_ea_and_arrow_dtype
+ )
+ warning = RuntimeWarning if NUMEXPR_INSTALLED else None
+ with tm.assert_produces_warning(warning):
+ result = df.eval("c = b - a")
+ expected = DataFrame(
+ [[1, 2, 1], [3, 4, 1]],
+ columns=["a", "b", "c"],
+ dtype=any_numeric_ea_and_arrow_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_ea_dtypes_and_scalar(self):
+ # GH#29618
+ df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"], dtype="Float64")
+ warning = RuntimeWarning if NUMEXPR_INSTALLED else None
+ with tm.assert_produces_warning(warning):
+ result = df.eval("c = b - 1")
+ expected = DataFrame(
+ [[1, 2, 1], [3, 4, 3]], columns=["a", "b", "c"], dtype="Float64"
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_ea_dtypes_and_scalar_operation(self, any_numeric_ea_and_arrow_dtype):
+ # GH#29618
+ df = DataFrame(
+ [[1, 2], [3, 4]], columns=["a", "b"], dtype=any_numeric_ea_and_arrow_dtype
+ )
+ result = df.eval("c = 2 - 1")
+ expected = DataFrame(
+ {
+ "a": Series([1, 3], dtype=any_numeric_ea_and_arrow_dtype),
+ "b": Series([2, 4], dtype=any_numeric_ea_and_arrow_dtype),
+ "c": Series([1, 1], dtype=result["c"].dtype),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["int64", "Int64", "int64[pyarrow]"])
+ def test_query_ea_dtypes(self, dtype):
+ if dtype == "int64[pyarrow]":
+ pytest.importorskip("pyarrow")
+ # GH#50261
+ df = DataFrame({"a": Series([1, 2], dtype=dtype)})
+ ref = {2} # noqa: F841
+ warning = RuntimeWarning if dtype == "Int64" and NUMEXPR_INSTALLED else None
+ with tm.assert_produces_warning(warning):
+ result = df.query("a in @ref")
+ expected = DataFrame({"a": Series([2], dtype=dtype, index=[1])})
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("engine", ["python", "numexpr"])
+ @pytest.mark.parametrize("dtype", ["int64", "Int64", "int64[pyarrow]"])
+ def test_query_ea_equality_comparison(self, dtype, engine):
+ # GH#50261
+ warning = RuntimeWarning if engine == "numexpr" else None
+ if engine == "numexpr" and not NUMEXPR_INSTALLED:
+ pytest.skip("numexpr not installed")
+ if dtype == "int64[pyarrow]":
+ pytest.importorskip("pyarrow")
+ df = DataFrame(
+ {"A": Series([1, 1, 2], dtype="Int64"), "B": Series([1, 2, 2], dtype=dtype)}
+ )
+ with tm.assert_produces_warning(warning):
+ result = df.query("A == B", engine=engine)
+ expected = DataFrame(
+ {
+ "A": Series([1, 2], dtype="Int64", index=[0, 2]),
+ "B": Series([1, 2], dtype=dtype, index=[0, 2]),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_reductions.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_reductions.py
new file mode 100644
index 0000000000000000000000000000000000000000..bec1fcd1e7462beb278bf7e1ee8f03caf89eae0d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_reductions.py
@@ -0,0 +1,2043 @@
+from datetime import timedelta
+from decimal import Decimal
+import re
+
+from dateutil.tz import tzlocal
+import numpy as np
+import pytest
+
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
+from pandas.compat.numpy import np_version_gt2
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ CategoricalDtype,
+ DataFrame,
+ Index,
+ Series,
+ Timestamp,
+ date_range,
+ isna,
+ notna,
+ to_datetime,
+ to_timedelta,
+)
+import pandas._testing as tm
+from pandas.core import (
+ algorithms,
+ nanops,
+)
+
+is_windows_np2_or_is32 = (is_platform_windows() and not np_version_gt2) or not IS64
+is_windows_or_is32 = is_platform_windows() or not IS64
+
+
+def assert_stat_op_calc(
+ opname,
+ alternative,
+ frame,
+ has_skipna=True,
+ check_dtype=True,
+ check_dates=False,
+ rtol=1e-5,
+ atol=1e-8,
+ skipna_alternative=None,
+):
+ """
+ Check that operator opname works as advertised on frame
+
+ Parameters
+ ----------
+ opname : str
+ Name of the operator to test on frame
+ alternative : function
+ Function that opname is tested against; i.e. "frame.opname()" should
+ equal "alternative(frame)".
+ frame : DataFrame
+ The object that the tests are executed on
+ has_skipna : bool, default True
+ Whether the method "opname" has the kwarg "skip_na"
+ check_dtype : bool, default True
+ Whether the dtypes of the result of "frame.opname()" and
+ "alternative(frame)" should be checked.
+ check_dates : bool, default false
+ Whether opname should be tested on a Datetime Series
+ rtol : float, default 1e-5
+ Relative tolerance.
+ atol : float, default 1e-8
+ Absolute tolerance.
+ skipna_alternative : function, default None
+ NaN-safe version of alternative
+ """
+ f = getattr(frame, opname)
+
+ if check_dates:
+ df = DataFrame({"b": date_range("1/1/2001", periods=2)})
+ with tm.assert_produces_warning(None):
+ result = getattr(df, opname)()
+ assert isinstance(result, Series)
+
+ df["a"] = range(len(df))
+ with tm.assert_produces_warning(None):
+ result = getattr(df, opname)()
+ assert isinstance(result, Series)
+ assert len(result)
+
+ if has_skipna:
+
+ def wrapper(x):
+ return alternative(x.values)
+
+ skipna_wrapper = tm._make_skipna_wrapper(alternative, skipna_alternative)
+ result0 = f(axis=0, skipna=False)
+ result1 = f(axis=1, skipna=False)
+ tm.assert_series_equal(
+ result0, frame.apply(wrapper), check_dtype=check_dtype, rtol=rtol, atol=atol
+ )
+ tm.assert_series_equal(
+ result1,
+ frame.apply(wrapper, axis=1),
+ rtol=rtol,
+ atol=atol,
+ )
+ else:
+ skipna_wrapper = alternative
+
+ result0 = f(axis=0)
+ result1 = f(axis=1)
+ tm.assert_series_equal(
+ result0,
+ frame.apply(skipna_wrapper),
+ check_dtype=check_dtype,
+ rtol=rtol,
+ atol=atol,
+ )
+
+ if opname in ["sum", "prod"]:
+ expected = frame.apply(skipna_wrapper, axis=1)
+ tm.assert_series_equal(
+ result1, expected, check_dtype=False, rtol=rtol, atol=atol
+ )
+
+ # check dtypes
+ if check_dtype:
+ lcd_dtype = frame.values.dtype
+ assert lcd_dtype == result0.dtype
+ assert lcd_dtype == result1.dtype
+
+ # bad axis
+ with pytest.raises(ValueError, match="No axis named 2"):
+ f(axis=2)
+
+ # all NA case
+ if has_skipna:
+ all_na = frame * np.nan
+ r0 = getattr(all_na, opname)(axis=0)
+ r1 = getattr(all_na, opname)(axis=1)
+ if opname in ["sum", "prod"]:
+ unit = 1 if opname == "prod" else 0 # result for empty sum/prod
+ expected = Series(unit, index=r0.index, dtype=r0.dtype)
+ tm.assert_series_equal(r0, expected)
+ expected = Series(unit, index=r1.index, dtype=r1.dtype)
+ tm.assert_series_equal(r1, expected)
+
+
+class TestDataFrameAnalytics:
+ # ---------------------------------------------------------------------
+ # Reductions
+ @pytest.mark.parametrize("axis", [0, 1])
+ @pytest.mark.parametrize(
+ "opname",
+ [
+ "count",
+ "sum",
+ "mean",
+ "product",
+ "median",
+ "min",
+ "max",
+ "nunique",
+ "var",
+ "std",
+ "sem",
+ pytest.param("skew", marks=td.skip_if_no_scipy),
+ pytest.param("kurt", marks=td.skip_if_no_scipy),
+ ],
+ )
+ def test_stat_op_api_float_string_frame(self, float_string_frame, axis, opname):
+ if (opname in ("sum", "min", "max") and axis == 0) or opname in (
+ "count",
+ "nunique",
+ ):
+ getattr(float_string_frame, opname)(axis=axis)
+ else:
+ if opname in ["var", "std", "sem", "skew", "kurt"]:
+ msg = "could not convert string to float: 'bar'"
+ elif opname == "product":
+ if axis == 1:
+ msg = "can't multiply sequence by non-int of type 'float'"
+ else:
+ msg = "can't multiply sequence by non-int of type 'str'"
+ elif opname == "sum":
+ msg = r"unsupported operand type\(s\) for \+: 'float' and 'str'"
+ elif opname == "mean":
+ if axis == 0:
+ # different message on different builds
+ msg = "|".join(
+ [
+ r"Could not convert \['.*'\] to numeric",
+ "Could not convert string '(bar){30}' to numeric",
+ ]
+ )
+ else:
+ msg = r"unsupported operand type\(s\) for \+: 'float' and 'str'"
+ elif opname in ["min", "max"]:
+ msg = "'[><]=' not supported between instances of 'float' and 'str'"
+ elif opname == "median":
+ msg = re.compile(r"Cannot convert \[.*\] to numeric", flags=re.S)
+ with pytest.raises(TypeError, match=msg):
+ getattr(float_string_frame, opname)(axis=axis)
+ if opname != "nunique":
+ getattr(float_string_frame, opname)(axis=axis, numeric_only=True)
+
+ @pytest.mark.parametrize("axis", [0, 1])
+ @pytest.mark.parametrize(
+ "opname",
+ [
+ "count",
+ "sum",
+ "mean",
+ "product",
+ "median",
+ "min",
+ "max",
+ "var",
+ "std",
+ "sem",
+ pytest.param("skew", marks=td.skip_if_no_scipy),
+ pytest.param("kurt", marks=td.skip_if_no_scipy),
+ ],
+ )
+ def test_stat_op_api_float_frame(self, float_frame, axis, opname):
+ getattr(float_frame, opname)(axis=axis, numeric_only=False)
+
+ def test_stat_op_calc(self, float_frame_with_na, mixed_float_frame):
+ def count(s):
+ return notna(s).sum()
+
+ def nunique(s):
+ return len(algorithms.unique1d(s.dropna()))
+
+ def var(x):
+ return np.var(x, ddof=1)
+
+ def std(x):
+ return np.std(x, ddof=1)
+
+ def sem(x):
+ return np.std(x, ddof=1) / np.sqrt(len(x))
+
+ assert_stat_op_calc(
+ "nunique",
+ nunique,
+ float_frame_with_na,
+ has_skipna=False,
+ check_dtype=False,
+ check_dates=True,
+ )
+
+ # GH#32571: rol needed for flaky CI builds
+ # mixed types (with upcasting happening)
+ assert_stat_op_calc(
+ "sum",
+ np.sum,
+ mixed_float_frame.astype("float32"),
+ check_dtype=False,
+ rtol=1e-3,
+ )
+
+ assert_stat_op_calc(
+ "sum", np.sum, float_frame_with_na, skipna_alternative=np.nansum
+ )
+ assert_stat_op_calc("mean", np.mean, float_frame_with_na, check_dates=True)
+ assert_stat_op_calc(
+ "product", np.prod, float_frame_with_na, skipna_alternative=np.nanprod
+ )
+
+ assert_stat_op_calc("var", var, float_frame_with_na)
+ assert_stat_op_calc("std", std, float_frame_with_na)
+ assert_stat_op_calc("sem", sem, float_frame_with_na)
+
+ assert_stat_op_calc(
+ "count",
+ count,
+ float_frame_with_na,
+ has_skipna=False,
+ check_dtype=False,
+ check_dates=True,
+ )
+
+ def test_stat_op_calc_skew_kurtosis(self, float_frame_with_na):
+ sp_stats = pytest.importorskip("scipy.stats")
+
+ def skewness(x):
+ if len(x) < 3:
+ return np.nan
+ return sp_stats.skew(x, bias=False)
+
+ def kurt(x):
+ if len(x) < 4:
+ return np.nan
+ return sp_stats.kurtosis(x, bias=False)
+
+ assert_stat_op_calc("skew", skewness, float_frame_with_na)
+ assert_stat_op_calc("kurt", kurt, float_frame_with_na)
+
+ def test_median(self, float_frame_with_na, int_frame):
+ def wrapper(x):
+ if isna(x).any():
+ return np.nan
+ return np.median(x)
+
+ assert_stat_op_calc("median", wrapper, float_frame_with_na, check_dates=True)
+ assert_stat_op_calc(
+ "median", wrapper, int_frame, check_dtype=False, check_dates=True
+ )
+
+ @pytest.mark.parametrize(
+ "method", ["sum", "mean", "prod", "var", "std", "skew", "min", "max"]
+ )
+ @pytest.mark.parametrize(
+ "df",
+ [
+ DataFrame(
+ {
+ "a": [
+ -0.00049987540199591344,
+ -0.0016467257772919831,
+ 0.00067695870775883013,
+ ],
+ "b": [-0, -0, 0.0],
+ "c": [
+ 0.00031111847529610595,
+ 0.0014902627951905339,
+ -0.00094099200035979691,
+ ],
+ },
+ index=["foo", "bar", "baz"],
+ dtype="O",
+ ),
+ DataFrame({0: [np.nan, 2], 1: [np.nan, 3], 2: [np.nan, 4]}, dtype=object),
+ ],
+ )
+ @pytest.mark.filterwarnings("ignore:Mismatched null-like values:FutureWarning")
+ def test_stat_operators_attempt_obj_array(self, method, df, axis):
+ # GH#676
+ assert df.values.dtype == np.object_
+ result = getattr(df, method)(axis=axis)
+ expected = getattr(df.astype("f8"), method)(axis=axis).astype(object)
+ if axis in [1, "columns"] and method in ["min", "max"]:
+ expected[expected.isna()] = None
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("op", ["mean", "std", "var", "skew", "kurt", "sem"])
+ def test_mixed_ops(self, op):
+ # GH#16116
+ df = DataFrame(
+ {
+ "int": [1, 2, 3, 4],
+ "float": [1.0, 2.0, 3.0, 4.0],
+ "str": ["a", "b", "c", "d"],
+ }
+ )
+ msg = "|".join(
+ [
+ "Could not convert",
+ "could not convert",
+ "can't multiply sequence by non-int",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ getattr(df, op)()
+
+ with pd.option_context("use_bottleneck", False):
+ msg = "|".join(
+ [
+ "Could not convert",
+ "could not convert",
+ "can't multiply sequence by non-int",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ getattr(df, op)()
+
+ def test_reduce_mixed_frame(self):
+ # GH 6806
+ df = DataFrame(
+ {
+ "bool_data": [True, True, False, False, False],
+ "int_data": [10, 20, 30, 40, 50],
+ "string_data": ["a", "b", "c", "d", "e"],
+ }
+ )
+ df.reindex(columns=["bool_data", "int_data", "string_data"])
+ test = df.sum(axis=0)
+ tm.assert_numpy_array_equal(
+ test.values, np.array([2, 150, "abcde"], dtype=object)
+ )
+ alt = df.T.sum(axis=1)
+ tm.assert_series_equal(test, alt)
+
+ def test_nunique(self):
+ df = DataFrame({"A": [1, 1, 1], "B": [1, 2, 3], "C": [1, np.nan, 3]})
+ tm.assert_series_equal(df.nunique(), Series({"A": 1, "B": 3, "C": 2}))
+ tm.assert_series_equal(
+ df.nunique(dropna=False), Series({"A": 1, "B": 3, "C": 3})
+ )
+ tm.assert_series_equal(df.nunique(axis=1), Series({0: 1, 1: 2, 2: 2}))
+ tm.assert_series_equal(
+ df.nunique(axis=1, dropna=False), Series({0: 1, 1: 3, 2: 2})
+ )
+
+ @pytest.mark.parametrize("tz", [None, "UTC"])
+ def test_mean_mixed_datetime_numeric(self, tz):
+ # https://github.com/pandas-dev/pandas/issues/24752
+ df = DataFrame({"A": [1, 1], "B": [Timestamp("2000", tz=tz)] * 2})
+ result = df.mean()
+ expected = Series([1.0, Timestamp("2000", tz=tz)], index=["A", "B"])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("tz", [None, "UTC"])
+ def test_mean_includes_datetimes(self, tz):
+ # https://github.com/pandas-dev/pandas/issues/24752
+ # Behavior in 0.24.0rc1 was buggy.
+ # As of 2.0 with numeric_only=None we do *not* drop datetime columns
+ df = DataFrame({"A": [Timestamp("2000", tz=tz)] * 2})
+ result = df.mean()
+
+ expected = Series([Timestamp("2000", tz=tz)], index=["A"])
+ tm.assert_series_equal(result, expected)
+
+ def test_mean_mixed_string_decimal(self):
+ # GH 11670
+ # possible bug when calculating mean of DataFrame?
+
+ d = [
+ {"A": 2, "B": None, "C": Decimal("628.00")},
+ {"A": 1, "B": None, "C": Decimal("383.00")},
+ {"A": 3, "B": None, "C": Decimal("651.00")},
+ {"A": 2, "B": None, "C": Decimal("575.00")},
+ {"A": 4, "B": None, "C": Decimal("1114.00")},
+ {"A": 1, "B": "TEST", "C": Decimal("241.00")},
+ {"A": 2, "B": None, "C": Decimal("572.00")},
+ {"A": 4, "B": None, "C": Decimal("609.00")},
+ {"A": 3, "B": None, "C": Decimal("820.00")},
+ {"A": 5, "B": None, "C": Decimal("1223.00")},
+ ]
+
+ df = DataFrame(d)
+
+ with pytest.raises(TypeError, match="unsupported operand type"):
+ df.mean()
+ result = df[["A", "C"]].mean()
+ expected = Series([2.7, 681.6], index=["A", "C"], dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ def test_var_std(self, datetime_frame):
+ result = datetime_frame.std(ddof=4)
+ expected = datetime_frame.apply(lambda x: x.std(ddof=4))
+ tm.assert_almost_equal(result, expected)
+
+ result = datetime_frame.var(ddof=4)
+ expected = datetime_frame.apply(lambda x: x.var(ddof=4))
+ tm.assert_almost_equal(result, expected)
+
+ arr = np.repeat(np.random.default_rng(2).random((1, 1000)), 1000, 0)
+ result = nanops.nanvar(arr, axis=0)
+ assert not (result < 0).any()
+
+ with pd.option_context("use_bottleneck", False):
+ result = nanops.nanvar(arr, axis=0)
+ assert not (result < 0).any()
+
+ @pytest.mark.parametrize("meth", ["sem", "var", "std"])
+ def test_numeric_only_flag(self, meth):
+ # GH 9201
+ df1 = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)),
+ columns=["foo", "bar", "baz"],
+ )
+ # Cast to object to avoid implicit cast when setting entry to "100" below
+ df1 = df1.astype({"foo": object})
+ # set one entry to a number in str format
+ df1.loc[0, "foo"] = "100"
+
+ df2 = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)),
+ columns=["foo", "bar", "baz"],
+ )
+ # Cast to object to avoid implicit cast when setting entry to "a" below
+ df2 = df2.astype({"foo": object})
+ # set one entry to a non-number str
+ df2.loc[0, "foo"] = "a"
+
+ result = getattr(df1, meth)(axis=1, numeric_only=True)
+ expected = getattr(df1[["bar", "baz"]], meth)(axis=1)
+ tm.assert_series_equal(expected, result)
+
+ result = getattr(df2, meth)(axis=1, numeric_only=True)
+ expected = getattr(df2[["bar", "baz"]], meth)(axis=1)
+ tm.assert_series_equal(expected, result)
+
+ # df1 has all numbers, df2 has a letter inside
+ msg = r"unsupported operand type\(s\) for -: 'float' and 'str'"
+ with pytest.raises(TypeError, match=msg):
+ getattr(df1, meth)(axis=1, numeric_only=False)
+ msg = "could not convert string to float: 'a'"
+ with pytest.raises(TypeError, match=msg):
+ getattr(df2, meth)(axis=1, numeric_only=False)
+
+ def test_sem(self, datetime_frame):
+ result = datetime_frame.sem(ddof=4)
+ expected = datetime_frame.apply(lambda x: x.std(ddof=4) / np.sqrt(len(x)))
+ tm.assert_almost_equal(result, expected)
+
+ arr = np.repeat(np.random.default_rng(2).random((1, 1000)), 1000, 0)
+ result = nanops.nansem(arr, axis=0)
+ assert not (result < 0).any()
+
+ with pd.option_context("use_bottleneck", False):
+ result = nanops.nansem(arr, axis=0)
+ assert not (result < 0).any()
+
+ @pytest.mark.parametrize(
+ "dropna, expected",
+ [
+ (
+ True,
+ {
+ "A": [12],
+ "B": [10.0],
+ "C": [1.0],
+ "D": ["a"],
+ "E": Categorical(["a"], categories=["a"]),
+ "F": to_datetime(["2000-1-2"]),
+ "G": to_timedelta(["1 days"]),
+ },
+ ),
+ (
+ False,
+ {
+ "A": [12],
+ "B": [10.0],
+ "C": [np.nan],
+ "D": np.array([np.nan], dtype=object),
+ "E": Categorical([np.nan], categories=["a"]),
+ "F": [pd.NaT],
+ "G": to_timedelta([pd.NaT]),
+ },
+ ),
+ (
+ True,
+ {
+ "H": [8, 9, np.nan, np.nan],
+ "I": [8, 9, np.nan, np.nan],
+ "J": [1, np.nan, np.nan, np.nan],
+ "K": Categorical(["a", np.nan, np.nan, np.nan], categories=["a"]),
+ "L": to_datetime(["2000-1-2", "NaT", "NaT", "NaT"]),
+ "M": to_timedelta(["1 days", "nan", "nan", "nan"]),
+ "N": [0, 1, 2, 3],
+ },
+ ),
+ (
+ False,
+ {
+ "H": [8, 9, np.nan, np.nan],
+ "I": [8, 9, np.nan, np.nan],
+ "J": [1, np.nan, np.nan, np.nan],
+ "K": Categorical([np.nan, "a", np.nan, np.nan], categories=["a"]),
+ "L": to_datetime(["NaT", "2000-1-2", "NaT", "NaT"]),
+ "M": to_timedelta(["nan", "1 days", "nan", "nan"]),
+ "N": [0, 1, 2, 3],
+ },
+ ),
+ ],
+ )
+ def test_mode_dropna(self, dropna, expected):
+ df = DataFrame(
+ {
+ "A": [12, 12, 19, 11],
+ "B": [10, 10, np.nan, 3],
+ "C": [1, np.nan, np.nan, np.nan],
+ "D": [np.nan, np.nan, "a", np.nan],
+ "E": Categorical([np.nan, np.nan, "a", np.nan]),
+ "F": to_datetime(["NaT", "2000-1-2", "NaT", "NaT"]),
+ "G": to_timedelta(["1 days", "nan", "nan", "nan"]),
+ "H": [8, 8, 9, 9],
+ "I": [9, 9, 8, 8],
+ "J": [1, 1, np.nan, np.nan],
+ "K": Categorical(["a", np.nan, "a", np.nan]),
+ "L": to_datetime(["2000-1-2", "2000-1-2", "NaT", "NaT"]),
+ "M": to_timedelta(["1 days", "nan", "1 days", "nan"]),
+ "N": np.arange(4, dtype="int64"),
+ }
+ )
+
+ result = df[sorted(expected.keys())].mode(dropna=dropna)
+ expected = DataFrame(expected)
+ tm.assert_frame_equal(result, expected)
+
+ def test_mode_sortwarning(self):
+ # Check for the warning that is raised when the mode
+ # results cannot be sorted
+
+ df = DataFrame({"A": [np.nan, np.nan, "a", "a"]})
+ expected = DataFrame({"A": ["a", np.nan]})
+
+ with tm.assert_produces_warning(UserWarning):
+ result = df.mode(dropna=False)
+ result = result.sort_values(by="A").reset_index(drop=True)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_mode_empty_df(self):
+ df = DataFrame([], columns=["a", "b"])
+ result = df.mode()
+ expected = DataFrame([], columns=["a", "b"], index=Index([], dtype=np.int64))
+ tm.assert_frame_equal(result, expected)
+
+ def test_operators_timedelta64(self):
+ df = DataFrame(
+ {
+ "A": date_range("2012-1-1", periods=3, freq="D"),
+ "B": date_range("2012-1-2", periods=3, freq="D"),
+ "C": Timestamp("20120101") - timedelta(minutes=5, seconds=5),
+ }
+ )
+
+ diffs = DataFrame({"A": df["A"] - df["C"], "B": df["A"] - df["B"]})
+
+ # min
+ result = diffs.min()
+ assert result.iloc[0] == diffs.loc[0, "A"]
+ assert result.iloc[1] == diffs.loc[0, "B"]
+
+ result = diffs.min(axis=1)
+ assert (result == diffs.loc[0, "B"]).all()
+
+ # max
+ result = diffs.max()
+ assert result.iloc[0] == diffs.loc[2, "A"]
+ assert result.iloc[1] == diffs.loc[2, "B"]
+
+ result = diffs.max(axis=1)
+ assert (result == diffs["A"]).all()
+
+ # abs
+ result = diffs.abs()
+ result2 = abs(diffs)
+ expected = DataFrame({"A": df["A"] - df["C"], "B": df["B"] - df["A"]})
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(result2, expected)
+
+ # mixed frame
+ mixed = diffs.copy()
+ mixed["C"] = "foo"
+ mixed["D"] = 1
+ mixed["E"] = 1.0
+ mixed["F"] = Timestamp("20130101")
+
+ # results in an object array
+ result = mixed.min()
+ expected = Series(
+ [
+ pd.Timedelta(timedelta(seconds=5 * 60 + 5)),
+ pd.Timedelta(timedelta(days=-1)),
+ "foo",
+ 1,
+ 1.0,
+ Timestamp("20130101"),
+ ],
+ index=mixed.columns,
+ )
+ tm.assert_series_equal(result, expected)
+
+ # excludes non-numeric
+ result = mixed.min(axis=1, numeric_only=True)
+ expected = Series([1, 1, 1.0], index=[0, 1, 2])
+ tm.assert_series_equal(result, expected)
+
+ # works when only those columns are selected
+ result = mixed[["A", "B"]].min(1)
+ expected = Series([timedelta(days=-1)] * 3)
+ tm.assert_series_equal(result, expected)
+
+ result = mixed[["A", "B"]].min()
+ expected = Series(
+ [timedelta(seconds=5 * 60 + 5), timedelta(days=-1)], index=["A", "B"]
+ )
+ tm.assert_series_equal(result, expected)
+
+ # GH 3106
+ df = DataFrame(
+ {
+ "time": date_range("20130102", periods=5),
+ "time2": date_range("20130105", periods=5),
+ }
+ )
+ df["off1"] = df["time2"] - df["time"]
+ assert df["off1"].dtype == "timedelta64[ns]"
+
+ df["off2"] = df["time"] - df["time2"]
+ df._consolidate_inplace()
+ assert df["off1"].dtype == "timedelta64[ns]"
+ assert df["off2"].dtype == "timedelta64[ns]"
+
+ def test_std_timedelta64_skipna_false(self):
+ # GH#37392
+ tdi = pd.timedelta_range("1 Day", periods=10)
+ df = DataFrame({"A": tdi, "B": tdi}, copy=True)
+ df.iloc[-2, -1] = pd.NaT
+
+ result = df.std(skipna=False)
+ expected = Series(
+ [df["A"].std(), pd.NaT], index=["A", "B"], dtype="timedelta64[ns]"
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = df.std(axis=1, skipna=False)
+ expected = Series([pd.Timedelta(0)] * 8 + [pd.NaT, pd.Timedelta(0)])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "values", [["2022-01-01", "2022-01-02", pd.NaT, "2022-01-03"], 4 * [pd.NaT]]
+ )
+ def test_std_datetime64_with_nat(
+ self, values, skipna, using_array_manager, request
+ ):
+ # GH#51335
+ if using_array_manager and (
+ not skipna or all(value is pd.NaT for value in values)
+ ):
+ mark = pytest.mark.xfail(
+ reason="GH#51446: Incorrect type inference on NaT in reduction result"
+ )
+ request.node.add_marker(mark)
+ df = DataFrame({"a": to_datetime(values)})
+ result = df.std(skipna=skipna)
+ if not skipna or all(value is pd.NaT for value in values):
+ expected = Series({"a": pd.NaT}, dtype="timedelta64[ns]")
+ else:
+ # 86400000000000ns == 1 day
+ expected = Series({"a": 86400000000000}, dtype="timedelta64[ns]")
+ tm.assert_series_equal(result, expected)
+
+ def test_sum_corner(self):
+ empty_frame = DataFrame()
+
+ axis0 = empty_frame.sum(0)
+ axis1 = empty_frame.sum(1)
+ assert isinstance(axis0, Series)
+ assert isinstance(axis1, Series)
+ assert len(axis0) == 0
+ assert len(axis1) == 0
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ tm.makeRangeIndex(0),
+ tm.makeDateIndex(0),
+ tm.makeNumericIndex(0, dtype=int),
+ tm.makeNumericIndex(0, dtype=float),
+ tm.makeDateIndex(0, freq="M"),
+ tm.makePeriodIndex(0),
+ ],
+ )
+ def test_axis_1_empty(self, all_reductions, index, using_array_manager):
+ df = DataFrame(columns=["a"], index=index)
+ result = getattr(df, all_reductions)(axis=1)
+ if all_reductions in ("any", "all"):
+ expected_dtype = "bool"
+ elif all_reductions == "count":
+ expected_dtype = "int64"
+ else:
+ expected_dtype = "object"
+ expected = Series([], index=index, dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("method, unit", [("sum", 0), ("prod", 1)])
+ @pytest.mark.parametrize("numeric_only", [None, True, False])
+ def test_sum_prod_nanops(self, method, unit, numeric_only):
+ idx = ["a", "b", "c"]
+ df = DataFrame({"a": [unit, unit], "b": [unit, np.nan], "c": [np.nan, np.nan]})
+ # The default
+ result = getattr(df, method)(numeric_only=numeric_only)
+ expected = Series([unit, unit, unit], index=idx, dtype="float64")
+ tm.assert_series_equal(result, expected)
+
+ # min_count=1
+ result = getattr(df, method)(numeric_only=numeric_only, min_count=1)
+ expected = Series([unit, unit, np.nan], index=idx)
+ tm.assert_series_equal(result, expected)
+
+ # min_count=0
+ result = getattr(df, method)(numeric_only=numeric_only, min_count=0)
+ expected = Series([unit, unit, unit], index=idx, dtype="float64")
+ tm.assert_series_equal(result, expected)
+
+ result = getattr(df.iloc[1:], method)(numeric_only=numeric_only, min_count=1)
+ expected = Series([unit, np.nan, np.nan], index=idx)
+ tm.assert_series_equal(result, expected)
+
+ # min_count > 1
+ df = DataFrame({"A": [unit] * 10, "B": [unit] * 5 + [np.nan] * 5})
+ result = getattr(df, method)(numeric_only=numeric_only, min_count=5)
+ expected = Series(result, index=["A", "B"])
+ tm.assert_series_equal(result, expected)
+
+ result = getattr(df, method)(numeric_only=numeric_only, min_count=6)
+ expected = Series(result, index=["A", "B"])
+ tm.assert_series_equal(result, expected)
+
+ def test_sum_nanops_timedelta(self):
+ # prod isn't defined on timedeltas
+ idx = ["a", "b", "c"]
+ df = DataFrame({"a": [0, 0], "b": [0, np.nan], "c": [np.nan, np.nan]})
+
+ df2 = df.apply(to_timedelta)
+
+ # 0 by default
+ result = df2.sum()
+ expected = Series([0, 0, 0], dtype="m8[ns]", index=idx)
+ tm.assert_series_equal(result, expected)
+
+ # min_count=0
+ result = df2.sum(min_count=0)
+ tm.assert_series_equal(result, expected)
+
+ # min_count=1
+ result = df2.sum(min_count=1)
+ expected = Series([0, 0, np.nan], dtype="m8[ns]", index=idx)
+ tm.assert_series_equal(result, expected)
+
+ def test_sum_nanops_min_count(self):
+ # https://github.com/pandas-dev/pandas/issues/39738
+ df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+ result = df.sum(min_count=10)
+ expected = Series([np.nan, np.nan], index=["x", "y"])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("float_type", ["float16", "float32", "float64"])
+ @pytest.mark.parametrize(
+ "kwargs, expected_result",
+ [
+ ({"axis": 1, "min_count": 2}, [3.2, 5.3, np.nan]),
+ ({"axis": 1, "min_count": 3}, [np.nan, np.nan, np.nan]),
+ ({"axis": 1, "skipna": False}, [3.2, 5.3, np.nan]),
+ ],
+ )
+ def test_sum_nanops_dtype_min_count(self, float_type, kwargs, expected_result):
+ # GH#46947
+ df = DataFrame({"a": [1.0, 2.3, 4.4], "b": [2.2, 3, np.nan]}, dtype=float_type)
+ result = df.sum(**kwargs)
+ expected = Series(expected_result).astype(float_type)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("float_type", ["float16", "float32", "float64"])
+ @pytest.mark.parametrize(
+ "kwargs, expected_result",
+ [
+ ({"axis": 1, "min_count": 2}, [2.0, 4.0, np.nan]),
+ ({"axis": 1, "min_count": 3}, [np.nan, np.nan, np.nan]),
+ ({"axis": 1, "skipna": False}, [2.0, 4.0, np.nan]),
+ ],
+ )
+ def test_prod_nanops_dtype_min_count(self, float_type, kwargs, expected_result):
+ # GH#46947
+ df = DataFrame(
+ {"a": [1.0, 2.0, 4.4], "b": [2.0, 2.0, np.nan]}, dtype=float_type
+ )
+ result = df.prod(**kwargs)
+ expected = Series(expected_result).astype(float_type)
+ tm.assert_series_equal(result, expected)
+
+ def test_sum_object(self, float_frame):
+ values = float_frame.values.astype(int)
+ frame = DataFrame(values, index=float_frame.index, columns=float_frame.columns)
+ deltas = frame * timedelta(1)
+ deltas.sum()
+
+ def test_sum_bool(self, float_frame):
+ # ensure this works, bug report
+ bools = np.isnan(float_frame)
+ bools.sum(1)
+ bools.sum(0)
+
+ def test_sum_mixed_datetime(self):
+ # GH#30886
+ df = DataFrame({"A": date_range("2000", periods=4), "B": [1, 2, 3, 4]}).reindex(
+ [2, 3, 4]
+ )
+ with pytest.raises(TypeError, match="does not support reduction 'sum'"):
+ df.sum()
+
+ def test_mean_corner(self, float_frame, float_string_frame):
+ # unit test when have object data
+ with pytest.raises(TypeError, match="Could not convert"):
+ float_string_frame.mean(axis=0)
+
+ # xs sum mixed type, just want to know it works...
+ with pytest.raises(TypeError, match="unsupported operand type"):
+ float_string_frame.mean(axis=1)
+
+ # take mean of boolean column
+ float_frame["bool"] = float_frame["A"] > 0
+ means = float_frame.mean(0)
+ assert means["bool"] == float_frame["bool"].values.mean()
+
+ def test_mean_datetimelike(self):
+ # GH#24757 check that datetimelike are excluded by default, handled
+ # correctly with numeric_only=True
+ # As of 2.0, datetimelike are *not* excluded with numeric_only=None
+
+ df = DataFrame(
+ {
+ "A": np.arange(3),
+ "B": date_range("2016-01-01", periods=3),
+ "C": pd.timedelta_range("1D", periods=3),
+ "D": pd.period_range("2016", periods=3, freq="A"),
+ }
+ )
+ result = df.mean(numeric_only=True)
+ expected = Series({"A": 1.0})
+ tm.assert_series_equal(result, expected)
+
+ with pytest.raises(TypeError, match="mean is not implemented for PeriodArray"):
+ df.mean()
+
+ def test_mean_datetimelike_numeric_only_false(self):
+ df = DataFrame(
+ {
+ "A": np.arange(3),
+ "B": date_range("2016-01-01", periods=3),
+ "C": pd.timedelta_range("1D", periods=3),
+ }
+ )
+
+ # datetime(tz) and timedelta work
+ result = df.mean(numeric_only=False)
+ expected = Series({"A": 1, "B": df.loc[1, "B"], "C": df.loc[1, "C"]})
+ tm.assert_series_equal(result, expected)
+
+ # mean of period is not allowed
+ df["D"] = pd.period_range("2016", periods=3, freq="A")
+
+ with pytest.raises(TypeError, match="mean is not implemented for Period"):
+ df.mean(numeric_only=False)
+
+ def test_mean_extensionarray_numeric_only_true(self):
+ # https://github.com/pandas-dev/pandas/issues/33256
+ arr = np.random.default_rng(2).integers(1000, size=(10, 5))
+ df = DataFrame(arr, dtype="Int64")
+ result = df.mean(numeric_only=True)
+ expected = DataFrame(arr).mean().astype("Float64")
+ tm.assert_series_equal(result, expected)
+
+ def test_stats_mixed_type(self, float_string_frame):
+ with pytest.raises(TypeError, match="could not convert"):
+ float_string_frame.std(1)
+ with pytest.raises(TypeError, match="could not convert"):
+ float_string_frame.var(1)
+ with pytest.raises(TypeError, match="unsupported operand type"):
+ float_string_frame.mean(1)
+ with pytest.raises(TypeError, match="could not convert"):
+ float_string_frame.skew(1)
+
+ def test_sum_bools(self):
+ df = DataFrame(index=range(1), columns=range(10))
+ bools = isna(df)
+ assert bools.sum(axis=1)[0] == 10
+
+ # ----------------------------------------------------------------------
+ # Index of max / min
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ @pytest.mark.parametrize("axis", [0, 1])
+ def test_idxmin(self, float_frame, int_frame, skipna, axis):
+ frame = float_frame
+ frame.iloc[5:10] = np.nan
+ frame.iloc[15:20, -2:] = np.nan
+ for df in [frame, int_frame]:
+ warn = None
+ if skipna is False or axis == 1:
+ warn = None if df is int_frame else FutureWarning
+ msg = "The behavior of DataFrame.idxmin with all-NA values"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = df.idxmin(axis=axis, skipna=skipna)
+
+ msg2 = "The behavior of Series.idxmin"
+ with tm.assert_produces_warning(warn, match=msg2):
+ expected = df.apply(Series.idxmin, axis=axis, skipna=skipna)
+ expected = expected.astype(df.index.dtype)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("axis", [0, 1])
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_idxmin_empty(self, index, skipna, axis):
+ # GH53265
+ if axis == 0:
+ frame = DataFrame(index=index)
+ else:
+ frame = DataFrame(columns=index)
+
+ result = frame.idxmin(axis=axis, skipna=skipna)
+ expected = Series(dtype=index.dtype)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("numeric_only", [True, False])
+ def test_idxmin_numeric_only(self, numeric_only):
+ df = DataFrame({"a": [2, 3, 1], "b": [2, 1, 1], "c": list("xyx")})
+ result = df.idxmin(numeric_only=numeric_only)
+ if numeric_only:
+ expected = Series([2, 1], index=["a", "b"])
+ else:
+ expected = Series([2, 1, 0], index=["a", "b", "c"])
+ tm.assert_series_equal(result, expected)
+
+ def test_idxmin_axis_2(self, float_frame):
+ frame = float_frame
+ msg = "No axis named 2 for object type DataFrame"
+ with pytest.raises(ValueError, match=msg):
+ frame.idxmin(axis=2)
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ @pytest.mark.parametrize("axis", [0, 1])
+ def test_idxmax(self, float_frame, int_frame, skipna, axis):
+ frame = float_frame
+ frame.iloc[5:10] = np.nan
+ frame.iloc[15:20, -2:] = np.nan
+ for df in [frame, int_frame]:
+ warn = None
+ if skipna is False or axis == 1:
+ warn = None if df is int_frame else FutureWarning
+ msg = "The behavior of DataFrame.idxmax with all-NA values"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = df.idxmax(axis=axis, skipna=skipna)
+
+ msg2 = "The behavior of Series.idxmax"
+ with tm.assert_produces_warning(warn, match=msg2):
+ expected = df.apply(Series.idxmax, axis=axis, skipna=skipna)
+ expected = expected.astype(df.index.dtype)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("axis", [0, 1])
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_idxmax_empty(self, index, skipna, axis):
+ # GH53265
+ if axis == 0:
+ frame = DataFrame(index=index)
+ else:
+ frame = DataFrame(columns=index)
+
+ result = frame.idxmax(axis=axis, skipna=skipna)
+ expected = Series(dtype=index.dtype)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("numeric_only", [True, False])
+ def test_idxmax_numeric_only(self, numeric_only):
+ df = DataFrame({"a": [2, 3, 1], "b": [2, 1, 1], "c": list("xyx")})
+ result = df.idxmax(numeric_only=numeric_only)
+ if numeric_only:
+ expected = Series([1, 0], index=["a", "b"])
+ else:
+ expected = Series([1, 0, 1], index=["a", "b", "c"])
+ tm.assert_series_equal(result, expected)
+
+ def test_idxmax_arrow_types(self):
+ # GH#55368
+ pytest.importorskip("pyarrow")
+
+ df = DataFrame({"a": [2, 3, 1], "b": [2, 1, 1]}, dtype="int64[pyarrow]")
+ result = df.idxmax()
+ expected = Series([1, 0], index=["a", "b"])
+ tm.assert_series_equal(result, expected)
+
+ result = df.idxmin()
+ expected = Series([2, 1], index=["a", "b"])
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"a": ["b", "c", "a"]}, dtype="string[pyarrow]")
+ result = df.idxmax(numeric_only=False)
+ expected = Series([1], index=["a"])
+ tm.assert_series_equal(result, expected)
+
+ result = df.idxmin(numeric_only=False)
+ expected = Series([2], index=["a"])
+ tm.assert_series_equal(result, expected)
+
+ def test_idxmax_axis_2(self, float_frame):
+ frame = float_frame
+ msg = "No axis named 2 for object type DataFrame"
+ with pytest.raises(ValueError, match=msg):
+ frame.idxmax(axis=2)
+
+ def test_idxmax_mixed_dtype(self):
+ # don't cast to object, which would raise in nanops
+ dti = date_range("2016-01-01", periods=3)
+
+ # Copying dti is needed for ArrayManager otherwise when we set
+ # df.loc[0, 3] = pd.NaT below it edits dti
+ df = DataFrame({1: [0, 2, 1], 2: range(3)[::-1], 3: dti.copy(deep=True)})
+
+ result = df.idxmax()
+ expected = Series([1, 0, 2], index=[1, 2, 3])
+ tm.assert_series_equal(result, expected)
+
+ result = df.idxmin()
+ expected = Series([0, 2, 0], index=[1, 2, 3])
+ tm.assert_series_equal(result, expected)
+
+ # with NaTs
+ df.loc[0, 3] = pd.NaT
+ result = df.idxmax()
+ expected = Series([1, 0, 2], index=[1, 2, 3])
+ tm.assert_series_equal(result, expected)
+
+ result = df.idxmin()
+ expected = Series([0, 2, 1], index=[1, 2, 3])
+ tm.assert_series_equal(result, expected)
+
+ # with multi-column dt64 block
+ df[4] = dti[::-1]
+ df._consolidate_inplace()
+
+ result = df.idxmax()
+ expected = Series([1, 0, 2, 0], index=[1, 2, 3, 4])
+ tm.assert_series_equal(result, expected)
+
+ result = df.idxmin()
+ expected = Series([0, 2, 1, 2], index=[1, 2, 3, 4])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "op, expected_value",
+ [("idxmax", [0, 4]), ("idxmin", [0, 5])],
+ )
+ def test_idxmax_idxmin_convert_dtypes(self, op, expected_value):
+ # GH 40346
+ df = DataFrame(
+ {
+ "ID": [100, 100, 100, 200, 200, 200],
+ "value": [0, 0, 0, 1, 2, 0],
+ },
+ dtype="Int64",
+ )
+ df = df.groupby("ID")
+
+ result = getattr(df, op)()
+ expected = DataFrame(
+ {"value": expected_value},
+ index=Index([100, 200], name="ID", dtype="Int64"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_idxmax_dt64_multicolumn_axis1(self):
+ dti = date_range("2016-01-01", periods=3)
+ df = DataFrame({3: dti, 4: dti[::-1]}, copy=True)
+ df.iloc[0, 0] = pd.NaT
+
+ df._consolidate_inplace()
+
+ result = df.idxmax(axis=1)
+ expected = Series([4, 3, 3])
+ tm.assert_series_equal(result, expected)
+
+ result = df.idxmin(axis=1)
+ expected = Series([4, 3, 4])
+ tm.assert_series_equal(result, expected)
+
+ # ----------------------------------------------------------------------
+ # Logical reductions
+
+ @pytest.mark.parametrize("opname", ["any", "all"])
+ @pytest.mark.parametrize("axis", [0, 1])
+ @pytest.mark.parametrize("bool_only", [False, True])
+ def test_any_all_mixed_float(self, opname, axis, bool_only, float_string_frame):
+ # make sure op works on mixed-type frame
+ mixed = float_string_frame
+ mixed["_bool_"] = np.random.default_rng(2).standard_normal(len(mixed)) > 0.5
+
+ getattr(mixed, opname)(axis=axis, bool_only=bool_only)
+
+ @pytest.mark.parametrize("opname", ["any", "all"])
+ @pytest.mark.parametrize("axis", [0, 1])
+ def test_any_all_bool_with_na(self, opname, axis, bool_frame_with_na):
+ getattr(bool_frame_with_na, opname)(axis=axis, bool_only=False)
+
+ @pytest.mark.parametrize("opname", ["any", "all"])
+ def test_any_all_bool_frame(self, opname, bool_frame_with_na):
+ # GH#12863: numpy gives back non-boolean data for object type
+ # so fill NaNs to compare with pandas behavior
+ frame = bool_frame_with_na.fillna(True)
+ alternative = getattr(np, opname)
+ f = getattr(frame, opname)
+
+ def skipna_wrapper(x):
+ nona = x.dropna().values
+ return alternative(nona)
+
+ def wrapper(x):
+ return alternative(x.values)
+
+ result0 = f(axis=0, skipna=False)
+ result1 = f(axis=1, skipna=False)
+
+ tm.assert_series_equal(result0, frame.apply(wrapper))
+ tm.assert_series_equal(result1, frame.apply(wrapper, axis=1))
+
+ result0 = f(axis=0)
+ result1 = f(axis=1)
+
+ tm.assert_series_equal(result0, frame.apply(skipna_wrapper))
+ tm.assert_series_equal(
+ result1, frame.apply(skipna_wrapper, axis=1), check_dtype=False
+ )
+
+ # bad axis
+ with pytest.raises(ValueError, match="No axis named 2"):
+ f(axis=2)
+
+ # all NA case
+ all_na = frame * np.nan
+ r0 = getattr(all_na, opname)(axis=0)
+ r1 = getattr(all_na, opname)(axis=1)
+ if opname == "any":
+ assert not r0.any()
+ assert not r1.any()
+ else:
+ assert r0.all()
+ assert r1.all()
+
+ def test_any_all_extra(self):
+ df = DataFrame(
+ {
+ "A": [True, False, False],
+ "B": [True, True, False],
+ "C": [True, True, True],
+ },
+ index=["a", "b", "c"],
+ )
+ result = df[["A", "B"]].any(axis=1)
+ expected = Series([True, True, False], index=["a", "b", "c"])
+ tm.assert_series_equal(result, expected)
+
+ result = df[["A", "B"]].any(axis=1, bool_only=True)
+ tm.assert_series_equal(result, expected)
+
+ result = df.all(1)
+ expected = Series([True, False, False], index=["a", "b", "c"])
+ tm.assert_series_equal(result, expected)
+
+ result = df.all(1, bool_only=True)
+ tm.assert_series_equal(result, expected)
+
+ # Axis is None
+ result = df.all(axis=None).item()
+ assert result is False
+
+ result = df.any(axis=None).item()
+ assert result is True
+
+ result = df[["C"]].all(axis=None).item()
+ assert result is True
+
+ @pytest.mark.parametrize("axis", [0, 1])
+ @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_any_all_object_dtype(self, axis, bool_agg_func, skipna):
+ # GH#35450
+ df = DataFrame(
+ data=[
+ [1, np.nan, np.nan, True],
+ [np.nan, 2, np.nan, True],
+ [np.nan, np.nan, np.nan, True],
+ [np.nan, np.nan, "5", np.nan],
+ ]
+ )
+ result = getattr(df, bool_agg_func)(axis=axis, skipna=skipna)
+ expected = Series([True, True, True, True])
+ tm.assert_series_equal(result, expected)
+
+ # GH#50947 deprecates this but it is not emitting a warning in some builds.
+ @pytest.mark.filterwarnings(
+ "ignore:'any' with datetime64 dtypes is deprecated.*:FutureWarning"
+ )
+ def test_any_datetime(self):
+ # GH 23070
+ float_data = [1, np.nan, 3, np.nan]
+ datetime_data = [
+ Timestamp("1960-02-15"),
+ Timestamp("1960-02-16"),
+ pd.NaT,
+ pd.NaT,
+ ]
+ df = DataFrame({"A": float_data, "B": datetime_data})
+
+ result = df.any(axis=1)
+
+ expected = Series([True, True, True, False])
+ tm.assert_series_equal(result, expected)
+
+ def test_any_all_bool_only(self):
+ # GH 25101
+ df = DataFrame(
+ {"col1": [1, 2, 3], "col2": [4, 5, 6], "col3": [None, None, None]}
+ )
+
+ result = df.all(bool_only=True)
+ expected = Series(dtype=np.bool_, index=[])
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame(
+ {
+ "col1": [1, 2, 3],
+ "col2": [4, 5, 6],
+ "col3": [None, None, None],
+ "col4": [False, False, True],
+ }
+ )
+
+ result = df.all(bool_only=True)
+ expected = Series({"col4": False})
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "func, data, expected",
+ [
+ (np.any, {}, False),
+ (np.all, {}, True),
+ (np.any, {"A": []}, False),
+ (np.all, {"A": []}, True),
+ (np.any, {"A": [False, False]}, False),
+ (np.all, {"A": [False, False]}, False),
+ (np.any, {"A": [True, False]}, True),
+ (np.all, {"A": [True, False]}, False),
+ (np.any, {"A": [True, True]}, True),
+ (np.all, {"A": [True, True]}, True),
+ (np.any, {"A": [False], "B": [False]}, False),
+ (np.all, {"A": [False], "B": [False]}, False),
+ (np.any, {"A": [False, False], "B": [False, True]}, True),
+ (np.all, {"A": [False, False], "B": [False, True]}, False),
+ # other types
+ (np.all, {"A": Series([0.0, 1.0], dtype="float")}, False),
+ (np.any, {"A": Series([0.0, 1.0], dtype="float")}, True),
+ (np.all, {"A": Series([0, 1], dtype=int)}, False),
+ (np.any, {"A": Series([0, 1], dtype=int)}, True),
+ pytest.param(np.all, {"A": Series([0, 1], dtype="M8[ns]")}, False),
+ pytest.param(np.all, {"A": Series([0, 1], dtype="M8[ns, UTC]")}, False),
+ pytest.param(np.any, {"A": Series([0, 1], dtype="M8[ns]")}, True),
+ pytest.param(np.any, {"A": Series([0, 1], dtype="M8[ns, UTC]")}, True),
+ pytest.param(np.all, {"A": Series([1, 2], dtype="M8[ns]")}, True),
+ pytest.param(np.all, {"A": Series([1, 2], dtype="M8[ns, UTC]")}, True),
+ pytest.param(np.any, {"A": Series([1, 2], dtype="M8[ns]")}, True),
+ pytest.param(np.any, {"A": Series([1, 2], dtype="M8[ns, UTC]")}, True),
+ pytest.param(np.all, {"A": Series([0, 1], dtype="m8[ns]")}, False),
+ pytest.param(np.any, {"A": Series([0, 1], dtype="m8[ns]")}, True),
+ pytest.param(np.all, {"A": Series([1, 2], dtype="m8[ns]")}, True),
+ pytest.param(np.any, {"A": Series([1, 2], dtype="m8[ns]")}, True),
+ # np.all on Categorical raises, so the reduction drops the
+ # column, so all is being done on an empty Series, so is True
+ (np.all, {"A": Series([0, 1], dtype="category")}, True),
+ (np.any, {"A": Series([0, 1], dtype="category")}, False),
+ (np.all, {"A": Series([1, 2], dtype="category")}, True),
+ (np.any, {"A": Series([1, 2], dtype="category")}, False),
+ # Mix GH#21484
+ pytest.param(
+ np.all,
+ {
+ "A": Series([10, 20], dtype="M8[ns]"),
+ "B": Series([10, 20], dtype="m8[ns]"),
+ },
+ True,
+ ),
+ ],
+ )
+ def test_any_all_np_func(self, func, data, expected):
+ # GH 19976
+ data = DataFrame(data)
+
+ if any(isinstance(x, CategoricalDtype) for x in data.dtypes):
+ with pytest.raises(
+ TypeError, match="dtype category does not support reduction"
+ ):
+ func(data)
+
+ # method version
+ with pytest.raises(
+ TypeError, match="dtype category does not support reduction"
+ ):
+ getattr(DataFrame(data), func.__name__)(axis=None)
+ else:
+ msg = "'(any|all)' with datetime64 dtypes is deprecated"
+ if data.dtypes.apply(lambda x: x.kind == "M").any():
+ warn = FutureWarning
+ else:
+ warn = None
+
+ with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False):
+ # GH#34479
+ result = func(data)
+ assert isinstance(result, np.bool_)
+ assert result.item() is expected
+
+ # method version
+ with tm.assert_produces_warning(warn, match=msg):
+ # GH#34479
+ result = getattr(DataFrame(data), func.__name__)(axis=None)
+ assert isinstance(result, np.bool_)
+ assert result.item() is expected
+
+ def test_any_all_object(self):
+ # GH 19976
+ result = np.all(DataFrame(columns=["a", "b"])).item()
+ assert result is True
+
+ result = np.any(DataFrame(columns=["a", "b"])).item()
+ assert result is False
+
+ def test_any_all_object_bool_only(self):
+ df = DataFrame({"A": ["foo", 2], "B": [True, False]}).astype(object)
+ df._consolidate_inplace()
+ df["C"] = Series([True, True])
+
+ # Categorical of bools is _not_ considered booly
+ df["D"] = df["C"].astype("category")
+
+ # The underlying bug is in DataFrame._get_bool_data, so we check
+ # that while we're here
+ res = df._get_bool_data()
+ expected = df[["C"]]
+ tm.assert_frame_equal(res, expected)
+
+ res = df.all(bool_only=True, axis=0)
+ expected = Series([True], index=["C"])
+ tm.assert_series_equal(res, expected)
+
+ # operating on a subset of columns should not produce a _larger_ Series
+ res = df[["B", "C"]].all(bool_only=True, axis=0)
+ tm.assert_series_equal(res, expected)
+
+ assert df.all(bool_only=True, axis=None)
+
+ res = df.any(bool_only=True, axis=0)
+ expected = Series([True], index=["C"])
+ tm.assert_series_equal(res, expected)
+
+ # operating on a subset of columns should not produce a _larger_ Series
+ res = df[["C"]].any(bool_only=True, axis=0)
+ tm.assert_series_equal(res, expected)
+
+ assert df.any(bool_only=True, axis=None)
+
+ # ---------------------------------------------------------------------
+ # Unsorted
+
+ def test_series_broadcasting(self):
+ # smoke test for numpy warnings
+ # GH 16378, GH 16306
+ df = DataFrame([1.0, 1.0, 1.0])
+ df_nan = DataFrame({"A": [np.nan, 2.0, np.nan]})
+ s = Series([1, 1, 1])
+ s_nan = Series([np.nan, np.nan, 1])
+
+ with tm.assert_produces_warning(None):
+ df_nan.clip(lower=s, axis=0)
+ for op in ["lt", "le", "gt", "ge", "eq", "ne"]:
+ getattr(df, op)(s_nan, axis=0)
+
+
+class TestDataFrameReductions:
+ def test_min_max_dt64_with_NaT(self):
+ # Both NaT and Timestamp are in DataFrame.
+ df = DataFrame({"foo": [pd.NaT, pd.NaT, Timestamp("2012-05-01")]})
+
+ res = df.min()
+ exp = Series([Timestamp("2012-05-01")], index=["foo"])
+ tm.assert_series_equal(res, exp)
+
+ res = df.max()
+ exp = Series([Timestamp("2012-05-01")], index=["foo"])
+ tm.assert_series_equal(res, exp)
+
+ # GH12941, only NaTs are in DataFrame.
+ df = DataFrame({"foo": [pd.NaT, pd.NaT]})
+
+ res = df.min()
+ exp = Series([pd.NaT], index=["foo"])
+ tm.assert_series_equal(res, exp)
+
+ res = df.max()
+ exp = Series([pd.NaT], index=["foo"])
+ tm.assert_series_equal(res, exp)
+
+ def test_min_max_dt64_with_NaT_skipna_false(self, request, tz_naive_fixture):
+ # GH#36907
+ tz = tz_naive_fixture
+ if isinstance(tz, tzlocal) and is_platform_windows():
+ pytest.skip(
+ "GH#37659 OSError raised within tzlocal bc Windows "
+ "chokes in times before 1970-01-01"
+ )
+
+ df = DataFrame(
+ {
+ "a": [
+ Timestamp("2020-01-01 08:00:00", tz=tz),
+ Timestamp("1920-02-01 09:00:00", tz=tz),
+ ],
+ "b": [Timestamp("2020-02-01 08:00:00", tz=tz), pd.NaT],
+ }
+ )
+ res = df.min(axis=1, skipna=False)
+ expected = Series([df.loc[0, "a"], pd.NaT])
+ assert expected.dtype == df["a"].dtype
+
+ tm.assert_series_equal(res, expected)
+
+ res = df.max(axis=1, skipna=False)
+ expected = Series([df.loc[0, "b"], pd.NaT])
+ assert expected.dtype == df["a"].dtype
+
+ tm.assert_series_equal(res, expected)
+
+ def test_min_max_dt64_api_consistency_with_NaT(self):
+ # Calling the following sum functions returned an error for dataframes but
+ # returned NaT for series. These tests check that the API is consistent in
+ # min/max calls on empty Series/DataFrames. See GH:33704 for more
+ # information
+ df = DataFrame({"x": to_datetime([])})
+ expected_dt_series = Series(to_datetime([]))
+ # check axis 0
+ assert (df.min(axis=0).x is pd.NaT) == (expected_dt_series.min() is pd.NaT)
+ assert (df.max(axis=0).x is pd.NaT) == (expected_dt_series.max() is pd.NaT)
+
+ # check axis 1
+ tm.assert_series_equal(df.min(axis=1), expected_dt_series)
+ tm.assert_series_equal(df.max(axis=1), expected_dt_series)
+
+ def test_min_max_dt64_api_consistency_empty_df(self):
+ # check DataFrame/Series api consistency when calling min/max on an empty
+ # DataFrame/Series.
+ df = DataFrame({"x": []})
+ expected_float_series = Series([], dtype=float)
+ # check axis 0
+ assert np.isnan(df.min(axis=0).x) == np.isnan(expected_float_series.min())
+ assert np.isnan(df.max(axis=0).x) == np.isnan(expected_float_series.max())
+ # check axis 1
+ tm.assert_series_equal(df.min(axis=1), expected_float_series)
+ tm.assert_series_equal(df.min(axis=1), expected_float_series)
+
+ @pytest.mark.parametrize(
+ "initial",
+ ["2018-10-08 13:36:45+00:00", "2018-10-08 13:36:45+03:00"], # Non-UTC timezone
+ )
+ @pytest.mark.parametrize("method", ["min", "max"])
+ def test_preserve_timezone(self, initial: str, method):
+ # GH 28552
+ initial_dt = to_datetime(initial)
+ expected = Series([initial_dt])
+ df = DataFrame([expected])
+ result = getattr(df, method)(axis=1)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("method", ["min", "max"])
+ def test_minmax_tzaware_skipna_axis_1(self, method, skipna):
+ # GH#51242
+ val = to_datetime("1900-01-01", utc=True)
+ df = DataFrame(
+ {"a": Series([pd.NaT, pd.NaT, val]), "b": Series([pd.NaT, val, val])}
+ )
+ op = getattr(df, method)
+ result = op(axis=1, skipna=skipna)
+ if skipna:
+ expected = Series([pd.NaT, val, val])
+ else:
+ expected = Series([pd.NaT, pd.NaT, val])
+ tm.assert_series_equal(result, expected)
+
+ def test_frame_any_with_timedelta(self):
+ # GH#17667
+ df = DataFrame(
+ {
+ "a": Series([0, 0]),
+ "t": Series([to_timedelta(0, "s"), to_timedelta(1, "ms")]),
+ }
+ )
+
+ result = df.any(axis=0)
+ expected = Series(data=[False, True], index=["a", "t"])
+ tm.assert_series_equal(result, expected)
+
+ result = df.any(axis=1)
+ expected = Series(data=[False, True])
+ tm.assert_series_equal(result, expected)
+
+ def test_reductions_skipna_none_raises(
+ self, request, frame_or_series, all_reductions
+ ):
+ if all_reductions == "count":
+ request.node.add_marker(
+ pytest.mark.xfail(reason="Count does not accept skipna")
+ )
+ obj = frame_or_series([1, 2, 3])
+ msg = 'For argument "skipna" expected type bool, received type NoneType.'
+ with pytest.raises(ValueError, match=msg):
+ getattr(obj, all_reductions)(skipna=None)
+
+ @td.skip_array_manager_invalid_test
+ def test_reduction_timestamp_smallest_unit(self):
+ # GH#52524
+ df = DataFrame(
+ {
+ "a": Series([Timestamp("2019-12-31")], dtype="datetime64[s]"),
+ "b": Series(
+ [Timestamp("2019-12-31 00:00:00.123")], dtype="datetime64[ms]"
+ ),
+ }
+ )
+ result = df.max()
+ expected = Series(
+ [Timestamp("2019-12-31"), Timestamp("2019-12-31 00:00:00.123")],
+ dtype="datetime64[ms]",
+ index=["a", "b"],
+ )
+ tm.assert_series_equal(result, expected)
+
+ @td.skip_array_manager_not_yet_implemented
+ def test_reduction_timedelta_smallest_unit(self):
+ # GH#52524
+ df = DataFrame(
+ {
+ "a": Series([pd.Timedelta("1 days")], dtype="timedelta64[s]"),
+ "b": Series([pd.Timedelta("1 days")], dtype="timedelta64[ms]"),
+ }
+ )
+ result = df.max()
+ expected = Series(
+ [pd.Timedelta("1 days"), pd.Timedelta("1 days")],
+ dtype="timedelta64[ms]",
+ index=["a", "b"],
+ )
+ tm.assert_series_equal(result, expected)
+
+
+class TestNuisanceColumns:
+ @pytest.mark.parametrize("method", ["any", "all"])
+ def test_any_all_categorical_dtype_nuisance_column(self, method):
+ # GH#36076 DataFrame should match Series behavior
+ ser = Series([0, 1], dtype="category", name="A")
+ df = ser.to_frame()
+
+ # Double-check the Series behavior is to raise
+ with pytest.raises(TypeError, match="does not support reduction"):
+ getattr(ser, method)()
+
+ with pytest.raises(TypeError, match="does not support reduction"):
+ getattr(np, method)(ser)
+
+ with pytest.raises(TypeError, match="does not support reduction"):
+ getattr(df, method)(bool_only=False)
+
+ with pytest.raises(TypeError, match="does not support reduction"):
+ getattr(df, method)(bool_only=None)
+
+ with pytest.raises(TypeError, match="does not support reduction"):
+ getattr(np, method)(df, axis=0)
+
+ def test_median_categorical_dtype_nuisance_column(self):
+ # GH#21020 DataFrame.median should match Series.median
+ df = DataFrame({"A": Categorical([1, 2, 2, 2, 3])})
+ ser = df["A"]
+
+ # Double-check the Series behavior is to raise
+ with pytest.raises(TypeError, match="does not support reduction"):
+ ser.median()
+
+ with pytest.raises(TypeError, match="does not support reduction"):
+ df.median(numeric_only=False)
+
+ with pytest.raises(TypeError, match="does not support reduction"):
+ df.median()
+
+ # same thing, but with an additional non-categorical column
+ df["B"] = df["A"].astype(int)
+
+ with pytest.raises(TypeError, match="does not support reduction"):
+ df.median(numeric_only=False)
+
+ with pytest.raises(TypeError, match="does not support reduction"):
+ df.median()
+
+ # TODO: np.median(df, axis=0) gives np.array([2.0, 2.0]) instead
+ # of expected.values
+
+ @pytest.mark.parametrize("method", ["min", "max"])
+ def test_min_max_categorical_dtype_non_ordered_nuisance_column(self, method):
+ # GH#28949 DataFrame.min should behave like Series.min
+ cat = Categorical(["a", "b", "c", "b"], ordered=False)
+ ser = Series(cat)
+ df = ser.to_frame("A")
+
+ # Double-check the Series behavior
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(ser, method)()
+
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(np, method)(ser)
+
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(df, method)(numeric_only=False)
+
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(df, method)()
+
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(np, method)(df, axis=0)
+
+ # same thing, but with an additional non-categorical column
+ df["B"] = df["A"].astype(object)
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(df, method)()
+
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(np, method)(df, axis=0)
+
+
+class TestEmptyDataFrameReductions:
+ @pytest.mark.parametrize(
+ "opname, dtype, exp_value, exp_dtype",
+ [
+ ("sum", np.int8, 0, np.int64),
+ ("prod", np.int8, 1, np.int_),
+ ("sum", np.int64, 0, np.int64),
+ ("prod", np.int64, 1, np.int64),
+ ("sum", np.uint8, 0, np.uint64),
+ ("prod", np.uint8, 1, np.uint),
+ ("sum", np.uint64, 0, np.uint64),
+ ("prod", np.uint64, 1, np.uint64),
+ ("sum", np.float32, 0, np.float32),
+ ("prod", np.float32, 1, np.float32),
+ ("sum", np.float64, 0, np.float64),
+ ],
+ )
+ def test_df_empty_min_count_0(self, opname, dtype, exp_value, exp_dtype):
+ df = DataFrame({0: [], 1: []}, dtype=dtype)
+ result = getattr(df, opname)(min_count=0)
+
+ expected = Series([exp_value, exp_value], dtype=exp_dtype)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "opname, dtype, exp_dtype",
+ [
+ ("sum", np.int8, np.float64),
+ ("prod", np.int8, np.float64),
+ ("sum", np.int64, np.float64),
+ ("prod", np.int64, np.float64),
+ ("sum", np.uint8, np.float64),
+ ("prod", np.uint8, np.float64),
+ ("sum", np.uint64, np.float64),
+ ("prod", np.uint64, np.float64),
+ ("sum", np.float32, np.float32),
+ ("prod", np.float32, np.float32),
+ ("sum", np.float64, np.float64),
+ ],
+ )
+ def test_df_empty_min_count_1(self, opname, dtype, exp_dtype):
+ df = DataFrame({0: [], 1: []}, dtype=dtype)
+ result = getattr(df, opname)(min_count=1)
+
+ expected = Series([np.nan, np.nan], dtype=exp_dtype)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "opname, dtype, exp_value, exp_dtype",
+ [
+ ("sum", "Int8", 0, ("Int32" if is_windows_np2_or_is32 else "Int64")),
+ ("prod", "Int8", 1, ("Int32" if is_windows_np2_or_is32 else "Int64")),
+ ("prod", "Int8", 1, ("Int32" if is_windows_np2_or_is32 else "Int64")),
+ ("sum", "Int64", 0, "Int64"),
+ ("prod", "Int64", 1, "Int64"),
+ ("sum", "UInt8", 0, ("UInt32" if is_windows_np2_or_is32 else "UInt64")),
+ ("prod", "UInt8", 1, ("UInt32" if is_windows_np2_or_is32 else "UInt64")),
+ ("sum", "UInt64", 0, "UInt64"),
+ ("prod", "UInt64", 1, "UInt64"),
+ ("sum", "Float32", 0, "Float32"),
+ ("prod", "Float32", 1, "Float32"),
+ ("sum", "Float64", 0, "Float64"),
+ ],
+ )
+ def test_df_empty_nullable_min_count_0(self, opname, dtype, exp_value, exp_dtype):
+ df = DataFrame({0: [], 1: []}, dtype=dtype)
+ result = getattr(df, opname)(min_count=0)
+
+ expected = Series([exp_value, exp_value], dtype=exp_dtype)
+ tm.assert_series_equal(result, expected)
+
+ # TODO: why does min_count=1 impact the resulting Windows dtype
+ # differently than min_count=0?
+ @pytest.mark.parametrize(
+ "opname, dtype, exp_dtype",
+ [
+ ("sum", "Int8", ("Int32" if is_windows_or_is32 else "Int64")),
+ ("prod", "Int8", ("Int32" if is_windows_or_is32 else "Int64")),
+ ("sum", "Int64", "Int64"),
+ ("prod", "Int64", "Int64"),
+ ("sum", "UInt8", ("UInt32" if is_windows_or_is32 else "UInt64")),
+ ("prod", "UInt8", ("UInt32" if is_windows_or_is32 else "UInt64")),
+ ("sum", "UInt64", "UInt64"),
+ ("prod", "UInt64", "UInt64"),
+ ("sum", "Float32", "Float32"),
+ ("prod", "Float32", "Float32"),
+ ("sum", "Float64", "Float64"),
+ ],
+ )
+ def test_df_empty_nullable_min_count_1(self, opname, dtype, exp_dtype):
+ df = DataFrame({0: [], 1: []}, dtype=dtype)
+ result = getattr(df, opname)(min_count=1)
+
+ expected = Series([pd.NA, pd.NA], dtype=exp_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_sum_timedelta64_skipna_false(using_array_manager, request):
+ # GH#17235
+ if using_array_manager:
+ mark = pytest.mark.xfail(
+ reason="Incorrect type inference on NaT in reduction result"
+ )
+ request.node.add_marker(mark)
+
+ arr = np.arange(8).astype(np.int64).view("m8[s]").reshape(4, 2)
+ arr[-1, -1] = "Nat"
+
+ df = DataFrame(arr)
+ assert (df.dtypes == arr.dtype).all()
+
+ result = df.sum(skipna=False)
+ expected = Series([pd.Timedelta(seconds=12), pd.NaT], dtype="m8[s]")
+ tm.assert_series_equal(result, expected)
+
+ result = df.sum(axis=0, skipna=False)
+ tm.assert_series_equal(result, expected)
+
+ result = df.sum(axis=1, skipna=False)
+ expected = Series(
+ [
+ pd.Timedelta(seconds=1),
+ pd.Timedelta(seconds=5),
+ pd.Timedelta(seconds=9),
+ pd.NaT,
+ ],
+ dtype="m8[s]",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_mixed_frame_with_integer_sum():
+ # https://github.com/pandas-dev/pandas/issues/34520
+ df = DataFrame([["a", 1]], columns=list("ab"))
+ df = df.astype({"b": "Int64"})
+ result = df.sum()
+ expected = Series(["a", 1], index=["a", "b"])
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("numeric_only", [True, False, None])
+@pytest.mark.parametrize("method", ["min", "max"])
+def test_minmax_extensionarray(method, numeric_only):
+ # https://github.com/pandas-dev/pandas/issues/32651
+ int64_info = np.iinfo("int64")
+ ser = Series([int64_info.max, None, int64_info.min], dtype=pd.Int64Dtype())
+ df = DataFrame({"Int64": ser})
+ result = getattr(df, method)(numeric_only=numeric_only)
+ expected = Series(
+ [getattr(int64_info, method)],
+ dtype="Int64",
+ index=Index(["Int64"], dtype="object"),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("ts_value", [Timestamp("2000-01-01"), pd.NaT])
+def test_frame_mixed_numeric_object_with_timestamp(ts_value):
+ # GH 13912
+ df = DataFrame({"a": [1], "b": [1.1], "c": ["foo"], "d": [ts_value]})
+ with pytest.raises(TypeError, match="does not support reduction"):
+ df.sum()
+
+
+def test_prod_sum_min_count_mixed_object():
+ # https://github.com/pandas-dev/pandas/issues/41074
+ df = DataFrame([1, "a", True])
+
+ result = df.prod(axis=0, min_count=1, numeric_only=False)
+ expected = Series(["a"])
+ tm.assert_series_equal(result, expected)
+
+ msg = re.escape("unsupported operand type(s) for +: 'int' and 'str'")
+ with pytest.raises(TypeError, match=msg):
+ df.sum(axis=0, min_count=1, numeric_only=False)
+
+
+@pytest.mark.parametrize("method", ["min", "max", "mean", "median", "skew", "kurt"])
+@pytest.mark.parametrize("numeric_only", [True, False])
+@pytest.mark.parametrize("dtype", ["float64", "Float64"])
+def test_reduction_axis_none_returns_scalar(method, numeric_only, dtype):
+ # GH#21597 As of 2.0, axis=None reduces over all axes.
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((4, 4)), dtype=dtype)
+
+ result = getattr(df, method)(axis=None, numeric_only=numeric_only)
+ np_arr = df.to_numpy(dtype=np.float64)
+ if method in {"skew", "kurt"}:
+ comp_mod = pytest.importorskip("scipy.stats")
+ if method == "kurt":
+ method = "kurtosis"
+ expected = getattr(comp_mod, method)(np_arr, bias=False, axis=None)
+ tm.assert_almost_equal(result, expected)
+ else:
+ expected = getattr(np, method)(np_arr, axis=None)
+ assert result == expected
+
+
+@pytest.mark.parametrize(
+ "kernel",
+ [
+ "corr",
+ "corrwith",
+ "cov",
+ "idxmax",
+ "idxmin",
+ "kurt",
+ "max",
+ "mean",
+ "median",
+ "min",
+ "prod",
+ "quantile",
+ "sem",
+ "skew",
+ "std",
+ "sum",
+ "var",
+ ],
+)
+def test_fails_on_non_numeric(kernel):
+ # GH#46852
+ df = DataFrame({"a": [1, 2, 3], "b": object})
+ args = (df,) if kernel == "corrwith" else ()
+ msg = "|".join(
+ [
+ "not allowed for this dtype",
+ "argument must be a string or a number",
+ "not supported between instances of",
+ "unsupported operand type",
+ "argument must be a string or a real number",
+ ]
+ )
+ if kernel == "median":
+ # slightly different message on different builds
+ msg1 = (
+ r"Cannot convert \[\[ "
+ r"\]\] to numeric"
+ )
+ msg2 = (
+ r"Cannot convert \[ "
+ r"\] to numeric"
+ )
+ msg = "|".join([msg1, msg2])
+ with pytest.raises(TypeError, match=msg):
+ getattr(df, kernel)(*args)
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ "all",
+ "any",
+ "count",
+ "idxmax",
+ "idxmin",
+ "kurt",
+ "kurtosis",
+ "max",
+ "mean",
+ "median",
+ "min",
+ "nunique",
+ "prod",
+ "product",
+ "sem",
+ "skew",
+ "std",
+ "sum",
+ "var",
+ ],
+)
+@pytest.mark.parametrize("min_count", [0, 2])
+def test_numeric_ea_axis_1(method, skipna, min_count, any_numeric_ea_dtype):
+ # GH 54341
+ df = DataFrame(
+ {
+ "a": Series([0, 1, 2, 3], dtype=any_numeric_ea_dtype),
+ "b": Series([0, 1, pd.NA, 3], dtype=any_numeric_ea_dtype),
+ },
+ )
+ expected_df = DataFrame(
+ {
+ "a": [0.0, 1.0, 2.0, 3.0],
+ "b": [0.0, 1.0, np.nan, 3.0],
+ },
+ )
+ if method in ("count", "nunique"):
+ expected_dtype = "int64"
+ elif method in ("all", "any"):
+ expected_dtype = "boolean"
+ elif method in (
+ "kurt",
+ "kurtosis",
+ "mean",
+ "median",
+ "sem",
+ "skew",
+ "std",
+ "var",
+ ) and not any_numeric_ea_dtype.startswith("Float"):
+ expected_dtype = "Float64"
+ else:
+ expected_dtype = any_numeric_ea_dtype
+
+ kwargs = {}
+ if method not in ("count", "nunique", "quantile"):
+ kwargs["skipna"] = skipna
+ if method in ("prod", "product", "sum"):
+ kwargs["min_count"] = min_count
+
+ warn = None
+ msg = None
+ if not skipna and method in ("idxmax", "idxmin"):
+ warn = FutureWarning
+ msg = f"The behavior of DataFrame.{method} with all-NA values"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = getattr(df, method)(axis=1, **kwargs)
+ with tm.assert_produces_warning(warn, match=msg):
+ expected = getattr(expected_df, method)(axis=1, **kwargs)
+ if method not in ("idxmax", "idxmin"):
+ expected = expected.astype(expected_dtype)
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_repr_info.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_repr_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..64d516e48499155e528bf3854c2a8a6f24e476de
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_repr_info.py
@@ -0,0 +1,468 @@
+from datetime import (
+ datetime,
+ timedelta,
+)
+from io import StringIO
+
+import numpy as np
+import pytest
+
+from pandas import (
+ NA,
+ Categorical,
+ DataFrame,
+ MultiIndex,
+ NaT,
+ PeriodIndex,
+ Series,
+ Timestamp,
+ date_range,
+ option_context,
+ period_range,
+)
+import pandas._testing as tm
+
+import pandas.io.formats.format as fmt
+
+
+class TestDataFrameReprInfoEtc:
+ def test_repr_bytes_61_lines(self):
+ # GH#12857
+ lets = list("ACDEFGHIJKLMNOP")
+ slen = 50
+ nseqs = 1000
+ words = [
+ [np.random.default_rng(2).choice(lets) for x in range(slen)]
+ for _ in range(nseqs)
+ ]
+ df = DataFrame(words).astype("U1")
+ assert (df.dtypes == object).all()
+
+ # smoke tests; at one point this raised with 61 but not 60
+ repr(df)
+ repr(df.iloc[:60, :])
+ repr(df.iloc[:61, :])
+
+ def test_repr_unicode_level_names(self, frame_or_series):
+ index = MultiIndex.from_tuples([(0, 0), (1, 1)], names=["\u0394", "i1"])
+
+ obj = DataFrame(np.random.default_rng(2).standard_normal((2, 4)), index=index)
+ obj = tm.get_obj(obj, frame_or_series)
+ repr(obj)
+
+ def test_assign_index_sequences(self):
+ # GH#2200
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}).set_index(
+ ["a", "b"]
+ )
+ index = list(df.index)
+ index[0] = ("faz", "boo")
+ df.index = index
+ repr(df)
+
+ # this travels an improper code path
+ index[0] = ["faz", "boo"]
+ df.index = index
+ repr(df)
+
+ def test_repr_with_mi_nat(self):
+ df = DataFrame({"X": [1, 2]}, index=[[NaT, Timestamp("20130101")], ["a", "b"]])
+ result = repr(df)
+ expected = " X\nNaT a 1\n2013-01-01 b 2"
+ assert result == expected
+
+ def test_repr_with_different_nulls(self):
+ # GH45263
+ df = DataFrame([1, 2, 3, 4], [True, None, np.nan, NaT])
+ result = repr(df)
+ expected = """ 0
+True 1
+None 2
+NaN 3
+NaT 4"""
+ assert result == expected
+
+ def test_repr_with_different_nulls_cols(self):
+ # GH45263
+ d = {np.nan: [1, 2], None: [3, 4], NaT: [6, 7], True: [8, 9]}
+ df = DataFrame(data=d)
+ result = repr(df)
+ expected = """ NaN None NaT True
+0 1 3 6 8
+1 2 4 7 9"""
+ assert result == expected
+
+ def test_multiindex_na_repr(self):
+ # only an issue with long columns
+ df3 = DataFrame(
+ {
+ "A" * 30: {("A", "A0006000", "nuit"): "A0006000"},
+ "B" * 30: {("A", "A0006000", "nuit"): np.nan},
+ "C" * 30: {("A", "A0006000", "nuit"): np.nan},
+ "D" * 30: {("A", "A0006000", "nuit"): np.nan},
+ "E" * 30: {("A", "A0006000", "nuit"): "A"},
+ "F" * 30: {("A", "A0006000", "nuit"): np.nan},
+ }
+ )
+
+ idf = df3.set_index(["A" * 30, "C" * 30])
+ repr(idf)
+
+ def test_repr_name_coincide(self):
+ index = MultiIndex.from_tuples(
+ [("a", 0, "foo"), ("b", 1, "bar")], names=["a", "b", "c"]
+ )
+
+ df = DataFrame({"value": [0, 1]}, index=index)
+
+ lines = repr(df).split("\n")
+ assert lines[2].startswith("a 0 foo")
+
+ def test_repr_to_string(
+ self,
+ multiindex_year_month_day_dataframe_random_data,
+ multiindex_dataframe_random_data,
+ ):
+ ymd = multiindex_year_month_day_dataframe_random_data
+ frame = multiindex_dataframe_random_data
+
+ repr(frame)
+ repr(ymd)
+ repr(frame.T)
+ repr(ymd.T)
+
+ buf = StringIO()
+ frame.to_string(buf=buf)
+ ymd.to_string(buf=buf)
+ frame.T.to_string(buf=buf)
+ ymd.T.to_string(buf=buf)
+
+ def test_repr_empty(self):
+ # empty
+ repr(DataFrame())
+
+ # empty with index
+ frame = DataFrame(index=np.arange(1000))
+ repr(frame)
+
+ def test_repr_mixed(self, float_string_frame):
+ buf = StringIO()
+
+ # mixed
+ repr(float_string_frame)
+ float_string_frame.info(verbose=False, buf=buf)
+
+ @pytest.mark.slow
+ def test_repr_mixed_big(self):
+ # big mixed
+ biggie = DataFrame(
+ {
+ "A": np.random.default_rng(2).standard_normal(200),
+ "B": tm.makeStringIndex(200),
+ },
+ index=range(200),
+ )
+ biggie.loc[:20, "A"] = np.nan
+ biggie.loc[:20, "B"] = np.nan
+
+ repr(biggie)
+
+ def test_repr(self, float_frame):
+ buf = StringIO()
+
+ # small one
+ repr(float_frame)
+ float_frame.info(verbose=False, buf=buf)
+
+ # even smaller
+ float_frame.reindex(columns=["A"]).info(verbose=False, buf=buf)
+ float_frame.reindex(columns=["A", "B"]).info(verbose=False, buf=buf)
+
+ # exhausting cases in DataFrame.info
+
+ # columns but no index
+ no_index = DataFrame(columns=[0, 1, 3])
+ repr(no_index)
+
+ # no columns or index
+ DataFrame().info(buf=buf)
+
+ df = DataFrame(["a\n\r\tb"], columns=["a\n\r\td"], index=["a\n\r\tf"])
+ assert "\t" not in repr(df)
+ assert "\r" not in repr(df)
+ assert "a\n" not in repr(df)
+
+ def test_repr_dimensions(self):
+ df = DataFrame([[1, 2], [3, 4]])
+ with option_context("display.show_dimensions", True):
+ assert "2 rows x 2 columns" in repr(df)
+
+ with option_context("display.show_dimensions", False):
+ assert "2 rows x 2 columns" not in repr(df)
+
+ with option_context("display.show_dimensions", "truncate"):
+ assert "2 rows x 2 columns" not in repr(df)
+
+ @pytest.mark.slow
+ def test_repr_big(self):
+ # big one
+ biggie = DataFrame(np.zeros((200, 4)), columns=range(4), index=range(200))
+ repr(biggie)
+
+ def test_repr_unsortable(self, float_frame):
+ # columns are not sortable
+
+ unsortable = DataFrame(
+ {
+ "foo": [1] * 50,
+ datetime.today(): [1] * 50,
+ "bar": ["bar"] * 50,
+ datetime.today() + timedelta(1): ["bar"] * 50,
+ },
+ index=np.arange(50),
+ )
+ repr(unsortable)
+
+ fmt.set_option("display.precision", 3)
+ repr(float_frame)
+
+ fmt.set_option("display.max_rows", 10, "display.max_columns", 2)
+ repr(float_frame)
+
+ fmt.set_option("display.max_rows", 1000, "display.max_columns", 1000)
+ repr(float_frame)
+
+ tm.reset_display_options()
+
+ def test_repr_unicode(self):
+ uval = "\u03c3\u03c3\u03c3\u03c3"
+
+ df = DataFrame({"A": [uval, uval]})
+
+ result = repr(df)
+ ex_top = " A"
+ assert result.split("\n")[0].rstrip() == ex_top
+
+ df = DataFrame({"A": [uval, uval]})
+ result = repr(df)
+ assert result.split("\n")[0].rstrip() == ex_top
+
+ def test_unicode_string_with_unicode(self):
+ df = DataFrame({"A": ["\u05d0"]})
+ str(df)
+
+ def test_repr_unicode_columns(self):
+ df = DataFrame({"\u05d0": [1, 2, 3], "\u05d1": [4, 5, 6], "c": [7, 8, 9]})
+ repr(df.columns) # should not raise UnicodeDecodeError
+
+ def test_str_to_bytes_raises(self):
+ # GH 26447
+ df = DataFrame({"A": ["abc"]})
+ msg = "^'str' object cannot be interpreted as an integer$"
+ with pytest.raises(TypeError, match=msg):
+ bytes(df)
+
+ def test_very_wide_info_repr(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 20)),
+ columns=np.array(["a" * 10] * 20, dtype=object),
+ )
+ repr(df)
+
+ def test_repr_column_name_unicode_truncation_bug(self):
+ # #1906
+ df = DataFrame(
+ {
+ "Id": [7117434],
+ "StringCol": (
+ "Is it possible to modify drop plot code"
+ "so that the output graph is displayed "
+ "in iphone simulator, Is it possible to "
+ "modify drop plot code so that the "
+ "output graph is \xe2\x80\xa8displayed "
+ "in iphone simulator.Now we are adding "
+ "the CSV file externally. I want to Call "
+ "the File through the code.."
+ ),
+ }
+ )
+
+ with option_context("display.max_columns", 20):
+ assert "StringCol" in repr(df)
+
+ def test_latex_repr(self):
+ pytest.importorskip("jinja2")
+ expected = r"""\begin{tabular}{llll}
+\toprule
+ & 0 & 1 & 2 \\
+\midrule
+0 & $\alpha$ & b & c \\
+1 & 1 & 2 & 3 \\
+\bottomrule
+\end{tabular}
+"""
+ with option_context(
+ "styler.format.escape", None, "styler.render.repr", "latex"
+ ):
+ df = DataFrame([[r"$\alpha$", "b", "c"], [1, 2, 3]])
+ result = df._repr_latex_()
+ assert result == expected
+
+ # GH 12182
+ assert df._repr_latex_() is None
+
+ def test_repr_categorical_dates_periods(self):
+ # normal DataFrame
+ dt = date_range("2011-01-01 09:00", freq="H", periods=5, tz="US/Eastern")
+ p = period_range("2011-01", freq="M", periods=5)
+ df = DataFrame({"dt": dt, "p": p})
+ exp = """ dt p
+0 2011-01-01 09:00:00-05:00 2011-01
+1 2011-01-01 10:00:00-05:00 2011-02
+2 2011-01-01 11:00:00-05:00 2011-03
+3 2011-01-01 12:00:00-05:00 2011-04
+4 2011-01-01 13:00:00-05:00 2011-05"""
+
+ assert repr(df) == exp
+
+ df2 = DataFrame({"dt": Categorical(dt), "p": Categorical(p)})
+ assert repr(df2) == exp
+
+ @pytest.mark.parametrize("arg", [np.datetime64, np.timedelta64])
+ @pytest.mark.parametrize(
+ "box, expected",
+ [[Series, "0 NaT\ndtype: object"], [DataFrame, " 0\n0 NaT"]],
+ )
+ def test_repr_np_nat_with_object(self, arg, box, expected):
+ # GH 25445
+ result = repr(box([arg("NaT")], dtype=object))
+ assert result == expected
+
+ def test_frame_datetime64_pre1900_repr(self):
+ df = DataFrame({"year": date_range("1/1/1700", periods=50, freq="A-DEC")})
+ # it works!
+ repr(df)
+
+ def test_frame_to_string_with_periodindex(self):
+ index = PeriodIndex(["2011-1", "2011-2", "2011-3"], freq="M")
+ frame = DataFrame(np.random.default_rng(2).standard_normal((3, 4)), index=index)
+
+ # it works!
+ frame.to_string()
+
+ def test_to_string_ea_na_in_multiindex(self):
+ # GH#47986
+ df = DataFrame(
+ {"a": [1, 2]},
+ index=MultiIndex.from_arrays([Series([NA, 1], dtype="Int64")]),
+ )
+
+ result = df.to_string()
+ expected = """ a
+ 1
+1 2"""
+ assert result == expected
+
+ def test_datetime64tz_slice_non_truncate(self):
+ # GH 30263
+ df = DataFrame({"x": date_range("2019", periods=10, tz="UTC")})
+ expected = repr(df)
+ df = df.iloc[:, :5]
+ result = repr(df)
+ assert result == expected
+
+ def test_to_records_no_typeerror_in_repr(self):
+ # GH 48526
+ df = DataFrame([["a", "b"], ["c", "d"], ["e", "f"]], columns=["left", "right"])
+ df["record"] = df[["left", "right"]].to_records()
+ expected = """ left right record
+0 a b [0, a, b]
+1 c d [1, c, d]
+2 e f [2, e, f]"""
+ result = repr(df)
+ assert result == expected
+
+ def test_to_records_with_na_record_value(self):
+ # GH 48526
+ df = DataFrame(
+ [["a", np.nan], ["c", "d"], ["e", "f"]], columns=["left", "right"]
+ )
+ df["record"] = df[["left", "right"]].to_records()
+ expected = """ left right record
+0 a NaN [0, a, nan]
+1 c d [1, c, d]
+2 e f [2, e, f]"""
+ result = repr(df)
+ assert result == expected
+
+ def test_to_records_with_na_record(self):
+ # GH 48526
+ df = DataFrame(
+ [["a", "b"], [np.nan, np.nan], ["e", "f"]], columns=[np.nan, "right"]
+ )
+ df["record"] = df[[np.nan, "right"]].to_records()
+ expected = """ NaN right record
+0 a b [0, a, b]
+1 NaN NaN [1, nan, nan]
+2 e f [2, e, f]"""
+ result = repr(df)
+ assert result == expected
+
+ def test_to_records_with_inf_as_na_record(self):
+ # GH 48526
+ expected = """ NaN inf record
+0 NaN b [0, inf, b]
+1 NaN NaN [1, nan, nan]
+2 e f [2, e, f]"""
+ msg = "use_inf_as_na option is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ with option_context("use_inf_as_na", True):
+ df = DataFrame(
+ [[np.inf, "b"], [np.nan, np.nan], ["e", "f"]],
+ columns=[np.nan, np.inf],
+ )
+ df["record"] = df[[np.nan, np.inf]].to_records()
+ result = repr(df)
+ assert result == expected
+
+ def test_to_records_with_inf_record(self):
+ # GH 48526
+ expected = """ NaN inf record
+0 inf b [0, inf, b]
+1 NaN NaN [1, nan, nan]
+2 e f [2, e, f]"""
+ msg = "use_inf_as_na option is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ with option_context("use_inf_as_na", False):
+ df = DataFrame(
+ [[np.inf, "b"], [np.nan, np.nan], ["e", "f"]],
+ columns=[np.nan, np.inf],
+ )
+ df["record"] = df[[np.nan, np.inf]].to_records()
+ result = repr(df)
+ assert result == expected
+
+ def test_masked_ea_with_formatter(self):
+ # GH#39336
+ df = DataFrame(
+ {
+ "a": Series([0.123456789, 1.123456789], dtype="Float64"),
+ "b": Series([1, 2], dtype="Int64"),
+ }
+ )
+ result = df.to_string(formatters=["{:.2f}".format, "{:.2f}".format])
+ expected = """ a b
+0 0.12 1.00
+1 1.12 2.00"""
+ assert result == expected
+
+ def test_repr_ea_columns(self, any_string_dtype):
+ # GH#54797
+ pytest.importorskip("pyarrow")
+ df = DataFrame({"long_column_name": [1, 2, 3], "col2": [4, 5, 6]})
+ df.columns = df.columns.astype(any_string_dtype)
+ expected = """ long_column_name col2
+0 1 4
+1 2 5
+2 3 6"""
+ assert repr(df) == expected
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_stack_unstack.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_stack_unstack.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbd1f96fc17c936e79d6edc479fd4b0cd1de1c23
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_stack_unstack.py
@@ -0,0 +1,2526 @@
+from datetime import datetime
+from io import StringIO
+import itertools
+import re
+
+import numpy as np
+import pytest
+
+from pandas._libs import lib
+from pandas.errors import PerformanceWarning
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Period,
+ Series,
+ Timedelta,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.core.reshape import reshape as reshape_lib
+
+
+@pytest.fixture(params=[True, False])
+def future_stack(request):
+ return request.param
+
+
+class TestDataFrameReshape:
+ def test_stack_unstack(self, float_frame, future_stack):
+ df = float_frame.copy()
+ df[:] = np.arange(np.prod(df.shape)).reshape(df.shape)
+
+ stacked = df.stack(future_stack=future_stack)
+ stacked_df = DataFrame({"foo": stacked, "bar": stacked})
+
+ unstacked = stacked.unstack()
+ unstacked_df = stacked_df.unstack()
+
+ tm.assert_frame_equal(unstacked, df)
+ tm.assert_frame_equal(unstacked_df["bar"], df)
+
+ unstacked_cols = stacked.unstack(0)
+ unstacked_cols_df = stacked_df.unstack(0)
+ tm.assert_frame_equal(unstacked_cols.T, df)
+ tm.assert_frame_equal(unstacked_cols_df["bar"].T, df)
+
+ def test_stack_mixed_level(self, future_stack):
+ # GH 18310
+ levels = [range(3), [3, "a", "b"], [1, 2]]
+
+ # flat columns:
+ df = DataFrame(1, index=levels[0], columns=levels[1])
+ result = df.stack(future_stack=future_stack)
+ expected = Series(1, index=MultiIndex.from_product(levels[:2]))
+ tm.assert_series_equal(result, expected)
+
+ # MultiIndex columns:
+ df = DataFrame(1, index=levels[0], columns=MultiIndex.from_product(levels[1:]))
+ result = df.stack(1, future_stack=future_stack)
+ expected = DataFrame(
+ 1, index=MultiIndex.from_product([levels[0], levels[2]]), columns=levels[1]
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # as above, but used labels in level are actually of homogeneous type
+ result = df[["a", "b"]].stack(1, future_stack=future_stack)
+ expected = expected[["a", "b"]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_not_consolidated(self, using_array_manager):
+ # Gh#34708
+ df = DataFrame({"x": [1, 2, np.nan], "y": [3.0, 4, np.nan]})
+ df2 = df[["x"]]
+ df2["y"] = df["y"]
+ if not using_array_manager:
+ assert len(df2._mgr.blocks) == 2
+
+ res = df2.unstack()
+ expected = df.unstack()
+ tm.assert_series_equal(res, expected)
+
+ def test_unstack_fill(self, future_stack):
+ # GH #9746: fill_value keyword argument for Series
+ # and DataFrame unstack
+
+ # From a series
+ data = Series([1, 2, 4, 5], dtype=np.int16)
+ data.index = MultiIndex.from_tuples(
+ [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")]
+ )
+
+ result = data.unstack(fill_value=-1)
+ expected = DataFrame(
+ {"a": [1, -1, 5], "b": [2, 4, -1]}, index=["x", "y", "z"], dtype=np.int16
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # From a series with incorrect data type for fill_value
+ result = data.unstack(fill_value=0.5)
+ expected = DataFrame(
+ {"a": [1, 0.5, 5], "b": [2, 4, 0.5]}, index=["x", "y", "z"], dtype=float
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # GH #13971: fill_value when unstacking multiple levels:
+ df = DataFrame(
+ {"x": ["a", "a", "b"], "y": ["j", "k", "j"], "z": [0, 1, 2], "w": [0, 1, 2]}
+ ).set_index(["x", "y", "z"])
+ unstacked = df.unstack(["x", "y"], fill_value=0)
+ key = ("w", "b", "j")
+ expected = unstacked[key]
+ result = Series([0, 0, 2], index=unstacked.index, name=key)
+ tm.assert_series_equal(result, expected)
+
+ stacked = unstacked.stack(["x", "y"], future_stack=future_stack)
+ stacked.index = stacked.index.reorder_levels(df.index.names)
+ # Workaround for GH #17886 (unnecessarily casts to float):
+ stacked = stacked.astype(np.int64)
+ result = stacked.loc[df.index]
+ tm.assert_frame_equal(result, df)
+
+ # From a series
+ s = df["w"]
+ result = s.unstack(["x", "y"], fill_value=0)
+ expected = unstacked["w"]
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_fill_frame(self):
+ # From a dataframe
+ rows = [[1, 2], [3, 4], [5, 6], [7, 8]]
+ df = DataFrame(rows, columns=list("AB"), dtype=np.int32)
+ df.index = MultiIndex.from_tuples(
+ [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")]
+ )
+
+ result = df.unstack(fill_value=-1)
+
+ rows = [[1, 3, 2, 4], [-1, 5, -1, 6], [7, -1, 8, -1]]
+ expected = DataFrame(rows, index=list("xyz"), dtype=np.int32)
+ expected.columns = MultiIndex.from_tuples(
+ [("A", "a"), ("A", "b"), ("B", "a"), ("B", "b")]
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # From a mixed type dataframe
+ df["A"] = df["A"].astype(np.int16)
+ df["B"] = df["B"].astype(np.float64)
+
+ result = df.unstack(fill_value=-1)
+ expected["A"] = expected["A"].astype(np.int16)
+ expected["B"] = expected["B"].astype(np.float64)
+ tm.assert_frame_equal(result, expected)
+
+ # From a dataframe with incorrect data type for fill_value
+ result = df.unstack(fill_value=0.5)
+
+ rows = [[1, 3, 2, 4], [0.5, 5, 0.5, 6], [7, 0.5, 8, 0.5]]
+ expected = DataFrame(rows, index=list("xyz"), dtype=float)
+ expected.columns = MultiIndex.from_tuples(
+ [("A", "a"), ("A", "b"), ("B", "a"), ("B", "b")]
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_fill_frame_datetime(self):
+ # Test unstacking with date times
+ dv = date_range("2012-01-01", periods=4).values
+ data = Series(dv)
+ data.index = MultiIndex.from_tuples(
+ [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")]
+ )
+
+ result = data.unstack()
+ expected = DataFrame(
+ {"a": [dv[0], pd.NaT, dv[3]], "b": [dv[1], dv[2], pd.NaT]},
+ index=["x", "y", "z"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = data.unstack(fill_value=dv[0])
+ expected = DataFrame(
+ {"a": [dv[0], dv[0], dv[3]], "b": [dv[1], dv[2], dv[0]]},
+ index=["x", "y", "z"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_fill_frame_timedelta(self):
+ # Test unstacking with time deltas
+ td = [Timedelta(days=i) for i in range(4)]
+ data = Series(td)
+ data.index = MultiIndex.from_tuples(
+ [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")]
+ )
+
+ result = data.unstack()
+ expected = DataFrame(
+ {"a": [td[0], pd.NaT, td[3]], "b": [td[1], td[2], pd.NaT]},
+ index=["x", "y", "z"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = data.unstack(fill_value=td[1])
+ expected = DataFrame(
+ {"a": [td[0], td[1], td[3]], "b": [td[1], td[2], td[1]]},
+ index=["x", "y", "z"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_fill_frame_period(self):
+ # Test unstacking with period
+ periods = [
+ Period("2012-01"),
+ Period("2012-02"),
+ Period("2012-03"),
+ Period("2012-04"),
+ ]
+ data = Series(periods)
+ data.index = MultiIndex.from_tuples(
+ [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")]
+ )
+
+ result = data.unstack()
+ expected = DataFrame(
+ {"a": [periods[0], None, periods[3]], "b": [periods[1], periods[2], None]},
+ index=["x", "y", "z"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = data.unstack(fill_value=periods[1])
+ expected = DataFrame(
+ {
+ "a": [periods[0], periods[1], periods[3]],
+ "b": [periods[1], periods[2], periods[1]],
+ },
+ index=["x", "y", "z"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_fill_frame_categorical(self):
+ # Test unstacking with categorical
+ data = Series(["a", "b", "c", "a"], dtype="category")
+ data.index = MultiIndex.from_tuples(
+ [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")]
+ )
+
+ # By default missing values will be NaN
+ result = data.unstack()
+ expected = DataFrame(
+ {
+ "a": pd.Categorical(list("axa"), categories=list("abc")),
+ "b": pd.Categorical(list("bcx"), categories=list("abc")),
+ },
+ index=list("xyz"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # Fill with non-category results in a ValueError
+ msg = r"Cannot setitem on a Categorical with a new category \(d\)"
+ with pytest.raises(TypeError, match=msg):
+ data.unstack(fill_value="d")
+
+ # Fill with category value replaces missing values as expected
+ result = data.unstack(fill_value="c")
+ expected = DataFrame(
+ {
+ "a": pd.Categorical(list("aca"), categories=list("abc")),
+ "b": pd.Categorical(list("bcc"), categories=list("abc")),
+ },
+ index=list("xyz"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_tuplename_in_multiindex(self):
+ # GH 19966
+ idx = MultiIndex.from_product(
+ [["a", "b", "c"], [1, 2, 3]], names=[("A", "a"), ("B", "b")]
+ )
+ df = DataFrame({"d": [1] * 9, "e": [2] * 9}, index=idx)
+ result = df.unstack(("A", "a"))
+
+ expected = DataFrame(
+ [[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2]],
+ columns=MultiIndex.from_tuples(
+ [
+ ("d", "a"),
+ ("d", "b"),
+ ("d", "c"),
+ ("e", "a"),
+ ("e", "b"),
+ ("e", "c"),
+ ],
+ names=[None, ("A", "a")],
+ ),
+ index=Index([1, 2, 3], name=("B", "b")),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "unstack_idx, expected_values, expected_index, expected_columns",
+ [
+ (
+ ("A", "a"),
+ [[1, 1, 2, 2], [1, 1, 2, 2], [1, 1, 2, 2], [1, 1, 2, 2]],
+ MultiIndex.from_tuples(
+ [(1, 3), (1, 4), (2, 3), (2, 4)], names=["B", "C"]
+ ),
+ MultiIndex.from_tuples(
+ [("d", "a"), ("d", "b"), ("e", "a"), ("e", "b")],
+ names=[None, ("A", "a")],
+ ),
+ ),
+ (
+ (("A", "a"), "B"),
+ [[1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2]],
+ Index([3, 4], name="C"),
+ MultiIndex.from_tuples(
+ [
+ ("d", "a", 1),
+ ("d", "a", 2),
+ ("d", "b", 1),
+ ("d", "b", 2),
+ ("e", "a", 1),
+ ("e", "a", 2),
+ ("e", "b", 1),
+ ("e", "b", 2),
+ ],
+ names=[None, ("A", "a"), "B"],
+ ),
+ ),
+ ],
+ )
+ def test_unstack_mixed_type_name_in_multiindex(
+ self, unstack_idx, expected_values, expected_index, expected_columns
+ ):
+ # GH 19966
+ idx = MultiIndex.from_product(
+ [["a", "b"], [1, 2], [3, 4]], names=[("A", "a"), "B", "C"]
+ )
+ df = DataFrame({"d": [1] * 8, "e": [2] * 8}, index=idx)
+ result = df.unstack(unstack_idx)
+
+ expected = DataFrame(
+ expected_values, columns=expected_columns, index=expected_index
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_preserve_dtypes(self):
+ # Checks fix for #11847
+ df = DataFrame(
+ {
+ "state": ["IL", "MI", "NC"],
+ "index": ["a", "b", "c"],
+ "some_categories": Series(["a", "b", "c"]).astype("category"),
+ "A": np.random.default_rng(2).random(3),
+ "B": 1,
+ "C": "foo",
+ "D": pd.Timestamp("20010102"),
+ "E": Series([1.0, 50.0, 100.0]).astype("float32"),
+ "F": Series([3.0, 4.0, 5.0]).astype("float64"),
+ "G": False,
+ "H": Series([1, 200, 923442]).astype("int8"),
+ }
+ )
+
+ def unstack_and_compare(df, column_name):
+ unstacked1 = df.unstack([column_name])
+ unstacked2 = df.unstack(column_name)
+ tm.assert_frame_equal(unstacked1, unstacked2)
+
+ df1 = df.set_index(["state", "index"])
+ unstack_and_compare(df1, "index")
+
+ df1 = df.set_index(["state", "some_categories"])
+ unstack_and_compare(df1, "some_categories")
+
+ df1 = df.set_index(["F", "C"])
+ unstack_and_compare(df1, "F")
+
+ df1 = df.set_index(["G", "B", "state"])
+ unstack_and_compare(df1, "B")
+
+ df1 = df.set_index(["E", "A"])
+ unstack_and_compare(df1, "E")
+
+ df1 = df.set_index(["state", "index"])
+ s = df1["A"]
+ unstack_and_compare(s, "index")
+
+ def test_stack_ints(self, future_stack):
+ columns = MultiIndex.from_tuples(list(itertools.product(range(3), repeat=3)))
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 27)), columns=columns
+ )
+
+ tm.assert_frame_equal(
+ df.stack(level=[1, 2], future_stack=future_stack),
+ df.stack(level=1, future_stack=future_stack).stack(
+ level=1, future_stack=future_stack
+ ),
+ )
+ tm.assert_frame_equal(
+ df.stack(level=[-2, -1], future_stack=future_stack),
+ df.stack(level=1, future_stack=future_stack).stack(
+ level=1, future_stack=future_stack
+ ),
+ )
+
+ df_named = df.copy()
+ return_value = df_named.columns.set_names(range(3), inplace=True)
+ assert return_value is None
+
+ tm.assert_frame_equal(
+ df_named.stack(level=[1, 2], future_stack=future_stack),
+ df_named.stack(level=1, future_stack=future_stack).stack(
+ level=1, future_stack=future_stack
+ ),
+ )
+
+ def test_stack_mixed_levels(self, future_stack):
+ columns = MultiIndex.from_tuples(
+ [
+ ("A", "cat", "long"),
+ ("B", "cat", "long"),
+ ("A", "dog", "short"),
+ ("B", "dog", "short"),
+ ],
+ names=["exp", "animal", "hair_length"],
+ )
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)), columns=columns
+ )
+
+ animal_hair_stacked = df.stack(
+ level=["animal", "hair_length"], future_stack=future_stack
+ )
+ exp_hair_stacked = df.stack(
+ level=["exp", "hair_length"], future_stack=future_stack
+ )
+
+ # GH #8584: Need to check that stacking works when a number
+ # is passed that is both a level name and in the range of
+ # the level numbers
+ df2 = df.copy()
+ df2.columns.names = ["exp", "animal", 1]
+ tm.assert_frame_equal(
+ df2.stack(level=["animal", 1], future_stack=future_stack),
+ animal_hair_stacked,
+ check_names=False,
+ )
+ tm.assert_frame_equal(
+ df2.stack(level=["exp", 1], future_stack=future_stack),
+ exp_hair_stacked,
+ check_names=False,
+ )
+
+ # When mixed types are passed and the ints are not level
+ # names, raise
+ msg = (
+ "level should contain all level names or all level numbers, not "
+ "a mixture of the two"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df2.stack(level=["animal", 0], future_stack=future_stack)
+
+ # GH #8584: Having 0 in the level names could raise a
+ # strange error about lexsort depth
+ df3 = df.copy()
+ df3.columns.names = ["exp", "animal", 0]
+ tm.assert_frame_equal(
+ df3.stack(level=["animal", 0], future_stack=future_stack),
+ animal_hair_stacked,
+ check_names=False,
+ )
+
+ def test_stack_int_level_names(self, future_stack):
+ columns = MultiIndex.from_tuples(
+ [
+ ("A", "cat", "long"),
+ ("B", "cat", "long"),
+ ("A", "dog", "short"),
+ ("B", "dog", "short"),
+ ],
+ names=["exp", "animal", "hair_length"],
+ )
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)), columns=columns
+ )
+
+ exp_animal_stacked = df.stack(
+ level=["exp", "animal"], future_stack=future_stack
+ )
+ animal_hair_stacked = df.stack(
+ level=["animal", "hair_length"], future_stack=future_stack
+ )
+ exp_hair_stacked = df.stack(
+ level=["exp", "hair_length"], future_stack=future_stack
+ )
+
+ df2 = df.copy()
+ df2.columns.names = [0, 1, 2]
+ tm.assert_frame_equal(
+ df2.stack(level=[1, 2], future_stack=future_stack),
+ animal_hair_stacked,
+ check_names=False,
+ )
+ tm.assert_frame_equal(
+ df2.stack(level=[0, 1], future_stack=future_stack),
+ exp_animal_stacked,
+ check_names=False,
+ )
+ tm.assert_frame_equal(
+ df2.stack(level=[0, 2], future_stack=future_stack),
+ exp_hair_stacked,
+ check_names=False,
+ )
+
+ # Out-of-order int column names
+ df3 = df.copy()
+ df3.columns.names = [2, 0, 1]
+ tm.assert_frame_equal(
+ df3.stack(level=[0, 1], future_stack=future_stack),
+ animal_hair_stacked,
+ check_names=False,
+ )
+ tm.assert_frame_equal(
+ df3.stack(level=[2, 0], future_stack=future_stack),
+ exp_animal_stacked,
+ check_names=False,
+ )
+ tm.assert_frame_equal(
+ df3.stack(level=[2, 1], future_stack=future_stack),
+ exp_hair_stacked,
+ check_names=False,
+ )
+
+ def test_unstack_bool(self):
+ df = DataFrame(
+ [False, False],
+ index=MultiIndex.from_arrays([["a", "b"], ["c", "l"]]),
+ columns=["col"],
+ )
+ rs = df.unstack()
+ xp = DataFrame(
+ np.array([[False, np.nan], [np.nan, False]], dtype=object),
+ index=["a", "b"],
+ columns=MultiIndex.from_arrays([["col", "col"], ["c", "l"]]),
+ )
+ tm.assert_frame_equal(rs, xp)
+
+ def test_unstack_level_binding(self, future_stack):
+ # GH9856
+ mi = MultiIndex(
+ levels=[["foo", "bar"], ["one", "two"], ["a", "b"]],
+ codes=[[0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 1, 0]],
+ names=["first", "second", "third"],
+ )
+ s = Series(0, index=mi)
+ result = s.unstack([1, 2]).stack(0, future_stack=future_stack)
+
+ expected_mi = MultiIndex(
+ levels=[["foo", "bar"], ["one", "two"]],
+ codes=[[0, 0, 1, 1], [0, 1, 0, 1]],
+ names=["first", "second"],
+ )
+
+ expected = DataFrame(
+ np.array(
+ [[0, np.nan], [np.nan, 0], [0, np.nan], [np.nan, 0]], dtype=np.float64
+ ),
+ index=expected_mi,
+ columns=Index(["b", "a"], name="third"),
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_to_series(self, float_frame):
+ # check reversibility
+ data = float_frame.unstack()
+
+ assert isinstance(data, Series)
+ undo = data.unstack().T
+ tm.assert_frame_equal(undo, float_frame)
+
+ # check NA handling
+ data = DataFrame({"x": [1, 2, np.nan], "y": [3.0, 4, np.nan]})
+ data.index = Index(["a", "b", "c"])
+ result = data.unstack()
+
+ midx = MultiIndex(
+ levels=[["x", "y"], ["a", "b", "c"]],
+ codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]],
+ )
+ expected = Series([1, 2, np.nan, 3, 4, np.nan], index=midx)
+
+ tm.assert_series_equal(result, expected)
+
+ # check composability of unstack
+ old_data = data.copy()
+ for _ in range(4):
+ data = data.unstack()
+ tm.assert_frame_equal(old_data, data)
+
+ def test_unstack_dtypes(self):
+ # GH 2929
+ rows = [[1, 1, 3, 4], [1, 2, 3, 4], [2, 1, 3, 4], [2, 2, 3, 4]]
+
+ df = DataFrame(rows, columns=list("ABCD"))
+ result = df.dtypes
+ expected = Series([np.dtype("int64")] * 4, index=list("ABCD"))
+ tm.assert_series_equal(result, expected)
+
+ # single dtype
+ df2 = df.set_index(["A", "B"])
+ df3 = df2.unstack("B")
+ result = df3.dtypes
+ expected = Series(
+ [np.dtype("int64")] * 4,
+ index=MultiIndex.from_arrays(
+ [["C", "C", "D", "D"], [1, 2, 1, 2]], names=(None, "B")
+ ),
+ )
+ tm.assert_series_equal(result, expected)
+
+ # mixed
+ df2 = df.set_index(["A", "B"])
+ df2["C"] = 3.0
+ df3 = df2.unstack("B")
+ result = df3.dtypes
+ expected = Series(
+ [np.dtype("float64")] * 2 + [np.dtype("int64")] * 2,
+ index=MultiIndex.from_arrays(
+ [["C", "C", "D", "D"], [1, 2, 1, 2]], names=(None, "B")
+ ),
+ )
+ tm.assert_series_equal(result, expected)
+ df2["D"] = "foo"
+ df3 = df2.unstack("B")
+ result = df3.dtypes
+ expected = Series(
+ [np.dtype("float64")] * 2 + [np.dtype("object")] * 2,
+ index=MultiIndex.from_arrays(
+ [["C", "C", "D", "D"], [1, 2, 1, 2]], names=(None, "B")
+ ),
+ )
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "c, d",
+ (
+ (np.zeros(5), np.zeros(5)),
+ (np.arange(5, dtype="f8"), np.arange(5, 10, dtype="f8")),
+ ),
+ )
+ def test_unstack_dtypes_mixed_date(self, c, d):
+ # GH7405
+ df = DataFrame(
+ {
+ "A": ["a"] * 5,
+ "C": c,
+ "D": d,
+ "B": date_range("2012-01-01", periods=5),
+ }
+ )
+
+ right = df.iloc[:3].copy(deep=True)
+
+ df = df.set_index(["A", "B"])
+ df["D"] = df["D"].astype("int64")
+
+ left = df.iloc[:3].unstack(0)
+ right = right.set_index(["A", "B"]).unstack(0)
+ right[("D", "a")] = right[("D", "a")].astype("int64")
+
+ assert left.shape == (3, 2)
+ tm.assert_frame_equal(left, right)
+
+ def test_unstack_non_unique_index_names(self, future_stack):
+ idx = MultiIndex.from_tuples([("a", "b"), ("c", "d")], names=["c1", "c1"])
+ df = DataFrame([1, 2], index=idx)
+ msg = "The name c1 occurs multiple times, use a level number"
+ with pytest.raises(ValueError, match=msg):
+ df.unstack("c1")
+
+ with pytest.raises(ValueError, match=msg):
+ df.T.stack("c1", future_stack=future_stack)
+
+ def test_unstack_unused_levels(self):
+ # GH 17845: unused codes in index make unstack() cast int to float
+ idx = MultiIndex.from_product([["a"], ["A", "B", "C", "D"]])[:-1]
+ df = DataFrame([[1, 0]] * 3, index=idx)
+
+ result = df.unstack()
+ exp_col = MultiIndex.from_product([[0, 1], ["A", "B", "C"]])
+ expected = DataFrame([[1, 1, 1, 0, 0, 0]], index=["a"], columns=exp_col)
+ tm.assert_frame_equal(result, expected)
+ assert (result.columns.levels[1] == idx.levels[1]).all()
+
+ # Unused items on both levels
+ levels = [[0, 1, 7], [0, 1, 2, 3]]
+ codes = [[0, 0, 1, 1], [0, 2, 0, 2]]
+ idx = MultiIndex(levels, codes)
+ block = np.arange(4).reshape(2, 2)
+ df = DataFrame(np.concatenate([block, block + 4]), index=idx)
+ result = df.unstack()
+ expected = DataFrame(
+ np.concatenate([block * 2, block * 2 + 1], axis=1), columns=idx
+ )
+ tm.assert_frame_equal(result, expected)
+ assert (result.columns.levels[1] == idx.levels[1]).all()
+
+ @pytest.mark.parametrize(
+ "level, idces, col_level, idx_level",
+ (
+ (0, [13, 16, 6, 9, 2, 5, 8, 11], [np.nan, "a", 2], [np.nan, 5, 1]),
+ (1, [8, 11, 1, 4, 12, 15, 13, 16], [np.nan, 5, 1], [np.nan, "a", 2]),
+ ),
+ )
+ def test_unstack_unused_levels_mixed_with_nan(
+ self, level, idces, col_level, idx_level
+ ):
+ # With mixed dtype and NaN
+ levels = [["a", 2, "c"], [1, 3, 5, 7]]
+ codes = [[0, -1, 1, 1], [0, 2, -1, 2]]
+ idx = MultiIndex(levels, codes)
+ data = np.arange(8)
+ df = DataFrame(data.reshape(4, 2), index=idx)
+
+ result = df.unstack(level=level)
+ exp_data = np.zeros(18) * np.nan
+ exp_data[idces] = data
+ cols = MultiIndex.from_product([[0, 1], col_level])
+ expected = DataFrame(exp_data.reshape(3, 6), index=idx_level, columns=cols)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("cols", [["A", "C"], slice(None)])
+ def test_unstack_unused_level(self, cols):
+ # GH 18562 : unused codes on the unstacked level
+ df = DataFrame([[2010, "a", "I"], [2011, "b", "II"]], columns=["A", "B", "C"])
+
+ ind = df.set_index(["A", "B", "C"], drop=False)
+ selection = ind.loc[(slice(None), slice(None), "I"), cols]
+ result = selection.unstack()
+
+ expected = ind.iloc[[0]][cols]
+ expected.columns = MultiIndex.from_product(
+ [expected.columns, ["I"]], names=[None, "C"]
+ )
+ expected.index = expected.index.droplevel("C")
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_long_index(self):
+ # PH 32624: Error when using a lot of indices to unstack.
+ # The error occurred only, if a lot of indices are used.
+ df = DataFrame(
+ [[1]],
+ columns=MultiIndex.from_tuples([[0]], names=["c1"]),
+ index=MultiIndex.from_tuples(
+ [[0, 0, 1, 0, 0, 0, 1]],
+ names=["i1", "i2", "i3", "i4", "i5", "i6", "i7"],
+ ),
+ )
+ result = df.unstack(["i2", "i3", "i4", "i5", "i6", "i7"])
+ expected = DataFrame(
+ [[1]],
+ columns=MultiIndex.from_tuples(
+ [[0, 0, 1, 0, 0, 0, 1]],
+ names=["c1", "i2", "i3", "i4", "i5", "i6", "i7"],
+ ),
+ index=Index([0], name="i1"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_multi_level_cols(self):
+ # PH 24729: Unstack a df with multi level columns
+ df = DataFrame(
+ [[0.0, 0.0], [0.0, 0.0]],
+ columns=MultiIndex.from_tuples(
+ [["B", "C"], ["B", "D"]], names=["c1", "c2"]
+ ),
+ index=MultiIndex.from_tuples(
+ [[10, 20, 30], [10, 20, 40]], names=["i1", "i2", "i3"]
+ ),
+ )
+ assert df.unstack(["i2", "i1"]).columns.names[-2:] == ["i2", "i1"]
+
+ def test_unstack_multi_level_rows_and_cols(self):
+ # PH 28306: Unstack df with multi level cols and rows
+ df = DataFrame(
+ [[1, 2], [3, 4], [-1, -2], [-3, -4]],
+ columns=MultiIndex.from_tuples([["a", "b", "c"], ["d", "e", "f"]]),
+ index=MultiIndex.from_tuples(
+ [
+ ["m1", "P3", 222],
+ ["m1", "A5", 111],
+ ["m2", "P3", 222],
+ ["m2", "A5", 111],
+ ],
+ names=["i1", "i2", "i3"],
+ ),
+ )
+ result = df.unstack(["i3", "i2"])
+ expected = df.unstack(["i3"]).unstack(["i2"])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("idx", [("jim", "joe"), ("joe", "jim")])
+ @pytest.mark.parametrize("lev", list(range(2)))
+ def test_unstack_nan_index1(self, idx, lev):
+ # GH7466
+ def cast(val):
+ val_str = "" if val != val else val
+ return f"{val_str:1}"
+
+ df = DataFrame(
+ {
+ "jim": ["a", "b", np.nan, "d"],
+ "joe": ["w", "x", "y", "z"],
+ "jolie": ["a.w", "b.x", " .y", "d.z"],
+ }
+ )
+
+ left = df.set_index(["jim", "joe"]).unstack()["jolie"]
+ right = df.set_index(["joe", "jim"]).unstack()["jolie"].T
+ tm.assert_frame_equal(left, right)
+
+ mi = df.set_index(list(idx))
+ udf = mi.unstack(level=lev)
+ assert udf.notna().values.sum() == len(df)
+ mk_list = lambda a: list(a) if isinstance(a, tuple) else [a]
+ rows, cols = udf["jolie"].notna().values.nonzero()
+ for i, j in zip(rows, cols):
+ left = sorted(udf["jolie"].iloc[i, j].split("."))
+ right = mk_list(udf["jolie"].index[i]) + mk_list(udf["jolie"].columns[j])
+ right = sorted(map(cast, right))
+ assert left == right
+
+ @pytest.mark.parametrize("idx", itertools.permutations(["1st", "2nd", "3rd"]))
+ @pytest.mark.parametrize("lev", list(range(3)))
+ @pytest.mark.parametrize("col", ["4th", "5th"])
+ def test_unstack_nan_index_repeats(self, idx, lev, col):
+ def cast(val):
+ val_str = "" if val != val else val
+ return f"{val_str:1}"
+
+ df = DataFrame(
+ {
+ "1st": ["d"] * 3
+ + [np.nan] * 5
+ + ["a"] * 2
+ + ["c"] * 3
+ + ["e"] * 2
+ + ["b"] * 5,
+ "2nd": ["y"] * 2
+ + ["w"] * 3
+ + [np.nan] * 3
+ + ["z"] * 4
+ + [np.nan] * 3
+ + ["x"] * 3
+ + [np.nan] * 2,
+ "3rd": [
+ 67,
+ 39,
+ 53,
+ 72,
+ 57,
+ 80,
+ 31,
+ 18,
+ 11,
+ 30,
+ 59,
+ 50,
+ 62,
+ 59,
+ 76,
+ 52,
+ 14,
+ 53,
+ 60,
+ 51,
+ ],
+ }
+ )
+
+ df["4th"], df["5th"] = (
+ df.apply(lambda r: ".".join(map(cast, r)), axis=1),
+ df.apply(lambda r: ".".join(map(cast, r.iloc[::-1])), axis=1),
+ )
+
+ mi = df.set_index(list(idx))
+ udf = mi.unstack(level=lev)
+ assert udf.notna().values.sum() == 2 * len(df)
+ mk_list = lambda a: list(a) if isinstance(a, tuple) else [a]
+ rows, cols = udf[col].notna().values.nonzero()
+ for i, j in zip(rows, cols):
+ left = sorted(udf[col].iloc[i, j].split("."))
+ right = mk_list(udf[col].index[i]) + mk_list(udf[col].columns[j])
+ right = sorted(map(cast, right))
+ assert left == right
+
+ def test_unstack_nan_index2(self):
+ # GH7403
+ df = DataFrame({"A": list("aaaabbbb"), "B": range(8), "C": range(8)})
+ # Explicit cast to avoid implicit cast when setting to np.nan
+ df = df.astype({"B": "float"})
+ df.iloc[3, 1] = np.nan
+ left = df.set_index(["A", "B"]).unstack(0)
+
+ vals = [
+ [3, 0, 1, 2, np.nan, np.nan, np.nan, np.nan],
+ [np.nan, np.nan, np.nan, np.nan, 4, 5, 6, 7],
+ ]
+ vals = list(map(list, zip(*vals)))
+ idx = Index([np.nan, 0, 1, 2, 4, 5, 6, 7], name="B")
+ cols = MultiIndex(
+ levels=[["C"], ["a", "b"]], codes=[[0, 0], [0, 1]], names=[None, "A"]
+ )
+
+ right = DataFrame(vals, columns=cols, index=idx)
+ tm.assert_frame_equal(left, right)
+
+ df = DataFrame({"A": list("aaaabbbb"), "B": list(range(4)) * 2, "C": range(8)})
+ # Explicit cast to avoid implicit cast when setting to np.nan
+ df = df.astype({"B": "float"})
+ df.iloc[2, 1] = np.nan
+ left = df.set_index(["A", "B"]).unstack(0)
+
+ vals = [[2, np.nan], [0, 4], [1, 5], [np.nan, 6], [3, 7]]
+ cols = MultiIndex(
+ levels=[["C"], ["a", "b"]], codes=[[0, 0], [0, 1]], names=[None, "A"]
+ )
+ idx = Index([np.nan, 0, 1, 2, 3], name="B")
+ right = DataFrame(vals, columns=cols, index=idx)
+ tm.assert_frame_equal(left, right)
+
+ df = DataFrame({"A": list("aaaabbbb"), "B": list(range(4)) * 2, "C": range(8)})
+ # Explicit cast to avoid implicit cast when setting to np.nan
+ df = df.astype({"B": "float"})
+ df.iloc[3, 1] = np.nan
+ left = df.set_index(["A", "B"]).unstack(0)
+
+ vals = [[3, np.nan], [0, 4], [1, 5], [2, 6], [np.nan, 7]]
+ cols = MultiIndex(
+ levels=[["C"], ["a", "b"]], codes=[[0, 0], [0, 1]], names=[None, "A"]
+ )
+ idx = Index([np.nan, 0, 1, 2, 3], name="B")
+ right = DataFrame(vals, columns=cols, index=idx)
+ tm.assert_frame_equal(left, right)
+
+ def test_unstack_nan_index3(self, using_array_manager):
+ # GH7401
+ df = DataFrame(
+ {
+ "A": list("aaaaabbbbb"),
+ "B": (date_range("2012-01-01", periods=5).tolist() * 2),
+ "C": np.arange(10),
+ }
+ )
+
+ df.iloc[3, 1] = np.nan
+ left = df.set_index(["A", "B"]).unstack()
+
+ vals = np.array([[3, 0, 1, 2, np.nan, 4], [np.nan, 5, 6, 7, 8, 9]])
+ idx = Index(["a", "b"], name="A")
+ cols = MultiIndex(
+ levels=[["C"], date_range("2012-01-01", periods=5)],
+ codes=[[0, 0, 0, 0, 0, 0], [-1, 0, 1, 2, 3, 4]],
+ names=[None, "B"],
+ )
+
+ right = DataFrame(vals, columns=cols, index=idx)
+ if using_array_manager:
+ # INFO(ArrayManager) with ArrayManager preserve dtype where possible
+ cols = right.columns[[1, 2, 3, 5]]
+ right[cols] = right[cols].astype(df["C"].dtype)
+ tm.assert_frame_equal(left, right)
+
+ def test_unstack_nan_index4(self):
+ # GH4862
+ vals = [
+ ["Hg", np.nan, np.nan, 680585148],
+ ["U", 0.0, np.nan, 680585148],
+ ["Pb", 7.07e-06, np.nan, 680585148],
+ ["Sn", 2.3614e-05, 0.0133, 680607017],
+ ["Ag", 0.0, 0.0133, 680607017],
+ ["Hg", -0.00015, 0.0133, 680607017],
+ ]
+ df = DataFrame(
+ vals,
+ columns=["agent", "change", "dosage", "s_id"],
+ index=[17263, 17264, 17265, 17266, 17267, 17268],
+ )
+
+ left = df.copy().set_index(["s_id", "dosage", "agent"]).unstack()
+
+ vals = [
+ [np.nan, np.nan, 7.07e-06, np.nan, 0.0],
+ [0.0, -0.00015, np.nan, 2.3614e-05, np.nan],
+ ]
+
+ idx = MultiIndex(
+ levels=[[680585148, 680607017], [0.0133]],
+ codes=[[0, 1], [-1, 0]],
+ names=["s_id", "dosage"],
+ )
+
+ cols = MultiIndex(
+ levels=[["change"], ["Ag", "Hg", "Pb", "Sn", "U"]],
+ codes=[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4]],
+ names=[None, "agent"],
+ )
+
+ right = DataFrame(vals, columns=cols, index=idx)
+ tm.assert_frame_equal(left, right)
+
+ left = df.loc[17264:].copy().set_index(["s_id", "dosage", "agent"])
+ tm.assert_frame_equal(left.unstack(), right)
+
+ def test_unstack_nan_index5(self):
+ # GH9497 - multiple unstack with nulls
+ df = DataFrame(
+ {
+ "1st": [1, 2, 1, 2, 1, 2],
+ "2nd": date_range("2014-02-01", periods=6, freq="D"),
+ "jim": 100 + np.arange(6),
+ "joe": (np.random.default_rng(2).standard_normal(6) * 10).round(2),
+ }
+ )
+
+ df["3rd"] = df["2nd"] - pd.Timestamp("2014-02-02")
+ df.loc[1, "2nd"] = df.loc[3, "2nd"] = np.nan
+ df.loc[1, "3rd"] = df.loc[4, "3rd"] = np.nan
+
+ left = df.set_index(["1st", "2nd", "3rd"]).unstack(["2nd", "3rd"])
+ assert left.notna().values.sum() == 2 * len(df)
+
+ for col in ["jim", "joe"]:
+ for _, r in df.iterrows():
+ key = r["1st"], (col, r["2nd"], r["3rd"])
+ assert r[col] == left.loc[key]
+
+ def test_stack_datetime_column_multiIndex(self, future_stack):
+ # GH 8039
+ t = datetime(2014, 1, 1)
+ df = DataFrame([1, 2, 3, 4], columns=MultiIndex.from_tuples([(t, "A", "B")]))
+ result = df.stack(future_stack=future_stack)
+
+ eidx = MultiIndex.from_product([(0, 1, 2, 3), ("B",)])
+ ecols = MultiIndex.from_tuples([(t, "A")])
+ expected = DataFrame([1, 2, 3, 4], index=eidx, columns=ecols)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "multiindex_columns",
+ [
+ [0, 1, 2, 3, 4],
+ [0, 1, 2, 3],
+ [0, 1, 2, 4],
+ [0, 1, 2],
+ [1, 2, 3],
+ [2, 3, 4],
+ [0, 1],
+ [0, 2],
+ [0, 3],
+ [0],
+ [2],
+ [4],
+ [4, 3, 2, 1, 0],
+ [3, 2, 1, 0],
+ [4, 2, 1, 0],
+ [2, 1, 0],
+ [3, 2, 1],
+ [4, 3, 2],
+ [1, 0],
+ [2, 0],
+ [3, 0],
+ ],
+ )
+ @pytest.mark.parametrize("level", (-1, 0, 1, [0, 1], [1, 0]))
+ def test_stack_partial_multiIndex(self, multiindex_columns, level, future_stack):
+ # GH 8844
+ dropna = False if not future_stack else lib.no_default
+ full_multiindex = MultiIndex.from_tuples(
+ [("B", "x"), ("B", "z"), ("A", "y"), ("C", "x"), ("C", "u")],
+ names=["Upper", "Lower"],
+ )
+ multiindex = full_multiindex[multiindex_columns]
+ df = DataFrame(
+ np.arange(3 * len(multiindex)).reshape(3, len(multiindex)),
+ columns=multiindex,
+ )
+ result = df.stack(level=level, dropna=dropna, future_stack=future_stack)
+
+ if isinstance(level, int) and not future_stack:
+ # Stacking a single level should not make any all-NaN rows,
+ # so df.stack(level=level, dropna=False) should be the same
+ # as df.stack(level=level, dropna=True).
+ expected = df.stack(level=level, dropna=True, future_stack=future_stack)
+ if isinstance(expected, Series):
+ tm.assert_series_equal(result, expected)
+ else:
+ tm.assert_frame_equal(result, expected)
+
+ df.columns = MultiIndex.from_tuples(
+ df.columns.to_numpy(), names=df.columns.names
+ )
+ expected = df.stack(level=level, dropna=dropna, future_stack=future_stack)
+ if isinstance(expected, Series):
+ tm.assert_series_equal(result, expected)
+ else:
+ tm.assert_frame_equal(result, expected)
+
+ def test_stack_full_multiIndex(self, future_stack):
+ # GH 8844
+ full_multiindex = MultiIndex.from_tuples(
+ [("B", "x"), ("B", "z"), ("A", "y"), ("C", "x"), ("C", "u")],
+ names=["Upper", "Lower"],
+ )
+ df = DataFrame(np.arange(6).reshape(2, 3), columns=full_multiindex[[0, 1, 3]])
+ dropna = False if not future_stack else lib.no_default
+ result = df.stack(dropna=dropna, future_stack=future_stack)
+ expected = DataFrame(
+ [[0, 2], [1, np.nan], [3, 5], [4, np.nan]],
+ index=MultiIndex(
+ levels=[[0, 1], ["u", "x", "y", "z"]],
+ codes=[[0, 0, 1, 1], [1, 3, 1, 3]],
+ names=[None, "Lower"],
+ ),
+ columns=Index(["B", "C"], name="Upper"),
+ )
+ expected["B"] = expected["B"].astype(df.dtypes.iloc[0])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("ordered", [False, True])
+ def test_stack_preserve_categorical_dtype(self, ordered, future_stack):
+ # GH13854
+ cidx = pd.CategoricalIndex(list("yxz"), categories=list("xyz"), ordered=ordered)
+ df = DataFrame([[10, 11, 12]], columns=cidx)
+ result = df.stack(future_stack=future_stack)
+
+ # `MultiIndex.from_product` preserves categorical dtype -
+ # it's tested elsewhere.
+ midx = MultiIndex.from_product([df.index, cidx])
+ expected = Series([10, 11, 12], index=midx)
+
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("ordered", [False, True])
+ @pytest.mark.parametrize(
+ "labels,data",
+ [
+ (list("xyz"), [10, 11, 12, 13, 14, 15]),
+ (list("zyx"), [14, 15, 12, 13, 10, 11]),
+ ],
+ )
+ def test_stack_multi_preserve_categorical_dtype(
+ self, ordered, labels, data, future_stack
+ ):
+ # GH-36991
+ cidx = pd.CategoricalIndex(labels, categories=sorted(labels), ordered=ordered)
+ cidx2 = pd.CategoricalIndex(["u", "v"], ordered=ordered)
+ midx = MultiIndex.from_product([cidx, cidx2])
+ df = DataFrame([sorted(data)], columns=midx)
+ result = df.stack([0, 1], future_stack=future_stack)
+
+ labels = labels if future_stack else sorted(labels)
+ s_cidx = pd.CategoricalIndex(labels, ordered=ordered)
+ expected_data = sorted(data) if future_stack else data
+ expected = Series(
+ expected_data, index=MultiIndex.from_product([[0], s_cidx, cidx2])
+ )
+
+ tm.assert_series_equal(result, expected)
+
+ def test_stack_preserve_categorical_dtype_values(self, future_stack):
+ # GH-23077
+ cat = pd.Categorical(["a", "a", "b", "c"])
+ df = DataFrame({"A": cat, "B": cat})
+ result = df.stack(future_stack=future_stack)
+ index = MultiIndex.from_product([[0, 1, 2, 3], ["A", "B"]])
+ expected = Series(
+ pd.Categorical(["a", "a", "a", "a", "b", "b", "c", "c"]), index=index
+ )
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "index, columns",
+ [
+ ([0, 0, 1, 1], MultiIndex.from_product([[1, 2], ["a", "b"]])),
+ ([0, 0, 2, 3], MultiIndex.from_product([[1, 2], ["a", "b"]])),
+ ([0, 1, 2, 3], MultiIndex.from_product([[1, 2], ["a", "b"]])),
+ ],
+ )
+ def test_stack_multi_columns_non_unique_index(self, index, columns, future_stack):
+ # GH-28301
+ df = DataFrame(index=index, columns=columns).fillna(1)
+ stacked = df.stack(future_stack=future_stack)
+ new_index = MultiIndex.from_tuples(stacked.index.to_numpy())
+ expected = DataFrame(
+ stacked.to_numpy(), index=new_index, columns=stacked.columns
+ )
+ tm.assert_frame_equal(stacked, expected)
+ stacked_codes = np.asarray(stacked.index.codes)
+ expected_codes = np.asarray(new_index.codes)
+ tm.assert_numpy_array_equal(stacked_codes, expected_codes)
+
+ @pytest.mark.parametrize(
+ "vals1, vals2, dtype1, dtype2, expected_dtype",
+ [
+ ([1, 2], [3.0, 4.0], "Int64", "Float64", "Float64"),
+ ([1, 2], ["foo", "bar"], "Int64", "string", "object"),
+ ],
+ )
+ def test_stack_multi_columns_mixed_extension_types(
+ self, vals1, vals2, dtype1, dtype2, expected_dtype, future_stack
+ ):
+ # GH45740
+ df = DataFrame(
+ {
+ ("A", 1): Series(vals1, dtype=dtype1),
+ ("A", 2): Series(vals2, dtype=dtype2),
+ }
+ )
+ result = df.stack(future_stack=future_stack)
+ expected = (
+ df.astype(object).stack(future_stack=future_stack).astype(expected_dtype)
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("level", [0, 1])
+ def test_unstack_mixed_extension_types(self, level):
+ index = MultiIndex.from_tuples([("A", 0), ("A", 1), ("B", 1)], names=["a", "b"])
+ df = DataFrame(
+ {
+ "A": pd.array([0, 1, None], dtype="Int64"),
+ "B": pd.Categorical(["a", "a", "b"]),
+ },
+ index=index,
+ )
+
+ result = df.unstack(level=level)
+ expected = df.astype(object).unstack(level=level)
+ if level == 0:
+ expected[("A", "B")] = expected[("A", "B")].fillna(pd.NA)
+ else:
+ expected[("A", 0)] = expected[("A", 0)].fillna(pd.NA)
+
+ expected_dtypes = Series(
+ [df.A.dtype] * 2 + [df.B.dtype] * 2, index=result.columns
+ )
+ tm.assert_series_equal(result.dtypes, expected_dtypes)
+ tm.assert_frame_equal(result.astype(object), expected)
+
+ @pytest.mark.parametrize("level", [0, "baz"])
+ def test_unstack_swaplevel_sortlevel(self, level):
+ # GH 20994
+ mi = MultiIndex.from_product([[0], ["d", "c"]], names=["bar", "baz"])
+ df = DataFrame([[0, 2], [1, 3]], index=mi, columns=["B", "A"])
+ df.columns.name = "foo"
+
+ expected = DataFrame(
+ [[3, 1, 2, 0]],
+ columns=MultiIndex.from_tuples(
+ [("c", "A"), ("c", "B"), ("d", "A"), ("d", "B")], names=["baz", "foo"]
+ ),
+ )
+ expected.index.name = "bar"
+
+ result = df.unstack().swaplevel(axis=1).sort_index(axis=1, level=level)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["float64", "Float64"])
+def test_unstack_sort_false(frame_or_series, dtype):
+ # GH 15105
+ index = MultiIndex.from_tuples(
+ [("two", "z", "b"), ("two", "y", "a"), ("one", "z", "b"), ("one", "y", "a")]
+ )
+ obj = frame_or_series(np.arange(1.0, 5.0), index=index, dtype=dtype)
+ result = obj.unstack(level=-1, sort=False)
+
+ if frame_or_series is DataFrame:
+ expected_columns = MultiIndex.from_tuples([(0, "b"), (0, "a")])
+ else:
+ expected_columns = ["b", "a"]
+ expected = DataFrame(
+ [[1.0, np.nan], [np.nan, 2.0], [3.0, np.nan], [np.nan, 4.0]],
+ columns=expected_columns,
+ index=MultiIndex.from_tuples(
+ [("two", "z"), ("two", "y"), ("one", "z"), ("one", "y")]
+ ),
+ dtype=dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = obj.unstack(level=[1, 2], sort=False)
+
+ if frame_or_series is DataFrame:
+ expected_columns = MultiIndex.from_tuples([(0, "z", "b"), (0, "y", "a")])
+ else:
+ expected_columns = MultiIndex.from_tuples([("z", "b"), ("y", "a")])
+ expected = DataFrame(
+ [[1.0, 2.0], [3.0, 4.0]],
+ index=["two", "one"],
+ columns=expected_columns,
+ dtype=dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_unstack_fill_frame_object():
+ # GH12815 Test unstacking with object.
+ data = Series(["a", "b", "c", "a"], dtype="object")
+ data.index = MultiIndex.from_tuples(
+ [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")]
+ )
+
+ # By default missing values will be NaN
+ result = data.unstack()
+ expected = DataFrame(
+ {"a": ["a", np.nan, "a"], "b": ["b", "c", np.nan]}, index=list("xyz")
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # Fill with any value replaces missing values as expected
+ result = data.unstack(fill_value="d")
+ expected = DataFrame(
+ {"a": ["a", "d", "a"], "b": ["b", "c", "d"]}, index=list("xyz")
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_unstack_timezone_aware_values():
+ # GH 18338
+ df = DataFrame(
+ {
+ "timestamp": [pd.Timestamp("2017-08-27 01:00:00.709949+0000", tz="UTC")],
+ "a": ["a"],
+ "b": ["b"],
+ "c": ["c"],
+ },
+ columns=["timestamp", "a", "b", "c"],
+ )
+ result = df.set_index(["a", "b"]).unstack()
+ expected = DataFrame(
+ [[pd.Timestamp("2017-08-27 01:00:00.709949+0000", tz="UTC"), "c"]],
+ index=Index(["a"], name="a"),
+ columns=MultiIndex(
+ levels=[["timestamp", "c"], ["b"]],
+ codes=[[0, 1], [0, 0]],
+ names=[None, "b"],
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_stack_timezone_aware_values(future_stack):
+ # GH 19420
+ ts = date_range(freq="D", start="20180101", end="20180103", tz="America/New_York")
+ df = DataFrame({"A": ts}, index=["a", "b", "c"])
+ result = df.stack(future_stack=future_stack)
+ expected = Series(
+ ts,
+ index=MultiIndex(levels=[["a", "b", "c"], ["A"]], codes=[[0, 1, 2], [0, 0, 0]]),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("dropna", [True, False, lib.no_default])
+def test_stack_empty_frame(dropna, future_stack):
+ # GH 36113
+ levels = [np.array([], dtype=np.int64), np.array([], dtype=np.int64)]
+ expected = Series(dtype=np.float64, index=MultiIndex(levels=levels, codes=[[], []]))
+ if future_stack and dropna is not lib.no_default:
+ with pytest.raises(ValueError, match="dropna must be unspecified"):
+ DataFrame(dtype=np.float64).stack(dropna=dropna, future_stack=future_stack)
+ else:
+ result = DataFrame(dtype=np.float64).stack(
+ dropna=dropna, future_stack=future_stack
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("dropna", [True, False, lib.no_default])
+@pytest.mark.parametrize("fill_value", [None, 0])
+def test_stack_unstack_empty_frame(dropna, fill_value, future_stack):
+ # GH 36113
+ if future_stack and dropna is not lib.no_default:
+ with pytest.raises(ValueError, match="dropna must be unspecified"):
+ DataFrame(dtype=np.int64).stack(
+ dropna=dropna, future_stack=future_stack
+ ).unstack(fill_value=fill_value)
+ else:
+ result = (
+ DataFrame(dtype=np.int64)
+ .stack(dropna=dropna, future_stack=future_stack)
+ .unstack(fill_value=fill_value)
+ )
+ expected = DataFrame(dtype=np.int64)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_unstack_single_index_series():
+ # GH 36113
+ msg = r"index must be a MultiIndex to unstack.*"
+ with pytest.raises(ValueError, match=msg):
+ Series(dtype=np.int64).unstack()
+
+
+def test_unstacking_multi_index_df():
+ # see gh-30740
+ df = DataFrame(
+ {
+ "name": ["Alice", "Bob"],
+ "score": [9.5, 8],
+ "employed": [False, True],
+ "kids": [0, 0],
+ "gender": ["female", "male"],
+ }
+ )
+ df = df.set_index(["name", "employed", "kids", "gender"])
+ df = df.unstack(["gender"], fill_value=0)
+ expected = df.unstack("employed", fill_value=0).unstack("kids", fill_value=0)
+ result = df.unstack(["employed", "kids"], fill_value=0)
+ expected = DataFrame(
+ [[9.5, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 8.0]],
+ index=Index(["Alice", "Bob"], name="name"),
+ columns=MultiIndex.from_tuples(
+ [
+ ("score", "female", False, 0),
+ ("score", "female", True, 0),
+ ("score", "male", False, 0),
+ ("score", "male", True, 0),
+ ],
+ names=[None, "gender", "employed", "kids"],
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_stack_positional_level_duplicate_column_names(future_stack):
+ # https://github.com/pandas-dev/pandas/issues/36353
+ columns = MultiIndex.from_product([("x", "y"), ("y", "z")], names=["a", "a"])
+ df = DataFrame([[1, 1, 1, 1]], columns=columns)
+ result = df.stack(0, future_stack=future_stack)
+
+ new_columns = Index(["y", "z"], name="a")
+ new_index = MultiIndex.from_tuples([(0, "x"), (0, "y")], names=[None, "a"])
+ expected = DataFrame([[1, 1], [1, 1]], index=new_index, columns=new_columns)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_unstack_non_slice_like_blocks(using_array_manager):
+ # Case where the mgr_locs of a DataFrame's underlying blocks are not slice-like
+
+ mi = MultiIndex.from_product([range(5), ["A", "B", "C"]])
+ df = DataFrame(
+ {
+ 0: np.random.default_rng(2).standard_normal(15),
+ 1: np.random.default_rng(2).standard_normal(15).astype(np.int64),
+ 2: np.random.default_rng(2).standard_normal(15),
+ 3: np.random.default_rng(2).standard_normal(15),
+ },
+ index=mi,
+ )
+ if not using_array_manager:
+ assert any(not x.mgr_locs.is_slice_like for x in df._mgr.blocks)
+
+ res = df.unstack()
+
+ expected = pd.concat([df[n].unstack() for n in range(4)], keys=range(4), axis=1)
+ tm.assert_frame_equal(res, expected)
+
+
+def test_stack_sort_false(future_stack):
+ # GH 15105
+ data = [[1, 2, 3.0, 4.0], [2, 3, 4.0, 5.0], [3, 4, np.nan, np.nan]]
+ df = DataFrame(
+ data,
+ columns=MultiIndex(
+ levels=[["B", "A"], ["x", "y"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]
+ ),
+ )
+ kwargs = {} if future_stack else {"sort": False}
+ result = df.stack(level=0, future_stack=future_stack, **kwargs)
+ if future_stack:
+ expected = DataFrame(
+ {
+ "x": [1.0, 3.0, 2.0, 4.0, 3.0, np.nan],
+ "y": [2.0, 4.0, 3.0, 5.0, 4.0, np.nan],
+ },
+ index=MultiIndex.from_arrays(
+ [[0, 0, 1, 1, 2, 2], ["B", "A", "B", "A", "B", "A"]]
+ ),
+ )
+ else:
+ expected = DataFrame(
+ {"x": [1.0, 3.0, 2.0, 4.0, 3.0], "y": [2.0, 4.0, 3.0, 5.0, 4.0]},
+ index=MultiIndex.from_arrays([[0, 0, 1, 1, 2], ["B", "A", "B", "A", "B"]]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # Codes sorted in this call
+ df = DataFrame(
+ data,
+ columns=MultiIndex.from_arrays([["B", "B", "A", "A"], ["x", "y", "x", "y"]]),
+ )
+ kwargs = {} if future_stack else {"sort": False}
+ result = df.stack(level=0, future_stack=future_stack, **kwargs)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_stack_sort_false_multi_level(future_stack):
+ # GH 15105
+ idx = MultiIndex.from_tuples([("weight", "kg"), ("height", "m")])
+ df = DataFrame([[1.0, 2.0], [3.0, 4.0]], index=["cat", "dog"], columns=idx)
+ kwargs = {} if future_stack else {"sort": False}
+ result = df.stack([0, 1], future_stack=future_stack, **kwargs)
+ expected_index = MultiIndex.from_tuples(
+ [
+ ("cat", "weight", "kg"),
+ ("cat", "height", "m"),
+ ("dog", "weight", "kg"),
+ ("dog", "height", "m"),
+ ]
+ )
+ expected = Series([1.0, 2.0, 3.0, 4.0], index=expected_index)
+ tm.assert_series_equal(result, expected)
+
+
+class TestStackUnstackMultiLevel:
+ def test_unstack(self, multiindex_year_month_day_dataframe_random_data):
+ # just check that it works for now
+ ymd = multiindex_year_month_day_dataframe_random_data
+
+ unstacked = ymd.unstack()
+ unstacked.unstack()
+
+ # test that ints work
+ ymd.astype(int).unstack()
+
+ # test that int32 work
+ ymd.astype(np.int32).unstack()
+
+ @pytest.mark.parametrize(
+ "result_rows,result_columns,index_product,expected_row",
+ [
+ (
+ [[1, 1, None, None, 30.0, None], [2, 2, None, None, 30.0, None]],
+ ["ix1", "ix2", "col1", "col2", "col3", "col4"],
+ 2,
+ [None, None, 30.0, None],
+ ),
+ (
+ [[1, 1, None, None, 30.0], [2, 2, None, None, 30.0]],
+ ["ix1", "ix2", "col1", "col2", "col3"],
+ 2,
+ [None, None, 30.0],
+ ),
+ (
+ [[1, 1, None, None, 30.0], [2, None, None, None, 30.0]],
+ ["ix1", "ix2", "col1", "col2", "col3"],
+ None,
+ [None, None, 30.0],
+ ),
+ ],
+ )
+ def test_unstack_partial(
+ self, result_rows, result_columns, index_product, expected_row
+ ):
+ # check for regressions on this issue:
+ # https://github.com/pandas-dev/pandas/issues/19351
+ # make sure DataFrame.unstack() works when its run on a subset of the DataFrame
+ # and the Index levels contain values that are not present in the subset
+ result = DataFrame(result_rows, columns=result_columns).set_index(
+ ["ix1", "ix2"]
+ )
+ result = result.iloc[1:2].unstack("ix2")
+ expected = DataFrame(
+ [expected_row],
+ columns=MultiIndex.from_product(
+ [result_columns[2:], [index_product]], names=[None, "ix2"]
+ ),
+ index=Index([2], name="ix1"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_multiple_no_empty_columns(self):
+ index = MultiIndex.from_tuples(
+ [(0, "foo", 0), (0, "bar", 0), (1, "baz", 1), (1, "qux", 1)]
+ )
+
+ s = Series(np.random.default_rng(2).standard_normal(4), index=index)
+
+ unstacked = s.unstack([1, 2])
+ expected = unstacked.dropna(axis=1, how="all")
+ tm.assert_frame_equal(unstacked, expected)
+
+ def test_stack(self, multiindex_year_month_day_dataframe_random_data, future_stack):
+ ymd = multiindex_year_month_day_dataframe_random_data
+
+ # regular roundtrip
+ unstacked = ymd.unstack()
+ restacked = unstacked.stack(future_stack=future_stack)
+ if future_stack:
+ # NA values in unstacked persist to restacked in version 3
+ restacked = restacked.dropna(how="all")
+ tm.assert_frame_equal(restacked, ymd)
+
+ unlexsorted = ymd.sort_index(level=2)
+
+ unstacked = unlexsorted.unstack(2)
+ restacked = unstacked.stack(future_stack=future_stack)
+ if future_stack:
+ # NA values in unstacked persist to restacked in version 3
+ restacked = restacked.dropna(how="all")
+ tm.assert_frame_equal(restacked.sort_index(level=0), ymd)
+
+ unlexsorted = unlexsorted[::-1]
+ unstacked = unlexsorted.unstack(1)
+ restacked = unstacked.stack(future_stack=future_stack).swaplevel(1, 2)
+ if future_stack:
+ # NA values in unstacked persist to restacked in version 3
+ restacked = restacked.dropna(how="all")
+ tm.assert_frame_equal(restacked.sort_index(level=0), ymd)
+
+ unlexsorted = unlexsorted.swaplevel(0, 1)
+ unstacked = unlexsorted.unstack(0).swaplevel(0, 1, axis=1)
+ restacked = unstacked.stack(0, future_stack=future_stack).swaplevel(1, 2)
+ if future_stack:
+ # NA values in unstacked persist to restacked in version 3
+ restacked = restacked.dropna(how="all")
+ tm.assert_frame_equal(restacked.sort_index(level=0), ymd)
+
+ # columns unsorted
+ unstacked = ymd.unstack()
+ restacked = unstacked.stack(future_stack=future_stack)
+ if future_stack:
+ # NA values in unstacked persist to restacked in version 3
+ restacked = restacked.dropna(how="all")
+ tm.assert_frame_equal(restacked, ymd)
+
+ # more than 2 levels in the columns
+ unstacked = ymd.unstack(1).unstack(1)
+
+ result = unstacked.stack(1, future_stack=future_stack)
+ expected = ymd.unstack()
+ tm.assert_frame_equal(result, expected)
+
+ result = unstacked.stack(2, future_stack=future_stack)
+ expected = ymd.unstack(1)
+ tm.assert_frame_equal(result, expected)
+
+ result = unstacked.stack(0, future_stack=future_stack)
+ expected = ymd.stack(future_stack=future_stack).unstack(1).unstack(1)
+ tm.assert_frame_equal(result, expected)
+
+ # not all levels present in each echelon
+ unstacked = ymd.unstack(2).loc[:, ::3]
+ stacked = unstacked.stack(future_stack=future_stack).stack(
+ future_stack=future_stack
+ )
+ ymd_stacked = ymd.stack(future_stack=future_stack)
+ if future_stack:
+ # NA values in unstacked persist to restacked in version 3
+ stacked = stacked.dropna(how="all")
+ ymd_stacked = ymd_stacked.dropna(how="all")
+ tm.assert_series_equal(stacked, ymd_stacked.reindex(stacked.index))
+
+ # stack with negative number
+ result = ymd.unstack(0).stack(-2, future_stack=future_stack)
+ expected = ymd.unstack(0).stack(0, future_stack=future_stack)
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "idx, columns, exp_idx",
+ [
+ [
+ list("abab"),
+ ["1st", "2nd", "1st"],
+ MultiIndex(
+ levels=[["a", "b"], ["1st", "2nd"]],
+ codes=[np.tile(np.arange(2).repeat(3), 2), np.tile([0, 1, 0], 4)],
+ ),
+ ],
+ [
+ MultiIndex.from_tuples((("a", 2), ("b", 1), ("a", 1), ("b", 2))),
+ ["1st", "2nd", "1st"],
+ MultiIndex(
+ levels=[["a", "b"], [1, 2], ["1st", "2nd"]],
+ codes=[
+ np.tile(np.arange(2).repeat(3), 2),
+ np.repeat([1, 0, 1], [3, 6, 3]),
+ np.tile([0, 1, 0], 4),
+ ],
+ ),
+ ],
+ ],
+ )
+ def test_stack_duplicate_index(self, idx, columns, exp_idx, future_stack):
+ # GH10417
+ df = DataFrame(
+ np.arange(12).reshape(4, 3),
+ index=idx,
+ columns=columns,
+ )
+ if future_stack:
+ msg = "Columns with duplicate values are not supported in stack"
+ with pytest.raises(ValueError, match=msg):
+ df.stack(future_stack=future_stack)
+ else:
+ result = df.stack(future_stack=future_stack)
+ expected = Series(np.arange(12), index=exp_idx)
+ tm.assert_series_equal(result, expected)
+ assert result.index.is_unique is False
+ li, ri = result.index, expected.index
+ tm.assert_index_equal(li, ri)
+
+ def test_unstack_odd_failure(self, future_stack):
+ data = """day,time,smoker,sum,len
+Fri,Dinner,No,8.25,3.
+Fri,Dinner,Yes,27.03,9
+Fri,Lunch,No,3.0,1
+Fri,Lunch,Yes,13.68,6
+Sat,Dinner,No,139.63,45
+Sat,Dinner,Yes,120.77,42
+Sun,Dinner,No,180.57,57
+Sun,Dinner,Yes,66.82,19
+Thu,Dinner,No,3.0,1
+Thu,Lunch,No,117.32,44
+Thu,Lunch,Yes,51.51,17"""
+
+ df = pd.read_csv(StringIO(data)).set_index(["day", "time", "smoker"])
+
+ # it works, #2100
+ result = df.unstack(2)
+
+ recons = result.stack(future_stack=future_stack)
+ if future_stack:
+ # NA values in unstacked persist to restacked in version 3
+ recons = recons.dropna(how="all")
+ tm.assert_frame_equal(recons, df)
+
+ def test_stack_mixed_dtype(self, multiindex_dataframe_random_data, future_stack):
+ frame = multiindex_dataframe_random_data
+
+ df = frame.T
+ df["foo", "four"] = "foo"
+ df = df.sort_index(level=1, axis=1)
+
+ stacked = df.stack(future_stack=future_stack)
+ result = df["foo"].stack(future_stack=future_stack).sort_index()
+ tm.assert_series_equal(stacked["foo"], result, check_names=False)
+ assert result.name is None
+ assert stacked["bar"].dtype == np.float64
+
+ def test_unstack_bug(self, future_stack):
+ df = DataFrame(
+ {
+ "state": ["naive", "naive", "naive", "active", "active", "active"],
+ "exp": ["a", "b", "b", "b", "a", "a"],
+ "barcode": [1, 2, 3, 4, 1, 3],
+ "v": ["hi", "hi", "bye", "bye", "bye", "peace"],
+ "extra": np.arange(6.0),
+ }
+ )
+
+ result = df.groupby(["state", "exp", "barcode", "v"]).apply(len)
+
+ unstacked = result.unstack()
+ restacked = unstacked.stack(future_stack=future_stack)
+ tm.assert_series_equal(restacked, result.reindex(restacked.index).astype(float))
+
+ def test_stack_unstack_preserve_names(
+ self, multiindex_dataframe_random_data, future_stack
+ ):
+ frame = multiindex_dataframe_random_data
+
+ unstacked = frame.unstack()
+ assert unstacked.index.name == "first"
+ assert unstacked.columns.names == ["exp", "second"]
+
+ restacked = unstacked.stack(future_stack=future_stack)
+ assert restacked.index.names == frame.index.names
+
+ @pytest.mark.parametrize("method", ["stack", "unstack"])
+ def test_stack_unstack_wrong_level_name(
+ self, method, multiindex_dataframe_random_data, future_stack
+ ):
+ # GH 18303 - wrong level name should raise
+ frame = multiindex_dataframe_random_data
+
+ # A DataFrame with flat axes:
+ df = frame.loc["foo"]
+
+ kwargs = {"future_stack": future_stack} if method == "stack" else {}
+ with pytest.raises(KeyError, match="does not match index name"):
+ getattr(df, method)("mistake", **kwargs)
+
+ if method == "unstack":
+ # Same on a Series:
+ s = df.iloc[:, 0]
+ with pytest.raises(KeyError, match="does not match index name"):
+ getattr(s, method)("mistake", **kwargs)
+
+ def test_unstack_level_name(self, multiindex_dataframe_random_data):
+ frame = multiindex_dataframe_random_data
+
+ result = frame.unstack("second")
+ expected = frame.unstack(level=1)
+ tm.assert_frame_equal(result, expected)
+
+ def test_stack_level_name(self, multiindex_dataframe_random_data, future_stack):
+ frame = multiindex_dataframe_random_data
+
+ unstacked = frame.unstack("second")
+ result = unstacked.stack("exp", future_stack=future_stack)
+ expected = frame.unstack().stack(0, future_stack=future_stack)
+ tm.assert_frame_equal(result, expected)
+
+ result = frame.stack("exp", future_stack=future_stack)
+ expected = frame.stack(future_stack=future_stack)
+ tm.assert_series_equal(result, expected)
+
+ def test_stack_unstack_multiple(
+ self, multiindex_year_month_day_dataframe_random_data, future_stack
+ ):
+ ymd = multiindex_year_month_day_dataframe_random_data
+
+ unstacked = ymd.unstack(["year", "month"])
+ expected = ymd.unstack("year").unstack("month")
+ tm.assert_frame_equal(unstacked, expected)
+ assert unstacked.columns.names == expected.columns.names
+
+ # series
+ s = ymd["A"]
+ s_unstacked = s.unstack(["year", "month"])
+ tm.assert_frame_equal(s_unstacked, expected["A"])
+
+ restacked = unstacked.stack(["year", "month"], future_stack=future_stack)
+ if future_stack:
+ # NA values in unstacked persist to restacked in version 3
+ restacked = restacked.dropna(how="all")
+ restacked = restacked.swaplevel(0, 1).swaplevel(1, 2)
+ restacked = restacked.sort_index(level=0)
+
+ tm.assert_frame_equal(restacked, ymd)
+ assert restacked.index.names == ymd.index.names
+
+ # GH #451
+ unstacked = ymd.unstack([1, 2])
+ expected = ymd.unstack(1).unstack(1).dropna(axis=1, how="all")
+ tm.assert_frame_equal(unstacked, expected)
+
+ unstacked = ymd.unstack([2, 1])
+ expected = ymd.unstack(2).unstack(1).dropna(axis=1, how="all")
+ tm.assert_frame_equal(unstacked, expected.loc[:, unstacked.columns])
+
+ def test_stack_names_and_numbers(
+ self, multiindex_year_month_day_dataframe_random_data, future_stack
+ ):
+ ymd = multiindex_year_month_day_dataframe_random_data
+
+ unstacked = ymd.unstack(["year", "month"])
+
+ # Can't use mixture of names and numbers to stack
+ with pytest.raises(ValueError, match="level should contain"):
+ unstacked.stack([0, "month"], future_stack=future_stack)
+
+ def test_stack_multiple_out_of_bounds(
+ self, multiindex_year_month_day_dataframe_random_data, future_stack
+ ):
+ # nlevels == 3
+ ymd = multiindex_year_month_day_dataframe_random_data
+
+ unstacked = ymd.unstack(["year", "month"])
+
+ with pytest.raises(IndexError, match="Too many levels"):
+ unstacked.stack([2, 3], future_stack=future_stack)
+ with pytest.raises(IndexError, match="not a valid level number"):
+ unstacked.stack([-4, -3], future_stack=future_stack)
+
+ def test_unstack_period_series(self):
+ # GH4342
+ idx1 = pd.PeriodIndex(
+ ["2013-01", "2013-01", "2013-02", "2013-02", "2013-03", "2013-03"],
+ freq="M",
+ name="period",
+ )
+ idx2 = Index(["A", "B"] * 3, name="str")
+ value = [1, 2, 3, 4, 5, 6]
+
+ idx = MultiIndex.from_arrays([idx1, idx2])
+ s = Series(value, index=idx)
+
+ result1 = s.unstack()
+ result2 = s.unstack(level=1)
+ result3 = s.unstack(level=0)
+
+ e_idx = pd.PeriodIndex(
+ ["2013-01", "2013-02", "2013-03"], freq="M", name="period"
+ )
+ expected = DataFrame(
+ {"A": [1, 3, 5], "B": [2, 4, 6]}, index=e_idx, columns=["A", "B"]
+ )
+ expected.columns.name = "str"
+
+ tm.assert_frame_equal(result1, expected)
+ tm.assert_frame_equal(result2, expected)
+ tm.assert_frame_equal(result3, expected.T)
+
+ idx1 = pd.PeriodIndex(
+ ["2013-01", "2013-01", "2013-02", "2013-02", "2013-03", "2013-03"],
+ freq="M",
+ name="period1",
+ )
+
+ idx2 = pd.PeriodIndex(
+ ["2013-12", "2013-11", "2013-10", "2013-09", "2013-08", "2013-07"],
+ freq="M",
+ name="period2",
+ )
+ idx = MultiIndex.from_arrays([idx1, idx2])
+ s = Series(value, index=idx)
+
+ result1 = s.unstack()
+ result2 = s.unstack(level=1)
+ result3 = s.unstack(level=0)
+
+ e_idx = pd.PeriodIndex(
+ ["2013-01", "2013-02", "2013-03"], freq="M", name="period1"
+ )
+ e_cols = pd.PeriodIndex(
+ ["2013-07", "2013-08", "2013-09", "2013-10", "2013-11", "2013-12"],
+ freq="M",
+ name="period2",
+ )
+ expected = DataFrame(
+ [
+ [np.nan, np.nan, np.nan, np.nan, 2, 1],
+ [np.nan, np.nan, 4, 3, np.nan, np.nan],
+ [6, 5, np.nan, np.nan, np.nan, np.nan],
+ ],
+ index=e_idx,
+ columns=e_cols,
+ )
+
+ tm.assert_frame_equal(result1, expected)
+ tm.assert_frame_equal(result2, expected)
+ tm.assert_frame_equal(result3, expected.T)
+
+ def test_unstack_period_frame(self):
+ # GH4342
+ idx1 = pd.PeriodIndex(
+ ["2014-01", "2014-02", "2014-02", "2014-02", "2014-01", "2014-01"],
+ freq="M",
+ name="period1",
+ )
+ idx2 = pd.PeriodIndex(
+ ["2013-12", "2013-12", "2014-02", "2013-10", "2013-10", "2014-02"],
+ freq="M",
+ name="period2",
+ )
+ value = {"A": [1, 2, 3, 4, 5, 6], "B": [6, 5, 4, 3, 2, 1]}
+ idx = MultiIndex.from_arrays([idx1, idx2])
+ df = DataFrame(value, index=idx)
+
+ result1 = df.unstack()
+ result2 = df.unstack(level=1)
+ result3 = df.unstack(level=0)
+
+ e_1 = pd.PeriodIndex(["2014-01", "2014-02"], freq="M", name="period1")
+ e_2 = pd.PeriodIndex(
+ ["2013-10", "2013-12", "2014-02", "2013-10", "2013-12", "2014-02"],
+ freq="M",
+ name="period2",
+ )
+ e_cols = MultiIndex.from_arrays(["A A A B B B".split(), e_2])
+ expected = DataFrame(
+ [[5, 1, 6, 2, 6, 1], [4, 2, 3, 3, 5, 4]], index=e_1, columns=e_cols
+ )
+
+ tm.assert_frame_equal(result1, expected)
+ tm.assert_frame_equal(result2, expected)
+
+ e_1 = pd.PeriodIndex(
+ ["2014-01", "2014-02", "2014-01", "2014-02"], freq="M", name="period1"
+ )
+ e_2 = pd.PeriodIndex(
+ ["2013-10", "2013-12", "2014-02"], freq="M", name="period2"
+ )
+ e_cols = MultiIndex.from_arrays(["A A B B".split(), e_1])
+ expected = DataFrame(
+ [[5, 4, 2, 3], [1, 2, 6, 5], [6, 3, 1, 4]], index=e_2, columns=e_cols
+ )
+
+ tm.assert_frame_equal(result3, expected)
+
+ def test_stack_multiple_bug(self, future_stack):
+ # bug when some uniques are not present in the data GH#3170
+ id_col = ([1] * 3) + ([2] * 3)
+ name = (["a"] * 3) + (["b"] * 3)
+ date = pd.to_datetime(["2013-01-03", "2013-01-04", "2013-01-05"] * 2)
+ var1 = np.random.default_rng(2).integers(0, 100, 6)
+ df = DataFrame({"ID": id_col, "NAME": name, "DATE": date, "VAR1": var1})
+
+ multi = df.set_index(["DATE", "ID"])
+ multi.columns.name = "Params"
+ unst = multi.unstack("ID")
+ msg = re.escape("agg function failed [how->mean,dtype->object]")
+ with pytest.raises(TypeError, match=msg):
+ unst.resample("W-THU").mean()
+ down = unst.resample("W-THU").mean(numeric_only=True)
+ rs = down.stack("ID", future_stack=future_stack)
+ xp = (
+ unst.loc[:, ["VAR1"]]
+ .resample("W-THU")
+ .mean()
+ .stack("ID", future_stack=future_stack)
+ )
+ xp.columns.name = "Params"
+ tm.assert_frame_equal(rs, xp)
+
+ def test_stack_dropna(self, future_stack):
+ # GH#3997
+ df = DataFrame({"A": ["a1", "a2"], "B": ["b1", "b2"], "C": [1, 1]})
+ df = df.set_index(["A", "B"])
+
+ dropna = False if not future_stack else lib.no_default
+ stacked = df.unstack().stack(dropna=dropna, future_stack=future_stack)
+ assert len(stacked) > len(stacked.dropna())
+
+ if future_stack:
+ with pytest.raises(ValueError, match="dropna must be unspecified"):
+ df.unstack().stack(dropna=True, future_stack=future_stack)
+ else:
+ stacked = df.unstack().stack(dropna=True, future_stack=future_stack)
+ tm.assert_frame_equal(stacked, stacked.dropna())
+
+ def test_unstack_multiple_hierarchical(self, future_stack):
+ df = DataFrame(
+ index=[
+ [0, 0, 0, 0, 1, 1, 1, 1],
+ [0, 0, 1, 1, 0, 0, 1, 1],
+ [0, 1, 0, 1, 0, 1, 0, 1],
+ ],
+ columns=[[0, 0, 1, 1], [0, 1, 0, 1]],
+ )
+
+ df.index.names = ["a", "b", "c"]
+ df.columns.names = ["d", "e"]
+
+ # it works!
+ df.unstack(["b", "c"])
+
+ def test_unstack_sparse_keyspace(self):
+ # memory problems with naive impl GH#2278
+ # Generate Long File & Test Pivot
+ NUM_ROWS = 1000
+
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).integers(100, size=NUM_ROWS),
+ "B": np.random.default_rng(3).integers(300, size=NUM_ROWS),
+ "C": np.random.default_rng(4).integers(-7, 7, size=NUM_ROWS),
+ "D": np.random.default_rng(5).integers(-19, 19, size=NUM_ROWS),
+ "E": np.random.default_rng(6).integers(3000, size=NUM_ROWS),
+ "F": np.random.default_rng(7).standard_normal(NUM_ROWS),
+ }
+ )
+
+ idf = df.set_index(["A", "B", "C", "D", "E"])
+
+ # it works! is sufficient
+ idf.unstack("E")
+
+ def test_unstack_unobserved_keys(self, future_stack):
+ # related to GH#2278 refactoring
+ levels = [[0, 1], [0, 1, 2, 3]]
+ codes = [[0, 0, 1, 1], [0, 2, 0, 2]]
+
+ index = MultiIndex(levels, codes)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((4, 2)), index=index)
+
+ result = df.unstack()
+ assert len(result.columns) == 4
+
+ recons = result.stack(future_stack=future_stack)
+ tm.assert_frame_equal(recons, df)
+
+ @pytest.mark.slow
+ def test_unstack_number_of_levels_larger_than_int32(self, monkeypatch):
+ # GH#20601
+ # GH 26314: Change ValueError to PerformanceWarning
+
+ class MockUnstacker(reshape_lib._Unstacker):
+ def __init__(self, *args, **kwargs) -> None:
+ # __init__ will raise the warning
+ super().__init__(*args, **kwargs)
+ raise Exception("Don't compute final result.")
+
+ with monkeypatch.context() as m:
+ m.setattr(reshape_lib, "_Unstacker", MockUnstacker)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((2**16, 2)),
+ index=[np.arange(2**16), np.arange(2**16)],
+ )
+ msg = "The following operation may generate"
+ with tm.assert_produces_warning(PerformanceWarning, match=msg):
+ with pytest.raises(Exception, match="Don't compute final result."):
+ df.unstack()
+
+ @pytest.mark.parametrize(
+ "levels",
+ itertools.chain.from_iterable(
+ itertools.product(itertools.permutations([0, 1, 2], width), repeat=2)
+ for width in [2, 3]
+ ),
+ )
+ @pytest.mark.parametrize("stack_lev", range(2))
+ @pytest.mark.parametrize("sort", [True, False])
+ def test_stack_order_with_unsorted_levels(
+ self, levels, stack_lev, sort, future_stack
+ ):
+ # GH#16323
+ # deep check for 1-row case
+ columns = MultiIndex(levels=levels, codes=[[0, 0, 1, 1], [0, 1, 0, 1]])
+ df = DataFrame(columns=columns, data=[range(4)])
+ kwargs = {} if future_stack else {"sort": sort}
+ df_stacked = df.stack(stack_lev, future_stack=future_stack, **kwargs)
+ for row in df.index:
+ for col in df.columns:
+ expected = df.loc[row, col]
+ result_row = row, col[stack_lev]
+ result_col = col[1 - stack_lev]
+ result = df_stacked.loc[result_row, result_col]
+ assert result == expected
+
+ def test_stack_order_with_unsorted_levels_multi_row(self, future_stack):
+ # GH#16323
+
+ # check multi-row case
+ mi = MultiIndex(
+ levels=[["A", "C", "B"], ["B", "A", "C"]],
+ codes=[np.repeat(range(3), 3), np.tile(range(3), 3)],
+ )
+ df = DataFrame(
+ columns=mi, index=range(5), data=np.arange(5 * len(mi)).reshape(5, -1)
+ )
+ assert all(
+ df.loc[row, col]
+ == df.stack(0, future_stack=future_stack).loc[(row, col[0]), col[1]]
+ for row in df.index
+ for col in df.columns
+ )
+
+ def test_stack_order_with_unsorted_levels_multi_row_2(self, future_stack):
+ # GH#53636
+ levels = ((0, 1), (1, 0))
+ stack_lev = 1
+ columns = MultiIndex(levels=levels, codes=[[0, 0, 1, 1], [0, 1, 0, 1]])
+ df = DataFrame(columns=columns, data=[range(4)], index=[1, 0, 2, 3])
+ kwargs = {} if future_stack else {"sort": True}
+ result = df.stack(stack_lev, future_stack=future_stack, **kwargs)
+ expected_index = MultiIndex(
+ levels=[[0, 1, 2, 3], [0, 1]],
+ codes=[[1, 1, 0, 0, 2, 2, 3, 3], [1, 0, 1, 0, 1, 0, 1, 0]],
+ )
+ expected = DataFrame(
+ {
+ 0: [0, 1, 0, 1, 0, 1, 0, 1],
+ 1: [2, 3, 2, 3, 2, 3, 2, 3],
+ },
+ index=expected_index,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_stack_unstack_unordered_multiindex(self, future_stack):
+ # GH# 18265
+ values = np.arange(5)
+ data = np.vstack(
+ [
+ [f"b{x}" for x in values], # b0, b1, ..
+ [f"a{x}" for x in values], # a0, a1, ..
+ ]
+ )
+ df = DataFrame(data.T, columns=["b", "a"])
+ df.columns.name = "first"
+ second_level_dict = {"x": df}
+ multi_level_df = pd.concat(second_level_dict, axis=1)
+ multi_level_df.columns.names = ["second", "first"]
+ df = multi_level_df.reindex(sorted(multi_level_df.columns), axis=1)
+ result = df.stack(["first", "second"], future_stack=future_stack).unstack(
+ ["first", "second"]
+ )
+ expected = DataFrame(
+ [["a0", "b0"], ["a1", "b1"], ["a2", "b2"], ["a3", "b3"], ["a4", "b4"]],
+ index=[0, 1, 2, 3, 4],
+ columns=MultiIndex.from_tuples(
+ [("a", "x"), ("b", "x")], names=["first", "second"]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_preserve_types(
+ self, multiindex_year_month_day_dataframe_random_data
+ ):
+ # GH#403
+ ymd = multiindex_year_month_day_dataframe_random_data
+ ymd["E"] = "foo"
+ ymd["F"] = 2
+
+ unstacked = ymd.unstack("month")
+ assert unstacked["A", 1].dtype == np.float64
+ assert unstacked["E", 1].dtype == np.object_
+ assert unstacked["F", 1].dtype == np.float64
+
+ def test_unstack_group_index_overflow(self, future_stack):
+ codes = np.tile(np.arange(500), 2)
+ level = np.arange(500)
+
+ index = MultiIndex(
+ levels=[level] * 8 + [[0, 1]],
+ codes=[codes] * 8 + [np.arange(2).repeat(500)],
+ )
+
+ s = Series(np.arange(1000), index=index)
+ result = s.unstack()
+ assert result.shape == (500, 2)
+
+ # test roundtrip
+ stacked = result.stack(future_stack=future_stack)
+ tm.assert_series_equal(s, stacked.reindex(s.index))
+
+ # put it at beginning
+ index = MultiIndex(
+ levels=[[0, 1]] + [level] * 8,
+ codes=[np.arange(2).repeat(500)] + [codes] * 8,
+ )
+
+ s = Series(np.arange(1000), index=index)
+ result = s.unstack(0)
+ assert result.shape == (500, 2)
+
+ # put it in middle
+ index = MultiIndex(
+ levels=[level] * 4 + [[0, 1]] + [level] * 4,
+ codes=([codes] * 4 + [np.arange(2).repeat(500)] + [codes] * 4),
+ )
+
+ s = Series(np.arange(1000), index=index)
+ result = s.unstack(4)
+ assert result.shape == (500, 2)
+
+ def test_unstack_with_missing_int_cast_to_float(self, using_array_manager):
+ # https://github.com/pandas-dev/pandas/issues/37115
+ df = DataFrame(
+ {
+ "a": ["A", "A", "B"],
+ "b": ["ca", "cb", "cb"],
+ "v": [10] * 3,
+ }
+ ).set_index(["a", "b"])
+
+ # add another int column to get 2 blocks
+ df["is_"] = 1
+ if not using_array_manager:
+ assert len(df._mgr.blocks) == 2
+
+ result = df.unstack("b")
+ result[("is_", "ca")] = result[("is_", "ca")].fillna(0)
+
+ expected = DataFrame(
+ [[10.0, 10.0, 1.0, 1.0], [np.nan, 10.0, 0.0, 1.0]],
+ index=Index(["A", "B"], dtype="object", name="a"),
+ columns=MultiIndex.from_tuples(
+ [("v", "ca"), ("v", "cb"), ("is_", "ca"), ("is_", "cb")],
+ names=[None, "b"],
+ ),
+ )
+ if using_array_manager:
+ # INFO(ArrayManager) with ArrayManager preserve dtype where possible
+ expected[("v", "cb")] = expected[("v", "cb")].astype("int64")
+ expected[("is_", "cb")] = expected[("is_", "cb")].astype("int64")
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_with_level_has_nan(self):
+ # GH 37510
+ df1 = DataFrame(
+ {
+ "L1": [1, 2, 3, 4],
+ "L2": [3, 4, 1, 2],
+ "L3": [1, 1, 1, 1],
+ "x": [1, 2, 3, 4],
+ }
+ )
+ df1 = df1.set_index(["L1", "L2", "L3"])
+ new_levels = ["n1", "n2", "n3", None]
+ df1.index = df1.index.set_levels(levels=new_levels, level="L1")
+ df1.index = df1.index.set_levels(levels=new_levels, level="L2")
+
+ result = df1.unstack("L3")[("x", 1)].sort_index().index
+ expected = MultiIndex(
+ levels=[["n1", "n2", "n3", None], ["n1", "n2", "n3", None]],
+ codes=[[0, 1, 2, 3], [2, 3, 0, 1]],
+ names=["L1", "L2"],
+ )
+
+ tm.assert_index_equal(result, expected)
+
+ def test_stack_nan_in_multiindex_columns(self, future_stack):
+ # GH#39481
+ df = DataFrame(
+ np.zeros([1, 5]),
+ columns=MultiIndex.from_tuples(
+ [
+ (0, None, None),
+ (0, 2, 0),
+ (0, 2, 1),
+ (0, 3, 0),
+ (0, 3, 1),
+ ],
+ ),
+ )
+ result = df.stack(2, future_stack=future_stack)
+ if future_stack:
+ index = MultiIndex(levels=[[0], [0.0, 1.0]], codes=[[0, 0, 0], [-1, 0, 1]])
+ columns = MultiIndex(levels=[[0], [2, 3]], codes=[[0, 0, 0], [-1, 0, 1]])
+ else:
+ index = Index([(0, None), (0, 0), (0, 1)])
+ columns = Index([(0, None), (0, 2), (0, 3)])
+ expected = DataFrame(
+ [[0.0, np.nan, np.nan], [np.nan, 0.0, 0.0], [np.nan, 0.0, 0.0]],
+ index=index,
+ columns=columns,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_multi_level_stack_categorical(self, future_stack):
+ # GH 15239
+ midx = MultiIndex.from_arrays(
+ [
+ ["A"] * 2 + ["B"] * 2,
+ pd.Categorical(list("abab")),
+ pd.Categorical(list("ccdd")),
+ ]
+ )
+ df = DataFrame(np.arange(8).reshape(2, 4), columns=midx)
+ result = df.stack([1, 2], future_stack=future_stack)
+ if future_stack:
+ expected = DataFrame(
+ [
+ [0, np.nan],
+ [1, np.nan],
+ [np.nan, 2],
+ [np.nan, 3],
+ [4, np.nan],
+ [5, np.nan],
+ [np.nan, 6],
+ [np.nan, 7],
+ ],
+ columns=["A", "B"],
+ index=MultiIndex.from_arrays(
+ [
+ [0] * 4 + [1] * 4,
+ pd.Categorical(list("abababab")),
+ pd.Categorical(list("ccddccdd")),
+ ]
+ ),
+ )
+ else:
+ expected = DataFrame(
+ [
+ [0, np.nan],
+ [np.nan, 2],
+ [1, np.nan],
+ [np.nan, 3],
+ [4, np.nan],
+ [np.nan, 6],
+ [5, np.nan],
+ [np.nan, 7],
+ ],
+ columns=["A", "B"],
+ index=MultiIndex.from_arrays(
+ [
+ [0] * 4 + [1] * 4,
+ pd.Categorical(list("aabbaabb")),
+ pd.Categorical(list("cdcdcdcd")),
+ ]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_stack_nan_level(self, future_stack):
+ # GH 9406
+ df_nan = DataFrame(
+ np.arange(4).reshape(2, 2),
+ columns=MultiIndex.from_tuples(
+ [("A", np.nan), ("B", "b")], names=["Upper", "Lower"]
+ ),
+ index=Index([0, 1], name="Num"),
+ dtype=np.float64,
+ )
+ result = df_nan.stack(future_stack=future_stack)
+ if future_stack:
+ index = MultiIndex(
+ levels=[[0, 1], [np.nan, "b"]],
+ codes=[[0, 0, 1, 1], [0, 1, 0, 1]],
+ names=["Num", "Lower"],
+ )
+ else:
+ index = MultiIndex.from_tuples(
+ [(0, np.nan), (0, "b"), (1, np.nan), (1, "b")], names=["Num", "Lower"]
+ )
+ expected = DataFrame(
+ [[0.0, np.nan], [np.nan, 1], [2.0, np.nan], [np.nan, 3.0]],
+ columns=Index(["A", "B"], name="Upper"),
+ index=index,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_categorical_columns(self):
+ # GH 14018
+ idx = MultiIndex.from_product([["A"], [0, 1]])
+ df = DataFrame({"cat": pd.Categorical(["a", "b"])}, index=idx)
+ result = df.unstack()
+ expected = DataFrame(
+ {
+ 0: pd.Categorical(["a"], categories=["a", "b"]),
+ 1: pd.Categorical(["b"], categories=["a", "b"]),
+ },
+ index=["A"],
+ )
+ expected.columns = MultiIndex.from_tuples([("cat", 0), ("cat", 1)])
+ tm.assert_frame_equal(result, expected)
+
+ def test_stack_unsorted(self, future_stack):
+ # GH 16925
+ PAE = ["ITA", "FRA"]
+ VAR = ["A1", "A2"]
+ TYP = ["CRT", "DBT", "NET"]
+ MI = MultiIndex.from_product([PAE, VAR, TYP], names=["PAE", "VAR", "TYP"])
+
+ V = list(range(len(MI)))
+ DF = DataFrame(data=V, index=MI, columns=["VALUE"])
+
+ DF = DF.unstack(["VAR", "TYP"])
+ DF.columns = DF.columns.droplevel(0)
+ DF.loc[:, ("A0", "NET")] = 9999
+
+ result = DF.stack(["VAR", "TYP"], future_stack=future_stack).sort_index()
+ expected = (
+ DF.sort_index(axis=1)
+ .stack(["VAR", "TYP"], future_stack=future_stack)
+ .sort_index()
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_stack_nullable_dtype(self, future_stack):
+ # GH#43561
+ columns = MultiIndex.from_product(
+ [["54511", "54515"], ["r", "t_mean"]], names=["station", "element"]
+ )
+ index = Index([1, 2, 3], name="time")
+
+ arr = np.array([[50, 226, 10, 215], [10, 215, 9, 220], [305, 232, 111, 220]])
+ df = DataFrame(arr, columns=columns, index=index, dtype=pd.Int64Dtype())
+
+ result = df.stack("station", future_stack=future_stack)
+
+ expected = (
+ df.astype(np.int64)
+ .stack("station", future_stack=future_stack)
+ .astype(pd.Int64Dtype())
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # non-homogeneous case
+ df[df.columns[0]] = df[df.columns[0]].astype(pd.Float64Dtype())
+ result = df.stack("station", future_stack=future_stack)
+
+ expected = DataFrame(
+ {
+ "r": pd.array(
+ [50.0, 10.0, 10.0, 9.0, 305.0, 111.0], dtype=pd.Float64Dtype()
+ ),
+ "t_mean": pd.array(
+ [226, 215, 215, 220, 232, 220], dtype=pd.Int64Dtype()
+ ),
+ },
+ index=MultiIndex.from_product([index, columns.levels[0]]),
+ )
+ expected.columns.name = "element"
+ tm.assert_frame_equal(result, expected)
+
+ def test_unstack_mixed_level_names(self):
+ # GH#48763
+ arrays = [["a", "a"], [1, 2], ["red", "blue"]]
+ idx = MultiIndex.from_arrays(arrays, names=("x", 0, "y"))
+ df = DataFrame({"m": [1, 2]}, index=idx)
+ result = df.unstack("x")
+ expected = DataFrame(
+ [[1], [2]],
+ columns=MultiIndex.from_tuples([("m", "a")], names=[None, "x"]),
+ index=MultiIndex.from_tuples([(1, "red"), (2, "blue")], names=[0, "y"]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_stack_tuple_columns(future_stack):
+ # GH#54948 - test stack when the input has a non-MultiIndex with tuples
+ df = DataFrame(
+ [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=[("a", 1), ("a", 2), ("b", 1)]
+ )
+ result = df.stack(future_stack=future_stack)
+ expected = Series(
+ [1, 2, 3, 4, 5, 6, 7, 8, 9],
+ index=MultiIndex(
+ levels=[[0, 1, 2], [("a", 1), ("a", 2), ("b", 1)]],
+ codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],
+ ),
+ )
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_subclass.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_subclass.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef78ae62cb4d6c1c956ca372d9e25cde1729c9be
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_subclass.py
@@ -0,0 +1,814 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
+import pandas._testing as tm
+
+pytestmark = pytest.mark.filterwarnings(
+ "ignore:Passing a BlockManager|Passing a SingleBlockManager:DeprecationWarning"
+)
+
+
+@pytest.fixture()
+def gpd_style_subclass_df():
+ class SubclassedDataFrame(DataFrame):
+ @property
+ def _constructor(self):
+ return SubclassedDataFrame
+
+ return SubclassedDataFrame({"a": [1, 2, 3]})
+
+
+class TestDataFrameSubclassing:
+ def test_frame_subclassing_and_slicing(self):
+ # Subclass frame and ensure it returns the right class on slicing it
+ # In reference to PR 9632
+
+ class CustomSeries(Series):
+ @property
+ def _constructor(self):
+ return CustomSeries
+
+ def custom_series_function(self):
+ return "OK"
+
+ class CustomDataFrame(DataFrame):
+ """
+ Subclasses pandas DF, fills DF with simulation results, adds some
+ custom plotting functions.
+ """
+
+ def __init__(self, *args, **kw) -> None:
+ super().__init__(*args, **kw)
+
+ @property
+ def _constructor(self):
+ return CustomDataFrame
+
+ _constructor_sliced = CustomSeries
+
+ def custom_frame_function(self):
+ return "OK"
+
+ data = {"col1": range(10), "col2": range(10)}
+ cdf = CustomDataFrame(data)
+
+ # Did we get back our own DF class?
+ assert isinstance(cdf, CustomDataFrame)
+
+ # Do we get back our own Series class after selecting a column?
+ cdf_series = cdf.col1
+ assert isinstance(cdf_series, CustomSeries)
+ assert cdf_series.custom_series_function() == "OK"
+
+ # Do we get back our own DF class after slicing row-wise?
+ cdf_rows = cdf[1:5]
+ assert isinstance(cdf_rows, CustomDataFrame)
+ assert cdf_rows.custom_frame_function() == "OK"
+
+ # Make sure sliced part of multi-index frame is custom class
+ mcol = MultiIndex.from_tuples([("A", "A"), ("A", "B")])
+ cdf_multi = CustomDataFrame([[0, 1], [2, 3]], columns=mcol)
+ assert isinstance(cdf_multi["A"], CustomDataFrame)
+
+ mcol = MultiIndex.from_tuples([("A", ""), ("B", "")])
+ cdf_multi2 = CustomDataFrame([[0, 1], [2, 3]], columns=mcol)
+ assert isinstance(cdf_multi2["A"], CustomSeries)
+
+ def test_dataframe_metadata(self):
+ df = tm.SubclassedDataFrame(
+ {"X": [1, 2, 3], "Y": [1, 2, 3]}, index=["a", "b", "c"]
+ )
+ df.testattr = "XXX"
+
+ assert df.testattr == "XXX"
+ assert df[["X"]].testattr == "XXX"
+ assert df.loc[["a", "b"], :].testattr == "XXX"
+ assert df.iloc[[0, 1], :].testattr == "XXX"
+
+ # see gh-9776
+ assert df.iloc[0:1, :].testattr == "XXX"
+
+ # see gh-10553
+ unpickled = tm.round_trip_pickle(df)
+ tm.assert_frame_equal(df, unpickled)
+ assert df._metadata == unpickled._metadata
+ assert df.testattr == unpickled.testattr
+
+ def test_indexing_sliced(self):
+ # GH 11559
+ df = tm.SubclassedDataFrame(
+ {"X": [1, 2, 3], "Y": [4, 5, 6], "Z": [7, 8, 9]}, index=["a", "b", "c"]
+ )
+ res = df.loc[:, "X"]
+ exp = tm.SubclassedSeries([1, 2, 3], index=list("abc"), name="X")
+ tm.assert_series_equal(res, exp)
+ assert isinstance(res, tm.SubclassedSeries)
+
+ res = df.iloc[:, 1]
+ exp = tm.SubclassedSeries([4, 5, 6], index=list("abc"), name="Y")
+ tm.assert_series_equal(res, exp)
+ assert isinstance(res, tm.SubclassedSeries)
+
+ res = df.loc[:, "Z"]
+ exp = tm.SubclassedSeries([7, 8, 9], index=list("abc"), name="Z")
+ tm.assert_series_equal(res, exp)
+ assert isinstance(res, tm.SubclassedSeries)
+
+ res = df.loc["a", :]
+ exp = tm.SubclassedSeries([1, 4, 7], index=list("XYZ"), name="a")
+ tm.assert_series_equal(res, exp)
+ assert isinstance(res, tm.SubclassedSeries)
+
+ res = df.iloc[1, :]
+ exp = tm.SubclassedSeries([2, 5, 8], index=list("XYZ"), name="b")
+ tm.assert_series_equal(res, exp)
+ assert isinstance(res, tm.SubclassedSeries)
+
+ res = df.loc["c", :]
+ exp = tm.SubclassedSeries([3, 6, 9], index=list("XYZ"), name="c")
+ tm.assert_series_equal(res, exp)
+ assert isinstance(res, tm.SubclassedSeries)
+
+ def test_subclass_attr_err_propagation(self):
+ # GH 11808
+ class A(DataFrame):
+ @property
+ def nonexistence(self):
+ return self.i_dont_exist
+
+ with pytest.raises(AttributeError, match=".*i_dont_exist.*"):
+ A().nonexistence
+
+ def test_subclass_align(self):
+ # GH 12983
+ df1 = tm.SubclassedDataFrame(
+ {"a": [1, 3, 5], "b": [1, 3, 5]}, index=list("ACE")
+ )
+ df2 = tm.SubclassedDataFrame(
+ {"c": [1, 2, 4], "d": [1, 2, 4]}, index=list("ABD")
+ )
+
+ res1, res2 = df1.align(df2, axis=0)
+ exp1 = tm.SubclassedDataFrame(
+ {"a": [1, np.nan, 3, np.nan, 5], "b": [1, np.nan, 3, np.nan, 5]},
+ index=list("ABCDE"),
+ )
+ exp2 = tm.SubclassedDataFrame(
+ {"c": [1, 2, np.nan, 4, np.nan], "d": [1, 2, np.nan, 4, np.nan]},
+ index=list("ABCDE"),
+ )
+ assert isinstance(res1, tm.SubclassedDataFrame)
+ tm.assert_frame_equal(res1, exp1)
+ assert isinstance(res2, tm.SubclassedDataFrame)
+ tm.assert_frame_equal(res2, exp2)
+
+ res1, res2 = df1.a.align(df2.c)
+ assert isinstance(res1, tm.SubclassedSeries)
+ tm.assert_series_equal(res1, exp1.a)
+ assert isinstance(res2, tm.SubclassedSeries)
+ tm.assert_series_equal(res2, exp2.c)
+
+ def test_subclass_align_combinations(self):
+ # GH 12983
+ df = tm.SubclassedDataFrame({"a": [1, 3, 5], "b": [1, 3, 5]}, index=list("ACE"))
+ s = tm.SubclassedSeries([1, 2, 4], index=list("ABD"), name="x")
+
+ # frame + series
+ res1, res2 = df.align(s, axis=0)
+ exp1 = tm.SubclassedDataFrame(
+ {"a": [1, np.nan, 3, np.nan, 5], "b": [1, np.nan, 3, np.nan, 5]},
+ index=list("ABCDE"),
+ )
+ # name is lost when
+ exp2 = tm.SubclassedSeries(
+ [1, 2, np.nan, 4, np.nan], index=list("ABCDE"), name="x"
+ )
+
+ assert isinstance(res1, tm.SubclassedDataFrame)
+ tm.assert_frame_equal(res1, exp1)
+ assert isinstance(res2, tm.SubclassedSeries)
+ tm.assert_series_equal(res2, exp2)
+
+ # series + frame
+ res1, res2 = s.align(df)
+ assert isinstance(res1, tm.SubclassedSeries)
+ tm.assert_series_equal(res1, exp2)
+ assert isinstance(res2, tm.SubclassedDataFrame)
+ tm.assert_frame_equal(res2, exp1)
+
+ def test_subclass_iterrows(self):
+ # GH 13977
+ df = tm.SubclassedDataFrame({"a": [1]})
+ for i, row in df.iterrows():
+ assert isinstance(row, tm.SubclassedSeries)
+ tm.assert_series_equal(row, df.loc[i])
+
+ def test_subclass_stack(self):
+ # GH 15564
+ df = tm.SubclassedDataFrame(
+ [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ index=["a", "b", "c"],
+ columns=["X", "Y", "Z"],
+ )
+
+ res = df.stack(future_stack=True)
+ exp = tm.SubclassedSeries(
+ [1, 2, 3, 4, 5, 6, 7, 8, 9], index=[list("aaabbbccc"), list("XYZXYZXYZ")]
+ )
+
+ tm.assert_series_equal(res, exp)
+
+ def test_subclass_stack_multi(self):
+ # GH 15564
+ df = tm.SubclassedDataFrame(
+ [[10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]],
+ index=MultiIndex.from_tuples(
+ list(zip(list("AABB"), list("cdcd"))), names=["aaa", "ccc"]
+ ),
+ columns=MultiIndex.from_tuples(
+ list(zip(list("WWXX"), list("yzyz"))), names=["www", "yyy"]
+ ),
+ )
+
+ exp = tm.SubclassedDataFrame(
+ [
+ [10, 12],
+ [11, 13],
+ [20, 22],
+ [21, 23],
+ [30, 32],
+ [31, 33],
+ [40, 42],
+ [41, 43],
+ ],
+ index=MultiIndex.from_tuples(
+ list(zip(list("AAAABBBB"), list("ccddccdd"), list("yzyzyzyz"))),
+ names=["aaa", "ccc", "yyy"],
+ ),
+ columns=Index(["W", "X"], name="www"),
+ )
+
+ res = df.stack(future_stack=True)
+ tm.assert_frame_equal(res, exp)
+
+ res = df.stack("yyy", future_stack=True)
+ tm.assert_frame_equal(res, exp)
+
+ exp = tm.SubclassedDataFrame(
+ [
+ [10, 11],
+ [12, 13],
+ [20, 21],
+ [22, 23],
+ [30, 31],
+ [32, 33],
+ [40, 41],
+ [42, 43],
+ ],
+ index=MultiIndex.from_tuples(
+ list(zip(list("AAAABBBB"), list("ccddccdd"), list("WXWXWXWX"))),
+ names=["aaa", "ccc", "www"],
+ ),
+ columns=Index(["y", "z"], name="yyy"),
+ )
+
+ res = df.stack("www", future_stack=True)
+ tm.assert_frame_equal(res, exp)
+
+ def test_subclass_stack_multi_mixed(self):
+ # GH 15564
+ df = tm.SubclassedDataFrame(
+ [
+ [10, 11, 12.0, 13.0],
+ [20, 21, 22.0, 23.0],
+ [30, 31, 32.0, 33.0],
+ [40, 41, 42.0, 43.0],
+ ],
+ index=MultiIndex.from_tuples(
+ list(zip(list("AABB"), list("cdcd"))), names=["aaa", "ccc"]
+ ),
+ columns=MultiIndex.from_tuples(
+ list(zip(list("WWXX"), list("yzyz"))), names=["www", "yyy"]
+ ),
+ )
+
+ exp = tm.SubclassedDataFrame(
+ [
+ [10, 12.0],
+ [11, 13.0],
+ [20, 22.0],
+ [21, 23.0],
+ [30, 32.0],
+ [31, 33.0],
+ [40, 42.0],
+ [41, 43.0],
+ ],
+ index=MultiIndex.from_tuples(
+ list(zip(list("AAAABBBB"), list("ccddccdd"), list("yzyzyzyz"))),
+ names=["aaa", "ccc", "yyy"],
+ ),
+ columns=Index(["W", "X"], name="www"),
+ )
+
+ res = df.stack(future_stack=True)
+ tm.assert_frame_equal(res, exp)
+
+ res = df.stack("yyy", future_stack=True)
+ tm.assert_frame_equal(res, exp)
+
+ exp = tm.SubclassedDataFrame(
+ [
+ [10.0, 11.0],
+ [12.0, 13.0],
+ [20.0, 21.0],
+ [22.0, 23.0],
+ [30.0, 31.0],
+ [32.0, 33.0],
+ [40.0, 41.0],
+ [42.0, 43.0],
+ ],
+ index=MultiIndex.from_tuples(
+ list(zip(list("AAAABBBB"), list("ccddccdd"), list("WXWXWXWX"))),
+ names=["aaa", "ccc", "www"],
+ ),
+ columns=Index(["y", "z"], name="yyy"),
+ )
+
+ res = df.stack("www", future_stack=True)
+ tm.assert_frame_equal(res, exp)
+
+ def test_subclass_unstack(self):
+ # GH 15564
+ df = tm.SubclassedDataFrame(
+ [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ index=["a", "b", "c"],
+ columns=["X", "Y", "Z"],
+ )
+
+ res = df.unstack()
+ exp = tm.SubclassedSeries(
+ [1, 4, 7, 2, 5, 8, 3, 6, 9], index=[list("XXXYYYZZZ"), list("abcabcabc")]
+ )
+
+ tm.assert_series_equal(res, exp)
+
+ def test_subclass_unstack_multi(self):
+ # GH 15564
+ df = tm.SubclassedDataFrame(
+ [[10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]],
+ index=MultiIndex.from_tuples(
+ list(zip(list("AABB"), list("cdcd"))), names=["aaa", "ccc"]
+ ),
+ columns=MultiIndex.from_tuples(
+ list(zip(list("WWXX"), list("yzyz"))), names=["www", "yyy"]
+ ),
+ )
+
+ exp = tm.SubclassedDataFrame(
+ [[10, 20, 11, 21, 12, 22, 13, 23], [30, 40, 31, 41, 32, 42, 33, 43]],
+ index=Index(["A", "B"], name="aaa"),
+ columns=MultiIndex.from_tuples(
+ list(zip(list("WWWWXXXX"), list("yyzzyyzz"), list("cdcdcdcd"))),
+ names=["www", "yyy", "ccc"],
+ ),
+ )
+
+ res = df.unstack()
+ tm.assert_frame_equal(res, exp)
+
+ res = df.unstack("ccc")
+ tm.assert_frame_equal(res, exp)
+
+ exp = tm.SubclassedDataFrame(
+ [[10, 30, 11, 31, 12, 32, 13, 33], [20, 40, 21, 41, 22, 42, 23, 43]],
+ index=Index(["c", "d"], name="ccc"),
+ columns=MultiIndex.from_tuples(
+ list(zip(list("WWWWXXXX"), list("yyzzyyzz"), list("ABABABAB"))),
+ names=["www", "yyy", "aaa"],
+ ),
+ )
+
+ res = df.unstack("aaa")
+ tm.assert_frame_equal(res, exp)
+
+ def test_subclass_unstack_multi_mixed(self):
+ # GH 15564
+ df = tm.SubclassedDataFrame(
+ [
+ [10, 11, 12.0, 13.0],
+ [20, 21, 22.0, 23.0],
+ [30, 31, 32.0, 33.0],
+ [40, 41, 42.0, 43.0],
+ ],
+ index=MultiIndex.from_tuples(
+ list(zip(list("AABB"), list("cdcd"))), names=["aaa", "ccc"]
+ ),
+ columns=MultiIndex.from_tuples(
+ list(zip(list("WWXX"), list("yzyz"))), names=["www", "yyy"]
+ ),
+ )
+
+ exp = tm.SubclassedDataFrame(
+ [
+ [10, 20, 11, 21, 12.0, 22.0, 13.0, 23.0],
+ [30, 40, 31, 41, 32.0, 42.0, 33.0, 43.0],
+ ],
+ index=Index(["A", "B"], name="aaa"),
+ columns=MultiIndex.from_tuples(
+ list(zip(list("WWWWXXXX"), list("yyzzyyzz"), list("cdcdcdcd"))),
+ names=["www", "yyy", "ccc"],
+ ),
+ )
+
+ res = df.unstack()
+ tm.assert_frame_equal(res, exp)
+
+ res = df.unstack("ccc")
+ tm.assert_frame_equal(res, exp)
+
+ exp = tm.SubclassedDataFrame(
+ [
+ [10, 30, 11, 31, 12.0, 32.0, 13.0, 33.0],
+ [20, 40, 21, 41, 22.0, 42.0, 23.0, 43.0],
+ ],
+ index=Index(["c", "d"], name="ccc"),
+ columns=MultiIndex.from_tuples(
+ list(zip(list("WWWWXXXX"), list("yyzzyyzz"), list("ABABABAB"))),
+ names=["www", "yyy", "aaa"],
+ ),
+ )
+
+ res = df.unstack("aaa")
+ tm.assert_frame_equal(res, exp)
+
+ def test_subclass_pivot(self):
+ # GH 15564
+ df = tm.SubclassedDataFrame(
+ {
+ "index": ["A", "B", "C", "C", "B", "A"],
+ "columns": ["One", "One", "One", "Two", "Two", "Two"],
+ "values": [1.0, 2.0, 3.0, 3.0, 2.0, 1.0],
+ }
+ )
+
+ pivoted = df.pivot(index="index", columns="columns", values="values")
+
+ expected = tm.SubclassedDataFrame(
+ {
+ "One": {"A": 1.0, "B": 2.0, "C": 3.0},
+ "Two": {"A": 1.0, "B": 2.0, "C": 3.0},
+ }
+ )
+
+ expected.index.name, expected.columns.name = "index", "columns"
+
+ tm.assert_frame_equal(pivoted, expected)
+
+ def test_subclassed_melt(self):
+ # GH 15564
+ cheese = tm.SubclassedDataFrame(
+ {
+ "first": ["John", "Mary"],
+ "last": ["Doe", "Bo"],
+ "height": [5.5, 6.0],
+ "weight": [130, 150],
+ }
+ )
+
+ melted = pd.melt(cheese, id_vars=["first", "last"])
+
+ expected = tm.SubclassedDataFrame(
+ [
+ ["John", "Doe", "height", 5.5],
+ ["Mary", "Bo", "height", 6.0],
+ ["John", "Doe", "weight", 130],
+ ["Mary", "Bo", "weight", 150],
+ ],
+ columns=["first", "last", "variable", "value"],
+ )
+
+ tm.assert_frame_equal(melted, expected)
+
+ def test_subclassed_wide_to_long(self):
+ # GH 9762
+
+ x = np.random.default_rng(2).standard_normal(3)
+ df = tm.SubclassedDataFrame(
+ {
+ "A1970": {0: "a", 1: "b", 2: "c"},
+ "A1980": {0: "d", 1: "e", 2: "f"},
+ "B1970": {0: 2.5, 1: 1.2, 2: 0.7},
+ "B1980": {0: 3.2, 1: 1.3, 2: 0.1},
+ "X": dict(zip(range(3), x)),
+ }
+ )
+
+ df["id"] = df.index
+ exp_data = {
+ "X": x.tolist() + x.tolist(),
+ "A": ["a", "b", "c", "d", "e", "f"],
+ "B": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1],
+ "year": [1970, 1970, 1970, 1980, 1980, 1980],
+ "id": [0, 1, 2, 0, 1, 2],
+ }
+ expected = tm.SubclassedDataFrame(exp_data)
+ expected = expected.set_index(["id", "year"])[["X", "A", "B"]]
+ long_frame = pd.wide_to_long(df, ["A", "B"], i="id", j="year")
+
+ tm.assert_frame_equal(long_frame, expected)
+
+ def test_subclassed_apply(self):
+ # GH 19822
+
+ def check_row_subclass(row):
+ assert isinstance(row, tm.SubclassedSeries)
+
+ def stretch(row):
+ if row["variable"] == "height":
+ row["value"] += 0.5
+ return row
+
+ df = tm.SubclassedDataFrame(
+ [
+ ["John", "Doe", "height", 5.5],
+ ["Mary", "Bo", "height", 6.0],
+ ["John", "Doe", "weight", 130],
+ ["Mary", "Bo", "weight", 150],
+ ],
+ columns=["first", "last", "variable", "value"],
+ )
+
+ df.apply(lambda x: check_row_subclass(x))
+ df.apply(lambda x: check_row_subclass(x), axis=1)
+
+ expected = tm.SubclassedDataFrame(
+ [
+ ["John", "Doe", "height", 6.0],
+ ["Mary", "Bo", "height", 6.5],
+ ["John", "Doe", "weight", 130],
+ ["Mary", "Bo", "weight", 150],
+ ],
+ columns=["first", "last", "variable", "value"],
+ )
+
+ result = df.apply(lambda x: stretch(x), axis=1)
+ assert isinstance(result, tm.SubclassedDataFrame)
+ tm.assert_frame_equal(result, expected)
+
+ expected = tm.SubclassedDataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]])
+
+ result = df.apply(lambda x: tm.SubclassedSeries([1, 2, 3]), axis=1)
+ assert isinstance(result, tm.SubclassedDataFrame)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="expand")
+ assert isinstance(result, tm.SubclassedDataFrame)
+ tm.assert_frame_equal(result, expected)
+
+ expected = tm.SubclassedSeries([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]])
+
+ result = df.apply(lambda x: [1, 2, 3], axis=1)
+ assert not isinstance(result, tm.SubclassedDataFrame)
+ tm.assert_series_equal(result, expected)
+
+ def test_subclassed_reductions(self, all_reductions):
+ # GH 25596
+
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result = getattr(df, all_reductions)()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_subclassed_count(self):
+ df = tm.SubclassedDataFrame(
+ {
+ "Person": ["John", "Myla", "Lewis", "John", "Myla"],
+ "Age": [24.0, np.nan, 21.0, 33, 26],
+ "Single": [False, True, True, True, False],
+ }
+ )
+ result = df.count()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ df = tm.SubclassedDataFrame({"A": [1, 0, 3], "B": [0, 5, 6], "C": [7, 8, 0]})
+ result = df.count()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ df = tm.SubclassedDataFrame(
+ [[10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]],
+ index=MultiIndex.from_tuples(
+ list(zip(list("AABB"), list("cdcd"))), names=["aaa", "ccc"]
+ ),
+ columns=MultiIndex.from_tuples(
+ list(zip(list("WWXX"), list("yzyz"))), names=["www", "yyy"]
+ ),
+ )
+ result = df.count()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ df = tm.SubclassedDataFrame()
+ result = df.count()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_isin(self):
+ df = tm.SubclassedDataFrame(
+ {"num_legs": [2, 4], "num_wings": [2, 0]}, index=["falcon", "dog"]
+ )
+ result = df.isin([0, 2])
+ assert isinstance(result, tm.SubclassedDataFrame)
+
+ def test_duplicated(self):
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result = df.duplicated()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ df = tm.SubclassedDataFrame()
+ result = df.duplicated()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ @pytest.mark.parametrize("idx_method", ["idxmax", "idxmin"])
+ def test_idx(self, idx_method):
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result = getattr(df, idx_method)()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_dot(self):
+ df = tm.SubclassedDataFrame([[0, 1, -2, -1], [1, 1, 1, 1]])
+ s = tm.SubclassedSeries([1, 1, 2, 1])
+ result = df.dot(s)
+ assert isinstance(result, tm.SubclassedSeries)
+
+ df = tm.SubclassedDataFrame([[0, 1, -2, -1], [1, 1, 1, 1]])
+ s = tm.SubclassedDataFrame([1, 1, 2, 1])
+ result = df.dot(s)
+ assert isinstance(result, tm.SubclassedDataFrame)
+
+ def test_memory_usage(self):
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result = df.memory_usage()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ result = df.memory_usage(index=False)
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_corrwith(self):
+ pytest.importorskip("scipy")
+ index = ["a", "b", "c", "d", "e"]
+ columns = ["one", "two", "three", "four"]
+ df1 = tm.SubclassedDataFrame(
+ np.random.default_rng(2).standard_normal((5, 4)),
+ index=index,
+ columns=columns,
+ )
+ df2 = tm.SubclassedDataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=index[:4],
+ columns=columns,
+ )
+ correls = df1.corrwith(df2, axis=1, drop=True, method="kendall")
+
+ assert isinstance(correls, (tm.SubclassedSeries))
+
+ def test_asof(self):
+ N = 3
+ rng = pd.date_range("1/1/1990", periods=N, freq="53s")
+ df = tm.SubclassedDataFrame(
+ {
+ "A": [np.nan, np.nan, np.nan],
+ "B": [np.nan, np.nan, np.nan],
+ "C": [np.nan, np.nan, np.nan],
+ },
+ index=rng,
+ )
+
+ result = df.asof(rng[-2:])
+ assert isinstance(result, tm.SubclassedDataFrame)
+
+ result = df.asof(rng[-2])
+ assert isinstance(result, tm.SubclassedSeries)
+
+ result = df.asof("1989-12-31")
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_idxmin_preserves_subclass(self):
+ # GH 28330
+
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result = df.idxmin()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_idxmax_preserves_subclass(self):
+ # GH 28330
+
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result = df.idxmax()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_convert_dtypes_preserves_subclass(self, gpd_style_subclass_df):
+ # GH 43668
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result = df.convert_dtypes()
+ assert isinstance(result, tm.SubclassedDataFrame)
+
+ result = gpd_style_subclass_df.convert_dtypes()
+ assert isinstance(result, type(gpd_style_subclass_df))
+
+ def test_astype_preserves_subclass(self):
+ # GH#40810
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+
+ result = df.astype({"A": np.int64, "B": np.int32, "C": np.float64})
+ assert isinstance(result, tm.SubclassedDataFrame)
+
+ def test_equals_subclass(self):
+ # https://github.com/pandas-dev/pandas/pull/34402
+ # allow subclass in both directions
+ df1 = DataFrame({"a": [1, 2, 3]})
+ df2 = tm.SubclassedDataFrame({"a": [1, 2, 3]})
+ assert df1.equals(df2)
+ assert df2.equals(df1)
+
+ def test_replace_list_method(self):
+ # https://github.com/pandas-dev/pandas/pull/46018
+ df = tm.SubclassedDataFrame({"A": [0, 1, 2]})
+ msg = "The 'method' keyword in SubclassedDataFrame.replace is deprecated"
+ with tm.assert_produces_warning(
+ FutureWarning, match=msg, raise_on_extra_warnings=False
+ ):
+ result = df.replace([1, 2], method="ffill")
+ expected = tm.SubclassedDataFrame({"A": [0, 0, 0]})
+ assert isinstance(result, tm.SubclassedDataFrame)
+ tm.assert_frame_equal(result, expected)
+
+
+class MySubclassWithMetadata(DataFrame):
+ _metadata = ["my_metadata"]
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+
+ my_metadata = kwargs.pop("my_metadata", None)
+ if args and isinstance(args[0], MySubclassWithMetadata):
+ my_metadata = args[0].my_metadata # type: ignore[has-type]
+ self.my_metadata = my_metadata
+
+ @property
+ def _constructor(self):
+ return MySubclassWithMetadata
+
+
+def test_constructor_with_metadata():
+ # https://github.com/pandas-dev/pandas/pull/54922
+ # https://github.com/pandas-dev/pandas/issues/55120
+ df = MySubclassWithMetadata(
+ np.random.default_rng(2).random((5, 3)), columns=["A", "B", "C"]
+ )
+ subset = df[["A", "B"]]
+ assert isinstance(subset, MySubclassWithMetadata)
+
+
+class SimpleDataFrameSubClass(DataFrame):
+ """A subclass of DataFrame that does not define a constructor."""
+
+
+class SimpleSeriesSubClass(Series):
+ """A subclass of Series that does not define a constructor."""
+
+
+class TestSubclassWithoutConstructor:
+ def test_copy_df(self):
+ expected = DataFrame({"a": [1, 2, 3]})
+ result = SimpleDataFrameSubClass(expected).copy()
+
+ assert (
+ type(result) is DataFrame
+ ) # assert_frame_equal only checks isinstance(lhs, type(rhs))
+ tm.assert_frame_equal(result, expected)
+
+ def test_copy_series(self):
+ expected = Series([1, 2, 3])
+ result = SimpleSeriesSubClass(expected).copy()
+
+ tm.assert_series_equal(result, expected)
+
+ def test_series_to_frame(self):
+ orig = Series([1, 2, 3])
+ expected = orig.to_frame()
+ result = SimpleSeriesSubClass(orig).to_frame()
+
+ assert (
+ type(result) is DataFrame
+ ) # assert_frame_equal only checks isinstance(lhs, type(rhs))
+ tm.assert_frame_equal(result, expected)
+
+ def test_groupby(self):
+ df = SimpleDataFrameSubClass(DataFrame({"a": [1, 2, 3]}))
+
+ for _, v in df.groupby("a"):
+ assert type(v) is DataFrame
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_ufunc.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_ufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..305c0f8bba8ce210811d488f669a4953370d094b
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_ufunc.py
@@ -0,0 +1,311 @@
+from functools import partial
+import re
+
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.api.types import is_extension_array_dtype
+
+dtypes = [
+ "int64",
+ "Int64",
+ {"A": "int64", "B": "Int64"},
+]
+
+
+@pytest.mark.parametrize("dtype", dtypes)
+def test_unary_unary(dtype):
+ # unary input, unary output
+ values = np.array([[-1, -1], [1, 1]], dtype="int64")
+ df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype)
+ result = np.positive(df)
+ expected = pd.DataFrame(
+ np.positive(values), index=df.index, columns=df.columns
+ ).astype(dtype)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", dtypes)
+def test_unary_binary(request, dtype):
+ # unary input, binary output
+ if is_extension_array_dtype(dtype) or isinstance(dtype, dict):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="Extension / mixed with multiple outputs not implemented."
+ )
+ )
+
+ values = np.array([[-1, -1], [1, 1]], dtype="int64")
+ df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype)
+ result_pandas = np.modf(df)
+ assert isinstance(result_pandas, tuple)
+ assert len(result_pandas) == 2
+ expected_numpy = np.modf(values)
+
+ for result, b in zip(result_pandas, expected_numpy):
+ expected = pd.DataFrame(b, index=df.index, columns=df.columns)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", dtypes)
+def test_binary_input_dispatch_binop(dtype):
+ # binop ufuncs are dispatched to our dunder methods.
+ values = np.array([[-1, -1], [1, 1]], dtype="int64")
+ df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype)
+ result = np.add(df, df)
+ expected = pd.DataFrame(
+ np.add(values, values), index=df.index, columns=df.columns
+ ).astype(dtype)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "func,arg,expected",
+ [
+ (np.add, 1, [2, 3, 4, 5]),
+ (
+ partial(np.add, where=[[False, True], [True, False]]),
+ np.array([[1, 1], [1, 1]]),
+ [0, 3, 4, 0],
+ ),
+ (np.power, np.array([[1, 1], [2, 2]]), [1, 2, 9, 16]),
+ (np.subtract, 2, [-1, 0, 1, 2]),
+ (
+ partial(np.negative, where=np.array([[False, True], [True, False]])),
+ None,
+ [0, -2, -3, 0],
+ ),
+ ],
+)
+def test_ufunc_passes_args(func, arg, expected):
+ # GH#40662
+ arr = np.array([[1, 2], [3, 4]])
+ df = pd.DataFrame(arr)
+ result_inplace = np.zeros_like(arr)
+ # 1-argument ufunc
+ if arg is None:
+ result = func(df, out=result_inplace)
+ else:
+ result = func(df, arg, out=result_inplace)
+
+ expected = np.array(expected).reshape(2, 2)
+ tm.assert_numpy_array_equal(result_inplace, expected)
+
+ expected = pd.DataFrame(expected)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype_a", dtypes)
+@pytest.mark.parametrize("dtype_b", dtypes)
+def test_binary_input_aligns_columns(request, dtype_a, dtype_b):
+ if (
+ is_extension_array_dtype(dtype_a)
+ or isinstance(dtype_a, dict)
+ or is_extension_array_dtype(dtype_b)
+ or isinstance(dtype_b, dict)
+ ):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="Extension / mixed with multiple inputs not implemented."
+ )
+ )
+
+ df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}).astype(dtype_a)
+
+ if isinstance(dtype_a, dict) and isinstance(dtype_b, dict):
+ dtype_b = dtype_b.copy()
+ dtype_b["C"] = dtype_b.pop("B")
+ df2 = pd.DataFrame({"A": [1, 2], "C": [3, 4]}).astype(dtype_b)
+ # As of 2.0, align first before applying the ufunc
+ result = np.heaviside(df1, df2)
+ expected = np.heaviside(
+ np.array([[1, 3, np.nan], [2, 4, np.nan]]),
+ np.array([[1, np.nan, 3], [2, np.nan, 4]]),
+ )
+ expected = pd.DataFrame(expected, index=[0, 1], columns=["A", "B", "C"])
+ tm.assert_frame_equal(result, expected)
+
+ result = np.heaviside(df1, df2.values)
+ expected = pd.DataFrame([[1.0, 1.0], [1.0, 1.0]], columns=["A", "B"])
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", dtypes)
+def test_binary_input_aligns_index(request, dtype):
+ if is_extension_array_dtype(dtype) or isinstance(dtype, dict):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="Extension / mixed with multiple inputs not implemented."
+ )
+ )
+ df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "b"]).astype(dtype)
+ df2 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "c"]).astype(dtype)
+ result = np.heaviside(df1, df2)
+ expected = np.heaviside(
+ np.array([[1, 3], [3, 4], [np.nan, np.nan]]),
+ np.array([[1, 3], [np.nan, np.nan], [3, 4]]),
+ )
+ # TODO(FloatArray): this will be Float64Dtype.
+ expected = pd.DataFrame(expected, index=["a", "b", "c"], columns=["A", "B"])
+ tm.assert_frame_equal(result, expected)
+
+ result = np.heaviside(df1, df2.values)
+ expected = pd.DataFrame(
+ [[1.0, 1.0], [1.0, 1.0]], columns=["A", "B"], index=["a", "b"]
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_binary_frame_series_raises():
+ # We don't currently implement
+ df = pd.DataFrame({"A": [1, 2]})
+ with pytest.raises(NotImplementedError, match="logaddexp"):
+ np.logaddexp(df, df["A"])
+
+ with pytest.raises(NotImplementedError, match="logaddexp"):
+ np.logaddexp(df["A"], df)
+
+
+def test_unary_accumulate_axis():
+ # https://github.com/pandas-dev/pandas/issues/39259
+ df = pd.DataFrame({"a": [1, 3, 2, 4]})
+ result = np.maximum.accumulate(df)
+ expected = pd.DataFrame({"a": [1, 3, 3, 4]})
+ tm.assert_frame_equal(result, expected)
+
+ df = pd.DataFrame({"a": [1, 3, 2, 4], "b": [0.1, 4.0, 3.0, 2.0]})
+ result = np.maximum.accumulate(df)
+ # in theory could preserve int dtype for default axis=0
+ expected = pd.DataFrame({"a": [1.0, 3.0, 3.0, 4.0], "b": [0.1, 4.0, 4.0, 4.0]})
+ tm.assert_frame_equal(result, expected)
+
+ result = np.maximum.accumulate(df, axis=0)
+ tm.assert_frame_equal(result, expected)
+
+ result = np.maximum.accumulate(df, axis=1)
+ expected = pd.DataFrame({"a": [1.0, 3.0, 2.0, 4.0], "b": [1.0, 4.0, 3.0, 4.0]})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_frame_outer_disallowed():
+ df = pd.DataFrame({"A": [1, 2]})
+ with pytest.raises(NotImplementedError, match=""):
+ # deprecation enforced in 2.0
+ np.subtract.outer(df, df)
+
+
+def test_alignment_deprecation_enforced():
+ # Enforced in 2.0
+ # https://github.com/pandas-dev/pandas/issues/39184
+ df1 = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df2 = pd.DataFrame({"b": [1, 2, 3], "c": [4, 5, 6]})
+ s1 = pd.Series([1, 2], index=["a", "b"])
+ s2 = pd.Series([1, 2], index=["b", "c"])
+
+ # binary dataframe / dataframe
+ expected = pd.DataFrame({"a": [2, 4, 6], "b": [8, 10, 12]})
+
+ with tm.assert_produces_warning(None):
+ # aligned -> no warning!
+ result = np.add(df1, df1)
+ tm.assert_frame_equal(result, expected)
+
+ result = np.add(df1, df2.values)
+ tm.assert_frame_equal(result, expected)
+
+ result = np.add(df1, df2)
+ expected = pd.DataFrame({"a": [np.nan] * 3, "b": [5, 7, 9], "c": [np.nan] * 3})
+ tm.assert_frame_equal(result, expected)
+
+ result = np.add(df1.values, df2)
+ expected = pd.DataFrame({"b": [2, 4, 6], "c": [8, 10, 12]})
+ tm.assert_frame_equal(result, expected)
+
+ # binary dataframe / series
+ expected = pd.DataFrame({"a": [2, 3, 4], "b": [6, 7, 8]})
+
+ with tm.assert_produces_warning(None):
+ # aligned -> no warning!
+ result = np.add(df1, s1)
+ tm.assert_frame_equal(result, expected)
+
+ result = np.add(df1, s2.values)
+ tm.assert_frame_equal(result, expected)
+
+ expected = pd.DataFrame(
+ {"a": [np.nan] * 3, "b": [5.0, 6.0, 7.0], "c": [np.nan] * 3}
+ )
+ result = np.add(df1, s2)
+ tm.assert_frame_equal(result, expected)
+
+ msg = "Cannot apply ufunc to mixed DataFrame and Series inputs."
+ with pytest.raises(NotImplementedError, match=msg):
+ np.add(s2, df1)
+
+
+def test_alignment_deprecation_many_inputs_enforced():
+ # Enforced in 2.0
+ # https://github.com/pandas-dev/pandas/issues/39184
+ # test that the deprecation also works with > 2 inputs -> using a numba
+ # written ufunc for this because numpy itself doesn't have such ufuncs
+ numba = pytest.importorskip("numba")
+
+ @numba.vectorize([numba.float64(numba.float64, numba.float64, numba.float64)])
+ def my_ufunc(x, y, z):
+ return x + y + z
+
+ df1 = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df2 = pd.DataFrame({"b": [1, 2, 3], "c": [4, 5, 6]})
+ df3 = pd.DataFrame({"a": [1, 2, 3], "c": [4, 5, 6]})
+
+ result = my_ufunc(df1, df2, df3)
+ expected = pd.DataFrame(np.full((3, 3), np.nan), columns=["a", "b", "c"])
+ tm.assert_frame_equal(result, expected)
+
+ # all aligned -> no warning
+ with tm.assert_produces_warning(None):
+ result = my_ufunc(df1, df1, df1)
+ expected = pd.DataFrame([[3.0, 12.0], [6.0, 15.0], [9.0, 18.0]], columns=["a", "b"])
+ tm.assert_frame_equal(result, expected)
+
+ # mixed frame / arrays
+ msg = (
+ r"operands could not be broadcast together with shapes \(3,3\) \(3,3\) \(3,2\)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ my_ufunc(df1, df2, df3.values)
+
+ # single frame -> no warning
+ with tm.assert_produces_warning(None):
+ result = my_ufunc(df1, df2.values, df3.values)
+ tm.assert_frame_equal(result, expected)
+
+ # takes indices of first frame
+ msg = (
+ r"operands could not be broadcast together with shapes \(3,2\) \(3,3\) \(3,3\)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ my_ufunc(df1.values, df2, df3)
+
+
+def test_array_ufuncs_for_many_arguments():
+ # GH39853
+ def add3(x, y, z):
+ return x + y + z
+
+ ufunc = np.frompyfunc(add3, 3, 1)
+ df = pd.DataFrame([[1, 2], [3, 4]])
+
+ result = ufunc(df, df, 1)
+ expected = pd.DataFrame([[3, 5], [7, 9]], dtype=object)
+ tm.assert_frame_equal(result, expected)
+
+ ser = pd.Series([1, 2])
+ msg = (
+ "Cannot apply ufunc "
+ "to mixed DataFrame and Series inputs."
+ )
+ with pytest.raises(NotImplementedError, match=re.escape(msg)):
+ ufunc(df, df, ser)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_unary.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_unary.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e29d3c868983bac65ca0df6679c96798ee9c915
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_unary.py
@@ -0,0 +1,194 @@
+from decimal import Decimal
+
+import numpy as np
+import pytest
+
+from pandas.compat.numpy import np_version_gte1p25
+
+import pandas as pd
+import pandas._testing as tm
+
+
+class TestDataFrameUnaryOperators:
+ # __pos__, __neg__, __invert__
+
+ @pytest.mark.parametrize(
+ "df,expected",
+ [
+ (pd.DataFrame({"a": [-1, 1]}), pd.DataFrame({"a": [1, -1]})),
+ (pd.DataFrame({"a": [False, True]}), pd.DataFrame({"a": [True, False]})),
+ (
+ pd.DataFrame({"a": pd.Series(pd.to_timedelta([-1, 1]))}),
+ pd.DataFrame({"a": pd.Series(pd.to_timedelta([1, -1]))}),
+ ),
+ ],
+ )
+ def test_neg_numeric(self, df, expected):
+ tm.assert_frame_equal(-df, expected)
+ tm.assert_series_equal(-df["a"], expected["a"])
+
+ @pytest.mark.parametrize(
+ "df, expected",
+ [
+ (np.array([1, 2], dtype=object), np.array([-1, -2], dtype=object)),
+ ([Decimal("1.0"), Decimal("2.0")], [Decimal("-1.0"), Decimal("-2.0")]),
+ ],
+ )
+ def test_neg_object(self, df, expected):
+ # GH#21380
+ df = pd.DataFrame({"a": df})
+ expected = pd.DataFrame({"a": expected})
+ tm.assert_frame_equal(-df, expected)
+ tm.assert_series_equal(-df["a"], expected["a"])
+
+ @pytest.mark.parametrize(
+ "df",
+ [
+ pd.DataFrame({"a": ["a", "b"]}),
+ pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])}),
+ ],
+ )
+ def test_neg_raises(self, df):
+ msg = (
+ "bad operand type for unary -: 'str'|"
+ r"bad operand type for unary -: 'DatetimeArray'"
+ )
+ with pytest.raises(TypeError, match=msg):
+ (-df)
+ with pytest.raises(TypeError, match=msg):
+ (-df["a"])
+
+ def test_invert(self, float_frame):
+ df = float_frame
+
+ tm.assert_frame_equal(-(df < 0), ~(df < 0))
+
+ def test_invert_mixed(self):
+ shape = (10, 5)
+ df = pd.concat(
+ [
+ pd.DataFrame(np.zeros(shape, dtype="bool")),
+ pd.DataFrame(np.zeros(shape, dtype=int)),
+ ],
+ axis=1,
+ ignore_index=True,
+ )
+ result = ~df
+ expected = pd.concat(
+ [
+ pd.DataFrame(np.ones(shape, dtype="bool")),
+ pd.DataFrame(-np.ones(shape, dtype=int)),
+ ],
+ axis=1,
+ ignore_index=True,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_invert_empty_not_input(self):
+ # GH#51032
+ df = pd.DataFrame()
+ result = ~df
+ tm.assert_frame_equal(df, result)
+ assert df is not result
+
+ @pytest.mark.parametrize(
+ "df",
+ [
+ pd.DataFrame({"a": [-1, 1]}),
+ pd.DataFrame({"a": [False, True]}),
+ pd.DataFrame({"a": pd.Series(pd.to_timedelta([-1, 1]))}),
+ ],
+ )
+ def test_pos_numeric(self, df):
+ # GH#16073
+ tm.assert_frame_equal(+df, df)
+ tm.assert_series_equal(+df["a"], df["a"])
+
+ @pytest.mark.parametrize(
+ "df",
+ [
+ pd.DataFrame({"a": np.array([-1, 2], dtype=object)}),
+ pd.DataFrame({"a": [Decimal("-1.0"), Decimal("2.0")]}),
+ ],
+ )
+ def test_pos_object(self, df):
+ # GH#21380
+ tm.assert_frame_equal(+df, df)
+ tm.assert_series_equal(+df["a"], df["a"])
+
+ @pytest.mark.parametrize(
+ "df",
+ [
+ pytest.param(
+ pd.DataFrame({"a": ["a", "b"]}),
+ # filterwarnings removable once min numpy version is 1.25
+ marks=[
+ pytest.mark.filterwarnings("ignore:Applying:DeprecationWarning")
+ ],
+ ),
+ ],
+ )
+ def test_pos_object_raises(self, df):
+ # GH#21380
+ if np_version_gte1p25:
+ with pytest.raises(
+ TypeError, match=r"^bad operand type for unary \+: \'str\'$"
+ ):
+ tm.assert_frame_equal(+df, df)
+ else:
+ tm.assert_series_equal(+df["a"], df["a"])
+
+ @pytest.mark.parametrize(
+ "df", [pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])})]
+ )
+ def test_pos_raises(self, df):
+ msg = r"bad operand type for unary \+: 'DatetimeArray'"
+ with pytest.raises(TypeError, match=msg):
+ (+df)
+ with pytest.raises(TypeError, match=msg):
+ (+df["a"])
+
+ def test_unary_nullable(self):
+ df = pd.DataFrame(
+ {
+ "a": pd.array([1, -2, 3, pd.NA], dtype="Int64"),
+ "b": pd.array([4.0, -5.0, 6.0, pd.NA], dtype="Float32"),
+ "c": pd.array([True, False, False, pd.NA], dtype="boolean"),
+ # include numpy bool to make sure bool-vs-boolean behavior
+ # is consistent in non-NA locations
+ "d": np.array([True, False, False, True]),
+ }
+ )
+
+ result = +df
+ res_ufunc = np.positive(df)
+ expected = df
+ # TODO: assert that we have copies?
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(res_ufunc, expected)
+
+ result = -df
+ res_ufunc = np.negative(df)
+ expected = pd.DataFrame(
+ {
+ "a": pd.array([-1, 2, -3, pd.NA], dtype="Int64"),
+ "b": pd.array([-4.0, 5.0, -6.0, pd.NA], dtype="Float32"),
+ "c": pd.array([False, True, True, pd.NA], dtype="boolean"),
+ "d": np.array([False, True, True, False]),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(res_ufunc, expected)
+
+ result = abs(df)
+ res_ufunc = np.abs(df)
+ expected = pd.DataFrame(
+ {
+ "a": pd.array([1, 2, 3, pd.NA], dtype="Int64"),
+ "b": pd.array([4.0, 5.0, 6.0, pd.NA], dtype="Float32"),
+ "c": pd.array([True, False, False, pd.NA], dtype="boolean"),
+ "d": np.array([True, False, False, True]),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(res_ufunc, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_validate.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_validate.py
new file mode 100644
index 0000000000000000000000000000000000000000..e99e0a686384883d570feef949597d08da7e8ff9
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/frame/test_validate.py
@@ -0,0 +1,41 @@
+import pytest
+
+from pandas.core.frame import DataFrame
+
+
+@pytest.fixture
+def dataframe():
+ return DataFrame({"a": [1, 2], "b": [3, 4]})
+
+
+class TestDataFrameValidate:
+ """Tests for error handling related to data types of method arguments."""
+
+ @pytest.mark.parametrize(
+ "func",
+ [
+ "query",
+ "eval",
+ "set_index",
+ "reset_index",
+ "dropna",
+ "drop_duplicates",
+ "sort_values",
+ ],
+ )
+ @pytest.mark.parametrize("inplace", [1, "True", [1, 2, 3], 5.0])
+ def test_validate_bool_args(self, dataframe, func, inplace):
+ msg = 'For argument "inplace" expected type bool'
+ kwargs = {"inplace": inplace}
+
+ if func == "query":
+ kwargs["expr"] = "a > b"
+ elif func == "eval":
+ kwargs["expr"] = "a + b"
+ elif func == "set_index":
+ kwargs["keys"] = ["a"]
+ elif func == "sort_values":
+ kwargs["by"] = ["a"]
+
+ with pytest.raises(ValueError, match=msg):
+ getattr(dataframe, func)(**kwargs)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_duplicate_labels.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_duplicate_labels.py
new file mode 100644
index 0000000000000000000000000000000000000000..a81e013290b648125982fcd342bb58c3da28bde0
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_duplicate_labels.py
@@ -0,0 +1,411 @@
+"""Tests dealing with the NDFrame.allows_duplicates."""
+import operator
+
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+not_implemented = pytest.mark.xfail(reason="Not implemented.")
+
+# ----------------------------------------------------------------------------
+# Preservation
+
+
+class TestPreserves:
+ @pytest.mark.parametrize(
+ "cls, data",
+ [
+ (pd.Series, np.array([])),
+ (pd.Series, [1, 2]),
+ (pd.DataFrame, {}),
+ (pd.DataFrame, {"A": [1, 2]}),
+ ],
+ )
+ def test_construction_ok(self, cls, data):
+ result = cls(data)
+ assert result.flags.allows_duplicate_labels is True
+
+ result = cls(data).set_flags(allows_duplicate_labels=False)
+ assert result.flags.allows_duplicate_labels is False
+
+ @pytest.mark.parametrize(
+ "func",
+ [
+ operator.itemgetter(["a"]),
+ operator.methodcaller("add", 1),
+ operator.methodcaller("rename", str.upper),
+ operator.methodcaller("rename", "name"),
+ operator.methodcaller("abs"),
+ np.abs,
+ ],
+ )
+ def test_preserved_series(self, func):
+ s = pd.Series([0, 1], index=["a", "b"]).set_flags(allows_duplicate_labels=False)
+ assert func(s).flags.allows_duplicate_labels is False
+
+ @pytest.mark.parametrize(
+ "other", [pd.Series(0, index=["a", "b", "c"]), pd.Series(0, index=["a", "b"])]
+ )
+ # TODO: frame
+ @not_implemented
+ def test_align(self, other):
+ s = pd.Series([0, 1], index=["a", "b"]).set_flags(allows_duplicate_labels=False)
+ a, b = s.align(other)
+ assert a.flags.allows_duplicate_labels is False
+ assert b.flags.allows_duplicate_labels is False
+
+ def test_preserved_frame(self):
+ df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "b"]).set_flags(
+ allows_duplicate_labels=False
+ )
+ assert df.loc[["a"]].flags.allows_duplicate_labels is False
+ assert df.loc[:, ["A", "B"]].flags.allows_duplicate_labels is False
+
+ def test_to_frame(self):
+ ser = pd.Series(dtype=float).set_flags(allows_duplicate_labels=False)
+ assert ser.to_frame().flags.allows_duplicate_labels is False
+
+ @pytest.mark.parametrize("func", ["add", "sub"])
+ @pytest.mark.parametrize("frame", [False, True])
+ @pytest.mark.parametrize("other", [1, pd.Series([1, 2], name="A")])
+ def test_binops(self, func, other, frame):
+ df = pd.Series([1, 2], name="A", index=["a", "b"]).set_flags(
+ allows_duplicate_labels=False
+ )
+ if frame:
+ df = df.to_frame()
+ if isinstance(other, pd.Series) and frame:
+ other = other.to_frame()
+ func = operator.methodcaller(func, other)
+ assert df.flags.allows_duplicate_labels is False
+ assert func(df).flags.allows_duplicate_labels is False
+
+ def test_preserve_getitem(self):
+ df = pd.DataFrame({"A": [1, 2]}).set_flags(allows_duplicate_labels=False)
+ assert df[["A"]].flags.allows_duplicate_labels is False
+ assert df["A"].flags.allows_duplicate_labels is False
+ assert df.loc[0].flags.allows_duplicate_labels is False
+ assert df.loc[[0]].flags.allows_duplicate_labels is False
+ assert df.loc[0, ["A"]].flags.allows_duplicate_labels is False
+
+ def test_ndframe_getitem_caching_issue(self, request, using_copy_on_write):
+ if not using_copy_on_write:
+ request.node.add_marker(pytest.mark.xfail(reason="Unclear behavior."))
+ # NDFrame.__getitem__ will cache the first df['A']. May need to
+ # invalidate that cache? Update the cached entries?
+ df = pd.DataFrame({"A": [0]}).set_flags(allows_duplicate_labels=False)
+ assert df["A"].flags.allows_duplicate_labels is False
+ df.flags.allows_duplicate_labels = True
+ assert df["A"].flags.allows_duplicate_labels is True
+
+ @pytest.mark.parametrize(
+ "objs, kwargs",
+ [
+ # Series
+ (
+ [
+ pd.Series(1, index=["a", "b"]),
+ pd.Series(2, index=["c", "d"]),
+ ],
+ {},
+ ),
+ (
+ [
+ pd.Series(1, index=["a", "b"]),
+ pd.Series(2, index=["a", "b"]),
+ ],
+ {"ignore_index": True},
+ ),
+ (
+ [
+ pd.Series(1, index=["a", "b"]),
+ pd.Series(2, index=["a", "b"]),
+ ],
+ {"axis": 1},
+ ),
+ # Frame
+ (
+ [
+ pd.DataFrame({"A": [1, 2]}, index=["a", "b"]),
+ pd.DataFrame({"A": [1, 2]}, index=["c", "d"]),
+ ],
+ {},
+ ),
+ (
+ [
+ pd.DataFrame({"A": [1, 2]}, index=["a", "b"]),
+ pd.DataFrame({"A": [1, 2]}, index=["a", "b"]),
+ ],
+ {"ignore_index": True},
+ ),
+ (
+ [
+ pd.DataFrame({"A": [1, 2]}, index=["a", "b"]),
+ pd.DataFrame({"B": [1, 2]}, index=["a", "b"]),
+ ],
+ {"axis": 1},
+ ),
+ # Series / Frame
+ (
+ [
+ pd.DataFrame({"A": [1, 2]}, index=["a", "b"]),
+ pd.Series([1, 2], index=["a", "b"], name="B"),
+ ],
+ {"axis": 1},
+ ),
+ ],
+ )
+ def test_concat(self, objs, kwargs):
+ objs = [x.set_flags(allows_duplicate_labels=False) for x in objs]
+ result = pd.concat(objs, **kwargs)
+ assert result.flags.allows_duplicate_labels is False
+
+ @pytest.mark.parametrize(
+ "left, right, expected",
+ [
+ # false false false
+ pytest.param(
+ pd.DataFrame({"A": [0, 1]}, index=["a", "b"]).set_flags(
+ allows_duplicate_labels=False
+ ),
+ pd.DataFrame({"B": [0, 1]}, index=["a", "d"]).set_flags(
+ allows_duplicate_labels=False
+ ),
+ False,
+ marks=not_implemented,
+ ),
+ # false true false
+ pytest.param(
+ pd.DataFrame({"A": [0, 1]}, index=["a", "b"]).set_flags(
+ allows_duplicate_labels=False
+ ),
+ pd.DataFrame({"B": [0, 1]}, index=["a", "d"]),
+ False,
+ marks=not_implemented,
+ ),
+ # true true true
+ (
+ pd.DataFrame({"A": [0, 1]}, index=["a", "b"]),
+ pd.DataFrame({"B": [0, 1]}, index=["a", "d"]),
+ True,
+ ),
+ ],
+ )
+ def test_merge(self, left, right, expected):
+ result = pd.merge(left, right, left_index=True, right_index=True)
+ assert result.flags.allows_duplicate_labels is expected
+
+ @not_implemented
+ def test_groupby(self):
+ # XXX: This is under tested
+ # TODO:
+ # - apply
+ # - transform
+ # - Should passing a grouper that disallows duplicates propagate?
+ df = pd.DataFrame({"A": [1, 2, 3]}).set_flags(allows_duplicate_labels=False)
+ result = df.groupby([0, 0, 1]).agg("count")
+ assert result.flags.allows_duplicate_labels is False
+
+ @pytest.mark.parametrize("frame", [True, False])
+ @not_implemented
+ def test_window(self, frame):
+ df = pd.Series(
+ 1,
+ index=pd.date_range("2000", periods=12),
+ name="A",
+ allows_duplicate_labels=False,
+ )
+ if frame:
+ df = df.to_frame()
+ assert df.rolling(3).mean().flags.allows_duplicate_labels is False
+ assert df.ewm(3).mean().flags.allows_duplicate_labels is False
+ assert df.expanding(3).mean().flags.allows_duplicate_labels is False
+
+
+# ----------------------------------------------------------------------------
+# Raises
+
+
+class TestRaises:
+ @pytest.mark.parametrize(
+ "cls, axes",
+ [
+ (pd.Series, {"index": ["a", "a"], "dtype": float}),
+ (pd.DataFrame, {"index": ["a", "a"]}),
+ (pd.DataFrame, {"index": ["a", "a"], "columns": ["b", "b"]}),
+ (pd.DataFrame, {"columns": ["b", "b"]}),
+ ],
+ )
+ def test_set_flags_with_duplicates(self, cls, axes):
+ result = cls(**axes)
+ assert result.flags.allows_duplicate_labels is True
+
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
+ cls(**axes).set_flags(allows_duplicate_labels=False)
+
+ @pytest.mark.parametrize(
+ "data",
+ [
+ pd.Series(index=[0, 0], dtype=float),
+ pd.DataFrame(index=[0, 0]),
+ pd.DataFrame(columns=[0, 0]),
+ ],
+ )
+ def test_setting_allows_duplicate_labels_raises(self, data):
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
+ data.flags.allows_duplicate_labels = False
+
+ assert data.flags.allows_duplicate_labels is True
+
+ def test_series_raises(self):
+ a = pd.Series(0, index=["a", "b"])
+ b = pd.Series([0, 1], index=["a", "b"]).set_flags(allows_duplicate_labels=False)
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
+ pd.concat([a, b])
+
+ @pytest.mark.parametrize(
+ "getter, target",
+ [
+ (operator.itemgetter(["A", "A"]), None),
+ # loc
+ (operator.itemgetter(["a", "a"]), "loc"),
+ pytest.param(operator.itemgetter(("a", ["A", "A"])), "loc"),
+ (operator.itemgetter((["a", "a"], "A")), "loc"),
+ # iloc
+ (operator.itemgetter([0, 0]), "iloc"),
+ pytest.param(operator.itemgetter((0, [0, 0])), "iloc"),
+ pytest.param(operator.itemgetter(([0, 0], 0)), "iloc"),
+ ],
+ )
+ def test_getitem_raises(self, getter, target):
+ df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "b"]).set_flags(
+ allows_duplicate_labels=False
+ )
+ if target:
+ # df, df.loc, or df.iloc
+ target = getattr(df, target)
+ else:
+ target = df
+
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
+ getter(target)
+
+ @pytest.mark.parametrize(
+ "objs, kwargs",
+ [
+ (
+ [
+ pd.Series(1, index=[0, 1], name="a"),
+ pd.Series(2, index=[0, 1], name="a"),
+ ],
+ {"axis": 1},
+ )
+ ],
+ )
+ def test_concat_raises(self, objs, kwargs):
+ objs = [x.set_flags(allows_duplicate_labels=False) for x in objs]
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
+ pd.concat(objs, **kwargs)
+
+ @not_implemented
+ def test_merge_raises(self):
+ a = pd.DataFrame({"A": [0, 1, 2]}, index=["a", "b", "c"]).set_flags(
+ allows_duplicate_labels=False
+ )
+ b = pd.DataFrame({"B": [0, 1, 2]}, index=["a", "b", "b"])
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
+ pd.merge(a, b, left_index=True, right_index=True)
+
+
+@pytest.mark.parametrize(
+ "idx",
+ [
+ pd.Index([1, 1]),
+ pd.Index(["a", "a"]),
+ pd.Index([1.1, 1.1]),
+ pd.PeriodIndex([pd.Period("2000", "D")] * 2),
+ pd.DatetimeIndex([pd.Timestamp("2000")] * 2),
+ pd.TimedeltaIndex([pd.Timedelta("1D")] * 2),
+ pd.CategoricalIndex(["a", "a"]),
+ pd.IntervalIndex([pd.Interval(0, 1)] * 2),
+ pd.MultiIndex.from_tuples([("a", 1), ("a", 1)]),
+ ],
+ ids=lambda x: type(x).__name__,
+)
+def test_raises_basic(idx):
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
+ pd.Series(1, index=idx).set_flags(allows_duplicate_labels=False)
+
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
+ pd.DataFrame({"A": [1, 1]}, index=idx).set_flags(allows_duplicate_labels=False)
+
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
+ pd.DataFrame([[1, 2]], columns=idx).set_flags(allows_duplicate_labels=False)
+
+
+def test_format_duplicate_labels_message():
+ idx = pd.Index(["a", "b", "a", "b", "c"])
+ result = idx._format_duplicate_message()
+ expected = pd.DataFrame(
+ {"positions": [[0, 2], [1, 3]]}, index=pd.Index(["a", "b"], name="label")
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_format_duplicate_labels_message_multi():
+ idx = pd.MultiIndex.from_product([["A"], ["a", "b", "a", "b", "c"]])
+ result = idx._format_duplicate_message()
+ expected = pd.DataFrame(
+ {"positions": [[0, 2], [1, 3]]},
+ index=pd.MultiIndex.from_product([["A"], ["a", "b"]]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_dataframe_insert_raises():
+ df = pd.DataFrame({"A": [1, 2]}).set_flags(allows_duplicate_labels=False)
+ msg = "Cannot specify"
+ with pytest.raises(ValueError, match=msg):
+ df.insert(0, "A", [3, 4], allow_duplicates=True)
+
+
+@pytest.mark.parametrize(
+ "method, frame_only",
+ [
+ (operator.methodcaller("set_index", "A", inplace=True), True),
+ (operator.methodcaller("reset_index", inplace=True), True),
+ (operator.methodcaller("rename", lambda x: x, inplace=True), False),
+ ],
+)
+def test_inplace_raises(method, frame_only):
+ df = pd.DataFrame({"A": [0, 0], "B": [1, 2]}).set_flags(
+ allows_duplicate_labels=False
+ )
+ s = df["A"]
+ s.flags.allows_duplicate_labels = False
+ msg = "Cannot specify"
+
+ with pytest.raises(ValueError, match=msg):
+ method(df)
+ if not frame_only:
+ with pytest.raises(ValueError, match=msg):
+ method(s)
+
+
+def test_pickle():
+ a = pd.Series([1, 2]).set_flags(allows_duplicate_labels=False)
+ b = tm.round_trip_pickle(a)
+ tm.assert_series_equal(a, b)
+
+ a = pd.DataFrame({"A": []}).set_flags(allows_duplicate_labels=False)
+ b = tm.round_trip_pickle(a)
+ tm.assert_frame_equal(a, b)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_finalize.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_finalize.py
new file mode 100644
index 0000000000000000000000000000000000000000..1522b83a4f5d088ceaed4f630ae87965d033f48a
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_finalize.py
@@ -0,0 +1,772 @@
+"""
+An exhaustive list of pandas methods exercising NDFrame.__finalize__.
+"""
+import operator
+import re
+
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+# TODO:
+# * Binary methods (mul, div, etc.)
+# * Binary outputs (align, etc.)
+# * top-level methods (concat, merge, get_dummies, etc.)
+# * window
+# * cumulative reductions
+
+not_implemented_mark = pytest.mark.xfail(reason="not implemented")
+
+mi = pd.MultiIndex.from_product([["a", "b"], [0, 1]], names=["A", "B"])
+
+frame_data = ({"A": [1]},)
+frame_mi_data = ({"A": [1, 2, 3, 4]}, mi)
+
+
+# Tuple of
+# - Callable: Constructor (Series, DataFrame)
+# - Tuple: Constructor args
+# - Callable: pass the constructed value with attrs set to this.
+
+_all_methods = [
+ (
+ pd.Series,
+ (np.array([0], dtype="float64")),
+ operator.methodcaller("view", "int64"),
+ ),
+ (pd.Series, ([0],), operator.methodcaller("take", [])),
+ (pd.Series, ([0],), operator.methodcaller("__getitem__", [True])),
+ (pd.Series, ([0],), operator.methodcaller("repeat", 2)),
+ (pd.Series, ([0],), operator.methodcaller("reset_index")),
+ (pd.Series, ([0],), operator.methodcaller("reset_index", drop=True)),
+ (pd.Series, ([0],), operator.methodcaller("to_frame")),
+ (pd.Series, ([0, 0],), operator.methodcaller("drop_duplicates")),
+ (pd.Series, ([0, 0],), operator.methodcaller("duplicated")),
+ (pd.Series, ([0, 0],), operator.methodcaller("round")),
+ (pd.Series, ([0, 0],), operator.methodcaller("rename", lambda x: x + 1)),
+ (pd.Series, ([0, 0],), operator.methodcaller("rename", "name")),
+ (pd.Series, ([0, 0],), operator.methodcaller("set_axis", ["a", "b"])),
+ (pd.Series, ([0, 0],), operator.methodcaller("reindex", [1, 0])),
+ (pd.Series, ([0, 0],), operator.methodcaller("drop", [0])),
+ (pd.Series, (pd.array([0, pd.NA]),), operator.methodcaller("fillna", 0)),
+ (pd.Series, ([0, 0],), operator.methodcaller("replace", {0: 1})),
+ (pd.Series, ([0, 0],), operator.methodcaller("shift")),
+ (pd.Series, ([0, 0],), operator.methodcaller("isin", [0, 1])),
+ (pd.Series, ([0, 0],), operator.methodcaller("between", 0, 2)),
+ (pd.Series, ([0, 0],), operator.methodcaller("isna")),
+ (pd.Series, ([0, 0],), operator.methodcaller("isnull")),
+ (pd.Series, ([0, 0],), operator.methodcaller("notna")),
+ (pd.Series, ([0, 0],), operator.methodcaller("notnull")),
+ (pd.Series, ([1],), operator.methodcaller("add", pd.Series([1]))),
+ # TODO: mul, div, etc.
+ (
+ pd.Series,
+ ([0], pd.period_range("2000", periods=1)),
+ operator.methodcaller("to_timestamp"),
+ ),
+ (
+ pd.Series,
+ ([0], pd.date_range("2000", periods=1)),
+ operator.methodcaller("to_period"),
+ ),
+ pytest.param(
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("dot", pd.DataFrame(index=["A"])),
+ ),
+ marks=pytest.mark.xfail(reason="Implement binary finalize"),
+ ),
+ (pd.DataFrame, frame_data, operator.methodcaller("transpose")),
+ (pd.DataFrame, frame_data, operator.methodcaller("__getitem__", "A")),
+ (pd.DataFrame, frame_data, operator.methodcaller("__getitem__", ["A"])),
+ (pd.DataFrame, frame_data, operator.methodcaller("__getitem__", np.array([True]))),
+ (pd.DataFrame, ({("A", "a"): [1]},), operator.methodcaller("__getitem__", ["A"])),
+ (pd.DataFrame, frame_data, operator.methodcaller("query", "A == 1")),
+ (pd.DataFrame, frame_data, operator.methodcaller("eval", "A + 1", engine="python")),
+ (pd.DataFrame, frame_data, operator.methodcaller("select_dtypes", include="int")),
+ (pd.DataFrame, frame_data, operator.methodcaller("assign", b=1)),
+ (pd.DataFrame, frame_data, operator.methodcaller("set_axis", ["A"])),
+ (pd.DataFrame, frame_data, operator.methodcaller("reindex", [0, 1])),
+ (pd.DataFrame, frame_data, operator.methodcaller("drop", columns=["A"])),
+ (pd.DataFrame, frame_data, operator.methodcaller("drop", index=[0])),
+ (pd.DataFrame, frame_data, operator.methodcaller("rename", columns={"A": "a"})),
+ (pd.DataFrame, frame_data, operator.methodcaller("rename", index=lambda x: x)),
+ (pd.DataFrame, frame_data, operator.methodcaller("fillna", "A")),
+ (pd.DataFrame, frame_data, operator.methodcaller("fillna", method="ffill")),
+ (pd.DataFrame, frame_data, operator.methodcaller("set_index", "A")),
+ (pd.DataFrame, frame_data, operator.methodcaller("reset_index")),
+ (pd.DataFrame, frame_data, operator.methodcaller("isna")),
+ (pd.DataFrame, frame_data, operator.methodcaller("isnull")),
+ (pd.DataFrame, frame_data, operator.methodcaller("notna")),
+ (pd.DataFrame, frame_data, operator.methodcaller("notnull")),
+ (pd.DataFrame, frame_data, operator.methodcaller("dropna")),
+ (pd.DataFrame, frame_data, operator.methodcaller("drop_duplicates")),
+ (pd.DataFrame, frame_data, operator.methodcaller("duplicated")),
+ (pd.DataFrame, frame_data, operator.methodcaller("sort_values", by="A")),
+ (pd.DataFrame, frame_data, operator.methodcaller("sort_index")),
+ (pd.DataFrame, frame_data, operator.methodcaller("nlargest", 1, "A")),
+ (pd.DataFrame, frame_data, operator.methodcaller("nsmallest", 1, "A")),
+ (pd.DataFrame, frame_mi_data, operator.methodcaller("swaplevel")),
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("add", pd.DataFrame(*frame_data)),
+ ),
+ # TODO: div, mul, etc.
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("combine", pd.DataFrame(*frame_data), operator.add),
+ ),
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("combine_first", pd.DataFrame(*frame_data)),
+ ),
+ pytest.param(
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("update", pd.DataFrame(*frame_data)),
+ ),
+ marks=not_implemented_mark,
+ ),
+ (pd.DataFrame, frame_data, operator.methodcaller("pivot", columns="A")),
+ (
+ pd.DataFrame,
+ ({"A": [1], "B": [1]},),
+ operator.methodcaller("pivot_table", columns="A"),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1], "B": [1]},),
+ operator.methodcaller("pivot_table", columns="A", aggfunc=["mean", "sum"]),
+ ),
+ (pd.DataFrame, frame_data, operator.methodcaller("stack")),
+ (pd.DataFrame, frame_data, operator.methodcaller("explode", "A")),
+ (pd.DataFrame, frame_mi_data, operator.methodcaller("unstack")),
+ (
+ pd.DataFrame,
+ ({"A": ["a", "b", "c"], "B": [1, 3, 5], "C": [2, 4, 6]},),
+ operator.methodcaller("melt", id_vars=["A"], value_vars=["B"]),
+ ),
+ (pd.DataFrame, frame_data, operator.methodcaller("map", lambda x: x)),
+ pytest.param(
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("merge", pd.DataFrame({"A": [1]})),
+ ),
+ marks=not_implemented_mark,
+ ),
+ (pd.DataFrame, frame_data, operator.methodcaller("round", 2)),
+ (pd.DataFrame, frame_data, operator.methodcaller("corr")),
+ pytest.param(
+ (pd.DataFrame, frame_data, operator.methodcaller("cov")),
+ marks=[
+ pytest.mark.filterwarnings("ignore::RuntimeWarning"),
+ ],
+ ),
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("corrwith", pd.DataFrame(*frame_data)),
+ ),
+ (pd.DataFrame, frame_data, operator.methodcaller("count")),
+ (pd.DataFrame, frame_data, operator.methodcaller("nunique")),
+ (pd.DataFrame, frame_data, operator.methodcaller("idxmin")),
+ (pd.DataFrame, frame_data, operator.methodcaller("idxmax")),
+ (pd.DataFrame, frame_data, operator.methodcaller("mode")),
+ (pd.Series, [0], operator.methodcaller("mode")),
+ (pd.DataFrame, frame_data, operator.methodcaller("median")),
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("quantile", numeric_only=True),
+ ),
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("quantile", q=[0.25, 0.75], numeric_only=True),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [pd.Timedelta(days=1), pd.Timedelta(days=2)]},),
+ operator.methodcaller("quantile", numeric_only=False),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [np.datetime64("2022-01-01"), np.datetime64("2022-01-02")]},),
+ operator.methodcaller("quantile", numeric_only=True),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1]}, [pd.Period("2000", "D")]),
+ operator.methodcaller("to_timestamp"),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1]}, [pd.Timestamp("2000")]),
+ operator.methodcaller("to_period", freq="D"),
+ ),
+ (pd.DataFrame, frame_mi_data, operator.methodcaller("isin", [1])),
+ (pd.DataFrame, frame_mi_data, operator.methodcaller("isin", pd.Series([1]))),
+ (
+ pd.DataFrame,
+ frame_mi_data,
+ operator.methodcaller("isin", pd.DataFrame({"A": [1]})),
+ ),
+ (pd.DataFrame, frame_mi_data, operator.methodcaller("droplevel", "A")),
+ (pd.DataFrame, frame_data, operator.methodcaller("pop", "A")),
+ # Squeeze on columns, otherwise we'll end up with a scalar
+ (pd.DataFrame, frame_data, operator.methodcaller("squeeze", axis="columns")),
+ (pd.Series, ([1, 2],), operator.methodcaller("squeeze")),
+ (pd.Series, ([1, 2],), operator.methodcaller("rename_axis", index="a")),
+ (pd.DataFrame, frame_data, operator.methodcaller("rename_axis", columns="a")),
+ # Unary ops
+ (pd.DataFrame, frame_data, operator.neg),
+ (pd.Series, [1], operator.neg),
+ (pd.DataFrame, frame_data, operator.pos),
+ (pd.Series, [1], operator.pos),
+ (pd.DataFrame, frame_data, operator.inv),
+ (pd.Series, [1], operator.inv),
+ (pd.DataFrame, frame_data, abs),
+ (pd.Series, [1], abs),
+ (pd.DataFrame, frame_data, round),
+ (pd.Series, [1], round),
+ (pd.DataFrame, frame_data, operator.methodcaller("take", [0, 0])),
+ (pd.DataFrame, frame_mi_data, operator.methodcaller("xs", "a")),
+ (pd.Series, (1, mi), operator.methodcaller("xs", "a")),
+ (pd.DataFrame, frame_data, operator.methodcaller("get", "A")),
+ (
+ pd.DataFrame,
+ frame_data,
+ operator.methodcaller("reindex_like", pd.DataFrame({"A": [1, 2, 3]})),
+ ),
+ (
+ pd.Series,
+ frame_data,
+ operator.methodcaller("reindex_like", pd.Series([0, 1, 2])),
+ ),
+ (pd.DataFrame, frame_data, operator.methodcaller("add_prefix", "_")),
+ (pd.DataFrame, frame_data, operator.methodcaller("add_suffix", "_")),
+ (pd.Series, (1, ["a", "b"]), operator.methodcaller("add_prefix", "_")),
+ (pd.Series, (1, ["a", "b"]), operator.methodcaller("add_suffix", "_")),
+ (pd.Series, ([3, 2],), operator.methodcaller("sort_values")),
+ (pd.Series, ([1] * 10,), operator.methodcaller("head")),
+ (pd.DataFrame, ({"A": [1] * 10},), operator.methodcaller("head")),
+ (pd.Series, ([1] * 10,), operator.methodcaller("tail")),
+ (pd.DataFrame, ({"A": [1] * 10},), operator.methodcaller("tail")),
+ (pd.Series, ([1, 2],), operator.methodcaller("sample", n=2, replace=True)),
+ (pd.DataFrame, (frame_data,), operator.methodcaller("sample", n=2, replace=True)),
+ (pd.Series, ([1, 2],), operator.methodcaller("astype", float)),
+ (pd.DataFrame, frame_data, operator.methodcaller("astype", float)),
+ (pd.Series, ([1, 2],), operator.methodcaller("copy")),
+ (pd.DataFrame, frame_data, operator.methodcaller("copy")),
+ (pd.Series, ([1, 2], None, object), operator.methodcaller("infer_objects")),
+ (
+ pd.DataFrame,
+ ({"A": np.array([1, 2], dtype=object)},),
+ operator.methodcaller("infer_objects"),
+ ),
+ (pd.Series, ([1, 2],), operator.methodcaller("convert_dtypes")),
+ (pd.DataFrame, frame_data, operator.methodcaller("convert_dtypes")),
+ (pd.Series, ([1, None, 3],), operator.methodcaller("interpolate")),
+ (pd.DataFrame, ({"A": [1, None, 3]},), operator.methodcaller("interpolate")),
+ (pd.Series, ([1, 2],), operator.methodcaller("clip", lower=1)),
+ (pd.DataFrame, frame_data, operator.methodcaller("clip", lower=1)),
+ (
+ pd.Series,
+ (1, pd.date_range("2000", periods=4)),
+ operator.methodcaller("asfreq", "H"),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)),
+ operator.methodcaller("asfreq", "H"),
+ ),
+ (
+ pd.Series,
+ (1, pd.date_range("2000", periods=4)),
+ operator.methodcaller("at_time", "12:00"),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)),
+ operator.methodcaller("at_time", "12:00"),
+ ),
+ (
+ pd.Series,
+ (1, pd.date_range("2000", periods=4)),
+ operator.methodcaller("between_time", "12:00", "13:00"),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)),
+ operator.methodcaller("between_time", "12:00", "13:00"),
+ ),
+ (
+ pd.Series,
+ (1, pd.date_range("2000", periods=4)),
+ operator.methodcaller("last", "3D"),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)),
+ operator.methodcaller("last", "3D"),
+ ),
+ (pd.Series, ([1, 2],), operator.methodcaller("rank")),
+ (pd.DataFrame, frame_data, operator.methodcaller("rank")),
+ (pd.Series, ([1, 2],), operator.methodcaller("where", np.array([True, False]))),
+ (pd.DataFrame, frame_data, operator.methodcaller("where", np.array([[True]]))),
+ (pd.Series, ([1, 2],), operator.methodcaller("mask", np.array([True, False]))),
+ (pd.DataFrame, frame_data, operator.methodcaller("mask", np.array([[True]]))),
+ (pd.Series, ([1, 2],), operator.methodcaller("truncate", before=0)),
+ (pd.DataFrame, frame_data, operator.methodcaller("truncate", before=0)),
+ (
+ pd.Series,
+ (1, pd.date_range("2000", periods=4, tz="UTC")),
+ operator.methodcaller("tz_convert", "CET"),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4, tz="UTC")),
+ operator.methodcaller("tz_convert", "CET"),
+ ),
+ (
+ pd.Series,
+ (1, pd.date_range("2000", periods=4)),
+ operator.methodcaller("tz_localize", "CET"),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)),
+ operator.methodcaller("tz_localize", "CET"),
+ ),
+ (pd.Series, ([1, 2],), operator.methodcaller("describe")),
+ (pd.DataFrame, frame_data, operator.methodcaller("describe")),
+ (pd.Series, ([1, 2],), operator.methodcaller("pct_change")),
+ (pd.DataFrame, frame_data, operator.methodcaller("pct_change")),
+ (pd.Series, ([1],), operator.methodcaller("transform", lambda x: x - x.min())),
+ (
+ pd.DataFrame,
+ frame_mi_data,
+ operator.methodcaller("transform", lambda x: x - x.min()),
+ ),
+ (pd.Series, ([1],), operator.methodcaller("apply", lambda x: x)),
+ (pd.DataFrame, frame_mi_data, operator.methodcaller("apply", lambda x: x)),
+ # Cumulative reductions
+ (pd.Series, ([1],), operator.methodcaller("cumsum")),
+ (pd.DataFrame, frame_data, operator.methodcaller("cumsum")),
+ (pd.Series, ([1],), operator.methodcaller("cummin")),
+ (pd.DataFrame, frame_data, operator.methodcaller("cummin")),
+ (pd.Series, ([1],), operator.methodcaller("cummax")),
+ (pd.DataFrame, frame_data, operator.methodcaller("cummax")),
+ (pd.Series, ([1],), operator.methodcaller("cumprod")),
+ (pd.DataFrame, frame_data, operator.methodcaller("cumprod")),
+ # Reductions
+ (pd.DataFrame, frame_data, operator.methodcaller("any")),
+ (pd.DataFrame, frame_data, operator.methodcaller("all")),
+ (pd.DataFrame, frame_data, operator.methodcaller("min")),
+ (pd.DataFrame, frame_data, operator.methodcaller("max")),
+ (pd.DataFrame, frame_data, operator.methodcaller("sum")),
+ (pd.DataFrame, frame_data, operator.methodcaller("std")),
+ (pd.DataFrame, frame_data, operator.methodcaller("mean")),
+ (pd.DataFrame, frame_data, operator.methodcaller("prod")),
+ (pd.DataFrame, frame_data, operator.methodcaller("sem")),
+ (pd.DataFrame, frame_data, operator.methodcaller("skew")),
+ (pd.DataFrame, frame_data, operator.methodcaller("kurt")),
+]
+
+
+def idfn(x):
+ xpr = re.compile(r"'(.*)?'")
+ m = xpr.search(str(x))
+ if m:
+ return m.group(1)
+ else:
+ return str(x)
+
+
+@pytest.fixture(params=_all_methods, ids=lambda x: idfn(x[-1]))
+def ndframe_method(request):
+ """
+ An NDFrame method returning an NDFrame.
+ """
+ return request.param
+
+
+@pytest.mark.filterwarnings(
+ "ignore:DataFrame.fillna with 'method' is deprecated:FutureWarning",
+ "ignore:last is deprecated:FutureWarning",
+)
+def test_finalize_called(ndframe_method):
+ cls, init_args, method = ndframe_method
+ ndframe = cls(*init_args)
+
+ ndframe.attrs = {"a": 1}
+ result = method(ndframe)
+
+ assert result.attrs == {"a": 1}
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ pd.Series(1, pd.date_range("2000", periods=4)),
+ pd.DataFrame({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)),
+ ],
+)
+def test_finalize_first(data):
+ deprecated_msg = "first is deprecated"
+
+ data.attrs = {"a": 1}
+ with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):
+ result = data.first("3D")
+ assert result.attrs == {"a": 1}
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ pd.Series(1, pd.date_range("2000", periods=4)),
+ pd.DataFrame({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)),
+ ],
+)
+def test_finalize_last(data):
+ # GH 53710
+ deprecated_msg = "last is deprecated"
+
+ data.attrs = {"a": 1}
+ with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):
+ result = data.last("3D")
+ assert result.attrs == {"a": 1}
+
+
+@not_implemented_mark
+def test_finalize_called_eval_numexpr():
+ pytest.importorskip("numexpr")
+ df = pd.DataFrame({"A": [1, 2]})
+ df.attrs["A"] = 1
+ result = df.eval("A + 1", engine="numexpr")
+ assert result.attrs == {"A": 1}
+
+
+# ----------------------------------------------------------------------------
+# Binary operations
+
+
+@pytest.mark.parametrize("annotate", ["left", "right", "both"])
+@pytest.mark.parametrize(
+ "args",
+ [
+ (1, pd.Series([1])),
+ (1, pd.DataFrame({"A": [1]})),
+ (pd.Series([1]), 1),
+ (pd.DataFrame({"A": [1]}), 1),
+ (pd.Series([1]), pd.Series([1])),
+ (pd.DataFrame({"A": [1]}), pd.DataFrame({"A": [1]})),
+ (pd.Series([1]), pd.DataFrame({"A": [1]})),
+ (pd.DataFrame({"A": [1]}), pd.Series([1])),
+ ],
+ ids=lambda x: f"({type(x[0]).__name__},{type(x[1]).__name__})",
+)
+def test_binops(request, args, annotate, all_binary_operators):
+ # This generates 624 tests... Is that needed?
+ left, right = args
+ if isinstance(left, (pd.DataFrame, pd.Series)):
+ left.attrs = {}
+ if isinstance(right, (pd.DataFrame, pd.Series)):
+ right.attrs = {}
+
+ if annotate == "left" and isinstance(left, int):
+ pytest.skip("left is an int and doesn't support .attrs")
+ if annotate == "right" and isinstance(right, int):
+ pytest.skip("right is an int and doesn't support .attrs")
+
+ if not (isinstance(left, int) or isinstance(right, int)) and annotate != "both":
+ if not all_binary_operators.__name__.startswith("r"):
+ if annotate == "right" and isinstance(left, type(right)):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"{all_binary_operators} doesn't work when right has "
+ f"attrs and both are {type(left)}"
+ )
+ )
+ if not isinstance(left, type(right)):
+ if annotate == "left" and isinstance(left, pd.Series):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"{all_binary_operators} doesn't work when the "
+ "objects are different Series has attrs"
+ )
+ )
+ elif annotate == "right" and isinstance(right, pd.Series):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"{all_binary_operators} doesn't work when the "
+ "objects are different Series has attrs"
+ )
+ )
+ else:
+ if annotate == "left" and isinstance(left, type(right)):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"{all_binary_operators} doesn't work when left has "
+ f"attrs and both are {type(left)}"
+ )
+ )
+ if not isinstance(left, type(right)):
+ if annotate == "right" and isinstance(right, pd.Series):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"{all_binary_operators} doesn't work when the "
+ "objects are different Series has attrs"
+ )
+ )
+ elif annotate == "left" and isinstance(left, pd.Series):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"{all_binary_operators} doesn't work when the "
+ "objects are different Series has attrs"
+ )
+ )
+ if annotate in {"left", "both"} and not isinstance(left, int):
+ left.attrs = {"a": 1}
+ if annotate in {"right", "both"} and not isinstance(right, int):
+ right.attrs = {"a": 1}
+
+ is_cmp = all_binary_operators in [
+ operator.eq,
+ operator.ne,
+ operator.gt,
+ operator.ge,
+ operator.lt,
+ operator.le,
+ ]
+ if is_cmp and isinstance(left, pd.DataFrame) and isinstance(right, pd.Series):
+ # in 2.0 silent alignment on comparisons was removed xref GH#28759
+ left, right = left.align(right, axis=1, copy=False)
+ elif is_cmp and isinstance(left, pd.Series) and isinstance(right, pd.DataFrame):
+ right, left = right.align(left, axis=1, copy=False)
+
+ result = all_binary_operators(left, right)
+ assert result.attrs == {"a": 1}
+
+
+# ----------------------------------------------------------------------------
+# Accessors
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ operator.methodcaller("capitalize"),
+ operator.methodcaller("casefold"),
+ operator.methodcaller("cat", ["a"]),
+ operator.methodcaller("contains", "a"),
+ operator.methodcaller("count", "a"),
+ operator.methodcaller("encode", "utf-8"),
+ operator.methodcaller("endswith", "a"),
+ operator.methodcaller("extract", r"(\w)(\d)"),
+ operator.methodcaller("extract", r"(\w)(\d)", expand=False),
+ operator.methodcaller("find", "a"),
+ operator.methodcaller("findall", "a"),
+ operator.methodcaller("get", 0),
+ operator.methodcaller("index", "a"),
+ operator.methodcaller("len"),
+ operator.methodcaller("ljust", 4),
+ operator.methodcaller("lower"),
+ operator.methodcaller("lstrip"),
+ operator.methodcaller("match", r"\w"),
+ operator.methodcaller("normalize", "NFC"),
+ operator.methodcaller("pad", 4),
+ operator.methodcaller("partition", "a"),
+ operator.methodcaller("repeat", 2),
+ operator.methodcaller("replace", "a", "b"),
+ operator.methodcaller("rfind", "a"),
+ operator.methodcaller("rindex", "a"),
+ operator.methodcaller("rjust", 4),
+ operator.methodcaller("rpartition", "a"),
+ operator.methodcaller("rstrip"),
+ operator.methodcaller("slice", 4),
+ operator.methodcaller("slice_replace", 1, repl="a"),
+ operator.methodcaller("startswith", "a"),
+ operator.methodcaller("strip"),
+ operator.methodcaller("swapcase"),
+ operator.methodcaller("translate", {"a": "b"}),
+ operator.methodcaller("upper"),
+ operator.methodcaller("wrap", 4),
+ operator.methodcaller("zfill", 4),
+ operator.methodcaller("isalnum"),
+ operator.methodcaller("isalpha"),
+ operator.methodcaller("isdigit"),
+ operator.methodcaller("isspace"),
+ operator.methodcaller("islower"),
+ operator.methodcaller("isupper"),
+ operator.methodcaller("istitle"),
+ operator.methodcaller("isnumeric"),
+ operator.methodcaller("isdecimal"),
+ operator.methodcaller("get_dummies"),
+ ],
+ ids=idfn,
+)
+def test_string_method(method):
+ s = pd.Series(["a1"])
+ s.attrs = {"a": 1}
+ result = method(s.str)
+ assert result.attrs == {"a": 1}
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ operator.methodcaller("to_period"),
+ operator.methodcaller("tz_localize", "CET"),
+ operator.methodcaller("normalize"),
+ operator.methodcaller("strftime", "%Y"),
+ operator.methodcaller("round", "H"),
+ operator.methodcaller("floor", "H"),
+ operator.methodcaller("ceil", "H"),
+ operator.methodcaller("month_name"),
+ operator.methodcaller("day_name"),
+ ],
+ ids=idfn,
+)
+def test_datetime_method(method):
+ s = pd.Series(pd.date_range("2000", periods=4))
+ s.attrs = {"a": 1}
+ result = method(s.dt)
+ assert result.attrs == {"a": 1}
+
+
+@pytest.mark.parametrize(
+ "attr",
+ [
+ "date",
+ "time",
+ "timetz",
+ "year",
+ "month",
+ "day",
+ "hour",
+ "minute",
+ "second",
+ "microsecond",
+ "nanosecond",
+ "dayofweek",
+ "day_of_week",
+ "dayofyear",
+ "day_of_year",
+ "quarter",
+ "is_month_start",
+ "is_month_end",
+ "is_quarter_start",
+ "is_quarter_end",
+ "is_year_start",
+ "is_year_end",
+ "is_leap_year",
+ "daysinmonth",
+ "days_in_month",
+ ],
+)
+def test_datetime_property(attr):
+ s = pd.Series(pd.date_range("2000", periods=4))
+ s.attrs = {"a": 1}
+ result = getattr(s.dt, attr)
+ assert result.attrs == {"a": 1}
+
+
+@pytest.mark.parametrize(
+ "attr", ["days", "seconds", "microseconds", "nanoseconds", "components"]
+)
+def test_timedelta_property(attr):
+ s = pd.Series(pd.timedelta_range("2000", periods=4))
+ s.attrs = {"a": 1}
+ result = getattr(s.dt, attr)
+ assert result.attrs == {"a": 1}
+
+
+@pytest.mark.parametrize("method", [operator.methodcaller("total_seconds")])
+def test_timedelta_methods(method):
+ s = pd.Series(pd.timedelta_range("2000", periods=4))
+ s.attrs = {"a": 1}
+ result = method(s.dt)
+ assert result.attrs == {"a": 1}
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ operator.methodcaller("add_categories", ["c"]),
+ operator.methodcaller("as_ordered"),
+ operator.methodcaller("as_unordered"),
+ lambda x: getattr(x, "codes"),
+ operator.methodcaller("remove_categories", "a"),
+ operator.methodcaller("remove_unused_categories"),
+ operator.methodcaller("rename_categories", {"a": "A", "b": "B"}),
+ operator.methodcaller("reorder_categories", ["b", "a"]),
+ operator.methodcaller("set_categories", ["A", "B"]),
+ ],
+)
+@not_implemented_mark
+def test_categorical_accessor(method):
+ s = pd.Series(["a", "b"], dtype="category")
+ s.attrs = {"a": 1}
+ result = method(s.cat)
+ assert result.attrs == {"a": 1}
+
+
+# ----------------------------------------------------------------------------
+# Groupby
+
+
+@pytest.mark.parametrize(
+ "obj", [pd.Series([0, 0]), pd.DataFrame({"A": [0, 1], "B": [1, 2]})]
+)
+@pytest.mark.parametrize(
+ "method",
+ [
+ operator.methodcaller("sum"),
+ lambda x: x.apply(lambda y: y),
+ lambda x: x.agg("sum"),
+ lambda x: x.agg("mean"),
+ lambda x: x.agg("median"),
+ ],
+)
+def test_groupby_finalize(obj, method):
+ obj.attrs = {"a": 1}
+ result = method(obj.groupby([0, 0], group_keys=False))
+ assert result.attrs == {"a": 1}
+
+
+@pytest.mark.parametrize(
+ "obj", [pd.Series([0, 0]), pd.DataFrame({"A": [0, 1], "B": [1, 2]})]
+)
+@pytest.mark.parametrize(
+ "method",
+ [
+ lambda x: x.agg(["sum", "count"]),
+ lambda x: x.agg("std"),
+ lambda x: x.agg("var"),
+ lambda x: x.agg("sem"),
+ lambda x: x.agg("size"),
+ lambda x: x.agg("ohlc"),
+ ],
+)
+@not_implemented_mark
+def test_groupby_finalize_not_implemented(obj, method):
+ obj.attrs = {"a": 1}
+ result = method(obj.groupby([0, 0]))
+ assert result.attrs == {"a": 1}
+
+
+def test_finalize_frame_series_name():
+ # https://github.com/pandas-dev/pandas/pull/37186/files#r506978889
+ # ensure we don't copy the column `name` to the Series.
+ df = pd.DataFrame({"name": [1, 2]})
+ result = pd.Series([1, 2]).__finalize__(df)
+ assert result.name is None
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_frame.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_frame.py
new file mode 100644
index 0000000000000000000000000000000000000000..620d5055f5d3b56408f30dae3d3c83cae9af48a8
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_frame.py
@@ -0,0 +1,209 @@
+from copy import deepcopy
+from operator import methodcaller
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+
+
+class TestDataFrame:
+ @pytest.mark.parametrize("func", ["_set_axis_name", "rename_axis"])
+ def test_set_axis_name(self, func):
+ df = DataFrame([[1, 2], [3, 4]])
+
+ result = methodcaller(func, "foo")(df)
+ assert df.index.name is None
+ assert result.index.name == "foo"
+
+ result = methodcaller(func, "cols", axis=1)(df)
+ assert df.columns.name is None
+ assert result.columns.name == "cols"
+
+ @pytest.mark.parametrize("func", ["_set_axis_name", "rename_axis"])
+ def test_set_axis_name_mi(self, func):
+ df = DataFrame(
+ np.empty((3, 3)),
+ index=MultiIndex.from_tuples([("A", x) for x in list("aBc")]),
+ columns=MultiIndex.from_tuples([("C", x) for x in list("xyz")]),
+ )
+
+ level_names = ["L1", "L2"]
+
+ result = methodcaller(func, level_names)(df)
+ assert result.index.names == level_names
+ assert result.columns.names == [None, None]
+
+ result = methodcaller(func, level_names, axis=1)(df)
+ assert result.columns.names == ["L1", "L2"]
+ assert result.index.names == [None, None]
+
+ def test_nonzero_single_element(self):
+ # allow single item via bool method
+ msg_warn = (
+ "DataFrame.bool is now deprecated and will be removed "
+ "in future version of pandas"
+ )
+ df = DataFrame([[True]])
+ df1 = DataFrame([[False]])
+ with tm.assert_produces_warning(FutureWarning, match=msg_warn):
+ assert df.bool()
+
+ with tm.assert_produces_warning(FutureWarning, match=msg_warn):
+ assert not df1.bool()
+
+ df = DataFrame([[False, False]])
+ msg_err = "The truth value of a DataFrame is ambiguous"
+ with pytest.raises(ValueError, match=msg_err):
+ bool(df)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg_warn):
+ with pytest.raises(ValueError, match=msg_err):
+ df.bool()
+
+ def test_metadata_propagation_indiv_groupby(self):
+ # groupby
+ df = DataFrame(
+ {
+ "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
+ "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
+ "C": np.random.default_rng(2).standard_normal(8),
+ "D": np.random.default_rng(2).standard_normal(8),
+ }
+ )
+ result = df.groupby("A").sum()
+ tm.assert_metadata_equivalent(df, result)
+
+ def test_metadata_propagation_indiv_resample(self):
+ # resample
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((1000, 2)),
+ index=date_range("20130101", periods=1000, freq="s"),
+ )
+ result = df.resample("1T")
+ tm.assert_metadata_equivalent(df, result)
+
+ def test_metadata_propagation_indiv(self, monkeypatch):
+ # merging with override
+ # GH 6923
+
+ def finalize(self, other, method=None, **kwargs):
+ for name in self._metadata:
+ if method == "merge":
+ left, right = other.left, other.right
+ value = getattr(left, name, "") + "|" + getattr(right, name, "")
+ object.__setattr__(self, name, value)
+ elif method == "concat":
+ value = "+".join(
+ [getattr(o, name) for o in other.objs if getattr(o, name, None)]
+ )
+ object.__setattr__(self, name, value)
+ else:
+ object.__setattr__(self, name, getattr(other, name, ""))
+
+ return self
+
+ with monkeypatch.context() as m:
+ m.setattr(DataFrame, "_metadata", ["filename"])
+ m.setattr(DataFrame, "__finalize__", finalize)
+
+ df1 = DataFrame(
+ np.random.default_rng(2).integers(0, 4, (3, 2)), columns=["a", "b"]
+ )
+ df2 = DataFrame(
+ np.random.default_rng(2).integers(0, 4, (3, 2)), columns=["c", "d"]
+ )
+ DataFrame._metadata = ["filename"]
+ df1.filename = "fname1.csv"
+ df2.filename = "fname2.csv"
+
+ result = df1.merge(df2, left_on=["a"], right_on=["c"], how="inner")
+ assert result.filename == "fname1.csv|fname2.csv"
+
+ # concat
+ # GH#6927
+ df1 = DataFrame(
+ np.random.default_rng(2).integers(0, 4, (3, 2)), columns=list("ab")
+ )
+ df1.filename = "foo"
+
+ result = pd.concat([df1, df1])
+ assert result.filename == "foo+foo"
+
+ def test_set_attribute(self):
+ # Test for consistent setattr behavior when an attribute and a column
+ # have the same name (Issue #8994)
+ df = DataFrame({"x": [1, 2, 3]})
+
+ df.y = 2
+ df["y"] = [2, 4, 6]
+ df.y = 5
+
+ assert df.y == 5
+ tm.assert_series_equal(df["y"], Series([2, 4, 6], name="y"))
+
+ def test_deepcopy_empty(self):
+ # This test covers empty frame copying with non-empty column sets
+ # as reported in issue GH15370
+ empty_frame = DataFrame(data=[], index=[], columns=["A"])
+ empty_frame_copy = deepcopy(empty_frame)
+
+ tm.assert_frame_equal(empty_frame_copy, empty_frame)
+
+
+# formerly in Generic but only test DataFrame
+class TestDataFrame2:
+ @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
+ def test_validate_bool_args(self, value):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+
+ msg = 'For argument "inplace" expected type bool, received type'
+ with pytest.raises(ValueError, match=msg):
+ df.copy().rename_axis(mapper={"a": "x", "b": "y"}, axis=1, inplace=value)
+
+ with pytest.raises(ValueError, match=msg):
+ df.copy().drop("a", axis=1, inplace=value)
+
+ with pytest.raises(ValueError, match=msg):
+ df.copy().fillna(value=0, inplace=value)
+
+ with pytest.raises(ValueError, match=msg):
+ df.copy().replace(to_replace=1, value=7, inplace=value)
+
+ with pytest.raises(ValueError, match=msg):
+ df.copy().interpolate(inplace=value)
+
+ with pytest.raises(ValueError, match=msg):
+ df.copy()._where(cond=df.a > 2, inplace=value)
+
+ with pytest.raises(ValueError, match=msg):
+ df.copy().mask(cond=df.a > 2, inplace=value)
+
+ def test_unexpected_keyword(self):
+ # GH8597
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=["jim", "joe"]
+ )
+ ca = pd.Categorical([0, 0, 2, 2, 3, np.nan])
+ ts = df["joe"].copy()
+ ts[2] = np.nan
+
+ msg = "unexpected keyword"
+ with pytest.raises(TypeError, match=msg):
+ df.drop("joe", axis=1, in_place=True)
+
+ with pytest.raises(TypeError, match=msg):
+ df.reindex([1, 0], inplace=True)
+
+ with pytest.raises(TypeError, match=msg):
+ ca.fillna(0, inplace=True)
+
+ with pytest.raises(TypeError, match=msg):
+ ts.fillna(0, in_place=True)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_generic.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_generic.py
new file mode 100644
index 0000000000000000000000000000000000000000..87beab04bc58630b128772ea7f2d8c1623f25812
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_generic.py
@@ -0,0 +1,462 @@
+from copy import (
+ copy,
+ deepcopy,
+)
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.common import is_scalar
+
+from pandas import (
+ DataFrame,
+ Series,
+)
+import pandas._testing as tm
+
+# ----------------------------------------------------------------------
+# Generic types test cases
+
+
+def construct(box, shape, value=None, dtype=None, **kwargs):
+ """
+ construct an object for the given shape
+ if value is specified use that if its a scalar
+ if value is an array, repeat it as needed
+ """
+ if isinstance(shape, int):
+ shape = tuple([shape] * box._AXIS_LEN)
+ if value is not None:
+ if is_scalar(value):
+ if value == "empty":
+ arr = None
+ dtype = np.float64
+
+ # remove the info axis
+ kwargs.pop(box._info_axis_name, None)
+ else:
+ arr = np.empty(shape, dtype=dtype)
+ arr.fill(value)
+ else:
+ fshape = np.prod(shape)
+ arr = value.ravel()
+ new_shape = fshape / arr.shape[0]
+ if fshape % arr.shape[0] != 0:
+ raise Exception("invalid value passed in construct")
+
+ arr = np.repeat(arr, new_shape).reshape(shape)
+ else:
+ arr = np.random.default_rng(2).standard_normal(shape)
+ return box(arr, dtype=dtype, **kwargs)
+
+
+class TestGeneric:
+ @pytest.mark.parametrize(
+ "func",
+ [
+ str.lower,
+ {x: x.lower() for x in list("ABCD")},
+ Series({x: x.lower() for x in list("ABCD")}),
+ ],
+ )
+ def test_rename(self, frame_or_series, func):
+ # single axis
+ idx = list("ABCD")
+
+ for axis in frame_or_series._AXIS_ORDERS:
+ kwargs = {axis: idx}
+ obj = construct(frame_or_series, 4, **kwargs)
+
+ # rename a single axis
+ result = obj.rename(**{axis: func})
+ expected = obj.copy()
+ setattr(expected, axis, list("abcd"))
+ tm.assert_equal(result, expected)
+
+ def test_get_numeric_data(self, frame_or_series):
+ n = 4
+ kwargs = {
+ frame_or_series._get_axis_name(i): list(range(n))
+ for i in range(frame_or_series._AXIS_LEN)
+ }
+
+ # get the numeric data
+ o = construct(frame_or_series, n, **kwargs)
+ result = o._get_numeric_data()
+ tm.assert_equal(result, o)
+
+ # non-inclusion
+ result = o._get_bool_data()
+ expected = construct(frame_or_series, n, value="empty", **kwargs)
+ if isinstance(o, DataFrame):
+ # preserve columns dtype
+ expected.columns = o.columns[:0]
+ # https://github.com/pandas-dev/pandas/issues/50862
+ tm.assert_equal(result.reset_index(drop=True), expected)
+
+ # get the bool data
+ arr = np.array([True, True, False, True])
+ o = construct(frame_or_series, n, value=arr, **kwargs)
+ result = o._get_numeric_data()
+ tm.assert_equal(result, o)
+
+ def test_nonzero(self, frame_or_series):
+ # GH 4633
+ # look at the boolean/nonzero behavior for objects
+ obj = construct(frame_or_series, shape=4)
+ msg = f"The truth value of a {frame_or_series.__name__} is ambiguous"
+ with pytest.raises(ValueError, match=msg):
+ bool(obj == 0)
+ with pytest.raises(ValueError, match=msg):
+ bool(obj == 1)
+ with pytest.raises(ValueError, match=msg):
+ bool(obj)
+
+ obj = construct(frame_or_series, shape=4, value=1)
+ with pytest.raises(ValueError, match=msg):
+ bool(obj == 0)
+ with pytest.raises(ValueError, match=msg):
+ bool(obj == 1)
+ with pytest.raises(ValueError, match=msg):
+ bool(obj)
+
+ obj = construct(frame_or_series, shape=4, value=np.nan)
+ with pytest.raises(ValueError, match=msg):
+ bool(obj == 0)
+ with pytest.raises(ValueError, match=msg):
+ bool(obj == 1)
+ with pytest.raises(ValueError, match=msg):
+ bool(obj)
+
+ # empty
+ obj = construct(frame_or_series, shape=0)
+ with pytest.raises(ValueError, match=msg):
+ bool(obj)
+
+ # invalid behaviors
+
+ obj1 = construct(frame_or_series, shape=4, value=1)
+ obj2 = construct(frame_or_series, shape=4, value=1)
+
+ with pytest.raises(ValueError, match=msg):
+ if obj1:
+ pass
+
+ with pytest.raises(ValueError, match=msg):
+ obj1 and obj2
+ with pytest.raises(ValueError, match=msg):
+ obj1 or obj2
+ with pytest.raises(ValueError, match=msg):
+ not obj1
+
+ def test_frame_or_series_compound_dtypes(self, frame_or_series):
+ # see gh-5191
+ # Compound dtypes should raise NotImplementedError.
+
+ def f(dtype):
+ return construct(frame_or_series, shape=3, value=1, dtype=dtype)
+
+ msg = (
+ "compound dtypes are not implemented "
+ f"in the {frame_or_series.__name__} constructor"
+ )
+
+ with pytest.raises(NotImplementedError, match=msg):
+ f([("A", "datetime64[h]"), ("B", "str"), ("C", "int32")])
+
+ # these work (though results may be unexpected)
+ f("int64")
+ f("float64")
+ f("M8[ns]")
+
+ def test_metadata_propagation(self, frame_or_series):
+ # check that the metadata matches up on the resulting ops
+
+ o = construct(frame_or_series, shape=3)
+ o.name = "foo"
+ o2 = construct(frame_or_series, shape=3)
+ o2.name = "bar"
+
+ # ----------
+ # preserving
+ # ----------
+
+ # simple ops with scalars
+ for op in ["__add__", "__sub__", "__truediv__", "__mul__"]:
+ result = getattr(o, op)(1)
+ tm.assert_metadata_equivalent(o, result)
+
+ # ops with like
+ for op in ["__add__", "__sub__", "__truediv__", "__mul__"]:
+ result = getattr(o, op)(o)
+ tm.assert_metadata_equivalent(o, result)
+
+ # simple boolean
+ for op in ["__eq__", "__le__", "__ge__"]:
+ v1 = getattr(o, op)(o)
+ tm.assert_metadata_equivalent(o, v1)
+ tm.assert_metadata_equivalent(o, v1 & v1)
+ tm.assert_metadata_equivalent(o, v1 | v1)
+
+ # combine_first
+ result = o.combine_first(o2)
+ tm.assert_metadata_equivalent(o, result)
+
+ # ---------------------------
+ # non-preserving (by default)
+ # ---------------------------
+
+ # add non-like
+ result = o + o2
+ tm.assert_metadata_equivalent(result)
+
+ # simple boolean
+ for op in ["__eq__", "__le__", "__ge__"]:
+ # this is a name matching op
+ v1 = getattr(o, op)(o)
+ v2 = getattr(o, op)(o2)
+ tm.assert_metadata_equivalent(v2)
+ tm.assert_metadata_equivalent(v1 & v2)
+ tm.assert_metadata_equivalent(v1 | v2)
+
+ def test_size_compat(self, frame_or_series):
+ # GH8846
+ # size property should be defined
+
+ o = construct(frame_or_series, shape=10)
+ assert o.size == np.prod(o.shape)
+ assert o.size == 10 ** len(o.axes)
+
+ def test_split_compat(self, frame_or_series):
+ # xref GH8846
+ o = construct(frame_or_series, shape=10)
+ with tm.assert_produces_warning(
+ FutureWarning, match=".swapaxes' is deprecated", check_stacklevel=False
+ ):
+ assert len(np.array_split(o, 5)) == 5
+ assert len(np.array_split(o, 2)) == 2
+
+ # See gh-12301
+ def test_stat_unexpected_keyword(self, frame_or_series):
+ obj = construct(frame_or_series, 5)
+ starwars = "Star Wars"
+ errmsg = "unexpected keyword"
+
+ with pytest.raises(TypeError, match=errmsg):
+ obj.max(epic=starwars) # stat_function
+ with pytest.raises(TypeError, match=errmsg):
+ obj.var(epic=starwars) # stat_function_ddof
+ with pytest.raises(TypeError, match=errmsg):
+ obj.sum(epic=starwars) # cum_function
+ with pytest.raises(TypeError, match=errmsg):
+ obj.any(epic=starwars) # logical_function
+
+ @pytest.mark.parametrize("func", ["sum", "cumsum", "any", "var"])
+ def test_api_compat(self, func, frame_or_series):
+ # GH 12021
+ # compat for __name__, __qualname__
+
+ obj = construct(frame_or_series, 5)
+ f = getattr(obj, func)
+ assert f.__name__ == func
+ assert f.__qualname__.endswith(func)
+
+ def test_stat_non_defaults_args(self, frame_or_series):
+ obj = construct(frame_or_series, 5)
+ out = np.array([0])
+ errmsg = "the 'out' parameter is not supported"
+
+ with pytest.raises(ValueError, match=errmsg):
+ obj.max(out=out) # stat_function
+ with pytest.raises(ValueError, match=errmsg):
+ obj.var(out=out) # stat_function_ddof
+ with pytest.raises(ValueError, match=errmsg):
+ obj.sum(out=out) # cum_function
+ with pytest.raises(ValueError, match=errmsg):
+ obj.any(out=out) # logical_function
+
+ def test_truncate_out_of_bounds(self, frame_or_series):
+ # GH11382
+
+ # small
+ shape = [2000] + ([1] * (frame_or_series._AXIS_LEN - 1))
+ small = construct(frame_or_series, shape, dtype="int8", value=1)
+ tm.assert_equal(small.truncate(), small)
+ tm.assert_equal(small.truncate(before=0, after=3e3), small)
+ tm.assert_equal(small.truncate(before=-1, after=2e3), small)
+
+ # big
+ shape = [2_000_000] + ([1] * (frame_or_series._AXIS_LEN - 1))
+ big = construct(frame_or_series, shape, dtype="int8", value=1)
+ tm.assert_equal(big.truncate(), big)
+ tm.assert_equal(big.truncate(before=0, after=3e6), big)
+ tm.assert_equal(big.truncate(before=-1, after=2e6), big)
+
+ @pytest.mark.parametrize(
+ "func",
+ [copy, deepcopy, lambda x: x.copy(deep=False), lambda x: x.copy(deep=True)],
+ )
+ @pytest.mark.parametrize("shape", [0, 1, 2])
+ def test_copy_and_deepcopy(self, frame_or_series, shape, func):
+ # GH 15444
+ obj = construct(frame_or_series, shape)
+ obj_copy = func(obj)
+ assert obj_copy is not obj
+ tm.assert_equal(obj_copy, obj)
+
+ def test_data_deprecated(self, frame_or_series):
+ obj = frame_or_series()
+ msg = "(Series|DataFrame)._data is deprecated"
+ with tm.assert_produces_warning(DeprecationWarning, match=msg):
+ mgr = obj._data
+ assert mgr is obj._mgr
+
+
+class TestNDFrame:
+ # tests that don't fit elsewhere
+
+ @pytest.mark.parametrize(
+ "ser", [tm.makeFloatSeries(), tm.makeStringSeries(), tm.makeObjectSeries()]
+ )
+ def test_squeeze_series_noop(self, ser):
+ # noop
+ tm.assert_series_equal(ser.squeeze(), ser)
+
+ def test_squeeze_frame_noop(self):
+ # noop
+ df = tm.makeTimeDataFrame()
+ tm.assert_frame_equal(df.squeeze(), df)
+
+ def test_squeeze_frame_reindex(self):
+ # squeezing
+ df = tm.makeTimeDataFrame().reindex(columns=["A"])
+ tm.assert_series_equal(df.squeeze(), df["A"])
+
+ def test_squeeze_0_len_dim(self):
+ # don't fail with 0 length dimensions GH11229 & GH8999
+ empty_series = Series([], name="five", dtype=np.float64)
+ empty_frame = DataFrame([empty_series])
+ tm.assert_series_equal(empty_series, empty_series.squeeze())
+ tm.assert_series_equal(empty_series, empty_frame.squeeze())
+
+ def test_squeeze_axis(self):
+ # axis argument
+ df = tm.makeTimeDataFrame(nper=1).iloc[:, :1]
+ assert df.shape == (1, 1)
+ tm.assert_series_equal(df.squeeze(axis=0), df.iloc[0])
+ tm.assert_series_equal(df.squeeze(axis="index"), df.iloc[0])
+ tm.assert_series_equal(df.squeeze(axis=1), df.iloc[:, 0])
+ tm.assert_series_equal(df.squeeze(axis="columns"), df.iloc[:, 0])
+ assert df.squeeze() == df.iloc[0, 0]
+ msg = "No axis named 2 for object type DataFrame"
+ with pytest.raises(ValueError, match=msg):
+ df.squeeze(axis=2)
+ msg = "No axis named x for object type DataFrame"
+ with pytest.raises(ValueError, match=msg):
+ df.squeeze(axis="x")
+
+ def test_squeeze_axis_len_3(self):
+ df = tm.makeTimeDataFrame(3)
+ tm.assert_frame_equal(df.squeeze(axis=0), df)
+
+ def test_numpy_squeeze(self):
+ s = tm.makeFloatSeries()
+ tm.assert_series_equal(np.squeeze(s), s)
+
+ df = tm.makeTimeDataFrame().reindex(columns=["A"])
+ tm.assert_series_equal(np.squeeze(df), df["A"])
+
+ @pytest.mark.parametrize(
+ "ser", [tm.makeFloatSeries(), tm.makeStringSeries(), tm.makeObjectSeries()]
+ )
+ def test_transpose_series(self, ser):
+ # calls implementation in pandas/core/base.py
+ tm.assert_series_equal(ser.transpose(), ser)
+
+ def test_transpose_frame(self):
+ df = tm.makeTimeDataFrame()
+ tm.assert_frame_equal(df.transpose().transpose(), df)
+
+ def test_numpy_transpose(self, frame_or_series):
+ obj = tm.makeTimeDataFrame()
+ obj = tm.get_obj(obj, frame_or_series)
+
+ if frame_or_series is Series:
+ # 1D -> np.transpose is no-op
+ tm.assert_series_equal(np.transpose(obj), obj)
+
+ # round-trip preserved
+ tm.assert_equal(np.transpose(np.transpose(obj)), obj)
+
+ msg = "the 'axes' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ np.transpose(obj, axes=1)
+
+ @pytest.mark.parametrize(
+ "ser", [tm.makeFloatSeries(), tm.makeStringSeries(), tm.makeObjectSeries()]
+ )
+ def test_take_series(self, ser):
+ indices = [1, 5, -2, 6, 3, -1]
+ out = ser.take(indices)
+ expected = Series(
+ data=ser.values.take(indices),
+ index=ser.index.take(indices),
+ dtype=ser.dtype,
+ )
+ tm.assert_series_equal(out, expected)
+
+ def test_take_frame(self):
+ indices = [1, 5, -2, 6, 3, -1]
+ df = tm.makeTimeDataFrame()
+ out = df.take(indices)
+ expected = DataFrame(
+ data=df.values.take(indices, axis=0),
+ index=df.index.take(indices),
+ columns=df.columns,
+ )
+ tm.assert_frame_equal(out, expected)
+
+ def test_take_invalid_kwargs(self, frame_or_series):
+ indices = [-3, 2, 0, 1]
+
+ obj = tm.makeTimeDataFrame()
+ obj = tm.get_obj(obj, frame_or_series)
+
+ msg = r"take\(\) got an unexpected keyword argument 'foo'"
+ with pytest.raises(TypeError, match=msg):
+ obj.take(indices, foo=2)
+
+ msg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ obj.take(indices, out=indices)
+
+ msg = "the 'mode' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ obj.take(indices, mode="clip")
+
+ def test_axis_classmethods(self, frame_or_series):
+ box = frame_or_series
+ obj = box(dtype=object)
+ values = box._AXIS_TO_AXIS_NUMBER.keys()
+ for v in values:
+ assert obj._get_axis_number(v) == box._get_axis_number(v)
+ assert obj._get_axis_name(v) == box._get_axis_name(v)
+ assert obj._get_block_manager_axis(v) == box._get_block_manager_axis(v)
+
+ def test_flags_identity(self, frame_or_series):
+ obj = Series([1, 2])
+ if frame_or_series is DataFrame:
+ obj = obj.to_frame()
+
+ assert obj.flags is obj.flags
+ obj2 = obj.copy()
+ assert obj2.flags is not obj.flags
+
+ def test_bool_dep(self) -> None:
+ # GH-51749
+ msg_warn = (
+ "DataFrame.bool is now deprecated and will be removed "
+ "in future version of pandas"
+ )
+ with tm.assert_produces_warning(FutureWarning, match=msg_warn):
+ DataFrame({"col": [False]}).bool()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_label_or_level_utils.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_label_or_level_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..97be46f716d7daa98c1c1ebab04e1e6abb3a55bc
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_label_or_level_utils.py
@@ -0,0 +1,336 @@
+import pytest
+
+from pandas.core.dtypes.missing import array_equivalent
+
+import pandas as pd
+
+
+# Fixtures
+# ========
+@pytest.fixture
+def df():
+ """DataFrame with columns 'L1', 'L2', and 'L3'"""
+ return pd.DataFrame({"L1": [1, 2, 3], "L2": [11, 12, 13], "L3": ["A", "B", "C"]})
+
+
+@pytest.fixture(params=[[], ["L1"], ["L1", "L2"], ["L1", "L2", "L3"]])
+def df_levels(request, df):
+ """DataFrame with columns or index levels 'L1', 'L2', and 'L3'"""
+ levels = request.param
+
+ if levels:
+ df = df.set_index(levels)
+
+ return df
+
+
+@pytest.fixture
+def df_ambig(df):
+ """DataFrame with levels 'L1' and 'L2' and labels 'L1' and 'L3'"""
+ df = df.set_index(["L1", "L2"])
+
+ df["L1"] = df["L3"]
+
+ return df
+
+
+@pytest.fixture
+def df_duplabels(df):
+ """DataFrame with level 'L1' and labels 'L2', 'L3', and 'L2'"""
+ df = df.set_index(["L1"])
+ df = pd.concat([df, df["L2"]], axis=1)
+
+ return df
+
+
+# Test is label/level reference
+# =============================
+def get_labels_levels(df_levels):
+ expected_labels = list(df_levels.columns)
+ expected_levels = [name for name in df_levels.index.names if name is not None]
+ return expected_labels, expected_levels
+
+
+def assert_label_reference(frame, labels, axis):
+ for label in labels:
+ assert frame._is_label_reference(label, axis=axis)
+ assert not frame._is_level_reference(label, axis=axis)
+ assert frame._is_label_or_level_reference(label, axis=axis)
+
+
+def assert_level_reference(frame, levels, axis):
+ for level in levels:
+ assert frame._is_level_reference(level, axis=axis)
+ assert not frame._is_label_reference(level, axis=axis)
+ assert frame._is_label_or_level_reference(level, axis=axis)
+
+
+# DataFrame
+# ---------
+def test_is_level_or_label_reference_df_simple(df_levels, axis):
+ axis = df_levels._get_axis_number(axis)
+ # Compute expected labels and levels
+ expected_labels, expected_levels = get_labels_levels(df_levels)
+
+ # Transpose frame if axis == 1
+ if axis == 1:
+ df_levels = df_levels.T
+
+ # Perform checks
+ assert_level_reference(df_levels, expected_levels, axis=axis)
+ assert_label_reference(df_levels, expected_labels, axis=axis)
+
+
+def test_is_level_reference_df_ambig(df_ambig, axis):
+ axis = df_ambig._get_axis_number(axis)
+
+ # Transpose frame if axis == 1
+ if axis == 1:
+ df_ambig = df_ambig.T
+
+ # df has both an on-axis level and off-axis label named L1
+ # Therefore L1 should reference the label, not the level
+ assert_label_reference(df_ambig, ["L1"], axis=axis)
+
+ # df has an on-axis level named L2 and it is not ambiguous
+ # Therefore L2 is an level reference
+ assert_level_reference(df_ambig, ["L2"], axis=axis)
+
+ # df has a column named L3 and it not an level reference
+ assert_label_reference(df_ambig, ["L3"], axis=axis)
+
+
+# Series
+# ------
+def test_is_level_reference_series_simple_axis0(df):
+ # Make series with L1 as index
+ s = df.set_index("L1").L2
+ assert_level_reference(s, ["L1"], axis=0)
+ assert not s._is_level_reference("L2")
+
+ # Make series with L1 and L2 as index
+ s = df.set_index(["L1", "L2"]).L3
+ assert_level_reference(s, ["L1", "L2"], axis=0)
+ assert not s._is_level_reference("L3")
+
+
+def test_is_level_reference_series_axis1_error(df):
+ # Make series with L1 as index
+ s = df.set_index("L1").L2
+
+ with pytest.raises(ValueError, match="No axis named 1"):
+ s._is_level_reference("L1", axis=1)
+
+
+# Test _check_label_or_level_ambiguity_df
+# =======================================
+
+
+# DataFrame
+# ---------
+def test_check_label_or_level_ambiguity_df(df_ambig, axis):
+ axis = df_ambig._get_axis_number(axis)
+ # Transpose frame if axis == 1
+ if axis == 1:
+ df_ambig = df_ambig.T
+ msg = "'L1' is both a column level and an index label"
+
+ else:
+ msg = "'L1' is both an index level and a column label"
+ # df_ambig has both an on-axis level and off-axis label named L1
+ # Therefore, L1 is ambiguous.
+ with pytest.raises(ValueError, match=msg):
+ df_ambig._check_label_or_level_ambiguity("L1", axis=axis)
+
+ # df_ambig has an on-axis level named L2,, and it is not ambiguous.
+ df_ambig._check_label_or_level_ambiguity("L2", axis=axis)
+
+ # df_ambig has an off-axis label named L3, and it is not ambiguous
+ assert not df_ambig._check_label_or_level_ambiguity("L3", axis=axis)
+
+
+# Series
+# ------
+def test_check_label_or_level_ambiguity_series(df):
+ # A series has no columns and therefore references are never ambiguous
+
+ # Make series with L1 as index
+ s = df.set_index("L1").L2
+ s._check_label_or_level_ambiguity("L1", axis=0)
+ s._check_label_or_level_ambiguity("L2", axis=0)
+
+ # Make series with L1 and L2 as index
+ s = df.set_index(["L1", "L2"]).L3
+ s._check_label_or_level_ambiguity("L1", axis=0)
+ s._check_label_or_level_ambiguity("L2", axis=0)
+ s._check_label_or_level_ambiguity("L3", axis=0)
+
+
+def test_check_label_or_level_ambiguity_series_axis1_error(df):
+ # Make series with L1 as index
+ s = df.set_index("L1").L2
+
+ with pytest.raises(ValueError, match="No axis named 1"):
+ s._check_label_or_level_ambiguity("L1", axis=1)
+
+
+# Test _get_label_or_level_values
+# ===============================
+def assert_label_values(frame, labels, axis):
+ axis = frame._get_axis_number(axis)
+ for label in labels:
+ if axis == 0:
+ expected = frame[label]._values
+ else:
+ expected = frame.loc[label]._values
+
+ result = frame._get_label_or_level_values(label, axis=axis)
+ assert array_equivalent(expected, result)
+
+
+def assert_level_values(frame, levels, axis):
+ axis = frame._get_axis_number(axis)
+ for level in levels:
+ if axis == 0:
+ expected = frame.index.get_level_values(level=level)._values
+ else:
+ expected = frame.columns.get_level_values(level=level)._values
+
+ result = frame._get_label_or_level_values(level, axis=axis)
+ assert array_equivalent(expected, result)
+
+
+# DataFrame
+# ---------
+def test_get_label_or_level_values_df_simple(df_levels, axis):
+ # Compute expected labels and levels
+ expected_labels, expected_levels = get_labels_levels(df_levels)
+
+ axis = df_levels._get_axis_number(axis)
+ # Transpose frame if axis == 1
+ if axis == 1:
+ df_levels = df_levels.T
+
+ # Perform checks
+ assert_label_values(df_levels, expected_labels, axis=axis)
+ assert_level_values(df_levels, expected_levels, axis=axis)
+
+
+def test_get_label_or_level_values_df_ambig(df_ambig, axis):
+ axis = df_ambig._get_axis_number(axis)
+ # Transpose frame if axis == 1
+ if axis == 1:
+ df_ambig = df_ambig.T
+
+ # df has an on-axis level named L2, and it is not ambiguous.
+ assert_level_values(df_ambig, ["L2"], axis=axis)
+
+ # df has an off-axis label named L3, and it is not ambiguous.
+ assert_label_values(df_ambig, ["L3"], axis=axis)
+
+
+def test_get_label_or_level_values_df_duplabels(df_duplabels, axis):
+ axis = df_duplabels._get_axis_number(axis)
+ # Transpose frame if axis == 1
+ if axis == 1:
+ df_duplabels = df_duplabels.T
+
+ # df has unambiguous level 'L1'
+ assert_level_values(df_duplabels, ["L1"], axis=axis)
+
+ # df has unique label 'L3'
+ assert_label_values(df_duplabels, ["L3"], axis=axis)
+
+ # df has duplicate labels 'L2'
+ if axis == 0:
+ expected_msg = "The column label 'L2' is not unique"
+ else:
+ expected_msg = "The index label 'L2' is not unique"
+
+ with pytest.raises(ValueError, match=expected_msg):
+ assert_label_values(df_duplabels, ["L2"], axis=axis)
+
+
+# Series
+# ------
+def test_get_label_or_level_values_series_axis0(df):
+ # Make series with L1 as index
+ s = df.set_index("L1").L2
+ assert_level_values(s, ["L1"], axis=0)
+
+ # Make series with L1 and L2 as index
+ s = df.set_index(["L1", "L2"]).L3
+ assert_level_values(s, ["L1", "L2"], axis=0)
+
+
+def test_get_label_or_level_values_series_axis1_error(df):
+ # Make series with L1 as index
+ s = df.set_index("L1").L2
+
+ with pytest.raises(ValueError, match="No axis named 1"):
+ s._get_label_or_level_values("L1", axis=1)
+
+
+# Test _drop_labels_or_levels
+# ===========================
+def assert_labels_dropped(frame, labels, axis):
+ axis = frame._get_axis_number(axis)
+ for label in labels:
+ df_dropped = frame._drop_labels_or_levels(label, axis=axis)
+
+ if axis == 0:
+ assert label in frame.columns
+ assert label not in df_dropped.columns
+ else:
+ assert label in frame.index
+ assert label not in df_dropped.index
+
+
+def assert_levels_dropped(frame, levels, axis):
+ axis = frame._get_axis_number(axis)
+ for level in levels:
+ df_dropped = frame._drop_labels_or_levels(level, axis=axis)
+
+ if axis == 0:
+ assert level in frame.index.names
+ assert level not in df_dropped.index.names
+ else:
+ assert level in frame.columns.names
+ assert level not in df_dropped.columns.names
+
+
+# DataFrame
+# ---------
+def test_drop_labels_or_levels_df(df_levels, axis):
+ # Compute expected labels and levels
+ expected_labels, expected_levels = get_labels_levels(df_levels)
+
+ axis = df_levels._get_axis_number(axis)
+ # Transpose frame if axis == 1
+ if axis == 1:
+ df_levels = df_levels.T
+
+ # Perform checks
+ assert_labels_dropped(df_levels, expected_labels, axis=axis)
+ assert_levels_dropped(df_levels, expected_levels, axis=axis)
+
+ with pytest.raises(ValueError, match="not valid labels or levels"):
+ df_levels._drop_labels_or_levels("L4", axis=axis)
+
+
+# Series
+# ------
+def test_drop_labels_or_levels_series(df):
+ # Make series with L1 as index
+ s = df.set_index("L1").L2
+ assert_levels_dropped(s, ["L1"], axis=0)
+
+ with pytest.raises(ValueError, match="not valid labels or levels"):
+ s._drop_labels_or_levels("L4", axis=0)
+
+ # Make series with L1 and L2 as index
+ s = df.set_index(["L1", "L2"]).L3
+ assert_levels_dropped(s, ["L1", "L2"], axis=0)
+
+ with pytest.raises(ValueError, match="not valid labels or levels"):
+ s._drop_labels_or_levels("L4", axis=0)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_series.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_series.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ea205ac13c475c41b810df25001f158ba4ca016
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_series.py
@@ -0,0 +1,159 @@
+from operator import methodcaller
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ MultiIndex,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+
+
+class TestSeries:
+ @pytest.mark.parametrize("func", ["rename_axis", "_set_axis_name"])
+ def test_set_axis_name_mi(self, func):
+ ser = Series(
+ [11, 21, 31],
+ index=MultiIndex.from_tuples(
+ [("A", x) for x in ["a", "B", "c"]], names=["l1", "l2"]
+ ),
+ )
+
+ result = methodcaller(func, ["L1", "L2"])(ser)
+ assert ser.index.name is None
+ assert ser.index.names == ["l1", "l2"]
+ assert result.index.name is None
+ assert result.index.names, ["L1", "L2"]
+
+ def test_set_axis_name_raises(self):
+ ser = Series([1])
+ msg = "No axis named 1 for object type Series"
+ with pytest.raises(ValueError, match=msg):
+ ser._set_axis_name(name="a", axis=1)
+
+ def test_get_bool_data_preserve_dtype(self):
+ ser = Series([True, False, True])
+ result = ser._get_bool_data()
+ tm.assert_series_equal(result, ser)
+
+ def test_nonzero_single_element(self):
+ # allow single item via bool method
+ msg_warn = (
+ "Series.bool is now deprecated and will be removed "
+ "in future version of pandas"
+ )
+ ser = Series([True])
+ ser1 = Series([False])
+ with tm.assert_produces_warning(FutureWarning, match=msg_warn):
+ assert ser.bool()
+ with tm.assert_produces_warning(FutureWarning, match=msg_warn):
+ assert not ser1.bool()
+
+ @pytest.mark.parametrize("data", [np.nan, pd.NaT, True, False])
+ def test_nonzero_single_element_raise_1(self, data):
+ # single item nan to raise
+ series = Series([data])
+
+ msg = "The truth value of a Series is ambiguous"
+ with pytest.raises(ValueError, match=msg):
+ bool(series)
+
+ @pytest.mark.parametrize("data", [np.nan, pd.NaT])
+ def test_nonzero_single_element_raise_2(self, data):
+ msg_warn = (
+ "Series.bool is now deprecated and will be removed "
+ "in future version of pandas"
+ )
+ msg_err = "bool cannot act on a non-boolean single element Series"
+ series = Series([data])
+ with tm.assert_produces_warning(FutureWarning, match=msg_warn):
+ with pytest.raises(ValueError, match=msg_err):
+ series.bool()
+
+ @pytest.mark.parametrize("data", [(True, True), (False, False)])
+ def test_nonzero_multiple_element_raise(self, data):
+ # multiple bool are still an error
+ msg_warn = (
+ "Series.bool is now deprecated and will be removed "
+ "in future version of pandas"
+ )
+ msg_err = "The truth value of a Series is ambiguous"
+ series = Series([data])
+ with pytest.raises(ValueError, match=msg_err):
+ bool(series)
+ with tm.assert_produces_warning(FutureWarning, match=msg_warn):
+ with pytest.raises(ValueError, match=msg_err):
+ series.bool()
+
+ @pytest.mark.parametrize("data", [1, 0, "a", 0.0])
+ def test_nonbool_single_element_raise(self, data):
+ # single non-bool are an error
+ msg_warn = (
+ "Series.bool is now deprecated and will be removed "
+ "in future version of pandas"
+ )
+ msg_err1 = "The truth value of a Series is ambiguous"
+ msg_err2 = "bool cannot act on a non-boolean single element Series"
+ series = Series([data])
+ with pytest.raises(ValueError, match=msg_err1):
+ bool(series)
+ with tm.assert_produces_warning(FutureWarning, match=msg_warn):
+ with pytest.raises(ValueError, match=msg_err2):
+ series.bool()
+
+ def test_metadata_propagation_indiv_resample(self):
+ # resample
+ ts = Series(
+ np.random.default_rng(2).random(1000),
+ index=date_range("20130101", periods=1000, freq="s"),
+ name="foo",
+ )
+ result = ts.resample("1T").mean()
+ tm.assert_metadata_equivalent(ts, result)
+
+ result = ts.resample("1T").min()
+ tm.assert_metadata_equivalent(ts, result)
+
+ result = ts.resample("1T").apply(lambda x: x.sum())
+ tm.assert_metadata_equivalent(ts, result)
+
+ def test_metadata_propagation_indiv(self, monkeypatch):
+ # check that the metadata matches up on the resulting ops
+
+ ser = Series(range(3), range(3))
+ ser.name = "foo"
+ ser2 = Series(range(3), range(3))
+ ser2.name = "bar"
+
+ result = ser.T
+ tm.assert_metadata_equivalent(ser, result)
+
+ def finalize(self, other, method=None, **kwargs):
+ for name in self._metadata:
+ if method == "concat" and name == "filename":
+ value = "+".join(
+ [
+ getattr(obj, name)
+ for obj in other.objs
+ if getattr(obj, name, None)
+ ]
+ )
+ object.__setattr__(self, name, value)
+ else:
+ object.__setattr__(self, name, getattr(other, name, None))
+
+ return self
+
+ with monkeypatch.context() as m:
+ m.setattr(Series, "_metadata", ["name", "filename"])
+ m.setattr(Series, "__finalize__", finalize)
+
+ ser.filename = "foo"
+ ser2.filename = "bar"
+
+ result = pd.concat([ser, ser2])
+ assert result.filename == "foo+bar"
+ assert result.name is None
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_to_xarray.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_to_xarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6eacf4f9079bc762e44b956d98a166dcc379d76
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/generic/test_to_xarray.py
@@ -0,0 +1,126 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ Categorical,
+ DataFrame,
+ MultiIndex,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+
+pytest.importorskip("xarray")
+
+
+class TestDataFrameToXArray:
+ @pytest.fixture
+ def df(self):
+ return DataFrame(
+ {
+ "a": list("abc"),
+ "b": list(range(1, 4)),
+ "c": np.arange(3, 6).astype("u1"),
+ "d": np.arange(4.0, 7.0, dtype="float64"),
+ "e": [True, False, True],
+ "f": Categorical(list("abc")),
+ "g": date_range("20130101", periods=3),
+ "h": date_range("20130101", periods=3, tz="US/Eastern"),
+ }
+ )
+
+ def test_to_xarray_index_types(self, index_flat, df):
+ index = index_flat
+ # MultiIndex is tested in test_to_xarray_with_multiindex
+ if len(index) == 0:
+ pytest.skip("Test doesn't make sense for empty index")
+
+ from xarray import Dataset
+
+ df.index = index[:3]
+ df.index.name = "foo"
+ df.columns.name = "bar"
+ result = df.to_xarray()
+ assert result.dims["foo"] == 3
+ assert len(result.coords) == 1
+ assert len(result.data_vars) == 8
+ tm.assert_almost_equal(list(result.coords.keys()), ["foo"])
+ assert isinstance(result, Dataset)
+
+ # idempotency
+ # datetimes w/tz are preserved
+ # column names are lost
+ expected = df.copy()
+ expected["f"] = expected["f"].astype(object)
+ expected.columns.name = None
+ tm.assert_frame_equal(result.to_dataframe(), expected)
+
+ def test_to_xarray_empty(self, df):
+ from xarray import Dataset
+
+ df.index.name = "foo"
+ result = df[0:0].to_xarray()
+ assert result.dims["foo"] == 0
+ assert isinstance(result, Dataset)
+
+ def test_to_xarray_with_multiindex(self, df):
+ from xarray import Dataset
+
+ # MultiIndex
+ df.index = MultiIndex.from_product([["a"], range(3)], names=["one", "two"])
+ result = df.to_xarray()
+ assert result.dims["one"] == 1
+ assert result.dims["two"] == 3
+ assert len(result.coords) == 2
+ assert len(result.data_vars) == 8
+ tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"])
+ assert isinstance(result, Dataset)
+
+ result = result.to_dataframe()
+ expected = df.copy()
+ expected["f"] = expected["f"].astype(object)
+ expected.columns.name = None
+ tm.assert_frame_equal(result, expected)
+
+
+class TestSeriesToXArray:
+ def test_to_xarray_index_types(self, index_flat):
+ index = index_flat
+ # MultiIndex is tested in test_to_xarray_with_multiindex
+
+ from xarray import DataArray
+
+ ser = Series(range(len(index)), index=index, dtype="int64")
+ ser.index.name = "foo"
+ result = ser.to_xarray()
+ repr(result)
+ assert len(result) == len(index)
+ assert len(result.coords) == 1
+ tm.assert_almost_equal(list(result.coords.keys()), ["foo"])
+ assert isinstance(result, DataArray)
+
+ # idempotency
+ tm.assert_series_equal(result.to_series(), ser)
+
+ def test_to_xarray_empty(self):
+ from xarray import DataArray
+
+ ser = Series([], dtype=object)
+ ser.index.name = "foo"
+ result = ser.to_xarray()
+ assert len(result) == 0
+ assert len(result.coords) == 1
+ tm.assert_almost_equal(list(result.coords.keys()), ["foo"])
+ assert isinstance(result, DataArray)
+
+ def test_to_xarray_with_multiindex(self):
+ from xarray import DataArray
+
+ mi = MultiIndex.from_product([["a", "b"], range(3)], names=["one", "two"])
+ ser = Series(range(6), dtype="int64", index=mi)
+ result = ser.to_xarray()
+ assert len(result) == 2
+ tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"])
+ assert isinstance(result, DataArray)
+ res = result.to_series()
+ tm.assert_series_equal(res, ser)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..446d9da4377712b073d76dac7672dcf1de00cf04
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/__init__.py
@@ -0,0 +1,25 @@
+def get_groupby_method_args(name, obj):
+ """
+ Get required arguments for a groupby method.
+
+ When parametrizing a test over groupby methods (e.g. "sum", "mean", "fillna"),
+ it is often the case that arguments are required for certain methods.
+
+ Parameters
+ ----------
+ name: str
+ Name of the method.
+ obj: Series or DataFrame
+ pandas object that is being grouped.
+
+ Returns
+ -------
+ A tuple of required arguments for the method.
+ """
+ if name in ("nth", "fillna", "take"):
+ return (0,)
+ if name == "quantile":
+ return (0.5,)
+ if name == "corrwith":
+ return (obj,)
+ return ()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..49fa9dc51f0d35a81fa7c71268b916c2b8b39efd
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/conftest.py
@@ -0,0 +1,224 @@
+import numpy as np
+import pytest
+
+from pandas import DataFrame
+import pandas._testing as tm
+from pandas.core.groupby.base import (
+ reduction_kernels,
+ transformation_kernels,
+)
+
+
+@pytest.fixture(params=[True, False])
+def sort(request):
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def as_index(request):
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def dropna(request):
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def skipna(request):
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def observed(request):
+ return request.param
+
+
+@pytest.fixture
+def mframe(multiindex_dataframe_random_data):
+ return multiindex_dataframe_random_data
+
+
+@pytest.fixture
+def df():
+ return DataFrame(
+ {
+ "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
+ "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
+ "C": np.random.default_rng(2).standard_normal(8),
+ "D": np.random.default_rng(2).standard_normal(8),
+ }
+ )
+
+
+@pytest.fixture
+def ts():
+ return tm.makeTimeSeries()
+
+
+@pytest.fixture
+def tsd():
+ return tm.getTimeSeriesData()
+
+
+@pytest.fixture
+def tsframe(tsd):
+ return DataFrame(tsd)
+
+
+@pytest.fixture
+def df_mixed_floats():
+ return DataFrame(
+ {
+ "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
+ "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
+ "C": np.random.default_rng(2).standard_normal(8),
+ "D": np.array(np.random.default_rng(2).standard_normal(8), dtype="float32"),
+ }
+ )
+
+
+@pytest.fixture
+def three_group():
+ return DataFrame(
+ {
+ "A": [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ "foo",
+ "foo",
+ "foo",
+ ],
+ "B": [
+ "one",
+ "one",
+ "one",
+ "two",
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "two",
+ "one",
+ ],
+ "C": [
+ "dull",
+ "dull",
+ "shiny",
+ "dull",
+ "dull",
+ "shiny",
+ "shiny",
+ "dull",
+ "shiny",
+ "shiny",
+ "shiny",
+ ],
+ "D": np.random.default_rng(2).standard_normal(11),
+ "E": np.random.default_rng(2).standard_normal(11),
+ "F": np.random.default_rng(2).standard_normal(11),
+ }
+ )
+
+
+@pytest.fixture()
+def slice_test_df():
+ data = [
+ [0, "a", "a0_at_0"],
+ [1, "b", "b0_at_1"],
+ [2, "a", "a1_at_2"],
+ [3, "b", "b1_at_3"],
+ [4, "c", "c0_at_4"],
+ [5, "a", "a2_at_5"],
+ [6, "a", "a3_at_6"],
+ [7, "a", "a4_at_7"],
+ ]
+ df = DataFrame(data, columns=["Index", "Group", "Value"])
+ return df.set_index("Index")
+
+
+@pytest.fixture()
+def slice_test_grouped(slice_test_df):
+ return slice_test_df.groupby("Group", as_index=False)
+
+
+@pytest.fixture(params=sorted(reduction_kernels))
+def reduction_func(request):
+ """
+ yields the string names of all groupby reduction functions, one at a time.
+ """
+ return request.param
+
+
+@pytest.fixture(params=sorted(transformation_kernels))
+def transformation_func(request):
+ """yields the string names of all groupby transformation functions."""
+ return request.param
+
+
+@pytest.fixture(params=sorted(reduction_kernels) + sorted(transformation_kernels))
+def groupby_func(request):
+ """yields both aggregation and transformation functions."""
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def parallel(request):
+ """parallel keyword argument for numba.jit"""
+ return request.param
+
+
+# Can parameterize nogil & nopython over True | False, but limiting per
+# https://github.com/pandas-dev/pandas/pull/41971#issuecomment-860607472
+
+
+@pytest.fixture(params=[False])
+def nogil(request):
+ """nogil keyword argument for numba.jit"""
+ return request.param
+
+
+@pytest.fixture(params=[True])
+def nopython(request):
+ """nopython keyword argument for numba.jit"""
+ return request.param
+
+
+@pytest.fixture(
+ params=[
+ ("mean", {}),
+ ("var", {"ddof": 1}),
+ ("var", {"ddof": 0}),
+ ("std", {"ddof": 1}),
+ ("std", {"ddof": 0}),
+ ("sum", {}),
+ ("min", {}),
+ ("max", {}),
+ ("sum", {"min_count": 2}),
+ ("min", {"min_count": 2}),
+ ("max", {"min_count": 2}),
+ ],
+ ids=[
+ "mean",
+ "var_1",
+ "var_0",
+ "std_1",
+ "std_0",
+ "sum",
+ "min",
+ "max",
+ "sum-min_count",
+ "min-min_count",
+ "max-min_count",
+ ],
+)
+def numba_supported_reductions(request):
+ """reductions supported with engine='numba'"""
+ return request.param
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_any_all.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_any_all.py
new file mode 100644
index 0000000000000000000000000000000000000000..57a83335be849c86adcefb9188d125ee08e30a78
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_any_all.py
@@ -0,0 +1,188 @@
+import builtins
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ isna,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize("agg_func", ["any", "all"])
+@pytest.mark.parametrize(
+ "vals",
+ [
+ ["foo", "bar", "baz"],
+ ["foo", "", ""],
+ ["", "", ""],
+ [1, 2, 3],
+ [1, 0, 0],
+ [0, 0, 0],
+ [1.0, 2.0, 3.0],
+ [1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [True, True, True],
+ [True, False, False],
+ [False, False, False],
+ [np.nan, np.nan, np.nan],
+ ],
+)
+def test_groupby_bool_aggs(skipna, agg_func, vals):
+ df = DataFrame({"key": ["a"] * 3 + ["b"] * 3, "val": vals * 2})
+
+ # Figure out expectation using Python builtin
+ exp = getattr(builtins, agg_func)(vals)
+
+ # edge case for missing data with skipna and 'any'
+ if skipna and all(isna(vals)) and agg_func == "any":
+ exp = False
+
+ expected = DataFrame(
+ [exp] * 2, columns=["val"], index=Index(["a", "b"], name="key")
+ )
+ result = getattr(df.groupby("key"), agg_func)(skipna=skipna)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_any():
+ df = DataFrame(
+ [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]],
+ columns=["A", "B", "C"],
+ )
+ expected = DataFrame(
+ [[True, True], [False, True]], columns=["B", "C"], index=[1, 3]
+ )
+ expected.index.name = "A"
+ result = df.groupby("A").any()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
+def test_bool_aggs_dup_column_labels(bool_agg_func):
+ # GH#21668
+ df = DataFrame([[True, True]], columns=["a", "a"])
+ grp_by = df.groupby([0])
+ result = getattr(grp_by, bool_agg_func)()
+
+ expected = df.set_axis(np.array([0]))
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
+@pytest.mark.parametrize(
+ "data",
+ [
+ [False, False, False],
+ [True, True, True],
+ [pd.NA, pd.NA, pd.NA],
+ [False, pd.NA, False],
+ [True, pd.NA, True],
+ [True, pd.NA, False],
+ ],
+)
+def test_masked_kleene_logic(bool_agg_func, skipna, data):
+ # GH#37506
+ ser = Series(data, dtype="boolean")
+
+ # The result should match aggregating on the whole series. Correctness
+ # there is verified in test_reductions.py::test_any_all_boolean_kleene_logic
+ expected_data = getattr(ser, bool_agg_func)(skipna=skipna)
+ expected = Series(expected_data, index=np.array([0]), dtype="boolean")
+
+ result = ser.groupby([0, 0, 0]).agg(bool_agg_func, skipna=skipna)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "dtype1,dtype2,exp_col1,exp_col2",
+ [
+ (
+ "float",
+ "Float64",
+ np.array([True], dtype=bool),
+ pd.array([pd.NA], dtype="boolean"),
+ ),
+ (
+ "Int64",
+ "float",
+ pd.array([pd.NA], dtype="boolean"),
+ np.array([True], dtype=bool),
+ ),
+ (
+ "Int64",
+ "Int64",
+ pd.array([pd.NA], dtype="boolean"),
+ pd.array([pd.NA], dtype="boolean"),
+ ),
+ (
+ "Float64",
+ "boolean",
+ pd.array([pd.NA], dtype="boolean"),
+ pd.array([pd.NA], dtype="boolean"),
+ ),
+ ],
+)
+def test_masked_mixed_types(dtype1, dtype2, exp_col1, exp_col2):
+ # GH#37506
+ data = [1.0, np.nan]
+ df = DataFrame(
+ {"col1": pd.array(data, dtype=dtype1), "col2": pd.array(data, dtype=dtype2)}
+ )
+ result = df.groupby([1, 1]).agg("all", skipna=False)
+
+ expected = DataFrame({"col1": exp_col1, "col2": exp_col2}, index=np.array([1]))
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
+@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"])
+def test_masked_bool_aggs_skipna(bool_agg_func, dtype, skipna, frame_or_series):
+ # GH#40585
+ obj = frame_or_series([pd.NA, 1], dtype=dtype)
+ expected_res = True
+ if not skipna and bool_agg_func == "all":
+ expected_res = pd.NA
+ expected = frame_or_series([expected_res], index=np.array([1]), dtype="boolean")
+
+ result = obj.groupby([1, 1]).agg(bool_agg_func, skipna=skipna)
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "bool_agg_func,data,expected_res",
+ [
+ ("any", [pd.NA, np.nan], False),
+ ("any", [pd.NA, 1, np.nan], True),
+ ("all", [pd.NA, pd.NaT], True),
+ ("all", [pd.NA, False, pd.NaT], False),
+ ],
+)
+def test_object_type_missing_vals(bool_agg_func, data, expected_res, frame_or_series):
+ # GH#37501
+ obj = frame_or_series(data, dtype=object)
+ result = obj.groupby([1] * len(data)).agg(bool_agg_func)
+ expected = frame_or_series([expected_res], index=np.array([1]), dtype="bool")
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
+def test_object_NA_raises_with_skipna_false(bool_agg_func):
+ # GH#37501
+ ser = Series([pd.NA], dtype=object)
+ with pytest.raises(TypeError, match="boolean value of NA is ambiguous"):
+ ser.groupby([1]).agg(bool_agg_func, skipna=False)
+
+
+@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
+def test_empty(frame_or_series, bool_agg_func):
+ # GH 45231
+ kwargs = {"columns": ["a"]} if frame_or_series is DataFrame else {"name": "a"}
+ obj = frame_or_series(**kwargs, dtype=object)
+ result = getattr(obj.groupby(obj.index), bool_agg_func)()
+ expected = frame_or_series(**kwargs, dtype=bool)
+ tm.assert_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_api.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a030841ba3abbd343ed0a2bdf8fe6dc0343d324
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_api.py
@@ -0,0 +1,261 @@
+"""
+Tests of the groupby API, including internal consistency and with other pandas objects.
+
+Tests in this file should only check the existence, names, and arguments of groupby
+methods. It should not test the results of any groupby operation.
+"""
+
+import inspect
+
+import pytest
+
+from pandas import (
+ DataFrame,
+ Series,
+)
+from pandas.core.groupby.base import (
+ groupby_other_methods,
+ reduction_kernels,
+ transformation_kernels,
+)
+from pandas.core.groupby.generic import (
+ DataFrameGroupBy,
+ SeriesGroupBy,
+)
+
+
+def test_tab_completion(mframe):
+ grp = mframe.groupby(level="second")
+ results = {v for v in dir(grp) if not v.startswith("_")}
+ expected = {
+ "A",
+ "B",
+ "C",
+ "agg",
+ "aggregate",
+ "apply",
+ "boxplot",
+ "filter",
+ "first",
+ "get_group",
+ "groups",
+ "hist",
+ "indices",
+ "last",
+ "max",
+ "mean",
+ "median",
+ "min",
+ "ngroups",
+ "nth",
+ "ohlc",
+ "plot",
+ "prod",
+ "size",
+ "std",
+ "sum",
+ "transform",
+ "var",
+ "sem",
+ "count",
+ "nunique",
+ "head",
+ "describe",
+ "cummax",
+ "quantile",
+ "rank",
+ "cumprod",
+ "tail",
+ "resample",
+ "cummin",
+ "fillna",
+ "cumsum",
+ "cumcount",
+ "ngroup",
+ "all",
+ "shift",
+ "skew",
+ "take",
+ "pct_change",
+ "any",
+ "corr",
+ "corrwith",
+ "cov",
+ "dtypes",
+ "ndim",
+ "diff",
+ "idxmax",
+ "idxmin",
+ "ffill",
+ "bfill",
+ "rolling",
+ "expanding",
+ "pipe",
+ "sample",
+ "ewm",
+ "value_counts",
+ }
+ assert results == expected
+
+
+def test_all_methods_categorized(mframe):
+ grp = mframe.groupby(mframe.iloc[:, 0])
+ names = {_ for _ in dir(grp) if not _.startswith("_")} - set(mframe.columns)
+ new_names = set(names)
+ new_names -= reduction_kernels
+ new_names -= transformation_kernels
+ new_names -= groupby_other_methods
+
+ assert not reduction_kernels & transformation_kernels
+ assert not reduction_kernels & groupby_other_methods
+ assert not transformation_kernels & groupby_other_methods
+
+ # new public method?
+ if new_names:
+ msg = f"""
+There are uncategorized methods defined on the Grouper class:
+{new_names}.
+
+Was a new method recently added?
+
+Every public method On Grouper must appear in exactly one the
+following three lists defined in pandas.core.groupby.base:
+- `reduction_kernels`
+- `transformation_kernels`
+- `groupby_other_methods`
+see the comments in pandas/core/groupby/base.py for guidance on
+how to fix this test.
+ """
+ raise AssertionError(msg)
+
+ # removed a public method?
+ all_categorized = reduction_kernels | transformation_kernels | groupby_other_methods
+ if names != all_categorized:
+ msg = f"""
+Some methods which are supposed to be on the Grouper class
+are missing:
+{all_categorized - names}.
+
+They're still defined in one of the lists that live in pandas/core/groupby/base.py.
+If you removed a method, you should update them
+"""
+ raise AssertionError(msg)
+
+
+def test_frame_consistency(groupby_func):
+ # GH#48028
+ if groupby_func in ("first", "last"):
+ msg = "first and last are entirely different between frame and groupby"
+ pytest.skip(reason=msg)
+
+ if groupby_func in ("cumcount", "ngroup"):
+ assert not hasattr(DataFrame, groupby_func)
+ return
+
+ frame_method = getattr(DataFrame, groupby_func)
+ gb_method = getattr(DataFrameGroupBy, groupby_func)
+ result = set(inspect.signature(gb_method).parameters)
+ if groupby_func == "size":
+ # "size" is a method on GroupBy but property on DataFrame:
+ expected = {"self"}
+ else:
+ expected = set(inspect.signature(frame_method).parameters)
+
+ # Exclude certain arguments from result and expected depending on the operation
+ # Some of these may be purposeful inconsistencies between the APIs
+ exclude_expected, exclude_result = set(), set()
+ if groupby_func in ("any", "all"):
+ exclude_expected = {"kwargs", "bool_only", "axis"}
+ elif groupby_func in ("count",):
+ exclude_expected = {"numeric_only", "axis"}
+ elif groupby_func in ("nunique",):
+ exclude_expected = {"axis"}
+ elif groupby_func in ("max", "min"):
+ exclude_expected = {"axis", "kwargs", "skipna"}
+ exclude_result = {"min_count", "engine", "engine_kwargs"}
+ elif groupby_func in ("mean", "std", "sum", "var"):
+ exclude_expected = {"axis", "kwargs", "skipna"}
+ exclude_result = {"engine", "engine_kwargs"}
+ elif groupby_func in ("median", "prod", "sem"):
+ exclude_expected = {"axis", "kwargs", "skipna"}
+ elif groupby_func in ("backfill", "bfill", "ffill", "pad"):
+ exclude_expected = {"downcast", "inplace", "axis"}
+ elif groupby_func in ("cummax", "cummin"):
+ exclude_expected = {"skipna", "args"}
+ exclude_result = {"numeric_only"}
+ elif groupby_func in ("cumprod", "cumsum"):
+ exclude_expected = {"skipna"}
+ elif groupby_func in ("pct_change",):
+ exclude_expected = {"kwargs"}
+ exclude_result = {"axis"}
+ elif groupby_func in ("rank",):
+ exclude_expected = {"numeric_only"}
+ elif groupby_func in ("quantile",):
+ exclude_expected = {"method", "axis"}
+
+ # Ensure excluded arguments are actually in the signatures
+ assert result & exclude_result == exclude_result
+ assert expected & exclude_expected == exclude_expected
+
+ result -= exclude_result
+ expected -= exclude_expected
+ assert result == expected
+
+
+def test_series_consistency(request, groupby_func):
+ # GH#48028
+ if groupby_func in ("first", "last"):
+ pytest.skip("first and last are entirely different between Series and groupby")
+
+ if groupby_func in ("cumcount", "corrwith", "ngroup"):
+ assert not hasattr(Series, groupby_func)
+ return
+
+ series_method = getattr(Series, groupby_func)
+ gb_method = getattr(SeriesGroupBy, groupby_func)
+ result = set(inspect.signature(gb_method).parameters)
+ if groupby_func == "size":
+ # "size" is a method on GroupBy but property on Series
+ expected = {"self"}
+ else:
+ expected = set(inspect.signature(series_method).parameters)
+
+ # Exclude certain arguments from result and expected depending on the operation
+ # Some of these may be purposeful inconsistencies between the APIs
+ exclude_expected, exclude_result = set(), set()
+ if groupby_func in ("any", "all"):
+ exclude_expected = {"kwargs", "bool_only", "axis"}
+ elif groupby_func in ("diff",):
+ exclude_result = {"axis"}
+ elif groupby_func in ("max", "min"):
+ exclude_expected = {"axis", "kwargs", "skipna"}
+ exclude_result = {"min_count", "engine", "engine_kwargs"}
+ elif groupby_func in ("mean", "std", "sum", "var"):
+ exclude_expected = {"axis", "kwargs", "skipna"}
+ exclude_result = {"engine", "engine_kwargs"}
+ elif groupby_func in ("median", "prod", "sem"):
+ exclude_expected = {"axis", "kwargs", "skipna"}
+ elif groupby_func in ("backfill", "bfill", "ffill", "pad"):
+ exclude_expected = {"downcast", "inplace", "axis"}
+ elif groupby_func in ("cummax", "cummin"):
+ exclude_expected = {"skipna", "args"}
+ exclude_result = {"numeric_only"}
+ elif groupby_func in ("cumprod", "cumsum"):
+ exclude_expected = {"skipna"}
+ elif groupby_func in ("pct_change",):
+ exclude_expected = {"kwargs"}
+ exclude_result = {"axis"}
+ elif groupby_func in ("rank",):
+ exclude_expected = {"numeric_only"}
+ elif groupby_func in ("idxmin", "idxmax"):
+ exclude_expected = {"args", "kwargs"}
+ elif groupby_func in ("quantile",):
+ exclude_result = {"numeric_only"}
+
+ # Ensure excluded arguments are actually in the signatures
+ assert result & exclude_result == exclude_result
+ assert expected & exclude_expected == exclude_expected
+
+ result -= exclude_result
+ expected -= exclude_expected
+ assert result == expected
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_apply.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_apply.py
new file mode 100644
index 0000000000000000000000000000000000000000..d04ee7cec0db1932ef1bd14ff66cf509bba673c9
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_apply.py
@@ -0,0 +1,1422 @@
+from datetime import (
+ date,
+ datetime,
+)
+from io import StringIO
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ bdate_range,
+)
+import pandas._testing as tm
+from pandas.tests.groupby import get_groupby_method_args
+
+
+def test_apply_func_that_appends_group_to_list_without_copy():
+ # GH: 17718
+
+ df = DataFrame(1, index=list(range(10)) * 10, columns=[0]).reset_index()
+ groups = []
+
+ def store(group):
+ groups.append(group)
+
+ df.groupby("index").apply(store)
+ expected_value = DataFrame(
+ {"index": [0] * 10, 0: [1] * 10}, index=pd.RangeIndex(0, 100, 10)
+ )
+
+ tm.assert_frame_equal(groups[0], expected_value)
+
+
+def test_apply_issues():
+ # GH 5788
+
+ s = """2011.05.16,00:00,1.40893
+2011.05.16,01:00,1.40760
+2011.05.16,02:00,1.40750
+2011.05.16,03:00,1.40649
+2011.05.17,02:00,1.40893
+2011.05.17,03:00,1.40760
+2011.05.17,04:00,1.40750
+2011.05.17,05:00,1.40649
+2011.05.18,02:00,1.40893
+2011.05.18,03:00,1.40760
+2011.05.18,04:00,1.40750
+2011.05.18,05:00,1.40649"""
+
+ df = pd.read_csv(
+ StringIO(s),
+ header=None,
+ names=["date", "time", "value"],
+ parse_dates=[["date", "time"]],
+ )
+ df = df.set_index("date_time")
+
+ expected = df.groupby(df.index.date).idxmax()
+ result = df.groupby(df.index.date).apply(lambda x: x.idxmax())
+ tm.assert_frame_equal(result, expected)
+
+ # GH 5789
+ # don't auto coerce dates
+ df = pd.read_csv(StringIO(s), header=None, names=["date", "time", "value"])
+ exp_idx = Index(
+ ["2011.05.16", "2011.05.17", "2011.05.18"], dtype=object, name="date"
+ )
+ expected = Series(["00:00", "02:00", "02:00"], index=exp_idx)
+ result = df.groupby("date", group_keys=False).apply(
+ lambda x: x["time"][x["value"].idxmax()]
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_trivial():
+ # GH 20066
+ # trivial apply: ignore input and return a constant dataframe.
+ df = DataFrame(
+ {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]},
+ columns=["key", "data"],
+ )
+ expected = pd.concat([df.iloc[1:], df.iloc[1:]], axis=1, keys=["float64", "object"])
+
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby([str(x) for x in df.dtypes], axis=1)
+ result = gb.apply(lambda x: df.iloc[1:])
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_trivial_fail():
+ # GH 20066
+ df = DataFrame(
+ {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]},
+ columns=["key", "data"],
+ )
+ expected = pd.concat([df, df], axis=1, keys=["float64", "object"])
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby([str(x) for x in df.dtypes], axis=1, group_keys=True)
+ result = gb.apply(lambda x: df)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "df, group_names",
+ [
+ (DataFrame({"a": [1, 1, 1, 2, 3], "b": ["a", "a", "a", "b", "c"]}), [1, 2, 3]),
+ (DataFrame({"a": [0, 0, 1, 1], "b": [0, 1, 0, 1]}), [0, 1]),
+ (DataFrame({"a": [1]}), [1]),
+ (DataFrame({"a": [1, 1, 1, 2, 2, 1, 1, 2], "b": range(8)}), [1, 2]),
+ (DataFrame({"a": [1, 2, 3, 1, 2, 3], "two": [4, 5, 6, 7, 8, 9]}), [1, 2, 3]),
+ (
+ DataFrame(
+ {
+ "a": list("aaabbbcccc"),
+ "B": [3, 4, 3, 6, 5, 2, 1, 9, 5, 4],
+ "C": [4, 0, 2, 2, 2, 7, 8, 6, 2, 8],
+ }
+ ),
+ ["a", "b", "c"],
+ ),
+ (DataFrame([[1, 2, 3], [2, 2, 3]], columns=["a", "b", "c"]), [1, 2]),
+ ],
+ ids=[
+ "GH2936",
+ "GH7739 & GH10519",
+ "GH10519",
+ "GH2656",
+ "GH12155",
+ "GH20084",
+ "GH21417",
+ ],
+)
+def test_group_apply_once_per_group(df, group_names):
+ # GH2936, GH7739, GH10519, GH2656, GH12155, GH20084, GH21417
+
+ # This test should ensure that a function is only evaluated
+ # once per group. Previously the function has been evaluated twice
+ # on the first group to check if the Cython index slider is safe to use
+ # This test ensures that the side effect (append to list) is only triggered
+ # once per group
+
+ names = []
+ # cannot parameterize over the functions since they need external
+ # `names` to detect side effects
+
+ def f_copy(group):
+ # this takes the fast apply path
+ names.append(group.name)
+ return group.copy()
+
+ def f_nocopy(group):
+ # this takes the slow apply path
+ names.append(group.name)
+ return group
+
+ def f_scalar(group):
+ # GH7739, GH2656
+ names.append(group.name)
+ return 0
+
+ def f_none(group):
+ # GH10519, GH12155, GH21417
+ names.append(group.name)
+
+ def f_constant_df(group):
+ # GH2936, GH20084
+ names.append(group.name)
+ return DataFrame({"a": [1], "b": [1]})
+
+ for func in [f_copy, f_nocopy, f_scalar, f_none, f_constant_df]:
+ del names[:]
+
+ df.groupby("a", group_keys=False).apply(func)
+ assert names == group_names
+
+
+def test_group_apply_once_per_group2(capsys):
+ # GH: 31111
+ # groupby-apply need to execute len(set(group_by_columns)) times
+
+ expected = 2 # Number of times `apply` should call a function for the current test
+
+ df = DataFrame(
+ {
+ "group_by_column": [0, 0, 0, 0, 1, 1, 1, 1],
+ "test_column": ["0", "2", "4", "6", "8", "10", "12", "14"],
+ },
+ index=["0", "2", "4", "6", "8", "10", "12", "14"],
+ )
+
+ df.groupby("group_by_column", group_keys=False).apply(
+ lambda df: print("function_called")
+ )
+
+ result = capsys.readouterr().out.count("function_called")
+ # If `groupby` behaves unexpectedly, this test will break
+ assert result == expected
+
+
+def test_apply_fast_slow_identical():
+ # GH 31613
+
+ df = DataFrame({"A": [0, 0, 1], "b": range(3)})
+
+ # For simple index structures we check for fast/slow apply using
+ # an identity check on in/output
+ def slow(group):
+ return group
+
+ def fast(group):
+ return group.copy()
+
+ fast_df = df.groupby("A", group_keys=False).apply(fast)
+ slow_df = df.groupby("A", group_keys=False).apply(slow)
+
+ tm.assert_frame_equal(fast_df, slow_df)
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ lambda x: x,
+ lambda x: x[:],
+ lambda x: x.copy(deep=False),
+ lambda x: x.copy(deep=True),
+ ],
+)
+def test_groupby_apply_identity_maybecopy_index_identical(func):
+ # GH 14927
+ # Whether the function returns a copy of the input data or not should not
+ # have an impact on the index structure of the result since this is not
+ # transparent to the user
+
+ df = DataFrame({"g": [1, 2, 2, 2], "a": [1, 2, 3, 4], "b": [5, 6, 7, 8]})
+
+ result = df.groupby("g", group_keys=False).apply(func)
+ tm.assert_frame_equal(result, df)
+
+
+def test_apply_with_mixed_dtype():
+ # GH3480, apply with mixed dtype on axis=1 breaks in 0.11
+ df = DataFrame(
+ {
+ "foo1": np.random.default_rng(2).standard_normal(6),
+ "foo2": ["one", "two", "two", "three", "one", "two"],
+ }
+ )
+ result = df.apply(lambda x: x, axis=1).dtypes
+ expected = df.dtypes
+ tm.assert_series_equal(result, expected)
+
+ # GH 3610 incorrect dtype conversion with as_index=False
+ df = DataFrame({"c1": [1, 2, 6, 6, 8]})
+ df["c2"] = df.c1 / 2.0
+ result1 = df.groupby("c2").mean().reset_index().c2
+ result2 = df.groupby("c2", as_index=False).mean().c2
+ tm.assert_series_equal(result1, result2)
+
+
+def test_groupby_as_index_apply():
+ # GH #4648 and #3417
+ df = DataFrame(
+ {
+ "item_id": ["b", "b", "a", "c", "a", "b"],
+ "user_id": [1, 2, 1, 1, 3, 1],
+ "time": range(6),
+ }
+ )
+
+ g_as = df.groupby("user_id", as_index=True)
+ g_not_as = df.groupby("user_id", as_index=False)
+
+ res_as = g_as.head(2).index
+ res_not_as = g_not_as.head(2).index
+ exp = Index([0, 1, 2, 4])
+ tm.assert_index_equal(res_as, exp)
+ tm.assert_index_equal(res_not_as, exp)
+
+ res_as_apply = g_as.apply(lambda x: x.head(2)).index
+ res_not_as_apply = g_not_as.apply(lambda x: x.head(2)).index
+
+ # apply doesn't maintain the original ordering
+ # changed in GH5610 as the as_index=False returns a MI here
+ exp_not_as_apply = MultiIndex.from_tuples([(0, 0), (0, 2), (1, 1), (2, 4)])
+ tp = [(1, 0), (1, 2), (2, 1), (3, 4)]
+ exp_as_apply = MultiIndex.from_tuples(tp, names=["user_id", None])
+
+ tm.assert_index_equal(res_as_apply, exp_as_apply)
+ tm.assert_index_equal(res_not_as_apply, exp_not_as_apply)
+
+ ind = Index(list("abcde"))
+ df = DataFrame([[1, 2], [2, 3], [1, 4], [1, 5], [2, 6]], index=ind)
+ res = df.groupby(0, as_index=False, group_keys=False).apply(lambda x: x).index
+ tm.assert_index_equal(res, ind)
+
+
+def test_apply_concat_preserve_names(three_group):
+ grouped = three_group.groupby(["A", "B"])
+
+ def desc(group):
+ result = group.describe()
+ result.index.name = "stat"
+ return result
+
+ def desc2(group):
+ result = group.describe()
+ result.index.name = "stat"
+ result = result[: len(group)]
+ # weirdo
+ return result
+
+ def desc3(group):
+ result = group.describe()
+
+ # names are different
+ result.index.name = f"stat_{len(group):d}"
+
+ result = result[: len(group)]
+ # weirdo
+ return result
+
+ result = grouped.apply(desc)
+ assert result.index.names == ("A", "B", "stat")
+
+ result2 = grouped.apply(desc2)
+ assert result2.index.names == ("A", "B", "stat")
+
+ result3 = grouped.apply(desc3)
+ assert result3.index.names == ("A", "B", None)
+
+
+def test_apply_series_to_frame():
+ def f(piece):
+ with np.errstate(invalid="ignore"):
+ logged = np.log(piece)
+ return DataFrame(
+ {"value": piece, "demeaned": piece - piece.mean(), "logged": logged}
+ )
+
+ dr = bdate_range("1/1/2000", periods=100)
+ ts = Series(np.random.default_rng(2).standard_normal(100), index=dr)
+
+ grouped = ts.groupby(lambda x: x.month, group_keys=False)
+ result = grouped.apply(f)
+
+ assert isinstance(result, DataFrame)
+ assert not hasattr(result, "name") # GH49907
+ tm.assert_index_equal(result.index, ts.index)
+
+
+def test_apply_series_yield_constant(df):
+ result = df.groupby(["A", "B"])["C"].apply(len)
+ assert result.index.names[:2] == ("A", "B")
+
+
+def test_apply_frame_yield_constant(df):
+ # GH13568
+ result = df.groupby(["A", "B"]).apply(len)
+ assert isinstance(result, Series)
+ assert result.name is None
+
+ result = df.groupby(["A", "B"])[["C", "D"]].apply(len)
+ assert isinstance(result, Series)
+ assert result.name is None
+
+
+def test_apply_frame_to_series(df):
+ grouped = df.groupby(["A", "B"])
+ result = grouped.apply(len)
+ expected = grouped.count()["C"]
+ tm.assert_index_equal(result.index, expected.index)
+ tm.assert_numpy_array_equal(result.values, expected.values)
+
+
+def test_apply_frame_not_as_index_column_name(df):
+ # GH 35964 - path within _wrap_applied_output not hit by a test
+ grouped = df.groupby(["A", "B"], as_index=False)
+ result = grouped.apply(len)
+ expected = grouped.count().rename(columns={"C": np.nan}).drop(columns="D")
+ # TODO(GH#34306): Use assert_frame_equal when column name is not np.nan
+ tm.assert_index_equal(result.index, expected.index)
+ tm.assert_numpy_array_equal(result.values, expected.values)
+
+
+def test_apply_frame_concat_series():
+ def trans(group):
+ return group.groupby("B")["C"].sum().sort_values().iloc[:2]
+
+ def trans2(group):
+ grouped = group.groupby(df.reindex(group.index)["B"])
+ return grouped.sum().sort_values().iloc[:2]
+
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).integers(0, 5, 1000),
+ "B": np.random.default_rng(2).integers(0, 5, 1000),
+ "C": np.random.default_rng(2).standard_normal(1000),
+ }
+ )
+
+ result = df.groupby("A").apply(trans)
+ exp = df.groupby("A")["C"].apply(trans2)
+ tm.assert_series_equal(result, exp, check_names=False)
+ assert result.name == "C"
+
+
+def test_apply_transform(ts):
+ grouped = ts.groupby(lambda x: x.month, group_keys=False)
+ result = grouped.apply(lambda x: x * 2)
+ expected = grouped.transform(lambda x: x * 2)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_multikey_corner(tsframe):
+ grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month])
+
+ def f(group):
+ return group.sort_values("A")[-5:]
+
+ result = grouped.apply(f)
+ for key, group in grouped:
+ tm.assert_frame_equal(result.loc[key], f(group))
+
+
+@pytest.mark.parametrize("group_keys", [True, False])
+def test_apply_chunk_view(group_keys):
+ # Low level tinkering could be unsafe, make sure not
+ df = DataFrame({"key": [1, 1, 1, 2, 2, 2, 3, 3, 3], "value": range(9)})
+
+ result = df.groupby("key", group_keys=group_keys).apply(lambda x: x.iloc[:2])
+ expected = df.take([0, 1, 3, 4, 6, 7])
+ if group_keys:
+ expected.index = MultiIndex.from_arrays(
+ [[1, 1, 2, 2, 3, 3], expected.index], names=["key", None]
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_no_name_column_conflict():
+ df = DataFrame(
+ {
+ "name": [1, 1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "name2": [0, 0, 0, 1, 1, 1, 0, 0, 1, 1],
+ "value": range(9, -1, -1),
+ }
+ )
+
+ # it works! #2605
+ grouped = df.groupby(["name", "name2"])
+ grouped.apply(lambda x: x.sort_values("value", inplace=True))
+
+
+def test_apply_typecast_fail():
+ df = DataFrame(
+ {
+ "d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0],
+ "c": np.tile(["a", "b", "c"], 2),
+ "v": np.arange(1.0, 7.0),
+ }
+ )
+
+ def f(group):
+ v = group["v"]
+ group["v2"] = (v - v.min()) / (v.max() - v.min())
+ return group
+
+ result = df.groupby("d", group_keys=False).apply(f)
+
+ expected = df.copy()
+ expected["v2"] = np.tile([0.0, 0.5, 1], 2)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_multiindex_fail():
+ index = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1], [1, 2, 3, 1, 2, 3]])
+ df = DataFrame(
+ {
+ "d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0],
+ "c": np.tile(["a", "b", "c"], 2),
+ "v": np.arange(1.0, 7.0),
+ },
+ index=index,
+ )
+
+ def f(group):
+ v = group["v"]
+ group["v2"] = (v - v.min()) / (v.max() - v.min())
+ return group
+
+ result = df.groupby("d", group_keys=False).apply(f)
+
+ expected = df.copy()
+ expected["v2"] = np.tile([0.0, 0.5, 1], 2)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_corner(tsframe):
+ result = tsframe.groupby(lambda x: x.year, group_keys=False).apply(lambda x: x * 2)
+ expected = tsframe * 2
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_without_copy():
+ # GH 5545
+ # returning a non-copy in an applied function fails
+
+ data = DataFrame(
+ {
+ "id_field": [100, 100, 200, 300],
+ "category": ["a", "b", "c", "c"],
+ "value": [1, 2, 3, 4],
+ }
+ )
+
+ def filt1(x):
+ if x.shape[0] == 1:
+ return x.copy()
+ else:
+ return x[x.category == "c"]
+
+ def filt2(x):
+ if x.shape[0] == 1:
+ return x
+ else:
+ return x[x.category == "c"]
+
+ expected = data.groupby("id_field").apply(filt1)
+ result = data.groupby("id_field").apply(filt2)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("test_series", [True, False])
+def test_apply_with_duplicated_non_sorted_axis(test_series):
+ # GH 30667
+ df = DataFrame(
+ [["x", "p"], ["x", "p"], ["x", "o"]], columns=["X", "Y"], index=[1, 2, 2]
+ )
+ if test_series:
+ ser = df.set_index("Y")["X"]
+ result = ser.groupby(level=0, group_keys=False).apply(lambda x: x)
+
+ # not expecting the order to remain the same for duplicated axis
+ result = result.sort_index()
+ expected = ser.sort_index()
+ tm.assert_series_equal(result, expected)
+ else:
+ result = df.groupby("Y", group_keys=False).apply(lambda x: x)
+
+ # not expecting the order to remain the same for duplicated axis
+ result = result.sort_values("Y")
+ expected = df.sort_values("Y")
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_reindex_values():
+ # GH: 26209
+ # reindexing from a single column of a groupby object with duplicate indices caused
+ # a ValueError (cannot reindex from duplicate axis) in 0.24.2, the problem was
+ # solved in #30679
+ values = [1, 2, 3, 4]
+ indices = [1, 1, 2, 2]
+ df = DataFrame({"group": ["Group1", "Group2"] * 2, "value": values}, index=indices)
+ expected = Series(values, index=indices, name="value")
+
+ def reindex_helper(x):
+ return x.reindex(np.arange(x.index.min(), x.index.max() + 1))
+
+ # the following group by raised a ValueError
+ result = df.groupby("group", group_keys=False).value.apply(reindex_helper)
+ tm.assert_series_equal(expected, result)
+
+
+def test_apply_corner_cases():
+ # #535, can't use sliding iterator
+
+ N = 1000
+ labels = np.random.default_rng(2).integers(0, 100, size=N)
+ df = DataFrame(
+ {
+ "key": labels,
+ "value1": np.random.default_rng(2).standard_normal(N),
+ "value2": ["foo", "bar", "baz", "qux"] * (N // 4),
+ }
+ )
+
+ grouped = df.groupby("key", group_keys=False)
+
+ def f(g):
+ g["value3"] = g["value1"] * 2
+ return g
+
+ result = grouped.apply(f)
+ assert "value3" in result
+
+
+def test_apply_numeric_coercion_when_datetime():
+ # In the past, group-by/apply operations have been over-eager
+ # in converting dtypes to numeric, in the presence of datetime
+ # columns. Various GH issues were filed, the reproductions
+ # for which are here.
+
+ # GH 15670
+ df = DataFrame(
+ {"Number": [1, 2], "Date": ["2017-03-02"] * 2, "Str": ["foo", "inf"]}
+ )
+ expected = df.groupby(["Number"]).apply(lambda x: x.iloc[0])
+ df.Date = pd.to_datetime(df.Date)
+ result = df.groupby(["Number"]).apply(lambda x: x.iloc[0])
+ tm.assert_series_equal(result["Str"], expected["Str"])
+
+ # GH 15421
+ df = DataFrame(
+ {"A": [10, 20, 30], "B": ["foo", "3", "4"], "T": [pd.Timestamp("12:31:22")] * 3}
+ )
+
+ def get_B(g):
+ return g.iloc[0][["B"]]
+
+ result = df.groupby("A").apply(get_B)["B"]
+ expected = df.B
+ expected.index = df.A
+ tm.assert_series_equal(result, expected)
+
+ # GH 14423
+ def predictions(tool):
+ out = Series(index=["p1", "p2", "useTime"], dtype=object)
+ if "step1" in list(tool.State):
+ out["p1"] = str(tool[tool.State == "step1"].Machine.values[0])
+ if "step2" in list(tool.State):
+ out["p2"] = str(tool[tool.State == "step2"].Machine.values[0])
+ out["useTime"] = str(tool[tool.State == "step2"].oTime.values[0])
+ return out
+
+ df1 = DataFrame(
+ {
+ "Key": ["B", "B", "A", "A"],
+ "State": ["step1", "step2", "step1", "step2"],
+ "oTime": ["", "2016-09-19 05:24:33", "", "2016-09-19 23:59:04"],
+ "Machine": ["23", "36L", "36R", "36R"],
+ }
+ )
+ df2 = df1.copy()
+ df2.oTime = pd.to_datetime(df2.oTime)
+ expected = df1.groupby("Key").apply(predictions).p1
+ result = df2.groupby("Key").apply(predictions).p1
+ tm.assert_series_equal(expected, result)
+
+
+def test_apply_aggregating_timedelta_and_datetime():
+ # Regression test for GH 15562
+ # The following groupby caused ValueErrors and IndexErrors pre 0.20.0
+
+ df = DataFrame(
+ {
+ "clientid": ["A", "B", "C"],
+ "datetime": [np.datetime64("2017-02-01 00:00:00")] * 3,
+ }
+ )
+ df["time_delta_zero"] = df.datetime - df.datetime
+ result = df.groupby("clientid").apply(
+ lambda ddf: Series(
+ {"clientid_age": ddf.time_delta_zero.min(), "date": ddf.datetime.min()}
+ )
+ )
+ expected = DataFrame(
+ {
+ "clientid": ["A", "B", "C"],
+ "clientid_age": [np.timedelta64(0, "D")] * 3,
+ "date": [np.datetime64("2017-02-01 00:00:00")] * 3,
+ }
+ ).set_index("clientid")
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_groupby_datetimeindex():
+ # GH 26182
+ # groupby apply failed on dataframe with DatetimeIndex
+
+ data = [["A", 10], ["B", 20], ["B", 30], ["C", 40], ["C", 50]]
+ df = DataFrame(
+ data, columns=["Name", "Value"], index=pd.date_range("2020-09-01", "2020-09-05")
+ )
+
+ result = df.groupby("Name").sum()
+
+ expected = DataFrame({"Name": ["A", "B", "C"], "Value": [10, 50, 90]})
+ expected.set_index("Name", inplace=True)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_time_field_bug():
+ # Test a fix for the following error related to GH issue 11324 When
+ # non-key fields in a group-by dataframe contained time-based fields
+ # that were not returned by the apply function, an exception would be
+ # raised.
+
+ df = DataFrame({"a": 1, "b": [datetime.now() for nn in range(10)]})
+
+ def func_with_no_date(batch):
+ return Series({"c": 2})
+
+ def func_with_date(batch):
+ return Series({"b": datetime(2015, 1, 1), "c": 2})
+
+ dfg_no_conversion = df.groupby(by=["a"]).apply(func_with_no_date)
+ dfg_no_conversion_expected = DataFrame({"c": 2}, index=[1])
+ dfg_no_conversion_expected.index.name = "a"
+
+ dfg_conversion = df.groupby(by=["a"]).apply(func_with_date)
+ dfg_conversion_expected = DataFrame(
+ {"b": pd.Timestamp(2015, 1, 1).as_unit("ns"), "c": 2}, index=[1]
+ )
+ dfg_conversion_expected.index.name = "a"
+
+ tm.assert_frame_equal(dfg_no_conversion, dfg_no_conversion_expected)
+ tm.assert_frame_equal(dfg_conversion, dfg_conversion_expected)
+
+
+def test_gb_apply_list_of_unequal_len_arrays():
+ # GH1738
+ df = DataFrame(
+ {
+ "group1": ["a", "a", "a", "b", "b", "b", "a", "a", "a", "b", "b", "b"],
+ "group2": ["c", "c", "d", "d", "d", "e", "c", "c", "d", "d", "d", "e"],
+ "weight": [1.1, 2, 3, 4, 5, 6, 2, 4, 6, 8, 1, 2],
+ "value": [7.1, 8, 9, 10, 11, 12, 8, 7, 6, 5, 4, 3],
+ }
+ )
+ df = df.set_index(["group1", "group2"])
+ df_grouped = df.groupby(level=["group1", "group2"], sort=True)
+
+ def noddy(value, weight):
+ out = np.array(value * weight).repeat(3)
+ return out
+
+ # the kernel function returns arrays of unequal length
+ # pandas sniffs the first one, sees it's an array and not
+ # a list, and assumed the rest are of equal length
+ # and so tries a vstack
+
+ # don't die
+ df_grouped.apply(lambda x: noddy(x.value, x.weight))
+
+
+def test_groupby_apply_all_none():
+ # Tests to make sure no errors if apply function returns all None
+ # values. Issue 9684.
+ test_df = DataFrame({"groups": [0, 0, 1, 1], "random_vars": [8, 7, 4, 5]})
+
+ def test_func(x):
+ pass
+
+ result = test_df.groupby("groups").apply(test_func)
+ expected = DataFrame()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_apply_none_first():
+ # GH 12824. Tests if apply returns None first.
+ test_df1 = DataFrame({"groups": [1, 1, 1, 2], "vars": [0, 1, 2, 3]})
+ test_df2 = DataFrame({"groups": [1, 2, 2, 2], "vars": [0, 1, 2, 3]})
+
+ def test_func(x):
+ if x.shape[0] < 2:
+ return None
+ return x.iloc[[0, -1]]
+
+ result1 = test_df1.groupby("groups").apply(test_func)
+ result2 = test_df2.groupby("groups").apply(test_func)
+ index1 = MultiIndex.from_arrays([[1, 1], [0, 2]], names=["groups", None])
+ index2 = MultiIndex.from_arrays([[2, 2], [1, 3]], names=["groups", None])
+ expected1 = DataFrame({"groups": [1, 1], "vars": [0, 2]}, index=index1)
+ expected2 = DataFrame({"groups": [2, 2], "vars": [1, 3]}, index=index2)
+ tm.assert_frame_equal(result1, expected1)
+ tm.assert_frame_equal(result2, expected2)
+
+
+def test_groupby_apply_return_empty_chunk():
+ # GH 22221: apply filter which returns some empty groups
+ df = DataFrame({"value": [0, 1], "group": ["filled", "empty"]})
+ groups = df.groupby("group")
+ result = groups.apply(lambda group: group[group.value != 1]["value"])
+ expected = Series(
+ [0],
+ name="value",
+ index=MultiIndex.from_product(
+ [["empty", "filled"], [0]], names=["group", None]
+ ).drop("empty"),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_with_mixed_types():
+ # gh-20949
+ df = DataFrame({"A": "a a b".split(), "B": [1, 2, 3], "C": [4, 6, 5]})
+ g = df.groupby("A", group_keys=False)
+
+ result = g.transform(lambda x: x / x.sum())
+ expected = DataFrame({"B": [1 / 3.0, 2 / 3.0, 1], "C": [0.4, 0.6, 1.0]})
+ tm.assert_frame_equal(result, expected)
+
+ result = g.apply(lambda x: x / x.sum())
+ tm.assert_frame_equal(result, expected)
+
+
+def test_func_returns_object():
+ # GH 28652
+ df = DataFrame({"a": [1, 2]}, index=Index([1, 2]))
+ result = df.groupby("a").apply(lambda g: g.index)
+ expected = Series([Index([1]), Index([2])], index=Index([1, 2], name="a"))
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "group_column_dtlike",
+ [datetime.today(), datetime.today().date(), datetime.today().time()],
+)
+def test_apply_datetime_issue(group_column_dtlike):
+ # GH-28247
+ # groupby-apply throws an error if one of the columns in the DataFrame
+ # is a datetime object and the column labels are different from
+ # standard int values in range(len(num_columns))
+
+ df = DataFrame({"a": ["foo"], "b": [group_column_dtlike]})
+ result = df.groupby("a").apply(lambda x: Series(["spam"], index=[42]))
+
+ expected = DataFrame(
+ ["spam"], Index(["foo"], dtype="object", name="a"), columns=[42]
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_series_return_dataframe_groups():
+ # GH 10078
+ tdf = DataFrame(
+ {
+ "day": {
+ 0: pd.Timestamp("2015-02-24 00:00:00"),
+ 1: pd.Timestamp("2015-02-24 00:00:00"),
+ 2: pd.Timestamp("2015-02-24 00:00:00"),
+ 3: pd.Timestamp("2015-02-24 00:00:00"),
+ 4: pd.Timestamp("2015-02-24 00:00:00"),
+ },
+ "userAgent": {
+ 0: "some UA string",
+ 1: "some UA string",
+ 2: "some UA string",
+ 3: "another UA string",
+ 4: "some UA string",
+ },
+ "userId": {
+ 0: "17661101",
+ 1: "17661101",
+ 2: "17661101",
+ 3: "17661101",
+ 4: "17661101",
+ },
+ }
+ )
+
+ def most_common_values(df):
+ return Series({c: s.value_counts().index[0] for c, s in df.items()})
+
+ result = tdf.groupby("day").apply(most_common_values)["userId"]
+ expected = Series(
+ ["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId"
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("category", [False, True])
+def test_apply_multi_level_name(category):
+ # https://github.com/pandas-dev/pandas/issues/31068
+ b = [1, 2] * 5
+ if category:
+ b = pd.Categorical(b, categories=[1, 2, 3])
+ expected_index = pd.CategoricalIndex([1, 2, 3], categories=[1, 2, 3], name="B")
+ expected_values = [20, 25, 0]
+ else:
+ expected_index = Index([1, 2], name="B")
+ expected_values = [20, 25]
+ expected = DataFrame(
+ {"C": expected_values, "D": expected_values}, index=expected_index
+ )
+
+ df = DataFrame(
+ {"A": np.arange(10), "B": b, "C": list(range(10)), "D": list(range(10))}
+ ).set_index(["A", "B"])
+ result = df.groupby("B", observed=False).apply(lambda x: x.sum())
+ tm.assert_frame_equal(result, expected)
+ assert df.index.names == ["A", "B"]
+
+
+def test_groupby_apply_datetime_result_dtypes():
+ # GH 14849
+ data = DataFrame.from_records(
+ [
+ (pd.Timestamp(2016, 1, 1), "red", "dark", 1, "8"),
+ (pd.Timestamp(2015, 1, 1), "green", "stormy", 2, "9"),
+ (pd.Timestamp(2014, 1, 1), "blue", "bright", 3, "10"),
+ (pd.Timestamp(2013, 1, 1), "blue", "calm", 4, "potato"),
+ ],
+ columns=["observation", "color", "mood", "intensity", "score"],
+ )
+ result = data.groupby("color").apply(lambda g: g.iloc[0]).dtypes
+ expected = Series(
+ [np.dtype("datetime64[ns]"), object, object, np.int64, object],
+ index=["observation", "color", "mood", "intensity", "score"],
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "index",
+ [
+ pd.CategoricalIndex(list("abc")),
+ pd.interval_range(0, 3),
+ pd.period_range("2020", periods=3, freq="D"),
+ MultiIndex.from_tuples([("a", 0), ("a", 1), ("b", 0)]),
+ ],
+)
+def test_apply_index_has_complex_internals(index):
+ # GH 31248
+ df = DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index)
+ result = df.groupby("group", group_keys=False).apply(lambda x: x)
+ tm.assert_frame_equal(result, df)
+
+
+@pytest.mark.parametrize(
+ "function, expected_values",
+ [
+ (lambda x: x.index.to_list(), [[0, 1], [2, 3]]),
+ (lambda x: set(x.index.to_list()), [{0, 1}, {2, 3}]),
+ (lambda x: tuple(x.index.to_list()), [(0, 1), (2, 3)]),
+ (
+ lambda x: dict(enumerate(x.index.to_list())),
+ [{0: 0, 1: 1}, {0: 2, 1: 3}],
+ ),
+ (
+ lambda x: [{n: i} for (n, i) in enumerate(x.index.to_list())],
+ [[{0: 0}, {1: 1}], [{0: 2}, {1: 3}]],
+ ),
+ ],
+)
+def test_apply_function_returns_non_pandas_non_scalar(function, expected_values):
+ # GH 31441
+ df = DataFrame(["A", "A", "B", "B"], columns=["groups"])
+ result = df.groupby("groups").apply(function)
+ expected = Series(expected_values, index=Index(["A", "B"], name="groups"))
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_function_returns_numpy_array():
+ # GH 31605
+ def fct(group):
+ return group["B"].values.flatten()
+
+ df = DataFrame({"A": ["a", "a", "b", "none"], "B": [1, 2, 3, np.nan]})
+
+ result = df.groupby("A").apply(fct)
+ expected = Series(
+ [[1.0, 2.0], [3.0], [np.nan]], index=Index(["a", "b", "none"], name="A")
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("function", [lambda gr: gr.index, lambda gr: gr.index + 1 - 1])
+def test_apply_function_index_return(function):
+ # GH: 22541
+ df = DataFrame([1, 2, 2, 2, 1, 2, 3, 1, 3, 1], columns=["id"])
+ result = df.groupby("id").apply(function)
+ expected = Series(
+ [Index([0, 4, 7, 9]), Index([1, 2, 3, 5]), Index([6, 8])],
+ index=Index([1, 2, 3], name="id"),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_function_with_indexing_return_column():
+ # GH#7002, GH#41480, GH#49256
+ df = DataFrame(
+ {
+ "foo1": ["one", "two", "two", "three", "one", "two"],
+ "foo2": [1, 2, 4, 4, 5, 6],
+ }
+ )
+ result = df.groupby("foo1", as_index=False).apply(lambda x: x.mean())
+ expected = DataFrame(
+ {
+ "foo1": ["one", "three", "two"],
+ "foo2": [3.0, 4.0, 4.0],
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "udf",
+ [(lambda x: x.copy()), (lambda x: x.copy().rename(lambda y: y + 1))],
+)
+@pytest.mark.parametrize("group_keys", [True, False])
+def test_apply_result_type(group_keys, udf):
+ # https://github.com/pandas-dev/pandas/issues/34809
+ # We'd like to control whether the group keys end up in the index
+ # regardless of whether the UDF happens to be a transform.
+ df = DataFrame({"A": ["a", "b"], "B": [1, 2]})
+ df_result = df.groupby("A", group_keys=group_keys).apply(udf)
+ series_result = df.B.groupby(df.A, group_keys=group_keys).apply(udf)
+
+ if group_keys:
+ assert df_result.index.nlevels == 2
+ assert series_result.index.nlevels == 2
+ else:
+ assert df_result.index.nlevels == 1
+ assert series_result.index.nlevels == 1
+
+
+def test_result_order_group_keys_false():
+ # GH 34998
+ # apply result order should not depend on whether index is the same or just equal
+ df = DataFrame({"A": [2, 1, 2], "B": [1, 2, 3]})
+ result = df.groupby("A", group_keys=False).apply(lambda x: x)
+ expected = df.groupby("A", group_keys=False).apply(lambda x: x.copy())
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_with_timezones_aware():
+ # GH: 27212
+ dates = ["2001-01-01"] * 2 + ["2001-01-02"] * 2 + ["2001-01-03"] * 2
+ index_no_tz = pd.DatetimeIndex(dates)
+ index_tz = pd.DatetimeIndex(dates, tz="UTC")
+ df1 = DataFrame({"x": list(range(2)) * 3, "y": range(6), "t": index_no_tz})
+ df2 = DataFrame({"x": list(range(2)) * 3, "y": range(6), "t": index_tz})
+
+ result1 = df1.groupby("x", group_keys=False).apply(lambda df: df[["x", "y"]].copy())
+ result2 = df2.groupby("x", group_keys=False).apply(lambda df: df[["x", "y"]].copy())
+
+ tm.assert_frame_equal(result1, result2)
+
+
+def test_apply_is_unchanged_when_other_methods_are_called_first(reduction_func):
+ # GH #34656
+ # GH #34271
+ df = DataFrame(
+ {
+ "a": [99, 99, 99, 88, 88, 88],
+ "b": [1, 2, 3, 4, 5, 6],
+ "c": [10, 20, 30, 40, 50, 60],
+ }
+ )
+
+ expected = DataFrame(
+ {"a": [264, 297], "b": [15, 6], "c": [150, 60]},
+ index=Index([88, 99], name="a"),
+ )
+
+ # Check output when no other methods are called before .apply()
+ grp = df.groupby(by="a")
+ msg = "The behavior of DataFrame.sum with axis=None is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False):
+ result = grp.apply(sum)
+ tm.assert_frame_equal(result, expected)
+
+ # Check output when another method is called before .apply()
+ grp = df.groupby(by="a")
+ args = get_groupby_method_args(reduction_func, df)
+ _ = getattr(grp, reduction_func)(*args)
+ with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False):
+ result = grp.apply(sum)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_with_date_in_multiindex_does_not_convert_to_timestamp():
+ # GH 29617
+
+ df = DataFrame(
+ {
+ "A": ["a", "a", "a", "b"],
+ "B": [
+ date(2020, 1, 10),
+ date(2020, 1, 10),
+ date(2020, 2, 10),
+ date(2020, 2, 10),
+ ],
+ "C": [1, 2, 3, 4],
+ },
+ index=Index([100, 101, 102, 103], name="idx"),
+ )
+
+ grp = df.groupby(["A", "B"])
+ result = grp.apply(lambda x: x.head(1))
+
+ expected = df.iloc[[0, 2, 3]]
+ expected = expected.reset_index()
+ expected.index = MultiIndex.from_frame(expected[["A", "B", "idx"]])
+ expected = expected.drop(columns="idx")
+
+ tm.assert_frame_equal(result, expected)
+ for val in result.index.levels[1]:
+ assert type(val) is date
+
+
+def test_apply_by_cols_equals_apply_by_rows_transposed():
+ # GH 16646
+ # Operating on the columns, or transposing and operating on the rows
+ # should give the same result. There was previously a bug where the
+ # by_rows operation would work fine, but by_cols would throw a ValueError
+
+ df = DataFrame(
+ np.random.default_rng(2).random([6, 4]),
+ columns=MultiIndex.from_product([["A", "B"], [1, 2]]),
+ )
+
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.T.groupby(axis=0, level=0)
+ by_rows = gb.apply(lambda x: x.droplevel(axis=0, level=0))
+
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb2 = df.groupby(axis=1, level=0)
+ by_cols = gb2.apply(lambda x: x.droplevel(axis=1, level=0))
+
+ tm.assert_frame_equal(by_cols, by_rows.T)
+ tm.assert_frame_equal(by_cols, df)
+
+
+@pytest.mark.parametrize("dropna", [True, False])
+def test_apply_dropna_with_indexed_same(dropna):
+ # GH 38227
+ # GH#43205
+ df = DataFrame(
+ {
+ "col": [1, 2, 3, 4, 5],
+ "group": ["a", np.nan, np.nan, "b", "b"],
+ },
+ index=list("xxyxz"),
+ )
+ result = df.groupby("group", dropna=dropna, group_keys=False).apply(lambda x: x)
+ expected = df.dropna() if dropna else df.iloc[[0, 3, 1, 2, 4]]
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "as_index, expected",
+ [
+ [
+ False,
+ DataFrame(
+ [[1, 1, 1], [2, 2, 1]], columns=Index(["a", "b", None], dtype=object)
+ ),
+ ],
+ [
+ True,
+ Series(
+ [1, 1], index=MultiIndex.from_tuples([(1, 1), (2, 2)], names=["a", "b"])
+ ),
+ ],
+ ],
+)
+def test_apply_as_index_constant_lambda(as_index, expected):
+ # GH 13217
+ df = DataFrame({"a": [1, 1, 2, 2], "b": [1, 1, 2, 2], "c": [1, 1, 1, 1]})
+ result = df.groupby(["a", "b"], as_index=as_index).apply(lambda x: 1)
+ tm.assert_equal(result, expected)
+
+
+def test_sort_index_groups():
+ # GH 20420
+ df = DataFrame(
+ {"A": [1, 2, 3, 4, 5], "B": [6, 7, 8, 9, 0], "C": [1, 1, 1, 2, 2]},
+ index=range(5),
+ )
+ result = df.groupby("C").apply(lambda x: x.A.sort_index())
+ expected = Series(
+ range(1, 6),
+ index=MultiIndex.from_tuples(
+ [(1, 0), (1, 1), (1, 2), (2, 3), (2, 4)], names=["C", None]
+ ),
+ name="A",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_positional_slice_groups_datetimelike():
+ # GH 21651
+ expected = DataFrame(
+ {
+ "date": pd.date_range("2010-01-01", freq="12H", periods=5),
+ "vals": range(5),
+ "let": list("abcde"),
+ }
+ )
+ result = expected.groupby(
+ [expected.let, expected.date.dt.date], group_keys=False
+ ).apply(lambda x: x.iloc[0:])
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_apply_shape_cache_safety():
+ # GH#42702 this fails if we cache_readonly Block.shape
+ df = DataFrame({"A": ["a", "a", "b"], "B": [1, 2, 3], "C": [4, 6, 5]})
+ gb = df.groupby("A")
+ result = gb[["B", "C"]].apply(lambda x: x.astype(float).max() - x.min())
+
+ expected = DataFrame(
+ {"B": [1.0, 0.0], "C": [2.0, 0.0]}, index=Index(["a", "b"], name="A")
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_apply_to_series_name():
+ # GH52444
+ df = DataFrame.from_dict(
+ {
+ "a": ["a", "b", "a", "b"],
+ "b1": ["aa", "ac", "ac", "ad"],
+ "b2": ["aa", "aa", "aa", "ac"],
+ }
+ )
+ grp = df.groupby("a")[["b1", "b2"]]
+ result = grp.apply(lambda x: x.unstack().value_counts())
+
+ expected_idx = MultiIndex.from_arrays(
+ arrays=[["a", "a", "b", "b", "b"], ["aa", "ac", "ac", "ad", "aa"]],
+ names=["a", None],
+ )
+ expected = Series([3, 1, 2, 1, 1], index=expected_idx, name="count")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("dropna", [True, False])
+def test_apply_na(dropna):
+ # GH#28984
+ df = DataFrame(
+ {"grp": [1, 1, 2, 2], "y": [1, 0, 2, 5], "z": [1, 2, np.nan, np.nan]}
+ )
+ dfgrp = df.groupby("grp", dropna=dropna)
+ result = dfgrp.apply(lambda grp_df: grp_df.nlargest(1, "z"))
+ expected = dfgrp.apply(lambda x: x.sort_values("z", ascending=False).head(1))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_empty_string_nan_coerce_bug():
+ # GH#24903
+ result = (
+ DataFrame(
+ {
+ "a": [1, 1, 2, 2],
+ "b": ["", "", "", ""],
+ "c": pd.to_datetime([1, 2, 3, 4], unit="s"),
+ }
+ )
+ .groupby(["a", "b"])
+ .apply(lambda df: df.iloc[-1])
+ )
+ expected = DataFrame(
+ [[1, "", pd.to_datetime(2, unit="s")], [2, "", pd.to_datetime(4, unit="s")]],
+ columns=["a", "b", "c"],
+ index=MultiIndex.from_tuples([(1, ""), (2, "")], names=["a", "b"]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("index_values", [[1, 2, 3], [1.0, 2.0, 3.0]])
+def test_apply_index_key_error_bug(index_values):
+ # GH 44310
+ result = DataFrame(
+ {
+ "a": ["aa", "a2", "a3"],
+ "b": [1, 2, 3],
+ },
+ index=Index(index_values),
+ )
+ expected = DataFrame(
+ {
+ "b_mean": [2.0, 3.0, 1.0],
+ },
+ index=Index(["a2", "a3", "aa"], name="a"),
+ )
+ result = result.groupby("a").apply(
+ lambda df: Series([df["b"].mean()], index=["b_mean"])
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "arg,idx",
+ [
+ [
+ [
+ 1,
+ 2,
+ 3,
+ ],
+ [
+ 0.1,
+ 0.3,
+ 0.2,
+ ],
+ ],
+ [
+ [
+ 1,
+ 2,
+ 3,
+ ],
+ [
+ 0.1,
+ 0.2,
+ 0.3,
+ ],
+ ],
+ [
+ [
+ 1,
+ 4,
+ 3,
+ ],
+ [
+ 0.1,
+ 0.4,
+ 0.2,
+ ],
+ ],
+ ],
+)
+def test_apply_nonmonotonic_float_index(arg, idx):
+ # GH 34455
+ expected = DataFrame({"col": arg}, index=idx)
+ result = expected.groupby("col", group_keys=False).apply(lambda x: x)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("args, kwargs", [([True], {}), ([], {"numeric_only": True})])
+def test_apply_str_with_args(df, args, kwargs):
+ # GH#46479
+ gb = df.groupby("A")
+ result = gb.apply("sum", *args, **kwargs)
+ expected = gb.sum(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("name", ["some_name", None])
+def test_result_name_when_one_group(name):
+ # GH 46369
+ ser = Series([1, 2], name=name)
+ result = ser.groupby(["a", "a"], group_keys=False).apply(lambda x: x)
+ expected = Series([1, 2], name=name)
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "method, op",
+ [
+ ("apply", lambda gb: gb.values[-1]),
+ ("apply", lambda gb: gb["b"].iloc[0]),
+ ("agg", "skew"),
+ ("agg", "prod"),
+ ("agg", "sum"),
+ ],
+)
+def test_empty_df(method, op):
+ # GH 47985
+ empty_df = DataFrame({"a": [], "b": []})
+ gb = empty_df.groupby("a", group_keys=True)
+ group = getattr(gb, "b")
+
+ result = getattr(group, method)(op)
+ expected = Series(
+ [], name="b", dtype="float64", index=Index([], dtype="float64", name="a")
+ )
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "group_col",
+ [([0.0, np.nan, 0.0, 0.0]), ([np.nan, 0.0, 0.0, 0.0]), ([0, 0.0, 0.0, np.nan])],
+)
+def test_apply_inconsistent_output(group_col):
+ # GH 34478
+ df = DataFrame({"group_col": group_col, "value_col": [2, 2, 2, 2]})
+
+ result = df.groupby("group_col").value_col.apply(
+ lambda x: x.value_counts().reindex(index=[1, 2, 3])
+ )
+ expected = Series(
+ [np.nan, 3.0, np.nan],
+ name="value_col",
+ index=MultiIndex.from_product([[0.0], [1, 2, 3]], names=["group_col", 0.0]),
+ )
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_array_output_multi_getitem():
+ # GH 18930
+ df = DataFrame(
+ {"A": {"a": 1, "b": 2}, "B": {"a": 1, "b": 2}, "C": {"a": 1, "b": 2}}
+ )
+ result = df.groupby("A")[["B", "C"]].apply(lambda x: np.array([0]))
+ expected = Series(
+ [np.array([0])] * 2, index=Index([1, 2], name="A"), name=("B", "C")
+ )
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_apply_mutate.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_apply_mutate.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bc07b584e9d18556780465ba67c424127c17e90
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_apply_mutate.py
@@ -0,0 +1,147 @@
+import numpy as np
+
+import pandas as pd
+import pandas._testing as tm
+
+
+def test_group_by_copy():
+ # GH#44803
+ df = pd.DataFrame(
+ {
+ "name": ["Alice", "Bob", "Carl"],
+ "age": [20, 21, 20],
+ }
+ ).set_index("name")
+
+ grp_by_same_value = df.groupby(["age"], group_keys=False).apply(lambda group: group)
+ grp_by_copy = df.groupby(["age"], group_keys=False).apply(
+ lambda group: group.copy()
+ )
+ tm.assert_frame_equal(grp_by_same_value, grp_by_copy)
+
+
+def test_mutate_groups():
+ # GH3380
+
+ df = pd.DataFrame(
+ {
+ "cat1": ["a"] * 8 + ["b"] * 6,
+ "cat2": ["c"] * 2
+ + ["d"] * 2
+ + ["e"] * 2
+ + ["f"] * 2
+ + ["c"] * 2
+ + ["d"] * 2
+ + ["e"] * 2,
+ "cat3": [f"g{x}" for x in range(1, 15)],
+ "val": np.random.default_rng(2).integers(100, size=14),
+ }
+ )
+
+ def f_copy(x):
+ x = x.copy()
+ x["rank"] = x.val.rank(method="min")
+ return x.groupby("cat2")["rank"].min()
+
+ def f_no_copy(x):
+ x["rank"] = x.val.rank(method="min")
+ return x.groupby("cat2")["rank"].min()
+
+ grpby_copy = df.groupby("cat1").apply(f_copy)
+ grpby_no_copy = df.groupby("cat1").apply(f_no_copy)
+ tm.assert_series_equal(grpby_copy, grpby_no_copy)
+
+
+def test_no_mutate_but_looks_like():
+ # GH 8467
+ # first show's mutation indicator
+ # second does not, but should yield the same results
+ df = pd.DataFrame({"key": [1, 1, 1, 2, 2, 2, 3, 3, 3], "value": range(9)})
+
+ result1 = df.groupby("key", group_keys=True).apply(lambda x: x[:].key)
+ result2 = df.groupby("key", group_keys=True).apply(lambda x: x.key)
+ tm.assert_series_equal(result1, result2)
+
+
+def test_apply_function_with_indexing():
+ # GH: 33058
+ df = pd.DataFrame(
+ {"col1": ["A", "A", "A", "B", "B", "B"], "col2": [1, 2, 3, 4, 5, 6]}
+ )
+
+ def fn(x):
+ x.loc[x.index[-1], "col2"] = 0
+ return x.col2
+
+ result = df.groupby(["col1"], as_index=False).apply(fn)
+ expected = pd.Series(
+ [1, 2, 0, 4, 5, 0],
+ index=pd.MultiIndex.from_tuples(
+ [(0, 0), (0, 1), (0, 2), (1, 3), (1, 4), (1, 5)]
+ ),
+ name="col2",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_mutate_columns_multiindex():
+ # GH 12652
+ df = pd.DataFrame(
+ {
+ ("C", "julian"): [1, 2, 3],
+ ("B", "geoffrey"): [1, 2, 3],
+ ("A", "julian"): [1, 2, 3],
+ ("B", "julian"): [1, 2, 3],
+ ("A", "geoffrey"): [1, 2, 3],
+ ("C", "geoffrey"): [1, 2, 3],
+ },
+ columns=pd.MultiIndex.from_tuples(
+ [
+ ("A", "julian"),
+ ("A", "geoffrey"),
+ ("B", "julian"),
+ ("B", "geoffrey"),
+ ("C", "julian"),
+ ("C", "geoffrey"),
+ ]
+ ),
+ )
+
+ def add_column(grouped):
+ name = grouped.columns[0][1]
+ grouped["sum", name] = grouped.sum(axis=1)
+ return grouped
+
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby(level=1, axis=1)
+ result = gb.apply(add_column)
+ expected = pd.DataFrame(
+ [
+ [1, 1, 1, 3, 1, 1, 1, 3],
+ [2, 2, 2, 6, 2, 2, 2, 6],
+ [
+ 3,
+ 3,
+ 3,
+ 9,
+ 3,
+ 3,
+ 3,
+ 9,
+ ],
+ ],
+ columns=pd.MultiIndex.from_tuples(
+ [
+ ("geoffrey", "A", "geoffrey"),
+ ("geoffrey", "B", "geoffrey"),
+ ("geoffrey", "C", "geoffrey"),
+ ("geoffrey", "sum", "geoffrey"),
+ ("julian", "A", "julian"),
+ ("julian", "B", "julian"),
+ ("julian", "C", "julian"),
+ ("julian", "sum", "julian"),
+ ]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_bin_groupby.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_bin_groupby.py
new file mode 100644
index 0000000000000000000000000000000000000000..49b2e621b7adc97947ec9d6c376a9d0f10e672fb
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_bin_groupby.py
@@ -0,0 +1,65 @@
+import numpy as np
+import pytest
+
+from pandas._libs import lib
+import pandas.util._test_decorators as td
+
+import pandas as pd
+import pandas._testing as tm
+
+
+def assert_block_lengths(x):
+ assert len(x) == len(x._mgr.blocks[0].mgr_locs)
+ return 0
+
+
+def cumsum_max(x):
+ x.cumsum().max()
+ return 0
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ cumsum_max,
+ pytest.param(assert_block_lengths, marks=td.skip_array_manager_invalid_test),
+ ],
+)
+def test_mgr_locs_updated(func):
+ # https://github.com/pandas-dev/pandas/issues/31802
+ # Some operations may require creating new blocks, which requires
+ # valid mgr_locs
+ df = pd.DataFrame({"A": ["a", "a", "a"], "B": ["a", "b", "b"], "C": [1, 1, 1]})
+ result = df.groupby(["A", "B"]).agg(func)
+ expected = pd.DataFrame(
+ {"C": [0, 0]},
+ index=pd.MultiIndex.from_product([["a"], ["a", "b"]], names=["A", "B"]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "binner,closed,expected",
+ [
+ (
+ np.array([0, 3, 6, 9], dtype=np.int64),
+ "left",
+ np.array([2, 5, 6], dtype=np.int64),
+ ),
+ (
+ np.array([0, 3, 6, 9], dtype=np.int64),
+ "right",
+ np.array([3, 6, 6], dtype=np.int64),
+ ),
+ (np.array([0, 3, 6], dtype=np.int64), "left", np.array([2, 5], dtype=np.int64)),
+ (
+ np.array([0, 3, 6], dtype=np.int64),
+ "right",
+ np.array([3, 6], dtype=np.int64),
+ ),
+ ],
+)
+def test_generate_bins(binner, closed, expected):
+ values = np.array([1, 2, 3, 4, 5, 6], dtype=np.int64)
+ result = lib.generate_bins_dt64(values, binner, closed=closed)
+ tm.assert_numpy_array_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_categorical.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_categorical.py
new file mode 100644
index 0000000000000000000000000000000000000000..68ce58ad236906d126c8f9b6245569536848d28e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_categorical.py
@@ -0,0 +1,2119 @@
+from datetime import datetime
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ qcut,
+)
+import pandas._testing as tm
+from pandas.api.typing import SeriesGroupBy
+from pandas.tests.groupby import get_groupby_method_args
+
+
+def cartesian_product_for_groupers(result, args, names, fill_value=np.nan):
+ """Reindex to a cartesian production for the groupers,
+ preserving the nature (Categorical) of each grouper
+ """
+
+ def f(a):
+ if isinstance(a, (CategoricalIndex, Categorical)):
+ categories = a.categories
+ a = Categorical.from_codes(
+ np.arange(len(categories)), categories=categories, ordered=a.ordered
+ )
+ return a
+
+ index = MultiIndex.from_product(map(f, args), names=names)
+ return result.reindex(index, fill_value=fill_value).sort_index()
+
+
+_results_for_groupbys_with_missing_categories = {
+ # This maps the builtin groupby functions to their expected outputs for
+ # missing categories when they are called on a categorical grouper with
+ # observed=False. Some functions are expected to return NaN, some zero.
+ # These expected values can be used across several tests (i.e. they are
+ # the same for SeriesGroupBy and DataFrameGroupBy) but they should only be
+ # hardcoded in one place.
+ "all": np.nan,
+ "any": np.nan,
+ "count": 0,
+ "corrwith": np.nan,
+ "first": np.nan,
+ "idxmax": np.nan,
+ "idxmin": np.nan,
+ "last": np.nan,
+ "max": np.nan,
+ "mean": np.nan,
+ "median": np.nan,
+ "min": np.nan,
+ "nth": np.nan,
+ "nunique": 0,
+ "prod": np.nan,
+ "quantile": np.nan,
+ "sem": np.nan,
+ "size": 0,
+ "skew": np.nan,
+ "std": np.nan,
+ "sum": 0,
+ "var": np.nan,
+}
+
+
+def test_apply_use_categorical_name(df):
+ cats = qcut(df.C, 4)
+
+ def get_stats(group):
+ return {
+ "min": group.min(),
+ "max": group.max(),
+ "count": group.count(),
+ "mean": group.mean(),
+ }
+
+ result = df.groupby(cats, observed=False).D.apply(get_stats)
+ assert result.index.names[0] == "C"
+
+
+def test_basic(): # TODO: split this test
+ cats = Categorical(
+ ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
+ categories=["a", "b", "c", "d"],
+ ordered=True,
+ )
+ data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats})
+
+ exp_index = CategoricalIndex(list("abcd"), name="b", ordered=True)
+ expected = DataFrame({"a": [1, 2, 4, np.nan]}, index=exp_index)
+ result = data.groupby("b", observed=False).mean()
+ tm.assert_frame_equal(result, expected)
+
+ cat1 = Categorical(["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True)
+ cat2 = Categorical(["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True)
+ df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]})
+
+ # single grouper
+ gb = df.groupby("A", observed=False)
+ exp_idx = CategoricalIndex(["a", "b", "z"], name="A", ordered=True)
+ expected = DataFrame({"values": Series([3, 7, 0], index=exp_idx)})
+ result = gb.sum(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ # GH 8623
+ x = DataFrame(
+ [[1, "John P. Doe"], [2, "Jane Dove"], [1, "John P. Doe"]],
+ columns=["person_id", "person_name"],
+ )
+ x["person_name"] = Categorical(x.person_name)
+
+ g = x.groupby(["person_id"], observed=False)
+ result = g.transform(lambda x: x)
+ tm.assert_frame_equal(result, x[["person_name"]])
+
+ result = x.drop_duplicates("person_name")
+ expected = x.iloc[[0, 1]]
+ tm.assert_frame_equal(result, expected)
+
+ def f(x):
+ return x.drop_duplicates("person_name").iloc[0]
+
+ result = g.apply(f)
+ expected = x.iloc[[0, 1]].copy()
+ expected.index = Index([1, 2], name="person_id")
+ expected["person_name"] = expected["person_name"].astype("object")
+ tm.assert_frame_equal(result, expected)
+
+ # GH 9921
+ # Monotonic
+ df = DataFrame({"a": [5, 15, 25]})
+ c = pd.cut(df.a, bins=[0, 10, 20, 30, 40])
+
+ msg = "using SeriesGroupBy.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result = df.a.groupby(c, observed=False).transform(sum)
+ tm.assert_series_equal(result, df["a"])
+
+ tm.assert_series_equal(
+ df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df["a"]
+ )
+ msg = "using DataFrameGroupBy.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result = df.groupby(c, observed=False).transform(sum)
+ expected = df[["a"]]
+ tm.assert_frame_equal(result, expected)
+
+ gbc = df.groupby(c, observed=False)
+ result = gbc.transform(lambda xs: np.max(xs, axis=0))
+ tm.assert_frame_equal(result, df[["a"]])
+
+ result2 = gbc.transform(lambda xs: np.max(xs, axis=0))
+ msg = "using DataFrameGroupBy.max"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result3 = gbc.transform(max)
+ result4 = gbc.transform(np.maximum.reduce)
+ result5 = gbc.transform(lambda xs: np.maximum.reduce(xs))
+ tm.assert_frame_equal(result2, df[["a"]], check_dtype=False)
+ tm.assert_frame_equal(result3, df[["a"]], check_dtype=False)
+ tm.assert_frame_equal(result4, df[["a"]])
+ tm.assert_frame_equal(result5, df[["a"]])
+
+ # Filter
+ tm.assert_series_equal(df.a.groupby(c, observed=False).filter(np.all), df["a"])
+ tm.assert_frame_equal(df.groupby(c, observed=False).filter(np.all), df)
+
+ # Non-monotonic
+ df = DataFrame({"a": [5, 15, 25, -5]})
+ c = pd.cut(df.a, bins=[-10, 0, 10, 20, 30, 40])
+
+ msg = "using SeriesGroupBy.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result = df.a.groupby(c, observed=False).transform(sum)
+ tm.assert_series_equal(result, df["a"])
+
+ tm.assert_series_equal(
+ df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df["a"]
+ )
+ msg = "using DataFrameGroupBy.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result = df.groupby(c, observed=False).transform(sum)
+ expected = df[["a"]]
+ tm.assert_frame_equal(result, expected)
+
+ tm.assert_frame_equal(
+ df.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df[["a"]]
+ )
+
+ # GH 9603
+ df = DataFrame({"a": [1, 0, 0, 0]})
+ c = pd.cut(df.a, [0, 1, 2, 3, 4], labels=Categorical(list("abcd")))
+ result = df.groupby(c, observed=False).apply(len)
+
+ exp_index = CategoricalIndex(c.values.categories, ordered=c.values.ordered)
+ expected = Series([1, 0, 0, 0], index=exp_index)
+ expected.index.name = "a"
+ tm.assert_series_equal(result, expected)
+
+ # more basic
+ levels = ["foo", "bar", "baz", "qux"]
+ codes = np.random.default_rng(2).integers(0, 4, size=100)
+
+ cats = Categorical.from_codes(codes, levels, ordered=True)
+
+ data = DataFrame(np.random.default_rng(2).standard_normal((100, 4)))
+
+ result = data.groupby(cats, observed=False).mean()
+
+ expected = data.groupby(np.asarray(cats), observed=False).mean()
+ exp_idx = CategoricalIndex(levels, categories=cats.categories, ordered=True)
+ expected = expected.reindex(exp_idx)
+
+ tm.assert_frame_equal(result, expected)
+
+ grouped = data.groupby(cats, observed=False)
+ desc_result = grouped.describe()
+
+ idx = cats.codes.argsort()
+ ord_labels = np.asarray(cats).take(idx)
+ ord_data = data.take(idx)
+
+ exp_cats = Categorical(
+ ord_labels, ordered=True, categories=["foo", "bar", "baz", "qux"]
+ )
+ expected = ord_data.groupby(exp_cats, sort=False, observed=False).describe()
+ tm.assert_frame_equal(desc_result, expected)
+
+ # GH 10460
+ expc = Categorical.from_codes(np.arange(4).repeat(8), levels, ordered=True)
+ exp = CategoricalIndex(expc)
+ tm.assert_index_equal(
+ (desc_result.stack(future_stack=True).index.get_level_values(0)), exp
+ )
+ exp = Index(["count", "mean", "std", "min", "25%", "50%", "75%", "max"] * 4)
+ tm.assert_index_equal(
+ (desc_result.stack(future_stack=True).index.get_level_values(1)), exp
+ )
+
+
+def test_level_get_group(observed):
+ # GH15155
+ df = DataFrame(
+ data=np.arange(2, 22, 2),
+ index=MultiIndex(
+ levels=[CategoricalIndex(["a", "b"]), range(10)],
+ codes=[[0] * 5 + [1] * 5, range(10)],
+ names=["Index1", "Index2"],
+ ),
+ )
+ g = df.groupby(level=["Index1"], observed=observed)
+
+ # expected should equal test.loc[["a"]]
+ # GH15166
+ expected = DataFrame(
+ data=np.arange(2, 12, 2),
+ index=MultiIndex(
+ levels=[CategoricalIndex(["a", "b"]), range(5)],
+ codes=[[0] * 5, range(5)],
+ names=["Index1", "Index2"],
+ ),
+ )
+ result = g.get_group("a")
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_sorting_with_different_categoricals():
+ # GH 24271
+ df = DataFrame(
+ {
+ "group": ["A"] * 6 + ["B"] * 6,
+ "dose": ["high", "med", "low"] * 4,
+ "outcomes": np.arange(12.0),
+ }
+ )
+
+ df.dose = Categorical(df.dose, categories=["low", "med", "high"], ordered=True)
+
+ result = df.groupby("group")["dose"].value_counts()
+ result = result.sort_index(level=0, sort_remaining=True)
+ index = ["low", "med", "high", "low", "med", "high"]
+ index = Categorical(index, categories=["low", "med", "high"], ordered=True)
+ index = [["A", "A", "A", "B", "B", "B"], CategoricalIndex(index)]
+ index = MultiIndex.from_arrays(index, names=["group", "dose"])
+ expected = Series([2] * 6, index=index, name="count")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("ordered", [True, False])
+def test_apply(ordered):
+ # GH 10138
+
+ dense = Categorical(list("abc"), ordered=ordered)
+
+ # 'b' is in the categories but not in the list
+ missing = Categorical(list("aaa"), categories=["a", "b"], ordered=ordered)
+ values = np.arange(len(dense))
+ df = DataFrame({"missing": missing, "dense": dense, "values": values})
+ grouped = df.groupby(["missing", "dense"], observed=True)
+
+ # missing category 'b' should still exist in the output index
+ idx = MultiIndex.from_arrays([missing, dense], names=["missing", "dense"])
+ expected = DataFrame([0, 1, 2.0], index=idx, columns=["values"])
+
+ result = grouped.apply(lambda x: np.mean(x, axis=0))
+ tm.assert_frame_equal(result, expected)
+
+ result = grouped.mean()
+ tm.assert_frame_equal(result, expected)
+
+ msg = "using DataFrameGroupBy.mean"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result = grouped.agg(np.mean)
+ tm.assert_frame_equal(result, expected)
+
+ # but for transform we should still get back the original index
+ idx = MultiIndex.from_arrays([missing, dense], names=["missing", "dense"])
+ expected = Series(1, index=idx)
+ result = grouped.apply(lambda x: 1)
+ tm.assert_series_equal(result, expected)
+
+
+def test_observed(observed):
+ # multiple groupers, don't re-expand the output space
+ # of the grouper
+ # gh-14942 (implement)
+ # gh-10132 (back-compat)
+ # gh-8138 (back-compat)
+ # gh-8869
+
+ cat1 = Categorical(["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True)
+ cat2 = Categorical(["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True)
+ df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]})
+ df["C"] = ["foo", "bar"] * 2
+
+ # multiple groupers with a non-cat
+ gb = df.groupby(["A", "B", "C"], observed=observed)
+ exp_index = MultiIndex.from_arrays(
+ [cat1, cat2, ["foo", "bar"] * 2], names=["A", "B", "C"]
+ )
+ expected = DataFrame({"values": Series([1, 2, 3, 4], index=exp_index)}).sort_index()
+ result = gb.sum()
+ if not observed:
+ expected = cartesian_product_for_groupers(
+ expected, [cat1, cat2, ["foo", "bar"]], list("ABC"), fill_value=0
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ gb = df.groupby(["A", "B"], observed=observed)
+ exp_index = MultiIndex.from_arrays([cat1, cat2], names=["A", "B"])
+ expected = DataFrame(
+ {"values": [1, 2, 3, 4], "C": ["foo", "bar", "foo", "bar"]}, index=exp_index
+ )
+ result = gb.sum()
+ if not observed:
+ expected = cartesian_product_for_groupers(
+ expected, [cat1, cat2], list("AB"), fill_value=0
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ # https://github.com/pandas-dev/pandas/issues/8138
+ d = {
+ "cat": Categorical(
+ ["a", "b", "a", "b"], categories=["a", "b", "c"], ordered=True
+ ),
+ "ints": [1, 1, 2, 2],
+ "val": [10, 20, 30, 40],
+ }
+ df = DataFrame(d)
+
+ # Grouping on a single column
+ groups_single_key = df.groupby("cat", observed=observed)
+ result = groups_single_key.mean()
+
+ exp_index = CategoricalIndex(
+ list("ab"), name="cat", categories=list("abc"), ordered=True
+ )
+ expected = DataFrame({"ints": [1.5, 1.5], "val": [20.0, 30]}, index=exp_index)
+ if not observed:
+ index = CategoricalIndex(
+ list("abc"), name="cat", categories=list("abc"), ordered=True
+ )
+ expected = expected.reindex(index)
+
+ tm.assert_frame_equal(result, expected)
+
+ # Grouping on two columns
+ groups_double_key = df.groupby(["cat", "ints"], observed=observed)
+ result = groups_double_key.agg("mean")
+ expected = DataFrame(
+ {
+ "val": [10.0, 30.0, 20.0, 40.0],
+ "cat": Categorical(
+ ["a", "a", "b", "b"], categories=["a", "b", "c"], ordered=True
+ ),
+ "ints": [1, 2, 1, 2],
+ }
+ ).set_index(["cat", "ints"])
+ if not observed:
+ expected = cartesian_product_for_groupers(
+ expected, [df.cat.values, [1, 2]], ["cat", "ints"]
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ # GH 10132
+ for key in [("a", 1), ("b", 2), ("b", 1), ("a", 2)]:
+ c, i = key
+ result = groups_double_key.get_group(key)
+ expected = df[(df.cat == c) & (df.ints == i)]
+ tm.assert_frame_equal(result, expected)
+
+ # gh-8869
+ # with as_index
+ d = {
+ "foo": [10, 8, 4, 8, 4, 1, 1],
+ "bar": [10, 20, 30, 40, 50, 60, 70],
+ "baz": ["d", "c", "e", "a", "a", "d", "c"],
+ }
+ df = DataFrame(d)
+ cat = pd.cut(df["foo"], np.linspace(0, 10, 3))
+ df["range"] = cat
+ groups = df.groupby(["range", "baz"], as_index=False, observed=observed)
+ result = groups.agg("mean")
+
+ groups2 = df.groupby(["range", "baz"], as_index=True, observed=observed)
+ expected = groups2.agg("mean").reset_index()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_observed_codes_remap(observed):
+ d = {"C1": [3, 3, 4, 5], "C2": [1, 2, 3, 4], "C3": [10, 100, 200, 34]}
+ df = DataFrame(d)
+ values = pd.cut(df["C1"], [1, 2, 3, 6])
+ values.name = "cat"
+ groups_double_key = df.groupby([values, "C2"], observed=observed)
+
+ idx = MultiIndex.from_arrays([values, [1, 2, 3, 4]], names=["cat", "C2"])
+ expected = DataFrame(
+ {"C1": [3.0, 3.0, 4.0, 5.0], "C3": [10.0, 100.0, 200.0, 34.0]}, index=idx
+ )
+ if not observed:
+ expected = cartesian_product_for_groupers(
+ expected, [values.values, [1, 2, 3, 4]], ["cat", "C2"]
+ )
+
+ result = groups_double_key.agg("mean")
+ tm.assert_frame_equal(result, expected)
+
+
+def test_observed_perf():
+ # we create a cartesian product, so this is
+ # non-performant if we don't use observed values
+ # gh-14942
+ df = DataFrame(
+ {
+ "cat": np.random.default_rng(2).integers(0, 255, size=30000),
+ "int_id": np.random.default_rng(2).integers(0, 255, size=30000),
+ "other_id": np.random.default_rng(2).integers(0, 10000, size=30000),
+ "foo": 0,
+ }
+ )
+ df["cat"] = df.cat.astype(str).astype("category")
+
+ grouped = df.groupby(["cat", "int_id", "other_id"], observed=True)
+ result = grouped.count()
+ assert result.index.levels[0].nunique() == df.cat.nunique()
+ assert result.index.levels[1].nunique() == df.int_id.nunique()
+ assert result.index.levels[2].nunique() == df.other_id.nunique()
+
+
+def test_observed_groups(observed):
+ # gh-20583
+ # test that we have the appropriate groups
+
+ cat = Categorical(["a", "c", "a"], categories=["a", "b", "c"])
+ df = DataFrame({"cat": cat, "vals": [1, 2, 3]})
+ g = df.groupby("cat", observed=observed)
+
+ result = g.groups
+ if observed:
+ expected = {"a": Index([0, 2], dtype="int64"), "c": Index([1], dtype="int64")}
+ else:
+ expected = {
+ "a": Index([0, 2], dtype="int64"),
+ "b": Index([], dtype="int64"),
+ "c": Index([1], dtype="int64"),
+ }
+
+ tm.assert_dict_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "keys, expected_values, expected_index_levels",
+ [
+ ("a", [15, 9, 0], CategoricalIndex([1, 2, 3], name="a")),
+ (
+ ["a", "b"],
+ [7, 8, 0, 0, 0, 9, 0, 0, 0],
+ [CategoricalIndex([1, 2, 3], name="a"), Index([4, 5, 6])],
+ ),
+ (
+ ["a", "a2"],
+ [15, 0, 0, 0, 9, 0, 0, 0, 0],
+ [
+ CategoricalIndex([1, 2, 3], name="a"),
+ CategoricalIndex([1, 2, 3], name="a"),
+ ],
+ ),
+ ],
+)
+@pytest.mark.parametrize("test_series", [True, False])
+def test_unobserved_in_index(keys, expected_values, expected_index_levels, test_series):
+ # GH#49354 - ensure unobserved cats occur when grouping by index levels
+ df = DataFrame(
+ {
+ "a": Categorical([1, 1, 2], categories=[1, 2, 3]),
+ "a2": Categorical([1, 1, 2], categories=[1, 2, 3]),
+ "b": [4, 5, 6],
+ "c": [7, 8, 9],
+ }
+ ).set_index(["a", "a2"])
+ if "b" not in keys:
+ # Only keep b when it is used for grouping for consistent columns in the result
+ df = df.drop(columns="b")
+
+ gb = df.groupby(keys, observed=False)
+ if test_series:
+ gb = gb["c"]
+ result = gb.sum()
+
+ if len(keys) == 1:
+ index = expected_index_levels
+ else:
+ codes = [[0, 0, 0, 1, 1, 1, 2, 2, 2], 3 * [0, 1, 2]]
+ index = MultiIndex(
+ expected_index_levels,
+ codes=codes,
+ names=keys,
+ )
+ expected = DataFrame({"c": expected_values}, index=index)
+ if test_series:
+ expected = expected["c"]
+ tm.assert_equal(result, expected)
+
+
+def test_observed_groups_with_nan(observed):
+ # GH 24740
+ df = DataFrame(
+ {
+ "cat": Categorical(["a", np.nan, "a"], categories=["a", "b", "d"]),
+ "vals": [1, 2, 3],
+ }
+ )
+ g = df.groupby("cat", observed=observed)
+ result = g.groups
+ if observed:
+ expected = {"a": Index([0, 2], dtype="int64")}
+ else:
+ expected = {
+ "a": Index([0, 2], dtype="int64"),
+ "b": Index([], dtype="int64"),
+ "d": Index([], dtype="int64"),
+ }
+ tm.assert_dict_equal(result, expected)
+
+
+def test_observed_nth():
+ # GH 26385
+ cat = Categorical(["a", np.nan, np.nan], categories=["a", "b", "c"])
+ ser = Series([1, 2, 3])
+ df = DataFrame({"cat": cat, "ser": ser})
+
+ result = df.groupby("cat", observed=False)["ser"].nth(0)
+ expected = df["ser"].iloc[[0]]
+ tm.assert_series_equal(result, expected)
+
+
+def test_dataframe_categorical_with_nan(observed):
+ # GH 21151
+ s1 = Categorical([np.nan, "a", np.nan, "a"], categories=["a", "b", "c"])
+ s2 = Series([1, 2, 3, 4])
+ df = DataFrame({"s1": s1, "s2": s2})
+ result = df.groupby("s1", observed=observed).first().reset_index()
+ if observed:
+ expected = DataFrame(
+ {"s1": Categorical(["a"], categories=["a", "b", "c"]), "s2": [2]}
+ )
+ else:
+ expected = DataFrame(
+ {
+ "s1": Categorical(["a", "b", "c"], categories=["a", "b", "c"]),
+ "s2": [2, np.nan, np.nan],
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("ordered", [True, False])
+@pytest.mark.parametrize("observed", [True, False])
+@pytest.mark.parametrize("sort", [True, False])
+def test_dataframe_categorical_ordered_observed_sort(ordered, observed, sort):
+ # GH 25871: Fix groupby sorting on ordered Categoricals
+ # GH 25167: Groupby with observed=True doesn't sort
+
+ # Build a dataframe with cat having one unobserved category ('missing'),
+ # and a Series with identical values
+ label = Categorical(
+ ["d", "a", "b", "a", "d", "b"],
+ categories=["a", "b", "missing", "d"],
+ ordered=ordered,
+ )
+ val = Series(["d", "a", "b", "a", "d", "b"])
+ df = DataFrame({"label": label, "val": val})
+
+ # aggregate on the Categorical
+ result = df.groupby("label", observed=observed, sort=sort)["val"].aggregate("first")
+
+ # If ordering works, we expect index labels equal to aggregation results,
+ # except for 'observed=False': label 'missing' has aggregation None
+ label = Series(result.index.array, dtype="object")
+ aggr = Series(result.array)
+ if not observed:
+ aggr[aggr.isna()] = "missing"
+ if not all(label == aggr):
+ msg = (
+ "Labels and aggregation results not consistently sorted\n"
+ f"for (ordered={ordered}, observed={observed}, sort={sort})\n"
+ f"Result:\n{result}"
+ )
+ assert False, msg
+
+
+def test_datetime():
+ # GH9049: ensure backward compatibility
+ levels = pd.date_range("2014-01-01", periods=4)
+ codes = np.random.default_rng(2).integers(0, 4, size=100)
+
+ cats = Categorical.from_codes(codes, levels, ordered=True)
+
+ data = DataFrame(np.random.default_rng(2).standard_normal((100, 4)))
+ result = data.groupby(cats, observed=False).mean()
+
+ expected = data.groupby(np.asarray(cats), observed=False).mean()
+ expected = expected.reindex(levels)
+ expected.index = CategoricalIndex(
+ expected.index, categories=expected.index, ordered=True
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ grouped = data.groupby(cats, observed=False)
+ desc_result = grouped.describe()
+
+ idx = cats.codes.argsort()
+ ord_labels = cats.take(idx)
+ ord_data = data.take(idx)
+ expected = ord_data.groupby(ord_labels, observed=False).describe()
+ tm.assert_frame_equal(desc_result, expected)
+ tm.assert_index_equal(desc_result.index, expected.index)
+ tm.assert_index_equal(
+ desc_result.index.get_level_values(0), expected.index.get_level_values(0)
+ )
+
+ # GH 10460
+ expc = Categorical.from_codes(np.arange(4).repeat(8), levels, ordered=True)
+ exp = CategoricalIndex(expc)
+ tm.assert_index_equal(
+ (desc_result.stack(future_stack=True).index.get_level_values(0)), exp
+ )
+ exp = Index(["count", "mean", "std", "min", "25%", "50%", "75%", "max"] * 4)
+ tm.assert_index_equal(
+ (desc_result.stack(future_stack=True).index.get_level_values(1)), exp
+ )
+
+
+def test_categorical_index():
+ s = np.random.default_rng(2)
+ levels = ["foo", "bar", "baz", "qux"]
+ codes = s.integers(0, 4, size=20)
+ cats = Categorical.from_codes(codes, levels, ordered=True)
+ df = DataFrame(np.repeat(np.arange(20), 4).reshape(-1, 4), columns=list("abcd"))
+ df["cats"] = cats
+
+ # with a cat index
+ result = df.set_index("cats").groupby(level=0, observed=False).sum()
+ expected = df[list("abcd")].groupby(cats.codes, observed=False).sum()
+ expected.index = CategoricalIndex(
+ Categorical.from_codes([0, 1, 2, 3], levels, ordered=True), name="cats"
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # with a cat column, should produce a cat index
+ result = df.groupby("cats", observed=False).sum()
+ expected = df[list("abcd")].groupby(cats.codes, observed=False).sum()
+ expected.index = CategoricalIndex(
+ Categorical.from_codes([0, 1, 2, 3], levels, ordered=True), name="cats"
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_describe_categorical_columns():
+ # GH 11558
+ cats = CategoricalIndex(
+ ["qux", "foo", "baz", "bar"],
+ categories=["foo", "bar", "baz", "qux"],
+ ordered=True,
+ )
+ df = DataFrame(np.random.default_rng(2).standard_normal((20, 4)), columns=cats)
+ result = df.groupby([1, 2, 3, 4] * 5).describe()
+
+ tm.assert_index_equal(result.stack(future_stack=True).columns, cats)
+ tm.assert_categorical_equal(
+ result.stack(future_stack=True).columns.values, cats.values
+ )
+
+
+def test_unstack_categorical():
+ # GH11558 (example is taken from the original issue)
+ df = DataFrame(
+ {"a": range(10), "medium": ["A", "B"] * 5, "artist": list("XYXXY") * 2}
+ )
+ df["medium"] = df["medium"].astype("category")
+
+ gcat = df.groupby(["artist", "medium"], observed=False)["a"].count().unstack()
+ result = gcat.describe()
+
+ exp_columns = CategoricalIndex(["A", "B"], ordered=False, name="medium")
+ tm.assert_index_equal(result.columns, exp_columns)
+ tm.assert_categorical_equal(result.columns.values, exp_columns.values)
+
+ result = gcat["A"] + gcat["B"]
+ expected = Series([6, 4], index=Index(["X", "Y"], name="artist"))
+ tm.assert_series_equal(result, expected)
+
+
+def test_bins_unequal_len():
+ # GH3011
+ series = Series([np.nan, np.nan, 1, 1, 2, 2, 3, 3, 4, 4])
+ bins = pd.cut(series.dropna().values, 4)
+
+ # len(bins) != len(series) here
+ with pytest.raises(ValueError, match="Grouper and axis must be same length"):
+ series.groupby(bins).mean()
+
+
+@pytest.mark.parametrize(
+ ["series", "data"],
+ [
+ # Group a series with length and index equal to those of the grouper.
+ (Series(range(4)), {"A": [0, 3], "B": [1, 2]}),
+ # Group a series with length equal to that of the grouper and index unequal to
+ # that of the grouper.
+ (Series(range(4)).rename(lambda idx: idx + 1), {"A": [2], "B": [0, 1]}),
+ # GH44179: Group a series with length unequal to that of the grouper.
+ (Series(range(7)), {"A": [0, 3], "B": [1, 2]}),
+ ],
+)
+def test_categorical_series(series, data):
+ # Group the given series by a series with categorical data type such that group A
+ # takes indices 0 and 3 and group B indices 1 and 2, obtaining the values mapped in
+ # the given data.
+ groupby = series.groupby(Series(list("ABBA"), dtype="category"), observed=False)
+ result = groupby.aggregate(list)
+ expected = Series(data, index=CategoricalIndex(data.keys()))
+ tm.assert_series_equal(result, expected)
+
+
+def test_as_index():
+ # GH13204
+ df = DataFrame(
+ {
+ "cat": Categorical([1, 2, 2], [1, 2, 3]),
+ "A": [10, 11, 11],
+ "B": [101, 102, 103],
+ }
+ )
+ result = df.groupby(["cat", "A"], as_index=False, observed=True).sum()
+ expected = DataFrame(
+ {
+ "cat": Categorical([1, 2], categories=df.cat.cat.categories),
+ "A": [10, 11],
+ "B": [101, 205],
+ },
+ columns=["cat", "A", "B"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # function grouper
+ f = lambda r: df.loc[r, "A"]
+ msg = "A grouping .* was excluded from the result"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.groupby(["cat", f], as_index=False, observed=True).sum()
+ expected = DataFrame(
+ {
+ "cat": Categorical([1, 2], categories=df.cat.cat.categories),
+ "A": [10, 22],
+ "B": [101, 205],
+ },
+ columns=["cat", "A", "B"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # another not in-axis grouper (conflicting names in index)
+ s = Series(["a", "b", "b"], name="cat")
+ msg = "A grouping .* was excluded from the result"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.groupby(["cat", s], as_index=False, observed=True).sum()
+ tm.assert_frame_equal(result, expected)
+
+ # is original index dropped?
+ group_columns = ["cat", "A"]
+ expected = DataFrame(
+ {
+ "cat": Categorical([1, 2], categories=df.cat.cat.categories),
+ "A": [10, 11],
+ "B": [101, 205],
+ },
+ columns=["cat", "A", "B"],
+ )
+
+ for name in [None, "X", "B"]:
+ df.index = Index(list("abc"), name=name)
+ result = df.groupby(group_columns, as_index=False, observed=True).sum()
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_preserve_categories():
+ # GH-13179
+ categories = list("abc")
+
+ # ordered=True
+ df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=True)})
+ sort_index = CategoricalIndex(categories, categories, ordered=True, name="A")
+ nosort_index = CategoricalIndex(list("bac"), categories, ordered=True, name="A")
+ tm.assert_index_equal(
+ df.groupby("A", sort=True, observed=False).first().index, sort_index
+ )
+ # GH#42482 - don't sort result when sort=False, even when ordered=True
+ tm.assert_index_equal(
+ df.groupby("A", sort=False, observed=False).first().index, nosort_index
+ )
+
+ # ordered=False
+ df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)})
+ sort_index = CategoricalIndex(categories, categories, ordered=False, name="A")
+ # GH#48749 - don't change order of categories
+ # GH#42482 - don't sort result when sort=False, even when ordered=True
+ nosort_index = CategoricalIndex(list("bac"), list("abc"), ordered=False, name="A")
+ tm.assert_index_equal(
+ df.groupby("A", sort=True, observed=False).first().index, sort_index
+ )
+ tm.assert_index_equal(
+ df.groupby("A", sort=False, observed=False).first().index, nosort_index
+ )
+
+
+def test_preserve_categorical_dtype():
+ # GH13743, GH13854
+ df = DataFrame(
+ {
+ "A": [1, 2, 1, 1, 2],
+ "B": [10, 16, 22, 28, 34],
+ "C1": Categorical(list("abaab"), categories=list("bac"), ordered=False),
+ "C2": Categorical(list("abaab"), categories=list("bac"), ordered=True),
+ }
+ )
+ # single grouper
+ exp_full = DataFrame(
+ {
+ "A": [2.0, 1.0, np.nan],
+ "B": [25.0, 20.0, np.nan],
+ "C1": Categorical(list("bac"), categories=list("bac"), ordered=False),
+ "C2": Categorical(list("bac"), categories=list("bac"), ordered=True),
+ }
+ )
+ for col in ["C1", "C2"]:
+ result1 = df.groupby(by=col, as_index=False, observed=False).mean(
+ numeric_only=True
+ )
+ result2 = (
+ df.groupby(by=col, as_index=True, observed=False)
+ .mean(numeric_only=True)
+ .reset_index()
+ )
+ expected = exp_full.reindex(columns=result1.columns)
+ tm.assert_frame_equal(result1, expected)
+ tm.assert_frame_equal(result2, expected)
+
+
+@pytest.mark.parametrize(
+ "func, values",
+ [
+ ("first", ["second", "first"]),
+ ("last", ["fourth", "third"]),
+ ("min", ["fourth", "first"]),
+ ("max", ["second", "third"]),
+ ],
+)
+def test_preserve_on_ordered_ops(func, values):
+ # gh-18502
+ # preserve the categoricals on ops
+ c = Categorical(["first", "second", "third", "fourth"], ordered=True)
+ df = DataFrame({"payload": [-1, -2, -1, -2], "col": c})
+ g = df.groupby("payload")
+ result = getattr(g, func)()
+ expected = DataFrame(
+ {"payload": [-2, -1], "col": Series(values, dtype=c.dtype)}
+ ).set_index("payload")
+ tm.assert_frame_equal(result, expected)
+
+ # we should also preserve categorical for SeriesGroupBy
+ sgb = df.groupby("payload")["col"]
+ result = getattr(sgb, func)()
+ expected = expected["col"]
+ tm.assert_series_equal(result, expected)
+
+
+def test_categorical_no_compress():
+ data = Series(np.random.default_rng(2).standard_normal(9))
+
+ codes = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
+ cats = Categorical.from_codes(codes, [0, 1, 2], ordered=True)
+
+ result = data.groupby(cats, observed=False).mean()
+ exp = data.groupby(codes, observed=False).mean()
+
+ exp.index = CategoricalIndex(
+ exp.index, categories=cats.categories, ordered=cats.ordered
+ )
+ tm.assert_series_equal(result, exp)
+
+ codes = np.array([0, 0, 0, 1, 1, 1, 3, 3, 3])
+ cats = Categorical.from_codes(codes, [0, 1, 2, 3], ordered=True)
+
+ result = data.groupby(cats, observed=False).mean()
+ exp = data.groupby(codes, observed=False).mean().reindex(cats.categories)
+ exp.index = CategoricalIndex(
+ exp.index, categories=cats.categories, ordered=cats.ordered
+ )
+ tm.assert_series_equal(result, exp)
+
+ cats = Categorical(
+ ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
+ categories=["a", "b", "c", "d"],
+ ordered=True,
+ )
+ data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats})
+
+ result = data.groupby("b", observed=False).mean()
+ result = result["a"].values
+ exp = np.array([1, 2, 4, np.nan])
+ tm.assert_numpy_array_equal(result, exp)
+
+
+def test_groupby_empty_with_category():
+ # GH-9614
+ # test fix for when group by on None resulted in
+ # coercion of dtype categorical -> float
+ df = DataFrame({"A": [None] * 3, "B": Categorical(["train", "train", "test"])})
+ result = df.groupby("A").first()["B"]
+ expected = Series(
+ Categorical([], categories=["test", "train"]),
+ index=Series([], dtype="object", name="A"),
+ name="B",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_sort():
+ # https://stackoverflow.com/questions/23814368/sorting-pandas-
+ # categorical-labels-after-groupby
+ # This should result in a properly sorted Series so that the plot
+ # has a sorted x axis
+ # self.cat.groupby(['value_group'])['value_group'].count().plot(kind='bar')
+
+ df = DataFrame({"value": np.random.default_rng(2).integers(0, 10000, 100)})
+ labels = [f"{i} - {i+499}" for i in range(0, 10000, 500)]
+ cat_labels = Categorical(labels, labels)
+
+ df = df.sort_values(by=["value"], ascending=True)
+ df["value_group"] = pd.cut(
+ df.value, range(0, 10500, 500), right=False, labels=cat_labels
+ )
+
+ res = df.groupby(["value_group"], observed=False)["value_group"].count()
+ exp = res[sorted(res.index, key=lambda x: float(x.split()[0]))]
+ exp.index = CategoricalIndex(exp.index, name=exp.index.name)
+ tm.assert_series_equal(res, exp)
+
+
+@pytest.mark.parametrize("ordered", [True, False])
+def test_sort2(sort, ordered):
+ # dataframe groupby sort was being ignored # GH 8868
+ # GH#48749 - don't change order of categories
+ # GH#42482 - don't sort result when sort=False, even when ordered=True
+ df = DataFrame(
+ [
+ ["(7.5, 10]", 10, 10],
+ ["(7.5, 10]", 8, 20],
+ ["(2.5, 5]", 5, 30],
+ ["(5, 7.5]", 6, 40],
+ ["(2.5, 5]", 4, 50],
+ ["(0, 2.5]", 1, 60],
+ ["(5, 7.5]", 7, 70],
+ ],
+ columns=["range", "foo", "bar"],
+ )
+ df["range"] = Categorical(df["range"], ordered=ordered)
+ result = df.groupby("range", sort=sort, observed=False).first()
+
+ if sort:
+ data_values = [[1, 60], [5, 30], [6, 40], [10, 10]]
+ index_values = ["(0, 2.5]", "(2.5, 5]", "(5, 7.5]", "(7.5, 10]"]
+ else:
+ data_values = [[10, 10], [5, 30], [6, 40], [1, 60]]
+ index_values = ["(7.5, 10]", "(2.5, 5]", "(5, 7.5]", "(0, 2.5]"]
+ expected = DataFrame(
+ data_values,
+ columns=["foo", "bar"],
+ index=CategoricalIndex(index_values, name="range", ordered=ordered),
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("ordered", [True, False])
+def test_sort_datetimelike(sort, ordered):
+ # GH10505
+ # GH#42482 - don't sort result when sort=False, even when ordered=True
+
+ # use same data as test_groupby_sort_categorical, which category is
+ # corresponding to datetime.month
+ df = DataFrame(
+ {
+ "dt": [
+ datetime(2011, 7, 1),
+ datetime(2011, 7, 1),
+ datetime(2011, 2, 1),
+ datetime(2011, 5, 1),
+ datetime(2011, 2, 1),
+ datetime(2011, 1, 1),
+ datetime(2011, 5, 1),
+ ],
+ "foo": [10, 8, 5, 6, 4, 1, 7],
+ "bar": [10, 20, 30, 40, 50, 60, 70],
+ },
+ columns=["dt", "foo", "bar"],
+ )
+
+ # ordered=True
+ df["dt"] = Categorical(df["dt"], ordered=ordered)
+ if sort:
+ data_values = [[1, 60], [5, 30], [6, 40], [10, 10]]
+ index_values = [
+ datetime(2011, 1, 1),
+ datetime(2011, 2, 1),
+ datetime(2011, 5, 1),
+ datetime(2011, 7, 1),
+ ]
+ else:
+ data_values = [[10, 10], [5, 30], [6, 40], [1, 60]]
+ index_values = [
+ datetime(2011, 7, 1),
+ datetime(2011, 2, 1),
+ datetime(2011, 5, 1),
+ datetime(2011, 1, 1),
+ ]
+ expected = DataFrame(
+ data_values,
+ columns=["foo", "bar"],
+ index=CategoricalIndex(index_values, name="dt", ordered=ordered),
+ )
+ result = df.groupby("dt", sort=sort, observed=False).first()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_empty_sum():
+ # https://github.com/pandas-dev/pandas/issues/18678
+ df = DataFrame(
+ {"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"]), "B": [1, 2, 1]}
+ )
+ expected_idx = CategoricalIndex(["a", "b", "c"], name="A")
+
+ # 0 by default
+ result = df.groupby("A", observed=False).B.sum()
+ expected = Series([3, 1, 0], expected_idx, name="B")
+ tm.assert_series_equal(result, expected)
+
+ # min_count=0
+ result = df.groupby("A", observed=False).B.sum(min_count=0)
+ expected = Series([3, 1, 0], expected_idx, name="B")
+ tm.assert_series_equal(result, expected)
+
+ # min_count=1
+ result = df.groupby("A", observed=False).B.sum(min_count=1)
+ expected = Series([3, 1, np.nan], expected_idx, name="B")
+ tm.assert_series_equal(result, expected)
+
+ # min_count>1
+ result = df.groupby("A", observed=False).B.sum(min_count=2)
+ expected = Series([3, np.nan, np.nan], expected_idx, name="B")
+ tm.assert_series_equal(result, expected)
+
+
+def test_empty_prod():
+ # https://github.com/pandas-dev/pandas/issues/18678
+ df = DataFrame(
+ {"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"]), "B": [1, 2, 1]}
+ )
+
+ expected_idx = CategoricalIndex(["a", "b", "c"], name="A")
+
+ # 1 by default
+ result = df.groupby("A", observed=False).B.prod()
+ expected = Series([2, 1, 1], expected_idx, name="B")
+ tm.assert_series_equal(result, expected)
+
+ # min_count=0
+ result = df.groupby("A", observed=False).B.prod(min_count=0)
+ expected = Series([2, 1, 1], expected_idx, name="B")
+ tm.assert_series_equal(result, expected)
+
+ # min_count=1
+ result = df.groupby("A", observed=False).B.prod(min_count=1)
+ expected = Series([2, 1, np.nan], expected_idx, name="B")
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_multiindex_categorical_datetime():
+ # https://github.com/pandas-dev/pandas/issues/21390
+
+ df = DataFrame(
+ {
+ "key1": Categorical(list("abcbabcba")),
+ "key2": Categorical(
+ list(pd.date_range("2018-06-01 00", freq="1T", periods=3)) * 3
+ ),
+ "values": np.arange(9),
+ }
+ )
+ result = df.groupby(["key1", "key2"], observed=False).mean()
+
+ idx = MultiIndex.from_product(
+ [
+ Categorical(["a", "b", "c"]),
+ Categorical(pd.date_range("2018-06-01 00", freq="1T", periods=3)),
+ ],
+ names=["key1", "key2"],
+ )
+ expected = DataFrame({"values": [0, 4, 8, 3, 4, 5, 6, np.nan, 2]}, index=idx)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "as_index, expected",
+ [
+ (
+ True,
+ Series(
+ index=MultiIndex.from_arrays(
+ [Series([1, 1, 2], dtype="category"), [1, 2, 2]], names=["a", "b"]
+ ),
+ data=[1, 2, 3],
+ name="x",
+ ),
+ ),
+ (
+ False,
+ DataFrame(
+ {
+ "a": Series([1, 1, 2], dtype="category"),
+ "b": [1, 2, 2],
+ "x": [1, 2, 3],
+ }
+ ),
+ ),
+ ],
+)
+def test_groupby_agg_observed_true_single_column(as_index, expected):
+ # GH-23970
+ df = DataFrame(
+ {"a": Series([1, 1, 2], dtype="category"), "b": [1, 2, 2], "x": [1, 2, 3]}
+ )
+
+ result = df.groupby(["a", "b"], as_index=as_index, observed=True)["x"].sum()
+
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize("fill_value", [None, np.nan, pd.NaT])
+def test_shift(fill_value):
+ ct = Categorical(
+ ["a", "b", "c", "d"], categories=["a", "b", "c", "d"], ordered=False
+ )
+ expected = Categorical(
+ [None, "a", "b", "c"], categories=["a", "b", "c", "d"], ordered=False
+ )
+ res = ct.shift(1, fill_value=fill_value)
+ tm.assert_equal(res, expected)
+
+
+@pytest.fixture
+def df_cat(df):
+ """
+ DataFrame with multiple categorical columns and a column of integers.
+ Shortened so as not to contain all possible combinations of categories.
+ Useful for testing `observed` kwarg functionality on GroupBy objects.
+
+ Parameters
+ ----------
+ df: DataFrame
+ Non-categorical, longer DataFrame from another fixture, used to derive
+ this one
+
+ Returns
+ -------
+ df_cat: DataFrame
+ """
+ df_cat = df.copy()[:4] # leave out some groups
+ df_cat["A"] = df_cat["A"].astype("category")
+ df_cat["B"] = df_cat["B"].astype("category")
+ df_cat["C"] = Series([1, 2, 3, 4])
+ df_cat = df_cat.drop(["D"], axis=1)
+ return df_cat
+
+
+@pytest.mark.parametrize("operation", ["agg", "apply"])
+def test_seriesgroupby_observed_true(df_cat, operation):
+ # GH#24880
+ # GH#49223 - order of results was wrong when grouping by index levels
+ lev_a = Index(["bar", "bar", "foo", "foo"], dtype=df_cat["A"].dtype, name="A")
+ lev_b = Index(["one", "three", "one", "two"], dtype=df_cat["B"].dtype, name="B")
+ index = MultiIndex.from_arrays([lev_a, lev_b])
+ expected = Series(data=[2, 4, 1, 3], index=index, name="C").sort_index()
+
+ grouped = df_cat.groupby(["A", "B"], observed=True)["C"]
+ msg = "using np.sum" if operation == "apply" else "using SeriesGroupBy.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result = getattr(grouped, operation)(sum)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("operation", ["agg", "apply"])
+@pytest.mark.parametrize("observed", [False, None])
+def test_seriesgroupby_observed_false_or_none(df_cat, observed, operation):
+ # GH 24880
+ # GH#49223 - order of results was wrong when grouping by index levels
+ index, _ = MultiIndex.from_product(
+ [
+ CategoricalIndex(["bar", "foo"], ordered=False),
+ CategoricalIndex(["one", "three", "two"], ordered=False),
+ ],
+ names=["A", "B"],
+ ).sortlevel()
+
+ expected = Series(data=[2, 4, np.nan, 1, np.nan, 3], index=index, name="C")
+ if operation == "agg":
+ msg = "The 'downcast' keyword in fillna is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = expected.fillna(0, downcast="infer")
+ grouped = df_cat.groupby(["A", "B"], observed=observed)["C"]
+ msg = "using SeriesGroupBy.sum" if operation == "agg" else "using np.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result = getattr(grouped, operation)(sum)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "observed, index, data",
+ [
+ (
+ True,
+ MultiIndex.from_arrays(
+ [
+ Index(["bar"] * 4 + ["foo"] * 4, dtype="category", name="A"),
+ Index(
+ ["one", "one", "three", "three", "one", "one", "two", "two"],
+ dtype="category",
+ name="B",
+ ),
+ Index(["min", "max"] * 4),
+ ]
+ ),
+ [2, 2, 4, 4, 1, 1, 3, 3],
+ ),
+ (
+ False,
+ MultiIndex.from_product(
+ [
+ CategoricalIndex(["bar", "foo"], ordered=False),
+ CategoricalIndex(["one", "three", "two"], ordered=False),
+ Index(["min", "max"]),
+ ],
+ names=["A", "B", None],
+ ),
+ [2, 2, 4, 4, np.nan, np.nan, 1, 1, np.nan, np.nan, 3, 3],
+ ),
+ (
+ None,
+ MultiIndex.from_product(
+ [
+ CategoricalIndex(["bar", "foo"], ordered=False),
+ CategoricalIndex(["one", "three", "two"], ordered=False),
+ Index(["min", "max"]),
+ ],
+ names=["A", "B", None],
+ ),
+ [2, 2, 4, 4, np.nan, np.nan, 1, 1, np.nan, np.nan, 3, 3],
+ ),
+ ],
+)
+def test_seriesgroupby_observed_apply_dict(df_cat, observed, index, data):
+ # GH 24880
+ expected = Series(data=data, index=index, name="C")
+ result = df_cat.groupby(["A", "B"], observed=observed)["C"].apply(
+ lambda x: {"min": x.min(), "max": x.max()}
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_categorical_series_dataframe_consistent(df_cat):
+ # GH 20416
+ expected = df_cat.groupby(["A", "B"], observed=False)["C"].mean()
+ result = df_cat.groupby(["A", "B"], observed=False).mean()["C"]
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("code", [([1, 0, 0]), ([0, 0, 0])])
+def test_groupby_categorical_axis_1(code):
+ # GH 13420
+ df = DataFrame({"a": [1, 2, 3, 4], "b": [-1, -2, -3, -4], "c": [5, 6, 7, 8]})
+ cat = Categorical.from_codes(code, categories=list("abc"))
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby(cat, axis=1, observed=False)
+ result = gb.mean()
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb2 = df.T.groupby(cat, axis=0, observed=False)
+ expected = gb2.mean().T
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_cat_preserves_structure(observed, ordered):
+ # GH 28787
+ df = DataFrame(
+ {"Name": Categorical(["Bob", "Greg"], ordered=ordered), "Item": [1, 2]},
+ columns=["Name", "Item"],
+ )
+ expected = df.copy()
+
+ result = (
+ df.groupby("Name", observed=observed)
+ .agg(DataFrame.sum, skipna=True)
+ .reset_index()
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_get_nonexistent_category():
+ # Accessing a Category that is not in the dataframe
+ df = DataFrame({"var": ["a", "a", "b", "b"], "val": range(4)})
+ with pytest.raises(KeyError, match="'vau'"):
+ df.groupby("var").apply(
+ lambda rows: DataFrame(
+ {"var": [rows.iloc[-1]["var"]], "val": [rows.iloc[-1]["vau"]]}
+ )
+ )
+
+
+def test_series_groupby_on_2_categoricals_unobserved(reduction_func, observed):
+ # GH 17605
+ if reduction_func == "ngroup":
+ pytest.skip("ngroup is not truly a reduction")
+
+ df = DataFrame(
+ {
+ "cat_1": Categorical(list("AABB"), categories=list("ABCD")),
+ "cat_2": Categorical(list("AB") * 2, categories=list("ABCD")),
+ "value": [0.1] * 4,
+ }
+ )
+ args = get_groupby_method_args(reduction_func, df)
+
+ expected_length = 4 if observed else 16
+
+ series_groupby = df.groupby(["cat_1", "cat_2"], observed=observed)["value"]
+
+ if reduction_func == "corrwith":
+ # TODO: implemented SeriesGroupBy.corrwith. See GH 32293
+ assert not hasattr(series_groupby, reduction_func)
+ return
+
+ agg = getattr(series_groupby, reduction_func)
+ result = agg(*args)
+
+ assert len(result) == expected_length
+
+
+def test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans(
+ reduction_func, request
+):
+ # GH 17605
+ # Tests whether the unobserved categories in the result contain 0 or NaN
+
+ if reduction_func == "ngroup":
+ pytest.skip("ngroup is not truly a reduction")
+
+ if reduction_func == "corrwith": # GH 32293
+ mark = pytest.mark.xfail(
+ reason="TODO: implemented SeriesGroupBy.corrwith. See GH 32293"
+ )
+ request.node.add_marker(mark)
+
+ df = DataFrame(
+ {
+ "cat_1": Categorical(list("AABB"), categories=list("ABC")),
+ "cat_2": Categorical(list("AB") * 2, categories=list("ABC")),
+ "value": [0.1] * 4,
+ }
+ )
+ unobserved = [tuple("AC"), tuple("BC"), tuple("CA"), tuple("CB"), tuple("CC")]
+ args = get_groupby_method_args(reduction_func, df)
+
+ series_groupby = df.groupby(["cat_1", "cat_2"], observed=False)["value"]
+ agg = getattr(series_groupby, reduction_func)
+ result = agg(*args)
+
+ zero_or_nan = _results_for_groupbys_with_missing_categories[reduction_func]
+
+ for idx in unobserved:
+ val = result.loc[idx]
+ assert (pd.isna(zero_or_nan) and pd.isna(val)) or (val == zero_or_nan)
+
+ # If we expect unobserved values to be zero, we also expect the dtype to be int.
+ # Except for .sum(). If the observed categories sum to dtype=float (i.e. their
+ # sums have decimals), then the zeros for the missing categories should also be
+ # floats.
+ if zero_or_nan == 0 and reduction_func != "sum":
+ assert np.issubdtype(result.dtype, np.integer)
+
+
+def test_dataframe_groupby_on_2_categoricals_when_observed_is_true(reduction_func):
+ # GH 23865
+ # GH 27075
+ # Ensure that df.groupby, when 'by' is two Categorical variables,
+ # does not return the categories that are not in df when observed=True
+ if reduction_func == "ngroup":
+ pytest.skip("ngroup does not return the Categories on the index")
+
+ df = DataFrame(
+ {
+ "cat_1": Categorical(list("AABB"), categories=list("ABC")),
+ "cat_2": Categorical(list("1111"), categories=list("12")),
+ "value": [0.1, 0.1, 0.1, 0.1],
+ }
+ )
+ unobserved_cats = [("A", "2"), ("B", "2"), ("C", "1"), ("C", "2")]
+
+ df_grp = df.groupby(["cat_1", "cat_2"], observed=True)
+
+ args = get_groupby_method_args(reduction_func, df)
+ res = getattr(df_grp, reduction_func)(*args)
+
+ for cat in unobserved_cats:
+ assert cat not in res.index
+
+
+@pytest.mark.parametrize("observed", [False, None])
+def test_dataframe_groupby_on_2_categoricals_when_observed_is_false(
+ reduction_func, observed
+):
+ # GH 23865
+ # GH 27075
+ # Ensure that df.groupby, when 'by' is two Categorical variables,
+ # returns the categories that are not in df when observed=False/None
+
+ if reduction_func == "ngroup":
+ pytest.skip("ngroup does not return the Categories on the index")
+
+ df = DataFrame(
+ {
+ "cat_1": Categorical(list("AABB"), categories=list("ABC")),
+ "cat_2": Categorical(list("1111"), categories=list("12")),
+ "value": [0.1, 0.1, 0.1, 0.1],
+ }
+ )
+ unobserved_cats = [("A", "2"), ("B", "2"), ("C", "1"), ("C", "2")]
+
+ df_grp = df.groupby(["cat_1", "cat_2"], observed=observed)
+
+ args = get_groupby_method_args(reduction_func, df)
+ res = getattr(df_grp, reduction_func)(*args)
+
+ expected = _results_for_groupbys_with_missing_categories[reduction_func]
+
+ if expected is np.nan:
+ assert res.loc[unobserved_cats].isnull().all().all()
+ else:
+ assert (res.loc[unobserved_cats] == expected).all().all()
+
+
+def test_series_groupby_categorical_aggregation_getitem():
+ # GH 8870
+ d = {"foo": [10, 8, 4, 1], "bar": [10, 20, 30, 40], "baz": ["d", "c", "d", "c"]}
+ df = DataFrame(d)
+ cat = pd.cut(df["foo"], np.linspace(0, 20, 5))
+ df["range"] = cat
+ groups = df.groupby(["range", "baz"], as_index=True, sort=True, observed=False)
+ result = groups["foo"].agg("mean")
+ expected = groups.agg("mean")["foo"]
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "func, expected_values",
+ [(Series.nunique, [1, 1, 2]), (Series.count, [1, 2, 2])],
+)
+def test_groupby_agg_categorical_columns(func, expected_values):
+ # 31256
+ df = DataFrame(
+ {
+ "id": [0, 1, 2, 3, 4],
+ "groups": [0, 1, 1, 2, 2],
+ "value": Categorical([0, 0, 0, 0, 1]),
+ }
+ ).set_index("id")
+ result = df.groupby("groups").agg(func)
+
+ expected = DataFrame(
+ {"value": expected_values}, index=Index([0, 1, 2], name="groups")
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_agg_non_numeric():
+ df = DataFrame({"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"])})
+ expected = DataFrame({"A": [2, 1]}, index=np.array([1, 2]))
+
+ result = df.groupby([1, 2, 1]).agg(Series.nunique)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby([1, 2, 1]).nunique()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", ["first", "last"])
+def test_groupby_first_returned_categorical_instead_of_dataframe(func):
+ # GH 28641: groupby drops index, when grouping over categorical column with
+ # first/last. Renamed Categorical instead of DataFrame previously.
+ df = DataFrame({"A": [1997], "B": Series(["b"], dtype="category").cat.as_ordered()})
+ df_grouped = df.groupby("A")["B"]
+ result = getattr(df_grouped, func)()
+
+ # ordered categorical dtype should be preserved
+ expected = Series(
+ ["b"], index=Index([1997], name="A"), name="B", dtype=df["B"].dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_read_only_category_no_sort():
+ # GH33410
+ cats = np.array([1, 2])
+ cats.flags.writeable = False
+ df = DataFrame(
+ {"a": [1, 3, 5, 7], "b": Categorical([1, 1, 2, 2], categories=Index(cats))}
+ )
+ expected = DataFrame(data={"a": [2.0, 6.0]}, index=CategoricalIndex(cats, name="b"))
+ result = df.groupby("b", sort=False, observed=False).mean()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_sorted_missing_category_values():
+ # GH 28597
+ df = DataFrame(
+ {
+ "foo": [
+ "small",
+ "large",
+ "large",
+ "large",
+ "medium",
+ "large",
+ "large",
+ "medium",
+ ],
+ "bar": ["C", "A", "A", "C", "A", "C", "A", "C"],
+ }
+ )
+ df["foo"] = (
+ df["foo"]
+ .astype("category")
+ .cat.set_categories(["tiny", "small", "medium", "large"], ordered=True)
+ )
+
+ expected = DataFrame(
+ {
+ "tiny": {"A": 0, "C": 0},
+ "small": {"A": 0, "C": 1},
+ "medium": {"A": 1, "C": 1},
+ "large": {"A": 3, "C": 2},
+ }
+ )
+ expected = expected.rename_axis("bar", axis="index")
+ expected.columns = CategoricalIndex(
+ ["tiny", "small", "medium", "large"],
+ categories=["tiny", "small", "medium", "large"],
+ ordered=True,
+ name="foo",
+ dtype="category",
+ )
+
+ result = df.groupby(["bar", "foo"], observed=False).size().unstack()
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_agg_cython_category_not_implemented_fallback():
+ # https://github.com/pandas-dev/pandas/issues/31450
+ df = DataFrame({"col_num": [1, 1, 2, 3]})
+ df["col_cat"] = df["col_num"].astype("category")
+
+ result = df.groupby("col_num").col_cat.first()
+
+ # ordered categorical dtype should definitely be preserved;
+ # this is unordered, so is less-clear case (if anything, it should raise)
+ expected = Series(
+ [1, 2, 3],
+ index=Index([1, 2, 3], name="col_num"),
+ name="col_cat",
+ dtype=df["col_cat"].dtype,
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = df.groupby("col_num").agg({"col_cat": "first"})
+ expected = expected.to_frame()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_aggregate_categorical_with_isnan():
+ # GH 29837
+ df = DataFrame(
+ {
+ "A": [1, 1, 1, 1],
+ "B": [1, 2, 1, 2],
+ "numerical_col": [0.1, 0.2, np.nan, 0.3],
+ "object_col": ["foo", "bar", "foo", "fee"],
+ "categorical_col": ["foo", "bar", "foo", "fee"],
+ }
+ )
+
+ df = df.astype({"categorical_col": "category"})
+
+ result = df.groupby(["A", "B"]).agg(lambda df: df.isna().sum())
+ index = MultiIndex.from_arrays([[1, 1], [1, 2]], names=("A", "B"))
+ expected = DataFrame(
+ data={
+ "numerical_col": [1, 0],
+ "object_col": [0, 0],
+ "categorical_col": [0, 0],
+ },
+ index=index,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_categorical_transform():
+ # GH 29037
+ df = DataFrame(
+ {
+ "package_id": [1, 1, 1, 2, 2, 3],
+ "status": [
+ "Waiting",
+ "OnTheWay",
+ "Delivered",
+ "Waiting",
+ "OnTheWay",
+ "Waiting",
+ ],
+ }
+ )
+
+ delivery_status_type = pd.CategoricalDtype(
+ categories=["Waiting", "OnTheWay", "Delivered"], ordered=True
+ )
+ df["status"] = df["status"].astype(delivery_status_type)
+ msg = "using SeriesGroupBy.max"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ df["last_status"] = df.groupby("package_id")["status"].transform(max)
+ result = df.copy()
+
+ expected = DataFrame(
+ {
+ "package_id": [1, 1, 1, 2, 2, 3],
+ "status": [
+ "Waiting",
+ "OnTheWay",
+ "Delivered",
+ "Waiting",
+ "OnTheWay",
+ "Waiting",
+ ],
+ "last_status": [
+ "Delivered",
+ "Delivered",
+ "Delivered",
+ "OnTheWay",
+ "OnTheWay",
+ "Waiting",
+ ],
+ }
+ )
+
+ expected["status"] = expected["status"].astype(delivery_status_type)
+
+ # .transform(max) should preserve ordered categoricals
+ expected["last_status"] = expected["last_status"].astype(delivery_status_type)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", ["first", "last"])
+def test_series_groupby_first_on_categorical_col_grouped_on_2_categoricals(
+ func: str, observed: bool
+):
+ # GH 34951
+ cat = Categorical([0, 0, 1, 1])
+ val = [0, 1, 1, 0]
+ df = DataFrame({"a": cat, "b": cat, "c": val})
+
+ cat2 = Categorical([0, 1])
+ idx = MultiIndex.from_product([cat2, cat2], names=["a", "b"])
+ expected_dict = {
+ "first": Series([0, np.nan, np.nan, 1], idx, name="c"),
+ "last": Series([1, np.nan, np.nan, 0], idx, name="c"),
+ }
+
+ expected = expected_dict[func]
+ if observed:
+ expected = expected.dropna().astype(np.int64)
+
+ srs_grp = df.groupby(["a", "b"], observed=observed)["c"]
+ result = getattr(srs_grp, func)()
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", ["first", "last"])
+def test_df_groupby_first_on_categorical_col_grouped_on_2_categoricals(
+ func: str, observed: bool
+):
+ # GH 34951
+ cat = Categorical([0, 0, 1, 1])
+ val = [0, 1, 1, 0]
+ df = DataFrame({"a": cat, "b": cat, "c": val})
+
+ cat2 = Categorical([0, 1])
+ idx = MultiIndex.from_product([cat2, cat2], names=["a", "b"])
+ expected_dict = {
+ "first": Series([0, np.nan, np.nan, 1], idx, name="c"),
+ "last": Series([1, np.nan, np.nan, 0], idx, name="c"),
+ }
+
+ expected = expected_dict[func].to_frame()
+ if observed:
+ expected = expected.dropna().astype(np.int64)
+
+ df_grp = df.groupby(["a", "b"], observed=observed)
+ result = getattr(df_grp, func)()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_categorical_indices_unused_categories():
+ # GH#38642
+ df = DataFrame(
+ {
+ "key": Categorical(["b", "b", "a"], categories=["a", "b", "c"]),
+ "col": range(3),
+ }
+ )
+ grouped = df.groupby("key", sort=False, observed=False)
+ result = grouped.indices
+ expected = {
+ "b": np.array([0, 1], dtype="intp"),
+ "a": np.array([2], dtype="intp"),
+ "c": np.array([], dtype="intp"),
+ }
+ assert result.keys() == expected.keys()
+ for key in result.keys():
+ tm.assert_numpy_array_equal(result[key], expected[key])
+
+
+@pytest.mark.parametrize("func", ["first", "last"])
+def test_groupby_last_first_preserve_categoricaldtype(func):
+ # GH#33090
+ df = DataFrame({"a": [1, 2, 3]})
+ df["b"] = df["a"].astype("category")
+ result = getattr(df.groupby("a")["b"], func)()
+ expected = Series(
+ Categorical([1, 2, 3]), name="b", index=Index([1, 2, 3], name="a")
+ )
+ tm.assert_series_equal(expected, result)
+
+
+def test_groupby_categorical_observed_nunique():
+ # GH#45128
+ df = DataFrame({"a": [1, 2], "b": [1, 2], "c": [10, 11]})
+ df = df.astype(dtype={"a": "category", "b": "category"})
+ result = df.groupby(["a", "b"], observed=True).nunique()["c"]
+ expected = Series(
+ [1, 1],
+ index=MultiIndex.from_arrays(
+ [CategoricalIndex([1, 2], name="a"), CategoricalIndex([1, 2], name="b")]
+ ),
+ name="c",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_categorical_aggregate_functions():
+ # GH#37275
+ dtype = pd.CategoricalDtype(categories=["small", "big"], ordered=True)
+ df = DataFrame(
+ [[1, "small"], [1, "big"], [2, "small"]], columns=["grp", "description"]
+ ).astype({"description": dtype})
+
+ result = df.groupby("grp")["description"].max()
+ expected = Series(
+ ["big", "small"],
+ index=Index([1, 2], name="grp"),
+ name="description",
+ dtype=pd.CategoricalDtype(categories=["small", "big"], ordered=True),
+ )
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_categorical_dropna(observed, dropna):
+ # GH#48645 - dropna should have no impact on the result when there are no NA values
+ cat = Categorical([1, 2], categories=[1, 2, 3])
+ df = DataFrame({"x": Categorical([1, 2], categories=[1, 2, 3]), "y": [3, 4]})
+ gb = df.groupby("x", observed=observed, dropna=dropna)
+ result = gb.sum()
+
+ if observed:
+ expected = DataFrame({"y": [3, 4]}, index=cat)
+ else:
+ index = CategoricalIndex([1, 2, 3], [1, 2, 3])
+ expected = DataFrame({"y": [3, 4, 0]}, index=index)
+ expected.index.name = "x"
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("index_kind", ["range", "single", "multi"])
+@pytest.mark.parametrize("ordered", [True, False])
+def test_category_order_reducer(
+ request, as_index, sort, observed, reduction_func, index_kind, ordered
+):
+ # GH#48749
+ if (
+ reduction_func in ("idxmax", "idxmin")
+ and not observed
+ and index_kind != "multi"
+ ):
+ msg = "GH#10694 - idxmax/min fail with unused categories"
+ request.node.add_marker(pytest.mark.xfail(reason=msg))
+ elif reduction_func == "corrwith" and not as_index:
+ msg = "GH#49950 - corrwith with as_index=False may not have grouping column"
+ request.node.add_marker(pytest.mark.xfail(reason=msg))
+ elif index_kind != "range" and not as_index:
+ pytest.skip(reason="Result doesn't have categories, nothing to test")
+ df = DataFrame(
+ {
+ "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered),
+ "b": range(4),
+ }
+ )
+ if index_kind == "range":
+ keys = ["a"]
+ elif index_kind == "single":
+ keys = ["a"]
+ df = df.set_index(keys)
+ elif index_kind == "multi":
+ keys = ["a", "a2"]
+ df["a2"] = df["a"]
+ df = df.set_index(keys)
+ args = get_groupby_method_args(reduction_func, df)
+ gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed)
+ op_result = getattr(gb, reduction_func)(*args)
+ if as_index:
+ result = op_result.index.get_level_values("a").categories
+ else:
+ result = op_result["a"].cat.categories
+ expected = Index([1, 4, 3, 2])
+ tm.assert_index_equal(result, expected)
+
+ if index_kind == "multi":
+ result = op_result.index.get_level_values("a2").categories
+ tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize("index_kind", ["single", "multi"])
+@pytest.mark.parametrize("ordered", [True, False])
+def test_category_order_transformer(
+ as_index, sort, observed, transformation_func, index_kind, ordered
+):
+ # GH#48749
+ df = DataFrame(
+ {
+ "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered),
+ "b": range(4),
+ }
+ )
+ if index_kind == "single":
+ keys = ["a"]
+ df = df.set_index(keys)
+ elif index_kind == "multi":
+ keys = ["a", "a2"]
+ df["a2"] = df["a"]
+ df = df.set_index(keys)
+ args = get_groupby_method_args(transformation_func, df)
+ gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed)
+ op_result = getattr(gb, transformation_func)(*args)
+ result = op_result.index.get_level_values("a").categories
+ expected = Index([1, 4, 3, 2])
+ tm.assert_index_equal(result, expected)
+
+ if index_kind == "multi":
+ result = op_result.index.get_level_values("a2").categories
+ tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize("index_kind", ["range", "single", "multi"])
+@pytest.mark.parametrize("method", ["head", "tail"])
+@pytest.mark.parametrize("ordered", [True, False])
+def test_category_order_head_tail(
+ as_index, sort, observed, method, index_kind, ordered
+):
+ # GH#48749
+ df = DataFrame(
+ {
+ "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered),
+ "b": range(4),
+ }
+ )
+ if index_kind == "range":
+ keys = ["a"]
+ elif index_kind == "single":
+ keys = ["a"]
+ df = df.set_index(keys)
+ elif index_kind == "multi":
+ keys = ["a", "a2"]
+ df["a2"] = df["a"]
+ df = df.set_index(keys)
+ gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed)
+ op_result = getattr(gb, method)()
+ if index_kind == "range":
+ result = op_result["a"].cat.categories
+ else:
+ result = op_result.index.get_level_values("a").categories
+ expected = Index([1, 4, 3, 2])
+ tm.assert_index_equal(result, expected)
+
+ if index_kind == "multi":
+ result = op_result.index.get_level_values("a2").categories
+ tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize("index_kind", ["range", "single", "multi"])
+@pytest.mark.parametrize("method", ["apply", "agg", "transform"])
+@pytest.mark.parametrize("ordered", [True, False])
+def test_category_order_apply(as_index, sort, observed, method, index_kind, ordered):
+ # GH#48749
+ if (method == "transform" and index_kind == "range") or (
+ not as_index and index_kind != "range"
+ ):
+ pytest.skip("No categories in result, nothing to test")
+ df = DataFrame(
+ {
+ "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered),
+ "b": range(4),
+ }
+ )
+ if index_kind == "range":
+ keys = ["a"]
+ elif index_kind == "single":
+ keys = ["a"]
+ df = df.set_index(keys)
+ elif index_kind == "multi":
+ keys = ["a", "a2"]
+ df["a2"] = df["a"]
+ df = df.set_index(keys)
+ gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed)
+ op_result = getattr(gb, method)(lambda x: x.sum(numeric_only=True))
+ if (method == "transform" or not as_index) and index_kind == "range":
+ result = op_result["a"].cat.categories
+ else:
+ result = op_result.index.get_level_values("a").categories
+ expected = Index([1, 4, 3, 2])
+ tm.assert_index_equal(result, expected)
+
+ if index_kind == "multi":
+ result = op_result.index.get_level_values("a2").categories
+ tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize("index_kind", ["range", "single", "multi"])
+def test_many_categories(as_index, sort, index_kind, ordered):
+ # GH#48749 - Test when the grouper has many categories
+ if index_kind != "range" and not as_index:
+ pytest.skip(reason="Result doesn't have categories, nothing to test")
+ categories = np.arange(9999, -1, -1)
+ grouper = Categorical([2, 1, 2, 3], categories=categories, ordered=ordered)
+ df = DataFrame({"a": grouper, "b": range(4)})
+ if index_kind == "range":
+ keys = ["a"]
+ elif index_kind == "single":
+ keys = ["a"]
+ df = df.set_index(keys)
+ elif index_kind == "multi":
+ keys = ["a", "a2"]
+ df["a2"] = df["a"]
+ df = df.set_index(keys)
+ gb = df.groupby(keys, as_index=as_index, sort=sort, observed=True)
+ result = gb.sum()
+
+ # Test is setup so that data and index are the same values
+ data = [3, 2, 1] if sort else [2, 1, 3]
+
+ index = CategoricalIndex(
+ data, categories=grouper.categories, ordered=ordered, name="a"
+ )
+ if as_index:
+ expected = DataFrame({"b": data})
+ if index_kind == "multi":
+ expected.index = MultiIndex.from_frame(DataFrame({"a": index, "a2": index}))
+ else:
+ expected.index = index
+ elif index_kind == "multi":
+ expected = DataFrame({"a": Series(index), "a2": Series(index), "b": data})
+ else:
+ expected = DataFrame({"a": Series(index), "b": data})
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("cat_columns", ["a", "b", ["a", "b"]])
+@pytest.mark.parametrize("keys", ["a", "b", ["a", "b"]])
+def test_groupby_default_depr(cat_columns, keys):
+ # GH#43999
+ df = DataFrame({"a": [1, 1, 2, 3], "b": [4, 5, 6, 7]})
+ df[cat_columns] = df[cat_columns].astype("category")
+ msg = "The default of observed=False is deprecated"
+ klass = FutureWarning if set(cat_columns) & set(keys) else None
+ with tm.assert_produces_warning(klass, match=msg):
+ df.groupby(keys)
+
+
+@pytest.mark.parametrize("test_series", [True, False])
+@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]])
+def test_agg_list(request, as_index, observed, reduction_func, test_series, keys):
+ # GH#52760
+ if test_series and reduction_func == "corrwith":
+ assert not hasattr(SeriesGroupBy, "corrwith")
+ pytest.skip("corrwith not implemented for SeriesGroupBy")
+ elif reduction_func == "corrwith":
+ msg = "GH#32293: attempts to call SeriesGroupBy.corrwith"
+ request.node.add_marker(pytest.mark.xfail(reason=msg))
+ elif (
+ reduction_func == "nunique"
+ and not test_series
+ and len(keys) != 1
+ and not observed
+ and not as_index
+ ):
+ msg = "GH#52848 - raises a ValueError"
+ request.node.add_marker(pytest.mark.xfail(reason=msg))
+
+ df = DataFrame({"a1": [0, 0, 1], "a2": [2, 3, 3], "b": [4, 5, 6]})
+ df = df.astype({"a1": "category", "a2": "category"})
+ if "a2" not in keys:
+ df = df.drop(columns="a2")
+ gb = df.groupby(by=keys, as_index=as_index, observed=observed)
+ if test_series:
+ gb = gb["b"]
+ args = get_groupby_method_args(reduction_func, df)
+
+ result = gb.agg([reduction_func], *args)
+ expected = getattr(gb, reduction_func)(*args)
+
+ if as_index and (test_series or reduction_func == "size"):
+ expected = expected.to_frame(reduction_func)
+ if not test_series:
+ expected.columns = MultiIndex.from_tuples(
+ [(ind, "") for ind in expected.columns[:-1]] + [("b", reduction_func)]
+ )
+ elif not as_index:
+ expected.columns = keys + [reduction_func]
+
+ tm.assert_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_counting.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_counting.py
new file mode 100644
index 0000000000000000000000000000000000000000..885e7848b76cbc5c286c1c6f7188f3c9de541d29
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_counting.py
@@ -0,0 +1,392 @@
+from itertools import product
+from string import ascii_lowercase
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Period,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+
+
+class TestCounting:
+ def test_cumcount(self):
+ df = DataFrame([["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"])
+ g = df.groupby("A")
+ sg = g.A
+
+ expected = Series([0, 1, 2, 0, 3])
+
+ tm.assert_series_equal(expected, g.cumcount())
+ tm.assert_series_equal(expected, sg.cumcount())
+
+ def test_cumcount_empty(self):
+ ge = DataFrame().groupby(level=0)
+ se = Series(dtype=object).groupby(level=0)
+
+ # edge case, as this is usually considered float
+ e = Series(dtype="int64")
+
+ tm.assert_series_equal(e, ge.cumcount())
+ tm.assert_series_equal(e, se.cumcount())
+
+ def test_cumcount_dupe_index(self):
+ df = DataFrame(
+ [["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=[0] * 5
+ )
+ g = df.groupby("A")
+ sg = g.A
+
+ expected = Series([0, 1, 2, 0, 3], index=[0] * 5)
+
+ tm.assert_series_equal(expected, g.cumcount())
+ tm.assert_series_equal(expected, sg.cumcount())
+
+ def test_cumcount_mi(self):
+ mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]])
+ df = DataFrame([["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=mi)
+ g = df.groupby("A")
+ sg = g.A
+
+ expected = Series([0, 1, 2, 0, 3], index=mi)
+
+ tm.assert_series_equal(expected, g.cumcount())
+ tm.assert_series_equal(expected, sg.cumcount())
+
+ def test_cumcount_groupby_not_col(self):
+ df = DataFrame(
+ [["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=[0] * 5
+ )
+ g = df.groupby([0, 0, 0, 1, 0])
+ sg = g.A
+
+ expected = Series([0, 1, 2, 0, 3], index=[0] * 5)
+
+ tm.assert_series_equal(expected, g.cumcount())
+ tm.assert_series_equal(expected, sg.cumcount())
+
+ def test_ngroup(self):
+ df = DataFrame({"A": list("aaaba")})
+ g = df.groupby("A")
+ sg = g.A
+
+ expected = Series([0, 0, 0, 1, 0])
+
+ tm.assert_series_equal(expected, g.ngroup())
+ tm.assert_series_equal(expected, sg.ngroup())
+
+ def test_ngroup_distinct(self):
+ df = DataFrame({"A": list("abcde")})
+ g = df.groupby("A")
+ sg = g.A
+
+ expected = Series(range(5), dtype="int64")
+
+ tm.assert_series_equal(expected, g.ngroup())
+ tm.assert_series_equal(expected, sg.ngroup())
+
+ def test_ngroup_one_group(self):
+ df = DataFrame({"A": [0] * 5})
+ g = df.groupby("A")
+ sg = g.A
+
+ expected = Series([0] * 5)
+
+ tm.assert_series_equal(expected, g.ngroup())
+ tm.assert_series_equal(expected, sg.ngroup())
+
+ def test_ngroup_empty(self):
+ ge = DataFrame().groupby(level=0)
+ se = Series(dtype=object).groupby(level=0)
+
+ # edge case, as this is usually considered float
+ e = Series(dtype="int64")
+
+ tm.assert_series_equal(e, ge.ngroup())
+ tm.assert_series_equal(e, se.ngroup())
+
+ def test_ngroup_series_matches_frame(self):
+ df = DataFrame({"A": list("aaaba")})
+ s = Series(list("aaaba"))
+
+ tm.assert_series_equal(df.groupby(s).ngroup(), s.groupby(s).ngroup())
+
+ def test_ngroup_dupe_index(self):
+ df = DataFrame({"A": list("aaaba")}, index=[0] * 5)
+ g = df.groupby("A")
+ sg = g.A
+
+ expected = Series([0, 0, 0, 1, 0], index=[0] * 5)
+
+ tm.assert_series_equal(expected, g.ngroup())
+ tm.assert_series_equal(expected, sg.ngroup())
+
+ def test_ngroup_mi(self):
+ mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]])
+ df = DataFrame({"A": list("aaaba")}, index=mi)
+ g = df.groupby("A")
+ sg = g.A
+ expected = Series([0, 0, 0, 1, 0], index=mi)
+
+ tm.assert_series_equal(expected, g.ngroup())
+ tm.assert_series_equal(expected, sg.ngroup())
+
+ def test_ngroup_groupby_not_col(self):
+ df = DataFrame({"A": list("aaaba")}, index=[0] * 5)
+ g = df.groupby([0, 0, 0, 1, 0])
+ sg = g.A
+
+ expected = Series([0, 0, 0, 1, 0], index=[0] * 5)
+
+ tm.assert_series_equal(expected, g.ngroup())
+ tm.assert_series_equal(expected, sg.ngroup())
+
+ def test_ngroup_descending(self):
+ df = DataFrame(["a", "a", "b", "a", "b"], columns=["A"])
+ g = df.groupby(["A"])
+
+ ascending = Series([0, 0, 1, 0, 1])
+ descending = Series([1, 1, 0, 1, 0])
+
+ tm.assert_series_equal(descending, (g.ngroups - 1) - ascending)
+ tm.assert_series_equal(ascending, g.ngroup(ascending=True))
+ tm.assert_series_equal(descending, g.ngroup(ascending=False))
+
+ def test_ngroup_matches_cumcount(self):
+ # verify one manually-worked out case works
+ df = DataFrame(
+ [["a", "x"], ["a", "y"], ["b", "x"], ["a", "x"], ["b", "y"]],
+ columns=["A", "X"],
+ )
+ g = df.groupby(["A", "X"])
+ g_ngroup = g.ngroup()
+ g_cumcount = g.cumcount()
+ expected_ngroup = Series([0, 1, 2, 0, 3])
+ expected_cumcount = Series([0, 0, 0, 1, 0])
+
+ tm.assert_series_equal(g_ngroup, expected_ngroup)
+ tm.assert_series_equal(g_cumcount, expected_cumcount)
+
+ def test_ngroup_cumcount_pair(self):
+ # brute force comparison for all small series
+ for p in product(range(3), repeat=4):
+ df = DataFrame({"a": p})
+ g = df.groupby(["a"])
+
+ order = sorted(set(p))
+ ngroupd = [order.index(val) for val in p]
+ cumcounted = [p[:i].count(val) for i, val in enumerate(p)]
+
+ tm.assert_series_equal(g.ngroup(), Series(ngroupd))
+ tm.assert_series_equal(g.cumcount(), Series(cumcounted))
+
+ def test_ngroup_respects_groupby_order(self, sort):
+ df = DataFrame({"a": np.random.default_rng(2).choice(list("abcdef"), 100)})
+ g = df.groupby("a", sort=sort)
+ df["group_id"] = -1
+ df["group_index"] = -1
+
+ for i, (_, group) in enumerate(g):
+ df.loc[group.index, "group_id"] = i
+ for j, ind in enumerate(group.index):
+ df.loc[ind, "group_index"] = j
+
+ tm.assert_series_equal(Series(df["group_id"].values), g.ngroup())
+ tm.assert_series_equal(Series(df["group_index"].values), g.cumcount())
+
+ @pytest.mark.parametrize(
+ "datetimelike",
+ [
+ [Timestamp(f"2016-05-{i:02d} 20:09:25+00:00") for i in range(1, 4)],
+ [Timestamp(f"2016-05-{i:02d} 20:09:25") for i in range(1, 4)],
+ [Timestamp(f"2016-05-{i:02d} 20:09:25", tz="UTC") for i in range(1, 4)],
+ [Timedelta(x, unit="h") for x in range(1, 4)],
+ [Period(freq="2W", year=2017, month=x) for x in range(1, 4)],
+ ],
+ )
+ def test_count_with_datetimelike(self, datetimelike):
+ # test for #13393, where DataframeGroupBy.count() fails
+ # when counting a datetimelike column.
+
+ df = DataFrame({"x": ["a", "a", "b"], "y": datetimelike})
+ res = df.groupby("x").count()
+ expected = DataFrame({"y": [2, 1]}, index=["a", "b"])
+ expected.index.name = "x"
+ tm.assert_frame_equal(expected, res)
+
+ def test_count_with_only_nans_in_first_group(self):
+ # GH21956
+ df = DataFrame({"A": [np.nan, np.nan], "B": ["a", "b"], "C": [1, 2]})
+ result = df.groupby(["A", "B"]).C.count()
+ mi = MultiIndex(levels=[[], ["a", "b"]], codes=[[], []], names=["A", "B"])
+ expected = Series([], index=mi, dtype=np.int64, name="C")
+ tm.assert_series_equal(result, expected, check_index_type=False)
+
+ def test_count_groupby_column_with_nan_in_groupby_column(self):
+ # https://github.com/pandas-dev/pandas/issues/32841
+ df = DataFrame({"A": [1, 1, 1, 1, 1], "B": [5, 4, np.nan, 3, 0]})
+ res = df.groupby(["B"]).count()
+ expected = DataFrame(
+ index=Index([0.0, 3.0, 4.0, 5.0], name="B"), data={"A": [1, 1, 1, 1]}
+ )
+ tm.assert_frame_equal(expected, res)
+
+ def test_groupby_count_dateparseerror(self):
+ dr = date_range(start="1/1/2012", freq="5min", periods=10)
+
+ # BAD Example, datetimes first
+ ser = Series(np.arange(10), index=[dr, np.arange(10)])
+ grouped = ser.groupby(lambda x: x[1] % 2 == 0)
+ result = grouped.count()
+
+ ser = Series(np.arange(10), index=[np.arange(10), dr])
+ grouped = ser.groupby(lambda x: x[0] % 2 == 0)
+ expected = grouped.count()
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_timedelta_cython_count():
+ df = DataFrame(
+ {"g": list("ab" * 2), "delta": np.arange(4).astype("timedelta64[ns]")}
+ )
+ expected = Series([2, 2], index=Index(["a", "b"], name="g"), name="delta")
+ result = df.groupby("g").delta.count()
+ tm.assert_series_equal(expected, result)
+
+
+def test_count():
+ n = 1 << 15
+ dr = date_range("2015-08-30", periods=n // 10, freq="T")
+
+ df = DataFrame(
+ {
+ "1st": np.random.default_rng(2).choice(list(ascii_lowercase), n),
+ "2nd": np.random.default_rng(2).integers(0, 5, n),
+ "3rd": np.random.default_rng(2).standard_normal(n).round(3),
+ "4th": np.random.default_rng(2).integers(-10, 10, n),
+ "5th": np.random.default_rng(2).choice(dr, n),
+ "6th": np.random.default_rng(2).standard_normal(n).round(3),
+ "7th": np.random.default_rng(2).standard_normal(n).round(3),
+ "8th": np.random.default_rng(2).choice(dr, n)
+ - np.random.default_rng(2).choice(dr, 1),
+ "9th": np.random.default_rng(2).choice(list(ascii_lowercase), n),
+ }
+ )
+
+ for col in df.columns.drop(["1st", "2nd", "4th"]):
+ df.loc[np.random.default_rng(2).choice(n, n // 10), col] = np.nan
+
+ df["9th"] = df["9th"].astype("category")
+
+ for key in ["1st", "2nd", ["1st", "2nd"]]:
+ left = df.groupby(key).count()
+ right = df.groupby(key).apply(DataFrame.count).drop(key, axis=1)
+ tm.assert_frame_equal(left, right)
+
+
+def test_count_non_nulls():
+ # GH#5610
+ # count counts non-nulls
+ df = DataFrame(
+ [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, np.nan]],
+ columns=["A", "B", "C"],
+ )
+
+ count_as = df.groupby("A").count()
+ count_not_as = df.groupby("A", as_index=False).count()
+
+ expected = DataFrame([[1, 2], [0, 0]], columns=["B", "C"], index=[1, 3])
+ expected.index.name = "A"
+ tm.assert_frame_equal(count_not_as, expected.reset_index())
+ tm.assert_frame_equal(count_as, expected)
+
+ count_B = df.groupby("A")["B"].count()
+ tm.assert_series_equal(count_B, expected["B"])
+
+
+def test_count_object():
+ df = DataFrame({"a": ["a"] * 3 + ["b"] * 3, "c": [2] * 3 + [3] * 3})
+ result = df.groupby("c").a.count()
+ expected = Series([3, 3], index=Index([2, 3], name="c"), name="a")
+ tm.assert_series_equal(result, expected)
+
+ df = DataFrame({"a": ["a", np.nan, np.nan] + ["b"] * 3, "c": [2] * 3 + [3] * 3})
+ result = df.groupby("c").a.count()
+ expected = Series([1, 3], index=Index([2, 3], name="c"), name="a")
+ tm.assert_series_equal(result, expected)
+
+
+def test_count_cross_type():
+ # GH8169
+ # Set float64 dtype to avoid upcast when setting nan below
+ vals = np.hstack(
+ (
+ np.random.default_rng(2).integers(0, 5, (100, 2)),
+ np.random.default_rng(2).integers(0, 2, (100, 2)),
+ )
+ ).astype("float64")
+
+ df = DataFrame(vals, columns=["a", "b", "c", "d"])
+ df[df == 2] = np.nan
+ expected = df.groupby(["c", "d"]).count()
+
+ for t in ["float32", "object"]:
+ df["a"] = df["a"].astype(t)
+ df["b"] = df["b"].astype(t)
+ result = df.groupby(["c", "d"]).count()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_lower_int_prec_count():
+ df = DataFrame(
+ {
+ "a": np.array([0, 1, 2, 100], np.int8),
+ "b": np.array([1, 2, 3, 6], np.uint32),
+ "c": np.array([4, 5, 6, 8], np.int16),
+ "grp": list("ab" * 2),
+ }
+ )
+ result = df.groupby("grp").count()
+ expected = DataFrame(
+ {"a": [2, 2], "b": [2, 2], "c": [2, 2]}, index=Index(list("ab"), name="grp")
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_count_uses_size_on_exception():
+ class RaisingObjectException(Exception):
+ pass
+
+ class RaisingObject:
+ def __init__(self, msg="I will raise inside Cython") -> None:
+ super().__init__()
+ self.msg = msg
+
+ def __eq__(self, other):
+ # gets called in Cython to check that raising calls the method
+ raise RaisingObjectException(self.msg)
+
+ df = DataFrame({"a": [RaisingObject() for _ in range(4)], "grp": list("ab" * 2)})
+ result = df.groupby("grp").count()
+ expected = DataFrame({"a": [2, 2]}, index=Index(list("ab"), name="grp"))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_count_arrow_string_array(any_string_dtype):
+ # GH#54751
+ pytest.importorskip("pyarrow")
+ df = DataFrame(
+ {"a": [1, 2, 3], "b": Series(["a", "b", "a"], dtype=any_string_dtype)}
+ )
+ result = df.groupby("a").count()
+ expected = DataFrame({"b": 1}, index=Index([1, 2, 3], name="a"))
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_filters.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bb7ad4fd274db357a153d51c025e5d8f6946fa7
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_filters.py
@@ -0,0 +1,632 @@
+from string import ascii_lowercase
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
+import pandas._testing as tm
+
+
+def test_filter_series():
+ s = Series([1, 3, 20, 5, 22, 24, 7])
+ expected_odd = Series([1, 3, 5, 7], index=[0, 1, 3, 6])
+ expected_even = Series([20, 22, 24], index=[2, 4, 5])
+ grouper = s.apply(lambda x: x % 2)
+ grouped = s.groupby(grouper)
+ tm.assert_series_equal(grouped.filter(lambda x: x.mean() < 10), expected_odd)
+ tm.assert_series_equal(grouped.filter(lambda x: x.mean() > 10), expected_even)
+ # Test dropna=False.
+ tm.assert_series_equal(
+ grouped.filter(lambda x: x.mean() < 10, dropna=False),
+ expected_odd.reindex(s.index),
+ )
+ tm.assert_series_equal(
+ grouped.filter(lambda x: x.mean() > 10, dropna=False),
+ expected_even.reindex(s.index),
+ )
+
+
+def test_filter_single_column_df():
+ df = DataFrame([1, 3, 20, 5, 22, 24, 7])
+ expected_odd = DataFrame([1, 3, 5, 7], index=[0, 1, 3, 6])
+ expected_even = DataFrame([20, 22, 24], index=[2, 4, 5])
+ grouper = df[0].apply(lambda x: x % 2)
+ grouped = df.groupby(grouper)
+ tm.assert_frame_equal(grouped.filter(lambda x: x.mean() < 10), expected_odd)
+ tm.assert_frame_equal(grouped.filter(lambda x: x.mean() > 10), expected_even)
+ # Test dropna=False.
+ tm.assert_frame_equal(
+ grouped.filter(lambda x: x.mean() < 10, dropna=False),
+ expected_odd.reindex(df.index),
+ )
+ tm.assert_frame_equal(
+ grouped.filter(lambda x: x.mean() > 10, dropna=False),
+ expected_even.reindex(df.index),
+ )
+
+
+def test_filter_multi_column_df():
+ df = DataFrame({"A": [1, 12, 12, 1], "B": [1, 1, 1, 1]})
+ grouper = df["A"].apply(lambda x: x % 2)
+ grouped = df.groupby(grouper)
+ expected = DataFrame({"A": [12, 12], "B": [1, 1]}, index=[1, 2])
+ tm.assert_frame_equal(
+ grouped.filter(lambda x: x["A"].sum() - x["B"].sum() > 10), expected
+ )
+
+
+def test_filter_mixed_df():
+ df = DataFrame({"A": [1, 12, 12, 1], "B": "a b c d".split()})
+ grouper = df["A"].apply(lambda x: x % 2)
+ grouped = df.groupby(grouper)
+ expected = DataFrame({"A": [12, 12], "B": ["b", "c"]}, index=[1, 2])
+ tm.assert_frame_equal(grouped.filter(lambda x: x["A"].sum() > 10), expected)
+
+
+def test_filter_out_all_groups():
+ s = Series([1, 3, 20, 5, 22, 24, 7])
+ grouper = s.apply(lambda x: x % 2)
+ grouped = s.groupby(grouper)
+ tm.assert_series_equal(grouped.filter(lambda x: x.mean() > 1000), s[[]])
+ df = DataFrame({"A": [1, 12, 12, 1], "B": "a b c d".split()})
+ grouper = df["A"].apply(lambda x: x % 2)
+ grouped = df.groupby(grouper)
+ tm.assert_frame_equal(grouped.filter(lambda x: x["A"].sum() > 1000), df.loc[[]])
+
+
+def test_filter_out_no_groups():
+ s = Series([1, 3, 20, 5, 22, 24, 7])
+ grouper = s.apply(lambda x: x % 2)
+ grouped = s.groupby(grouper)
+ filtered = grouped.filter(lambda x: x.mean() > 0)
+ tm.assert_series_equal(filtered, s)
+ df = DataFrame({"A": [1, 12, 12, 1], "B": "a b c d".split()})
+ grouper = df["A"].apply(lambda x: x % 2)
+ grouped = df.groupby(grouper)
+ filtered = grouped.filter(lambda x: x["A"].mean() > 0)
+ tm.assert_frame_equal(filtered, df)
+
+
+def test_filter_out_all_groups_in_df():
+ # GH12768
+ df = DataFrame({"a": [1, 1, 2], "b": [1, 2, 0]})
+ res = df.groupby("a")
+ res = res.filter(lambda x: x["b"].sum() > 5, dropna=False)
+ expected = DataFrame({"a": [np.nan] * 3, "b": [np.nan] * 3})
+ tm.assert_frame_equal(expected, res)
+
+ df = DataFrame({"a": [1, 1, 2], "b": [1, 2, 0]})
+ res = df.groupby("a")
+ res = res.filter(lambda x: x["b"].sum() > 5, dropna=True)
+ expected = DataFrame({"a": [], "b": []}, dtype="int64")
+ tm.assert_frame_equal(expected, res)
+
+
+def test_filter_condition_raises():
+ def raise_if_sum_is_zero(x):
+ if x.sum() == 0:
+ raise ValueError
+ return x.sum() > 0
+
+ s = Series([-1, 0, 1, 2])
+ grouper = s.apply(lambda x: x % 2)
+ grouped = s.groupby(grouper)
+ msg = "the filter must return a boolean result"
+ with pytest.raises(TypeError, match=msg):
+ grouped.filter(raise_if_sum_is_zero)
+
+
+def test_filter_with_axis_in_groupby():
+ # issue 11041
+ index = pd.MultiIndex.from_product([range(10), [0, 1]])
+ data = DataFrame(np.arange(100).reshape(-1, 20), columns=index, dtype="int64")
+
+ msg = "DataFrame.groupby with axis=1"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = data.groupby(level=0, axis=1)
+ result = gb.filter(lambda x: x.iloc[0, 0] > 10)
+ expected = data.iloc[:, 12:20]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_filter_bad_shapes():
+ df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)})
+ s = df["B"]
+ g_df = df.groupby("B")
+ g_s = s.groupby(s)
+
+ f = lambda x: x
+ msg = "filter function returned a DataFrame, but expected a scalar bool"
+ with pytest.raises(TypeError, match=msg):
+ g_df.filter(f)
+ msg = "the filter must return a boolean result"
+ with pytest.raises(TypeError, match=msg):
+ g_s.filter(f)
+
+ f = lambda x: x == 1
+ msg = "filter function returned a DataFrame, but expected a scalar bool"
+ with pytest.raises(TypeError, match=msg):
+ g_df.filter(f)
+ msg = "the filter must return a boolean result"
+ with pytest.raises(TypeError, match=msg):
+ g_s.filter(f)
+
+ f = lambda x: np.outer(x, x)
+ msg = "can't multiply sequence by non-int of type 'str'"
+ with pytest.raises(TypeError, match=msg):
+ g_df.filter(f)
+ msg = "the filter must return a boolean result"
+ with pytest.raises(TypeError, match=msg):
+ g_s.filter(f)
+
+
+def test_filter_nan_is_false():
+ df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)})
+ s = df["B"]
+ g_df = df.groupby(df["B"])
+ g_s = s.groupby(s)
+
+ f = lambda x: np.nan
+ tm.assert_frame_equal(g_df.filter(f), df.loc[[]])
+ tm.assert_series_equal(g_s.filter(f), s[[]])
+
+
+def test_filter_pdna_is_false():
+ # in particular, dont raise in filter trying to call bool(pd.NA)
+ df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)})
+ ser = df["B"]
+ g_df = df.groupby(df["B"])
+ g_s = ser.groupby(ser)
+
+ func = lambda x: pd.NA
+ res = g_df.filter(func)
+ tm.assert_frame_equal(res, df.loc[[]])
+ res = g_s.filter(func)
+ tm.assert_series_equal(res, ser[[]])
+
+
+def test_filter_against_workaround():
+ # Series of ints
+ s = Series(np.random.default_rng(2).integers(0, 100, 1000))
+ grouper = s.apply(lambda x: np.round(x, -1))
+ grouped = s.groupby(grouper)
+ f = lambda x: x.mean() > 10
+
+ old_way = s[grouped.transform(f).astype("bool")]
+ new_way = grouped.filter(f)
+ tm.assert_series_equal(new_way.sort_values(), old_way.sort_values())
+
+ # Series of floats
+ s = 100 * Series(np.random.default_rng(2).random(1000))
+ grouper = s.apply(lambda x: np.round(x, -1))
+ grouped = s.groupby(grouper)
+ f = lambda x: x.mean() > 10
+ old_way = s[grouped.transform(f).astype("bool")]
+ new_way = grouped.filter(f)
+ tm.assert_series_equal(new_way.sort_values(), old_way.sort_values())
+
+ # Set up DataFrame of ints, floats, strings.
+ letters = np.array(list(ascii_lowercase))
+ N = 1000
+ random_letters = letters.take(
+ np.random.default_rng(2).integers(0, 26, N, dtype=int)
+ )
+ df = DataFrame(
+ {
+ "ints": Series(np.random.default_rng(2).integers(0, 100, N)),
+ "floats": N / 10 * Series(np.random.default_rng(2).random(N)),
+ "letters": Series(random_letters),
+ }
+ )
+
+ # Group by ints; filter on floats.
+ grouped = df.groupby("ints")
+ old_way = df[grouped.floats.transform(lambda x: x.mean() > N / 20).astype("bool")]
+ new_way = grouped.filter(lambda x: x["floats"].mean() > N / 20)
+ tm.assert_frame_equal(new_way, old_way)
+
+ # Group by floats (rounded); filter on strings.
+ grouper = df.floats.apply(lambda x: np.round(x, -1))
+ grouped = df.groupby(grouper)
+ old_way = df[grouped.letters.transform(lambda x: len(x) < N / 10).astype("bool")]
+ new_way = grouped.filter(lambda x: len(x.letters) < N / 10)
+ tm.assert_frame_equal(new_way, old_way)
+
+ # Group by strings; filter on ints.
+ grouped = df.groupby("letters")
+ old_way = df[grouped.ints.transform(lambda x: x.mean() > N / 20).astype("bool")]
+ new_way = grouped.filter(lambda x: x["ints"].mean() > N / 20)
+ tm.assert_frame_equal(new_way, old_way)
+
+
+def test_filter_using_len():
+ # BUG GH4447
+ df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)})
+ grouped = df.groupby("B")
+ actual = grouped.filter(lambda x: len(x) > 2)
+ expected = DataFrame(
+ {"A": np.arange(2, 6), "B": list("bbbb"), "C": np.arange(2, 6)},
+ index=np.arange(2, 6, dtype=np.int64),
+ )
+ tm.assert_frame_equal(actual, expected)
+
+ actual = grouped.filter(lambda x: len(x) > 4)
+ expected = df.loc[[]]
+ tm.assert_frame_equal(actual, expected)
+
+ # Series have always worked properly, but we'll test anyway.
+ s = df["B"]
+ grouped = s.groupby(s)
+ actual = grouped.filter(lambda x: len(x) > 2)
+ expected = Series(4 * ["b"], index=np.arange(2, 6, dtype=np.int64), name="B")
+ tm.assert_series_equal(actual, expected)
+
+ actual = grouped.filter(lambda x: len(x) > 4)
+ expected = s[[]]
+ tm.assert_series_equal(actual, expected)
+
+
+def test_filter_maintains_ordering():
+ # Simple case: index is sequential. #4621
+ df = DataFrame(
+ {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]}
+ )
+ s = df["pid"]
+ grouped = df.groupby("tag")
+ actual = grouped.filter(lambda x: len(x) > 1)
+ expected = df.iloc[[1, 2, 4, 7]]
+ tm.assert_frame_equal(actual, expected)
+
+ grouped = s.groupby(df["tag"])
+ actual = grouped.filter(lambda x: len(x) > 1)
+ expected = s.iloc[[1, 2, 4, 7]]
+ tm.assert_series_equal(actual, expected)
+
+ # Now index is sequentially decreasing.
+ df.index = np.arange(len(df) - 1, -1, -1)
+ s = df["pid"]
+ grouped = df.groupby("tag")
+ actual = grouped.filter(lambda x: len(x) > 1)
+ expected = df.iloc[[1, 2, 4, 7]]
+ tm.assert_frame_equal(actual, expected)
+
+ grouped = s.groupby(df["tag"])
+ actual = grouped.filter(lambda x: len(x) > 1)
+ expected = s.iloc[[1, 2, 4, 7]]
+ tm.assert_series_equal(actual, expected)
+
+ # Index is shuffled.
+ SHUFFLED = [4, 6, 7, 2, 1, 0, 5, 3]
+ df.index = df.index[SHUFFLED]
+ s = df["pid"]
+ grouped = df.groupby("tag")
+ actual = grouped.filter(lambda x: len(x) > 1)
+ expected = df.iloc[[1, 2, 4, 7]]
+ tm.assert_frame_equal(actual, expected)
+
+ grouped = s.groupby(df["tag"])
+ actual = grouped.filter(lambda x: len(x) > 1)
+ expected = s.iloc[[1, 2, 4, 7]]
+ tm.assert_series_equal(actual, expected)
+
+
+def test_filter_multiple_timestamp():
+ # GH 10114
+ df = DataFrame(
+ {
+ "A": np.arange(5, dtype="int64"),
+ "B": ["foo", "bar", "foo", "bar", "bar"],
+ "C": Timestamp("20130101"),
+ }
+ )
+
+ grouped = df.groupby(["B", "C"])
+
+ result = grouped["A"].filter(lambda x: True)
+ tm.assert_series_equal(df["A"], result)
+
+ result = grouped["A"].transform(len)
+ expected = Series([2, 3, 2, 3, 3], name="A")
+ tm.assert_series_equal(result, expected)
+
+ result = grouped.filter(lambda x: True)
+ tm.assert_frame_equal(df, result)
+
+ result = grouped.transform("sum")
+ expected = DataFrame({"A": [2, 8, 2, 8, 8]})
+ tm.assert_frame_equal(result, expected)
+
+ result = grouped.transform(len)
+ expected = DataFrame({"A": [2, 3, 2, 3, 3]})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_filter_and_transform_with_non_unique_int_index():
+ # GH4620
+ index = [1, 1, 1, 2, 1, 1, 0, 1]
+ df = DataFrame(
+ {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
+ index=index,
+ )
+ grouped_df = df.groupby("tag")
+ ser = df["pid"]
+ grouped_ser = ser.groupby(df["tag"])
+ expected_indexes = [1, 2, 4, 7]
+
+ # Filter DataFrame
+ actual = grouped_df.filter(lambda x: len(x) > 1)
+ expected = df.iloc[expected_indexes]
+ tm.assert_frame_equal(actual, expected)
+
+ actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
+ expected.iloc[[0, 3, 5, 6]] = np.nan
+ tm.assert_frame_equal(actual, expected)
+
+ # Filter Series
+ actual = grouped_ser.filter(lambda x: len(x) > 1)
+ expected = ser.take(expected_indexes)
+ tm.assert_series_equal(actual, expected)
+
+ actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
+ expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid")
+ # ^ made manually because this can get confusing!
+ tm.assert_series_equal(actual, expected)
+
+ # Transform Series
+ actual = grouped_ser.transform(len)
+ expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
+ tm.assert_series_equal(actual, expected)
+
+ # Transform (a column from) DataFrameGroupBy
+ actual = grouped_df.pid.transform(len)
+ tm.assert_series_equal(actual, expected)
+
+
+def test_filter_and_transform_with_multiple_non_unique_int_index():
+ # GH4620
+ index = [1, 1, 1, 2, 0, 0, 0, 1]
+ df = DataFrame(
+ {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
+ index=index,
+ )
+ grouped_df = df.groupby("tag")
+ ser = df["pid"]
+ grouped_ser = ser.groupby(df["tag"])
+ expected_indexes = [1, 2, 4, 7]
+
+ # Filter DataFrame
+ actual = grouped_df.filter(lambda x: len(x) > 1)
+ expected = df.iloc[expected_indexes]
+ tm.assert_frame_equal(actual, expected)
+
+ actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
+ expected.iloc[[0, 3, 5, 6]] = np.nan
+ tm.assert_frame_equal(actual, expected)
+
+ # Filter Series
+ actual = grouped_ser.filter(lambda x: len(x) > 1)
+ expected = ser.take(expected_indexes)
+ tm.assert_series_equal(actual, expected)
+
+ actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
+ expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid")
+ # ^ made manually because this can get confusing!
+ tm.assert_series_equal(actual, expected)
+
+ # Transform Series
+ actual = grouped_ser.transform(len)
+ expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
+ tm.assert_series_equal(actual, expected)
+
+ # Transform (a column from) DataFrameGroupBy
+ actual = grouped_df.pid.transform(len)
+ tm.assert_series_equal(actual, expected)
+
+
+def test_filter_and_transform_with_non_unique_float_index():
+ # GH4620
+ index = np.array([1, 1, 1, 2, 1, 1, 0, 1], dtype=float)
+ df = DataFrame(
+ {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
+ index=index,
+ )
+ grouped_df = df.groupby("tag")
+ ser = df["pid"]
+ grouped_ser = ser.groupby(df["tag"])
+ expected_indexes = [1, 2, 4, 7]
+
+ # Filter DataFrame
+ actual = grouped_df.filter(lambda x: len(x) > 1)
+ expected = df.iloc[expected_indexes]
+ tm.assert_frame_equal(actual, expected)
+
+ actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
+ expected.iloc[[0, 3, 5, 6]] = np.nan
+ tm.assert_frame_equal(actual, expected)
+
+ # Filter Series
+ actual = grouped_ser.filter(lambda x: len(x) > 1)
+ expected = ser.take(expected_indexes)
+ tm.assert_series_equal(actual, expected)
+
+ actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
+ expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid")
+ # ^ made manually because this can get confusing!
+ tm.assert_series_equal(actual, expected)
+
+ # Transform Series
+ actual = grouped_ser.transform(len)
+ expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
+ tm.assert_series_equal(actual, expected)
+
+ # Transform (a column from) DataFrameGroupBy
+ actual = grouped_df.pid.transform(len)
+ tm.assert_series_equal(actual, expected)
+
+
+def test_filter_and_transform_with_non_unique_timestamp_index():
+ # GH4620
+ t0 = Timestamp("2013-09-30 00:05:00")
+ t1 = Timestamp("2013-10-30 00:05:00")
+ t2 = Timestamp("2013-11-30 00:05:00")
+ index = [t1, t1, t1, t2, t1, t1, t0, t1]
+ df = DataFrame(
+ {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
+ index=index,
+ )
+ grouped_df = df.groupby("tag")
+ ser = df["pid"]
+ grouped_ser = ser.groupby(df["tag"])
+ expected_indexes = [1, 2, 4, 7]
+
+ # Filter DataFrame
+ actual = grouped_df.filter(lambda x: len(x) > 1)
+ expected = df.iloc[expected_indexes]
+ tm.assert_frame_equal(actual, expected)
+
+ actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
+ expected.iloc[[0, 3, 5, 6]] = np.nan
+ tm.assert_frame_equal(actual, expected)
+
+ # Filter Series
+ actual = grouped_ser.filter(lambda x: len(x) > 1)
+ expected = ser.take(expected_indexes)
+ tm.assert_series_equal(actual, expected)
+
+ actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
+ expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid")
+ # ^ made manually because this can get confusing!
+ tm.assert_series_equal(actual, expected)
+
+ # Transform Series
+ actual = grouped_ser.transform(len)
+ expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
+ tm.assert_series_equal(actual, expected)
+
+ # Transform (a column from) DataFrameGroupBy
+ actual = grouped_df.pid.transform(len)
+ tm.assert_series_equal(actual, expected)
+
+
+def test_filter_and_transform_with_non_unique_string_index():
+ # GH4620
+ index = list("bbbcbbab")
+ df = DataFrame(
+ {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
+ index=index,
+ )
+ grouped_df = df.groupby("tag")
+ ser = df["pid"]
+ grouped_ser = ser.groupby(df["tag"])
+ expected_indexes = [1, 2, 4, 7]
+
+ # Filter DataFrame
+ actual = grouped_df.filter(lambda x: len(x) > 1)
+ expected = df.iloc[expected_indexes]
+ tm.assert_frame_equal(actual, expected)
+
+ actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
+ expected.iloc[[0, 3, 5, 6]] = np.nan
+ tm.assert_frame_equal(actual, expected)
+
+ # Filter Series
+ actual = grouped_ser.filter(lambda x: len(x) > 1)
+ expected = ser.take(expected_indexes)
+ tm.assert_series_equal(actual, expected)
+
+ actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
+ expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid")
+ # ^ made manually because this can get confusing!
+ tm.assert_series_equal(actual, expected)
+
+ # Transform Series
+ actual = grouped_ser.transform(len)
+ expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
+ tm.assert_series_equal(actual, expected)
+
+ # Transform (a column from) DataFrameGroupBy
+ actual = grouped_df.pid.transform(len)
+ tm.assert_series_equal(actual, expected)
+
+
+def test_filter_has_access_to_grouped_cols():
+ df = DataFrame([[1, 2], [1, 3], [5, 6]], columns=["A", "B"])
+ g = df.groupby("A")
+ # previously didn't have access to col A #????
+ filt = g.filter(lambda x: x["A"].sum() == 2)
+ tm.assert_frame_equal(filt, df.iloc[[0, 1]])
+
+
+def test_filter_enforces_scalarness():
+ df = DataFrame(
+ [
+ ["best", "a", "x"],
+ ["worst", "b", "y"],
+ ["best", "c", "x"],
+ ["best", "d", "y"],
+ ["worst", "d", "y"],
+ ["worst", "d", "y"],
+ ["best", "d", "z"],
+ ],
+ columns=["a", "b", "c"],
+ )
+ with pytest.raises(TypeError, match="filter function returned a.*"):
+ df.groupby("c").filter(lambda g: g["a"] == "best")
+
+
+def test_filter_non_bool_raises():
+ df = DataFrame(
+ [
+ ["best", "a", 1],
+ ["worst", "b", 1],
+ ["best", "c", 1],
+ ["best", "d", 1],
+ ["worst", "d", 1],
+ ["worst", "d", 1],
+ ["best", "d", 1],
+ ],
+ columns=["a", "b", "c"],
+ )
+ with pytest.raises(TypeError, match="filter function returned a.*"):
+ df.groupby("a").filter(lambda g: g.c.mean())
+
+
+def test_filter_dropna_with_empty_groups():
+ # GH 10780
+ data = Series(np.random.default_rng(2).random(9), index=np.repeat([1, 2, 3], 3))
+ grouped = data.groupby(level=0)
+ result_false = grouped.filter(lambda x: x.mean() > 1, dropna=False)
+ expected_false = Series([np.nan] * 9, index=np.repeat([1, 2, 3], 3))
+ tm.assert_series_equal(result_false, expected_false)
+
+ result_true = grouped.filter(lambda x: x.mean() > 1, dropna=True)
+ expected_true = Series(index=pd.Index([], dtype=int), dtype=np.float64)
+ tm.assert_series_equal(result_true, expected_true)
+
+
+def test_filter_consistent_result_before_after_agg_func():
+ # GH 17091
+ df = DataFrame({"data": range(6), "key": list("ABCABC")})
+ grouper = df.groupby("key")
+ result = grouper.filter(lambda x: True)
+ expected = DataFrame({"data": range(6), "key": list("ABCABC")})
+ tm.assert_frame_equal(result, expected)
+
+ grouper.sum()
+ result = grouper.filter(lambda x: True)
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_function.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_function.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac58701f5fa392ad531f64ccf471cb3ad10e1de0
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_function.py
@@ -0,0 +1,1767 @@
+import builtins
+from io import StringIO
+import re
+
+import numpy as np
+import pytest
+
+from pandas._libs import lib
+from pandas.errors import UnsupportedFunctionCall
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.tests.groupby import get_groupby_method_args
+from pandas.util import _test_decorators as td
+
+
+@pytest.fixture(
+ params=[np.int32, np.int64, np.float32, np.float64, "Int64", "Float64"],
+ ids=["np.int32", "np.int64", "np.float32", "np.float64", "Int64", "Float64"],
+)
+def dtypes_for_minmax(request):
+ """
+ Fixture of dtypes with min and max values used for testing
+ cummin and cummax
+ """
+ dtype = request.param
+
+ np_type = dtype
+ if dtype == "Int64":
+ np_type = np.int64
+ elif dtype == "Float64":
+ np_type = np.float64
+
+ min_val = (
+ np.iinfo(np_type).min
+ if np.dtype(np_type).kind == "i"
+ else np.finfo(np_type).min
+ )
+ max_val = (
+ np.iinfo(np_type).max
+ if np.dtype(np_type).kind == "i"
+ else np.finfo(np_type).max
+ )
+
+ return (dtype, min_val, max_val)
+
+
+def test_intercept_builtin_sum():
+ s = Series([1.0, 2.0, np.nan, 3.0])
+ grouped = s.groupby([0, 1, 2, 2])
+
+ msg = "using SeriesGroupBy.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result = grouped.agg(builtins.sum)
+ msg = "using np.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#53425
+ result2 = grouped.apply(builtins.sum)
+ expected = grouped.sum()
+ tm.assert_series_equal(result, expected)
+ tm.assert_series_equal(result2, expected)
+
+
+@pytest.mark.parametrize("f", [max, min, sum])
+@pytest.mark.parametrize("keys", ["jim", ["jim", "joe"]]) # Single key # Multi-key
+def test_builtins_apply(keys, f):
+ # see gh-8155
+ rs = np.random.default_rng(2)
+ df = DataFrame(rs.integers(1, 7, (10, 2)), columns=["jim", "joe"])
+ df["jolie"] = rs.standard_normal(10)
+
+ gb = df.groupby(keys)
+
+ fname = f.__name__
+
+ warn = None if f is not sum else FutureWarning
+ msg = "The behavior of DataFrame.sum with axis=None is deprecated"
+ with tm.assert_produces_warning(
+ warn, match=msg, check_stacklevel=False, raise_on_extra_warnings=False
+ ):
+ # Also warns on deprecation GH#53425
+ result = gb.apply(f)
+ ngroups = len(df.drop_duplicates(subset=keys))
+
+ assert_msg = f"invalid frame shape: {result.shape} (expected ({ngroups}, 3))"
+ assert result.shape == (ngroups, 3), assert_msg
+
+ npfunc = lambda x: getattr(np, fname)(x, axis=0) # numpy's equivalent function
+ expected = gb.apply(npfunc)
+ tm.assert_frame_equal(result, expected)
+
+ with tm.assert_produces_warning(None):
+ expected2 = gb.apply(lambda x: npfunc(x))
+ tm.assert_frame_equal(result, expected2)
+
+ if f != sum:
+ expected = gb.agg(fname).reset_index()
+ expected.set_index(keys, inplace=True, drop=False)
+ tm.assert_frame_equal(result, expected, check_dtype=False)
+
+ tm.assert_series_equal(getattr(result, fname)(axis=0), getattr(df, fname)(axis=0))
+
+
+class TestNumericOnly:
+ # make sure that we are passing thru kwargs to our agg functions
+
+ @pytest.fixture
+ def df(self):
+ # GH3668
+ # GH5724
+ df = DataFrame(
+ {
+ "group": [1, 1, 2],
+ "int": [1, 2, 3],
+ "float": [4.0, 5.0, 6.0],
+ "string": list("abc"),
+ "category_string": Series(list("abc")).astype("category"),
+ "category_int": [7, 8, 9],
+ "datetime": date_range("20130101", periods=3),
+ "datetimetz": date_range("20130101", periods=3, tz="US/Eastern"),
+ "timedelta": pd.timedelta_range("1 s", periods=3, freq="s"),
+ },
+ columns=[
+ "group",
+ "int",
+ "float",
+ "string",
+ "category_string",
+ "category_int",
+ "datetime",
+ "datetimetz",
+ "timedelta",
+ ],
+ )
+ return df
+
+ @pytest.mark.parametrize("method", ["mean", "median"])
+ def test_averages(self, df, method):
+ # mean / median
+ expected_columns_numeric = Index(["int", "float", "category_int"])
+
+ gb = df.groupby("group")
+ expected = DataFrame(
+ {
+ "category_int": [7.5, 9],
+ "float": [4.5, 6.0],
+ "timedelta": [pd.Timedelta("1.5s"), pd.Timedelta("3s")],
+ "int": [1.5, 3],
+ "datetime": [
+ Timestamp("2013-01-01 12:00:00"),
+ Timestamp("2013-01-03 00:00:00"),
+ ],
+ "datetimetz": [
+ Timestamp("2013-01-01 12:00:00", tz="US/Eastern"),
+ Timestamp("2013-01-03 00:00:00", tz="US/Eastern"),
+ ],
+ },
+ index=Index([1, 2], name="group"),
+ columns=[
+ "int",
+ "float",
+ "category_int",
+ ],
+ )
+
+ result = getattr(gb, method)(numeric_only=True)
+ tm.assert_frame_equal(result.reindex_like(expected), expected)
+
+ expected_columns = expected.columns
+
+ self._check(df, method, expected_columns, expected_columns_numeric)
+
+ @pytest.mark.parametrize("method", ["min", "max"])
+ def test_extrema(self, df, method):
+ # TODO: min, max *should* handle
+ # categorical (ordered) dtype
+
+ expected_columns = Index(
+ [
+ "int",
+ "float",
+ "string",
+ "category_int",
+ "datetime",
+ "datetimetz",
+ "timedelta",
+ ]
+ )
+ expected_columns_numeric = expected_columns
+
+ self._check(df, method, expected_columns, expected_columns_numeric)
+
+ @pytest.mark.parametrize("method", ["first", "last"])
+ def test_first_last(self, df, method):
+ expected_columns = Index(
+ [
+ "int",
+ "float",
+ "string",
+ "category_string",
+ "category_int",
+ "datetime",
+ "datetimetz",
+ "timedelta",
+ ]
+ )
+ expected_columns_numeric = expected_columns
+
+ self._check(df, method, expected_columns, expected_columns_numeric)
+
+ @pytest.mark.parametrize("method", ["sum", "cumsum"])
+ def test_sum_cumsum(self, df, method):
+ expected_columns_numeric = Index(["int", "float", "category_int"])
+ expected_columns = Index(
+ ["int", "float", "string", "category_int", "timedelta"]
+ )
+ if method == "cumsum":
+ # cumsum loses string
+ expected_columns = Index(["int", "float", "category_int", "timedelta"])
+
+ self._check(df, method, expected_columns, expected_columns_numeric)
+
+ @pytest.mark.parametrize("method", ["prod", "cumprod"])
+ def test_prod_cumprod(self, df, method):
+ expected_columns = Index(["int", "float", "category_int"])
+ expected_columns_numeric = expected_columns
+
+ self._check(df, method, expected_columns, expected_columns_numeric)
+
+ @pytest.mark.parametrize("method", ["cummin", "cummax"])
+ def test_cummin_cummax(self, df, method):
+ # like min, max, but don't include strings
+ expected_columns = Index(
+ ["int", "float", "category_int", "datetime", "datetimetz", "timedelta"]
+ )
+
+ # GH#15561: numeric_only=False set by default like min/max
+ expected_columns_numeric = expected_columns
+
+ self._check(df, method, expected_columns, expected_columns_numeric)
+
+ def _check(self, df, method, expected_columns, expected_columns_numeric):
+ gb = df.groupby("group")
+
+ # object dtypes for transformations are not implemented in Cython and
+ # have no Python fallback
+ exception = NotImplementedError if method.startswith("cum") else TypeError
+
+ if method in ("min", "max", "cummin", "cummax", "cumsum", "cumprod"):
+ # The methods default to numeric_only=False and raise TypeError
+ msg = "|".join(
+ [
+ "Categorical is not ordered",
+ f"Cannot perform {method} with non-ordered Categorical",
+ re.escape(f"agg function failed [how->{method},dtype->object]"),
+ # cumsum/cummin/cummax/cumprod
+ "function is not implemented for this dtype",
+ ]
+ )
+ with pytest.raises(exception, match=msg):
+ getattr(gb, method)()
+ elif method in ("sum", "mean", "median", "prod"):
+ msg = "|".join(
+ [
+ "category type does not support sum operations",
+ re.escape(f"agg function failed [how->{method},dtype->object]"),
+ ]
+ )
+ with pytest.raises(exception, match=msg):
+ getattr(gb, method)()
+ else:
+ result = getattr(gb, method)()
+ tm.assert_index_equal(result.columns, expected_columns_numeric)
+
+ if method not in ("first", "last"):
+ msg = "|".join(
+ [
+ "Categorical is not ordered",
+ "category type does not support",
+ "function is not implemented for this dtype",
+ f"Cannot perform {method} with non-ordered Categorical",
+ re.escape(f"agg function failed [how->{method},dtype->object]"),
+ ]
+ )
+ with pytest.raises(exception, match=msg):
+ getattr(gb, method)(numeric_only=False)
+ else:
+ result = getattr(gb, method)(numeric_only=False)
+ tm.assert_index_equal(result.columns, expected_columns)
+
+
+class TestGroupByNonCythonPaths:
+ # GH#5610 non-cython calls should not include the grouper
+ # Tests for code not expected to go through cython paths.
+
+ @pytest.fixture
+ def df(self):
+ df = DataFrame(
+ [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]],
+ columns=["A", "B", "C"],
+ )
+ return df
+
+ @pytest.fixture
+ def gb(self, df):
+ gb = df.groupby("A")
+ return gb
+
+ @pytest.fixture
+ def gni(self, df):
+ gni = df.groupby("A", as_index=False)
+ return gni
+
+ def test_describe(self, df, gb, gni):
+ # describe
+ expected_index = Index([1, 3], name="A")
+ expected_col = MultiIndex(
+ levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]],
+ codes=[[0] * 8, list(range(8))],
+ )
+ expected = DataFrame(
+ [
+ [1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0],
+ [0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
+ ],
+ index=expected_index,
+ columns=expected_col,
+ )
+ result = gb.describe()
+ tm.assert_frame_equal(result, expected)
+
+ expected = expected.reset_index()
+ result = gni.describe()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_cython_api2():
+ # this takes the fast apply path
+
+ # cumsum (GH5614)
+ df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=["A", "B", "C"])
+ expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=["B", "C"])
+ result = df.groupby("A").cumsum()
+ tm.assert_frame_equal(result, expected)
+
+ # GH 5755 - cumsum is a transformer and should ignore as_index
+ result = df.groupby("A", as_index=False).cumsum()
+ tm.assert_frame_equal(result, expected)
+
+ # GH 13994
+ msg = "DataFrameGroupBy.cumsum with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.groupby("A").cumsum(axis=1)
+ expected = df.cumsum(axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ msg = "DataFrameGroupBy.cumprod with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.groupby("A").cumprod(axis=1)
+ expected = df.cumprod(axis=1)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_cython_median():
+ arr = np.random.default_rng(2).standard_normal(1000)
+ arr[::2] = np.nan
+ df = DataFrame(arr)
+
+ labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float)
+ labels[::17] = np.nan
+
+ result = df.groupby(labels).median()
+ msg = "using DataFrameGroupBy.median"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ exp = df.groupby(labels).agg(np.nanmedian)
+ tm.assert_frame_equal(result, exp)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((1000, 5)))
+ msg = "using DataFrameGroupBy.median"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ rs = df.groupby(labels).agg(np.median)
+ xp = df.groupby(labels).median()
+ tm.assert_frame_equal(rs, xp)
+
+
+def test_median_empty_bins(observed):
+ df = DataFrame(np.random.default_rng(2).integers(0, 44, 500))
+
+ grps = range(0, 55, 5)
+ bins = pd.cut(df[0], grps)
+
+ result = df.groupby(bins, observed=observed).median()
+ expected = df.groupby(bins, observed=observed).agg(lambda x: x.median())
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "dtype", ["int8", "int16", "int32", "int64", "float32", "float64", "uint64"]
+)
+@pytest.mark.parametrize(
+ "method,data",
+ [
+ ("first", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}),
+ ("last", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}),
+ ("min", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}),
+ ("max", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}),
+ ("count", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 2}], "out_type": "int64"}),
+ ],
+)
+def test_groupby_non_arithmetic_agg_types(dtype, method, data):
+ # GH9311, GH6620
+ df = DataFrame(
+ [{"a": 1, "b": 1}, {"a": 1, "b": 2}, {"a": 2, "b": 3}, {"a": 2, "b": 4}]
+ )
+
+ df["b"] = df.b.astype(dtype)
+
+ if "args" not in data:
+ data["args"] = []
+
+ if "out_type" in data:
+ out_type = data["out_type"]
+ else:
+ out_type = dtype
+
+ exp = data["df"]
+ df_out = DataFrame(exp)
+
+ df_out["b"] = df_out.b.astype(out_type)
+ df_out.set_index("a", inplace=True)
+
+ grpd = df.groupby("a")
+ t = getattr(grpd, method)(*data["args"])
+ tm.assert_frame_equal(t, df_out)
+
+
+@pytest.mark.parametrize(
+ "i",
+ [
+ (
+ Timestamp("2011-01-15 12:50:28.502376"),
+ Timestamp("2011-01-20 12:50:28.593448"),
+ ),
+ (24650000000000001, 24650000000000002),
+ ],
+)
+def test_groupby_non_arithmetic_agg_int_like_precision(i):
+ # see gh-6620, gh-9311
+ df = DataFrame([{"a": 1, "b": i[0]}, {"a": 1, "b": i[1]}])
+
+ grp_exp = {
+ "first": {"expected": i[0]},
+ "last": {"expected": i[1]},
+ "min": {"expected": i[0]},
+ "max": {"expected": i[1]},
+ "nth": {"expected": i[1], "args": [1]},
+ "count": {"expected": 2},
+ }
+
+ for method, data in grp_exp.items():
+ if "args" not in data:
+ data["args"] = []
+
+ grouped = df.groupby("a")
+ res = getattr(grouped, method)(*data["args"])
+
+ assert res.iloc[0].b == data["expected"]
+
+
+@pytest.mark.parametrize(
+ "func, values",
+ [
+ ("idxmin", {"c_int": [0, 2], "c_float": [1, 3], "c_date": [1, 2]}),
+ ("idxmax", {"c_int": [1, 3], "c_float": [0, 2], "c_date": [0, 3]}),
+ ],
+)
+@pytest.mark.parametrize("numeric_only", [True, False])
+def test_idxmin_idxmax_returns_int_types(func, values, numeric_only):
+ # GH 25444
+ df = DataFrame(
+ {
+ "name": ["A", "A", "B", "B"],
+ "c_int": [1, 2, 3, 4],
+ "c_float": [4.02, 3.03, 2.04, 1.05],
+ "c_date": ["2019", "2018", "2016", "2017"],
+ }
+ )
+ df["c_date"] = pd.to_datetime(df["c_date"])
+ df["c_date_tz"] = df["c_date"].dt.tz_localize("US/Pacific")
+ df["c_timedelta"] = df["c_date"] - df["c_date"].iloc[0]
+ df["c_period"] = df["c_date"].dt.to_period("W")
+ df["c_Integer"] = df["c_int"].astype("Int64")
+ df["c_Floating"] = df["c_float"].astype("Float64")
+
+ result = getattr(df.groupby("name"), func)(numeric_only=numeric_only)
+
+ expected = DataFrame(values, index=Index(["A", "B"], name="name"))
+ if numeric_only:
+ expected = expected.drop(columns=["c_date"])
+ else:
+ expected["c_date_tz"] = expected["c_date"]
+ expected["c_timedelta"] = expected["c_date"]
+ expected["c_period"] = expected["c_date"]
+ expected["c_Integer"] = expected["c_int"]
+ expected["c_Floating"] = expected["c_float"]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_idxmin_idxmax_axis1():
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)), columns=["A", "B", "C", "D"]
+ )
+ df["A"] = [1, 2, 3, 1, 2, 3, 1, 2, 3, 4]
+
+ gb = df.groupby("A")
+
+ warn_msg = "DataFrameGroupBy.idxmax with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ res = gb.idxmax(axis=1)
+
+ alt = df.iloc[:, 1:].idxmax(axis=1)
+ indexer = res.index.get_level_values(1)
+
+ tm.assert_series_equal(alt[indexer], res.droplevel("A"))
+
+ df["E"] = date_range("2016-01-01", periods=10)
+ gb2 = df.groupby("A")
+
+ msg = "'>' not supported between instances of 'Timestamp' and 'float'"
+ with pytest.raises(TypeError, match=msg):
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ gb2.idxmax(axis=1)
+
+
+@pytest.mark.parametrize("numeric_only", [True, False, None])
+def test_axis1_numeric_only(request, groupby_func, numeric_only):
+ if groupby_func in ("idxmax", "idxmin"):
+ pytest.skip("idxmax and idx_min tested in test_idxmin_idxmax_axis1")
+ if groupby_func in ("corrwith", "skew"):
+ msg = "GH#47723 groupby.corrwith and skew do not correctly implement axis=1"
+ request.node.add_marker(pytest.mark.xfail(reason=msg))
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)), columns=["A", "B", "C", "D"]
+ )
+ df["E"] = "x"
+ groups = [1, 2, 3, 1, 2, 3, 1, 2, 3, 4]
+ gb = df.groupby(groups)
+ method = getattr(gb, groupby_func)
+ args = get_groupby_method_args(groupby_func, df)
+ kwargs = {"axis": 1}
+ if numeric_only is not None:
+ # when numeric_only is None we don't pass any argument
+ kwargs["numeric_only"] = numeric_only
+
+ # Functions without numeric_only and axis args
+ no_args = ("cumprod", "cumsum", "diff", "fillna", "pct_change", "rank", "shift")
+ # Functions with axis args
+ has_axis = (
+ "cumprod",
+ "cumsum",
+ "diff",
+ "pct_change",
+ "rank",
+ "shift",
+ "cummax",
+ "cummin",
+ "idxmin",
+ "idxmax",
+ "fillna",
+ )
+ warn_msg = f"DataFrameGroupBy.{groupby_func} with axis=1 is deprecated"
+ if numeric_only is not None and groupby_func in no_args:
+ msg = "got an unexpected keyword argument 'numeric_only'"
+ if groupby_func in ["cumprod", "cumsum"]:
+ with pytest.raises(TypeError, match=msg):
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ method(*args, **kwargs)
+ else:
+ with pytest.raises(TypeError, match=msg):
+ method(*args, **kwargs)
+ elif groupby_func not in has_axis:
+ msg = "got an unexpected keyword argument 'axis'"
+ with pytest.raises(TypeError, match=msg):
+ method(*args, **kwargs)
+ # fillna and shift are successful even on object dtypes
+ elif (numeric_only is None or not numeric_only) and groupby_func not in (
+ "fillna",
+ "shift",
+ ):
+ msgs = (
+ # cummax, cummin, rank
+ "not supported between instances of",
+ # cumprod
+ "can't multiply sequence by non-int of type 'float'",
+ # cumsum, diff, pct_change
+ "unsupported operand type",
+ )
+ with pytest.raises(TypeError, match=f"({'|'.join(msgs)})"):
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ method(*args, **kwargs)
+ else:
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ result = method(*args, **kwargs)
+
+ df_expected = df.drop(columns="E").T if numeric_only else df.T
+ expected = getattr(df_expected, groupby_func)(*args).T
+ if groupby_func == "shift" and not numeric_only:
+ # shift with axis=1 leaves the leftmost column as numeric
+ # but transposing for expected gives us object dtype
+ expected = expected.astype(float)
+
+ tm.assert_equal(result, expected)
+
+
+def test_groupby_cumprod():
+ # GH 4095
+ df = DataFrame({"key": ["b"] * 10, "value": 2})
+
+ actual = df.groupby("key")["value"].cumprod()
+ expected = df.groupby("key", group_keys=False)["value"].apply(lambda x: x.cumprod())
+ expected.name = "value"
+ tm.assert_series_equal(actual, expected)
+
+ df = DataFrame({"key": ["b"] * 100, "value": 2})
+ df["value"] = df["value"].astype(float)
+ actual = df.groupby("key")["value"].cumprod()
+ expected = df.groupby("key", group_keys=False)["value"].apply(lambda x: x.cumprod())
+ expected.name = "value"
+ tm.assert_series_equal(actual, expected)
+
+
+def test_groupby_cumprod_overflow():
+ # GH#37493 if we overflow we return garbage consistent with numpy
+ df = DataFrame({"key": ["b"] * 4, "value": 100_000})
+ actual = df.groupby("key")["value"].cumprod()
+ expected = Series(
+ [100_000, 10_000_000_000, 1_000_000_000_000_000, 7766279631452241920],
+ name="value",
+ )
+ tm.assert_series_equal(actual, expected)
+
+ numpy_result = df.groupby("key", group_keys=False)["value"].apply(
+ lambda x: x.cumprod()
+ )
+ numpy_result.name = "value"
+ tm.assert_series_equal(actual, numpy_result)
+
+
+def test_groupby_cumprod_nan_influences_other_columns():
+ # GH#48064
+ df = DataFrame(
+ {
+ "a": 1,
+ "b": [1, np.nan, 2],
+ "c": [1, 2, 3.0],
+ }
+ )
+ result = df.groupby("a").cumprod(numeric_only=True, skipna=False)
+ expected = DataFrame({"b": [1, np.nan, np.nan], "c": [1, 2, 6.0]})
+ tm.assert_frame_equal(result, expected)
+
+
+def scipy_sem(*args, **kwargs):
+ from scipy.stats import sem
+
+ return sem(*args, ddof=1, **kwargs)
+
+
+@pytest.mark.parametrize(
+ "op,targop",
+ [
+ ("mean", np.mean),
+ ("median", np.median),
+ ("std", np.std),
+ ("var", np.var),
+ ("sum", np.sum),
+ ("prod", np.prod),
+ ("min", np.min),
+ ("max", np.max),
+ ("first", lambda x: x.iloc[0]),
+ ("last", lambda x: x.iloc[-1]),
+ ("count", np.size),
+ pytest.param("sem", scipy_sem, marks=td.skip_if_no_scipy),
+ ],
+)
+def test_ops_general(op, targop):
+ df = DataFrame(np.random.default_rng(2).standard_normal(1000))
+ labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float)
+
+ result = getattr(df.groupby(labels), op)()
+ warn = None if op in ("first", "last", "count", "sem") else FutureWarning
+ msg = f"using DataFrameGroupBy.{op}"
+ with tm.assert_produces_warning(warn, match=msg):
+ expected = df.groupby(labels).agg(targop)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_max_nan_bug():
+ raw = """,Date,app,File
+-04-23,2013-04-23 00:00:00,,log080001.log
+-05-06,2013-05-06 00:00:00,,log.log
+-05-07,2013-05-07 00:00:00,OE,xlsx"""
+
+ with tm.assert_produces_warning(UserWarning, match="Could not infer format"):
+ df = pd.read_csv(StringIO(raw), parse_dates=[0])
+ gb = df.groupby("Date")
+ r = gb[["File"]].max()
+ e = gb["File"].max().to_frame()
+ tm.assert_frame_equal(r, e)
+ assert not r["File"].isna().any()
+
+
+def test_nlargest():
+ a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10])
+ b = Series(list("a" * 5 + "b" * 5))
+ gb = a.groupby(b)
+ r = gb.nlargest(3)
+ e = Series(
+ [7, 5, 3, 10, 9, 6],
+ index=MultiIndex.from_arrays([list("aaabbb"), [3, 2, 1, 9, 5, 8]]),
+ )
+ tm.assert_series_equal(r, e)
+
+ a = Series([1, 1, 3, 2, 0, 3, 3, 2, 1, 0])
+ gb = a.groupby(b)
+ e = Series(
+ [3, 2, 1, 3, 3, 2],
+ index=MultiIndex.from_arrays([list("aaabbb"), [2, 3, 1, 6, 5, 7]]),
+ )
+ tm.assert_series_equal(gb.nlargest(3, keep="last"), e)
+
+
+def test_nlargest_mi_grouper():
+ # see gh-21411
+ npr = np.random.default_rng(2)
+
+ dts = date_range("20180101", periods=10)
+ iterables = [dts, ["one", "two"]]
+
+ idx = MultiIndex.from_product(iterables, names=["first", "second"])
+ s = Series(npr.standard_normal(20), index=idx)
+
+ result = s.groupby("first").nlargest(1)
+
+ exp_idx = MultiIndex.from_tuples(
+ [
+ (dts[0], dts[0], "one"),
+ (dts[1], dts[1], "one"),
+ (dts[2], dts[2], "one"),
+ (dts[3], dts[3], "two"),
+ (dts[4], dts[4], "one"),
+ (dts[5], dts[5], "one"),
+ (dts[6], dts[6], "one"),
+ (dts[7], dts[7], "one"),
+ (dts[8], dts[8], "one"),
+ (dts[9], dts[9], "one"),
+ ],
+ names=["first", "first", "second"],
+ )
+
+ exp_values = [
+ 0.18905338179353307,
+ -0.41306354339189344,
+ 1.799707382720902,
+ 0.7738065867276614,
+ 0.28121066979764925,
+ 0.9775674511260357,
+ -0.3288239040579627,
+ 0.45495807124085547,
+ 0.5452887139646817,
+ 0.12682784711186987,
+ ]
+
+ expected = Series(exp_values, index=exp_idx)
+ tm.assert_series_equal(result, expected, check_exact=False, rtol=1e-3)
+
+
+def test_nsmallest():
+ a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10])
+ b = Series(list("a" * 5 + "b" * 5))
+ gb = a.groupby(b)
+ r = gb.nsmallest(3)
+ e = Series(
+ [1, 2, 3, 0, 4, 6],
+ index=MultiIndex.from_arrays([list("aaabbb"), [0, 4, 1, 6, 7, 8]]),
+ )
+ tm.assert_series_equal(r, e)
+
+ a = Series([1, 1, 3, 2, 0, 3, 3, 2, 1, 0])
+ gb = a.groupby(b)
+ e = Series(
+ [0, 1, 1, 0, 1, 2],
+ index=MultiIndex.from_arrays([list("aaabbb"), [4, 1, 0, 9, 8, 7]]),
+ )
+ tm.assert_series_equal(gb.nsmallest(3, keep="last"), e)
+
+
+@pytest.mark.parametrize(
+ "data, groups",
+ [([0, 1, 2, 3], [0, 0, 1, 1]), ([0], [0])],
+)
+@pytest.mark.parametrize("dtype", [None, *tm.ALL_INT_NUMPY_DTYPES])
+@pytest.mark.parametrize("method", ["nlargest", "nsmallest"])
+def test_nlargest_and_smallest_noop(data, groups, dtype, method):
+ # GH 15272, GH 16345, GH 29129
+ # Test nlargest/smallest when it results in a noop,
+ # i.e. input is sorted and group size <= n
+ if dtype is not None:
+ data = np.array(data, dtype=dtype)
+ if method == "nlargest":
+ data = list(reversed(data))
+ ser = Series(data, name="a")
+ result = getattr(ser.groupby(groups), method)(n=2)
+ expidx = np.array(groups, dtype=int) if isinstance(groups, list) else groups
+ expected = Series(data, index=MultiIndex.from_arrays([expidx, ser.index]), name="a")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", ["cumprod", "cumsum"])
+def test_numpy_compat(func):
+ # see gh-12811
+ df = DataFrame({"A": [1, 2, 1], "B": [1, 2, 3]})
+ g = df.groupby("A")
+
+ msg = "numpy operations are not valid with groupby"
+
+ with pytest.raises(UnsupportedFunctionCall, match=msg):
+ getattr(g, func)(1, 2, 3)
+ with pytest.raises(UnsupportedFunctionCall, match=msg):
+ getattr(g, func)(foo=1)
+
+
+def test_cummin(dtypes_for_minmax):
+ dtype = dtypes_for_minmax[0]
+ min_val = dtypes_for_minmax[1]
+
+ # GH 15048
+ base_df = DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]})
+ expected_mins = [3, 3, 3, 2, 2, 2, 2, 1]
+
+ df = base_df.astype(dtype)
+
+ expected = DataFrame({"B": expected_mins}).astype(dtype)
+ result = df.groupby("A").cummin()
+ tm.assert_frame_equal(result, expected)
+ result = df.groupby("A", group_keys=False).B.apply(lambda x: x.cummin()).to_frame()
+ tm.assert_frame_equal(result, expected)
+
+ # Test w/ min value for dtype
+ df.loc[[2, 6], "B"] = min_val
+ df.loc[[1, 5], "B"] = min_val + 1
+ expected.loc[[2, 3, 6, 7], "B"] = min_val
+ expected.loc[[1, 5], "B"] = min_val + 1 # should not be rounded to min_val
+ result = df.groupby("A").cummin()
+ tm.assert_frame_equal(result, expected, check_exact=True)
+ expected = (
+ df.groupby("A", group_keys=False).B.apply(lambda x: x.cummin()).to_frame()
+ )
+ tm.assert_frame_equal(result, expected, check_exact=True)
+
+ # Test nan in some values
+ # Explicit cast to float to avoid implicit cast when setting nan
+ base_df = base_df.astype({"B": "float"})
+ base_df.loc[[0, 2, 4, 6], "B"] = np.nan
+ expected = DataFrame({"B": [np.nan, 4, np.nan, 2, np.nan, 3, np.nan, 1]})
+ result = base_df.groupby("A").cummin()
+ tm.assert_frame_equal(result, expected)
+ expected = (
+ base_df.groupby("A", group_keys=False).B.apply(lambda x: x.cummin()).to_frame()
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # GH 15561
+ df = DataFrame({"a": [1], "b": pd.to_datetime(["2001"])})
+ expected = Series(pd.to_datetime("2001"), index=[0], name="b")
+
+ result = df.groupby("a")["b"].cummin()
+ tm.assert_series_equal(expected, result)
+
+ # GH 15635
+ df = DataFrame({"a": [1, 2, 1], "b": [1, 2, 2]})
+ result = df.groupby("a").b.cummin()
+ expected = Series([1, 2, 1], name="b")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["cummin", "cummax"])
+@pytest.mark.parametrize("dtype", ["UInt64", "Int64", "Float64", "float", "boolean"])
+def test_cummin_max_all_nan_column(method, dtype):
+ base_df = DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [np.nan] * 8})
+ base_df["B"] = base_df["B"].astype(dtype)
+ grouped = base_df.groupby("A")
+
+ expected = DataFrame({"B": [np.nan] * 8}, dtype=dtype)
+ result = getattr(grouped, method)()
+ tm.assert_frame_equal(expected, result)
+
+ result = getattr(grouped["B"], method)().to_frame()
+ tm.assert_frame_equal(expected, result)
+
+
+def test_cummax(dtypes_for_minmax):
+ dtype = dtypes_for_minmax[0]
+ max_val = dtypes_for_minmax[2]
+
+ # GH 15048
+ base_df = DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]})
+ expected_maxs = [3, 4, 4, 4, 2, 3, 3, 3]
+
+ df = base_df.astype(dtype)
+
+ expected = DataFrame({"B": expected_maxs}).astype(dtype)
+ result = df.groupby("A").cummax()
+ tm.assert_frame_equal(result, expected)
+ result = df.groupby("A", group_keys=False).B.apply(lambda x: x.cummax()).to_frame()
+ tm.assert_frame_equal(result, expected)
+
+ # Test w/ max value for dtype
+ df.loc[[2, 6], "B"] = max_val
+ expected.loc[[2, 3, 6, 7], "B"] = max_val
+ result = df.groupby("A").cummax()
+ tm.assert_frame_equal(result, expected)
+ expected = (
+ df.groupby("A", group_keys=False).B.apply(lambda x: x.cummax()).to_frame()
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # Test nan in some values
+ # Explicit cast to float to avoid implicit cast when setting nan
+ base_df = base_df.astype({"B": "float"})
+ base_df.loc[[0, 2, 4, 6], "B"] = np.nan
+ expected = DataFrame({"B": [np.nan, 4, np.nan, 4, np.nan, 3, np.nan, 3]})
+ result = base_df.groupby("A").cummax()
+ tm.assert_frame_equal(result, expected)
+ expected = (
+ base_df.groupby("A", group_keys=False).B.apply(lambda x: x.cummax()).to_frame()
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # GH 15561
+ df = DataFrame({"a": [1], "b": pd.to_datetime(["2001"])})
+ expected = Series(pd.to_datetime("2001"), index=[0], name="b")
+
+ result = df.groupby("a")["b"].cummax()
+ tm.assert_series_equal(expected, result)
+
+ # GH 15635
+ df = DataFrame({"a": [1, 2, 1], "b": [2, 1, 1]})
+ result = df.groupby("a").b.cummax()
+ expected = Series([2, 1, 2], name="b")
+ tm.assert_series_equal(result, expected)
+
+
+def test_cummax_i8_at_implementation_bound():
+ # the minimum value used to be treated as NPY_NAT+1 instead of NPY_NAT
+ # for int64 dtype GH#46382
+ ser = Series([pd.NaT._value + n for n in range(5)])
+ df = DataFrame({"A": 1, "B": ser, "C": ser.view("M8[ns]")})
+ gb = df.groupby("A")
+
+ res = gb.cummax()
+ exp = df[["B", "C"]]
+ tm.assert_frame_equal(res, exp)
+
+
+@pytest.mark.parametrize("method", ["cummin", "cummax"])
+@pytest.mark.parametrize("dtype", ["float", "Int64", "Float64"])
+@pytest.mark.parametrize(
+ "groups,expected_data",
+ [
+ ([1, 1, 1], [1, None, None]),
+ ([1, 2, 3], [1, None, 2]),
+ ([1, 3, 3], [1, None, None]),
+ ],
+)
+def test_cummin_max_skipna(method, dtype, groups, expected_data):
+ # GH-34047
+ df = DataFrame({"a": Series([1, None, 2], dtype=dtype)})
+ orig = df.copy()
+ gb = df.groupby(groups)["a"]
+
+ result = getattr(gb, method)(skipna=False)
+ expected = Series(expected_data, dtype=dtype, name="a")
+
+ # check we didn't accidentally alter df
+ tm.assert_frame_equal(df, orig)
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["cummin", "cummax"])
+def test_cummin_max_skipna_multiple_cols(method):
+ # Ensure missing value in "a" doesn't cause "b" to be nan-filled
+ df = DataFrame({"a": [np.nan, 2.0, 2.0], "b": [2.0, 2.0, 2.0]})
+ gb = df.groupby([1, 1, 1])[["a", "b"]]
+
+ result = getattr(gb, method)(skipna=False)
+ expected = DataFrame({"a": [np.nan, np.nan, np.nan], "b": [2.0, 2.0, 2.0]})
+
+ tm.assert_frame_equal(result, expected)
+
+
+@td.skip_if_32bit
+@pytest.mark.parametrize("method", ["cummin", "cummax"])
+@pytest.mark.parametrize(
+ "dtype,val", [("UInt64", np.iinfo("uint64").max), ("Int64", 2**53 + 1)]
+)
+def test_nullable_int_not_cast_as_float(method, dtype, val):
+ data = [val, pd.NA]
+ df = DataFrame({"grp": [1, 1], "b": data}, dtype=dtype)
+ grouped = df.groupby("grp")
+
+ result = grouped.transform(method)
+ expected = DataFrame({"b": data}, dtype=dtype)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "in_vals, out_vals",
+ [
+ # Basics: strictly increasing (T), strictly decreasing (F),
+ # abs val increasing (F), non-strictly increasing (T)
+ ([1, 2, 5, 3, 2, 0, 4, 5, -6, 1, 1], [True, False, False, True]),
+ # Test with inf vals
+ (
+ [1, 2.1, np.inf, 3, 2, np.inf, -np.inf, 5, 11, 1, -np.inf],
+ [True, False, True, False],
+ ),
+ # Test with nan vals; should always be False
+ (
+ [1, 2, np.nan, 3, 2, np.nan, np.nan, 5, -np.inf, 1, np.nan],
+ [False, False, False, False],
+ ),
+ ],
+)
+def test_is_monotonic_increasing(in_vals, out_vals):
+ # GH 17015
+ source_dict = {
+ "A": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"],
+ "B": ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d"],
+ "C": in_vals,
+ }
+ df = DataFrame(source_dict)
+ result = df.groupby("B").C.is_monotonic_increasing
+ index = Index(list("abcd"), name="B")
+ expected = Series(index=index, data=out_vals, name="C")
+ tm.assert_series_equal(result, expected)
+
+ # Also check result equal to manually taking x.is_monotonic_increasing.
+ expected = df.groupby(["B"]).C.apply(lambda x: x.is_monotonic_increasing)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "in_vals, out_vals",
+ [
+ # Basics: strictly decreasing (T), strictly increasing (F),
+ # abs val decreasing (F), non-strictly increasing (T)
+ ([10, 9, 7, 3, 4, 5, -3, 2, 0, 1, 1], [True, False, False, True]),
+ # Test with inf vals
+ (
+ [np.inf, 1, -np.inf, np.inf, 2, -3, -np.inf, 5, -3, -np.inf, -np.inf],
+ [True, True, False, True],
+ ),
+ # Test with nan vals; should always be False
+ (
+ [1, 2, np.nan, 3, 2, np.nan, np.nan, 5, -np.inf, 1, np.nan],
+ [False, False, False, False],
+ ),
+ ],
+)
+def test_is_monotonic_decreasing(in_vals, out_vals):
+ # GH 17015
+ source_dict = {
+ "A": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"],
+ "B": ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d"],
+ "C": in_vals,
+ }
+
+ df = DataFrame(source_dict)
+ result = df.groupby("B").C.is_monotonic_decreasing
+ index = Index(list("abcd"), name="B")
+ expected = Series(index=index, data=out_vals, name="C")
+ tm.assert_series_equal(result, expected)
+
+
+# describe
+# --------------------------------
+
+
+def test_apply_describe_bug(mframe):
+ grouped = mframe.groupby(level="first")
+ grouped.describe() # it works!
+
+
+def test_series_describe_multikey():
+ ts = tm.makeTimeSeries()
+ grouped = ts.groupby([lambda x: x.year, lambda x: x.month])
+ result = grouped.describe()
+ tm.assert_series_equal(result["mean"], grouped.mean(), check_names=False)
+ tm.assert_series_equal(result["std"], grouped.std(), check_names=False)
+ tm.assert_series_equal(result["min"], grouped.min(), check_names=False)
+
+
+def test_series_describe_single():
+ ts = tm.makeTimeSeries()
+ grouped = ts.groupby(lambda x: x.month)
+ result = grouped.apply(lambda x: x.describe())
+ expected = grouped.describe().stack(future_stack=True)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("keys", ["key1", ["key1", "key2"]])
+def test_series_describe_as_index(as_index, keys):
+ # GH#49256
+ df = DataFrame(
+ {
+ "key1": ["one", "two", "two", "three", "two"],
+ "key2": ["one", "two", "two", "three", "two"],
+ "foo2": [1, 2, 4, 4, 6],
+ }
+ )
+ gb = df.groupby(keys, as_index=as_index)["foo2"]
+ result = gb.describe()
+ expected = DataFrame(
+ {
+ "key1": ["one", "three", "two"],
+ "count": [1.0, 1.0, 3.0],
+ "mean": [1.0, 4.0, 4.0],
+ "std": [np.nan, np.nan, 2.0],
+ "min": [1.0, 4.0, 2.0],
+ "25%": [1.0, 4.0, 3.0],
+ "50%": [1.0, 4.0, 4.0],
+ "75%": [1.0, 4.0, 5.0],
+ "max": [1.0, 4.0, 6.0],
+ }
+ )
+ if len(keys) == 2:
+ expected.insert(1, "key2", expected["key1"])
+ if as_index:
+ expected = expected.set_index(keys)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_series_index_name(df):
+ grouped = df.loc[:, ["C"]].groupby(df["A"])
+ result = grouped.agg(lambda x: x.mean())
+ assert result.index.name == "A"
+
+
+def test_frame_describe_multikey(tsframe):
+ grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month])
+ result = grouped.describe()
+ desc_groups = []
+ for col in tsframe:
+ group = grouped[col].describe()
+ # GH 17464 - Remove duplicate MultiIndex levels
+ group_col = MultiIndex(
+ levels=[[col], group.columns],
+ codes=[[0] * len(group.columns), range(len(group.columns))],
+ )
+ group = DataFrame(group.values, columns=group_col, index=group.index)
+ desc_groups.append(group)
+ expected = pd.concat(desc_groups, axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ groupedT = tsframe.groupby({"A": 0, "B": 0, "C": 1, "D": 1}, axis=1)
+ result = groupedT.describe()
+ expected = tsframe.describe().T
+ # reverting the change from https://github.com/pandas-dev/pandas/pull/35441/
+ expected.index = MultiIndex(
+ levels=[[0, 1], expected.index],
+ codes=[[0, 0, 1, 1], range(len(expected.index))],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_frame_describe_tupleindex():
+ # GH 14848 - regression from 0.19.0 to 0.19.1
+ df1 = DataFrame(
+ {
+ "x": [1, 2, 3, 4, 5] * 3,
+ "y": [10, 20, 30, 40, 50] * 3,
+ "z": [100, 200, 300, 400, 500] * 3,
+ }
+ )
+ df1["k"] = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] * 5
+ df2 = df1.rename(columns={"k": "key"})
+ msg = "Names should be list-like for a MultiIndex"
+ with pytest.raises(ValueError, match=msg):
+ df1.groupby("k").describe()
+ with pytest.raises(ValueError, match=msg):
+ df2.groupby("key").describe()
+
+
+def test_frame_describe_unstacked_format():
+ # GH 4792
+ prices = {
+ Timestamp("2011-01-06 10:59:05", tz=None): 24990,
+ Timestamp("2011-01-06 12:43:33", tz=None): 25499,
+ Timestamp("2011-01-06 12:54:09", tz=None): 25499,
+ }
+ volumes = {
+ Timestamp("2011-01-06 10:59:05", tz=None): 1500000000,
+ Timestamp("2011-01-06 12:43:33", tz=None): 5000000000,
+ Timestamp("2011-01-06 12:54:09", tz=None): 100000000,
+ }
+ df = DataFrame({"PRICE": prices, "VOLUME": volumes})
+ result = df.groupby("PRICE").VOLUME.describe()
+ data = [
+ df[df.PRICE == 24990].VOLUME.describe().values.tolist(),
+ df[df.PRICE == 25499].VOLUME.describe().values.tolist(),
+ ]
+ expected = DataFrame(
+ data,
+ index=Index([24990, 25499], name="PRICE"),
+ columns=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.filterwarnings(
+ "ignore:"
+ "indexing past lexsort depth may impact performance:"
+ "pandas.errors.PerformanceWarning"
+)
+@pytest.mark.parametrize("as_index", [True, False])
+@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]])
+def test_describe_with_duplicate_output_column_names(as_index, keys):
+ # GH 35314
+ df = DataFrame(
+ {
+ "a1": [99, 99, 99, 88, 88, 88],
+ "a2": [99, 99, 99, 88, 88, 88],
+ "b": [1, 2, 3, 4, 5, 6],
+ "c": [10, 20, 30, 40, 50, 60],
+ },
+ columns=["a1", "a2", "b", "b"],
+ copy=False,
+ )
+ if keys == ["a1"]:
+ df = df.drop(columns="a2")
+
+ expected = (
+ DataFrame.from_records(
+ [
+ ("b", "count", 3.0, 3.0),
+ ("b", "mean", 5.0, 2.0),
+ ("b", "std", 1.0, 1.0),
+ ("b", "min", 4.0, 1.0),
+ ("b", "25%", 4.5, 1.5),
+ ("b", "50%", 5.0, 2.0),
+ ("b", "75%", 5.5, 2.5),
+ ("b", "max", 6.0, 3.0),
+ ("b", "count", 3.0, 3.0),
+ ("b", "mean", 5.0, 2.0),
+ ("b", "std", 1.0, 1.0),
+ ("b", "min", 4.0, 1.0),
+ ("b", "25%", 4.5, 1.5),
+ ("b", "50%", 5.0, 2.0),
+ ("b", "75%", 5.5, 2.5),
+ ("b", "max", 6.0, 3.0),
+ ],
+ )
+ .set_index([0, 1])
+ .T
+ )
+ expected.columns.names = [None, None]
+ if len(keys) == 2:
+ expected.index = MultiIndex(
+ levels=[[88, 99], [88, 99]], codes=[[0, 1], [0, 1]], names=["a1", "a2"]
+ )
+ else:
+ expected.index = Index([88, 99], name="a1")
+
+ if not as_index:
+ expected = expected.reset_index()
+
+ result = df.groupby(keys, as_index=as_index).describe()
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_describe_duplicate_columns():
+ # GH#50806
+ df = DataFrame([[0, 1, 2, 3]])
+ df.columns = [0, 1, 2, 0]
+ gb = df.groupby(df[1])
+ result = gb.describe(percentiles=[])
+
+ columns = ["count", "mean", "std", "min", "50%", "max"]
+ frames = [
+ DataFrame([[1.0, val, np.nan, val, val, val]], index=[1], columns=columns)
+ for val in (0.0, 2.0, 3.0)
+ ]
+ expected = pd.concat(frames, axis=1)
+ expected.columns = MultiIndex(
+ levels=[[0, 2], columns],
+ codes=[6 * [0] + 6 * [1] + 6 * [0], 3 * list(range(6))],
+ )
+ expected.index.names = [1]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_mean_no_overflow():
+ # Regression test for (#22487)
+ df = DataFrame(
+ {
+ "user": ["A", "A", "A", "A", "A"],
+ "connections": [4970, 4749, 4719, 4704, 18446744073699999744],
+ }
+ )
+ assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840
+
+
+@pytest.mark.parametrize(
+ "values",
+ [
+ {
+ "a": [1, 1, 1, 2, 2, 2, 3, 3, 3],
+ "b": [1, pd.NA, 2, 1, pd.NA, 2, 1, pd.NA, 2],
+ },
+ {"a": [1, 1, 2, 2, 3, 3], "b": [1, 2, 1, 2, 1, 2]},
+ ],
+)
+@pytest.mark.parametrize("function", ["mean", "median", "var"])
+def test_apply_to_nullable_integer_returns_float(values, function):
+ # https://github.com/pandas-dev/pandas/issues/32219
+ output = 0.5 if function == "var" else 1.5
+ arr = np.array([output] * 3, dtype=float)
+ idx = Index([1, 2, 3], name="a", dtype="Int64")
+ expected = DataFrame({"b": arr}, index=idx).astype("Float64")
+
+ groups = DataFrame(values, dtype="Int64").groupby("a")
+
+ result = getattr(groups, function)()
+ tm.assert_frame_equal(result, expected)
+
+ result = groups.agg(function)
+ tm.assert_frame_equal(result, expected)
+
+ result = groups.agg([function])
+ expected.columns = MultiIndex.from_tuples([("b", function)])
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("min_count", [0, 10])
+def test_groupby_sum_mincount_boolean(min_count):
+ b = True
+ a = False
+ na = np.nan
+ dfg = pd.array([b, b, na, na, a, a, b], dtype="boolean")
+
+ df = DataFrame({"A": [1, 1, 2, 2, 3, 3, 1], "B": dfg})
+ result = df.groupby("A").sum(min_count=min_count)
+ if min_count == 0:
+ expected = DataFrame(
+ {"B": pd.array([3, 0, 0], dtype="Int64")},
+ index=Index([1, 2, 3], name="A"),
+ )
+ tm.assert_frame_equal(result, expected)
+ else:
+ expected = DataFrame(
+ {"B": pd.array([pd.NA] * 3, dtype="Int64")},
+ index=Index([1, 2, 3], name="A"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_sum_below_mincount_nullable_integer():
+ # https://github.com/pandas-dev/pandas/issues/32861
+ df = DataFrame({"a": [0, 1, 2], "b": [0, 1, 2], "c": [0, 1, 2]}, dtype="Int64")
+ grouped = df.groupby("a")
+ idx = Index([0, 1, 2], name="a", dtype="Int64")
+
+ result = grouped["b"].sum(min_count=2)
+ expected = Series([pd.NA] * 3, dtype="Int64", index=idx, name="b")
+ tm.assert_series_equal(result, expected)
+
+ result = grouped.sum(min_count=2)
+ expected = DataFrame({"b": [pd.NA] * 3, "c": [pd.NA] * 3}, dtype="Int64", index=idx)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_mean_on_timedelta():
+ # GH 17382
+ df = DataFrame({"time": pd.to_timedelta(range(10)), "cat": ["A", "B"] * 5})
+ result = df.groupby("cat")["time"].mean()
+ expected = Series(
+ pd.to_timedelta([4, 5]), name="time", index=Index(["A", "B"], name="cat")
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_sum_timedelta_with_nat():
+ # GH#42659
+ df = DataFrame(
+ {
+ "a": [1, 1, 2, 2],
+ "b": [pd.Timedelta("1d"), pd.Timedelta("2d"), pd.Timedelta("3d"), pd.NaT],
+ }
+ )
+ td3 = pd.Timedelta(days=3)
+
+ gb = df.groupby("a")
+
+ res = gb.sum()
+ expected = DataFrame({"b": [td3, td3]}, index=Index([1, 2], name="a"))
+ tm.assert_frame_equal(res, expected)
+
+ res = gb["b"].sum()
+ tm.assert_series_equal(res, expected["b"])
+
+ res = gb["b"].sum(min_count=2)
+ expected = Series([td3, pd.NaT], dtype="m8[ns]", name="b", index=expected.index)
+ tm.assert_series_equal(res, expected)
+
+
+@pytest.mark.parametrize(
+ "kernel, has_arg",
+ [
+ ("all", False),
+ ("any", False),
+ ("bfill", False),
+ ("corr", True),
+ ("corrwith", True),
+ ("cov", True),
+ ("cummax", True),
+ ("cummin", True),
+ ("cumprod", True),
+ ("cumsum", True),
+ ("diff", False),
+ ("ffill", False),
+ ("fillna", False),
+ ("first", True),
+ ("idxmax", True),
+ ("idxmin", True),
+ ("last", True),
+ ("max", True),
+ ("mean", True),
+ ("median", True),
+ ("min", True),
+ ("nth", False),
+ ("nunique", False),
+ ("pct_change", False),
+ ("prod", True),
+ ("quantile", True),
+ ("sem", True),
+ ("skew", True),
+ ("std", True),
+ ("sum", True),
+ ("var", True),
+ ],
+)
+@pytest.mark.parametrize("numeric_only", [True, False, lib.no_default])
+@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]])
+def test_numeric_only(kernel, has_arg, numeric_only, keys):
+ # GH#46072
+ # drops_nuisance: Whether the op drops nuisance columns even when numeric_only=False
+ # has_arg: Whether the op has a numeric_only arg
+ df = DataFrame({"a1": [1, 1], "a2": [2, 2], "a3": [5, 6], "b": 2 * [object]})
+
+ args = get_groupby_method_args(kernel, df)
+ kwargs = {} if numeric_only is lib.no_default else {"numeric_only": numeric_only}
+
+ gb = df.groupby(keys)
+ method = getattr(gb, kernel)
+ if has_arg and numeric_only is True:
+ # Cases where b does not appear in the result
+ result = method(*args, **kwargs)
+ assert "b" not in result.columns
+ elif (
+ # kernels that work on any dtype and have numeric_only arg
+ kernel in ("first", "last")
+ or (
+ # kernels that work on any dtype and don't have numeric_only arg
+ kernel in ("any", "all", "bfill", "ffill", "fillna", "nth", "nunique")
+ and numeric_only is lib.no_default
+ )
+ ):
+ result = method(*args, **kwargs)
+ assert "b" in result.columns
+ elif has_arg:
+ assert numeric_only is not True
+ # kernels that are successful on any dtype were above; this will fail
+
+ # object dtypes for transformations are not implemented in Cython and
+ # have no Python fallback
+ exception = NotImplementedError if kernel.startswith("cum") else TypeError
+
+ msg = "|".join(
+ [
+ "not allowed for this dtype",
+ "cannot be performed against 'object' dtypes",
+ # On PY39 message is "a number"; on PY310 and after is "a real number"
+ "must be a string or a.* number",
+ "unsupported operand type",
+ "function is not implemented for this dtype",
+ re.escape(f"agg function failed [how->{kernel},dtype->object]"),
+ ]
+ )
+ if kernel == "idxmin":
+ msg = "'<' not supported between instances of 'type' and 'type'"
+ elif kernel == "idxmax":
+ msg = "'>' not supported between instances of 'type' and 'type'"
+ with pytest.raises(exception, match=msg):
+ method(*args, **kwargs)
+ elif not has_arg and numeric_only is not lib.no_default:
+ with pytest.raises(
+ TypeError, match="got an unexpected keyword argument 'numeric_only'"
+ ):
+ method(*args, **kwargs)
+ else:
+ assert kernel in ("diff", "pct_change")
+ assert numeric_only is lib.no_default
+ # Doesn't have numeric_only argument and fails on nuisance columns
+ with pytest.raises(TypeError, match=r"unsupported operand type"):
+ method(*args, **kwargs)
+
+
+@pytest.mark.parametrize("dtype", [bool, int, float, object])
+def test_deprecate_numeric_only_series(dtype, groupby_func, request):
+ # GH#46560
+ grouper = [0, 0, 1]
+
+ ser = Series([1, 0, 0], dtype=dtype)
+ gb = ser.groupby(grouper)
+
+ if groupby_func == "corrwith":
+ # corrwith is not implemented on SeriesGroupBy
+ assert not hasattr(gb, groupby_func)
+ return
+
+ method = getattr(gb, groupby_func)
+
+ expected_ser = Series([1, 0, 0])
+ expected_gb = expected_ser.groupby(grouper)
+ expected_method = getattr(expected_gb, groupby_func)
+
+ args = get_groupby_method_args(groupby_func, ser)
+
+ fails_on_numeric_object = (
+ "corr",
+ "cov",
+ "cummax",
+ "cummin",
+ "cumprod",
+ "cumsum",
+ "quantile",
+ )
+ # ops that give an object result on object input
+ obj_result = (
+ "first",
+ "last",
+ "nth",
+ "bfill",
+ "ffill",
+ "shift",
+ "sum",
+ "diff",
+ "pct_change",
+ "var",
+ "mean",
+ "median",
+ "min",
+ "max",
+ "prod",
+ "skew",
+ )
+
+ # Test default behavior; kernels that fail may be enabled in the future but kernels
+ # that succeed should not be allowed to fail (without deprecation, at least)
+ if groupby_func in fails_on_numeric_object and dtype is object:
+ if groupby_func == "quantile":
+ msg = "cannot be performed against 'object' dtypes"
+ else:
+ msg = "is not supported for object dtype"
+ with pytest.raises(TypeError, match=msg):
+ method(*args)
+ elif dtype is object:
+ result = method(*args)
+ expected = expected_method(*args)
+ if groupby_func in obj_result:
+ expected = expected.astype(object)
+ tm.assert_series_equal(result, expected)
+
+ has_numeric_only = (
+ "first",
+ "last",
+ "max",
+ "mean",
+ "median",
+ "min",
+ "prod",
+ "quantile",
+ "sem",
+ "skew",
+ "std",
+ "sum",
+ "var",
+ "cummax",
+ "cummin",
+ "cumprod",
+ "cumsum",
+ )
+ if groupby_func not in has_numeric_only:
+ msg = "got an unexpected keyword argument 'numeric_only'"
+ with pytest.raises(TypeError, match=msg):
+ method(*args, numeric_only=True)
+ elif dtype is object:
+ msg = "|".join(
+ [
+ "SeriesGroupBy.sem called with numeric_only=True and dtype object",
+ "Series.skew does not allow numeric_only=True with non-numeric",
+ "cum(sum|prod|min|max) is not supported for object dtype",
+ r"Cannot use numeric_only=True with SeriesGroupBy\..* and non-numeric",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ method(*args, numeric_only=True)
+ elif dtype == bool and groupby_func == "quantile":
+ msg = "Allowing bool dtype in SeriesGroupBy.quantile"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#51424
+ result = method(*args, numeric_only=True)
+ expected = method(*args, numeric_only=False)
+ tm.assert_series_equal(result, expected)
+ else:
+ result = method(*args, numeric_only=True)
+ expected = method(*args, numeric_only=False)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", [int, float, object])
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"percentiles": [0.10, 0.20, 0.30], "include": "all", "exclude": None},
+ {"percentiles": [0.10, 0.20, 0.30], "include": None, "exclude": ["int"]},
+ {"percentiles": [0.10, 0.20, 0.30], "include": ["int"], "exclude": None},
+ ],
+)
+def test_groupby_empty_dataset(dtype, kwargs):
+ # GH#41575
+ df = DataFrame([[1, 2, 3]], columns=["A", "B", "C"], dtype=dtype)
+ df["B"] = df["B"].astype(int)
+ df["C"] = df["C"].astype(float)
+
+ result = df.iloc[:0].groupby("A").describe(**kwargs)
+ expected = df.groupby("A").describe(**kwargs).reset_index(drop=True).iloc[:0]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[:0].groupby("A").B.describe(**kwargs)
+ expected = df.groupby("A").B.describe(**kwargs).reset_index(drop=True).iloc[:0]
+ expected.index = Index([])
+ tm.assert_frame_equal(result, expected)
+
+
+def test_corrwith_with_1_axis():
+ # GH 47723
+ df = DataFrame({"a": [1, 1, 2], "b": [3, 7, 4]})
+ gb = df.groupby("a")
+
+ msg = "DataFrameGroupBy.corrwith with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = gb.corrwith(df, axis=1)
+ index = Index(
+ data=[(1, 0), (1, 1), (1, 2), (2, 2), (2, 0), (2, 1)],
+ name=("a", None),
+ )
+ expected = Series([np.nan] * 6, index=index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_multiindex_group_all_columns_when_empty(groupby_func):
+ # GH 32464
+ df = DataFrame({"a": [], "b": [], "c": []}).set_index(["a", "b", "c"])
+ gb = df.groupby(["a", "b", "c"], group_keys=False)
+ method = getattr(gb, groupby_func)
+ args = get_groupby_method_args(groupby_func, df)
+
+ result = method(*args).index
+ expected = df.index
+ tm.assert_index_equal(result, expected)
+
+
+def test_duplicate_columns(request, groupby_func, as_index):
+ # GH#50806
+ if groupby_func == "corrwith":
+ msg = "GH#50845 - corrwith fails when there are duplicate columns"
+ request.node.add_marker(pytest.mark.xfail(reason=msg))
+ df = DataFrame([[1, 3, 6], [1, 4, 7], [2, 5, 8]], columns=list("abb"))
+ args = get_groupby_method_args(groupby_func, df)
+ gb = df.groupby("a", as_index=as_index)
+ result = getattr(gb, groupby_func)(*args)
+
+ expected_df = df.set_axis(["a", "b", "c"], axis=1)
+ expected_args = get_groupby_method_args(groupby_func, expected_df)
+ expected_gb = expected_df.groupby("a", as_index=as_index)
+ expected = getattr(expected_gb, groupby_func)(*expected_args)
+ if groupby_func not in ("size", "ngroup", "cumcount"):
+ expected = expected.rename(columns={"c": "b"})
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "op",
+ [
+ "sum",
+ "prod",
+ "min",
+ "max",
+ "median",
+ "mean",
+ "skew",
+ "std",
+ "var",
+ "sem",
+ ],
+)
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize("skipna", [True, False])
+@pytest.mark.parametrize("sort", [True, False])
+def test_regression_allowlist_methods(op, axis, skipna, sort):
+ # GH6944
+ # GH 17537
+ # explicitly test the allowlist methods
+ raw_frame = DataFrame([0])
+ if axis == 0:
+ frame = raw_frame
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated and will be"
+ else:
+ frame = raw_frame.T
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ grouped = frame.groupby(level=0, axis=axis, sort=sort)
+
+ if op == "skew":
+ # skew has skipna
+ result = getattr(grouped, op)(skipna=skipna)
+ expected = frame.groupby(level=0).apply(
+ lambda h: getattr(h, op)(axis=axis, skipna=skipna)
+ )
+ if sort:
+ expected = expected.sort_index(axis=axis)
+ tm.assert_frame_equal(result, expected)
+ else:
+ result = getattr(grouped, op)()
+ expected = frame.groupby(level=0).apply(lambda h: getattr(h, op)(axis=axis))
+ if sort:
+ expected = expected.sort_index(axis=axis)
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby.py
new file mode 100644
index 0000000000000000000000000000000000000000..49ae217513018f82a92456890d3ca2f660d8ab81
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby.py
@@ -0,0 +1,3200 @@
+from datetime import datetime
+from decimal import Decimal
+import re
+
+import numpy as np
+import pytest
+
+from pandas.errors import (
+ PerformanceWarning,
+ SpecificationError,
+)
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DataFrame,
+ Grouper,
+ Index,
+ Interval,
+ MultiIndex,
+ RangeIndex,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+ to_datetime,
+)
+import pandas._testing as tm
+from pandas.core.arrays import BooleanArray
+import pandas.core.common as com
+from pandas.tests.groupby import get_groupby_method_args
+
+pytestmark = pytest.mark.filterwarnings("ignore:Mean of empty slice:RuntimeWarning")
+
+
+def test_repr():
+ # GH18203
+ result = repr(Grouper(key="A", level="B"))
+ expected = "Grouper(key='A', level='B', axis=0, sort=False, dropna=True)"
+ assert result == expected
+
+
+def test_groupby_std_datetimelike():
+ # GH#48481
+ tdi = pd.timedelta_range("1 Day", periods=10000)
+ ser = Series(tdi)
+ ser[::5] *= 2 # get different std for different groups
+
+ df = ser.to_frame("A")
+
+ df["B"] = ser + Timestamp(0)
+ df["C"] = ser + Timestamp(0, tz="UTC")
+ df.iloc[-1] = pd.NaT # last group includes NaTs
+
+ gb = df.groupby(list(range(5)) * 2000)
+
+ result = gb.std()
+
+ # Note: this does not _exactly_ match what we would get if we did
+ # [gb.get_group(i).std() for i in gb.groups]
+ # but it _does_ match the floating point error we get doing the
+ # same operation on int64 data xref GH#51332
+ td1 = Timedelta("2887 days 11:21:02.326710176")
+ td4 = Timedelta("2886 days 00:42:34.664668096")
+ exp_ser = Series([td1 * 2, td1, td1, td1, td4], index=np.arange(5))
+ expected = DataFrame({"A": exp_ser, "B": exp_ser, "C": exp_ser})
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"])
+def test_basic_aggregations(dtype):
+ data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype)
+
+ index = np.arange(9)
+ np.random.default_rng(2).shuffle(index)
+ data = data.reindex(index)
+
+ grouped = data.groupby(lambda x: x // 3, group_keys=False)
+
+ for k, v in grouped:
+ assert len(v) == 3
+
+ msg = "using SeriesGroupBy.mean"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ agged = grouped.aggregate(np.mean)
+ assert agged[1] == 1
+
+ msg = "using SeriesGroupBy.mean"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = grouped.agg(np.mean)
+ tm.assert_series_equal(agged, expected) # shorthand
+ tm.assert_series_equal(agged, grouped.mean())
+ result = grouped.sum()
+ msg = "using SeriesGroupBy.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = grouped.agg(np.sum)
+ tm.assert_series_equal(result, expected)
+
+ expected = grouped.apply(lambda x: x * x.sum())
+ transformed = grouped.transform(lambda x: x * x.sum())
+ assert transformed[7] == 12
+ tm.assert_series_equal(transformed, expected)
+
+ value_grouped = data.groupby(data)
+ msg = "using SeriesGroupBy.mean"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = value_grouped.aggregate(np.mean)
+ tm.assert_series_equal(result, agged, check_index_type=False)
+
+ # complex agg
+ msg = "using SeriesGroupBy.[mean|std]"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ agged = grouped.aggregate([np.mean, np.std])
+
+ msg = r"nested renamer is not supported"
+ with pytest.raises(SpecificationError, match=msg):
+ grouped.aggregate({"one": np.mean, "two": np.std})
+
+ group_constants = {0: 10, 1: 20, 2: 30}
+ msg = (
+ "Pinning the groupby key to each group in SeriesGroupBy.agg is deprecated, "
+ "and cases that relied on it will raise in a future version"
+ )
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#41090
+ agged = grouped.agg(lambda x: group_constants[x.name] + x.mean())
+ assert agged[1] == 21
+
+ # corner cases
+ msg = "Must produce aggregated value"
+ # exception raised is type Exception
+ with pytest.raises(Exception, match=msg):
+ grouped.aggregate(lambda x: x * 2)
+
+
+def test_groupby_nonobject_dtype(mframe, df_mixed_floats):
+ key = mframe.index.codes[0]
+ grouped = mframe.groupby(key)
+ result = grouped.sum()
+
+ expected = mframe.groupby(key.astype("O")).sum()
+ assert result.index.dtype == np.int8
+ assert expected.index.dtype == np.int64
+ tm.assert_frame_equal(result, expected, check_index_type=False)
+
+ # GH 3911, mixed frame non-conversion
+ df = df_mixed_floats.copy()
+ df["value"] = range(len(df))
+
+ def max_value(group):
+ return group.loc[group["value"].idxmax()]
+
+ applied = df.groupby("A").apply(max_value)
+ result = applied.dtypes
+ expected = df.dtypes
+ tm.assert_series_equal(result, expected)
+
+
+def test_inconsistent_return_type():
+ # GH5592
+ # inconsistent return type
+ df = DataFrame(
+ {
+ "A": ["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"],
+ "B": Series(np.arange(7), dtype="int64"),
+ "C": date_range("20130101", periods=7),
+ }
+ )
+
+ def f_0(grp):
+ return grp.iloc[0]
+
+ expected = df.groupby("A").first()[["B"]]
+ result = df.groupby("A").apply(f_0)[["B"]]
+ tm.assert_frame_equal(result, expected)
+
+ def f_1(grp):
+ if grp.name == "Tiger":
+ return None
+ return grp.iloc[0]
+
+ result = df.groupby("A").apply(f_1)[["B"]]
+ # Cast to avoid upcast when setting nan below
+ e = expected.copy().astype("float64")
+ e.loc["Tiger"] = np.nan
+ tm.assert_frame_equal(result, e)
+
+ def f_2(grp):
+ if grp.name == "Pony":
+ return None
+ return grp.iloc[0]
+
+ result = df.groupby("A").apply(f_2)[["B"]]
+ # Explicit cast to float to avoid implicit cast when setting nan
+ e = expected.copy().astype({"B": "float"})
+ e.loc["Pony"] = np.nan
+ tm.assert_frame_equal(result, e)
+
+ # 5592 revisited, with datetimes
+ def f_3(grp):
+ if grp.name == "Pony":
+ return None
+ return grp.iloc[0]
+
+ result = df.groupby("A").apply(f_3)[["C"]]
+ e = df.groupby("A").first()[["C"]]
+ e.loc["Pony"] = pd.NaT
+ tm.assert_frame_equal(result, e)
+
+ # scalar outputs
+ def f_4(grp):
+ if grp.name == "Pony":
+ return None
+ return grp.iloc[0].loc["C"]
+
+ result = df.groupby("A").apply(f_4)
+ e = df.groupby("A").first()["C"].copy()
+ e.loc["Pony"] = np.nan
+ e.name = None
+ tm.assert_series_equal(result, e)
+
+
+def test_pass_args_kwargs(ts, tsframe):
+ def f(x, q=None, axis=0):
+ return np.percentile(x, q, axis=axis)
+
+ g = lambda x: np.percentile(x, 80, axis=0)
+
+ # Series
+ ts_grouped = ts.groupby(lambda x: x.month)
+ agg_result = ts_grouped.agg(np.percentile, 80, axis=0)
+ apply_result = ts_grouped.apply(np.percentile, 80, axis=0)
+ trans_result = ts_grouped.transform(np.percentile, 80, axis=0)
+
+ agg_expected = ts_grouped.quantile(0.8)
+ trans_expected = ts_grouped.transform(g)
+
+ tm.assert_series_equal(apply_result, agg_expected)
+ tm.assert_series_equal(agg_result, agg_expected)
+ tm.assert_series_equal(trans_result, trans_expected)
+
+ agg_result = ts_grouped.agg(f, q=80)
+ apply_result = ts_grouped.apply(f, q=80)
+ trans_result = ts_grouped.transform(f, q=80)
+ tm.assert_series_equal(agg_result, agg_expected)
+ tm.assert_series_equal(apply_result, agg_expected)
+ tm.assert_series_equal(trans_result, trans_expected)
+
+ # DataFrame
+ for as_index in [True, False]:
+ df_grouped = tsframe.groupby(lambda x: x.month, as_index=as_index)
+ warn = None if as_index else FutureWarning
+ msg = "A grouping .* was excluded from the result"
+ with tm.assert_produces_warning(warn, match=msg):
+ agg_result = df_grouped.agg(np.percentile, 80, axis=0)
+ with tm.assert_produces_warning(warn, match=msg):
+ apply_result = df_grouped.apply(DataFrame.quantile, 0.8)
+ with tm.assert_produces_warning(warn, match=msg):
+ expected = df_grouped.quantile(0.8)
+ tm.assert_frame_equal(apply_result, expected, check_names=False)
+ tm.assert_frame_equal(agg_result, expected)
+
+ apply_result = df_grouped.apply(DataFrame.quantile, [0.4, 0.8])
+ with tm.assert_produces_warning(warn, match=msg):
+ expected_seq = df_grouped.quantile([0.4, 0.8])
+ tm.assert_frame_equal(apply_result, expected_seq, check_names=False)
+
+ with tm.assert_produces_warning(warn, match=msg):
+ agg_result = df_grouped.agg(f, q=80)
+ with tm.assert_produces_warning(warn, match=msg):
+ apply_result = df_grouped.apply(DataFrame.quantile, q=0.8)
+ tm.assert_frame_equal(agg_result, expected)
+ tm.assert_frame_equal(apply_result, expected, check_names=False)
+
+
+@pytest.mark.parametrize("as_index", [True, False])
+def test_pass_args_kwargs_duplicate_columns(tsframe, as_index):
+ # go through _aggregate_frame with self.axis == 0 and duplicate columns
+ tsframe.columns = ["A", "B", "A", "C"]
+ gb = tsframe.groupby(lambda x: x.month, as_index=as_index)
+
+ warn = None if as_index else FutureWarning
+ msg = "A grouping .* was excluded from the result"
+ with tm.assert_produces_warning(warn, match=msg):
+ res = gb.agg(np.percentile, 80, axis=0)
+
+ ex_data = {
+ 1: tsframe[tsframe.index.month == 1].quantile(0.8),
+ 2: tsframe[tsframe.index.month == 2].quantile(0.8),
+ }
+ expected = DataFrame(ex_data).T
+ if not as_index:
+ # TODO: try to get this more consistent?
+ expected.index = Index(range(2))
+
+ tm.assert_frame_equal(res, expected)
+
+
+def test_len():
+ df = tm.makeTimeDataFrame()
+ grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
+ assert len(grouped) == len(df)
+
+ grouped = df.groupby([lambda x: x.year, lambda x: x.month])
+ expected = len({(x.year, x.month) for x in df.index})
+ assert len(grouped) == expected
+
+ # issue 11016
+ df = DataFrame({"a": [np.nan] * 3, "b": [1, 2, 3]})
+ assert len(df.groupby("a")) == 0
+ assert len(df.groupby("b")) == 3
+ assert len(df.groupby(["a", "b"])) == 3
+
+
+def test_basic_regression():
+ # regression
+ result = Series([1.0 * x for x in list(range(1, 10)) * 10])
+
+ data = np.random.default_rng(2).random(1100) * 10.0
+ groupings = Series(data)
+
+ grouped = result.groupby(groupings)
+ grouped.mean()
+
+
+@pytest.mark.parametrize(
+ "dtype", ["float64", "float32", "int64", "int32", "int16", "int8"]
+)
+def test_with_na_groups(dtype):
+ index = Index(np.arange(10))
+ values = Series(np.ones(10), index, dtype=dtype)
+ labels = Series(
+ [np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"],
+ index=index,
+ )
+
+ # this SHOULD be an int
+ grouped = values.groupby(labels)
+ agged = grouped.agg(len)
+ expected = Series([4, 2], index=["bar", "foo"])
+
+ tm.assert_series_equal(agged, expected, check_dtype=False)
+
+ # assert issubclass(agged.dtype.type, np.integer)
+
+ # explicitly return a float from my function
+ def f(x):
+ return float(len(x))
+
+ agged = grouped.agg(f)
+ expected = Series([4.0, 2.0], index=["bar", "foo"])
+
+ tm.assert_series_equal(agged, expected)
+
+
+def test_indices_concatenation_order():
+ # GH 2808
+
+ def f1(x):
+ y = x[(x.b % 2) == 1] ** 2
+ if y.empty:
+ multiindex = MultiIndex(levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"])
+ res = DataFrame(columns=["a"], index=multiindex)
+ return res
+ else:
+ y = y.set_index(["b", "c"])
+ return y
+
+ def f2(x):
+ y = x[(x.b % 2) == 1] ** 2
+ if y.empty:
+ return DataFrame()
+ else:
+ y = y.set_index(["b", "c"])
+ return y
+
+ def f3(x):
+ y = x[(x.b % 2) == 1] ** 2
+ if y.empty:
+ multiindex = MultiIndex(
+ levels=[[]] * 2, codes=[[]] * 2, names=["foo", "bar"]
+ )
+ res = DataFrame(columns=["a", "b"], index=multiindex)
+ return res
+ else:
+ return y
+
+ df = DataFrame({"a": [1, 2, 2, 2], "b": range(4), "c": range(5, 9)})
+
+ df2 = DataFrame({"a": [3, 2, 2, 2], "b": range(4), "c": range(5, 9)})
+
+ depr_msg = "The behavior of array concatenation with empty entries is deprecated"
+
+ # correct result
+ result1 = df.groupby("a").apply(f1)
+ result2 = df2.groupby("a").apply(f1)
+ tm.assert_frame_equal(result1, result2)
+
+ # should fail (not the same number of levels)
+ msg = "Cannot concat indices that do not have the same number of levels"
+ with pytest.raises(AssertionError, match=msg):
+ df.groupby("a").apply(f2)
+ with pytest.raises(AssertionError, match=msg):
+ df2.groupby("a").apply(f2)
+
+ # should fail (incorrect shape)
+ with pytest.raises(AssertionError, match=msg):
+ df.groupby("a").apply(f3)
+ with pytest.raises(AssertionError, match=msg):
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ df2.groupby("a").apply(f3)
+
+
+def test_attr_wrapper(ts):
+ grouped = ts.groupby(lambda x: x.weekday())
+
+ result = grouped.std()
+ expected = grouped.agg(lambda x: np.std(x, ddof=1))
+ tm.assert_series_equal(result, expected)
+
+ # this is pretty cool
+ result = grouped.describe()
+ expected = {name: gp.describe() for name, gp in grouped}
+ expected = DataFrame(expected).T
+ tm.assert_frame_equal(result, expected)
+
+ # get attribute
+ result = grouped.dtype
+ expected = grouped.agg(lambda x: x.dtype)
+ tm.assert_series_equal(result, expected)
+
+ # make sure raises error
+ msg = "'SeriesGroupBy' object has no attribute 'foo'"
+ with pytest.raises(AttributeError, match=msg):
+ getattr(grouped, "foo")
+
+
+def test_frame_groupby(tsframe):
+ grouped = tsframe.groupby(lambda x: x.weekday())
+
+ # aggregate
+ aggregated = grouped.aggregate("mean")
+ assert len(aggregated) == 5
+ assert len(aggregated.columns) == 4
+
+ # by string
+ tscopy = tsframe.copy()
+ tscopy["weekday"] = [x.weekday() for x in tscopy.index]
+ stragged = tscopy.groupby("weekday").aggregate("mean")
+ tm.assert_frame_equal(stragged, aggregated, check_names=False)
+
+ # transform
+ grouped = tsframe.head(30).groupby(lambda x: x.weekday())
+ transformed = grouped.transform(lambda x: x - x.mean())
+ assert len(transformed) == 30
+ assert len(transformed.columns) == 4
+
+ # transform propagate
+ transformed = grouped.transform(lambda x: x.mean())
+ for name, group in grouped:
+ mean = group.mean()
+ for idx in group.index:
+ tm.assert_series_equal(transformed.xs(idx), mean, check_names=False)
+
+ # iterate
+ for weekday, group in grouped:
+ assert group.index[0].weekday() == weekday
+
+ # groups / group_indices
+ groups = grouped.groups
+ indices = grouped.indices
+
+ for k, v in groups.items():
+ samething = tsframe.index.take(indices[k])
+ assert (samething == v).all()
+
+
+def test_frame_groupby_columns(tsframe):
+ mapping = {"A": 0, "B": 0, "C": 1, "D": 1}
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ grouped = tsframe.groupby(mapping, axis=1)
+
+ # aggregate
+ aggregated = grouped.aggregate("mean")
+ assert len(aggregated) == len(tsframe)
+ assert len(aggregated.columns) == 2
+
+ # transform
+ tf = lambda x: x - x.mean()
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ groupedT = tsframe.T.groupby(mapping, axis=0)
+ tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf))
+
+ # iterate
+ for k, v in grouped:
+ assert len(v.columns) == 2
+
+
+def test_frame_set_name_single(df):
+ grouped = df.groupby("A")
+
+ result = grouped.mean(numeric_only=True)
+ assert result.index.name == "A"
+
+ result = df.groupby("A", as_index=False).mean(numeric_only=True)
+ assert result.index.name != "A"
+
+ result = grouped[["C", "D"]].agg("mean")
+ assert result.index.name == "A"
+
+ result = grouped.agg({"C": "mean", "D": "std"})
+ assert result.index.name == "A"
+
+ result = grouped["C"].mean()
+ assert result.index.name == "A"
+ result = grouped["C"].agg("mean")
+ assert result.index.name == "A"
+ result = grouped["C"].agg(["mean", "std"])
+ assert result.index.name == "A"
+
+ msg = r"nested renamer is not supported"
+ with pytest.raises(SpecificationError, match=msg):
+ grouped["C"].agg({"foo": "mean", "bar": "std"})
+
+
+def test_multi_func(df):
+ col1 = df["A"]
+ col2 = df["B"]
+
+ grouped = df.groupby([col1.get, col2.get])
+ agged = grouped.mean(numeric_only=True)
+ expected = df.groupby(["A", "B"]).mean()
+
+ # TODO groupby get drops names
+ tm.assert_frame_equal(
+ agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names=False
+ )
+
+ # some "groups" with no data
+ df = DataFrame(
+ {
+ "v1": np.random.default_rng(2).standard_normal(6),
+ "v2": np.random.default_rng(2).standard_normal(6),
+ "k1": np.array(["b", "b", "b", "a", "a", "a"]),
+ "k2": np.array(["1", "1", "1", "2", "2", "2"]),
+ },
+ index=["one", "two", "three", "four", "five", "six"],
+ )
+ # only verify that it works for now
+ grouped = df.groupby(["k1", "k2"])
+ grouped.agg("sum")
+
+
+def test_multi_key_multiple_functions(df):
+ grouped = df.groupby(["A", "B"])["C"]
+
+ agged = grouped.agg(["mean", "std"])
+ expected = DataFrame({"mean": grouped.agg("mean"), "std": grouped.agg("std")})
+ tm.assert_frame_equal(agged, expected)
+
+
+def test_frame_multi_key_function_list():
+ data = DataFrame(
+ {
+ "A": [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ "foo",
+ "foo",
+ "foo",
+ ],
+ "B": [
+ "one",
+ "one",
+ "one",
+ "two",
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "two",
+ "one",
+ ],
+ "D": np.random.default_rng(2).standard_normal(11),
+ "E": np.random.default_rng(2).standard_normal(11),
+ "F": np.random.default_rng(2).standard_normal(11),
+ }
+ )
+
+ grouped = data.groupby(["A", "B"])
+ funcs = ["mean", "std"]
+ agged = grouped.agg(funcs)
+ expected = pd.concat(
+ [grouped["D"].agg(funcs), grouped["E"].agg(funcs), grouped["F"].agg(funcs)],
+ keys=["D", "E", "F"],
+ axis=1,
+ )
+ assert isinstance(agged.index, MultiIndex)
+ assert isinstance(expected.index, MultiIndex)
+ tm.assert_frame_equal(agged, expected)
+
+
+def test_frame_multi_key_function_list_partial_failure():
+ data = DataFrame(
+ {
+ "A": [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ "foo",
+ "foo",
+ "foo",
+ ],
+ "B": [
+ "one",
+ "one",
+ "one",
+ "two",
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "two",
+ "one",
+ ],
+ "C": [
+ "dull",
+ "dull",
+ "shiny",
+ "dull",
+ "dull",
+ "shiny",
+ "shiny",
+ "dull",
+ "shiny",
+ "shiny",
+ "shiny",
+ ],
+ "D": np.random.default_rng(2).standard_normal(11),
+ "E": np.random.default_rng(2).standard_normal(11),
+ "F": np.random.default_rng(2).standard_normal(11),
+ }
+ )
+
+ grouped = data.groupby(["A", "B"])
+ funcs = ["mean", "std"]
+ msg = re.escape("agg function failed [how->mean,dtype->object]")
+ with pytest.raises(TypeError, match=msg):
+ grouped.agg(funcs)
+
+
+@pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()])
+def test_groupby_multiple_columns(df, op):
+ data = df
+ grouped = data.groupby(["A", "B"])
+
+ result1 = op(grouped)
+
+ keys = []
+ values = []
+ for n1, gp1 in data.groupby("A"):
+ for n2, gp2 in gp1.groupby("B"):
+ keys.append((n1, n2))
+ values.append(op(gp2.loc[:, ["C", "D"]]))
+
+ mi = MultiIndex.from_tuples(keys, names=["A", "B"])
+ expected = pd.concat(values, axis=1).T
+ expected.index = mi
+
+ # a little bit crude
+ for col in ["C", "D"]:
+ result_col = op(grouped[col])
+ pivoted = result1[col]
+ exp = expected[col]
+ tm.assert_series_equal(result_col, exp)
+ tm.assert_series_equal(pivoted, exp)
+
+ # test single series works the same
+ result = data["C"].groupby([data["A"], data["B"]]).mean()
+ expected = data.groupby(["A", "B"]).mean()["C"]
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_as_index_select_column():
+ # GH 5764
+ df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
+ result = df.groupby("A", as_index=False)["B"].get_group(1)
+ expected = Series([2, 4], name="B")
+ tm.assert_series_equal(result, expected)
+
+ result = df.groupby("A", as_index=False, group_keys=True)["B"].apply(
+ lambda x: x.cumsum()
+ )
+ expected = Series(
+ [2, 6, 6], name="B", index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)])
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_obj_arg_get_group_deprecated():
+ depr_msg = "obj is deprecated"
+
+ df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]})
+ expected = df.iloc[df.groupby("b").indices.get(4)]
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ result = df.groupby("b").get_group(4, obj=df)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_as_index_select_column_sum_empty_df():
+ # GH 35246
+ df = DataFrame(columns=Index(["A", "B", "C"], name="alpha"))
+ left = df.groupby(by="A", as_index=False)["B"].sum(numeric_only=False)
+
+ expected = DataFrame(columns=df.columns[:2], index=range(0))
+ # GH#50744 - Columns after selection shouldn't retain names
+ expected.columns.names = [None]
+ tm.assert_frame_equal(left, expected)
+
+
+def test_groupby_as_index_agg(df):
+ grouped = df.groupby("A", as_index=False)
+
+ # single-key
+
+ result = grouped[["C", "D"]].agg("mean")
+ expected = grouped.mean(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ result2 = grouped.agg({"C": "mean", "D": "sum"})
+ expected2 = grouped.mean(numeric_only=True)
+ expected2["D"] = grouped.sum()["D"]
+ tm.assert_frame_equal(result2, expected2)
+
+ grouped = df.groupby("A", as_index=True)
+
+ msg = r"nested renamer is not supported"
+ with pytest.raises(SpecificationError, match=msg):
+ grouped["C"].agg({"Q": "sum"})
+
+ # multi-key
+
+ grouped = df.groupby(["A", "B"], as_index=False)
+
+ result = grouped.agg("mean")
+ expected = grouped.mean()
+ tm.assert_frame_equal(result, expected)
+
+ result2 = grouped.agg({"C": "mean", "D": "sum"})
+ expected2 = grouped.mean()
+ expected2["D"] = grouped.sum()["D"]
+ tm.assert_frame_equal(result2, expected2)
+
+ expected3 = grouped["C"].sum()
+ expected3 = DataFrame(expected3).rename(columns={"C": "Q"})
+ msg = "Passing a dictionary to SeriesGroupBy.agg is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result3 = grouped["C"].agg({"Q": "sum"})
+ tm.assert_frame_equal(result3, expected3)
+
+ # GH7115 & GH8112 & GH8582
+ df = DataFrame(
+ np.random.default_rng(2).integers(0, 100, (50, 3)),
+ columns=["jim", "joe", "jolie"],
+ )
+ ts = Series(np.random.default_rng(2).integers(5, 10, 50), name="jim")
+
+ gr = df.groupby(ts)
+ gr.nth(0) # invokes set_selection_from_grouper internally
+
+ msg = "The behavior of DataFrame.sum with axis=None is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False):
+ res = gr.apply(sum)
+ with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False):
+ alt = df.groupby(ts).apply(sum)
+ tm.assert_frame_equal(res, alt)
+
+ for attr in ["mean", "max", "count", "idxmax", "cumsum", "all"]:
+ gr = df.groupby(ts, as_index=False)
+ left = getattr(gr, attr)()
+
+ gr = df.groupby(ts.values, as_index=True)
+ right = getattr(gr, attr)().reset_index(drop=True)
+
+ tm.assert_frame_equal(left, right)
+
+
+def test_ops_not_as_index(reduction_func):
+ # GH 10355, 21090
+ # Using as_index=False should not modify grouped column
+
+ if reduction_func in ("corrwith", "nth", "ngroup"):
+ pytest.skip(f"GH 5755: Test not applicable for {reduction_func}")
+
+ df = DataFrame(
+ np.random.default_rng(2).integers(0, 5, size=(100, 2)), columns=["a", "b"]
+ )
+ expected = getattr(df.groupby("a"), reduction_func)()
+ if reduction_func == "size":
+ expected = expected.rename("size")
+ expected = expected.reset_index()
+
+ if reduction_func != "size":
+ # 32 bit compat -> groupby preserves dtype whereas reset_index casts to int64
+ expected["a"] = expected["a"].astype(df["a"].dtype)
+
+ g = df.groupby("a", as_index=False)
+
+ result = getattr(g, reduction_func)()
+ tm.assert_frame_equal(result, expected)
+
+ result = g.agg(reduction_func)
+ tm.assert_frame_equal(result, expected)
+
+ result = getattr(g["b"], reduction_func)()
+ tm.assert_frame_equal(result, expected)
+
+ result = g["b"].agg(reduction_func)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_as_index_series_return_frame(df):
+ grouped = df.groupby("A", as_index=False)
+ grouped2 = df.groupby(["A", "B"], as_index=False)
+
+ result = grouped["C"].agg("sum")
+ expected = grouped.agg("sum").loc[:, ["A", "C"]]
+ assert isinstance(result, DataFrame)
+ tm.assert_frame_equal(result, expected)
+
+ result2 = grouped2["C"].agg("sum")
+ expected2 = grouped2.agg("sum").loc[:, ["A", "B", "C"]]
+ assert isinstance(result2, DataFrame)
+ tm.assert_frame_equal(result2, expected2)
+
+ result = grouped["C"].sum()
+ expected = grouped.sum().loc[:, ["A", "C"]]
+ assert isinstance(result, DataFrame)
+ tm.assert_frame_equal(result, expected)
+
+ result2 = grouped2["C"].sum()
+ expected2 = grouped2.sum().loc[:, ["A", "B", "C"]]
+ assert isinstance(result2, DataFrame)
+ tm.assert_frame_equal(result2, expected2)
+
+
+def test_as_index_series_column_slice_raises(df):
+ # GH15072
+ grouped = df.groupby("A", as_index=False)
+ msg = r"Column\(s\) C already selected"
+
+ with pytest.raises(IndexError, match=msg):
+ grouped["C"].__getitem__("D")
+
+
+def test_groupby_as_index_cython(df):
+ data = df
+
+ # single-key
+ grouped = data.groupby("A", as_index=False)
+ result = grouped.mean(numeric_only=True)
+ expected = data.groupby(["A"]).mean(numeric_only=True)
+ expected.insert(0, "A", expected.index)
+ expected.index = RangeIndex(len(expected))
+ tm.assert_frame_equal(result, expected)
+
+ # multi-key
+ grouped = data.groupby(["A", "B"], as_index=False)
+ result = grouped.mean()
+ expected = data.groupby(["A", "B"]).mean()
+
+ arrays = list(zip(*expected.index.values))
+ expected.insert(0, "A", arrays[0])
+ expected.insert(1, "B", arrays[1])
+ expected.index = RangeIndex(len(expected))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_as_index_series_scalar(df):
+ grouped = df.groupby(["A", "B"], as_index=False)
+
+ # GH #421
+
+ result = grouped["C"].agg(len)
+ expected = grouped.agg(len).loc[:, ["A", "B", "C"]]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_as_index_corner(df, ts):
+ msg = "as_index=False only valid with DataFrame"
+ with pytest.raises(TypeError, match=msg):
+ ts.groupby(lambda x: x.weekday(), as_index=False)
+
+ msg = "as_index=False only valid for axis=0"
+ depr_msg = "DataFrame.groupby with axis=1 is deprecated"
+ with pytest.raises(ValueError, match=msg):
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ df.groupby(lambda x: x.lower(), as_index=False, axis=1)
+
+
+def test_groupby_multiple_key():
+ df = tm.makeTimeDataFrame()
+ grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
+ agged = grouped.sum()
+ tm.assert_almost_equal(df.values, agged.values)
+
+ depr_msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ grouped = df.T.groupby(
+ [lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1
+ )
+
+ agged = grouped.agg(lambda x: x.sum())
+ tm.assert_index_equal(agged.index, df.columns)
+ tm.assert_almost_equal(df.T.values, agged.values)
+
+ agged = grouped.agg(lambda x: x.sum())
+ tm.assert_almost_equal(df.T.values, agged.values)
+
+
+def test_groupby_multi_corner(df):
+ # test that having an all-NA column doesn't mess you up
+ df = df.copy()
+ df["bad"] = np.nan
+ agged = df.groupby(["A", "B"]).mean()
+
+ expected = df.groupby(["A", "B"]).mean()
+ expected["bad"] = np.nan
+
+ tm.assert_frame_equal(agged, expected)
+
+
+def test_raises_on_nuisance(df):
+ grouped = df.groupby("A")
+ msg = re.escape("agg function failed [how->mean,dtype->object]")
+ with pytest.raises(TypeError, match=msg):
+ grouped.agg("mean")
+ with pytest.raises(TypeError, match=msg):
+ grouped.mean()
+
+ df = df.loc[:, ["A", "C", "D"]]
+ df["E"] = datetime.now()
+ grouped = df.groupby("A")
+ msg = "datetime64 type does not support sum operations"
+ with pytest.raises(TypeError, match=msg):
+ grouped.agg("sum")
+ with pytest.raises(TypeError, match=msg):
+ grouped.sum()
+
+ # won't work with axis = 1
+ depr_msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1)
+ msg = "does not support reduction 'sum'"
+ with pytest.raises(TypeError, match=msg):
+ grouped.agg(lambda x: x.sum(0, numeric_only=False))
+
+
+@pytest.mark.parametrize(
+ "agg_function",
+ ["max", "min"],
+)
+def test_keep_nuisance_agg(df, agg_function):
+ # GH 38815
+ grouped = df.groupby("A")
+ result = getattr(grouped, agg_function)()
+ expected = result.copy()
+ expected.loc["bar", "B"] = getattr(df.loc[df["A"] == "bar", "B"], agg_function)()
+ expected.loc["foo", "B"] = getattr(df.loc[df["A"] == "foo", "B"], agg_function)()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "agg_function",
+ ["sum", "mean", "prod", "std", "var", "sem", "median"],
+)
+@pytest.mark.parametrize("numeric_only", [True, False])
+def test_omit_nuisance_agg(df, agg_function, numeric_only):
+ # GH 38774, GH 38815
+ grouped = df.groupby("A")
+
+ no_drop_nuisance = ("var", "std", "sem", "mean", "prod", "median")
+ if agg_function in no_drop_nuisance and not numeric_only:
+ # Added numeric_only as part of GH#46560; these do not drop nuisance
+ # columns when numeric_only is False
+ if agg_function in ("std", "sem"):
+ klass = ValueError
+ msg = "could not convert string to float: 'one'"
+ else:
+ klass = TypeError
+ msg = re.escape(f"agg function failed [how->{agg_function},dtype->object]")
+ with pytest.raises(klass, match=msg):
+ getattr(grouped, agg_function)(numeric_only=numeric_only)
+ else:
+ result = getattr(grouped, agg_function)(numeric_only=numeric_only)
+ if not numeric_only and agg_function == "sum":
+ # sum is successful on column B
+ columns = ["A", "B", "C", "D"]
+ else:
+ columns = ["A", "C", "D"]
+ expected = getattr(df.loc[:, columns].groupby("A"), agg_function)(
+ numeric_only=numeric_only
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_raise_on_nuisance_python_single(df):
+ # GH 38815
+ grouped = df.groupby("A")
+ with pytest.raises(ValueError, match="could not convert"):
+ grouped.skew()
+
+
+def test_raise_on_nuisance_python_multiple(three_group):
+ grouped = three_group.groupby(["A", "B"])
+ msg = re.escape("agg function failed [how->mean,dtype->object]")
+ with pytest.raises(TypeError, match=msg):
+ grouped.agg("mean")
+ with pytest.raises(TypeError, match=msg):
+ grouped.mean()
+
+
+def test_empty_groups_corner(mframe):
+ # handle empty groups
+ df = DataFrame(
+ {
+ "k1": np.array(["b", "b", "b", "a", "a", "a"]),
+ "k2": np.array(["1", "1", "1", "2", "2", "2"]),
+ "k3": ["foo", "bar"] * 3,
+ "v1": np.random.default_rng(2).standard_normal(6),
+ "v2": np.random.default_rng(2).standard_normal(6),
+ }
+ )
+
+ grouped = df.groupby(["k1", "k2"])
+ result = grouped[["v1", "v2"]].agg("mean")
+ expected = grouped.mean(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ grouped = mframe[3:5].groupby(level=0)
+ agged = grouped.apply(lambda x: x.mean())
+ agged_A = grouped["A"].apply("mean")
+ tm.assert_series_equal(agged["A"], agged_A)
+ assert agged.index.name == "first"
+
+
+def test_nonsense_func():
+ df = DataFrame([0])
+ msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'"
+ with pytest.raises(TypeError, match=msg):
+ df.groupby(lambda x: x + "foo")
+
+
+def test_wrap_aggregated_output_multindex(mframe):
+ df = mframe.T
+ df["baz", "two"] = "peekaboo"
+
+ keys = [np.array([0, 0, 1]), np.array([0, 0, 1])]
+ msg = re.escape("agg function failed [how->mean,dtype->object]")
+ with pytest.raises(TypeError, match=msg):
+ df.groupby(keys).agg("mean")
+ agged = df.drop(columns=("baz", "two")).groupby(keys).agg("mean")
+ assert isinstance(agged.columns, MultiIndex)
+
+ def aggfun(ser):
+ if ser.name == ("foo", "one"):
+ raise TypeError("Test error message")
+ return ser.sum()
+
+ with pytest.raises(TypeError, match="Test error message"):
+ df.groupby(keys).aggregate(aggfun)
+
+
+def test_groupby_level_apply(mframe):
+ result = mframe.groupby(level=0).count()
+ assert result.index.name == "first"
+ result = mframe.groupby(level=1).count()
+ assert result.index.name == "second"
+
+ result = mframe["A"].groupby(level=0).count()
+ assert result.index.name == "first"
+
+
+def test_groupby_level_mapper(mframe):
+ deleveled = mframe.reset_index()
+
+ mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1}
+ mapper1 = {"one": 0, "two": 0, "three": 1}
+
+ result0 = mframe.groupby(mapper0, level=0).sum()
+ result1 = mframe.groupby(mapper1, level=1).sum()
+
+ mapped_level0 = np.array(
+ [mapper0.get(x) for x in deleveled["first"]], dtype=np.int64
+ )
+ mapped_level1 = np.array(
+ [mapper1.get(x) for x in deleveled["second"]], dtype=np.int64
+ )
+ expected0 = mframe.groupby(mapped_level0).sum()
+ expected1 = mframe.groupby(mapped_level1).sum()
+ expected0.index.name, expected1.index.name = "first", "second"
+
+ tm.assert_frame_equal(result0, expected0)
+ tm.assert_frame_equal(result1, expected1)
+
+
+def test_groupby_level_nonmulti():
+ # GH 1313, GH 13901
+ s = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo"))
+ expected = Series([11, 22, 3, 4, 5, 6], Index(range(1, 7), name="foo"))
+
+ result = s.groupby(level=0).sum()
+ tm.assert_series_equal(result, expected)
+ result = s.groupby(level=[0]).sum()
+ tm.assert_series_equal(result, expected)
+ result = s.groupby(level=-1).sum()
+ tm.assert_series_equal(result, expected)
+ result = s.groupby(level=[-1]).sum()
+ tm.assert_series_equal(result, expected)
+
+ msg = "level > 0 or level < -1 only valid with MultiIndex"
+ with pytest.raises(ValueError, match=msg):
+ s.groupby(level=1)
+ with pytest.raises(ValueError, match=msg):
+ s.groupby(level=-2)
+ msg = "No group keys passed!"
+ with pytest.raises(ValueError, match=msg):
+ s.groupby(level=[])
+ msg = "multiple levels only valid with MultiIndex"
+ with pytest.raises(ValueError, match=msg):
+ s.groupby(level=[0, 0])
+ with pytest.raises(ValueError, match=msg):
+ s.groupby(level=[0, 1])
+ msg = "level > 0 or level < -1 only valid with MultiIndex"
+ with pytest.raises(ValueError, match=msg):
+ s.groupby(level=[1])
+
+
+def test_groupby_complex():
+ # GH 12902
+ a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1])
+ expected = Series((1 + 2j, 5 + 10j))
+
+ result = a.groupby(level=0).sum()
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_complex_numbers():
+ # GH 17927
+ df = DataFrame(
+ [
+ {"a": 1, "b": 1 + 1j},
+ {"a": 1, "b": 1 + 2j},
+ {"a": 4, "b": 1},
+ ]
+ )
+ expected = DataFrame(
+ np.array([1, 1, 1], dtype=np.int64),
+ index=Index([(1 + 1j), (1 + 2j), (1 + 0j)], name="b"),
+ columns=Index(["a"], dtype="object"),
+ )
+ result = df.groupby("b", sort=False).count()
+ tm.assert_frame_equal(result, expected)
+
+ # Sorted by the magnitude of the complex numbers
+ expected.index = Index([(1 + 0j), (1 + 1j), (1 + 2j)], name="b")
+ result = df.groupby("b", sort=True).count()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_series_indexed_differently():
+ s1 = Series(
+ [5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7],
+ index=Index(["a", "b", "c", "d", "e", "f", "g"]),
+ )
+ s2 = Series(
+ [1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"])
+ )
+
+ grouped = s1.groupby(s2)
+ agged = grouped.mean()
+ exp = s1.groupby(s2.reindex(s1.index).get).mean()
+ tm.assert_series_equal(agged, exp)
+
+
+def test_groupby_with_hier_columns():
+ tuples = list(
+ zip(
+ *[
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
+ ["one", "two", "one", "two", "one", "two", "one", "two"],
+ ]
+ )
+ )
+ index = MultiIndex.from_tuples(tuples)
+ columns = MultiIndex.from_tuples(
+ [("A", "cat"), ("B", "dog"), ("B", "cat"), ("A", "dog")]
+ )
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((8, 4)), index=index, columns=columns
+ )
+
+ result = df.groupby(level=0).mean()
+ tm.assert_index_equal(result.columns, columns)
+
+ depr_msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ gb = df.groupby(level=0, axis=1)
+ result = gb.mean()
+ tm.assert_index_equal(result.index, df.index)
+
+ result = df.groupby(level=0).agg("mean")
+ tm.assert_index_equal(result.columns, columns)
+
+ result = df.groupby(level=0).apply(lambda x: x.mean())
+ tm.assert_index_equal(result.columns, columns)
+
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ gb = df.groupby(level=0, axis=1)
+ result = gb.agg(lambda x: x.mean(1))
+ tm.assert_index_equal(result.columns, Index(["A", "B"]))
+ tm.assert_index_equal(result.index, df.index)
+
+ # add a nuisance column
+ sorted_columns, _ = columns.sortlevel(0)
+ df["A", "foo"] = "bar"
+ result = df.groupby(level=0).mean(numeric_only=True)
+ tm.assert_index_equal(result.columns, df.columns[:-1])
+
+
+def test_grouping_ndarray(df):
+ grouped = df.groupby(df["A"].values)
+ result = grouped.sum()
+ expected = df.groupby(df["A"].rename(None)).sum()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_wrong_multi_labels():
+ index = Index([0, 1, 2, 3, 4], name="index")
+ data = DataFrame(
+ {
+ "foo": ["foo1", "foo1", "foo2", "foo1", "foo3"],
+ "bar": ["bar1", "bar2", "bar2", "bar1", "bar1"],
+ "baz": ["baz1", "baz1", "baz1", "baz2", "baz2"],
+ "spam": ["spam2", "spam3", "spam2", "spam1", "spam1"],
+ "data": [20, 30, 40, 50, 60],
+ },
+ index=index,
+ )
+
+ grouped = data.groupby(["foo", "bar", "baz", "spam"])
+
+ result = grouped.agg("mean")
+ expected = grouped.mean()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_series_with_name(df):
+ result = df.groupby(df["A"]).mean(numeric_only=True)
+ result2 = df.groupby(df["A"], as_index=False).mean(numeric_only=True)
+ assert result.index.name == "A"
+ assert "A" in result2
+
+ result = df.groupby([df["A"], df["B"]]).mean()
+ result2 = df.groupby([df["A"], df["B"]], as_index=False).mean()
+ assert result.index.names == ("A", "B")
+ assert "A" in result2
+ assert "B" in result2
+
+
+def test_seriesgroupby_name_attr(df):
+ # GH 6265
+ result = df.groupby("A")["C"]
+ assert result.count().name == "C"
+ assert result.mean().name == "C"
+
+ testFunc = lambda x: np.sum(x) * 2
+ assert result.agg(testFunc).name == "C"
+
+
+def test_consistency_name():
+ # GH 12363
+
+ df = DataFrame(
+ {
+ "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
+ "B": ["one", "one", "two", "two", "two", "two", "one", "two"],
+ "C": np.random.default_rng(2).standard_normal(8) + 1.0,
+ "D": np.arange(8),
+ }
+ )
+
+ expected = df.groupby(["A"]).B.count()
+ result = df.B.groupby(df.A).count()
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_name_propagation(df):
+ # GH 6124
+ def summarize(df, name=None):
+ return Series({"count": 1, "mean": 2, "omissions": 3}, name=name)
+
+ def summarize_random_name(df):
+ # Provide a different name for each Series. In this case, groupby
+ # should not attempt to propagate the Series name since they are
+ # inconsistent.
+ return Series({"count": 1, "mean": 2, "omissions": 3}, name=df.iloc[0]["A"])
+
+ metrics = df.groupby("A").apply(summarize)
+ assert metrics.columns.name is None
+ metrics = df.groupby("A").apply(summarize, "metrics")
+ assert metrics.columns.name == "metrics"
+ metrics = df.groupby("A").apply(summarize_random_name)
+ assert metrics.columns.name is None
+
+
+def test_groupby_nonstring_columns():
+ df = DataFrame([np.arange(10) for x in range(10)])
+ grouped = df.groupby(0)
+ result = grouped.mean()
+ expected = df.groupby(df[0]).mean()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_mixed_type_columns():
+ # GH 13432, unorderable types in py3
+ df = DataFrame([[0, 1, 2]], columns=["A", "B", 0])
+ expected = DataFrame([[1, 2]], columns=["B", 0], index=Index([0], name="A"))
+
+ result = df.groupby("A").first()
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("A").sum()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_cython_grouper_series_bug_noncontig():
+ arr = np.empty((100, 100))
+ arr.fill(np.nan)
+ obj = Series(arr[:, 0])
+ inds = np.tile(range(10), 10)
+
+ result = obj.groupby(inds).agg(Series.median)
+ assert result.isna().all()
+
+
+def test_series_grouper_noncontig_index():
+ index = Index(["a" * 10] * 100)
+
+ values = Series(np.random.default_rng(2).standard_normal(50), index=index[::2])
+ labels = np.random.default_rng(2).integers(0, 5, 50)
+
+ # it works!
+ grouped = values.groupby(labels)
+
+ # accessing the index elements causes segfault
+ f = lambda x: len(set(map(id, x.index)))
+ grouped.agg(f)
+
+
+def test_convert_objects_leave_decimal_alone():
+ s = Series(range(5))
+ labels = np.array(["a", "b", "c", "d", "e"], dtype="O")
+
+ def convert_fast(x):
+ return Decimal(str(x.mean()))
+
+ def convert_force_pure(x):
+ # base will be length 0
+ assert len(x.values.base) > 0
+ return Decimal(str(x.mean()))
+
+ grouped = s.groupby(labels)
+
+ result = grouped.agg(convert_fast)
+ assert result.dtype == np.object_
+ assert isinstance(result.iloc[0], Decimal)
+
+ result = grouped.agg(convert_force_pure)
+ assert result.dtype == np.object_
+ assert isinstance(result.iloc[0], Decimal)
+
+
+def test_groupby_dtype_inference_empty():
+ # GH 6733
+ df = DataFrame({"x": [], "range": np.arange(0, dtype="int64")})
+ assert df["x"].dtype == np.float64
+
+ result = df.groupby("x").first()
+ exp_index = Index([], name="x", dtype=np.float64)
+ expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")})
+ tm.assert_frame_equal(result, expected, by_blocks=True)
+
+
+def test_groupby_unit64_float_conversion():
+ # GH: 30859 groupby converts unit64 to floats sometimes
+ df = DataFrame({"first": [1], "second": [1], "value": [16148277970000000000]})
+ result = df.groupby(["first", "second"])["value"].max()
+ expected = Series(
+ [16148277970000000000],
+ MultiIndex.from_product([[1], [1]], names=["first", "second"]),
+ name="value",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_list_infer_array_like(df):
+ result = df.groupby(list(df["A"])).mean(numeric_only=True)
+ expected = df.groupby(df["A"]).mean(numeric_only=True)
+ tm.assert_frame_equal(result, expected, check_names=False)
+
+ with pytest.raises(KeyError, match=r"^'foo'$"):
+ df.groupby(list(df["A"][:-1]))
+
+ # pathological case of ambiguity
+ df = DataFrame(
+ {
+ "foo": [0, 1],
+ "bar": [3, 4],
+ "val": np.random.default_rng(2).standard_normal(2),
+ }
+ )
+
+ result = df.groupby(["foo", "bar"]).mean()
+ expected = df.groupby([df["foo"], df["bar"]]).mean()[["val"]]
+
+
+def test_groupby_keys_same_size_as_index():
+ # GH 11185
+ freq = "s"
+ index = date_range(
+ start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq
+ )
+ df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index)
+ result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean()
+ expected = df.set_index([df.index, "metric"]).astype(float)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_one_row():
+ # GH 11741
+ msg = r"^'Z'$"
+ df1 = DataFrame(
+ np.random.default_rng(2).standard_normal((1, 4)), columns=list("ABCD")
+ )
+ with pytest.raises(KeyError, match=msg):
+ df1.groupby("Z")
+ df2 = DataFrame(
+ np.random.default_rng(2).standard_normal((2, 4)), columns=list("ABCD")
+ )
+ with pytest.raises(KeyError, match=msg):
+ df2.groupby("Z")
+
+
+def test_groupby_nat_exclude():
+ # GH 6992
+ df = DataFrame(
+ {
+ "values": np.random.default_rng(2).standard_normal(8),
+ "dt": [
+ np.nan,
+ Timestamp("2013-01-01"),
+ np.nan,
+ Timestamp("2013-02-01"),
+ np.nan,
+ Timestamp("2013-02-01"),
+ np.nan,
+ Timestamp("2013-01-01"),
+ ],
+ "str": [np.nan, "a", np.nan, "a", np.nan, "a", np.nan, "b"],
+ }
+ )
+ grouped = df.groupby("dt")
+
+ expected = [Index([1, 7]), Index([3, 5])]
+ keys = sorted(grouped.groups.keys())
+ assert len(keys) == 2
+ for k, e in zip(keys, expected):
+ # grouped.groups keys are np.datetime64 with system tz
+ # not to be affected by tz, only compare values
+ tm.assert_index_equal(grouped.groups[k], e)
+
+ # confirm obj is not filtered
+ tm.assert_frame_equal(grouped.grouper.groupings[0].obj, df)
+ assert grouped.ngroups == 2
+
+ expected = {
+ Timestamp("2013-01-01 00:00:00"): np.array([1, 7], dtype=np.intp),
+ Timestamp("2013-02-01 00:00:00"): np.array([3, 5], dtype=np.intp),
+ }
+
+ for k in grouped.indices:
+ tm.assert_numpy_array_equal(grouped.indices[k], expected[k])
+
+ tm.assert_frame_equal(grouped.get_group(Timestamp("2013-01-01")), df.iloc[[1, 7]])
+ tm.assert_frame_equal(grouped.get_group(Timestamp("2013-02-01")), df.iloc[[3, 5]])
+
+ with pytest.raises(KeyError, match=r"^NaT$"):
+ grouped.get_group(pd.NaT)
+
+ nan_df = DataFrame(
+ {"nan": [np.nan, np.nan, np.nan], "nat": [pd.NaT, pd.NaT, pd.NaT]}
+ )
+ assert nan_df["nan"].dtype == "float64"
+ assert nan_df["nat"].dtype == "datetime64[ns]"
+
+ for key in ["nan", "nat"]:
+ grouped = nan_df.groupby(key)
+ assert grouped.groups == {}
+ assert grouped.ngroups == 0
+ assert grouped.indices == {}
+ with pytest.raises(KeyError, match=r"^nan$"):
+ grouped.get_group(np.nan)
+ with pytest.raises(KeyError, match=r"^NaT$"):
+ grouped.get_group(pd.NaT)
+
+
+def test_groupby_two_group_keys_all_nan():
+ # GH #36842: Grouping over two group keys shouldn't raise an error
+ df = DataFrame({"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 2]})
+ result = df.groupby(["a", "b"]).indices
+ assert result == {}
+
+
+def test_groupby_2d_malformed():
+ d = DataFrame(index=range(2))
+ d["group"] = ["g1", "g2"]
+ d["zeros"] = [0, 0]
+ d["ones"] = [1, 1]
+ d["label"] = ["l1", "l2"]
+ tmp = d.groupby(["group"]).mean(numeric_only=True)
+ res_values = np.array([[0.0, 1.0], [0.0, 1.0]])
+ tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"]))
+ tm.assert_numpy_array_equal(tmp.values, res_values)
+
+
+def test_int32_overflow():
+ B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000)))
+ A = np.arange(25000)
+ df = DataFrame(
+ {
+ "A": A,
+ "B": B,
+ "C": A,
+ "D": B,
+ "E": np.random.default_rng(2).standard_normal(25000),
+ }
+ )
+
+ left = df.groupby(["A", "B", "C", "D"]).sum()
+ right = df.groupby(["D", "C", "B", "A"]).sum()
+ assert len(left) == len(right)
+
+
+def test_groupby_sort_multi():
+ df = DataFrame(
+ {
+ "a": ["foo", "bar", "baz"],
+ "b": [3, 2, 1],
+ "c": [0, 1, 2],
+ "d": np.random.default_rng(2).standard_normal(3),
+ }
+ )
+
+ tups = [tuple(row) for row in df[["a", "b", "c"]].values]
+ tups = com.asarray_tuplesafe(tups)
+ result = df.groupby(["a", "b", "c"], sort=True).sum()
+ tm.assert_numpy_array_equal(result.index.values, tups[[1, 2, 0]])
+
+ tups = [tuple(row) for row in df[["c", "a", "b"]].values]
+ tups = com.asarray_tuplesafe(tups)
+ result = df.groupby(["c", "a", "b"], sort=True).sum()
+ tm.assert_numpy_array_equal(result.index.values, tups)
+
+ tups = [tuple(x) for x in df[["b", "c", "a"]].values]
+ tups = com.asarray_tuplesafe(tups)
+ result = df.groupby(["b", "c", "a"], sort=True).sum()
+ tm.assert_numpy_array_equal(result.index.values, tups[[2, 1, 0]])
+
+ df = DataFrame(
+ {
+ "a": [0, 1, 2, 0, 1, 2],
+ "b": [0, 0, 0, 1, 1, 1],
+ "d": np.random.default_rng(2).standard_normal(6),
+ }
+ )
+ grouped = df.groupby(["a", "b"])["d"]
+ result = grouped.sum()
+
+ def _check_groupby(df, result, keys, field, f=lambda x: x.sum()):
+ tups = [tuple(row) for row in df[keys].values]
+ tups = com.asarray_tuplesafe(tups)
+ expected = f(df.groupby(tups)[field])
+ for k, v in expected.items():
+ assert result[k] == v
+
+ _check_groupby(df, result, ["a", "b"], "d")
+
+
+def test_dont_clobber_name_column():
+ df = DataFrame(
+ {"key": ["a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2}
+ )
+
+ result = df.groupby("key", group_keys=False).apply(lambda x: x)
+ tm.assert_frame_equal(result, df)
+
+
+def test_skip_group_keys():
+ tsf = tm.makeTimeDataFrame()
+
+ grouped = tsf.groupby(lambda x: x.month, group_keys=False)
+ result = grouped.apply(lambda x: x.sort_values(by="A")[:3])
+
+ pieces = [group.sort_values(by="A")[:3] for key, group in grouped]
+
+ expected = pd.concat(pieces)
+ tm.assert_frame_equal(result, expected)
+
+ grouped = tsf["A"].groupby(lambda x: x.month, group_keys=False)
+ result = grouped.apply(lambda x: x.sort_values()[:3])
+
+ pieces = [group.sort_values()[:3] for key, group in grouped]
+
+ expected = pd.concat(pieces)
+ tm.assert_series_equal(result, expected)
+
+
+def test_no_nonsense_name(float_frame):
+ # GH #995
+ s = float_frame["C"].copy()
+ s.name = None
+
+ result = s.groupby(float_frame["A"]).agg("sum")
+ assert result.name is None
+
+
+def test_multifunc_sum_bug():
+ # GH #1065
+ x = DataFrame(np.arange(9).reshape(3, 3))
+ x["test"] = 0
+ x["fl"] = [1.3, 1.5, 1.6]
+
+ grouped = x.groupby("test")
+ result = grouped.agg({"fl": "sum", 2: "size"})
+ assert result["fl"].dtype == np.float64
+
+
+def test_handle_dict_return_value(df):
+ def f(group):
+ return {"max": group.max(), "min": group.min()}
+
+ def g(group):
+ return Series({"max": group.max(), "min": group.min()})
+
+ result = df.groupby("A")["C"].apply(f)
+ expected = df.groupby("A")["C"].apply(g)
+
+ assert isinstance(result, Series)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("grouper", ["A", ["A", "B"]])
+def test_set_group_name(df, grouper):
+ def f(group):
+ assert group.name is not None
+ return group
+
+ def freduce(group):
+ assert group.name is not None
+ return group.sum()
+
+ def freducex(x):
+ return freduce(x)
+
+ grouped = df.groupby(grouper, group_keys=False)
+
+ # make sure all these work
+ grouped.apply(f)
+ grouped.aggregate(freduce)
+ grouped.aggregate({"C": freduce, "D": freduce})
+ grouped.transform(f)
+
+ grouped["C"].apply(f)
+ grouped["C"].aggregate(freduce)
+ grouped["C"].aggregate([freduce, freducex])
+ grouped["C"].transform(f)
+
+
+def test_group_name_available_in_inference_pass():
+ # gh-15062
+ df = DataFrame({"a": [0, 0, 1, 1, 2, 2], "b": np.arange(6)})
+
+ names = []
+
+ def f(group):
+ names.append(group.name)
+ return group.copy()
+
+ df.groupby("a", sort=False, group_keys=False).apply(f)
+
+ expected_names = [0, 1, 2]
+ assert names == expected_names
+
+
+def test_no_dummy_key_names(df):
+ # see gh-1291
+ result = df.groupby(df["A"].values).sum()
+ assert result.index.name is None
+
+ result = df.groupby([df["A"].values, df["B"].values]).sum()
+ assert result.index.names == (None, None)
+
+
+def test_groupby_sort_multiindex_series():
+ # series multiindex groupby sort argument was not being passed through
+ # _compress_group_index
+ # GH 9444
+ index = MultiIndex(
+ levels=[[1, 2], [1, 2]],
+ codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]],
+ names=["a", "b"],
+ )
+ mseries = Series([0, 1, 2, 3, 4, 5], index=index)
+ index = MultiIndex(
+ levels=[[1, 2], [1, 2]], codes=[[0, 0, 1], [1, 0, 0]], names=["a", "b"]
+ )
+ mseries_result = Series([0, 2, 4], index=index)
+
+ result = mseries.groupby(level=["a", "b"], sort=False).first()
+ tm.assert_series_equal(result, mseries_result)
+ result = mseries.groupby(level=["a", "b"], sort=True).first()
+ tm.assert_series_equal(result, mseries_result.sort_index())
+
+
+def test_groupby_reindex_inside_function():
+ periods = 1000
+ ind = date_range(start="2012/1/1", freq="5min", periods=periods)
+ df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind)
+
+ def agg_before(func, fix=False):
+ """
+ Run an aggregate func on the subset of data.
+ """
+
+ def _func(data):
+ d = data.loc[data.index.map(lambda x: x.hour < 11)].dropna()
+ if fix:
+ data[data.index[0]]
+ if len(d) == 0:
+ return None
+ return func(d)
+
+ return _func
+
+ grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
+ closure_bad = grouped.agg({"high": agg_before(np.max)})
+ closure_good = grouped.agg({"high": agg_before(np.max, True)})
+
+ tm.assert_frame_equal(closure_bad, closure_good)
+
+
+def test_groupby_multiindex_missing_pair():
+ # GH9049
+ df = DataFrame(
+ {
+ "group1": ["a", "a", "a", "b"],
+ "group2": ["c", "c", "d", "c"],
+ "value": [1, 1, 1, 5],
+ }
+ )
+ df = df.set_index(["group1", "group2"])
+ df_grouped = df.groupby(level=["group1", "group2"], sort=True)
+
+ res = df_grouped.agg("sum")
+ idx = MultiIndex.from_tuples(
+ [("a", "c"), ("a", "d"), ("b", "c")], names=["group1", "group2"]
+ )
+ exp = DataFrame([[2], [1], [5]], index=idx, columns=["value"])
+
+ tm.assert_frame_equal(res, exp)
+
+
+def test_groupby_multiindex_not_lexsorted():
+ # GH 11640
+
+ # define the lexsorted version
+ lexsorted_mi = MultiIndex.from_tuples(
+ [("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"]
+ )
+ lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi)
+ assert lexsorted_df.columns._is_lexsorted()
+
+ # define the non-lexsorted version
+ not_lexsorted_df = DataFrame(
+ columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]]
+ )
+ not_lexsorted_df = not_lexsorted_df.pivot_table(
+ index="a", columns=["b", "c"], values="d"
+ )
+ not_lexsorted_df = not_lexsorted_df.reset_index()
+ assert not not_lexsorted_df.columns._is_lexsorted()
+
+ expected = lexsorted_df.groupby("a").mean()
+ with tm.assert_produces_warning(PerformanceWarning):
+ result = not_lexsorted_df.groupby("a").mean()
+ tm.assert_frame_equal(expected, result)
+
+ # a transforming function should work regardless of sort
+ # GH 14776
+ df = DataFrame(
+ {"x": ["a", "a", "b", "a"], "y": [1, 1, 2, 2], "z": [1, 2, 3, 4]}
+ ).set_index(["x", "y"])
+ assert not df.index._is_lexsorted()
+
+ for level in [0, 1, [0, 1]]:
+ for sort in [False, True]:
+ result = df.groupby(level=level, sort=sort, group_keys=False).apply(
+ DataFrame.drop_duplicates
+ )
+ expected = df
+ tm.assert_frame_equal(expected, result)
+
+ result = (
+ df.sort_index()
+ .groupby(level=level, sort=sort, group_keys=False)
+ .apply(DataFrame.drop_duplicates)
+ )
+ expected = df.sort_index()
+ tm.assert_frame_equal(expected, result)
+
+
+def test_index_label_overlaps_location():
+ # checking we don't have any label/location confusion in the
+ # wake of GH5375
+ df = DataFrame(list("ABCDE"), index=[2, 0, 2, 1, 1])
+ g = df.groupby(list("ababb"))
+ actual = g.filter(lambda x: len(x) > 2)
+ expected = df.iloc[[1, 3, 4]]
+ tm.assert_frame_equal(actual, expected)
+
+ ser = df[0]
+ g = ser.groupby(list("ababb"))
+ actual = g.filter(lambda x: len(x) > 2)
+ expected = ser.take([1, 3, 4])
+ tm.assert_series_equal(actual, expected)
+
+ # and again, with a generic Index of floats
+ df.index = df.index.astype(float)
+ g = df.groupby(list("ababb"))
+ actual = g.filter(lambda x: len(x) > 2)
+ expected = df.iloc[[1, 3, 4]]
+ tm.assert_frame_equal(actual, expected)
+
+ ser = df[0]
+ g = ser.groupby(list("ababb"))
+ actual = g.filter(lambda x: len(x) > 2)
+ expected = ser.take([1, 3, 4])
+ tm.assert_series_equal(actual, expected)
+
+
+def test_transform_doesnt_clobber_ints():
+ # GH 7972
+ n = 6
+ x = np.arange(n)
+ df = DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x})
+ df2 = DataFrame({"a": x // 2 * 1.0, "b": 2.0 * x, "c": 3.0 * x})
+
+ gb = df.groupby("a")
+ result = gb.transform("mean")
+
+ gb2 = df2.groupby("a")
+ expected = gb2.transform("mean")
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "sort_column",
+ ["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]],
+)
+@pytest.mark.parametrize(
+ "group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]]
+)
+def test_groupby_preserves_sort(sort_column, group_column):
+ # Test to ensure that groupby always preserves sort order of original
+ # object. Issue #8588 and #9651
+
+ df = DataFrame(
+ {
+ "int_groups": [3, 1, 0, 1, 0, 3, 3, 3],
+ "string_groups": ["z", "a", "z", "a", "a", "g", "g", "g"],
+ "ints": [8, 7, 4, 5, 2, 9, 1, 1],
+ "floats": [2.3, 5.3, 6.2, -2.4, 2.2, 1.1, 1.1, 5],
+ "strings": ["z", "d", "a", "e", "word", "word2", "42", "47"],
+ }
+ )
+
+ # Try sorting on different types and with different group types
+
+ df = df.sort_values(by=sort_column)
+ g = df.groupby(group_column)
+
+ def test_sort(x):
+ tm.assert_frame_equal(x, x.sort_values(by=sort_column))
+
+ g.apply(test_sort)
+
+
+def test_pivot_table_values_key_error():
+ # This test is designed to replicate the error in issue #14938
+ df = DataFrame(
+ {
+ "eventDate": date_range(datetime.today(), periods=20, freq="M").tolist(),
+ "thename": range(0, 20),
+ }
+ )
+
+ df["year"] = df.set_index("eventDate").index.year
+ df["month"] = df.set_index("eventDate").index.month
+
+ with pytest.raises(KeyError, match="'badname'"):
+ df.reset_index().pivot_table(
+ index="year", columns="month", values="badname", aggfunc="count"
+ )
+
+
+@pytest.mark.parametrize("columns", ["C", ["C"]])
+@pytest.mark.parametrize("keys", [["A"], ["A", "B"]])
+@pytest.mark.parametrize(
+ "values",
+ [
+ [True],
+ [0],
+ [0.0],
+ ["a"],
+ Categorical([0]),
+ [to_datetime(0)],
+ date_range(0, 1, 1, tz="US/Eastern"),
+ pd.period_range("2016-01-01", periods=3, freq="D"),
+ pd.array([0], dtype="Int64"),
+ pd.array([0], dtype="Float64"),
+ pd.array([False], dtype="boolean"),
+ ],
+ ids=[
+ "bool",
+ "int",
+ "float",
+ "str",
+ "cat",
+ "dt64",
+ "dt64tz",
+ "period",
+ "Int64",
+ "Float64",
+ "boolean",
+ ],
+)
+@pytest.mark.parametrize("method", ["attr", "agg", "apply"])
+@pytest.mark.parametrize(
+ "op", ["idxmax", "idxmin", "min", "max", "sum", "prod", "skew"]
+)
+def test_empty_groupby(
+ columns, keys, values, method, op, request, using_array_manager, dropna
+):
+ # GH8093 & GH26411
+ override_dtype = None
+
+ if (
+ isinstance(values, Categorical)
+ and len(keys) == 1
+ and op in ["idxmax", "idxmin"]
+ ):
+ mark = pytest.mark.xfail(
+ raises=ValueError, match="attempt to get arg(min|max) of an empty sequence"
+ )
+ request.node.add_marker(mark)
+
+ if isinstance(values, BooleanArray) and op in ["sum", "prod"]:
+ # We expect to get Int64 back for these
+ override_dtype = "Int64"
+
+ if isinstance(values[0], bool) and op in ("prod", "sum"):
+ # sum/product of bools is an integer
+ override_dtype = "int64"
+
+ df = DataFrame({"A": values, "B": values, "C": values}, columns=list("ABC"))
+
+ if hasattr(values, "dtype"):
+ # check that we did the construction right
+ assert (df.dtypes == values.dtype).all()
+
+ df = df.iloc[:0]
+
+ gb = df.groupby(keys, group_keys=False, dropna=dropna, observed=False)[columns]
+
+ def get_result(**kwargs):
+ if method == "attr":
+ return getattr(gb, op)(**kwargs)
+ else:
+ return getattr(gb, method)(op, **kwargs)
+
+ def get_categorical_invalid_expected():
+ # Categorical is special without 'observed=True', we get an NaN entry
+ # corresponding to the unobserved group. If we passed observed=True
+ # to groupby, expected would just be 'df.set_index(keys)[columns]'
+ # as below
+ lev = Categorical([0], dtype=values.dtype)
+ if len(keys) != 1:
+ idx = MultiIndex.from_product([lev, lev], names=keys)
+ else:
+ # all columns are dropped, but we end up with one row
+ # Categorical is special without 'observed=True'
+ idx = Index(lev, name=keys[0])
+
+ expected = DataFrame([], columns=[], index=idx)
+ return expected
+
+ is_per = isinstance(df.dtypes.iloc[0], pd.PeriodDtype)
+ is_dt64 = df.dtypes.iloc[0].kind == "M"
+ is_cat = isinstance(values, Categorical)
+
+ if isinstance(values, Categorical) and not values.ordered and op in ["min", "max"]:
+ msg = f"Cannot perform {op} with non-ordered Categorical"
+ with pytest.raises(TypeError, match=msg):
+ get_result()
+
+ if isinstance(columns, list):
+ # i.e. DataframeGroupBy, not SeriesGroupBy
+ result = get_result(numeric_only=True)
+ expected = get_categorical_invalid_expected()
+ tm.assert_equal(result, expected)
+ return
+
+ if op in ["prod", "sum", "skew"]:
+ # ops that require more than just ordered-ness
+ if is_dt64 or is_cat or is_per:
+ # GH#41291
+ # datetime64 -> prod and sum are invalid
+ if is_dt64:
+ msg = "datetime64 type does not support"
+ elif is_per:
+ msg = "Period type does not support"
+ else:
+ msg = "category type does not support"
+ if op == "skew":
+ msg = "|".join([msg, "does not support reduction 'skew'"])
+ with pytest.raises(TypeError, match=msg):
+ get_result()
+
+ if not isinstance(columns, list):
+ # i.e. SeriesGroupBy
+ return
+ elif op == "skew":
+ # TODO: test the numeric_only=True case
+ return
+ else:
+ # i.e. op in ["prod", "sum"]:
+ # i.e. DataFrameGroupBy
+ # ops that require more than just ordered-ness
+ # GH#41291
+ result = get_result(numeric_only=True)
+
+ # with numeric_only=True, these are dropped, and we get
+ # an empty DataFrame back
+ expected = df.set_index(keys)[[]]
+ if is_cat:
+ expected = get_categorical_invalid_expected()
+ tm.assert_equal(result, expected)
+ return
+
+ result = get_result()
+ expected = df.set_index(keys)[columns]
+ if op in ["idxmax", "idxmin"]:
+ expected = expected.astype(df.index.dtype)
+ if override_dtype is not None:
+ expected = expected.astype(override_dtype)
+ if len(keys) == 1:
+ expected.index.name = keys[0]
+ tm.assert_equal(result, expected)
+
+
+def test_empty_groupby_apply_nonunique_columns():
+ # GH#44417
+ df = DataFrame(np.random.default_rng(2).standard_normal((0, 4)))
+ df[3] = df[3].astype(np.int64)
+ df.columns = [0, 1, 2, 0]
+ gb = df.groupby(df[1], group_keys=False)
+ res = gb.apply(lambda x: x)
+ assert (res.dtypes == df.dtypes).all()
+
+
+def test_tuple_as_grouping():
+ # https://github.com/pandas-dev/pandas/issues/18314
+ df = DataFrame(
+ {
+ ("a", "b"): [1, 1, 1, 1],
+ "a": [2, 2, 2, 2],
+ "b": [2, 2, 2, 2],
+ "c": [1, 1, 1, 1],
+ }
+ )
+
+ with pytest.raises(KeyError, match=r"('a', 'b')"):
+ df[["a", "b", "c"]].groupby(("a", "b"))
+
+ result = df.groupby(("a", "b"))["c"].sum()
+ expected = Series([4], name="c", index=Index([1], name=("a", "b")))
+ tm.assert_series_equal(result, expected)
+
+
+def test_tuple_correct_keyerror():
+ # https://github.com/pandas-dev/pandas/issues/18798
+ df = DataFrame(1, index=range(3), columns=MultiIndex.from_product([[1, 2], [3, 4]]))
+ with pytest.raises(KeyError, match=r"^\(7, 8\)$"):
+ df.groupby((7, 8)).mean()
+
+
+def test_groupby_agg_ohlc_non_first():
+ # GH 21716
+ df = DataFrame(
+ [[1], [1]],
+ columns=Index(["foo"], name="mycols"),
+ index=date_range("2018-01-01", periods=2, freq="D", name="dti"),
+ )
+
+ expected = DataFrame(
+ [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]],
+ columns=MultiIndex.from_tuples(
+ (
+ ("foo", "sum", "foo"),
+ ("foo", "ohlc", "open"),
+ ("foo", "ohlc", "high"),
+ ("foo", "ohlc", "low"),
+ ("foo", "ohlc", "close"),
+ ),
+ names=["mycols", None, None],
+ ),
+ index=date_range("2018-01-01", periods=2, freq="D", name="dti"),
+ )
+
+ result = df.groupby(Grouper(freq="D")).agg(["sum", "ohlc"])
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_multiindex_nat():
+ # GH 9236
+ values = [
+ (pd.NaT, "a"),
+ (datetime(2012, 1, 2), "a"),
+ (datetime(2012, 1, 2), "b"),
+ (datetime(2012, 1, 3), "a"),
+ ]
+ mi = MultiIndex.from_tuples(values, names=["date", None])
+ ser = Series([3, 2, 2.5, 4], index=mi)
+
+ result = ser.groupby(level=1).mean()
+ expected = Series([3.0, 2.5], index=["a", "b"])
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_empty_list_raises():
+ # GH 5289
+ values = zip(range(10), range(10))
+ df = DataFrame(values, columns=["apple", "b"])
+ msg = "Grouper and axis must be same length"
+ with pytest.raises(ValueError, match=msg):
+ df.groupby([[]])
+
+
+def test_groupby_multiindex_series_keys_len_equal_group_axis():
+ # GH 25704
+ index_array = [["x", "x"], ["a", "b"], ["k", "k"]]
+ index_names = ["first", "second", "third"]
+ ri = MultiIndex.from_arrays(index_array, names=index_names)
+ s = Series(data=[1, 2], index=ri)
+ result = s.groupby(["first", "third"]).sum()
+
+ index_array = [["x"], ["k"]]
+ index_names = ["first", "third"]
+ ei = MultiIndex.from_arrays(index_array, names=index_names)
+ expected = Series([3], index=ei)
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_groups_in_BaseGrouper():
+ # GH 26326
+ # Test if DataFrame grouped with a pandas.Grouper has correct groups
+ mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"])
+ df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi)
+ result = df.groupby([Grouper(level="alpha"), "beta"])
+ expected = df.groupby(["alpha", "beta"])
+ assert result.groups == expected.groups
+
+ result = df.groupby(["beta", Grouper(level="alpha")])
+ expected = df.groupby(["beta", "alpha"])
+ assert result.groups == expected.groups
+
+
+@pytest.mark.parametrize("group_name", ["x", ["x"]])
+def test_groupby_axis_1(group_name):
+ # GH 27614
+ df = DataFrame(
+ np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20]
+ )
+ df.index.name = "y"
+ df.columns.name = "x"
+
+ depr_msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ gb = df.groupby(group_name, axis=1)
+
+ results = gb.sum()
+ expected = df.T.groupby(group_name).sum().T
+ tm.assert_frame_equal(results, expected)
+
+ # test on MI column
+ iterables = [["bar", "baz", "foo"], ["one", "two"]]
+ mi = MultiIndex.from_product(iterables=iterables, names=["x", "x1"])
+ df = DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi)
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ gb = df.groupby(group_name, axis=1)
+ results = gb.sum()
+ expected = df.T.groupby(group_name).sum().T
+ tm.assert_frame_equal(results, expected)
+
+
+@pytest.mark.parametrize(
+ "op, expected",
+ [
+ (
+ "shift",
+ {
+ "time": [
+ None,
+ None,
+ Timestamp("2019-01-01 12:00:00"),
+ Timestamp("2019-01-01 12:30:00"),
+ None,
+ None,
+ ]
+ },
+ ),
+ (
+ "bfill",
+ {
+ "time": [
+ Timestamp("2019-01-01 12:00:00"),
+ Timestamp("2019-01-01 12:30:00"),
+ Timestamp("2019-01-01 14:00:00"),
+ Timestamp("2019-01-01 14:30:00"),
+ Timestamp("2019-01-01 14:00:00"),
+ Timestamp("2019-01-01 14:30:00"),
+ ]
+ },
+ ),
+ (
+ "ffill",
+ {
+ "time": [
+ Timestamp("2019-01-01 12:00:00"),
+ Timestamp("2019-01-01 12:30:00"),
+ Timestamp("2019-01-01 12:00:00"),
+ Timestamp("2019-01-01 12:30:00"),
+ Timestamp("2019-01-01 14:00:00"),
+ Timestamp("2019-01-01 14:30:00"),
+ ]
+ },
+ ),
+ ],
+)
+def test_shift_bfill_ffill_tz(tz_naive_fixture, op, expected):
+ # GH19995, GH27992: Check that timezone does not drop in shift, bfill, and ffill
+ tz = tz_naive_fixture
+ data = {
+ "id": ["A", "B", "A", "B", "A", "B"],
+ "time": [
+ Timestamp("2019-01-01 12:00:00"),
+ Timestamp("2019-01-01 12:30:00"),
+ None,
+ None,
+ Timestamp("2019-01-01 14:00:00"),
+ Timestamp("2019-01-01 14:30:00"),
+ ],
+ }
+ df = DataFrame(data).assign(time=lambda x: x.time.dt.tz_localize(tz))
+
+ grouped = df.groupby("id")
+ result = getattr(grouped, op)()
+ expected = DataFrame(expected).assign(time=lambda x: x.time.dt.tz_localize(tz))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_only_none_group():
+ # see GH21624
+ # this was crashing with "ValueError: Length of passed values is 1, index implies 0"
+ df = DataFrame({"g": [None], "x": 1})
+ actual = df.groupby("g")["x"].transform("sum")
+ expected = Series([np.nan], name="x")
+
+ tm.assert_series_equal(actual, expected)
+
+
+def test_groupby_duplicate_index():
+ # GH#29189 the groupby call here used to raise
+ ser = Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0])
+ gb = ser.groupby(level=0)
+
+ result = gb.mean()
+ expected = Series([2, 5.5, 8], index=[2.0, 4.0, 5.0])
+ tm.assert_series_equal(result, expected)
+
+
+def test_group_on_empty_multiindex(transformation_func, request):
+ # GH 47787
+ # With one row, those are transforms so the schema should be the same
+ df = DataFrame(
+ data=[[1, Timestamp("today"), 3, 4]],
+ columns=["col_1", "col_2", "col_3", "col_4"],
+ )
+ df["col_3"] = df["col_3"].astype(int)
+ df["col_4"] = df["col_4"].astype(int)
+ df = df.set_index(["col_1", "col_2"])
+ if transformation_func == "fillna":
+ args = ("ffill",)
+ else:
+ args = ()
+ result = df.iloc[:0].groupby(["col_1"]).transform(transformation_func, *args)
+ expected = df.groupby(["col_1"]).transform(transformation_func, *args).iloc[:0]
+ if transformation_func in ("diff", "shift"):
+ expected = expected.astype(int)
+ tm.assert_equal(result, expected)
+
+ result = (
+ df["col_3"].iloc[:0].groupby(["col_1"]).transform(transformation_func, *args)
+ )
+ expected = (
+ df["col_3"].groupby(["col_1"]).transform(transformation_func, *args).iloc[:0]
+ )
+ if transformation_func in ("diff", "shift"):
+ expected = expected.astype(int)
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "idx",
+ [
+ Index(["a", "a"], name="foo"),
+ MultiIndex.from_tuples((("a", "a"), ("a", "a")), names=["foo", "bar"]),
+ ],
+)
+def test_dup_labels_output_shape(groupby_func, idx):
+ if groupby_func in {"size", "ngroup", "cumcount"}:
+ pytest.skip(f"Not applicable for {groupby_func}")
+
+ df = DataFrame([[1, 1]], columns=idx)
+ grp_by = df.groupby([0])
+
+ args = get_groupby_method_args(groupby_func, df)
+ result = getattr(grp_by, groupby_func)(*args)
+
+ assert result.shape == (1, 2)
+ tm.assert_index_equal(result.columns, idx)
+
+
+def test_groupby_crash_on_nunique(axis):
+ # Fix following 30253
+ dti = date_range("2016-01-01", periods=2, name="foo")
+ df = DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]})
+ df.columns.names = ("bar", "baz")
+ df.index = dti
+
+ axis_number = df._get_axis_number(axis)
+ if not axis_number:
+ df = df.T
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ else:
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby(axis=axis_number, level=0)
+ result = gb.nunique()
+
+ expected = DataFrame({"A": [1, 2], "D": [1, 1]}, index=dti)
+ expected.columns.name = "bar"
+ if not axis_number:
+ expected = expected.T
+
+ tm.assert_frame_equal(result, expected)
+
+ if axis_number == 0:
+ # same thing, but empty columns
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb2 = df[[]].groupby(axis=axis_number, level=0)
+ exp = expected[[]]
+ else:
+ # same thing, but empty rows
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb2 = df.loc[[]].groupby(axis=axis_number, level=0)
+ # default for empty when we can't infer a dtype is float64
+ exp = expected.loc[[]].astype(np.float64)
+
+ res = gb2.nunique()
+ tm.assert_frame_equal(res, exp)
+
+
+def test_groupby_list_level():
+ # GH 9790
+ expected = DataFrame(np.arange(0, 9).reshape(3, 3), dtype=float)
+ result = expected.groupby(level=[0]).mean()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "max_seq_items, expected",
+ [
+ (5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"),
+ (4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"),
+ (1, "{0: [0], ...}"),
+ ],
+)
+def test_groups_repr_truncates(max_seq_items, expected):
+ # GH 1135
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 1)))
+ df["a"] = df.index
+
+ with pd.option_context("display.max_seq_items", max_seq_items):
+ result = df.groupby("a").groups.__repr__()
+ assert result == expected
+
+ result = df.groupby(np.array(df.a)).groups.__repr__()
+ assert result == expected
+
+
+def test_group_on_two_row_multiindex_returns_one_tuple_key():
+ # GH 18451
+ df = DataFrame([{"a": 1, "b": 2, "c": 99}, {"a": 1, "b": 2, "c": 88}])
+ df = df.set_index(["a", "b"])
+
+ grp = df.groupby(["a", "b"])
+ result = grp.indices
+ expected = {(1, 2): np.array([0, 1], dtype=np.int64)}
+
+ assert len(result) == 1
+ key = (1, 2)
+ assert (result[key] == expected[key]).all()
+
+
+@pytest.mark.parametrize(
+ "klass, attr, value",
+ [
+ (DataFrame, "level", "a"),
+ (DataFrame, "as_index", False),
+ (DataFrame, "sort", False),
+ (DataFrame, "group_keys", False),
+ (DataFrame, "observed", True),
+ (DataFrame, "dropna", False),
+ (Series, "level", "a"),
+ (Series, "as_index", False),
+ (Series, "sort", False),
+ (Series, "group_keys", False),
+ (Series, "observed", True),
+ (Series, "dropna", False),
+ ],
+)
+def test_subsetting_columns_keeps_attrs(klass, attr, value):
+ # GH 9959 - When subsetting columns, don't drop attributes
+ df = DataFrame({"a": [1], "b": [2], "c": [3]})
+ if attr != "axis":
+ df = df.set_index("a")
+
+ expected = df.groupby("a", **{attr: value})
+ result = expected[["b"]] if klass is DataFrame else expected["b"]
+ assert getattr(result, attr) == getattr(expected, attr)
+
+
+def test_subsetting_columns_axis_1():
+ # GH 37725
+ df = DataFrame({"A": [1], "B": [2], "C": [3]})
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ g = df.groupby([0, 0, 1], axis=1)
+ match = "Cannot subset columns when using axis=1"
+ with pytest.raises(ValueError, match=match):
+ g[["A", "B"]].sum()
+
+
+@pytest.mark.parametrize("func", ["sum", "any", "shift"])
+def test_groupby_column_index_name_lost(func):
+ # GH: 29764 groupby loses index sometimes
+ expected = Index(["a"], name="idx")
+ df = DataFrame([[1]], columns=expected)
+ df_grouped = df.groupby([1])
+ result = getattr(df_grouped, func)().columns
+ tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "infer_string",
+ [
+ False,
+ pytest.param(True, marks=td.skip_if_no("pyarrow")),
+ ],
+)
+def test_groupby_duplicate_columns(infer_string):
+ # GH: 31735
+ df = DataFrame(
+ {"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]}
+ ).astype(object)
+ df.columns = ["A", "B", "B"]
+ with pd.option_context("future.infer_string", infer_string):
+ result = df.groupby([0, 0, 0, 0]).min()
+ expected = DataFrame(
+ [["e", "a", 1]], index=np.array([0]), columns=["A", "B", "B"], dtype=object
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_series_with_tuple_name():
+ # GH 37755
+ ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a"))
+ ser.index.name = ("b", "b")
+ result = ser.groupby(level=0).last()
+ expected = Series([2, 4], index=[1, 2], name=("a", "a"))
+ expected.index.name = ("b", "b")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "func, values", [("sum", [97.0, 98.0]), ("mean", [24.25, 24.5])]
+)
+def test_groupby_numerical_stability_sum_mean(func, values):
+ # GH#38778
+ data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15]
+ df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data})
+ result = getattr(df.groupby("group"), func)()
+ expected = DataFrame({"a": values, "b": values}, index=Index([1, 2], name="group"))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_numerical_stability_cumsum():
+ # GH#38934
+ data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15]
+ df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data})
+ result = df.groupby("group").cumsum()
+ exp_data = (
+ [1e16] * 2 + [1e16 + 96, 1e16 + 98] + [5e15 + 97, 5e15 + 98] + [97.0, 98.0]
+ )
+ expected = DataFrame({"a": exp_data, "b": exp_data})
+ tm.assert_frame_equal(result, expected, check_exact=True)
+
+
+def test_groupby_cumsum_skipna_false():
+ # GH#46216 don't propagate np.nan above the diagonal
+ arr = np.random.default_rng(2).standard_normal((5, 5))
+ df = DataFrame(arr)
+ for i in range(5):
+ df.iloc[i, i] = np.nan
+
+ df["A"] = 1
+ gb = df.groupby("A")
+
+ res = gb.cumsum(skipna=False)
+
+ expected = df[[0, 1, 2, 3, 4]].cumsum(skipna=False)
+ tm.assert_frame_equal(res, expected)
+
+
+def test_groupby_cumsum_timedelta64():
+ # GH#46216 don't ignore is_datetimelike in libgroupby.group_cumsum
+ dti = date_range("2016-01-01", periods=5)
+ ser = Series(dti) - dti[0]
+ ser[2] = pd.NaT
+
+ df = DataFrame({"A": 1, "B": ser})
+ gb = df.groupby("A")
+
+ res = gb.cumsum(numeric_only=False, skipna=True)
+ exp = DataFrame({"B": [ser[0], ser[1], pd.NaT, ser[4], ser[4] * 2]})
+ tm.assert_frame_equal(res, exp)
+
+ res = gb.cumsum(numeric_only=False, skipna=False)
+ exp = DataFrame({"B": [ser[0], ser[1], pd.NaT, pd.NaT, pd.NaT]})
+ tm.assert_frame_equal(res, exp)
+
+
+def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex):
+ dups = rand_series_with_duplicate_datetimeindex
+ result = dups.groupby(level=0).mean()
+ expected = dups.groupby(dups.index).mean()
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_all_nan_groups_drop():
+ # GH 15036
+ s = Series([1, 2, 3], [np.nan, np.nan, np.nan])
+ result = s.groupby(s.index).sum()
+ expected = Series([], index=Index([], dtype=np.float64), dtype=np.int64)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("numeric_only", [True, False])
+def test_groupby_empty_multi_column(as_index, numeric_only):
+ # GH 15106 & GH 41998
+ df = DataFrame(data=[], columns=["A", "B", "C"])
+ gb = df.groupby(["A", "B"], as_index=as_index)
+ result = gb.sum(numeric_only=numeric_only)
+ if as_index:
+ index = MultiIndex([[], []], [[], []], names=["A", "B"])
+ columns = ["C"] if not numeric_only else []
+ else:
+ index = RangeIndex(0)
+ columns = ["A", "B", "C"] if not numeric_only else ["A", "B"]
+ expected = DataFrame([], columns=columns, index=index)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_aggregation_non_numeric_dtype():
+ # GH #43108
+ df = DataFrame(
+ [["M", [1]], ["M", [1]], ["W", [10]], ["W", [20]]], columns=["MW", "v"]
+ )
+
+ expected = DataFrame(
+ {
+ "v": [[1, 1], [10, 20]],
+ },
+ index=Index(["M", "W"], dtype="object", name="MW"),
+ )
+
+ gb = df.groupby(by=["MW"])
+ result = gb.sum()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_aggregation_multi_non_numeric_dtype():
+ # GH #42395
+ df = DataFrame(
+ {
+ "x": [1, 0, 1, 1, 0],
+ "y": [Timedelta(i, "days") for i in range(1, 6)],
+ "z": [Timedelta(i * 10, "days") for i in range(1, 6)],
+ }
+ )
+
+ expected = DataFrame(
+ {
+ "y": [Timedelta(i, "days") for i in range(7, 9)],
+ "z": [Timedelta(i * 10, "days") for i in range(7, 9)],
+ },
+ index=Index([0, 1], dtype="int64", name="x"),
+ )
+
+ gb = df.groupby(by=["x"])
+ result = gb.sum()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_aggregation_numeric_with_non_numeric_dtype():
+ # GH #43108
+ df = DataFrame(
+ {
+ "x": [1, 0, 1, 1, 0],
+ "y": [Timedelta(i, "days") for i in range(1, 6)],
+ "z": list(range(1, 6)),
+ }
+ )
+
+ expected = DataFrame(
+ {"y": [Timedelta(7, "days"), Timedelta(8, "days")], "z": [7, 8]},
+ index=Index([0, 1], dtype="int64", name="x"),
+ )
+
+ gb = df.groupby(by=["x"])
+ result = gb.sum()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_filtered_df_std():
+ # GH 16174
+ dicts = [
+ {"filter_col": False, "groupby_col": True, "bool_col": True, "float_col": 10.5},
+ {"filter_col": True, "groupby_col": True, "bool_col": True, "float_col": 20.5},
+ {"filter_col": True, "groupby_col": True, "bool_col": True, "float_col": 30.5},
+ ]
+ df = DataFrame(dicts)
+
+ df_filter = df[df["filter_col"] == True] # noqa: E712
+ dfgb = df_filter.groupby("groupby_col")
+ result = dfgb.std()
+ expected = DataFrame(
+ [[0.0, 0.0, 7.071068]],
+ columns=["filter_col", "bool_col", "float_col"],
+ index=Index([True], name="groupby_col"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_datetime_categorical_multikey_groupby_indices():
+ # GH 26859
+ df = DataFrame(
+ {
+ "a": Series(list("abc")),
+ "b": Series(
+ to_datetime(["2018-01-01", "2018-02-01", "2018-03-01"]),
+ dtype="category",
+ ),
+ "c": Categorical.from_codes([-1, 0, 1], categories=[0, 1]),
+ }
+ )
+ result = df.groupby(["a", "b"], observed=False).indices
+ expected = {
+ ("a", Timestamp("2018-01-01 00:00:00")): np.array([0]),
+ ("b", Timestamp("2018-02-01 00:00:00")): np.array([1]),
+ ("c", Timestamp("2018-03-01 00:00:00")): np.array([2]),
+ }
+ assert result == expected
+
+
+def test_rolling_wrong_param_min_period():
+ # GH34037
+ name_l = ["Alice"] * 5 + ["Bob"] * 5
+ val_l = [np.nan, np.nan, 1, 2, 3] + [np.nan, 1, 2, 3, 4]
+ test_df = DataFrame([name_l, val_l]).T
+ test_df.columns = ["name", "val"]
+
+ result_error_msg = r"__init__\(\) got an unexpected keyword argument 'min_period'"
+ with pytest.raises(TypeError, match=result_error_msg):
+ test_df.groupby("name")["val"].rolling(window=2, min_period=1).sum()
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ object,
+ pytest.param("string[pyarrow_numpy]", marks=td.skip_if_no("pyarrow")),
+ ],
+)
+def test_by_column_values_with_same_starting_value(dtype):
+ # GH29635
+ df = DataFrame(
+ {
+ "Name": ["Thomas", "Thomas", "Thomas John"],
+ "Credit": [1200, 1300, 900],
+ "Mood": Series(["sad", "happy", "happy"], dtype=dtype),
+ }
+ )
+ aggregate_details = {"Mood": Series.mode, "Credit": "sum"}
+
+ result = df.groupby(["Name"]).agg(aggregate_details)
+ expected_result = DataFrame(
+ {
+ "Mood": [["happy", "sad"], "happy"],
+ "Credit": [2500, 900],
+ "Name": ["Thomas", "Thomas John"],
+ }
+ ).set_index("Name")
+
+ tm.assert_frame_equal(result, expected_result)
+
+
+def test_groupby_none_in_first_mi_level():
+ # GH#47348
+ arr = [[None, 1, 0, 1], [2, 3, 2, 3]]
+ ser = Series(1, index=MultiIndex.from_arrays(arr, names=["a", "b"]))
+ result = ser.groupby(level=[0, 1]).sum()
+ expected = Series(
+ [1, 2], MultiIndex.from_tuples([(0.0, 2), (1.0, 3)], names=["a", "b"])
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_none_column_name():
+ # GH#47348
+ df = DataFrame({None: [1, 1, 2, 2], "b": [1, 1, 2, 3], "c": [4, 5, 6, 7]})
+ result = df.groupby(by=[None]).sum()
+ expected = DataFrame({"b": [2, 5], "c": [9, 13]}, index=Index([1, 2], name=None))
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("selection", [None, "a", ["a"]])
+def test_single_element_list_grouping(selection):
+ # GH#42795, GH#53500
+ df = DataFrame({"a": [1, 2], "b": [np.nan, 5], "c": [np.nan, 2]}, index=["x", "y"])
+ grouped = df.groupby(["a"]) if selection is None else df.groupby(["a"])[selection]
+ result = [key for key, _ in grouped]
+
+ expected = [(1,), (2,)]
+ assert result == expected
+
+
+def test_groupby_string_dtype():
+ # GH 40148
+ df = DataFrame({"str_col": ["a", "b", "c", "a"], "num_col": [1, 2, 3, 2]})
+ df["str_col"] = df["str_col"].astype("string")
+ expected = DataFrame(
+ {
+ "str_col": [
+ "a",
+ "b",
+ "c",
+ ],
+ "num_col": [1.5, 2.0, 3.0],
+ }
+ )
+ expected["str_col"] = expected["str_col"].astype("string")
+ grouped = df.groupby("str_col", as_index=False)
+ result = grouped.mean()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "level_arg, multiindex", [([0], False), ((0,), False), ([0], True), ((0,), True)]
+)
+def test_single_element_listlike_level_grouping_deprecation(level_arg, multiindex):
+ # GH 51583
+ df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"])
+ if multiindex:
+ df = df.set_index(["a", "b"])
+ depr_msg = (
+ "Creating a Groupby object with a length-1 list-like "
+ "level parameter will yield indexes as tuples in a future version. "
+ "To keep indexes as scalars, create Groupby objects with "
+ "a scalar level parameter instead."
+ )
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ [key for key, _ in df.groupby(level=level_arg)]
+
+
+@pytest.mark.parametrize("func", ["sum", "cumsum", "cumprod", "prod"])
+def test_groupby_avoid_casting_to_float(func):
+ # GH#37493
+ val = 922337203685477580
+ df = DataFrame({"a": 1, "b": [val]})
+ result = getattr(df.groupby("a"), func)() - val
+ expected = DataFrame({"b": [0]}, index=Index([1], name="a"))
+ if func in ["cumsum", "cumprod"]:
+ expected = expected.reset_index(drop=True)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("func, val", [("sum", 3), ("prod", 2)])
+def test_groupby_sum_support_mask(any_numeric_ea_dtype, func, val):
+ # GH#37493
+ df = DataFrame({"a": 1, "b": [1, 2, pd.NA]}, dtype=any_numeric_ea_dtype)
+ result = getattr(df.groupby("a"), func)()
+ expected = DataFrame(
+ {"b": [val]},
+ index=Index([1], name="a", dtype=any_numeric_ea_dtype),
+ dtype=any_numeric_ea_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("val, dtype", [(111, "int"), (222, "uint")])
+def test_groupby_overflow(val, dtype):
+ # GH#37493
+ df = DataFrame({"a": 1, "b": [val, val]}, dtype=f"{dtype}8")
+ result = df.groupby("a").sum()
+ expected = DataFrame(
+ {"b": [val * 2]},
+ index=Index([1], name="a", dtype=f"{dtype}8"),
+ dtype=f"{dtype}64",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("a").cumsum()
+ expected = DataFrame({"b": [val, val * 2]}, dtype=f"{dtype}64")
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("a").prod()
+ expected = DataFrame(
+ {"b": [val * val]},
+ index=Index([1], name="a", dtype=f"{dtype}8"),
+ dtype=f"{dtype}64",
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("skipna, val", [(True, 3), (False, pd.NA)])
+def test_groupby_cumsum_mask(any_numeric_ea_dtype, skipna, val):
+ # GH#37493
+ df = DataFrame({"a": 1, "b": [1, pd.NA, 2]}, dtype=any_numeric_ea_dtype)
+ result = df.groupby("a").cumsum(skipna=skipna)
+ expected = DataFrame(
+ {"b": [1, pd.NA, val]},
+ dtype=any_numeric_ea_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "val_in, index, val_out",
+ [
+ (
+ [1.0, 2.0, 3.0, 4.0, 5.0],
+ ["foo", "foo", "bar", "baz", "blah"],
+ [3.0, 4.0, 5.0, 3.0],
+ ),
+ (
+ [1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
+ ["foo", "foo", "bar", "baz", "blah", "blah"],
+ [3.0, 4.0, 11.0, 3.0],
+ ),
+ ],
+)
+def test_groupby_index_name_in_index_content(val_in, index, val_out):
+ # GH 48567
+ series = Series(data=val_in, name="values", index=Index(index, name="blah"))
+ result = series.groupby("blah").sum()
+ expected = Series(
+ data=val_out,
+ name="values",
+ index=Index(["bar", "baz", "blah", "foo"], name="blah"),
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = series.to_frame().groupby("blah").sum()
+ expected = expected.to_frame()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("n", [1, 10, 32, 100, 1000])
+def test_sum_of_booleans(n):
+ # GH 50347
+ df = DataFrame({"groupby_col": 1, "bool": [True] * n})
+ df["bool"] = df["bool"].eq(True)
+ result = df.groupby("groupby_col").sum()
+ expected = DataFrame({"bool": [n]}, index=Index([1], name="groupby_col"))
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.filterwarnings(
+ "ignore:invalid value encountered in remainder:RuntimeWarning"
+)
+@pytest.mark.parametrize("method", ["head", "tail", "nth", "first", "last"])
+def test_groupby_method_drop_na(method):
+ # GH 21755
+ df = DataFrame({"A": ["a", np.nan, "b", np.nan, "c"], "B": range(5)})
+
+ if method == "nth":
+ result = getattr(df.groupby("A"), method)(n=0)
+ else:
+ result = getattr(df.groupby("A"), method)()
+
+ if method in ["first", "last"]:
+ expected = DataFrame({"B": [0, 2, 4]}).set_index(
+ Series(["a", "b", "c"], name="A")
+ )
+ else:
+ expected = DataFrame({"A": ["a", "b", "c"], "B": [0, 2, 4]}, index=[0, 2, 4])
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_reduce_period():
+ # GH#51040
+ pi = pd.period_range("2016-01-01", periods=100, freq="D")
+ grps = list(range(10)) * 10
+ ser = pi.to_series()
+ gb = ser.groupby(grps)
+
+ with pytest.raises(TypeError, match="Period type does not support sum operations"):
+ gb.sum()
+ with pytest.raises(
+ TypeError, match="Period type does not support cumsum operations"
+ ):
+ gb.cumsum()
+ with pytest.raises(TypeError, match="Period type does not support prod operations"):
+ gb.prod()
+ with pytest.raises(
+ TypeError, match="Period type does not support cumprod operations"
+ ):
+ gb.cumprod()
+
+ res = gb.max()
+ expected = ser[-10:]
+ expected.index = Index(range(10), dtype=int)
+ tm.assert_series_equal(res, expected)
+
+ res = gb.min()
+ expected = ser[:10]
+ expected.index = Index(range(10), dtype=int)
+ tm.assert_series_equal(res, expected)
+
+
+def test_obj_with_exclusions_duplicate_columns():
+ # GH#50806
+ df = DataFrame([[0, 1, 2, 3]])
+ df.columns = [0, 1, 2, 0]
+ gb = df.groupby(df[1])
+ result = gb._obj_with_exclusions
+ expected = df.take([0, 2, 3], axis=1)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("numeric_only", [True, False])
+def test_groupby_numeric_only_std_no_result(numeric_only):
+ # GH 51080
+ dicts_non_numeric = [{"a": "foo", "b": "bar"}, {"a": "car", "b": "dar"}]
+ df = DataFrame(dicts_non_numeric)
+ dfgb = df.groupby("a", as_index=False, sort=False)
+
+ if numeric_only:
+ result = dfgb.std(numeric_only=True)
+ expected_df = DataFrame(["foo", "car"], columns=["a"])
+ tm.assert_frame_equal(result, expected_df)
+ else:
+ with pytest.raises(
+ ValueError, match="could not convert string to float: 'bar'"
+ ):
+ dfgb.std(numeric_only=numeric_only)
+
+
+def test_grouping_with_categorical_interval_columns():
+ # GH#34164
+ df = DataFrame({"x": [0.1, 0.2, 0.3, -0.4, 0.5], "w": ["a", "b", "a", "c", "a"]})
+ qq = pd.qcut(df["x"], q=np.linspace(0, 1, 5))
+ result = df.groupby([qq, "w"], observed=False)["x"].agg("mean")
+ categorical_index_level_1 = Categorical(
+ [
+ Interval(-0.401, 0.1, closed="right"),
+ Interval(0.1, 0.2, closed="right"),
+ Interval(0.2, 0.3, closed="right"),
+ Interval(0.3, 0.5, closed="right"),
+ ],
+ ordered=True,
+ )
+ index_level_2 = ["a", "b", "c"]
+ mi = MultiIndex.from_product(
+ [categorical_index_level_1, index_level_2], names=["x", "w"]
+ )
+ expected = Series(
+ np.array(
+ [
+ 0.1,
+ np.nan,
+ -0.4,
+ np.nan,
+ 0.2,
+ np.nan,
+ 0.3,
+ np.nan,
+ np.nan,
+ 0.5,
+ np.nan,
+ np.nan,
+ ]
+ ),
+ index=mi,
+ name="x",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("bug_var", [1, "a"])
+def test_groupby_sum_on_nan_should_return_nan(bug_var):
+ # GH 24196
+ df = DataFrame({"A": [bug_var, bug_var, bug_var, np.nan]})
+ dfgb = df.groupby(lambda x: x)
+ result = dfgb.sum(min_count=1)
+
+ expected_df = DataFrame([bug_var, bug_var, bug_var, None], columns=["A"])
+ tm.assert_frame_equal(result, expected_df)
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ "count",
+ "corr",
+ "cummax",
+ "cummin",
+ "cumprod",
+ "describe",
+ "rank",
+ "quantile",
+ "diff",
+ "shift",
+ "all",
+ "any",
+ "idxmin",
+ "idxmax",
+ "ffill",
+ "bfill",
+ "pct_change",
+ ],
+)
+def test_groupby_selection_with_methods(df, method):
+ # some methods which require DatetimeIndex
+ rng = date_range("2014", periods=len(df))
+ df.index = rng
+
+ g = df.groupby(["A"])[["C"]]
+ g_exp = df[["C"]].groupby(df["A"])
+ # TODO check groupby with > 1 col ?
+
+ res = getattr(g, method)()
+ exp = getattr(g_exp, method)()
+
+ # should always be frames!
+ tm.assert_frame_equal(res, exp)
+
+
+def test_groupby_selection_other_methods(df):
+ # some methods which require DatetimeIndex
+ rng = date_range("2014", periods=len(df))
+ df.columns.name = "foo"
+ df.index = rng
+
+ g = df.groupby(["A"])[["C"]]
+ g_exp = df[["C"]].groupby(df["A"])
+
+ # methods which aren't just .foo()
+ tm.assert_frame_equal(g.fillna(0), g_exp.fillna(0))
+ msg = "DataFrameGroupBy.dtypes is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ tm.assert_frame_equal(g.dtypes, g_exp.dtypes)
+ tm.assert_frame_equal(g.apply(lambda x: x.sum()), g_exp.apply(lambda x: x.sum()))
+
+ tm.assert_frame_equal(g.resample("D").mean(), g_exp.resample("D").mean())
+ tm.assert_frame_equal(g.resample("D").ohlc(), g_exp.resample("D").ohlc())
+
+ tm.assert_frame_equal(
+ g.filter(lambda x: len(x) == 3), g_exp.filter(lambda x: len(x) == 3)
+ )
+
+
+def test_groupby_with_Time_Grouper():
+ idx2 = [
+ to_datetime("2016-08-31 22:08:12.000"),
+ to_datetime("2016-08-31 22:09:12.200"),
+ to_datetime("2016-08-31 22:20:12.400"),
+ ]
+
+ test_data = DataFrame(
+ {"quant": [1.0, 1.0, 3.0], "quant2": [1.0, 1.0, 3.0], "time2": idx2}
+ )
+
+ expected_output = DataFrame(
+ {
+ "time2": date_range("2016-08-31 22:08:00", periods=13, freq="1T"),
+ "quant": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+ "quant2": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+ }
+ )
+
+ df = test_data.groupby(Grouper(key="time2", freq="1T")).count().reset_index()
+
+ tm.assert_frame_equal(df, expected_output)
+
+
+def test_groupby_series_with_datetimeindex_month_name():
+ # GH 48509
+ s = Series([0, 1, 0], index=date_range("2022-01-01", periods=3), name="jan")
+ result = s.groupby(s).count()
+ expected = Series([2, 1], name="jan")
+ expected.index.name = "jan"
+ tm.assert_series_equal(result, expected)
+
+
+def test_get_group_axis_1():
+ # GH#54858
+ df = DataFrame(
+ {
+ "col1": [0, 3, 2, 3],
+ "col2": [4, 1, 6, 7],
+ "col3": [3, 8, 2, 10],
+ "col4": [1, 13, 6, 15],
+ "col5": [-4, 5, 6, -7],
+ }
+ )
+ with tm.assert_produces_warning(FutureWarning, match="deprecated"):
+ grouped = df.groupby(axis=1, by=[1, 2, 3, 2, 1])
+ result = grouped.get_group(1)
+ expected = DataFrame(
+ {
+ "col1": [0, 3, 2, 3],
+ "col5": [-4, 5, 6, -7],
+ }
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_dropna.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_dropna.py
new file mode 100644
index 0000000000000000000000000000000000000000..099e7bc3890d080a4709ac05b7b68c4f2e24ee68
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_dropna.py
@@ -0,0 +1,696 @@
+import numpy as np
+import pytest
+
+from pandas.compat.pyarrow import pa_version_under7p0
+
+from pandas.core.dtypes.missing import na_value_for_dtype
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.tests.groupby import get_groupby_method_args
+
+
+@pytest.mark.parametrize(
+ "dropna, tuples, outputs",
+ [
+ (
+ True,
+ [["A", "B"], ["B", "A"]],
+ {"c": [13.0, 123.23], "d": [13.0, 123.0], "e": [13.0, 1.0]},
+ ),
+ (
+ False,
+ [["A", "B"], ["A", np.nan], ["B", "A"]],
+ {
+ "c": [13.0, 12.3, 123.23],
+ "d": [13.0, 233.0, 123.0],
+ "e": [13.0, 12.0, 1.0],
+ },
+ ),
+ ],
+)
+def test_groupby_dropna_multi_index_dataframe_nan_in_one_group(
+ dropna, tuples, outputs, nulls_fixture
+):
+ # GH 3729 this is to test that NA is in one group
+ df_list = [
+ ["A", "B", 12, 12, 12],
+ ["A", nulls_fixture, 12.3, 233.0, 12],
+ ["B", "A", 123.23, 123, 1],
+ ["A", "B", 1, 1, 1.0],
+ ]
+ df = pd.DataFrame(df_list, columns=["a", "b", "c", "d", "e"])
+ grouped = df.groupby(["a", "b"], dropna=dropna).sum()
+
+ mi = pd.MultiIndex.from_tuples(tuples, names=list("ab"))
+
+ # Since right now, by default MI will drop NA from levels when we create MI
+ # via `from_*`, so we need to add NA for level manually afterwards.
+ if not dropna:
+ mi = mi.set_levels(["A", "B", np.nan], level="b")
+ expected = pd.DataFrame(outputs, index=mi)
+
+ tm.assert_frame_equal(grouped, expected)
+
+
+@pytest.mark.parametrize(
+ "dropna, tuples, outputs",
+ [
+ (
+ True,
+ [["A", "B"], ["B", "A"]],
+ {"c": [12.0, 123.23], "d": [12.0, 123.0], "e": [12.0, 1.0]},
+ ),
+ (
+ False,
+ [["A", "B"], ["A", np.nan], ["B", "A"], [np.nan, "B"]],
+ {
+ "c": [12.0, 13.3, 123.23, 1.0],
+ "d": [12.0, 234.0, 123.0, 1.0],
+ "e": [12.0, 13.0, 1.0, 1.0],
+ },
+ ),
+ ],
+)
+def test_groupby_dropna_multi_index_dataframe_nan_in_two_groups(
+ dropna, tuples, outputs, nulls_fixture, nulls_fixture2
+):
+ # GH 3729 this is to test that NA in different groups with different representations
+ df_list = [
+ ["A", "B", 12, 12, 12],
+ ["A", nulls_fixture, 12.3, 233.0, 12],
+ ["B", "A", 123.23, 123, 1],
+ [nulls_fixture2, "B", 1, 1, 1.0],
+ ["A", nulls_fixture2, 1, 1, 1.0],
+ ]
+ df = pd.DataFrame(df_list, columns=["a", "b", "c", "d", "e"])
+ grouped = df.groupby(["a", "b"], dropna=dropna).sum()
+
+ mi = pd.MultiIndex.from_tuples(tuples, names=list("ab"))
+
+ # Since right now, by default MI will drop NA from levels when we create MI
+ # via `from_*`, so we need to add NA for level manually afterwards.
+ if not dropna:
+ mi = mi.set_levels([["A", "B", np.nan], ["A", "B", np.nan]])
+ expected = pd.DataFrame(outputs, index=mi)
+
+ tm.assert_frame_equal(grouped, expected)
+
+
+@pytest.mark.parametrize(
+ "dropna, idx, outputs",
+ [
+ (True, ["A", "B"], {"b": [123.23, 13.0], "c": [123.0, 13.0], "d": [1.0, 13.0]}),
+ (
+ False,
+ ["A", "B", np.nan],
+ {
+ "b": [123.23, 13.0, 12.3],
+ "c": [123.0, 13.0, 233.0],
+ "d": [1.0, 13.0, 12.0],
+ },
+ ),
+ ],
+)
+def test_groupby_dropna_normal_index_dataframe(dropna, idx, outputs):
+ # GH 3729
+ df_list = [
+ ["B", 12, 12, 12],
+ [None, 12.3, 233.0, 12],
+ ["A", 123.23, 123, 1],
+ ["B", 1, 1, 1.0],
+ ]
+ df = pd.DataFrame(df_list, columns=["a", "b", "c", "d"])
+ grouped = df.groupby("a", dropna=dropna).sum()
+
+ expected = pd.DataFrame(outputs, index=pd.Index(idx, dtype="object", name="a"))
+
+ tm.assert_frame_equal(grouped, expected)
+
+
+@pytest.mark.parametrize(
+ "dropna, idx, expected",
+ [
+ (True, ["a", "a", "b", np.nan], pd.Series([3, 3], index=["a", "b"])),
+ (
+ False,
+ ["a", "a", "b", np.nan],
+ pd.Series([3, 3, 3], index=["a", "b", np.nan]),
+ ),
+ ],
+)
+def test_groupby_dropna_series_level(dropna, idx, expected):
+ ser = pd.Series([1, 2, 3, 3], index=idx)
+
+ result = ser.groupby(level=0, dropna=dropna).sum()
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "dropna, expected",
+ [
+ (True, pd.Series([210.0, 350.0], index=["a", "b"], name="Max Speed")),
+ (
+ False,
+ pd.Series([210.0, 350.0, 20.0], index=["a", "b", np.nan], name="Max Speed"),
+ ),
+ ],
+)
+def test_groupby_dropna_series_by(dropna, expected):
+ ser = pd.Series(
+ [390.0, 350.0, 30.0, 20.0],
+ index=["Falcon", "Falcon", "Parrot", "Parrot"],
+ name="Max Speed",
+ )
+
+ result = ser.groupby(["a", "b", "a", np.nan], dropna=dropna).mean()
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("dropna", (False, True))
+def test_grouper_dropna_propagation(dropna):
+ # GH 36604
+ df = pd.DataFrame({"A": [0, 0, 1, None], "B": [1, 2, 3, None]})
+ gb = df.groupby("A", dropna=dropna)
+ assert gb.grouper.dropna == dropna
+
+
+@pytest.mark.parametrize(
+ "index",
+ [
+ pd.RangeIndex(0, 4),
+ list("abcd"),
+ pd.MultiIndex.from_product([(1, 2), ("R", "B")], names=["num", "col"]),
+ ],
+)
+def test_groupby_dataframe_slice_then_transform(dropna, index):
+ # GH35014 & GH35612
+ expected_data = {"B": [2, 2, 1, np.nan if dropna else 1]}
+
+ df = pd.DataFrame({"A": [0, 0, 1, None], "B": [1, 2, 3, None]}, index=index)
+ gb = df.groupby("A", dropna=dropna)
+
+ result = gb.transform(len)
+ expected = pd.DataFrame(expected_data, index=index)
+ tm.assert_frame_equal(result, expected)
+
+ result = gb[["B"]].transform(len)
+ expected = pd.DataFrame(expected_data, index=index)
+ tm.assert_frame_equal(result, expected)
+
+ result = gb["B"].transform(len)
+ expected = pd.Series(expected_data["B"], index=index, name="B")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "dropna, tuples, outputs",
+ [
+ (
+ True,
+ [["A", "B"], ["B", "A"]],
+ {"c": [13.0, 123.23], "d": [12.0, 123.0], "e": [1.0, 1.0]},
+ ),
+ (
+ False,
+ [["A", "B"], ["A", np.nan], ["B", "A"]],
+ {
+ "c": [13.0, 12.3, 123.23],
+ "d": [12.0, 233.0, 123.0],
+ "e": [1.0, 12.0, 1.0],
+ },
+ ),
+ ],
+)
+def test_groupby_dropna_multi_index_dataframe_agg(dropna, tuples, outputs):
+ # GH 3729
+ df_list = [
+ ["A", "B", 12, 12, 12],
+ ["A", None, 12.3, 233.0, 12],
+ ["B", "A", 123.23, 123, 1],
+ ["A", "B", 1, 1, 1.0],
+ ]
+ df = pd.DataFrame(df_list, columns=["a", "b", "c", "d", "e"])
+ agg_dict = {"c": "sum", "d": "max", "e": "min"}
+ grouped = df.groupby(["a", "b"], dropna=dropna).agg(agg_dict)
+
+ mi = pd.MultiIndex.from_tuples(tuples, names=list("ab"))
+
+ # Since right now, by default MI will drop NA from levels when we create MI
+ # via `from_*`, so we need to add NA for level manually afterwards.
+ if not dropna:
+ mi = mi.set_levels(["A", "B", np.nan], level="b")
+ expected = pd.DataFrame(outputs, index=mi)
+
+ tm.assert_frame_equal(grouped, expected)
+
+
+@pytest.mark.arm_slow
+@pytest.mark.parametrize(
+ "datetime1, datetime2",
+ [
+ (pd.Timestamp("2020-01-01"), pd.Timestamp("2020-02-01")),
+ (pd.Timedelta("-2 days"), pd.Timedelta("-1 days")),
+ (pd.Period("2020-01-01"), pd.Period("2020-02-01")),
+ ],
+)
+@pytest.mark.parametrize("dropna, values", [(True, [12, 3]), (False, [12, 3, 6])])
+def test_groupby_dropna_datetime_like_data(
+ dropna, values, datetime1, datetime2, unique_nulls_fixture, unique_nulls_fixture2
+):
+ # 3729
+ df = pd.DataFrame(
+ {
+ "values": [1, 2, 3, 4, 5, 6],
+ "dt": [
+ datetime1,
+ unique_nulls_fixture,
+ datetime2,
+ unique_nulls_fixture2,
+ datetime1,
+ datetime1,
+ ],
+ }
+ )
+
+ if dropna:
+ indexes = [datetime1, datetime2]
+ else:
+ indexes = [datetime1, datetime2, np.nan]
+
+ grouped = df.groupby("dt", dropna=dropna).agg({"values": "sum"})
+ expected = pd.DataFrame({"values": values}, index=pd.Index(indexes, name="dt"))
+
+ tm.assert_frame_equal(grouped, expected)
+
+
+@pytest.mark.parametrize(
+ "dropna, data, selected_data, levels",
+ [
+ pytest.param(
+ False,
+ {"groups": ["a", "a", "b", np.nan], "values": [10, 10, 20, 30]},
+ {"values": [0, 1, 0, 0]},
+ ["a", "b", np.nan],
+ id="dropna_false_has_nan",
+ ),
+ pytest.param(
+ True,
+ {"groups": ["a", "a", "b", np.nan], "values": [10, 10, 20, 30]},
+ {"values": [0, 1, 0]},
+ None,
+ id="dropna_true_has_nan",
+ ),
+ pytest.param(
+ # no nan in "groups"; dropna=True|False should be same.
+ False,
+ {"groups": ["a", "a", "b", "c"], "values": [10, 10, 20, 30]},
+ {"values": [0, 1, 0, 0]},
+ None,
+ id="dropna_false_no_nan",
+ ),
+ pytest.param(
+ # no nan in "groups"; dropna=True|False should be same.
+ True,
+ {"groups": ["a", "a", "b", "c"], "values": [10, 10, 20, 30]},
+ {"values": [0, 1, 0, 0]},
+ None,
+ id="dropna_true_no_nan",
+ ),
+ ],
+)
+def test_groupby_apply_with_dropna_for_multi_index(dropna, data, selected_data, levels):
+ # GH 35889
+
+ df = pd.DataFrame(data)
+ gb = df.groupby("groups", dropna=dropna)
+ result = gb.apply(lambda grp: pd.DataFrame({"values": range(len(grp))}))
+
+ mi_tuples = tuple(zip(data["groups"], selected_data["values"]))
+ mi = pd.MultiIndex.from_tuples(mi_tuples, names=["groups", None])
+ # Since right now, by default MI will drop NA from levels when we create MI
+ # via `from_*`, so we need to add NA for level manually afterwards.
+ if not dropna and levels:
+ mi = mi.set_levels(levels, level="groups")
+
+ expected = pd.DataFrame(selected_data, index=mi)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("input_index", [None, ["a"], ["a", "b"]])
+@pytest.mark.parametrize("keys", [["a"], ["a", "b"]])
+@pytest.mark.parametrize("series", [True, False])
+def test_groupby_dropna_with_multiindex_input(input_index, keys, series):
+ # GH#46783
+ obj = pd.DataFrame(
+ {
+ "a": [1, np.nan],
+ "b": [1, 1],
+ "c": [2, 3],
+ }
+ )
+
+ expected = obj.set_index(keys)
+ if series:
+ expected = expected["c"]
+ elif input_index == ["a", "b"] and keys == ["a"]:
+ # Column b should not be aggregated
+ expected = expected[["c"]]
+
+ if input_index is not None:
+ obj = obj.set_index(input_index)
+ gb = obj.groupby(keys, dropna=False)
+ if series:
+ gb = gb["c"]
+ result = gb.sum()
+
+ tm.assert_equal(result, expected)
+
+
+def test_groupby_nan_included():
+ # GH 35646
+ data = {"group": ["g1", np.nan, "g1", "g2", np.nan], "B": [0, 1, 2, 3, 4]}
+ df = pd.DataFrame(data)
+ grouped = df.groupby("group", dropna=False)
+ result = grouped.indices
+ dtype = np.intp
+ expected = {
+ "g1": np.array([0, 2], dtype=dtype),
+ "g2": np.array([3], dtype=dtype),
+ np.nan: np.array([1, 4], dtype=dtype),
+ }
+ for result_values, expected_values in zip(result.values(), expected.values()):
+ tm.assert_numpy_array_equal(result_values, expected_values)
+ assert np.isnan(list(result.keys())[2])
+ assert list(result.keys())[0:2] == ["g1", "g2"]
+
+
+def test_groupby_drop_nan_with_multi_index():
+ # GH 39895
+ df = pd.DataFrame([[np.nan, 0, 1]], columns=["a", "b", "c"])
+ df = df.set_index(["a", "b"])
+ result = df.groupby(["a", "b"], dropna=False).first()
+ expected = df
+ tm.assert_frame_equal(result, expected)
+
+
+# sequence_index enumerates all strings made up of x, y, z of length 4
+@pytest.mark.parametrize("sequence_index", range(3**4))
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ None,
+ "UInt8",
+ "Int8",
+ "UInt16",
+ "Int16",
+ "UInt32",
+ "Int32",
+ "UInt64",
+ "Int64",
+ "Float32",
+ "Int64",
+ "Float64",
+ "category",
+ "string",
+ pytest.param(
+ "string[pyarrow]",
+ marks=pytest.mark.skipif(
+ pa_version_under7p0, reason="pyarrow is not installed"
+ ),
+ ),
+ "datetime64[ns]",
+ "period[d]",
+ "Sparse[float]",
+ ],
+)
+@pytest.mark.parametrize("test_series", [True, False])
+def test_no_sort_keep_na(sequence_index, dtype, test_series, as_index):
+ # GH#46584, GH#48794
+
+ # Convert sequence_index into a string sequence, e.g. 5 becomes "xxyz"
+ # This sequence is used for the grouper.
+ sequence = "".join(
+ [{0: "x", 1: "y", 2: "z"}[sequence_index // (3**k) % 3] for k in range(4)]
+ )
+
+ # Unique values to use for grouper, depends on dtype
+ if dtype in ("string", "string[pyarrow]"):
+ uniques = {"x": "x", "y": "y", "z": pd.NA}
+ elif dtype in ("datetime64[ns]", "period[d]"):
+ uniques = {"x": "2016-01-01", "y": "2017-01-01", "z": pd.NA}
+ else:
+ uniques = {"x": 1, "y": 2, "z": np.nan}
+
+ df = pd.DataFrame(
+ {
+ "key": pd.Series([uniques[label] for label in sequence], dtype=dtype),
+ "a": [0, 1, 2, 3],
+ }
+ )
+ gb = df.groupby("key", dropna=False, sort=False, as_index=as_index, observed=False)
+ if test_series:
+ gb = gb["a"]
+ result = gb.sum()
+
+ # Manually compute the groupby sum, use the labels "x", "y", and "z" to avoid
+ # issues with hashing np.nan
+ summed = {}
+ for idx, label in enumerate(sequence):
+ summed[label] = summed.get(label, 0) + idx
+ if dtype == "category":
+ index = pd.CategoricalIndex(
+ [uniques[e] for e in summed],
+ df["key"].cat.categories,
+ name="key",
+ )
+ elif isinstance(dtype, str) and dtype.startswith("Sparse"):
+ index = pd.Index(
+ pd.array([uniques[label] for label in summed], dtype=dtype), name="key"
+ )
+ else:
+ index = pd.Index([uniques[label] for label in summed], dtype=dtype, name="key")
+ expected = pd.Series(summed.values(), index=index, name="a", dtype=None)
+ if not test_series:
+ expected = expected.to_frame()
+ if not as_index:
+ expected = expected.reset_index()
+ if dtype is not None and dtype.startswith("Sparse"):
+ expected["key"] = expected["key"].astype(dtype)
+
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize("test_series", [True, False])
+@pytest.mark.parametrize("dtype", [object, None])
+def test_null_is_null_for_dtype(
+ sort, dtype, nulls_fixture, nulls_fixture2, test_series
+):
+ # GH#48506 - groups should always result in using the null for the dtype
+ df = pd.DataFrame({"a": [1, 2]})
+ groups = pd.Series([nulls_fixture, nulls_fixture2], dtype=dtype)
+ obj = df["a"] if test_series else df
+ gb = obj.groupby(groups, dropna=False, sort=sort)
+ result = gb.sum()
+ index = pd.Index([na_value_for_dtype(groups.dtype)])
+ expected = pd.DataFrame({"a": [3]}, index=index)
+ if test_series:
+ tm.assert_series_equal(result, expected["a"])
+ else:
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("index_kind", ["range", "single", "multi"])
+def test_categorical_reducers(
+ request, reduction_func, observed, sort, as_index, index_kind
+):
+ # GH#36327
+ if (
+ reduction_func in ("idxmin", "idxmax")
+ and not observed
+ and index_kind != "multi"
+ ):
+ msg = "GH#10694 - idxmin/max broken for categorical with observed=False"
+ request.node.add_marker(pytest.mark.xfail(reason=msg))
+
+ # Ensure there is at least one null value by appending to the end
+ values = np.append(np.random.default_rng(2).choice([1, 2, None], size=19), None)
+ df = pd.DataFrame(
+ {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(20)}
+ )
+
+ # Strategy: Compare to dropna=True by filling null values with a new code
+ df_filled = df.copy()
+ df_filled["x"] = pd.Categorical(values, categories=[1, 2, 3, 4]).fillna(4)
+
+ if index_kind == "range":
+ keys = ["x"]
+ elif index_kind == "single":
+ keys = ["x"]
+ df = df.set_index("x")
+ df_filled = df_filled.set_index("x")
+ else:
+ keys = ["x", "x2"]
+ df["x2"] = df["x"]
+ df = df.set_index(["x", "x2"])
+ df_filled["x2"] = df_filled["x"]
+ df_filled = df_filled.set_index(["x", "x2"])
+ args = get_groupby_method_args(reduction_func, df)
+ args_filled = get_groupby_method_args(reduction_func, df_filled)
+ if reduction_func == "corrwith" and index_kind == "range":
+ # Don't include the grouping columns so we can call reset_index
+ args = (args[0].drop(columns=keys),)
+ args_filled = (args_filled[0].drop(columns=keys),)
+
+ gb_filled = df_filled.groupby(keys, observed=observed, sort=sort, as_index=True)
+ expected = getattr(gb_filled, reduction_func)(*args_filled).reset_index()
+ expected["x"] = expected["x"].replace(4, None)
+ if index_kind == "multi":
+ expected["x2"] = expected["x2"].replace(4, None)
+ if as_index:
+ if index_kind == "multi":
+ expected = expected.set_index(["x", "x2"])
+ else:
+ expected = expected.set_index("x")
+ elif index_kind != "range" and reduction_func != "size":
+ # size, unlike other methods, has the desired behavior in GH#49519
+ expected = expected.drop(columns="x")
+ if index_kind == "multi":
+ expected = expected.drop(columns="x2")
+ if reduction_func in ("idxmax", "idxmin") and index_kind != "range":
+ # expected was computed with a RangeIndex; need to translate to index values
+ values = expected["y"].values.tolist()
+ if index_kind == "single":
+ values = [np.nan if e == 4 else e for e in values]
+ else:
+ values = [(np.nan, np.nan) if e == (4, 4) else e for e in values]
+ expected["y"] = values
+ if reduction_func == "size":
+ # size, unlike other methods, has the desired behavior in GH#49519
+ expected = expected.rename(columns={0: "size"})
+ if as_index:
+ expected = expected["size"].rename(None)
+
+ gb_keepna = df.groupby(
+ keys, dropna=False, observed=observed, sort=sort, as_index=as_index
+ )
+ if as_index or index_kind == "range" or reduction_func == "size":
+ warn = None
+ else:
+ warn = FutureWarning
+ msg = "A grouping .* was excluded from the result"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = getattr(gb_keepna, reduction_func)(*args)
+
+ # size will return a Series, others are DataFrame
+ tm.assert_equal(result, expected)
+
+
+def test_categorical_transformers(
+ request, transformation_func, observed, sort, as_index
+):
+ # GH#36327
+ if transformation_func == "fillna":
+ msg = "GH#49651 fillna may incorrectly reorders results when dropna=False"
+ request.node.add_marker(pytest.mark.xfail(reason=msg, strict=False))
+
+ values = np.append(np.random.default_rng(2).choice([1, 2, None], size=19), None)
+ df = pd.DataFrame(
+ {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(20)}
+ )
+ args = get_groupby_method_args(transformation_func, df)
+
+ # Compute result for null group
+ null_group_values = df[df["x"].isnull()]["y"]
+ if transformation_func == "cumcount":
+ null_group_data = list(range(len(null_group_values)))
+ elif transformation_func == "ngroup":
+ if sort:
+ if observed:
+ na_group = df["x"].nunique(dropna=False) - 1
+ else:
+ # TODO: Should this be 3?
+ na_group = df["x"].nunique(dropna=False) - 1
+ else:
+ na_group = df.iloc[: null_group_values.index[0]]["x"].nunique()
+ null_group_data = len(null_group_values) * [na_group]
+ else:
+ null_group_data = getattr(null_group_values, transformation_func)(*args)
+ null_group_result = pd.DataFrame({"y": null_group_data})
+
+ gb_keepna = df.groupby(
+ "x", dropna=False, observed=observed, sort=sort, as_index=as_index
+ )
+ gb_dropna = df.groupby("x", dropna=True, observed=observed, sort=sort)
+
+ msg = "The default fill_method='ffill' in DataFrameGroupBy.pct_change is deprecated"
+ if transformation_func == "pct_change":
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = getattr(gb_keepna, "pct_change")(*args)
+ else:
+ result = getattr(gb_keepna, transformation_func)(*args)
+ expected = getattr(gb_dropna, transformation_func)(*args)
+
+ for iloc, value in zip(
+ df[df["x"].isnull()].index.tolist(), null_group_result.values.ravel()
+ ):
+ if expected.ndim == 1:
+ expected.iloc[iloc] = value
+ else:
+ expected.iloc[iloc, 0] = value
+ if transformation_func == "ngroup":
+ expected[df["x"].notnull() & expected.ge(na_group)] += 1
+ if transformation_func not in ("rank", "diff", "pct_change", "shift"):
+ expected = expected.astype("int64")
+
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["head", "tail"])
+def test_categorical_head_tail(method, observed, sort, as_index):
+ # GH#36327
+ values = np.random.default_rng(2).choice([1, 2, None], 30)
+ df = pd.DataFrame(
+ {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(len(values))}
+ )
+ gb = df.groupby("x", dropna=False, observed=observed, sort=sort, as_index=as_index)
+ result = getattr(gb, method)()
+
+ if method == "tail":
+ values = values[::-1]
+ # Take the top 5 values from each group
+ mask = (
+ ((values == 1) & ((values == 1).cumsum() <= 5))
+ | ((values == 2) & ((values == 2).cumsum() <= 5))
+ # flake8 doesn't like the vectorized check for None, thinks we should use `is`
+ | ((values == None) & ((values == None).cumsum() <= 5)) # noqa: E711
+ )
+ if method == "tail":
+ mask = mask[::-1]
+ expected = df[mask]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_categorical_agg():
+ # GH#36327
+ values = np.random.default_rng(2).choice([1, 2, None], 30)
+ df = pd.DataFrame(
+ {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(len(values))}
+ )
+ gb = df.groupby("x", dropna=False, observed=False)
+ result = gb.agg(lambda x: x.sum())
+ expected = gb.sum()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_categorical_transform():
+ # GH#36327
+ values = np.random.default_rng(2).choice([1, 2, None], 30)
+ df = pd.DataFrame(
+ {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(len(values))}
+ )
+ gb = df.groupby("x", dropna=False, observed=False)
+ result = gb.transform(lambda x: x.sum())
+ expected = gb.transform("sum")
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_shift_diff.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_shift_diff.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb4b9aa866ac9e2f897b6ce8ffd08cfda0c9a491
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_shift_diff.py
@@ -0,0 +1,254 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ NaT,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+
+
+def test_group_shift_with_null_key():
+ # This test is designed to replicate the segfault in issue #13813.
+ n_rows = 1200
+
+ # Generate a moderately large dataframe with occasional missing
+ # values in column `B`, and then group by [`A`, `B`]. This should
+ # force `-1` in `labels` array of `g.grouper.group_info` exactly
+ # at those places, where the group-by key is partially missing.
+ df = DataFrame(
+ [(i % 12, i % 3 if i % 3 else np.nan, i) for i in range(n_rows)],
+ dtype=float,
+ columns=["A", "B", "Z"],
+ index=None,
+ )
+ g = df.groupby(["A", "B"])
+
+ expected = DataFrame(
+ [(i + 12 if i % 3 and i < n_rows - 12 else np.nan) for i in range(n_rows)],
+ dtype=float,
+ columns=["Z"],
+ index=None,
+ )
+ result = g.shift(-1)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_group_shift_with_fill_value():
+ # GH #24128
+ n_rows = 24
+ df = DataFrame(
+ [(i % 12, i % 3, i) for i in range(n_rows)],
+ dtype=float,
+ columns=["A", "B", "Z"],
+ index=None,
+ )
+ g = df.groupby(["A", "B"])
+
+ expected = DataFrame(
+ [(i + 12 if i < n_rows - 12 else 0) for i in range(n_rows)],
+ dtype=float,
+ columns=["Z"],
+ index=None,
+ )
+ result = g.shift(-1, fill_value=0)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_group_shift_lose_timezone():
+ # GH 30134
+ now_dt = Timestamp.utcnow().as_unit("ns")
+ df = DataFrame({"a": [1, 1], "date": now_dt})
+ result = df.groupby("a").shift(0).iloc[0]
+ expected = Series({"date": now_dt}, name=result.name)
+ tm.assert_series_equal(result, expected)
+
+
+def test_group_diff_real_series(any_real_numpy_dtype):
+ df = DataFrame(
+ {"a": [1, 2, 3, 3, 2], "b": [1, 2, 3, 4, 5]},
+ dtype=any_real_numpy_dtype,
+ )
+ result = df.groupby("a")["b"].diff()
+ exp_dtype = "float"
+ if any_real_numpy_dtype in ["int8", "int16", "float32"]:
+ exp_dtype = "float32"
+ expected = Series([np.nan, np.nan, np.nan, 1.0, 3.0], dtype=exp_dtype, name="b")
+ tm.assert_series_equal(result, expected)
+
+
+def test_group_diff_real_frame(any_real_numpy_dtype):
+ df = DataFrame(
+ {
+ "a": [1, 2, 3, 3, 2],
+ "b": [1, 2, 3, 4, 5],
+ "c": [1, 2, 3, 4, 6],
+ },
+ dtype=any_real_numpy_dtype,
+ )
+ result = df.groupby("a").diff()
+ exp_dtype = "float"
+ if any_real_numpy_dtype in ["int8", "int16", "float32"]:
+ exp_dtype = "float32"
+ expected = DataFrame(
+ {
+ "b": [np.nan, np.nan, np.nan, 1.0, 3.0],
+ "c": [np.nan, np.nan, np.nan, 1.0, 4.0],
+ },
+ dtype=exp_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ [
+ Timestamp("2013-01-01"),
+ Timestamp("2013-01-02"),
+ Timestamp("2013-01-03"),
+ ],
+ [Timedelta("5 days"), Timedelta("6 days"), Timedelta("7 days")],
+ ],
+)
+def test_group_diff_datetimelike(data):
+ df = DataFrame({"a": [1, 2, 2], "b": data})
+ result = df.groupby("a")["b"].diff()
+ expected = Series([NaT, NaT, Timedelta("1 days")], name="b")
+ tm.assert_series_equal(result, expected)
+
+
+def test_group_diff_bool():
+ df = DataFrame({"a": [1, 2, 3, 3, 2], "b": [True, True, False, False, True]})
+ result = df.groupby("a")["b"].diff()
+ expected = Series([np.nan, np.nan, np.nan, False, False], name="b")
+ tm.assert_series_equal(result, expected)
+
+
+def test_group_diff_object_raises(object_dtype):
+ df = DataFrame(
+ {"a": ["foo", "bar", "bar"], "b": ["baz", "foo", "foo"]}, dtype=object_dtype
+ )
+ with pytest.raises(TypeError, match=r"unsupported operand type\(s\) for -"):
+ df.groupby("a")["b"].diff()
+
+
+def test_empty_shift_with_fill():
+ # GH 41264, single-index check
+ df = DataFrame(columns=["a", "b", "c"])
+ shifted = df.groupby(["a"]).shift(1)
+ shifted_with_fill = df.groupby(["a"]).shift(1, fill_value=0)
+ tm.assert_frame_equal(shifted, shifted_with_fill)
+ tm.assert_index_equal(shifted.index, shifted_with_fill.index)
+
+
+def test_multindex_empty_shift_with_fill():
+ # GH 41264, multi-index check
+ df = DataFrame(columns=["a", "b", "c"])
+ shifted = df.groupby(["a", "b"]).shift(1)
+ shifted_with_fill = df.groupby(["a", "b"]).shift(1, fill_value=0)
+ tm.assert_frame_equal(shifted, shifted_with_fill)
+ tm.assert_index_equal(shifted.index, shifted_with_fill.index)
+
+
+def test_shift_periods_freq():
+ # GH 54093
+ data = {"a": [1, 2, 3, 4, 5, 6], "b": [0, 0, 0, 1, 1, 1]}
+ df = DataFrame(data, index=date_range(start="20100101", periods=6))
+ result = df.groupby(df.index).shift(periods=-2, freq="D")
+ expected = DataFrame(data, index=date_range(start="2009-12-30", periods=6))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_shift_deprecate_freq_and_fill_value():
+ # GH 53832
+ data = {"a": [1, 2, 3, 4, 5, 6], "b": [0, 0, 0, 1, 1, 1]}
+ df = DataFrame(data, index=date_range(start="20100101", periods=6))
+ msg = (
+ "Passing a 'freq' together with a 'fill_value' silently ignores the fill_value"
+ )
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.groupby(df.index).shift(periods=-2, freq="D", fill_value="1")
+
+
+def test_shift_disallow_suffix_if_periods_is_int():
+ # GH#44424
+ data = {"a": [1, 2, 3, 4, 5, 6], "b": [0, 0, 0, 1, 1, 1]}
+ df = DataFrame(data)
+ msg = "Cannot specify `suffix` if `periods` is an int."
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("b").shift(1, suffix="fails")
+
+
+def test_group_shift_with_multiple_periods():
+ # GH#44424
+ df = DataFrame({"a": [1, 2, 3, 3, 2], "b": [True, True, False, False, True]})
+
+ shifted_df = df.groupby("b")[["a"]].shift([0, 1])
+ expected_df = DataFrame(
+ {"a_0": [1, 2, 3, 3, 2], "a_1": [np.nan, 1.0, np.nan, 3.0, 2.0]}
+ )
+ tm.assert_frame_equal(shifted_df, expected_df)
+
+ # series
+ shifted_series = df.groupby("b")["a"].shift([0, 1])
+ tm.assert_frame_equal(shifted_series, expected_df)
+
+
+def test_group_shift_with_multiple_periods_and_freq():
+ # GH#44424
+ df = DataFrame(
+ {"a": [1, 2, 3, 4, 5], "b": [True, True, False, False, True]},
+ index=date_range("1/1/2000", periods=5, freq="H"),
+ )
+ shifted_df = df.groupby("b")[["a"]].shift(
+ [0, 1],
+ freq="H",
+ )
+ expected_df = DataFrame(
+ {
+ "a_0": [1.0, 2.0, 3.0, 4.0, 5.0, np.nan],
+ "a_1": [
+ np.nan,
+ 1.0,
+ 2.0,
+ 3.0,
+ 4.0,
+ 5.0,
+ ],
+ },
+ index=date_range("1/1/2000", periods=6, freq="H"),
+ )
+ tm.assert_frame_equal(shifted_df, expected_df)
+
+
+def test_group_shift_with_multiple_periods_and_fill_value():
+ # GH#44424
+ df = DataFrame(
+ {"a": [1, 2, 3, 4, 5], "b": [True, True, False, False, True]},
+ )
+ shifted_df = df.groupby("b")[["a"]].shift([0, 1], fill_value=-1)
+ expected_df = DataFrame(
+ {"a_0": [1, 2, 3, 4, 5], "a_1": [-1, 1, -1, 3, 2]},
+ )
+ tm.assert_frame_equal(shifted_df, expected_df)
+
+
+def test_group_shift_with_multiple_periods_and_both_fill_and_freq_deprecated():
+ # GH#44424
+ df = DataFrame(
+ {"a": [1, 2, 3, 4, 5], "b": [True, True, False, False, True]},
+ index=date_range("1/1/2000", periods=5, freq="H"),
+ )
+ msg = (
+ "Passing a 'freq' together with a 'fill_value' silently ignores the "
+ "fill_value"
+ )
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.groupby("b")[["a"]].shift([1, 2], fill_value=1, freq="H")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_subclass.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_subclass.py
new file mode 100644
index 0000000000000000000000000000000000000000..678211ea4a053781746a2430756ed46814b15cfe
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_subclass.py
@@ -0,0 +1,109 @@
+from datetime import datetime
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
+import pandas._testing as tm
+from pandas.tests.groupby import get_groupby_method_args
+
+pytestmark = pytest.mark.filterwarnings(
+ "ignore:Passing a BlockManager|Passing a SingleBlockManager:DeprecationWarning"
+)
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ tm.SubclassedDataFrame({"A": np.arange(0, 10)}),
+ tm.SubclassedSeries(np.arange(0, 10), name="A"),
+ ],
+)
+def test_groupby_preserves_subclass(obj, groupby_func):
+ # GH28330 -- preserve subclass through groupby operations
+
+ if isinstance(obj, Series) and groupby_func in {"corrwith"}:
+ pytest.skip(f"Not applicable for Series and {groupby_func}")
+
+ grouped = obj.groupby(np.arange(0, 10))
+
+ # Groups should preserve subclass type
+ assert isinstance(grouped.get_group(0), type(obj))
+
+ args = get_groupby_method_args(groupby_func, obj)
+
+ result1 = getattr(grouped, groupby_func)(*args)
+ result2 = grouped.agg(groupby_func, *args)
+
+ # Reduction or transformation kernels should preserve type
+ slices = {"ngroup", "cumcount", "size"}
+ if isinstance(obj, DataFrame) and groupby_func in slices:
+ assert isinstance(result1, tm.SubclassedSeries)
+ else:
+ assert isinstance(result1, type(obj))
+
+ # Confirm .agg() groupby operations return same results
+ if isinstance(result1, DataFrame):
+ tm.assert_frame_equal(result1, result2)
+ else:
+ tm.assert_series_equal(result1, result2)
+
+
+def test_groupby_preserves_metadata():
+ # GH-37343
+ custom_df = tm.SubclassedDataFrame({"a": [1, 2, 3], "b": [1, 1, 2], "c": [7, 8, 9]})
+ assert "testattr" in custom_df._metadata
+ custom_df.testattr = "hello"
+ for _, group_df in custom_df.groupby("c"):
+ assert group_df.testattr == "hello"
+
+ # GH-45314
+ def func(group):
+ assert isinstance(group, tm.SubclassedDataFrame)
+ assert hasattr(group, "testattr")
+ return group.testattr
+
+ result = custom_df.groupby("c").apply(func)
+ expected = tm.SubclassedSeries(["hello"] * 3, index=Index([7, 8, 9], name="c"))
+ tm.assert_series_equal(result, expected)
+
+ def func2(group):
+ assert isinstance(group, tm.SubclassedSeries)
+ assert hasattr(group, "testattr")
+ return group.testattr
+
+ custom_series = tm.SubclassedSeries([1, 2, 3])
+ custom_series.testattr = "hello"
+ result = custom_series.groupby(custom_df["c"]).apply(func2)
+ tm.assert_series_equal(result, expected)
+ result = custom_series.groupby(custom_df["c"]).agg(func2)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("obj", [DataFrame, tm.SubclassedDataFrame])
+def test_groupby_resample_preserves_subclass(obj):
+ # GH28330 -- preserve subclass through groupby.resample()
+
+ df = obj(
+ {
+ "Buyer": "Carl Carl Carl Carl Joe Carl".split(),
+ "Quantity": [18, 3, 5, 1, 9, 3],
+ "Date": [
+ datetime(2013, 9, 1, 13, 0),
+ datetime(2013, 9, 1, 13, 5),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 3, 10, 0),
+ datetime(2013, 12, 2, 12, 0),
+ datetime(2013, 9, 2, 14, 0),
+ ],
+ }
+ )
+ df = df.set_index("Date")
+
+ # Confirm groupby.resample() preserves dataframe type
+ result = df.groupby("Buyer").resample("5D").sum()
+ assert isinstance(result, obj)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_grouping.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_grouping.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0793ada679c21a20a49ef584c1ba7dc53a447bb
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_grouping.py
@@ -0,0 +1,1169 @@
+"""
+test where we are determining what we are grouping, or getting groups
+"""
+from datetime import (
+ date,
+ timedelta,
+)
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ CategoricalIndex,
+ DataFrame,
+ Grouper,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.core.groupby.grouper import Grouping
+
+# selection
+# --------------------------------
+
+
+class TestSelection:
+ def test_select_bad_cols(self):
+ df = DataFrame([[1, 2]], columns=["A", "B"])
+ g = df.groupby("A")
+ with pytest.raises(KeyError, match="\"Columns not found: 'C'\""):
+ g[["C"]]
+
+ with pytest.raises(KeyError, match="^[^A]+$"):
+ # A should not be referenced as a bad column...
+ # will have to rethink regex if you change message!
+ g[["A", "C"]]
+
+ def test_groupby_duplicated_column_errormsg(self):
+ # GH7511
+ df = DataFrame(
+ columns=["A", "B", "A", "C"], data=[range(4), range(2, 6), range(0, 8, 2)]
+ )
+
+ msg = "Grouper for 'A' not 1-dimensional"
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("A")
+ with pytest.raises(ValueError, match=msg):
+ df.groupby(["A", "B"])
+
+ grouped = df.groupby("B")
+ c = grouped.count()
+ assert c.columns.nlevels == 1
+ assert c.columns.size == 3
+
+ def test_column_select_via_attr(self, df):
+ result = df.groupby("A").C.sum()
+ expected = df.groupby("A")["C"].sum()
+ tm.assert_series_equal(result, expected)
+
+ df["mean"] = 1.5
+ result = df.groupby("A").mean(numeric_only=True)
+ expected = df.groupby("A")[["C", "D", "mean"]].agg("mean")
+ tm.assert_frame_equal(result, expected)
+
+ def test_getitem_list_of_columns(self):
+ df = DataFrame(
+ {
+ "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
+ "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
+ "C": np.random.default_rng(2).standard_normal(8),
+ "D": np.random.default_rng(2).standard_normal(8),
+ "E": np.random.default_rng(2).standard_normal(8),
+ }
+ )
+
+ result = df.groupby("A")[["C", "D"]].mean()
+ result2 = df.groupby("A")[df.columns[2:4]].mean()
+
+ expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean()
+
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(result2, expected)
+
+ def test_getitem_numeric_column_names(self):
+ # GH #13731
+ df = DataFrame(
+ {
+ 0: list("abcd") * 2,
+ 2: np.random.default_rng(2).standard_normal(8),
+ 4: np.random.default_rng(2).standard_normal(8),
+ 6: np.random.default_rng(2).standard_normal(8),
+ }
+ )
+ result = df.groupby(0)[df.columns[1:3]].mean()
+ result2 = df.groupby(0)[[2, 4]].mean()
+
+ expected = df.loc[:, [0, 2, 4]].groupby(0).mean()
+
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(result2, expected)
+
+ # per GH 23566 enforced deprecation raises a ValueError
+ with pytest.raises(ValueError, match="Cannot subset columns with a tuple"):
+ df.groupby(0)[2, 4].mean()
+
+ def test_getitem_single_tuple_of_columns_raises(self, df):
+ # per GH 23566 enforced deprecation raises a ValueError
+ with pytest.raises(ValueError, match="Cannot subset columns with a tuple"):
+ df.groupby("A")["C", "D"].mean()
+
+ def test_getitem_single_column(self):
+ df = DataFrame(
+ {
+ "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
+ "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
+ "C": np.random.default_rng(2).standard_normal(8),
+ "D": np.random.default_rng(2).standard_normal(8),
+ "E": np.random.default_rng(2).standard_normal(8),
+ }
+ )
+
+ result = df.groupby("A")["C"].mean()
+
+ as_frame = df.loc[:, ["A", "C"]].groupby("A").mean()
+ as_series = as_frame.iloc[:, 0]
+ expected = as_series
+
+ tm.assert_series_equal(result, expected)
+
+ def test_indices_grouped_by_tuple_with_lambda(self):
+ # GH 36158
+ df = DataFrame(
+ {
+ "Tuples": (
+ (x, y)
+ for x in [0, 1]
+ for y in np.random.default_rng(2).integers(3, 5, 5)
+ )
+ }
+ )
+
+ gb = df.groupby("Tuples")
+ gb_lambda = df.groupby(lambda x: df.iloc[x, 0])
+
+ expected = gb.indices
+ result = gb_lambda.indices
+
+ tm.assert_dict_equal(result, expected)
+
+
+# grouping
+# --------------------------------
+
+
+class TestGrouping:
+ @pytest.mark.parametrize(
+ "index",
+ [
+ tm.makeFloatIndex,
+ tm.makeStringIndex,
+ tm.makeIntIndex,
+ tm.makeDateIndex,
+ tm.makePeriodIndex,
+ ],
+ )
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_grouper_index_types(self, index):
+ # related GH5375
+ # groupby misbehaving when using a Floatlike index
+ df = DataFrame(np.arange(10).reshape(5, 2), columns=list("AB"))
+
+ df.index = index(len(df))
+ df.groupby(list("abcde"), group_keys=False).apply(lambda x: x)
+
+ df.index = list(reversed(df.index.tolist()))
+ df.groupby(list("abcde"), group_keys=False).apply(lambda x: x)
+
+ def test_grouper_multilevel_freq(self):
+ # GH 7885
+ # with level and freq specified in a Grouper
+ d0 = date.today() - timedelta(days=14)
+ dates = date_range(d0, date.today())
+ date_index = MultiIndex.from_product([dates, dates], names=["foo", "bar"])
+ df = DataFrame(np.random.default_rng(2).integers(0, 100, 225), index=date_index)
+
+ # Check string level
+ expected = (
+ df.reset_index()
+ .groupby([Grouper(key="foo", freq="W"), Grouper(key="bar", freq="W")])
+ .sum()
+ )
+ # reset index changes columns dtype to object
+ expected.columns = Index([0], dtype="int64")
+
+ result = df.groupby(
+ [Grouper(level="foo", freq="W"), Grouper(level="bar", freq="W")]
+ ).sum()
+ tm.assert_frame_equal(result, expected)
+
+ # Check integer level
+ result = df.groupby(
+ [Grouper(level=0, freq="W"), Grouper(level=1, freq="W")]
+ ).sum()
+ tm.assert_frame_equal(result, expected)
+
+ def test_grouper_creation_bug(self):
+ # GH 8795
+ df = DataFrame({"A": [0, 0, 1, 1, 2, 2], "B": [1, 2, 3, 4, 5, 6]})
+ g = df.groupby("A")
+ expected = g.sum()
+
+ g = df.groupby(Grouper(key="A"))
+ result = g.sum()
+ tm.assert_frame_equal(result, expected)
+
+ msg = "Grouper axis keyword is deprecated and will be removed"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gpr = Grouper(key="A", axis=0)
+ g = df.groupby(gpr)
+ result = g.sum()
+ tm.assert_frame_equal(result, expected)
+
+ result = g.apply(lambda x: x.sum())
+ expected["A"] = [0, 2, 4]
+ expected = expected.loc[:, ["A", "B"]]
+ tm.assert_frame_equal(result, expected)
+
+ # GH14334
+ # Grouper(key=...) may be passed in a list
+ df = DataFrame(
+ {"A": [0, 0, 0, 1, 1, 1], "B": [1, 1, 2, 2, 3, 3], "C": [1, 2, 3, 4, 5, 6]}
+ )
+ # Group by single column
+ expected = df.groupby("A").sum()
+ g = df.groupby([Grouper(key="A")])
+ result = g.sum()
+ tm.assert_frame_equal(result, expected)
+
+ # Group by two columns
+ # using a combination of strings and Grouper objects
+ expected = df.groupby(["A", "B"]).sum()
+
+ # Group with two Grouper objects
+ g = df.groupby([Grouper(key="A"), Grouper(key="B")])
+ result = g.sum()
+ tm.assert_frame_equal(result, expected)
+
+ # Group with a string and a Grouper object
+ g = df.groupby(["A", Grouper(key="B")])
+ result = g.sum()
+ tm.assert_frame_equal(result, expected)
+
+ # Group with a Grouper object and a string
+ g = df.groupby([Grouper(key="A"), "B"])
+ result = g.sum()
+ tm.assert_frame_equal(result, expected)
+
+ # GH8866
+ s = Series(
+ np.arange(8, dtype="int64"),
+ index=MultiIndex.from_product(
+ [list("ab"), range(2), date_range("20130101", periods=2)],
+ names=["one", "two", "three"],
+ ),
+ )
+ result = s.groupby(Grouper(level="three", freq="M")).sum()
+ expected = Series(
+ [28],
+ index=pd.DatetimeIndex([Timestamp("2013-01-31")], freq="M", name="three"),
+ )
+ tm.assert_series_equal(result, expected)
+
+ # just specifying a level breaks
+ result = s.groupby(Grouper(level="one")).sum()
+ expected = s.groupby(level="one").sum()
+ tm.assert_series_equal(result, expected)
+
+ def test_grouper_column_and_index(self):
+ # GH 14327
+
+ # Grouping a multi-index frame by a column and an index level should
+ # be equivalent to resetting the index and grouping by two columns
+ idx = MultiIndex.from_tuples(
+ [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)]
+ )
+ idx.names = ["outer", "inner"]
+ df_multi = DataFrame(
+ {"A": np.arange(6), "B": ["one", "one", "two", "two", "one", "one"]},
+ index=idx,
+ )
+ result = df_multi.groupby(["B", Grouper(level="inner")]).mean(numeric_only=True)
+ expected = (
+ df_multi.reset_index().groupby(["B", "inner"]).mean(numeric_only=True)
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # Test the reverse grouping order
+ result = df_multi.groupby([Grouper(level="inner"), "B"]).mean(numeric_only=True)
+ expected = (
+ df_multi.reset_index().groupby(["inner", "B"]).mean(numeric_only=True)
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # Grouping a single-index frame by a column and the index should
+ # be equivalent to resetting the index and grouping by two columns
+ df_single = df_multi.reset_index("outer")
+ result = df_single.groupby(["B", Grouper(level="inner")]).mean(
+ numeric_only=True
+ )
+ expected = (
+ df_single.reset_index().groupby(["B", "inner"]).mean(numeric_only=True)
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # Test the reverse grouping order
+ result = df_single.groupby([Grouper(level="inner"), "B"]).mean(
+ numeric_only=True
+ )
+ expected = (
+ df_single.reset_index().groupby(["inner", "B"]).mean(numeric_only=True)
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_groupby_levels_and_columns(self):
+ # GH9344, GH9049
+ idx_names = ["x", "y"]
+ idx = MultiIndex.from_tuples([(1, 1), (1, 2), (3, 4), (5, 6)], names=idx_names)
+ df = DataFrame(np.arange(12).reshape(-1, 3), index=idx)
+
+ by_levels = df.groupby(level=idx_names).mean()
+ # reset_index changes columns dtype to object
+ by_columns = df.reset_index().groupby(idx_names).mean()
+
+ # without casting, by_columns.columns is object-dtype
+ by_columns.columns = by_columns.columns.astype(np.int64)
+ tm.assert_frame_equal(by_levels, by_columns)
+
+ def test_groupby_categorical_index_and_columns(self, observed):
+ # GH18432, adapted for GH25871
+ columns = ["A", "B", "A", "B"]
+ categories = ["B", "A"]
+ data = np.array(
+ [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]], int
+ )
+ cat_columns = CategoricalIndex(columns, categories=categories, ordered=True)
+ df = DataFrame(data=data, columns=cat_columns)
+ depr_msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ result = df.groupby(axis=1, level=0, observed=observed).sum()
+ expected_data = np.array([[4, 2], [4, 2], [4, 2], [4, 2], [4, 2]], int)
+ expected_columns = CategoricalIndex(
+ categories, categories=categories, ordered=True
+ )
+ expected = DataFrame(data=expected_data, columns=expected_columns)
+ tm.assert_frame_equal(result, expected)
+
+ # test transposed version
+ df = DataFrame(data.T, index=cat_columns)
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.groupby(axis=0, level=0, observed=observed).sum()
+ expected = DataFrame(data=expected_data.T, index=expected_columns)
+ tm.assert_frame_equal(result, expected)
+
+ def test_grouper_getting_correct_binner(self):
+ # GH 10063
+ # using a non-time-based grouper and a time-based grouper
+ # and specifying levels
+ df = DataFrame(
+ {"A": 1},
+ index=MultiIndex.from_product(
+ [list("ab"), date_range("20130101", periods=80)], names=["one", "two"]
+ ),
+ )
+ result = df.groupby(
+ [Grouper(level="one"), Grouper(level="two", freq="M")]
+ ).sum()
+ expected = DataFrame(
+ {"A": [31, 28, 21, 31, 28, 21]},
+ index=MultiIndex.from_product(
+ [list("ab"), date_range("20130101", freq="M", periods=3)],
+ names=["one", "two"],
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_grouper_iter(self, df):
+ assert sorted(df.groupby("A").grouper) == ["bar", "foo"]
+
+ def test_empty_groups(self, df):
+ # see gh-1048
+ with pytest.raises(ValueError, match="No group keys passed!"):
+ df.groupby([])
+
+ def test_groupby_grouper(self, df):
+ grouped = df.groupby("A")
+
+ result = df.groupby(grouped.grouper).mean(numeric_only=True)
+ expected = grouped.mean(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ def test_groupby_dict_mapping(self):
+ # GH #679
+ s = Series({"T1": 5})
+ result = s.groupby({"T1": "T2"}).agg("sum")
+ expected = s.groupby(["T2"]).agg("sum")
+ tm.assert_series_equal(result, expected)
+
+ s = Series([1.0, 2.0, 3.0, 4.0], index=list("abcd"))
+ mapping = {"a": 0, "b": 0, "c": 1, "d": 1}
+
+ result = s.groupby(mapping).mean()
+ result2 = s.groupby(mapping).agg("mean")
+ exp_key = np.array([0, 0, 1, 1], dtype=np.int64)
+ expected = s.groupby(exp_key).mean()
+ expected2 = s.groupby(exp_key).mean()
+ tm.assert_series_equal(result, expected)
+ tm.assert_series_equal(result, result2)
+ tm.assert_series_equal(result, expected2)
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ [0, 1, 2, 3],
+ ["a", "b", "c", "d"],
+ [Timestamp(2021, 7, 28 + i) for i in range(4)],
+ ],
+ )
+ def test_groupby_series_named_with_tuple(self, frame_or_series, index):
+ # GH 42731
+ obj = frame_or_series([1, 2, 3, 4], index=index)
+ groups = Series([1, 0, 1, 0], index=index, name=("a", "a"))
+ result = obj.groupby(groups).last()
+ expected = frame_or_series([4, 3])
+ expected.index.name = ("a", "a")
+ tm.assert_equal(result, expected)
+
+ def test_groupby_grouper_f_sanity_checked(self):
+ dates = date_range("01-Jan-2013", periods=12, freq="MS")
+ ts = Series(np.random.default_rng(2).standard_normal(12), index=dates)
+
+ # GH51979
+ # simple check that the passed function doesn't operates on the whole index
+ msg = "'Timestamp' object is not subscriptable"
+ with pytest.raises(TypeError, match=msg):
+ ts.groupby(lambda key: key[0:6])
+
+ result = ts.groupby(lambda x: x).sum()
+ expected = ts.groupby(ts.index).sum()
+ expected.index.freq = None
+ tm.assert_series_equal(result, expected)
+
+ def test_groupby_with_datetime_key(self):
+ # GH 51158
+ df = DataFrame(
+ {
+ "id": ["a", "b"] * 3,
+ "b": date_range("2000-01-01", "2000-01-03", freq="9H"),
+ }
+ )
+ grouper = Grouper(key="b", freq="D")
+ gb = df.groupby([grouper, "id"])
+
+ # test number of groups
+ expected = {
+ (Timestamp("2000-01-01"), "a"): [0, 2],
+ (Timestamp("2000-01-01"), "b"): [1],
+ (Timestamp("2000-01-02"), "a"): [4],
+ (Timestamp("2000-01-02"), "b"): [3, 5],
+ }
+ tm.assert_dict_equal(gb.groups, expected)
+
+ # test number of group keys
+ assert len(gb.groups.keys()) == 4
+
+ def test_grouping_error_on_multidim_input(self, df):
+ msg = "Grouper for '' not 1-dimensional"
+ with pytest.raises(ValueError, match=msg):
+ Grouping(df.index, df[["A", "A"]])
+
+ def test_multiindex_passthru(self):
+ # GH 7997
+ # regression from 0.14.1
+ df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ df.columns = MultiIndex.from_tuples([(0, 1), (1, 1), (2, 1)])
+
+ depr_msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ gb = df.groupby(axis=1, level=[0, 1])
+ result = gb.first()
+ tm.assert_frame_equal(result, df)
+
+ def test_multiindex_negative_level(self, mframe):
+ # GH 13901
+ result = mframe.groupby(level=-1).sum()
+ expected = mframe.groupby(level="second").sum()
+ tm.assert_frame_equal(result, expected)
+
+ result = mframe.groupby(level=-2).sum()
+ expected = mframe.groupby(level="first").sum()
+ tm.assert_frame_equal(result, expected)
+
+ result = mframe.groupby(level=[-2, -1]).sum()
+ expected = mframe.sort_index()
+ tm.assert_frame_equal(result, expected)
+
+ result = mframe.groupby(level=[-1, "first"]).sum()
+ expected = mframe.groupby(level=["second", "first"]).sum()
+ tm.assert_frame_equal(result, expected)
+
+ def test_multifunc_select_col_integer_cols(self, df):
+ df.columns = np.arange(len(df.columns))
+
+ # it works!
+ msg = "Passing a dictionary to SeriesGroupBy.agg is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.groupby(1, as_index=False)[2].agg({"Q": np.mean})
+
+ def test_multiindex_columns_empty_level(self):
+ lst = [["count", "values"], ["to filter", ""]]
+ midx = MultiIndex.from_tuples(lst)
+
+ df = DataFrame([[1, "A"]], columns=midx)
+
+ grouped = df.groupby("to filter").groups
+ assert grouped["A"] == [0]
+
+ grouped = df.groupby([("to filter", "")]).groups
+ assert grouped["A"] == [0]
+
+ df = DataFrame([[1, "A"], [2, "B"]], columns=midx)
+
+ expected = df.groupby("to filter").groups
+ result = df.groupby([("to filter", "")]).groups
+ assert result == expected
+
+ df = DataFrame([[1, "A"], [2, "A"]], columns=midx)
+
+ expected = df.groupby("to filter").groups
+ result = df.groupby([("to filter", "")]).groups
+ tm.assert_dict_equal(result, expected)
+
+ def test_groupby_multiindex_tuple(self):
+ # GH 17979
+ df = DataFrame(
+ [[1, 2, 3, 4], [3, 4, 5, 6], [1, 4, 2, 3]],
+ columns=MultiIndex.from_arrays([["a", "b", "b", "c"], [1, 1, 2, 2]]),
+ )
+ expected = df.groupby([("b", 1)]).groups
+ result = df.groupby(("b", 1)).groups
+ tm.assert_dict_equal(expected, result)
+
+ df2 = DataFrame(
+ df.values,
+ columns=MultiIndex.from_arrays(
+ [["a", "b", "b", "c"], ["d", "d", "e", "e"]]
+ ),
+ )
+ expected = df2.groupby([("b", "d")]).groups
+ result = df.groupby(("b", 1)).groups
+ tm.assert_dict_equal(expected, result)
+
+ df3 = DataFrame(df.values, columns=[("a", "d"), ("b", "d"), ("b", "e"), "c"])
+ expected = df3.groupby([("b", "d")]).groups
+ result = df.groupby(("b", 1)).groups
+ tm.assert_dict_equal(expected, result)
+
+ def test_groupby_multiindex_partial_indexing_equivalence(self):
+ # GH 17977
+ df = DataFrame(
+ [[1, 2, 3, 4], [3, 4, 5, 6], [1, 4, 2, 3]],
+ columns=MultiIndex.from_arrays([["a", "b", "b", "c"], [1, 1, 2, 2]]),
+ )
+
+ expected_mean = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].mean()
+ result_mean = df.groupby([("a", 1)])["b"].mean()
+ tm.assert_frame_equal(expected_mean, result_mean)
+
+ expected_sum = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].sum()
+ result_sum = df.groupby([("a", 1)])["b"].sum()
+ tm.assert_frame_equal(expected_sum, result_sum)
+
+ expected_count = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].count()
+ result_count = df.groupby([("a", 1)])["b"].count()
+ tm.assert_frame_equal(expected_count, result_count)
+
+ expected_min = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].min()
+ result_min = df.groupby([("a", 1)])["b"].min()
+ tm.assert_frame_equal(expected_min, result_min)
+
+ expected_max = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].max()
+ result_max = df.groupby([("a", 1)])["b"].max()
+ tm.assert_frame_equal(expected_max, result_max)
+
+ expected_groups = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].groups
+ result_groups = df.groupby([("a", 1)])["b"].groups
+ tm.assert_dict_equal(expected_groups, result_groups)
+
+ @pytest.mark.parametrize("sort", [True, False])
+ def test_groupby_level(self, sort, mframe, df):
+ # GH 17537
+ frame = mframe
+ deleveled = frame.reset_index()
+
+ result0 = frame.groupby(level=0, sort=sort).sum()
+ result1 = frame.groupby(level=1, sort=sort).sum()
+
+ expected0 = frame.groupby(deleveled["first"].values, sort=sort).sum()
+ expected1 = frame.groupby(deleveled["second"].values, sort=sort).sum()
+
+ expected0.index.name = "first"
+ expected1.index.name = "second"
+
+ assert result0.index.name == "first"
+ assert result1.index.name == "second"
+
+ tm.assert_frame_equal(result0, expected0)
+ tm.assert_frame_equal(result1, expected1)
+ assert result0.index.name == frame.index.names[0]
+ assert result1.index.name == frame.index.names[1]
+
+ # groupby level name
+ result0 = frame.groupby(level="first", sort=sort).sum()
+ result1 = frame.groupby(level="second", sort=sort).sum()
+ tm.assert_frame_equal(result0, expected0)
+ tm.assert_frame_equal(result1, expected1)
+
+ # axis=1
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result0 = frame.T.groupby(level=0, axis=1, sort=sort).sum()
+ result1 = frame.T.groupby(level=1, axis=1, sort=sort).sum()
+ tm.assert_frame_equal(result0, expected0.T)
+ tm.assert_frame_equal(result1, expected1.T)
+
+ # raise exception for non-MultiIndex
+ msg = "level > 0 or level < -1 only valid with MultiIndex"
+ with pytest.raises(ValueError, match=msg):
+ df.groupby(level=1)
+
+ def test_groupby_level_index_names(self, axis):
+ # GH4014 this used to raise ValueError since 'exp'>1 (in py2)
+ df = DataFrame({"exp": ["A"] * 3 + ["B"] * 3, "var1": range(6)}).set_index(
+ "exp"
+ )
+ if axis in (1, "columns"):
+ df = df.T
+ depr_msg = "DataFrame.groupby with axis=1 is deprecated"
+ else:
+ depr_msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ df.groupby(level="exp", axis=axis)
+ msg = f"level name foo is not the name of the {df._get_axis_name(axis)}"
+ with pytest.raises(ValueError, match=msg):
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ df.groupby(level="foo", axis=axis)
+
+ @pytest.mark.parametrize("sort", [True, False])
+ def test_groupby_level_with_nas(self, sort):
+ # GH 17537
+ index = MultiIndex(
+ levels=[[1, 0], [0, 1, 2, 3]],
+ codes=[[1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 2, 3, 0, 1, 2, 3]],
+ )
+
+ # factorizing doesn't confuse things
+ s = Series(np.arange(8.0), index=index)
+ result = s.groupby(level=0, sort=sort).sum()
+ expected = Series([6.0, 22.0], index=[0, 1])
+ tm.assert_series_equal(result, expected)
+
+ index = MultiIndex(
+ levels=[[1, 0], [0, 1, 2, 3]],
+ codes=[[1, 1, 1, 1, -1, 0, 0, 0], [0, 1, 2, 3, 0, 1, 2, 3]],
+ )
+
+ # factorizing doesn't confuse things
+ s = Series(np.arange(8.0), index=index)
+ result = s.groupby(level=0, sort=sort).sum()
+ expected = Series([6.0, 18.0], index=[0.0, 1.0])
+ tm.assert_series_equal(result, expected)
+
+ def test_groupby_args(self, mframe):
+ # PR8618 and issue 8015
+ frame = mframe
+
+ msg = "You have to supply one of 'by' and 'level'"
+ with pytest.raises(TypeError, match=msg):
+ frame.groupby()
+
+ msg = "You have to supply one of 'by' and 'level'"
+ with pytest.raises(TypeError, match=msg):
+ frame.groupby(by=None, level=None)
+
+ @pytest.mark.parametrize(
+ "sort,labels",
+ [
+ [True, [2, 2, 2, 0, 0, 1, 1, 3, 3, 3]],
+ [False, [0, 0, 0, 1, 1, 2, 2, 3, 3, 3]],
+ ],
+ )
+ def test_level_preserve_order(self, sort, labels, mframe):
+ # GH 17537
+ grouped = mframe.groupby(level=0, sort=sort)
+ exp_labels = np.array(labels, np.intp)
+ tm.assert_almost_equal(grouped.grouper.codes[0], exp_labels)
+
+ def test_grouping_labels(self, mframe):
+ grouped = mframe.groupby(mframe.index.get_level_values(0))
+ exp_labels = np.array([2, 2, 2, 0, 0, 1, 1, 3, 3, 3], dtype=np.intp)
+ tm.assert_almost_equal(grouped.grouper.codes[0], exp_labels)
+
+ def test_list_grouper_with_nat(self):
+ # GH 14715
+ df = DataFrame({"date": date_range("1/1/2011", periods=365, freq="D")})
+ df.iloc[-1] = pd.NaT
+ grouper = Grouper(key="date", freq="AS")
+
+ # Grouper in a list grouping
+ result = df.groupby([grouper])
+ expected = {Timestamp("2011-01-01"): Index(list(range(364)))}
+ tm.assert_dict_equal(result.groups, expected)
+
+ # Test case without a list
+ result = df.groupby(grouper)
+ expected = {Timestamp("2011-01-01"): 365}
+ tm.assert_dict_equal(result.groups, expected)
+
+ @pytest.mark.parametrize(
+ "func,expected",
+ [
+ (
+ "transform",
+ Series(name=2, dtype=np.float64),
+ ),
+ (
+ "agg",
+ Series(
+ name=2, dtype=np.float64, index=Index([], dtype=np.float64, name=1)
+ ),
+ ),
+ (
+ "apply",
+ Series(
+ name=2, dtype=np.float64, index=Index([], dtype=np.float64, name=1)
+ ),
+ ),
+ ],
+ )
+ def test_evaluate_with_empty_groups(self, func, expected):
+ # 26208
+ # test transform'ing empty groups
+ # (not testing other agg fns, because they return
+ # different index objects.
+ df = DataFrame({1: [], 2: []})
+ g = df.groupby(1, group_keys=False)
+ result = getattr(g[2], func)(lambda x: x)
+ tm.assert_series_equal(result, expected)
+
+ def test_groupby_empty(self):
+ # https://github.com/pandas-dev/pandas/issues/27190
+ s = Series([], name="name", dtype="float64")
+ gr = s.groupby([])
+
+ result = gr.mean()
+ expected = s.set_axis(Index([], dtype=np.intp))
+ tm.assert_series_equal(result, expected)
+
+ # check group properties
+ assert len(gr.grouper.groupings) == 1
+ tm.assert_numpy_array_equal(
+ gr.grouper.group_info[0], np.array([], dtype=np.dtype(np.intp))
+ )
+
+ tm.assert_numpy_array_equal(
+ gr.grouper.group_info[1], np.array([], dtype=np.dtype(np.intp))
+ )
+
+ assert gr.grouper.group_info[2] == 0
+
+ # check name
+ assert s.groupby(s).grouper.names == ["name"]
+
+ def test_groupby_level_index_value_all_na(self):
+ # issue 20519
+ df = DataFrame(
+ [["x", np.nan, 10], [None, np.nan, 20]], columns=["A", "B", "C"]
+ ).set_index(["A", "B"])
+ result = df.groupby(level=["A", "B"]).sum()
+ expected = DataFrame(
+ data=[],
+ index=MultiIndex(
+ levels=[Index(["x"], dtype="object"), Index([], dtype="float64")],
+ codes=[[], []],
+ names=["A", "B"],
+ ),
+ columns=["C"],
+ dtype="int64",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_groupby_multiindex_level_empty(self):
+ # https://github.com/pandas-dev/pandas/issues/31670
+ df = DataFrame(
+ [[123, "a", 1.0], [123, "b", 2.0]], columns=["id", "category", "value"]
+ )
+ df = df.set_index(["id", "category"])
+ empty = df[df.value < 0]
+ result = empty.groupby("id").sum()
+ expected = DataFrame(
+ dtype="float64",
+ columns=["value"],
+ index=Index([], dtype=np.int64, name="id"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+# get_group
+# --------------------------------
+
+
+class TestGetGroup:
+ def test_get_group(self):
+ # GH 5267
+ # be datelike friendly
+ df = DataFrame(
+ {
+ "DATE": pd.to_datetime(
+ [
+ "10-Oct-2013",
+ "10-Oct-2013",
+ "10-Oct-2013",
+ "11-Oct-2013",
+ "11-Oct-2013",
+ "11-Oct-2013",
+ ]
+ ),
+ "label": ["foo", "foo", "bar", "foo", "foo", "bar"],
+ "VAL": [1, 2, 3, 4, 5, 6],
+ }
+ )
+
+ g = df.groupby("DATE")
+ key = next(iter(g.groups))
+ result1 = g.get_group(key)
+ result2 = g.get_group(Timestamp(key).to_pydatetime())
+ result3 = g.get_group(str(Timestamp(key)))
+ tm.assert_frame_equal(result1, result2)
+ tm.assert_frame_equal(result1, result3)
+
+ g = df.groupby(["DATE", "label"])
+
+ key = next(iter(g.groups))
+ result1 = g.get_group(key)
+ result2 = g.get_group((Timestamp(key[0]).to_pydatetime(), key[1]))
+ result3 = g.get_group((str(Timestamp(key[0])), key[1]))
+ tm.assert_frame_equal(result1, result2)
+ tm.assert_frame_equal(result1, result3)
+
+ # must pass a same-length tuple with multiple keys
+ msg = "must supply a tuple to get_group with multiple grouping keys"
+ with pytest.raises(ValueError, match=msg):
+ g.get_group("foo")
+ with pytest.raises(ValueError, match=msg):
+ g.get_group("foo")
+ msg = "must supply a same-length tuple to get_group with multiple grouping keys"
+ with pytest.raises(ValueError, match=msg):
+ g.get_group(("foo", "bar", "baz"))
+
+ def test_get_group_empty_bins(self, observed):
+ d = DataFrame([3, 1, 7, 6])
+ bins = [0, 5, 10, 15]
+ g = d.groupby(pd.cut(d[0], bins), observed=observed)
+
+ # TODO: should prob allow a str of Interval work as well
+ # IOW '(0, 5]'
+ result = g.get_group(pd.Interval(0, 5))
+ expected = DataFrame([3, 1], index=[0, 1])
+ tm.assert_frame_equal(result, expected)
+
+ msg = r"Interval\(10, 15, closed='right'\)"
+ with pytest.raises(KeyError, match=msg):
+ g.get_group(pd.Interval(10, 15))
+
+ def test_get_group_grouped_by_tuple(self):
+ # GH 8121
+ df = DataFrame([[(1,), (1, 2), (1,), (1, 2)]], index=["ids"]).T
+ gr = df.groupby("ids")
+ expected = DataFrame({"ids": [(1,), (1,)]}, index=[0, 2])
+ result = gr.get_group((1,))
+ tm.assert_frame_equal(result, expected)
+
+ dt = pd.to_datetime(["2010-01-01", "2010-01-02", "2010-01-01", "2010-01-02"])
+ df = DataFrame({"ids": [(x,) for x in dt]})
+ gr = df.groupby("ids")
+ result = gr.get_group(("2010-01-01",))
+ expected = DataFrame({"ids": [(dt[0],), (dt[0],)]}, index=[0, 2])
+ tm.assert_frame_equal(result, expected)
+
+ def test_get_group_grouped_by_tuple_with_lambda(self):
+ # GH 36158
+ df = DataFrame(
+ {
+ "Tuples": (
+ (x, y)
+ for x in [0, 1]
+ for y in np.random.default_rng(2).integers(3, 5, 5)
+ )
+ }
+ )
+
+ gb = df.groupby("Tuples")
+ gb_lambda = df.groupby(lambda x: df.iloc[x, 0])
+
+ expected = gb.get_group(next(iter(gb.groups.keys())))
+ result = gb_lambda.get_group(next(iter(gb_lambda.groups.keys())))
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_groupby_with_empty(self):
+ index = pd.DatetimeIndex(())
+ data = ()
+ series = Series(data, index, dtype=object)
+ grouper = Grouper(freq="D")
+ grouped = series.groupby(grouper)
+ assert next(iter(grouped), None) is None
+
+ def test_groupby_with_single_column(self):
+ df = DataFrame({"a": list("abssbab")})
+ tm.assert_frame_equal(df.groupby("a").get_group("a"), df.iloc[[0, 5]])
+ # GH 13530
+ exp = DataFrame(index=Index(["a", "b", "s"], name="a"), columns=[])
+ tm.assert_frame_equal(df.groupby("a").count(), exp)
+ tm.assert_frame_equal(df.groupby("a").sum(), exp)
+
+ exp = df.iloc[[3, 4, 5]]
+ tm.assert_frame_equal(df.groupby("a").nth(1), exp)
+
+ def test_gb_key_len_equal_axis_len(self):
+ # GH16843
+ # test ensures that index and column keys are recognized correctly
+ # when number of keys equals axis length of groupby
+ df = DataFrame(
+ [["foo", "bar", "B", 1], ["foo", "bar", "B", 2], ["foo", "baz", "C", 3]],
+ columns=["first", "second", "third", "one"],
+ )
+ df = df.set_index(["first", "second"])
+ df = df.groupby(["first", "second", "third"]).size()
+ assert df.loc[("foo", "bar", "B")] == 2
+ assert df.loc[("foo", "baz", "C")] == 1
+
+
+# groups & iteration
+# --------------------------------
+
+
+class TestIteration:
+ def test_groups(self, df):
+ grouped = df.groupby(["A"])
+ groups = grouped.groups
+ assert groups is grouped.groups # caching works
+
+ for k, v in grouped.groups.items():
+ assert (df.loc[v]["A"] == k).all()
+
+ grouped = df.groupby(["A", "B"])
+ groups = grouped.groups
+ assert groups is grouped.groups # caching works
+
+ for k, v in grouped.groups.items():
+ assert (df.loc[v]["A"] == k[0]).all()
+ assert (df.loc[v]["B"] == k[1]).all()
+
+ def test_grouping_is_iterable(self, tsframe):
+ # this code path isn't used anywhere else
+ # not sure it's useful
+ grouped = tsframe.groupby([lambda x: x.weekday(), lambda x: x.year])
+
+ # test it works
+ for g in grouped.grouper.groupings[0]:
+ pass
+
+ def test_multi_iter(self):
+ s = Series(np.arange(6))
+ k1 = np.array(["a", "a", "a", "b", "b", "b"])
+ k2 = np.array(["1", "2", "1", "2", "1", "2"])
+
+ grouped = s.groupby([k1, k2])
+
+ iterated = list(grouped)
+ expected = [
+ ("a", "1", s[[0, 2]]),
+ ("a", "2", s[[1]]),
+ ("b", "1", s[[4]]),
+ ("b", "2", s[[3, 5]]),
+ ]
+ for i, ((one, two), three) in enumerate(iterated):
+ e1, e2, e3 = expected[i]
+ assert e1 == one
+ assert e2 == two
+ tm.assert_series_equal(three, e3)
+
+ def test_multi_iter_frame(self, three_group):
+ k1 = np.array(["b", "b", "b", "a", "a", "a"])
+ k2 = np.array(["1", "2", "1", "2", "1", "2"])
+ df = DataFrame(
+ {
+ "v1": np.random.default_rng(2).standard_normal(6),
+ "v2": np.random.default_rng(2).standard_normal(6),
+ "k1": k1,
+ "k2": k2,
+ },
+ index=["one", "two", "three", "four", "five", "six"],
+ )
+
+ grouped = df.groupby(["k1", "k2"])
+
+ # things get sorted!
+ iterated = list(grouped)
+ idx = df.index
+ expected = [
+ ("a", "1", df.loc[idx[[4]]]),
+ ("a", "2", df.loc[idx[[3, 5]]]),
+ ("b", "1", df.loc[idx[[0, 2]]]),
+ ("b", "2", df.loc[idx[[1]]]),
+ ]
+ for i, ((one, two), three) in enumerate(iterated):
+ e1, e2, e3 = expected[i]
+ assert e1 == one
+ assert e2 == two
+ tm.assert_frame_equal(three, e3)
+
+ # don't iterate through groups with no data
+ df["k1"] = np.array(["b", "b", "b", "a", "a", "a"])
+ df["k2"] = np.array(["1", "1", "1", "2", "2", "2"])
+ grouped = df.groupby(["k1", "k2"])
+ # calling `dict` on a DataFrameGroupBy leads to a TypeError,
+ # we need to use a dictionary comprehension here
+ # pylint: disable-next=unnecessary-comprehension
+ groups = {key: gp for key, gp in grouped} # noqa: C416
+ assert len(groups) == 2
+
+ # axis = 1
+ three_levels = three_group.groupby(["A", "B", "C"]).mean()
+ depr_msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
+ grouped = three_levels.T.groupby(axis=1, level=(1, 2))
+ for key, group in grouped:
+ pass
+
+ def test_dictify(self, df):
+ dict(iter(df.groupby("A")))
+ dict(iter(df.groupby(["A", "B"])))
+ dict(iter(df["C"].groupby(df["A"])))
+ dict(iter(df["C"].groupby([df["A"], df["B"]])))
+ dict(iter(df.groupby("A")["C"]))
+ dict(iter(df.groupby(["A", "B"])["C"]))
+
+ def test_groupby_with_small_elem(self):
+ # GH 8542
+ # length=2
+ df = DataFrame(
+ {"event": ["start", "start"], "change": [1234, 5678]},
+ index=pd.DatetimeIndex(["2014-09-10", "2013-10-10"]),
+ )
+ grouped = df.groupby([Grouper(freq="M"), "event"])
+ assert len(grouped.groups) == 2
+ assert grouped.ngroups == 2
+ assert (Timestamp("2014-09-30"), "start") in grouped.groups
+ assert (Timestamp("2013-10-31"), "start") in grouped.groups
+
+ res = grouped.get_group((Timestamp("2014-09-30"), "start"))
+ tm.assert_frame_equal(res, df.iloc[[0], :])
+ res = grouped.get_group((Timestamp("2013-10-31"), "start"))
+ tm.assert_frame_equal(res, df.iloc[[1], :])
+
+ df = DataFrame(
+ {"event": ["start", "start", "start"], "change": [1234, 5678, 9123]},
+ index=pd.DatetimeIndex(["2014-09-10", "2013-10-10", "2014-09-15"]),
+ )
+ grouped = df.groupby([Grouper(freq="M"), "event"])
+ assert len(grouped.groups) == 2
+ assert grouped.ngroups == 2
+ assert (Timestamp("2014-09-30"), "start") in grouped.groups
+ assert (Timestamp("2013-10-31"), "start") in grouped.groups
+
+ res = grouped.get_group((Timestamp("2014-09-30"), "start"))
+ tm.assert_frame_equal(res, df.iloc[[0, 2], :])
+ res = grouped.get_group((Timestamp("2013-10-31"), "start"))
+ tm.assert_frame_equal(res, df.iloc[[1], :])
+
+ # length=3
+ df = DataFrame(
+ {"event": ["start", "start", "start"], "change": [1234, 5678, 9123]},
+ index=pd.DatetimeIndex(["2014-09-10", "2013-10-10", "2014-08-05"]),
+ )
+ grouped = df.groupby([Grouper(freq="M"), "event"])
+ assert len(grouped.groups) == 3
+ assert grouped.ngroups == 3
+ assert (Timestamp("2014-09-30"), "start") in grouped.groups
+ assert (Timestamp("2013-10-31"), "start") in grouped.groups
+ assert (Timestamp("2014-08-31"), "start") in grouped.groups
+
+ res = grouped.get_group((Timestamp("2014-09-30"), "start"))
+ tm.assert_frame_equal(res, df.iloc[[0], :])
+ res = grouped.get_group((Timestamp("2013-10-31"), "start"))
+ tm.assert_frame_equal(res, df.iloc[[1], :])
+ res = grouped.get_group((Timestamp("2014-08-31"), "start"))
+ tm.assert_frame_equal(res, df.iloc[[2], :])
+
+ def test_grouping_string_repr(self):
+ # GH 13394
+ mi = MultiIndex.from_arrays([list("AAB"), list("aba")])
+ df = DataFrame([[1, 2, 3]], columns=mi)
+ gr = df.groupby(df[("A", "a")])
+
+ result = gr.grouper.groupings[0].__repr__()
+ expected = "Grouping(('A', 'a'))"
+ assert result == expected
+
+
+def test_grouping_by_key_is_in_axis():
+ # GH#50413 - Groupers specified by key are in-axis
+ df = DataFrame({"a": [1, 1, 2], "b": [1, 1, 2], "c": [3, 4, 5]}).set_index("a")
+ gb = df.groupby([Grouper(level="a"), Grouper(key="b")], as_index=False)
+ assert not gb.grouper.groupings[0].in_axis
+ assert gb.grouper.groupings[1].in_axis
+
+ # Currently only in-axis groupings are including in the result when as_index=False;
+ # This is likely to change in the future.
+ msg = "A grouping .* was excluded from the result"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = gb.sum()
+ expected = DataFrame({"b": [1, 2], "c": [7, 5]})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_grouper_groups():
+ # GH#51182 check Grouper.groups does not raise AttributeError
+ df = DataFrame({"a": [1, 2, 3], "b": 1})
+ grper = Grouper(key="a")
+ gb = df.groupby(grper)
+
+ msg = "Use GroupBy.groups instead"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = grper.groups
+ assert res is gb.groups
+
+ msg = "Use GroupBy.grouper instead"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = grper.grouper
+ assert res is gb.grouper
+
+ msg = "Grouper.obj is deprecated and will be removed"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = grper.obj
+ assert res is gb.obj
+
+ msg = "Use Resampler.ax instead"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ grper.ax
+
+ msg = "Grouper.indexer is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ grper.indexer
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_index_as_string.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_index_as_string.py
new file mode 100644
index 0000000000000000000000000000000000000000..4aaf3de9a23b2416603947db312bb49eea343ba8
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_index_as_string.py
@@ -0,0 +1,85 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+
+@pytest.fixture(params=[["inner"], ["inner", "outer"]])
+def frame(request):
+ levels = request.param
+ df = pd.DataFrame(
+ {
+ "outer": ["a", "a", "a", "b", "b", "b"],
+ "inner": [1, 2, 3, 1, 2, 3],
+ "A": np.arange(6),
+ "B": ["one", "one", "two", "two", "one", "one"],
+ }
+ )
+ if levels:
+ df = df.set_index(levels)
+
+ return df
+
+
+@pytest.fixture()
+def series():
+ df = pd.DataFrame(
+ {
+ "outer": ["a", "a", "a", "b", "b", "b"],
+ "inner": [1, 2, 3, 1, 2, 3],
+ "A": np.arange(6),
+ "B": ["one", "one", "two", "two", "one", "one"],
+ }
+ )
+ s = df.set_index(["outer", "inner", "B"])["A"]
+
+ return s
+
+
+@pytest.mark.parametrize(
+ "key_strs,groupers",
+ [
+ ("inner", pd.Grouper(level="inner")), # Index name
+ (["inner"], [pd.Grouper(level="inner")]), # List of index name
+ (["B", "inner"], ["B", pd.Grouper(level="inner")]), # Column and index
+ (["inner", "B"], [pd.Grouper(level="inner"), "B"]), # Index and column
+ ],
+)
+def test_grouper_index_level_as_string(frame, key_strs, groupers):
+ if "B" not in key_strs or "outer" in frame.columns:
+ result = frame.groupby(key_strs).mean(numeric_only=True)
+ expected = frame.groupby(groupers).mean(numeric_only=True)
+ else:
+ result = frame.groupby(key_strs).mean()
+ expected = frame.groupby(groupers).mean()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "levels",
+ [
+ "inner",
+ "outer",
+ "B",
+ ["inner"],
+ ["outer"],
+ ["B"],
+ ["inner", "outer"],
+ ["outer", "inner"],
+ ["inner", "outer", "B"],
+ ["B", "outer", "inner"],
+ ],
+)
+def test_grouper_index_level_as_string_series(series, levels):
+ # Compute expected result
+ if isinstance(levels, list):
+ groupers = [pd.Grouper(level=lv) for lv in levels]
+ else:
+ groupers = pd.Grouper(level=levels)
+
+ expected = series.groupby(groupers).mean()
+
+ # Compute and check result
+ result = series.groupby(levels).mean()
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_indexing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_indexing.py
new file mode 100644
index 0000000000000000000000000000000000000000..664c52babac1381f77f2e2ee7266a9d41031f15e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_indexing.py
@@ -0,0 +1,333 @@
+# Test GroupBy._positional_selector positional grouped indexing GH#42864
+
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize(
+ "arg, expected_rows",
+ [
+ [0, [0, 1, 4]],
+ [2, [5]],
+ [5, []],
+ [-1, [3, 4, 7]],
+ [-2, [1, 6]],
+ [-6, []],
+ ],
+)
+def test_int(slice_test_df, slice_test_grouped, arg, expected_rows):
+ # Test single integer
+ result = slice_test_grouped._positional_selector[arg]
+ expected = slice_test_df.iloc[expected_rows]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_slice(slice_test_df, slice_test_grouped):
+ # Test single slice
+ result = slice_test_grouped._positional_selector[0:3:2]
+ expected = slice_test_df.iloc[[0, 1, 4, 5]]
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "arg, expected_rows",
+ [
+ [[0, 2], [0, 1, 4, 5]],
+ [[0, 2, -1], [0, 1, 3, 4, 5, 7]],
+ [range(0, 3, 2), [0, 1, 4, 5]],
+ [{0, 2}, [0, 1, 4, 5]],
+ ],
+ ids=[
+ "list",
+ "negative",
+ "range",
+ "set",
+ ],
+)
+def test_list(slice_test_df, slice_test_grouped, arg, expected_rows):
+ # Test lists of integers and integer valued iterables
+ result = slice_test_grouped._positional_selector[arg]
+ expected = slice_test_df.iloc[expected_rows]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_ints(slice_test_df, slice_test_grouped):
+ # Test tuple of ints
+ result = slice_test_grouped._positional_selector[0, 2, -1]
+ expected = slice_test_df.iloc[[0, 1, 3, 4, 5, 7]]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_slices(slice_test_df, slice_test_grouped):
+ # Test tuple of slices
+ result = slice_test_grouped._positional_selector[:2, -2:]
+ expected = slice_test_df.iloc[[0, 1, 2, 3, 4, 6, 7]]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_mix(slice_test_df, slice_test_grouped):
+ # Test mixed tuple of ints and slices
+ result = slice_test_grouped._positional_selector[0, 1, -2:]
+ expected = slice_test_df.iloc[[0, 1, 2, 3, 4, 6, 7]]
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "arg, expected_rows",
+ [
+ [0, [0, 1, 4]],
+ [[0, 2, -1], [0, 1, 3, 4, 5, 7]],
+ [(slice(None, 2), slice(-2, None)), [0, 1, 2, 3, 4, 6, 7]],
+ ],
+)
+def test_as_index(slice_test_df, arg, expected_rows):
+ # Test the default as_index behaviour
+ result = slice_test_df.groupby("Group", sort=False)._positional_selector[arg]
+ expected = slice_test_df.iloc[expected_rows]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_doc_examples():
+ # Test the examples in the documentation
+ df = pd.DataFrame(
+ [["a", 1], ["a", 2], ["a", 3], ["b", 4], ["b", 5]], columns=["A", "B"]
+ )
+
+ grouped = df.groupby("A", as_index=False)
+
+ result = grouped._positional_selector[1:2]
+ expected = pd.DataFrame([["a", 2], ["b", 5]], columns=["A", "B"], index=[1, 4])
+
+ tm.assert_frame_equal(result, expected)
+
+ result = grouped._positional_selector[1, -1]
+ expected = pd.DataFrame(
+ [["a", 2], ["a", 3], ["b", 5]], columns=["A", "B"], index=[1, 2, 4]
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.fixture()
+def multiindex_data():
+ rng = np.random.default_rng(2)
+ ndates = 100
+ nitems = 20
+ dates = pd.date_range("20130101", periods=ndates, freq="D")
+ items = [f"item {i}" for i in range(nitems)]
+
+ data = {}
+ for date in dates:
+ nitems_for_date = nitems - rng.integers(0, 12)
+ levels = [
+ (item, rng.integers(0, 10000) / 100, rng.integers(0, 10000) / 100)
+ for item in items[:nitems_for_date]
+ ]
+ levels.sort(key=lambda x: x[1])
+ data[date] = levels
+
+ return data
+
+
+def _make_df_from_data(data):
+ rows = {}
+ for date in data:
+ for level in data[date]:
+ rows[(date, level[0])] = {"A": level[1], "B": level[2]}
+
+ df = pd.DataFrame.from_dict(rows, orient="index")
+ df.index.names = ("Date", "Item")
+ return df
+
+
+def test_multiindex(multiindex_data):
+ # Test the multiindex mentioned as the use-case in the documentation
+ df = _make_df_from_data(multiindex_data)
+ result = df.groupby("Date", as_index=False).nth(slice(3, -3))
+
+ sliced = {date: multiindex_data[date][3:-3] for date in multiindex_data}
+ expected = _make_df_from_data(sliced)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("arg", [1, 5, 30, 1000, -1, -5, -30, -1000])
+@pytest.mark.parametrize("method", ["head", "tail"])
+@pytest.mark.parametrize("simulated", [True, False])
+def test_against_head_and_tail(arg, method, simulated):
+ # Test gives the same results as grouped head and tail
+ n_groups = 100
+ n_rows_per_group = 30
+
+ data = {
+ "group": [
+ f"group {g}" for j in range(n_rows_per_group) for g in range(n_groups)
+ ],
+ "value": [
+ f"group {g} row {j}"
+ for j in range(n_rows_per_group)
+ for g in range(n_groups)
+ ],
+ }
+ df = pd.DataFrame(data)
+ grouped = df.groupby("group", as_index=False)
+ size = arg if arg >= 0 else n_rows_per_group + arg
+
+ if method == "head":
+ result = grouped._positional_selector[:arg]
+
+ if simulated:
+ indices = [
+ j * n_groups + i
+ for j in range(size)
+ for i in range(n_groups)
+ if j * n_groups + i < n_groups * n_rows_per_group
+ ]
+ expected = df.iloc[indices]
+
+ else:
+ expected = grouped.head(arg)
+
+ else:
+ result = grouped._positional_selector[-arg:]
+
+ if simulated:
+ indices = [
+ (n_rows_per_group + j - size) * n_groups + i
+ for j in range(size)
+ for i in range(n_groups)
+ if (n_rows_per_group + j - size) * n_groups + i >= 0
+ ]
+ expected = df.iloc[indices]
+
+ else:
+ expected = grouped.tail(arg)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("start", [None, 0, 1, 10, -1, -10])
+@pytest.mark.parametrize("stop", [None, 0, 1, 10, -1, -10])
+@pytest.mark.parametrize("step", [None, 1, 5])
+def test_against_df_iloc(start, stop, step):
+ # Test that a single group gives the same results as DataFrame.iloc
+ n_rows = 30
+
+ data = {
+ "group": ["group 0"] * n_rows,
+ "value": list(range(n_rows)),
+ }
+ df = pd.DataFrame(data)
+ grouped = df.groupby("group", as_index=False)
+
+ result = grouped._positional_selector[start:stop:step]
+ expected = df.iloc[start:stop:step]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_series():
+ # Test grouped Series
+ ser = pd.Series([1, 2, 3, 4, 5], index=["a", "a", "a", "b", "b"])
+ grouped = ser.groupby(level=0)
+ result = grouped._positional_selector[1:2]
+ expected = pd.Series([2, 5], index=["a", "b"])
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("step", [1, 2, 3, 4, 5])
+def test_step(step):
+ # Test slice with various step values
+ data = [["x", f"x{i}"] for i in range(5)]
+ data += [["y", f"y{i}"] for i in range(4)]
+ data += [["z", f"z{i}"] for i in range(3)]
+ df = pd.DataFrame(data, columns=["A", "B"])
+
+ grouped = df.groupby("A", as_index=False)
+
+ result = grouped._positional_selector[::step]
+
+ data = [["x", f"x{i}"] for i in range(0, 5, step)]
+ data += [["y", f"y{i}"] for i in range(0, 4, step)]
+ data += [["z", f"z{i}"] for i in range(0, 3, step)]
+
+ index = [0 + i for i in range(0, 5, step)]
+ index += [5 + i for i in range(0, 4, step)]
+ index += [9 + i for i in range(0, 3, step)]
+
+ expected = pd.DataFrame(data, columns=["A", "B"], index=index)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.fixture()
+def column_group_df():
+ return pd.DataFrame(
+ [[0, 1, 2, 3, 4, 5, 6], [0, 0, 1, 0, 1, 0, 2]],
+ columns=["A", "B", "C", "D", "E", "F", "G"],
+ )
+
+
+def test_column_axis(column_group_df):
+ msg = "DataFrame.groupby with axis=1"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ g = column_group_df.groupby(column_group_df.iloc[1], axis=1)
+ result = g._positional_selector[1:-1]
+ expected = column_group_df.iloc[:, [1, 3]]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_columns_on_iter():
+ # GitHub issue #44821
+ df = pd.DataFrame({k: range(10) for k in "ABC"})
+
+ # Group-by and select columns
+ cols = ["A", "B"]
+ for _, dg in df.groupby(df.A < 4)[cols]:
+ tm.assert_index_equal(dg.columns, pd.Index(cols))
+ assert "C" not in dg.columns
+
+
+@pytest.mark.parametrize("func", [list, pd.Index, pd.Series, np.array])
+def test_groupby_duplicated_columns(func):
+ # GH#44924
+ df = pd.DataFrame(
+ {
+ "A": [1, 2],
+ "B": [3, 3],
+ "C": ["G", "G"],
+ }
+ )
+ result = df.groupby("C")[func(["A", "B", "A"])].mean()
+ expected = pd.DataFrame(
+ [[1.5, 3.0, 1.5]], columns=["A", "B", "A"], index=pd.Index(["G"], name="C")
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_get_nonexisting_groups():
+ # GH#32492
+ df = pd.DataFrame(
+ data={
+ "A": ["a1", "a2", None],
+ "B": ["b1", "b2", "b1"],
+ "val": [1, 2, 3],
+ }
+ )
+ grps = df.groupby(by=["A", "B"])
+
+ msg = "('a2', 'b1')"
+ with pytest.raises(KeyError, match=msg):
+ grps.get_group(("a2", "b1"))
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_libgroupby.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_libgroupby.py
new file mode 100644
index 0000000000000000000000000000000000000000..35b8fa93b8e033b8dd9287bc7de8e1ca18ade439
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_libgroupby.py
@@ -0,0 +1,331 @@
+import numpy as np
+import pytest
+
+from pandas._libs import groupby as libgroupby
+from pandas._libs.groupby import (
+ group_cumprod,
+ group_cumsum,
+ group_mean,
+ group_sum,
+ group_var,
+)
+
+from pandas.core.dtypes.common import ensure_platform_int
+
+from pandas import isna
+import pandas._testing as tm
+
+
+class GroupVarTestMixin:
+ def test_group_var_generic_1d(self):
+ prng = np.random.default_rng(2)
+
+ out = (np.nan * np.ones((5, 1))).astype(self.dtype)
+ counts = np.zeros(5, dtype="int64")
+ values = 10 * prng.random((15, 1)).astype(self.dtype)
+ labels = np.tile(np.arange(5), (3,)).astype("intp")
+
+ expected_out = (
+ np.squeeze(values).reshape((5, 3), order="F").std(axis=1, ddof=1) ** 2
+ )[:, np.newaxis]
+ expected_counts = counts + 3
+
+ self.algo(out, counts, values, labels)
+ assert np.allclose(out, expected_out, self.rtol)
+ tm.assert_numpy_array_equal(counts, expected_counts)
+
+ def test_group_var_generic_1d_flat_labels(self):
+ prng = np.random.default_rng(2)
+
+ out = (np.nan * np.ones((1, 1))).astype(self.dtype)
+ counts = np.zeros(1, dtype="int64")
+ values = 10 * prng.random((5, 1)).astype(self.dtype)
+ labels = np.zeros(5, dtype="intp")
+
+ expected_out = np.array([[values.std(ddof=1) ** 2]])
+ expected_counts = counts + 5
+
+ self.algo(out, counts, values, labels)
+
+ assert np.allclose(out, expected_out, self.rtol)
+ tm.assert_numpy_array_equal(counts, expected_counts)
+
+ def test_group_var_generic_2d_all_finite(self):
+ prng = np.random.default_rng(2)
+
+ out = (np.nan * np.ones((5, 2))).astype(self.dtype)
+ counts = np.zeros(5, dtype="int64")
+ values = 10 * prng.random((10, 2)).astype(self.dtype)
+ labels = np.tile(np.arange(5), (2,)).astype("intp")
+
+ expected_out = np.std(values.reshape(2, 5, 2), ddof=1, axis=0) ** 2
+ expected_counts = counts + 2
+
+ self.algo(out, counts, values, labels)
+ assert np.allclose(out, expected_out, self.rtol)
+ tm.assert_numpy_array_equal(counts, expected_counts)
+
+ def test_group_var_generic_2d_some_nan(self):
+ prng = np.random.default_rng(2)
+
+ out = (np.nan * np.ones((5, 2))).astype(self.dtype)
+ counts = np.zeros(5, dtype="int64")
+ values = 10 * prng.random((10, 2)).astype(self.dtype)
+ values[:, 1] = np.nan
+ labels = np.tile(np.arange(5), (2,)).astype("intp")
+
+ expected_out = np.vstack(
+ [
+ values[:, 0].reshape(5, 2, order="F").std(ddof=1, axis=1) ** 2,
+ np.nan * np.ones(5),
+ ]
+ ).T.astype(self.dtype)
+ expected_counts = counts + 2
+
+ self.algo(out, counts, values, labels)
+ tm.assert_almost_equal(out, expected_out, rtol=0.5e-06)
+ tm.assert_numpy_array_equal(counts, expected_counts)
+
+ def test_group_var_constant(self):
+ # Regression test from GH 10448.
+
+ out = np.array([[np.nan]], dtype=self.dtype)
+ counts = np.array([0], dtype="int64")
+ values = 0.832845131556193 * np.ones((3, 1), dtype=self.dtype)
+ labels = np.zeros(3, dtype="intp")
+
+ self.algo(out, counts, values, labels)
+
+ assert counts[0] == 3
+ assert out[0, 0] >= 0
+ tm.assert_almost_equal(out[0, 0], 0.0)
+
+
+class TestGroupVarFloat64(GroupVarTestMixin):
+ __test__ = True
+
+ algo = staticmethod(group_var)
+ dtype = np.float64
+ rtol = 1e-5
+
+ def test_group_var_large_inputs(self):
+ prng = np.random.default_rng(2)
+
+ out = np.array([[np.nan]], dtype=self.dtype)
+ counts = np.array([0], dtype="int64")
+ values = (prng.random(10**6) + 10**12).astype(self.dtype)
+ values.shape = (10**6, 1)
+ labels = np.zeros(10**6, dtype="intp")
+
+ self.algo(out, counts, values, labels)
+
+ assert counts[0] == 10**6
+ tm.assert_almost_equal(out[0, 0], 1.0 / 12, rtol=0.5e-3)
+
+
+class TestGroupVarFloat32(GroupVarTestMixin):
+ __test__ = True
+
+ algo = staticmethod(group_var)
+ dtype = np.float32
+ rtol = 1e-2
+
+
+@pytest.mark.parametrize("dtype", ["float32", "float64"])
+def test_group_ohlc(dtype):
+ obj = np.array(np.random.default_rng(2).standard_normal(20), dtype=dtype)
+
+ bins = np.array([6, 12, 20])
+ out = np.zeros((3, 4), dtype)
+ counts = np.zeros(len(out), dtype=np.int64)
+ labels = ensure_platform_int(np.repeat(np.arange(3), np.diff(np.r_[0, bins])))
+
+ func = libgroupby.group_ohlc
+ func(out, counts, obj[:, None], labels)
+
+ def _ohlc(group):
+ if isna(group).all():
+ return np.repeat(np.nan, 4)
+ return [group[0], group.max(), group.min(), group[-1]]
+
+ expected = np.array([_ohlc(obj[:6]), _ohlc(obj[6:12]), _ohlc(obj[12:])])
+
+ tm.assert_almost_equal(out, expected)
+ tm.assert_numpy_array_equal(counts, np.array([6, 6, 8], dtype=np.int64))
+
+ obj[:6] = np.nan
+ func(out, counts, obj[:, None], labels)
+ expected[0] = np.nan
+ tm.assert_almost_equal(out, expected)
+
+
+def _check_cython_group_transform_cumulative(pd_op, np_op, dtype):
+ """
+ Check a group transform that executes a cumulative function.
+
+ Parameters
+ ----------
+ pd_op : callable
+ The pandas cumulative function.
+ np_op : callable
+ The analogous one in NumPy.
+ dtype : type
+ The specified dtype of the data.
+ """
+ is_datetimelike = False
+
+ data = np.array([[1], [2], [3], [4]], dtype=dtype)
+ answer = np.zeros_like(data)
+
+ labels = np.array([0, 0, 0, 0], dtype=np.intp)
+ ngroups = 1
+ pd_op(answer, data, labels, ngroups, is_datetimelike)
+
+ tm.assert_numpy_array_equal(np_op(data), answer[:, 0], check_dtype=False)
+
+
+@pytest.mark.parametrize("np_dtype", ["int64", "uint64", "float32", "float64"])
+def test_cython_group_transform_cumsum(np_dtype):
+ # see gh-4095
+ dtype = np.dtype(np_dtype).type
+ pd_op, np_op = group_cumsum, np.cumsum
+ _check_cython_group_transform_cumulative(pd_op, np_op, dtype)
+
+
+def test_cython_group_transform_cumprod():
+ # see gh-4095
+ dtype = np.float64
+ pd_op, np_op = group_cumprod, np.cumprod
+ _check_cython_group_transform_cumulative(pd_op, np_op, dtype)
+
+
+def test_cython_group_transform_algos():
+ # see gh-4095
+ is_datetimelike = False
+
+ # with nans
+ labels = np.array([0, 0, 0, 0, 0], dtype=np.intp)
+ ngroups = 1
+
+ data = np.array([[1], [2], [3], [np.nan], [4]], dtype="float64")
+ actual = np.zeros_like(data)
+ actual.fill(np.nan)
+ group_cumprod(actual, data, labels, ngroups, is_datetimelike)
+ expected = np.array([1, 2, 6, np.nan, 24], dtype="float64")
+ tm.assert_numpy_array_equal(actual[:, 0], expected)
+
+ actual = np.zeros_like(data)
+ actual.fill(np.nan)
+ group_cumsum(actual, data, labels, ngroups, is_datetimelike)
+ expected = np.array([1, 3, 6, np.nan, 10], dtype="float64")
+ tm.assert_numpy_array_equal(actual[:, 0], expected)
+
+ # timedelta
+ is_datetimelike = True
+ data = np.array([np.timedelta64(1, "ns")] * 5, dtype="m8[ns]")[:, None]
+ actual = np.zeros_like(data, dtype="int64")
+ group_cumsum(actual, data.view("int64"), labels, ngroups, is_datetimelike)
+ expected = np.array(
+ [
+ np.timedelta64(1, "ns"),
+ np.timedelta64(2, "ns"),
+ np.timedelta64(3, "ns"),
+ np.timedelta64(4, "ns"),
+ np.timedelta64(5, "ns"),
+ ]
+ )
+ tm.assert_numpy_array_equal(actual[:, 0].view("m8[ns]"), expected)
+
+
+def test_cython_group_mean_datetimelike():
+ actual = np.zeros(shape=(1, 1), dtype="float64")
+ counts = np.array([0], dtype="int64")
+ data = (
+ np.array(
+ [np.timedelta64(2, "ns"), np.timedelta64(4, "ns"), np.timedelta64("NaT")],
+ dtype="m8[ns]",
+ )[:, None]
+ .view("int64")
+ .astype("float64")
+ )
+ labels = np.zeros(len(data), dtype=np.intp)
+
+ group_mean(actual, counts, data, labels, is_datetimelike=True)
+
+ tm.assert_numpy_array_equal(actual[:, 0], np.array([3], dtype="float64"))
+
+
+def test_cython_group_mean_wrong_min_count():
+ actual = np.zeros(shape=(1, 1), dtype="float64")
+ counts = np.zeros(1, dtype="int64")
+ data = np.zeros(1, dtype="float64")[:, None]
+ labels = np.zeros(1, dtype=np.intp)
+
+ with pytest.raises(AssertionError, match="min_count"):
+ group_mean(actual, counts, data, labels, is_datetimelike=True, min_count=0)
+
+
+def test_cython_group_mean_not_datetimelike_but_has_NaT_values():
+ actual = np.zeros(shape=(1, 1), dtype="float64")
+ counts = np.array([0], dtype="int64")
+ data = (
+ np.array(
+ [np.timedelta64("NaT"), np.timedelta64("NaT")],
+ dtype="m8[ns]",
+ )[:, None]
+ .view("int64")
+ .astype("float64")
+ )
+ labels = np.zeros(len(data), dtype=np.intp)
+
+ group_mean(actual, counts, data, labels, is_datetimelike=False)
+
+ tm.assert_numpy_array_equal(
+ actual[:, 0], np.array(np.divide(np.add(data[0], data[1]), 2), dtype="float64")
+ )
+
+
+def test_cython_group_mean_Inf_at_begining_and_end():
+ # GH 50367
+ actual = np.array([[np.nan, np.nan], [np.nan, np.nan]], dtype="float64")
+ counts = np.array([0, 0], dtype="int64")
+ data = np.array(
+ [[np.inf, 1.0], [1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0], [5, np.inf]],
+ dtype="float64",
+ )
+ labels = np.array([0, 1, 0, 1, 0, 1], dtype=np.intp)
+
+ group_mean(actual, counts, data, labels, is_datetimelike=False)
+
+ expected = np.array([[np.inf, 3], [3, np.inf]], dtype="float64")
+
+ tm.assert_numpy_array_equal(
+ actual,
+ expected,
+ )
+
+
+@pytest.mark.parametrize(
+ "values, out",
+ [
+ ([[np.inf], [np.inf], [np.inf]], [[np.inf], [np.inf]]),
+ ([[np.inf], [np.inf], [-np.inf]], [[np.inf], [np.nan]]),
+ ([[np.inf], [-np.inf], [np.inf]], [[np.inf], [np.nan]]),
+ ([[np.inf], [-np.inf], [-np.inf]], [[np.inf], [-np.inf]]),
+ ],
+)
+def test_cython_group_sum_Inf_at_begining_and_end(values, out):
+ # GH #53606
+ actual = np.array([[np.nan], [np.nan]], dtype="float64")
+ counts = np.array([0, 0], dtype="int64")
+ data = np.array(values, dtype="float64")
+ labels = np.array([0, 1, 1], dtype=np.intp)
+
+ group_sum(actual, counts, data, labels, None, is_datetimelike=False)
+
+ expected = np.array(out, dtype="float64")
+
+ tm.assert_numpy_array_equal(
+ actual,
+ expected,
+ )
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_min_max.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_min_max.py
new file mode 100644
index 0000000000000000000000000000000000000000..30c7e1df1e691b47d69450bb827ee23e9e30b8a2
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_min_max.py
@@ -0,0 +1,272 @@
+import numpy as np
+import pytest
+
+from pandas._libs.tslibs import iNaT
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
+import pandas._testing as tm
+
+
+def test_max_min_non_numeric():
+ # #2700
+ aa = DataFrame({"nn": [11, 11, 22, 22], "ii": [1, 2, 3, 4], "ss": 4 * ["mama"]})
+
+ result = aa.groupby("nn").max()
+ assert "ss" in result
+
+ result = aa.groupby("nn").max(numeric_only=False)
+ assert "ss" in result
+
+ result = aa.groupby("nn").min()
+ assert "ss" in result
+
+ result = aa.groupby("nn").min(numeric_only=False)
+ assert "ss" in result
+
+
+def test_max_min_object_multiple_columns(using_array_manager):
+ # GH#41111 case where the aggregation is valid for some columns but not
+ # others; we split object blocks column-wise, consistent with
+ # DataFrame._reduce
+
+ df = DataFrame(
+ {
+ "A": [1, 1, 2, 2, 3],
+ "B": [1, "foo", 2, "bar", False],
+ "C": ["a", "b", "c", "d", "e"],
+ }
+ )
+ df._consolidate_inplace() # should already be consolidate, but double-check
+ if not using_array_manager:
+ assert len(df._mgr.blocks) == 2
+
+ gb = df.groupby("A")
+
+ result = gb[["C"]].max()
+ # "max" is valid for column "C" but not for "B"
+ ei = Index([1, 2, 3], name="A")
+ expected = DataFrame({"C": ["b", "d", "e"]}, index=ei)
+ tm.assert_frame_equal(result, expected)
+
+ result = gb[["C"]].min()
+ # "min" is valid for column "C" but not for "B"
+ ei = Index([1, 2, 3], name="A")
+ expected = DataFrame({"C": ["a", "c", "e"]}, index=ei)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_min_date_with_nans():
+ # GH26321
+ dates = pd.to_datetime(
+ Series(["2019-05-09", "2019-05-09", "2019-05-09"]), format="%Y-%m-%d"
+ ).dt.date
+ df = DataFrame({"a": [np.nan, "1", np.nan], "b": [0, 1, 1], "c": dates})
+
+ result = df.groupby("b", as_index=False)["c"].min()["c"]
+ expected = pd.to_datetime(
+ Series(["2019-05-09", "2019-05-09"], name="c"), format="%Y-%m-%d"
+ ).dt.date
+ tm.assert_series_equal(result, expected)
+
+ result = df.groupby("b")["c"].min()
+ expected.index.name = "b"
+ tm.assert_series_equal(result, expected)
+
+
+def test_max_inat():
+ # GH#40767 dont interpret iNaT as NaN
+ ser = Series([1, iNaT])
+ key = np.array([1, 1], dtype=np.int64)
+ gb = ser.groupby(key)
+
+ result = gb.max(min_count=2)
+ expected = Series({1: 1}, dtype=np.int64)
+ tm.assert_series_equal(result, expected, check_exact=True)
+
+ result = gb.min(min_count=2)
+ expected = Series({1: iNaT}, dtype=np.int64)
+ tm.assert_series_equal(result, expected, check_exact=True)
+
+ # not enough entries -> gets masked to NaN
+ result = gb.min(min_count=3)
+ expected = Series({1: np.nan})
+ tm.assert_series_equal(result, expected, check_exact=True)
+
+
+def test_max_inat_not_all_na():
+ # GH#40767 dont interpret iNaT as NaN
+
+ # make sure we dont round iNaT+1 to iNaT
+ ser = Series([1, iNaT, 2, iNaT + 1])
+ gb = ser.groupby([1, 2, 3, 3])
+ result = gb.min(min_count=2)
+
+ # Note: in converting to float64, the iNaT + 1 maps to iNaT, i.e. is lossy
+ expected = Series({1: np.nan, 2: np.nan, 3: iNaT + 1})
+ expected.index = expected.index.astype(int)
+ tm.assert_series_equal(result, expected, check_exact=True)
+
+
+@pytest.mark.parametrize("func", ["min", "max"])
+def test_groupby_aggregate_period_column(func):
+ # GH 31471
+ groups = [1, 2]
+ periods = pd.period_range("2020", periods=2, freq="Y")
+ df = DataFrame({"a": groups, "b": periods})
+
+ result = getattr(df.groupby("a")["b"], func)()
+ idx = Index([1, 2], name="a")
+ expected = Series(periods, index=idx, name="b")
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", ["min", "max"])
+def test_groupby_aggregate_period_frame(func):
+ # GH 31471
+ groups = [1, 2]
+ periods = pd.period_range("2020", periods=2, freq="Y")
+ df = DataFrame({"a": groups, "b": periods})
+
+ result = getattr(df.groupby("a"), func)()
+ idx = Index([1, 2], name="a")
+ expected = DataFrame({"b": periods}, index=idx)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_aggregate_numeric_object_dtype():
+ # https://github.com/pandas-dev/pandas/issues/39329
+ # simplified case: multiple object columns where one is all-NaN
+ # -> gets split as the all-NaN is inferred as float
+ df = DataFrame(
+ {"key": ["A", "A", "B", "B"], "col1": list("abcd"), "col2": [np.nan] * 4},
+ ).astype(object)
+ result = df.groupby("key").min()
+ expected = (
+ DataFrame(
+ {"key": ["A", "B"], "col1": ["a", "c"], "col2": [np.nan, np.nan]},
+ )
+ .set_index("key")
+ .astype(object)
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # same but with numbers
+ df = DataFrame(
+ {"key": ["A", "A", "B", "B"], "col1": list("abcd"), "col2": range(4)},
+ ).astype(object)
+ result = df.groupby("key").min()
+ expected = (
+ DataFrame({"key": ["A", "B"], "col1": ["a", "c"], "col2": [0, 2]})
+ .set_index("key")
+ .astype(object)
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", ["min", "max"])
+def test_aggregate_categorical_lost_index(func: str):
+ # GH: 28641 groupby drops index, when grouping over categorical column with min/max
+ ds = Series(["b"], dtype="category").cat.as_ordered()
+ df = DataFrame({"A": [1997], "B": ds})
+ result = df.groupby("A").agg({"B": func})
+ expected = DataFrame({"B": ["b"]}, index=Index([1997], name="A"))
+
+ # ordered categorical dtype should be preserved
+ expected["B"] = expected["B"].astype(ds.dtype)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["Int64", "Int32", "Float64", "Float32", "boolean"])
+def test_groupby_min_max_nullable(dtype):
+ if dtype == "Int64":
+ # GH#41743 avoid precision loss
+ ts = 1618556707013635762
+ elif dtype == "boolean":
+ ts = 0
+ else:
+ ts = 4.0
+
+ df = DataFrame({"id": [2, 2], "ts": [ts, ts + 1]})
+ df["ts"] = df["ts"].astype(dtype)
+
+ gb = df.groupby("id")
+
+ result = gb.min()
+ expected = df.iloc[:1].set_index("id")
+ tm.assert_frame_equal(result, expected)
+
+ res_max = gb.max()
+ expected_max = df.iloc[1:].set_index("id")
+ tm.assert_frame_equal(res_max, expected_max)
+
+ result2 = gb.min(min_count=3)
+ expected2 = DataFrame({"ts": [pd.NA]}, index=expected.index, dtype=dtype)
+ tm.assert_frame_equal(result2, expected2)
+
+ res_max2 = gb.max(min_count=3)
+ tm.assert_frame_equal(res_max2, expected2)
+
+ # Case with NA values
+ df2 = DataFrame({"id": [2, 2, 2], "ts": [ts, pd.NA, ts + 1]})
+ df2["ts"] = df2["ts"].astype(dtype)
+ gb2 = df2.groupby("id")
+
+ result3 = gb2.min()
+ tm.assert_frame_equal(result3, expected)
+
+ res_max3 = gb2.max()
+ tm.assert_frame_equal(res_max3, expected_max)
+
+ result4 = gb2.min(min_count=100)
+ tm.assert_frame_equal(result4, expected2)
+
+ res_max4 = gb2.max(min_count=100)
+ tm.assert_frame_equal(res_max4, expected2)
+
+
+def test_min_max_nullable_uint64_empty_group():
+ # don't raise NotImplementedError from libgroupby
+ cat = pd.Categorical([0] * 10, categories=[0, 1])
+ df = DataFrame({"A": cat, "B": pd.array(np.arange(10, dtype=np.uint64))})
+ gb = df.groupby("A", observed=False)
+
+ res = gb.min()
+
+ idx = pd.CategoricalIndex([0, 1], dtype=cat.dtype, name="A")
+ expected = DataFrame({"B": pd.array([0, pd.NA], dtype="UInt64")}, index=idx)
+ tm.assert_frame_equal(res, expected)
+
+ res = gb.max()
+ expected.iloc[0, 0] = 9
+ tm.assert_frame_equal(res, expected)
+
+
+@pytest.mark.parametrize("func", ["first", "last", "min", "max"])
+def test_groupby_min_max_categorical(func):
+ # GH: 52151
+ df = DataFrame(
+ {
+ "col1": pd.Categorical(["A"], categories=list("AB"), ordered=True),
+ "col2": pd.Categorical([1], categories=[1, 2], ordered=True),
+ "value": 0.1,
+ }
+ )
+ result = getattr(df.groupby("col1", observed=False), func)()
+
+ idx = pd.CategoricalIndex(data=["A", "B"], name="col1", ordered=True)
+ expected = DataFrame(
+ {
+ "col2": pd.Categorical([1, None], categories=[1, 2], ordered=True),
+ "value": [0.1, None],
+ },
+ index=idx,
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_missing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_missing.py
new file mode 100644
index 0000000000000000000000000000000000000000..37bf22279b38c3d8ae2c1b91efece4d46565d510
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_missing.py
@@ -0,0 +1,161 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ date_range,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize("func", ["ffill", "bfill"])
+def test_groupby_column_index_name_lost_fill_funcs(func):
+ # GH: 29764 groupby loses index sometimes
+ df = DataFrame(
+ [[1, 1.0, -1.0], [1, np.nan, np.nan], [1, 2.0, -2.0]],
+ columns=Index(["type", "a", "b"], name="idx"),
+ )
+ df_grouped = df.groupby(["type"])[["a", "b"]]
+ result = getattr(df_grouped, func)().columns
+ expected = Index(["a", "b"], name="idx")
+ tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", ["ffill", "bfill"])
+def test_groupby_fill_duplicate_column_names(func):
+ # GH: 25610 ValueError with duplicate column names
+ df1 = DataFrame({"field1": [1, 3, 4], "field2": [1, 3, 4]})
+ df2 = DataFrame({"field1": [1, np.nan, 4]})
+ df_grouped = pd.concat([df1, df2], axis=1).groupby(by=["field2"])
+ expected = DataFrame(
+ [[1, 1.0], [3, np.nan], [4, 4.0]], columns=["field1", "field1"]
+ )
+ result = getattr(df_grouped, func)()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_ffill_missing_arguments():
+ # GH 14955
+ df = DataFrame({"a": [1, 2], "b": [1, 1]})
+ with pytest.raises(ValueError, match="Must specify a fill"):
+ df.groupby("b").fillna()
+
+
+@pytest.mark.parametrize(
+ "method, expected", [("ffill", [None, "a", "a"]), ("bfill", ["a", "a", None])]
+)
+def test_fillna_with_string_dtype(method, expected):
+ # GH 40250
+ df = DataFrame({"a": pd.array([None, "a", None], dtype="string"), "b": [0, 0, 0]})
+ grp = df.groupby("b")
+ msg = "DataFrameGroupBy.fillna with 'method' is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = grp.fillna(method=method)
+ expected = DataFrame({"a": pd.array(expected, dtype="string")})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_fill_consistency():
+ # GH9221
+ # pass thru keyword arguments to the generated wrapper
+ # are set if the passed kw is None (only)
+ df = DataFrame(
+ index=pd.MultiIndex.from_product(
+ [["value1", "value2"], date_range("2014-01-01", "2014-01-06")]
+ ),
+ columns=Index(["1", "2"], name="id"),
+ )
+ df["1"] = [
+ np.nan,
+ 1,
+ np.nan,
+ np.nan,
+ 11,
+ np.nan,
+ np.nan,
+ 2,
+ np.nan,
+ np.nan,
+ 22,
+ np.nan,
+ ]
+ df["2"] = [
+ np.nan,
+ 3,
+ np.nan,
+ np.nan,
+ 33,
+ np.nan,
+ np.nan,
+ 4,
+ np.nan,
+ np.nan,
+ 44,
+ np.nan,
+ ]
+
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = df.groupby(level=0, axis=0).fillna(method="ffill")
+
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.T.groupby(level=0, axis=1).fillna(method="ffill").T
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["ffill", "bfill"])
+@pytest.mark.parametrize("dropna", [True, False])
+@pytest.mark.parametrize("has_nan_group", [True, False])
+def test_ffill_handles_nan_groups(dropna, method, has_nan_group):
+ # GH 34725
+
+ df_without_nan_rows = DataFrame([(1, 0.1), (2, 0.2)])
+
+ ridx = [-1, 0, -1, -1, 1, -1]
+ df = df_without_nan_rows.reindex(ridx).reset_index(drop=True)
+
+ group_b = np.nan if has_nan_group else "b"
+ df["group_col"] = pd.Series(["a"] * 3 + [group_b] * 3)
+
+ grouped = df.groupby(by="group_col", dropna=dropna)
+ result = getattr(grouped, method)(limit=None)
+
+ expected_rows = {
+ ("ffill", True, True): [-1, 0, 0, -1, -1, -1],
+ ("ffill", True, False): [-1, 0, 0, -1, 1, 1],
+ ("ffill", False, True): [-1, 0, 0, -1, 1, 1],
+ ("ffill", False, False): [-1, 0, 0, -1, 1, 1],
+ ("bfill", True, True): [0, 0, -1, -1, -1, -1],
+ ("bfill", True, False): [0, 0, -1, 1, 1, -1],
+ ("bfill", False, True): [0, 0, -1, 1, 1, -1],
+ ("bfill", False, False): [0, 0, -1, 1, 1, -1],
+ }
+
+ ridx = expected_rows.get((method, dropna, has_nan_group))
+ expected = df_without_nan_rows.reindex(ridx).reset_index(drop=True)
+ # columns are a 'take' on df.columns, which are object dtype
+ expected.columns = expected.columns.astype(object)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("min_count, value", [(2, np.nan), (-1, 1.0)])
+@pytest.mark.parametrize("func", ["first", "last", "max", "min"])
+def test_min_count(func, min_count, value):
+ # GH#37821
+ df = DataFrame({"a": [1] * 3, "b": [1, np.nan, np.nan], "c": [np.nan] * 3})
+ result = getattr(df.groupby("a"), func)(min_count=min_count)
+ expected = DataFrame({"b": [value], "c": [np.nan]}, index=Index([1], name="a"))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_indices_with_missing():
+ # GH 9304
+ df = DataFrame({"a": [1, 1, np.nan], "b": [2, 3, 4], "c": [5, 6, 7]})
+ g = df.groupby(["a", "b"])
+ result = g.indices
+ expected = {(1.0, 2): np.array([0]), (1.0, 3): np.array([1])}
+ assert result == expected
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_nth.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_nth.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cf4a90e25f1b5f316182fe82d08091a694b4503
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_nth.py
@@ -0,0 +1,875 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ isna,
+)
+import pandas._testing as tm
+
+
+def test_first_last_nth(df):
+ # tests for first / last / nth
+ grouped = df.groupby("A")
+ first = grouped.first()
+ expected = df.loc[[1, 0], ["B", "C", "D"]]
+ expected.index = Index(["bar", "foo"], name="A")
+ expected = expected.sort_index()
+ tm.assert_frame_equal(first, expected)
+
+ nth = grouped.nth(0)
+ expected = df.loc[[0, 1]]
+ tm.assert_frame_equal(nth, expected)
+
+ last = grouped.last()
+ expected = df.loc[[5, 7], ["B", "C", "D"]]
+ expected.index = Index(["bar", "foo"], name="A")
+ tm.assert_frame_equal(last, expected)
+
+ nth = grouped.nth(-1)
+ expected = df.iloc[[5, 7]]
+ tm.assert_frame_equal(nth, expected)
+
+ nth = grouped.nth(1)
+ expected = df.iloc[[2, 3]]
+ tm.assert_frame_equal(nth, expected)
+
+ # it works!
+ grouped["B"].first()
+ grouped["B"].last()
+ grouped["B"].nth(0)
+
+ df.loc[df["A"] == "foo", "B"] = np.nan
+ assert isna(grouped["B"].first()["foo"])
+ assert isna(grouped["B"].last()["foo"])
+ assert isna(grouped["B"].nth(0).iloc[0])
+
+ # v0.14.0 whatsnew
+ df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"])
+ g = df.groupby("A")
+ result = g.first()
+ expected = df.iloc[[1, 2]].set_index("A")
+ tm.assert_frame_equal(result, expected)
+
+ expected = df.iloc[[1, 2]]
+ result = g.nth(0, dropna="any")
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["first", "last"])
+def test_first_last_with_na_object(method, nulls_fixture):
+ # https://github.com/pandas-dev/pandas/issues/32123
+ groups = DataFrame({"a": [1, 1, 2, 2], "b": [1, 2, 3, nulls_fixture]}).groupby("a")
+ result = getattr(groups, method)()
+
+ if method == "first":
+ values = [1, 3]
+ else:
+ values = [2, 3]
+
+ values = np.array(values, dtype=result["b"].dtype)
+ idx = Index([1, 2], name="a")
+ expected = DataFrame({"b": values}, index=idx)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("index", [0, -1])
+def test_nth_with_na_object(index, nulls_fixture):
+ # https://github.com/pandas-dev/pandas/issues/32123
+ df = DataFrame({"a": [1, 1, 2, 2], "b": [1, 2, 3, nulls_fixture]})
+ groups = df.groupby("a")
+ result = groups.nth(index)
+ expected = df.iloc[[0, 2]] if index == 0 else df.iloc[[1, 3]]
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["first", "last"])
+def test_first_last_with_None(method):
+ # https://github.com/pandas-dev/pandas/issues/32800
+ # None should be preserved as object dtype
+ df = DataFrame.from_dict({"id": ["a"], "value": [None]})
+ groups = df.groupby("id", as_index=False)
+ result = getattr(groups, method)()
+
+ tm.assert_frame_equal(result, df)
+
+
+@pytest.mark.parametrize("method", ["first", "last"])
+@pytest.mark.parametrize(
+ "df, expected",
+ [
+ (
+ DataFrame({"id": "a", "value": [None, "foo", np.nan]}),
+ DataFrame({"value": ["foo"]}, index=Index(["a"], name="id")),
+ ),
+ (
+ DataFrame({"id": "a", "value": [np.nan]}, dtype=object),
+ DataFrame({"value": [None]}, index=Index(["a"], name="id")),
+ ),
+ ],
+)
+def test_first_last_with_None_expanded(method, df, expected):
+ # GH 32800, 38286
+ result = getattr(df.groupby("id"), method)()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_first_last_nth_dtypes(df_mixed_floats):
+ df = df_mixed_floats.copy()
+ df["E"] = True
+ df["F"] = 1
+
+ # tests for first / last / nth
+ grouped = df.groupby("A")
+ first = grouped.first()
+ expected = df.loc[[1, 0], ["B", "C", "D", "E", "F"]]
+ expected.index = Index(["bar", "foo"], name="A")
+ expected = expected.sort_index()
+ tm.assert_frame_equal(first, expected)
+
+ last = grouped.last()
+ expected = df.loc[[5, 7], ["B", "C", "D", "E", "F"]]
+ expected.index = Index(["bar", "foo"], name="A")
+ expected = expected.sort_index()
+ tm.assert_frame_equal(last, expected)
+
+ nth = grouped.nth(1)
+ expected = df.iloc[[2, 3]]
+ tm.assert_frame_equal(nth, expected)
+
+ # GH 2763, first/last shifting dtypes
+ idx = list(range(10))
+ idx.append(9)
+ s = Series(data=range(11), index=idx, name="IntCol")
+ assert s.dtype == "int64"
+ f = s.groupby(level=0).first()
+ assert f.dtype == "int64"
+
+
+def test_first_last_nth_nan_dtype():
+ # GH 33591
+ df = DataFrame({"data": ["A"], "nans": Series([None], dtype=object)})
+ grouped = df.groupby("data")
+
+ expected = df.set_index("data").nans
+ tm.assert_series_equal(grouped.nans.first(), expected)
+ tm.assert_series_equal(grouped.nans.last(), expected)
+
+ expected = df.nans
+ tm.assert_series_equal(grouped.nans.nth(-1), expected)
+ tm.assert_series_equal(grouped.nans.nth(0), expected)
+
+
+def test_first_strings_timestamps():
+ # GH 11244
+ test = DataFrame(
+ {
+ Timestamp("2012-01-01 00:00:00"): ["a", "b"],
+ Timestamp("2012-01-02 00:00:00"): ["c", "d"],
+ "name": ["e", "e"],
+ "aaaa": ["f", "g"],
+ }
+ )
+ result = test.groupby("name").first()
+ expected = DataFrame(
+ [["a", "c", "f"]],
+ columns=Index([Timestamp("2012-01-01"), Timestamp("2012-01-02"), "aaaa"]),
+ index=Index(["e"], name="name"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_nth():
+ df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"])
+ g = df.groupby("A")
+
+ tm.assert_frame_equal(g.nth(0), df.iloc[[0, 2]])
+ tm.assert_frame_equal(g.nth(1), df.iloc[[1]])
+ tm.assert_frame_equal(g.nth(2), df.loc[[]])
+ tm.assert_frame_equal(g.nth(-1), df.iloc[[1, 2]])
+ tm.assert_frame_equal(g.nth(-2), df.iloc[[0]])
+ tm.assert_frame_equal(g.nth(-3), df.loc[[]])
+ tm.assert_series_equal(g.B.nth(0), df.B.iloc[[0, 2]])
+ tm.assert_series_equal(g.B.nth(1), df.B.iloc[[1]])
+ tm.assert_frame_equal(g[["B"]].nth(0), df[["B"]].iloc[[0, 2]])
+
+ tm.assert_frame_equal(g.nth(0, dropna="any"), df.iloc[[1, 2]])
+ tm.assert_frame_equal(g.nth(-1, dropna="any"), df.iloc[[1, 2]])
+
+ tm.assert_frame_equal(g.nth(7, dropna="any"), df.iloc[:0])
+ tm.assert_frame_equal(g.nth(2, dropna="any"), df.iloc[:0])
+
+ # out of bounds, regression from 0.13.1
+ # GH 6621
+ df = DataFrame(
+ {
+ "color": {0: "green", 1: "green", 2: "red", 3: "red", 4: "red"},
+ "food": {0: "ham", 1: "eggs", 2: "eggs", 3: "ham", 4: "pork"},
+ "two": {
+ 0: 1.5456590000000001,
+ 1: -0.070345000000000005,
+ 2: -2.4004539999999999,
+ 3: 0.46206000000000003,
+ 4: 0.52350799999999997,
+ },
+ "one": {
+ 0: 0.56573799999999996,
+ 1: -0.9742360000000001,
+ 2: 1.033801,
+ 3: -0.78543499999999999,
+ 4: 0.70422799999999997,
+ },
+ }
+ ).set_index(["color", "food"])
+
+ result = df.groupby(level=0, as_index=False).nth(2)
+ expected = df.iloc[[-1]]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(level=0, as_index=False).nth(3)
+ expected = df.loc[[]]
+ tm.assert_frame_equal(result, expected)
+
+ # GH 7559
+ # from the vbench
+ df = DataFrame(np.random.default_rng(2).integers(1, 10, (100, 2)), dtype="int64")
+ s = df[1]
+ g = df[0]
+ expected = s.groupby(g).first()
+ expected2 = s.groupby(g).apply(lambda x: x.iloc[0])
+ tm.assert_series_equal(expected2, expected, check_names=False)
+ assert expected.name == 1
+ assert expected2.name == 1
+
+ # validate first
+ v = s[g == 1].iloc[0]
+ assert expected.iloc[0] == v
+ assert expected2.iloc[0] == v
+
+ with pytest.raises(ValueError, match="For a DataFrame"):
+ s.groupby(g, sort=False).nth(0, dropna=True)
+
+ # doc example
+ df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"])
+ g = df.groupby("A")
+ result = g.B.nth(0, dropna="all")
+ expected = df.B.iloc[[1, 2]]
+ tm.assert_series_equal(result, expected)
+
+ # test multiple nth values
+ df = DataFrame([[1, np.nan], [1, 3], [1, 4], [5, 6], [5, 7]], columns=["A", "B"])
+ g = df.groupby("A")
+
+ tm.assert_frame_equal(g.nth(0), df.iloc[[0, 3]])
+ tm.assert_frame_equal(g.nth([0]), df.iloc[[0, 3]])
+ tm.assert_frame_equal(g.nth([0, 1]), df.iloc[[0, 1, 3, 4]])
+ tm.assert_frame_equal(g.nth([0, -1]), df.iloc[[0, 2, 3, 4]])
+ tm.assert_frame_equal(g.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]])
+ tm.assert_frame_equal(g.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]])
+ tm.assert_frame_equal(g.nth([2]), df.iloc[[2]])
+ tm.assert_frame_equal(g.nth([3, 4]), df.loc[[]])
+
+ business_dates = pd.date_range(start="4/1/2014", end="6/30/2014", freq="B")
+ df = DataFrame(1, index=business_dates, columns=["a", "b"])
+ # get the first, fourth and last two business days for each month
+ key = [df.index.year, df.index.month]
+ result = df.groupby(key, as_index=False).nth([0, 3, -2, -1])
+ expected_dates = pd.to_datetime(
+ [
+ "2014/4/1",
+ "2014/4/4",
+ "2014/4/29",
+ "2014/4/30",
+ "2014/5/1",
+ "2014/5/6",
+ "2014/5/29",
+ "2014/5/30",
+ "2014/6/2",
+ "2014/6/5",
+ "2014/6/27",
+ "2014/6/30",
+ ]
+ )
+ expected = DataFrame(1, columns=["a", "b"], index=expected_dates)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_nth_multi_grouper(three_group):
+ # PR 9090, related to issue 8979
+ # test nth on multiple groupers
+ grouped = three_group.groupby(["A", "B"])
+ result = grouped.nth(0)
+ expected = three_group.iloc[[0, 3, 4, 7]]
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, expected_first, expected_last",
+ [
+ (
+ {
+ "id": ["A"],
+ "time": Timestamp("2012-02-01 14:00:00", tz="US/Central"),
+ "foo": [1],
+ },
+ {
+ "id": ["A"],
+ "time": Timestamp("2012-02-01 14:00:00", tz="US/Central"),
+ "foo": [1],
+ },
+ {
+ "id": ["A"],
+ "time": Timestamp("2012-02-01 14:00:00", tz="US/Central"),
+ "foo": [1],
+ },
+ ),
+ (
+ {
+ "id": ["A", "B", "A"],
+ "time": [
+ Timestamp("2012-01-01 13:00:00", tz="America/New_York"),
+ Timestamp("2012-02-01 14:00:00", tz="US/Central"),
+ Timestamp("2012-03-01 12:00:00", tz="Europe/London"),
+ ],
+ "foo": [1, 2, 3],
+ },
+ {
+ "id": ["A", "B"],
+ "time": [
+ Timestamp("2012-01-01 13:00:00", tz="America/New_York"),
+ Timestamp("2012-02-01 14:00:00", tz="US/Central"),
+ ],
+ "foo": [1, 2],
+ },
+ {
+ "id": ["A", "B"],
+ "time": [
+ Timestamp("2012-03-01 12:00:00", tz="Europe/London"),
+ Timestamp("2012-02-01 14:00:00", tz="US/Central"),
+ ],
+ "foo": [3, 2],
+ },
+ ),
+ ],
+)
+def test_first_last_tz(data, expected_first, expected_last):
+ # GH15884
+ # Test that the timezone is retained when calling first
+ # or last on groupby with as_index=False
+
+ df = DataFrame(data)
+
+ result = df.groupby("id", as_index=False).first()
+ expected = DataFrame(expected_first)
+ cols = ["id", "time", "foo"]
+ tm.assert_frame_equal(result[cols], expected[cols])
+
+ result = df.groupby("id", as_index=False)["time"].first()
+ tm.assert_frame_equal(result, expected[["id", "time"]])
+
+ result = df.groupby("id", as_index=False).last()
+ expected = DataFrame(expected_last)
+ cols = ["id", "time", "foo"]
+ tm.assert_frame_equal(result[cols], expected[cols])
+
+ result = df.groupby("id", as_index=False)["time"].last()
+ tm.assert_frame_equal(result, expected[["id", "time"]])
+
+
+@pytest.mark.parametrize(
+ "method, ts, alpha",
+ [
+ ["first", Timestamp("2013-01-01", tz="US/Eastern"), "a"],
+ ["last", Timestamp("2013-01-02", tz="US/Eastern"), "b"],
+ ],
+)
+def test_first_last_tz_multi_column(method, ts, alpha):
+ # GH 21603
+ category_string = Series(list("abc")).astype("category")
+ df = DataFrame(
+ {
+ "group": [1, 1, 2],
+ "category_string": category_string,
+ "datetimetz": pd.date_range("20130101", periods=3, tz="US/Eastern"),
+ }
+ )
+ result = getattr(df.groupby("group"), method)()
+ expected = DataFrame(
+ {
+ "category_string": pd.Categorical(
+ [alpha, "c"], dtype=category_string.dtype
+ ),
+ "datetimetz": [ts, Timestamp("2013-01-03", tz="US/Eastern")],
+ },
+ index=Index([1, 2], name="group"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "values",
+ [
+ pd.array([True, False], dtype="boolean"),
+ pd.array([1, 2], dtype="Int64"),
+ pd.to_datetime(["2020-01-01", "2020-02-01"]),
+ pd.to_timedelta([1, 2], unit="D"),
+ ],
+)
+@pytest.mark.parametrize("function", ["first", "last", "min", "max"])
+def test_first_last_extension_array_keeps_dtype(values, function):
+ # https://github.com/pandas-dev/pandas/issues/33071
+ # https://github.com/pandas-dev/pandas/issues/32194
+ df = DataFrame({"a": [1, 2], "b": values})
+ grouped = df.groupby("a")
+ idx = Index([1, 2], name="a")
+ expected_series = Series(values, name="b", index=idx)
+ expected_frame = DataFrame({"b": values}, index=idx)
+
+ result_series = getattr(grouped["b"], function)()
+ tm.assert_series_equal(result_series, expected_series)
+
+ result_frame = grouped.agg({"b": function})
+ tm.assert_frame_equal(result_frame, expected_frame)
+
+
+def test_nth_multi_index_as_expected():
+ # PR 9090, related to issue 8979
+ # test nth on MultiIndex
+ three_group = DataFrame(
+ {
+ "A": [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ "foo",
+ "foo",
+ "foo",
+ ],
+ "B": [
+ "one",
+ "one",
+ "one",
+ "two",
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "two",
+ "one",
+ ],
+ "C": [
+ "dull",
+ "dull",
+ "shiny",
+ "dull",
+ "dull",
+ "shiny",
+ "shiny",
+ "dull",
+ "shiny",
+ "shiny",
+ "shiny",
+ ],
+ }
+ )
+ grouped = three_group.groupby(["A", "B"])
+ result = grouped.nth(0)
+ expected = three_group.iloc[[0, 3, 4, 7]]
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "op, n, expected_rows",
+ [
+ ("head", -1, [0]),
+ ("head", 0, []),
+ ("head", 1, [0, 2]),
+ ("head", 7, [0, 1, 2]),
+ ("tail", -1, [1]),
+ ("tail", 0, []),
+ ("tail", 1, [1, 2]),
+ ("tail", 7, [0, 1, 2]),
+ ],
+)
+@pytest.mark.parametrize("columns", [None, [], ["A"], ["B"], ["A", "B"]])
+@pytest.mark.parametrize("as_index", [True, False])
+def test_groupby_head_tail(op, n, expected_rows, columns, as_index):
+ df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
+ g = df.groupby("A", as_index=as_index)
+ expected = df.iloc[expected_rows]
+ if columns is not None:
+ g = g[columns]
+ expected = expected[columns]
+ result = getattr(g, op)(n)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "op, n, expected_cols",
+ [
+ ("head", -1, [0]),
+ ("head", 0, []),
+ ("head", 1, [0, 2]),
+ ("head", 7, [0, 1, 2]),
+ ("tail", -1, [1]),
+ ("tail", 0, []),
+ ("tail", 1, [1, 2]),
+ ("tail", 7, [0, 1, 2]),
+ ],
+)
+def test_groupby_head_tail_axis_1(op, n, expected_cols):
+ # GH 9772
+ df = DataFrame(
+ [[1, 2, 3], [1, 4, 5], [2, 6, 7], [3, 8, 9]], columns=["A", "B", "C"]
+ )
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ g = df.groupby([0, 0, 1], axis=1)
+ expected = df.iloc[:, expected_cols]
+ result = getattr(g, op)(n)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_group_selection_cache():
+ # GH 12839 nth, head, and tail should return same result consistently
+ df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
+ expected = df.iloc[[0, 2]]
+
+ g = df.groupby("A")
+ result1 = g.head(n=2)
+ result2 = g.nth(0)
+ tm.assert_frame_equal(result1, df)
+ tm.assert_frame_equal(result2, expected)
+
+ g = df.groupby("A")
+ result1 = g.tail(n=2)
+ result2 = g.nth(0)
+ tm.assert_frame_equal(result1, df)
+ tm.assert_frame_equal(result2, expected)
+
+ g = df.groupby("A")
+ result1 = g.nth(0)
+ result2 = g.head(n=2)
+ tm.assert_frame_equal(result1, expected)
+ tm.assert_frame_equal(result2, df)
+
+ g = df.groupby("A")
+ result1 = g.nth(0)
+ result2 = g.tail(n=2)
+ tm.assert_frame_equal(result1, expected)
+ tm.assert_frame_equal(result2, df)
+
+
+def test_nth_empty():
+ # GH 16064
+ df = DataFrame(index=[0], columns=["a", "b", "c"])
+ result = df.groupby("a").nth(10)
+ expected = df.iloc[:0]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(["a", "b"]).nth(10)
+ expected = df.iloc[:0]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_nth_column_order():
+ # GH 20760
+ # Check that nth preserves column order
+ df = DataFrame(
+ [[1, "b", 100], [1, "a", 50], [1, "a", np.nan], [2, "c", 200], [2, "d", 150]],
+ columns=["A", "C", "B"],
+ )
+ result = df.groupby("A").nth(0)
+ expected = df.iloc[[0, 3]]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("A").nth(-1, dropna="any")
+ expected = df.iloc[[1, 4]]
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dropna", [None, "any", "all"])
+def test_nth_nan_in_grouper(dropna):
+ # GH 26011
+ df = DataFrame(
+ {
+ "a": [np.nan, "a", np.nan, "b", np.nan],
+ "b": [0, 2, 4, 6, 8],
+ "c": [1, 3, 5, 7, 9],
+ }
+ )
+ result = df.groupby("a").nth(0, dropna=dropna)
+ expected = df.iloc[[1, 3]]
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dropna", [None, "any", "all"])
+def test_nth_nan_in_grouper_series(dropna):
+ # GH 26454
+ df = DataFrame(
+ {
+ "a": [np.nan, "a", np.nan, "b", np.nan],
+ "b": [0, 2, 4, 6, 8],
+ }
+ )
+ result = df.groupby("a")["b"].nth(0, dropna=dropna)
+ expected = df["b"].iloc[[1, 3]]
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_first_categorical_and_datetime_data_nat():
+ # GH 20520
+ df = DataFrame(
+ {
+ "group": ["first", "first", "second", "third", "third"],
+ "time": 5 * [np.datetime64("NaT")],
+ "categories": Series(["a", "b", "c", "a", "b"], dtype="category"),
+ }
+ )
+ result = df.groupby("group").first()
+ expected = DataFrame(
+ {
+ "time": 3 * [np.datetime64("NaT")],
+ "categories": Series(["a", "c", "a"]).astype(
+ pd.CategoricalDtype(["a", "b", "c"])
+ ),
+ }
+ )
+ expected.index = Index(["first", "second", "third"], name="group")
+ tm.assert_frame_equal(result, expected)
+
+
+def test_first_multi_key_groupby_categorical():
+ # GH 22512
+ df = DataFrame(
+ {
+ "A": [1, 1, 1, 2, 2],
+ "B": [100, 100, 200, 100, 100],
+ "C": ["apple", "orange", "mango", "mango", "orange"],
+ "D": ["jupiter", "mercury", "mars", "venus", "venus"],
+ }
+ )
+ df = df.astype({"D": "category"})
+ result = df.groupby(by=["A", "B"]).first()
+ expected = DataFrame(
+ {
+ "C": ["apple", "mango", "mango"],
+ "D": Series(["jupiter", "mars", "venus"]).astype(
+ pd.CategoricalDtype(["jupiter", "mars", "mercury", "venus"])
+ ),
+ }
+ )
+ expected.index = MultiIndex.from_tuples(
+ [(1, 100), (1, 200), (2, 100)], names=["A", "B"]
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["first", "last", "nth"])
+def test_groupby_last_first_nth_with_none(method, nulls_fixture):
+ # GH29645
+ expected = Series(["y"])
+ data = Series(
+ [nulls_fixture, nulls_fixture, nulls_fixture, "y", nulls_fixture],
+ index=[0, 0, 0, 0, 0],
+ ).groupby(level=0)
+
+ if method == "nth":
+ result = getattr(data, method)(3)
+ else:
+ result = getattr(data, method)()
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "arg, expected_rows",
+ [
+ [slice(None, 3, 2), [0, 1, 4, 5]],
+ [slice(None, -2), [0, 2, 5]],
+ [[slice(None, 2), slice(-2, None)], [0, 1, 2, 3, 4, 6, 7]],
+ [[0, 1, slice(-2, None)], [0, 1, 2, 3, 4, 6, 7]],
+ ],
+)
+def test_slice(slice_test_df, slice_test_grouped, arg, expected_rows):
+ # Test slices GH #42947
+
+ result = slice_test_grouped.nth[arg]
+ equivalent = slice_test_grouped.nth(arg)
+ expected = slice_test_df.iloc[expected_rows]
+
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(equivalent, expected)
+
+
+def test_nth_indexed(slice_test_df, slice_test_grouped):
+ # Test index notation GH #44688
+
+ result = slice_test_grouped.nth[0, 1, -2:]
+ equivalent = slice_test_grouped.nth([0, 1, slice(-2, None)])
+ expected = slice_test_df.iloc[[0, 1, 2, 3, 4, 6, 7]]
+
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(equivalent, expected)
+
+
+def test_invalid_argument(slice_test_grouped):
+ # Test for error on invalid argument
+
+ with pytest.raises(TypeError, match="Invalid index"):
+ slice_test_grouped.nth(3.14)
+
+
+def test_negative_step(slice_test_grouped):
+ # Test for error on negative slice step
+
+ with pytest.raises(ValueError, match="Invalid step"):
+ slice_test_grouped.nth(slice(None, None, -1))
+
+
+def test_np_ints(slice_test_df, slice_test_grouped):
+ # Test np ints work
+
+ result = slice_test_grouped.nth(np.array([0, 1]))
+ expected = slice_test_df.iloc[[0, 1, 2, 3, 4]]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_nth_with_column_axis():
+ # GH43926
+ df = DataFrame(
+ [
+ [4, 5, 6],
+ [8, 8, 7],
+ ],
+ index=["z", "y"],
+ columns=["C", "B", "A"],
+ )
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby(df.iloc[1], axis=1)
+ result = gb.nth(0)
+ expected = df.iloc[:, [0, 2]]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_nth_interval():
+ # GH#24205
+ idx_result = MultiIndex(
+ [
+ pd.CategoricalIndex([pd.Interval(0, 1), pd.Interval(1, 2)]),
+ pd.CategoricalIndex([pd.Interval(0, 10), pd.Interval(10, 20)]),
+ ],
+ [[0, 0, 0, 1, 1], [0, 1, 1, 0, -1]],
+ )
+ df_result = DataFrame({"col": range(len(idx_result))}, index=idx_result)
+ result = df_result.groupby(level=[0, 1], observed=False).nth(0)
+ val_expected = [0, 1, 3]
+ idx_expected = MultiIndex(
+ [
+ pd.CategoricalIndex([pd.Interval(0, 1), pd.Interval(1, 2)]),
+ pd.CategoricalIndex([pd.Interval(0, 10), pd.Interval(10, 20)]),
+ ],
+ [[0, 0, 1], [0, 1, 0]],
+ )
+ expected = DataFrame(val_expected, index=idx_expected, columns=["col"])
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "start, stop, expected_values, expected_columns",
+ [
+ (None, None, [0, 1, 2, 3, 4], list("ABCDE")),
+ (None, 1, [0, 3], list("AD")),
+ (None, 9, [0, 1, 2, 3, 4], list("ABCDE")),
+ (None, -1, [0, 1, 3], list("ABD")),
+ (1, None, [1, 2, 4], list("BCE")),
+ (1, -1, [1], list("B")),
+ (-1, None, [2, 4], list("CE")),
+ (-1, 2, [4], list("E")),
+ ],
+)
+@pytest.mark.parametrize("method", ["call", "index"])
+def test_nth_slices_with_column_axis(
+ start, stop, expected_values, expected_columns, method
+):
+ df = DataFrame([range(5)], columns=[list("ABCDE")])
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby([5, 5, 5, 6, 6], axis=1)
+ result = {
+ "call": lambda start, stop: gb.nth(slice(start, stop)),
+ "index": lambda start, stop: gb.nth[start:stop],
+ }[method](start, stop)
+ expected = DataFrame([expected_values], columns=[expected_columns])
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.filterwarnings(
+ "ignore:invalid value encountered in remainder:RuntimeWarning"
+)
+def test_head_tail_dropna_true():
+ # GH#45089
+ df = DataFrame(
+ [["a", "z"], ["b", np.nan], ["c", np.nan], ["c", np.nan]], columns=["X", "Y"]
+ )
+ expected = DataFrame([["a", "z"]], columns=["X", "Y"])
+
+ result = df.groupby(["X", "Y"]).head(n=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(["X", "Y"]).tail(n=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(["X", "Y"]).nth(n=0)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_head_tail_dropna_false():
+ # GH#45089
+ df = DataFrame([["a", "z"], ["b", np.nan], ["c", np.nan]], columns=["X", "Y"])
+ expected = DataFrame([["a", "z"], ["b", np.nan], ["c", np.nan]], columns=["X", "Y"])
+
+ result = df.groupby(["X", "Y"], dropna=False).head(n=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(["X", "Y"], dropna=False).tail(n=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(["X", "Y"], dropna=False).nth(n=0)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("selection", ("b", ["b"], ["b", "c"]))
+@pytest.mark.parametrize("dropna", ["any", "all", None])
+def test_nth_after_selection(selection, dropna):
+ # GH#11038, GH#53518
+ df = DataFrame(
+ {
+ "a": [1, 1, 2],
+ "b": [np.nan, 3, 4],
+ "c": [5, 6, 7],
+ }
+ )
+ gb = df.groupby("a")[selection]
+ result = gb.nth(0, dropna=dropna)
+ if dropna == "any" or (dropna == "all" and selection != ["b", "c"]):
+ locs = [1, 2]
+ else:
+ locs = [0, 2]
+ expected = df.loc[locs, selection]
+ tm.assert_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_numba.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_numba.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee7d3424724932befa772e47162e032e28f2cd1d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_numba.py
@@ -0,0 +1,80 @@
+import pytest
+
+from pandas import (
+ DataFrame,
+ Series,
+ option_context,
+)
+import pandas._testing as tm
+
+pytestmark = pytest.mark.single_cpu
+
+pytest.importorskip("numba")
+
+
+@pytest.mark.filterwarnings("ignore")
+# Filter warnings when parallel=True and the function can't be parallelized by Numba
+class TestEngine:
+ def test_cython_vs_numba_frame(
+ self, sort, nogil, parallel, nopython, numba_supported_reductions
+ ):
+ func, kwargs = numba_supported_reductions
+ df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)})
+ engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
+ gb = df.groupby("a", sort=sort)
+ result = getattr(gb, func)(
+ engine="numba", engine_kwargs=engine_kwargs, **kwargs
+ )
+ expected = getattr(gb, func)(**kwargs)
+ tm.assert_frame_equal(result, expected)
+
+ def test_cython_vs_numba_getitem(
+ self, sort, nogil, parallel, nopython, numba_supported_reductions
+ ):
+ func, kwargs = numba_supported_reductions
+ df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)})
+ engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
+ gb = df.groupby("a", sort=sort)["c"]
+ result = getattr(gb, func)(
+ engine="numba", engine_kwargs=engine_kwargs, **kwargs
+ )
+ expected = getattr(gb, func)(**kwargs)
+ tm.assert_series_equal(result, expected)
+
+ def test_cython_vs_numba_series(
+ self, sort, nogil, parallel, nopython, numba_supported_reductions
+ ):
+ func, kwargs = numba_supported_reductions
+ ser = Series(range(3), index=[1, 2, 1], name="foo")
+ engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
+ gb = ser.groupby(level=0, sort=sort)
+ result = getattr(gb, func)(
+ engine="numba", engine_kwargs=engine_kwargs, **kwargs
+ )
+ expected = getattr(gb, func)(**kwargs)
+ tm.assert_series_equal(result, expected)
+
+ def test_as_index_false_unsupported(self, numba_supported_reductions):
+ func, kwargs = numba_supported_reductions
+ df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)})
+ gb = df.groupby("a", as_index=False)
+ with pytest.raises(NotImplementedError, match="as_index=False"):
+ getattr(gb, func)(engine="numba", **kwargs)
+
+ def test_axis_1_unsupported(self, numba_supported_reductions):
+ func, kwargs = numba_supported_reductions
+ df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)})
+ gb = df.groupby("a", axis=1)
+ with pytest.raises(NotImplementedError, match="axis=1"):
+ getattr(gb, func)(engine="numba", **kwargs)
+
+ def test_no_engine_doesnt_raise(self):
+ # GH55520
+ df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)})
+ gb = df.groupby("a")
+ # Make sure behavior of functions w/out engine argument don't raise
+ # when the global use_numba option is set
+ with option_context("compute.use_numba", True):
+ res = gb.agg({"b": "first"})
+ expected = gb.agg({"b": "first"})
+ tm.assert_frame_equal(res, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_nunique.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_nunique.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c9e32d9ce226d0e94c59e53b0c5e1f538a75f8e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_nunique.py
@@ -0,0 +1,190 @@
+import datetime as dt
+from string import ascii_lowercase
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ NaT,
+ Series,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize("sort", [False, True])
+@pytest.mark.parametrize("dropna", [False, True])
+@pytest.mark.parametrize("as_index", [True, False])
+@pytest.mark.parametrize("with_nan", [True, False])
+@pytest.mark.parametrize("keys", [["joe"], ["joe", "jim"]])
+def test_series_groupby_nunique(sort, dropna, as_index, with_nan, keys):
+ n = 100
+ m = 10
+ days = date_range("2015-08-23", periods=10)
+ df = DataFrame(
+ {
+ "jim": np.random.default_rng(2).choice(list(ascii_lowercase), n),
+ "joe": np.random.default_rng(2).choice(days, n),
+ "julie": np.random.default_rng(2).integers(0, m, n),
+ }
+ )
+ if with_nan:
+ df = df.astype({"julie": float}) # Explicit cast to avoid implicit cast below
+ df.loc[1::17, "jim"] = None
+ df.loc[3::37, "joe"] = None
+ df.loc[7::19, "julie"] = None
+ df.loc[8::19, "julie"] = None
+ df.loc[9::19, "julie"] = None
+ original_df = df.copy()
+ gr = df.groupby(keys, as_index=as_index, sort=sort)
+ left = gr["julie"].nunique(dropna=dropna)
+
+ gr = df.groupby(keys, as_index=as_index, sort=sort)
+ right = gr["julie"].apply(Series.nunique, dropna=dropna)
+ if not as_index:
+ right = right.reset_index(drop=True)
+
+ if as_index:
+ tm.assert_series_equal(left, right, check_names=False)
+ else:
+ tm.assert_frame_equal(left, right, check_names=False)
+ tm.assert_frame_equal(df, original_df)
+
+
+def test_nunique():
+ df = DataFrame({"A": list("abbacc"), "B": list("abxacc"), "C": list("abbacx")})
+
+ expected = DataFrame({"A": list("abc"), "B": [1, 2, 1], "C": [1, 1, 2]})
+ result = df.groupby("A", as_index=False).nunique()
+ tm.assert_frame_equal(result, expected)
+
+ # as_index
+ expected.index = list("abc")
+ expected.index.name = "A"
+ expected = expected.drop(columns="A")
+ result = df.groupby("A").nunique()
+ tm.assert_frame_equal(result, expected)
+
+ # with na
+ result = df.replace({"x": None}).groupby("A").nunique(dropna=False)
+ tm.assert_frame_equal(result, expected)
+
+ # dropna
+ expected = DataFrame({"B": [1] * 3, "C": [1] * 3}, index=list("abc"))
+ expected.index.name = "A"
+ result = df.replace({"x": None}).groupby("A").nunique()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_nunique_with_object():
+ # GH 11077
+ data = DataFrame(
+ [
+ [100, 1, "Alice"],
+ [200, 2, "Bob"],
+ [300, 3, "Charlie"],
+ [-400, 4, "Dan"],
+ [500, 5, "Edith"],
+ ],
+ columns=["amount", "id", "name"],
+ )
+
+ result = data.groupby(["id", "amount"])["name"].nunique()
+ index = MultiIndex.from_arrays([data.id, data.amount])
+ expected = Series([1] * 5, name="name", index=index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_nunique_with_empty_series():
+ # GH 12553
+ data = Series(name="name", dtype=object)
+ result = data.groupby(level=0).nunique()
+ expected = Series(name="name", dtype="int64")
+ tm.assert_series_equal(result, expected)
+
+
+def test_nunique_with_timegrouper():
+ # GH 13453
+ test = DataFrame(
+ {
+ "time": [
+ Timestamp("2016-06-28 09:35:35"),
+ Timestamp("2016-06-28 16:09:30"),
+ Timestamp("2016-06-28 16:46:28"),
+ ],
+ "data": ["1", "2", "3"],
+ }
+ ).set_index("time")
+ result = test.groupby(pd.Grouper(freq="h"))["data"].nunique()
+ expected = test.groupby(pd.Grouper(freq="h"))["data"].apply(Series.nunique)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "key, data, dropna, expected",
+ [
+ (
+ ["x", "x", "x"],
+ [Timestamp("2019-01-01"), NaT, Timestamp("2019-01-01")],
+ True,
+ Series([1], index=pd.Index(["x"], name="key"), name="data"),
+ ),
+ (
+ ["x", "x", "x"],
+ [dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1)],
+ True,
+ Series([1], index=pd.Index(["x"], name="key"), name="data"),
+ ),
+ (
+ ["x", "x", "x", "y", "y"],
+ [dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1)],
+ False,
+ Series([2, 2], index=pd.Index(["x", "y"], name="key"), name="data"),
+ ),
+ (
+ ["x", "x", "x", "x", "y"],
+ [dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1)],
+ False,
+ Series([2, 1], index=pd.Index(["x", "y"], name="key"), name="data"),
+ ),
+ ],
+)
+def test_nunique_with_NaT(key, data, dropna, expected):
+ # GH 27951
+ df = DataFrame({"key": key, "data": data})
+ result = df.groupby(["key"])["data"].nunique(dropna=dropna)
+ tm.assert_series_equal(result, expected)
+
+
+def test_nunique_preserves_column_level_names():
+ # GH 23222
+ test = DataFrame([1, 2, 2], columns=pd.Index(["A"], name="level_0"))
+ result = test.groupby([0, 0, 0]).nunique()
+ expected = DataFrame([2], index=np.array([0]), columns=test.columns)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_nunique_transform_with_datetime():
+ # GH 35109 - transform with nunique on datetimes results in integers
+ df = DataFrame(date_range("2008-12-31", "2009-01-02"), columns=["date"])
+ result = df.groupby([0, 0, 1])["date"].transform("nunique")
+ expected = Series([2, 2, 1], name="date")
+ tm.assert_series_equal(result, expected)
+
+
+def test_empty_categorical(observed):
+ # GH#21334
+ cat = Series([1]).astype("category")
+ ser = cat[:0]
+ gb = ser.groupby(ser, observed=observed)
+ result = gb.nunique()
+ if observed:
+ expected = Series([], index=cat[:0], dtype="int64")
+ else:
+ expected = Series([0], index=cat, dtype="int64")
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_pipe.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_pipe.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d5c1625b8ab466677280de30562eb13c53376d7
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_pipe.py
@@ -0,0 +1,80 @@
+import numpy as np
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+)
+import pandas._testing as tm
+
+
+def test_pipe():
+ # Test the pipe method of DataFrameGroupBy.
+ # Issue #17871
+
+ random_state = np.random.default_rng(2)
+
+ df = DataFrame(
+ {
+ "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
+ "B": random_state.standard_normal(8),
+ "C": random_state.standard_normal(8),
+ }
+ )
+
+ def f(dfgb):
+ return dfgb.B.max() - dfgb.C.min().min()
+
+ def square(srs):
+ return srs**2
+
+ # Note that the transformations are
+ # GroupBy -> Series
+ # Series -> Series
+ # This then chains the GroupBy.pipe and the
+ # NDFrame.pipe methods
+ result = df.groupby("A").pipe(f).pipe(square)
+
+ index = Index(["bar", "foo"], dtype="object", name="A")
+ expected = pd.Series([3.749306591013693, 6.717707873081384], name="B", index=index)
+
+ tm.assert_series_equal(expected, result)
+
+
+def test_pipe_args():
+ # Test passing args to the pipe method of DataFrameGroupBy.
+ # Issue #17871
+
+ df = DataFrame(
+ {
+ "group": ["A", "A", "B", "B", "C"],
+ "x": [1.0, 2.0, 3.0, 2.0, 5.0],
+ "y": [10.0, 100.0, 1000.0, -100.0, -1000.0],
+ }
+ )
+
+ def f(dfgb, arg1):
+ filtered = dfgb.filter(lambda grp: grp.y.mean() > arg1, dropna=False)
+ return filtered.groupby("group")
+
+ def g(dfgb, arg2):
+ return dfgb.sum() / dfgb.sum().sum() + arg2
+
+ def h(df, arg3):
+ return df.x + df.y - arg3
+
+ result = df.groupby("group").pipe(f, 0).pipe(g, 10).pipe(h, 100)
+
+ # Assert the results here
+ index = Index(["A", "B"], name="group")
+ expected = pd.Series([-79.5160891089, -78.4839108911], index=index)
+
+ tm.assert_series_equal(result, expected)
+
+ # test SeriesGroupby.pipe
+ ser = pd.Series([1, 1, 2, 2, 3, 3])
+ result = ser.groupby(ser).pipe(lambda grp: grp.sum() * grp.count())
+
+ expected = pd.Series([4, 8, 12], index=Index([1, 2, 3], dtype=np.int64))
+
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_quantile.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_quantile.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a12f9a8e0e35643c9c481adb5b37484d7779125
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_quantile.py
@@ -0,0 +1,503 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize(
+ "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"]
+)
+@pytest.mark.parametrize(
+ "a_vals,b_vals",
+ [
+ # Ints
+ ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]),
+ ([1, 2, 3, 4], [4, 3, 2, 1]),
+ ([1, 2, 3, 4, 5], [4, 3, 2, 1]),
+ # Floats
+ ([1.0, 2.0, 3.0, 4.0, 5.0], [5.0, 4.0, 3.0, 2.0, 1.0]),
+ # Missing data
+ ([1.0, np.nan, 3.0, np.nan, 5.0], [5.0, np.nan, 3.0, np.nan, 1.0]),
+ ([np.nan, 4.0, np.nan, 2.0, np.nan], [np.nan, 4.0, np.nan, 2.0, np.nan]),
+ # Timestamps
+ (
+ pd.date_range("1/1/18", freq="D", periods=5),
+ pd.date_range("1/1/18", freq="D", periods=5)[::-1],
+ ),
+ (
+ pd.date_range("1/1/18", freq="D", periods=5).as_unit("s"),
+ pd.date_range("1/1/18", freq="D", periods=5)[::-1].as_unit("s"),
+ ),
+ # All NA
+ ([np.nan] * 5, [np.nan] * 5),
+ ],
+)
+@pytest.mark.parametrize("q", [0, 0.25, 0.5, 0.75, 1])
+def test_quantile(interpolation, a_vals, b_vals, q, request):
+ if (
+ interpolation == "nearest"
+ and q == 0.5
+ and isinstance(b_vals, list)
+ and b_vals == [4, 3, 2, 1]
+ ):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="Unclear numpy expectation for nearest "
+ "result with equidistant data"
+ )
+ )
+ all_vals = pd.concat([pd.Series(a_vals), pd.Series(b_vals)])
+
+ a_expected = pd.Series(a_vals).quantile(q, interpolation=interpolation)
+ b_expected = pd.Series(b_vals).quantile(q, interpolation=interpolation)
+
+ df = DataFrame({"key": ["a"] * len(a_vals) + ["b"] * len(b_vals), "val": all_vals})
+
+ expected = DataFrame(
+ [a_expected, b_expected], columns=["val"], index=Index(["a", "b"], name="key")
+ )
+ if all_vals.dtype.kind == "M" and expected.dtypes.values[0].kind == "M":
+ # TODO(non-nano): this should be unnecessary once array_to_datetime
+ # correctly infers non-nano from Timestamp.unit
+ expected = expected.astype(all_vals.dtype)
+ result = df.groupby("key").quantile(q, interpolation=interpolation)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_array():
+ # https://github.com/pandas-dev/pandas/issues/27526
+ df = DataFrame({"A": [0, 1, 2, 3, 4]})
+ key = np.array([0, 0, 1, 1, 1], dtype=np.int64)
+ result = df.groupby(key).quantile([0.25])
+
+ index = pd.MultiIndex.from_product([[0, 1], [0.25]])
+ expected = DataFrame({"A": [0.25, 2.50]}, index=index)
+ tm.assert_frame_equal(result, expected)
+
+ df = DataFrame({"A": [0, 1, 2, 3], "B": [4, 5, 6, 7]})
+ index = pd.MultiIndex.from_product([[0, 1], [0.25, 0.75]])
+
+ key = np.array([0, 0, 1, 1], dtype=np.int64)
+ result = df.groupby(key).quantile([0.25, 0.75])
+ expected = DataFrame(
+ {"A": [0.25, 0.75, 2.25, 2.75], "B": [4.25, 4.75, 6.25, 6.75]}, index=index
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_array2():
+ # https://github.com/pandas-dev/pandas/pull/28085#issuecomment-524066959
+ arr = np.random.default_rng(2).integers(0, 5, size=(10, 3), dtype=np.int64)
+ df = DataFrame(arr, columns=list("ABC"))
+ result = df.groupby("A").quantile([0.3, 0.7])
+ expected = DataFrame(
+ {
+ "B": [2.0, 2.0, 2.3, 2.7, 0.3, 0.7, 3.2, 4.0, 0.3, 0.7],
+ "C": [1.0, 1.0, 1.9, 3.0999999999999996, 0.3, 0.7, 2.6, 3.0, 1.2, 2.8],
+ },
+ index=pd.MultiIndex.from_product(
+ [[0, 1, 2, 3, 4], [0.3, 0.7]], names=["A", None]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_array_no_sort():
+ df = DataFrame({"A": [0, 1, 2], "B": [3, 4, 5]})
+ key = np.array([1, 0, 1], dtype=np.int64)
+ result = df.groupby(key, sort=False).quantile([0.25, 0.5, 0.75])
+ expected = DataFrame(
+ {"A": [0.5, 1.0, 1.5, 1.0, 1.0, 1.0], "B": [3.5, 4.0, 4.5, 4.0, 4.0, 4.0]},
+ index=pd.MultiIndex.from_product([[1, 0], [0.25, 0.5, 0.75]]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(key, sort=False).quantile([0.75, 0.25])
+ expected = DataFrame(
+ {"A": [1.5, 0.5, 1.0, 1.0], "B": [4.5, 3.5, 4.0, 4.0]},
+ index=pd.MultiIndex.from_product([[1, 0], [0.75, 0.25]]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_array_multiple_levels():
+ df = DataFrame(
+ {"A": [0, 1, 2], "B": [3, 4, 5], "c": ["a", "a", "a"], "d": ["a", "a", "b"]}
+ )
+ result = df.groupby(["c", "d"]).quantile([0.25, 0.75])
+ index = pd.MultiIndex.from_tuples(
+ [("a", "a", 0.25), ("a", "a", 0.75), ("a", "b", 0.25), ("a", "b", 0.75)],
+ names=["c", "d", None],
+ )
+ expected = DataFrame(
+ {"A": [0.25, 0.75, 2.0, 2.0], "B": [3.25, 3.75, 5.0, 5.0]}, index=index
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("frame_size", [(2, 3), (100, 10)])
+@pytest.mark.parametrize("groupby", [[0], [0, 1]])
+@pytest.mark.parametrize("q", [[0.5, 0.6]])
+def test_groupby_quantile_with_arraylike_q_and_int_columns(frame_size, groupby, q):
+ # GH30289
+ nrow, ncol = frame_size
+ df = DataFrame(np.array([ncol * [_ % 4] for _ in range(nrow)]), columns=range(ncol))
+
+ idx_levels = [np.arange(min(nrow, 4))] * len(groupby) + [q]
+ idx_codes = [[x for x in range(min(nrow, 4)) for _ in q]] * len(groupby) + [
+ list(range(len(q))) * min(nrow, 4)
+ ]
+ expected_index = pd.MultiIndex(
+ levels=idx_levels, codes=idx_codes, names=groupby + [None]
+ )
+ expected_values = [
+ [float(x)] * (ncol - len(groupby)) for x in range(min(nrow, 4)) for _ in q
+ ]
+ expected_columns = [x for x in range(ncol) if x not in groupby]
+ expected = DataFrame(
+ expected_values, index=expected_index, columns=expected_columns
+ )
+ result = df.groupby(groupby).quantile(q)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_raises():
+ df = DataFrame([["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"])
+
+ with pytest.raises(TypeError, match="cannot be performed against 'object' dtypes"):
+ df.groupby("key").quantile()
+
+
+def test_quantile_out_of_bounds_q_raises():
+ # https://github.com/pandas-dev/pandas/issues/27470
+ df = DataFrame({"a": [0, 0, 0, 1, 1, 1], "b": range(6)})
+ g = df.groupby([0, 0, 0, 1, 1, 1])
+ with pytest.raises(ValueError, match="Got '50.0' instead"):
+ g.quantile(50)
+
+ with pytest.raises(ValueError, match="Got '-1.0' instead"):
+ g.quantile(-1)
+
+
+def test_quantile_missing_group_values_no_segfaults():
+ # GH 28662
+ data = np.array([1.0, np.nan, 1.0])
+ df = DataFrame({"key": data, "val": range(3)})
+
+ # Random segfaults; would have been guaranteed in loop
+ grp = df.groupby("key")
+ for _ in range(100):
+ grp.quantile()
+
+
+@pytest.mark.parametrize(
+ "key, val, expected_key, expected_val",
+ [
+ ([1.0, np.nan, 3.0, np.nan], range(4), [1.0, 3.0], [0.0, 2.0]),
+ ([1.0, np.nan, 2.0, 2.0], range(4), [1.0, 2.0], [0.0, 2.5]),
+ (["a", "b", "b", np.nan], range(4), ["a", "b"], [0, 1.5]),
+ ([0], [42], [0], [42.0]),
+ ([], [], np.array([], dtype="float64"), np.array([], dtype="float64")),
+ ],
+)
+def test_quantile_missing_group_values_correct_results(
+ key, val, expected_key, expected_val
+):
+ # GH 28662, GH 33200, GH 33569
+ df = DataFrame({"key": key, "val": val})
+
+ expected = DataFrame(
+ expected_val, index=Index(expected_key, name="key"), columns=["val"]
+ )
+
+ grp = df.groupby("key")
+
+ result = grp.quantile(0.5)
+ tm.assert_frame_equal(result, expected)
+
+ result = grp.quantile()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "values",
+ [
+ pd.array([1, 0, None] * 2, dtype="Int64"),
+ pd.array([True, False, None] * 2, dtype="boolean"),
+ ],
+)
+@pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0]])
+def test_groupby_quantile_nullable_array(values, q):
+ # https://github.com/pandas-dev/pandas/issues/33136
+ df = DataFrame({"a": ["x"] * 3 + ["y"] * 3, "b": values})
+ result = df.groupby("a")["b"].quantile(q)
+
+ if isinstance(q, list):
+ idx = pd.MultiIndex.from_product((["x", "y"], q), names=["a", None])
+ true_quantiles = [0.0, 0.5, 1.0]
+ else:
+ idx = Index(["x", "y"], name="a")
+ true_quantiles = [0.5]
+
+ expected = pd.Series(true_quantiles * 2, index=idx, name="b", dtype="Float64")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0]])
+@pytest.mark.parametrize("numeric_only", [True, False])
+def test_groupby_quantile_raises_on_invalid_dtype(q, numeric_only):
+ df = DataFrame({"a": [1], "b": [2.0], "c": ["x"]})
+ if numeric_only:
+ result = df.groupby("a").quantile(q, numeric_only=numeric_only)
+ expected = df.groupby("a")[["b"]].quantile(q)
+ tm.assert_frame_equal(result, expected)
+ else:
+ with pytest.raises(
+ TypeError, match="'quantile' cannot be performed against 'object' dtypes!"
+ ):
+ df.groupby("a").quantile(q, numeric_only=numeric_only)
+
+
+def test_groupby_quantile_NA_float(any_float_dtype):
+ # GH#42849
+ df = DataFrame({"x": [1, 1], "y": [0.2, np.nan]}, dtype=any_float_dtype)
+ result = df.groupby("x")["y"].quantile(0.5)
+ exp_index = Index([1.0], dtype=any_float_dtype, name="x")
+
+ if any_float_dtype in ["Float32", "Float64"]:
+ expected_dtype = any_float_dtype
+ else:
+ expected_dtype = None
+
+ expected = pd.Series([0.2], dtype=expected_dtype, index=exp_index, name="y")
+ tm.assert_series_equal(result, expected)
+
+ result = df.groupby("x")["y"].quantile([0.5, 0.75])
+ expected = pd.Series(
+ [0.2] * 2,
+ index=pd.MultiIndex.from_product((exp_index, [0.5, 0.75]), names=["x", None]),
+ name="y",
+ dtype=expected_dtype,
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_quantile_NA_int(any_int_ea_dtype):
+ # GH#42849
+ df = DataFrame({"x": [1, 1], "y": [2, 5]}, dtype=any_int_ea_dtype)
+ result = df.groupby("x")["y"].quantile(0.5)
+ expected = pd.Series(
+ [3.5],
+ dtype="Float64",
+ index=Index([1], name="x", dtype=any_int_ea_dtype),
+ name="y",
+ )
+ tm.assert_series_equal(expected, result)
+
+ result = df.groupby("x").quantile(0.5)
+ expected = DataFrame(
+ {"y": 3.5}, dtype="Float64", index=Index([1], name="x", dtype=any_int_ea_dtype)
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "interpolation, val1, val2", [("lower", 2, 2), ("higher", 2, 3), ("nearest", 2, 2)]
+)
+def test_groupby_quantile_all_na_group_masked(
+ interpolation, val1, val2, any_numeric_ea_dtype
+):
+ # GH#37493
+ df = DataFrame(
+ {"a": [1, 1, 1, 2], "b": [1, 2, 3, pd.NA]}, dtype=any_numeric_ea_dtype
+ )
+ result = df.groupby("a").quantile(q=[0.5, 0.7], interpolation=interpolation)
+ expected = DataFrame(
+ {"b": [val1, val2, pd.NA, pd.NA]},
+ dtype=any_numeric_ea_dtype,
+ index=pd.MultiIndex.from_arrays(
+ [pd.Series([1, 1, 2, 2], dtype=any_numeric_ea_dtype), [0.5, 0.7, 0.5, 0.7]],
+ names=["a", None],
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("interpolation", ["midpoint", "linear"])
+def test_groupby_quantile_all_na_group_masked_interp(
+ interpolation, any_numeric_ea_dtype
+):
+ # GH#37493
+ df = DataFrame(
+ {"a": [1, 1, 1, 2], "b": [1, 2, 3, pd.NA]}, dtype=any_numeric_ea_dtype
+ )
+ result = df.groupby("a").quantile(q=[0.5, 0.75], interpolation=interpolation)
+
+ if any_numeric_ea_dtype == "Float32":
+ expected_dtype = any_numeric_ea_dtype
+ else:
+ expected_dtype = "Float64"
+
+ expected = DataFrame(
+ {"b": [2.0, 2.5, pd.NA, pd.NA]},
+ dtype=expected_dtype,
+ index=pd.MultiIndex.from_arrays(
+ [
+ pd.Series([1, 1, 2, 2], dtype=any_numeric_ea_dtype),
+ [0.5, 0.75, 0.5, 0.75],
+ ],
+ names=["a", None],
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["Float64", "Float32"])
+def test_groupby_quantile_allNA_column(dtype):
+ # GH#42849
+ df = DataFrame({"x": [1, 1], "y": [pd.NA] * 2}, dtype=dtype)
+ result = df.groupby("x")["y"].quantile(0.5)
+ expected = pd.Series(
+ [np.nan], dtype=dtype, index=Index([1.0], dtype=dtype), name="y"
+ )
+ expected.index.name = "x"
+ tm.assert_series_equal(expected, result)
+
+
+def test_groupby_timedelta_quantile():
+ # GH: 29485
+ df = DataFrame(
+ {"value": pd.to_timedelta(np.arange(4), unit="s"), "group": [1, 1, 2, 2]}
+ )
+ result = df.groupby("group").quantile(0.99)
+ expected = DataFrame(
+ {
+ "value": [
+ pd.Timedelta("0 days 00:00:00.990000"),
+ pd.Timedelta("0 days 00:00:02.990000"),
+ ]
+ },
+ index=Index([1, 2], name="group"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_columns_groupby_quantile():
+ # GH 33795
+ df = DataFrame(
+ np.arange(12).reshape(3, -1),
+ index=list("XYZ"),
+ columns=pd.Series(list("ABAB"), name="col"),
+ )
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby("col", axis=1)
+ result = gb.quantile(q=[0.8, 0.2])
+ expected = DataFrame(
+ [
+ [1.6, 0.4, 2.6, 1.4],
+ [5.6, 4.4, 6.6, 5.4],
+ [9.6, 8.4, 10.6, 9.4],
+ ],
+ index=list("XYZ"),
+ columns=pd.MultiIndex.from_tuples(
+ [("A", 0.8), ("A", 0.2), ("B", 0.8), ("B", 0.2)], names=["col", None]
+ ),
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_timestamp_groupby_quantile():
+ # GH 33168
+ df = DataFrame(
+ {
+ "timestamp": pd.date_range(
+ start="2020-04-19 00:00:00", freq="1T", periods=100, tz="UTC"
+ ).floor("1H"),
+ "category": list(range(1, 101)),
+ "value": list(range(101, 201)),
+ }
+ )
+
+ result = df.groupby("timestamp").quantile([0.2, 0.8])
+
+ expected = DataFrame(
+ [
+ {"category": 12.8, "value": 112.8},
+ {"category": 48.2, "value": 148.2},
+ {"category": 68.8, "value": 168.8},
+ {"category": 92.2, "value": 192.2},
+ ],
+ index=pd.MultiIndex.from_tuples(
+ [
+ (pd.Timestamp("2020-04-19 00:00:00+00:00"), 0.2),
+ (pd.Timestamp("2020-04-19 00:00:00+00:00"), 0.8),
+ (pd.Timestamp("2020-04-19 01:00:00+00:00"), 0.2),
+ (pd.Timestamp("2020-04-19 01:00:00+00:00"), 0.8),
+ ],
+ names=("timestamp", None),
+ ),
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_quantile_dt64tz_period():
+ # GH#51373
+ dti = pd.date_range("2016-01-01", periods=1000)
+ ser = pd.Series(dti)
+ df = ser.to_frame()
+ df[1] = dti.tz_localize("US/Pacific")
+ df[2] = dti.to_period("D")
+ df[3] = dti - dti[0]
+ df.iloc[-1] = pd.NaT
+
+ by = np.tile(np.arange(5), 200)
+ gb = df.groupby(by)
+
+ result = gb.quantile(0.5)
+
+ # Check that we match the group-by-group result
+ exp = {i: df.iloc[i::5].quantile(0.5) for i in range(5)}
+ expected = DataFrame(exp).T.infer_objects()
+ expected.index = expected.index.astype(int)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_quantile_nonmulti_levels_order():
+ # Non-regression test for GH #53009
+ ind = pd.MultiIndex.from_tuples(
+ [
+ (0, "a", "B"),
+ (0, "a", "A"),
+ (0, "b", "B"),
+ (0, "b", "A"),
+ (1, "a", "B"),
+ (1, "a", "A"),
+ (1, "b", "B"),
+ (1, "b", "A"),
+ ],
+ names=["sample", "cat0", "cat1"],
+ )
+ ser = pd.Series(range(8), index=ind)
+ result = ser.groupby(level="cat1", sort=False).quantile([0.2, 0.8])
+
+ qind = pd.MultiIndex.from_tuples(
+ [("B", 0.2), ("B", 0.8), ("A", 0.2), ("A", 0.8)], names=["cat1", None]
+ )
+ expected = pd.Series([1.2, 4.8, 2.2, 5.8], index=qind)
+
+ tm.assert_series_equal(result, expected)
+
+ # We need to check that index levels are not sorted
+ expected_levels = pd.core.indexes.frozen.FrozenList([["B", "A"], [0.2, 0.8]])
+ tm.assert_equal(result.index.levels, expected_levels)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_raises.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_raises.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9a2b3d44b117e3f66589ec1963c05f11681122d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_raises.py
@@ -0,0 +1,688 @@
+# Only tests that raise an error and have no better location should go here.
+# Tests for specific groupby methods should go in their respective
+# test file.
+
+import datetime
+import re
+
+import numpy as np
+import pytest
+
+from pandas import (
+ Categorical,
+ DataFrame,
+ Grouper,
+ Series,
+)
+import pandas._testing as tm
+from pandas.tests.groupby import get_groupby_method_args
+
+
+@pytest.fixture(
+ params=[
+ "a",
+ ["a"],
+ ["a", "b"],
+ Grouper(key="a"),
+ lambda x: x % 2,
+ [0, 0, 0, 1, 2, 2, 2, 3, 3],
+ np.array([0, 0, 0, 1, 2, 2, 2, 3, 3]),
+ dict(zip(range(9), [0, 0, 0, 1, 2, 2, 2, 3, 3])),
+ Series([1, 1, 1, 1, 1, 2, 2, 2, 2]),
+ [Series([1, 1, 1, 1, 1, 2, 2, 2, 2]), Series([3, 3, 4, 4, 4, 4, 4, 3, 3])],
+ ]
+)
+def by(request):
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def groupby_series(request):
+ return request.param
+
+
+@pytest.fixture
+def df_with_string_col():
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": list("xyzwtyuio"),
+ }
+ )
+ return df
+
+
+@pytest.fixture
+def df_with_datetime_col():
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": datetime.datetime(2005, 1, 1, 10, 30, 23, 540000),
+ }
+ )
+ return df
+
+
+@pytest.fixture
+def df_with_timedelta_col():
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": datetime.timedelta(days=1),
+ }
+ )
+ return df
+
+
+@pytest.fixture
+def df_with_cat_col():
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": Categorical(
+ ["a", "a", "a", "a", "b", "b", "b", "b", "c"],
+ categories=["a", "b", "c", "d"],
+ ordered=True,
+ ),
+ }
+ )
+ return df
+
+
+def _call_and_check(klass, msg, how, gb, groupby_func, args):
+ if klass is None:
+ if how == "method":
+ getattr(gb, groupby_func)(*args)
+ elif how == "agg":
+ gb.agg(groupby_func, *args)
+ else:
+ gb.transform(groupby_func, *args)
+ else:
+ with pytest.raises(klass, match=msg):
+ if how == "method":
+ getattr(gb, groupby_func)(*args)
+ elif how == "agg":
+ gb.agg(groupby_func, *args)
+ else:
+ gb.transform(groupby_func, *args)
+
+
+@pytest.mark.parametrize("how", ["method", "agg", "transform"])
+def test_groupby_raises_string(
+ how, by, groupby_series, groupby_func, df_with_string_col
+):
+ df = df_with_string_col
+ args = get_groupby_method_args(groupby_func, df)
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ if groupby_func == "corrwith":
+ assert not hasattr(gb, "corrwith")
+ return
+
+ klass, msg = {
+ "all": (None, ""),
+ "any": (None, ""),
+ "bfill": (None, ""),
+ "corrwith": (TypeError, "Could not convert"),
+ "count": (None, ""),
+ "cumcount": (None, ""),
+ "cummax": (
+ (NotImplementedError, TypeError),
+ "(function|cummax) is not (implemented|supported) for (this|object) dtype",
+ ),
+ "cummin": (
+ (NotImplementedError, TypeError),
+ "(function|cummin) is not (implemented|supported) for (this|object) dtype",
+ ),
+ "cumprod": (
+ (NotImplementedError, TypeError),
+ "(function|cumprod) is not (implemented|supported) for (this|object) dtype",
+ ),
+ "cumsum": (
+ (NotImplementedError, TypeError),
+ "(function|cumsum) is not (implemented|supported) for (this|object) dtype",
+ ),
+ "diff": (TypeError, "unsupported operand type"),
+ "ffill": (None, ""),
+ "fillna": (None, ""),
+ "first": (None, ""),
+ "idxmax": (None, ""),
+ "idxmin": (None, ""),
+ "last": (None, ""),
+ "max": (None, ""),
+ "mean": (
+ TypeError,
+ re.escape("agg function failed [how->mean,dtype->object]"),
+ ),
+ "median": (
+ TypeError,
+ re.escape("agg function failed [how->median,dtype->object]"),
+ ),
+ "min": (None, ""),
+ "ngroup": (None, ""),
+ "nunique": (None, ""),
+ "pct_change": (TypeError, "unsupported operand type"),
+ "prod": (
+ TypeError,
+ re.escape("agg function failed [how->prod,dtype->object]"),
+ ),
+ "quantile": (TypeError, "cannot be performed against 'object' dtypes!"),
+ "rank": (None, ""),
+ "sem": (ValueError, "could not convert string to float"),
+ "shift": (None, ""),
+ "size": (None, ""),
+ "skew": (ValueError, "could not convert string to float"),
+ "std": (ValueError, "could not convert string to float"),
+ "sum": (None, ""),
+ "var": (
+ TypeError,
+ re.escape("agg function failed [how->var,dtype->object]"),
+ ),
+ }[groupby_func]
+
+ _call_and_check(klass, msg, how, gb, groupby_func, args)
+
+
+@pytest.mark.parametrize("how", ["agg", "transform"])
+def test_groupby_raises_string_udf(how, by, groupby_series, df_with_string_col):
+ df = df_with_string_col
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ def func(x):
+ raise TypeError("Test error message")
+
+ with pytest.raises(TypeError, match="Test error message"):
+ getattr(gb, how)(func)
+
+
+@pytest.mark.parametrize("how", ["agg", "transform"])
+@pytest.mark.parametrize("groupby_func_np", [np.sum, np.mean])
+def test_groupby_raises_string_np(
+ how, by, groupby_series, groupby_func_np, df_with_string_col
+):
+ # GH#50749
+ df = df_with_string_col
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ klass, msg = {
+ np.sum: (None, ""),
+ np.mean: (
+ TypeError,
+ re.escape("agg function failed [how->mean,dtype->object]"),
+ ),
+ }[groupby_func_np]
+
+ if groupby_series:
+ warn_msg = "using SeriesGroupBy.[sum|mean]"
+ else:
+ warn_msg = "using DataFrameGroupBy.[sum|mean]"
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ _call_and_check(klass, msg, how, gb, groupby_func_np, ())
+
+
+@pytest.mark.parametrize("how", ["method", "agg", "transform"])
+def test_groupby_raises_datetime(
+ how, by, groupby_series, groupby_func, df_with_datetime_col
+):
+ df = df_with_datetime_col
+ args = get_groupby_method_args(groupby_func, df)
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ if groupby_func == "corrwith":
+ assert not hasattr(gb, "corrwith")
+ return
+
+ klass, msg = {
+ "all": (None, ""),
+ "any": (None, ""),
+ "bfill": (None, ""),
+ "corrwith": (TypeError, "cannot perform __mul__ with this index type"),
+ "count": (None, ""),
+ "cumcount": (None, ""),
+ "cummax": (None, ""),
+ "cummin": (None, ""),
+ "cumprod": (TypeError, "datetime64 type does not support cumprod operations"),
+ "cumsum": (TypeError, "datetime64 type does not support cumsum operations"),
+ "diff": (None, ""),
+ "ffill": (None, ""),
+ "fillna": (None, ""),
+ "first": (None, ""),
+ "idxmax": (None, ""),
+ "idxmin": (None, ""),
+ "last": (None, ""),
+ "max": (None, ""),
+ "mean": (None, ""),
+ "median": (None, ""),
+ "min": (None, ""),
+ "ngroup": (None, ""),
+ "nunique": (None, ""),
+ "pct_change": (TypeError, "cannot perform __truediv__ with this index type"),
+ "prod": (TypeError, "datetime64 type does not support prod"),
+ "quantile": (None, ""),
+ "rank": (None, ""),
+ "sem": (None, ""),
+ "shift": (None, ""),
+ "size": (None, ""),
+ "skew": (
+ TypeError,
+ "|".join(
+ [
+ r"dtype datetime64\[ns\] does not support reduction",
+ "datetime64 type does not support skew operations",
+ ]
+ ),
+ ),
+ "std": (None, ""),
+ "sum": (TypeError, "datetime64 type does not support sum operations"),
+ "var": (TypeError, "datetime64 type does not support var operations"),
+ }[groupby_func]
+
+ warn = None
+ warn_msg = f"'{groupby_func}' with datetime64 dtypes is deprecated"
+ if groupby_func in ["any", "all"]:
+ warn = FutureWarning
+
+ with tm.assert_produces_warning(warn, match=warn_msg):
+ _call_and_check(klass, msg, how, gb, groupby_func, args)
+
+
+@pytest.mark.parametrize("how", ["agg", "transform"])
+def test_groupby_raises_datetime_udf(how, by, groupby_series, df_with_datetime_col):
+ df = df_with_datetime_col
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ def func(x):
+ raise TypeError("Test error message")
+
+ with pytest.raises(TypeError, match="Test error message"):
+ getattr(gb, how)(func)
+
+
+@pytest.mark.parametrize("how", ["agg", "transform"])
+@pytest.mark.parametrize("groupby_func_np", [np.sum, np.mean])
+def test_groupby_raises_datetime_np(
+ how, by, groupby_series, groupby_func_np, df_with_datetime_col
+):
+ # GH#50749
+ df = df_with_datetime_col
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ klass, msg = {
+ np.sum: (TypeError, "datetime64 type does not support sum operations"),
+ np.mean: (None, ""),
+ }[groupby_func_np]
+
+ if groupby_series:
+ warn_msg = "using SeriesGroupBy.[sum|mean]"
+ else:
+ warn_msg = "using DataFrameGroupBy.[sum|mean]"
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ _call_and_check(klass, msg, how, gb, groupby_func_np, ())
+
+
+@pytest.mark.parametrize("func", ["prod", "cumprod", "skew", "var"])
+def test_groupby_raises_timedelta(func, df_with_timedelta_col):
+ df = df_with_timedelta_col
+ gb = df.groupby(by="a")
+
+ _call_and_check(
+ TypeError,
+ "timedelta64 type does not support .* operations",
+ "method",
+ gb,
+ func,
+ [],
+ )
+
+
+@pytest.mark.parametrize("how", ["method", "agg", "transform"])
+def test_groupby_raises_category(
+ how, by, groupby_series, groupby_func, using_copy_on_write, df_with_cat_col
+):
+ # GH#50749
+ df = df_with_cat_col
+ args = get_groupby_method_args(groupby_func, df)
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ if groupby_func == "corrwith":
+ assert not hasattr(gb, "corrwith")
+ return
+
+ klass, msg = {
+ "all": (None, ""),
+ "any": (None, ""),
+ "bfill": (None, ""),
+ "corrwith": (
+ TypeError,
+ r"unsupported operand type\(s\) for \*: 'Categorical' and 'int'",
+ ),
+ "count": (None, ""),
+ "cumcount": (None, ""),
+ "cummax": (
+ (NotImplementedError, TypeError),
+ "(category type does not support cummax operations|"
+ "category dtype not supported|"
+ "cummax is not supported for category dtype)",
+ ),
+ "cummin": (
+ (NotImplementedError, TypeError),
+ "(category type does not support cummin operations|"
+ "category dtype not supported|"
+ "cummin is not supported for category dtype)",
+ ),
+ "cumprod": (
+ (NotImplementedError, TypeError),
+ "(category type does not support cumprod operations|"
+ "category dtype not supported|"
+ "cumprod is not supported for category dtype)",
+ ),
+ "cumsum": (
+ (NotImplementedError, TypeError),
+ "(category type does not support cumsum operations|"
+ "category dtype not supported|"
+ "cumsum is not supported for category dtype)",
+ ),
+ "diff": (
+ TypeError,
+ r"unsupported operand type\(s\) for -: 'Categorical' and 'Categorical'",
+ ),
+ "ffill": (None, ""),
+ "fillna": (
+ TypeError,
+ r"Cannot setitem on a Categorical with a new category \(0\), "
+ "set the categories first",
+ )
+ if not using_copy_on_write
+ else (None, ""), # no-op with CoW
+ "first": (None, ""),
+ "idxmax": (None, ""),
+ "idxmin": (None, ""),
+ "last": (None, ""),
+ "max": (None, ""),
+ "mean": (
+ TypeError,
+ "|".join(
+ [
+ "'Categorical' .* does not support reduction 'mean'",
+ "category dtype does not support aggregation 'mean'",
+ ]
+ ),
+ ),
+ "median": (
+ TypeError,
+ "|".join(
+ [
+ "'Categorical' .* does not support reduction 'median'",
+ "category dtype does not support aggregation 'median'",
+ ]
+ ),
+ ),
+ "min": (None, ""),
+ "ngroup": (None, ""),
+ "nunique": (None, ""),
+ "pct_change": (
+ TypeError,
+ r"unsupported operand type\(s\) for /: 'Categorical' and 'Categorical'",
+ ),
+ "prod": (TypeError, "category type does not support prod operations"),
+ "quantile": (TypeError, "No matching signature found"),
+ "rank": (None, ""),
+ "sem": (
+ TypeError,
+ "|".join(
+ [
+ "'Categorical' .* does not support reduction 'sem'",
+ "category dtype does not support aggregation 'sem'",
+ ]
+ ),
+ ),
+ "shift": (None, ""),
+ "size": (None, ""),
+ "skew": (
+ TypeError,
+ "|".join(
+ [
+ "dtype category does not support reduction 'skew'",
+ "category type does not support skew operations",
+ ]
+ ),
+ ),
+ "std": (
+ TypeError,
+ "|".join(
+ [
+ "'Categorical' .* does not support reduction 'std'",
+ "category dtype does not support aggregation 'std'",
+ ]
+ ),
+ ),
+ "sum": (TypeError, "category type does not support sum operations"),
+ "var": (
+ TypeError,
+ "|".join(
+ [
+ "'Categorical' .* does not support reduction 'var'",
+ "category dtype does not support aggregation 'var'",
+ ]
+ ),
+ ),
+ }[groupby_func]
+
+ _call_and_check(klass, msg, how, gb, groupby_func, args)
+
+
+@pytest.mark.parametrize("how", ["agg", "transform"])
+def test_groupby_raises_category_udf(how, by, groupby_series, df_with_cat_col):
+ # GH#50749
+ df = df_with_cat_col
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ def func(x):
+ raise TypeError("Test error message")
+
+ with pytest.raises(TypeError, match="Test error message"):
+ getattr(gb, how)(func)
+
+
+@pytest.mark.parametrize("how", ["agg", "transform"])
+@pytest.mark.parametrize("groupby_func_np", [np.sum, np.mean])
+def test_groupby_raises_category_np(
+ how, by, groupby_series, groupby_func_np, df_with_cat_col
+):
+ # GH#50749
+ df = df_with_cat_col
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ klass, msg = {
+ np.sum: (TypeError, "category type does not support sum operations"),
+ np.mean: (
+ TypeError,
+ "category dtype does not support aggregation 'mean'",
+ ),
+ }[groupby_func_np]
+
+ if groupby_series:
+ warn_msg = "using SeriesGroupBy.[sum|mean]"
+ else:
+ warn_msg = "using DataFrameGroupBy.[sum|mean]"
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ _call_and_check(klass, msg, how, gb, groupby_func_np, ())
+
+
+@pytest.mark.parametrize("how", ["method", "agg", "transform"])
+def test_groupby_raises_category_on_category(
+ how,
+ by,
+ groupby_series,
+ groupby_func,
+ observed,
+ using_copy_on_write,
+ df_with_cat_col,
+):
+ # GH#50749
+ df = df_with_cat_col
+ df["a"] = Categorical(
+ ["a", "a", "a", "a", "b", "b", "b", "b", "c"],
+ categories=["a", "b", "c", "d"],
+ ordered=True,
+ )
+ args = get_groupby_method_args(groupby_func, df)
+ gb = df.groupby(by=by, observed=observed)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ if groupby_func == "corrwith":
+ assert not hasattr(gb, "corrwith")
+ return
+
+ empty_groups = any(group.empty for group in gb.groups.values())
+
+ klass, msg = {
+ "all": (None, ""),
+ "any": (None, ""),
+ "bfill": (None, ""),
+ "corrwith": (
+ TypeError,
+ r"unsupported operand type\(s\) for \*: 'Categorical' and 'int'",
+ ),
+ "count": (None, ""),
+ "cumcount": (None, ""),
+ "cummax": (
+ (NotImplementedError, TypeError),
+ "(cummax is not supported for category dtype|"
+ "category dtype not supported|"
+ "category type does not support cummax operations)",
+ ),
+ "cummin": (
+ (NotImplementedError, TypeError),
+ "(cummin is not supported for category dtype|"
+ "category dtype not supported|"
+ "category type does not support cummin operations)",
+ ),
+ "cumprod": (
+ (NotImplementedError, TypeError),
+ "(cumprod is not supported for category dtype|"
+ "category dtype not supported|"
+ "category type does not support cumprod operations)",
+ ),
+ "cumsum": (
+ (NotImplementedError, TypeError),
+ "(cumsum is not supported for category dtype|"
+ "category dtype not supported|"
+ "category type does not support cumsum operations)",
+ ),
+ "diff": (TypeError, "unsupported operand type"),
+ "ffill": (None, ""),
+ "fillna": (
+ TypeError,
+ r"Cannot setitem on a Categorical with a new category \(0\), "
+ "set the categories first",
+ )
+ if not using_copy_on_write
+ else (None, ""), # no-op with CoW
+ "first": (None, ""),
+ "idxmax": (ValueError, "attempt to get argmax of an empty sequence")
+ if empty_groups
+ else (None, ""),
+ "idxmin": (ValueError, "attempt to get argmin of an empty sequence")
+ if empty_groups
+ else (None, ""),
+ "last": (None, ""),
+ "max": (None, ""),
+ "mean": (TypeError, "category dtype does not support aggregation 'mean'"),
+ "median": (TypeError, "category dtype does not support aggregation 'median'"),
+ "min": (None, ""),
+ "ngroup": (None, ""),
+ "nunique": (None, ""),
+ "pct_change": (TypeError, "unsupported operand type"),
+ "prod": (TypeError, "category type does not support prod operations"),
+ "quantile": (TypeError, ""),
+ "rank": (None, ""),
+ "sem": (
+ TypeError,
+ "|".join(
+ [
+ "'Categorical' .* does not support reduction 'sem'",
+ "category dtype does not support aggregation 'sem'",
+ ]
+ ),
+ ),
+ "shift": (None, ""),
+ "size": (None, ""),
+ "skew": (
+ TypeError,
+ "|".join(
+ [
+ "category type does not support skew operations",
+ "dtype category does not support reduction 'skew'",
+ ]
+ ),
+ ),
+ "std": (
+ TypeError,
+ "|".join(
+ [
+ "'Categorical' .* does not support reduction 'std'",
+ "category dtype does not support aggregation 'std'",
+ ]
+ ),
+ ),
+ "sum": (TypeError, "category type does not support sum operations"),
+ "var": (
+ TypeError,
+ "|".join(
+ [
+ "'Categorical' .* does not support reduction 'var'",
+ "category dtype does not support aggregation 'var'",
+ ]
+ ),
+ ),
+ }[groupby_func]
+
+ _call_and_check(klass, msg, how, gb, groupby_func, args)
+
+
+def test_subsetting_columns_axis_1_raises():
+ # GH 35443
+ df = DataFrame({"a": [1], "b": [2], "c": [3]})
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby("a", axis=1)
+ with pytest.raises(ValueError, match="Cannot subset columns when using axis=1"):
+ gb["b"]
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_rank.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_rank.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d85a0783e02477553231d8b44bea7d6f586e6ae
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_rank.py
@@ -0,0 +1,712 @@
+from datetime import datetime
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ NaT,
+ Series,
+ concat,
+)
+import pandas._testing as tm
+
+
+def test_rank_unordered_categorical_typeerror():
+ # GH#51034 should be TypeError, not NotImplementedError
+ cat = pd.Categorical([], ordered=False)
+ ser = Series(cat)
+ df = ser.to_frame()
+
+ msg = "Cannot perform rank with non-ordered Categorical"
+
+ gb = ser.groupby(cat, observed=False)
+ with pytest.raises(TypeError, match=msg):
+ gb.rank()
+
+ gb2 = df.groupby(cat, observed=False)
+ with pytest.raises(TypeError, match=msg):
+ gb2.rank()
+
+
+def test_rank_apply():
+ lev1 = np.array(["a" * 10] * 100, dtype=object)
+ lev2 = np.array(["b" * 10] * 130, dtype=object)
+ lab1 = np.random.default_rng(2).integers(0, 100, size=500, dtype=int)
+ lab2 = np.random.default_rng(2).integers(0, 130, size=500, dtype=int)
+
+ df = DataFrame(
+ {
+ "value": np.random.default_rng(2).standard_normal(500),
+ "key1": lev1.take(lab1),
+ "key2": lev2.take(lab2),
+ }
+ )
+
+ result = df.groupby(["key1", "key2"]).value.rank()
+
+ expected = [piece.value.rank() for key, piece in df.groupby(["key1", "key2"])]
+ expected = concat(expected, axis=0)
+ expected = expected.reindex(result.index)
+ tm.assert_series_equal(result, expected)
+
+ result = df.groupby(["key1", "key2"]).value.rank(pct=True)
+
+ expected = [
+ piece.value.rank(pct=True) for key, piece in df.groupby(["key1", "key2"])
+ ]
+ expected = concat(expected, axis=0)
+ expected = expected.reindex(result.index)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("grps", [["qux"], ["qux", "quux"]])
+@pytest.mark.parametrize(
+ "vals",
+ [
+ np.array([2, 2, 8, 2, 6], dtype=dtype)
+ for dtype in ["i8", "i4", "i2", "i1", "u8", "u4", "u2", "u1", "f8", "f4", "f2"]
+ ]
+ + [
+ [
+ pd.Timestamp("2018-01-02"),
+ pd.Timestamp("2018-01-02"),
+ pd.Timestamp("2018-01-08"),
+ pd.Timestamp("2018-01-02"),
+ pd.Timestamp("2018-01-06"),
+ ],
+ [
+ pd.Timestamp("2018-01-02", tz="US/Pacific"),
+ pd.Timestamp("2018-01-02", tz="US/Pacific"),
+ pd.Timestamp("2018-01-08", tz="US/Pacific"),
+ pd.Timestamp("2018-01-02", tz="US/Pacific"),
+ pd.Timestamp("2018-01-06", tz="US/Pacific"),
+ ],
+ [
+ pd.Timestamp("2018-01-02") - pd.Timestamp(0),
+ pd.Timestamp("2018-01-02") - pd.Timestamp(0),
+ pd.Timestamp("2018-01-08") - pd.Timestamp(0),
+ pd.Timestamp("2018-01-02") - pd.Timestamp(0),
+ pd.Timestamp("2018-01-06") - pd.Timestamp(0),
+ ],
+ [
+ pd.Timestamp("2018-01-02").to_period("D"),
+ pd.Timestamp("2018-01-02").to_period("D"),
+ pd.Timestamp("2018-01-08").to_period("D"),
+ pd.Timestamp("2018-01-02").to_period("D"),
+ pd.Timestamp("2018-01-06").to_period("D"),
+ ],
+ ],
+ ids=lambda x: type(x[0]),
+)
+@pytest.mark.parametrize(
+ "ties_method,ascending,pct,exp",
+ [
+ ("average", True, False, [2.0, 2.0, 5.0, 2.0, 4.0]),
+ ("average", True, True, [0.4, 0.4, 1.0, 0.4, 0.8]),
+ ("average", False, False, [4.0, 4.0, 1.0, 4.0, 2.0]),
+ ("average", False, True, [0.8, 0.8, 0.2, 0.8, 0.4]),
+ ("min", True, False, [1.0, 1.0, 5.0, 1.0, 4.0]),
+ ("min", True, True, [0.2, 0.2, 1.0, 0.2, 0.8]),
+ ("min", False, False, [3.0, 3.0, 1.0, 3.0, 2.0]),
+ ("min", False, True, [0.6, 0.6, 0.2, 0.6, 0.4]),
+ ("max", True, False, [3.0, 3.0, 5.0, 3.0, 4.0]),
+ ("max", True, True, [0.6, 0.6, 1.0, 0.6, 0.8]),
+ ("max", False, False, [5.0, 5.0, 1.0, 5.0, 2.0]),
+ ("max", False, True, [1.0, 1.0, 0.2, 1.0, 0.4]),
+ ("first", True, False, [1.0, 2.0, 5.0, 3.0, 4.0]),
+ ("first", True, True, [0.2, 0.4, 1.0, 0.6, 0.8]),
+ ("first", False, False, [3.0, 4.0, 1.0, 5.0, 2.0]),
+ ("first", False, True, [0.6, 0.8, 0.2, 1.0, 0.4]),
+ ("dense", True, False, [1.0, 1.0, 3.0, 1.0, 2.0]),
+ ("dense", True, True, [1.0 / 3.0, 1.0 / 3.0, 3.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0]),
+ ("dense", False, False, [3.0, 3.0, 1.0, 3.0, 2.0]),
+ ("dense", False, True, [3.0 / 3.0, 3.0 / 3.0, 1.0 / 3.0, 3.0 / 3.0, 2.0 / 3.0]),
+ ],
+)
+def test_rank_args(grps, vals, ties_method, ascending, pct, exp):
+ key = np.repeat(grps, len(vals))
+
+ orig_vals = vals
+ vals = list(vals) * len(grps)
+ if isinstance(orig_vals, np.ndarray):
+ vals = np.array(vals, dtype=orig_vals.dtype)
+
+ df = DataFrame({"key": key, "val": vals})
+ result = df.groupby("key").rank(method=ties_method, ascending=ascending, pct=pct)
+
+ exp_df = DataFrame(exp * len(grps), columns=["val"])
+ tm.assert_frame_equal(result, exp_df)
+
+
+@pytest.mark.parametrize("grps", [["qux"], ["qux", "quux"]])
+@pytest.mark.parametrize(
+ "vals", [[-np.inf, -np.inf, np.nan, 1.0, np.nan, np.inf, np.inf]]
+)
+@pytest.mark.parametrize(
+ "ties_method,ascending,na_option,exp",
+ [
+ ("average", True, "keep", [1.5, 1.5, np.nan, 3, np.nan, 4.5, 4.5]),
+ ("average", True, "top", [3.5, 3.5, 1.5, 5.0, 1.5, 6.5, 6.5]),
+ ("average", True, "bottom", [1.5, 1.5, 6.5, 3.0, 6.5, 4.5, 4.5]),
+ ("average", False, "keep", [4.5, 4.5, np.nan, 3, np.nan, 1.5, 1.5]),
+ ("average", False, "top", [6.5, 6.5, 1.5, 5.0, 1.5, 3.5, 3.5]),
+ ("average", False, "bottom", [4.5, 4.5, 6.5, 3.0, 6.5, 1.5, 1.5]),
+ ("min", True, "keep", [1.0, 1.0, np.nan, 3.0, np.nan, 4.0, 4.0]),
+ ("min", True, "top", [3.0, 3.0, 1.0, 5.0, 1.0, 6.0, 6.0]),
+ ("min", True, "bottom", [1.0, 1.0, 6.0, 3.0, 6.0, 4.0, 4.0]),
+ ("min", False, "keep", [4.0, 4.0, np.nan, 3.0, np.nan, 1.0, 1.0]),
+ ("min", False, "top", [6.0, 6.0, 1.0, 5.0, 1.0, 3.0, 3.0]),
+ ("min", False, "bottom", [4.0, 4.0, 6.0, 3.0, 6.0, 1.0, 1.0]),
+ ("max", True, "keep", [2.0, 2.0, np.nan, 3.0, np.nan, 5.0, 5.0]),
+ ("max", True, "top", [4.0, 4.0, 2.0, 5.0, 2.0, 7.0, 7.0]),
+ ("max", True, "bottom", [2.0, 2.0, 7.0, 3.0, 7.0, 5.0, 5.0]),
+ ("max", False, "keep", [5.0, 5.0, np.nan, 3.0, np.nan, 2.0, 2.0]),
+ ("max", False, "top", [7.0, 7.0, 2.0, 5.0, 2.0, 4.0, 4.0]),
+ ("max", False, "bottom", [5.0, 5.0, 7.0, 3.0, 7.0, 2.0, 2.0]),
+ ("first", True, "keep", [1.0, 2.0, np.nan, 3.0, np.nan, 4.0, 5.0]),
+ ("first", True, "top", [3.0, 4.0, 1.0, 5.0, 2.0, 6.0, 7.0]),
+ ("first", True, "bottom", [1.0, 2.0, 6.0, 3.0, 7.0, 4.0, 5.0]),
+ ("first", False, "keep", [4.0, 5.0, np.nan, 3.0, np.nan, 1.0, 2.0]),
+ ("first", False, "top", [6.0, 7.0, 1.0, 5.0, 2.0, 3.0, 4.0]),
+ ("first", False, "bottom", [4.0, 5.0, 6.0, 3.0, 7.0, 1.0, 2.0]),
+ ("dense", True, "keep", [1.0, 1.0, np.nan, 2.0, np.nan, 3.0, 3.0]),
+ ("dense", True, "top", [2.0, 2.0, 1.0, 3.0, 1.0, 4.0, 4.0]),
+ ("dense", True, "bottom", [1.0, 1.0, 4.0, 2.0, 4.0, 3.0, 3.0]),
+ ("dense", False, "keep", [3.0, 3.0, np.nan, 2.0, np.nan, 1.0, 1.0]),
+ ("dense", False, "top", [4.0, 4.0, 1.0, 3.0, 1.0, 2.0, 2.0]),
+ ("dense", False, "bottom", [3.0, 3.0, 4.0, 2.0, 4.0, 1.0, 1.0]),
+ ],
+)
+def test_infs_n_nans(grps, vals, ties_method, ascending, na_option, exp):
+ # GH 20561
+ key = np.repeat(grps, len(vals))
+ vals = vals * len(grps)
+ df = DataFrame({"key": key, "val": vals})
+ result = df.groupby("key").rank(
+ method=ties_method, ascending=ascending, na_option=na_option
+ )
+ exp_df = DataFrame(exp * len(grps), columns=["val"])
+ tm.assert_frame_equal(result, exp_df)
+
+
+@pytest.mark.parametrize("grps", [["qux"], ["qux", "quux"]])
+@pytest.mark.parametrize(
+ "vals",
+ [
+ np.array([2, 2, np.nan, 8, 2, 6, np.nan, np.nan], dtype=dtype)
+ for dtype in ["f8", "f4", "f2"]
+ ]
+ + [
+ [
+ pd.Timestamp("2018-01-02"),
+ pd.Timestamp("2018-01-02"),
+ np.nan,
+ pd.Timestamp("2018-01-08"),
+ pd.Timestamp("2018-01-02"),
+ pd.Timestamp("2018-01-06"),
+ np.nan,
+ np.nan,
+ ],
+ [
+ pd.Timestamp("2018-01-02", tz="US/Pacific"),
+ pd.Timestamp("2018-01-02", tz="US/Pacific"),
+ np.nan,
+ pd.Timestamp("2018-01-08", tz="US/Pacific"),
+ pd.Timestamp("2018-01-02", tz="US/Pacific"),
+ pd.Timestamp("2018-01-06", tz="US/Pacific"),
+ np.nan,
+ np.nan,
+ ],
+ [
+ pd.Timestamp("2018-01-02") - pd.Timestamp(0),
+ pd.Timestamp("2018-01-02") - pd.Timestamp(0),
+ np.nan,
+ pd.Timestamp("2018-01-08") - pd.Timestamp(0),
+ pd.Timestamp("2018-01-02") - pd.Timestamp(0),
+ pd.Timestamp("2018-01-06") - pd.Timestamp(0),
+ np.nan,
+ np.nan,
+ ],
+ [
+ pd.Timestamp("2018-01-02").to_period("D"),
+ pd.Timestamp("2018-01-02").to_period("D"),
+ np.nan,
+ pd.Timestamp("2018-01-08").to_period("D"),
+ pd.Timestamp("2018-01-02").to_period("D"),
+ pd.Timestamp("2018-01-06").to_period("D"),
+ np.nan,
+ np.nan,
+ ],
+ ],
+ ids=lambda x: type(x[0]),
+)
+@pytest.mark.parametrize(
+ "ties_method,ascending,na_option,pct,exp",
+ [
+ (
+ "average",
+ True,
+ "keep",
+ False,
+ [2.0, 2.0, np.nan, 5.0, 2.0, 4.0, np.nan, np.nan],
+ ),
+ (
+ "average",
+ True,
+ "keep",
+ True,
+ [0.4, 0.4, np.nan, 1.0, 0.4, 0.8, np.nan, np.nan],
+ ),
+ (
+ "average",
+ False,
+ "keep",
+ False,
+ [4.0, 4.0, np.nan, 1.0, 4.0, 2.0, np.nan, np.nan],
+ ),
+ (
+ "average",
+ False,
+ "keep",
+ True,
+ [0.8, 0.8, np.nan, 0.2, 0.8, 0.4, np.nan, np.nan],
+ ),
+ ("min", True, "keep", False, [1.0, 1.0, np.nan, 5.0, 1.0, 4.0, np.nan, np.nan]),
+ ("min", True, "keep", True, [0.2, 0.2, np.nan, 1.0, 0.2, 0.8, np.nan, np.nan]),
+ (
+ "min",
+ False,
+ "keep",
+ False,
+ [3.0, 3.0, np.nan, 1.0, 3.0, 2.0, np.nan, np.nan],
+ ),
+ ("min", False, "keep", True, [0.6, 0.6, np.nan, 0.2, 0.6, 0.4, np.nan, np.nan]),
+ ("max", True, "keep", False, [3.0, 3.0, np.nan, 5.0, 3.0, 4.0, np.nan, np.nan]),
+ ("max", True, "keep", True, [0.6, 0.6, np.nan, 1.0, 0.6, 0.8, np.nan, np.nan]),
+ (
+ "max",
+ False,
+ "keep",
+ False,
+ [5.0, 5.0, np.nan, 1.0, 5.0, 2.0, np.nan, np.nan],
+ ),
+ ("max", False, "keep", True, [1.0, 1.0, np.nan, 0.2, 1.0, 0.4, np.nan, np.nan]),
+ (
+ "first",
+ True,
+ "keep",
+ False,
+ [1.0, 2.0, np.nan, 5.0, 3.0, 4.0, np.nan, np.nan],
+ ),
+ (
+ "first",
+ True,
+ "keep",
+ True,
+ [0.2, 0.4, np.nan, 1.0, 0.6, 0.8, np.nan, np.nan],
+ ),
+ (
+ "first",
+ False,
+ "keep",
+ False,
+ [3.0, 4.0, np.nan, 1.0, 5.0, 2.0, np.nan, np.nan],
+ ),
+ (
+ "first",
+ False,
+ "keep",
+ True,
+ [0.6, 0.8, np.nan, 0.2, 1.0, 0.4, np.nan, np.nan],
+ ),
+ (
+ "dense",
+ True,
+ "keep",
+ False,
+ [1.0, 1.0, np.nan, 3.0, 1.0, 2.0, np.nan, np.nan],
+ ),
+ (
+ "dense",
+ True,
+ "keep",
+ True,
+ [
+ 1.0 / 3.0,
+ 1.0 / 3.0,
+ np.nan,
+ 3.0 / 3.0,
+ 1.0 / 3.0,
+ 2.0 / 3.0,
+ np.nan,
+ np.nan,
+ ],
+ ),
+ (
+ "dense",
+ False,
+ "keep",
+ False,
+ [3.0, 3.0, np.nan, 1.0, 3.0, 2.0, np.nan, np.nan],
+ ),
+ (
+ "dense",
+ False,
+ "keep",
+ True,
+ [
+ 3.0 / 3.0,
+ 3.0 / 3.0,
+ np.nan,
+ 1.0 / 3.0,
+ 3.0 / 3.0,
+ 2.0 / 3.0,
+ np.nan,
+ np.nan,
+ ],
+ ),
+ ("average", True, "bottom", False, [2.0, 2.0, 7.0, 5.0, 2.0, 4.0, 7.0, 7.0]),
+ (
+ "average",
+ True,
+ "bottom",
+ True,
+ [0.25, 0.25, 0.875, 0.625, 0.25, 0.5, 0.875, 0.875],
+ ),
+ ("average", False, "bottom", False, [4.0, 4.0, 7.0, 1.0, 4.0, 2.0, 7.0, 7.0]),
+ (
+ "average",
+ False,
+ "bottom",
+ True,
+ [0.5, 0.5, 0.875, 0.125, 0.5, 0.25, 0.875, 0.875],
+ ),
+ ("min", True, "bottom", False, [1.0, 1.0, 6.0, 5.0, 1.0, 4.0, 6.0, 6.0]),
+ (
+ "min",
+ True,
+ "bottom",
+ True,
+ [0.125, 0.125, 0.75, 0.625, 0.125, 0.5, 0.75, 0.75],
+ ),
+ ("min", False, "bottom", False, [3.0, 3.0, 6.0, 1.0, 3.0, 2.0, 6.0, 6.0]),
+ (
+ "min",
+ False,
+ "bottom",
+ True,
+ [0.375, 0.375, 0.75, 0.125, 0.375, 0.25, 0.75, 0.75],
+ ),
+ ("max", True, "bottom", False, [3.0, 3.0, 8.0, 5.0, 3.0, 4.0, 8.0, 8.0]),
+ ("max", True, "bottom", True, [0.375, 0.375, 1.0, 0.625, 0.375, 0.5, 1.0, 1.0]),
+ ("max", False, "bottom", False, [5.0, 5.0, 8.0, 1.0, 5.0, 2.0, 8.0, 8.0]),
+ (
+ "max",
+ False,
+ "bottom",
+ True,
+ [0.625, 0.625, 1.0, 0.125, 0.625, 0.25, 1.0, 1.0],
+ ),
+ ("first", True, "bottom", False, [1.0, 2.0, 6.0, 5.0, 3.0, 4.0, 7.0, 8.0]),
+ (
+ "first",
+ True,
+ "bottom",
+ True,
+ [0.125, 0.25, 0.75, 0.625, 0.375, 0.5, 0.875, 1.0],
+ ),
+ ("first", False, "bottom", False, [3.0, 4.0, 6.0, 1.0, 5.0, 2.0, 7.0, 8.0]),
+ (
+ "first",
+ False,
+ "bottom",
+ True,
+ [0.375, 0.5, 0.75, 0.125, 0.625, 0.25, 0.875, 1.0],
+ ),
+ ("dense", True, "bottom", False, [1.0, 1.0, 4.0, 3.0, 1.0, 2.0, 4.0, 4.0]),
+ ("dense", True, "bottom", True, [0.25, 0.25, 1.0, 0.75, 0.25, 0.5, 1.0, 1.0]),
+ ("dense", False, "bottom", False, [3.0, 3.0, 4.0, 1.0, 3.0, 2.0, 4.0, 4.0]),
+ ("dense", False, "bottom", True, [0.75, 0.75, 1.0, 0.25, 0.75, 0.5, 1.0, 1.0]),
+ ],
+)
+def test_rank_args_missing(grps, vals, ties_method, ascending, na_option, pct, exp):
+ key = np.repeat(grps, len(vals))
+
+ orig_vals = vals
+ vals = list(vals) * len(grps)
+ if isinstance(orig_vals, np.ndarray):
+ vals = np.array(vals, dtype=orig_vals.dtype)
+
+ df = DataFrame({"key": key, "val": vals})
+ result = df.groupby("key").rank(
+ method=ties_method, ascending=ascending, na_option=na_option, pct=pct
+ )
+
+ exp_df = DataFrame(exp * len(grps), columns=["val"])
+ tm.assert_frame_equal(result, exp_df)
+
+
+@pytest.mark.parametrize(
+ "pct,exp", [(False, [3.0, 3.0, 3.0, 3.0, 3.0]), (True, [0.6, 0.6, 0.6, 0.6, 0.6])]
+)
+def test_rank_resets_each_group(pct, exp):
+ df = DataFrame(
+ {"key": ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"], "val": [1] * 10}
+ )
+ result = df.groupby("key").rank(pct=pct)
+ exp_df = DataFrame(exp * 2, columns=["val"])
+ tm.assert_frame_equal(result, exp_df)
+
+
+@pytest.mark.parametrize(
+ "dtype", ["int64", "int32", "uint64", "uint32", "float64", "float32"]
+)
+@pytest.mark.parametrize("upper", [True, False])
+def test_rank_avg_even_vals(dtype, upper):
+ if upper:
+ # use IntegerDtype/FloatingDtype
+ dtype = dtype[0].upper() + dtype[1:]
+ dtype = dtype.replace("Ui", "UI")
+ df = DataFrame({"key": ["a"] * 4, "val": [1] * 4})
+ df["val"] = df["val"].astype(dtype)
+ assert df["val"].dtype == dtype
+
+ result = df.groupby("key").rank()
+ exp_df = DataFrame([2.5, 2.5, 2.5, 2.5], columns=["val"])
+ if upper:
+ exp_df = exp_df.astype("Float64")
+ tm.assert_frame_equal(result, exp_df)
+
+
+@pytest.mark.parametrize("ties_method", ["average", "min", "max", "first", "dense"])
+@pytest.mark.parametrize("ascending", [True, False])
+@pytest.mark.parametrize("na_option", ["keep", "top", "bottom"])
+@pytest.mark.parametrize("pct", [True, False])
+@pytest.mark.parametrize(
+ "vals", [["bar", "bar", "foo", "bar", "baz"], ["bar", np.nan, "foo", np.nan, "baz"]]
+)
+def test_rank_object_dtype(ties_method, ascending, na_option, pct, vals):
+ df = DataFrame({"key": ["foo"] * 5, "val": vals})
+ mask = df["val"].isna()
+
+ gb = df.groupby("key")
+ res = gb.rank(method=ties_method, ascending=ascending, na_option=na_option, pct=pct)
+
+ # construct our expected by using numeric values with the same ordering
+ if mask.any():
+ df2 = DataFrame({"key": ["foo"] * 5, "val": [0, np.nan, 2, np.nan, 1]})
+ else:
+ df2 = DataFrame({"key": ["foo"] * 5, "val": [0, 0, 2, 0, 1]})
+
+ gb2 = df2.groupby("key")
+ alt = gb2.rank(
+ method=ties_method, ascending=ascending, na_option=na_option, pct=pct
+ )
+
+ tm.assert_frame_equal(res, alt)
+
+
+@pytest.mark.parametrize("na_option", [True, "bad", 1])
+@pytest.mark.parametrize("ties_method", ["average", "min", "max", "first", "dense"])
+@pytest.mark.parametrize("ascending", [True, False])
+@pytest.mark.parametrize("pct", [True, False])
+@pytest.mark.parametrize(
+ "vals",
+ [
+ ["bar", "bar", "foo", "bar", "baz"],
+ ["bar", np.nan, "foo", np.nan, "baz"],
+ [1, np.nan, 2, np.nan, 3],
+ ],
+)
+def test_rank_naoption_raises(ties_method, ascending, na_option, pct, vals):
+ df = DataFrame({"key": ["foo"] * 5, "val": vals})
+ msg = "na_option must be one of 'keep', 'top', or 'bottom'"
+
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("key").rank(
+ method=ties_method, ascending=ascending, na_option=na_option, pct=pct
+ )
+
+
+def test_rank_empty_group():
+ # see gh-22519
+ column = "A"
+ df = DataFrame({"A": [0, 1, 0], "B": [1.0, np.nan, 2.0]})
+
+ result = df.groupby(column).B.rank(pct=True)
+ expected = Series([0.5, np.nan, 1.0], name="B")
+ tm.assert_series_equal(result, expected)
+
+ result = df.groupby(column).rank(pct=True)
+ expected = DataFrame({"B": [0.5, np.nan, 1.0]})
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "input_key,input_value,output_value",
+ [
+ ([1, 2], [1, 1], [1.0, 1.0]),
+ ([1, 1, 2, 2], [1, 2, 1, 2], [0.5, 1.0, 0.5, 1.0]),
+ ([1, 1, 2, 2], [1, 2, 1, np.nan], [0.5, 1.0, 1.0, np.nan]),
+ ([1, 1, 2], [1, 2, np.nan], [0.5, 1.0, np.nan]),
+ ],
+)
+def test_rank_zero_div(input_key, input_value, output_value):
+ # GH 23666
+ df = DataFrame({"A": input_key, "B": input_value})
+
+ result = df.groupby("A").rank(method="dense", pct=True)
+ expected = DataFrame({"B": output_value})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_rank_min_int():
+ # GH-32859
+ df = DataFrame(
+ {
+ "grp": [1, 1, 2],
+ "int_col": [
+ np.iinfo(np.int64).min,
+ np.iinfo(np.int64).max,
+ np.iinfo(np.int64).min,
+ ],
+ "datetimelike": [NaT, datetime(2001, 1, 1), NaT],
+ }
+ )
+
+ result = df.groupby("grp").rank()
+ expected = DataFrame(
+ {"int_col": [1.0, 2.0, 1.0], "datetimelike": [np.nan, 1.0, np.nan]}
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("use_nan", [True, False])
+def test_rank_pct_equal_values_on_group_transition(use_nan):
+ # GH#40518
+ fill_value = np.nan if use_nan else 3
+ df = DataFrame(
+ [
+ [-1, 1],
+ [-1, 2],
+ [1, fill_value],
+ [-1, fill_value],
+ ],
+ columns=["group", "val"],
+ )
+ result = df.groupby(["group"])["val"].rank(
+ method="dense",
+ pct=True,
+ )
+ if use_nan:
+ expected = Series([0.5, 1, np.nan, np.nan], name="val")
+ else:
+ expected = Series([1 / 3, 2 / 3, 1, 1], name="val")
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_rank_multiindex():
+ # GH27721
+ df = concat(
+ {
+ "a": DataFrame({"col1": [3, 4], "col2": [1, 2]}),
+ "b": DataFrame({"col3": [5, 6], "col4": [7, 8]}),
+ },
+ axis=1,
+ )
+
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby(level=0, axis=1)
+ msg = "DataFrameGroupBy.rank with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = gb.rank(axis=1)
+
+ expected = concat(
+ [
+ df["a"].rank(axis=1),
+ df["b"].rank(axis=1),
+ ],
+ axis=1,
+ keys=["a", "b"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_axis0_rank_axis1():
+ # GH#41320
+ df = DataFrame(
+ {0: [1, 3, 5, 7], 1: [2, 4, 6, 8], 2: [1.5, 3.5, 5.5, 7.5]},
+ index=["a", "a", "b", "b"],
+ )
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby(level=0, axis=0)
+
+ msg = "DataFrameGroupBy.rank with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = gb.rank(axis=1)
+
+ # This should match what we get when "manually" operating group-by-group
+ expected = concat([df.loc["a"].rank(axis=1), df.loc["b"].rank(axis=1)], axis=0)
+ tm.assert_frame_equal(res, expected)
+
+ # check that we haven't accidentally written a case that coincidentally
+ # matches rank(axis=0)
+ msg = "The 'axis' keyword in DataFrameGroupBy.rank"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ alt = gb.rank(axis=0)
+ assert not alt.equals(expected)
+
+
+def test_groupby_axis0_cummax_axis1():
+ # case where groupby axis is 0 and axis keyword in transform is 1
+
+ # df has mixed dtype -> multiple blocks
+ df = DataFrame(
+ {0: [1, 3, 5, 7], 1: [2, 4, 6, 8], 2: [1.5, 3.5, 5.5, 7.5]},
+ index=["a", "a", "b", "b"],
+ )
+ msg = "The 'axis' keyword in DataFrame.groupby is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gb = df.groupby(level=0, axis=0)
+
+ msg = "DataFrameGroupBy.cummax with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ cmax = gb.cummax(axis=1)
+ expected = df[[0, 1]].astype(np.float64)
+ expected[2] = expected[1]
+ tm.assert_frame_equal(cmax, expected)
+
+
+def test_non_unique_index():
+ # GH 16577
+ df = DataFrame(
+ {"A": [1.0, 2.0, 3.0, np.nan], "value": 1.0},
+ index=[pd.Timestamp("20170101", tz="US/Eastern")] * 4,
+ )
+ result = df.groupby([df.index, "A"]).value.rank(ascending=True, pct=True)
+ expected = Series(
+ [1.0, 1.0, 1.0, np.nan],
+ index=[pd.Timestamp("20170101", tz="US/Eastern")] * 4,
+ name="value",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_rank_categorical():
+ cat = pd.Categorical(["a", "a", "b", np.nan, "c", "b"], ordered=True)
+ cat2 = pd.Categorical([1, 2, 3, np.nan, 4, 5], ordered=True)
+
+ df = DataFrame({"col1": [0, 1, 0, 1, 0, 1], "col2": cat, "col3": cat2})
+
+ gb = df.groupby("col1")
+
+ res = gb.rank()
+
+ expected = df.astype(object).groupby("col1").rank()
+ tm.assert_frame_equal(res, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_sample.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_sample.py
new file mode 100644
index 0000000000000000000000000000000000000000..4dd474741740d4abdea1ebabf2b36c3b68d690ad
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_sample.py
@@ -0,0 +1,154 @@
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize("n, frac", [(2, None), (None, 0.2)])
+def test_groupby_sample_balanced_groups_shape(n, frac):
+ values = [1] * 10 + [2] * 10
+ df = DataFrame({"a": values, "b": values})
+
+ result = df.groupby("a").sample(n=n, frac=frac)
+ values = [1] * 2 + [2] * 2
+ expected = DataFrame({"a": values, "b": values}, index=result.index)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("a")["b"].sample(n=n, frac=frac)
+ expected = Series(values, name="b", index=result.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_sample_unbalanced_groups_shape():
+ values = [1] * 10 + [2] * 20
+ df = DataFrame({"a": values, "b": values})
+
+ result = df.groupby("a").sample(n=5)
+ values = [1] * 5 + [2] * 5
+ expected = DataFrame({"a": values, "b": values}, index=result.index)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("a")["b"].sample(n=5)
+ expected = Series(values, name="b", index=result.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_sample_index_value_spans_groups():
+ values = [1] * 3 + [2] * 3
+ df = DataFrame({"a": values, "b": values}, index=[1, 2, 2, 2, 2, 2])
+
+ result = df.groupby("a").sample(n=2)
+ values = [1] * 2 + [2] * 2
+ expected = DataFrame({"a": values, "b": values}, index=result.index)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("a")["b"].sample(n=2)
+ expected = Series(values, name="b", index=result.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_sample_n_and_frac_raises():
+ df = DataFrame({"a": [1, 2], "b": [1, 2]})
+ msg = "Please enter a value for `frac` OR `n`, not both"
+
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("a").sample(n=1, frac=1.0)
+
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("a")["b"].sample(n=1, frac=1.0)
+
+
+def test_groupby_sample_frac_gt_one_without_replacement_raises():
+ df = DataFrame({"a": [1, 2], "b": [1, 2]})
+ msg = "Replace has to be set to `True` when upsampling the population `frac` > 1."
+
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("a").sample(frac=1.5, replace=False)
+
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("a")["b"].sample(frac=1.5, replace=False)
+
+
+@pytest.mark.parametrize("n", [-1, 1.5])
+def test_groupby_sample_invalid_n_raises(n):
+ df = DataFrame({"a": [1, 2], "b": [1, 2]})
+
+ if n < 0:
+ msg = "A negative number of rows requested. Please provide `n` >= 0."
+ else:
+ msg = "Only integers accepted as `n` values"
+
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("a").sample(n=n)
+
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("a")["b"].sample(n=n)
+
+
+def test_groupby_sample_oversample():
+ values = [1] * 10 + [2] * 10
+ df = DataFrame({"a": values, "b": values})
+
+ result = df.groupby("a").sample(frac=2.0, replace=True)
+ values = [1] * 20 + [2] * 20
+ expected = DataFrame({"a": values, "b": values}, index=result.index)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("a")["b"].sample(frac=2.0, replace=True)
+ expected = Series(values, name="b", index=result.index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_sample_without_n_or_frac():
+ values = [1] * 10 + [2] * 10
+ df = DataFrame({"a": values, "b": values})
+
+ result = df.groupby("a").sample(n=None, frac=None)
+ expected = DataFrame({"a": [1, 2], "b": [1, 2]}, index=result.index)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("a")["b"].sample(n=None, frac=None)
+ expected = Series([1, 2], name="b", index=result.index)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "index, expected_index",
+ [(["w", "x", "y", "z"], ["w", "w", "y", "y"]), ([3, 4, 5, 6], [3, 3, 5, 5])],
+)
+def test_groupby_sample_with_weights(index, expected_index):
+ # GH 39927 - tests for integer index needed
+ values = [1] * 2 + [2] * 2
+ df = DataFrame({"a": values, "b": values}, index=Index(index))
+
+ result = df.groupby("a").sample(n=2, replace=True, weights=[1, 0, 1, 0])
+ expected = DataFrame({"a": values, "b": values}, index=Index(expected_index))
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby("a")["b"].sample(n=2, replace=True, weights=[1, 0, 1, 0])
+ expected = Series(values, name="b", index=Index(expected_index))
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_sample_with_selections():
+ # GH 39928
+ values = [1] * 10 + [2] * 10
+ df = DataFrame({"a": values, "b": values, "c": values})
+
+ result = df.groupby("a")[["b", "c"]].sample(n=None, frac=None)
+ expected = DataFrame({"b": [1, 2], "c": [1, 2]}, index=result.index)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_sample_with_empty_inputs():
+ # GH48459
+ df = DataFrame({"a": [], "b": []})
+ groupby_df = df.groupby("a")
+
+ result = groupby_df.sample()
+ expected = df
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_size.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_size.py
new file mode 100644
index 0000000000000000000000000000000000000000..93a4e743d0d71db1d2a1fcca4163e6db83eb4ffb
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_size.py
@@ -0,0 +1,130 @@
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+from pandas.core.dtypes.common import is_integer_dtype
+
+from pandas import (
+ DataFrame,
+ Index,
+ PeriodIndex,
+ Series,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize("by", ["A", "B", ["A", "B"]])
+def test_size(df, by):
+ grouped = df.groupby(by=by)
+ result = grouped.size()
+ for key, group in grouped:
+ assert result[key] == len(group)
+
+
+@pytest.mark.parametrize(
+ "by",
+ [
+ [0, 0, 0, 0],
+ [0, 1, 1, 1],
+ [1, 0, 1, 1],
+ [0, None, None, None],
+ pytest.param([None, None, None, None], marks=pytest.mark.xfail),
+ ],
+)
+def test_size_axis_1(df, axis_1, by, sort, dropna):
+ # GH#45715
+ counts = {key: sum(value == key for value in by) for key in dict.fromkeys(by)}
+ if dropna:
+ counts = {key: value for key, value in counts.items() if key is not None}
+ expected = Series(counts, dtype="int64")
+ if sort:
+ expected = expected.sort_index()
+ if is_integer_dtype(expected.index.dtype) and not any(x is None for x in by):
+ expected.index = expected.index.astype(int)
+
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ grouped = df.groupby(by=by, axis=axis_1, sort=sort, dropna=dropna)
+ result = grouped.size()
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("by", ["A", "B", ["A", "B"]])
+@pytest.mark.parametrize("sort", [True, False])
+def test_size_sort(sort, by):
+ df = DataFrame(np.random.default_rng(2).choice(20, (1000, 3)), columns=list("ABC"))
+ left = df.groupby(by=by, sort=sort).size()
+ right = df.groupby(by=by, sort=sort)["C"].apply(lambda a: a.shape[0])
+ tm.assert_series_equal(left, right, check_names=False)
+
+
+def test_size_series_dataframe():
+ # https://github.com/pandas-dev/pandas/issues/11699
+ df = DataFrame(columns=["A", "B"])
+ out = Series(dtype="int64", index=Index([], name="A"))
+ tm.assert_series_equal(df.groupby("A").size(), out)
+
+
+def test_size_groupby_all_null():
+ # https://github.com/pandas-dev/pandas/issues/23050
+ # Assert no 'Value Error : Length of passed values is 2, index implies 0'
+ df = DataFrame({"A": [None, None]}) # all-null groups
+ result = df.groupby("A").size()
+ expected = Series(dtype="int64", index=Index([], name="A"))
+ tm.assert_series_equal(result, expected)
+
+
+def test_size_period_index():
+ # https://github.com/pandas-dev/pandas/issues/34010
+ ser = Series([1], index=PeriodIndex(["2000"], name="A", freq="D"))
+ grp = ser.groupby(level="A")
+ result = grp.size()
+ tm.assert_series_equal(result, ser)
+
+
+@pytest.mark.parametrize("as_index", [True, False])
+def test_size_on_categorical(as_index):
+ df = DataFrame([[1, 1], [2, 2]], columns=["A", "B"])
+ df["A"] = df["A"].astype("category")
+ result = df.groupby(["A", "B"], as_index=as_index, observed=False).size()
+
+ expected = DataFrame(
+ [[1, 1, 1], [1, 2, 0], [2, 1, 0], [2, 2, 1]], columns=["A", "B", "size"]
+ )
+ expected["A"] = expected["A"].astype("category")
+ if as_index:
+ expected = expected.set_index(["A", "B"])["size"].rename(None)
+
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"])
+def test_size_series_masked_type_returns_Int64(dtype):
+ # GH 54132
+ ser = Series([1, 1, 1], index=["a", "a", "b"], dtype=dtype)
+ result = ser.groupby(level=0).size()
+ expected = Series([2, 1], dtype="Int64", index=["a", "b"])
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ object,
+ pytest.param("string[pyarrow_numpy]", marks=td.skip_if_no("pyarrow")),
+ pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")),
+ ],
+)
+def test_size_strings(dtype):
+ # GH#55627
+ df = DataFrame({"a": ["a", "a", "b"], "b": "a"}, dtype=dtype)
+ result = df.groupby("a")["b"].size()
+ exp_dtype = "Int64" if dtype == "string[pyarrow]" else "int64"
+ expected = Series(
+ [2, 1],
+ index=Index(["a", "b"], name="a", dtype=dtype),
+ name="b",
+ dtype=exp_dtype,
+ )
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_skew.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_skew.py
new file mode 100644
index 0000000000000000000000000000000000000000..563da89b6ab24a898f042f0e21377ccc2709b072
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_skew.py
@@ -0,0 +1,27 @@
+import numpy as np
+
+import pandas as pd
+import pandas._testing as tm
+
+
+def test_groupby_skew_equivalence():
+ # Test that that groupby skew method (which uses libgroupby.group_skew)
+ # matches the results of operating group-by-group (which uses nanops.nanskew)
+ nrows = 1000
+ ngroups = 3
+ ncols = 2
+ nan_frac = 0.05
+
+ arr = np.random.default_rng(2).standard_normal((nrows, ncols))
+ arr[np.random.default_rng(2).random(nrows) < nan_frac] = np.nan
+
+ df = pd.DataFrame(arr)
+ grps = np.random.default_rng(2).integers(0, ngroups, size=nrows)
+ gb = df.groupby(grps)
+
+ result = gb.skew()
+
+ grpwise = [grp.skew().to_frame(i).T for i, grp in gb]
+ expected = pd.concat(grpwise, axis=0)
+ expected.index = expected.index.astype(result.index.dtype) # 32bit builds
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_timegrouper.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_timegrouper.py
new file mode 100644
index 0000000000000000000000000000000000000000..527e7c6081970d7a21caa1a790db2899b9f50e3e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_timegrouper.py
@@ -0,0 +1,927 @@
+"""
+test with the TimeGrouper / grouping with datetimes
+"""
+from datetime import (
+ datetime,
+ timedelta,
+)
+from io import StringIO
+
+import numpy as np
+import pytest
+import pytz
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+ offsets,
+)
+import pandas._testing as tm
+from pandas.core.groupby.grouper import Grouper
+from pandas.core.groupby.ops import BinGrouper
+
+
+@pytest.fixture
+def frame_for_truncated_bingrouper():
+ """
+ DataFrame used by groupby_with_truncated_bingrouper, made into
+ a separate fixture for easier re-use in
+ test_groupby_apply_timegrouper_with_nat_apply_squeeze
+ """
+ df = DataFrame(
+ {
+ "Quantity": [18, 3, 5, 1, 9, 3],
+ "Date": [
+ Timestamp(2013, 9, 1, 13, 0),
+ Timestamp(2013, 9, 1, 13, 5),
+ Timestamp(2013, 10, 1, 20, 0),
+ Timestamp(2013, 10, 3, 10, 0),
+ pd.NaT,
+ Timestamp(2013, 9, 2, 14, 0),
+ ],
+ }
+ )
+ return df
+
+
+@pytest.fixture
+def groupby_with_truncated_bingrouper(frame_for_truncated_bingrouper):
+ """
+ GroupBy object such that gb.grouper is a BinGrouper and
+ len(gb.grouper.result_index) < len(gb.grouper.group_keys_seq)
+
+ Aggregations on this groupby should have
+
+ dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date")
+
+ As either the index or an index level.
+ """
+ df = frame_for_truncated_bingrouper
+
+ tdg = Grouper(key="Date", freq="5D")
+ gb = df.groupby(tdg)
+
+ # check we're testing the case we're interested in
+ assert len(gb.grouper.result_index) != len(gb.grouper.group_keys_seq)
+
+ return gb
+
+
+class TestGroupBy:
+ def test_groupby_with_timegrouper(self):
+ # GH 4161
+ # TimeGrouper requires a sorted index
+ # also verifies that the resultant index has the correct name
+ df_original = DataFrame(
+ {
+ "Buyer": "Carl Carl Carl Carl Joe Carl".split(),
+ "Quantity": [18, 3, 5, 1, 9, 3],
+ "Date": [
+ datetime(2013, 9, 1, 13, 0),
+ datetime(2013, 9, 1, 13, 5),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 3, 10, 0),
+ datetime(2013, 12, 2, 12, 0),
+ datetime(2013, 9, 2, 14, 0),
+ ],
+ }
+ )
+
+ # GH 6908 change target column's order
+ df_reordered = df_original.sort_values(by="Quantity")
+
+ for df in [df_original, df_reordered]:
+ df = df.set_index(["Date"])
+
+ expected = DataFrame(
+ {"Buyer": 0, "Quantity": 0},
+ index=date_range(
+ "20130901", "20131205", freq="5D", name="Date", inclusive="left"
+ ),
+ )
+ # Cast to object to avoid implicit cast when setting entry to "CarlCarlCarl"
+ expected = expected.astype({"Buyer": object})
+ expected.iloc[0, 0] = "CarlCarlCarl"
+ expected.iloc[6, 0] = "CarlCarl"
+ expected.iloc[18, 0] = "Joe"
+ expected.iloc[[0, 6, 18], 1] = np.array([24, 6, 9], dtype="int64")
+
+ result1 = df.resample("5D").sum()
+ tm.assert_frame_equal(result1, expected)
+
+ df_sorted = df.sort_index()
+ result2 = df_sorted.groupby(Grouper(freq="5D")).sum()
+ tm.assert_frame_equal(result2, expected)
+
+ result3 = df.groupby(Grouper(freq="5D")).sum()
+ tm.assert_frame_equal(result3, expected)
+
+ @pytest.mark.parametrize("should_sort", [True, False])
+ def test_groupby_with_timegrouper_methods(self, should_sort):
+ # GH 3881
+ # make sure API of timegrouper conforms
+
+ df = DataFrame(
+ {
+ "Branch": "A A A A A B".split(),
+ "Buyer": "Carl Mark Carl Joe Joe Carl".split(),
+ "Quantity": [1, 3, 5, 8, 9, 3],
+ "Date": [
+ datetime(2013, 1, 1, 13, 0),
+ datetime(2013, 1, 1, 13, 5),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 2, 10, 0),
+ datetime(2013, 12, 2, 12, 0),
+ datetime(2013, 12, 2, 14, 0),
+ ],
+ }
+ )
+
+ if should_sort:
+ df = df.sort_values(by="Quantity", ascending=False)
+
+ df = df.set_index("Date", drop=False)
+ g = df.groupby(Grouper(freq="6M"))
+ assert g.group_keys
+
+ assert isinstance(g.grouper, BinGrouper)
+ groups = g.groups
+ assert isinstance(groups, dict)
+ assert len(groups) == 3
+
+ def test_timegrouper_with_reg_groups(self):
+ # GH 3794
+ # allow combination of timegrouper/reg groups
+
+ df_original = DataFrame(
+ {
+ "Branch": "A A A A A A A B".split(),
+ "Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(),
+ "Quantity": [1, 3, 5, 1, 8, 1, 9, 3],
+ "Date": [
+ datetime(2013, 1, 1, 13, 0),
+ datetime(2013, 1, 1, 13, 5),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 2, 10, 0),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 2, 10, 0),
+ datetime(2013, 12, 2, 12, 0),
+ datetime(2013, 12, 2, 14, 0),
+ ],
+ }
+ ).set_index("Date")
+
+ df_sorted = df_original.sort_values(by="Quantity", ascending=False)
+
+ for df in [df_original, df_sorted]:
+ expected = DataFrame(
+ {
+ "Buyer": "Carl Joe Mark".split(),
+ "Quantity": [10, 18, 3],
+ "Date": [
+ datetime(2013, 12, 31, 0, 0),
+ datetime(2013, 12, 31, 0, 0),
+ datetime(2013, 12, 31, 0, 0),
+ ],
+ }
+ ).set_index(["Date", "Buyer"])
+
+ msg = "The default value of numeric_only"
+ result = df.groupby([Grouper(freq="A"), "Buyer"]).sum(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ expected = DataFrame(
+ {
+ "Buyer": "Carl Mark Carl Joe".split(),
+ "Quantity": [1, 3, 9, 18],
+ "Date": [
+ datetime(2013, 1, 1, 0, 0),
+ datetime(2013, 1, 1, 0, 0),
+ datetime(2013, 7, 1, 0, 0),
+ datetime(2013, 7, 1, 0, 0),
+ ],
+ }
+ ).set_index(["Date", "Buyer"])
+ result = df.groupby([Grouper(freq="6MS"), "Buyer"]).sum(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ df_original = DataFrame(
+ {
+ "Branch": "A A A A A A A B".split(),
+ "Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(),
+ "Quantity": [1, 3, 5, 1, 8, 1, 9, 3],
+ "Date": [
+ datetime(2013, 10, 1, 13, 0),
+ datetime(2013, 10, 1, 13, 5),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 2, 10, 0),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 2, 10, 0),
+ datetime(2013, 10, 2, 12, 0),
+ datetime(2013, 10, 2, 14, 0),
+ ],
+ }
+ ).set_index("Date")
+
+ df_sorted = df_original.sort_values(by="Quantity", ascending=False)
+ for df in [df_original, df_sorted]:
+ expected = DataFrame(
+ {
+ "Buyer": "Carl Joe Mark Carl Joe".split(),
+ "Quantity": [6, 8, 3, 4, 10],
+ "Date": [
+ datetime(2013, 10, 1, 0, 0),
+ datetime(2013, 10, 1, 0, 0),
+ datetime(2013, 10, 1, 0, 0),
+ datetime(2013, 10, 2, 0, 0),
+ datetime(2013, 10, 2, 0, 0),
+ ],
+ }
+ ).set_index(["Date", "Buyer"])
+
+ result = df.groupby([Grouper(freq="1D"), "Buyer"]).sum(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby([Grouper(freq="1M"), "Buyer"]).sum(numeric_only=True)
+ expected = DataFrame(
+ {
+ "Buyer": "Carl Joe Mark".split(),
+ "Quantity": [10, 18, 3],
+ "Date": [
+ datetime(2013, 10, 31, 0, 0),
+ datetime(2013, 10, 31, 0, 0),
+ datetime(2013, 10, 31, 0, 0),
+ ],
+ }
+ ).set_index(["Date", "Buyer"])
+ tm.assert_frame_equal(result, expected)
+
+ # passing the name
+ df = df.reset_index()
+ result = df.groupby([Grouper(freq="1M", key="Date"), "Buyer"]).sum(
+ numeric_only=True
+ )
+ tm.assert_frame_equal(result, expected)
+
+ with pytest.raises(KeyError, match="'The grouper name foo is not found'"):
+ df.groupby([Grouper(freq="1M", key="foo"), "Buyer"]).sum()
+
+ # passing the level
+ df = df.set_index("Date")
+ result = df.groupby([Grouper(freq="1M", level="Date"), "Buyer"]).sum(
+ numeric_only=True
+ )
+ tm.assert_frame_equal(result, expected)
+ result = df.groupby([Grouper(freq="1M", level=0), "Buyer"]).sum(
+ numeric_only=True
+ )
+ tm.assert_frame_equal(result, expected)
+
+ with pytest.raises(ValueError, match="The level foo is not valid"):
+ df.groupby([Grouper(freq="1M", level="foo"), "Buyer"]).sum()
+
+ # multi names
+ df = df.copy()
+ df["Date"] = df.index + offsets.MonthEnd(2)
+ result = df.groupby([Grouper(freq="1M", key="Date"), "Buyer"]).sum(
+ numeric_only=True
+ )
+ expected = DataFrame(
+ {
+ "Buyer": "Carl Joe Mark".split(),
+ "Quantity": [10, 18, 3],
+ "Date": [
+ datetime(2013, 11, 30, 0, 0),
+ datetime(2013, 11, 30, 0, 0),
+ datetime(2013, 11, 30, 0, 0),
+ ],
+ }
+ ).set_index(["Date", "Buyer"])
+ tm.assert_frame_equal(result, expected)
+
+ # error as we have both a level and a name!
+ msg = "The Grouper cannot specify both a key and a level!"
+ with pytest.raises(ValueError, match=msg):
+ df.groupby(
+ [Grouper(freq="1M", key="Date", level="Date"), "Buyer"]
+ ).sum()
+
+ # single groupers
+ expected = DataFrame(
+ [[31]],
+ columns=["Quantity"],
+ index=DatetimeIndex(
+ [datetime(2013, 10, 31, 0, 0)], freq=offsets.MonthEnd(), name="Date"
+ ),
+ )
+ result = df.groupby(Grouper(freq="1M")).sum(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby([Grouper(freq="1M")]).sum(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ expected.index = expected.index.shift(1)
+ assert expected.index.freq == offsets.MonthEnd()
+ result = df.groupby(Grouper(freq="1M", key="Date")).sum(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby([Grouper(freq="1M", key="Date")]).sum(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("freq", ["D", "M", "A", "Q-APR"])
+ def test_timegrouper_with_reg_groups_freq(self, freq):
+ # GH 6764 multiple grouping with/without sort
+ df = DataFrame(
+ {
+ "date": pd.to_datetime(
+ [
+ "20121002",
+ "20121007",
+ "20130130",
+ "20130202",
+ "20130305",
+ "20121002",
+ "20121207",
+ "20130130",
+ "20130202",
+ "20130305",
+ "20130202",
+ "20130305",
+ ]
+ ),
+ "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5],
+ "whole_cost": [
+ 1790,
+ 364,
+ 280,
+ 259,
+ 201,
+ 623,
+ 90,
+ 312,
+ 359,
+ 301,
+ 359,
+ 801,
+ ],
+ "cost1": [12, 15, 10, 24, 39, 1, 0, 90, 45, 34, 1, 12],
+ }
+ ).set_index("date")
+
+ expected = (
+ df.groupby("user_id")["whole_cost"]
+ .resample(freq)
+ .sum(min_count=1) # XXX
+ .dropna()
+ .reorder_levels(["date", "user_id"])
+ .sort_index()
+ .astype("int64")
+ )
+ expected.name = "whole_cost"
+
+ result1 = (
+ df.sort_index().groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum()
+ )
+ tm.assert_series_equal(result1, expected)
+
+ result2 = df.groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum()
+ tm.assert_series_equal(result2, expected)
+
+ def test_timegrouper_get_group(self):
+ # GH 6914
+
+ df_original = DataFrame(
+ {
+ "Buyer": "Carl Joe Joe Carl Joe Carl".split(),
+ "Quantity": [18, 3, 5, 1, 9, 3],
+ "Date": [
+ datetime(2013, 9, 1, 13, 0),
+ datetime(2013, 9, 1, 13, 5),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 3, 10, 0),
+ datetime(2013, 12, 2, 12, 0),
+ datetime(2013, 9, 2, 14, 0),
+ ],
+ }
+ )
+ df_reordered = df_original.sort_values(by="Quantity")
+
+ # single grouping
+ expected_list = [
+ df_original.iloc[[0, 1, 5]],
+ df_original.iloc[[2, 3]],
+ df_original.iloc[[4]],
+ ]
+ dt_list = ["2013-09-30", "2013-10-31", "2013-12-31"]
+
+ for df in [df_original, df_reordered]:
+ grouped = df.groupby(Grouper(freq="M", key="Date"))
+ for t, expected in zip(dt_list, expected_list):
+ dt = Timestamp(t)
+ result = grouped.get_group(dt)
+ tm.assert_frame_equal(result, expected)
+
+ # multiple grouping
+ expected_list = [
+ df_original.iloc[[1]],
+ df_original.iloc[[3]],
+ df_original.iloc[[4]],
+ ]
+ g_list = [("Joe", "2013-09-30"), ("Carl", "2013-10-31"), ("Joe", "2013-12-31")]
+
+ for df in [df_original, df_reordered]:
+ grouped = df.groupby(["Buyer", Grouper(freq="M", key="Date")])
+ for (b, t), expected in zip(g_list, expected_list):
+ dt = Timestamp(t)
+ result = grouped.get_group((b, dt))
+ tm.assert_frame_equal(result, expected)
+
+ # with index
+ df_original = df_original.set_index("Date")
+ df_reordered = df_original.sort_values(by="Quantity")
+
+ expected_list = [
+ df_original.iloc[[0, 1, 5]],
+ df_original.iloc[[2, 3]],
+ df_original.iloc[[4]],
+ ]
+
+ for df in [df_original, df_reordered]:
+ grouped = df.groupby(Grouper(freq="M"))
+ for t, expected in zip(dt_list, expected_list):
+ dt = Timestamp(t)
+ result = grouped.get_group(dt)
+ tm.assert_frame_equal(result, expected)
+
+ def test_timegrouper_apply_return_type_series(self):
+ # Using `apply` with the `TimeGrouper` should give the
+ # same return type as an `apply` with a `Grouper`.
+ # Issue #11742
+ df = DataFrame({"date": ["10/10/2000", "11/10/2000"], "value": [10, 13]})
+ df_dt = df.copy()
+ df_dt["date"] = pd.to_datetime(df_dt["date"])
+
+ def sumfunc_series(x):
+ return Series([x["value"].sum()], ("sum",))
+
+ expected = df.groupby(Grouper(key="date")).apply(sumfunc_series)
+ result = df_dt.groupby(Grouper(freq="M", key="date")).apply(sumfunc_series)
+ tm.assert_frame_equal(
+ result.reset_index(drop=True), expected.reset_index(drop=True)
+ )
+
+ def test_timegrouper_apply_return_type_value(self):
+ # Using `apply` with the `TimeGrouper` should give the
+ # same return type as an `apply` with a `Grouper`.
+ # Issue #11742
+ df = DataFrame({"date": ["10/10/2000", "11/10/2000"], "value": [10, 13]})
+ df_dt = df.copy()
+ df_dt["date"] = pd.to_datetime(df_dt["date"])
+
+ def sumfunc_value(x):
+ return x.value.sum()
+
+ expected = df.groupby(Grouper(key="date")).apply(sumfunc_value)
+ result = df_dt.groupby(Grouper(freq="M", key="date")).apply(sumfunc_value)
+ tm.assert_series_equal(
+ result.reset_index(drop=True), expected.reset_index(drop=True)
+ )
+
+ def test_groupby_groups_datetimeindex(self):
+ # GH#1430
+ periods = 1000
+ ind = date_range(start="2012/1/1", freq="5min", periods=periods)
+ df = DataFrame(
+ {"high": np.arange(periods), "low": np.arange(periods)}, index=ind
+ )
+ grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
+
+ # it works!
+ groups = grouped.groups
+ assert isinstance(next(iter(groups.keys())), datetime)
+
+ # GH#11442
+ index = date_range("2015/01/01", periods=5, name="date")
+ df = DataFrame({"A": [5, 6, 7, 8, 9], "B": [1, 2, 3, 4, 5]}, index=index)
+ result = df.groupby(level="date").groups
+ dates = ["2015-01-05", "2015-01-04", "2015-01-03", "2015-01-02", "2015-01-01"]
+ expected = {
+ Timestamp(date): DatetimeIndex([date], name="date") for date in dates
+ }
+ tm.assert_dict_equal(result, expected)
+
+ grouped = df.groupby(level="date")
+ for date in dates:
+ result = grouped.get_group(date)
+ data = [[df.loc[date, "A"], df.loc[date, "B"]]]
+ expected_index = DatetimeIndex([date], name="date", freq="D")
+ expected = DataFrame(data, columns=list("AB"), index=expected_index)
+ tm.assert_frame_equal(result, expected)
+
+ def test_groupby_groups_datetimeindex_tz(self):
+ # GH 3950
+ dates = [
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ ]
+ df = DataFrame(
+ {
+ "label": ["a", "a", "a", "b", "b", "b"],
+ "datetime": dates,
+ "value1": np.arange(6, dtype="int64"),
+ "value2": [1, 2] * 3,
+ }
+ )
+ df["datetime"] = df["datetime"].apply(lambda d: Timestamp(d, tz="US/Pacific"))
+
+ exp_idx1 = DatetimeIndex(
+ [
+ "2011-07-19 07:00:00",
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ "2011-07-19 09:00:00",
+ ],
+ tz="US/Pacific",
+ name="datetime",
+ )
+ exp_idx2 = Index(["a", "b"] * 3, name="label")
+ exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2])
+ expected = DataFrame(
+ {"value1": [0, 3, 1, 4, 2, 5], "value2": [1, 2, 2, 1, 1, 2]},
+ index=exp_idx,
+ columns=["value1", "value2"],
+ )
+
+ result = df.groupby(["datetime", "label"]).sum()
+ tm.assert_frame_equal(result, expected)
+
+ # by level
+ didx = DatetimeIndex(dates, tz="Asia/Tokyo")
+ df = DataFrame(
+ {"value1": np.arange(6, dtype="int64"), "value2": [1, 2, 3, 1, 2, 3]},
+ index=didx,
+ )
+
+ exp_idx = DatetimeIndex(
+ ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"],
+ tz="Asia/Tokyo",
+ )
+ expected = DataFrame(
+ {"value1": [3, 5, 7], "value2": [2, 4, 6]},
+ index=exp_idx,
+ columns=["value1", "value2"],
+ )
+
+ result = df.groupby(level=0).sum()
+ tm.assert_frame_equal(result, expected)
+
+ def test_frame_datetime64_handling_groupby(self):
+ # it works!
+ df = DataFrame(
+ [(3, np.datetime64("2012-07-03")), (3, np.datetime64("2012-07-04"))],
+ columns=["a", "date"],
+ )
+ result = df.groupby("a").first()
+ assert result["date"][3] == Timestamp("2012-07-03")
+
+ def test_groupby_multi_timezone(self):
+ # combining multiple / different timezones yields UTC
+
+ data = """0,2000-01-28 16:47:00,America/Chicago
+1,2000-01-29 16:48:00,America/Chicago
+2,2000-01-30 16:49:00,America/Los_Angeles
+3,2000-01-31 16:50:00,America/Chicago
+4,2000-01-01 16:50:00,America/New_York"""
+
+ df = pd.read_csv(StringIO(data), header=None, names=["value", "date", "tz"])
+ result = df.groupby("tz", group_keys=False).date.apply(
+ lambda x: pd.to_datetime(x).dt.tz_localize(x.name)
+ )
+
+ expected = Series(
+ [
+ Timestamp("2000-01-28 16:47:00-0600", tz="America/Chicago"),
+ Timestamp("2000-01-29 16:48:00-0600", tz="America/Chicago"),
+ Timestamp("2000-01-30 16:49:00-0800", tz="America/Los_Angeles"),
+ Timestamp("2000-01-31 16:50:00-0600", tz="America/Chicago"),
+ Timestamp("2000-01-01 16:50:00-0500", tz="America/New_York"),
+ ],
+ name="date",
+ dtype=object,
+ )
+ tm.assert_series_equal(result, expected)
+
+ tz = "America/Chicago"
+ res_values = df.groupby("tz").date.get_group(tz)
+ result = pd.to_datetime(res_values).dt.tz_localize(tz)
+ exp_values = Series(
+ ["2000-01-28 16:47:00", "2000-01-29 16:48:00", "2000-01-31 16:50:00"],
+ index=[0, 1, 3],
+ name="date",
+ )
+ expected = pd.to_datetime(exp_values).dt.tz_localize(tz)
+ tm.assert_series_equal(result, expected)
+
+ def test_groupby_groups_periods(self):
+ dates = [
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ ]
+ df = DataFrame(
+ {
+ "label": ["a", "a", "a", "b", "b", "b"],
+ "period": [pd.Period(d, freq="H") for d in dates],
+ "value1": np.arange(6, dtype="int64"),
+ "value2": [1, 2] * 3,
+ }
+ )
+
+ exp_idx1 = pd.PeriodIndex(
+ [
+ "2011-07-19 07:00:00",
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ "2011-07-19 09:00:00",
+ ],
+ freq="H",
+ name="period",
+ )
+ exp_idx2 = Index(["a", "b"] * 3, name="label")
+ exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2])
+ expected = DataFrame(
+ {"value1": [0, 3, 1, 4, 2, 5], "value2": [1, 2, 2, 1, 1, 2]},
+ index=exp_idx,
+ columns=["value1", "value2"],
+ )
+
+ result = df.groupby(["period", "label"]).sum()
+ tm.assert_frame_equal(result, expected)
+
+ # by level
+ didx = pd.PeriodIndex(dates, freq="H")
+ df = DataFrame(
+ {"value1": np.arange(6, dtype="int64"), "value2": [1, 2, 3, 1, 2, 3]},
+ index=didx,
+ )
+
+ exp_idx = pd.PeriodIndex(
+ ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"],
+ freq="H",
+ )
+ expected = DataFrame(
+ {"value1": [3, 5, 7], "value2": [2, 4, 6]},
+ index=exp_idx,
+ columns=["value1", "value2"],
+ )
+
+ result = df.groupby(level=0).sum()
+ tm.assert_frame_equal(result, expected)
+
+ def test_groupby_first_datetime64(self):
+ df = DataFrame([(1, 1351036800000000000), (2, 1351036800000000000)])
+ df[1] = df[1].view("M8[ns]")
+
+ assert issubclass(df[1].dtype.type, np.datetime64)
+
+ result = df.groupby(level=0).first()
+ got_dt = result[1].dtype
+ assert issubclass(got_dt.type, np.datetime64)
+
+ result = df[1].groupby(level=0).first()
+ got_dt = result.dtype
+ assert issubclass(got_dt.type, np.datetime64)
+
+ def test_groupby_max_datetime64(self):
+ # GH 5869
+ # datetimelike dtype conversion from int
+ df = DataFrame({"A": Timestamp("20130101"), "B": np.arange(5)})
+ # TODO: can we retain second reso in .apply here?
+ expected = df.groupby("A")["A"].apply(lambda x: x.max()).astype("M8[s]")
+ result = df.groupby("A")["A"].max()
+ tm.assert_series_equal(result, expected)
+
+ def test_groupby_datetime64_32_bit(self):
+ # GH 6410 / numpy 4328
+ # 32-bit under 1.9-dev indexing issue
+
+ df = DataFrame({"A": range(2), "B": [Timestamp("2000-01-1")] * 2})
+ result = df.groupby("A")["B"].transform("min")
+ expected = Series([Timestamp("2000-01-1")] * 2, name="B")
+ tm.assert_series_equal(result, expected)
+
+ def test_groupby_with_timezone_selection(self):
+ # GH 11616
+ # Test that column selection returns output in correct timezone.
+
+ df = DataFrame(
+ {
+ "factor": np.random.default_rng(2).integers(0, 3, size=60),
+ "time": date_range("01/01/2000 00:00", periods=60, freq="s", tz="UTC"),
+ }
+ )
+ df1 = df.groupby("factor").max()["time"]
+ df2 = df.groupby("factor")["time"].max()
+ tm.assert_series_equal(df1, df2)
+
+ def test_timezone_info(self):
+ # see gh-11682: Timezone info lost when broadcasting
+ # scalar datetime to DataFrame
+
+ df = DataFrame({"a": [1], "b": [datetime.now(pytz.utc)]})
+ assert df["b"][0].tzinfo == pytz.utc
+ df = DataFrame({"a": [1, 2, 3]})
+ df["b"] = datetime.now(pytz.utc)
+ assert df["b"][0].tzinfo == pytz.utc
+
+ def test_datetime_count(self):
+ df = DataFrame(
+ {"a": [1, 2, 3] * 2, "dates": date_range("now", periods=6, freq="T")}
+ )
+ result = df.groupby("a").dates.count()
+ expected = Series([2, 2, 2], index=Index([1, 2, 3], name="a"), name="dates")
+ tm.assert_series_equal(result, expected)
+
+ def test_first_last_max_min_on_time_data(self):
+ # GH 10295
+ # Verify that NaT is not in the result of max, min, first and last on
+ # Dataframe with datetime or timedelta values.
+ df_test = DataFrame(
+ {
+ "dt": [
+ np.nan,
+ "2015-07-24 10:10",
+ "2015-07-25 11:11",
+ "2015-07-23 12:12",
+ np.nan,
+ ],
+ "td": [
+ np.nan,
+ timedelta(days=1),
+ timedelta(days=2),
+ timedelta(days=3),
+ np.nan,
+ ],
+ }
+ )
+ df_test.dt = pd.to_datetime(df_test.dt)
+ df_test["group"] = "A"
+ df_ref = df_test[df_test.dt.notna()]
+
+ grouped_test = df_test.groupby("group")
+ grouped_ref = df_ref.groupby("group")
+
+ tm.assert_frame_equal(grouped_ref.max(), grouped_test.max())
+ tm.assert_frame_equal(grouped_ref.min(), grouped_test.min())
+ tm.assert_frame_equal(grouped_ref.first(), grouped_test.first())
+ tm.assert_frame_equal(grouped_ref.last(), grouped_test.last())
+
+ def test_nunique_with_timegrouper_and_nat(self):
+ # GH 17575
+ test = DataFrame(
+ {
+ "time": [
+ Timestamp("2016-06-28 09:35:35"),
+ pd.NaT,
+ Timestamp("2016-06-28 16:46:28"),
+ ],
+ "data": ["1", "2", "3"],
+ }
+ )
+
+ grouper = Grouper(key="time", freq="h")
+ result = test.groupby(grouper)["data"].nunique()
+ expected = test[test.time.notnull()].groupby(grouper)["data"].nunique()
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(result, expected)
+
+ def test_scalar_call_versus_list_call(self):
+ # Issue: 17530
+ data_frame = {
+ "location": ["shanghai", "beijing", "shanghai"],
+ "time": Series(
+ ["2017-08-09 13:32:23", "2017-08-11 23:23:15", "2017-08-11 22:23:15"],
+ dtype="datetime64[ns]",
+ ),
+ "value": [1, 2, 3],
+ }
+ data_frame = DataFrame(data_frame).set_index("time")
+ grouper = Grouper(freq="D")
+
+ grouped = data_frame.groupby(grouper)
+ result = grouped.count()
+ grouped = data_frame.groupby([grouper])
+ expected = grouped.count()
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_grouper_period_index(self):
+ # GH 32108
+ periods = 2
+ index = pd.period_range(
+ start="2018-01", periods=periods, freq="M", name="Month"
+ )
+ period_series = Series(range(periods), index=index)
+ result = period_series.groupby(period_series.index.month).sum()
+
+ expected = Series(
+ range(0, periods), index=Index(range(1, periods + 1), name=index.name)
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_groupby_apply_timegrouper_with_nat_dict_returns(
+ self, groupby_with_truncated_bingrouper
+ ):
+ # GH#43500 case where gb.grouper.result_index and gb.grouper.group_keys_seq
+ # have different lengths that goes through the `isinstance(values[0], dict)`
+ # path
+ gb = groupby_with_truncated_bingrouper
+
+ res = gb["Quantity"].apply(lambda x: {"foo": len(x)})
+
+ dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date")
+ mi = MultiIndex.from_arrays([dti, ["foo"] * len(dti)])
+ expected = Series([3, 0, 0, 0, 0, 0, 2], index=mi, name="Quantity")
+ tm.assert_series_equal(res, expected)
+
+ def test_groupby_apply_timegrouper_with_nat_scalar_returns(
+ self, groupby_with_truncated_bingrouper
+ ):
+ # GH#43500 Previously raised ValueError bc used index with incorrect
+ # length in wrap_applied_result
+ gb = groupby_with_truncated_bingrouper
+
+ res = gb["Quantity"].apply(lambda x: x.iloc[0] if len(x) else np.nan)
+
+ dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date")
+ expected = Series(
+ [18, np.nan, np.nan, np.nan, np.nan, np.nan, 5],
+ index=dti._with_freq(None),
+ name="Quantity",
+ )
+
+ tm.assert_series_equal(res, expected)
+
+ def test_groupby_apply_timegrouper_with_nat_apply_squeeze(
+ self, frame_for_truncated_bingrouper
+ ):
+ df = frame_for_truncated_bingrouper
+
+ # We need to create a GroupBy object with only one non-NaT group,
+ # so use a huge freq so that all non-NaT dates will be grouped together
+ tdg = Grouper(key="Date", freq="100Y")
+ gb = df.groupby(tdg)
+
+ # check that we will go through the singular_series path
+ # in _wrap_applied_output_series
+ assert gb.ngroups == 1
+ assert gb._selected_obj._get_axis(gb.axis).nlevels == 1
+
+ # function that returns a Series
+ res = gb.apply(lambda x: x["Quantity"] * 2)
+
+ expected = DataFrame(
+ [[36, 6, 6, 10, 2]],
+ index=Index([Timestamp("2013-12-31")], name="Date"),
+ columns=Index([0, 1, 5, 2, 3], name="Quantity"),
+ )
+ tm.assert_frame_equal(res, expected)
+
+ @pytest.mark.single_cpu
+ def test_groupby_agg_numba_timegrouper_with_nat(
+ self, groupby_with_truncated_bingrouper
+ ):
+ pytest.importorskip("numba")
+
+ # See discussion in GH#43487
+ gb = groupby_with_truncated_bingrouper
+
+ result = gb["Quantity"].aggregate(
+ lambda values, index: np.nanmean(values), engine="numba"
+ )
+
+ expected = gb["Quantity"].aggregate("mean")
+ tm.assert_series_equal(result, expected)
+
+ result_df = gb[["Quantity"]].aggregate(
+ lambda values, index: np.nanmean(values), engine="numba"
+ )
+ expected_df = gb[["Quantity"]].aggregate("mean")
+ tm.assert_frame_equal(result_df, expected_df)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_value_counts.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_value_counts.py
new file mode 100644
index 0000000000000000000000000000000000000000..070bdda976dc4e4de9d978ff2acb15c5d3477487
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/groupby/test_value_counts.py
@@ -0,0 +1,1175 @@
+"""
+these are systematically testing all of the args to value_counts
+with different size combinations. This is to ensure stability of the sorting
+and proper parameter handling
+"""
+
+from itertools import product
+
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ DataFrame,
+ Grouper,
+ Index,
+ MultiIndex,
+ Series,
+ date_range,
+ to_datetime,
+)
+import pandas._testing as tm
+from pandas.util.version import Version
+
+
+def tests_value_counts_index_names_category_column():
+ # GH44324 Missing name of index category column
+ df = DataFrame(
+ {
+ "gender": ["female"],
+ "country": ["US"],
+ }
+ )
+ df["gender"] = df["gender"].astype("category")
+ result = df.groupby("country")["gender"].value_counts()
+
+ # Construct expected, very specific multiindex
+ df_mi_expected = DataFrame([["US", "female"]], columns=["country", "gender"])
+ df_mi_expected["gender"] = df_mi_expected["gender"].astype("category")
+ mi_expected = MultiIndex.from_frame(df_mi_expected)
+ expected = Series([1], index=mi_expected, name="count")
+
+ tm.assert_series_equal(result, expected)
+
+
+# our starting frame
+def seed_df(seed_nans, n, m):
+ days = date_range("2015-08-24", periods=10)
+
+ frame = DataFrame(
+ {
+ "1st": np.random.default_rng(2).choice(list("abcd"), n),
+ "2nd": np.random.default_rng(2).choice(days, n),
+ "3rd": np.random.default_rng(2).integers(1, m + 1, n),
+ }
+ )
+
+ if seed_nans:
+ # Explicitly cast to float to avoid implicit cast when setting nan
+ frame["3rd"] = frame["3rd"].astype("float")
+ frame.loc[1::11, "1st"] = np.nan
+ frame.loc[3::17, "2nd"] = np.nan
+ frame.loc[7::19, "3rd"] = np.nan
+ frame.loc[8::19, "3rd"] = np.nan
+ frame.loc[9::19, "3rd"] = np.nan
+
+ return frame
+
+
+# create input df, keys, and the bins
+binned = []
+ids = []
+for seed_nans in [True, False]:
+ for n, m in product((100, 1000), (5, 20)):
+ df = seed_df(seed_nans, n, m)
+ bins = None, np.arange(0, max(5, df["3rd"].max()) + 1, 2)
+ keys = "1st", "2nd", ["1st", "2nd"]
+ for k, b in product(keys, bins):
+ binned.append((df, k, b, n, m))
+ ids.append(f"{k}-{n}-{m}")
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize("df, keys, bins, n, m", binned, ids=ids)
+@pytest.mark.parametrize("isort", [True, False])
+@pytest.mark.parametrize("normalize, name", [(True, "proportion"), (False, "count")])
+@pytest.mark.parametrize("sort", [True, False])
+@pytest.mark.parametrize("ascending", [True, False])
+@pytest.mark.parametrize("dropna", [True, False])
+def test_series_groupby_value_counts(
+ df, keys, bins, n, m, isort, normalize, name, sort, ascending, dropna
+):
+ def rebuild_index(df):
+ arr = list(map(df.index.get_level_values, range(df.index.nlevels)))
+ df.index = MultiIndex.from_arrays(arr, names=df.index.names)
+ return df
+
+ kwargs = {
+ "normalize": normalize,
+ "sort": sort,
+ "ascending": ascending,
+ "dropna": dropna,
+ "bins": bins,
+ }
+
+ gr = df.groupby(keys, sort=isort)
+ left = gr["3rd"].value_counts(**kwargs)
+
+ gr = df.groupby(keys, sort=isort)
+ right = gr["3rd"].apply(Series.value_counts, **kwargs)
+ right.index.names = right.index.names[:-1] + ["3rd"]
+ # https://github.com/pandas-dev/pandas/issues/49909
+ right = right.rename(name)
+
+ # have to sort on index because of unstable sort on values
+ left, right = map(rebuild_index, (left, right)) # xref GH9212
+ tm.assert_series_equal(left.sort_index(), right.sort_index())
+
+
+@pytest.mark.parametrize("utc", [True, False])
+def test_series_groupby_value_counts_with_grouper(utc):
+ # GH28479
+ df = DataFrame(
+ {
+ "Timestamp": [
+ 1565083561,
+ 1565083561 + 86400,
+ 1565083561 + 86500,
+ 1565083561 + 86400 * 2,
+ 1565083561 + 86400 * 3,
+ 1565083561 + 86500 * 3,
+ 1565083561 + 86400 * 4,
+ ],
+ "Food": ["apple", "apple", "banana", "banana", "orange", "orange", "pear"],
+ }
+ ).drop([3])
+
+ df["Datetime"] = to_datetime(df["Timestamp"], utc=utc, unit="s")
+ dfg = df.groupby(Grouper(freq="1D", key="Datetime"))
+
+ # have to sort on index because of unstable sort on values xref GH9212
+ result = dfg["Food"].value_counts().sort_index()
+ expected = dfg["Food"].apply(Series.value_counts).sort_index()
+ expected.index.names = result.index.names
+ # https://github.com/pandas-dev/pandas/issues/49909
+ expected = expected.rename("count")
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("columns", [["A", "B"], ["A", "B", "C"]])
+def test_series_groupby_value_counts_empty(columns):
+ # GH39172
+ df = DataFrame(columns=columns)
+ dfg = df.groupby(columns[:-1])
+
+ result = dfg[columns[-1]].value_counts()
+ expected = Series([], dtype=result.dtype, name="count")
+ expected.index = MultiIndex.from_arrays([[]] * len(columns), names=columns)
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("columns", [["A", "B"], ["A", "B", "C"]])
+def test_series_groupby_value_counts_one_row(columns):
+ # GH42618
+ df = DataFrame(data=[range(len(columns))], columns=columns)
+ dfg = df.groupby(columns[:-1])
+
+ result = dfg[columns[-1]].value_counts()
+ expected = df.value_counts()
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_series_groupby_value_counts_on_categorical():
+ # GH38672
+
+ s = Series(Categorical(["a"], categories=["a", "b"]))
+ result = s.groupby([0]).value_counts()
+
+ expected = Series(
+ data=[1, 0],
+ index=MultiIndex.from_arrays(
+ [
+ np.array([0, 0]),
+ CategoricalIndex(
+ ["a", "b"], categories=["a", "b"], ordered=False, dtype="category"
+ ),
+ ]
+ ),
+ name="count",
+ )
+
+ # Expected:
+ # 0 a 1
+ # b 0
+ # dtype: int64
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_series_groupby_value_counts_no_sort():
+ # GH#50482
+ df = DataFrame(
+ {
+ "gender": ["male", "male", "female", "male", "female", "male"],
+ "education": ["low", "medium", "high", "low", "high", "low"],
+ "country": ["US", "FR", "US", "FR", "FR", "FR"],
+ }
+ )
+ gb = df.groupby(["country", "gender"], sort=False)["education"]
+ result = gb.value_counts(sort=False)
+ index = MultiIndex(
+ levels=[["US", "FR"], ["male", "female"], ["low", "medium", "high"]],
+ codes=[[0, 1, 0, 1, 1], [0, 0, 1, 0, 1], [0, 1, 2, 0, 2]],
+ names=["country", "gender", "education"],
+ )
+ expected = Series([1, 1, 1, 2, 1], index=index, name="count")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.fixture
+def education_df():
+ return DataFrame(
+ {
+ "gender": ["male", "male", "female", "male", "female", "male"],
+ "education": ["low", "medium", "high", "low", "high", "low"],
+ "country": ["US", "FR", "US", "FR", "FR", "FR"],
+ }
+ )
+
+
+def test_axis(education_df):
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ gp = education_df.groupby("country", axis=1)
+ with pytest.raises(NotImplementedError, match="axis"):
+ gp.value_counts()
+
+
+def test_bad_subset(education_df):
+ gp = education_df.groupby("country")
+ with pytest.raises(ValueError, match="subset"):
+ gp.value_counts(subset=["country"])
+
+
+def test_basic(education_df, request):
+ # gh43564
+ if Version(np.__version__) >= Version("1.25"):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=(
+ "pandas default unstable sorting of duplicates"
+ "issue with numpy>=1.25 with AVX instructions"
+ ),
+ strict=False,
+ )
+ )
+ result = education_df.groupby("country")[["gender", "education"]].value_counts(
+ normalize=True
+ )
+ expected = Series(
+ data=[0.5, 0.25, 0.25, 0.5, 0.5],
+ index=MultiIndex.from_tuples(
+ [
+ ("FR", "male", "low"),
+ ("FR", "female", "high"),
+ ("FR", "male", "medium"),
+ ("US", "female", "high"),
+ ("US", "male", "low"),
+ ],
+ names=["country", "gender", "education"],
+ ),
+ name="proportion",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def _frame_value_counts(df, keys, normalize, sort, ascending):
+ return df[keys].value_counts(normalize=normalize, sort=sort, ascending=ascending)
+
+
+@pytest.mark.parametrize("groupby", ["column", "array", "function"])
+@pytest.mark.parametrize("normalize, name", [(True, "proportion"), (False, "count")])
+@pytest.mark.parametrize(
+ "sort, ascending",
+ [
+ (False, None),
+ (True, True),
+ (True, False),
+ ],
+)
+@pytest.mark.parametrize("as_index", [True, False])
+@pytest.mark.parametrize("frame", [True, False])
+def test_against_frame_and_seriesgroupby(
+ education_df, groupby, normalize, name, sort, ascending, as_index, frame, request
+):
+ # test all parameters:
+ # - Use column, array or function as by= parameter
+ # - Whether or not to normalize
+ # - Whether or not to sort and how
+ # - Whether or not to use the groupby as an index
+ # - 3-way compare against:
+ # - apply with :meth:`~DataFrame.value_counts`
+ # - `~SeriesGroupBy.value_counts`
+ if Version(np.__version__) >= Version("1.25") and frame and sort and normalize:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=(
+ "pandas default unstable sorting of duplicates"
+ "issue with numpy>=1.25 with AVX instructions"
+ ),
+ strict=False,
+ )
+ )
+ by = {
+ "column": "country",
+ "array": education_df["country"].values,
+ "function": lambda x: education_df["country"][x] == "US",
+ }[groupby]
+
+ gp = education_df.groupby(by=by, as_index=as_index)
+ result = gp[["gender", "education"]].value_counts(
+ normalize=normalize, sort=sort, ascending=ascending
+ )
+ if frame:
+ # compare against apply with DataFrame value_counts
+ expected = gp.apply(
+ _frame_value_counts, ["gender", "education"], normalize, sort, ascending
+ )
+
+ if as_index:
+ tm.assert_series_equal(result, expected)
+ else:
+ name = "proportion" if normalize else "count"
+ expected = expected.reset_index().rename({0: name}, axis=1)
+ if groupby == "column":
+ expected = expected.rename({"level_0": "country"}, axis=1)
+ expected["country"] = np.where(expected["country"], "US", "FR")
+ elif groupby == "function":
+ expected["level_0"] = expected["level_0"] == 1
+ else:
+ expected["level_0"] = np.where(expected["level_0"], "US", "FR")
+ tm.assert_frame_equal(result, expected)
+ else:
+ # compare against SeriesGroupBy value_counts
+ education_df["both"] = education_df["gender"] + "-" + education_df["education"]
+ expected = gp["both"].value_counts(
+ normalize=normalize, sort=sort, ascending=ascending
+ )
+ expected.name = name
+ if as_index:
+ index_frame = expected.index.to_frame(index=False)
+ index_frame["gender"] = index_frame["both"].str.split("-").str.get(0)
+ index_frame["education"] = index_frame["both"].str.split("-").str.get(1)
+ del index_frame["both"]
+ index_frame = index_frame.rename({0: None}, axis=1)
+ expected.index = MultiIndex.from_frame(index_frame)
+ tm.assert_series_equal(result, expected)
+ else:
+ expected.insert(1, "gender", expected["both"].str.split("-").str.get(0))
+ expected.insert(2, "education", expected["both"].str.split("-").str.get(1))
+ del expected["both"]
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ object,
+ pytest.param("string[pyarrow_numpy]", marks=td.skip_if_no("pyarrow")),
+ pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")),
+ ],
+)
+@pytest.mark.parametrize("normalize", [True, False])
+@pytest.mark.parametrize(
+ "sort, ascending, expected_rows, expected_count, expected_group_size",
+ [
+ (False, None, [0, 1, 2, 3, 4], [1, 1, 1, 2, 1], [1, 3, 1, 3, 1]),
+ (True, False, [4, 3, 1, 2, 0], [1, 2, 1, 1, 1], [1, 3, 3, 1, 1]),
+ (True, True, [4, 1, 3, 2, 0], [1, 1, 2, 1, 1], [1, 3, 3, 1, 1]),
+ ],
+)
+def test_compound(
+ education_df,
+ normalize,
+ sort,
+ ascending,
+ expected_rows,
+ expected_count,
+ expected_group_size,
+ dtype,
+):
+ education_df = education_df.astype(dtype)
+ education_df.columns = education_df.columns.astype(dtype)
+ # Multiple groupby keys and as_index=False
+ gp = education_df.groupby(["country", "gender"], as_index=False, sort=False)
+ result = gp["education"].value_counts(
+ normalize=normalize, sort=sort, ascending=ascending
+ )
+ expected = DataFrame()
+ for column in ["country", "gender", "education"]:
+ expected[column] = [education_df[column][row] for row in expected_rows]
+ expected = expected.astype(dtype)
+ expected.columns = expected.columns.astype(dtype)
+ if normalize:
+ expected["proportion"] = expected_count
+ expected["proportion"] /= expected_group_size
+ if dtype == "string[pyarrow]":
+ expected["proportion"] = expected["proportion"].convert_dtypes()
+ else:
+ expected["count"] = expected_count
+ if dtype == "string[pyarrow]":
+ expected["count"] = expected["count"].convert_dtypes()
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.fixture
+def animals_df():
+ return DataFrame(
+ {"key": [1, 1, 1, 1], "num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]},
+ index=["falcon", "dog", "cat", "ant"],
+ )
+
+
+@pytest.mark.parametrize(
+ "sort, ascending, normalize, name, expected_data, expected_index",
+ [
+ (False, None, False, "count", [1, 2, 1], [(1, 1, 1), (2, 4, 6), (2, 0, 0)]),
+ (True, True, False, "count", [1, 1, 2], [(1, 1, 1), (2, 6, 4), (2, 0, 0)]),
+ (True, False, False, "count", [2, 1, 1], [(1, 1, 1), (4, 2, 6), (0, 2, 0)]),
+ (
+ True,
+ False,
+ True,
+ "proportion",
+ [0.5, 0.25, 0.25],
+ [(1, 1, 1), (4, 2, 6), (0, 2, 0)],
+ ),
+ ],
+)
+def test_data_frame_value_counts(
+ animals_df, sort, ascending, normalize, name, expected_data, expected_index
+):
+ # 3-way compare with :meth:`~DataFrame.value_counts`
+ # Tests from frame/methods/test_value_counts.py
+ result_frame = animals_df.value_counts(
+ sort=sort, ascending=ascending, normalize=normalize
+ )
+ expected = Series(
+ data=expected_data,
+ index=MultiIndex.from_arrays(
+ expected_index, names=["key", "num_legs", "num_wings"]
+ ),
+ name=name,
+ )
+ tm.assert_series_equal(result_frame, expected)
+
+ result_frame_groupby = animals_df.groupby("key").value_counts(
+ sort=sort, ascending=ascending, normalize=normalize
+ )
+
+ tm.assert_series_equal(result_frame_groupby, expected)
+
+
+@pytest.fixture
+def nulls_df():
+ n = np.nan
+ return DataFrame(
+ {
+ "A": [1, 1, n, 4, n, 6, 6, 6, 6],
+ "B": [1, 1, 3, n, n, 6, 6, 6, 6],
+ "C": [1, 2, 3, 4, 5, 6, n, 8, n],
+ "D": [1, 2, 3, 4, 5, 6, 7, n, n],
+ }
+ )
+
+
+@pytest.mark.parametrize(
+ "group_dropna, count_dropna, expected_rows, expected_values",
+ [
+ (
+ False,
+ False,
+ [0, 1, 3, 5, 7, 6, 8, 2, 4],
+ [0.5, 0.5, 1.0, 0.25, 0.25, 0.25, 0.25, 1.0, 1.0],
+ ),
+ (False, True, [0, 1, 3, 5, 2, 4], [0.5, 0.5, 1.0, 1.0, 1.0, 1.0]),
+ (True, False, [0, 1, 5, 7, 6, 8], [0.5, 0.5, 0.25, 0.25, 0.25, 0.25]),
+ (True, True, [0, 1, 5], [0.5, 0.5, 1.0]),
+ ],
+)
+def test_dropna_combinations(
+ nulls_df, group_dropna, count_dropna, expected_rows, expected_values, request
+):
+ if Version(np.__version__) >= Version("1.25") and not group_dropna:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=(
+ "pandas default unstable sorting of duplicates"
+ "issue with numpy>=1.25 with AVX instructions"
+ ),
+ strict=False,
+ )
+ )
+ gp = nulls_df.groupby(["A", "B"], dropna=group_dropna)
+ result = gp.value_counts(normalize=True, sort=True, dropna=count_dropna)
+ columns = DataFrame()
+ for column in nulls_df.columns:
+ columns[column] = [nulls_df[column][row] for row in expected_rows]
+ index = MultiIndex.from_frame(columns)
+ expected = Series(data=expected_values, index=index, name="proportion")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.fixture
+def names_with_nulls_df(nulls_fixture):
+ return DataFrame(
+ {
+ "key": [1, 1, 1, 1],
+ "first_name": ["John", "Anne", "John", "Beth"],
+ "middle_name": ["Smith", nulls_fixture, nulls_fixture, "Louise"],
+ },
+ )
+
+
+@pytest.mark.parametrize(
+ "dropna, expected_data, expected_index",
+ [
+ (
+ True,
+ [1, 1],
+ MultiIndex.from_arrays(
+ [(1, 1), ("Beth", "John"), ("Louise", "Smith")],
+ names=["key", "first_name", "middle_name"],
+ ),
+ ),
+ (
+ False,
+ [1, 1, 1, 1],
+ MultiIndex(
+ levels=[
+ Index([1]),
+ Index(["Anne", "Beth", "John"]),
+ Index(["Louise", "Smith", np.nan]),
+ ],
+ codes=[[0, 0, 0, 0], [0, 1, 2, 2], [2, 0, 1, 2]],
+ names=["key", "first_name", "middle_name"],
+ ),
+ ),
+ ],
+)
+@pytest.mark.parametrize("normalize, name", [(False, "count"), (True, "proportion")])
+def test_data_frame_value_counts_dropna(
+ names_with_nulls_df, dropna, normalize, name, expected_data, expected_index
+):
+ # GH 41334
+ # 3-way compare with :meth:`~DataFrame.value_counts`
+ # Tests with nulls from frame/methods/test_value_counts.py
+ result_frame = names_with_nulls_df.value_counts(dropna=dropna, normalize=normalize)
+ expected = Series(
+ data=expected_data,
+ index=expected_index,
+ name=name,
+ )
+ if normalize:
+ expected /= float(len(expected_data))
+
+ tm.assert_series_equal(result_frame, expected)
+
+ result_frame_groupby = names_with_nulls_df.groupby("key").value_counts(
+ dropna=dropna, normalize=normalize
+ )
+
+ tm.assert_series_equal(result_frame_groupby, expected)
+
+
+@pytest.mark.parametrize("as_index", [False, True])
+@pytest.mark.parametrize("observed", [False, True])
+@pytest.mark.parametrize(
+ "normalize, name, expected_data",
+ [
+ (
+ False,
+ "count",
+ np.array([2, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0], dtype=np.int64),
+ ),
+ (
+ True,
+ "proportion",
+ np.array([0.5, 0.25, 0.25, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0]),
+ ),
+ ],
+)
+def test_categorical_single_grouper_with_only_observed_categories(
+ education_df, as_index, observed, normalize, name, expected_data, request
+):
+ # Test single categorical grouper with only observed grouping categories
+ # when non-groupers are also categorical
+ if Version(np.__version__) >= Version("1.25"):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=(
+ "pandas default unstable sorting of duplicates"
+ "issue with numpy>=1.25 with AVX instructions"
+ ),
+ strict=False,
+ )
+ )
+
+ gp = education_df.astype("category").groupby(
+ "country", as_index=as_index, observed=observed
+ )
+ result = gp.value_counts(normalize=normalize)
+
+ expected_index = MultiIndex.from_tuples(
+ [
+ ("FR", "male", "low"),
+ ("FR", "female", "high"),
+ ("FR", "male", "medium"),
+ ("FR", "female", "low"),
+ ("FR", "female", "medium"),
+ ("FR", "male", "high"),
+ ("US", "female", "high"),
+ ("US", "male", "low"),
+ ("US", "female", "low"),
+ ("US", "female", "medium"),
+ ("US", "male", "high"),
+ ("US", "male", "medium"),
+ ],
+ names=["country", "gender", "education"],
+ )
+
+ expected_series = Series(
+ data=expected_data,
+ index=expected_index,
+ name=name,
+ )
+ for i in range(3):
+ expected_series.index = expected_series.index.set_levels(
+ CategoricalIndex(expected_series.index.levels[i]), level=i
+ )
+
+ if as_index:
+ tm.assert_series_equal(result, expected_series)
+ else:
+ expected = expected_series.reset_index(
+ name="proportion" if normalize else "count"
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def assert_categorical_single_grouper(
+ education_df, as_index, observed, expected_index, normalize, name, expected_data
+):
+ # Test single categorical grouper when non-groupers are also categorical
+ education_df = education_df.copy().astype("category")
+
+ # Add non-observed grouping categories
+ education_df["country"] = education_df["country"].cat.add_categories(["ASIA"])
+
+ gp = education_df.groupby("country", as_index=as_index, observed=observed)
+ result = gp.value_counts(normalize=normalize)
+
+ expected_series = Series(
+ data=expected_data,
+ index=MultiIndex.from_tuples(
+ expected_index,
+ names=["country", "gender", "education"],
+ ),
+ name=name,
+ )
+ for i in range(3):
+ index_level = CategoricalIndex(expected_series.index.levels[i])
+ if i == 0:
+ index_level = index_level.set_categories(
+ education_df["country"].cat.categories
+ )
+ expected_series.index = expected_series.index.set_levels(index_level, level=i)
+
+ if as_index:
+ tm.assert_series_equal(result, expected_series)
+ else:
+ expected = expected_series.reset_index(name=name)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("as_index", [True, False])
+@pytest.mark.parametrize(
+ "normalize, name, expected_data",
+ [
+ (
+ False,
+ "count",
+ np.array([2, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0], dtype=np.int64),
+ ),
+ (
+ True,
+ "proportion",
+ np.array([0.5, 0.25, 0.25, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0]),
+ ),
+ ],
+)
+def test_categorical_single_grouper_observed_true(
+ education_df, as_index, normalize, name, expected_data, request
+):
+ # GH#46357
+
+ if Version(np.__version__) >= Version("1.25"):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=(
+ "pandas default unstable sorting of duplicates"
+ "issue with numpy>=1.25 with AVX instructions"
+ ),
+ strict=False,
+ )
+ )
+
+ expected_index = [
+ ("FR", "male", "low"),
+ ("FR", "female", "high"),
+ ("FR", "male", "medium"),
+ ("FR", "female", "low"),
+ ("FR", "female", "medium"),
+ ("FR", "male", "high"),
+ ("US", "female", "high"),
+ ("US", "male", "low"),
+ ("US", "female", "low"),
+ ("US", "female", "medium"),
+ ("US", "male", "high"),
+ ("US", "male", "medium"),
+ ]
+
+ assert_categorical_single_grouper(
+ education_df=education_df,
+ as_index=as_index,
+ observed=True,
+ expected_index=expected_index,
+ normalize=normalize,
+ name=name,
+ expected_data=expected_data,
+ )
+
+
+@pytest.mark.parametrize("as_index", [True, False])
+@pytest.mark.parametrize(
+ "normalize, name, expected_data",
+ [
+ (
+ False,
+ "count",
+ np.array(
+ [2, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=np.int64
+ ),
+ ),
+ (
+ True,
+ "proportion",
+ np.array(
+ [
+ 0.5,
+ 0.25,
+ 0.25,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.5,
+ 0.5,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ ]
+ ),
+ ),
+ ],
+)
+def test_categorical_single_grouper_observed_false(
+ education_df, as_index, normalize, name, expected_data, request
+):
+ # GH#46357
+
+ if Version(np.__version__) >= Version("1.25"):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=(
+ "pandas default unstable sorting of duplicates"
+ "issue with numpy>=1.25 with AVX instructions"
+ ),
+ strict=False,
+ )
+ )
+
+ expected_index = [
+ ("FR", "male", "low"),
+ ("FR", "female", "high"),
+ ("FR", "male", "medium"),
+ ("FR", "female", "low"),
+ ("FR", "male", "high"),
+ ("FR", "female", "medium"),
+ ("US", "female", "high"),
+ ("US", "male", "low"),
+ ("US", "male", "medium"),
+ ("US", "male", "high"),
+ ("US", "female", "medium"),
+ ("US", "female", "low"),
+ ("ASIA", "male", "low"),
+ ("ASIA", "male", "high"),
+ ("ASIA", "female", "medium"),
+ ("ASIA", "female", "low"),
+ ("ASIA", "female", "high"),
+ ("ASIA", "male", "medium"),
+ ]
+
+ assert_categorical_single_grouper(
+ education_df=education_df,
+ as_index=as_index,
+ observed=False,
+ expected_index=expected_index,
+ normalize=normalize,
+ name=name,
+ expected_data=expected_data,
+ )
+
+
+@pytest.mark.parametrize("as_index", [True, False])
+@pytest.mark.parametrize(
+ "observed, expected_index",
+ [
+ (
+ False,
+ [
+ ("FR", "high", "female"),
+ ("FR", "high", "male"),
+ ("FR", "low", "male"),
+ ("FR", "low", "female"),
+ ("FR", "medium", "male"),
+ ("FR", "medium", "female"),
+ ("US", "high", "female"),
+ ("US", "high", "male"),
+ ("US", "low", "male"),
+ ("US", "low", "female"),
+ ("US", "medium", "female"),
+ ("US", "medium", "male"),
+ ],
+ ),
+ (
+ True,
+ [
+ ("FR", "high", "female"),
+ ("FR", "low", "male"),
+ ("FR", "medium", "male"),
+ ("US", "high", "female"),
+ ("US", "low", "male"),
+ ],
+ ),
+ ],
+)
+@pytest.mark.parametrize(
+ "normalize, name, expected_data",
+ [
+ (
+ False,
+ "count",
+ np.array([1, 0, 2, 0, 1, 0, 1, 0, 1, 0, 0, 0], dtype=np.int64),
+ ),
+ (
+ True,
+ "proportion",
+ # NaN values corresponds to non-observed groups
+ np.array([1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]),
+ ),
+ ],
+)
+def test_categorical_multiple_groupers(
+ education_df, as_index, observed, expected_index, normalize, name, expected_data
+):
+ # GH#46357
+
+ # Test multiple categorical groupers when non-groupers are non-categorical
+ education_df = education_df.copy()
+ education_df["country"] = education_df["country"].astype("category")
+ education_df["education"] = education_df["education"].astype("category")
+
+ gp = education_df.groupby(
+ ["country", "education"], as_index=as_index, observed=observed
+ )
+ result = gp.value_counts(normalize=normalize)
+
+ expected_series = Series(
+ data=expected_data[expected_data > 0.0] if observed else expected_data,
+ index=MultiIndex.from_tuples(
+ expected_index,
+ names=["country", "education", "gender"],
+ ),
+ name=name,
+ )
+ for i in range(2):
+ expected_series.index = expected_series.index.set_levels(
+ CategoricalIndex(expected_series.index.levels[i]), level=i
+ )
+
+ if as_index:
+ tm.assert_series_equal(result, expected_series)
+ else:
+ expected = expected_series.reset_index(
+ name="proportion" if normalize else "count"
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("as_index", [False, True])
+@pytest.mark.parametrize("observed", [False, True])
+@pytest.mark.parametrize(
+ "normalize, name, expected_data",
+ [
+ (
+ False,
+ "count",
+ np.array([2, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0], dtype=np.int64),
+ ),
+ (
+ True,
+ "proportion",
+ # NaN values corresponds to non-observed groups
+ np.array([0.5, 0.25, 0.25, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0]),
+ ),
+ ],
+)
+def test_categorical_non_groupers(
+ education_df, as_index, observed, normalize, name, expected_data, request
+):
+ # GH#46357 Test non-observed categories are included in the result,
+ # regardless of `observed`
+
+ if Version(np.__version__) >= Version("1.25"):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=(
+ "pandas default unstable sorting of duplicates"
+ "issue with numpy>=1.25 with AVX instructions"
+ ),
+ strict=False,
+ )
+ )
+
+ education_df = education_df.copy()
+ education_df["gender"] = education_df["gender"].astype("category")
+ education_df["education"] = education_df["education"].astype("category")
+
+ gp = education_df.groupby("country", as_index=as_index, observed=observed)
+ result = gp.value_counts(normalize=normalize)
+
+ expected_index = [
+ ("FR", "male", "low"),
+ ("FR", "female", "high"),
+ ("FR", "male", "medium"),
+ ("FR", "female", "low"),
+ ("FR", "female", "medium"),
+ ("FR", "male", "high"),
+ ("US", "female", "high"),
+ ("US", "male", "low"),
+ ("US", "female", "low"),
+ ("US", "female", "medium"),
+ ("US", "male", "high"),
+ ("US", "male", "medium"),
+ ]
+ expected_series = Series(
+ data=expected_data,
+ index=MultiIndex.from_tuples(
+ expected_index,
+ names=["country", "gender", "education"],
+ ),
+ name=name,
+ )
+ for i in range(1, 3):
+ expected_series.index = expected_series.index.set_levels(
+ CategoricalIndex(expected_series.index.levels[i]), level=i
+ )
+
+ if as_index:
+ tm.assert_series_equal(result, expected_series)
+ else:
+ expected = expected_series.reset_index(
+ name="proportion" if normalize else "count"
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "normalize, expected_label, expected_values",
+ [
+ (False, "count", [1, 1, 1]),
+ (True, "proportion", [0.5, 0.5, 1.0]),
+ ],
+)
+def test_mixed_groupings(normalize, expected_label, expected_values):
+ # Test multiple groupings
+ df = DataFrame({"A": [1, 2, 1], "B": [1, 2, 3]})
+ gp = df.groupby([[4, 5, 4], "A", lambda i: 7 if i == 1 else 8], as_index=False)
+ result = gp.value_counts(sort=True, normalize=normalize)
+ expected = DataFrame(
+ {
+ "level_0": np.array([4, 4, 5], dtype=int),
+ "A": [1, 1, 2],
+ "level_2": [8, 8, 7],
+ "B": [1, 3, 2],
+ expected_label: expected_values,
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "test, columns, expected_names",
+ [
+ ("repeat", list("abbde"), ["a", None, "d", "b", "b", "e"]),
+ ("level", list("abcd") + ["level_1"], ["a", None, "d", "b", "c", "level_1"]),
+ ],
+)
+@pytest.mark.parametrize("as_index", [False, True])
+def test_column_label_duplicates(test, columns, expected_names, as_index):
+ # GH 44992
+ # Test for duplicate input column labels and generated duplicate labels
+ df = DataFrame([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]], columns=columns)
+ expected_data = [(1, 0, 7, 3, 5, 9), (2, 1, 8, 4, 6, 10)]
+ keys = ["a", np.array([0, 1], dtype=np.int64), "d"]
+ result = df.groupby(keys, as_index=as_index).value_counts()
+ if as_index:
+ expected = Series(
+ data=(1, 1),
+ index=MultiIndex.from_tuples(
+ expected_data,
+ names=expected_names,
+ ),
+ name="count",
+ )
+ tm.assert_series_equal(result, expected)
+ else:
+ expected_data = [list(row) + [1] for row in expected_data]
+ expected_columns = list(expected_names)
+ expected_columns[1] = "level_1"
+ expected_columns.append("count")
+ expected = DataFrame(expected_data, columns=expected_columns)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "normalize, expected_label",
+ [
+ (False, "count"),
+ (True, "proportion"),
+ ],
+)
+def test_result_label_duplicates(normalize, expected_label):
+ # Test for result column label duplicating an input column label
+ gb = DataFrame([[1, 2, 3]], columns=["a", "b", expected_label]).groupby(
+ "a", as_index=False
+ )
+ msg = f"Column label '{expected_label}' is duplicate of result column"
+ with pytest.raises(ValueError, match=msg):
+ gb.value_counts(normalize=normalize)
+
+
+def test_ambiguous_grouping():
+ # Test that groupby is not confused by groupings length equal to row count
+ df = DataFrame({"a": [1, 1]})
+ gb = df.groupby(np.array([1, 1], dtype=np.int64))
+ result = gb.value_counts()
+ expected = Series(
+ [2], index=MultiIndex.from_tuples([[1, 1]], names=[None, "a"]), name="count"
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_subset_overlaps_gb_key_raises():
+ # GH 46383
+ df = DataFrame({"c1": ["a", "b", "c"], "c2": ["x", "y", "y"]}, index=[0, 1, 1])
+ msg = "Keys {'c1'} in subset cannot be in the groupby column keys."
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("c1").value_counts(subset=["c1"])
+
+
+def test_subset_doesnt_exist_in_frame():
+ # GH 46383
+ df = DataFrame({"c1": ["a", "b", "c"], "c2": ["x", "y", "y"]}, index=[0, 1, 1])
+ msg = "Keys {'c3'} in subset do not exist in the DataFrame."
+ with pytest.raises(ValueError, match=msg):
+ df.groupby("c1").value_counts(subset=["c3"])
+
+
+def test_subset():
+ # GH 46383
+ df = DataFrame({"c1": ["a", "b", "c"], "c2": ["x", "y", "y"]}, index=[0, 1, 1])
+ result = df.groupby(level=0).value_counts(subset=["c2"])
+ expected = Series(
+ [1, 2],
+ index=MultiIndex.from_arrays([[0, 1], ["x", "y"]], names=[None, "c2"]),
+ name="count",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_subset_duplicate_columns():
+ # GH 46383
+ df = DataFrame(
+ [["a", "x", "x"], ["b", "y", "y"], ["b", "y", "y"]],
+ index=[0, 1, 1],
+ columns=["c1", "c2", "c2"],
+ )
+ result = df.groupby(level=0).value_counts(subset=["c2"])
+ expected = Series(
+ [1, 2],
+ index=MultiIndex.from_arrays(
+ [[0, 1], ["x", "y"], ["x", "y"]], names=[None, "c2", "c2"]
+ ),
+ name="count",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("utc", [True, False])
+def test_value_counts_time_grouper(utc):
+ # GH#50486
+ df = DataFrame(
+ {
+ "Timestamp": [
+ 1565083561,
+ 1565083561 + 86400,
+ 1565083561 + 86500,
+ 1565083561 + 86400 * 2,
+ 1565083561 + 86400 * 3,
+ 1565083561 + 86500 * 3,
+ 1565083561 + 86400 * 4,
+ ],
+ "Food": ["apple", "apple", "banana", "banana", "orange", "orange", "pear"],
+ }
+ ).drop([3])
+
+ df["Datetime"] = to_datetime(df["Timestamp"], utc=utc, unit="s")
+ gb = df.groupby(Grouper(freq="1D", key="Datetime"))
+ result = gb.value_counts()
+ dates = to_datetime(
+ ["2019-08-06", "2019-08-07", "2019-08-09", "2019-08-10"], utc=utc
+ )
+ timestamps = df["Timestamp"].unique()
+ index = MultiIndex(
+ levels=[dates, timestamps, ["apple", "banana", "orange", "pear"]],
+ codes=[[0, 1, 1, 2, 2, 3], range(6), [0, 0, 1, 2, 2, 3]],
+ names=["Datetime", "Timestamp", "Food"],
+ )
+ expected = Series(1, index=index, name="count")
+ tm.assert_series_equal(result, expected)
+
+
+def test_value_counts_integer_columns():
+ # GH#55627
+ df = DataFrame({1: ["a", "a", "a"], 2: ["a", "a", "d"], 3: ["a", "b", "c"]})
+ gp = df.groupby([1, 2], as_index=False, sort=False)
+ result = gp[3].value_counts()
+ expected = DataFrame(
+ {1: ["a", "a", "a"], 2: ["a", "a", "d"], 3: ["a", "b", "c"], "count": 1}
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..458a37c99409197c9ef776080530a4dda367ba74
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/conftest.py
@@ -0,0 +1,61 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ Series,
+ array,
+)
+import pandas._testing as tm
+
+
+@pytest.fixture(params=[None, False])
+def sort(request):
+ """
+ Valid values for the 'sort' parameter used in the Index
+ setops methods (intersection, union, etc.)
+
+ Caution:
+ Don't confuse this one with the "sort" fixture used
+ for DataFrame.append or concat. That one has
+ parameters [True, False].
+
+ We can't combine them as sort=True is not permitted
+ in the Index setops methods.
+ """
+ return request.param
+
+
+@pytest.fixture(params=["D", "3D", "-3D", "H", "2H", "-2H", "T", "2T", "S", "-3S"])
+def freq_sample(request):
+ """
+ Valid values for 'freq' parameter used to create date_range and
+ timedelta_range..
+ """
+ return request.param
+
+
+@pytest.fixture(params=[list, tuple, np.array, array, Series])
+def listlike_box(request):
+ """
+ Types that may be passed as the indexer to searchsorted.
+ """
+ return request.param
+
+
+@pytest.fixture(
+ params=tm.ALL_REAL_NUMPY_DTYPES
+ + [
+ "object",
+ "category",
+ "datetime64[ns]",
+ "timedelta64[ns]",
+ ]
+)
+def any_dtype_for_small_pos_integer_indexes(request):
+ """
+ Dtypes that can be given to an Index with small positive integers.
+
+ This means that for any dtype `x` in the params list, `Index([1, 2, 3], dtype=x)` is
+ valid and gives the correct Index (sub-)class.
+ """
+ return request.param
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_any_index.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_any_index.py
new file mode 100644
index 0000000000000000000000000000000000000000..10204cfb78e8928dd69e0ea33ce40b02840959ed
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_any_index.py
@@ -0,0 +1,172 @@
+"""
+Tests that can be parametrized over _any_ Index object.
+"""
+import re
+
+import numpy as np
+import pytest
+
+from pandas.errors import InvalidIndexError
+
+import pandas._testing as tm
+
+
+def test_boolean_context_compat(index):
+ # GH#7897
+ with pytest.raises(ValueError, match="The truth value of a"):
+ if index:
+ pass
+
+ with pytest.raises(ValueError, match="The truth value of a"):
+ bool(index)
+
+
+def test_sort(index):
+ msg = "cannot sort an Index object in-place, use sort_values instead"
+ with pytest.raises(TypeError, match=msg):
+ index.sort()
+
+
+def test_hash_error(index):
+ with pytest.raises(TypeError, match=f"unhashable type: '{type(index).__name__}'"):
+ hash(index)
+
+
+def test_mutability(index):
+ if not len(index):
+ pytest.skip("Test doesn't make sense for empty index")
+ msg = "Index does not support mutable operations"
+ with pytest.raises(TypeError, match=msg):
+ index[0] = index[0]
+
+
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+def test_map_identity_mapping(index, request):
+ # GH#12766
+
+ result = index.map(lambda x: x)
+ if index.dtype == object and result.dtype == bool:
+ assert (index == result).all()
+ # TODO: could work that into the 'exact="equiv"'?
+ return # FIXME: doesn't belong in this file anymore!
+ tm.assert_index_equal(result, index, exact="equiv")
+
+
+def test_wrong_number_names(index):
+ names = index.nlevels * ["apple", "banana", "carrot"]
+ with pytest.raises(ValueError, match="^Length"):
+ index.names = names
+
+
+def test_view_preserves_name(index):
+ assert index.view().name == index.name
+
+
+def test_ravel(index):
+ # GH#19956 ravel returning ndarray is deprecated, in 2.0 returns a view on self
+ res = index.ravel()
+ tm.assert_index_equal(res, index)
+
+
+class TestConversion:
+ def test_to_series(self, index):
+ # assert that we are creating a copy of the index
+
+ ser = index.to_series()
+ assert ser.values is not index.values
+ assert ser.index is not index
+ assert ser.name == index.name
+
+ def test_to_series_with_arguments(self, index):
+ # GH#18699
+
+ # index kwarg
+ ser = index.to_series(index=index)
+
+ assert ser.values is not index.values
+ assert ser.index is index
+ assert ser.name == index.name
+
+ # name kwarg
+ ser = index.to_series(name="__test")
+
+ assert ser.values is not index.values
+ assert ser.index is not index
+ assert ser.name != index.name
+
+ def test_tolist_matches_list(self, index):
+ assert index.tolist() == list(index)
+
+
+class TestRoundTrips:
+ def test_pickle_roundtrip(self, index):
+ result = tm.round_trip_pickle(index)
+ tm.assert_index_equal(result, index, exact=True)
+ if result.nlevels > 1:
+ # GH#8367 round-trip with timezone
+ assert index.equal_levels(result)
+
+ def test_pickle_preserves_name(self, index):
+ original_name, index.name = index.name, "foo"
+ unpickled = tm.round_trip_pickle(index)
+ assert index.equals(unpickled)
+ index.name = original_name
+
+
+class TestIndexing:
+ def test_get_loc_listlike_raises_invalid_index_error(self, index):
+ # and never TypeError
+ key = np.array([0, 1], dtype=np.intp)
+
+ with pytest.raises(InvalidIndexError, match=r"\[0 1\]"):
+ index.get_loc(key)
+
+ with pytest.raises(InvalidIndexError, match=r"\[False True\]"):
+ index.get_loc(key.astype(bool))
+
+ def test_getitem_ellipsis(self, index):
+ # GH#21282
+ result = index[...]
+ assert result.equals(index)
+ assert result is not index
+
+ def test_slice_keeps_name(self, index):
+ assert index.name == index[1:].name
+
+ @pytest.mark.parametrize("item", [101, "no_int", 2.5])
+ def test_getitem_error(self, index, item):
+ msg = "|".join(
+ [
+ r"index 101 is out of bounds for axis 0 with size [\d]+",
+ re.escape(
+ "only integers, slices (`:`), ellipsis (`...`), "
+ "numpy.newaxis (`None`) and integer or boolean arrays "
+ "are valid indices"
+ ),
+ "index out of bounds", # string[pyarrow]
+ ]
+ )
+ with pytest.raises(IndexError, match=msg):
+ index[item]
+
+
+class TestRendering:
+ def test_str(self, index):
+ # test the string repr
+ index.name = "foo"
+ assert "'foo'" in str(index)
+ assert type(index).__name__ in str(index)
+
+
+class TestReductions:
+ def test_argmax_axis_invalid(self, index):
+ # GH#23081
+ msg = r"`axis` must be fewer than the number of dimensions \(1\)"
+ with pytest.raises(ValueError, match=msg):
+ index.argmax(axis=1)
+ with pytest.raises(ValueError, match=msg):
+ index.argmin(axis=2)
+ with pytest.raises(ValueError, match=msg):
+ index.min(axis=-2)
+ with pytest.raises(ValueError, match=msg):
+ index.max(axis=-3)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_base.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..da4b44227bef34787103c4ed44b9a1bed846833d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_base.py
@@ -0,0 +1,1635 @@
+from collections import defaultdict
+from datetime import datetime
+from io import StringIO
+import math
+import operator
+import re
+
+import numpy as np
+import pytest
+
+from pandas.compat import IS64
+from pandas.errors import InvalidIndexError
+
+from pandas.core.dtypes.common import (
+ is_any_real_numeric_dtype,
+ is_numeric_dtype,
+ is_object_dtype,
+)
+
+import pandas as pd
+from pandas import (
+ CategoricalIndex,
+ DataFrame,
+ DatetimeIndex,
+ IntervalIndex,
+ PeriodIndex,
+ RangeIndex,
+ Series,
+ TimedeltaIndex,
+ date_range,
+ period_range,
+)
+import pandas._testing as tm
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+ _get_combined_index,
+ ensure_index,
+ ensure_index_from_sequences,
+)
+
+
+class TestIndex:
+ @pytest.fixture
+ def simple_index(self) -> Index:
+ return Index(list("abcde"))
+
+ def test_can_hold_identifiers(self, simple_index):
+ index = simple_index
+ key = index[0]
+ assert index._can_hold_identifiers_and_holds_name(key) is True
+
+ @pytest.mark.parametrize("index", ["datetime"], indirect=True)
+ def test_new_axis(self, index):
+ # TODO: a bunch of scattered tests check this deprecation is enforced.
+ # de-duplicate/centralize them.
+ with pytest.raises(ValueError, match="Multi-dimensional indexing"):
+ # GH#30588 multi-dimensional indexing deprecated
+ index[None, :]
+
+ def test_constructor_regular(self, index):
+ tm.assert_contains_all(index, index)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ def test_constructor_casting(self, index):
+ # casting
+ arr = np.array(index)
+ new_index = Index(arr)
+ tm.assert_contains_all(arr, new_index)
+ tm.assert_index_equal(index, new_index)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ def test_constructor_copy(self, index):
+ arr = np.array(index)
+ new_index = Index(arr, copy=True, name="name")
+ assert isinstance(new_index, Index)
+ assert new_index.name == "name"
+ tm.assert_numpy_array_equal(arr, new_index.values)
+ arr[0] = "SOMEBIGLONGSTRING"
+ assert new_index[0] != "SOMEBIGLONGSTRING"
+
+ @pytest.mark.parametrize("cast_as_obj", [True, False])
+ @pytest.mark.parametrize(
+ "index",
+ [
+ date_range(
+ "2015-01-01 10:00",
+ freq="D",
+ periods=3,
+ tz="US/Eastern",
+ name="Green Eggs & Ham",
+ ), # DTI with tz
+ date_range("2015-01-01 10:00", freq="D", periods=3), # DTI no tz
+ pd.timedelta_range("1 days", freq="D", periods=3), # td
+ period_range("2015-01-01", freq="D", periods=3), # period
+ ],
+ )
+ def test_constructor_from_index_dtlike(self, cast_as_obj, index):
+ if cast_as_obj:
+ result = Index(index.astype(object))
+ else:
+ result = Index(index)
+
+ tm.assert_index_equal(result, index)
+
+ if isinstance(index, DatetimeIndex):
+ assert result.tz == index.tz
+ if cast_as_obj:
+ # GH#23524 check that Index(dti, dtype=object) does not
+ # incorrectly raise ValueError, and that nanoseconds are not
+ # dropped
+ index += pd.Timedelta(nanoseconds=50)
+ result = Index(index, dtype=object)
+ assert result.dtype == np.object_
+ assert list(result) == list(index)
+
+ @pytest.mark.parametrize(
+ "index,has_tz",
+ [
+ (
+ date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern"),
+ True,
+ ), # datetimetz
+ (pd.timedelta_range("1 days", freq="D", periods=3), False), # td
+ (period_range("2015-01-01", freq="D", periods=3), False), # period
+ ],
+ )
+ def test_constructor_from_series_dtlike(self, index, has_tz):
+ result = Index(Series(index))
+ tm.assert_index_equal(result, index)
+
+ if has_tz:
+ assert result.tz == index.tz
+
+ def test_constructor_from_series_freq(self):
+ # GH 6273
+ # create from a series, passing a freq
+ dts = ["1-1-1990", "2-1-1990", "3-1-1990", "4-1-1990", "5-1-1990"]
+ expected = DatetimeIndex(dts, freq="MS")
+
+ s = Series(pd.to_datetime(dts))
+ result = DatetimeIndex(s, freq="MS")
+
+ tm.assert_index_equal(result, expected)
+
+ def test_constructor_from_frame_series_freq(self):
+ # GH 6273
+ # create from a series, passing a freq
+ dts = ["1-1-1990", "2-1-1990", "3-1-1990", "4-1-1990", "5-1-1990"]
+ expected = DatetimeIndex(dts, freq="MS")
+
+ df = DataFrame(np.random.default_rng(2).random((5, 3)))
+ df["date"] = dts
+ result = DatetimeIndex(df["date"], freq="MS")
+
+ assert df["date"].dtype == object
+ expected.name = "date"
+ tm.assert_index_equal(result, expected)
+
+ expected = Series(dts, name="date")
+ tm.assert_series_equal(df["date"], expected)
+
+ # GH 6274
+ # infer freq of same
+ freq = pd.infer_freq(df["date"])
+ assert freq == "MS"
+
+ def test_constructor_int_dtype_nan(self):
+ # see gh-15187
+ data = [np.nan]
+ expected = Index(data, dtype=np.float64)
+ result = Index(data, dtype="float")
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "klass,dtype,na_val",
+ [
+ (Index, np.float64, np.nan),
+ (DatetimeIndex, "datetime64[ns]", pd.NaT),
+ ],
+ )
+ def test_index_ctor_infer_nan_nat(self, klass, dtype, na_val):
+ # GH 13467
+ na_list = [na_val, na_val]
+ expected = klass(na_list)
+ assert expected.dtype == dtype
+
+ result = Index(na_list)
+ tm.assert_index_equal(result, expected)
+
+ result = Index(np.array(na_list))
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "vals,dtype",
+ [
+ ([1, 2, 3, 4, 5], "int"),
+ ([1.1, np.nan, 2.2, 3.0], "float"),
+ (["A", "B", "C", np.nan], "obj"),
+ ],
+ )
+ def test_constructor_simple_new(self, vals, dtype):
+ index = Index(vals, name=dtype)
+ result = index._simple_new(index.values, dtype)
+ tm.assert_index_equal(result, index)
+
+ @pytest.mark.parametrize("attr", ["values", "asi8"])
+ @pytest.mark.parametrize("klass", [Index, DatetimeIndex])
+ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass):
+ # Test constructing with a datetimetz dtype
+ # .values produces numpy datetimes, so these are considered naive
+ # .asi8 produces integers, so these are considered epoch timestamps
+ # ^the above will be true in a later version. Right now we `.view`
+ # the i8 values as NS_DTYPE, effectively treating them as wall times.
+ index = date_range("2011-01-01", periods=5)
+ arg = getattr(index, attr)
+ index = index.tz_localize(tz_naive_fixture)
+ dtype = index.dtype
+
+ # As of 2.0 astype raises on dt64.astype(dt64tz)
+ err = tz_naive_fixture is not None
+ msg = "Cannot use .astype to convert from timezone-naive dtype to"
+
+ if attr == "asi8":
+ result = DatetimeIndex(arg).tz_localize(tz_naive_fixture)
+ tm.assert_index_equal(result, index)
+ elif klass is Index:
+ with pytest.raises(TypeError, match="unexpected keyword"):
+ klass(arg, tz=tz_naive_fixture)
+ else:
+ result = klass(arg, tz=tz_naive_fixture)
+ tm.assert_index_equal(result, index)
+
+ if attr == "asi8":
+ if err:
+ with pytest.raises(TypeError, match=msg):
+ DatetimeIndex(arg).astype(dtype)
+ else:
+ result = DatetimeIndex(arg).astype(dtype)
+ tm.assert_index_equal(result, index)
+ else:
+ result = klass(arg, dtype=dtype)
+ tm.assert_index_equal(result, index)
+
+ if attr == "asi8":
+ result = DatetimeIndex(list(arg)).tz_localize(tz_naive_fixture)
+ tm.assert_index_equal(result, index)
+ elif klass is Index:
+ with pytest.raises(TypeError, match="unexpected keyword"):
+ klass(arg, tz=tz_naive_fixture)
+ else:
+ result = klass(list(arg), tz=tz_naive_fixture)
+ tm.assert_index_equal(result, index)
+
+ if attr == "asi8":
+ if err:
+ with pytest.raises(TypeError, match=msg):
+ DatetimeIndex(list(arg)).astype(dtype)
+ else:
+ result = DatetimeIndex(list(arg)).astype(dtype)
+ tm.assert_index_equal(result, index)
+ else:
+ result = klass(list(arg), dtype=dtype)
+ tm.assert_index_equal(result, index)
+
+ @pytest.mark.parametrize("attr", ["values", "asi8"])
+ @pytest.mark.parametrize("klass", [Index, TimedeltaIndex])
+ def test_constructor_dtypes_timedelta(self, attr, klass):
+ index = pd.timedelta_range("1 days", periods=5)
+ index = index._with_freq(None) # won't be preserved by constructors
+ dtype = index.dtype
+
+ values = getattr(index, attr)
+
+ result = klass(values, dtype=dtype)
+ tm.assert_index_equal(result, index)
+
+ result = klass(list(values), dtype=dtype)
+ tm.assert_index_equal(result, index)
+
+ @pytest.mark.parametrize("value", [[], iter([]), (_ for _ in [])])
+ @pytest.mark.parametrize(
+ "klass",
+ [
+ Index,
+ CategoricalIndex,
+ DatetimeIndex,
+ TimedeltaIndex,
+ ],
+ )
+ def test_constructor_empty(self, value, klass):
+ empty = klass(value)
+ assert isinstance(empty, klass)
+ assert not len(empty)
+
+ @pytest.mark.parametrize(
+ "empty,klass",
+ [
+ (PeriodIndex([], freq="D"), PeriodIndex),
+ (PeriodIndex(iter([]), freq="D"), PeriodIndex),
+ (PeriodIndex((_ for _ in []), freq="D"), PeriodIndex),
+ (RangeIndex(step=1), RangeIndex),
+ (MultiIndex(levels=[[1, 2], ["blue", "red"]], codes=[[], []]), MultiIndex),
+ ],
+ )
+ def test_constructor_empty_special(self, empty, klass):
+ assert isinstance(empty, klass)
+ assert not len(empty)
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ "datetime",
+ "float64",
+ "float32",
+ "int64",
+ "int32",
+ "period",
+ "range",
+ "repeats",
+ "timedelta",
+ "tuples",
+ "uint64",
+ "uint32",
+ ],
+ indirect=True,
+ )
+ def test_view_with_args(self, index):
+ index.view("i8")
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ "string",
+ pytest.param("categorical", marks=pytest.mark.xfail(reason="gh-25464")),
+ "bool-object",
+ "bool-dtype",
+ "empty",
+ ],
+ indirect=True,
+ )
+ def test_view_with_args_object_array_raises(self, index):
+ if index.dtype == bool:
+ msg = "When changing to a larger dtype"
+ with pytest.raises(ValueError, match=msg):
+ index.view("i8")
+ else:
+ msg = "Cannot change data-type for object array"
+ with pytest.raises(TypeError, match=msg):
+ index.view("i8")
+
+ @pytest.mark.parametrize(
+ "index",
+ ["int64", "int32", "range"],
+ indirect=True,
+ )
+ def test_astype(self, index):
+ casted = index.astype("i8")
+
+ # it works!
+ casted.get_loc(5)
+
+ # pass on name
+ index.name = "foobar"
+ casted = index.astype("i8")
+ assert casted.name == "foobar"
+
+ def test_equals_object(self):
+ # same
+ assert Index(["a", "b", "c"]).equals(Index(["a", "b", "c"]))
+
+ @pytest.mark.parametrize(
+ "comp", [Index(["a", "b"]), Index(["a", "b", "d"]), ["a", "b", "c"]]
+ )
+ def test_not_equals_object(self, comp):
+ assert not Index(["a", "b", "c"]).equals(comp)
+
+ def test_identical(self):
+ # index
+ i1 = Index(["a", "b", "c"])
+ i2 = Index(["a", "b", "c"])
+
+ assert i1.identical(i2)
+
+ i1 = i1.rename("foo")
+ assert i1.equals(i2)
+ assert not i1.identical(i2)
+
+ i2 = i2.rename("foo")
+ assert i1.identical(i2)
+
+ i3 = Index([("a", "a"), ("a", "b"), ("b", "a")])
+ i4 = Index([("a", "a"), ("a", "b"), ("b", "a")], tupleize_cols=False)
+ assert not i3.identical(i4)
+
+ def test_is_(self):
+ ind = Index(range(10))
+ assert ind.is_(ind)
+ assert ind.is_(ind.view().view().view().view())
+ assert not ind.is_(Index(range(10)))
+ assert not ind.is_(ind.copy())
+ assert not ind.is_(ind.copy(deep=False))
+ assert not ind.is_(ind[:])
+ assert not ind.is_(np.array(range(10)))
+
+ # quasi-implementation dependent
+ assert ind.is_(ind.view())
+ ind2 = ind.view()
+ ind2.name = "bob"
+ assert ind.is_(ind2)
+ assert ind2.is_(ind)
+ # doesn't matter if Indices are *actually* views of underlying data,
+ assert not ind.is_(Index(ind.values))
+ arr = np.array(range(1, 11))
+ ind1 = Index(arr, copy=False)
+ ind2 = Index(arr, copy=False)
+ assert not ind1.is_(ind2)
+
+ def test_asof_numeric_vs_bool_raises(self):
+ left = Index([1, 2, 3])
+ right = Index([True, False], dtype=object)
+
+ msg = "Cannot compare dtypes int64 and bool"
+ with pytest.raises(TypeError, match=msg):
+ left.asof(right[0])
+ # TODO: should right.asof(left[0]) also raise?
+
+ with pytest.raises(InvalidIndexError, match=re.escape(str(right))):
+ left.asof(right)
+
+ with pytest.raises(InvalidIndexError, match=re.escape(str(left))):
+ right.asof(left)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ def test_booleanindex(self, index):
+ bool_index = np.ones(len(index), dtype=bool)
+ bool_index[5:30:2] = False
+
+ sub_index = index[bool_index]
+
+ for i, val in enumerate(sub_index):
+ assert sub_index.get_loc(val) == i
+
+ sub_index = index[list(bool_index)]
+ for i, val in enumerate(sub_index):
+ assert sub_index.get_loc(val) == i
+
+ def test_fancy(self, simple_index):
+ index = simple_index
+ sl = index[[1, 2, 3]]
+ for i in sl:
+ assert i == sl[sl.get_loc(i)]
+
+ @pytest.mark.parametrize(
+ "index",
+ ["string", "int64", "int32", "uint64", "uint32", "float64", "float32"],
+ indirect=True,
+ )
+ @pytest.mark.parametrize("dtype", [int, np.bool_])
+ def test_empty_fancy(self, index, dtype):
+ empty_arr = np.array([], dtype=dtype)
+ empty_index = type(index)([], dtype=index.dtype)
+
+ assert index[[]].identical(empty_index)
+ assert index[empty_arr].identical(empty_index)
+
+ @pytest.mark.parametrize(
+ "index",
+ ["string", "int64", "int32", "uint64", "uint32", "float64", "float32"],
+ indirect=True,
+ )
+ def test_empty_fancy_raises(self, index):
+ # DatetimeIndex is excluded, because it overrides getitem and should
+ # be tested separately.
+ empty_farr = np.array([], dtype=np.float64)
+ empty_index = type(index)([], dtype=index.dtype)
+
+ assert index[[]].identical(empty_index)
+ # np.ndarray only accepts ndarray of int & bool dtypes, so should Index
+ msg = r"arrays used as indices must be of integer \(or boolean\) type"
+ with pytest.raises(IndexError, match=msg):
+ index[empty_farr]
+
+ def test_union_dt_as_obj(self, simple_index):
+ # TODO: Replace with fixturesult
+ index = simple_index
+ date_index = date_range("2019-01-01", periods=10)
+ first_cat = index.union(date_index)
+ second_cat = index.union(index)
+
+ appended = np.append(index, date_index.astype("O"))
+
+ assert tm.equalContents(first_cat, appended)
+ assert tm.equalContents(second_cat, index)
+ tm.assert_contains_all(index, first_cat)
+ tm.assert_contains_all(index, second_cat)
+ tm.assert_contains_all(date_index, first_cat)
+
+ def test_map_with_tuples(self):
+ # GH 12766
+
+ # Test that returning a single tuple from an Index
+ # returns an Index.
+ index = tm.makeIntIndex(3)
+ result = tm.makeIntIndex(3).map(lambda x: (x,))
+ expected = Index([(i,) for i in index])
+ tm.assert_index_equal(result, expected)
+
+ # Test that returning a tuple from a map of a single index
+ # returns a MultiIndex object.
+ result = index.map(lambda x: (x, x == 1))
+ expected = MultiIndex.from_tuples([(i, i == 1) for i in index])
+ tm.assert_index_equal(result, expected)
+
+ def test_map_with_tuples_mi(self):
+ # Test that returning a single object from a MultiIndex
+ # returns an Index.
+ first_level = ["foo", "bar", "baz"]
+ multi_index = MultiIndex.from_tuples(zip(first_level, [1, 2, 3]))
+ reduced_index = multi_index.map(lambda x: x[0])
+ tm.assert_index_equal(reduced_index, Index(first_level))
+
+ @pytest.mark.parametrize(
+ "attr", ["makeDateIndex", "makePeriodIndex", "makeTimedeltaIndex"]
+ )
+ def test_map_tseries_indices_return_index(self, attr):
+ index = getattr(tm, attr)(10)
+ expected = Index([1] * 10)
+ result = index.map(lambda x: 1)
+ tm.assert_index_equal(expected, result)
+
+ def test_map_tseries_indices_accsr_return_index(self):
+ date_index = tm.makeDateIndex(24, freq="h", name="hourly")
+ result = date_index.map(lambda x: x.hour)
+ expected = Index(np.arange(24, dtype="int64"), name="hourly")
+ tm.assert_index_equal(result, expected, exact=True)
+
+ @pytest.mark.parametrize(
+ "mapper",
+ [
+ lambda values, index: {i: e for e, i in zip(values, index)},
+ lambda values, index: Series(values, index),
+ ],
+ )
+ def test_map_dictlike_simple(self, mapper):
+ # GH 12756
+ expected = Index(["foo", "bar", "baz"])
+ index = tm.makeIntIndex(3)
+ result = index.map(mapper(expected.values, index))
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "mapper",
+ [
+ lambda values, index: {i: e for e, i in zip(values, index)},
+ lambda values, index: Series(values, index),
+ ],
+ )
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_map_dictlike(self, index, mapper, request):
+ # GH 12756
+ if isinstance(index, CategoricalIndex):
+ pytest.skip("Tested in test_categorical")
+ elif not index.is_unique:
+ pytest.skip("Cannot map duplicated index")
+
+ rng = np.arange(len(index), 0, -1, dtype=np.int64)
+
+ if index.empty:
+ # to match proper result coercion for uints
+ expected = Index([])
+ elif is_numeric_dtype(index.dtype):
+ expected = index._constructor(rng, dtype=index.dtype)
+ elif type(index) is Index and index.dtype != object:
+ # i.e. EA-backed, for now just Nullable
+ expected = Index(rng, dtype=index.dtype)
+ else:
+ expected = Index(rng)
+
+ result = index.map(mapper(expected, index))
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "mapper",
+ [Series(["foo", 2.0, "baz"], index=[0, 2, -1]), {0: "foo", 2: 2.0, -1: "baz"}],
+ )
+ def test_map_with_non_function_missing_values(self, mapper):
+ # GH 12756
+ expected = Index([2.0, np.nan, "foo"])
+ result = Index([2, 1, 0]).map(mapper)
+
+ tm.assert_index_equal(expected, result)
+
+ def test_map_na_exclusion(self):
+ index = Index([1.5, np.nan, 3, np.nan, 5])
+
+ result = index.map(lambda x: x * 2, na_action="ignore")
+ expected = index * 2
+ tm.assert_index_equal(result, expected)
+
+ def test_map_defaultdict(self):
+ index = Index([1, 2, 3])
+ default_dict = defaultdict(lambda: "blank")
+ default_dict[1] = "stuff"
+ result = index.map(default_dict)
+ expected = Index(["stuff", "blank", "blank"])
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("name,expected", [("foo", "foo"), ("bar", None)])
+ def test_append_empty_preserve_name(self, name, expected):
+ left = Index([], name="foo")
+ right = Index([1, 2, 3], name=name)
+
+ msg = "The behavior of array concatenation with empty entries is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = left.append(right)
+ assert result.name == expected
+
+ @pytest.mark.parametrize(
+ "index, expected",
+ [
+ ("string", False),
+ ("bool-object", False),
+ ("bool-dtype", False),
+ ("categorical", False),
+ ("int64", True),
+ ("int32", True),
+ ("uint64", True),
+ ("uint32", True),
+ ("datetime", False),
+ ("float64", True),
+ ("float32", True),
+ ],
+ indirect=["index"],
+ )
+ def test_is_numeric(self, index, expected):
+ assert is_any_real_numeric_dtype(index) is expected
+
+ @pytest.mark.parametrize(
+ "index, expected",
+ [
+ ("string", True),
+ ("bool-object", True),
+ ("bool-dtype", False),
+ ("categorical", False),
+ ("int64", False),
+ ("int32", False),
+ ("uint64", False),
+ ("uint32", False),
+ ("datetime", False),
+ ("float64", False),
+ ("float32", False),
+ ],
+ indirect=["index"],
+ )
+ def test_is_object(self, index, expected):
+ assert is_object_dtype(index) is expected
+
+ def test_summary(self, index):
+ index._summary()
+
+ def test_format_bug(self):
+ # GH 14626
+ # windows has different precision on datetime.datetime.now (it doesn't
+ # include us since the default for Timestamp shows these but Index
+ # formatting does not we are skipping)
+ now = datetime.now()
+ if not str(now).endswith("000"):
+ index = Index([now])
+ formatted = index.format()
+ expected = [str(index[0])]
+ assert formatted == expected
+
+ Index([]).format()
+
+ @pytest.mark.parametrize("vals", [[1, 2.0 + 3.0j, 4.0], ["a", "b", "c"]])
+ def test_format_missing(self, vals, nulls_fixture):
+ # 2845
+ vals = list(vals) # Copy for each iteration
+ vals.append(nulls_fixture)
+ index = Index(vals, dtype=object)
+ # TODO: case with complex dtype?
+
+ formatted = index.format()
+ null_repr = "NaN" if isinstance(nulls_fixture, float) else str(nulls_fixture)
+ expected = [str(index[0]), str(index[1]), str(index[2]), null_repr]
+
+ assert formatted == expected
+ assert index[3] is nulls_fixture
+
+ @pytest.mark.parametrize("op", ["any", "all"])
+ def test_logical_compat(self, op, simple_index):
+ index = simple_index
+ left = getattr(index, op)()
+ assert left == getattr(index.values, op)()
+ right = getattr(index.to_series(), op)()
+ # left might not match right exactly in e.g. string cases where the
+ # because we use np.any/all instead of .any/all
+ assert bool(left) == bool(right)
+
+ @pytest.mark.parametrize(
+ "index", ["string", "int64", "int32", "float64", "float32"], indirect=True
+ )
+ def test_drop_by_str_label(self, index):
+ n = len(index)
+ drop = index[list(range(5, 10))]
+ dropped = index.drop(drop)
+
+ expected = index[list(range(5)) + list(range(10, n))]
+ tm.assert_index_equal(dropped, expected)
+
+ dropped = index.drop(index[0])
+ expected = index[1:]
+ tm.assert_index_equal(dropped, expected)
+
+ @pytest.mark.parametrize(
+ "index", ["string", "int64", "int32", "float64", "float32"], indirect=True
+ )
+ @pytest.mark.parametrize("keys", [["foo", "bar"], ["1", "bar"]])
+ def test_drop_by_str_label_raises_missing_keys(self, index, keys):
+ with pytest.raises(KeyError, match=""):
+ index.drop(keys)
+
+ @pytest.mark.parametrize(
+ "index", ["string", "int64", "int32", "float64", "float32"], indirect=True
+ )
+ def test_drop_by_str_label_errors_ignore(self, index):
+ n = len(index)
+ drop = index[list(range(5, 10))]
+ mixed = drop.tolist() + ["foo"]
+ dropped = index.drop(mixed, errors="ignore")
+
+ expected = index[list(range(5)) + list(range(10, n))]
+ tm.assert_index_equal(dropped, expected)
+
+ dropped = index.drop(["foo", "bar"], errors="ignore")
+ expected = index[list(range(n))]
+ tm.assert_index_equal(dropped, expected)
+
+ def test_drop_by_numeric_label_loc(self):
+ # TODO: Parametrize numeric and str tests after self.strIndex fixture
+ index = Index([1, 2, 3])
+ dropped = index.drop(1)
+ expected = Index([2, 3])
+
+ tm.assert_index_equal(dropped, expected)
+
+ def test_drop_by_numeric_label_raises_missing_keys(self):
+ index = Index([1, 2, 3])
+ with pytest.raises(KeyError, match=""):
+ index.drop([3, 4])
+
+ @pytest.mark.parametrize(
+ "key,expected", [(4, Index([1, 2, 3])), ([3, 4, 5], Index([1, 2]))]
+ )
+ def test_drop_by_numeric_label_errors_ignore(self, key, expected):
+ index = Index([1, 2, 3])
+ dropped = index.drop(key, errors="ignore")
+
+ tm.assert_index_equal(dropped, expected)
+
+ @pytest.mark.parametrize(
+ "values",
+ [["a", "b", ("c", "d")], ["a", ("c", "d"), "b"], [("c", "d"), "a", "b"]],
+ )
+ @pytest.mark.parametrize("to_drop", [[("c", "d"), "a"], ["a", ("c", "d")]])
+ def test_drop_tuple(self, values, to_drop):
+ # GH 18304
+ index = Index(values)
+ expected = Index(["b"])
+
+ result = index.drop(to_drop)
+ tm.assert_index_equal(result, expected)
+
+ removed = index.drop(to_drop[0])
+ for drop_me in to_drop[1], [to_drop[1]]:
+ result = removed.drop(drop_me)
+ tm.assert_index_equal(result, expected)
+
+ removed = index.drop(to_drop[1])
+ msg = rf"\"\[{re.escape(to_drop[1].__repr__())}\] not found in axis\""
+ for drop_me in to_drop[1], [to_drop[1]]:
+ with pytest.raises(KeyError, match=msg):
+ removed.drop(drop_me)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_drop_with_duplicates_in_index(self, index):
+ # GH38051
+ if len(index) == 0 or isinstance(index, MultiIndex):
+ pytest.skip("Test doesn't make sense for empty MultiIndex")
+ if isinstance(index, IntervalIndex) and not IS64:
+ pytest.skip("Cannot test IntervalIndex with int64 dtype on 32 bit platform")
+ index = index.unique().repeat(2)
+ expected = index[2:]
+ result = index.drop(index[0])
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "attr",
+ [
+ "is_monotonic_increasing",
+ "is_monotonic_decreasing",
+ "_is_strictly_monotonic_increasing",
+ "_is_strictly_monotonic_decreasing",
+ ],
+ )
+ def test_is_monotonic_incomparable(self, attr):
+ index = Index([5, datetime.now(), 7])
+ assert not getattr(index, attr)
+
+ @pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}])
+ @pytest.mark.parametrize(
+ "index,expected",
+ [
+ (Index(["qux", "baz", "foo", "bar"]), np.array([False, False, True, True])),
+ (Index([]), np.array([], dtype=bool)), # empty
+ ],
+ )
+ def test_isin(self, values, index, expected):
+ result = index.isin(values)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_isin_nan_common_object(self, nulls_fixture, nulls_fixture2):
+ # Test cartesian product of null fixtures and ensure that we don't
+ # mangle the various types (save a corner case with PyPy)
+
+ # all nans are the same
+ if (
+ isinstance(nulls_fixture, float)
+ and isinstance(nulls_fixture2, float)
+ and math.isnan(nulls_fixture)
+ and math.isnan(nulls_fixture2)
+ ):
+ tm.assert_numpy_array_equal(
+ Index(["a", nulls_fixture]).isin([nulls_fixture2]),
+ np.array([False, True]),
+ )
+
+ elif nulls_fixture is nulls_fixture2: # should preserve NA type
+ tm.assert_numpy_array_equal(
+ Index(["a", nulls_fixture]).isin([nulls_fixture2]),
+ np.array([False, True]),
+ )
+
+ else:
+ tm.assert_numpy_array_equal(
+ Index(["a", nulls_fixture]).isin([nulls_fixture2]),
+ np.array([False, False]),
+ )
+
+ def test_isin_nan_common_float64(self, nulls_fixture, float_numpy_dtype):
+ dtype = float_numpy_dtype
+
+ if nulls_fixture is pd.NaT or nulls_fixture is pd.NA:
+ # Check 1) that we cannot construct a float64 Index with this value
+ # and 2) that with an NaN we do not have .isin(nulls_fixture)
+ msg = (
+ r"float\(\) argument must be a string or a (real )?number, "
+ f"not {repr(type(nulls_fixture).__name__)}"
+ )
+ with pytest.raises(TypeError, match=msg):
+ Index([1.0, nulls_fixture], dtype=dtype)
+
+ idx = Index([1.0, np.nan], dtype=dtype)
+ assert not idx.isin([nulls_fixture]).any()
+ return
+
+ idx = Index([1.0, nulls_fixture], dtype=dtype)
+ res = idx.isin([np.nan])
+ tm.assert_numpy_array_equal(res, np.array([False, True]))
+
+ # we cannot compare NaT with NaN
+ res = idx.isin([pd.NaT])
+ tm.assert_numpy_array_equal(res, np.array([False, False]))
+
+ @pytest.mark.parametrize("level", [0, -1])
+ @pytest.mark.parametrize(
+ "index",
+ [
+ Index(["qux", "baz", "foo", "bar"]),
+ Index([1.0, 2.0, 3.0, 4.0], dtype=np.float64),
+ ],
+ )
+ def test_isin_level_kwarg(self, level, index):
+ values = index.tolist()[-2:] + ["nonexisting"]
+
+ expected = np.array([False, False, True, True])
+ tm.assert_numpy_array_equal(expected, index.isin(values, level=level))
+
+ index.name = "foobar"
+ tm.assert_numpy_array_equal(expected, index.isin(values, level="foobar"))
+
+ def test_isin_level_kwarg_bad_level_raises(self, index):
+ for level in [10, index.nlevels, -(index.nlevels + 1)]:
+ with pytest.raises(IndexError, match="Too many levels"):
+ index.isin([], level=level)
+
+ @pytest.mark.parametrize("label", [1.0, "foobar", "xyzzy", np.nan])
+ def test_isin_level_kwarg_bad_label_raises(self, label, index):
+ if isinstance(index, MultiIndex):
+ index = index.rename(["foo", "bar"] + index.names[2:])
+ msg = f"'Level {label} not found'"
+ else:
+ index = index.rename("foo")
+ msg = rf"Requested level \({label}\) does not match index name \(foo\)"
+ with pytest.raises(KeyError, match=msg):
+ index.isin([], level=label)
+
+ @pytest.mark.parametrize("empty", [[], Series(dtype=object), np.array([])])
+ def test_isin_empty(self, empty):
+ # see gh-16991
+ index = Index(["a", "b"])
+ expected = np.array([False, False])
+
+ result = index.isin(empty)
+ tm.assert_numpy_array_equal(expected, result)
+
+ @pytest.mark.parametrize(
+ "values",
+ [
+ [1, 2, 3, 4],
+ [1.0, 2.0, 3.0, 4.0],
+ [True, True, True, True],
+ ["foo", "bar", "baz", "qux"],
+ date_range("2018-01-01", freq="D", periods=4),
+ ],
+ )
+ def test_boolean_cmp(self, values):
+ index = Index(values)
+ result = index == values
+ expected = np.array([True, True, True, True], dtype=bool)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ @pytest.mark.parametrize("name,level", [(None, 0), ("a", "a")])
+ def test_get_level_values(self, index, name, level):
+ expected = index.copy()
+ if name:
+ expected.name = name
+
+ result = expected.get_level_values(level)
+ tm.assert_index_equal(result, expected)
+
+ def test_slice_keep_name(self):
+ index = Index(["a", "b"], name="asdf")
+ assert index.name == index[1:].name
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ "string",
+ "datetime",
+ "int64",
+ "int32",
+ "uint64",
+ "uint32",
+ "float64",
+ "float32",
+ ],
+ indirect=True,
+ )
+ def test_join_self(self, index, join_type):
+ joined = index.join(index, how=join_type)
+ assert index is joined
+
+ @pytest.mark.parametrize("method", ["strip", "rstrip", "lstrip"])
+ def test_str_attribute(self, method):
+ # GH9068
+ index = Index([" jack", "jill ", " jesse ", "frank"])
+ expected = Index([getattr(str, method)(x) for x in index.values])
+
+ result = getattr(index.str, method)()
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ Index(range(5)),
+ tm.makeDateIndex(10),
+ MultiIndex.from_tuples([("foo", "1"), ("bar", "3")]),
+ period_range(start="2000", end="2010", freq="A"),
+ ],
+ )
+ def test_str_attribute_raises(self, index):
+ with pytest.raises(AttributeError, match="only use .str accessor"):
+ index.str.repeat(2)
+
+ @pytest.mark.parametrize(
+ "expand,expected",
+ [
+ (None, Index([["a", "b", "c"], ["d", "e"], ["f"]])),
+ (False, Index([["a", "b", "c"], ["d", "e"], ["f"]])),
+ (
+ True,
+ MultiIndex.from_tuples(
+ [("a", "b", "c"), ("d", "e", np.nan), ("f", np.nan, np.nan)]
+ ),
+ ),
+ ],
+ )
+ def test_str_split(self, expand, expected):
+ index = Index(["a b c", "d e", "f"])
+ if expand is not None:
+ result = index.str.split(expand=expand)
+ else:
+ result = index.str.split()
+
+ tm.assert_index_equal(result, expected)
+
+ def test_str_bool_return(self):
+ # test boolean case, should return np.array instead of boolean Index
+ index = Index(["a1", "a2", "b1", "b2"])
+ result = index.str.startswith("a")
+ expected = np.array([True, True, False, False])
+
+ tm.assert_numpy_array_equal(result, expected)
+ assert isinstance(result, np.ndarray)
+
+ def test_str_bool_series_indexing(self):
+ index = Index(["a1", "a2", "b1", "b2"])
+ s = Series(range(4), index=index)
+
+ result = s[s.index.str.startswith("a")]
+ expected = Series(range(2), index=["a1", "a2"])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "index,expected", [(Index(list("abcd")), True), (Index(range(4)), False)]
+ )
+ def test_tab_completion(self, index, expected):
+ # GH 9910
+ result = "str" in dir(index)
+ assert result == expected
+
+ def test_indexing_doesnt_change_class(self):
+ index = Index([1, 2, 3, "a", "b", "c"])
+
+ assert index[1:3].identical(Index([2, 3], dtype=np.object_))
+ assert index[[0, 1]].identical(Index([1, 2], dtype=np.object_))
+
+ def test_outer_join_sort(self):
+ left_index = Index(np.random.default_rng(2).permutation(15))
+ right_index = tm.makeDateIndex(10)
+
+ with tm.assert_produces_warning(RuntimeWarning):
+ result = left_index.join(right_index, how="outer")
+
+ # right_index in this case because DatetimeIndex has join precedence
+ # over int64 Index
+ with tm.assert_produces_warning(RuntimeWarning):
+ expected = right_index.astype(object).union(left_index.astype(object))
+
+ tm.assert_index_equal(result, expected)
+
+ def test_take_fill_value(self):
+ # GH 12631
+ index = Index(list("ABC"), name="xxx")
+ result = index.take(np.array([1, 0, -1]))
+ expected = Index(list("BAC"), name="xxx")
+ tm.assert_index_equal(result, expected)
+
+ # fill_value
+ result = index.take(np.array([1, 0, -1]), fill_value=True)
+ expected = Index(["B", "A", np.nan], name="xxx")
+ tm.assert_index_equal(result, expected)
+
+ # allow_fill=False
+ result = index.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
+ expected = Index(["B", "A", "C"], name="xxx")
+ tm.assert_index_equal(result, expected)
+
+ def test_take_fill_value_none_raises(self):
+ index = Index(list("ABC"), name="xxx")
+ msg = (
+ "When allow_fill=True and fill_value is not None, "
+ "all indices must be >= -1"
+ )
+
+ with pytest.raises(ValueError, match=msg):
+ index.take(np.array([1, 0, -2]), fill_value=True)
+ with pytest.raises(ValueError, match=msg):
+ index.take(np.array([1, 0, -5]), fill_value=True)
+
+ def test_take_bad_bounds_raises(self):
+ index = Index(list("ABC"), name="xxx")
+ with pytest.raises(IndexError, match="out of bounds"):
+ index.take(np.array([1, -5]))
+
+ @pytest.mark.parametrize("name", [None, "foobar"])
+ @pytest.mark.parametrize(
+ "labels",
+ [
+ [],
+ np.array([]),
+ ["A", "B", "C"],
+ ["C", "B", "A"],
+ np.array(["A", "B", "C"]),
+ np.array(["C", "B", "A"]),
+ # Must preserve name even if dtype changes
+ date_range("20130101", periods=3).values,
+ date_range("20130101", periods=3).tolist(),
+ ],
+ )
+ def test_reindex_preserves_name_if_target_is_list_or_ndarray(self, name, labels):
+ # GH6552
+ index = Index([0, 1, 2])
+ index.name = name
+ assert index.reindex(labels)[0].name == name
+
+ @pytest.mark.parametrize("labels", [[], np.array([]), np.array([], dtype=np.int64)])
+ def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, labels):
+ # GH7774
+ index = Index(list("abc"))
+ assert index.reindex(labels)[0].dtype.type == np.object_
+
+ @pytest.mark.parametrize(
+ "labels,dtype",
+ [
+ (DatetimeIndex([]), np.datetime64),
+ ],
+ )
+ def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, labels, dtype):
+ # GH7774
+ index = Index(list("abc"))
+ assert index.reindex(labels)[0].dtype.type == dtype
+
+ def test_reindex_doesnt_preserve_type_if_target_is_empty_index_numeric(
+ self, any_real_numpy_dtype
+ ):
+ # GH7774
+ dtype = any_real_numpy_dtype
+ index = Index(list("abc"))
+ labels = Index([], dtype=dtype)
+ assert index.reindex(labels)[0].dtype == dtype
+
+ def test_reindex_no_type_preserve_target_empty_mi(self):
+ index = Index(list("abc"))
+ result = index.reindex(
+ MultiIndex([Index([], np.int64), Index([], np.float64)], [[], []])
+ )[0]
+ assert result.levels[0].dtype.type == np.int64
+ assert result.levels[1].dtype.type == np.float64
+
+ def test_reindex_ignoring_level(self):
+ # GH#35132
+ idx = Index([1, 2, 3], name="x")
+ idx2 = Index([1, 2, 3, 4], name="x")
+ expected = Index([1, 2, 3, 4], name="x")
+ result, _ = idx.reindex(idx2, level="x")
+ tm.assert_index_equal(result, expected)
+
+ def test_groupby(self):
+ index = Index(range(5))
+ result = index.groupby(np.array([1, 1, 2, 2, 2]))
+ expected = {1: Index([0, 1]), 2: Index([2, 3, 4])}
+
+ tm.assert_dict_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "mi,expected",
+ [
+ (MultiIndex.from_tuples([(1, 2), (4, 5)]), np.array([True, True])),
+ (MultiIndex.from_tuples([(1, 2), (4, 6)]), np.array([True, False])),
+ ],
+ )
+ def test_equals_op_multiindex(self, mi, expected):
+ # GH9785
+ # test comparisons of multiindex
+ df = pd.read_csv(StringIO("a,b,c\n1,2,3\n4,5,6"), index_col=[0, 1])
+
+ result = df.index == mi
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_equals_op_multiindex_identify(self):
+ df = pd.read_csv(StringIO("a,b,c\n1,2,3\n4,5,6"), index_col=[0, 1])
+
+ result = df.index == df.index
+ expected = np.array([True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)]),
+ Index(["foo", "bar", "baz"]),
+ ],
+ )
+ def test_equals_op_mismatched_multiindex_raises(self, index):
+ df = pd.read_csv(StringIO("a,b,c\n1,2,3\n4,5,6"), index_col=[0, 1])
+
+ with pytest.raises(ValueError, match="Lengths must match"):
+ df.index == index
+
+ def test_equals_op_index_vs_mi_same_length(self):
+ mi = MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)])
+ index = Index(["foo", "bar", "baz"])
+
+ result = mi == index
+ expected = np.array([False, False, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "dt_conv, arg",
+ [
+ (pd.to_datetime, ["2000-01-01", "2000-01-02"]),
+ (pd.to_timedelta, ["01:02:03", "01:02:04"]),
+ ],
+ )
+ def test_dt_conversion_preserves_name(self, dt_conv, arg):
+ # GH 10875
+ index = Index(arg, name="label")
+ assert index.name == dt_conv(index).name
+
+ def test_cached_properties_not_settable(self):
+ index = Index([1, 2, 3])
+ with pytest.raises(AttributeError, match="Can't set attribute"):
+ index.is_unique = False
+
+ def test_tab_complete_warning(self, ip):
+ # https://github.com/pandas-dev/pandas/issues/16409
+ pytest.importorskip("IPython", minversion="6.0.0")
+ from IPython.core.completer import provisionalcompleter
+
+ code = "import pandas as pd; idx = pd.Index([1, 2])"
+ ip.run_cell(code)
+
+ # GH 31324 newer jedi version raises Deprecation warning;
+ # appears resolved 2021-02-02
+ with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
+ with provisionalcompleter("ignore"):
+ list(ip.Completer.completions("idx.", 4))
+
+ def test_contains_method_removed(self, index):
+ # GH#30103 method removed for all types except IntervalIndex
+ if isinstance(index, IntervalIndex):
+ index.contains(1)
+ else:
+ msg = f"'{type(index).__name__}' object has no attribute 'contains'"
+ with pytest.raises(AttributeError, match=msg):
+ index.contains(1)
+
+ def test_sortlevel(self):
+ index = Index([5, 4, 3, 2, 1])
+ with pytest.raises(Exception, match="ascending must be a single bool value or"):
+ index.sortlevel(ascending="True")
+
+ with pytest.raises(
+ Exception, match="ascending must be a list of bool values of length 1"
+ ):
+ index.sortlevel(ascending=[True, True])
+
+ with pytest.raises(Exception, match="ascending must be a bool value"):
+ index.sortlevel(ascending=["True"])
+
+ expected = Index([1, 2, 3, 4, 5])
+ result = index.sortlevel(ascending=[True])
+ tm.assert_index_equal(result[0], expected)
+
+ expected = Index([1, 2, 3, 4, 5])
+ result = index.sortlevel(ascending=True)
+ tm.assert_index_equal(result[0], expected)
+
+ expected = Index([5, 4, 3, 2, 1])
+ result = index.sortlevel(ascending=False)
+ tm.assert_index_equal(result[0], expected)
+
+ def test_sortlevel_na_position(self):
+ # GH#51612
+ idx = Index([1, np.nan])
+ result = idx.sortlevel(na_position="first")[0]
+ expected = Index([np.nan, 1])
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "periods, expected_results",
+ [
+ (1, [np.nan, 10, 10, 10, 10]),
+ (2, [np.nan, np.nan, 20, 20, 20]),
+ (3, [np.nan, np.nan, np.nan, 30, 30]),
+ ],
+ )
+ def test_index_diff(self, periods, expected_results):
+ # GH#19708
+ idx = Index([10, 20, 30, 40, 50])
+ result = idx.diff(periods)
+ expected = Index(expected_results)
+
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "decimals, expected_results",
+ [
+ (0, [1.0, 2.0, 3.0]),
+ (1, [1.2, 2.3, 3.5]),
+ (2, [1.23, 2.35, 3.46]),
+ ],
+ )
+ def test_index_round(self, decimals, expected_results):
+ # GH#19708
+ idx = Index([1.234, 2.345, 3.456])
+ result = idx.round(decimals)
+ expected = Index(expected_results)
+
+ tm.assert_index_equal(result, expected)
+
+
+class TestMixedIntIndex:
+ # Mostly the tests from common.py for which the results differ
+ # in py2 and py3 because ints and strings are uncomparable in py3
+ # (GH 13514)
+ @pytest.fixture
+ def simple_index(self) -> Index:
+ return Index([0, "a", 1, "b", 2, "c"])
+
+ def test_argsort(self, simple_index):
+ index = simple_index
+ with pytest.raises(TypeError, match="'>|<' not supported"):
+ index.argsort()
+
+ def test_numpy_argsort(self, simple_index):
+ index = simple_index
+ with pytest.raises(TypeError, match="'>|<' not supported"):
+ np.argsort(index)
+
+ def test_copy_name(self, simple_index):
+ # Check that "name" argument passed at initialization is honoured
+ # GH12309
+ index = simple_index
+
+ first = type(index)(index, copy=True, name="mario")
+ second = type(first)(first, copy=False)
+
+ # Even though "copy=False", we want a new object.
+ assert first is not second
+ tm.assert_index_equal(first, second)
+
+ assert first.name == "mario"
+ assert second.name == "mario"
+
+ s1 = Series(2, index=first)
+ s2 = Series(3, index=second[:-1])
+
+ s3 = s1 * s2
+
+ assert s3.index.name == "mario"
+
+ def test_copy_name2(self):
+ # Check that adding a "name" parameter to the copy is honored
+ # GH14302
+ index = Index([1, 2], name="MyName")
+ index1 = index.copy()
+
+ tm.assert_index_equal(index, index1)
+
+ index2 = index.copy(name="NewName")
+ tm.assert_index_equal(index, index2, check_names=False)
+ assert index.name == "MyName"
+ assert index2.name == "NewName"
+
+ def test_unique_na(self):
+ idx = Index([2, np.nan, 2, 1], name="my_index")
+ expected = Index([2, np.nan, 1], name="my_index")
+ result = idx.unique()
+ tm.assert_index_equal(result, expected)
+
+ def test_logical_compat(self, simple_index):
+ index = simple_index
+ assert index.all() == index.values.all()
+ assert index.any() == index.values.any()
+
+ @pytest.mark.parametrize("how", ["any", "all"])
+ @pytest.mark.parametrize("dtype", [None, object, "category"])
+ @pytest.mark.parametrize(
+ "vals,expected",
+ [
+ ([1, 2, 3], [1, 2, 3]),
+ ([1.0, 2.0, 3.0], [1.0, 2.0, 3.0]),
+ ([1.0, 2.0, np.nan, 3.0], [1.0, 2.0, 3.0]),
+ (["A", "B", "C"], ["A", "B", "C"]),
+ (["A", np.nan, "B", "C"], ["A", "B", "C"]),
+ ],
+ )
+ def test_dropna(self, how, dtype, vals, expected):
+ # GH 6194
+ index = Index(vals, dtype=dtype)
+ result = index.dropna(how=how)
+ expected = Index(expected, dtype=dtype)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("how", ["any", "all"])
+ @pytest.mark.parametrize(
+ "index,expected",
+ [
+ (
+ DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]),
+ DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]),
+ ),
+ (
+ DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", pd.NaT]),
+ DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]),
+ ),
+ (
+ TimedeltaIndex(["1 days", "2 days", "3 days"]),
+ TimedeltaIndex(["1 days", "2 days", "3 days"]),
+ ),
+ (
+ TimedeltaIndex([pd.NaT, "1 days", "2 days", "3 days", pd.NaT]),
+ TimedeltaIndex(["1 days", "2 days", "3 days"]),
+ ),
+ (
+ PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
+ PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
+ ),
+ (
+ PeriodIndex(["2012-02", "2012-04", "NaT", "2012-05"], freq="M"),
+ PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
+ ),
+ ],
+ )
+ def test_dropna_dt_like(self, how, index, expected):
+ result = index.dropna(how=how)
+ tm.assert_index_equal(result, expected)
+
+ def test_dropna_invalid_how_raises(self):
+ msg = "invalid how option: xxx"
+ with pytest.raises(ValueError, match=msg):
+ Index([1, 2, 3]).dropna(how="xxx")
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ Index([np.nan]),
+ Index([np.nan, 1]),
+ Index([1, 2, np.nan]),
+ Index(["a", "b", np.nan]),
+ pd.to_datetime(["NaT"]),
+ pd.to_datetime(["NaT", "2000-01-01"]),
+ pd.to_datetime(["2000-01-01", "NaT", "2000-01-02"]),
+ pd.to_timedelta(["1 day", "NaT"]),
+ ],
+ )
+ def test_is_monotonic_na(self, index):
+ assert index.is_monotonic_increasing is False
+ assert index.is_monotonic_decreasing is False
+ assert index._is_strictly_monotonic_increasing is False
+ assert index._is_strictly_monotonic_decreasing is False
+
+ def test_int_name_format(self, frame_or_series):
+ index = Index(["a", "b", "c"], name=0)
+ result = frame_or_series(list(range(3)), index=index)
+ assert "0" in repr(result)
+
+ def test_str_to_bytes_raises(self):
+ # GH 26447
+ index = Index([str(x) for x in range(10)])
+ msg = "^'str' object cannot be interpreted as an integer$"
+ with pytest.raises(TypeError, match=msg):
+ bytes(index)
+
+ @pytest.mark.filterwarnings("ignore:elementwise comparison failed:FutureWarning")
+ def test_index_with_tuple_bool(self):
+ # GH34123
+ # TODO: also this op right now produces FutureWarning from numpy
+ # https://github.com/numpy/numpy/issues/11521
+ idx = Index([("a", "b"), ("b", "c"), ("c", "a")])
+ result = idx == ("c", "a")
+ expected = np.array([False, False, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+
+class TestIndexUtils:
+ @pytest.mark.parametrize(
+ "data, names, expected",
+ [
+ ([[1, 2, 3]], None, Index([1, 2, 3])),
+ ([[1, 2, 3]], ["name"], Index([1, 2, 3], name="name")),
+ (
+ [["a", "a"], ["c", "d"]],
+ None,
+ MultiIndex([["a"], ["c", "d"]], [[0, 0], [0, 1]]),
+ ),
+ (
+ [["a", "a"], ["c", "d"]],
+ ["L1", "L2"],
+ MultiIndex([["a"], ["c", "d"]], [[0, 0], [0, 1]], names=["L1", "L2"]),
+ ),
+ ],
+ )
+ def test_ensure_index_from_sequences(self, data, names, expected):
+ result = ensure_index_from_sequences(data, names)
+ tm.assert_index_equal(result, expected)
+
+ def test_ensure_index_mixed_closed_intervals(self):
+ # GH27172
+ intervals = [
+ pd.Interval(0, 1, closed="left"),
+ pd.Interval(1, 2, closed="right"),
+ pd.Interval(2, 3, closed="neither"),
+ pd.Interval(3, 4, closed="both"),
+ ]
+ result = ensure_index(intervals)
+ expected = Index(intervals, dtype=object)
+ tm.assert_index_equal(result, expected)
+
+ def test_ensure_index_uint64(self):
+ # with both 0 and a large-uint64, np.array will infer to float64
+ # https://github.com/numpy/numpy/issues/19146
+ # but a more accurate choice would be uint64
+ values = [0, np.iinfo(np.uint64).max]
+
+ result = ensure_index(values)
+ assert list(result) == values
+
+ expected = Index(values, dtype="uint64")
+ tm.assert_index_equal(result, expected)
+
+ def test_get_combined_index(self):
+ result = _get_combined_index([])
+ expected = Index([])
+ tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "opname",
+ [
+ "eq",
+ "ne",
+ "le",
+ "lt",
+ "ge",
+ "gt",
+ "add",
+ "radd",
+ "sub",
+ "rsub",
+ "mul",
+ "rmul",
+ "truediv",
+ "rtruediv",
+ "floordiv",
+ "rfloordiv",
+ "pow",
+ "rpow",
+ "mod",
+ "divmod",
+ ],
+)
+def test_generated_op_names(opname, index):
+ opname = f"__{opname}__"
+ method = getattr(index, opname)
+ assert method.__name__ == opname
+
+
+@pytest.mark.parametrize("index_maker", tm.index_subclass_makers_generator())
+def test_index_subclass_constructor_wrong_kwargs(index_maker):
+ # GH #19348
+ with pytest.raises(TypeError, match="unexpected keyword argument"):
+ index_maker(foo="bar")
+
+
+def test_deprecated_fastpath():
+ msg = "[Uu]nexpected keyword argument"
+ with pytest.raises(TypeError, match=msg):
+ Index(np.array(["a", "b"], dtype=object), name="test", fastpath=True)
+
+ with pytest.raises(TypeError, match=msg):
+ Index(np.array([1, 2, 3], dtype="int64"), name="test", fastpath=True)
+
+ with pytest.raises(TypeError, match=msg):
+ RangeIndex(0, 5, 2, name="test", fastpath=True)
+
+ with pytest.raises(TypeError, match=msg):
+ CategoricalIndex(["a", "b", "c"], name="test", fastpath=True)
+
+
+def test_shape_of_invalid_index():
+ # Pre-2.0, it was possible to create "invalid" index objects backed by
+ # a multi-dimensional array (see https://github.com/pandas-dev/pandas/issues/27125
+ # about this). However, as long as this is not solved in general,this test ensures
+ # that the returned shape is consistent with this underlying array for
+ # compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775)
+ idx = Index([0, 1, 2, 3])
+ with pytest.raises(ValueError, match="Multi-dimensional indexing"):
+ # GH#30588 multi-dimensional indexing deprecated
+ idx[:, None]
+
+
+@pytest.mark.parametrize("dtype", [None, np.int64, np.uint64, np.float64])
+def test_validate_1d_input(dtype):
+ # GH#27125 check that we do not have >1-dimensional input
+ msg = "Index data must be 1-dimensional"
+
+ arr = np.arange(8).reshape(2, 2, 2)
+ with pytest.raises(ValueError, match=msg):
+ Index(arr, dtype=dtype)
+
+ df = DataFrame(arr.reshape(4, 2))
+ with pytest.raises(ValueError, match=msg):
+ Index(df, dtype=dtype)
+
+ # GH#13601 trying to assign a multi-dimensional array to an index is not allowed
+ ser = Series(0, range(4))
+ with pytest.raises(ValueError, match=msg):
+ ser.index = np.array([[2, 3]] * 4, dtype=dtype)
+
+
+@pytest.mark.parametrize(
+ "klass, extra_kwargs",
+ [
+ [Index, {}],
+ *[[lambda x: Index(x, dtype=dtyp), {}] for dtyp in tm.ALL_REAL_NUMPY_DTYPES],
+ [DatetimeIndex, {}],
+ [TimedeltaIndex, {}],
+ [PeriodIndex, {"freq": "Y"}],
+ ],
+)
+def test_construct_from_memoryview(klass, extra_kwargs):
+ # GH 13120
+ result = klass(memoryview(np.arange(2000, 2005)), **extra_kwargs)
+ expected = klass(list(range(2000, 2005)), **extra_kwargs)
+ tm.assert_index_equal(result, expected, exact=True)
+
+
+@pytest.mark.parametrize("op", [operator.lt, operator.gt])
+def test_nan_comparison_same_object(op):
+ # GH#47105
+ idx = Index([np.nan])
+ expected = np.array([False])
+
+ result = op(idx, idx)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = op(idx, idx.copy())
+ tm.assert_numpy_array_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..6245a129afedc1ca52fd33569b33f7128359069e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_common.py
@@ -0,0 +1,502 @@
+"""
+Collection of tests asserting things that should be true for
+any index subclass except for MultiIndex. Makes use of the `index_flat`
+fixture defined in pandas/conftest.py.
+"""
+from copy import (
+ copy,
+ deepcopy,
+)
+import re
+
+import numpy as np
+import pytest
+
+from pandas.compat import IS64
+from pandas.compat.numpy import np_version_gte1p25
+
+from pandas.core.dtypes.common import (
+ is_integer_dtype,
+ is_numeric_dtype,
+)
+
+import pandas as pd
+from pandas import (
+ CategoricalIndex,
+ MultiIndex,
+ PeriodIndex,
+ RangeIndex,
+)
+import pandas._testing as tm
+
+
+class TestCommon:
+ @pytest.mark.parametrize("name", [None, "new_name"])
+ def test_to_frame(self, name, index_flat, using_copy_on_write):
+ # see GH#15230, GH#22580
+ idx = index_flat
+
+ if name:
+ idx_name = name
+ else:
+ idx_name = idx.name or 0
+
+ df = idx.to_frame(name=idx_name)
+
+ assert df.index is idx
+ assert len(df.columns) == 1
+ assert df.columns[0] == idx_name
+ if not using_copy_on_write:
+ assert df[idx_name].values is not idx.values
+
+ df = idx.to_frame(index=False, name=idx_name)
+ assert df.index is not idx
+
+ def test_droplevel(self, index_flat):
+ # GH 21115
+ # MultiIndex is tested separately in test_multi.py
+ index = index_flat
+
+ assert index.droplevel([]).equals(index)
+
+ for level in [index.name, [index.name]]:
+ if isinstance(index.name, tuple) and level is index.name:
+ # GH 21121 : droplevel with tuple name
+ continue
+ msg = (
+ "Cannot remove 1 levels from an index with 1 levels: at least one "
+ "level must be left."
+ )
+ with pytest.raises(ValueError, match=msg):
+ index.droplevel(level)
+
+ for level in "wrong", ["wrong"]:
+ with pytest.raises(
+ KeyError,
+ match=r"'Requested level \(wrong\) does not match index name \(None\)'",
+ ):
+ index.droplevel(level)
+
+ def test_constructor_non_hashable_name(self, index_flat):
+ # GH 20527
+ index = index_flat
+
+ message = "Index.name must be a hashable type"
+ renamed = [["1"]]
+
+ # With .rename()
+ with pytest.raises(TypeError, match=message):
+ index.rename(name=renamed)
+
+ # With .set_names()
+ with pytest.raises(TypeError, match=message):
+ index.set_names(names=renamed)
+
+ def test_constructor_unwraps_index(self, index_flat):
+ a = index_flat
+ # Passing dtype is necessary for Index([True, False], dtype=object)
+ # case.
+ b = type(a)(a, dtype=a.dtype)
+ tm.assert_equal(a._data, b._data)
+
+ def test_to_flat_index(self, index_flat):
+ # 22866
+ index = index_flat
+
+ result = index.to_flat_index()
+ tm.assert_index_equal(result, index)
+
+ def test_set_name_methods(self, index_flat):
+ # MultiIndex tested separately
+ index = index_flat
+ new_name = "This is the new name for this index"
+
+ original_name = index.name
+ new_ind = index.set_names([new_name])
+ assert new_ind.name == new_name
+ assert index.name == original_name
+ res = index.rename(new_name, inplace=True)
+
+ # should return None
+ assert res is None
+ assert index.name == new_name
+ assert index.names == [new_name]
+ with pytest.raises(ValueError, match="Level must be None"):
+ index.set_names("a", level=0)
+
+ # rename in place just leaves tuples and other containers alone
+ name = ("A", "B")
+ index.rename(name, inplace=True)
+ assert index.name == name
+ assert index.names == [name]
+
+ @pytest.mark.xfail
+ def test_set_names_single_label_no_level(self, index_flat):
+ with pytest.raises(TypeError, match="list-like"):
+ # should still fail even if it would be the right length
+ index_flat.set_names("a")
+
+ def test_copy_and_deepcopy(self, index_flat):
+ index = index_flat
+
+ for func in (copy, deepcopy):
+ idx_copy = func(index)
+ assert idx_copy is not index
+ assert idx_copy.equals(index)
+
+ new_copy = index.copy(deep=True, name="banana")
+ assert new_copy.name == "banana"
+
+ def test_copy_name(self, index_flat):
+ # GH#12309: Check that the "name" argument
+ # passed at initialization is honored.
+ index = index_flat
+
+ first = type(index)(index, copy=True, name="mario")
+ second = type(first)(first, copy=False)
+
+ # Even though "copy=False", we want a new object.
+ assert first is not second
+ tm.assert_index_equal(first, second)
+
+ # Not using tm.assert_index_equal() since names differ.
+ assert index.equals(first)
+
+ assert first.name == "mario"
+ assert second.name == "mario"
+
+ # TODO: belongs in series arithmetic tests?
+ s1 = pd.Series(2, index=first)
+ s2 = pd.Series(3, index=second[:-1])
+ # See GH#13365
+ s3 = s1 * s2
+ assert s3.index.name == "mario"
+
+ def test_copy_name2(self, index_flat):
+ # GH#35592
+ index = index_flat
+
+ assert index.copy(name="mario").name == "mario"
+
+ with pytest.raises(ValueError, match="Length of new names must be 1, got 2"):
+ index.copy(name=["mario", "luigi"])
+
+ msg = f"{type(index).__name__}.name must be a hashable type"
+ with pytest.raises(TypeError, match=msg):
+ index.copy(name=[["mario"]])
+
+ def test_unique_level(self, index_flat):
+ # don't test a MultiIndex here (as its tested separated)
+ index = index_flat
+
+ # GH 17896
+ expected = index.drop_duplicates()
+ for level in [0, index.name, None]:
+ result = index.unique(level=level)
+ tm.assert_index_equal(result, expected)
+
+ msg = "Too many levels: Index has only 1 level, not 4"
+ with pytest.raises(IndexError, match=msg):
+ index.unique(level=3)
+
+ msg = (
+ rf"Requested level \(wrong\) does not match index name "
+ rf"\({re.escape(index.name.__repr__())}\)"
+ )
+ with pytest.raises(KeyError, match=msg):
+ index.unique(level="wrong")
+
+ def test_unique(self, index_flat):
+ # MultiIndex tested separately
+ index = index_flat
+ if not len(index):
+ pytest.skip("Skip check for empty Index and MultiIndex")
+
+ idx = index[[0] * 5]
+ idx_unique = index[[0]]
+
+ # We test against `idx_unique`, so first we make sure it's unique
+ # and doesn't contain nans.
+ assert idx_unique.is_unique is True
+ try:
+ assert idx_unique.hasnans is False
+ except NotImplementedError:
+ pass
+
+ result = idx.unique()
+ tm.assert_index_equal(result, idx_unique)
+
+ # nans:
+ if not index._can_hold_na:
+ pytest.skip("Skip na-check if index cannot hold na")
+
+ vals = index._values[[0] * 5]
+ vals[0] = np.nan
+
+ vals_unique = vals[:2]
+ idx_nan = index._shallow_copy(vals)
+ idx_unique_nan = index._shallow_copy(vals_unique)
+ assert idx_unique_nan.is_unique is True
+
+ assert idx_nan.dtype == index.dtype
+ assert idx_unique_nan.dtype == index.dtype
+
+ expected = idx_unique_nan
+ for pos, i in enumerate([idx_nan, idx_unique_nan]):
+ result = i.unique()
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.filterwarnings("ignore:Period with BDay freq:FutureWarning")
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_searchsorted_monotonic(self, index_flat, request):
+ # GH17271
+ index = index_flat
+ # not implemented for tuple searches in MultiIndex
+ # or Intervals searches in IntervalIndex
+ if isinstance(index, pd.IntervalIndex):
+ mark = pytest.mark.xfail(
+ reason="IntervalIndex.searchsorted does not support Interval arg",
+ raises=NotImplementedError,
+ )
+ request.node.add_marker(mark)
+
+ # nothing to test if the index is empty
+ if index.empty:
+ pytest.skip("Skip check for empty Index")
+ value = index[0]
+
+ # determine the expected results (handle dupes for 'right')
+ expected_left, expected_right = 0, (index == value).argmin()
+ if expected_right == 0:
+ # all values are the same, expected_right should be length
+ expected_right = len(index)
+
+ # test _searchsorted_monotonic in all cases
+ # test searchsorted only for increasing
+ if index.is_monotonic_increasing:
+ ssm_left = index._searchsorted_monotonic(value, side="left")
+ assert expected_left == ssm_left
+
+ ssm_right = index._searchsorted_monotonic(value, side="right")
+ assert expected_right == ssm_right
+
+ ss_left = index.searchsorted(value, side="left")
+ assert expected_left == ss_left
+
+ ss_right = index.searchsorted(value, side="right")
+ assert expected_right == ss_right
+
+ elif index.is_monotonic_decreasing:
+ ssm_left = index._searchsorted_monotonic(value, side="left")
+ assert expected_left == ssm_left
+
+ ssm_right = index._searchsorted_monotonic(value, side="right")
+ assert expected_right == ssm_right
+ else:
+ # non-monotonic should raise.
+ msg = "index must be monotonic increasing or decreasing"
+ with pytest.raises(ValueError, match=msg):
+ index._searchsorted_monotonic(value, side="left")
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_drop_duplicates(self, index_flat, keep):
+ # MultiIndex is tested separately
+ index = index_flat
+ if isinstance(index, RangeIndex):
+ pytest.skip(
+ "RangeIndex is tested in test_drop_duplicates_no_duplicates "
+ "as it cannot hold duplicates"
+ )
+ if len(index) == 0:
+ pytest.skip(
+ "empty index is tested in test_drop_duplicates_no_duplicates "
+ "as it cannot hold duplicates"
+ )
+
+ # make unique index
+ holder = type(index)
+ unique_values = list(set(index))
+ dtype = index.dtype if is_numeric_dtype(index) else None
+ unique_idx = holder(unique_values, dtype=dtype)
+
+ # make duplicated index
+ n = len(unique_idx)
+ duplicated_selection = np.random.default_rng(2).choice(n, int(n * 1.5))
+ idx = holder(unique_idx.values[duplicated_selection])
+
+ # Series.duplicated is tested separately
+ expected_duplicated = (
+ pd.Series(duplicated_selection).duplicated(keep=keep).values
+ )
+ tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected_duplicated)
+
+ # Series.drop_duplicates is tested separately
+ expected_dropped = holder(pd.Series(idx).drop_duplicates(keep=keep))
+ tm.assert_index_equal(idx.drop_duplicates(keep=keep), expected_dropped)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_drop_duplicates_no_duplicates(self, index_flat):
+ # MultiIndex is tested separately
+ index = index_flat
+
+ # make unique index
+ if isinstance(index, RangeIndex):
+ # RangeIndex cannot have duplicates
+ unique_idx = index
+ else:
+ holder = type(index)
+ unique_values = list(set(index))
+ dtype = index.dtype if is_numeric_dtype(index) else None
+ unique_idx = holder(unique_values, dtype=dtype)
+
+ # check on unique index
+ expected_duplicated = np.array([False] * len(unique_idx), dtype="bool")
+ tm.assert_numpy_array_equal(unique_idx.duplicated(), expected_duplicated)
+ result_dropped = unique_idx.drop_duplicates()
+ tm.assert_index_equal(result_dropped, unique_idx)
+ # validate shallow copy
+ assert result_dropped is not unique_idx
+
+ def test_drop_duplicates_inplace(self, index):
+ msg = r"drop_duplicates\(\) got an unexpected keyword argument"
+ with pytest.raises(TypeError, match=msg):
+ index.drop_duplicates(inplace=True)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_has_duplicates(self, index_flat):
+ # MultiIndex tested separately in:
+ # tests/indexes/multi/test_unique_and_duplicates.
+ index = index_flat
+ holder = type(index)
+ if not len(index) or isinstance(index, RangeIndex):
+ # MultiIndex tested separately in:
+ # tests/indexes/multi/test_unique_and_duplicates.
+ # RangeIndex is unique by definition.
+ pytest.skip("Skip check for empty Index, MultiIndex, and RangeIndex")
+
+ idx = holder([index[0]] * 5)
+ assert idx.is_unique is False
+ assert idx.has_duplicates is True
+
+ @pytest.mark.parametrize(
+ "dtype",
+ ["int64", "uint64", "float64", "category", "datetime64[ns]", "timedelta64[ns]"],
+ )
+ def test_astype_preserves_name(self, index, dtype):
+ # https://github.com/pandas-dev/pandas/issues/32013
+ if isinstance(index, MultiIndex):
+ index.names = ["idx" + str(i) for i in range(index.nlevels)]
+ else:
+ index.name = "idx"
+
+ warn = None
+ if index.dtype.kind == "c" and dtype in ["float64", "int64", "uint64"]:
+ # imaginary components discarded
+ if np_version_gte1p25:
+ warn = np.exceptions.ComplexWarning
+ else:
+ warn = np.ComplexWarning
+
+ is_pyarrow_str = str(index.dtype) == "string[pyarrow]" and dtype == "category"
+ try:
+ # Some of these conversions cannot succeed so we use a try / except
+ with tm.assert_produces_warning(
+ warn,
+ raise_on_extra_warnings=is_pyarrow_str,
+ check_stacklevel=False,
+ ):
+ result = index.astype(dtype)
+ except (ValueError, TypeError, NotImplementedError, SystemError):
+ return
+
+ if isinstance(index, MultiIndex):
+ assert result.names == index.names
+ else:
+ assert result.name == index.name
+
+ def test_hasnans_isnans(self, index_flat):
+ # GH#11343, added tests for hasnans / isnans
+ index = index_flat
+
+ # cases in indices doesn't include NaN
+ idx = index.copy(deep=True)
+ expected = np.array([False] * len(idx), dtype=bool)
+ tm.assert_numpy_array_equal(idx._isnan, expected)
+ assert idx.hasnans is False
+
+ idx = index.copy(deep=True)
+ values = idx._values
+
+ if len(index) == 0:
+ return
+ elif is_integer_dtype(index.dtype):
+ return
+ elif index.dtype == bool:
+ # values[1] = np.nan below casts to True!
+ return
+
+ values[1] = np.nan
+
+ idx = type(index)(values)
+
+ expected = np.array([False] * len(idx), dtype=bool)
+ expected[1] = True
+ tm.assert_numpy_array_equal(idx._isnan, expected)
+ assert idx.hasnans is True
+
+
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+@pytest.mark.parametrize("na_position", [None, "middle"])
+def test_sort_values_invalid_na_position(index_with_missing, na_position):
+ with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"):
+ index_with_missing.sort_values(na_position=na_position)
+
+
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+@pytest.mark.parametrize("na_position", ["first", "last"])
+def test_sort_values_with_missing(index_with_missing, na_position, request):
+ # GH 35584. Test that sort_values works with missing values,
+ # sort non-missing and place missing according to na_position
+
+ if isinstance(index_with_missing, CategoricalIndex):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="missing value sorting order not well-defined", strict=False
+ )
+ )
+
+ missing_count = np.sum(index_with_missing.isna())
+ not_na_vals = index_with_missing[index_with_missing.notna()].values
+ sorted_values = np.sort(not_na_vals)
+ if na_position == "first":
+ sorted_values = np.concatenate([[None] * missing_count, sorted_values])
+ else:
+ sorted_values = np.concatenate([sorted_values, [None] * missing_count])
+
+ # Explicitly pass dtype needed for Index backed by EA e.g. IntegerArray
+ expected = type(index_with_missing)(sorted_values, dtype=index_with_missing.dtype)
+
+ result = index_with_missing.sort_values(na_position=na_position)
+ tm.assert_index_equal(result, expected)
+
+
+def test_ndarray_compat_properties(index):
+ if isinstance(index, PeriodIndex) and not IS64:
+ pytest.skip("Overflow")
+ idx = index
+ assert idx.T.equals(idx)
+ assert idx.transpose().equals(idx)
+
+ values = idx.values
+
+ assert idx.shape == values.shape
+ assert idx.ndim == values.ndim
+ assert idx.size == values.size
+
+ if not isinstance(index, (RangeIndex, MultiIndex)):
+ # These two are not backed by an ndarray
+ assert idx.nbytes == values.nbytes
+
+ # test for validity
+ idx.nbytes
+ idx.values.nbytes
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_datetimelike.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_datetimelike.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ad2e9b2f717ef7424d99355fe1489bd9cf494d8
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_datetimelike.py
@@ -0,0 +1,169 @@
+""" generic datetimelike tests """
+
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+
+class TestDatetimeLike:
+ @pytest.fixture(
+ params=[
+ pd.period_range("20130101", periods=5, freq="D"),
+ pd.TimedeltaIndex(
+ [
+ "0 days 01:00:00",
+ "1 days 01:00:00",
+ "2 days 01:00:00",
+ "3 days 01:00:00",
+ "4 days 01:00:00",
+ ],
+ dtype="timedelta64[ns]",
+ freq="D",
+ ),
+ pd.DatetimeIndex(
+ ["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"],
+ dtype="datetime64[ns]",
+ freq="D",
+ ),
+ ]
+ )
+ def simple_index(self, request):
+ return request.param
+
+ def test_isin(self, simple_index):
+ index = simple_index[:4]
+ result = index.isin(index)
+ assert result.all()
+
+ result = index.isin(list(index))
+ assert result.all()
+
+ result = index.isin([index[2], 5])
+ expected = np.array([False, False, True, False])
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_argsort_matches_array(self, simple_index):
+ idx = simple_index
+ idx = idx.insert(1, pd.NaT)
+
+ result = idx.argsort()
+ expected = idx._data.argsort()
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_can_hold_identifiers(self, simple_index):
+ idx = simple_index
+ key = idx[0]
+ assert idx._can_hold_identifiers_and_holds_name(key) is False
+
+ def test_shift_identity(self, simple_index):
+ idx = simple_index
+ tm.assert_index_equal(idx, idx.shift(0))
+
+ def test_shift_empty(self, simple_index):
+ # GH#14811
+ idx = simple_index[:0]
+ tm.assert_index_equal(idx, idx.shift(1))
+
+ def test_str(self, simple_index):
+ # test the string repr
+ idx = simple_index.copy()
+ idx.name = "foo"
+ assert f"length={len(idx)}" not in str(idx)
+ assert "'foo'" in str(idx)
+ assert type(idx).__name__ in str(idx)
+
+ if hasattr(idx, "tz"):
+ if idx.tz is not None:
+ assert idx.tz in str(idx)
+ if isinstance(idx, pd.PeriodIndex):
+ assert f"dtype='period[{idx.freqstr}]'" in str(idx)
+ else:
+ assert f"freq='{idx.freqstr}'" in str(idx)
+
+ def test_view(self, simple_index):
+ idx = simple_index
+
+ idx_view = idx.view("i8")
+ result = type(simple_index)(idx)
+ tm.assert_index_equal(result, idx)
+
+ idx_view = idx.view(type(simple_index))
+ result = type(simple_index)(idx)
+ tm.assert_index_equal(result, idx_view)
+
+ def test_map_callable(self, simple_index):
+ index = simple_index
+ expected = index + index.freq
+ result = index.map(lambda x: x + index.freq)
+ tm.assert_index_equal(result, expected)
+
+ # map to NaT
+ result = index.map(lambda x: pd.NaT if x == index[0] else x)
+ expected = pd.Index([pd.NaT] + index[1:].tolist())
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "mapper",
+ [
+ lambda values, index: {i: e for e, i in zip(values, index)},
+ lambda values, index: pd.Series(values, index, dtype=object),
+ ],
+ )
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_map_dictlike(self, mapper, simple_index):
+ index = simple_index
+ expected = index + index.freq
+
+ # don't compare the freqs
+ if isinstance(expected, (pd.DatetimeIndex, pd.TimedeltaIndex)):
+ expected = expected._with_freq(None)
+
+ result = index.map(mapper(expected, index))
+ tm.assert_index_equal(result, expected)
+
+ expected = pd.Index([pd.NaT] + index[1:].tolist())
+ result = index.map(mapper(expected, index))
+ tm.assert_index_equal(result, expected)
+
+ # empty map; these map to np.nan because we cannot know
+ # to re-infer things
+ expected = pd.Index([np.nan] * len(index))
+ result = index.map(mapper([], []))
+ tm.assert_index_equal(result, expected)
+
+ def test_getitem_preserves_freq(self, simple_index):
+ index = simple_index
+ assert index.freq is not None
+
+ result = index[:]
+ assert result.freq == index.freq
+
+ def test_where_cast_str(self, simple_index):
+ index = simple_index
+
+ mask = np.ones(len(index), dtype=bool)
+ mask[-1] = False
+
+ result = index.where(mask, str(index[0]))
+ expected = index.where(mask, index[0])
+ tm.assert_index_equal(result, expected)
+
+ result = index.where(mask, [str(index[0])])
+ tm.assert_index_equal(result, expected)
+
+ expected = index.astype(object).where(mask, "foo")
+ result = index.where(mask, "foo")
+ tm.assert_index_equal(result, expected)
+
+ result = index.where(mask, ["foo"])
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
+ def test_diff(self, unit):
+ # GH 55080
+ dti = pd.to_datetime([10, 20, 30], unit=unit).as_unit(unit)
+ result = dti.diff(1)
+ expected = pd.TimedeltaIndex([pd.NaT, 10, 10], unit=unit).as_unit(unit)
+ tm.assert_index_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_engines.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_engines.py
new file mode 100644
index 0000000000000000000000000000000000000000..468c2240c8192098a6ff75a5a2d0210c8108a176
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_engines.py
@@ -0,0 +1,192 @@
+import re
+
+import numpy as np
+import pytest
+
+from pandas._libs import index as libindex
+
+import pandas as pd
+
+
+@pytest.fixture(
+ params=[
+ (libindex.Int64Engine, np.int64),
+ (libindex.Int32Engine, np.int32),
+ (libindex.Int16Engine, np.int16),
+ (libindex.Int8Engine, np.int8),
+ (libindex.UInt64Engine, np.uint64),
+ (libindex.UInt32Engine, np.uint32),
+ (libindex.UInt16Engine, np.uint16),
+ (libindex.UInt8Engine, np.uint8),
+ (libindex.Float64Engine, np.float64),
+ (libindex.Float32Engine, np.float32),
+ ],
+ ids=lambda x: x[0].__name__,
+)
+def numeric_indexing_engine_type_and_dtype(request):
+ return request.param
+
+
+class TestDatetimeEngine:
+ @pytest.mark.parametrize(
+ "scalar",
+ [
+ pd.Timedelta(pd.Timestamp("2016-01-01").asm8.view("m8[ns]")),
+ pd.Timestamp("2016-01-01")._value,
+ pd.Timestamp("2016-01-01").to_pydatetime(),
+ pd.Timestamp("2016-01-01").to_datetime64(),
+ ],
+ )
+ def test_not_contains_requires_timestamp(self, scalar):
+ dti1 = pd.date_range("2016-01-01", periods=3)
+ dti2 = dti1.insert(1, pd.NaT) # non-monotonic
+ dti3 = dti1.insert(3, dti1[0]) # non-unique
+ dti4 = pd.date_range("2016-01-01", freq="ns", periods=2_000_000)
+ dti5 = dti4.insert(0, dti4[0]) # over size threshold, not unique
+
+ msg = "|".join([re.escape(str(scalar)), re.escape(repr(scalar))])
+ for dti in [dti1, dti2, dti3, dti4, dti5]:
+ with pytest.raises(TypeError, match=msg):
+ scalar in dti._engine
+
+ with pytest.raises(KeyError, match=msg):
+ dti._engine.get_loc(scalar)
+
+
+class TestTimedeltaEngine:
+ @pytest.mark.parametrize(
+ "scalar",
+ [
+ pd.Timestamp(pd.Timedelta(days=42).asm8.view("datetime64[ns]")),
+ pd.Timedelta(days=42)._value,
+ pd.Timedelta(days=42).to_pytimedelta(),
+ pd.Timedelta(days=42).to_timedelta64(),
+ ],
+ )
+ def test_not_contains_requires_timedelta(self, scalar):
+ tdi1 = pd.timedelta_range("42 days", freq="9h", periods=1234)
+ tdi2 = tdi1.insert(1, pd.NaT) # non-monotonic
+ tdi3 = tdi1.insert(3, tdi1[0]) # non-unique
+ tdi4 = pd.timedelta_range("42 days", freq="ns", periods=2_000_000)
+ tdi5 = tdi4.insert(0, tdi4[0]) # over size threshold, not unique
+
+ msg = "|".join([re.escape(str(scalar)), re.escape(repr(scalar))])
+ for tdi in [tdi1, tdi2, tdi3, tdi4, tdi5]:
+ with pytest.raises(TypeError, match=msg):
+ scalar in tdi._engine
+
+ with pytest.raises(KeyError, match=msg):
+ tdi._engine.get_loc(scalar)
+
+
+class TestNumericEngine:
+ def test_is_monotonic(self, numeric_indexing_engine_type_and_dtype):
+ engine_type, dtype = numeric_indexing_engine_type_and_dtype
+ num = 1000
+ arr = np.array([1] * num + [2] * num + [3] * num, dtype=dtype)
+
+ # monotonic increasing
+ engine = engine_type(arr)
+ assert engine.is_monotonic_increasing is True
+ assert engine.is_monotonic_decreasing is False
+
+ # monotonic decreasing
+ engine = engine_type(arr[::-1])
+ assert engine.is_monotonic_increasing is False
+ assert engine.is_monotonic_decreasing is True
+
+ # neither monotonic increasing or decreasing
+ arr = np.array([1] * num + [2] * num + [1] * num, dtype=dtype)
+ engine = engine_type(arr[::-1])
+ assert engine.is_monotonic_increasing is False
+ assert engine.is_monotonic_decreasing is False
+
+ def test_is_unique(self, numeric_indexing_engine_type_and_dtype):
+ engine_type, dtype = numeric_indexing_engine_type_and_dtype
+
+ # unique
+ arr = np.array([1, 3, 2], dtype=dtype)
+ engine = engine_type(arr)
+ assert engine.is_unique is True
+
+ # not unique
+ arr = np.array([1, 2, 1], dtype=dtype)
+ engine = engine_type(arr)
+ assert engine.is_unique is False
+
+ def test_get_loc(self, numeric_indexing_engine_type_and_dtype):
+ engine_type, dtype = numeric_indexing_engine_type_and_dtype
+
+ # unique
+ arr = np.array([1, 2, 3], dtype=dtype)
+ engine = engine_type(arr)
+ assert engine.get_loc(2) == 1
+
+ # monotonic
+ num = 1000
+ arr = np.array([1] * num + [2] * num + [3] * num, dtype=dtype)
+ engine = engine_type(arr)
+ assert engine.get_loc(2) == slice(1000, 2000)
+
+ # not monotonic
+ arr = np.array([1, 2, 3] * num, dtype=dtype)
+ engine = engine_type(arr)
+ expected = np.array([False, True, False] * num, dtype=bool)
+ result = engine.get_loc(2)
+ assert (result == expected).all()
+
+
+class TestObjectEngine:
+ engine_type = libindex.ObjectEngine
+ dtype = np.object_
+ values = list("abc")
+
+ def test_is_monotonic(self):
+ num = 1000
+ arr = np.array(["a"] * num + ["a"] * num + ["c"] * num, dtype=self.dtype)
+
+ # monotonic increasing
+ engine = self.engine_type(arr)
+ assert engine.is_monotonic_increasing is True
+ assert engine.is_monotonic_decreasing is False
+
+ # monotonic decreasing
+ engine = self.engine_type(arr[::-1])
+ assert engine.is_monotonic_increasing is False
+ assert engine.is_monotonic_decreasing is True
+
+ # neither monotonic increasing or decreasing
+ arr = np.array(["a"] * num + ["b"] * num + ["a"] * num, dtype=self.dtype)
+ engine = self.engine_type(arr[::-1])
+ assert engine.is_monotonic_increasing is False
+ assert engine.is_monotonic_decreasing is False
+
+ def test_is_unique(self):
+ # unique
+ arr = np.array(self.values, dtype=self.dtype)
+ engine = self.engine_type(arr)
+ assert engine.is_unique is True
+
+ # not unique
+ arr = np.array(["a", "b", "a"], dtype=self.dtype)
+ engine = self.engine_type(arr)
+ assert engine.is_unique is False
+
+ def test_get_loc(self):
+ # unique
+ arr = np.array(self.values, dtype=self.dtype)
+ engine = self.engine_type(arr)
+ assert engine.get_loc("b") == 1
+
+ # monotonic
+ num = 1000
+ arr = np.array(["a"] * num + ["b"] * num + ["c"] * num, dtype=self.dtype)
+ engine = self.engine_type(arr)
+ assert engine.get_loc("b") == slice(1000, 2000)
+
+ # not monotonic
+ arr = np.array(self.values * num, dtype=self.dtype)
+ engine = self.engine_type(arr)
+ expected = np.array([False, True, False] * num, dtype=bool)
+ result = engine.get_loc("b")
+ assert (result == expected).all()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_frozen.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_frozen.py
new file mode 100644
index 0000000000000000000000000000000000000000..ace66b5b06a51291d2cf229fdc446d070054836a
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_frozen.py
@@ -0,0 +1,113 @@
+import re
+
+import pytest
+
+from pandas.core.indexes.frozen import FrozenList
+
+
+@pytest.fixture
+def lst():
+ return [1, 2, 3, 4, 5]
+
+
+@pytest.fixture
+def container(lst):
+ return FrozenList(lst)
+
+
+@pytest.fixture
+def unicode_container():
+ return FrozenList(["\u05d0", "\u05d1", "c"])
+
+
+class TestFrozenList:
+ def check_mutable_error(self, *args, **kwargs):
+ # Pass whatever function you normally would to pytest.raises
+ # (after the Exception kind).
+ mutable_regex = re.compile("does not support mutable operations")
+ msg = "'(_s)?re.(SRE_)?Pattern' object is not callable"
+ with pytest.raises(TypeError, match=msg):
+ mutable_regex(*args, **kwargs)
+
+ def test_no_mutable_funcs(self, container):
+ def setitem():
+ container[0] = 5
+
+ self.check_mutable_error(setitem)
+
+ def setslice():
+ container[1:2] = 3
+
+ self.check_mutable_error(setslice)
+
+ def delitem():
+ del container[0]
+
+ self.check_mutable_error(delitem)
+
+ def delslice():
+ del container[0:3]
+
+ self.check_mutable_error(delslice)
+
+ mutable_methods = ("extend", "pop", "remove", "insert")
+
+ for meth in mutable_methods:
+ self.check_mutable_error(getattr(container, meth))
+
+ def test_slicing_maintains_type(self, container, lst):
+ result = container[1:2]
+ expected = lst[1:2]
+ self.check_result(result, expected)
+
+ def check_result(self, result, expected):
+ assert isinstance(result, FrozenList)
+ assert result == expected
+
+ def test_string_methods_dont_fail(self, container):
+ repr(container)
+ str(container)
+ bytes(container)
+
+ def test_tricky_container(self, unicode_container):
+ repr(unicode_container)
+ str(unicode_container)
+
+ def test_add(self, container, lst):
+ result = container + (1, 2, 3)
+ expected = FrozenList(lst + [1, 2, 3])
+ self.check_result(result, expected)
+
+ result = (1, 2, 3) + container
+ expected = FrozenList([1, 2, 3] + lst)
+ self.check_result(result, expected)
+
+ def test_iadd(self, container, lst):
+ q = r = container
+
+ q += [5]
+ self.check_result(q, lst + [5])
+
+ # Other shouldn't be mutated.
+ self.check_result(r, lst)
+
+ def test_union(self, container, lst):
+ result = container.union((1, 2, 3))
+ expected = FrozenList(lst + [1, 2, 3])
+ self.check_result(result, expected)
+
+ def test_difference(self, container):
+ result = container.difference([2])
+ expected = FrozenList([1, 3, 4, 5])
+ self.check_result(result, expected)
+
+ def test_difference_dupe(self):
+ result = FrozenList([1, 2, 3, 2]).difference([2])
+ expected = FrozenList([1, 3])
+ self.check_result(result, expected)
+
+ def test_tricky_container_to_bytes_raises(self, unicode_container):
+ # GH 26447
+ msg = "^'str' object cannot be interpreted as an integer$"
+ with pytest.raises(TypeError, match=msg):
+ bytes(unicode_container)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_index_new.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_index_new.py
new file mode 100644
index 0000000000000000000000000000000000000000..d35c35661051a9f13c28f5bda031e9343fc1d388
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_index_new.py
@@ -0,0 +1,403 @@
+"""
+Tests for the Index constructor conducting inference.
+"""
+from datetime import (
+ datetime,
+ timedelta,
+)
+from decimal import Decimal
+
+import numpy as np
+import pytest
+
+from pandas import (
+ NA,
+ Categorical,
+ CategoricalIndex,
+ DatetimeIndex,
+ Index,
+ IntervalIndex,
+ MultiIndex,
+ NaT,
+ PeriodIndex,
+ Series,
+ TimedeltaIndex,
+ Timestamp,
+ array,
+ date_range,
+ period_range,
+ timedelta_range,
+)
+import pandas._testing as tm
+
+
+class TestIndexConstructorInference:
+ def test_object_all_bools(self):
+ # GH#49594 match Series behavior on ndarray[object] of all bools
+ arr = np.array([True, False], dtype=object)
+ res = Index(arr)
+ assert res.dtype == object
+
+ # since the point is matching Series behavior, let's double check
+ assert Series(arr).dtype == object
+
+ def test_object_all_complex(self):
+ # GH#49594 match Series behavior on ndarray[object] of all complex
+ arr = np.array([complex(1), complex(2)], dtype=object)
+ res = Index(arr)
+ assert res.dtype == object
+
+ # since the point is matching Series behavior, let's double check
+ assert Series(arr).dtype == object
+
+ @pytest.mark.parametrize("val", [NaT, None, np.nan, float("nan")])
+ def test_infer_nat(self, val):
+ # GH#49340 all NaT/None/nan and at least 1 NaT -> datetime64[ns],
+ # matching Series behavior
+ values = [NaT, val]
+
+ idx = Index(values)
+ assert idx.dtype == "datetime64[ns]" and idx.isna().all()
+
+ idx = Index(values[::-1])
+ assert idx.dtype == "datetime64[ns]" and idx.isna().all()
+
+ idx = Index(np.array(values, dtype=object))
+ assert idx.dtype == "datetime64[ns]" and idx.isna().all()
+
+ idx = Index(np.array(values, dtype=object)[::-1])
+ assert idx.dtype == "datetime64[ns]" and idx.isna().all()
+
+ @pytest.mark.parametrize("na_value", [None, np.nan])
+ @pytest.mark.parametrize("vtype", [list, tuple, iter])
+ def test_construction_list_tuples_nan(self, na_value, vtype):
+ # GH#18505 : valid tuples containing NaN
+ values = [(1, "two"), (3.0, na_value)]
+ result = Index(vtype(values))
+ expected = MultiIndex.from_tuples(values)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "dtype",
+ [int, "int64", "int32", "int16", "int8", "uint64", "uint32", "uint16", "uint8"],
+ )
+ def test_constructor_int_dtype_float(self, dtype):
+ # GH#18400
+ expected = Index([0, 1, 2, 3], dtype=dtype)
+ result = Index([0.0, 1.0, 2.0, 3.0], dtype=dtype)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("cast_index", [True, False])
+ @pytest.mark.parametrize(
+ "vals", [[True, False, True], np.array([True, False, True], dtype=bool)]
+ )
+ def test_constructor_dtypes_to_object(self, cast_index, vals):
+ if cast_index:
+ index = Index(vals, dtype=bool)
+ else:
+ index = Index(vals)
+
+ assert type(index) is Index
+ assert index.dtype == bool
+
+ def test_constructor_categorical_to_object(self):
+ # GH#32167 Categorical data and dtype=object should return object-dtype
+ ci = CategoricalIndex(range(5))
+ result = Index(ci, dtype=object)
+ assert not isinstance(result, CategoricalIndex)
+
+ def test_constructor_infer_periodindex(self):
+ xp = period_range("2012-1-1", freq="M", periods=3)
+ rs = Index(xp)
+ tm.assert_index_equal(rs, xp)
+ assert isinstance(rs, PeriodIndex)
+
+ def test_from_list_of_periods(self):
+ rng = period_range("1/1/2000", periods=20, freq="D")
+ periods = list(rng)
+
+ result = Index(periods)
+ assert isinstance(result, PeriodIndex)
+
+ @pytest.mark.parametrize("pos", [0, 1])
+ @pytest.mark.parametrize(
+ "klass,dtype,ctor",
+ [
+ (DatetimeIndex, "datetime64[ns]", np.datetime64("nat")),
+ (TimedeltaIndex, "timedelta64[ns]", np.timedelta64("nat")),
+ ],
+ )
+ def test_constructor_infer_nat_dt_like(
+ self, pos, klass, dtype, ctor, nulls_fixture, request
+ ):
+ if isinstance(nulls_fixture, Decimal):
+ # We dont cast these to datetime64/timedelta64
+ pytest.skip(
+ f"We don't cast {type(nulls_fixture).__name__} to "
+ "datetime64/timedelta64"
+ )
+
+ expected = klass([NaT, NaT])
+ assert expected.dtype == dtype
+ data = [ctor]
+ data.insert(pos, nulls_fixture)
+
+ warn = None
+ if nulls_fixture is NA:
+ expected = Index([NA, NaT])
+ mark = pytest.mark.xfail(reason="Broken with np.NaT ctor; see GH 31884")
+ request.node.add_marker(mark)
+ # GH#35942 numpy will emit a DeprecationWarning within the
+ # assert_index_equal calls. Since we can't do anything
+ # about it until GH#31884 is fixed, we suppress that warning.
+ warn = DeprecationWarning
+
+ result = Index(data)
+
+ with tm.assert_produces_warning(warn):
+ tm.assert_index_equal(result, expected)
+
+ result = Index(np.array(data, dtype=object))
+
+ with tm.assert_produces_warning(warn):
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("swap_objs", [True, False])
+ def test_constructor_mixed_nat_objs_infers_object(self, swap_objs):
+ # mixed np.datetime64/timedelta64 nat results in object
+ data = [np.datetime64("nat"), np.timedelta64("nat")]
+ if swap_objs:
+ data = data[::-1]
+
+ expected = Index(data, dtype=object)
+ tm.assert_index_equal(Index(data), expected)
+ tm.assert_index_equal(Index(np.array(data, dtype=object)), expected)
+
+ @pytest.mark.parametrize("swap_objs", [True, False])
+ def test_constructor_datetime_and_datetime64(self, swap_objs):
+ data = [Timestamp(2021, 6, 8, 9, 42), np.datetime64("now")]
+ if swap_objs:
+ data = data[::-1]
+ expected = DatetimeIndex(data)
+
+ tm.assert_index_equal(Index(data), expected)
+ tm.assert_index_equal(Index(np.array(data, dtype=object)), expected)
+
+
+class TestDtypeEnforced:
+ # check we don't silently ignore the dtype keyword
+
+ def test_constructor_object_dtype_with_ea_data(self, any_numeric_ea_dtype):
+ # GH#45206
+ arr = array([0], dtype=any_numeric_ea_dtype)
+
+ idx = Index(arr, dtype=object)
+ assert idx.dtype == object
+
+ @pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"])
+ def test_constructor_range_values_mismatched_dtype(self, dtype):
+ rng = Index(range(5))
+
+ result = Index(rng, dtype=dtype)
+ assert result.dtype == dtype
+
+ result = Index(range(5), dtype=dtype)
+ assert result.dtype == dtype
+
+ @pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"])
+ def test_constructor_categorical_values_mismatched_non_ea_dtype(self, dtype):
+ cat = Categorical([1, 2, 3])
+
+ result = Index(cat, dtype=dtype)
+ assert result.dtype == dtype
+
+ def test_constructor_categorical_values_mismatched_dtype(self):
+ dti = date_range("2016-01-01", periods=3)
+ cat = Categorical(dti)
+ result = Index(cat, dti.dtype)
+ tm.assert_index_equal(result, dti)
+
+ dti2 = dti.tz_localize("Asia/Tokyo")
+ cat2 = Categorical(dti2)
+ result = Index(cat2, dti2.dtype)
+ tm.assert_index_equal(result, dti2)
+
+ ii = IntervalIndex.from_breaks(range(5))
+ cat3 = Categorical(ii)
+ result = Index(cat3, dtype=ii.dtype)
+ tm.assert_index_equal(result, ii)
+
+ def test_constructor_ea_values_mismatched_categorical_dtype(self):
+ dti = date_range("2016-01-01", periods=3)
+ result = Index(dti, dtype="category")
+ expected = CategoricalIndex(dti)
+ tm.assert_index_equal(result, expected)
+
+ dti2 = date_range("2016-01-01", periods=3, tz="US/Pacific")
+ result = Index(dti2, dtype="category")
+ expected = CategoricalIndex(dti2)
+ tm.assert_index_equal(result, expected)
+
+ def test_constructor_period_values_mismatched_dtype(self):
+ pi = period_range("2016-01-01", periods=3, freq="D")
+ result = Index(pi, dtype="category")
+ expected = CategoricalIndex(pi)
+ tm.assert_index_equal(result, expected)
+
+ def test_constructor_timedelta64_values_mismatched_dtype(self):
+ # check we don't silently ignore the dtype keyword
+ tdi = timedelta_range("4 Days", periods=5)
+ result = Index(tdi, dtype="category")
+ expected = CategoricalIndex(tdi)
+ tm.assert_index_equal(result, expected)
+
+ def test_constructor_interval_values_mismatched_dtype(self):
+ dti = date_range("2016-01-01", periods=3)
+ ii = IntervalIndex.from_breaks(dti)
+ result = Index(ii, dtype="category")
+ expected = CategoricalIndex(ii)
+ tm.assert_index_equal(result, expected)
+
+ def test_constructor_datetime64_values_mismatched_period_dtype(self):
+ dti = date_range("2016-01-01", periods=3)
+ result = Index(dti, dtype="Period[D]")
+ expected = dti.to_period("D")
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["int64", "uint64"])
+ def test_constructor_int_dtype_nan_raises(self, dtype):
+ # see GH#15187
+ data = [np.nan]
+ msg = "cannot convert"
+ with pytest.raises(ValueError, match=msg):
+ Index(data, dtype=dtype)
+
+ @pytest.mark.parametrize(
+ "vals",
+ [
+ [1, 2, 3],
+ np.array([1, 2, 3]),
+ np.array([1, 2, 3], dtype=int),
+ # below should coerce
+ [1.0, 2.0, 3.0],
+ np.array([1.0, 2.0, 3.0], dtype=float),
+ ],
+ )
+ def test_constructor_dtypes_to_int(self, vals, any_int_numpy_dtype):
+ dtype = any_int_numpy_dtype
+ index = Index(vals, dtype=dtype)
+ assert index.dtype == dtype
+
+ @pytest.mark.parametrize(
+ "vals",
+ [
+ [1, 2, 3],
+ [1.0, 2.0, 3.0],
+ np.array([1.0, 2.0, 3.0]),
+ np.array([1, 2, 3], dtype=int),
+ np.array([1.0, 2.0, 3.0], dtype=float),
+ ],
+ )
+ def test_constructor_dtypes_to_float(self, vals, float_numpy_dtype):
+ dtype = float_numpy_dtype
+ index = Index(vals, dtype=dtype)
+ assert index.dtype == dtype
+
+ @pytest.mark.parametrize(
+ "vals",
+ [
+ [1, 2, 3],
+ np.array([1, 2, 3], dtype=int),
+ np.array(["2011-01-01", "2011-01-02"], dtype="datetime64[ns]"),
+ [datetime(2011, 1, 1), datetime(2011, 1, 2)],
+ ],
+ )
+ def test_constructor_dtypes_to_categorical(self, vals):
+ index = Index(vals, dtype="category")
+ assert isinstance(index, CategoricalIndex)
+
+ @pytest.mark.parametrize("cast_index", [True, False])
+ @pytest.mark.parametrize(
+ "vals",
+ [
+ Index(np.array([np.datetime64("2011-01-01"), np.datetime64("2011-01-02")])),
+ Index([datetime(2011, 1, 1), datetime(2011, 1, 2)]),
+ ],
+ )
+ def test_constructor_dtypes_to_datetime(self, cast_index, vals):
+ if cast_index:
+ index = Index(vals, dtype=object)
+ assert isinstance(index, Index)
+ assert index.dtype == object
+ else:
+ index = Index(vals)
+ assert isinstance(index, DatetimeIndex)
+
+ @pytest.mark.parametrize("cast_index", [True, False])
+ @pytest.mark.parametrize(
+ "vals",
+ [
+ np.array([np.timedelta64(1, "D"), np.timedelta64(1, "D")]),
+ [timedelta(1), timedelta(1)],
+ ],
+ )
+ def test_constructor_dtypes_to_timedelta(self, cast_index, vals):
+ if cast_index:
+ index = Index(vals, dtype=object)
+ assert isinstance(index, Index)
+ assert index.dtype == object
+ else:
+ index = Index(vals)
+ assert isinstance(index, TimedeltaIndex)
+
+
+class TestIndexConstructorUnwrapping:
+ # Test passing different arraylike values to pd.Index
+
+ @pytest.mark.parametrize("klass", [Index, DatetimeIndex])
+ def test_constructor_from_series_dt64(self, klass):
+ stamps = [Timestamp("20110101"), Timestamp("20120101"), Timestamp("20130101")]
+ expected = DatetimeIndex(stamps)
+ ser = Series(stamps)
+ result = klass(ser)
+ tm.assert_index_equal(result, expected)
+
+ def test_constructor_no_pandas_array(self):
+ ser = Series([1, 2, 3])
+ result = Index(ser.array)
+ expected = Index([1, 2, 3])
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "array",
+ [
+ np.arange(5),
+ np.array(["a", "b", "c"]),
+ date_range("2000-01-01", periods=3).values,
+ ],
+ )
+ def test_constructor_ndarray_like(self, array):
+ # GH#5460#issuecomment-44474502
+ # it should be possible to convert any object that satisfies the numpy
+ # ndarray interface directly into an Index
+ class ArrayLike:
+ def __init__(self, array) -> None:
+ self.array = array
+
+ def __array__(self, dtype=None) -> np.ndarray:
+ return self.array
+
+ expected = Index(array)
+ result = Index(ArrayLike(array))
+ tm.assert_index_equal(result, expected)
+
+
+class TestIndexConstructionErrors:
+ def test_constructor_overflow_int64(self):
+ # see GH#15832
+ msg = (
+ "The elements provided in the data cannot "
+ "all be casted to the dtype int64"
+ )
+ with pytest.raises(OverflowError, match=msg):
+ Index([np.iinfo(np.uint64).max - 1], dtype="int64")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_indexing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_indexing.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ea47f636ac9b64346b21496fe25d4fe109cd711
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_indexing.py
@@ -0,0 +1,357 @@
+"""
+test_indexing tests the following Index methods:
+ __getitem__
+ get_loc
+ get_value
+ __contains__
+ take
+ where
+ get_indexer
+ get_indexer_for
+ slice_locs
+ asof_locs
+
+The corresponding tests.indexes.[index_type].test_indexing files
+contain tests for the corresponding methods specific to those Index subclasses.
+"""
+import numpy as np
+import pytest
+
+from pandas.errors import InvalidIndexError
+
+from pandas.core.dtypes.common import (
+ is_float_dtype,
+ is_scalar,
+)
+
+from pandas import (
+ NA,
+ DatetimeIndex,
+ Index,
+ IntervalIndex,
+ MultiIndex,
+ NaT,
+ PeriodIndex,
+ TimedeltaIndex,
+)
+import pandas._testing as tm
+
+
+class TestTake:
+ def test_take_invalid_kwargs(self, index):
+ indices = [1, 2]
+
+ msg = r"take\(\) got an unexpected keyword argument 'foo'"
+ with pytest.raises(TypeError, match=msg):
+ index.take(indices, foo=2)
+
+ msg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ index.take(indices, out=indices)
+
+ msg = "the 'mode' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ index.take(indices, mode="clip")
+
+ def test_take(self, index):
+ indexer = [4, 3, 0, 2]
+ if len(index) < 5:
+ pytest.skip("Test doesn't make sense since not enough elements")
+
+ result = index.take(indexer)
+ expected = index[indexer]
+ assert result.equals(expected)
+
+ if not isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
+ # GH 10791
+ msg = r"'(.*Index)' object has no attribute 'freq'"
+ with pytest.raises(AttributeError, match=msg):
+ index.freq
+
+ def test_take_indexer_type(self):
+ # GH#42875
+ integer_index = Index([0, 1, 2, 3])
+ scalar_index = 1
+ msg = "Expected indices to be array-like"
+ with pytest.raises(TypeError, match=msg):
+ integer_index.take(scalar_index)
+
+ def test_take_minus1_without_fill(self, index):
+ # -1 does not get treated as NA unless allow_fill=True is passed
+ if len(index) == 0:
+ # Test is not applicable
+ pytest.skip("Test doesn't make sense for empty index")
+
+ result = index.take([0, 0, -1])
+
+ expected = index.take([0, 0, len(index) - 1])
+ tm.assert_index_equal(result, expected)
+
+
+class TestContains:
+ @pytest.mark.parametrize(
+ "index,val",
+ [
+ (Index([0, 1, 2]), 2),
+ (Index([0, 1, "2"]), "2"),
+ (Index([0, 1, 2, np.inf, 4]), 4),
+ (Index([0, 1, 2, np.nan, 4]), 4),
+ (Index([0, 1, 2, np.inf]), np.inf),
+ (Index([0, 1, 2, np.nan]), np.nan),
+ ],
+ )
+ def test_index_contains(self, index, val):
+ assert val in index
+
+ @pytest.mark.parametrize(
+ "index,val",
+ [
+ (Index([0, 1, 2]), "2"),
+ (Index([0, 1, "2"]), 2),
+ (Index([0, 1, 2, np.inf]), 4),
+ (Index([0, 1, 2, np.nan]), 4),
+ (Index([0, 1, 2, np.inf]), np.nan),
+ (Index([0, 1, 2, np.nan]), np.inf),
+ # Checking if np.inf in int64 Index should not cause an OverflowError
+ # Related to GH 16957
+ (Index([0, 1, 2], dtype=np.int64), np.inf),
+ (Index([0, 1, 2], dtype=np.int64), np.nan),
+ (Index([0, 1, 2], dtype=np.uint64), np.inf),
+ (Index([0, 1, 2], dtype=np.uint64), np.nan),
+ ],
+ )
+ def test_index_not_contains(self, index, val):
+ assert val not in index
+
+ @pytest.mark.parametrize(
+ "index,val", [(Index([0, 1, "2"]), 0), (Index([0, 1, "2"]), "2")]
+ )
+ def test_mixed_index_contains(self, index, val):
+ # GH#19860
+ assert val in index
+
+ @pytest.mark.parametrize(
+ "index,val", [(Index([0, 1, "2"]), "1"), (Index([0, 1, "2"]), 2)]
+ )
+ def test_mixed_index_not_contains(self, index, val):
+ # GH#19860
+ assert val not in index
+
+ def test_contains_with_float_index(self, any_real_numpy_dtype):
+ # GH#22085
+ dtype = any_real_numpy_dtype
+ data = [0, 1, 2, 3] if not is_float_dtype(dtype) else [0.1, 1.1, 2.2, 3.3]
+ index = Index(data, dtype=dtype)
+
+ if not is_float_dtype(index.dtype):
+ assert 1.1 not in index
+ assert 1.0 in index
+ assert 1 in index
+ else:
+ assert 1.1 in index
+ assert 1.0 not in index
+ assert 1 not in index
+
+ def test_contains_requires_hashable_raises(self, index):
+ if isinstance(index, MultiIndex):
+ return # TODO: do we want this to raise?
+
+ msg = "unhashable type: 'list'"
+ with pytest.raises(TypeError, match=msg):
+ [] in index
+
+ msg = "|".join(
+ [
+ r"unhashable type: 'dict'",
+ r"must be real number, not dict",
+ r"an integer is required",
+ r"\{\}",
+ r"pandas\._libs\.interval\.IntervalTree' is not iterable",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ {} in index._engine
+
+
+class TestGetLoc:
+ def test_get_loc_non_hashable(self, index):
+ with pytest.raises(InvalidIndexError, match="[0, 1]"):
+ index.get_loc([0, 1])
+
+ def test_get_loc_non_scalar_hashable(self, index):
+ # GH52877
+ from enum import Enum
+
+ class E(Enum):
+ X1 = "x1"
+
+ assert not is_scalar(E.X1)
+
+ exc = KeyError
+ msg = ""
+ if isinstance(
+ index,
+ (
+ DatetimeIndex,
+ TimedeltaIndex,
+ PeriodIndex,
+ IntervalIndex,
+ ),
+ ):
+ # TODO: make these more consistent?
+ exc = InvalidIndexError
+ msg = "E.X1"
+ with pytest.raises(exc, match=msg):
+ index.get_loc(E.X1)
+
+ def test_get_loc_generator(self, index):
+ exc = KeyError
+ if isinstance(
+ index,
+ (
+ DatetimeIndex,
+ TimedeltaIndex,
+ PeriodIndex,
+ IntervalIndex,
+ MultiIndex,
+ ),
+ ):
+ # TODO: make these more consistent?
+ exc = InvalidIndexError
+ with pytest.raises(exc, match="generator object"):
+ # MultiIndex specifically checks for generator; others for scalar
+ index.get_loc(x for x in range(5))
+
+ def test_get_loc_masked_duplicated_na(self):
+ # GH#48411
+ idx = Index([1, 2, NA, NA], dtype="Int64")
+ result = idx.get_loc(NA)
+ expected = np.array([False, False, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+
+class TestGetIndexer:
+ def test_get_indexer_base(self, index):
+ if index._index_as_unique:
+ expected = np.arange(index.size, dtype=np.intp)
+ actual = index.get_indexer(index)
+ tm.assert_numpy_array_equal(expected, actual)
+ else:
+ msg = "Reindexing only valid with uniquely valued Index objects"
+ with pytest.raises(InvalidIndexError, match=msg):
+ index.get_indexer(index)
+
+ with pytest.raises(ValueError, match="Invalid fill method"):
+ index.get_indexer(index, method="invalid")
+
+ def test_get_indexer_consistency(self, index):
+ # See GH#16819
+
+ if index._index_as_unique:
+ indexer = index.get_indexer(index[0:2])
+ assert isinstance(indexer, np.ndarray)
+ assert indexer.dtype == np.intp
+ else:
+ msg = "Reindexing only valid with uniquely valued Index objects"
+ with pytest.raises(InvalidIndexError, match=msg):
+ index.get_indexer(index[0:2])
+
+ indexer, _ = index.get_indexer_non_unique(index[0:2])
+ assert isinstance(indexer, np.ndarray)
+ assert indexer.dtype == np.intp
+
+ def test_get_indexer_masked_duplicated_na(self):
+ # GH#48411
+ idx = Index([1, 2, NA, NA], dtype="Int64")
+ result = idx.get_indexer_for(Index([1, NA], dtype="Int64"))
+ expected = np.array([0, 2, 3], dtype=result.dtype)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+class TestConvertSliceIndexer:
+ def test_convert_almost_null_slice(self, index):
+ # slice with None at both ends, but not step
+
+ key = slice(None, None, "foo")
+
+ if isinstance(index, IntervalIndex):
+ msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
+ with pytest.raises(ValueError, match=msg):
+ index._convert_slice_indexer(key, "loc")
+ else:
+ msg = "'>=' not supported between instances of 'str' and 'int'"
+ with pytest.raises(TypeError, match=msg):
+ index._convert_slice_indexer(key, "loc")
+
+
+class TestPutmask:
+ def test_putmask_with_wrong_mask(self, index):
+ # GH#18368
+ if not len(index):
+ pytest.skip("Test doesn't make sense for empty index")
+
+ fill = index[0]
+
+ msg = "putmask: mask and data must be the same size"
+ with pytest.raises(ValueError, match=msg):
+ index.putmask(np.ones(len(index) + 1, np.bool_), fill)
+
+ with pytest.raises(ValueError, match=msg):
+ index.putmask(np.ones(len(index) - 1, np.bool_), fill)
+
+ with pytest.raises(ValueError, match=msg):
+ index.putmask("foo", fill)
+
+
+@pytest.mark.parametrize(
+ "idx", [Index([1, 2, 3]), Index([0.1, 0.2, 0.3]), Index(["a", "b", "c"])]
+)
+def test_getitem_deprecated_float(idx):
+ # https://github.com/pandas-dev/pandas/issues/34191
+
+ msg = "Indexing with a float is no longer supported"
+ with pytest.raises(IndexError, match=msg):
+ idx[1.0]
+
+
+@pytest.mark.parametrize(
+ "idx,target,expected",
+ [
+ ([np.nan, "var1", np.nan], [np.nan], np.array([0, 2], dtype=np.intp)),
+ (
+ [np.nan, "var1", np.nan],
+ [np.nan, "var1"],
+ np.array([0, 2, 1], dtype=np.intp),
+ ),
+ (
+ np.array([np.nan, "var1", np.nan], dtype=object),
+ [np.nan],
+ np.array([0, 2], dtype=np.intp),
+ ),
+ (
+ DatetimeIndex(["2020-08-05", NaT, NaT]),
+ [NaT],
+ np.array([1, 2], dtype=np.intp),
+ ),
+ (["a", "b", "a", np.nan], [np.nan], np.array([3], dtype=np.intp)),
+ (
+ np.array(["b", np.nan, float("NaN"), "b"], dtype=object),
+ Index([np.nan], dtype=object),
+ np.array([1, 2], dtype=np.intp),
+ ),
+ ],
+)
+def test_get_indexer_non_unique_multiple_nans(idx, target, expected):
+ # GH 35392
+ axis = Index(idx)
+ actual = axis.get_indexer_for(target)
+ tm.assert_numpy_array_equal(actual, expected)
+
+
+def test_get_indexer_non_unique_nans_in_object_dtype_target(nulls_fixture):
+ idx = Index([1.0, 2.0])
+ target = Index([1, nulls_fixture], dtype="object")
+
+ result_idx, result_missing = idx.get_indexer_non_unique(target)
+ tm.assert_numpy_array_equal(result_idx, np.array([0, -1], dtype=np.intp))
+ tm.assert_numpy_array_equal(result_missing, np.array([1], dtype=np.intp))
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_numpy_compat.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_numpy_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..ace78d77350cbdc4ca3aa837720767a965443051
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_numpy_compat.py
@@ -0,0 +1,189 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ CategoricalIndex,
+ DatetimeIndex,
+ Index,
+ PeriodIndex,
+ TimedeltaIndex,
+ isna,
+)
+import pandas._testing as tm
+from pandas.api.types import (
+ is_complex_dtype,
+ is_numeric_dtype,
+)
+from pandas.core.arrays import BooleanArray
+from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin
+
+
+def test_numpy_ufuncs_out(index):
+ result = index == index
+
+ out = np.empty(index.shape, dtype=bool)
+ np.equal(index, index, out=out)
+ tm.assert_numpy_array_equal(out, result)
+
+ if not index._is_multi:
+ # same thing on the ExtensionArray
+ out = np.empty(index.shape, dtype=bool)
+ np.equal(index.array, index.array, out=out)
+ tm.assert_numpy_array_equal(out, result)
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ np.exp,
+ np.exp2,
+ np.expm1,
+ np.log,
+ np.log2,
+ np.log10,
+ np.log1p,
+ np.sqrt,
+ np.sin,
+ np.cos,
+ np.tan,
+ np.arcsin,
+ np.arccos,
+ np.arctan,
+ np.sinh,
+ np.cosh,
+ np.tanh,
+ np.arcsinh,
+ np.arccosh,
+ np.arctanh,
+ np.deg2rad,
+ np.rad2deg,
+ ],
+ ids=lambda x: x.__name__,
+)
+def test_numpy_ufuncs_basic(index, func):
+ # test ufuncs of numpy, see:
+ # https://numpy.org/doc/stable/reference/ufuncs.html
+
+ if isinstance(index, DatetimeIndexOpsMixin):
+ with tm.external_error_raised((TypeError, AttributeError)):
+ with np.errstate(all="ignore"):
+ func(index)
+ elif is_numeric_dtype(index) and not (
+ is_complex_dtype(index) and func in [np.deg2rad, np.rad2deg]
+ ):
+ # coerces to float (e.g. np.sin)
+ with np.errstate(all="ignore"):
+ result = func(index)
+ arr_result = func(index.values)
+ if arr_result.dtype == np.float16:
+ arr_result = arr_result.astype(np.float32)
+ exp = Index(arr_result, name=index.name)
+
+ tm.assert_index_equal(result, exp)
+ if isinstance(index.dtype, np.dtype) and is_numeric_dtype(index):
+ if is_complex_dtype(index):
+ assert result.dtype == index.dtype
+ elif index.dtype in ["bool", "int8", "uint8"]:
+ assert result.dtype in ["float16", "float32"]
+ elif index.dtype in ["int16", "uint16", "float32"]:
+ assert result.dtype == "float32"
+ else:
+ assert result.dtype == "float64"
+ else:
+ # e.g. np.exp with Int64 -> Float64
+ assert type(result) is Index
+ # raise AttributeError or TypeError
+ elif len(index) == 0:
+ pass
+ else:
+ with tm.external_error_raised((TypeError, AttributeError)):
+ with np.errstate(all="ignore"):
+ func(index)
+
+
+@pytest.mark.parametrize(
+ "func", [np.isfinite, np.isinf, np.isnan, np.signbit], ids=lambda x: x.__name__
+)
+def test_numpy_ufuncs_other(index, func):
+ # test ufuncs of numpy, see:
+ # https://numpy.org/doc/stable/reference/ufuncs.html
+ if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
+ if func in (np.isfinite, np.isinf, np.isnan):
+ # numpy 1.18 changed isinf and isnan to not raise on dt64/td64
+ result = func(index)
+ assert isinstance(result, np.ndarray)
+
+ out = np.empty(index.shape, dtype=bool)
+ func(index, out=out)
+ tm.assert_numpy_array_equal(out, result)
+ else:
+ with tm.external_error_raised(TypeError):
+ func(index)
+
+ elif isinstance(index, PeriodIndex):
+ with tm.external_error_raised(TypeError):
+ func(index)
+
+ elif is_numeric_dtype(index) and not (
+ is_complex_dtype(index) and func is np.signbit
+ ):
+ # Results in bool array
+ result = func(index)
+ if not isinstance(index.dtype, np.dtype):
+ # e.g. Int64 we expect to get BooleanArray back
+ assert isinstance(result, BooleanArray)
+ else:
+ assert isinstance(result, np.ndarray)
+
+ out = np.empty(index.shape, dtype=bool)
+ func(index, out=out)
+
+ if not isinstance(index.dtype, np.dtype):
+ tm.assert_numpy_array_equal(out, result._data)
+ else:
+ tm.assert_numpy_array_equal(out, result)
+
+ elif len(index) == 0:
+ pass
+ else:
+ with tm.external_error_raised(TypeError):
+ func(index)
+
+
+@pytest.mark.parametrize("func", [np.maximum, np.minimum])
+def test_numpy_ufuncs_reductions(index, func, request):
+ # TODO: overlap with tests.series.test_ufunc.test_reductions
+ if len(index) == 0:
+ pytest.skip("Test doesn't make sense for empty index.")
+
+ if isinstance(index, CategoricalIndex) and index.dtype.ordered is False:
+ with pytest.raises(TypeError, match="is not ordered for"):
+ func.reduce(index)
+ return
+ else:
+ result = func.reduce(index)
+
+ if func is np.maximum:
+ expected = index.max(skipna=False)
+ else:
+ expected = index.min(skipna=False)
+ # TODO: do we have cases both with and without NAs?
+
+ assert type(result) is type(expected)
+ if isna(result):
+ assert isna(expected)
+ else:
+ assert result == expected
+
+
+@pytest.mark.parametrize("func", [np.bitwise_and, np.bitwise_or, np.bitwise_xor])
+def test_numpy_ufuncs_bitwise(func):
+ # https://github.com/pandas-dev/pandas/issues/46769
+ idx1 = Index([1, 2, 3, 4], dtype="int64")
+ idx2 = Index([3, 4, 5, 6], dtype="int64")
+
+ with tm.assert_produces_warning(None):
+ result = func(idx1, idx2)
+
+ expected = Index(func(idx1.values, idx2.values))
+ tm.assert_index_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_old_base.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_old_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..79dc423f12a85b93a5f91df6fe5d8269800b06fa
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_old_base.py
@@ -0,0 +1,1025 @@
+from __future__ import annotations
+
+from datetime import datetime
+import gc
+
+import numpy as np
+import pytest
+
+from pandas._libs.tslibs import Timestamp
+
+from pandas.core.dtypes.common import (
+ is_integer_dtype,
+ is_numeric_dtype,
+)
+from pandas.core.dtypes.dtypes import CategoricalDtype
+
+import pandas as pd
+from pandas import (
+ CategoricalIndex,
+ DatetimeIndex,
+ DatetimeTZDtype,
+ Index,
+ IntervalIndex,
+ MultiIndex,
+ PeriodIndex,
+ RangeIndex,
+ Series,
+ TimedeltaIndex,
+ isna,
+ period_range,
+)
+import pandas._testing as tm
+from pandas.core.arrays import BaseMaskedArray
+
+
+class TestBase:
+ @pytest.fixture(
+ params=[
+ RangeIndex(start=0, stop=20, step=2),
+ Index(np.arange(5, dtype=np.float64)),
+ Index(np.arange(5, dtype=np.float32)),
+ Index(np.arange(5, dtype=np.uint64)),
+ Index(range(0, 20, 2), dtype=np.int64),
+ Index(range(0, 20, 2), dtype=np.int32),
+ Index(range(0, 20, 2), dtype=np.int16),
+ Index(range(0, 20, 2), dtype=np.int8),
+ Index(list("abcde")),
+ Index([0, "a", 1, "b", 2, "c"]),
+ period_range("20130101", periods=5, freq="D"),
+ TimedeltaIndex(
+ [
+ "0 days 01:00:00",
+ "1 days 01:00:00",
+ "2 days 01:00:00",
+ "3 days 01:00:00",
+ "4 days 01:00:00",
+ ],
+ dtype="timedelta64[ns]",
+ freq="D",
+ ),
+ DatetimeIndex(
+ ["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"],
+ dtype="datetime64[ns]",
+ freq="D",
+ ),
+ IntervalIndex.from_breaks(range(11), closed="right"),
+ ]
+ )
+ def simple_index(self, request):
+ return request.param
+
+ def test_pickle_compat_construction(self, simple_index):
+ # need an object to create with
+ if isinstance(simple_index, RangeIndex):
+ pytest.skip("RangeIndex() is a valid constructor")
+ msg = "|".join(
+ [
+ r"Index\(\.\.\.\) must be called with a collection of some "
+ r"kind, None was passed",
+ r"DatetimeIndex\(\) must be called with a collection of some "
+ r"kind, None was passed",
+ r"TimedeltaIndex\(\) must be called with a collection of some "
+ r"kind, None was passed",
+ r"__new__\(\) missing 1 required positional argument: 'data'",
+ r"__new__\(\) takes at least 2 arguments \(1 given\)",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ type(simple_index)()
+
+ def test_shift(self, simple_index):
+ # GH8083 test the base class for shift
+ if isinstance(simple_index, (DatetimeIndex, TimedeltaIndex, PeriodIndex)):
+ pytest.skip("Tested in test_ops/test_arithmetic")
+ idx = simple_index
+ msg = (
+ f"This method is only implemented for DatetimeIndex, PeriodIndex and "
+ f"TimedeltaIndex; Got type {type(idx).__name__}"
+ )
+ with pytest.raises(NotImplementedError, match=msg):
+ idx.shift(1)
+ with pytest.raises(NotImplementedError, match=msg):
+ idx.shift(1, 2)
+
+ def test_constructor_name_unhashable(self, simple_index):
+ # GH#29069 check that name is hashable
+ # See also same-named test in tests.series.test_constructors
+ idx = simple_index
+ with pytest.raises(TypeError, match="Index.name must be a hashable type"):
+ type(idx)(idx, name=[])
+
+ def test_create_index_existing_name(self, simple_index):
+ # GH11193, when an existing index is passed, and a new name is not
+ # specified, the new index should inherit the previous object name
+ expected = simple_index.copy()
+ if not isinstance(expected, MultiIndex):
+ expected.name = "foo"
+ result = Index(expected)
+ tm.assert_index_equal(result, expected)
+
+ result = Index(expected, name="bar")
+ expected.name = "bar"
+ tm.assert_index_equal(result, expected)
+ else:
+ expected.names = ["foo", "bar"]
+ result = Index(expected)
+ tm.assert_index_equal(
+ result,
+ Index(
+ Index(
+ [
+ ("foo", "one"),
+ ("foo", "two"),
+ ("bar", "one"),
+ ("baz", "two"),
+ ("qux", "one"),
+ ("qux", "two"),
+ ],
+ dtype="object",
+ ),
+ names=["foo", "bar"],
+ ),
+ )
+
+ result = Index(expected, names=["A", "B"])
+ tm.assert_index_equal(
+ result,
+ Index(
+ Index(
+ [
+ ("foo", "one"),
+ ("foo", "two"),
+ ("bar", "one"),
+ ("baz", "two"),
+ ("qux", "one"),
+ ("qux", "two"),
+ ],
+ dtype="object",
+ ),
+ names=["A", "B"],
+ ),
+ )
+
+ def test_numeric_compat(self, simple_index):
+ idx = simple_index
+ # Check that this doesn't cover MultiIndex case, if/when it does,
+ # we can remove multi.test_compat.test_numeric_compat
+ assert not isinstance(idx, MultiIndex)
+ if type(idx) is Index:
+ pytest.skip("Not applicable for Index")
+ if is_numeric_dtype(simple_index.dtype) or isinstance(
+ simple_index, TimedeltaIndex
+ ):
+ pytest.skip("Tested elsewhere.")
+
+ typ = type(idx._data).__name__
+ cls = type(idx).__name__
+ lmsg = "|".join(
+ [
+ rf"unsupported operand type\(s\) for \*: '{typ}' and 'int'",
+ "cannot perform (__mul__|__truediv__|__floordiv__) with "
+ f"this index type: ({cls}|{typ})",
+ ]
+ )
+ with pytest.raises(TypeError, match=lmsg):
+ idx * 1
+ rmsg = "|".join(
+ [
+ rf"unsupported operand type\(s\) for \*: 'int' and '{typ}'",
+ "cannot perform (__rmul__|__rtruediv__|__rfloordiv__) with "
+ f"this index type: ({cls}|{typ})",
+ ]
+ )
+ with pytest.raises(TypeError, match=rmsg):
+ 1 * idx
+
+ div_err = lmsg.replace("*", "/")
+ with pytest.raises(TypeError, match=div_err):
+ idx / 1
+ div_err = rmsg.replace("*", "/")
+ with pytest.raises(TypeError, match=div_err):
+ 1 / idx
+
+ floordiv_err = lmsg.replace("*", "//")
+ with pytest.raises(TypeError, match=floordiv_err):
+ idx // 1
+ floordiv_err = rmsg.replace("*", "//")
+ with pytest.raises(TypeError, match=floordiv_err):
+ 1 // idx
+
+ def test_logical_compat(self, simple_index):
+ if simple_index.dtype == object:
+ pytest.skip("Tested elsewhere.")
+ idx = simple_index
+ if idx.dtype.kind in "iufcbm":
+ assert idx.all() == idx._values.all()
+ assert idx.all() == idx.to_series().all()
+ assert idx.any() == idx._values.any()
+ assert idx.any() == idx.to_series().any()
+ else:
+ msg = "cannot perform (any|all)"
+ if isinstance(idx, IntervalIndex):
+ msg = (
+ r"'IntervalArray' with dtype interval\[.*\] does "
+ "not support reduction '(any|all)'"
+ )
+ with pytest.raises(TypeError, match=msg):
+ idx.all()
+ with pytest.raises(TypeError, match=msg):
+ idx.any()
+
+ def test_repr_roundtrip(self, simple_index):
+ if isinstance(simple_index, IntervalIndex):
+ pytest.skip(f"Not a valid repr for {type(simple_index).__name__}")
+ idx = simple_index
+ tm.assert_index_equal(eval(repr(idx)), idx)
+
+ def test_repr_max_seq_item_setting(self, simple_index):
+ # GH10182
+ if isinstance(simple_index, IntervalIndex):
+ pytest.skip(f"Not a valid repr for {type(simple_index).__name__}")
+ idx = simple_index
+ idx = idx.repeat(50)
+ with pd.option_context("display.max_seq_items", None):
+ repr(idx)
+ assert "..." not in str(idx)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_ensure_copied_data(self, index):
+ # Check the "copy" argument of each Index.__new__ is honoured
+ # GH12309
+ init_kwargs = {}
+ if isinstance(index, PeriodIndex):
+ # Needs "freq" specification:
+ init_kwargs["freq"] = index.freq
+ elif isinstance(index, (RangeIndex, MultiIndex, CategoricalIndex)):
+ pytest.skip(
+ "RangeIndex cannot be initialized from data, "
+ "MultiIndex and CategoricalIndex are tested separately"
+ )
+ elif index.dtype == object and index.inferred_type == "boolean":
+ init_kwargs["dtype"] = index.dtype
+
+ index_type = type(index)
+ result = index_type(index.values, copy=True, **init_kwargs)
+ if isinstance(index.dtype, DatetimeTZDtype):
+ result = result.tz_localize("UTC").tz_convert(index.tz)
+ if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
+ index = index._with_freq(None)
+
+ tm.assert_index_equal(index, result)
+
+ if isinstance(index, PeriodIndex):
+ # .values an object array of Period, thus copied
+ result = index_type(ordinal=index.asi8, copy=False, **init_kwargs)
+ tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same")
+ elif isinstance(index, IntervalIndex):
+ # checked in test_interval.py
+ pass
+ elif type(index) is Index and not isinstance(index.dtype, np.dtype):
+ result = index_type(index.values, copy=False, **init_kwargs)
+ tm.assert_index_equal(result, index)
+
+ if isinstance(index._values, BaseMaskedArray):
+ assert np.shares_memory(index._values._data, result._values._data)
+ tm.assert_numpy_array_equal(
+ index._values._data, result._values._data, check_same="same"
+ )
+ assert np.shares_memory(index._values._mask, result._values._mask)
+ tm.assert_numpy_array_equal(
+ index._values._mask, result._values._mask, check_same="same"
+ )
+ elif index.dtype == "string[python]":
+ assert np.shares_memory(index._values._ndarray, result._values._ndarray)
+ tm.assert_numpy_array_equal(
+ index._values._ndarray, result._values._ndarray, check_same="same"
+ )
+ elif index.dtype == "string[pyarrow]":
+ assert tm.shares_memory(result._values, index._values)
+ else:
+ raise NotImplementedError(index.dtype)
+ else:
+ result = index_type(index.values, copy=False, **init_kwargs)
+ tm.assert_numpy_array_equal(index.values, result.values, check_same="same")
+
+ def test_memory_usage(self, index):
+ index._engine.clear_mapping()
+ result = index.memory_usage()
+ if index.empty:
+ # we report 0 for no-length
+ assert result == 0
+ return
+
+ # non-zero length
+ index.get_loc(index[0])
+ result2 = index.memory_usage()
+ result3 = index.memory_usage(deep=True)
+
+ # RangeIndex, IntervalIndex
+ # don't have engines
+ # Index[EA] has engine but it does not have a Hashtable .mapping
+ if not isinstance(index, (RangeIndex, IntervalIndex)) and not (
+ type(index) is Index and not isinstance(index.dtype, np.dtype)
+ ):
+ assert result2 > result
+
+ if index.inferred_type == "object":
+ assert result3 > result2
+
+ def test_argsort(self, index):
+ if isinstance(index, CategoricalIndex):
+ pytest.skip(f"{type(self).__name__} separately tested")
+
+ result = index.argsort()
+ expected = np.array(index).argsort()
+ tm.assert_numpy_array_equal(result, expected, check_dtype=False)
+
+ def test_numpy_argsort(self, index):
+ result = np.argsort(index)
+ expected = index.argsort()
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.argsort(index, kind="mergesort")
+ expected = index.argsort(kind="mergesort")
+ tm.assert_numpy_array_equal(result, expected)
+
+ # these are the only two types that perform
+ # pandas compatibility input validation - the
+ # rest already perform separate (or no) such
+ # validation via their 'values' attribute as
+ # defined in pandas.core.indexes/base.py - they
+ # cannot be changed at the moment due to
+ # backwards compatibility concerns
+ if isinstance(index, (CategoricalIndex, RangeIndex)):
+ msg = "the 'axis' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ np.argsort(index, axis=1)
+
+ msg = "the 'order' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ np.argsort(index, order=("a", "b"))
+
+ def test_repeat(self, simple_index):
+ rep = 2
+ idx = simple_index.copy()
+ new_index_cls = idx._constructor
+ expected = new_index_cls(idx.values.repeat(rep), name=idx.name)
+ tm.assert_index_equal(idx.repeat(rep), expected)
+
+ idx = simple_index
+ rep = np.arange(len(idx))
+ expected = new_index_cls(idx.values.repeat(rep), name=idx.name)
+ tm.assert_index_equal(idx.repeat(rep), expected)
+
+ def test_numpy_repeat(self, simple_index):
+ rep = 2
+ idx = simple_index
+ expected = idx.repeat(rep)
+ tm.assert_index_equal(np.repeat(idx, rep), expected)
+
+ msg = "the 'axis' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ np.repeat(idx, rep, axis=0)
+
+ def test_where(self, listlike_box, simple_index):
+ if isinstance(simple_index, (IntervalIndex, PeriodIndex)) or is_numeric_dtype(
+ simple_index.dtype
+ ):
+ pytest.skip("Tested elsewhere.")
+ klass = listlike_box
+
+ idx = simple_index
+ if isinstance(idx, (DatetimeIndex, TimedeltaIndex)):
+ # where does not preserve freq
+ idx = idx._with_freq(None)
+
+ cond = [True] * len(idx)
+ result = idx.where(klass(cond))
+ expected = idx
+ tm.assert_index_equal(result, expected)
+
+ cond = [False] + [True] * len(idx[1:])
+ expected = Index([idx._na_value] + idx[1:].tolist(), dtype=idx.dtype)
+ result = idx.where(klass(cond))
+ tm.assert_index_equal(result, expected)
+
+ def test_insert_base(self, index):
+ result = index[1:4]
+
+ if not len(index):
+ pytest.skip("Not applicable for empty index")
+
+ # test 0th element
+ assert index[0:4].equals(result.insert(0, index[0]))
+
+ def test_insert_out_of_bounds(self, index):
+ # TypeError/IndexError matches what np.insert raises in these cases
+
+ if len(index) > 0:
+ err = TypeError
+ else:
+ err = IndexError
+ if len(index) == 0:
+ # 0 vs 0.5 in error message varies with numpy version
+ msg = "index (0|0.5) is out of bounds for axis 0 with size 0"
+ else:
+ msg = "slice indices must be integers or None or have an __index__ method"
+ with pytest.raises(err, match=msg):
+ index.insert(0.5, "foo")
+
+ msg = "|".join(
+ [
+ r"index -?\d+ is out of bounds for axis 0 with size \d+",
+ "loc must be an integer between",
+ ]
+ )
+ with pytest.raises(IndexError, match=msg):
+ index.insert(len(index) + 1, 1)
+
+ with pytest.raises(IndexError, match=msg):
+ index.insert(-len(index) - 1, 1)
+
+ def test_delete_base(self, index):
+ if not len(index):
+ pytest.skip("Not applicable for empty index")
+
+ if isinstance(index, RangeIndex):
+ # tested in class
+ pytest.skip(f"{type(self).__name__} tested elsewhere")
+
+ expected = index[1:]
+ result = index.delete(0)
+ assert result.equals(expected)
+ assert result.name == expected.name
+
+ expected = index[:-1]
+ result = index.delete(-1)
+ assert result.equals(expected)
+ assert result.name == expected.name
+
+ length = len(index)
+ msg = f"index {length} is out of bounds for axis 0 with size {length}"
+ with pytest.raises(IndexError, match=msg):
+ index.delete(length)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_equals(self, index):
+ if isinstance(index, IntervalIndex):
+ pytest.skip(f"{type(index).__name__} tested elsewhere")
+
+ is_ea_idx = type(index) is Index and not isinstance(index.dtype, np.dtype)
+
+ assert index.equals(index)
+ assert index.equals(index.copy())
+ if not is_ea_idx:
+ # doesn't hold for e.g. IntegerDtype
+ assert index.equals(index.astype(object))
+
+ assert not index.equals(list(index))
+ assert not index.equals(np.array(index))
+
+ # Cannot pass in non-int64 dtype to RangeIndex
+ if not isinstance(index, RangeIndex) and not is_ea_idx:
+ same_values = Index(index, dtype=object)
+ assert index.equals(same_values)
+ assert same_values.equals(index)
+
+ if index.nlevels == 1:
+ # do not test MultiIndex
+ assert not index.equals(Series(index))
+
+ def test_equals_op(self, simple_index):
+ # GH9947, GH10637
+ index_a = simple_index
+
+ n = len(index_a)
+ index_b = index_a[0:-1]
+ index_c = index_a[0:-1].append(index_a[-2:-1])
+ index_d = index_a[0:1]
+
+ msg = "Lengths must match|could not be broadcast"
+ with pytest.raises(ValueError, match=msg):
+ index_a == index_b
+ expected1 = np.array([True] * n)
+ expected2 = np.array([True] * (n - 1) + [False])
+ tm.assert_numpy_array_equal(index_a == index_a, expected1)
+ tm.assert_numpy_array_equal(index_a == index_c, expected2)
+
+ # test comparisons with numpy arrays
+ array_a = np.array(index_a)
+ array_b = np.array(index_a[0:-1])
+ array_c = np.array(index_a[0:-1].append(index_a[-2:-1]))
+ array_d = np.array(index_a[0:1])
+ with pytest.raises(ValueError, match=msg):
+ index_a == array_b
+ tm.assert_numpy_array_equal(index_a == array_a, expected1)
+ tm.assert_numpy_array_equal(index_a == array_c, expected2)
+
+ # test comparisons with Series
+ series_a = Series(array_a)
+ series_b = Series(array_b)
+ series_c = Series(array_c)
+ series_d = Series(array_d)
+ with pytest.raises(ValueError, match=msg):
+ index_a == series_b
+
+ tm.assert_numpy_array_equal(index_a == series_a, expected1)
+ tm.assert_numpy_array_equal(index_a == series_c, expected2)
+
+ # cases where length is 1 for one of them
+ with pytest.raises(ValueError, match="Lengths must match"):
+ index_a == index_d
+ with pytest.raises(ValueError, match="Lengths must match"):
+ index_a == series_d
+ with pytest.raises(ValueError, match="Lengths must match"):
+ index_a == array_d
+ msg = "Can only compare identically-labeled Series objects"
+ with pytest.raises(ValueError, match=msg):
+ series_a == series_d
+ with pytest.raises(ValueError, match="Lengths must match"):
+ series_a == array_d
+
+ # comparing with a scalar should broadcast; note that we are excluding
+ # MultiIndex because in this case each item in the index is a tuple of
+ # length 2, and therefore is considered an array of length 2 in the
+ # comparison instead of a scalar
+ if not isinstance(index_a, MultiIndex):
+ expected3 = np.array([False] * (len(index_a) - 2) + [True, False])
+ # assuming the 2nd to last item is unique in the data
+ item = index_a[-2]
+ tm.assert_numpy_array_equal(index_a == item, expected3)
+ tm.assert_series_equal(series_a == item, Series(expected3))
+
+ def test_format(self, simple_index):
+ # GH35439
+ if is_numeric_dtype(simple_index.dtype) or isinstance(
+ simple_index, DatetimeIndex
+ ):
+ pytest.skip("Tested elsewhere.")
+ idx = simple_index
+ expected = [str(x) for x in idx]
+ assert idx.format() == expected
+
+ def test_format_empty(self, simple_index):
+ # GH35712
+ if isinstance(simple_index, (PeriodIndex, RangeIndex)):
+ pytest.skip("Tested elsewhere")
+ empty_idx = type(simple_index)([])
+ assert empty_idx.format() == []
+ assert empty_idx.format(name=True) == [""]
+
+ def test_fillna(self, index):
+ # GH 11343
+ if len(index) == 0:
+ pytest.skip("Not relevant for empty index")
+ elif index.dtype == bool:
+ pytest.skip(f"{index.dtype} cannot hold NAs")
+ elif isinstance(index, Index) and is_integer_dtype(index.dtype):
+ pytest.skip(f"Not relevant for Index with {index.dtype}")
+ elif isinstance(index, MultiIndex):
+ idx = index.copy(deep=True)
+ msg = "isna is not defined for MultiIndex"
+ with pytest.raises(NotImplementedError, match=msg):
+ idx.fillna(idx[0])
+ else:
+ idx = index.copy(deep=True)
+ result = idx.fillna(idx[0])
+ tm.assert_index_equal(result, idx)
+ assert result is not idx
+
+ msg = "'value' must be a scalar, passed: "
+ with pytest.raises(TypeError, match=msg):
+ idx.fillna([idx[0]])
+
+ idx = index.copy(deep=True)
+ values = idx._values
+
+ values[1] = np.nan
+
+ idx = type(index)(values)
+
+ msg = "does not support 'downcast'"
+ msg2 = r"The 'downcast' keyword in .*Index\.fillna is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg2):
+ with pytest.raises(NotImplementedError, match=msg):
+ # For now at least, we only raise if there are NAs present
+ idx.fillna(idx[0], downcast="infer")
+
+ expected = np.array([False] * len(idx), dtype=bool)
+ expected[1] = True
+ tm.assert_numpy_array_equal(idx._isnan, expected)
+ assert idx.hasnans is True
+
+ def test_nulls(self, index):
+ # this is really a smoke test for the methods
+ # as these are adequately tested for function elsewhere
+ if len(index) == 0:
+ tm.assert_numpy_array_equal(index.isna(), np.array([], dtype=bool))
+ elif isinstance(index, MultiIndex):
+ idx = index.copy()
+ msg = "isna is not defined for MultiIndex"
+ with pytest.raises(NotImplementedError, match=msg):
+ idx.isna()
+ elif not index.hasnans:
+ tm.assert_numpy_array_equal(index.isna(), np.zeros(len(index), dtype=bool))
+ tm.assert_numpy_array_equal(index.notna(), np.ones(len(index), dtype=bool))
+ else:
+ result = isna(index)
+ tm.assert_numpy_array_equal(index.isna(), result)
+ tm.assert_numpy_array_equal(index.notna(), ~result)
+
+ def test_empty(self, simple_index):
+ # GH 15270
+ idx = simple_index
+ assert not idx.empty
+ assert idx[:0].empty
+
+ def test_join_self_unique(self, join_type, simple_index):
+ idx = simple_index
+ if idx.is_unique:
+ joined = idx.join(idx, how=join_type)
+ assert (idx == joined).all()
+
+ def test_map(self, simple_index):
+ # callable
+ if isinstance(simple_index, (TimedeltaIndex, PeriodIndex)):
+ pytest.skip("Tested elsewhere.")
+ idx = simple_index
+
+ result = idx.map(lambda x: x)
+ # RangeIndex are equivalent to the similar Index with int64 dtype
+ tm.assert_index_equal(result, idx, exact="equiv")
+
+ @pytest.mark.parametrize(
+ "mapper",
+ [
+ lambda values, index: {i: e for e, i in zip(values, index)},
+ lambda values, index: Series(values, index),
+ ],
+ )
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_map_dictlike(self, mapper, simple_index, request):
+ idx = simple_index
+ if isinstance(idx, (DatetimeIndex, TimedeltaIndex, PeriodIndex)):
+ pytest.skip("Tested elsewhere.")
+
+ identity = mapper(idx.values, idx)
+
+ result = idx.map(identity)
+ # RangeIndex are equivalent to the similar Index with int64 dtype
+ tm.assert_index_equal(result, idx, exact="equiv")
+
+ # empty mappable
+ dtype = None
+ if idx.dtype.kind == "f":
+ dtype = idx.dtype
+
+ expected = Index([np.nan] * len(idx), dtype=dtype)
+ result = idx.map(mapper(expected, idx))
+ tm.assert_index_equal(result, expected)
+
+ def test_map_str(self, simple_index):
+ # GH 31202
+ if isinstance(simple_index, CategoricalIndex):
+ pytest.skip("See test_map.py")
+ idx = simple_index
+ result = idx.map(str)
+ expected = Index([str(x) for x in idx], dtype=object)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("copy", [True, False])
+ @pytest.mark.parametrize("name", [None, "foo"])
+ @pytest.mark.parametrize("ordered", [True, False])
+ def test_astype_category(self, copy, name, ordered, simple_index):
+ # GH 18630
+ idx = simple_index
+ if name:
+ idx = idx.rename(name)
+
+ # standard categories
+ dtype = CategoricalDtype(ordered=ordered)
+ result = idx.astype(dtype, copy=copy)
+ expected = CategoricalIndex(idx, name=name, ordered=ordered)
+ tm.assert_index_equal(result, expected, exact=True)
+
+ # non-standard categories
+ dtype = CategoricalDtype(idx.unique().tolist()[:-1], ordered)
+ result = idx.astype(dtype, copy=copy)
+ expected = CategoricalIndex(idx, name=name, dtype=dtype)
+ tm.assert_index_equal(result, expected, exact=True)
+
+ if ordered is False:
+ # dtype='category' defaults to ordered=False, so only test once
+ result = idx.astype("category", copy=copy)
+ expected = CategoricalIndex(idx, name=name)
+ tm.assert_index_equal(result, expected, exact=True)
+
+ def test_is_unique(self, simple_index):
+ # initialize a unique index
+ index = simple_index.drop_duplicates()
+ assert index.is_unique is True
+
+ # empty index should be unique
+ index_empty = index[:0]
+ assert index_empty.is_unique is True
+
+ # test basic dupes
+ index_dup = index.insert(0, index[0])
+ assert index_dup.is_unique is False
+
+ # single NA should be unique
+ index_na = index.insert(0, np.nan)
+ assert index_na.is_unique is True
+
+ # multiple NA should not be unique
+ index_na_dup = index_na.insert(0, np.nan)
+ assert index_na_dup.is_unique is False
+
+ @pytest.mark.arm_slow
+ def test_engine_reference_cycle(self, simple_index):
+ # GH27585
+ index = simple_index
+ nrefs_pre = len(gc.get_referrers(index))
+ index._engine
+ assert len(gc.get_referrers(index)) == nrefs_pre
+
+ def test_getitem_2d_deprecated(self, simple_index):
+ # GH#30588, GH#31479
+ if isinstance(simple_index, IntervalIndex):
+ pytest.skip("Tested elsewhere")
+ idx = simple_index
+ msg = "Multi-dimensional indexing"
+ with pytest.raises(ValueError, match=msg):
+ idx[:, None]
+
+ if not isinstance(idx, RangeIndex):
+ # GH#44051 RangeIndex already raised pre-2.0 with a different message
+ with pytest.raises(ValueError, match=msg):
+ idx[True]
+ with pytest.raises(ValueError, match=msg):
+ idx[False]
+ else:
+ msg = "only integers, slices"
+ with pytest.raises(IndexError, match=msg):
+ idx[True]
+ with pytest.raises(IndexError, match=msg):
+ idx[False]
+
+ def test_copy_shares_cache(self, simple_index):
+ # GH32898, GH36840
+ idx = simple_index
+ idx.get_loc(idx[0]) # populates the _cache.
+ copy = idx.copy()
+
+ assert copy._cache is idx._cache
+
+ def test_shallow_copy_shares_cache(self, simple_index):
+ # GH32669, GH36840
+ idx = simple_index
+ idx.get_loc(idx[0]) # populates the _cache.
+ shallow_copy = idx._view()
+
+ assert shallow_copy._cache is idx._cache
+
+ shallow_copy = idx._shallow_copy(idx._data)
+ assert shallow_copy._cache is not idx._cache
+ assert shallow_copy._cache == {}
+
+ def test_index_groupby(self, simple_index):
+ idx = simple_index[:5]
+ to_groupby = np.array([1, 2, np.nan, 2, 1])
+ tm.assert_dict_equal(
+ idx.groupby(to_groupby), {1.0: idx[[0, 4]], 2.0: idx[[1, 3]]}
+ )
+
+ to_groupby = DatetimeIndex(
+ [
+ datetime(2011, 11, 1),
+ datetime(2011, 12, 1),
+ pd.NaT,
+ datetime(2011, 12, 1),
+ datetime(2011, 11, 1),
+ ],
+ tz="UTC",
+ ).values
+
+ ex_keys = [Timestamp("2011-11-01"), Timestamp("2011-12-01")]
+ expected = {ex_keys[0]: idx[[0, 4]], ex_keys[1]: idx[[1, 3]]}
+ tm.assert_dict_equal(idx.groupby(to_groupby), expected)
+
+ def test_append_preserves_dtype(self, simple_index):
+ # In particular Index with dtype float32
+ index = simple_index
+ N = len(index)
+
+ result = index.append(index)
+ assert result.dtype == index.dtype
+ tm.assert_index_equal(result[:N], index, check_exact=True)
+ tm.assert_index_equal(result[N:], index, check_exact=True)
+
+ alt = index.take(list(range(N)) * 2)
+ tm.assert_index_equal(result, alt, check_exact=True)
+
+ def test_inv(self, simple_index):
+ idx = simple_index
+
+ if idx.dtype.kind in ["i", "u"]:
+ res = ~idx
+ expected = Index(~idx.values, name=idx.name)
+ tm.assert_index_equal(res, expected)
+
+ # check that we are matching Series behavior
+ res2 = ~Series(idx)
+ tm.assert_series_equal(res2, Series(expected))
+ else:
+ if idx.dtype.kind == "f":
+ msg = "ufunc 'invert' not supported for the input types"
+ else:
+ msg = "bad operand"
+ with pytest.raises(TypeError, match=msg):
+ ~idx
+
+ # check that we get the same behavior with Series
+ with pytest.raises(TypeError, match=msg):
+ ~Series(idx)
+
+ def test_is_boolean_is_deprecated(self, simple_index):
+ # GH50042
+ idx = simple_index
+ with tm.assert_produces_warning(FutureWarning):
+ idx.is_boolean()
+
+ def test_is_floating_is_deprecated(self, simple_index):
+ # GH50042
+ idx = simple_index
+ with tm.assert_produces_warning(FutureWarning):
+ idx.is_floating()
+
+ def test_is_integer_is_deprecated(self, simple_index):
+ # GH50042
+ idx = simple_index
+ with tm.assert_produces_warning(FutureWarning):
+ idx.is_integer()
+
+ def test_holds_integer_deprecated(self, simple_index):
+ # GH50243
+ idx = simple_index
+ msg = f"{type(idx).__name__}.holds_integer is deprecated. "
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ idx.holds_integer()
+
+ def test_is_numeric_is_deprecated(self, simple_index):
+ # GH50042
+ idx = simple_index
+ with tm.assert_produces_warning(
+ FutureWarning,
+ match=f"{type(idx).__name__}.is_numeric is deprecated. ",
+ ):
+ idx.is_numeric()
+
+ def test_is_categorical_is_deprecated(self, simple_index):
+ # GH50042
+ idx = simple_index
+ with tm.assert_produces_warning(
+ FutureWarning,
+ match=r"Use pandas\.api\.types\.is_categorical_dtype instead",
+ ):
+ idx.is_categorical()
+
+ def test_is_interval_is_deprecated(self, simple_index):
+ # GH50042
+ idx = simple_index
+ with tm.assert_produces_warning(FutureWarning):
+ idx.is_interval()
+
+ def test_is_object_is_deprecated(self, simple_index):
+ # GH50042
+ idx = simple_index
+ with tm.assert_produces_warning(FutureWarning):
+ idx.is_object()
+
+
+class TestNumericBase:
+ @pytest.fixture(
+ params=[
+ RangeIndex(start=0, stop=20, step=2),
+ Index(np.arange(5, dtype=np.float64)),
+ Index(np.arange(5, dtype=np.float32)),
+ Index(np.arange(5, dtype=np.uint64)),
+ Index(range(0, 20, 2), dtype=np.int64),
+ Index(range(0, 20, 2), dtype=np.int32),
+ Index(range(0, 20, 2), dtype=np.int16),
+ Index(range(0, 20, 2), dtype=np.int8),
+ ]
+ )
+ def simple_index(self, request):
+ return request.param
+
+ def test_constructor_unwraps_index(self, simple_index):
+ if isinstance(simple_index, RangeIndex):
+ pytest.skip("Tested elsewhere.")
+ index_cls = type(simple_index)
+ dtype = simple_index.dtype
+
+ idx = Index([1, 2], dtype=dtype)
+ result = index_cls(idx)
+ expected = np.array([1, 2], dtype=idx.dtype)
+ tm.assert_numpy_array_equal(result._data, expected)
+
+ def test_can_hold_identifiers(self, simple_index):
+ idx = simple_index
+ key = idx[0]
+ assert idx._can_hold_identifiers_and_holds_name(key) is False
+
+ def test_view(self, simple_index):
+ if isinstance(simple_index, RangeIndex):
+ pytest.skip("Tested elsewhere.")
+ index_cls = type(simple_index)
+ dtype = simple_index.dtype
+
+ idx = index_cls([], dtype=dtype, name="Foo")
+ idx_view = idx.view()
+ assert idx_view.name == "Foo"
+
+ idx_view = idx.view(dtype)
+ tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True)
+
+ idx_view = idx.view(index_cls)
+ tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True)
+
+ def test_format(self, simple_index):
+ # GH35439
+ if isinstance(simple_index, DatetimeIndex):
+ pytest.skip("Tested elsewhere")
+ idx = simple_index
+ max_width = max(len(str(x)) for x in idx)
+ expected = [str(x).ljust(max_width) for x in idx]
+ assert idx.format() == expected
+
+ def test_insert_non_na(self, simple_index):
+ # GH#43921 inserting an element that we know we can hold should
+ # not change dtype or type (except for RangeIndex)
+ index = simple_index
+
+ result = index.insert(0, index[0])
+
+ expected = Index([index[0]] + list(index), dtype=index.dtype)
+ tm.assert_index_equal(result, expected, exact=True)
+
+ def test_insert_na(self, nulls_fixture, simple_index):
+ # GH 18295 (test missing)
+ index = simple_index
+ na_val = nulls_fixture
+
+ if na_val is pd.NaT:
+ expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object)
+ else:
+ expected = Index([index[0], np.nan] + list(index[1:]))
+ # GH#43921 we preserve float dtype
+ if index.dtype.kind == "f":
+ expected = Index(expected, dtype=index.dtype)
+
+ result = index.insert(1, na_val)
+ tm.assert_index_equal(result, expected, exact=True)
+
+ def test_arithmetic_explicit_conversions(self, simple_index):
+ # GH 8608
+ # add/sub are overridden explicitly for Float/Int Index
+ index_cls = type(simple_index)
+ if index_cls is RangeIndex:
+ idx = RangeIndex(5)
+ else:
+ idx = index_cls(np.arange(5, dtype="int64"))
+
+ # float conversions
+ arr = np.arange(5, dtype="int64") * 3.2
+ expected = Index(arr, dtype=np.float64)
+ fidx = idx * 3.2
+ tm.assert_index_equal(fidx, expected)
+ fidx = 3.2 * idx
+ tm.assert_index_equal(fidx, expected)
+
+ # interops with numpy arrays
+ expected = Index(arr, dtype=np.float64)
+ a = np.zeros(5, dtype="float64")
+ result = fidx - a
+ tm.assert_index_equal(result, expected)
+
+ expected = Index(-arr, dtype=np.float64)
+ a = np.zeros(5, dtype="float64")
+ result = a - fidx
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("complex_dtype", [np.complex64, np.complex128])
+ def test_astype_to_complex(self, complex_dtype, simple_index):
+ result = simple_index.astype(complex_dtype)
+
+ assert type(result) is Index and result.dtype == complex_dtype
+
+ def test_cast_string(self, simple_index):
+ if isinstance(simple_index, RangeIndex):
+ pytest.skip("casting of strings not relevant for RangeIndex")
+ result = type(simple_index)(["0", "1", "2"], dtype=simple_index.dtype)
+ expected = type(simple_index)([0, 1, 2], dtype=simple_index.dtype)
+ tm.assert_index_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_setops.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_setops.py
new file mode 100644
index 0000000000000000000000000000000000000000..a64994efec85a257afefc95283df1747e1ee39e5
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_setops.py
@@ -0,0 +1,908 @@
+"""
+The tests in this package are to ensure the proper resultant dtypes of
+set operations.
+"""
+from datetime import datetime
+import operator
+
+import numpy as np
+import pytest
+
+from pandas._libs import lib
+
+from pandas.core.dtypes.cast import find_common_type
+
+from pandas import (
+ CategoricalDtype,
+ CategoricalIndex,
+ DatetimeTZDtype,
+ Index,
+ MultiIndex,
+ PeriodDtype,
+ RangeIndex,
+ Series,
+ Timestamp,
+)
+import pandas._testing as tm
+from pandas.api.types import (
+ is_signed_integer_dtype,
+ pandas_dtype,
+)
+
+
+def test_union_same_types(index):
+ # Union with a non-unique, non-monotonic index raises error
+ # Only needed for bool index factory
+ idx1 = index.sort_values()
+ idx2 = index.sort_values()
+ assert idx1.union(idx2).dtype == idx1.dtype
+
+
+def test_union_different_types(index_flat, index_flat2, request):
+ # This test only considers combinations of indices
+ # GH 23525
+ idx1 = index_flat
+ idx2 = index_flat2
+
+ if (
+ not idx1.is_unique
+ and not idx2.is_unique
+ and idx1.dtype.kind == "i"
+ and idx2.dtype.kind == "b"
+ ) or (
+ not idx2.is_unique
+ and not idx1.is_unique
+ and idx2.dtype.kind == "i"
+ and idx1.dtype.kind == "b"
+ ):
+ # Each condition had idx[1|2].is_monotonic_decreasing
+ # but failed when e.g.
+ # idx1 = Index(
+ # [True, True, True, True, True, True, True, True, False, False], dtype='bool'
+ # )
+ # idx2 = Index([0, 0, 1, 1, 2, 2], dtype='int64')
+ mark = pytest.mark.xfail(
+ reason="GH#44000 True==1", raises=ValueError, strict=False
+ )
+ request.node.add_marker(mark)
+
+ common_dtype = find_common_type([idx1.dtype, idx2.dtype])
+
+ warn = None
+ msg = "'<' not supported between"
+ if not len(idx1) or not len(idx2):
+ pass
+ elif (idx1.dtype.kind == "c" and (not lib.is_np_dtype(idx2.dtype, "iufc"))) or (
+ idx2.dtype.kind == "c" and (not lib.is_np_dtype(idx1.dtype, "iufc"))
+ ):
+ # complex objects non-sortable
+ warn = RuntimeWarning
+ elif (
+ isinstance(idx1.dtype, PeriodDtype) and isinstance(idx2.dtype, CategoricalDtype)
+ ) or (
+ isinstance(idx2.dtype, PeriodDtype) and isinstance(idx1.dtype, CategoricalDtype)
+ ):
+ warn = FutureWarning
+ msg = r"PeriodDtype\[B\] is deprecated"
+ mark = pytest.mark.xfail(
+ reason="Warning not produced on all builds",
+ raises=AssertionError,
+ strict=False,
+ )
+ request.node.add_marker(mark)
+
+ any_uint64 = np.uint64 in (idx1.dtype, idx2.dtype)
+ idx1_signed = is_signed_integer_dtype(idx1.dtype)
+ idx2_signed = is_signed_integer_dtype(idx2.dtype)
+
+ # Union with a non-unique, non-monotonic index raises error
+ # This applies to the boolean index
+ idx1 = idx1.sort_values()
+ idx2 = idx2.sort_values()
+
+ with tm.assert_produces_warning(warn, match=msg):
+ res1 = idx1.union(idx2)
+ res2 = idx2.union(idx1)
+
+ if any_uint64 and (idx1_signed or idx2_signed):
+ assert res1.dtype == np.dtype("O")
+ assert res2.dtype == np.dtype("O")
+ else:
+ assert res1.dtype == common_dtype
+ assert res2.dtype == common_dtype
+
+
+@pytest.mark.parametrize(
+ "idx_fact1,idx_fact2",
+ [
+ (tm.makeIntIndex, tm.makeRangeIndex),
+ (tm.makeFloatIndex, tm.makeIntIndex),
+ (tm.makeFloatIndex, tm.makeRangeIndex),
+ (tm.makeFloatIndex, tm.makeUIntIndex),
+ ],
+)
+def test_compatible_inconsistent_pairs(idx_fact1, idx_fact2):
+ # GH 23525
+ idx1 = idx_fact1(10)
+ idx2 = idx_fact2(20)
+
+ res1 = idx1.union(idx2)
+ res2 = idx2.union(idx1)
+
+ assert res1.dtype in (idx1.dtype, idx2.dtype)
+ assert res2.dtype in (idx1.dtype, idx2.dtype)
+
+
+@pytest.mark.parametrize(
+ "left, right, expected",
+ [
+ ("int64", "int64", "int64"),
+ ("int64", "uint64", "object"),
+ ("int64", "float64", "float64"),
+ ("uint64", "float64", "float64"),
+ ("uint64", "uint64", "uint64"),
+ ("float64", "float64", "float64"),
+ ("datetime64[ns]", "int64", "object"),
+ ("datetime64[ns]", "uint64", "object"),
+ ("datetime64[ns]", "float64", "object"),
+ ("datetime64[ns, CET]", "int64", "object"),
+ ("datetime64[ns, CET]", "uint64", "object"),
+ ("datetime64[ns, CET]", "float64", "object"),
+ ("Period[D]", "int64", "object"),
+ ("Period[D]", "uint64", "object"),
+ ("Period[D]", "float64", "object"),
+ ],
+)
+@pytest.mark.parametrize("names", [("foo", "foo", "foo"), ("foo", "bar", None)])
+def test_union_dtypes(left, right, expected, names):
+ left = pandas_dtype(left)
+ right = pandas_dtype(right)
+ a = Index([], dtype=left, name=names[0])
+ b = Index([], dtype=right, name=names[1])
+ result = a.union(b)
+ assert result.dtype == expected
+ assert result.name == names[2]
+
+ # Testing name retention
+ # TODO: pin down desired dtype; do we want it to be commutative?
+ result = a.intersection(b)
+ assert result.name == names[2]
+
+
+@pytest.mark.parametrize("values", [[1, 2, 2, 3], [3, 3]])
+def test_intersection_duplicates(values):
+ # GH#31326
+ a = Index(values)
+ b = Index([3, 3])
+ result = a.intersection(b)
+ expected = Index([3])
+ tm.assert_index_equal(result, expected)
+
+
+class TestSetOps:
+ # Set operation tests shared by all indexes in the `index` fixture
+ @pytest.mark.parametrize("case", [0.5, "xxx"])
+ @pytest.mark.parametrize(
+ "method", ["intersection", "union", "difference", "symmetric_difference"]
+ )
+ def test_set_ops_error_cases(self, case, method, index):
+ # non-iterable input
+ msg = "Input must be Index or array-like"
+ with pytest.raises(TypeError, match=msg):
+ getattr(index, method)(case)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_intersection_base(self, index):
+ if isinstance(index, CategoricalIndex):
+ pytest.skip(f"Not relevant for {type(index).__name__}")
+
+ first = index[:5]
+ second = index[:3]
+ intersect = first.intersection(second)
+ assert tm.equalContents(intersect, second)
+
+ if isinstance(index.dtype, DatetimeTZDtype):
+ # The second.values below will drop tz, so the rest of this test
+ # is not applicable.
+ return
+
+ # GH#10149
+ cases = [second.to_numpy(), second.to_series(), second.to_list()]
+ for case in cases:
+ result = first.intersection(case)
+ assert tm.equalContents(result, second)
+
+ if isinstance(index, MultiIndex):
+ msg = "other must be a MultiIndex or a list of tuples"
+ with pytest.raises(TypeError, match=msg):
+ first.intersection([1, 2, 3])
+
+ @pytest.mark.filterwarnings(
+ "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
+ )
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_union_base(self, index):
+ first = index[3:]
+ second = index[:5]
+ everything = index
+
+ union = first.union(second)
+ assert tm.equalContents(union, everything)
+
+ if isinstance(index.dtype, DatetimeTZDtype):
+ # The second.values below will drop tz, so the rest of this test
+ # is not applicable.
+ return
+
+ # GH#10149
+ cases = [second.to_numpy(), second.to_series(), second.to_list()]
+ for case in cases:
+ result = first.union(case)
+ assert tm.equalContents(result, everything)
+
+ if isinstance(index, MultiIndex):
+ msg = "other must be a MultiIndex or a list of tuples"
+ with pytest.raises(TypeError, match=msg):
+ first.union([1, 2, 3])
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ @pytest.mark.filterwarnings(
+ "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
+ )
+ def test_difference_base(self, sort, index):
+ first = index[2:]
+ second = index[:4]
+ if index.inferred_type == "boolean":
+ # i think (TODO: be sure) there assumptions baked in about
+ # the index fixture that don't hold here?
+ answer = set(first).difference(set(second))
+ elif isinstance(index, CategoricalIndex):
+ answer = []
+ else:
+ answer = index[4:]
+ result = first.difference(second, sort)
+ assert tm.equalContents(result, answer)
+
+ # GH#10149
+ cases = [second.to_numpy(), second.to_series(), second.to_list()]
+ for case in cases:
+ result = first.difference(case, sort)
+ assert tm.equalContents(result, answer)
+
+ if isinstance(index, MultiIndex):
+ msg = "other must be a MultiIndex or a list of tuples"
+ with pytest.raises(TypeError, match=msg):
+ first.difference([1, 2, 3], sort)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ @pytest.mark.filterwarnings(
+ "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
+ )
+ def test_symmetric_difference(self, index):
+ if isinstance(index, CategoricalIndex):
+ pytest.skip(f"Not relevant for {type(index).__name__}")
+ if len(index) < 2:
+ pytest.skip("Too few values for test")
+ if index[0] in index[1:] or index[-1] in index[:-1]:
+ # index fixture has e.g. an index of bools that does not satisfy this,
+ # another with [0, 0, 1, 1, 2, 2]
+ pytest.skip("Index values no not satisfy test condition.")
+
+ first = index[1:]
+ second = index[:-1]
+ answer = index[[0, -1]]
+ result = first.symmetric_difference(second)
+ assert tm.equalContents(result, answer)
+
+ # GH#10149
+ cases = [second.to_numpy(), second.to_series(), second.to_list()]
+ for case in cases:
+ result = first.symmetric_difference(case)
+ assert tm.equalContents(result, answer)
+
+ if isinstance(index, MultiIndex):
+ msg = "other must be a MultiIndex or a list of tuples"
+ with pytest.raises(TypeError, match=msg):
+ first.symmetric_difference([1, 2, 3])
+
+ @pytest.mark.parametrize(
+ "fname, sname, expected_name",
+ [
+ ("A", "A", "A"),
+ ("A", "B", None),
+ ("A", None, None),
+ (None, "B", None),
+ (None, None, None),
+ ],
+ )
+ def test_corner_union(self, index_flat, fname, sname, expected_name):
+ # GH#9943, GH#9862
+ # Test unions with various name combinations
+ # Do not test MultiIndex or repeats
+ if not index_flat.is_unique:
+ pytest.skip("Randomly generated index_flat was not unique.")
+ index = index_flat
+
+ # Test copy.union(copy)
+ first = index.copy().set_names(fname)
+ second = index.copy().set_names(sname)
+ union = first.union(second)
+ expected = index.copy().set_names(expected_name)
+ tm.assert_index_equal(union, expected)
+
+ # Test copy.union(empty)
+ first = index.copy().set_names(fname)
+ second = index.drop(index).set_names(sname)
+ union = first.union(second)
+ expected = index.copy().set_names(expected_name)
+ tm.assert_index_equal(union, expected)
+
+ # Test empty.union(copy)
+ first = index.drop(index).set_names(fname)
+ second = index.copy().set_names(sname)
+ union = first.union(second)
+ expected = index.copy().set_names(expected_name)
+ tm.assert_index_equal(union, expected)
+
+ # Test empty.union(empty)
+ first = index.drop(index).set_names(fname)
+ second = index.drop(index).set_names(sname)
+ union = first.union(second)
+ expected = index.drop(index).set_names(expected_name)
+ tm.assert_index_equal(union, expected)
+
+ @pytest.mark.parametrize(
+ "fname, sname, expected_name",
+ [
+ ("A", "A", "A"),
+ ("A", "B", None),
+ ("A", None, None),
+ (None, "B", None),
+ (None, None, None),
+ ],
+ )
+ def test_union_unequal(self, index_flat, fname, sname, expected_name):
+ if not index_flat.is_unique:
+ pytest.skip("Randomly generated index_flat was not unique.")
+ index = index_flat
+
+ # test copy.union(subset) - need sort for unicode and string
+ first = index.copy().set_names(fname)
+ second = index[1:].set_names(sname)
+ union = first.union(second).sort_values()
+ expected = index.set_names(expected_name).sort_values()
+ tm.assert_index_equal(union, expected)
+
+ @pytest.mark.parametrize(
+ "fname, sname, expected_name",
+ [
+ ("A", "A", "A"),
+ ("A", "B", None),
+ ("A", None, None),
+ (None, "B", None),
+ (None, None, None),
+ ],
+ )
+ def test_corner_intersect(self, index_flat, fname, sname, expected_name):
+ # GH#35847
+ # Test intersections with various name combinations
+ if not index_flat.is_unique:
+ pytest.skip("Randomly generated index_flat was not unique.")
+ index = index_flat
+
+ # Test copy.intersection(copy)
+ first = index.copy().set_names(fname)
+ second = index.copy().set_names(sname)
+ intersect = first.intersection(second)
+ expected = index.copy().set_names(expected_name)
+ tm.assert_index_equal(intersect, expected)
+
+ # Test copy.intersection(empty)
+ first = index.copy().set_names(fname)
+ second = index.drop(index).set_names(sname)
+ intersect = first.intersection(second)
+ expected = index.drop(index).set_names(expected_name)
+ tm.assert_index_equal(intersect, expected)
+
+ # Test empty.intersection(copy)
+ first = index.drop(index).set_names(fname)
+ second = index.copy().set_names(sname)
+ intersect = first.intersection(second)
+ expected = index.drop(index).set_names(expected_name)
+ tm.assert_index_equal(intersect, expected)
+
+ # Test empty.intersection(empty)
+ first = index.drop(index).set_names(fname)
+ second = index.drop(index).set_names(sname)
+ intersect = first.intersection(second)
+ expected = index.drop(index).set_names(expected_name)
+ tm.assert_index_equal(intersect, expected)
+
+ @pytest.mark.parametrize(
+ "fname, sname, expected_name",
+ [
+ ("A", "A", "A"),
+ ("A", "B", None),
+ ("A", None, None),
+ (None, "B", None),
+ (None, None, None),
+ ],
+ )
+ def test_intersect_unequal(self, index_flat, fname, sname, expected_name):
+ if not index_flat.is_unique:
+ pytest.skip("Randomly generated index_flat was not unique.")
+ index = index_flat
+
+ # test copy.intersection(subset) - need sort for unicode and string
+ first = index.copy().set_names(fname)
+ second = index[1:].set_names(sname)
+ intersect = first.intersection(second).sort_values()
+ expected = index[1:].set_names(expected_name).sort_values()
+ tm.assert_index_equal(intersect, expected)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_intersection_name_retention_with_nameless(self, index):
+ if isinstance(index, MultiIndex):
+ index = index.rename(list(range(index.nlevels)))
+ else:
+ index = index.rename("foo")
+
+ other = np.asarray(index)
+
+ result = index.intersection(other)
+ assert result.name == index.name
+
+ # empty other, same dtype
+ result = index.intersection(other[:0])
+ assert result.name == index.name
+
+ # empty `self`
+ result = index[:0].intersection(other)
+ assert result.name == index.name
+
+ def test_difference_preserves_type_empty(self, index, sort):
+ # GH#20040
+ # If taking difference of a set and itself, it
+ # needs to preserve the type of the index
+ if not index.is_unique:
+ pytest.skip("Not relevant since index is not unique")
+ result = index.difference(index, sort=sort)
+ expected = index[:0]
+ tm.assert_index_equal(result, expected, exact=True)
+
+ def test_difference_name_retention_equals(self, index, names):
+ if isinstance(index, MultiIndex):
+ names = [[x] * index.nlevels for x in names]
+ index = index.rename(names[0])
+ other = index.rename(names[1])
+
+ assert index.equals(other)
+
+ result = index.difference(other)
+ expected = index[:0].rename(names[2])
+ tm.assert_index_equal(result, expected)
+
+ def test_intersection_difference_match_empty(self, index, sort):
+ # GH#20040
+ # Test that the intersection of an index with an
+ # empty index produces the same index as the difference
+ # of an index with itself. Test for all types
+ if not index.is_unique:
+ pytest.skip("Not relevant because index is not unique")
+ inter = index.intersection(index[:0])
+ diff = index.difference(index, sort=sort)
+ tm.assert_index_equal(inter, diff, exact=True)
+
+
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+@pytest.mark.filterwarnings(
+ "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
+)
+@pytest.mark.parametrize(
+ "method", ["intersection", "union", "difference", "symmetric_difference"]
+)
+def test_setop_with_categorical(index_flat, sort, method):
+ # MultiIndex tested separately in tests.indexes.multi.test_setops
+ index = index_flat
+
+ other = index.astype("category")
+ exact = "equiv" if isinstance(index, RangeIndex) else True
+
+ result = getattr(index, method)(other, sort=sort)
+ expected = getattr(index, method)(index, sort=sort)
+ tm.assert_index_equal(result, expected, exact=exact)
+
+ result = getattr(index, method)(other[:5], sort=sort)
+ expected = getattr(index, method)(index[:5], sort=sort)
+ tm.assert_index_equal(result, expected, exact=exact)
+
+
+def test_intersection_duplicates_all_indexes(index):
+ # GH#38743
+ if index.empty:
+ # No duplicates in empty indexes
+ pytest.skip("Not relevant for empty Index")
+
+ idx = index
+ idx_non_unique = idx[[0, 0, 1, 2]]
+
+ assert idx.intersection(idx_non_unique).equals(idx_non_unique.intersection(idx))
+ assert idx.intersection(idx_non_unique).is_unique
+
+
+def test_union_duplicate_index_subsets_of_each_other(
+ any_dtype_for_small_pos_integer_indexes,
+):
+ # GH#31326
+ dtype = any_dtype_for_small_pos_integer_indexes
+ a = Index([1, 2, 2, 3], dtype=dtype)
+ b = Index([3, 3, 4], dtype=dtype)
+
+ expected = Index([1, 2, 2, 3, 3, 4], dtype=dtype)
+ if isinstance(a, CategoricalIndex):
+ expected = Index([1, 2, 2, 3, 3, 4])
+ result = a.union(b)
+ tm.assert_index_equal(result, expected)
+ result = a.union(b, sort=False)
+ tm.assert_index_equal(result, expected)
+
+
+def test_union_with_duplicate_index_and_non_monotonic(
+ any_dtype_for_small_pos_integer_indexes,
+):
+ # GH#36289
+ dtype = any_dtype_for_small_pos_integer_indexes
+ a = Index([1, 0, 0], dtype=dtype)
+ b = Index([0, 1], dtype=dtype)
+ expected = Index([0, 0, 1], dtype=dtype)
+
+ result = a.union(b)
+ tm.assert_index_equal(result, expected)
+
+ result = b.union(a)
+ tm.assert_index_equal(result, expected)
+
+
+def test_union_duplicate_index_different_dtypes():
+ # GH#36289
+ a = Index([1, 2, 2, 3])
+ b = Index(["1", "0", "0"])
+ expected = Index([1, 2, 2, 3, "1", "0", "0"])
+ result = a.union(b, sort=False)
+ tm.assert_index_equal(result, expected)
+
+
+def test_union_same_value_duplicated_in_both():
+ # GH#36289
+ a = Index([0, 0, 1])
+ b = Index([0, 0, 1, 2])
+ result = a.union(b)
+ expected = Index([0, 0, 1, 2])
+ tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize("dup", [1, np.nan])
+def test_union_nan_in_both(dup):
+ # GH#36289
+ a = Index([np.nan, 1, 2, 2])
+ b = Index([np.nan, dup, 1, 2])
+ result = a.union(b, sort=False)
+ expected = Index([np.nan, dup, 1.0, 2.0, 2.0])
+ tm.assert_index_equal(result, expected)
+
+
+def test_union_rangeindex_sort_true():
+ # GH 53490
+ idx1 = RangeIndex(1, 100, 6)
+ idx2 = RangeIndex(1, 50, 3)
+ result = idx1.union(idx2, sort=True)
+ expected = Index(
+ [
+ 1,
+ 4,
+ 7,
+ 10,
+ 13,
+ 16,
+ 19,
+ 22,
+ 25,
+ 28,
+ 31,
+ 34,
+ 37,
+ 40,
+ 43,
+ 46,
+ 49,
+ 55,
+ 61,
+ 67,
+ 73,
+ 79,
+ 85,
+ 91,
+ 97,
+ ]
+ )
+ tm.assert_index_equal(result, expected)
+
+
+def test_union_with_duplicate_index_not_subset_and_non_monotonic(
+ any_dtype_for_small_pos_integer_indexes,
+):
+ # GH#36289
+ dtype = any_dtype_for_small_pos_integer_indexes
+ a = Index([1, 0, 2], dtype=dtype)
+ b = Index([0, 0, 1], dtype=dtype)
+ expected = Index([0, 0, 1, 2], dtype=dtype)
+ if isinstance(a, CategoricalIndex):
+ expected = Index([0, 0, 1, 2])
+
+ result = a.union(b)
+ tm.assert_index_equal(result, expected)
+
+ result = b.union(a)
+ tm.assert_index_equal(result, expected)
+
+
+def test_union_int_categorical_with_nan():
+ ci = CategoricalIndex([1, 2, np.nan])
+ assert ci.categories.dtype.kind == "i"
+
+ idx = Index([1, 2])
+
+ result = idx.union(ci)
+ expected = Index([1, 2, np.nan], dtype=np.float64)
+ tm.assert_index_equal(result, expected)
+
+ result = ci.union(idx)
+ tm.assert_index_equal(result, expected)
+
+
+class TestSetOpsUnsorted:
+ # These may eventually belong in a dtype-specific test_setops, or
+ # parametrized over a more general fixture
+ def test_intersect_str_dates(self):
+ dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)]
+
+ index1 = Index(dt_dates, dtype=object)
+ index2 = Index(["aa"], dtype=object)
+ result = index2.intersection(index1)
+
+ expected = Index([], dtype=object)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ def test_intersection(self, index, sort):
+ first = index[:20]
+ second = index[:10]
+ intersect = first.intersection(second, sort=sort)
+ if sort is None:
+ tm.assert_index_equal(intersect, second.sort_values())
+ assert tm.equalContents(intersect, second)
+
+ # Corner cases
+ inter = first.intersection(first, sort=sort)
+ assert inter is first
+
+ @pytest.mark.parametrize(
+ "index2,keeps_name",
+ [
+ (Index([3, 4, 5, 6, 7], name="index"), True), # preserve same name
+ (Index([3, 4, 5, 6, 7], name="other"), False), # drop diff names
+ (Index([3, 4, 5, 6, 7]), False),
+ ],
+ )
+ def test_intersection_name_preservation(self, index2, keeps_name, sort):
+ index1 = Index([1, 2, 3, 4, 5], name="index")
+ expected = Index([3, 4, 5])
+ result = index1.intersection(index2, sort)
+
+ if keeps_name:
+ expected.name = "index"
+
+ assert result.name == expected.name
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ @pytest.mark.parametrize(
+ "first_name,second_name,expected_name",
+ [("A", "A", "A"), ("A", "B", None), (None, "B", None)],
+ )
+ def test_intersection_name_preservation2(
+ self, index, first_name, second_name, expected_name, sort
+ ):
+ first = index[5:20]
+ second = index[:10]
+ first.name = first_name
+ second.name = second_name
+ intersect = first.intersection(second, sort=sort)
+ assert intersect.name == expected_name
+
+ def test_chained_union(self, sort):
+ # Chained unions handles names correctly
+ i1 = Index([1, 2], name="i1")
+ i2 = Index([5, 6], name="i2")
+ i3 = Index([3, 4], name="i3")
+ union = i1.union(i2.union(i3, sort=sort), sort=sort)
+ expected = i1.union(i2, sort=sort).union(i3, sort=sort)
+ tm.assert_index_equal(union, expected)
+
+ j1 = Index([1, 2], name="j1")
+ j2 = Index([], name="j2")
+ j3 = Index([], name="j3")
+ union = j1.union(j2.union(j3, sort=sort), sort=sort)
+ expected = j1.union(j2, sort=sort).union(j3, sort=sort)
+ tm.assert_index_equal(union, expected)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ def test_union(self, index, sort):
+ first = index[5:20]
+ second = index[:10]
+ everything = index[:20]
+
+ union = first.union(second, sort=sort)
+ if sort is None:
+ tm.assert_index_equal(union, everything.sort_values())
+ assert tm.equalContents(union, everything)
+
+ @pytest.mark.parametrize("klass", [np.array, Series, list])
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ def test_union_from_iterables(self, index, klass, sort):
+ # GH#10149
+ first = index[5:20]
+ second = index[:10]
+ everything = index[:20]
+
+ case = klass(second.values)
+ result = first.union(case, sort=sort)
+ if sort is None:
+ tm.assert_index_equal(result, everything.sort_values())
+ assert tm.equalContents(result, everything)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ def test_union_identity(self, index, sort):
+ first = index[5:20]
+
+ union = first.union(first, sort=sort)
+ # i.e. identity is not preserved when sort is True
+ assert (union is first) is (not sort)
+
+ # This should no longer be the same object, since [] is not consistent,
+ # both objects will be recast to dtype('O')
+ union = first.union([], sort=sort)
+ assert (union is first) is (not sort)
+
+ union = Index([]).union(first, sort=sort)
+ assert (union is first) is (not sort)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ @pytest.mark.parametrize("second_name,expected", [(None, None), ("name", "name")])
+ def test_difference_name_preservation(self, index, second_name, expected, sort):
+ first = index[5:20]
+ second = index[:10]
+ answer = index[10:20]
+
+ first.name = "name"
+ second.name = second_name
+ result = first.difference(second, sort=sort)
+
+ assert tm.equalContents(result, answer)
+
+ if expected is None:
+ assert result.name is None
+ else:
+ assert result.name == expected
+
+ def test_difference_empty_arg(self, index, sort):
+ first = index[5:20]
+ first.name = "name"
+ result = first.difference([], sort)
+
+ tm.assert_index_equal(result, first)
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ def test_difference_identity(self, index, sort):
+ first = index[5:20]
+ first.name = "name"
+ result = first.difference(first, sort)
+
+ assert len(result) == 0
+ assert result.name == first.name
+
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
+ def test_difference_sort(self, index, sort):
+ first = index[5:20]
+ second = index[:10]
+
+ result = first.difference(second, sort)
+ expected = index[10:20]
+
+ if sort is None:
+ expected = expected.sort_values()
+
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"])
+ def test_difference_incomparable(self, opname):
+ a = Index([3, Timestamp("2000"), 1])
+ b = Index([2, Timestamp("1999"), 1])
+ op = operator.methodcaller(opname, b)
+
+ with tm.assert_produces_warning(RuntimeWarning):
+ # sort=None, the default
+ result = op(a)
+ expected = Index([3, Timestamp("2000"), 2, Timestamp("1999")])
+ if opname == "difference":
+ expected = expected[:2]
+ tm.assert_index_equal(result, expected)
+
+ # sort=False
+ op = operator.methodcaller(opname, b, sort=False)
+ result = op(a)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"])
+ def test_difference_incomparable_true(self, opname):
+ a = Index([3, Timestamp("2000"), 1])
+ b = Index([2, Timestamp("1999"), 1])
+ op = operator.methodcaller(opname, b, sort=True)
+
+ msg = "'<' not supported between instances of 'Timestamp' and 'int'"
+ with pytest.raises(TypeError, match=msg):
+ op(a)
+
+ def test_symmetric_difference_mi(self, sort):
+ index1 = MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3]))
+ index2 = MultiIndex.from_tuples([("foo", 1), ("bar", 3)])
+ result = index1.symmetric_difference(index2, sort=sort)
+ expected = MultiIndex.from_tuples([("bar", 2), ("baz", 3), ("bar", 3)])
+ if sort is None:
+ expected = expected.sort_values()
+ tm.assert_index_equal(result, expected)
+ assert tm.equalContents(result, expected)
+
+ @pytest.mark.parametrize(
+ "index2,expected",
+ [
+ (Index([0, 1, np.nan]), Index([2.0, 3.0, 0.0])),
+ (Index([0, 1]), Index([np.nan, 2.0, 3.0, 0.0])),
+ ],
+ )
+ def test_symmetric_difference_missing(self, index2, expected, sort):
+ # GH#13514 change: {nan} - {nan} == {}
+ # (GH#6444, sorting of nans, is no longer an issue)
+ index1 = Index([1, np.nan, 2, 3])
+
+ result = index1.symmetric_difference(index2, sort=sort)
+ if sort is None:
+ expected = expected.sort_values()
+ tm.assert_index_equal(result, expected)
+
+ def test_symmetric_difference_non_index(self, sort):
+ index1 = Index([1, 2, 3, 4], name="index1")
+ index2 = np.array([2, 3, 4, 5])
+ expected = Index([1, 5])
+ result = index1.symmetric_difference(index2, sort=sort)
+ assert tm.equalContents(result, expected)
+ assert result.name == "index1"
+
+ result = index1.symmetric_difference(index2, result_name="new_name", sort=sort)
+ assert tm.equalContents(result, expected)
+ assert result.name == "new_name"
+
+ def test_union_ea_dtypes(self, any_numeric_ea_and_arrow_dtype):
+ # GH#51365
+ idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype)
+ idx2 = Index([3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype)
+ result = idx.union(idx2)
+ expected = Index([1, 2, 3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype)
+ tm.assert_index_equal(result, expected)
+
+ def test_union_string_array(self, any_string_dtype):
+ idx1 = Index(["a"], dtype=any_string_dtype)
+ idx2 = Index(["b"], dtype=any_string_dtype)
+ result = idx1.union(idx2)
+ expected = Index(["a", "b"], dtype=any_string_dtype)
+ tm.assert_index_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_subclass.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_subclass.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3287e1ddcddcedc14857f2299798d3957830921
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexes/test_subclass.py
@@ -0,0 +1,40 @@
+"""
+Tests involving custom Index subclasses
+"""
+import numpy as np
+
+from pandas import (
+ DataFrame,
+ Index,
+)
+import pandas._testing as tm
+
+
+class CustomIndex(Index):
+ def __new__(cls, data, name=None):
+ # assert that this index class cannot hold strings
+ if any(isinstance(val, str) for val in data):
+ raise TypeError("CustomIndex cannot hold strings")
+
+ if name is None and hasattr(data, "name"):
+ name = data.name
+ data = np.array(data, dtype="O")
+
+ return cls._simple_new(data, name)
+
+
+def test_insert_fallback_to_base_index():
+ # https://github.com/pandas-dev/pandas/issues/47071
+
+ idx = CustomIndex([1, 2, 3])
+ result = idx.insert(0, "string")
+ expected = Index(["string", 1, 2, 3], dtype=object)
+ tm.assert_index_equal(result, expected)
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((2, 3)),
+ columns=idx,
+ index=Index([1, 2], name="string"),
+ )
+ result = df.reset_index()
+ tm.assert_index_equal(result.columns, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..2af76f69a4300ac744a5e6f1f7dab185e19767ca
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/common.py
@@ -0,0 +1,40 @@
+""" common utilities """
+from __future__ import annotations
+
+from typing import (
+ Any,
+ Literal,
+)
+
+
+def _mklbl(prefix: str, n: int):
+ return [f"{prefix}{i}" for i in range(n)]
+
+
+def check_indexing_smoketest_or_raises(
+ obj,
+ method: Literal["iloc", "loc"],
+ key: Any,
+ axes: Literal[0, 1] | None = None,
+ fails=None,
+) -> None:
+ if axes is None:
+ axes_list = [0, 1]
+ else:
+ assert axes in [0, 1]
+ axes_list = [axes]
+
+ for ax in axes_list:
+ if ax < obj.ndim:
+ # create a tuple accessor
+ new_axes = [slice(None)] * obj.ndim
+ new_axes[ax] = key
+ axified = tuple(new_axes)
+ try:
+ getattr(obj, method).__getitem__(axified)
+ except (IndexError, TypeError, KeyError) as detail:
+ # if we are in fails, the ok, otherwise raise it
+ if fails is not None:
+ if isinstance(detail, fails):
+ return
+ raise
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..4184c6a0047ccf0dccb8a72f028b27879130aea5
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/conftest.py
@@ -0,0 +1,127 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ date_range,
+)
+
+
+@pytest.fixture
+def series_ints():
+ return Series(np.random.default_rng(2).random(4), index=np.arange(0, 8, 2))
+
+
+@pytest.fixture
+def frame_ints():
+ return DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=np.arange(0, 8, 2),
+ columns=np.arange(0, 12, 3),
+ )
+
+
+@pytest.fixture
+def series_uints():
+ return Series(
+ np.random.default_rng(2).random(4),
+ index=Index(np.arange(0, 8, 2, dtype=np.uint64)),
+ )
+
+
+@pytest.fixture
+def frame_uints():
+ return DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=Index(range(0, 8, 2), dtype=np.uint64),
+ columns=Index(range(0, 12, 3), dtype=np.uint64),
+ )
+
+
+@pytest.fixture
+def series_labels():
+ return Series(np.random.default_rng(2).standard_normal(4), index=list("abcd"))
+
+
+@pytest.fixture
+def frame_labels():
+ return DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=list("abcd"),
+ columns=list("ABCD"),
+ )
+
+
+@pytest.fixture
+def series_ts():
+ return Series(
+ np.random.default_rng(2).standard_normal(4),
+ index=date_range("20130101", periods=4),
+ )
+
+
+@pytest.fixture
+def frame_ts():
+ return DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=date_range("20130101", periods=4),
+ )
+
+
+@pytest.fixture
+def series_floats():
+ return Series(
+ np.random.default_rng(2).random(4),
+ index=Index(range(0, 8, 2), dtype=np.float64),
+ )
+
+
+@pytest.fixture
+def frame_floats():
+ return DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=Index(range(0, 8, 2), dtype=np.float64),
+ columns=Index(range(0, 12, 3), dtype=np.float64),
+ )
+
+
+@pytest.fixture
+def series_mixed():
+ return Series(np.random.default_rng(2).standard_normal(4), index=[2, 4, "null", 8])
+
+
+@pytest.fixture
+def frame_mixed():
+ return DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)), index=[2, 4, "null", 8]
+ )
+
+
+@pytest.fixture
+def frame_empty():
+ return DataFrame()
+
+
+@pytest.fixture
+def series_empty():
+ return Series(dtype=object)
+
+
+@pytest.fixture
+def frame_multi():
+ return DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=MultiIndex.from_product([[1, 2], [3, 4]]),
+ columns=MultiIndex.from_product([[5, 6], [7, 8]]),
+ )
+
+
+@pytest.fixture
+def series_multi():
+ return Series(
+ np.random.default_rng(2).random(4),
+ index=MultiIndex.from_product([[1, 2], [3, 4]]),
+ )
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_at.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_at.py
new file mode 100644
index 0000000000000000000000000000000000000000..7504c984794e8d1b10d6b7d25d34817ecbb74127
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_at.py
@@ -0,0 +1,252 @@
+from datetime import (
+ datetime,
+ timezone,
+)
+
+import numpy as np
+import pytest
+
+from pandas.errors import InvalidIndexError
+
+from pandas import (
+ CategoricalDtype,
+ CategoricalIndex,
+ DataFrame,
+ DatetimeIndex,
+ MultiIndex,
+ Series,
+ Timestamp,
+)
+import pandas._testing as tm
+
+
+def test_at_timezone():
+ # https://github.com/pandas-dev/pandas/issues/33544
+ result = DataFrame({"foo": [datetime(2000, 1, 1)]})
+ with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
+ result.at[0, "foo"] = datetime(2000, 1, 2, tzinfo=timezone.utc)
+ expected = DataFrame(
+ {"foo": [datetime(2000, 1, 2, tzinfo=timezone.utc)]}, dtype=object
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_selection_methods_of_assigned_col():
+ # GH 29282
+ df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]})
+ df2 = DataFrame(data={"c": [7, 8, 9]}, index=[2, 1, 0])
+ df["c"] = df2["c"]
+ df.at[1, "c"] = 11
+ result = df
+ expected = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [9, 11, 7]})
+ tm.assert_frame_equal(result, expected)
+ result = df.at[1, "c"]
+ assert result == 11
+
+ result = df["c"]
+ expected = Series([9, 11, 7], name="c")
+ tm.assert_series_equal(result, expected)
+
+ result = df[["c"]]
+ expected = DataFrame({"c": [9, 11, 7]})
+ tm.assert_frame_equal(result, expected)
+
+
+class TestAtSetItem:
+ def test_at_setitem_item_cache_cleared(self):
+ # GH#22372 Note the multi-step construction is necessary to trigger
+ # the original bug. pandas/issues/22372#issuecomment-413345309
+ df = DataFrame(index=[0])
+ df["x"] = 1
+ df["cost"] = 2
+
+ # accessing df["cost"] adds "cost" to the _item_cache
+ df["cost"]
+
+ # This loc[[0]] lookup used to call _consolidate_inplace at the
+ # BlockManager level, which failed to clear the _item_cache
+ df.loc[[0]]
+
+ df.at[0, "x"] = 4
+ df.at[0, "cost"] = 789
+
+ expected = DataFrame({"x": [4], "cost": 789}, index=[0])
+ tm.assert_frame_equal(df, expected)
+
+ # And in particular, check that the _item_cache has updated correctly.
+ tm.assert_series_equal(df["cost"], expected["cost"])
+
+ def test_at_setitem_mixed_index_assignment(self):
+ # GH#19860
+ ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
+ ser.at["a"] = 11
+ assert ser.iat[0] == 11
+ ser.at[1] = 22
+ assert ser.iat[3] == 22
+
+ def test_at_setitem_categorical_missing(self):
+ df = DataFrame(
+ index=range(3), columns=range(3), dtype=CategoricalDtype(["foo", "bar"])
+ )
+ df.at[1, 1] = "foo"
+
+ expected = DataFrame(
+ [
+ [np.nan, np.nan, np.nan],
+ [np.nan, "foo", np.nan],
+ [np.nan, np.nan, np.nan],
+ ],
+ dtype=CategoricalDtype(["foo", "bar"]),
+ )
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_at_setitem_multiindex(self):
+ df = DataFrame(
+ np.zeros((3, 2), dtype="int64"),
+ columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]),
+ )
+ df.at[0, "a"] = 10
+ expected = DataFrame(
+ [[10, 10], [0, 0], [0, 0]],
+ columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]),
+ )
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("row", (Timestamp("2019-01-01"), "2019-01-01"))
+ def test_at_datetime_index(self, row):
+ # Set float64 dtype to avoid upcast when setting .5
+ df = DataFrame(
+ data=[[1] * 2], index=DatetimeIndex(data=["2019-01-01", "2019-01-02"])
+ ).astype({0: "float64"})
+ expected = DataFrame(
+ data=[[0.5, 1], [1.0, 1]],
+ index=DatetimeIndex(data=["2019-01-01", "2019-01-02"]),
+ )
+
+ df.at[row, 0] = 0.5
+ tm.assert_frame_equal(df, expected)
+
+
+class TestAtSetItemWithExpansion:
+ def test_at_setitem_expansion_series_dt64tz_value(self, tz_naive_fixture):
+ # GH#25506
+ ts = Timestamp("2017-08-05 00:00:00+0100", tz=tz_naive_fixture)
+ result = Series(ts)
+ result.at[1] = ts
+ expected = Series([ts, ts])
+ tm.assert_series_equal(result, expected)
+
+
+class TestAtWithDuplicates:
+ def test_at_with_duplicate_axes_requires_scalar_lookup(self):
+ # GH#33041 check that falling back to loc doesn't allow non-scalar
+ # args to slip in
+
+ arr = np.random.default_rng(2).standard_normal(6).reshape(3, 2)
+ df = DataFrame(arr, columns=["A", "A"])
+
+ msg = "Invalid call for scalar access"
+ with pytest.raises(ValueError, match=msg):
+ df.at[[1, 2]]
+ with pytest.raises(ValueError, match=msg):
+ df.at[1, ["A"]]
+ with pytest.raises(ValueError, match=msg):
+ df.at[:, "A"]
+
+ with pytest.raises(ValueError, match=msg):
+ df.at[[1, 2]] = 1
+ with pytest.raises(ValueError, match=msg):
+ df.at[1, ["A"]] = 1
+ with pytest.raises(ValueError, match=msg):
+ df.at[:, "A"] = 1
+
+
+class TestAtErrors:
+ # TODO: De-duplicate/parametrize
+ # test_at_series_raises_key_error2, test_at_frame_raises_key_error2
+
+ def test_at_series_raises_key_error(self, indexer_al):
+ # GH#31724 .at should match .loc
+
+ ser = Series([1, 2, 3], index=[3, 2, 1])
+ result = indexer_al(ser)[1]
+ assert result == 3
+
+ with pytest.raises(KeyError, match="a"):
+ indexer_al(ser)["a"]
+
+ def test_at_frame_raises_key_error(self, indexer_al):
+ # GH#31724 .at should match .loc
+
+ df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1])
+
+ result = indexer_al(df)[1, 0]
+ assert result == 3
+
+ with pytest.raises(KeyError, match="a"):
+ indexer_al(df)["a", 0]
+
+ with pytest.raises(KeyError, match="a"):
+ indexer_al(df)[1, "a"]
+
+ def test_at_series_raises_key_error2(self, indexer_al):
+ # at should not fallback
+ # GH#7814
+ # GH#31724 .at should match .loc
+ ser = Series([1, 2, 3], index=list("abc"))
+ result = indexer_al(ser)["a"]
+ assert result == 1
+
+ with pytest.raises(KeyError, match="^0$"):
+ indexer_al(ser)[0]
+
+ def test_at_frame_raises_key_error2(self, indexer_al):
+ # GH#31724 .at should match .loc
+ df = DataFrame({"A": [1, 2, 3]}, index=list("abc"))
+ result = indexer_al(df)["a", "A"]
+ assert result == 1
+
+ with pytest.raises(KeyError, match="^0$"):
+ indexer_al(df)["a", 0]
+
+ def test_at_frame_multiple_columns(self):
+ # GH#48296 - at shouldn't modify multiple columns
+ df = DataFrame({"a": [1, 2], "b": [3, 4]})
+ new_row = [6, 7]
+ with pytest.raises(
+ InvalidIndexError,
+ match=f"You can only assign a scalar value not a \\{type(new_row)}",
+ ):
+ df.at[5] = new_row
+
+ def test_at_getitem_mixed_index_no_fallback(self):
+ # GH#19860
+ ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
+ with pytest.raises(KeyError, match="^0$"):
+ ser.at[0]
+ with pytest.raises(KeyError, match="^4$"):
+ ser.at[4]
+
+ def test_at_categorical_integers(self):
+ # CategoricalIndex with integer categories that don't happen to match
+ # the Categorical's codes
+ ci = CategoricalIndex([3, 4])
+
+ arr = np.arange(4).reshape(2, 2)
+ frame = DataFrame(arr, index=ci)
+
+ for df in [frame, frame.T]:
+ for key in [0, 1]:
+ with pytest.raises(KeyError, match=str(key)):
+ df.at[key, key]
+
+ def test_at_applied_for_rows(self):
+ # GH#48729 .at should raise InvalidIndexError when assigning rows
+ df = DataFrame(index=["a"], columns=["col1", "col2"])
+ new_row = [123, 15]
+ with pytest.raises(
+ InvalidIndexError,
+ match=f"You can only assign a scalar value not a \\{type(new_row)}",
+ ):
+ df.at["a"] = new_row
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_categorical.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_categorical.py
new file mode 100644
index 0000000000000000000000000000000000000000..b45d197af332e9fb71878f55e17fe64d4de6fa36
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_categorical.py
@@ -0,0 +1,563 @@
+import re
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ CategoricalDtype,
+ CategoricalIndex,
+ DataFrame,
+ Index,
+ Interval,
+ Series,
+ Timedelta,
+ Timestamp,
+)
+import pandas._testing as tm
+from pandas.api.types import CategoricalDtype as CDT
+
+
+@pytest.fixture
+def df():
+ return DataFrame(
+ {
+ "A": np.arange(6, dtype="int64"),
+ },
+ index=CategoricalIndex(list("aabbca"), dtype=CDT(list("cab")), name="B"),
+ )
+
+
+@pytest.fixture
+def df2():
+ return DataFrame(
+ {
+ "A": np.arange(6, dtype="int64"),
+ },
+ index=CategoricalIndex(list("aabbca"), dtype=CDT(list("cabe")), name="B"),
+ )
+
+
+class TestCategoricalIndex:
+ def test_loc_scalar(self, df):
+ dtype = CDT(list("cab"))
+ result = df.loc["a"]
+ bidx = Series(list("aaa"), name="B").astype(dtype)
+ assert bidx.dtype == dtype
+
+ expected = DataFrame({"A": [0, 1, 5]}, index=Index(bidx))
+ tm.assert_frame_equal(result, expected)
+
+ df = df.copy()
+ df.loc["a"] = 20
+ bidx2 = Series(list("aabbca"), name="B").astype(dtype)
+ assert bidx2.dtype == dtype
+ expected = DataFrame(
+ {
+ "A": [20, 20, 2, 3, 4, 20],
+ },
+ index=Index(bidx2),
+ )
+ tm.assert_frame_equal(df, expected)
+
+ # value not in the categories
+ with pytest.raises(KeyError, match=r"^'d'$"):
+ df.loc["d"]
+
+ df2 = df.copy()
+ expected = df2.copy()
+ expected.index = expected.index.astype(object)
+ expected.loc["d"] = 10
+ df2.loc["d"] = 10
+ tm.assert_frame_equal(df2, expected)
+
+ def test_loc_setitem_with_expansion_non_category(self, df):
+ # Setting-with-expansion with a new key "d" that is not among caegories
+ df.loc["a"] = 20
+
+ # Setting a new row on an existing column
+ df3 = df.copy()
+ df3.loc["d", "A"] = 10
+ bidx3 = Index(list("aabbcad"), name="B")
+ expected3 = DataFrame(
+ {
+ "A": [20, 20, 2, 3, 4, 20, 10.0],
+ },
+ index=Index(bidx3),
+ )
+ tm.assert_frame_equal(df3, expected3)
+
+ # Settig a new row _and_ new column
+ df4 = df.copy()
+ df4.loc["d", "C"] = 10
+ expected3 = DataFrame(
+ {
+ "A": [20, 20, 2, 3, 4, 20, np.nan],
+ "C": [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 10],
+ },
+ index=Index(bidx3),
+ )
+ tm.assert_frame_equal(df4, expected3)
+
+ def test_loc_getitem_scalar_non_category(self, df):
+ with pytest.raises(KeyError, match="^1$"):
+ df.loc[1]
+
+ def test_slicing(self):
+ cat = Series(Categorical([1, 2, 3, 4]))
+ reverse = cat[::-1]
+ exp = np.array([4, 3, 2, 1], dtype=np.int64)
+ tm.assert_numpy_array_equal(reverse.__array__(), exp)
+
+ df = DataFrame({"value": (np.arange(100) + 1).astype("int64")})
+ df["D"] = pd.cut(df.value, bins=[0, 25, 50, 75, 100])
+
+ expected = Series([11, Interval(0, 25)], index=["value", "D"], name=10)
+ result = df.iloc[10]
+ tm.assert_series_equal(result, expected)
+
+ expected = DataFrame(
+ {"value": np.arange(11, 21).astype("int64")},
+ index=np.arange(10, 20).astype("int64"),
+ )
+ expected["D"] = pd.cut(expected.value, bins=[0, 25, 50, 75, 100])
+ result = df.iloc[10:20]
+ tm.assert_frame_equal(result, expected)
+
+ expected = Series([9, Interval(0, 25)], index=["value", "D"], name=8)
+ result = df.loc[8]
+ tm.assert_series_equal(result, expected)
+
+ def test_slicing_and_getting_ops(self):
+ # systematically test the slicing operations:
+ # for all slicing ops:
+ # - returning a dataframe
+ # - returning a column
+ # - returning a row
+ # - returning a single value
+
+ cats = Categorical(
+ ["a", "c", "b", "c", "c", "c", "c"], categories=["a", "b", "c"]
+ )
+ idx = Index(["h", "i", "j", "k", "l", "m", "n"])
+ values = [1, 2, 3, 4, 5, 6, 7]
+ df = DataFrame({"cats": cats, "values": values}, index=idx)
+
+ # the expected values
+ cats2 = Categorical(["b", "c"], categories=["a", "b", "c"])
+ idx2 = Index(["j", "k"])
+ values2 = [3, 4]
+
+ # 2:4,: | "j":"k",:
+ exp_df = DataFrame({"cats": cats2, "values": values2}, index=idx2)
+
+ # :,"cats" | :,0
+ exp_col = Series(cats, index=idx, name="cats")
+
+ # "j",: | 2,:
+ exp_row = Series(["b", 3], index=["cats", "values"], dtype="object", name="j")
+
+ # "j","cats | 2,0
+ exp_val = "b"
+
+ # iloc
+ # frame
+ res_df = df.iloc[2:4, :]
+ tm.assert_frame_equal(res_df, exp_df)
+ assert isinstance(res_df["cats"].dtype, CategoricalDtype)
+
+ # row
+ res_row = df.iloc[2, :]
+ tm.assert_series_equal(res_row, exp_row)
+ assert isinstance(res_row["cats"], str)
+
+ # col
+ res_col = df.iloc[:, 0]
+ tm.assert_series_equal(res_col, exp_col)
+ assert isinstance(res_col.dtype, CategoricalDtype)
+
+ # single value
+ res_val = df.iloc[2, 0]
+ assert res_val == exp_val
+
+ # loc
+ # frame
+ res_df = df.loc["j":"k", :]
+ tm.assert_frame_equal(res_df, exp_df)
+ assert isinstance(res_df["cats"].dtype, CategoricalDtype)
+
+ # row
+ res_row = df.loc["j", :]
+ tm.assert_series_equal(res_row, exp_row)
+ assert isinstance(res_row["cats"], str)
+
+ # col
+ res_col = df.loc[:, "cats"]
+ tm.assert_series_equal(res_col, exp_col)
+ assert isinstance(res_col.dtype, CategoricalDtype)
+
+ # single value
+ res_val = df.loc["j", "cats"]
+ assert res_val == exp_val
+
+ # single value
+ res_val = df.loc["j", df.columns[0]]
+ assert res_val == exp_val
+
+ # iat
+ res_val = df.iat[2, 0]
+ assert res_val == exp_val
+
+ # at
+ res_val = df.at["j", "cats"]
+ assert res_val == exp_val
+
+ # fancy indexing
+ exp_fancy = df.iloc[[2]]
+
+ res_fancy = df[df["cats"] == "b"]
+ tm.assert_frame_equal(res_fancy, exp_fancy)
+ res_fancy = df[df["values"] == 3]
+ tm.assert_frame_equal(res_fancy, exp_fancy)
+
+ # get_value
+ res_val = df.at["j", "cats"]
+ assert res_val == exp_val
+
+ # i : int, slice, or sequence of integers
+ res_row = df.iloc[2]
+ tm.assert_series_equal(res_row, exp_row)
+ assert isinstance(res_row["cats"], str)
+
+ res_df = df.iloc[slice(2, 4)]
+ tm.assert_frame_equal(res_df, exp_df)
+ assert isinstance(res_df["cats"].dtype, CategoricalDtype)
+
+ res_df = df.iloc[[2, 3]]
+ tm.assert_frame_equal(res_df, exp_df)
+ assert isinstance(res_df["cats"].dtype, CategoricalDtype)
+
+ res_col = df.iloc[:, 0]
+ tm.assert_series_equal(res_col, exp_col)
+ assert isinstance(res_col.dtype, CategoricalDtype)
+
+ res_df = df.iloc[:, slice(0, 2)]
+ tm.assert_frame_equal(res_df, df)
+ assert isinstance(res_df["cats"].dtype, CategoricalDtype)
+
+ res_df = df.iloc[:, [0, 1]]
+ tm.assert_frame_equal(res_df, df)
+ assert isinstance(res_df["cats"].dtype, CategoricalDtype)
+
+ def test_slicing_doc_examples(self):
+ # GH 7918
+ cats = Categorical(
+ ["a", "b", "b", "b", "c", "c", "c"], categories=["a", "b", "c"]
+ )
+ idx = Index(["h", "i", "j", "k", "l", "m", "n"])
+ values = [1, 2, 2, 2, 3, 4, 5]
+ df = DataFrame({"cats": cats, "values": values}, index=idx)
+
+ result = df.iloc[2:4, :]
+ expected = DataFrame(
+ {
+ "cats": Categorical(["b", "b"], categories=["a", "b", "c"]),
+ "values": [2, 2],
+ },
+ index=["j", "k"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[2:4, :].dtypes
+ expected = Series(["category", "int64"], ["cats", "values"])
+ tm.assert_series_equal(result, expected)
+
+ result = df.loc["h":"j", "cats"]
+ expected = Series(
+ Categorical(["a", "b", "b"], categories=["a", "b", "c"]),
+ index=["h", "i", "j"],
+ name="cats",
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = df.loc["h":"j", df.columns[0:1]]
+ expected = DataFrame(
+ {"cats": Categorical(["a", "b", "b"], categories=["a", "b", "c"])},
+ index=["h", "i", "j"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_getitem_listlike_labels(self, df):
+ # list of labels
+ result = df.loc[["c", "a"]]
+ expected = df.iloc[[4, 0, 1, 5]]
+ tm.assert_frame_equal(result, expected, check_index_type=True)
+
+ def test_loc_getitem_listlike_unused_category(self, df2):
+ # GH#37901 a label that is in index.categories but not in index
+ # listlike containing an element in the categories but not in the values
+ with pytest.raises(KeyError, match=re.escape("['e'] not in index")):
+ df2.loc[["a", "b", "e"]]
+
+ def test_loc_getitem_label_unused_category(self, df2):
+ # element in the categories but not in the values
+ with pytest.raises(KeyError, match=r"^'e'$"):
+ df2.loc["e"]
+
+ def test_loc_getitem_non_category(self, df2):
+ # not all labels in the categories
+ with pytest.raises(KeyError, match=re.escape("['d'] not in index")):
+ df2.loc[["a", "d"]]
+
+ def test_loc_setitem_expansion_label_unused_category(self, df2):
+ # assigning with a label that is in the categories but not in the index
+ df = df2.copy()
+ df.loc["e"] = 20
+ result = df.loc[["a", "b", "e"]]
+ exp_index = CategoricalIndex(list("aaabbe"), categories=list("cabe"), name="B")
+ expected = DataFrame({"A": [0, 1, 5, 2, 3, 20]}, index=exp_index)
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_listlike_dtypes(self):
+ # GH 11586
+
+ # unique categories and codes
+ index = CategoricalIndex(["a", "b", "c"])
+ df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index)
+
+ # unique slice
+ res = df.loc[["a", "b"]]
+ exp_index = CategoricalIndex(["a", "b"], categories=index.categories)
+ exp = DataFrame({"A": [1, 2], "B": [4, 5]}, index=exp_index)
+ tm.assert_frame_equal(res, exp, check_index_type=True)
+
+ # duplicated slice
+ res = df.loc[["a", "a", "b"]]
+
+ exp_index = CategoricalIndex(["a", "a", "b"], categories=index.categories)
+ exp = DataFrame({"A": [1, 1, 2], "B": [4, 4, 5]}, index=exp_index)
+ tm.assert_frame_equal(res, exp, check_index_type=True)
+
+ with pytest.raises(KeyError, match=re.escape("['x'] not in index")):
+ df.loc[["a", "x"]]
+
+ def test_loc_listlike_dtypes_duplicated_categories_and_codes(self):
+ # duplicated categories and codes
+ index = CategoricalIndex(["a", "b", "a"])
+ df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index)
+
+ # unique slice
+ res = df.loc[["a", "b"]]
+ exp = DataFrame(
+ {"A": [1, 3, 2], "B": [4, 6, 5]}, index=CategoricalIndex(["a", "a", "b"])
+ )
+ tm.assert_frame_equal(res, exp, check_index_type=True)
+
+ # duplicated slice
+ res = df.loc[["a", "a", "b"]]
+ exp = DataFrame(
+ {"A": [1, 3, 1, 3, 2], "B": [4, 6, 4, 6, 5]},
+ index=CategoricalIndex(["a", "a", "a", "a", "b"]),
+ )
+ tm.assert_frame_equal(res, exp, check_index_type=True)
+
+ with pytest.raises(KeyError, match=re.escape("['x'] not in index")):
+ df.loc[["a", "x"]]
+
+ def test_loc_listlike_dtypes_unused_category(self):
+ # contains unused category
+ index = CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde"))
+ df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=index)
+
+ res = df.loc[["a", "b"]]
+ exp = DataFrame(
+ {"A": [1, 3, 2], "B": [5, 7, 6]},
+ index=CategoricalIndex(["a", "a", "b"], categories=list("abcde")),
+ )
+ tm.assert_frame_equal(res, exp, check_index_type=True)
+
+ # duplicated slice
+ res = df.loc[["a", "a", "b"]]
+ exp = DataFrame(
+ {"A": [1, 3, 1, 3, 2], "B": [5, 7, 5, 7, 6]},
+ index=CategoricalIndex(["a", "a", "a", "a", "b"], categories=list("abcde")),
+ )
+ tm.assert_frame_equal(res, exp, check_index_type=True)
+
+ with pytest.raises(KeyError, match=re.escape("['x'] not in index")):
+ df.loc[["a", "x"]]
+
+ def test_loc_getitem_listlike_unused_category_raises_keyerror(self):
+ # key that is an *unused* category raises
+ index = CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde"))
+ df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=index)
+
+ with pytest.raises(KeyError, match="e"):
+ # For comparison, check the scalar behavior
+ df.loc["e"]
+
+ with pytest.raises(KeyError, match=re.escape("['e'] not in index")):
+ df.loc[["a", "e"]]
+
+ def test_ix_categorical_index(self):
+ # GH 12531
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ index=list("ABC"),
+ columns=list("XYZ"),
+ )
+ cdf = df.copy()
+ cdf.index = CategoricalIndex(df.index)
+ cdf.columns = CategoricalIndex(df.columns)
+
+ expect = Series(df.loc["A", :], index=cdf.columns, name="A")
+ tm.assert_series_equal(cdf.loc["A", :], expect)
+
+ expect = Series(df.loc[:, "X"], index=cdf.index, name="X")
+ tm.assert_series_equal(cdf.loc[:, "X"], expect)
+
+ exp_index = CategoricalIndex(list("AB"), categories=["A", "B", "C"])
+ expect = DataFrame(df.loc[["A", "B"], :], columns=cdf.columns, index=exp_index)
+ tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect)
+
+ exp_columns = CategoricalIndex(list("XY"), categories=["X", "Y", "Z"])
+ expect = DataFrame(df.loc[:, ["X", "Y"]], index=cdf.index, columns=exp_columns)
+ tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect)
+
+ def test_ix_categorical_index_non_unique(self):
+ # non-unique
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ index=list("ABA"),
+ columns=list("XYX"),
+ )
+ cdf = df.copy()
+ cdf.index = CategoricalIndex(df.index)
+ cdf.columns = CategoricalIndex(df.columns)
+
+ exp_index = CategoricalIndex(list("AA"), categories=["A", "B"])
+ expect = DataFrame(df.loc["A", :], columns=cdf.columns, index=exp_index)
+ tm.assert_frame_equal(cdf.loc["A", :], expect)
+
+ exp_columns = CategoricalIndex(list("XX"), categories=["X", "Y"])
+ expect = DataFrame(df.loc[:, "X"], index=cdf.index, columns=exp_columns)
+ tm.assert_frame_equal(cdf.loc[:, "X"], expect)
+
+ expect = DataFrame(
+ df.loc[["A", "B"], :],
+ columns=cdf.columns,
+ index=CategoricalIndex(list("AAB")),
+ )
+ tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect)
+
+ expect = DataFrame(
+ df.loc[:, ["X", "Y"]],
+ index=cdf.index,
+ columns=CategoricalIndex(list("XXY")),
+ )
+ tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect)
+
+ def test_loc_slice(self, df):
+ # GH9748
+ msg = (
+ "cannot do slice indexing on CategoricalIndex with these "
+ r"indexers \[1\] of type int"
+ )
+ with pytest.raises(TypeError, match=msg):
+ df.loc[1:5]
+
+ result = df.loc["b":"c"]
+ expected = df.iloc[[2, 3, 4]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_and_at_with_categorical_index(self):
+ # GH 20629
+ df = DataFrame(
+ [[1, 2], [3, 4], [5, 6]], index=CategoricalIndex(["A", "B", "C"])
+ )
+
+ s = df[0]
+ assert s.loc["A"] == 1
+ assert s.at["A"] == 1
+
+ assert df.loc["B", 1] == 4
+ assert df.at["B", 1] == 4
+
+ @pytest.mark.parametrize(
+ "idx_values",
+ [
+ # python types
+ [1, 2, 3],
+ [-1, -2, -3],
+ [1.5, 2.5, 3.5],
+ [-1.5, -2.5, -3.5],
+ # numpy int/uint
+ *(np.array([1, 2, 3], dtype=dtype) for dtype in tm.ALL_INT_NUMPY_DTYPES),
+ # numpy floats
+ *(np.array([1.5, 2.5, 3.5], dtype=dtyp) for dtyp in tm.FLOAT_NUMPY_DTYPES),
+ # numpy object
+ np.array([1, "b", 3.5], dtype=object),
+ # pandas scalars
+ [Interval(1, 4), Interval(4, 6), Interval(6, 9)],
+ [Timestamp(2019, 1, 1), Timestamp(2019, 2, 1), Timestamp(2019, 3, 1)],
+ [Timedelta(1, "d"), Timedelta(2, "d"), Timedelta(3, "D")],
+ # pandas Integer arrays
+ *(pd.array([1, 2, 3], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES),
+ # other pandas arrays
+ pd.IntervalIndex.from_breaks([1, 4, 6, 9]).array,
+ pd.date_range("2019-01-01", periods=3).array,
+ pd.timedelta_range(start="1d", periods=3).array,
+ ],
+ )
+ def test_loc_getitem_with_non_string_categories(self, idx_values, ordered):
+ # GH-17569
+ cat_idx = CategoricalIndex(idx_values, ordered=ordered)
+ df = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx)
+ sl = slice(idx_values[0], idx_values[1])
+
+ # scalar selection
+ result = df.loc[idx_values[0]]
+ expected = Series(["foo"], index=["A"], name=idx_values[0])
+ tm.assert_series_equal(result, expected)
+
+ # list selection
+ result = df.loc[idx_values[:2]]
+ expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"])
+ tm.assert_frame_equal(result, expected)
+
+ # slice selection
+ result = df.loc[sl]
+ expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"])
+ tm.assert_frame_equal(result, expected)
+
+ # scalar assignment
+ result = df.copy()
+ result.loc[idx_values[0]] = "qux"
+ expected = DataFrame({"A": ["qux", "bar", "baz"]}, index=cat_idx)
+ tm.assert_frame_equal(result, expected)
+
+ # list assignment
+ result = df.copy()
+ result.loc[idx_values[:2], "A"] = ["qux", "qux2"]
+ expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx)
+ tm.assert_frame_equal(result, expected)
+
+ # slice assignment
+ result = df.copy()
+ result.loc[sl, "A"] = ["qux", "qux2"]
+ expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx)
+ tm.assert_frame_equal(result, expected)
+
+ def test_getitem_categorical_with_nan(self):
+ # GH#41933
+ ci = CategoricalIndex(["A", "B", np.nan])
+
+ ser = Series(range(3), index=ci)
+
+ assert ser[np.nan] == 2
+ assert ser.loc[np.nan] == 2
+
+ df = DataFrame(ser)
+ assert df.loc[np.nan, 0] == 2
+ assert df.loc[np.nan][0] == 2
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_chaining_and_caching.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_chaining_and_caching.py
new file mode 100644
index 0000000000000000000000000000000000000000..f36fdf0d36ea94760baefb317729a7b6505490be
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_chaining_and_caching.py
@@ -0,0 +1,631 @@
+from string import ascii_letters as letters
+
+import numpy as np
+import pytest
+
+from pandas.errors import (
+ SettingWithCopyError,
+ SettingWithCopyWarning,
+)
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+ date_range,
+ option_context,
+)
+import pandas._testing as tm
+
+msg = "A value is trying to be set on a copy of a slice from a DataFrame"
+
+
+def random_text(nobs=100):
+ # Construct a DataFrame where each row is a random slice from 'letters'
+ idxs = np.random.default_rng(2).integers(len(letters), size=(nobs, 2))
+ idxs.sort(axis=1)
+ strings = [letters[x[0] : x[1]] for x in idxs]
+
+ return DataFrame(strings, columns=["letters"])
+
+
+class TestCaching:
+ def test_slice_consolidate_invalidate_item_cache(self, using_copy_on_write):
+ # this is chained assignment, but will 'work'
+ with option_context("chained_assignment", None):
+ # #3970
+ df = DataFrame({"aa": np.arange(5), "bb": [2.2] * 5})
+
+ # Creates a second float block
+ df["cc"] = 0.0
+
+ # caches a reference to the 'bb' series
+ df["bb"]
+
+ # repr machinery triggers consolidation
+ repr(df)
+
+ # Assignment to wrong series
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["bb"].iloc[0] = 0.17
+ else:
+ df["bb"].iloc[0] = 0.17
+ df._clear_item_cache()
+ if not using_copy_on_write:
+ tm.assert_almost_equal(df["bb"][0], 0.17)
+ else:
+ # with ArrayManager, parent is not mutated with chained assignment
+ tm.assert_almost_equal(df["bb"][0], 2.2)
+
+ @pytest.mark.parametrize("do_ref", [True, False])
+ def test_setitem_cache_updating(self, do_ref):
+ # GH 5424
+ cont = ["one", "two", "three", "four", "five", "six", "seven"]
+
+ df = DataFrame({"a": cont, "b": cont[3:] + cont[:3], "c": np.arange(7)})
+
+ # ref the cache
+ if do_ref:
+ df.loc[0, "c"]
+
+ # set it
+ df.loc[7, "c"] = 1
+
+ assert df.loc[0, "c"] == 0.0
+ assert df.loc[7, "c"] == 1.0
+
+ def test_setitem_cache_updating_slices(self, using_copy_on_write):
+ # GH 7084
+ # not updating cache on series setting with slices
+ expected = DataFrame(
+ {"A": [600, 600, 600]}, index=date_range("5/7/2014", "5/9/2014")
+ )
+ out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014"))
+ df = DataFrame({"C": ["A", "A", "A"], "D": [100, 200, 300]})
+
+ # loop through df to update out
+ six = Timestamp("5/7/2014")
+ eix = Timestamp("5/9/2014")
+ for ix, row in df.iterrows():
+ out.loc[six:eix, row["C"]] = out.loc[six:eix, row["C"]] + row["D"]
+
+ tm.assert_frame_equal(out, expected)
+ tm.assert_series_equal(out["A"], expected["A"])
+
+ # try via a chain indexing
+ # this actually works
+ out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014"))
+ out_original = out.copy()
+ for ix, row in df.iterrows():
+ v = out[row["C"]][six:eix] + row["D"]
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ out[row["C"]][six:eix] = v
+ else:
+ out[row["C"]][six:eix] = v
+
+ if not using_copy_on_write:
+ tm.assert_frame_equal(out, expected)
+ tm.assert_series_equal(out["A"], expected["A"])
+ else:
+ tm.assert_frame_equal(out, out_original)
+ tm.assert_series_equal(out["A"], out_original["A"])
+
+ out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014"))
+ for ix, row in df.iterrows():
+ out.loc[six:eix, row["C"]] += row["D"]
+
+ tm.assert_frame_equal(out, expected)
+ tm.assert_series_equal(out["A"], expected["A"])
+
+ def test_altering_series_clears_parent_cache(self, using_copy_on_write):
+ # GH #33675
+ df = DataFrame([[1, 2], [3, 4]], index=["a", "b"], columns=["A", "B"])
+ ser = df["A"]
+
+ if using_copy_on_write:
+ assert "A" not in df._item_cache
+ else:
+ assert "A" in df._item_cache
+
+ # Adding a new entry to ser swaps in a new array, so "A" needs to
+ # be removed from df._item_cache
+ ser["c"] = 5
+ assert len(ser) == 3
+ assert "A" not in df._item_cache
+ assert df["A"] is not ser
+ assert len(df["A"]) == 2
+
+
+class TestChaining:
+ def test_setitem_chained_setfault(self, using_copy_on_write):
+ # GH6026
+ data = ["right", "left", "left", "left", "right", "left", "timeout"]
+ mdata = ["right", "left", "left", "left", "right", "left", "none"]
+
+ df = DataFrame({"response": np.array(data)})
+ mask = df.response == "timeout"
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df.response[mask] = "none"
+ tm.assert_frame_equal(df, DataFrame({"response": data}))
+ else:
+ df.response[mask] = "none"
+ tm.assert_frame_equal(df, DataFrame({"response": mdata}))
+
+ recarray = np.rec.fromarrays([data], names=["response"])
+ df = DataFrame(recarray)
+ mask = df.response == "timeout"
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df.response[mask] = "none"
+ tm.assert_frame_equal(df, DataFrame({"response": data}))
+ else:
+ df.response[mask] = "none"
+ tm.assert_frame_equal(df, DataFrame({"response": mdata}))
+
+ df = DataFrame({"response": data, "response1": data})
+ df_original = df.copy()
+ mask = df.response == "timeout"
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df.response[mask] = "none"
+ tm.assert_frame_equal(df, df_original)
+ else:
+ df.response[mask] = "none"
+ tm.assert_frame_equal(df, DataFrame({"response": mdata, "response1": data}))
+
+ # GH 6056
+ expected = DataFrame({"A": [np.nan, "bar", "bah", "foo", "bar"]})
+ df = DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])})
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["A"].iloc[0] = np.nan
+ expected = DataFrame({"A": ["foo", "bar", "bah", "foo", "bar"]})
+ else:
+ df["A"].iloc[0] = np.nan
+ expected = DataFrame({"A": [np.nan, "bar", "bah", "foo", "bar"]})
+ result = df.head()
+ tm.assert_frame_equal(result, expected)
+
+ df = DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])})
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df.A.iloc[0] = np.nan
+ else:
+ df.A.iloc[0] = np.nan
+ result = df.head()
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment(self, using_copy_on_write):
+ with option_context("chained_assignment", "raise"):
+ # work with the chain
+ expected = DataFrame([[-5, 1], [-6, 3]], columns=list("AB"))
+ df = DataFrame(
+ np.arange(4).reshape(2, 2), columns=list("AB"), dtype="int64"
+ )
+ df_original = df.copy()
+ assert df._is_copy is None
+
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["A"][0] = -5
+ with tm.raises_chained_assignment_error():
+ df["A"][1] = -6
+ tm.assert_frame_equal(df, df_original)
+ else:
+ df["A"][0] = -5
+ df["A"][1] = -6
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_raises(
+ self, using_array_manager, using_copy_on_write
+ ):
+ # test with the chaining
+ df = DataFrame(
+ {
+ "A": Series(range(2), dtype="int64"),
+ "B": np.array(np.arange(2, 4), dtype=np.float64),
+ }
+ )
+ df_original = df.copy()
+ assert df._is_copy is None
+
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["A"][0] = -5
+ with tm.raises_chained_assignment_error():
+ df["A"][1] = -6
+ tm.assert_frame_equal(df, df_original)
+ elif not using_array_manager:
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df["A"][0] = -5
+
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df["A"][1] = np.nan
+
+ assert df["A"]._is_copy is None
+ else:
+ # INFO(ArrayManager) for ArrayManager it doesn't matter that it's
+ # a mixed dataframe
+ df["A"][0] = -5
+ df["A"][1] = -6
+ expected = DataFrame([[-5, 2], [-6, 3]], columns=list("AB"))
+ expected["B"] = expected["B"].astype("float64")
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_fails(self, using_copy_on_write):
+ # Using a copy (the chain), fails
+ df = DataFrame(
+ {
+ "A": Series(range(2), dtype="int64"),
+ "B": np.array(np.arange(2, 4), dtype=np.float64),
+ }
+ )
+
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df.loc[0]["A"] = -5
+ else:
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df.loc[0]["A"] = -5
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_doc_example(self, using_copy_on_write):
+ # Doc example
+ df = DataFrame(
+ {
+ "a": ["one", "one", "two", "three", "two", "one", "six"],
+ "c": Series(range(7), dtype="int64"),
+ }
+ )
+ assert df._is_copy is None
+
+ if using_copy_on_write:
+ indexer = df.a.str.startswith("o")
+ with tm.raises_chained_assignment_error():
+ df[indexer]["c"] = 42
+ else:
+ with pytest.raises(SettingWithCopyError, match=msg):
+ indexer = df.a.str.startswith("o")
+ df[indexer]["c"] = 42
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_object_dtype(
+ self, using_array_manager, using_copy_on_write
+ ):
+ expected = DataFrame({"A": [111, "bbb", "ccc"], "B": [1, 2, 3]})
+ df = DataFrame({"A": ["aaa", "bbb", "ccc"], "B": [1, 2, 3]})
+ df_original = df.copy()
+
+ if not using_copy_on_write:
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df.loc[0]["A"] = 111
+
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["A"][0] = 111
+ tm.assert_frame_equal(df, df_original)
+ elif not using_array_manager:
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df["A"][0] = 111
+
+ df.loc[0, "A"] = 111
+ tm.assert_frame_equal(df, expected)
+ else:
+ # INFO(ArrayManager) for ArrayManager it doesn't matter that it's
+ # a mixed dataframe
+ df["A"][0] = 111
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_is_copy_pickle(self):
+ # gh-5475: Make sure that is_copy is picked up reconstruction
+ df = DataFrame({"A": [1, 2]})
+ assert df._is_copy is None
+
+ with tm.ensure_clean("__tmp__pickle") as path:
+ df.to_pickle(path)
+ df2 = pd.read_pickle(path)
+ df2["B"] = df2["A"]
+ df2["B"] = df2["A"]
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_setting_entire_column(self):
+ # gh-5597: a spurious raise as we are setting the entire column here
+
+ df = random_text(100000)
+
+ # Always a copy
+ x = df.iloc[[0, 1, 2]]
+ assert x._is_copy is not None
+
+ x = df.iloc[[0, 1, 2, 4]]
+ assert x._is_copy is not None
+
+ # Explicitly copy
+ indexer = df.letters.apply(lambda x: len(x) > 10)
+ df = df.loc[indexer].copy()
+
+ assert df._is_copy is None
+ df["letters"] = df["letters"].apply(str.lower)
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_implicit_take(self):
+ # Implicitly take
+ df = random_text(100000)
+ indexer = df.letters.apply(lambda x: len(x) > 10)
+ df = df.loc[indexer]
+
+ assert df._is_copy is not None
+ df["letters"] = df["letters"].apply(str.lower)
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_implicit_take2(self, using_copy_on_write):
+ if using_copy_on_write:
+ pytest.skip("_is_copy is not always set for CoW")
+ # Implicitly take 2
+ df = random_text(100000)
+ indexer = df.letters.apply(lambda x: len(x) > 10)
+
+ df = df.loc[indexer]
+ assert df._is_copy is not None
+ df.loc[:, "letters"] = df["letters"].apply(str.lower)
+
+ # with the enforcement of #45333 in 2.0, the .loc[:, letters] setting
+ # is inplace, so df._is_copy remains non-None.
+ assert df._is_copy is not None
+
+ df["letters"] = df["letters"].apply(str.lower)
+ assert df._is_copy is None
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_str(self):
+ df = random_text(100000)
+ indexer = df.letters.apply(lambda x: len(x) > 10)
+ df.loc[indexer, "letters"] = df.loc[indexer, "letters"].apply(str.lower)
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_is_copy(self):
+ # an identical take, so no copy
+ df = DataFrame({"a": [1]}).dropna()
+ assert df._is_copy is None
+ df["a"] += 1
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_sorting(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
+ ser = df.iloc[:, 0].sort_values()
+
+ tm.assert_series_equal(ser, df.iloc[:, 0].sort_values())
+ tm.assert_series_equal(ser, df[0].sort_values())
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_false_positives(self):
+ # see gh-6025: false positives
+ df = DataFrame({"column1": ["a", "a", "a"], "column2": [4, 8, 9]})
+ str(df)
+
+ df["column1"] = df["column1"] + "b"
+ str(df)
+
+ df = df[df["column2"] != 8]
+ str(df)
+
+ df["column1"] = df["column1"] + "c"
+ str(df)
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_undefined_column(self, using_copy_on_write):
+ # from SO:
+ # https://stackoverflow.com/questions/24054495/potential-bug-setting-value-for-undefined-column-using-iloc
+ df = DataFrame(np.arange(0, 9), columns=["count"])
+ df["group"] = "b"
+ df_original = df.copy()
+
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df.iloc[0:5]["group"] = "a"
+ tm.assert_frame_equal(df, df_original)
+ else:
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df.iloc[0:5]["group"] = "a"
+
+ @pytest.mark.arm_slow
+ def test_detect_chained_assignment_changing_dtype(
+ self, using_array_manager, using_copy_on_write
+ ):
+ # Mixed type setting but same dtype & changing dtype
+ df = DataFrame(
+ {
+ "A": date_range("20130101", periods=5),
+ "B": np.random.default_rng(2).standard_normal(5),
+ "C": np.arange(5, dtype="int64"),
+ "D": ["a", "b", "c", "d", "e"],
+ }
+ )
+ df_original = df.copy()
+
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df.loc[2]["D"] = "foo"
+ with tm.raises_chained_assignment_error():
+ df.loc[2]["C"] = "foo"
+ with tm.raises_chained_assignment_error(extra_warnings=(FutureWarning,)):
+ df["C"][2] = "foo"
+ tm.assert_frame_equal(df, df_original)
+
+ if not using_copy_on_write:
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df.loc[2]["D"] = "foo"
+
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df.loc[2]["C"] = "foo"
+
+ if not using_array_manager:
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df["C"][2] = "foo"
+ else:
+ # INFO(ArrayManager) for ArrayManager it doesn't matter if it's
+ # changing the dtype or not
+ df["C"][2] = "foo"
+ assert df.loc[2, "C"] == "foo"
+
+ def test_setting_with_copy_bug(self, using_copy_on_write):
+ # operating on a copy
+ df = DataFrame(
+ {"a": list(range(4)), "b": list("ab.."), "c": ["a", "b", np.nan, "d"]}
+ )
+ df_original = df.copy()
+ mask = pd.isna(df.c)
+
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df[["c"]][mask] = df[["b"]][mask]
+ tm.assert_frame_equal(df, df_original)
+ else:
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df[["c"]][mask] = df[["b"]][mask]
+
+ def test_setting_with_copy_bug_no_warning(self):
+ # invalid warning as we are returning a new object
+ # GH 8730
+ df1 = DataFrame({"x": Series(["a", "b", "c"]), "y": Series(["d", "e", "f"])})
+ df2 = df1[["x"]]
+
+ # this should not raise
+ df2["y"] = ["g", "h", "i"]
+
+ def test_detect_chained_assignment_warnings_errors(self, using_copy_on_write):
+ df = DataFrame({"A": ["aaa", "bbb", "ccc"], "B": [1, 2, 3]})
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df.loc[0]["A"] = 111
+ return
+
+ with option_context("chained_assignment", "warn"):
+ with tm.assert_produces_warning(SettingWithCopyWarning):
+ df.loc[0]["A"] = 111
+
+ with option_context("chained_assignment", "raise"):
+ with pytest.raises(SettingWithCopyError, match=msg):
+ df.loc[0]["A"] = 111
+
+ @pytest.mark.parametrize("rhs", [3, DataFrame({0: [1, 2, 3, 4]})])
+ def test_detect_chained_assignment_warning_stacklevel(
+ self, rhs, using_copy_on_write
+ ):
+ # GH#42570
+ df = DataFrame(np.arange(25).reshape(5, 5))
+ df_original = df.copy()
+ chained = df.loc[:3]
+ with option_context("chained_assignment", "warn"):
+ if not using_copy_on_write:
+ with tm.assert_produces_warning(SettingWithCopyWarning) as t:
+ chained[2] = rhs
+ assert t[0].filename == __file__
+ else:
+ # INFO(CoW) no warning, and original dataframe not changed
+ with tm.assert_produces_warning(None):
+ chained[2] = rhs
+ tm.assert_frame_equal(df, df_original)
+
+ # TODO(ArrayManager) fast_xs with array-like scalars is not yet working
+ @td.skip_array_manager_not_yet_implemented
+ def test_chained_getitem_with_lists(self):
+ # GH6394
+ # Regression in chained getitem indexing with embedded list-like from
+ # 0.12
+
+ df = DataFrame({"A": 5 * [np.zeros(3)], "B": 5 * [np.ones(3)]})
+ expected = df["A"].iloc[2]
+ result = df.loc[2, "A"]
+ tm.assert_numpy_array_equal(result, expected)
+ result2 = df.iloc[2]["A"]
+ tm.assert_numpy_array_equal(result2, expected)
+ result3 = df["A"].loc[2]
+ tm.assert_numpy_array_equal(result3, expected)
+ result4 = df["A"].iloc[2]
+ tm.assert_numpy_array_equal(result4, expected)
+
+ def test_cache_updating(self):
+ # GH 4939, make sure to update the cache on setitem
+
+ df = tm.makeDataFrame()
+ df["A"] # cache series
+ df.loc["Hello Friend"] = df.iloc[0]
+ assert "Hello Friend" in df["A"].index
+ assert "Hello Friend" in df["B"].index
+
+ def test_cache_updating2(self, using_copy_on_write):
+ # 10264
+ df = DataFrame(
+ np.zeros((5, 5), dtype="int64"),
+ columns=["a", "b", "c", "d", "e"],
+ index=range(5),
+ )
+ df["f"] = 0
+ df_orig = df.copy()
+ if using_copy_on_write:
+ with pytest.raises(ValueError, match="read-only"):
+ df.f.values[3] = 1
+ tm.assert_frame_equal(df, df_orig)
+ return
+
+ df.f.values[3] = 1
+
+ df.f.values[3] = 2
+ expected = DataFrame(
+ np.zeros((5, 6), dtype="int64"),
+ columns=["a", "b", "c", "d", "e", "f"],
+ index=range(5),
+ )
+ expected.at[3, "f"] = 2
+ tm.assert_frame_equal(df, expected)
+ expected = Series([0, 0, 0, 2, 0], name="f")
+ tm.assert_series_equal(df.f, expected)
+
+ def test_iloc_setitem_chained_assignment(self, using_copy_on_write):
+ # GH#3970
+ with option_context("chained_assignment", None):
+ df = DataFrame({"aa": range(5), "bb": [2.2] * 5})
+ df["cc"] = 0.0
+
+ ck = [True] * len(df)
+
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["bb"].iloc[0] = 0.13
+ else:
+ df["bb"].iloc[0] = 0.13
+
+ # GH#3970 this lookup used to break the chained setting to 0.15
+ df.iloc[ck]
+
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["bb"].iloc[0] = 0.15
+ else:
+ df["bb"].iloc[0] = 0.15
+
+ if not using_copy_on_write:
+ assert df["bb"].iloc[0] == 0.15
+ else:
+ assert df["bb"].iloc[0] == 2.2
+
+ def test_getitem_loc_assignment_slice_state(self, using_copy_on_write):
+ # GH 13569
+ df = DataFrame({"a": [10, 20, 30]})
+ if using_copy_on_write:
+ with tm.raises_chained_assignment_error():
+ df["a"].loc[4] = 40
+ else:
+ df["a"].loc[4] = 40
+ tm.assert_frame_equal(df, DataFrame({"a": [10, 20, 30]}))
+ tm.assert_series_equal(df["a"], Series([10, 20, 30], name="a"))
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_check_indexer.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_check_indexer.py
new file mode 100644
index 0000000000000000000000000000000000000000..975a31b873792c6afe59a23e5fef43b56ce7e46e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_check_indexer.py
@@ -0,0 +1,105 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.api.indexers import check_array_indexer
+
+
+@pytest.mark.parametrize(
+ "indexer, expected",
+ [
+ # integer
+ ([1, 2], np.array([1, 2], dtype=np.intp)),
+ (np.array([1, 2], dtype="int64"), np.array([1, 2], dtype=np.intp)),
+ (pd.array([1, 2], dtype="Int32"), np.array([1, 2], dtype=np.intp)),
+ (pd.Index([1, 2]), np.array([1, 2], dtype=np.intp)),
+ # boolean
+ ([True, False, True], np.array([True, False, True], dtype=np.bool_)),
+ (np.array([True, False, True]), np.array([True, False, True], dtype=np.bool_)),
+ (
+ pd.array([True, False, True], dtype="boolean"),
+ np.array([True, False, True], dtype=np.bool_),
+ ),
+ # other
+ ([], np.array([], dtype=np.intp)),
+ ],
+)
+def test_valid_input(indexer, expected):
+ arr = np.array([1, 2, 3])
+ result = check_array_indexer(arr, indexer)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "indexer", [[True, False, None], pd.array([True, False, None], dtype="boolean")]
+)
+def test_boolean_na_returns_indexer(indexer):
+ # https://github.com/pandas-dev/pandas/issues/31503
+ arr = np.array([1, 2, 3])
+
+ result = check_array_indexer(arr, indexer)
+ expected = np.array([True, False, False], dtype=bool)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "indexer",
+ [
+ [True, False],
+ pd.array([True, False], dtype="boolean"),
+ np.array([True, False], dtype=np.bool_),
+ ],
+)
+def test_bool_raise_length(indexer):
+ arr = np.array([1, 2, 3])
+
+ msg = "Boolean index has wrong length"
+ with pytest.raises(IndexError, match=msg):
+ check_array_indexer(arr, indexer)
+
+
+@pytest.mark.parametrize(
+ "indexer", [[0, 1, None], pd.array([0, 1, pd.NA], dtype="Int64")]
+)
+def test_int_raise_missing_values(indexer):
+ arr = np.array([1, 2, 3])
+
+ msg = "Cannot index with an integer indexer containing NA values"
+ with pytest.raises(ValueError, match=msg):
+ check_array_indexer(arr, indexer)
+
+
+@pytest.mark.parametrize(
+ "indexer",
+ [
+ [0.0, 1.0],
+ np.array([1.0, 2.0], dtype="float64"),
+ np.array([True, False], dtype=object),
+ pd.Index([True, False], dtype=object),
+ ],
+)
+def test_raise_invalid_array_dtypes(indexer):
+ arr = np.array([1, 2, 3])
+
+ msg = "arrays used as indices must be of integer or boolean type"
+ with pytest.raises(IndexError, match=msg):
+ check_array_indexer(arr, indexer)
+
+
+def test_raise_nullable_string_dtype(nullable_string_dtype):
+ indexer = pd.array(["a", "b"], dtype=nullable_string_dtype)
+ arr = np.array([1, 2, 3])
+
+ msg = "arrays used as indices must be of integer or boolean type"
+ with pytest.raises(IndexError, match=msg):
+ check_array_indexer(arr, indexer)
+
+
+@pytest.mark.parametrize("indexer", [None, Ellipsis, slice(0, 3), (None,)])
+def test_pass_through_non_array_likes(indexer):
+ arr = np.array([1, 2, 3])
+
+ result = check_array_indexer(arr, indexer)
+ assert result == indexer
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_coercion.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_coercion.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c39729097487993f542152aa394ab956b2aba1f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_coercion.py
@@ -0,0 +1,906 @@
+from __future__ import annotations
+
+from datetime import (
+ datetime,
+ timedelta,
+)
+import itertools
+
+import numpy as np
+import pytest
+
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
+
+import pandas as pd
+import pandas._testing as tm
+
+###############################################################
+# Index / Series common tests which may trigger dtype coercions
+###############################################################
+
+
+@pytest.fixture(autouse=True, scope="class")
+def check_comprehensiveness(request):
+ # Iterate over combination of dtype, method and klass
+ # and ensure that each are contained within a collected test
+ cls = request.cls
+ combos = itertools.product(cls.klasses, cls.dtypes, [cls.method])
+
+ def has_test(combo):
+ klass, dtype, method = combo
+ cls_funcs = request.node.session.items
+ return any(
+ klass in x.name and dtype in x.name and method in x.name for x in cls_funcs
+ )
+
+ opts = request.config.option
+ if opts.lf or opts.keyword:
+ # If we are running with "last-failed" or -k foo, we expect to only
+ # run a subset of tests.
+ yield
+
+ else:
+ for combo in combos:
+ if not has_test(combo):
+ raise AssertionError(
+ f"test method is not defined: {cls.__name__}, {combo}"
+ )
+
+ yield
+
+
+class CoercionBase:
+ klasses = ["index", "series"]
+ dtypes = [
+ "object",
+ "int64",
+ "float64",
+ "complex128",
+ "bool",
+ "datetime64",
+ "datetime64tz",
+ "timedelta64",
+ "period",
+ ]
+
+ @property
+ def method(self):
+ raise NotImplementedError(self)
+
+
+class TestSetitemCoercion(CoercionBase):
+ method = "setitem"
+
+ # disable comprehensiveness tests, as most of these have been moved to
+ # tests.series.indexing.test_setitem in SetitemCastingEquivalents subclasses.
+ klasses: list[str] = []
+
+ def test_setitem_series_no_coercion_from_values_list(self):
+ # GH35865 - int casted to str when internally calling np.array(ser.values)
+ ser = pd.Series(["a", 1])
+ ser[:] = list(ser.values)
+
+ expected = pd.Series(["a", 1])
+
+ tm.assert_series_equal(ser, expected)
+
+ def _assert_setitem_index_conversion(
+ self, original_series, loc_key, expected_index, expected_dtype
+ ):
+ """test index's coercion triggered by assign key"""
+ temp = original_series.copy()
+ # GH#33469 pre-2.0 with int loc_key and temp.index.dtype == np.float64
+ # `temp[loc_key] = 5` treated loc_key as positional
+ temp[loc_key] = 5
+ exp = pd.Series([1, 2, 3, 4, 5], index=expected_index)
+ tm.assert_series_equal(temp, exp)
+ # check dtype explicitly for sure
+ assert temp.index.dtype == expected_dtype
+
+ temp = original_series.copy()
+ temp.loc[loc_key] = 5
+ exp = pd.Series([1, 2, 3, 4, 5], index=expected_index)
+ tm.assert_series_equal(temp, exp)
+ # check dtype explicitly for sure
+ assert temp.index.dtype == expected_dtype
+
+ @pytest.mark.parametrize(
+ "val,exp_dtype", [("x", object), (5, IndexError), (1.1, object)]
+ )
+ def test_setitem_index_object(self, val, exp_dtype):
+ obj = pd.Series([1, 2, 3, 4], index=list("abcd"))
+ assert obj.index.dtype == object
+
+ if exp_dtype is IndexError:
+ temp = obj.copy()
+ warn_msg = "Series.__setitem__ treating keys as positions is deprecated"
+ msg = "index 5 is out of bounds for axis 0 with size 4"
+ with pytest.raises(exp_dtype, match=msg):
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ temp[5] = 5
+ else:
+ exp_index = pd.Index(list("abcd") + [val])
+ self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
+
+ @pytest.mark.parametrize(
+ "val,exp_dtype", [(5, np.int64), (1.1, np.float64), ("x", object)]
+ )
+ def test_setitem_index_int64(self, val, exp_dtype):
+ obj = pd.Series([1, 2, 3, 4])
+ assert obj.index.dtype == np.int64
+
+ exp_index = pd.Index([0, 1, 2, 3, val])
+ self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
+
+ @pytest.mark.parametrize(
+ "val,exp_dtype", [(5, np.float64), (5.1, np.float64), ("x", object)]
+ )
+ def test_setitem_index_float64(self, val, exp_dtype, request):
+ obj = pd.Series([1, 2, 3, 4], index=[1.1, 2.1, 3.1, 4.1])
+ assert obj.index.dtype == np.float64
+
+ exp_index = pd.Index([1.1, 2.1, 3.1, 4.1, val])
+ self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_setitem_series_period(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_setitem_index_complex128(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_setitem_index_bool(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_setitem_index_datetime64(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_setitem_index_datetime64tz(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_setitem_index_timedelta64(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_setitem_index_period(self):
+ raise NotImplementedError
+
+
+class TestInsertIndexCoercion(CoercionBase):
+ klasses = ["index"]
+ method = "insert"
+
+ def _assert_insert_conversion(self, original, value, expected, expected_dtype):
+ """test coercion triggered by insert"""
+ target = original.copy()
+ res = target.insert(1, value)
+ tm.assert_index_equal(res, expected)
+ assert res.dtype == expected_dtype
+
+ @pytest.mark.parametrize(
+ "insert, coerced_val, coerced_dtype",
+ [
+ (1, 1, object),
+ (1.1, 1.1, object),
+ (False, False, object),
+ ("x", "x", object),
+ ],
+ )
+ def test_insert_index_object(self, insert, coerced_val, coerced_dtype):
+ obj = pd.Index(list("abcd"))
+ assert obj.dtype == object
+
+ exp = pd.Index(["a", coerced_val, "b", "c", "d"])
+ self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
+
+ @pytest.mark.parametrize(
+ "insert, coerced_val, coerced_dtype",
+ [
+ (1, 1, None),
+ (1.1, 1.1, np.float64),
+ (False, False, object), # GH#36319
+ ("x", "x", object),
+ ],
+ )
+ def test_insert_int_index(
+ self, any_int_numpy_dtype, insert, coerced_val, coerced_dtype
+ ):
+ dtype = any_int_numpy_dtype
+ obj = pd.Index([1, 2, 3, 4], dtype=dtype)
+ coerced_dtype = coerced_dtype if coerced_dtype is not None else dtype
+
+ exp = pd.Index([1, coerced_val, 2, 3, 4], dtype=coerced_dtype)
+ self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
+
+ @pytest.mark.parametrize(
+ "insert, coerced_val, coerced_dtype",
+ [
+ (1, 1.0, None),
+ (1.1, 1.1, np.float64),
+ (False, False, object), # GH#36319
+ ("x", "x", object),
+ ],
+ )
+ def test_insert_float_index(
+ self, float_numpy_dtype, insert, coerced_val, coerced_dtype
+ ):
+ dtype = float_numpy_dtype
+ obj = pd.Index([1.0, 2.0, 3.0, 4.0], dtype=dtype)
+ coerced_dtype = coerced_dtype if coerced_dtype is not None else dtype
+
+ exp = pd.Index([1.0, coerced_val, 2.0, 3.0, 4.0], dtype=coerced_dtype)
+ self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,exp_dtype",
+ [
+ (pd.Timestamp("2012-01-01"), "datetime64[ns]"),
+ (pd.Timestamp("2012-01-01", tz="US/Eastern"), "datetime64[ns, US/Eastern]"),
+ ],
+ ids=["datetime64", "datetime64tz"],
+ )
+ @pytest.mark.parametrize(
+ "insert_value",
+ [pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), 1],
+ )
+ def test_insert_index_datetimes(self, fill_val, exp_dtype, insert_value):
+ obj = pd.DatetimeIndex(
+ ["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], tz=fill_val.tz
+ )
+ assert obj.dtype == exp_dtype
+
+ exp = pd.DatetimeIndex(
+ ["2011-01-01", fill_val.date(), "2011-01-02", "2011-01-03", "2011-01-04"],
+ tz=fill_val.tz,
+ )
+ self._assert_insert_conversion(obj, fill_val, exp, exp_dtype)
+
+ if fill_val.tz:
+ # mismatched tzawareness
+ ts = pd.Timestamp("2012-01-01")
+ result = obj.insert(1, ts)
+ expected = obj.astype(object).insert(1, ts)
+ assert expected.dtype == object
+ tm.assert_index_equal(result, expected)
+
+ ts = pd.Timestamp("2012-01-01", tz="Asia/Tokyo")
+ result = obj.insert(1, ts)
+ # once deprecation is enforced:
+ expected = obj.insert(1, ts.tz_convert(obj.dtype.tz))
+ assert expected.dtype == obj.dtype
+ tm.assert_index_equal(result, expected)
+
+ else:
+ # mismatched tzawareness
+ ts = pd.Timestamp("2012-01-01", tz="Asia/Tokyo")
+ result = obj.insert(1, ts)
+ expected = obj.astype(object).insert(1, ts)
+ assert expected.dtype == object
+ tm.assert_index_equal(result, expected)
+
+ item = 1
+ result = obj.insert(1, item)
+ expected = obj.astype(object).insert(1, item)
+ assert expected[1] == item
+ assert expected.dtype == object
+ tm.assert_index_equal(result, expected)
+
+ def test_insert_index_timedelta64(self):
+ obj = pd.TimedeltaIndex(["1 day", "2 day", "3 day", "4 day"])
+ assert obj.dtype == "timedelta64[ns]"
+
+ # timedelta64 + timedelta64 => timedelta64
+ exp = pd.TimedeltaIndex(["1 day", "10 day", "2 day", "3 day", "4 day"])
+ self._assert_insert_conversion(
+ obj, pd.Timedelta("10 day"), exp, "timedelta64[ns]"
+ )
+
+ for item in [pd.Timestamp("2012-01-01"), 1]:
+ result = obj.insert(1, item)
+ expected = obj.astype(object).insert(1, item)
+ assert expected.dtype == object
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "insert, coerced_val, coerced_dtype",
+ [
+ (pd.Period("2012-01", freq="M"), "2012-01", "period[M]"),
+ (pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-01"), object),
+ (1, 1, object),
+ ("x", "x", object),
+ ],
+ )
+ def test_insert_index_period(self, insert, coerced_val, coerced_dtype):
+ obj = pd.PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq="M")
+ assert obj.dtype == "period[M]"
+
+ data = [
+ pd.Period("2011-01", freq="M"),
+ coerced_val,
+ pd.Period("2011-02", freq="M"),
+ pd.Period("2011-03", freq="M"),
+ pd.Period("2011-04", freq="M"),
+ ]
+ if isinstance(insert, pd.Period):
+ exp = pd.PeriodIndex(data, freq="M")
+ self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
+
+ # string that can be parsed to appropriate PeriodDtype
+ self._assert_insert_conversion(obj, str(insert), exp, coerced_dtype)
+
+ else:
+ result = obj.insert(0, insert)
+ expected = obj.astype(object).insert(0, insert)
+ tm.assert_index_equal(result, expected)
+
+ # TODO: ATM inserting '2012-01-01 00:00:00' when we have obj.freq=="M"
+ # casts that string to Period[M], not clear that is desirable
+ if not isinstance(insert, pd.Timestamp):
+ # non-castable string
+ result = obj.insert(0, str(insert))
+ expected = obj.astype(object).insert(0, str(insert))
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_insert_index_complex128(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_insert_index_bool(self):
+ raise NotImplementedError
+
+
+class TestWhereCoercion(CoercionBase):
+ method = "where"
+ _cond = np.array([True, False, True, False])
+
+ def _assert_where_conversion(
+ self, original, cond, values, expected, expected_dtype
+ ):
+ """test coercion triggered by where"""
+ target = original.copy()
+ res = target.where(cond, values)
+ tm.assert_equal(res, expected)
+ assert res.dtype == expected_dtype
+
+ def _construct_exp(self, obj, klass, fill_val, exp_dtype):
+ if fill_val is True:
+ values = klass([True, False, True, True])
+ elif isinstance(fill_val, (datetime, np.datetime64)):
+ values = pd.date_range(fill_val, periods=4)
+ else:
+ values = klass(x * fill_val for x in [5, 6, 7, 8])
+
+ exp = klass([obj[0], values[1], obj[2], values[3]], dtype=exp_dtype)
+ return values, exp
+
+ def _run_test(self, obj, fill_val, klass, exp_dtype):
+ cond = klass(self._cond)
+
+ exp = klass([obj[0], fill_val, obj[2], fill_val], dtype=exp_dtype)
+ self._assert_where_conversion(obj, cond, fill_val, exp, exp_dtype)
+
+ values, exp = self._construct_exp(obj, klass, fill_val, exp_dtype)
+ self._assert_where_conversion(obj, cond, values, exp, exp_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,exp_dtype",
+ [(1, object), (1.1, object), (1 + 1j, object), (True, object)],
+ )
+ def test_where_object(self, index_or_series, fill_val, exp_dtype):
+ klass = index_or_series
+ obj = klass(list("abcd"))
+ assert obj.dtype == object
+ self._run_test(obj, fill_val, klass, exp_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,exp_dtype",
+ [(1, np.int64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
+ )
+ def test_where_int64(self, index_or_series, fill_val, exp_dtype, request):
+ klass = index_or_series
+
+ obj = klass([1, 2, 3, 4])
+ assert obj.dtype == np.int64
+ self._run_test(obj, fill_val, klass, exp_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val, exp_dtype",
+ [(1, np.float64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
+ )
+ def test_where_float64(self, index_or_series, fill_val, exp_dtype, request):
+ klass = index_or_series
+
+ obj = klass([1.1, 2.2, 3.3, 4.4])
+ assert obj.dtype == np.float64
+ self._run_test(obj, fill_val, klass, exp_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,exp_dtype",
+ [
+ (1, np.complex128),
+ (1.1, np.complex128),
+ (1 + 1j, np.complex128),
+ (True, object),
+ ],
+ )
+ def test_where_complex128(self, index_or_series, fill_val, exp_dtype):
+ klass = index_or_series
+ obj = klass([1 + 1j, 2 + 2j, 3 + 3j, 4 + 4j], dtype=np.complex128)
+ assert obj.dtype == np.complex128
+ self._run_test(obj, fill_val, klass, exp_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,exp_dtype",
+ [(1, object), (1.1, object), (1 + 1j, object), (True, np.bool_)],
+ )
+ def test_where_series_bool(self, fill_val, exp_dtype):
+ klass = pd.Series # TODO: use index_or_series once we have Index[bool]
+
+ obj = klass([True, False, True, False])
+ assert obj.dtype == np.bool_
+ self._run_test(obj, fill_val, klass, exp_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,exp_dtype",
+ [
+ (pd.Timestamp("2012-01-01"), "datetime64[ns]"),
+ (pd.Timestamp("2012-01-01", tz="US/Eastern"), object),
+ ],
+ ids=["datetime64", "datetime64tz"],
+ )
+ def test_where_datetime64(self, index_or_series, fill_val, exp_dtype):
+ klass = index_or_series
+
+ obj = klass(pd.date_range("2011-01-01", periods=4, freq="D")._with_freq(None))
+ assert obj.dtype == "datetime64[ns]"
+
+ fv = fill_val
+ # do the check with each of the available datetime scalars
+ if exp_dtype == "datetime64[ns]":
+ for scalar in [fv, fv.to_pydatetime(), fv.to_datetime64()]:
+ self._run_test(obj, scalar, klass, exp_dtype)
+ else:
+ for scalar in [fv, fv.to_pydatetime()]:
+ self._run_test(obj, fill_val, klass, exp_dtype)
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_where_index_complex128(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_where_index_bool(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_where_series_timedelta64(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_where_series_period(self):
+ raise NotImplementedError
+
+ @pytest.mark.parametrize(
+ "value", [pd.Timedelta(days=9), timedelta(days=9), np.timedelta64(9, "D")]
+ )
+ def test_where_index_timedelta64(self, value):
+ tdi = pd.timedelta_range("1 Day", periods=4)
+ cond = np.array([True, False, False, True])
+
+ expected = pd.TimedeltaIndex(["1 Day", value, value, "4 Days"])
+ result = tdi.where(cond, value)
+ tm.assert_index_equal(result, expected)
+
+ # wrong-dtyped NaT
+ dtnat = np.datetime64("NaT", "ns")
+ expected = pd.Index([tdi[0], dtnat, dtnat, tdi[3]], dtype=object)
+ assert expected[1] is dtnat
+
+ result = tdi.where(cond, dtnat)
+ tm.assert_index_equal(result, expected)
+
+ def test_where_index_period(self):
+ dti = pd.date_range("2016-01-01", periods=3, freq="QS")
+ pi = dti.to_period("Q")
+
+ cond = np.array([False, True, False])
+
+ # Passing a valid scalar
+ value = pi[-1] + pi.freq * 10
+ expected = pd.PeriodIndex([value, pi[1], value])
+ result = pi.where(cond, value)
+ tm.assert_index_equal(result, expected)
+
+ # Case passing ndarray[object] of Periods
+ other = np.asarray(pi + pi.freq * 10, dtype=object)
+ result = pi.where(cond, other)
+ expected = pd.PeriodIndex([other[0], pi[1], other[2]])
+ tm.assert_index_equal(result, expected)
+
+ # Passing a mismatched scalar -> casts to object
+ td = pd.Timedelta(days=4)
+ expected = pd.Index([td, pi[1], td], dtype=object)
+ result = pi.where(cond, td)
+ tm.assert_index_equal(result, expected)
+
+ per = pd.Period("2020-04-21", "D")
+ expected = pd.Index([per, pi[1], per], dtype=object)
+ result = pi.where(cond, per)
+ tm.assert_index_equal(result, expected)
+
+
+class TestFillnaSeriesCoercion(CoercionBase):
+ # not indexing, but place here for consistency
+
+ method = "fillna"
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_has_comprehensive_tests(self):
+ raise NotImplementedError
+
+ def _assert_fillna_conversion(self, original, value, expected, expected_dtype):
+ """test coercion triggered by fillna"""
+ target = original.copy()
+ res = target.fillna(value)
+ tm.assert_equal(res, expected)
+ assert res.dtype == expected_dtype
+
+ @pytest.mark.parametrize(
+ "fill_val, fill_dtype",
+ [(1, object), (1.1, object), (1 + 1j, object), (True, object)],
+ )
+ def test_fillna_object(self, index_or_series, fill_val, fill_dtype):
+ klass = index_or_series
+ obj = klass(["a", np.nan, "c", "d"])
+ assert obj.dtype == object
+
+ exp = klass(["a", fill_val, "c", "d"])
+ self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,fill_dtype",
+ [(1, np.float64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
+ )
+ def test_fillna_float64(self, index_or_series, fill_val, fill_dtype):
+ klass = index_or_series
+ obj = klass([1.1, np.nan, 3.3, 4.4])
+ assert obj.dtype == np.float64
+
+ exp = klass([1.1, fill_val, 3.3, 4.4])
+ self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,fill_dtype",
+ [
+ (1, np.complex128),
+ (1.1, np.complex128),
+ (1 + 1j, np.complex128),
+ (True, object),
+ ],
+ )
+ def test_fillna_complex128(self, index_or_series, fill_val, fill_dtype):
+ klass = index_or_series
+ obj = klass([1 + 1j, np.nan, 3 + 3j, 4 + 4j], dtype=np.complex128)
+ assert obj.dtype == np.complex128
+
+ exp = klass([1 + 1j, fill_val, 3 + 3j, 4 + 4j])
+ self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,fill_dtype",
+ [
+ (pd.Timestamp("2012-01-01"), "datetime64[ns]"),
+ (pd.Timestamp("2012-01-01", tz="US/Eastern"), object),
+ (1, object),
+ ("x", object),
+ ],
+ ids=["datetime64", "datetime64tz", "object", "object"],
+ )
+ def test_fillna_datetime(self, index_or_series, fill_val, fill_dtype):
+ klass = index_or_series
+ obj = klass(
+ [
+ pd.Timestamp("2011-01-01"),
+ pd.NaT,
+ pd.Timestamp("2011-01-03"),
+ pd.Timestamp("2011-01-04"),
+ ]
+ )
+ assert obj.dtype == "datetime64[ns]"
+
+ exp = klass(
+ [
+ pd.Timestamp("2011-01-01"),
+ fill_val,
+ pd.Timestamp("2011-01-03"),
+ pd.Timestamp("2011-01-04"),
+ ]
+ )
+ self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val,fill_dtype",
+ [
+ (pd.Timestamp("2012-01-01", tz="US/Eastern"), "datetime64[ns, US/Eastern]"),
+ (pd.Timestamp("2012-01-01"), object),
+ # pre-2.0 with a mismatched tz we would get object result
+ (pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), "datetime64[ns, US/Eastern]"),
+ (1, object),
+ ("x", object),
+ ],
+ )
+ def test_fillna_datetime64tz(self, index_or_series, fill_val, fill_dtype):
+ klass = index_or_series
+ tz = "US/Eastern"
+
+ obj = klass(
+ [
+ pd.Timestamp("2011-01-01", tz=tz),
+ pd.NaT,
+ pd.Timestamp("2011-01-03", tz=tz),
+ pd.Timestamp("2011-01-04", tz=tz),
+ ]
+ )
+ assert obj.dtype == "datetime64[ns, US/Eastern]"
+
+ if getattr(fill_val, "tz", None) is None:
+ fv = fill_val
+ else:
+ fv = fill_val.tz_convert(tz)
+ exp = klass(
+ [
+ pd.Timestamp("2011-01-01", tz=tz),
+ fv,
+ pd.Timestamp("2011-01-03", tz=tz),
+ pd.Timestamp("2011-01-04", tz=tz),
+ ]
+ )
+ self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
+
+ @pytest.mark.parametrize(
+ "fill_val",
+ [
+ 1,
+ 1.1,
+ 1 + 1j,
+ True,
+ pd.Interval(1, 2, closed="left"),
+ pd.Timestamp("2012-01-01", tz="US/Eastern"),
+ pd.Timestamp("2012-01-01"),
+ pd.Timedelta(days=1),
+ pd.Period("2016-01-01", "D"),
+ ],
+ )
+ def test_fillna_interval(self, index_or_series, fill_val):
+ ii = pd.interval_range(1.0, 5.0, closed="right").insert(1, np.nan)
+ assert isinstance(ii.dtype, pd.IntervalDtype)
+ obj = index_or_series(ii)
+
+ exp = index_or_series([ii[0], fill_val, ii[2], ii[3], ii[4]], dtype=object)
+
+ fill_dtype = object
+ self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_fillna_series_int64(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_fillna_index_int64(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_fillna_series_bool(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_fillna_index_bool(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_fillna_series_timedelta64(self):
+ raise NotImplementedError
+
+ @pytest.mark.parametrize(
+ "fill_val",
+ [
+ 1,
+ 1.1,
+ 1 + 1j,
+ True,
+ pd.Interval(1, 2, closed="left"),
+ pd.Timestamp("2012-01-01", tz="US/Eastern"),
+ pd.Timestamp("2012-01-01"),
+ pd.Timedelta(days=1),
+ pd.Period("2016-01-01", "W"),
+ ],
+ )
+ def test_fillna_series_period(self, index_or_series, fill_val):
+ pi = pd.period_range("2016-01-01", periods=4, freq="D").insert(1, pd.NaT)
+ assert isinstance(pi.dtype, pd.PeriodDtype)
+ obj = index_or_series(pi)
+
+ exp = index_or_series([pi[0], fill_val, pi[2], pi[3], pi[4]], dtype=object)
+
+ fill_dtype = object
+ self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_fillna_index_timedelta64(self):
+ raise NotImplementedError
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_fillna_index_period(self):
+ raise NotImplementedError
+
+
+class TestReplaceSeriesCoercion(CoercionBase):
+ klasses = ["series"]
+ method = "replace"
+
+ rep: dict[str, list] = {}
+ rep["object"] = ["a", "b"]
+ rep["int64"] = [4, 5]
+ rep["float64"] = [1.1, 2.2]
+ rep["complex128"] = [1 + 1j, 2 + 2j]
+ rep["bool"] = [True, False]
+ rep["datetime64[ns]"] = [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-03")]
+
+ for tz in ["UTC", "US/Eastern"]:
+ # to test tz => different tz replacement
+ key = f"datetime64[ns, {tz}]"
+ rep[key] = [
+ pd.Timestamp("2011-01-01", tz=tz),
+ pd.Timestamp("2011-01-03", tz=tz),
+ ]
+
+ rep["timedelta64[ns]"] = [pd.Timedelta("1 day"), pd.Timedelta("2 day")]
+
+ @pytest.fixture(params=["dict", "series"])
+ def how(self, request):
+ return request.param
+
+ @pytest.fixture(
+ params=[
+ "object",
+ "int64",
+ "float64",
+ "complex128",
+ "bool",
+ "datetime64[ns]",
+ "datetime64[ns, UTC]",
+ "datetime64[ns, US/Eastern]",
+ "timedelta64[ns]",
+ ]
+ )
+ def from_key(self, request):
+ return request.param
+
+ @pytest.fixture(
+ params=[
+ "object",
+ "int64",
+ "float64",
+ "complex128",
+ "bool",
+ "datetime64[ns]",
+ "datetime64[ns, UTC]",
+ "datetime64[ns, US/Eastern]",
+ "timedelta64[ns]",
+ ],
+ ids=[
+ "object",
+ "int64",
+ "float64",
+ "complex128",
+ "bool",
+ "datetime64",
+ "datetime64tz",
+ "datetime64tz",
+ "timedelta64",
+ ],
+ )
+ def to_key(self, request):
+ return request.param
+
+ @pytest.fixture
+ def replacer(self, how, from_key, to_key):
+ """
+ Object we will pass to `Series.replace`
+ """
+ if how == "dict":
+ replacer = dict(zip(self.rep[from_key], self.rep[to_key]))
+ elif how == "series":
+ replacer = pd.Series(self.rep[to_key], index=self.rep[from_key])
+ else:
+ raise ValueError
+ return replacer
+
+ def test_replace_series(self, how, to_key, from_key, replacer):
+ index = pd.Index([3, 4], name="xxx")
+ obj = pd.Series(self.rep[from_key], index=index, name="yyy")
+ assert obj.dtype == from_key
+
+ if from_key.startswith("datetime") and to_key.startswith("datetime"):
+ # tested below
+ return
+ elif from_key in ["datetime64[ns, US/Eastern]", "datetime64[ns, UTC]"]:
+ # tested below
+ return
+
+ result = obj.replace(replacer)
+
+ if (from_key == "float64" and to_key in ("int64")) or (
+ from_key == "complex128" and to_key in ("int64", "float64")
+ ):
+ if not IS64 or is_platform_windows():
+ pytest.skip(f"32-bit platform buggy: {from_key} -> {to_key}")
+
+ # Expected: do not downcast by replacement
+ exp = pd.Series(self.rep[to_key], index=index, name="yyy", dtype=from_key)
+
+ else:
+ exp = pd.Series(self.rep[to_key], index=index, name="yyy")
+ assert exp.dtype == to_key
+
+ tm.assert_series_equal(result, exp)
+
+ @pytest.mark.parametrize(
+ "to_key",
+ ["timedelta64[ns]", "bool", "object", "complex128", "float64", "int64"],
+ indirect=True,
+ )
+ @pytest.mark.parametrize(
+ "from_key", ["datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"], indirect=True
+ )
+ def test_replace_series_datetime_tz(self, how, to_key, from_key, replacer):
+ index = pd.Index([3, 4], name="xyz")
+ obj = pd.Series(self.rep[from_key], index=index, name="yyy")
+ assert obj.dtype == from_key
+
+ result = obj.replace(replacer)
+
+ exp = pd.Series(self.rep[to_key], index=index, name="yyy")
+ assert exp.dtype == to_key
+
+ tm.assert_series_equal(result, exp)
+
+ @pytest.mark.parametrize(
+ "to_key",
+ ["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"],
+ indirect=True,
+ )
+ @pytest.mark.parametrize(
+ "from_key",
+ ["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"],
+ indirect=True,
+ )
+ def test_replace_series_datetime_datetime(self, how, to_key, from_key, replacer):
+ index = pd.Index([3, 4], name="xyz")
+ obj = pd.Series(self.rep[from_key], index=index, name="yyy")
+ assert obj.dtype == from_key
+
+ result = obj.replace(replacer)
+
+ exp = pd.Series(self.rep[to_key], index=index, name="yyy")
+ if isinstance(obj.dtype, pd.DatetimeTZDtype) and isinstance(
+ exp.dtype, pd.DatetimeTZDtype
+ ):
+ # with mismatched tzs, we retain the original dtype as of 2.0
+ exp = exp.astype(obj.dtype)
+ else:
+ assert exp.dtype == to_key
+
+ tm.assert_series_equal(result, exp)
+
+ @pytest.mark.xfail(reason="Test not implemented")
+ def test_replace_series_period(self):
+ raise NotImplementedError
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_datetime.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_datetime.py
new file mode 100644
index 0000000000000000000000000000000000000000..6510612ba6f877d46ee53fea05977d58ca4ef13d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_datetime.py
@@ -0,0 +1,188 @@
+import re
+
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+
+
+class TestDatetimeIndex:
+ def test_get_loc_naive_dti_aware_str_deprecated(self):
+ # GH#46903
+ ts = Timestamp("20130101")._value
+ dti = pd.DatetimeIndex([ts + 50 + i for i in range(100)])
+ ser = Series(range(100), index=dti)
+
+ key = "2013-01-01 00:00:00.000000050+0000"
+ msg = re.escape(repr(key))
+ with pytest.raises(KeyError, match=msg):
+ ser[key]
+
+ with pytest.raises(KeyError, match=msg):
+ dti.get_loc(key)
+
+ def test_indexing_with_datetime_tz(self):
+ # GH#8260
+ # support datetime64 with tz
+
+ idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo")
+ dr = date_range("20130110", periods=3)
+ df = DataFrame({"A": idx, "B": dr})
+ df["C"] = idx
+ df.iloc[1, 1] = pd.NaT
+ df.iloc[1, 2] = pd.NaT
+
+ expected = Series(
+ [Timestamp("2013-01-02 00:00:00-0500", tz="US/Eastern"), pd.NaT, pd.NaT],
+ index=list("ABC"),
+ dtype="object",
+ name=1,
+ )
+
+ # indexing
+ result = df.iloc[1]
+ tm.assert_series_equal(result, expected)
+ result = df.loc[1]
+ tm.assert_series_equal(result, expected)
+
+ def test_indexing_fast_xs(self):
+ # indexing - fast_xs
+ df = DataFrame({"a": date_range("2014-01-01", periods=10, tz="UTC")})
+ result = df.iloc[5]
+ expected = Series(
+ [Timestamp("2014-01-06 00:00:00+0000", tz="UTC")], index=["a"], name=5
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = df.loc[5]
+ tm.assert_series_equal(result, expected)
+
+ # indexing - boolean
+ result = df[df.a > df.a[3]]
+ expected = df.iloc[4:]
+ tm.assert_frame_equal(result, expected)
+
+ def test_consistency_with_tz_aware_scalar(self):
+ # xef gh-12938
+ # various ways of indexing the same tz-aware scalar
+ df = Series([Timestamp("2016-03-30 14:35:25", tz="Europe/Brussels")]).to_frame()
+
+ df = pd.concat([df, df]).reset_index(drop=True)
+ expected = Timestamp("2016-03-30 14:35:25+0200", tz="Europe/Brussels")
+
+ result = df[0][0]
+ assert result == expected
+
+ result = df.iloc[0, 0]
+ assert result == expected
+
+ result = df.loc[0, 0]
+ assert result == expected
+
+ result = df.iat[0, 0]
+ assert result == expected
+
+ result = df.at[0, 0]
+ assert result == expected
+
+ result = df[0].loc[0]
+ assert result == expected
+
+ result = df[0].at[0]
+ assert result == expected
+
+ def test_indexing_with_datetimeindex_tz(self, indexer_sl):
+ # GH 12050
+ # indexing on a series with a datetimeindex with tz
+ index = date_range("2015-01-01", periods=2, tz="utc")
+
+ ser = Series(range(2), index=index, dtype="int64")
+
+ # list-like indexing
+
+ for sel in (index, list(index)):
+ # getitem
+ result = indexer_sl(ser)[sel]
+ expected = ser.copy()
+ if sel is not index:
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(result, expected)
+
+ # setitem
+ result = ser.copy()
+ indexer_sl(result)[sel] = 1
+ expected = Series(1, index=index)
+ tm.assert_series_equal(result, expected)
+
+ # single element indexing
+
+ # getitem
+ assert indexer_sl(ser)[index[1]] == 1
+
+ # setitem
+ result = ser.copy()
+ indexer_sl(result)[index[1]] = 5
+ expected = Series([0, 5], index=index)
+ tm.assert_series_equal(result, expected)
+
+ def test_nanosecond_getitem_setitem_with_tz(self):
+ # GH 11679
+ data = ["2016-06-28 08:30:00.123456789"]
+ index = pd.DatetimeIndex(data, dtype="datetime64[ns, America/Chicago]")
+ df = DataFrame({"a": [10]}, index=index)
+ result = df.loc[df.index[0]]
+ expected = Series(10, index=["a"], name=df.index[0])
+ tm.assert_series_equal(result, expected)
+
+ result = df.copy()
+ result.loc[df.index[0], "a"] = -1
+ expected = DataFrame(-1, index=index, columns=["a"])
+ tm.assert_frame_equal(result, expected)
+
+ def test_getitem_str_slice_millisecond_resolution(self, frame_or_series):
+ # GH#33589
+
+ keys = [
+ "2017-10-25T16:25:04.151",
+ "2017-10-25T16:25:04.252",
+ "2017-10-25T16:50:05.237",
+ "2017-10-25T16:50:05.238",
+ ]
+ obj = frame_or_series(
+ [1, 2, 3, 4],
+ index=[Timestamp(x) for x in keys],
+ )
+ result = obj[keys[1] : keys[2]]
+ expected = frame_or_series(
+ [2, 3],
+ index=[
+ Timestamp(keys[1]),
+ Timestamp(keys[2]),
+ ],
+ )
+ tm.assert_equal(result, expected)
+
+ def test_getitem_pyarrow_index(self, frame_or_series):
+ # GH 53644
+ pytest.importorskip("pyarrow")
+ obj = frame_or_series(
+ range(5),
+ index=date_range("2020", freq="D", periods=5).astype(
+ "timestamp[us][pyarrow]"
+ ),
+ )
+ result = obj.loc[obj.index[:-3]]
+ expected = frame_or_series(
+ range(2),
+ index=date_range("2020", freq="D", periods=2).astype(
+ "timestamp[us][pyarrow]"
+ ),
+ )
+ tm.assert_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_floats.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_floats.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9fbf95751dfe66d8624911ee0ab15a8afe73ccf
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_floats.py
@@ -0,0 +1,686 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ RangeIndex,
+ Series,
+)
+import pandas._testing as tm
+
+
+def gen_obj(klass, index):
+ if klass is Series:
+ obj = Series(np.arange(len(index)), index=index)
+ else:
+ obj = DataFrame(
+ np.random.default_rng(2).standard_normal((len(index), len(index))),
+ index=index,
+ columns=index,
+ )
+ return obj
+
+
+class TestFloatIndexers:
+ def check(self, result, original, indexer, getitem):
+ """
+ comparator for results
+ we need to take care if we are indexing on a
+ Series or a frame
+ """
+ if isinstance(original, Series):
+ expected = original.iloc[indexer]
+ elif getitem:
+ expected = original.iloc[:, indexer]
+ else:
+ expected = original.iloc[indexer]
+
+ tm.assert_almost_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "index_func",
+ [
+ tm.makeStringIndex,
+ tm.makeCategoricalIndex,
+ tm.makeDateIndex,
+ tm.makeTimedeltaIndex,
+ tm.makePeriodIndex,
+ ],
+ )
+ def test_scalar_non_numeric(self, index_func, frame_or_series, indexer_sl):
+ # GH 4892
+ # float_indexers should raise exceptions
+ # on appropriate Index types & accessors
+
+ i = index_func(5)
+ s = gen_obj(frame_or_series, i)
+
+ # getting
+ with pytest.raises(KeyError, match="^3.0$"):
+ indexer_sl(s)[3.0]
+
+ # contains
+ assert 3.0 not in s
+
+ s2 = s.copy()
+ indexer_sl(s2)[3.0] = 10
+
+ if indexer_sl is tm.setitem:
+ assert 3.0 in s2.axes[-1]
+ elif indexer_sl is tm.loc:
+ assert 3.0 in s2.axes[0]
+ else:
+ assert 3.0 not in s2.axes[0]
+ assert 3.0 not in s2.axes[-1]
+
+ @pytest.mark.parametrize(
+ "index_func",
+ [
+ tm.makeStringIndex,
+ tm.makeCategoricalIndex,
+ tm.makeDateIndex,
+ tm.makeTimedeltaIndex,
+ tm.makePeriodIndex,
+ ],
+ )
+ def test_scalar_non_numeric_series_fallback(self, index_func):
+ # fallsback to position selection, series only
+ i = index_func(5)
+ s = Series(np.arange(len(i)), index=i)
+
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ s[3]
+ with pytest.raises(KeyError, match="^3.0$"):
+ s[3.0]
+
+ def test_scalar_with_mixed(self, indexer_sl):
+ s2 = Series([1, 2, 3], index=["a", "b", "c"])
+ s3 = Series([1, 2, 3], index=["a", "b", 1.5])
+
+ # lookup in a pure string index with an invalid indexer
+
+ with pytest.raises(KeyError, match="^1.0$"):
+ indexer_sl(s2)[1.0]
+
+ with pytest.raises(KeyError, match=r"^1\.0$"):
+ indexer_sl(s2)[1.0]
+
+ result = indexer_sl(s2)["b"]
+ expected = 2
+ assert result == expected
+
+ # mixed index so we have label
+ # indexing
+ with pytest.raises(KeyError, match="^1.0$"):
+ indexer_sl(s3)[1.0]
+
+ if indexer_sl is not tm.loc:
+ # __getitem__ falls back to positional
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = s3[1]
+ expected = 2
+ assert result == expected
+
+ with pytest.raises(KeyError, match=r"^1\.0$"):
+ indexer_sl(s3)[1.0]
+
+ result = indexer_sl(s3)[1.5]
+ expected = 3
+ assert result == expected
+
+ @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
+ def test_scalar_integer(self, index_func, frame_or_series, indexer_sl):
+ getitem = indexer_sl is not tm.loc
+
+ # test how scalar float indexers work on int indexes
+
+ # integer index
+ i = index_func(5)
+ obj = gen_obj(frame_or_series, i)
+
+ # coerce to equal int
+
+ result = indexer_sl(obj)[3.0]
+ self.check(result, obj, 3, getitem)
+
+ if isinstance(obj, Series):
+
+ def compare(x, y):
+ assert x == y
+
+ expected = 100
+ else:
+ compare = tm.assert_series_equal
+ if getitem:
+ expected = Series(100, index=range(len(obj)), name=3)
+ else:
+ expected = Series(100.0, index=range(len(obj)), name=3)
+
+ s2 = obj.copy()
+ indexer_sl(s2)[3.0] = 100
+
+ result = indexer_sl(s2)[3.0]
+ compare(result, expected)
+
+ result = indexer_sl(s2)[3]
+ compare(result, expected)
+
+ @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
+ def test_scalar_integer_contains_float(self, index_func, frame_or_series):
+ # contains
+ # integer index
+ index = index_func(5)
+ obj = gen_obj(frame_or_series, index)
+
+ # coerce to equal int
+ assert 3.0 in obj
+
+ def test_scalar_float(self, frame_or_series):
+ # scalar float indexers work on a float index
+ index = Index(np.arange(5.0))
+ s = gen_obj(frame_or_series, index)
+
+ # assert all operations except for iloc are ok
+ indexer = index[3]
+ for idxr in [tm.loc, tm.setitem]:
+ getitem = idxr is not tm.loc
+
+ # getting
+ result = idxr(s)[indexer]
+ self.check(result, s, 3, getitem)
+
+ # setting
+ s2 = s.copy()
+
+ result = idxr(s2)[indexer]
+ self.check(result, s, 3, getitem)
+
+ # random float is a KeyError
+ with pytest.raises(KeyError, match=r"^3\.5$"):
+ idxr(s)[3.5]
+
+ # contains
+ assert 3.0 in s
+
+ # iloc succeeds with an integer
+ expected = s.iloc[3]
+ s2 = s.copy()
+
+ s2.iloc[3] = expected
+ result = s2.iloc[3]
+ self.check(result, s, 3, False)
+
+ @pytest.mark.parametrize(
+ "index_func",
+ [
+ tm.makeStringIndex,
+ tm.makeDateIndex,
+ tm.makeTimedeltaIndex,
+ tm.makePeriodIndex,
+ ],
+ )
+ @pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
+ def test_slice_non_numeric(self, index_func, idx, frame_or_series, indexer_sli):
+ # GH 4892
+ # float_indexers should raise exceptions
+ # on appropriate Index types & accessors
+
+ index = index_func(5)
+ s = gen_obj(frame_or_series, index)
+
+ # getitem
+ if indexer_sli is tm.iloc:
+ msg = (
+ "cannot do positional indexing "
+ rf"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
+ "type float"
+ )
+ else:
+ msg = (
+ "cannot do slice indexing "
+ rf"on {type(index).__name__} with these indexers "
+ r"\[(3|4)(\.0)?\] "
+ r"of type (float|int)"
+ )
+ with pytest.raises(TypeError, match=msg):
+ indexer_sli(s)[idx]
+
+ # setitem
+ if indexer_sli is tm.iloc:
+ # otherwise we keep the same message as above
+ msg = "slice indices must be integers or None or have an __index__ method"
+ with pytest.raises(TypeError, match=msg):
+ indexer_sli(s)[idx] = 0
+
+ def test_slice_integer(self):
+ # same as above, but for Integer based indexes
+ # these coerce to a like integer
+ # oob indicates if we are out of bounds
+ # of positional indexing
+ for index, oob in [
+ (Index(np.arange(5, dtype=np.int64)), False),
+ (RangeIndex(5), False),
+ (Index(np.arange(5, dtype=np.int64) + 10), True),
+ ]:
+ # s is an in-range index
+ s = Series(range(5), index=index)
+
+ # getitem
+ for idx in [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]:
+ result = s.loc[idx]
+
+ # these are all label indexing
+ # except getitem which is positional
+ # empty
+ if oob:
+ indexer = slice(0, 0)
+ else:
+ indexer = slice(3, 5)
+ self.check(result, s, indexer, False)
+
+ # getitem out-of-bounds
+ for idx in [slice(-6, 6), slice(-6.0, 6.0)]:
+ result = s.loc[idx]
+
+ # these are all label indexing
+ # except getitem which is positional
+ # empty
+ if oob:
+ indexer = slice(0, 0)
+ else:
+ indexer = slice(-6, 6)
+ self.check(result, s, indexer, False)
+
+ # positional indexing
+ msg = (
+ "cannot do slice indexing "
+ rf"on {type(index).__name__} with these indexers \[-6\.0\] of "
+ "type float"
+ )
+ with pytest.raises(TypeError, match=msg):
+ s[slice(-6.0, 6.0)]
+
+ # getitem odd floats
+ for idx, res1 in [
+ (slice(2.5, 4), slice(3, 5)),
+ (slice(2, 3.5), slice(2, 4)),
+ (slice(2.5, 3.5), slice(3, 4)),
+ ]:
+ result = s.loc[idx]
+ if oob:
+ res = slice(0, 0)
+ else:
+ res = res1
+
+ self.check(result, s, res, False)
+
+ # positional indexing
+ msg = (
+ "cannot do slice indexing "
+ rf"on {type(index).__name__} with these indexers \[(2|3)\.5\] of "
+ "type float"
+ )
+ with pytest.raises(TypeError, match=msg):
+ s[idx]
+
+ @pytest.mark.parametrize("idx", [slice(2, 4.0), slice(2.0, 4), slice(2.0, 4.0)])
+ def test_integer_positional_indexing(self, idx):
+ """make sure that we are raising on positional indexing
+ w.r.t. an integer index
+ """
+ s = Series(range(2, 6), index=range(2, 6))
+
+ result = s[2:4]
+ expected = s.iloc[2:4]
+ tm.assert_series_equal(result, expected)
+
+ klass = RangeIndex
+ msg = (
+ "cannot do (slice|positional) indexing "
+ rf"on {klass.__name__} with these indexers \[(2|4)\.0\] of "
+ "type float"
+ )
+ with pytest.raises(TypeError, match=msg):
+ s[idx]
+ with pytest.raises(TypeError, match=msg):
+ s.iloc[idx]
+
+ @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
+ def test_slice_integer_frame_getitem(self, index_func):
+ # similar to above, but on the getitem dim (of a DataFrame)
+ index = index_func(5)
+
+ s = DataFrame(np.random.default_rng(2).standard_normal((5, 2)), index=index)
+
+ # getitem
+ for idx in [slice(0.0, 1), slice(0, 1.0), slice(0.0, 1.0)]:
+ result = s.loc[idx]
+ indexer = slice(0, 2)
+ self.check(result, s, indexer, False)
+
+ # positional indexing
+ msg = (
+ "cannot do slice indexing "
+ rf"on {type(index).__name__} with these indexers \[(0|1)\.0\] of "
+ "type float"
+ )
+ with pytest.raises(TypeError, match=msg):
+ s[idx]
+
+ # getitem out-of-bounds
+ for idx in [slice(-10, 10), slice(-10.0, 10.0)]:
+ result = s.loc[idx]
+ self.check(result, s, slice(-10, 10), True)
+
+ # positional indexing
+ msg = (
+ "cannot do slice indexing "
+ rf"on {type(index).__name__} with these indexers \[-10\.0\] of "
+ "type float"
+ )
+ with pytest.raises(TypeError, match=msg):
+ s[slice(-10.0, 10.0)]
+
+ # getitem odd floats
+ for idx, res in [
+ (slice(0.5, 1), slice(1, 2)),
+ (slice(0, 0.5), slice(0, 1)),
+ (slice(0.5, 1.5), slice(1, 2)),
+ ]:
+ result = s.loc[idx]
+ self.check(result, s, res, False)
+
+ # positional indexing
+ msg = (
+ "cannot do slice indexing "
+ rf"on {type(index).__name__} with these indexers \[0\.5\] of "
+ "type float"
+ )
+ with pytest.raises(TypeError, match=msg):
+ s[idx]
+
+ @pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
+ @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
+ def test_float_slice_getitem_with_integer_index_raises(self, idx, index_func):
+ # similar to above, but on the getitem dim (of a DataFrame)
+ index = index_func(5)
+
+ s = DataFrame(np.random.default_rng(2).standard_normal((5, 2)), index=index)
+
+ # setitem
+ sc = s.copy()
+ sc.loc[idx] = 0
+ result = sc.loc[idx].values.ravel()
+ assert (result == 0).all()
+
+ # positional indexing
+ msg = (
+ "cannot do slice indexing "
+ rf"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
+ "type float"
+ )
+ with pytest.raises(TypeError, match=msg):
+ s[idx] = 0
+
+ with pytest.raises(TypeError, match=msg):
+ s[idx]
+
+ @pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
+ def test_slice_float(self, idx, frame_or_series, indexer_sl):
+ # same as above, but for floats
+ index = Index(np.arange(5.0)) + 0.1
+ s = gen_obj(frame_or_series, index)
+
+ expected = s.iloc[3:4]
+
+ # getitem
+ result = indexer_sl(s)[idx]
+ assert isinstance(result, type(s))
+ tm.assert_equal(result, expected)
+
+ # setitem
+ s2 = s.copy()
+ indexer_sl(s2)[idx] = 0
+ result = indexer_sl(s2)[idx].values.ravel()
+ assert (result == 0).all()
+
+ def test_floating_index_doc_example(self):
+ index = Index([1.5, 2, 3, 4.5, 5])
+ s = Series(range(5), index=index)
+ assert s[3] == 2
+ assert s.loc[3] == 2
+ assert s.iloc[3] == 3
+
+ def test_floating_misc(self, indexer_sl):
+ # related 236
+ # scalar/slicing of a float index
+ s = Series(np.arange(5), index=np.arange(5) * 2.5, dtype=np.int64)
+
+ # label based slicing
+ result = indexer_sl(s)[1.0:3.0]
+ expected = Series(1, index=[2.5])
+ tm.assert_series_equal(result, expected)
+
+ # exact indexing when found
+
+ result = indexer_sl(s)[5.0]
+ assert result == 2
+
+ result = indexer_sl(s)[5]
+ assert result == 2
+
+ # value not found (and no fallbacking at all)
+
+ # scalar integers
+ with pytest.raises(KeyError, match=r"^4$"):
+ indexer_sl(s)[4]
+
+ # fancy floats/integers create the correct entry (as nan)
+ # fancy tests
+ expected = Series([2, 0], index=Index([5.0, 0.0], dtype=np.float64))
+ for fancy_idx in [[5.0, 0.0], np.array([5.0, 0.0])]: # float
+ tm.assert_series_equal(indexer_sl(s)[fancy_idx], expected)
+
+ expected = Series([2, 0], index=Index([5, 0], dtype="float64"))
+ for fancy_idx in [[5, 0], np.array([5, 0])]:
+ tm.assert_series_equal(indexer_sl(s)[fancy_idx], expected)
+
+ warn = FutureWarning if indexer_sl is tm.setitem else None
+ msg = r"The behavior of obj\[i:j\] with a float-dtype index"
+
+ # all should return the same as we are slicing 'the same'
+ with tm.assert_produces_warning(warn, match=msg):
+ result1 = indexer_sl(s)[2:5]
+ result2 = indexer_sl(s)[2.0:5.0]
+ result3 = indexer_sl(s)[2.0:5]
+ result4 = indexer_sl(s)[2.1:5]
+ tm.assert_series_equal(result1, result2)
+ tm.assert_series_equal(result1, result3)
+ tm.assert_series_equal(result1, result4)
+
+ expected = Series([1, 2], index=[2.5, 5.0])
+ with tm.assert_produces_warning(warn, match=msg):
+ result = indexer_sl(s)[2:5]
+
+ tm.assert_series_equal(result, expected)
+
+ # list selection
+ result1 = indexer_sl(s)[[0.0, 5, 10]]
+ result2 = s.iloc[[0, 2, 4]]
+ tm.assert_series_equal(result1, result2)
+
+ with pytest.raises(KeyError, match="not in index"):
+ indexer_sl(s)[[1.6, 5, 10]]
+
+ with pytest.raises(KeyError, match="not in index"):
+ indexer_sl(s)[[0, 1, 2]]
+
+ result = indexer_sl(s)[[2.5, 5]]
+ tm.assert_series_equal(result, Series([1, 2], index=[2.5, 5.0]))
+
+ result = indexer_sl(s)[[2.5]]
+ tm.assert_series_equal(result, Series([1], index=[2.5]))
+
+ def test_floatindex_slicing_bug(self, float_numpy_dtype):
+ # GH 5557, related to slicing a float index
+ dtype = float_numpy_dtype
+ ser = {
+ 256: 2321.0,
+ 1: 78.0,
+ 2: 2716.0,
+ 3: 0.0,
+ 4: 369.0,
+ 5: 0.0,
+ 6: 269.0,
+ 7: 0.0,
+ 8: 0.0,
+ 9: 0.0,
+ 10: 3536.0,
+ 11: 0.0,
+ 12: 24.0,
+ 13: 0.0,
+ 14: 931.0,
+ 15: 0.0,
+ 16: 101.0,
+ 17: 78.0,
+ 18: 9643.0,
+ 19: 0.0,
+ 20: 0.0,
+ 21: 0.0,
+ 22: 63761.0,
+ 23: 0.0,
+ 24: 446.0,
+ 25: 0.0,
+ 26: 34773.0,
+ 27: 0.0,
+ 28: 729.0,
+ 29: 78.0,
+ 30: 0.0,
+ 31: 0.0,
+ 32: 3374.0,
+ 33: 0.0,
+ 34: 1391.0,
+ 35: 0.0,
+ 36: 361.0,
+ 37: 0.0,
+ 38: 61808.0,
+ 39: 0.0,
+ 40: 0.0,
+ 41: 0.0,
+ 42: 6677.0,
+ 43: 0.0,
+ 44: 802.0,
+ 45: 0.0,
+ 46: 2691.0,
+ 47: 0.0,
+ 48: 3582.0,
+ 49: 0.0,
+ 50: 734.0,
+ 51: 0.0,
+ 52: 627.0,
+ 53: 70.0,
+ 54: 2584.0,
+ 55: 0.0,
+ 56: 324.0,
+ 57: 0.0,
+ 58: 605.0,
+ 59: 0.0,
+ 60: 0.0,
+ 61: 0.0,
+ 62: 3989.0,
+ 63: 10.0,
+ 64: 42.0,
+ 65: 0.0,
+ 66: 904.0,
+ 67: 0.0,
+ 68: 88.0,
+ 69: 70.0,
+ 70: 8172.0,
+ 71: 0.0,
+ 72: 0.0,
+ 73: 0.0,
+ 74: 64902.0,
+ 75: 0.0,
+ 76: 347.0,
+ 77: 0.0,
+ 78: 36605.0,
+ 79: 0.0,
+ 80: 379.0,
+ 81: 70.0,
+ 82: 0.0,
+ 83: 0.0,
+ 84: 3001.0,
+ 85: 0.0,
+ 86: 1630.0,
+ 87: 7.0,
+ 88: 364.0,
+ 89: 0.0,
+ 90: 67404.0,
+ 91: 9.0,
+ 92: 0.0,
+ 93: 0.0,
+ 94: 7685.0,
+ 95: 0.0,
+ 96: 1017.0,
+ 97: 0.0,
+ 98: 2831.0,
+ 99: 0.0,
+ 100: 2963.0,
+ 101: 0.0,
+ 102: 854.0,
+ 103: 0.0,
+ 104: 0.0,
+ 105: 0.0,
+ 106: 0.0,
+ 107: 0.0,
+ 108: 0.0,
+ 109: 0.0,
+ 110: 0.0,
+ 111: 0.0,
+ 112: 0.0,
+ 113: 0.0,
+ 114: 0.0,
+ 115: 0.0,
+ 116: 0.0,
+ 117: 0.0,
+ 118: 0.0,
+ 119: 0.0,
+ 120: 0.0,
+ 121: 0.0,
+ 122: 0.0,
+ 123: 0.0,
+ 124: 0.0,
+ 125: 0.0,
+ 126: 67744.0,
+ 127: 22.0,
+ 128: 264.0,
+ 129: 0.0,
+ 260: 197.0,
+ 268: 0.0,
+ 265: 0.0,
+ 269: 0.0,
+ 261: 0.0,
+ 266: 1198.0,
+ 267: 0.0,
+ 262: 2629.0,
+ 258: 775.0,
+ 257: 0.0,
+ 263: 0.0,
+ 259: 0.0,
+ 264: 163.0,
+ 250: 10326.0,
+ 251: 0.0,
+ 252: 1228.0,
+ 253: 0.0,
+ 254: 2769.0,
+ 255: 0.0,
+ }
+
+ # smoke test for the repr
+ s = Series(ser, dtype=dtype)
+ result = s.value_counts()
+ assert result.index.dtype == dtype
+ str(result)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_iat.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_iat.py
new file mode 100644
index 0000000000000000000000000000000000000000..4497c16efdfda7ab0baf7d12b7cda4ec28fcba62
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_iat.py
@@ -0,0 +1,48 @@
+import numpy as np
+
+from pandas import (
+ DataFrame,
+ Series,
+ period_range,
+)
+
+
+def test_iat(float_frame):
+ for i, row in enumerate(float_frame.index):
+ for j, col in enumerate(float_frame.columns):
+ result = float_frame.iat[i, j]
+ expected = float_frame.at[row, col]
+ assert result == expected
+
+
+def test_iat_duplicate_columns():
+ # https://github.com/pandas-dev/pandas/issues/11754
+ df = DataFrame([[1, 2]], columns=["x", "x"])
+ assert df.iat[0, 0] == 1
+
+
+def test_iat_getitem_series_with_period_index():
+ # GH#4390, iat incorrectly indexing
+ index = period_range("1/1/2001", periods=10)
+ ser = Series(np.random.default_rng(2).standard_normal(10), index=index)
+ expected = ser[index[0]]
+ result = ser.iat[0]
+ assert expected == result
+
+
+def test_iat_setitem_item_cache_cleared(indexer_ial, using_copy_on_write):
+ # GH#45684
+ data = {"x": np.arange(8, dtype=np.int64), "y": np.int64(0)}
+ df = DataFrame(data).copy()
+ ser = df["y"]
+
+ # previously this iat setting would split the block and fail to clear
+ # the item_cache.
+ indexer_ial(df)[7, 0] = 9999
+
+ indexer_ial(df)[7, 1] = 1234
+
+ assert df.iat[7, 1] == 1234
+ if not using_copy_on_write:
+ assert ser.iloc[-1] == 1234
+ assert df.iloc[-1, -1] == 1234
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_iloc.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_iloc.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc7604330695fc3bd92647fc374207f5a6b3c1f9
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_iloc.py
@@ -0,0 +1,1462 @@
+""" test positional based indexing with iloc """
+
+from datetime import datetime
+import re
+
+import numpy as np
+import pytest
+
+from pandas.errors import IndexingError
+import pandas.util._test_decorators as td
+
+from pandas import (
+ NA,
+ Categorical,
+ CategoricalDtype,
+ DataFrame,
+ Index,
+ Interval,
+ NaT,
+ Series,
+ Timestamp,
+ array,
+ concat,
+ date_range,
+ interval_range,
+ isna,
+ to_datetime,
+)
+import pandas._testing as tm
+from pandas.api.types import is_scalar
+from pandas.tests.indexing.common import check_indexing_smoketest_or_raises
+
+# We pass through the error message from numpy
+_slice_iloc_msg = re.escape(
+ "only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) "
+ "and integer or boolean arrays are valid indices"
+)
+
+
+class TestiLoc:
+ @pytest.mark.parametrize("key", [2, -1, [0, 1, 2]])
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ @pytest.mark.parametrize(
+ "col",
+ ["labels", "mixed", "ts", "floats", "empty"],
+ )
+ def test_iloc_getitem_int_and_list_int(self, key, kind, col, request):
+ obj = request.getfixturevalue(f"{kind}_{col}")
+ check_indexing_smoketest_or_raises(
+ obj,
+ "iloc",
+ key,
+ fails=IndexError,
+ )
+
+ # array of ints (GH5006), make sure that a single indexer is returning
+ # the correct type
+
+
+class TestiLocBaseIndependent:
+ """Tests Independent Of Base Class"""
+
+ @pytest.mark.parametrize(
+ "key",
+ [
+ slice(None),
+ slice(3),
+ range(3),
+ [0, 1, 2],
+ Index(range(3)),
+ np.asarray([0, 1, 2]),
+ ],
+ )
+ @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
+ def test_iloc_setitem_fullcol_categorical(self, indexer, key, using_array_manager):
+ frame = DataFrame({0: range(3)}, dtype=object)
+
+ cat = Categorical(["alpha", "beta", "gamma"])
+
+ if not using_array_manager:
+ assert frame._mgr.blocks[0]._can_hold_element(cat)
+
+ df = frame.copy()
+ orig_vals = df.values
+
+ indexer(df)[key, 0] = cat
+
+ expected = DataFrame({0: cat}).astype(object)
+ if not using_array_manager:
+ assert np.shares_memory(df[0].values, orig_vals)
+
+ tm.assert_frame_equal(df, expected)
+
+ # check we dont have a view on cat (may be undesired GH#39986)
+ df.iloc[0, 0] = "gamma"
+ assert cat[0] != "gamma"
+
+ # pre-2.0 with mixed dataframe ("split" path) we always overwrote the
+ # column. as of 2.0 we correctly write "into" the column, so
+ # we retain the object dtype.
+ frame = DataFrame({0: np.array([0, 1, 2], dtype=object), 1: range(3)})
+ df = frame.copy()
+ orig_vals = df.values
+ indexer(df)[key, 0] = cat
+ expected = DataFrame({0: cat.astype(object), 1: range(3)})
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("box", [array, Series])
+ def test_iloc_setitem_ea_inplace(self, frame_or_series, box, using_copy_on_write):
+ # GH#38952 Case with not setting a full column
+ # IntegerArray without NAs
+ arr = array([1, 2, 3, 4])
+ obj = frame_or_series(arr.to_numpy("i8"))
+
+ if frame_or_series is Series:
+ values = obj.values
+ else:
+ values = obj._mgr.arrays[0]
+
+ if frame_or_series is Series:
+ obj.iloc[:2] = box(arr[2:])
+ else:
+ obj.iloc[:2, 0] = box(arr[2:])
+
+ expected = frame_or_series(np.array([3, 4, 3, 4], dtype="i8"))
+ tm.assert_equal(obj, expected)
+
+ # Check that we are actually in-place
+ if frame_or_series is Series:
+ if using_copy_on_write:
+ assert obj.values is not values
+ assert np.shares_memory(obj.values, values)
+ else:
+ assert obj.values is values
+ else:
+ assert np.shares_memory(obj[0].values, values)
+
+ def test_is_scalar_access(self):
+ # GH#32085 index with duplicates doesn't matter for _is_scalar_access
+ index = Index([1, 2, 1])
+ ser = Series(range(3), index=index)
+
+ assert ser.iloc._is_scalar_access((1,))
+
+ df = ser.to_frame()
+ assert df.iloc._is_scalar_access((1, 0))
+
+ def test_iloc_exceeds_bounds(self):
+ # GH6296
+ # iloc should allow indexers that exceed the bounds
+ df = DataFrame(np.random.default_rng(2).random((20, 5)), columns=list("ABCDE"))
+
+ # lists of positions should raise IndexError!
+ msg = "positional indexers are out-of-bounds"
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[:, [0, 1, 2, 3, 4, 5]]
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[[1, 30]]
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[[1, -30]]
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[[100]]
+
+ s = df["A"]
+ with pytest.raises(IndexError, match=msg):
+ s.iloc[[100]]
+ with pytest.raises(IndexError, match=msg):
+ s.iloc[[-100]]
+
+ # still raise on a single indexer
+ msg = "single positional indexer is out-of-bounds"
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[30]
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[-30]
+
+ # GH10779
+ # single positive/negative indexer exceeding Series bounds should raise
+ # an IndexError
+ with pytest.raises(IndexError, match=msg):
+ s.iloc[30]
+ with pytest.raises(IndexError, match=msg):
+ s.iloc[-30]
+
+ # slices are ok
+ result = df.iloc[:, 4:10] # 0 < start < len < stop
+ expected = df.iloc[:, 4:]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[:, -4:-10] # stop < 0 < start < len
+ expected = df.iloc[:, :0]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[:, 10:4:-1] # 0 < stop < len < start (down)
+ expected = df.iloc[:, :4:-1]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[:, 4:-10:-1] # stop < 0 < start < len (down)
+ expected = df.iloc[:, 4::-1]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[:, -10:4] # start < 0 < stop < len
+ expected = df.iloc[:, :4]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[:, 10:4] # 0 < stop < len < start
+ expected = df.iloc[:, :0]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[:, -10:-11:-1] # stop < start < 0 < len (down)
+ expected = df.iloc[:, :0]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[:, 10:11] # 0 < len < start < stop
+ expected = df.iloc[:, :0]
+ tm.assert_frame_equal(result, expected)
+
+ # slice bounds exceeding is ok
+ result = s.iloc[18:30]
+ expected = s.iloc[18:]
+ tm.assert_series_equal(result, expected)
+
+ result = s.iloc[30:]
+ expected = s.iloc[:0]
+ tm.assert_series_equal(result, expected)
+
+ result = s.iloc[30::-1]
+ expected = s.iloc[::-1]
+ tm.assert_series_equal(result, expected)
+
+ # doc example
+ def check(result, expected):
+ str(result)
+ result.dtypes
+ tm.assert_frame_equal(result, expected)
+
+ dfl = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 2)), columns=list("AB")
+ )
+ check(dfl.iloc[:, 2:3], DataFrame(index=dfl.index, columns=[]))
+ check(dfl.iloc[:, 1:3], dfl.iloc[:, [1]])
+ check(dfl.iloc[4:6], dfl.iloc[[4]])
+
+ msg = "positional indexers are out-of-bounds"
+ with pytest.raises(IndexError, match=msg):
+ dfl.iloc[[4, 5, 6]]
+ msg = "single positional indexer is out-of-bounds"
+ with pytest.raises(IndexError, match=msg):
+ dfl.iloc[:, 4]
+
+ @pytest.mark.parametrize("index,columns", [(np.arange(20), list("ABCDE"))])
+ @pytest.mark.parametrize(
+ "index_vals,column_vals",
+ [
+ ([slice(None), ["A", "D"]]),
+ (["1", "2"], slice(None)),
+ ([datetime(2019, 1, 1)], slice(None)),
+ ],
+ )
+ def test_iloc_non_integer_raises(self, index, columns, index_vals, column_vals):
+ # GH 25753
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(index), len(columns))),
+ index=index,
+ columns=columns,
+ )
+ msg = ".iloc requires numeric indexers, got"
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[index_vals, column_vals]
+
+ def test_iloc_getitem_invalid_scalar(self, frame_or_series):
+ # GH 21982
+
+ obj = DataFrame(np.arange(100).reshape(10, 10))
+ obj = tm.get_obj(obj, frame_or_series)
+
+ with pytest.raises(TypeError, match="Cannot index by location index"):
+ obj.iloc["a"]
+
+ def test_iloc_array_not_mutating_negative_indices(self):
+ # GH 21867
+ array_with_neg_numbers = np.array([1, 2, -1])
+ array_copy = array_with_neg_numbers.copy()
+ df = DataFrame(
+ {"A": [100, 101, 102], "B": [103, 104, 105], "C": [106, 107, 108]},
+ index=[1, 2, 3],
+ )
+ df.iloc[array_with_neg_numbers]
+ tm.assert_numpy_array_equal(array_with_neg_numbers, array_copy)
+ df.iloc[:, array_with_neg_numbers]
+ tm.assert_numpy_array_equal(array_with_neg_numbers, array_copy)
+
+ def test_iloc_getitem_neg_int_can_reach_first_index(self):
+ # GH10547 and GH10779
+ # negative integers should be able to reach index 0
+ df = DataFrame({"A": [2, 3, 5], "B": [7, 11, 13]})
+ s = df["A"]
+
+ expected = df.iloc[0]
+ result = df.iloc[-3]
+ tm.assert_series_equal(result, expected)
+
+ expected = df.iloc[[0]]
+ result = df.iloc[[-3]]
+ tm.assert_frame_equal(result, expected)
+
+ expected = s.iloc[0]
+ result = s.iloc[-3]
+ assert result == expected
+
+ expected = s.iloc[[0]]
+ result = s.iloc[[-3]]
+ tm.assert_series_equal(result, expected)
+
+ # check the length 1 Series case highlighted in GH10547
+ expected = Series(["a"], index=["A"])
+ result = expected.iloc[[-1]]
+ tm.assert_series_equal(result, expected)
+
+ def test_iloc_getitem_dups(self):
+ # GH 6766
+ df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}])
+ df2 = DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}])
+ df = concat([df1, df2], axis=1)
+
+ # cross-sectional indexing
+ result = df.iloc[0, 0]
+ assert isna(result)
+
+ result = df.iloc[0, :]
+ expected = Series([np.nan, 1, 3, 3], index=["A", "B", "A", "B"], name=0)
+ tm.assert_series_equal(result, expected)
+
+ def test_iloc_getitem_array(self):
+ df = DataFrame(
+ [
+ {"A": 1, "B": 2, "C": 3},
+ {"A": 100, "B": 200, "C": 300},
+ {"A": 1000, "B": 2000, "C": 3000},
+ ]
+ )
+
+ expected = DataFrame([{"A": 1, "B": 2, "C": 3}])
+ tm.assert_frame_equal(df.iloc[[0]], expected)
+
+ expected = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 100, "B": 200, "C": 300}])
+ tm.assert_frame_equal(df.iloc[[0, 1]], expected)
+
+ expected = DataFrame([{"B": 2, "C": 3}, {"B": 2000, "C": 3000}], index=[0, 2])
+ result = df.iloc[[0, 2], [1, 2]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_iloc_getitem_bool(self):
+ df = DataFrame(
+ [
+ {"A": 1, "B": 2, "C": 3},
+ {"A": 100, "B": 200, "C": 300},
+ {"A": 1000, "B": 2000, "C": 3000},
+ ]
+ )
+
+ expected = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 100, "B": 200, "C": 300}])
+ result = df.iloc[[True, True, False]]
+ tm.assert_frame_equal(result, expected)
+
+ expected = DataFrame(
+ [{"A": 1, "B": 2, "C": 3}, {"A": 1000, "B": 2000, "C": 3000}], index=[0, 2]
+ )
+ result = df.iloc[lambda x: x.index % 2 == 0]
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("index", [[True, False], [True, False, True, False]])
+ def test_iloc_getitem_bool_diff_len(self, index):
+ # GH26658
+ s = Series([1, 2, 3])
+ msg = f"Boolean index has wrong length: {len(index)} instead of {len(s)}"
+ with pytest.raises(IndexError, match=msg):
+ s.iloc[index]
+
+ def test_iloc_getitem_slice(self):
+ df = DataFrame(
+ [
+ {"A": 1, "B": 2, "C": 3},
+ {"A": 100, "B": 200, "C": 300},
+ {"A": 1000, "B": 2000, "C": 3000},
+ ]
+ )
+
+ expected = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 100, "B": 200, "C": 300}])
+ result = df.iloc[:2]
+ tm.assert_frame_equal(result, expected)
+
+ expected = DataFrame([{"A": 100, "B": 200}], index=[1])
+ result = df.iloc[1:2, 0:2]
+ tm.assert_frame_equal(result, expected)
+
+ expected = DataFrame(
+ [{"A": 1, "C": 3}, {"A": 100, "C": 300}, {"A": 1000, "C": 3000}]
+ )
+ result = df.iloc[:, lambda df: [0, 2]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_iloc_getitem_slice_dups(self):
+ df1 = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)),
+ columns=["A", "A", "B", "B"],
+ )
+ df2 = DataFrame(
+ np.random.default_rng(2).integers(0, 10, size=20).reshape(10, 2),
+ columns=["A", "C"],
+ )
+
+ # axis=1
+ df = concat([df1, df2], axis=1)
+ tm.assert_frame_equal(df.iloc[:, :4], df1)
+ tm.assert_frame_equal(df.iloc[:, 4:], df2)
+
+ df = concat([df2, df1], axis=1)
+ tm.assert_frame_equal(df.iloc[:, :2], df2)
+ tm.assert_frame_equal(df.iloc[:, 2:], df1)
+
+ exp = concat([df2, df1.iloc[:, [0]]], axis=1)
+ tm.assert_frame_equal(df.iloc[:, 0:3], exp)
+
+ # axis=0
+ df = concat([df, df], axis=0)
+ tm.assert_frame_equal(df.iloc[0:10, :2], df2)
+ tm.assert_frame_equal(df.iloc[0:10, 2:], df1)
+ tm.assert_frame_equal(df.iloc[10:, :2], df2)
+ tm.assert_frame_equal(df.iloc[10:, 2:], df1)
+
+ def test_iloc_setitem(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=np.arange(0, 8, 2),
+ columns=np.arange(0, 12, 3),
+ )
+
+ df.iloc[1, 1] = 1
+ result = df.iloc[1, 1]
+ assert result == 1
+
+ df.iloc[:, 2:3] = 0
+ expected = df.iloc[:, 2:3]
+ result = df.iloc[:, 2:3]
+ tm.assert_frame_equal(result, expected)
+
+ # GH5771
+ s = Series(0, index=[4, 5, 6])
+ s.iloc[1:2] += 1
+ expected = Series([0, 1, 0], index=[4, 5, 6])
+ tm.assert_series_equal(s, expected)
+
+ def test_iloc_setitem_axis_argument(self):
+ # GH45032
+ df = DataFrame([[6, "c", 10], [7, "d", 11], [8, "e", 12]])
+ expected = DataFrame([[6, "c", 10], [7, "d", 11], [5, 5, 5]])
+ df.iloc(axis=0)[2] = 5
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame([[6, "c", 10], [7, "d", 11], [8, "e", 12]])
+ expected = DataFrame([[6, "c", 5], [7, "d", 5], [8, "e", 5]])
+ df.iloc(axis=1)[2] = 5
+ tm.assert_frame_equal(df, expected)
+
+ def test_iloc_setitem_list(self):
+ # setitem with an iloc list
+ df = DataFrame(
+ np.arange(9).reshape((3, 3)), index=["A", "B", "C"], columns=["A", "B", "C"]
+ )
+ df.iloc[[0, 1], [1, 2]]
+ df.iloc[[0, 1], [1, 2]] += 100
+
+ expected = DataFrame(
+ np.array([0, 101, 102, 3, 104, 105, 6, 7, 8]).reshape((3, 3)),
+ index=["A", "B", "C"],
+ columns=["A", "B", "C"],
+ )
+ tm.assert_frame_equal(df, expected)
+
+ def test_iloc_setitem_pandas_object(self):
+ # GH 17193
+ s_orig = Series([0, 1, 2, 3])
+ expected = Series([0, -1, -2, 3])
+
+ s = s_orig.copy()
+ s.iloc[Series([1, 2])] = [-1, -2]
+ tm.assert_series_equal(s, expected)
+
+ s = s_orig.copy()
+ s.iloc[Index([1, 2])] = [-1, -2]
+ tm.assert_series_equal(s, expected)
+
+ def test_iloc_setitem_dups(self):
+ # GH 6766
+ # iloc with a mask aligning from another iloc
+ df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}])
+ df2 = DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}])
+ df = concat([df1, df2], axis=1)
+
+ expected = df.fillna(3)
+ inds = np.isnan(df.iloc[:, 0])
+ mask = inds[inds].index
+ df.iloc[mask, 0] = df.iloc[mask, 2]
+ tm.assert_frame_equal(df, expected)
+
+ # del a dup column across blocks
+ expected = DataFrame({0: [1, 2], 1: [3, 4]})
+ expected.columns = ["B", "B"]
+ del df["A"]
+ tm.assert_frame_equal(df, expected)
+
+ # assign back to self
+ df.iloc[[0, 1], [0, 1]] = df.iloc[[0, 1], [0, 1]]
+ tm.assert_frame_equal(df, expected)
+
+ # reversed x 2
+ df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index(drop=True)
+ df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index(drop=True)
+ tm.assert_frame_equal(df, expected)
+
+ def test_iloc_setitem_frame_duplicate_columns_multiple_blocks(
+ self, using_array_manager
+ ):
+ # Same as the "assign back to self" check in test_iloc_setitem_dups
+ # but on a DataFrame with multiple blocks
+ df = DataFrame([[0, 1], [2, 3]], columns=["B", "B"])
+
+ # setting float values that can be held by existing integer arrays
+ # is inplace
+ df.iloc[:, 0] = df.iloc[:, 0].astype("f8")
+ if not using_array_manager:
+ assert len(df._mgr.blocks) == 1
+
+ # if the assigned values cannot be held by existing integer arrays,
+ # we cast
+ df.iloc[:, 0] = df.iloc[:, 0] + 0.5
+ if not using_array_manager:
+ assert len(df._mgr.blocks) == 2
+
+ expected = df.copy()
+
+ # assign back to self
+ df.iloc[[0, 1], [0, 1]] = df.iloc[[0, 1], [0, 1]]
+
+ tm.assert_frame_equal(df, expected)
+
+ # TODO: GH#27620 this test used to compare iloc against ix; check if this
+ # is redundant with another test comparing iloc against loc
+ def test_iloc_getitem_frame(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)),
+ index=range(0, 20, 2),
+ columns=range(0, 8, 2),
+ )
+
+ result = df.iloc[2]
+ exp = df.loc[4]
+ tm.assert_series_equal(result, exp)
+
+ result = df.iloc[2, 2]
+ exp = df.loc[4, 4]
+ assert result == exp
+
+ # slice
+ result = df.iloc[4:8]
+ expected = df.loc[8:14]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[:, 2:3]
+ expected = df.loc[:, 4:5]
+ tm.assert_frame_equal(result, expected)
+
+ # list of integers
+ result = df.iloc[[0, 1, 3]]
+ expected = df.loc[[0, 2, 6]]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.iloc[[0, 1, 3], [0, 1]]
+ expected = df.loc[[0, 2, 6], [0, 2]]
+ tm.assert_frame_equal(result, expected)
+
+ # neg indices
+ result = df.iloc[[-1, 1, 3], [-1, 1]]
+ expected = df.loc[[18, 2, 6], [6, 2]]
+ tm.assert_frame_equal(result, expected)
+
+ # dups indices
+ result = df.iloc[[-1, -1, 1, 3], [-1, 1]]
+ expected = df.loc[[18, 18, 2, 6], [6, 2]]
+ tm.assert_frame_equal(result, expected)
+
+ # with index-like
+ s = Series(index=range(1, 5), dtype=object)
+ result = df.iloc[s.index]
+ expected = df.loc[[2, 4, 6, 8]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_iloc_getitem_labelled_frame(self):
+ # try with labelled frame
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)),
+ index=list("abcdefghij"),
+ columns=list("ABCD"),
+ )
+
+ result = df.iloc[1, 1]
+ exp = df.loc["b", "B"]
+ assert result == exp
+
+ result = df.iloc[:, 2:3]
+ expected = df.loc[:, ["C"]]
+ tm.assert_frame_equal(result, expected)
+
+ # negative indexing
+ result = df.iloc[-1, -1]
+ exp = df.loc["j", "D"]
+ assert result == exp
+
+ # out-of-bounds exception
+ msg = "index 5 is out of bounds for axis 0 with size 4"
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[10, 5]
+
+ # trying to use a label
+ msg = (
+ r"Location based indexing can only have \[integer, integer "
+ r"slice \(START point is INCLUDED, END point is EXCLUDED\), "
+ r"listlike of integers, boolean array\] types"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.iloc["j", "D"]
+
+ def test_iloc_getitem_doc_issue(self, using_array_manager):
+ # multi axis slicing issue with single block
+ # surfaced in GH 6059
+
+ arr = np.random.default_rng(2).standard_normal((6, 4))
+ index = date_range("20130101", periods=6)
+ columns = list("ABCD")
+ df = DataFrame(arr, index=index, columns=columns)
+
+ # defines ref_locs
+ df.describe()
+
+ result = df.iloc[3:5, 0:2]
+ str(result)
+ result.dtypes
+
+ expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=columns[0:2])
+ tm.assert_frame_equal(result, expected)
+
+ # for dups
+ df.columns = list("aaaa")
+ result = df.iloc[3:5, 0:2]
+ str(result)
+ result.dtypes
+
+ expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=list("aa"))
+ tm.assert_frame_equal(result, expected)
+
+ # related
+ arr = np.random.default_rng(2).standard_normal((6, 4))
+ index = list(range(0, 12, 2))
+ columns = list(range(0, 8, 2))
+ df = DataFrame(arr, index=index, columns=columns)
+
+ if not using_array_manager:
+ df._mgr.blocks[0].mgr_locs
+ result = df.iloc[1:5, 2:4]
+ str(result)
+ result.dtypes
+ expected = DataFrame(arr[1:5, 2:4], index=index[1:5], columns=columns[2:4])
+ tm.assert_frame_equal(result, expected)
+
+ def test_iloc_setitem_series(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)),
+ index=list("abcdefghij"),
+ columns=list("ABCD"),
+ )
+
+ df.iloc[1, 1] = 1
+ result = df.iloc[1, 1]
+ assert result == 1
+
+ df.iloc[:, 2:3] = 0
+ expected = df.iloc[:, 2:3]
+ result = df.iloc[:, 2:3]
+ tm.assert_frame_equal(result, expected)
+
+ s = Series(np.random.default_rng(2).standard_normal(10), index=range(0, 20, 2))
+
+ s.iloc[1] = 1
+ result = s.iloc[1]
+ assert result == 1
+
+ s.iloc[:4] = 0
+ expected = s.iloc[:4]
+ result = s.iloc[:4]
+ tm.assert_series_equal(result, expected)
+
+ s = Series([-1] * 6)
+ s.iloc[0::2] = [0, 2, 4]
+ s.iloc[1::2] = [1, 3, 5]
+ result = s
+ expected = Series([0, 1, 2, 3, 4, 5])
+ tm.assert_series_equal(result, expected)
+
+ def test_iloc_setitem_list_of_lists(self):
+ # GH 7551
+ # list-of-list is set incorrectly in mixed vs. single dtyped frames
+ df = DataFrame(
+ {"A": np.arange(5, dtype="int64"), "B": np.arange(5, 10, dtype="int64")}
+ )
+ df.iloc[2:4] = [[10, 11], [12, 13]]
+ expected = DataFrame({"A": [0, 1, 10, 12, 4], "B": [5, 6, 11, 13, 9]})
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame(
+ {"A": ["a", "b", "c", "d", "e"], "B": np.arange(5, 10, dtype="int64")}
+ )
+ df.iloc[2:4] = [["x", 11], ["y", 13]]
+ expected = DataFrame({"A": ["a", "b", "x", "y", "e"], "B": [5, 6, 11, 13, 9]})
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("indexer", [[0], slice(None, 1, None), np.array([0])])
+ @pytest.mark.parametrize("value", [["Z"], np.array(["Z"])])
+ def test_iloc_setitem_with_scalar_index(self, indexer, value):
+ # GH #19474
+ # assigning like "df.iloc[0, [0]] = ['Z']" should be evaluated
+ # elementwisely, not using "setter('A', ['Z'])".
+
+ # Set object type to avoid upcast when setting "Z"
+ df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"]).astype({"A": object})
+ df.iloc[0, indexer] = value
+ result = df.iloc[0, 0]
+
+ assert is_scalar(result) and result == "Z"
+
+ @pytest.mark.filterwarnings("ignore::UserWarning")
+ def test_iloc_mask(self):
+ # GH 3631, iloc with a mask (of a series) should raise
+ df = DataFrame(list(range(5)), index=list("ABCDE"), columns=["a"])
+ mask = df.a % 2 == 0
+ msg = "iLocation based boolean indexing cannot use an indexable as a mask"
+ with pytest.raises(ValueError, match=msg):
+ df.iloc[mask]
+ mask.index = range(len(mask))
+ msg = "iLocation based boolean indexing on an integer type is not available"
+ with pytest.raises(NotImplementedError, match=msg):
+ df.iloc[mask]
+
+ # ndarray ok
+ result = df.iloc[np.array([True] * len(mask), dtype=bool)]
+ tm.assert_frame_equal(result, df)
+
+ # the possibilities
+ locs = np.arange(4)
+ nums = 2**locs
+ reps = [bin(num) for num in nums]
+ df = DataFrame({"locs": locs, "nums": nums}, reps)
+
+ expected = {
+ (None, ""): "0b1100",
+ (None, ".loc"): "0b1100",
+ (None, ".iloc"): "0b1100",
+ ("index", ""): "0b11",
+ ("index", ".loc"): "0b11",
+ ("index", ".iloc"): (
+ "iLocation based boolean indexing cannot use an indexable as a mask"
+ ),
+ ("locs", ""): "Unalignable boolean Series provided as indexer "
+ "(index of the boolean Series and of the indexed "
+ "object do not match).",
+ ("locs", ".loc"): "Unalignable boolean Series provided as indexer "
+ "(index of the boolean Series and of the "
+ "indexed object do not match).",
+ ("locs", ".iloc"): (
+ "iLocation based boolean indexing on an "
+ "integer type is not available"
+ ),
+ }
+
+ # UserWarnings from reindex of a boolean mask
+ for idx in [None, "index", "locs"]:
+ mask = (df.nums > 2).values
+ if idx:
+ mask_index = getattr(df, idx)[::-1]
+ mask = Series(mask, list(mask_index))
+ for method in ["", ".loc", ".iloc"]:
+ try:
+ if method:
+ accessor = getattr(df, method[1:])
+ else:
+ accessor = df
+ answer = str(bin(accessor[mask]["nums"].sum()))
+ except (ValueError, IndexingError, NotImplementedError) as e:
+ answer = str(e)
+
+ key = (
+ idx,
+ method,
+ )
+ r = expected.get(key)
+ if r != answer:
+ raise AssertionError(
+ f"[{key}] does not match [{answer}], received [{r}]"
+ )
+
+ def test_iloc_non_unique_indexing(self):
+ # GH 4017, non-unique indexing (on the axis)
+ df = DataFrame({"A": [0.1] * 3000, "B": [1] * 3000})
+ idx = np.arange(30) * 99
+ expected = df.iloc[idx]
+
+ df3 = concat([df, 2 * df, 3 * df])
+ result = df3.iloc[idx]
+
+ tm.assert_frame_equal(result, expected)
+
+ df2 = DataFrame({"A": [0.1] * 1000, "B": [1] * 1000})
+ df2 = concat([df2, 2 * df2, 3 * df2])
+
+ with pytest.raises(KeyError, match="not in index"):
+ df2.loc[idx]
+
+ def test_iloc_empty_list_indexer_is_ok(self):
+ df = tm.makeCustomDataframe(5, 2)
+ # vertical empty
+ tm.assert_frame_equal(
+ df.iloc[:, []],
+ df.iloc[:, :0],
+ check_index_type=True,
+ check_column_type=True,
+ )
+ # horizontal empty
+ tm.assert_frame_equal(
+ df.iloc[[], :],
+ df.iloc[:0, :],
+ check_index_type=True,
+ check_column_type=True,
+ )
+ # horizontal empty
+ tm.assert_frame_equal(
+ df.iloc[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True
+ )
+
+ def test_identity_slice_returns_new_object(self, using_copy_on_write):
+ # GH13873
+ original_df = DataFrame({"a": [1, 2, 3]})
+ sliced_df = original_df.iloc[:]
+ assert sliced_df is not original_df
+
+ # should be a shallow copy
+ assert np.shares_memory(original_df["a"], sliced_df["a"])
+
+ # Setting using .loc[:, "a"] sets inplace so alters both sliced and orig
+ # depending on CoW
+ original_df.loc[:, "a"] = [4, 4, 4]
+ if using_copy_on_write:
+ assert (sliced_df["a"] == [1, 2, 3]).all()
+ else:
+ assert (sliced_df["a"] == 4).all()
+
+ original_series = Series([1, 2, 3, 4, 5, 6])
+ sliced_series = original_series.iloc[:]
+ assert sliced_series is not original_series
+
+ # should also be a shallow copy
+ original_series[:3] = [7, 8, 9]
+ if using_copy_on_write:
+ # shallow copy not updated (CoW)
+ assert all(sliced_series[:3] == [1, 2, 3])
+ else:
+ assert all(sliced_series[:3] == [7, 8, 9])
+
+ def test_indexing_zerodim_np_array(self):
+ # GH24919
+ df = DataFrame([[1, 2], [3, 4]])
+ result = df.iloc[np.array(0)]
+ s = Series([1, 2], name=0)
+ tm.assert_series_equal(result, s)
+
+ def test_series_indexing_zerodim_np_array(self):
+ # GH24919
+ s = Series([1, 2])
+ result = s.iloc[np.array(0)]
+ assert result == 1
+
+ def test_iloc_setitem_categorical_updates_inplace(self):
+ # Mixed dtype ensures we go through take_split_path in setitem_with_indexer
+ cat = Categorical(["A", "B", "C"])
+ df = DataFrame({1: cat, 2: [1, 2, 3]}, copy=False)
+
+ assert tm.shares_memory(df[1], cat)
+
+ # With the enforcement of GH#45333 in 2.0, this modifies original
+ # values inplace
+ df.iloc[:, 0] = cat[::-1]
+
+ assert tm.shares_memory(df[1], cat)
+ expected = Categorical(["C", "B", "A"], categories=["A", "B", "C"])
+ tm.assert_categorical_equal(cat, expected)
+
+ def test_iloc_with_boolean_operation(self):
+ # GH 20627
+ result = DataFrame([[0, 1], [2, 3], [4, 5], [6, np.nan]])
+ result.iloc[result.index <= 2] *= 2
+ expected = DataFrame([[0, 2], [4, 6], [8, 10], [6, np.nan]])
+ tm.assert_frame_equal(result, expected)
+
+ result.iloc[result.index > 2] *= 2
+ expected = DataFrame([[0, 2], [4, 6], [8, 10], [12, np.nan]])
+ tm.assert_frame_equal(result, expected)
+
+ result.iloc[[True, True, False, False]] *= 2
+ expected = DataFrame([[0, 4], [8, 12], [8, 10], [12, np.nan]])
+ tm.assert_frame_equal(result, expected)
+
+ result.iloc[[False, False, True, True]] /= 2
+ expected = DataFrame([[0, 4.0], [8, 12.0], [4, 5.0], [6, np.nan]])
+ tm.assert_frame_equal(result, expected)
+
+ def test_iloc_getitem_singlerow_slice_categoricaldtype_gives_series(self):
+ # GH#29521
+ df = DataFrame({"x": Categorical("a b c d e".split())})
+ result = df.iloc[0]
+ raw_cat = Categorical(["a"], categories=["a", "b", "c", "d", "e"])
+ expected = Series(raw_cat, index=["x"], name=0, dtype="category")
+
+ tm.assert_series_equal(result, expected)
+
+ def test_iloc_getitem_categorical_values(self):
+ # GH#14580
+ # test iloc() on Series with Categorical data
+
+ ser = Series([1, 2, 3]).astype("category")
+
+ # get slice
+ result = ser.iloc[0:2]
+ expected = Series([1, 2]).astype(CategoricalDtype([1, 2, 3]))
+ tm.assert_series_equal(result, expected)
+
+ # get list of indexes
+ result = ser.iloc[[0, 1]]
+ expected = Series([1, 2]).astype(CategoricalDtype([1, 2, 3]))
+ tm.assert_series_equal(result, expected)
+
+ # get boolean array
+ result = ser.iloc[[True, False, False]]
+ expected = Series([1]).astype(CategoricalDtype([1, 2, 3]))
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("value", [None, NaT, np.nan])
+ def test_iloc_setitem_td64_values_cast_na(self, value):
+ # GH#18586
+ series = Series([0, 1, 2], dtype="timedelta64[ns]")
+ series.iloc[0] = value
+ expected = Series([NaT, 1, 2], dtype="timedelta64[ns]")
+ tm.assert_series_equal(series, expected)
+
+ @pytest.mark.parametrize("not_na", [Interval(0, 1), "a", 1.0])
+ def test_setitem_mix_of_nan_and_interval(self, not_na, nulls_fixture):
+ # GH#27937
+ dtype = CategoricalDtype(categories=[not_na])
+ ser = Series(
+ [nulls_fixture, nulls_fixture, nulls_fixture, nulls_fixture], dtype=dtype
+ )
+ ser.iloc[:3] = [nulls_fixture, not_na, nulls_fixture]
+ exp = Series([nulls_fixture, not_na, nulls_fixture, nulls_fixture], dtype=dtype)
+ tm.assert_series_equal(ser, exp)
+
+ def test_iloc_setitem_empty_frame_raises_with_3d_ndarray(self):
+ idx = Index([])
+ obj = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), len(idx))),
+ index=idx,
+ columns=idx,
+ )
+ nd3 = np.random.default_rng(2).integers(5, size=(2, 2, 2))
+
+ msg = f"Cannot set values with ndim > {obj.ndim}"
+ with pytest.raises(ValueError, match=msg):
+ obj.iloc[nd3] = 0
+
+ @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
+ def test_iloc_getitem_read_only_values(self, indexer):
+ # GH#10043 this is fundamentally a test for iloc, but test loc while
+ # we're here
+ rw_array = np.eye(10)
+ rw_df = DataFrame(rw_array)
+
+ ro_array = np.eye(10)
+ ro_array.setflags(write=False)
+ ro_df = DataFrame(ro_array)
+
+ tm.assert_frame_equal(indexer(rw_df)[[1, 2, 3]], indexer(ro_df)[[1, 2, 3]])
+ tm.assert_frame_equal(indexer(rw_df)[[1]], indexer(ro_df)[[1]])
+ tm.assert_series_equal(indexer(rw_df)[1], indexer(ro_df)[1])
+ tm.assert_frame_equal(indexer(rw_df)[1:3], indexer(ro_df)[1:3])
+
+ def test_iloc_getitem_readonly_key(self):
+ # GH#17192 iloc with read-only array raising TypeError
+ df = DataFrame({"data": np.ones(100, dtype="float64")})
+ indices = np.array([1, 3, 6])
+ indices.flags.writeable = False
+
+ result = df.iloc[indices]
+ expected = df.loc[[1, 3, 6]]
+ tm.assert_frame_equal(result, expected)
+
+ result = df["data"].iloc[indices]
+ expected = df["data"].loc[[1, 3, 6]]
+ tm.assert_series_equal(result, expected)
+
+ def test_iloc_assign_series_to_df_cell(self):
+ # GH 37593
+ df = DataFrame(columns=["a"], index=[0])
+ df.iloc[0, 0] = Series([1, 2, 3])
+ expected = DataFrame({"a": [Series([1, 2, 3])]}, columns=["a"], index=[0])
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("klass", [list, np.array])
+ def test_iloc_setitem_bool_indexer(self, klass):
+ # GH#36741
+ df = DataFrame({"flag": ["x", "y", "z"], "value": [1, 3, 4]})
+ indexer = klass([True, False, False])
+ df.iloc[indexer, 1] = df.iloc[indexer, 1] * 2
+ expected = DataFrame({"flag": ["x", "y", "z"], "value": [2, 3, 4]})
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("indexer", [[1], slice(1, 2)])
+ def test_iloc_setitem_pure_position_based(self, indexer):
+ # GH#22046
+ df1 = DataFrame({"a2": [11, 12, 13], "b2": [14, 15, 16]})
+ df2 = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})
+ df2.iloc[:, indexer] = df1.iloc[:, [0]]
+ expected = DataFrame({"a": [1, 2, 3], "b": [11, 12, 13], "c": [7, 8, 9]})
+ tm.assert_frame_equal(df2, expected)
+
+ def test_iloc_setitem_dictionary_value(self):
+ # GH#37728
+ df = DataFrame({"x": [1, 2], "y": [2, 2]})
+ rhs = {"x": 9, "y": 99}
+ df.iloc[1] = rhs
+ expected = DataFrame({"x": [1, 9], "y": [2, 99]})
+ tm.assert_frame_equal(df, expected)
+
+ # GH#38335 same thing, mixed dtypes
+ df = DataFrame({"x": [1, 2], "y": [2.0, 2.0]})
+ df.iloc[1] = rhs
+ expected = DataFrame({"x": [1, 9], "y": [2.0, 99.0]})
+ tm.assert_frame_equal(df, expected)
+
+ def test_iloc_getitem_float_duplicates(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ index=[0.1, 0.2, 0.2],
+ columns=list("abc"),
+ )
+ expect = df.iloc[1:]
+ tm.assert_frame_equal(df.loc[0.2], expect)
+
+ expect = df.iloc[1:, 0]
+ tm.assert_series_equal(df.loc[0.2, "a"], expect)
+
+ df.index = [1, 0.2, 0.2]
+ expect = df.iloc[1:]
+ tm.assert_frame_equal(df.loc[0.2], expect)
+
+ expect = df.iloc[1:, 0]
+ tm.assert_series_equal(df.loc[0.2, "a"], expect)
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 3)),
+ index=[1, 0.2, 0.2, 1],
+ columns=list("abc"),
+ )
+ expect = df.iloc[1:-1]
+ tm.assert_frame_equal(df.loc[0.2], expect)
+
+ expect = df.iloc[1:-1, 0]
+ tm.assert_series_equal(df.loc[0.2, "a"], expect)
+
+ df.index = [0.1, 0.2, 2, 0.2]
+ expect = df.iloc[[1, -1]]
+ tm.assert_frame_equal(df.loc[0.2], expect)
+
+ expect = df.iloc[[1, -1], 0]
+ tm.assert_series_equal(df.loc[0.2, "a"], expect)
+
+ def test_iloc_setitem_custom_object(self):
+ # iloc with an object
+ class TO:
+ def __init__(self, value) -> None:
+ self.value = value
+
+ def __str__(self) -> str:
+ return f"[{self.value}]"
+
+ __repr__ = __str__
+
+ def __eq__(self, other) -> bool:
+ return self.value == other.value
+
+ def view(self):
+ return self
+
+ df = DataFrame(index=[0, 1], columns=[0])
+ df.iloc[1, 0] = TO(1)
+ df.iloc[1, 0] = TO(2)
+
+ result = DataFrame(index=[0, 1], columns=[0])
+ result.iloc[1, 0] = TO(2)
+
+ tm.assert_frame_equal(result, df)
+
+ # remains object dtype even after setting it back
+ df = DataFrame(index=[0, 1], columns=[0])
+ df.iloc[1, 0] = TO(1)
+ df.iloc[1, 0] = np.nan
+ result = DataFrame(index=[0, 1], columns=[0])
+
+ tm.assert_frame_equal(result, df)
+
+ def test_iloc_getitem_with_duplicates(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((3, 3)),
+ columns=list("ABC"),
+ index=list("aab"),
+ )
+
+ result = df.iloc[0]
+ assert isinstance(result, Series)
+ tm.assert_almost_equal(result.values, df.values[0])
+
+ result = df.T.iloc[:, 0]
+ assert isinstance(result, Series)
+ tm.assert_almost_equal(result.values, df.values[0])
+
+ def test_iloc_getitem_with_duplicates2(self):
+ # GH#2259
+ df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1, 1, 2])
+ result = df.iloc[:, [0]]
+ expected = df.take([0], axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ def test_iloc_interval(self):
+ # GH#17130
+ df = DataFrame({Interval(1, 2): [1, 2]})
+
+ result = df.iloc[0]
+ expected = Series({Interval(1, 2): 1}, name=0)
+ tm.assert_series_equal(result, expected)
+
+ result = df.iloc[:, 0]
+ expected = Series([1, 2], name=Interval(1, 2))
+ tm.assert_series_equal(result, expected)
+
+ result = df.copy()
+ result.iloc[:, 0] += 1
+ expected = DataFrame({Interval(1, 2): [2, 3]})
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("indexing_func", [list, np.array])
+ @pytest.mark.parametrize("rhs_func", [list, np.array])
+ def test_loc_setitem_boolean_list(self, rhs_func, indexing_func):
+ # GH#20438 testing specifically list key, not arraylike
+ ser = Series([0, 1, 2])
+ ser.iloc[indexing_func([True, False, True])] = rhs_func([5, 10])
+ expected = Series([5, 1, 10])
+ tm.assert_series_equal(ser, expected)
+
+ df = DataFrame({"a": [0, 1, 2]})
+ df.iloc[indexing_func([True, False, True])] = rhs_func([[5], [10]])
+ expected = DataFrame({"a": [5, 1, 10]})
+ tm.assert_frame_equal(df, expected)
+
+ def test_iloc_getitem_slice_negative_step_ea_block(self):
+ # GH#44551
+ df = DataFrame({"A": [1, 2, 3]}, dtype="Int64")
+
+ res = df.iloc[:, ::-1]
+ tm.assert_frame_equal(res, df)
+
+ df["B"] = "foo"
+ res = df.iloc[:, ::-1]
+ expected = DataFrame({"B": df["B"], "A": df["A"]})
+ tm.assert_frame_equal(res, expected)
+
+ def test_iloc_setitem_2d_ndarray_into_ea_block(self):
+ # GH#44703
+ df = DataFrame({"status": ["a", "b", "c"]}, dtype="category")
+ df.iloc[np.array([0, 1]), np.array([0])] = np.array([["a"], ["a"]])
+
+ expected = DataFrame({"status": ["a", "a", "c"]}, dtype=df["status"].dtype)
+ tm.assert_frame_equal(df, expected)
+
+ @td.skip_array_manager_not_yet_implemented
+ def test_iloc_getitem_int_single_ea_block_view(self):
+ # GH#45241
+ # TODO: make an extension interface test for this?
+ arr = interval_range(1, 10.0)._values
+ df = DataFrame(arr)
+
+ # ser should be a *view* on the DataFrame data
+ ser = df.iloc[2]
+
+ # if we have a view, then changing arr[2] should also change ser[0]
+ assert arr[2] != arr[-1] # otherwise the rest isn't meaningful
+ arr[2] = arr[-1]
+ assert ser[0] == arr[-1]
+
+ def test_iloc_setitem_multicolumn_to_datetime(self):
+ # GH#20511
+ df = DataFrame({"A": ["2022-01-01", "2022-01-02"], "B": ["2021", "2022"]})
+
+ df.iloc[:, [0]] = DataFrame({"A": to_datetime(["2021", "2022"])})
+ expected = DataFrame(
+ {
+ "A": [
+ Timestamp("2021-01-01 00:00:00"),
+ Timestamp("2022-01-01 00:00:00"),
+ ],
+ "B": ["2021", "2022"],
+ }
+ )
+ tm.assert_frame_equal(df, expected, check_dtype=False)
+
+
+class TestILocErrors:
+ # NB: this test should work for _any_ Series we can pass as
+ # series_with_simple_index
+ def test_iloc_float_raises(self, series_with_simple_index, frame_or_series):
+ # GH#4892
+ # float_indexers should raise exceptions
+ # on appropriate Index types & accessors
+ # this duplicates the code below
+ # but is specifically testing for the error
+ # message
+
+ obj = series_with_simple_index
+ if frame_or_series is DataFrame:
+ obj = obj.to_frame()
+
+ msg = "Cannot index by location index with a non-integer key"
+ with pytest.raises(TypeError, match=msg):
+ obj.iloc[3.0]
+
+ with pytest.raises(IndexError, match=_slice_iloc_msg):
+ obj.iloc[3.0] = 0
+
+ def test_iloc_getitem_setitem_fancy_exceptions(self, float_frame):
+ with pytest.raises(IndexingError, match="Too many indexers"):
+ float_frame.iloc[:, :, :]
+
+ with pytest.raises(IndexError, match="too many indices for array"):
+ # GH#32257 we let numpy do validation, get their exception
+ float_frame.iloc[:, :, :] = 1
+
+ def test_iloc_frame_indexer(self):
+ # GH#39004
+ df = DataFrame({"a": [1, 2, 3]})
+ indexer = DataFrame({"a": [True, False, True]})
+ msg = "DataFrame indexer for .iloc is not supported. Consider using .loc"
+ with pytest.raises(TypeError, match=msg):
+ df.iloc[indexer] = 1
+
+ msg = (
+ "DataFrame indexer is not allowed for .iloc\n"
+ "Consider using .loc for automatic alignment."
+ )
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[indexer]
+
+
+class TestILocSetItemDuplicateColumns:
+ def test_iloc_setitem_scalar_duplicate_columns(self):
+ # GH#15686, duplicate columns and mixed dtype
+ df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}])
+ df2 = DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}])
+ df = concat([df1, df2], axis=1)
+ df.iloc[0, 0] = -1
+
+ assert df.iloc[0, 0] == -1
+ assert df.iloc[0, 2] == 3
+ assert df.dtypes.iloc[2] == np.int64
+
+ def test_iloc_setitem_list_duplicate_columns(self):
+ # GH#22036 setting with same-sized list
+ df = DataFrame([[0, "str", "str2"]], columns=["a", "b", "b"])
+
+ df.iloc[:, 2] = ["str3"]
+
+ expected = DataFrame([[0, "str", "str3"]], columns=["a", "b", "b"])
+ tm.assert_frame_equal(df, expected)
+
+ def test_iloc_setitem_series_duplicate_columns(self):
+ df = DataFrame(
+ np.arange(8, dtype=np.int64).reshape(2, 4), columns=["A", "B", "A", "B"]
+ )
+ df.iloc[:, 0] = df.iloc[:, 0].astype(np.float64)
+ assert df.dtypes.iloc[2] == np.int64
+
+ @pytest.mark.parametrize(
+ ["dtypes", "init_value", "expected_value"],
+ [("int64", "0", 0), ("float", "1.2", 1.2)],
+ )
+ def test_iloc_setitem_dtypes_duplicate_columns(
+ self, dtypes, init_value, expected_value
+ ):
+ # GH#22035
+ df = DataFrame([[init_value, "str", "str2"]], columns=["a", "b", "b"])
+
+ # with the enforcement of GH#45333 in 2.0, this sets values inplace,
+ # so we retain object dtype
+ df.iloc[:, 0] = df.iloc[:, 0].astype(dtypes)
+
+ expected_df = DataFrame(
+ [[expected_value, "str", "str2"]],
+ columns=["a", "b", "b"],
+ dtype=object,
+ )
+ tm.assert_frame_equal(df, expected_df)
+
+
+class TestILocCallable:
+ def test_frame_iloc_getitem_callable(self):
+ # GH#11485
+ df = DataFrame({"X": [1, 2, 3, 4], "Y": list("aabb")}, index=list("ABCD"))
+
+ # return location
+ res = df.iloc[lambda x: [1, 3]]
+ tm.assert_frame_equal(res, df.iloc[[1, 3]])
+
+ res = df.iloc[lambda x: [1, 3], :]
+ tm.assert_frame_equal(res, df.iloc[[1, 3], :])
+
+ res = df.iloc[lambda x: [1, 3], lambda x: 0]
+ tm.assert_series_equal(res, df.iloc[[1, 3], 0])
+
+ res = df.iloc[lambda x: [1, 3], lambda x: [0]]
+ tm.assert_frame_equal(res, df.iloc[[1, 3], [0]])
+
+ # mixture
+ res = df.iloc[[1, 3], lambda x: 0]
+ tm.assert_series_equal(res, df.iloc[[1, 3], 0])
+
+ res = df.iloc[[1, 3], lambda x: [0]]
+ tm.assert_frame_equal(res, df.iloc[[1, 3], [0]])
+
+ res = df.iloc[lambda x: [1, 3], 0]
+ tm.assert_series_equal(res, df.iloc[[1, 3], 0])
+
+ res = df.iloc[lambda x: [1, 3], [0]]
+ tm.assert_frame_equal(res, df.iloc[[1, 3], [0]])
+
+ def test_frame_iloc_setitem_callable(self):
+ # GH#11485
+ df = DataFrame({"X": [1, 2, 3, 4], "Y": list("aabb")}, index=list("ABCD"))
+
+ # return location
+ res = df.copy()
+ res.iloc[lambda x: [1, 3]] = 0
+ exp = df.copy()
+ exp.iloc[[1, 3]] = 0
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.iloc[lambda x: [1, 3], :] = -1
+ exp = df.copy()
+ exp.iloc[[1, 3], :] = -1
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.iloc[lambda x: [1, 3], lambda x: 0] = 5
+ exp = df.copy()
+ exp.iloc[[1, 3], 0] = 5
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.iloc[lambda x: [1, 3], lambda x: [0]] = 25
+ exp = df.copy()
+ exp.iloc[[1, 3], [0]] = 25
+ tm.assert_frame_equal(res, exp)
+
+ # mixture
+ res = df.copy()
+ res.iloc[[1, 3], lambda x: 0] = -3
+ exp = df.copy()
+ exp.iloc[[1, 3], 0] = -3
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.iloc[[1, 3], lambda x: [0]] = -5
+ exp = df.copy()
+ exp.iloc[[1, 3], [0]] = -5
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.iloc[lambda x: [1, 3], 0] = 10
+ exp = df.copy()
+ exp.iloc[[1, 3], 0] = 10
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.iloc[lambda x: [1, 3], [0]] = [-5, -5]
+ exp = df.copy()
+ exp.iloc[[1, 3], [0]] = [-5, -5]
+ tm.assert_frame_equal(res, exp)
+
+
+class TestILocSeries:
+ def test_iloc(self, using_copy_on_write):
+ ser = Series(
+ np.random.default_rng(2).standard_normal(10), index=list(range(0, 20, 2))
+ )
+ ser_original = ser.copy()
+
+ for i in range(len(ser)):
+ result = ser.iloc[i]
+ exp = ser[ser.index[i]]
+ tm.assert_almost_equal(result, exp)
+
+ # pass a slice
+ result = ser.iloc[slice(1, 3)]
+ expected = ser.loc[2:4]
+ tm.assert_series_equal(result, expected)
+
+ # test slice is a view
+ with tm.assert_produces_warning(None):
+ # GH#45324 make sure we aren't giving a spurious FutureWarning
+ result[:] = 0
+ if using_copy_on_write:
+ tm.assert_series_equal(ser, ser_original)
+ else:
+ assert (ser.iloc[1:3] == 0).all()
+
+ # list of integers
+ result = ser.iloc[[0, 2, 3, 4, 5]]
+ expected = ser.reindex(ser.index[[0, 2, 3, 4, 5]])
+ tm.assert_series_equal(result, expected)
+
+ def test_iloc_getitem_nonunique(self):
+ ser = Series([0, 1, 2], index=[0, 1, 0])
+ assert ser.iloc[2] == 2
+
+ def test_iloc_setitem_pure_position_based(self):
+ # GH#22046
+ ser1 = Series([1, 2, 3])
+ ser2 = Series([4, 5, 6], index=[1, 0, 2])
+ ser1.iloc[1:3] = ser2.iloc[1:3]
+ expected = Series([1, 5, 6])
+ tm.assert_series_equal(ser1, expected)
+
+ def test_iloc_nullable_int64_size_1_nan(self):
+ # GH 31861
+ result = DataFrame({"a": ["test"], "b": [np.nan]})
+ result.loc[:, "b"] = result.loc[:, "b"].astype("Int64")
+ expected = DataFrame({"a": ["test"], "b": array([NA], dtype="Int64")})
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_indexers.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_indexers.py
new file mode 100644
index 0000000000000000000000000000000000000000..ddc5c039160d5ada6c6dccb62514590a4ce9f620
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_indexers.py
@@ -0,0 +1,61 @@
+# Tests aimed at pandas.core.indexers
+import numpy as np
+import pytest
+
+from pandas.core.indexers import (
+ is_scalar_indexer,
+ length_of_indexer,
+ validate_indices,
+)
+
+
+def test_length_of_indexer():
+ arr = np.zeros(4, dtype=bool)
+ arr[0] = 1
+ result = length_of_indexer(arr)
+ assert result == 1
+
+
+def test_is_scalar_indexer():
+ indexer = (0, 1)
+ assert is_scalar_indexer(indexer, 2)
+ assert not is_scalar_indexer(indexer[0], 2)
+
+ indexer = (np.array([2]), 1)
+ assert not is_scalar_indexer(indexer, 2)
+
+ indexer = (np.array([2]), np.array([3]))
+ assert not is_scalar_indexer(indexer, 2)
+
+ indexer = (np.array([2]), np.array([3, 4]))
+ assert not is_scalar_indexer(indexer, 2)
+
+ assert not is_scalar_indexer(slice(None), 1)
+
+ indexer = 0
+ assert is_scalar_indexer(indexer, 1)
+
+ indexer = (0,)
+ assert is_scalar_indexer(indexer, 1)
+
+
+class TestValidateIndices:
+ def test_validate_indices_ok(self):
+ indices = np.asarray([0, 1])
+ validate_indices(indices, 2)
+ validate_indices(indices[:0], 0)
+ validate_indices(np.array([-1, -1]), 0)
+
+ def test_validate_indices_low(self):
+ indices = np.asarray([0, -2])
+ with pytest.raises(ValueError, match="'indices' contains"):
+ validate_indices(indices, 2)
+
+ def test_validate_indices_high(self):
+ indices = np.asarray([0, 1, 2])
+ with pytest.raises(IndexError, match="indices are out"):
+ validate_indices(indices, 2)
+
+ def test_validate_indices_empty(self):
+ with pytest.raises(IndexError, match="indices are out"):
+ validate_indices(np.array([0, 1]), 0)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_indexing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_indexing.py
new file mode 100644
index 0000000000000000000000000000000000000000..54e204c43dadd509059d9c2568ebb8d23621ebb2
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_indexing.py
@@ -0,0 +1,1142 @@
+""" test fancy indexing & misc """
+
+import array
+from datetime import datetime
+import re
+import weakref
+
+import numpy as np
+import pytest
+
+from pandas.errors import IndexingError
+
+from pandas.core.dtypes.common import (
+ is_float_dtype,
+ is_integer_dtype,
+ is_object_dtype,
+)
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ NaT,
+ Series,
+ date_range,
+ offsets,
+ timedelta_range,
+)
+import pandas._testing as tm
+from pandas.tests.indexing.common import _mklbl
+from pandas.tests.indexing.test_floats import gen_obj
+
+# ------------------------------------------------------------------------
+# Indexing test cases
+
+
+class TestFancy:
+ """pure get/set item & fancy indexing"""
+
+ def test_setitem_ndarray_1d(self):
+ # GH5508
+
+ # len of indexer vs length of the 1d ndarray
+ df = DataFrame(index=Index(np.arange(1, 11), dtype=np.int64))
+ df["foo"] = np.zeros(10, dtype=np.float64)
+ df["bar"] = np.zeros(10, dtype=complex)
+
+ # invalid
+ msg = "Must have equal len keys and value when setting with an iterable"
+ with pytest.raises(ValueError, match=msg):
+ df.loc[df.index[2:5], "bar"] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0])
+
+ # valid
+ df.loc[df.index[2:6], "bar"] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0])
+
+ result = df.loc[df.index[2:6], "bar"]
+ expected = Series(
+ [2.33j, 1.23 + 0.1j, 2.2, 1.0], index=[3, 4, 5, 6], name="bar"
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_setitem_ndarray_1d_2(self):
+ # GH5508
+
+ # dtype getting changed?
+ df = DataFrame(index=Index(np.arange(1, 11)))
+ df["foo"] = np.zeros(10, dtype=np.float64)
+ df["bar"] = np.zeros(10, dtype=complex)
+
+ msg = "Must have equal len keys and value when setting with an iterable"
+ with pytest.raises(ValueError, match=msg):
+ df[2:5] = np.arange(1, 4) * 1j
+
+ @pytest.mark.filterwarnings(
+ "ignore:Series.__getitem__ treating keys as positions is deprecated:"
+ "FutureWarning"
+ )
+ def test_getitem_ndarray_3d(
+ self, index, frame_or_series, indexer_sli, using_array_manager
+ ):
+ # GH 25567
+ obj = gen_obj(frame_or_series, index)
+ idxr = indexer_sli(obj)
+ nd3 = np.random.default_rng(2).integers(5, size=(2, 2, 2))
+
+ msgs = []
+ if frame_or_series is Series and indexer_sli in [tm.setitem, tm.iloc]:
+ msgs.append(r"Wrong number of dimensions. values.ndim > ndim \[3 > 1\]")
+ if using_array_manager:
+ msgs.append("Passed array should be 1-dimensional")
+ if frame_or_series is Series or indexer_sli is tm.iloc:
+ msgs.append(r"Buffer has wrong number of dimensions \(expected 1, got 3\)")
+ if using_array_manager:
+ msgs.append("indexer should be 1-dimensional")
+ if indexer_sli is tm.loc or (
+ frame_or_series is Series and indexer_sli is tm.setitem
+ ):
+ msgs.append("Cannot index with multidimensional key")
+ if frame_or_series is DataFrame and indexer_sli is tm.setitem:
+ msgs.append("Index data must be 1-dimensional")
+ if isinstance(index, pd.IntervalIndex) and indexer_sli is tm.iloc:
+ msgs.append("Index data must be 1-dimensional")
+ if isinstance(index, (pd.TimedeltaIndex, pd.DatetimeIndex, pd.PeriodIndex)):
+ msgs.append("Data must be 1-dimensional")
+ if len(index) == 0 or isinstance(index, pd.MultiIndex):
+ msgs.append("positional indexers are out-of-bounds")
+ if type(index) is Index and not isinstance(index._values, np.ndarray):
+ # e.g. Int64
+ msgs.append("values must be a 1D array")
+
+ # string[pyarrow]
+ msgs.append("only handle 1-dimensional arrays")
+
+ msg = "|".join(msgs)
+
+ potential_errors = (IndexError, ValueError, NotImplementedError)
+ with pytest.raises(potential_errors, match=msg):
+ idxr[nd3]
+
+ @pytest.mark.filterwarnings(
+ "ignore:Series.__setitem__ treating keys as positions is deprecated:"
+ "FutureWarning"
+ )
+ def test_setitem_ndarray_3d(self, index, frame_or_series, indexer_sli):
+ # GH 25567
+ obj = gen_obj(frame_or_series, index)
+ idxr = indexer_sli(obj)
+ nd3 = np.random.default_rng(2).integers(5, size=(2, 2, 2))
+
+ if indexer_sli is tm.iloc:
+ err = ValueError
+ msg = f"Cannot set values with ndim > {obj.ndim}"
+ else:
+ err = ValueError
+ msg = "|".join(
+ [
+ r"Buffer has wrong number of dimensions \(expected 1, got 3\)",
+ "Cannot set values with ndim > 1",
+ "Index data must be 1-dimensional",
+ "Data must be 1-dimensional",
+ "Array conditional must be same shape as self",
+ ]
+ )
+
+ with pytest.raises(err, match=msg):
+ idxr[nd3] = 0
+
+ def test_getitem_ndarray_0d(self):
+ # GH#24924
+ key = np.array(0)
+
+ # dataframe __getitem__
+ df = DataFrame([[1, 2], [3, 4]])
+ result = df[key]
+ expected = Series([1, 3], name=0)
+ tm.assert_series_equal(result, expected)
+
+ # series __getitem__
+ ser = Series([1, 2])
+ result = ser[key]
+ assert result == 1
+
+ def test_inf_upcast(self):
+ # GH 16957
+ # We should be able to use np.inf as a key
+ # np.inf should cause an index to convert to float
+
+ # Test with np.inf in rows
+ df = DataFrame(columns=[0])
+ df.loc[1] = 1
+ df.loc[2] = 2
+ df.loc[np.inf] = 3
+
+ # make sure we can look up the value
+ assert df.loc[np.inf, 0] == 3
+
+ result = df.index
+ expected = Index([1, 2, np.inf], dtype=np.float64)
+ tm.assert_index_equal(result, expected)
+
+ def test_setitem_dtype_upcast(self):
+ # GH3216
+ df = DataFrame([{"a": 1}, {"a": 3, "b": 2}])
+ df["c"] = np.nan
+ assert df["c"].dtype == np.float64
+
+ with tm.assert_produces_warning(
+ FutureWarning, match="item of incompatible dtype"
+ ):
+ df.loc[0, "c"] = "foo"
+ expected = DataFrame(
+ [{"a": 1, "b": np.nan, "c": "foo"}, {"a": 3, "b": 2, "c": np.nan}]
+ )
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("val", [3.14, "wxyz"])
+ def test_setitem_dtype_upcast2(self, val):
+ # GH10280
+ df = DataFrame(
+ np.arange(6, dtype="int64").reshape(2, 3),
+ index=list("ab"),
+ columns=["foo", "bar", "baz"],
+ )
+
+ left = df.copy()
+ with tm.assert_produces_warning(
+ FutureWarning, match="item of incompatible dtype"
+ ):
+ left.loc["a", "bar"] = val
+ right = DataFrame(
+ [[0, val, 2], [3, 4, 5]],
+ index=list("ab"),
+ columns=["foo", "bar", "baz"],
+ )
+
+ tm.assert_frame_equal(left, right)
+ assert is_integer_dtype(left["foo"])
+ assert is_integer_dtype(left["baz"])
+
+ def test_setitem_dtype_upcast3(self):
+ left = DataFrame(
+ np.arange(6, dtype="int64").reshape(2, 3) / 10.0,
+ index=list("ab"),
+ columns=["foo", "bar", "baz"],
+ )
+ with tm.assert_produces_warning(
+ FutureWarning, match="item of incompatible dtype"
+ ):
+ left.loc["a", "bar"] = "wxyz"
+
+ right = DataFrame(
+ [[0, "wxyz", 0.2], [0.3, 0.4, 0.5]],
+ index=list("ab"),
+ columns=["foo", "bar", "baz"],
+ )
+
+ tm.assert_frame_equal(left, right)
+ assert is_float_dtype(left["foo"])
+ assert is_float_dtype(left["baz"])
+
+ def test_dups_fancy_indexing(self):
+ # GH 3455
+
+ df = tm.makeCustomDataframe(10, 3)
+ df.columns = ["a", "a", "b"]
+ result = df[["b", "a"]].columns
+ expected = Index(["b", "a", "a"])
+ tm.assert_index_equal(result, expected)
+
+ def test_dups_fancy_indexing_across_dtypes(self):
+ # across dtypes
+ df = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("aaaaaaa"))
+ df.head()
+ str(df)
+ result = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]])
+ result.columns = list("aaaaaaa") # GH#3468
+
+ # GH#3509 smoke tests for indexing with duplicate columns
+ df.iloc[:, 4]
+ result.iloc[:, 4]
+
+ tm.assert_frame_equal(df, result)
+
+ def test_dups_fancy_indexing_not_in_order(self):
+ # GH 3561, dups not in selected order
+ df = DataFrame(
+ {"test": [5, 7, 9, 11], "test1": [4.0, 5, 6, 7], "other": list("abcd")},
+ index=["A", "A", "B", "C"],
+ )
+ rows = ["C", "B"]
+ expected = DataFrame(
+ {"test": [11, 9], "test1": [7.0, 6], "other": ["d", "c"]}, index=rows
+ )
+ result = df.loc[rows]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.loc[Index(rows)]
+ tm.assert_frame_equal(result, expected)
+
+ rows = ["C", "B", "E"]
+ with pytest.raises(KeyError, match="not in index"):
+ df.loc[rows]
+
+ # see GH5553, make sure we use the right indexer
+ rows = ["F", "G", "H", "C", "B", "E"]
+ with pytest.raises(KeyError, match="not in index"):
+ df.loc[rows]
+
+ def test_dups_fancy_indexing_only_missing_label(self):
+ # List containing only missing label
+ dfnu = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)), index=list("AABCD")
+ )
+ with pytest.raises(
+ KeyError,
+ match=re.escape(
+ "\"None of [Index(['E'], dtype='object')] are in the [index]\""
+ ),
+ ):
+ dfnu.loc[["E"]]
+
+ @pytest.mark.parametrize("vals", [[0, 1, 2], list("abc")])
+ def test_dups_fancy_indexing_missing_label(self, vals):
+ # GH 4619; duplicate indexer with missing label
+ df = DataFrame({"A": vals})
+ with pytest.raises(KeyError, match="not in index"):
+ df.loc[[0, 8, 0]]
+
+ def test_dups_fancy_indexing_non_unique(self):
+ # non unique with non unique selector
+ df = DataFrame({"test": [5, 7, 9, 11]}, index=["A", "A", "B", "C"])
+ with pytest.raises(KeyError, match="not in index"):
+ df.loc[["A", "A", "E"]]
+
+ def test_dups_fancy_indexing2(self):
+ # GH 5835
+ # dups on index and missing values
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 5)),
+ columns=["A", "B", "B", "B", "A"],
+ )
+
+ with pytest.raises(KeyError, match="not in index"):
+ df.loc[:, ["A", "B", "C"]]
+
+ def test_dups_fancy_indexing3(self):
+ # GH 6504, multi-axis indexing
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((9, 2)),
+ index=[1, 1, 1, 2, 2, 2, 3, 3, 3],
+ columns=["a", "b"],
+ )
+
+ expected = df.iloc[0:6]
+ result = df.loc[[1, 2]]
+ tm.assert_frame_equal(result, expected)
+
+ expected = df
+ result = df.loc[:, ["a", "b"]]
+ tm.assert_frame_equal(result, expected)
+
+ expected = df.iloc[0:6, :]
+ result = df.loc[[1, 2], ["a", "b"]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_duplicate_int_indexing(self, indexer_sl):
+ # GH 17347
+ ser = Series(range(3), index=[1, 1, 3])
+ expected = Series(range(2), index=[1, 1])
+ result = indexer_sl(ser)[[1]]
+ tm.assert_series_equal(result, expected)
+
+ def test_indexing_mixed_frame_bug(self):
+ # GH3492
+ df = DataFrame(
+ {"a": {1: "aaa", 2: "bbb", 3: "ccc"}, "b": {1: 111, 2: 222, 3: 333}}
+ )
+
+ # this works, new column is created correctly
+ df["test"] = df["a"].apply(lambda x: "_" if x == "aaa" else x)
+
+ # this does not work, ie column test is not changed
+ idx = df["test"] == "_"
+ temp = df.loc[idx, "a"].apply(lambda x: "-----" if x == "aaa" else x)
+ df.loc[idx, "test"] = temp
+ assert df.iloc[0, 2] == "-----"
+
+ def test_multitype_list_index_access(self):
+ # GH 10610
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 5)), columns=["a"] + [20, 21, 22, 23]
+ )
+
+ with pytest.raises(KeyError, match=re.escape("'[26, -8] not in index'")):
+ df[[22, 26, -8]]
+ assert df[21].shape[0] == df.shape[0]
+
+ def test_set_index_nan(self):
+ # GH 3586
+ df = DataFrame(
+ {
+ "PRuid": {
+ 17: "nonQC",
+ 18: "nonQC",
+ 19: "nonQC",
+ 20: "10",
+ 21: "11",
+ 22: "12",
+ 23: "13",
+ 24: "24",
+ 25: "35",
+ 26: "46",
+ 27: "47",
+ 28: "48",
+ 29: "59",
+ 30: "10",
+ },
+ "QC": {
+ 17: 0.0,
+ 18: 0.0,
+ 19: 0.0,
+ 20: np.nan,
+ 21: np.nan,
+ 22: np.nan,
+ 23: np.nan,
+ 24: 1.0,
+ 25: np.nan,
+ 26: np.nan,
+ 27: np.nan,
+ 28: np.nan,
+ 29: np.nan,
+ 30: np.nan,
+ },
+ "data": {
+ 17: 7.9544899999999998,
+ 18: 8.0142609999999994,
+ 19: 7.8591520000000008,
+ 20: 0.86140349999999999,
+ 21: 0.87853110000000001,
+ 22: 0.8427041999999999,
+ 23: 0.78587700000000005,
+ 24: 0.73062459999999996,
+ 25: 0.81668560000000001,
+ 26: 0.81927080000000008,
+ 27: 0.80705009999999999,
+ 28: 0.81440240000000008,
+ 29: 0.80140849999999997,
+ 30: 0.81307740000000006,
+ },
+ "year": {
+ 17: 2006,
+ 18: 2007,
+ 19: 2008,
+ 20: 1985,
+ 21: 1985,
+ 22: 1985,
+ 23: 1985,
+ 24: 1985,
+ 25: 1985,
+ 26: 1985,
+ 27: 1985,
+ 28: 1985,
+ 29: 1985,
+ 30: 1986,
+ },
+ }
+ ).reset_index()
+
+ result = (
+ df.set_index(["year", "PRuid", "QC"])
+ .reset_index()
+ .reindex(columns=df.columns)
+ )
+ tm.assert_frame_equal(result, df)
+
+ def test_multi_assign(self):
+ # GH 3626, an assignment of a sub-df to a df
+ # set float64 to avoid upcast when setting nan
+ df = DataFrame(
+ {
+ "FC": ["a", "b", "a", "b", "a", "b"],
+ "PF": [0, 0, 0, 0, 1, 1],
+ "col1": list(range(6)),
+ "col2": list(range(6, 12)),
+ }
+ ).astype({"col2": "float64"})
+ df.iloc[1, 0] = np.nan
+ df2 = df.copy()
+
+ mask = ~df2.FC.isna()
+ cols = ["col1", "col2"]
+
+ dft = df2 * 2
+ dft.iloc[3, 3] = np.nan
+
+ expected = DataFrame(
+ {
+ "FC": ["a", np.nan, "a", "b", "a", "b"],
+ "PF": [0, 0, 0, 0, 1, 1],
+ "col1": Series([0, 1, 4, 6, 8, 10]),
+ "col2": [12, 7, 16, np.nan, 20, 22],
+ }
+ )
+
+ # frame on rhs
+ df2.loc[mask, cols] = dft.loc[mask, cols]
+ tm.assert_frame_equal(df2, expected)
+
+ # with an ndarray on rhs
+ # coerces to float64 because values has float64 dtype
+ # GH 14001
+ expected = DataFrame(
+ {
+ "FC": ["a", np.nan, "a", "b", "a", "b"],
+ "PF": [0, 0, 0, 0, 1, 1],
+ "col1": [0, 1, 4, 6, 8, 10],
+ "col2": [12, 7, 16, np.nan, 20, 22],
+ }
+ )
+ df2 = df.copy()
+ df2.loc[mask, cols] = dft.loc[mask, cols].values
+ tm.assert_frame_equal(df2, expected)
+
+ def test_multi_assign_broadcasting_rhs(self):
+ # broadcasting on the rhs is required
+ df = DataFrame(
+ {
+ "A": [1, 2, 0, 0, 0],
+ "B": [0, 0, 0, 10, 11],
+ "C": [0, 0, 0, 10, 11],
+ "D": [3, 4, 5, 6, 7],
+ }
+ )
+
+ expected = df.copy()
+ mask = expected["A"] == 0
+ for col in ["A", "B"]:
+ expected.loc[mask, col] = df["D"]
+
+ df.loc[df["A"] == 0, ["A", "B"]] = df["D"]
+ tm.assert_frame_equal(df, expected)
+
+ def test_setitem_list(self):
+ # GH 6043
+ # iloc with a list
+ df = DataFrame(index=[0, 1], columns=[0])
+ df.iloc[1, 0] = [1, 2, 3]
+ df.iloc[1, 0] = [1, 2]
+
+ result = DataFrame(index=[0, 1], columns=[0])
+ result.iloc[1, 0] = [1, 2]
+
+ tm.assert_frame_equal(result, df)
+
+ def test_string_slice(self):
+ # GH 14424
+ # string indexing against datetimelike with object
+ # dtype should properly raises KeyError
+ df = DataFrame([1], Index([pd.Timestamp("2011-01-01")], dtype=object))
+ assert df.index._is_all_dates
+ with pytest.raises(KeyError, match="'2011'"):
+ df["2011"]
+
+ with pytest.raises(KeyError, match="'2011'"):
+ df.loc["2011", 0]
+
+ def test_string_slice_empty(self):
+ # GH 14424
+
+ df = DataFrame()
+ assert not df.index._is_all_dates
+ with pytest.raises(KeyError, match="'2011'"):
+ df["2011"]
+
+ with pytest.raises(KeyError, match="^0$"):
+ df.loc["2011", 0]
+
+ def test_astype_assignment(self):
+ # GH4312 (iloc)
+ df_orig = DataFrame(
+ [["1", "2", "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
+ )
+
+ df = df_orig.copy()
+
+ # with the enforcement of GH#45333 in 2.0, this setting is attempted inplace,
+ # so object dtype is retained
+ df.iloc[:, 0:2] = df.iloc[:, 0:2].astype(np.int64)
+ expected = DataFrame(
+ [[1, 2, "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
+ )
+ expected["A"] = expected["A"].astype(object)
+ expected["B"] = expected["B"].astype(object)
+ tm.assert_frame_equal(df, expected)
+
+ # GH5702 (loc)
+ df = df_orig.copy()
+ df.loc[:, "A"] = df.loc[:, "A"].astype(np.int64)
+ expected = DataFrame(
+ [[1, "2", "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
+ )
+ expected["A"] = expected["A"].astype(object)
+ tm.assert_frame_equal(df, expected)
+
+ df = df_orig.copy()
+ df.loc[:, ["B", "C"]] = df.loc[:, ["B", "C"]].astype(np.int64)
+ expected = DataFrame(
+ [["1", 2, 3, ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
+ )
+ expected["B"] = expected["B"].astype(object)
+ expected["C"] = expected["C"].astype(object)
+ tm.assert_frame_equal(df, expected)
+
+ def test_astype_assignment_full_replacements(self):
+ # full replacements / no nans
+ df = DataFrame({"A": [1.0, 2.0, 3.0, 4.0]})
+
+ # With the enforcement of GH#45333 in 2.0, this assignment occurs inplace,
+ # so float64 is retained
+ df.iloc[:, 0] = df["A"].astype(np.int64)
+ expected = DataFrame({"A": [1.0, 2.0, 3.0, 4.0]})
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame({"A": [1.0, 2.0, 3.0, 4.0]})
+ df.loc[:, "A"] = df["A"].astype(np.int64)
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("indexer", [tm.getitem, tm.loc])
+ def test_index_type_coercion(self, indexer):
+ # GH 11836
+ # if we have an index type and set it with something that looks
+ # to numpy like the same, but is actually, not
+ # (e.g. setting with a float or string '0')
+ # then we need to coerce to object
+
+ # integer indexes
+ for s in [Series(range(5)), Series(range(5), index=range(1, 6))]:
+ assert is_integer_dtype(s.index)
+
+ s2 = s.copy()
+ indexer(s2)[0.1] = 0
+ assert is_float_dtype(s2.index)
+ assert indexer(s2)[0.1] == 0
+
+ s2 = s.copy()
+ indexer(s2)[0.0] = 0
+ exp = s.index
+ if 0 not in s:
+ exp = Index(s.index.tolist() + [0])
+ tm.assert_index_equal(s2.index, exp)
+
+ s2 = s.copy()
+ indexer(s2)["0"] = 0
+ assert is_object_dtype(s2.index)
+
+ for s in [Series(range(5), index=np.arange(5.0))]:
+ assert is_float_dtype(s.index)
+
+ s2 = s.copy()
+ indexer(s2)[0.1] = 0
+ assert is_float_dtype(s2.index)
+ assert indexer(s2)[0.1] == 0
+
+ s2 = s.copy()
+ indexer(s2)[0.0] = 0
+ tm.assert_index_equal(s2.index, s.index)
+
+ s2 = s.copy()
+ indexer(s2)["0"] = 0
+ assert is_object_dtype(s2.index)
+
+
+class TestMisc:
+ def test_float_index_to_mixed(self):
+ df = DataFrame(
+ {
+ 0.0: np.random.default_rng(2).random(10),
+ 1.0: np.random.default_rng(2).random(10),
+ }
+ )
+ df["a"] = 10
+
+ expected = DataFrame({0.0: df[0.0], 1.0: df[1.0], "a": [10] * 10})
+ tm.assert_frame_equal(expected, df)
+
+ def test_float_index_non_scalar_assignment(self):
+ df = DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}, index=[1.0, 2.0, 3.0])
+ df.loc[df.index[:2]] = 1
+ expected = DataFrame({"a": [1, 1, 3], "b": [1, 1, 5]}, index=df.index)
+ tm.assert_frame_equal(expected, df)
+
+ def test_loc_setitem_fullindex_views(self):
+ df = DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}, index=[1.0, 2.0, 3.0])
+ df2 = df.copy()
+ df.loc[df.index] = df.loc[df.index]
+ tm.assert_frame_equal(df, df2)
+
+ def test_rhs_alignment(self):
+ # GH8258, tests that both rows & columns are aligned to what is
+ # assigned to. covers both uniform data-type & multi-type cases
+ def run_tests(df, rhs, right_loc, right_iloc):
+ # label, index, slice
+ lbl_one, idx_one, slice_one = list("bcd"), [1, 2, 3], slice(1, 4)
+ lbl_two, idx_two, slice_two = ["joe", "jolie"], [1, 2], slice(1, 3)
+
+ left = df.copy()
+ left.loc[lbl_one, lbl_two] = rhs
+ tm.assert_frame_equal(left, right_loc)
+
+ left = df.copy()
+ left.iloc[idx_one, idx_two] = rhs
+ tm.assert_frame_equal(left, right_iloc)
+
+ left = df.copy()
+ left.iloc[slice_one, slice_two] = rhs
+ tm.assert_frame_equal(left, right_iloc)
+
+ xs = np.arange(20).reshape(5, 4)
+ cols = ["jim", "joe", "jolie", "joline"]
+ df = DataFrame(xs, columns=cols, index=list("abcde"), dtype="int64")
+
+ # right hand side; permute the indices and multiplpy by -2
+ rhs = -2 * df.iloc[3:0:-1, 2:0:-1]
+
+ # expected `right` result; just multiply by -2
+ right_iloc = df.copy()
+ right_iloc["joe"] = [1, 14, 10, 6, 17]
+ right_iloc["jolie"] = [2, 13, 9, 5, 18]
+ right_iloc.iloc[1:4, 1:3] *= -2
+ right_loc = df.copy()
+ right_loc.iloc[1:4, 1:3] *= -2
+
+ # run tests with uniform dtypes
+ run_tests(df, rhs, right_loc, right_iloc)
+
+ # make frames multi-type & re-run tests
+ for frame in [df, rhs, right_loc, right_iloc]:
+ frame["joe"] = frame["joe"].astype("float64")
+ frame["jolie"] = frame["jolie"].map(lambda x: f"@{x}")
+ right_iloc["joe"] = [1.0, "@-28", "@-20", "@-12", 17.0]
+ right_iloc["jolie"] = ["@2", -26.0, -18.0, -10.0, "@18"]
+ with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
+ run_tests(df, rhs, right_loc, right_iloc)
+
+ @pytest.mark.parametrize(
+ "idx", [_mklbl("A", 20), np.arange(20) + 100, np.linspace(100, 150, 20)]
+ )
+ def test_str_label_slicing_with_negative_step(self, idx):
+ SLC = pd.IndexSlice
+
+ idx = Index(idx)
+ ser = Series(np.arange(20), index=idx)
+ tm.assert_indexing_slices_equivalent(ser, SLC[idx[9] :: -1], SLC[9::-1])
+ tm.assert_indexing_slices_equivalent(ser, SLC[: idx[9] : -1], SLC[:8:-1])
+ tm.assert_indexing_slices_equivalent(
+ ser, SLC[idx[13] : idx[9] : -1], SLC[13:8:-1]
+ )
+ tm.assert_indexing_slices_equivalent(ser, SLC[idx[9] : idx[13] : -1], SLC[:0])
+
+ def test_slice_with_zero_step_raises(self, index, indexer_sl, frame_or_series):
+ obj = frame_or_series(np.arange(len(index)), index=index)
+ with pytest.raises(ValueError, match="slice step cannot be zero"):
+ indexer_sl(obj)[::0]
+
+ def test_loc_setitem_indexing_assignment_dict_already_exists(self):
+ index = Index([-5, 0, 5], name="z")
+ df = DataFrame({"x": [1, 2, 6], "y": [2, 2, 8]}, index=index)
+ expected = df.copy()
+ rhs = {"x": 9, "y": 99}
+ df.loc[5] = rhs
+ expected.loc[5] = [9, 99]
+ tm.assert_frame_equal(df, expected)
+
+ # GH#38335 same thing, mixed dtypes
+ df = DataFrame({"x": [1, 2, 6], "y": [2.0, 2.0, 8.0]}, index=index)
+ df.loc[5] = rhs
+ expected = DataFrame({"x": [1, 2, 9], "y": [2.0, 2.0, 99.0]}, index=index)
+ tm.assert_frame_equal(df, expected)
+
+ def test_iloc_getitem_indexing_dtypes_on_empty(self):
+ # Check that .iloc returns correct dtypes GH9983
+ df = DataFrame({"a": [1, 2, 3], "b": ["b", "b2", "b3"]})
+ df2 = df.iloc[[], :]
+
+ assert df2.loc[:, "a"].dtype == np.int64
+ tm.assert_series_equal(df2.loc[:, "a"], df2.iloc[:, 0])
+
+ @pytest.mark.parametrize("size", [5, 999999, 1000000])
+ def test_loc_range_in_series_indexing(self, size):
+ # range can cause an indexing error
+ # GH 11652
+ s = Series(index=range(size), dtype=np.float64)
+ s.loc[range(1)] = 42
+ tm.assert_series_equal(s.loc[range(1)], Series(42.0, index=[0]))
+
+ s.loc[range(2)] = 43
+ tm.assert_series_equal(s.loc[range(2)], Series(43.0, index=[0, 1]))
+
+ def test_partial_boolean_frame_indexing(self):
+ # GH 17170
+ df = DataFrame(
+ np.arange(9.0).reshape(3, 3), index=list("abc"), columns=list("ABC")
+ )
+ index_df = DataFrame(1, index=list("ab"), columns=list("AB"))
+ result = df[index_df.notnull()]
+ expected = DataFrame(
+ np.array([[0.0, 1.0, np.nan], [3.0, 4.0, np.nan], [np.nan] * 3]),
+ index=list("abc"),
+ columns=list("ABC"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_no_reference_cycle(self):
+ df = DataFrame({"a": [0, 1], "b": [2, 3]})
+ for name in ("loc", "iloc", "at", "iat"):
+ getattr(df, name)
+ wr = weakref.ref(df)
+ del df
+ assert wr() is None
+
+ def test_label_indexing_on_nan(self, nulls_fixture):
+ # GH 32431
+ df = Series([1, "{1,2}", 1, nulls_fixture])
+ vc = df.value_counts(dropna=False)
+ result1 = vc.loc[nulls_fixture]
+ result2 = vc[nulls_fixture]
+
+ expected = 1
+ assert result1 == expected
+ assert result2 == expected
+
+
+class TestDataframeNoneCoercion:
+ EXPECTED_SINGLE_ROW_RESULTS = [
+ # For numeric series, we should coerce to NaN.
+ ([1, 2, 3], [np.nan, 2, 3], FutureWarning),
+ ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0], None),
+ # For datetime series, we should coerce to NaT.
+ (
+ [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
+ [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)],
+ None,
+ ),
+ # For objects, we should preserve the None value.
+ (["foo", "bar", "baz"], [None, "bar", "baz"], None),
+ ]
+
+ @pytest.mark.parametrize("expected", EXPECTED_SINGLE_ROW_RESULTS)
+ def test_coercion_with_loc(self, expected):
+ start_data, expected_result, warn = expected
+
+ start_dataframe = DataFrame({"foo": start_data})
+ start_dataframe.loc[0, ["foo"]] = None
+
+ expected_dataframe = DataFrame({"foo": expected_result})
+ tm.assert_frame_equal(start_dataframe, expected_dataframe)
+
+ @pytest.mark.parametrize("expected", EXPECTED_SINGLE_ROW_RESULTS)
+ def test_coercion_with_setitem_and_dataframe(self, expected):
+ start_data, expected_result, warn = expected
+
+ start_dataframe = DataFrame({"foo": start_data})
+ start_dataframe[start_dataframe["foo"] == start_dataframe["foo"][0]] = None
+
+ expected_dataframe = DataFrame({"foo": expected_result})
+ tm.assert_frame_equal(start_dataframe, expected_dataframe)
+
+ @pytest.mark.parametrize("expected", EXPECTED_SINGLE_ROW_RESULTS)
+ def test_none_coercion_loc_and_dataframe(self, expected):
+ start_data, expected_result, warn = expected
+
+ start_dataframe = DataFrame({"foo": start_data})
+ start_dataframe.loc[start_dataframe["foo"] == start_dataframe["foo"][0]] = None
+
+ expected_dataframe = DataFrame({"foo": expected_result})
+ tm.assert_frame_equal(start_dataframe, expected_dataframe)
+
+ def test_none_coercion_mixed_dtypes(self):
+ start_dataframe = DataFrame(
+ {
+ "a": [1, 2, 3],
+ "b": [1.0, 2.0, 3.0],
+ "c": [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
+ "d": ["a", "b", "c"],
+ }
+ )
+ start_dataframe.iloc[0] = None
+
+ exp = DataFrame(
+ {
+ "a": [np.nan, 2, 3],
+ "b": [np.nan, 2.0, 3.0],
+ "c": [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)],
+ "d": [None, "b", "c"],
+ }
+ )
+ tm.assert_frame_equal(start_dataframe, exp)
+
+
+class TestDatetimelikeCoercion:
+ def test_setitem_dt64_string_scalar(self, tz_naive_fixture, indexer_sli):
+ # dispatching _can_hold_element to underlying DatetimeArray
+ tz = tz_naive_fixture
+
+ dti = date_range("2016-01-01", periods=3, tz=tz)
+ ser = Series(dti.copy(deep=True))
+
+ values = ser._values
+
+ newval = "2018-01-01"
+ values._validate_setitem_value(newval)
+
+ indexer_sli(ser)[0] = newval
+
+ if tz is None:
+ # TODO(EA2D): we can make this no-copy in tz-naive case too
+ assert ser.dtype == dti.dtype
+ assert ser._values._ndarray is values._ndarray
+ else:
+ assert ser._values is values
+
+ @pytest.mark.parametrize("box", [list, np.array, pd.array, pd.Categorical, Index])
+ @pytest.mark.parametrize(
+ "key", [[0, 1], slice(0, 2), np.array([True, True, False])]
+ )
+ def test_setitem_dt64_string_values(self, tz_naive_fixture, indexer_sli, key, box):
+ # dispatching _can_hold_element to underling DatetimeArray
+ tz = tz_naive_fixture
+
+ if isinstance(key, slice) and indexer_sli is tm.loc:
+ key = slice(0, 1)
+
+ dti = date_range("2016-01-01", periods=3, tz=tz)
+ ser = Series(dti.copy(deep=True))
+
+ values = ser._values
+
+ newvals = box(["2019-01-01", "2010-01-02"])
+ values._validate_setitem_value(newvals)
+
+ indexer_sli(ser)[key] = newvals
+
+ if tz is None:
+ # TODO(EA2D): we can make this no-copy in tz-naive case too
+ assert ser.dtype == dti.dtype
+ assert ser._values._ndarray is values._ndarray
+ else:
+ assert ser._values is values
+
+ @pytest.mark.parametrize("scalar", ["3 Days", offsets.Hour(4)])
+ def test_setitem_td64_scalar(self, indexer_sli, scalar):
+ # dispatching _can_hold_element to underling TimedeltaArray
+ tdi = timedelta_range("1 Day", periods=3)
+ ser = Series(tdi.copy(deep=True))
+
+ values = ser._values
+ values._validate_setitem_value(scalar)
+
+ indexer_sli(ser)[0] = scalar
+ assert ser._values._ndarray is values._ndarray
+
+ @pytest.mark.parametrize("box", [list, np.array, pd.array, pd.Categorical, Index])
+ @pytest.mark.parametrize(
+ "key", [[0, 1], slice(0, 2), np.array([True, True, False])]
+ )
+ def test_setitem_td64_string_values(self, indexer_sli, key, box):
+ # dispatching _can_hold_element to underling TimedeltaArray
+ if isinstance(key, slice) and indexer_sli is tm.loc:
+ key = slice(0, 1)
+
+ tdi = timedelta_range("1 Day", periods=3)
+ ser = Series(tdi.copy(deep=True))
+
+ values = ser._values
+
+ newvals = box(["10 Days", "44 hours"])
+ values._validate_setitem_value(newvals)
+
+ indexer_sli(ser)[key] = newvals
+ assert ser._values._ndarray is values._ndarray
+
+
+def test_extension_array_cross_section():
+ # A cross-section of a homogeneous EA should be an EA
+ df = DataFrame(
+ {
+ "A": pd.array([1, 2], dtype="Int64"),
+ "B": pd.array([3, 4], dtype="Int64"),
+ },
+ index=["a", "b"],
+ )
+ expected = Series(pd.array([1, 3], dtype="Int64"), index=["A", "B"], name="a")
+ result = df.loc["a"]
+ tm.assert_series_equal(result, expected)
+
+ result = df.iloc[0]
+ tm.assert_series_equal(result, expected)
+
+
+def test_extension_array_cross_section_converts():
+ # all numeric columns -> numeric series
+ df = DataFrame(
+ {
+ "A": pd.array([1, 2], dtype="Int64"),
+ "B": np.array([1, 2], dtype="int64"),
+ },
+ index=["a", "b"],
+ )
+ result = df.loc["a"]
+ expected = Series([1, 1], dtype="Int64", index=["A", "B"], name="a")
+ tm.assert_series_equal(result, expected)
+
+ result = df.iloc[0]
+ tm.assert_series_equal(result, expected)
+
+ # mixed columns -> object series
+ df = DataFrame(
+ {"A": pd.array([1, 2], dtype="Int64"), "B": np.array(["a", "b"])},
+ index=["a", "b"],
+ )
+ result = df.loc["a"]
+ expected = Series([1, "a"], dtype=object, index=["A", "B"], name="a")
+ tm.assert_series_equal(result, expected)
+
+ result = df.iloc[0]
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ser, keys",
+ [(Series([10]), (0, 0)), (Series([1, 2, 3], index=list("abc")), (0, 1))],
+)
+def test_ser_tup_indexer_exceeds_dimensions(ser, keys, indexer_li):
+ # GH#13831
+ exp_err, exp_msg = IndexingError, "Too many indexers"
+ with pytest.raises(exp_err, match=exp_msg):
+ indexer_li(ser)[keys]
+
+ if indexer_li == tm.iloc:
+ # For iloc.__setitem__ we let numpy handle the error reporting.
+ exp_err, exp_msg = IndexError, "too many indices for array"
+
+ with pytest.raises(exp_err, match=exp_msg):
+ indexer_li(ser)[keys] = 0
+
+
+def test_ser_list_indexer_exceeds_dimensions(indexer_li):
+ # GH#13831
+ # Make sure an exception is raised when a tuple exceeds the dimension of the series,
+ # but not list when a list is used.
+ ser = Series([10])
+ res = indexer_li(ser)[[0, 0]]
+ exp = Series([10, 10], index=Index([0, 0]))
+ tm.assert_series_equal(res, exp)
+
+
+@pytest.mark.parametrize(
+ "value", [(0, 1), [0, 1], np.array([0, 1]), array.array("b", [0, 1])]
+)
+def test_scalar_setitem_with_nested_value(value):
+ # For numeric data, we try to unpack and thus raise for mismatching length
+ df = DataFrame({"A": [1, 2, 3]})
+ msg = "|".join(
+ [
+ "Must have equal len keys and value",
+ "setting an array element with a sequence",
+ ]
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.loc[0, "B"] = value
+
+ # TODO For object dtype this happens as well, but should we rather preserve
+ # the nested data and set as such?
+ df = DataFrame({"A": [1, 2, 3], "B": np.array([1, "a", "b"], dtype=object)})
+ with pytest.raises(ValueError, match="Must have equal len keys and value"):
+ df.loc[0, "B"] = value
+ # if isinstance(value, np.ndarray):
+ # assert (df.loc[0, "B"] == value).all()
+ # else:
+ # assert df.loc[0, "B"] == value
+
+
+@pytest.mark.parametrize(
+ "value", [(0, 1), [0, 1], np.array([0, 1]), array.array("b", [0, 1])]
+)
+def test_scalar_setitem_series_with_nested_value(value, indexer_sli):
+ # For numeric data, we try to unpack and thus raise for mismatching length
+ ser = Series([1, 2, 3])
+ with pytest.raises(ValueError, match="setting an array element with a sequence"):
+ indexer_sli(ser)[0] = value
+
+ # but for object dtype we preserve the nested data and set as such
+ ser = Series([1, "a", "b"], dtype=object)
+ indexer_sli(ser)[0] = value
+ if isinstance(value, np.ndarray):
+ assert (ser.loc[0] == value).all()
+ else:
+ assert ser.loc[0] == value
+
+
+@pytest.mark.parametrize(
+ "value", [(0.0,), [0.0], np.array([0.0]), array.array("d", [0.0])]
+)
+def test_scalar_setitem_with_nested_value_length1(value):
+ # https://github.com/pandas-dev/pandas/issues/46268
+
+ # For numeric data, assigning length-1 array to scalar position gets unpacked
+ df = DataFrame({"A": [1, 2, 3]})
+ df.loc[0, "B"] = value
+ expected = DataFrame({"A": [1, 2, 3], "B": [0.0, np.nan, np.nan]})
+ tm.assert_frame_equal(df, expected)
+
+ # but for object dtype we preserve the nested data
+ df = DataFrame({"A": [1, 2, 3], "B": np.array([1, "a", "b"], dtype=object)})
+ df.loc[0, "B"] = value
+ if isinstance(value, np.ndarray):
+ assert (df.loc[0, "B"] == value).all()
+ else:
+ assert df.loc[0, "B"] == value
+
+
+@pytest.mark.parametrize(
+ "value", [(0.0,), [0.0], np.array([0.0]), array.array("d", [0.0])]
+)
+def test_scalar_setitem_series_with_nested_value_length1(value, indexer_sli):
+ # For numeric data, assigning length-1 array to scalar position gets unpacked
+ # TODO this only happens in case of ndarray, should we make this consistent
+ # for all list-likes? (as happens for DataFrame.(i)loc, see test above)
+ ser = Series([1.0, 2.0, 3.0])
+ if isinstance(value, np.ndarray):
+ indexer_sli(ser)[0] = value
+ expected = Series([0.0, 2.0, 3.0])
+ tm.assert_series_equal(ser, expected)
+ else:
+ with pytest.raises(
+ ValueError, match="setting an array element with a sequence"
+ ):
+ indexer_sli(ser)[0] = value
+
+ # but for object dtype we preserve the nested data
+ ser = Series([1, "a", "b"], dtype=object)
+ indexer_sli(ser)[0] = value
+ if isinstance(value, np.ndarray):
+ assert (ser.loc[0] == value).all()
+ else:
+ assert ser.loc[0] == value
+
+
+def test_object_dtype_series_set_series_element():
+ # GH 48933
+ s1 = Series(dtype="O", index=["a", "b"])
+
+ s1["a"] = Series()
+ s1.loc["b"] = Series()
+
+ tm.assert_series_equal(s1.loc["a"], Series())
+ tm.assert_series_equal(s1.loc["b"], Series())
+
+ s2 = Series(dtype="O", index=["a", "b"])
+
+ s2.iloc[1] = Series()
+ tm.assert_series_equal(s2.iloc[1], Series())
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_loc.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_loc.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b2730b3ab082ca2494a086f3b16a3f7c3038504
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_loc.py
@@ -0,0 +1,3291 @@
+""" test label based indexing with loc """
+from collections import namedtuple
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
+import re
+
+from dateutil.tz import gettz
+import numpy as np
+import pytest
+
+from pandas.errors import IndexingError
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ CategoricalDtype,
+ CategoricalIndex,
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ IndexSlice,
+ MultiIndex,
+ Period,
+ PeriodIndex,
+ Series,
+ SparseDtype,
+ Timedelta,
+ Timestamp,
+ date_range,
+ timedelta_range,
+ to_datetime,
+ to_timedelta,
+)
+import pandas._testing as tm
+from pandas.api.types import is_scalar
+from pandas.core.indexing import _one_ellipsis_message
+from pandas.tests.indexing.common import check_indexing_smoketest_or_raises
+
+
+@pytest.mark.parametrize(
+ "series, new_series, expected_ser",
+ [
+ [[np.nan, np.nan, "b"], ["a", np.nan, np.nan], [False, True, True]],
+ [[np.nan, "b"], ["a", np.nan], [False, True]],
+ ],
+)
+def test_not_change_nan_loc(series, new_series, expected_ser):
+ # GH 28403
+ df = DataFrame({"A": series})
+ df.loc[:, "A"] = new_series
+ expected = DataFrame({"A": expected_ser})
+ tm.assert_frame_equal(df.isna(), expected)
+ tm.assert_frame_equal(df.notna(), ~expected)
+
+
+class TestLoc:
+ def test_none_values_on_string_columns(self):
+ # Issue #32218
+ df = DataFrame(["1", "2", None], columns=["a"], dtype="str")
+
+ assert df.loc[2, "a"] is None
+
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ def test_loc_getitem_int(self, kind, request):
+ # int label
+ obj = request.getfixturevalue(f"{kind}_labels")
+ check_indexing_smoketest_or_raises(obj, "loc", 2, fails=KeyError)
+
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ def test_loc_getitem_label(self, kind, request):
+ # label
+ obj = request.getfixturevalue(f"{kind}_empty")
+ check_indexing_smoketest_or_raises(obj, "loc", "c", fails=KeyError)
+
+ @pytest.mark.parametrize(
+ "key, typs, axes",
+ [
+ ["f", ["ints", "uints", "labels", "mixed", "ts"], None],
+ ["f", ["floats"], None],
+ [20, ["ints", "uints", "mixed"], None],
+ [20, ["labels"], None],
+ [20, ["ts"], 0],
+ [20, ["floats"], 0],
+ ],
+ )
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ def test_loc_getitem_label_out_of_range(self, key, typs, axes, kind, request):
+ for typ in typs:
+ obj = request.getfixturevalue(f"{kind}_{typ}")
+ # out of range label
+ check_indexing_smoketest_or_raises(
+ obj, "loc", key, axes=axes, fails=KeyError
+ )
+
+ @pytest.mark.parametrize(
+ "key, typs",
+ [
+ [[0, 1, 2], ["ints", "uints", "floats"]],
+ [[1, 3.0, "A"], ["ints", "uints", "floats"]],
+ ],
+ )
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ def test_loc_getitem_label_list(self, key, typs, kind, request):
+ for typ in typs:
+ obj = request.getfixturevalue(f"{kind}_{typ}")
+ # list of labels
+ check_indexing_smoketest_or_raises(obj, "loc", key, fails=KeyError)
+
+ @pytest.mark.parametrize(
+ "key, typs, axes",
+ [
+ [[0, 1, 2], ["empty"], None],
+ [[0, 2, 10], ["ints", "uints", "floats"], 0],
+ [[3, 6, 7], ["ints", "uints", "floats"], 1],
+ # GH 17758 - MultiIndex and missing keys
+ [[(1, 3), (1, 4), (2, 5)], ["multi"], 0],
+ ],
+ )
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ def test_loc_getitem_label_list_with_missing(self, key, typs, axes, kind, request):
+ for typ in typs:
+ obj = request.getfixturevalue(f"{kind}_{typ}")
+ check_indexing_smoketest_or_raises(
+ obj, "loc", key, axes=axes, fails=KeyError
+ )
+
+ @pytest.mark.parametrize("typs", ["ints", "uints"])
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ def test_loc_getitem_label_list_fails(self, typs, kind, request):
+ # fails
+ obj = request.getfixturevalue(f"{kind}_{typs}")
+ check_indexing_smoketest_or_raises(
+ obj, "loc", [20, 30, 40], axes=1, fails=KeyError
+ )
+
+ def test_loc_getitem_label_array_like(self):
+ # TODO: test something?
+ # array like
+ pass
+
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ def test_loc_getitem_bool(self, kind, request):
+ obj = request.getfixturevalue(f"{kind}_empty")
+ # boolean indexers
+ b = [True, False, True, False]
+
+ check_indexing_smoketest_or_raises(obj, "loc", b, fails=IndexError)
+
+ @pytest.mark.parametrize(
+ "slc, typs, axes, fails",
+ [
+ [
+ slice(1, 3),
+ ["labels", "mixed", "empty", "ts", "floats"],
+ None,
+ TypeError,
+ ],
+ [slice("20130102", "20130104"), ["ts"], 1, TypeError],
+ [slice(2, 8), ["mixed"], 0, TypeError],
+ [slice(2, 8), ["mixed"], 1, KeyError],
+ [slice(2, 4, 2), ["mixed"], 0, TypeError],
+ ],
+ )
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ def test_loc_getitem_label_slice(self, slc, typs, axes, fails, kind, request):
+ # label slices (with ints)
+
+ # real label slices
+
+ # GH 14316
+ for typ in typs:
+ obj = request.getfixturevalue(f"{kind}_{typ}")
+ check_indexing_smoketest_or_raises(
+ obj,
+ "loc",
+ slc,
+ axes=axes,
+ fails=fails,
+ )
+
+ def test_setitem_from_duplicate_axis(self):
+ # GH#34034
+ df = DataFrame(
+ [[20, "a"], [200, "a"], [200, "a"]],
+ columns=["col1", "col2"],
+ index=[10, 1, 1],
+ )
+ df.loc[1, "col1"] = np.arange(2)
+ expected = DataFrame(
+ [[20, "a"], [0, "a"], [1, "a"]], columns=["col1", "col2"], index=[10, 1, 1]
+ )
+ tm.assert_frame_equal(df, expected)
+
+ def test_column_types_consistent(self):
+ # GH 26779
+ df = DataFrame(
+ data={
+ "channel": [1, 2, 3],
+ "A": ["String 1", np.nan, "String 2"],
+ "B": [
+ Timestamp("2019-06-11 11:00:00"),
+ pd.NaT,
+ Timestamp("2019-06-11 12:00:00"),
+ ],
+ }
+ )
+ df2 = DataFrame(
+ data={"A": ["String 3"], "B": [Timestamp("2019-06-11 12:00:00")]}
+ )
+ # Change Columns A and B to df2.values wherever Column A is NaN
+ df.loc[df["A"].isna(), ["A", "B"]] = df2.values
+ expected = DataFrame(
+ data={
+ "channel": [1, 2, 3],
+ "A": ["String 1", "String 3", "String 2"],
+ "B": [
+ Timestamp("2019-06-11 11:00:00"),
+ Timestamp("2019-06-11 12:00:00"),
+ Timestamp("2019-06-11 12:00:00"),
+ ],
+ }
+ )
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize(
+ "obj, key, exp",
+ [
+ (
+ DataFrame([[1]], columns=Index([False])),
+ IndexSlice[:, False],
+ Series([1], name=False),
+ ),
+ (Series([1], index=Index([False])), False, [1]),
+ (DataFrame([[1]], index=Index([False])), False, Series([1], name=False)),
+ ],
+ )
+ def test_loc_getitem_single_boolean_arg(self, obj, key, exp):
+ # GH 44322
+ res = obj.loc[key]
+ if isinstance(exp, (DataFrame, Series)):
+ tm.assert_equal(res, exp)
+ else:
+ assert res == exp
+
+
+class TestLocBaseIndependent:
+ # Tests for loc that do not depend on subclassing Base
+ def test_loc_npstr(self):
+ # GH#45580
+ df = DataFrame(index=date_range("2021", "2022"))
+ result = df.loc[np.array(["2021/6/1"])[0] :]
+ expected = df.iloc[151:]
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "msg, key",
+ [
+ (r"Period\('2019', 'A-DEC'\), 'foo', 'bar'", (Period(2019), "foo", "bar")),
+ (r"Period\('2019', 'A-DEC'\), 'y1', 'bar'", (Period(2019), "y1", "bar")),
+ (r"Period\('2019', 'A-DEC'\), 'foo', 'z1'", (Period(2019), "foo", "z1")),
+ (
+ r"Period\('2018', 'A-DEC'\), Period\('2016', 'A-DEC'\), 'bar'",
+ (Period(2018), Period(2016), "bar"),
+ ),
+ (r"Period\('2018', 'A-DEC'\), 'foo', 'y1'", (Period(2018), "foo", "y1")),
+ (
+ r"Period\('2017', 'A-DEC'\), 'foo', Period\('2015', 'A-DEC'\)",
+ (Period(2017), "foo", Period(2015)),
+ ),
+ (r"Period\('2017', 'A-DEC'\), 'z1', 'bar'", (Period(2017), "z1", "bar")),
+ ],
+ )
+ def test_contains_raise_error_if_period_index_is_in_multi_index(self, msg, key):
+ # GH#20684
+ """
+ parse_datetime_string_with_reso return parameter if type not matched.
+ PeriodIndex.get_loc takes returned value from parse_datetime_string_with_reso
+ as a tuple.
+ If first argument is Period and a tuple has 3 items,
+ process go on not raise exception
+ """
+ df = DataFrame(
+ {
+ "A": [Period(2019), "x1", "x2"],
+ "B": [Period(2018), Period(2016), "y1"],
+ "C": [Period(2017), "z1", Period(2015)],
+ "V1": [1, 2, 3],
+ "V2": [10, 20, 30],
+ }
+ ).set_index(["A", "B", "C"])
+ with pytest.raises(KeyError, match=msg):
+ df.loc[key]
+
+ def test_loc_getitem_missing_unicode_key(self):
+ df = DataFrame({"a": [1]})
+ with pytest.raises(KeyError, match="\u05d0"):
+ df.loc[:, "\u05d0"] # should not raise UnicodeEncodeError
+
+ def test_loc_getitem_dups(self):
+ # GH 5678
+ # repeated getitems on a dup index returning a ndarray
+ df = DataFrame(
+ np.random.default_rng(2).random((20, 5)),
+ index=["ABCDE"[x % 5] for x in range(20)],
+ )
+ expected = df.loc["A", 0]
+ result = df.loc[:, 0].loc["A"]
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_getitem_dups2(self):
+ # GH4726
+ # dup indexing with iloc/loc
+ df = DataFrame(
+ [[1, 2, "foo", "bar", Timestamp("20130101")]],
+ columns=["a", "a", "a", "a", "a"],
+ index=[1],
+ )
+ expected = Series(
+ [1, 2, "foo", "bar", Timestamp("20130101")],
+ index=["a", "a", "a", "a", "a"],
+ name=1,
+ )
+
+ result = df.iloc[0]
+ tm.assert_series_equal(result, expected)
+
+ result = df.loc[1]
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_setitem_dups(self):
+ # GH 6541
+ df_orig = DataFrame(
+ {
+ "me": list("rttti"),
+ "foo": list("aaade"),
+ "bar": np.arange(5, dtype="float64") * 1.34 + 2,
+ "bar2": np.arange(5, dtype="float64") * -0.34 + 2,
+ }
+ ).set_index("me")
+
+ indexer = (
+ "r",
+ ["bar", "bar2"],
+ )
+ df = df_orig.copy()
+ df.loc[indexer] *= 2.0
+ tm.assert_series_equal(df.loc[indexer], 2.0 * df_orig.loc[indexer])
+
+ indexer = (
+ "r",
+ "bar",
+ )
+ df = df_orig.copy()
+ df.loc[indexer] *= 2.0
+ assert df.loc[indexer] == 2.0 * df_orig.loc[indexer]
+
+ indexer = (
+ "t",
+ ["bar", "bar2"],
+ )
+ df = df_orig.copy()
+ df.loc[indexer] *= 2.0
+ tm.assert_frame_equal(df.loc[indexer], 2.0 * df_orig.loc[indexer])
+
+ def test_loc_setitem_slice(self):
+ # GH10503
+
+ # assigning the same type should not change the type
+ df1 = DataFrame({"a": [0, 1, 1], "b": Series([100, 200, 300], dtype="uint32")})
+ ix = df1["a"] == 1
+ newb1 = df1.loc[ix, "b"] + 1
+ df1.loc[ix, "b"] = newb1
+ expected = DataFrame(
+ {"a": [0, 1, 1], "b": Series([100, 201, 301], dtype="uint32")}
+ )
+ tm.assert_frame_equal(df1, expected)
+
+ # assigning a new type should get the inferred type
+ df2 = DataFrame({"a": [0, 1, 1], "b": [100, 200, 300]}, dtype="uint64")
+ ix = df1["a"] == 1
+ newb2 = df2.loc[ix, "b"]
+ with tm.assert_produces_warning(
+ FutureWarning, match="item of incompatible dtype"
+ ):
+ df1.loc[ix, "b"] = newb2
+ expected = DataFrame({"a": [0, 1, 1], "b": [100, 200, 300]}, dtype="uint64")
+ tm.assert_frame_equal(df2, expected)
+
+ def test_loc_setitem_dtype(self):
+ # GH31340
+ df = DataFrame({"id": ["A"], "a": [1.2], "b": [0.0], "c": [-2.5]})
+ cols = ["a", "b", "c"]
+ df.loc[:, cols] = df.loc[:, cols].astype("float32")
+
+ # pre-2.0 this setting would swap in new arrays, in 2.0 it is correctly
+ # in-place, consistent with non-split-path
+ expected = DataFrame(
+ {
+ "id": ["A"],
+ "a": np.array([1.2], dtype="float64"),
+ "b": np.array([0.0], dtype="float64"),
+ "c": np.array([-2.5], dtype="float64"),
+ }
+ ) # id is inferred as object
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_getitem_label_list_with_missing(self):
+ s = Series(range(3), index=["a", "b", "c"])
+
+ # consistency
+ with pytest.raises(KeyError, match="not in index"):
+ s[["a", "d"]]
+
+ s = Series(range(3))
+ with pytest.raises(KeyError, match="not in index"):
+ s[[0, 3]]
+
+ @pytest.mark.parametrize("index", [[True, False], [True, False, True, False]])
+ def test_loc_getitem_bool_diff_len(self, index):
+ # GH26658
+ s = Series([1, 2, 3])
+ msg = f"Boolean index has wrong length: {len(index)} instead of {len(s)}"
+ with pytest.raises(IndexError, match=msg):
+ s.loc[index]
+
+ def test_loc_getitem_int_slice(self):
+ # TODO: test something here?
+ pass
+
+ def test_loc_to_fail(self):
+ # GH3449
+ df = DataFrame(
+ np.random.default_rng(2).random((3, 3)),
+ index=["a", "b", "c"],
+ columns=["e", "f", "g"],
+ )
+
+ msg = (
+ rf"\"None of \[Index\(\[1, 2\], dtype='{np.dtype(int)}'\)\] are "
+ r"in the \[index\]\""
+ )
+ with pytest.raises(KeyError, match=msg):
+ df.loc[[1, 2], [1, 2]]
+
+ def test_loc_to_fail2(self):
+ # GH 7496
+ # loc should not fallback
+
+ s = Series(dtype=object)
+ s.loc[1] = 1
+ s.loc["a"] = 2
+
+ with pytest.raises(KeyError, match=r"^-1$"):
+ s.loc[-1]
+
+ msg = (
+ rf"\"None of \[Index\(\[-1, -2\], dtype='{np.dtype(int)}'\)\] are "
+ r"in the \[index\]\""
+ )
+ with pytest.raises(KeyError, match=msg):
+ s.loc[[-1, -2]]
+
+ msg = r"\"None of \[Index\(\['4'\], dtype='object'\)\] are in the \[index\]\""
+ with pytest.raises(KeyError, match=msg):
+ s.loc[["4"]]
+
+ s.loc[-1] = 3
+ with pytest.raises(KeyError, match="not in index"):
+ s.loc[[-1, -2]]
+
+ s["a"] = 2
+ msg = (
+ rf"\"None of \[Index\(\[-2\], dtype='{np.dtype(int)}'\)\] are "
+ r"in the \[index\]\""
+ )
+ with pytest.raises(KeyError, match=msg):
+ s.loc[[-2]]
+
+ del s["a"]
+
+ with pytest.raises(KeyError, match=msg):
+ s.loc[[-2]] = 0
+
+ def test_loc_to_fail3(self):
+ # inconsistency between .loc[values] and .loc[values,:]
+ # GH 7999
+ df = DataFrame([["a"], ["b"]], index=[1, 2], columns=["value"])
+
+ msg = (
+ rf"\"None of \[Index\(\[3\], dtype='{np.dtype(int)}'\)\] are "
+ r"in the \[index\]\""
+ )
+ with pytest.raises(KeyError, match=msg):
+ df.loc[[3], :]
+
+ with pytest.raises(KeyError, match=msg):
+ df.loc[[3]]
+
+ def test_loc_getitem_list_with_fail(self):
+ # 15747
+ # should KeyError if *any* missing labels
+
+ s = Series([1, 2, 3])
+
+ s.loc[[2]]
+
+ msg = f"\"None of [Index([3], dtype='{np.dtype(int)}')] are in the [index]"
+ with pytest.raises(KeyError, match=re.escape(msg)):
+ s.loc[[3]]
+
+ # a non-match and a match
+ with pytest.raises(KeyError, match="not in index"):
+ s.loc[[2, 3]]
+
+ def test_loc_index(self):
+ # gh-17131
+ # a boolean index should index like a boolean numpy array
+
+ df = DataFrame(
+ np.random.default_rng(2).random(size=(5, 10)),
+ index=["alpha_0", "alpha_1", "alpha_2", "beta_0", "beta_1"],
+ )
+
+ mask = df.index.map(lambda x: "alpha" in x)
+ expected = df.loc[np.array(mask)]
+
+ result = df.loc[mask]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.loc[mask.values]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.loc[pd.array(mask, dtype="boolean")]
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_general(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((4, 4)),
+ columns=["A", "B", "C", "D"],
+ index=["A", "B", "C", "D"],
+ )
+
+ # want this to work
+ result = df.loc[:, "A":"B"].iloc[0:2, :]
+ assert (result.columns == ["A", "B"]).all()
+ assert (result.index == ["A", "B"]).all()
+
+ # mixed type
+ result = DataFrame({"a": [Timestamp("20130101")], "b": [1]}).iloc[0]
+ expected = Series([Timestamp("20130101"), 1], index=["a", "b"], name=0)
+ tm.assert_series_equal(result, expected)
+ assert result.dtype == object
+
+ @pytest.fixture
+ def frame_for_consistency(self):
+ return DataFrame(
+ {
+ "date": date_range("2000-01-01", "2000-01-5"),
+ "val": Series(range(5), dtype=np.int64),
+ }
+ )
+
+ @pytest.mark.parametrize(
+ "val",
+ [0, np.array(0, dtype=np.int64), np.array([0, 0, 0, 0, 0], dtype=np.int64)],
+ )
+ def test_loc_setitem_consistency(self, frame_for_consistency, val):
+ # GH 6149
+ # coerce similarly for setitem and loc when rows have a null-slice
+ expected = DataFrame(
+ {
+ "date": Series(0, index=range(5), dtype=np.int64),
+ "val": Series(range(5), dtype=np.int64),
+ }
+ )
+ df = frame_for_consistency.copy()
+ df.loc[:, "date"] = val
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_consistency_dt64_to_str(self, frame_for_consistency):
+ # GH 6149
+ # coerce similarly for setitem and loc when rows have a null-slice
+
+ expected = DataFrame(
+ {
+ "date": Series("foo", index=range(5)),
+ "val": Series(range(5), dtype=np.int64),
+ }
+ )
+ df = frame_for_consistency.copy()
+ df.loc[:, "date"] = "foo"
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_consistency_dt64_to_float(self, frame_for_consistency):
+ # GH 6149
+ # coerce similarly for setitem and loc when rows have a null-slice
+ expected = DataFrame(
+ {
+ "date": Series(1.0, index=range(5)),
+ "val": Series(range(5), dtype=np.int64),
+ }
+ )
+ df = frame_for_consistency.copy()
+ df.loc[:, "date"] = 1.0
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_consistency_single_row(self):
+ # GH 15494
+ # setting on frame with single row
+ df = DataFrame({"date": Series([Timestamp("20180101")])})
+ df.loc[:, "date"] = "string"
+ expected = DataFrame({"date": Series(["string"])})
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_consistency_empty(self):
+ # empty (essentially noops)
+ # before the enforcement of #45333 in 2.0, the loc.setitem here would
+ # change the dtype of df.x to int64
+ expected = DataFrame(columns=["x", "y"])
+ df = DataFrame(columns=["x", "y"])
+ with tm.assert_produces_warning(None):
+ df.loc[:, "x"] = 1
+ tm.assert_frame_equal(df, expected)
+
+ # setting with setitem swaps in a new array, so changes the dtype
+ df = DataFrame(columns=["x", "y"])
+ df["x"] = 1
+ expected["x"] = expected["x"].astype(np.int64)
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_consistency_slice_column_len(self):
+ # .loc[:,column] setting with slice == len of the column
+ # GH10408
+ levels = [
+ ["Region_1"] * 4,
+ ["Site_1", "Site_1", "Site_2", "Site_2"],
+ [3987227376, 3980680971, 3977723249, 3977723089],
+ ]
+ mi = MultiIndex.from_arrays(levels, names=["Region", "Site", "RespondentID"])
+
+ clevels = [
+ ["Respondent", "Respondent", "Respondent", "OtherCat", "OtherCat"],
+ ["Something", "StartDate", "EndDate", "Yes/No", "SomethingElse"],
+ ]
+ cols = MultiIndex.from_arrays(clevels, names=["Level_0", "Level_1"])
+
+ values = [
+ ["A", "5/25/2015 10:59", "5/25/2015 11:22", "Yes", np.nan],
+ ["A", "5/21/2015 9:40", "5/21/2015 9:52", "Yes", "Yes"],
+ ["A", "5/20/2015 8:27", "5/20/2015 8:41", "Yes", np.nan],
+ ["A", "5/20/2015 8:33", "5/20/2015 9:09", "Yes", "No"],
+ ]
+ df = DataFrame(values, index=mi, columns=cols)
+
+ df.loc[:, ("Respondent", "StartDate")] = to_datetime(
+ df.loc[:, ("Respondent", "StartDate")]
+ )
+ df.loc[:, ("Respondent", "EndDate")] = to_datetime(
+ df.loc[:, ("Respondent", "EndDate")]
+ )
+ df = df.infer_objects(copy=False)
+
+ # Adding a new key
+ df.loc[:, ("Respondent", "Duration")] = (
+ df.loc[:, ("Respondent", "EndDate")]
+ - df.loc[:, ("Respondent", "StartDate")]
+ )
+
+ # timedelta64[m] -> float, so this cannot be done inplace, so
+ # no warning
+ df.loc[:, ("Respondent", "Duration")] = df.loc[
+ :, ("Respondent", "Duration")
+ ] / Timedelta(60_000_000_000)
+
+ expected = Series(
+ [23.0, 12.0, 14.0, 36.0], index=df.index, name=("Respondent", "Duration")
+ )
+ tm.assert_series_equal(df[("Respondent", "Duration")], expected)
+
+ @pytest.mark.parametrize("unit", ["Y", "M", "D", "h", "m", "s", "ms", "us"])
+ def test_loc_assign_non_ns_datetime(self, unit):
+ # GH 27395, non-ns dtype assignment via .loc should work
+ # and return the same result when using simple assignment
+ df = DataFrame(
+ {
+ "timestamp": [
+ np.datetime64("2017-02-11 12:41:29"),
+ np.datetime64("1991-11-07 04:22:37"),
+ ]
+ }
+ )
+
+ df.loc[:, unit] = df.loc[:, "timestamp"].values.astype(f"datetime64[{unit}]")
+ df["expected"] = df.loc[:, "timestamp"].values.astype(f"datetime64[{unit}]")
+ expected = Series(df.loc[:, "expected"], name=unit)
+ tm.assert_series_equal(df.loc[:, unit], expected)
+
+ def test_loc_modify_datetime(self):
+ # see gh-28837
+ df = DataFrame.from_dict(
+ {"date": [1485264372711, 1485265925110, 1540215845888, 1540282121025]}
+ )
+
+ df["date_dt"] = to_datetime(df["date"], unit="ms", cache=True)
+
+ df.loc[:, "date_dt_cp"] = df.loc[:, "date_dt"]
+ df.loc[[2, 3], "date_dt_cp"] = df.loc[[2, 3], "date_dt"]
+
+ expected = DataFrame(
+ [
+ [1485264372711, "2017-01-24 13:26:12.711", "2017-01-24 13:26:12.711"],
+ [1485265925110, "2017-01-24 13:52:05.110", "2017-01-24 13:52:05.110"],
+ [1540215845888, "2018-10-22 13:44:05.888", "2018-10-22 13:44:05.888"],
+ [1540282121025, "2018-10-23 08:08:41.025", "2018-10-23 08:08:41.025"],
+ ],
+ columns=["date", "date_dt", "date_dt_cp"],
+ )
+
+ columns = ["date_dt", "date_dt_cp"]
+ expected[columns] = expected[columns].apply(to_datetime)
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_frame_with_reindex(self):
+ # GH#6254 setting issue
+ df = DataFrame(index=[3, 5, 4], columns=["A"], dtype=float)
+ df.loc[[4, 3, 5], "A"] = np.array([1, 2, 3], dtype="int64")
+
+ # setting integer values into a float dataframe with loc is inplace,
+ # so we retain float dtype
+ ser = Series([2, 3, 1], index=[3, 5, 4], dtype=float)
+ expected = DataFrame({"A": ser})
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_frame_with_reindex_mixed(self):
+ # GH#40480
+ df = DataFrame(index=[3, 5, 4], columns=["A", "B"], dtype=float)
+ df["B"] = "string"
+ df.loc[[4, 3, 5], "A"] = np.array([1, 2, 3], dtype="int64")
+ ser = Series([2, 3, 1], index=[3, 5, 4], dtype="int64")
+ # pre-2.0 this setting swapped in a new array, now it is inplace
+ # consistent with non-split-path
+ expected = DataFrame({"A": ser.astype(float)})
+ expected["B"] = "string"
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_frame_with_inverted_slice(self):
+ # GH#40480
+ df = DataFrame(index=[1, 2, 3], columns=["A", "B"], dtype=float)
+ df["B"] = "string"
+ df.loc[slice(3, 0, -1), "A"] = np.array([1, 2, 3], dtype="int64")
+ # pre-2.0 this setting swapped in a new array, now it is inplace
+ # consistent with non-split-path
+ expected = DataFrame({"A": [3.0, 2.0, 1.0], "B": "string"}, index=[1, 2, 3])
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_empty_frame(self):
+ # GH#6252 setting with an empty frame
+ keys1 = ["@" + str(i) for i in range(5)]
+ val1 = np.arange(5, dtype="int64")
+
+ keys2 = ["@" + str(i) for i in range(4)]
+ val2 = np.arange(4, dtype="int64")
+
+ index = list(set(keys1).union(keys2))
+ df = DataFrame(index=index)
+ df["A"] = np.nan
+ df.loc[keys1, "A"] = val1
+
+ df["B"] = np.nan
+ df.loc[keys2, "B"] = val2
+
+ # Because df["A"] was initialized as float64, setting values into it
+ # is inplace, so that dtype is retained
+ sera = Series(val1, index=keys1, dtype=np.float64)
+ serb = Series(val2, index=keys2)
+ expected = DataFrame({"A": sera, "B": serb}).reindex(index=index)
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_frame(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ index=list("abcd"),
+ columns=list("ABCD"),
+ )
+
+ result = df.iloc[0, 0]
+
+ df.loc["a", "A"] = 1
+ result = df.loc["a", "A"]
+ assert result == 1
+
+ result = df.iloc[0, 0]
+ assert result == 1
+
+ df.loc[:, "B":"D"] = 0
+ expected = df.loc[:, "B":"D"]
+ result = df.iloc[:, 1:]
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_setitem_frame_nan_int_coercion_invalid(self):
+ # GH 8669
+ # invalid coercion of nan -> int
+ df = DataFrame({"A": [1, 2, 3], "B": np.nan})
+ df.loc[df.B > df.A, "B"] = df.A
+ expected = DataFrame({"A": [1, 2, 3], "B": np.nan})
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_frame_mixed_labels(self):
+ # GH 6546
+ # setting with mixed labels
+ df = DataFrame({1: [1, 2], 2: [3, 4], "a": ["a", "b"]})
+
+ result = df.loc[0, [1, 2]]
+ expected = Series(
+ [1, 3], index=Index([1, 2], dtype=object), dtype=object, name=0
+ )
+ tm.assert_series_equal(result, expected)
+
+ expected = DataFrame({1: [5, 2], 2: [6, 4], "a": ["a", "b"]})
+ df.loc[0, [1, 2]] = [5, 6]
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_frame_multiples(self):
+ # multiple setting
+ df = DataFrame(
+ {"A": ["foo", "bar", "baz"], "B": Series(range(3), dtype=np.int64)}
+ )
+ rhs = df.loc[1:2]
+ rhs.index = df.index[0:2]
+ df.loc[0:1] = rhs
+ expected = DataFrame(
+ {"A": ["bar", "baz", "baz"], "B": Series([1, 2, 2], dtype=np.int64)}
+ )
+ tm.assert_frame_equal(df, expected)
+
+ # multiple setting with frame on rhs (with M8)
+ df = DataFrame(
+ {
+ "date": date_range("2000-01-01", "2000-01-5"),
+ "val": Series(range(5), dtype=np.int64),
+ }
+ )
+ expected = DataFrame(
+ {
+ "date": [
+ Timestamp("20000101"),
+ Timestamp("20000102"),
+ Timestamp("20000101"),
+ Timestamp("20000102"),
+ Timestamp("20000103"),
+ ],
+ "val": Series([0, 1, 0, 1, 2], dtype=np.int64),
+ }
+ )
+ rhs = df.loc[0:2]
+ rhs.index = df.index[2:5]
+ df.loc[2:4] = rhs
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize(
+ "indexer", [["A"], slice(None, "A", None), np.array(["A"])]
+ )
+ @pytest.mark.parametrize("value", [["Z"], np.array(["Z"])])
+ def test_loc_setitem_with_scalar_index(self, indexer, value):
+ # GH #19474
+ # assigning like "df.loc[0, ['A']] = ['Z']" should be evaluated
+ # elementwisely, not using "setter('A', ['Z'])".
+
+ # Set object dtype to avoid upcast when setting 'Z'
+ df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"]).astype({"A": object})
+ df.loc[0, indexer] = value
+ result = df.loc[0, "A"]
+
+ assert is_scalar(result) and result == "Z"
+
+ @pytest.mark.parametrize(
+ "index,box,expected",
+ [
+ (
+ ([0, 2], ["A", "B", "C", "D"]),
+ 7,
+ DataFrame(
+ [[7, 7, 7, 7], [3, 4, np.nan, np.nan], [7, 7, 7, 7]],
+ columns=["A", "B", "C", "D"],
+ ),
+ ),
+ (
+ (1, ["C", "D"]),
+ [7, 8],
+ DataFrame(
+ [[1, 2, np.nan, np.nan], [3, 4, 7, 8], [5, 6, np.nan, np.nan]],
+ columns=["A", "B", "C", "D"],
+ ),
+ ),
+ (
+ (1, ["A", "B", "C"]),
+ np.array([7, 8, 9], dtype=np.int64),
+ DataFrame(
+ [[1, 2, np.nan], [7, 8, 9], [5, 6, np.nan]], columns=["A", "B", "C"]
+ ),
+ ),
+ (
+ (slice(1, 3, None), ["B", "C", "D"]),
+ [[7, 8, 9], [10, 11, 12]],
+ DataFrame(
+ [[1, 2, np.nan, np.nan], [3, 7, 8, 9], [5, 10, 11, 12]],
+ columns=["A", "B", "C", "D"],
+ ),
+ ),
+ (
+ (slice(1, 3, None), ["C", "A", "D"]),
+ np.array([[7, 8, 9], [10, 11, 12]], dtype=np.int64),
+ DataFrame(
+ [[1, 2, np.nan, np.nan], [8, 4, 7, 9], [11, 6, 10, 12]],
+ columns=["A", "B", "C", "D"],
+ ),
+ ),
+ (
+ (slice(None, None, None), ["A", "C"]),
+ DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]),
+ DataFrame(
+ [[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"]
+ ),
+ ),
+ ],
+ )
+ def test_loc_setitem_missing_columns(self, index, box, expected):
+ # GH 29334
+ df = DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"])
+
+ df.loc[index] = box
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_coercion(self):
+ # GH#12411
+ df = DataFrame({"date": [Timestamp("20130101").tz_localize("UTC"), pd.NaT]})
+ expected = df.dtypes
+
+ result = df.iloc[[0]]
+ tm.assert_series_equal(result.dtypes, expected)
+
+ result = df.iloc[[1]]
+ tm.assert_series_equal(result.dtypes, expected)
+
+ def test_loc_coercion2(self):
+ # GH#12045
+ df = DataFrame({"date": [datetime(2012, 1, 1), datetime(1012, 1, 2)]})
+ expected = df.dtypes
+
+ result = df.iloc[[0]]
+ tm.assert_series_equal(result.dtypes, expected)
+
+ result = df.iloc[[1]]
+ tm.assert_series_equal(result.dtypes, expected)
+
+ def test_loc_coercion3(self):
+ # GH#11594
+ df = DataFrame({"text": ["some words"] + [None] * 9})
+ expected = df.dtypes
+
+ result = df.iloc[0:2]
+ tm.assert_series_equal(result.dtypes, expected)
+
+ result = df.iloc[3:]
+ tm.assert_series_equal(result.dtypes, expected)
+
+ def test_setitem_new_key_tz(self, indexer_sl):
+ # GH#12862 should not raise on assigning the second value
+ vals = [
+ to_datetime(42).tz_localize("UTC"),
+ to_datetime(666).tz_localize("UTC"),
+ ]
+ expected = Series(vals, index=["foo", "bar"])
+
+ ser = Series(dtype=object)
+ indexer_sl(ser)["foo"] = vals[0]
+ indexer_sl(ser)["bar"] = vals[1]
+
+ tm.assert_series_equal(ser, expected)
+
+ def test_loc_non_unique(self):
+ # GH3659
+ # non-unique indexer with loc slice
+ # https://groups.google.com/forum/?fromgroups#!topic/pydata/zTm2No0crYs
+
+ # these are going to raise because the we are non monotonic
+ df = DataFrame(
+ {"A": [1, 2, 3, 4, 5, 6], "B": [3, 4, 5, 6, 7, 8]}, index=[0, 1, 0, 1, 2, 3]
+ )
+ msg = "'Cannot get left slice bound for non-unique label: 1'"
+ with pytest.raises(KeyError, match=msg):
+ df.loc[1:]
+ msg = "'Cannot get left slice bound for non-unique label: 0'"
+ with pytest.raises(KeyError, match=msg):
+ df.loc[0:]
+ msg = "'Cannot get left slice bound for non-unique label: 1'"
+ with pytest.raises(KeyError, match=msg):
+ df.loc[1:2]
+
+ # monotonic are ok
+ df = DataFrame(
+ {"A": [1, 2, 3, 4, 5, 6], "B": [3, 4, 5, 6, 7, 8]}, index=[0, 1, 0, 1, 2, 3]
+ ).sort_index(axis=0)
+ result = df.loc[1:]
+ expected = DataFrame({"A": [2, 4, 5, 6], "B": [4, 6, 7, 8]}, index=[1, 1, 2, 3])
+ tm.assert_frame_equal(result, expected)
+
+ result = df.loc[0:]
+ tm.assert_frame_equal(result, df)
+
+ result = df.loc[1:2]
+ expected = DataFrame({"A": [2, 4, 5], "B": [4, 6, 7]}, index=[1, 1, 2])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.arm_slow
+ @pytest.mark.parametrize("length, l2", [[900, 100], [900000, 100000]])
+ def test_loc_non_unique_memory_error(self, length, l2):
+ # GH 4280
+ # non_unique index with a large selection triggers a memory error
+
+ columns = list("ABCDEFG")
+
+ df = pd.concat(
+ [
+ DataFrame(
+ np.random.default_rng(2).standard_normal((length, len(columns))),
+ index=np.arange(length),
+ columns=columns,
+ ),
+ DataFrame(np.ones((l2, len(columns))), index=[0] * l2, columns=columns),
+ ]
+ )
+
+ assert df.index.is_unique is False
+
+ mask = np.arange(l2)
+ result = df.loc[mask]
+ expected = pd.concat(
+ [
+ df.take([0]),
+ DataFrame(
+ np.ones((len(mask), len(columns))),
+ index=[0] * len(mask),
+ columns=columns,
+ ),
+ df.take(mask[1:]),
+ ]
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_name(self):
+ # GH 3880
+ df = DataFrame([[1, 1], [1, 1]])
+ df.index.name = "index_name"
+ result = df.iloc[[0, 1]].index.name
+ assert result == "index_name"
+
+ result = df.loc[[0, 1]].index.name
+ assert result == "index_name"
+
+ def test_loc_empty_list_indexer_is_ok(self):
+ df = tm.makeCustomDataframe(5, 2)
+ # vertical empty
+ tm.assert_frame_equal(
+ df.loc[:, []], df.iloc[:, :0], check_index_type=True, check_column_type=True
+ )
+ # horizontal empty
+ tm.assert_frame_equal(
+ df.loc[[], :], df.iloc[:0, :], check_index_type=True, check_column_type=True
+ )
+ # horizontal empty
+ tm.assert_frame_equal(
+ df.loc[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True
+ )
+
+ def test_identity_slice_returns_new_object(self, using_copy_on_write):
+ # GH13873
+
+ original_df = DataFrame({"a": [1, 2, 3]})
+ sliced_df = original_df.loc[:]
+ assert sliced_df is not original_df
+ assert original_df[:] is not original_df
+ assert original_df.loc[:, :] is not original_df
+
+ # should be a shallow copy
+ assert np.shares_memory(original_df["a"]._values, sliced_df["a"]._values)
+
+ # Setting using .loc[:, "a"] sets inplace so alters both sliced and orig
+ # depending on CoW
+ original_df.loc[:, "a"] = [4, 4, 4]
+ if using_copy_on_write:
+ assert (sliced_df["a"] == [1, 2, 3]).all()
+ else:
+ assert (sliced_df["a"] == 4).all()
+
+ # These should not return copies
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
+ if using_copy_on_write:
+ assert df[0] is not df.loc[:, 0]
+ else:
+ assert df[0] is df.loc[:, 0]
+
+ # Same tests for Series
+ original_series = Series([1, 2, 3, 4, 5, 6])
+ sliced_series = original_series.loc[:]
+ assert sliced_series is not original_series
+ assert original_series[:] is not original_series
+
+ original_series[:3] = [7, 8, 9]
+ if using_copy_on_write:
+ assert all(sliced_series[:3] == [1, 2, 3])
+ else:
+ assert all(sliced_series[:3] == [7, 8, 9])
+
+ def test_loc_copy_vs_view(self, request, using_copy_on_write):
+ # GH 15631
+
+ if not using_copy_on_write:
+ mark = pytest.mark.xfail(reason="accidental fix reverted - GH37497")
+ request.node.add_marker(mark)
+ x = DataFrame(zip(range(3), range(3)), columns=["a", "b"])
+
+ y = x.copy()
+ q = y.loc[:, "a"]
+ q += 2
+
+ tm.assert_frame_equal(x, y)
+
+ z = x.copy()
+ q = z.loc[x.index, "a"]
+ q += 2
+
+ tm.assert_frame_equal(x, z)
+
+ def test_loc_uint64(self):
+ # GH20722
+ # Test whether loc accept uint64 max value as index.
+ umax = np.iinfo("uint64").max
+ ser = Series([1, 2], index=[umax - 1, umax])
+
+ result = ser.loc[umax - 1]
+ expected = ser.iloc[0]
+ assert result == expected
+
+ result = ser.loc[[umax - 1]]
+ expected = ser.iloc[[0]]
+ tm.assert_series_equal(result, expected)
+
+ result = ser.loc[[umax - 1, umax]]
+ tm.assert_series_equal(result, ser)
+
+ def test_loc_uint64_disallow_negative(self):
+ # GH#41775
+ umax = np.iinfo("uint64").max
+ ser = Series([1, 2], index=[umax - 1, umax])
+
+ with pytest.raises(KeyError, match="-1"):
+ # don't wrap around
+ ser.loc[-1]
+
+ with pytest.raises(KeyError, match="-1"):
+ # don't wrap around
+ ser.loc[[-1]]
+
+ def test_loc_setitem_empty_append_expands_rows(self):
+ # GH6173, various appends to an empty dataframe
+
+ data = [1, 2, 3]
+ expected = DataFrame(
+ {"x": data, "y": np.array([np.nan] * len(data), dtype=object)}
+ )
+
+ # appends to fit length of data
+ df = DataFrame(columns=["x", "y"])
+ df.loc[:, "x"] = data
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_empty_append_expands_rows_mixed_dtype(self):
+ # GH#37932 same as test_loc_setitem_empty_append_expands_rows
+ # but with mixed dtype so we go through take_split_path
+ data = [1, 2, 3]
+ expected = DataFrame(
+ {"x": data, "y": np.array([np.nan] * len(data), dtype=object)}
+ )
+
+ df = DataFrame(columns=["x", "y"])
+ df["x"] = df["x"].astype(np.int64)
+ df.loc[:, "x"] = data
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_empty_append_single_value(self):
+ # only appends one value
+ expected = DataFrame({"x": [1.0], "y": [np.nan]})
+ df = DataFrame(columns=["x", "y"], dtype=float)
+ df.loc[0, "x"] = expected.loc[0, "x"]
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_empty_append_raises(self):
+ # GH6173, various appends to an empty dataframe
+
+ data = [1, 2]
+ df = DataFrame(columns=["x", "y"])
+ df.index = df.index.astype(np.int64)
+ msg = (
+ rf"None of \[Index\(\[0, 1\], dtype='{np.dtype(int)}'\)\] "
+ r"are in the \[index\]"
+ )
+ with pytest.raises(KeyError, match=msg):
+ df.loc[[0, 1], "x"] = data
+
+ msg = "|".join(
+ [
+ "cannot copy sequence with size 2 to array axis with dimension 0",
+ r"could not broadcast input array from shape \(2,\) into shape \(0,\)",
+ "Must have equal len keys and value when setting with an iterable",
+ ]
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.loc[0:2, "x"] = data
+
+ def test_indexing_zerodim_np_array(self):
+ # GH24924
+ df = DataFrame([[1, 2], [3, 4]])
+ result = df.loc[np.array(0)]
+ s = Series([1, 2], name=0)
+ tm.assert_series_equal(result, s)
+
+ def test_series_indexing_zerodim_np_array(self):
+ # GH24924
+ s = Series([1, 2])
+ result = s.loc[np.array(0)]
+ assert result == 1
+
+ def test_loc_reverse_assignment(self):
+ # GH26939
+ data = [1, 2, 3, 4, 5, 6] + [None] * 4
+ expected = Series(data, index=range(2010, 2020))
+
+ result = Series(index=range(2010, 2020), dtype=np.float64)
+ result.loc[2015:2010:-1] = [6, 5, 4, 3, 2, 1]
+
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_setitem_str_to_small_float_conversion_type(self):
+ # GH#20388
+
+ col_data = [str(np.random.default_rng(2).random() * 1e-12) for _ in range(5)]
+ result = DataFrame(col_data, columns=["A"])
+ expected = DataFrame(col_data, columns=["A"], dtype=object)
+ tm.assert_frame_equal(result, expected)
+
+ # assigning with loc/iloc attempts to set the values inplace, which
+ # in this case is successful
+ result.loc[result.index, "A"] = [float(x) for x in col_data]
+ expected = DataFrame(col_data, columns=["A"], dtype=float).astype(object)
+ tm.assert_frame_equal(result, expected)
+
+ # assigning the entire column using __setitem__ swaps in the new array
+ # GH#???
+ result["A"] = [float(x) for x in col_data]
+ expected = DataFrame(col_data, columns=["A"], dtype=float)
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_getitem_time_object(self, frame_or_series):
+ rng = date_range("1/1/2000", "1/5/2000", freq="5min")
+ mask = (rng.hour == 9) & (rng.minute == 30)
+
+ obj = DataFrame(
+ np.random.default_rng(2).standard_normal((len(rng), 3)), index=rng
+ )
+ obj = tm.get_obj(obj, frame_or_series)
+
+ result = obj.loc[time(9, 30)]
+ exp = obj.loc[mask]
+ tm.assert_equal(result, exp)
+
+ chunk = obj.loc["1/4/2000":]
+ result = chunk.loc[time(9, 30)]
+ expected = result[-1:]
+
+ # Without resetting the freqs, these are 5 min and 1440 min, respectively
+ result.index = result.index._with_freq(None)
+ expected.index = expected.index._with_freq(None)
+ tm.assert_equal(result, expected)
+
+ @pytest.mark.parametrize("spmatrix_t", ["coo_matrix", "csc_matrix", "csr_matrix"])
+ @pytest.mark.parametrize("dtype", [np.int64, np.float64, complex])
+ def test_loc_getitem_range_from_spmatrix(self, spmatrix_t, dtype):
+ sp_sparse = pytest.importorskip("scipy.sparse")
+
+ spmatrix_t = getattr(sp_sparse, spmatrix_t)
+
+ # The bug is triggered by a sparse matrix with purely sparse columns. So the
+ # recipe below generates a rectangular matrix of dimension (5, 7) where all the
+ # diagonal cells are ones, meaning the last two columns are purely sparse.
+ rows, cols = 5, 7
+ spmatrix = spmatrix_t(np.eye(rows, cols, dtype=dtype), dtype=dtype)
+ df = DataFrame.sparse.from_spmatrix(spmatrix)
+
+ # regression test for GH#34526
+ itr_idx = range(2, rows)
+ result = df.loc[itr_idx].values
+ expected = spmatrix.toarray()[itr_idx]
+ tm.assert_numpy_array_equal(result, expected)
+
+ # regression test for GH#34540
+ result = df.loc[itr_idx].dtypes.values
+ expected = np.full(cols, SparseDtype(dtype, fill_value=0))
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_loc_getitem_listlike_all_retains_sparse(self):
+ df = DataFrame({"A": pd.array([0, 0], dtype=SparseDtype("int64"))})
+ result = df.loc[[0, 1]]
+ tm.assert_frame_equal(result, df)
+
+ def test_loc_getitem_sparse_frame(self):
+ # GH34687
+ sp_sparse = pytest.importorskip("scipy.sparse")
+
+ df = DataFrame.sparse.from_spmatrix(sp_sparse.eye(5))
+ result = df.loc[range(2)]
+ expected = DataFrame(
+ [[1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0]],
+ dtype=SparseDtype("float64", 0.0),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.loc[range(2)].loc[range(1)]
+ expected = DataFrame(
+ [[1.0, 0.0, 0.0, 0.0, 0.0]], dtype=SparseDtype("float64", 0.0)
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_getitem_sparse_series(self):
+ # GH34687
+ s = Series([1.0, 0.0, 0.0, 0.0, 0.0], dtype=SparseDtype("float64", 0.0))
+
+ result = s.loc[range(2)]
+ expected = Series([1.0, 0.0], dtype=SparseDtype("float64", 0.0))
+ tm.assert_series_equal(result, expected)
+
+ result = s.loc[range(3)].loc[range(2)]
+ expected = Series([1.0, 0.0], dtype=SparseDtype("float64", 0.0))
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("indexer", ["loc", "iloc"])
+ def test_getitem_single_row_sparse_df(self, indexer):
+ # GH#46406
+ df = DataFrame([[1.0, 0.0, 1.5], [0.0, 2.0, 0.0]], dtype=SparseDtype(float))
+ result = getattr(df, indexer)[0]
+ expected = Series([1.0, 0.0, 1.5], dtype=SparseDtype(float), name=0)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("key_type", [iter, np.array, Series, Index])
+ def test_loc_getitem_iterable(self, float_frame, key_type):
+ idx = key_type(["A", "B", "C"])
+ result = float_frame.loc[:, idx]
+ expected = float_frame.loc[:, ["A", "B", "C"]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_getitem_timedelta_0seconds(self):
+ # GH#10583
+ df = DataFrame(np.random.default_rng(2).normal(size=(10, 4)))
+ df.index = timedelta_range(start="0s", periods=10, freq="s")
+ expected = df.loc[Timedelta("0s") :, :]
+ result = df.loc["0s":, :]
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "val,expected", [(2**63 - 1, Series([1])), (2**63, Series([2]))]
+ )
+ def test_loc_getitem_uint64_scalar(self, val, expected):
+ # see GH#19399
+ df = DataFrame([1, 2], index=[2**63 - 1, 2**63])
+ result = df.loc[val]
+
+ expected.name = val
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_setitem_int_label_with_float_index(self, float_numpy_dtype):
+ # note labels are floats
+ dtype = float_numpy_dtype
+ ser = Series(["a", "b", "c"], index=Index([0, 0.5, 1], dtype=dtype))
+ expected = ser.copy()
+
+ ser.loc[1] = "zoo"
+ expected.iloc[2] = "zoo"
+
+ tm.assert_series_equal(ser, expected)
+
+ @pytest.mark.parametrize(
+ "indexer, expected",
+ [
+ # The test name is a misnomer in the 0 case as df.index[indexer]
+ # is a scalar.
+ (0, [20, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
+ (slice(4, 8), [0, 1, 2, 3, 20, 20, 20, 20, 8, 9]),
+ ([3, 5], [0, 1, 2, 20, 4, 20, 6, 7, 8, 9]),
+ ],
+ )
+ def test_loc_setitem_listlike_with_timedelta64index(self, indexer, expected):
+ # GH#16637
+ tdi = to_timedelta(range(10), unit="s")
+ df = DataFrame({"x": range(10)}, dtype="int64", index=tdi)
+
+ df.loc[df.index[indexer], "x"] = 20
+
+ expected = DataFrame(
+ expected,
+ index=tdi,
+ columns=["x"],
+ dtype="int64",
+ )
+
+ tm.assert_frame_equal(expected, df)
+
+ def test_loc_setitem_categorical_values_partial_column_slice(self):
+ # Assigning a Category to parts of a int/... column uses the values of
+ # the Categorical
+ df = DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")})
+ exp = DataFrame({"a": [1, "b", "b", 1, 1], "b": list("aabba")})
+ with tm.assert_produces_warning(
+ FutureWarning, match="item of incompatible dtype"
+ ):
+ df.loc[1:2, "a"] = Categorical(["b", "b"], categories=["a", "b"])
+ df.loc[2:3, "b"] = Categorical(["b", "b"], categories=["a", "b"])
+ tm.assert_frame_equal(df, exp)
+
+ def test_loc_setitem_single_row_categorical(self):
+ # GH#25495
+ df = DataFrame({"Alpha": ["a"], "Numeric": [0]})
+ categories = Categorical(df["Alpha"], categories=["a", "b", "c"])
+
+ # pre-2.0 this swapped in a new array, in 2.0 it operates inplace,
+ # consistent with non-split-path
+ df.loc[:, "Alpha"] = categories
+
+ result = df["Alpha"]
+ expected = Series(categories, index=df.index, name="Alpha").astype(object)
+ tm.assert_series_equal(result, expected)
+
+ # double-check that the non-loc setting retains categoricalness
+ df["Alpha"] = categories
+ tm.assert_series_equal(df["Alpha"], Series(categories, name="Alpha"))
+
+ def test_loc_setitem_datetime_coercion(self):
+ # GH#1048
+ df = DataFrame({"c": [Timestamp("2010-10-01")] * 3})
+ df.loc[0:1, "c"] = np.datetime64("2008-08-08")
+ assert Timestamp("2008-08-08") == df.loc[0, "c"]
+ assert Timestamp("2008-08-08") == df.loc[1, "c"]
+ with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
+ df.loc[2, "c"] = date(2005, 5, 5)
+ assert Timestamp("2005-05-05").date() == df.loc[2, "c"]
+
+ @pytest.mark.parametrize("idxer", ["var", ["var"]])
+ def test_loc_setitem_datetimeindex_tz(self, idxer, tz_naive_fixture):
+ # GH#11365
+ tz = tz_naive_fixture
+ idx = date_range(start="2015-07-12", periods=3, freq="H", tz=tz)
+ expected = DataFrame(1.2, index=idx, columns=["var"])
+ # if result started off with object dtype, then the .loc.__setitem__
+ # below would retain object dtype
+ result = DataFrame(index=idx, columns=["var"], dtype=np.float64)
+ result.loc[:, idxer] = expected
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_setitem_time_key(self, using_array_manager):
+ index = date_range("2012-01-01", "2012-01-05", freq="30min")
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(index), 5)), index=index
+ )
+ akey = time(12, 0, 0)
+ bkey = slice(time(13, 0, 0), time(14, 0, 0))
+ ainds = [24, 72, 120, 168]
+ binds = [26, 27, 28, 74, 75, 76, 122, 123, 124, 170, 171, 172]
+
+ result = df.copy()
+ result.loc[akey] = 0
+ result = result.loc[akey]
+ expected = df.loc[akey].copy()
+ expected.loc[:] = 0
+ if using_array_manager:
+ # TODO(ArrayManager) we are still overwriting columns
+ expected = expected.astype(float)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.copy()
+ result.loc[akey] = 0
+ result.loc[akey] = df.iloc[ainds]
+ tm.assert_frame_equal(result, df)
+
+ result = df.copy()
+ result.loc[bkey] = 0
+ result = result.loc[bkey]
+ expected = df.loc[bkey].copy()
+ expected.loc[:] = 0
+ if using_array_manager:
+ # TODO(ArrayManager) we are still overwriting columns
+ expected = expected.astype(float)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.copy()
+ result.loc[bkey] = 0
+ result.loc[bkey] = df.iloc[binds]
+ tm.assert_frame_equal(result, df)
+
+ @pytest.mark.parametrize("key", ["A", ["A"], ("A", slice(None))])
+ def test_loc_setitem_unsorted_multiindex_columns(self, key):
+ # GH#38601
+ mi = MultiIndex.from_tuples([("A", 4), ("B", "3"), ("A", "2")])
+ df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi)
+ obj = df.copy()
+ obj.loc[:, key] = np.zeros((2, 2), dtype="int64")
+ expected = DataFrame([[0, 2, 0], [0, 5, 0]], columns=mi)
+ tm.assert_frame_equal(obj, expected)
+
+ df = df.sort_index(axis=1)
+ df.loc[:, key] = np.zeros((2, 2), dtype="int64")
+ expected = expected.sort_index(axis=1)
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_uint_drop(self, any_int_numpy_dtype):
+ # see GH#18311
+ # assigning series.loc[0] = 4 changed series.dtype to int
+ series = Series([1, 2, 3], dtype=any_int_numpy_dtype)
+ series.loc[0] = 4
+ expected = Series([4, 2, 3], dtype=any_int_numpy_dtype)
+ tm.assert_series_equal(series, expected)
+
+ def test_loc_setitem_td64_non_nano(self):
+ # GH#14155
+ ser = Series(10 * [np.timedelta64(10, "m")])
+ ser.loc[[1, 2, 3]] = np.timedelta64(20, "m")
+ expected = Series(10 * [np.timedelta64(10, "m")])
+ expected.loc[[1, 2, 3]] = Timedelta(np.timedelta64(20, "m"))
+ tm.assert_series_equal(ser, expected)
+
+ def test_loc_setitem_2d_to_1d_raises(self):
+ data = np.random.default_rng(2).standard_normal((2, 2))
+ # float64 dtype to avoid upcast when trying to set float data
+ ser = Series(range(2), dtype="float64")
+
+ msg = "|".join(
+ [
+ r"shape mismatch: value array of shape \(2,2\)",
+ r"cannot reshape array of size 4 into shape \(2,\)",
+ ]
+ )
+ with pytest.raises(ValueError, match=msg):
+ ser.loc[range(2)] = data
+
+ msg = r"could not broadcast input array from shape \(2,2\) into shape \(2,?\)"
+ with pytest.raises(ValueError, match=msg):
+ ser.loc[:] = data
+
+ def test_loc_getitem_interval_index(self):
+ # GH#19977
+ index = pd.interval_range(start=0, periods=3)
+ df = DataFrame(
+ [[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=index, columns=["A", "B", "C"]
+ )
+
+ expected = 1
+ result = df.loc[0.5, "A"]
+ tm.assert_almost_equal(result, expected)
+
+ def test_loc_getitem_interval_index2(self):
+ # GH#19977
+ index = pd.interval_range(start=0, periods=3, closed="both")
+ df = DataFrame(
+ [[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=index, columns=["A", "B", "C"]
+ )
+
+ index_exp = pd.interval_range(start=0, periods=2, freq=1, closed="both")
+ expected = Series([1, 4], index=index_exp, name="A")
+ result = df.loc[1, "A"]
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("tpl", [(1,), (1, 2)])
+ def test_loc_getitem_index_single_double_tuples(self, tpl):
+ # GH#20991
+ idx = Index(
+ [(1,), (1, 2)],
+ name="A",
+ tupleize_cols=False,
+ )
+ df = DataFrame(index=idx)
+
+ result = df.loc[[tpl]]
+ idx = Index([tpl], name="A", tupleize_cols=False)
+ expected = DataFrame(index=idx)
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_getitem_index_namedtuple(self):
+ IndexType = namedtuple("IndexType", ["a", "b"])
+ idx1 = IndexType("foo", "bar")
+ idx2 = IndexType("baz", "bof")
+ index = Index([idx1, idx2], name="composite_index", tupleize_cols=False)
+ df = DataFrame([(1, 2), (3, 4)], index=index, columns=["A", "B"])
+
+ result = df.loc[IndexType("foo", "bar")]["A"]
+ assert result == 1
+
+ def test_loc_setitem_single_column_mixed(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)),
+ index=["a", "b", "c", "d", "e"],
+ columns=["foo", "bar", "baz"],
+ )
+ df["str"] = "qux"
+ df.loc[df.index[::2], "str"] = np.nan
+ expected = np.array([np.nan, "qux", np.nan, "qux", np.nan], dtype=object)
+ tm.assert_almost_equal(df["str"].values, expected)
+
+ def test_loc_setitem_cast2(self):
+ # GH#7704
+ # dtype conversion on setting
+ df = DataFrame(np.random.default_rng(2).random((30, 3)), columns=tuple("ABC"))
+ df["event"] = np.nan
+ with tm.assert_produces_warning(
+ FutureWarning, match="item of incompatible dtype"
+ ):
+ df.loc[10, "event"] = "foo"
+ result = df.dtypes
+ expected = Series(
+ [np.dtype("float64")] * 3 + [np.dtype("object")],
+ index=["A", "B", "C", "event"],
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_setitem_cast3(self):
+ # Test that data type is preserved . GH#5782
+ df = DataFrame({"one": np.arange(6, dtype=np.int8)})
+ df.loc[1, "one"] = 6
+ assert df.dtypes.one == np.dtype(np.int8)
+ df.one = np.int8(7)
+ assert df.dtypes.one == np.dtype(np.int8)
+
+ def test_loc_setitem_range_key(self, frame_or_series):
+ # GH#45479 don't treat range key as positional
+ obj = frame_or_series(range(5), index=[3, 4, 1, 0, 2])
+
+ values = [9, 10, 11]
+ if obj.ndim == 2:
+ values = [[9], [10], [11]]
+
+ obj.loc[range(3)] = values
+
+ expected = frame_or_series([0, 1, 10, 9, 11], index=obj.index)
+ tm.assert_equal(obj, expected)
+
+
+class TestLocWithEllipsis:
+ @pytest.fixture(params=[tm.loc, tm.iloc])
+ def indexer(self, request):
+ # Test iloc while we're here
+ return request.param
+
+ @pytest.fixture
+ def obj(self, series_with_simple_index, frame_or_series):
+ obj = series_with_simple_index
+ if frame_or_series is not Series:
+ obj = obj.to_frame()
+ return obj
+
+ def test_loc_iloc_getitem_ellipsis(self, obj, indexer):
+ result = indexer(obj)[...]
+ tm.assert_equal(result, obj)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_loc_iloc_getitem_leading_ellipses(self, series_with_simple_index, indexer):
+ obj = series_with_simple_index
+ key = 0 if (indexer is tm.iloc or len(obj) == 0) else obj.index[0]
+
+ if indexer is tm.loc and obj.index.inferred_type == "boolean":
+ # passing [False] will get interpreted as a boolean mask
+ # TODO: should it? unambiguous when lengths dont match?
+ return
+ if indexer is tm.loc and isinstance(obj.index, MultiIndex):
+ msg = "MultiIndex does not support indexing with Ellipsis"
+ with pytest.raises(NotImplementedError, match=msg):
+ result = indexer(obj)[..., [key]]
+
+ elif len(obj) != 0:
+ result = indexer(obj)[..., [key]]
+ expected = indexer(obj)[[key]]
+ tm.assert_series_equal(result, expected)
+
+ key2 = 0 if indexer is tm.iloc else obj.name
+ df = obj.to_frame()
+ result = indexer(df)[..., [key2]]
+ expected = indexer(df)[:, [key2]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_iloc_getitem_ellipses_only_one_ellipsis(self, obj, indexer):
+ # GH37750
+ key = 0 if (indexer is tm.iloc or len(obj) == 0) else obj.index[0]
+
+ with pytest.raises(IndexingError, match=_one_ellipsis_message):
+ indexer(obj)[..., ...]
+
+ with pytest.raises(IndexingError, match=_one_ellipsis_message):
+ indexer(obj)[..., [key], ...]
+
+ with pytest.raises(IndexingError, match=_one_ellipsis_message):
+ indexer(obj)[..., ..., key]
+
+ # one_ellipsis_message takes precedence over "Too many indexers"
+ # only when the first key is Ellipsis
+ with pytest.raises(IndexingError, match="Too many indexers"):
+ indexer(obj)[key, ..., ...]
+
+
+class TestLocWithMultiIndex:
+ @pytest.mark.parametrize(
+ "keys, expected",
+ [
+ (["b", "a"], [["b", "b", "a", "a"], [1, 2, 1, 2]]),
+ (["a", "b"], [["a", "a", "b", "b"], [1, 2, 1, 2]]),
+ ((["a", "b"], [1, 2]), [["a", "a", "b", "b"], [1, 2, 1, 2]]),
+ ((["a", "b"], [2, 1]), [["a", "a", "b", "b"], [2, 1, 2, 1]]),
+ ((["b", "a"], [2, 1]), [["b", "b", "a", "a"], [2, 1, 2, 1]]),
+ ((["b", "a"], [1, 2]), [["b", "b", "a", "a"], [1, 2, 1, 2]]),
+ ((["c", "a"], [2, 1]), [["c", "a", "a"], [1, 2, 1]]),
+ ],
+ )
+ @pytest.mark.parametrize("dim", ["index", "columns"])
+ def test_loc_getitem_multilevel_index_order(self, dim, keys, expected):
+ # GH#22797
+ # Try to respect order of keys given for MultiIndex.loc
+ kwargs = {dim: [["c", "a", "a", "b", "b"], [1, 1, 2, 1, 2]]}
+ df = DataFrame(np.arange(25).reshape(5, 5), **kwargs)
+ exp_index = MultiIndex.from_arrays(expected)
+ if dim == "index":
+ res = df.loc[keys, :]
+ tm.assert_index_equal(res.index, exp_index)
+ elif dim == "columns":
+ res = df.loc[:, keys]
+ tm.assert_index_equal(res.columns, exp_index)
+
+ def test_loc_preserve_names(self, multiindex_year_month_day_dataframe_random_data):
+ ymd = multiindex_year_month_day_dataframe_random_data
+
+ result = ymd.loc[2000]
+ result2 = ymd["A"].loc[2000]
+ assert result.index.names == ymd.index.names[1:]
+ assert result2.index.names == ymd.index.names[1:]
+
+ result = ymd.loc[2000, 2]
+ result2 = ymd["A"].loc[2000, 2]
+ assert result.index.name == ymd.index.names[2]
+ assert result2.index.name == ymd.index.names[2]
+
+ def test_loc_getitem_multiindex_nonunique_len_zero(self):
+ # GH#13691
+ mi = MultiIndex.from_product([[0], [1, 1]])
+ ser = Series(0, index=mi)
+
+ res = ser.loc[[]]
+
+ expected = ser[:0]
+ tm.assert_series_equal(res, expected)
+
+ res2 = ser.loc[ser.iloc[0:0]]
+ tm.assert_series_equal(res2, expected)
+
+ def test_loc_getitem_access_none_value_in_multiindex(self):
+ # GH#34318: test that you can access a None value using .loc
+ # through a Multiindex
+
+ ser = Series([None], MultiIndex.from_arrays([["Level1"], ["Level2"]]))
+ result = ser.loc[("Level1", "Level2")]
+ assert result is None
+
+ midx = MultiIndex.from_product([["Level1"], ["Level2_a", "Level2_b"]])
+ ser = Series([None] * len(midx), dtype=object, index=midx)
+ result = ser.loc[("Level1", "Level2_a")]
+ assert result is None
+
+ ser = Series([1] * len(midx), dtype=object, index=midx)
+ result = ser.loc[("Level1", "Level2_a")]
+ assert result == 1
+
+ def test_loc_setitem_multiindex_slice(self):
+ # GH 34870
+
+ index = MultiIndex.from_tuples(
+ zip(
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
+ ["one", "two", "one", "two", "one", "two", "one", "two"],
+ ),
+ names=["first", "second"],
+ )
+
+ result = Series([1, 1, 1, 1, 1, 1, 1, 1], index=index)
+ result.loc[("baz", "one"):("foo", "two")] = 100
+
+ expected = Series([1, 1, 100, 100, 100, 100, 1, 1], index=index)
+
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_getitem_slice_datetime_objs_with_datetimeindex(self):
+ times = date_range("2000-01-01", freq="10min", periods=100000)
+ ser = Series(range(100000), times)
+ result = ser.loc[datetime(1900, 1, 1) : datetime(2100, 1, 1)]
+ tm.assert_series_equal(result, ser)
+
+ def test_loc_getitem_datetime_string_with_datetimeindex(self):
+ # GH 16710
+ df = DataFrame(
+ {"a": range(10), "b": range(10)},
+ index=date_range("2010-01-01", "2010-01-10"),
+ )
+ result = df.loc[["2010-01-01", "2010-01-05"], ["a", "b"]]
+ expected = DataFrame(
+ {"a": [0, 4], "b": [0, 4]},
+ index=DatetimeIndex(["2010-01-01", "2010-01-05"]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_getitem_sorted_index_level_with_duplicates(self):
+ # GH#4516 sorting a MultiIndex with duplicates and multiple dtypes
+ mi = MultiIndex.from_tuples(
+ [
+ ("foo", "bar"),
+ ("foo", "bar"),
+ ("bah", "bam"),
+ ("bah", "bam"),
+ ("foo", "bar"),
+ ("bah", "bam"),
+ ],
+ names=["A", "B"],
+ )
+ df = DataFrame(
+ [
+ [1.0, 1],
+ [2.0, 2],
+ [3.0, 3],
+ [4.0, 4],
+ [5.0, 5],
+ [6.0, 6],
+ ],
+ index=mi,
+ columns=["C", "D"],
+ )
+ df = df.sort_index(level=0)
+
+ expected = DataFrame(
+ [[1.0, 1], [2.0, 2], [5.0, 5]], columns=["C", "D"], index=mi.take([0, 1, 4])
+ )
+
+ result = df.loc[("foo", "bar")]
+ tm.assert_frame_equal(result, expected)
+
+ def test_additional_element_to_categorical_series_loc(self):
+ # GH#47677
+ result = Series(["a", "b", "c"], dtype="category")
+ result.loc[3] = 0
+ expected = Series(["a", "b", "c", 0], dtype="object")
+ tm.assert_series_equal(result, expected)
+
+ def test_additional_categorical_element_loc(self):
+ # GH#47677
+ result = Series(["a", "b", "c"], dtype="category")
+ result.loc[3] = "a"
+ expected = Series(["a", "b", "c", "a"], dtype="category")
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_set_nan_in_categorical_series(self, any_numeric_ea_dtype):
+ # GH#47677
+ srs = Series(
+ [1, 2, 3],
+ dtype=CategoricalDtype(Index([1, 2, 3], dtype=any_numeric_ea_dtype)),
+ )
+ # enlarge
+ srs.loc[3] = np.nan
+ expected = Series(
+ [1, 2, 3, np.nan],
+ dtype=CategoricalDtype(Index([1, 2, 3], dtype=any_numeric_ea_dtype)),
+ )
+ tm.assert_series_equal(srs, expected)
+ # set into
+ srs.loc[1] = np.nan
+ expected = Series(
+ [1, np.nan, 3, np.nan],
+ dtype=CategoricalDtype(Index([1, 2, 3], dtype=any_numeric_ea_dtype)),
+ )
+ tm.assert_series_equal(srs, expected)
+
+ @pytest.mark.parametrize("na", (np.nan, pd.NA, None, pd.NaT))
+ def test_loc_consistency_series_enlarge_set_into(self, na):
+ # GH#47677
+ srs_enlarge = Series(["a", "b", "c"], dtype="category")
+ srs_enlarge.loc[3] = na
+
+ srs_setinto = Series(["a", "b", "c", "a"], dtype="category")
+ srs_setinto.loc[3] = na
+
+ tm.assert_series_equal(srs_enlarge, srs_setinto)
+ expected = Series(["a", "b", "c", na], dtype="category")
+ tm.assert_series_equal(srs_enlarge, expected)
+
+ def test_loc_getitem_preserves_index_level_category_dtype(self):
+ # GH#15166
+ df = DataFrame(
+ data=np.arange(2, 22, 2),
+ index=MultiIndex(
+ levels=[CategoricalIndex(["a", "b"]), range(10)],
+ codes=[[0] * 5 + [1] * 5, range(10)],
+ names=["Index1", "Index2"],
+ ),
+ )
+
+ expected = CategoricalIndex(
+ ["a", "b"],
+ categories=["a", "b"],
+ ordered=False,
+ name="Index1",
+ dtype="category",
+ )
+
+ result = df.index.levels[0]
+ tm.assert_index_equal(result, expected)
+
+ result = df.loc[["a"]].index.levels[0]
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("lt_value", [30, 10])
+ def test_loc_multiindex_levels_contain_values_not_in_index_anymore(self, lt_value):
+ # GH#41170
+ df = DataFrame({"a": [12, 23, 34, 45]}, index=[list("aabb"), [0, 1, 2, 3]])
+ with pytest.raises(KeyError, match=r"\['b'\] not in index"):
+ df.loc[df["a"] < lt_value, :].loc[["b"], :]
+
+ def test_loc_multiindex_null_slice_na_level(self):
+ # GH#42055
+ lev1 = np.array([np.nan, np.nan])
+ lev2 = ["bar", "baz"]
+ mi = MultiIndex.from_arrays([lev1, lev2])
+ ser = Series([0, 1], index=mi)
+ result = ser.loc[:, "bar"]
+
+ # TODO: should we have name="bar"?
+ expected = Series([0], index=[np.nan])
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_drops_level(self):
+ # Based on test_series_varied_multiindex_alignment, where
+ # this used to fail to drop the first level
+ mi = MultiIndex.from_product(
+ [list("ab"), list("xy"), [1, 2]], names=["ab", "xy", "num"]
+ )
+ ser = Series(range(8), index=mi)
+
+ loc_result = ser.loc["a", :, :]
+ expected = ser.index.droplevel(0)[:4]
+ tm.assert_index_equal(loc_result.index, expected)
+
+
+class TestLocSetitemWithExpansion:
+ @pytest.mark.slow
+ def test_loc_setitem_with_expansion_large_dataframe(self):
+ # GH#10692
+ result = DataFrame({"x": range(10**6)}, dtype="int64")
+ result.loc[len(result)] = len(result) + 1
+ expected = DataFrame({"x": range(10**6 + 1)}, dtype="int64")
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_setitem_empty_series(self):
+ # GH#5226
+
+ # partially set with an empty object series
+ ser = Series(dtype=object)
+ ser.loc[1] = 1
+ tm.assert_series_equal(ser, Series([1], index=[1]))
+ ser.loc[3] = 3
+ tm.assert_series_equal(ser, Series([1, 3], index=[1, 3]))
+
+ def test_loc_setitem_empty_series_float(self):
+ # GH#5226
+
+ # partially set with an empty object series
+ ser = Series(dtype=object)
+ ser.loc[1] = 1.0
+ tm.assert_series_equal(ser, Series([1.0], index=[1]))
+ ser.loc[3] = 3.0
+ tm.assert_series_equal(ser, Series([1.0, 3.0], index=[1, 3]))
+
+ def test_loc_setitem_empty_series_str_idx(self):
+ # GH#5226
+
+ # partially set with an empty object series
+ ser = Series(dtype=object)
+ ser.loc["foo"] = 1
+ tm.assert_series_equal(ser, Series([1], index=["foo"]))
+ ser.loc["bar"] = 3
+ tm.assert_series_equal(ser, Series([1, 3], index=["foo", "bar"]))
+ ser.loc[3] = 4
+ tm.assert_series_equal(ser, Series([1, 3, 4], index=["foo", "bar", 3]))
+
+ def test_loc_setitem_incremental_with_dst(self):
+ # GH#20724
+ base = datetime(2015, 11, 1, tzinfo=gettz("US/Pacific"))
+ idxs = [base + timedelta(seconds=i * 900) for i in range(16)]
+ result = Series([0], index=[idxs[0]])
+ for ts in idxs:
+ result.loc[ts] = 1
+ expected = Series(1, index=idxs)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "conv",
+ [
+ lambda x: x,
+ lambda x: x.to_datetime64(),
+ lambda x: x.to_pydatetime(),
+ lambda x: np.datetime64(x),
+ ],
+ ids=["self", "to_datetime64", "to_pydatetime", "np.datetime64"],
+ )
+ def test_loc_setitem_datetime_keys_cast(self, conv):
+ # GH#9516
+ dt1 = Timestamp("20130101 09:00:00")
+ dt2 = Timestamp("20130101 10:00:00")
+ df = DataFrame()
+ df.loc[conv(dt1), "one"] = 100
+ df.loc[conv(dt2), "one"] = 200
+
+ expected = DataFrame({"one": [100.0, 200.0]}, index=[dt1, dt2])
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_categorical_column_retains_dtype(self, ordered):
+ # GH16360
+ result = DataFrame({"A": [1]})
+ result.loc[:, "B"] = Categorical(["b"], ordered=ordered)
+ expected = DataFrame({"A": [1], "B": Categorical(["b"], ordered=ordered)})
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_setitem_with_expansion_and_existing_dst(self):
+ # GH#18308
+ start = Timestamp("2017-10-29 00:00:00+0200", tz="Europe/Madrid")
+ end = Timestamp("2017-10-29 03:00:00+0100", tz="Europe/Madrid")
+ ts = Timestamp("2016-10-10 03:00:00", tz="Europe/Madrid")
+ idx = date_range(start, end, inclusive="left", freq="H")
+ assert ts not in idx # i.e. result.loc setitem is with-expansion
+
+ result = DataFrame(index=idx, columns=["value"])
+ result.loc[ts, "value"] = 12
+ expected = DataFrame(
+ [np.nan] * len(idx) + [12],
+ index=idx.append(DatetimeIndex([ts])),
+ columns=["value"],
+ dtype=object,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_setitem_with_expansion(self):
+ # indexing - setting an element
+ df = DataFrame(
+ data=to_datetime(["2015-03-30 20:12:32", "2015-03-12 00:11:11"]),
+ columns=["time"],
+ )
+ df["new_col"] = ["new", "old"]
+ df.time = df.set_index("time").index.tz_localize("UTC")
+ v = df[df.new_col == "new"].set_index("time").index.tz_convert("US/Pacific")
+
+ # pre-2.0 trying to set a single element on a part of a different
+ # timezone converted to object; in 2.0 it retains dtype
+ df2 = df.copy()
+ df2.loc[df2.new_col == "new", "time"] = v
+
+ expected = Series([v[0].tz_convert("UTC"), df.loc[1, "time"]], name="time")
+ tm.assert_series_equal(df2.time, expected)
+
+ v = df.loc[df.new_col == "new", "time"] + Timedelta("1s")
+ df.loc[df.new_col == "new", "time"] = v
+ tm.assert_series_equal(df.loc[df.new_col == "new", "time"], v)
+
+ def test_loc_setitem_with_expansion_inf_upcast_empty(self):
+ # Test with np.inf in columns
+ df = DataFrame()
+ df.loc[0, 0] = 1
+ df.loc[1, 1] = 2
+ df.loc[0, np.inf] = 3
+
+ result = df.columns
+ expected = Index([0, 1, np.inf], dtype=np.float64)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.filterwarnings("ignore:indexing past lexsort depth")
+ def test_loc_setitem_with_expansion_nonunique_index(self, index):
+ # GH#40096
+ if not len(index):
+ pytest.skip("Not relevant for empty Index")
+
+ index = index.repeat(2) # ensure non-unique
+ N = len(index)
+ arr = np.arange(N).astype(np.int64)
+
+ orig = DataFrame(arr, index=index, columns=[0])
+
+ # key that will requiring object-dtype casting in the index
+ key = "kapow"
+ assert key not in index # otherwise test is invalid
+ # TODO: using a tuple key breaks here in many cases
+
+ exp_index = index.insert(len(index), key)
+ if isinstance(index, MultiIndex):
+ assert exp_index[-1][0] == key
+ else:
+ assert exp_index[-1] == key
+ exp_data = np.arange(N + 1).astype(np.float64)
+ expected = DataFrame(exp_data, index=exp_index, columns=[0])
+
+ # Add new row, but no new columns
+ df = orig.copy()
+ df.loc[key, 0] = N
+ tm.assert_frame_equal(df, expected)
+
+ # add new row on a Series
+ ser = orig.copy()[0]
+ ser.loc[key] = N
+ # the series machinery lets us preserve int dtype instead of float
+ expected = expected[0].astype(np.int64)
+ tm.assert_series_equal(ser, expected)
+
+ # add new row and new column
+ df = orig.copy()
+ df.loc[key, 1] = N
+ expected = DataFrame(
+ {0: list(arr) + [np.nan], 1: [np.nan] * N + [float(N)]},
+ index=exp_index,
+ )
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize(
+ "dtype", ["Int32", "Int64", "UInt32", "UInt64", "Float32", "Float64"]
+ )
+ def test_loc_setitem_with_expansion_preserves_nullable_int(self, dtype):
+ # GH#42099
+ ser = Series([0, 1, 2, 3], dtype=dtype)
+ df = DataFrame({"data": ser})
+
+ result = DataFrame(index=df.index)
+ result.loc[df.index, "data"] = ser
+
+ tm.assert_frame_equal(result, df)
+
+ result = DataFrame(index=df.index)
+ result.loc[df.index, "data"] = ser._values
+ tm.assert_frame_equal(result, df)
+
+
+class TestLocCallable:
+ def test_frame_loc_getitem_callable(self):
+ # GH#11485
+ df = DataFrame({"A": [1, 2, 3, 4], "B": list("aabb"), "C": [1, 2, 3, 4]})
+ # iloc cannot use boolean Series (see GH3635)
+
+ # return bool indexer
+ res = df.loc[lambda x: x.A > 2]
+ tm.assert_frame_equal(res, df.loc[df.A > 2])
+
+ res = df.loc[lambda x: x.B == "b", :]
+ tm.assert_frame_equal(res, df.loc[df.B == "b", :])
+
+ res = df.loc[lambda x: x.A > 2, lambda x: x.columns == "B"]
+ tm.assert_frame_equal(res, df.loc[df.A > 2, [False, True, False]])
+
+ res = df.loc[lambda x: x.A > 2, lambda x: "B"]
+ tm.assert_series_equal(res, df.loc[df.A > 2, "B"])
+
+ res = df.loc[lambda x: x.A > 2, lambda x: ["A", "B"]]
+ tm.assert_frame_equal(res, df.loc[df.A > 2, ["A", "B"]])
+
+ res = df.loc[lambda x: x.A == 2, lambda x: ["A", "B"]]
+ tm.assert_frame_equal(res, df.loc[df.A == 2, ["A", "B"]])
+
+ # scalar
+ res = df.loc[lambda x: 1, lambda x: "A"]
+ assert res == df.loc[1, "A"]
+
+ def test_frame_loc_getitem_callable_mixture(self):
+ # GH#11485
+ df = DataFrame({"A": [1, 2, 3, 4], "B": list("aabb"), "C": [1, 2, 3, 4]})
+
+ res = df.loc[lambda x: x.A > 2, ["A", "B"]]
+ tm.assert_frame_equal(res, df.loc[df.A > 2, ["A", "B"]])
+
+ res = df.loc[[2, 3], lambda x: ["A", "B"]]
+ tm.assert_frame_equal(res, df.loc[[2, 3], ["A", "B"]])
+
+ res = df.loc[3, lambda x: ["A", "B"]]
+ tm.assert_series_equal(res, df.loc[3, ["A", "B"]])
+
+ def test_frame_loc_getitem_callable_labels(self):
+ # GH#11485
+ df = DataFrame({"X": [1, 2, 3, 4], "Y": list("aabb")}, index=list("ABCD"))
+
+ # return label
+ res = df.loc[lambda x: ["A", "C"]]
+ tm.assert_frame_equal(res, df.loc[["A", "C"]])
+
+ res = df.loc[lambda x: ["A", "C"], :]
+ tm.assert_frame_equal(res, df.loc[["A", "C"], :])
+
+ res = df.loc[lambda x: ["A", "C"], lambda x: "X"]
+ tm.assert_series_equal(res, df.loc[["A", "C"], "X"])
+
+ res = df.loc[lambda x: ["A", "C"], lambda x: ["X"]]
+ tm.assert_frame_equal(res, df.loc[["A", "C"], ["X"]])
+
+ # mixture
+ res = df.loc[["A", "C"], lambda x: "X"]
+ tm.assert_series_equal(res, df.loc[["A", "C"], "X"])
+
+ res = df.loc[["A", "C"], lambda x: ["X"]]
+ tm.assert_frame_equal(res, df.loc[["A", "C"], ["X"]])
+
+ res = df.loc[lambda x: ["A", "C"], "X"]
+ tm.assert_series_equal(res, df.loc[["A", "C"], "X"])
+
+ res = df.loc[lambda x: ["A", "C"], ["X"]]
+ tm.assert_frame_equal(res, df.loc[["A", "C"], ["X"]])
+
+ def test_frame_loc_setitem_callable(self):
+ # GH#11485
+ df = DataFrame({"X": [1, 2, 3, 4], "Y": list("aabb")}, index=list("ABCD"))
+
+ # return label
+ res = df.copy()
+ res.loc[lambda x: ["A", "C"]] = -20
+ exp = df.copy()
+ exp.loc[["A", "C"]] = -20
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.loc[lambda x: ["A", "C"], :] = 20
+ exp = df.copy()
+ exp.loc[["A", "C"], :] = 20
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.loc[lambda x: ["A", "C"], lambda x: "X"] = -1
+ exp = df.copy()
+ exp.loc[["A", "C"], "X"] = -1
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.loc[lambda x: ["A", "C"], lambda x: ["X"]] = [5, 10]
+ exp = df.copy()
+ exp.loc[["A", "C"], ["X"]] = [5, 10]
+ tm.assert_frame_equal(res, exp)
+
+ # mixture
+ res = df.copy()
+ res.loc[["A", "C"], lambda x: "X"] = np.array([-1, -2])
+ exp = df.copy()
+ exp.loc[["A", "C"], "X"] = np.array([-1, -2])
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.loc[["A", "C"], lambda x: ["X"]] = 10
+ exp = df.copy()
+ exp.loc[["A", "C"], ["X"]] = 10
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.loc[lambda x: ["A", "C"], "X"] = -2
+ exp = df.copy()
+ exp.loc[["A", "C"], "X"] = -2
+ tm.assert_frame_equal(res, exp)
+
+ res = df.copy()
+ res.loc[lambda x: ["A", "C"], ["X"]] = -4
+ exp = df.copy()
+ exp.loc[["A", "C"], ["X"]] = -4
+ tm.assert_frame_equal(res, exp)
+
+
+class TestPartialStringSlicing:
+ def test_loc_getitem_partial_string_slicing_datetimeindex(self):
+ # GH#35509
+ df = DataFrame(
+ {"col1": ["a", "b", "c"], "col2": [1, 2, 3]},
+ index=to_datetime(["2020-08-01", "2020-07-02", "2020-08-05"]),
+ )
+ expected = DataFrame(
+ {"col1": ["a", "c"], "col2": [1, 3]},
+ index=to_datetime(["2020-08-01", "2020-08-05"]),
+ )
+ result = df.loc["2020-08"]
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_getitem_partial_string_slicing_with_periodindex(self):
+ pi = pd.period_range(start="2017-01-01", end="2018-01-01", freq="M")
+ ser = pi.to_series()
+ result = ser.loc[:"2017-12"]
+ expected = ser.iloc[:-1]
+
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_getitem_partial_string_slicing_with_timedeltaindex(self):
+ ix = timedelta_range(start="1 day", end="2 days", freq="1H")
+ ser = ix.to_series()
+ result = ser.loc[:"1 days"]
+ expected = ser.iloc[:-1]
+
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_getitem_str_timedeltaindex(self):
+ # GH#16896
+ df = DataFrame({"x": range(3)}, index=to_timedelta(range(3), unit="days"))
+ expected = df.iloc[0]
+ sliced = df.loc["0 days"]
+ tm.assert_series_equal(sliced, expected)
+
+ @pytest.mark.parametrize("indexer_end", [None, "2020-01-02 23:59:59.999999999"])
+ def test_loc_getitem_partial_slice_non_monotonicity(
+ self, tz_aware_fixture, indexer_end, frame_or_series
+ ):
+ # GH#33146
+ obj = frame_or_series(
+ [1] * 5,
+ index=DatetimeIndex(
+ [
+ Timestamp("2019-12-30"),
+ Timestamp("2020-01-01"),
+ Timestamp("2019-12-25"),
+ Timestamp("2020-01-02 23:59:59.999999999"),
+ Timestamp("2019-12-19"),
+ ],
+ tz=tz_aware_fixture,
+ ),
+ )
+ expected = frame_or_series(
+ [1] * 2,
+ index=DatetimeIndex(
+ [
+ Timestamp("2020-01-01"),
+ Timestamp("2020-01-02 23:59:59.999999999"),
+ ],
+ tz=tz_aware_fixture,
+ ),
+ )
+ indexer = slice("2020-01-01", indexer_end)
+
+ result = obj[indexer]
+ tm.assert_equal(result, expected)
+
+ result = obj.loc[indexer]
+ tm.assert_equal(result, expected)
+
+
+class TestLabelSlicing:
+ def test_loc_getitem_slicing_datetimes_frame(self):
+ # GH#7523
+
+ # unique
+ df_unique = DataFrame(
+ np.arange(4.0, dtype="float64"),
+ index=[datetime(2001, 1, i, 10, 00) for i in [1, 2, 3, 4]],
+ )
+
+ # duplicates
+ df_dups = DataFrame(
+ np.arange(5.0, dtype="float64"),
+ index=[datetime(2001, 1, i, 10, 00) for i in [1, 2, 2, 3, 4]],
+ )
+
+ for df in [df_unique, df_dups]:
+ result = df.loc[datetime(2001, 1, 1, 10) :]
+ tm.assert_frame_equal(result, df)
+ result = df.loc[: datetime(2001, 1, 4, 10)]
+ tm.assert_frame_equal(result, df)
+ result = df.loc[datetime(2001, 1, 1, 10) : datetime(2001, 1, 4, 10)]
+ tm.assert_frame_equal(result, df)
+
+ result = df.loc[datetime(2001, 1, 1, 11) :]
+ expected = df.iloc[1:]
+ tm.assert_frame_equal(result, expected)
+ result = df.loc["20010101 11":]
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_getitem_label_slice_across_dst(self):
+ # GH#21846
+ idx = date_range(
+ "2017-10-29 01:30:00", tz="Europe/Berlin", periods=5, freq="30 min"
+ )
+ series2 = Series([0, 1, 2, 3, 4], index=idx)
+
+ t_1 = Timestamp("2017-10-29 02:30:00+02:00", tz="Europe/Berlin")
+ t_2 = Timestamp("2017-10-29 02:00:00+01:00", tz="Europe/Berlin")
+ result = series2.loc[t_1:t_2]
+ expected = Series([2, 3], index=idx[2:4])
+ tm.assert_series_equal(result, expected)
+
+ result = series2[t_1]
+ expected = 2
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ pd.period_range(start="2017-01-01", end="2018-01-01", freq="M"),
+ timedelta_range(start="1 day", end="2 days", freq="1H"),
+ ],
+ )
+ def test_loc_getitem_label_slice_period_timedelta(self, index):
+ ser = index.to_series()
+ result = ser.loc[: index[-2]]
+ expected = ser.iloc[:-1]
+
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_getitem_slice_floats_inexact(self):
+ index = [52195.504153, 52196.303147, 52198.369883]
+ df = DataFrame(np.random.default_rng(2).random((3, 2)), index=index)
+
+ s1 = df.loc[52195.1:52196.5]
+ assert len(s1) == 2
+
+ s1 = df.loc[52195.1:52196.6]
+ assert len(s1) == 2
+
+ s1 = df.loc[52195.1:52198.9]
+ assert len(s1) == 3
+
+ def test_loc_getitem_float_slice_floatindex(self, float_numpy_dtype):
+ dtype = float_numpy_dtype
+ ser = Series(
+ np.random.default_rng(2).random(10), index=np.arange(10, 20, dtype=dtype)
+ )
+
+ assert len(ser.loc[12.0:]) == 8
+ assert len(ser.loc[12.5:]) == 7
+
+ idx = np.arange(10, 20, dtype=dtype)
+ idx[2] = 12.2
+ ser.index = idx
+ assert len(ser.loc[12.0:]) == 8
+ assert len(ser.loc[12.5:]) == 7
+
+ @pytest.mark.parametrize(
+ "start,stop, expected_slice",
+ [
+ [np.timedelta64(0, "ns"), None, slice(0, 11)],
+ [np.timedelta64(1, "D"), np.timedelta64(6, "D"), slice(1, 7)],
+ [None, np.timedelta64(4, "D"), slice(0, 5)],
+ ],
+ )
+ def test_loc_getitem_slice_label_td64obj(self, start, stop, expected_slice):
+ # GH#20393
+ ser = Series(range(11), timedelta_range("0 days", "10 days"))
+ result = ser.loc[slice(start, stop)]
+ expected = ser.iloc[expected_slice]
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("start", ["2018", "2020"])
+ def test_loc_getitem_slice_unordered_dt_index(self, frame_or_series, start):
+ obj = frame_or_series(
+ [1, 2, 3],
+ index=[Timestamp("2016"), Timestamp("2019"), Timestamp("2017")],
+ )
+ with pytest.raises(
+ KeyError, match="Value based partial slicing on non-monotonic"
+ ):
+ obj.loc[start:"2022"]
+
+ @pytest.mark.parametrize("value", [1, 1.5])
+ def test_loc_getitem_slice_labels_int_in_object_index(self, frame_or_series, value):
+ # GH: 26491
+ obj = frame_or_series(range(4), index=[value, "first", 2, "third"])
+ result = obj.loc[value:"third"]
+ expected = frame_or_series(range(4), index=[value, "first", 2, "third"])
+ tm.assert_equal(result, expected)
+
+ def test_loc_getitem_slice_columns_mixed_dtype(self):
+ # GH: 20975
+ df = DataFrame({"test": 1, 1: 2, 2: 3}, index=[0])
+ expected = DataFrame(
+ data=[[2, 3]], index=[0], columns=Index([1, 2], dtype=object)
+ )
+ tm.assert_frame_equal(df.loc[:, 1:], expected)
+
+
+class TestLocBooleanLabelsAndSlices:
+ @pytest.mark.parametrize("bool_value", [True, False])
+ def test_loc_bool_incompatible_index_raises(
+ self, index, frame_or_series, bool_value
+ ):
+ # GH20432
+ message = f"{bool_value}: boolean label can not be used without a boolean index"
+ if index.inferred_type != "boolean":
+ obj = frame_or_series(index=index, dtype="object")
+ with pytest.raises(KeyError, match=message):
+ obj.loc[bool_value]
+
+ @pytest.mark.parametrize("bool_value", [True, False])
+ def test_loc_bool_should_not_raise(self, frame_or_series, bool_value):
+ obj = frame_or_series(
+ index=Index([True, False], dtype="boolean"), dtype="object"
+ )
+ obj.loc[bool_value]
+
+ def test_loc_bool_slice_raises(self, index, frame_or_series):
+ # GH20432
+ message = (
+ r"slice\(True, False, None\): boolean values can not be used in a slice"
+ )
+ obj = frame_or_series(index=index, dtype="object")
+ with pytest.raises(TypeError, match=message):
+ obj.loc[True:False]
+
+
+class TestLocBooleanMask:
+ def test_loc_setitem_bool_mask_timedeltaindex(self):
+ # GH#14946
+ df = DataFrame({"x": range(10)})
+ df.index = to_timedelta(range(10), unit="s")
+ conditions = [df["x"] > 3, df["x"] == 3, df["x"] < 3]
+ expected_data = [
+ [0, 1, 2, 3, 10, 10, 10, 10, 10, 10],
+ [0, 1, 2, 10, 4, 5, 6, 7, 8, 9],
+ [10, 10, 10, 3, 4, 5, 6, 7, 8, 9],
+ ]
+ for cond, data in zip(conditions, expected_data):
+ result = df.copy()
+ result.loc[cond, "x"] = 10
+
+ expected = DataFrame(
+ data,
+ index=to_timedelta(range(10), unit="s"),
+ columns=["x"],
+ dtype="int64",
+ )
+ tm.assert_frame_equal(expected, result)
+
+ @pytest.mark.parametrize("tz", [None, "UTC"])
+ def test_loc_setitem_mask_with_datetimeindex_tz(self, tz):
+ # GH#16889
+ # support .loc with alignment and tz-aware DatetimeIndex
+ mask = np.array([True, False, True, False])
+
+ idx = date_range("20010101", periods=4, tz=tz)
+ df = DataFrame({"a": np.arange(4)}, index=idx).astype("float64")
+
+ result = df.copy()
+ result.loc[mask, :] = df.loc[mask, :]
+ tm.assert_frame_equal(result, df)
+
+ result = df.copy()
+ result.loc[mask] = df.loc[mask]
+ tm.assert_frame_equal(result, df)
+
+ def test_loc_setitem_mask_and_label_with_datetimeindex(self):
+ # GH#9478
+ # a datetimeindex alignment issue with partial setting
+ df = DataFrame(
+ np.arange(6.0).reshape(3, 2),
+ columns=list("AB"),
+ index=date_range("1/1/2000", periods=3, freq="1H"),
+ )
+ expected = df.copy()
+ expected["C"] = [expected.index[0]] + [pd.NaT, pd.NaT]
+
+ mask = df.A < 1
+ df.loc[mask, "C"] = df.loc[mask].index
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_mask_td64_series_value(self):
+ # GH#23462 key list of bools, value is a Series
+ td1 = Timedelta(0)
+ td2 = Timedelta(28767471428571405)
+ df = DataFrame({"col": Series([td1, td2])})
+ df_copy = df.copy()
+ ser = Series([td1])
+
+ expected = df["col"].iloc[1]._value
+ df.loc[[True, False]] = ser
+ result = df["col"].iloc[1]._value
+
+ assert expected == result
+ tm.assert_frame_equal(df, df_copy)
+
+ @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values
+ def test_loc_setitem_boolean_and_column(self, float_frame):
+ expected = float_frame.copy()
+ mask = float_frame["A"] > 0
+
+ float_frame.loc[mask, "B"] = 0
+
+ values = expected.values.copy()
+ values[mask.values, 1] = 0
+ expected = DataFrame(values, index=expected.index, columns=expected.columns)
+ tm.assert_frame_equal(float_frame, expected)
+
+ def test_loc_setitem_ndframe_values_alignment(self, using_copy_on_write):
+ # GH#45501
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df.loc[[False, False, True], ["a"]] = DataFrame(
+ {"a": [10, 20, 30]}, index=[2, 1, 0]
+ )
+
+ expected = DataFrame({"a": [1, 2, 10], "b": [4, 5, 6]})
+ tm.assert_frame_equal(df, expected)
+
+ # same thing with Series RHS
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df.loc[[False, False, True], ["a"]] = Series([10, 11, 12], index=[2, 1, 0])
+ tm.assert_frame_equal(df, expected)
+
+ # same thing but setting "a" instead of ["a"]
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df.loc[[False, False, True], "a"] = Series([10, 11, 12], index=[2, 1, 0])
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ df_orig = df.copy()
+ ser = df["a"]
+ ser.loc[[False, False, True]] = Series([10, 11, 12], index=[2, 1, 0])
+ if using_copy_on_write:
+ tm.assert_frame_equal(df, df_orig)
+ else:
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_indexer_empty_broadcast(self):
+ # GH#51450
+ df = DataFrame({"a": [], "b": []}, dtype=object)
+ expected = df.copy()
+ df.loc[np.array([], dtype=np.bool_), ["a"]] = df["a"]
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_indexer_all_false_broadcast(self):
+ # GH#51450
+ df = DataFrame({"a": ["x"], "b": ["y"]}, dtype=object)
+ expected = df.copy()
+ df.loc[np.array([False], dtype=np.bool_), ["a"]] = df["b"]
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_indexer_length_one(self):
+ # GH#51435
+ df = DataFrame({"a": ["x"], "b": ["y"]}, dtype=object)
+ expected = DataFrame({"a": ["y"], "b": ["y"]}, dtype=object)
+ df.loc[np.array([True], dtype=np.bool_), ["a"]] = df["b"]
+ tm.assert_frame_equal(df, expected)
+
+
+class TestLocListlike:
+ @pytest.mark.parametrize("box", [lambda x: x, np.asarray, list])
+ def test_loc_getitem_list_of_labels_categoricalindex_with_na(self, box):
+ # passing a list can include valid categories _or_ NA values
+ ci = CategoricalIndex(["A", "B", np.nan])
+ ser = Series(range(3), index=ci)
+
+ result = ser.loc[box(ci)]
+ tm.assert_series_equal(result, ser)
+
+ result = ser[box(ci)]
+ tm.assert_series_equal(result, ser)
+
+ result = ser.to_frame().loc[box(ci)]
+ tm.assert_frame_equal(result, ser.to_frame())
+
+ ser2 = ser[:-1]
+ ci2 = ci[1:]
+ # but if there are no NAs present, this should raise KeyError
+ msg = "not in index"
+ with pytest.raises(KeyError, match=msg):
+ ser2.loc[box(ci2)]
+
+ with pytest.raises(KeyError, match=msg):
+ ser2[box(ci2)]
+
+ with pytest.raises(KeyError, match=msg):
+ ser2.to_frame().loc[box(ci2)]
+
+ def test_loc_getitem_series_label_list_missing_values(self):
+ # gh-11428
+ key = np.array(
+ ["2001-01-04", "2001-01-02", "2001-01-04", "2001-01-14"], dtype="datetime64"
+ )
+ ser = Series([2, 5, 8, 11], date_range("2001-01-01", freq="D", periods=4))
+ with pytest.raises(KeyError, match="not in index"):
+ ser.loc[key]
+
+ def test_loc_getitem_series_label_list_missing_integer_values(self):
+ # GH: 25927
+ ser = Series(
+ index=np.array([9730701000001104, 10049011000001109]),
+ data=np.array([999000011000001104, 999000011000001104]),
+ )
+ with pytest.raises(KeyError, match="not in index"):
+ ser.loc[np.array([9730701000001104, 10047311000001102])]
+
+ @pytest.mark.parametrize("to_period", [True, False])
+ def test_loc_getitem_listlike_of_datetimelike_keys(self, to_period):
+ # GH#11497
+
+ idx = date_range("2011-01-01", "2011-01-02", freq="D", name="idx")
+ if to_period:
+ idx = idx.to_period("D")
+ ser = Series([0.1, 0.2], index=idx, name="s")
+
+ keys = [Timestamp("2011-01-01"), Timestamp("2011-01-02")]
+ if to_period:
+ keys = [x.to_period("D") for x in keys]
+ result = ser.loc[keys]
+ exp = Series([0.1, 0.2], index=idx, name="s")
+ if not to_period:
+ exp.index = exp.index._with_freq(None)
+ tm.assert_series_equal(result, exp, check_index_type=True)
+
+ keys = [
+ Timestamp("2011-01-02"),
+ Timestamp("2011-01-02"),
+ Timestamp("2011-01-01"),
+ ]
+ if to_period:
+ keys = [x.to_period("D") for x in keys]
+ exp = Series(
+ [0.2, 0.2, 0.1], index=Index(keys, name="idx", dtype=idx.dtype), name="s"
+ )
+ result = ser.loc[keys]
+ tm.assert_series_equal(result, exp, check_index_type=True)
+
+ keys = [
+ Timestamp("2011-01-03"),
+ Timestamp("2011-01-02"),
+ Timestamp("2011-01-03"),
+ ]
+ if to_period:
+ keys = [x.to_period("D") for x in keys]
+
+ with pytest.raises(KeyError, match="not in index"):
+ ser.loc[keys]
+
+ def test_loc_named_index(self):
+ # GH 42790
+ df = DataFrame(
+ [[1, 2], [4, 5], [7, 8]],
+ index=["cobra", "viper", "sidewinder"],
+ columns=["max_speed", "shield"],
+ )
+ expected = df.iloc[:2]
+ expected.index.name = "foo"
+ result = df.loc[Index(["cobra", "viper"], name="foo")]
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "columns, column_key, expected_columns",
+ [
+ ([2011, 2012, 2013], [2011, 2012], [0, 1]),
+ ([2011, 2012, "All"], [2011, 2012], [0, 1]),
+ ([2011, 2012, "All"], [2011, "All"], [0, 2]),
+ ],
+)
+def test_loc_getitem_label_list_integer_labels(columns, column_key, expected_columns):
+ # gh-14836
+ df = DataFrame(
+ np.random.default_rng(2).random((3, 3)), columns=columns, index=list("ABC")
+ )
+ expected = df.iloc[:, expected_columns]
+ result = df.loc[["A", "B", "C"], column_key]
+
+ tm.assert_frame_equal(result, expected, check_column_type=True)
+
+
+def test_loc_setitem_float_intindex():
+ # GH 8720
+ rand_data = np.random.default_rng(2).standard_normal((8, 4))
+ result = DataFrame(rand_data)
+ result.loc[:, 0.5] = np.nan
+ expected_data = np.hstack((rand_data, np.array([np.nan] * 8).reshape(8, 1)))
+ expected = DataFrame(expected_data, columns=[0.0, 1.0, 2.0, 3.0, 0.5])
+ tm.assert_frame_equal(result, expected)
+
+ result = DataFrame(rand_data)
+ result.loc[:, 0.5] = np.nan
+ tm.assert_frame_equal(result, expected)
+
+
+def test_loc_axis_1_slice():
+ # GH 10586
+ cols = [(yr, m) for yr in [2014, 2015] for m in [7, 8, 9, 10]]
+ df = DataFrame(
+ np.ones((10, 8)),
+ index=tuple("ABCDEFGHIJ"),
+ columns=MultiIndex.from_tuples(cols),
+ )
+ result = df.loc(axis=1)[(2014, 9):(2015, 8)]
+ expected = DataFrame(
+ np.ones((10, 4)),
+ index=tuple("ABCDEFGHIJ"),
+ columns=MultiIndex.from_tuples([(2014, 9), (2014, 10), (2015, 7), (2015, 8)]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_loc_set_dataframe_multiindex():
+ # GH 14592
+ expected = DataFrame(
+ "a", index=range(2), columns=MultiIndex.from_product([range(2), range(2)])
+ )
+ result = expected.copy()
+ result.loc[0, [(0, 1)]] = result.loc[0, [(0, 1)]]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_loc_mixed_int_float():
+ # GH#19456
+ ser = Series(range(2), Index([1, 2.0], dtype=object))
+
+ result = ser.loc[1]
+ assert result == 0
+
+
+def test_loc_with_positional_slice_raises():
+ # GH#31840
+ ser = Series(range(4), index=["A", "B", "C", "D"])
+
+ with pytest.raises(TypeError, match="Slicing a positional slice with .loc"):
+ ser.loc[:3] = 2
+
+
+def test_loc_slice_disallows_positional():
+ # GH#16121, GH#24612, GH#31810
+ dti = date_range("2016-01-01", periods=3)
+ df = DataFrame(np.random.default_rng(2).random((3, 2)), index=dti)
+
+ ser = df[0]
+
+ msg = (
+ "cannot do slice indexing on DatetimeIndex with these "
+ r"indexers \[1\] of type int"
+ )
+
+ for obj in [df, ser]:
+ with pytest.raises(TypeError, match=msg):
+ obj.loc[1:3]
+
+ with pytest.raises(TypeError, match="Slicing a positional slice with .loc"):
+ # GH#31840 enforce incorrect behavior
+ obj.loc[1:3] = 1
+
+ with pytest.raises(TypeError, match=msg):
+ df.loc[1:3, 1]
+
+ with pytest.raises(TypeError, match="Slicing a positional slice with .loc"):
+ # GH#31840 enforce incorrect behavior
+ df.loc[1:3, 1] = 2
+
+
+def test_loc_datetimelike_mismatched_dtypes():
+ # GH#32650 dont mix and match datetime/timedelta/period dtypes
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)),
+ columns=["a", "b", "c"],
+ index=date_range("2012", freq="H", periods=5),
+ )
+ # create dataframe with non-unique DatetimeIndex
+ df = df.iloc[[0, 2, 2, 3]].copy()
+
+ dti = df.index
+ tdi = pd.TimedeltaIndex(dti.asi8) # matching i8 values
+
+ msg = r"None of \[TimedeltaIndex.* are in the \[index\]"
+ with pytest.raises(KeyError, match=msg):
+ df.loc[tdi]
+
+ with pytest.raises(KeyError, match=msg):
+ df["a"].loc[tdi]
+
+
+def test_loc_with_period_index_indexer():
+ # GH#4125
+ idx = pd.period_range("2002-01", "2003-12", freq="M")
+ df = DataFrame(np.random.default_rng(2).standard_normal((24, 10)), index=idx)
+ tm.assert_frame_equal(df, df.loc[idx])
+ tm.assert_frame_equal(df, df.loc[list(idx)])
+ tm.assert_frame_equal(df, df.loc[list(idx)])
+ tm.assert_frame_equal(df.iloc[0:5], df.loc[idx[0:5]])
+ tm.assert_frame_equal(df, df.loc[list(idx)])
+
+
+def test_loc_setitem_multiindex_timestamp():
+ # GH#13831
+ vals = np.random.default_rng(2).standard_normal((8, 6))
+ idx = date_range("1/1/2000", periods=8)
+ cols = ["A", "B", "C", "D", "E", "F"]
+ exp = DataFrame(vals, index=idx, columns=cols)
+ exp.loc[exp.index[1], ("A", "B")] = np.nan
+ vals[1][0:2] = np.nan
+ res = DataFrame(vals, index=idx, columns=cols)
+ tm.assert_frame_equal(res, exp)
+
+
+def test_loc_getitem_multiindex_tuple_level():
+ # GH#27591
+ lev1 = ["a", "b", "c"]
+ lev2 = [(0, 1), (1, 0)]
+ lev3 = [0, 1]
+ cols = MultiIndex.from_product([lev1, lev2, lev3], names=["x", "y", "z"])
+ df = DataFrame(6, index=range(5), columns=cols)
+
+ # the lev2[0] here should be treated as a single label, not as a sequence
+ # of labels
+ result = df.loc[:, (lev1[0], lev2[0], lev3[0])]
+
+ # TODO: i think this actually should drop levels
+ expected = df.iloc[:, :1]
+ tm.assert_frame_equal(result, expected)
+
+ alt = df.xs((lev1[0], lev2[0], lev3[0]), level=[0, 1, 2], axis=1)
+ tm.assert_frame_equal(alt, expected)
+
+ # same thing on a Series
+ ser = df.iloc[0]
+ expected2 = ser.iloc[:1]
+
+ alt2 = ser.xs((lev1[0], lev2[0], lev3[0]), level=[0, 1, 2], axis=0)
+ tm.assert_series_equal(alt2, expected2)
+
+ result2 = ser.loc[lev1[0], lev2[0], lev3[0]]
+ assert result2 == 6
+
+
+def test_loc_getitem_nullable_index_with_duplicates():
+ # GH#34497
+ df = DataFrame(
+ data=np.array([[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, np.nan, np.nan]]).T,
+ columns=["a", "b", "c"],
+ dtype="Int64",
+ )
+ df2 = df.set_index("c")
+ assert df2.index.dtype == "Int64"
+
+ res = df2.loc[1]
+ expected = Series([1, 5], index=df2.columns, dtype="Int64", name=1)
+ tm.assert_series_equal(res, expected)
+
+ # pd.NA and duplicates in an object-dtype Index
+ df2.index = df2.index.astype(object)
+ res = df2.loc[1]
+ tm.assert_series_equal(res, expected)
+
+
+@pytest.mark.parametrize("value", [300, np.uint16(300), np.int16(300)])
+def test_loc_setitem_uint8_upcast(value):
+ # GH#26049
+
+ df = DataFrame([1, 2, 3, 4], columns=["col1"], dtype="uint8")
+ with tm.assert_produces_warning(FutureWarning, match="item of incompatible dtype"):
+ df.loc[2, "col1"] = value # value that can't be held in uint8
+
+ expected = DataFrame([1, 2, 300, 4], columns=["col1"], dtype="uint16")
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.parametrize(
+ "fill_val,exp_dtype",
+ [
+ (Timestamp("2022-01-06"), "datetime64[ns]"),
+ (Timestamp("2022-01-07", tz="US/Eastern"), "datetime64[ns, US/Eastern]"),
+ ],
+)
+def test_loc_setitem_using_datetimelike_str_as_index(fill_val, exp_dtype):
+ data = ["2022-01-02", "2022-01-03", "2022-01-04", fill_val.date()]
+ index = DatetimeIndex(data, tz=fill_val.tz, dtype=exp_dtype)
+ df = DataFrame([10, 11, 12, 14], columns=["a"], index=index)
+ # adding new row using an unexisting datetime-like str index
+ df.loc["2022-01-08", "a"] = 13
+
+ data.append("2022-01-08")
+ expected_index = DatetimeIndex(data, dtype=exp_dtype)
+ tm.assert_index_equal(df.index, expected_index, exact=True)
+
+
+def test_loc_set_int_dtype():
+ # GH#23326
+ df = DataFrame([list("abc")])
+ df.loc[:, "col1"] = 5
+
+ expected = DataFrame({0: ["a"], 1: ["b"], 2: ["c"], "col1": [5]})
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.filterwarnings(r"ignore:Period with BDay freq is deprecated:FutureWarning")
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+def test_loc_periodindex_3_levels():
+ # GH#24091
+ p_index = PeriodIndex(
+ ["20181101 1100", "20181101 1200", "20181102 1300", "20181102 1400"],
+ name="datetime",
+ freq="B",
+ )
+ mi_series = DataFrame(
+ [["A", "B", 1.0], ["A", "C", 2.0], ["Z", "Q", 3.0], ["W", "F", 4.0]],
+ index=p_index,
+ columns=["ONE", "TWO", "VALUES"],
+ )
+ mi_series = mi_series.set_index(["ONE", "TWO"], append=True)["VALUES"]
+ assert mi_series.loc[(p_index[0], "A", "B")] == 1.0
+
+
+def test_loc_setitem_pyarrow_strings():
+ # GH#52319
+ pytest.importorskip("pyarrow")
+ df = DataFrame(
+ {
+ "strings": Series(["A", "B", "C"], dtype="string[pyarrow]"),
+ "ids": Series([True, True, False]),
+ }
+ )
+ new_value = Series(["X", "Y"])
+ df.loc[df.ids, "strings"] = new_value
+
+ expected_df = DataFrame(
+ {
+ "strings": Series(["X", "Y", "C"], dtype="string[pyarrow]"),
+ "ids": Series([True, True, False]),
+ }
+ )
+
+ tm.assert_frame_equal(df, expected_df)
+
+
+class TestLocSeries:
+ @pytest.mark.parametrize("val,expected", [(2**63 - 1, 3), (2**63, 4)])
+ def test_loc_uint64(self, val, expected):
+ # see GH#19399
+ ser = Series({2**63 - 1: 3, 2**63: 4})
+ assert ser.loc[val] == expected
+
+ def test_loc_getitem(self, string_series, datetime_series):
+ inds = string_series.index[[3, 4, 7]]
+ tm.assert_series_equal(string_series.loc[inds], string_series.reindex(inds))
+ tm.assert_series_equal(string_series.iloc[5::2], string_series[5::2])
+
+ # slice with indices
+ d1, d2 = datetime_series.index[[5, 15]]
+ result = datetime_series.loc[d1:d2]
+ expected = datetime_series.truncate(d1, d2)
+ tm.assert_series_equal(result, expected)
+
+ # boolean
+ mask = string_series > string_series.median()
+ tm.assert_series_equal(string_series.loc[mask], string_series[mask])
+
+ # ask for index value
+ assert datetime_series.loc[d1] == datetime_series[d1]
+ assert datetime_series.loc[d2] == datetime_series[d2]
+
+ def test_loc_getitem_not_monotonic(self, datetime_series):
+ d1, d2 = datetime_series.index[[5, 15]]
+
+ ts2 = datetime_series[::2].iloc[[1, 2, 0]]
+
+ msg = r"Timestamp\('2000-01-10 00:00:00'\)"
+ with pytest.raises(KeyError, match=msg):
+ ts2.loc[d1:d2]
+ with pytest.raises(KeyError, match=msg):
+ ts2.loc[d1:d2] = 0
+
+ def test_loc_getitem_setitem_integer_slice_keyerrors(self):
+ ser = Series(
+ np.random.default_rng(2).standard_normal(10), index=list(range(0, 20, 2))
+ )
+
+ # this is OK
+ cp = ser.copy()
+ cp.iloc[4:10] = 0
+ assert (cp.iloc[4:10] == 0).all()
+
+ # so is this
+ cp = ser.copy()
+ cp.iloc[3:11] = 0
+ assert (cp.iloc[3:11] == 0).values.all()
+
+ result = ser.iloc[2:6]
+ result2 = ser.loc[3:11]
+ expected = ser.reindex([4, 6, 8, 10])
+
+ tm.assert_series_equal(result, expected)
+ tm.assert_series_equal(result2, expected)
+
+ # non-monotonic, raise KeyError
+ s2 = ser.iloc[list(range(5)) + list(range(9, 4, -1))]
+ with pytest.raises(KeyError, match=r"^3$"):
+ s2.loc[3:11]
+ with pytest.raises(KeyError, match=r"^3$"):
+ s2.loc[3:11] = 0
+
+ def test_loc_getitem_iterator(self, string_series):
+ idx = iter(string_series.index[:10])
+ result = string_series.loc[idx]
+ tm.assert_series_equal(result, string_series[:10])
+
+ def test_loc_setitem_boolean(self, string_series):
+ mask = string_series > string_series.median()
+
+ result = string_series.copy()
+ result.loc[mask] = 0
+ expected = string_series
+ expected[mask] = 0
+ tm.assert_series_equal(result, expected)
+
+ def test_loc_setitem_corner(self, string_series):
+ inds = list(string_series.index[[5, 8, 12]])
+ string_series.loc[inds] = 5
+ msg = r"\['foo'\] not in index"
+ with pytest.raises(KeyError, match=msg):
+ string_series.loc[inds + ["foo"]] = 5
+
+ def test_basic_setitem_with_labels(self, datetime_series):
+ indices = datetime_series.index[[5, 10, 15]]
+
+ cp = datetime_series.copy()
+ exp = datetime_series.copy()
+ cp[indices] = 0
+ exp.loc[indices] = 0
+ tm.assert_series_equal(cp, exp)
+
+ cp = datetime_series.copy()
+ exp = datetime_series.copy()
+ cp[indices[0] : indices[2]] = 0
+ exp.loc[indices[0] : indices[2]] = 0
+ tm.assert_series_equal(cp, exp)
+
+ def test_loc_setitem_listlike_of_ints(self):
+ # integer indexes, be careful
+ ser = Series(
+ np.random.default_rng(2).standard_normal(10), index=list(range(0, 20, 2))
+ )
+ inds = [0, 4, 6]
+ arr_inds = np.array([0, 4, 6])
+
+ cp = ser.copy()
+ exp = ser.copy()
+ ser[inds] = 0
+ ser.loc[inds] = 0
+ tm.assert_series_equal(cp, exp)
+
+ cp = ser.copy()
+ exp = ser.copy()
+ ser[arr_inds] = 0
+ ser.loc[arr_inds] = 0
+ tm.assert_series_equal(cp, exp)
+
+ inds_notfound = [0, 4, 5, 6]
+ arr_inds_notfound = np.array([0, 4, 5, 6])
+ msg = r"\[5\] not in index"
+ with pytest.raises(KeyError, match=msg):
+ ser[inds_notfound] = 0
+ with pytest.raises(Exception, match=msg):
+ ser[arr_inds_notfound] = 0
+
+ def test_loc_setitem_dt64tz_values(self):
+ # GH#12089
+ ser = Series(
+ date_range("2011-01-01", periods=3, tz="US/Eastern"),
+ index=["a", "b", "c"],
+ )
+ s2 = ser.copy()
+ expected = Timestamp("2011-01-03", tz="US/Eastern")
+ s2.loc["a"] = expected
+ result = s2.loc["a"]
+ assert result == expected
+
+ s2 = ser.copy()
+ s2.iloc[0] = expected
+ result = s2.iloc[0]
+ assert result == expected
+
+ s2 = ser.copy()
+ s2["a"] = expected
+ result = s2["a"]
+ assert result == expected
+
+ @pytest.mark.parametrize("array_fn", [np.array, pd.array, list, tuple])
+ @pytest.mark.parametrize("size", [0, 4, 5, 6])
+ def test_loc_iloc_setitem_with_listlike(self, size, array_fn):
+ # GH37748
+ # testing insertion, in a Series of size N (here 5), of a listlike object
+ # of size 0, N-1, N, N+1
+
+ arr = array_fn([0] * size)
+ expected = Series([arr, 0, 0, 0, 0], index=list("abcde"), dtype=object)
+
+ ser = Series(0, index=list("abcde"), dtype=object)
+ ser.loc["a"] = arr
+ tm.assert_series_equal(ser, expected)
+
+ ser = Series(0, index=list("abcde"), dtype=object)
+ ser.iloc[0] = arr
+ tm.assert_series_equal(ser, expected)
+
+ @pytest.mark.parametrize("indexer", [IndexSlice["A", :], ("A", slice(None))])
+ def test_loc_series_getitem_too_many_dimensions(self, indexer):
+ # GH#35349
+ ser = Series(
+ index=MultiIndex.from_tuples([("A", "0"), ("A", "1"), ("B", "0")]),
+ data=[21, 22, 23],
+ )
+ msg = "Too many indexers"
+ with pytest.raises(IndexingError, match=msg):
+ ser.loc[indexer, :]
+
+ with pytest.raises(IndexingError, match=msg):
+ ser.loc[indexer, :] = 1
+
+ def test_loc_setitem(self, string_series):
+ inds = string_series.index[[3, 4, 7]]
+
+ result = string_series.copy()
+ result.loc[inds] = 5
+
+ expected = string_series.copy()
+ expected.iloc[[3, 4, 7]] = 5
+ tm.assert_series_equal(result, expected)
+
+ result.iloc[5:10] = 10
+ expected[5:10] = 10
+ tm.assert_series_equal(result, expected)
+
+ # set slice with indices
+ d1, d2 = string_series.index[[5, 15]]
+ result.loc[d1:d2] = 6
+ expected[5:16] = 6 # because it's inclusive
+ tm.assert_series_equal(result, expected)
+
+ # set index value
+ string_series.loc[d1] = 4
+ string_series.loc[d2] = 6
+ assert string_series[d1] == 4
+ assert string_series[d2] == 6
+
+ @pytest.mark.parametrize("dtype", ["object", "string"])
+ def test_loc_assign_dict_to_row(self, dtype):
+ # GH41044
+ df = DataFrame({"A": ["abc", "def"], "B": ["ghi", "jkl"]}, dtype=dtype)
+ df.loc[0, :] = {"A": "newA", "B": "newB"}
+
+ expected = DataFrame({"A": ["newA", "def"], "B": ["newB", "jkl"]}, dtype=dtype)
+
+ tm.assert_frame_equal(df, expected)
+
+ @td.skip_array_manager_invalid_test
+ def test_loc_setitem_dict_timedelta_multiple_set(self):
+ # GH 16309
+ result = DataFrame(columns=["time", "value"])
+ result.loc[1] = {"time": Timedelta(6, unit="s"), "value": "foo"}
+ result.loc[1] = {"time": Timedelta(6, unit="s"), "value": "foo"}
+ expected = DataFrame(
+ [[Timedelta(6, unit="s"), "foo"]], columns=["time", "value"], index=[1]
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_set_multiple_items_in_multiple_new_columns(self):
+ # GH 25594
+ df = DataFrame(index=[1, 2], columns=["a"])
+ df.loc[1, ["b", "c"]] = [6, 7]
+
+ expected = DataFrame(
+ {
+ "a": Series([np.nan, np.nan], dtype="object"),
+ "b": [6, np.nan],
+ "c": [7, np.nan],
+ },
+ index=[1, 2],
+ )
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_getitem_loc_str_periodindex(self):
+ # GH#33964
+ msg = "Period with BDay freq is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ index = pd.period_range(start="2000", periods=20, freq="B")
+ series = Series(range(20), index=index)
+ assert series.loc["2000-01-14"] == 9
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_na_indexing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_na_indexing.py
new file mode 100644
index 0000000000000000000000000000000000000000..5364cfe85243001040bf40c8b72b4f71808c3d9c
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_na_indexing.py
@@ -0,0 +1,75 @@
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize(
+ "values, dtype",
+ [
+ ([], "object"),
+ ([1, 2, 3], "int64"),
+ ([1.0, 2.0, 3.0], "float64"),
+ (["a", "b", "c"], "object"),
+ (["a", "b", "c"], "string"),
+ ([1, 2, 3], "datetime64[ns]"),
+ ([1, 2, 3], "datetime64[ns, CET]"),
+ ([1, 2, 3], "timedelta64[ns]"),
+ (["2000", "2001", "2002"], "Period[D]"),
+ ([1, 0, 3], "Sparse"),
+ ([pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(3, 4)], "interval"),
+ ],
+)
+@pytest.mark.parametrize(
+ "mask", [[True, False, False], [True, True, True], [False, False, False]]
+)
+@pytest.mark.parametrize("indexer_class", [list, pd.array, pd.Index, pd.Series])
+@pytest.mark.parametrize("frame", [True, False])
+def test_series_mask_boolean(values, dtype, mask, indexer_class, frame):
+ # In case len(values) < 3
+ index = ["a", "b", "c"][: len(values)]
+ mask = mask[: len(values)]
+
+ obj = pd.Series(values, dtype=dtype, index=index)
+ if frame:
+ if len(values) == 0:
+ # Otherwise obj is an empty DataFrame with shape (0, 1)
+ obj = pd.DataFrame(dtype=dtype, index=index)
+ else:
+ obj = obj.to_frame()
+
+ if indexer_class is pd.array:
+ mask = pd.array(mask, dtype="boolean")
+ elif indexer_class is pd.Series:
+ mask = pd.Series(mask, index=obj.index, dtype="boolean")
+ else:
+ mask = indexer_class(mask)
+
+ expected = obj[mask]
+
+ result = obj[mask]
+ tm.assert_equal(result, expected)
+
+ if indexer_class is pd.Series:
+ msg = "iLocation based boolean indexing cannot use an indexable as a mask"
+ with pytest.raises(ValueError, match=msg):
+ result = obj.iloc[mask]
+ tm.assert_equal(result, expected)
+ else:
+ result = obj.iloc[mask]
+ tm.assert_equal(result, expected)
+
+ result = obj.loc[mask]
+ tm.assert_equal(result, expected)
+
+
+def test_na_treated_as_false(frame_or_series, indexer_sli):
+ # https://github.com/pandas-dev/pandas/issues/31503
+ obj = frame_or_series([1, 2, 3])
+
+ mask = pd.array([True, False, None], dtype="boolean")
+
+ result = indexer_sli(obj)[mask]
+ expected = indexer_sli(obj)[mask.fillna(False)]
+
+ tm.assert_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_partial.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_partial.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f499644f101391c78c01692fc1efb3bcf82b827
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_partial.py
@@ -0,0 +1,679 @@
+"""
+test setting *parts* of objects both positionally and label based
+
+TODO: these should be split among the indexer tests
+"""
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ Period,
+ Series,
+ Timestamp,
+ date_range,
+ period_range,
+)
+import pandas._testing as tm
+
+
+class TestEmptyFrameSetitemExpansion:
+ def test_empty_frame_setitem_index_name_retained(self):
+ # GH#31368 empty frame has non-None index.name -> retained
+ df = DataFrame({}, index=pd.RangeIndex(0, name="df_index"))
+ series = Series(1.23, index=pd.RangeIndex(4, name="series_index"))
+
+ df["series"] = series
+ expected = DataFrame(
+ {"series": [1.23] * 4}, index=pd.RangeIndex(4, name="df_index")
+ )
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_empty_frame_setitem_index_name_inherited(self):
+ # GH#36527 empty frame has None index.name -> not retained
+ df = DataFrame()
+ series = Series(1.23, index=pd.RangeIndex(4, name="series_index"))
+ df["series"] = series
+ expected = DataFrame(
+ {"series": [1.23] * 4}, index=pd.RangeIndex(4, name="series_index")
+ )
+ tm.assert_frame_equal(df, expected)
+
+ def test_loc_setitem_zerolen_series_columns_align(self):
+ # columns will align
+ df = DataFrame(columns=["A", "B"])
+ df.loc[0] = Series(1, index=range(4))
+ expected = DataFrame(columns=["A", "B"], index=[0], dtype=np.float64)
+ tm.assert_frame_equal(df, expected)
+
+ # columns will align
+ df = DataFrame(columns=["A", "B"])
+ df.loc[0] = Series(1, index=["B"])
+
+ exp = DataFrame([[np.nan, 1]], columns=["A", "B"], index=[0], dtype="float64")
+ tm.assert_frame_equal(df, exp)
+
+ def test_loc_setitem_zerolen_list_length_must_match_columns(self):
+ # list-like must conform
+ df = DataFrame(columns=["A", "B"])
+
+ msg = "cannot set a row with mismatched columns"
+ with pytest.raises(ValueError, match=msg):
+ df.loc[0] = [1, 2, 3]
+
+ df = DataFrame(columns=["A", "B"])
+ df.loc[3] = [6, 7] # length matches len(df.columns) --> OK!
+
+ exp = DataFrame([[6, 7]], index=[3], columns=["A", "B"], dtype=np.int64)
+ tm.assert_frame_equal(df, exp)
+
+ def test_partial_set_empty_frame(self):
+ # partially set with an empty object
+ # frame
+ df = DataFrame()
+
+ msg = "cannot set a frame with no defined columns"
+
+ with pytest.raises(ValueError, match=msg):
+ df.loc[1] = 1
+
+ with pytest.raises(ValueError, match=msg):
+ df.loc[1] = Series([1], index=["foo"])
+
+ msg = "cannot set a frame with no defined index and a scalar"
+ with pytest.raises(ValueError, match=msg):
+ df.loc[:, 1] = 1
+
+ def test_partial_set_empty_frame2(self):
+ # these work as they don't really change
+ # anything but the index
+ # GH#5632
+ expected = DataFrame(columns=["foo"], index=Index([], dtype="object"))
+
+ df = DataFrame(index=Index([], dtype="object"))
+ df["foo"] = Series([], dtype="object")
+
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame(index=Index([]))
+ df["foo"] = Series(df.index)
+
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame(index=Index([]))
+ df["foo"] = df.index
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_partial_set_empty_frame3(self):
+ expected = DataFrame(columns=["foo"], index=Index([], dtype="int64"))
+ expected["foo"] = expected["foo"].astype("float64")
+
+ df = DataFrame(index=Index([], dtype="int64"))
+ df["foo"] = []
+
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame(index=Index([], dtype="int64"))
+ df["foo"] = Series(np.arange(len(df)), dtype="float64")
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_partial_set_empty_frame4(self):
+ df = DataFrame(index=Index([], dtype="int64"))
+ df["foo"] = range(len(df))
+
+ expected = DataFrame(columns=["foo"], index=Index([], dtype="int64"))
+ # range is int-dtype-like, so we get int64 dtype
+ expected["foo"] = expected["foo"].astype("int64")
+ tm.assert_frame_equal(df, expected)
+
+ def test_partial_set_empty_frame5(self):
+ df = DataFrame()
+ tm.assert_index_equal(df.columns, pd.RangeIndex(0))
+ df2 = DataFrame()
+ df2[1] = Series([1], index=["foo"])
+ df.loc[:, 1] = Series([1], index=["foo"])
+ tm.assert_frame_equal(df, DataFrame([[1]], index=["foo"], columns=[1]))
+ tm.assert_frame_equal(df, df2)
+
+ def test_partial_set_empty_frame_no_index(self):
+ # no index to start
+ expected = DataFrame({0: Series(1, index=range(4))}, columns=["A", "B", 0])
+
+ df = DataFrame(columns=["A", "B"])
+ df[0] = Series(1, index=range(4))
+ df.dtypes
+ str(df)
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame(columns=["A", "B"])
+ df.loc[:, 0] = Series(1, index=range(4))
+ df.dtypes
+ str(df)
+ tm.assert_frame_equal(df, expected)
+
+ def test_partial_set_empty_frame_row(self):
+ # GH#5720, GH#5744
+ # don't create rows when empty
+ expected = DataFrame(columns=["A", "B", "New"], index=Index([], dtype="int64"))
+ expected["A"] = expected["A"].astype("int64")
+ expected["B"] = expected["B"].astype("float64")
+ expected["New"] = expected["New"].astype("float64")
+
+ df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
+ y = df[df.A > 5]
+ y["New"] = np.nan
+ tm.assert_frame_equal(y, expected)
+
+ expected = DataFrame(columns=["a", "b", "c c", "d"])
+ expected["d"] = expected["d"].astype("int64")
+ df = DataFrame(columns=["a", "b", "c c"])
+ df["d"] = 3
+ tm.assert_frame_equal(df, expected)
+ tm.assert_series_equal(df["c c"], Series(name="c c", dtype=object))
+
+ # reindex columns is ok
+ df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
+ y = df[df.A > 5]
+ result = y.reindex(columns=["A", "B", "C"])
+ expected = DataFrame(columns=["A", "B", "C"])
+ expected["A"] = expected["A"].astype("int64")
+ expected["B"] = expected["B"].astype("float64")
+ expected["C"] = expected["C"].astype("float64")
+ tm.assert_frame_equal(result, expected)
+
+ def test_partial_set_empty_frame_set_series(self):
+ # GH#5756
+ # setting with empty Series
+ df = DataFrame(Series(dtype=object))
+ expected = DataFrame({0: Series(dtype=object)})
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame(Series(name="foo", dtype=object))
+ expected = DataFrame({"foo": Series(dtype=object)})
+ tm.assert_frame_equal(df, expected)
+
+ def test_partial_set_empty_frame_empty_copy_assignment(self):
+ # GH#5932
+ # copy on empty with assignment fails
+ df = DataFrame(index=[0])
+ df = df.copy()
+ df["a"] = 0
+ expected = DataFrame(0, index=[0], columns=["a"])
+ tm.assert_frame_equal(df, expected)
+
+ def test_partial_set_empty_frame_empty_consistencies(self):
+ # GH#6171
+ # consistency on empty frames
+ df = DataFrame(columns=["x", "y"])
+ df["x"] = [1, 2]
+ expected = DataFrame({"x": [1, 2], "y": [np.nan, np.nan]})
+ tm.assert_frame_equal(df, expected, check_dtype=False)
+
+ df = DataFrame(columns=["x", "y"])
+ df["x"] = ["1", "2"]
+ expected = DataFrame({"x": ["1", "2"], "y": [np.nan, np.nan]}, dtype=object)
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame(columns=["x", "y"])
+ df.loc[0, "x"] = 1
+ expected = DataFrame({"x": [1], "y": [np.nan]})
+ tm.assert_frame_equal(df, expected, check_dtype=False)
+
+
+class TestPartialSetting:
+ def test_partial_setting(self):
+ # GH2578, allow ix and friends to partially set
+
+ # series
+ s_orig = Series([1, 2, 3])
+
+ s = s_orig.copy()
+ s[5] = 5
+ expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5])
+ tm.assert_series_equal(s, expected)
+
+ s = s_orig.copy()
+ s.loc[5] = 5
+ expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5])
+ tm.assert_series_equal(s, expected)
+
+ s = s_orig.copy()
+ s[5] = 5.0
+ expected = Series([1, 2, 3, 5.0], index=[0, 1, 2, 5])
+ tm.assert_series_equal(s, expected)
+
+ s = s_orig.copy()
+ s.loc[5] = 5.0
+ expected = Series([1, 2, 3, 5.0], index=[0, 1, 2, 5])
+ tm.assert_series_equal(s, expected)
+
+ # iloc/iat raise
+ s = s_orig.copy()
+
+ msg = "iloc cannot enlarge its target object"
+ with pytest.raises(IndexError, match=msg):
+ s.iloc[3] = 5.0
+
+ msg = "index 3 is out of bounds for axis 0 with size 3"
+ with pytest.raises(IndexError, match=msg):
+ s.iat[3] = 5.0
+
+ def test_partial_setting_frame(self, using_array_manager):
+ df_orig = DataFrame(
+ np.arange(6).reshape(3, 2), columns=["A", "B"], dtype="int64"
+ )
+
+ # iloc/iat raise
+ df = df_orig.copy()
+
+ msg = "iloc cannot enlarge its target object"
+ with pytest.raises(IndexError, match=msg):
+ df.iloc[4, 2] = 5.0
+
+ msg = "index 2 is out of bounds for axis 0 with size 2"
+ if using_array_manager:
+ msg = "list index out of range"
+ with pytest.raises(IndexError, match=msg):
+ df.iat[4, 2] = 5.0
+
+ # row setting where it exists
+ expected = DataFrame({"A": [0, 4, 4], "B": [1, 5, 5]})
+ df = df_orig.copy()
+ df.iloc[1] = df.iloc[2]
+ tm.assert_frame_equal(df, expected)
+
+ expected = DataFrame({"A": [0, 4, 4], "B": [1, 5, 5]})
+ df = df_orig.copy()
+ df.loc[1] = df.loc[2]
+ tm.assert_frame_equal(df, expected)
+
+ # like 2578, partial setting with dtype preservation
+ expected = DataFrame({"A": [0, 2, 4, 4], "B": [1, 3, 5, 5]})
+ df = df_orig.copy()
+ df.loc[3] = df.loc[2]
+ tm.assert_frame_equal(df, expected)
+
+ # single dtype frame, overwrite
+ expected = DataFrame({"A": [0, 2, 4], "B": [0, 2, 4]})
+ df = df_orig.copy()
+ df.loc[:, "B"] = df.loc[:, "A"]
+ tm.assert_frame_equal(df, expected)
+
+ # mixed dtype frame, overwrite
+ expected = DataFrame({"A": [0, 2, 4], "B": Series([0.0, 2.0, 4.0])})
+ df = df_orig.copy()
+ df["B"] = df["B"].astype(np.float64)
+ # as of 2.0, df.loc[:, "B"] = ... attempts (and here succeeds) at
+ # setting inplace
+ df.loc[:, "B"] = df.loc[:, "A"]
+ tm.assert_frame_equal(df, expected)
+
+ # single dtype frame, partial setting
+ expected = df_orig.copy()
+ expected["C"] = df["A"]
+ df = df_orig.copy()
+ df.loc[:, "C"] = df.loc[:, "A"]
+ tm.assert_frame_equal(df, expected)
+
+ # mixed frame, partial setting
+ expected = df_orig.copy()
+ expected["C"] = df["A"]
+ df = df_orig.copy()
+ df.loc[:, "C"] = df.loc[:, "A"]
+ tm.assert_frame_equal(df, expected)
+
+ def test_partial_setting2(self):
+ # GH 8473
+ dates = date_range("1/1/2000", periods=8)
+ df_orig = DataFrame(
+ np.random.default_rng(2).standard_normal((8, 4)),
+ index=dates,
+ columns=["A", "B", "C", "D"],
+ )
+
+ expected = pd.concat(
+ [df_orig, DataFrame({"A": 7}, index=dates[-1:] + dates.freq)], sort=True
+ )
+ df = df_orig.copy()
+ df.loc[dates[-1] + dates.freq, "A"] = 7
+ tm.assert_frame_equal(df, expected)
+ df = df_orig.copy()
+ df.at[dates[-1] + dates.freq, "A"] = 7
+ tm.assert_frame_equal(df, expected)
+
+ exp_other = DataFrame({0: 7}, index=dates[-1:] + dates.freq)
+ expected = pd.concat([df_orig, exp_other], axis=1)
+
+ df = df_orig.copy()
+ df.loc[dates[-1] + dates.freq, 0] = 7
+ tm.assert_frame_equal(df, expected)
+ df = df_orig.copy()
+ df.at[dates[-1] + dates.freq, 0] = 7
+ tm.assert_frame_equal(df, expected)
+
+ def test_partial_setting_mixed_dtype(self):
+ # in a mixed dtype environment, try to preserve dtypes
+ # by appending
+ df = DataFrame([[True, 1], [False, 2]], columns=["female", "fitness"])
+
+ s = df.loc[1].copy()
+ s.name = 2
+ expected = pd.concat([df, DataFrame(s).T.infer_objects()])
+
+ df.loc[2] = df.loc[1]
+ tm.assert_frame_equal(df, expected)
+
+ def test_series_partial_set(self):
+ # partial set with new index
+ # Regression from GH4825
+ ser = Series([0.1, 0.2], index=[1, 2])
+
+ # loc equiv to .reindex
+ expected = Series([np.nan, 0.2, np.nan], index=[3, 2, 3])
+ with pytest.raises(KeyError, match=r"not in index"):
+ ser.loc[[3, 2, 3]]
+
+ result = ser.reindex([3, 2, 3])
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ expected = Series([np.nan, 0.2, np.nan, np.nan], index=[3, 2, 3, "x"])
+ with pytest.raises(KeyError, match="not in index"):
+ ser.loc[[3, 2, 3, "x"]]
+
+ result = ser.reindex([3, 2, 3, "x"])
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ expected = Series([0.2, 0.2, 0.1], index=[2, 2, 1])
+ result = ser.loc[[2, 2, 1]]
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ expected = Series([0.2, 0.2, np.nan, 0.1], index=[2, 2, "x", 1])
+ with pytest.raises(KeyError, match="not in index"):
+ ser.loc[[2, 2, "x", 1]]
+
+ result = ser.reindex([2, 2, "x", 1])
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ # raises as nothing is in the index
+ msg = (
+ rf"\"None of \[Index\(\[3, 3, 3\], dtype='{np.dtype(int)}'\)\] "
+ r"are in the \[index\]\""
+ )
+ with pytest.raises(KeyError, match=msg):
+ ser.loc[[3, 3, 3]]
+
+ expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3])
+ with pytest.raises(KeyError, match="not in index"):
+ ser.loc[[2, 2, 3]]
+
+ result = ser.reindex([2, 2, 3])
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ s = Series([0.1, 0.2, 0.3], index=[1, 2, 3])
+ expected = Series([0.3, np.nan, np.nan], index=[3, 4, 4])
+ with pytest.raises(KeyError, match="not in index"):
+ s.loc[[3, 4, 4]]
+
+ result = s.reindex([3, 4, 4])
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ s = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4])
+ expected = Series([np.nan, 0.3, 0.3], index=[5, 3, 3])
+ with pytest.raises(KeyError, match="not in index"):
+ s.loc[[5, 3, 3]]
+
+ result = s.reindex([5, 3, 3])
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ s = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4])
+ expected = Series([np.nan, 0.4, 0.4], index=[5, 4, 4])
+ with pytest.raises(KeyError, match="not in index"):
+ s.loc[[5, 4, 4]]
+
+ result = s.reindex([5, 4, 4])
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ s = Series([0.1, 0.2, 0.3, 0.4], index=[4, 5, 6, 7])
+ expected = Series([0.4, np.nan, np.nan], index=[7, 2, 2])
+ with pytest.raises(KeyError, match="not in index"):
+ s.loc[[7, 2, 2]]
+
+ result = s.reindex([7, 2, 2])
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ s = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4])
+ expected = Series([0.4, np.nan, np.nan], index=[4, 5, 5])
+ with pytest.raises(KeyError, match="not in index"):
+ s.loc[[4, 5, 5]]
+
+ result = s.reindex([4, 5, 5])
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ # iloc
+ expected = Series([0.2, 0.2, 0.1, 0.1], index=[2, 2, 1, 1])
+ result = ser.iloc[[1, 1, 0, 0]]
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ def test_series_partial_set_with_name(self):
+ # GH 11497
+
+ idx = Index([1, 2], dtype="int64", name="idx")
+ ser = Series([0.1, 0.2], index=idx, name="s")
+
+ # loc
+ with pytest.raises(KeyError, match=r"\[3\] not in index"):
+ ser.loc[[3, 2, 3]]
+
+ with pytest.raises(KeyError, match=r"not in index"):
+ ser.loc[[3, 2, 3, "x"]]
+
+ exp_idx = Index([2, 2, 1], dtype="int64", name="idx")
+ expected = Series([0.2, 0.2, 0.1], index=exp_idx, name="s")
+ result = ser.loc[[2, 2, 1]]
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ with pytest.raises(KeyError, match=r"\['x'\] not in index"):
+ ser.loc[[2, 2, "x", 1]]
+
+ # raises as nothing is in the index
+ msg = (
+ rf"\"None of \[Index\(\[3, 3, 3\], dtype='{np.dtype(int)}', "
+ r"name='idx'\)\] are in the \[index\]\""
+ )
+ with pytest.raises(KeyError, match=msg):
+ ser.loc[[3, 3, 3]]
+
+ with pytest.raises(KeyError, match="not in index"):
+ ser.loc[[2, 2, 3]]
+
+ idx = Index([1, 2, 3], dtype="int64", name="idx")
+ with pytest.raises(KeyError, match="not in index"):
+ Series([0.1, 0.2, 0.3], index=idx, name="s").loc[[3, 4, 4]]
+
+ idx = Index([1, 2, 3, 4], dtype="int64", name="idx")
+ with pytest.raises(KeyError, match="not in index"):
+ Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[5, 3, 3]]
+
+ idx = Index([1, 2, 3, 4], dtype="int64", name="idx")
+ with pytest.raises(KeyError, match="not in index"):
+ Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[5, 4, 4]]
+
+ idx = Index([4, 5, 6, 7], dtype="int64", name="idx")
+ with pytest.raises(KeyError, match="not in index"):
+ Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[7, 2, 2]]
+
+ idx = Index([1, 2, 3, 4], dtype="int64", name="idx")
+ with pytest.raises(KeyError, match="not in index"):
+ Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[4, 5, 5]]
+
+ # iloc
+ exp_idx = Index([2, 2, 1, 1], dtype="int64", name="idx")
+ expected = Series([0.2, 0.2, 0.1, 0.1], index=exp_idx, name="s")
+ result = ser.iloc[[1, 1, 0, 0]]
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ @pytest.mark.parametrize("key", [100, 100.0])
+ def test_setitem_with_expansion_numeric_into_datetimeindex(self, key):
+ # GH#4940 inserting non-strings
+ orig = tm.makeTimeDataFrame()
+ df = orig.copy()
+
+ df.loc[key, :] = df.iloc[0]
+ ex_index = Index(list(orig.index) + [key], dtype=object, name=orig.index.name)
+ ex_data = np.concatenate([orig.values, df.iloc[[0]].values], axis=0)
+ expected = DataFrame(ex_data, index=ex_index, columns=orig.columns)
+
+ tm.assert_frame_equal(df, expected)
+
+ def test_partial_set_invalid(self):
+ # GH 4940
+ # allow only setting of 'valid' values
+
+ orig = tm.makeTimeDataFrame()
+
+ # allow object conversion here
+ df = orig.copy()
+ df.loc["a", :] = df.iloc[0]
+ ser = Series(df.iloc[0], name="a")
+ exp = pd.concat([orig, DataFrame(ser).T.infer_objects()])
+ tm.assert_frame_equal(df, exp)
+ tm.assert_index_equal(df.index, Index(orig.index.tolist() + ["a"]))
+ assert df.index.dtype == "object"
+
+ @pytest.mark.parametrize(
+ "idx,labels,expected_idx",
+ [
+ (
+ period_range(start="2000", periods=20, freq="D"),
+ ["2000-01-04", "2000-01-08", "2000-01-12"],
+ [
+ Period("2000-01-04", freq="D"),
+ Period("2000-01-08", freq="D"),
+ Period("2000-01-12", freq="D"),
+ ],
+ ),
+ (
+ date_range(start="2000", periods=20, freq="D"),
+ ["2000-01-04", "2000-01-08", "2000-01-12"],
+ [
+ Timestamp("2000-01-04"),
+ Timestamp("2000-01-08"),
+ Timestamp("2000-01-12"),
+ ],
+ ),
+ (
+ pd.timedelta_range(start="1 day", periods=20),
+ ["4D", "8D", "12D"],
+ [pd.Timedelta("4 day"), pd.Timedelta("8 day"), pd.Timedelta("12 day")],
+ ),
+ ],
+ )
+ def test_loc_with_list_of_strings_representing_datetimes(
+ self, idx, labels, expected_idx, frame_or_series
+ ):
+ # GH 11278
+ obj = frame_or_series(range(20), index=idx)
+
+ expected_value = [3, 7, 11]
+ expected = frame_or_series(expected_value, expected_idx)
+
+ tm.assert_equal(expected, obj.loc[labels])
+ if frame_or_series is Series:
+ tm.assert_series_equal(expected, obj[labels])
+
+ @pytest.mark.parametrize(
+ "idx,labels",
+ [
+ (
+ period_range(start="2000", periods=20, freq="D"),
+ ["2000-01-04", "2000-01-30"],
+ ),
+ (
+ date_range(start="2000", periods=20, freq="D"),
+ ["2000-01-04", "2000-01-30"],
+ ),
+ (pd.timedelta_range(start="1 day", periods=20), ["3 day", "30 day"]),
+ ],
+ )
+ def test_loc_with_list_of_strings_representing_datetimes_missing_value(
+ self, idx, labels
+ ):
+ # GH 11278
+ ser = Series(range(20), index=idx)
+ df = DataFrame(range(20), index=idx)
+ msg = r"not in index"
+
+ with pytest.raises(KeyError, match=msg):
+ ser.loc[labels]
+ with pytest.raises(KeyError, match=msg):
+ ser[labels]
+ with pytest.raises(KeyError, match=msg):
+ df.loc[labels]
+
+ @pytest.mark.parametrize(
+ "idx,labels,msg",
+ [
+ (
+ period_range(start="2000", periods=20, freq="D"),
+ ["4D", "8D"],
+ (
+ r"None of \[Index\(\['4D', '8D'\], dtype='object'\)\] "
+ r"are in the \[index\]"
+ ),
+ ),
+ (
+ date_range(start="2000", periods=20, freq="D"),
+ ["4D", "8D"],
+ (
+ r"None of \[Index\(\['4D', '8D'\], dtype='object'\)\] "
+ r"are in the \[index\]"
+ ),
+ ),
+ (
+ pd.timedelta_range(start="1 day", periods=20),
+ ["2000-01-04", "2000-01-08"],
+ (
+ r"None of \[Index\(\['2000-01-04', '2000-01-08'\], "
+ r"dtype='object'\)\] are in the \[index\]"
+ ),
+ ),
+ ],
+ )
+ def test_loc_with_list_of_strings_representing_datetimes_not_matched_type(
+ self, idx, labels, msg
+ ):
+ # GH 11278
+ ser = Series(range(20), index=idx)
+ df = DataFrame(range(20), index=idx)
+
+ with pytest.raises(KeyError, match=msg):
+ ser.loc[labels]
+ with pytest.raises(KeyError, match=msg):
+ ser[labels]
+ with pytest.raises(KeyError, match=msg):
+ df.loc[labels]
+
+
+class TestStringSlicing:
+ def test_slice_irregular_datetime_index_with_nan(self):
+ # GH36953
+ index = pd.to_datetime(["2012-01-01", "2012-01-02", "2012-01-03", None])
+ df = DataFrame(range(len(index)), index=index)
+ expected = DataFrame(range(len(index[:3])), index=index[:3])
+ with pytest.raises(KeyError, match="non-existing keys is not allowed"):
+ # Upper bound is not in index (which is unordered)
+ # GH53983
+ # GH37819
+ df["2012-01-01":"2012-01-04"]
+ # Need this precision for right bound since the right slice
+ # bound is "rounded" up to the largest timepoint smaller than
+ # the next "resolution"-step of the provided point.
+ # e.g. 2012-01-03 is rounded up to 2012-01-04 - 1ns
+ result = df["2012-01-01":"2012-01-03 00:00:00.000000000"]
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_scalar.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_scalar.py
new file mode 100644
index 0000000000000000000000000000000000000000..2753b3574e58355b67b0d30a73c34638ee553701
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/indexing/test_scalar.py
@@ -0,0 +1,301 @@
+""" test scalar indexing, including at and iat """
+from datetime import (
+ datetime,
+ timedelta,
+)
+import itertools
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+)
+import pandas._testing as tm
+
+
+def generate_indices(f, values=False):
+ """
+ generate the indices
+ if values is True , use the axis values
+ is False, use the range
+ """
+ axes = f.axes
+ if values:
+ axes = (list(range(len(ax))) for ax in axes)
+
+ return itertools.product(*axes)
+
+
+class TestScalar:
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ @pytest.mark.parametrize("col", ["ints", "uints"])
+ def test_iat_set_ints(self, kind, col, request):
+ f = request.getfixturevalue(f"{kind}_{col}")
+ indices = generate_indices(f, True)
+ for i in indices:
+ f.iat[i] = 1
+ expected = f.values[i]
+ tm.assert_almost_equal(expected, 1)
+
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ @pytest.mark.parametrize("col", ["labels", "ts", "floats"])
+ def test_iat_set_other(self, kind, col, request):
+ f = request.getfixturevalue(f"{kind}_{col}")
+ msg = "iAt based indexing can only have integer indexers"
+ with pytest.raises(ValueError, match=msg):
+ idx = next(generate_indices(f, False))
+ f.iat[idx] = 1
+
+ @pytest.mark.parametrize("kind", ["series", "frame"])
+ @pytest.mark.parametrize("col", ["ints", "uints", "labels", "ts", "floats"])
+ def test_at_set_ints_other(self, kind, col, request):
+ f = request.getfixturevalue(f"{kind}_{col}")
+ indices = generate_indices(f, False)
+ for i in indices:
+ f.at[i] = 1
+ expected = f.loc[i]
+ tm.assert_almost_equal(expected, 1)
+
+
+class TestAtAndiAT:
+ # at and iat tests that don't need Base class
+
+ def test_float_index_at_iat(self):
+ ser = Series([1, 2, 3], index=[0.1, 0.2, 0.3])
+ for el, item in ser.items():
+ assert ser.at[el] == item
+ for i in range(len(ser)):
+ assert ser.iat[i] == i + 1
+
+ def test_at_iat_coercion(self):
+ # as timestamp is not a tuple!
+ dates = date_range("1/1/2000", periods=8)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((8, 4)),
+ index=dates,
+ columns=["A", "B", "C", "D"],
+ )
+ s = df["A"]
+
+ result = s.at[dates[5]]
+ xp = s.values[5]
+ assert result == xp
+
+ @pytest.mark.parametrize(
+ "ser, expected",
+ [
+ [
+ Series(["2014-01-01", "2014-02-02"], dtype="datetime64[ns]"),
+ Timestamp("2014-02-02"),
+ ],
+ [
+ Series(["1 days", "2 days"], dtype="timedelta64[ns]"),
+ Timedelta("2 days"),
+ ],
+ ],
+ )
+ def test_iloc_iat_coercion_datelike(self, indexer_ial, ser, expected):
+ # GH 7729
+ # make sure we are boxing the returns
+ result = indexer_ial(ser)[1]
+ assert result == expected
+
+ def test_imethods_with_dups(self):
+ # GH6493
+ # iat/iloc with dups
+
+ s = Series(range(5), index=[1, 1, 2, 2, 3], dtype="int64")
+ result = s.iloc[2]
+ assert result == 2
+ result = s.iat[2]
+ assert result == 2
+
+ msg = "index 10 is out of bounds for axis 0 with size 5"
+ with pytest.raises(IndexError, match=msg):
+ s.iat[10]
+ msg = "index -10 is out of bounds for axis 0 with size 5"
+ with pytest.raises(IndexError, match=msg):
+ s.iat[-10]
+
+ result = s.iloc[[2, 3]]
+ expected = Series([2, 3], [2, 2], dtype="int64")
+ tm.assert_series_equal(result, expected)
+
+ df = s.to_frame()
+ result = df.iloc[2]
+ expected = Series(2, index=[0], name=2)
+ tm.assert_series_equal(result, expected)
+
+ result = df.iat[2, 0]
+ assert result == 2
+
+ def test_frame_at_with_duplicate_axes(self):
+ # GH#33041
+ arr = np.random.default_rng(2).standard_normal(6).reshape(3, 2)
+ df = DataFrame(arr, columns=["A", "A"])
+
+ result = df.at[0, "A"]
+ expected = df.iloc[0]
+
+ tm.assert_series_equal(result, expected)
+
+ result = df.T.at["A", 0]
+ tm.assert_series_equal(result, expected)
+
+ # setter
+ df.at[1, "A"] = 2
+ expected = Series([2.0, 2.0], index=["A", "A"], name=1)
+ tm.assert_series_equal(df.iloc[1], expected)
+
+ def test_at_getitem_dt64tz_values(self):
+ # gh-15822
+ df = DataFrame(
+ {
+ "name": ["John", "Anderson"],
+ "date": [
+ Timestamp(2017, 3, 13, 13, 32, 56),
+ Timestamp(2017, 2, 16, 12, 10, 3),
+ ],
+ }
+ )
+ df["date"] = df["date"].dt.tz_localize("Asia/Shanghai")
+
+ expected = Timestamp("2017-03-13 13:32:56+0800", tz="Asia/Shanghai")
+
+ result = df.loc[0, "date"]
+ assert result == expected
+
+ result = df.at[0, "date"]
+ assert result == expected
+
+ def test_mixed_index_at_iat_loc_iloc_series(self):
+ # GH 19860
+ s = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
+ for el, item in s.items():
+ assert s.at[el] == s.loc[el] == item
+ for i in range(len(s)):
+ assert s.iat[i] == s.iloc[i] == i + 1
+
+ with pytest.raises(KeyError, match="^4$"):
+ s.at[4]
+ with pytest.raises(KeyError, match="^4$"):
+ s.loc[4]
+
+ def test_mixed_index_at_iat_loc_iloc_dataframe(self):
+ # GH 19860
+ df = DataFrame(
+ [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], columns=["a", "b", "c", 1, 2]
+ )
+ for rowIdx, row in df.iterrows():
+ for el, item in row.items():
+ assert df.at[rowIdx, el] == df.loc[rowIdx, el] == item
+
+ for row in range(2):
+ for i in range(5):
+ assert df.iat[row, i] == df.iloc[row, i] == row * 5 + i
+
+ with pytest.raises(KeyError, match="^3$"):
+ df.at[0, 3]
+ with pytest.raises(KeyError, match="^3$"):
+ df.loc[0, 3]
+
+ def test_iat_setter_incompatible_assignment(self):
+ # GH 23236
+ result = DataFrame({"a": [0.0, 1.0], "b": [4, 5]})
+ result.iat[0, 0] = None
+ expected = DataFrame({"a": [None, 1], "b": [4, 5]})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_iat_dont_wrap_object_datetimelike():
+ # GH#32809 .iat calls go through DataFrame._get_value, should not
+ # call maybe_box_datetimelike
+ dti = date_range("2016-01-01", periods=3)
+ tdi = dti - dti
+ ser = Series(dti.to_pydatetime(), dtype=object)
+ ser2 = Series(tdi.to_pytimedelta(), dtype=object)
+ df = DataFrame({"A": ser, "B": ser2})
+ assert (df.dtypes == object).all()
+
+ for result in [df.at[0, "A"], df.iat[0, 0], df.loc[0, "A"], df.iloc[0, 0]]:
+ assert result is ser[0]
+ assert isinstance(result, datetime)
+ assert not isinstance(result, Timestamp)
+
+ for result in [df.at[1, "B"], df.iat[1, 1], df.loc[1, "B"], df.iloc[1, 1]]:
+ assert result is ser2[1]
+ assert isinstance(result, timedelta)
+ assert not isinstance(result, Timedelta)
+
+
+def test_at_with_tuple_index_get():
+ # GH 26989
+ # DataFrame.at getter works with Index of tuples
+ df = DataFrame({"a": [1, 2]}, index=[(1, 2), (3, 4)])
+ assert df.index.nlevels == 1
+ assert df.at[(1, 2), "a"] == 1
+
+ # Series.at getter works with Index of tuples
+ series = df["a"]
+ assert series.index.nlevels == 1
+ assert series.at[(1, 2)] == 1
+
+
+def test_at_with_tuple_index_set():
+ # GH 26989
+ # DataFrame.at setter works with Index of tuples
+ df = DataFrame({"a": [1, 2]}, index=[(1, 2), (3, 4)])
+ assert df.index.nlevels == 1
+ df.at[(1, 2), "a"] = 2
+ assert df.at[(1, 2), "a"] == 2
+
+ # Series.at setter works with Index of tuples
+ series = df["a"]
+ assert series.index.nlevels == 1
+ series.at[1, 2] = 3
+ assert series.at[1, 2] == 3
+
+
+class TestMultiIndexScalar:
+ def test_multiindex_at_get(self):
+ # GH 26989
+ # DataFrame.at and DataFrame.loc getter works with MultiIndex
+ df = DataFrame({"a": [1, 2]}, index=[[1, 2], [3, 4]])
+ assert df.index.nlevels == 2
+ assert df.at[(1, 3), "a"] == 1
+ assert df.loc[(1, 3), "a"] == 1
+
+ # Series.at and Series.loc getter works with MultiIndex
+ series = df["a"]
+ assert series.index.nlevels == 2
+ assert series.at[1, 3] == 1
+ assert series.loc[1, 3] == 1
+
+ def test_multiindex_at_set(self):
+ # GH 26989
+ # DataFrame.at and DataFrame.loc setter works with MultiIndex
+ df = DataFrame({"a": [1, 2]}, index=[[1, 2], [3, 4]])
+ assert df.index.nlevels == 2
+ df.at[(1, 3), "a"] = 3
+ assert df.at[(1, 3), "a"] == 3
+ df.loc[(1, 3), "a"] = 4
+ assert df.loc[(1, 3), "a"] == 4
+
+ # Series.at and Series.loc setter works with MultiIndex
+ series = df["a"]
+ assert series.index.nlevels == 2
+ series.at[1, 3] = 5
+ assert series.at[1, 3] == 5
+ series.loc[1, 3] = 6
+ assert series.loc[1, 3] == 6
+
+ def test_multiindex_at_get_one_level(self):
+ # GH#38053
+ s2 = Series((0, 1), index=[[False, True]])
+ result = s2.at[False]
+ assert result == 0
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/test_impl.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/test_impl.py
new file mode 100644
index 0000000000000000000000000000000000000000..97a388569e26135d534d2a5d911814248f4c488a
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/test_impl.py
@@ -0,0 +1,364 @@
+from datetime import datetime
+
+import numpy as np
+import pytest
+
+from pandas._libs.tslibs import iNaT
+from pandas.compat import (
+ is_ci_environment,
+ is_platform_windows,
+)
+import pandas.util._test_decorators as td
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.interchange.column import PandasColumn
+from pandas.core.interchange.dataframe_protocol import (
+ ColumnNullType,
+ DtypeKind,
+)
+from pandas.core.interchange.from_dataframe import from_dataframe
+from pandas.core.interchange.utils import ArrowCTypes
+
+
+@pytest.fixture
+def data_categorical():
+ return {
+ "ordered": pd.Categorical(list("testdata") * 30, ordered=True),
+ "unordered": pd.Categorical(list("testdata") * 30, ordered=False),
+ }
+
+
+@pytest.fixture
+def string_data():
+ return {
+ "separator data": [
+ "abC|DeF,Hik",
+ "234,3245.67",
+ "gSaf,qWer|Gre",
+ "asd3,4sad|",
+ np.nan,
+ ]
+ }
+
+
+@pytest.mark.parametrize("data", [("ordered", True), ("unordered", False)])
+def test_categorical_dtype(data, data_categorical):
+ df = pd.DataFrame({"A": (data_categorical[data[0]])})
+
+ col = df.__dataframe__().get_column_by_name("A")
+ assert col.dtype[0] == DtypeKind.CATEGORICAL
+ assert col.null_count == 0
+ assert col.describe_null == (ColumnNullType.USE_SENTINEL, -1)
+ assert col.num_chunks() == 1
+ desc_cat = col.describe_categorical
+ assert desc_cat["is_ordered"] == data[1]
+ assert desc_cat["is_dictionary"] is True
+ assert isinstance(desc_cat["categories"], PandasColumn)
+ tm.assert_series_equal(
+ desc_cat["categories"]._col, pd.Series(["a", "d", "e", "s", "t"])
+ )
+
+ tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))
+
+
+def test_categorical_pyarrow():
+ # GH 49889
+ pa = pytest.importorskip("pyarrow", "11.0.0")
+
+ arr = ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", "Sun"]
+ table = pa.table({"weekday": pa.array(arr).dictionary_encode()})
+ exchange_df = table.__dataframe__()
+ result = from_dataframe(exchange_df)
+ weekday = pd.Categorical(
+ arr, categories=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
+ )
+ expected = pd.DataFrame({"weekday": weekday})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_empty_categorical_pyarrow():
+ # https://github.com/pandas-dev/pandas/issues/53077
+ pa = pytest.importorskip("pyarrow", "11.0.0")
+
+ arr = [None]
+ table = pa.table({"arr": pa.array(arr, "float64").dictionary_encode()})
+ exchange_df = table.__dataframe__()
+ result = pd.api.interchange.from_dataframe(exchange_df)
+ expected = pd.DataFrame({"arr": pd.Categorical([np.nan])})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_large_string_pyarrow():
+ # GH 52795
+ pa = pytest.importorskip("pyarrow", "11.0.0")
+
+ arr = ["Mon", "Tue"]
+ table = pa.table({"weekday": pa.array(arr, "large_string")})
+ exchange_df = table.__dataframe__()
+ result = from_dataframe(exchange_df)
+ expected = pd.DataFrame({"weekday": ["Mon", "Tue"]})
+ tm.assert_frame_equal(result, expected)
+
+ # check round-trip
+ assert pa.Table.equals(pa.interchange.from_dataframe(result), table)
+
+
+@pytest.mark.parametrize(
+ ("offset", "length", "expected_values"),
+ [
+ (0, None, [3.3, float("nan"), 2.1]),
+ (1, None, [float("nan"), 2.1]),
+ (2, None, [2.1]),
+ (0, 2, [3.3, float("nan")]),
+ (0, 1, [3.3]),
+ (1, 1, [float("nan")]),
+ ],
+)
+def test_bitmasks_pyarrow(offset, length, expected_values):
+ # GH 52795
+ pa = pytest.importorskip("pyarrow", "11.0.0")
+
+ arr = [3.3, None, 2.1]
+ table = pa.table({"arr": arr}).slice(offset, length)
+ exchange_df = table.__dataframe__()
+ result = from_dataframe(exchange_df)
+ expected = pd.DataFrame({"arr": expected_values})
+ tm.assert_frame_equal(result, expected)
+
+ # check round-trip
+ assert pa.Table.equals(pa.interchange.from_dataframe(result), table)
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ lambda: np.random.default_rng(2).integers(-100, 100),
+ lambda: np.random.default_rng(2).integers(1, 100),
+ lambda: np.random.default_rng(2).random(),
+ lambda: np.random.default_rng(2).choice([True, False]),
+ lambda: datetime(
+ year=np.random.default_rng(2).integers(1900, 2100),
+ month=np.random.default_rng(2).integers(1, 12),
+ day=np.random.default_rng(2).integers(1, 20),
+ ),
+ ],
+)
+def test_dataframe(data):
+ NCOLS, NROWS = 10, 20
+ data = {
+ f"col{int((i - NCOLS / 2) % NCOLS + 1)}": [data() for _ in range(NROWS)]
+ for i in range(NCOLS)
+ }
+ df = pd.DataFrame(data)
+
+ df2 = df.__dataframe__()
+
+ assert df2.num_columns() == NCOLS
+ assert df2.num_rows() == NROWS
+
+ assert list(df2.column_names()) == list(data.keys())
+
+ indices = (0, 2)
+ names = tuple(list(data.keys())[idx] for idx in indices)
+
+ result = from_dataframe(df2.select_columns(indices))
+ expected = from_dataframe(df2.select_columns_by_name(names))
+ tm.assert_frame_equal(result, expected)
+
+ assert isinstance(result.attrs["_INTERCHANGE_PROTOCOL_BUFFERS"], list)
+ assert isinstance(expected.attrs["_INTERCHANGE_PROTOCOL_BUFFERS"], list)
+
+
+def test_missing_from_masked():
+ df = pd.DataFrame(
+ {
+ "x": np.array([1.0, 2.0, 3.0, 4.0, 0.0]),
+ "y": np.array([1.5, 2.5, 3.5, 4.5, 0]),
+ "z": np.array([1.0, 0.0, 1.0, 1.0, 1.0]),
+ }
+ )
+
+ df2 = df.__dataframe__()
+
+ rng = np.random.default_rng(2)
+ dict_null = {col: rng.integers(low=0, high=len(df)) for col in df.columns}
+ for col, num_nulls in dict_null.items():
+ null_idx = df.index[
+ rng.choice(np.arange(len(df)), size=num_nulls, replace=False)
+ ]
+ df.loc[null_idx, col] = None
+
+ df2 = df.__dataframe__()
+
+ assert df2.get_column_by_name("x").null_count == dict_null["x"]
+ assert df2.get_column_by_name("y").null_count == dict_null["y"]
+ assert df2.get_column_by_name("z").null_count == dict_null["z"]
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ {"x": [1.5, 2.5, 3.5], "y": [9.2, 10.5, 11.8]},
+ {"x": [1, 2, 0], "y": [9.2, 10.5, 11.8]},
+ {
+ "x": np.array([True, True, False]),
+ "y": np.array([1, 2, 0]),
+ "z": np.array([9.2, 10.5, 11.8]),
+ },
+ ],
+)
+def test_mixed_data(data):
+ df = pd.DataFrame(data)
+ df2 = df.__dataframe__()
+
+ for col_name in df.columns:
+ assert df2.get_column_by_name(col_name).null_count == 0
+
+
+def test_mixed_missing():
+ df = pd.DataFrame(
+ {
+ "x": np.array([True, None, False, None, True]),
+ "y": np.array([None, 2, None, 1, 2]),
+ "z": np.array([9.2, 10.5, None, 11.8, None]),
+ }
+ )
+
+ df2 = df.__dataframe__()
+
+ for col_name in df.columns:
+ assert df2.get_column_by_name(col_name).null_count == 2
+
+
+def test_string(string_data):
+ test_str_data = string_data["separator data"] + [""]
+ df = pd.DataFrame({"A": test_str_data})
+ col = df.__dataframe__().get_column_by_name("A")
+
+ assert col.size() == 6
+ assert col.null_count == 1
+ assert col.dtype[0] == DtypeKind.STRING
+ assert col.describe_null == (ColumnNullType.USE_BYTEMASK, 0)
+
+ df_sliced = df[1:]
+ col = df_sliced.__dataframe__().get_column_by_name("A")
+ assert col.size() == 5
+ assert col.null_count == 1
+ assert col.dtype[0] == DtypeKind.STRING
+ assert col.describe_null == (ColumnNullType.USE_BYTEMASK, 0)
+
+
+def test_nonstring_object():
+ df = pd.DataFrame({"A": ["a", 10, 1.0, ()]})
+ col = df.__dataframe__().get_column_by_name("A")
+ with pytest.raises(NotImplementedError, match="not supported yet"):
+ col.dtype
+
+
+def test_datetime():
+ df = pd.DataFrame({"A": [pd.Timestamp("2022-01-01"), pd.NaT]})
+ col = df.__dataframe__().get_column_by_name("A")
+
+ assert col.size() == 2
+ assert col.null_count == 1
+ assert col.dtype[0] == DtypeKind.DATETIME
+ assert col.describe_null == (ColumnNullType.USE_SENTINEL, iNaT)
+
+ tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))
+
+
+@td.skip_if_np_lt("1.23")
+def test_categorical_to_numpy_dlpack():
+ # https://github.com/pandas-dev/pandas/issues/48393
+ df = pd.DataFrame({"A": pd.Categorical(["a", "b", "a"])})
+ col = df.__dataframe__().get_column_by_name("A")
+ result = np.from_dlpack(col.get_buffers()["data"][0])
+ expected = np.array([0, 1, 0], dtype="int8")
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("data", [{}, {"a": []}])
+def test_empty_pyarrow(data):
+ # GH 53155
+ pytest.importorskip("pyarrow", "11.0.0")
+ from pyarrow.interchange import from_dataframe as pa_from_dataframe
+
+ expected = pd.DataFrame(data)
+ arrow_df = pa_from_dataframe(expected)
+ result = from_dataframe(arrow_df)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_multi_chunk_pyarrow() -> None:
+ pa = pytest.importorskip("pyarrow", "11.0.0")
+ n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
+ names = ["n_legs"]
+ table = pa.table([n_legs], names=names)
+ with pytest.raises(
+ RuntimeError,
+ match="To join chunks a copy is required which is "
+ "forbidden by allow_copy=False",
+ ):
+ pd.api.interchange.from_dataframe(table, allow_copy=False)
+
+
+@pytest.mark.parametrize("tz", ["UTC", "US/Pacific"])
+@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
+def test_datetimetzdtype(tz, unit):
+ # GH 54239
+ tz_data = (
+ pd.date_range("2018-01-01", periods=5, freq="D").tz_localize(tz).as_unit(unit)
+ )
+ df = pd.DataFrame({"ts_tz": tz_data})
+ tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))
+
+
+def test_interchange_from_non_pandas_tz_aware(request):
+ # GH 54239, 54287
+ pa = pytest.importorskip("pyarrow", "11.0.0")
+ import pyarrow.compute as pc
+
+ if is_platform_windows() and is_ci_environment():
+ mark = pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason=(
+ "TODO: Set ARROW_TIMEZONE_DATABASE environment variable "
+ "on CI to path to the tzdata for pyarrow."
+ ),
+ )
+ request.node.add_marker(mark)
+
+ arr = pa.array([datetime(2020, 1, 1), None, datetime(2020, 1, 2)])
+ arr = pc.assume_timezone(arr, "Asia/Kathmandu")
+ table = pa.table({"arr": arr})
+ exchange_df = table.__dataframe__()
+ result = from_dataframe(exchange_df)
+
+ expected = pd.DataFrame(
+ ["2020-01-01 00:00:00+05:45", "NaT", "2020-01-02 00:00:00+05:45"],
+ columns=["arr"],
+ dtype="datetime64[us, Asia/Kathmandu]",
+ )
+ tm.assert_frame_equal(expected, result)
+
+
+def test_interchange_from_corrected_buffer_dtypes(monkeypatch) -> None:
+ # https://github.com/pandas-dev/pandas/issues/54781
+ df = pd.DataFrame({"a": ["foo", "bar"]}).__dataframe__()
+ interchange = df.__dataframe__()
+ column = interchange.get_column_by_name("a")
+ buffers = column.get_buffers()
+ buffers_data = buffers["data"]
+ buffer_dtype = buffers_data[1]
+ buffer_dtype = (
+ DtypeKind.UINT,
+ 8,
+ ArrowCTypes.UINT8,
+ buffer_dtype[3],
+ )
+ buffers["data"] = (buffers_data[0], buffer_dtype)
+ column.get_buffers = lambda: buffers
+ interchange.get_column_by_name = lambda _: column
+ monkeypatch.setattr(df, "__dataframe__", lambda allow_copy: interchange)
+ pd.api.interchange.from_dataframe(df)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/test_spec_conformance.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/test_spec_conformance.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c02379c118539032cb79d682d4baa2c7ae1fb81
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/test_spec_conformance.py
@@ -0,0 +1,175 @@
+"""
+A verbatim copy (vendored) of the spec tests.
+Taken from https://github.com/data-apis/dataframe-api
+"""
+import ctypes
+import math
+
+import pytest
+
+import pandas as pd
+
+
+@pytest.fixture
+def df_from_dict():
+ def maker(dct, is_categorical=False):
+ df = pd.DataFrame(dct)
+ return df.astype("category") if is_categorical else df
+
+ return maker
+
+
+@pytest.mark.parametrize(
+ "test_data",
+ [
+ {"a": ["foo", "bar"], "b": ["baz", "qux"]},
+ {"a": [1.5, 2.5, 3.5], "b": [9.2, 10.5, 11.8]},
+ {"A": [1, 2, 3, 4], "B": [1, 2, 3, 4]},
+ ],
+ ids=["str_data", "float_data", "int_data"],
+)
+def test_only_one_dtype(test_data, df_from_dict):
+ columns = list(test_data.keys())
+ df = df_from_dict(test_data)
+ dfX = df.__dataframe__()
+
+ column_size = len(test_data[columns[0]])
+ for column in columns:
+ null_count = dfX.get_column_by_name(column).null_count
+ assert null_count == 0
+ assert isinstance(null_count, int)
+ assert dfX.get_column_by_name(column).size() == column_size
+ assert dfX.get_column_by_name(column).offset == 0
+
+
+def test_mixed_dtypes(df_from_dict):
+ df = df_from_dict(
+ {
+ "a": [1, 2, 3], # dtype kind INT = 0
+ "b": [3, 4, 5], # dtype kind INT = 0
+ "c": [1.5, 2.5, 3.5], # dtype kind FLOAT = 2
+ "d": [9, 10, 11], # dtype kind INT = 0
+ "e": [True, False, True], # dtype kind BOOLEAN = 20
+ "f": ["a", "", "c"], # dtype kind STRING = 21
+ }
+ )
+ dfX = df.__dataframe__()
+ # for meanings of dtype[0] see the spec; we cannot import the spec here as this
+ # file is expected to be vendored *anywhere*;
+ # values for dtype[0] are explained above
+ columns = {"a": 0, "b": 0, "c": 2, "d": 0, "e": 20, "f": 21}
+
+ for column, kind in columns.items():
+ colX = dfX.get_column_by_name(column)
+ assert colX.null_count == 0
+ assert isinstance(colX.null_count, int)
+ assert colX.size() == 3
+ assert colX.offset == 0
+
+ assert colX.dtype[0] == kind
+
+ assert dfX.get_column_by_name("c").dtype[1] == 64
+
+
+def test_na_float(df_from_dict):
+ df = df_from_dict({"a": [1.0, math.nan, 2.0]})
+ dfX = df.__dataframe__()
+ colX = dfX.get_column_by_name("a")
+ assert colX.null_count == 1
+ assert isinstance(colX.null_count, int)
+
+
+def test_noncategorical(df_from_dict):
+ df = df_from_dict({"a": [1, 2, 3]})
+ dfX = df.__dataframe__()
+ colX = dfX.get_column_by_name("a")
+ with pytest.raises(TypeError, match=".*categorical.*"):
+ colX.describe_categorical
+
+
+def test_categorical(df_from_dict):
+ df = df_from_dict(
+ {"weekday": ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", "Sun"]},
+ is_categorical=True,
+ )
+
+ colX = df.__dataframe__().get_column_by_name("weekday")
+ categorical = colX.describe_categorical
+ assert isinstance(categorical["is_ordered"], bool)
+ assert isinstance(categorical["is_dictionary"], bool)
+
+
+def test_dataframe(df_from_dict):
+ df = df_from_dict(
+ {"x": [True, True, False], "y": [1, 2, 0], "z": [9.2, 10.5, 11.8]}
+ )
+ dfX = df.__dataframe__()
+
+ assert dfX.num_columns() == 3
+ assert dfX.num_rows() == 3
+ assert dfX.num_chunks() == 1
+ assert list(dfX.column_names()) == ["x", "y", "z"]
+ assert list(dfX.select_columns((0, 2)).column_names()) == list(
+ dfX.select_columns_by_name(("x", "z")).column_names()
+ )
+
+
+@pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])
+def test_df_get_chunks(size, n_chunks, df_from_dict):
+ df = df_from_dict({"x": list(range(size))})
+ dfX = df.__dataframe__()
+ chunks = list(dfX.get_chunks(n_chunks))
+ assert len(chunks) == n_chunks
+ assert sum(chunk.num_rows() for chunk in chunks) == size
+
+
+@pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])
+def test_column_get_chunks(size, n_chunks, df_from_dict):
+ df = df_from_dict({"x": list(range(size))})
+ dfX = df.__dataframe__()
+ chunks = list(dfX.get_column(0).get_chunks(n_chunks))
+ assert len(chunks) == n_chunks
+ assert sum(chunk.size() for chunk in chunks) == size
+
+
+def test_get_columns(df_from_dict):
+ df = df_from_dict({"a": [0, 1], "b": [2.5, 3.5]})
+ dfX = df.__dataframe__()
+ for colX in dfX.get_columns():
+ assert colX.size() == 2
+ assert colX.num_chunks() == 1
+ # for meanings of dtype[0] see the spec; we cannot import the spec here as this
+ # file is expected to be vendored *anywhere*
+ assert dfX.get_column(0).dtype[0] == 0 # INT
+ assert dfX.get_column(1).dtype[0] == 2 # FLOAT
+
+
+def test_buffer(df_from_dict):
+ arr = [0, 1, -1]
+ df = df_from_dict({"a": arr})
+ dfX = df.__dataframe__()
+ colX = dfX.get_column(0)
+ bufX = colX.get_buffers()
+
+ dataBuf, dataDtype = bufX["data"]
+
+ assert dataBuf.bufsize > 0
+ assert dataBuf.ptr != 0
+ device, _ = dataBuf.__dlpack_device__()
+
+ # for meanings of dtype[0] see the spec; we cannot import the spec here as this
+ # file is expected to be vendored *anywhere*
+ assert dataDtype[0] == 0 # INT
+
+ if device == 1: # CPU-only as we're going to directly read memory here
+ bitwidth = dataDtype[1]
+ ctype = {
+ 8: ctypes.c_int8,
+ 16: ctypes.c_int16,
+ 32: ctypes.c_int32,
+ 64: ctypes.c_int64,
+ }[bitwidth]
+
+ for idx, truth in enumerate(arr):
+ val = ctype.from_address(dataBuf.ptr + idx * (bitwidth // 8)).value
+ assert val == truth, f"Buffer at index {idx} mismatch"
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/test_utils.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a47bc2752ff32f5eb7630a3960e7611242cb73e3
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/interchange/test_utils.py
@@ -0,0 +1,89 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas.core.interchange.utils import dtype_to_arrow_c_fmt
+
+# TODO: use ArrowSchema to get reference C-string.
+# At the time, there is no way to access ArrowSchema holding a type format string
+# from python. The only way to access it is to export the structure to a C-pointer,
+# see DataType._export_to_c() method defined in
+# https://github.com/apache/arrow/blob/master/python/pyarrow/types.pxi
+
+
+@pytest.mark.parametrize(
+ "pandas_dtype, c_string",
+ [
+ (np.dtype("bool"), "b"),
+ (np.dtype("int8"), "c"),
+ (np.dtype("uint8"), "C"),
+ (np.dtype("int16"), "s"),
+ (np.dtype("uint16"), "S"),
+ (np.dtype("int32"), "i"),
+ (np.dtype("uint32"), "I"),
+ (np.dtype("int64"), "l"),
+ (np.dtype("uint64"), "L"),
+ (np.dtype("float16"), "e"),
+ (np.dtype("float32"), "f"),
+ (np.dtype("float64"), "g"),
+ (pd.Series(["a"]).dtype, "u"),
+ (
+ pd.Series([0]).astype("datetime64[ns]").dtype,
+ "tsn:",
+ ),
+ (pd.CategoricalDtype(["a"]), "l"),
+ (np.dtype("O"), "u"),
+ ],
+)
+def test_dtype_to_arrow_c_fmt(pandas_dtype, c_string): # PR01
+ """Test ``dtype_to_arrow_c_fmt`` utility function."""
+ assert dtype_to_arrow_c_fmt(pandas_dtype) == c_string
+
+
+@pytest.mark.parametrize(
+ "pa_dtype, args_kwargs, c_string",
+ [
+ ["null", {}, "n"],
+ ["bool_", {}, "b"],
+ ["uint8", {}, "C"],
+ ["uint16", {}, "S"],
+ ["uint32", {}, "I"],
+ ["uint64", {}, "L"],
+ ["int8", {}, "c"],
+ ["int16", {}, "S"],
+ ["int32", {}, "i"],
+ ["int64", {}, "l"],
+ ["float16", {}, "e"],
+ ["float32", {}, "f"],
+ ["float64", {}, "g"],
+ ["string", {}, "u"],
+ ["binary", {}, "z"],
+ ["time32", ("s",), "tts"],
+ ["time32", ("ms",), "ttm"],
+ ["time64", ("us",), "ttu"],
+ ["time64", ("ns",), "ttn"],
+ ["date32", {}, "tdD"],
+ ["date64", {}, "tdm"],
+ ["timestamp", {"unit": "s"}, "tss:"],
+ ["timestamp", {"unit": "ms"}, "tsm:"],
+ ["timestamp", {"unit": "us"}, "tsu:"],
+ ["timestamp", {"unit": "ns"}, "tsn:"],
+ ["timestamp", {"unit": "ns", "tz": "UTC"}, "tsn:UTC"],
+ ["duration", ("s",), "tDs"],
+ ["duration", ("ms",), "tDm"],
+ ["duration", ("us",), "tDu"],
+ ["duration", ("ns",), "tDn"],
+ ["decimal128", {"precision": 4, "scale": 2}, "d:4,2"],
+ ],
+)
+def test_dtype_to_arrow_c_fmt_arrowdtype(pa_dtype, args_kwargs, c_string):
+ # GH 52323
+ pa = pytest.importorskip("pyarrow")
+ if not args_kwargs:
+ pa_type = getattr(pa, pa_dtype)()
+ elif isinstance(args_kwargs, tuple):
+ pa_type = getattr(pa, pa_dtype)(*args_kwargs)
+ else:
+ pa_type = getattr(pa, pa_dtype)(**args_kwargs)
+ arrow_type = pd.ArrowDtype(pa_type)
+ assert dtype_to_arrow_c_fmt(arrow_type) == c_string
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd5c556f064598f9379a19d2bf54594155a825f5
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/__init__.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/test_api.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/test_api.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d105b4bfee0aeba4d3808c8c6cce797e2df90d1f
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/test_api.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/test_internals.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/test_internals.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d841026b770af6892768b57c86fbdf8e3647600
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/test_internals.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/test_managers.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/test_managers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e2c467c7785b03ec20bbc06baf549c26b890f17
Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/__pycache__/test_managers.cpython-312.pyc differ
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/test_api.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/test_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cd6c718260ea4ca3206d2c58466b5b6c62b3e30
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/test_api.py
@@ -0,0 +1,53 @@
+"""
+Tests for the pseudo-public API implemented in internals/api.py and exposed
+in core.internals
+"""
+
+import pandas as pd
+from pandas.core import internals
+from pandas.core.internals import api
+
+
+def test_internals_api():
+ assert internals.make_block is api.make_block
+
+
+def test_namespace():
+ # SUBJECT TO CHANGE
+
+ modules = [
+ "blocks",
+ "concat",
+ "managers",
+ "construction",
+ "array_manager",
+ "base",
+ "api",
+ "ops",
+ ]
+ expected = [
+ "Block",
+ "DatetimeTZBlock",
+ "ExtensionBlock",
+ "make_block",
+ "DataManager",
+ "ArrayManager",
+ "BlockManager",
+ "SingleDataManager",
+ "SingleBlockManager",
+ "SingleArrayManager",
+ "concatenate_managers",
+ "create_block_manager_from_blocks",
+ ]
+
+ result = [x for x in dir(internals) if not x.startswith("__")]
+ assert set(result) == set(expected + modules)
+
+
+def test_make_block_2d_with_dti():
+ # GH#41168
+ dti = pd.date_range("2012", periods=3, tz="UTC")
+ blk = api.make_block(dti, placement=[0])
+
+ assert blk.shape == (1, 3)
+ assert blk.values.shape == (1, 3)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/test_internals.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/test_internals.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b23829a554aa10a71682331bdc356a566d14d21
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/test_internals.py
@@ -0,0 +1,1442 @@
+from datetime import (
+ date,
+ datetime,
+)
+import itertools
+import re
+
+import numpy as np
+import pytest
+
+from pandas._libs.internals import BlockPlacement
+from pandas.compat import IS64
+import pandas.util._test_decorators as td
+
+from pandas.core.dtypes.common import is_scalar
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ IntervalIndex,
+ Series,
+ Timedelta,
+ Timestamp,
+ period_range,
+)
+import pandas._testing as tm
+import pandas.core.algorithms as algos
+from pandas.core.arrays import (
+ DatetimeArray,
+ SparseArray,
+ TimedeltaArray,
+)
+from pandas.core.internals import (
+ BlockManager,
+ SingleBlockManager,
+ make_block,
+)
+from pandas.core.internals.blocks import (
+ ensure_block_shape,
+ maybe_coerce_values,
+ new_block,
+)
+
+# this file contains BlockManager specific tests
+# TODO(ArrayManager) factor out interleave_dtype tests
+pytestmark = td.skip_array_manager_invalid_test
+
+
+@pytest.fixture(params=[new_block, make_block])
+def block_maker(request):
+ """
+ Fixture to test both the internal new_block and pseudo-public make_block.
+ """
+ return request.param
+
+
+@pytest.fixture
+def mgr():
+ return create_mgr(
+ "a: f8; b: object; c: f8; d: object; e: f8;"
+ "f: bool; g: i8; h: complex; i: datetime-1; j: datetime-2;"
+ "k: M8[ns, US/Eastern]; l: M8[ns, CET];"
+ )
+
+
+def assert_block_equal(left, right):
+ tm.assert_numpy_array_equal(left.values, right.values)
+ assert left.dtype == right.dtype
+ assert isinstance(left.mgr_locs, BlockPlacement)
+ assert isinstance(right.mgr_locs, BlockPlacement)
+ tm.assert_numpy_array_equal(left.mgr_locs.as_array, right.mgr_locs.as_array)
+
+
+def get_numeric_mat(shape):
+ arr = np.arange(shape[0])
+ return np.lib.stride_tricks.as_strided(
+ x=arr, shape=shape, strides=(arr.itemsize,) + (0,) * (len(shape) - 1)
+ ).copy()
+
+
+N = 10
+
+
+def create_block(typestr, placement, item_shape=None, num_offset=0, maker=new_block):
+ """
+ Supported typestr:
+
+ * float, f8, f4, f2
+ * int, i8, i4, i2, i1
+ * uint, u8, u4, u2, u1
+ * complex, c16, c8
+ * bool
+ * object, string, O
+ * datetime, dt, M8[ns], M8[ns, tz]
+ * timedelta, td, m8[ns]
+ * sparse (SparseArray with fill_value=0.0)
+ * sparse_na (SparseArray with fill_value=np.nan)
+ * category, category2
+
+ """
+ placement = BlockPlacement(placement)
+ num_items = len(placement)
+
+ if item_shape is None:
+ item_shape = (N,)
+
+ shape = (num_items,) + item_shape
+
+ mat = get_numeric_mat(shape)
+
+ if typestr in (
+ "float",
+ "f8",
+ "f4",
+ "f2",
+ "int",
+ "i8",
+ "i4",
+ "i2",
+ "i1",
+ "uint",
+ "u8",
+ "u4",
+ "u2",
+ "u1",
+ ):
+ values = mat.astype(typestr) + num_offset
+ elif typestr in ("complex", "c16", "c8"):
+ values = 1.0j * (mat.astype(typestr) + num_offset)
+ elif typestr in ("object", "string", "O"):
+ values = np.reshape([f"A{i:d}" for i in mat.ravel() + num_offset], shape)
+ elif typestr in ("b", "bool"):
+ values = np.ones(shape, dtype=np.bool_)
+ elif typestr in ("datetime", "dt", "M8[ns]"):
+ values = (mat * 1e9).astype("M8[ns]")
+ elif typestr.startswith("M8[ns"):
+ # datetime with tz
+ m = re.search(r"M8\[ns,\s*(\w+\/?\w*)\]", typestr)
+ assert m is not None, f"incompatible typestr -> {typestr}"
+ tz = m.groups()[0]
+ assert num_items == 1, "must have only 1 num items for a tz-aware"
+ values = DatetimeIndex(np.arange(N) * 10**9, tz=tz)._data
+ values = ensure_block_shape(values, ndim=len(shape))
+ elif typestr in ("timedelta", "td", "m8[ns]"):
+ values = (mat * 1).astype("m8[ns]")
+ elif typestr in ("category",):
+ values = Categorical([1, 1, 2, 2, 3, 3, 3, 3, 4, 4])
+ elif typestr in ("category2",):
+ values = Categorical(["a", "a", "a", "a", "b", "b", "c", "c", "c", "d"])
+ elif typestr in ("sparse", "sparse_na"):
+ if shape[-1] != 10:
+ # We also are implicitly assuming this in the category cases above
+ raise NotImplementedError
+
+ assert all(s == 1 for s in shape[:-1])
+ if typestr.endswith("_na"):
+ fill_value = np.nan
+ else:
+ fill_value = 0.0
+ values = SparseArray(
+ [fill_value, fill_value, 1, 2, 3, fill_value, 4, 5, fill_value, 6],
+ fill_value=fill_value,
+ )
+ arr = values.sp_values.view()
+ arr += num_offset - 1
+ else:
+ raise ValueError(f'Unsupported typestr: "{typestr}"')
+
+ values = maybe_coerce_values(values)
+ return maker(values, placement=placement, ndim=len(shape))
+
+
+def create_single_mgr(typestr, num_rows=None):
+ if num_rows is None:
+ num_rows = N
+
+ return SingleBlockManager(
+ create_block(typestr, placement=slice(0, num_rows), item_shape=()),
+ Index(np.arange(num_rows)),
+ )
+
+
+def create_mgr(descr, item_shape=None):
+ """
+ Construct BlockManager from string description.
+
+ String description syntax looks similar to np.matrix initializer. It looks
+ like this::
+
+ a,b,c: f8; d,e,f: i8
+
+ Rules are rather simple:
+
+ * see list of supported datatypes in `create_block` method
+ * components are semicolon-separated
+ * each component is `NAME,NAME,NAME: DTYPE_ID`
+ * whitespace around colons & semicolons are removed
+ * components with same DTYPE_ID are combined into single block
+ * to force multiple blocks with same dtype, use '-SUFFIX'::
+
+ 'a:f8-1; b:f8-2; c:f8-foobar'
+
+ """
+ if item_shape is None:
+ item_shape = (N,)
+
+ offset = 0
+ mgr_items = []
+ block_placements = {}
+ for d in descr.split(";"):
+ d = d.strip()
+ if not len(d):
+ continue
+ names, blockstr = d.partition(":")[::2]
+ blockstr = blockstr.strip()
+ names = names.strip().split(",")
+
+ mgr_items.extend(names)
+ placement = list(np.arange(len(names)) + offset)
+ try:
+ block_placements[blockstr].extend(placement)
+ except KeyError:
+ block_placements[blockstr] = placement
+ offset += len(names)
+
+ mgr_items = Index(mgr_items)
+
+ blocks = []
+ num_offset = 0
+ for blockstr, placement in block_placements.items():
+ typestr = blockstr.split("-")[0]
+ blocks.append(
+ create_block(
+ typestr, placement, item_shape=item_shape, num_offset=num_offset
+ )
+ )
+ num_offset += len(placement)
+
+ sblocks = sorted(blocks, key=lambda b: b.mgr_locs[0])
+ return BlockManager(
+ tuple(sblocks),
+ [mgr_items] + [Index(np.arange(n)) for n in item_shape],
+ )
+
+
+@pytest.fixture
+def fblock():
+ return create_block("float", [0, 2, 4])
+
+
+class TestBlock:
+ def test_constructor(self):
+ int32block = create_block("i4", [0])
+ assert int32block.dtype == np.int32
+
+ @pytest.mark.parametrize(
+ "typ, data",
+ [
+ ["float", [0, 2, 4]],
+ ["complex", [7]],
+ ["object", [1, 3]],
+ ["bool", [5]],
+ ],
+ )
+ def test_pickle(self, typ, data):
+ blk = create_block(typ, data)
+ assert_block_equal(tm.round_trip_pickle(blk), blk)
+
+ def test_mgr_locs(self, fblock):
+ assert isinstance(fblock.mgr_locs, BlockPlacement)
+ tm.assert_numpy_array_equal(
+ fblock.mgr_locs.as_array, np.array([0, 2, 4], dtype=np.intp)
+ )
+
+ def test_attrs(self, fblock):
+ assert fblock.shape == fblock.values.shape
+ assert fblock.dtype == fblock.values.dtype
+ assert len(fblock) == len(fblock.values)
+
+ def test_copy(self, fblock):
+ cop = fblock.copy()
+ assert cop is not fblock
+ assert_block_equal(fblock, cop)
+
+ def test_delete(self, fblock):
+ newb = fblock.copy()
+ locs = newb.mgr_locs
+ nb = newb.delete(0)[0]
+ assert newb.mgr_locs is locs
+
+ assert nb is not newb
+
+ tm.assert_numpy_array_equal(
+ nb.mgr_locs.as_array, np.array([2, 4], dtype=np.intp)
+ )
+ assert not (newb.values[0] == 1).all()
+ assert (nb.values[0] == 1).all()
+
+ newb = fblock.copy()
+ locs = newb.mgr_locs
+ nb = newb.delete(1)
+ assert len(nb) == 2
+ assert newb.mgr_locs is locs
+
+ tm.assert_numpy_array_equal(
+ nb[0].mgr_locs.as_array, np.array([0], dtype=np.intp)
+ )
+ tm.assert_numpy_array_equal(
+ nb[1].mgr_locs.as_array, np.array([4], dtype=np.intp)
+ )
+ assert not (newb.values[1] == 2).all()
+ assert (nb[1].values[0] == 2).all()
+
+ newb = fblock.copy()
+ nb = newb.delete(2)
+ assert len(nb) == 1
+ tm.assert_numpy_array_equal(
+ nb[0].mgr_locs.as_array, np.array([0, 2], dtype=np.intp)
+ )
+ assert (nb[0].values[1] == 1).all()
+
+ newb = fblock.copy()
+
+ with pytest.raises(IndexError, match=None):
+ newb.delete(3)
+
+ def test_delete_datetimelike(self):
+ # dont use np.delete on values, as that will coerce from DTA/TDA to ndarray
+ arr = np.arange(20, dtype="i8").reshape(5, 4).view("m8[ns]")
+ df = DataFrame(arr)
+ blk = df._mgr.blocks[0]
+ assert isinstance(blk.values, TimedeltaArray)
+
+ nb = blk.delete(1)
+ assert len(nb) == 2
+ assert isinstance(nb[0].values, TimedeltaArray)
+ assert isinstance(nb[1].values, TimedeltaArray)
+
+ df = DataFrame(arr.view("M8[ns]"))
+ blk = df._mgr.blocks[0]
+ assert isinstance(blk.values, DatetimeArray)
+
+ nb = blk.delete([1, 3])
+ assert len(nb) == 2
+ assert isinstance(nb[0].values, DatetimeArray)
+ assert isinstance(nb[1].values, DatetimeArray)
+
+ def test_split(self):
+ # GH#37799
+ values = np.random.default_rng(2).standard_normal((3, 4))
+ blk = new_block(values, placement=BlockPlacement([3, 1, 6]), ndim=2)
+ result = blk._split()
+
+ # check that we get views, not copies
+ values[:] = -9999
+ assert (blk.values == -9999).all()
+
+ assert len(result) == 3
+ expected = [
+ new_block(values[[0]], placement=BlockPlacement([3]), ndim=2),
+ new_block(values[[1]], placement=BlockPlacement([1]), ndim=2),
+ new_block(values[[2]], placement=BlockPlacement([6]), ndim=2),
+ ]
+ for res, exp in zip(result, expected):
+ assert_block_equal(res, exp)
+
+
+class TestBlockManager:
+ def test_attrs(self):
+ mgr = create_mgr("a,b,c: f8-1; d,e,f: f8-2")
+ assert mgr.nblocks == 2
+ assert len(mgr) == 6
+
+ def test_duplicate_ref_loc_failure(self):
+ tmp_mgr = create_mgr("a:bool; a: f8")
+
+ axes, blocks = tmp_mgr.axes, tmp_mgr.blocks
+
+ blocks[0].mgr_locs = BlockPlacement(np.array([0]))
+ blocks[1].mgr_locs = BlockPlacement(np.array([0]))
+
+ # test trying to create block manager with overlapping ref locs
+
+ msg = "Gaps in blk ref_locs"
+
+ with pytest.raises(AssertionError, match=msg):
+ mgr = BlockManager(blocks, axes)
+ mgr._rebuild_blknos_and_blklocs()
+
+ blocks[0].mgr_locs = BlockPlacement(np.array([0]))
+ blocks[1].mgr_locs = BlockPlacement(np.array([1]))
+ mgr = BlockManager(blocks, axes)
+ mgr.iget(1)
+
+ def test_pickle(self, mgr):
+ mgr2 = tm.round_trip_pickle(mgr)
+ tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))
+
+ # GH2431
+ assert hasattr(mgr2, "_is_consolidated")
+ assert hasattr(mgr2, "_known_consolidated")
+
+ # reset to False on load
+ assert not mgr2._is_consolidated
+ assert not mgr2._known_consolidated
+
+ @pytest.mark.parametrize("mgr_string", ["a,a,a:f8", "a: f8; a: i8"])
+ def test_non_unique_pickle(self, mgr_string):
+ mgr = create_mgr(mgr_string)
+ mgr2 = tm.round_trip_pickle(mgr)
+ tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))
+
+ def test_categorical_block_pickle(self):
+ mgr = create_mgr("a: category")
+ mgr2 = tm.round_trip_pickle(mgr)
+ tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))
+
+ smgr = create_single_mgr("category")
+ smgr2 = tm.round_trip_pickle(smgr)
+ tm.assert_series_equal(Series(smgr), Series(smgr2))
+
+ def test_iget(self):
+ cols = Index(list("abc"))
+ values = np.random.default_rng(2).random((3, 3))
+ block = new_block(
+ values=values.copy(),
+ placement=BlockPlacement(np.arange(3, dtype=np.intp)),
+ ndim=values.ndim,
+ )
+ mgr = BlockManager(blocks=(block,), axes=[cols, Index(np.arange(3))])
+
+ tm.assert_almost_equal(mgr.iget(0).internal_values(), values[0])
+ tm.assert_almost_equal(mgr.iget(1).internal_values(), values[1])
+ tm.assert_almost_equal(mgr.iget(2).internal_values(), values[2])
+
+ def test_set(self):
+ mgr = create_mgr("a,b,c: int", item_shape=(3,))
+
+ mgr.insert(len(mgr.items), "d", np.array(["foo"] * 3))
+ mgr.iset(1, np.array(["bar"] * 3))
+ tm.assert_numpy_array_equal(mgr.iget(0).internal_values(), np.array([0] * 3))
+ tm.assert_numpy_array_equal(
+ mgr.iget(1).internal_values(), np.array(["bar"] * 3, dtype=np.object_)
+ )
+ tm.assert_numpy_array_equal(mgr.iget(2).internal_values(), np.array([2] * 3))
+ tm.assert_numpy_array_equal(
+ mgr.iget(3).internal_values(), np.array(["foo"] * 3, dtype=np.object_)
+ )
+
+ def test_set_change_dtype(self, mgr):
+ mgr.insert(len(mgr.items), "baz", np.zeros(N, dtype=bool))
+
+ mgr.iset(mgr.items.get_loc("baz"), np.repeat("foo", N))
+ idx = mgr.items.get_loc("baz")
+ assert mgr.iget(idx).dtype == np.object_
+
+ mgr2 = mgr.consolidate()
+ mgr2.iset(mgr2.items.get_loc("baz"), np.repeat("foo", N))
+ idx = mgr2.items.get_loc("baz")
+ assert mgr2.iget(idx).dtype == np.object_
+
+ mgr2.insert(
+ len(mgr2.items),
+ "quux",
+ np.random.default_rng(2).standard_normal(N).astype(int),
+ )
+ idx = mgr2.items.get_loc("quux")
+ assert mgr2.iget(idx).dtype == np.dtype(int)
+
+ mgr2.iset(
+ mgr2.items.get_loc("quux"), np.random.default_rng(2).standard_normal(N)
+ )
+ assert mgr2.iget(idx).dtype == np.float64
+
+ def test_copy(self, mgr):
+ cp = mgr.copy(deep=False)
+ for blk, cp_blk in zip(mgr.blocks, cp.blocks):
+ # view assertion
+ tm.assert_equal(cp_blk.values, blk.values)
+ if isinstance(blk.values, np.ndarray):
+ assert cp_blk.values.base is blk.values.base
+ else:
+ # DatetimeTZBlock has DatetimeIndex values
+ assert cp_blk.values._ndarray.base is blk.values._ndarray.base
+
+ # copy(deep=True) consolidates, so the block-wise assertions will
+ # fail is mgr is not consolidated
+ mgr._consolidate_inplace()
+ cp = mgr.copy(deep=True)
+ for blk, cp_blk in zip(mgr.blocks, cp.blocks):
+ bvals = blk.values
+ cpvals = cp_blk.values
+
+ tm.assert_equal(cpvals, bvals)
+
+ if isinstance(cpvals, np.ndarray):
+ lbase = cpvals.base
+ rbase = bvals.base
+ else:
+ lbase = cpvals._ndarray.base
+ rbase = bvals._ndarray.base
+
+ # copy assertion we either have a None for a base or in case of
+ # some blocks it is an array (e.g. datetimetz), but was copied
+ if isinstance(cpvals, DatetimeArray):
+ assert (lbase is None and rbase is None) or (lbase is not rbase)
+ elif not isinstance(cpvals, np.ndarray):
+ assert lbase is not rbase
+ else:
+ assert lbase is None and rbase is None
+
+ def test_sparse(self):
+ mgr = create_mgr("a: sparse-1; b: sparse-2")
+ assert mgr.as_array().dtype == np.float64
+
+ def test_sparse_mixed(self):
+ mgr = create_mgr("a: sparse-1; b: sparse-2; c: f8")
+ assert len(mgr.blocks) == 3
+ assert isinstance(mgr, BlockManager)
+
+ @pytest.mark.parametrize(
+ "mgr_string, dtype",
+ [("c: f4; d: f2", np.float32), ("c: f4; d: f2; e: f8", np.float64)],
+ )
+ def test_as_array_float(self, mgr_string, dtype):
+ mgr = create_mgr(mgr_string)
+ assert mgr.as_array().dtype == dtype
+
+ @pytest.mark.parametrize(
+ "mgr_string, dtype",
+ [
+ ("a: bool-1; b: bool-2", np.bool_),
+ ("a: i8-1; b: i8-2; c: i4; d: i2; e: u1", np.int64),
+ ("c: i4; d: i2; e: u1", np.int32),
+ ],
+ )
+ def test_as_array_int_bool(self, mgr_string, dtype):
+ mgr = create_mgr(mgr_string)
+ assert mgr.as_array().dtype == dtype
+
+ def test_as_array_datetime(self):
+ mgr = create_mgr("h: datetime-1; g: datetime-2")
+ assert mgr.as_array().dtype == "M8[ns]"
+
+ def test_as_array_datetime_tz(self):
+ mgr = create_mgr("h: M8[ns, US/Eastern]; g: M8[ns, CET]")
+ assert mgr.iget(0).dtype == "datetime64[ns, US/Eastern]"
+ assert mgr.iget(1).dtype == "datetime64[ns, CET]"
+ assert mgr.as_array().dtype == "object"
+
+ @pytest.mark.parametrize("t", ["float16", "float32", "float64", "int32", "int64"])
+ def test_astype(self, t):
+ # coerce all
+ mgr = create_mgr("c: f4; d: f2; e: f8")
+
+ t = np.dtype(t)
+ tmgr = mgr.astype(t)
+ assert tmgr.iget(0).dtype.type == t
+ assert tmgr.iget(1).dtype.type == t
+ assert tmgr.iget(2).dtype.type == t
+
+ # mixed
+ mgr = create_mgr("a,b: object; c: bool; d: datetime; e: f4; f: f2; g: f8")
+
+ t = np.dtype(t)
+ tmgr = mgr.astype(t, errors="ignore")
+ assert tmgr.iget(2).dtype.type == t
+ assert tmgr.iget(4).dtype.type == t
+ assert tmgr.iget(5).dtype.type == t
+ assert tmgr.iget(6).dtype.type == t
+
+ assert tmgr.iget(0).dtype.type == np.object_
+ assert tmgr.iget(1).dtype.type == np.object_
+ if t != np.int64:
+ assert tmgr.iget(3).dtype.type == np.datetime64
+ else:
+ assert tmgr.iget(3).dtype.type == t
+
+ def test_convert(self):
+ def _compare(old_mgr, new_mgr):
+ """compare the blocks, numeric compare ==, object don't"""
+ old_blocks = set(old_mgr.blocks)
+ new_blocks = set(new_mgr.blocks)
+ assert len(old_blocks) == len(new_blocks)
+
+ # compare non-numeric
+ for b in old_blocks:
+ found = False
+ for nb in new_blocks:
+ if (b.values == nb.values).all():
+ found = True
+ break
+ assert found
+
+ for b in new_blocks:
+ found = False
+ for ob in old_blocks:
+ if (b.values == ob.values).all():
+ found = True
+ break
+ assert found
+
+ # noops
+ mgr = create_mgr("f: i8; g: f8")
+ new_mgr = mgr.convert(copy=True)
+ _compare(mgr, new_mgr)
+
+ # convert
+ mgr = create_mgr("a,b,foo: object; f: i8; g: f8")
+ mgr.iset(0, np.array(["1"] * N, dtype=np.object_))
+ mgr.iset(1, np.array(["2."] * N, dtype=np.object_))
+ mgr.iset(2, np.array(["foo."] * N, dtype=np.object_))
+ new_mgr = mgr.convert(copy=True)
+ assert new_mgr.iget(0).dtype == np.object_
+ assert new_mgr.iget(1).dtype == np.object_
+ assert new_mgr.iget(2).dtype == np.object_
+ assert new_mgr.iget(3).dtype == np.int64
+ assert new_mgr.iget(4).dtype == np.float64
+
+ mgr = create_mgr(
+ "a,b,foo: object; f: i4; bool: bool; dt: datetime; i: i8; g: f8; h: f2"
+ )
+ mgr.iset(0, np.array(["1"] * N, dtype=np.object_))
+ mgr.iset(1, np.array(["2."] * N, dtype=np.object_))
+ mgr.iset(2, np.array(["foo."] * N, dtype=np.object_))
+ new_mgr = mgr.convert(copy=True)
+ assert new_mgr.iget(0).dtype == np.object_
+ assert new_mgr.iget(1).dtype == np.object_
+ assert new_mgr.iget(2).dtype == np.object_
+ assert new_mgr.iget(3).dtype == np.int32
+ assert new_mgr.iget(4).dtype == np.bool_
+ assert new_mgr.iget(5).dtype.type, np.datetime64
+ assert new_mgr.iget(6).dtype == np.int64
+ assert new_mgr.iget(7).dtype == np.float64
+ assert new_mgr.iget(8).dtype == np.float16
+
+ def test_interleave(self):
+ # self
+ for dtype in ["f8", "i8", "object", "bool", "complex", "M8[ns]", "m8[ns]"]:
+ mgr = create_mgr(f"a: {dtype}")
+ assert mgr.as_array().dtype == dtype
+ mgr = create_mgr(f"a: {dtype}; b: {dtype}")
+ assert mgr.as_array().dtype == dtype
+
+ @pytest.mark.parametrize(
+ "mgr_string, dtype",
+ [
+ ("a: category", "i8"),
+ ("a: category; b: category", "i8"),
+ ("a: category; b: category2", "object"),
+ ("a: category2", "object"),
+ ("a: category2; b: category2", "object"),
+ ("a: f8", "f8"),
+ ("a: f8; b: i8", "f8"),
+ ("a: f4; b: i8", "f8"),
+ ("a: f4; b: i8; d: object", "object"),
+ ("a: bool; b: i8", "object"),
+ ("a: complex", "complex"),
+ ("a: f8; b: category", "object"),
+ ("a: M8[ns]; b: category", "object"),
+ ("a: M8[ns]; b: bool", "object"),
+ ("a: M8[ns]; b: i8", "object"),
+ ("a: m8[ns]; b: bool", "object"),
+ ("a: m8[ns]; b: i8", "object"),
+ ("a: M8[ns]; b: m8[ns]", "object"),
+ ],
+ )
+ def test_interleave_dtype(self, mgr_string, dtype):
+ # will be converted according the actual dtype of the underlying
+ mgr = create_mgr("a: category")
+ assert mgr.as_array().dtype == "i8"
+ mgr = create_mgr("a: category; b: category2")
+ assert mgr.as_array().dtype == "object"
+ mgr = create_mgr("a: category2")
+ assert mgr.as_array().dtype == "object"
+
+ # combinations
+ mgr = create_mgr("a: f8")
+ assert mgr.as_array().dtype == "f8"
+ mgr = create_mgr("a: f8; b: i8")
+ assert mgr.as_array().dtype == "f8"
+ mgr = create_mgr("a: f4; b: i8")
+ assert mgr.as_array().dtype == "f8"
+ mgr = create_mgr("a: f4; b: i8; d: object")
+ assert mgr.as_array().dtype == "object"
+ mgr = create_mgr("a: bool; b: i8")
+ assert mgr.as_array().dtype == "object"
+ mgr = create_mgr("a: complex")
+ assert mgr.as_array().dtype == "complex"
+ mgr = create_mgr("a: f8; b: category")
+ assert mgr.as_array().dtype == "f8"
+ mgr = create_mgr("a: M8[ns]; b: category")
+ assert mgr.as_array().dtype == "object"
+ mgr = create_mgr("a: M8[ns]; b: bool")
+ assert mgr.as_array().dtype == "object"
+ mgr = create_mgr("a: M8[ns]; b: i8")
+ assert mgr.as_array().dtype == "object"
+ mgr = create_mgr("a: m8[ns]; b: bool")
+ assert mgr.as_array().dtype == "object"
+ mgr = create_mgr("a: m8[ns]; b: i8")
+ assert mgr.as_array().dtype == "object"
+ mgr = create_mgr("a: M8[ns]; b: m8[ns]")
+ assert mgr.as_array().dtype == "object"
+
+ def test_consolidate_ordering_issues(self, mgr):
+ mgr.iset(mgr.items.get_loc("f"), np.random.default_rng(2).standard_normal(N))
+ mgr.iset(mgr.items.get_loc("d"), np.random.default_rng(2).standard_normal(N))
+ mgr.iset(mgr.items.get_loc("b"), np.random.default_rng(2).standard_normal(N))
+ mgr.iset(mgr.items.get_loc("g"), np.random.default_rng(2).standard_normal(N))
+ mgr.iset(mgr.items.get_loc("h"), np.random.default_rng(2).standard_normal(N))
+
+ # we have datetime/tz blocks in mgr
+ cons = mgr.consolidate()
+ assert cons.nblocks == 4
+ cons = mgr.consolidate().get_numeric_data()
+ assert cons.nblocks == 1
+ assert isinstance(cons.blocks[0].mgr_locs, BlockPlacement)
+ tm.assert_numpy_array_equal(
+ cons.blocks[0].mgr_locs.as_array, np.arange(len(cons.items), dtype=np.intp)
+ )
+
+ def test_reindex_items(self):
+ # mgr is not consolidated, f8 & f8-2 blocks
+ mgr = create_mgr("a: f8; b: i8; c: f8; d: i8; e: f8; f: bool; g: f8-2")
+
+ reindexed = mgr.reindex_axis(["g", "c", "a", "d"], axis=0)
+ # reindex_axis does not consolidate_inplace, as that risks failing to
+ # invalidate _item_cache
+ assert not reindexed.is_consolidated()
+
+ tm.assert_index_equal(reindexed.items, Index(["g", "c", "a", "d"]))
+ tm.assert_almost_equal(
+ mgr.iget(6).internal_values(), reindexed.iget(0).internal_values()
+ )
+ tm.assert_almost_equal(
+ mgr.iget(2).internal_values(), reindexed.iget(1).internal_values()
+ )
+ tm.assert_almost_equal(
+ mgr.iget(0).internal_values(), reindexed.iget(2).internal_values()
+ )
+ tm.assert_almost_equal(
+ mgr.iget(3).internal_values(), reindexed.iget(3).internal_values()
+ )
+
+ def test_get_numeric_data(self, using_copy_on_write):
+ mgr = create_mgr(
+ "int: int; float: float; complex: complex;"
+ "str: object; bool: bool; obj: object; dt: datetime",
+ item_shape=(3,),
+ )
+ mgr.iset(5, np.array([1, 2, 3], dtype=np.object_))
+
+ numeric = mgr.get_numeric_data()
+ tm.assert_index_equal(numeric.items, Index(["int", "float", "complex", "bool"]))
+ tm.assert_almost_equal(
+ mgr.iget(mgr.items.get_loc("float")).internal_values(),
+ numeric.iget(numeric.items.get_loc("float")).internal_values(),
+ )
+
+ # Check sharing
+ numeric.iset(
+ numeric.items.get_loc("float"),
+ np.array([100.0, 200.0, 300.0]),
+ inplace=True,
+ )
+ if using_copy_on_write:
+ tm.assert_almost_equal(
+ mgr.iget(mgr.items.get_loc("float")).internal_values(),
+ np.array([1.0, 1.0, 1.0]),
+ )
+ else:
+ tm.assert_almost_equal(
+ mgr.iget(mgr.items.get_loc("float")).internal_values(),
+ np.array([100.0, 200.0, 300.0]),
+ )
+
+ numeric2 = mgr.get_numeric_data(copy=True)
+ tm.assert_index_equal(numeric.items, Index(["int", "float", "complex", "bool"]))
+ numeric2.iset(
+ numeric2.items.get_loc("float"),
+ np.array([1000.0, 2000.0, 3000.0]),
+ inplace=True,
+ )
+ if using_copy_on_write:
+ tm.assert_almost_equal(
+ mgr.iget(mgr.items.get_loc("float")).internal_values(),
+ np.array([1.0, 1.0, 1.0]),
+ )
+ else:
+ tm.assert_almost_equal(
+ mgr.iget(mgr.items.get_loc("float")).internal_values(),
+ np.array([100.0, 200.0, 300.0]),
+ )
+
+ def test_get_bool_data(self, using_copy_on_write):
+ mgr = create_mgr(
+ "int: int; float: float; complex: complex;"
+ "str: object; bool: bool; obj: object; dt: datetime",
+ item_shape=(3,),
+ )
+ mgr.iset(6, np.array([True, False, True], dtype=np.object_))
+
+ bools = mgr.get_bool_data()
+ tm.assert_index_equal(bools.items, Index(["bool"]))
+ tm.assert_almost_equal(
+ mgr.iget(mgr.items.get_loc("bool")).internal_values(),
+ bools.iget(bools.items.get_loc("bool")).internal_values(),
+ )
+
+ bools.iset(0, np.array([True, False, True]), inplace=True)
+ if using_copy_on_write:
+ tm.assert_numpy_array_equal(
+ mgr.iget(mgr.items.get_loc("bool")).internal_values(),
+ np.array([True, True, True]),
+ )
+ else:
+ tm.assert_numpy_array_equal(
+ mgr.iget(mgr.items.get_loc("bool")).internal_values(),
+ np.array([True, False, True]),
+ )
+
+ # Check sharing
+ bools2 = mgr.get_bool_data(copy=True)
+ bools2.iset(0, np.array([False, True, False]))
+ if using_copy_on_write:
+ tm.assert_numpy_array_equal(
+ mgr.iget(mgr.items.get_loc("bool")).internal_values(),
+ np.array([True, True, True]),
+ )
+ else:
+ tm.assert_numpy_array_equal(
+ mgr.iget(mgr.items.get_loc("bool")).internal_values(),
+ np.array([True, False, True]),
+ )
+
+ def test_unicode_repr_doesnt_raise(self):
+ repr(create_mgr("b,\u05d0: object"))
+
+ @pytest.mark.parametrize(
+ "mgr_string", ["a,b,c: i8-1; d,e,f: i8-2", "a,a,a: i8-1; b,b,b: i8-2"]
+ )
+ def test_equals(self, mgr_string):
+ # unique items
+ bm1 = create_mgr(mgr_string)
+ bm2 = BlockManager(bm1.blocks[::-1], bm1.axes)
+ assert bm1.equals(bm2)
+
+ @pytest.mark.parametrize(
+ "mgr_string",
+ [
+ "a:i8;b:f8", # basic case
+ "a:i8;b:f8;c:c8;d:b", # many types
+ "a:i8;e:dt;f:td;g:string", # more types
+ "a:i8;b:category;c:category2", # categories
+ "c:sparse;d:sparse_na;b:f8", # sparse
+ ],
+ )
+ def test_equals_block_order_different_dtypes(self, mgr_string):
+ # GH 9330
+ bm = create_mgr(mgr_string)
+ block_perms = itertools.permutations(bm.blocks)
+ for bm_perm in block_perms:
+ bm_this = BlockManager(tuple(bm_perm), bm.axes)
+ assert bm.equals(bm_this)
+ assert bm_this.equals(bm)
+
+ def test_single_mgr_ctor(self):
+ mgr = create_single_mgr("f8", num_rows=5)
+ assert mgr.external_values().tolist() == [0.0, 1.0, 2.0, 3.0, 4.0]
+
+ @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
+ def test_validate_bool_args(self, value):
+ bm1 = create_mgr("a,b,c: i8-1; d,e,f: i8-2")
+
+ msg = (
+ 'For argument "inplace" expected type bool, '
+ f"received type {type(value).__name__}."
+ )
+ with pytest.raises(ValueError, match=msg):
+ bm1.replace_list([1], [2], inplace=value)
+
+ def test_iset_split_block(self):
+ bm = create_mgr("a,b,c: i8; d: f8")
+ bm._iset_split_block(0, np.array([0]))
+ tm.assert_numpy_array_equal(
+ bm.blklocs, np.array([0, 0, 1, 0], dtype="int64" if IS64 else "int32")
+ )
+ # First indexer currently does not have a block associated with it in case
+ tm.assert_numpy_array_equal(
+ bm.blknos, np.array([0, 0, 0, 1], dtype="int64" if IS64 else "int32")
+ )
+ assert len(bm.blocks) == 2
+
+ def test_iset_split_block_values(self):
+ bm = create_mgr("a,b,c: i8; d: f8")
+ bm._iset_split_block(0, np.array([0]), np.array([list(range(10))]))
+ tm.assert_numpy_array_equal(
+ bm.blklocs, np.array([0, 0, 1, 0], dtype="int64" if IS64 else "int32")
+ )
+ # First indexer currently does not have a block associated with it in case
+ tm.assert_numpy_array_equal(
+ bm.blknos, np.array([0, 2, 2, 1], dtype="int64" if IS64 else "int32")
+ )
+ assert len(bm.blocks) == 3
+
+
+def _as_array(mgr):
+ if mgr.ndim == 1:
+ return mgr.external_values()
+ return mgr.as_array().T
+
+
+class TestIndexing:
+ # Nosetests-style data-driven tests.
+ #
+ # This test applies different indexing routines to block managers and
+ # compares the outcome to the result of same operations on np.ndarray.
+ #
+ # NOTE: sparse (SparseBlock with fill_value != np.nan) fail a lot of tests
+ # and are disabled.
+
+ MANAGERS = [
+ create_single_mgr("f8", N),
+ create_single_mgr("i8", N),
+ # 2-dim
+ create_mgr("a,b,c,d,e,f: f8", item_shape=(N,)),
+ create_mgr("a,b,c,d,e,f: i8", item_shape=(N,)),
+ create_mgr("a,b: f8; c,d: i8; e,f: string", item_shape=(N,)),
+ create_mgr("a,b: f8; c,d: i8; e,f: f8", item_shape=(N,)),
+ ]
+
+ @pytest.mark.parametrize("mgr", MANAGERS)
+ def test_get_slice(self, mgr):
+ def assert_slice_ok(mgr, axis, slobj):
+ mat = _as_array(mgr)
+
+ # we maybe using an ndarray to test slicing and
+ # might not be the full length of the axis
+ if isinstance(slobj, np.ndarray):
+ ax = mgr.axes[axis]
+ if len(ax) and len(slobj) and len(slobj) != len(ax):
+ slobj = np.concatenate(
+ [slobj, np.zeros(len(ax) - len(slobj), dtype=bool)]
+ )
+
+ if isinstance(slobj, slice):
+ sliced = mgr.get_slice(slobj, axis=axis)
+ elif (
+ mgr.ndim == 1
+ and axis == 0
+ and isinstance(slobj, np.ndarray)
+ and slobj.dtype == bool
+ ):
+ sliced = mgr.get_rows_with_mask(slobj)
+ else:
+ # BlockManager doesn't support non-slice, SingleBlockManager
+ # doesn't support axis > 0
+ raise TypeError(slobj)
+
+ mat_slobj = (slice(None),) * axis + (slobj,)
+ tm.assert_numpy_array_equal(
+ mat[mat_slobj], _as_array(sliced), check_dtype=False
+ )
+ tm.assert_index_equal(mgr.axes[axis][slobj], sliced.axes[axis])
+
+ assert mgr.ndim <= 2, mgr.ndim
+ for ax in range(mgr.ndim):
+ # slice
+ assert_slice_ok(mgr, ax, slice(None))
+ assert_slice_ok(mgr, ax, slice(3))
+ assert_slice_ok(mgr, ax, slice(100))
+ assert_slice_ok(mgr, ax, slice(1, 4))
+ assert_slice_ok(mgr, ax, slice(3, 0, -2))
+
+ if mgr.ndim < 2:
+ # 2D only support slice objects
+
+ # boolean mask
+ assert_slice_ok(mgr, ax, np.array([], dtype=np.bool_))
+ assert_slice_ok(mgr, ax, np.ones(mgr.shape[ax], dtype=np.bool_))
+ assert_slice_ok(mgr, ax, np.zeros(mgr.shape[ax], dtype=np.bool_))
+
+ if mgr.shape[ax] >= 3:
+ assert_slice_ok(mgr, ax, np.arange(mgr.shape[ax]) % 3 == 0)
+ assert_slice_ok(
+ mgr, ax, np.array([True, True, False], dtype=np.bool_)
+ )
+
+ @pytest.mark.parametrize("mgr", MANAGERS)
+ def test_take(self, mgr):
+ def assert_take_ok(mgr, axis, indexer):
+ mat = _as_array(mgr)
+ taken = mgr.take(indexer, axis)
+ tm.assert_numpy_array_equal(
+ np.take(mat, indexer, axis), _as_array(taken), check_dtype=False
+ )
+ tm.assert_index_equal(mgr.axes[axis].take(indexer), taken.axes[axis])
+
+ for ax in range(mgr.ndim):
+ # take/fancy indexer
+ assert_take_ok(mgr, ax, indexer=np.array([], dtype=np.intp))
+ assert_take_ok(mgr, ax, indexer=np.array([0, 0, 0], dtype=np.intp))
+ assert_take_ok(
+ mgr, ax, indexer=np.array(list(range(mgr.shape[ax])), dtype=np.intp)
+ )
+
+ if mgr.shape[ax] >= 3:
+ assert_take_ok(mgr, ax, indexer=np.array([0, 1, 2], dtype=np.intp))
+ assert_take_ok(mgr, ax, indexer=np.array([-1, -2, -3], dtype=np.intp))
+
+ @pytest.mark.parametrize("mgr", MANAGERS)
+ @pytest.mark.parametrize("fill_value", [None, np.nan, 100.0])
+ def test_reindex_axis(self, fill_value, mgr):
+ def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value):
+ mat = _as_array(mgr)
+ indexer = mgr.axes[axis].get_indexer_for(new_labels)
+
+ reindexed = mgr.reindex_axis(new_labels, axis, fill_value=fill_value)
+ tm.assert_numpy_array_equal(
+ algos.take_nd(mat, indexer, axis, fill_value=fill_value),
+ _as_array(reindexed),
+ check_dtype=False,
+ )
+ tm.assert_index_equal(reindexed.axes[axis], new_labels)
+
+ for ax in range(mgr.ndim):
+ assert_reindex_axis_is_ok(mgr, ax, Index([]), fill_value)
+ assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax], fill_value)
+ assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][[0, 0, 0]], fill_value)
+ assert_reindex_axis_is_ok(mgr, ax, Index(["foo", "bar", "baz"]), fill_value)
+ assert_reindex_axis_is_ok(
+ mgr, ax, Index(["foo", mgr.axes[ax][0], "baz"]), fill_value
+ )
+
+ if mgr.shape[ax] >= 3:
+ assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][:-3], fill_value)
+ assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][-3::-1], fill_value)
+ assert_reindex_axis_is_ok(
+ mgr, ax, mgr.axes[ax][[0, 1, 2, 0, 1, 2]], fill_value
+ )
+
+ @pytest.mark.parametrize("mgr", MANAGERS)
+ @pytest.mark.parametrize("fill_value", [None, np.nan, 100.0])
+ def test_reindex_indexer(self, fill_value, mgr):
+ def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value):
+ mat = _as_array(mgr)
+ reindexed_mat = algos.take_nd(mat, indexer, axis, fill_value=fill_value)
+ reindexed = mgr.reindex_indexer(
+ new_labels, indexer, axis, fill_value=fill_value
+ )
+ tm.assert_numpy_array_equal(
+ reindexed_mat, _as_array(reindexed), check_dtype=False
+ )
+ tm.assert_index_equal(reindexed.axes[axis], new_labels)
+
+ for ax in range(mgr.ndim):
+ assert_reindex_indexer_is_ok(
+ mgr, ax, Index([]), np.array([], dtype=np.intp), fill_value
+ )
+ assert_reindex_indexer_is_ok(
+ mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax]), fill_value
+ )
+ assert_reindex_indexer_is_ok(
+ mgr,
+ ax,
+ Index(["foo"] * mgr.shape[ax]),
+ np.arange(mgr.shape[ax]),
+ fill_value,
+ )
+ assert_reindex_indexer_is_ok(
+ mgr, ax, mgr.axes[ax][::-1], np.arange(mgr.shape[ax]), fill_value
+ )
+ assert_reindex_indexer_is_ok(
+ mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax])[::-1], fill_value
+ )
+ assert_reindex_indexer_is_ok(
+ mgr, ax, Index(["foo", "bar", "baz"]), np.array([0, 0, 0]), fill_value
+ )
+ assert_reindex_indexer_is_ok(
+ mgr, ax, Index(["foo", "bar", "baz"]), np.array([-1, 0, -1]), fill_value
+ )
+ assert_reindex_indexer_is_ok(
+ mgr,
+ ax,
+ Index(["foo", mgr.axes[ax][0], "baz"]),
+ np.array([-1, -1, -1]),
+ fill_value,
+ )
+
+ if mgr.shape[ax] >= 3:
+ assert_reindex_indexer_is_ok(
+ mgr,
+ ax,
+ Index(["foo", "bar", "baz"]),
+ np.array([0, 1, 2]),
+ fill_value,
+ )
+
+
+class TestBlockPlacement:
+ @pytest.mark.parametrize(
+ "slc, expected",
+ [
+ (slice(0, 4), 4),
+ (slice(0, 4, 2), 2),
+ (slice(0, 3, 2), 2),
+ (slice(0, 1, 2), 1),
+ (slice(1, 0, -1), 1),
+ ],
+ )
+ def test_slice_len(self, slc, expected):
+ assert len(BlockPlacement(slc)) == expected
+
+ @pytest.mark.parametrize("slc", [slice(1, 1, 0), slice(1, 2, 0)])
+ def test_zero_step_raises(self, slc):
+ msg = "slice step cannot be zero"
+ with pytest.raises(ValueError, match=msg):
+ BlockPlacement(slc)
+
+ def test_slice_canonize_negative_stop(self):
+ # GH#37524 negative stop is OK with negative step and positive start
+ slc = slice(3, -1, -2)
+
+ bp = BlockPlacement(slc)
+ assert bp.indexer == slice(3, None, -2)
+
+ @pytest.mark.parametrize(
+ "slc",
+ [
+ slice(None, None),
+ slice(10, None),
+ slice(None, None, -1),
+ slice(None, 10, -1),
+ # These are "unbounded" because negative index will
+ # change depending on container shape.
+ slice(-1, None),
+ slice(None, -1),
+ slice(-1, -1),
+ slice(-1, None, -1),
+ slice(None, -1, -1),
+ slice(-1, -1, -1),
+ ],
+ )
+ def test_unbounded_slice_raises(self, slc):
+ msg = "unbounded slice"
+ with pytest.raises(ValueError, match=msg):
+ BlockPlacement(slc)
+
+ @pytest.mark.parametrize(
+ "slc",
+ [
+ slice(0, 0),
+ slice(100, 0),
+ slice(100, 100),
+ slice(100, 100, -1),
+ slice(0, 100, -1),
+ ],
+ )
+ def test_not_slice_like_slices(self, slc):
+ assert not BlockPlacement(slc).is_slice_like
+
+ @pytest.mark.parametrize(
+ "arr, slc",
+ [
+ ([0], slice(0, 1, 1)),
+ ([100], slice(100, 101, 1)),
+ ([0, 1, 2], slice(0, 3, 1)),
+ ([0, 5, 10], slice(0, 15, 5)),
+ ([0, 100], slice(0, 200, 100)),
+ ([2, 1], slice(2, 0, -1)),
+ ],
+ )
+ def test_array_to_slice_conversion(self, arr, slc):
+ assert BlockPlacement(arr).as_slice == slc
+
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ [],
+ [-1],
+ [-1, -2, -3],
+ [-10],
+ [-1],
+ [-1, 0, 1, 2],
+ [-2, 0, 2, 4],
+ [1, 0, -1],
+ [1, 1, 1],
+ ],
+ )
+ def test_not_slice_like_arrays(self, arr):
+ assert not BlockPlacement(arr).is_slice_like
+
+ @pytest.mark.parametrize(
+ "slc, expected",
+ [(slice(0, 3), [0, 1, 2]), (slice(0, 0), []), (slice(3, 0), [])],
+ )
+ def test_slice_iter(self, slc, expected):
+ assert list(BlockPlacement(slc)) == expected
+
+ @pytest.mark.parametrize(
+ "slc, arr",
+ [
+ (slice(0, 3), [0, 1, 2]),
+ (slice(0, 0), []),
+ (slice(3, 0), []),
+ (slice(3, 0, -1), [3, 2, 1]),
+ ],
+ )
+ def test_slice_to_array_conversion(self, slc, arr):
+ tm.assert_numpy_array_equal(
+ BlockPlacement(slc).as_array, np.asarray(arr, dtype=np.intp)
+ )
+
+ def test_blockplacement_add(self):
+ bpl = BlockPlacement(slice(0, 5))
+ assert bpl.add(1).as_slice == slice(1, 6, 1)
+ assert bpl.add(np.arange(5)).as_slice == slice(0, 10, 2)
+ assert list(bpl.add(np.arange(5, 0, -1))) == [5, 5, 5, 5, 5]
+
+ @pytest.mark.parametrize(
+ "val, inc, expected",
+ [
+ (slice(0, 0), 0, []),
+ (slice(1, 4), 0, [1, 2, 3]),
+ (slice(3, 0, -1), 0, [3, 2, 1]),
+ ([1, 2, 4], 0, [1, 2, 4]),
+ (slice(0, 0), 10, []),
+ (slice(1, 4), 10, [11, 12, 13]),
+ (slice(3, 0, -1), 10, [13, 12, 11]),
+ ([1, 2, 4], 10, [11, 12, 14]),
+ (slice(0, 0), -1, []),
+ (slice(1, 4), -1, [0, 1, 2]),
+ ([1, 2, 4], -1, [0, 1, 3]),
+ ],
+ )
+ def test_blockplacement_add_int(self, val, inc, expected):
+ assert list(BlockPlacement(val).add(inc)) == expected
+
+ @pytest.mark.parametrize("val", [slice(1, 4), [1, 2, 4]])
+ def test_blockplacement_add_int_raises(self, val):
+ msg = "iadd causes length change"
+ with pytest.raises(ValueError, match=msg):
+ BlockPlacement(val).add(-10)
+
+
+class TestCanHoldElement:
+ @pytest.fixture(
+ params=[
+ lambda x: x,
+ lambda x: x.to_series(),
+ lambda x: x._data,
+ lambda x: list(x),
+ lambda x: x.astype(object),
+ lambda x: np.asarray(x),
+ lambda x: x[0],
+ lambda x: x[:0],
+ ]
+ )
+ def element(self, request):
+ """
+ Functions that take an Index and return an element that should have
+ blk._can_hold_element(element) for a Block with this index's dtype.
+ """
+ return request.param
+
+ def test_datetime_block_can_hold_element(self):
+ block = create_block("datetime", [0])
+
+ assert block._can_hold_element([])
+
+ # We will check that block._can_hold_element iff arr.__setitem__ works
+ arr = pd.array(block.values.ravel())
+
+ # coerce None
+ assert block._can_hold_element(None)
+ arr[0] = None
+ assert arr[0] is pd.NaT
+
+ # coerce different types of datetime objects
+ vals = [np.datetime64("2010-10-10"), datetime(2010, 10, 10)]
+ for val in vals:
+ assert block._can_hold_element(val)
+ arr[0] = val
+
+ val = date(2010, 10, 10)
+ assert not block._can_hold_element(val)
+
+ msg = (
+ "value should be a 'Timestamp', 'NaT', "
+ "or array of those. Got 'date' instead."
+ )
+ with pytest.raises(TypeError, match=msg):
+ arr[0] = val
+
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
+ def test_interval_can_hold_element_emptylist(self, dtype, element):
+ arr = np.array([1, 3, 4], dtype=dtype)
+ ii = IntervalIndex.from_breaks(arr)
+ blk = new_block(ii._data, BlockPlacement([1]), ndim=2)
+
+ assert blk._can_hold_element([])
+ # TODO: check this holds for all blocks
+
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
+ def test_interval_can_hold_element(self, dtype, element):
+ arr = np.array([1, 3, 4, 9], dtype=dtype)
+ ii = IntervalIndex.from_breaks(arr)
+ blk = new_block(ii._data, BlockPlacement([1]), ndim=2)
+
+ elem = element(ii)
+ self.check_series_setitem(elem, ii, True)
+ assert blk._can_hold_element(elem)
+
+ # Careful: to get the expected Series-inplace behavior we need
+ # `elem` to not have the same length as `arr`
+ ii2 = IntervalIndex.from_breaks(arr[:-1], closed="neither")
+ elem = element(ii2)
+ with tm.assert_produces_warning(FutureWarning):
+ self.check_series_setitem(elem, ii, False)
+ assert not blk._can_hold_element(elem)
+
+ ii3 = IntervalIndex.from_breaks([Timestamp(1), Timestamp(3), Timestamp(4)])
+ elem = element(ii3)
+ with tm.assert_produces_warning(FutureWarning):
+ self.check_series_setitem(elem, ii, False)
+ assert not blk._can_hold_element(elem)
+
+ ii4 = IntervalIndex.from_breaks([Timedelta(1), Timedelta(3), Timedelta(4)])
+ elem = element(ii4)
+ with tm.assert_produces_warning(FutureWarning):
+ self.check_series_setitem(elem, ii, False)
+ assert not blk._can_hold_element(elem)
+
+ def test_period_can_hold_element_emptylist(self):
+ pi = period_range("2016", periods=3, freq="A")
+ blk = new_block(pi._data.reshape(1, 3), BlockPlacement([1]), ndim=2)
+
+ assert blk._can_hold_element([])
+
+ def test_period_can_hold_element(self, element):
+ pi = period_range("2016", periods=3, freq="A")
+
+ elem = element(pi)
+ self.check_series_setitem(elem, pi, True)
+
+ # Careful: to get the expected Series-inplace behavior we need
+ # `elem` to not have the same length as `arr`
+ pi2 = pi.asfreq("D")[:-1]
+ elem = element(pi2)
+ with tm.assert_produces_warning(FutureWarning):
+ self.check_series_setitem(elem, pi, False)
+
+ dti = pi.to_timestamp("S")[:-1]
+ elem = element(dti)
+ with tm.assert_produces_warning(FutureWarning):
+ self.check_series_setitem(elem, pi, False)
+
+ def check_can_hold_element(self, obj, elem, inplace: bool):
+ blk = obj._mgr.blocks[0]
+ if inplace:
+ assert blk._can_hold_element(elem)
+ else:
+ assert not blk._can_hold_element(elem)
+
+ def check_series_setitem(self, elem, index: Index, inplace: bool):
+ arr = index._data.copy()
+ ser = Series(arr, copy=False)
+
+ self.check_can_hold_element(ser, elem, inplace)
+
+ if is_scalar(elem):
+ ser[0] = elem
+ else:
+ ser[: len(elem)] = elem
+
+ if inplace:
+ assert ser.array is arr # i.e. setting was done inplace
+ else:
+ assert ser.dtype == object
+
+
+class TestShouldStore:
+ def test_should_store_categorical(self):
+ cat = Categorical(["A", "B", "C"])
+ df = DataFrame(cat)
+ blk = df._mgr.blocks[0]
+
+ # matching dtype
+ assert blk.should_store(cat)
+ assert blk.should_store(cat[:-1])
+
+ # different dtype
+ assert not blk.should_store(cat.as_ordered())
+
+ # ndarray instead of Categorical
+ assert not blk.should_store(np.asarray(cat))
+
+
+def test_validate_ndim():
+ values = np.array([1.0, 2.0])
+ placement = BlockPlacement(slice(2))
+ msg = r"Wrong number of dimensions. values.ndim != ndim \[1 != 2\]"
+
+ with pytest.raises(ValueError, match=msg):
+ make_block(values, placement, ndim=2)
+
+
+def test_block_shape():
+ idx = Index([0, 1, 2, 3, 4])
+ a = Series([1, 2, 3]).reindex(idx)
+ b = Series(Categorical([1, 2, 3])).reindex(idx)
+
+ assert a._mgr.blocks[0].mgr_locs.indexer == b._mgr.blocks[0].mgr_locs.indexer
+
+
+def test_make_block_no_pandas_array(block_maker):
+ # https://github.com/pandas-dev/pandas/pull/24866
+ arr = pd.arrays.NumpyExtensionArray(np.array([1, 2]))
+
+ # NumpyExtensionArray, no dtype
+ result = block_maker(arr, BlockPlacement(slice(len(arr))), ndim=arr.ndim)
+ assert result.dtype.kind in ["i", "u"]
+
+ if block_maker is make_block:
+ # new_block requires caller to unwrap NumpyExtensionArray
+ assert result.is_extension is False
+
+ # NumpyExtensionArray, NumpyEADtype
+ result = block_maker(arr, slice(len(arr)), dtype=arr.dtype, ndim=arr.ndim)
+ assert result.dtype.kind in ["i", "u"]
+ assert result.is_extension is False
+
+ # new_block no longer taked dtype keyword
+ # ndarray, NumpyEADtype
+ result = block_maker(
+ arr.to_numpy(), slice(len(arr)), dtype=arr.dtype, ndim=arr.ndim
+ )
+ assert result.dtype.kind in ["i", "u"]
+ assert result.is_extension is False
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/test_managers.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/test_managers.py
new file mode 100644
index 0000000000000000000000000000000000000000..75aa901fce9103a63f1b5c5bc20212cef7a5ee03
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/internals/test_managers.py
@@ -0,0 +1,70 @@
+"""
+Testing interaction between the different managers (BlockManager, ArrayManager)
+"""
+from pandas.core.dtypes.missing import array_equivalent
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.internals import (
+ ArrayManager,
+ BlockManager,
+ SingleArrayManager,
+ SingleBlockManager,
+)
+
+
+def test_dataframe_creation():
+ with pd.option_context("mode.data_manager", "block"):
+ df_block = pd.DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]})
+ assert isinstance(df_block._mgr, BlockManager)
+
+ with pd.option_context("mode.data_manager", "array"):
+ df_array = pd.DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]})
+ assert isinstance(df_array._mgr, ArrayManager)
+
+ # also ensure both are seen as equal
+ tm.assert_frame_equal(df_block, df_array)
+
+ # conversion from one manager to the other
+ result = df_block._as_manager("block")
+ assert isinstance(result._mgr, BlockManager)
+ result = df_block._as_manager("array")
+ assert isinstance(result._mgr, ArrayManager)
+ tm.assert_frame_equal(result, df_block)
+ assert all(
+ array_equivalent(left, right)
+ for left, right in zip(result._mgr.arrays, df_array._mgr.arrays)
+ )
+
+ result = df_array._as_manager("array")
+ assert isinstance(result._mgr, ArrayManager)
+ result = df_array._as_manager("block")
+ assert isinstance(result._mgr, BlockManager)
+ tm.assert_frame_equal(result, df_array)
+ assert len(result._mgr.blocks) == 2
+
+
+def test_series_creation():
+ with pd.option_context("mode.data_manager", "block"):
+ s_block = pd.Series([1, 2, 3], name="A", index=["a", "b", "c"])
+ assert isinstance(s_block._mgr, SingleBlockManager)
+
+ with pd.option_context("mode.data_manager", "array"):
+ s_array = pd.Series([1, 2, 3], name="A", index=["a", "b", "c"])
+ assert isinstance(s_array._mgr, SingleArrayManager)
+
+ # also ensure both are seen as equal
+ tm.assert_series_equal(s_block, s_array)
+
+ # conversion from one manager to the other
+ result = s_block._as_manager("block")
+ assert isinstance(result._mgr, SingleBlockManager)
+ result = s_block._as_manager("array")
+ assert isinstance(result._mgr, SingleArrayManager)
+ tm.assert_series_equal(result, s_block)
+
+ result = s_array._as_manager("array")
+ assert isinstance(result._mgr, SingleArrayManager)
+ result = s_array._as_manager("block")
+ assert isinstance(result._mgr, SingleBlockManager)
+ tm.assert_series_equal(result, s_array)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..701bfe3767db4df06c3816b396373c2122c096fe
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/conftest.py
@@ -0,0 +1,252 @@
+import shlex
+import subprocess
+import time
+import uuid
+
+import pytest
+
+from pandas.compat import (
+ is_ci_environment,
+ is_platform_arm,
+ is_platform_mac,
+ is_platform_windows,
+)
+import pandas.util._test_decorators as td
+
+import pandas.io.common as icom
+from pandas.io.parsers import read_csv
+
+
+@pytest.fixture
+def compression_to_extension():
+ return {value: key for key, value in icom.extension_to_compression.items()}
+
+
+@pytest.fixture
+def tips_file(datapath):
+ """Path to the tips dataset"""
+ return datapath("io", "data", "csv", "tips.csv")
+
+
+@pytest.fixture
+def jsonl_file(datapath):
+ """Path to a JSONL dataset"""
+ return datapath("io", "parser", "data", "items.jsonl")
+
+
+@pytest.fixture
+def salaries_table(datapath):
+ """DataFrame with the salaries dataset"""
+ return read_csv(datapath("io", "parser", "data", "salaries.csv"), sep="\t")
+
+
+@pytest.fixture
+def feather_file(datapath):
+ return datapath("io", "data", "feather", "feather-0_3_1.feather")
+
+
+@pytest.fixture
+def xml_file(datapath):
+ return datapath("io", "data", "xml", "books.xml")
+
+
+@pytest.fixture
+def s3so(worker_id):
+ if is_ci_environment():
+ url = "http://localhost:5000/"
+ else:
+ worker_id = "5" if worker_id == "master" else worker_id.lstrip("gw")
+ url = f"http://127.0.0.1:555{worker_id}/"
+ return {"client_kwargs": {"endpoint_url": url}}
+
+
+@pytest.fixture(scope="function" if is_ci_environment() else "session")
+def monkeysession():
+ with pytest.MonkeyPatch.context() as mp:
+ yield mp
+
+
+@pytest.fixture(scope="function" if is_ci_environment() else "session")
+def s3_base(worker_id, monkeysession):
+ """
+ Fixture for mocking S3 interaction.
+
+ Sets up moto server in separate process locally
+ Return url for motoserver/moto CI service
+ """
+ pytest.importorskip("s3fs")
+ pytest.importorskip("boto3")
+
+ # temporary workaround as moto fails for botocore >= 1.11 otherwise,
+ # see https://github.com/spulec/moto/issues/1924 & 1952
+ monkeysession.setenv("AWS_ACCESS_KEY_ID", "foobar_key")
+ monkeysession.setenv("AWS_SECRET_ACCESS_KEY", "foobar_secret")
+ if is_ci_environment():
+ if is_platform_arm() or is_platform_mac() or is_platform_windows():
+ # NOT RUN on Windows/macOS/ARM, only Ubuntu
+ # - subprocess in CI can cause timeouts
+ # - GitHub Actions do not support
+ # container services for the above OSs
+ # - CircleCI will probably hit the Docker rate pull limit
+ pytest.skip(
+ "S3 tests do not have a corresponding service in "
+ "Windows, macOS or ARM platforms"
+ )
+ else:
+ yield "http://localhost:5000"
+ else:
+ requests = pytest.importorskip("requests")
+ pytest.importorskip("moto", minversion="1.3.14")
+ pytest.importorskip("flask") # server mode needs flask too
+
+ # Launching moto in server mode, i.e., as a separate process
+ # with an S3 endpoint on localhost
+
+ worker_id = "5" if worker_id == "master" else worker_id.lstrip("gw")
+ endpoint_port = f"555{worker_id}"
+ endpoint_uri = f"http://127.0.0.1:{endpoint_port}/"
+
+ # pipe to null to avoid logging in terminal
+ with subprocess.Popen(
+ shlex.split(f"moto_server s3 -p {endpoint_port}"),
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ ) as proc:
+ timeout = 5
+ while timeout > 0:
+ try:
+ # OK to go once server is accepting connections
+ r = requests.get(endpoint_uri)
+ if r.ok:
+ break
+ except Exception:
+ pass
+ timeout -= 0.1
+ time.sleep(0.1)
+ yield endpoint_uri
+
+ proc.terminate()
+
+
+@pytest.fixture
+def s3_resource(s3_base):
+ import boto3
+
+ s3 = boto3.resource("s3", endpoint_url=s3_base)
+ return s3
+
+
+@pytest.fixture
+def s3_public_bucket(s3_resource):
+ bucket = s3_resource.Bucket(f"pandas-test-{uuid.uuid4()}")
+ bucket.create()
+ yield bucket
+ bucket.objects.delete()
+ bucket.delete()
+
+
+@pytest.fixture
+def s3_public_bucket_with_data(
+ s3_public_bucket, tips_file, jsonl_file, feather_file, xml_file
+):
+ """
+ The following datasets
+ are loaded.
+
+ - tips.csv
+ - tips.csv.gz
+ - tips.csv.bz2
+ - items.jsonl
+ """
+ test_s3_files = [
+ ("tips#1.csv", tips_file),
+ ("tips.csv", tips_file),
+ ("tips.csv.gz", tips_file + ".gz"),
+ ("tips.csv.bz2", tips_file + ".bz2"),
+ ("items.jsonl", jsonl_file),
+ ("simple_dataset.feather", feather_file),
+ ("books.xml", xml_file),
+ ]
+ for s3_key, file_name in test_s3_files:
+ with open(file_name, "rb") as f:
+ s3_public_bucket.put_object(Key=s3_key, Body=f)
+ return s3_public_bucket
+
+
+@pytest.fixture
+def s3_private_bucket(s3_resource):
+ bucket = s3_resource.Bucket(f"cant_get_it-{uuid.uuid4()}")
+ bucket.create(ACL="private")
+ yield bucket
+ bucket.objects.delete()
+ bucket.delete()
+
+
+@pytest.fixture
+def s3_private_bucket_with_data(
+ s3_private_bucket, tips_file, jsonl_file, feather_file, xml_file
+):
+ """
+ The following datasets
+ are loaded.
+
+ - tips.csv
+ - tips.csv.gz
+ - tips.csv.bz2
+ - items.jsonl
+ """
+ test_s3_files = [
+ ("tips#1.csv", tips_file),
+ ("tips.csv", tips_file),
+ ("tips.csv.gz", tips_file + ".gz"),
+ ("tips.csv.bz2", tips_file + ".bz2"),
+ ("items.jsonl", jsonl_file),
+ ("simple_dataset.feather", feather_file),
+ ("books.xml", xml_file),
+ ]
+ for s3_key, file_name in test_s3_files:
+ with open(file_name, "rb") as f:
+ s3_private_bucket.put_object(Key=s3_key, Body=f)
+ return s3_private_bucket
+
+
+_compression_formats_params = [
+ (".no_compress", None),
+ ("", None),
+ (".gz", "gzip"),
+ (".GZ", "gzip"),
+ (".bz2", "bz2"),
+ (".BZ2", "bz2"),
+ (".zip", "zip"),
+ (".ZIP", "zip"),
+ (".xz", "xz"),
+ (".XZ", "xz"),
+ pytest.param((".zst", "zstd"), marks=td.skip_if_no("zstandard")),
+ pytest.param((".ZST", "zstd"), marks=td.skip_if_no("zstandard")),
+]
+
+
+@pytest.fixture(params=_compression_formats_params[1:])
+def compression_format(request):
+ return request.param
+
+
+@pytest.fixture(params=_compression_formats_params)
+def compression_ext(request):
+ return request.param[0]
+
+
+@pytest.fixture(
+ params=[
+ "python",
+ pytest.param("pyarrow", marks=td.skip_if_no("pyarrow")),
+ ]
+)
+def string_storage(request):
+ """
+ Parametrized fixture for pd.options.mode.string_storage.
+
+ * 'python'
+ * 'pyarrow'
+ """
+ return request.param
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/generate_legacy_storage_files.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/generate_legacy_storage_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..974a2174cb03bf1a184f297ca4d89cc61e8b72c2
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/generate_legacy_storage_files.py
@@ -0,0 +1,341 @@
+"""
+self-contained to write legacy storage pickle files
+
+To use this script. Create an environment where you want
+generate pickles, say its for 0.20.3, with your pandas clone
+in ~/pandas
+
+. activate pandas_0.20.3
+cd ~/pandas/pandas
+
+$ python -m tests.io.generate_legacy_storage_files \
+ tests/io/data/legacy_pickle/0.20.3/ pickle
+
+This script generates a storage file for the current arch, system,
+and python version
+ pandas version: 0.20.3
+ output dir : pandas/pandas/tests/io/data/legacy_pickle/0.20.3/
+ storage format: pickle
+created pickle file: 0.20.3_x86_64_darwin_3.5.2.pickle
+
+The idea here is you are using the *current* version of the
+generate_legacy_storage_files with an *older* version of pandas to
+generate a pickle file. We will then check this file into a current
+branch, and test using test_pickle.py. This will load the *older*
+pickles and test versus the current data that is generated
+(with main). These are then compared.
+
+If we have cases where we changed the signature (e.g. we renamed
+offset -> freq in Timestamp). Then we have to conditionally execute
+in the generate_legacy_storage_files.py to make it
+run under the older AND the newer version.
+
+"""
+
+from datetime import timedelta
+import os
+import pickle
+import platform as pl
+import sys
+
+import numpy as np
+
+import pandas
+from pandas import (
+ Categorical,
+ DataFrame,
+ Index,
+ MultiIndex,
+ NaT,
+ Period,
+ RangeIndex,
+ Series,
+ Timestamp,
+ bdate_range,
+ date_range,
+ interval_range,
+ period_range,
+ timedelta_range,
+)
+from pandas.arrays import SparseArray
+
+from pandas.tseries.offsets import (
+ FY5253,
+ BusinessDay,
+ BusinessHour,
+ CustomBusinessDay,
+ DateOffset,
+ Day,
+ Easter,
+ Hour,
+ LastWeekOfMonth,
+ Minute,
+ MonthBegin,
+ MonthEnd,
+ QuarterBegin,
+ QuarterEnd,
+ SemiMonthBegin,
+ SemiMonthEnd,
+ Week,
+ WeekOfMonth,
+ YearBegin,
+ YearEnd,
+)
+
+
+def _create_sp_series():
+ nan = np.nan
+
+ # nan-based
+ arr = np.arange(15, dtype=np.float64)
+ arr[7:12] = nan
+ arr[-1:] = nan
+
+ bseries = Series(SparseArray(arr, kind="block"))
+ bseries.name = "bseries"
+ return bseries
+
+
+def _create_sp_tsseries():
+ nan = np.nan
+
+ # nan-based
+ arr = np.arange(15, dtype=np.float64)
+ arr[7:12] = nan
+ arr[-1:] = nan
+
+ date_index = bdate_range("1/1/2011", periods=len(arr))
+ bseries = Series(SparseArray(arr, kind="block"), index=date_index)
+ bseries.name = "btsseries"
+ return bseries
+
+
+def _create_sp_frame():
+ nan = np.nan
+
+ data = {
+ "A": [nan, nan, nan, 0, 1, 2, 3, 4, 5, 6],
+ "B": [0, 1, 2, nan, nan, nan, 3, 4, 5, 6],
+ "C": np.arange(10).astype(np.int64),
+ "D": [0, 1, 2, 3, 4, 5, nan, nan, nan, nan],
+ }
+
+ dates = bdate_range("1/1/2011", periods=10)
+ return DataFrame(data, index=dates).apply(SparseArray)
+
+
+def create_data():
+ """create the pickle data"""
+ data = {
+ "A": [0.0, 1.0, 2.0, 3.0, np.nan],
+ "B": [0, 1, 0, 1, 0],
+ "C": ["foo1", "foo2", "foo3", "foo4", "foo5"],
+ "D": date_range("1/1/2009", periods=5),
+ "E": [0.0, 1, Timestamp("20100101"), "foo", 2.0],
+ }
+
+ scalars = {"timestamp": Timestamp("20130101"), "period": Period("2012", "M")}
+
+ index = {
+ "int": Index(np.arange(10)),
+ "date": date_range("20130101", periods=10),
+ "period": period_range("2013-01-01", freq="M", periods=10),
+ "float": Index(np.arange(10, dtype=np.float64)),
+ "uint": Index(np.arange(10, dtype=np.uint64)),
+ "timedelta": timedelta_range("00:00:00", freq="30T", periods=10),
+ }
+
+ index["range"] = RangeIndex(10)
+
+ index["interval"] = interval_range(0, periods=10)
+
+ mi = {
+ "reg2": MultiIndex.from_tuples(
+ tuple(
+ zip(
+ *[
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
+ ["one", "two", "one", "two", "one", "two", "one", "two"],
+ ]
+ )
+ ),
+ names=["first", "second"],
+ )
+ }
+
+ series = {
+ "float": Series(data["A"]),
+ "int": Series(data["B"]),
+ "mixed": Series(data["E"]),
+ "ts": Series(
+ np.arange(10).astype(np.int64), index=date_range("20130101", periods=10)
+ ),
+ "mi": Series(
+ np.arange(5).astype(np.float64),
+ index=MultiIndex.from_tuples(
+ tuple(zip(*[[1, 1, 2, 2, 2], [3, 4, 3, 4, 5]])), names=["one", "two"]
+ ),
+ ),
+ "dup": Series(np.arange(5).astype(np.float64), index=["A", "B", "C", "D", "A"]),
+ "cat": Series(Categorical(["foo", "bar", "baz"])),
+ "dt": Series(date_range("20130101", periods=5)),
+ "dt_tz": Series(date_range("20130101", periods=5, tz="US/Eastern")),
+ "period": Series([Period("2000Q1")] * 5),
+ }
+
+ mixed_dup_df = DataFrame(data)
+ mixed_dup_df.columns = list("ABCDA")
+ frame = {
+ "float": DataFrame({"A": series["float"], "B": series["float"] + 1}),
+ "int": DataFrame({"A": series["int"], "B": series["int"] + 1}),
+ "mixed": DataFrame({k: data[k] for k in ["A", "B", "C", "D"]}),
+ "mi": DataFrame(
+ {"A": np.arange(5).astype(np.float64), "B": np.arange(5).astype(np.int64)},
+ index=MultiIndex.from_tuples(
+ tuple(
+ zip(
+ *[
+ ["bar", "bar", "baz", "baz", "baz"],
+ ["one", "two", "one", "two", "three"],
+ ]
+ )
+ ),
+ names=["first", "second"],
+ ),
+ ),
+ "dup": DataFrame(
+ np.arange(15).reshape(5, 3).astype(np.float64), columns=["A", "B", "A"]
+ ),
+ "cat_onecol": DataFrame({"A": Categorical(["foo", "bar"])}),
+ "cat_and_float": DataFrame(
+ {
+ "A": Categorical(["foo", "bar", "baz"]),
+ "B": np.arange(3).astype(np.int64),
+ }
+ ),
+ "mixed_dup": mixed_dup_df,
+ "dt_mixed_tzs": DataFrame(
+ {
+ "A": Timestamp("20130102", tz="US/Eastern"),
+ "B": Timestamp("20130603", tz="CET"),
+ },
+ index=range(5),
+ ),
+ "dt_mixed2_tzs": DataFrame(
+ {
+ "A": Timestamp("20130102", tz="US/Eastern"),
+ "B": Timestamp("20130603", tz="CET"),
+ "C": Timestamp("20130603", tz="UTC"),
+ },
+ index=range(5),
+ ),
+ }
+
+ cat = {
+ "int8": Categorical(list("abcdefg")),
+ "int16": Categorical(np.arange(1000)),
+ "int32": Categorical(np.arange(10000)),
+ }
+
+ timestamp = {
+ "normal": Timestamp("2011-01-01"),
+ "nat": NaT,
+ "tz": Timestamp("2011-01-01", tz="US/Eastern"),
+ }
+
+ off = {
+ "DateOffset": DateOffset(years=1),
+ "DateOffset_h_ns": DateOffset(hour=6, nanoseconds=5824),
+ "BusinessDay": BusinessDay(offset=timedelta(seconds=9)),
+ "BusinessHour": BusinessHour(normalize=True, n=6, end="15:14"),
+ "CustomBusinessDay": CustomBusinessDay(weekmask="Mon Fri"),
+ "SemiMonthBegin": SemiMonthBegin(day_of_month=9),
+ "SemiMonthEnd": SemiMonthEnd(day_of_month=24),
+ "MonthBegin": MonthBegin(1),
+ "MonthEnd": MonthEnd(1),
+ "QuarterBegin": QuarterBegin(1),
+ "QuarterEnd": QuarterEnd(1),
+ "Day": Day(1),
+ "YearBegin": YearBegin(1),
+ "YearEnd": YearEnd(1),
+ "Week": Week(1),
+ "Week_Tues": Week(2, normalize=False, weekday=1),
+ "WeekOfMonth": WeekOfMonth(week=3, weekday=4),
+ "LastWeekOfMonth": LastWeekOfMonth(n=1, weekday=3),
+ "FY5253": FY5253(n=2, weekday=6, startingMonth=7, variation="last"),
+ "Easter": Easter(),
+ "Hour": Hour(1),
+ "Minute": Minute(1),
+ }
+
+ return {
+ "series": series,
+ "frame": frame,
+ "index": index,
+ "scalars": scalars,
+ "mi": mi,
+ "sp_series": {"float": _create_sp_series(), "ts": _create_sp_tsseries()},
+ "sp_frame": {"float": _create_sp_frame()},
+ "cat": cat,
+ "timestamp": timestamp,
+ "offsets": off,
+ }
+
+
+def create_pickle_data():
+ data = create_data()
+
+ return data
+
+
+def platform_name():
+ return "_".join(
+ [
+ str(pandas.__version__),
+ str(pl.machine()),
+ str(pl.system().lower()),
+ str(pl.python_version()),
+ ]
+ )
+
+
+def write_legacy_pickles(output_dir):
+ version = pandas.__version__
+
+ print(
+ "This script generates a storage file for the current arch, system, "
+ "and python version"
+ )
+ print(f" pandas version: {version}")
+ print(f" output dir : {output_dir}")
+ print(" storage format: pickle")
+
+ pth = f"{platform_name()}.pickle"
+
+ with open(os.path.join(output_dir, pth), "wb") as fh:
+ pickle.dump(create_pickle_data(), fh, pickle.DEFAULT_PROTOCOL)
+
+ print(f"created pickle file: {pth}")
+
+
+def write_legacy_file():
+ # force our cwd to be the first searched
+ sys.path.insert(0, ".")
+
+ if not 3 <= len(sys.argv) <= 4:
+ sys.exit(
+ "Specify output directory and storage type: generate_legacy_"
+ "storage_files.py "
+ )
+
+ output_dir = str(sys.argv[1])
+ storage_type = str(sys.argv[2])
+
+ if storage_type == "pickle":
+ write_legacy_pickles(output_dir=output_dir)
+ else:
+ sys.exit("storage_type must be one of {'pickle'}")
+
+
+if __name__ == "__main__":
+ write_legacy_file()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_clipboard.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_clipboard.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b3c82ad3f083bfa5139f2d48307bc61d896cdb8
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_clipboard.py
@@ -0,0 +1,473 @@
+import os
+from textwrap import dedent
+
+import numpy as np
+import pytest
+
+from pandas.compat import (
+ is_ci_environment,
+ is_platform_mac,
+)
+from pandas.errors import (
+ PyperclipException,
+ PyperclipWindowsException,
+)
+
+import pandas as pd
+from pandas import (
+ NA,
+ DataFrame,
+ Series,
+ get_option,
+ read_clipboard,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ ArrowStringArray,
+ StringArray,
+)
+
+from pandas.io.clipboard import (
+ CheckedCall,
+ _stringifyText,
+ clipboard_get,
+ clipboard_set,
+)
+
+
+def build_kwargs(sep, excel):
+ kwargs = {}
+ if excel != "default":
+ kwargs["excel"] = excel
+ if sep != "default":
+ kwargs["sep"] = sep
+ return kwargs
+
+
+@pytest.fixture(
+ params=[
+ "delims",
+ "utf8",
+ "utf16",
+ "string",
+ "long",
+ "nonascii",
+ "colwidth",
+ "mixed",
+ "float",
+ "int",
+ ]
+)
+def df(request):
+ data_type = request.param
+
+ if data_type == "delims":
+ return DataFrame({"a": ['"a,\t"b|c', "d\tef`"], "b": ["hi'j", "k''lm"]})
+ elif data_type == "utf8":
+ return DataFrame({"a": ["µasd", "Ωœ∑`"], "b": ["øπ∆˚¬", "œ∑`®"]})
+ elif data_type == "utf16":
+ return DataFrame(
+ {"a": ["\U0001f44d\U0001f44d", "\U0001f44d\U0001f44d"], "b": ["abc", "def"]}
+ )
+ elif data_type == "string":
+ return tm.makeCustomDataframe(
+ 5, 3, c_idx_type="s", r_idx_type="i", c_idx_names=[None], r_idx_names=[None]
+ )
+ elif data_type == "long":
+ max_rows = get_option("display.max_rows")
+ return tm.makeCustomDataframe(
+ max_rows + 1,
+ 3,
+ data_gen_f=lambda *args: np.random.default_rng(2).integers(2),
+ c_idx_type="s",
+ r_idx_type="i",
+ c_idx_names=[None],
+ r_idx_names=[None],
+ )
+ elif data_type == "nonascii":
+ return DataFrame({"en": "in English".split(), "es": "en español".split()})
+ elif data_type == "colwidth":
+ _cw = get_option("display.max_colwidth") + 1
+ return tm.makeCustomDataframe(
+ 5,
+ 3,
+ data_gen_f=lambda *args: "x" * _cw,
+ c_idx_type="s",
+ r_idx_type="i",
+ c_idx_names=[None],
+ r_idx_names=[None],
+ )
+ elif data_type == "mixed":
+ return DataFrame(
+ {
+ "a": np.arange(1.0, 6.0) + 0.01,
+ "b": np.arange(1, 6).astype(np.int64),
+ "c": list("abcde"),
+ }
+ )
+ elif data_type == "float":
+ return tm.makeCustomDataframe(
+ 5,
+ 3,
+ data_gen_f=lambda r, c: float(r) + 0.01,
+ c_idx_type="s",
+ r_idx_type="i",
+ c_idx_names=[None],
+ r_idx_names=[None],
+ )
+ elif data_type == "int":
+ return tm.makeCustomDataframe(
+ 5,
+ 3,
+ data_gen_f=lambda *args: np.random.default_rng(2).integers(2),
+ c_idx_type="s",
+ r_idx_type="i",
+ c_idx_names=[None],
+ r_idx_names=[None],
+ )
+ else:
+ raise ValueError
+
+
+@pytest.fixture
+def mock_ctypes(monkeypatch):
+ """
+ Mocks WinError to help with testing the clipboard.
+ """
+
+ def _mock_win_error():
+ return "Window Error"
+
+ # Set raising to False because WinError won't exist on non-windows platforms
+ with monkeypatch.context() as m:
+ m.setattr("ctypes.WinError", _mock_win_error, raising=False)
+ yield
+
+
+@pytest.mark.usefixtures("mock_ctypes")
+def test_checked_call_with_bad_call(monkeypatch):
+ """
+ Give CheckCall a function that returns a falsey value and
+ mock get_errno so it returns false so an exception is raised.
+ """
+
+ def _return_false():
+ return False
+
+ monkeypatch.setattr("pandas.io.clipboard.get_errno", lambda: True)
+ msg = f"Error calling {_return_false.__name__} \\(Window Error\\)"
+
+ with pytest.raises(PyperclipWindowsException, match=msg):
+ CheckedCall(_return_false)()
+
+
+@pytest.mark.usefixtures("mock_ctypes")
+def test_checked_call_with_valid_call(monkeypatch):
+ """
+ Give CheckCall a function that returns a truthy value and
+ mock get_errno so it returns true so an exception is not raised.
+ The function should return the results from _return_true.
+ """
+
+ def _return_true():
+ return True
+
+ monkeypatch.setattr("pandas.io.clipboard.get_errno", lambda: False)
+
+ # Give CheckedCall a callable that returns a truthy value s
+ checked_call = CheckedCall(_return_true)
+ assert checked_call() is True
+
+
+@pytest.mark.parametrize(
+ "text",
+ [
+ "String_test",
+ True,
+ 1,
+ 1.0,
+ 1j,
+ ],
+)
+def test_stringify_text(text):
+ valid_types = (str, int, float, bool)
+
+ if isinstance(text, valid_types):
+ result = _stringifyText(text)
+ assert result == str(text)
+ else:
+ msg = (
+ "only str, int, float, and bool values "
+ f"can be copied to the clipboard, not {type(text).__name__}"
+ )
+ with pytest.raises(PyperclipException, match=msg):
+ _stringifyText(text)
+
+
+@pytest.fixture
+def mock_clipboard(monkeypatch, request):
+ """Fixture mocking clipboard IO.
+
+ This mocks pandas.io.clipboard.clipboard_get and
+ pandas.io.clipboard.clipboard_set.
+
+ This uses a local dict for storing data. The dictionary
+ key used is the test ID, available with ``request.node.name``.
+
+ This returns the local dictionary, for direct manipulation by
+ tests.
+ """
+ # our local clipboard for tests
+ _mock_data = {}
+
+ def _mock_set(data):
+ _mock_data[request.node.name] = data
+
+ def _mock_get():
+ return _mock_data[request.node.name]
+
+ monkeypatch.setattr("pandas.io.clipboard.clipboard_set", _mock_set)
+ monkeypatch.setattr("pandas.io.clipboard.clipboard_get", _mock_get)
+
+ yield _mock_data
+
+
+@pytest.mark.clipboard
+def test_mock_clipboard(mock_clipboard):
+ import pandas.io.clipboard
+
+ pandas.io.clipboard.clipboard_set("abc")
+ assert "abc" in set(mock_clipboard.values())
+ result = pandas.io.clipboard.clipboard_get()
+ assert result == "abc"
+
+
+@pytest.mark.single_cpu
+@pytest.mark.clipboard
+@pytest.mark.usefixtures("mock_clipboard")
+class TestClipboard:
+ def check_round_trip_frame(self, data, excel=None, sep=None, encoding=None):
+ data.to_clipboard(excel=excel, sep=sep, encoding=encoding)
+ result = read_clipboard(sep=sep or "\t", index_col=0, encoding=encoding)
+ tm.assert_frame_equal(data, result)
+
+ # Test that default arguments copy as tab delimited
+ def test_round_trip_frame(self, df):
+ self.check_round_trip_frame(df)
+
+ # Test that explicit delimiters are respected
+ @pytest.mark.parametrize("sep", ["\t", ",", "|"])
+ def test_round_trip_frame_sep(self, df, sep):
+ self.check_round_trip_frame(df, sep=sep)
+
+ # Test white space separator
+ def test_round_trip_frame_string(self, df):
+ df.to_clipboard(excel=False, sep=None)
+ result = read_clipboard()
+ assert df.to_string() == result.to_string()
+ assert df.shape == result.shape
+
+ # Two character separator is not supported in to_clipboard
+ # Test that multi-character separators are not silently passed
+ def test_excel_sep_warning(self, df):
+ with tm.assert_produces_warning(
+ UserWarning,
+ match="to_clipboard in excel mode requires a single character separator.",
+ check_stacklevel=False,
+ ):
+ df.to_clipboard(excel=True, sep=r"\t")
+
+ # Separator is ignored when excel=False and should produce a warning
+ def test_copy_delim_warning(self, df):
+ with tm.assert_produces_warning():
+ df.to_clipboard(excel=False, sep="\t")
+
+ # Tests that the default behavior of to_clipboard is tab
+ # delimited and excel="True"
+ @pytest.mark.parametrize("sep", ["\t", None, "default"])
+ @pytest.mark.parametrize("excel", [True, None, "default"])
+ def test_clipboard_copy_tabs_default(self, sep, excel, df, request, mock_clipboard):
+ kwargs = build_kwargs(sep, excel)
+ df.to_clipboard(**kwargs)
+ assert mock_clipboard[request.node.name] == df.to_csv(sep="\t")
+
+ # Tests reading of white space separated tables
+ @pytest.mark.parametrize("sep", [None, "default"])
+ @pytest.mark.parametrize("excel", [False])
+ def test_clipboard_copy_strings(self, sep, excel, df):
+ kwargs = build_kwargs(sep, excel)
+ df.to_clipboard(**kwargs)
+ result = read_clipboard(sep=r"\s+")
+ assert result.to_string() == df.to_string()
+ assert df.shape == result.shape
+
+ def test_read_clipboard_infer_excel(self, request, mock_clipboard):
+ # gh-19010: avoid warnings
+ clip_kwargs = {"engine": "python"}
+
+ text = dedent(
+ """
+ John James\tCharlie Mingus
+ 1\t2
+ 4\tHarry Carney
+ """.strip()
+ )
+ mock_clipboard[request.node.name] = text
+ df = read_clipboard(**clip_kwargs)
+
+ # excel data is parsed correctly
+ assert df.iloc[1, 1] == "Harry Carney"
+
+ # having diff tab counts doesn't trigger it
+ text = dedent(
+ """
+ a\t b
+ 1 2
+ 3 4
+ """.strip()
+ )
+ mock_clipboard[request.node.name] = text
+ res = read_clipboard(**clip_kwargs)
+
+ text = dedent(
+ """
+ a b
+ 1 2
+ 3 4
+ """.strip()
+ )
+ mock_clipboard[request.node.name] = text
+ exp = read_clipboard(**clip_kwargs)
+
+ tm.assert_frame_equal(res, exp)
+
+ def test_infer_excel_with_nulls(self, request, mock_clipboard):
+ # GH41108
+ text = "col1\tcol2\n1\tred\n\tblue\n2\tgreen"
+
+ mock_clipboard[request.node.name] = text
+ df = read_clipboard()
+ df_expected = DataFrame(
+ data={"col1": [1, None, 2], "col2": ["red", "blue", "green"]}
+ )
+
+ # excel data is parsed correctly
+ tm.assert_frame_equal(df, df_expected)
+
+ @pytest.mark.parametrize(
+ "multiindex",
+ [
+ ( # Can't use `dedent` here as it will remove the leading `\t`
+ "\n".join(
+ [
+ "\t\t\tcol1\tcol2",
+ "A\t0\tTrue\t1\tred",
+ "A\t1\tTrue\t\tblue",
+ "B\t0\tFalse\t2\tgreen",
+ ]
+ ),
+ [["A", "A", "B"], [0, 1, 0], [True, True, False]],
+ ),
+ (
+ "\n".join(
+ ["\t\tcol1\tcol2", "A\t0\t1\tred", "A\t1\t\tblue", "B\t0\t2\tgreen"]
+ ),
+ [["A", "A", "B"], [0, 1, 0]],
+ ),
+ ],
+ )
+ def test_infer_excel_with_multiindex(self, request, mock_clipboard, multiindex):
+ # GH41108
+
+ mock_clipboard[request.node.name] = multiindex[0]
+ df = read_clipboard()
+ df_expected = DataFrame(
+ data={"col1": [1, None, 2], "col2": ["red", "blue", "green"]},
+ index=multiindex[1],
+ )
+
+ # excel data is parsed correctly
+ tm.assert_frame_equal(df, df_expected)
+
+ def test_invalid_encoding(self, df):
+ msg = "clipboard only supports utf-8 encoding"
+ # test case for testing invalid encoding
+ with pytest.raises(ValueError, match=msg):
+ df.to_clipboard(encoding="ascii")
+ with pytest.raises(NotImplementedError, match=msg):
+ read_clipboard(encoding="ascii")
+
+ @pytest.mark.parametrize("enc", ["UTF-8", "utf-8", "utf8"])
+ def test_round_trip_valid_encodings(self, enc, df):
+ self.check_round_trip_frame(df, encoding=enc)
+
+ @pytest.mark.single_cpu
+ @pytest.mark.parametrize("data", ["\U0001f44d...", "Ωœ∑`...", "abcd..."])
+ @pytest.mark.xfail(
+ (os.environ.get("DISPLAY") is None and not is_platform_mac())
+ or is_ci_environment(),
+ reason="Cannot pass if a headless system is not put in place with Xvfb",
+ strict=not is_ci_environment(), # Flaky failures in the CI
+ )
+ def test_raw_roundtrip(self, data):
+ # PR #25040 wide unicode wasn't copied correctly on PY3 on windows
+ clipboard_set(data)
+ assert data == clipboard_get()
+
+ @pytest.mark.parametrize("engine", ["c", "python"])
+ def test_read_clipboard_dtype_backend(
+ self, request, mock_clipboard, string_storage, dtype_backend, engine
+ ):
+ # GH#50502
+ if string_storage == "pyarrow" or dtype_backend == "pyarrow":
+ pa = pytest.importorskip("pyarrow")
+
+ if string_storage == "python":
+ string_array = StringArray(np.array(["x", "y"], dtype=np.object_))
+ string_array_na = StringArray(np.array(["x", NA], dtype=np.object_))
+
+ else:
+ string_array = ArrowStringArray(pa.array(["x", "y"]))
+ string_array_na = ArrowStringArray(pa.array(["x", None]))
+
+ text = """a,b,c,d,e,f,g,h,i
+x,1,4.0,x,2,4.0,,True,False
+y,2,5.0,,,,,False,"""
+ mock_clipboard[request.node.name] = text
+
+ with pd.option_context("mode.string_storage", string_storage):
+ result = read_clipboard(sep=",", dtype_backend=dtype_backend, engine=engine)
+
+ expected = DataFrame(
+ {
+ "a": string_array,
+ "b": Series([1, 2], dtype="Int64"),
+ "c": Series([4.0, 5.0], dtype="Float64"),
+ "d": string_array_na,
+ "e": Series([2, NA], dtype="Int64"),
+ "f": Series([4.0, NA], dtype="Float64"),
+ "g": Series([NA, NA], dtype="Int64"),
+ "h": Series([True, False], dtype="boolean"),
+ "i": Series([False, NA], dtype="boolean"),
+ }
+ )
+ if dtype_backend == "pyarrow":
+ from pandas.arrays import ArrowExtensionArray
+
+ expected = DataFrame(
+ {
+ col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))
+ for col in expected.columns
+ }
+ )
+ expected["g"] = ArrowExtensionArray(pa.array([None, None]))
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_invalid_dtype_backend(self):
+ msg = (
+ "dtype_backend numpy is invalid, only 'numpy_nullable' and "
+ "'pyarrow' are allowed."
+ )
+ with pytest.raises(ValueError, match=msg):
+ read_clipboard(dtype_backend="numpy")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7ece6a6d7b08fcfa9ec737adcce3ce8aed0d9b5
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_common.py
@@ -0,0 +1,621 @@
+"""
+Tests for the pandas.io.common functionalities
+"""
+import codecs
+import errno
+from functools import partial
+from io import (
+ BytesIO,
+ StringIO,
+ UnsupportedOperation,
+)
+import mmap
+import os
+from pathlib import Path
+import pickle
+import tempfile
+
+import pytest
+
+from pandas.compat import is_platform_windows
+import pandas.util._test_decorators as td
+
+import pandas as pd
+import pandas._testing as tm
+
+import pandas.io.common as icom
+
+
+class CustomFSPath:
+ """For testing fspath on unknown objects"""
+
+ def __init__(self, path) -> None:
+ self.path = path
+
+ def __fspath__(self):
+ return self.path
+
+
+# Functions that consume a string path and return a string or path-like object
+path_types = [str, CustomFSPath, Path]
+
+try:
+ from py.path import local as LocalPath
+
+ path_types.append(LocalPath)
+except ImportError:
+ pass
+
+HERE = os.path.abspath(os.path.dirname(__file__))
+
+
+# https://github.com/cython/cython/issues/1720
+class TestCommonIOCapabilities:
+ data1 = """index,A,B,C,D
+foo,2,3,4,5
+bar,7,8,9,10
+baz,12,13,14,15
+qux,12,13,14,15
+foo2,12,13,14,15
+bar2,12,13,14,15
+"""
+
+ def test_expand_user(self):
+ filename = "~/sometest"
+ expanded_name = icom._expand_user(filename)
+
+ assert expanded_name != filename
+ assert os.path.isabs(expanded_name)
+ assert os.path.expanduser(filename) == expanded_name
+
+ def test_expand_user_normal_path(self):
+ filename = "/somefolder/sometest"
+ expanded_name = icom._expand_user(filename)
+
+ assert expanded_name == filename
+ assert os.path.expanduser(filename) == expanded_name
+
+ def test_stringify_path_pathlib(self):
+ rel_path = icom.stringify_path(Path("."))
+ assert rel_path == "."
+ redundant_path = icom.stringify_path(Path("foo//bar"))
+ assert redundant_path == os.path.join("foo", "bar")
+
+ @td.skip_if_no("py.path")
+ def test_stringify_path_localpath(self):
+ path = os.path.join("foo", "bar")
+ abs_path = os.path.abspath(path)
+ lpath = LocalPath(path)
+ assert icom.stringify_path(lpath) == abs_path
+
+ def test_stringify_path_fspath(self):
+ p = CustomFSPath("foo/bar.csv")
+ result = icom.stringify_path(p)
+ assert result == "foo/bar.csv"
+
+ def test_stringify_file_and_path_like(self):
+ # GH 38125: do not stringify file objects that are also path-like
+ fsspec = pytest.importorskip("fsspec")
+ with tm.ensure_clean() as path:
+ with fsspec.open(f"file://{path}", mode="wb") as fsspec_obj:
+ assert fsspec_obj == icom.stringify_path(fsspec_obj)
+
+ @pytest.mark.parametrize("path_type", path_types)
+ def test_infer_compression_from_path(self, compression_format, path_type):
+ extension, expected = compression_format
+ path = path_type("foo/bar.csv" + extension)
+ compression = icom.infer_compression(path, compression="infer")
+ assert compression == expected
+
+ @pytest.mark.parametrize("path_type", [str, CustomFSPath, Path])
+ def test_get_handle_with_path(self, path_type):
+ # ignore LocalPath: it creates strange paths: /absolute/~/sometest
+ with tempfile.TemporaryDirectory(dir=Path.home()) as tmp:
+ filename = path_type("~/" + Path(tmp).name + "/sometest")
+ with icom.get_handle(filename, "w") as handles:
+ assert Path(handles.handle.name).is_absolute()
+ assert os.path.expanduser(filename) == handles.handle.name
+
+ def test_get_handle_with_buffer(self):
+ with StringIO() as input_buffer:
+ with icom.get_handle(input_buffer, "r") as handles:
+ assert handles.handle == input_buffer
+ assert not input_buffer.closed
+ assert input_buffer.closed
+
+ # Test that BytesIOWrapper(get_handle) returns correct amount of bytes every time
+ def test_bytesiowrapper_returns_correct_bytes(self):
+ # Test latin1, ucs-2, and ucs-4 chars
+ data = """a,b,c
+1,2,3
+©,®,®
+Look,a snake,🐍"""
+ with icom.get_handle(StringIO(data), "rb", is_text=False) as handles:
+ result = b""
+ chunksize = 5
+ while True:
+ chunk = handles.handle.read(chunksize)
+ # Make sure each chunk is correct amount of bytes
+ assert len(chunk) <= chunksize
+ if len(chunk) < chunksize:
+ # Can be less amount of bytes, but only at EOF
+ # which happens when read returns empty
+ assert len(handles.handle.read()) == 0
+ result += chunk
+ break
+ result += chunk
+ assert result == data.encode("utf-8")
+
+ # Test that pyarrow can handle a file opened with get_handle
+ def test_get_handle_pyarrow_compat(self):
+ pa_csv = pytest.importorskip("pyarrow.csv")
+
+ # Test latin1, ucs-2, and ucs-4 chars
+ data = """a,b,c
+1,2,3
+©,®,®
+Look,a snake,🐍"""
+ expected = pd.DataFrame(
+ {"a": ["1", "©", "Look"], "b": ["2", "®", "a snake"], "c": ["3", "®", "🐍"]}
+ )
+ s = StringIO(data)
+ with icom.get_handle(s, "rb", is_text=False) as handles:
+ df = pa_csv.read_csv(handles.handle).to_pandas()
+ tm.assert_frame_equal(df, expected)
+ assert not s.closed
+
+ def test_iterator(self):
+ with pd.read_csv(StringIO(self.data1), chunksize=1) as reader:
+ result = pd.concat(reader, ignore_index=True)
+ expected = pd.read_csv(StringIO(self.data1))
+ tm.assert_frame_equal(result, expected)
+
+ # GH12153
+ with pd.read_csv(StringIO(self.data1), chunksize=1) as it:
+ first = next(it)
+ tm.assert_frame_equal(first, expected.iloc[[0]])
+ tm.assert_frame_equal(pd.concat(it), expected.iloc[1:])
+
+ @pytest.mark.parametrize(
+ "reader, module, error_class, fn_ext",
+ [
+ (pd.read_csv, "os", FileNotFoundError, "csv"),
+ (pd.read_fwf, "os", FileNotFoundError, "txt"),
+ (pd.read_excel, "xlrd", FileNotFoundError, "xlsx"),
+ (pd.read_feather, "pyarrow", OSError, "feather"),
+ (pd.read_hdf, "tables", FileNotFoundError, "h5"),
+ (pd.read_stata, "os", FileNotFoundError, "dta"),
+ (pd.read_sas, "os", FileNotFoundError, "sas7bdat"),
+ (pd.read_json, "os", FileNotFoundError, "json"),
+ (pd.read_pickle, "os", FileNotFoundError, "pickle"),
+ ],
+ )
+ def test_read_non_existent(self, reader, module, error_class, fn_ext):
+ pytest.importorskip(module)
+
+ path = os.path.join(HERE, "data", "does_not_exist." + fn_ext)
+ msg1 = rf"File (b')?.+does_not_exist\.{fn_ext}'? does not exist"
+ msg2 = rf"\[Errno 2\] No such file or directory: '.+does_not_exist\.{fn_ext}'"
+ msg3 = "Expected object or value"
+ msg4 = "path_or_buf needs to be a string file path or file-like"
+ msg5 = (
+ rf"\[Errno 2\] File .+does_not_exist\.{fn_ext} does not exist: "
+ rf"'.+does_not_exist\.{fn_ext}'"
+ )
+ msg6 = rf"\[Errno 2\] 没有那个文件或目录: '.+does_not_exist\.{fn_ext}'"
+ msg7 = (
+ rf"\[Errno 2\] File o directory non esistente: '.+does_not_exist\.{fn_ext}'"
+ )
+ msg8 = rf"Failed to open local file.+does_not_exist\.{fn_ext}"
+
+ with pytest.raises(
+ error_class,
+ match=rf"({msg1}|{msg2}|{msg3}|{msg4}|{msg5}|{msg6}|{msg7}|{msg8})",
+ ):
+ reader(path)
+
+ @pytest.mark.parametrize(
+ "method, module, error_class, fn_ext",
+ [
+ (pd.DataFrame.to_csv, "os", OSError, "csv"),
+ (pd.DataFrame.to_html, "os", OSError, "html"),
+ (pd.DataFrame.to_excel, "xlrd", OSError, "xlsx"),
+ (pd.DataFrame.to_feather, "pyarrow", OSError, "feather"),
+ (pd.DataFrame.to_parquet, "pyarrow", OSError, "parquet"),
+ (pd.DataFrame.to_stata, "os", OSError, "dta"),
+ (pd.DataFrame.to_json, "os", OSError, "json"),
+ (pd.DataFrame.to_pickle, "os", OSError, "pickle"),
+ ],
+ )
+ # NOTE: Missing parent directory for pd.DataFrame.to_hdf is handled by PyTables
+ def test_write_missing_parent_directory(self, method, module, error_class, fn_ext):
+ pytest.importorskip(module)
+
+ dummy_frame = pd.DataFrame({"a": [1, 2, 3], "b": [2, 3, 4], "c": [3, 4, 5]})
+
+ path = os.path.join(HERE, "data", "missing_folder", "does_not_exist." + fn_ext)
+
+ with pytest.raises(
+ error_class,
+ match=r"Cannot save file into a non-existent directory: .*missing_folder",
+ ):
+ method(dummy_frame, path)
+
+ @pytest.mark.parametrize(
+ "reader, module, error_class, fn_ext",
+ [
+ (pd.read_csv, "os", FileNotFoundError, "csv"),
+ (pd.read_table, "os", FileNotFoundError, "csv"),
+ (pd.read_fwf, "os", FileNotFoundError, "txt"),
+ (pd.read_excel, "xlrd", FileNotFoundError, "xlsx"),
+ (pd.read_feather, "pyarrow", OSError, "feather"),
+ (pd.read_hdf, "tables", FileNotFoundError, "h5"),
+ (pd.read_stata, "os", FileNotFoundError, "dta"),
+ (pd.read_sas, "os", FileNotFoundError, "sas7bdat"),
+ (pd.read_json, "os", FileNotFoundError, "json"),
+ (pd.read_pickle, "os", FileNotFoundError, "pickle"),
+ ],
+ )
+ def test_read_expands_user_home_dir(
+ self, reader, module, error_class, fn_ext, monkeypatch
+ ):
+ pytest.importorskip(module)
+
+ path = os.path.join("~", "does_not_exist." + fn_ext)
+ monkeypatch.setattr(icom, "_expand_user", lambda x: os.path.join("foo", x))
+
+ msg1 = rf"File (b')?.+does_not_exist\.{fn_ext}'? does not exist"
+ msg2 = rf"\[Errno 2\] No such file or directory: '.+does_not_exist\.{fn_ext}'"
+ msg3 = "Unexpected character found when decoding 'false'"
+ msg4 = "path_or_buf needs to be a string file path or file-like"
+ msg5 = (
+ rf"\[Errno 2\] File .+does_not_exist\.{fn_ext} does not exist: "
+ rf"'.+does_not_exist\.{fn_ext}'"
+ )
+ msg6 = rf"\[Errno 2\] 没有那个文件或目录: '.+does_not_exist\.{fn_ext}'"
+ msg7 = (
+ rf"\[Errno 2\] File o directory non esistente: '.+does_not_exist\.{fn_ext}'"
+ )
+ msg8 = rf"Failed to open local file.+does_not_exist\.{fn_ext}"
+
+ with pytest.raises(
+ error_class,
+ match=rf"({msg1}|{msg2}|{msg3}|{msg4}|{msg5}|{msg6}|{msg7}|{msg8})",
+ ):
+ reader(path)
+
+ @pytest.mark.parametrize(
+ "reader, module, path",
+ [
+ (pd.read_csv, "os", ("io", "data", "csv", "iris.csv")),
+ (pd.read_table, "os", ("io", "data", "csv", "iris.csv")),
+ (
+ pd.read_fwf,
+ "os",
+ ("io", "data", "fixed_width", "fixed_width_format.txt"),
+ ),
+ (pd.read_excel, "xlrd", ("io", "data", "excel", "test1.xlsx")),
+ (
+ pd.read_feather,
+ "pyarrow",
+ ("io", "data", "feather", "feather-0_3_1.feather"),
+ ),
+ (
+ pd.read_hdf,
+ "tables",
+ ("io", "data", "legacy_hdf", "datetimetz_object.h5"),
+ ),
+ (pd.read_stata, "os", ("io", "data", "stata", "stata10_115.dta")),
+ (pd.read_sas, "os", ("io", "sas", "data", "test1.sas7bdat")),
+ (pd.read_json, "os", ("io", "json", "data", "tsframe_v012.json")),
+ (
+ pd.read_pickle,
+ "os",
+ ("io", "data", "pickle", "categorical.0.25.0.pickle"),
+ ),
+ ],
+ )
+ def test_read_fspath_all(self, reader, module, path, datapath):
+ pytest.importorskip(module)
+ path = datapath(*path)
+
+ mypath = CustomFSPath(path)
+ result = reader(mypath)
+ expected = reader(path)
+
+ if path.endswith(".pickle"):
+ # categorical
+ tm.assert_categorical_equal(result, expected)
+ else:
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "writer_name, writer_kwargs, module",
+ [
+ ("to_csv", {}, "os"),
+ ("to_excel", {"engine": "openpyxl"}, "openpyxl"),
+ ("to_feather", {}, "pyarrow"),
+ ("to_html", {}, "os"),
+ ("to_json", {}, "os"),
+ ("to_latex", {}, "os"),
+ ("to_pickle", {}, "os"),
+ ("to_stata", {"time_stamp": pd.to_datetime("2019-01-01 00:00")}, "os"),
+ ],
+ )
+ def test_write_fspath_all(self, writer_name, writer_kwargs, module):
+ if writer_name in ["to_latex"]: # uses Styler implementation
+ pytest.importorskip("jinja2")
+ p1 = tm.ensure_clean("string")
+ p2 = tm.ensure_clean("fspath")
+ df = pd.DataFrame({"A": [1, 2]})
+
+ with p1 as string, p2 as fspath:
+ pytest.importorskip(module)
+ mypath = CustomFSPath(fspath)
+ writer = getattr(df, writer_name)
+
+ writer(string, **writer_kwargs)
+ writer(mypath, **writer_kwargs)
+ with open(string, "rb") as f_str, open(fspath, "rb") as f_path:
+ if writer_name == "to_excel":
+ # binary representation of excel contains time creation
+ # data that causes flaky CI failures
+ result = pd.read_excel(f_str, **writer_kwargs)
+ expected = pd.read_excel(f_path, **writer_kwargs)
+ tm.assert_frame_equal(result, expected)
+ else:
+ result = f_str.read()
+ expected = f_path.read()
+ assert result == expected
+
+ def test_write_fspath_hdf5(self):
+ # Same test as write_fspath_all, except HDF5 files aren't
+ # necessarily byte-for-byte identical for a given dataframe, so we'll
+ # have to read and compare equality
+ pytest.importorskip("tables")
+
+ df = pd.DataFrame({"A": [1, 2]})
+ p1 = tm.ensure_clean("string")
+ p2 = tm.ensure_clean("fspath")
+
+ with p1 as string, p2 as fspath:
+ mypath = CustomFSPath(fspath)
+ df.to_hdf(mypath, key="bar")
+ df.to_hdf(string, key="bar")
+
+ result = pd.read_hdf(fspath, key="bar")
+ expected = pd.read_hdf(string, key="bar")
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.fixture
+def mmap_file(datapath):
+ return datapath("io", "data", "csv", "test_mmap.csv")
+
+
+class TestMMapWrapper:
+ def test_constructor_bad_file(self, mmap_file):
+ non_file = StringIO("I am not a file")
+ non_file.fileno = lambda: -1
+
+ # the error raised is different on Windows
+ if is_platform_windows():
+ msg = "The parameter is incorrect"
+ err = OSError
+ else:
+ msg = "[Errno 22]"
+ err = mmap.error
+
+ with pytest.raises(err, match=msg):
+ icom._maybe_memory_map(non_file, True)
+
+ with open(mmap_file, encoding="utf-8") as target:
+ pass
+
+ msg = "I/O operation on closed file"
+ with pytest.raises(ValueError, match=msg):
+ icom._maybe_memory_map(target, True)
+
+ def test_next(self, mmap_file):
+ with open(mmap_file, encoding="utf-8") as target:
+ lines = target.readlines()
+
+ with icom.get_handle(
+ target, "r", is_text=True, memory_map=True
+ ) as wrappers:
+ wrapper = wrappers.handle
+ assert isinstance(wrapper.buffer.buffer, mmap.mmap)
+
+ for line in lines:
+ next_line = next(wrapper)
+ assert next_line.strip() == line.strip()
+
+ with pytest.raises(StopIteration, match=r"^$"):
+ next(wrapper)
+
+ def test_unknown_engine(self):
+ with tm.ensure_clean() as path:
+ df = tm.makeDataFrame()
+ df.to_csv(path)
+ with pytest.raises(ValueError, match="Unknown engine"):
+ pd.read_csv(path, engine="pyt")
+
+ def test_binary_mode(self):
+ """
+ 'encoding' shouldn't be passed to 'open' in binary mode.
+
+ GH 35058
+ """
+ with tm.ensure_clean() as path:
+ df = tm.makeDataFrame()
+ df.to_csv(path, mode="w+b")
+ tm.assert_frame_equal(df, pd.read_csv(path, index_col=0))
+
+ @pytest.mark.parametrize("encoding", ["utf-16", "utf-32"])
+ @pytest.mark.parametrize("compression_", ["bz2", "xz"])
+ def test_warning_missing_utf_bom(self, encoding, compression_):
+ """
+ bz2 and xz do not write the byte order mark (BOM) for utf-16/32.
+
+ https://stackoverflow.com/questions/55171439
+
+ GH 35681
+ """
+ df = tm.makeDataFrame()
+ with tm.ensure_clean() as path:
+ with tm.assert_produces_warning(UnicodeWarning):
+ df.to_csv(path, compression=compression_, encoding=encoding)
+
+ # reading should fail (otherwise we wouldn't need the warning)
+ msg = r"UTF-\d+ stream does not start with BOM"
+ with pytest.raises(UnicodeError, match=msg):
+ pd.read_csv(path, compression=compression_, encoding=encoding)
+
+
+def test_is_fsspec_url():
+ assert icom.is_fsspec_url("gcs://pandas/somethingelse.com")
+ assert icom.is_fsspec_url("gs://pandas/somethingelse.com")
+ # the following is the only remote URL that is handled without fsspec
+ assert not icom.is_fsspec_url("http://pandas/somethingelse.com")
+ assert not icom.is_fsspec_url("random:pandas/somethingelse.com")
+ assert not icom.is_fsspec_url("/local/path")
+ assert not icom.is_fsspec_url("relative/local/path")
+ # fsspec URL in string should not be recognized
+ assert not icom.is_fsspec_url("this is not fsspec://url")
+ assert not icom.is_fsspec_url("{'url': 'gs://pandas/somethingelse.com'}")
+ # accept everything that conforms to RFC 3986 schema
+ assert icom.is_fsspec_url("RFC-3986+compliant.spec://something")
+
+
+@pytest.mark.parametrize("encoding", [None, "utf-8"])
+@pytest.mark.parametrize("format", ["csv", "json"])
+def test_codecs_encoding(encoding, format):
+ # GH39247
+ expected = tm.makeDataFrame()
+ with tm.ensure_clean() as path:
+ with codecs.open(path, mode="w", encoding=encoding) as handle:
+ getattr(expected, f"to_{format}")(handle)
+ with codecs.open(path, mode="r", encoding=encoding) as handle:
+ if format == "csv":
+ df = pd.read_csv(handle, index_col=0)
+ else:
+ df = pd.read_json(handle)
+ tm.assert_frame_equal(expected, df)
+
+
+def test_codecs_get_writer_reader():
+ # GH39247
+ expected = tm.makeDataFrame()
+ with tm.ensure_clean() as path:
+ with open(path, "wb") as handle:
+ with codecs.getwriter("utf-8")(handle) as encoded:
+ expected.to_csv(encoded)
+ with open(path, "rb") as handle:
+ with codecs.getreader("utf-8")(handle) as encoded:
+ df = pd.read_csv(encoded, index_col=0)
+ tm.assert_frame_equal(expected, df)
+
+
+@pytest.mark.parametrize(
+ "io_class,mode,msg",
+ [
+ (BytesIO, "t", "a bytes-like object is required, not 'str'"),
+ (StringIO, "b", "string argument expected, got 'bytes'"),
+ ],
+)
+def test_explicit_encoding(io_class, mode, msg):
+ # GH39247; this test makes sure that if a user provides mode="*t" or "*b",
+ # it is used. In the case of this test it leads to an error as intentionally the
+ # wrong mode is requested
+ expected = tm.makeDataFrame()
+ with io_class() as buffer:
+ with pytest.raises(TypeError, match=msg):
+ expected.to_csv(buffer, mode=f"w{mode}")
+
+
+@pytest.mark.parametrize("encoding_errors", [None, "strict", "replace"])
+@pytest.mark.parametrize("format", ["csv", "json"])
+def test_encoding_errors(encoding_errors, format):
+ # GH39450
+ msg = "'utf-8' codec can't decode byte"
+ bad_encoding = b"\xe4"
+
+ if format == "csv":
+ content = b"," + bad_encoding + b"\n" + bad_encoding * 2 + b"," + bad_encoding
+ reader = partial(pd.read_csv, index_col=0)
+ else:
+ content = (
+ b'{"'
+ + bad_encoding * 2
+ + b'": {"'
+ + bad_encoding
+ + b'":"'
+ + bad_encoding
+ + b'"}}'
+ )
+ reader = partial(pd.read_json, orient="index")
+ with tm.ensure_clean() as path:
+ file = Path(path)
+ file.write_bytes(content)
+
+ if encoding_errors != "replace":
+ with pytest.raises(UnicodeDecodeError, match=msg):
+ reader(path, encoding_errors=encoding_errors)
+ else:
+ df = reader(path, encoding_errors=encoding_errors)
+ decoded = bad_encoding.decode(errors=encoding_errors)
+ expected = pd.DataFrame({decoded: [decoded]}, index=[decoded * 2])
+ tm.assert_frame_equal(df, expected)
+
+
+def test_bad_encdoing_errors():
+ # GH 39777
+ with tm.ensure_clean() as path:
+ with pytest.raises(LookupError, match="unknown error handler name"):
+ icom.get_handle(path, "w", errors="bad")
+
+
+def test_errno_attribute():
+ # GH 13872
+ with pytest.raises(FileNotFoundError, match="\\[Errno 2\\]") as err:
+ pd.read_csv("doesnt_exist")
+ assert err.errno == errno.ENOENT
+
+
+def test_fail_mmap():
+ with pytest.raises(UnsupportedOperation, match="fileno"):
+ with BytesIO() as buffer:
+ icom.get_handle(buffer, "rb", memory_map=True)
+
+
+def test_close_on_error():
+ # GH 47136
+ class TestError:
+ def close(self):
+ raise OSError("test")
+
+ with pytest.raises(OSError, match="test"):
+ with BytesIO() as buffer:
+ with icom.get_handle(buffer, "rb") as handles:
+ handles.created_handles.append(TestError())
+
+
+@pytest.mark.parametrize(
+ "reader",
+ [
+ pd.read_csv,
+ pd.read_fwf,
+ pd.read_excel,
+ pd.read_feather,
+ pd.read_hdf,
+ pd.read_stata,
+ pd.read_sas,
+ pd.read_json,
+ pd.read_pickle,
+ ],
+)
+def test_pickle_reader(reader):
+ # GH 22265
+ with BytesIO() as buffer:
+ pickle.dump(reader, buffer)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_compression.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_compression.py
new file mode 100644
index 0000000000000000000000000000000000000000..af83ec4a55fa58aa54384a32d16a5c6ea9dc7229
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_compression.py
@@ -0,0 +1,365 @@
+import gzip
+import io
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tarfile
+import textwrap
+import time
+import zipfile
+
+import pytest
+
+from pandas.compat import is_platform_windows
+
+import pandas as pd
+import pandas._testing as tm
+
+import pandas.io.common as icom
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ pd.DataFrame(
+ 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ columns=["X", "Y", "Z"],
+ ),
+ pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),
+ ],
+)
+@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"])
+def test_compression_size(obj, method, compression_only):
+ if compression_only == "tar":
+ compression_only = {"method": "tar", "mode": "w:gz"}
+
+ with tm.ensure_clean() as path:
+ getattr(obj, method)(path, compression=compression_only)
+ compressed_size = os.path.getsize(path)
+ getattr(obj, method)(path, compression=None)
+ uncompressed_size = os.path.getsize(path)
+ assert uncompressed_size > compressed_size
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ pd.DataFrame(
+ 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ columns=["X", "Y", "Z"],
+ ),
+ pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),
+ ],
+)
+@pytest.mark.parametrize("method", ["to_csv", "to_json"])
+def test_compression_size_fh(obj, method, compression_only):
+ with tm.ensure_clean() as path:
+ with icom.get_handle(
+ path,
+ "w:gz" if compression_only == "tar" else "w",
+ compression=compression_only,
+ ) as handles:
+ getattr(obj, method)(handles.handle)
+ assert not handles.handle.closed
+ compressed_size = os.path.getsize(path)
+ with tm.ensure_clean() as path:
+ with icom.get_handle(path, "w", compression=None) as handles:
+ getattr(obj, method)(handles.handle)
+ assert not handles.handle.closed
+ uncompressed_size = os.path.getsize(path)
+ assert uncompressed_size > compressed_size
+
+
+@pytest.mark.parametrize(
+ "write_method, write_kwargs, read_method",
+ [
+ ("to_csv", {"index": False}, pd.read_csv),
+ ("to_json", {}, pd.read_json),
+ ("to_pickle", {}, pd.read_pickle),
+ ],
+)
+def test_dataframe_compression_defaults_to_infer(
+ write_method, write_kwargs, read_method, compression_only, compression_to_extension
+):
+ # GH22004
+ input = pd.DataFrame([[1.0, 0, -4], [3.4, 5, 2]], columns=["X", "Y", "Z"])
+ extension = compression_to_extension[compression_only]
+ with tm.ensure_clean("compressed" + extension) as path:
+ getattr(input, write_method)(path, **write_kwargs)
+ output = read_method(path, compression=compression_only)
+ tm.assert_frame_equal(output, input)
+
+
+@pytest.mark.parametrize(
+ "write_method,write_kwargs,read_method,read_kwargs",
+ [
+ ("to_csv", {"index": False, "header": True}, pd.read_csv, {"squeeze": True}),
+ ("to_json", {}, pd.read_json, {"typ": "series"}),
+ ("to_pickle", {}, pd.read_pickle, {}),
+ ],
+)
+def test_series_compression_defaults_to_infer(
+ write_method,
+ write_kwargs,
+ read_method,
+ read_kwargs,
+ compression_only,
+ compression_to_extension,
+):
+ # GH22004
+ input = pd.Series([0, 5, -2, 10], name="X")
+ extension = compression_to_extension[compression_only]
+ with tm.ensure_clean("compressed" + extension) as path:
+ getattr(input, write_method)(path, **write_kwargs)
+ if "squeeze" in read_kwargs:
+ kwargs = read_kwargs.copy()
+ del kwargs["squeeze"]
+ output = read_method(path, compression=compression_only, **kwargs).squeeze(
+ "columns"
+ )
+ else:
+ output = read_method(path, compression=compression_only, **read_kwargs)
+ tm.assert_series_equal(output, input, check_names=False)
+
+
+def test_compression_warning(compression_only):
+ # Assert that passing a file object to to_csv while explicitly specifying a
+ # compression protocol triggers a RuntimeWarning, as per GH21227.
+ df = pd.DataFrame(
+ 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ columns=["X", "Y", "Z"],
+ )
+ with tm.ensure_clean() as path:
+ with icom.get_handle(path, "w", compression=compression_only) as handles:
+ with tm.assert_produces_warning(RuntimeWarning):
+ df.to_csv(handles.handle, compression=compression_only)
+
+
+def test_compression_binary(compression_only):
+ """
+ Binary file handles support compression.
+
+ GH22555
+ """
+ df = tm.makeDataFrame()
+
+ # with a file
+ with tm.ensure_clean() as path:
+ with open(path, mode="wb") as file:
+ df.to_csv(file, mode="wb", compression=compression_only)
+ file.seek(0) # file shouldn't be closed
+ tm.assert_frame_equal(
+ df, pd.read_csv(path, index_col=0, compression=compression_only)
+ )
+
+ # with BytesIO
+ file = io.BytesIO()
+ df.to_csv(file, mode="wb", compression=compression_only)
+ file.seek(0) # file shouldn't be closed
+ tm.assert_frame_equal(
+ df, pd.read_csv(file, index_col=0, compression=compression_only)
+ )
+
+
+def test_gzip_reproducibility_file_name():
+ """
+ Gzip should create reproducible archives with mtime.
+
+ Note: Archives created with different filenames will still be different!
+
+ GH 28103
+ """
+ df = tm.makeDataFrame()
+ compression_options = {"method": "gzip", "mtime": 1}
+
+ # test for filename
+ with tm.ensure_clean() as path:
+ path = Path(path)
+ df.to_csv(path, compression=compression_options)
+ time.sleep(0.1)
+ output = path.read_bytes()
+ df.to_csv(path, compression=compression_options)
+ assert output == path.read_bytes()
+
+
+def test_gzip_reproducibility_file_object():
+ """
+ Gzip should create reproducible archives with mtime.
+
+ GH 28103
+ """
+ df = tm.makeDataFrame()
+ compression_options = {"method": "gzip", "mtime": 1}
+
+ # test for file object
+ buffer = io.BytesIO()
+ df.to_csv(buffer, compression=compression_options, mode="wb")
+ output = buffer.getvalue()
+ time.sleep(0.1)
+ buffer = io.BytesIO()
+ df.to_csv(buffer, compression=compression_options, mode="wb")
+ assert output == buffer.getvalue()
+
+
+@pytest.mark.single_cpu
+def test_with_missing_lzma():
+ """Tests if import pandas works when lzma is not present."""
+ # https://github.com/pandas-dev/pandas/issues/27575
+ code = textwrap.dedent(
+ """\
+ import sys
+ sys.modules['lzma'] = None
+ import pandas
+ """
+ )
+ subprocess.check_output([sys.executable, "-c", code], stderr=subprocess.PIPE)
+
+
+@pytest.mark.single_cpu
+def test_with_missing_lzma_runtime():
+ """Tests if RuntimeError is hit when calling lzma without
+ having the module available.
+ """
+ code = textwrap.dedent(
+ """
+ import sys
+ import pytest
+ sys.modules['lzma'] = None
+ import pandas as pd
+ df = pd.DataFrame()
+ with pytest.raises(RuntimeError, match='lzma module'):
+ df.to_csv('foo.csv', compression='xz')
+ """
+ )
+ subprocess.check_output([sys.executable, "-c", code], stderr=subprocess.PIPE)
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ pd.DataFrame(
+ 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ columns=["X", "Y", "Z"],
+ ),
+ pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),
+ ],
+)
+@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"])
+def test_gzip_compression_level(obj, method):
+ # GH33196
+ with tm.ensure_clean() as path:
+ getattr(obj, method)(path, compression="gzip")
+ compressed_size_default = os.path.getsize(path)
+ getattr(obj, method)(path, compression={"method": "gzip", "compresslevel": 1})
+ compressed_size_fast = os.path.getsize(path)
+ assert compressed_size_default < compressed_size_fast
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ pd.DataFrame(
+ 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ columns=["X", "Y", "Z"],
+ ),
+ pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),
+ ],
+)
+@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"])
+def test_xz_compression_level_read(obj, method):
+ with tm.ensure_clean() as path:
+ getattr(obj, method)(path, compression="xz")
+ compressed_size_default = os.path.getsize(path)
+ getattr(obj, method)(path, compression={"method": "xz", "preset": 1})
+ compressed_size_fast = os.path.getsize(path)
+ assert compressed_size_default < compressed_size_fast
+ if method == "to_csv":
+ pd.read_csv(path, compression="xz")
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ pd.DataFrame(
+ 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ columns=["X", "Y", "Z"],
+ ),
+ pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),
+ ],
+)
+@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"])
+def test_bzip_compression_level(obj, method):
+ """GH33196 bzip needs file size > 100k to show a size difference between
+ compression levels, so here we just check if the call works when
+ compression is passed as a dict.
+ """
+ with tm.ensure_clean() as path:
+ getattr(obj, method)(path, compression={"method": "bz2", "compresslevel": 1})
+
+
+@pytest.mark.parametrize(
+ "suffix,archive",
+ [
+ (".zip", zipfile.ZipFile),
+ (".tar", tarfile.TarFile),
+ ],
+)
+def test_empty_archive_zip(suffix, archive):
+ with tm.ensure_clean(filename=suffix) as path:
+ with archive(path, "w"):
+ pass
+ with pytest.raises(ValueError, match="Zero files found"):
+ pd.read_csv(path)
+
+
+def test_ambiguous_archive_zip():
+ with tm.ensure_clean(filename=".zip") as path:
+ with zipfile.ZipFile(path, "w") as file:
+ file.writestr("a.csv", "foo,bar")
+ file.writestr("b.csv", "foo,bar")
+ with pytest.raises(ValueError, match="Multiple files found in ZIP file"):
+ pd.read_csv(path)
+
+
+def test_ambiguous_archive_tar(tmp_path):
+ csvAPath = tmp_path / "a.csv"
+ with open(csvAPath, "w", encoding="utf-8") as a:
+ a.write("foo,bar\n")
+ csvBPath = tmp_path / "b.csv"
+ with open(csvBPath, "w", encoding="utf-8") as b:
+ b.write("foo,bar\n")
+
+ tarpath = tmp_path / "archive.tar"
+ with tarfile.TarFile(tarpath, "w") as tar:
+ tar.add(csvAPath, "a.csv")
+ tar.add(csvBPath, "b.csv")
+
+ with pytest.raises(ValueError, match="Multiple files found in TAR archive"):
+ pd.read_csv(tarpath)
+
+
+def test_tar_gz_to_different_filename():
+ with tm.ensure_clean(filename=".foo") as file:
+ pd.DataFrame(
+ [["1", "2"]],
+ columns=["foo", "bar"],
+ ).to_csv(file, compression={"method": "tar", "mode": "w:gz"}, index=False)
+ with gzip.open(file) as uncompressed:
+ with tarfile.TarFile(fileobj=uncompressed) as archive:
+ members = archive.getmembers()
+ assert len(members) == 1
+ content = archive.extractfile(members[0]).read().decode("utf8")
+
+ if is_platform_windows():
+ expected = "foo,bar\r\n1,2\r\n"
+ else:
+ expected = "foo,bar\n1,2\n"
+
+ assert content == expected
+
+
+def test_tar_no_error_on_close():
+ with io.BytesIO() as buffer:
+ with icom._BytesTarFile(fileobj=buffer, mode="w"):
+ pass
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_feather.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_feather.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf43203466ef4f4ee85b30cb9124ce99f636b4ef
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_feather.py
@@ -0,0 +1,231 @@
+""" test feather-format compat """
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import (
+ ArrowStringArray,
+ StringArray,
+)
+
+from pandas.io.feather_format import read_feather, to_feather # isort:skip
+
+pyarrow = pytest.importorskip("pyarrow")
+
+
+@pytest.mark.single_cpu
+class TestFeather:
+ def check_error_on_write(self, df, exc, err_msg):
+ # check that we are raising the exception
+ # on writing
+
+ with pytest.raises(exc, match=err_msg):
+ with tm.ensure_clean() as path:
+ to_feather(df, path)
+
+ def check_external_error_on_write(self, df):
+ # check that we are raising the exception
+ # on writing
+
+ with tm.external_error_raised(Exception):
+ with tm.ensure_clean() as path:
+ to_feather(df, path)
+
+ def check_round_trip(self, df, expected=None, write_kwargs={}, **read_kwargs):
+ if expected is None:
+ expected = df.copy()
+
+ with tm.ensure_clean() as path:
+ to_feather(df, path, **write_kwargs)
+
+ result = read_feather(path, **read_kwargs)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_error(self):
+ msg = "feather only support IO with DataFrames"
+ for obj in [
+ pd.Series([1, 2, 3]),
+ 1,
+ "foo",
+ pd.Timestamp("20130101"),
+ np.array([1, 2, 3]),
+ ]:
+ self.check_error_on_write(obj, ValueError, msg)
+
+ def test_basic(self):
+ df = pd.DataFrame(
+ {
+ "string": list("abc"),
+ "int": list(range(1, 4)),
+ "uint": np.arange(3, 6).astype("u1"),
+ "float": np.arange(4.0, 7.0, dtype="float64"),
+ "float_with_null": [1.0, np.nan, 3],
+ "bool": [True, False, True],
+ "bool_with_null": [True, np.nan, False],
+ "cat": pd.Categorical(list("abc")),
+ "dt": pd.DatetimeIndex(
+ list(pd.date_range("20130101", periods=3)), freq=None
+ ),
+ "dttz": pd.DatetimeIndex(
+ list(pd.date_range("20130101", periods=3, tz="US/Eastern")),
+ freq=None,
+ ),
+ "dt_with_null": [
+ pd.Timestamp("20130101"),
+ pd.NaT,
+ pd.Timestamp("20130103"),
+ ],
+ "dtns": pd.DatetimeIndex(
+ list(pd.date_range("20130101", periods=3, freq="ns")), freq=None
+ ),
+ }
+ )
+ df["periods"] = pd.period_range("2013", freq="M", periods=3)
+ df["timedeltas"] = pd.timedelta_range("1 day", periods=3)
+ df["intervals"] = pd.interval_range(0, 3, 3)
+
+ assert df.dttz.dtype.tz.zone == "US/Eastern"
+
+ expected = df.copy()
+ expected.loc[1, "bool_with_null"] = None
+ self.check_round_trip(df, expected=expected)
+
+ def test_duplicate_columns(self):
+ # https://github.com/wesm/feather/issues/53
+ # not currently able to handle duplicate columns
+ df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy()
+ self.check_external_error_on_write(df)
+
+ def test_read_columns(self):
+ # GH 24025
+ df = pd.DataFrame(
+ {
+ "col1": list("abc"),
+ "col2": list(range(1, 4)),
+ "col3": list("xyz"),
+ "col4": list(range(4, 7)),
+ }
+ )
+ columns = ["col1", "col3"]
+ self.check_round_trip(df, expected=df[columns], columns=columns)
+
+ def test_read_columns_different_order(self):
+ # GH 33878
+ df = pd.DataFrame({"A": [1, 2], "B": ["x", "y"], "C": [True, False]})
+ expected = df[["B", "A"]]
+ self.check_round_trip(df, expected, columns=["B", "A"])
+
+ def test_unsupported_other(self):
+ # mixed python objects
+ df = pd.DataFrame({"a": ["a", 1, 2.0]})
+ self.check_external_error_on_write(df)
+
+ def test_rw_use_threads(self):
+ df = pd.DataFrame({"A": np.arange(100000)})
+ self.check_round_trip(df, use_threads=True)
+ self.check_round_trip(df, use_threads=False)
+
+ def test_path_pathlib(self):
+ df = tm.makeDataFrame().reset_index()
+ result = tm.round_trip_pathlib(df.to_feather, read_feather)
+ tm.assert_frame_equal(df, result)
+
+ def test_path_localpath(self):
+ df = tm.makeDataFrame().reset_index()
+ result = tm.round_trip_localpath(df.to_feather, read_feather)
+ tm.assert_frame_equal(df, result)
+
+ def test_passthrough_keywords(self):
+ df = tm.makeDataFrame().reset_index()
+ self.check_round_trip(df, write_kwargs={"version": 1})
+
+ @pytest.mark.network
+ @pytest.mark.single_cpu
+ def test_http_path(self, feather_file, httpserver):
+ # GH 29055
+ expected = read_feather(feather_file)
+ with open(feather_file, "rb") as f:
+ httpserver.serve_content(content=f.read())
+ res = read_feather(httpserver.url)
+ tm.assert_frame_equal(expected, res)
+
+ def test_read_feather_dtype_backend(self, string_storage, dtype_backend):
+ # GH#50765
+ pa = pytest.importorskip("pyarrow")
+ df = pd.DataFrame(
+ {
+ "a": pd.Series([1, np.nan, 3], dtype="Int64"),
+ "b": pd.Series([1, 2, 3], dtype="Int64"),
+ "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": [True, False, None],
+ "f": [True, False, True],
+ "g": ["a", "b", "c"],
+ "h": ["a", "b", None],
+ }
+ )
+
+ if string_storage == "python":
+ string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_))
+ string_array_na = StringArray(np.array(["a", "b", pd.NA], dtype=np.object_))
+
+ else:
+ string_array = ArrowStringArray(pa.array(["a", "b", "c"]))
+ string_array_na = ArrowStringArray(pa.array(["a", "b", None]))
+
+ with tm.ensure_clean() as path:
+ to_feather(df, path)
+ with pd.option_context("mode.string_storage", string_storage):
+ result = read_feather(path, dtype_backend=dtype_backend)
+
+ expected = pd.DataFrame(
+ {
+ "a": pd.Series([1, np.nan, 3], dtype="Int64"),
+ "b": pd.Series([1, 2, 3], dtype="Int64"),
+ "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": pd.Series([True, False, pd.NA], dtype="boolean"),
+ "f": pd.Series([True, False, True], dtype="boolean"),
+ "g": string_array,
+ "h": string_array_na,
+ }
+ )
+
+ if dtype_backend == "pyarrow":
+ from pandas.arrays import ArrowExtensionArray
+
+ expected = pd.DataFrame(
+ {
+ col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))
+ for col in expected.columns
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_int_columns_and_index(self):
+ df = pd.DataFrame({"a": [1, 2, 3]}, index=pd.Index([3, 4, 5], name="test"))
+ self.check_round_trip(df)
+
+ def test_invalid_dtype_backend(self):
+ msg = (
+ "dtype_backend numpy is invalid, only 'numpy_nullable' and "
+ "'pyarrow' are allowed."
+ )
+ df = pd.DataFrame({"int": list(range(1, 4))})
+ with tm.ensure_clean("tmp.feather") as path:
+ df.to_feather(path)
+ with pytest.raises(ValueError, match=msg):
+ read_feather(path, dtype_backend="numpy")
+
+ def test_string_inference(self, tmp_path):
+ # GH#54431
+ path = tmp_path / "test_string_inference.p"
+ df = pd.DataFrame(data={"a": ["x", "y"]})
+ df.to_feather(path)
+ with pd.option_context("future.infer_string", True):
+ result = read_feather(path)
+ expected = pd.DataFrame(data={"a": ["x", "y"]}, dtype="string[pyarrow_numpy]")
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_fsspec.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_fsspec.py
new file mode 100644
index 0000000000000000000000000000000000000000..030505f617b972a380d6bb4cde2dab45dc9d8918
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_fsspec.py
@@ -0,0 +1,319 @@
+import io
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ date_range,
+ read_csv,
+ read_excel,
+ read_feather,
+ read_json,
+ read_parquet,
+ read_pickle,
+ read_stata,
+ read_table,
+)
+import pandas._testing as tm
+from pandas.util import _test_decorators as td
+
+
+@pytest.fixture
+def df1():
+ return DataFrame(
+ {
+ "int": [1, 3],
+ "float": [2.0, np.nan],
+ "str": ["t", "s"],
+ "dt": date_range("2018-06-18", periods=2),
+ }
+ )
+
+
+@pytest.fixture
+def cleared_fs():
+ fsspec = pytest.importorskip("fsspec")
+
+ memfs = fsspec.filesystem("memory")
+ yield memfs
+ memfs.store.clear()
+
+
+def test_read_csv(cleared_fs, df1):
+ text = str(df1.to_csv(index=False)).encode()
+ with cleared_fs.open("test/test.csv", "wb") as w:
+ w.write(text)
+ df2 = read_csv("memory://test/test.csv", parse_dates=["dt"])
+
+ tm.assert_frame_equal(df1, df2)
+
+
+def test_reasonable_error(monkeypatch, cleared_fs):
+ from fsspec.registry import known_implementations
+
+ with pytest.raises(ValueError, match="nosuchprotocol"):
+ read_csv("nosuchprotocol://test/test.csv")
+ err_msg = "test error message"
+ monkeypatch.setitem(
+ known_implementations,
+ "couldexist",
+ {"class": "unimportable.CouldExist", "err": err_msg},
+ )
+ with pytest.raises(ImportError, match=err_msg):
+ read_csv("couldexist://test/test.csv")
+
+
+def test_to_csv(cleared_fs, df1):
+ df1.to_csv("memory://test/test.csv", index=True)
+
+ df2 = read_csv("memory://test/test.csv", parse_dates=["dt"], index_col=0)
+
+ tm.assert_frame_equal(df1, df2)
+
+
+def test_to_excel(cleared_fs, df1):
+ pytest.importorskip("openpyxl")
+ ext = "xlsx"
+ path = f"memory://test/test.{ext}"
+ df1.to_excel(path, index=True)
+
+ df2 = read_excel(path, parse_dates=["dt"], index_col=0)
+
+ tm.assert_frame_equal(df1, df2)
+
+
+@pytest.mark.parametrize("binary_mode", [False, True])
+def test_to_csv_fsspec_object(cleared_fs, binary_mode, df1):
+ fsspec = pytest.importorskip("fsspec")
+
+ path = "memory://test/test.csv"
+ mode = "wb" if binary_mode else "w"
+ with fsspec.open(path, mode=mode).open() as fsspec_object:
+ df1.to_csv(fsspec_object, index=True)
+ assert not fsspec_object.closed
+
+ mode = mode.replace("w", "r")
+ with fsspec.open(path, mode=mode) as fsspec_object:
+ df2 = read_csv(
+ fsspec_object,
+ parse_dates=["dt"],
+ index_col=0,
+ )
+ assert not fsspec_object.closed
+
+ tm.assert_frame_equal(df1, df2)
+
+
+def test_csv_options(fsspectest):
+ df = DataFrame({"a": [0]})
+ df.to_csv(
+ "testmem://test/test.csv", storage_options={"test": "csv_write"}, index=False
+ )
+ assert fsspectest.test[0] == "csv_write"
+ read_csv("testmem://test/test.csv", storage_options={"test": "csv_read"})
+ assert fsspectest.test[0] == "csv_read"
+
+
+def test_read_table_options(fsspectest):
+ # GH #39167
+ df = DataFrame({"a": [0]})
+ df.to_csv(
+ "testmem://test/test.csv", storage_options={"test": "csv_write"}, index=False
+ )
+ assert fsspectest.test[0] == "csv_write"
+ read_table("testmem://test/test.csv", storage_options={"test": "csv_read"})
+ assert fsspectest.test[0] == "csv_read"
+
+
+def test_excel_options(fsspectest):
+ pytest.importorskip("openpyxl")
+ extension = "xlsx"
+
+ df = DataFrame({"a": [0]})
+
+ path = f"testmem://test/test.{extension}"
+
+ df.to_excel(path, storage_options={"test": "write"}, index=False)
+ assert fsspectest.test[0] == "write"
+ read_excel(path, storage_options={"test": "read"})
+ assert fsspectest.test[0] == "read"
+
+
+def test_to_parquet_new_file(cleared_fs, df1):
+ """Regression test for writing to a not-yet-existent GCS Parquet file."""
+ pytest.importorskip("fastparquet")
+
+ df1.to_parquet(
+ "memory://test/test.csv", index=True, engine="fastparquet", compression=None
+ )
+
+
+def test_arrowparquet_options(fsspectest):
+ """Regression test for writing to a not-yet-existent GCS Parquet file."""
+ pytest.importorskip("pyarrow")
+ df = DataFrame({"a": [0]})
+ df.to_parquet(
+ "testmem://test/test.csv",
+ engine="pyarrow",
+ compression=None,
+ storage_options={"test": "parquet_write"},
+ )
+ assert fsspectest.test[0] == "parquet_write"
+ read_parquet(
+ "testmem://test/test.csv",
+ engine="pyarrow",
+ storage_options={"test": "parquet_read"},
+ )
+ assert fsspectest.test[0] == "parquet_read"
+
+
+@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) fastparquet
+def test_fastparquet_options(fsspectest):
+ """Regression test for writing to a not-yet-existent GCS Parquet file."""
+ pytest.importorskip("fastparquet")
+
+ df = DataFrame({"a": [0]})
+ df.to_parquet(
+ "testmem://test/test.csv",
+ engine="fastparquet",
+ compression=None,
+ storage_options={"test": "parquet_write"},
+ )
+ assert fsspectest.test[0] == "parquet_write"
+ read_parquet(
+ "testmem://test/test.csv",
+ engine="fastparquet",
+ storage_options={"test": "parquet_read"},
+ )
+ assert fsspectest.test[0] == "parquet_read"
+
+
+@pytest.mark.single_cpu
+def test_from_s3_csv(s3_public_bucket_with_data, tips_file, s3so):
+ pytest.importorskip("s3fs")
+ tm.assert_equal(
+ read_csv(
+ f"s3://{s3_public_bucket_with_data.name}/tips.csv", storage_options=s3so
+ ),
+ read_csv(tips_file),
+ )
+ # the following are decompressed by pandas, not fsspec
+ tm.assert_equal(
+ read_csv(
+ f"s3://{s3_public_bucket_with_data.name}/tips.csv.gz", storage_options=s3so
+ ),
+ read_csv(tips_file),
+ )
+ tm.assert_equal(
+ read_csv(
+ f"s3://{s3_public_bucket_with_data.name}/tips.csv.bz2", storage_options=s3so
+ ),
+ read_csv(tips_file),
+ )
+
+
+@pytest.mark.single_cpu
+@pytest.mark.parametrize("protocol", ["s3", "s3a", "s3n"])
+def test_s3_protocols(s3_public_bucket_with_data, tips_file, protocol, s3so):
+ pytest.importorskip("s3fs")
+ tm.assert_equal(
+ read_csv(
+ f"{protocol}://{s3_public_bucket_with_data.name}/tips.csv",
+ storage_options=s3so,
+ ),
+ read_csv(tips_file),
+ )
+
+
+@pytest.mark.single_cpu
+@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) fastparquet
+def test_s3_parquet(s3_public_bucket, s3so, df1):
+ pytest.importorskip("fastparquet")
+ pytest.importorskip("s3fs")
+
+ fn = f"s3://{s3_public_bucket.name}/test.parquet"
+ df1.to_parquet(
+ fn, index=False, engine="fastparquet", compression=None, storage_options=s3so
+ )
+ df2 = read_parquet(fn, engine="fastparquet", storage_options=s3so)
+ tm.assert_equal(df1, df2)
+
+
+@td.skip_if_installed("fsspec")
+def test_not_present_exception():
+ msg = "Missing optional dependency 'fsspec'|fsspec library is required"
+ with pytest.raises(ImportError, match=msg):
+ read_csv("memory://test/test.csv")
+
+
+def test_feather_options(fsspectest):
+ pytest.importorskip("pyarrow")
+ df = DataFrame({"a": [0]})
+ df.to_feather("testmem://mockfile", storage_options={"test": "feather_write"})
+ assert fsspectest.test[0] == "feather_write"
+ out = read_feather("testmem://mockfile", storage_options={"test": "feather_read"})
+ assert fsspectest.test[0] == "feather_read"
+ tm.assert_frame_equal(df, out)
+
+
+def test_pickle_options(fsspectest):
+ df = DataFrame({"a": [0]})
+ df.to_pickle("testmem://mockfile", storage_options={"test": "pickle_write"})
+ assert fsspectest.test[0] == "pickle_write"
+ out = read_pickle("testmem://mockfile", storage_options={"test": "pickle_read"})
+ assert fsspectest.test[0] == "pickle_read"
+ tm.assert_frame_equal(df, out)
+
+
+def test_json_options(fsspectest, compression):
+ df = DataFrame({"a": [0]})
+ df.to_json(
+ "testmem://mockfile",
+ compression=compression,
+ storage_options={"test": "json_write"},
+ )
+ assert fsspectest.test[0] == "json_write"
+ out = read_json(
+ "testmem://mockfile",
+ compression=compression,
+ storage_options={"test": "json_read"},
+ )
+ assert fsspectest.test[0] == "json_read"
+ tm.assert_frame_equal(df, out)
+
+
+def test_stata_options(fsspectest):
+ df = DataFrame({"a": [0]})
+ df.to_stata(
+ "testmem://mockfile", storage_options={"test": "stata_write"}, write_index=False
+ )
+ assert fsspectest.test[0] == "stata_write"
+ out = read_stata("testmem://mockfile", storage_options={"test": "stata_read"})
+ assert fsspectest.test[0] == "stata_read"
+ tm.assert_frame_equal(df, out.astype("int64"))
+
+
+def test_markdown_options(fsspectest):
+ pytest.importorskip("tabulate")
+ df = DataFrame({"a": [0]})
+ df.to_markdown("testmem://mockfile", storage_options={"test": "md_write"})
+ assert fsspectest.test[0] == "md_write"
+ assert fsspectest.cat("testmem://mockfile")
+
+
+def test_non_fsspec_options():
+ pytest.importorskip("pyarrow")
+ with pytest.raises(ValueError, match="storage_options"):
+ read_csv("localfile", storage_options={"a": True})
+ with pytest.raises(ValueError, match="storage_options"):
+ # separate test for parquet, which has a different code path
+ read_parquet("localfile", storage_options={"a": True})
+ by = io.BytesIO()
+
+ with pytest.raises(ValueError, match="storage_options"):
+ read_csv(by, storage_options={"a": True})
+
+ df = DataFrame({"a": [0]})
+ with pytest.raises(ValueError, match="storage_options"):
+ df.to_parquet("nonfsspecpath", storage_options={"a": True})
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_gcs.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_gcs.py
new file mode 100644
index 0000000000000000000000000000000000000000..89655e8693d7f099b0034496d564fcc9981b3a6f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_gcs.py
@@ -0,0 +1,210 @@
+from io import BytesIO
+import os
+import pathlib
+import tarfile
+import zipfile
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ date_range,
+ read_csv,
+ read_excel,
+ read_json,
+ read_parquet,
+)
+import pandas._testing as tm
+from pandas.util import _test_decorators as td
+
+
+@pytest.fixture
+def gcs_buffer():
+ """Emulate GCS using a binary buffer."""
+ pytest.importorskip("gcsfs")
+ fsspec = pytest.importorskip("fsspec")
+
+ gcs_buffer = BytesIO()
+ gcs_buffer.close = lambda: True
+
+ class MockGCSFileSystem(fsspec.AbstractFileSystem):
+ @staticmethod
+ def open(*args, **kwargs):
+ gcs_buffer.seek(0)
+ return gcs_buffer
+
+ def ls(self, path, **kwargs):
+ # needed for pyarrow
+ return [{"name": path, "type": "file"}]
+
+ # Overwrites the default implementation from gcsfs to our mock class
+ fsspec.register_implementation("gs", MockGCSFileSystem, clobber=True)
+
+ return gcs_buffer
+
+
+# Patches pyarrow; other processes should not pick up change
+@pytest.mark.single_cpu
+@pytest.mark.parametrize("format", ["csv", "json", "parquet", "excel", "markdown"])
+def test_to_read_gcs(gcs_buffer, format, monkeypatch, capsys):
+ """
+ Test that many to/read functions support GCS.
+
+ GH 33987
+ """
+
+ df1 = DataFrame(
+ {
+ "int": [1, 3],
+ "float": [2.0, np.nan],
+ "str": ["t", "s"],
+ "dt": date_range("2018-06-18", periods=2),
+ }
+ )
+
+ path = f"gs://test/test.{format}"
+
+ if format == "csv":
+ df1.to_csv(path, index=True)
+ df2 = read_csv(path, parse_dates=["dt"], index_col=0)
+ elif format == "excel":
+ path = "gs://test/test.xlsx"
+ df1.to_excel(path)
+ df2 = read_excel(path, parse_dates=["dt"], index_col=0)
+ elif format == "json":
+ df1.to_json(path)
+ df2 = read_json(path, convert_dates=["dt"])
+ elif format == "parquet":
+ pytest.importorskip("pyarrow")
+ pa_fs = pytest.importorskip("pyarrow.fs")
+
+ class MockFileSystem(pa_fs.FileSystem):
+ @staticmethod
+ def from_uri(path):
+ print("Using pyarrow filesystem")
+ to_local = pathlib.Path(path.replace("gs://", "")).absolute().as_uri()
+ return pa_fs.LocalFileSystem(to_local)
+
+ with monkeypatch.context() as m:
+ m.setattr(pa_fs, "FileSystem", MockFileSystem)
+ df1.to_parquet(path)
+ df2 = read_parquet(path)
+ captured = capsys.readouterr()
+ assert captured.out == "Using pyarrow filesystem\nUsing pyarrow filesystem\n"
+ elif format == "markdown":
+ pytest.importorskip("tabulate")
+ df1.to_markdown(path)
+ df2 = df1
+
+ tm.assert_frame_equal(df1, df2)
+
+
+def assert_equal_zip_safe(result: bytes, expected: bytes, compression: str):
+ """
+ For zip compression, only compare the CRC-32 checksum of the file contents
+ to avoid checking the time-dependent last-modified timestamp which
+ in some CI builds is off-by-one
+
+ See https://en.wikipedia.org/wiki/ZIP_(file_format)#File_headers
+ """
+ if compression == "zip":
+ # Only compare the CRC checksum of the file contents
+ with zipfile.ZipFile(BytesIO(result)) as exp, zipfile.ZipFile(
+ BytesIO(expected)
+ ) as res:
+ for res_info, exp_info in zip(res.infolist(), exp.infolist()):
+ assert res_info.CRC == exp_info.CRC
+ elif compression == "tar":
+ with tarfile.open(fileobj=BytesIO(result)) as tar_exp, tarfile.open(
+ fileobj=BytesIO(expected)
+ ) as tar_res:
+ for tar_res_info, tar_exp_info in zip(
+ tar_res.getmembers(), tar_exp.getmembers()
+ ):
+ actual_file = tar_res.extractfile(tar_res_info)
+ expected_file = tar_exp.extractfile(tar_exp_info)
+ assert (actual_file is None) == (expected_file is None)
+ if actual_file is not None and expected_file is not None:
+ assert actual_file.read() == expected_file.read()
+ else:
+ assert result == expected
+
+
+@pytest.mark.parametrize("encoding", ["utf-8", "cp1251"])
+def test_to_csv_compression_encoding_gcs(
+ gcs_buffer, compression_only, encoding, compression_to_extension
+):
+ """
+ Compression and encoding should with GCS.
+
+ GH 35677 (to_csv, compression), GH 26124 (to_csv, encoding), and
+ GH 32392 (read_csv, encoding)
+ """
+ df = tm.makeDataFrame()
+
+ # reference of compressed and encoded file
+ compression = {"method": compression_only}
+ if compression_only == "gzip":
+ compression["mtime"] = 1 # be reproducible
+ buffer = BytesIO()
+ df.to_csv(buffer, compression=compression, encoding=encoding, mode="wb")
+
+ # write compressed file with explicit compression
+ path_gcs = "gs://test/test.csv"
+ df.to_csv(path_gcs, compression=compression, encoding=encoding)
+ res = gcs_buffer.getvalue()
+ expected = buffer.getvalue()
+ assert_equal_zip_safe(res, expected, compression_only)
+
+ read_df = read_csv(
+ path_gcs, index_col=0, compression=compression_only, encoding=encoding
+ )
+ tm.assert_frame_equal(df, read_df)
+
+ # write compressed file with implicit compression
+ file_ext = compression_to_extension[compression_only]
+ compression["method"] = "infer"
+ path_gcs += f".{file_ext}"
+ df.to_csv(path_gcs, compression=compression, encoding=encoding)
+
+ res = gcs_buffer.getvalue()
+ expected = buffer.getvalue()
+ assert_equal_zip_safe(res, expected, compression_only)
+
+ read_df = read_csv(path_gcs, index_col=0, compression="infer", encoding=encoding)
+ tm.assert_frame_equal(df, read_df)
+
+
+def test_to_parquet_gcs_new_file(monkeypatch, tmpdir):
+ """Regression test for writing to a not-yet-existent GCS Parquet file."""
+ pytest.importorskip("fastparquet")
+ pytest.importorskip("gcsfs")
+
+ from fsspec import AbstractFileSystem
+
+ df1 = DataFrame(
+ {
+ "int": [1, 3],
+ "float": [2.0, np.nan],
+ "str": ["t", "s"],
+ "dt": date_range("2018-06-18", periods=2),
+ }
+ )
+
+ class MockGCSFileSystem(AbstractFileSystem):
+ def open(self, path, mode="r", *args):
+ if "w" not in mode:
+ raise FileNotFoundError
+ return open(os.path.join(tmpdir, "test.parquet"), mode, encoding="utf-8")
+
+ monkeypatch.setattr("gcsfs.GCSFileSystem", MockGCSFileSystem)
+ df1.to_parquet(
+ "gs://test/test.csv", index=True, engine="fastparquet", compression=None
+ )
+
+
+@td.skip_if_installed("gcsfs")
+def test_gcs_not_present_exception():
+ with tm.external_error_raised(ImportError):
+ read_csv("gs://test/test.csv")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_html.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_html.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cf90749e5b30c98be74cc517a2779cc0dcef38c
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_html.py
@@ -0,0 +1,1627 @@
+from collections.abc import Iterator
+from functools import partial
+from io import (
+ BytesIO,
+ StringIO,
+)
+import os
+from pathlib import Path
+import re
+import threading
+from urllib.error import URLError
+
+import numpy as np
+import pytest
+
+from pandas.compat import is_platform_windows
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ NA,
+ DataFrame,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+ read_csv,
+ read_html,
+ to_datetime,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ ArrowStringArray,
+ StringArray,
+)
+
+from pandas.io.common import file_path_to_url
+
+
+@pytest.fixture(
+ params=[
+ "chinese_utf-16.html",
+ "chinese_utf-32.html",
+ "chinese_utf-8.html",
+ "letz_latin1.html",
+ ]
+)
+def html_encoding_file(request, datapath):
+ """Parametrized fixture for HTML encoding test filenames."""
+ return datapath("io", "data", "html_encoding", request.param)
+
+
+def assert_framelist_equal(list1, list2, *args, **kwargs):
+ assert len(list1) == len(list2), (
+ "lists are not of equal size "
+ f"len(list1) == {len(list1)}, "
+ f"len(list2) == {len(list2)}"
+ )
+ msg = "not all list elements are DataFrames"
+ both_frames = all(
+ map(
+ lambda x, y: isinstance(x, DataFrame) and isinstance(y, DataFrame),
+ list1,
+ list2,
+ )
+ )
+ assert both_frames, msg
+ for frame_i, frame_j in zip(list1, list2):
+ tm.assert_frame_equal(frame_i, frame_j, *args, **kwargs)
+ assert not frame_i.empty, "frames are both empty"
+
+
+def test_bs4_version_fails(monkeypatch, datapath):
+ bs4 = pytest.importorskip("bs4")
+ pytest.importorskip("html5lib")
+
+ monkeypatch.setattr(bs4, "__version__", "4.2")
+ with pytest.raises(ImportError, match="Pandas requires version"):
+ read_html(datapath("io", "data", "html", "spam.html"), flavor="bs4")
+
+
+def test_invalid_flavor():
+ url = "google.com"
+ flavor = "invalid flavor"
+ msg = r"\{" + flavor + r"\} is not a valid set of flavors"
+
+ with pytest.raises(ValueError, match=msg):
+ read_html(StringIO(url), match="google", flavor=flavor)
+
+
+def test_same_ordering(datapath):
+ pytest.importorskip("bs4")
+ pytest.importorskip("lxml")
+ pytest.importorskip("html5lib")
+
+ filename = datapath("io", "data", "html", "valid_markup.html")
+ dfs_lxml = read_html(filename, index_col=0, flavor=["lxml"])
+ dfs_bs4 = read_html(filename, index_col=0, flavor=["bs4"])
+ assert_framelist_equal(dfs_lxml, dfs_bs4)
+
+
+@pytest.mark.parametrize(
+ "flavor",
+ [
+ pytest.param("bs4", marks=[td.skip_if_no("bs4"), td.skip_if_no("html5lib")]),
+ pytest.param("lxml", marks=td.skip_if_no("lxml")),
+ ],
+)
+class TestReadHtml:
+ def test_literal_html_deprecation(self):
+ # GH 53785
+ msg = (
+ "Passing literal html to 'read_html' is deprecated and "
+ "will be removed in a future version. To read from a "
+ "literal string, wrap it in a 'StringIO' object."
+ )
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ self.read_html(
+ """
+
+
+ A
+ B
+
+
+
+
+ 1
+ 2
+
+
+
+
+ 3
+ 4
+
+
+
"""
+ )
+
+ @pytest.fixture
+ def spam_data(self, datapath):
+ return datapath("io", "data", "html", "spam.html")
+
+ @pytest.fixture
+ def banklist_data(self, datapath):
+ return datapath("io", "data", "html", "banklist.html")
+
+ @pytest.fixture(autouse=True)
+ def set_defaults(self, flavor):
+ self.read_html = partial(read_html, flavor=flavor)
+ yield
+
+ def test_to_html_compat(self):
+ df = (
+ tm.makeCustomDataframe(
+ 4,
+ 3,
+ data_gen_f=lambda *args: np.random.default_rng(2).random(),
+ c_idx_names=False,
+ r_idx_names=False,
+ )
+ # pylint: disable-next=consider-using-f-string
+ .map("{:.3f}".format).astype(float)
+ )
+ out = df.to_html()
+ res = self.read_html(StringIO(out), attrs={"class": "dataframe"}, index_col=0)[
+ 0
+ ]
+ tm.assert_frame_equal(res, df)
+
+ def test_dtype_backend(self, string_storage, dtype_backend):
+ # GH#50286
+ df = DataFrame(
+ {
+ "a": Series([1, np.nan, 3], dtype="Int64"),
+ "b": Series([1, 2, 3], dtype="Int64"),
+ "c": Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": [True, False, None],
+ "f": [True, False, True],
+ "g": ["a", "b", "c"],
+ "h": ["a", "b", None],
+ }
+ )
+
+ if string_storage == "python":
+ string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_))
+ string_array_na = StringArray(np.array(["a", "b", NA], dtype=np.object_))
+
+ else:
+ pa = pytest.importorskip("pyarrow")
+ string_array = ArrowStringArray(pa.array(["a", "b", "c"]))
+ string_array_na = ArrowStringArray(pa.array(["a", "b", None]))
+
+ out = df.to_html(index=False)
+ with pd.option_context("mode.string_storage", string_storage):
+ result = self.read_html(StringIO(out), dtype_backend=dtype_backend)[0]
+
+ expected = DataFrame(
+ {
+ "a": Series([1, np.nan, 3], dtype="Int64"),
+ "b": Series([1, 2, 3], dtype="Int64"),
+ "c": Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": Series([True, False, NA], dtype="boolean"),
+ "f": Series([True, False, True], dtype="boolean"),
+ "g": string_array,
+ "h": string_array_na,
+ }
+ )
+
+ if dtype_backend == "pyarrow":
+ import pyarrow as pa
+
+ from pandas.arrays import ArrowExtensionArray
+
+ expected = DataFrame(
+ {
+ col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))
+ for col in expected.columns
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.network
+ @pytest.mark.single_cpu
+ def test_banklist_url(self, httpserver, banklist_data):
+ with open(banklist_data, encoding="utf-8") as f:
+ httpserver.serve_content(content=f.read())
+ df1 = self.read_html(
+ # lxml cannot find attrs leave out for now
+ httpserver.url,
+ match="First Federal Bank of Florida", # attrs={"class": "dataTable"}
+ )
+ # lxml cannot find attrs leave out for now
+ df2 = self.read_html(
+ httpserver.url,
+ match="Metcalf Bank",
+ ) # attrs={"class": "dataTable"})
+
+ assert_framelist_equal(df1, df2)
+
+ @pytest.mark.network
+ @pytest.mark.single_cpu
+ def test_spam_url(self, httpserver, spam_data):
+ with open(spam_data, encoding="utf-8") as f:
+ httpserver.serve_content(content=f.read())
+ df1 = self.read_html(httpserver.url, match=".*Water.*")
+ df2 = self.read_html(httpserver.url, match="Unit")
+
+ assert_framelist_equal(df1, df2)
+
+ @pytest.mark.slow
+ def test_banklist(self, banklist_data):
+ df1 = self.read_html(banklist_data, match=".*Florida.*", attrs={"id": "table"})
+ df2 = self.read_html(banklist_data, match="Metcalf Bank", attrs={"id": "table"})
+
+ assert_framelist_equal(df1, df2)
+
+ def test_spam(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*")
+ df2 = self.read_html(spam_data, match="Unit")
+ assert_framelist_equal(df1, df2)
+
+ assert df1[0].iloc[0, 0] == "Proximates"
+ assert df1[0].columns[0] == "Nutrient"
+
+ def test_spam_no_match(self, spam_data):
+ dfs = self.read_html(spam_data)
+ for df in dfs:
+ assert isinstance(df, DataFrame)
+
+ def test_banklist_no_match(self, banklist_data):
+ dfs = self.read_html(banklist_data, attrs={"id": "table"})
+ for df in dfs:
+ assert isinstance(df, DataFrame)
+
+ def test_spam_header(self, spam_data):
+ df = self.read_html(spam_data, match=".*Water.*", header=2)[0]
+ assert df.columns[0] == "Proximates"
+ assert not df.empty
+
+ def test_skiprows_int(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", skiprows=1)
+ df2 = self.read_html(spam_data, match="Unit", skiprows=1)
+
+ assert_framelist_equal(df1, df2)
+
+ def test_skiprows_range(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", skiprows=range(2))
+ df2 = self.read_html(spam_data, match="Unit", skiprows=range(2))
+
+ assert_framelist_equal(df1, df2)
+
+ def test_skiprows_list(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", skiprows=[1, 2])
+ df2 = self.read_html(spam_data, match="Unit", skiprows=[2, 1])
+
+ assert_framelist_equal(df1, df2)
+
+ def test_skiprows_set(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", skiprows={1, 2})
+ df2 = self.read_html(spam_data, match="Unit", skiprows={2, 1})
+
+ assert_framelist_equal(df1, df2)
+
+ def test_skiprows_slice(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", skiprows=1)
+ df2 = self.read_html(spam_data, match="Unit", skiprows=1)
+
+ assert_framelist_equal(df1, df2)
+
+ def test_skiprows_slice_short(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", skiprows=slice(2))
+ df2 = self.read_html(spam_data, match="Unit", skiprows=slice(2))
+
+ assert_framelist_equal(df1, df2)
+
+ def test_skiprows_slice_long(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", skiprows=slice(2, 5))
+ df2 = self.read_html(spam_data, match="Unit", skiprows=slice(4, 1, -1))
+
+ assert_framelist_equal(df1, df2)
+
+ def test_skiprows_ndarray(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", skiprows=np.arange(2))
+ df2 = self.read_html(spam_data, match="Unit", skiprows=np.arange(2))
+
+ assert_framelist_equal(df1, df2)
+
+ def test_skiprows_invalid(self, spam_data):
+ with pytest.raises(TypeError, match=("is not a valid type for skipping rows")):
+ self.read_html(spam_data, match=".*Water.*", skiprows="asdf")
+
+ def test_index(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", index_col=0)
+ df2 = self.read_html(spam_data, match="Unit", index_col=0)
+ assert_framelist_equal(df1, df2)
+
+ def test_header_and_index_no_types(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", header=1, index_col=0)
+ df2 = self.read_html(spam_data, match="Unit", header=1, index_col=0)
+ assert_framelist_equal(df1, df2)
+
+ def test_header_and_index_with_types(self, spam_data):
+ df1 = self.read_html(spam_data, match=".*Water.*", header=1, index_col=0)
+ df2 = self.read_html(spam_data, match="Unit", header=1, index_col=0)
+ assert_framelist_equal(df1, df2)
+
+ def test_infer_types(self, spam_data):
+ # 10892 infer_types removed
+ df1 = self.read_html(spam_data, match=".*Water.*", index_col=0)
+ df2 = self.read_html(spam_data, match="Unit", index_col=0)
+ assert_framelist_equal(df1, df2)
+
+ def test_string_io(self, spam_data):
+ with open(spam_data, encoding="UTF-8") as f:
+ data1 = StringIO(f.read())
+
+ with open(spam_data, encoding="UTF-8") as f:
+ data2 = StringIO(f.read())
+
+ df1 = self.read_html(data1, match=".*Water.*")
+ df2 = self.read_html(data2, match="Unit")
+ assert_framelist_equal(df1, df2)
+
+ def test_string(self, spam_data):
+ with open(spam_data, encoding="UTF-8") as f:
+ data = f.read()
+
+ df1 = self.read_html(StringIO(data), match=".*Water.*")
+ df2 = self.read_html(StringIO(data), match="Unit")
+
+ assert_framelist_equal(df1, df2)
+
+ def test_file_like(self, spam_data):
+ with open(spam_data, encoding="UTF-8") as f:
+ df1 = self.read_html(f, match=".*Water.*")
+
+ with open(spam_data, encoding="UTF-8") as f:
+ df2 = self.read_html(f, match="Unit")
+
+ assert_framelist_equal(df1, df2)
+
+ @pytest.mark.network
+ @pytest.mark.single_cpu
+ def test_bad_url_protocol(self, httpserver):
+ httpserver.serve_content("urlopen error unknown url type: git", code=404)
+ with pytest.raises(URLError, match="urlopen error unknown url type: git"):
+ self.read_html("git://github.com", match=".*Water.*")
+
+ @pytest.mark.slow
+ @pytest.mark.network
+ @pytest.mark.single_cpu
+ def test_invalid_url(self, httpserver):
+ httpserver.serve_content("Name or service not known", code=404)
+ with pytest.raises((URLError, ValueError), match="HTTP Error 404: NOT FOUND"):
+ self.read_html(httpserver.url, match=".*Water.*")
+
+ @pytest.mark.slow
+ def test_file_url(self, banklist_data):
+ url = banklist_data
+ dfs = self.read_html(
+ file_path_to_url(os.path.abspath(url)), match="First", attrs={"id": "table"}
+ )
+ assert isinstance(dfs, list)
+ for df in dfs:
+ assert isinstance(df, DataFrame)
+
+ @pytest.mark.slow
+ def test_invalid_table_attrs(self, banklist_data):
+ url = banklist_data
+ with pytest.raises(ValueError, match="No tables found"):
+ self.read_html(
+ url, match="First Federal Bank of Florida", attrs={"id": "tasdfable"}
+ )
+
+ def _bank_data(self, path, **kwargs):
+ return self.read_html(path, match="Metcalf", attrs={"id": "table"}, **kwargs)
+
+ @pytest.mark.slow
+ def test_multiindex_header(self, banklist_data):
+ df = self._bank_data(banklist_data, header=[0, 1])[0]
+ assert isinstance(df.columns, MultiIndex)
+
+ @pytest.mark.slow
+ def test_multiindex_index(self, banklist_data):
+ df = self._bank_data(banklist_data, index_col=[0, 1])[0]
+ assert isinstance(df.index, MultiIndex)
+
+ @pytest.mark.slow
+ def test_multiindex_header_index(self, banklist_data):
+ df = self._bank_data(banklist_data, header=[0, 1], index_col=[0, 1])[0]
+ assert isinstance(df.columns, MultiIndex)
+ assert isinstance(df.index, MultiIndex)
+
+ @pytest.mark.slow
+ def test_multiindex_header_skiprows_tuples(self, banklist_data):
+ df = self._bank_data(banklist_data, header=[0, 1], skiprows=1)[0]
+ assert isinstance(df.columns, MultiIndex)
+
+ @pytest.mark.slow
+ def test_multiindex_header_skiprows(self, banklist_data):
+ df = self._bank_data(banklist_data, header=[0, 1], skiprows=1)[0]
+ assert isinstance(df.columns, MultiIndex)
+
+ @pytest.mark.slow
+ def test_multiindex_header_index_skiprows(self, banklist_data):
+ df = self._bank_data(
+ banklist_data, header=[0, 1], index_col=[0, 1], skiprows=1
+ )[0]
+ assert isinstance(df.index, MultiIndex)
+ assert isinstance(df.columns, MultiIndex)
+
+ @pytest.mark.slow
+ def test_regex_idempotency(self, banklist_data):
+ url = banklist_data
+ dfs = self.read_html(
+ file_path_to_url(os.path.abspath(url)),
+ match=re.compile(re.compile("Florida")),
+ attrs={"id": "table"},
+ )
+ assert isinstance(dfs, list)
+ for df in dfs:
+ assert isinstance(df, DataFrame)
+
+ def test_negative_skiprows(self, spam_data):
+ msg = r"\(you passed a negative value\)"
+ with pytest.raises(ValueError, match=msg):
+ self.read_html(spam_data, match="Water", skiprows=-1)
+
+ @pytest.fixture
+ def python_docs(self):
+ return """
+
+
+ What's new in Python 2.7?
+ or all "What's new" documents since 2.0
+ Tutorial
+ start here
+ Library Reference
+ keep this under your pillow
+ Language Reference
+ describes syntax and language elements
+ Python Setup and Usage
+ how to use Python on different platforms
+ Python HOWTOs
+ in-depth documents on specific topics
+
+ Installing Python Modules
+ installing from the Python Package Index & other sources
+ Distributing Python Modules
+ publishing modules for installation by others
+ Extending and Embedding
+ tutorial for C/C++ programmers
+ Python/C API
+ reference for C/C++ programmers
+ FAQs
+ frequently asked questions (with answers!)
+
+
+
+ Indices and tables:
+
+
+ Python Global Module Index
+ quick access to all modules
+ General Index
+ all functions, classes, terms
+ Glossary
+ the most important terms explained
+
+ Search page
+ search this documentation
+ Complete Table of Contents
+ lists all sections and subsections
+
+
+ """ # noqa: E501
+
+ @pytest.mark.network
+ @pytest.mark.single_cpu
+ def test_multiple_matches(self, python_docs, httpserver):
+ httpserver.serve_content(content=python_docs)
+ dfs = self.read_html(httpserver.url, match="Python")
+ assert len(dfs) > 1
+
+ @pytest.mark.network
+ @pytest.mark.single_cpu
+ def test_python_docs_table(self, python_docs, httpserver):
+ httpserver.serve_content(content=python_docs)
+ dfs = self.read_html(httpserver.url, match="Python")
+ zz = [df.iloc[0, 0][0:4] for df in dfs]
+ assert sorted(zz) == ["Pyth", "What"]
+
+ def test_empty_tables(self):
+ """
+ Make sure that read_html ignores empty tables.
+ """
+ html = """
+
+
+
+ A
+ B
+
+
+
+
+ 1
+ 2
+
+
+
+
+ """
+ result = self.read_html(StringIO(html))
+ assert len(result) == 1
+
+ def test_multiple_tbody(self):
+ # GH-20690
+ # Read all tbody tags within a single table.
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ A
+ B
+
+
+
+
+ 1
+ 2
+
+
+
+
+ 3
+ 4
+
+
+
"""
+ )
+ )[0]
+
+ expected = DataFrame(data=[[1, 2], [3, 4]], columns=["A", "B"])
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_header_and_one_column(self):
+ """
+ Don't fail with bs4 when there is a header and only one column
+ as described in issue #9178
+ """
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ Header
+
+
+
+
+ first
+
+
+
"""
+ )
+ )[0]
+
+ expected = DataFrame(data={"Header": "first"}, index=[0])
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_thead_without_tr(self):
+ """
+ Ensure parser adds within on malformed HTML.
+ """
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ Country
+ Municipality
+ Year
+
+
+
+
+ Ukraine
+ Odessa
+ 1944
+
+
+
"""
+ )
+ )[0]
+
+ expected = DataFrame(
+ data=[["Ukraine", "Odessa", 1944]],
+ columns=["Country", "Municipality", "Year"],
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_tfoot_read(self):
+ """
+ Make sure that read_html reads tfoot, containing td or th.
+ Ignores empty tfoot
+ """
+ data_template = """
+
+
+ A
+ B
+
+
+
+
+ bodyA
+ bodyB
+
+
+
+ {footer}
+
+
"""
+
+ expected1 = DataFrame(data=[["bodyA", "bodyB"]], columns=["A", "B"])
+
+ expected2 = DataFrame(
+ data=[["bodyA", "bodyB"], ["footA", "footB"]], columns=["A", "B"]
+ )
+
+ data1 = data_template.format(footer="")
+ data2 = data_template.format(footer="footA footB ")
+
+ result1 = self.read_html(StringIO(data1))[0]
+ result2 = self.read_html(StringIO(data2))[0]
+
+ tm.assert_frame_equal(result1, expected1)
+ tm.assert_frame_equal(result2, expected2)
+
+ def test_parse_header_of_non_string_column(self):
+ # GH5048: if header is specified explicitly, an int column should be
+ # parsed as int while its header is parsed as str
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ S
+ I
+
+
+ text
+ 1944
+
+
+ """
+ ),
+ header=0,
+ )[0]
+
+ expected = DataFrame([["text", 1944]], columns=("S", "I"))
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.slow
+ def test_banklist_header(self, banklist_data, datapath):
+ from pandas.io.html import _remove_whitespace
+
+ def try_remove_ws(x):
+ try:
+ return _remove_whitespace(x)
+ except AttributeError:
+ return x
+
+ df = self.read_html(banklist_data, match="Metcalf", attrs={"id": "table"})[0]
+ ground_truth = read_csv(
+ datapath("io", "data", "csv", "banklist.csv"),
+ converters={"Updated Date": Timestamp, "Closing Date": Timestamp},
+ )
+ assert df.shape == ground_truth.shape
+ old = [
+ "First Vietnamese American Bank In Vietnamese",
+ "Westernbank Puerto Rico En Espanol",
+ "R-G Premier Bank of Puerto Rico En Espanol",
+ "Eurobank En Espanol",
+ "Sanderson State Bank En Espanol",
+ "Washington Mutual Bank (Including its subsidiary Washington "
+ "Mutual Bank FSB)",
+ "Silver State Bank En Espanol",
+ "AmTrade International Bank En Espanol",
+ "Hamilton Bank, NA En Espanol",
+ "The Citizens Savings Bank Pioneer Community Bank, Inc.",
+ ]
+ new = [
+ "First Vietnamese American Bank",
+ "Westernbank Puerto Rico",
+ "R-G Premier Bank of Puerto Rico",
+ "Eurobank",
+ "Sanderson State Bank",
+ "Washington Mutual Bank",
+ "Silver State Bank",
+ "AmTrade International Bank",
+ "Hamilton Bank, NA",
+ "The Citizens Savings Bank",
+ ]
+ dfnew = df.map(try_remove_ws).replace(old, new)
+ gtnew = ground_truth.map(try_remove_ws)
+ converted = dfnew
+ date_cols = ["Closing Date", "Updated Date"]
+ converted[date_cols] = converted[date_cols].apply(to_datetime)
+ tm.assert_frame_equal(converted, gtnew)
+
+ @pytest.mark.slow
+ def test_gold_canyon(self, banklist_data):
+ gc = "Gold Canyon"
+ with open(banklist_data, encoding="utf-8") as f:
+ raw_text = f.read()
+
+ assert gc in raw_text
+ df = self.read_html(banklist_data, match="Gold Canyon", attrs={"id": "table"})[
+ 0
+ ]
+ assert gc in df.to_string()
+
+ def test_different_number_of_cols(self):
+ expected = self.read_html(
+ StringIO(
+ """
+
+
+
+ C_l0_g0
+ C_l0_g1
+ C_l0_g2
+ C_l0_g3
+ C_l0_g4
+
+
+
+
+ R_l0_g0
+ 0.763
+ 0.233
+ nan
+ nan
+ nan
+
+
+ R_l0_g1
+ 0.244
+ 0.285
+ 0.392
+ 0.137
+ 0.222
+
+
+
"""
+ ),
+ index_col=0,
+ )[0]
+
+ result = self.read_html(
+ StringIO(
+ """
+
+
+
+ C_l0_g0
+ C_l0_g1
+ C_l0_g2
+ C_l0_g3
+ C_l0_g4
+
+
+
+
+ R_l0_g0
+ 0.763
+ 0.233
+
+
+ R_l0_g1
+ 0.244
+ 0.285
+ 0.392
+ 0.137
+ 0.222
+
+
+
"""
+ ),
+ index_col=0,
+ )[0]
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_colspan_rowspan_1(self):
+ # GH17054
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ A
+ B
+ C
+
+
+ a
+ b
+ c
+
+
+ """
+ )
+ )[0]
+
+ expected = DataFrame([["a", "b", "c"]], columns=["A", "B", "C"])
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_colspan_rowspan_copy_values(self):
+ # GH17054
+
+ # In ASCII, with lowercase letters being copies:
+ #
+ # X x Y Z W
+ # A B b z C
+
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ X
+ Y
+ Z
+ W
+
+
+ A
+ B
+ C
+
+
+ """
+ ),
+ header=0,
+ )[0]
+
+ expected = DataFrame(
+ data=[["A", "B", "B", "Z", "C"]], columns=["X", "X.1", "Y", "Z", "W"]
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_colspan_rowspan_both_not_1(self):
+ # GH17054
+
+ # In ASCII, with lowercase letters being copies:
+ #
+ # A B b b C
+ # a b b b D
+
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ A
+ B
+ C
+
+
+ D
+
+
+ """
+ ),
+ header=0,
+ )[0]
+
+ expected = DataFrame(
+ data=[["A", "B", "B", "B", "D"]], columns=["A", "B", "B.1", "B.2", "C"]
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_rowspan_at_end_of_row(self):
+ # GH17054
+
+ # In ASCII, with lowercase letters being copies:
+ #
+ # A B
+ # C b
+
+ result = self.read_html(
+ StringIO(
+ """
+
+ """
+ ),
+ header=0,
+ )[0]
+
+ expected = DataFrame(data=[["C", "B"]], columns=["A", "B"])
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_rowspan_only_rows(self):
+ # GH17054
+
+ result = self.read_html(
+ StringIO(
+ """
+
+ """
+ ),
+ header=0,
+ )[0]
+
+ expected = DataFrame(data=[["A", "B"], ["A", "B"]], columns=["A", "B"])
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_header_inferred_from_rows_with_only_th(self):
+ # GH17054
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ A
+ B
+
+
+ a
+ b
+
+
+ 1
+ 2
+
+
+ """
+ )
+ )[0]
+
+ columns = MultiIndex(levels=[["A", "B"], ["a", "b"]], codes=[[0, 1], [0, 1]])
+ expected = DataFrame(data=[[1, 2]], columns=columns)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_parse_dates_list(self):
+ df = DataFrame({"date": date_range("1/1/2001", periods=10)})
+ expected = df.to_html()
+ res = self.read_html(StringIO(expected), parse_dates=[1], index_col=0)
+ tm.assert_frame_equal(df, res[0])
+ res = self.read_html(StringIO(expected), parse_dates=["date"], index_col=0)
+ tm.assert_frame_equal(df, res[0])
+
+ def test_parse_dates_combine(self):
+ raw_dates = Series(date_range("1/1/2001", periods=10))
+ df = DataFrame(
+ {
+ "date": raw_dates.map(lambda x: str(x.date())),
+ "time": raw_dates.map(lambda x: str(x.time())),
+ }
+ )
+ res = self.read_html(
+ StringIO(df.to_html()), parse_dates={"datetime": [1, 2]}, index_col=1
+ )
+ newdf = DataFrame({"datetime": raw_dates})
+ tm.assert_frame_equal(newdf, res[0])
+
+ def test_wikipedia_states_table(self, datapath):
+ data = datapath("io", "data", "html", "wikipedia_states.html")
+ assert os.path.isfile(data), f"{repr(data)} is not a file"
+ assert os.path.getsize(data), f"{repr(data)} is an empty file"
+ result = self.read_html(data, match="Arizona", header=1)[0]
+ assert result.shape == (60, 12)
+ assert "Unnamed" in result.columns[-1]
+ assert result["sq mi"].dtype == np.dtype("float64")
+ assert np.allclose(result.loc[0, "sq mi"], 665384.04)
+
+ def test_wikipedia_states_multiindex(self, datapath):
+ data = datapath("io", "data", "html", "wikipedia_states.html")
+ result = self.read_html(data, match="Arizona", index_col=0)[0]
+ assert result.shape == (60, 11)
+ assert "Unnamed" in result.columns[-1][1]
+ assert result.columns.nlevels == 2
+ assert np.allclose(result.loc["Alaska", ("Total area[2]", "sq mi")], 665384.04)
+
+ def test_parser_error_on_empty_header_row(self):
+ result = self.read_html(
+ StringIO(
+ """
+
+ """
+ ),
+ header=[0, 1],
+ )
+ expected = DataFrame(
+ [["a", "b"]],
+ columns=MultiIndex.from_tuples(
+ [("Unnamed: 0_level_0", "A"), ("Unnamed: 1_level_0", "B")]
+ ),
+ )
+ tm.assert_frame_equal(result[0], expected)
+
+ def test_decimal_rows(self):
+ # GH 12907
+ result = self.read_html(
+ StringIO(
+ """
+
+
+
+
+ Header
+
+
+
+
+ 1100#101
+
+
+
+
+ """
+ ),
+ decimal="#",
+ )[0]
+
+ expected = DataFrame(data={"Header": 1100.101}, index=[0])
+
+ assert result["Header"].dtype == np.dtype("float64")
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("arg", [True, False])
+ def test_bool_header_arg(self, spam_data, arg):
+ # GH 6114
+ msg = re.escape(
+ "Passing a bool to header is invalid. Use header=None for no header or "
+ "header=int or list-like of ints to specify the row(s) making up the "
+ "column names"
+ )
+ with pytest.raises(TypeError, match=msg):
+ self.read_html(spam_data, header=arg)
+
+ def test_converters(self):
+ # GH 13461
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ a
+
+
+
+
+ 0.763
+
+
+ 0.244
+
+
+
"""
+ ),
+ converters={"a": str},
+ )[0]
+
+ expected = DataFrame({"a": ["0.763", "0.244"]})
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_na_values(self):
+ # GH 13461
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ a
+
+
+
+
+ 0.763
+
+
+ 0.244
+
+
+
"""
+ ),
+ na_values=[0.244],
+ )[0]
+
+ expected = DataFrame({"a": [0.763, np.nan]})
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_keep_default_na(self):
+ html_data = """
+
+
+ a
+
+
+
+
+ N/A
+
+
+ NA
+
+
+
"""
+
+ expected_df = DataFrame({"a": ["N/A", "NA"]})
+ html_df = self.read_html(StringIO(html_data), keep_default_na=False)[0]
+ tm.assert_frame_equal(expected_df, html_df)
+
+ expected_df = DataFrame({"a": [np.nan, np.nan]})
+ html_df = self.read_html(StringIO(html_data), keep_default_na=True)[0]
+ tm.assert_frame_equal(expected_df, html_df)
+
+ def test_preserve_empty_rows(self):
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ A
+ B
+
+
+ a
+ b
+
+
+
+
+
+
+ """
+ )
+ )[0]
+
+ expected = DataFrame(data=[["a", "b"], [np.nan, np.nan]], columns=["A", "B"])
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_ignore_empty_rows_when_inferring_header(self):
+ result = self.read_html(
+ StringIO(
+ """
+
+
+
+ A B
+ a b
+
+
+ 1 2
+
+
+ """
+ )
+ )[0]
+
+ columns = MultiIndex(levels=[["A", "B"], ["a", "b"]], codes=[[0, 1], [0, 1]])
+ expected = DataFrame(data=[[1, 2]], columns=columns)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_multiple_header_rows(self):
+ # Issue #13434
+ expected_df = DataFrame(
+ data=[("Hillary", 68, "D"), ("Bernie", 74, "D"), ("Donald", 69, "R")]
+ )
+ expected_df.columns = [
+ ["Unnamed: 0_level_0", "Age", "Party"],
+ ["Name", "Unnamed: 1_level_1", "Unnamed: 2_level_1"],
+ ]
+ html = expected_df.to_html(index=False)
+ html_df = self.read_html(StringIO(html))[0]
+ tm.assert_frame_equal(expected_df, html_df)
+
+ def test_works_on_valid_markup(self, datapath):
+ filename = datapath("io", "data", "html", "valid_markup.html")
+ dfs = self.read_html(filename, index_col=0)
+ assert isinstance(dfs, list)
+ assert isinstance(dfs[0], DataFrame)
+
+ @pytest.mark.slow
+ def test_fallback_success(self, datapath):
+ banklist_data = datapath("io", "data", "html", "banklist.html")
+
+ self.read_html(banklist_data, match=".*Water.*", flavor=["lxml", "html5lib"])
+
+ def test_to_html_timestamp(self):
+ rng = date_range("2000-01-01", periods=10)
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=rng)
+
+ result = df.to_html()
+ assert "2000-01-01" in result
+
+ def test_to_html_borderless(self):
+ df = DataFrame([{"A": 1, "B": 2}])
+ out_border_default = df.to_html()
+ out_border_true = df.to_html(border=True)
+ out_border_explicit_default = df.to_html(border=1)
+ out_border_nondefault = df.to_html(border=2)
+ out_border_zero = df.to_html(border=0)
+
+ out_border_false = df.to_html(border=False)
+
+ assert ' border="1"' in out_border_default
+ assert out_border_true == out_border_default
+ assert out_border_default == out_border_explicit_default
+ assert out_border_default != out_border_nondefault
+ assert ' border="2"' in out_border_nondefault
+ assert ' border="0"' not in out_border_zero
+ assert " border" not in out_border_false
+ assert out_border_zero == out_border_false
+
+ @pytest.mark.parametrize(
+ "displayed_only,exp0,exp1",
+ [
+ (True, DataFrame(["foo"]), None),
+ (False, DataFrame(["foo bar baz qux"]), DataFrame(["foo"])),
+ ],
+ )
+ def test_displayed_only(self, displayed_only, exp0, exp1):
+ # GH 20027
+ data = """
+
+
+
+
+ foo
+ bar
+ baz
+ qux
+
+
+
+
+
+ """
+
+ dfs = self.read_html(StringIO(data), displayed_only=displayed_only)
+ tm.assert_frame_equal(dfs[0], exp0)
+
+ if exp1 is not None:
+ tm.assert_frame_equal(dfs[1], exp1)
+ else:
+ assert len(dfs) == 1 # Should not parse hidden table
+
+ @pytest.mark.parametrize("displayed_only", [True, False])
+ def test_displayed_only_with_many_elements(self, displayed_only):
+ html_table = """
+
+
+ A
+ B
+
+
+ 1
+ 2
+
+
+ 4
+ 5
+
+
+ """
+ result = read_html(StringIO(html_table), displayed_only=displayed_only)[0]
+ expected = DataFrame({"A": [1, 4], "B": [2, 5]})
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.filterwarnings(
+ "ignore:You provided Unicode markup but also provided a value for "
+ "from_encoding.*:UserWarning"
+ )
+ def test_encode(self, html_encoding_file):
+ base_path = os.path.basename(html_encoding_file)
+ root = os.path.splitext(base_path)[0]
+ _, encoding = root.split("_")
+
+ try:
+ with open(html_encoding_file, "rb") as fobj:
+ from_string = self.read_html(
+ fobj.read(), encoding=encoding, index_col=0
+ ).pop()
+
+ with open(html_encoding_file, "rb") as fobj:
+ from_file_like = self.read_html(
+ BytesIO(fobj.read()), encoding=encoding, index_col=0
+ ).pop()
+
+ from_filename = self.read_html(
+ html_encoding_file, encoding=encoding, index_col=0
+ ).pop()
+ tm.assert_frame_equal(from_string, from_file_like)
+ tm.assert_frame_equal(from_string, from_filename)
+ except Exception:
+ # seems utf-16/32 fail on windows
+ if is_platform_windows():
+ if "16" in encoding or "32" in encoding:
+ pytest.skip()
+ raise
+
+ def test_parse_failure_unseekable(self):
+ # Issue #17975
+
+ if self.read_html.keywords.get("flavor") == "lxml":
+ pytest.skip("Not applicable for lxml")
+
+ class UnseekableStringIO(StringIO):
+ def seekable(self):
+ return False
+
+ bad = UnseekableStringIO(
+ """
+ """
+ )
+
+ assert self.read_html(bad)
+
+ with pytest.raises(ValueError, match="passed a non-rewindable file object"):
+ self.read_html(bad)
+
+ def test_parse_failure_rewinds(self):
+ # Issue #17975
+
+ class MockFile:
+ def __init__(self, data) -> None:
+ self.data = data
+ self.at_end = False
+
+ def read(self, size=None):
+ data = "" if self.at_end else self.data
+ self.at_end = True
+ return data
+
+ def seek(self, offset):
+ self.at_end = False
+
+ def seekable(self):
+ return True
+
+ # GH 49036 pylint checks for presence of __next__ for iterators
+ def __next__(self):
+ ...
+
+ def __iter__(self) -> Iterator:
+ # `is_file_like` depends on the presence of
+ # the __iter__ attribute.
+ return self
+
+ good = MockFile("")
+ bad = MockFile("")
+
+ assert self.read_html(good)
+ assert self.read_html(bad)
+
+ @pytest.mark.slow
+ @pytest.mark.single_cpu
+ def test_importcheck_thread_safety(self, datapath):
+ # see gh-16928
+
+ class ErrorThread(threading.Thread):
+ def run(self):
+ try:
+ super().run()
+ except Exception as err:
+ self.err = err
+ else:
+ self.err = None
+
+ filename = datapath("io", "data", "html", "valid_markup.html")
+ helper_thread1 = ErrorThread(target=self.read_html, args=(filename,))
+ helper_thread2 = ErrorThread(target=self.read_html, args=(filename,))
+
+ helper_thread1.start()
+ helper_thread2.start()
+
+ while helper_thread1.is_alive() or helper_thread2.is_alive():
+ pass
+ assert None is helper_thread1.err is helper_thread2.err
+
+ def test_parse_path_object(self, datapath):
+ # GH 37705
+ file_path_string = datapath("io", "data", "html", "spam.html")
+ file_path = Path(file_path_string)
+ df1 = self.read_html(file_path_string)[0]
+ df2 = self.read_html(file_path)[0]
+ tm.assert_frame_equal(df1, df2)
+
+ def test_parse_br_as_space(self):
+ # GH 29528: pd.read_html() convert to space
+ result = self.read_html(
+ StringIO(
+ """
+
+
+ A
+
+
+ word1 word2
+
+
+ """
+ )
+ )[0]
+
+ expected = DataFrame(data=[["word1 word2"]], columns=["A"])
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("arg", ["all", "body", "header", "footer"])
+ def test_extract_links(self, arg):
+ gh_13141_data = """
+
+ """
+
+ gh_13141_expected = {
+ "head_ignore": ["HTTP", "FTP", "Linkless"],
+ "head_extract": [
+ ("HTTP", None),
+ ("FTP", None),
+ ("Linkless", "https://en.wiktionary.org/wiki/linkless"),
+ ],
+ "body_ignore": ["Wikipedia", "SURROUNDING Debian TEXT", "Linkless"],
+ "body_extract": [
+ ("Wikipedia", "https://en.wikipedia.org/"),
+ ("SURROUNDING Debian TEXT", "ftp://ftp.us.debian.org/"),
+ ("Linkless", None),
+ ],
+ "footer_ignore": [
+ "Footer",
+ "Multiple links: Only first captured.",
+ None,
+ ],
+ "footer_extract": [
+ ("Footer", "https://en.wikipedia.org/wiki/Page_footer"),
+ ("Multiple links: Only first captured.", "1"),
+ None,
+ ],
+ }
+
+ data_exp = gh_13141_expected["body_ignore"]
+ foot_exp = gh_13141_expected["footer_ignore"]
+ head_exp = gh_13141_expected["head_ignore"]
+ if arg == "all":
+ data_exp = gh_13141_expected["body_extract"]
+ foot_exp = gh_13141_expected["footer_extract"]
+ head_exp = gh_13141_expected["head_extract"]
+ elif arg == "body":
+ data_exp = gh_13141_expected["body_extract"]
+ elif arg == "footer":
+ foot_exp = gh_13141_expected["footer_extract"]
+ elif arg == "header":
+ head_exp = gh_13141_expected["head_extract"]
+
+ result = self.read_html(StringIO(gh_13141_data), extract_links=arg)[0]
+ expected = DataFrame([data_exp, foot_exp], columns=head_exp)
+ expected = expected.fillna(np.nan)
+ tm.assert_frame_equal(result, expected)
+
+ def test_extract_links_bad(self, spam_data):
+ msg = (
+ "`extract_links` must be one of "
+ '{None, "header", "footer", "body", "all"}, got "incorrect"'
+ )
+ with pytest.raises(ValueError, match=msg):
+ read_html(spam_data, extract_links="incorrect")
+
+ def test_extract_links_all_no_header(self):
+ # GH 48316
+ data = """
+
+ """
+ result = self.read_html(StringIO(data), extract_links="all")[0]
+ expected = DataFrame([[("Google.com", "https://google.com")]])
+ tm.assert_frame_equal(result, expected)
+
+ def test_invalid_dtype_backend(self):
+ msg = (
+ "dtype_backend numpy is invalid, only 'numpy_nullable' and "
+ "'pyarrow' are allowed."
+ )
+ with pytest.raises(ValueError, match=msg):
+ read_html("test", dtype_backend="numpy")
+
+ def test_style_tag(self):
+ # GH 48316
+ data = """
+
+
+
+
+ A
+
+ B
+
+
+ A1
+ B1
+
+
+ A2
+ B2
+
+
+ """
+ result = self.read_html(StringIO(data))[0]
+ expected = DataFrame(data=[["A1", "B1"], ["A2", "B2"]], columns=["A", "B"])
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_orc.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_orc.py
new file mode 100644
index 0000000000000000000000000000000000000000..d90f803f1e60722d69bd7e227ffb9e0339078896
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_orc.py
@@ -0,0 +1,432 @@
+""" test orc compat """
+import datetime
+from decimal import Decimal
+from io import BytesIO
+import os
+import pathlib
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import read_orc
+import pandas._testing as tm
+from pandas.core.arrays import StringArray
+
+pytest.importorskip("pyarrow.orc")
+
+import pyarrow as pa
+
+
+@pytest.fixture
+def dirpath(datapath):
+ return datapath("io", "data", "orc")
+
+
+@pytest.fixture(
+ params=[
+ np.array([1, 20], dtype="uint64"),
+ pd.Series(["a", "b", "a"], dtype="category"),
+ [pd.Interval(left=0, right=2), pd.Interval(left=0, right=5)],
+ [pd.Period("2022-01-03", freq="D"), pd.Period("2022-01-04", freq="D")],
+ ]
+)
+def orc_writer_dtypes_not_supported(request):
+ # Examples of dataframes with dtypes for which conversion to ORC
+ # hasn't been implemented yet, that is, Category, unsigned integers,
+ # interval, period and sparse.
+ return pd.DataFrame({"unimpl": request.param})
+
+
+def test_orc_reader_empty(dirpath):
+ columns = [
+ "boolean1",
+ "byte1",
+ "short1",
+ "int1",
+ "long1",
+ "float1",
+ "double1",
+ "bytes1",
+ "string1",
+ ]
+ dtypes = [
+ "bool",
+ "int8",
+ "int16",
+ "int32",
+ "int64",
+ "float32",
+ "float64",
+ "object",
+ "object",
+ ]
+ expected = pd.DataFrame(index=pd.RangeIndex(0))
+ for colname, dtype in zip(columns, dtypes):
+ expected[colname] = pd.Series(dtype=dtype)
+
+ inputfile = os.path.join(dirpath, "TestOrcFile.emptyFile.orc")
+ got = read_orc(inputfile, columns=columns)
+
+ tm.assert_equal(expected, got)
+
+
+def test_orc_reader_basic(dirpath):
+ data = {
+ "boolean1": np.array([False, True], dtype="bool"),
+ "byte1": np.array([1, 100], dtype="int8"),
+ "short1": np.array([1024, 2048], dtype="int16"),
+ "int1": np.array([65536, 65536], dtype="int32"),
+ "long1": np.array([9223372036854775807, 9223372036854775807], dtype="int64"),
+ "float1": np.array([1.0, 2.0], dtype="float32"),
+ "double1": np.array([-15.0, -5.0], dtype="float64"),
+ "bytes1": np.array([b"\x00\x01\x02\x03\x04", b""], dtype="object"),
+ "string1": np.array(["hi", "bye"], dtype="object"),
+ }
+ expected = pd.DataFrame.from_dict(data)
+
+ inputfile = os.path.join(dirpath, "TestOrcFile.test1.orc")
+ got = read_orc(inputfile, columns=data.keys())
+
+ tm.assert_equal(expected, got)
+
+
+def test_orc_reader_decimal(dirpath):
+ # Only testing the first 10 rows of data
+ data = {
+ "_col0": np.array(
+ [
+ Decimal("-1000.50000"),
+ Decimal("-999.60000"),
+ Decimal("-998.70000"),
+ Decimal("-997.80000"),
+ Decimal("-996.90000"),
+ Decimal("-995.10000"),
+ Decimal("-994.11000"),
+ Decimal("-993.12000"),
+ Decimal("-992.13000"),
+ Decimal("-991.14000"),
+ ],
+ dtype="object",
+ )
+ }
+ expected = pd.DataFrame.from_dict(data)
+
+ inputfile = os.path.join(dirpath, "TestOrcFile.decimal.orc")
+ got = read_orc(inputfile).iloc[:10]
+
+ tm.assert_equal(expected, got)
+
+
+def test_orc_reader_date_low(dirpath):
+ data = {
+ "time": np.array(
+ [
+ "1900-05-05 12:34:56.100000",
+ "1900-05-05 12:34:56.100100",
+ "1900-05-05 12:34:56.100200",
+ "1900-05-05 12:34:56.100300",
+ "1900-05-05 12:34:56.100400",
+ "1900-05-05 12:34:56.100500",
+ "1900-05-05 12:34:56.100600",
+ "1900-05-05 12:34:56.100700",
+ "1900-05-05 12:34:56.100800",
+ "1900-05-05 12:34:56.100900",
+ ],
+ dtype="datetime64[ns]",
+ ),
+ "date": np.array(
+ [
+ datetime.date(1900, 12, 25),
+ datetime.date(1900, 12, 25),
+ datetime.date(1900, 12, 25),
+ datetime.date(1900, 12, 25),
+ datetime.date(1900, 12, 25),
+ datetime.date(1900, 12, 25),
+ datetime.date(1900, 12, 25),
+ datetime.date(1900, 12, 25),
+ datetime.date(1900, 12, 25),
+ datetime.date(1900, 12, 25),
+ ],
+ dtype="object",
+ ),
+ }
+ expected = pd.DataFrame.from_dict(data)
+
+ inputfile = os.path.join(dirpath, "TestOrcFile.testDate1900.orc")
+ got = read_orc(inputfile).iloc[:10]
+
+ tm.assert_equal(expected, got)
+
+
+def test_orc_reader_date_high(dirpath):
+ data = {
+ "time": np.array(
+ [
+ "2038-05-05 12:34:56.100000",
+ "2038-05-05 12:34:56.100100",
+ "2038-05-05 12:34:56.100200",
+ "2038-05-05 12:34:56.100300",
+ "2038-05-05 12:34:56.100400",
+ "2038-05-05 12:34:56.100500",
+ "2038-05-05 12:34:56.100600",
+ "2038-05-05 12:34:56.100700",
+ "2038-05-05 12:34:56.100800",
+ "2038-05-05 12:34:56.100900",
+ ],
+ dtype="datetime64[ns]",
+ ),
+ "date": np.array(
+ [
+ datetime.date(2038, 12, 25),
+ datetime.date(2038, 12, 25),
+ datetime.date(2038, 12, 25),
+ datetime.date(2038, 12, 25),
+ datetime.date(2038, 12, 25),
+ datetime.date(2038, 12, 25),
+ datetime.date(2038, 12, 25),
+ datetime.date(2038, 12, 25),
+ datetime.date(2038, 12, 25),
+ datetime.date(2038, 12, 25),
+ ],
+ dtype="object",
+ ),
+ }
+ expected = pd.DataFrame.from_dict(data)
+
+ inputfile = os.path.join(dirpath, "TestOrcFile.testDate2038.orc")
+ got = read_orc(inputfile).iloc[:10]
+
+ tm.assert_equal(expected, got)
+
+
+def test_orc_reader_snappy_compressed(dirpath):
+ data = {
+ "int1": np.array(
+ [
+ -1160101563,
+ 1181413113,
+ 2065821249,
+ -267157795,
+ 172111193,
+ 1752363137,
+ 1406072123,
+ 1911809390,
+ -1308542224,
+ -467100286,
+ ],
+ dtype="int32",
+ ),
+ "string1": np.array(
+ [
+ "f50dcb8",
+ "382fdaaa",
+ "90758c6",
+ "9e8caf3f",
+ "ee97332b",
+ "d634da1",
+ "2bea4396",
+ "d67d89e8",
+ "ad71007e",
+ "e8c82066",
+ ],
+ dtype="object",
+ ),
+ }
+ expected = pd.DataFrame.from_dict(data)
+
+ inputfile = os.path.join(dirpath, "TestOrcFile.testSnappy.orc")
+ got = read_orc(inputfile).iloc[:10]
+
+ tm.assert_equal(expected, got)
+
+
+def test_orc_roundtrip_file(dirpath):
+ # GH44554
+ # PyArrow gained ORC write support with the current argument order
+ pytest.importorskip("pyarrow")
+
+ data = {
+ "boolean1": np.array([False, True], dtype="bool"),
+ "byte1": np.array([1, 100], dtype="int8"),
+ "short1": np.array([1024, 2048], dtype="int16"),
+ "int1": np.array([65536, 65536], dtype="int32"),
+ "long1": np.array([9223372036854775807, 9223372036854775807], dtype="int64"),
+ "float1": np.array([1.0, 2.0], dtype="float32"),
+ "double1": np.array([-15.0, -5.0], dtype="float64"),
+ "bytes1": np.array([b"\x00\x01\x02\x03\x04", b""], dtype="object"),
+ "string1": np.array(["hi", "bye"], dtype="object"),
+ }
+ expected = pd.DataFrame.from_dict(data)
+
+ with tm.ensure_clean() as path:
+ expected.to_orc(path)
+ got = read_orc(path)
+
+ tm.assert_equal(expected, got)
+
+
+def test_orc_roundtrip_bytesio():
+ # GH44554
+ # PyArrow gained ORC write support with the current argument order
+ pytest.importorskip("pyarrow")
+
+ data = {
+ "boolean1": np.array([False, True], dtype="bool"),
+ "byte1": np.array([1, 100], dtype="int8"),
+ "short1": np.array([1024, 2048], dtype="int16"),
+ "int1": np.array([65536, 65536], dtype="int32"),
+ "long1": np.array([9223372036854775807, 9223372036854775807], dtype="int64"),
+ "float1": np.array([1.0, 2.0], dtype="float32"),
+ "double1": np.array([-15.0, -5.0], dtype="float64"),
+ "bytes1": np.array([b"\x00\x01\x02\x03\x04", b""], dtype="object"),
+ "string1": np.array(["hi", "bye"], dtype="object"),
+ }
+ expected = pd.DataFrame.from_dict(data)
+
+ bytes = expected.to_orc()
+ got = read_orc(BytesIO(bytes))
+
+ tm.assert_equal(expected, got)
+
+
+def test_orc_writer_dtypes_not_supported(orc_writer_dtypes_not_supported):
+ # GH44554
+ # PyArrow gained ORC write support with the current argument order
+ pytest.importorskip("pyarrow")
+
+ msg = "The dtype of one or more columns is not supported yet."
+ with pytest.raises(NotImplementedError, match=msg):
+ orc_writer_dtypes_not_supported.to_orc()
+
+
+def test_orc_dtype_backend_pyarrow():
+ pytest.importorskip("pyarrow")
+ df = pd.DataFrame(
+ {
+ "string": list("abc"),
+ "string_with_nan": ["a", np.nan, "c"],
+ "string_with_none": ["a", None, "c"],
+ "bytes": [b"foo", b"bar", None],
+ "int": list(range(1, 4)),
+ "float": np.arange(4.0, 7.0, dtype="float64"),
+ "float_with_nan": [2.0, np.nan, 3.0],
+ "bool": [True, False, True],
+ "bool_with_na": [True, False, None],
+ "datetime": pd.date_range("20130101", periods=3),
+ "datetime_with_nat": [
+ pd.Timestamp("20130101"),
+ pd.NaT,
+ pd.Timestamp("20130103"),
+ ],
+ }
+ )
+
+ bytes_data = df.copy().to_orc()
+ result = read_orc(BytesIO(bytes_data), dtype_backend="pyarrow")
+
+ expected = pd.DataFrame(
+ {
+ col: pd.arrays.ArrowExtensionArray(pa.array(df[col], from_pandas=True))
+ for col in df.columns
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_orc_dtype_backend_numpy_nullable():
+ # GH#50503
+ pytest.importorskip("pyarrow")
+ df = pd.DataFrame(
+ {
+ "string": list("abc"),
+ "string_with_nan": ["a", np.nan, "c"],
+ "string_with_none": ["a", None, "c"],
+ "int": list(range(1, 4)),
+ "int_with_nan": pd.Series([1, pd.NA, 3], dtype="Int64"),
+ "na_only": pd.Series([pd.NA, pd.NA, pd.NA], dtype="Int64"),
+ "float": np.arange(4.0, 7.0, dtype="float64"),
+ "float_with_nan": [2.0, np.nan, 3.0],
+ "bool": [True, False, True],
+ "bool_with_na": [True, False, None],
+ }
+ )
+
+ bytes_data = df.copy().to_orc()
+ result = read_orc(BytesIO(bytes_data), dtype_backend="numpy_nullable")
+
+ expected = pd.DataFrame(
+ {
+ "string": StringArray(np.array(["a", "b", "c"], dtype=np.object_)),
+ "string_with_nan": StringArray(
+ np.array(["a", pd.NA, "c"], dtype=np.object_)
+ ),
+ "string_with_none": StringArray(
+ np.array(["a", pd.NA, "c"], dtype=np.object_)
+ ),
+ "int": pd.Series([1, 2, 3], dtype="Int64"),
+ "int_with_nan": pd.Series([1, pd.NA, 3], dtype="Int64"),
+ "na_only": pd.Series([pd.NA, pd.NA, pd.NA], dtype="Int64"),
+ "float": pd.Series([4.0, 5.0, 6.0], dtype="Float64"),
+ "float_with_nan": pd.Series([2.0, pd.NA, 3.0], dtype="Float64"),
+ "bool": pd.Series([True, False, True], dtype="boolean"),
+ "bool_with_na": pd.Series([True, False, pd.NA], dtype="boolean"),
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_orc_uri_path():
+ expected = pd.DataFrame({"int": list(range(1, 4))})
+ with tm.ensure_clean("tmp.orc") as path:
+ expected.to_orc(path)
+ uri = pathlib.Path(path).as_uri()
+ result = read_orc(uri)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "index",
+ [
+ pd.RangeIndex(start=2, stop=5, step=1),
+ pd.RangeIndex(start=0, stop=3, step=1, name="non-default"),
+ pd.Index([1, 2, 3]),
+ ],
+)
+def test_to_orc_non_default_index(index):
+ df = pd.DataFrame({"a": [1, 2, 3]}, index=index)
+ msg = (
+ "orc does not support serializing a non-default index|"
+ "orc does not serialize index meta-data"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.to_orc()
+
+
+def test_invalid_dtype_backend():
+ msg = (
+ "dtype_backend numpy is invalid, only 'numpy_nullable' and "
+ "'pyarrow' are allowed."
+ )
+ df = pd.DataFrame({"int": list(range(1, 4))})
+ with tm.ensure_clean("tmp.orc") as path:
+ df.to_orc(path)
+ with pytest.raises(ValueError, match=msg):
+ read_orc(path, dtype_backend="numpy")
+
+
+def test_string_inference(tmp_path):
+ # GH#54431
+ path = tmp_path / "test_string_inference.p"
+ df = pd.DataFrame(data={"a": ["x", "y"]})
+ df.to_orc(path)
+ with pd.option_context("future.infer_string", True):
+ result = read_orc(path)
+ expected = pd.DataFrame(
+ data={"a": ["x", "y"]},
+ dtype="string[pyarrow_numpy]",
+ columns=pd.Index(["a"], dtype="string[pyarrow_numpy]"),
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_parquet.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_parquet.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d68f12270b55e5c3b6dc5f5cc770e4356f9d66e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_parquet.py
@@ -0,0 +1,1427 @@
+""" test parquet compat """
+import datetime
+from decimal import Decimal
+from io import BytesIO
+import os
+import pathlib
+
+import numpy as np
+import pytest
+
+from pandas._config import (
+ get_option,
+ using_copy_on_write,
+)
+
+from pandas.compat import is_platform_windows
+from pandas.compat.pyarrow import (
+ pa_version_under7p0,
+ pa_version_under8p0,
+ pa_version_under11p0,
+ pa_version_under13p0,
+)
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.util.version import Version
+
+from pandas.io.parquet import (
+ FastParquetImpl,
+ PyArrowImpl,
+ get_engine,
+ read_parquet,
+ to_parquet,
+)
+
+try:
+ import pyarrow
+
+ _HAVE_PYARROW = True
+except ImportError:
+ _HAVE_PYARROW = False
+
+try:
+ import fastparquet
+
+ _HAVE_FASTPARQUET = True
+except ImportError:
+ _HAVE_FASTPARQUET = False
+
+
+# TODO(ArrayManager) fastparquet relies on BlockManager internals
+
+pytestmark = pytest.mark.filterwarnings(
+ "ignore:DataFrame._data is deprecated:FutureWarning"
+)
+
+
+# setup engines & skips
+@pytest.fixture(
+ params=[
+ pytest.param(
+ "fastparquet",
+ marks=pytest.mark.skipif(
+ not _HAVE_FASTPARQUET or get_option("mode.data_manager") == "array",
+ reason="fastparquet is not installed or ArrayManager is used",
+ ),
+ ),
+ pytest.param(
+ "pyarrow",
+ marks=pytest.mark.skipif(
+ not _HAVE_PYARROW, reason="pyarrow is not installed"
+ ),
+ ),
+ ]
+)
+def engine(request):
+ return request.param
+
+
+@pytest.fixture
+def pa():
+ if not _HAVE_PYARROW:
+ pytest.skip("pyarrow is not installed")
+ return "pyarrow"
+
+
+@pytest.fixture
+def fp():
+ if not _HAVE_FASTPARQUET:
+ pytest.skip("fastparquet is not installed")
+ elif get_option("mode.data_manager") == "array":
+ pytest.skip("ArrayManager is not supported with fastparquet")
+ return "fastparquet"
+
+
+@pytest.fixture
+def df_compat():
+ return pd.DataFrame({"A": [1, 2, 3], "B": "foo"})
+
+
+@pytest.fixture
+def df_cross_compat():
+ df = pd.DataFrame(
+ {
+ "a": list("abc"),
+ "b": list(range(1, 4)),
+ # 'c': np.arange(3, 6).astype('u1'),
+ "d": np.arange(4.0, 7.0, dtype="float64"),
+ "e": [True, False, True],
+ "f": pd.date_range("20130101", periods=3),
+ # 'g': pd.date_range('20130101', periods=3,
+ # tz='US/Eastern'),
+ # 'h': pd.date_range('20130101', periods=3, freq='ns')
+ }
+ )
+ return df
+
+
+@pytest.fixture
+def df_full():
+ return pd.DataFrame(
+ {
+ "string": list("abc"),
+ "string_with_nan": ["a", np.nan, "c"],
+ "string_with_none": ["a", None, "c"],
+ "bytes": [b"foo", b"bar", b"baz"],
+ "unicode": ["foo", "bar", "baz"],
+ "int": list(range(1, 4)),
+ "uint": np.arange(3, 6).astype("u1"),
+ "float": np.arange(4.0, 7.0, dtype="float64"),
+ "float_with_nan": [2.0, np.nan, 3.0],
+ "bool": [True, False, True],
+ "datetime": pd.date_range("20130101", periods=3),
+ "datetime_with_nat": [
+ pd.Timestamp("20130101"),
+ pd.NaT,
+ pd.Timestamp("20130103"),
+ ],
+ }
+ )
+
+
+@pytest.fixture(
+ params=[
+ datetime.datetime.now(datetime.timezone.utc),
+ datetime.datetime.now(datetime.timezone.min),
+ datetime.datetime.now(datetime.timezone.max),
+ datetime.datetime.strptime("2019-01-04T16:41:24+0200", "%Y-%m-%dT%H:%M:%S%z"),
+ datetime.datetime.strptime("2019-01-04T16:41:24+0215", "%Y-%m-%dT%H:%M:%S%z"),
+ datetime.datetime.strptime("2019-01-04T16:41:24-0200", "%Y-%m-%dT%H:%M:%S%z"),
+ datetime.datetime.strptime("2019-01-04T16:41:24-0215", "%Y-%m-%dT%H:%M:%S%z"),
+ ]
+)
+def timezone_aware_date_list(request):
+ return request.param
+
+
+def check_round_trip(
+ df,
+ engine=None,
+ path=None,
+ write_kwargs=None,
+ read_kwargs=None,
+ expected=None,
+ check_names=True,
+ check_like=False,
+ check_dtype=True,
+ repeat=2,
+):
+ """Verify parquet serializer and deserializer produce the same results.
+
+ Performs a pandas to disk and disk to pandas round trip,
+ then compares the 2 resulting DataFrames to verify equality.
+
+ Parameters
+ ----------
+ df: Dataframe
+ engine: str, optional
+ 'pyarrow' or 'fastparquet'
+ path: str, optional
+ write_kwargs: dict of str:str, optional
+ read_kwargs: dict of str:str, optional
+ expected: DataFrame, optional
+ Expected deserialization result, otherwise will be equal to `df`
+ check_names: list of str, optional
+ Closed set of column names to be compared
+ check_like: bool, optional
+ If True, ignore the order of index & columns.
+ repeat: int, optional
+ How many times to repeat the test
+ """
+ write_kwargs = write_kwargs or {"compression": None}
+ read_kwargs = read_kwargs or {}
+
+ if expected is None:
+ expected = df
+
+ if engine:
+ write_kwargs["engine"] = engine
+ read_kwargs["engine"] = engine
+
+ def compare(repeat):
+ for _ in range(repeat):
+ df.to_parquet(path, **write_kwargs)
+ actual = read_parquet(path, **read_kwargs)
+
+ if "string_with_nan" in expected:
+ expected.loc[1, "string_with_nan"] = None
+ tm.assert_frame_equal(
+ expected,
+ actual,
+ check_names=check_names,
+ check_like=check_like,
+ check_dtype=check_dtype,
+ )
+
+ if path is None:
+ with tm.ensure_clean() as path:
+ compare(repeat)
+ else:
+ compare(repeat)
+
+
+def check_partition_names(path, expected):
+ """Check partitions of a parquet file are as expected.
+
+ Parameters
+ ----------
+ path: str
+ Path of the dataset.
+ expected: iterable of str
+ Expected partition names.
+ """
+ if pa_version_under7p0:
+ import pyarrow.parquet as pq
+
+ dataset = pq.ParquetDataset(path, validate_schema=False)
+ assert len(dataset.partitions.partition_names) == len(expected)
+ assert dataset.partitions.partition_names == set(expected)
+ else:
+ import pyarrow.dataset as ds
+
+ dataset = ds.dataset(path, partitioning="hive")
+ assert dataset.partitioning.schema.names == expected
+
+
+def test_invalid_engine(df_compat):
+ msg = "engine must be one of 'pyarrow', 'fastparquet'"
+ with pytest.raises(ValueError, match=msg):
+ check_round_trip(df_compat, "foo", "bar")
+
+
+def test_options_py(df_compat, pa):
+ # use the set option
+
+ with pd.option_context("io.parquet.engine", "pyarrow"):
+ check_round_trip(df_compat)
+
+
+def test_options_fp(df_compat, fp):
+ # use the set option
+
+ with pd.option_context("io.parquet.engine", "fastparquet"):
+ check_round_trip(df_compat)
+
+
+def test_options_auto(df_compat, fp, pa):
+ # use the set option
+
+ with pd.option_context("io.parquet.engine", "auto"):
+ check_round_trip(df_compat)
+
+
+def test_options_get_engine(fp, pa):
+ assert isinstance(get_engine("pyarrow"), PyArrowImpl)
+ assert isinstance(get_engine("fastparquet"), FastParquetImpl)
+
+ with pd.option_context("io.parquet.engine", "pyarrow"):
+ assert isinstance(get_engine("auto"), PyArrowImpl)
+ assert isinstance(get_engine("pyarrow"), PyArrowImpl)
+ assert isinstance(get_engine("fastparquet"), FastParquetImpl)
+
+ with pd.option_context("io.parquet.engine", "fastparquet"):
+ assert isinstance(get_engine("auto"), FastParquetImpl)
+ assert isinstance(get_engine("pyarrow"), PyArrowImpl)
+ assert isinstance(get_engine("fastparquet"), FastParquetImpl)
+
+ with pd.option_context("io.parquet.engine", "auto"):
+ assert isinstance(get_engine("auto"), PyArrowImpl)
+ assert isinstance(get_engine("pyarrow"), PyArrowImpl)
+ assert isinstance(get_engine("fastparquet"), FastParquetImpl)
+
+
+def test_get_engine_auto_error_message():
+ # Expect different error messages from get_engine(engine="auto")
+ # if engines aren't installed vs. are installed but bad version
+ from pandas.compat._optional import VERSIONS
+
+ # Do we have engines installed, but a bad version of them?
+ pa_min_ver = VERSIONS.get("pyarrow")
+ fp_min_ver = VERSIONS.get("fastparquet")
+ have_pa_bad_version = (
+ False
+ if not _HAVE_PYARROW
+ else Version(pyarrow.__version__) < Version(pa_min_ver)
+ )
+ have_fp_bad_version = (
+ False
+ if not _HAVE_FASTPARQUET
+ else Version(fastparquet.__version__) < Version(fp_min_ver)
+ )
+ # Do we have usable engines installed?
+ have_usable_pa = _HAVE_PYARROW and not have_pa_bad_version
+ have_usable_fp = _HAVE_FASTPARQUET and not have_fp_bad_version
+
+ if not have_usable_pa and not have_usable_fp:
+ # No usable engines found.
+ if have_pa_bad_version:
+ match = f"Pandas requires version .{pa_min_ver}. or newer of .pyarrow."
+ with pytest.raises(ImportError, match=match):
+ get_engine("auto")
+ else:
+ match = "Missing optional dependency .pyarrow."
+ with pytest.raises(ImportError, match=match):
+ get_engine("auto")
+
+ if have_fp_bad_version:
+ match = f"Pandas requires version .{fp_min_ver}. or newer of .fastparquet."
+ with pytest.raises(ImportError, match=match):
+ get_engine("auto")
+ else:
+ match = "Missing optional dependency .fastparquet."
+ with pytest.raises(ImportError, match=match):
+ get_engine("auto")
+
+
+def test_cross_engine_pa_fp(df_cross_compat, pa, fp):
+ # cross-compat with differing reading/writing engines
+
+ df = df_cross_compat
+ with tm.ensure_clean() as path:
+ df.to_parquet(path, engine=pa, compression=None)
+
+ result = read_parquet(path, engine=fp)
+ tm.assert_frame_equal(result, df)
+
+ result = read_parquet(path, engine=fp, columns=["a", "d"])
+ tm.assert_frame_equal(result, df[["a", "d"]])
+
+
+def test_cross_engine_fp_pa(df_cross_compat, pa, fp):
+ # cross-compat with differing reading/writing engines
+ df = df_cross_compat
+ with tm.ensure_clean() as path:
+ df.to_parquet(path, engine=fp, compression=None)
+
+ result = read_parquet(path, engine=pa)
+ tm.assert_frame_equal(result, df)
+
+ result = read_parquet(path, engine=pa, columns=["a", "d"])
+ tm.assert_frame_equal(result, df[["a", "d"]])
+
+
+class Base:
+ def check_error_on_write(self, df, engine, exc, err_msg):
+ # check that we are raising the exception on writing
+ with tm.ensure_clean() as path:
+ with pytest.raises(exc, match=err_msg):
+ to_parquet(df, path, engine, compression=None)
+
+ def check_external_error_on_write(self, df, engine, exc):
+ # check that an external library is raising the exception on writing
+ with tm.ensure_clean() as path:
+ with tm.external_error_raised(exc):
+ to_parquet(df, path, engine, compression=None)
+
+ @pytest.mark.network
+ @pytest.mark.single_cpu
+ def test_parquet_read_from_url(self, httpserver, datapath, df_compat, engine):
+ if engine != "auto":
+ pytest.importorskip(engine)
+ with open(datapath("io", "data", "parquet", "simple.parquet"), mode="rb") as f:
+ httpserver.serve_content(content=f.read())
+ df = read_parquet(httpserver.url)
+ tm.assert_frame_equal(df, df_compat)
+
+
+class TestBasic(Base):
+ def test_error(self, engine):
+ for obj in [
+ pd.Series([1, 2, 3]),
+ 1,
+ "foo",
+ pd.Timestamp("20130101"),
+ np.array([1, 2, 3]),
+ ]:
+ msg = "to_parquet only supports IO with DataFrames"
+ self.check_error_on_write(obj, engine, ValueError, msg)
+
+ def test_columns_dtypes(self, engine):
+ df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))})
+
+ # unicode
+ df.columns = ["foo", "bar"]
+ check_round_trip(df, engine)
+
+ @pytest.mark.parametrize("compression", [None, "gzip", "snappy", "brotli"])
+ def test_compression(self, engine, compression):
+ df = pd.DataFrame({"A": [1, 2, 3]})
+ check_round_trip(df, engine, write_kwargs={"compression": compression})
+
+ def test_read_columns(self, engine):
+ # GH18154
+ df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))})
+
+ expected = pd.DataFrame({"string": list("abc")})
+ check_round_trip(
+ df, engine, expected=expected, read_kwargs={"columns": ["string"]}
+ )
+
+ def test_read_filters(self, engine, tmp_path):
+ df = pd.DataFrame(
+ {
+ "int": list(range(4)),
+ "part": list("aabb"),
+ }
+ )
+
+ expected = pd.DataFrame({"int": [0, 1]})
+ check_round_trip(
+ df,
+ engine,
+ path=tmp_path,
+ expected=expected,
+ write_kwargs={"partition_cols": ["part"]},
+ read_kwargs={"filters": [("part", "==", "a")], "columns": ["int"]},
+ repeat=1,
+ )
+
+ def test_write_index(self, engine, using_copy_on_write, request):
+ check_names = engine != "fastparquet"
+ if using_copy_on_write and engine == "fastparquet":
+ request.node.add_marker(
+ pytest.mark.xfail(reason="fastparquet write into index")
+ )
+
+ df = pd.DataFrame({"A": [1, 2, 3]})
+ check_round_trip(df, engine)
+
+ indexes = [
+ [2, 3, 4],
+ pd.date_range("20130101", periods=3),
+ list("abc"),
+ [1, 3, 4],
+ ]
+ # non-default index
+ for index in indexes:
+ df.index = index
+ if isinstance(index, pd.DatetimeIndex):
+ df.index = df.index._with_freq(None) # freq doesn't round-trip
+ check_round_trip(df, engine, check_names=check_names)
+
+ # index with meta-data
+ df.index = [0, 1, 2]
+ df.index.name = "foo"
+ check_round_trip(df, engine)
+
+ def test_write_multiindex(self, pa):
+ # Not supported in fastparquet as of 0.1.3 or older pyarrow version
+ engine = pa
+
+ df = pd.DataFrame({"A": [1, 2, 3]})
+ index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1)])
+ df.index = index
+ check_round_trip(df, engine)
+
+ def test_multiindex_with_columns(self, pa):
+ engine = pa
+ dates = pd.date_range("01-Jan-2018", "01-Dec-2018", freq="MS")
+ df = pd.DataFrame(
+ np.random.default_rng(2).standard_normal((2 * len(dates), 3)),
+ columns=list("ABC"),
+ )
+ index1 = pd.MultiIndex.from_product(
+ [["Level1", "Level2"], dates], names=["level", "date"]
+ )
+ index2 = index1.copy(names=None)
+ for index in [index1, index2]:
+ df.index = index
+
+ check_round_trip(df, engine)
+ check_round_trip(
+ df, engine, read_kwargs={"columns": ["A", "B"]}, expected=df[["A", "B"]]
+ )
+
+ def test_write_ignoring_index(self, engine):
+ # ENH 20768
+ # Ensure index=False omits the index from the written Parquet file.
+ df = pd.DataFrame({"a": [1, 2, 3], "b": ["q", "r", "s"]})
+
+ write_kwargs = {"compression": None, "index": False}
+
+ # Because we're dropping the index, we expect the loaded dataframe to
+ # have the default integer index.
+ expected = df.reset_index(drop=True)
+
+ check_round_trip(df, engine, write_kwargs=write_kwargs, expected=expected)
+
+ # Ignore custom index
+ df = pd.DataFrame(
+ {"a": [1, 2, 3], "b": ["q", "r", "s"]}, index=["zyx", "wvu", "tsr"]
+ )
+
+ check_round_trip(df, engine, write_kwargs=write_kwargs, expected=expected)
+
+ # Ignore multi-indexes as well.
+ arrays = [
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
+ ["one", "two", "one", "two", "one", "two", "one", "two"],
+ ]
+ df = pd.DataFrame(
+ {"one": list(range(8)), "two": [-i for i in range(8)]}, index=arrays
+ )
+
+ expected = df.reset_index(drop=True)
+ check_round_trip(df, engine, write_kwargs=write_kwargs, expected=expected)
+
+ def test_write_column_multiindex(self, engine):
+ # Not able to write column multi-indexes with non-string column names.
+ mi_columns = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1)])
+ df = pd.DataFrame(
+ np.random.default_rng(2).standard_normal((4, 3)), columns=mi_columns
+ )
+
+ if engine == "fastparquet":
+ self.check_error_on_write(
+ df, engine, TypeError, "Column name must be a string"
+ )
+ elif engine == "pyarrow":
+ check_round_trip(df, engine)
+
+ def test_write_column_multiindex_nonstring(self, engine):
+ # GH #34777
+
+ # Not able to write column multi-indexes with non-string column names
+ arrays = [
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
+ [1, 2, 1, 2, 1, 2, 1, 2],
+ ]
+ df = pd.DataFrame(
+ np.random.default_rng(2).standard_normal((8, 8)), columns=arrays
+ )
+ df.columns.names = ["Level1", "Level2"]
+ if engine == "fastparquet":
+ self.check_error_on_write(df, engine, ValueError, "Column name")
+ elif engine == "pyarrow":
+ check_round_trip(df, engine)
+
+ def test_write_column_multiindex_string(self, pa):
+ # GH #34777
+ # Not supported in fastparquet as of 0.1.3
+ engine = pa
+
+ # Write column multi-indexes with string column names
+ arrays = [
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
+ ["one", "two", "one", "two", "one", "two", "one", "two"],
+ ]
+ df = pd.DataFrame(
+ np.random.default_rng(2).standard_normal((8, 8)), columns=arrays
+ )
+ df.columns.names = ["ColLevel1", "ColLevel2"]
+
+ check_round_trip(df, engine)
+
+ def test_write_column_index_string(self, pa):
+ # GH #34777
+ # Not supported in fastparquet as of 0.1.3
+ engine = pa
+
+ # Write column indexes with string column names
+ arrays = ["bar", "baz", "foo", "qux"]
+ df = pd.DataFrame(
+ np.random.default_rng(2).standard_normal((8, 4)), columns=arrays
+ )
+ df.columns.name = "StringCol"
+
+ check_round_trip(df, engine)
+
+ def test_write_column_index_nonstring(self, engine):
+ # GH #34777
+
+ # Write column indexes with string column names
+ arrays = [1, 2, 3, 4]
+ df = pd.DataFrame(
+ np.random.default_rng(2).standard_normal((8, 4)), columns=arrays
+ )
+ df.columns.name = "NonStringCol"
+ if engine == "fastparquet":
+ self.check_error_on_write(
+ df, engine, TypeError, "Column name must be a string"
+ )
+ else:
+ check_round_trip(df, engine)
+
+ @pytest.mark.skipif(pa_version_under7p0, reason="minimum pyarrow not installed")
+ def test_dtype_backend(self, engine, request):
+ import pyarrow.parquet as pq
+
+ if engine == "fastparquet":
+ # We are manually disabling fastparquet's
+ # nullable dtype support pending discussion
+ mark = pytest.mark.xfail(
+ reason="Fastparquet nullable dtype support is disabled"
+ )
+ request.node.add_marker(mark)
+
+ table = pyarrow.table(
+ {
+ "a": pyarrow.array([1, 2, 3, None], "int64"),
+ "b": pyarrow.array([1, 2, 3, None], "uint8"),
+ "c": pyarrow.array(["a", "b", "c", None]),
+ "d": pyarrow.array([True, False, True, None]),
+ # Test that nullable dtypes used even in absence of nulls
+ "e": pyarrow.array([1, 2, 3, 4], "int64"),
+ # GH 45694
+ "f": pyarrow.array([1.0, 2.0, 3.0, None], "float32"),
+ "g": pyarrow.array([1.0, 2.0, 3.0, None], "float64"),
+ }
+ )
+ with tm.ensure_clean() as path:
+ # write manually with pyarrow to write integers
+ pq.write_table(table, path)
+ result1 = read_parquet(path, engine=engine)
+ result2 = read_parquet(path, engine=engine, dtype_backend="numpy_nullable")
+
+ assert result1["a"].dtype == np.dtype("float64")
+ expected = pd.DataFrame(
+ {
+ "a": pd.array([1, 2, 3, None], dtype="Int64"),
+ "b": pd.array([1, 2, 3, None], dtype="UInt8"),
+ "c": pd.array(["a", "b", "c", None], dtype="string"),
+ "d": pd.array([True, False, True, None], dtype="boolean"),
+ "e": pd.array([1, 2, 3, 4], dtype="Int64"),
+ "f": pd.array([1.0, 2.0, 3.0, None], dtype="Float32"),
+ "g": pd.array([1.0, 2.0, 3.0, None], dtype="Float64"),
+ }
+ )
+ if engine == "fastparquet":
+ # Fastparquet doesn't support string columns yet
+ # Only int and boolean
+ result2 = result2.drop("c", axis=1)
+ expected = expected.drop("c", axis=1)
+ tm.assert_frame_equal(result2, expected)
+
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "Int64",
+ "UInt8",
+ "boolean",
+ "object",
+ "datetime64[ns, UTC]",
+ "float",
+ "period[D]",
+ "Float64",
+ "string",
+ ],
+ )
+ def test_read_empty_array(self, pa, dtype):
+ # GH #41241
+ df = pd.DataFrame(
+ {
+ "value": pd.array([], dtype=dtype),
+ }
+ )
+ # GH 45694
+ expected = None
+ if dtype == "float":
+ expected = pd.DataFrame(
+ {
+ "value": pd.array([], dtype="Float64"),
+ }
+ )
+ check_round_trip(
+ df, pa, read_kwargs={"dtype_backend": "numpy_nullable"}, expected=expected
+ )
+
+
+class TestParquetPyArrow(Base):
+ def test_basic(self, pa, df_full):
+ df = df_full
+
+ # additional supported types for pyarrow
+ dti = pd.date_range("20130101", periods=3, tz="Europe/Brussels")
+ dti = dti._with_freq(None) # freq doesn't round-trip
+ df["datetime_tz"] = dti
+ df["bool_with_none"] = [True, None, True]
+
+ check_round_trip(df, pa)
+
+ def test_basic_subset_columns(self, pa, df_full):
+ # GH18628
+
+ df = df_full
+ # additional supported types for pyarrow
+ df["datetime_tz"] = pd.date_range("20130101", periods=3, tz="Europe/Brussels")
+
+ check_round_trip(
+ df,
+ pa,
+ expected=df[["string", "int"]],
+ read_kwargs={"columns": ["string", "int"]},
+ )
+
+ def test_to_bytes_without_path_or_buf_provided(self, pa, df_full):
+ # GH 37105
+ msg = "Mismatched null-like values nan and None found"
+ warn = None
+ if using_copy_on_write():
+ warn = FutureWarning
+
+ buf_bytes = df_full.to_parquet(engine=pa)
+ assert isinstance(buf_bytes, bytes)
+
+ buf_stream = BytesIO(buf_bytes)
+ res = read_parquet(buf_stream)
+
+ expected = df_full.copy(deep=False)
+ expected.loc[1, "string_with_nan"] = None
+ with tm.assert_produces_warning(warn, match=msg):
+ tm.assert_frame_equal(df_full, res)
+
+ def test_duplicate_columns(self, pa):
+ # not currently able to handle duplicate columns
+ df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy()
+ self.check_error_on_write(df, pa, ValueError, "Duplicate column names found")
+
+ def test_timedelta(self, pa):
+ df = pd.DataFrame({"a": pd.timedelta_range("1 day", periods=3)})
+ if pa_version_under8p0:
+ self.check_external_error_on_write(df, pa, NotImplementedError)
+ else:
+ check_round_trip(df, pa)
+
+ def test_unsupported(self, pa):
+ # mixed python objects
+ df = pd.DataFrame({"a": ["a", 1, 2.0]})
+ # pyarrow 0.11 raises ArrowTypeError
+ # older pyarrows raise ArrowInvalid
+ self.check_external_error_on_write(df, pa, pyarrow.ArrowException)
+
+ def test_unsupported_float16(self, pa):
+ # #44847, #44914
+ # Not able to write float 16 column using pyarrow.
+ data = np.arange(2, 10, dtype=np.float16)
+ df = pd.DataFrame(data=data, columns=["fp16"])
+ self.check_external_error_on_write(df, pa, pyarrow.ArrowException)
+
+ @pytest.mark.xfail(
+ is_platform_windows(),
+ reason=(
+ "PyArrow does not cleanup of partial files dumps when unsupported "
+ "dtypes are passed to_parquet function in windows"
+ ),
+ )
+ @pytest.mark.parametrize("path_type", [str, pathlib.Path])
+ def test_unsupported_float16_cleanup(self, pa, path_type):
+ # #44847, #44914
+ # Not able to write float 16 column using pyarrow.
+ # Tests cleanup by pyarrow in case of an error
+ data = np.arange(2, 10, dtype=np.float16)
+ df = pd.DataFrame(data=data, columns=["fp16"])
+
+ with tm.ensure_clean() as path_str:
+ path = path_type(path_str)
+ with tm.external_error_raised(pyarrow.ArrowException):
+ df.to_parquet(path=path, engine=pa)
+ assert not os.path.isfile(path)
+
+ def test_categorical(self, pa):
+ # supported in >= 0.7.0
+ df = pd.DataFrame()
+ df["a"] = pd.Categorical(list("abcdef"))
+
+ # test for null, out-of-order values, and unobserved category
+ df["b"] = pd.Categorical(
+ ["bar", "foo", "foo", "bar", None, "bar"],
+ dtype=pd.CategoricalDtype(["foo", "bar", "baz"]),
+ )
+
+ # test for ordered flag
+ df["c"] = pd.Categorical(
+ ["a", "b", "c", "a", "c", "b"], categories=["b", "c", "d"], ordered=True
+ )
+
+ check_round_trip(df, pa)
+
+ @pytest.mark.single_cpu
+ def test_s3_roundtrip_explicit_fs(self, df_compat, s3_public_bucket, pa, s3so):
+ s3fs = pytest.importorskip("s3fs")
+ s3 = s3fs.S3FileSystem(**s3so)
+ kw = {"filesystem": s3}
+ check_round_trip(
+ df_compat,
+ pa,
+ path=f"{s3_public_bucket.name}/pyarrow.parquet",
+ read_kwargs=kw,
+ write_kwargs=kw,
+ )
+
+ @pytest.mark.single_cpu
+ def test_s3_roundtrip(self, df_compat, s3_public_bucket, pa, s3so):
+ # GH #19134
+ s3so = {"storage_options": s3so}
+ check_round_trip(
+ df_compat,
+ pa,
+ path=f"s3://{s3_public_bucket.name}/pyarrow.parquet",
+ read_kwargs=s3so,
+ write_kwargs=s3so,
+ )
+
+ @pytest.mark.single_cpu
+ @pytest.mark.parametrize(
+ "partition_col",
+ [
+ ["A"],
+ [],
+ ],
+ )
+ def test_s3_roundtrip_for_dir(
+ self, df_compat, s3_public_bucket, pa, partition_col, s3so
+ ):
+ pytest.importorskip("s3fs")
+ # GH #26388
+ expected_df = df_compat.copy()
+
+ # GH #35791
+ if partition_col:
+ expected_df = expected_df.astype(dict.fromkeys(partition_col, np.int32))
+ partition_col_type = "category"
+
+ expected_df[partition_col] = expected_df[partition_col].astype(
+ partition_col_type
+ )
+
+ check_round_trip(
+ df_compat,
+ pa,
+ expected=expected_df,
+ path=f"s3://{s3_public_bucket.name}/parquet_dir",
+ read_kwargs={"storage_options": s3so},
+ write_kwargs={
+ "partition_cols": partition_col,
+ "compression": None,
+ "storage_options": s3so,
+ },
+ check_like=True,
+ repeat=1,
+ )
+
+ def test_read_file_like_obj_support(self, df_compat):
+ pytest.importorskip("pyarrow")
+ buffer = BytesIO()
+ df_compat.to_parquet(buffer)
+ df_from_buf = read_parquet(buffer)
+ tm.assert_frame_equal(df_compat, df_from_buf)
+
+ def test_expand_user(self, df_compat, monkeypatch):
+ pytest.importorskip("pyarrow")
+ monkeypatch.setenv("HOME", "TestingUser")
+ monkeypatch.setenv("USERPROFILE", "TestingUser")
+ with pytest.raises(OSError, match=r".*TestingUser.*"):
+ read_parquet("~/file.parquet")
+ with pytest.raises(OSError, match=r".*TestingUser.*"):
+ df_compat.to_parquet("~/file.parquet")
+
+ def test_partition_cols_supported(self, tmp_path, pa, df_full):
+ # GH #23283
+ partition_cols = ["bool", "int"]
+ df = df_full
+ df.to_parquet(tmp_path, partition_cols=partition_cols, compression=None)
+ check_partition_names(tmp_path, partition_cols)
+ assert read_parquet(tmp_path).shape == df.shape
+
+ def test_partition_cols_string(self, tmp_path, pa, df_full):
+ # GH #27117
+ partition_cols = "bool"
+ partition_cols_list = [partition_cols]
+ df = df_full
+ df.to_parquet(tmp_path, partition_cols=partition_cols, compression=None)
+ check_partition_names(tmp_path, partition_cols_list)
+ assert read_parquet(tmp_path).shape == df.shape
+
+ @pytest.mark.parametrize(
+ "path_type", [str, lambda x: x], ids=["string", "pathlib.Path"]
+ )
+ def test_partition_cols_pathlib(self, tmp_path, pa, df_compat, path_type):
+ # GH 35902
+
+ partition_cols = "B"
+ partition_cols_list = [partition_cols]
+ df = df_compat
+
+ path = path_type(tmp_path)
+ df.to_parquet(path, partition_cols=partition_cols_list)
+ assert read_parquet(path).shape == df.shape
+
+ def test_empty_dataframe(self, pa):
+ # GH #27339
+ df = pd.DataFrame(index=[], columns=[])
+ check_round_trip(df, pa)
+
+ def test_write_with_schema(self, pa):
+ import pyarrow
+
+ df = pd.DataFrame({"x": [0, 1]})
+ schema = pyarrow.schema([pyarrow.field("x", type=pyarrow.bool_())])
+ out_df = df.astype(bool)
+ check_round_trip(df, pa, write_kwargs={"schema": schema}, expected=out_df)
+
+ def test_additional_extension_arrays(self, pa):
+ # test additional ExtensionArrays that are supported through the
+ # __arrow_array__ protocol
+ pytest.importorskip("pyarrow")
+ df = pd.DataFrame(
+ {
+ "a": pd.Series([1, 2, 3], dtype="Int64"),
+ "b": pd.Series([1, 2, 3], dtype="UInt32"),
+ "c": pd.Series(["a", None, "c"], dtype="string"),
+ }
+ )
+ check_round_trip(df, pa)
+
+ df = pd.DataFrame({"a": pd.Series([1, 2, 3, None], dtype="Int64")})
+ check_round_trip(df, pa)
+
+ def test_pyarrow_backed_string_array(self, pa, string_storage):
+ # test ArrowStringArray supported through the __arrow_array__ protocol
+ pytest.importorskip("pyarrow")
+ df = pd.DataFrame({"a": pd.Series(["a", None, "c"], dtype="string[pyarrow]")})
+ with pd.option_context("string_storage", string_storage):
+ check_round_trip(df, pa, expected=df.astype(f"string[{string_storage}]"))
+
+ def test_additional_extension_types(self, pa):
+ # test additional ExtensionArrays that are supported through the
+ # __arrow_array__ protocol + by defining a custom ExtensionType
+ pytest.importorskip("pyarrow")
+ df = pd.DataFrame(
+ {
+ "c": pd.IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)]),
+ "d": pd.period_range("2012-01-01", periods=3, freq="D"),
+ # GH-45881 issue with interval with datetime64[ns] subtype
+ "e": pd.IntervalIndex.from_breaks(
+ pd.date_range("2012-01-01", periods=4, freq="D")
+ ),
+ }
+ )
+ check_round_trip(df, pa)
+
+ def test_timestamp_nanoseconds(self, pa):
+ # with version 2.6, pyarrow defaults to writing the nanoseconds, so
+ # this should work without error
+ # Note in previous pyarrows(<7.0.0), only the pseudo-version 2.0 was available
+ if not pa_version_under7p0:
+ ver = "2.6"
+ else:
+ ver = "2.0"
+ df = pd.DataFrame({"a": pd.date_range("2017-01-01", freq="1n", periods=10)})
+ check_round_trip(df, pa, write_kwargs={"version": ver})
+
+ def test_timezone_aware_index(self, request, pa, timezone_aware_date_list):
+ if (
+ not pa_version_under7p0
+ and timezone_aware_date_list.tzinfo != datetime.timezone.utc
+ ):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="temporary skip this test until it is properly resolved: "
+ "https://github.com/pandas-dev/pandas/issues/37286"
+ )
+ )
+ idx = 5 * [timezone_aware_date_list]
+ df = pd.DataFrame(index=idx, data={"index_as_col": idx})
+
+ # see gh-36004
+ # compare time(zone) values only, skip their class:
+ # pyarrow always creates fixed offset timezones using pytz.FixedOffset()
+ # even if it was datetime.timezone() originally
+ #
+ # technically they are the same:
+ # they both implement datetime.tzinfo
+ # they both wrap datetime.timedelta()
+ # this use-case sets the resolution to 1 minute
+ check_round_trip(df, pa, check_dtype=False)
+
+ def test_filter_row_groups(self, pa):
+ # https://github.com/pandas-dev/pandas/issues/26551
+ pytest.importorskip("pyarrow")
+ df = pd.DataFrame({"a": list(range(0, 3))})
+ with tm.ensure_clean() as path:
+ df.to_parquet(path, pa)
+ result = read_parquet(
+ path, pa, filters=[("a", "==", 0)], use_legacy_dataset=False
+ )
+ assert len(result) == 1
+
+ def test_read_parquet_manager(self, pa, using_array_manager):
+ # ensure that read_parquet honors the pandas.options.mode.data_manager option
+ df = pd.DataFrame(
+ np.random.default_rng(2).standard_normal((10, 3)), columns=["A", "B", "C"]
+ )
+
+ with tm.ensure_clean() as path:
+ df.to_parquet(path, pa)
+ result = read_parquet(path, pa)
+ if using_array_manager:
+ assert isinstance(result._mgr, pd.core.internals.ArrayManager)
+ else:
+ assert isinstance(result._mgr, pd.core.internals.BlockManager)
+
+ def test_read_dtype_backend_pyarrow_config(self, pa, df_full):
+ import pyarrow
+
+ df = df_full
+
+ # additional supported types for pyarrow
+ dti = pd.date_range("20130101", periods=3, tz="Europe/Brussels")
+ dti = dti._with_freq(None) # freq doesn't round-trip
+ df["datetime_tz"] = dti
+ df["bool_with_none"] = [True, None, True]
+
+ pa_table = pyarrow.Table.from_pandas(df)
+ expected = pa_table.to_pandas(types_mapper=pd.ArrowDtype)
+ if pa_version_under13p0:
+ # pyarrow infers datetimes as us instead of ns
+ expected["datetime"] = expected["datetime"].astype("timestamp[us][pyarrow]")
+ expected["datetime_with_nat"] = expected["datetime_with_nat"].astype(
+ "timestamp[us][pyarrow]"
+ )
+ expected["datetime_tz"] = expected["datetime_tz"].astype(
+ pd.ArrowDtype(pyarrow.timestamp(unit="us", tz="Europe/Brussels"))
+ )
+
+ check_round_trip(
+ df,
+ engine=pa,
+ read_kwargs={"dtype_backend": "pyarrow"},
+ expected=expected,
+ )
+
+ def test_read_dtype_backend_pyarrow_config_index(self, pa):
+ df = pd.DataFrame(
+ {"a": [1, 2]}, index=pd.Index([3, 4], name="test"), dtype="int64[pyarrow]"
+ )
+ expected = df.copy()
+ import pyarrow
+
+ if Version(pyarrow.__version__) > Version("11.0.0"):
+ expected.index = expected.index.astype("int64[pyarrow]")
+ check_round_trip(
+ df,
+ engine=pa,
+ read_kwargs={"dtype_backend": "pyarrow"},
+ expected=expected,
+ )
+
+ def test_columns_dtypes_not_invalid(self, pa):
+ df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))})
+
+ # numeric
+ df.columns = [0, 1]
+ check_round_trip(df, pa)
+
+ # bytes
+ df.columns = [b"foo", b"bar"]
+ with pytest.raises(NotImplementedError, match="|S3"):
+ # Bytes fails on read_parquet
+ check_round_trip(df, pa)
+
+ # python object
+ df.columns = [
+ datetime.datetime(2011, 1, 1, 0, 0),
+ datetime.datetime(2011, 1, 1, 1, 1),
+ ]
+ check_round_trip(df, pa)
+
+ def test_empty_columns(self, pa):
+ # GH 52034
+ df = pd.DataFrame(index=pd.Index(["a", "b", "c"], name="custom name"))
+ check_round_trip(df, pa)
+
+ def test_df_attrs_persistence(self, tmp_path, pa):
+ path = tmp_path / "test_df_metadata.p"
+ df = pd.DataFrame(data={1: [1]})
+ df.attrs = {"test_attribute": 1}
+ df.to_parquet(path, engine=pa)
+ new_df = read_parquet(path, engine=pa)
+ assert new_df.attrs == df.attrs
+
+ def test_string_inference(self, tmp_path, pa):
+ # GH#54431
+ path = tmp_path / "test_string_inference.p"
+ df = pd.DataFrame(data={"a": ["x", "y"]}, index=["a", "b"])
+ df.to_parquet(path, engine="pyarrow")
+ with pd.option_context("future.infer_string", True):
+ result = read_parquet(path, engine="pyarrow")
+ expected = pd.DataFrame(
+ data={"a": ["x", "y"]},
+ dtype="string[pyarrow_numpy]",
+ index=pd.Index(["a", "b"], dtype="string[pyarrow_numpy]"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.skipif(pa_version_under11p0, reason="not supported before 11.0")
+ def test_roundtrip_decimal(self, tmp_path, pa):
+ # GH#54768
+ import pyarrow as pa
+
+ path = tmp_path / "decimal.p"
+ df = pd.DataFrame({"a": [Decimal("123.00")]}, dtype="string[pyarrow]")
+ df.to_parquet(path, schema=pa.schema([("a", pa.decimal128(5))]))
+ result = read_parquet(path)
+ expected = pd.DataFrame({"a": ["123"]}, dtype="string[python]")
+ tm.assert_frame_equal(result, expected)
+
+ def test_infer_string_large_string_type(self, tmp_path, pa):
+ # GH#54798
+ import pyarrow as pa
+ import pyarrow.parquet as pq
+
+ path = tmp_path / "large_string.p"
+
+ table = pa.table({"a": pa.array([None, "b", "c"], pa.large_string())})
+ pq.write_table(table, path)
+
+ with pd.option_context("future.infer_string", True):
+ result = read_parquet(path)
+ expected = pd.DataFrame(
+ data={"a": [None, "b", "c"]},
+ dtype="string[pyarrow_numpy]",
+ columns=pd.Index(["a"], dtype="string[pyarrow_numpy]"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # NOTE: this test is not run by default, because it requires a lot of memory (>5GB)
+ # @pytest.mark.slow
+ # def test_string_column_above_2GB(self, tmp_path, pa):
+ # # https://github.com/pandas-dev/pandas/issues/55606
+ # # above 2GB of string data
+ # v1 = b"x" * 100000000
+ # v2 = b"x" * 147483646
+ # df = pd.DataFrame({"strings": [v1] * 20 + [v2] + ["x"] * 20}, dtype="string")
+ # df.to_parquet(tmp_path / "test.parquet")
+ # result = read_parquet(tmp_path / "test.parquet")
+ # assert result["strings"].dtype == "string"
+
+
+class TestParquetFastParquet(Base):
+ def test_basic(self, fp, df_full):
+ df = df_full
+
+ dti = pd.date_range("20130101", periods=3, tz="US/Eastern")
+ dti = dti._with_freq(None) # freq doesn't round-trip
+ df["datetime_tz"] = dti
+ df["timedelta"] = pd.timedelta_range("1 day", periods=3)
+ check_round_trip(df, fp)
+
+ def test_columns_dtypes_invalid(self, fp):
+ df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))})
+
+ err = TypeError
+ msg = "Column name must be a string"
+
+ # numeric
+ df.columns = [0, 1]
+ self.check_error_on_write(df, fp, err, msg)
+
+ # bytes
+ df.columns = [b"foo", b"bar"]
+ self.check_error_on_write(df, fp, err, msg)
+
+ # python object
+ df.columns = [
+ datetime.datetime(2011, 1, 1, 0, 0),
+ datetime.datetime(2011, 1, 1, 1, 1),
+ ]
+ self.check_error_on_write(df, fp, err, msg)
+
+ def test_duplicate_columns(self, fp):
+ # not currently able to handle duplicate columns
+ df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy()
+ msg = "Cannot create parquet dataset with duplicate column names"
+ self.check_error_on_write(df, fp, ValueError, msg)
+
+ def test_bool_with_none(self, fp):
+ df = pd.DataFrame({"a": [True, None, False]})
+ expected = pd.DataFrame({"a": [1.0, np.nan, 0.0]}, dtype="float16")
+ # Fastparquet bug in 0.7.1 makes it so that this dtype becomes
+ # float64
+ check_round_trip(df, fp, expected=expected, check_dtype=False)
+
+ def test_unsupported(self, fp):
+ # period
+ df = pd.DataFrame({"a": pd.period_range("2013", freq="M", periods=3)})
+ # error from fastparquet -> don't check exact error message
+ self.check_error_on_write(df, fp, ValueError, None)
+
+ # mixed
+ df = pd.DataFrame({"a": ["a", 1, 2.0]})
+ msg = "Can't infer object conversion type"
+ self.check_error_on_write(df, fp, ValueError, msg)
+
+ def test_categorical(self, fp):
+ df = pd.DataFrame({"a": pd.Categorical(list("abc"))})
+ check_round_trip(df, fp)
+
+ def test_filter_row_groups(self, fp):
+ d = {"a": list(range(0, 3))}
+ df = pd.DataFrame(d)
+ with tm.ensure_clean() as path:
+ df.to_parquet(path, fp, compression=None, row_group_offsets=1)
+ result = read_parquet(path, fp, filters=[("a", "==", 0)])
+ assert len(result) == 1
+
+ @pytest.mark.single_cpu
+ def test_s3_roundtrip(self, df_compat, s3_public_bucket, fp, s3so):
+ # GH #19134
+ check_round_trip(
+ df_compat,
+ fp,
+ path=f"s3://{s3_public_bucket.name}/fastparquet.parquet",
+ read_kwargs={"storage_options": s3so},
+ write_kwargs={"compression": None, "storage_options": s3so},
+ )
+
+ def test_partition_cols_supported(self, tmp_path, fp, df_full):
+ # GH #23283
+ partition_cols = ["bool", "int"]
+ df = df_full
+ df.to_parquet(
+ tmp_path,
+ engine="fastparquet",
+ partition_cols=partition_cols,
+ compression=None,
+ )
+ assert os.path.exists(tmp_path)
+ import fastparquet
+
+ actual_partition_cols = fastparquet.ParquetFile(str(tmp_path), False).cats
+ assert len(actual_partition_cols) == 2
+
+ def test_partition_cols_string(self, tmp_path, fp, df_full):
+ # GH #27117
+ partition_cols = "bool"
+ df = df_full
+ df.to_parquet(
+ tmp_path,
+ engine="fastparquet",
+ partition_cols=partition_cols,
+ compression=None,
+ )
+ assert os.path.exists(tmp_path)
+ import fastparquet
+
+ actual_partition_cols = fastparquet.ParquetFile(str(tmp_path), False).cats
+ assert len(actual_partition_cols) == 1
+
+ def test_partition_on_supported(self, tmp_path, fp, df_full):
+ # GH #23283
+ partition_cols = ["bool", "int"]
+ df = df_full
+ df.to_parquet(
+ tmp_path,
+ engine="fastparquet",
+ compression=None,
+ partition_on=partition_cols,
+ )
+ assert os.path.exists(tmp_path)
+ import fastparquet
+
+ actual_partition_cols = fastparquet.ParquetFile(str(tmp_path), False).cats
+ assert len(actual_partition_cols) == 2
+
+ def test_error_on_using_partition_cols_and_partition_on(
+ self, tmp_path, fp, df_full
+ ):
+ # GH #23283
+ partition_cols = ["bool", "int"]
+ df = df_full
+ msg = (
+ "Cannot use both partition_on and partition_cols. Use partition_cols for "
+ "partitioning data"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.to_parquet(
+ tmp_path,
+ engine="fastparquet",
+ compression=None,
+ partition_on=partition_cols,
+ partition_cols=partition_cols,
+ )
+
+ @pytest.mark.skipif(using_copy_on_write(), reason="fastparquet writes into Index")
+ def test_empty_dataframe(self, fp):
+ # GH #27339
+ df = pd.DataFrame()
+ expected = df.copy()
+ check_round_trip(df, fp, expected=expected)
+
+ @pytest.mark.skipif(using_copy_on_write(), reason="fastparquet writes into Index")
+ def test_timezone_aware_index(self, fp, timezone_aware_date_list):
+ idx = 5 * [timezone_aware_date_list]
+
+ df = pd.DataFrame(index=idx, data={"index_as_col": idx})
+
+ expected = df.copy()
+ expected.index.name = "index"
+ check_round_trip(df, fp, expected=expected)
+
+ def test_use_nullable_dtypes_not_supported(self, fp):
+ df = pd.DataFrame({"a": [1, 2]})
+
+ with tm.ensure_clean() as path:
+ df.to_parquet(path)
+ with pytest.raises(ValueError, match="not supported for the fastparquet"):
+ with tm.assert_produces_warning(FutureWarning):
+ read_parquet(path, engine="fastparquet", use_nullable_dtypes=True)
+ with pytest.raises(ValueError, match="not supported for the fastparquet"):
+ read_parquet(path, engine="fastparquet", dtype_backend="pyarrow")
+
+ def test_close_file_handle_on_read_error(self):
+ with tm.ensure_clean("test.parquet") as path:
+ pathlib.Path(path).write_bytes(b"breakit")
+ with pytest.raises(Exception, match=""): # Not important which exception
+ read_parquet(path, engine="fastparquet")
+ # The next line raises an error on Windows if the file is still open
+ pathlib.Path(path).unlink(missing_ok=False)
+
+ def test_bytes_file_name(self, engine):
+ # GH#48944
+ df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]})
+ with tm.ensure_clean("test.parquet") as path:
+ with open(path.encode(), "wb") as f:
+ df.to_parquet(f)
+
+ result = read_parquet(path, engine=engine)
+ tm.assert_frame_equal(result, df)
+
+ def test_filesystem_notimplemented(self):
+ pytest.importorskip("fastparquet")
+ df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]})
+ with tm.ensure_clean() as path:
+ with pytest.raises(
+ NotImplementedError, match="filesystem is not implemented"
+ ):
+ df.to_parquet(path, engine="fastparquet", filesystem="foo")
+
+ with tm.ensure_clean() as path:
+ pathlib.Path(path).write_bytes(b"foo")
+ with pytest.raises(
+ NotImplementedError, match="filesystem is not implemented"
+ ):
+ read_parquet(path, engine="fastparquet", filesystem="foo")
+
+ def test_invalid_filesystem(self):
+ pytest.importorskip("pyarrow")
+ df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]})
+ with tm.ensure_clean() as path:
+ with pytest.raises(
+ ValueError, match="filesystem must be a pyarrow or fsspec FileSystem"
+ ):
+ df.to_parquet(path, engine="pyarrow", filesystem="foo")
+
+ with tm.ensure_clean() as path:
+ pathlib.Path(path).write_bytes(b"foo")
+ with pytest.raises(
+ ValueError, match="filesystem must be a pyarrow or fsspec FileSystem"
+ ):
+ read_parquet(path, engine="pyarrow", filesystem="foo")
+
+ def test_unsupported_pa_filesystem_storage_options(self):
+ pa_fs = pytest.importorskip("pyarrow.fs")
+ df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]})
+ with tm.ensure_clean() as path:
+ with pytest.raises(
+ NotImplementedError,
+ match="storage_options not supported with a pyarrow FileSystem.",
+ ):
+ df.to_parquet(
+ path,
+ engine="pyarrow",
+ filesystem=pa_fs.LocalFileSystem(),
+ storage_options={"foo": "bar"},
+ )
+
+ with tm.ensure_clean() as path:
+ pathlib.Path(path).write_bytes(b"foo")
+ with pytest.raises(
+ NotImplementedError,
+ match="storage_options not supported with a pyarrow FileSystem.",
+ ):
+ read_parquet(
+ path,
+ engine="pyarrow",
+ filesystem=pa_fs.LocalFileSystem(),
+ storage_options={"foo": "bar"},
+ )
+
+ def test_invalid_dtype_backend(self, engine):
+ msg = (
+ "dtype_backend numpy is invalid, only 'numpy_nullable' and "
+ "'pyarrow' are allowed."
+ )
+ df = pd.DataFrame({"int": list(range(1, 4))})
+ with tm.ensure_clean("tmp.parquet") as path:
+ df.to_parquet(path)
+ with pytest.raises(ValueError, match=msg):
+ read_parquet(path, dtype_backend="numpy")
+
+ @pytest.mark.skipif(using_copy_on_write(), reason="fastparquet writes into Index")
+ def test_empty_columns(self, fp):
+ # GH 52034
+ df = pd.DataFrame(index=pd.Index(["a", "b", "c"], name="custom name"))
+ expected = pd.DataFrame(index=pd.Index(["a", "b", "c"], name="custom name"))
+ check_round_trip(df, fp, expected=expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_pickle.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_pickle.py
new file mode 100644
index 0000000000000000000000000000000000000000..75e4de7074e63f989c2a273c0836bf8c41d9237d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_pickle.py
@@ -0,0 +1,587 @@
+"""
+manage legacy pickle tests
+
+How to add pickle tests:
+
+1. Install pandas version intended to output the pickle.
+
+2. Execute "generate_legacy_storage_files.py" to create the pickle.
+$ python generate_legacy_storage_files.py pickle
+
+3. Move the created pickle to "data/legacy_pickle/" directory.
+"""
+from array import array
+import bz2
+import datetime
+import functools
+from functools import partial
+import gzip
+import io
+import os
+from pathlib import Path
+import pickle
+import shutil
+import tarfile
+import uuid
+import zipfile
+
+import numpy as np
+import pytest
+
+from pandas.compat import (
+ get_lzma_file,
+ is_platform_little_endian,
+)
+from pandas.compat._optional import import_optional_dependency
+from pandas.compat.compressors import flatten_buffer
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ Index,
+ Series,
+ period_range,
+)
+import pandas._testing as tm
+from pandas.tests.io.generate_legacy_storage_files import create_pickle_data
+
+import pandas.io.common as icom
+from pandas.tseries.offsets import (
+ Day,
+ MonthEnd,
+)
+
+
+@pytest.fixture
+def current_pickle_data():
+ # our current version pickle data
+ return create_pickle_data()
+
+
+# ---------------------
+# comparison functions
+# ---------------------
+def compare_element(result, expected, typ):
+ if isinstance(expected, Index):
+ tm.assert_index_equal(expected, result)
+ return
+
+ if typ.startswith("sp_"):
+ tm.assert_equal(result, expected)
+ elif typ == "timestamp":
+ if expected is pd.NaT:
+ assert result is pd.NaT
+ else:
+ assert result == expected
+ else:
+ comparator = getattr(tm, f"assert_{typ}_equal", tm.assert_almost_equal)
+ comparator(result, expected)
+
+
+# ---------------------
+# tests
+# ---------------------
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ b"123",
+ b"123456",
+ bytearray(b"123"),
+ memoryview(b"123"),
+ pickle.PickleBuffer(b"123"),
+ array("I", [1, 2, 3]),
+ memoryview(b"123456").cast("B", (3, 2)),
+ memoryview(b"123456").cast("B", (3, 2))[::2],
+ np.arange(12).reshape((3, 4), order="C"),
+ np.arange(12).reshape((3, 4), order="F"),
+ np.arange(12).reshape((3, 4), order="C")[:, ::2],
+ ],
+)
+def test_flatten_buffer(data):
+ result = flatten_buffer(data)
+ expected = memoryview(data).tobytes("A")
+ assert result == expected
+ if isinstance(data, (bytes, bytearray)):
+ assert result is data
+ elif isinstance(result, memoryview):
+ assert result.ndim == 1
+ assert result.format == "B"
+ assert result.contiguous
+ assert result.shape == (result.nbytes,)
+
+
+def test_pickles(datapath):
+ if not is_platform_little_endian():
+ pytest.skip("known failure on non-little endian")
+
+ # For loop for compat with --strict-data-files
+ for legacy_pickle in Path(__file__).parent.glob("data/legacy_pickle/*/*.p*kl*"):
+ legacy_pickle = datapath(legacy_pickle)
+
+ data = pd.read_pickle(legacy_pickle)
+
+ for typ, dv in data.items():
+ for dt, result in dv.items():
+ expected = data[typ][dt]
+
+ if typ == "series" and dt == "ts":
+ # GH 7748
+ tm.assert_series_equal(result, expected)
+ assert result.index.freq == expected.index.freq
+ assert not result.index.freq.normalize
+ tm.assert_series_equal(result > 0, expected > 0)
+
+ # GH 9291
+ freq = result.index.freq
+ assert freq + Day(1) == Day(2)
+
+ res = freq + pd.Timedelta(hours=1)
+ assert isinstance(res, pd.Timedelta)
+ assert res == pd.Timedelta(days=1, hours=1)
+
+ res = freq + pd.Timedelta(nanoseconds=1)
+ assert isinstance(res, pd.Timedelta)
+ assert res == pd.Timedelta(days=1, nanoseconds=1)
+ elif typ == "index" and dt == "period":
+ tm.assert_index_equal(result, expected)
+ assert isinstance(result.freq, MonthEnd)
+ assert result.freq == MonthEnd()
+ assert result.freqstr == "M"
+ tm.assert_index_equal(result.shift(2), expected.shift(2))
+ elif typ == "series" and dt in ("dt_tz", "cat"):
+ tm.assert_series_equal(result, expected)
+ elif typ == "frame" and dt in (
+ "dt_mixed_tzs",
+ "cat_onecol",
+ "cat_and_float",
+ ):
+ tm.assert_frame_equal(result, expected)
+ else:
+ compare_element(result, expected, typ)
+
+
+def python_pickler(obj, path):
+ with open(path, "wb") as fh:
+ pickle.dump(obj, fh, protocol=-1)
+
+
+def python_unpickler(path):
+ with open(path, "rb") as fh:
+ fh.seek(0)
+ return pickle.load(fh)
+
+
+@pytest.mark.parametrize(
+ "pickle_writer",
+ [
+ pytest.param(python_pickler, id="python"),
+ pytest.param(pd.to_pickle, id="pandas_proto_default"),
+ pytest.param(
+ functools.partial(pd.to_pickle, protocol=pickle.HIGHEST_PROTOCOL),
+ id="pandas_proto_highest",
+ ),
+ pytest.param(functools.partial(pd.to_pickle, protocol=4), id="pandas_proto_4"),
+ pytest.param(
+ functools.partial(pd.to_pickle, protocol=5),
+ id="pandas_proto_5",
+ ),
+ ],
+)
+@pytest.mark.parametrize("writer", [pd.to_pickle, python_pickler])
+def test_round_trip_current(current_pickle_data, pickle_writer, writer):
+ data = current_pickle_data
+ for typ, dv in data.items():
+ for dt, expected in dv.items():
+ with tm.ensure_clean() as path:
+ # test writing with each pickler
+ pickle_writer(expected, path)
+
+ # test reading with each unpickler
+ result = pd.read_pickle(path)
+ compare_element(result, expected, typ)
+
+ result = python_unpickler(path)
+ compare_element(result, expected, typ)
+
+ # and the same for file objects (GH 35679)
+ with open(path, mode="wb") as handle:
+ writer(expected, path)
+ handle.seek(0) # shouldn't close file handle
+ with open(path, mode="rb") as handle:
+ result = pd.read_pickle(handle)
+ handle.seek(0) # shouldn't close file handle
+ compare_element(result, expected, typ)
+
+
+def test_pickle_path_pathlib():
+ df = tm.makeDataFrame()
+ result = tm.round_trip_pathlib(df.to_pickle, pd.read_pickle)
+ tm.assert_frame_equal(df, result)
+
+
+def test_pickle_path_localpath():
+ df = tm.makeDataFrame()
+ result = tm.round_trip_localpath(df.to_pickle, pd.read_pickle)
+ tm.assert_frame_equal(df, result)
+
+
+# ---------------------
+# test pickle compression
+# ---------------------
+
+
+@pytest.fixture
+def get_random_path():
+ return f"__{uuid.uuid4()}__.pickle"
+
+
+class TestCompression:
+ _extension_to_compression = icom.extension_to_compression
+
+ def compress_file(self, src_path, dest_path, compression):
+ if compression is None:
+ shutil.copyfile(src_path, dest_path)
+ return
+
+ if compression == "gzip":
+ f = gzip.open(dest_path, "w")
+ elif compression == "bz2":
+ f = bz2.BZ2File(dest_path, "w")
+ elif compression == "zip":
+ with zipfile.ZipFile(dest_path, "w", compression=zipfile.ZIP_DEFLATED) as f:
+ f.write(src_path, os.path.basename(src_path))
+ elif compression == "tar":
+ with open(src_path, "rb") as fh:
+ with tarfile.open(dest_path, mode="w") as tar:
+ tarinfo = tar.gettarinfo(src_path, os.path.basename(src_path))
+ tar.addfile(tarinfo, fh)
+ elif compression == "xz":
+ f = get_lzma_file()(dest_path, "w")
+ elif compression == "zstd":
+ f = import_optional_dependency("zstandard").open(dest_path, "wb")
+ else:
+ msg = f"Unrecognized compression type: {compression}"
+ raise ValueError(msg)
+
+ if compression not in ["zip", "tar"]:
+ with open(src_path, "rb") as fh:
+ with f:
+ f.write(fh.read())
+
+ def test_write_explicit(self, compression, get_random_path):
+ base = get_random_path
+ path1 = base + ".compressed"
+ path2 = base + ".raw"
+
+ with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:
+ df = tm.makeDataFrame()
+
+ # write to compressed file
+ df.to_pickle(p1, compression=compression)
+
+ # decompress
+ with tm.decompress_file(p1, compression=compression) as f:
+ with open(p2, "wb") as fh:
+ fh.write(f.read())
+
+ # read decompressed file
+ df2 = pd.read_pickle(p2, compression=None)
+
+ tm.assert_frame_equal(df, df2)
+
+ @pytest.mark.parametrize("compression", ["", "None", "bad", "7z"])
+ def test_write_explicit_bad(self, compression, get_random_path):
+ with pytest.raises(ValueError, match="Unrecognized compression type"):
+ with tm.ensure_clean(get_random_path) as path:
+ df = tm.makeDataFrame()
+ df.to_pickle(path, compression=compression)
+
+ def test_write_infer(self, compression_ext, get_random_path):
+ base = get_random_path
+ path1 = base + compression_ext
+ path2 = base + ".raw"
+ compression = self._extension_to_compression.get(compression_ext.lower())
+
+ with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:
+ df = tm.makeDataFrame()
+
+ # write to compressed file by inferred compression method
+ df.to_pickle(p1)
+
+ # decompress
+ with tm.decompress_file(p1, compression=compression) as f:
+ with open(p2, "wb") as fh:
+ fh.write(f.read())
+
+ # read decompressed file
+ df2 = pd.read_pickle(p2, compression=None)
+
+ tm.assert_frame_equal(df, df2)
+
+ def test_read_explicit(self, compression, get_random_path):
+ base = get_random_path
+ path1 = base + ".raw"
+ path2 = base + ".compressed"
+
+ with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:
+ df = tm.makeDataFrame()
+
+ # write to uncompressed file
+ df.to_pickle(p1, compression=None)
+
+ # compress
+ self.compress_file(p1, p2, compression=compression)
+
+ # read compressed file
+ df2 = pd.read_pickle(p2, compression=compression)
+ tm.assert_frame_equal(df, df2)
+
+ def test_read_infer(self, compression_ext, get_random_path):
+ base = get_random_path
+ path1 = base + ".raw"
+ path2 = base + compression_ext
+ compression = self._extension_to_compression.get(compression_ext.lower())
+
+ with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:
+ df = tm.makeDataFrame()
+
+ # write to uncompressed file
+ df.to_pickle(p1, compression=None)
+
+ # compress
+ self.compress_file(p1, p2, compression=compression)
+
+ # read compressed file by inferred compression method
+ df2 = pd.read_pickle(p2)
+ tm.assert_frame_equal(df, df2)
+
+
+# ---------------------
+# test pickle compression
+# ---------------------
+
+
+class TestProtocol:
+ @pytest.mark.parametrize("protocol", [-1, 0, 1, 2])
+ def test_read(self, protocol, get_random_path):
+ with tm.ensure_clean(get_random_path) as path:
+ df = tm.makeDataFrame()
+ df.to_pickle(path, protocol=protocol)
+ df2 = pd.read_pickle(path)
+ tm.assert_frame_equal(df, df2)
+
+
+@pytest.mark.parametrize(
+ ["pickle_file", "excols"],
+ [
+ ("test_py27.pkl", Index(["a", "b", "c"])),
+ (
+ "test_mi_py27.pkl",
+ pd.MultiIndex.from_arrays([["a", "b", "c"], ["A", "B", "C"]]),
+ ),
+ ],
+)
+def test_unicode_decode_error(datapath, pickle_file, excols):
+ # pickle file written with py27, should be readable without raising
+ # UnicodeDecodeError, see GH#28645 and GH#31988
+ path = datapath("io", "data", "pickle", pickle_file)
+ df = pd.read_pickle(path)
+
+ # just test the columns are correct since the values are random
+ tm.assert_index_equal(df.columns, excols)
+
+
+# ---------------------
+# tests for buffer I/O
+# ---------------------
+
+
+def test_pickle_buffer_roundtrip():
+ with tm.ensure_clean() as path:
+ df = tm.makeDataFrame()
+ with open(path, "wb") as fh:
+ df.to_pickle(fh)
+ with open(path, "rb") as fh:
+ result = pd.read_pickle(fh)
+ tm.assert_frame_equal(df, result)
+
+
+# ---------------------
+# tests for URL I/O
+# ---------------------
+
+
+@pytest.mark.parametrize(
+ "mockurl", ["http://url.com", "ftp://test.com", "http://gzip.com"]
+)
+def test_pickle_generalurl_read(monkeypatch, mockurl):
+ def python_pickler(obj, path):
+ with open(path, "wb") as fh:
+ pickle.dump(obj, fh, protocol=-1)
+
+ class MockReadResponse:
+ def __init__(self, path) -> None:
+ self.file = open(path, "rb")
+ if "gzip" in path:
+ self.headers = {"Content-Encoding": "gzip"}
+ else:
+ self.headers = {"Content-Encoding": ""}
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ self.close()
+
+ def read(self):
+ return self.file.read()
+
+ def close(self):
+ return self.file.close()
+
+ with tm.ensure_clean() as path:
+
+ def mock_urlopen_read(*args, **kwargs):
+ return MockReadResponse(path)
+
+ df = tm.makeDataFrame()
+ python_pickler(df, path)
+ monkeypatch.setattr("urllib.request.urlopen", mock_urlopen_read)
+ result = pd.read_pickle(mockurl)
+ tm.assert_frame_equal(df, result)
+
+
+def test_pickle_fsspec_roundtrip():
+ pytest.importorskip("fsspec")
+ with tm.ensure_clean():
+ mockurl = "memory://mockfile"
+ df = tm.makeDataFrame()
+ df.to_pickle(mockurl)
+ result = pd.read_pickle(mockurl)
+ tm.assert_frame_equal(df, result)
+
+
+class MyTz(datetime.tzinfo):
+ def __init__(self) -> None:
+ pass
+
+
+def test_read_pickle_with_subclass():
+ # GH 12163
+ expected = Series(dtype=object), MyTz()
+ result = tm.round_trip_pickle(expected)
+
+ tm.assert_series_equal(result[0], expected[0])
+ assert isinstance(result[1], MyTz)
+
+
+def test_pickle_binary_object_compression(compression):
+ """
+ Read/write from binary file-objects w/wo compression.
+
+ GH 26237, GH 29054, and GH 29570
+ """
+ df = tm.makeDataFrame()
+
+ # reference for compression
+ with tm.ensure_clean() as path:
+ df.to_pickle(path, compression=compression)
+ reference = Path(path).read_bytes()
+
+ # write
+ buffer = io.BytesIO()
+ df.to_pickle(buffer, compression=compression)
+ buffer.seek(0)
+
+ # gzip and zip safe the filename: cannot compare the compressed content
+ assert buffer.getvalue() == reference or compression in ("gzip", "zip", "tar")
+
+ # read
+ read_df = pd.read_pickle(buffer, compression=compression)
+ buffer.seek(0)
+ tm.assert_frame_equal(df, read_df)
+
+
+def test_pickle_dataframe_with_multilevel_index(
+ multiindex_year_month_day_dataframe_random_data,
+ multiindex_dataframe_random_data,
+):
+ ymd = multiindex_year_month_day_dataframe_random_data
+ frame = multiindex_dataframe_random_data
+
+ def _test_roundtrip(frame):
+ unpickled = tm.round_trip_pickle(frame)
+ tm.assert_frame_equal(frame, unpickled)
+
+ _test_roundtrip(frame)
+ _test_roundtrip(frame.T)
+ _test_roundtrip(ymd)
+ _test_roundtrip(ymd.T)
+
+
+def test_pickle_timeseries_periodindex():
+ # GH#2891
+ prng = period_range("1/1/2011", "1/1/2012", freq="M")
+ ts = Series(np.random.default_rng(2).standard_normal(len(prng)), prng)
+ new_ts = tm.round_trip_pickle(ts)
+ assert new_ts.index.freq == "M"
+
+
+@pytest.mark.parametrize(
+ "name", [777, 777.0, "name", datetime.datetime(2001, 11, 11), (1, 2)]
+)
+def test_pickle_preserve_name(name):
+ unpickled = tm.round_trip_pickle(tm.makeTimeSeries(name=name))
+ assert unpickled.name == name
+
+
+def test_pickle_datetimes(datetime_series):
+ unp_ts = tm.round_trip_pickle(datetime_series)
+ tm.assert_series_equal(unp_ts, datetime_series)
+
+
+def test_pickle_strings(string_series):
+ unp_series = tm.round_trip_pickle(string_series)
+ tm.assert_series_equal(unp_series, string_series)
+
+
+@td.skip_array_manager_invalid_test
+def test_pickle_preserves_block_ndim():
+ # GH#37631
+ ser = Series(list("abc")).astype("category").iloc[[0]]
+ res = tm.round_trip_pickle(ser)
+
+ assert res._mgr.blocks[0].ndim == 1
+ assert res._mgr.blocks[0].shape == (1,)
+
+ # GH#37631 OP issue was about indexing, underlying problem was pickle
+ tm.assert_series_equal(res[[True]], ser)
+
+
+@pytest.mark.parametrize("protocol", [pickle.DEFAULT_PROTOCOL, pickle.HIGHEST_PROTOCOL])
+def test_pickle_big_dataframe_compression(protocol, compression):
+ # GH#39002
+ df = pd.DataFrame(range(100000))
+ result = tm.round_trip_pathlib(
+ partial(df.to_pickle, protocol=protocol, compression=compression),
+ partial(pd.read_pickle, compression=compression),
+ )
+ tm.assert_frame_equal(df, result)
+
+
+def test_pickle_frame_v124_unpickle_130(datapath):
+ # GH#42345 DataFrame created in 1.2.x, unpickle in 1.3.x
+ path = datapath(
+ Path(__file__).parent,
+ "data",
+ "legacy_pickle",
+ "1.2.4",
+ "empty_frame_v1_2_4-GH#42345.pkl",
+ )
+ with open(path, "rb") as fd:
+ df = pickle.load(fd)
+
+ expected = pd.DataFrame(index=[], columns=[])
+ tm.assert_frame_equal(df, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_s3.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_s3.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ee3c09631d0e106515fb0e99cdf832b390dbbc2
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_s3.py
@@ -0,0 +1,48 @@
+from io import BytesIO
+
+import pytest
+
+from pandas import read_csv
+
+
+def test_streaming_s3_objects():
+ # GH17135
+ # botocore gained iteration support in 1.10.47, can now be used in read_*
+ pytest.importorskip("botocore", minversion="1.10.47")
+ from botocore.response import StreamingBody
+
+ data = [b"foo,bar,baz\n1,2,3\n4,5,6\n", b"just,the,header\n"]
+ for el in data:
+ body = StreamingBody(BytesIO(el), content_length=len(el))
+ read_csv(body)
+
+
+@pytest.mark.single_cpu
+def test_read_without_creds_from_pub_bucket(s3_public_bucket_with_data, s3so):
+ # GH 34626
+ pytest.importorskip("s3fs")
+ result = read_csv(
+ f"s3://{s3_public_bucket_with_data.name}/tips.csv",
+ nrows=3,
+ storage_options=s3so,
+ )
+ assert len(result) == 3
+
+
+@pytest.mark.single_cpu
+def test_read_with_creds_from_pub_bucket(s3_public_bucket_with_data, monkeypatch, s3so):
+ # Ensure we can read from a public bucket with credentials
+ # GH 34626
+
+ # temporary workaround as moto fails for botocore >= 1.11 otherwise,
+ # see https://github.com/spulec/moto/issues/1924 & 1952
+ pytest.importorskip("s3fs")
+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "foobar_key")
+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "foobar_secret")
+ df = read_csv(
+ f"s3://{s3_public_bucket_with_data.name}/tips.csv",
+ nrows=5,
+ header=None,
+ storage_options=s3so,
+ )
+ assert len(df) == 5
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_spss.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_spss.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1d0795234e729c076fb1dca09ff2263cf9292a0
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_spss.py
@@ -0,0 +1,113 @@
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+pyreadstat = pytest.importorskip("pyreadstat")
+
+
+# TODO(CoW) - detection of chained assignment in cython
+# https://github.com/pandas-dev/pandas/issues/51315
+@pytest.mark.filterwarnings("ignore::pandas.errors.ChainedAssignmentError")
+@pytest.mark.parametrize("path_klass", [lambda p: p, Path])
+def test_spss_labelled_num(path_klass, datapath):
+ # test file from the Haven project (https://haven.tidyverse.org/)
+ fname = path_klass(datapath("io", "data", "spss", "labelled-num.sav"))
+
+ df = pd.read_spss(fname, convert_categoricals=True)
+ expected = pd.DataFrame({"VAR00002": "This is one"}, index=[0])
+ expected["VAR00002"] = pd.Categorical(expected["VAR00002"])
+ tm.assert_frame_equal(df, expected)
+
+ df = pd.read_spss(fname, convert_categoricals=False)
+ expected = pd.DataFrame({"VAR00002": 1.0}, index=[0])
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.filterwarnings("ignore::pandas.errors.ChainedAssignmentError")
+def test_spss_labelled_num_na(datapath):
+ # test file from the Haven project (https://haven.tidyverse.org/)
+ fname = datapath("io", "data", "spss", "labelled-num-na.sav")
+
+ df = pd.read_spss(fname, convert_categoricals=True)
+ expected = pd.DataFrame({"VAR00002": ["This is one", None]})
+ expected["VAR00002"] = pd.Categorical(expected["VAR00002"])
+ tm.assert_frame_equal(df, expected)
+
+ df = pd.read_spss(fname, convert_categoricals=False)
+ expected = pd.DataFrame({"VAR00002": [1.0, np.nan]})
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.filterwarnings("ignore::pandas.errors.ChainedAssignmentError")
+def test_spss_labelled_str(datapath):
+ # test file from the Haven project (https://haven.tidyverse.org/)
+ fname = datapath("io", "data", "spss", "labelled-str.sav")
+
+ df = pd.read_spss(fname, convert_categoricals=True)
+ expected = pd.DataFrame({"gender": ["Male", "Female"]})
+ expected["gender"] = pd.Categorical(expected["gender"])
+ tm.assert_frame_equal(df, expected)
+
+ df = pd.read_spss(fname, convert_categoricals=False)
+ expected = pd.DataFrame({"gender": ["M", "F"]})
+ tm.assert_frame_equal(df, expected)
+
+
+@pytest.mark.filterwarnings("ignore::pandas.errors.ChainedAssignmentError")
+def test_spss_umlauts(datapath):
+ # test file from the Haven project (https://haven.tidyverse.org/)
+ fname = datapath("io", "data", "spss", "umlauts.sav")
+
+ df = pd.read_spss(fname, convert_categoricals=True)
+ expected = pd.DataFrame(
+ {"var1": ["the ä umlaut", "the ü umlaut", "the ä umlaut", "the ö umlaut"]}
+ )
+ expected["var1"] = pd.Categorical(expected["var1"])
+ tm.assert_frame_equal(df, expected)
+
+ df = pd.read_spss(fname, convert_categoricals=False)
+ expected = pd.DataFrame({"var1": [1.0, 2.0, 1.0, 3.0]})
+ tm.assert_frame_equal(df, expected)
+
+
+def test_spss_usecols(datapath):
+ # usecols must be list-like
+ fname = datapath("io", "data", "spss", "labelled-num.sav")
+
+ with pytest.raises(TypeError, match="usecols must be list-like."):
+ pd.read_spss(fname, usecols="VAR00002")
+
+
+def test_spss_umlauts_dtype_backend(datapath, dtype_backend):
+ # test file from the Haven project (https://haven.tidyverse.org/)
+ fname = datapath("io", "data", "spss", "umlauts.sav")
+
+ df = pd.read_spss(fname, convert_categoricals=False, dtype_backend=dtype_backend)
+ expected = pd.DataFrame({"var1": [1.0, 2.0, 1.0, 3.0]}, dtype="Int64")
+
+ if dtype_backend == "pyarrow":
+ pa = pytest.importorskip("pyarrow")
+
+ from pandas.arrays import ArrowExtensionArray
+
+ expected = pd.DataFrame(
+ {
+ col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))
+ for col in expected.columns
+ }
+ )
+
+ tm.assert_frame_equal(df, expected)
+
+
+def test_invalid_dtype_backend():
+ msg = (
+ "dtype_backend numpy is invalid, only 'numpy_nullable' and "
+ "'pyarrow' are allowed."
+ )
+ with pytest.raises(ValueError, match=msg):
+ pd.read_spss("test", dtype_backend="numpy")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_sql.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_sql.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fd6a52031c5270d16a7d3d501e37a972ddecdda
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_sql.py
@@ -0,0 +1,3619 @@
+"""SQL io tests
+
+The SQL tests are broken down in different classes:
+
+- `PandasSQLTest`: base class with common methods for all test classes
+- Tests for the public API (only tests with sqlite3)
+ - `_TestSQLApi` base class
+ - `TestSQLApi`: test the public API with sqlalchemy engine
+ - `TestSQLiteFallbackApi`: test the public API with a sqlite DBAPI
+ connection
+- Tests for the different SQL flavors (flavor specific type conversions)
+ - Tests for the sqlalchemy mode: `_TestSQLAlchemy` is the base class with
+ common methods. The different tested flavors (sqlite3, MySQL,
+ PostgreSQL) derive from the base class
+ - Tests for the fallback mode (`TestSQLiteFallback`)
+
+"""
+from __future__ import annotations
+
+import contextlib
+from contextlib import closing
+import csv
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
+from io import StringIO
+from pathlib import Path
+import sqlite3
+import uuid
+
+import numpy as np
+import pytest
+
+from pandas._libs import lib
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ DatetimeTZDtype,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ concat,
+ date_range,
+ isna,
+ to_datetime,
+ to_timedelta,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ ArrowStringArray,
+ StringArray,
+)
+from pandas.util.version import Version
+
+from pandas.io import sql
+from pandas.io.sql import (
+ SQLAlchemyEngine,
+ SQLDatabase,
+ SQLiteDatabase,
+ get_engine,
+ pandasSQL_builder,
+ read_sql_query,
+ read_sql_table,
+)
+
+try:
+ import sqlalchemy
+
+ SQLALCHEMY_INSTALLED = True
+except ImportError:
+ SQLALCHEMY_INSTALLED = False
+
+
+@pytest.fixture
+def sql_strings():
+ return {
+ "read_parameters": {
+ "sqlite": "SELECT * FROM iris WHERE Name=? AND SepalLength=?",
+ "mysql": "SELECT * FROM iris WHERE `Name`=%s AND `SepalLength`=%s",
+ "postgresql": 'SELECT * FROM iris WHERE "Name"=%s AND "SepalLength"=%s',
+ },
+ "read_named_parameters": {
+ "sqlite": """
+ SELECT * FROM iris WHERE Name=:name AND SepalLength=:length
+ """,
+ "mysql": """
+ SELECT * FROM iris WHERE
+ `Name`=%(name)s AND `SepalLength`=%(length)s
+ """,
+ "postgresql": """
+ SELECT * FROM iris WHERE
+ "Name"=%(name)s AND "SepalLength"=%(length)s
+ """,
+ },
+ "read_no_parameters_with_percent": {
+ "sqlite": "SELECT * FROM iris WHERE Name LIKE '%'",
+ "mysql": "SELECT * FROM iris WHERE `Name` LIKE '%'",
+ "postgresql": "SELECT * FROM iris WHERE \"Name\" LIKE '%'",
+ },
+ }
+
+
+def iris_table_metadata(dialect: str):
+ from sqlalchemy import (
+ REAL,
+ Column,
+ Float,
+ MetaData,
+ String,
+ Table,
+ )
+
+ dtype = Float if dialect == "postgresql" else REAL
+ metadata = MetaData()
+ iris = Table(
+ "iris",
+ metadata,
+ Column("SepalLength", dtype),
+ Column("SepalWidth", dtype),
+ Column("PetalLength", dtype),
+ Column("PetalWidth", dtype),
+ Column("Name", String(200)),
+ )
+ return iris
+
+
+def create_and_load_iris_sqlite3(conn: sqlite3.Connection, iris_file: Path):
+ cur = conn.cursor()
+ stmt = """CREATE TABLE iris (
+ "SepalLength" REAL,
+ "SepalWidth" REAL,
+ "PetalLength" REAL,
+ "PetalWidth" REAL,
+ "Name" TEXT
+ )"""
+ cur.execute(stmt)
+ with iris_file.open(newline=None, encoding="utf-8") as csvfile:
+ reader = csv.reader(csvfile)
+ next(reader)
+ stmt = "INSERT INTO iris VALUES(?, ?, ?, ?, ?)"
+ cur.executemany(stmt, reader)
+
+
+def create_and_load_iris(conn, iris_file: Path, dialect: str):
+ from sqlalchemy import insert
+ from sqlalchemy.engine import Engine
+
+ iris = iris_table_metadata(dialect)
+
+ with iris_file.open(newline=None, encoding="utf-8") as csvfile:
+ reader = csv.reader(csvfile)
+ header = next(reader)
+ params = [dict(zip(header, row)) for row in reader]
+ stmt = insert(iris).values(params)
+ if isinstance(conn, Engine):
+ with conn.connect() as conn:
+ with conn.begin():
+ iris.drop(conn, checkfirst=True)
+ iris.create(bind=conn)
+ conn.execute(stmt)
+ else:
+ with conn.begin():
+ iris.drop(conn, checkfirst=True)
+ iris.create(bind=conn)
+ conn.execute(stmt)
+
+
+def create_and_load_iris_view(conn):
+ stmt = "CREATE VIEW iris_view AS SELECT * FROM iris"
+ if isinstance(conn, sqlite3.Connection):
+ cur = conn.cursor()
+ cur.execute(stmt)
+ else:
+ from sqlalchemy import text
+ from sqlalchemy.engine import Engine
+
+ stmt = text(stmt)
+ if isinstance(conn, Engine):
+ with conn.connect() as conn:
+ with conn.begin():
+ conn.execute(stmt)
+ else:
+ with conn.begin():
+ conn.execute(stmt)
+
+
+def types_table_metadata(dialect: str):
+ from sqlalchemy import (
+ TEXT,
+ Boolean,
+ Column,
+ DateTime,
+ Float,
+ Integer,
+ MetaData,
+ Table,
+ )
+
+ date_type = TEXT if dialect == "sqlite" else DateTime
+ bool_type = Integer if dialect == "sqlite" else Boolean
+ metadata = MetaData()
+ types = Table(
+ "types",
+ metadata,
+ Column("TextCol", TEXT),
+ Column("DateCol", date_type),
+ Column("IntDateCol", Integer),
+ Column("IntDateOnlyCol", Integer),
+ Column("FloatCol", Float),
+ Column("IntCol", Integer),
+ Column("BoolCol", bool_type),
+ Column("IntColWithNull", Integer),
+ Column("BoolColWithNull", bool_type),
+ )
+ if dialect == "postgresql":
+ types.append_column(Column("DateColWithTz", DateTime(timezone=True)))
+ return types
+
+
+def create_and_load_types_sqlite3(conn: sqlite3.Connection, types_data: list[dict]):
+ cur = conn.cursor()
+ stmt = """CREATE TABLE types (
+ "TextCol" TEXT,
+ "DateCol" TEXT,
+ "IntDateCol" INTEGER,
+ "IntDateOnlyCol" INTEGER,
+ "FloatCol" REAL,
+ "IntCol" INTEGER,
+ "BoolCol" INTEGER,
+ "IntColWithNull" INTEGER,
+ "BoolColWithNull" INTEGER
+ )"""
+ cur.execute(stmt)
+
+ stmt = """
+ INSERT INTO types
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """
+ cur.executemany(stmt, types_data)
+
+
+def create_and_load_types(conn, types_data: list[dict], dialect: str):
+ from sqlalchemy import insert
+ from sqlalchemy.engine import Engine
+
+ types = types_table_metadata(dialect)
+
+ stmt = insert(types).values(types_data)
+ if isinstance(conn, Engine):
+ with conn.connect() as conn:
+ with conn.begin():
+ types.drop(conn, checkfirst=True)
+ types.create(bind=conn)
+ conn.execute(stmt)
+ else:
+ with conn.begin():
+ types.drop(conn, checkfirst=True)
+ types.create(bind=conn)
+ conn.execute(stmt)
+
+
+def check_iris_frame(frame: DataFrame):
+ pytype = frame.dtypes.iloc[0].type
+ row = frame.iloc[0]
+ assert issubclass(pytype, np.floating)
+ tm.equalContents(row.values, [5.1, 3.5, 1.4, 0.2, "Iris-setosa"])
+ assert frame.shape in ((150, 5), (8, 5))
+
+
+def count_rows(conn, table_name: str):
+ stmt = f"SELECT count(*) AS count_1 FROM {table_name}"
+ if isinstance(conn, sqlite3.Connection):
+ cur = conn.cursor()
+ return cur.execute(stmt).fetchone()[0]
+ else:
+ from sqlalchemy import create_engine
+ from sqlalchemy.engine import Engine
+
+ if isinstance(conn, str):
+ try:
+ engine = create_engine(conn)
+ with engine.connect() as conn:
+ return conn.exec_driver_sql(stmt).scalar_one()
+ finally:
+ engine.dispose()
+ elif isinstance(conn, Engine):
+ with conn.connect() as conn:
+ return conn.exec_driver_sql(stmt).scalar_one()
+ else:
+ return conn.exec_driver_sql(stmt).scalar_one()
+
+
+@pytest.fixture
+def iris_path(datapath):
+ iris_path = datapath("io", "data", "csv", "iris.csv")
+ return Path(iris_path)
+
+
+@pytest.fixture
+def types_data():
+ return [
+ {
+ "TextCol": "first",
+ "DateCol": "2000-01-03 00:00:00",
+ "IntDateCol": 535852800,
+ "IntDateOnlyCol": 20101010,
+ "FloatCol": 10.10,
+ "IntCol": 1,
+ "BoolCol": False,
+ "IntColWithNull": 1,
+ "BoolColWithNull": False,
+ "DateColWithTz": "2000-01-01 00:00:00-08:00",
+ },
+ {
+ "TextCol": "first",
+ "DateCol": "2000-01-04 00:00:00",
+ "IntDateCol": 1356998400,
+ "IntDateOnlyCol": 20101212,
+ "FloatCol": 10.10,
+ "IntCol": 1,
+ "BoolCol": False,
+ "IntColWithNull": None,
+ "BoolColWithNull": None,
+ "DateColWithTz": "2000-06-01 00:00:00-07:00",
+ },
+ ]
+
+
+@pytest.fixture
+def types_data_frame(types_data):
+ dtypes = {
+ "TextCol": "str",
+ "DateCol": "str",
+ "IntDateCol": "int64",
+ "IntDateOnlyCol": "int64",
+ "FloatCol": "float",
+ "IntCol": "int64",
+ "BoolCol": "int64",
+ "IntColWithNull": "float",
+ "BoolColWithNull": "float",
+ }
+ df = DataFrame(types_data)
+ return df[dtypes.keys()].astype(dtypes)
+
+
+@pytest.fixture
+def test_frame1():
+ columns = ["index", "A", "B", "C", "D"]
+ data = [
+ (
+ "2000-01-03 00:00:00",
+ 0.980268513777,
+ 3.68573087906,
+ -0.364216805298,
+ -1.15973806169,
+ ),
+ (
+ "2000-01-04 00:00:00",
+ 1.04791624281,
+ -0.0412318367011,
+ -0.16181208307,
+ 0.212549316967,
+ ),
+ (
+ "2000-01-05 00:00:00",
+ 0.498580885705,
+ 0.731167677815,
+ -0.537677223318,
+ 1.34627041952,
+ ),
+ (
+ "2000-01-06 00:00:00",
+ 1.12020151869,
+ 1.56762092543,
+ 0.00364077397681,
+ 0.67525259227,
+ ),
+ ]
+ return DataFrame(data, columns=columns)
+
+
+@pytest.fixture
+def test_frame3():
+ columns = ["index", "A", "B"]
+ data = [
+ ("2000-01-03 00:00:00", 2**31 - 1, -1.987670),
+ ("2000-01-04 00:00:00", -29, -0.0412318367011),
+ ("2000-01-05 00:00:00", 20000, 0.731167677815),
+ ("2000-01-06 00:00:00", -290867, 1.56762092543),
+ ]
+ return DataFrame(data, columns=columns)
+
+
+@pytest.fixture
+def mysql_pymysql_engine(iris_path, types_data):
+ sqlalchemy = pytest.importorskip("sqlalchemy")
+ pymysql = pytest.importorskip("pymysql")
+ engine = sqlalchemy.create_engine(
+ "mysql+pymysql://root@localhost:3306/pandas",
+ connect_args={"client_flag": pymysql.constants.CLIENT.MULTI_STATEMENTS},
+ poolclass=sqlalchemy.pool.NullPool,
+ )
+ insp = sqlalchemy.inspect(engine)
+ if not insp.has_table("iris"):
+ create_and_load_iris(engine, iris_path, "mysql")
+ if not insp.has_table("types"):
+ for entry in types_data:
+ entry.pop("DateColWithTz")
+ create_and_load_types(engine, types_data, "mysql")
+ yield engine
+ with engine.connect() as conn:
+ with conn.begin():
+ stmt = sqlalchemy.text("DROP TABLE IF EXISTS test_frame;")
+ conn.execute(stmt)
+ engine.dispose()
+
+
+@pytest.fixture
+def mysql_pymysql_conn(mysql_pymysql_engine):
+ with mysql_pymysql_engine.connect() as conn:
+ yield conn
+
+
+@pytest.fixture
+def postgresql_psycopg2_engine(iris_path, types_data):
+ sqlalchemy = pytest.importorskip("sqlalchemy")
+ pytest.importorskip("psycopg2")
+ engine = sqlalchemy.create_engine(
+ "postgresql+psycopg2://postgres:postgres@localhost:5432/pandas",
+ poolclass=sqlalchemy.pool.NullPool,
+ )
+ insp = sqlalchemy.inspect(engine)
+ if not insp.has_table("iris"):
+ create_and_load_iris(engine, iris_path, "postgresql")
+ if not insp.has_table("types"):
+ create_and_load_types(engine, types_data, "postgresql")
+ yield engine
+ with engine.connect() as conn:
+ with conn.begin():
+ stmt = sqlalchemy.text("DROP TABLE IF EXISTS test_frame;")
+ conn.execute(stmt)
+ engine.dispose()
+
+
+@pytest.fixture
+def postgresql_psycopg2_conn(postgresql_psycopg2_engine):
+ with postgresql_psycopg2_engine.connect() as conn:
+ yield conn
+
+
+@pytest.fixture
+def sqlite_str():
+ pytest.importorskip("sqlalchemy")
+ with tm.ensure_clean() as name:
+ yield "sqlite:///" + name
+
+
+@pytest.fixture
+def sqlite_engine(sqlite_str):
+ sqlalchemy = pytest.importorskip("sqlalchemy")
+ engine = sqlalchemy.create_engine(sqlite_str, poolclass=sqlalchemy.pool.NullPool)
+ yield engine
+ engine.dispose()
+
+
+@pytest.fixture
+def sqlite_conn(sqlite_engine):
+ with sqlite_engine.connect() as conn:
+ yield conn
+
+
+@pytest.fixture
+def sqlite_iris_str(sqlite_str, iris_path):
+ sqlalchemy = pytest.importorskip("sqlalchemy")
+ engine = sqlalchemy.create_engine(sqlite_str)
+ create_and_load_iris(engine, iris_path, "sqlite")
+ engine.dispose()
+ return sqlite_str
+
+
+@pytest.fixture
+def sqlite_iris_engine(sqlite_engine, iris_path):
+ create_and_load_iris(sqlite_engine, iris_path, "sqlite")
+ return sqlite_engine
+
+
+@pytest.fixture
+def sqlite_iris_conn(sqlite_iris_engine):
+ with sqlite_iris_engine.connect() as conn:
+ yield conn
+
+
+@pytest.fixture
+def sqlite_buildin():
+ with contextlib.closing(sqlite3.connect(":memory:")) as closing_conn:
+ with closing_conn as conn:
+ yield conn
+
+
+@pytest.fixture
+def sqlite_buildin_iris(sqlite_buildin, iris_path):
+ create_and_load_iris_sqlite3(sqlite_buildin, iris_path)
+ return sqlite_buildin
+
+
+mysql_connectable = [
+ "mysql_pymysql_engine",
+ "mysql_pymysql_conn",
+]
+
+
+postgresql_connectable = [
+ "postgresql_psycopg2_engine",
+ "postgresql_psycopg2_conn",
+]
+
+sqlite_connectable = [
+ "sqlite_engine",
+ "sqlite_conn",
+ "sqlite_str",
+]
+
+sqlite_iris_connectable = [
+ "sqlite_iris_engine",
+ "sqlite_iris_conn",
+ "sqlite_iris_str",
+]
+
+sqlalchemy_connectable = mysql_connectable + postgresql_connectable + sqlite_connectable
+
+sqlalchemy_connectable_iris = (
+ mysql_connectable + postgresql_connectable + sqlite_iris_connectable
+)
+
+all_connectable = sqlalchemy_connectable + ["sqlite_buildin"]
+
+all_connectable_iris = sqlalchemy_connectable_iris + ["sqlite_buildin_iris"]
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", all_connectable)
+def test_dataframe_to_sql(conn, test_frame1, request):
+ # GH 51086 if conn is sqlite_engine
+ conn = request.getfixturevalue(conn)
+ test_frame1.to_sql(name="test", con=conn, if_exists="append", index=False)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", all_connectable)
+def test_dataframe_to_sql_arrow_dtypes(conn, request):
+ # GH 52046
+ pytest.importorskip("pyarrow")
+ df = DataFrame(
+ {
+ "int": pd.array([1], dtype="int8[pyarrow]"),
+ "datetime": pd.array(
+ [datetime(2023, 1, 1)], dtype="timestamp[ns][pyarrow]"
+ ),
+ "date": pd.array([date(2023, 1, 1)], dtype="date32[day][pyarrow]"),
+ "timedelta": pd.array([timedelta(1)], dtype="duration[ns][pyarrow]"),
+ "string": pd.array(["a"], dtype="string[pyarrow]"),
+ }
+ )
+ conn = request.getfixturevalue(conn)
+ with tm.assert_produces_warning(UserWarning, match="the 'timedelta'"):
+ df.to_sql(name="test_arrow", con=conn, if_exists="replace", index=False)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", all_connectable)
+def test_dataframe_to_sql_arrow_dtypes_missing(conn, request, nulls_fixture):
+ # GH 52046
+ pytest.importorskip("pyarrow")
+ df = DataFrame(
+ {
+ "datetime": pd.array(
+ [datetime(2023, 1, 1), nulls_fixture], dtype="timestamp[ns][pyarrow]"
+ ),
+ }
+ )
+ conn = request.getfixturevalue(conn)
+ df.to_sql(name="test_arrow", con=conn, if_exists="replace", index=False)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", all_connectable)
+@pytest.mark.parametrize("method", [None, "multi"])
+def test_to_sql(conn, method, test_frame1, request):
+ conn = request.getfixturevalue(conn)
+ with pandasSQL_builder(conn, need_transaction=True) as pandasSQL:
+ pandasSQL.to_sql(test_frame1, "test_frame", method=method)
+ assert pandasSQL.has_table("test_frame")
+ assert count_rows(conn, "test_frame") == len(test_frame1)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", all_connectable)
+@pytest.mark.parametrize("mode, num_row_coef", [("replace", 1), ("append", 2)])
+def test_to_sql_exist(conn, mode, num_row_coef, test_frame1, request):
+ conn = request.getfixturevalue(conn)
+ with pandasSQL_builder(conn, need_transaction=True) as pandasSQL:
+ pandasSQL.to_sql(test_frame1, "test_frame", if_exists="fail")
+ pandasSQL.to_sql(test_frame1, "test_frame", if_exists=mode)
+ assert pandasSQL.has_table("test_frame")
+ assert count_rows(conn, "test_frame") == num_row_coef * len(test_frame1)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", all_connectable)
+def test_to_sql_exist_fail(conn, test_frame1, request):
+ conn = request.getfixturevalue(conn)
+ with pandasSQL_builder(conn, need_transaction=True) as pandasSQL:
+ pandasSQL.to_sql(test_frame1, "test_frame", if_exists="fail")
+ assert pandasSQL.has_table("test_frame")
+
+ msg = "Table 'test_frame' already exists"
+ with pytest.raises(ValueError, match=msg):
+ pandasSQL.to_sql(test_frame1, "test_frame", if_exists="fail")
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", all_connectable_iris)
+def test_read_iris_query(conn, request):
+ conn = request.getfixturevalue(conn)
+ iris_frame = read_sql_query("SELECT * FROM iris", conn)
+ check_iris_frame(iris_frame)
+ iris_frame = pd.read_sql("SELECT * FROM iris", conn)
+ check_iris_frame(iris_frame)
+ iris_frame = pd.read_sql("SELECT * FROM iris where 0=1", conn)
+ assert iris_frame.shape == (0, 5)
+ assert "SepalWidth" in iris_frame.columns
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", all_connectable_iris)
+def test_read_iris_query_chunksize(conn, request):
+ conn = request.getfixturevalue(conn)
+ iris_frame = concat(read_sql_query("SELECT * FROM iris", conn, chunksize=7))
+ check_iris_frame(iris_frame)
+ iris_frame = concat(pd.read_sql("SELECT * FROM iris", conn, chunksize=7))
+ check_iris_frame(iris_frame)
+ iris_frame = concat(pd.read_sql("SELECT * FROM iris where 0=1", conn, chunksize=7))
+ assert iris_frame.shape == (0, 5)
+ assert "SepalWidth" in iris_frame.columns
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", sqlalchemy_connectable_iris)
+def test_read_iris_query_expression_with_parameter(conn, request):
+ conn = request.getfixturevalue(conn)
+ from sqlalchemy import (
+ MetaData,
+ Table,
+ create_engine,
+ select,
+ )
+
+ metadata = MetaData()
+ autoload_con = create_engine(conn) if isinstance(conn, str) else conn
+ iris = Table("iris", metadata, autoload_with=autoload_con)
+ iris_frame = read_sql_query(
+ select(iris), conn, params={"name": "Iris-setosa", "length": 5.1}
+ )
+ check_iris_frame(iris_frame)
+ if isinstance(conn, str):
+ autoload_con.dispose()
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", all_connectable_iris)
+def test_read_iris_query_string_with_parameter(conn, request, sql_strings):
+ for db, query in sql_strings["read_parameters"].items():
+ if db in conn:
+ break
+ else:
+ raise KeyError(f"No part of {conn} found in sql_strings['read_parameters']")
+ conn = request.getfixturevalue(conn)
+ iris_frame = read_sql_query(query, conn, params=("Iris-setosa", 5.1))
+ check_iris_frame(iris_frame)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", sqlalchemy_connectable_iris)
+def test_read_iris_table(conn, request):
+ # GH 51015 if conn = sqlite_iris_str
+ conn = request.getfixturevalue(conn)
+ iris_frame = read_sql_table("iris", conn)
+ check_iris_frame(iris_frame)
+ iris_frame = pd.read_sql("iris", conn)
+ check_iris_frame(iris_frame)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", sqlalchemy_connectable_iris)
+def test_read_iris_table_chunksize(conn, request):
+ conn = request.getfixturevalue(conn)
+ iris_frame = concat(read_sql_table("iris", conn, chunksize=7))
+ check_iris_frame(iris_frame)
+ iris_frame = concat(pd.read_sql("iris", conn, chunksize=7))
+ check_iris_frame(iris_frame)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", sqlalchemy_connectable)
+def test_to_sql_callable(conn, test_frame1, request):
+ conn = request.getfixturevalue(conn)
+
+ check = [] # used to double check function below is really being used
+
+ def sample(pd_table, conn, keys, data_iter):
+ check.append(1)
+ data = [dict(zip(keys, row)) for row in data_iter]
+ conn.execute(pd_table.table.insert(), data)
+
+ with pandasSQL_builder(conn, need_transaction=True) as pandasSQL:
+ pandasSQL.to_sql(test_frame1, "test_frame", method=sample)
+ assert pandasSQL.has_table("test_frame")
+ assert check == [1]
+ assert count_rows(conn, "test_frame") == len(test_frame1)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", mysql_connectable)
+def test_default_type_conversion(conn, request):
+ conn = request.getfixturevalue(conn)
+ df = sql.read_sql_table("types", conn)
+
+ assert issubclass(df.FloatCol.dtype.type, np.floating)
+ assert issubclass(df.IntCol.dtype.type, np.integer)
+
+ # MySQL has no real BOOL type (it's an alias for TINYINT)
+ assert issubclass(df.BoolCol.dtype.type, np.integer)
+
+ # Int column with NA values stays as float
+ assert issubclass(df.IntColWithNull.dtype.type, np.floating)
+
+ # Bool column with NA = int column with NA values => becomes float
+ assert issubclass(df.BoolColWithNull.dtype.type, np.floating)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", mysql_connectable)
+def test_read_procedure(conn, request):
+ conn = request.getfixturevalue(conn)
+
+ # GH 7324
+ # Although it is more an api test, it is added to the
+ # mysql tests as sqlite does not have stored procedures
+ from sqlalchemy import text
+ from sqlalchemy.engine import Engine
+
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
+ df.to_sql(name="test_frame", con=conn, index=False)
+
+ proc = """DROP PROCEDURE IF EXISTS get_testdb;
+
+ CREATE PROCEDURE get_testdb ()
+
+ BEGIN
+ SELECT * FROM test_frame;
+ END"""
+ proc = text(proc)
+ if isinstance(conn, Engine):
+ with conn.connect() as engine_conn:
+ with engine_conn.begin():
+ engine_conn.execute(proc)
+ else:
+ with conn.begin():
+ conn.execute(proc)
+
+ res1 = sql.read_sql_query("CALL get_testdb();", conn)
+ tm.assert_frame_equal(df, res1)
+
+ # test delegation to read_sql_query
+ res2 = sql.read_sql("CALL get_testdb();", conn)
+ tm.assert_frame_equal(df, res2)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", postgresql_connectable)
+@pytest.mark.parametrize("expected_count", [2, "Success!"])
+def test_copy_from_callable_insertion_method(conn, expected_count, request):
+ # GH 8953
+ # Example in io.rst found under _io.sql.method
+ # not available in sqlite, mysql
+ def psql_insert_copy(table, conn, keys, data_iter):
+ # gets a DBAPI connection that can provide a cursor
+ dbapi_conn = conn.connection
+ with dbapi_conn.cursor() as cur:
+ s_buf = StringIO()
+ writer = csv.writer(s_buf)
+ writer.writerows(data_iter)
+ s_buf.seek(0)
+
+ columns = ", ".join([f'"{k}"' for k in keys])
+ if table.schema:
+ table_name = f"{table.schema}.{table.name}"
+ else:
+ table_name = table.name
+
+ sql_query = f"COPY {table_name} ({columns}) FROM STDIN WITH CSV"
+ cur.copy_expert(sql=sql_query, file=s_buf)
+ return expected_count
+
+ conn = request.getfixturevalue(conn)
+ expected = DataFrame({"col1": [1, 2], "col2": [0.1, 0.2], "col3": ["a", "n"]})
+ result_count = expected.to_sql(
+ name="test_frame", con=conn, index=False, method=psql_insert_copy
+ )
+ # GH 46891
+ if expected_count is None:
+ assert result_count is None
+ else:
+ assert result_count == expected_count
+ result = sql.read_sql_table("test_frame", conn)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", postgresql_connectable)
+def test_insertion_method_on_conflict_do_nothing(conn, request):
+ # GH 15988: Example in to_sql docstring
+ conn = request.getfixturevalue(conn)
+
+ from sqlalchemy.dialects.postgresql import insert
+ from sqlalchemy.engine import Engine
+ from sqlalchemy.sql import text
+
+ def insert_on_conflict(table, conn, keys, data_iter):
+ data = [dict(zip(keys, row)) for row in data_iter]
+ stmt = (
+ insert(table.table)
+ .values(data)
+ .on_conflict_do_nothing(index_elements=["a"])
+ )
+ result = conn.execute(stmt)
+ return result.rowcount
+
+ create_sql = text(
+ """
+ CREATE TABLE test_insert_conflict (
+ a integer PRIMARY KEY,
+ b numeric,
+ c text
+ );
+ """
+ )
+ if isinstance(conn, Engine):
+ with conn.connect() as con:
+ with con.begin():
+ con.execute(create_sql)
+ else:
+ with conn.begin():
+ conn.execute(create_sql)
+
+ expected = DataFrame([[1, 2.1, "a"]], columns=list("abc"))
+ expected.to_sql(
+ name="test_insert_conflict", con=conn, if_exists="append", index=False
+ )
+
+ df_insert = DataFrame([[1, 3.2, "b"]], columns=list("abc"))
+ inserted = df_insert.to_sql(
+ name="test_insert_conflict",
+ con=conn,
+ index=False,
+ if_exists="append",
+ method=insert_on_conflict,
+ )
+ result = sql.read_sql_table("test_insert_conflict", conn)
+ tm.assert_frame_equal(result, expected)
+ assert inserted == 0
+
+ # Cleanup
+ with sql.SQLDatabase(conn, need_transaction=True) as pandasSQL:
+ pandasSQL.drop_table("test_insert_conflict")
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", mysql_connectable)
+def test_insertion_method_on_conflict_update(conn, request):
+ # GH 14553: Example in to_sql docstring
+ conn = request.getfixturevalue(conn)
+
+ from sqlalchemy.dialects.mysql import insert
+ from sqlalchemy.engine import Engine
+ from sqlalchemy.sql import text
+
+ def insert_on_conflict(table, conn, keys, data_iter):
+ data = [dict(zip(keys, row)) for row in data_iter]
+ stmt = insert(table.table).values(data)
+ stmt = stmt.on_duplicate_key_update(b=stmt.inserted.b, c=stmt.inserted.c)
+ result = conn.execute(stmt)
+ return result.rowcount
+
+ create_sql = text(
+ """
+ CREATE TABLE test_insert_conflict (
+ a INT PRIMARY KEY,
+ b FLOAT,
+ c VARCHAR(10)
+ );
+ """
+ )
+ if isinstance(conn, Engine):
+ with conn.connect() as con:
+ with con.begin():
+ con.execute(create_sql)
+ else:
+ with conn.begin():
+ conn.execute(create_sql)
+
+ df = DataFrame([[1, 2.1, "a"]], columns=list("abc"))
+ df.to_sql(name="test_insert_conflict", con=conn, if_exists="append", index=False)
+
+ expected = DataFrame([[1, 3.2, "b"]], columns=list("abc"))
+ inserted = expected.to_sql(
+ name="test_insert_conflict",
+ con=conn,
+ index=False,
+ if_exists="append",
+ method=insert_on_conflict,
+ )
+ result = sql.read_sql_table("test_insert_conflict", conn)
+ tm.assert_frame_equal(result, expected)
+ assert inserted == 2
+
+ # Cleanup
+ with sql.SQLDatabase(conn, need_transaction=True) as pandasSQL:
+ pandasSQL.drop_table("test_insert_conflict")
+
+
+@pytest.mark.db
+@pytest.mark.parametrize("conn", postgresql_connectable)
+def test_read_view_postgres(conn, request):
+ # GH 52969
+ conn = request.getfixturevalue(conn)
+
+ from sqlalchemy.engine import Engine
+ from sqlalchemy.sql import text
+
+ table_name = f"group_{uuid.uuid4().hex}"
+ view_name = f"group_view_{uuid.uuid4().hex}"
+
+ sql_stmt = text(
+ f"""
+ CREATE TABLE {table_name} (
+ group_id INTEGER,
+ name TEXT
+ );
+ INSERT INTO {table_name} VALUES
+ (1, 'name');
+ CREATE VIEW {view_name}
+ AS
+ SELECT * FROM {table_name};
+ """
+ )
+ if isinstance(conn, Engine):
+ with conn.connect() as con:
+ with con.begin():
+ con.execute(sql_stmt)
+ else:
+ with conn.begin():
+ conn.execute(sql_stmt)
+ result = read_sql_table(view_name, conn)
+ expected = DataFrame({"group_id": [1], "name": "name"})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_read_view_sqlite(sqlite_buildin):
+ # GH 52969
+ create_table = """
+CREATE TABLE groups (
+ group_id INTEGER,
+ name TEXT
+);
+"""
+ insert_into = """
+INSERT INTO groups VALUES
+ (1, 'name');
+"""
+ create_view = """
+CREATE VIEW group_view
+AS
+SELECT * FROM groups;
+"""
+ sqlite_buildin.execute(create_table)
+ sqlite_buildin.execute(insert_into)
+ sqlite_buildin.execute(create_view)
+ result = pd.read_sql("SELECT * FROM group_view", sqlite_buildin)
+ expected = DataFrame({"group_id": [1], "name": "name"})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_execute_typeerror(sqlite_iris_engine):
+ with pytest.raises(TypeError, match="pandas.io.sql.execute requires a connection"):
+ with tm.assert_produces_warning(
+ FutureWarning,
+ match="`pandas.io.sql.execute` is deprecated and "
+ "will be removed in the future version.",
+ ):
+ sql.execute("select * from iris", sqlite_iris_engine)
+
+
+def test_execute_deprecated(sqlite_buildin_iris):
+ # GH50185
+ with tm.assert_produces_warning(
+ FutureWarning,
+ match="`pandas.io.sql.execute` is deprecated and "
+ "will be removed in the future version.",
+ ):
+ sql.execute("select * from iris", sqlite_buildin_iris)
+
+
+class MixInBase:
+ def teardown_method(self):
+ # if setup fails, there may not be a connection to close.
+ if hasattr(self, "conn"):
+ self.conn.close()
+ # use a fresh connection to ensure we can drop all tables.
+ try:
+ conn = self.connect()
+ except (sqlalchemy.exc.OperationalError, sqlite3.OperationalError):
+ pass
+ else:
+ with conn:
+ for view in self._get_all_views(conn):
+ self.drop_view(view, conn)
+ for tbl in self._get_all_tables(conn):
+ self.drop_table(tbl, conn)
+
+
+class SQLiteMixIn(MixInBase):
+ def connect(self):
+ return sqlite3.connect(":memory:")
+
+ def drop_table(self, table_name, conn):
+ conn.execute(f"DROP TABLE IF EXISTS {sql._get_valid_sqlite_name(table_name)}")
+ conn.commit()
+
+ def _get_all_tables(self, conn):
+ c = conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
+ return [table[0] for table in c.fetchall()]
+
+ def drop_view(self, view_name, conn):
+ conn.execute(f"DROP VIEW IF EXISTS {sql._get_valid_sqlite_name(view_name)}")
+ conn.commit()
+
+ def _get_all_views(self, conn):
+ c = conn.execute("SELECT name FROM sqlite_master WHERE type='view'")
+ return [view[0] for view in c.fetchall()]
+
+
+class SQLAlchemyMixIn(MixInBase):
+ @classmethod
+ def teardown_class(cls):
+ cls.engine.dispose()
+
+ def connect(self):
+ return self.engine.connect()
+
+ def drop_table(self, table_name, conn):
+ if conn.in_transaction():
+ conn.get_transaction().rollback()
+ with conn.begin():
+ sql.SQLDatabase(conn).drop_table(table_name)
+
+ def _get_all_tables(self, conn):
+ from sqlalchemy import inspect
+
+ return inspect(conn).get_table_names()
+
+ def drop_view(self, view_name, conn):
+ quoted_view = conn.engine.dialect.identifier_preparer.quote_identifier(
+ view_name
+ )
+ if conn.in_transaction():
+ conn.get_transaction().rollback()
+ with conn.begin():
+ conn.exec_driver_sql(f"DROP VIEW IF EXISTS {quoted_view}")
+
+ def _get_all_views(self, conn):
+ from sqlalchemy import inspect
+
+ return inspect(conn).get_view_names()
+
+
+class PandasSQLTest:
+ """
+ Base class with common private methods for SQLAlchemy and fallback cases.
+
+ """
+
+ def load_iris_data(self, iris_path):
+ self.drop_table("iris", self.conn)
+ if isinstance(self.conn, sqlite3.Connection):
+ create_and_load_iris_sqlite3(self.conn, iris_path)
+ else:
+ create_and_load_iris(self.conn, iris_path, self.flavor)
+
+ def load_types_data(self, types_data):
+ if self.flavor != "postgresql":
+ for entry in types_data:
+ entry.pop("DateColWithTz")
+ if isinstance(self.conn, sqlite3.Connection):
+ types_data = [tuple(entry.values()) for entry in types_data]
+ create_and_load_types_sqlite3(self.conn, types_data)
+ else:
+ create_and_load_types(self.conn, types_data, self.flavor)
+
+ def _read_sql_iris_parameter(self, sql_strings):
+ query = sql_strings["read_parameters"][self.flavor]
+ params = ("Iris-setosa", 5.1)
+ iris_frame = self.pandasSQL.read_query(query, params=params)
+ check_iris_frame(iris_frame)
+
+ def _read_sql_iris_named_parameter(self, sql_strings):
+ query = sql_strings["read_named_parameters"][self.flavor]
+ params = {"name": "Iris-setosa", "length": 5.1}
+ iris_frame = self.pandasSQL.read_query(query, params=params)
+ check_iris_frame(iris_frame)
+
+ def _read_sql_iris_no_parameter_with_percent(self, sql_strings):
+ query = sql_strings["read_no_parameters_with_percent"][self.flavor]
+ iris_frame = self.pandasSQL.read_query(query, params=None)
+ check_iris_frame(iris_frame)
+
+ def _to_sql_empty(self, test_frame1):
+ self.drop_table("test_frame1", self.conn)
+ assert self.pandasSQL.to_sql(test_frame1.iloc[:0], "test_frame1") == 0
+
+ def _to_sql_with_sql_engine(self, test_frame1, engine="auto", **engine_kwargs):
+ """`to_sql` with the `engine` param"""
+ # mostly copied from this class's `_to_sql()` method
+ self.drop_table("test_frame1", self.conn)
+
+ assert (
+ self.pandasSQL.to_sql(
+ test_frame1, "test_frame1", engine=engine, **engine_kwargs
+ )
+ == 4
+ )
+ assert self.pandasSQL.has_table("test_frame1")
+
+ num_entries = len(test_frame1)
+ num_rows = count_rows(self.conn, "test_frame1")
+ assert num_rows == num_entries
+
+ # Nuke table
+ self.drop_table("test_frame1", self.conn)
+
+ def _roundtrip(self, test_frame1):
+ self.drop_table("test_frame_roundtrip", self.conn)
+ assert self.pandasSQL.to_sql(test_frame1, "test_frame_roundtrip") == 4
+ result = self.pandasSQL.read_query("SELECT * FROM test_frame_roundtrip")
+
+ result.set_index("level_0", inplace=True)
+ # result.index.astype(int)
+
+ result.index.name = None
+
+ tm.assert_frame_equal(result, test_frame1)
+
+ def _execute_sql(self):
+ # drop_sql = "DROP TABLE IF EXISTS test" # should already be done
+ iris_results = self.pandasSQL.execute("SELECT * FROM iris")
+ row = iris_results.fetchone()
+ tm.equalContents(row, [5.1, 3.5, 1.4, 0.2, "Iris-setosa"])
+
+ def _to_sql_save_index(self):
+ df = DataFrame.from_records(
+ [(1, 2.1, "line1"), (2, 1.5, "line2")], columns=["A", "B", "C"], index=["A"]
+ )
+ assert self.pandasSQL.to_sql(df, "test_to_sql_saves_index") == 2
+ ix_cols = self._get_index_columns("test_to_sql_saves_index")
+ assert ix_cols == [["A"]]
+
+ def _transaction_test(self):
+ with self.pandasSQL.run_transaction() as trans:
+ stmt = "CREATE TABLE test_trans (A INT, B TEXT)"
+ if isinstance(self.pandasSQL, SQLiteDatabase):
+ trans.execute(stmt)
+ else:
+ from sqlalchemy import text
+
+ stmt = text(stmt)
+ trans.execute(stmt)
+
+ class DummyException(Exception):
+ pass
+
+ # Make sure when transaction is rolled back, no rows get inserted
+ ins_sql = "INSERT INTO test_trans (A,B) VALUES (1, 'blah')"
+ if isinstance(self.pandasSQL, SQLDatabase):
+ from sqlalchemy import text
+
+ ins_sql = text(ins_sql)
+ try:
+ with self.pandasSQL.run_transaction() as trans:
+ trans.execute(ins_sql)
+ raise DummyException("error")
+ except DummyException:
+ # ignore raised exception
+ pass
+ res = self.pandasSQL.read_query("SELECT * FROM test_trans")
+ assert len(res) == 0
+
+ # Make sure when transaction is committed, rows do get inserted
+ with self.pandasSQL.run_transaction() as trans:
+ trans.execute(ins_sql)
+ res2 = self.pandasSQL.read_query("SELECT * FROM test_trans")
+ assert len(res2) == 1
+
+
+# -----------------------------------------------------------------------------
+# -- Testing the public API
+
+
+class _TestSQLApi(PandasSQLTest):
+ """
+ Base class to test the public API.
+
+ From this two classes are derived to run these tests for both the
+ sqlalchemy mode (`TestSQLApi`) and the fallback mode
+ (`TestSQLiteFallbackApi`). These tests are run with sqlite3. Specific
+ tests for the different sql flavours are included in `_TestSQLAlchemy`.
+
+ Notes:
+ flavor can always be passed even in SQLAlchemy mode,
+ should be correctly ignored.
+
+ we don't use drop_table because that isn't part of the public api
+
+ """
+
+ flavor = "sqlite"
+ mode: str
+
+ @pytest.fixture(autouse=True)
+ def setup_method(self, iris_path, types_data):
+ self.conn = self.connect()
+ self.load_iris_data(iris_path)
+ self.load_types_data(types_data)
+ self.load_test_data_and_sql()
+
+ def load_test_data_and_sql(self):
+ create_and_load_iris_view(self.conn)
+
+ def test_read_sql_view(self):
+ iris_frame = sql.read_sql_query("SELECT * FROM iris_view", self.conn)
+ check_iris_frame(iris_frame)
+
+ def test_read_sql_with_chunksize_no_result(self):
+ query = "SELECT * FROM iris_view WHERE SepalLength < 0.0"
+ with_batch = sql.read_sql_query(query, self.conn, chunksize=5)
+ without_batch = sql.read_sql_query(query, self.conn)
+ tm.assert_frame_equal(concat(with_batch), without_batch)
+
+ def test_to_sql(self, test_frame1):
+ sql.to_sql(test_frame1, "test_frame1", self.conn)
+ assert sql.has_table("test_frame1", self.conn)
+
+ def test_to_sql_fail(self, test_frame1):
+ sql.to_sql(test_frame1, "test_frame2", self.conn, if_exists="fail")
+ assert sql.has_table("test_frame2", self.conn)
+
+ msg = "Table 'test_frame2' already exists"
+ with pytest.raises(ValueError, match=msg):
+ sql.to_sql(test_frame1, "test_frame2", self.conn, if_exists="fail")
+
+ def test_to_sql_replace(self, test_frame1):
+ sql.to_sql(test_frame1, "test_frame3", self.conn, if_exists="fail")
+ # Add to table again
+ sql.to_sql(test_frame1, "test_frame3", self.conn, if_exists="replace")
+ assert sql.has_table("test_frame3", self.conn)
+
+ num_entries = len(test_frame1)
+ num_rows = count_rows(self.conn, "test_frame3")
+
+ assert num_rows == num_entries
+
+ def test_to_sql_append(self, test_frame1):
+ assert sql.to_sql(test_frame1, "test_frame4", self.conn, if_exists="fail") == 4
+
+ # Add to table again
+ assert (
+ sql.to_sql(test_frame1, "test_frame4", self.conn, if_exists="append") == 4
+ )
+ assert sql.has_table("test_frame4", self.conn)
+
+ num_entries = 2 * len(test_frame1)
+ num_rows = count_rows(self.conn, "test_frame4")
+
+ assert num_rows == num_entries
+
+ def test_to_sql_type_mapping(self, test_frame3):
+ sql.to_sql(test_frame3, "test_frame5", self.conn, index=False)
+ result = sql.read_sql("SELECT * FROM test_frame5", self.conn)
+
+ tm.assert_frame_equal(test_frame3, result)
+
+ def test_to_sql_series(self):
+ s = Series(np.arange(5, dtype="int64"), name="series")
+ sql.to_sql(s, "test_series", self.conn, index=False)
+ s2 = sql.read_sql_query("SELECT * FROM test_series", self.conn)
+ tm.assert_frame_equal(s.to_frame(), s2)
+
+ def test_roundtrip(self, test_frame1):
+ sql.to_sql(test_frame1, "test_frame_roundtrip", con=self.conn)
+ result = sql.read_sql_query("SELECT * FROM test_frame_roundtrip", con=self.conn)
+
+ # HACK!
+ result.index = test_frame1.index
+ result.set_index("level_0", inplace=True)
+ result.index.astype(int)
+ result.index.name = None
+ tm.assert_frame_equal(result, test_frame1)
+
+ def test_roundtrip_chunksize(self, test_frame1):
+ sql.to_sql(
+ test_frame1,
+ "test_frame_roundtrip",
+ con=self.conn,
+ index=False,
+ chunksize=2,
+ )
+ result = sql.read_sql_query("SELECT * FROM test_frame_roundtrip", con=self.conn)
+ tm.assert_frame_equal(result, test_frame1)
+
+ def test_execute_sql(self):
+ # drop_sql = "DROP TABLE IF EXISTS test" # should already be done
+ with sql.pandasSQL_builder(self.conn) as pandas_sql:
+ iris_results = pandas_sql.execute("SELECT * FROM iris")
+ row = iris_results.fetchone()
+ tm.equalContents(row, [5.1, 3.5, 1.4, 0.2, "Iris-setosa"])
+
+ def test_date_parsing(self):
+ # Test date parsing in read_sql
+ # No Parsing
+ df = sql.read_sql_query("SELECT * FROM types", self.conn)
+ assert not issubclass(df.DateCol.dtype.type, np.datetime64)
+
+ df = sql.read_sql_query(
+ "SELECT * FROM types", self.conn, parse_dates=["DateCol"]
+ )
+ assert issubclass(df.DateCol.dtype.type, np.datetime64)
+ assert df.DateCol.tolist() == [
+ Timestamp(2000, 1, 3, 0, 0, 0),
+ Timestamp(2000, 1, 4, 0, 0, 0),
+ ]
+
+ df = sql.read_sql_query(
+ "SELECT * FROM types",
+ self.conn,
+ parse_dates={"DateCol": "%Y-%m-%d %H:%M:%S"},
+ )
+ assert issubclass(df.DateCol.dtype.type, np.datetime64)
+ assert df.DateCol.tolist() == [
+ Timestamp(2000, 1, 3, 0, 0, 0),
+ Timestamp(2000, 1, 4, 0, 0, 0),
+ ]
+
+ df = sql.read_sql_query(
+ "SELECT * FROM types", self.conn, parse_dates=["IntDateCol"]
+ )
+ assert issubclass(df.IntDateCol.dtype.type, np.datetime64)
+ assert df.IntDateCol.tolist() == [
+ Timestamp(1986, 12, 25, 0, 0, 0),
+ Timestamp(2013, 1, 1, 0, 0, 0),
+ ]
+
+ df = sql.read_sql_query(
+ "SELECT * FROM types", self.conn, parse_dates={"IntDateCol": "s"}
+ )
+ assert issubclass(df.IntDateCol.dtype.type, np.datetime64)
+ assert df.IntDateCol.tolist() == [
+ Timestamp(1986, 12, 25, 0, 0, 0),
+ Timestamp(2013, 1, 1, 0, 0, 0),
+ ]
+
+ df = sql.read_sql_query(
+ "SELECT * FROM types",
+ self.conn,
+ parse_dates={"IntDateOnlyCol": "%Y%m%d"},
+ )
+ assert issubclass(df.IntDateOnlyCol.dtype.type, np.datetime64)
+ assert df.IntDateOnlyCol.tolist() == [
+ Timestamp("2010-10-10"),
+ Timestamp("2010-12-12"),
+ ]
+
+ @pytest.mark.parametrize("error", ["ignore", "raise", "coerce"])
+ @pytest.mark.parametrize(
+ "read_sql, text, mode",
+ [
+ (sql.read_sql, "SELECT * FROM types", ("sqlalchemy", "fallback")),
+ (sql.read_sql, "types", ("sqlalchemy")),
+ (
+ sql.read_sql_query,
+ "SELECT * FROM types",
+ ("sqlalchemy", "fallback"),
+ ),
+ (sql.read_sql_table, "types", ("sqlalchemy")),
+ ],
+ )
+ def test_custom_dateparsing_error(
+ self, read_sql, text, mode, error, types_data_frame
+ ):
+ if self.mode in mode:
+ expected = types_data_frame.astype({"DateCol": "datetime64[ns]"})
+
+ result = read_sql(
+ text,
+ con=self.conn,
+ parse_dates={
+ "DateCol": {"errors": error},
+ },
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_date_and_index(self):
+ # Test case where same column appears in parse_date and index_col
+
+ df = sql.read_sql_query(
+ "SELECT * FROM types",
+ self.conn,
+ index_col="DateCol",
+ parse_dates=["DateCol", "IntDateCol"],
+ )
+
+ assert issubclass(df.index.dtype.type, np.datetime64)
+ assert issubclass(df.IntDateCol.dtype.type, np.datetime64)
+
+ def test_timedelta(self):
+ # see #6921
+ df = to_timedelta(Series(["00:00:01", "00:00:03"], name="foo")).to_frame()
+ with tm.assert_produces_warning(UserWarning):
+ result_count = df.to_sql(name="test_timedelta", con=self.conn)
+ assert result_count == 2
+ result = sql.read_sql_query("SELECT * FROM test_timedelta", self.conn)
+ tm.assert_series_equal(result["foo"], df["foo"].view("int64"))
+
+ def test_complex_raises(self):
+ df = DataFrame({"a": [1 + 1j, 2j]})
+ msg = "Complex datatypes not supported"
+ with pytest.raises(ValueError, match=msg):
+ assert df.to_sql("test_complex", con=self.conn) is None
+
+ @pytest.mark.parametrize(
+ "index_name,index_label,expected",
+ [
+ # no index name, defaults to 'index'
+ (None, None, "index"),
+ # specifying index_label
+ (None, "other_label", "other_label"),
+ # using the index name
+ ("index_name", None, "index_name"),
+ # has index name, but specifying index_label
+ ("index_name", "other_label", "other_label"),
+ # index name is integer
+ (0, None, "0"),
+ # index name is None but index label is integer
+ (None, 0, "0"),
+ ],
+ )
+ def test_to_sql_index_label(self, index_name, index_label, expected):
+ temp_frame = DataFrame({"col1": range(4)})
+ temp_frame.index.name = index_name
+ query = "SELECT * FROM test_index_label"
+ sql.to_sql(temp_frame, "test_index_label", self.conn, index_label=index_label)
+ frame = sql.read_sql_query(query, self.conn)
+ assert frame.columns[0] == expected
+
+ def test_to_sql_index_label_multiindex(self):
+ expected_row_count = 4
+ temp_frame = DataFrame(
+ {"col1": range(4)},
+ index=MultiIndex.from_product([("A0", "A1"), ("B0", "B1")]),
+ )
+
+ # no index name, defaults to 'level_0' and 'level_1'
+ result = sql.to_sql(temp_frame, "test_index_label", self.conn)
+ assert result == expected_row_count
+ frame = sql.read_sql_query("SELECT * FROM test_index_label", self.conn)
+ assert frame.columns[0] == "level_0"
+ assert frame.columns[1] == "level_1"
+
+ # specifying index_label
+ result = sql.to_sql(
+ temp_frame,
+ "test_index_label",
+ self.conn,
+ if_exists="replace",
+ index_label=["A", "B"],
+ )
+ assert result == expected_row_count
+ frame = sql.read_sql_query("SELECT * FROM test_index_label", self.conn)
+ assert frame.columns[:2].tolist() == ["A", "B"]
+
+ # using the index name
+ temp_frame.index.names = ["A", "B"]
+ result = sql.to_sql(
+ temp_frame, "test_index_label", self.conn, if_exists="replace"
+ )
+ assert result == expected_row_count
+ frame = sql.read_sql_query("SELECT * FROM test_index_label", self.conn)
+ assert frame.columns[:2].tolist() == ["A", "B"]
+
+ # has index name, but specifying index_label
+ result = sql.to_sql(
+ temp_frame,
+ "test_index_label",
+ self.conn,
+ if_exists="replace",
+ index_label=["C", "D"],
+ )
+ assert result == expected_row_count
+ frame = sql.read_sql_query("SELECT * FROM test_index_label", self.conn)
+ assert frame.columns[:2].tolist() == ["C", "D"]
+
+ msg = "Length of 'index_label' should match number of levels, which is 2"
+ with pytest.raises(ValueError, match=msg):
+ sql.to_sql(
+ temp_frame,
+ "test_index_label",
+ self.conn,
+ if_exists="replace",
+ index_label="C",
+ )
+
+ def test_multiindex_roundtrip(self):
+ df = DataFrame.from_records(
+ [(1, 2.1, "line1"), (2, 1.5, "line2")],
+ columns=["A", "B", "C"],
+ index=["A", "B"],
+ )
+
+ df.to_sql(name="test_multiindex_roundtrip", con=self.conn)
+ result = sql.read_sql_query(
+ "SELECT * FROM test_multiindex_roundtrip", self.conn, index_col=["A", "B"]
+ )
+ tm.assert_frame_equal(df, result, check_index_type=True)
+
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ None,
+ int,
+ float,
+ {"A": int, "B": float},
+ ],
+ )
+ def test_dtype_argument(self, dtype):
+ # GH10285 Add dtype argument to read_sql_query
+ df = DataFrame([[1.2, 3.4], [5.6, 7.8]], columns=["A", "B"])
+ assert df.to_sql(name="test_dtype_argument", con=self.conn) == 2
+
+ expected = df.astype(dtype)
+ result = sql.read_sql_query(
+ "SELECT A, B FROM test_dtype_argument", con=self.conn, dtype=dtype
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_integer_col_names(self):
+ df = DataFrame([[1, 2], [3, 4]], columns=[0, 1])
+ sql.to_sql(df, "test_frame_integer_col_names", self.conn, if_exists="replace")
+
+ def test_get_schema(self, test_frame1):
+ create_sql = sql.get_schema(test_frame1, "test", con=self.conn)
+ assert "CREATE" in create_sql
+
+ def test_get_schema_with_schema(self, test_frame1):
+ # GH28486
+ create_sql = sql.get_schema(test_frame1, "test", con=self.conn, schema="pypi")
+ assert "CREATE TABLE pypi." in create_sql
+
+ def test_get_schema_dtypes(self):
+ if self.mode == "sqlalchemy":
+ from sqlalchemy import Integer
+
+ dtype = Integer
+ else:
+ dtype = "INTEGER"
+
+ float_frame = DataFrame({"a": [1.1, 1.2], "b": [2.1, 2.2]})
+ create_sql = sql.get_schema(
+ float_frame, "test", con=self.conn, dtype={"b": dtype}
+ )
+ assert "CREATE" in create_sql
+ assert "INTEGER" in create_sql
+
+ def test_get_schema_keys(self, test_frame1):
+ frame = DataFrame({"Col1": [1.1, 1.2], "Col2": [2.1, 2.2]})
+ create_sql = sql.get_schema(frame, "test", con=self.conn, keys="Col1")
+ constraint_sentence = 'CONSTRAINT test_pk PRIMARY KEY ("Col1")'
+ assert constraint_sentence in create_sql
+
+ # multiple columns as key (GH10385)
+ create_sql = sql.get_schema(test_frame1, "test", con=self.conn, keys=["A", "B"])
+ constraint_sentence = 'CONSTRAINT test_pk PRIMARY KEY ("A", "B")'
+ assert constraint_sentence in create_sql
+
+ def test_chunksize_read(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((22, 5)), columns=list("abcde")
+ )
+ df.to_sql(name="test_chunksize", con=self.conn, index=False)
+
+ # reading the query in one time
+ res1 = sql.read_sql_query("select * from test_chunksize", self.conn)
+
+ # reading the query in chunks with read_sql_query
+ res2 = DataFrame()
+ i = 0
+ sizes = [5, 5, 5, 5, 2]
+
+ for chunk in sql.read_sql_query(
+ "select * from test_chunksize", self.conn, chunksize=5
+ ):
+ res2 = concat([res2, chunk], ignore_index=True)
+ assert len(chunk) == sizes[i]
+ i += 1
+
+ tm.assert_frame_equal(res1, res2)
+
+ # reading the query in chunks with read_sql_query
+ if self.mode == "sqlalchemy":
+ res3 = DataFrame()
+ i = 0
+ sizes = [5, 5, 5, 5, 2]
+
+ for chunk in sql.read_sql_table("test_chunksize", self.conn, chunksize=5):
+ res3 = concat([res3, chunk], ignore_index=True)
+ assert len(chunk) == sizes[i]
+ i += 1
+
+ tm.assert_frame_equal(res1, res3)
+
+ def test_categorical(self):
+ # GH8624
+ # test that categorical gets written correctly as dense column
+ df = DataFrame(
+ {
+ "person_id": [1, 2, 3],
+ "person_name": ["John P. Doe", "Jane Dove", "John P. Doe"],
+ }
+ )
+ df2 = df.copy()
+ df2["person_name"] = df2["person_name"].astype("category")
+
+ df2.to_sql(name="test_categorical", con=self.conn, index=False)
+ res = sql.read_sql_query("SELECT * FROM test_categorical", self.conn)
+
+ tm.assert_frame_equal(res, df)
+
+ def test_unicode_column_name(self):
+ # GH 11431
+ df = DataFrame([[1, 2], [3, 4]], columns=["\xe9", "b"])
+ df.to_sql(name="test_unicode", con=self.conn, index=False)
+
+ def test_escaped_table_name(self):
+ # GH 13206
+ df = DataFrame({"A": [0, 1, 2], "B": [0.2, np.nan, 5.6]})
+ df.to_sql(name="d1187b08-4943-4c8d-a7f6", con=self.conn, index=False)
+
+ res = sql.read_sql_query("SELECT * FROM `d1187b08-4943-4c8d-a7f6`", self.conn)
+
+ tm.assert_frame_equal(res, df)
+
+ def test_read_sql_duplicate_columns(self):
+ # GH#53117
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": 1})
+ df.to_sql(name="test_table", con=self.conn, index=False)
+
+ result = pd.read_sql("SELECT a, b, a +1 as a, c FROM test_table;", self.conn)
+ expected = DataFrame(
+ [[1, 0.1, 2, 1], [2, 0.2, 3, 1], [3, 0.3, 4, 1]],
+ columns=["a", "b", "a", "c"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.skipif(not SQLALCHEMY_INSTALLED, reason="SQLAlchemy not installed")
+class TestSQLApi(SQLAlchemyMixIn, _TestSQLApi):
+ """
+ Test the public API as it would be used directly
+
+ Tests for `read_sql_table` are included here, as this is specific for the
+ sqlalchemy mode.
+
+ """
+
+ flavor = "sqlite"
+ mode = "sqlalchemy"
+
+ @classmethod
+ def setup_class(cls):
+ cls.engine = sqlalchemy.create_engine("sqlite:///:memory:")
+
+ def test_read_table_columns(self, test_frame1):
+ # test columns argument in read_table
+ sql.to_sql(test_frame1, "test_frame", self.conn)
+
+ cols = ["A", "B"]
+ result = sql.read_sql_table("test_frame", self.conn, columns=cols)
+ assert result.columns.tolist() == cols
+
+ def test_read_table_index_col(self, test_frame1):
+ # test columns argument in read_table
+ sql.to_sql(test_frame1, "test_frame", self.conn)
+
+ result = sql.read_sql_table("test_frame", self.conn, index_col="index")
+ assert result.index.names == ["index"]
+
+ result = sql.read_sql_table("test_frame", self.conn, index_col=["A", "B"])
+ assert result.index.names == ["A", "B"]
+
+ result = sql.read_sql_table(
+ "test_frame", self.conn, index_col=["A", "B"], columns=["C", "D"]
+ )
+ assert result.index.names == ["A", "B"]
+ assert result.columns.tolist() == ["C", "D"]
+
+ def test_read_sql_delegate(self):
+ iris_frame1 = sql.read_sql_query("SELECT * FROM iris", self.conn)
+ iris_frame2 = sql.read_sql("SELECT * FROM iris", self.conn)
+ tm.assert_frame_equal(iris_frame1, iris_frame2)
+
+ iris_frame1 = sql.read_sql_table("iris", self.conn)
+ iris_frame2 = sql.read_sql("iris", self.conn)
+ tm.assert_frame_equal(iris_frame1, iris_frame2)
+
+ def test_not_reflect_all_tables(self):
+ from sqlalchemy import text
+ from sqlalchemy.engine import Engine
+
+ # create invalid table
+ query_list = [
+ text("CREATE TABLE invalid (x INTEGER, y UNKNOWN);"),
+ text("CREATE TABLE other_table (x INTEGER, y INTEGER);"),
+ ]
+ for query in query_list:
+ if isinstance(self.conn, Engine):
+ with self.conn.connect() as conn:
+ with conn.begin():
+ conn.execute(query)
+ else:
+ with self.conn.begin():
+ self.conn.execute(query)
+
+ with tm.assert_produces_warning(None):
+ sql.read_sql_table("other_table", self.conn)
+ sql.read_sql_query("SELECT * FROM other_table", self.conn)
+
+ def test_warning_case_insensitive_table_name(self, test_frame1):
+ # see gh-7815
+ with tm.assert_produces_warning(
+ UserWarning,
+ match=(
+ r"The provided table name 'TABLE1' is not found exactly as such in "
+ r"the database after writing the table, possibly due to case "
+ r"sensitivity issues. Consider using lower case table names."
+ ),
+ ):
+ sql.SQLDatabase(self.conn).check_case_sensitive("TABLE1", "")
+
+ # Test that the warning is certainly NOT triggered in a normal case.
+ with tm.assert_produces_warning(None):
+ test_frame1.to_sql(name="CaseSensitive", con=self.conn)
+
+ def _get_index_columns(self, tbl_name):
+ from sqlalchemy.engine import reflection
+
+ insp = reflection.Inspector.from_engine(self.conn)
+ ixs = insp.get_indexes("test_index_saved")
+ ixs = [i["column_names"] for i in ixs]
+ return ixs
+
+ def test_sqlalchemy_type_mapping(self):
+ from sqlalchemy import TIMESTAMP
+
+ # Test Timestamp objects (no datetime64 because of timezone) (GH9085)
+ df = DataFrame(
+ {"time": to_datetime(["2014-12-12 01:54", "2014-12-11 02:54"], utc=True)}
+ )
+ db = sql.SQLDatabase(self.conn)
+ table = sql.SQLTable("test_type", db, frame=df)
+ # GH 9086: TIMESTAMP is the suggested type for datetimes with timezones
+ assert isinstance(table.table.c["time"].type, TIMESTAMP)
+
+ @pytest.mark.parametrize(
+ "integer, expected",
+ [
+ ("int8", "SMALLINT"),
+ ("Int8", "SMALLINT"),
+ ("uint8", "SMALLINT"),
+ ("UInt8", "SMALLINT"),
+ ("int16", "SMALLINT"),
+ ("Int16", "SMALLINT"),
+ ("uint16", "INTEGER"),
+ ("UInt16", "INTEGER"),
+ ("int32", "INTEGER"),
+ ("Int32", "INTEGER"),
+ ("uint32", "BIGINT"),
+ ("UInt32", "BIGINT"),
+ ("int64", "BIGINT"),
+ ("Int64", "BIGINT"),
+ (int, "BIGINT" if np.dtype(int).name == "int64" else "INTEGER"),
+ ],
+ )
+ def test_sqlalchemy_integer_mapping(self, integer, expected):
+ # GH35076 Map pandas integer to optimal SQLAlchemy integer type
+ df = DataFrame([0, 1], columns=["a"], dtype=integer)
+ db = sql.SQLDatabase(self.conn)
+ table = sql.SQLTable("test_type", db, frame=df)
+
+ result = str(table.table.c.a.type)
+ assert result == expected
+
+ @pytest.mark.parametrize("integer", ["uint64", "UInt64"])
+ def test_sqlalchemy_integer_overload_mapping(self, integer):
+ # GH35076 Map pandas integer to optimal SQLAlchemy integer type
+ df = DataFrame([0, 1], columns=["a"], dtype=integer)
+ db = sql.SQLDatabase(self.conn)
+ with pytest.raises(
+ ValueError, match="Unsigned 64 bit integer datatype is not supported"
+ ):
+ sql.SQLTable("test_type", db, frame=df)
+
+ def test_database_uri_string(self, test_frame1):
+ # Test read_sql and .to_sql method with a database URI (GH10654)
+ # db_uri = 'sqlite:///:memory:' # raises
+ # sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near
+ # "iris": syntax error [SQL: 'iris']
+ with tm.ensure_clean() as name:
+ db_uri = "sqlite:///" + name
+ table = "iris"
+ test_frame1.to_sql(name=table, con=db_uri, if_exists="replace", index=False)
+ test_frame2 = sql.read_sql(table, db_uri)
+ test_frame3 = sql.read_sql_table(table, db_uri)
+ query = "SELECT * FROM iris"
+ test_frame4 = sql.read_sql_query(query, db_uri)
+ tm.assert_frame_equal(test_frame1, test_frame2)
+ tm.assert_frame_equal(test_frame1, test_frame3)
+ tm.assert_frame_equal(test_frame1, test_frame4)
+
+ @td.skip_if_installed("pg8000")
+ def test_pg8000_sqlalchemy_passthrough_error(self):
+ # using driver that will not be installed on CI to trigger error
+ # in sqlalchemy.create_engine -> test passing of this error to user
+ db_uri = "postgresql+pg8000://user:pass@host/dbname"
+ with pytest.raises(ImportError, match="pg8000"):
+ sql.read_sql("select * from table", db_uri)
+
+ def test_query_by_text_obj(self):
+ # WIP : GH10846
+ from sqlalchemy import text
+
+ name_text = text("select * from iris where name=:name")
+ iris_df = sql.read_sql(name_text, self.conn, params={"name": "Iris-versicolor"})
+ all_names = set(iris_df["Name"])
+ assert all_names == {"Iris-versicolor"}
+
+ def test_query_by_select_obj(self):
+ # WIP : GH10846
+ from sqlalchemy import (
+ bindparam,
+ select,
+ )
+
+ iris = iris_table_metadata(self.flavor)
+ name_select = select(iris).where(iris.c.Name == bindparam("name"))
+ iris_df = sql.read_sql(name_select, self.conn, params={"name": "Iris-setosa"})
+ all_names = set(iris_df["Name"])
+ assert all_names == {"Iris-setosa"}
+
+ def test_column_with_percentage(self):
+ # GH 37157
+ df = DataFrame({"A": [0, 1, 2], "%_variation": [3, 4, 5]})
+ df.to_sql(name="test_column_percentage", con=self.conn, index=False)
+
+ res = sql.read_sql_table("test_column_percentage", self.conn)
+
+ tm.assert_frame_equal(res, df)
+
+
+class TestSQLiteFallbackApi(SQLiteMixIn, _TestSQLApi):
+ """
+ Test the public sqlite connection fallback API
+
+ """
+
+ flavor = "sqlite"
+ mode = "fallback"
+
+ def connect(self, database=":memory:"):
+ return sqlite3.connect(database)
+
+ def test_sql_open_close(self, test_frame3):
+ # Test if the IO in the database still work if the connection closed
+ # between the writing and reading (as in many real situations).
+
+ with tm.ensure_clean() as name:
+ with closing(self.connect(name)) as conn:
+ assert (
+ sql.to_sql(test_frame3, "test_frame3_legacy", conn, index=False)
+ == 4
+ )
+
+ with closing(self.connect(name)) as conn:
+ result = sql.read_sql_query("SELECT * FROM test_frame3_legacy;", conn)
+
+ tm.assert_frame_equal(test_frame3, result)
+
+ @pytest.mark.skipif(SQLALCHEMY_INSTALLED, reason="SQLAlchemy is installed")
+ def test_con_string_import_error(self):
+ conn = "mysql://root@localhost/pandas"
+ msg = "Using URI string without sqlalchemy installed"
+ with pytest.raises(ImportError, match=msg):
+ sql.read_sql("SELECT * FROM iris", conn)
+
+ @pytest.mark.skipif(SQLALCHEMY_INSTALLED, reason="SQLAlchemy is installed")
+ def test_con_unknown_dbapi2_class_does_not_error_without_sql_alchemy_installed(
+ self,
+ ):
+ class MockSqliteConnection:
+ def __init__(self, *args, **kwargs) -> None:
+ self.conn = sqlite3.Connection(*args, **kwargs)
+
+ def __getattr__(self, name):
+ return getattr(self.conn, name)
+
+ def close(self):
+ self.conn.close()
+
+ with contextlib.closing(MockSqliteConnection(":memory:")) as conn:
+ with tm.assert_produces_warning(UserWarning):
+ sql.read_sql("SELECT 1", conn)
+
+ def test_read_sql_delegate(self):
+ iris_frame1 = sql.read_sql_query("SELECT * FROM iris", self.conn)
+ iris_frame2 = sql.read_sql("SELECT * FROM iris", self.conn)
+ tm.assert_frame_equal(iris_frame1, iris_frame2)
+
+ msg = "Execution failed on sql 'iris': near \"iris\": syntax error"
+ with pytest.raises(sql.DatabaseError, match=msg):
+ sql.read_sql("iris", self.conn)
+
+ def test_get_schema2(self, test_frame1):
+ # without providing a connection object (available for backwards comp)
+ create_sql = sql.get_schema(test_frame1, "test")
+ assert "CREATE" in create_sql
+
+ def _get_sqlite_column_type(self, schema, column):
+ for col in schema.split("\n"):
+ if col.split()[0].strip('"') == column:
+ return col.split()[1]
+ raise ValueError(f"Column {column} not found")
+
+ def test_sqlite_type_mapping(self):
+ # Test Timestamp objects (no datetime64 because of timezone) (GH9085)
+ df = DataFrame(
+ {"time": to_datetime(["2014-12-12 01:54", "2014-12-11 02:54"], utc=True)}
+ )
+ db = sql.SQLiteDatabase(self.conn)
+ table = sql.SQLiteTable("test_type", db, frame=df)
+ schema = table.sql_schema()
+ assert self._get_sqlite_column_type(schema, "time") == "TIMESTAMP"
+
+
+# -----------------------------------------------------------------------------
+# -- Database flavor specific tests
+
+
+@pytest.mark.skipif(not SQLALCHEMY_INSTALLED, reason="SQLAlchemy not installed")
+class _TestSQLAlchemy(SQLAlchemyMixIn, PandasSQLTest):
+ """
+ Base class for testing the sqlalchemy backend.
+
+ Subclasses for specific database types are created below. Tests that
+ deviate for each flavor are overwritten there.
+
+ """
+
+ flavor: str
+
+ @classmethod
+ def setup_class(cls):
+ cls.setup_driver()
+ cls.setup_engine()
+
+ @pytest.fixture(autouse=True)
+ def setup_method(self, iris_path, types_data):
+ try:
+ self.conn = self.engine.connect()
+ self.pandasSQL = sql.SQLDatabase(self.conn)
+ except sqlalchemy.exc.OperationalError:
+ pytest.skip(f"Can't connect to {self.flavor} server")
+ self.load_iris_data(iris_path)
+ self.load_types_data(types_data)
+
+ @classmethod
+ def setup_driver(cls):
+ raise NotImplementedError()
+
+ @classmethod
+ def setup_engine(cls):
+ raise NotImplementedError()
+
+ def test_read_sql_parameter(self, sql_strings):
+ self._read_sql_iris_parameter(sql_strings)
+
+ def test_read_sql_named_parameter(self, sql_strings):
+ self._read_sql_iris_named_parameter(sql_strings)
+
+ def test_to_sql_empty(self, test_frame1):
+ self._to_sql_empty(test_frame1)
+
+ def test_create_table(self):
+ from sqlalchemy import inspect
+
+ temp_conn = self.connect()
+ temp_frame = DataFrame(
+ {"one": [1.0, 2.0, 3.0, 4.0], "two": [4.0, 3.0, 2.0, 1.0]}
+ )
+ with sql.SQLDatabase(temp_conn, need_transaction=True) as pandasSQL:
+ assert pandasSQL.to_sql(temp_frame, "temp_frame") == 4
+
+ insp = inspect(temp_conn)
+ assert insp.has_table("temp_frame")
+
+ # Cleanup
+ with sql.SQLDatabase(temp_conn, need_transaction=True) as pandasSQL:
+ pandasSQL.drop_table("temp_frame")
+
+ def test_drop_table(self):
+ from sqlalchemy import inspect
+
+ temp_conn = self.connect()
+ temp_frame = DataFrame(
+ {"one": [1.0, 2.0, 3.0, 4.0], "two": [4.0, 3.0, 2.0, 1.0]}
+ )
+ pandasSQL = sql.SQLDatabase(temp_conn)
+ assert pandasSQL.to_sql(temp_frame, "temp_frame") == 4
+
+ insp = inspect(temp_conn)
+ assert insp.has_table("temp_frame")
+
+ pandasSQL.drop_table("temp_frame")
+ try:
+ insp.clear_cache() # needed with SQLAlchemy 2.0, unavailable prior
+ except AttributeError:
+ pass
+ assert not insp.has_table("temp_frame")
+
+ def test_roundtrip(self, test_frame1):
+ self._roundtrip(test_frame1)
+
+ def test_execute_sql(self):
+ self._execute_sql()
+
+ def test_read_table(self):
+ iris_frame = sql.read_sql_table("iris", con=self.conn)
+ check_iris_frame(iris_frame)
+
+ def test_read_table_columns(self):
+ iris_frame = sql.read_sql_table(
+ "iris", con=self.conn, columns=["SepalLength", "SepalLength"]
+ )
+ tm.equalContents(iris_frame.columns.values, ["SepalLength", "SepalLength"])
+
+ def test_read_table_absent_raises(self):
+ msg = "Table this_doesnt_exist not found"
+ with pytest.raises(ValueError, match=msg):
+ sql.read_sql_table("this_doesnt_exist", con=self.conn)
+
+ def test_default_type_conversion(self):
+ df = sql.read_sql_table("types", self.conn)
+
+ assert issubclass(df.FloatCol.dtype.type, np.floating)
+ assert issubclass(df.IntCol.dtype.type, np.integer)
+ assert issubclass(df.BoolCol.dtype.type, np.bool_)
+
+ # Int column with NA values stays as float
+ assert issubclass(df.IntColWithNull.dtype.type, np.floating)
+ # Bool column with NA values becomes object
+ assert issubclass(df.BoolColWithNull.dtype.type, object)
+
+ def test_bigint(self):
+ # int64 should be converted to BigInteger, GH7433
+ df = DataFrame(data={"i64": [2**62]})
+ assert df.to_sql(name="test_bigint", con=self.conn, index=False) == 1
+ result = sql.read_sql_table("test_bigint", self.conn)
+
+ tm.assert_frame_equal(df, result)
+
+ def test_default_date_load(self):
+ df = sql.read_sql_table("types", self.conn)
+
+ # IMPORTANT - sqlite has no native date type, so shouldn't parse, but
+ # MySQL SHOULD be converted.
+ assert issubclass(df.DateCol.dtype.type, np.datetime64)
+
+ def test_datetime_with_timezone(self, request):
+ # edge case that converts postgresql datetime with time zone types
+ # to datetime64[ns,psycopg2.tz.FixedOffsetTimezone..], which is ok
+ # but should be more natural, so coerce to datetime64[ns] for now
+
+ def check(col):
+ # check that a column is either datetime64[ns]
+ # or datetime64[ns, UTC]
+ if lib.is_np_dtype(col.dtype, "M"):
+ # "2000-01-01 00:00:00-08:00" should convert to
+ # "2000-01-01 08:00:00"
+ assert col[0] == Timestamp("2000-01-01 08:00:00")
+
+ # "2000-06-01 00:00:00-07:00" should convert to
+ # "2000-06-01 07:00:00"
+ assert col[1] == Timestamp("2000-06-01 07:00:00")
+
+ elif isinstance(col.dtype, DatetimeTZDtype):
+ assert str(col.dt.tz) == "UTC"
+
+ # "2000-01-01 00:00:00-08:00" should convert to
+ # "2000-01-01 08:00:00"
+ # "2000-06-01 00:00:00-07:00" should convert to
+ # "2000-06-01 07:00:00"
+ # GH 6415
+ expected_data = [
+ Timestamp("2000-01-01 08:00:00", tz="UTC"),
+ Timestamp("2000-06-01 07:00:00", tz="UTC"),
+ ]
+ expected = Series(expected_data, name=col.name)
+ tm.assert_series_equal(col, expected)
+
+ else:
+ raise AssertionError(
+ f"DateCol loaded with incorrect type -> {col.dtype}"
+ )
+
+ # GH11216
+ df = read_sql_query("select * from types", self.conn)
+ if not hasattr(df, "DateColWithTz"):
+ request.node.add_marker(
+ pytest.mark.xfail(reason="no column with datetime with time zone")
+ )
+
+ # this is parsed on Travis (linux), but not on macosx for some reason
+ # even with the same versions of psycopg2 & sqlalchemy, possibly a
+ # Postgresql server version difference
+ col = df.DateColWithTz
+ assert isinstance(col.dtype, DatetimeTZDtype)
+
+ df = read_sql_query(
+ "select * from types", self.conn, parse_dates=["DateColWithTz"]
+ )
+ if not hasattr(df, "DateColWithTz"):
+ request.node.add_marker(
+ pytest.mark.xfail(reason="no column with datetime with time zone")
+ )
+ col = df.DateColWithTz
+ assert isinstance(col.dtype, DatetimeTZDtype)
+ assert str(col.dt.tz) == "UTC"
+ check(df.DateColWithTz)
+
+ df = concat(
+ list(read_sql_query("select * from types", self.conn, chunksize=1)),
+ ignore_index=True,
+ )
+ col = df.DateColWithTz
+ assert isinstance(col.dtype, DatetimeTZDtype)
+ assert str(col.dt.tz) == "UTC"
+ expected = sql.read_sql_table("types", self.conn)
+ col = expected.DateColWithTz
+ assert isinstance(col.dtype, DatetimeTZDtype)
+ tm.assert_series_equal(df.DateColWithTz, expected.DateColWithTz)
+
+ # xref #7139
+ # this might or might not be converted depending on the postgres driver
+ df = sql.read_sql_table("types", self.conn)
+ check(df.DateColWithTz)
+
+ def test_datetime_with_timezone_roundtrip(self):
+ # GH 9086
+ # Write datetimetz data to a db and read it back
+ # For dbs that support timestamps with timezones, should get back UTC
+ # otherwise naive data should be returned
+ expected = DataFrame(
+ {"A": date_range("2013-01-01 09:00:00", periods=3, tz="US/Pacific")}
+ )
+ assert expected.to_sql(name="test_datetime_tz", con=self.conn, index=False) == 3
+
+ if self.flavor == "postgresql":
+ # SQLAlchemy "timezones" (i.e. offsets) are coerced to UTC
+ expected["A"] = expected["A"].dt.tz_convert("UTC")
+ else:
+ # Otherwise, timestamps are returned as local, naive
+ expected["A"] = expected["A"].dt.tz_localize(None)
+
+ result = sql.read_sql_table("test_datetime_tz", self.conn)
+ tm.assert_frame_equal(result, expected)
+
+ result = sql.read_sql_query("SELECT * FROM test_datetime_tz", self.conn)
+ if self.flavor == "sqlite":
+ # read_sql_query does not return datetime type like read_sql_table
+ assert isinstance(result.loc[0, "A"], str)
+ result["A"] = to_datetime(result["A"])
+ tm.assert_frame_equal(result, expected)
+
+ def test_out_of_bounds_datetime(self):
+ # GH 26761
+ data = DataFrame({"date": datetime(9999, 1, 1)}, index=[0])
+ assert data.to_sql(name="test_datetime_obb", con=self.conn, index=False) == 1
+ result = sql.read_sql_table("test_datetime_obb", self.conn)
+ expected = DataFrame([pd.NaT], columns=["date"])
+ tm.assert_frame_equal(result, expected)
+
+ def test_naive_datetimeindex_roundtrip(self):
+ # GH 23510
+ # Ensure that a naive DatetimeIndex isn't converted to UTC
+ dates = date_range("2018-01-01", periods=5, freq="6H")._with_freq(None)
+ expected = DataFrame({"nums": range(5)}, index=dates)
+ assert (
+ expected.to_sql(name="foo_table", con=self.conn, index_label="info_date")
+ == 5
+ )
+ result = sql.read_sql_table("foo_table", self.conn, index_col="info_date")
+ # result index with gain a name from a set_index operation; expected
+ tm.assert_frame_equal(result, expected, check_names=False)
+
+ def test_date_parsing(self):
+ # No Parsing
+ df = sql.read_sql_table("types", self.conn)
+ expected_type = object if self.flavor == "sqlite" else np.datetime64
+ assert issubclass(df.DateCol.dtype.type, expected_type)
+
+ df = sql.read_sql_table("types", self.conn, parse_dates=["DateCol"])
+ assert issubclass(df.DateCol.dtype.type, np.datetime64)
+
+ df = sql.read_sql_table(
+ "types", self.conn, parse_dates={"DateCol": "%Y-%m-%d %H:%M:%S"}
+ )
+ assert issubclass(df.DateCol.dtype.type, np.datetime64)
+
+ df = sql.read_sql_table(
+ "types",
+ self.conn,
+ parse_dates={"DateCol": {"format": "%Y-%m-%d %H:%M:%S"}},
+ )
+ assert issubclass(df.DateCol.dtype.type, np.datetime64)
+
+ df = sql.read_sql_table("types", self.conn, parse_dates=["IntDateCol"])
+ assert issubclass(df.IntDateCol.dtype.type, np.datetime64)
+
+ df = sql.read_sql_table("types", self.conn, parse_dates={"IntDateCol": "s"})
+ assert issubclass(df.IntDateCol.dtype.type, np.datetime64)
+
+ df = sql.read_sql_table(
+ "types", self.conn, parse_dates={"IntDateCol": {"unit": "s"}}
+ )
+ assert issubclass(df.IntDateCol.dtype.type, np.datetime64)
+
+ def test_datetime(self):
+ df = DataFrame(
+ {"A": date_range("2013-01-01 09:00:00", periods=3), "B": np.arange(3.0)}
+ )
+ assert df.to_sql(name="test_datetime", con=self.conn) == 3
+
+ # with read_table -> type information from schema used
+ result = sql.read_sql_table("test_datetime", self.conn)
+ result = result.drop("index", axis=1)
+ tm.assert_frame_equal(result, df)
+
+ # with read_sql -> no type information -> sqlite has no native
+ result = sql.read_sql_query("SELECT * FROM test_datetime", self.conn)
+ result = result.drop("index", axis=1)
+ if self.flavor == "sqlite":
+ assert isinstance(result.loc[0, "A"], str)
+ result["A"] = to_datetime(result["A"])
+ tm.assert_frame_equal(result, df)
+ else:
+ tm.assert_frame_equal(result, df)
+
+ def test_datetime_NaT(self):
+ df = DataFrame(
+ {"A": date_range("2013-01-01 09:00:00", periods=3), "B": np.arange(3.0)}
+ )
+ df.loc[1, "A"] = np.nan
+ assert df.to_sql(name="test_datetime", con=self.conn, index=False) == 3
+
+ # with read_table -> type information from schema used
+ result = sql.read_sql_table("test_datetime", self.conn)
+ tm.assert_frame_equal(result, df)
+
+ # with read_sql -> no type information -> sqlite has no native
+ result = sql.read_sql_query("SELECT * FROM test_datetime", self.conn)
+ if self.flavor == "sqlite":
+ assert isinstance(result.loc[0, "A"], str)
+ result["A"] = to_datetime(result["A"], errors="coerce")
+ tm.assert_frame_equal(result, df)
+ else:
+ tm.assert_frame_equal(result, df)
+
+ def test_datetime_date(self):
+ # test support for datetime.date
+ df = DataFrame([date(2014, 1, 1), date(2014, 1, 2)], columns=["a"])
+ assert df.to_sql(name="test_date", con=self.conn, index=False) == 2
+ res = read_sql_table("test_date", self.conn)
+ result = res["a"]
+ expected = to_datetime(df["a"])
+ # comes back as datetime64
+ tm.assert_series_equal(result, expected)
+
+ def test_datetime_time(self, sqlite_buildin):
+ # test support for datetime.time
+ df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
+ assert df.to_sql(name="test_time", con=self.conn, index=False) == 2
+ res = read_sql_table("test_time", self.conn)
+ tm.assert_frame_equal(res, df)
+
+ # GH8341
+ # first, use the fallback to have the sqlite adapter put in place
+ sqlite_conn = sqlite_buildin
+ assert sql.to_sql(df, "test_time2", sqlite_conn, index=False) == 2
+ res = sql.read_sql_query("SELECT * FROM test_time2", sqlite_conn)
+ ref = df.map(lambda _: _.strftime("%H:%M:%S.%f"))
+ tm.assert_frame_equal(ref, res) # check if adapter is in place
+ # then test if sqlalchemy is unaffected by the sqlite adapter
+ assert sql.to_sql(df, "test_time3", self.conn, index=False) == 2
+ if self.flavor == "sqlite":
+ res = sql.read_sql_query("SELECT * FROM test_time3", self.conn)
+ ref = df.map(lambda _: _.strftime("%H:%M:%S.%f"))
+ tm.assert_frame_equal(ref, res)
+ res = sql.read_sql_table("test_time3", self.conn)
+ tm.assert_frame_equal(df, res)
+
+ def test_mixed_dtype_insert(self):
+ # see GH6509
+ s1 = Series(2**25 + 1, dtype=np.int32)
+ s2 = Series(0.0, dtype=np.float32)
+ df = DataFrame({"s1": s1, "s2": s2})
+
+ # write and read again
+ assert df.to_sql(name="test_read_write", con=self.conn, index=False) == 1
+ df2 = sql.read_sql_table("test_read_write", self.conn)
+
+ tm.assert_frame_equal(df, df2, check_dtype=False, check_exact=True)
+
+ def test_nan_numeric(self):
+ # NaNs in numeric float column
+ df = DataFrame({"A": [0, 1, 2], "B": [0.2, np.nan, 5.6]})
+ assert df.to_sql(name="test_nan", con=self.conn, index=False) == 3
+
+ # with read_table
+ result = sql.read_sql_table("test_nan", self.conn)
+ tm.assert_frame_equal(result, df)
+
+ # with read_sql
+ result = sql.read_sql_query("SELECT * FROM test_nan", self.conn)
+ tm.assert_frame_equal(result, df)
+
+ def test_nan_fullcolumn(self):
+ # full NaN column (numeric float column)
+ df = DataFrame({"A": [0, 1, 2], "B": [np.nan, np.nan, np.nan]})
+ assert df.to_sql(name="test_nan", con=self.conn, index=False) == 3
+
+ # with read_table
+ result = sql.read_sql_table("test_nan", self.conn)
+ tm.assert_frame_equal(result, df)
+
+ # with read_sql -> not type info from table -> stays None
+ df["B"] = df["B"].astype("object")
+ df["B"] = None
+ result = sql.read_sql_query("SELECT * FROM test_nan", self.conn)
+ tm.assert_frame_equal(result, df)
+
+ def test_nan_string(self):
+ # NaNs in string column
+ df = DataFrame({"A": [0, 1, 2], "B": ["a", "b", np.nan]})
+ assert df.to_sql(name="test_nan", con=self.conn, index=False) == 3
+
+ # NaNs are coming back as None
+ df.loc[2, "B"] = None
+
+ # with read_table
+ result = sql.read_sql_table("test_nan", self.conn)
+ tm.assert_frame_equal(result, df)
+
+ # with read_sql
+ result = sql.read_sql_query("SELECT * FROM test_nan", self.conn)
+ tm.assert_frame_equal(result, df)
+
+ def _get_index_columns(self, tbl_name):
+ from sqlalchemy import inspect
+
+ insp = inspect(self.conn)
+
+ ixs = insp.get_indexes(tbl_name)
+ ixs = [i["column_names"] for i in ixs]
+ return ixs
+
+ def test_to_sql_save_index(self):
+ self._to_sql_save_index()
+
+ def test_transactions(self):
+ self._transaction_test()
+
+ def test_get_schema_create_table(self, test_frame3):
+ # Use a dataframe without a bool column, since MySQL converts bool to
+ # TINYINT (which read_sql_table returns as an int and causes a dtype
+ # mismatch)
+ from sqlalchemy import text
+ from sqlalchemy.engine import Engine
+
+ tbl = "test_get_schema_create_table"
+ create_sql = sql.get_schema(test_frame3, tbl, con=self.conn)
+ blank_test_df = test_frame3.iloc[:0]
+
+ self.drop_table(tbl, self.conn)
+ create_sql = text(create_sql)
+ if isinstance(self.conn, Engine):
+ with self.conn.connect() as conn:
+ with conn.begin():
+ conn.execute(create_sql)
+ else:
+ with self.conn.begin():
+ self.conn.execute(create_sql)
+ returned_df = sql.read_sql_table(tbl, self.conn)
+ tm.assert_frame_equal(returned_df, blank_test_df, check_index_type=False)
+ self.drop_table(tbl, self.conn)
+
+ def test_dtype(self):
+ from sqlalchemy import (
+ TEXT,
+ String,
+ )
+ from sqlalchemy.schema import MetaData
+
+ cols = ["A", "B"]
+ data = [(0.8, True), (0.9, None)]
+ df = DataFrame(data, columns=cols)
+ assert df.to_sql(name="dtype_test", con=self.conn) == 2
+ assert df.to_sql(name="dtype_test2", con=self.conn, dtype={"B": TEXT}) == 2
+ meta = MetaData()
+ meta.reflect(bind=self.conn)
+ sqltype = meta.tables["dtype_test2"].columns["B"].type
+ assert isinstance(sqltype, TEXT)
+ msg = "The type of B is not a SQLAlchemy type"
+ with pytest.raises(ValueError, match=msg):
+ df.to_sql(name="error", con=self.conn, dtype={"B": str})
+
+ # GH9083
+ assert (
+ df.to_sql(name="dtype_test3", con=self.conn, dtype={"B": String(10)}) == 2
+ )
+ meta.reflect(bind=self.conn)
+ sqltype = meta.tables["dtype_test3"].columns["B"].type
+ assert isinstance(sqltype, String)
+ assert sqltype.length == 10
+
+ # single dtype
+ assert df.to_sql(name="single_dtype_test", con=self.conn, dtype=TEXT) == 2
+ meta.reflect(bind=self.conn)
+ sqltypea = meta.tables["single_dtype_test"].columns["A"].type
+ sqltypeb = meta.tables["single_dtype_test"].columns["B"].type
+ assert isinstance(sqltypea, TEXT)
+ assert isinstance(sqltypeb, TEXT)
+
+ def test_notna_dtype(self):
+ from sqlalchemy import (
+ Boolean,
+ DateTime,
+ Float,
+ Integer,
+ )
+ from sqlalchemy.schema import MetaData
+
+ cols = {
+ "Bool": Series([True, None]),
+ "Date": Series([datetime(2012, 5, 1), None]),
+ "Int": Series([1, None], dtype="object"),
+ "Float": Series([1.1, None]),
+ }
+ df = DataFrame(cols)
+
+ tbl = "notna_dtype_test"
+ assert df.to_sql(name=tbl, con=self.conn) == 2
+ _ = sql.read_sql_table(tbl, self.conn)
+ meta = MetaData()
+ meta.reflect(bind=self.conn)
+ my_type = Integer if self.flavor == "mysql" else Boolean
+ col_dict = meta.tables[tbl].columns
+ assert isinstance(col_dict["Bool"].type, my_type)
+ assert isinstance(col_dict["Date"].type, DateTime)
+ assert isinstance(col_dict["Int"].type, Integer)
+ assert isinstance(col_dict["Float"].type, Float)
+
+ def test_double_precision(self):
+ from sqlalchemy import (
+ BigInteger,
+ Float,
+ Integer,
+ )
+ from sqlalchemy.schema import MetaData
+
+ V = 1.23456789101112131415
+
+ df = DataFrame(
+ {
+ "f32": Series([V], dtype="float32"),
+ "f64": Series([V], dtype="float64"),
+ "f64_as_f32": Series([V], dtype="float64"),
+ "i32": Series([5], dtype="int32"),
+ "i64": Series([5], dtype="int64"),
+ }
+ )
+
+ assert (
+ df.to_sql(
+ name="test_dtypes",
+ con=self.conn,
+ index=False,
+ if_exists="replace",
+ dtype={"f64_as_f32": Float(precision=23)},
+ )
+ == 1
+ )
+ res = sql.read_sql_table("test_dtypes", self.conn)
+
+ # check precision of float64
+ assert np.round(df["f64"].iloc[0], 14) == np.round(res["f64"].iloc[0], 14)
+
+ # check sql types
+ meta = MetaData()
+ meta.reflect(bind=self.conn)
+ col_dict = meta.tables["test_dtypes"].columns
+ assert str(col_dict["f32"].type) == str(col_dict["f64_as_f32"].type)
+ assert isinstance(col_dict["f32"].type, Float)
+ assert isinstance(col_dict["f64"].type, Float)
+ assert isinstance(col_dict["i32"].type, Integer)
+ assert isinstance(col_dict["i64"].type, BigInteger)
+
+ def test_connectable_issue_example(self):
+ # This tests the example raised in issue
+ # https://github.com/pandas-dev/pandas/issues/10104
+ from sqlalchemy.engine import Engine
+
+ def test_select(connection):
+ query = "SELECT test_foo_data FROM test_foo_data"
+ return sql.read_sql_query(query, con=connection)
+
+ def test_append(connection, data):
+ data.to_sql(name="test_foo_data", con=connection, if_exists="append")
+
+ def test_connectable(conn):
+ # https://github.com/sqlalchemy/sqlalchemy/commit/
+ # 00b5c10846e800304caa86549ab9da373b42fa5d#r48323973
+ foo_data = test_select(conn)
+ test_append(conn, foo_data)
+
+ def main(connectable):
+ if isinstance(connectable, Engine):
+ with connectable.connect() as conn:
+ with conn.begin():
+ test_connectable(conn)
+ else:
+ test_connectable(connectable)
+
+ assert (
+ DataFrame({"test_foo_data": [0, 1, 2]}).to_sql(
+ name="test_foo_data", con=self.conn
+ )
+ == 3
+ )
+ main(self.conn)
+
+ @pytest.mark.parametrize(
+ "input",
+ [{"foo": [np.inf]}, {"foo": [-np.inf]}, {"foo": [-np.inf], "infe0": ["bar"]}],
+ )
+ def test_to_sql_with_negative_npinf(self, input, request):
+ # GH 34431
+
+ df = DataFrame(input)
+
+ if self.flavor == "mysql":
+ # GH 36465
+ # The input {"foo": [-np.inf], "infe0": ["bar"]} does not raise any error
+ # for pymysql version >= 0.10
+ # TODO(GH#36465): remove this version check after GH 36465 is fixed
+ pymysql = pytest.importorskip("pymysql")
+
+ if (
+ Version(pymysql.__version__) < Version("1.0.3")
+ and "infe0" in df.columns
+ ):
+ mark = pytest.mark.xfail(reason="GH 36465")
+ request.node.add_marker(mark)
+
+ msg = "inf cannot be used with MySQL"
+ with pytest.raises(ValueError, match=msg):
+ df.to_sql(name="foobar", con=self.conn, index=False)
+ else:
+ assert df.to_sql(name="foobar", con=self.conn, index=False) == 1
+ res = sql.read_sql_table("foobar", self.conn)
+ tm.assert_equal(df, res)
+
+ def test_temporary_table(self):
+ from sqlalchemy import (
+ Column,
+ Integer,
+ Unicode,
+ select,
+ )
+ from sqlalchemy.orm import (
+ Session,
+ declarative_base,
+ )
+
+ test_data = "Hello, World!"
+ expected = DataFrame({"spam": [test_data]})
+ Base = declarative_base()
+
+ class Temporary(Base):
+ __tablename__ = "temp_test"
+ __table_args__ = {"prefixes": ["TEMPORARY"]}
+ id = Column(Integer, primary_key=True)
+ spam = Column(Unicode(30), nullable=False)
+
+ with Session(self.conn) as session:
+ with session.begin():
+ conn = session.connection()
+ Temporary.__table__.create(conn)
+ session.add(Temporary(spam=test_data))
+ session.flush()
+ df = sql.read_sql_query(sql=select(Temporary.spam), con=conn)
+ tm.assert_frame_equal(df, expected)
+
+ # -- SQL Engine tests (in the base class for now)
+ def test_invalid_engine(self, test_frame1):
+ msg = "engine must be one of 'auto', 'sqlalchemy'"
+ with pytest.raises(ValueError, match=msg):
+ self._to_sql_with_sql_engine(test_frame1, "bad_engine")
+
+ def test_options_sqlalchemy(self, test_frame1):
+ # use the set option
+ with pd.option_context("io.sql.engine", "sqlalchemy"):
+ self._to_sql_with_sql_engine(test_frame1)
+
+ def test_options_auto(self, test_frame1):
+ # use the set option
+ with pd.option_context("io.sql.engine", "auto"):
+ self._to_sql_with_sql_engine(test_frame1)
+
+ def test_options_get_engine(self):
+ assert isinstance(get_engine("sqlalchemy"), SQLAlchemyEngine)
+
+ with pd.option_context("io.sql.engine", "sqlalchemy"):
+ assert isinstance(get_engine("auto"), SQLAlchemyEngine)
+ assert isinstance(get_engine("sqlalchemy"), SQLAlchemyEngine)
+
+ with pd.option_context("io.sql.engine", "auto"):
+ assert isinstance(get_engine("auto"), SQLAlchemyEngine)
+ assert isinstance(get_engine("sqlalchemy"), SQLAlchemyEngine)
+
+ def test_get_engine_auto_error_message(self):
+ # Expect different error messages from get_engine(engine="auto")
+ # if engines aren't installed vs. are installed but bad version
+ pass
+ # TODO(GH#36893) fill this in when we add more engines
+
+ @pytest.mark.parametrize("func", ["read_sql", "read_sql_query"])
+ def test_read_sql_dtype_backend(self, string_storage, func, dtype_backend):
+ # GH#50048
+ table = "test"
+ df = self.dtype_backend_data()
+ df.to_sql(name=table, con=self.conn, index=False, if_exists="replace")
+
+ with pd.option_context("mode.string_storage", string_storage):
+ result = getattr(pd, func)(
+ f"Select * from {table}", self.conn, dtype_backend=dtype_backend
+ )
+ expected = self.dtype_backend_expected(string_storage, dtype_backend)
+ tm.assert_frame_equal(result, expected)
+
+ with pd.option_context("mode.string_storage", string_storage):
+ iterator = getattr(pd, func)(
+ f"Select * from {table}",
+ con=self.conn,
+ dtype_backend=dtype_backend,
+ chunksize=3,
+ )
+ expected = self.dtype_backend_expected(string_storage, dtype_backend)
+ for result in iterator:
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("func", ["read_sql", "read_sql_table"])
+ def test_read_sql_dtype_backend_table(self, string_storage, func, dtype_backend):
+ # GH#50048
+ table = "test"
+ df = self.dtype_backend_data()
+ df.to_sql(name=table, con=self.conn, index=False, if_exists="replace")
+
+ with pd.option_context("mode.string_storage", string_storage):
+ result = getattr(pd, func)(table, self.conn, dtype_backend=dtype_backend)
+ expected = self.dtype_backend_expected(string_storage, dtype_backend)
+ tm.assert_frame_equal(result, expected)
+
+ with pd.option_context("mode.string_storage", string_storage):
+ iterator = getattr(pd, func)(
+ table,
+ self.conn,
+ dtype_backend=dtype_backend,
+ chunksize=3,
+ )
+ expected = self.dtype_backend_expected(string_storage, dtype_backend)
+ for result in iterator:
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("func", ["read_sql", "read_sql_table", "read_sql_query"])
+ def test_read_sql_invalid_dtype_backend_table(self, func):
+ table = "test"
+ df = self.dtype_backend_data()
+ df.to_sql(name=table, con=self.conn, index=False, if_exists="replace")
+
+ msg = (
+ "dtype_backend numpy is invalid, only 'numpy_nullable' and "
+ "'pyarrow' are allowed."
+ )
+ with pytest.raises(ValueError, match=msg):
+ getattr(pd, func)(table, self.conn, dtype_backend="numpy")
+
+ def dtype_backend_data(self) -> DataFrame:
+ return DataFrame(
+ {
+ "a": Series([1, np.nan, 3], dtype="Int64"),
+ "b": Series([1, 2, 3], dtype="Int64"),
+ "c": Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": [True, False, None],
+ "f": [True, False, True],
+ "g": ["a", "b", "c"],
+ "h": ["a", "b", None],
+ }
+ )
+
+ def dtype_backend_expected(self, storage, dtype_backend) -> DataFrame:
+ string_array: StringArray | ArrowStringArray
+ string_array_na: StringArray | ArrowStringArray
+ if storage == "python":
+ string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_))
+ string_array_na = StringArray(np.array(["a", "b", pd.NA], dtype=np.object_))
+
+ else:
+ pa = pytest.importorskip("pyarrow")
+ string_array = ArrowStringArray(pa.array(["a", "b", "c"]))
+ string_array_na = ArrowStringArray(pa.array(["a", "b", None]))
+
+ df = DataFrame(
+ {
+ "a": Series([1, np.nan, 3], dtype="Int64"),
+ "b": Series([1, 2, 3], dtype="Int64"),
+ "c": Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": Series([True, False, pd.NA], dtype="boolean"),
+ "f": Series([True, False, True], dtype="boolean"),
+ "g": string_array,
+ "h": string_array_na,
+ }
+ )
+ if dtype_backend == "pyarrow":
+ pa = pytest.importorskip("pyarrow")
+
+ from pandas.arrays import ArrowExtensionArray
+
+ df = DataFrame(
+ {
+ col: ArrowExtensionArray(pa.array(df[col], from_pandas=True))
+ for col in df.columns
+ }
+ )
+ return df
+
+ def test_chunksize_empty_dtypes(self):
+ # GH#50245
+ dtypes = {"a": "int64", "b": "object"}
+ df = DataFrame(columns=["a", "b"]).astype(dtypes)
+ expected = df.copy()
+ df.to_sql(name="test", con=self.conn, index=False, if_exists="replace")
+
+ for result in read_sql_query(
+ "SELECT * FROM test",
+ self.conn,
+ dtype=dtypes,
+ chunksize=1,
+ ):
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype_backend", [lib.no_default, "numpy_nullable"])
+ @pytest.mark.parametrize("func", ["read_sql", "read_sql_query"])
+ def test_read_sql_dtype(self, func, dtype_backend):
+ # GH#50797
+ table = "test"
+ df = DataFrame({"a": [1, 2, 3], "b": 5})
+ df.to_sql(name=table, con=self.conn, index=False, if_exists="replace")
+
+ result = getattr(pd, func)(
+ f"Select * from {table}",
+ self.conn,
+ dtype={"a": np.float64},
+ dtype_backend=dtype_backend,
+ )
+ expected = DataFrame(
+ {
+ "a": Series([1, 2, 3], dtype=np.float64),
+ "b": Series(
+ [5, 5, 5],
+ dtype="int64" if not dtype_backend == "numpy_nullable" else "Int64",
+ ),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+class TestSQLiteAlchemy(_TestSQLAlchemy):
+ """
+ Test the sqlalchemy backend against an in-memory sqlite database.
+
+ """
+
+ flavor = "sqlite"
+
+ @classmethod
+ def setup_engine(cls):
+ cls.engine = sqlalchemy.create_engine("sqlite:///:memory:")
+
+ @classmethod
+ def setup_driver(cls):
+ # sqlite3 is built-in
+ cls.driver = None
+
+ def test_keyword_deprecation(self):
+ # GH 54397
+ msg = (
+ "Starting with pandas version 3.0 all arguments of to_sql except for the "
+ "arguments 'name' and 'con' will be keyword-only."
+ )
+ df = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 1, "B": 2, "C": 3}])
+ df.to_sql("example", self.conn)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.to_sql("example", self.conn, None, if_exists="replace")
+
+ def test_default_type_conversion(self):
+ df = sql.read_sql_table("types", self.conn)
+
+ assert issubclass(df.FloatCol.dtype.type, np.floating)
+ assert issubclass(df.IntCol.dtype.type, np.integer)
+
+ # sqlite has no boolean type, so integer type is returned
+ assert issubclass(df.BoolCol.dtype.type, np.integer)
+
+ # Int column with NA values stays as float
+ assert issubclass(df.IntColWithNull.dtype.type, np.floating)
+
+ # Non-native Bool column with NA values stays as float
+ assert issubclass(df.BoolColWithNull.dtype.type, np.floating)
+
+ def test_default_date_load(self):
+ df = sql.read_sql_table("types", self.conn)
+
+ # IMPORTANT - sqlite has no native date type, so shouldn't parse, but
+ assert not issubclass(df.DateCol.dtype.type, np.datetime64)
+
+ def test_bigint_warning(self):
+ # test no warning for BIGINT (to support int64) is raised (GH7433)
+ df = DataFrame({"a": [1, 2]}, dtype="int64")
+ assert df.to_sql(name="test_bigintwarning", con=self.conn, index=False) == 2
+
+ with tm.assert_produces_warning(None):
+ sql.read_sql_table("test_bigintwarning", self.conn)
+
+ def test_valueerror_exception(self):
+ df = DataFrame({"col1": [1, 2], "col2": [3, 4]})
+ with pytest.raises(ValueError, match="Empty table name specified"):
+ df.to_sql(name="", con=self.conn, if_exists="replace", index=False)
+
+ def test_row_object_is_named_tuple(self):
+ # GH 40682
+ # Test for the is_named_tuple() function
+ # Placed here due to its usage of sqlalchemy
+
+ from sqlalchemy import (
+ Column,
+ Integer,
+ String,
+ )
+ from sqlalchemy.orm import (
+ declarative_base,
+ sessionmaker,
+ )
+
+ BaseModel = declarative_base()
+
+ class Test(BaseModel):
+ __tablename__ = "test_frame"
+ id = Column(Integer, primary_key=True)
+ string_column = Column(String(50))
+
+ with self.conn.begin():
+ BaseModel.metadata.create_all(self.conn)
+ Session = sessionmaker(bind=self.conn)
+ with Session() as session:
+ df = DataFrame({"id": [0, 1], "string_column": ["hello", "world"]})
+ assert (
+ df.to_sql(
+ name="test_frame", con=self.conn, index=False, if_exists="replace"
+ )
+ == 2
+ )
+ session.commit()
+ test_query = session.query(Test.id, Test.string_column)
+ df = DataFrame(test_query)
+
+ assert list(df.columns) == ["id", "string_column"]
+
+ def dtype_backend_expected(self, storage, dtype_backend) -> DataFrame:
+ df = super().dtype_backend_expected(storage, dtype_backend)
+ if dtype_backend == "numpy_nullable":
+ df = df.astype({"e": "Int64", "f": "Int64"})
+ else:
+ df = df.astype({"e": "int64[pyarrow]", "f": "int64[pyarrow]"})
+
+ return df
+
+ @pytest.mark.parametrize("func", ["read_sql", "read_sql_table"])
+ def test_read_sql_dtype_backend_table(self, string_storage, func):
+ # GH#50048 Not supported for sqlite
+ pass
+
+ def test_read_sql_string_inference(self):
+ # GH#54430
+ pytest.importorskip("pyarrow")
+ table = "test"
+ df = DataFrame({"a": ["x", "y"]})
+ df.to_sql(table, con=self.conn, index=False, if_exists="replace")
+
+ with pd.option_context("future.infer_string", True):
+ result = read_sql_table(table, self.conn)
+
+ dtype = "string[pyarrow_numpy]"
+ expected = DataFrame(
+ {"a": ["x", "y"]}, dtype=dtype, columns=Index(["a"], dtype=dtype)
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_roundtripping_datetimes(self):
+ # GH#54877
+ df = DataFrame({"t": [datetime(2020, 12, 31, 12)]}, dtype="datetime64[ns]")
+ df.to_sql("test", self.conn, if_exists="replace", index=False)
+ result = pd.read_sql("select * from test", self.conn).iloc[0, 0]
+ assert result == "2020-12-31 12:00:00.000000"
+
+
+@pytest.fixture
+def sqlite_builtin_detect_types():
+ with contextlib.closing(
+ sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
+ ) as closing_conn:
+ with closing_conn as conn:
+ yield conn
+
+
+def test_roundtripping_datetimes_detect_types(sqlite_builtin_detect_types):
+ # https://github.com/pandas-dev/pandas/issues/55554
+ conn = sqlite_builtin_detect_types
+ df = DataFrame({"t": [datetime(2020, 12, 31, 12)]}, dtype="datetime64[ns]")
+ df.to_sql("test", conn, if_exists="replace", index=False)
+ result = pd.read_sql("select * from test", conn).iloc[0, 0]
+ assert result == Timestamp("2020-12-31 12:00:00.000000")
+
+
+@pytest.mark.db
+class TestMySQLAlchemy(_TestSQLAlchemy):
+ """
+ Test the sqlalchemy backend against an MySQL database.
+
+ """
+
+ flavor = "mysql"
+ port = 3306
+
+ @classmethod
+ def setup_engine(cls):
+ cls.engine = sqlalchemy.create_engine(
+ f"mysql+{cls.driver}://root@localhost:{cls.port}/pandas",
+ connect_args=cls.connect_args,
+ )
+
+ @classmethod
+ def setup_driver(cls):
+ pymysql = pytest.importorskip("pymysql")
+ cls.driver = "pymysql"
+ cls.connect_args = {"client_flag": pymysql.constants.CLIENT.MULTI_STATEMENTS}
+
+ def test_default_type_conversion(self):
+ pass
+
+ def dtype_backend_expected(self, storage, dtype_backend) -> DataFrame:
+ df = super().dtype_backend_expected(storage, dtype_backend)
+ if dtype_backend == "numpy_nullable":
+ df = df.astype({"e": "Int64", "f": "Int64"})
+ else:
+ df = df.astype({"e": "int64[pyarrow]", "f": "int64[pyarrow]"})
+
+ return df
+
+
+@pytest.mark.db
+class TestPostgreSQLAlchemy(_TestSQLAlchemy):
+ """
+ Test the sqlalchemy backend against an PostgreSQL database.
+
+ """
+
+ flavor = "postgresql"
+ port = 5432
+
+ @classmethod
+ def setup_engine(cls):
+ cls.engine = sqlalchemy.create_engine(
+ f"postgresql+{cls.driver}://postgres:postgres@localhost:{cls.port}/pandas"
+ )
+
+ @classmethod
+ def setup_driver(cls):
+ pytest.importorskip("psycopg2")
+ cls.driver = "psycopg2"
+
+ def test_schema_support(self):
+ from sqlalchemy.engine import Engine
+
+ # only test this for postgresql (schema's not supported in
+ # mysql/sqlite)
+ df = DataFrame({"col1": [1, 2], "col2": [0.1, 0.2], "col3": ["a", "n"]})
+
+ # create a schema
+ with self.conn.begin():
+ self.conn.exec_driver_sql("DROP SCHEMA IF EXISTS other CASCADE;")
+ self.conn.exec_driver_sql("CREATE SCHEMA other;")
+
+ # write dataframe to different schema's
+ assert df.to_sql(name="test_schema_public", con=self.conn, index=False) == 2
+ assert (
+ df.to_sql(
+ name="test_schema_public_explicit",
+ con=self.conn,
+ index=False,
+ schema="public",
+ )
+ == 2
+ )
+ assert (
+ df.to_sql(
+ name="test_schema_other", con=self.conn, index=False, schema="other"
+ )
+ == 2
+ )
+
+ # read dataframes back in
+ res1 = sql.read_sql_table("test_schema_public", self.conn)
+ tm.assert_frame_equal(df, res1)
+ res2 = sql.read_sql_table("test_schema_public_explicit", self.conn)
+ tm.assert_frame_equal(df, res2)
+ res3 = sql.read_sql_table(
+ "test_schema_public_explicit", self.conn, schema="public"
+ )
+ tm.assert_frame_equal(df, res3)
+ res4 = sql.read_sql_table("test_schema_other", self.conn, schema="other")
+ tm.assert_frame_equal(df, res4)
+ msg = "Table test_schema_other not found"
+ with pytest.raises(ValueError, match=msg):
+ sql.read_sql_table("test_schema_other", self.conn, schema="public")
+
+ # different if_exists options
+
+ # create a schema
+ with self.conn.begin():
+ self.conn.exec_driver_sql("DROP SCHEMA IF EXISTS other CASCADE;")
+ self.conn.exec_driver_sql("CREATE SCHEMA other;")
+
+ # write dataframe with different if_exists options
+ assert (
+ df.to_sql(
+ name="test_schema_other", con=self.conn, schema="other", index=False
+ )
+ == 2
+ )
+ df.to_sql(
+ name="test_schema_other",
+ con=self.conn,
+ schema="other",
+ index=False,
+ if_exists="replace",
+ )
+ assert (
+ df.to_sql(
+ name="test_schema_other",
+ con=self.conn,
+ schema="other",
+ index=False,
+ if_exists="append",
+ )
+ == 2
+ )
+ res = sql.read_sql_table("test_schema_other", self.conn, schema="other")
+ tm.assert_frame_equal(concat([df, df], ignore_index=True), res)
+
+ # specifying schema in user-provided meta
+
+ # The schema won't be applied on another Connection
+ # because of transactional schemas
+ if isinstance(self.conn, Engine):
+ engine2 = self.connect()
+ pdsql = sql.SQLDatabase(engine2, schema="other")
+ assert pdsql.to_sql(df, "test_schema_other2", index=False) == 2
+ assert (
+ pdsql.to_sql(df, "test_schema_other2", index=False, if_exists="replace")
+ == 2
+ )
+ assert (
+ pdsql.to_sql(df, "test_schema_other2", index=False, if_exists="append")
+ == 2
+ )
+ res1 = sql.read_sql_table("test_schema_other2", self.conn, schema="other")
+ res2 = pdsql.read_table("test_schema_other2")
+ tm.assert_frame_equal(res1, res2)
+
+ def test_self_join_date_columns(self):
+ # GH 44421
+ from sqlalchemy.engine import Engine
+ from sqlalchemy.sql import text
+
+ create_table = text(
+ """
+ CREATE TABLE person
+ (
+ id serial constraint person_pkey primary key,
+ created_dt timestamp with time zone
+ );
+
+ INSERT INTO person
+ VALUES (1, '2021-01-01T00:00:00Z');
+ """
+ )
+ if isinstance(self.conn, Engine):
+ with self.conn.connect() as con:
+ with con.begin():
+ con.execute(create_table)
+ else:
+ with self.conn.begin():
+ self.conn.execute(create_table)
+
+ sql_query = (
+ 'SELECT * FROM "person" AS p1 INNER JOIN "person" AS p2 ON p1.id = p2.id;'
+ )
+ result = pd.read_sql(sql_query, self.conn)
+ expected = DataFrame(
+ [[1, Timestamp("2021", tz="UTC")] * 2], columns=["id", "created_dt"] * 2
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # Cleanup
+ with sql.SQLDatabase(self.conn, need_transaction=True) as pandasSQL:
+ pandasSQL.drop_table("person")
+
+
+# -----------------------------------------------------------------------------
+# -- Test Sqlite / MySQL fallback
+
+
+class TestSQLiteFallback(SQLiteMixIn, PandasSQLTest):
+ """
+ Test the fallback mode against an in-memory sqlite database.
+
+ """
+
+ flavor = "sqlite"
+
+ @pytest.fixture(autouse=True)
+ def setup_method(self, iris_path, types_data):
+ self.conn = self.connect()
+ self.load_iris_data(iris_path)
+ self.load_types_data(types_data)
+ self.pandasSQL = sql.SQLiteDatabase(self.conn)
+
+ def test_read_sql_parameter(self, sql_strings):
+ self._read_sql_iris_parameter(sql_strings)
+
+ def test_read_sql_named_parameter(self, sql_strings):
+ self._read_sql_iris_named_parameter(sql_strings)
+
+ def test_to_sql_empty(self, test_frame1):
+ self._to_sql_empty(test_frame1)
+
+ def test_create_and_drop_table(self):
+ temp_frame = DataFrame(
+ {"one": [1.0, 2.0, 3.0, 4.0], "two": [4.0, 3.0, 2.0, 1.0]}
+ )
+
+ assert self.pandasSQL.to_sql(temp_frame, "drop_test_frame") == 4
+
+ assert self.pandasSQL.has_table("drop_test_frame")
+
+ self.pandasSQL.drop_table("drop_test_frame")
+
+ assert not self.pandasSQL.has_table("drop_test_frame")
+
+ def test_roundtrip(self, test_frame1):
+ self._roundtrip(test_frame1)
+
+ def test_execute_sql(self):
+ self._execute_sql()
+
+ def test_datetime_date(self):
+ # test support for datetime.date
+ df = DataFrame([date(2014, 1, 1), date(2014, 1, 2)], columns=["a"])
+ assert df.to_sql(name="test_date", con=self.conn, index=False) == 2
+ res = read_sql_query("SELECT * FROM test_date", self.conn)
+ if self.flavor == "sqlite":
+ # comes back as strings
+ tm.assert_frame_equal(res, df.astype(str))
+ elif self.flavor == "mysql":
+ tm.assert_frame_equal(res, df)
+
+ @pytest.mark.parametrize("tz_aware", [False, True])
+ def test_datetime_time(self, tz_aware):
+ # test support for datetime.time, GH #8341
+ if not tz_aware:
+ tz_times = [time(9, 0, 0), time(9, 1, 30)]
+ else:
+ tz_dt = date_range("2013-01-01 09:00:00", periods=2, tz="US/Pacific")
+ tz_times = Series(tz_dt.to_pydatetime()).map(lambda dt: dt.timetz())
+
+ df = DataFrame(tz_times, columns=["a"])
+
+ assert df.to_sql(name="test_time", con=self.conn, index=False) == 2
+ res = read_sql_query("SELECT * FROM test_time", self.conn)
+ if self.flavor == "sqlite":
+ # comes back as strings
+ expected = df.map(lambda _: _.strftime("%H:%M:%S.%f"))
+ tm.assert_frame_equal(res, expected)
+
+ def _get_index_columns(self, tbl_name):
+ ixs = sql.read_sql_query(
+ "SELECT * FROM sqlite_master WHERE type = 'index' "
+ f"AND tbl_name = '{tbl_name}'",
+ self.conn,
+ )
+ ix_cols = []
+ for ix_name in ixs.name:
+ ix_info = sql.read_sql_query(f"PRAGMA index_info({ix_name})", self.conn)
+ ix_cols.append(ix_info.name.tolist())
+ return ix_cols
+
+ def test_to_sql_save_index(self):
+ self._to_sql_save_index()
+
+ def test_transactions(self):
+ self._transaction_test()
+
+ def _get_sqlite_column_type(self, table, column):
+ recs = self.conn.execute(f"PRAGMA table_info({table})")
+ for cid, name, ctype, not_null, default, pk in recs:
+ if name == column:
+ return ctype
+ raise ValueError(f"Table {table}, column {column} not found")
+
+ def test_dtype(self):
+ if self.flavor == "mysql":
+ pytest.skip("Not applicable to MySQL legacy")
+ cols = ["A", "B"]
+ data = [(0.8, True), (0.9, None)]
+ df = DataFrame(data, columns=cols)
+ assert df.to_sql(name="dtype_test", con=self.conn) == 2
+ assert df.to_sql(name="dtype_test2", con=self.conn, dtype={"B": "STRING"}) == 2
+
+ # sqlite stores Boolean values as INTEGER
+ assert self._get_sqlite_column_type("dtype_test", "B") == "INTEGER"
+
+ assert self._get_sqlite_column_type("dtype_test2", "B") == "STRING"
+ msg = r"B \(\) not a string"
+ with pytest.raises(ValueError, match=msg):
+ df.to_sql(name="error", con=self.conn, dtype={"B": bool})
+
+ # single dtype
+ assert df.to_sql(name="single_dtype_test", con=self.conn, dtype="STRING") == 2
+ assert self._get_sqlite_column_type("single_dtype_test", "A") == "STRING"
+ assert self._get_sqlite_column_type("single_dtype_test", "B") == "STRING"
+
+ def test_notna_dtype(self):
+ if self.flavor == "mysql":
+ pytest.skip("Not applicable to MySQL legacy")
+
+ cols = {
+ "Bool": Series([True, None]),
+ "Date": Series([datetime(2012, 5, 1), None]),
+ "Int": Series([1, None], dtype="object"),
+ "Float": Series([1.1, None]),
+ }
+ df = DataFrame(cols)
+
+ tbl = "notna_dtype_test"
+ assert df.to_sql(name=tbl, con=self.conn) == 2
+
+ assert self._get_sqlite_column_type(tbl, "Bool") == "INTEGER"
+ assert self._get_sqlite_column_type(tbl, "Date") == "TIMESTAMP"
+ assert self._get_sqlite_column_type(tbl, "Int") == "INTEGER"
+ assert self._get_sqlite_column_type(tbl, "Float") == "REAL"
+
+ def test_illegal_names(self):
+ # For sqlite, these should work fine
+ df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
+
+ msg = "Empty table or column name specified"
+ with pytest.raises(ValueError, match=msg):
+ df.to_sql(name="", con=self.conn)
+
+ for ndx, weird_name in enumerate(
+ [
+ "test_weird_name]",
+ "test_weird_name[",
+ "test_weird_name`",
+ 'test_weird_name"',
+ "test_weird_name'",
+ "_b.test_weird_name_01-30",
+ '"_b.test_weird_name_01-30"',
+ "99beginswithnumber",
+ "12345",
+ "\xe9",
+ ]
+ ):
+ assert df.to_sql(name=weird_name, con=self.conn) == 2
+ sql.table_exists(weird_name, self.conn)
+
+ df2 = DataFrame([[1, 2], [3, 4]], columns=["a", weird_name])
+ c_tbl = f"test_weird_col_name{ndx:d}"
+ assert df2.to_sql(name=c_tbl, con=self.conn) == 2
+ sql.table_exists(c_tbl, self.conn)
+
+
+# -----------------------------------------------------------------------------
+# -- Old tests from 0.13.1 (before refactor using sqlalchemy)
+
+
+_formatters = {
+ datetime: "'{}'".format,
+ str: "'{}'".format,
+ np.str_: "'{}'".format,
+ bytes: "'{}'".format,
+ float: "{:.8f}".format,
+ int: "{:d}".format,
+ type(None): lambda x: "NULL",
+ np.float64: "{:.10f}".format,
+ bool: "'{!s}'".format,
+}
+
+
+def format_query(sql, *args):
+ processed_args = []
+ for arg in args:
+ if isinstance(arg, float) and isna(arg):
+ arg = None
+
+ formatter = _formatters[type(arg)]
+ processed_args.append(formatter(arg))
+
+ return sql % tuple(processed_args)
+
+
+def tquery(query, con=None):
+ """Replace removed sql.tquery function"""
+ with sql.pandasSQL_builder(con) as pandas_sql:
+ res = pandas_sql.execute(query).fetchall()
+ return None if res is None else list(res)
+
+
+class TestXSQLite:
+ def drop_table(self, table_name, conn):
+ cur = conn.cursor()
+ cur.execute(f"DROP TABLE IF EXISTS {sql._get_valid_sqlite_name(table_name)}")
+ conn.commit()
+
+ def test_basic(self, sqlite_buildin):
+ frame = tm.makeTimeDataFrame()
+ assert (
+ sql.to_sql(frame, name="test_table", con=sqlite_buildin, index=False) == 30
+ )
+ result = sql.read_sql("select * from test_table", sqlite_buildin)
+
+ # HACK! Change this once indexes are handled properly.
+ result.index = frame.index
+
+ expected = frame
+ tm.assert_frame_equal(result, frame)
+
+ frame["txt"] = ["a"] * len(frame)
+ frame2 = frame.copy()
+ new_idx = Index(np.arange(len(frame2)), dtype=np.int64) + 10
+ frame2["Idx"] = new_idx.copy()
+ assert (
+ sql.to_sql(frame2, name="test_table2", con=sqlite_buildin, index=False)
+ == 30
+ )
+ result = sql.read_sql(
+ "select * from test_table2", sqlite_buildin, index_col="Idx"
+ )
+ expected = frame.copy()
+ expected.index = new_idx
+ expected.index.name = "Idx"
+ tm.assert_frame_equal(expected, result)
+
+ def test_write_row_by_row(self, sqlite_buildin):
+ frame = tm.makeTimeDataFrame()
+ frame.iloc[0, 0] = np.nan
+ create_sql = sql.get_schema(frame, "test")
+ cur = sqlite_buildin.cursor()
+ cur.execute(create_sql)
+
+ ins = "INSERT INTO test VALUES (%s, %s, %s, %s)"
+ for _, row in frame.iterrows():
+ fmt_sql = format_query(ins, *row)
+ tquery(fmt_sql, con=sqlite_buildin)
+
+ sqlite_buildin.commit()
+
+ result = sql.read_sql("select * from test", con=sqlite_buildin)
+ result.index = frame.index
+ tm.assert_frame_equal(result, frame, rtol=1e-3)
+
+ def test_execute(self, sqlite_buildin):
+ frame = tm.makeTimeDataFrame()
+ create_sql = sql.get_schema(frame, "test")
+ cur = sqlite_buildin.cursor()
+ cur.execute(create_sql)
+ ins = "INSERT INTO test VALUES (?, ?, ?, ?)"
+
+ row = frame.iloc[0]
+ with sql.pandasSQL_builder(sqlite_buildin) as pandas_sql:
+ pandas_sql.execute(ins, tuple(row))
+ sqlite_buildin.commit()
+
+ result = sql.read_sql("select * from test", sqlite_buildin)
+ result.index = frame.index[:1]
+ tm.assert_frame_equal(result, frame[:1])
+
+ def test_schema(self, sqlite_buildin):
+ frame = tm.makeTimeDataFrame()
+ create_sql = sql.get_schema(frame, "test")
+ lines = create_sql.splitlines()
+ for line in lines:
+ tokens = line.split(" ")
+ if len(tokens) == 2 and tokens[0] == "A":
+ assert tokens[1] == "DATETIME"
+
+ create_sql = sql.get_schema(frame, "test", keys=["A", "B"])
+ lines = create_sql.splitlines()
+ assert 'PRIMARY KEY ("A", "B")' in create_sql
+ cur = sqlite_buildin.cursor()
+ cur.execute(create_sql)
+
+ def test_execute_fail(self, sqlite_buildin):
+ create_sql = """
+ CREATE TABLE test
+ (
+ a TEXT,
+ b TEXT,
+ c REAL,
+ PRIMARY KEY (a, b)
+ );
+ """
+ cur = sqlite_buildin.cursor()
+ cur.execute(create_sql)
+
+ with sql.pandasSQL_builder(sqlite_buildin) as pandas_sql:
+ pandas_sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)')
+ pandas_sql.execute('INSERT INTO test VALUES("foo", "baz", 2.567)')
+
+ with pytest.raises(sql.DatabaseError, match="Execution failed on sql"):
+ pandas_sql.execute('INSERT INTO test VALUES("foo", "bar", 7)')
+
+ def test_execute_closed_connection(self):
+ create_sql = """
+ CREATE TABLE test
+ (
+ a TEXT,
+ b TEXT,
+ c REAL,
+ PRIMARY KEY (a, b)
+ );
+ """
+ with contextlib.closing(sqlite3.connect(":memory:")) as conn:
+ cur = conn.cursor()
+ cur.execute(create_sql)
+
+ with sql.pandasSQL_builder(conn) as pandas_sql:
+ pandas_sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)')
+
+ msg = "Cannot operate on a closed database."
+ with pytest.raises(sqlite3.ProgrammingError, match=msg):
+ tquery("select * from test", con=conn)
+
+ def test_keyword_as_column_names(self, sqlite_buildin):
+ df = DataFrame({"From": np.ones(5)})
+ assert sql.to_sql(df, con=sqlite_buildin, name="testkeywords", index=False) == 5
+
+ def test_onecolumn_of_integer(self, sqlite_buildin):
+ # GH 3628
+ # a column_of_integers dataframe should transfer well to sql
+
+ mono_df = DataFrame([1, 2], columns=["c0"])
+ assert sql.to_sql(mono_df, con=sqlite_buildin, name="mono_df", index=False) == 2
+ # computing the sum via sql
+ con_x = sqlite_buildin
+ the_sum = sum(my_c0[0] for my_c0 in con_x.execute("select * from mono_df"))
+ # it should not fail, and gives 3 ( Issue #3628 )
+ assert the_sum == 3
+
+ result = sql.read_sql("select * from mono_df", con_x)
+ tm.assert_frame_equal(result, mono_df)
+
+ def test_if_exists(self, sqlite_buildin):
+ df_if_exists_1 = DataFrame({"col1": [1, 2], "col2": ["A", "B"]})
+ df_if_exists_2 = DataFrame({"col1": [3, 4, 5], "col2": ["C", "D", "E"]})
+ table_name = "table_if_exists"
+ sql_select = f"SELECT * FROM {table_name}"
+
+ msg = "'notvalidvalue' is not valid for if_exists"
+ with pytest.raises(ValueError, match=msg):
+ sql.to_sql(
+ frame=df_if_exists_1,
+ con=sqlite_buildin,
+ name=table_name,
+ if_exists="notvalidvalue",
+ )
+ self.drop_table(table_name, sqlite_buildin)
+
+ # test if_exists='fail'
+ sql.to_sql(
+ frame=df_if_exists_1, con=sqlite_buildin, name=table_name, if_exists="fail"
+ )
+ msg = "Table 'table_if_exists' already exists"
+ with pytest.raises(ValueError, match=msg):
+ sql.to_sql(
+ frame=df_if_exists_1,
+ con=sqlite_buildin,
+ name=table_name,
+ if_exists="fail",
+ )
+ # test if_exists='replace'
+ sql.to_sql(
+ frame=df_if_exists_1,
+ con=sqlite_buildin,
+ name=table_name,
+ if_exists="replace",
+ index=False,
+ )
+ assert tquery(sql_select, con=sqlite_buildin) == [(1, "A"), (2, "B")]
+ assert (
+ sql.to_sql(
+ frame=df_if_exists_2,
+ con=sqlite_buildin,
+ name=table_name,
+ if_exists="replace",
+ index=False,
+ )
+ == 3
+ )
+ assert tquery(sql_select, con=sqlite_buildin) == [(3, "C"), (4, "D"), (5, "E")]
+ self.drop_table(table_name, sqlite_buildin)
+
+ # test if_exists='append'
+ assert (
+ sql.to_sql(
+ frame=df_if_exists_1,
+ con=sqlite_buildin,
+ name=table_name,
+ if_exists="fail",
+ index=False,
+ )
+ == 2
+ )
+ assert tquery(sql_select, con=sqlite_buildin) == [(1, "A"), (2, "B")]
+ assert (
+ sql.to_sql(
+ frame=df_if_exists_2,
+ con=sqlite_buildin,
+ name=table_name,
+ if_exists="append",
+ index=False,
+ )
+ == 3
+ )
+ assert tquery(sql_select, con=sqlite_buildin) == [
+ (1, "A"),
+ (2, "B"),
+ (3, "C"),
+ (4, "D"),
+ (5, "E"),
+ ]
+ self.drop_table(table_name, sqlite_buildin)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_stata.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_stata.py
new file mode 100644
index 0000000000000000000000000000000000000000..7459aa1df8f3e3514720a56bb9935509b5a70e91
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_stata.py
@@ -0,0 +1,2324 @@
+import bz2
+import datetime as dt
+from datetime import datetime
+import gzip
+import io
+import os
+import struct
+import tarfile
+import zipfile
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import CategoricalDtype
+import pandas._testing as tm
+from pandas.core.frame import (
+ DataFrame,
+ Series,
+)
+
+from pandas.io.parsers import read_csv
+from pandas.io.stata import (
+ CategoricalConversionWarning,
+ InvalidColumnName,
+ PossiblePrecisionLoss,
+ StataMissingValue,
+ StataReader,
+ StataWriter,
+ StataWriterUTF8,
+ ValueLabelTypeMismatch,
+ read_stata,
+)
+
+
+@pytest.fixture
+def mixed_frame():
+ return DataFrame(
+ {
+ "a": [1, 2, 3, 4],
+ "b": [1.0, 3.0, 27.0, 81.0],
+ "c": ["Atlanta", "Birmingham", "Cincinnati", "Detroit"],
+ }
+ )
+
+
+@pytest.fixture
+def parsed_114(datapath):
+ dta14_114 = datapath("io", "data", "stata", "stata5_114.dta")
+ parsed_114 = read_stata(dta14_114, convert_dates=True)
+ parsed_114.index.name = "index"
+ return parsed_114
+
+
+class TestStata:
+ def read_dta(self, file):
+ # Legacy default reader configuration
+ return read_stata(file, convert_dates=True)
+
+ def read_csv(self, file):
+ return read_csv(file, parse_dates=True)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_read_empty_dta(self, version):
+ empty_ds = DataFrame(columns=["unit"])
+ # GH 7369, make sure can read a 0-obs dta file
+ with tm.ensure_clean() as path:
+ empty_ds.to_stata(path, write_index=False, version=version)
+ empty_ds2 = read_stata(path)
+ tm.assert_frame_equal(empty_ds, empty_ds2)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_read_empty_dta_with_dtypes(self, version):
+ # GH 46240
+ # Fixing above bug revealed that types are not correctly preserved when
+ # writing empty DataFrames
+ empty_df_typed = DataFrame(
+ {
+ "i8": np.array([0], dtype=np.int8),
+ "i16": np.array([0], dtype=np.int16),
+ "i32": np.array([0], dtype=np.int32),
+ "i64": np.array([0], dtype=np.int64),
+ "u8": np.array([0], dtype=np.uint8),
+ "u16": np.array([0], dtype=np.uint16),
+ "u32": np.array([0], dtype=np.uint32),
+ "u64": np.array([0], dtype=np.uint64),
+ "f32": np.array([0], dtype=np.float32),
+ "f64": np.array([0], dtype=np.float64),
+ }
+ )
+ expected = empty_df_typed.copy()
+ # No uint# support. Downcast since values in range for int#
+ expected["u8"] = expected["u8"].astype(np.int8)
+ expected["u16"] = expected["u16"].astype(np.int16)
+ expected["u32"] = expected["u32"].astype(np.int32)
+ # No int64 supported at all. Downcast since values in range for int32
+ expected["u64"] = expected["u64"].astype(np.int32)
+ expected["i64"] = expected["i64"].astype(np.int32)
+
+ # GH 7369, make sure can read a 0-obs dta file
+ with tm.ensure_clean() as path:
+ empty_df_typed.to_stata(path, write_index=False, version=version)
+ empty_reread = read_stata(path)
+ tm.assert_frame_equal(expected, empty_reread)
+ tm.assert_series_equal(expected.dtypes, empty_reread.dtypes)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_read_index_col_none(self, version):
+ df = DataFrame({"a": range(5), "b": ["b1", "b2", "b3", "b4", "b5"]})
+ # GH 7369, make sure can read a 0-obs dta file
+ with tm.ensure_clean() as path:
+ df.to_stata(path, write_index=False, version=version)
+ read_df = read_stata(path)
+
+ assert isinstance(read_df.index, pd.RangeIndex)
+ expected = df.copy()
+ expected["a"] = expected["a"].astype(np.int32)
+ tm.assert_frame_equal(read_df, expected, check_index_type=True)
+
+ @pytest.mark.parametrize("file", ["stata1_114", "stata1_117"])
+ def test_read_dta1(self, file, datapath):
+ file = datapath("io", "data", "stata", f"{file}.dta")
+ parsed = self.read_dta(file)
+
+ # Pandas uses np.nan as missing value.
+ # Thus, all columns will be of type float, regardless of their name.
+ expected = DataFrame(
+ [(np.nan, np.nan, np.nan, np.nan, np.nan)],
+ columns=["float_miss", "double_miss", "byte_miss", "int_miss", "long_miss"],
+ )
+
+ # this is an oddity as really the nan should be float64, but
+ # the casting doesn't fail so need to match stata here
+ expected["float_miss"] = expected["float_miss"].astype(np.float32)
+
+ tm.assert_frame_equal(parsed, expected)
+
+ @pytest.mark.filterwarnings("always")
+ def test_read_dta2(self, datapath):
+ expected = DataFrame.from_records(
+ [
+ (
+ datetime(2006, 11, 19, 23, 13, 20),
+ 1479596223000,
+ datetime(2010, 1, 20),
+ datetime(2010, 1, 8),
+ datetime(2010, 1, 1),
+ datetime(1974, 7, 1),
+ datetime(2010, 1, 1),
+ datetime(2010, 1, 1),
+ ),
+ (
+ datetime(1959, 12, 31, 20, 3, 20),
+ -1479590,
+ datetime(1953, 10, 2),
+ datetime(1948, 6, 10),
+ datetime(1955, 1, 1),
+ datetime(1955, 7, 1),
+ datetime(1955, 1, 1),
+ datetime(2, 1, 1),
+ ),
+ (pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT),
+ ],
+ columns=[
+ "datetime_c",
+ "datetime_big_c",
+ "date",
+ "weekly_date",
+ "monthly_date",
+ "quarterly_date",
+ "half_yearly_date",
+ "yearly_date",
+ ],
+ )
+ expected["yearly_date"] = expected["yearly_date"].astype("O")
+
+ path1 = datapath("io", "data", "stata", "stata2_114.dta")
+ path2 = datapath("io", "data", "stata", "stata2_115.dta")
+ path3 = datapath("io", "data", "stata", "stata2_117.dta")
+
+ with tm.assert_produces_warning(UserWarning):
+ parsed_114 = self.read_dta(path1)
+ with tm.assert_produces_warning(UserWarning):
+ parsed_115 = self.read_dta(path2)
+ with tm.assert_produces_warning(UserWarning):
+ parsed_117 = self.read_dta(path3)
+ # 113 is buggy due to limits of date format support in Stata
+ # parsed_113 = self.read_dta(
+ # datapath("io", "data", "stata", "stata2_113.dta")
+ # )
+
+ # buggy test because of the NaT comparison on certain platforms
+ # Format 113 test fails since it does not support tc and tC formats
+ # tm.assert_frame_equal(parsed_113, expected)
+ tm.assert_frame_equal(parsed_114, expected, check_datetimelike_compat=True)
+ tm.assert_frame_equal(parsed_115, expected, check_datetimelike_compat=True)
+ tm.assert_frame_equal(parsed_117, expected, check_datetimelike_compat=True)
+
+ @pytest.mark.parametrize(
+ "file", ["stata3_113", "stata3_114", "stata3_115", "stata3_117"]
+ )
+ def test_read_dta3(self, file, datapath):
+ file = datapath("io", "data", "stata", f"{file}.dta")
+ parsed = self.read_dta(file)
+
+ # match stata here
+ expected = self.read_csv(datapath("io", "data", "stata", "stata3.csv"))
+ expected = expected.astype(np.float32)
+ expected["year"] = expected["year"].astype(np.int16)
+ expected["quarter"] = expected["quarter"].astype(np.int8)
+
+ tm.assert_frame_equal(parsed, expected)
+
+ @pytest.mark.parametrize(
+ "file", ["stata4_113", "stata4_114", "stata4_115", "stata4_117"]
+ )
+ def test_read_dta4(self, file, datapath):
+ file = datapath("io", "data", "stata", f"{file}.dta")
+ parsed = self.read_dta(file)
+
+ expected = DataFrame.from_records(
+ [
+ ["one", "ten", "one", "one", "one"],
+ ["two", "nine", "two", "two", "two"],
+ ["three", "eight", "three", "three", "three"],
+ ["four", "seven", 4, "four", "four"],
+ ["five", "six", 5, np.nan, "five"],
+ ["six", "five", 6, np.nan, "six"],
+ ["seven", "four", 7, np.nan, "seven"],
+ ["eight", "three", 8, np.nan, "eight"],
+ ["nine", "two", 9, np.nan, "nine"],
+ ["ten", "one", "ten", np.nan, "ten"],
+ ],
+ columns=[
+ "fully_labeled",
+ "fully_labeled2",
+ "incompletely_labeled",
+ "labeled_with_missings",
+ "float_labelled",
+ ],
+ )
+
+ # these are all categoricals
+ for col in expected:
+ orig = expected[col].copy()
+
+ categories = np.asarray(expected["fully_labeled"][orig.notna()])
+ if col == "incompletely_labeled":
+ categories = orig
+
+ cat = orig.astype("category")._values
+ cat = cat.set_categories(categories, ordered=True)
+ cat.categories.rename(None, inplace=True)
+
+ expected[col] = cat
+
+ # stata doesn't save .category metadata
+ tm.assert_frame_equal(parsed, expected)
+
+ # File containing strls
+ def test_read_dta12(self, datapath):
+ parsed_117 = self.read_dta(datapath("io", "data", "stata", "stata12_117.dta"))
+ expected = DataFrame.from_records(
+ [
+ [1, "abc", "abcdefghi"],
+ [3, "cba", "qwertywertyqwerty"],
+ [93, "", "strl"],
+ ],
+ columns=["x", "y", "z"],
+ )
+
+ tm.assert_frame_equal(parsed_117, expected, check_dtype=False)
+
+ def test_read_dta18(self, datapath):
+ parsed_118 = self.read_dta(datapath("io", "data", "stata", "stata14_118.dta"))
+ parsed_118["Bytes"] = parsed_118["Bytes"].astype("O")
+ expected = DataFrame.from_records(
+ [
+ ["Cat", "Bogota", "Bogotá", 1, 1.0, "option b Ünicode", 1.0],
+ ["Dog", "Boston", "Uzunköprü", np.nan, np.nan, np.nan, np.nan],
+ ["Plane", "Rome", "Tromsø", 0, 0.0, "option a", 0.0],
+ ["Potato", "Tokyo", "Elâzığ", -4, 4.0, 4, 4], # noqa: RUF001
+ ["", "", "", 0, 0.3332999, "option a", 1 / 3.0],
+ ],
+ columns=[
+ "Things",
+ "Cities",
+ "Unicode_Cities_Strl",
+ "Ints",
+ "Floats",
+ "Bytes",
+ "Longs",
+ ],
+ )
+ expected["Floats"] = expected["Floats"].astype(np.float32)
+ for col in parsed_118.columns:
+ tm.assert_almost_equal(parsed_118[col], expected[col])
+
+ with StataReader(datapath("io", "data", "stata", "stata14_118.dta")) as rdr:
+ vl = rdr.variable_labels()
+ vl_expected = {
+ "Unicode_Cities_Strl": "Here are some strls with Ünicode chars",
+ "Longs": "long data",
+ "Things": "Here are some things",
+ "Bytes": "byte data",
+ "Ints": "int data",
+ "Cities": "Here are some cities",
+ "Floats": "float data",
+ }
+ tm.assert_dict_equal(vl, vl_expected)
+
+ assert rdr.data_label == "This is a Ünicode data label"
+
+ def test_read_write_dta5(self):
+ original = DataFrame(
+ [(np.nan, np.nan, np.nan, np.nan, np.nan)],
+ columns=["float_miss", "double_miss", "byte_miss", "int_miss", "long_miss"],
+ )
+ original.index.name = "index"
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path, convert_dates=None)
+ written_and_read_again = self.read_dta(path)
+
+ expected = original.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
+
+ def test_write_dta6(self, datapath):
+ original = self.read_csv(datapath("io", "data", "stata", "stata3.csv"))
+ original.index.name = "index"
+ original.index = original.index.astype(np.int32)
+ original["year"] = original["year"].astype(np.int32)
+ original["quarter"] = original["quarter"].astype(np.int32)
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path, convert_dates=None)
+ written_and_read_again = self.read_dta(path)
+ tm.assert_frame_equal(
+ written_and_read_again.set_index("index"),
+ original,
+ check_index_type=False,
+ )
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_read_write_dta10(self, version):
+ original = DataFrame(
+ data=[["string", "object", 1, 1.1, np.datetime64("2003-12-25")]],
+ columns=["string", "object", "integer", "floating", "datetime"],
+ )
+ original["object"] = Series(original["object"], dtype=object)
+ original.index.name = "index"
+ original.index = original.index.astype(np.int32)
+ original["integer"] = original["integer"].astype(np.int32)
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path, convert_dates={"datetime": "tc"}, version=version)
+ written_and_read_again = self.read_dta(path)
+ # original.index is np.int32, read index is np.int64
+ tm.assert_frame_equal(
+ written_and_read_again.set_index("index"),
+ original,
+ check_index_type=False,
+ )
+
+ def test_stata_doc_examples(self):
+ with tm.ensure_clean() as path:
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)), columns=list("AB")
+ )
+ df.to_stata(path)
+
+ def test_write_preserves_original(self):
+ # 9795
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 4)), columns=list("abcd")
+ )
+ df.loc[2, "a":"c"] = np.nan
+ df_copy = df.copy()
+ with tm.ensure_clean() as path:
+ df.to_stata(path, write_index=False)
+ tm.assert_frame_equal(df, df_copy)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_encoding(self, version, datapath):
+ # GH 4626, proper encoding handling
+ raw = read_stata(datapath("io", "data", "stata", "stata1_encoding.dta"))
+ encoded = read_stata(datapath("io", "data", "stata", "stata1_encoding.dta"))
+ result = encoded.kreis1849[0]
+
+ expected = raw.kreis1849[0]
+ assert result == expected
+ assert isinstance(result, str)
+
+ with tm.ensure_clean() as path:
+ encoded.to_stata(path, write_index=False, version=version)
+ reread_encoded = read_stata(path)
+ tm.assert_frame_equal(encoded, reread_encoded)
+
+ def test_read_write_dta11(self):
+ original = DataFrame(
+ [(1, 2, 3, 4)],
+ columns=[
+ "good",
+ "b\u00E4d",
+ "8number",
+ "astringwithmorethan32characters______",
+ ],
+ )
+ formatted = DataFrame(
+ [(1, 2, 3, 4)],
+ columns=["good", "b_d", "_8number", "astringwithmorethan32characters_"],
+ )
+ formatted.index.name = "index"
+ formatted = formatted.astype(np.int32)
+
+ with tm.ensure_clean() as path:
+ with tm.assert_produces_warning(InvalidColumnName):
+ original.to_stata(path, convert_dates=None)
+
+ written_and_read_again = self.read_dta(path)
+
+ expected = formatted.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_read_write_dta12(self, version):
+ original = DataFrame(
+ [(1, 2, 3, 4, 5, 6)],
+ columns=[
+ "astringwithmorethan32characters_1",
+ "astringwithmorethan32characters_2",
+ "+",
+ "-",
+ "short",
+ "delete",
+ ],
+ )
+ formatted = DataFrame(
+ [(1, 2, 3, 4, 5, 6)],
+ columns=[
+ "astringwithmorethan32characters_",
+ "_0astringwithmorethan32character",
+ "_",
+ "_1_",
+ "_short",
+ "_delete",
+ ],
+ )
+ formatted.index.name = "index"
+ formatted = formatted.astype(np.int32)
+
+ with tm.ensure_clean() as path:
+ with tm.assert_produces_warning(InvalidColumnName):
+ original.to_stata(path, convert_dates=None, version=version)
+ # should get a warning for that format.
+
+ written_and_read_again = self.read_dta(path)
+
+ expected = formatted.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
+
+ def test_read_write_dta13(self):
+ s1 = Series(2**9, dtype=np.int16)
+ s2 = Series(2**17, dtype=np.int32)
+ s3 = Series(2**33, dtype=np.int64)
+ original = DataFrame({"int16": s1, "int32": s2, "int64": s3})
+ original.index.name = "index"
+
+ formatted = original
+ formatted["int64"] = formatted["int64"].astype(np.float64)
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path)
+ written_and_read_again = self.read_dta(path)
+
+ expected = formatted.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ @pytest.mark.parametrize(
+ "file", ["stata5_113", "stata5_114", "stata5_115", "stata5_117"]
+ )
+ def test_read_write_reread_dta14(self, file, parsed_114, version, datapath):
+ file = datapath("io", "data", "stata", f"{file}.dta")
+ parsed = self.read_dta(file)
+ parsed.index.name = "index"
+
+ tm.assert_frame_equal(parsed_114, parsed)
+
+ with tm.ensure_clean() as path:
+ parsed_114.to_stata(path, convert_dates={"date_td": "td"}, version=version)
+ written_and_read_again = self.read_dta(path)
+
+ expected = parsed_114.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
+
+ @pytest.mark.parametrize(
+ "file", ["stata6_113", "stata6_114", "stata6_115", "stata6_117"]
+ )
+ def test_read_write_reread_dta15(self, file, datapath):
+ expected = self.read_csv(datapath("io", "data", "stata", "stata6.csv"))
+ expected["byte_"] = expected["byte_"].astype(np.int8)
+ expected["int_"] = expected["int_"].astype(np.int16)
+ expected["long_"] = expected["long_"].astype(np.int32)
+ expected["float_"] = expected["float_"].astype(np.float32)
+ expected["double_"] = expected["double_"].astype(np.float64)
+ expected["date_td"] = expected["date_td"].apply(
+ datetime.strptime, args=("%Y-%m-%d",)
+ )
+
+ file = datapath("io", "data", "stata", f"{file}.dta")
+ parsed = self.read_dta(file)
+
+ tm.assert_frame_equal(expected, parsed)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_timestamp_and_label(self, version):
+ original = DataFrame([(1,)], columns=["variable"])
+ time_stamp = datetime(2000, 2, 29, 14, 21)
+ data_label = "This is a data file."
+ with tm.ensure_clean() as path:
+ original.to_stata(
+ path, time_stamp=time_stamp, data_label=data_label, version=version
+ )
+
+ with StataReader(path) as reader:
+ assert reader.time_stamp == "29 Feb 2000 14:21"
+ assert reader.data_label == data_label
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_invalid_timestamp(self, version):
+ original = DataFrame([(1,)], columns=["variable"])
+ time_stamp = "01 Jan 2000, 00:00:00"
+ with tm.ensure_clean() as path:
+ msg = "time_stamp should be datetime type"
+ with pytest.raises(ValueError, match=msg):
+ original.to_stata(path, time_stamp=time_stamp, version=version)
+ assert not os.path.isfile(path)
+
+ def test_numeric_column_names(self):
+ original = DataFrame(np.reshape(np.arange(25.0), (5, 5)))
+ original.index.name = "index"
+ with tm.ensure_clean() as path:
+ # should get a warning for that format.
+ with tm.assert_produces_warning(InvalidColumnName):
+ original.to_stata(path)
+
+ written_and_read_again = self.read_dta(path)
+
+ written_and_read_again = written_and_read_again.set_index("index")
+ columns = list(written_and_read_again.columns)
+ convert_col_name = lambda x: int(x[1])
+ written_and_read_again.columns = map(convert_col_name, columns)
+
+ expected = original.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(expected, written_and_read_again)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_nan_to_missing_value(self, version):
+ s1 = Series(np.arange(4.0), dtype=np.float32)
+ s2 = Series(np.arange(4.0), dtype=np.float64)
+ s1[::2] = np.nan
+ s2[1::2] = np.nan
+ original = DataFrame({"s1": s1, "s2": s2})
+ original.index.name = "index"
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path, version=version)
+ written_and_read_again = self.read_dta(path)
+
+ written_and_read_again = written_and_read_again.set_index("index")
+ expected = original.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(written_and_read_again, expected)
+
+ def test_no_index(self):
+ columns = ["x", "y"]
+ original = DataFrame(np.reshape(np.arange(10.0), (5, 2)), columns=columns)
+ original.index.name = "index_not_written"
+ with tm.ensure_clean() as path:
+ original.to_stata(path, write_index=False)
+ written_and_read_again = self.read_dta(path)
+ with pytest.raises(KeyError, match=original.index.name):
+ written_and_read_again["index_not_written"]
+
+ def test_string_no_dates(self):
+ s1 = Series(["a", "A longer string"])
+ s2 = Series([1.0, 2.0], dtype=np.float64)
+ original = DataFrame({"s1": s1, "s2": s2})
+ original.index.name = "index"
+ with tm.ensure_clean() as path:
+ original.to_stata(path)
+ written_and_read_again = self.read_dta(path)
+
+ expected = original.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
+
+ def test_large_value_conversion(self):
+ s0 = Series([1, 99], dtype=np.int8)
+ s1 = Series([1, 127], dtype=np.int8)
+ s2 = Series([1, 2**15 - 1], dtype=np.int16)
+ s3 = Series([1, 2**63 - 1], dtype=np.int64)
+ original = DataFrame({"s0": s0, "s1": s1, "s2": s2, "s3": s3})
+ original.index.name = "index"
+ with tm.ensure_clean() as path:
+ with tm.assert_produces_warning(PossiblePrecisionLoss):
+ original.to_stata(path)
+
+ written_and_read_again = self.read_dta(path)
+
+ modified = original.copy()
+ modified["s1"] = Series(modified["s1"], dtype=np.int16)
+ modified["s2"] = Series(modified["s2"], dtype=np.int32)
+ modified["s3"] = Series(modified["s3"], dtype=np.float64)
+ modified.index = original.index.astype(np.int32)
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), modified)
+
+ def test_dates_invalid_column(self):
+ original = DataFrame([datetime(2006, 11, 19, 23, 13, 20)])
+ original.index.name = "index"
+ with tm.ensure_clean() as path:
+ with tm.assert_produces_warning(InvalidColumnName):
+ original.to_stata(path, convert_dates={0: "tc"})
+
+ written_and_read_again = self.read_dta(path)
+
+ modified = original.copy()
+ modified.columns = ["_0"]
+ modified.index = original.index.astype(np.int32)
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), modified)
+
+ def test_105(self, datapath):
+ # Data obtained from:
+ # http://go.worldbank.org/ZXY29PVJ21
+ dpath = datapath("io", "data", "stata", "S4_EDUC1.dta")
+ df = read_stata(dpath)
+ df0 = [[1, 1, 3, -2], [2, 1, 2, -2], [4, 1, 1, -2]]
+ df0 = DataFrame(df0)
+ df0.columns = ["clustnum", "pri_schl", "psch_num", "psch_dis"]
+ df0["clustnum"] = df0["clustnum"].astype(np.int16)
+ df0["pri_schl"] = df0["pri_schl"].astype(np.int8)
+ df0["psch_num"] = df0["psch_num"].astype(np.int8)
+ df0["psch_dis"] = df0["psch_dis"].astype(np.float32)
+ tm.assert_frame_equal(df.head(3), df0)
+
+ def test_value_labels_old_format(self, datapath):
+ # GH 19417
+ #
+ # Test that value_labels() returns an empty dict if the file format
+ # predates supporting value labels.
+ dpath = datapath("io", "data", "stata", "S4_EDUC1.dta")
+ with StataReader(dpath) as reader:
+ assert reader.value_labels() == {}
+
+ def test_date_export_formats(self):
+ columns = ["tc", "td", "tw", "tm", "tq", "th", "ty"]
+ conversions = {c: c for c in columns}
+ data = [datetime(2006, 11, 20, 23, 13, 20)] * len(columns)
+ original = DataFrame([data], columns=columns)
+ original.index.name = "index"
+ expected_values = [
+ datetime(2006, 11, 20, 23, 13, 20), # Time
+ datetime(2006, 11, 20), # Day
+ datetime(2006, 11, 19), # Week
+ datetime(2006, 11, 1), # Month
+ datetime(2006, 10, 1), # Quarter year
+ datetime(2006, 7, 1), # Half year
+ datetime(2006, 1, 1),
+ ] # Year
+
+ expected = DataFrame(
+ [expected_values],
+ index=pd.Index([0], dtype=np.int32, name="index"),
+ columns=columns,
+ )
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path, convert_dates=conversions)
+ written_and_read_again = self.read_dta(path)
+
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
+
+ def test_write_missing_strings(self):
+ original = DataFrame([["1"], [None]], columns=["foo"])
+
+ expected = DataFrame(
+ [["1"], [""]],
+ index=pd.Index([0, 1], dtype=np.int32, name="index"),
+ columns=["foo"],
+ )
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path)
+ written_and_read_again = self.read_dta(path)
+
+ tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ @pytest.mark.parametrize("byteorder", [">", "<"])
+ def test_bool_uint(self, byteorder, version):
+ s0 = Series([0, 1, True], dtype=np.bool_)
+ s1 = Series([0, 1, 100], dtype=np.uint8)
+ s2 = Series([0, 1, 255], dtype=np.uint8)
+ s3 = Series([0, 1, 2**15 - 100], dtype=np.uint16)
+ s4 = Series([0, 1, 2**16 - 1], dtype=np.uint16)
+ s5 = Series([0, 1, 2**31 - 100], dtype=np.uint32)
+ s6 = Series([0, 1, 2**32 - 1], dtype=np.uint32)
+
+ original = DataFrame(
+ {"s0": s0, "s1": s1, "s2": s2, "s3": s3, "s4": s4, "s5": s5, "s6": s6}
+ )
+ original.index.name = "index"
+ expected = original.copy()
+ expected.index = original.index.astype(np.int32)
+ expected_types = (
+ np.int8,
+ np.int8,
+ np.int16,
+ np.int16,
+ np.int32,
+ np.int32,
+ np.float64,
+ )
+ for c, t in zip(expected.columns, expected_types):
+ expected[c] = expected[c].astype(t)
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path, byteorder=byteorder, version=version)
+ written_and_read_again = self.read_dta(path)
+
+ written_and_read_again = written_and_read_again.set_index("index")
+ tm.assert_frame_equal(written_and_read_again, expected)
+
+ def test_variable_labels(self, datapath):
+ with StataReader(datapath("io", "data", "stata", "stata7_115.dta")) as rdr:
+ sr_115 = rdr.variable_labels()
+ with StataReader(datapath("io", "data", "stata", "stata7_117.dta")) as rdr:
+ sr_117 = rdr.variable_labels()
+ keys = ("var1", "var2", "var3")
+ labels = ("label1", "label2", "label3")
+ for k, v in sr_115.items():
+ assert k in sr_117
+ assert v == sr_117[k]
+ assert k in keys
+ assert v in labels
+
+ def test_minimal_size_col(self):
+ str_lens = (1, 100, 244)
+ s = {}
+ for str_len in str_lens:
+ s["s" + str(str_len)] = Series(
+ ["a" * str_len, "b" * str_len, "c" * str_len]
+ )
+ original = DataFrame(s)
+ with tm.ensure_clean() as path:
+ original.to_stata(path, write_index=False)
+
+ with StataReader(path) as sr:
+ sr._ensure_open() # The `_*list` variables are initialized here
+ for variable, fmt, typ in zip(sr._varlist, sr._fmtlist, sr._typlist):
+ assert int(variable[1:]) == int(fmt[1:-1])
+ assert int(variable[1:]) == typ
+
+ def test_excessively_long_string(self):
+ str_lens = (1, 244, 500)
+ s = {}
+ for str_len in str_lens:
+ s["s" + str(str_len)] = Series(
+ ["a" * str_len, "b" * str_len, "c" * str_len]
+ )
+ original = DataFrame(s)
+ msg = (
+ r"Fixed width strings in Stata \.dta files are limited to 244 "
+ r"\(or fewer\)\ncharacters\. Column 's500' does not satisfy "
+ r"this restriction\. Use the\n'version=117' parameter to write "
+ r"the newer \(Stata 13 and later\) format\."
+ )
+ with pytest.raises(ValueError, match=msg):
+ with tm.ensure_clean() as path:
+ original.to_stata(path)
+
+ def test_missing_value_generator(self):
+ types = ("b", "h", "l")
+ df = DataFrame([[0.0]], columns=["float_"])
+ with tm.ensure_clean() as path:
+ df.to_stata(path)
+ with StataReader(path) as rdr:
+ valid_range = rdr.VALID_RANGE
+ expected_values = ["." + chr(97 + i) for i in range(26)]
+ expected_values.insert(0, ".")
+ for t in types:
+ offset = valid_range[t][1]
+ for i in range(0, 27):
+ val = StataMissingValue(offset + 1 + i)
+ assert val.string == expected_values[i]
+
+ # Test extremes for floats
+ val = StataMissingValue(struct.unpack(" DataFrame:
+ """
+ Emulate the categorical casting behavior we expect from roundtripping.
+ """
+ for col in from_frame:
+ ser = from_frame[col]
+ if isinstance(ser.dtype, CategoricalDtype):
+ cat = ser._values.remove_unused_categories()
+ if cat.categories.dtype == object:
+ categories = pd.Index._with_infer(cat.categories._values)
+ cat = cat.set_categories(categories)
+ from_frame[col] = cat
+ return from_frame
+
+ def test_iterator(self, datapath):
+ fname = datapath("io", "data", "stata", "stata3_117.dta")
+
+ parsed = read_stata(fname)
+
+ with read_stata(fname, iterator=True) as itr:
+ chunk = itr.read(5)
+ tm.assert_frame_equal(parsed.iloc[0:5, :], chunk)
+
+ with read_stata(fname, chunksize=5) as itr:
+ chunk = list(itr)
+ tm.assert_frame_equal(parsed.iloc[0:5, :], chunk[0])
+
+ with read_stata(fname, iterator=True) as itr:
+ chunk = itr.get_chunk(5)
+ tm.assert_frame_equal(parsed.iloc[0:5, :], chunk)
+
+ with read_stata(fname, chunksize=5) as itr:
+ chunk = itr.get_chunk()
+ tm.assert_frame_equal(parsed.iloc[0:5, :], chunk)
+
+ # GH12153
+ with read_stata(fname, chunksize=4) as itr:
+ from_chunks = pd.concat(itr)
+ tm.assert_frame_equal(parsed, from_chunks)
+
+ @pytest.mark.filterwarnings("ignore::UserWarning")
+ @pytest.mark.parametrize(
+ "file",
+ [
+ "stata2_115",
+ "stata3_115",
+ "stata4_115",
+ "stata5_115",
+ "stata6_115",
+ "stata7_115",
+ "stata8_115",
+ "stata9_115",
+ "stata10_115",
+ "stata11_115",
+ ],
+ )
+ @pytest.mark.parametrize("chunksize", [1, 2])
+ @pytest.mark.parametrize("convert_categoricals", [False, True])
+ @pytest.mark.parametrize("convert_dates", [False, True])
+ def test_read_chunks_115(
+ self, file, chunksize, convert_categoricals, convert_dates, datapath
+ ):
+ fname = datapath("io", "data", "stata", f"{file}.dta")
+
+ # Read the whole file
+ parsed = read_stata(
+ fname,
+ convert_categoricals=convert_categoricals,
+ convert_dates=convert_dates,
+ )
+
+ # Compare to what we get when reading by chunk
+ with read_stata(
+ fname,
+ iterator=True,
+ convert_dates=convert_dates,
+ convert_categoricals=convert_categoricals,
+ ) as itr:
+ pos = 0
+ for j in range(5):
+ try:
+ chunk = itr.read(chunksize)
+ except StopIteration:
+ break
+ from_frame = parsed.iloc[pos : pos + chunksize, :].copy()
+ from_frame = self._convert_categorical(from_frame)
+ tm.assert_frame_equal(
+ from_frame, chunk, check_dtype=False, check_datetimelike_compat=True
+ )
+ pos += chunksize
+
+ def test_read_chunks_columns(self, datapath):
+ fname = datapath("io", "data", "stata", "stata3_117.dta")
+ columns = ["quarter", "cpi", "m1"]
+ chunksize = 2
+
+ parsed = read_stata(fname, columns=columns)
+ with read_stata(fname, iterator=True) as itr:
+ pos = 0
+ for j in range(5):
+ chunk = itr.read(chunksize, columns=columns)
+ if chunk is None:
+ break
+ from_frame = parsed.iloc[pos : pos + chunksize, :]
+ tm.assert_frame_equal(from_frame, chunk, check_dtype=False)
+ pos += chunksize
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_write_variable_labels(self, version, mixed_frame):
+ # GH 13631, add support for writing variable labels
+ mixed_frame.index.name = "index"
+ variable_labels = {"a": "City Rank", "b": "City Exponent", "c": "City"}
+ with tm.ensure_clean() as path:
+ mixed_frame.to_stata(path, variable_labels=variable_labels, version=version)
+ with StataReader(path) as sr:
+ read_labels = sr.variable_labels()
+ expected_labels = {
+ "index": "",
+ "a": "City Rank",
+ "b": "City Exponent",
+ "c": "City",
+ }
+ assert read_labels == expected_labels
+
+ variable_labels["index"] = "The Index"
+ with tm.ensure_clean() as path:
+ mixed_frame.to_stata(path, variable_labels=variable_labels, version=version)
+ with StataReader(path) as sr:
+ read_labels = sr.variable_labels()
+ assert read_labels == variable_labels
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_invalid_variable_labels(self, version, mixed_frame):
+ mixed_frame.index.name = "index"
+ variable_labels = {"a": "very long" * 10, "b": "City Exponent", "c": "City"}
+ with tm.ensure_clean() as path:
+ msg = "Variable labels must be 80 characters or fewer"
+ with pytest.raises(ValueError, match=msg):
+ mixed_frame.to_stata(
+ path, variable_labels=variable_labels, version=version
+ )
+
+ @pytest.mark.parametrize("version", [114, 117])
+ def test_invalid_variable_label_encoding(self, version, mixed_frame):
+ mixed_frame.index.name = "index"
+ variable_labels = {"a": "very long" * 10, "b": "City Exponent", "c": "City"}
+ variable_labels["a"] = "invalid character Œ"
+ with tm.ensure_clean() as path:
+ with pytest.raises(
+ ValueError, match="Variable labels must contain only characters"
+ ):
+ mixed_frame.to_stata(
+ path, variable_labels=variable_labels, version=version
+ )
+
+ def test_write_variable_label_errors(self, mixed_frame):
+ values = ["\u03A1", "\u0391", "\u039D", "\u0394", "\u0391", "\u03A3"]
+
+ variable_labels_utf8 = {
+ "a": "City Rank",
+ "b": "City Exponent",
+ "c": "".join(values),
+ }
+
+ msg = (
+ "Variable labels must contain only characters that can be "
+ "encoded in Latin-1"
+ )
+ with pytest.raises(ValueError, match=msg):
+ with tm.ensure_clean() as path:
+ mixed_frame.to_stata(path, variable_labels=variable_labels_utf8)
+
+ variable_labels_long = {
+ "a": "City Rank",
+ "b": "City Exponent",
+ "c": "A very, very, very long variable label "
+ "that is too long for Stata which means "
+ "that it has more than 80 characters",
+ }
+
+ msg = "Variable labels must be 80 characters or fewer"
+ with pytest.raises(ValueError, match=msg):
+ with tm.ensure_clean() as path:
+ mixed_frame.to_stata(path, variable_labels=variable_labels_long)
+
+ def test_default_date_conversion(self):
+ # GH 12259
+ dates = [
+ dt.datetime(1999, 12, 31, 12, 12, 12, 12000),
+ dt.datetime(2012, 12, 21, 12, 21, 12, 21000),
+ dt.datetime(1776, 7, 4, 7, 4, 7, 4000),
+ ]
+ original = DataFrame(
+ {
+ "nums": [1.0, 2.0, 3.0],
+ "strs": ["apple", "banana", "cherry"],
+ "dates": dates,
+ }
+ )
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path, write_index=False)
+ reread = read_stata(path, convert_dates=True)
+ tm.assert_frame_equal(original, reread)
+
+ original.to_stata(path, write_index=False, convert_dates={"dates": "tc"})
+ direct = read_stata(path, convert_dates=True)
+ tm.assert_frame_equal(reread, direct)
+
+ dates_idx = original.columns.tolist().index("dates")
+ original.to_stata(path, write_index=False, convert_dates={dates_idx: "tc"})
+ direct = read_stata(path, convert_dates=True)
+ tm.assert_frame_equal(reread, direct)
+
+ def test_unsupported_type(self):
+ original = DataFrame({"a": [1 + 2j, 2 + 4j]})
+
+ msg = "Data type complex128 not supported"
+ with pytest.raises(NotImplementedError, match=msg):
+ with tm.ensure_clean() as path:
+ original.to_stata(path)
+
+ def test_unsupported_datetype(self):
+ dates = [
+ dt.datetime(1999, 12, 31, 12, 12, 12, 12000),
+ dt.datetime(2012, 12, 21, 12, 21, 12, 21000),
+ dt.datetime(1776, 7, 4, 7, 4, 7, 4000),
+ ]
+ original = DataFrame(
+ {
+ "nums": [1.0, 2.0, 3.0],
+ "strs": ["apple", "banana", "cherry"],
+ "dates": dates,
+ }
+ )
+
+ msg = "Format %tC not implemented"
+ with pytest.raises(NotImplementedError, match=msg):
+ with tm.ensure_clean() as path:
+ original.to_stata(path, convert_dates={"dates": "tC"})
+
+ dates = pd.date_range("1-1-1990", periods=3, tz="Asia/Hong_Kong")
+ original = DataFrame(
+ {
+ "nums": [1.0, 2.0, 3.0],
+ "strs": ["apple", "banana", "cherry"],
+ "dates": dates,
+ }
+ )
+ with pytest.raises(NotImplementedError, match="Data type datetime64"):
+ with tm.ensure_clean() as path:
+ original.to_stata(path)
+
+ def test_repeated_column_labels(self, datapath):
+ # GH 13923, 25772
+ msg = """
+Value labels for column ethnicsn are not unique. These cannot be converted to
+pandas categoricals.
+
+Either read the file with `convert_categoricals` set to False or use the
+low level interface in `StataReader` to separately read the values and the
+value_labels.
+
+The repeated labels are:\n-+\nwolof
+"""
+ with pytest.raises(ValueError, match=msg):
+ read_stata(
+ datapath("io", "data", "stata", "stata15.dta"),
+ convert_categoricals=True,
+ )
+
+ def test_stata_111(self, datapath):
+ # 111 is an old version but still used by current versions of
+ # SAS when exporting to Stata format. We do not know of any
+ # on-line documentation for this version.
+ df = read_stata(datapath("io", "data", "stata", "stata7_111.dta"))
+ original = DataFrame(
+ {
+ "y": [1, 1, 1, 1, 1, 0, 0, np.nan, 0, 0],
+ "x": [1, 2, 1, 3, np.nan, 4, 3, 5, 1, 6],
+ "w": [2, np.nan, 5, 2, 4, 4, 3, 1, 2, 3],
+ "z": ["a", "b", "c", "d", "e", "", "g", "h", "i", "j"],
+ }
+ )
+ original = original[["y", "x", "w", "z"]]
+ tm.assert_frame_equal(original, df)
+
+ def test_out_of_range_double(self):
+ # GH 14618
+ df = DataFrame(
+ {
+ "ColumnOk": [0.0, np.finfo(np.double).eps, 4.49423283715579e307],
+ "ColumnTooBig": [0.0, np.finfo(np.double).eps, np.finfo(np.double).max],
+ }
+ )
+ msg = (
+ r"Column ColumnTooBig has a maximum value \(.+\) outside the range "
+ r"supported by Stata \(.+\)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ with tm.ensure_clean() as path:
+ df.to_stata(path)
+
+ def test_out_of_range_float(self):
+ original = DataFrame(
+ {
+ "ColumnOk": [
+ 0.0,
+ np.finfo(np.float32).eps,
+ np.finfo(np.float32).max / 10.0,
+ ],
+ "ColumnTooBig": [
+ 0.0,
+ np.finfo(np.float32).eps,
+ np.finfo(np.float32).max,
+ ],
+ }
+ )
+ original.index.name = "index"
+ for col in original:
+ original[col] = original[col].astype(np.float32)
+
+ with tm.ensure_clean() as path:
+ original.to_stata(path)
+ reread = read_stata(path)
+
+ original["ColumnTooBig"] = original["ColumnTooBig"].astype(np.float64)
+ expected = original.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(reread.set_index("index"), expected)
+
+ @pytest.mark.parametrize("infval", [np.inf, -np.inf])
+ def test_inf(self, infval):
+ # GH 45350
+ df = DataFrame({"WithoutInf": [0.0, 1.0], "WithInf": [2.0, infval]})
+ msg = (
+ "Column WithInf contains infinity or -infinity"
+ "which is outside the range supported by Stata."
+ )
+ with pytest.raises(ValueError, match=msg):
+ with tm.ensure_clean() as path:
+ df.to_stata(path)
+
+ def test_path_pathlib(self):
+ df = tm.makeDataFrame()
+ df.index.name = "index"
+ reader = lambda x: read_stata(x).set_index("index")
+ result = tm.round_trip_pathlib(df.to_stata, reader)
+ tm.assert_frame_equal(df, result)
+
+ def test_pickle_path_localpath(self):
+ df = tm.makeDataFrame()
+ df.index.name = "index"
+ reader = lambda x: read_stata(x).set_index("index")
+ result = tm.round_trip_localpath(df.to_stata, reader)
+ tm.assert_frame_equal(df, result)
+
+ @pytest.mark.parametrize("write_index", [True, False])
+ def test_value_labels_iterator(self, write_index):
+ # GH 16923
+ d = {"A": ["B", "E", "C", "A", "E"]}
+ df = DataFrame(data=d)
+ df["A"] = df["A"].astype("category")
+ with tm.ensure_clean() as path:
+ df.to_stata(path, write_index=write_index)
+
+ with read_stata(path, iterator=True) as dta_iter:
+ value_labels = dta_iter.value_labels()
+ assert value_labels == {"A": {0: "A", 1: "B", 2: "C", 3: "E"}}
+
+ def test_set_index(self):
+ # GH 17328
+ df = tm.makeDataFrame()
+ df.index.name = "index"
+ with tm.ensure_clean() as path:
+ df.to_stata(path)
+ reread = read_stata(path, index_col="index")
+ tm.assert_frame_equal(df, reread)
+
+ @pytest.mark.parametrize(
+ "column", ["ms", "day", "week", "month", "qtr", "half", "yr"]
+ )
+ def test_date_parsing_ignores_format_details(self, column, datapath):
+ # GH 17797
+ #
+ # Test that display formats are ignored when determining if a numeric
+ # column is a date value.
+ #
+ # All date types are stored as numbers and format associated with the
+ # column denotes both the type of the date and the display format.
+ #
+ # STATA supports 9 date types which each have distinct units. We test 7
+ # of the 9 types, ignoring %tC and %tb. %tC is a variant of %tc that
+ # accounts for leap seconds and %tb relies on STATAs business calendar.
+ df = read_stata(datapath("io", "data", "stata", "stata13_dates.dta"))
+ unformatted = df.loc[0, column]
+ formatted = df.loc[0, column + "_fmt"]
+ assert unformatted == formatted
+
+ def test_writer_117(self):
+ original = DataFrame(
+ data=[
+ [
+ "string",
+ "object",
+ 1,
+ 1,
+ 1,
+ 1.1,
+ 1.1,
+ np.datetime64("2003-12-25"),
+ "a",
+ "a" * 2045,
+ "a" * 5000,
+ "a",
+ ],
+ [
+ "string-1",
+ "object-1",
+ 1,
+ 1,
+ 1,
+ 1.1,
+ 1.1,
+ np.datetime64("2003-12-26"),
+ "b",
+ "b" * 2045,
+ "",
+ "",
+ ],
+ ],
+ columns=[
+ "string",
+ "object",
+ "int8",
+ "int16",
+ "int32",
+ "float32",
+ "float64",
+ "datetime",
+ "s1",
+ "s2045",
+ "srtl",
+ "forced_strl",
+ ],
+ )
+ original["object"] = Series(original["object"], dtype=object)
+ original["int8"] = Series(original["int8"], dtype=np.int8)
+ original["int16"] = Series(original["int16"], dtype=np.int16)
+ original["int32"] = original["int32"].astype(np.int32)
+ original["float32"] = Series(original["float32"], dtype=np.float32)
+ original.index.name = "index"
+ original.index = original.index.astype(np.int32)
+ copy = original.copy()
+ with tm.ensure_clean() as path:
+ original.to_stata(
+ path,
+ convert_dates={"datetime": "tc"},
+ convert_strl=["forced_strl"],
+ version=117,
+ )
+ written_and_read_again = self.read_dta(path)
+ # original.index is np.int32, read index is np.int64
+ tm.assert_frame_equal(
+ written_and_read_again.set_index("index"),
+ original,
+ check_index_type=False,
+ )
+ tm.assert_frame_equal(original, copy)
+
+ def test_convert_strl_name_swap(self):
+ original = DataFrame(
+ [["a" * 3000, "A", "apple"], ["b" * 1000, "B", "banana"]],
+ columns=["long1" * 10, "long", 1],
+ )
+ original.index.name = "index"
+
+ with tm.assert_produces_warning(InvalidColumnName):
+ with tm.ensure_clean() as path:
+ original.to_stata(path, convert_strl=["long", 1], version=117)
+ reread = self.read_dta(path)
+ reread = reread.set_index("index")
+ reread.columns = original.columns
+ tm.assert_frame_equal(reread, original, check_index_type=False)
+
+ def test_invalid_date_conversion(self):
+ # GH 12259
+ dates = [
+ dt.datetime(1999, 12, 31, 12, 12, 12, 12000),
+ dt.datetime(2012, 12, 21, 12, 21, 12, 21000),
+ dt.datetime(1776, 7, 4, 7, 4, 7, 4000),
+ ]
+ original = DataFrame(
+ {
+ "nums": [1.0, 2.0, 3.0],
+ "strs": ["apple", "banana", "cherry"],
+ "dates": dates,
+ }
+ )
+
+ with tm.ensure_clean() as path:
+ msg = "convert_dates key must be a column or an integer"
+ with pytest.raises(ValueError, match=msg):
+ original.to_stata(path, convert_dates={"wrong_name": "tc"})
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_nonfile_writing(self, version):
+ # GH 21041
+ bio = io.BytesIO()
+ df = tm.makeDataFrame()
+ df.index.name = "index"
+ with tm.ensure_clean() as path:
+ df.to_stata(bio, version=version)
+ bio.seek(0)
+ with open(path, "wb") as dta:
+ dta.write(bio.read())
+ reread = read_stata(path, index_col="index")
+ tm.assert_frame_equal(df, reread)
+
+ def test_gzip_writing(self):
+ # writing version 117 requires seek and cannot be used with gzip
+ df = tm.makeDataFrame()
+ df.index.name = "index"
+ with tm.ensure_clean() as path:
+ with gzip.GzipFile(path, "wb") as gz:
+ df.to_stata(gz, version=114)
+ with gzip.GzipFile(path, "rb") as gz:
+ reread = read_stata(gz, index_col="index")
+ tm.assert_frame_equal(df, reread)
+
+ def test_unicode_dta_118(self, datapath):
+ unicode_df = self.read_dta(datapath("io", "data", "stata", "stata16_118.dta"))
+
+ columns = ["utf8", "latin1", "ascii", "utf8_strl", "ascii_strl"]
+ values = [
+ ["ραηδας", "PÄNDÄS", "p", "ραηδας", "p"],
+ ["ƤĀńĐąŜ", "Ö", "a", "ƤĀńĐąŜ", "a"],
+ ["ᴘᴀᴎᴅᴀS", "Ü", "n", "ᴘᴀᴎᴅᴀS", "n"],
+ [" ", " ", "d", " ", "d"],
+ [" ", "", "a", " ", "a"],
+ ["", "", "s", "", "s"],
+ ["", "", " ", "", " "],
+ ]
+ expected = DataFrame(values, columns=columns)
+
+ tm.assert_frame_equal(unicode_df, expected)
+
+ def test_mixed_string_strl(self):
+ # GH 23633
+ output = [{"mixed": "string" * 500, "number": 0}, {"mixed": None, "number": 1}]
+ output = DataFrame(output)
+ output.number = output.number.astype("int32")
+
+ with tm.ensure_clean() as path:
+ output.to_stata(path, write_index=False, version=117)
+ reread = read_stata(path)
+ expected = output.fillna("")
+ tm.assert_frame_equal(reread, expected)
+
+ # Check strl supports all None (null)
+ output["mixed"] = None
+ output.to_stata(
+ path, write_index=False, convert_strl=["mixed"], version=117
+ )
+ reread = read_stata(path)
+ expected = output.fillna("")
+ tm.assert_frame_equal(reread, expected)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_all_none_exception(self, version):
+ output = [{"none": "none", "number": 0}, {"none": None, "number": 1}]
+ output = DataFrame(output)
+ output["none"] = None
+ with tm.ensure_clean() as path:
+ with pytest.raises(ValueError, match="Column `none` cannot be exported"):
+ output.to_stata(path, version=version)
+
+ @pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+ def test_invalid_file_not_written(self, version):
+ content = "Here is one __�__ Another one __·__ Another one __½__"
+ df = DataFrame([content], columns=["invalid"])
+ with tm.ensure_clean() as path:
+ msg1 = (
+ r"'latin-1' codec can't encode character '\\ufffd' "
+ r"in position 14: ordinal not in range\(256\)"
+ )
+ msg2 = (
+ "'ascii' codec can't decode byte 0xef in position 14: "
+ r"ordinal not in range\(128\)"
+ )
+ with pytest.raises(UnicodeEncodeError, match=f"{msg1}|{msg2}"):
+ df.to_stata(path)
+
+ def test_strl_latin1(self):
+ # GH 23573, correct GSO data to reflect correct size
+ output = DataFrame(
+ [["pandas"] * 2, ["þâÑÐŧ"] * 2], columns=["var_str", "var_strl"]
+ )
+
+ with tm.ensure_clean() as path:
+ output.to_stata(path, version=117, convert_strl=["var_strl"])
+ with open(path, "rb") as reread:
+ content = reread.read()
+ expected = "þâÑÐŧ"
+ assert expected.encode("latin-1") in content
+ assert expected.encode("utf-8") in content
+ gsos = content.split(b"strls")[1][1:-2]
+ for gso in gsos.split(b"GSO")[1:]:
+ val = gso.split(b"\x00")[-2]
+ size = gso[gso.find(b"\x82") + 1]
+ assert len(val) == size - 1
+
+ def test_encoding_latin1_118(self, datapath):
+ # GH 25960
+ msg = """
+One or more strings in the dta file could not be decoded using utf-8, and
+so the fallback encoding of latin-1 is being used. This can happen when a file
+has been incorrectly encoded by Stata or some other software. You should verify
+the string values returned are correct."""
+ # Move path outside of read_stata, or else assert_produces_warning
+ # will block pytests skip mechanism from triggering (failing the test)
+ # if the path is not present
+ path = datapath("io", "data", "stata", "stata1_encoding_118.dta")
+ with tm.assert_produces_warning(UnicodeWarning, filter_level="once") as w:
+ encoded = read_stata(path)
+ # with filter_level="always", produces 151 warnings which can be slow
+ assert len(w) == 1
+ assert w[0].message.args[0] == msg
+
+ expected = DataFrame([["Düsseldorf"]] * 151, columns=["kreis1849"])
+ tm.assert_frame_equal(encoded, expected)
+
+ @pytest.mark.slow
+ def test_stata_119(self, datapath):
+ # Gzipped since contains 32,999 variables and uncompressed is 20MiB
+ with gzip.open(
+ datapath("io", "data", "stata", "stata1_119.dta.gz"), "rb"
+ ) as gz:
+ df = read_stata(gz)
+ assert df.shape == (1, 32999)
+ assert df.iloc[0, 6] == "A" * 3000
+ assert df.iloc[0, 7] == 3.14
+ assert df.iloc[0, -1] == 1
+ assert df.iloc[0, 0] == pd.Timestamp(datetime(2012, 12, 21, 21, 12, 21))
+
+ @pytest.mark.parametrize("version", [118, 119, None])
+ def test_utf8_writer(self, version):
+ cat = pd.Categorical(["a", "β", "ĉ"], ordered=True)
+ data = DataFrame(
+ [
+ [1.0, 1, "ᴬ", "ᴀ relatively long ŝtring"],
+ [2.0, 2, "ᴮ", ""],
+ [3.0, 3, "ᴰ", None],
+ ],
+ columns=["Å", "β", "ĉ", "strls"],
+ )
+ data["ᴐᴬᵀ"] = cat
+ variable_labels = {
+ "Å": "apple",
+ "β": "ᵈᵉᵊ",
+ "ĉ": "ᴎტჄႲႳႴႶႺ",
+ "strls": "Long Strings",
+ "ᴐᴬᵀ": "",
+ }
+ data_label = "ᴅaᵀa-label"
+ value_labels = {"β": {1: "label", 2: "æøå", 3: "ŋot valid latin-1"}}
+ data["β"] = data["β"].astype(np.int32)
+ with tm.ensure_clean() as path:
+ writer = StataWriterUTF8(
+ path,
+ data,
+ data_label=data_label,
+ convert_strl=["strls"],
+ variable_labels=variable_labels,
+ write_index=False,
+ version=version,
+ value_labels=value_labels,
+ )
+ writer.write_file()
+ reread_encoded = read_stata(path)
+ # Missing is intentionally converted to empty strl
+ data["strls"] = data["strls"].fillna("")
+ # Variable with value labels is reread as categorical
+ data["β"] = (
+ data["β"].replace(value_labels["β"]).astype("category").cat.as_ordered()
+ )
+ tm.assert_frame_equal(data, reread_encoded)
+ with StataReader(path) as reader:
+ assert reader.data_label == data_label
+ assert reader.variable_labels() == variable_labels
+
+ data.to_stata(path, version=version, write_index=False)
+ reread_to_stata = read_stata(path)
+ tm.assert_frame_equal(data, reread_to_stata)
+
+ def test_writer_118_exceptions(self):
+ df = DataFrame(np.zeros((1, 33000), dtype=np.int8))
+ with tm.ensure_clean() as path:
+ with pytest.raises(ValueError, match="version must be either 118 or 119."):
+ StataWriterUTF8(path, df, version=117)
+ with tm.ensure_clean() as path:
+ with pytest.raises(ValueError, match="You must use version 119"):
+ StataWriterUTF8(path, df, version=118)
+
+
+@pytest.mark.parametrize("version", [105, 108, 111, 113, 114])
+def test_backward_compat(version, datapath):
+ data_base = datapath("io", "data", "stata")
+ ref = os.path.join(data_base, "stata-compat-118.dta")
+ old = os.path.join(data_base, f"stata-compat-{version}.dta")
+ expected = read_stata(ref)
+ old_dta = read_stata(old)
+ tm.assert_frame_equal(old_dta, expected, check_dtype=False)
+
+
+def test_direct_read(datapath, monkeypatch):
+ file_path = datapath("io", "data", "stata", "stata-compat-118.dta")
+
+ # Test that opening a file path doesn't buffer the file.
+ with StataReader(file_path) as reader:
+ # Must not have been buffered to memory
+ assert not reader.read().empty
+ assert not isinstance(reader._path_or_buf, io.BytesIO)
+
+ # Test that we use a given fp exactly, if possible.
+ with open(file_path, "rb") as fp:
+ with StataReader(fp) as reader:
+ assert not reader.read().empty
+ assert reader._path_or_buf is fp
+
+ # Test that we use a given BytesIO exactly, if possible.
+ with open(file_path, "rb") as fp:
+ with io.BytesIO(fp.read()) as bio:
+ with StataReader(bio) as reader:
+ assert not reader.read().empty
+ assert reader._path_or_buf is bio
+
+
+def test_statareader_warns_when_used_without_context(datapath):
+ file_path = datapath("io", "data", "stata", "stata-compat-118.dta")
+ with tm.assert_produces_warning(
+ ResourceWarning,
+ match="without using a context manager",
+ ):
+ sr = StataReader(file_path)
+ sr.read()
+ with tm.assert_produces_warning(
+ FutureWarning,
+ match="is not part of the public API",
+ ):
+ sr.close()
+
+
+@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+@pytest.mark.parametrize("use_dict", [True, False])
+@pytest.mark.parametrize("infer", [True, False])
+def test_compression(compression, version, use_dict, infer, compression_to_extension):
+ file_name = "dta_inferred_compression.dta"
+ if compression:
+ if use_dict:
+ file_ext = compression
+ else:
+ file_ext = compression_to_extension[compression]
+ file_name += f".{file_ext}"
+ compression_arg = compression
+ if infer:
+ compression_arg = "infer"
+ if use_dict:
+ compression_arg = {"method": compression}
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)), columns=list("AB")
+ )
+ df.index.name = "index"
+ with tm.ensure_clean(file_name) as path:
+ df.to_stata(path, version=version, compression=compression_arg)
+ if compression == "gzip":
+ with gzip.open(path, "rb") as comp:
+ fp = io.BytesIO(comp.read())
+ elif compression == "zip":
+ with zipfile.ZipFile(path, "r") as comp:
+ fp = io.BytesIO(comp.read(comp.filelist[0]))
+ elif compression == "tar":
+ with tarfile.open(path) as tar:
+ fp = io.BytesIO(tar.extractfile(tar.getnames()[0]).read())
+ elif compression == "bz2":
+ with bz2.open(path, "rb") as comp:
+ fp = io.BytesIO(comp.read())
+ elif compression == "zstd":
+ zstd = pytest.importorskip("zstandard")
+ with zstd.open(path, "rb") as comp:
+ fp = io.BytesIO(comp.read())
+ elif compression == "xz":
+ lzma = pytest.importorskip("lzma")
+ with lzma.open(path, "rb") as comp:
+ fp = io.BytesIO(comp.read())
+ elif compression is None:
+ fp = path
+ reread = read_stata(fp, index_col="index")
+
+ expected = df.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(reread, expected)
+
+
+@pytest.mark.parametrize("method", ["zip", "infer"])
+@pytest.mark.parametrize("file_ext", [None, "dta", "zip"])
+def test_compression_dict(method, file_ext):
+ file_name = f"test.{file_ext}"
+ archive_name = "test.dta"
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)), columns=list("AB")
+ )
+ df.index.name = "index"
+ with tm.ensure_clean(file_name) as path:
+ compression = {"method": method, "archive_name": archive_name}
+ df.to_stata(path, compression=compression)
+ if method == "zip" or file_ext == "zip":
+ with zipfile.ZipFile(path, "r") as zp:
+ assert len(zp.filelist) == 1
+ assert zp.filelist[0].filename == archive_name
+ fp = io.BytesIO(zp.read(zp.filelist[0]))
+ else:
+ fp = path
+ reread = read_stata(fp, index_col="index")
+
+ expected = df.copy()
+ expected.index = expected.index.astype(np.int32)
+ tm.assert_frame_equal(reread, expected)
+
+
+@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+def test_chunked_categorical(version):
+ df = DataFrame({"cats": Series(["a", "b", "a", "b", "c"], dtype="category")})
+ df.index.name = "index"
+
+ expected = df.copy()
+ expected.index = expected.index.astype(np.int32)
+
+ with tm.ensure_clean() as path:
+ df.to_stata(path, version=version)
+ with StataReader(path, chunksize=2, order_categoricals=False) as reader:
+ for i, block in enumerate(reader):
+ block = block.set_index("index")
+ assert "cats" in block
+ tm.assert_series_equal(
+ block.cats, expected.cats.iloc[2 * i : 2 * (i + 1)]
+ )
+
+
+def test_chunked_categorical_partial(datapath):
+ dta_file = datapath("io", "data", "stata", "stata-dta-partially-labeled.dta")
+ values = ["a", "b", "a", "b", 3.0]
+ with StataReader(dta_file, chunksize=2) as reader:
+ with tm.assert_produces_warning(CategoricalConversionWarning):
+ for i, block in enumerate(reader):
+ assert list(block.cats) == values[2 * i : 2 * (i + 1)]
+ if i < 2:
+ idx = pd.Index(["a", "b"])
+ else:
+ idx = pd.Index([3.0], dtype="float64")
+ tm.assert_index_equal(block.cats.cat.categories, idx)
+ with tm.assert_produces_warning(CategoricalConversionWarning):
+ with StataReader(dta_file, chunksize=5) as reader:
+ large_chunk = reader.__next__()
+ direct = read_stata(dta_file)
+ tm.assert_frame_equal(direct, large_chunk)
+
+
+@pytest.mark.parametrize("chunksize", (-1, 0, "apple"))
+def test_iterator_errors(datapath, chunksize):
+ dta_file = datapath("io", "data", "stata", "stata-dta-partially-labeled.dta")
+ with pytest.raises(ValueError, match="chunksize must be a positive"):
+ with StataReader(dta_file, chunksize=chunksize):
+ pass
+
+
+def test_iterator_value_labels():
+ # GH 31544
+ values = ["c_label", "b_label"] + ["a_label"] * 500
+ df = DataFrame({f"col{k}": pd.Categorical(values, ordered=True) for k in range(2)})
+ with tm.ensure_clean() as path:
+ df.to_stata(path, write_index=False)
+ expected = pd.Index(["a_label", "b_label", "c_label"], dtype="object")
+ with read_stata(path, chunksize=100) as reader:
+ for j, chunk in enumerate(reader):
+ for i in range(2):
+ tm.assert_index_equal(chunk.dtypes.iloc[i].categories, expected)
+ tm.assert_frame_equal(chunk, df.iloc[j * 100 : (j + 1) * 100])
+
+
+def test_precision_loss():
+ df = DataFrame(
+ [[sum(2**i for i in range(60)), sum(2**i for i in range(52))]],
+ columns=["big", "little"],
+ )
+ with tm.ensure_clean() as path:
+ with tm.assert_produces_warning(
+ PossiblePrecisionLoss, match="Column converted from int64 to float64"
+ ):
+ df.to_stata(path, write_index=False)
+ reread = read_stata(path)
+ expected_dt = Series([np.float64, np.float64], index=["big", "little"])
+ tm.assert_series_equal(reread.dtypes, expected_dt)
+ assert reread.loc[0, "little"] == df.loc[0, "little"]
+ assert reread.loc[0, "big"] == float(df.loc[0, "big"])
+
+
+def test_compression_roundtrip(compression):
+ df = DataFrame(
+ [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ index=["A", "B"],
+ columns=["X", "Y", "Z"],
+ )
+ df.index.name = "index"
+
+ with tm.ensure_clean() as path:
+ df.to_stata(path, compression=compression)
+ reread = read_stata(path, compression=compression, index_col="index")
+ tm.assert_frame_equal(df, reread)
+
+ # explicitly ensure file was compressed.
+ with tm.decompress_file(path, compression) as fh:
+ contents = io.BytesIO(fh.read())
+ reread = read_stata(contents, index_col="index")
+ tm.assert_frame_equal(df, reread)
+
+
+@pytest.mark.parametrize("to_infer", [True, False])
+@pytest.mark.parametrize("read_infer", [True, False])
+def test_stata_compression(
+ compression_only, read_infer, to_infer, compression_to_extension
+):
+ compression = compression_only
+
+ ext = compression_to_extension[compression]
+ filename = f"test.{ext}"
+
+ df = DataFrame(
+ [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ index=["A", "B"],
+ columns=["X", "Y", "Z"],
+ )
+ df.index.name = "index"
+
+ to_compression = "infer" if to_infer else compression
+ read_compression = "infer" if read_infer else compression
+
+ with tm.ensure_clean(filename) as path:
+ df.to_stata(path, compression=to_compression)
+ result = read_stata(path, compression=read_compression, index_col="index")
+ tm.assert_frame_equal(result, df)
+
+
+def test_non_categorical_value_labels():
+ data = DataFrame(
+ {
+ "fully_labelled": [1, 2, 3, 3, 1],
+ "partially_labelled": [1.0, 2.0, np.nan, 9.0, np.nan],
+ "Y": [7, 7, 9, 8, 10],
+ "Z": pd.Categorical(["j", "k", "l", "k", "j"]),
+ }
+ )
+
+ with tm.ensure_clean() as path:
+ value_labels = {
+ "fully_labelled": {1: "one", 2: "two", 3: "three"},
+ "partially_labelled": {1.0: "one", 2.0: "two"},
+ }
+ expected = {**value_labels, "Z": {0: "j", 1: "k", 2: "l"}}
+
+ writer = StataWriter(path, data, value_labels=value_labels)
+ writer.write_file()
+
+ with StataReader(path) as reader:
+ reader_value_labels = reader.value_labels()
+ assert reader_value_labels == expected
+
+ msg = "Can't create value labels for notY, it wasn't found in the dataset."
+ with pytest.raises(KeyError, match=msg):
+ value_labels = {"notY": {7: "label1", 8: "label2"}}
+ StataWriter(path, data, value_labels=value_labels)
+
+ msg = (
+ "Can't create value labels for Z, value labels "
+ "can only be applied to numeric columns."
+ )
+ with pytest.raises(ValueError, match=msg):
+ value_labels = {"Z": {1: "a", 2: "k", 3: "j", 4: "i"}}
+ StataWriter(path, data, value_labels=value_labels)
+
+
+def test_non_categorical_value_label_name_conversion():
+ # Check conversion of invalid variable names
+ data = DataFrame(
+ {
+ "invalid~!": [1, 1, 2, 3, 5, 8], # Only alphanumeric and _
+ "6_invalid": [1, 1, 2, 3, 5, 8], # Must start with letter or _
+ "invalid_name_longer_than_32_characters": [8, 8, 9, 9, 8, 8], # Too long
+ "aggregate": [2, 5, 5, 6, 6, 9], # Reserved words
+ (1, 2): [1, 2, 3, 4, 5, 6], # Hashable non-string
+ }
+ )
+
+ value_labels = {
+ "invalid~!": {1: "label1", 2: "label2"},
+ "6_invalid": {1: "label1", 2: "label2"},
+ "invalid_name_longer_than_32_characters": {8: "eight", 9: "nine"},
+ "aggregate": {5: "five"},
+ (1, 2): {3: "three"},
+ }
+
+ expected = {
+ "invalid__": {1: "label1", 2: "label2"},
+ "_6_invalid": {1: "label1", 2: "label2"},
+ "invalid_name_longer_than_32_char": {8: "eight", 9: "nine"},
+ "_aggregate": {5: "five"},
+ "_1__2_": {3: "three"},
+ }
+
+ with tm.ensure_clean() as path:
+ with tm.assert_produces_warning(InvalidColumnName):
+ data.to_stata(path, value_labels=value_labels)
+
+ with StataReader(path) as reader:
+ reader_value_labels = reader.value_labels()
+ assert reader_value_labels == expected
+
+
+def test_non_categorical_value_label_convert_categoricals_error():
+ # Mapping more than one value to the same label is valid for Stata
+ # labels, but can't be read with convert_categoricals=True
+ value_labels = {
+ "repeated_labels": {10: "Ten", 20: "More than ten", 40: "More than ten"}
+ }
+
+ data = DataFrame(
+ {
+ "repeated_labels": [10, 10, 20, 20, 40, 40],
+ }
+ )
+
+ with tm.ensure_clean() as path:
+ data.to_stata(path, value_labels=value_labels)
+
+ with StataReader(path, convert_categoricals=False) as reader:
+ reader_value_labels = reader.value_labels()
+ assert reader_value_labels == value_labels
+
+ col = "repeated_labels"
+ repeats = "-" * 80 + "\n" + "\n".join(["More than ten"])
+
+ msg = f"""
+Value labels for column {col} are not unique. These cannot be converted to
+pandas categoricals.
+
+Either read the file with `convert_categoricals` set to False or use the
+low level interface in `StataReader` to separately read the values and the
+value_labels.
+
+The repeated labels are:
+{repeats}
+"""
+ with pytest.raises(ValueError, match=msg):
+ read_stata(path, convert_categoricals=True)
+
+
+@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ pd.BooleanDtype,
+ pd.Int8Dtype,
+ pd.Int16Dtype,
+ pd.Int32Dtype,
+ pd.Int64Dtype,
+ pd.UInt8Dtype,
+ pd.UInt16Dtype,
+ pd.UInt32Dtype,
+ pd.UInt64Dtype,
+ ],
+)
+def test_nullable_support(dtype, version):
+ df = DataFrame(
+ {
+ "a": Series([1.0, 2.0, 3.0]),
+ "b": Series([1, pd.NA, pd.NA], dtype=dtype.name),
+ "c": Series(["a", "b", None]),
+ }
+ )
+ dtype_name = df.b.dtype.numpy_dtype.name
+ # Only use supported names: no uint, bool or int64
+ dtype_name = dtype_name.replace("u", "")
+ if dtype_name == "int64":
+ dtype_name = "int32"
+ elif dtype_name == "bool":
+ dtype_name = "int8"
+ value = StataMissingValue.BASE_MISSING_VALUES[dtype_name]
+ smv = StataMissingValue(value)
+ expected_b = Series([1, smv, smv], dtype=object, name="b")
+ expected_c = Series(["a", "b", ""], name="c")
+ with tm.ensure_clean() as path:
+ df.to_stata(path, write_index=False, version=version)
+ reread = read_stata(path, convert_missing=True)
+ tm.assert_series_equal(df.a, reread.a)
+ tm.assert_series_equal(reread.b, expected_b)
+ tm.assert_series_equal(reread.c, expected_c)
+
+
+def test_empty_frame():
+ # GH 46240
+ # create an empty DataFrame with int64 and float64 dtypes
+ df = DataFrame(data={"a": range(3), "b": [1.0, 2.0, 3.0]}).head(0)
+ with tm.ensure_clean() as path:
+ df.to_stata(path, write_index=False, version=117)
+ # Read entire dataframe
+ df2 = read_stata(path)
+ assert "b" in df2
+ # Dtypes don't match since no support for int32
+ dtypes = Series({"a": np.dtype("int32"), "b": np.dtype("float64")})
+ tm.assert_series_equal(df2.dtypes, dtypes)
+ # read one column of empty .dta file
+ df3 = read_stata(path, columns=["a"])
+ assert "b" not in df3
+ tm.assert_series_equal(df3.dtypes, dtypes.loc[["a"]])
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_user_agent.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_user_agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0656b938eaa679fa83039faabf9b8939e65c205
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/io/test_user_agent.py
@@ -0,0 +1,400 @@
+"""
+Tests for the pandas custom headers in http(s) requests
+"""
+import gzip
+import http.server
+from io import BytesIO
+import multiprocessing
+import socket
+import time
+import urllib.error
+
+import pytest
+
+from pandas.compat import is_ci_environment
+import pandas.util._test_decorators as td
+
+import pandas as pd
+import pandas._testing as tm
+
+pytestmark = [
+ pytest.mark.single_cpu,
+ pytest.mark.skipif(
+ is_ci_environment(),
+ reason="GH 45651: This test can hang in our CI min_versions build",
+ ),
+]
+
+
+class BaseUserAgentResponder(http.server.BaseHTTPRequestHandler):
+ """
+ Base class for setting up a server that can be set up to respond
+ with a particular file format with accompanying content-type headers.
+ The interfaces on the different io methods are different enough
+ that this seemed logical to do.
+ """
+
+ def start_processing_headers(self):
+ """
+ shared logic at the start of a GET request
+ """
+ self.send_response(200)
+ self.requested_from_user_agent = self.headers["User-Agent"]
+ response_df = pd.DataFrame(
+ {
+ "header": [self.requested_from_user_agent],
+ }
+ )
+ return response_df
+
+ def gzip_bytes(self, response_bytes):
+ """
+ some web servers will send back gzipped files to save bandwidth
+ """
+ with BytesIO() as bio:
+ with gzip.GzipFile(fileobj=bio, mode="w") as zipper:
+ zipper.write(response_bytes)
+ response_bytes = bio.getvalue()
+ return response_bytes
+
+ def write_back_bytes(self, response_bytes):
+ """
+ shared logic at the end of a GET request
+ """
+ self.wfile.write(response_bytes)
+
+
+class CSVUserAgentResponder(BaseUserAgentResponder):
+ def do_GET(self):
+ response_df = self.start_processing_headers()
+
+ self.send_header("Content-Type", "text/csv")
+ self.end_headers()
+
+ response_bytes = response_df.to_csv(index=False).encode("utf-8")
+ self.write_back_bytes(response_bytes)
+
+
+class GzippedCSVUserAgentResponder(BaseUserAgentResponder):
+ def do_GET(self):
+ response_df = self.start_processing_headers()
+ self.send_header("Content-Type", "text/csv")
+ self.send_header("Content-Encoding", "gzip")
+ self.end_headers()
+
+ response_bytes = response_df.to_csv(index=False).encode("utf-8")
+ response_bytes = self.gzip_bytes(response_bytes)
+
+ self.write_back_bytes(response_bytes)
+
+
+class JSONUserAgentResponder(BaseUserAgentResponder):
+ def do_GET(self):
+ response_df = self.start_processing_headers()
+ self.send_header("Content-Type", "application/json")
+ self.end_headers()
+
+ response_bytes = response_df.to_json().encode("utf-8")
+
+ self.write_back_bytes(response_bytes)
+
+
+class GzippedJSONUserAgentResponder(BaseUserAgentResponder):
+ def do_GET(self):
+ response_df = self.start_processing_headers()
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Encoding", "gzip")
+ self.end_headers()
+
+ response_bytes = response_df.to_json().encode("utf-8")
+ response_bytes = self.gzip_bytes(response_bytes)
+
+ self.write_back_bytes(response_bytes)
+
+
+class HTMLUserAgentResponder(BaseUserAgentResponder):
+ def do_GET(self):
+ response_df = self.start_processing_headers()
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+
+ response_bytes = response_df.to_html(index=False).encode("utf-8")
+
+ self.write_back_bytes(response_bytes)
+
+
+class ParquetPyArrowUserAgentResponder(BaseUserAgentResponder):
+ def do_GET(self):
+ response_df = self.start_processing_headers()
+ self.send_header("Content-Type", "application/octet-stream")
+ self.end_headers()
+
+ response_bytes = response_df.to_parquet(index=False, engine="pyarrow")
+
+ self.write_back_bytes(response_bytes)
+
+
+class ParquetFastParquetUserAgentResponder(BaseUserAgentResponder):
+ def do_GET(self):
+ response_df = self.start_processing_headers()
+ self.send_header("Content-Type", "application/octet-stream")
+ self.end_headers()
+
+ # the fastparquet engine doesn't like to write to a buffer
+ # it can do it via the open_with function being set appropriately
+ # however it automatically calls the close method and wipes the buffer
+ # so just overwrite that attribute on this instance to not do that
+
+ # protected by an importorskip in the respective test
+ import fsspec
+
+ response_df.to_parquet(
+ "memory://fastparquet_user_agent.parquet",
+ index=False,
+ engine="fastparquet",
+ compression=None,
+ )
+ with fsspec.open("memory://fastparquet_user_agent.parquet", "rb") as f:
+ response_bytes = f.read()
+
+ self.write_back_bytes(response_bytes)
+
+
+class PickleUserAgentResponder(BaseUserAgentResponder):
+ def do_GET(self):
+ response_df = self.start_processing_headers()
+ self.send_header("Content-Type", "application/octet-stream")
+ self.end_headers()
+
+ bio = BytesIO()
+ response_df.to_pickle(bio)
+ response_bytes = bio.getvalue()
+
+ self.write_back_bytes(response_bytes)
+
+
+class StataUserAgentResponder(BaseUserAgentResponder):
+ def do_GET(self):
+ response_df = self.start_processing_headers()
+ self.send_header("Content-Type", "application/octet-stream")
+ self.end_headers()
+
+ bio = BytesIO()
+ response_df.to_stata(bio, write_index=False)
+ response_bytes = bio.getvalue()
+
+ self.write_back_bytes(response_bytes)
+
+
+class AllHeaderCSVResponder(http.server.BaseHTTPRequestHandler):
+ """
+ Send all request headers back for checking round trip
+ """
+
+ def do_GET(self):
+ response_df = pd.DataFrame(self.headers.items())
+ self.send_response(200)
+ self.send_header("Content-Type", "text/csv")
+ self.end_headers()
+ response_bytes = response_df.to_csv(index=False).encode("utf-8")
+ self.wfile.write(response_bytes)
+
+
+def wait_until_ready(func, *args, **kwargs):
+ def inner(*args, **kwargs):
+ while True:
+ try:
+ return func(*args, **kwargs)
+ except urllib.error.URLError:
+ # Connection refused as http server is starting
+ time.sleep(0.1)
+
+ return inner
+
+
+def process_server(responder, port):
+ with http.server.HTTPServer(("localhost", port), responder) as server:
+ server.handle_request()
+ server.server_close()
+
+
+@pytest.fixture
+def responder(request):
+ """
+ Fixture that starts a local http server in a separate process on localhost
+ and returns the port.
+
+ Running in a separate process instead of a thread to allow termination/killing
+ of http server upon cleanup.
+ """
+ # Find an available port
+ with socket.socket() as sock:
+ sock.bind(("localhost", 0))
+ port = sock.getsockname()[1]
+
+ server_process = multiprocessing.Process(
+ target=process_server, args=(request.param, port)
+ )
+ server_process.start()
+ yield port
+ server_process.join(10)
+ server_process.terminate()
+ kill_time = 5
+ wait_time = 0
+ while server_process.is_alive():
+ if wait_time > kill_time:
+ server_process.kill()
+ break
+ wait_time += 0.1
+ time.sleep(0.1)
+ server_process.close()
+
+
+@pytest.mark.parametrize(
+ "responder, read_method, parquet_engine",
+ [
+ (CSVUserAgentResponder, pd.read_csv, None),
+ (JSONUserAgentResponder, pd.read_json, None),
+ (
+ HTMLUserAgentResponder,
+ lambda *args, **kwargs: pd.read_html(*args, **kwargs)[0],
+ None,
+ ),
+ (ParquetPyArrowUserAgentResponder, pd.read_parquet, "pyarrow"),
+ pytest.param(
+ ParquetFastParquetUserAgentResponder,
+ pd.read_parquet,
+ "fastparquet",
+ # TODO(ArrayManager) fastparquet
+ marks=[
+ td.skip_array_manager_not_yet_implemented,
+ ],
+ ),
+ (PickleUserAgentResponder, pd.read_pickle, None),
+ (StataUserAgentResponder, pd.read_stata, None),
+ (GzippedCSVUserAgentResponder, pd.read_csv, None),
+ (GzippedJSONUserAgentResponder, pd.read_json, None),
+ ],
+ indirect=["responder"],
+)
+def test_server_and_default_headers(responder, read_method, parquet_engine):
+ if parquet_engine is not None:
+ pytest.importorskip(parquet_engine)
+ if parquet_engine == "fastparquet":
+ pytest.importorskip("fsspec")
+
+ read_method = wait_until_ready(read_method)
+ if parquet_engine is None:
+ df_http = read_method(f"http://localhost:{responder}")
+ else:
+ df_http = read_method(f"http://localhost:{responder}", engine=parquet_engine)
+
+ assert not df_http.empty
+
+
+@pytest.mark.parametrize(
+ "responder, read_method, parquet_engine",
+ [
+ (CSVUserAgentResponder, pd.read_csv, None),
+ (JSONUserAgentResponder, pd.read_json, None),
+ (
+ HTMLUserAgentResponder,
+ lambda *args, **kwargs: pd.read_html(*args, **kwargs)[0],
+ None,
+ ),
+ (ParquetPyArrowUserAgentResponder, pd.read_parquet, "pyarrow"),
+ pytest.param(
+ ParquetFastParquetUserAgentResponder,
+ pd.read_parquet,
+ "fastparquet",
+ # TODO(ArrayManager) fastparquet
+ marks=[
+ td.skip_array_manager_not_yet_implemented,
+ ],
+ ),
+ (PickleUserAgentResponder, pd.read_pickle, None),
+ (StataUserAgentResponder, pd.read_stata, None),
+ (GzippedCSVUserAgentResponder, pd.read_csv, None),
+ (GzippedJSONUserAgentResponder, pd.read_json, None),
+ ],
+ indirect=["responder"],
+)
+def test_server_and_custom_headers(responder, read_method, parquet_engine):
+ if parquet_engine is not None:
+ pytest.importorskip(parquet_engine)
+ if parquet_engine == "fastparquet":
+ pytest.importorskip("fsspec")
+
+ custom_user_agent = "Super Cool One"
+ df_true = pd.DataFrame({"header": [custom_user_agent]})
+
+ read_method = wait_until_ready(read_method)
+ if parquet_engine is None:
+ df_http = read_method(
+ f"http://localhost:{responder}",
+ storage_options={"User-Agent": custom_user_agent},
+ )
+ else:
+ df_http = read_method(
+ f"http://localhost:{responder}",
+ storage_options={"User-Agent": custom_user_agent},
+ engine=parquet_engine,
+ )
+
+ tm.assert_frame_equal(df_true, df_http)
+
+
+@pytest.mark.parametrize(
+ "responder, read_method",
+ [
+ (AllHeaderCSVResponder, pd.read_csv),
+ ],
+ indirect=["responder"],
+)
+def test_server_and_all_custom_headers(responder, read_method):
+ custom_user_agent = "Super Cool One"
+ custom_auth_token = "Super Secret One"
+ storage_options = {
+ "User-Agent": custom_user_agent,
+ "Auth": custom_auth_token,
+ }
+ read_method = wait_until_ready(read_method)
+ df_http = read_method(
+ f"http://localhost:{responder}",
+ storage_options=storage_options,
+ )
+
+ df_http = df_http[df_http["0"].isin(storage_options.keys())]
+ df_http = df_http.sort_values(["0"]).reset_index()
+ df_http = df_http[["0", "1"]]
+
+ keys = list(storage_options.keys())
+ df_true = pd.DataFrame({"0": keys, "1": [storage_options[k] for k in keys]})
+ df_true = df_true.sort_values(["0"])
+ df_true = df_true.reset_index().drop(["index"], axis=1)
+
+ tm.assert_frame_equal(df_true, df_http)
+
+
+@pytest.mark.parametrize(
+ "engine",
+ [
+ "pyarrow",
+ "fastparquet",
+ ],
+)
+def test_to_parquet_to_disk_with_storage_options(engine):
+ headers = {
+ "User-Agent": "custom",
+ "Auth": "other_custom",
+ }
+
+ pytest.importorskip(engine)
+
+ true_df = pd.DataFrame({"column_name": ["column_value"]})
+ msg = (
+ "storage_options passed with file object or non-fsspec file path|"
+ "storage_options passed with buffer, or non-supported URL"
+ )
+ with pytest.raises(ValueError, match=msg):
+ true_df.to_parquet("/tmp/junk.parquet", storage_options=headers, engine=engine)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/test_hashtable.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/test_hashtable.py
new file mode 100644
index 0000000000000000000000000000000000000000..b78e6426ca17fb5fae899402d667f79d4a92f60d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/test_hashtable.py
@@ -0,0 +1,737 @@
+from collections.abc import Generator
+from contextlib import contextmanager
+import re
+import struct
+import tracemalloc
+
+import numpy as np
+import pytest
+
+from pandas._libs import hashtable as ht
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.algorithms import isin
+
+
+@contextmanager
+def activated_tracemalloc() -> Generator[None, None, None]:
+ tracemalloc.start()
+ try:
+ yield
+ finally:
+ tracemalloc.stop()
+
+
+def get_allocated_khash_memory():
+ snapshot = tracemalloc.take_snapshot()
+ snapshot = snapshot.filter_traces(
+ (tracemalloc.DomainFilter(True, ht.get_hashtable_trace_domain()),)
+ )
+ return sum(x.size for x in snapshot.traces)
+
+
+@pytest.mark.parametrize(
+ "table_type, dtype",
+ [
+ (ht.PyObjectHashTable, np.object_),
+ (ht.Complex128HashTable, np.complex128),
+ (ht.Int64HashTable, np.int64),
+ (ht.UInt64HashTable, np.uint64),
+ (ht.Float64HashTable, np.float64),
+ (ht.Complex64HashTable, np.complex64),
+ (ht.Int32HashTable, np.int32),
+ (ht.UInt32HashTable, np.uint32),
+ (ht.Float32HashTable, np.float32),
+ (ht.Int16HashTable, np.int16),
+ (ht.UInt16HashTable, np.uint16),
+ (ht.Int8HashTable, np.int8),
+ (ht.UInt8HashTable, np.uint8),
+ (ht.IntpHashTable, np.intp),
+ ],
+)
+class TestHashTable:
+ def test_get_set_contains_len(self, table_type, dtype):
+ index = 5
+ table = table_type(55)
+ assert len(table) == 0
+ assert index not in table
+
+ table.set_item(index, 42)
+ assert len(table) == 1
+ assert index in table
+ assert table.get_item(index) == 42
+
+ table.set_item(index + 1, 41)
+ assert index in table
+ assert index + 1 in table
+ assert len(table) == 2
+ assert table.get_item(index) == 42
+ assert table.get_item(index + 1) == 41
+
+ table.set_item(index, 21)
+ assert index in table
+ assert index + 1 in table
+ assert len(table) == 2
+ assert table.get_item(index) == 21
+ assert table.get_item(index + 1) == 41
+ assert index + 2 not in table
+
+ table.set_item(index + 1, 21)
+ assert index in table
+ assert index + 1 in table
+ assert len(table) == 2
+ assert table.get_item(index) == 21
+ assert table.get_item(index + 1) == 21
+
+ with pytest.raises(KeyError, match=str(index + 2)):
+ table.get_item(index + 2)
+
+ def test_get_set_contains_len_mask(self, table_type, dtype):
+ if table_type == ht.PyObjectHashTable:
+ pytest.skip("Mask not supported for object")
+ index = 5
+ table = table_type(55, uses_mask=True)
+ assert len(table) == 0
+ assert index not in table
+
+ table.set_item(index, 42)
+ assert len(table) == 1
+ assert index in table
+ assert table.get_item(index) == 42
+ with pytest.raises(KeyError, match="NA"):
+ table.get_na()
+
+ table.set_item(index + 1, 41)
+ table.set_na(41)
+ assert pd.NA in table
+ assert index in table
+ assert index + 1 in table
+ assert len(table) == 3
+ assert table.get_item(index) == 42
+ assert table.get_item(index + 1) == 41
+ assert table.get_na() == 41
+
+ table.set_na(21)
+ assert index in table
+ assert index + 1 in table
+ assert len(table) == 3
+ assert table.get_item(index + 1) == 41
+ assert table.get_na() == 21
+ assert index + 2 not in table
+
+ with pytest.raises(KeyError, match=str(index + 2)):
+ table.get_item(index + 2)
+
+ def test_map_keys_to_values(self, table_type, dtype, writable):
+ # only Int64HashTable has this method
+ if table_type == ht.Int64HashTable:
+ N = 77
+ table = table_type()
+ keys = np.arange(N).astype(dtype)
+ vals = np.arange(N).astype(np.int64) + N
+ keys.flags.writeable = writable
+ vals.flags.writeable = writable
+ table.map_keys_to_values(keys, vals)
+ for i in range(N):
+ assert table.get_item(keys[i]) == i + N
+
+ def test_map_locations(self, table_type, dtype, writable):
+ N = 8
+ table = table_type()
+ keys = (np.arange(N) + N).astype(dtype)
+ keys.flags.writeable = writable
+ table.map_locations(keys)
+ for i in range(N):
+ assert table.get_item(keys[i]) == i
+
+ def test_map_locations_mask(self, table_type, dtype, writable):
+ if table_type == ht.PyObjectHashTable:
+ pytest.skip("Mask not supported for object")
+ N = 3
+ table = table_type(uses_mask=True)
+ keys = (np.arange(N) + N).astype(dtype)
+ keys.flags.writeable = writable
+ table.map_locations(keys, np.array([False, False, True]))
+ for i in range(N - 1):
+ assert table.get_item(keys[i]) == i
+
+ with pytest.raises(KeyError, match=re.escape(str(keys[N - 1]))):
+ table.get_item(keys[N - 1])
+
+ assert table.get_na() == 2
+
+ def test_lookup(self, table_type, dtype, writable):
+ N = 3
+ table = table_type()
+ keys = (np.arange(N) + N).astype(dtype)
+ keys.flags.writeable = writable
+ table.map_locations(keys)
+ result = table.lookup(keys)
+ expected = np.arange(N)
+ tm.assert_numpy_array_equal(result.astype(np.int64), expected.astype(np.int64))
+
+ def test_lookup_wrong(self, table_type, dtype):
+ if dtype in (np.int8, np.uint8):
+ N = 100
+ else:
+ N = 512
+ table = table_type()
+ keys = (np.arange(N) + N).astype(dtype)
+ table.map_locations(keys)
+ wrong_keys = np.arange(N).astype(dtype)
+ result = table.lookup(wrong_keys)
+ assert np.all(result == -1)
+
+ def test_lookup_mask(self, table_type, dtype, writable):
+ if table_type == ht.PyObjectHashTable:
+ pytest.skip("Mask not supported for object")
+ N = 3
+ table = table_type(uses_mask=True)
+ keys = (np.arange(N) + N).astype(dtype)
+ mask = np.array([False, True, False])
+ keys.flags.writeable = writable
+ table.map_locations(keys, mask)
+ result = table.lookup(keys, mask)
+ expected = np.arange(N)
+ tm.assert_numpy_array_equal(result.astype(np.int64), expected.astype(np.int64))
+
+ result = table.lookup(np.array([1 + N]).astype(dtype), np.array([False]))
+ tm.assert_numpy_array_equal(
+ result.astype(np.int64), np.array([-1], dtype=np.int64)
+ )
+
+ def test_unique(self, table_type, dtype, writable):
+ if dtype in (np.int8, np.uint8):
+ N = 88
+ else:
+ N = 1000
+ table = table_type()
+ expected = (np.arange(N) + N).astype(dtype)
+ keys = np.repeat(expected, 5)
+ keys.flags.writeable = writable
+ unique = table.unique(keys)
+ tm.assert_numpy_array_equal(unique, expected)
+
+ def test_tracemalloc_works(self, table_type, dtype):
+ if dtype in (np.int8, np.uint8):
+ N = 256
+ else:
+ N = 30000
+ keys = np.arange(N).astype(dtype)
+ with activated_tracemalloc():
+ table = table_type()
+ table.map_locations(keys)
+ used = get_allocated_khash_memory()
+ my_size = table.sizeof()
+ assert used == my_size
+ del table
+ assert get_allocated_khash_memory() == 0
+
+ def test_tracemalloc_for_empty(self, table_type, dtype):
+ with activated_tracemalloc():
+ table = table_type()
+ used = get_allocated_khash_memory()
+ my_size = table.sizeof()
+ assert used == my_size
+ del table
+ assert get_allocated_khash_memory() == 0
+
+ def test_get_state(self, table_type, dtype):
+ table = table_type(1000)
+ state = table.get_state()
+ assert state["size"] == 0
+ assert state["n_occupied"] == 0
+ assert "n_buckets" in state
+ assert "upper_bound" in state
+
+ @pytest.mark.parametrize("N", range(1, 110))
+ def test_no_reallocation(self, table_type, dtype, N):
+ keys = np.arange(N).astype(dtype)
+ preallocated_table = table_type(N)
+ n_buckets_start = preallocated_table.get_state()["n_buckets"]
+ preallocated_table.map_locations(keys)
+ n_buckets_end = preallocated_table.get_state()["n_buckets"]
+ # original number of buckets was enough:
+ assert n_buckets_start == n_buckets_end
+ # check with clean table (not too much preallocated)
+ clean_table = table_type()
+ clean_table.map_locations(keys)
+ assert n_buckets_start == clean_table.get_state()["n_buckets"]
+
+
+class TestHashTableUnsorted:
+ # TODO: moved from test_algos; may be redundancies with other tests
+ def test_string_hashtable_set_item_signature(self):
+ # GH#30419 fix typing in StringHashTable.set_item to prevent segfault
+ tbl = ht.StringHashTable()
+
+ tbl.set_item("key", 1)
+ assert tbl.get_item("key") == 1
+
+ with pytest.raises(TypeError, match="'key' has incorrect type"):
+ # key arg typed as string, not object
+ tbl.set_item(4, 6)
+ with pytest.raises(TypeError, match="'val' has incorrect type"):
+ tbl.get_item(4)
+
+ def test_lookup_nan(self, writable):
+ # GH#21688 ensure we can deal with readonly memory views
+ xs = np.array([2.718, 3.14, np.nan, -7, 5, 2, 3])
+ xs.setflags(write=writable)
+ m = ht.Float64HashTable()
+ m.map_locations(xs)
+ tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.intp))
+
+ def test_add_signed_zeros(self):
+ # GH#21866 inconsistent hash-function for float64
+ # default hash-function would lead to different hash-buckets
+ # for 0.0 and -0.0 if there are more than 2^30 hash-buckets
+ # but this would mean 16GB
+ N = 4 # 12 * 10**8 would trigger the error, if you have enough memory
+ m = ht.Float64HashTable(N)
+ m.set_item(0.0, 0)
+ m.set_item(-0.0, 0)
+ assert len(m) == 1 # 0.0 and -0.0 are equivalent
+
+ def test_add_different_nans(self):
+ # GH#21866 inconsistent hash-function for float64
+ # create different nans from bit-patterns:
+ NAN1 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000000))[0]
+ NAN2 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000001))[0]
+ assert NAN1 != NAN1
+ assert NAN2 != NAN2
+ # default hash function would lead to different hash-buckets
+ # for NAN1 and NAN2 even if there are only 4 buckets:
+ m = ht.Float64HashTable()
+ m.set_item(NAN1, 0)
+ m.set_item(NAN2, 0)
+ assert len(m) == 1 # NAN1 and NAN2 are equivalent
+
+ def test_lookup_overflow(self, writable):
+ xs = np.array([1, 2, 2**63], dtype=np.uint64)
+ # GH 21688 ensure we can deal with readonly memory views
+ xs.setflags(write=writable)
+ m = ht.UInt64HashTable()
+ m.map_locations(xs)
+ tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.intp))
+
+ @pytest.mark.parametrize("nvals", [0, 10]) # resizing to 0 is special case
+ @pytest.mark.parametrize(
+ "htable, uniques, dtype, safely_resizes",
+ [
+ (ht.PyObjectHashTable, ht.ObjectVector, "object", False),
+ (ht.StringHashTable, ht.ObjectVector, "object", True),
+ (ht.Float64HashTable, ht.Float64Vector, "float64", False),
+ (ht.Int64HashTable, ht.Int64Vector, "int64", False),
+ (ht.Int32HashTable, ht.Int32Vector, "int32", False),
+ (ht.UInt64HashTable, ht.UInt64Vector, "uint64", False),
+ ],
+ )
+ def test_vector_resize(
+ self, writable, htable, uniques, dtype, safely_resizes, nvals
+ ):
+ # Test for memory errors after internal vector
+ # reallocations (GH 7157)
+ # Changed from using np.random.default_rng(2).rand to range
+ # which could cause flaky CI failures when safely_resizes=False
+ vals = np.array(range(1000), dtype=dtype)
+
+ # GH 21688 ensures we can deal with read-only memory views
+ vals.setflags(write=writable)
+
+ # initialise instances; cannot initialise in parametrization,
+ # as otherwise external views would be held on the array (which is
+ # one of the things this test is checking)
+ htable = htable()
+ uniques = uniques()
+
+ # get_labels may append to uniques
+ htable.get_labels(vals[:nvals], uniques, 0, -1)
+ # to_array() sets an external_view_exists flag on uniques.
+ tmp = uniques.to_array()
+ oldshape = tmp.shape
+
+ # subsequent get_labels() calls can no longer append to it
+ # (except for StringHashTables + ObjectVector)
+ if safely_resizes:
+ htable.get_labels(vals, uniques, 0, -1)
+ else:
+ with pytest.raises(ValueError, match="external reference.*"):
+ htable.get_labels(vals, uniques, 0, -1)
+
+ uniques.to_array() # should not raise here
+ assert tmp.shape == oldshape
+
+ @pytest.mark.parametrize(
+ "hashtable",
+ [
+ ht.PyObjectHashTable,
+ ht.StringHashTable,
+ ht.Float64HashTable,
+ ht.Int64HashTable,
+ ht.Int32HashTable,
+ ht.UInt64HashTable,
+ ],
+ )
+ def test_hashtable_large_sizehint(self, hashtable):
+ # GH#22729 smoketest for not raising when passing a large size_hint
+ size_hint = np.iinfo(np.uint32).max + 1
+ hashtable(size_hint=size_hint)
+
+
+class TestPyObjectHashTableWithNans:
+ def test_nan_float(self):
+ nan1 = float("nan")
+ nan2 = float("nan")
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+
+ def test_nan_complex_both(self):
+ nan1 = complex(float("nan"), float("nan"))
+ nan2 = complex(float("nan"), float("nan"))
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+
+ def test_nan_complex_real(self):
+ nan1 = complex(float("nan"), 1)
+ nan2 = complex(float("nan"), 1)
+ other = complex(float("nan"), 2)
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+ with pytest.raises(KeyError, match=None) as error:
+ table.get_item(other)
+ assert str(error.value) == str(other)
+
+ def test_nan_complex_imag(self):
+ nan1 = complex(1, float("nan"))
+ nan2 = complex(1, float("nan"))
+ other = complex(2, float("nan"))
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+ with pytest.raises(KeyError, match=None) as error:
+ table.get_item(other)
+ assert str(error.value) == str(other)
+
+ def test_nan_in_tuple(self):
+ nan1 = (float("nan"),)
+ nan2 = (float("nan"),)
+ assert nan1[0] is not nan2[0]
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+
+ def test_nan_in_nested_tuple(self):
+ nan1 = (1, (2, (float("nan"),)))
+ nan2 = (1, (2, (float("nan"),)))
+ other = (1, 2)
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+ with pytest.raises(KeyError, match=None) as error:
+ table.get_item(other)
+ assert str(error.value) == str(other)
+
+
+def test_hash_equal_tuple_with_nans():
+ a = (float("nan"), (float("nan"), float("nan")))
+ b = (float("nan"), (float("nan"), float("nan")))
+ assert ht.object_hash(a) == ht.object_hash(b)
+ assert ht.objects_are_equal(a, b)
+
+
+def test_get_labels_groupby_for_Int64(writable):
+ table = ht.Int64HashTable()
+ vals = np.array([1, 2, -1, 2, 1, -1], dtype=np.int64)
+ vals.flags.writeable = writable
+ arr, unique = table.get_labels_groupby(vals)
+ expected_arr = np.array([0, 1, -1, 1, 0, -1], dtype=np.intp)
+ expected_unique = np.array([1, 2], dtype=np.int64)
+ tm.assert_numpy_array_equal(arr, expected_arr)
+ tm.assert_numpy_array_equal(unique, expected_unique)
+
+
+def test_tracemalloc_works_for_StringHashTable():
+ N = 1000
+ keys = np.arange(N).astype(np.str_).astype(np.object_)
+ with activated_tracemalloc():
+ table = ht.StringHashTable()
+ table.map_locations(keys)
+ used = get_allocated_khash_memory()
+ my_size = table.sizeof()
+ assert used == my_size
+ del table
+ assert get_allocated_khash_memory() == 0
+
+
+def test_tracemalloc_for_empty_StringHashTable():
+ with activated_tracemalloc():
+ table = ht.StringHashTable()
+ used = get_allocated_khash_memory()
+ my_size = table.sizeof()
+ assert used == my_size
+ del table
+ assert get_allocated_khash_memory() == 0
+
+
+@pytest.mark.parametrize("N", range(1, 110))
+def test_no_reallocation_StringHashTable(N):
+ keys = np.arange(N).astype(np.str_).astype(np.object_)
+ preallocated_table = ht.StringHashTable(N)
+ n_buckets_start = preallocated_table.get_state()["n_buckets"]
+ preallocated_table.map_locations(keys)
+ n_buckets_end = preallocated_table.get_state()["n_buckets"]
+ # original number of buckets was enough:
+ assert n_buckets_start == n_buckets_end
+ # check with clean table (not too much preallocated)
+ clean_table = ht.StringHashTable()
+ clean_table.map_locations(keys)
+ assert n_buckets_start == clean_table.get_state()["n_buckets"]
+
+
+@pytest.mark.parametrize(
+ "table_type, dtype",
+ [
+ (ht.Float64HashTable, np.float64),
+ (ht.Float32HashTable, np.float32),
+ (ht.Complex128HashTable, np.complex128),
+ (ht.Complex64HashTable, np.complex64),
+ ],
+)
+class TestHashTableWithNans:
+ def test_get_set_contains_len(self, table_type, dtype):
+ index = float("nan")
+ table = table_type()
+ assert index not in table
+
+ table.set_item(index, 42)
+ assert len(table) == 1
+ assert index in table
+ assert table.get_item(index) == 42
+
+ table.set_item(index, 41)
+ assert len(table) == 1
+ assert index in table
+ assert table.get_item(index) == 41
+
+ def test_map_locations(self, table_type, dtype):
+ N = 10
+ table = table_type()
+ keys = np.full(N, np.nan, dtype=dtype)
+ table.map_locations(keys)
+ assert len(table) == 1
+ assert table.get_item(np.nan) == N - 1
+
+ def test_unique(self, table_type, dtype):
+ N = 1020
+ table = table_type()
+ keys = np.full(N, np.nan, dtype=dtype)
+ unique = table.unique(keys)
+ assert np.all(np.isnan(unique)) and len(unique) == 1
+
+
+def test_unique_for_nan_objects_floats():
+ table = ht.PyObjectHashTable()
+ keys = np.array([float("nan") for i in range(50)], dtype=np.object_)
+ unique = table.unique(keys)
+ assert len(unique) == 1
+
+
+def test_unique_for_nan_objects_complex():
+ table = ht.PyObjectHashTable()
+ keys = np.array([complex(float("nan"), 1.0) for i in range(50)], dtype=np.object_)
+ unique = table.unique(keys)
+ assert len(unique) == 1
+
+
+def test_unique_for_nan_objects_tuple():
+ table = ht.PyObjectHashTable()
+ keys = np.array(
+ [1] + [(1.0, (float("nan"), 1.0)) for i in range(50)], dtype=np.object_
+ )
+ unique = table.unique(keys)
+ assert len(unique) == 2
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ np.object_,
+ np.complex128,
+ np.int64,
+ np.uint64,
+ np.float64,
+ np.complex64,
+ np.int32,
+ np.uint32,
+ np.float32,
+ np.int16,
+ np.uint16,
+ np.int8,
+ np.uint8,
+ np.intp,
+ ],
+)
+class TestHelpFunctions:
+ def test_value_count(self, dtype, writable):
+ N = 43
+ expected = (np.arange(N) + N).astype(dtype)
+ values = np.repeat(expected, 5)
+ values.flags.writeable = writable
+ keys, counts = ht.value_count(values, False)
+ tm.assert_numpy_array_equal(np.sort(keys), expected)
+ assert np.all(counts == 5)
+
+ def test_value_count_stable(self, dtype, writable):
+ # GH12679
+ values = np.array([2, 1, 5, 22, 3, -1, 8]).astype(dtype)
+ values.flags.writeable = writable
+ keys, counts = ht.value_count(values, False)
+ tm.assert_numpy_array_equal(keys, values)
+ assert np.all(counts == 1)
+
+ def test_duplicated_first(self, dtype, writable):
+ N = 100
+ values = np.repeat(np.arange(N).astype(dtype), 5)
+ values.flags.writeable = writable
+ result = ht.duplicated(values)
+ expected = np.ones_like(values, dtype=np.bool_)
+ expected[::5] = False
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_ismember_yes(self, dtype, writable):
+ N = 127
+ arr = np.arange(N).astype(dtype)
+ values = np.arange(N).astype(dtype)
+ arr.flags.writeable = writable
+ values.flags.writeable = writable
+ result = ht.ismember(arr, values)
+ expected = np.ones_like(values, dtype=np.bool_)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_ismember_no(self, dtype):
+ N = 17
+ arr = np.arange(N).astype(dtype)
+ values = (np.arange(N) + N).astype(dtype)
+ result = ht.ismember(arr, values)
+ expected = np.zeros_like(values, dtype=np.bool_)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_mode(self, dtype, writable):
+ if dtype in (np.int8, np.uint8):
+ N = 53
+ else:
+ N = 11111
+ values = np.repeat(np.arange(N).astype(dtype), 5)
+ values[0] = 42
+ values.flags.writeable = writable
+ result = ht.mode(values, False)
+ assert result == 42
+
+ def test_mode_stable(self, dtype, writable):
+ values = np.array([2, 1, 5, 22, 3, -1, 8]).astype(dtype)
+ values.flags.writeable = writable
+ keys = ht.mode(values, False)
+ tm.assert_numpy_array_equal(keys, values)
+
+
+def test_modes_with_nans():
+ # GH42688, nans aren't mangled
+ nulls = [pd.NA, np.nan, pd.NaT, None]
+ values = np.array([True] + nulls * 2, dtype=np.object_)
+ modes = ht.mode(values, False)
+ assert modes.size == len(nulls)
+
+
+def test_unique_label_indices_intp(writable):
+ keys = np.array([1, 2, 2, 2, 1, 3], dtype=np.intp)
+ keys.flags.writeable = writable
+ result = ht.unique_label_indices(keys)
+ expected = np.array([0, 1, 5], dtype=np.intp)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_unique_label_indices():
+ a = np.random.default_rng(2).integers(1, 1 << 10, 1 << 15).astype(np.intp)
+
+ left = ht.unique_label_indices(a)
+ right = np.unique(a, return_index=True)[1]
+
+ tm.assert_numpy_array_equal(left, right, check_dtype=False)
+
+ a[np.random.default_rng(2).choice(len(a), 10)] = -1
+ left = ht.unique_label_indices(a)
+ right = np.unique(a, return_index=True)[1][1:]
+ tm.assert_numpy_array_equal(left, right, check_dtype=False)
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ np.float64,
+ np.float32,
+ np.complex128,
+ np.complex64,
+ ],
+)
+class TestHelpFunctionsWithNans:
+ def test_value_count(self, dtype):
+ values = np.array([np.nan, np.nan, np.nan], dtype=dtype)
+ keys, counts = ht.value_count(values, True)
+ assert len(keys) == 0
+ keys, counts = ht.value_count(values, False)
+ assert len(keys) == 1 and np.all(np.isnan(keys))
+ assert counts[0] == 3
+
+ def test_duplicated_first(self, dtype):
+ values = np.array([np.nan, np.nan, np.nan], dtype=dtype)
+ result = ht.duplicated(values)
+ expected = np.array([False, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_ismember_yes(self, dtype):
+ arr = np.array([np.nan, np.nan, np.nan], dtype=dtype)
+ values = np.array([np.nan, np.nan], dtype=dtype)
+ result = ht.ismember(arr, values)
+ expected = np.array([True, True, True], dtype=np.bool_)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_ismember_no(self, dtype):
+ arr = np.array([np.nan, np.nan, np.nan], dtype=dtype)
+ values = np.array([1], dtype=dtype)
+ result = ht.ismember(arr, values)
+ expected = np.array([False, False, False], dtype=np.bool_)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_mode(self, dtype):
+ values = np.array([42, np.nan, np.nan, np.nan], dtype=dtype)
+ assert ht.mode(values, True) == 42
+ assert np.isnan(ht.mode(values, False))
+
+
+def test_ismember_tuple_with_nans():
+ # GH-41836
+ values = [("a", float("nan")), ("b", 1)]
+ comps = [("a", float("nan"))]
+
+ msg = "isin with argument that is not not a Series"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = isin(values, comps)
+ expected = np.array([True, False], dtype=np.bool_)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_float_complex_int_are_equal_as_objects():
+ values = ["a", 5, 5.0, 5.0 + 0j]
+ comps = list(range(129))
+ result = isin(np.array(values, dtype=object), np.asarray(comps))
+ expected = np.array([False, True, True, True], dtype=np.bool_)
+ tm.assert_numpy_array_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/test_join.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/test_join.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba2e6e713092916648d375a991e3cb4d9fc7828d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/test_join.py
@@ -0,0 +1,390 @@
+import numpy as np
+import pytest
+
+from pandas._libs import join as libjoin
+from pandas._libs.join import (
+ inner_join,
+ left_outer_join,
+)
+
+import pandas._testing as tm
+
+
+class TestIndexer:
+ @pytest.mark.parametrize(
+ "dtype", ["int32", "int64", "float32", "float64", "object"]
+ )
+ def test_outer_join_indexer(self, dtype):
+ indexer = libjoin.outer_join_indexer
+
+ left = np.arange(3, dtype=dtype)
+ right = np.arange(2, 5, dtype=dtype)
+ empty = np.array([], dtype=dtype)
+
+ result, lindexer, rindexer = indexer(left, right)
+ assert isinstance(result, np.ndarray)
+ assert isinstance(lindexer, np.ndarray)
+ assert isinstance(rindexer, np.ndarray)
+ tm.assert_numpy_array_equal(result, np.arange(5, dtype=dtype))
+ exp = np.array([0, 1, 2, -1, -1], dtype=np.intp)
+ tm.assert_numpy_array_equal(lindexer, exp)
+ exp = np.array([-1, -1, 0, 1, 2], dtype=np.intp)
+ tm.assert_numpy_array_equal(rindexer, exp)
+
+ result, lindexer, rindexer = indexer(empty, right)
+ tm.assert_numpy_array_equal(result, right)
+ exp = np.array([-1, -1, -1], dtype=np.intp)
+ tm.assert_numpy_array_equal(lindexer, exp)
+ exp = np.array([0, 1, 2], dtype=np.intp)
+ tm.assert_numpy_array_equal(rindexer, exp)
+
+ result, lindexer, rindexer = indexer(left, empty)
+ tm.assert_numpy_array_equal(result, left)
+ exp = np.array([0, 1, 2], dtype=np.intp)
+ tm.assert_numpy_array_equal(lindexer, exp)
+ exp = np.array([-1, -1, -1], dtype=np.intp)
+ tm.assert_numpy_array_equal(rindexer, exp)
+
+ def test_cython_left_outer_join(self):
+ left = np.array([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.intp)
+ right = np.array([1, 1, 0, 4, 2, 2, 1], dtype=np.intp)
+ max_group = 5
+
+ ls, rs = left_outer_join(left, right, max_group)
+
+ exp_ls = left.argsort(kind="mergesort")
+ exp_rs = right.argsort(kind="mergesort")
+
+ exp_li = np.array([0, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8, 9, 10])
+ exp_ri = np.array(
+ [0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5, 4, 5, 4, 5, -1, -1]
+ )
+
+ exp_ls = exp_ls.take(exp_li)
+ exp_ls[exp_li == -1] = -1
+
+ exp_rs = exp_rs.take(exp_ri)
+ exp_rs[exp_ri == -1] = -1
+
+ tm.assert_numpy_array_equal(ls, exp_ls, check_dtype=False)
+ tm.assert_numpy_array_equal(rs, exp_rs, check_dtype=False)
+
+ def test_cython_right_outer_join(self):
+ left = np.array([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.intp)
+ right = np.array([1, 1, 0, 4, 2, 2, 1], dtype=np.intp)
+ max_group = 5
+
+ rs, ls = left_outer_join(right, left, max_group)
+
+ exp_ls = left.argsort(kind="mergesort")
+ exp_rs = right.argsort(kind="mergesort")
+
+ # 0 1 1 1
+ exp_li = np.array(
+ [
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 3,
+ 4,
+ 5,
+ 3,
+ 4,
+ 5,
+ # 2 2 4
+ 6,
+ 7,
+ 8,
+ 6,
+ 7,
+ 8,
+ -1,
+ ]
+ )
+ exp_ri = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6])
+
+ exp_ls = exp_ls.take(exp_li)
+ exp_ls[exp_li == -1] = -1
+
+ exp_rs = exp_rs.take(exp_ri)
+ exp_rs[exp_ri == -1] = -1
+
+ tm.assert_numpy_array_equal(ls, exp_ls)
+ tm.assert_numpy_array_equal(rs, exp_rs)
+
+ def test_cython_inner_join(self):
+ left = np.array([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.intp)
+ right = np.array([1, 1, 0, 4, 2, 2, 1, 4], dtype=np.intp)
+ max_group = 5
+
+ ls, rs = inner_join(left, right, max_group)
+
+ exp_ls = left.argsort(kind="mergesort")
+ exp_rs = right.argsort(kind="mergesort")
+
+ exp_li = np.array([0, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8])
+ exp_ri = np.array([0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5, 4, 5, 4, 5])
+
+ exp_ls = exp_ls.take(exp_li)
+ exp_ls[exp_li == -1] = -1
+
+ exp_rs = exp_rs.take(exp_ri)
+ exp_rs[exp_ri == -1] = -1
+
+ tm.assert_numpy_array_equal(ls, exp_ls)
+ tm.assert_numpy_array_equal(rs, exp_rs)
+
+
+@pytest.mark.parametrize("readonly", [True, False])
+def test_left_join_indexer_unique(readonly):
+ a = np.array([1, 2, 3, 4, 5], dtype=np.int64)
+ b = np.array([2, 2, 3, 4, 4], dtype=np.int64)
+ if readonly:
+ # GH#37312, GH#37264
+ a.setflags(write=False)
+ b.setflags(write=False)
+
+ result = libjoin.left_join_indexer_unique(b, a)
+ expected = np.array([1, 1, 2, 3, 3], dtype=np.intp)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_left_outer_join_bug():
+ left = np.array(
+ [
+ 0,
+ 1,
+ 0,
+ 1,
+ 1,
+ 2,
+ 3,
+ 1,
+ 0,
+ 2,
+ 1,
+ 2,
+ 0,
+ 1,
+ 1,
+ 2,
+ 3,
+ 2,
+ 3,
+ 2,
+ 1,
+ 1,
+ 3,
+ 0,
+ 3,
+ 2,
+ 3,
+ 0,
+ 0,
+ 2,
+ 3,
+ 2,
+ 0,
+ 3,
+ 1,
+ 3,
+ 0,
+ 1,
+ 3,
+ 0,
+ 0,
+ 1,
+ 0,
+ 3,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 1,
+ 0,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 0,
+ 3,
+ 1,
+ 2,
+ 0,
+ 0,
+ 3,
+ 1,
+ 3,
+ 2,
+ 2,
+ 0,
+ 1,
+ 3,
+ 0,
+ 2,
+ 3,
+ 2,
+ 3,
+ 3,
+ 2,
+ 3,
+ 3,
+ 1,
+ 3,
+ 2,
+ 0,
+ 0,
+ 3,
+ 1,
+ 1,
+ 1,
+ 0,
+ 2,
+ 3,
+ 3,
+ 1,
+ 2,
+ 0,
+ 3,
+ 1,
+ 2,
+ 0,
+ 2,
+ ],
+ dtype=np.intp,
+ )
+
+ right = np.array([3, 1], dtype=np.intp)
+ max_groups = 4
+
+ lidx, ridx = libjoin.left_outer_join(left, right, max_groups, sort=False)
+
+ exp_lidx = np.arange(len(left), dtype=np.intp)
+ exp_ridx = -np.ones(len(left), dtype=np.intp)
+
+ exp_ridx[left == 1] = 1
+ exp_ridx[left == 3] = 0
+
+ tm.assert_numpy_array_equal(lidx, exp_lidx)
+ tm.assert_numpy_array_equal(ridx, exp_ridx)
+
+
+def test_inner_join_indexer():
+ a = np.array([1, 2, 3, 4, 5], dtype=np.int64)
+ b = np.array([0, 3, 5, 7, 9], dtype=np.int64)
+
+ index, ares, bres = libjoin.inner_join_indexer(a, b)
+
+ index_exp = np.array([3, 5], dtype=np.int64)
+ tm.assert_almost_equal(index, index_exp)
+
+ aexp = np.array([2, 4], dtype=np.intp)
+ bexp = np.array([1, 2], dtype=np.intp)
+ tm.assert_almost_equal(ares, aexp)
+ tm.assert_almost_equal(bres, bexp)
+
+ a = np.array([5], dtype=np.int64)
+ b = np.array([5], dtype=np.int64)
+
+ index, ares, bres = libjoin.inner_join_indexer(a, b)
+ tm.assert_numpy_array_equal(index, np.array([5], dtype=np.int64))
+ tm.assert_numpy_array_equal(ares, np.array([0], dtype=np.intp))
+ tm.assert_numpy_array_equal(bres, np.array([0], dtype=np.intp))
+
+
+def test_outer_join_indexer():
+ a = np.array([1, 2, 3, 4, 5], dtype=np.int64)
+ b = np.array([0, 3, 5, 7, 9], dtype=np.int64)
+
+ index, ares, bres = libjoin.outer_join_indexer(a, b)
+
+ index_exp = np.array([0, 1, 2, 3, 4, 5, 7, 9], dtype=np.int64)
+ tm.assert_almost_equal(index, index_exp)
+
+ aexp = np.array([-1, 0, 1, 2, 3, 4, -1, -1], dtype=np.intp)
+ bexp = np.array([0, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp)
+ tm.assert_almost_equal(ares, aexp)
+ tm.assert_almost_equal(bres, bexp)
+
+ a = np.array([5], dtype=np.int64)
+ b = np.array([5], dtype=np.int64)
+
+ index, ares, bres = libjoin.outer_join_indexer(a, b)
+ tm.assert_numpy_array_equal(index, np.array([5], dtype=np.int64))
+ tm.assert_numpy_array_equal(ares, np.array([0], dtype=np.intp))
+ tm.assert_numpy_array_equal(bres, np.array([0], dtype=np.intp))
+
+
+def test_left_join_indexer():
+ a = np.array([1, 2, 3, 4, 5], dtype=np.int64)
+ b = np.array([0, 3, 5, 7, 9], dtype=np.int64)
+
+ index, ares, bres = libjoin.left_join_indexer(a, b)
+
+ tm.assert_almost_equal(index, a)
+
+ aexp = np.array([0, 1, 2, 3, 4], dtype=np.intp)
+ bexp = np.array([-1, -1, 1, -1, 2], dtype=np.intp)
+ tm.assert_almost_equal(ares, aexp)
+ tm.assert_almost_equal(bres, bexp)
+
+ a = np.array([5], dtype=np.int64)
+ b = np.array([5], dtype=np.int64)
+
+ index, ares, bres = libjoin.left_join_indexer(a, b)
+ tm.assert_numpy_array_equal(index, np.array([5], dtype=np.int64))
+ tm.assert_numpy_array_equal(ares, np.array([0], dtype=np.intp))
+ tm.assert_numpy_array_equal(bres, np.array([0], dtype=np.intp))
+
+
+def test_left_join_indexer2():
+ idx = np.array([1, 1, 2, 5], dtype=np.int64)
+ idx2 = np.array([1, 2, 5, 7, 9], dtype=np.int64)
+
+ res, lidx, ridx = libjoin.left_join_indexer(idx2, idx)
+
+ exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64)
+ tm.assert_almost_equal(res, exp_res)
+
+ exp_lidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
+ tm.assert_almost_equal(lidx, exp_lidx)
+
+ exp_ridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
+ tm.assert_almost_equal(ridx, exp_ridx)
+
+
+def test_outer_join_indexer2():
+ idx = np.array([1, 1, 2, 5], dtype=np.int64)
+ idx2 = np.array([1, 2, 5, 7, 9], dtype=np.int64)
+
+ res, lidx, ridx = libjoin.outer_join_indexer(idx2, idx)
+
+ exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64)
+ tm.assert_almost_equal(res, exp_res)
+
+ exp_lidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
+ tm.assert_almost_equal(lidx, exp_lidx)
+
+ exp_ridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
+ tm.assert_almost_equal(ridx, exp_ridx)
+
+
+def test_inner_join_indexer2():
+ idx = np.array([1, 1, 2, 5], dtype=np.int64)
+ idx2 = np.array([1, 2, 5, 7, 9], dtype=np.int64)
+
+ res, lidx, ridx = libjoin.inner_join_indexer(idx2, idx)
+
+ exp_res = np.array([1, 1, 2, 5], dtype=np.int64)
+ tm.assert_almost_equal(res, exp_res)
+
+ exp_lidx = np.array([0, 0, 1, 2], dtype=np.intp)
+ tm.assert_almost_equal(lidx, exp_lidx)
+
+ exp_ridx = np.array([0, 1, 2, 3], dtype=np.intp)
+ tm.assert_almost_equal(ridx, exp_ridx)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/test_lib.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/test_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..8583d8bcc052c4d76e090227272facca2faafa1f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/libs/test_lib.py
@@ -0,0 +1,285 @@
+import numpy as np
+import pytest
+
+from pandas._libs import (
+ Timedelta,
+ lib,
+ writers as libwriters,
+)
+from pandas.compat import IS64
+
+from pandas import Index
+import pandas._testing as tm
+
+
+class TestMisc:
+ def test_max_len_string_array(self):
+ arr = a = np.array(["foo", "b", np.nan], dtype="object")
+ assert libwriters.max_len_string_array(arr) == 3
+
+ # unicode
+ arr = a.astype("U").astype(object)
+ assert libwriters.max_len_string_array(arr) == 3
+
+ # bytes for python3
+ arr = a.astype("S").astype(object)
+ assert libwriters.max_len_string_array(arr) == 3
+
+ # raises
+ msg = "No matching signature found"
+ with pytest.raises(TypeError, match=msg):
+ libwriters.max_len_string_array(arr.astype("U"))
+
+ def test_fast_unique_multiple_list_gen_sort(self):
+ keys = [["p", "a"], ["n", "d"], ["a", "s"]]
+
+ gen = (key for key in keys)
+ expected = np.array(["a", "d", "n", "p", "s"])
+ out = lib.fast_unique_multiple_list_gen(gen, sort=True)
+ tm.assert_numpy_array_equal(np.array(out), expected)
+
+ gen = (key for key in keys)
+ expected = np.array(["p", "a", "n", "d", "s"])
+ out = lib.fast_unique_multiple_list_gen(gen, sort=False)
+ tm.assert_numpy_array_equal(np.array(out), expected)
+
+ def test_fast_multiget_timedelta_resos(self):
+ # This will become relevant for test_constructor_dict_timedelta64_index
+ # once Timedelta constructor preserves reso when passed a
+ # np.timedelta64 object
+ td = Timedelta(days=1)
+
+ mapping1 = {td: 1}
+ mapping2 = {td.as_unit("s"): 1}
+
+ oindex = Index([td * n for n in range(3)])._values.astype(object)
+
+ expected = lib.fast_multiget(mapping1, oindex)
+ result = lib.fast_multiget(mapping2, oindex)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # case that can't be cast to td64ns
+ td = Timedelta(np.timedelta64(146000, "D"))
+ assert hash(td) == hash(td.as_unit("ms"))
+ assert hash(td) == hash(td.as_unit("us"))
+ mapping1 = {td: 1}
+ mapping2 = {td.as_unit("ms"): 1}
+
+ oindex = Index([td * n for n in range(3)])._values.astype(object)
+
+ expected = lib.fast_multiget(mapping1, oindex)
+ result = lib.fast_multiget(mapping2, oindex)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+class TestIndexing:
+ def test_maybe_indices_to_slice_left_edge(self):
+ target = np.arange(100)
+
+ # slice
+ indices = np.array([], dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ @pytest.mark.parametrize("end", [1, 2, 5, 20, 99])
+ @pytest.mark.parametrize("step", [1, 2, 4])
+ def test_maybe_indices_to_slice_left_edge_not_slice_end_steps(self, end, step):
+ target = np.arange(100)
+ indices = np.arange(0, end, step, dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ # reverse
+ indices = indices[::-1]
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ @pytest.mark.parametrize(
+ "case", [[2, 1, 2, 0], [2, 2, 1, 0], [0, 1, 2, 1], [-2, 0, 2], [2, 0, -2]]
+ )
+ def test_maybe_indices_to_slice_left_edge_not_slice(self, case):
+ # not slice
+ target = np.arange(100)
+ indices = np.array(case, dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert not isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(maybe_slice, indices)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ @pytest.mark.parametrize("start", [0, 2, 5, 20, 97, 98])
+ @pytest.mark.parametrize("step", [1, 2, 4])
+ def test_maybe_indices_to_slice_right_edge(self, start, step):
+ target = np.arange(100)
+
+ # slice
+ indices = np.arange(start, 99, step, dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ # reverse
+ indices = indices[::-1]
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ def test_maybe_indices_to_slice_right_edge_not_slice(self):
+ # not slice
+ target = np.arange(100)
+ indices = np.array([97, 98, 99, 100], dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert not isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(maybe_slice, indices)
+
+ msg = "index 100 is out of bounds for axis (0|1) with size 100"
+
+ with pytest.raises(IndexError, match=msg):
+ target[indices]
+ with pytest.raises(IndexError, match=msg):
+ target[maybe_slice]
+
+ indices = np.array([100, 99, 98, 97], dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert not isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(maybe_slice, indices)
+
+ with pytest.raises(IndexError, match=msg):
+ target[indices]
+ with pytest.raises(IndexError, match=msg):
+ target[maybe_slice]
+
+ @pytest.mark.parametrize(
+ "case", [[99, 97, 99, 96], [99, 99, 98, 97], [98, 98, 97, 96]]
+ )
+ def test_maybe_indices_to_slice_right_edge_cases(self, case):
+ target = np.arange(100)
+ indices = np.array(case, dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert not isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(maybe_slice, indices)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ @pytest.mark.parametrize("step", [1, 2, 4, 5, 8, 9])
+ def test_maybe_indices_to_slice_both_edges(self, step):
+ target = np.arange(10)
+
+ # slice
+ indices = np.arange(0, 9, step, dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+ assert isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ # reverse
+ indices = indices[::-1]
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+ assert isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ @pytest.mark.parametrize("case", [[4, 2, 0, -2], [2, 2, 1, 0], [0, 1, 2, 1]])
+ def test_maybe_indices_to_slice_both_edges_not_slice(self, case):
+ # not slice
+ target = np.arange(10)
+ indices = np.array(case, dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+ assert not isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(maybe_slice, indices)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ @pytest.mark.parametrize("start, end", [(2, 10), (5, 25), (65, 97)])
+ @pytest.mark.parametrize("step", [1, 2, 4, 20])
+ def test_maybe_indices_to_slice_middle(self, start, end, step):
+ target = np.arange(100)
+
+ # slice
+ indices = np.arange(start, end, step, dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ # reverse
+ indices = indices[::-1]
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ @pytest.mark.parametrize(
+ "case", [[14, 12, 10, 12], [12, 12, 11, 10], [10, 11, 12, 11]]
+ )
+ def test_maybe_indices_to_slice_middle_not_slice(self, case):
+ # not slice
+ target = np.arange(100)
+ indices = np.array(case, dtype=np.intp)
+ maybe_slice = lib.maybe_indices_to_slice(indices, len(target))
+
+ assert not isinstance(maybe_slice, slice)
+ tm.assert_numpy_array_equal(maybe_slice, indices)
+ tm.assert_numpy_array_equal(target[indices], target[maybe_slice])
+
+ def test_maybe_booleans_to_slice(self):
+ arr = np.array([0, 0, 1, 1, 1, 0, 1], dtype=np.uint8)
+ result = lib.maybe_booleans_to_slice(arr)
+ assert result.dtype == np.bool_
+
+ result = lib.maybe_booleans_to_slice(arr[:0])
+ assert result == slice(0, 0)
+
+ def test_get_reverse_indexer(self):
+ indexer = np.array([-1, -1, 1, 2, 0, -1, 3, 4], dtype=np.intp)
+ result = lib.get_reverse_indexer(indexer, 5)
+ expected = np.array([4, 2, 3, 6, 7], dtype=np.intp)
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["int64", "int32"])
+ def test_is_range_indexer(self, dtype):
+ # GH#50592
+ left = np.arange(0, 100, dtype=dtype)
+ assert lib.is_range_indexer(left, 100)
+
+ @pytest.mark.skipif(
+ not IS64,
+ reason="2**31 is too big for Py_ssize_t on 32-bit. "
+ "It doesn't matter though since you cannot create an array that long on 32-bit",
+ )
+ @pytest.mark.parametrize("dtype", ["int64", "int32"])
+ def test_is_range_indexer_big_n(self, dtype):
+ # GH53616
+ left = np.arange(0, 100, dtype=dtype)
+
+ assert not lib.is_range_indexer(left, 2**31)
+
+ @pytest.mark.parametrize("dtype", ["int64", "int32"])
+ def test_is_range_indexer_not_equal(self, dtype):
+ # GH#50592
+ left = np.array([1, 2], dtype=dtype)
+ assert not lib.is_range_indexer(left, 2)
+
+ @pytest.mark.parametrize("dtype", ["int64", "int32"])
+ def test_is_range_indexer_not_equal_shape(self, dtype):
+ # GH#50592
+ left = np.array([0, 1, 2], dtype=dtype)
+ assert not lib.is_range_indexer(left, 2)
+
+
+def test_cache_readonly_preserve_docstrings():
+ # GH18197
+ assert Index.hasnans.__doc__ is not None
+
+
+def test_no_default_pickle():
+ # GH#40397
+ obj = tm.round_trip_pickle(lib.no_default)
+ assert obj is lib.no_default
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..e51dd06881c4fd3fa982293c68c2a9f0aa464b62
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/common.py
@@ -0,0 +1,566 @@
+"""
+Module consolidating common testing functions for checking plotting.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import numpy as np
+
+from pandas.core.dtypes.api import is_list_like
+
+import pandas as pd
+from pandas import Series
+import pandas._testing as tm
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from matplotlib.axes import Axes
+
+
+def _check_legend_labels(axes, labels=None, visible=True):
+ """
+ Check each axes has expected legend labels
+
+ Parameters
+ ----------
+ axes : matplotlib Axes object, or its list-like
+ labels : list-like
+ expected legend labels
+ visible : bool
+ expected legend visibility. labels are checked only when visible is
+ True
+ """
+ if visible and (labels is None):
+ raise ValueError("labels must be specified when visible is True")
+ axes = _flatten_visible(axes)
+ for ax in axes:
+ if visible:
+ assert ax.get_legend() is not None
+ _check_text_labels(ax.get_legend().get_texts(), labels)
+ else:
+ assert ax.get_legend() is None
+
+
+def _check_legend_marker(ax, expected_markers=None, visible=True):
+ """
+ Check ax has expected legend markers
+
+ Parameters
+ ----------
+ ax : matplotlib Axes object
+ expected_markers : list-like
+ expected legend markers
+ visible : bool
+ expected legend visibility. labels are checked only when visible is
+ True
+ """
+ if visible and (expected_markers is None):
+ raise ValueError("Markers must be specified when visible is True")
+ if visible:
+ handles, _ = ax.get_legend_handles_labels()
+ markers = [handle.get_marker() for handle in handles]
+ assert markers == expected_markers
+ else:
+ assert ax.get_legend() is None
+
+
+def _check_data(xp, rs):
+ """
+ Check each axes has identical lines
+
+ Parameters
+ ----------
+ xp : matplotlib Axes object
+ rs : matplotlib Axes object
+ """
+ import matplotlib.pyplot as plt
+
+ xp_lines = xp.get_lines()
+ rs_lines = rs.get_lines()
+
+ assert len(xp_lines) == len(rs_lines)
+ for xpl, rsl in zip(xp_lines, rs_lines):
+ xpdata = xpl.get_xydata()
+ rsdata = rsl.get_xydata()
+ tm.assert_almost_equal(xpdata, rsdata)
+
+ plt.close("all")
+
+
+def _check_visible(collections, visible=True):
+ """
+ Check each artist is visible or not
+
+ Parameters
+ ----------
+ collections : matplotlib Artist or its list-like
+ target Artist or its list or collection
+ visible : bool
+ expected visibility
+ """
+ from matplotlib.collections import Collection
+
+ if not isinstance(collections, Collection) and not is_list_like(collections):
+ collections = [collections]
+
+ for patch in collections:
+ assert patch.get_visible() == visible
+
+
+def _check_patches_all_filled(axes: Axes | Sequence[Axes], filled: bool = True) -> None:
+ """
+ Check for each artist whether it is filled or not
+
+ Parameters
+ ----------
+ axes : matplotlib Axes object, or its list-like
+ filled : bool
+ expected filling
+ """
+
+ axes = _flatten_visible(axes)
+ for ax in axes:
+ for patch in ax.patches:
+ assert patch.fill == filled
+
+
+def _get_colors_mapped(series, colors):
+ unique = series.unique()
+ # unique and colors length can be differed
+ # depending on slice value
+ mapped = dict(zip(unique, colors))
+ return [mapped[v] for v in series.values]
+
+
+def _check_colors(collections, linecolors=None, facecolors=None, mapping=None):
+ """
+ Check each artist has expected line colors and face colors
+
+ Parameters
+ ----------
+ collections : list-like
+ list or collection of target artist
+ linecolors : list-like which has the same length as collections
+ list of expected line colors
+ facecolors : list-like which has the same length as collections
+ list of expected face colors
+ mapping : Series
+ Series used for color grouping key
+ used for andrew_curves, parallel_coordinates, radviz test
+ """
+ from matplotlib import colors
+ from matplotlib.collections import (
+ Collection,
+ LineCollection,
+ PolyCollection,
+ )
+ from matplotlib.lines import Line2D
+
+ conv = colors.ColorConverter
+ if linecolors is not None:
+ if mapping is not None:
+ linecolors = _get_colors_mapped(mapping, linecolors)
+ linecolors = linecolors[: len(collections)]
+
+ assert len(collections) == len(linecolors)
+ for patch, color in zip(collections, linecolors):
+ if isinstance(patch, Line2D):
+ result = patch.get_color()
+ # Line2D may contains string color expression
+ result = conv.to_rgba(result)
+ elif isinstance(patch, (PolyCollection, LineCollection)):
+ result = tuple(patch.get_edgecolor()[0])
+ else:
+ result = patch.get_edgecolor()
+
+ expected = conv.to_rgba(color)
+ assert result == expected
+
+ if facecolors is not None:
+ if mapping is not None:
+ facecolors = _get_colors_mapped(mapping, facecolors)
+ facecolors = facecolors[: len(collections)]
+
+ assert len(collections) == len(facecolors)
+ for patch, color in zip(collections, facecolors):
+ if isinstance(patch, Collection):
+ # returned as list of np.array
+ result = patch.get_facecolor()[0]
+ else:
+ result = patch.get_facecolor()
+
+ if isinstance(result, np.ndarray):
+ result = tuple(result)
+
+ expected = conv.to_rgba(color)
+ assert result == expected
+
+
+def _check_text_labels(texts, expected):
+ """
+ Check each text has expected labels
+
+ Parameters
+ ----------
+ texts : matplotlib Text object, or its list-like
+ target text, or its list
+ expected : str or list-like which has the same length as texts
+ expected text label, or its list
+ """
+ if not is_list_like(texts):
+ assert texts.get_text() == expected
+ else:
+ labels = [t.get_text() for t in texts]
+ assert len(labels) == len(expected)
+ for label, e in zip(labels, expected):
+ assert label == e
+
+
+def _check_ticks_props(axes, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None):
+ """
+ Check each axes has expected tick properties
+
+ Parameters
+ ----------
+ axes : matplotlib Axes object, or its list-like
+ xlabelsize : number
+ expected xticks font size
+ xrot : number
+ expected xticks rotation
+ ylabelsize : number
+ expected yticks font size
+ yrot : number
+ expected yticks rotation
+ """
+ from matplotlib.ticker import NullFormatter
+
+ axes = _flatten_visible(axes)
+ for ax in axes:
+ if xlabelsize is not None or xrot is not None:
+ if isinstance(ax.xaxis.get_minor_formatter(), NullFormatter):
+ # If minor ticks has NullFormatter, rot / fontsize are not
+ # retained
+ labels = ax.get_xticklabels()
+ else:
+ labels = ax.get_xticklabels() + ax.get_xticklabels(minor=True)
+
+ for label in labels:
+ if xlabelsize is not None:
+ tm.assert_almost_equal(label.get_fontsize(), xlabelsize)
+ if xrot is not None:
+ tm.assert_almost_equal(label.get_rotation(), xrot)
+
+ if ylabelsize is not None or yrot is not None:
+ if isinstance(ax.yaxis.get_minor_formatter(), NullFormatter):
+ labels = ax.get_yticklabels()
+ else:
+ labels = ax.get_yticklabels() + ax.get_yticklabels(minor=True)
+
+ for label in labels:
+ if ylabelsize is not None:
+ tm.assert_almost_equal(label.get_fontsize(), ylabelsize)
+ if yrot is not None:
+ tm.assert_almost_equal(label.get_rotation(), yrot)
+
+
+def _check_ax_scales(axes, xaxis="linear", yaxis="linear"):
+ """
+ Check each axes has expected scales
+
+ Parameters
+ ----------
+ axes : matplotlib Axes object, or its list-like
+ xaxis : {'linear', 'log'}
+ expected xaxis scale
+ yaxis : {'linear', 'log'}
+ expected yaxis scale
+ """
+ axes = _flatten_visible(axes)
+ for ax in axes:
+ assert ax.xaxis.get_scale() == xaxis
+ assert ax.yaxis.get_scale() == yaxis
+
+
+def _check_axes_shape(axes, axes_num=None, layout=None, figsize=None):
+ """
+ Check expected number of axes is drawn in expected layout
+
+ Parameters
+ ----------
+ axes : matplotlib Axes object, or its list-like
+ axes_num : number
+ expected number of axes. Unnecessary axes should be set to
+ invisible.
+ layout : tuple
+ expected layout, (expected number of rows , columns)
+ figsize : tuple
+ expected figsize. default is matplotlib default
+ """
+ from pandas.plotting._matplotlib.tools import flatten_axes
+
+ if figsize is None:
+ figsize = (6.4, 4.8)
+ visible_axes = _flatten_visible(axes)
+
+ if axes_num is not None:
+ assert len(visible_axes) == axes_num
+ for ax in visible_axes:
+ # check something drawn on visible axes
+ assert len(ax.get_children()) > 0
+
+ if layout is not None:
+ x_set = set()
+ y_set = set()
+ for ax in flatten_axes(axes):
+ # check axes coordinates to estimate layout
+ points = ax.get_position().get_points()
+ x_set.add(points[0][0])
+ y_set.add(points[0][1])
+ result = (len(y_set), len(x_set))
+ assert result == layout
+
+ tm.assert_numpy_array_equal(
+ visible_axes[0].figure.get_size_inches(),
+ np.array(figsize, dtype=np.float64),
+ )
+
+
+def _flatten_visible(axes):
+ """
+ Flatten axes, and filter only visible
+
+ Parameters
+ ----------
+ axes : matplotlib Axes object, or its list-like
+
+ """
+ from pandas.plotting._matplotlib.tools import flatten_axes
+
+ axes = flatten_axes(axes)
+ axes = [ax for ax in axes if ax.get_visible()]
+ return axes
+
+
+def _check_has_errorbars(axes, xerr=0, yerr=0):
+ """
+ Check axes has expected number of errorbars
+
+ Parameters
+ ----------
+ axes : matplotlib Axes object, or its list-like
+ xerr : number
+ expected number of x errorbar
+ yerr : number
+ expected number of y errorbar
+ """
+ axes = _flatten_visible(axes)
+ for ax in axes:
+ containers = ax.containers
+ xerr_count = 0
+ yerr_count = 0
+ for c in containers:
+ has_xerr = getattr(c, "has_xerr", False)
+ has_yerr = getattr(c, "has_yerr", False)
+ if has_xerr:
+ xerr_count += 1
+ if has_yerr:
+ yerr_count += 1
+ assert xerr == xerr_count
+ assert yerr == yerr_count
+
+
+def _check_box_return_type(
+ returned, return_type, expected_keys=None, check_ax_title=True
+):
+ """
+ Check box returned type is correct
+
+ Parameters
+ ----------
+ returned : object to be tested, returned from boxplot
+ return_type : str
+ return_type passed to boxplot
+ expected_keys : list-like, optional
+ group labels in subplot case. If not passed,
+ the function checks assuming boxplot uses single ax
+ check_ax_title : bool
+ Whether to check the ax.title is the same as expected_key
+ Intended to be checked by calling from ``boxplot``.
+ Normal ``plot`` doesn't attach ``ax.title``, it must be disabled.
+ """
+ from matplotlib.axes import Axes
+
+ types = {"dict": dict, "axes": Axes, "both": tuple}
+ if expected_keys is None:
+ # should be fixed when the returning default is changed
+ if return_type is None:
+ return_type = "dict"
+
+ assert isinstance(returned, types[return_type])
+ if return_type == "both":
+ assert isinstance(returned.ax, Axes)
+ assert isinstance(returned.lines, dict)
+ else:
+ # should be fixed when the returning default is changed
+ if return_type is None:
+ for r in _flatten_visible(returned):
+ assert isinstance(r, Axes)
+ return
+
+ assert isinstance(returned, Series)
+
+ assert sorted(returned.keys()) == sorted(expected_keys)
+ for key, value in returned.items():
+ assert isinstance(value, types[return_type])
+ # check returned dict has correct mapping
+ if return_type == "axes":
+ if check_ax_title:
+ assert value.get_title() == key
+ elif return_type == "both":
+ if check_ax_title:
+ assert value.ax.get_title() == key
+ assert isinstance(value.ax, Axes)
+ assert isinstance(value.lines, dict)
+ elif return_type == "dict":
+ line = value["medians"][0]
+ axes = line.axes
+ if check_ax_title:
+ assert axes.get_title() == key
+ else:
+ raise AssertionError
+
+
+def _check_grid_settings(obj, kinds, kws={}):
+ # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792
+
+ import matplotlib as mpl
+
+ def is_grid_on():
+ xticks = mpl.pyplot.gca().xaxis.get_major_ticks()
+ yticks = mpl.pyplot.gca().yaxis.get_major_ticks()
+ xoff = all(not g.gridline.get_visible() for g in xticks)
+ yoff = all(not g.gridline.get_visible() for g in yticks)
+
+ return not (xoff and yoff)
+
+ spndx = 1
+ for kind in kinds:
+ mpl.pyplot.subplot(1, 4 * len(kinds), spndx)
+ spndx += 1
+ mpl.rc("axes", grid=False)
+ obj.plot(kind=kind, **kws)
+ assert not is_grid_on()
+ mpl.pyplot.clf()
+
+ mpl.pyplot.subplot(1, 4 * len(kinds), spndx)
+ spndx += 1
+ mpl.rc("axes", grid=True)
+ obj.plot(kind=kind, grid=False, **kws)
+ assert not is_grid_on()
+ mpl.pyplot.clf()
+
+ if kind not in ["pie", "hexbin", "scatter"]:
+ mpl.pyplot.subplot(1, 4 * len(kinds), spndx)
+ spndx += 1
+ mpl.rc("axes", grid=True)
+ obj.plot(kind=kind, **kws)
+ assert is_grid_on()
+ mpl.pyplot.clf()
+
+ mpl.pyplot.subplot(1, 4 * len(kinds), spndx)
+ spndx += 1
+ mpl.rc("axes", grid=False)
+ obj.plot(kind=kind, grid=True, **kws)
+ assert is_grid_on()
+ mpl.pyplot.clf()
+
+
+def _unpack_cycler(rcParams, field="color"):
+ """
+ Auxiliary function for correctly unpacking cycler after MPL >= 1.5
+ """
+ return [v[field] for v in rcParams["axes.prop_cycle"]]
+
+
+def get_x_axis(ax):
+ return ax._shared_axes["x"]
+
+
+def get_y_axis(ax):
+ return ax._shared_axes["y"]
+
+
+def _check_plot_works(f, default_axes=False, **kwargs):
+ """
+ Create plot and ensure that plot return object is valid.
+
+ Parameters
+ ----------
+ f : func
+ Plotting function.
+ default_axes : bool, optional
+ If False (default):
+ - If `ax` not in `kwargs`, then create subplot(211) and plot there
+ - Create new subplot(212) and plot there as well
+ - Mind special corner case for bootstrap_plot (see `_gen_two_subplots`)
+ If True:
+ - Simply run plotting function with kwargs provided
+ - All required axes instances will be created automatically
+ - It is recommended to use it when the plotting function
+ creates multiple axes itself. It helps avoid warnings like
+ 'UserWarning: To output multiple subplots,
+ the figure containing the passed axes is being cleared'
+ **kwargs
+ Keyword arguments passed to the plotting function.
+
+ Returns
+ -------
+ Plot object returned by the last plotting.
+ """
+ import matplotlib.pyplot as plt
+
+ if default_axes:
+ gen_plots = _gen_default_plot
+ else:
+ gen_plots = _gen_two_subplots
+
+ ret = None
+ try:
+ fig = kwargs.get("figure", plt.gcf())
+ plt.clf()
+
+ for ret in gen_plots(f, fig, **kwargs):
+ tm.assert_is_valid_plot_return_object(ret)
+
+ with tm.ensure_clean(return_filelike=True) as path:
+ plt.savefig(path)
+
+ finally:
+ plt.close(fig)
+
+ return ret
+
+
+def _gen_default_plot(f, fig, **kwargs):
+ """
+ Create plot in a default way.
+ """
+ yield f(**kwargs)
+
+
+def _gen_two_subplots(f, fig, **kwargs):
+ """
+ Create plot on two subplots forcefully created.
+ """
+ if "ax" not in kwargs:
+ fig.add_subplot(211)
+ yield f(**kwargs)
+
+ if f is pd.plotting.bootstrap_plot:
+ assert "ax" not in kwargs
+ else:
+ kwargs["ax"] = fig.add_subplot(212)
+ yield f(**kwargs)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..d688bbd47595c2ec6451bd9ddf7c916275013384
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/conftest.py
@@ -0,0 +1,56 @@
+import gc
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ to_datetime,
+)
+
+
+@pytest.fixture(autouse=True)
+def mpl_cleanup():
+ # matplotlib/testing/decorators.py#L24
+ # 1) Resets units registry
+ # 2) Resets rc_context
+ # 3) Closes all figures
+ mpl = pytest.importorskip("matplotlib")
+ mpl_units = pytest.importorskip("matplotlib.units")
+ plt = pytest.importorskip("matplotlib.pyplot")
+ orig_units_registry = mpl_units.registry.copy()
+ with mpl.rc_context():
+ mpl.use("template")
+ yield
+ mpl_units.registry.clear()
+ mpl_units.registry.update(orig_units_registry)
+ plt.close("all")
+ # https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.6.0.html#garbage-collection-is-no-longer-run-on-figure-close # noqa: E501
+ gc.collect(1)
+
+
+@pytest.fixture
+def hist_df():
+ n = 50
+ rng = np.random.default_rng(10)
+ gender = rng.choice(["Male", "Female"], size=n)
+ classroom = rng.choice(["A", "B", "C"], size=n)
+
+ hist_df = DataFrame(
+ {
+ "gender": gender,
+ "classroom": classroom,
+ "height": rng.normal(66, 4, size=n),
+ "weight": rng.normal(161, 32, size=n),
+ "category": rng.integers(4, size=n),
+ "datetime": to_datetime(
+ rng.integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=n,
+ dtype=np.int64,
+ )
+ ),
+ }
+ )
+ return hist_df
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame.py
new file mode 100644
index 0000000000000000000000000000000000000000..b97f1d64d57fdfbbd5e6dedd035b00e0f6183bfd
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame.py
@@ -0,0 +1,2509 @@
+""" Test cases for DataFrame.plot """
+from datetime import (
+ date,
+ datetime,
+)
+import gc
+import itertools
+import re
+import string
+import weakref
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.api import is_list_like
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ PeriodIndex,
+ Series,
+ bdate_range,
+ date_range,
+ plotting,
+)
+import pandas._testing as tm
+from pandas.tests.plotting.common import (
+ _check_ax_scales,
+ _check_axes_shape,
+ _check_box_return_type,
+ _check_colors,
+ _check_data,
+ _check_grid_settings,
+ _check_has_errorbars,
+ _check_legend_labels,
+ _check_plot_works,
+ _check_text_labels,
+ _check_ticks_props,
+ _check_visible,
+ get_y_axis,
+)
+
+from pandas.io.formats.printing import pprint_thing
+
+mpl = pytest.importorskip("matplotlib")
+plt = pytest.importorskip("matplotlib.pyplot")
+
+
+class TestDataFramePlots:
+ @pytest.mark.slow
+ def test_plot(self):
+ df = tm.makeTimeDataFrame()
+ _check_plot_works(df.plot, grid=False)
+
+ @pytest.mark.slow
+ def test_plot_subplots(self):
+ df = tm.makeTimeDataFrame()
+ # _check_plot_works adds an ax so use default_axes=True to avoid warning
+ axes = _check_plot_works(df.plot, default_axes=True, subplots=True)
+ _check_axes_shape(axes, axes_num=4, layout=(4, 1))
+
+ @pytest.mark.slow
+ def test_plot_subplots_negative_layout(self):
+ df = tm.makeTimeDataFrame()
+ axes = _check_plot_works(
+ df.plot,
+ default_axes=True,
+ subplots=True,
+ layout=(-1, 2),
+ )
+ _check_axes_shape(axes, axes_num=4, layout=(2, 2))
+
+ @pytest.mark.slow
+ def test_plot_subplots_use_index(self):
+ df = tm.makeTimeDataFrame()
+ axes = _check_plot_works(
+ df.plot,
+ default_axes=True,
+ subplots=True,
+ use_index=False,
+ )
+ _check_ticks_props(axes, xrot=0)
+ _check_axes_shape(axes, axes_num=4, layout=(4, 1))
+
+ @pytest.mark.xfail(reason="Api changed in 3.6.0")
+ @pytest.mark.slow
+ def test_plot_invalid_arg(self):
+ df = DataFrame({"x": [1, 2], "y": [3, 4]})
+ msg = "'Line2D' object has no property 'blarg'"
+ with pytest.raises(AttributeError, match=msg):
+ df.plot.line(blarg=True)
+
+ @pytest.mark.slow
+ def test_plot_tick_props(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+
+ ax = _check_plot_works(df.plot, use_index=True)
+ _check_ticks_props(ax, xrot=0)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"yticks": [1, 5, 10]},
+ {"xticks": [1, 5, 10]},
+ {"ylim": (-100, 100), "xlim": (-100, 100)},
+ {"default_axes": True, "subplots": True, "title": "blah"},
+ ],
+ )
+ def test_plot_other_args(self, kwargs):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+ _check_plot_works(df.plot, **kwargs)
+
+ @pytest.mark.slow
+ def test_plot_visible_ax(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+ # We have to redo it here because _check_plot_works does two plots,
+ # once without an ax kwarg and once with an ax kwarg and the new sharex
+ # behaviour does not remove the visibility of the latter axis (as ax is
+ # present). see: https://github.com/pandas-dev/pandas/issues/9737
+
+ axes = df.plot(subplots=True, title="blah")
+ _check_axes_shape(axes, axes_num=3, layout=(3, 1))
+ for ax in axes[:2]:
+ _check_visible(ax.xaxis) # xaxis must be visible for grid
+ _check_visible(ax.get_xticklabels(), visible=False)
+ _check_visible(ax.get_xticklabels(minor=True), visible=False)
+ _check_visible([ax.xaxis.get_label()], visible=False)
+ for ax in [axes[2]]:
+ _check_visible(ax.xaxis)
+ _check_visible(ax.get_xticklabels())
+ _check_visible([ax.xaxis.get_label()])
+ _check_ticks_props(ax, xrot=0)
+
+ @pytest.mark.slow
+ def test_plot_title(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+ _check_plot_works(df.plot, title="blah")
+
+ @pytest.mark.slow
+ def test_plot_multiindex(self):
+ tuples = zip(string.ascii_letters[:10], range(10))
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=MultiIndex.from_tuples(tuples),
+ )
+ ax = _check_plot_works(df.plot, use_index=True)
+ _check_ticks_props(ax, xrot=0)
+
+ @pytest.mark.slow
+ def test_plot_multiindex_unicode(self):
+ # unicode
+ index = MultiIndex.from_tuples(
+ [
+ ("\u03b1", 0),
+ ("\u03b1", 1),
+ ("\u03b2", 2),
+ ("\u03b2", 3),
+ ("\u03b3", 4),
+ ("\u03b3", 5),
+ ("\u03b4", 6),
+ ("\u03b4", 7),
+ ],
+ names=["i0", "i1"],
+ )
+ columns = MultiIndex.from_tuples(
+ [("bar", "\u0394"), ("bar", "\u0395")], names=["c0", "c1"]
+ )
+ df = DataFrame(
+ np.random.default_rng(2).integers(0, 10, (8, 2)),
+ columns=columns,
+ index=index,
+ )
+ _check_plot_works(df.plot, title="\u03A3")
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("layout", [None, (-1, 1)])
+ def test_plot_single_column_bar(self, layout):
+ # GH 6951
+ # Test with single column
+ df = DataFrame({"x": np.random.default_rng(2).random(10)})
+ axes = _check_plot_works(df.plot.bar, subplots=True, layout=layout)
+ _check_axes_shape(axes, axes_num=1, layout=(1, 1))
+
+ @pytest.mark.slow
+ def test_plot_passed_ax(self):
+ # When ax is supplied and required number of axes is 1,
+ # passed ax should be used:
+ df = DataFrame({"x": np.random.default_rng(2).random(10)})
+ _, ax = mpl.pyplot.subplots()
+ axes = df.plot.bar(subplots=True, ax=ax)
+ assert len(axes) == 1
+ result = ax.axes
+ assert result is axes[0]
+
+ @pytest.mark.parametrize(
+ "cols, x, y",
+ [
+ [list("ABCDE"), "A", "B"],
+ [["A", "B"], "A", "B"],
+ [["C", "A"], "C", "A"],
+ [["A", "C"], "A", "C"],
+ [["B", "C"], "B", "C"],
+ [["A", "D"], "A", "D"],
+ [["A", "E"], "A", "E"],
+ ],
+ )
+ def test_nullable_int_plot(self, cols, x, y):
+ # GH 32073
+ dates = ["2008", "2009", None, "2011", "2012"]
+ df = DataFrame(
+ {
+ "A": [1, 2, 3, 4, 5],
+ "B": [1, 2, 3, 4, 5],
+ "C": np.array([7, 5, np.nan, 3, 2], dtype=object),
+ "D": pd.to_datetime(dates, format="%Y").view("i8"),
+ "E": pd.to_datetime(dates, format="%Y", utc=True).view("i8"),
+ }
+ )
+
+ _check_plot_works(df[cols].plot, x=x, y=y)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("plot", ["line", "bar", "hist", "pie"])
+ def test_integer_array_plot_series(self, plot):
+ # GH 25587
+ arr = pd.array([1, 2, 3, 4], dtype="UInt32")
+
+ s = Series(arr)
+ _check_plot_works(getattr(s.plot, plot))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "plot, kwargs",
+ [
+ ["line", {}],
+ ["bar", {}],
+ ["hist", {}],
+ ["pie", {"y": "y"}],
+ ["scatter", {"x": "x", "y": "y"}],
+ ["hexbin", {"x": "x", "y": "y"}],
+ ],
+ )
+ def test_integer_array_plot_df(self, plot, kwargs):
+ # GH 25587
+ arr = pd.array([1, 2, 3, 4], dtype="UInt32")
+ df = DataFrame({"x": arr, "y": arr})
+ _check_plot_works(getattr(df.plot, plot), **kwargs)
+
+ def test_nonnumeric_exclude(self):
+ df = DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]})
+ ax = df.plot()
+ assert len(ax.get_lines()) == 1 # B was plotted
+
+ def test_implicit_label(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 3)), columns=["a", "b", "c"]
+ )
+ ax = df.plot(x="a", y="b")
+ _check_text_labels(ax.xaxis.get_label(), "a")
+
+ def test_donot_overwrite_index_name(self):
+ # GH 8494
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((2, 2)), columns=["a", "b"]
+ )
+ df.index.name = "NAME"
+ df.plot(y="b", label="LABEL")
+ assert df.index.name == "NAME"
+
+ def test_plot_xy(self):
+ # columns.inferred_type == 'string'
+ df = tm.makeTimeDataFrame(5)
+ _check_data(df.plot(x=0, y=1), df.set_index("A")["B"].plot())
+ _check_data(df.plot(x=0), df.set_index("A").plot())
+ _check_data(df.plot(y=0), df.B.plot())
+ _check_data(df.plot(x="A", y="B"), df.set_index("A").B.plot())
+ _check_data(df.plot(x="A"), df.set_index("A").plot())
+ _check_data(df.plot(y="B"), df.B.plot())
+
+ def test_plot_xy_int_cols(self):
+ df = tm.makeTimeDataFrame(5)
+ # columns.inferred_type == 'integer'
+ df.columns = np.arange(1, len(df.columns) + 1)
+ _check_data(df.plot(x=1, y=2), df.set_index(1)[2].plot())
+ _check_data(df.plot(x=1), df.set_index(1).plot())
+ _check_data(df.plot(y=1), df[1].plot())
+
+ def test_plot_xy_figsize_and_title(self):
+ df = tm.makeTimeDataFrame(5)
+ # figsize and title
+ ax = df.plot(x=1, y=2, title="Test", figsize=(16, 8))
+ _check_text_labels(ax.title, "Test")
+ _check_axes_shape(ax, axes_num=1, layout=(1, 1), figsize=(16.0, 8.0))
+
+ # columns.inferred_type == 'mixed'
+ # TODO add MultiIndex test
+
+ @pytest.mark.parametrize(
+ "input_log, expected_log", [(True, "log"), ("sym", "symlog")]
+ )
+ def test_logscales(self, input_log, expected_log):
+ df = DataFrame({"a": np.arange(100)}, index=np.arange(100))
+
+ ax = df.plot(logy=input_log)
+ _check_ax_scales(ax, yaxis=expected_log)
+ assert ax.get_yscale() == expected_log
+
+ ax = df.plot(logx=input_log)
+ _check_ax_scales(ax, xaxis=expected_log)
+ assert ax.get_xscale() == expected_log
+
+ ax = df.plot(loglog=input_log)
+ _check_ax_scales(ax, xaxis=expected_log, yaxis=expected_log)
+ assert ax.get_xscale() == expected_log
+ assert ax.get_yscale() == expected_log
+
+ @pytest.mark.parametrize("input_param", ["logx", "logy", "loglog"])
+ def test_invalid_logscale(self, input_param):
+ # GH: 24867
+ df = DataFrame({"a": np.arange(100)}, index=np.arange(100))
+
+ msg = "Boolean, None and 'sym' are valid options, 'sm' is given."
+ with pytest.raises(ValueError, match=msg):
+ df.plot(**{input_param: "sm"})
+
+ def test_xcompat(self):
+ df = tm.makeTimeDataFrame()
+ ax = df.plot(x_compat=True)
+ lines = ax.get_lines()
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
+ _check_ticks_props(ax, xrot=30)
+
+ def test_xcompat_plot_params(self):
+ df = tm.makeTimeDataFrame()
+ plotting.plot_params["xaxis.compat"] = True
+ ax = df.plot()
+ lines = ax.get_lines()
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
+ _check_ticks_props(ax, xrot=30)
+
+ def test_xcompat_plot_params_x_compat(self):
+ df = tm.makeTimeDataFrame()
+ plotting.plot_params["x_compat"] = False
+
+ ax = df.plot()
+ lines = ax.get_lines()
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex)
+
+ def test_xcompat_plot_params_context_manager(self):
+ df = tm.makeTimeDataFrame()
+ # useful if you're plotting a bunch together
+ with plotting.plot_params.use("x_compat", True):
+ ax = df.plot()
+ lines = ax.get_lines()
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
+ _check_ticks_props(ax, xrot=30)
+
+ def test_xcompat_plot_period(self):
+ df = tm.makeTimeDataFrame()
+ ax = df.plot()
+ lines = ax.get_lines()
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
+ msg = r"PeriodDtype\[B\] is deprecated "
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex)
+ _check_ticks_props(ax, xrot=0)
+
+ def test_period_compat(self):
+ # GH 9012
+ # period-array conversions
+ df = DataFrame(
+ np.random.default_rng(2).random((21, 2)),
+ index=bdate_range(datetime(2000, 1, 1), datetime(2000, 1, 31)),
+ columns=["a", "b"],
+ )
+
+ df.plot()
+ mpl.pyplot.axhline(y=0)
+
+ @pytest.mark.parametrize("index_dtype", [np.int64, np.float64])
+ def test_unsorted_index(self, index_dtype):
+ df = DataFrame(
+ {"y": np.arange(100)},
+ index=pd.Index(np.arange(99, -1, -1), dtype=index_dtype),
+ dtype=np.int64,
+ )
+ ax = df.plot()
+ lines = ax.get_lines()[0]
+ rs = lines.get_xydata()
+ rs = Series(rs[:, 1], rs[:, 0], dtype=np.int64, name="y")
+ tm.assert_series_equal(rs, df.y, check_index_type=False)
+
+ @pytest.mark.parametrize(
+ "df",
+ [
+ DataFrame({"y": [0.0, 1.0, 2.0, 3.0]}, index=[1.0, 0.0, 3.0, 2.0]),
+ DataFrame(
+ {"y": [0.0, 1.0, np.nan, 3.0, 4.0, 5.0, 6.0]},
+ index=[1.0, 0.0, 3.0, 2.0, np.nan, 3.0, 2.0],
+ ),
+ ],
+ )
+ def test_unsorted_index_lims(self, df):
+ ax = df.plot()
+ xmin, xmax = ax.get_xlim()
+ lines = ax.get_lines()
+ assert xmin <= np.nanmin(lines[0].get_data()[0])
+ assert xmax >= np.nanmax(lines[0].get_data()[0])
+
+ def test_unsorted_index_lims_x_y(self):
+ df = DataFrame({"y": [0.0, 1.0, 2.0, 3.0], "z": [91.0, 90.0, 93.0, 92.0]})
+ ax = df.plot(x="z", y="y")
+ xmin, xmax = ax.get_xlim()
+ lines = ax.get_lines()
+ assert xmin <= np.nanmin(lines[0].get_data()[0])
+ assert xmax >= np.nanmax(lines[0].get_data()[0])
+
+ def test_negative_log(self):
+ df = -DataFrame(
+ np.random.default_rng(2).random((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["x", "y", "z", "four"],
+ )
+ msg = "Log-y scales are not supported in area plot"
+ with pytest.raises(ValueError, match=msg):
+ df.plot.area(logy=True)
+ with pytest.raises(ValueError, match=msg):
+ df.plot.area(loglog=True)
+
+ def _compare_stacked_y_cood(self, normal_lines, stacked_lines):
+ base = np.zeros(len(normal_lines[0].get_data()[1]))
+ for nl, sl in zip(normal_lines, stacked_lines):
+ base += nl.get_data()[1] # get y coordinates
+ sy = sl.get_data()[1]
+ tm.assert_numpy_array_equal(base, sy)
+
+ @pytest.mark.parametrize("kind", ["line", "area"])
+ @pytest.mark.parametrize("mult", [1, -1])
+ def test_line_area_stacked(self, kind, mult):
+ df = mult * DataFrame(
+ np.random.default_rng(2).random((6, 4)), columns=["w", "x", "y", "z"]
+ )
+
+ ax1 = _check_plot_works(df.plot, kind=kind, stacked=False)
+ ax2 = _check_plot_works(df.plot, kind=kind, stacked=True)
+ self._compare_stacked_y_cood(ax1.lines, ax2.lines)
+
+ @pytest.mark.parametrize("kind", ["line", "area"])
+ def test_line_area_stacked_sep_df(self, kind):
+ # each column has either positive or negative value
+ sep_df = DataFrame(
+ {
+ "w": np.random.default_rng(2).random(6),
+ "x": np.random.default_rng(2).random(6),
+ "y": -np.random.default_rng(2).random(6),
+ "z": -np.random.default_rng(2).random(6),
+ }
+ )
+ ax1 = _check_plot_works(sep_df.plot, kind=kind, stacked=False)
+ ax2 = _check_plot_works(sep_df.plot, kind=kind, stacked=True)
+ self._compare_stacked_y_cood(ax1.lines[:2], ax2.lines[:2])
+ self._compare_stacked_y_cood(ax1.lines[2:], ax2.lines[2:])
+
+ def test_line_area_stacked_mixed(self):
+ mixed_df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["w", "x", "y", "z"],
+ )
+ _check_plot_works(mixed_df.plot, stacked=False)
+
+ msg = (
+ "When stacked is True, each column must be either all positive or "
+ "all negative. Column 'w' contains both positive and negative "
+ "values"
+ )
+ with pytest.raises(ValueError, match=msg):
+ mixed_df.plot(stacked=True)
+
+ @pytest.mark.parametrize("kind", ["line", "area"])
+ def test_line_area_stacked_positive_idx(self, kind):
+ df = DataFrame(
+ np.random.default_rng(2).random((6, 4)), columns=["w", "x", "y", "z"]
+ )
+ # Use an index with strictly positive values, preventing
+ # matplotlib from warning about ignoring xlim
+ df2 = df.set_index(df.index + 1)
+ _check_plot_works(df2.plot, kind=kind, logx=True, stacked=True)
+
+ @pytest.mark.parametrize(
+ "idx", [range(4), date_range("2023-01-1", freq="D", periods=4)]
+ )
+ def test_line_area_nan_df(self, idx):
+ values1 = [1, 2, np.nan, 3]
+ values2 = [3, np.nan, 2, 1]
+ df = DataFrame({"a": values1, "b": values2}, index=idx)
+
+ ax = _check_plot_works(df.plot)
+ masked1 = ax.lines[0].get_ydata()
+ masked2 = ax.lines[1].get_ydata()
+ # remove nan for comparison purpose
+
+ exp = np.array([1, 2, 3], dtype=np.float64)
+ tm.assert_numpy_array_equal(np.delete(masked1.data, 2), exp)
+
+ exp = np.array([3, 2, 1], dtype=np.float64)
+ tm.assert_numpy_array_equal(np.delete(masked2.data, 1), exp)
+ tm.assert_numpy_array_equal(masked1.mask, np.array([False, False, True, False]))
+ tm.assert_numpy_array_equal(masked2.mask, np.array([False, True, False, False]))
+
+ @pytest.mark.parametrize(
+ "idx", [range(4), date_range("2023-01-1", freq="D", periods=4)]
+ )
+ def test_line_area_nan_df_stacked(self, idx):
+ values1 = [1, 2, np.nan, 3]
+ values2 = [3, np.nan, 2, 1]
+ df = DataFrame({"a": values1, "b": values2}, index=idx)
+
+ expected1 = np.array([1, 2, 0, 3], dtype=np.float64)
+ expected2 = np.array([3, 0, 2, 1], dtype=np.float64)
+
+ ax = _check_plot_works(df.plot, stacked=True)
+ tm.assert_numpy_array_equal(ax.lines[0].get_ydata(), expected1)
+ tm.assert_numpy_array_equal(ax.lines[1].get_ydata(), expected1 + expected2)
+
+ @pytest.mark.parametrize(
+ "idx", [range(4), date_range("2023-01-1", freq="D", periods=4)]
+ )
+ @pytest.mark.parametrize("kwargs", [{}, {"stacked": False}])
+ def test_line_area_nan_df_stacked_area(self, idx, kwargs):
+ values1 = [1, 2, np.nan, 3]
+ values2 = [3, np.nan, 2, 1]
+ df = DataFrame({"a": values1, "b": values2}, index=idx)
+
+ expected1 = np.array([1, 2, 0, 3], dtype=np.float64)
+ expected2 = np.array([3, 0, 2, 1], dtype=np.float64)
+
+ ax = _check_plot_works(df.plot.area, **kwargs)
+ tm.assert_numpy_array_equal(ax.lines[0].get_ydata(), expected1)
+ if kwargs:
+ tm.assert_numpy_array_equal(ax.lines[1].get_ydata(), expected2)
+ else:
+ tm.assert_numpy_array_equal(ax.lines[1].get_ydata(), expected1 + expected2)
+
+ ax = _check_plot_works(df.plot.area, stacked=False)
+ tm.assert_numpy_array_equal(ax.lines[0].get_ydata(), expected1)
+ tm.assert_numpy_array_equal(ax.lines[1].get_ydata(), expected2)
+
+ @pytest.mark.parametrize("kwargs", [{}, {"secondary_y": True}])
+ def test_line_lim(self, kwargs):
+ df = DataFrame(np.random.default_rng(2).random((6, 3)), columns=["x", "y", "z"])
+ ax = df.plot(**kwargs)
+ xmin, xmax = ax.get_xlim()
+ lines = ax.get_lines()
+ assert xmin <= lines[0].get_data()[0][0]
+ assert xmax >= lines[0].get_data()[0][-1]
+
+ def test_line_lim_subplots(self):
+ df = DataFrame(np.random.default_rng(2).random((6, 3)), columns=["x", "y", "z"])
+ axes = df.plot(secondary_y=True, subplots=True)
+ _check_axes_shape(axes, axes_num=3, layout=(3, 1))
+ for ax in axes:
+ assert hasattr(ax, "left_ax")
+ assert not hasattr(ax, "right_ax")
+ xmin, xmax = ax.get_xlim()
+ lines = ax.get_lines()
+ assert xmin <= lines[0].get_data()[0][0]
+ assert xmax >= lines[0].get_data()[0][-1]
+
+ @pytest.mark.xfail(
+ strict=False,
+ reason="2020-12-01 this has been failing periodically on the "
+ "ymin==0 assertion for a week or so.",
+ )
+ @pytest.mark.parametrize("stacked", [True, False])
+ def test_area_lim(self, stacked):
+ df = DataFrame(
+ np.random.default_rng(2).random((6, 4)), columns=["x", "y", "z", "four"]
+ )
+
+ neg_df = -df
+
+ ax = _check_plot_works(df.plot.area, stacked=stacked)
+ xmin, xmax = ax.get_xlim()
+ ymin, ymax = ax.get_ylim()
+ lines = ax.get_lines()
+ assert xmin <= lines[0].get_data()[0][0]
+ assert xmax >= lines[0].get_data()[0][-1]
+ assert ymin == 0
+
+ ax = _check_plot_works(neg_df.plot.area, stacked=stacked)
+ ymin, ymax = ax.get_ylim()
+ assert ymax == 0
+
+ def test_area_sharey_dont_overwrite(self):
+ # GH37942
+ df = DataFrame(np.random.default_rng(2).random((4, 2)), columns=["x", "y"])
+ fig, (ax1, ax2) = mpl.pyplot.subplots(1, 2, sharey=True)
+
+ df.plot(ax=ax1, kind="area")
+ df.plot(ax=ax2, kind="area")
+
+ assert get_y_axis(ax1).joined(ax1, ax2)
+ assert get_y_axis(ax2).joined(ax1, ax2)
+
+ @pytest.mark.parametrize("stacked", [True, False])
+ def test_bar_linewidth(self, stacked):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+
+ ax = df.plot.bar(stacked=stacked, linewidth=2)
+ for r in ax.patches:
+ assert r.get_linewidth() == 2
+
+ def test_bar_linewidth_subplots(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # subplots
+ axes = df.plot.bar(linewidth=2, subplots=True)
+ _check_axes_shape(axes, axes_num=5, layout=(5, 1))
+ for ax in axes:
+ for r in ax.patches:
+ assert r.get_linewidth() == 2
+
+ @pytest.mark.parametrize(
+ "meth, dim", [("bar", "get_width"), ("barh", "get_height")]
+ )
+ @pytest.mark.parametrize("stacked", [True, False])
+ def test_bar_barwidth(self, meth, dim, stacked):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+
+ width = 0.9
+
+ ax = getattr(df.plot, meth)(stacked=stacked, width=width)
+ for r in ax.patches:
+ if not stacked:
+ assert getattr(r, dim)() == width / len(df.columns)
+ else:
+ assert getattr(r, dim)() == width
+
+ @pytest.mark.parametrize(
+ "meth, dim", [("bar", "get_width"), ("barh", "get_height")]
+ )
+ def test_barh_barwidth_subplots(self, meth, dim):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+
+ width = 0.9
+
+ axes = getattr(df.plot, meth)(width=width, subplots=True)
+ for ax in axes:
+ for r in ax.patches:
+ assert getattr(r, dim)() == width
+
+ def test_bar_bottom_left_bottom(self):
+ df = DataFrame(np.random.default_rng(2).random((5, 5)))
+ ax = df.plot.bar(stacked=False, bottom=1)
+ result = [p.get_y() for p in ax.patches]
+ assert result == [1] * 25
+
+ ax = df.plot.bar(stacked=True, bottom=[-1, -2, -3, -4, -5])
+ result = [p.get_y() for p in ax.patches[:5]]
+ assert result == [-1, -2, -3, -4, -5]
+
+ def test_bar_bottom_left_left(self):
+ df = DataFrame(np.random.default_rng(2).random((5, 5)))
+ ax = df.plot.barh(stacked=False, left=np.array([1, 1, 1, 1, 1]))
+ result = [p.get_x() for p in ax.patches]
+ assert result == [1] * 25
+
+ ax = df.plot.barh(stacked=True, left=[1, 2, 3, 4, 5])
+ result = [p.get_x() for p in ax.patches[:5]]
+ assert result == [1, 2, 3, 4, 5]
+
+ def test_bar_bottom_left_subplots(self):
+ df = DataFrame(np.random.default_rng(2).random((5, 5)))
+ axes = df.plot.bar(subplots=True, bottom=-1)
+ for ax in axes:
+ result = [p.get_y() for p in ax.patches]
+ assert result == [-1] * 5
+
+ axes = df.plot.barh(subplots=True, left=np.array([1, 1, 1, 1, 1]))
+ for ax in axes:
+ result = [p.get_x() for p in ax.patches]
+ assert result == [1] * 5
+
+ def test_bar_nan(self):
+ df = DataFrame({"A": [10, np.nan, 20], "B": [5, 10, 20], "C": [1, 2, 3]})
+ ax = df.plot.bar()
+ expected = [10, 0, 20, 5, 10, 20, 1, 2, 3]
+ result = [p.get_height() for p in ax.patches]
+ assert result == expected
+
+ def test_bar_nan_stacked(self):
+ df = DataFrame({"A": [10, np.nan, 20], "B": [5, 10, 20], "C": [1, 2, 3]})
+ ax = df.plot.bar(stacked=True)
+ expected = [10, 0, 20, 5, 10, 20, 1, 2, 3]
+ result = [p.get_height() for p in ax.patches]
+ assert result == expected
+
+ result = [p.get_y() for p in ax.patches]
+ expected = [0.0, 0.0, 0.0, 10.0, 0.0, 20.0, 15.0, 10.0, 40.0]
+ assert result == expected
+
+ @pytest.mark.parametrize("idx", [pd.Index, pd.CategoricalIndex])
+ def test_bar_categorical(self, idx):
+ # GH 13019
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 5)),
+ index=idx(list("ABCDEF")),
+ columns=idx(list("abcde")),
+ )
+
+ ax = df.plot.bar()
+ ticks = ax.xaxis.get_ticklocs()
+ tm.assert_numpy_array_equal(ticks, np.array([0, 1, 2, 3, 4, 5]))
+ assert ax.get_xlim() == (-0.5, 5.5)
+ # check left-edge of bars
+ assert ax.patches[0].get_x() == -0.25
+ assert ax.patches[-1].get_x() == 5.15
+
+ ax = df.plot.bar(stacked=True)
+ tm.assert_numpy_array_equal(ticks, np.array([0, 1, 2, 3, 4, 5]))
+ assert ax.get_xlim() == (-0.5, 5.5)
+ assert ax.patches[0].get_x() == -0.25
+ assert ax.patches[-1].get_x() == 4.75
+
+ @pytest.mark.parametrize("x, y", [("x", "y"), (1, 2)])
+ def test_plot_scatter(self, x, y):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["x", "y", "z", "four"],
+ )
+
+ _check_plot_works(df.plot.scatter, x=x, y=y)
+
+ def test_plot_scatter_error(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["x", "y", "z", "four"],
+ )
+ msg = re.escape("scatter() missing 1 required positional argument: 'y'")
+ with pytest.raises(TypeError, match=msg):
+ df.plot.scatter(x="x")
+ msg = re.escape("scatter() missing 1 required positional argument: 'x'")
+ with pytest.raises(TypeError, match=msg):
+ df.plot.scatter(y="y")
+
+ def test_plot_scatter_shape(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["x", "y", "z", "four"],
+ )
+ # GH 6951
+ axes = df.plot(x="x", y="y", kind="scatter", subplots=True)
+ _check_axes_shape(axes, axes_num=1, layout=(1, 1))
+
+ def test_raise_error_on_datetime_time_data(self):
+ # GH 8113, datetime.time type is not supported by matplotlib in scatter
+ df = DataFrame(np.random.default_rng(2).standard_normal(10), columns=["a"])
+ df["dtime"] = date_range(start="2014-01-01", freq="h", periods=10).time
+ msg = "must be a string or a (real )?number, not 'datetime.time'"
+
+ with pytest.raises(TypeError, match=msg):
+ df.plot(kind="scatter", x="dtime", y="a")
+
+ @pytest.mark.parametrize("x, y", [("dates", "vals"), (0, 1)])
+ def test_scatterplot_datetime_data(self, x, y):
+ # GH 30391
+ dates = date_range(start=date(2019, 1, 1), periods=12, freq="W")
+ vals = np.random.default_rng(2).normal(0, 1, len(dates))
+ df = DataFrame({"dates": dates, "vals": vals})
+
+ _check_plot_works(df.plot.scatter, x=x, y=y)
+
+ @pytest.mark.parametrize("x, y", [("a", "b"), (0, 1)])
+ @pytest.mark.parametrize("b_col", [[2, 3, 4], ["a", "b", "c"]])
+ def test_scatterplot_object_data(self, b_col, x, y):
+ # GH 18755
+ df = DataFrame({"a": ["A", "B", "C"], "b": b_col})
+
+ _check_plot_works(df.plot.scatter, x=x, y=y)
+
+ @pytest.mark.parametrize("ordered", [True, False])
+ @pytest.mark.parametrize(
+ "categories",
+ (["setosa", "versicolor", "virginica"], ["versicolor", "virginica", "setosa"]),
+ )
+ def test_scatterplot_color_by_categorical(self, ordered, categories):
+ df = DataFrame(
+ [[5.1, 3.5], [4.9, 3.0], [7.0, 3.2], [6.4, 3.2], [5.9, 3.0]],
+ columns=["length", "width"],
+ )
+ df["species"] = pd.Categorical(
+ ["setosa", "setosa", "virginica", "virginica", "versicolor"],
+ ordered=ordered,
+ categories=categories,
+ )
+ ax = df.plot.scatter(x=0, y=1, c="species")
+ (colorbar_collection,) = ax.collections
+ colorbar = colorbar_collection.colorbar
+
+ expected_ticks = np.array([0.5, 1.5, 2.5])
+ result_ticks = colorbar.get_ticks()
+ tm.assert_numpy_array_equal(result_ticks, expected_ticks)
+
+ expected_boundaries = np.array([0.0, 1.0, 2.0, 3.0])
+ result_boundaries = colorbar._boundaries
+ tm.assert_numpy_array_equal(result_boundaries, expected_boundaries)
+
+ expected_yticklabels = categories
+ result_yticklabels = [i.get_text() for i in colorbar.ax.get_ymajorticklabels()]
+ assert all(i == j for i, j in zip(result_yticklabels, expected_yticklabels))
+
+ @pytest.mark.parametrize("x, y", [("x", "y"), ("y", "x"), ("y", "y")])
+ def test_plot_scatter_with_categorical_data(self, x, y):
+ # after fixing GH 18755, should be able to plot categorical data
+ df = DataFrame({"x": [1, 2, 3, 4], "y": pd.Categorical(["a", "b", "a", "c"])})
+
+ _check_plot_works(df.plot.scatter, x=x, y=y)
+
+ @pytest.mark.parametrize("x, y, c", [("x", "y", "z"), (0, 1, 2)])
+ def test_plot_scatter_with_c(self, x, y, c):
+ df = DataFrame(
+ np.random.default_rng(2).integers(low=0, high=100, size=(6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["x", "y", "z", "four"],
+ )
+
+ ax = df.plot.scatter(x=x, y=y, c=c)
+ # default to Greys
+ assert ax.collections[0].cmap.name == "Greys"
+
+ assert ax.collections[0].colorbar.ax.get_ylabel() == "z"
+
+ def test_plot_scatter_with_c_props(self):
+ df = DataFrame(
+ np.random.default_rng(2).integers(low=0, high=100, size=(6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["x", "y", "z", "four"],
+ )
+ cm = "cubehelix"
+ ax = df.plot.scatter(x="x", y="y", c="z", colormap=cm)
+ assert ax.collections[0].cmap.name == cm
+
+ # verify turning off colorbar works
+ ax = df.plot.scatter(x="x", y="y", c="z", colorbar=False)
+ assert ax.collections[0].colorbar is None
+
+ # verify that we can still plot a solid color
+ ax = df.plot.scatter(x=0, y=1, c="red")
+ assert ax.collections[0].colorbar is None
+ _check_colors(ax.collections, facecolors=["r"])
+
+ def test_plot_scatter_with_c_array(self):
+ # Ensure that we can pass an np.array straight through to matplotlib,
+ # this functionality was accidentally removed previously.
+ # See https://github.com/pandas-dev/pandas/issues/8852 for bug report
+ #
+ # Exercise colormap path and non-colormap path as they are independent
+ #
+ df = DataFrame({"A": [1, 2], "B": [3, 4]})
+ red_rgba = [1.0, 0.0, 0.0, 1.0]
+ green_rgba = [0.0, 1.0, 0.0, 1.0]
+ rgba_array = np.array([red_rgba, green_rgba])
+ ax = df.plot.scatter(x="A", y="B", c=rgba_array)
+ # expect the face colors of the points in the non-colormap path to be
+ # identical to the values we supplied, normally we'd be on shaky ground
+ # comparing floats for equality but here we expect them to be
+ # identical.
+ tm.assert_numpy_array_equal(ax.collections[0].get_facecolor(), rgba_array)
+ # we don't test the colors of the faces in this next plot because they
+ # are dependent on the spring colormap, which may change its colors
+ # later.
+ float_array = np.array([0.0, 1.0])
+ df.plot.scatter(x="A", y="B", c=float_array, cmap="spring")
+
+ def test_plot_scatter_with_s(self):
+ # this refers to GH 32904
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)) * 100, columns=["a", "b", "c"]
+ )
+
+ ax = df.plot.scatter(x="a", y="b", s="c")
+ tm.assert_numpy_array_equal(df["c"].values, right=ax.collections[0].get_sizes())
+
+ def test_plot_scatter_with_norm(self):
+ # added while fixing GH 45809
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)) * 100, columns=["a", "b", "c"]
+ )
+ norm = mpl.colors.LogNorm()
+ ax = df.plot.scatter(x="a", y="b", c="c", norm=norm)
+ assert ax.collections[0].norm is norm
+
+ def test_plot_scatter_without_norm(self):
+ # added while fixing GH 45809
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)) * 100, columns=["a", "b", "c"]
+ )
+ ax = df.plot.scatter(x="a", y="b", c="c")
+ plot_norm = ax.collections[0].norm
+ color_min_max = (df.c.min(), df.c.max())
+ default_norm = mpl.colors.Normalize(*color_min_max)
+ for value in df.c:
+ assert plot_norm(value) == default_norm(value)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {},
+ {"legend": False},
+ {"default_axes": True, "subplots": True},
+ {"stacked": True},
+ ],
+ )
+ def test_plot_bar(self, kwargs):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["one", "two", "three", "four"],
+ )
+
+ _check_plot_works(df.plot.bar, **kwargs)
+
+ @pytest.mark.slow
+ def test_plot_bar_int_col(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 15)),
+ index=list(string.ascii_letters[:10]),
+ columns=range(15),
+ )
+ _check_plot_works(df.plot.bar)
+
+ @pytest.mark.slow
+ def test_plot_bar_ticks(self):
+ df = DataFrame({"a": [0, 1], "b": [1, 0]})
+ ax = _check_plot_works(df.plot.bar)
+ _check_ticks_props(ax, xrot=90)
+
+ ax = df.plot.bar(rot=35, fontsize=10)
+ _check_ticks_props(ax, xrot=35, xlabelsize=10, ylabelsize=10)
+
+ @pytest.mark.slow
+ def test_plot_barh_ticks(self):
+ df = DataFrame({"a": [0, 1], "b": [1, 0]})
+ ax = _check_plot_works(df.plot.barh)
+ _check_ticks_props(ax, yrot=0)
+
+ ax = df.plot.barh(rot=55, fontsize=11)
+ _check_ticks_props(ax, yrot=55, ylabelsize=11, xlabelsize=11)
+
+ def test_boxplot(self, hist_df):
+ df = hist_df
+ numeric_cols = df._get_numeric_data().columns
+ labels = [pprint_thing(c) for c in numeric_cols]
+
+ ax = _check_plot_works(df.plot.box)
+ _check_text_labels(ax.get_xticklabels(), labels)
+ tm.assert_numpy_array_equal(
+ ax.xaxis.get_ticklocs(), np.arange(1, len(numeric_cols) + 1)
+ )
+ assert len(ax.lines) == 7 * len(numeric_cols)
+
+ def test_boxplot_series(self, hist_df):
+ df = hist_df
+ series = df["height"]
+ axes = series.plot.box(rot=40)
+ _check_ticks_props(axes, xrot=40, yrot=0)
+
+ _check_plot_works(series.plot.box)
+
+ def test_boxplot_series_positions(self, hist_df):
+ df = hist_df
+ positions = np.array([1, 6, 7])
+ ax = df.plot.box(positions=positions)
+ numeric_cols = df._get_numeric_data().columns
+ labels = [pprint_thing(c) for c in numeric_cols]
+ _check_text_labels(ax.get_xticklabels(), labels)
+ tm.assert_numpy_array_equal(ax.xaxis.get_ticklocs(), positions)
+ assert len(ax.lines) == 7 * len(numeric_cols)
+
+ def test_boxplot_vertical(self, hist_df):
+ df = hist_df
+ numeric_cols = df._get_numeric_data().columns
+ labels = [pprint_thing(c) for c in numeric_cols]
+
+ # if horizontal, yticklabels are rotated
+ ax = df.plot.box(rot=50, fontsize=8, vert=False)
+ _check_ticks_props(ax, xrot=0, yrot=50, ylabelsize=8)
+ _check_text_labels(ax.get_yticklabels(), labels)
+ assert len(ax.lines) == 7 * len(numeric_cols)
+
+ @pytest.mark.filterwarnings("ignore:Attempt:UserWarning")
+ def test_boxplot_vertical_subplots(self, hist_df):
+ df = hist_df
+ numeric_cols = df._get_numeric_data().columns
+ labels = [pprint_thing(c) for c in numeric_cols]
+ axes = _check_plot_works(
+ df.plot.box,
+ default_axes=True,
+ subplots=True,
+ vert=False,
+ logx=True,
+ )
+ _check_axes_shape(axes, axes_num=3, layout=(1, 3))
+ _check_ax_scales(axes, xaxis="log")
+ for ax, label in zip(axes, labels):
+ _check_text_labels(ax.get_yticklabels(), [label])
+ assert len(ax.lines) == 7
+
+ def test_boxplot_vertical_positions(self, hist_df):
+ df = hist_df
+ numeric_cols = df._get_numeric_data().columns
+ labels = [pprint_thing(c) for c in numeric_cols]
+ positions = np.array([3, 2, 8])
+ ax = df.plot.box(positions=positions, vert=False)
+ _check_text_labels(ax.get_yticklabels(), labels)
+ tm.assert_numpy_array_equal(ax.yaxis.get_ticklocs(), positions)
+ assert len(ax.lines) == 7 * len(numeric_cols)
+
+ def test_boxplot_return_type_invalid(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["one", "two", "three", "four"],
+ )
+ msg = "return_type must be {None, 'axes', 'dict', 'both'}"
+ with pytest.raises(ValueError, match=msg):
+ df.plot.box(return_type="not_a_type")
+
+ @pytest.mark.parametrize("return_type", ["dict", "axes", "both"])
+ def test_boxplot_return_type_invalid_type(self, return_type):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["one", "two", "three", "four"],
+ )
+ result = df.plot.box(return_type=return_type)
+ _check_box_return_type(result, return_type)
+
+ def test_kde_df(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((100, 4)))
+ ax = _check_plot_works(df.plot, kind="kde")
+ expected = [pprint_thing(c) for c in df.columns]
+ _check_legend_labels(ax, labels=expected)
+ _check_ticks_props(ax, xrot=0)
+
+ def test_kde_df_rot(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
+ ax = df.plot(kind="kde", rot=20, fontsize=5)
+ _check_ticks_props(ax, xrot=20, xlabelsize=5, ylabelsize=5)
+
+ def test_kde_df_subplots(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
+ axes = _check_plot_works(
+ df.plot,
+ default_axes=True,
+ kind="kde",
+ subplots=True,
+ )
+ _check_axes_shape(axes, axes_num=4, layout=(4, 1))
+
+ def test_kde_df_logy(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
+ axes = df.plot(kind="kde", logy=True, subplots=True)
+ _check_ax_scales(axes, yaxis="log")
+
+ def test_kde_missing_vals(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).uniform(size=(100, 4)))
+ df.loc[0, 0] = np.nan
+ _check_plot_works(df.plot, kind="kde")
+
+ def test_hist_df(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((100, 4)))
+
+ ax = _check_plot_works(df.plot.hist)
+ expected = [pprint_thing(c) for c in df.columns]
+ _check_legend_labels(ax, labels=expected)
+
+ axes = _check_plot_works(
+ df.plot.hist,
+ default_axes=True,
+ subplots=True,
+ logy=True,
+ )
+ _check_axes_shape(axes, axes_num=4, layout=(4, 1))
+ _check_ax_scales(axes, yaxis="log")
+
+ def test_hist_df_series(self):
+ series = Series(np.random.default_rng(2).random(10))
+ axes = series.plot.hist(rot=40)
+ _check_ticks_props(axes, xrot=40, yrot=0)
+
+ def test_hist_df_series_cumulative_density(self):
+ from matplotlib.patches import Rectangle
+
+ series = Series(np.random.default_rng(2).random(10))
+ ax = series.plot.hist(cumulative=True, bins=4, density=True)
+ # height of last bin (index 5) must be 1.0
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
+ tm.assert_almost_equal(rects[-1].get_height(), 1.0)
+
+ def test_hist_df_series_cumulative(self):
+ from matplotlib.patches import Rectangle
+
+ series = Series(np.random.default_rng(2).random(10))
+ ax = series.plot.hist(cumulative=True, bins=4)
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
+
+ tm.assert_almost_equal(rects[-2].get_height(), 10.0)
+
+ def test_hist_df_orientation(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
+ # if horizontal, yticklabels are rotated
+ axes = df.plot.hist(rot=50, fontsize=8, orientation="horizontal")
+ _check_ticks_props(axes, xrot=0, yrot=50, ylabelsize=8)
+
+ @pytest.mark.parametrize(
+ "weights", [0.1 * np.ones(shape=(100,)), 0.1 * np.ones(shape=(100, 2))]
+ )
+ def test_hist_weights(self, weights):
+ # GH 33173
+
+ df = DataFrame(
+ dict(zip(["A", "B"], np.random.default_rng(2).standard_normal((2, 100))))
+ )
+
+ ax1 = _check_plot_works(df.plot, kind="hist", weights=weights)
+ ax2 = _check_plot_works(df.plot, kind="hist")
+
+ patch_height_with_weights = [patch.get_height() for patch in ax1.patches]
+
+ # original heights with no weights, and we manually multiply with example
+ # weights, so after multiplication, they should be almost same
+ expected_patch_height = [0.1 * patch.get_height() for patch in ax2.patches]
+
+ tm.assert_almost_equal(patch_height_with_weights, expected_patch_height)
+
+ def _check_box_coord(
+ self,
+ patches,
+ expected_y=None,
+ expected_h=None,
+ expected_x=None,
+ expected_w=None,
+ ):
+ result_y = np.array([p.get_y() for p in patches])
+ result_height = np.array([p.get_height() for p in patches])
+ result_x = np.array([p.get_x() for p in patches])
+ result_width = np.array([p.get_width() for p in patches])
+ # dtype is depending on above values, no need to check
+
+ if expected_y is not None:
+ tm.assert_numpy_array_equal(result_y, expected_y, check_dtype=False)
+ if expected_h is not None:
+ tm.assert_numpy_array_equal(result_height, expected_h, check_dtype=False)
+ if expected_x is not None:
+ tm.assert_numpy_array_equal(result_x, expected_x, check_dtype=False)
+ if expected_w is not None:
+ tm.assert_numpy_array_equal(result_width, expected_w, check_dtype=False)
+
+ @pytest.mark.parametrize(
+ "data",
+ [
+ {
+ "A": np.repeat(np.array([1, 2, 3, 4, 5]), np.array([10, 9, 8, 7, 6])),
+ "B": np.repeat(np.array([1, 2, 3, 4, 5]), np.array([8, 8, 8, 8, 8])),
+ "C": np.repeat(np.array([1, 2, 3, 4, 5]), np.array([6, 7, 8, 9, 10])),
+ },
+ {
+ "A": np.repeat(
+ np.array([np.nan, 1, 2, 3, 4, 5]), np.array([3, 10, 9, 8, 7, 6])
+ ),
+ "B": np.repeat(
+ np.array([1, np.nan, 2, 3, 4, 5]), np.array([8, 3, 8, 8, 8, 8])
+ ),
+ "C": np.repeat(
+ np.array([1, 2, 3, np.nan, 4, 5]), np.array([6, 7, 8, 3, 9, 10])
+ ),
+ },
+ ],
+ )
+ def test_hist_df_coord(self, data):
+ df = DataFrame(data)
+
+ ax = df.plot.hist(bins=5)
+ self._check_box_coord(
+ ax.patches[:5],
+ expected_y=np.array([0, 0, 0, 0, 0]),
+ expected_h=np.array([10, 9, 8, 7, 6]),
+ )
+ self._check_box_coord(
+ ax.patches[5:10],
+ expected_y=np.array([0, 0, 0, 0, 0]),
+ expected_h=np.array([8, 8, 8, 8, 8]),
+ )
+ self._check_box_coord(
+ ax.patches[10:],
+ expected_y=np.array([0, 0, 0, 0, 0]),
+ expected_h=np.array([6, 7, 8, 9, 10]),
+ )
+
+ ax = df.plot.hist(bins=5, stacked=True)
+ self._check_box_coord(
+ ax.patches[:5],
+ expected_y=np.array([0, 0, 0, 0, 0]),
+ expected_h=np.array([10, 9, 8, 7, 6]),
+ )
+ self._check_box_coord(
+ ax.patches[5:10],
+ expected_y=np.array([10, 9, 8, 7, 6]),
+ expected_h=np.array([8, 8, 8, 8, 8]),
+ )
+ self._check_box_coord(
+ ax.patches[10:],
+ expected_y=np.array([18, 17, 16, 15, 14]),
+ expected_h=np.array([6, 7, 8, 9, 10]),
+ )
+
+ axes = df.plot.hist(bins=5, stacked=True, subplots=True)
+ self._check_box_coord(
+ axes[0].patches,
+ expected_y=np.array([0, 0, 0, 0, 0]),
+ expected_h=np.array([10, 9, 8, 7, 6]),
+ )
+ self._check_box_coord(
+ axes[1].patches,
+ expected_y=np.array([0, 0, 0, 0, 0]),
+ expected_h=np.array([8, 8, 8, 8, 8]),
+ )
+ self._check_box_coord(
+ axes[2].patches,
+ expected_y=np.array([0, 0, 0, 0, 0]),
+ expected_h=np.array([6, 7, 8, 9, 10]),
+ )
+
+ # horizontal
+ ax = df.plot.hist(bins=5, orientation="horizontal")
+ self._check_box_coord(
+ ax.patches[:5],
+ expected_x=np.array([0, 0, 0, 0, 0]),
+ expected_w=np.array([10, 9, 8, 7, 6]),
+ )
+ self._check_box_coord(
+ ax.patches[5:10],
+ expected_x=np.array([0, 0, 0, 0, 0]),
+ expected_w=np.array([8, 8, 8, 8, 8]),
+ )
+ self._check_box_coord(
+ ax.patches[10:],
+ expected_x=np.array([0, 0, 0, 0, 0]),
+ expected_w=np.array([6, 7, 8, 9, 10]),
+ )
+
+ ax = df.plot.hist(bins=5, stacked=True, orientation="horizontal")
+ self._check_box_coord(
+ ax.patches[:5],
+ expected_x=np.array([0, 0, 0, 0, 0]),
+ expected_w=np.array([10, 9, 8, 7, 6]),
+ )
+ self._check_box_coord(
+ ax.patches[5:10],
+ expected_x=np.array([10, 9, 8, 7, 6]),
+ expected_w=np.array([8, 8, 8, 8, 8]),
+ )
+ self._check_box_coord(
+ ax.patches[10:],
+ expected_x=np.array([18, 17, 16, 15, 14]),
+ expected_w=np.array([6, 7, 8, 9, 10]),
+ )
+
+ axes = df.plot.hist(
+ bins=5, stacked=True, subplots=True, orientation="horizontal"
+ )
+ self._check_box_coord(
+ axes[0].patches,
+ expected_x=np.array([0, 0, 0, 0, 0]),
+ expected_w=np.array([10, 9, 8, 7, 6]),
+ )
+ self._check_box_coord(
+ axes[1].patches,
+ expected_x=np.array([0, 0, 0, 0, 0]),
+ expected_w=np.array([8, 8, 8, 8, 8]),
+ )
+ self._check_box_coord(
+ axes[2].patches,
+ expected_x=np.array([0, 0, 0, 0, 0]),
+ expected_w=np.array([6, 7, 8, 9, 10]),
+ )
+
+ def test_plot_int_columns(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((100, 4))).cumsum()
+ _check_plot_works(df.plot, legend=True)
+
+ @pytest.mark.parametrize(
+ "markers",
+ [
+ {0: "^", 1: "+", 2: "o"},
+ {0: "^", 1: "+"},
+ ["^", "+", "o"],
+ ["^", "+"],
+ ],
+ )
+ def test_style_by_column(self, markers):
+ import matplotlib.pyplot as plt
+
+ fig = plt.gcf()
+ fig.clf()
+ fig.add_subplot(111)
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 3)))
+ ax = df.plot(style=markers)
+ for idx, line in enumerate(ax.get_lines()[: len(markers)]):
+ assert line.get_marker() == markers[idx]
+
+ def test_line_label_none(self):
+ s = Series([1, 2])
+ ax = s.plot()
+ assert ax.get_legend() is None
+
+ ax = s.plot(legend=True)
+ assert ax.get_legend().get_texts()[0].get_text() == ""
+
+ @pytest.mark.parametrize(
+ "props, expected",
+ [
+ ("boxprops", "boxes"),
+ ("whiskerprops", "whiskers"),
+ ("capprops", "caps"),
+ ("medianprops", "medians"),
+ ],
+ )
+ def test_specified_props_kwd_plot_box(self, props, expected):
+ # GH 30346
+ df = DataFrame({k: np.random.default_rng(2).random(100) for k in "ABC"})
+ kwd = {props: {"color": "C1"}}
+ result = df.plot.box(return_type="dict", **kwd)
+
+ assert result[expected][0].get_color() == "C1"
+
+ def test_unordered_ts(self):
+ df = DataFrame(
+ np.array([3.0, 2.0, 1.0]),
+ index=[date(2012, 10, 1), date(2012, 9, 1), date(2012, 8, 1)],
+ columns=["test"],
+ )
+ ax = df.plot()
+ xticks = ax.lines[0].get_xdata()
+ assert xticks[0] < xticks[1]
+ ydata = ax.lines[0].get_ydata()
+ tm.assert_numpy_array_equal(ydata, np.array([1.0, 2.0, 3.0]))
+
+ @pytest.mark.parametrize("kind", plotting.PlotAccessor._common_kinds)
+ def test_kind_both_ways(self, kind):
+ pytest.importorskip("scipy")
+ df = DataFrame({"x": [1, 2, 3]})
+ df.plot(kind=kind)
+ getattr(df.plot, kind)()
+
+ @pytest.mark.parametrize("kind", ["scatter", "hexbin"])
+ def test_kind_both_ways_x_y(self, kind):
+ pytest.importorskip("scipy")
+ df = DataFrame({"x": [1, 2, 3]})
+ df.plot("x", "x", kind=kind)
+ getattr(df.plot, kind)("x", "x")
+
+ @pytest.mark.parametrize("kind", plotting.PlotAccessor._common_kinds)
+ def test_all_invalid_plot_data(self, kind):
+ df = DataFrame(list("abcd"))
+ msg = "no numeric data to plot"
+ with pytest.raises(TypeError, match=msg):
+ df.plot(kind=kind)
+
+ @pytest.mark.parametrize(
+ "kind", list(plotting.PlotAccessor._common_kinds) + ["area"]
+ )
+ def test_partially_invalid_plot_data_numeric(self, kind):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)),
+ dtype=object,
+ )
+ df[np.random.default_rng(2).random(df.shape[0]) > 0.5] = "a"
+ msg = "no numeric data to plot"
+ with pytest.raises(TypeError, match=msg):
+ df.plot(kind=kind)
+
+ def test_invalid_kind(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+ msg = "invalid_plot_kind is not a valid plot kind"
+ with pytest.raises(ValueError, match=msg):
+ df.plot(kind="invalid_plot_kind")
+
+ @pytest.mark.parametrize(
+ "x,y,lbl",
+ [
+ (["B", "C"], "A", "a"),
+ (["A"], ["B", "C"], ["b", "c"]),
+ ],
+ )
+ def test_invalid_xy_args(self, x, y, lbl):
+ # GH 18671, 19699 allows y to be list-like but not x
+ df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
+ with pytest.raises(ValueError, match="x must be a label or position"):
+ df.plot(x=x, y=y, label=lbl)
+
+ def test_bad_label(self):
+ df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
+ msg = "label should be list-like and same length as y"
+ with pytest.raises(ValueError, match=msg):
+ df.plot(x="A", y=["B", "C"], label="bad_label")
+
+ @pytest.mark.parametrize("x,y", [("A", "B"), (["A"], "B")])
+ def test_invalid_xy_args_dup_cols(self, x, y):
+ # GH 18671, 19699 allows y to be list-like but not x
+ df = DataFrame([[1, 3, 5], [2, 4, 6]], columns=list("AAB"))
+ with pytest.raises(ValueError, match="x must be a label or position"):
+ df.plot(x=x, y=y)
+
+ @pytest.mark.parametrize(
+ "x,y,lbl,colors",
+ [
+ ("A", ["B"], ["b"], ["red"]),
+ ("A", ["B", "C"], ["b", "c"], ["red", "blue"]),
+ (0, [1, 2], ["bokeh", "cython"], ["green", "yellow"]),
+ ],
+ )
+ def test_y_listlike(self, x, y, lbl, colors):
+ # GH 19699: tests list-like y and verifies lbls & colors
+ df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
+ _check_plot_works(df.plot, x="A", y=y, label=lbl)
+
+ ax = df.plot(x=x, y=y, label=lbl, color=colors)
+ assert len(ax.lines) == len(y)
+ _check_colors(ax.get_lines(), linecolors=colors)
+
+ @pytest.mark.parametrize("x,y,colnames", [(0, 1, ["A", "B"]), (1, 0, [0, 1])])
+ def test_xy_args_integer(self, x, y, colnames):
+ # GH 20056: tests integer args for xy and checks col names
+ df = DataFrame({"A": [1, 2], "B": [3, 4]})
+ df.columns = colnames
+ _check_plot_works(df.plot, x=x, y=y)
+
+ def test_hexbin_basic(self):
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).uniform(size=20),
+ "B": np.random.default_rng(2).uniform(size=20),
+ "C": np.arange(20) + np.random.default_rng(2).uniform(size=20),
+ }
+ )
+
+ ax = df.plot.hexbin(x="A", y="B", gridsize=10)
+ # TODO: need better way to test. This just does existence.
+ assert len(ax.collections) == 1
+
+ def test_hexbin_basic_subplots(self):
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).uniform(size=20),
+ "B": np.random.default_rng(2).uniform(size=20),
+ "C": np.arange(20) + np.random.default_rng(2).uniform(size=20),
+ }
+ )
+ # GH 6951
+ axes = df.plot.hexbin(x="A", y="B", subplots=True)
+ # hexbin should have 2 axes in the figure, 1 for plotting and another
+ # is colorbar
+ assert len(axes[0].figure.axes) == 2
+ # return value is single axes
+ _check_axes_shape(axes, axes_num=1, layout=(1, 1))
+
+ @pytest.mark.parametrize("reduce_C", [None, np.std])
+ def test_hexbin_with_c(self, reduce_C):
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).uniform(size=20),
+ "B": np.random.default_rng(2).uniform(size=20),
+ "C": np.arange(20) + np.random.default_rng(2).uniform(size=20),
+ }
+ )
+
+ ax = df.plot.hexbin(x="A", y="B", C="C", reduce_C_function=reduce_C)
+ assert len(ax.collections) == 1
+
+ @pytest.mark.parametrize(
+ "kwargs, expected",
+ [
+ ({}, "BuGn"), # default cmap
+ ({"colormap": "cubehelix"}, "cubehelix"),
+ ({"cmap": "YlGn"}, "YlGn"),
+ ],
+ )
+ def test_hexbin_cmap(self, kwargs, expected):
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).uniform(size=20),
+ "B": np.random.default_rng(2).uniform(size=20),
+ "C": np.arange(20) + np.random.default_rng(2).uniform(size=20),
+ }
+ )
+ ax = df.plot.hexbin(x="A", y="B", **kwargs)
+ assert ax.collections[0].cmap.name == expected
+
+ def test_pie_df_err(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((5, 3)),
+ columns=["X", "Y", "Z"],
+ index=["a", "b", "c", "d", "e"],
+ )
+ msg = "pie requires either y column or 'subplots=True'"
+ with pytest.raises(ValueError, match=msg):
+ df.plot.pie()
+
+ @pytest.mark.parametrize("y", ["Y", 2])
+ def test_pie_df(self, y):
+ df = DataFrame(
+ np.random.default_rng(2).random((5, 3)),
+ columns=["X", "Y", "Z"],
+ index=["a", "b", "c", "d", "e"],
+ )
+ ax = _check_plot_works(df.plot.pie, y=y)
+ _check_text_labels(ax.texts, df.index)
+
+ def test_pie_df_subplots(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((5, 3)),
+ columns=["X", "Y", "Z"],
+ index=["a", "b", "c", "d", "e"],
+ )
+ axes = _check_plot_works(
+ df.plot.pie,
+ default_axes=True,
+ subplots=True,
+ )
+ assert len(axes) == len(df.columns)
+ for ax in axes:
+ _check_text_labels(ax.texts, df.index)
+ for ax, ylabel in zip(axes, df.columns):
+ assert ax.get_ylabel() == ylabel
+
+ def test_pie_df_labels_colors(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((5, 3)),
+ columns=["X", "Y", "Z"],
+ index=["a", "b", "c", "d", "e"],
+ )
+ labels = ["A", "B", "C", "D", "E"]
+ color_args = ["r", "g", "b", "c", "m"]
+ axes = _check_plot_works(
+ df.plot.pie,
+ default_axes=True,
+ subplots=True,
+ labels=labels,
+ colors=color_args,
+ )
+ assert len(axes) == len(df.columns)
+
+ for ax in axes:
+ _check_text_labels(ax.texts, labels)
+ _check_colors(ax.patches, facecolors=color_args)
+
+ def test_pie_df_nan(self):
+ df = DataFrame(np.random.default_rng(2).random((4, 4)))
+ for i in range(4):
+ df.iloc[i, i] = np.nan
+ _, axes = mpl.pyplot.subplots(ncols=4)
+
+ # GH 37668
+ kwargs = {"normalize": True}
+
+ with tm.assert_produces_warning(None):
+ df.plot.pie(subplots=True, ax=axes, legend=True, **kwargs)
+
+ base_expected = ["0", "1", "2", "3"]
+ for i, ax in enumerate(axes):
+ expected = list(base_expected) # force copy
+ expected[i] = ""
+ result = [x.get_text() for x in ax.texts]
+ assert result == expected
+
+ # legend labels
+ # NaN's not included in legend with subplots
+ # see https://github.com/pandas-dev/pandas/issues/8390
+ result_labels = [x.get_text() for x in ax.get_legend().get_texts()]
+ expected_labels = base_expected[:i] + base_expected[i + 1 :]
+ assert result_labels == expected_labels
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"logy": True},
+ {"logx": True, "logy": True},
+ {"loglog": True},
+ ],
+ )
+ def test_errorbar_plot(self, kwargs):
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
+ df = DataFrame(d)
+ d_err = {"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4}
+ df_err = DataFrame(d_err)
+
+ # check line plots
+ ax = _check_plot_works(df.plot, yerr=df_err, **kwargs)
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ @pytest.mark.slow
+ def test_errorbar_plot_bar(self):
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
+ df = DataFrame(d)
+ d_err = {"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4}
+ df_err = DataFrame(d_err)
+ ax = _check_plot_works(
+ (df + 1).plot, yerr=df_err, xerr=df_err, kind="bar", log=True
+ )
+ _check_has_errorbars(ax, xerr=2, yerr=2)
+
+ @pytest.mark.slow
+ def test_errorbar_plot_yerr_array(self):
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
+ df = DataFrame(d)
+ # yerr is raw error values
+ ax = _check_plot_works(df["y"].plot, yerr=np.ones(12) * 0.4)
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+
+ ax = _check_plot_works(df.plot, yerr=np.ones((2, 12)) * 0.4)
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("yerr", ["yerr", "誤差"])
+ def test_errorbar_plot_column_name(self, yerr):
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
+ df = DataFrame(d)
+ df[yerr] = np.ones(12) * 0.2
+
+ ax = _check_plot_works(df.plot, yerr=yerr)
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ ax = _check_plot_works(df.plot, y="y", x="x", yerr=yerr)
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+
+ @pytest.mark.slow
+ def test_errorbar_plot_external_valueerror(self):
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
+ df = DataFrame(d)
+ with tm.external_error_raised(ValueError):
+ df.plot(yerr=np.random.default_rng(2).standard_normal(11))
+
+ @pytest.mark.slow
+ def test_errorbar_plot_external_typeerror(self):
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
+ df = DataFrame(d)
+ df_err = DataFrame({"x": ["zzz"] * 12, "y": ["zzz"] * 12})
+ with tm.external_error_raised(TypeError):
+ df.plot(yerr=df_err)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kind", ["line", "bar", "barh"])
+ @pytest.mark.parametrize(
+ "y_err",
+ [
+ Series(np.ones(12) * 0.2, name="x"),
+ DataFrame({"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4}),
+ ],
+ )
+ def test_errorbar_plot_different_yerr(self, kind, y_err):
+ df = DataFrame({"x": np.arange(12), "y": np.arange(12, 0, -1)})
+
+ ax = _check_plot_works(df.plot, yerr=y_err, kind=kind)
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kind", ["line", "bar", "barh"])
+ @pytest.mark.parametrize(
+ "y_err, x_err",
+ [
+ (
+ DataFrame({"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4}),
+ DataFrame({"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4}),
+ ),
+ (Series(np.ones(12) * 0.2, name="x"), Series(np.ones(12) * 0.2, name="x")),
+ (0.2, 0.2),
+ ],
+ )
+ def test_errorbar_plot_different_yerr_xerr(self, kind, y_err, x_err):
+ df = DataFrame({"x": np.arange(12), "y": np.arange(12, 0, -1)})
+ ax = _check_plot_works(df.plot, yerr=y_err, xerr=x_err, kind=kind)
+ _check_has_errorbars(ax, xerr=2, yerr=2)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kind", ["line", "bar", "barh"])
+ def test_errorbar_plot_different_yerr_xerr_subplots(self, kind):
+ df = DataFrame({"x": np.arange(12), "y": np.arange(12, 0, -1)})
+ df_err = DataFrame({"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4})
+ axes = _check_plot_works(
+ df.plot,
+ default_axes=True,
+ yerr=df_err,
+ xerr=df_err,
+ subplots=True,
+ kind=kind,
+ )
+ _check_has_errorbars(axes, xerr=1, yerr=1)
+
+ @pytest.mark.xfail(reason="Iterator is consumed", raises=ValueError)
+ def test_errorbar_plot_iterator(self):
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
+ df = DataFrame(d)
+
+ # yerr is iterator
+ ax = _check_plot_works(df.plot, yerr=itertools.repeat(0.1, len(df)))
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ def test_errorbar_with_integer_column_names(self):
+ # test with integer column names
+ df = DataFrame(np.abs(np.random.default_rng(2).standard_normal((10, 2))))
+ df_err = DataFrame(np.abs(np.random.default_rng(2).standard_normal((10, 2))))
+ ax = _check_plot_works(df.plot, yerr=df_err)
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+ ax = _check_plot_works(df.plot, y=0, yerr=1)
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kind", ["line", "bar"])
+ def test_errorbar_with_partial_columns_kind(self, kind):
+ df = DataFrame(np.abs(np.random.default_rng(2).standard_normal((10, 3))))
+ df_err = DataFrame(
+ np.abs(np.random.default_rng(2).standard_normal((10, 2))), columns=[0, 2]
+ )
+ ax = _check_plot_works(df.plot, yerr=df_err, kind=kind)
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ @pytest.mark.slow
+ def test_errorbar_with_partial_columns_dti(self):
+ df = DataFrame(np.abs(np.random.default_rng(2).standard_normal((10, 3))))
+ df_err = DataFrame(
+ np.abs(np.random.default_rng(2).standard_normal((10, 2))), columns=[0, 2]
+ )
+ ix = date_range("1/1/2000", periods=10, freq="M")
+ df.set_index(ix, inplace=True)
+ df_err.set_index(ix, inplace=True)
+ ax = _check_plot_works(df.plot, yerr=df_err, kind="line")
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("err_box", [lambda x: x, DataFrame])
+ def test_errorbar_with_partial_columns_box(self, err_box):
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
+ df = DataFrame(d)
+ err = err_box({"x": np.ones(12) * 0.2, "z": np.ones(12) * 0.4})
+ ax = _check_plot_works(df.plot, yerr=err)
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+
+ @pytest.mark.parametrize("kind", ["line", "bar", "barh"])
+ def test_errorbar_timeseries(self, kind):
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
+ d_err = {"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4}
+
+ # check time-series plots
+ ix = date_range("1/1/2000", "1/1/2001", freq="M")
+ tdf = DataFrame(d, index=ix)
+ tdf_err = DataFrame(d_err, index=ix)
+
+ ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind)
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ ax = _check_plot_works(tdf.plot, yerr=d_err, kind=kind)
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ ax = _check_plot_works(tdf.plot, y="y", yerr=tdf_err["x"], kind=kind)
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+
+ ax = _check_plot_works(tdf.plot, y="y", yerr="x", kind=kind)
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+
+ ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind)
+ _check_has_errorbars(ax, xerr=0, yerr=2)
+
+ axes = _check_plot_works(
+ tdf.plot,
+ default_axes=True,
+ kind=kind,
+ yerr=tdf_err,
+ subplots=True,
+ )
+ _check_has_errorbars(axes, xerr=0, yerr=1)
+
+ def test_errorbar_asymmetrical(self):
+ err = np.random.default_rng(2).random((3, 2, 5))
+
+ # each column is [0, 1, 2, 3, 4], [3, 4, 5, 6, 7]...
+ df = DataFrame(np.arange(15).reshape(3, 5)).T
+
+ ax = df.plot(yerr=err, xerr=err / 2)
+
+ yerr_0_0 = ax.collections[1].get_paths()[0].vertices[:, 1]
+ expected_0_0 = err[0, :, 0] * np.array([-1, 1])
+ tm.assert_almost_equal(yerr_0_0, expected_0_0)
+
+ msg = re.escape(
+ "Asymmetrical error bars should be provided with the shape (3, 2, 5)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.plot(yerr=err.T)
+
+ def test_table(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+ _check_plot_works(df.plot, table=True)
+ _check_plot_works(df.plot, table=df)
+
+ # GH 35945 UserWarning
+ with tm.assert_produces_warning(None):
+ ax = df.plot()
+ assert len(ax.tables) == 0
+ plotting.table(ax, df.T)
+ assert len(ax.tables) == 1
+
+ def test_errorbar_scatter(self):
+ df = DataFrame(
+ np.abs(np.random.default_rng(2).standard_normal((5, 2))),
+ index=range(5),
+ columns=["x", "y"],
+ )
+ df_err = DataFrame(
+ np.abs(np.random.default_rng(2).standard_normal((5, 2))) / 5,
+ index=range(5),
+ columns=["x", "y"],
+ )
+
+ ax = _check_plot_works(df.plot.scatter, x="x", y="y")
+ _check_has_errorbars(ax, xerr=0, yerr=0)
+ ax = _check_plot_works(df.plot.scatter, x="x", y="y", xerr=df_err)
+ _check_has_errorbars(ax, xerr=1, yerr=0)
+
+ ax = _check_plot_works(df.plot.scatter, x="x", y="y", yerr=df_err)
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+ ax = _check_plot_works(df.plot.scatter, x="x", y="y", xerr=df_err, yerr=df_err)
+ _check_has_errorbars(ax, xerr=1, yerr=1)
+
+ def test_errorbar_scatter_color(self):
+ def _check_errorbar_color(containers, expected, has_err="has_xerr"):
+ lines = []
+ errs = next(c.lines for c in ax.containers if getattr(c, has_err, False))
+ for el in errs:
+ if is_list_like(el):
+ lines.extend(el)
+ else:
+ lines.append(el)
+ err_lines = [x for x in lines if x in ax.collections]
+ _check_colors(err_lines, linecolors=np.array([expected] * len(err_lines)))
+
+ # GH 8081
+ df = DataFrame(
+ np.abs(np.random.default_rng(2).standard_normal((10, 5))),
+ columns=["a", "b", "c", "d", "e"],
+ )
+ ax = df.plot.scatter(x="a", y="b", xerr="d", yerr="e", c="red")
+ _check_has_errorbars(ax, xerr=1, yerr=1)
+ _check_errorbar_color(ax.containers, "red", has_err="has_xerr")
+ _check_errorbar_color(ax.containers, "red", has_err="has_yerr")
+
+ ax = df.plot.scatter(x="a", y="b", yerr="e", color="green")
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+ _check_errorbar_color(ax.containers, "green", has_err="has_yerr")
+
+ def test_scatter_unknown_colormap(self):
+ # GH#48726
+ df = DataFrame({"a": [1, 2, 3], "b": 4})
+ with pytest.raises((ValueError, KeyError), match="'unknown' is not a"):
+ df.plot(x="a", y="b", colormap="unknown", kind="scatter")
+
+ def test_sharex_and_ax(self):
+ # https://github.com/pandas-dev/pandas/issues/9737 using gridspec,
+ # the axis in fig.get_axis() are sorted differently than pandas
+ # expected them, so make sure that only the right ones are removed
+ import matplotlib.pyplot as plt
+
+ plt.close("all")
+ gs, axes = _generate_4_axes_via_gridspec()
+
+ df = DataFrame(
+ {
+ "a": [1, 2, 3, 4, 5, 6],
+ "b": [1, 2, 3, 4, 5, 6],
+ "c": [1, 2, 3, 4, 5, 6],
+ "d": [1, 2, 3, 4, 5, 6],
+ }
+ )
+
+ def _check(axes):
+ for ax in axes:
+ assert len(ax.lines) == 1
+ _check_visible(ax.get_yticklabels(), visible=True)
+ for ax in [axes[0], axes[2]]:
+ _check_visible(ax.get_xticklabels(), visible=False)
+ _check_visible(ax.get_xticklabels(minor=True), visible=False)
+ for ax in [axes[1], axes[3]]:
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+
+ for ax in axes:
+ df.plot(x="a", y="b", title="title", ax=ax, sharex=True)
+ gs.tight_layout(plt.gcf())
+ _check(axes)
+ plt.close("all")
+
+ gs, axes = _generate_4_axes_via_gridspec()
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.plot(subplots=True, ax=axes, sharex=True)
+ _check(axes)
+
+ def test_sharex_false_and_ax(self):
+ # https://github.com/pandas-dev/pandas/issues/9737 using gridspec,
+ # the axis in fig.get_axis() are sorted differently than pandas
+ # expected them, so make sure that only the right ones are removed
+ import matplotlib.pyplot as plt
+
+ df = DataFrame(
+ {
+ "a": [1, 2, 3, 4, 5, 6],
+ "b": [1, 2, 3, 4, 5, 6],
+ "c": [1, 2, 3, 4, 5, 6],
+ "d": [1, 2, 3, 4, 5, 6],
+ }
+ )
+ gs, axes = _generate_4_axes_via_gridspec()
+ # without sharex, no labels should be touched!
+ for ax in axes:
+ df.plot(x="a", y="b", title="title", ax=ax)
+
+ gs.tight_layout(plt.gcf())
+ for ax in axes:
+ assert len(ax.lines) == 1
+ _check_visible(ax.get_yticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+
+ def test_sharey_and_ax(self):
+ # https://github.com/pandas-dev/pandas/issues/9737 using gridspec,
+ # the axis in fig.get_axis() are sorted differently than pandas
+ # expected them, so make sure that only the right ones are removed
+ import matplotlib.pyplot as plt
+
+ gs, axes = _generate_4_axes_via_gridspec()
+
+ df = DataFrame(
+ {
+ "a": [1, 2, 3, 4, 5, 6],
+ "b": [1, 2, 3, 4, 5, 6],
+ "c": [1, 2, 3, 4, 5, 6],
+ "d": [1, 2, 3, 4, 5, 6],
+ }
+ )
+
+ def _check(axes):
+ for ax in axes:
+ assert len(ax.lines) == 1
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+ for ax in [axes[0], axes[1]]:
+ _check_visible(ax.get_yticklabels(), visible=True)
+ for ax in [axes[2], axes[3]]:
+ _check_visible(ax.get_yticklabels(), visible=False)
+
+ for ax in axes:
+ df.plot(x="a", y="b", title="title", ax=ax, sharey=True)
+ gs.tight_layout(plt.gcf())
+ _check(axes)
+ plt.close("all")
+
+ gs, axes = _generate_4_axes_via_gridspec()
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.plot(subplots=True, ax=axes, sharey=True)
+
+ gs.tight_layout(plt.gcf())
+ _check(axes)
+
+ def test_sharey_and_ax_tight(self):
+ # https://github.com/pandas-dev/pandas/issues/9737 using gridspec,
+ import matplotlib.pyplot as plt
+
+ df = DataFrame(
+ {
+ "a": [1, 2, 3, 4, 5, 6],
+ "b": [1, 2, 3, 4, 5, 6],
+ "c": [1, 2, 3, 4, 5, 6],
+ "d": [1, 2, 3, 4, 5, 6],
+ }
+ )
+ gs, axes = _generate_4_axes_via_gridspec()
+ # without sharex, no labels should be touched!
+ for ax in axes:
+ df.plot(x="a", y="b", title="title", ax=ax)
+
+ gs.tight_layout(plt.gcf())
+ for ax in axes:
+ assert len(ax.lines) == 1
+ _check_visible(ax.get_yticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+
+ @pytest.mark.parametrize("kind", plotting.PlotAccessor._all_kinds)
+ def test_memory_leak(self, kind):
+ """Check that every plot type gets properly collected."""
+ pytest.importorskip("scipy")
+ args = {}
+ if kind in ["hexbin", "scatter", "pie"]:
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).uniform(size=20),
+ "B": np.random.default_rng(2).uniform(size=20),
+ "C": np.arange(20) + np.random.default_rng(2).uniform(size=20),
+ }
+ )
+ args = {"x": "A", "y": "B"}
+ elif kind == "area":
+ df = tm.makeTimeDataFrame().abs()
+ else:
+ df = tm.makeTimeDataFrame()
+
+ # Use a weakref so we can see if the object gets collected without
+ # also preventing it from being collected
+ ref = weakref.ref(df.plot(kind=kind, **args))
+
+ # have matplotlib delete all the figures
+ plt.close("all")
+ # force a garbage collection
+ gc.collect()
+ assert ref() is None
+
+ def test_df_gridspec_patterns_vert_horiz(self):
+ # GH 10819
+ from matplotlib import gridspec
+ import matplotlib.pyplot as plt
+
+ ts = Series(
+ np.random.default_rng(2).standard_normal(10),
+ index=date_range("1/1/2000", periods=10),
+ )
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)),
+ index=ts.index,
+ columns=list("AB"),
+ )
+
+ def _get_vertical_grid():
+ gs = gridspec.GridSpec(3, 1)
+ fig = plt.figure()
+ ax1 = fig.add_subplot(gs[:2, :])
+ ax2 = fig.add_subplot(gs[2, :])
+ return ax1, ax2
+
+ def _get_horizontal_grid():
+ gs = gridspec.GridSpec(1, 3)
+ fig = plt.figure()
+ ax1 = fig.add_subplot(gs[:, :2])
+ ax2 = fig.add_subplot(gs[:, 2])
+ return ax1, ax2
+
+ for ax1, ax2 in [_get_vertical_grid(), _get_horizontal_grid()]:
+ ax1 = ts.plot(ax=ax1)
+ assert len(ax1.lines) == 1
+ ax2 = df.plot(ax=ax2)
+ assert len(ax2.lines) == 2
+ for ax in [ax1, ax2]:
+ _check_visible(ax.get_yticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+ plt.close("all")
+
+ # subplots=True
+ for ax1, ax2 in [_get_vertical_grid(), _get_horizontal_grid()]:
+ axes = df.plot(subplots=True, ax=[ax1, ax2])
+ assert len(ax1.lines) == 1
+ assert len(ax2.lines) == 1
+ for ax in axes:
+ _check_visible(ax.get_yticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+ plt.close("all")
+
+ # vertical / subplots / sharex=True / sharey=True
+ ax1, ax2 = _get_vertical_grid()
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.plot(subplots=True, ax=[ax1, ax2], sharex=True, sharey=True)
+ assert len(axes[0].lines) == 1
+ assert len(axes[1].lines) == 1
+ for ax in [ax1, ax2]:
+ # yaxis are visible because there is only one column
+ _check_visible(ax.get_yticklabels(), visible=True)
+ # xaxis of axes0 (top) are hidden
+ _check_visible(axes[0].get_xticklabels(), visible=False)
+ _check_visible(axes[0].get_xticklabels(minor=True), visible=False)
+ _check_visible(axes[1].get_xticklabels(), visible=True)
+ _check_visible(axes[1].get_xticklabels(minor=True), visible=True)
+ plt.close("all")
+
+ # horizontal / subplots / sharex=True / sharey=True
+ ax1, ax2 = _get_horizontal_grid()
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.plot(subplots=True, ax=[ax1, ax2], sharex=True, sharey=True)
+ assert len(axes[0].lines) == 1
+ assert len(axes[1].lines) == 1
+ _check_visible(axes[0].get_yticklabels(), visible=True)
+ # yaxis of axes1 (right) are hidden
+ _check_visible(axes[1].get_yticklabels(), visible=False)
+ for ax in [ax1, ax2]:
+ # xaxis are visible because there is only one column
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+ plt.close("all")
+
+ def test_df_gridspec_patterns_boxed(self):
+ # GH 10819
+ from matplotlib import gridspec
+ import matplotlib.pyplot as plt
+
+ ts = Series(
+ np.random.default_rng(2).standard_normal(10),
+ index=date_range("1/1/2000", periods=10),
+ )
+
+ # boxed
+ def _get_boxed_grid():
+ gs = gridspec.GridSpec(3, 3)
+ fig = plt.figure()
+ ax1 = fig.add_subplot(gs[:2, :2])
+ ax2 = fig.add_subplot(gs[:2, 2])
+ ax3 = fig.add_subplot(gs[2, :2])
+ ax4 = fig.add_subplot(gs[2, 2])
+ return ax1, ax2, ax3, ax4
+
+ axes = _get_boxed_grid()
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)),
+ index=ts.index,
+ columns=list("ABCD"),
+ )
+ axes = df.plot(subplots=True, ax=axes)
+ for ax in axes:
+ assert len(ax.lines) == 1
+ # axis are visible because these are not shared
+ _check_visible(ax.get_yticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+ plt.close("all")
+
+ # subplots / sharex=True / sharey=True
+ axes = _get_boxed_grid()
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.plot(subplots=True, ax=axes, sharex=True, sharey=True)
+ for ax in axes:
+ assert len(ax.lines) == 1
+ for ax in [axes[0], axes[2]]: # left column
+ _check_visible(ax.get_yticklabels(), visible=True)
+ for ax in [axes[1], axes[3]]: # right column
+ _check_visible(ax.get_yticklabels(), visible=False)
+ for ax in [axes[0], axes[1]]: # top row
+ _check_visible(ax.get_xticklabels(), visible=False)
+ _check_visible(ax.get_xticklabels(minor=True), visible=False)
+ for ax in [axes[2], axes[3]]: # bottom row
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+ plt.close("all")
+
+ def test_df_grid_settings(self):
+ # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792
+ _check_grid_settings(
+ DataFrame({"a": [1, 2, 3], "b": [2, 3, 4]}),
+ plotting.PlotAccessor._dataframe_kinds,
+ kws={"x": "a", "y": "b"},
+ )
+
+ def test_plain_axes(self):
+ # supplied ax itself is a SubplotAxes, but figure contains also
+ # a plain Axes object (GH11556)
+ fig, ax = mpl.pyplot.subplots()
+ fig.add_axes([0.2, 0.2, 0.2, 0.2])
+ Series(np.random.default_rng(2).random(10)).plot(ax=ax)
+
+ def test_plain_axes_df(self):
+ # supplied ax itself is a plain Axes, but because the cmap keyword
+ # a new ax is created for the colorbar -> also multiples axes (GH11520)
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(8),
+ "b": np.random.default_rng(2).standard_normal(8),
+ }
+ )
+ fig = mpl.pyplot.figure()
+ ax = fig.add_axes((0, 0, 1, 1))
+ df.plot(kind="scatter", ax=ax, x="a", y="b", c="a", cmap="hsv")
+
+ def test_plain_axes_make_axes_locatable(self):
+ # other examples
+ fig, ax = mpl.pyplot.subplots()
+ from mpl_toolkits.axes_grid1 import make_axes_locatable
+
+ divider = make_axes_locatable(ax)
+ cax = divider.append_axes("right", size="5%", pad=0.05)
+ Series(np.random.default_rng(2).random(10)).plot(ax=ax)
+ Series(np.random.default_rng(2).random(10)).plot(ax=cax)
+
+ def test_plain_axes_make_inset_axes(self):
+ fig, ax = mpl.pyplot.subplots()
+ from mpl_toolkits.axes_grid1.inset_locator import inset_axes
+
+ iax = inset_axes(ax, width="30%", height=1.0, loc=3)
+ Series(np.random.default_rng(2).random(10)).plot(ax=ax)
+ Series(np.random.default_rng(2).random(10)).plot(ax=iax)
+
+ @pytest.mark.parametrize("method", ["line", "barh", "bar"])
+ def test_secondary_axis_font_size(self, method):
+ # GH: 12565
+ df = (
+ DataFrame(
+ np.random.default_rng(2).standard_normal((15, 2)), columns=list("AB")
+ )
+ .assign(C=lambda df: df.B.cumsum())
+ .assign(D=lambda df: df.C * 1.1)
+ )
+
+ fontsize = 20
+ sy = ["C", "D"]
+
+ kwargs = {"secondary_y": sy, "fontsize": fontsize, "mark_right": True}
+ ax = getattr(df.plot, method)(**kwargs)
+ _check_ticks_props(axes=ax.right_ax, ylabelsize=fontsize)
+
+ def test_x_string_values_ticks(self):
+ # Test if string plot index have a fixed xtick position
+ # GH: 7612, GH: 22334
+ df = DataFrame(
+ {
+ "sales": [3, 2, 3],
+ "visits": [20, 42, 28],
+ "day": ["Monday", "Tuesday", "Wednesday"],
+ }
+ )
+ ax = df.plot.area(x="day")
+ ax.set_xlim(-1, 3)
+ xticklabels = [t.get_text() for t in ax.get_xticklabels()]
+ labels_position = dict(zip(xticklabels, ax.get_xticks()))
+ # Testing if the label stayed at the right position
+ assert labels_position["Monday"] == 0.0
+ assert labels_position["Tuesday"] == 1.0
+ assert labels_position["Wednesday"] == 2.0
+
+ def test_x_multiindex_values_ticks(self):
+ # Test if multiindex plot index have a fixed xtick position
+ # GH: 15912
+ index = MultiIndex.from_product([[2012, 2013], [1, 2]])
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 2)),
+ columns=["A", "B"],
+ index=index,
+ )
+ ax = df.plot()
+ ax.set_xlim(-1, 4)
+ xticklabels = [t.get_text() for t in ax.get_xticklabels()]
+ labels_position = dict(zip(xticklabels, ax.get_xticks()))
+ # Testing if the label stayed at the right position
+ assert labels_position["(2012, 1)"] == 0.0
+ assert labels_position["(2012, 2)"] == 1.0
+ assert labels_position["(2013, 1)"] == 2.0
+ assert labels_position["(2013, 2)"] == 3.0
+
+ @pytest.mark.parametrize("kind", ["line", "area"])
+ def test_xlim_plot_line(self, kind):
+ # test if xlim is set correctly in plot.line and plot.area
+ # GH 27686
+ df = DataFrame([2, 4], index=[1, 2])
+ ax = df.plot(kind=kind)
+ xlims = ax.get_xlim()
+ assert xlims[0] < 1
+ assert xlims[1] > 2
+
+ def test_xlim_plot_line_correctly_in_mixed_plot_type(self):
+ # test if xlim is set correctly when ax contains multiple different kinds
+ # of plots, GH 27686
+ fig, ax = mpl.pyplot.subplots()
+
+ indexes = ["k1", "k2", "k3", "k4"]
+ df = DataFrame(
+ {
+ "s1": [1000, 2000, 1500, 2000],
+ "s2": [900, 1400, 2000, 3000],
+ "s3": [1500, 1500, 1600, 1200],
+ "secondary_y": [1, 3, 4, 3],
+ },
+ index=indexes,
+ )
+ df[["s1", "s2", "s3"]].plot.bar(ax=ax, stacked=False)
+ df[["secondary_y"]].plot(ax=ax, secondary_y=True)
+
+ xlims = ax.get_xlim()
+ assert xlims[0] < 0
+ assert xlims[1] > 3
+
+ # make sure axis labels are plotted correctly as well
+ xticklabels = [t.get_text() for t in ax.get_xticklabels()]
+ assert xticklabels == indexes
+
+ def test_plot_no_rows(self):
+ # GH 27758
+ df = DataFrame(columns=["foo"], dtype=int)
+ assert df.empty
+ ax = df.plot()
+ assert len(ax.get_lines()) == 1
+ line = ax.get_lines()[0]
+ assert len(line.get_xdata()) == 0
+ assert len(line.get_ydata()) == 0
+
+ def test_plot_no_numeric_data(self):
+ df = DataFrame(["a", "b", "c"])
+ with pytest.raises(TypeError, match="no numeric data to plot"):
+ df.plot()
+
+ @pytest.mark.parametrize(
+ "kind", ("line", "bar", "barh", "hist", "kde", "density", "area", "pie")
+ )
+ def test_group_subplot(self, kind):
+ pytest.importorskip("scipy")
+ d = {
+ "a": np.arange(10),
+ "b": np.arange(10) + 1,
+ "c": np.arange(10) + 1,
+ "d": np.arange(10),
+ "e": np.arange(10),
+ }
+ df = DataFrame(d)
+
+ axes = df.plot(subplots=[("b", "e"), ("c", "d")], kind=kind)
+ assert len(axes) == 3 # 2 groups + single column a
+
+ expected_labels = (["b", "e"], ["c", "d"], ["a"])
+ for ax, labels in zip(axes, expected_labels):
+ if kind != "pie":
+ _check_legend_labels(ax, labels=labels)
+ if kind == "line":
+ assert len(ax.lines) == len(labels)
+
+ def test_group_subplot_series_notimplemented(self):
+ ser = Series(range(1))
+ msg = "An iterable subplots for a Series"
+ with pytest.raises(NotImplementedError, match=msg):
+ ser.plot(subplots=[("a",)])
+
+ def test_group_subplot_multiindex_notimplemented(self):
+ df = DataFrame(np.eye(2), columns=MultiIndex.from_tuples([(0, 1), (1, 2)]))
+ msg = "An iterable subplots for a DataFrame with a MultiIndex"
+ with pytest.raises(NotImplementedError, match=msg):
+ df.plot(subplots=[(0, 1)])
+
+ def test_group_subplot_nonunique_cols_notimplemented(self):
+ df = DataFrame(np.eye(2), columns=["a", "a"])
+ msg = "An iterable subplots for a DataFrame with non-unique"
+ with pytest.raises(NotImplementedError, match=msg):
+ df.plot(subplots=[("a",)])
+
+ @pytest.mark.parametrize(
+ "subplots, expected_msg",
+ [
+ (123, "subplots should be a bool or an iterable"),
+ ("a", "each entry should be a list/tuple"), # iterable of non-iterable
+ ((1,), "each entry should be a list/tuple"), # iterable of non-iterable
+ (("a",), "each entry should be a list/tuple"), # iterable of strings
+ ],
+ )
+ def test_group_subplot_bad_input(self, subplots, expected_msg):
+ # Make sure error is raised when subplots is not a properly
+ # formatted iterable. Only iterables of iterables are permitted, and
+ # entries should not be strings.
+ d = {"a": np.arange(10), "b": np.arange(10)}
+ df = DataFrame(d)
+
+ with pytest.raises(ValueError, match=expected_msg):
+ df.plot(subplots=subplots)
+
+ def test_group_subplot_invalid_column_name(self):
+ d = {"a": np.arange(10), "b": np.arange(10)}
+ df = DataFrame(d)
+
+ with pytest.raises(ValueError, match=r"Column label\(s\) \['bad_name'\]"):
+ df.plot(subplots=[("a", "bad_name")])
+
+ def test_group_subplot_duplicated_column(self):
+ d = {"a": np.arange(10), "b": np.arange(10), "c": np.arange(10)}
+ df = DataFrame(d)
+
+ with pytest.raises(ValueError, match="should be in only one subplot"):
+ df.plot(subplots=[("a", "b"), ("a", "c")])
+
+ @pytest.mark.parametrize("kind", ("box", "scatter", "hexbin"))
+ def test_group_subplot_invalid_kind(self, kind):
+ d = {"a": np.arange(10), "b": np.arange(10)}
+ df = DataFrame(d)
+ with pytest.raises(
+ ValueError, match="When subplots is an iterable, kind must be one of"
+ ):
+ df.plot(subplots=[("a", "b")], kind=kind)
+
+ @pytest.mark.parametrize(
+ "index_name, old_label, new_label",
+ [
+ (None, "", "new"),
+ ("old", "old", "new"),
+ (None, "", ""),
+ (None, "", 1),
+ (None, "", [1, 2]),
+ ],
+ )
+ @pytest.mark.parametrize("kind", ["line", "area", "bar"])
+ def test_xlabel_ylabel_dataframe_single_plot(
+ self, kind, index_name, old_label, new_label
+ ):
+ # GH 9093
+ df = DataFrame([[1, 2], [2, 5]], columns=["Type A", "Type B"])
+ df.index.name = index_name
+
+ # default is the ylabel is not shown and xlabel is index name
+ ax = df.plot(kind=kind)
+ assert ax.get_xlabel() == old_label
+ assert ax.get_ylabel() == ""
+
+ # old xlabel will be overridden and assigned ylabel will be used as ylabel
+ ax = df.plot(kind=kind, ylabel=new_label, xlabel=new_label)
+ assert ax.get_ylabel() == str(new_label)
+ assert ax.get_xlabel() == str(new_label)
+
+ @pytest.mark.parametrize(
+ "xlabel, ylabel",
+ [
+ (None, None),
+ ("X Label", None),
+ (None, "Y Label"),
+ ("X Label", "Y Label"),
+ ],
+ )
+ @pytest.mark.parametrize("kind", ["scatter", "hexbin"])
+ def test_xlabel_ylabel_dataframe_plane_plot(self, kind, xlabel, ylabel):
+ # GH 37001
+ xcol = "Type A"
+ ycol = "Type B"
+ df = DataFrame([[1, 2], [2, 5]], columns=[xcol, ycol])
+
+ # default is the labels are column names
+ ax = df.plot(kind=kind, x=xcol, y=ycol, xlabel=xlabel, ylabel=ylabel)
+ assert ax.get_xlabel() == (xcol if xlabel is None else xlabel)
+ assert ax.get_ylabel() == (ycol if ylabel is None else ylabel)
+
+ @pytest.mark.parametrize("secondary_y", (False, True))
+ def test_secondary_y(self, secondary_y):
+ ax_df = DataFrame([0]).plot(
+ secondary_y=secondary_y, ylabel="Y", ylim=(0, 100), yticks=[99]
+ )
+ for ax in ax_df.figure.axes:
+ if ax.yaxis.get_visible():
+ assert ax.get_ylabel() == "Y"
+ assert ax.get_ylim() == (0, 100)
+ assert ax.get_yticks()[0] == 99
+
+ @pytest.mark.slow
+ def test_plot_no_warning(self):
+ # GH 55138
+ # TODO(3.0): this can be removed once Period[B] deprecation is enforced
+ df = tm.makeTimeDataFrame()
+ with tm.assert_produces_warning(False):
+ _ = df.plot()
+ _ = df.T.plot()
+
+
+def _generate_4_axes_via_gridspec():
+ import matplotlib.pyplot as plt
+
+ gs = mpl.gridspec.GridSpec(2, 2)
+ ax_tl = plt.subplot(gs[0, 0])
+ ax_ll = plt.subplot(gs[1, 0])
+ ax_tr = plt.subplot(gs[0, 1])
+ ax_lr = plt.subplot(gs[1, 1])
+
+ return gs, [ax_tl, ax_ll, ax_tr, ax_lr]
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame_color.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame_color.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff1edd323ef280cef5e7e79aa809906434a86407
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame_color.py
@@ -0,0 +1,670 @@
+""" Test cases for DataFrame.plot """
+import re
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import DataFrame
+import pandas._testing as tm
+from pandas.tests.plotting.common import (
+ _check_colors,
+ _check_plot_works,
+ _unpack_cycler,
+)
+from pandas.util.version import Version
+
+mpl = pytest.importorskip("matplotlib")
+plt = pytest.importorskip("matplotlib.pyplot")
+cm = pytest.importorskip("matplotlib.cm")
+
+
+def _check_colors_box(bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=None):
+ if fliers_c is None:
+ fliers_c = "k"
+ _check_colors(bp["boxes"], linecolors=[box_c] * len(bp["boxes"]))
+ _check_colors(bp["whiskers"], linecolors=[whiskers_c] * len(bp["whiskers"]))
+ _check_colors(bp["medians"], linecolors=[medians_c] * len(bp["medians"]))
+ _check_colors(bp["fliers"], linecolors=[fliers_c] * len(bp["fliers"]))
+ _check_colors(bp["caps"], linecolors=[caps_c] * len(bp["caps"]))
+
+
+class TestDataFrameColor:
+ @pytest.mark.parametrize(
+ "color", ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
+ )
+ def test_mpl2_color_cycle_str(self, color):
+ # GH 15516
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 3)), columns=["a", "b", "c"]
+ )
+ _check_plot_works(df.plot, color=color)
+
+ def test_color_single_series_list(self):
+ # GH 3486
+ df = DataFrame({"A": [1, 2, 3]})
+ _check_plot_works(df.plot, color=["red"])
+
+ @pytest.mark.parametrize("color", [(1, 0, 0), (1, 0, 0, 0.5)])
+ def test_rgb_tuple_color(self, color):
+ # GH 16695
+ df = DataFrame({"x": [1, 2], "y": [3, 4]})
+ _check_plot_works(df.plot, x="x", y="y", color=color)
+
+ def test_color_empty_string(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+ with pytest.raises(ValueError, match="Invalid color argument:"):
+ df.plot(color="")
+
+ def test_color_and_style_arguments(self):
+ df = DataFrame({"x": [1, 2], "y": [3, 4]})
+ # passing both 'color' and 'style' arguments should be allowed
+ # if there is no color symbol in the style strings:
+ ax = df.plot(color=["red", "black"], style=["-", "--"])
+ # check that the linestyles are correctly set:
+ linestyle = [line.get_linestyle() for line in ax.lines]
+ assert linestyle == ["-", "--"]
+ # check that the colors are correctly set:
+ color = [line.get_color() for line in ax.lines]
+ assert color == ["red", "black"]
+ # passing both 'color' and 'style' arguments should not be allowed
+ # if there is a color symbol in the style strings:
+ msg = (
+ "Cannot pass 'style' string with a color symbol and 'color' keyword "
+ "argument. Please use one or the other or pass 'style' without a color "
+ "symbol"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.plot(color=["red", "black"], style=["k-", "r--"])
+
+ @pytest.mark.parametrize(
+ "color, expected",
+ [
+ ("green", ["green"] * 4),
+ (["yellow", "red", "green", "blue"], ["yellow", "red", "green", "blue"]),
+ ],
+ )
+ def test_color_and_marker(self, color, expected):
+ # GH 21003
+ df = DataFrame(np.random.default_rng(2).random((7, 4)))
+ ax = df.plot(color=color, style="d--")
+ # check colors
+ result = [i.get_color() for i in ax.lines]
+ assert result == expected
+ # check markers and linestyles
+ assert all(i.get_linestyle() == "--" for i in ax.lines)
+ assert all(i.get_marker() == "d" for i in ax.lines)
+
+ def test_bar_colors(self):
+ default_colors = _unpack_cycler(plt.rcParams)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot.bar()
+ _check_colors(ax.patches[::5], facecolors=default_colors[:5])
+
+ def test_bar_colors_custom(self):
+ custom_colors = "rgcby"
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot.bar(color=custom_colors)
+ _check_colors(ax.patches[::5], facecolors=custom_colors)
+
+ @pytest.mark.parametrize("colormap", ["jet", cm.jet])
+ def test_bar_colors_cmap(self, colormap):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+
+ ax = df.plot.bar(colormap=colormap)
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)]
+ _check_colors(ax.patches[::5], facecolors=rgba_colors)
+
+ def test_bar_colors_single_col(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.loc[:, [0]].plot.bar(color="DodgerBlue")
+ _check_colors([ax.patches[0]], facecolors=["DodgerBlue"])
+
+ def test_bar_colors_green(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot(kind="bar", color="green")
+ _check_colors(ax.patches[::5], facecolors=["green"] * 5)
+
+ def test_bar_user_colors(self):
+ df = DataFrame(
+ {"A": range(4), "B": range(1, 5), "color": ["red", "blue", "blue", "red"]}
+ )
+ # This should *only* work when `y` is specified, else
+ # we use one color per column
+ ax = df.plot.bar(y="A", color=df["color"])
+ result = [p.get_facecolor() for p in ax.patches]
+ expected = [
+ (1.0, 0.0, 0.0, 1.0),
+ (0.0, 0.0, 1.0, 1.0),
+ (0.0, 0.0, 1.0, 1.0),
+ (1.0, 0.0, 0.0, 1.0),
+ ]
+ assert result == expected
+
+ def test_if_scatterplot_colorbar_affects_xaxis_visibility(self):
+ # addressing issue #10611, to ensure colobar does not
+ # interfere with x-axis label and ticklabels with
+ # ipython inline backend.
+ random_array = np.random.default_rng(2).random((10, 3))
+ df = DataFrame(random_array, columns=["A label", "B label", "C label"])
+
+ ax1 = df.plot.scatter(x="A label", y="B label")
+ ax2 = df.plot.scatter(x="A label", y="B label", c="C label")
+
+ vis1 = [vis.get_visible() for vis in ax1.xaxis.get_minorticklabels()]
+ vis2 = [vis.get_visible() for vis in ax2.xaxis.get_minorticklabels()]
+ assert vis1 == vis2
+
+ vis1 = [vis.get_visible() for vis in ax1.xaxis.get_majorticklabels()]
+ vis2 = [vis.get_visible() for vis in ax2.xaxis.get_majorticklabels()]
+ assert vis1 == vis2
+
+ assert (
+ ax1.xaxis.get_label().get_visible() == ax2.xaxis.get_label().get_visible()
+ )
+
+ def test_if_hexbin_xaxis_label_is_visible(self):
+ # addressing issue #10678, to ensure colobar does not
+ # interfere with x-axis label and ticklabels with
+ # ipython inline backend.
+ random_array = np.random.default_rng(2).random((10, 3))
+ df = DataFrame(random_array, columns=["A label", "B label", "C label"])
+
+ ax = df.plot.hexbin("A label", "B label", gridsize=12)
+ assert all(vis.get_visible() for vis in ax.xaxis.get_minorticklabels())
+ assert all(vis.get_visible() for vis in ax.xaxis.get_majorticklabels())
+ assert ax.xaxis.get_label().get_visible()
+
+ def test_if_scatterplot_colorbars_are_next_to_parent_axes(self):
+ random_array = np.random.default_rng(2).random((10, 3))
+ df = DataFrame(random_array, columns=["A label", "B label", "C label"])
+
+ fig, axes = plt.subplots(1, 2)
+ df.plot.scatter("A label", "B label", c="C label", ax=axes[0])
+ df.plot.scatter("A label", "B label", c="C label", ax=axes[1])
+ plt.tight_layout()
+
+ points = np.array([ax.get_position().get_points() for ax in fig.axes])
+ axes_x_coords = points[:, :, 0]
+ parent_distance = axes_x_coords[1, :] - axes_x_coords[0, :]
+ colorbar_distance = axes_x_coords[3, :] - axes_x_coords[2, :]
+ assert np.isclose(parent_distance, colorbar_distance, atol=1e-7).all()
+
+ @pytest.mark.parametrize("cmap", [None, "Greys"])
+ def test_scatter_with_c_column_name_with_colors(self, cmap):
+ # https://github.com/pandas-dev/pandas/issues/34316
+
+ df = DataFrame(
+ [[5.1, 3.5], [4.9, 3.0], [7.0, 3.2], [6.4, 3.2], [5.9, 3.0]],
+ columns=["length", "width"],
+ )
+ df["species"] = ["r", "r", "g", "g", "b"]
+ if cmap is not None:
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ ax = df.plot.scatter(x=0, y=1, cmap=cmap, c="species")
+ else:
+ ax = df.plot.scatter(x=0, y=1, c="species", cmap=cmap)
+ assert ax.collections[0].colorbar is None
+
+ def test_scatter_colors(self):
+ df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3], "c": [1, 2, 3]})
+ with pytest.raises(TypeError, match="Specify exactly one of `c` and `color`"):
+ df.plot.scatter(x="a", y="b", c="c", color="green")
+
+ def test_scatter_colors_not_raising_warnings(self):
+ # GH-53908. Do not raise UserWarning: No data for colormapping
+ # provided via 'c'. Parameters 'cmap' will be ignored
+ df = DataFrame({"x": [1, 2, 3], "y": [1, 2, 3]})
+ with tm.assert_produces_warning(None):
+ df.plot.scatter(x="x", y="y", c="b")
+
+ def test_scatter_colors_default(self):
+ df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3], "c": [1, 2, 3]})
+ default_colors = _unpack_cycler(mpl.pyplot.rcParams)
+
+ ax = df.plot.scatter(x="a", y="b", c="c")
+ tm.assert_numpy_array_equal(
+ ax.collections[0].get_facecolor()[0],
+ np.array(mpl.colors.ColorConverter.to_rgba(default_colors[0])),
+ )
+
+ def test_scatter_colors_white(self):
+ df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3], "c": [1, 2, 3]})
+ ax = df.plot.scatter(x="a", y="b", color="white")
+ tm.assert_numpy_array_equal(
+ ax.collections[0].get_facecolor()[0],
+ np.array([1, 1, 1, 1], dtype=np.float64),
+ )
+
+ def test_scatter_colorbar_different_cmap(self):
+ # GH 33389
+ df = DataFrame({"x": [1, 2, 3], "y": [1, 3, 2], "c": [1, 2, 3]})
+ df["x2"] = df["x"] + 1
+
+ _, ax = plt.subplots()
+ df.plot("x", "y", c="c", kind="scatter", cmap="cividis", ax=ax)
+ df.plot("x2", "y", c="c", kind="scatter", cmap="magma", ax=ax)
+
+ assert ax.collections[0].cmap.name == "cividis"
+ assert ax.collections[1].cmap.name == "magma"
+
+ def test_line_colors(self):
+ custom_colors = "rgcby"
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+
+ ax = df.plot(color=custom_colors)
+ _check_colors(ax.get_lines(), linecolors=custom_colors)
+
+ plt.close("all")
+
+ ax2 = df.plot(color=custom_colors)
+ lines2 = ax2.get_lines()
+
+ for l1, l2 in zip(ax.get_lines(), lines2):
+ assert l1.get_color() == l2.get_color()
+
+ @pytest.mark.parametrize("colormap", ["jet", cm.jet])
+ def test_line_colors_cmap(self, colormap):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot(colormap=colormap)
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
+ _check_colors(ax.get_lines(), linecolors=rgba_colors)
+
+ def test_line_colors_single_col(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # make color a list if plotting one column frame
+ # handles cases like df.plot(color='DodgerBlue')
+ ax = df.loc[:, [0]].plot(color="DodgerBlue")
+ _check_colors(ax.lines, linecolors=["DodgerBlue"])
+
+ def test_line_colors_single_color(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot(color="red")
+ _check_colors(ax.get_lines(), linecolors=["red"] * 5)
+
+ def test_line_colors_hex(self):
+ # GH 10299
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ custom_colors = ["#FF0000", "#0000FF", "#FFFF00", "#000000", "#FFFFFF"]
+ ax = df.plot(color=custom_colors)
+ _check_colors(ax.get_lines(), linecolors=custom_colors)
+
+ def test_dont_modify_colors(self):
+ colors = ["r", "g", "b"]
+ DataFrame(np.random.default_rng(2).random((10, 2))).plot(color=colors)
+ assert len(colors) == 3
+
+ def test_line_colors_and_styles_subplots(self):
+ # GH 9894
+ default_colors = _unpack_cycler(mpl.pyplot.rcParams)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+
+ axes = df.plot(subplots=True)
+ for ax, c in zip(axes, list(default_colors)):
+ _check_colors(ax.get_lines(), linecolors=[c])
+
+ @pytest.mark.parametrize("color", ["k", "green"])
+ def test_line_colors_and_styles_subplots_single_color_str(self, color):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ axes = df.plot(subplots=True, color=color)
+ for ax in axes:
+ _check_colors(ax.get_lines(), linecolors=[color])
+
+ @pytest.mark.parametrize("color", ["rgcby", list("rgcby")])
+ def test_line_colors_and_styles_subplots_custom_colors(self, color):
+ # GH 9894
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ axes = df.plot(color=color, subplots=True)
+ for ax, c in zip(axes, list(color)):
+ _check_colors(ax.get_lines(), linecolors=[c])
+
+ def test_line_colors_and_styles_subplots_colormap_hex(self):
+ # GH 9894
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # GH 10299
+ custom_colors = ["#FF0000", "#0000FF", "#FFFF00", "#000000", "#FFFFFF"]
+ axes = df.plot(color=custom_colors, subplots=True)
+ for ax, c in zip(axes, list(custom_colors)):
+ _check_colors(ax.get_lines(), linecolors=[c])
+
+ @pytest.mark.parametrize("cmap", ["jet", cm.jet])
+ def test_line_colors_and_styles_subplots_colormap_subplot(self, cmap):
+ # GH 9894
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
+ axes = df.plot(colormap=cmap, subplots=True)
+ for ax, c in zip(axes, rgba_colors):
+ _check_colors(ax.get_lines(), linecolors=[c])
+
+ def test_line_colors_and_styles_subplots_single_col(self):
+ # GH 9894
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # make color a list if plotting one column frame
+ # handles cases like df.plot(color='DodgerBlue')
+ axes = df.loc[:, [0]].plot(color="DodgerBlue", subplots=True)
+ _check_colors(axes[0].lines, linecolors=["DodgerBlue"])
+
+ def test_line_colors_and_styles_subplots_single_char(self):
+ # GH 9894
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # single character style
+ axes = df.plot(style="r", subplots=True)
+ for ax in axes:
+ _check_colors(ax.get_lines(), linecolors=["r"])
+
+ def test_line_colors_and_styles_subplots_list_styles(self):
+ # GH 9894
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # list of styles
+ styles = list("rgcby")
+ axes = df.plot(style=styles, subplots=True)
+ for ax, c in zip(axes, styles):
+ _check_colors(ax.get_lines(), linecolors=[c])
+
+ def test_area_colors(self):
+ from matplotlib.collections import PolyCollection
+
+ custom_colors = "rgcby"
+ df = DataFrame(np.random.default_rng(2).random((5, 5)))
+
+ ax = df.plot.area(color=custom_colors)
+ _check_colors(ax.get_lines(), linecolors=custom_colors)
+ poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
+ _check_colors(poly, facecolors=custom_colors)
+
+ handles, _ = ax.get_legend_handles_labels()
+ _check_colors(handles, facecolors=custom_colors)
+
+ for h in handles:
+ assert h.get_alpha() is None
+
+ def test_area_colors_poly(self):
+ from matplotlib import cm
+ from matplotlib.collections import PolyCollection
+
+ df = DataFrame(np.random.default_rng(2).random((5, 5)))
+ ax = df.plot.area(colormap="jet")
+ jet_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
+ _check_colors(ax.get_lines(), linecolors=jet_colors)
+ poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
+ _check_colors(poly, facecolors=jet_colors)
+
+ handles, _ = ax.get_legend_handles_labels()
+ _check_colors(handles, facecolors=jet_colors)
+ for h in handles:
+ assert h.get_alpha() is None
+
+ def test_area_colors_stacked_false(self):
+ from matplotlib import cm
+ from matplotlib.collections import PolyCollection
+
+ df = DataFrame(np.random.default_rng(2).random((5, 5)))
+ jet_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
+ # When stacked=False, alpha is set to 0.5
+ ax = df.plot.area(colormap=cm.jet, stacked=False)
+ _check_colors(ax.get_lines(), linecolors=jet_colors)
+ poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
+ jet_with_alpha = [(c[0], c[1], c[2], 0.5) for c in jet_colors]
+ _check_colors(poly, facecolors=jet_with_alpha)
+
+ handles, _ = ax.get_legend_handles_labels()
+ linecolors = jet_with_alpha
+ _check_colors(handles[: len(jet_colors)], linecolors=linecolors)
+ for h in handles:
+ assert h.get_alpha() == 0.5
+
+ def test_hist_colors(self):
+ default_colors = _unpack_cycler(mpl.pyplot.rcParams)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot.hist()
+ _check_colors(ax.patches[::10], facecolors=default_colors[:5])
+
+ def test_hist_colors_single_custom(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ custom_colors = "rgcby"
+ ax = df.plot.hist(color=custom_colors)
+ _check_colors(ax.patches[::10], facecolors=custom_colors)
+
+ @pytest.mark.parametrize("colormap", ["jet", cm.jet])
+ def test_hist_colors_cmap(self, colormap):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot.hist(colormap=colormap)
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)]
+ _check_colors(ax.patches[::10], facecolors=rgba_colors)
+
+ def test_hist_colors_single_col(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.loc[:, [0]].plot.hist(color="DodgerBlue")
+ _check_colors([ax.patches[0]], facecolors=["DodgerBlue"])
+
+ def test_hist_colors_single_color(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot(kind="hist", color="green")
+ _check_colors(ax.patches[::10], facecolors=["green"] * 5)
+
+ def test_kde_colors(self):
+ pytest.importorskip("scipy")
+ custom_colors = "rgcby"
+ df = DataFrame(np.random.default_rng(2).random((5, 5)))
+
+ ax = df.plot.kde(color=custom_colors)
+ _check_colors(ax.get_lines(), linecolors=custom_colors)
+
+ @pytest.mark.parametrize("colormap", ["jet", cm.jet])
+ def test_kde_colors_cmap(self, colormap):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot.kde(colormap=colormap)
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
+ _check_colors(ax.get_lines(), linecolors=rgba_colors)
+
+ def test_kde_colors_and_styles_subplots(self):
+ pytest.importorskip("scipy")
+ default_colors = _unpack_cycler(mpl.pyplot.rcParams)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+
+ axes = df.plot(kind="kde", subplots=True)
+ for ax, c in zip(axes, list(default_colors)):
+ _check_colors(ax.get_lines(), linecolors=[c])
+
+ @pytest.mark.parametrize("colormap", ["k", "red"])
+ def test_kde_colors_and_styles_subplots_single_col_str(self, colormap):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ axes = df.plot(kind="kde", color=colormap, subplots=True)
+ for ax in axes:
+ _check_colors(ax.get_lines(), linecolors=[colormap])
+
+ def test_kde_colors_and_styles_subplots_custom_color(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ custom_colors = "rgcby"
+ axes = df.plot(kind="kde", color=custom_colors, subplots=True)
+ for ax, c in zip(axes, list(custom_colors)):
+ _check_colors(ax.get_lines(), linecolors=[c])
+
+ @pytest.mark.parametrize("colormap", ["jet", cm.jet])
+ def test_kde_colors_and_styles_subplots_cmap(self, colormap):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
+ axes = df.plot(kind="kde", colormap=colormap, subplots=True)
+ for ax, c in zip(axes, rgba_colors):
+ _check_colors(ax.get_lines(), linecolors=[c])
+
+ def test_kde_colors_and_styles_subplots_single_col(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # make color a list if plotting one column frame
+ # handles cases like df.plot(color='DodgerBlue')
+ axes = df.loc[:, [0]].plot(kind="kde", color="DodgerBlue", subplots=True)
+ _check_colors(axes[0].lines, linecolors=["DodgerBlue"])
+
+ def test_kde_colors_and_styles_subplots_single_char(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # list of styles
+ # single character style
+ axes = df.plot(kind="kde", style="r", subplots=True)
+ for ax in axes:
+ _check_colors(ax.get_lines(), linecolors=["r"])
+
+ def test_kde_colors_and_styles_subplots_list(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # list of styles
+ styles = list("rgcby")
+ axes = df.plot(kind="kde", style=styles, subplots=True)
+ for ax, c in zip(axes, styles):
+ _check_colors(ax.get_lines(), linecolors=[c])
+
+ def test_boxplot_colors(self):
+ default_colors = _unpack_cycler(mpl.pyplot.rcParams)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ bp = df.plot.box(return_type="dict")
+ _check_colors_box(
+ bp,
+ default_colors[0],
+ default_colors[0],
+ default_colors[2],
+ default_colors[0],
+ )
+
+ def test_boxplot_colors_dict_colors(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ dict_colors = {
+ "boxes": "#572923",
+ "whiskers": "#982042",
+ "medians": "#804823",
+ "caps": "#123456",
+ }
+ bp = df.plot.box(color=dict_colors, sym="r+", return_type="dict")
+ _check_colors_box(
+ bp,
+ dict_colors["boxes"],
+ dict_colors["whiskers"],
+ dict_colors["medians"],
+ dict_colors["caps"],
+ "r",
+ )
+
+ def test_boxplot_colors_default_color(self):
+ default_colors = _unpack_cycler(mpl.pyplot.rcParams)
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # partial colors
+ dict_colors = {"whiskers": "c", "medians": "m"}
+ bp = df.plot.box(color=dict_colors, return_type="dict")
+ _check_colors_box(bp, default_colors[0], "c", "m", default_colors[0])
+
+ @pytest.mark.parametrize("colormap", ["jet", cm.jet])
+ def test_boxplot_colors_cmap(self, colormap):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ bp = df.plot.box(colormap=colormap, return_type="dict")
+ jet_colors = [cm.jet(n) for n in np.linspace(0, 1, 3)]
+ _check_colors_box(
+ bp, jet_colors[0], jet_colors[0], jet_colors[2], jet_colors[0]
+ )
+
+ def test_boxplot_colors_single(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # string color is applied to all artists except fliers
+ bp = df.plot.box(color="DodgerBlue", return_type="dict")
+ _check_colors_box(bp, "DodgerBlue", "DodgerBlue", "DodgerBlue", "DodgerBlue")
+
+ def test_boxplot_colors_tuple(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # tuple is also applied to all artists except fliers
+ bp = df.plot.box(color=(0, 1, 0), sym="#123456", return_type="dict")
+ _check_colors_box(bp, (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), "#123456")
+
+ def test_boxplot_colors_invalid(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ msg = re.escape(
+ "color dict contains invalid key 'xxxx'. The key must be either "
+ "['boxes', 'whiskers', 'medians', 'caps']"
+ )
+ with pytest.raises(ValueError, match=msg):
+ # Color contains invalid key results in ValueError
+ df.plot.box(color={"boxes": "red", "xxxx": "blue"})
+
+ def test_default_color_cycle(self):
+ import cycler
+
+ colors = list("rgbk")
+ plt.rcParams["axes.prop_cycle"] = cycler.cycler("color", colors)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
+ ax = df.plot()
+
+ expected = _unpack_cycler(plt.rcParams)[:3]
+ _check_colors(ax.get_lines(), linecolors=expected)
+
+ def test_no_color_bar(self):
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).uniform(size=20),
+ "B": np.random.default_rng(2).uniform(size=20),
+ "C": np.arange(20) + np.random.default_rng(2).uniform(size=20),
+ }
+ )
+ ax = df.plot.hexbin(x="A", y="B", colorbar=None)
+ assert ax.collections[0].colorbar is None
+
+ def test_mixing_cmap_and_colormap_raises(self):
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).uniform(size=20),
+ "B": np.random.default_rng(2).uniform(size=20),
+ "C": np.arange(20) + np.random.default_rng(2).uniform(size=20),
+ }
+ )
+ msg = "Only specify one of `cmap` and `colormap`"
+ with pytest.raises(TypeError, match=msg):
+ df.plot.hexbin(x="A", y="B", cmap="YlGn", colormap="BuGn")
+
+ def test_passed_bar_colors(self):
+ color_tuples = [(0.9, 0, 0, 1), (0, 0.9, 0, 1), (0, 0, 0.9, 1)]
+ colormap = mpl.colors.ListedColormap(color_tuples)
+ barplot = DataFrame([[1, 2, 3]]).plot(kind="bar", cmap=colormap)
+ assert color_tuples == [c.get_facecolor() for c in barplot.patches]
+
+ def test_rcParams_bar_colors(self):
+ color_tuples = [(0.9, 0, 0, 1), (0, 0.9, 0, 1), (0, 0, 0.9, 1)]
+ with mpl.rc_context(rc={"axes.prop_cycle": mpl.cycler("color", color_tuples)}):
+ barplot = DataFrame([[1, 2, 3]]).plot(kind="bar")
+ assert color_tuples == [c.get_facecolor() for c in barplot.patches]
+
+ def test_colors_of_columns_with_same_name(self):
+ # ISSUE 11136 -> https://github.com/pandas-dev/pandas/issues/11136
+ # Creating a DataFrame with duplicate column labels and testing colors of them.
+ df = DataFrame({"b": [0, 1, 0], "a": [1, 2, 3]})
+ df1 = DataFrame({"a": [2, 4, 6]})
+ df_concat = pd.concat([df, df1], axis=1)
+ result = df_concat.plot()
+ legend = result.get_legend()
+ if Version(mpl.__version__) < Version("3.7"):
+ handles = legend.legendHandles
+ else:
+ handles = legend.legend_handles
+ for legend, line in zip(handles, result.lines):
+ assert legend.get_color() == line.get_color()
+
+ def test_invalid_colormap(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 2)), columns=["A", "B"]
+ )
+ msg = "(is not a valid value)|(is not a known colormap)"
+ with pytest.raises((ValueError, KeyError), match=msg):
+ df.plot(colormap="invalid_colormap")
+
+ def test_dataframe_none_color(self):
+ # GH51953
+ df = DataFrame([[1, 2, 3]])
+ ax = df.plot(color=None)
+ expected = _unpack_cycler(mpl.pyplot.rcParams)[:3]
+ _check_colors(ax.get_lines(), linecolors=expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame_legend.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame_legend.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2924930667b6bd172cb50e34ab077fe7ecaf6ce
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame_legend.py
@@ -0,0 +1,272 @@
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+from pandas import (
+ DataFrame,
+ date_range,
+)
+from pandas.tests.plotting.common import (
+ _check_legend_labels,
+ _check_legend_marker,
+ _check_text_labels,
+)
+from pandas.util.version import Version
+
+mpl = pytest.importorskip("matplotlib")
+
+
+class TestFrameLegend:
+ @pytest.mark.xfail(
+ reason=(
+ "Open bug in matplotlib "
+ "https://github.com/matplotlib/matplotlib/issues/11357"
+ )
+ )
+ def test_mixed_yerr(self):
+ # https://github.com/pandas-dev/pandas/issues/39522
+ from matplotlib.collections import LineCollection
+ from matplotlib.lines import Line2D
+
+ df = DataFrame([{"x": 1, "a": 1, "b": 1}, {"x": 2, "a": 2, "b": 3}])
+
+ ax = df.plot("x", "a", c="orange", yerr=0.1, label="orange")
+ df.plot("x", "b", c="blue", yerr=None, ax=ax, label="blue")
+
+ legend = ax.get_legend()
+ if Version(mpl.__version__) < Version("3.7"):
+ result_handles = legend.legendHandles
+ else:
+ result_handles = legend.legend_handles
+
+ assert isinstance(result_handles[0], LineCollection)
+ assert isinstance(result_handles[1], Line2D)
+
+ def test_legend_false(self):
+ # https://github.com/pandas-dev/pandas/issues/40044
+ df = DataFrame({"a": [1, 1], "b": [2, 3]})
+ df2 = DataFrame({"d": [2.5, 2.5]})
+
+ ax = df.plot(legend=True, color={"a": "blue", "b": "green"}, secondary_y="b")
+ df2.plot(legend=True, color={"d": "red"}, ax=ax)
+ legend = ax.get_legend()
+ if Version(mpl.__version__) < Version("3.7"):
+ handles = legend.legendHandles
+ else:
+ handles = legend.legend_handles
+ result = [handle.get_color() for handle in handles]
+ expected = ["blue", "green", "red"]
+ assert result == expected
+
+ @pytest.mark.parametrize("kind", ["line", "bar", "barh", "kde", "area", "hist"])
+ def test_df_legend_labels(self, kind):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).random((3, 3)), columns=["a", "b", "c"])
+ df2 = DataFrame(
+ np.random.default_rng(2).random((3, 3)), columns=["d", "e", "f"]
+ )
+ df3 = DataFrame(
+ np.random.default_rng(2).random((3, 3)), columns=["g", "h", "i"]
+ )
+ df4 = DataFrame(
+ np.random.default_rng(2).random((3, 3)), columns=["j", "k", "l"]
+ )
+
+ ax = df.plot(kind=kind, legend=True)
+ _check_legend_labels(ax, labels=df.columns)
+
+ ax = df2.plot(kind=kind, legend=False, ax=ax)
+ _check_legend_labels(ax, labels=df.columns)
+
+ ax = df3.plot(kind=kind, legend=True, ax=ax)
+ _check_legend_labels(ax, labels=df.columns.union(df3.columns))
+
+ ax = df4.plot(kind=kind, legend="reverse", ax=ax)
+ expected = list(df.columns.union(df3.columns)) + list(reversed(df4.columns))
+ _check_legend_labels(ax, labels=expected)
+
+ def test_df_legend_labels_secondary_y(self):
+ pytest.importorskip("scipy")
+ df = DataFrame(np.random.default_rng(2).random((3, 3)), columns=["a", "b", "c"])
+ df2 = DataFrame(
+ np.random.default_rng(2).random((3, 3)), columns=["d", "e", "f"]
+ )
+ df3 = DataFrame(
+ np.random.default_rng(2).random((3, 3)), columns=["g", "h", "i"]
+ )
+ # Secondary Y
+ ax = df.plot(legend=True, secondary_y="b")
+ _check_legend_labels(ax, labels=["a", "b (right)", "c"])
+ ax = df2.plot(legend=False, ax=ax)
+ _check_legend_labels(ax, labels=["a", "b (right)", "c"])
+ ax = df3.plot(kind="bar", legend=True, secondary_y="h", ax=ax)
+ _check_legend_labels(ax, labels=["a", "b (right)", "c", "g", "h (right)", "i"])
+
+ def test_df_legend_labels_time_series(self):
+ # Time Series
+ pytest.importorskip("scipy")
+ ind = date_range("1/1/2014", periods=3)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ columns=["a", "b", "c"],
+ index=ind,
+ )
+ df2 = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ columns=["d", "e", "f"],
+ index=ind,
+ )
+ df3 = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ columns=["g", "h", "i"],
+ index=ind,
+ )
+ ax = df.plot(legend=True, secondary_y="b")
+ _check_legend_labels(ax, labels=["a", "b (right)", "c"])
+ ax = df2.plot(legend=False, ax=ax)
+ _check_legend_labels(ax, labels=["a", "b (right)", "c"])
+ ax = df3.plot(legend=True, ax=ax)
+ _check_legend_labels(ax, labels=["a", "b (right)", "c", "g", "h", "i"])
+
+ def test_df_legend_labels_time_series_scatter(self):
+ # Time Series
+ pytest.importorskip("scipy")
+ ind = date_range("1/1/2014", periods=3)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ columns=["a", "b", "c"],
+ index=ind,
+ )
+ df2 = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ columns=["d", "e", "f"],
+ index=ind,
+ )
+ df3 = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ columns=["g", "h", "i"],
+ index=ind,
+ )
+ # scatter
+ ax = df.plot.scatter(x="a", y="b", label="data1")
+ _check_legend_labels(ax, labels=["data1"])
+ ax = df2.plot.scatter(x="d", y="e", legend=False, label="data2", ax=ax)
+ _check_legend_labels(ax, labels=["data1"])
+ ax = df3.plot.scatter(x="g", y="h", label="data3", ax=ax)
+ _check_legend_labels(ax, labels=["data1", "data3"])
+
+ def test_df_legend_labels_time_series_no_mutate(self):
+ pytest.importorskip("scipy")
+ ind = date_range("1/1/2014", periods=3)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 3)),
+ columns=["a", "b", "c"],
+ index=ind,
+ )
+ # ensure label args pass through and
+ # index name does not mutate
+ # column names don't mutate
+ df5 = df.set_index("a")
+ ax = df5.plot(y="b")
+ _check_legend_labels(ax, labels=["b"])
+ ax = df5.plot(y="b", label="LABEL_b")
+ _check_legend_labels(ax, labels=["LABEL_b"])
+ _check_text_labels(ax.xaxis.get_label(), "a")
+ ax = df5.plot(y="c", label="LABEL_c", ax=ax)
+ _check_legend_labels(ax, labels=["LABEL_b", "LABEL_c"])
+ assert df5.columns.tolist() == ["b", "c"]
+
+ def test_missing_marker_multi_plots_on_same_ax(self):
+ # GH 18222
+ df = DataFrame(data=[[1, 1, 1, 1], [2, 2, 4, 8]], columns=["x", "r", "g", "b"])
+ _, ax = mpl.pyplot.subplots(nrows=1, ncols=3)
+ # Left plot
+ df.plot(x="x", y="r", linewidth=0, marker="o", color="r", ax=ax[0])
+ df.plot(x="x", y="g", linewidth=1, marker="x", color="g", ax=ax[0])
+ df.plot(x="x", y="b", linewidth=1, marker="o", color="b", ax=ax[0])
+ _check_legend_labels(ax[0], labels=["r", "g", "b"])
+ _check_legend_marker(ax[0], expected_markers=["o", "x", "o"])
+ # Center plot
+ df.plot(x="x", y="b", linewidth=1, marker="o", color="b", ax=ax[1])
+ df.plot(x="x", y="r", linewidth=0, marker="o", color="r", ax=ax[1])
+ df.plot(x="x", y="g", linewidth=1, marker="x", color="g", ax=ax[1])
+ _check_legend_labels(ax[1], labels=["b", "r", "g"])
+ _check_legend_marker(ax[1], expected_markers=["o", "o", "x"])
+ # Right plot
+ df.plot(x="x", y="g", linewidth=1, marker="x", color="g", ax=ax[2])
+ df.plot(x="x", y="b", linewidth=1, marker="o", color="b", ax=ax[2])
+ df.plot(x="x", y="r", linewidth=0, marker="o", color="r", ax=ax[2])
+ _check_legend_labels(ax[2], labels=["g", "b", "r"])
+ _check_legend_marker(ax[2], expected_markers=["x", "o", "o"])
+
+ def test_legend_name(self):
+ multi = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 4)),
+ columns=[np.array(["a", "a", "b", "b"]), np.array(["x", "y", "x", "y"])],
+ )
+ multi.columns.names = ["group", "individual"]
+
+ ax = multi.plot()
+ leg_title = ax.legend_.get_title()
+ _check_text_labels(leg_title, "group,individual")
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot(legend=True, ax=ax)
+ leg_title = ax.legend_.get_title()
+ _check_text_labels(leg_title, "group,individual")
+
+ df.columns.name = "new"
+ ax = df.plot(legend=False, ax=ax)
+ leg_title = ax.legend_.get_title()
+ _check_text_labels(leg_title, "group,individual")
+
+ ax = df.plot(legend=True, ax=ax)
+ leg_title = ax.legend_.get_title()
+ _check_text_labels(leg_title, "new")
+
+ @pytest.mark.parametrize(
+ "kind",
+ [
+ "line",
+ "bar",
+ "barh",
+ pytest.param("kde", marks=td.skip_if_no_scipy),
+ "area",
+ "hist",
+ ],
+ )
+ def test_no_legend(self, kind):
+ df = DataFrame(np.random.default_rng(2).random((3, 3)), columns=["a", "b", "c"])
+ ax = df.plot(kind=kind, legend=False)
+ _check_legend_labels(ax, visible=False)
+
+ def test_missing_markers_legend(self):
+ # 14958
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((8, 3)), columns=["A", "B", "C"]
+ )
+ ax = df.plot(y=["A"], marker="x", linestyle="solid")
+ df.plot(y=["B"], marker="o", linestyle="dotted", ax=ax)
+ df.plot(y=["C"], marker="<", linestyle="dotted", ax=ax)
+
+ _check_legend_labels(ax, labels=["A", "B", "C"])
+ _check_legend_marker(ax, expected_markers=["x", "o", "<"])
+
+ def test_missing_markers_legend_using_style(self):
+ # 14563
+ df = DataFrame(
+ {
+ "A": [1, 2, 3, 4, 5, 6],
+ "B": [2, 4, 1, 3, 2, 4],
+ "C": [3, 3, 2, 6, 4, 2],
+ "X": [1, 2, 3, 4, 5, 6],
+ }
+ )
+
+ _, ax = mpl.pyplot.subplots()
+ for kind in "ABC":
+ df.plot("X", kind, label=kind, ax=ax, style=".")
+
+ _check_legend_labels(ax, labels=["A", "B", "C"])
+ _check_legend_marker(ax, expected_markers=[".", ".", "."])
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame_subplots.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame_subplots.py
new file mode 100644
index 0000000000000000000000000000000000000000..bce00600f6615ad5d0b459b287962d750191bcf5
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_frame_subplots.py
@@ -0,0 +1,752 @@
+""" Test cases for DataFrame.plot """
+
+import string
+
+import numpy as np
+import pytest
+
+from pandas.compat import is_platform_linux
+from pandas.compat.numpy import np_version_gte1p24
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.tests.plotting.common import (
+ _check_axes_shape,
+ _check_box_return_type,
+ _check_legend_labels,
+ _check_ticks_props,
+ _check_visible,
+ _flatten_visible,
+)
+
+from pandas.io.formats.printing import pprint_thing
+
+mpl = pytest.importorskip("matplotlib")
+plt = pytest.importorskip("matplotlib.pyplot")
+
+
+class TestDataFramePlotsSubplots:
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kind", ["bar", "barh", "line", "area"])
+ def test_subplots(self, kind):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+
+ axes = df.plot(kind=kind, subplots=True, sharex=True, legend=True)
+ _check_axes_shape(axes, axes_num=3, layout=(3, 1))
+ assert axes.shape == (3,)
+
+ for ax, column in zip(axes, df.columns):
+ _check_legend_labels(ax, labels=[pprint_thing(column)])
+
+ for ax in axes[:-2]:
+ _check_visible(ax.xaxis) # xaxis must be visible for grid
+ _check_visible(ax.get_xticklabels(), visible=False)
+ if kind != "bar":
+ # change https://github.com/pandas-dev/pandas/issues/26714
+ _check_visible(ax.get_xticklabels(minor=True), visible=False)
+ _check_visible(ax.xaxis.get_label(), visible=False)
+ _check_visible(ax.get_yticklabels())
+
+ _check_visible(axes[-1].xaxis)
+ _check_visible(axes[-1].get_xticklabels())
+ _check_visible(axes[-1].get_xticklabels(minor=True))
+ _check_visible(axes[-1].xaxis.get_label())
+ _check_visible(axes[-1].get_yticklabels())
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kind", ["bar", "barh", "line", "area"])
+ def test_subplots_no_share_x(self, kind):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+ axes = df.plot(kind=kind, subplots=True, sharex=False)
+ for ax in axes:
+ _check_visible(ax.xaxis)
+ _check_visible(ax.get_xticklabels())
+ _check_visible(ax.get_xticklabels(minor=True))
+ _check_visible(ax.xaxis.get_label())
+ _check_visible(ax.get_yticklabels())
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kind", ["bar", "barh", "line", "area"])
+ def test_subplots_no_legend(self, kind):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+ axes = df.plot(kind=kind, subplots=True, legend=False)
+ for ax in axes:
+ assert ax.get_legend() is None
+
+ @pytest.mark.parametrize("kind", ["line", "area"])
+ def test_subplots_timeseries(self, kind):
+ idx = date_range(start="2014-07-01", freq="M", periods=10)
+ df = DataFrame(np.random.default_rng(2).random((10, 3)), index=idx)
+
+ axes = df.plot(kind=kind, subplots=True, sharex=True)
+ _check_axes_shape(axes, axes_num=3, layout=(3, 1))
+
+ for ax in axes[:-2]:
+ # GH 7801
+ _check_visible(ax.xaxis) # xaxis must be visible for grid
+ _check_visible(ax.get_xticklabels(), visible=False)
+ _check_visible(ax.get_xticklabels(minor=True), visible=False)
+ _check_visible(ax.xaxis.get_label(), visible=False)
+ _check_visible(ax.get_yticklabels())
+
+ _check_visible(axes[-1].xaxis)
+ _check_visible(axes[-1].get_xticklabels())
+ _check_visible(axes[-1].get_xticklabels(minor=True))
+ _check_visible(axes[-1].xaxis.get_label())
+ _check_visible(axes[-1].get_yticklabels())
+ _check_ticks_props(axes, xrot=0)
+
+ @pytest.mark.parametrize("kind", ["line", "area"])
+ def test_subplots_timeseries_rot(self, kind):
+ idx = date_range(start="2014-07-01", freq="M", periods=10)
+ df = DataFrame(np.random.default_rng(2).random((10, 3)), index=idx)
+ axes = df.plot(kind=kind, subplots=True, sharex=False, rot=45, fontsize=7)
+ for ax in axes:
+ _check_visible(ax.xaxis)
+ _check_visible(ax.get_xticklabels())
+ _check_visible(ax.get_xticklabels(minor=True))
+ _check_visible(ax.xaxis.get_label())
+ _check_visible(ax.get_yticklabels())
+ _check_ticks_props(ax, xlabelsize=7, xrot=45, ylabelsize=7)
+
+ @pytest.mark.parametrize(
+ "col", ["numeric", "timedelta", "datetime_no_tz", "datetime_all_tz"]
+ )
+ def test_subplots_timeseries_y_axis(self, col):
+ # GH16953
+ data = {
+ "numeric": np.array([1, 2, 5]),
+ "timedelta": [
+ pd.Timedelta(-10, unit="s"),
+ pd.Timedelta(10, unit="m"),
+ pd.Timedelta(10, unit="h"),
+ ],
+ "datetime_no_tz": [
+ pd.to_datetime("2017-08-01 00:00:00"),
+ pd.to_datetime("2017-08-01 02:00:00"),
+ pd.to_datetime("2017-08-02 00:00:00"),
+ ],
+ "datetime_all_tz": [
+ pd.to_datetime("2017-08-01 00:00:00", utc=True),
+ pd.to_datetime("2017-08-01 02:00:00", utc=True),
+ pd.to_datetime("2017-08-02 00:00:00", utc=True),
+ ],
+ "text": ["This", "should", "fail"],
+ }
+ testdata = DataFrame(data)
+
+ ax = testdata.plot(y=col)
+ result = ax.get_lines()[0].get_data()[1]
+ expected = testdata[col].values
+ assert (result == expected).all()
+
+ def test_subplots_timeseries_y_text_error(self):
+ # GH16953
+ data = {
+ "numeric": np.array([1, 2, 5]),
+ "text": ["This", "should", "fail"],
+ }
+ testdata = DataFrame(data)
+ msg = "no numeric data to plot"
+ with pytest.raises(TypeError, match=msg):
+ testdata.plot(y="text")
+
+ @pytest.mark.xfail(reason="not support for period, categorical, datetime_mixed_tz")
+ def test_subplots_timeseries_y_axis_not_supported(self):
+ """
+ This test will fail for:
+ period:
+ since period isn't yet implemented in ``select_dtypes``
+ and because it will need a custom value converter +
+ tick formatter (as was done for x-axis plots)
+
+ categorical:
+ because it will need a custom value converter +
+ tick formatter (also doesn't work for x-axis, as of now)
+
+ datetime_mixed_tz:
+ because of the way how pandas handles ``Series`` of
+ ``datetime`` objects with different timezone,
+ generally converting ``datetime`` objects in a tz-aware
+ form could help with this problem
+ """
+ data = {
+ "numeric": np.array([1, 2, 5]),
+ "period": [
+ pd.Period("2017-08-01 00:00:00", freq="H"),
+ pd.Period("2017-08-01 02:00", freq="H"),
+ pd.Period("2017-08-02 00:00:00", freq="H"),
+ ],
+ "categorical": pd.Categorical(
+ ["c", "b", "a"], categories=["a", "b", "c"], ordered=False
+ ),
+ "datetime_mixed_tz": [
+ pd.to_datetime("2017-08-01 00:00:00", utc=True),
+ pd.to_datetime("2017-08-01 02:00:00"),
+ pd.to_datetime("2017-08-02 00:00:00"),
+ ],
+ }
+ testdata = DataFrame(data)
+ ax_period = testdata.plot(x="numeric", y="period")
+ assert (
+ ax_period.get_lines()[0].get_data()[1] == testdata["period"].values
+ ).all()
+ ax_categorical = testdata.plot(x="numeric", y="categorical")
+ assert (
+ ax_categorical.get_lines()[0].get_data()[1]
+ == testdata["categorical"].values
+ ).all()
+ ax_datetime_mixed_tz = testdata.plot(x="numeric", y="datetime_mixed_tz")
+ assert (
+ ax_datetime_mixed_tz.get_lines()[0].get_data()[1]
+ == testdata["datetime_mixed_tz"].values
+ ).all()
+
+ @pytest.mark.parametrize(
+ "layout, exp_layout",
+ [
+ [(2, 2), (2, 2)],
+ [(-1, 2), (2, 2)],
+ [(2, -1), (2, 2)],
+ [(1, 4), (1, 4)],
+ [(-1, 4), (1, 4)],
+ [(4, -1), (4, 1)],
+ ],
+ )
+ def test_subplots_layout_multi_column(self, layout, exp_layout):
+ # GH 6667
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+
+ axes = df.plot(subplots=True, layout=layout)
+ _check_axes_shape(axes, axes_num=3, layout=exp_layout)
+ assert axes.shape == exp_layout
+
+ def test_subplots_layout_multi_column_error(self):
+ # GH 6667
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+ msg = "Layout of 1x1 must be larger than required size 3"
+
+ with pytest.raises(ValueError, match=msg):
+ df.plot(subplots=True, layout=(1, 1))
+
+ msg = "At least one dimension of layout must be positive"
+ with pytest.raises(ValueError, match=msg):
+ df.plot(subplots=True, layout=(-1, -1))
+
+ @pytest.mark.parametrize(
+ "kwargs, expected_axes_num, expected_layout, expected_shape",
+ [
+ ({}, 1, (1, 1), (1,)),
+ ({"layout": (3, 3)}, 1, (3, 3), (3, 3)),
+ ],
+ )
+ def test_subplots_layout_single_column(
+ self, kwargs, expected_axes_num, expected_layout, expected_shape
+ ):
+ # GH 6667
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 1)),
+ index=list(string.ascii_letters[:10]),
+ )
+ axes = df.plot(subplots=True, **kwargs)
+ _check_axes_shape(
+ axes,
+ axes_num=expected_axes_num,
+ layout=expected_layout,
+ )
+ assert axes.shape == expected_shape
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("idx", [range(5), date_range("1/1/2000", periods=5)])
+ def test_subplots_warnings(self, idx):
+ # GH 9464
+ with tm.assert_produces_warning(None):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 4)), index=idx)
+ df.plot(subplots=True, layout=(3, 2))
+
+ def test_subplots_multiple_axes(self):
+ # GH 5353, 6970, GH 7069
+ fig, axes = mpl.pyplot.subplots(2, 3)
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+
+ returned = df.plot(subplots=True, ax=axes[0], sharex=False, sharey=False)
+ _check_axes_shape(returned, axes_num=3, layout=(1, 3))
+ assert returned.shape == (3,)
+ assert returned[0].figure is fig
+ # draw on second row
+ returned = df.plot(subplots=True, ax=axes[1], sharex=False, sharey=False)
+ _check_axes_shape(returned, axes_num=3, layout=(1, 3))
+ assert returned.shape == (3,)
+ assert returned[0].figure is fig
+ _check_axes_shape(axes, axes_num=6, layout=(2, 3))
+
+ def test_subplots_multiple_axes_error(self):
+ # GH 5353, 6970, GH 7069
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=list(string.ascii_letters[:10]),
+ )
+ msg = "The number of passed axes must be 3, the same as the output plot"
+ _, axes = mpl.pyplot.subplots(2, 3)
+
+ with pytest.raises(ValueError, match=msg):
+ # pass different number of axes from required
+ df.plot(subplots=True, ax=axes)
+
+ @pytest.mark.parametrize(
+ "layout, exp_layout",
+ [
+ [(2, 1), (2, 2)],
+ [(2, -1), (2, 2)],
+ [(-1, 2), (2, 2)],
+ ],
+ )
+ def test_subplots_multiple_axes_2_dim(self, layout, exp_layout):
+ # GH 5353, 6970, GH 7069
+ # pass 2-dim axes and invalid layout
+ # invalid lauout should not affect to input and return value
+ # (show warning is tested in
+ # TestDataFrameGroupByPlots.test_grouped_box_multiple_axes
+ _, axes = mpl.pyplot.subplots(2, 2)
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 4)),
+ index=list(string.ascii_letters[:10]),
+ )
+ with tm.assert_produces_warning(UserWarning):
+ returned = df.plot(
+ subplots=True, ax=axes, layout=layout, sharex=False, sharey=False
+ )
+ _check_axes_shape(returned, axes_num=4, layout=exp_layout)
+ assert returned.shape == (4,)
+
+ def test_subplots_multiple_axes_single_col(self):
+ # GH 5353, 6970, GH 7069
+ # single column
+ _, axes = mpl.pyplot.subplots(1, 1)
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 1)),
+ index=list(string.ascii_letters[:10]),
+ )
+
+ axes = df.plot(subplots=True, ax=[axes], sharex=False, sharey=False)
+ _check_axes_shape(axes, axes_num=1, layout=(1, 1))
+ assert axes.shape == (1,)
+
+ def test_subplots_ts_share_axes(self):
+ # GH 3964
+ _, axes = mpl.pyplot.subplots(3, 3, sharex=True, sharey=True)
+ mpl.pyplot.subplots_adjust(left=0.05, right=0.95, hspace=0.3, wspace=0.3)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 9)),
+ index=date_range(start="2014-07-01", freq="M", periods=10),
+ )
+ for i, ax in enumerate(axes.ravel()):
+ df[i].plot(ax=ax, fontsize=5)
+
+ # Rows other than bottom should not be visible
+ for ax in axes[0:-1].ravel():
+ _check_visible(ax.get_xticklabels(), visible=False)
+
+ # Bottom row should be visible
+ for ax in axes[-1].ravel():
+ _check_visible(ax.get_xticklabels(), visible=True)
+
+ # First column should be visible
+ for ax in axes[[0, 1, 2], [0]].ravel():
+ _check_visible(ax.get_yticklabels(), visible=True)
+
+ # Other columns should not be visible
+ for ax in axes[[0, 1, 2], [1]].ravel():
+ _check_visible(ax.get_yticklabels(), visible=False)
+ for ax in axes[[0, 1, 2], [2]].ravel():
+ _check_visible(ax.get_yticklabels(), visible=False)
+
+ def test_subplots_sharex_axes_existing_axes(self):
+ # GH 9158
+ d = {"A": [1.0, 2.0, 3.0, 4.0], "B": [4.0, 3.0, 2.0, 1.0], "C": [5, 1, 3, 4]}
+ df = DataFrame(d, index=date_range("2014 10 11", "2014 10 14"))
+
+ axes = df[["A", "B"]].plot(subplots=True)
+ df["C"].plot(ax=axes[0], secondary_y=True)
+
+ _check_visible(axes[0].get_xticklabels(), visible=False)
+ _check_visible(axes[1].get_xticklabels(), visible=True)
+ for ax in axes.ravel():
+ _check_visible(ax.get_yticklabels(), visible=True)
+
+ def test_subplots_dup_columns(self):
+ # GH 10962
+ df = DataFrame(np.random.default_rng(2).random((5, 5)), columns=list("aaaaa"))
+ axes = df.plot(subplots=True)
+ for ax in axes:
+ _check_legend_labels(ax, labels=["a"])
+ assert len(ax.lines) == 1
+
+ def test_subplots_dup_columns_secondary_y(self):
+ # GH 10962
+ df = DataFrame(np.random.default_rng(2).random((5, 5)), columns=list("aaaaa"))
+ axes = df.plot(subplots=True, secondary_y="a")
+ for ax in axes:
+ # (right) is only attached when subplots=False
+ _check_legend_labels(ax, labels=["a"])
+ assert len(ax.lines) == 1
+
+ def test_subplots_dup_columns_secondary_y_no_subplot(self):
+ # GH 10962
+ df = DataFrame(np.random.default_rng(2).random((5, 5)), columns=list("aaaaa"))
+ ax = df.plot(secondary_y="a")
+ _check_legend_labels(ax, labels=["a (right)"] * 5)
+ assert len(ax.lines) == 0
+ assert len(ax.right_ax.lines) == 5
+
+ @pytest.mark.xfail(
+ np_version_gte1p24 and is_platform_linux(),
+ reason="Weird rounding problems",
+ strict=False,
+ )
+ def test_bar_log_no_subplots(self):
+ # GH3254, GH3298 matplotlib/matplotlib#1882, #1892
+ # regressions in 1.2.1
+ expected = np.array([0.1, 1.0, 10.0, 100])
+
+ # no subplots
+ df = DataFrame({"A": [3] * 5, "B": list(range(1, 6))}, index=range(5))
+ ax = df.plot.bar(grid=True, log=True)
+ tm.assert_numpy_array_equal(ax.yaxis.get_ticklocs(), expected)
+
+ @pytest.mark.xfail(
+ np_version_gte1p24 and is_platform_linux(),
+ reason="Weird rounding problems",
+ strict=False,
+ )
+ def test_bar_log_subplots(self):
+ expected = np.array([0.1, 1.0, 10.0, 100.0, 1000.0, 1e4])
+
+ ax = DataFrame([Series([200, 300]), Series([300, 500])]).plot.bar(
+ log=True, subplots=True
+ )
+
+ tm.assert_numpy_array_equal(ax[0].yaxis.get_ticklocs(), expected)
+ tm.assert_numpy_array_equal(ax[1].yaxis.get_ticklocs(), expected)
+
+ def test_boxplot_subplots_return_type_default(self, hist_df):
+ df = hist_df
+
+ # normal style: return_type=None
+ result = df.plot.box(subplots=True)
+ assert isinstance(result, Series)
+ _check_box_return_type(
+ result, None, expected_keys=["height", "weight", "category"]
+ )
+
+ @pytest.mark.parametrize("rt", ["dict", "axes", "both"])
+ def test_boxplot_subplots_return_type(self, hist_df, rt):
+ df = hist_df
+ returned = df.plot.box(return_type=rt, subplots=True)
+ _check_box_return_type(
+ returned,
+ rt,
+ expected_keys=["height", "weight", "category"],
+ check_ax_title=False,
+ )
+
+ def test_df_subplots_patterns_minorticks(self):
+ # GH 10657
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)),
+ index=date_range("1/1/2000", periods=10),
+ columns=list("AB"),
+ )
+
+ # shared subplots
+ _, axes = plt.subplots(2, 1, sharex=True)
+ axes = df.plot(subplots=True, ax=axes)
+ for ax in axes:
+ assert len(ax.lines) == 1
+ _check_visible(ax.get_yticklabels(), visible=True)
+ # xaxis of 1st ax must be hidden
+ _check_visible(axes[0].get_xticklabels(), visible=False)
+ _check_visible(axes[0].get_xticklabels(minor=True), visible=False)
+ _check_visible(axes[1].get_xticklabels(), visible=True)
+ _check_visible(axes[1].get_xticklabels(minor=True), visible=True)
+
+ def test_df_subplots_patterns_minorticks_1st_ax_hidden(self):
+ # GH 10657
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)),
+ index=date_range("1/1/2000", periods=10),
+ columns=list("AB"),
+ )
+ _, axes = plt.subplots(2, 1)
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.plot(subplots=True, ax=axes, sharex=True)
+ for ax in axes:
+ assert len(ax.lines) == 1
+ _check_visible(ax.get_yticklabels(), visible=True)
+ # xaxis of 1st ax must be hidden
+ _check_visible(axes[0].get_xticklabels(), visible=False)
+ _check_visible(axes[0].get_xticklabels(minor=True), visible=False)
+ _check_visible(axes[1].get_xticklabels(), visible=True)
+ _check_visible(axes[1].get_xticklabels(minor=True), visible=True)
+
+ def test_df_subplots_patterns_minorticks_not_shared(self):
+ # GH 10657
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 2)),
+ index=date_range("1/1/2000", periods=10),
+ columns=list("AB"),
+ )
+ # not shared
+ _, axes = plt.subplots(2, 1)
+ axes = df.plot(subplots=True, ax=axes)
+ for ax in axes:
+ assert len(ax.lines) == 1
+ _check_visible(ax.get_yticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(), visible=True)
+ _check_visible(ax.get_xticklabels(minor=True), visible=True)
+
+ def test_subplots_sharex_false(self):
+ # test when sharex is set to False, two plots should have different
+ # labels, GH 25160
+ df = DataFrame(np.random.default_rng(2).random((10, 2)))
+ df.iloc[5:, 1] = np.nan
+ df.iloc[:5, 0] = np.nan
+
+ _, axs = mpl.pyplot.subplots(2, 1)
+ df.plot.line(ax=axs, subplots=True, sharex=False)
+
+ expected_ax1 = np.arange(4.5, 10, 0.5)
+ expected_ax2 = np.arange(-0.5, 5, 0.5)
+
+ tm.assert_numpy_array_equal(axs[0].get_xticks(), expected_ax1)
+ tm.assert_numpy_array_equal(axs[1].get_xticks(), expected_ax2)
+
+ def test_subplots_constrained_layout(self):
+ # GH 25261
+ idx = date_range(start="now", periods=10)
+ df = DataFrame(np.random.default_rng(2).random((10, 3)), index=idx)
+ kwargs = {}
+ if hasattr(mpl.pyplot.Figure, "get_constrained_layout"):
+ kwargs["constrained_layout"] = True
+ _, axes = mpl.pyplot.subplots(2, **kwargs)
+ with tm.assert_produces_warning(None):
+ df.plot(ax=axes[0])
+ with tm.ensure_clean(return_filelike=True) as path:
+ mpl.pyplot.savefig(path)
+
+ @pytest.mark.parametrize(
+ "index_name, old_label, new_label",
+ [
+ (None, "", "new"),
+ ("old", "old", "new"),
+ (None, "", ""),
+ (None, "", 1),
+ (None, "", [1, 2]),
+ ],
+ )
+ @pytest.mark.parametrize("kind", ["line", "area", "bar"])
+ def test_xlabel_ylabel_dataframe_subplots(
+ self, kind, index_name, old_label, new_label
+ ):
+ # GH 9093
+ df = DataFrame([[1, 2], [2, 5]], columns=["Type A", "Type B"])
+ df.index.name = index_name
+
+ # default is the ylabel is not shown and xlabel is index name
+ axes = df.plot(kind=kind, subplots=True)
+ assert all(ax.get_ylabel() == "" for ax in axes)
+ assert all(ax.get_xlabel() == old_label for ax in axes)
+
+ # old xlabel will be overridden and assigned ylabel will be used as ylabel
+ axes = df.plot(kind=kind, ylabel=new_label, xlabel=new_label, subplots=True)
+ assert all(ax.get_ylabel() == str(new_label) for ax in axes)
+ assert all(ax.get_xlabel() == str(new_label) for ax in axes)
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ # stacked center
+ {"kind": "bar", "stacked": True},
+ {"kind": "bar", "stacked": True, "width": 0.9},
+ {"kind": "barh", "stacked": True},
+ {"kind": "barh", "stacked": True, "width": 0.9},
+ # center
+ {"kind": "bar", "stacked": False},
+ {"kind": "bar", "stacked": False, "width": 0.9},
+ {"kind": "barh", "stacked": False},
+ {"kind": "barh", "stacked": False, "width": 0.9},
+ # subplots center
+ {"kind": "bar", "subplots": True},
+ {"kind": "bar", "subplots": True, "width": 0.9},
+ {"kind": "barh", "subplots": True},
+ {"kind": "barh", "subplots": True, "width": 0.9},
+ # align edge
+ {"kind": "bar", "stacked": True, "align": "edge"},
+ {"kind": "bar", "stacked": True, "width": 0.9, "align": "edge"},
+ {"kind": "barh", "stacked": True, "align": "edge"},
+ {"kind": "barh", "stacked": True, "width": 0.9, "align": "edge"},
+ {"kind": "bar", "stacked": False, "align": "edge"},
+ {"kind": "bar", "stacked": False, "width": 0.9, "align": "edge"},
+ {"kind": "barh", "stacked": False, "align": "edge"},
+ {"kind": "barh", "stacked": False, "width": 0.9, "align": "edge"},
+ {"kind": "bar", "subplots": True, "align": "edge"},
+ {"kind": "bar", "subplots": True, "width": 0.9, "align": "edge"},
+ {"kind": "barh", "subplots": True, "align": "edge"},
+ {"kind": "barh", "subplots": True, "width": 0.9, "align": "edge"},
+ ],
+ )
+ def test_bar_align_multiple_columns(self, kwargs):
+ # GH2157
+ df = DataFrame({"A": [3] * 5, "B": list(range(5))}, index=range(5))
+ self._check_bar_alignment(df, **kwargs)
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"kind": "bar", "stacked": False},
+ {"kind": "bar", "stacked": True},
+ {"kind": "barh", "stacked": False},
+ {"kind": "barh", "stacked": True},
+ {"kind": "bar", "subplots": True},
+ {"kind": "barh", "subplots": True},
+ ],
+ )
+ def test_bar_align_single_column(self, kwargs):
+ df = DataFrame(np.random.default_rng(2).standard_normal(5))
+ self._check_bar_alignment(df, **kwargs)
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"kind": "bar", "stacked": False},
+ {"kind": "bar", "stacked": True},
+ {"kind": "barh", "stacked": False},
+ {"kind": "barh", "stacked": True},
+ {"kind": "bar", "subplots": True},
+ {"kind": "barh", "subplots": True},
+ ],
+ )
+ def test_bar_barwidth_position(self, kwargs):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ self._check_bar_alignment(df, width=0.9, position=0.2, **kwargs)
+
+ @pytest.mark.parametrize("w", [1, 1.0])
+ def test_bar_barwidth_position_int(self, w):
+ # GH 12979
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ ax = df.plot.bar(stacked=True, width=w)
+ ticks = ax.xaxis.get_ticklocs()
+ tm.assert_numpy_array_equal(ticks, np.array([0, 1, 2, 3, 4]))
+ assert ax.get_xlim() == (-0.75, 4.75)
+ # check left-edge of bars
+ assert ax.patches[0].get_x() == -0.5
+ assert ax.patches[-1].get_x() == 3.5
+
+ @pytest.mark.parametrize(
+ "kind, kwargs",
+ [
+ ["bar", {"stacked": True}],
+ ["barh", {"stacked": False}],
+ ["barh", {"stacked": True}],
+ ["bar", {"subplots": True}],
+ ["barh", {"subplots": True}],
+ ],
+ )
+ def test_bar_barwidth_position_int_width_1(self, kind, kwargs):
+ # GH 12979
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ self._check_bar_alignment(df, kind=kind, width=1, **kwargs)
+
+ def _check_bar_alignment(
+ self,
+ df,
+ kind="bar",
+ stacked=False,
+ subplots=False,
+ align="center",
+ width=0.5,
+ position=0.5,
+ ):
+ axes = df.plot(
+ kind=kind,
+ stacked=stacked,
+ subplots=subplots,
+ align=align,
+ width=width,
+ position=position,
+ grid=True,
+ )
+
+ axes = _flatten_visible(axes)
+
+ for ax in axes:
+ if kind == "bar":
+ axis = ax.xaxis
+ ax_min, ax_max = ax.get_xlim()
+ min_edge = min(p.get_x() for p in ax.patches)
+ max_edge = max(p.get_x() + p.get_width() for p in ax.patches)
+ elif kind == "barh":
+ axis = ax.yaxis
+ ax_min, ax_max = ax.get_ylim()
+ min_edge = min(p.get_y() for p in ax.patches)
+ max_edge = max(p.get_y() + p.get_height() for p in ax.patches)
+ else:
+ raise ValueError
+
+ # GH 7498
+ # compare margins between lim and bar edges
+ tm.assert_almost_equal(ax_min, min_edge - 0.25)
+ tm.assert_almost_equal(ax_max, max_edge + 0.25)
+
+ p = ax.patches[0]
+ if kind == "bar" and (stacked is True or subplots is True):
+ edge = p.get_x()
+ center = edge + p.get_width() * position
+ elif kind == "bar" and stacked is False:
+ center = p.get_x() + p.get_width() * len(df.columns) * position
+ edge = p.get_x()
+ elif kind == "barh" and (stacked is True or subplots is True):
+ center = p.get_y() + p.get_height() * position
+ edge = p.get_y()
+ elif kind == "barh" and stacked is False:
+ center = p.get_y() + p.get_height() * len(df.columns) * position
+ edge = p.get_y()
+ else:
+ raise ValueError
+
+ # Check the ticks locates on integer
+ assert (axis.get_ticklocs() == np.arange(len(df))).all()
+
+ if align == "center":
+ # Check whether the bar locates on center
+ tm.assert_almost_equal(axis.get_ticklocs()[0], center)
+ elif align == "edge":
+ # Check whether the bar's edge starts from the tick
+ tm.assert_almost_equal(axis.get_ticklocs()[0], edge)
+ else:
+ raise ValueError
+
+ return axes
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_hist_box_by.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_hist_box_by.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9250fa8347cc04fa34c28b016e1fb27d837284f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/frame/test_hist_box_by.py
@@ -0,0 +1,342 @@
+import re
+
+import numpy as np
+import pytest
+
+from pandas import DataFrame
+import pandas._testing as tm
+from pandas.tests.plotting.common import (
+ _check_axes_shape,
+ _check_plot_works,
+ get_x_axis,
+ get_y_axis,
+)
+
+pytest.importorskip("matplotlib")
+
+
+@pytest.fixture
+def hist_df():
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 2)), columns=["A", "B"]
+ )
+ df["C"] = np.random.default_rng(2).choice(["a", "b", "c"], 30)
+ df["D"] = np.random.default_rng(2).choice(["a", "b", "c"], 30)
+ return df
+
+
+class TestHistWithBy:
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "by, column, titles, legends",
+ [
+ ("C", "A", ["a", "b", "c"], [["A"]] * 3),
+ ("C", ["A", "B"], ["a", "b", "c"], [["A", "B"]] * 3),
+ ("C", None, ["a", "b", "c"], [["A", "B"]] * 3),
+ (
+ ["C", "D"],
+ "A",
+ [
+ "(a, a)",
+ "(b, b)",
+ "(c, c)",
+ ],
+ [["A"]] * 3,
+ ),
+ (
+ ["C", "D"],
+ ["A", "B"],
+ [
+ "(a, a)",
+ "(b, b)",
+ "(c, c)",
+ ],
+ [["A", "B"]] * 3,
+ ),
+ (
+ ["C", "D"],
+ None,
+ [
+ "(a, a)",
+ "(b, b)",
+ "(c, c)",
+ ],
+ [["A", "B"]] * 3,
+ ),
+ ],
+ )
+ def test_hist_plot_by_argument(self, by, column, titles, legends, hist_df):
+ # GH 15079
+ axes = _check_plot_works(
+ hist_df.plot.hist, column=column, by=by, default_axes=True
+ )
+ result_titles = [ax.get_title() for ax in axes]
+ result_legends = [
+ [legend.get_text() for legend in ax.get_legend().texts] for ax in axes
+ ]
+
+ assert result_legends == legends
+ assert result_titles == titles
+
+ @pytest.mark.parametrize(
+ "by, column, titles, legends",
+ [
+ (0, "A", ["a", "b", "c"], [["A"]] * 3),
+ (0, None, ["a", "b", "c"], [["A", "B"]] * 3),
+ (
+ [0, "D"],
+ "A",
+ [
+ "(a, a)",
+ "(b, b)",
+ "(c, c)",
+ ],
+ [["A"]] * 3,
+ ),
+ ],
+ )
+ def test_hist_plot_by_0(self, by, column, titles, legends, hist_df):
+ # GH 15079
+ df = hist_df.copy()
+ df = df.rename(columns={"C": 0})
+
+ axes = _check_plot_works(df.plot.hist, default_axes=True, column=column, by=by)
+ result_titles = [ax.get_title() for ax in axes]
+ result_legends = [
+ [legend.get_text() for legend in ax.get_legend().texts] for ax in axes
+ ]
+
+ assert result_legends == legends
+ assert result_titles == titles
+
+ @pytest.mark.parametrize(
+ "by, column",
+ [
+ ([], ["A"]),
+ ([], ["A", "B"]),
+ ((), None),
+ ((), ["A", "B"]),
+ ],
+ )
+ def test_hist_plot_empty_list_string_tuple_by(self, by, column, hist_df):
+ # GH 15079
+ msg = "No group keys passed"
+ with pytest.raises(ValueError, match=msg):
+ _check_plot_works(
+ hist_df.plot.hist, default_axes=True, column=column, by=by
+ )
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "by, column, layout, axes_num",
+ [
+ (["C"], "A", (2, 2), 3),
+ ("C", "A", (2, 2), 3),
+ (["C"], ["A"], (1, 3), 3),
+ ("C", None, (3, 1), 3),
+ ("C", ["A", "B"], (3, 1), 3),
+ (["C", "D"], "A", (9, 1), 3),
+ (["C", "D"], "A", (3, 3), 3),
+ (["C", "D"], ["A"], (5, 2), 3),
+ (["C", "D"], ["A", "B"], (9, 1), 3),
+ (["C", "D"], None, (9, 1), 3),
+ (["C", "D"], ["A", "B"], (5, 2), 3),
+ ],
+ )
+ def test_hist_plot_layout_with_by(self, by, column, layout, axes_num, hist_df):
+ # GH 15079
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(
+ hist_df.plot.hist, column=column, by=by, layout=layout
+ )
+ _check_axes_shape(axes, axes_num=axes_num, layout=layout)
+
+ @pytest.mark.parametrize(
+ "msg, by, layout",
+ [
+ ("larger than required size", ["C", "D"], (1, 1)),
+ (re.escape("Layout must be a tuple of (rows, columns)"), "C", (1,)),
+ ("At least one dimension of layout must be positive", "C", (-1, -1)),
+ ],
+ )
+ def test_hist_plot_invalid_layout_with_by_raises(self, msg, by, layout, hist_df):
+ # GH 15079, test if error is raised when invalid layout is given
+
+ with pytest.raises(ValueError, match=msg):
+ hist_df.plot.hist(column=["A", "B"], by=by, layout=layout)
+
+ @pytest.mark.slow
+ def test_axis_share_x_with_by(self, hist_df):
+ # GH 15079
+ ax1, ax2, ax3 = hist_df.plot.hist(column="A", by="C", sharex=True)
+
+ # share x
+ assert get_x_axis(ax1).joined(ax1, ax2)
+ assert get_x_axis(ax2).joined(ax1, ax2)
+ assert get_x_axis(ax3).joined(ax1, ax3)
+ assert get_x_axis(ax3).joined(ax2, ax3)
+
+ # don't share y
+ assert not get_y_axis(ax1).joined(ax1, ax2)
+ assert not get_y_axis(ax2).joined(ax1, ax2)
+ assert not get_y_axis(ax3).joined(ax1, ax3)
+ assert not get_y_axis(ax3).joined(ax2, ax3)
+
+ @pytest.mark.slow
+ def test_axis_share_y_with_by(self, hist_df):
+ # GH 15079
+ ax1, ax2, ax3 = hist_df.plot.hist(column="A", by="C", sharey=True)
+
+ # share y
+ assert get_y_axis(ax1).joined(ax1, ax2)
+ assert get_y_axis(ax2).joined(ax1, ax2)
+ assert get_y_axis(ax3).joined(ax1, ax3)
+ assert get_y_axis(ax3).joined(ax2, ax3)
+
+ # don't share x
+ assert not get_x_axis(ax1).joined(ax1, ax2)
+ assert not get_x_axis(ax2).joined(ax1, ax2)
+ assert not get_x_axis(ax3).joined(ax1, ax3)
+ assert not get_x_axis(ax3).joined(ax2, ax3)
+
+ @pytest.mark.parametrize("figsize", [(12, 8), (20, 10)])
+ def test_figure_shape_hist_with_by(self, figsize, hist_df):
+ # GH 15079
+ axes = hist_df.plot.hist(column="A", by="C", figsize=figsize)
+ _check_axes_shape(axes, axes_num=3, figsize=figsize)
+
+
+class TestBoxWithBy:
+ @pytest.mark.parametrize(
+ "by, column, titles, xticklabels",
+ [
+ ("C", "A", ["A"], [["a", "b", "c"]]),
+ (
+ ["C", "D"],
+ "A",
+ ["A"],
+ [
+ [
+ "(a, a)",
+ "(b, b)",
+ "(c, c)",
+ ]
+ ],
+ ),
+ ("C", ["A", "B"], ["A", "B"], [["a", "b", "c"]] * 2),
+ (
+ ["C", "D"],
+ ["A", "B"],
+ ["A", "B"],
+ [
+ [
+ "(a, a)",
+ "(b, b)",
+ "(c, c)",
+ ]
+ ]
+ * 2,
+ ),
+ (["C"], None, ["A", "B"], [["a", "b", "c"]] * 2),
+ ],
+ )
+ def test_box_plot_by_argument(self, by, column, titles, xticklabels, hist_df):
+ # GH 15079
+ axes = _check_plot_works(
+ hist_df.plot.box, default_axes=True, column=column, by=by
+ )
+ result_titles = [ax.get_title() for ax in axes]
+ result_xticklabels = [
+ [label.get_text() for label in ax.get_xticklabels()] for ax in axes
+ ]
+
+ assert result_xticklabels == xticklabels
+ assert result_titles == titles
+
+ @pytest.mark.parametrize(
+ "by, column, titles, xticklabels",
+ [
+ (0, "A", ["A"], [["a", "b", "c"]]),
+ (
+ [0, "D"],
+ "A",
+ ["A"],
+ [
+ [
+ "(a, a)",
+ "(b, b)",
+ "(c, c)",
+ ]
+ ],
+ ),
+ (0, None, ["A", "B"], [["a", "b", "c"]] * 2),
+ ],
+ )
+ def test_box_plot_by_0(self, by, column, titles, xticklabels, hist_df):
+ # GH 15079
+ df = hist_df.copy()
+ df = df.rename(columns={"C": 0})
+
+ axes = _check_plot_works(df.plot.box, default_axes=True, column=column, by=by)
+ result_titles = [ax.get_title() for ax in axes]
+ result_xticklabels = [
+ [label.get_text() for label in ax.get_xticklabels()] for ax in axes
+ ]
+
+ assert result_xticklabels == xticklabels
+ assert result_titles == titles
+
+ @pytest.mark.parametrize(
+ "by, column",
+ [
+ ([], ["A"]),
+ ((), "A"),
+ ([], None),
+ ((), ["A", "B"]),
+ ],
+ )
+ def test_box_plot_with_none_empty_list_by(self, by, column, hist_df):
+ # GH 15079
+ msg = "No group keys passed"
+ with pytest.raises(ValueError, match=msg):
+ _check_plot_works(hist_df.plot.box, default_axes=True, column=column, by=by)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "by, column, layout, axes_num",
+ [
+ (["C"], "A", (1, 1), 1),
+ ("C", "A", (1, 1), 1),
+ ("C", None, (2, 1), 2),
+ ("C", ["A", "B"], (1, 2), 2),
+ (["C", "D"], "A", (1, 1), 1),
+ (["C", "D"], None, (1, 2), 2),
+ ],
+ )
+ def test_box_plot_layout_with_by(self, by, column, layout, axes_num, hist_df):
+ # GH 15079
+ axes = _check_plot_works(
+ hist_df.plot.box, default_axes=True, column=column, by=by, layout=layout
+ )
+ _check_axes_shape(axes, axes_num=axes_num, layout=layout)
+
+ @pytest.mark.parametrize(
+ "msg, by, layout",
+ [
+ ("larger than required size", ["C", "D"], (1, 1)),
+ (re.escape("Layout must be a tuple of (rows, columns)"), "C", (1,)),
+ ("At least one dimension of layout must be positive", "C", (-1, -1)),
+ ],
+ )
+ def test_box_plot_invalid_layout_with_by_raises(self, msg, by, layout, hist_df):
+ # GH 15079, test if error is raised when invalid layout is given
+
+ with pytest.raises(ValueError, match=msg):
+ hist_df.plot.box(column=["A", "B"], by=by, layout=layout)
+
+ @pytest.mark.parametrize("figsize", [(12, 8), (20, 10)])
+ def test_figure_shape_hist_with_by(self, figsize, hist_df):
+ # GH 15079
+ axes = hist_df.plot.box(column="A", by="C", figsize=figsize)
+ _check_axes_shape(axes, axes_num=1, figsize=figsize)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_backend.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0ad8e0c9608d3d04723f472a5956d3e366ffcac
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_backend.py
@@ -0,0 +1,98 @@
+import sys
+import types
+
+import pytest
+
+import pandas.util._test_decorators as td
+
+import pandas
+
+
+@pytest.fixture
+def dummy_backend():
+ db = types.ModuleType("pandas_dummy_backend")
+ setattr(db, "plot", lambda *args, **kwargs: "used_dummy")
+ return db
+
+
+@pytest.fixture
+def restore_backend():
+ """Restore the plotting backend to matplotlib"""
+ with pandas.option_context("plotting.backend", "matplotlib"):
+ yield
+
+
+def test_backend_is_not_module():
+ msg = "Could not find plotting backend 'not_an_existing_module'."
+ with pytest.raises(ValueError, match=msg):
+ pandas.set_option("plotting.backend", "not_an_existing_module")
+
+ assert pandas.options.plotting.backend == "matplotlib"
+
+
+def test_backend_is_correct(monkeypatch, restore_backend, dummy_backend):
+ monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend)
+
+ pandas.set_option("plotting.backend", "pandas_dummy_backend")
+ assert pandas.get_option("plotting.backend") == "pandas_dummy_backend"
+ assert (
+ pandas.plotting._core._get_plot_backend("pandas_dummy_backend") is dummy_backend
+ )
+
+
+def test_backend_can_be_set_in_plot_call(monkeypatch, restore_backend, dummy_backend):
+ monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend)
+ df = pandas.DataFrame([1, 2, 3])
+
+ assert pandas.get_option("plotting.backend") == "matplotlib"
+ assert df.plot(backend="pandas_dummy_backend") == "used_dummy"
+
+
+def test_register_entrypoint(restore_backend, tmp_path, monkeypatch, dummy_backend):
+ monkeypatch.syspath_prepend(tmp_path)
+ monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend)
+
+ dist_info = tmp_path / "my_backend-0.0.0.dist-info"
+ dist_info.mkdir()
+ # entry_point name should not match module name - otherwise pandas will
+ # fall back to backend lookup by module name
+ (dist_info / "entry_points.txt").write_bytes(
+ b"[pandas_plotting_backends]\nmy_ep_backend = pandas_dummy_backend\n"
+ )
+
+ assert pandas.plotting._core._get_plot_backend("my_ep_backend") is dummy_backend
+
+ with pandas.option_context("plotting.backend", "my_ep_backend"):
+ assert pandas.plotting._core._get_plot_backend() is dummy_backend
+
+
+def test_setting_backend_without_plot_raises(monkeypatch):
+ # GH-28163
+ module = types.ModuleType("pandas_plot_backend")
+ monkeypatch.setitem(sys.modules, "pandas_plot_backend", module)
+
+ assert pandas.options.plotting.backend == "matplotlib"
+ with pytest.raises(
+ ValueError, match="Could not find plotting backend 'pandas_plot_backend'."
+ ):
+ pandas.set_option("plotting.backend", "pandas_plot_backend")
+
+ assert pandas.options.plotting.backend == "matplotlib"
+
+
+@td.skip_if_mpl
+def test_no_matplotlib_ok():
+ msg = (
+ 'matplotlib is required for plotting when the default backend "matplotlib" is '
+ "selected."
+ )
+ with pytest.raises(ImportError, match=msg):
+ pandas.plotting._core._get_plot_backend("matplotlib")
+
+
+def test_extra_kinds_ok(monkeypatch, restore_backend, dummy_backend):
+ # https://github.com/pandas-dev/pandas/pull/28647
+ monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend)
+ pandas.set_option("plotting.backend", "pandas_dummy_backend")
+ df = pandas.DataFrame({"A": [1, 2, 3]})
+ df.plot(kind="not a real kind")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_boxplot_method.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_boxplot_method.py
new file mode 100644
index 0000000000000000000000000000000000000000..555b9fd0c82c29dba47ef50be38649e762b90d18
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_boxplot_method.py
@@ -0,0 +1,745 @@
+""" Test cases for .boxplot method """
+
+import itertools
+import string
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ date_range,
+ plotting,
+ timedelta_range,
+)
+import pandas._testing as tm
+from pandas.tests.plotting.common import (
+ _check_axes_shape,
+ _check_box_return_type,
+ _check_plot_works,
+ _check_ticks_props,
+ _check_visible,
+)
+
+from pandas.io.formats.printing import pprint_thing
+
+mpl = pytest.importorskip("matplotlib")
+plt = pytest.importorskip("matplotlib.pyplot")
+
+
+def _check_ax_limits(col, ax):
+ y_min, y_max = ax.get_ylim()
+ assert y_min <= col.min()
+ assert y_max >= col.max()
+
+
+class TestDataFramePlots:
+ def test_stacked_boxplot_set_axis(self):
+ # GH2980
+ import matplotlib.pyplot as plt
+
+ n = 80
+ df = DataFrame(
+ {
+ "Clinical": np.random.default_rng(2).choice([0, 1, 2, 3], n),
+ "Confirmed": np.random.default_rng(2).choice([0, 1, 2, 3], n),
+ "Discarded": np.random.default_rng(2).choice([0, 1, 2, 3], n),
+ },
+ index=np.arange(0, n),
+ )
+ ax = df.plot(kind="bar", stacked=True)
+ assert [int(x.get_text()) for x in ax.get_xticklabels()] == df.index.to_list()
+ ax.set_xticks(np.arange(0, 80, 10))
+ plt.draw() # Update changes
+ assert [int(x.get_text()) for x in ax.get_xticklabels()] == list(
+ np.arange(0, 80, 10)
+ )
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "kwargs, warn",
+ [
+ [{"return_type": "dict"}, None],
+ [{"column": ["one", "two"]}, None],
+ [{"column": ["one", "two"], "by": "indic"}, UserWarning],
+ [{"column": ["one"], "by": ["indic", "indic2"]}, None],
+ [{"by": "indic"}, UserWarning],
+ [{"by": ["indic", "indic2"]}, UserWarning],
+ [{"notch": 1}, None],
+ [{"by": "indic", "notch": 1}, UserWarning],
+ ],
+ )
+ def test_boxplot_legacy1(self, kwargs, warn):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["one", "two", "three", "four"],
+ )
+ df["indic"] = ["foo", "bar"] * 3
+ df["indic2"] = ["foo", "bar", "foo"] * 2
+
+ # _check_plot_works can add an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(warn, check_stacklevel=False):
+ _check_plot_works(df.boxplot, **kwargs)
+
+ def test_boxplot_legacy1_series(self):
+ ser = Series(np.random.default_rng(2).standard_normal(6))
+ _check_plot_works(plotting._core.boxplot, data=ser, return_type="dict")
+
+ def test_boxplot_legacy2(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"]
+ )
+ df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
+ df["Y"] = Series(["A"] * 10)
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ _check_plot_works(df.boxplot, by="X")
+
+ def test_boxplot_legacy2_with_ax(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"]
+ )
+ df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
+ df["Y"] = Series(["A"] * 10)
+ # When ax is supplied and required number of axes is 1,
+ # passed ax should be used:
+ _, ax = mpl.pyplot.subplots()
+ axes = df.boxplot("Col1", by="X", ax=ax)
+ ax_axes = ax.axes
+ assert ax_axes is axes
+
+ def test_boxplot_legacy2_with_ax_return_type(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"]
+ )
+ df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
+ df["Y"] = Series(["A"] * 10)
+ fig, ax = mpl.pyplot.subplots()
+ axes = df.groupby("Y").boxplot(ax=ax, return_type="axes")
+ ax_axes = ax.axes
+ assert ax_axes is axes["A"]
+
+ def test_boxplot_legacy2_with_multi_col(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"]
+ )
+ df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
+ df["Y"] = Series(["A"] * 10)
+ # Multiple columns with an ax argument should use same figure
+ fig, ax = mpl.pyplot.subplots()
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.boxplot(
+ column=["Col1", "Col2"], by="X", ax=ax, return_type="axes"
+ )
+ assert axes["Col1"].get_figure() is fig
+
+ def test_boxplot_legacy2_by_none(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"]
+ )
+ df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
+ df["Y"] = Series(["A"] * 10)
+ # When by is None, check that all relevant lines are present in the
+ # dict
+ _, ax = mpl.pyplot.subplots()
+ d = df.boxplot(ax=ax, return_type="dict")
+ lines = list(itertools.chain.from_iterable(d.values()))
+ assert len(ax.get_lines()) == len(lines)
+
+ def test_boxplot_return_type_none(self, hist_df):
+ # GH 12216; return_type=None & by=None -> axes
+ result = hist_df.boxplot()
+ assert isinstance(result, mpl.pyplot.Axes)
+
+ def test_boxplot_return_type_legacy(self):
+ # API change in https://github.com/pandas-dev/pandas/pull/7096
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["one", "two", "three", "four"],
+ )
+ msg = "return_type must be {'axes', 'dict', 'both'}"
+ with pytest.raises(ValueError, match=msg):
+ df.boxplot(return_type="NOT_A_TYPE")
+
+ result = df.boxplot()
+ _check_box_return_type(result, "axes")
+
+ @pytest.mark.parametrize("return_type", ["dict", "axes", "both"])
+ def test_boxplot_return_type_legacy_return_type(self, return_type):
+ # API change in https://github.com/pandas-dev/pandas/pull/7096
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 4)),
+ index=list(string.ascii_letters[:6]),
+ columns=["one", "two", "three", "four"],
+ )
+ with tm.assert_produces_warning(False):
+ result = df.boxplot(return_type=return_type)
+ _check_box_return_type(result, return_type)
+
+ def test_boxplot_axis_limits(self, hist_df):
+ df = hist_df.copy()
+ df["age"] = np.random.default_rng(2).integers(1, 20, df.shape[0])
+ # One full row
+ height_ax, weight_ax = df.boxplot(["height", "weight"], by="category")
+ _check_ax_limits(df["height"], height_ax)
+ _check_ax_limits(df["weight"], weight_ax)
+ assert weight_ax._sharey == height_ax
+
+ def test_boxplot_axis_limits_two_rows(self, hist_df):
+ df = hist_df.copy()
+ df["age"] = np.random.default_rng(2).integers(1, 20, df.shape[0])
+ # Two rows, one partial
+ p = df.boxplot(["height", "weight", "age"], by="category")
+ height_ax, weight_ax, age_ax = p[0, 0], p[0, 1], p[1, 0]
+ dummy_ax = p[1, 1]
+
+ _check_ax_limits(df["height"], height_ax)
+ _check_ax_limits(df["weight"], weight_ax)
+ _check_ax_limits(df["age"], age_ax)
+ assert weight_ax._sharey == height_ax
+ assert age_ax._sharey == height_ax
+ assert dummy_ax._sharey is None
+
+ def test_boxplot_empty_column(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((20, 4)))
+ df.loc[:, 0] = np.nan
+ _check_plot_works(df.boxplot, return_type="axes")
+
+ def test_figsize(self):
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 5)), columns=["A", "B", "C", "D", "E"]
+ )
+ result = df.boxplot(return_type="axes", figsize=(12, 8))
+ assert result.figure.bbox_inches.width == 12
+ assert result.figure.bbox_inches.height == 8
+
+ def test_fontsize(self):
+ df = DataFrame({"a": [1, 2, 3, 4, 5, 6]})
+ _check_ticks_props(df.boxplot("a", fontsize=16), xlabelsize=16, ylabelsize=16)
+
+ def test_boxplot_numeric_data(self):
+ # GH 22799
+ df = DataFrame(
+ {
+ "a": date_range("2012-01-01", periods=100),
+ "b": np.random.default_rng(2).standard_normal(100),
+ "c": np.random.default_rng(2).standard_normal(100) + 2,
+ "d": date_range("2012-01-01", periods=100).astype(str),
+ "e": date_range("2012-01-01", periods=100, tz="UTC"),
+ "f": timedelta_range("1 days", periods=100),
+ }
+ )
+ ax = df.plot(kind="box")
+ assert [x.get_text() for x in ax.get_xticklabels()] == ["b", "c"]
+
+ @pytest.mark.parametrize(
+ "colors_kwd, expected",
+ [
+ (
+ {"boxes": "r", "whiskers": "b", "medians": "g", "caps": "c"},
+ {"boxes": "r", "whiskers": "b", "medians": "g", "caps": "c"},
+ ),
+ ({"boxes": "r"}, {"boxes": "r"}),
+ ("r", {"boxes": "r", "whiskers": "r", "medians": "r", "caps": "r"}),
+ ],
+ )
+ def test_color_kwd(self, colors_kwd, expected):
+ # GH: 26214
+ df = DataFrame(np.random.default_rng(2).random((10, 2)))
+ result = df.boxplot(color=colors_kwd, return_type="dict")
+ for k, v in expected.items():
+ assert result[k][0].get_color() == v
+
+ @pytest.mark.parametrize(
+ "scheme,expected",
+ [
+ (
+ "dark_background",
+ {
+ "boxes": "#8dd3c7",
+ "whiskers": "#8dd3c7",
+ "medians": "#bfbbd9",
+ "caps": "#8dd3c7",
+ },
+ ),
+ (
+ "default",
+ {
+ "boxes": "#1f77b4",
+ "whiskers": "#1f77b4",
+ "medians": "#2ca02c",
+ "caps": "#1f77b4",
+ },
+ ),
+ ],
+ )
+ def test_colors_in_theme(self, scheme, expected):
+ # GH: 40769
+ df = DataFrame(np.random.default_rng(2).random((10, 2)))
+ import matplotlib.pyplot as plt
+
+ plt.style.use(scheme)
+ result = df.plot.box(return_type="dict")
+ for k, v in expected.items():
+ assert result[k][0].get_color() == v
+
+ @pytest.mark.parametrize(
+ "dict_colors, msg",
+ [({"boxes": "r", "invalid_key": "r"}, "invalid key 'invalid_key'")],
+ )
+ def test_color_kwd_errors(self, dict_colors, msg):
+ # GH: 26214
+ df = DataFrame(np.random.default_rng(2).random((10, 2)))
+ with pytest.raises(ValueError, match=msg):
+ df.boxplot(color=dict_colors, return_type="dict")
+
+ @pytest.mark.parametrize(
+ "props, expected",
+ [
+ ("boxprops", "boxes"),
+ ("whiskerprops", "whiskers"),
+ ("capprops", "caps"),
+ ("medianprops", "medians"),
+ ],
+ )
+ def test_specified_props_kwd(self, props, expected):
+ # GH 30346
+ df = DataFrame({k: np.random.default_rng(2).random(10) for k in "ABC"})
+ kwd = {props: {"color": "C1"}}
+ result = df.boxplot(return_type="dict", **kwd)
+
+ assert result[expected][0].get_color() == "C1"
+
+ @pytest.mark.parametrize("vert", [True, False])
+ def test_plot_xlabel_ylabel(self, vert):
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(10),
+ "b": np.random.default_rng(2).standard_normal(10),
+ "group": np.random.default_rng(2).choice(["group1", "group2"], 10),
+ }
+ )
+ xlabel, ylabel = "x", "y"
+ ax = df.plot(kind="box", vert=vert, xlabel=xlabel, ylabel=ylabel)
+ assert ax.get_xlabel() == xlabel
+ assert ax.get_ylabel() == ylabel
+
+ @pytest.mark.parametrize("vert", [True, False])
+ def test_boxplot_xlabel_ylabel(self, vert):
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(10),
+ "b": np.random.default_rng(2).standard_normal(10),
+ "group": np.random.default_rng(2).choice(["group1", "group2"], 10),
+ }
+ )
+ xlabel, ylabel = "x", "y"
+ ax = df.boxplot(vert=vert, xlabel=xlabel, ylabel=ylabel)
+ assert ax.get_xlabel() == xlabel
+ assert ax.get_ylabel() == ylabel
+
+ @pytest.mark.parametrize("vert", [True, False])
+ def test_boxplot_group_xlabel_ylabel(self, vert):
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(10),
+ "b": np.random.default_rng(2).standard_normal(10),
+ "group": np.random.default_rng(2).choice(["group1", "group2"], 10),
+ }
+ )
+ xlabel, ylabel = "x", "y"
+ ax = df.boxplot(by="group", vert=vert, xlabel=xlabel, ylabel=ylabel)
+ for subplot in ax:
+ assert subplot.get_xlabel() == xlabel
+ assert subplot.get_ylabel() == ylabel
+ mpl.pyplot.close()
+
+ @pytest.mark.parametrize("vert", [True, False])
+ def test_boxplot_group_no_xlabel_ylabel(self, vert):
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(10),
+ "b": np.random.default_rng(2).standard_normal(10),
+ "group": np.random.default_rng(2).choice(["group1", "group2"], 10),
+ }
+ )
+ ax = df.boxplot(by="group", vert=vert)
+ for subplot in ax:
+ target_label = subplot.get_xlabel() if vert else subplot.get_ylabel()
+ assert target_label == pprint_thing(["group"])
+ mpl.pyplot.close()
+
+
+class TestDataFrameGroupByPlots:
+ def test_boxplot_legacy1(self, hist_df):
+ grouped = hist_df.groupby(by="gender")
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(grouped.boxplot, return_type="axes")
+ _check_axes_shape(list(axes.values), axes_num=2, layout=(1, 2))
+
+ def test_boxplot_legacy1_return_type(self, hist_df):
+ grouped = hist_df.groupby(by="gender")
+ axes = _check_plot_works(grouped.boxplot, subplots=False, return_type="axes")
+ _check_axes_shape(axes, axes_num=1, layout=(1, 1))
+
+ @pytest.mark.slow
+ def test_boxplot_legacy2(self):
+ tuples = zip(string.ascii_letters[:10], range(10))
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=MultiIndex.from_tuples(tuples),
+ )
+ grouped = df.groupby(level=1)
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(grouped.boxplot, return_type="axes")
+ _check_axes_shape(list(axes.values), axes_num=10, layout=(4, 3))
+
+ @pytest.mark.slow
+ def test_boxplot_legacy2_return_type(self):
+ tuples = zip(string.ascii_letters[:10], range(10))
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=MultiIndex.from_tuples(tuples),
+ )
+ grouped = df.groupby(level=1)
+ axes = _check_plot_works(grouped.boxplot, subplots=False, return_type="axes")
+ _check_axes_shape(axes, axes_num=1, layout=(1, 1))
+
+ @pytest.mark.parametrize(
+ "subplots, warn, axes_num, layout",
+ [[True, UserWarning, 3, (2, 2)], [False, None, 1, (1, 1)]],
+ )
+ def test_boxplot_legacy3(self, subplots, warn, axes_num, layout):
+ tuples = zip(string.ascii_letters[:10], range(10))
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 3)),
+ index=MultiIndex.from_tuples(tuples),
+ )
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ grouped = df.unstack(level=1).groupby(level=0, axis=1)
+ with tm.assert_produces_warning(warn, check_stacklevel=False):
+ axes = _check_plot_works(
+ grouped.boxplot, subplots=subplots, return_type="axes"
+ )
+ _check_axes_shape(axes, axes_num=axes_num, layout=layout)
+
+ def test_grouped_plot_fignums(self):
+ n = 10
+ weight = Series(np.random.default_rng(2).normal(166, 20, size=n))
+ height = Series(np.random.default_rng(2).normal(60, 10, size=n))
+ gender = np.random.default_rng(2).choice(["male", "female"], size=n)
+ df = DataFrame({"height": height, "weight": weight, "gender": gender})
+ gb = df.groupby("gender")
+
+ res = gb.plot()
+ assert len(mpl.pyplot.get_fignums()) == 2
+ assert len(res) == 2
+ plt.close("all")
+
+ res = gb.boxplot(return_type="axes")
+ assert len(mpl.pyplot.get_fignums()) == 1
+ assert len(res) == 2
+
+ def test_grouped_plot_fignums_excluded_col(self):
+ n = 10
+ weight = Series(np.random.default_rng(2).normal(166, 20, size=n))
+ height = Series(np.random.default_rng(2).normal(60, 10, size=n))
+ gender = np.random.default_rng(2).choice(["male", "female"], size=n)
+ df = DataFrame({"height": height, "weight": weight, "gender": gender})
+ # now works with GH 5610 as gender is excluded
+ df.groupby("gender").hist()
+
+ @pytest.mark.slow
+ def test_grouped_box_return_type(self, hist_df):
+ df = hist_df
+
+ # old style: return_type=None
+ result = df.boxplot(by="gender")
+ assert isinstance(result, np.ndarray)
+ _check_box_return_type(
+ result, None, expected_keys=["height", "weight", "category"]
+ )
+
+ @pytest.mark.slow
+ def test_grouped_box_return_type_groupby(self, hist_df):
+ df = hist_df
+ # now for groupby
+ result = df.groupby("gender").boxplot(return_type="dict")
+ _check_box_return_type(result, "dict", expected_keys=["Male", "Female"])
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("return_type", ["dict", "axes", "both"])
+ def test_grouped_box_return_type_arg(self, hist_df, return_type):
+ df = hist_df
+
+ returned = df.groupby("classroom").boxplot(return_type=return_type)
+ _check_box_return_type(returned, return_type, expected_keys=["A", "B", "C"])
+
+ returned = df.boxplot(by="classroom", return_type=return_type)
+ _check_box_return_type(
+ returned, return_type, expected_keys=["height", "weight", "category"]
+ )
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("return_type", ["dict", "axes", "both"])
+ def test_grouped_box_return_type_arg_duplcate_cats(self, return_type):
+ columns2 = "X B C D A".split()
+ df2 = DataFrame(
+ np.random.default_rng(2).standard_normal((6, 5)), columns=columns2
+ )
+ categories2 = "A B".split()
+ df2["category"] = categories2 * 3
+
+ returned = df2.groupby("category").boxplot(return_type=return_type)
+ _check_box_return_type(returned, return_type, expected_keys=categories2)
+
+ returned = df2.boxplot(by="category", return_type=return_type)
+ _check_box_return_type(returned, return_type, expected_keys=columns2)
+
+ @pytest.mark.slow
+ def test_grouped_box_layout_too_small(self, hist_df):
+ df = hist_df
+
+ msg = "Layout of 1x1 must be larger than required size 2"
+ with pytest.raises(ValueError, match=msg):
+ df.boxplot(column=["weight", "height"], by=df.gender, layout=(1, 1))
+
+ @pytest.mark.slow
+ def test_grouped_box_layout_needs_by(self, hist_df):
+ df = hist_df
+ msg = "The 'layout' keyword is not supported when 'by' is None"
+ with pytest.raises(ValueError, match=msg):
+ df.boxplot(
+ column=["height", "weight", "category"],
+ layout=(2, 1),
+ return_type="dict",
+ )
+
+ @pytest.mark.slow
+ def test_grouped_box_layout_positive_layout(self, hist_df):
+ df = hist_df
+ msg = "At least one dimension of layout must be positive"
+ with pytest.raises(ValueError, match=msg):
+ df.boxplot(column=["weight", "height"], by=df.gender, layout=(-1, -1))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "gb_key, axes_num, rows",
+ [["gender", 2, 1], ["category", 4, 2], ["classroom", 3, 2]],
+ )
+ def test_grouped_box_layout_positive_layout_axes(
+ self, hist_df, gb_key, axes_num, rows
+ ):
+ df = hist_df
+ # _check_plot_works adds an ax so catch warning. see GH #13188 GH 6769
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ _check_plot_works(
+ df.groupby(gb_key).boxplot, column="height", return_type="dict"
+ )
+ _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=axes_num, layout=(rows, 2))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "col, visible", [["height", False], ["weight", True], ["category", True]]
+ )
+ def test_grouped_box_layout_visible(self, hist_df, col, visible):
+ df = hist_df
+ # GH 5897
+ axes = df.boxplot(
+ column=["height", "weight", "category"], by="gender", return_type="axes"
+ )
+ _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(2, 2))
+ ax = axes[col]
+ _check_visible(ax.get_xticklabels(), visible=visible)
+ _check_visible([ax.xaxis.get_label()], visible=visible)
+
+ @pytest.mark.slow
+ def test_grouped_box_layout_shape(self, hist_df):
+ df = hist_df
+ df.groupby("classroom").boxplot(
+ column=["height", "weight", "category"], return_type="dict"
+ )
+ _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(2, 2))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("cols", [2, -1])
+ def test_grouped_box_layout_works(self, hist_df, cols):
+ df = hist_df
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ _check_plot_works(
+ df.groupby("category").boxplot,
+ column="height",
+ layout=(3, cols),
+ return_type="dict",
+ )
+ _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=4, layout=(3, 2))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("rows, res", [[4, 4], [-1, 3]])
+ def test_grouped_box_layout_axes_shape_rows(self, hist_df, rows, res):
+ df = hist_df
+ df.boxplot(
+ column=["height", "weight", "category"], by="gender", layout=(rows, 1)
+ )
+ _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(res, 1))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("cols, res", [[4, 4], [-1, 3]])
+ def test_grouped_box_layout_axes_shape_cols_groupby(self, hist_df, cols, res):
+ df = hist_df
+ df.groupby("classroom").boxplot(
+ column=["height", "weight", "category"],
+ layout=(1, cols),
+ return_type="dict",
+ )
+ _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(1, res))
+
+ @pytest.mark.slow
+ def test_grouped_box_multiple_axes(self, hist_df):
+ # GH 6970, GH 7069
+ df = hist_df
+
+ # check warning to ignore sharex / sharey
+ # this check should be done in the first function which
+ # passes multiple axes to plot, hist or boxplot
+ # location should be changed if other test is added
+ # which has earlier alphabetical order
+ with tm.assert_produces_warning(UserWarning):
+ _, axes = mpl.pyplot.subplots(2, 2)
+ df.groupby("category").boxplot(column="height", return_type="axes", ax=axes)
+ _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=4, layout=(2, 2))
+
+ @pytest.mark.slow
+ def test_grouped_box_multiple_axes_on_fig(self, hist_df):
+ # GH 6970, GH 7069
+ df = hist_df
+ fig, axes = mpl.pyplot.subplots(2, 3)
+ with tm.assert_produces_warning(UserWarning):
+ returned = df.boxplot(
+ column=["height", "weight", "category"],
+ by="gender",
+ return_type="axes",
+ ax=axes[0],
+ )
+ returned = np.array(list(returned.values))
+ _check_axes_shape(returned, axes_num=3, layout=(1, 3))
+ tm.assert_numpy_array_equal(returned, axes[0])
+ assert returned[0].figure is fig
+
+ # draw on second row
+ with tm.assert_produces_warning(UserWarning):
+ returned = df.groupby("classroom").boxplot(
+ column=["height", "weight", "category"], return_type="axes", ax=axes[1]
+ )
+ returned = np.array(list(returned.values))
+ _check_axes_shape(returned, axes_num=3, layout=(1, 3))
+ tm.assert_numpy_array_equal(returned, axes[1])
+ assert returned[0].figure is fig
+
+ @pytest.mark.slow
+ def test_grouped_box_multiple_axes_ax_error(self, hist_df):
+ # GH 6970, GH 7069
+ df = hist_df
+ msg = "The number of passed axes must be 3, the same as the output plot"
+ with pytest.raises(ValueError, match=msg):
+ fig, axes = mpl.pyplot.subplots(2, 3)
+ # pass different number of axes from required
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.groupby("classroom").boxplot(ax=axes)
+
+ def test_fontsize(self):
+ df = DataFrame({"a": [1, 2, 3, 4, 5, 6], "b": [0, 0, 0, 1, 1, 1]})
+ _check_ticks_props(
+ df.boxplot("a", by="b", fontsize=16), xlabelsize=16, ylabelsize=16
+ )
+
+ @pytest.mark.parametrize(
+ "col, expected_xticklabel",
+ [
+ ("v", ["(a, v)", "(b, v)", "(c, v)", "(d, v)", "(e, v)"]),
+ (["v"], ["(a, v)", "(b, v)", "(c, v)", "(d, v)", "(e, v)"]),
+ ("v1", ["(a, v1)", "(b, v1)", "(c, v1)", "(d, v1)", "(e, v1)"]),
+ (
+ ["v", "v1"],
+ [
+ "(a, v)",
+ "(a, v1)",
+ "(b, v)",
+ "(b, v1)",
+ "(c, v)",
+ "(c, v1)",
+ "(d, v)",
+ "(d, v1)",
+ "(e, v)",
+ "(e, v1)",
+ ],
+ ),
+ (
+ None,
+ [
+ "(a, v)",
+ "(a, v1)",
+ "(b, v)",
+ "(b, v1)",
+ "(c, v)",
+ "(c, v1)",
+ "(d, v)",
+ "(d, v1)",
+ "(e, v)",
+ "(e, v1)",
+ ],
+ ),
+ ],
+ )
+ def test_groupby_boxplot_subplots_false(self, col, expected_xticklabel):
+ # GH 16748
+ df = DataFrame(
+ {
+ "cat": np.random.default_rng(2).choice(list("abcde"), 100),
+ "v": np.random.default_rng(2).random(100),
+ "v1": np.random.default_rng(2).random(100),
+ }
+ )
+ grouped = df.groupby("cat")
+
+ axes = _check_plot_works(
+ grouped.boxplot, subplots=False, column=col, return_type="axes"
+ )
+
+ result_xticklabel = [x.get_text() for x in axes.get_xticklabels()]
+ assert expected_xticklabel == result_xticklabel
+
+ def test_groupby_boxplot_object(self, hist_df):
+ # GH 43480
+ df = hist_df.astype("object")
+ grouped = df.groupby("gender")
+ msg = "boxplot method requires numerical columns, nothing to plot"
+ with pytest.raises(ValueError, match=msg):
+ _check_plot_works(grouped.boxplot, subplots=False)
+
+ def test_boxplot_multiindex_column(self):
+ # GH 16748
+ arrays = [
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
+ ["one", "two", "one", "two", "one", "two", "one", "two"],
+ ]
+ tuples = list(zip(*arrays))
+ index = MultiIndex.from_tuples(tuples, names=["first", "second"])
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, 8)),
+ index=["A", "B", "C"],
+ columns=index,
+ )
+
+ col = [("bar", "one"), ("bar", "two")]
+ axes = _check_plot_works(df.boxplot, column=col, return_type="axes")
+
+ expected_xticklabel = ["(bar, one)", "(bar, two)"]
+ result_xticklabel = [x.get_text() for x in axes.get_xticklabels()]
+ assert expected_xticklabel == result_xticklabel
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..20daf5935624843af3224f991497f84fa6639a0d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_common.py
@@ -0,0 +1,60 @@
+import pytest
+
+from pandas import DataFrame
+from pandas.tests.plotting.common import (
+ _check_plot_works,
+ _check_ticks_props,
+ _gen_two_subplots,
+)
+
+plt = pytest.importorskip("matplotlib.pyplot")
+
+
+class TestCommon:
+ def test__check_ticks_props(self):
+ # GH 34768
+ df = DataFrame({"b": [0, 1, 0], "a": [1, 2, 3]})
+ ax = _check_plot_works(df.plot, rot=30)
+ ax.yaxis.set_tick_params(rotation=30)
+ msg = "expected 0.00000 but got "
+ with pytest.raises(AssertionError, match=msg):
+ _check_ticks_props(ax, xrot=0)
+ with pytest.raises(AssertionError, match=msg):
+ _check_ticks_props(ax, xlabelsize=0)
+ with pytest.raises(AssertionError, match=msg):
+ _check_ticks_props(ax, yrot=0)
+ with pytest.raises(AssertionError, match=msg):
+ _check_ticks_props(ax, ylabelsize=0)
+
+ def test__gen_two_subplots_with_ax(self):
+ fig = plt.gcf()
+ gen = _gen_two_subplots(f=lambda **kwargs: None, fig=fig, ax="test")
+ # On the first yield, no subplot should be added since ax was passed
+ next(gen)
+ assert fig.get_axes() == []
+ # On the second, the one axis should match fig.subplot(2, 1, 2)
+ next(gen)
+ axes = fig.get_axes()
+ assert len(axes) == 1
+ subplot_geometry = list(axes[0].get_subplotspec().get_geometry()[:-1])
+ subplot_geometry[-1] += 1
+ assert subplot_geometry == [2, 1, 2]
+
+ def test_colorbar_layout(self):
+ fig = plt.figure()
+
+ axes = fig.subplot_mosaic(
+ """
+ AB
+ CC
+ """
+ )
+
+ x = [1, 2, 3]
+ y = [1, 2, 3]
+
+ cs0 = axes["A"].scatter(x, y)
+ axes["B"].scatter(x, y)
+
+ fig.colorbar(cs0, ax=[axes["A"], axes["B"]], location="right")
+ DataFrame(x).plot(ax=axes["C"])
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_converter.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..56d7900e2907d7943377106d3eca65770dd52962
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_converter.py
@@ -0,0 +1,408 @@
+from datetime import (
+ date,
+ datetime,
+)
+import subprocess
+import sys
+
+import numpy as np
+import pytest
+
+import pandas._config.config as cf
+
+from pandas import (
+ Index,
+ Period,
+ PeriodIndex,
+ Series,
+ Timestamp,
+ arrays,
+ date_range,
+)
+import pandas._testing as tm
+
+from pandas.plotting import (
+ deregister_matplotlib_converters,
+ register_matplotlib_converters,
+)
+from pandas.tseries.offsets import (
+ Day,
+ Micro,
+ Milli,
+ Second,
+)
+
+try:
+ from pandas.plotting._matplotlib import converter
+except ImportError:
+ # try / except, rather than skip, to avoid internal refactoring
+ # causing an improper skip
+ pass
+
+pytest.importorskip("matplotlib.pyplot")
+dates = pytest.importorskip("matplotlib.dates")
+
+
+@pytest.mark.single_cpu
+def test_registry_mpl_resets():
+ # Check that Matplotlib converters are properly reset (see issue #27481)
+ code = (
+ "import matplotlib.units as units; "
+ "import matplotlib.dates as mdates; "
+ "n_conv = len(units.registry); "
+ "import pandas as pd; "
+ "pd.plotting.register_matplotlib_converters(); "
+ "pd.plotting.deregister_matplotlib_converters(); "
+ "assert len(units.registry) == n_conv"
+ )
+ call = [sys.executable, "-c", code]
+ subprocess.check_output(call)
+
+
+def test_timtetonum_accepts_unicode():
+ assert converter.time2num("00:01") == converter.time2num("00:01")
+
+
+class TestRegistration:
+ @pytest.mark.single_cpu
+ def test_dont_register_by_default(self):
+ # Run in subprocess to ensure a clean state
+ code = (
+ "import matplotlib.units; "
+ "import pandas as pd; "
+ "units = dict(matplotlib.units.registry); "
+ "assert pd.Timestamp not in units"
+ )
+ call = [sys.executable, "-c", code]
+ assert subprocess.check_call(call) == 0
+
+ def test_registering_no_warning(self):
+ plt = pytest.importorskip("matplotlib.pyplot")
+ s = Series(range(12), index=date_range("2017", periods=12))
+ _, ax = plt.subplots()
+
+ # Set to the "warn" state, in case this isn't the first test run
+ register_matplotlib_converters()
+ ax.plot(s.index, s.values)
+ plt.close()
+
+ def test_pandas_plots_register(self):
+ plt = pytest.importorskip("matplotlib.pyplot")
+ s = Series(range(12), index=date_range("2017", periods=12))
+ # Set to the "warn" state, in case this isn't the first test run
+ with tm.assert_produces_warning(None) as w:
+ s.plot()
+
+ try:
+ assert len(w) == 0
+ finally:
+ plt.close()
+
+ def test_matplotlib_formatters(self):
+ units = pytest.importorskip("matplotlib.units")
+
+ # Can't make any assertion about the start state.
+ # We we check that toggling converters off removes it, and toggling it
+ # on restores it.
+
+ with cf.option_context("plotting.matplotlib.register_converters", True):
+ with cf.option_context("plotting.matplotlib.register_converters", False):
+ assert Timestamp not in units.registry
+ assert Timestamp in units.registry
+
+ def test_option_no_warning(self):
+ pytest.importorskip("matplotlib.pyplot")
+ ctx = cf.option_context("plotting.matplotlib.register_converters", False)
+ plt = pytest.importorskip("matplotlib.pyplot")
+ s = Series(range(12), index=date_range("2017", periods=12))
+ _, ax = plt.subplots()
+
+ # Test without registering first, no warning
+ with ctx:
+ ax.plot(s.index, s.values)
+
+ # Now test with registering
+ register_matplotlib_converters()
+ with ctx:
+ ax.plot(s.index, s.values)
+ plt.close()
+
+ def test_registry_resets(self):
+ units = pytest.importorskip("matplotlib.units")
+ dates = pytest.importorskip("matplotlib.dates")
+
+ # make a copy, to reset to
+ original = dict(units.registry)
+
+ try:
+ # get to a known state
+ units.registry.clear()
+ date_converter = dates.DateConverter()
+ units.registry[datetime] = date_converter
+ units.registry[date] = date_converter
+
+ register_matplotlib_converters()
+ assert units.registry[date] is not date_converter
+ deregister_matplotlib_converters()
+ assert units.registry[date] is date_converter
+
+ finally:
+ # restore original stater
+ units.registry.clear()
+ for k, v in original.items():
+ units.registry[k] = v
+
+
+class TestDateTimeConverter:
+ @pytest.fixture
+ def dtc(self):
+ return converter.DatetimeConverter()
+
+ def test_convert_accepts_unicode(self, dtc):
+ r1 = dtc.convert("2000-01-01 12:22", None, None)
+ r2 = dtc.convert("2000-01-01 12:22", None, None)
+ assert r1 == r2, "DatetimeConverter.convert should accept unicode"
+
+ def test_conversion(self, dtc):
+ rs = dtc.convert(["2012-1-1"], None, None)[0]
+ xp = dates.date2num(datetime(2012, 1, 1))
+ assert rs == xp
+
+ rs = dtc.convert("2012-1-1", None, None)
+ assert rs == xp
+
+ rs = dtc.convert(date(2012, 1, 1), None, None)
+ assert rs == xp
+
+ rs = dtc.convert("2012-1-1", None, None)
+ assert rs == xp
+
+ rs = dtc.convert(Timestamp("2012-1-1"), None, None)
+ assert rs == xp
+
+ # also testing datetime64 dtype (GH8614)
+ rs = dtc.convert("2012-01-01", None, None)
+ assert rs == xp
+
+ rs = dtc.convert("2012-01-01 00:00:00+0000", None, None)
+ assert rs == xp
+
+ rs = dtc.convert(
+ np.array(["2012-01-01 00:00:00+0000", "2012-01-02 00:00:00+0000"]),
+ None,
+ None,
+ )
+ assert rs[0] == xp
+
+ # we have a tz-aware date (constructed to that when we turn to utc it
+ # is the same as our sample)
+ ts = Timestamp("2012-01-01").tz_localize("UTC").tz_convert("US/Eastern")
+ rs = dtc.convert(ts, None, None)
+ assert rs == xp
+
+ rs = dtc.convert(ts.to_pydatetime(), None, None)
+ assert rs == xp
+
+ rs = dtc.convert(Index([ts - Day(1), ts]), None, None)
+ assert rs[1] == xp
+
+ rs = dtc.convert(Index([ts - Day(1), ts]).to_pydatetime(), None, None)
+ assert rs[1] == xp
+
+ def test_conversion_float(self, dtc):
+ rtol = 0.5 * 10**-9
+
+ rs = dtc.convert(Timestamp("2012-1-1 01:02:03", tz="UTC"), None, None)
+ xp = converter.mdates.date2num(Timestamp("2012-1-1 01:02:03", tz="UTC"))
+ tm.assert_almost_equal(rs, xp, rtol=rtol)
+
+ rs = dtc.convert(
+ Timestamp("2012-1-1 09:02:03", tz="Asia/Hong_Kong"), None, None
+ )
+ tm.assert_almost_equal(rs, xp, rtol=rtol)
+
+ rs = dtc.convert(datetime(2012, 1, 1, 1, 2, 3), None, None)
+ tm.assert_almost_equal(rs, xp, rtol=rtol)
+
+ @pytest.mark.parametrize(
+ "values",
+ [
+ [date(1677, 1, 1), date(1677, 1, 2)],
+ [datetime(1677, 1, 1, 12), datetime(1677, 1, 2, 12)],
+ ],
+ )
+ def test_conversion_outofbounds_datetime(self, dtc, values):
+ # 2579
+ rs = dtc.convert(values, None, None)
+ xp = converter.mdates.date2num(values)
+ tm.assert_numpy_array_equal(rs, xp)
+ rs = dtc.convert(values[0], None, None)
+ xp = converter.mdates.date2num(values[0])
+ assert rs == xp
+
+ @pytest.mark.parametrize(
+ "time,format_expected",
+ [
+ (0, "00:00"), # time2num(datetime.time.min)
+ (86399.999999, "23:59:59.999999"), # time2num(datetime.time.max)
+ (90000, "01:00"),
+ (3723, "01:02:03"),
+ (39723.2, "11:02:03.200"),
+ ],
+ )
+ def test_time_formatter(self, time, format_expected):
+ # issue 18478
+ result = converter.TimeFormatter(None)(time)
+ assert result == format_expected
+
+ @pytest.mark.parametrize("freq", ("B", "L", "S"))
+ def test_dateindex_conversion(self, freq, dtc):
+ rtol = 10**-9
+ dateindex = tm.makeDateIndex(k=10, freq=freq)
+ rs = dtc.convert(dateindex, None, None)
+ xp = converter.mdates.date2num(dateindex._mpl_repr())
+ tm.assert_almost_equal(rs, xp, rtol=rtol)
+
+ @pytest.mark.parametrize("offset", [Second(), Milli(), Micro(50)])
+ def test_resolution(self, offset, dtc):
+ # Matplotlib's time representation using floats cannot distinguish
+ # intervals smaller than ~10 microsecond in the common range of years.
+ ts1 = Timestamp("2012-1-1")
+ ts2 = ts1 + offset
+ val1 = dtc.convert(ts1, None, None)
+ val2 = dtc.convert(ts2, None, None)
+ if not val1 < val2:
+ raise AssertionError(f"{val1} is not less than {val2}.")
+
+ def test_convert_nested(self, dtc):
+ inner = [Timestamp("2017-01-01"), Timestamp("2017-01-02")]
+ data = [inner, inner]
+ result = dtc.convert(data, None, None)
+ expected = [dtc.convert(x, None, None) for x in data]
+ assert (np.array(result) == expected).all()
+
+
+class TestPeriodConverter:
+ @pytest.fixture
+ def pc(self):
+ return converter.PeriodConverter()
+
+ @pytest.fixture
+ def axis(self):
+ class Axis:
+ pass
+
+ axis = Axis()
+ axis.freq = "D"
+ return axis
+
+ def test_convert_accepts_unicode(self, pc, axis):
+ r1 = pc.convert("2012-1-1", None, axis)
+ r2 = pc.convert("2012-1-1", None, axis)
+ assert r1 == r2
+
+ def test_conversion(self, pc, axis):
+ rs = pc.convert(["2012-1-1"], None, axis)[0]
+ xp = Period("2012-1-1").ordinal
+ assert rs == xp
+
+ rs = pc.convert("2012-1-1", None, axis)
+ assert rs == xp
+
+ rs = pc.convert([date(2012, 1, 1)], None, axis)[0]
+ assert rs == xp
+
+ rs = pc.convert(date(2012, 1, 1), None, axis)
+ assert rs == xp
+
+ rs = pc.convert([Timestamp("2012-1-1")], None, axis)[0]
+ assert rs == xp
+
+ rs = pc.convert(Timestamp("2012-1-1"), None, axis)
+ assert rs == xp
+
+ rs = pc.convert("2012-01-01", None, axis)
+ assert rs == xp
+
+ rs = pc.convert("2012-01-01 00:00:00+0000", None, axis)
+ assert rs == xp
+
+ rs = pc.convert(
+ np.array(
+ ["2012-01-01 00:00:00", "2012-01-02 00:00:00"],
+ dtype="datetime64[ns]",
+ ),
+ None,
+ axis,
+ )
+ assert rs[0] == xp
+
+ def test_integer_passthrough(self, pc, axis):
+ # GH9012
+ rs = pc.convert([0, 1], None, axis)
+ xp = [0, 1]
+ assert rs == xp
+
+ def test_convert_nested(self, pc, axis):
+ data = ["2012-1-1", "2012-1-2"]
+ r1 = pc.convert([data, data], None, axis)
+ r2 = [pc.convert(data, None, axis) for _ in range(2)]
+ assert r1 == r2
+
+
+class TestTimeDeltaConverter:
+ """Test timedelta converter"""
+
+ @pytest.mark.parametrize(
+ "x, decimal, format_expected",
+ [
+ (0.0, 0, "00:00:00"),
+ (3972320000000, 1, "01:06:12.3"),
+ (713233432000000, 2, "8 days 06:07:13.43"),
+ (32423432000000, 4, "09:00:23.4320"),
+ ],
+ )
+ def test_format_timedelta_ticks(self, x, decimal, format_expected):
+ tdc = converter.TimeSeries_TimedeltaFormatter
+ result = tdc.format_timedelta_ticks(x, pos=None, n_decimals=decimal)
+ assert result == format_expected
+
+ @pytest.mark.parametrize("view_interval", [(1, 2), (2, 1)])
+ def test_call_w_different_view_intervals(self, view_interval, monkeypatch):
+ # previously broke on reversed xlmits; see GH37454
+ class mock_axis:
+ def get_view_interval(self):
+ return view_interval
+
+ tdc = converter.TimeSeries_TimedeltaFormatter()
+ monkeypatch.setattr(tdc, "axis", mock_axis())
+ tdc(0.0, 0)
+
+
+@pytest.mark.parametrize("year_span", [11.25, 30, 80, 150, 400, 800, 1500, 2500, 3500])
+# The range is limited to 11.25 at the bottom by if statements in
+# the _quarterly_finder() function
+def test_quarterly_finder(year_span):
+ vmin = -1000
+ vmax = vmin + year_span * 4
+ span = vmax - vmin + 1
+ if span < 45:
+ pytest.skip("the quarterly finder is only invoked if the span is >= 45")
+ nyears = span / 4
+ (min_anndef, maj_anndef) = converter._get_default_annual_spacing(nyears)
+ result = converter._quarterly_finder(vmin, vmax, "Q")
+ quarters = PeriodIndex(
+ arrays.PeriodArray(np.array([x[0] for x in result]), dtype="period[Q]")
+ )
+ majors = np.array([x[1] for x in result])
+ minors = np.array([x[2] for x in result])
+ major_quarters = quarters[majors]
+ minor_quarters = quarters[minors]
+ check_major_years = major_quarters.year % maj_anndef == 0
+ check_minor_years = minor_quarters.year % min_anndef == 0
+ check_major_quarters = major_quarters.quarter == 1
+ check_minor_quarters = minor_quarters.quarter == 1
+ assert np.all(check_major_years)
+ assert np.all(check_minor_years)
+ assert np.all(check_major_quarters)
+ assert np.all(check_minor_quarters)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_datetimelike.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_datetimelike.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3ae25ac9168f1041bea9b5de248b82b88a0b387
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_datetimelike.py
@@ -0,0 +1,1650 @@
+""" Test cases for time series specific (freq conversion, etc) """
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
+import pickle
+
+import numpy as np
+import pytest
+
+from pandas._libs.tslibs import (
+ BaseOffset,
+ to_offset,
+)
+
+from pandas import (
+ DataFrame,
+ Index,
+ NaT,
+ Series,
+ concat,
+ isna,
+ to_datetime,
+)
+import pandas._testing as tm
+from pandas.core.indexes.datetimes import (
+ DatetimeIndex,
+ bdate_range,
+ date_range,
+)
+from pandas.core.indexes.period import (
+ Period,
+ PeriodIndex,
+ period_range,
+)
+from pandas.core.indexes.timedeltas import timedelta_range
+from pandas.tests.plotting.common import _check_ticks_props
+
+from pandas.tseries.offsets import WeekOfMonth
+
+mpl = pytest.importorskip("matplotlib")
+
+
+class TestTSPlot:
+ @pytest.mark.filterwarnings("ignore::UserWarning")
+ def test_ts_plot_with_tz(self, tz_aware_fixture):
+ # GH2877, GH17173, GH31205, GH31580
+ tz = tz_aware_fixture
+ index = date_range("1/1/2011", periods=2, freq="H", tz=tz)
+ ts = Series([188.5, 328.25], index=index)
+ _check_plot_works(ts.plot)
+ ax = ts.plot()
+ xdata = next(iter(ax.get_lines())).get_xdata()
+ # Check first and last points' labels are correct
+ assert (xdata[0].hour, xdata[0].minute) == (0, 0)
+ assert (xdata[-1].hour, xdata[-1].minute) == (1, 0)
+
+ def test_fontsize_set_correctly(self):
+ # For issue #8765
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 9)), index=range(10)
+ )
+ _, ax = mpl.pyplot.subplots()
+ df.plot(fontsize=2, ax=ax)
+ for label in ax.get_xticklabels() + ax.get_yticklabels():
+ assert label.get_fontsize() == 2
+
+ def test_frame_inferred(self):
+ # inferred freq
+ idx = date_range("1/1/1987", freq="MS", periods=100)
+ idx = DatetimeIndex(idx.values, freq=None)
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx
+ )
+ _check_plot_works(df.plot)
+
+ # axes freq
+ idx = idx[0:40].union(idx[45:99])
+ df2 = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx
+ )
+ _check_plot_works(df2.plot)
+
+ def test_frame_inferred_n_gt_1(self):
+ # N > 1
+ idx = date_range("2008-1-1 00:15:00", freq="15T", periods=10)
+ idx = DatetimeIndex(idx.values, freq=None)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx
+ )
+ _check_plot_works(df.plot)
+
+ def test_is_error_nozeroindex(self):
+ # GH11858
+ i = np.array([1, 2, 3])
+ a = DataFrame(i, index=i)
+ _check_plot_works(a.plot, xerr=a)
+ _check_plot_works(a.plot, yerr=a)
+
+ def test_nonnumeric_exclude(self):
+ idx = date_range("1/1/1987", freq="A", periods=3)
+ df = DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]}, idx)
+
+ fig, ax = mpl.pyplot.subplots()
+ df.plot(ax=ax) # it works
+ assert len(ax.get_lines()) == 1 # B was plotted
+ mpl.pyplot.close(fig)
+
+ def test_nonnumeric_exclude_error(self):
+ idx = date_range("1/1/1987", freq="A", periods=3)
+ df = DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]}, idx)
+ msg = "no numeric data to plot"
+ with pytest.raises(TypeError, match=msg):
+ df["A"].plot()
+
+ @pytest.mark.parametrize("freq", ["S", "T", "H", "D", "W", "M", "Q", "A"])
+ def test_tsplot_period(self, freq):
+ idx = period_range("12/31/1999", freq=freq, periods=100)
+ ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
+ _, ax = mpl.pyplot.subplots()
+ _check_plot_works(ser.plot, ax=ax)
+
+ @pytest.mark.parametrize(
+ "freq", ["S", "T", "H", "D", "W", "M", "Q-DEC", "A", "1B30Min"]
+ )
+ def test_tsplot_datetime(self, freq):
+ idx = date_range("12/31/1999", freq=freq, periods=100)
+ ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
+ _, ax = mpl.pyplot.subplots()
+ _check_plot_works(ser.plot, ax=ax)
+
+ def test_tsplot(self):
+ ts = tm.makeTimeSeries()
+ _, ax = mpl.pyplot.subplots()
+ ts.plot(style="k", ax=ax)
+ color = (0.0, 0.0, 0.0, 1)
+ assert color == ax.get_lines()[0].get_color()
+
+ def test_both_style_and_color(self):
+ ts = tm.makeTimeSeries()
+ msg = (
+ "Cannot pass 'style' string with a color symbol and 'color' "
+ "keyword argument. Please use one or the other or pass 'style' "
+ "without a color symbol"
+ )
+ with pytest.raises(ValueError, match=msg):
+ ts.plot(style="b-", color="#000099")
+
+ s = ts.reset_index(drop=True)
+ with pytest.raises(ValueError, match=msg):
+ s.plot(style="b-", color="#000099")
+
+ @pytest.mark.parametrize("freq", ["ms", "us"])
+ def test_high_freq(self, freq):
+ _, ax = mpl.pyplot.subplots()
+ rng = date_range("1/1/2012", periods=100, freq=freq)
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _check_plot_works(ser.plot, ax=ax)
+
+ def test_get_datevalue(self):
+ from pandas.plotting._matplotlib.converter import get_datevalue
+
+ assert get_datevalue(None, "D") is None
+ assert get_datevalue(1987, "A") == 1987
+ assert get_datevalue(Period(1987, "A"), "M") == Period("1987-12", "M").ordinal
+ assert get_datevalue("1/1/1987", "D") == Period("1987-1-1", "D").ordinal
+
+ def test_ts_plot_format_coord(self):
+ def check_format_of_first_point(ax, expected_string):
+ first_line = ax.get_lines()[0]
+ first_x = first_line.get_xdata()[0].ordinal
+ first_y = first_line.get_ydata()[0]
+ assert expected_string == ax.format_coord(first_x, first_y)
+
+ annual = Series(1, index=date_range("2014-01-01", periods=3, freq="A-DEC"))
+ _, ax = mpl.pyplot.subplots()
+ annual.plot(ax=ax)
+ check_format_of_first_point(ax, "t = 2014 y = 1.000000")
+
+ # note this is added to the annual plot already in existence, and
+ # changes its freq field
+ daily = Series(1, index=date_range("2014-01-01", periods=3, freq="D"))
+ daily.plot(ax=ax)
+ check_format_of_first_point(ax, "t = 2014-01-01 y = 1.000000")
+
+ @pytest.mark.parametrize("freq", ["S", "T", "H", "D", "W", "M", "Q", "A"])
+ def test_line_plot_period_series(self, freq):
+ idx = period_range("12/31/1999", freq=freq, periods=100)
+ ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
+ _check_plot_works(ser.plot, ser.index.freq)
+
+ @pytest.mark.parametrize(
+ "frqncy", ["1S", "3S", "5T", "7H", "4D", "8W", "11M", "3A"]
+ )
+ def test_line_plot_period_mlt_series(self, frqncy):
+ # test period index line plot for series with multiples (`mlt`) of the
+ # frequency (`frqncy`) rule code. tests resolution of issue #14763
+ idx = period_range("12/31/1999", freq=frqncy, periods=100)
+ s = Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
+ _check_plot_works(s.plot, s.index.freq.rule_code)
+
+ @pytest.mark.parametrize(
+ "freq", ["S", "T", "H", "D", "W", "M", "Q-DEC", "A", "1B30Min"]
+ )
+ def test_line_plot_datetime_series(self, freq):
+ idx = date_range("12/31/1999", freq=freq, periods=100)
+ ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
+ _check_plot_works(ser.plot, ser.index.freq.rule_code)
+
+ @pytest.mark.parametrize("freq", ["S", "T", "H", "D", "W", "M", "Q", "A"])
+ def test_line_plot_period_frame(self, freq):
+ idx = date_range("12/31/1999", freq=freq, periods=100)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 3)),
+ index=idx,
+ columns=["A", "B", "C"],
+ )
+ _check_plot_works(df.plot, df.index.freq)
+
+ @pytest.mark.parametrize(
+ "frqncy", ["1S", "3S", "5T", "7H", "4D", "8W", "11M", "3A"]
+ )
+ def test_line_plot_period_mlt_frame(self, frqncy):
+ # test period index line plot for DataFrames with multiples (`mlt`)
+ # of the frequency (`frqncy`) rule code. tests resolution of issue
+ # #14763
+ idx = period_range("12/31/1999", freq=frqncy, periods=100)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 3)),
+ index=idx,
+ columns=["A", "B", "C"],
+ )
+ freq = df.index.asfreq(df.index.freq.rule_code).freq
+ _check_plot_works(df.plot, freq)
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ @pytest.mark.parametrize(
+ "freq", ["S", "T", "H", "D", "W", "M", "Q-DEC", "A", "1B30Min"]
+ )
+ def test_line_plot_datetime_frame(self, freq):
+ idx = date_range("12/31/1999", freq=freq, periods=100)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 3)),
+ index=idx,
+ columns=["A", "B", "C"],
+ )
+ freq = df.index.to_period(df.index.freq.rule_code).freq
+ _check_plot_works(df.plot, freq)
+
+ @pytest.mark.parametrize(
+ "freq", ["S", "T", "H", "D", "W", "M", "Q-DEC", "A", "1B30Min"]
+ )
+ def test_line_plot_inferred_freq(self, freq):
+ idx = date_range("12/31/1999", freq=freq, periods=100)
+ ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
+ ser = Series(ser.values, Index(np.asarray(ser.index)))
+ _check_plot_works(ser.plot, ser.index.inferred_freq)
+
+ ser = ser.iloc[[0, 3, 5, 6]]
+ _check_plot_works(ser.plot)
+
+ def test_fake_inferred_business(self):
+ _, ax = mpl.pyplot.subplots()
+ rng = date_range("2001-1-1", "2001-1-10")
+ ts = Series(range(len(rng)), index=rng)
+ ts = concat([ts[:3], ts[5:]])
+ ts.plot(ax=ax)
+ assert not hasattr(ax, "freq")
+
+ def test_plot_offset_freq(self):
+ ser = tm.makeTimeSeries()
+ _check_plot_works(ser.plot)
+
+ def test_plot_offset_freq_business(self):
+ dr = date_range("2023-01-01", freq="BQS", periods=10)
+ ser = Series(np.random.default_rng(2).standard_normal(len(dr)), index=dr)
+ _check_plot_works(ser.plot)
+
+ def test_plot_multiple_inferred_freq(self):
+ dr = Index([datetime(2000, 1, 1), datetime(2000, 1, 6), datetime(2000, 1, 11)])
+ ser = Series(np.random.default_rng(2).standard_normal(len(dr)), index=dr)
+ _check_plot_works(ser.plot)
+
+ @pytest.mark.xfail(reason="Api changed in 3.6.0")
+ def test_uhf(self):
+ import pandas.plotting._matplotlib.converter as conv
+
+ idx = date_range("2012-6-22 21:59:51.960928", freq="L", periods=500)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 2)), index=idx
+ )
+
+ _, ax = mpl.pyplot.subplots()
+ df.plot(ax=ax)
+ axis = ax.get_xaxis()
+
+ tlocs = axis.get_ticklocs()
+ tlabels = axis.get_ticklabels()
+ for loc, label in zip(tlocs, tlabels):
+ xp = conv._from_ordinal(loc).strftime("%H:%M:%S.%f")
+ rs = str(label.get_text())
+ if len(rs):
+ assert xp == rs
+
+ def test_irreg_hf(self):
+ idx = date_range("2012-6-22 21:59:51", freq="S", periods=10)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 2)), index=idx
+ )
+
+ irreg = df.iloc[[0, 1, 3, 4]]
+ _, ax = mpl.pyplot.subplots()
+ irreg.plot(ax=ax)
+ diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
+
+ sec = 1.0 / 24 / 60 / 60
+ assert (np.fabs(diffs[1:] - [sec, sec * 2, sec]) < 1e-8).all()
+
+ def test_irreg_hf_object(self):
+ idx = date_range("2012-6-22 21:59:51", freq="S", periods=10)
+ df2 = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 2)), index=idx
+ )
+ _, ax = mpl.pyplot.subplots()
+ df2.index = df2.index.astype(object)
+ df2.plot(ax=ax)
+ diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
+ sec = 1.0 / 24 / 60 / 60
+ assert (np.fabs(diffs[1:] - sec) < 1e-8).all()
+
+ def test_irregular_datetime64_repr_bug(self):
+ ser = tm.makeTimeSeries()
+ ser = ser.iloc[[0, 1, 2, 7]]
+
+ _, ax = mpl.pyplot.subplots()
+
+ ret = ser.plot(ax=ax)
+ assert ret is not None
+
+ for rs, xp in zip(ax.get_lines()[0].get_xdata(), ser.index):
+ assert rs == xp
+
+ def test_business_freq(self):
+ bts = tm.makePeriodSeries()
+ msg = r"PeriodDtype\[B\] is deprecated"
+ dt = bts.index[0].to_timestamp()
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ bts.index = period_range(start=dt, periods=len(bts), freq="B")
+ _, ax = mpl.pyplot.subplots()
+ bts.plot(ax=ax)
+ assert ax.get_lines()[0].get_xydata()[0, 0] == bts.index[0].ordinal
+ idx = ax.get_lines()[0].get_xdata()
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert PeriodIndex(data=idx).freqstr == "B"
+
+ def test_business_freq_convert(self):
+ bts = tm.makeTimeSeries(300).asfreq("BM")
+ ts = bts.to_period("M")
+ _, ax = mpl.pyplot.subplots()
+ bts.plot(ax=ax)
+ assert ax.get_lines()[0].get_xydata()[0, 0] == ts.index[0].ordinal
+ idx = ax.get_lines()[0].get_xdata()
+ assert PeriodIndex(data=idx).freqstr == "M"
+
+ def test_freq_with_no_period_alias(self):
+ # GH34487
+ freq = WeekOfMonth()
+ bts = tm.makeTimeSeries(5).asfreq(freq)
+ _, ax = mpl.pyplot.subplots()
+ bts.plot(ax=ax)
+
+ idx = ax.get_lines()[0].get_xdata()
+ msg = "freq not specified and cannot be inferred"
+ with pytest.raises(ValueError, match=msg):
+ PeriodIndex(data=idx)
+
+ def test_nonzero_base(self):
+ # GH2571
+ idx = date_range("2012-12-20", periods=24, freq="H") + timedelta(minutes=30)
+ df = DataFrame(np.arange(24), index=idx)
+ _, ax = mpl.pyplot.subplots()
+ df.plot(ax=ax)
+ rs = ax.get_lines()[0].get_xdata()
+ assert not Index(rs).is_normalized
+
+ def test_dataframe(self):
+ bts = DataFrame({"a": tm.makeTimeSeries()})
+ _, ax = mpl.pyplot.subplots()
+ bts.plot(ax=ax)
+ idx = ax.get_lines()[0].get_xdata()
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ tm.assert_index_equal(bts.index.to_period(), PeriodIndex(idx))
+
+ @pytest.mark.filterwarnings(
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
+ )
+ @pytest.mark.parametrize(
+ "obj",
+ [
+ tm.makeTimeSeries(),
+ DataFrame({"a": tm.makeTimeSeries(), "b": tm.makeTimeSeries() + 1}),
+ ],
+ )
+ def test_axis_limits(self, obj):
+ _, ax = mpl.pyplot.subplots()
+ obj.plot(ax=ax)
+ xlim = ax.get_xlim()
+ ax.set_xlim(xlim[0] - 5, xlim[1] + 10)
+ result = ax.get_xlim()
+ assert result[0] == xlim[0] - 5
+ assert result[1] == xlim[1] + 10
+
+ # string
+ expected = (Period("1/1/2000", ax.freq), Period("4/1/2000", ax.freq))
+ ax.set_xlim("1/1/2000", "4/1/2000")
+ result = ax.get_xlim()
+ assert int(result[0]) == expected[0].ordinal
+ assert int(result[1]) == expected[1].ordinal
+
+ # datetime
+ expected = (Period("1/1/2000", ax.freq), Period("4/1/2000", ax.freq))
+ ax.set_xlim(datetime(2000, 1, 1), datetime(2000, 4, 1))
+ result = ax.get_xlim()
+ assert int(result[0]) == expected[0].ordinal
+ assert int(result[1]) == expected[1].ordinal
+ fig = ax.get_figure()
+ mpl.pyplot.close(fig)
+
+ def test_get_finder(self):
+ import pandas.plotting._matplotlib.converter as conv
+
+ assert conv.get_finder(to_offset("B")) == conv._daily_finder
+ assert conv.get_finder(to_offset("D")) == conv._daily_finder
+ assert conv.get_finder(to_offset("M")) == conv._monthly_finder
+ assert conv.get_finder(to_offset("Q")) == conv._quarterly_finder
+ assert conv.get_finder(to_offset("A")) == conv._annual_finder
+ assert conv.get_finder(to_offset("W")) == conv._daily_finder
+
+ def test_finder_daily(self):
+ day_lst = [10, 40, 252, 400, 950, 2750, 10000]
+
+ msg = "Period with BDay freq is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ xpl1 = xpl2 = [Period("1999-1-1", freq="B").ordinal] * len(day_lst)
+ rs1 = []
+ rs2 = []
+ for n in day_lst:
+ rng = bdate_range("1999-1-1", periods=n)
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ser.plot(ax=ax)
+ xaxis = ax.get_xaxis()
+ rs1.append(xaxis.get_majorticklocs()[0])
+
+ vmin, vmax = ax.get_xlim()
+ ax.set_xlim(vmin + 0.9, vmax)
+ rs2.append(xaxis.get_majorticklocs()[0])
+ mpl.pyplot.close(ax.get_figure())
+
+ assert rs1 == xpl1
+ assert rs2 == xpl2
+
+ def test_finder_quarterly(self):
+ yrs = [3.5, 11]
+
+ xpl1 = xpl2 = [Period("1988Q1").ordinal] * len(yrs)
+ rs1 = []
+ rs2 = []
+ for n in yrs:
+ rng = period_range("1987Q2", periods=int(n * 4), freq="Q")
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ser.plot(ax=ax)
+ xaxis = ax.get_xaxis()
+ rs1.append(xaxis.get_majorticklocs()[0])
+
+ (vmin, vmax) = ax.get_xlim()
+ ax.set_xlim(vmin + 0.9, vmax)
+ rs2.append(xaxis.get_majorticklocs()[0])
+ mpl.pyplot.close(ax.get_figure())
+
+ assert rs1 == xpl1
+ assert rs2 == xpl2
+
+ def test_finder_monthly(self):
+ yrs = [1.15, 2.5, 4, 11]
+
+ xpl1 = xpl2 = [Period("Jan 1988").ordinal] * len(yrs)
+ rs1 = []
+ rs2 = []
+ for n in yrs:
+ rng = period_range("1987Q2", periods=int(n * 12), freq="M")
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ser.plot(ax=ax)
+ xaxis = ax.get_xaxis()
+ rs1.append(xaxis.get_majorticklocs()[0])
+
+ vmin, vmax = ax.get_xlim()
+ ax.set_xlim(vmin + 0.9, vmax)
+ rs2.append(xaxis.get_majorticklocs()[0])
+ mpl.pyplot.close(ax.get_figure())
+
+ assert rs1 == xpl1
+ assert rs2 == xpl2
+
+ def test_finder_monthly_long(self):
+ rng = period_range("1988Q1", periods=24 * 12, freq="M")
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ser.plot(ax=ax)
+ xaxis = ax.get_xaxis()
+ rs = xaxis.get_majorticklocs()[0]
+ xp = Period("1989Q1", "M").ordinal
+ assert rs == xp
+
+ def test_finder_annual(self):
+ xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170]
+ xp = [Period(x, freq="A").ordinal for x in xp]
+ rs = []
+ for nyears in [5, 10, 19, 49, 99, 199, 599, 1001]:
+ rng = period_range("1987", periods=nyears, freq="A")
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ser.plot(ax=ax)
+ xaxis = ax.get_xaxis()
+ rs.append(xaxis.get_majorticklocs()[0])
+ mpl.pyplot.close(ax.get_figure())
+
+ assert rs == xp
+
+ @pytest.mark.slow
+ def test_finder_minutely(self):
+ nminutes = 50 * 24 * 60
+ rng = date_range("1/1/1999", freq="Min", periods=nminutes)
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ser.plot(ax=ax)
+ xaxis = ax.get_xaxis()
+ rs = xaxis.get_majorticklocs()[0]
+ xp = Period("1/1/1999", freq="Min").ordinal
+
+ assert rs == xp
+
+ def test_finder_hourly(self):
+ nhours = 23
+ rng = date_range("1/1/1999", freq="H", periods=nhours)
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ser.plot(ax=ax)
+ xaxis = ax.get_xaxis()
+ rs = xaxis.get_majorticklocs()[0]
+ xp = Period("1/1/1999", freq="H").ordinal
+
+ assert rs == xp
+
+ def test_gaps(self):
+ ts = tm.makeTimeSeries()
+ ts.iloc[5:25] = np.nan
+ _, ax = mpl.pyplot.subplots()
+ ts.plot(ax=ax)
+ lines = ax.get_lines()
+ assert len(lines) == 1
+ line = lines[0]
+ data = line.get_xydata()
+
+ data = np.ma.MaskedArray(data, mask=isna(data), fill_value=np.nan)
+
+ assert isinstance(data, np.ma.core.MaskedArray)
+ mask = data.mask
+ assert mask[5:25, 1].all()
+ mpl.pyplot.close(ax.get_figure())
+
+ def test_gaps_irregular(self):
+ # irregular
+ ts = tm.makeTimeSeries()
+ ts = ts.iloc[[0, 1, 2, 5, 7, 9, 12, 15, 20]]
+ ts.iloc[2:5] = np.nan
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot(ax=ax)
+ lines = ax.get_lines()
+ assert len(lines) == 1
+ line = lines[0]
+ data = line.get_xydata()
+
+ data = np.ma.MaskedArray(data, mask=isna(data), fill_value=np.nan)
+
+ assert isinstance(data, np.ma.core.MaskedArray)
+ mask = data.mask
+ assert mask[2:5, 1].all()
+ mpl.pyplot.close(ax.get_figure())
+
+ def test_gaps_non_ts(self):
+ # non-ts
+ idx = [0, 1, 2, 5, 7, 9, 12, 15, 20]
+ ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
+ ser.iloc[2:5] = np.nan
+ _, ax = mpl.pyplot.subplots()
+ ser.plot(ax=ax)
+ lines = ax.get_lines()
+ assert len(lines) == 1
+ line = lines[0]
+ data = line.get_xydata()
+ data = np.ma.MaskedArray(data, mask=isna(data), fill_value=np.nan)
+
+ assert isinstance(data, np.ma.core.MaskedArray)
+ mask = data.mask
+ assert mask[2:5, 1].all()
+
+ def test_gap_upsample(self):
+ low = tm.makeTimeSeries()
+ low.iloc[5:25] = np.nan
+ _, ax = mpl.pyplot.subplots()
+ low.plot(ax=ax)
+
+ idxh = date_range(low.index[0], low.index[-1], freq="12h")
+ s = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
+ s.plot(secondary_y=True)
+ lines = ax.get_lines()
+ assert len(lines) == 1
+ assert len(ax.right_ax.get_lines()) == 1
+
+ line = lines[0]
+ data = line.get_xydata()
+ data = np.ma.MaskedArray(data, mask=isna(data), fill_value=np.nan)
+
+ assert isinstance(data, np.ma.core.MaskedArray)
+ mask = data.mask
+ assert mask[5:25, 1].all()
+
+ def test_secondary_y(self):
+ ser = Series(np.random.default_rng(2).standard_normal(10))
+ fig, _ = mpl.pyplot.subplots()
+ ax = ser.plot(secondary_y=True)
+ assert hasattr(ax, "left_ax")
+ assert not hasattr(ax, "right_ax")
+ axes = fig.get_axes()
+ line = ax.get_lines()[0]
+ xp = Series(line.get_ydata(), line.get_xdata())
+ tm.assert_series_equal(ser, xp)
+ assert ax.get_yaxis().get_ticks_position() == "right"
+ assert not axes[0].get_yaxis().get_visible()
+ mpl.pyplot.close(fig)
+
+ def test_secondary_y_yaxis(self):
+ Series(np.random.default_rng(2).standard_normal(10))
+ ser2 = Series(np.random.default_rng(2).standard_normal(10))
+ _, ax2 = mpl.pyplot.subplots()
+ ser2.plot(ax=ax2)
+ assert ax2.get_yaxis().get_ticks_position() == "left"
+ mpl.pyplot.close(ax2.get_figure())
+
+ def test_secondary_both(self):
+ ser = Series(np.random.default_rng(2).standard_normal(10))
+ ser2 = Series(np.random.default_rng(2).standard_normal(10))
+ ax = ser2.plot()
+ ax2 = ser.plot(secondary_y=True)
+ assert ax.get_yaxis().get_visible()
+ assert not hasattr(ax, "left_ax")
+ assert hasattr(ax, "right_ax")
+ assert hasattr(ax2, "left_ax")
+ assert not hasattr(ax2, "right_ax")
+
+ def test_secondary_y_ts(self):
+ idx = date_range("1/1/2000", periods=10)
+ ser = Series(np.random.default_rng(2).standard_normal(10), idx)
+ fig, _ = mpl.pyplot.subplots()
+ ax = ser.plot(secondary_y=True)
+ assert hasattr(ax, "left_ax")
+ assert not hasattr(ax, "right_ax")
+ axes = fig.get_axes()
+ line = ax.get_lines()[0]
+ xp = Series(line.get_ydata(), line.get_xdata()).to_timestamp()
+ tm.assert_series_equal(ser, xp)
+ assert ax.get_yaxis().get_ticks_position() == "right"
+ assert not axes[0].get_yaxis().get_visible()
+ mpl.pyplot.close(fig)
+
+ def test_secondary_y_ts_yaxis(self):
+ idx = date_range("1/1/2000", periods=10)
+ ser2 = Series(np.random.default_rng(2).standard_normal(10), idx)
+ _, ax2 = mpl.pyplot.subplots()
+ ser2.plot(ax=ax2)
+ assert ax2.get_yaxis().get_ticks_position() == "left"
+ mpl.pyplot.close(ax2.get_figure())
+
+ def test_secondary_y_ts_visible(self):
+ idx = date_range("1/1/2000", periods=10)
+ ser2 = Series(np.random.default_rng(2).standard_normal(10), idx)
+ ax = ser2.plot()
+ assert ax.get_yaxis().get_visible()
+
+ def test_secondary_kde(self):
+ pytest.importorskip("scipy")
+ ser = Series(np.random.default_rng(2).standard_normal(10))
+ fig, ax = mpl.pyplot.subplots()
+ ax = ser.plot(secondary_y=True, kind="density", ax=ax)
+ assert hasattr(ax, "left_ax")
+ assert not hasattr(ax, "right_ax")
+ axes = fig.get_axes()
+ assert axes[1].get_yaxis().get_ticks_position() == "right"
+
+ def test_secondary_bar(self):
+ ser = Series(np.random.default_rng(2).standard_normal(10))
+ fig, ax = mpl.pyplot.subplots()
+ ser.plot(secondary_y=True, kind="bar", ax=ax)
+ axes = fig.get_axes()
+ assert axes[1].get_yaxis().get_ticks_position() == "right"
+
+ def test_secondary_frame(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)), columns=["a", "b", "c"]
+ )
+ axes = df.plot(secondary_y=["a", "c"], subplots=True)
+ assert axes[0].get_yaxis().get_ticks_position() == "right"
+ assert axes[1].get_yaxis().get_ticks_position() == "left"
+ assert axes[2].get_yaxis().get_ticks_position() == "right"
+
+ def test_secondary_bar_frame(self):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)), columns=["a", "b", "c"]
+ )
+ axes = df.plot(kind="bar", secondary_y=["a", "c"], subplots=True)
+ assert axes[0].get_yaxis().get_ticks_position() == "right"
+ assert axes[1].get_yaxis().get_ticks_position() == "left"
+ assert axes[2].get_yaxis().get_ticks_position() == "right"
+
+ def test_mixed_freq_regular_first(self):
+ # TODO
+ s1 = tm.makeTimeSeries()
+ s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]]
+
+ # it works!
+ _, ax = mpl.pyplot.subplots()
+ s1.plot(ax=ax)
+
+ ax2 = s2.plot(style="g", ax=ax)
+ lines = ax2.get_lines()
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ idx1 = PeriodIndex(lines[0].get_xdata())
+ idx2 = PeriodIndex(lines[1].get_xdata())
+
+ tm.assert_index_equal(idx1, s1.index.to_period("B"))
+ tm.assert_index_equal(idx2, s2.index.to_period("B"))
+
+ left, right = ax2.get_xlim()
+ pidx = s1.index.to_period()
+ assert left <= pidx[0].ordinal
+ assert right >= pidx[-1].ordinal
+
+ def test_mixed_freq_irregular_first(self):
+ s1 = tm.makeTimeSeries()
+ s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]]
+ _, ax = mpl.pyplot.subplots()
+ s2.plot(style="g", ax=ax)
+ s1.plot(ax=ax)
+ assert not hasattr(ax, "freq")
+ lines = ax.get_lines()
+ x1 = lines[0].get_xdata()
+ tm.assert_numpy_array_equal(x1, s2.index.astype(object).values)
+ x2 = lines[1].get_xdata()
+ tm.assert_numpy_array_equal(x2, s1.index.astype(object).values)
+
+ def test_mixed_freq_regular_first_df(self):
+ # GH 9852
+ s1 = tm.makeTimeSeries().to_frame()
+ s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15], :]
+ _, ax = mpl.pyplot.subplots()
+ s1.plot(ax=ax)
+ ax2 = s2.plot(style="g", ax=ax)
+ lines = ax2.get_lines()
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ idx1 = PeriodIndex(lines[0].get_xdata())
+ idx2 = PeriodIndex(lines[1].get_xdata())
+ assert idx1.equals(s1.index.to_period("B"))
+ assert idx2.equals(s2.index.to_period("B"))
+ left, right = ax2.get_xlim()
+ pidx = s1.index.to_period()
+ assert left <= pidx[0].ordinal
+ assert right >= pidx[-1].ordinal
+
+ def test_mixed_freq_irregular_first_df(self):
+ # GH 9852
+ s1 = tm.makeTimeSeries().to_frame()
+ s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15], :]
+ _, ax = mpl.pyplot.subplots()
+ s2.plot(style="g", ax=ax)
+ s1.plot(ax=ax)
+ assert not hasattr(ax, "freq")
+ lines = ax.get_lines()
+ x1 = lines[0].get_xdata()
+ tm.assert_numpy_array_equal(x1, s2.index.astype(object).values)
+ x2 = lines[1].get_xdata()
+ tm.assert_numpy_array_equal(x2, s1.index.astype(object).values)
+
+ def test_mixed_freq_hf_first(self):
+ idxh = date_range("1/1/1999", periods=365, freq="D")
+ idxl = date_range("1/1/1999", periods=12, freq="M")
+ high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
+ low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
+ _, ax = mpl.pyplot.subplots()
+ high.plot(ax=ax)
+ low.plot(ax=ax)
+ for line in ax.get_lines():
+ assert PeriodIndex(data=line.get_xdata()).freq == "D"
+
+ def test_mixed_freq_alignment(self):
+ ts_ind = date_range("2012-01-01 13:00", "2012-01-02", freq="H")
+ ts_data = np.random.default_rng(2).standard_normal(12)
+
+ ts = Series(ts_data, index=ts_ind)
+ ts2 = ts.asfreq("T").interpolate()
+
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot(ax=ax)
+ ts2.plot(style="r", ax=ax)
+
+ assert ax.lines[0].get_xdata()[0] == ax.lines[1].get_xdata()[0]
+
+ def test_mixed_freq_lf_first(self):
+ idxh = date_range("1/1/1999", periods=365, freq="D")
+ idxl = date_range("1/1/1999", periods=12, freq="M")
+ high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
+ low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
+ _, ax = mpl.pyplot.subplots()
+ low.plot(legend=True, ax=ax)
+ high.plot(legend=True, ax=ax)
+ for line in ax.get_lines():
+ assert PeriodIndex(data=line.get_xdata()).freq == "D"
+ leg = ax.get_legend()
+ assert len(leg.texts) == 2
+ mpl.pyplot.close(ax.get_figure())
+
+ def test_mixed_freq_lf_first_hourly(self):
+ idxh = date_range("1/1/1999", periods=240, freq="T")
+ idxl = date_range("1/1/1999", periods=4, freq="H")
+ high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
+ low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
+ _, ax = mpl.pyplot.subplots()
+ low.plot(ax=ax)
+ high.plot(ax=ax)
+ for line in ax.get_lines():
+ assert PeriodIndex(data=line.get_xdata()).freq == "T"
+
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+ def test_mixed_freq_irreg_period(self):
+ ts = tm.makeTimeSeries()
+ irreg = ts.iloc[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]]
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ rng = period_range("1/3/2000", periods=30, freq="B")
+ ps = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _, ax = mpl.pyplot.subplots()
+ irreg.plot(ax=ax)
+ ps.plot(ax=ax)
+
+ def test_mixed_freq_shared_ax(self):
+ # GH13341, using sharex=True
+ idx1 = date_range("2015-01-01", periods=3, freq="M")
+ idx2 = idx1[:1].union(idx1[2:])
+ s1 = Series(range(len(idx1)), idx1)
+ s2 = Series(range(len(idx2)), idx2)
+
+ _, (ax1, ax2) = mpl.pyplot.subplots(nrows=2, sharex=True)
+ s1.plot(ax=ax1)
+ s2.plot(ax=ax2)
+
+ assert ax1.freq == "M"
+ assert ax2.freq == "M"
+ assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0]
+
+ def test_mixed_freq_shared_ax_twin_x(self):
+ # GH13341, using sharex=True
+ idx1 = date_range("2015-01-01", periods=3, freq="M")
+ idx2 = idx1[:1].union(idx1[2:])
+ s1 = Series(range(len(idx1)), idx1)
+ s2 = Series(range(len(idx2)), idx2)
+ # using twinx
+ _, ax1 = mpl.pyplot.subplots()
+ ax2 = ax1.twinx()
+ s1.plot(ax=ax1)
+ s2.plot(ax=ax2)
+
+ assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0]
+
+ @pytest.mark.xfail(reason="TODO (GH14330, GH14322)")
+ def test_mixed_freq_shared_ax_twin_x_irregular_first(self):
+ # GH13341, using sharex=True
+ idx1 = date_range("2015-01-01", periods=3, freq="M")
+ idx2 = idx1[:1].union(idx1[2:])
+ s1 = Series(range(len(idx1)), idx1)
+ s2 = Series(range(len(idx2)), idx2)
+ _, ax1 = mpl.pyplot.subplots()
+ ax2 = ax1.twinx()
+ s2.plot(ax=ax1)
+ s1.plot(ax=ax2)
+ assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0]
+
+ def test_nat_handling(self):
+ _, ax = mpl.pyplot.subplots()
+
+ dti = DatetimeIndex(["2015-01-01", NaT, "2015-01-03"])
+ s = Series(range(len(dti)), dti)
+ s.plot(ax=ax)
+ xdata = ax.get_lines()[0].get_xdata()
+ # plot x data is bounded by index values
+ assert s.index.min() <= Series(xdata).min()
+ assert Series(xdata).max() <= s.index.max()
+
+ def test_to_weekly_resampling(self):
+ idxh = date_range("1/1/1999", periods=52, freq="W")
+ idxl = date_range("1/1/1999", periods=12, freq="M")
+ high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
+ low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
+ _, ax = mpl.pyplot.subplots()
+ high.plot(ax=ax)
+ low.plot(ax=ax)
+ for line in ax.get_lines():
+ assert PeriodIndex(data=line.get_xdata()).freq == idxh.freq
+
+ def test_from_weekly_resampling(self):
+ idxh = date_range("1/1/1999", periods=52, freq="W")
+ idxl = date_range("1/1/1999", periods=12, freq="M")
+ high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
+ low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
+ _, ax = mpl.pyplot.subplots()
+ low.plot(ax=ax)
+ high.plot(ax=ax)
+
+ expected_h = idxh.to_period().asi8.astype(np.float64)
+ expected_l = np.array(
+ [1514, 1519, 1523, 1527, 1531, 1536, 1540, 1544, 1549, 1553, 1558, 1562],
+ dtype=np.float64,
+ )
+ for line in ax.get_lines():
+ assert PeriodIndex(data=line.get_xdata()).freq == idxh.freq
+ xdata = line.get_xdata(orig=False)
+ if len(xdata) == 12: # idxl lines
+ tm.assert_numpy_array_equal(xdata, expected_l)
+ else:
+ tm.assert_numpy_array_equal(xdata, expected_h)
+
+ @pytest.mark.parametrize("kind1, kind2", [("line", "area"), ("area", "line")])
+ def test_from_resampling_area_line_mixed(self, kind1, kind2):
+ idxh = date_range("1/1/1999", periods=52, freq="W")
+ idxl = date_range("1/1/1999", periods=12, freq="M")
+ high = DataFrame(
+ np.random.default_rng(2).random((len(idxh), 3)),
+ index=idxh,
+ columns=[0, 1, 2],
+ )
+ low = DataFrame(
+ np.random.default_rng(2).random((len(idxl), 3)),
+ index=idxl,
+ columns=[0, 1, 2],
+ )
+
+ _, ax = mpl.pyplot.subplots()
+ low.plot(kind=kind1, stacked=True, ax=ax)
+ high.plot(kind=kind2, stacked=True, ax=ax)
+
+ # check low dataframe result
+ expected_x = np.array(
+ [
+ 1514,
+ 1519,
+ 1523,
+ 1527,
+ 1531,
+ 1536,
+ 1540,
+ 1544,
+ 1549,
+ 1553,
+ 1558,
+ 1562,
+ ],
+ dtype=np.float64,
+ )
+ expected_y = np.zeros(len(expected_x), dtype=np.float64)
+ for i in range(3):
+ line = ax.lines[i]
+ assert PeriodIndex(line.get_xdata()).freq == idxh.freq
+ tm.assert_numpy_array_equal(line.get_xdata(orig=False), expected_x)
+ # check stacked values are correct
+ expected_y += low[i].values
+ tm.assert_numpy_array_equal(line.get_ydata(orig=False), expected_y)
+
+ # check high dataframe result
+ expected_x = idxh.to_period().asi8.astype(np.float64)
+ expected_y = np.zeros(len(expected_x), dtype=np.float64)
+ for i in range(3):
+ line = ax.lines[3 + i]
+ assert PeriodIndex(data=line.get_xdata()).freq == idxh.freq
+ tm.assert_numpy_array_equal(line.get_xdata(orig=False), expected_x)
+ expected_y += high[i].values
+ tm.assert_numpy_array_equal(line.get_ydata(orig=False), expected_y)
+
+ @pytest.mark.parametrize("kind1, kind2", [("line", "area"), ("area", "line")])
+ def test_from_resampling_area_line_mixed_high_to_low(self, kind1, kind2):
+ idxh = date_range("1/1/1999", periods=52, freq="W")
+ idxl = date_range("1/1/1999", periods=12, freq="M")
+ high = DataFrame(
+ np.random.default_rng(2).random((len(idxh), 3)),
+ index=idxh,
+ columns=[0, 1, 2],
+ )
+ low = DataFrame(
+ np.random.default_rng(2).random((len(idxl), 3)),
+ index=idxl,
+ columns=[0, 1, 2],
+ )
+ _, ax = mpl.pyplot.subplots()
+ high.plot(kind=kind1, stacked=True, ax=ax)
+ low.plot(kind=kind2, stacked=True, ax=ax)
+
+ # check high dataframe result
+ expected_x = idxh.to_period().asi8.astype(np.float64)
+ expected_y = np.zeros(len(expected_x), dtype=np.float64)
+ for i in range(3):
+ line = ax.lines[i]
+ assert PeriodIndex(data=line.get_xdata()).freq == idxh.freq
+ tm.assert_numpy_array_equal(line.get_xdata(orig=False), expected_x)
+ expected_y += high[i].values
+ tm.assert_numpy_array_equal(line.get_ydata(orig=False), expected_y)
+
+ # check low dataframe result
+ expected_x = np.array(
+ [
+ 1514,
+ 1519,
+ 1523,
+ 1527,
+ 1531,
+ 1536,
+ 1540,
+ 1544,
+ 1549,
+ 1553,
+ 1558,
+ 1562,
+ ],
+ dtype=np.float64,
+ )
+ expected_y = np.zeros(len(expected_x), dtype=np.float64)
+ for i in range(3):
+ lines = ax.lines[3 + i]
+ assert PeriodIndex(data=lines.get_xdata()).freq == idxh.freq
+ tm.assert_numpy_array_equal(lines.get_xdata(orig=False), expected_x)
+ expected_y += low[i].values
+ tm.assert_numpy_array_equal(lines.get_ydata(orig=False), expected_y)
+
+ def test_mixed_freq_second_millisecond(self):
+ # GH 7772, GH 7760
+ idxh = date_range("2014-07-01 09:00", freq="S", periods=50)
+ idxl = date_range("2014-07-01 09:00", freq="100L", periods=500)
+ high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
+ low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
+ # high to low
+ _, ax = mpl.pyplot.subplots()
+ high.plot(ax=ax)
+ low.plot(ax=ax)
+ assert len(ax.get_lines()) == 2
+ for line in ax.get_lines():
+ assert PeriodIndex(data=line.get_xdata()).freq == "L"
+
+ def test_mixed_freq_second_millisecond_low_to_high(self):
+ # GH 7772, GH 7760
+ idxh = date_range("2014-07-01 09:00", freq="S", periods=50)
+ idxl = date_range("2014-07-01 09:00", freq="100L", periods=500)
+ high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
+ low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
+ # low to high
+ _, ax = mpl.pyplot.subplots()
+ low.plot(ax=ax)
+ high.plot(ax=ax)
+ assert len(ax.get_lines()) == 2
+ for line in ax.get_lines():
+ assert PeriodIndex(data=line.get_xdata()).freq == "L"
+
+ def test_irreg_dtypes(self):
+ # date
+ idx = [date(2000, 1, 1), date(2000, 1, 5), date(2000, 1, 20)]
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((len(idx), 3)),
+ Index(idx, dtype=object),
+ )
+ _check_plot_works(df.plot)
+
+ def test_irreg_dtypes_dt64(self):
+ # np.datetime64
+ idx = date_range("1/1/2000", periods=10)
+ idx = idx[[0, 2, 5, 9]].astype(object)
+ df = DataFrame(np.random.default_rng(2).standard_normal((len(idx), 3)), idx)
+ _, ax = mpl.pyplot.subplots()
+ _check_plot_works(df.plot, ax=ax)
+
+ def test_time(self):
+ t = datetime(1, 1, 1, 3, 30, 0)
+ deltas = np.random.default_rng(2).integers(1, 20, 3).cumsum()
+ ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas])
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(len(ts)),
+ "b": np.random.default_rng(2).standard_normal(len(ts)),
+ },
+ index=ts,
+ )
+ _, ax = mpl.pyplot.subplots()
+ df.plot(ax=ax)
+
+ # verify tick labels
+ ticks = ax.get_xticks()
+ labels = ax.get_xticklabels()
+ for _tick, _label in zip(ticks, labels):
+ m, s = divmod(int(_tick), 60)
+ h, m = divmod(m, 60)
+ rs = _label.get_text()
+ if len(rs) > 0:
+ if s != 0:
+ xp = time(h, m, s).strftime("%H:%M:%S")
+ else:
+ xp = time(h, m, s).strftime("%H:%M")
+ assert xp == rs
+
+ def test_time_change_xlim(self):
+ t = datetime(1, 1, 1, 3, 30, 0)
+ deltas = np.random.default_rng(2).integers(1, 20, 3).cumsum()
+ ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas])
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(len(ts)),
+ "b": np.random.default_rng(2).standard_normal(len(ts)),
+ },
+ index=ts,
+ )
+ _, ax = mpl.pyplot.subplots()
+ df.plot(ax=ax)
+
+ # verify tick labels
+ ticks = ax.get_xticks()
+ labels = ax.get_xticklabels()
+ for _tick, _label in zip(ticks, labels):
+ m, s = divmod(int(_tick), 60)
+ h, m = divmod(m, 60)
+ rs = _label.get_text()
+ if len(rs) > 0:
+ if s != 0:
+ xp = time(h, m, s).strftime("%H:%M:%S")
+ else:
+ xp = time(h, m, s).strftime("%H:%M")
+ assert xp == rs
+
+ # change xlim
+ ax.set_xlim("1:30", "5:00")
+
+ # check tick labels again
+ ticks = ax.get_xticks()
+ labels = ax.get_xticklabels()
+ for _tick, _label in zip(ticks, labels):
+ m, s = divmod(int(_tick), 60)
+ h, m = divmod(m, 60)
+ rs = _label.get_text()
+ if len(rs) > 0:
+ if s != 0:
+ xp = time(h, m, s).strftime("%H:%M:%S")
+ else:
+ xp = time(h, m, s).strftime("%H:%M")
+ assert xp == rs
+
+ def test_time_musec(self):
+ t = datetime(1, 1, 1, 3, 30, 0)
+ deltas = np.random.default_rng(2).integers(1, 20, 3).cumsum()
+ ts = np.array([(t + timedelta(microseconds=int(x))).time() for x in deltas])
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(len(ts)),
+ "b": np.random.default_rng(2).standard_normal(len(ts)),
+ },
+ index=ts,
+ )
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot(ax=ax)
+
+ # verify tick labels
+ ticks = ax.get_xticks()
+ labels = ax.get_xticklabels()
+ for _tick, _label in zip(ticks, labels):
+ m, s = divmod(int(_tick), 60)
+
+ us = round((_tick - int(_tick)) * 1e6)
+
+ h, m = divmod(m, 60)
+ rs = _label.get_text()
+ if len(rs) > 0:
+ if (us % 1000) != 0:
+ xp = time(h, m, s, us).strftime("%H:%M:%S.%f")
+ elif (us // 1000) != 0:
+ xp = time(h, m, s, us).strftime("%H:%M:%S.%f")[:-3]
+ elif s != 0:
+ xp = time(h, m, s, us).strftime("%H:%M:%S")
+ else:
+ xp = time(h, m, s, us).strftime("%H:%M")
+ assert xp == rs
+
+ def test_secondary_upsample(self):
+ idxh = date_range("1/1/1999", periods=365, freq="D")
+ idxl = date_range("1/1/1999", periods=12, freq="M")
+ high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
+ low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
+ _, ax = mpl.pyplot.subplots()
+ low.plot(ax=ax)
+ ax = high.plot(secondary_y=True, ax=ax)
+ for line in ax.get_lines():
+ assert PeriodIndex(line.get_xdata()).freq == "D"
+ assert hasattr(ax, "left_ax")
+ assert not hasattr(ax, "right_ax")
+ for line in ax.left_ax.get_lines():
+ assert PeriodIndex(line.get_xdata()).freq == "D"
+
+ def test_secondary_legend(self):
+ fig = mpl.pyplot.figure()
+ ax = fig.add_subplot(211)
+
+ # ts
+ df = tm.makeTimeDataFrame()
+ df.plot(secondary_y=["A", "B"], ax=ax)
+ leg = ax.get_legend()
+ assert len(leg.get_lines()) == 4
+ assert leg.get_texts()[0].get_text() == "A (right)"
+ assert leg.get_texts()[1].get_text() == "B (right)"
+ assert leg.get_texts()[2].get_text() == "C"
+ assert leg.get_texts()[3].get_text() == "D"
+ assert ax.right_ax.get_legend() is None
+ colors = set()
+ for line in leg.get_lines():
+ colors.add(line.get_color())
+
+ # TODO: color cycle problems
+ assert len(colors) == 4
+ mpl.pyplot.close(fig)
+
+ def test_secondary_legend_right(self):
+ df = tm.makeTimeDataFrame()
+ fig = mpl.pyplot.figure()
+ ax = fig.add_subplot(211)
+ df.plot(secondary_y=["A", "C"], mark_right=False, ax=ax)
+ leg = ax.get_legend()
+ assert len(leg.get_lines()) == 4
+ assert leg.get_texts()[0].get_text() == "A"
+ assert leg.get_texts()[1].get_text() == "B"
+ assert leg.get_texts()[2].get_text() == "C"
+ assert leg.get_texts()[3].get_text() == "D"
+ mpl.pyplot.close(fig)
+
+ def test_secondary_legend_bar(self):
+ df = tm.makeTimeDataFrame()
+ fig, ax = mpl.pyplot.subplots()
+ df.plot(kind="bar", secondary_y=["A"], ax=ax)
+ leg = ax.get_legend()
+ assert leg.get_texts()[0].get_text() == "A (right)"
+ assert leg.get_texts()[1].get_text() == "B"
+ mpl.pyplot.close(fig)
+
+ def test_secondary_legend_bar_right(self):
+ df = tm.makeTimeDataFrame()
+ fig, ax = mpl.pyplot.subplots()
+ df.plot(kind="bar", secondary_y=["A"], mark_right=False, ax=ax)
+ leg = ax.get_legend()
+ assert leg.get_texts()[0].get_text() == "A"
+ assert leg.get_texts()[1].get_text() == "B"
+ mpl.pyplot.close(fig)
+
+ def test_secondary_legend_multi_col(self):
+ df = tm.makeTimeDataFrame()
+ fig = mpl.pyplot.figure()
+ ax = fig.add_subplot(211)
+ df = tm.makeTimeDataFrame()
+ ax = df.plot(secondary_y=["C", "D"], ax=ax)
+ leg = ax.get_legend()
+ assert len(leg.get_lines()) == 4
+ assert ax.right_ax.get_legend() is None
+ colors = set()
+ for line in leg.get_lines():
+ colors.add(line.get_color())
+
+ # TODO: color cycle problems
+ assert len(colors) == 4
+ mpl.pyplot.close(fig)
+
+ def test_secondary_legend_nonts(self):
+ # non-ts
+ df = tm.makeDataFrame()
+ fig = mpl.pyplot.figure()
+ ax = fig.add_subplot(211)
+ ax = df.plot(secondary_y=["A", "B"], ax=ax)
+ leg = ax.get_legend()
+ assert len(leg.get_lines()) == 4
+ assert ax.right_ax.get_legend() is None
+ colors = set()
+ for line in leg.get_lines():
+ colors.add(line.get_color())
+
+ # TODO: color cycle problems
+ assert len(colors) == 4
+ mpl.pyplot.close()
+
+ def test_secondary_legend_nonts_multi_col(self):
+ # non-ts
+ df = tm.makeDataFrame()
+ fig = mpl.pyplot.figure()
+ ax = fig.add_subplot(211)
+ ax = df.plot(secondary_y=["C", "D"], ax=ax)
+ leg = ax.get_legend()
+ assert len(leg.get_lines()) == 4
+ assert ax.right_ax.get_legend() is None
+ colors = set()
+ for line in leg.get_lines():
+ colors.add(line.get_color())
+
+ # TODO: color cycle problems
+ assert len(colors) == 4
+
+ @pytest.mark.xfail(reason="Api changed in 3.6.0")
+ def test_format_date_axis(self):
+ rng = date_range("1/1/2012", periods=12, freq="M")
+ df = DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot(ax=ax)
+ xaxis = ax.get_xaxis()
+ for line in xaxis.get_ticklabels():
+ if len(line.get_text()) > 0:
+ assert line.get_rotation() == 30
+
+ def test_ax_plot(self):
+ x = date_range(start="2012-01-02", periods=10, freq="D")
+ y = list(range(len(x)))
+ _, ax = mpl.pyplot.subplots()
+ lines = ax.plot(x, y, label="Y")
+ tm.assert_index_equal(DatetimeIndex(lines[0].get_xdata()), x)
+
+ def test_mpl_nopandas(self):
+ dates = [date(2008, 12, 31), date(2009, 1, 31)]
+ values1 = np.arange(10.0, 11.0, 0.5)
+ values2 = np.arange(11.0, 12.0, 0.5)
+
+ kw = {"fmt": "-", "lw": 4}
+
+ _, ax = mpl.pyplot.subplots()
+ ax.plot_date([x.toordinal() for x in dates], values1, **kw)
+ ax.plot_date([x.toordinal() for x in dates], values2, **kw)
+
+ line1, line2 = ax.get_lines()
+
+ exp = np.array([x.toordinal() for x in dates], dtype=np.float64)
+ tm.assert_numpy_array_equal(line1.get_xydata()[:, 0], exp)
+ exp = np.array([x.toordinal() for x in dates], dtype=np.float64)
+ tm.assert_numpy_array_equal(line2.get_xydata()[:, 0], exp)
+
+ def test_irregular_ts_shared_ax_xlim(self):
+ # GH 2960
+ from pandas.plotting._matplotlib.converter import DatetimeConverter
+
+ ts = tm.makeTimeSeries()[:20]
+ ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]]
+
+ # plot the left section of the irregular series, then the right section
+ _, ax = mpl.pyplot.subplots()
+ ts_irregular[:5].plot(ax=ax)
+ ts_irregular[5:].plot(ax=ax)
+
+ # check that axis limits are correct
+ left, right = ax.get_xlim()
+ assert left <= DatetimeConverter.convert(ts_irregular.index.min(), "", ax)
+ assert right >= DatetimeConverter.convert(ts_irregular.index.max(), "", ax)
+
+ def test_secondary_y_non_ts_xlim(self):
+ # GH 3490 - non-timeseries with secondary y
+ index_1 = [1, 2, 3, 4]
+ index_2 = [5, 6, 7, 8]
+ s1 = Series(1, index=index_1)
+ s2 = Series(2, index=index_2)
+
+ _, ax = mpl.pyplot.subplots()
+ s1.plot(ax=ax)
+ left_before, right_before = ax.get_xlim()
+ s2.plot(secondary_y=True, ax=ax)
+ left_after, right_after = ax.get_xlim()
+
+ assert left_before >= left_after
+ assert right_before < right_after
+
+ def test_secondary_y_regular_ts_xlim(self):
+ # GH 3490 - regular-timeseries with secondary y
+ index_1 = date_range(start="2000-01-01", periods=4, freq="D")
+ index_2 = date_range(start="2000-01-05", periods=4, freq="D")
+ s1 = Series(1, index=index_1)
+ s2 = Series(2, index=index_2)
+
+ _, ax = mpl.pyplot.subplots()
+ s1.plot(ax=ax)
+ left_before, right_before = ax.get_xlim()
+ s2.plot(secondary_y=True, ax=ax)
+ left_after, right_after = ax.get_xlim()
+
+ assert left_before >= left_after
+ assert right_before < right_after
+
+ def test_secondary_y_mixed_freq_ts_xlim(self):
+ # GH 3490 - mixed frequency timeseries with secondary y
+ rng = date_range("2000-01-01", periods=10000, freq="min")
+ ts = Series(1, index=rng)
+
+ _, ax = mpl.pyplot.subplots()
+ ts.plot(ax=ax)
+ left_before, right_before = ax.get_xlim()
+ ts.resample("D").mean().plot(secondary_y=True, ax=ax)
+ left_after, right_after = ax.get_xlim()
+
+ # a downsample should not have changed either limit
+ assert left_before == left_after
+ assert right_before == right_after
+
+ def test_secondary_y_irregular_ts_xlim(self):
+ # GH 3490 - irregular-timeseries with secondary y
+ from pandas.plotting._matplotlib.converter import DatetimeConverter
+
+ ts = tm.makeTimeSeries()[:20]
+ ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]]
+
+ _, ax = mpl.pyplot.subplots()
+ ts_irregular[:5].plot(ax=ax)
+ # plot higher-x values on secondary axis
+ ts_irregular[5:].plot(secondary_y=True, ax=ax)
+ # ensure secondary limits aren't overwritten by plot on primary
+ ts_irregular[:5].plot(ax=ax)
+
+ left, right = ax.get_xlim()
+ assert left <= DatetimeConverter.convert(ts_irregular.index.min(), "", ax)
+ assert right >= DatetimeConverter.convert(ts_irregular.index.max(), "", ax)
+
+ def test_plot_outofbounds_datetime(self):
+ # 2579 - checking this does not raise
+ values = [date(1677, 1, 1), date(1677, 1, 2)]
+ _, ax = mpl.pyplot.subplots()
+ ax.plot(values)
+
+ values = [datetime(1677, 1, 1, 12), datetime(1677, 1, 2, 12)]
+ ax.plot(values)
+
+ def test_format_timedelta_ticks_narrow(self):
+ expected_labels = [f"00:00:00.0000000{i:0>2d}" for i in np.arange(10)]
+
+ rng = timedelta_range("0", periods=10, freq="ns")
+ df = DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng)
+ _, ax = mpl.pyplot.subplots()
+ df.plot(fontsize=2, ax=ax)
+ mpl.pyplot.draw()
+ labels = ax.get_xticklabels()
+
+ result_labels = [x.get_text() for x in labels]
+ assert len(result_labels) == len(expected_labels)
+ assert result_labels == expected_labels
+
+ def test_format_timedelta_ticks_wide(self):
+ expected_labels = [
+ "00:00:00",
+ "1 days 03:46:40",
+ "2 days 07:33:20",
+ "3 days 11:20:00",
+ "4 days 15:06:40",
+ "5 days 18:53:20",
+ "6 days 22:40:00",
+ "8 days 02:26:40",
+ "9 days 06:13:20",
+ ]
+
+ rng = timedelta_range("0", periods=10, freq="1 d")
+ df = DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot(fontsize=2, ax=ax)
+ mpl.pyplot.draw()
+ labels = ax.get_xticklabels()
+
+ result_labels = [x.get_text() for x in labels]
+ assert len(result_labels) == len(expected_labels)
+ assert result_labels == expected_labels
+
+ def test_timedelta_plot(self):
+ # test issue #8711
+ s = Series(range(5), timedelta_range("1day", periods=5))
+ _, ax = mpl.pyplot.subplots()
+ _check_plot_works(s.plot, ax=ax)
+
+ def test_timedelta_long_period(self):
+ # test long period
+ index = timedelta_range("1 day 2 hr 30 min 10 s", periods=10, freq="1 d")
+ s = Series(np.random.default_rng(2).standard_normal(len(index)), index)
+ _, ax = mpl.pyplot.subplots()
+ _check_plot_works(s.plot, ax=ax)
+
+ def test_timedelta_short_period(self):
+ # test short period
+ index = timedelta_range("1 day 2 hr 30 min 10 s", periods=10, freq="1 ns")
+ s = Series(np.random.default_rng(2).standard_normal(len(index)), index)
+ _, ax = mpl.pyplot.subplots()
+ _check_plot_works(s.plot, ax=ax)
+
+ def test_hist(self):
+ # https://github.com/matplotlib/matplotlib/issues/8459
+ rng = date_range("1/1/2011", periods=10, freq="H")
+ x = rng
+ w1 = np.arange(0, 1, 0.1)
+ w2 = np.arange(0, 1, 0.1)[::-1]
+ _, ax = mpl.pyplot.subplots()
+ ax.hist([x, x], weights=[w1, w2])
+
+ def test_overlapping_datetime(self):
+ # GB 6608
+ s1 = Series(
+ [1, 2, 3],
+ index=[
+ datetime(1995, 12, 31),
+ datetime(2000, 12, 31),
+ datetime(2005, 12, 31),
+ ],
+ )
+ s2 = Series(
+ [1, 2, 3],
+ index=[
+ datetime(1997, 12, 31),
+ datetime(2003, 12, 31),
+ datetime(2008, 12, 31),
+ ],
+ )
+
+ # plot first series, then add the second series to those axes,
+ # then try adding the first series again
+ _, ax = mpl.pyplot.subplots()
+ s1.plot(ax=ax)
+ s2.plot(ax=ax)
+ s1.plot(ax=ax)
+
+ @pytest.mark.xfail(reason="GH9053 matplotlib does not use ax.xaxis.converter")
+ def test_add_matplotlib_datetime64(self):
+ # GH9053 - ensure that a plot with PeriodConverter still understands
+ # datetime64 data. This still fails because matplotlib overrides the
+ # ax.xaxis.converter with a DatetimeConverter
+ s = Series(
+ np.random.default_rng(2).standard_normal(10),
+ index=date_range("1970-01-02", periods=10),
+ )
+ ax = s.plot()
+ with tm.assert_produces_warning(DeprecationWarning):
+ # multi-dimensional indexing
+ ax.plot(s.index, s.values, color="g")
+ l1, l2 = ax.lines
+ tm.assert_numpy_array_equal(l1.get_xydata(), l2.get_xydata())
+
+ def test_matplotlib_scatter_datetime64(self):
+ # https://github.com/matplotlib/matplotlib/issues/11391
+ df = DataFrame(np.random.default_rng(2).random((10, 2)), columns=["x", "y"])
+ df["time"] = date_range("2018-01-01", periods=10, freq="D")
+ _, ax = mpl.pyplot.subplots()
+ ax.scatter(x="time", y="y", data=df)
+ mpl.pyplot.draw()
+ label = ax.get_xticklabels()[0]
+ expected = "2018-01-01"
+ assert label.get_text() == expected
+
+ def test_check_xticks_rot(self):
+ # https://github.com/pandas-dev/pandas/issues/29460
+ # regular time series
+ x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-03"])
+ df = DataFrame({"x": x, "y": [1, 2, 3]})
+ axes = df.plot(x="x", y="y")
+ _check_ticks_props(axes, xrot=0)
+
+ def test_check_xticks_rot_irregular(self):
+ # irregular time series
+ x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"])
+ df = DataFrame({"x": x, "y": [1, 2, 3]})
+ axes = df.plot(x="x", y="y")
+ _check_ticks_props(axes, xrot=30)
+
+ def test_check_xticks_rot_use_idx(self):
+ # irregular time series
+ x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"])
+ df = DataFrame({"x": x, "y": [1, 2, 3]})
+ # use timeseries index or not
+ axes = df.set_index("x").plot(y="y", use_index=True)
+ _check_ticks_props(axes, xrot=30)
+ axes = df.set_index("x").plot(y="y", use_index=False)
+ _check_ticks_props(axes, xrot=0)
+
+ def test_check_xticks_rot_sharex(self):
+ # irregular time series
+ x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"])
+ df = DataFrame({"x": x, "y": [1, 2, 3]})
+ # separate subplots
+ axes = df.plot(x="x", y="y", subplots=True, sharex=True)
+ _check_ticks_props(axes, xrot=30)
+ axes = df.plot(x="x", y="y", subplots=True, sharex=False)
+ _check_ticks_props(axes, xrot=0)
+
+
+def _check_plot_works(f, freq=None, series=None, *args, **kwargs):
+ import matplotlib.pyplot as plt
+
+ fig = plt.gcf()
+
+ try:
+ plt.clf()
+ ax = fig.add_subplot(211)
+ orig_ax = kwargs.pop("ax", plt.gca())
+ orig_axfreq = getattr(orig_ax, "freq", None)
+
+ ret = f(*args, **kwargs)
+ assert ret is not None # do something more intelligent
+
+ ax = kwargs.pop("ax", plt.gca())
+ if series is not None:
+ dfreq = series.index.freq
+ if isinstance(dfreq, BaseOffset):
+ dfreq = dfreq.rule_code
+ if orig_axfreq is None:
+ assert ax.freq == dfreq
+
+ if freq is not None and orig_axfreq is None:
+ assert ax.freq == freq
+
+ ax = fig.add_subplot(212)
+ kwargs["ax"] = ax
+ ret = f(*args, **kwargs)
+ assert ret is not None # TODO: do something more intelligent
+
+ with tm.ensure_clean(return_filelike=True) as path:
+ plt.savefig(path)
+
+ # GH18439, GH#24088, statsmodels#4772
+ with tm.ensure_clean(return_filelike=True) as path:
+ pickle.dump(fig, path)
+ finally:
+ plt.close(fig)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_groupby.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_groupby.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ebf93510a61549c838d91ab2e703f9db23fd626
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_groupby.py
@@ -0,0 +1,155 @@
+""" Test cases for GroupBy.plot """
+
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
+from pandas.tests.plotting.common import (
+ _check_axes_shape,
+ _check_legend_labels,
+)
+
+pytest.importorskip("matplotlib")
+
+
+class TestDataFrameGroupByPlots:
+ def test_series_groupby_plotting_nominally_works(self):
+ n = 10
+ weight = Series(np.random.default_rng(2).normal(166, 20, size=n))
+ gender = np.random.default_rng(2).choice(["male", "female"], size=n)
+
+ weight.groupby(gender).plot()
+
+ def test_series_groupby_plotting_nominally_works_hist(self):
+ n = 10
+ height = Series(np.random.default_rng(2).normal(60, 10, size=n))
+ gender = np.random.default_rng(2).choice(["male", "female"], size=n)
+ height.groupby(gender).hist()
+
+ def test_series_groupby_plotting_nominally_works_alpha(self):
+ n = 10
+ height = Series(np.random.default_rng(2).normal(60, 10, size=n))
+ gender = np.random.default_rng(2).choice(["male", "female"], size=n)
+ # Regression test for GH8733
+ height.groupby(gender).plot(alpha=0.5)
+
+ def test_plotting_with_float_index_works(self):
+ # GH 7025
+ df = DataFrame(
+ {
+ "def": [1, 1, 1, 2, 2, 2, 3, 3, 3],
+ "val": np.random.default_rng(2).standard_normal(9),
+ },
+ index=[1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0],
+ )
+
+ df.groupby("def")["val"].plot()
+
+ def test_plotting_with_float_index_works_apply(self):
+ # GH 7025
+ df = DataFrame(
+ {
+ "def": [1, 1, 1, 2, 2, 2, 3, 3, 3],
+ "val": np.random.default_rng(2).standard_normal(9),
+ },
+ index=[1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0],
+ )
+ df.groupby("def")["val"].apply(lambda x: x.plot())
+
+ def test_hist_single_row(self):
+ # GH10214
+ bins = np.arange(80, 100 + 2, 1)
+ df = DataFrame({"Name": ["AAA", "BBB"], "ByCol": [1, 2], "Mark": [85, 89]})
+ df["Mark"].hist(by=df["ByCol"], bins=bins)
+
+ def test_hist_single_row_single_bycol(self):
+ # GH10214
+ bins = np.arange(80, 100 + 2, 1)
+ df = DataFrame({"Name": ["AAA"], "ByCol": [1], "Mark": [85]})
+ df["Mark"].hist(by=df["ByCol"], bins=bins)
+
+ def test_plot_submethod_works(self):
+ df = DataFrame({"x": [1, 2, 3, 4, 5], "y": [1, 2, 3, 2, 1], "z": list("ababa")})
+ df.groupby("z").plot.scatter("x", "y")
+
+ def test_plot_submethod_works_line(self):
+ df = DataFrame({"x": [1, 2, 3, 4, 5], "y": [1, 2, 3, 2, 1], "z": list("ababa")})
+ df.groupby("z")["x"].plot.line()
+
+ def test_plot_kwargs(self):
+ df = DataFrame({"x": [1, 2, 3, 4, 5], "y": [1, 2, 3, 2, 1], "z": list("ababa")})
+
+ res = df.groupby("z").plot(kind="scatter", x="x", y="y")
+ # check that a scatter plot is effectively plotted: the axes should
+ # contain a PathCollection from the scatter plot (GH11805)
+ assert len(res["a"].collections) == 1
+
+ def test_plot_kwargs_scatter(self):
+ df = DataFrame({"x": [1, 2, 3, 4, 5], "y": [1, 2, 3, 2, 1], "z": list("ababa")})
+ res = df.groupby("z").plot.scatter(x="x", y="y")
+ assert len(res["a"].collections) == 1
+
+ @pytest.mark.parametrize("column, expected_axes_num", [(None, 2), ("b", 1)])
+ def test_groupby_hist_frame_with_legend(self, column, expected_axes_num):
+ # GH 6279 - DataFrameGroupBy histogram can have a legend
+ expected_layout = (1, expected_axes_num)
+ expected_labels = column or [["a"], ["b"]]
+
+ index = Index(15 * ["1"] + 15 * ["2"], name="c")
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 2)),
+ index=index,
+ columns=["a", "b"],
+ )
+ g = df.groupby("c")
+
+ for axes in g.hist(legend=True, column=column):
+ _check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout)
+ for ax, expected_label in zip(axes[0], expected_labels):
+ _check_legend_labels(ax, expected_label)
+
+ @pytest.mark.parametrize("column", [None, "b"])
+ def test_groupby_hist_frame_with_legend_raises(self, column):
+ # GH 6279 - DataFrameGroupBy histogram with legend and label raises
+ index = Index(15 * ["1"] + 15 * ["2"], name="c")
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 2)),
+ index=index,
+ columns=["a", "b"],
+ )
+ g = df.groupby("c")
+
+ with pytest.raises(ValueError, match="Cannot use both legend and label"):
+ g.hist(legend=True, column=column, label="d")
+
+ def test_groupby_hist_series_with_legend(self):
+ # GH 6279 - SeriesGroupBy histogram can have a legend
+ index = Index(15 * ["1"] + 15 * ["2"], name="c")
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 2)),
+ index=index,
+ columns=["a", "b"],
+ )
+ g = df.groupby("c")
+
+ for ax in g["a"].hist(legend=True):
+ _check_axes_shape(ax, axes_num=1, layout=(1, 1))
+ _check_legend_labels(ax, ["1", "2"])
+
+ def test_groupby_hist_series_with_legend_raises(self):
+ # GH 6279 - SeriesGroupBy histogram with legend and label raises
+ index = Index(15 * ["1"] + 15 * ["2"], name="c")
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 2)),
+ index=index,
+ columns=["a", "b"],
+ )
+ g = df.groupby("c")
+
+ with pytest.raises(ValueError, match="Cannot use both legend and label"):
+ g.hist(legend=True, label="d")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_hist_method.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_hist_method.py
new file mode 100644
index 0000000000000000000000000000000000000000..e38cd696a2d906c473f24a704e3a3e1339abc5da
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_hist_method.py
@@ -0,0 +1,966 @@
+""" Test cases for .hist method """
+import re
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ to_datetime,
+)
+import pandas._testing as tm
+from pandas.tests.plotting.common import (
+ _check_ax_scales,
+ _check_axes_shape,
+ _check_colors,
+ _check_legend_labels,
+ _check_patches_all_filled,
+ _check_plot_works,
+ _check_text_labels,
+ _check_ticks_props,
+ get_x_axis,
+ get_y_axis,
+)
+
+mpl = pytest.importorskip("matplotlib")
+
+
+@pytest.fixture
+def ts():
+ return tm.makeTimeSeries(name="ts")
+
+
+class TestSeriesPlots:
+ @pytest.mark.parametrize("kwargs", [{}, {"grid": False}, {"figsize": (8, 10)}])
+ def test_hist_legacy_kwargs(self, ts, kwargs):
+ _check_plot_works(ts.hist, **kwargs)
+
+ @pytest.mark.parametrize("kwargs", [{}, {"bins": 5}])
+ def test_hist_legacy_kwargs_warning(self, ts, kwargs):
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ _check_plot_works(ts.hist, by=ts.index.month, **kwargs)
+
+ def test_hist_legacy_ax(self, ts):
+ fig, ax = mpl.pyplot.subplots(1, 1)
+ _check_plot_works(ts.hist, ax=ax, default_axes=True)
+
+ def test_hist_legacy_ax_and_fig(self, ts):
+ fig, ax = mpl.pyplot.subplots(1, 1)
+ _check_plot_works(ts.hist, ax=ax, figure=fig, default_axes=True)
+
+ def test_hist_legacy_fig(self, ts):
+ fig, _ = mpl.pyplot.subplots(1, 1)
+ _check_plot_works(ts.hist, figure=fig, default_axes=True)
+
+ def test_hist_legacy_multi_ax(self, ts):
+ fig, (ax1, ax2) = mpl.pyplot.subplots(1, 2)
+ _check_plot_works(ts.hist, figure=fig, ax=ax1, default_axes=True)
+ _check_plot_works(ts.hist, figure=fig, ax=ax2, default_axes=True)
+
+ def test_hist_legacy_by_fig_error(self, ts):
+ fig, _ = mpl.pyplot.subplots(1, 1)
+ msg = (
+ "Cannot pass 'figure' when using the 'by' argument, since a new 'Figure' "
+ "instance will be created"
+ )
+ with pytest.raises(ValueError, match=msg):
+ ts.hist(by=ts.index, figure=fig)
+
+ def test_hist_bins_legacy(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+ ax = df.hist(bins=2)[0][0]
+ assert len(ax.patches) == 2
+
+ def test_hist_layout(self, hist_df):
+ df = hist_df
+ msg = "The 'layout' keyword is not supported when 'by' is None"
+ with pytest.raises(ValueError, match=msg):
+ df.height.hist(layout=(1, 1))
+
+ with pytest.raises(ValueError, match=msg):
+ df.height.hist(layout=[1, 1])
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "by, layout, axes_num, res_layout",
+ [
+ ["gender", (2, 1), 2, (2, 1)],
+ ["gender", (3, -1), 2, (3, 1)],
+ ["category", (4, 1), 4, (4, 1)],
+ ["category", (2, -1), 4, (2, 2)],
+ ["category", (3, -1), 4, (3, 2)],
+ ["category", (-1, 4), 4, (1, 4)],
+ ["classroom", (2, 2), 3, (2, 2)],
+ ],
+ )
+ def test_hist_layout_with_by(self, hist_df, by, layout, axes_num, res_layout):
+ df = hist_df
+
+ # _check_plot_works adds an `ax` kwarg to the method call
+ # so we get a warning about an axis being cleared, even
+ # though we don't explicing pass one, see GH #13188
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(df.height.hist, by=getattr(df, by), layout=layout)
+ _check_axes_shape(axes, axes_num=axes_num, layout=res_layout)
+
+ def test_hist_layout_with_by_shape(self, hist_df):
+ df = hist_df
+
+ axes = df.height.hist(by=df.category, layout=(4, 2), figsize=(12, 7))
+ _check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 7))
+
+ def test_hist_no_overlap(self):
+ from matplotlib.pyplot import (
+ gcf,
+ subplot,
+ )
+
+ x = Series(np.random.default_rng(2).standard_normal(2))
+ y = Series(np.random.default_rng(2).standard_normal(2))
+ subplot(121)
+ x.hist()
+ subplot(122)
+ y.hist()
+ fig = gcf()
+ axes = fig.axes
+ assert len(axes) == 2
+
+ def test_hist_by_no_extra_plots(self, hist_df):
+ df = hist_df
+ df.height.hist(by=df.gender)
+ assert len(mpl.pyplot.get_fignums()) == 1
+
+ def test_plot_fails_when_ax_differs_from_figure(self, ts):
+ from pylab import figure
+
+ fig1 = figure()
+ fig2 = figure()
+ ax1 = fig1.add_subplot(111)
+ msg = "passed axis not bound to passed figure"
+ with pytest.raises(AssertionError, match=msg):
+ ts.hist(ax=ax1, figure=fig2)
+
+ @pytest.mark.parametrize(
+ "histtype, expected",
+ [
+ ("bar", True),
+ ("barstacked", True),
+ ("step", False),
+ ("stepfilled", True),
+ ],
+ )
+ def test_histtype_argument(self, histtype, expected):
+ # GH23992 Verify functioning of histtype argument
+ ser = Series(np.random.default_rng(2).integers(1, 10))
+ ax = ser.hist(histtype=histtype)
+ _check_patches_all_filled(ax, filled=expected)
+
+ @pytest.mark.parametrize(
+ "by, expected_axes_num, expected_layout", [(None, 1, (1, 1)), ("b", 2, (1, 2))]
+ )
+ def test_hist_with_legend(self, by, expected_axes_num, expected_layout):
+ # GH 6279 - Series histogram can have a legend
+ index = 15 * ["1"] + 15 * ["2"]
+ s = Series(np.random.default_rng(2).standard_normal(30), index=index, name="a")
+ s.index.name = "b"
+
+ # Use default_axes=True when plotting method generate subplots itself
+ axes = _check_plot_works(s.hist, default_axes=True, legend=True, by=by)
+ _check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout)
+ _check_legend_labels(axes, "a")
+
+ @pytest.mark.parametrize("by", [None, "b"])
+ def test_hist_with_legend_raises(self, by):
+ # GH 6279 - Series histogram with legend and label raises
+ index = 15 * ["1"] + 15 * ["2"]
+ s = Series(np.random.default_rng(2).standard_normal(30), index=index, name="a")
+ s.index.name = "b"
+
+ with pytest.raises(ValueError, match="Cannot use both legend and label"):
+ s.hist(legend=True, by=by, label="c")
+
+ def test_hist_kwargs(self, ts):
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.hist(bins=5, ax=ax)
+ assert len(ax.patches) == 5
+ _check_text_labels(ax.yaxis.get_label(), "Frequency")
+
+ def test_hist_kwargs_horizontal(self, ts):
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.hist(bins=5, ax=ax)
+ ax = ts.plot.hist(orientation="horizontal", ax=ax)
+ _check_text_labels(ax.xaxis.get_label(), "Frequency")
+
+ def test_hist_kwargs_align(self, ts):
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.hist(bins=5, ax=ax)
+ ax = ts.plot.hist(align="left", stacked=True, ax=ax)
+
+ @pytest.mark.xfail(reason="Api changed in 3.6.0")
+ def test_hist_kde(self, ts):
+ pytest.importorskip("scipy")
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.hist(logy=True, ax=ax)
+ _check_ax_scales(ax, yaxis="log")
+ xlabels = ax.get_xticklabels()
+ # ticks are values, thus ticklabels are blank
+ _check_text_labels(xlabels, [""] * len(xlabels))
+ ylabels = ax.get_yticklabels()
+ _check_text_labels(ylabels, [""] * len(ylabels))
+
+ def test_hist_kde_plot_works(self, ts):
+ pytest.importorskip("scipy")
+ _check_plot_works(ts.plot.kde)
+
+ def test_hist_kde_density_works(self, ts):
+ pytest.importorskip("scipy")
+ _check_plot_works(ts.plot.density)
+
+ @pytest.mark.xfail(reason="Api changed in 3.6.0")
+ def test_hist_kde_logy(self, ts):
+ pytest.importorskip("scipy")
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.kde(logy=True, ax=ax)
+ _check_ax_scales(ax, yaxis="log")
+ xlabels = ax.get_xticklabels()
+ _check_text_labels(xlabels, [""] * len(xlabels))
+ ylabels = ax.get_yticklabels()
+ _check_text_labels(ylabels, [""] * len(ylabels))
+
+ def test_hist_kde_color_bins(self, ts):
+ pytest.importorskip("scipy")
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.hist(logy=True, bins=10, color="b", ax=ax)
+ _check_ax_scales(ax, yaxis="log")
+ assert len(ax.patches) == 10
+ _check_colors(ax.patches, facecolors=["b"] * 10)
+
+ def test_hist_kde_color(self, ts):
+ pytest.importorskip("scipy")
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.kde(logy=True, color="r", ax=ax)
+ _check_ax_scales(ax, yaxis="log")
+ lines = ax.get_lines()
+ assert len(lines) == 1
+ _check_colors(lines, ["r"])
+
+
+class TestDataFramePlots:
+ @pytest.mark.slow
+ def test_hist_df_legacy(self, hist_df):
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ _check_plot_works(hist_df.hist)
+
+ @pytest.mark.slow
+ def test_hist_df_legacy_layout(self):
+ # make sure layout is handled
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+ df[2] = to_datetime(
+ np.random.default_rng(2).integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(df.hist, grid=False)
+ _check_axes_shape(axes, axes_num=3, layout=(2, 2))
+ assert not axes[1, 1].get_visible()
+
+ _check_plot_works(df[[2]].hist)
+
+ @pytest.mark.slow
+ def test_hist_df_legacy_layout2(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 1)))
+ _check_plot_works(df.hist)
+
+ @pytest.mark.slow
+ def test_hist_df_legacy_layout3(self):
+ # make sure layout is handled
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
+ df[5] = to_datetime(
+ np.random.default_rng(2).integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(df.hist, layout=(4, 2))
+ _check_axes_shape(axes, axes_num=6, layout=(4, 2))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "kwargs", [{"sharex": True, "sharey": True}, {"figsize": (8, 10)}, {"bins": 5}]
+ )
+ def test_hist_df_legacy_layout_kwargs(self, kwargs):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
+ df[5] = to_datetime(
+ np.random.default_rng(2).integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ # make sure sharex, sharey is handled
+ # handle figsize arg
+ # check bins argument
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ _check_plot_works(df.hist, **kwargs)
+
+ @pytest.mark.slow
+ def test_hist_df_legacy_layout_labelsize_rot(self, frame_or_series):
+ # make sure xlabelsize and xrot are handled
+ obj = frame_or_series(range(10))
+ xf, yf = 20, 18
+ xrot, yrot = 30, 40
+ axes = obj.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
+ _check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
+
+ @pytest.mark.slow
+ def test_hist_df_legacy_rectangles(self):
+ from matplotlib.patches import Rectangle
+
+ ser = Series(range(10))
+ ax = ser.hist(cumulative=True, bins=4, density=True)
+ # height of last bin (index 5) must be 1.0
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
+ tm.assert_almost_equal(rects[-1].get_height(), 1.0)
+
+ @pytest.mark.slow
+ def test_hist_df_legacy_scale(self):
+ ser = Series(range(10))
+ ax = ser.hist(log=True)
+ # scale of y must be 'log'
+ _check_ax_scales(ax, yaxis="log")
+
+ @pytest.mark.slow
+ def test_hist_df_legacy_external_error(self):
+ ser = Series(range(10))
+ # propagate attr exception from matplotlib.Axes.hist
+ with tm.external_error_raised(AttributeError):
+ ser.hist(foo="bar")
+
+ def test_hist_non_numerical_or_datetime_raises(self):
+ # gh-10444, GH32590
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).random(10),
+ "b": np.random.default_rng(2).integers(0, 10, 10),
+ "c": to_datetime(
+ np.random.default_rng(2).integers(
+ 1582800000000000000, 1583500000000000000, 10, dtype=np.int64
+ )
+ ),
+ "d": to_datetime(
+ np.random.default_rng(2).integers(
+ 1582800000000000000, 1583500000000000000, 10, dtype=np.int64
+ ),
+ utc=True,
+ ),
+ }
+ )
+ df_o = df.astype(object)
+
+ msg = "hist method requires numerical or datetime columns, nothing to plot."
+ with pytest.raises(ValueError, match=msg):
+ df_o.hist()
+
+ @pytest.mark.parametrize(
+ "layout_test",
+ (
+ {"layout": None, "expected_size": (2, 2)}, # default is 2x2
+ {"layout": (2, 2), "expected_size": (2, 2)},
+ {"layout": (4, 1), "expected_size": (4, 1)},
+ {"layout": (1, 4), "expected_size": (1, 4)},
+ {"layout": (3, 3), "expected_size": (3, 3)},
+ {"layout": (-1, 4), "expected_size": (1, 4)},
+ {"layout": (4, -1), "expected_size": (4, 1)},
+ {"layout": (-1, 2), "expected_size": (2, 2)},
+ {"layout": (2, -1), "expected_size": (2, 2)},
+ ),
+ )
+ def test_hist_layout(self, layout_test):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+ df[2] = to_datetime(
+ np.random.default_rng(2).integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ axes = df.hist(layout=layout_test["layout"])
+ expected = layout_test["expected_size"]
+ _check_axes_shape(axes, axes_num=3, layout=expected)
+
+ def test_hist_layout_error(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+ df[2] = to_datetime(
+ np.random.default_rng(2).integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ # layout too small for all 4 plots
+ msg = "Layout of 1x1 must be larger than required size 3"
+ with pytest.raises(ValueError, match=msg):
+ df.hist(layout=(1, 1))
+
+ # invalid format for layout
+ msg = re.escape("Layout must be a tuple of (rows, columns)")
+ with pytest.raises(ValueError, match=msg):
+ df.hist(layout=(1,))
+ msg = "At least one dimension of layout must be positive"
+ with pytest.raises(ValueError, match=msg):
+ df.hist(layout=(-1, -1))
+
+ # GH 9351
+ def test_tight_layout(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((100, 2)))
+ df[2] = to_datetime(
+ np.random.default_rng(2).integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=100,
+ dtype=np.int64,
+ )
+ )
+ # Use default_axes=True when plotting method generate subplots itself
+ _check_plot_works(df.hist, default_axes=True)
+ mpl.pyplot.tight_layout()
+
+ def test_hist_subplot_xrot(self):
+ # GH 30288
+ df = DataFrame(
+ {
+ "length": [1.5, 0.5, 1.2, 0.9, 3],
+ "animal": ["pig", "rabbit", "pig", "pig", "rabbit"],
+ }
+ )
+ # Use default_axes=True when plotting method generate subplots itself
+ axes = _check_plot_works(
+ df.hist,
+ default_axes=True,
+ column="length",
+ by="animal",
+ bins=5,
+ xrot=0,
+ )
+ _check_ticks_props(axes, xrot=0)
+
+ @pytest.mark.parametrize(
+ "column, expected",
+ [
+ (None, ["width", "length", "height"]),
+ (["length", "width", "height"], ["length", "width", "height"]),
+ ],
+ )
+ def test_hist_column_order_unchanged(self, column, expected):
+ # GH29235
+
+ df = DataFrame(
+ {
+ "width": [0.7, 0.2, 0.15, 0.2, 1.1],
+ "length": [1.5, 0.5, 1.2, 0.9, 3],
+ "height": [3, 0.5, 3.4, 2, 1],
+ },
+ index=["pig", "rabbit", "duck", "chicken", "horse"],
+ )
+
+ # Use default_axes=True when plotting method generate subplots itself
+ axes = _check_plot_works(
+ df.hist,
+ default_axes=True,
+ column=column,
+ layout=(1, 3),
+ )
+ result = [axes[0, i].get_title() for i in range(3)]
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "histtype, expected",
+ [
+ ("bar", True),
+ ("barstacked", True),
+ ("step", False),
+ ("stepfilled", True),
+ ],
+ )
+ def test_histtype_argument(self, histtype, expected):
+ # GH23992 Verify functioning of histtype argument
+ df = DataFrame(
+ np.random.default_rng(2).integers(1, 10, size=(100, 2)), columns=["a", "b"]
+ )
+ ax = df.hist(histtype=histtype)
+ _check_patches_all_filled(ax, filled=expected)
+
+ @pytest.mark.parametrize("by", [None, "c"])
+ @pytest.mark.parametrize("column", [None, "b"])
+ def test_hist_with_legend(self, by, column):
+ # GH 6279 - DataFrame histogram can have a legend
+ expected_axes_num = 1 if by is None and column is not None else 2
+ expected_layout = (1, expected_axes_num)
+ expected_labels = column or ["a", "b"]
+ if by is not None:
+ expected_labels = [expected_labels] * 2
+
+ index = Index(15 * ["1"] + 15 * ["2"], name="c")
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 2)),
+ index=index,
+ columns=["a", "b"],
+ )
+
+ # Use default_axes=True when plotting method generate subplots itself
+ axes = _check_plot_works(
+ df.hist,
+ default_axes=True,
+ legend=True,
+ by=by,
+ column=column,
+ )
+
+ _check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout)
+ if by is None and column is None:
+ axes = axes[0]
+ for expected_label, ax in zip(expected_labels, axes):
+ _check_legend_labels(ax, expected_label)
+
+ @pytest.mark.parametrize("by", [None, "c"])
+ @pytest.mark.parametrize("column", [None, "b"])
+ def test_hist_with_legend_raises(self, by, column):
+ # GH 6279 - DataFrame histogram with legend and label raises
+ index = Index(15 * ["1"] + 15 * ["2"], name="c")
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 2)),
+ index=index,
+ columns=["a", "b"],
+ )
+
+ with pytest.raises(ValueError, match="Cannot use both legend and label"):
+ df.hist(legend=True, by=by, column=column, label="d")
+
+ def test_hist_df_kwargs(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot.hist(bins=5, ax=ax)
+ assert len(ax.patches) == 10
+
+ def test_hist_df_with_nonnumerics(self):
+ # GH 9853
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)),
+ columns=["A", "B", "C", "D"],
+ )
+ df["E"] = ["x", "y"] * 5
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot.hist(bins=5, ax=ax)
+ assert len(ax.patches) == 20
+
+ def test_hist_df_with_nonnumerics_no_bins(self):
+ # GH 9853
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((10, 4)),
+ columns=["A", "B", "C", "D"],
+ )
+ df["E"] = ["x", "y"] * 5
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot.hist(ax=ax) # bins=10
+ assert len(ax.patches) == 40
+
+ def test_hist_secondary_legend(self):
+ # GH 9610
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd")
+ )
+
+ # primary -> secondary
+ _, ax = mpl.pyplot.subplots()
+ ax = df["a"].plot.hist(legend=True, ax=ax)
+ df["b"].plot.hist(ax=ax, legend=True, secondary_y=True)
+ # both legends are drawn on left ax
+ # left and right axis must be visible
+ _check_legend_labels(ax, labels=["a", "b (right)"])
+ assert ax.get_yaxis().get_visible()
+ assert ax.right_ax.get_yaxis().get_visible()
+
+ def test_hist_secondary_secondary(self):
+ # GH 9610
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd")
+ )
+ # secondary -> secondary
+ _, ax = mpl.pyplot.subplots()
+ ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax)
+ df["b"].plot.hist(ax=ax, legend=True, secondary_y=True)
+ # both legends are draw on left ax
+ # left axis must be invisible, right axis must be visible
+ _check_legend_labels(ax.left_ax, labels=["a (right)", "b (right)"])
+ assert not ax.left_ax.get_yaxis().get_visible()
+ assert ax.get_yaxis().get_visible()
+
+ def test_hist_secondary_primary(self):
+ # GH 9610
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd")
+ )
+ # secondary -> primary
+ _, ax = mpl.pyplot.subplots()
+ ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax)
+ # right axes is returned
+ df["b"].plot.hist(ax=ax, legend=True)
+ # both legends are draw on left ax
+ # left and right axis must be visible
+ _check_legend_labels(ax.left_ax, labels=["a (right)", "b"])
+ assert ax.left_ax.get_yaxis().get_visible()
+ assert ax.get_yaxis().get_visible()
+
+ def test_hist_with_nans_and_weights(self):
+ # GH 48884
+ mpl_patches = pytest.importorskip("matplotlib.patches")
+ df = DataFrame(
+ [[np.nan, 0.2, 0.3], [0.4, np.nan, np.nan], [0.7, 0.8, 0.9]],
+ columns=list("abc"),
+ )
+ weights = np.array([0.25, 0.3, 0.45])
+ no_nan_df = DataFrame([[0.4, 0.2, 0.3], [0.7, 0.8, 0.9]], columns=list("abc"))
+ no_nan_weights = np.array([[0.3, 0.25, 0.25], [0.45, 0.45, 0.45]])
+
+ _, ax0 = mpl.pyplot.subplots()
+ df.plot.hist(ax=ax0, weights=weights)
+ rects = [x for x in ax0.get_children() if isinstance(x, mpl_patches.Rectangle)]
+ heights = [rect.get_height() for rect in rects]
+ _, ax1 = mpl.pyplot.subplots()
+ no_nan_df.plot.hist(ax=ax1, weights=no_nan_weights)
+ no_nan_rects = [
+ x for x in ax1.get_children() if isinstance(x, mpl_patches.Rectangle)
+ ]
+ no_nan_heights = [rect.get_height() for rect in no_nan_rects]
+ assert all(h0 == h1 for h0, h1 in zip(heights, no_nan_heights))
+
+ idxerror_weights = np.array([[0.3, 0.25], [0.45, 0.45]])
+
+ msg = "weights must have the same shape as data, or be a single column"
+ with pytest.raises(ValueError, match=msg):
+ _, ax2 = mpl.pyplot.subplots()
+ no_nan_df.plot.hist(ax=ax2, weights=idxerror_weights)
+
+
+class TestDataFrameGroupByPlots:
+ def test_grouped_hist_legacy(self):
+ from pandas.plotting._matplotlib.hist import _grouped_hist
+
+ rs = np.random.default_rng(10)
+ df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
+ df["B"] = to_datetime(
+ rs.integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ df["C"] = rs.integers(0, 4, 10)
+ df["D"] = ["X"] * 10
+
+ axes = _grouped_hist(df.A, by=df.C)
+ _check_axes_shape(axes, axes_num=4, layout=(2, 2))
+
+ def test_grouped_hist_legacy_axes_shape_no_col(self):
+ rs = np.random.default_rng(10)
+ df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
+ df["B"] = to_datetime(
+ rs.integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ df["C"] = rs.integers(0, 4, 10)
+ df["D"] = ["X"] * 10
+ axes = df.hist(by=df.C)
+ _check_axes_shape(axes, axes_num=4, layout=(2, 2))
+
+ def test_grouped_hist_legacy_single_key(self):
+ rs = np.random.default_rng(2)
+ df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
+ df["B"] = to_datetime(
+ rs.integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ df["C"] = rs.integers(0, 4, 10)
+ df["D"] = ["X"] * 10
+ # group by a key with single value
+ axes = df.hist(by="D", rot=30)
+ _check_axes_shape(axes, axes_num=1, layout=(1, 1))
+ _check_ticks_props(axes, xrot=30)
+
+ def test_grouped_hist_legacy_grouped_hist_kwargs(self):
+ from matplotlib.patches import Rectangle
+
+ from pandas.plotting._matplotlib.hist import _grouped_hist
+
+ rs = np.random.default_rng(2)
+ df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
+ df["B"] = to_datetime(
+ rs.integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ df["C"] = rs.integers(0, 4, 10)
+ # make sure kwargs to hist are handled
+ xf, yf = 20, 18
+ xrot, yrot = 30, 40
+
+ axes = _grouped_hist(
+ df.A,
+ by=df.C,
+ cumulative=True,
+ bins=4,
+ xlabelsize=xf,
+ xrot=xrot,
+ ylabelsize=yf,
+ yrot=yrot,
+ density=True,
+ )
+ # height of last bin (index 5) must be 1.0
+ for ax in axes.ravel():
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
+ height = rects[-1].get_height()
+ tm.assert_almost_equal(height, 1.0)
+ _check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
+
+ def test_grouped_hist_legacy_grouped_hist(self):
+ from pandas.plotting._matplotlib.hist import _grouped_hist
+
+ rs = np.random.default_rng(2)
+ df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
+ df["B"] = to_datetime(
+ rs.integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ df["C"] = rs.integers(0, 4, 10)
+ df["D"] = ["X"] * 10
+ axes = _grouped_hist(df.A, by=df.C, log=True)
+ # scale of y must be 'log'
+ _check_ax_scales(axes, yaxis="log")
+
+ def test_grouped_hist_legacy_external_err(self):
+ from pandas.plotting._matplotlib.hist import _grouped_hist
+
+ rs = np.random.default_rng(2)
+ df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
+ df["B"] = to_datetime(
+ rs.integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ df["C"] = rs.integers(0, 4, 10)
+ df["D"] = ["X"] * 10
+ # propagate attr exception from matplotlib.Axes.hist
+ with tm.external_error_raised(AttributeError):
+ _grouped_hist(df.A, by=df.C, foo="bar")
+
+ def test_grouped_hist_legacy_figsize_err(self):
+ rs = np.random.default_rng(2)
+ df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
+ df["B"] = to_datetime(
+ rs.integers(
+ 812419200000000000,
+ 819331200000000000,
+ size=10,
+ dtype=np.int64,
+ )
+ )
+ df["C"] = rs.integers(0, 4, 10)
+ df["D"] = ["X"] * 10
+ msg = "Specify figure size by tuple instead"
+ with pytest.raises(ValueError, match=msg):
+ df.hist(by="C", figsize="default")
+
+ def test_grouped_hist_legacy2(self):
+ n = 10
+ weight = Series(np.random.default_rng(2).normal(166, 20, size=n))
+ height = Series(np.random.default_rng(2).normal(60, 10, size=n))
+ gender_int = np.random.default_rng(2).choice([0, 1], size=n)
+ df_int = DataFrame({"height": height, "weight": weight, "gender": gender_int})
+ gb = df_int.groupby("gender")
+ axes = gb.hist()
+ assert len(axes) == 2
+ assert len(mpl.pyplot.get_fignums()) == 2
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "msg, plot_col, by_col, layout",
+ [
+ [
+ "Layout of 1x1 must be larger than required size 2",
+ "weight",
+ "gender",
+ (1, 1),
+ ],
+ [
+ "Layout of 1x3 must be larger than required size 4",
+ "height",
+ "category",
+ (1, 3),
+ ],
+ [
+ "At least one dimension of layout must be positive",
+ "height",
+ "category",
+ (-1, -1),
+ ],
+ ],
+ )
+ def test_grouped_hist_layout_error(self, hist_df, msg, plot_col, by_col, layout):
+ df = hist_df
+ with pytest.raises(ValueError, match=msg):
+ df.hist(column=plot_col, by=getattr(df, by_col), layout=layout)
+
+ @pytest.mark.slow
+ def test_grouped_hist_layout_warning(self, hist_df):
+ df = hist_df
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(
+ df.hist, column="height", by=df.gender, layout=(2, 1)
+ )
+ _check_axes_shape(axes, axes_num=2, layout=(2, 1))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "layout, check_layout, figsize",
+ [[(4, 1), (4, 1), None], [(-1, 1), (4, 1), None], [(4, 2), (4, 2), (12, 8)]],
+ )
+ def test_grouped_hist_layout_figsize(self, hist_df, layout, check_layout, figsize):
+ df = hist_df
+ axes = df.hist(column="height", by=df.category, layout=layout, figsize=figsize)
+ _check_axes_shape(axes, axes_num=4, layout=check_layout, figsize=figsize)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kwargs", [{}, {"column": "height", "layout": (2, 2)}])
+ def test_grouped_hist_layout_by_warning(self, hist_df, kwargs):
+ df = hist_df
+ # GH 6769
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(df.hist, by="classroom", **kwargs)
+ _check_axes_shape(axes, axes_num=3, layout=(2, 2))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "kwargs, axes_num, layout",
+ [
+ [{"by": "gender", "layout": (3, 5)}, 2, (3, 5)],
+ [{"column": ["height", "weight", "category"]}, 3, (2, 2)],
+ ],
+ )
+ def test_grouped_hist_layout_axes(self, hist_df, kwargs, axes_num, layout):
+ df = hist_df
+ axes = df.hist(**kwargs)
+ _check_axes_shape(axes, axes_num=axes_num, layout=layout)
+
+ def test_grouped_hist_multiple_axes(self, hist_df):
+ # GH 6970, GH 7069
+ df = hist_df
+
+ fig, axes = mpl.pyplot.subplots(2, 3)
+ returned = df.hist(column=["height", "weight", "category"], ax=axes[0])
+ _check_axes_shape(returned, axes_num=3, layout=(1, 3))
+ tm.assert_numpy_array_equal(returned, axes[0])
+ assert returned[0].figure is fig
+
+ def test_grouped_hist_multiple_axes_no_cols(self, hist_df):
+ # GH 6970, GH 7069
+ df = hist_df
+
+ fig, axes = mpl.pyplot.subplots(2, 3)
+ returned = df.hist(by="classroom", ax=axes[1])
+ _check_axes_shape(returned, axes_num=3, layout=(1, 3))
+ tm.assert_numpy_array_equal(returned, axes[1])
+ assert returned[0].figure is fig
+
+ def test_grouped_hist_multiple_axes_error(self, hist_df):
+ # GH 6970, GH 7069
+ df = hist_df
+ fig, axes = mpl.pyplot.subplots(2, 3)
+ # pass different number of axes from required
+ msg = "The number of passed axes must be 1, the same as the output plot"
+ with pytest.raises(ValueError, match=msg):
+ axes = df.hist(column="height", ax=axes)
+
+ def test_axis_share_x(self, hist_df):
+ df = hist_df
+ # GH4089
+ ax1, ax2 = df.hist(column="height", by=df.gender, sharex=True)
+
+ # share x
+ assert get_x_axis(ax1).joined(ax1, ax2)
+ assert get_x_axis(ax2).joined(ax1, ax2)
+
+ # don't share y
+ assert not get_y_axis(ax1).joined(ax1, ax2)
+ assert not get_y_axis(ax2).joined(ax1, ax2)
+
+ def test_axis_share_y(self, hist_df):
+ df = hist_df
+ ax1, ax2 = df.hist(column="height", by=df.gender, sharey=True)
+
+ # share y
+ assert get_y_axis(ax1).joined(ax1, ax2)
+ assert get_y_axis(ax2).joined(ax1, ax2)
+
+ # don't share x
+ assert not get_x_axis(ax1).joined(ax1, ax2)
+ assert not get_x_axis(ax2).joined(ax1, ax2)
+
+ def test_axis_share_xy(self, hist_df):
+ df = hist_df
+ ax1, ax2 = df.hist(column="height", by=df.gender, sharex=True, sharey=True)
+
+ # share both x and y
+ assert get_x_axis(ax1).joined(ax1, ax2)
+ assert get_x_axis(ax2).joined(ax1, ax2)
+
+ assert get_y_axis(ax1).joined(ax1, ax2)
+ assert get_y_axis(ax2).joined(ax1, ax2)
+
+ @pytest.mark.parametrize(
+ "histtype, expected",
+ [
+ ("bar", True),
+ ("barstacked", True),
+ ("step", False),
+ ("stepfilled", True),
+ ],
+ )
+ def test_histtype_argument(self, histtype, expected):
+ # GH23992 Verify functioning of histtype argument
+ df = DataFrame(
+ np.random.default_rng(2).integers(1, 10, size=(10, 2)), columns=["a", "b"]
+ )
+ ax = df.hist(by="a", histtype=histtype)
+ _check_patches_all_filled(ax, filled=expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_misc.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5145472203a33b2b538a5cdd07952925f448a71
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_misc.py
@@ -0,0 +1,671 @@
+""" Test cases for misc plot functions """
+
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ Timestamp,
+ interval_range,
+ plotting,
+)
+import pandas._testing as tm
+from pandas.tests.plotting.common import (
+ _check_colors,
+ _check_legend_labels,
+ _check_plot_works,
+ _check_text_labels,
+ _check_ticks_props,
+)
+
+mpl = pytest.importorskip("matplotlib")
+cm = pytest.importorskip("matplotlib.cm")
+
+
+@td.skip_if_mpl
+def test_import_error_message():
+ # GH-19810
+ df = DataFrame({"A": [1, 2]})
+
+ with pytest.raises(ImportError, match="matplotlib is required for plotting"):
+ df.plot()
+
+
+def test_get_accessor_args():
+ func = plotting._core.PlotAccessor._get_call_args
+
+ msg = "Called plot accessor for type list, expected Series or DataFrame"
+ with pytest.raises(TypeError, match=msg):
+ func(backend_name="", data=[], args=[], kwargs={})
+
+ msg = "should not be called with positional arguments"
+ with pytest.raises(TypeError, match=msg):
+ func(backend_name="", data=Series(dtype=object), args=["line", None], kwargs={})
+
+ x, y, kind, kwargs = func(
+ backend_name="",
+ data=DataFrame(),
+ args=["x"],
+ kwargs={"y": "y", "kind": "bar", "grid": False},
+ )
+ assert x == "x"
+ assert y == "y"
+ assert kind == "bar"
+ assert kwargs == {"grid": False}
+
+ x, y, kind, kwargs = func(
+ backend_name="pandas.plotting._matplotlib",
+ data=Series(dtype=object),
+ args=[],
+ kwargs={},
+ )
+ assert x is None
+ assert y is None
+ assert kind == "line"
+ assert len(kwargs) == 24
+
+
+class TestSeriesPlots:
+ def test_autocorrelation_plot(self):
+ from pandas.plotting import autocorrelation_plot
+
+ ser = tm.makeTimeSeries(name="ts")
+ # Ensure no UserWarning when making plot
+ with tm.assert_produces_warning(None):
+ _check_plot_works(autocorrelation_plot, series=ser)
+ _check_plot_works(autocorrelation_plot, series=ser.values)
+
+ ax = autocorrelation_plot(ser, label="Test")
+ _check_legend_labels(ax, labels=["Test"])
+
+ @pytest.mark.parametrize("kwargs", [{}, {"lag": 5}])
+ def test_lag_plot(self, kwargs):
+ from pandas.plotting import lag_plot
+
+ ser = tm.makeTimeSeries(name="ts")
+ _check_plot_works(lag_plot, series=ser, **kwargs)
+
+ def test_bootstrap_plot(self):
+ from pandas.plotting import bootstrap_plot
+
+ ser = tm.makeTimeSeries(name="ts")
+ _check_plot_works(bootstrap_plot, series=ser, size=10)
+
+
+class TestDataFramePlots:
+ @pytest.mark.parametrize("pass_axis", [False, True])
+ def test_scatter_matrix_axis(self, pass_axis):
+ pytest.importorskip("scipy")
+ scatter_matrix = plotting.scatter_matrix
+
+ ax = None
+ if pass_axis:
+ _, ax = mpl.pyplot.subplots(3, 3)
+
+ df = DataFrame(np.random.default_rng(2).standard_normal((100, 3)))
+
+ # we are plotting multiples on a sub-plot
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(
+ scatter_matrix,
+ frame=df,
+ range_padding=0.1,
+ ax=ax,
+ )
+ axes0_labels = axes[0][0].yaxis.get_majorticklabels()
+ # GH 5662
+ expected = ["-2", "0", "2"]
+ _check_text_labels(axes0_labels, expected)
+ _check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0)
+
+ @pytest.mark.parametrize("pass_axis", [False, True])
+ def test_scatter_matrix_axis_smaller(self, pass_axis):
+ pytest.importorskip("scipy")
+ scatter_matrix = plotting.scatter_matrix
+
+ ax = None
+ if pass_axis:
+ _, ax = mpl.pyplot.subplots(3, 3)
+
+ df = DataFrame(np.random.default_rng(11).standard_normal((100, 3)))
+ df[0] = (df[0] - 2) / 3
+
+ # we are plotting multiples on a sub-plot
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
+ axes = _check_plot_works(
+ scatter_matrix,
+ frame=df,
+ range_padding=0.1,
+ ax=ax,
+ )
+ axes0_labels = axes[0][0].yaxis.get_majorticklabels()
+ expected = ["-1.0", "-0.5", "0.0"]
+ _check_text_labels(axes0_labels, expected)
+ _check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0)
+
+ @pytest.mark.slow
+ def test_andrews_curves_no_warning(self, iris):
+ from pandas.plotting import andrews_curves
+
+ df = iris
+ # Ensure no UserWarning when making plot
+ with tm.assert_produces_warning(None):
+ _check_plot_works(andrews_curves, frame=df, class_column="Name")
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "linecolors",
+ [
+ ("#556270", "#4ECDC4", "#C7F464"),
+ ["dodgerblue", "aquamarine", "seagreen"],
+ ],
+ )
+ @pytest.mark.parametrize(
+ "df",
+ [
+ "iris",
+ DataFrame(
+ {
+ "A": np.random.default_rng(2).standard_normal(10),
+ "B": np.random.default_rng(2).standard_normal(10),
+ "C": np.random.default_rng(2).standard_normal(10),
+ "Name": ["A"] * 10,
+ }
+ ),
+ ],
+ )
+ def test_andrews_curves_linecolors(self, request, df, linecolors):
+ from pandas.plotting import andrews_curves
+
+ if isinstance(df, str):
+ df = request.getfixturevalue(df)
+ ax = _check_plot_works(
+ andrews_curves, frame=df, class_column="Name", color=linecolors
+ )
+ _check_colors(
+ ax.get_lines()[:10], linecolors=linecolors, mapping=df["Name"][:10]
+ )
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "df",
+ [
+ "iris",
+ DataFrame(
+ {
+ "A": np.random.default_rng(2).standard_normal(10),
+ "B": np.random.default_rng(2).standard_normal(10),
+ "C": np.random.default_rng(2).standard_normal(10),
+ "Name": ["A"] * 10,
+ }
+ ),
+ ],
+ )
+ def test_andrews_curves_cmap(self, request, df):
+ from pandas.plotting import andrews_curves
+
+ if isinstance(df, str):
+ df = request.getfixturevalue(df)
+ cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())]
+ ax = _check_plot_works(
+ andrews_curves, frame=df, class_column="Name", color=cmaps
+ )
+ _check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10])
+
+ @pytest.mark.slow
+ def test_andrews_curves_handle(self):
+ from pandas.plotting import andrews_curves
+
+ colors = ["b", "g", "r"]
+ df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3], "C": [1, 2, 3], "Name": colors})
+ ax = andrews_curves(df, "Name", color=colors)
+ handles, _ = ax.get_legend_handles_labels()
+ _check_colors(handles, linecolors=colors)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "color",
+ [("#556270", "#4ECDC4", "#C7F464"), ["dodgerblue", "aquamarine", "seagreen"]],
+ )
+ def test_parallel_coordinates_colors(self, iris, color):
+ from pandas.plotting import parallel_coordinates
+
+ df = iris
+
+ ax = _check_plot_works(
+ parallel_coordinates, frame=df, class_column="Name", color=color
+ )
+ _check_colors(ax.get_lines()[:10], linecolors=color, mapping=df["Name"][:10])
+
+ @pytest.mark.slow
+ def test_parallel_coordinates_cmap(self, iris):
+ from matplotlib import cm
+
+ from pandas.plotting import parallel_coordinates
+
+ df = iris
+
+ ax = _check_plot_works(
+ parallel_coordinates, frame=df, class_column="Name", colormap=cm.jet
+ )
+ cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())]
+ _check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10])
+
+ @pytest.mark.slow
+ def test_parallel_coordinates_line_diff(self, iris):
+ from pandas.plotting import parallel_coordinates
+
+ df = iris
+
+ ax = _check_plot_works(parallel_coordinates, frame=df, class_column="Name")
+ nlines = len(ax.get_lines())
+ nxticks = len(ax.xaxis.get_ticklabels())
+
+ ax = _check_plot_works(
+ parallel_coordinates, frame=df, class_column="Name", axvlines=False
+ )
+ assert len(ax.get_lines()) == (nlines - nxticks)
+
+ @pytest.mark.slow
+ def test_parallel_coordinates_handles(self, iris):
+ from pandas.plotting import parallel_coordinates
+
+ df = iris
+ colors = ["b", "g", "r"]
+ df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3], "C": [1, 2, 3], "Name": colors})
+ ax = parallel_coordinates(df, "Name", color=colors)
+ handles, _ = ax.get_legend_handles_labels()
+ _check_colors(handles, linecolors=colors)
+
+ # not sure if this is indicative of a problem
+ @pytest.mark.filterwarnings("ignore:Attempting to set:UserWarning")
+ def test_parallel_coordinates_with_sorted_labels(self):
+ """For #15908"""
+ from pandas.plotting import parallel_coordinates
+
+ df = DataFrame(
+ {
+ "feat": list(range(30)),
+ "class": [2 for _ in range(10)]
+ + [3 for _ in range(10)]
+ + [1 for _ in range(10)],
+ }
+ )
+ ax = parallel_coordinates(df, "class", sort_labels=True)
+ polylines, labels = ax.get_legend_handles_labels()
+ color_label_tuples = zip(
+ [polyline.get_color() for polyline in polylines], labels
+ )
+ ordered_color_label_tuples = sorted(color_label_tuples, key=lambda x: x[1])
+ prev_next_tupels = zip(
+ list(ordered_color_label_tuples[0:-1]), list(ordered_color_label_tuples[1:])
+ )
+ for prev, nxt in prev_next_tupels:
+ # labels and colors are ordered strictly increasing
+ assert prev[1] < nxt[1] and prev[0] < nxt[0]
+
+ def test_radviz_no_warning(self, iris):
+ from pandas.plotting import radviz
+
+ df = iris
+ # Ensure no UserWarning when making plot
+ with tm.assert_produces_warning(None):
+ _check_plot_works(radviz, frame=df, class_column="Name")
+
+ @pytest.mark.parametrize(
+ "color",
+ [("#556270", "#4ECDC4", "#C7F464"), ["dodgerblue", "aquamarine", "seagreen"]],
+ )
+ def test_radviz_color(self, iris, color):
+ from pandas.plotting import radviz
+
+ df = iris
+ ax = _check_plot_works(radviz, frame=df, class_column="Name", color=color)
+ # skip Circle drawn as ticks
+ patches = [p for p in ax.patches[:20] if p.get_label() != ""]
+ _check_colors(patches[:10], facecolors=color, mapping=df["Name"][:10])
+
+ def test_radviz_color_cmap(self, iris):
+ from matplotlib import cm
+
+ from pandas.plotting import radviz
+
+ df = iris
+ ax = _check_plot_works(radviz, frame=df, class_column="Name", colormap=cm.jet)
+ cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())]
+ patches = [p for p in ax.patches[:20] if p.get_label() != ""]
+ _check_colors(patches, facecolors=cmaps, mapping=df["Name"][:10])
+
+ def test_radviz_colors_handles(self):
+ from pandas.plotting import radviz
+
+ colors = [[0.0, 0.0, 1.0, 1.0], [0.0, 0.5, 1.0, 1.0], [1.0, 0.0, 0.0, 1.0]]
+ df = DataFrame(
+ {"A": [1, 2, 3], "B": [2, 1, 3], "C": [3, 2, 1], "Name": ["b", "g", "r"]}
+ )
+ ax = radviz(df, "Name", color=colors)
+ handles, _ = ax.get_legend_handles_labels()
+ _check_colors(handles, facecolors=colors)
+
+ def test_subplot_titles(self, iris):
+ df = iris.drop("Name", axis=1).head()
+ # Use the column names as the subplot titles
+ title = list(df.columns)
+
+ # Case len(title) == len(df)
+ plot = df.plot(subplots=True, title=title)
+ assert [p.get_title() for p in plot] == title
+
+ def test_subplot_titles_too_much(self, iris):
+ df = iris.drop("Name", axis=1).head()
+ # Use the column names as the subplot titles
+ title = list(df.columns)
+ # Case len(title) > len(df)
+ msg = (
+ "The length of `title` must equal the number of columns if "
+ "using `title` of type `list` and `subplots=True`"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.plot(subplots=True, title=title + ["kittens > puppies"])
+
+ def test_subplot_titles_too_little(self, iris):
+ df = iris.drop("Name", axis=1).head()
+ # Use the column names as the subplot titles
+ title = list(df.columns)
+ msg = (
+ "The length of `title` must equal the number of columns if "
+ "using `title` of type `list` and `subplots=True`"
+ )
+ # Case len(title) < len(df)
+ with pytest.raises(ValueError, match=msg):
+ df.plot(subplots=True, title=title[:2])
+
+ def test_subplot_titles_subplots_false(self, iris):
+ df = iris.drop("Name", axis=1).head()
+ # Use the column names as the subplot titles
+ title = list(df.columns)
+ # Case subplots=False and title is of type list
+ msg = (
+ "Using `title` of type `list` is not supported unless "
+ "`subplots=True` is passed"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.plot(subplots=False, title=title)
+
+ def test_subplot_titles_numeric_square_layout(self, iris):
+ df = iris.drop("Name", axis=1).head()
+ # Use the column names as the subplot titles
+ title = list(df.columns)
+ # Case df with 3 numeric columns but layout of (2,2)
+ plot = df.drop("SepalWidth", axis=1).plot(
+ subplots=True, layout=(2, 2), title=title[:-1]
+ )
+ title_list = [ax.get_title() for sublist in plot for ax in sublist]
+ assert title_list == title[:3] + [""]
+
+ def test_get_standard_colors_random_seed(self):
+ # GH17525
+ df = DataFrame(np.zeros((10, 10)))
+
+ # Make sure that the random seed isn't reset by get_standard_colors
+ plotting.parallel_coordinates(df, 0)
+ rand1 = np.random.default_rng(None).random()
+ plotting.parallel_coordinates(df, 0)
+ rand2 = np.random.default_rng(None).random()
+ assert rand1 != rand2
+
+ def test_get_standard_colors_consistency(self):
+ # GH17525
+ # Make sure it produces the same colors every time it's called
+ from pandas.plotting._matplotlib.style import get_standard_colors
+
+ color1 = get_standard_colors(1, color_type="random")
+ color2 = get_standard_colors(1, color_type="random")
+ assert color1 == color2
+
+ def test_get_standard_colors_default_num_colors(self):
+ from pandas.plotting._matplotlib.style import get_standard_colors
+
+ # Make sure the default color_types returns the specified amount
+ color1 = get_standard_colors(1, color_type="default")
+ color2 = get_standard_colors(9, color_type="default")
+ color3 = get_standard_colors(20, color_type="default")
+ assert len(color1) == 1
+ assert len(color2) == 9
+ assert len(color3) == 20
+
+ def test_plot_single_color(self):
+ # Example from #20585. All 3 bars should have the same color
+ df = DataFrame(
+ {
+ "account-start": ["2017-02-03", "2017-03-03", "2017-01-01"],
+ "client": ["Alice Anders", "Bob Baker", "Charlie Chaplin"],
+ "balance": [-1432.32, 10.43, 30000.00],
+ "db-id": [1234, 2424, 251],
+ "proxy-id": [525, 1525, 2542],
+ "rank": [52, 525, 32],
+ }
+ )
+ ax = df.client.value_counts().plot.bar()
+ colors = [rect.get_facecolor() for rect in ax.get_children()[0:3]]
+ assert all(color == colors[0] for color in colors)
+
+ def test_get_standard_colors_no_appending(self):
+ # GH20726
+
+ # Make sure not to add more colors so that matplotlib can cycle
+ # correctly.
+ from matplotlib import cm
+
+ from pandas.plotting._matplotlib.style import get_standard_colors
+
+ color_before = cm.gnuplot(range(5))
+ color_after = get_standard_colors(1, color=color_before)
+ assert len(color_after) == len(color_before)
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((48, 4)), columns=list("ABCD")
+ )
+
+ color_list = cm.gnuplot(np.linspace(0, 1, 16))
+ p = df.A.plot.bar(figsize=(16, 7), color=color_list)
+ assert p.patches[1].get_facecolor() == p.patches[17].get_facecolor()
+
+ @pytest.mark.parametrize("kind", ["bar", "line"])
+ def test_dictionary_color(self, kind):
+ # issue-8193
+ # Test plot color dictionary format
+ data_files = ["a", "b"]
+
+ expected = [(0.5, 0.24, 0.6), (0.3, 0.7, 0.7)]
+
+ df1 = DataFrame(np.random.default_rng(2).random((2, 2)), columns=data_files)
+ dic_color = {"b": (0.3, 0.7, 0.7), "a": (0.5, 0.24, 0.6)}
+
+ ax = df1.plot(kind=kind, color=dic_color)
+ if kind == "bar":
+ colors = [rect.get_facecolor()[0:-1] for rect in ax.get_children()[0:3:2]]
+ else:
+ colors = [rect.get_color() for rect in ax.get_lines()[0:2]]
+ assert all(color == expected[index] for index, color in enumerate(colors))
+
+ def test_bar_plot(self):
+ # GH38947
+ # Test bar plot with string and int index
+ from matplotlib.text import Text
+
+ expected = [Text(0, 0, "0"), Text(1, 0, "Total")]
+
+ df = DataFrame(
+ {
+ "a": [1, 2],
+ },
+ index=Index([0, "Total"]),
+ )
+ plot_bar = df.plot.bar()
+ assert all(
+ (a.get_text() == b.get_text())
+ for a, b in zip(plot_bar.get_xticklabels(), expected)
+ )
+
+ def test_barh_plot_labels_mixed_integer_string(self):
+ # GH39126
+ # Test barh plot with string and integer at the same column
+ from matplotlib.text import Text
+
+ df = DataFrame([{"word": 1, "value": 0}, {"word": "knowledg", "value": 2}])
+ plot_barh = df.plot.barh(x="word", legend=None)
+ expected_yticklabels = [Text(0, 0, "1"), Text(0, 1, "knowledg")]
+ assert all(
+ actual.get_text() == expected.get_text()
+ for actual, expected in zip(
+ plot_barh.get_yticklabels(), expected_yticklabels
+ )
+ )
+
+ def test_has_externally_shared_axis_x_axis(self):
+ # GH33819
+ # Test _has_externally_shared_axis() works for x-axis
+ func = plotting._matplotlib.tools._has_externally_shared_axis
+
+ fig = mpl.pyplot.figure()
+ plots = fig.subplots(2, 4)
+
+ # Create *externally* shared axes for first and third columns
+ plots[0][0] = fig.add_subplot(231, sharex=plots[1][0])
+ plots[0][2] = fig.add_subplot(233, sharex=plots[1][2])
+
+ # Create *internally* shared axes for second and third columns
+ plots[0][1].twinx()
+ plots[0][2].twinx()
+
+ # First column is only externally shared
+ # Second column is only internally shared
+ # Third column is both
+ # Fourth column is neither
+ assert func(plots[0][0], "x")
+ assert not func(plots[0][1], "x")
+ assert func(plots[0][2], "x")
+ assert not func(plots[0][3], "x")
+
+ def test_has_externally_shared_axis_y_axis(self):
+ # GH33819
+ # Test _has_externally_shared_axis() works for y-axis
+ func = plotting._matplotlib.tools._has_externally_shared_axis
+
+ fig = mpl.pyplot.figure()
+ plots = fig.subplots(4, 2)
+
+ # Create *externally* shared axes for first and third rows
+ plots[0][0] = fig.add_subplot(321, sharey=plots[0][1])
+ plots[2][0] = fig.add_subplot(325, sharey=plots[2][1])
+
+ # Create *internally* shared axes for second and third rows
+ plots[1][0].twiny()
+ plots[2][0].twiny()
+
+ # First row is only externally shared
+ # Second row is only internally shared
+ # Third row is both
+ # Fourth row is neither
+ assert func(plots[0][0], "y")
+ assert not func(plots[1][0], "y")
+ assert func(plots[2][0], "y")
+ assert not func(plots[3][0], "y")
+
+ def test_has_externally_shared_axis_invalid_compare_axis(self):
+ # GH33819
+ # Test _has_externally_shared_axis() raises an exception when
+ # passed an invalid value as compare_axis parameter
+ func = plotting._matplotlib.tools._has_externally_shared_axis
+
+ fig = mpl.pyplot.figure()
+ plots = fig.subplots(4, 2)
+
+ # Create arbitrary axes
+ plots[0][0] = fig.add_subplot(321, sharey=plots[0][1])
+
+ # Check that an invalid compare_axis value triggers the expected exception
+ msg = "needs 'x' or 'y' as a second parameter"
+ with pytest.raises(ValueError, match=msg):
+ func(plots[0][0], "z")
+
+ def test_externally_shared_axes(self):
+ # Example from GH33819
+ # Create data
+ df = DataFrame(
+ {
+ "a": np.random.default_rng(2).standard_normal(1000),
+ "b": np.random.default_rng(2).standard_normal(1000),
+ }
+ )
+
+ # Create figure
+ fig = mpl.pyplot.figure()
+ plots = fig.subplots(2, 3)
+
+ # Create *externally* shared axes
+ plots[0][0] = fig.add_subplot(231, sharex=plots[1][0])
+ # note: no plots[0][1] that's the twin only case
+ plots[0][2] = fig.add_subplot(233, sharex=plots[1][2])
+
+ # Create *internally* shared axes
+ # note: no plots[0][0] that's the external only case
+ twin_ax1 = plots[0][1].twinx()
+ twin_ax2 = plots[0][2].twinx()
+
+ # Plot data to primary axes
+ df["a"].plot(ax=plots[0][0], title="External share only").set_xlabel(
+ "this label should never be visible"
+ )
+ df["a"].plot(ax=plots[1][0])
+
+ df["a"].plot(ax=plots[0][1], title="Internal share (twin) only").set_xlabel(
+ "this label should always be visible"
+ )
+ df["a"].plot(ax=plots[1][1])
+
+ df["a"].plot(ax=plots[0][2], title="Both").set_xlabel(
+ "this label should never be visible"
+ )
+ df["a"].plot(ax=plots[1][2])
+
+ # Plot data to twinned axes
+ df["b"].plot(ax=twin_ax1, color="green")
+ df["b"].plot(ax=twin_ax2, color="yellow")
+
+ assert not plots[0][0].xaxis.get_label().get_visible()
+ assert plots[0][1].xaxis.get_label().get_visible()
+ assert not plots[0][2].xaxis.get_label().get_visible()
+
+ def test_plot_bar_axis_units_timestamp_conversion(self):
+ # GH 38736
+ # Ensure string x-axis from the second plot will not be converted to datetime
+ # due to axis data from first plot
+ df = DataFrame(
+ [1.0],
+ index=[Timestamp("2022-02-22 22:22:22")],
+ )
+ _check_plot_works(df.plot)
+ s = Series({"A": 1.0})
+ _check_plot_works(s.plot.bar)
+
+ def test_bar_plt_xaxis_intervalrange(self):
+ # GH 38969
+ # Ensure IntervalIndex x-axis produces a bar plot as expected
+ from matplotlib.text import Text
+
+ expected = [Text(0, 0, "([0, 1],)"), Text(1, 0, "([1, 2],)")]
+ s = Series(
+ [1, 2],
+ index=[interval_range(0, 2, closed="both")],
+ )
+ _check_plot_works(s.plot.bar)
+ assert all(
+ (a.get_text() == b.get_text())
+ for a, b in zip(s.plot.bar().get_xticklabels(), expected)
+ )
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_series.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_series.py
new file mode 100644
index 0000000000000000000000000000000000000000..768fce023e6e06f7e689bfa9044ca8c27dd53595
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_series.py
@@ -0,0 +1,982 @@
+""" Test cases for Series.plot """
+from datetime import datetime
+from itertools import chain
+
+import numpy as np
+import pytest
+
+from pandas.compat import is_platform_linux
+from pandas.compat.numpy import np_version_gte1p24
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+ plotting,
+)
+import pandas._testing as tm
+from pandas.tests.plotting.common import (
+ _check_ax_scales,
+ _check_axes_shape,
+ _check_colors,
+ _check_grid_settings,
+ _check_has_errorbars,
+ _check_legend_labels,
+ _check_plot_works,
+ _check_text_labels,
+ _check_ticks_props,
+ _unpack_cycler,
+ get_y_axis,
+)
+
+mpl = pytest.importorskip("matplotlib")
+plt = pytest.importorskip("matplotlib.pyplot")
+
+
+@pytest.fixture
+def ts():
+ return tm.makeTimeSeries(name="ts")
+
+
+@pytest.fixture
+def series():
+ return tm.makeStringSeries(name="series")
+
+
+@pytest.fixture
+def iseries():
+ return tm.makePeriodSeries(name="iseries")
+
+
+class TestSeriesPlots:
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kwargs", [{"label": "foo"}, {"use_index": False}])
+ def test_plot(self, ts, kwargs):
+ _check_plot_works(ts.plot, **kwargs)
+
+ @pytest.mark.slow
+ def test_plot_tick_props(self, ts):
+ axes = _check_plot_works(ts.plot, rot=0)
+ _check_ticks_props(axes, xrot=0)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "scale, exp_scale",
+ [
+ [{"logy": True}, {"yaxis": "log"}],
+ [{"logx": True}, {"xaxis": "log"}],
+ [{"loglog": True}, {"xaxis": "log", "yaxis": "log"}],
+ ],
+ )
+ def test_plot_scales(self, ts, scale, exp_scale):
+ ax = _check_plot_works(ts.plot, style=".", **scale)
+ _check_ax_scales(ax, **exp_scale)
+
+ @pytest.mark.slow
+ def test_plot_ts_bar(self, ts):
+ _check_plot_works(ts[:10].plot.bar)
+
+ @pytest.mark.slow
+ def test_plot_ts_area_stacked(self, ts):
+ _check_plot_works(ts.plot.area, stacked=False)
+
+ def test_plot_iseries(self, iseries):
+ _check_plot_works(iseries.plot)
+
+ @pytest.mark.parametrize(
+ "kind",
+ [
+ "line",
+ "bar",
+ "barh",
+ pytest.param("kde", marks=td.skip_if_no_scipy),
+ "hist",
+ "box",
+ ],
+ )
+ def test_plot_series_kinds(self, series, kind):
+ _check_plot_works(series[:5].plot, kind=kind)
+
+ def test_plot_series_barh(self, series):
+ _check_plot_works(series[:10].plot.barh)
+
+ def test_plot_series_bar_ax(self):
+ ax = _check_plot_works(
+ Series(np.random.default_rng(2).standard_normal(10)).plot.bar, color="black"
+ )
+ _check_colors([ax.patches[0]], facecolors=["black"])
+
+ @pytest.mark.parametrize("kwargs", [{}, {"layout": (-1, 1)}, {"layout": (1, -1)}])
+ def test_plot_6951(self, ts, kwargs):
+ # GH 6951
+ ax = _check_plot_works(ts.plot, subplots=True, **kwargs)
+ _check_axes_shape(ax, axes_num=1, layout=(1, 1))
+
+ def test_plot_figsize_and_title(self, series):
+ # figsize and title
+ _, ax = mpl.pyplot.subplots()
+ ax = series.plot(title="Test", figsize=(16, 8), ax=ax)
+ _check_text_labels(ax.title, "Test")
+ _check_axes_shape(ax, axes_num=1, layout=(1, 1), figsize=(16, 8))
+
+ def test_dont_modify_rcParams(self):
+ # GH 8242
+ key = "axes.prop_cycle"
+ colors = mpl.pyplot.rcParams[key]
+ _, ax = mpl.pyplot.subplots()
+ Series([1, 2, 3]).plot(ax=ax)
+ assert colors == mpl.pyplot.rcParams[key]
+
+ @pytest.mark.parametrize("kwargs", [{}, {"secondary_y": True}])
+ def test_ts_line_lim(self, ts, kwargs):
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot(ax=ax, **kwargs)
+ xmin, xmax = ax.get_xlim()
+ lines = ax.get_lines()
+ assert xmin <= lines[0].get_data(orig=False)[0][0]
+ assert xmax >= lines[0].get_data(orig=False)[0][-1]
+
+ def test_ts_area_lim(self, ts):
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.area(stacked=False, ax=ax)
+ xmin, xmax = ax.get_xlim()
+ line = ax.get_lines()[0].get_data(orig=False)[0]
+ assert xmin <= line[0]
+ assert xmax >= line[-1]
+ _check_ticks_props(ax, xrot=0)
+
+ def test_ts_area_lim_xcompat(self, ts):
+ # GH 7471
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.area(stacked=False, x_compat=True, ax=ax)
+ xmin, xmax = ax.get_xlim()
+ line = ax.get_lines()[0].get_data(orig=False)[0]
+ assert xmin <= line[0]
+ assert xmax >= line[-1]
+ _check_ticks_props(ax, xrot=30)
+
+ def test_ts_tz_area_lim_xcompat(self, ts):
+ tz_ts = ts.copy()
+ tz_ts.index = tz_ts.tz_localize("GMT").tz_convert("CET")
+ _, ax = mpl.pyplot.subplots()
+ ax = tz_ts.plot.area(stacked=False, x_compat=True, ax=ax)
+ xmin, xmax = ax.get_xlim()
+ line = ax.get_lines()[0].get_data(orig=False)[0]
+ assert xmin <= line[0]
+ assert xmax >= line[-1]
+ _check_ticks_props(ax, xrot=0)
+
+ def test_ts_tz_area_lim_xcompat_secondary_y(self, ts):
+ tz_ts = ts.copy()
+ tz_ts.index = tz_ts.tz_localize("GMT").tz_convert("CET")
+ _, ax = mpl.pyplot.subplots()
+ ax = tz_ts.plot.area(stacked=False, secondary_y=True, ax=ax)
+ xmin, xmax = ax.get_xlim()
+ line = ax.get_lines()[0].get_data(orig=False)[0]
+ assert xmin <= line[0]
+ assert xmax >= line[-1]
+ _check_ticks_props(ax, xrot=0)
+
+ def test_area_sharey_dont_overwrite(self, ts):
+ # GH37942
+ fig, (ax1, ax2) = mpl.pyplot.subplots(1, 2, sharey=True)
+
+ abs(ts).plot(ax=ax1, kind="area")
+ abs(ts).plot(ax=ax2, kind="area")
+
+ assert get_y_axis(ax1).joined(ax1, ax2)
+ assert get_y_axis(ax2).joined(ax1, ax2)
+ plt.close(fig)
+
+ def test_label(self):
+ s = Series([1, 2])
+ _, ax = mpl.pyplot.subplots()
+ ax = s.plot(label="LABEL", legend=True, ax=ax)
+ _check_legend_labels(ax, labels=["LABEL"])
+ mpl.pyplot.close("all")
+
+ def test_label_none(self):
+ s = Series([1, 2])
+ _, ax = mpl.pyplot.subplots()
+ ax = s.plot(legend=True, ax=ax)
+ _check_legend_labels(ax, labels=[""])
+ mpl.pyplot.close("all")
+
+ def test_label_ser_name(self):
+ s = Series([1, 2], name="NAME")
+ _, ax = mpl.pyplot.subplots()
+ ax = s.plot(legend=True, ax=ax)
+ _check_legend_labels(ax, labels=["NAME"])
+ mpl.pyplot.close("all")
+
+ def test_label_ser_name_override(self):
+ s = Series([1, 2], name="NAME")
+ # override the default
+ _, ax = mpl.pyplot.subplots()
+ ax = s.plot(legend=True, label="LABEL", ax=ax)
+ _check_legend_labels(ax, labels=["LABEL"])
+ mpl.pyplot.close("all")
+
+ def test_label_ser_name_override_dont_draw(self):
+ s = Series([1, 2], name="NAME")
+ # Add lebel info, but don't draw
+ _, ax = mpl.pyplot.subplots()
+ ax = s.plot(legend=False, label="LABEL", ax=ax)
+ assert ax.get_legend() is None # Hasn't been drawn
+ ax.legend() # draw it
+ _check_legend_labels(ax, labels=["LABEL"])
+ mpl.pyplot.close("all")
+
+ def test_boolean(self):
+ # GH 23719
+ s = Series([False, False, True])
+ _check_plot_works(s.plot, include_bool=True)
+
+ msg = "no numeric data to plot"
+ with pytest.raises(TypeError, match=msg):
+ _check_plot_works(s.plot)
+
+ @pytest.mark.parametrize("index", [None, tm.makeDateIndex(k=4)])
+ def test_line_area_nan_series(self, index):
+ values = [1, 2, np.nan, 3]
+ d = Series(values, index=index)
+ ax = _check_plot_works(d.plot)
+ masked = ax.lines[0].get_ydata()
+ # remove nan for comparison purpose
+ exp = np.array([1, 2, 3], dtype=np.float64)
+ tm.assert_numpy_array_equal(np.delete(masked.data, 2), exp)
+ tm.assert_numpy_array_equal(masked.mask, np.array([False, False, True, False]))
+
+ expected = np.array([1, 2, 0, 3], dtype=np.float64)
+ ax = _check_plot_works(d.plot, stacked=True)
+ tm.assert_numpy_array_equal(ax.lines[0].get_ydata(), expected)
+ ax = _check_plot_works(d.plot.area)
+ tm.assert_numpy_array_equal(ax.lines[0].get_ydata(), expected)
+ ax = _check_plot_works(d.plot.area, stacked=False)
+ tm.assert_numpy_array_equal(ax.lines[0].get_ydata(), expected)
+
+ def test_line_use_index_false(self):
+ s = Series([1, 2, 3], index=["a", "b", "c"])
+ s.index.name = "The Index"
+ _, ax = mpl.pyplot.subplots()
+ ax = s.plot(use_index=False, ax=ax)
+ label = ax.get_xlabel()
+ assert label == ""
+
+ def test_line_use_index_false_diff_var(self):
+ s = Series([1, 2, 3], index=["a", "b", "c"])
+ s.index.name = "The Index"
+ _, ax = mpl.pyplot.subplots()
+ ax2 = s.plot.bar(use_index=False, ax=ax)
+ label2 = ax2.get_xlabel()
+ assert label2 == ""
+
+ @pytest.mark.xfail(
+ np_version_gte1p24 and is_platform_linux(),
+ reason="Weird rounding problems",
+ strict=False,
+ )
+ @pytest.mark.parametrize("axis, meth", [("yaxis", "bar"), ("xaxis", "barh")])
+ def test_bar_log(self, axis, meth):
+ expected = np.array([1e-1, 1e0, 1e1, 1e2, 1e3, 1e4])
+
+ _, ax = mpl.pyplot.subplots()
+ ax = getattr(Series([200, 500]).plot, meth)(log=True, ax=ax)
+ tm.assert_numpy_array_equal(getattr(ax, axis).get_ticklocs(), expected)
+
+ @pytest.mark.xfail(
+ np_version_gte1p24 and is_platform_linux(),
+ reason="Weird rounding problems",
+ strict=False,
+ )
+ @pytest.mark.parametrize(
+ "axis, kind, res_meth",
+ [["yaxis", "bar", "get_ylim"], ["xaxis", "barh", "get_xlim"]],
+ )
+ def test_bar_log_kind_bar(self, axis, kind, res_meth):
+ # GH 9905
+ expected = np.array([1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1])
+
+ _, ax = mpl.pyplot.subplots()
+ ax = Series([0.1, 0.01, 0.001]).plot(log=True, kind=kind, ax=ax)
+ ymin = 0.0007943282347242822
+ ymax = 0.12589254117941673
+ res = getattr(ax, res_meth)()
+ tm.assert_almost_equal(res[0], ymin)
+ tm.assert_almost_equal(res[1], ymax)
+ tm.assert_numpy_array_equal(getattr(ax, axis).get_ticklocs(), expected)
+
+ def test_bar_ignore_index(self):
+ df = Series([1, 2, 3, 4], index=["a", "b", "c", "d"])
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot.bar(use_index=False, ax=ax)
+ _check_text_labels(ax.get_xticklabels(), ["0", "1", "2", "3"])
+
+ def test_bar_user_colors(self):
+ s = Series([1, 2, 3, 4])
+ ax = s.plot.bar(color=["red", "blue", "blue", "red"])
+ result = [p.get_facecolor() for p in ax.patches]
+ expected = [
+ (1.0, 0.0, 0.0, 1.0),
+ (0.0, 0.0, 1.0, 1.0),
+ (0.0, 0.0, 1.0, 1.0),
+ (1.0, 0.0, 0.0, 1.0),
+ ]
+ assert result == expected
+
+ def test_rotation_default(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ # Default rot 0
+ _, ax = mpl.pyplot.subplots()
+ axes = df.plot(ax=ax)
+ _check_ticks_props(axes, xrot=0)
+
+ def test_rotation_30(self):
+ df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)))
+ _, ax = mpl.pyplot.subplots()
+ axes = df.plot(rot=30, ax=ax)
+ _check_ticks_props(axes, xrot=30)
+
+ def test_irregular_datetime(self):
+ from pandas.plotting._matplotlib.converter import DatetimeConverter
+
+ rng = date_range("1/1/2000", "3/1/2000")
+ rng = rng[[0, 1, 2, 3, 5, 9, 10, 11, 12]]
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+ _, ax = mpl.pyplot.subplots()
+ ax = ser.plot(ax=ax)
+ xp = DatetimeConverter.convert(datetime(1999, 1, 1), "", ax)
+ ax.set_xlim("1/1/1999", "1/1/2001")
+ assert xp == ax.get_xlim()[0]
+ _check_ticks_props(ax, xrot=30)
+
+ def test_unsorted_index_xlim(self):
+ ser = Series(
+ [0.0, 1.0, np.nan, 3.0, 4.0, 5.0, 6.0],
+ index=[1.0, 0.0, 3.0, 2.0, np.nan, 3.0, 2.0],
+ )
+ _, ax = mpl.pyplot.subplots()
+ ax = ser.plot(ax=ax)
+ xmin, xmax = ax.get_xlim()
+ lines = ax.get_lines()
+ assert xmin <= np.nanmin(lines[0].get_data(orig=False)[0])
+ assert xmax >= np.nanmax(lines[0].get_data(orig=False)[0])
+
+ def test_pie_series(self):
+ # if sum of values is less than 1.0, pie handle them as rate and draw
+ # semicircle.
+ series = Series(
+ np.random.default_rng(2).integers(1, 5),
+ index=["a", "b", "c", "d", "e"],
+ name="YLABEL",
+ )
+ ax = _check_plot_works(series.plot.pie)
+ _check_text_labels(ax.texts, series.index)
+ assert ax.get_ylabel() == "YLABEL"
+
+ def test_pie_series_no_label(self):
+ series = Series(
+ np.random.default_rng(2).integers(1, 5),
+ index=["a", "b", "c", "d", "e"],
+ name="YLABEL",
+ )
+ ax = _check_plot_works(series.plot.pie, labels=None)
+ _check_text_labels(ax.texts, [""] * 5)
+
+ def test_pie_series_less_colors_than_elements(self):
+ series = Series(
+ np.random.default_rng(2).integers(1, 5),
+ index=["a", "b", "c", "d", "e"],
+ name="YLABEL",
+ )
+ color_args = ["r", "g", "b"]
+ ax = _check_plot_works(series.plot.pie, colors=color_args)
+
+ color_expected = ["r", "g", "b", "r", "g"]
+ _check_colors(ax.patches, facecolors=color_expected)
+
+ def test_pie_series_labels_and_colors(self):
+ series = Series(
+ np.random.default_rng(2).integers(1, 5),
+ index=["a", "b", "c", "d", "e"],
+ name="YLABEL",
+ )
+ # with labels and colors
+ labels = ["A", "B", "C", "D", "E"]
+ color_args = ["r", "g", "b", "c", "m"]
+ ax = _check_plot_works(series.plot.pie, labels=labels, colors=color_args)
+ _check_text_labels(ax.texts, labels)
+ _check_colors(ax.patches, facecolors=color_args)
+
+ def test_pie_series_autopct_and_fontsize(self):
+ series = Series(
+ np.random.default_rng(2).integers(1, 5),
+ index=["a", "b", "c", "d", "e"],
+ name="YLABEL",
+ )
+ color_args = ["r", "g", "b", "c", "m"]
+ ax = _check_plot_works(
+ series.plot.pie, colors=color_args, autopct="%.2f", fontsize=7
+ )
+ pcts = [f"{s*100:.2f}" for s in series.values / series.sum()]
+ expected_texts = list(chain.from_iterable(zip(series.index, pcts)))
+ _check_text_labels(ax.texts, expected_texts)
+ for t in ax.texts:
+ assert t.get_fontsize() == 7
+
+ def test_pie_series_negative_raises(self):
+ # includes negative value
+ series = Series([1, 2, 0, 4, -1], index=["a", "b", "c", "d", "e"])
+ with pytest.raises(ValueError, match="pie plot doesn't allow negative values"):
+ series.plot.pie()
+
+ def test_pie_series_nan(self):
+ # includes nan
+ series = Series([1, 2, np.nan, 4], index=["a", "b", "c", "d"], name="YLABEL")
+ ax = _check_plot_works(series.plot.pie)
+ _check_text_labels(ax.texts, ["a", "b", "", "d"])
+
+ def test_pie_nan(self):
+ s = Series([1, np.nan, 1, 1])
+ _, ax = mpl.pyplot.subplots()
+ ax = s.plot.pie(legend=True, ax=ax)
+ expected = ["0", "", "2", "3"]
+ result = [x.get_text() for x in ax.texts]
+ assert result == expected
+
+ def test_df_series_secondary_legend(self):
+ # GH 9779
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 3)), columns=list("abc")
+ )
+ s = Series(np.random.default_rng(2).standard_normal(30), name="x")
+
+ # primary -> secondary (without passing ax)
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot(ax=ax)
+ s.plot(legend=True, secondary_y=True, ax=ax)
+ # both legends are drawn on left ax
+ # left and right axis must be visible
+ _check_legend_labels(ax, labels=["a", "b", "c", "x (right)"])
+ assert ax.get_yaxis().get_visible()
+ assert ax.right_ax.get_yaxis().get_visible()
+
+ def test_df_series_secondary_legend_with_axes(self):
+ # GH 9779
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 3)), columns=list("abc")
+ )
+ s = Series(np.random.default_rng(2).standard_normal(30), name="x")
+ # primary -> secondary (with passing ax)
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot(ax=ax)
+ s.plot(ax=ax, legend=True, secondary_y=True)
+ # both legends are drawn on left ax
+ # left and right axis must be visible
+ _check_legend_labels(ax, labels=["a", "b", "c", "x (right)"])
+ assert ax.get_yaxis().get_visible()
+ assert ax.right_ax.get_yaxis().get_visible()
+
+ def test_df_series_secondary_legend_both(self):
+ # GH 9779
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 3)), columns=list("abc")
+ )
+ s = Series(np.random.default_rng(2).standard_normal(30), name="x")
+ # secondary -> secondary (without passing ax)
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot(secondary_y=True, ax=ax)
+ s.plot(legend=True, secondary_y=True, ax=ax)
+ # both legends are drawn on left ax
+ # left axis must be invisible and right axis must be visible
+ expected = ["a (right)", "b (right)", "c (right)", "x (right)"]
+ _check_legend_labels(ax.left_ax, labels=expected)
+ assert not ax.left_ax.get_yaxis().get_visible()
+ assert ax.get_yaxis().get_visible()
+
+ def test_df_series_secondary_legend_both_with_axis(self):
+ # GH 9779
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 3)), columns=list("abc")
+ )
+ s = Series(np.random.default_rng(2).standard_normal(30), name="x")
+ # secondary -> secondary (with passing ax)
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot(secondary_y=True, ax=ax)
+ s.plot(ax=ax, legend=True, secondary_y=True)
+ # both legends are drawn on left ax
+ # left axis must be invisible and right axis must be visible
+ expected = ["a (right)", "b (right)", "c (right)", "x (right)"]
+ _check_legend_labels(ax.left_ax, expected)
+ assert not ax.left_ax.get_yaxis().get_visible()
+ assert ax.get_yaxis().get_visible()
+
+ def test_df_series_secondary_legend_both_with_axis_2(self):
+ # GH 9779
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((30, 3)), columns=list("abc")
+ )
+ s = Series(np.random.default_rng(2).standard_normal(30), name="x")
+ # secondary -> secondary (with passing ax)
+ _, ax = mpl.pyplot.subplots()
+ ax = df.plot(secondary_y=True, mark_right=False, ax=ax)
+ s.plot(ax=ax, legend=True, secondary_y=True)
+ # both legends are drawn on left ax
+ # left axis must be invisible and right axis must be visible
+ expected = ["a", "b", "c", "x (right)"]
+ _check_legend_labels(ax.left_ax, expected)
+ assert not ax.left_ax.get_yaxis().get_visible()
+ assert ax.get_yaxis().get_visible()
+
+ @pytest.mark.parametrize(
+ "input_logy, expected_scale", [(True, "log"), ("sym", "symlog")]
+ )
+ def test_secondary_logy(self, input_logy, expected_scale):
+ # GH 25545
+ s1 = Series(np.random.default_rng(2).standard_normal(100))
+ s2 = Series(np.random.default_rng(2).standard_normal(100))
+
+ # GH 24980
+ ax1 = s1.plot(logy=input_logy)
+ ax2 = s2.plot(secondary_y=True, logy=input_logy)
+
+ assert ax1.get_yscale() == expected_scale
+ assert ax2.get_yscale() == expected_scale
+
+ def test_plot_fails_with_dupe_color_and_style(self):
+ x = Series(np.random.default_rng(2).standard_normal(2))
+ _, ax = mpl.pyplot.subplots()
+ msg = (
+ "Cannot pass 'style' string with a color symbol and 'color' keyword "
+ "argument. Please use one or the other or pass 'style' without a color "
+ "symbol"
+ )
+ with pytest.raises(ValueError, match=msg):
+ x.plot(style="k--", color="k", ax=ax)
+
+ @pytest.mark.parametrize(
+ "bw_method, ind",
+ [
+ ["scott", 20],
+ [None, 20],
+ [None, np.int_(20)],
+ [0.5, np.linspace(-100, 100, 20)],
+ ],
+ )
+ def test_kde_kwargs(self, ts, bw_method, ind):
+ pytest.importorskip("scipy")
+ _check_plot_works(ts.plot.kde, bw_method=bw_method, ind=ind)
+
+ def test_density_kwargs(self, ts):
+ pytest.importorskip("scipy")
+ sample_points = np.linspace(-100, 100, 20)
+ _check_plot_works(ts.plot.density, bw_method=0.5, ind=sample_points)
+
+ def test_kde_kwargs_check_axes(self, ts):
+ pytest.importorskip("scipy")
+ _, ax = mpl.pyplot.subplots()
+ sample_points = np.linspace(-100, 100, 20)
+ ax = ts.plot.kde(logy=True, bw_method=0.5, ind=sample_points, ax=ax)
+ _check_ax_scales(ax, yaxis="log")
+ _check_text_labels(ax.yaxis.get_label(), "Density")
+
+ def test_kde_missing_vals(self):
+ pytest.importorskip("scipy")
+ s = Series(np.random.default_rng(2).uniform(size=50))
+ s[0] = np.nan
+ axes = _check_plot_works(s.plot.kde)
+
+ # gh-14821: check if the values have any missing values
+ assert any(~np.isnan(axes.lines[0].get_xdata()))
+
+ @pytest.mark.xfail(reason="Api changed in 3.6.0")
+ def test_boxplot_series(self, ts):
+ _, ax = mpl.pyplot.subplots()
+ ax = ts.plot.box(logy=True, ax=ax)
+ _check_ax_scales(ax, yaxis="log")
+ xlabels = ax.get_xticklabels()
+ _check_text_labels(xlabels, [ts.name])
+ ylabels = ax.get_yticklabels()
+ _check_text_labels(ylabels, [""] * len(ylabels))
+
+ @pytest.mark.parametrize(
+ "kind",
+ plotting.PlotAccessor._common_kinds + plotting.PlotAccessor._series_kinds,
+ )
+ def test_kind_kwarg(self, kind):
+ pytest.importorskip("scipy")
+ s = Series(range(3))
+ _, ax = mpl.pyplot.subplots()
+ s.plot(kind=kind, ax=ax)
+ mpl.pyplot.close()
+
+ @pytest.mark.parametrize(
+ "kind",
+ plotting.PlotAccessor._common_kinds + plotting.PlotAccessor._series_kinds,
+ )
+ def test_kind_attr(self, kind):
+ pytest.importorskip("scipy")
+ s = Series(range(3))
+ _, ax = mpl.pyplot.subplots()
+ getattr(s.plot, kind)()
+ mpl.pyplot.close()
+
+ @pytest.mark.parametrize("kind", plotting.PlotAccessor._common_kinds)
+ def test_invalid_plot_data(self, kind):
+ s = Series(list("abcd"))
+ _, ax = mpl.pyplot.subplots()
+ msg = "no numeric data to plot"
+ with pytest.raises(TypeError, match=msg):
+ s.plot(kind=kind, ax=ax)
+
+ @pytest.mark.parametrize("kind", plotting.PlotAccessor._common_kinds)
+ def test_valid_object_plot(self, kind):
+ pytest.importorskip("scipy")
+ s = Series(range(10), dtype=object)
+ _check_plot_works(s.plot, kind=kind)
+
+ @pytest.mark.parametrize("kind", plotting.PlotAccessor._common_kinds)
+ def test_partially_invalid_plot_data(self, kind):
+ s = Series(["a", "b", 1.0, 2])
+ _, ax = mpl.pyplot.subplots()
+ msg = "no numeric data to plot"
+ with pytest.raises(TypeError, match=msg):
+ s.plot(kind=kind, ax=ax)
+
+ def test_invalid_kind(self):
+ s = Series([1, 2])
+ with pytest.raises(ValueError, match="invalid_kind is not a valid plot kind"):
+ s.plot(kind="invalid_kind")
+
+ def test_dup_datetime_index_plot(self):
+ dr1 = date_range("1/1/2009", periods=4)
+ dr2 = date_range("1/2/2009", periods=4)
+ index = dr1.append(dr2)
+ values = np.random.default_rng(2).standard_normal(index.size)
+ s = Series(values, index=index)
+ _check_plot_works(s.plot)
+
+ def test_errorbar_asymmetrical(self):
+ # GH9536
+ s = Series(np.arange(10), name="x")
+ err = np.random.default_rng(2).random((2, 10))
+
+ ax = s.plot(yerr=err, xerr=err)
+
+ result = np.vstack([i.vertices[:, 1] for i in ax.collections[1].get_paths()])
+ expected = (err.T * np.array([-1, 1])) + s.to_numpy().reshape(-1, 1)
+ tm.assert_numpy_array_equal(result, expected)
+
+ msg = (
+ "Asymmetrical error bars should be provided "
+ f"with the shape \\(2, {len(s)}\\)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ s.plot(yerr=np.random.default_rng(2).random((2, 11)))
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("kind", ["line", "bar"])
+ @pytest.mark.parametrize(
+ "yerr",
+ [
+ Series(np.abs(np.random.default_rng(2).standard_normal(10))),
+ np.abs(np.random.default_rng(2).standard_normal(10)),
+ list(np.abs(np.random.default_rng(2).standard_normal(10))),
+ DataFrame(
+ np.abs(np.random.default_rng(2).standard_normal((10, 2))),
+ columns=["x", "y"],
+ ),
+ ],
+ )
+ def test_errorbar_plot(self, kind, yerr):
+ s = Series(np.arange(10), name="x")
+ ax = _check_plot_works(s.plot, yerr=yerr, kind=kind)
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+
+ @pytest.mark.slow
+ def test_errorbar_plot_yerr_0(self):
+ s = Series(np.arange(10), name="x")
+ s_err = np.abs(np.random.default_rng(2).standard_normal(10))
+ ax = _check_plot_works(s.plot, xerr=s_err)
+ _check_has_errorbars(ax, xerr=1, yerr=0)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "yerr",
+ [
+ Series(np.abs(np.random.default_rng(2).standard_normal(12))),
+ DataFrame(
+ np.abs(np.random.default_rng(2).standard_normal((12, 2))),
+ columns=["x", "y"],
+ ),
+ ],
+ )
+ def test_errorbar_plot_ts(self, yerr):
+ # test time series plotting
+ ix = date_range("1/1/2000", "1/1/2001", freq="M")
+ ts = Series(np.arange(12), index=ix, name="x")
+ yerr.index = ix
+
+ ax = _check_plot_works(ts.plot, yerr=yerr)
+ _check_has_errorbars(ax, xerr=0, yerr=1)
+
+ @pytest.mark.slow
+ def test_errorbar_plot_invalid_yerr_shape(self):
+ s = Series(np.arange(10), name="x")
+ # check incorrect lengths and types
+ with tm.external_error_raised(ValueError):
+ s.plot(yerr=np.arange(11))
+
+ @pytest.mark.slow
+ def test_errorbar_plot_invalid_yerr(self):
+ s = Series(np.arange(10), name="x")
+ s_err = ["zzz"] * 10
+ with tm.external_error_raised(TypeError):
+ s.plot(yerr=s_err)
+
+ @pytest.mark.slow
+ def test_table_true(self, series):
+ _check_plot_works(series.plot, table=True)
+
+ @pytest.mark.slow
+ def test_table_self(self, series):
+ _check_plot_works(series.plot, table=series)
+
+ @pytest.mark.slow
+ def test_series_grid_settings(self):
+ # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792
+ pytest.importorskip("scipy")
+ _check_grid_settings(
+ Series([1, 2, 3]),
+ plotting.PlotAccessor._series_kinds + plotting.PlotAccessor._common_kinds,
+ )
+
+ @pytest.mark.parametrize("c", ["r", "red", "green", "#FF0000"])
+ def test_standard_colors(self, c):
+ from pandas.plotting._matplotlib.style import get_standard_colors
+
+ result = get_standard_colors(1, color=c)
+ assert result == [c]
+
+ result = get_standard_colors(1, color=[c])
+ assert result == [c]
+
+ result = get_standard_colors(3, color=c)
+ assert result == [c] * 3
+
+ result = get_standard_colors(3, color=[c])
+ assert result == [c] * 3
+
+ def test_standard_colors_all(self):
+ from matplotlib import colors
+
+ from pandas.plotting._matplotlib.style import get_standard_colors
+
+ # multiple colors like mediumaquamarine
+ for c in colors.cnames:
+ result = get_standard_colors(num_colors=1, color=c)
+ assert result == [c]
+
+ result = get_standard_colors(num_colors=1, color=[c])
+ assert result == [c]
+
+ result = get_standard_colors(num_colors=3, color=c)
+ assert result == [c] * 3
+
+ result = get_standard_colors(num_colors=3, color=[c])
+ assert result == [c] * 3
+
+ # single letter colors like k
+ for c in colors.ColorConverter.colors:
+ result = get_standard_colors(num_colors=1, color=c)
+ assert result == [c]
+
+ result = get_standard_colors(num_colors=1, color=[c])
+ assert result == [c]
+
+ result = get_standard_colors(num_colors=3, color=c)
+ assert result == [c] * 3
+
+ result = get_standard_colors(num_colors=3, color=[c])
+ assert result == [c] * 3
+
+ def test_series_plot_color_kwargs(self):
+ # GH1890
+ _, ax = mpl.pyplot.subplots()
+ ax = Series(np.arange(12) + 1).plot(color="green", ax=ax)
+ _check_colors(ax.get_lines(), linecolors=["green"])
+
+ def test_time_series_plot_color_kwargs(self):
+ # #1890
+ _, ax = mpl.pyplot.subplots()
+ ax = Series(np.arange(12) + 1, index=date_range("1/1/2000", periods=12)).plot(
+ color="green", ax=ax
+ )
+ _check_colors(ax.get_lines(), linecolors=["green"])
+
+ def test_time_series_plot_color_with_empty_kwargs(self):
+ import matplotlib as mpl
+
+ def_colors = _unpack_cycler(mpl.rcParams)
+ index = date_range("1/1/2000", periods=12)
+ s = Series(np.arange(1, 13), index=index)
+
+ ncolors = 3
+
+ _, ax = mpl.pyplot.subplots()
+ for i in range(ncolors):
+ ax = s.plot(ax=ax)
+ _check_colors(ax.get_lines(), linecolors=def_colors[:ncolors])
+
+ def test_xticklabels(self):
+ # GH11529
+ s = Series(np.arange(10), index=[f"P{i:02d}" for i in range(10)])
+ _, ax = mpl.pyplot.subplots()
+ ax = s.plot(xticks=[0, 3, 5, 9], ax=ax)
+ exp = [f"P{i:02d}" for i in [0, 3, 5, 9]]
+ _check_text_labels(ax.get_xticklabels(), exp)
+
+ def test_xtick_barPlot(self):
+ # GH28172
+ s = Series(range(10), index=[f"P{i:02d}" for i in range(10)])
+ ax = s.plot.bar(xticks=range(0, 11, 2))
+ exp = np.array(list(range(0, 11, 2)))
+ tm.assert_numpy_array_equal(exp, ax.get_xticks())
+
+ def test_custom_business_day_freq(self):
+ # GH7222
+ from pandas.tseries.offsets import CustomBusinessDay
+
+ s = Series(
+ range(100, 121),
+ index=pd.bdate_range(
+ start="2014-05-01",
+ end="2014-06-01",
+ freq=CustomBusinessDay(holidays=["2014-05-26"]),
+ ),
+ )
+
+ _check_plot_works(s.plot)
+
+ @pytest.mark.xfail(
+ reason="GH#24426, see also "
+ "github.com/pandas-dev/pandas/commit/"
+ "ef1bd69fa42bbed5d09dd17f08c44fc8bfc2b685#r61470674"
+ )
+ def test_plot_accessor_updates_on_inplace(self):
+ ser = Series([1, 2, 3, 4])
+ _, ax = mpl.pyplot.subplots()
+ ax = ser.plot(ax=ax)
+ before = ax.xaxis.get_ticklocs()
+
+ ser.drop([0, 1], inplace=True)
+ _, ax = mpl.pyplot.subplots()
+ after = ax.xaxis.get_ticklocs()
+ tm.assert_numpy_array_equal(before, after)
+
+ @pytest.mark.parametrize("kind", ["line", "area"])
+ def test_plot_xlim_for_series(self, kind):
+ # test if xlim is also correctly plotted in Series for line and area
+ # GH 27686
+ s = Series([2, 3])
+ _, ax = mpl.pyplot.subplots()
+ s.plot(kind=kind, ax=ax)
+ xlims = ax.get_xlim()
+
+ assert xlims[0] < 0
+ assert xlims[1] > 1
+
+ def test_plot_no_rows(self):
+ # GH 27758
+ df = Series(dtype=int)
+ assert df.empty
+ ax = df.plot()
+ assert len(ax.get_lines()) == 1
+ line = ax.get_lines()[0]
+ assert len(line.get_xdata()) == 0
+ assert len(line.get_ydata()) == 0
+
+ def test_plot_no_numeric_data(self):
+ df = Series(["a", "b", "c"])
+ with pytest.raises(TypeError, match="no numeric data to plot"):
+ df.plot()
+
+ @pytest.mark.parametrize(
+ "data, index",
+ [
+ ([1, 2, 3, 4], [3, 2, 1, 0]),
+ ([10, 50, 20, 30], [1910, 1920, 1980, 1950]),
+ ],
+ )
+ def test_plot_order(self, data, index):
+ # GH38865 Verify plot order of a Series
+ ser = Series(data=data, index=index)
+ ax = ser.plot(kind="bar")
+
+ expected = ser.tolist()
+ result = [
+ patch.get_bbox().ymax
+ for patch in sorted(ax.patches, key=lambda patch: patch.get_bbox().xmax)
+ ]
+ assert expected == result
+
+ def test_style_single_ok(self):
+ s = Series([1, 2])
+ ax = s.plot(style="s", color="C3")
+ assert ax.lines[0].get_color() == "C3"
+
+ @pytest.mark.parametrize(
+ "index_name, old_label, new_label",
+ [(None, "", "new"), ("old", "old", "new"), (None, "", "")],
+ )
+ @pytest.mark.parametrize("kind", ["line", "area", "bar", "barh", "hist"])
+ def test_xlabel_ylabel_series(self, kind, index_name, old_label, new_label):
+ # GH 9093
+ ser = Series([1, 2, 3, 4])
+ ser.index.name = index_name
+
+ # default is the ylabel is not shown and xlabel is index name (reverse for barh)
+ ax = ser.plot(kind=kind)
+ if kind == "barh":
+ assert ax.get_xlabel() == ""
+ assert ax.get_ylabel() == old_label
+ elif kind == "hist":
+ assert ax.get_xlabel() == ""
+ assert ax.get_ylabel() == "Frequency"
+ else:
+ assert ax.get_ylabel() == ""
+ assert ax.get_xlabel() == old_label
+
+ # old xlabel will be overridden and assigned ylabel will be used as ylabel
+ ax = ser.plot(kind=kind, ylabel=new_label, xlabel=new_label)
+ assert ax.get_ylabel() == new_label
+ assert ax.get_xlabel() == new_label
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ pd.timedelta_range(start=0, periods=2, freq="D"),
+ [pd.Timedelta(days=1), pd.Timedelta(days=2)],
+ ],
+ )
+ def test_timedelta_index(self, index):
+ # GH37454
+ xlims = (3, 1)
+ ax = Series([1, 2], index=index).plot(xlim=(xlims))
+ assert ax.get_xlim() == (3, 1)
+
+ def test_series_none_color(self):
+ # GH51953
+ series = Series([1, 2, 3])
+ ax = series.plot(color=None)
+ expected = _unpack_cycler(mpl.pyplot.rcParams)[:1]
+ _check_colors(ax.get_lines(), linecolors=expected)
+
+ @pytest.mark.slow
+ def test_plot_no_warning(self, ts):
+ # GH 55138
+ # TODO(3.0): this can be removed once Period[B] deprecation is enforced
+ with tm.assert_produces_warning(False):
+ _ = ts.plot()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_style.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_style.py
new file mode 100644
index 0000000000000000000000000000000000000000..665bda15724fd67dc9917509d2b95957b03107e3
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/plotting/test_style.py
@@ -0,0 +1,157 @@
+import pytest
+
+from pandas import Series
+
+pytest.importorskip("matplotlib")
+from pandas.plotting._matplotlib.style import get_standard_colors
+
+
+class TestGetStandardColors:
+ @pytest.mark.parametrize(
+ "num_colors, expected",
+ [
+ (3, ["red", "green", "blue"]),
+ (5, ["red", "green", "blue", "red", "green"]),
+ (7, ["red", "green", "blue", "red", "green", "blue", "red"]),
+ (2, ["red", "green"]),
+ (1, ["red"]),
+ ],
+ )
+ def test_default_colors_named_from_prop_cycle(self, num_colors, expected):
+ import matplotlib as mpl
+ from matplotlib.pyplot import cycler
+
+ mpl_params = {
+ "axes.prop_cycle": cycler(color=["red", "green", "blue"]),
+ }
+ with mpl.rc_context(rc=mpl_params):
+ result = get_standard_colors(num_colors=num_colors)
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "num_colors, expected",
+ [
+ (1, ["b"]),
+ (3, ["b", "g", "r"]),
+ (4, ["b", "g", "r", "y"]),
+ (5, ["b", "g", "r", "y", "b"]),
+ (7, ["b", "g", "r", "y", "b", "g", "r"]),
+ ],
+ )
+ def test_default_colors_named_from_prop_cycle_string(self, num_colors, expected):
+ import matplotlib as mpl
+ from matplotlib.pyplot import cycler
+
+ mpl_params = {
+ "axes.prop_cycle": cycler(color="bgry"),
+ }
+ with mpl.rc_context(rc=mpl_params):
+ result = get_standard_colors(num_colors=num_colors)
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "num_colors, expected_name",
+ [
+ (1, ["C0"]),
+ (3, ["C0", "C1", "C2"]),
+ (
+ 12,
+ [
+ "C0",
+ "C1",
+ "C2",
+ "C3",
+ "C4",
+ "C5",
+ "C6",
+ "C7",
+ "C8",
+ "C9",
+ "C0",
+ "C1",
+ ],
+ ),
+ ],
+ )
+ def test_default_colors_named_undefined_prop_cycle(self, num_colors, expected_name):
+ import matplotlib as mpl
+ import matplotlib.colors as mcolors
+
+ with mpl.rc_context(rc={}):
+ expected = [mcolors.to_hex(x) for x in expected_name]
+ result = get_standard_colors(num_colors=num_colors)
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "num_colors, expected",
+ [
+ (1, ["red", "green", (0.1, 0.2, 0.3)]),
+ (2, ["red", "green", (0.1, 0.2, 0.3)]),
+ (3, ["red", "green", (0.1, 0.2, 0.3)]),
+ (4, ["red", "green", (0.1, 0.2, 0.3), "red"]),
+ ],
+ )
+ def test_user_input_color_sequence(self, num_colors, expected):
+ color = ["red", "green", (0.1, 0.2, 0.3)]
+ result = get_standard_colors(color=color, num_colors=num_colors)
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "num_colors, expected",
+ [
+ (1, ["r", "g", "b", "k"]),
+ (2, ["r", "g", "b", "k"]),
+ (3, ["r", "g", "b", "k"]),
+ (4, ["r", "g", "b", "k"]),
+ (5, ["r", "g", "b", "k", "r"]),
+ (6, ["r", "g", "b", "k", "r", "g"]),
+ ],
+ )
+ def test_user_input_color_string(self, num_colors, expected):
+ color = "rgbk"
+ result = get_standard_colors(color=color, num_colors=num_colors)
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "num_colors, expected",
+ [
+ (1, [(0.1, 0.2, 0.3)]),
+ (2, [(0.1, 0.2, 0.3), (0.1, 0.2, 0.3)]),
+ (3, [(0.1, 0.2, 0.3), (0.1, 0.2, 0.3), (0.1, 0.2, 0.3)]),
+ ],
+ )
+ def test_user_input_color_floats(self, num_colors, expected):
+ color = (0.1, 0.2, 0.3)
+ result = get_standard_colors(color=color, num_colors=num_colors)
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "color, num_colors, expected",
+ [
+ ("Crimson", 1, ["Crimson"]),
+ ("DodgerBlue", 2, ["DodgerBlue", "DodgerBlue"]),
+ ("firebrick", 3, ["firebrick", "firebrick", "firebrick"]),
+ ],
+ )
+ def test_user_input_named_color_string(self, color, num_colors, expected):
+ result = get_standard_colors(color=color, num_colors=num_colors)
+ assert result == expected
+
+ @pytest.mark.parametrize("color", ["", [], (), Series([], dtype="object")])
+ def test_empty_color_raises(self, color):
+ with pytest.raises(ValueError, match="Invalid color argument"):
+ get_standard_colors(color=color, num_colors=1)
+
+ @pytest.mark.parametrize(
+ "color",
+ [
+ "bad_color",
+ ("red", "green", "bad_color"),
+ (0.1,),
+ (0.1, 0.2),
+ (0.1, 0.2, 0.3, 0.4, 0.5), # must be either 3 or 4 floats
+ ],
+ )
+ def test_bad_color_raises(self, color):
+ with pytest.raises(ValueError, match="Invalid color"):
+ get_standard_colors(color=color, num_colors=5)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reductions/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reductions/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3851753b67421842a0d3d9fd5f88e7eb72734dd
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reductions/__init__.py
@@ -0,0 +1,4 @@
+"""
+Tests for reductions where we want to test for matching behavior across
+Array, Index, Series, and DataFrame methods.
+"""
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reductions/test_reductions.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reductions/test_reductions.py
new file mode 100644
index 0000000000000000000000000000000000000000..560b2377ada709ee0230b9fc5876f99e63874bcb
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reductions/test_reductions.py
@@ -0,0 +1,1661 @@
+from datetime import (
+ datetime,
+ timedelta,
+)
+from decimal import Decimal
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ NaT,
+ Period,
+ PeriodIndex,
+ RangeIndex,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ Timestamp,
+ date_range,
+ isna,
+ timedelta_range,
+ to_timedelta,
+)
+import pandas._testing as tm
+from pandas.core import nanops
+
+
+def get_objs():
+ indexes = [
+ tm.makeBoolIndex(10, name="a"),
+ tm.makeIntIndex(10, name="a"),
+ tm.makeFloatIndex(10, name="a"),
+ tm.makeDateIndex(10, name="a"),
+ tm.makeDateIndex(10, name="a").tz_localize(tz="US/Eastern"),
+ tm.makePeriodIndex(10, name="a"),
+ tm.makeStringIndex(10, name="a"),
+ ]
+
+ arr = np.random.default_rng(2).standard_normal(10)
+ series = [Series(arr, index=idx, name="a") for idx in indexes]
+
+ objs = indexes + series
+ return objs
+
+
+class TestReductions:
+ @pytest.mark.filterwarnings(
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
+ )
+ @pytest.mark.parametrize("opname", ["max", "min"])
+ @pytest.mark.parametrize("obj", get_objs())
+ def test_ops(self, opname, obj):
+ result = getattr(obj, opname)()
+ if not isinstance(obj, PeriodIndex):
+ expected = getattr(obj.values, opname)()
+ else:
+ expected = Period(ordinal=getattr(obj.asi8, opname)(), freq=obj.freq)
+
+ if getattr(obj, "tz", None) is not None:
+ # We need to de-localize before comparing to the numpy-produced result
+ expected = expected.astype("M8[ns]").astype("int64")
+ assert result._value == expected
+ else:
+ assert result == expected
+
+ @pytest.mark.parametrize("opname", ["max", "min"])
+ @pytest.mark.parametrize(
+ "dtype, val",
+ [
+ ("object", 2.0),
+ ("float64", 2.0),
+ ("datetime64[ns]", datetime(2011, 11, 1)),
+ ("Int64", 2),
+ ("boolean", True),
+ ],
+ )
+ def test_nanminmax(self, opname, dtype, val, index_or_series):
+ # GH#7261
+ klass = index_or_series
+
+ def check_missing(res):
+ if dtype == "datetime64[ns]":
+ return res is NaT
+ elif dtype in ["Int64", "boolean"]:
+ return res is pd.NA
+ else:
+ return isna(res)
+
+ obj = klass([None], dtype=dtype)
+ assert check_missing(getattr(obj, opname)())
+ assert check_missing(getattr(obj, opname)(skipna=False))
+
+ obj = klass([], dtype=dtype)
+ assert check_missing(getattr(obj, opname)())
+ assert check_missing(getattr(obj, opname)(skipna=False))
+
+ if dtype == "object":
+ # generic test with object only works for empty / all NaN
+ return
+
+ obj = klass([None, val], dtype=dtype)
+ assert getattr(obj, opname)() == val
+ assert check_missing(getattr(obj, opname)(skipna=False))
+
+ obj = klass([None, val, None], dtype=dtype)
+ assert getattr(obj, opname)() == val
+ assert check_missing(getattr(obj, opname)(skipna=False))
+
+ @pytest.mark.parametrize("opname", ["max", "min"])
+ def test_nanargminmax(self, opname, index_or_series):
+ # GH#7261
+ klass = index_or_series
+ arg_op = "arg" + opname if klass is Index else "idx" + opname
+
+ obj = klass([NaT, datetime(2011, 11, 1)])
+ assert getattr(obj, arg_op)() == 1
+
+ msg = (
+ "The behavior of (DatetimeIndex|Series).argmax/argmin with "
+ "skipna=False and NAs"
+ )
+ if klass is Series:
+ msg = "The behavior of Series.(idxmax|idxmin) with all-NA"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = getattr(obj, arg_op)(skipna=False)
+ if klass is Series:
+ assert np.isnan(result)
+ else:
+ assert result == -1
+
+ obj = klass([NaT, datetime(2011, 11, 1), NaT])
+ # check DatetimeIndex non-monotonic path
+ assert getattr(obj, arg_op)() == 1
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = getattr(obj, arg_op)(skipna=False)
+ if klass is Series:
+ assert np.isnan(result)
+ else:
+ assert result == -1
+
+ @pytest.mark.parametrize("opname", ["max", "min"])
+ @pytest.mark.parametrize("dtype", ["M8[ns]", "datetime64[ns, UTC]"])
+ def test_nanops_empty_object(self, opname, index_or_series, dtype):
+ klass = index_or_series
+ arg_op = "arg" + opname if klass is Index else "idx" + opname
+
+ obj = klass([], dtype=dtype)
+
+ assert getattr(obj, opname)() is NaT
+ assert getattr(obj, opname)(skipna=False) is NaT
+
+ with pytest.raises(ValueError, match="empty sequence"):
+ getattr(obj, arg_op)()
+ with pytest.raises(ValueError, match="empty sequence"):
+ getattr(obj, arg_op)(skipna=False)
+
+ def test_argminmax(self):
+ obj = Index(np.arange(5, dtype="int64"))
+ assert obj.argmin() == 0
+ assert obj.argmax() == 4
+
+ obj = Index([np.nan, 1, np.nan, 2])
+ assert obj.argmin() == 1
+ assert obj.argmax() == 3
+ msg = "The behavior of Index.argmax/argmin with skipna=False and NAs"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmin(skipna=False) == -1
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmax(skipna=False) == -1
+
+ obj = Index([np.nan])
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmin() == -1
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmax() == -1
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmin(skipna=False) == -1
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmax(skipna=False) == -1
+
+ msg = "The behavior of DatetimeIndex.argmax/argmin with skipna=False and NAs"
+ obj = Index([NaT, datetime(2011, 11, 1), datetime(2011, 11, 2), NaT])
+ assert obj.argmin() == 1
+ assert obj.argmax() == 2
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmin(skipna=False) == -1
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmax(skipna=False) == -1
+
+ obj = Index([NaT])
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmin() == -1
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmax() == -1
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmin(skipna=False) == -1
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert obj.argmax(skipna=False) == -1
+
+ @pytest.mark.parametrize("op, expected_col", [["max", "a"], ["min", "b"]])
+ def test_same_tz_min_max_axis_1(self, op, expected_col):
+ # GH 10390
+ df = DataFrame(
+ date_range("2016-01-01 00:00:00", periods=3, tz="UTC"), columns=["a"]
+ )
+ df["b"] = df.a.subtract(Timedelta(seconds=3600))
+ result = getattr(df, op)(axis=1)
+ expected = df[expected_col].rename(None)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("func", ["maximum", "minimum"])
+ def test_numpy_reduction_with_tz_aware_dtype(self, tz_aware_fixture, func):
+ # GH 15552
+ tz = tz_aware_fixture
+ arg = pd.to_datetime(["2019"]).tz_localize(tz)
+ expected = Series(arg)
+ result = getattr(np, func)(expected, expected)
+ tm.assert_series_equal(result, expected)
+
+ def test_nan_int_timedelta_sum(self):
+ # GH 27185
+ df = DataFrame(
+ {
+ "A": Series([1, 2, NaT], dtype="timedelta64[ns]"),
+ "B": Series([1, 2, np.nan], dtype="Int64"),
+ }
+ )
+ expected = Series({"A": Timedelta(3), "B": 3})
+ result = df.sum()
+ tm.assert_series_equal(result, expected)
+
+
+class TestIndexReductions:
+ # Note: the name TestIndexReductions indicates these tests
+ # were moved from a Index-specific test file, _not_ that these tests are
+ # intended long-term to be Index-specific
+
+ @pytest.mark.parametrize(
+ "start,stop,step",
+ [
+ (0, 400, 3),
+ (500, 0, -6),
+ (-(10**6), 10**6, 4),
+ (10**6, -(10**6), -4),
+ (0, 10, 20),
+ ],
+ )
+ def test_max_min_range(self, start, stop, step):
+ # GH#17607
+ idx = RangeIndex(start, stop, step)
+ expected = idx._values.max()
+ result = idx.max()
+ assert result == expected
+
+ # skipna should be irrelevant since RangeIndex should never have NAs
+ result2 = idx.max(skipna=False)
+ assert result2 == expected
+
+ expected = idx._values.min()
+ result = idx.min()
+ assert result == expected
+
+ # skipna should be irrelevant since RangeIndex should never have NAs
+ result2 = idx.min(skipna=False)
+ assert result2 == expected
+
+ # empty
+ idx = RangeIndex(start, stop, -step)
+ assert isna(idx.max())
+ assert isna(idx.min())
+
+ def test_minmax_timedelta64(self):
+ # monotonic
+ idx1 = TimedeltaIndex(["1 days", "2 days", "3 days"])
+ assert idx1.is_monotonic_increasing
+
+ # non-monotonic
+ idx2 = TimedeltaIndex(["1 days", np.nan, "3 days", "NaT"])
+ assert not idx2.is_monotonic_increasing
+
+ for idx in [idx1, idx2]:
+ assert idx.min() == Timedelta("1 days")
+ assert idx.max() == Timedelta("3 days")
+ assert idx.argmin() == 0
+ assert idx.argmax() == 2
+
+ @pytest.mark.parametrize("op", ["min", "max"])
+ def test_minmax_timedelta_empty_or_na(self, op):
+ # Return NaT
+ obj = TimedeltaIndex([])
+ assert getattr(obj, op)() is NaT
+
+ obj = TimedeltaIndex([NaT])
+ assert getattr(obj, op)() is NaT
+
+ obj = TimedeltaIndex([NaT, NaT, NaT])
+ assert getattr(obj, op)() is NaT
+
+ def test_numpy_minmax_timedelta64(self):
+ td = timedelta_range("16815 days", "16820 days", freq="D")
+
+ assert np.min(td) == Timedelta("16815 days")
+ assert np.max(td) == Timedelta("16820 days")
+
+ errmsg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=errmsg):
+ np.min(td, out=0)
+ with pytest.raises(ValueError, match=errmsg):
+ np.max(td, out=0)
+
+ assert np.argmin(td) == 0
+ assert np.argmax(td) == 5
+
+ errmsg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=errmsg):
+ np.argmin(td, out=0)
+ with pytest.raises(ValueError, match=errmsg):
+ np.argmax(td, out=0)
+
+ def test_timedelta_ops(self):
+ # GH#4984
+ # make sure ops return Timedelta
+ s = Series(
+ [Timestamp("20130101") + timedelta(seconds=i * i) for i in range(10)]
+ )
+ td = s.diff()
+
+ result = td.mean()
+ expected = to_timedelta(timedelta(seconds=9))
+ assert result == expected
+
+ result = td.to_frame().mean()
+ assert result[0] == expected
+
+ result = td.quantile(0.1)
+ expected = Timedelta(np.timedelta64(2600, "ms"))
+ assert result == expected
+
+ result = td.median()
+ expected = to_timedelta("00:00:09")
+ assert result == expected
+
+ result = td.to_frame().median()
+ assert result[0] == expected
+
+ # GH#6462
+ # consistency in returned values for sum
+ result = td.sum()
+ expected = to_timedelta("00:01:21")
+ assert result == expected
+
+ result = td.to_frame().sum()
+ assert result[0] == expected
+
+ # std
+ result = td.std()
+ expected = to_timedelta(Series(td.dropna().values).std())
+ assert result == expected
+
+ result = td.to_frame().std()
+ assert result[0] == expected
+
+ # GH#10040
+ # make sure NaT is properly handled by median()
+ s = Series([Timestamp("2015-02-03"), Timestamp("2015-02-07")])
+ assert s.diff().median() == timedelta(days=4)
+
+ s = Series(
+ [Timestamp("2015-02-03"), Timestamp("2015-02-07"), Timestamp("2015-02-15")]
+ )
+ assert s.diff().median() == timedelta(days=6)
+
+ @pytest.mark.parametrize("opname", ["skew", "kurt", "sem", "prod", "var"])
+ def test_invalid_td64_reductions(self, opname):
+ s = Series(
+ [Timestamp("20130101") + timedelta(seconds=i * i) for i in range(10)]
+ )
+ td = s.diff()
+
+ msg = "|".join(
+ [
+ f"reduction operation '{opname}' not allowed for this dtype",
+ rf"cannot perform {opname} with type timedelta64\[ns\]",
+ f"does not support reduction '{opname}'",
+ ]
+ )
+
+ with pytest.raises(TypeError, match=msg):
+ getattr(td, opname)()
+
+ with pytest.raises(TypeError, match=msg):
+ getattr(td.to_frame(), opname)(numeric_only=False)
+
+ def test_minmax_tz(self, tz_naive_fixture):
+ tz = tz_naive_fixture
+ # monotonic
+ idx1 = DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], tz=tz)
+ assert idx1.is_monotonic_increasing
+
+ # non-monotonic
+ idx2 = DatetimeIndex(
+ ["2011-01-01", NaT, "2011-01-03", "2011-01-02", NaT], tz=tz
+ )
+ assert not idx2.is_monotonic_increasing
+
+ for idx in [idx1, idx2]:
+ assert idx.min() == Timestamp("2011-01-01", tz=tz)
+ assert idx.max() == Timestamp("2011-01-03", tz=tz)
+ assert idx.argmin() == 0
+ assert idx.argmax() == 2
+
+ @pytest.mark.parametrize("op", ["min", "max"])
+ def test_minmax_nat_datetime64(self, op):
+ # Return NaT
+ obj = DatetimeIndex([])
+ assert isna(getattr(obj, op)())
+
+ obj = DatetimeIndex([NaT])
+ assert isna(getattr(obj, op)())
+
+ obj = DatetimeIndex([NaT, NaT, NaT])
+ assert isna(getattr(obj, op)())
+
+ def test_numpy_minmax_integer(self):
+ # GH#26125
+ idx = Index([1, 2, 3])
+
+ expected = idx.values.max()
+ result = np.max(idx)
+ assert result == expected
+
+ expected = idx.values.min()
+ result = np.min(idx)
+ assert result == expected
+
+ errmsg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=errmsg):
+ np.min(idx, out=0)
+ with pytest.raises(ValueError, match=errmsg):
+ np.max(idx, out=0)
+
+ expected = idx.values.argmax()
+ result = np.argmax(idx)
+ assert result == expected
+
+ expected = idx.values.argmin()
+ result = np.argmin(idx)
+ assert result == expected
+
+ errmsg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=errmsg):
+ np.argmin(idx, out=0)
+ with pytest.raises(ValueError, match=errmsg):
+ np.argmax(idx, out=0)
+
+ def test_numpy_minmax_range(self):
+ # GH#26125
+ idx = RangeIndex(0, 10, 3)
+
+ result = np.max(idx)
+ assert result == 9
+
+ result = np.min(idx)
+ assert result == 0
+
+ errmsg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=errmsg):
+ np.min(idx, out=0)
+ with pytest.raises(ValueError, match=errmsg):
+ np.max(idx, out=0)
+
+ # No need to test again argmax/argmin compat since the implementation
+ # is the same as basic integer index
+
+ def test_numpy_minmax_datetime64(self):
+ dr = date_range(start="2016-01-15", end="2016-01-20")
+
+ assert np.min(dr) == Timestamp("2016-01-15 00:00:00")
+ assert np.max(dr) == Timestamp("2016-01-20 00:00:00")
+
+ errmsg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=errmsg):
+ np.min(dr, out=0)
+
+ with pytest.raises(ValueError, match=errmsg):
+ np.max(dr, out=0)
+
+ assert np.argmin(dr) == 0
+ assert np.argmax(dr) == 5
+
+ errmsg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=errmsg):
+ np.argmin(dr, out=0)
+
+ with pytest.raises(ValueError, match=errmsg):
+ np.argmax(dr, out=0)
+
+ def test_minmax_period(self):
+ # monotonic
+ idx1 = PeriodIndex([NaT, "2011-01-01", "2011-01-02", "2011-01-03"], freq="D")
+ assert not idx1.is_monotonic_increasing
+ assert idx1[1:].is_monotonic_increasing
+
+ # non-monotonic
+ idx2 = PeriodIndex(
+ ["2011-01-01", NaT, "2011-01-03", "2011-01-02", NaT], freq="D"
+ )
+ assert not idx2.is_monotonic_increasing
+
+ for idx in [idx1, idx2]:
+ assert idx.min() == Period("2011-01-01", freq="D")
+ assert idx.max() == Period("2011-01-03", freq="D")
+ assert idx1.argmin() == 1
+ assert idx2.argmin() == 0
+ assert idx1.argmax() == 3
+ assert idx2.argmax() == 2
+
+ @pytest.mark.parametrize("op", ["min", "max"])
+ @pytest.mark.parametrize("data", [[], [NaT], [NaT, NaT, NaT]])
+ def test_minmax_period_empty_nat(self, op, data):
+ # Return NaT
+ obj = PeriodIndex(data, freq="M")
+ result = getattr(obj, op)()
+ assert result is NaT
+
+ def test_numpy_minmax_period(self):
+ pr = pd.period_range(start="2016-01-15", end="2016-01-20")
+
+ assert np.min(pr) == Period("2016-01-15", freq="D")
+ assert np.max(pr) == Period("2016-01-20", freq="D")
+
+ errmsg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=errmsg):
+ np.min(pr, out=0)
+ with pytest.raises(ValueError, match=errmsg):
+ np.max(pr, out=0)
+
+ assert np.argmin(pr) == 0
+ assert np.argmax(pr) == 5
+
+ errmsg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=errmsg):
+ np.argmin(pr, out=0)
+ with pytest.raises(ValueError, match=errmsg):
+ np.argmax(pr, out=0)
+
+ def test_min_max_categorical(self):
+ ci = pd.CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
+ msg = (
+ r"Categorical is not ordered for operation min\n"
+ r"you can use .as_ordered\(\) to change the Categorical to an ordered one\n"
+ )
+ with pytest.raises(TypeError, match=msg):
+ ci.min()
+ msg = (
+ r"Categorical is not ordered for operation max\n"
+ r"you can use .as_ordered\(\) to change the Categorical to an ordered one\n"
+ )
+ with pytest.raises(TypeError, match=msg):
+ ci.max()
+
+ ci = pd.CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=True)
+ assert ci.min() == "c"
+ assert ci.max() == "b"
+
+
+class TestSeriesReductions:
+ # Note: the name TestSeriesReductions indicates these tests
+ # were moved from a series-specific test file, _not_ that these tests are
+ # intended long-term to be series-specific
+
+ def test_sum_inf(self):
+ s = Series(np.random.default_rng(2).standard_normal(10))
+ s2 = s.copy()
+
+ s[5:8] = np.inf
+ s2[5:8] = np.nan
+
+ assert np.isinf(s.sum())
+
+ arr = np.random.default_rng(2).standard_normal((100, 100)).astype("f4")
+ arr[:, 2] = np.inf
+
+ msg = "use_inf_as_na option is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ with pd.option_context("mode.use_inf_as_na", True):
+ tm.assert_almost_equal(s.sum(), s2.sum())
+
+ res = nanops.nansum(arr, axis=1)
+ assert np.isinf(res).all()
+
+ @pytest.mark.parametrize(
+ "dtype", ["float64", "Float32", "Int64", "boolean", "object"]
+ )
+ @pytest.mark.parametrize("use_bottleneck", [True, False])
+ @pytest.mark.parametrize("method, unit", [("sum", 0.0), ("prod", 1.0)])
+ def test_empty(self, method, unit, use_bottleneck, dtype):
+ with pd.option_context("use_bottleneck", use_bottleneck):
+ # GH#9422 / GH#18921
+ # Entirely empty
+ s = Series([], dtype=dtype)
+ # NA by default
+ result = getattr(s, method)()
+ assert result == unit
+
+ # Explicit
+ result = getattr(s, method)(min_count=0)
+ assert result == unit
+
+ result = getattr(s, method)(min_count=1)
+ assert isna(result)
+
+ # Skipna, default
+ result = getattr(s, method)(skipna=True)
+ result == unit
+
+ # Skipna, explicit
+ result = getattr(s, method)(skipna=True, min_count=0)
+ assert result == unit
+
+ result = getattr(s, method)(skipna=True, min_count=1)
+ assert isna(result)
+
+ result = getattr(s, method)(skipna=False, min_count=0)
+ assert result == unit
+
+ result = getattr(s, method)(skipna=False, min_count=1)
+ assert isna(result)
+
+ # All-NA
+ s = Series([np.nan], dtype=dtype)
+ # NA by default
+ result = getattr(s, method)()
+ assert result == unit
+
+ # Explicit
+ result = getattr(s, method)(min_count=0)
+ assert result == unit
+
+ result = getattr(s, method)(min_count=1)
+ assert isna(result)
+
+ # Skipna, default
+ result = getattr(s, method)(skipna=True)
+ result == unit
+
+ # skipna, explicit
+ result = getattr(s, method)(skipna=True, min_count=0)
+ assert result == unit
+
+ result = getattr(s, method)(skipna=True, min_count=1)
+ assert isna(result)
+
+ # Mix of valid, empty
+ s = Series([np.nan, 1], dtype=dtype)
+ # Default
+ result = getattr(s, method)()
+ assert result == 1.0
+
+ # Explicit
+ result = getattr(s, method)(min_count=0)
+ assert result == 1.0
+
+ result = getattr(s, method)(min_count=1)
+ assert result == 1.0
+
+ # Skipna
+ result = getattr(s, method)(skipna=True)
+ assert result == 1.0
+
+ result = getattr(s, method)(skipna=True, min_count=0)
+ assert result == 1.0
+
+ # GH#844 (changed in GH#9422)
+ df = DataFrame(np.empty((10, 0)), dtype=dtype)
+ assert (getattr(df, method)(1) == unit).all()
+
+ s = Series([1], dtype=dtype)
+ result = getattr(s, method)(min_count=2)
+ assert isna(result)
+
+ result = getattr(s, method)(skipna=False, min_count=2)
+ assert isna(result)
+
+ s = Series([np.nan], dtype=dtype)
+ result = getattr(s, method)(min_count=2)
+ assert isna(result)
+
+ s = Series([np.nan, 1], dtype=dtype)
+ result = getattr(s, method)(min_count=2)
+ assert isna(result)
+
+ @pytest.mark.parametrize("method", ["mean", "var"])
+ @pytest.mark.parametrize("dtype", ["Float64", "Int64", "boolean"])
+ def test_ops_consistency_on_empty_nullable(self, method, dtype):
+ # GH#34814
+ # consistency for nullable dtypes on empty or ALL-NA mean
+
+ # empty series
+ eser = Series([], dtype=dtype)
+ result = getattr(eser, method)()
+ assert result is pd.NA
+
+ # ALL-NA series
+ nser = Series([np.nan], dtype=dtype)
+ result = getattr(nser, method)()
+ assert result is pd.NA
+
+ @pytest.mark.parametrize("method", ["mean", "median", "std", "var"])
+ def test_ops_consistency_on_empty(self, method):
+ # GH#7869
+ # consistency on empty
+
+ # float
+ result = getattr(Series(dtype=float), method)()
+ assert isna(result)
+
+ # timedelta64[ns]
+ tdser = Series([], dtype="m8[ns]")
+ if method == "var":
+ msg = "|".join(
+ [
+ "operation 'var' not allowed",
+ r"cannot perform var with type timedelta64\[ns\]",
+ "does not support reduction 'var'",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ getattr(tdser, method)()
+ else:
+ result = getattr(tdser, method)()
+ assert result is NaT
+
+ def test_nansum_buglet(self):
+ ser = Series([1.0, np.nan], index=[0, 1])
+ result = np.nansum(ser)
+ tm.assert_almost_equal(result, 1)
+
+ @pytest.mark.parametrize("use_bottleneck", [True, False])
+ @pytest.mark.parametrize("dtype", ["int32", "int64"])
+ def test_sum_overflow_int(self, use_bottleneck, dtype):
+ with pd.option_context("use_bottleneck", use_bottleneck):
+ # GH#6915
+ # overflowing on the smaller int dtypes
+ v = np.arange(5000000, dtype=dtype)
+ s = Series(v)
+
+ result = s.sum(skipna=False)
+ assert int(result) == v.sum(dtype="int64")
+ result = s.min(skipna=False)
+ assert int(result) == 0
+ result = s.max(skipna=False)
+ assert int(result) == v[-1]
+
+ @pytest.mark.parametrize("use_bottleneck", [True, False])
+ @pytest.mark.parametrize("dtype", ["float32", "float64"])
+ def test_sum_overflow_float(self, use_bottleneck, dtype):
+ with pd.option_context("use_bottleneck", use_bottleneck):
+ v = np.arange(5000000, dtype=dtype)
+ s = Series(v)
+
+ result = s.sum(skipna=False)
+ assert result == v.sum(dtype=dtype)
+ result = s.min(skipna=False)
+ assert np.allclose(float(result), 0.0)
+ result = s.max(skipna=False)
+ assert np.allclose(float(result), v[-1])
+
+ def test_mean_masked_overflow(self):
+ # GH#48378
+ val = 100_000_000_000_000_000
+ n_elements = 100
+ na = np.array([val] * n_elements)
+ ser = Series([val] * n_elements, dtype="Int64")
+
+ result_numpy = np.mean(na)
+ result_masked = ser.mean()
+ assert result_masked - result_numpy == 0
+ assert result_masked == 1e17
+
+ @pytest.mark.parametrize("ddof, exp", [(1, 2.5), (0, 2.0)])
+ def test_var_masked_array(self, ddof, exp):
+ # GH#48379
+ ser = Series([1, 2, 3, 4, 5], dtype="Int64")
+ ser_numpy_dtype = Series([1, 2, 3, 4, 5], dtype="int64")
+ result = ser.var(ddof=ddof)
+ result_numpy_dtype = ser_numpy_dtype.var(ddof=ddof)
+ assert result == result_numpy_dtype
+ assert result == exp
+
+ @pytest.mark.parametrize("dtype", ("m8[ns]", "m8[ns]", "M8[ns]", "M8[ns, UTC]"))
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_empty_timeseries_reductions_return_nat(self, dtype, skipna):
+ # covers GH#11245
+ assert Series([], dtype=dtype).min(skipna=skipna) is NaT
+ assert Series([], dtype=dtype).max(skipna=skipna) is NaT
+
+ def test_numpy_argmin(self):
+ # See GH#16830
+ data = np.arange(1, 11)
+
+ s = Series(data, index=data)
+ result = np.argmin(s)
+
+ expected = np.argmin(data)
+ assert result == expected
+
+ result = s.argmin()
+
+ assert result == expected
+
+ msg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ np.argmin(s, out=data)
+
+ def test_numpy_argmax(self):
+ # See GH#16830
+ data = np.arange(1, 11)
+
+ s = Series(data, index=data)
+ result = np.argmax(s)
+ expected = np.argmax(data)
+ assert result == expected
+
+ result = s.argmax()
+
+ assert result == expected
+
+ msg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ np.argmax(s, out=data)
+
+ def test_idxmin_dt64index(self):
+ # GH#43587 should have NaT instead of NaN
+ ser = Series(
+ [1.0, 2.0, np.nan], index=DatetimeIndex(["NaT", "2015-02-08", "NaT"])
+ )
+ msg = "The behavior of Series.idxmin with all-NA values"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = ser.idxmin(skipna=False)
+ assert res is NaT
+ msg = "The behavior of Series.idxmax with all-NA values"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = ser.idxmax(skipna=False)
+ assert res is NaT
+
+ df = ser.to_frame()
+ msg = "The behavior of DataFrame.idxmin with all-NA values"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = df.idxmin(skipna=False)
+ assert res.dtype == "M8[ns]"
+ assert res.isna().all()
+ msg = "The behavior of DataFrame.idxmax with all-NA values"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = df.idxmax(skipna=False)
+ assert res.dtype == "M8[ns]"
+ assert res.isna().all()
+
+ def test_idxmin(self):
+ # test idxmin
+ # _check_stat_op approach can not be used here because of isna check.
+ string_series = tm.makeStringSeries().rename("series")
+
+ # add some NaNs
+ string_series[5:15] = np.nan
+
+ # skipna or no
+ assert string_series[string_series.idxmin()] == string_series.min()
+ msg = "The behavior of Series.idxmin"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert isna(string_series.idxmin(skipna=False))
+
+ # no NaNs
+ nona = string_series.dropna()
+ assert nona[nona.idxmin()] == nona.min()
+ assert nona.index.values.tolist().index(nona.idxmin()) == nona.values.argmin()
+
+ # all NaNs
+ allna = string_series * np.nan
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert isna(allna.idxmin())
+
+ # datetime64[ns]
+ s = Series(date_range("20130102", periods=6))
+ result = s.idxmin()
+ assert result == 0
+
+ s[0] = np.nan
+ result = s.idxmin()
+ assert result == 1
+
+ def test_idxmax(self):
+ # test idxmax
+ # _check_stat_op approach can not be used here because of isna check.
+ string_series = tm.makeStringSeries().rename("series")
+
+ # add some NaNs
+ string_series[5:15] = np.nan
+
+ # skipna or no
+ assert string_series[string_series.idxmax()] == string_series.max()
+ msg = "The behavior of Series.idxmax with all-NA values"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert isna(string_series.idxmax(skipna=False))
+
+ # no NaNs
+ nona = string_series.dropna()
+ assert nona[nona.idxmax()] == nona.max()
+ assert nona.index.values.tolist().index(nona.idxmax()) == nona.values.argmax()
+
+ # all NaNs
+ allna = string_series * np.nan
+ msg = "The behavior of Series.idxmax with all-NA values"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert isna(allna.idxmax())
+
+ s = Series(date_range("20130102", periods=6))
+ result = s.idxmax()
+ assert result == 5
+
+ s[5] = np.nan
+ result = s.idxmax()
+ assert result == 4
+
+ # Index with float64 dtype
+ # GH#5914
+ s = Series([1, 2, 3], [1.1, 2.1, 3.1])
+ result = s.idxmax()
+ assert result == 3.1
+ result = s.idxmin()
+ assert result == 1.1
+
+ s = Series(s.index, s.index)
+ result = s.idxmax()
+ assert result == 3.1
+ result = s.idxmin()
+ assert result == 1.1
+
+ def test_all_any(self):
+ ts = tm.makeTimeSeries()
+ bool_series = ts > 0
+ assert not bool_series.all()
+ assert bool_series.any()
+
+ # Alternative types, with implicit 'object' dtype.
+ s = Series(["abc", True])
+ assert s.any()
+
+ def test_numpy_all_any(self, index_or_series):
+ # GH#40180
+ idx = index_or_series([0, 1, 2])
+ assert not np.all(idx)
+ assert np.any(idx)
+ idx = Index([1, 2, 3])
+ assert np.all(idx)
+
+ def test_all_any_skipna(self):
+ # Check skipna, with implicit 'object' dtype.
+ s1 = Series([np.nan, True])
+ s2 = Series([np.nan, False])
+ assert s1.all(skipna=False) # nan && True => True
+ assert s1.all(skipna=True)
+ assert s2.any(skipna=False)
+ assert not s2.any(skipna=True)
+
+ def test_all_any_bool_only(self):
+ s = Series([False, False, True, True, False, True], index=[0, 0, 1, 1, 2, 2])
+
+ # GH#47500 - test bool_only works
+ assert s.any(bool_only=True)
+ assert not s.all(bool_only=True)
+
+ @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_any_all_object_dtype(self, bool_agg_func, skipna):
+ # GH#12863
+ ser = Series(["a", "b", "c", "d", "e"], dtype=object)
+ result = getattr(ser, bool_agg_func)(skipna=skipna)
+ expected = True
+
+ assert result == expected
+
+ @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
+ @pytest.mark.parametrize(
+ "data", [[False, None], [None, False], [False, np.nan], [np.nan, False]]
+ )
+ def test_any_all_object_dtype_missing(self, data, bool_agg_func):
+ # GH#27709
+ ser = Series(data)
+ result = getattr(ser, bool_agg_func)(skipna=False)
+
+ # None is treated is False, but np.nan is treated as True
+ expected = bool_agg_func == "any" and None not in data
+ assert result == expected
+
+ @pytest.mark.parametrize("dtype", ["boolean", "Int64", "UInt64", "Float64"])
+ @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
+ @pytest.mark.parametrize("skipna", [True, False])
+ @pytest.mark.parametrize(
+ # expected_data indexed as [[skipna=False/any, skipna=False/all],
+ # [skipna=True/any, skipna=True/all]]
+ "data,expected_data",
+ [
+ ([0, 0, 0], [[False, False], [False, False]]),
+ ([1, 1, 1], [[True, True], [True, True]]),
+ ([pd.NA, pd.NA, pd.NA], [[pd.NA, pd.NA], [False, True]]),
+ ([0, pd.NA, 0], [[pd.NA, False], [False, False]]),
+ ([1, pd.NA, 1], [[True, pd.NA], [True, True]]),
+ ([1, pd.NA, 0], [[True, False], [True, False]]),
+ ],
+ )
+ def test_any_all_nullable_kleene_logic(
+ self, bool_agg_func, skipna, data, dtype, expected_data
+ ):
+ # GH-37506, GH-41967
+ ser = Series(data, dtype=dtype)
+ expected = expected_data[skipna][bool_agg_func == "all"]
+
+ result = getattr(ser, bool_agg_func)(skipna=skipna)
+ assert (result is pd.NA and expected is pd.NA) or result == expected
+
+ def test_any_axis1_bool_only(self):
+ # GH#32432
+ df = DataFrame({"A": [True, False], "B": [1, 2]})
+ result = df.any(axis=1, bool_only=True)
+ expected = Series([True, False])
+ tm.assert_series_equal(result, expected)
+
+ def test_any_all_datetimelike(self):
+ # GH#38723 these may not be the desired long-term behavior (GH#34479)
+ # but in the interim should be internally consistent
+ dta = date_range("1995-01-02", periods=3)._data
+ ser = Series(dta)
+ df = DataFrame(ser)
+
+ msg = "'(any|all)' with datetime64 dtypes is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#34479
+ assert dta.all()
+ assert dta.any()
+
+ assert ser.all()
+ assert ser.any()
+
+ assert df.any().all()
+ assert df.all().all()
+
+ dta = dta.tz_localize("UTC")
+ ser = Series(dta)
+ df = DataFrame(ser)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#34479
+ assert dta.all()
+ assert dta.any()
+
+ assert ser.all()
+ assert ser.any()
+
+ assert df.any().all()
+ assert df.all().all()
+
+ tda = dta - dta[0]
+ ser = Series(tda)
+ df = DataFrame(ser)
+
+ assert tda.any()
+ assert not tda.all()
+
+ assert ser.any()
+ assert not ser.all()
+
+ assert df.any().all()
+ assert not df.all().any()
+
+ def test_any_all_pyarrow_string(self):
+ # GH#54591
+ pytest.importorskip("pyarrow")
+ ser = Series(["", "a"], dtype="string[pyarrow_numpy]")
+ assert ser.any()
+ assert not ser.all()
+
+ ser = Series([None, "a"], dtype="string[pyarrow_numpy]")
+ assert ser.any()
+ assert ser.all()
+ assert not ser.all(skipna=False)
+
+ ser = Series([None, ""], dtype="string[pyarrow_numpy]")
+ assert not ser.any()
+ assert not ser.all()
+
+ ser = Series(["a", "b"], dtype="string[pyarrow_numpy]")
+ assert ser.any()
+ assert ser.all()
+
+ def test_timedelta64_analytics(self):
+ # index min/max
+ dti = date_range("2012-1-1", periods=3, freq="D")
+ td = Series(dti) - Timestamp("20120101")
+
+ result = td.idxmin()
+ assert result == 0
+
+ result = td.idxmax()
+ assert result == 2
+
+ # GH#2982
+ # with NaT
+ td[0] = np.nan
+
+ result = td.idxmin()
+ assert result == 1
+
+ result = td.idxmax()
+ assert result == 2
+
+ # abs
+ s1 = Series(date_range("20120101", periods=3))
+ s2 = Series(date_range("20120102", periods=3))
+ expected = Series(s2 - s1)
+
+ result = np.abs(s1 - s2)
+ tm.assert_series_equal(result, expected)
+
+ result = (s1 - s2).abs()
+ tm.assert_series_equal(result, expected)
+
+ # max/min
+ result = td.max()
+ expected = Timedelta("2 days")
+ assert result == expected
+
+ result = td.min()
+ expected = Timedelta("1 days")
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "test_input,error_type",
+ [
+ (Series([], dtype="float64"), ValueError),
+ # For strings, or any Series with dtype 'O'
+ (Series(["foo", "bar", "baz"]), TypeError),
+ (Series([(1,), (2,)]), TypeError),
+ # For mixed data types
+ (Series(["foo", "foo", "bar", "bar", None, np.nan, "baz"]), TypeError),
+ ],
+ )
+ def test_assert_idxminmax_empty_raises(self, test_input, error_type):
+ """
+ Cases where ``Series.argmax`` and related should raise an exception
+ """
+ test_input = Series([], dtype="float64")
+ msg = "attempt to get argmin of an empty sequence"
+ with pytest.raises(ValueError, match=msg):
+ test_input.idxmin()
+ with pytest.raises(ValueError, match=msg):
+ test_input.idxmin(skipna=False)
+ msg = "attempt to get argmax of an empty sequence"
+ with pytest.raises(ValueError, match=msg):
+ test_input.idxmax()
+ with pytest.raises(ValueError, match=msg):
+ test_input.idxmax(skipna=False)
+
+ def test_idxminmax_object_dtype(self):
+ # pre-2.1 object-dtype was disallowed for argmin/max
+ ser = Series(["foo", "bar", "baz"])
+ assert ser.idxmax() == 0
+ assert ser.idxmax(skipna=False) == 0
+ assert ser.idxmin() == 1
+ assert ser.idxmin(skipna=False) == 1
+
+ ser2 = Series([(1,), (2,)])
+ assert ser2.idxmax() == 1
+ assert ser2.idxmax(skipna=False) == 1
+ assert ser2.idxmin() == 0
+ assert ser2.idxmin(skipna=False) == 0
+
+ # attempting to compare np.nan with string raises
+ ser3 = Series(["foo", "foo", "bar", "bar", None, np.nan, "baz"])
+ msg = "'>' not supported between instances of 'float' and 'str'"
+ with pytest.raises(TypeError, match=msg):
+ ser3.idxmax()
+ with pytest.raises(TypeError, match=msg):
+ ser3.idxmax(skipna=False)
+ msg = "'<' not supported between instances of 'float' and 'str'"
+ with pytest.raises(TypeError, match=msg):
+ ser3.idxmin()
+ with pytest.raises(TypeError, match=msg):
+ ser3.idxmin(skipna=False)
+
+ def test_idxminmax_object_frame(self):
+ # GH#4279
+ df = DataFrame([["zimm", 2.5], ["biff", 1.0], ["bid", 12.0]])
+ res = df.idxmax()
+ exp = Series([0, 2])
+ tm.assert_series_equal(res, exp)
+
+ def test_idxminmax_object_tuples(self):
+ # GH#43697
+ ser = Series([(1, 3), (2, 2), (3, 1)])
+ assert ser.idxmax() == 2
+ assert ser.idxmin() == 0
+ assert ser.idxmax(skipna=False) == 2
+ assert ser.idxmin(skipna=False) == 0
+
+ def test_idxminmax_object_decimals(self):
+ # GH#40685
+ df = DataFrame(
+ {
+ "idx": [0, 1],
+ "x": [Decimal("8.68"), Decimal("42.23")],
+ "y": [Decimal("7.11"), Decimal("79.61")],
+ }
+ )
+ res = df.idxmax()
+ exp = Series({"idx": 1, "x": 1, "y": 1})
+ tm.assert_series_equal(res, exp)
+
+ res2 = df.idxmin()
+ exp2 = exp - 1
+ tm.assert_series_equal(res2, exp2)
+
+ def test_argminmax_object_ints(self):
+ # GH#18021
+ ser = Series([0, 1], dtype="object")
+ assert ser.argmax() == 1
+ assert ser.argmin() == 0
+ assert ser.argmax(skipna=False) == 1
+ assert ser.argmin(skipna=False) == 0
+
+ def test_idxminmax_with_inf(self):
+ # For numeric data with NA and Inf (GH #13595)
+ s = Series([0, -np.inf, np.inf, np.nan])
+
+ assert s.idxmin() == 1
+ msg = "The behavior of Series.idxmin with all-NA values"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert np.isnan(s.idxmin(skipna=False))
+
+ assert s.idxmax() == 2
+ msg = "The behavior of Series.idxmax with all-NA values"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert np.isnan(s.idxmax(skipna=False))
+
+ msg = "use_inf_as_na option is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # Using old-style behavior that treats floating point nan, -inf, and
+ # +inf as missing
+ with pd.option_context("mode.use_inf_as_na", True):
+ assert s.idxmin() == 0
+ assert np.isnan(s.idxmin(skipna=False))
+ assert s.idxmax() == 0
+ np.isnan(s.idxmax(skipna=False))
+
+ def test_sum_uint64(self):
+ # GH 53401
+ s = Series([10000000000000000000], dtype="uint64")
+ result = s.sum()
+ expected = np.uint64(10000000000000000000)
+ tm.assert_almost_equal(result, expected)
+
+
+class TestDatetime64SeriesReductions:
+ # Note: the name TestDatetime64SeriesReductions indicates these tests
+ # were moved from a series-specific test file, _not_ that these tests are
+ # intended long-term to be series-specific
+
+ @pytest.mark.parametrize(
+ "nat_ser",
+ [
+ Series([NaT, NaT]),
+ Series([NaT, Timedelta("nat")]),
+ Series([Timedelta("nat"), Timedelta("nat")]),
+ ],
+ )
+ def test_minmax_nat_series(self, nat_ser):
+ # GH#23282
+ assert nat_ser.min() is NaT
+ assert nat_ser.max() is NaT
+ assert nat_ser.min(skipna=False) is NaT
+ assert nat_ser.max(skipna=False) is NaT
+
+ @pytest.mark.parametrize(
+ "nat_df",
+ [
+ DataFrame([NaT, NaT]),
+ DataFrame([NaT, Timedelta("nat")]),
+ DataFrame([Timedelta("nat"), Timedelta("nat")]),
+ ],
+ )
+ def test_minmax_nat_dataframe(self, nat_df):
+ # GH#23282
+ assert nat_df.min()[0] is NaT
+ assert nat_df.max()[0] is NaT
+ assert nat_df.min(skipna=False)[0] is NaT
+ assert nat_df.max(skipna=False)[0] is NaT
+
+ def test_min_max(self):
+ rng = date_range("1/1/2000", "12/31/2000")
+ rng2 = rng.take(np.random.default_rng(2).permutation(len(rng)))
+
+ the_min = rng2.min()
+ the_max = rng2.max()
+ assert isinstance(the_min, Timestamp)
+ assert isinstance(the_max, Timestamp)
+ assert the_min == rng[0]
+ assert the_max == rng[-1]
+
+ assert rng.min() == rng[0]
+ assert rng.max() == rng[-1]
+
+ def test_min_max_series(self):
+ rng = date_range("1/1/2000", periods=10, freq="4h")
+ lvls = ["A", "A", "A", "B", "B", "B", "C", "C", "C", "C"]
+ df = DataFrame(
+ {
+ "TS": rng,
+ "V": np.random.default_rng(2).standard_normal(len(rng)),
+ "L": lvls,
+ }
+ )
+
+ result = df.TS.max()
+ exp = Timestamp(df.TS.iat[-1])
+ assert isinstance(result, Timestamp)
+ assert result == exp
+
+ result = df.TS.min()
+ exp = Timestamp(df.TS.iat[0])
+ assert isinstance(result, Timestamp)
+ assert result == exp
+
+
+class TestCategoricalSeriesReductions:
+ # Note: the name TestCategoricalSeriesReductions indicates these tests
+ # were moved from a series-specific test file, _not_ that these tests are
+ # intended long-term to be series-specific
+
+ @pytest.mark.parametrize("function", ["min", "max"])
+ def test_min_max_unordered_raises(self, function):
+ # unordered cats have no min/max
+ cat = Series(Categorical(["a", "b", "c", "d"], ordered=False))
+ msg = f"Categorical is not ordered for operation {function}"
+ with pytest.raises(TypeError, match=msg):
+ getattr(cat, function)()
+
+ @pytest.mark.parametrize(
+ "values, categories",
+ [
+ (list("abc"), list("abc")),
+ (list("abc"), list("cba")),
+ (list("abc") + [np.nan], list("cba")),
+ ([1, 2, 3], [3, 2, 1]),
+ ([1, 2, 3, np.nan], [3, 2, 1]),
+ ],
+ )
+ @pytest.mark.parametrize("function", ["min", "max"])
+ def test_min_max_ordered(self, values, categories, function):
+ # GH 25303
+ cat = Series(Categorical(values, categories=categories, ordered=True))
+ result = getattr(cat, function)(skipna=True)
+ expected = categories[0] if function == "min" else categories[2]
+ assert result == expected
+
+ @pytest.mark.parametrize("function", ["min", "max"])
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_min_max_ordered_with_nan_only(self, function, skipna):
+ # https://github.com/pandas-dev/pandas/issues/33450
+ cat = Series(Categorical([np.nan], categories=[1, 2], ordered=True))
+ result = getattr(cat, function)(skipna=skipna)
+ assert result is np.nan
+
+ @pytest.mark.parametrize("function", ["min", "max"])
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_min_max_skipna(self, function, skipna):
+ cat = Series(
+ Categorical(["a", "b", np.nan, "a"], categories=["b", "a"], ordered=True)
+ )
+ result = getattr(cat, function)(skipna=skipna)
+
+ if skipna is True:
+ expected = "b" if function == "min" else "a"
+ assert result == expected
+ else:
+ assert result is np.nan
+
+
+class TestSeriesMode:
+ # Note: the name TestSeriesMode indicates these tests
+ # were moved from a series-specific test file, _not_ that these tests are
+ # intended long-term to be series-specific
+
+ @pytest.mark.parametrize(
+ "dropna, expected",
+ [(True, Series([], dtype=np.float64)), (False, Series([], dtype=np.float64))],
+ )
+ def test_mode_empty(self, dropna, expected):
+ s = Series([], dtype=np.float64)
+ result = s.mode(dropna)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "dropna, data, expected",
+ [
+ (True, [1, 1, 1, 2], [1]),
+ (True, [1, 1, 1, 2, 3, 3, 3], [1, 3]),
+ (False, [1, 1, 1, 2], [1]),
+ (False, [1, 1, 1, 2, 3, 3, 3], [1, 3]),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "dt", list(np.typecodes["AllInteger"] + np.typecodes["Float"])
+ )
+ def test_mode_numerical(self, dropna, data, expected, dt):
+ s = Series(data, dtype=dt)
+ result = s.mode(dropna)
+ expected = Series(expected, dtype=dt)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("dropna, expected", [(True, [1.0]), (False, [1, np.nan])])
+ def test_mode_numerical_nan(self, dropna, expected):
+ s = Series([1, 1, 2, np.nan, np.nan])
+ result = s.mode(dropna)
+ expected = Series(expected)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "dropna, expected1, expected2, expected3",
+ [(True, ["b"], ["bar"], ["nan"]), (False, ["b"], [np.nan], ["nan"])],
+ )
+ def test_mode_str_obj(self, dropna, expected1, expected2, expected3):
+ # Test string and object types.
+ data = ["a"] * 2 + ["b"] * 3
+
+ s = Series(data, dtype="c")
+ result = s.mode(dropna)
+ expected1 = Series(expected1, dtype="c")
+ tm.assert_series_equal(result, expected1)
+
+ data = ["foo", "bar", "bar", np.nan, np.nan, np.nan]
+
+ s = Series(data, dtype=object)
+ result = s.mode(dropna)
+ expected2 = Series(expected2, dtype=object)
+ tm.assert_series_equal(result, expected2)
+
+ data = ["foo", "bar", "bar", np.nan, np.nan, np.nan]
+
+ s = Series(data, dtype=object).astype(str)
+ result = s.mode(dropna)
+ expected3 = Series(expected3, dtype=str)
+ tm.assert_series_equal(result, expected3)
+
+ @pytest.mark.parametrize(
+ "dropna, expected1, expected2",
+ [(True, ["foo"], ["foo"]), (False, ["foo"], [np.nan])],
+ )
+ def test_mode_mixeddtype(self, dropna, expected1, expected2):
+ s = Series([1, "foo", "foo"])
+ result = s.mode(dropna)
+ expected = Series(expected1)
+ tm.assert_series_equal(result, expected)
+
+ s = Series([1, "foo", "foo", np.nan, np.nan, np.nan])
+ result = s.mode(dropna)
+ expected = Series(expected2, dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "dropna, expected1, expected2",
+ [
+ (
+ True,
+ ["1900-05-03", "2011-01-03", "2013-01-02"],
+ ["2011-01-03", "2013-01-02"],
+ ),
+ (False, [np.nan], [np.nan, "2011-01-03", "2013-01-02"]),
+ ],
+ )
+ def test_mode_datetime(self, dropna, expected1, expected2):
+ s = Series(
+ ["2011-01-03", "2013-01-02", "1900-05-03", "nan", "nan"], dtype="M8[ns]"
+ )
+ result = s.mode(dropna)
+ expected1 = Series(expected1, dtype="M8[ns]")
+ tm.assert_series_equal(result, expected1)
+
+ s = Series(
+ [
+ "2011-01-03",
+ "2013-01-02",
+ "1900-05-03",
+ "2011-01-03",
+ "2013-01-02",
+ "nan",
+ "nan",
+ ],
+ dtype="M8[ns]",
+ )
+ result = s.mode(dropna)
+ expected2 = Series(expected2, dtype="M8[ns]")
+ tm.assert_series_equal(result, expected2)
+
+ @pytest.mark.parametrize(
+ "dropna, expected1, expected2",
+ [
+ (True, ["-1 days", "0 days", "1 days"], ["2 min", "1 day"]),
+ (False, [np.nan], [np.nan, "2 min", "1 day"]),
+ ],
+ )
+ def test_mode_timedelta(self, dropna, expected1, expected2):
+ # gh-5986: Test timedelta types.
+
+ s = Series(
+ ["1 days", "-1 days", "0 days", "nan", "nan"], dtype="timedelta64[ns]"
+ )
+ result = s.mode(dropna)
+ expected1 = Series(expected1, dtype="timedelta64[ns]")
+ tm.assert_series_equal(result, expected1)
+
+ s = Series(
+ [
+ "1 day",
+ "1 day",
+ "-1 day",
+ "-1 day 2 min",
+ "2 min",
+ "2 min",
+ "nan",
+ "nan",
+ ],
+ dtype="timedelta64[ns]",
+ )
+ result = s.mode(dropna)
+ expected2 = Series(expected2, dtype="timedelta64[ns]")
+ tm.assert_series_equal(result, expected2)
+
+ @pytest.mark.parametrize(
+ "dropna, expected1, expected2, expected3",
+ [
+ (
+ True,
+ Categorical([1, 2], categories=[1, 2]),
+ Categorical(["a"], categories=[1, "a"]),
+ Categorical([3, 1], categories=[3, 2, 1], ordered=True),
+ ),
+ (
+ False,
+ Categorical([np.nan], categories=[1, 2]),
+ Categorical([np.nan, "a"], categories=[1, "a"]),
+ Categorical([np.nan, 3, 1], categories=[3, 2, 1], ordered=True),
+ ),
+ ],
+ )
+ def test_mode_category(self, dropna, expected1, expected2, expected3):
+ s = Series(Categorical([1, 2, np.nan, np.nan]))
+ result = s.mode(dropna)
+ expected1 = Series(expected1, dtype="category")
+ tm.assert_series_equal(result, expected1)
+
+ s = Series(Categorical([1, "a", "a", np.nan, np.nan]))
+ result = s.mode(dropna)
+ expected2 = Series(expected2, dtype="category")
+ tm.assert_series_equal(result, expected2)
+
+ s = Series(
+ Categorical(
+ [1, 1, 2, 3, 3, np.nan, np.nan], categories=[3, 2, 1], ordered=True
+ )
+ )
+ result = s.mode(dropna)
+ expected3 = Series(expected3, dtype="category")
+ tm.assert_series_equal(result, expected3)
+
+ @pytest.mark.parametrize(
+ "dropna, expected1, expected2",
+ [(True, [2**63], [1, 2**63]), (False, [2**63], [1, 2**63])],
+ )
+ def test_mode_intoverflow(self, dropna, expected1, expected2):
+ # Test for uint64 overflow.
+ s = Series([1, 2**63, 2**63], dtype=np.uint64)
+ result = s.mode(dropna)
+ expected1 = Series(expected1, dtype=np.uint64)
+ tm.assert_series_equal(result, expected1)
+
+ s = Series([1, 2**63], dtype=np.uint64)
+ result = s.mode(dropna)
+ expected2 = Series(expected2, dtype=np.uint64)
+ tm.assert_series_equal(result, expected2)
+
+ def test_mode_sortwarning(self):
+ # Check for the warning that is raised when the mode
+ # results cannot be sorted
+
+ expected = Series(["foo", np.nan])
+ s = Series([1, "foo", "foo", np.nan, np.nan])
+
+ with tm.assert_produces_warning(UserWarning):
+ result = s.mode(dropna=False)
+ result = result.sort_values().reset_index(drop=True)
+
+ tm.assert_series_equal(result, expected)
+
+ def test_mode_boolean_with_na(self):
+ # GH#42107
+ ser = Series([True, False, True, pd.NA], dtype="boolean")
+ result = ser.mode()
+ expected = Series({0: True}, dtype="boolean")
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "array,expected,dtype",
+ [
+ (
+ [0, 1j, 1, 1, 1 + 1j, 1 + 2j],
+ Series([1], dtype=np.complex128),
+ np.complex128,
+ ),
+ (
+ [0, 1j, 1, 1, 1 + 1j, 1 + 2j],
+ Series([1], dtype=np.complex64),
+ np.complex64,
+ ),
+ (
+ [1 + 1j, 2j, 1 + 1j],
+ Series([1 + 1j], dtype=np.complex128),
+ np.complex128,
+ ),
+ ],
+ )
+ def test_single_mode_value_complex(self, array, expected, dtype):
+ result = Series(array, dtype=dtype).mode()
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "array,expected,dtype",
+ [
+ (
+ # no modes
+ [0, 1j, 1, 1 + 1j, 1 + 2j],
+ Series([0j, 1j, 1 + 0j, 1 + 1j, 1 + 2j], dtype=np.complex128),
+ np.complex128,
+ ),
+ (
+ [1 + 1j, 2j, 1 + 1j, 2j, 3],
+ Series([2j, 1 + 1j], dtype=np.complex64),
+ np.complex64,
+ ),
+ ],
+ )
+ def test_multimode_complex(self, array, expected, dtype):
+ # GH 17927
+ # mode tries to sort multimodal series.
+ # Complex numbers are sorted by their magnitude
+ result = Series(array, dtype=dtype).mode()
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reductions/test_stat_reductions.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reductions/test_stat_reductions.py
new file mode 100644
index 0000000000000000000000000000000000000000..55d78c516b6f3b75407d78245ca0ea2a39da5e75
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reductions/test_stat_reductions.py
@@ -0,0 +1,271 @@
+"""
+Tests for statistical reductions of 2nd moment or higher: var, skew, kurt, ...
+"""
+import inspect
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ DatetimeArray,
+ PeriodArray,
+ TimedeltaArray,
+)
+
+
+class TestDatetimeLikeStatReductions:
+ @pytest.mark.parametrize("box", [Series, pd.Index, DatetimeArray])
+ def test_dt64_mean(self, tz_naive_fixture, box):
+ tz = tz_naive_fixture
+
+ dti = pd.date_range("2001-01-01", periods=11, tz=tz)
+ # shuffle so that we are not just working with monotone-increasing
+ dti = dti.take([4, 1, 3, 10, 9, 7, 8, 5, 0, 2, 6])
+ dtarr = dti._data
+
+ obj = box(dtarr)
+ assert obj.mean() == pd.Timestamp("2001-01-06", tz=tz)
+ assert obj.mean(skipna=False) == pd.Timestamp("2001-01-06", tz=tz)
+
+ # dtarr[-2] will be the first date 2001-01-1
+ dtarr[-2] = pd.NaT
+
+ obj = box(dtarr)
+ assert obj.mean() == pd.Timestamp("2001-01-06 07:12:00", tz=tz)
+ assert obj.mean(skipna=False) is pd.NaT
+
+ @pytest.mark.parametrize("box", [Series, pd.Index, PeriodArray])
+ @pytest.mark.parametrize("freq", ["S", "H", "D", "W", "B"])
+ def test_period_mean(self, box, freq):
+ # GH#24757
+ dti = pd.date_range("2001-01-01", periods=11)
+ # shuffle so that we are not just working with monotone-increasing
+ dti = dti.take([4, 1, 3, 10, 9, 7, 8, 5, 0, 2, 6])
+
+ warn = FutureWarning if freq == "B" else None
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(warn, match=msg):
+ parr = dti._data.to_period(freq)
+ obj = box(parr)
+ with pytest.raises(TypeError, match="ambiguous"):
+ obj.mean()
+ with pytest.raises(TypeError, match="ambiguous"):
+ obj.mean(skipna=True)
+
+ # parr[-2] will be the first date 2001-01-1
+ parr[-2] = pd.NaT
+
+ with pytest.raises(TypeError, match="ambiguous"):
+ obj.mean()
+ with pytest.raises(TypeError, match="ambiguous"):
+ obj.mean(skipna=True)
+
+ @pytest.mark.parametrize("box", [Series, pd.Index, TimedeltaArray])
+ def test_td64_mean(self, box):
+ tdi = pd.TimedeltaIndex([0, 3, -2, -7, 1, 2, -1, 3, 5, -2, 4], unit="D")
+
+ tdarr = tdi._data
+ obj = box(tdarr, copy=False)
+
+ result = obj.mean()
+ expected = np.array(tdarr).mean()
+ assert result == expected
+
+ tdarr[0] = pd.NaT
+ assert obj.mean(skipna=False) is pd.NaT
+
+ result2 = obj.mean(skipna=True)
+ assert result2 == tdi[1:].mean()
+
+ # exact equality fails by 1 nanosecond
+ assert result2.round("us") == (result * 11.0 / 10).round("us")
+
+
+class TestSeriesStatReductions:
+ # Note: the name TestSeriesStatReductions indicates these tests
+ # were moved from a series-specific test file, _not_ that these tests are
+ # intended long-term to be series-specific
+
+ def _check_stat_op(
+ self, name, alternate, string_series_, check_objects=False, check_allna=False
+ ):
+ with pd.option_context("use_bottleneck", False):
+ f = getattr(Series, name)
+
+ # add some NaNs
+ string_series_[5:15] = np.nan
+
+ # mean, idxmax, idxmin, min, and max are valid for dates
+ if name not in ["max", "min", "mean", "median", "std"]:
+ ds = Series(pd.date_range("1/1/2001", periods=10))
+ msg = f"does not support reduction '{name}'"
+ with pytest.raises(TypeError, match=msg):
+ f(ds)
+
+ # skipna or no
+ assert pd.notna(f(string_series_))
+ assert pd.isna(f(string_series_, skipna=False))
+
+ # check the result is correct
+ nona = string_series_.dropna()
+ tm.assert_almost_equal(f(nona), alternate(nona.values))
+ tm.assert_almost_equal(f(string_series_), alternate(nona.values))
+
+ allna = string_series_ * np.nan
+
+ if check_allna:
+ assert np.isnan(f(allna))
+
+ # dtype=object with None, it works!
+ s = Series([1, 2, 3, None, 5])
+ f(s)
+
+ # GH#2888
+ items = [0]
+ items.extend(range(2**40, 2**40 + 1000))
+ s = Series(items, dtype="int64")
+ tm.assert_almost_equal(float(f(s)), float(alternate(s.values)))
+
+ # check date range
+ if check_objects:
+ s = Series(pd.bdate_range("1/1/2000", periods=10))
+ res = f(s)
+ exp = alternate(s)
+ assert res == exp
+
+ # check on string data
+ if name not in ["sum", "min", "max"]:
+ with pytest.raises(TypeError, match=None):
+ f(Series(list("abc")))
+
+ # Invalid axis.
+ msg = "No axis named 1 for object type Series"
+ with pytest.raises(ValueError, match=msg):
+ f(string_series_, axis=1)
+
+ if "numeric_only" in inspect.getfullargspec(f).args:
+ # only the index is string; dtype is float
+ f(string_series_, numeric_only=True)
+
+ def test_sum(self):
+ string_series = tm.makeStringSeries().rename("series")
+ self._check_stat_op("sum", np.sum, string_series, check_allna=False)
+
+ def test_mean(self):
+ string_series = tm.makeStringSeries().rename("series")
+ self._check_stat_op("mean", np.mean, string_series)
+
+ def test_median(self):
+ string_series = tm.makeStringSeries().rename("series")
+ self._check_stat_op("median", np.median, string_series)
+
+ # test with integers, test failure
+ int_ts = Series(np.ones(10, dtype=int), index=range(10))
+ tm.assert_almost_equal(np.median(int_ts), int_ts.median())
+
+ def test_prod(self):
+ string_series = tm.makeStringSeries().rename("series")
+ self._check_stat_op("prod", np.prod, string_series)
+
+ def test_min(self):
+ string_series = tm.makeStringSeries().rename("series")
+ self._check_stat_op("min", np.min, string_series, check_objects=True)
+
+ def test_max(self):
+ string_series = tm.makeStringSeries().rename("series")
+ self._check_stat_op("max", np.max, string_series, check_objects=True)
+
+ def test_var_std(self):
+ string_series = tm.makeStringSeries().rename("series")
+ datetime_series = tm.makeTimeSeries().rename("ts")
+
+ alt = lambda x: np.std(x, ddof=1)
+ self._check_stat_op("std", alt, string_series)
+
+ alt = lambda x: np.var(x, ddof=1)
+ self._check_stat_op("var", alt, string_series)
+
+ result = datetime_series.std(ddof=4)
+ expected = np.std(datetime_series.values, ddof=4)
+ tm.assert_almost_equal(result, expected)
+
+ result = datetime_series.var(ddof=4)
+ expected = np.var(datetime_series.values, ddof=4)
+ tm.assert_almost_equal(result, expected)
+
+ # 1 - element series with ddof=1
+ s = datetime_series.iloc[[0]]
+ result = s.var(ddof=1)
+ assert pd.isna(result)
+
+ result = s.std(ddof=1)
+ assert pd.isna(result)
+
+ def test_sem(self):
+ string_series = tm.makeStringSeries().rename("series")
+ datetime_series = tm.makeTimeSeries().rename("ts")
+
+ alt = lambda x: np.std(x, ddof=1) / np.sqrt(len(x))
+ self._check_stat_op("sem", alt, string_series)
+
+ result = datetime_series.sem(ddof=4)
+ expected = np.std(datetime_series.values, ddof=4) / np.sqrt(
+ len(datetime_series.values)
+ )
+ tm.assert_almost_equal(result, expected)
+
+ # 1 - element series with ddof=1
+ s = datetime_series.iloc[[0]]
+ result = s.sem(ddof=1)
+ assert pd.isna(result)
+
+ def test_skew(self):
+ sp_stats = pytest.importorskip("scipy.stats")
+
+ string_series = tm.makeStringSeries().rename("series")
+
+ alt = lambda x: sp_stats.skew(x, bias=False)
+ self._check_stat_op("skew", alt, string_series)
+
+ # test corner cases, skew() returns NaN unless there's at least 3
+ # values
+ min_N = 3
+ for i in range(1, min_N + 1):
+ s = Series(np.ones(i))
+ df = DataFrame(np.ones((i, i)))
+ if i < min_N:
+ assert np.isnan(s.skew())
+ assert np.isnan(df.skew()).all()
+ else:
+ assert 0 == s.skew()
+ assert isinstance(s.skew(), np.float64) # GH53482
+ assert (df.skew() == 0).all()
+
+ def test_kurt(self):
+ sp_stats = pytest.importorskip("scipy.stats")
+
+ string_series = tm.makeStringSeries().rename("series")
+
+ alt = lambda x: sp_stats.kurtosis(x, bias=False)
+ self._check_stat_op("kurt", alt, string_series)
+
+ def test_kurt_corner(self):
+ # test corner cases, kurt() returns NaN unless there's at least 4
+ # values
+ min_N = 4
+ for i in range(1, min_N + 1):
+ s = Series(np.ones(i))
+ df = DataFrame(np.ones((i, i)))
+ if i < min_N:
+ assert np.isnan(s.kurt())
+ assert np.isnan(df.kurt()).all()
+ else:
+ assert 0 == s.kurt()
+ assert isinstance(s.kurt(), np.float64) # GH53482
+ assert (df.kurt() == 0).all()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..90c2a91a22158dbf75910f97e58dcff2b8e6d878
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/conftest.py
@@ -0,0 +1,180 @@
+from datetime import datetime
+import warnings
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Series,
+)
+from pandas.core.indexes.datetimes import date_range
+from pandas.core.indexes.period import period_range
+
+# The various methods we support
+downsample_methods = [
+ "min",
+ "max",
+ "first",
+ "last",
+ "sum",
+ "mean",
+ "sem",
+ "median",
+ "prod",
+ "var",
+ "std",
+ "ohlc",
+ "quantile",
+]
+upsample_methods = ["count", "size"]
+series_methods = ["nunique"]
+resample_methods = downsample_methods + upsample_methods + series_methods
+
+
+@pytest.fixture(params=downsample_methods)
+def downsample_method(request):
+ """Fixture for parametrization of Grouper downsample methods."""
+ return request.param
+
+
+@pytest.fixture(params=resample_methods)
+def resample_method(request):
+ """Fixture for parametrization of Grouper resample methods."""
+ return request.param
+
+
+@pytest.fixture
+def simple_date_range_series():
+ """
+ Series with date range index and random data for test purposes.
+ """
+
+ def _simple_date_range_series(start, end, freq="D"):
+ rng = date_range(start, end, freq=freq)
+ return Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ return _simple_date_range_series
+
+
+@pytest.fixture
+def simple_period_range_series():
+ """
+ Series with period range index and random data for test purposes.
+ """
+
+ def _simple_period_range_series(start, end, freq="D"):
+ with warnings.catch_warnings():
+ # suppress Period[B] deprecation warning
+ msg = "|".join(["Period with BDay freq", r"PeriodDtype\[B\] is deprecated"])
+ warnings.filterwarnings(
+ "ignore",
+ msg,
+ category=FutureWarning,
+ )
+ rng = period_range(start, end, freq=freq)
+ return Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ return _simple_period_range_series
+
+
+@pytest.fixture
+def _index_start():
+ """Fixture for parametrization of index, series and frame."""
+ return datetime(2005, 1, 1)
+
+
+@pytest.fixture
+def _index_end():
+ """Fixture for parametrization of index, series and frame."""
+ return datetime(2005, 1, 10)
+
+
+@pytest.fixture
+def _index_freq():
+ """Fixture for parametrization of index, series and frame."""
+ return "D"
+
+
+@pytest.fixture
+def _index_name():
+ """Fixture for parametrization of index, series and frame."""
+ return None
+
+
+@pytest.fixture
+def index(_index_factory, _index_start, _index_end, _index_freq, _index_name):
+ """
+ Fixture for parametrization of date_range, period_range and
+ timedelta_range indexes
+ """
+ return _index_factory(_index_start, _index_end, freq=_index_freq, name=_index_name)
+
+
+@pytest.fixture
+def _static_values(index):
+ """
+ Fixture for parametrization of values used in parametrization of
+ Series and DataFrames with date_range, period_range and
+ timedelta_range indexes
+ """
+ return np.arange(len(index))
+
+
+@pytest.fixture
+def _series_name():
+ """
+ Fixture for parametrization of Series name for Series used with
+ date_range, period_range and timedelta_range indexes
+ """
+ return None
+
+
+@pytest.fixture
+def series(index, _series_name, _static_values):
+ """
+ Fixture for parametrization of Series with date_range, period_range and
+ timedelta_range indexes
+ """
+ return Series(_static_values, index=index, name=_series_name)
+
+
+@pytest.fixture
+def empty_series_dti(series):
+ """
+ Fixture for parametrization of empty Series with date_range,
+ period_range and timedelta_range indexes
+ """
+ return series[:0]
+
+
+@pytest.fixture
+def frame(index, _series_name, _static_values):
+ """
+ Fixture for parametrization of DataFrame with date_range, period_range
+ and timedelta_range indexes
+ """
+ # _series_name is intentionally unused
+ return DataFrame({"value": _static_values}, index=index)
+
+
+@pytest.fixture
+def empty_frame_dti(series):
+ """
+ Fixture for parametrization of empty DataFrame with date_range,
+ period_range and timedelta_range indexes
+ """
+ index = series.index[:0]
+ return DataFrame(index=index)
+
+
+@pytest.fixture
+def series_and_frame(frame_or_series, series, frame):
+ """
+ Fixture for parametrization of Series and DataFrame with date_range,
+ period_range and timedelta_range indexes
+ """
+ if frame_or_series == Series:
+ return series
+ if frame_or_series == DataFrame:
+ return frame
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_base.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a76a21a6c579d528df3e784eace87715d41ec74
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_base.py
@@ -0,0 +1,341 @@
+from datetime import datetime
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ NaT,
+ PeriodIndex,
+ Series,
+ TimedeltaIndex,
+)
+import pandas._testing as tm
+from pandas.core.groupby.groupby import DataError
+from pandas.core.groupby.grouper import Grouper
+from pandas.core.indexes.datetimes import date_range
+from pandas.core.indexes.period import period_range
+from pandas.core.indexes.timedeltas import timedelta_range
+from pandas.core.resample import _asfreq_compat
+
+# a fixture value can be overridden by the test parameter value. Note that the
+# value of the fixture can be overridden this way even if the test doesn't use
+# it directly (doesn't mention it in the function prototype).
+# see https://docs.pytest.org/en/latest/fixture.html#override-a-fixture-with-direct-test-parametrization # noqa: E501
+# in this module we override the fixture values defined in conftest.py
+# tuples of '_index_factory,_series_name,_index_start,_index_end'
+DATE_RANGE = (date_range, "dti", datetime(2005, 1, 1), datetime(2005, 1, 10))
+PERIOD_RANGE = (period_range, "pi", datetime(2005, 1, 1), datetime(2005, 1, 10))
+TIMEDELTA_RANGE = (timedelta_range, "tdi", "1 day", "10 day")
+
+all_ts = pytest.mark.parametrize(
+ "_index_factory,_series_name,_index_start,_index_end",
+ [DATE_RANGE, PERIOD_RANGE, TIMEDELTA_RANGE],
+)
+
+
+@pytest.fixture
+def create_index(_index_factory):
+ def _create_index(*args, **kwargs):
+ """return the _index_factory created using the args, kwargs"""
+ return _index_factory(*args, **kwargs)
+
+ return _create_index
+
+
+@pytest.mark.parametrize("freq", ["2D", "1H"])
+@pytest.mark.parametrize(
+ "_index_factory,_series_name,_index_start,_index_end", [DATE_RANGE, TIMEDELTA_RANGE]
+)
+def test_asfreq(series_and_frame, freq, create_index):
+ obj = series_and_frame
+
+ result = obj.resample(freq).asfreq()
+ new_index = create_index(obj.index[0], obj.index[-1], freq=freq)
+ expected = obj.reindex(new_index)
+ tm.assert_almost_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "_index_factory,_series_name,_index_start,_index_end", [DATE_RANGE, TIMEDELTA_RANGE]
+)
+def test_asfreq_fill_value(series, create_index):
+ # test for fill value during resampling, issue 3715
+
+ ser = series
+
+ result = ser.resample("1H").asfreq()
+ new_index = create_index(ser.index[0], ser.index[-1], freq="1H")
+ expected = ser.reindex(new_index)
+ tm.assert_series_equal(result, expected)
+
+ # Explicit cast to float to avoid implicit cast when setting None
+ frame = ser.astype("float").to_frame("value")
+ frame.iloc[1] = None
+ result = frame.resample("1H").asfreq(fill_value=4.0)
+ new_index = create_index(frame.index[0], frame.index[-1], freq="1H")
+ expected = frame.reindex(new_index, fill_value=4.0)
+ tm.assert_frame_equal(result, expected)
+
+
+@all_ts
+def test_resample_interpolate(frame):
+ # GH#12925
+ df = frame
+ result = df.resample("1T").asfreq().interpolate()
+ expected = df.resample("1T").interpolate()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_raises_on_non_datetimelike_index():
+ # this is a non datetimelike index
+ xp = DataFrame()
+ msg = (
+ "Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, "
+ "but got an instance of 'RangeIndex'"
+ )
+ with pytest.raises(TypeError, match=msg):
+ xp.resample("A")
+
+
+@all_ts
+@pytest.mark.parametrize("freq", ["M", "D", "H"])
+def test_resample_empty_series(freq, empty_series_dti, resample_method):
+ # GH12771 & GH12868
+
+ ser = empty_series_dti
+ if freq == "M" and isinstance(ser.index, TimedeltaIndex):
+ msg = (
+ "Resampling on a TimedeltaIndex requires fixed-duration `freq`, "
+ "e.g. '24H' or '3D', not "
+ )
+ with pytest.raises(ValueError, match=msg):
+ ser.resample(freq)
+ return
+
+ rs = ser.resample(freq)
+ result = getattr(rs, resample_method)()
+
+ if resample_method == "ohlc":
+ expected = DataFrame(
+ [], index=ser.index[:0].copy(), columns=["open", "high", "low", "close"]
+ )
+ expected.index = _asfreq_compat(ser.index, freq)
+ tm.assert_frame_equal(result, expected, check_dtype=False)
+ else:
+ expected = ser.copy()
+ expected.index = _asfreq_compat(ser.index, freq)
+ tm.assert_series_equal(result, expected, check_dtype=False)
+
+ tm.assert_index_equal(result.index, expected.index)
+ assert result.index.freq == expected.index.freq
+
+
+@all_ts
+@pytest.mark.parametrize(
+ "freq",
+ [
+ pytest.param("M", marks=pytest.mark.xfail(reason="Don't know why this fails")),
+ "D",
+ "H",
+ ],
+)
+def test_resample_nat_index_series(freq, series, resample_method):
+ # GH39227
+
+ ser = series.copy()
+ ser.index = PeriodIndex([NaT] * len(ser), freq=freq)
+ rs = ser.resample(freq)
+ result = getattr(rs, resample_method)()
+
+ if resample_method == "ohlc":
+ expected = DataFrame(
+ [], index=ser.index[:0].copy(), columns=["open", "high", "low", "close"]
+ )
+ tm.assert_frame_equal(result, expected, check_dtype=False)
+ else:
+ expected = ser[:0].copy()
+ tm.assert_series_equal(result, expected, check_dtype=False)
+ tm.assert_index_equal(result.index, expected.index)
+ assert result.index.freq == expected.index.freq
+
+
+@all_ts
+@pytest.mark.parametrize("freq", ["M", "D", "H"])
+@pytest.mark.parametrize("resample_method", ["count", "size"])
+def test_resample_count_empty_series(freq, empty_series_dti, resample_method):
+ # GH28427
+ ser = empty_series_dti
+ if freq == "M" and isinstance(ser.index, TimedeltaIndex):
+ msg = (
+ "Resampling on a TimedeltaIndex requires fixed-duration `freq`, "
+ "e.g. '24H' or '3D', not "
+ )
+ with pytest.raises(ValueError, match=msg):
+ ser.resample(freq)
+ return
+
+ rs = ser.resample(freq)
+
+ result = getattr(rs, resample_method)()
+
+ index = _asfreq_compat(ser.index, freq)
+
+ expected = Series([], dtype="int64", index=index, name=ser.name)
+
+ tm.assert_series_equal(result, expected)
+
+
+@all_ts
+@pytest.mark.parametrize("freq", ["M", "D", "H"])
+def test_resample_empty_dataframe(empty_frame_dti, freq, resample_method):
+ # GH13212
+ df = empty_frame_dti
+ # count retains dimensions too
+ if freq == "M" and isinstance(df.index, TimedeltaIndex):
+ msg = (
+ "Resampling on a TimedeltaIndex requires fixed-duration `freq`, "
+ "e.g. '24H' or '3D', not "
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.resample(freq, group_keys=False)
+ return
+
+ rs = df.resample(freq, group_keys=False)
+ result = getattr(rs, resample_method)()
+ if resample_method == "ohlc":
+ # TODO: no tests with len(df.columns) > 0
+ mi = MultiIndex.from_product([df.columns, ["open", "high", "low", "close"]])
+ expected = DataFrame(
+ [], index=df.index[:0].copy(), columns=mi, dtype=np.float64
+ )
+ expected.index = _asfreq_compat(df.index, freq)
+
+ elif resample_method != "size":
+ expected = df.copy()
+ else:
+ # GH14962
+ expected = Series([], dtype=np.int64)
+
+ expected.index = _asfreq_compat(df.index, freq)
+
+ tm.assert_index_equal(result.index, expected.index)
+ assert result.index.freq == expected.index.freq
+ tm.assert_almost_equal(result, expected)
+
+ # test size for GH13212 (currently stays as df)
+
+
+@all_ts
+@pytest.mark.parametrize("freq", ["M", "D", "H"])
+def test_resample_count_empty_dataframe(freq, empty_frame_dti):
+ # GH28427
+
+ empty_frame_dti["a"] = []
+
+ if freq == "M" and isinstance(empty_frame_dti.index, TimedeltaIndex):
+ msg = (
+ "Resampling on a TimedeltaIndex requires fixed-duration `freq`, "
+ "e.g. '24H' or '3D', not "
+ )
+ with pytest.raises(ValueError, match=msg):
+ empty_frame_dti.resample(freq)
+ return
+
+ result = empty_frame_dti.resample(freq).count()
+
+ index = _asfreq_compat(empty_frame_dti.index, freq)
+
+ expected = DataFrame({"a": []}, dtype="int64", index=index)
+
+ tm.assert_frame_equal(result, expected)
+
+
+@all_ts
+@pytest.mark.parametrize("freq", ["M", "D", "H"])
+def test_resample_size_empty_dataframe(freq, empty_frame_dti):
+ # GH28427
+
+ empty_frame_dti["a"] = []
+
+ if freq == "M" and isinstance(empty_frame_dti.index, TimedeltaIndex):
+ msg = (
+ "Resampling on a TimedeltaIndex requires fixed-duration `freq`, "
+ "e.g. '24H' or '3D', not "
+ )
+ with pytest.raises(ValueError, match=msg):
+ empty_frame_dti.resample(freq)
+ return
+
+ result = empty_frame_dti.resample(freq).size()
+
+ index = _asfreq_compat(empty_frame_dti.index, freq)
+
+ expected = Series([], dtype="int64", index=index)
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+@pytest.mark.parametrize("index", tm.all_timeseries_index_generator(0))
+@pytest.mark.parametrize("dtype", [float, int, object, "datetime64[ns]"])
+def test_resample_empty_dtypes(index, dtype, resample_method):
+ # Empty series were sometimes causing a segfault (for the functions
+ # with Cython bounds-checking disabled) or an IndexError. We just run
+ # them to ensure they no longer do. (GH #10228)
+ if isinstance(index, PeriodIndex):
+ # GH#53511
+ index = PeriodIndex([], freq="B", name=index.name)
+ empty_series_dti = Series([], index, dtype)
+ rs = empty_series_dti.resample("d", group_keys=False)
+ try:
+ getattr(rs, resample_method)()
+ except DataError:
+ # Ignore these since some combinations are invalid
+ # (ex: doing mean with dtype of np.object_)
+ pass
+
+
+@all_ts
+@pytest.mark.parametrize("freq", ["M", "D", "H"])
+def test_apply_to_empty_series(empty_series_dti, freq):
+ # GH 14313
+ ser = empty_series_dti
+
+ if freq == "M" and isinstance(empty_series_dti.index, TimedeltaIndex):
+ msg = (
+ "Resampling on a TimedeltaIndex requires fixed-duration `freq`, "
+ "e.g. '24H' or '3D', not "
+ )
+ with pytest.raises(ValueError, match=msg):
+ empty_series_dti.resample(freq)
+ return
+
+ result = ser.resample(freq, group_keys=False).apply(lambda x: 1)
+ expected = ser.resample(freq).apply("sum")
+
+ tm.assert_series_equal(result, expected, check_dtype=False)
+
+
+@all_ts
+def test_resampler_is_iterable(series):
+ # GH 15314
+ freq = "H"
+ tg = Grouper(freq=freq, convention="start")
+ grouped = series.groupby(tg)
+ resampled = series.resample(freq)
+ for (rk, rv), (gk, gv) in zip(resampled, grouped):
+ assert rk == gk
+ tm.assert_series_equal(rv, gv)
+
+
+@all_ts
+def test_resample_quantile(series):
+ # GH 15023
+ ser = series
+ q = 0.75
+ freq = "H"
+ result = ser.resample(freq).quantile(q)
+ expected = ser.resample(freq).agg(lambda x: x.quantile(q)).rename(ser.name)
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_datetime_index.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_datetime_index.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b20b383c4eae07f233d12e055599131ac6c33b5
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_datetime_index.py
@@ -0,0 +1,1996 @@
+from datetime import datetime
+from functools import partial
+from io import StringIO
+
+import numpy as np
+import pytest
+import pytz
+
+from pandas._libs import lib
+from pandas._typing import DatetimeNaTType
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ Timedelta,
+ Timestamp,
+ isna,
+ notna,
+)
+import pandas._testing as tm
+from pandas.core.groupby.grouper import Grouper
+from pandas.core.indexes.datetimes import date_range
+from pandas.core.indexes.period import (
+ Period,
+ period_range,
+)
+from pandas.core.resample import (
+ DatetimeIndex,
+ _get_timestamp_range_edges,
+)
+
+from pandas.tseries import offsets
+from pandas.tseries.offsets import Minute
+
+
+@pytest.fixture()
+def _index_factory():
+ return date_range
+
+
+@pytest.fixture
+def _index_freq():
+ return "Min"
+
+
+@pytest.fixture
+def _static_values(index):
+ return np.random.default_rng(2).random(len(index))
+
+
+@pytest.fixture(params=["s", "ms", "us", "ns"])
+def unit(request):
+ return request.param
+
+
+def test_custom_grouper(index, unit):
+ dti = index.as_unit(unit)
+ s = Series(np.array([1] * len(dti)), index=dti, dtype="int64")
+
+ b = Grouper(freq=Minute(5))
+ g = s.groupby(b)
+
+ # check all cython functions work
+ g.ohlc() # doesn't use _cython_agg_general
+ funcs = ["sum", "mean", "prod", "min", "max", "var"]
+ for f in funcs:
+ g._cython_agg_general(f, alt=None, numeric_only=True)
+
+ b = Grouper(freq=Minute(5), closed="right", label="right")
+ g = s.groupby(b)
+ # check all cython functions work
+ g.ohlc() # doesn't use _cython_agg_general
+ funcs = ["sum", "mean", "prod", "min", "max", "var"]
+ for f in funcs:
+ g._cython_agg_general(f, alt=None, numeric_only=True)
+
+ assert g.ngroups == 2593
+ assert notna(g.mean()).all()
+
+ # construct expected val
+ arr = [1] + [5] * 2592
+ idx = dti[0:-1:5]
+ idx = idx.append(dti[-1:])
+ idx = DatetimeIndex(idx, freq="5T").as_unit(unit)
+ expect = Series(arr, index=idx)
+
+ # GH2763 - return input dtype if we can
+ result = g.agg("sum")
+ tm.assert_series_equal(result, expect)
+
+
+def test_custom_grouper_df(index, unit):
+ b = Grouper(freq=Minute(5), closed="right", label="right")
+ dti = index.as_unit(unit)
+ df = DataFrame(
+ np.random.default_rng(2).random((len(dti), 10)), index=dti, dtype="float64"
+ )
+ r = df.groupby(b).agg("sum")
+
+ assert len(r.columns) == 10
+ assert len(r.index) == 2593
+
+
+@pytest.mark.parametrize(
+ "_index_start,_index_end,_index_name",
+ [("1/1/2000 00:00:00", "1/1/2000 00:13:00", "index")],
+)
+@pytest.mark.parametrize(
+ "closed, expected",
+ [
+ (
+ "right",
+ lambda s: Series(
+ [s.iloc[0], s[1:6].mean(), s[6:11].mean(), s[11:].mean()],
+ index=date_range("1/1/2000", periods=4, freq="5min", name="index"),
+ ),
+ ),
+ (
+ "left",
+ lambda s: Series(
+ [s[:5].mean(), s[5:10].mean(), s[10:].mean()],
+ index=date_range(
+ "1/1/2000 00:05", periods=3, freq="5min", name="index"
+ ),
+ ),
+ ),
+ ],
+)
+def test_resample_basic(series, closed, expected, unit):
+ s = series
+ s.index = s.index.as_unit(unit)
+ expected = expected(s)
+ expected.index = expected.index.as_unit(unit)
+ result = s.resample("5min", closed=closed, label="right").mean()
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_integerarray(unit):
+ # GH 25580, resample on IntegerArray
+ ts = Series(
+ range(9),
+ index=date_range("1/1/2000", periods=9, freq="T").as_unit(unit),
+ dtype="Int64",
+ )
+ result = ts.resample("3T").sum()
+ expected = Series(
+ [3, 12, 21],
+ index=date_range("1/1/2000", periods=3, freq="3T").as_unit(unit),
+ dtype="Int64",
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = ts.resample("3T").mean()
+ expected = Series(
+ [1, 4, 7],
+ index=date_range("1/1/2000", periods=3, freq="3T").as_unit(unit),
+ dtype="Float64",
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_basic_grouper(series, unit):
+ s = series
+ s.index = s.index.as_unit(unit)
+ result = s.resample("5Min").last()
+ grouper = Grouper(freq=Minute(5), closed="left", label="left")
+ expected = s.groupby(grouper).agg(lambda x: x.iloc[-1])
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "_index_start,_index_end,_index_name",
+ [("1/1/2000 00:00:00", "1/1/2000 00:13:00", "index")],
+)
+@pytest.mark.parametrize(
+ "keyword,value",
+ [("label", "righttt"), ("closed", "righttt"), ("convention", "starttt")],
+)
+def test_resample_string_kwargs(series, keyword, value, unit):
+ # see gh-19303
+ # Check that wrong keyword argument strings raise an error
+ series.index = series.index.as_unit(unit)
+ msg = f"Unsupported value {value} for `{keyword}`"
+ with pytest.raises(ValueError, match=msg):
+ series.resample("5min", **({keyword: value}))
+
+
+@pytest.mark.parametrize(
+ "_index_start,_index_end,_index_name",
+ [("1/1/2000 00:00:00", "1/1/2000 00:13:00", "index")],
+)
+def test_resample_how(series, downsample_method, unit):
+ if downsample_method == "ohlc":
+ pytest.skip("covered by test_resample_how_ohlc")
+
+ s = series
+ s.index = s.index.as_unit(unit)
+ grouplist = np.ones_like(s)
+ grouplist[0] = 0
+ grouplist[1:6] = 1
+ grouplist[6:11] = 2
+ grouplist[11:] = 3
+ expected = s.groupby(grouplist).agg(downsample_method)
+ expected.index = date_range(
+ "1/1/2000", periods=4, freq="5min", name="index"
+ ).as_unit(unit)
+
+ result = getattr(
+ s.resample("5min", closed="right", label="right"), downsample_method
+ )()
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "_index_start,_index_end,_index_name",
+ [("1/1/2000 00:00:00", "1/1/2000 00:13:00", "index")],
+)
+def test_resample_how_ohlc(series, unit):
+ s = series
+ s.index = s.index.as_unit(unit)
+ grouplist = np.ones_like(s)
+ grouplist[0] = 0
+ grouplist[1:6] = 1
+ grouplist[6:11] = 2
+ grouplist[11:] = 3
+
+ def _ohlc(group):
+ if isna(group).all():
+ return np.repeat(np.nan, 4)
+ return [group.iloc[0], group.max(), group.min(), group.iloc[-1]]
+
+ expected = DataFrame(
+ s.groupby(grouplist).agg(_ohlc).values.tolist(),
+ index=date_range("1/1/2000", periods=4, freq="5min", name="index").as_unit(
+ unit
+ ),
+ columns=["open", "high", "low", "close"],
+ )
+
+ result = s.resample("5min", closed="right", label="right").ohlc()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_how_callables(unit):
+ # GH#7929
+ data = np.arange(5, dtype=np.int64)
+ ind = date_range(start="2014-01-01", periods=len(data), freq="d").as_unit(unit)
+ df = DataFrame({"A": data, "B": data}, index=ind)
+
+ def fn(x, a=1):
+ return str(type(x))
+
+ class FnClass:
+ def __call__(self, x):
+ return str(type(x))
+
+ df_standard = df.resample("M").apply(fn)
+ df_lambda = df.resample("M").apply(lambda x: str(type(x)))
+ df_partial = df.resample("M").apply(partial(fn))
+ df_partial2 = df.resample("M").apply(partial(fn, a=2))
+ df_class = df.resample("M").apply(FnClass())
+
+ tm.assert_frame_equal(df_standard, df_lambda)
+ tm.assert_frame_equal(df_standard, df_partial)
+ tm.assert_frame_equal(df_standard, df_partial2)
+ tm.assert_frame_equal(df_standard, df_class)
+
+
+def test_resample_rounding(unit):
+ # GH 8371
+ # odd results when rounding is needed
+
+ data = """date,time,value
+11-08-2014,00:00:01.093,1
+11-08-2014,00:00:02.159,1
+11-08-2014,00:00:02.667,1
+11-08-2014,00:00:03.175,1
+11-08-2014,00:00:07.058,1
+11-08-2014,00:00:07.362,1
+11-08-2014,00:00:08.324,1
+11-08-2014,00:00:08.830,1
+11-08-2014,00:00:08.982,1
+11-08-2014,00:00:09.815,1
+11-08-2014,00:00:10.540,1
+11-08-2014,00:00:11.061,1
+11-08-2014,00:00:11.617,1
+11-08-2014,00:00:13.607,1
+11-08-2014,00:00:14.535,1
+11-08-2014,00:00:15.525,1
+11-08-2014,00:00:17.960,1
+11-08-2014,00:00:20.674,1
+11-08-2014,00:00:21.191,1"""
+
+ df = pd.read_csv(
+ StringIO(data),
+ parse_dates={"timestamp": ["date", "time"]},
+ index_col="timestamp",
+ )
+ df.index = df.index.as_unit(unit)
+ df.index.name = None
+ result = df.resample("6s").sum()
+ expected = DataFrame(
+ {"value": [4, 9, 4, 2]},
+ index=date_range("2014-11-08", freq="6s", periods=4).as_unit(unit),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.resample("7s").sum()
+ expected = DataFrame(
+ {"value": [4, 10, 4, 1]},
+ index=date_range("2014-11-08", freq="7s", periods=4).as_unit(unit),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.resample("11s").sum()
+ expected = DataFrame(
+ {"value": [11, 8]},
+ index=date_range("2014-11-08", freq="11s", periods=2).as_unit(unit),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.resample("13s").sum()
+ expected = DataFrame(
+ {"value": [13, 6]},
+ index=date_range("2014-11-08", freq="13s", periods=2).as_unit(unit),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.resample("17s").sum()
+ expected = DataFrame(
+ {"value": [16, 3]},
+ index=date_range("2014-11-08", freq="17s", periods=2).as_unit(unit),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_basic_from_daily(unit):
+ # from daily
+ dti = date_range(
+ start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq="D", name="index"
+ ).as_unit(unit)
+
+ s = Series(np.random.default_rng(2).random(len(dti)), dti)
+
+ # to weekly
+ result = s.resample("w-sun").last()
+
+ assert len(result) == 3
+ assert (result.index.dayofweek == [6, 6, 6]).all()
+ assert result.iloc[0] == s["1/2/2005"]
+ assert result.iloc[1] == s["1/9/2005"]
+ assert result.iloc[2] == s.iloc[-1]
+
+ result = s.resample("W-MON").last()
+ assert len(result) == 2
+ assert (result.index.dayofweek == [0, 0]).all()
+ assert result.iloc[0] == s["1/3/2005"]
+ assert result.iloc[1] == s["1/10/2005"]
+
+ result = s.resample("W-TUE").last()
+ assert len(result) == 2
+ assert (result.index.dayofweek == [1, 1]).all()
+ assert result.iloc[0] == s["1/4/2005"]
+ assert result.iloc[1] == s["1/10/2005"]
+
+ result = s.resample("W-WED").last()
+ assert len(result) == 2
+ assert (result.index.dayofweek == [2, 2]).all()
+ assert result.iloc[0] == s["1/5/2005"]
+ assert result.iloc[1] == s["1/10/2005"]
+
+ result = s.resample("W-THU").last()
+ assert len(result) == 2
+ assert (result.index.dayofweek == [3, 3]).all()
+ assert result.iloc[0] == s["1/6/2005"]
+ assert result.iloc[1] == s["1/10/2005"]
+
+ result = s.resample("W-FRI").last()
+ assert len(result) == 2
+ assert (result.index.dayofweek == [4, 4]).all()
+ assert result.iloc[0] == s["1/7/2005"]
+ assert result.iloc[1] == s["1/10/2005"]
+
+ # to biz day
+ result = s.resample("B").last()
+ assert len(result) == 7
+ assert (result.index.dayofweek == [4, 0, 1, 2, 3, 4, 0]).all()
+
+ assert result.iloc[0] == s["1/2/2005"]
+ assert result.iloc[1] == s["1/3/2005"]
+ assert result.iloc[5] == s["1/9/2005"]
+ assert result.index.name == "index"
+
+
+def test_resample_upsampling_picked_but_not_correct(unit):
+ # Test for issue #3020
+ dates = date_range("01-Jan-2014", "05-Jan-2014", freq="D").as_unit(unit)
+ series = Series(1, index=dates)
+
+ result = series.resample("D").mean()
+ assert result.index[0] == dates[0]
+
+ # GH 5955
+ # incorrect deciding to upsample when the axis frequency matches the
+ # resample frequency
+
+ s = Series(
+ np.arange(1.0, 6), index=[datetime(1975, 1, i, 12, 0) for i in range(1, 6)]
+ )
+ s.index = s.index.as_unit(unit)
+ expected = Series(
+ np.arange(1.0, 6),
+ index=date_range("19750101", periods=5, freq="D").as_unit(unit),
+ )
+
+ result = s.resample("D").count()
+ tm.assert_series_equal(result, Series(1, index=expected.index))
+
+ result1 = s.resample("D").sum()
+ result2 = s.resample("D").mean()
+ tm.assert_series_equal(result1, expected)
+ tm.assert_series_equal(result2, expected)
+
+
+@pytest.mark.parametrize("f", ["sum", "mean", "prod", "min", "max", "var"])
+def test_resample_frame_basic_cy_funcs(f, unit):
+ df = tm.makeTimeDataFrame()
+ df.index = df.index.as_unit(unit)
+
+ b = Grouper(freq="M")
+ g = df.groupby(b)
+
+ # check all cython functions work
+ g._cython_agg_general(f, alt=None, numeric_only=True)
+
+
+@pytest.mark.parametrize("freq", ["A", "M"])
+def test_resample_frame_basic_M_A(freq, unit):
+ df = tm.makeTimeDataFrame()
+ df.index = df.index.as_unit(unit)
+ result = df.resample(freq).mean()
+ tm.assert_series_equal(result["A"], df["A"].resample(freq).mean())
+
+
+@pytest.mark.parametrize("freq", ["W-WED", "M"])
+def test_resample_frame_basic_kind(freq, unit):
+ df = tm.makeTimeDataFrame()
+ df.index = df.index.as_unit(unit)
+ df.resample(freq, kind="period").mean()
+
+
+def test_resample_upsample(unit):
+ # from daily
+ dti = date_range(
+ start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq="D", name="index"
+ ).as_unit(unit)
+
+ s = Series(np.random.default_rng(2).random(len(dti)), dti)
+
+ # to minutely, by padding
+ result = s.resample("Min").ffill()
+ assert len(result) == 12961
+ assert result.iloc[0] == s.iloc[0]
+ assert result.iloc[-1] == s.iloc[-1]
+
+ assert result.index.name == "index"
+
+
+def test_resample_how_method(unit):
+ # GH9915
+ s = Series(
+ [11, 22],
+ index=[
+ Timestamp("2015-03-31 21:48:52.672000"),
+ Timestamp("2015-03-31 21:49:52.739000"),
+ ],
+ )
+ s.index = s.index.as_unit(unit)
+ expected = Series(
+ [11, np.nan, np.nan, np.nan, np.nan, np.nan, 22],
+ index=DatetimeIndex(
+ [
+ Timestamp("2015-03-31 21:48:50"),
+ Timestamp("2015-03-31 21:49:00"),
+ Timestamp("2015-03-31 21:49:10"),
+ Timestamp("2015-03-31 21:49:20"),
+ Timestamp("2015-03-31 21:49:30"),
+ Timestamp("2015-03-31 21:49:40"),
+ Timestamp("2015-03-31 21:49:50"),
+ ],
+ freq="10s",
+ ),
+ )
+ expected.index = expected.index.as_unit(unit)
+ tm.assert_series_equal(s.resample("10S").mean(), expected)
+
+
+def test_resample_extra_index_point(unit):
+ # GH#9756
+ index = date_range(start="20150101", end="20150331", freq="BM").as_unit(unit)
+ expected = DataFrame({"A": Series([21, 41, 63], index=index)})
+
+ index = date_range(start="20150101", end="20150331", freq="B").as_unit(unit)
+ df = DataFrame({"A": Series(range(len(index)), index=index)}, dtype="int64")
+ result = df.resample("BM").last()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_upsample_with_limit(unit):
+ rng = date_range("1/1/2000", periods=3, freq="5t").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+
+ result = ts.resample("t").ffill(limit=2)
+ expected = ts.reindex(result.index, method="ffill", limit=2)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("freq", ["5D", "10H", "5Min", "10S"])
+@pytest.mark.parametrize("rule", ["Y", "3M", "15D", "30H", "15Min", "30S"])
+def test_nearest_upsample_with_limit(tz_aware_fixture, freq, rule, unit):
+ # GH 33939
+ rng = date_range("1/1/2000", periods=3, freq=freq, tz=tz_aware_fixture).as_unit(
+ unit
+ )
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+
+ result = ts.resample(rule).nearest(limit=2)
+ expected = ts.reindex(result.index, method="nearest", limit=2)
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_ohlc(series, unit):
+ s = series
+ s.index = s.index.as_unit(unit)
+
+ grouper = Grouper(freq=Minute(5))
+ expect = s.groupby(grouper).agg(lambda x: x.iloc[-1])
+ result = s.resample("5Min").ohlc()
+
+ assert len(result) == len(expect)
+ assert len(result.columns) == 4
+
+ xs = result.iloc[-2]
+ assert xs["open"] == s.iloc[-6]
+ assert xs["high"] == s[-6:-1].max()
+ assert xs["low"] == s[-6:-1].min()
+ assert xs["close"] == s.iloc[-2]
+
+ xs = result.iloc[0]
+ assert xs["open"] == s.iloc[0]
+ assert xs["high"] == s[:5].max()
+ assert xs["low"] == s[:5].min()
+ assert xs["close"] == s.iloc[4]
+
+
+def test_resample_ohlc_result(unit):
+ # GH 12332
+ index = date_range("1-1-2000", "2-15-2000", freq="h").as_unit(unit)
+ index = index.union(date_range("4-15-2000", "5-15-2000", freq="h").as_unit(unit))
+ s = Series(range(len(index)), index=index)
+
+ a = s.loc[:"4-15-2000"].resample("30T").ohlc()
+ assert isinstance(a, DataFrame)
+
+ b = s.loc[:"4-14-2000"].resample("30T").ohlc()
+ assert isinstance(b, DataFrame)
+
+
+def test_resample_ohlc_result_odd_period(unit):
+ # GH12348
+ # raising on odd period
+ rng = date_range("2013-12-30", "2014-01-07").as_unit(unit)
+ index = rng.drop(
+ [
+ Timestamp("2014-01-01"),
+ Timestamp("2013-12-31"),
+ Timestamp("2014-01-04"),
+ Timestamp("2014-01-05"),
+ ]
+ )
+ df = DataFrame(data=np.arange(len(index)), index=index)
+ result = df.resample("B").mean()
+ expected = df.reindex(index=date_range(rng[0], rng[-1], freq="B").as_unit(unit))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_ohlc_dataframe(unit):
+ df = (
+ DataFrame(
+ {
+ "PRICE": {
+ Timestamp("2011-01-06 10:59:05", tz=None): 24990,
+ Timestamp("2011-01-06 12:43:33", tz=None): 25499,
+ Timestamp("2011-01-06 12:54:09", tz=None): 25499,
+ },
+ "VOLUME": {
+ Timestamp("2011-01-06 10:59:05", tz=None): 1500000000,
+ Timestamp("2011-01-06 12:43:33", tz=None): 5000000000,
+ Timestamp("2011-01-06 12:54:09", tz=None): 100000000,
+ },
+ }
+ )
+ ).reindex(["VOLUME", "PRICE"], axis=1)
+ df.index = df.index.as_unit(unit)
+ df.columns.name = "Cols"
+ res = df.resample("H").ohlc()
+ exp = pd.concat(
+ [df["VOLUME"].resample("H").ohlc(), df["PRICE"].resample("H").ohlc()],
+ axis=1,
+ keys=df.columns,
+ )
+ assert exp.columns.names[0] == "Cols"
+ tm.assert_frame_equal(exp, res)
+
+ df.columns = [["a", "b"], ["c", "d"]]
+ res = df.resample("H").ohlc()
+ exp.columns = pd.MultiIndex.from_tuples(
+ [
+ ("a", "c", "open"),
+ ("a", "c", "high"),
+ ("a", "c", "low"),
+ ("a", "c", "close"),
+ ("b", "d", "open"),
+ ("b", "d", "high"),
+ ("b", "d", "low"),
+ ("b", "d", "close"),
+ ]
+ )
+ tm.assert_frame_equal(exp, res)
+
+ # dupe columns fail atm
+ # df.columns = ['PRICE', 'PRICE']
+
+
+def test_resample_dup_index():
+ # GH 4812
+ # dup columns with resample raising
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((4, 12)),
+ index=[2000, 2000, 2000, 2000],
+ columns=[Period(year=2000, month=i + 1, freq="M") for i in range(12)],
+ )
+ df.iloc[3, :] = np.nan
+ warning_msg = "DataFrame.resample with axis=1 is deprecated."
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
+ result = df.resample("Q", axis=1).mean()
+
+ msg = "DataFrame.groupby with axis=1 is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = df.groupby(lambda x: int((x.month - 1) / 3), axis=1).mean()
+ expected.columns = [Period(year=2000, quarter=i + 1, freq="Q") for i in range(4)]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_reresample(unit):
+ dti = date_range(
+ start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq="D"
+ ).as_unit(unit)
+ s = Series(np.random.default_rng(2).random(len(dti)), dti)
+ bs = s.resample("B", closed="right", label="right").mean()
+ result = bs.resample("8H").mean()
+ assert len(result) == 22
+ assert isinstance(result.index.freq, offsets.DateOffset)
+ assert result.index.freq == offsets.Hour(8)
+
+
+@pytest.mark.parametrize(
+ "freq, expected_kwargs",
+ [
+ ["A-DEC", {"start": "1990", "end": "2000", "freq": "a-dec"}],
+ ["A-JUN", {"start": "1990", "end": "2000", "freq": "a-jun"}],
+ ["M", {"start": "1990-01", "end": "2000-01", "freq": "M"}],
+ ],
+)
+def test_resample_timestamp_to_period(
+ simple_date_range_series, freq, expected_kwargs, unit
+):
+ ts = simple_date_range_series("1/1/1990", "1/1/2000")
+ ts.index = ts.index.as_unit(unit)
+
+ result = ts.resample(freq, kind="period").mean()
+ expected = ts.resample(freq).mean()
+ expected.index = period_range(**expected_kwargs)
+ tm.assert_series_equal(result, expected)
+
+
+def test_ohlc_5min(unit):
+ def _ohlc(group):
+ if isna(group).all():
+ return np.repeat(np.nan, 4)
+ return [group.iloc[0], group.max(), group.min(), group.iloc[-1]]
+
+ rng = date_range("1/1/2000 00:00:00", "1/1/2000 5:59:50", freq="10s").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ resampled = ts.resample("5min", closed="right", label="right").ohlc()
+
+ assert (resampled.loc["1/1/2000 00:00"] == ts.iloc[0]).all()
+
+ exp = _ohlc(ts[1:31])
+ assert (resampled.loc["1/1/2000 00:05"] == exp).all()
+
+ exp = _ohlc(ts["1/1/2000 5:55:01":])
+ assert (resampled.loc["1/1/2000 6:00:00"] == exp).all()
+
+
+def test_downsample_non_unique(unit):
+ rng = date_range("1/1/2000", "2/29/2000").as_unit(unit)
+ rng2 = rng.repeat(5).values
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng2)), index=rng2)
+
+ result = ts.resample("M").mean()
+
+ expected = ts.groupby(lambda x: x.month).mean()
+ assert len(result) == 2
+ tm.assert_almost_equal(result.iloc[0], expected[1])
+ tm.assert_almost_equal(result.iloc[1], expected[2])
+
+
+def test_asfreq_non_unique(unit):
+ # GH #1077
+ rng = date_range("1/1/2000", "2/29/2000").as_unit(unit)
+ rng2 = rng.repeat(2).values
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng2)), index=rng2)
+
+ msg = "cannot reindex on an axis with duplicate labels"
+ with pytest.raises(ValueError, match=msg):
+ ts.asfreq("B")
+
+
+def test_resample_axis1(unit):
+ rng = date_range("1/1/2000", "2/29/2000").as_unit(unit)
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((3, len(rng))),
+ columns=rng,
+ index=["a", "b", "c"],
+ )
+
+ warning_msg = "DataFrame.resample with axis=1 is deprecated."
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
+ result = df.resample("M", axis=1).mean()
+ expected = df.T.resample("M").mean().T
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("freq", ["t", "5t", "15t", "30t", "4h", "12h"])
+def test_resample_anchored_ticks(freq, unit):
+ # If a fixed delta (5 minute, 4 hour) evenly divides a day, we should
+ # "anchor" the origin at midnight so we get regular intervals rather
+ # than starting from the first timestamp which might start in the
+ # middle of a desired interval
+
+ rng = date_range("1/1/2000 04:00:00", periods=86400, freq="s").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+ ts[:2] = np.nan # so results are the same
+ result = ts[2:].resample(freq, closed="left", label="left").mean()
+ expected = ts.resample(freq, closed="left", label="left").mean()
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("end", [1, 2])
+def test_resample_single_group(end, unit):
+ mysum = lambda x: x.sum()
+
+ rng = date_range("2000-1-1", f"2000-{end}-10", freq="D").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+ tm.assert_series_equal(ts.resample("M").sum(), ts.resample("M").apply(mysum))
+
+
+def test_resample_single_group_std(unit):
+ # GH 3849
+ s = Series(
+ [30.1, 31.6],
+ index=[Timestamp("20070915 15:30:00"), Timestamp("20070915 15:40:00")],
+ )
+ s.index = s.index.as_unit(unit)
+ expected = Series(
+ [0.75], index=DatetimeIndex([Timestamp("20070915")], freq="D").as_unit(unit)
+ )
+ result = s.resample("D").apply(lambda x: np.std(x))
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_offset(unit):
+ # GH 31809
+
+ rng = date_range("1/1/2000 00:00:00", "1/1/2000 02:00", freq="s").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ resampled = ts.resample("5min", offset="2min").mean()
+ exp_rng = date_range("12/31/1999 23:57:00", "1/1/2000 01:57", freq="5min").as_unit(
+ unit
+ )
+ tm.assert_index_equal(resampled.index, exp_rng)
+
+
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"origin": "1999-12-31 23:57:00"},
+ {"origin": Timestamp("1970-01-01 00:02:00")},
+ {"origin": "epoch", "offset": "2m"},
+ # origin of '1999-31-12 12:02:00' should be equivalent for this case
+ {"origin": "1999-12-31 12:02:00"},
+ {"offset": "-3m"},
+ ],
+)
+def test_resample_origin(kwargs, unit):
+ # GH 31809
+ rng = date_range("2000-01-01 00:00:00", "2000-01-01 02:00", freq="s").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ exp_rng = date_range(
+ "1999-12-31 23:57:00", "2000-01-01 01:57", freq="5min"
+ ).as_unit(unit)
+
+ resampled = ts.resample("5min", **kwargs).mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+
+
+@pytest.mark.parametrize(
+ "origin", ["invalid_value", "epch", "startday", "startt", "2000-30-30", object()]
+)
+def test_resample_bad_origin(origin, unit):
+ rng = date_range("2000-01-01 00:00:00", "2000-01-01 02:00", freq="s").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+ msg = (
+ "'origin' should be equal to 'epoch', 'start', 'start_day', "
+ "'end', 'end_day' or should be a Timestamp convertible type. Got "
+ f"'{origin}' instead."
+ )
+ with pytest.raises(ValueError, match=msg):
+ ts.resample("5min", origin=origin)
+
+
+@pytest.mark.parametrize("offset", ["invalid_value", "12dayys", "2000-30-30", object()])
+def test_resample_bad_offset(offset, unit):
+ rng = date_range("2000-01-01 00:00:00", "2000-01-01 02:00", freq="s").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+ msg = f"'offset' should be a Timedelta convertible type. Got '{offset}' instead."
+ with pytest.raises(ValueError, match=msg):
+ ts.resample("5min", offset=offset)
+
+
+def test_resample_origin_prime_freq(unit):
+ # GH 31809
+ start, end = "2000-10-01 23:30:00", "2000-10-02 00:30:00"
+ rng = date_range(start, end, freq="7min").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ exp_rng = date_range(
+ "2000-10-01 23:14:00", "2000-10-02 00:22:00", freq="17min"
+ ).as_unit(unit)
+ resampled = ts.resample("17min").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+ resampled = ts.resample("17min", origin="start_day").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+
+ exp_rng = date_range(
+ "2000-10-01 23:30:00", "2000-10-02 00:21:00", freq="17min"
+ ).as_unit(unit)
+ resampled = ts.resample("17min", origin="start").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+ resampled = ts.resample("17min", offset="23h30min").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+ resampled = ts.resample("17min", origin="start_day", offset="23h30min").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+
+ exp_rng = date_range(
+ "2000-10-01 23:18:00", "2000-10-02 00:26:00", freq="17min"
+ ).as_unit(unit)
+ resampled = ts.resample("17min", origin="epoch").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+
+ exp_rng = date_range(
+ "2000-10-01 23:24:00", "2000-10-02 00:15:00", freq="17min"
+ ).as_unit(unit)
+ resampled = ts.resample("17min", origin="2000-01-01").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+
+
+def test_resample_origin_with_tz(unit):
+ # GH 31809
+ msg = "The origin must have the same timezone as the index."
+
+ tz = "Europe/Paris"
+ rng = date_range(
+ "2000-01-01 00:00:00", "2000-01-01 02:00", freq="s", tz=tz
+ ).as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ exp_rng = date_range(
+ "1999-12-31 23:57:00", "2000-01-01 01:57", freq="5min", tz=tz
+ ).as_unit(unit)
+ resampled = ts.resample("5min", origin="1999-12-31 23:57:00+00:00").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+
+ # origin of '1999-31-12 12:02:00+03:00' should be equivalent for this case
+ resampled = ts.resample("5min", origin="1999-12-31 12:02:00+03:00").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+
+ resampled = ts.resample("5min", origin="epoch", offset="2m").mean()
+ tm.assert_index_equal(resampled.index, exp_rng)
+
+ with pytest.raises(ValueError, match=msg):
+ ts.resample("5min", origin="12/31/1999 23:57:00").mean()
+
+ # if the series is not tz aware, origin should not be tz aware
+ rng = date_range("2000-01-01 00:00:00", "2000-01-01 02:00", freq="s").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+ with pytest.raises(ValueError, match=msg):
+ ts.resample("5min", origin="12/31/1999 23:57:00+03:00").mean()
+
+
+def test_resample_origin_epoch_with_tz_day_vs_24h(unit):
+ # GH 34474
+ start, end = "2000-10-01 23:30:00+0500", "2000-12-02 00:30:00+0500"
+ rng = date_range(start, end, freq="7min").as_unit(unit)
+ random_values = np.random.default_rng(2).standard_normal(len(rng))
+ ts_1 = Series(random_values, index=rng)
+
+ result_1 = ts_1.resample("D", origin="epoch").mean()
+ result_2 = ts_1.resample("24H", origin="epoch").mean()
+ tm.assert_series_equal(result_1, result_2)
+
+ # check that we have the same behavior with epoch even if we are not timezone aware
+ ts_no_tz = ts_1.tz_localize(None)
+ result_3 = ts_no_tz.resample("D", origin="epoch").mean()
+ result_4 = ts_no_tz.resample("24H", origin="epoch").mean()
+ tm.assert_series_equal(result_1, result_3.tz_localize(rng.tz), check_freq=False)
+ tm.assert_series_equal(result_1, result_4.tz_localize(rng.tz), check_freq=False)
+
+ # check that we have the similar results with two different timezones (+2H and +5H)
+ start, end = "2000-10-01 23:30:00+0200", "2000-12-02 00:30:00+0200"
+ rng = date_range(start, end, freq="7min").as_unit(unit)
+ ts_2 = Series(random_values, index=rng)
+ result_5 = ts_2.resample("D", origin="epoch").mean()
+ result_6 = ts_2.resample("24H", origin="epoch").mean()
+ tm.assert_series_equal(result_1.tz_localize(None), result_5.tz_localize(None))
+ tm.assert_series_equal(result_1.tz_localize(None), result_6.tz_localize(None))
+
+
+def test_resample_origin_with_day_freq_on_dst(unit):
+ # GH 31809
+ tz = "America/Chicago"
+
+ def _create_series(values, timestamps, freq="D"):
+ return Series(
+ values,
+ index=DatetimeIndex(
+ [Timestamp(t, tz=tz) for t in timestamps], freq=freq, ambiguous=True
+ ).as_unit(unit),
+ )
+
+ # test classical behavior of origin in a DST context
+ start = Timestamp("2013-11-02", tz=tz)
+ end = Timestamp("2013-11-03 23:59", tz=tz)
+ rng = date_range(start, end, freq="1h").as_unit(unit)
+ ts = Series(np.ones(len(rng)), index=rng)
+
+ expected = _create_series([24.0, 25.0], ["2013-11-02", "2013-11-03"])
+ for origin in ["epoch", "start", "start_day", start, None]:
+ result = ts.resample("D", origin=origin).sum()
+ tm.assert_series_equal(result, expected)
+
+ # test complex behavior of origin/offset in a DST context
+ start = Timestamp("2013-11-03", tz=tz)
+ end = Timestamp("2013-11-03 23:59", tz=tz)
+ rng = date_range(start, end, freq="1h").as_unit(unit)
+ ts = Series(np.ones(len(rng)), index=rng)
+
+ expected_ts = ["2013-11-02 22:00-05:00", "2013-11-03 22:00-06:00"]
+ expected = _create_series([23.0, 2.0], expected_ts)
+ result = ts.resample("D", origin="start", offset="-2H").sum()
+ tm.assert_series_equal(result, expected)
+
+ expected_ts = ["2013-11-02 22:00-05:00", "2013-11-03 21:00-06:00"]
+ expected = _create_series([22.0, 3.0], expected_ts, freq="24H")
+ result = ts.resample("24H", origin="start", offset="-2H").sum()
+ tm.assert_series_equal(result, expected)
+
+ expected_ts = ["2013-11-02 02:00-05:00", "2013-11-03 02:00-06:00"]
+ expected = _create_series([3.0, 22.0], expected_ts)
+ result = ts.resample("D", origin="start", offset="2H").sum()
+ tm.assert_series_equal(result, expected)
+
+ expected_ts = ["2013-11-02 23:00-05:00", "2013-11-03 23:00-06:00"]
+ expected = _create_series([24.0, 1.0], expected_ts)
+ result = ts.resample("D", origin="start", offset="-1H").sum()
+ tm.assert_series_equal(result, expected)
+
+ expected_ts = ["2013-11-02 01:00-05:00", "2013-11-03 01:00:00-0500"]
+ expected = _create_series([1.0, 24.0], expected_ts)
+ result = ts.resample("D", origin="start", offset="1H").sum()
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_daily_anchored(unit):
+ rng = date_range("1/1/2000 0:00:00", periods=10000, freq="T").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+ ts[:2] = np.nan # so results are the same
+
+ result = ts[2:].resample("D", closed="left", label="left").mean()
+ expected = ts.resample("D", closed="left", label="left").mean()
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_to_period_monthly_buglet(unit):
+ # GH #1259
+
+ rng = date_range("1/1/2000", "12/31/2000").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ result = ts.resample("M", kind="period").mean()
+ exp_index = period_range("Jan-2000", "Dec-2000", freq="M")
+ tm.assert_index_equal(result.index, exp_index)
+
+
+def test_period_with_agg():
+ # aggregate a period resampler with a lambda
+ s2 = Series(
+ np.random.default_rng(2).integers(0, 5, 50),
+ index=period_range("2012-01-01", freq="H", periods=50),
+ dtype="float64",
+ )
+
+ expected = s2.to_timestamp().resample("D").mean().to_period()
+ result = s2.resample("D").agg(lambda x: x.mean())
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_segfault(unit):
+ # GH 8573
+ # segfaulting in older versions
+ all_wins_and_wagers = [
+ (1, datetime(2013, 10, 1, 16, 20), 1, 0),
+ (2, datetime(2013, 10, 1, 16, 10), 1, 0),
+ (2, datetime(2013, 10, 1, 18, 15), 1, 0),
+ (2, datetime(2013, 10, 1, 16, 10, 31), 1, 0),
+ ]
+
+ df = DataFrame.from_records(
+ all_wins_and_wagers, columns=("ID", "timestamp", "A", "B")
+ ).set_index("timestamp")
+ df.index = df.index.as_unit(unit)
+ result = df.groupby("ID").resample("5min").sum()
+ expected = df.groupby("ID").apply(lambda x: x.resample("5min").sum())
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_dtype_preservation(unit):
+ # GH 12202
+ # validation tests for dtype preservation
+
+ df = DataFrame(
+ {
+ "date": date_range(start="2016-01-01", periods=4, freq="W").as_unit(unit),
+ "group": [1, 1, 2, 2],
+ "val": Series([5, 6, 7, 8], dtype="int32"),
+ }
+ ).set_index("date")
+
+ result = df.resample("1D").ffill()
+ assert result.val.dtype == np.int32
+
+ result = df.groupby("group").resample("1D").ffill()
+ assert result.val.dtype == np.int32
+
+
+def test_resample_dtype_coercion(unit):
+ pytest.importorskip("scipy.interpolate")
+
+ # GH 16361
+ df = {"a": [1, 3, 1, 4]}
+ df = DataFrame(df, index=date_range("2017-01-01", "2017-01-04").as_unit(unit))
+
+ expected = df.astype("float64").resample("H").mean()["a"].interpolate("cubic")
+
+ result = df.resample("H")["a"].mean().interpolate("cubic")
+ tm.assert_series_equal(result, expected)
+
+ result = df.resample("H").mean()["a"].interpolate("cubic")
+ tm.assert_series_equal(result, expected)
+
+
+def test_weekly_resample_buglet(unit):
+ # #1327
+ rng = date_range("1/1/2000", freq="B", periods=20).as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ resampled = ts.resample("W").mean()
+ expected = ts.resample("W-SUN").mean()
+ tm.assert_series_equal(resampled, expected)
+
+
+def test_monthly_resample_error(unit):
+ # #1451
+ dates = date_range("4/16/2012 20:00", periods=5000, freq="h").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(dates)), index=dates)
+ # it works!
+ ts.resample("M")
+
+
+def test_nanosecond_resample_error():
+ # GH 12307 - Values falls after last bin when
+ # Resampling using pd.tseries.offsets.Nano as period
+ start = 1443707890427
+ exp_start = 1443707890400
+ indx = date_range(start=pd.to_datetime(start), periods=10, freq="100n")
+ ts = Series(range(len(indx)), index=indx)
+ r = ts.resample(pd.tseries.offsets.Nano(100))
+ result = r.agg("mean")
+
+ exp_indx = date_range(start=pd.to_datetime(exp_start), periods=10, freq="100n")
+ exp = Series(range(len(exp_indx)), index=exp_indx, dtype=float)
+
+ tm.assert_series_equal(result, exp)
+
+
+def test_resample_anchored_intraday(simple_date_range_series, unit):
+ # #1471, #1458
+
+ rng = date_range("1/1/2012", "4/1/2012", freq="100min").as_unit(unit)
+ df = DataFrame(rng.month, index=rng)
+
+ result = df.resample("M").mean()
+ expected = df.resample("M", kind="period").mean().to_timestamp(how="end")
+ expected.index += Timedelta(1, "ns") - Timedelta(1, "D")
+ expected.index = expected.index.as_unit(unit)._with_freq("infer")
+ assert expected.index.freq == "M"
+ tm.assert_frame_equal(result, expected)
+
+ result = df.resample("M", closed="left").mean()
+ exp = df.shift(1, freq="D").resample("M", kind="period").mean()
+ exp = exp.to_timestamp(how="end")
+
+ exp.index = exp.index + Timedelta(1, "ns") - Timedelta(1, "D")
+ exp.index = exp.index.as_unit(unit)._with_freq("infer")
+ assert exp.index.freq == "M"
+ tm.assert_frame_equal(result, exp)
+
+ rng = date_range("1/1/2012", "4/1/2012", freq="100min").as_unit(unit)
+ df = DataFrame(rng.month, index=rng)
+
+ result = df.resample("Q").mean()
+ expected = df.resample("Q", kind="period").mean().to_timestamp(how="end")
+ expected.index += Timedelta(1, "ns") - Timedelta(1, "D")
+ expected.index._data.freq = "Q"
+ expected.index._freq = lib.no_default
+ expected.index = expected.index.as_unit(unit)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.resample("Q", closed="left").mean()
+ expected = df.shift(1, freq="D").resample("Q", kind="period", closed="left").mean()
+ expected = expected.to_timestamp(how="end")
+ expected.index += Timedelta(1, "ns") - Timedelta(1, "D")
+ expected.index._data.freq = "Q"
+ expected.index._freq = lib.no_default
+ expected.index = expected.index.as_unit(unit)
+ tm.assert_frame_equal(result, expected)
+
+ ts = simple_date_range_series("2012-04-29 23:00", "2012-04-30 5:00", freq="h")
+ ts.index = ts.index.as_unit(unit)
+ resampled = ts.resample("M").mean()
+ assert len(resampled) == 1
+
+
+@pytest.mark.parametrize("freq", ["MS", "BMS", "QS-MAR", "AS-DEC", "AS-JUN"])
+def test_resample_anchored_monthstart(simple_date_range_series, freq, unit):
+ ts = simple_date_range_series("1/1/2000", "12/31/2002")
+ ts.index = ts.index.as_unit(unit)
+ ts.resample(freq).mean()
+
+
+@pytest.mark.parametrize("label, sec", [[None, 2.0], ["right", "4.2"]])
+def test_resample_anchored_multiday(label, sec):
+ # When resampling a range spanning multiple days, ensure that the
+ # start date gets used to determine the offset. Fixes issue where
+ # a one day period is not a multiple of the frequency.
+ #
+ # See: https://github.com/pandas-dev/pandas/issues/8683
+
+ index1 = date_range("2014-10-14 23:06:23.206", periods=3, freq="400L")
+ index2 = date_range("2014-10-15 23:00:00", periods=2, freq="2200L")
+ index = index1.union(index2)
+
+ s = Series(np.random.default_rng(2).standard_normal(5), index=index)
+
+ # Ensure left closing works
+ result = s.resample("2200L", label=label).mean()
+ assert result.index[-1] == Timestamp(f"2014-10-15 23:00:{sec}00")
+
+
+def test_corner_cases(unit):
+ # miscellaneous test coverage
+
+ rng = date_range("1/1/2000", periods=12, freq="t").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ result = ts.resample("5t", closed="right", label="left").mean()
+ ex_index = date_range("1999-12-31 23:55", periods=4, freq="5t").as_unit(unit)
+ tm.assert_index_equal(result.index, ex_index)
+
+
+def test_corner_cases_period(simple_period_range_series):
+ # miscellaneous test coverage
+ len0pts = simple_period_range_series("2007-01", "2010-05", freq="M")[:0]
+ # it works
+ result = len0pts.resample("A-DEC").mean()
+ assert len(result) == 0
+
+
+def test_corner_cases_date(simple_date_range_series, unit):
+ # resample to periods
+ ts = simple_date_range_series("2000-04-28", "2000-04-30 11:00", freq="h")
+ ts.index = ts.index.as_unit(unit)
+ result = ts.resample("M", kind="period").mean()
+ assert len(result) == 1
+ assert result.index[0] == Period("2000-04", freq="M")
+
+
+def test_anchored_lowercase_buglet(unit):
+ dates = date_range("4/16/2012 20:00", periods=50000, freq="s").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(dates)), index=dates)
+ # it works!
+ ts.resample("d").mean()
+
+
+def test_upsample_apply_functions(unit):
+ # #1596
+ rng = date_range("2012-06-12", periods=4, freq="h").as_unit(unit)
+
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ result = ts.resample("20min").aggregate(["mean", "sum"])
+ assert isinstance(result, DataFrame)
+
+
+def test_resample_not_monotonic(unit):
+ rng = date_range("2012-06-12", periods=200, freq="h").as_unit(unit)
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ ts = ts.take(np.random.default_rng(2).permutation(len(ts)))
+
+ result = ts.resample("D").sum()
+ exp = ts.sort_index().resample("D").sum()
+ tm.assert_series_equal(result, exp)
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ "int64",
+ "int32",
+ "float64",
+ pytest.param(
+ "float32",
+ marks=pytest.mark.xfail(
+ reason="Empty groups cause x.mean() to return float64"
+ ),
+ ),
+ ],
+)
+def test_resample_median_bug_1688(dtype):
+ df = DataFrame(
+ [1, 2],
+ index=[datetime(2012, 1, 1, 0, 0, 0), datetime(2012, 1, 1, 0, 5, 0)],
+ dtype=dtype,
+ )
+
+ result = df.resample("T").apply(lambda x: x.mean())
+ exp = df.asfreq("T")
+ tm.assert_frame_equal(result, exp)
+
+ result = df.resample("T").median()
+ exp = df.asfreq("T")
+ tm.assert_frame_equal(result, exp)
+
+
+def test_how_lambda_functions(simple_date_range_series, unit):
+ ts = simple_date_range_series("1/1/2000", "4/1/2000")
+ ts.index = ts.index.as_unit(unit)
+
+ result = ts.resample("M").apply(lambda x: x.mean())
+ exp = ts.resample("M").mean()
+ tm.assert_series_equal(result, exp)
+
+ foo_exp = ts.resample("M").mean()
+ foo_exp.name = "foo"
+ bar_exp = ts.resample("M").std()
+ bar_exp.name = "bar"
+
+ result = ts.resample("M").apply([lambda x: x.mean(), lambda x: x.std(ddof=1)])
+ result.columns = ["foo", "bar"]
+ tm.assert_series_equal(result["foo"], foo_exp)
+ tm.assert_series_equal(result["bar"], bar_exp)
+
+ # this is a MI Series, so comparing the names of the results
+ # doesn't make sense
+ result = ts.resample("M").aggregate(
+ {"foo": lambda x: x.mean(), "bar": lambda x: x.std(ddof=1)}
+ )
+ tm.assert_series_equal(result["foo"], foo_exp, check_names=False)
+ tm.assert_series_equal(result["bar"], bar_exp, check_names=False)
+
+
+def test_resample_unequal_times(unit):
+ # #1772
+ start = datetime(1999, 3, 1, 5)
+ # end hour is less than start
+ end = datetime(2012, 7, 31, 4)
+ bad_ind = date_range(start, end, freq="30min").as_unit(unit)
+ df = DataFrame({"close": 1}, index=bad_ind)
+
+ # it works!
+ df.resample("AS").sum()
+
+
+def test_resample_consistency(unit):
+ # GH 6418
+ # resample with bfill / limit / reindex consistency
+
+ i30 = date_range("2002-02-02", periods=4, freq="30T").as_unit(unit)
+ s = Series(np.arange(4.0), index=i30)
+ s.iloc[2] = np.nan
+
+ # Upsample by factor 3 with reindex() and resample() methods:
+ i10 = date_range(i30[0], i30[-1], freq="10T").as_unit(unit)
+
+ s10 = s.reindex(index=i10, method="bfill")
+ s10_2 = s.reindex(index=i10, method="bfill", limit=2)
+ rl = s.reindex_like(s10, method="bfill", limit=2)
+ r10_2 = s.resample("10Min").bfill(limit=2)
+ r10 = s.resample("10Min").bfill()
+
+ # s10_2, r10, r10_2, rl should all be equal
+ tm.assert_series_equal(s10_2, r10)
+ tm.assert_series_equal(s10_2, r10_2)
+ tm.assert_series_equal(s10_2, rl)
+
+
+dates1: list[DatetimeNaTType] = [
+ datetime(2014, 10, 1),
+ datetime(2014, 9, 3),
+ datetime(2014, 11, 5),
+ datetime(2014, 9, 5),
+ datetime(2014, 10, 8),
+ datetime(2014, 7, 15),
+]
+
+dates2: list[DatetimeNaTType] = (
+ dates1[:2] + [pd.NaT] + dates1[2:4] + [pd.NaT] + dates1[4:]
+)
+dates3 = [pd.NaT] + dates1 + [pd.NaT]
+
+
+@pytest.mark.parametrize("dates", [dates1, dates2, dates3])
+def test_resample_timegrouper(dates):
+ # GH 7227
+ df = DataFrame({"A": dates, "B": np.arange(len(dates))})
+ result = df.set_index("A").resample("M").count()
+ exp_idx = DatetimeIndex(
+ ["2014-07-31", "2014-08-31", "2014-09-30", "2014-10-31", "2014-11-30"],
+ freq="M",
+ name="A",
+ )
+ expected = DataFrame({"B": [1, 0, 2, 2, 1]}, index=exp_idx)
+ if df["A"].isna().any():
+ expected.index = expected.index._with_freq(None)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(Grouper(freq="M", key="A")).count()
+ tm.assert_frame_equal(result, expected)
+
+ df = DataFrame({"A": dates, "B": np.arange(len(dates)), "C": np.arange(len(dates))})
+ result = df.set_index("A").resample("M").count()
+ expected = DataFrame(
+ {"B": [1, 0, 2, 2, 1], "C": [1, 0, 2, 2, 1]},
+ index=exp_idx,
+ columns=["B", "C"],
+ )
+ if df["A"].isna().any():
+ expected.index = expected.index._with_freq(None)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(Grouper(freq="M", key="A")).count()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_nunique(unit):
+ # GH 12352
+ df = DataFrame(
+ {
+ "ID": {
+ Timestamp("2015-06-05 00:00:00"): "0010100903",
+ Timestamp("2015-06-08 00:00:00"): "0010150847",
+ },
+ "DATE": {
+ Timestamp("2015-06-05 00:00:00"): "2015-06-05",
+ Timestamp("2015-06-08 00:00:00"): "2015-06-08",
+ },
+ }
+ )
+ df.index = df.index.as_unit(unit)
+ r = df.resample("D")
+ g = df.groupby(Grouper(freq="D"))
+ expected = df.groupby(Grouper(freq="D")).ID.apply(lambda x: x.nunique())
+ assert expected.name == "ID"
+
+ for t in [r, g]:
+ result = t.ID.nunique()
+ tm.assert_series_equal(result, expected)
+
+ result = df.ID.resample("D").nunique()
+ tm.assert_series_equal(result, expected)
+
+ result = df.ID.groupby(Grouper(freq="D")).nunique()
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_nunique_preserves_column_level_names(unit):
+ # see gh-23222
+ df = tm.makeTimeDataFrame(freq="1D").abs()
+ df.index = df.index.as_unit(unit)
+ df.columns = pd.MultiIndex.from_arrays(
+ [df.columns.tolist()] * 2, names=["lev0", "lev1"]
+ )
+ result = df.resample("1h").nunique()
+ tm.assert_index_equal(df.columns, result.columns)
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ lambda x: x.nunique(),
+ lambda x: x.agg(Series.nunique),
+ lambda x: x.agg("nunique"),
+ ],
+ ids=["nunique", "series_nunique", "nunique_str"],
+)
+def test_resample_nunique_with_date_gap(func, unit):
+ # GH 13453
+ # Since all elements are unique, these should all be the same
+ index = date_range("1-1-2000", "2-15-2000", freq="h").as_unit(unit)
+ index2 = date_range("4-15-2000", "5-15-2000", freq="h").as_unit(unit)
+ index3 = index.append(index2)
+ s = Series(range(len(index3)), index=index3, dtype="int64")
+ r = s.resample("M")
+ result = r.count()
+ expected = func(r)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("n", [10000, 100000])
+@pytest.mark.parametrize("k", [10, 100, 1000])
+def test_resample_group_info(n, k, unit):
+ # GH10914
+
+ # use a fixed seed to always have the same uniques
+ prng = np.random.default_rng(2)
+
+ dr = date_range(start="2015-08-27", periods=n // 10, freq="T").as_unit(unit)
+ ts = Series(prng.integers(0, n // k, n).astype("int64"), index=prng.choice(dr, n))
+
+ left = ts.resample("30T").nunique()
+ ix = date_range(start=ts.index.min(), end=ts.index.max(), freq="30T").as_unit(unit)
+
+ vals = ts.values
+ bins = np.searchsorted(ix.values, ts.index, side="right")
+
+ sorter = np.lexsort((vals, bins))
+ vals, bins = vals[sorter], bins[sorter]
+
+ mask = np.r_[True, vals[1:] != vals[:-1]]
+ mask |= np.r_[True, bins[1:] != bins[:-1]]
+
+ arr = np.bincount(bins[mask] - 1, minlength=len(ix)).astype("int64", copy=False)
+ right = Series(arr, index=ix)
+
+ tm.assert_series_equal(left, right)
+
+
+def test_resample_size(unit):
+ n = 10000
+ dr = date_range("2015-09-19", periods=n, freq="T").as_unit(unit)
+ ts = Series(
+ np.random.default_rng(2).standard_normal(n),
+ index=np.random.default_rng(2).choice(dr, n),
+ )
+
+ left = ts.resample("7T").size()
+ ix = date_range(start=left.index.min(), end=ts.index.max(), freq="7T").as_unit(unit)
+
+ bins = np.searchsorted(ix.values, ts.index.values, side="right")
+ val = np.bincount(bins, minlength=len(ix) + 1)[1:].astype("int64", copy=False)
+
+ right = Series(val, index=ix)
+ tm.assert_series_equal(left, right)
+
+
+def test_resample_across_dst():
+ # The test resamples a DatetimeIndex with values before and after a
+ # DST change
+ # Issue: 14682
+
+ # The DatetimeIndex we will start with
+ # (note that DST happens at 03:00+02:00 -> 02:00+01:00)
+ # 2016-10-30 02:23:00+02:00, 2016-10-30 02:23:00+01:00
+ df1 = DataFrame([1477786980, 1477790580], columns=["ts"])
+ dti1 = DatetimeIndex(
+ pd.to_datetime(df1.ts, unit="s")
+ .dt.tz_localize("UTC")
+ .dt.tz_convert("Europe/Madrid")
+ )
+
+ # The expected DatetimeIndex after resampling.
+ # 2016-10-30 02:00:00+02:00, 2016-10-30 02:00:00+01:00
+ df2 = DataFrame([1477785600, 1477789200], columns=["ts"])
+ dti2 = DatetimeIndex(
+ pd.to_datetime(df2.ts, unit="s")
+ .dt.tz_localize("UTC")
+ .dt.tz_convert("Europe/Madrid"),
+ freq="H",
+ )
+ df = DataFrame([5, 5], index=dti1)
+
+ result = df.resample(rule="H").sum()
+ expected = DataFrame([5, 5], index=dti2)
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_with_dst_time_change(unit):
+ # GH 24972
+ index = (
+ DatetimeIndex([1478064900001000000, 1480037118776792000], tz="UTC")
+ .tz_convert("America/Chicago")
+ .as_unit(unit)
+ )
+
+ df = DataFrame([1, 2], index=index)
+ result = df.groupby(Grouper(freq="1d")).last()
+ expected_index_values = date_range(
+ "2016-11-02", "2016-11-24", freq="d", tz="America/Chicago"
+ ).as_unit(unit)
+
+ index = DatetimeIndex(expected_index_values)
+ expected = DataFrame([1.0] + ([np.nan] * 21) + [2.0], index=index)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_dst_anchor(unit):
+ # 5172
+ dti = DatetimeIndex([datetime(2012, 11, 4, 23)], tz="US/Eastern").as_unit(unit)
+ df = DataFrame([5], index=dti)
+
+ dti = DatetimeIndex(df.index.normalize(), freq="D").as_unit(unit)
+ expected = DataFrame([5], index=dti)
+ tm.assert_frame_equal(df.resample(rule="D").sum(), expected)
+ df.resample(rule="MS").sum()
+ tm.assert_frame_equal(
+ df.resample(rule="MS").sum(),
+ DataFrame(
+ [5],
+ index=DatetimeIndex(
+ [datetime(2012, 11, 1)], tz="US/Eastern", freq="MS"
+ ).as_unit(unit),
+ ),
+ )
+
+ dti = date_range(
+ "2013-09-30", "2013-11-02", freq="30Min", tz="Europe/Paris"
+ ).as_unit(unit)
+ values = range(dti.size)
+ df = DataFrame({"a": values, "b": values, "c": values}, index=dti, dtype="int64")
+ how = {"a": "min", "b": "max", "c": "count"}
+
+ tm.assert_frame_equal(
+ df.resample("W-MON").agg(how)[["a", "b", "c"]],
+ DataFrame(
+ {
+ "a": [0, 48, 384, 720, 1056, 1394],
+ "b": [47, 383, 719, 1055, 1393, 1586],
+ "c": [48, 336, 336, 336, 338, 193],
+ },
+ index=date_range(
+ "9/30/2013", "11/4/2013", freq="W-MON", tz="Europe/Paris"
+ ).as_unit(unit),
+ ),
+ "W-MON Frequency",
+ )
+
+ tm.assert_frame_equal(
+ df.resample("2W-MON").agg(how)[["a", "b", "c"]],
+ DataFrame(
+ {
+ "a": [0, 48, 720, 1394],
+ "b": [47, 719, 1393, 1586],
+ "c": [48, 672, 674, 193],
+ },
+ index=date_range(
+ "9/30/2013", "11/11/2013", freq="2W-MON", tz="Europe/Paris"
+ ).as_unit(unit),
+ ),
+ "2W-MON Frequency",
+ )
+
+ tm.assert_frame_equal(
+ df.resample("MS").agg(how)[["a", "b", "c"]],
+ DataFrame(
+ {"a": [0, 48, 1538], "b": [47, 1537, 1586], "c": [48, 1490, 49]},
+ index=date_range(
+ "9/1/2013", "11/1/2013", freq="MS", tz="Europe/Paris"
+ ).as_unit(unit),
+ ),
+ "MS Frequency",
+ )
+
+ tm.assert_frame_equal(
+ df.resample("2MS").agg(how)[["a", "b", "c"]],
+ DataFrame(
+ {"a": [0, 1538], "b": [1537, 1586], "c": [1538, 49]},
+ index=date_range(
+ "9/1/2013", "11/1/2013", freq="2MS", tz="Europe/Paris"
+ ).as_unit(unit),
+ ),
+ "2MS Frequency",
+ )
+
+ df_daily = df["10/26/2013":"10/29/2013"]
+ tm.assert_frame_equal(
+ df_daily.resample("D").agg({"a": "min", "b": "max", "c": "count"})[
+ ["a", "b", "c"]
+ ],
+ DataFrame(
+ {
+ "a": [1248, 1296, 1346, 1394],
+ "b": [1295, 1345, 1393, 1441],
+ "c": [48, 50, 48, 48],
+ },
+ index=date_range(
+ "10/26/2013", "10/29/2013", freq="D", tz="Europe/Paris"
+ ).as_unit(unit),
+ ),
+ "D Frequency",
+ )
+
+
+def test_downsample_across_dst(unit):
+ # GH 8531
+ tz = pytz.timezone("Europe/Berlin")
+ dt = datetime(2014, 10, 26)
+ dates = date_range(tz.localize(dt), periods=4, freq="2H").as_unit(unit)
+ result = Series(5, index=dates).resample("H").mean()
+ expected = Series(
+ [5.0, np.nan] * 3 + [5.0],
+ index=date_range(tz.localize(dt), periods=7, freq="H").as_unit(unit),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_downsample_across_dst_weekly(unit):
+ # GH 9119, GH 21459
+ df = DataFrame(
+ index=DatetimeIndex(
+ ["2017-03-25", "2017-03-26", "2017-03-27", "2017-03-28", "2017-03-29"],
+ tz="Europe/Amsterdam",
+ ).as_unit(unit),
+ data=[11, 12, 13, 14, 15],
+ )
+ result = df.resample("1W").sum()
+ expected = DataFrame(
+ [23, 42],
+ index=DatetimeIndex(
+ ["2017-03-26", "2017-04-02"], tz="Europe/Amsterdam", freq="W"
+ ).as_unit(unit),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_downsample_across_dst_weekly_2(unit):
+ # GH 9119, GH 21459
+ idx = date_range("2013-04-01", "2013-05-01", tz="Europe/London", freq="H").as_unit(
+ unit
+ )
+ s = Series(index=idx, dtype=np.float64)
+ result = s.resample("W").mean()
+ expected = Series(
+ index=date_range("2013-04-07", freq="W", periods=5, tz="Europe/London").as_unit(
+ unit
+ ),
+ dtype=np.float64,
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_downsample_dst_at_midnight(unit):
+ # GH 25758
+ start = datetime(2018, 11, 3, 12)
+ end = datetime(2018, 11, 5, 12)
+ index = date_range(start, end, freq="1H").as_unit(unit)
+ index = index.tz_localize("UTC").tz_convert("America/Havana")
+ data = list(range(len(index)))
+ dataframe = DataFrame(data, index=index)
+ result = dataframe.groupby(Grouper(freq="1D")).mean()
+
+ dti = date_range("2018-11-03", periods=3).tz_localize(
+ "America/Havana", ambiguous=True
+ )
+ dti = DatetimeIndex(dti, freq="D").as_unit(unit)
+ expected = DataFrame([7.5, 28.0, 44.5], index=dti)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_with_nat(unit):
+ # GH 13020
+ index = DatetimeIndex(
+ [
+ pd.NaT,
+ "1970-01-01 00:00:00",
+ pd.NaT,
+ "1970-01-01 00:00:01",
+ "1970-01-01 00:00:02",
+ ]
+ )
+ frame = DataFrame([2, 3, 5, 7, 11], index=index)
+ frame.index = frame.index.as_unit(unit)
+
+ index_1s = DatetimeIndex(
+ ["1970-01-01 00:00:00", "1970-01-01 00:00:01", "1970-01-01 00:00:02"]
+ ).as_unit(unit)
+ frame_1s = DataFrame([3.0, 7.0, 11.0], index=index_1s)
+ tm.assert_frame_equal(frame.resample("1s").mean(), frame_1s)
+
+ index_2s = DatetimeIndex(["1970-01-01 00:00:00", "1970-01-01 00:00:02"]).as_unit(
+ unit
+ )
+ frame_2s = DataFrame([5.0, 11.0], index=index_2s)
+ tm.assert_frame_equal(frame.resample("2s").mean(), frame_2s)
+
+ index_3s = DatetimeIndex(["1970-01-01 00:00:00"]).as_unit(unit)
+ frame_3s = DataFrame([7.0], index=index_3s)
+ tm.assert_frame_equal(frame.resample("3s").mean(), frame_3s)
+
+ tm.assert_frame_equal(frame.resample("60s").mean(), frame_3s)
+
+
+def test_resample_datetime_values(unit):
+ # GH 13119
+ # check that datetime dtype is preserved when NaT values are
+ # introduced by the resampling
+
+ dates = [datetime(2016, 1, 15), datetime(2016, 1, 19)]
+ df = DataFrame({"timestamp": dates}, index=dates)
+ df.index = df.index.as_unit(unit)
+
+ exp = Series(
+ [datetime(2016, 1, 15), pd.NaT, datetime(2016, 1, 19)],
+ index=date_range("2016-01-15", periods=3, freq="2D").as_unit(unit),
+ name="timestamp",
+ )
+
+ res = df.resample("2D").first()["timestamp"]
+ tm.assert_series_equal(res, exp)
+ res = df["timestamp"].resample("2D").first()
+ tm.assert_series_equal(res, exp)
+
+
+def test_resample_apply_with_additional_args(series, unit):
+ # GH 14615
+ def f(data, add_arg):
+ return np.mean(data) * add_arg
+
+ series.index = series.index.as_unit(unit)
+
+ multiplier = 10
+ result = series.resample("D").apply(f, multiplier)
+ expected = series.resample("D").mean().multiply(multiplier)
+ tm.assert_series_equal(result, expected)
+
+ # Testing as kwarg
+ result = series.resample("D").apply(f, add_arg=multiplier)
+ expected = series.resample("D").mean().multiply(multiplier)
+ tm.assert_series_equal(result, expected)
+
+ # Testing dataframe
+ df = DataFrame({"A": 1, "B": 2}, index=date_range("2017", periods=10))
+ result = df.groupby("A").resample("D").agg(f, multiplier).astype(float)
+ expected = df.groupby("A").resample("D").mean().multiply(multiplier)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("k", [1, 2, 3])
+@pytest.mark.parametrize(
+ "n1, freq1, n2, freq2",
+ [
+ (30, "S", 0.5, "Min"),
+ (60, "S", 1, "Min"),
+ (3600, "S", 1, "H"),
+ (60, "Min", 1, "H"),
+ (21600, "S", 0.25, "D"),
+ (86400, "S", 1, "D"),
+ (43200, "S", 0.5, "D"),
+ (1440, "Min", 1, "D"),
+ (12, "H", 0.5, "D"),
+ (24, "H", 1, "D"),
+ ],
+)
+def test_resample_equivalent_offsets(n1, freq1, n2, freq2, k, unit):
+ # GH 24127
+ n1_ = n1 * k
+ n2_ = n2 * k
+ dti = date_range("19910905 13:00", "19911005 07:00", freq=freq1).as_unit(unit)
+ ser = Series(range(len(dti)), index=dti)
+
+ result1 = ser.resample(str(n1_) + freq1).mean()
+ result2 = ser.resample(str(n2_) + freq2).mean()
+ tm.assert_series_equal(result1, result2)
+
+
+@pytest.mark.parametrize(
+ "first,last,freq,exp_first,exp_last",
+ [
+ ("19910905", "19920406", "D", "19910905", "19920407"),
+ ("19910905 00:00", "19920406 06:00", "D", "19910905", "19920407"),
+ ("19910905 06:00", "19920406 06:00", "H", "19910905 06:00", "19920406 07:00"),
+ ("19910906", "19920406", "M", "19910831", "19920430"),
+ ("19910831", "19920430", "M", "19910831", "19920531"),
+ ("1991-08", "1992-04", "M", "19910831", "19920531"),
+ ],
+)
+def test_get_timestamp_range_edges(first, last, freq, exp_first, exp_last, unit):
+ first = Period(first)
+ first = first.to_timestamp(first.freq).as_unit(unit)
+ last = Period(last)
+ last = last.to_timestamp(last.freq).as_unit(unit)
+
+ exp_first = Timestamp(exp_first)
+ exp_last = Timestamp(exp_last)
+
+ freq = pd.tseries.frequencies.to_offset(freq)
+ result = _get_timestamp_range_edges(first, last, freq, unit="ns")
+ expected = (exp_first, exp_last)
+ assert result == expected
+
+
+@pytest.mark.parametrize("duplicates", [True, False])
+def test_resample_apply_product(duplicates, unit):
+ # GH 5586
+ index = date_range(start="2012-01-31", freq="M", periods=12).as_unit(unit)
+
+ ts = Series(range(12), index=index)
+ df = DataFrame({"A": ts, "B": ts + 2})
+ if duplicates:
+ df.columns = ["A", "A"]
+
+ msg = "using DatetimeIndexResampler.prod"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.resample("Q").apply(np.prod)
+ expected = DataFrame(
+ np.array([[0, 24], [60, 210], [336, 720], [990, 1716]], dtype=np.int64),
+ index=DatetimeIndex(
+ ["2012-03-31", "2012-06-30", "2012-09-30", "2012-12-31"], freq="Q-DEC"
+ ).as_unit(unit),
+ columns=df.columns,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "first,last,freq_in,freq_out,exp_last",
+ [
+ (
+ "2020-03-28",
+ "2020-03-31",
+ "D",
+ "24H",
+ "2020-03-30 01:00",
+ ), # includes transition into DST
+ (
+ "2020-03-28",
+ "2020-10-27",
+ "D",
+ "24H",
+ "2020-10-27 00:00",
+ ), # includes transition into and out of DST
+ (
+ "2020-10-25",
+ "2020-10-27",
+ "D",
+ "24H",
+ "2020-10-26 23:00",
+ ), # includes transition out of DST
+ (
+ "2020-03-28",
+ "2020-03-31",
+ "24H",
+ "D",
+ "2020-03-30 00:00",
+ ), # same as above, but from 24H to D
+ ("2020-03-28", "2020-10-27", "24H", "D", "2020-10-27 00:00"),
+ ("2020-10-25", "2020-10-27", "24H", "D", "2020-10-26 00:00"),
+ ],
+)
+def test_resample_calendar_day_with_dst(
+ first: str, last: str, freq_in: str, freq_out: str, exp_last: str, unit
+):
+ # GH 35219
+ ts = Series(
+ 1.0, date_range(first, last, freq=freq_in, tz="Europe/Amsterdam").as_unit(unit)
+ )
+ result = ts.resample(freq_out).ffill()
+ expected = Series(
+ 1.0,
+ date_range(first, exp_last, freq=freq_out, tz="Europe/Amsterdam").as_unit(unit),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", ["min", "max", "first", "last"])
+def test_resample_aggregate_functions_min_count(func, unit):
+ # GH#37768
+ index = date_range(start="2020", freq="M", periods=3).as_unit(unit)
+ ser = Series([1, np.nan, np.nan], index)
+ result = getattr(ser.resample("Q"), func)(min_count=2)
+ expected = Series(
+ [np.nan],
+ index=DatetimeIndex(["2020-03-31"], freq="Q-DEC").as_unit(unit),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_unsigned_int(any_unsigned_int_numpy_dtype, unit):
+ # gh-43329
+ df = DataFrame(
+ index=date_range(start="2000-01-01", end="2000-01-03 23", freq="12H").as_unit(
+ unit
+ ),
+ columns=["x"],
+ data=[0, 1, 0] * 2,
+ dtype=any_unsigned_int_numpy_dtype,
+ )
+ df = df.loc[(df.index < "2000-01-02") | (df.index > "2000-01-03"), :]
+
+ result = df.resample("D").max()
+
+ expected = DataFrame(
+ [1, np.nan, 0],
+ columns=["x"],
+ index=date_range(start="2000-01-01", end="2000-01-03 23", freq="D").as_unit(
+ unit
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_long_rule_non_nano():
+ # https://github.com/pandas-dev/pandas/issues/51024
+ idx = date_range("0300-01-01", "2000-01-01", unit="s", freq="100Y")
+ ser = Series([1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5], index=idx)
+ result = ser.resample("200Y").mean()
+ expected_idx = DatetimeIndex(
+ np.array(
+ [
+ "0300-12-31",
+ "0500-12-31",
+ "0700-12-31",
+ "0900-12-31",
+ "1100-12-31",
+ "1300-12-31",
+ "1500-12-31",
+ "1700-12-31",
+ "1900-12-31",
+ ]
+ ).astype("datetime64[s]"),
+ freq="200A-DEC",
+ )
+ expected = Series([1.0, 3.0, 6.5, 4.0, 3.0, 6.5, 4.0, 3.0, 6.5], index=expected_idx)
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_empty_series_with_tz():
+ # GH#53664
+ df = DataFrame({"ts": [], "values": []}).astype(
+ {"ts": "datetime64[ns, Atlantic/Faroe]"}
+ )
+ result = df.resample("2MS", on="ts", closed="left", label="left", origin="start")[
+ "values"
+ ].sum()
+
+ expected_idx = DatetimeIndex(
+ [], freq="2MS", name="ts", dtype="datetime64[ns, Atlantic/Faroe]"
+ )
+ expected = Series([], index=expected_idx, name="values", dtype="float64")
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_period_index.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_period_index.py
new file mode 100644
index 0000000000000000000000000000000000000000..7559a85de7a6b0f2af95e369d6aa9c0b5450ae77
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_period_index.py
@@ -0,0 +1,895 @@
+from datetime import datetime
+
+import dateutil
+import numpy as np
+import pytest
+import pytz
+
+from pandas._libs.tslibs.ccalendar import (
+ DAYS,
+ MONTHS,
+)
+from pandas._libs.tslibs.period import IncompatibleFrequency
+from pandas.errors import InvalidIndexError
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
+import pandas._testing as tm
+from pandas.core.indexes.datetimes import date_range
+from pandas.core.indexes.period import (
+ Period,
+ PeriodIndex,
+ period_range,
+)
+from pandas.core.resample import _get_period_range_edges
+
+from pandas.tseries import offsets
+
+
+@pytest.fixture()
+def _index_factory():
+ return period_range
+
+
+@pytest.fixture
+def _series_name():
+ return "pi"
+
+
+class TestPeriodIndex:
+ @pytest.mark.parametrize("freq", ["2D", "1H", "2H"])
+ @pytest.mark.parametrize("kind", ["period", None, "timestamp"])
+ def test_asfreq(self, series_and_frame, freq, kind):
+ # GH 12884, 15944
+ # make sure .asfreq() returns PeriodIndex (except kind='timestamp')
+
+ obj = series_and_frame
+ if kind == "timestamp":
+ expected = obj.to_timestamp().resample(freq).asfreq()
+ else:
+ start = obj.index[0].to_timestamp(how="start")
+ end = (obj.index[-1] + obj.index.freq).to_timestamp(how="start")
+ new_index = date_range(start=start, end=end, freq=freq, inclusive="left")
+ expected = obj.to_timestamp().reindex(new_index).to_period(freq)
+ result = obj.resample(freq, kind=kind).asfreq()
+ tm.assert_almost_equal(result, expected)
+
+ def test_asfreq_fill_value(self, series):
+ # test for fill value during resampling, issue 3715
+
+ s = series
+ new_index = date_range(
+ s.index[0].to_timestamp(how="start"),
+ (s.index[-1]).to_timestamp(how="start"),
+ freq="1H",
+ )
+ expected = s.to_timestamp().reindex(new_index, fill_value=4.0)
+ result = s.resample("1H", kind="timestamp").asfreq(fill_value=4.0)
+ tm.assert_series_equal(result, expected)
+
+ frame = s.to_frame("value")
+ new_index = date_range(
+ frame.index[0].to_timestamp(how="start"),
+ (frame.index[-1]).to_timestamp(how="start"),
+ freq="1H",
+ )
+ expected = frame.to_timestamp().reindex(new_index, fill_value=3.0)
+ result = frame.resample("1H", kind="timestamp").asfreq(fill_value=3.0)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("freq", ["H", "12H", "2D", "W"])
+ @pytest.mark.parametrize("kind", [None, "period", "timestamp"])
+ @pytest.mark.parametrize("kwargs", [{"on": "date"}, {"level": "d"}])
+ def test_selection(self, index, freq, kind, kwargs):
+ # This is a bug, these should be implemented
+ # GH 14008
+ rng = np.arange(len(index), dtype=np.int64)
+ df = DataFrame(
+ {"date": index, "a": rng},
+ index=pd.MultiIndex.from_arrays([rng, index], names=["v", "d"]),
+ )
+ msg = (
+ "Resampling from level= or on= selection with a PeriodIndex is "
+ r"not currently supported, use \.set_index\(\.\.\.\) to "
+ "explicitly set index"
+ )
+ with pytest.raises(NotImplementedError, match=msg):
+ df.resample(freq, kind=kind, **kwargs)
+
+ @pytest.mark.parametrize("month", MONTHS)
+ @pytest.mark.parametrize("meth", ["ffill", "bfill"])
+ @pytest.mark.parametrize("conv", ["start", "end"])
+ @pytest.mark.parametrize("targ", ["D", "B", "M"])
+ def test_annual_upsample_cases(
+ self, targ, conv, meth, month, simple_period_range_series
+ ):
+ ts = simple_period_range_series("1/1/1990", "12/31/1991", freq=f"A-{month}")
+ warn = FutureWarning if targ == "B" else None
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = getattr(ts.resample(targ, convention=conv), meth)()
+ expected = result.to_timestamp(targ, how=conv)
+ expected = expected.asfreq(targ, meth).to_period()
+ tm.assert_series_equal(result, expected)
+
+ def test_basic_downsample(self, simple_period_range_series):
+ ts = simple_period_range_series("1/1/1990", "6/30/1995", freq="M")
+ result = ts.resample("a-dec").mean()
+
+ expected = ts.groupby(ts.index.year).mean()
+ expected.index = period_range("1/1/1990", "6/30/1995", freq="a-dec")
+ tm.assert_series_equal(result, expected)
+
+ # this is ok
+ tm.assert_series_equal(ts.resample("a-dec").mean(), result)
+ tm.assert_series_equal(ts.resample("a").mean(), result)
+
+ @pytest.mark.parametrize(
+ "rule,expected_error_msg",
+ [
+ ("a-dec", ""),
+ ("q-mar", ""),
+ ("M", ""),
+ ("w-thu", ""),
+ ],
+ )
+ def test_not_subperiod(self, simple_period_range_series, rule, expected_error_msg):
+ # These are incompatible period rules for resampling
+ ts = simple_period_range_series("1/1/1990", "6/30/1995", freq="w-wed")
+ msg = (
+ "Frequency cannot be resampled to "
+ f"{expected_error_msg}, as they are not sub or super periods"
+ )
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ ts.resample(rule).mean()
+
+ @pytest.mark.parametrize("freq", ["D", "2D"])
+ def test_basic_upsample(self, freq, simple_period_range_series):
+ ts = simple_period_range_series("1/1/1990", "6/30/1995", freq="M")
+ result = ts.resample("a-dec").mean()
+
+ resampled = result.resample(freq, convention="end").ffill()
+ expected = result.to_timestamp(freq, how="end")
+ expected = expected.asfreq(freq, "ffill").to_period(freq)
+ tm.assert_series_equal(resampled, expected)
+
+ def test_upsample_with_limit(self):
+ rng = period_range("1/1/2000", periods=5, freq="A")
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
+
+ result = ts.resample("M", convention="end").ffill(limit=2)
+ expected = ts.asfreq("M").reindex(result.index, method="ffill", limit=2)
+ tm.assert_series_equal(result, expected)
+
+ def test_annual_upsample(self, simple_period_range_series):
+ ts = simple_period_range_series("1/1/1990", "12/31/1995", freq="A-DEC")
+ df = DataFrame({"a": ts})
+ rdf = df.resample("D").ffill()
+ exp = df["a"].resample("D").ffill()
+ tm.assert_series_equal(rdf["a"], exp)
+
+ rng = period_range("2000", "2003", freq="A-DEC")
+ ts = Series([1, 2, 3, 4], index=rng)
+
+ result = ts.resample("M").ffill()
+ ex_index = period_range("2000-01", "2003-12", freq="M")
+
+ expected = ts.asfreq("M", how="start").reindex(ex_index, method="ffill")
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("month", MONTHS)
+ @pytest.mark.parametrize("target", ["D", "B", "M"])
+ @pytest.mark.parametrize("convention", ["start", "end"])
+ def test_quarterly_upsample(
+ self, month, target, convention, simple_period_range_series
+ ):
+ freq = f"Q-{month}"
+ ts = simple_period_range_series("1/1/1990", "12/31/1995", freq=freq)
+ warn = FutureWarning if target == "B" else None
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = ts.resample(target, convention=convention).ffill()
+ expected = result.to_timestamp(target, how=convention)
+ expected = expected.asfreq(target, "ffill").to_period()
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("target", ["D", "B"])
+ @pytest.mark.parametrize("convention", ["start", "end"])
+ def test_monthly_upsample(self, target, convention, simple_period_range_series):
+ ts = simple_period_range_series("1/1/1990", "12/31/1995", freq="M")
+
+ warn = None if target == "D" else FutureWarning
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = ts.resample(target, convention=convention).ffill()
+ expected = result.to_timestamp(target, how=convention)
+ expected = expected.asfreq(target, "ffill").to_period()
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_basic(self):
+ # GH3609
+ s = Series(
+ range(100),
+ index=date_range("20130101", freq="s", periods=100, name="idx"),
+ dtype="float",
+ )
+ s[10:30] = np.nan
+ index = PeriodIndex(
+ [Period("2013-01-01 00:00", "T"), Period("2013-01-01 00:01", "T")],
+ name="idx",
+ )
+ expected = Series([34.5, 79.5], index=index)
+ result = s.to_period().resample("T", kind="period").mean()
+ tm.assert_series_equal(result, expected)
+ result2 = s.resample("T", kind="period").mean()
+ tm.assert_series_equal(result2, expected)
+
+ @pytest.mark.parametrize(
+ "freq,expected_vals", [("M", [31, 29, 31, 9]), ("2M", [31 + 29, 31 + 9])]
+ )
+ def test_resample_count(self, freq, expected_vals):
+ # GH12774
+ series = Series(1, index=period_range(start="2000", periods=100))
+ result = series.resample(freq).count()
+ expected_index = period_range(
+ start="2000", freq=freq, periods=len(expected_vals)
+ )
+ expected = Series(expected_vals, index=expected_index)
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_same_freq(self, resample_method):
+ # GH12770
+ series = Series(range(3), index=period_range(start="2000", periods=3, freq="M"))
+ expected = series
+
+ result = getattr(series.resample("M"), resample_method)()
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_incompat_freq(self):
+ msg = (
+ "Frequency cannot be resampled to , "
+ "as they are not sub or super periods"
+ )
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ Series(
+ range(3), index=period_range(start="2000", periods=3, freq="M")
+ ).resample("W").mean()
+
+ def test_with_local_timezone_pytz(self):
+ # see gh-5430
+ local_timezone = pytz.timezone("America/Los_Angeles")
+
+ start = datetime(year=2013, month=11, day=1, hour=0, minute=0, tzinfo=pytz.utc)
+ # 1 day later
+ end = datetime(year=2013, month=11, day=2, hour=0, minute=0, tzinfo=pytz.utc)
+
+ index = date_range(start, end, freq="H")
+
+ series = Series(1, index=index)
+ series = series.tz_convert(local_timezone)
+ result = series.resample("D", kind="period").mean()
+
+ # Create the expected series
+ # Index is moved back a day with the timezone conversion from UTC to
+ # Pacific
+ expected_index = period_range(start=start, end=end, freq="D") - offsets.Day()
+ expected = Series(1.0, index=expected_index)
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_with_pytz(self):
+ # GH 13238
+ s = Series(
+ 2, index=date_range("2017-01-01", periods=48, freq="H", tz="US/Eastern")
+ )
+ result = s.resample("D").mean()
+ expected = Series(
+ 2.0,
+ index=pd.DatetimeIndex(
+ ["2017-01-01", "2017-01-02"], tz="US/Eastern", freq="D"
+ ),
+ )
+ tm.assert_series_equal(result, expected)
+ # Especially assert that the timezone is LMT for pytz
+ assert result.index.tz == pytz.timezone("US/Eastern")
+
+ def test_with_local_timezone_dateutil(self):
+ # see gh-5430
+ local_timezone = "dateutil/America/Los_Angeles"
+
+ start = datetime(
+ year=2013, month=11, day=1, hour=0, minute=0, tzinfo=dateutil.tz.tzutc()
+ )
+ # 1 day later
+ end = datetime(
+ year=2013, month=11, day=2, hour=0, minute=0, tzinfo=dateutil.tz.tzutc()
+ )
+
+ index = date_range(start, end, freq="H", name="idx")
+
+ series = Series(1, index=index)
+ series = series.tz_convert(local_timezone)
+ result = series.resample("D", kind="period").mean()
+
+ # Create the expected series
+ # Index is moved back a day with the timezone conversion from UTC to
+ # Pacific
+ expected_index = (
+ period_range(start=start, end=end, freq="D", name="idx") - offsets.Day()
+ )
+ expected = Series(1.0, index=expected_index)
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_nonexistent_time_bin_edge(self):
+ # GH 19375
+ index = date_range("2017-03-12", "2017-03-12 1:45:00", freq="15T")
+ s = Series(np.zeros(len(index)), index=index)
+ expected = s.tz_localize("US/Pacific")
+ expected.index = pd.DatetimeIndex(expected.index, freq="900S")
+ result = expected.resample("900S").mean()
+ tm.assert_series_equal(result, expected)
+
+ # GH 23742
+ index = date_range(start="2017-10-10", end="2017-10-20", freq="1H")
+ index = index.tz_localize("UTC").tz_convert("America/Sao_Paulo")
+ df = DataFrame(data=list(range(len(index))), index=index)
+ result = df.groupby(pd.Grouper(freq="1D")).count()
+ expected = date_range(
+ start="2017-10-09",
+ end="2017-10-20",
+ freq="D",
+ tz="America/Sao_Paulo",
+ nonexistent="shift_forward",
+ inclusive="left",
+ )
+ tm.assert_index_equal(result.index, expected)
+
+ def test_resample_ambiguous_time_bin_edge(self):
+ # GH 10117
+ idx = date_range(
+ "2014-10-25 22:00:00", "2014-10-26 00:30:00", freq="30T", tz="Europe/London"
+ )
+ expected = Series(np.zeros(len(idx)), index=idx)
+ result = expected.resample("30T").mean()
+ tm.assert_series_equal(result, expected)
+
+ def test_fill_method_and_how_upsample(self):
+ # GH2073
+ s = Series(
+ np.arange(9, dtype="int64"),
+ index=date_range("2010-01-01", periods=9, freq="Q"),
+ )
+ last = s.resample("M").ffill()
+ both = s.resample("M").ffill().resample("M").last().astype("int64")
+ tm.assert_series_equal(last, both)
+
+ @pytest.mark.parametrize("day", DAYS)
+ @pytest.mark.parametrize("target", ["D", "B"])
+ @pytest.mark.parametrize("convention", ["start", "end"])
+ def test_weekly_upsample(self, day, target, convention, simple_period_range_series):
+ freq = f"W-{day}"
+ ts = simple_period_range_series("1/1/1990", "12/31/1995", freq=freq)
+
+ warn = None if target == "D" else FutureWarning
+ msg = r"PeriodDtype\[B\] is deprecated"
+ with tm.assert_produces_warning(warn, match=msg):
+ result = ts.resample(target, convention=convention).ffill()
+ expected = result.to_timestamp(target, how=convention)
+ expected = expected.asfreq(target, "ffill").to_period()
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_to_timestamps(self, simple_period_range_series):
+ ts = simple_period_range_series("1/1/1990", "12/31/1995", freq="M")
+
+ result = ts.resample("A-DEC", kind="timestamp").mean()
+ expected = ts.to_timestamp(how="start").resample("A-DEC").mean()
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("month", MONTHS)
+ def test_resample_to_quarterly(self, simple_period_range_series, month):
+ ts = simple_period_range_series("1990", "1992", freq=f"A-{month}")
+ quar_ts = ts.resample(f"Q-{month}").ffill()
+
+ stamps = ts.to_timestamp("D", how="start")
+ qdates = period_range(
+ ts.index[0].asfreq("D", "start"),
+ ts.index[-1].asfreq("D", "end"),
+ freq=f"Q-{month}",
+ )
+
+ expected = stamps.reindex(qdates.to_timestamp("D", "s"), method="ffill")
+ expected.index = qdates
+
+ tm.assert_series_equal(quar_ts, expected)
+
+ @pytest.mark.parametrize("how", ["start", "end"])
+ def test_resample_to_quarterly_start_end(self, simple_period_range_series, how):
+ # conforms, but different month
+ ts = simple_period_range_series("1990", "1992", freq="A-JUN")
+ result = ts.resample("Q-MAR", convention=how).ffill()
+ expected = ts.asfreq("Q-MAR", how=how)
+ expected = expected.reindex(result.index, method="ffill")
+
+ # .to_timestamp('D')
+ # expected = expected.resample('Q-MAR').ffill()
+
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_fill_missing(self):
+ rng = PeriodIndex([2000, 2005, 2007, 2009], freq="A")
+
+ s = Series(np.random.default_rng(2).standard_normal(4), index=rng)
+
+ stamps = s.to_timestamp()
+ filled = s.resample("A").ffill()
+ expected = stamps.resample("A").ffill().to_period("A")
+ tm.assert_series_equal(filled, expected)
+
+ def test_cant_fill_missing_dups(self):
+ rng = PeriodIndex([2000, 2005, 2005, 2007, 2007], freq="A")
+ s = Series(np.random.default_rng(2).standard_normal(5), index=rng)
+ msg = "Reindexing only valid with uniquely valued Index objects"
+ with pytest.raises(InvalidIndexError, match=msg):
+ s.resample("A").ffill()
+
+ @pytest.mark.parametrize("freq", ["5min"])
+ @pytest.mark.parametrize("kind", ["period", None, "timestamp"])
+ def test_resample_5minute(self, freq, kind):
+ rng = period_range("1/1/2000", "1/5/2000", freq="T")
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+ expected = ts.to_timestamp().resample(freq).mean()
+ if kind != "timestamp":
+ expected = expected.to_period(freq)
+ result = ts.resample(freq, kind=kind).mean()
+ tm.assert_series_equal(result, expected)
+
+ def test_upsample_daily_business_daily(self, simple_period_range_series):
+ ts = simple_period_range_series("1/1/2000", "2/1/2000", freq="B")
+
+ result = ts.resample("D").asfreq()
+ expected = ts.asfreq("D").reindex(period_range("1/3/2000", "2/1/2000"))
+ tm.assert_series_equal(result, expected)
+
+ ts = simple_period_range_series("1/1/2000", "2/1/2000")
+ result = ts.resample("H", convention="s").asfreq()
+ exp_rng = period_range("1/1/2000", "2/1/2000 23:00", freq="H")
+ expected = ts.asfreq("H", how="s").reindex(exp_rng)
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_irregular_sparse(self):
+ dr = date_range(start="1/1/2012", freq="5min", periods=1000)
+ s = Series(np.array(100), index=dr)
+ # subset the data.
+ subset = s[:"2012-01-04 06:55"]
+
+ result = subset.resample("10min").apply(len)
+ expected = s.resample("10min").apply(len).loc[result.index]
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_weekly_all_na(self):
+ rng = date_range("1/1/2000", periods=10, freq="W-WED")
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ result = ts.resample("W-THU").asfreq()
+
+ assert result.isna().all()
+
+ result = ts.resample("W-THU").asfreq().ffill()[:-1]
+ expected = ts.asfreq("W-THU").ffill()
+ tm.assert_series_equal(result, expected)
+
+ def test_resample_tz_localized(self):
+ dr = date_range(start="2012-4-13", end="2012-5-1")
+ ts = Series(range(len(dr)), index=dr)
+
+ ts_utc = ts.tz_localize("UTC")
+ ts_local = ts_utc.tz_convert("America/Los_Angeles")
+
+ result = ts_local.resample("W").mean()
+
+ ts_local_naive = ts_local.copy()
+ ts_local_naive.index = [
+ x.replace(tzinfo=None) for x in ts_local_naive.index.to_pydatetime()
+ ]
+
+ exp = ts_local_naive.resample("W").mean().tz_localize("America/Los_Angeles")
+ exp.index = pd.DatetimeIndex(exp.index, freq="W")
+
+ tm.assert_series_equal(result, exp)
+
+ # it works
+ result = ts_local.resample("D").mean()
+
+ # #2245
+ idx = date_range(
+ "2001-09-20 15:59", "2001-09-20 16:00", freq="T", tz="Australia/Sydney"
+ )
+ s = Series([1, 2], index=idx)
+
+ result = s.resample("D", closed="right", label="right").mean()
+ ex_index = date_range("2001-09-21", periods=1, freq="D", tz="Australia/Sydney")
+ expected = Series([1.5], index=ex_index)
+
+ tm.assert_series_equal(result, expected)
+
+ # for good measure
+ result = s.resample("D", kind="period").mean()
+ ex_index = period_range("2001-09-20", periods=1, freq="D")
+ expected = Series([1.5], index=ex_index)
+ tm.assert_series_equal(result, expected)
+
+ # GH 6397
+ # comparing an offset that doesn't propagate tz's
+ rng = date_range("1/1/2011", periods=20000, freq="H")
+ rng = rng.tz_localize("EST")
+ ts = DataFrame(index=rng)
+ ts["first"] = np.random.default_rng(2).standard_normal(len(rng))
+ ts["second"] = np.cumsum(np.random.default_rng(2).standard_normal(len(rng)))
+ expected = DataFrame(
+ {
+ "first": ts.resample("A").sum()["first"],
+ "second": ts.resample("A").mean()["second"],
+ },
+ columns=["first", "second"],
+ )
+ result = (
+ ts.resample("A")
+ .agg({"first": "sum", "second": "mean"})
+ .reindex(columns=["first", "second"])
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_closed_left_corner(self):
+ # #1465
+ s = Series(
+ np.random.default_rng(2).standard_normal(21),
+ index=date_range(start="1/1/2012 9:30", freq="1min", periods=21),
+ )
+ s.iloc[0] = np.nan
+
+ result = s.resample("10min", closed="left", label="right").mean()
+ exp = s[1:].resample("10min", closed="left", label="right").mean()
+ tm.assert_series_equal(result, exp)
+
+ result = s.resample("10min", closed="left", label="left").mean()
+ exp = s[1:].resample("10min", closed="left", label="left").mean()
+
+ ex_index = date_range(start="1/1/2012 9:30", freq="10min", periods=3)
+
+ tm.assert_index_equal(result.index, ex_index)
+ tm.assert_series_equal(result, exp)
+
+ def test_quarterly_resampling(self):
+ rng = period_range("2000Q1", periods=10, freq="Q-DEC")
+ ts = Series(np.arange(10), index=rng)
+
+ result = ts.resample("A").mean()
+ exp = ts.to_timestamp().resample("A").mean().to_period()
+ tm.assert_series_equal(result, exp)
+
+ def test_resample_weekly_bug_1726(self):
+ # 8/6/12 is a Monday
+ ind = date_range(start="8/6/2012", end="8/26/2012", freq="D")
+ n = len(ind)
+ data = [[x] * 5 for x in range(n)]
+ df = DataFrame(data, columns=["open", "high", "low", "close", "vol"], index=ind)
+
+ # it works!
+ df.resample("W-MON", closed="left", label="left").first()
+
+ def test_resample_with_dst_time_change(self):
+ # GH 15549
+ index = (
+ pd.DatetimeIndex([1457537600000000000, 1458059600000000000])
+ .tz_localize("UTC")
+ .tz_convert("America/Chicago")
+ )
+ df = DataFrame([1, 2], index=index)
+ result = df.resample("12h", closed="right", label="right").last().ffill()
+
+ expected_index_values = [
+ "2016-03-09 12:00:00-06:00",
+ "2016-03-10 00:00:00-06:00",
+ "2016-03-10 12:00:00-06:00",
+ "2016-03-11 00:00:00-06:00",
+ "2016-03-11 12:00:00-06:00",
+ "2016-03-12 00:00:00-06:00",
+ "2016-03-12 12:00:00-06:00",
+ "2016-03-13 00:00:00-06:00",
+ "2016-03-13 13:00:00-05:00",
+ "2016-03-14 01:00:00-05:00",
+ "2016-03-14 13:00:00-05:00",
+ "2016-03-15 01:00:00-05:00",
+ "2016-03-15 13:00:00-05:00",
+ ]
+ index = pd.to_datetime(expected_index_values, utc=True).tz_convert(
+ "America/Chicago"
+ )
+ index = pd.DatetimeIndex(index, freq="12h")
+ expected = DataFrame(
+ [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0],
+ index=index,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_resample_bms_2752(self):
+ # GH2753
+ timeseries = Series(
+ index=pd.bdate_range("20000101", "20000201"), dtype=np.float64
+ )
+ res1 = timeseries.resample("BMS").mean()
+ res2 = timeseries.resample("BMS").mean().resample("B").mean()
+ assert res1.index[0] == Timestamp("20000103")
+ assert res1.index[0] == res2.index[0]
+
+ @pytest.mark.xfail(reason="Commented out for more than 3 years. Should this work?")
+ def test_monthly_convention_span(self):
+ rng = period_range("2000-01", periods=3, freq="M")
+ ts = Series(np.arange(3), index=rng)
+
+ # hacky way to get same thing
+ exp_index = period_range("2000-01-01", "2000-03-31", freq="D")
+ expected = ts.asfreq("D", how="end").reindex(exp_index)
+ expected = expected.fillna(method="bfill")
+
+ result = ts.resample("D").mean()
+
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "from_freq, to_freq", [("D", "M"), ("Q", "A"), ("M", "Q"), ("D", "W")]
+ )
+ def test_default_right_closed_label(self, from_freq, to_freq):
+ idx = date_range(start="8/15/2012", periods=100, freq=from_freq)
+ df = DataFrame(np.random.default_rng(2).standard_normal((len(idx), 2)), idx)
+
+ resampled = df.resample(to_freq).mean()
+ tm.assert_frame_equal(
+ resampled, df.resample(to_freq, closed="right", label="right").mean()
+ )
+
+ @pytest.mark.parametrize(
+ "from_freq, to_freq",
+ [("D", "MS"), ("Q", "AS"), ("M", "QS"), ("H", "D"), ("T", "H")],
+ )
+ def test_default_left_closed_label(self, from_freq, to_freq):
+ idx = date_range(start="8/15/2012", periods=100, freq=from_freq)
+ df = DataFrame(np.random.default_rng(2).standard_normal((len(idx), 2)), idx)
+
+ resampled = df.resample(to_freq).mean()
+ tm.assert_frame_equal(
+ resampled, df.resample(to_freq, closed="left", label="left").mean()
+ )
+
+ def test_all_values_single_bin(self):
+ # 2070
+ index = period_range(start="2012-01-01", end="2012-12-31", freq="M")
+ s = Series(np.random.default_rng(2).standard_normal(len(index)), index=index)
+
+ result = s.resample("A").mean()
+ tm.assert_almost_equal(result.iloc[0], s.mean())
+
+ def test_evenly_divisible_with_no_extra_bins(self):
+ # 4076
+ # when the frequency is evenly divisible, sometimes extra bins
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((9, 3)),
+ index=date_range("2000-1-1", periods=9),
+ )
+ result = df.resample("5D").mean()
+ expected = pd.concat([df.iloc[0:5].mean(), df.iloc[5:].mean()], axis=1).T
+ expected.index = pd.DatetimeIndex(
+ [Timestamp("2000-1-1"), Timestamp("2000-1-6")], freq="5D"
+ )
+ tm.assert_frame_equal(result, expected)
+
+ index = date_range(start="2001-5-4", periods=28)
+ df = DataFrame(
+ [
+ {
+ "REST_KEY": 1,
+ "DLY_TRN_QT": 80,
+ "DLY_SLS_AMT": 90,
+ "COOP_DLY_TRN_QT": 30,
+ "COOP_DLY_SLS_AMT": 20,
+ }
+ ]
+ * 28
+ + [
+ {
+ "REST_KEY": 2,
+ "DLY_TRN_QT": 70,
+ "DLY_SLS_AMT": 10,
+ "COOP_DLY_TRN_QT": 50,
+ "COOP_DLY_SLS_AMT": 20,
+ }
+ ]
+ * 28,
+ index=index.append(index),
+ ).sort_index()
+
+ index = date_range("2001-5-4", periods=4, freq="7D")
+ expected = DataFrame(
+ [
+ {
+ "REST_KEY": 14,
+ "DLY_TRN_QT": 14,
+ "DLY_SLS_AMT": 14,
+ "COOP_DLY_TRN_QT": 14,
+ "COOP_DLY_SLS_AMT": 14,
+ }
+ ]
+ * 4,
+ index=index,
+ )
+ result = df.resample("7D").count()
+ tm.assert_frame_equal(result, expected)
+
+ expected = DataFrame(
+ [
+ {
+ "REST_KEY": 21,
+ "DLY_TRN_QT": 1050,
+ "DLY_SLS_AMT": 700,
+ "COOP_DLY_TRN_QT": 560,
+ "COOP_DLY_SLS_AMT": 280,
+ }
+ ]
+ * 4,
+ index=index,
+ )
+ result = df.resample("7D").sum()
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("freq, period_mult", [("H", 24), ("12H", 2)])
+ @pytest.mark.parametrize("kind", [None, "period"])
+ def test_upsampling_ohlc(self, freq, period_mult, kind):
+ # GH 13083
+ pi = period_range(start="2000", freq="D", periods=10)
+ s = Series(range(len(pi)), index=pi)
+ expected = s.to_timestamp().resample(freq).ohlc().to_period(freq)
+
+ # timestamp-based resampling doesn't include all sub-periods
+ # of the last original period, so extend accordingly:
+ new_index = period_range(start="2000", freq=freq, periods=period_mult * len(pi))
+ expected = expected.reindex(new_index)
+ result = s.resample(freq, kind=kind).ohlc()
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "periods, values",
+ [
+ (
+ [
+ pd.NaT,
+ "1970-01-01 00:00:00",
+ pd.NaT,
+ "1970-01-01 00:00:02",
+ "1970-01-01 00:00:03",
+ ],
+ [2, 3, 5, 7, 11],
+ ),
+ (
+ [
+ pd.NaT,
+ pd.NaT,
+ "1970-01-01 00:00:00",
+ pd.NaT,
+ pd.NaT,
+ pd.NaT,
+ "1970-01-01 00:00:02",
+ "1970-01-01 00:00:03",
+ pd.NaT,
+ pd.NaT,
+ ],
+ [1, 2, 3, 5, 6, 8, 7, 11, 12, 13],
+ ),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "freq, expected_values",
+ [
+ ("1s", [3, np.nan, 7, 11]),
+ ("2s", [3, (7 + 11) / 2]),
+ ("3s", [(3 + 7) / 2, 11]),
+ ],
+ )
+ def test_resample_with_nat(self, periods, values, freq, expected_values):
+ # GH 13224
+ index = PeriodIndex(periods, freq="S")
+ frame = DataFrame(values, index=index)
+
+ expected_index = period_range(
+ "1970-01-01 00:00:00", periods=len(expected_values), freq=freq
+ )
+ expected = DataFrame(expected_values, index=expected_index)
+ result = frame.resample(freq).mean()
+ tm.assert_frame_equal(result, expected)
+
+ def test_resample_with_only_nat(self):
+ # GH 13224
+ pi = PeriodIndex([pd.NaT] * 3, freq="S")
+ frame = DataFrame([2, 3, 5], index=pi, columns=["a"])
+ expected_index = PeriodIndex(data=[], freq=pi.freq)
+ expected = DataFrame(index=expected_index, columns=["a"], dtype="float64")
+ result = frame.resample("1s").mean()
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "start,end,start_freq,end_freq,offset",
+ [
+ ("19910905", "19910909 03:00", "H", "24H", "10H"),
+ ("19910905", "19910909 12:00", "H", "24H", "10H"),
+ ("19910905", "19910909 23:00", "H", "24H", "10H"),
+ ("19910905 10:00", "19910909", "H", "24H", "10H"),
+ ("19910905 10:00", "19910909 10:00", "H", "24H", "10H"),
+ ("19910905", "19910909 10:00", "H", "24H", "10H"),
+ ("19910905 12:00", "19910909", "H", "24H", "10H"),
+ ("19910905 12:00", "19910909 03:00", "H", "24H", "10H"),
+ ("19910905 12:00", "19910909 12:00", "H", "24H", "10H"),
+ ("19910905 12:00", "19910909 12:00", "H", "24H", "34H"),
+ ("19910905 12:00", "19910909 12:00", "H", "17H", "10H"),
+ ("19910905 12:00", "19910909 12:00", "H", "17H", "3H"),
+ ("19910905 12:00", "19910909 1:00", "H", "M", "3H"),
+ ("19910905", "19910913 06:00", "2H", "24H", "10H"),
+ ("19910905", "19910905 01:39", "Min", "5Min", "3Min"),
+ ("19910905", "19910905 03:18", "2Min", "5Min", "3Min"),
+ ],
+ )
+ def test_resample_with_offset(self, start, end, start_freq, end_freq, offset):
+ # GH 23882 & 31809
+ pi = period_range(start, end, freq=start_freq)
+ ser = Series(np.arange(len(pi)), index=pi)
+ result = ser.resample(end_freq, offset=offset).mean()
+ result = result.to_timestamp(end_freq)
+
+ expected = ser.to_timestamp().resample(end_freq, offset=offset).mean()
+ if end_freq == "M":
+ # TODO: is non-tick the relevant characteristic? (GH 33815)
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "first,last,freq,exp_first,exp_last",
+ [
+ ("19910905", "19920406", "D", "19910905", "19920406"),
+ ("19910905 00:00", "19920406 06:00", "D", "19910905", "19920406"),
+ (
+ "19910905 06:00",
+ "19920406 06:00",
+ "H",
+ "19910905 06:00",
+ "19920406 06:00",
+ ),
+ ("19910906", "19920406", "M", "1991-09", "1992-04"),
+ ("19910831", "19920430", "M", "1991-08", "1992-04"),
+ ("1991-08", "1992-04", "M", "1991-08", "1992-04"),
+ ],
+ )
+ def test_get_period_range_edges(self, first, last, freq, exp_first, exp_last):
+ first = Period(first)
+ last = Period(last)
+
+ exp_first = Period(exp_first, freq=freq)
+ exp_last = Period(exp_last, freq=freq)
+
+ freq = pd.tseries.frequencies.to_offset(freq)
+ result = _get_period_range_edges(first, last, freq)
+ expected = (exp_first, exp_last)
+ assert result == expected
+
+ def test_sum_min_count(self):
+ # GH 19974
+ index = date_range(start="2018", freq="M", periods=6)
+ data = np.ones(6)
+ data[3:6] = np.nan
+ s = Series(data, index).to_period()
+ result = s.resample("Q").sum(min_count=1)
+ expected = Series(
+ [3.0, np.nan], index=PeriodIndex(["2018Q1", "2018Q2"], freq="Q-DEC")
+ )
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_resample_api.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_resample_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cfcf555355b539a7fddb2f990a2ce39f9cfb116
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_resample_api.py
@@ -0,0 +1,1063 @@
+from datetime import datetime
+import re
+
+import numpy as np
+import pytest
+
+from pandas._libs import lib
+from pandas.errors import UnsupportedFunctionCall
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ NamedAgg,
+ Series,
+)
+import pandas._testing as tm
+from pandas.core.indexes.datetimes import date_range
+
+
+@pytest.fixture
+def dti():
+ return date_range(start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq="Min")
+
+
+@pytest.fixture
+def _test_series(dti):
+ return Series(np.random.default_rng(2).random(len(dti)), dti)
+
+
+@pytest.fixture
+def test_frame(dti, _test_series):
+ return DataFrame({"A": _test_series, "B": _test_series, "C": np.arange(len(dti))})
+
+
+def test_str(_test_series):
+ r = _test_series.resample("H")
+ assert (
+ "DatetimeIndexResampler [freq=, axis=0, closed=left, "
+ "label=left, convention=start, origin=start_day]" in str(r)
+ )
+
+ r = _test_series.resample("H", origin="2000-01-01")
+ assert (
+ "DatetimeIndexResampler [freq=, axis=0, closed=left, "
+ "label=left, convention=start, origin=2000-01-01 00:00:00]" in str(r)
+ )
+
+
+def test_api(_test_series):
+ r = _test_series.resample("H")
+ result = r.mean()
+ assert isinstance(result, Series)
+ assert len(result) == 217
+
+ r = _test_series.to_frame().resample("H")
+ result = r.mean()
+ assert isinstance(result, DataFrame)
+ assert len(result) == 217
+
+
+def test_groupby_resample_api():
+ # GH 12448
+ # .groupby(...).resample(...) hitting warnings
+ # when appropriate
+ df = DataFrame(
+ {
+ "date": date_range(start="2016-01-01", periods=4, freq="W"),
+ "group": [1, 1, 2, 2],
+ "val": [5, 6, 7, 8],
+ }
+ ).set_index("date")
+
+ # replication step
+ i = (
+ date_range("2016-01-03", periods=8).tolist()
+ + date_range("2016-01-17", periods=8).tolist()
+ )
+ index = pd.MultiIndex.from_arrays([[1] * 8 + [2] * 8, i], names=["group", "date"])
+ expected = DataFrame({"val": [5] * 7 + [6] + [7] * 7 + [8]}, index=index)
+ result = df.groupby("group").apply(lambda x: x.resample("1D").ffill())[["val"]]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_resample_on_api():
+ # GH 15021
+ # .groupby(...).resample(on=...) results in an unexpected
+ # keyword warning.
+ df = DataFrame(
+ {
+ "key": ["A", "B"] * 5,
+ "dates": date_range("2016-01-01", periods=10),
+ "values": np.random.default_rng(2).standard_normal(10),
+ }
+ )
+
+ expected = df.set_index("dates").groupby("key").resample("D").mean()
+ result = df.groupby("key").resample("D", on="dates").mean()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_group_keys():
+ df = DataFrame({"A": 1, "B": 2}, index=date_range("2000", periods=10))
+ expected = df.copy()
+
+ # group_keys=False
+ g = df.resample("5D", group_keys=False)
+ result = g.apply(lambda x: x)
+ tm.assert_frame_equal(result, expected)
+
+ # group_keys defaults to False
+ g = df.resample("5D")
+ result = g.apply(lambda x: x)
+ tm.assert_frame_equal(result, expected)
+
+ # group_keys=True
+ expected.index = pd.MultiIndex.from_arrays(
+ [pd.to_datetime(["2000-01-01", "2000-01-06"]).repeat(5), expected.index]
+ )
+ g = df.resample("5D", group_keys=True)
+ result = g.apply(lambda x: x)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_pipe(test_frame, _test_series):
+ # GH17905
+
+ # series
+ r = _test_series.resample("H")
+ expected = r.max() - r.mean()
+ result = r.pipe(lambda x: x.max() - x.mean())
+ tm.assert_series_equal(result, expected)
+
+ # dataframe
+ r = test_frame.resample("H")
+ expected = r.max() - r.mean()
+ result = r.pipe(lambda x: x.max() - x.mean())
+ tm.assert_frame_equal(result, expected)
+
+
+def test_getitem(test_frame):
+ r = test_frame.resample("H")
+ tm.assert_index_equal(r._selected_obj.columns, test_frame.columns)
+
+ r = test_frame.resample("H")["B"]
+ assert r._selected_obj.name == test_frame.columns[1]
+
+ # technically this is allowed
+ r = test_frame.resample("H")["A", "B"]
+ tm.assert_index_equal(r._selected_obj.columns, test_frame.columns[[0, 1]])
+
+ r = test_frame.resample("H")["A", "B"]
+ tm.assert_index_equal(r._selected_obj.columns, test_frame.columns[[0, 1]])
+
+
+@pytest.mark.parametrize("key", [["D"], ["A", "D"]])
+def test_select_bad_cols(key, test_frame):
+ g = test_frame.resample("H")
+ # 'A' should not be referenced as a bad column...
+ # will have to rethink regex if you change message!
+ msg = r"^\"Columns not found: 'D'\"$"
+ with pytest.raises(KeyError, match=msg):
+ g[key]
+
+
+def test_attribute_access(test_frame):
+ r = test_frame.resample("H")
+ tm.assert_series_equal(r.A.sum(), r["A"].sum())
+
+
+@pytest.mark.parametrize("attr", ["groups", "ngroups", "indices"])
+def test_api_compat_before_use(attr):
+ # make sure that we are setting the binner
+ # on these attributes
+ rng = date_range("1/1/2012", periods=100, freq="S")
+ ts = Series(np.arange(len(rng)), index=rng)
+ rs = ts.resample("30s")
+
+ # before use
+ getattr(rs, attr)
+
+ # after grouper is initialized is ok
+ rs.mean()
+ getattr(rs, attr)
+
+
+def tests_raises_on_nuisance(test_frame):
+ df = test_frame
+ df["D"] = "foo"
+ r = df.resample("H")
+ result = r[["A", "B"]].mean()
+ expected = pd.concat([r.A.mean(), r.B.mean()], axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ expected = r[["A", "B", "C"]].mean()
+ msg = re.escape("agg function failed [how->mean,dtype->object]")
+ with pytest.raises(TypeError, match=msg):
+ r.mean()
+ result = r.mean(numeric_only=True)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_downsample_but_actually_upsampling():
+ # this is reindex / asfreq
+ rng = date_range("1/1/2012", periods=100, freq="S")
+ ts = Series(np.arange(len(rng), dtype="int64"), index=rng)
+ result = ts.resample("20s").asfreq()
+ expected = Series(
+ [0, 20, 40, 60, 80],
+ index=date_range("2012-01-01 00:00:00", freq="20s", periods=5),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_combined_up_downsampling_of_irregular():
+ # since we are really doing an operation like this
+ # ts2.resample('2s').mean().ffill()
+ # preserve these semantics
+
+ rng = date_range("1/1/2012", periods=100, freq="S")
+ ts = Series(np.arange(len(rng)), index=rng)
+ ts2 = ts.iloc[[0, 1, 2, 3, 5, 7, 11, 15, 16, 25, 30]]
+
+ result = ts2.resample("2s").mean().ffill()
+ expected = Series(
+ [
+ 0.5,
+ 2.5,
+ 5.0,
+ 7.0,
+ 7.0,
+ 11.0,
+ 11.0,
+ 15.0,
+ 16.0,
+ 16.0,
+ 16.0,
+ 16.0,
+ 25.0,
+ 25.0,
+ 25.0,
+ 30.0,
+ ],
+ index=pd.DatetimeIndex(
+ [
+ "2012-01-01 00:00:00",
+ "2012-01-01 00:00:02",
+ "2012-01-01 00:00:04",
+ "2012-01-01 00:00:06",
+ "2012-01-01 00:00:08",
+ "2012-01-01 00:00:10",
+ "2012-01-01 00:00:12",
+ "2012-01-01 00:00:14",
+ "2012-01-01 00:00:16",
+ "2012-01-01 00:00:18",
+ "2012-01-01 00:00:20",
+ "2012-01-01 00:00:22",
+ "2012-01-01 00:00:24",
+ "2012-01-01 00:00:26",
+ "2012-01-01 00:00:28",
+ "2012-01-01 00:00:30",
+ ],
+ dtype="datetime64[ns]",
+ freq="2S",
+ ),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_transform_series(_test_series):
+ r = _test_series.resample("20min")
+ expected = _test_series.groupby(pd.Grouper(freq="20min")).transform("mean")
+ result = r.transform("mean")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("on", [None, "date"])
+def test_transform_frame(on):
+ # GH#47079
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
+ index.name = "date"
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
+ )
+ expected = df.groupby(pd.Grouper(freq="20min")).transform("mean")
+ if on == "date":
+ # Move date to being a column; result will then have a RangeIndex
+ expected = expected.reset_index(drop=True)
+ df = df.reset_index()
+
+ r = df.resample("20min", on=on)
+ result = r.transform("mean")
+ tm.assert_frame_equal(result, expected)
+
+
+def test_fillna():
+ # need to upsample here
+ rng = date_range("1/1/2012", periods=10, freq="2S")
+ ts = Series(np.arange(len(rng), dtype="int64"), index=rng)
+ r = ts.resample("s")
+
+ expected = r.ffill()
+ msg = "DatetimeIndexResampler.fillna is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = r.fillna(method="ffill")
+ tm.assert_series_equal(result, expected)
+
+ expected = r.bfill()
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = r.fillna(method="bfill")
+ tm.assert_series_equal(result, expected)
+
+ msg2 = (
+ r"Invalid fill method\. Expecting pad \(ffill\), backfill "
+ r"\(bfill\) or nearest\. Got 0"
+ )
+ with pytest.raises(ValueError, match=msg2):
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ r.fillna(0)
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ lambda x: x.resample("20min", group_keys=False),
+ lambda x: x.groupby(pd.Grouper(freq="20min"), group_keys=False),
+ ],
+ ids=["resample", "groupby"],
+)
+def test_apply_without_aggregation(func, _test_series):
+ # both resample and groupby should work w/o aggregation
+ t = func(_test_series)
+ result = t.apply(lambda x: x)
+ tm.assert_series_equal(result, _test_series)
+
+
+def test_apply_without_aggregation2(_test_series):
+ grouped = _test_series.to_frame(name="foo").resample("20min", group_keys=False)
+ result = grouped["foo"].apply(lambda x: x)
+ tm.assert_series_equal(result, _test_series.rename("foo"))
+
+
+def test_agg_consistency():
+ # make sure that we are consistent across
+ # similar aggregations with and w/o selection list
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((1000, 3)),
+ index=date_range("1/1/2012", freq="S", periods=1000),
+ columns=["A", "B", "C"],
+ )
+
+ r = df.resample("3T")
+
+ msg = r"Column\(s\) \['r1', 'r2'\] do not exist"
+ with pytest.raises(KeyError, match=msg):
+ r.agg({"r1": "mean", "r2": "sum"})
+
+
+def test_agg_consistency_int_str_column_mix():
+ # GH#39025
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((1000, 2)),
+ index=date_range("1/1/2012", freq="S", periods=1000),
+ columns=[1, "a"],
+ )
+
+ r = df.resample("3T")
+
+ msg = r"Column\(s\) \[2, 'b'\] do not exist"
+ with pytest.raises(KeyError, match=msg):
+ r.agg({2: "mean", "b": "sum"})
+
+
+# TODO(GH#14008): once GH 14008 is fixed, move these tests into
+# `Base` test class
+
+
+def test_agg():
+ # test with all three Resampler apis and TimeGrouper
+
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
+ index.name = "date"
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
+ )
+ df_col = df.reset_index()
+ df_mult = df_col.copy()
+ df_mult.index = pd.MultiIndex.from_arrays(
+ [range(10), df.index], names=["index", "date"]
+ )
+ r = df.resample("2D")
+ cases = [
+ r,
+ df_col.resample("2D", on="date"),
+ df_mult.resample("2D", level="date"),
+ df.groupby(pd.Grouper(freq="2D")),
+ ]
+
+ a_mean = r["A"].mean()
+ a_std = r["A"].std()
+ a_sum = r["A"].sum()
+ b_mean = r["B"].mean()
+ b_std = r["B"].std()
+ b_sum = r["B"].sum()
+
+ expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1)
+ expected.columns = pd.MultiIndex.from_product([["A", "B"], ["mean", "std"]])
+ msg = "using SeriesGroupBy.[mean|std]"
+ for t in cases:
+ # In case 2, "date" is an index and a column, so get included in the agg
+ if t == cases[2]:
+ date_mean = t["date"].mean()
+ date_std = t["date"].std()
+ exp = pd.concat([date_mean, date_std, expected], axis=1)
+ exp.columns = pd.MultiIndex.from_product(
+ [["date", "A", "B"], ["mean", "std"]]
+ )
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = t.aggregate([np.mean, np.std])
+ tm.assert_frame_equal(result, exp)
+ else:
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = t.aggregate([np.mean, np.std])
+ tm.assert_frame_equal(result, expected)
+
+ expected = pd.concat([a_mean, b_std], axis=1)
+ for t in cases:
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = t.aggregate({"A": np.mean, "B": np.std})
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = t.aggregate(A=("A", np.mean), B=("B", np.std))
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = t.aggregate(A=NamedAgg("A", np.mean), B=NamedAgg("B", np.std))
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+ expected = pd.concat([a_mean, a_std], axis=1)
+ expected.columns = pd.MultiIndex.from_tuples([("A", "mean"), ("A", "std")])
+ for t in cases:
+ result = t.aggregate({"A": ["mean", "std"]})
+ tm.assert_frame_equal(result, expected)
+
+ expected = pd.concat([a_mean, a_sum], axis=1)
+ expected.columns = ["mean", "sum"]
+ for t in cases:
+ result = t["A"].aggregate(["mean", "sum"])
+ tm.assert_frame_equal(result, expected)
+
+ result = t["A"].aggregate(mean="mean", sum="sum")
+ tm.assert_frame_equal(result, expected)
+
+ msg = "nested renamer is not supported"
+ for t in cases:
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
+ t.aggregate({"A": {"mean": "mean", "sum": "sum"}})
+
+ expected = pd.concat([a_mean, a_sum, b_mean, b_sum], axis=1)
+ expected.columns = pd.MultiIndex.from_tuples(
+ [("A", "mean"), ("A", "sum"), ("B", "mean2"), ("B", "sum2")]
+ )
+ for t in cases:
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
+ t.aggregate(
+ {
+ "A": {"mean": "mean", "sum": "sum"},
+ "B": {"mean2": "mean", "sum2": "sum"},
+ }
+ )
+
+ expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1)
+ expected.columns = pd.MultiIndex.from_tuples(
+ [("A", "mean"), ("A", "std"), ("B", "mean"), ("B", "std")]
+ )
+ for t in cases:
+ result = t.aggregate({"A": ["mean", "std"], "B": ["mean", "std"]})
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+ expected = pd.concat([a_mean, a_sum, b_mean, b_sum], axis=1)
+ expected.columns = pd.MultiIndex.from_tuples(
+ [
+ ("r1", "A", "mean"),
+ ("r1", "A", "sum"),
+ ("r2", "B", "mean"),
+ ("r2", "B", "sum"),
+ ]
+ )
+
+
+def test_agg_misc():
+ # test with all three Resampler apis and TimeGrouper
+
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
+ index.name = "date"
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
+ )
+ df_col = df.reset_index()
+ df_mult = df_col.copy()
+ df_mult.index = pd.MultiIndex.from_arrays(
+ [range(10), df.index], names=["index", "date"]
+ )
+
+ r = df.resample("2D")
+ cases = [
+ r,
+ df_col.resample("2D", on="date"),
+ df_mult.resample("2D", level="date"),
+ df.groupby(pd.Grouper(freq="2D")),
+ ]
+
+ # passed lambda
+ msg = "using SeriesGroupBy.sum"
+ for t in cases:
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = t.agg({"A": np.sum, "B": lambda x: np.std(x, ddof=1)})
+ rcustom = t["B"].apply(lambda x: np.std(x, ddof=1))
+ expected = pd.concat([r["A"].sum(), rcustom], axis=1)
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = t.agg(A=("A", np.sum), B=("B", lambda x: np.std(x, ddof=1)))
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = t.agg(
+ A=NamedAgg("A", np.sum), B=NamedAgg("B", lambda x: np.std(x, ddof=1))
+ )
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+ # agg with renamers
+ expected = pd.concat(
+ [t["A"].sum(), t["B"].sum(), t["A"].mean(), t["B"].mean()], axis=1
+ )
+ expected.columns = pd.MultiIndex.from_tuples(
+ [("result1", "A"), ("result1", "B"), ("result2", "A"), ("result2", "B")]
+ )
+
+ msg = r"Column\(s\) \['result1', 'result2'\] do not exist"
+ for t in cases:
+ with pytest.raises(KeyError, match=msg):
+ t[["A", "B"]].agg({"result1": np.sum, "result2": np.mean})
+
+ with pytest.raises(KeyError, match=msg):
+ t[["A", "B"]].agg(A=("result1", np.sum), B=("result2", np.mean))
+
+ with pytest.raises(KeyError, match=msg):
+ t[["A", "B"]].agg(
+ A=NamedAgg("result1", np.sum), B=NamedAgg("result2", np.mean)
+ )
+
+ # agg with different hows
+ expected = pd.concat(
+ [t["A"].sum(), t["A"].std(), t["B"].mean(), t["B"].std()], axis=1
+ )
+ expected.columns = pd.MultiIndex.from_tuples(
+ [("A", "sum"), ("A", "std"), ("B", "mean"), ("B", "std")]
+ )
+ for t in cases:
+ result = t.agg({"A": ["sum", "std"], "B": ["mean", "std"]})
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+ # equivalent of using a selection list / or not
+ for t in cases:
+ result = t[["A", "B"]].agg({"A": ["sum", "std"], "B": ["mean", "std"]})
+ tm.assert_frame_equal(result, expected, check_like=True)
+
+ msg = "nested renamer is not supported"
+
+ # series like aggs
+ for t in cases:
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
+ t["A"].agg({"A": ["sum", "std"]})
+
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
+ t["A"].agg({"A": ["sum", "std"], "B": ["mean", "std"]})
+
+ # errors
+ # invalid names in the agg specification
+ msg = r"Column\(s\) \['B'\] do not exist"
+ for t in cases:
+ with pytest.raises(KeyError, match=msg):
+ t[["A"]].agg({"A": ["sum", "std"], "B": ["mean", "std"]})
+
+
+@pytest.mark.parametrize(
+ "func", [["min"], ["mean", "max"], {"A": "sum"}, {"A": "prod", "B": "median"}]
+)
+def test_multi_agg_axis_1_raises(func):
+ # GH#46904
+
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
+ index.name = "date"
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
+ ).T
+ warning_msg = "DataFrame.resample with axis=1 is deprecated."
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
+ res = df.resample("M", axis=1)
+ with pytest.raises(
+ NotImplementedError, match="axis other than 0 is not supported"
+ ):
+ res.agg(func)
+
+
+def test_agg_nested_dicts():
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
+ index.name = "date"
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
+ )
+ df_col = df.reset_index()
+ df_mult = df_col.copy()
+ df_mult.index = pd.MultiIndex.from_arrays(
+ [range(10), df.index], names=["index", "date"]
+ )
+ r = df.resample("2D")
+ cases = [
+ r,
+ df_col.resample("2D", on="date"),
+ df_mult.resample("2D", level="date"),
+ df.groupby(pd.Grouper(freq="2D")),
+ ]
+
+ msg = "nested renamer is not supported"
+ for t in cases:
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
+ t.aggregate({"r1": {"A": ["mean", "sum"]}, "r2": {"B": ["mean", "sum"]}})
+
+ for t in cases:
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
+ t[["A", "B"]].agg(
+ {"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}}
+ )
+
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
+ t.agg({"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}})
+
+
+def test_try_aggregate_non_existing_column():
+ # GH 16766
+ data = [
+ {"dt": datetime(2017, 6, 1, 0), "x": 1.0, "y": 2.0},
+ {"dt": datetime(2017, 6, 1, 1), "x": 2.0, "y": 2.0},
+ {"dt": datetime(2017, 6, 1, 2), "x": 3.0, "y": 1.5},
+ ]
+ df = DataFrame(data).set_index("dt")
+
+ # Error as we don't have 'z' column
+ msg = r"Column\(s\) \['z'\] do not exist"
+ with pytest.raises(KeyError, match=msg):
+ df.resample("30T").agg({"x": ["mean"], "y": ["median"], "z": ["sum"]})
+
+
+def test_agg_list_like_func_with_args():
+ # 50624
+ df = DataFrame(
+ {"x": [1, 2, 3]}, index=date_range("2020-01-01", periods=3, freq="D")
+ )
+
+ def foo1(x, a=1, c=0):
+ return x + a + c
+
+ def foo2(x, b=2, c=0):
+ return x + b + c
+
+ msg = r"foo1\(\) got an unexpected keyword argument 'b'"
+ with pytest.raises(TypeError, match=msg):
+ df.resample("D").agg([foo1, foo2], 3, b=3, c=4)
+
+ result = df.resample("D").agg([foo1, foo2], 3, c=4)
+ expected = DataFrame(
+ [[8, 8], [9, 9], [10, 10]],
+ index=date_range("2020-01-01", periods=3, freq="D"),
+ columns=pd.MultiIndex.from_tuples([("x", "foo1"), ("x", "foo2")]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_selection_api_validation():
+ # GH 13500
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
+
+ rng = np.arange(len(index), dtype=np.int64)
+ df = DataFrame(
+ {"date": index, "a": rng},
+ index=pd.MultiIndex.from_arrays([rng, index], names=["v", "d"]),
+ )
+ df_exp = DataFrame({"a": rng}, index=index)
+
+ # non DatetimeIndex
+ msg = (
+ "Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, "
+ "but got an instance of 'Index'"
+ )
+ with pytest.raises(TypeError, match=msg):
+ df.resample("2D", level="v")
+
+ msg = "The Grouper cannot specify both a key and a level!"
+ with pytest.raises(ValueError, match=msg):
+ df.resample("2D", on="date", level="d")
+
+ msg = "unhashable type: 'list'"
+ with pytest.raises(TypeError, match=msg):
+ df.resample("2D", on=["a", "date"])
+
+ msg = r"\"Level \['a', 'date'\] not found\""
+ with pytest.raises(KeyError, match=msg):
+ df.resample("2D", level=["a", "date"])
+
+ # upsampling not allowed
+ msg = (
+ "Upsampling from level= or on= selection is not supported, use "
+ r"\.set_index\(\.\.\.\) to explicitly set index to datetime-like"
+ )
+ with pytest.raises(ValueError, match=msg):
+ df.resample("2D", level="d").asfreq()
+ with pytest.raises(ValueError, match=msg):
+ df.resample("2D", on="date").asfreq()
+
+ exp = df_exp.resample("2D").sum()
+ exp.index.name = "date"
+ result = df.resample("2D", on="date").sum()
+ tm.assert_frame_equal(exp, result)
+
+ exp.index.name = "d"
+ with pytest.raises(TypeError, match="datetime64 type does not support sum"):
+ df.resample("2D", level="d").sum()
+ result = df.resample("2D", level="d").sum(numeric_only=True)
+ tm.assert_frame_equal(exp, result)
+
+
+@pytest.mark.parametrize(
+ "col_name", ["t2", "t2x", "t2q", "T_2M", "t2p", "t2m", "t2m1", "T2M"]
+)
+def test_agg_with_datetime_index_list_agg_func(col_name):
+ # GH 22660
+ # The parametrized column names would get converted to dates by our
+ # date parser. Some would result in OutOfBoundsError (ValueError) while
+ # others would result in OverflowError when passed into Timestamp.
+ # We catch these errors and move on to the correct branch.
+ df = DataFrame(
+ list(range(200)),
+ index=date_range(
+ start="2017-01-01", freq="15min", periods=200, tz="Europe/Berlin"
+ ),
+ columns=[col_name],
+ )
+ result = df.resample("1d").aggregate(["mean"])
+ expected = DataFrame(
+ [47.5, 143.5, 195.5],
+ index=date_range(start="2017-01-01", freq="D", periods=3, tz="Europe/Berlin"),
+ columns=pd.MultiIndex(levels=[[col_name], ["mean"]], codes=[[0], [0]]),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_agg_readonly():
+ # GH#31710 cython needs to allow readonly data
+ index = date_range("2020-01-01", "2020-01-02", freq="1h")
+ arr = np.zeros_like(index)
+ arr.setflags(write=False)
+
+ ser = Series(arr, index=index)
+ rs = ser.resample("1D")
+
+ expected = Series([pd.Timestamp(0), pd.Timestamp(0)], index=index[::24])
+
+ result = rs.agg("last")
+ tm.assert_series_equal(result, expected)
+
+ result = rs.agg("first")
+ tm.assert_series_equal(result, expected)
+
+ result = rs.agg("max")
+ tm.assert_series_equal(result, expected)
+
+ result = rs.agg("min")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "start,end,freq,data,resample_freq,origin,closed,exp_data,exp_end,exp_periods",
+ [
+ (
+ "2000-10-01 23:30:00",
+ "2000-10-02 00:26:00",
+ "7min",
+ [0, 3, 6, 9, 12, 15, 18, 21, 24],
+ "17min",
+ "end",
+ None,
+ [0, 18, 27, 63],
+ "20001002 00:26:00",
+ 4,
+ ),
+ (
+ "20200101 8:26:35",
+ "20200101 9:31:58",
+ "77s",
+ [1] * 51,
+ "7min",
+ "end",
+ "right",
+ [1, 6, 5, 6, 5, 6, 5, 6, 5, 6],
+ "2020-01-01 09:30:45",
+ 10,
+ ),
+ (
+ "2000-10-01 23:30:00",
+ "2000-10-02 00:26:00",
+ "7min",
+ [0, 3, 6, 9, 12, 15, 18, 21, 24],
+ "17min",
+ "end",
+ "left",
+ [0, 18, 27, 39, 24],
+ "20001002 00:43:00",
+ 5,
+ ),
+ (
+ "2000-10-01 23:30:00",
+ "2000-10-02 00:26:00",
+ "7min",
+ [0, 3, 6, 9, 12, 15, 18, 21, 24],
+ "17min",
+ "end_day",
+ None,
+ [3, 15, 45, 45],
+ "2000-10-02 00:29:00",
+ 4,
+ ),
+ ],
+)
+def test_end_and_end_day_origin(
+ start,
+ end,
+ freq,
+ data,
+ resample_freq,
+ origin,
+ closed,
+ exp_data,
+ exp_end,
+ exp_periods,
+):
+ rng = date_range(start, end, freq=freq)
+ ts = Series(data, index=rng)
+
+ res = ts.resample(resample_freq, origin=origin, closed=closed).sum()
+ expected = Series(
+ exp_data,
+ index=date_range(end=exp_end, freq=resample_freq, periods=exp_periods),
+ )
+
+ tm.assert_series_equal(res, expected)
+
+
+@pytest.mark.parametrize(
+ # expected_data is a string when op raises a ValueError
+ "method, numeric_only, expected_data",
+ [
+ ("sum", True, {"num": [25]}),
+ ("sum", False, {"cat": ["cat_1cat_2"], "num": [25]}),
+ ("sum", lib.no_default, {"cat": ["cat_1cat_2"], "num": [25]}),
+ ("prod", True, {"num": [100]}),
+ ("prod", False, "can't multiply sequence"),
+ ("prod", lib.no_default, "can't multiply sequence"),
+ ("min", True, {"num": [5]}),
+ ("min", False, {"cat": ["cat_1"], "num": [5]}),
+ ("min", lib.no_default, {"cat": ["cat_1"], "num": [5]}),
+ ("max", True, {"num": [20]}),
+ ("max", False, {"cat": ["cat_2"], "num": [20]}),
+ ("max", lib.no_default, {"cat": ["cat_2"], "num": [20]}),
+ ("first", True, {"num": [5]}),
+ ("first", False, {"cat": ["cat_1"], "num": [5]}),
+ ("first", lib.no_default, {"cat": ["cat_1"], "num": [5]}),
+ ("last", True, {"num": [20]}),
+ ("last", False, {"cat": ["cat_2"], "num": [20]}),
+ ("last", lib.no_default, {"cat": ["cat_2"], "num": [20]}),
+ ("mean", True, {"num": [12.5]}),
+ ("mean", False, "Could not convert"),
+ ("mean", lib.no_default, "Could not convert"),
+ ("median", True, {"num": [12.5]}),
+ ("median", False, r"Cannot convert \['cat_1' 'cat_2'\] to numeric"),
+ ("median", lib.no_default, r"Cannot convert \['cat_1' 'cat_2'\] to numeric"),
+ ("std", True, {"num": [10.606601717798213]}),
+ ("std", False, "could not convert string to float"),
+ ("std", lib.no_default, "could not convert string to float"),
+ ("var", True, {"num": [112.5]}),
+ ("var", False, "could not convert string to float"),
+ ("var", lib.no_default, "could not convert string to float"),
+ ("sem", True, {"num": [7.5]}),
+ ("sem", False, "could not convert string to float"),
+ ("sem", lib.no_default, "could not convert string to float"),
+ ],
+)
+def test_frame_downsample_method(method, numeric_only, expected_data):
+ # GH#46442 test if `numeric_only` behave as expected for DataFrameGroupBy
+
+ index = date_range("2018-01-01", periods=2, freq="D")
+ expected_index = date_range("2018-12-31", periods=1, freq="Y")
+ df = DataFrame({"cat": ["cat_1", "cat_2"], "num": [5, 20]}, index=index)
+ resampled = df.resample("Y")
+ if numeric_only is lib.no_default:
+ kwargs = {}
+ else:
+ kwargs = {"numeric_only": numeric_only}
+
+ func = getattr(resampled, method)
+ if isinstance(expected_data, str):
+ if method in ("var", "mean", "median", "prod"):
+ klass = TypeError
+ msg = re.escape(f"agg function failed [how->{method},dtype->object]")
+ else:
+ klass = ValueError
+ msg = expected_data
+ with pytest.raises(klass, match=msg):
+ _ = func(**kwargs)
+ else:
+ result = func(**kwargs)
+ expected = DataFrame(expected_data, index=expected_index)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "method, numeric_only, expected_data",
+ [
+ ("sum", True, ()),
+ ("sum", False, ["cat_1cat_2"]),
+ ("sum", lib.no_default, ["cat_1cat_2"]),
+ ("prod", True, ()),
+ ("prod", False, ()),
+ ("prod", lib.no_default, ()),
+ ("min", True, ()),
+ ("min", False, ["cat_1"]),
+ ("min", lib.no_default, ["cat_1"]),
+ ("max", True, ()),
+ ("max", False, ["cat_2"]),
+ ("max", lib.no_default, ["cat_2"]),
+ ("first", True, ()),
+ ("first", False, ["cat_1"]),
+ ("first", lib.no_default, ["cat_1"]),
+ ("last", True, ()),
+ ("last", False, ["cat_2"]),
+ ("last", lib.no_default, ["cat_2"]),
+ ],
+)
+def test_series_downsample_method(method, numeric_only, expected_data):
+ # GH#46442 test if `numeric_only` behave as expected for SeriesGroupBy
+
+ index = date_range("2018-01-01", periods=2, freq="D")
+ expected_index = date_range("2018-12-31", periods=1, freq="Y")
+ df = Series(["cat_1", "cat_2"], index=index)
+ resampled = df.resample("Y")
+ kwargs = {} if numeric_only is lib.no_default else {"numeric_only": numeric_only}
+
+ func = getattr(resampled, method)
+ if numeric_only and numeric_only is not lib.no_default:
+ msg = rf"Cannot use numeric_only=True with SeriesGroupBy\.{method}"
+ with pytest.raises(TypeError, match=msg):
+ func(**kwargs)
+ elif method == "prod":
+ msg = re.escape("agg function failed [how->prod,dtype->object]")
+ with pytest.raises(TypeError, match=msg):
+ func(**kwargs)
+ else:
+ result = func(**kwargs)
+ expected = Series(expected_data, index=expected_index)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "method, raises",
+ [
+ ("sum", True),
+ ("prod", True),
+ ("min", True),
+ ("max", True),
+ ("first", False),
+ ("last", False),
+ ("median", False),
+ ("mean", True),
+ ("std", True),
+ ("var", True),
+ ("sem", False),
+ ("ohlc", False),
+ ("nunique", False),
+ ],
+)
+def test_args_kwargs_depr(method, raises):
+ index = date_range("20180101", periods=3, freq="h")
+ df = Series([2, 4, 6], index=index)
+ resampled = df.resample("30min")
+ args = ()
+
+ func = getattr(resampled, method)
+
+ error_msg = "numpy operations are not valid with resample."
+ error_msg_type = "too many arguments passed in"
+ warn_msg = f"Passing additional args to DatetimeIndexResampler.{method}"
+
+ if raises:
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ with pytest.raises(UnsupportedFunctionCall, match=error_msg):
+ func(*args, 1, 2, 3)
+ else:
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ with pytest.raises(TypeError, match=error_msg_type):
+ func(*args, 1, 2, 3)
+
+
+def test_df_axis_param_depr():
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
+ index.name = "date"
+ df = DataFrame(
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
+ ).T
+
+ # Deprecation error when axis=1 is explicitly passed
+ warning_msg = "DataFrame.resample with axis=1 is deprecated."
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
+ df.resample("M", axis=1)
+
+ # Deprecation error when axis=0 is explicitly passed
+ df = df.T
+ warning_msg = (
+ "The 'axis' keyword in DataFrame.resample is deprecated and "
+ "will be removed in a future version."
+ )
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
+ df.resample("M", axis=0)
+
+
+def test_series_axis_param_depr(_test_series):
+ warning_msg = (
+ "The 'axis' keyword in Series.resample is "
+ "deprecated and will be removed in a future version."
+ )
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
+ _test_series.resample("H", axis=0)
+
+
+def test_resample_empty():
+ # GH#52484
+ df = DataFrame(
+ index=pd.to_datetime(
+ ["2018-01-01 00:00:00", "2018-01-01 12:00:00", "2018-01-02 00:00:00"]
+ )
+ )
+ expected = DataFrame(
+ index=pd.to_datetime(
+ [
+ "2018-01-01 00:00:00",
+ "2018-01-01 08:00:00",
+ "2018-01-01 16:00:00",
+ "2018-01-02 00:00:00",
+ ]
+ )
+ )
+ result = df.resample("8H").mean()
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_resampler_grouper.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_resampler_grouper.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5288c793dafa1270b36be0b7ffbfd051f3ca59f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_resampler_grouper.py
@@ -0,0 +1,690 @@
+from textwrap import dedent
+
+import numpy as np
+import pytest
+
+from pandas.compat import is_platform_windows
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ TimedeltaIndex,
+ Timestamp,
+)
+import pandas._testing as tm
+from pandas.core.indexes.datetimes import date_range
+
+
+@pytest.fixture
+def test_frame():
+ return DataFrame(
+ {"A": [1] * 20 + [2] * 12 + [3] * 8, "B": np.arange(40)},
+ index=date_range("1/1/2000", freq="s", periods=40),
+ )
+
+
+def test_tab_complete_ipython6_warning(ip):
+ from IPython.core.completer import provisionalcompleter
+
+ code = dedent(
+ """\
+ import pandas._testing as tm
+ s = tm.makeTimeSeries()
+ rs = s.resample("D")
+ """
+ )
+ ip.run_cell(code)
+
+ # GH 31324 newer jedi version raises Deprecation warning;
+ # appears resolved 2021-02-02
+ with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
+ with provisionalcompleter("ignore"):
+ list(ip.Completer.completions("rs.", 1))
+
+
+def test_deferred_with_groupby():
+ # GH 12486
+ # support deferred resample ops with groupby
+ data = [
+ ["2010-01-01", "A", 2],
+ ["2010-01-02", "A", 3],
+ ["2010-01-05", "A", 8],
+ ["2010-01-10", "A", 7],
+ ["2010-01-13", "A", 3],
+ ["2010-01-01", "B", 5],
+ ["2010-01-03", "B", 2],
+ ["2010-01-04", "B", 1],
+ ["2010-01-11", "B", 7],
+ ["2010-01-14", "B", 3],
+ ]
+
+ df = DataFrame(data, columns=["date", "id", "score"])
+ df.date = pd.to_datetime(df.date)
+
+ def f_0(x):
+ return x.set_index("date").resample("D").asfreq()
+
+ expected = df.groupby("id").apply(f_0)
+ result = df.set_index("date").groupby("id").resample("D").asfreq()
+ tm.assert_frame_equal(result, expected)
+
+ df = DataFrame(
+ {
+ "date": date_range(start="2016-01-01", periods=4, freq="W"),
+ "group": [1, 1, 2, 2],
+ "val": [5, 6, 7, 8],
+ }
+ ).set_index("date")
+
+ def f_1(x):
+ return x.resample("1D").ffill()
+
+ expected = df.groupby("group").apply(f_1)
+ result = df.groupby("group").resample("1D").ffill()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_getitem(test_frame):
+ g = test_frame.groupby("A")
+
+ expected = g.B.apply(lambda x: x.resample("2s").mean())
+
+ result = g.resample("2s").B.mean()
+ tm.assert_series_equal(result, expected)
+
+ result = g.B.resample("2s").mean()
+ tm.assert_series_equal(result, expected)
+
+ result = g.resample("2s").mean().B
+ tm.assert_series_equal(result, expected)
+
+
+def test_getitem_multiple():
+ # GH 13174
+ # multiple calls after selection causing an issue with aliasing
+ data = [{"id": 1, "buyer": "A"}, {"id": 2, "buyer": "B"}]
+ df = DataFrame(data, index=date_range("2016-01-01", periods=2))
+ r = df.groupby("id").resample("1D")
+ result = r["buyer"].count()
+ expected = Series(
+ [1, 1],
+ index=pd.MultiIndex.from_tuples(
+ [(1, Timestamp("2016-01-01")), (2, Timestamp("2016-01-02"))],
+ names=["id", None],
+ ),
+ name="buyer",
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = r["buyer"].count()
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_resample_on_api_with_getitem():
+ # GH 17813
+ df = DataFrame(
+ {"id": list("aabbb"), "date": date_range("1-1-2016", periods=5), "data": 1}
+ )
+ exp = df.set_index("date").groupby("id").resample("2D")["data"].sum()
+ result = df.groupby("id").resample("2D", on="date")["data"].sum()
+ tm.assert_series_equal(result, exp)
+
+
+def test_groupby_with_origin():
+ # GH 31809
+
+ freq = "1399min" # prime number that is smaller than 24h
+ start, end = "1/1/2000 00:00:00", "1/31/2000 00:00"
+ middle = "1/15/2000 00:00:00"
+
+ rng = date_range(start, end, freq="1231min") # prime number
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+ ts2 = ts[middle:end]
+
+ # proves that grouper without a fixed origin does not work
+ # when dealing with unusual frequencies
+ simple_grouper = pd.Grouper(freq=freq)
+ count_ts = ts.groupby(simple_grouper).agg("count")
+ count_ts = count_ts[middle:end]
+ count_ts2 = ts2.groupby(simple_grouper).agg("count")
+ with pytest.raises(AssertionError, match="Index are different"):
+ tm.assert_index_equal(count_ts.index, count_ts2.index)
+
+ # test origin on 1970-01-01 00:00:00
+ origin = Timestamp(0)
+ adjusted_grouper = pd.Grouper(freq=freq, origin=origin)
+ adjusted_count_ts = ts.groupby(adjusted_grouper).agg("count")
+ adjusted_count_ts = adjusted_count_ts[middle:end]
+ adjusted_count_ts2 = ts2.groupby(adjusted_grouper).agg("count")
+ tm.assert_series_equal(adjusted_count_ts, adjusted_count_ts2)
+
+ # test origin on 2049-10-18 20:00:00
+ origin_future = Timestamp(0) + pd.Timedelta("1399min") * 30_000
+ adjusted_grouper2 = pd.Grouper(freq=freq, origin=origin_future)
+ adjusted2_count_ts = ts.groupby(adjusted_grouper2).agg("count")
+ adjusted2_count_ts = adjusted2_count_ts[middle:end]
+ adjusted2_count_ts2 = ts2.groupby(adjusted_grouper2).agg("count")
+ tm.assert_series_equal(adjusted2_count_ts, adjusted2_count_ts2)
+
+ # both grouper use an adjusted timestamp that is a multiple of 1399 min
+ # they should be equals even if the adjusted_timestamp is in the future
+ tm.assert_series_equal(adjusted_count_ts, adjusted2_count_ts2)
+
+
+def test_nearest():
+ # GH 17496
+ # Resample nearest
+ index = date_range("1/1/2000", periods=3, freq="T")
+ result = Series(range(3), index=index).resample("20s").nearest()
+
+ expected = Series(
+ [0, 0, 1, 1, 1, 2, 2],
+ index=pd.DatetimeIndex(
+ [
+ "2000-01-01 00:00:00",
+ "2000-01-01 00:00:20",
+ "2000-01-01 00:00:40",
+ "2000-01-01 00:01:00",
+ "2000-01-01 00:01:20",
+ "2000-01-01 00:01:40",
+ "2000-01-01 00:02:00",
+ ],
+ dtype="datetime64[ns]",
+ freq="20S",
+ ),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "f",
+ [
+ "first",
+ "last",
+ "median",
+ "sem",
+ "sum",
+ "mean",
+ "min",
+ "max",
+ "size",
+ "count",
+ "nearest",
+ "bfill",
+ "ffill",
+ "asfreq",
+ "ohlc",
+ ],
+)
+def test_methods(f, test_frame):
+ g = test_frame.groupby("A")
+ r = g.resample("2s")
+
+ result = getattr(r, f)()
+ expected = g.apply(lambda x: getattr(x.resample("2s"), f)())
+ tm.assert_equal(result, expected)
+
+
+def test_methods_nunique(test_frame):
+ # series only
+ g = test_frame.groupby("A")
+ r = g.resample("2s")
+ result = r.B.nunique()
+ expected = g.B.apply(lambda x: x.resample("2s").nunique())
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("f", ["std", "var"])
+def test_methods_std_var(f, test_frame):
+ g = test_frame.groupby("A")
+ r = g.resample("2s")
+ result = getattr(r, f)(ddof=1)
+ expected = g.apply(lambda x: getattr(x.resample("2s"), f)(ddof=1))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply(test_frame):
+ g = test_frame.groupby("A")
+ r = g.resample("2s")
+
+ # reduction
+ expected = g.resample("2s").sum()
+
+ def f_0(x):
+ return x.resample("2s").sum()
+
+ result = r.apply(f_0)
+ tm.assert_frame_equal(result, expected)
+
+ def f_1(x):
+ return x.resample("2s").apply(lambda y: y.sum())
+
+ result = g.apply(f_1)
+ # y.sum() results in int64 instead of int32 on 32-bit architectures
+ expected = expected.astype("int64")
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_with_mutated_index():
+ # GH 15169
+ index = date_range("1-1-2015", "12-31-15", freq="D")
+ df = DataFrame(
+ data={"col1": np.random.default_rng(2).random(len(index))}, index=index
+ )
+
+ def f(x):
+ s = Series([1, 2], index=["a", "b"])
+ return s
+
+ expected = df.groupby(pd.Grouper(freq="M")).apply(f)
+
+ result = df.resample("M").apply(f)
+ tm.assert_frame_equal(result, expected)
+
+ # A case for series
+ expected = df["col1"].groupby(pd.Grouper(freq="M"), group_keys=False).apply(f)
+ result = df["col1"].resample("M").apply(f)
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_columns_multilevel():
+ # GH 16231
+ cols = pd.MultiIndex.from_tuples([("A", "a", "", "one"), ("B", "b", "i", "two")])
+ ind = date_range(start="2017-01-01", freq="15Min", periods=8)
+ df = DataFrame(np.array([0] * 16).reshape(8, 2), index=ind, columns=cols)
+ agg_dict = {col: (np.sum if col[3] == "one" else np.mean) for col in df.columns}
+ result = df.resample("H").apply(lambda x: agg_dict[x.name](x))
+ expected = DataFrame(
+ 2 * [[0, 0.0]],
+ index=date_range(start="2017-01-01", freq="1H", periods=2),
+ columns=pd.MultiIndex.from_tuples(
+ [("A", "a", "", "one"), ("B", "b", "i", "two")]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_non_naive_index():
+ def weighted_quantile(series, weights, q):
+ series = series.sort_values()
+ cumsum = weights.reindex(series.index).fillna(0).cumsum()
+ cutoff = cumsum.iloc[-1] * q
+ return series[cumsum >= cutoff].iloc[0]
+
+ times = date_range("2017-6-23 18:00", periods=8, freq="15T", tz="UTC")
+ data = Series([1.0, 1, 1, 1, 1, 2, 2, 0], index=times)
+ weights = Series([160.0, 91, 65, 43, 24, 10, 1, 0], index=times)
+
+ result = data.resample("D").apply(weighted_quantile, weights=weights, q=0.5)
+ ind = date_range(
+ "2017-06-23 00:00:00+00:00", "2017-06-23 00:00:00+00:00", freq="D", tz="UTC"
+ )
+ expected = Series([1.0], index=ind)
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_groupby_with_label():
+ # GH 13235
+ index = date_range("2000-01-01", freq="2D", periods=5)
+ df = DataFrame(index=index, data={"col0": [0, 0, 1, 1, 2], "col1": [1, 1, 1, 1, 1]})
+ result = df.groupby("col0").resample("1W", label="left").sum()
+
+ mi = [
+ np.array([0, 0, 1, 2], dtype=np.int64),
+ pd.to_datetime(
+ np.array(["1999-12-26", "2000-01-02", "2000-01-02", "2000-01-02"])
+ ),
+ ]
+ mindex = pd.MultiIndex.from_arrays(mi, names=["col0", None])
+ expected = DataFrame(
+ data={"col0": [0, 0, 2, 2], "col1": [1, 1, 2, 1]}, index=mindex
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_consistency_with_window(test_frame):
+ # consistent return values with window
+ df = test_frame
+ expected = Index([1, 2, 3], name="A")
+ result = df.groupby("A").resample("2s").mean()
+ assert result.index.nlevels == 2
+ tm.assert_index_equal(result.index.levels[0], expected)
+
+ result = df.groupby("A").rolling(20).mean()
+ assert result.index.nlevels == 2
+ tm.assert_index_equal(result.index.levels[0], expected)
+
+
+def test_median_duplicate_columns():
+ # GH 14233
+
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((20, 3)),
+ columns=list("aaa"),
+ index=date_range("2012-01-01", periods=20, freq="s"),
+ )
+ df2 = df.copy()
+ df2.columns = ["a", "b", "c"]
+ expected = df2.resample("5s").median()
+ result = df.resample("5s").median()
+ expected.columns = result.columns
+ tm.assert_frame_equal(result, expected)
+
+
+def test_apply_to_one_column_of_df():
+ # GH: 36951
+ df = DataFrame(
+ {"col": range(10), "col1": range(10, 20)},
+ index=date_range("2012-01-01", periods=10, freq="20min"),
+ )
+
+ # access "col" via getattr -> make sure we handle AttributeError
+ result = df.resample("H").apply(lambda group: group.col.sum())
+ expected = Series(
+ [3, 12, 21, 9], index=date_range("2012-01-01", periods=4, freq="H")
+ )
+ tm.assert_series_equal(result, expected)
+
+ # access "col" via _getitem__ -> make sure we handle KeyErrpr
+ result = df.resample("H").apply(lambda group: group["col"].sum())
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_groupby_agg():
+ # GH: 33548
+ df = DataFrame(
+ {
+ "cat": [
+ "cat_1",
+ "cat_1",
+ "cat_2",
+ "cat_1",
+ "cat_2",
+ "cat_1",
+ "cat_2",
+ "cat_1",
+ ],
+ "num": [5, 20, 22, 3, 4, 30, 10, 50],
+ "date": [
+ "2019-2-1",
+ "2018-02-03",
+ "2020-3-11",
+ "2019-2-2",
+ "2019-2-2",
+ "2018-12-4",
+ "2020-3-11",
+ "2020-12-12",
+ ],
+ }
+ )
+ df["date"] = pd.to_datetime(df["date"])
+
+ resampled = df.groupby("cat").resample("Y", on="date")
+ expected = resampled[["num"]].sum()
+ result = resampled.agg({"num": "sum"})
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_groupby_agg_listlike():
+ # GH 42905
+ ts = Timestamp("2021-02-28 00:00:00")
+ df = DataFrame({"class": ["beta"], "value": [69]}, index=Index([ts], name="date"))
+ resampled = df.groupby("class").resample("M")["value"]
+ result = resampled.agg(["sum", "size"])
+ expected = DataFrame(
+ [[69, 1]],
+ index=pd.MultiIndex.from_tuples([("beta", ts)], names=["class", "date"]),
+ columns=["sum", "size"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("keys", [["a"], ["a", "b"]])
+def test_empty(keys):
+ # GH 26411
+ df = DataFrame([], columns=["a", "b"], index=TimedeltaIndex([]))
+ result = df.groupby(keys).resample(rule=pd.to_timedelta("00:00:01")).mean()
+ expected = (
+ DataFrame(columns=["a", "b"])
+ .set_index(keys, drop=False)
+ .set_index(TimedeltaIndex([]), append=True)
+ )
+ if len(keys) == 1:
+ expected.index.name = keys[0]
+
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("consolidate", [True, False])
+def test_resample_groupby_agg_object_dtype_all_nan(consolidate):
+ # https://github.com/pandas-dev/pandas/issues/39329
+
+ dates = date_range("2020-01-01", periods=15, freq="D")
+ df1 = DataFrame({"key": "A", "date": dates, "col1": range(15), "col_object": "val"})
+ df2 = DataFrame({"key": "B", "date": dates, "col1": range(15)})
+ df = pd.concat([df1, df2], ignore_index=True)
+ if consolidate:
+ df = df._consolidate()
+
+ result = df.groupby(["key"]).resample("W", on="date").min()
+ idx = pd.MultiIndex.from_arrays(
+ [
+ ["A"] * 3 + ["B"] * 3,
+ pd.to_datetime(["2020-01-05", "2020-01-12", "2020-01-19"] * 2),
+ ],
+ names=["key", "date"],
+ )
+ expected = DataFrame(
+ {
+ "key": ["A"] * 3 + ["B"] * 3,
+ "col1": [0, 5, 12] * 2,
+ "col_object": ["val"] * 3 + [np.nan] * 3,
+ },
+ index=idx,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_resample_with_list_of_keys():
+ # GH 47362
+ df = DataFrame(
+ data={
+ "date": date_range(start="2016-01-01", periods=8),
+ "group": [0, 0, 0, 0, 1, 1, 1, 1],
+ "val": [1, 7, 5, 2, 3, 10, 5, 1],
+ }
+ )
+ result = df.groupby("group").resample("2D", on="date")[["val"]].mean()
+ expected = DataFrame(
+ data={
+ "val": [4.0, 3.5, 6.5, 3.0],
+ },
+ index=Index(
+ data=[
+ (0, Timestamp("2016-01-01")),
+ (0, Timestamp("2016-01-03")),
+ (1, Timestamp("2016-01-05")),
+ (1, Timestamp("2016-01-07")),
+ ],
+ name=("group", "date"),
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("keys", [["a"], ["a", "b"]])
+def test_resample_no_index(keys):
+ # GH 47705
+ df = DataFrame([], columns=["a", "b", "date"])
+ df["date"] = pd.to_datetime(df["date"])
+ df = df.set_index("date")
+ result = df.groupby(keys).resample(rule=pd.to_timedelta("00:00:01")).mean()
+ expected = DataFrame(columns=["a", "b", "date"]).set_index(keys, drop=False)
+ expected["date"] = pd.to_datetime(expected["date"])
+ expected = expected.set_index("date", append=True, drop=True)
+ if len(keys) == 1:
+ expected.index.name = keys[0]
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_no_columns():
+ # GH#52484
+ df = DataFrame(
+ index=Index(
+ pd.to_datetime(
+ ["2018-01-01 00:00:00", "2018-01-01 12:00:00", "2018-01-02 00:00:00"]
+ ),
+ name="date",
+ )
+ )
+ result = df.groupby([0, 0, 1]).resample(rule=pd.to_timedelta("06:00:00")).mean()
+ index = pd.to_datetime(
+ [
+ "2018-01-01 00:00:00",
+ "2018-01-01 06:00:00",
+ "2018-01-01 12:00:00",
+ "2018-01-02 00:00:00",
+ ]
+ )
+ expected = DataFrame(
+ index=pd.MultiIndex(
+ levels=[np.array([0, 1], dtype=np.intp), index],
+ codes=[[0, 0, 0, 1], [0, 1, 2, 3]],
+ names=[None, "date"],
+ )
+ )
+
+ # GH#52710 - Index comes out as 32-bit on 64-bit Windows
+ tm.assert_frame_equal(result, expected, check_index_type=not is_platform_windows())
+
+
+def test_groupby_resample_size_all_index_same():
+ # GH 46826
+ df = DataFrame(
+ {"A": [1] * 3 + [2] * 3 + [1] * 3 + [2] * 3, "B": np.arange(12)},
+ index=date_range("31/12/2000 18:00", freq="H", periods=12),
+ )
+ result = df.groupby("A").resample("D").size()
+ expected = Series(
+ 3,
+ index=pd.MultiIndex.from_tuples(
+ [
+ (1, Timestamp("2000-12-31")),
+ (1, Timestamp("2001-01-01")),
+ (2, Timestamp("2000-12-31")),
+ (2, Timestamp("2001-01-01")),
+ ],
+ names=["A", None],
+ ),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_resample_on_index_with_list_of_keys():
+ # GH 50840
+ df = DataFrame(
+ data={
+ "group": [0, 0, 0, 0, 1, 1, 1, 1],
+ "val": [3, 1, 4, 1, 5, 9, 2, 6],
+ },
+ index=Series(
+ date_range(start="2016-01-01", periods=8),
+ name="date",
+ ),
+ )
+ result = df.groupby("group").resample("2D")[["val"]].mean()
+ expected = DataFrame(
+ data={
+ "val": [2.0, 2.5, 7.0, 4.0],
+ },
+ index=Index(
+ data=[
+ (0, Timestamp("2016-01-01")),
+ (0, Timestamp("2016-01-03")),
+ (1, Timestamp("2016-01-05")),
+ (1, Timestamp("2016-01-07")),
+ ],
+ name=("group", "date"),
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_resample_on_index_with_list_of_keys_multi_columns():
+ # GH 50876
+ df = DataFrame(
+ data={
+ "group": [0, 0, 0, 0, 1, 1, 1, 1],
+ "first_val": [3, 1, 4, 1, 5, 9, 2, 6],
+ "second_val": [2, 7, 1, 8, 2, 8, 1, 8],
+ "third_val": [1, 4, 1, 4, 2, 1, 3, 5],
+ },
+ index=Series(
+ date_range(start="2016-01-01", periods=8),
+ name="date",
+ ),
+ )
+ result = df.groupby("group").resample("2D")[["first_val", "second_val"]].mean()
+ expected = DataFrame(
+ data={
+ "first_val": [2.0, 2.5, 7.0, 4.0],
+ "second_val": [4.5, 4.5, 5.0, 4.5],
+ },
+ index=Index(
+ data=[
+ (0, Timestamp("2016-01-01")),
+ (0, Timestamp("2016-01-03")),
+ (1, Timestamp("2016-01-05")),
+ (1, Timestamp("2016-01-07")),
+ ],
+ name=("group", "date"),
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_resample_on_index_with_list_of_keys_missing_column():
+ # GH 50876
+ df = DataFrame(
+ data={
+ "group": [0, 0, 0, 0, 1, 1, 1, 1],
+ "val": [3, 1, 4, 1, 5, 9, 2, 6],
+ },
+ index=Series(
+ date_range(start="2016-01-01", periods=8),
+ name="date",
+ ),
+ )
+ with pytest.raises(KeyError, match="Columns not found"):
+ df.groupby("group").resample("2D")[["val_not_in_dataframe"]].mean()
+
+
+@pytest.mark.parametrize("kind", ["datetime", "period"])
+def test_groupby_resample_kind(kind):
+ # GH 24103
+ df = DataFrame(
+ {
+ "datetime": pd.to_datetime(
+ ["20181101 1100", "20181101 1200", "20181102 1300", "20181102 1400"]
+ ),
+ "group": ["A", "B", "A", "B"],
+ "value": [1, 2, 3, 4],
+ }
+ )
+ df = df.set_index("datetime")
+ result = df.groupby("group")["value"].resample("D", kind=kind).last()
+
+ dt_level = pd.DatetimeIndex(["2018-11-01", "2018-11-02"])
+ if kind == "period":
+ dt_level = dt_level.to_period(freq="D")
+ expected_index = pd.MultiIndex.from_product(
+ [["A", "B"], dt_level],
+ names=["group", "datetime"],
+ )
+ expected = Series([1, 3, 2, 4], index=expected_index, name="value")
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_time_grouper.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_time_grouper.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c06f1e8a1e384e3caf859a63ab86995bf4bf3f2
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_time_grouper.py
@@ -0,0 +1,379 @@
+from datetime import datetime
+from operator import methodcaller
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
+import pandas._testing as tm
+from pandas.core.groupby.grouper import Grouper
+from pandas.core.indexes.datetimes import date_range
+
+
+@pytest.fixture
+def test_series():
+ return Series(
+ np.random.default_rng(2).standard_normal(1000),
+ index=date_range("1/1/2000", periods=1000),
+ )
+
+
+def test_apply(test_series):
+ grouper = Grouper(freq="A", label="right", closed="right")
+
+ grouped = test_series.groupby(grouper)
+
+ def f(x):
+ return x.sort_values()[-3:]
+
+ applied = grouped.apply(f)
+ expected = test_series.groupby(lambda x: x.year).apply(f)
+
+ applied.index = applied.index.droplevel(0)
+ expected.index = expected.index.droplevel(0)
+ tm.assert_series_equal(applied, expected)
+
+
+def test_count(test_series):
+ test_series[::3] = np.nan
+
+ expected = test_series.groupby(lambda x: x.year).count()
+
+ grouper = Grouper(freq="A", label="right", closed="right")
+ result = test_series.groupby(grouper).count()
+ expected.index = result.index
+ tm.assert_series_equal(result, expected)
+
+ result = test_series.resample("A").count()
+ expected.index = result.index
+ tm.assert_series_equal(result, expected)
+
+
+def test_numpy_reduction(test_series):
+ result = test_series.resample("A", closed="right").prod()
+
+ msg = "using SeriesGroupBy.prod"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = test_series.groupby(lambda x: x.year).agg(np.prod)
+ expected.index = result.index
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_apply_iteration():
+ # #2300
+ N = 1000
+ ind = date_range(start="2000-01-01", freq="D", periods=N)
+ df = DataFrame({"open": 1, "close": 2}, index=ind)
+ tg = Grouper(freq="M")
+
+ grouper, _ = tg._get_grouper(df)
+
+ # Errors
+ grouped = df.groupby(grouper, group_keys=False)
+
+ def f(df):
+ return df["close"] / df["open"]
+
+ # it works!
+ result = grouped.apply(f)
+ tm.assert_index_equal(result.index, df.index)
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ tm.makeIntIndex,
+ tm.makeStringIndex,
+ tm.makeFloatIndex,
+ (lambda m: tm.makeCustomIndex(m, 2)),
+ ],
+)
+def test_fails_on_no_datetime_index(func):
+ n = 2
+ index = func(n)
+ name = type(index).__name__
+ df = DataFrame({"a": np.random.default_rng(2).standard_normal(n)}, index=index)
+
+ msg = (
+ "Only valid with DatetimeIndex, TimedeltaIndex "
+ f"or PeriodIndex, but got an instance of '{name}'"
+ )
+ with pytest.raises(TypeError, match=msg):
+ df.groupby(Grouper(freq="D"))
+
+
+def test_aaa_group_order():
+ # GH 12840
+ # check TimeGrouper perform stable sorts
+ n = 20
+ data = np.random.default_rng(2).standard_normal((n, 4))
+ df = DataFrame(data, columns=["A", "B", "C", "D"])
+ df["key"] = [
+ datetime(2013, 1, 1),
+ datetime(2013, 1, 2),
+ datetime(2013, 1, 3),
+ datetime(2013, 1, 4),
+ datetime(2013, 1, 5),
+ ] * 4
+ grouped = df.groupby(Grouper(key="key", freq="D"))
+
+ tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 1)), df[::5])
+ tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 2)), df[1::5])
+ tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 3)), df[2::5])
+ tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 4)), df[3::5])
+ tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 5)), df[4::5])
+
+
+def test_aggregate_normal(resample_method):
+ """Check TimeGrouper's aggregation is identical as normal groupby."""
+
+ data = np.random.default_rng(2).standard_normal((20, 4))
+ normal_df = DataFrame(data, columns=["A", "B", "C", "D"])
+ normal_df["key"] = [1, 2, 3, 4, 5] * 4
+
+ dt_df = DataFrame(data, columns=["A", "B", "C", "D"])
+ dt_df["key"] = [
+ datetime(2013, 1, 1),
+ datetime(2013, 1, 2),
+ datetime(2013, 1, 3),
+ datetime(2013, 1, 4),
+ datetime(2013, 1, 5),
+ ] * 4
+
+ normal_grouped = normal_df.groupby("key")
+ dt_grouped = dt_df.groupby(Grouper(key="key", freq="D"))
+
+ expected = getattr(normal_grouped, resample_method)()
+ dt_result = getattr(dt_grouped, resample_method)()
+ expected.index = date_range(start="2013-01-01", freq="D", periods=5, name="key")
+ tm.assert_equal(expected, dt_result)
+
+
+@pytest.mark.xfail(reason="if TimeGrouper is used included, 'nth' doesn't work yet")
+def test_aggregate_nth():
+ """Check TimeGrouper's aggregation is identical as normal groupby."""
+
+ data = np.random.default_rng(2).standard_normal((20, 4))
+ normal_df = DataFrame(data, columns=["A", "B", "C", "D"])
+ normal_df["key"] = [1, 2, 3, 4, 5] * 4
+
+ dt_df = DataFrame(data, columns=["A", "B", "C", "D"])
+ dt_df["key"] = [
+ datetime(2013, 1, 1),
+ datetime(2013, 1, 2),
+ datetime(2013, 1, 3),
+ datetime(2013, 1, 4),
+ datetime(2013, 1, 5),
+ ] * 4
+
+ normal_grouped = normal_df.groupby("key")
+ dt_grouped = dt_df.groupby(Grouper(key="key", freq="D"))
+
+ expected = normal_grouped.nth(3)
+ expected.index = date_range(start="2013-01-01", freq="D", periods=5, name="key")
+ dt_result = dt_grouped.nth(3)
+ tm.assert_frame_equal(expected, dt_result)
+
+
+@pytest.mark.parametrize(
+ "method, method_args, unit",
+ [
+ ("sum", {}, 0),
+ ("sum", {"min_count": 0}, 0),
+ ("sum", {"min_count": 1}, np.nan),
+ ("prod", {}, 1),
+ ("prod", {"min_count": 0}, 1),
+ ("prod", {"min_count": 1}, np.nan),
+ ],
+)
+def test_resample_entirely_nat_window(method, method_args, unit):
+ s = Series([0] * 2 + [np.nan] * 2, index=date_range("2017", periods=4))
+ result = methodcaller(method, **method_args)(s.resample("2d"))
+ expected = Series(
+ [0.0, unit], index=pd.DatetimeIndex(["2017-01-01", "2017-01-03"], freq="2D")
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "func, fill_value",
+ [("min", np.nan), ("max", np.nan), ("sum", 0), ("prod", 1), ("count", 0)],
+)
+def test_aggregate_with_nat(func, fill_value):
+ # check TimeGrouper's aggregation is identical as normal groupby
+ # if NaT is included, 'var', 'std', 'mean', 'first','last'
+ # and 'nth' doesn't work yet
+
+ n = 20
+ data = np.random.default_rng(2).standard_normal((n, 4)).astype("int64")
+ normal_df = DataFrame(data, columns=["A", "B", "C", "D"])
+ normal_df["key"] = [1, 2, np.nan, 4, 5] * 4
+
+ dt_df = DataFrame(data, columns=["A", "B", "C", "D"])
+ dt_df["key"] = [
+ datetime(2013, 1, 1),
+ datetime(2013, 1, 2),
+ pd.NaT,
+ datetime(2013, 1, 4),
+ datetime(2013, 1, 5),
+ ] * 4
+
+ normal_grouped = normal_df.groupby("key")
+ dt_grouped = dt_df.groupby(Grouper(key="key", freq="D"))
+
+ normal_result = getattr(normal_grouped, func)()
+ dt_result = getattr(dt_grouped, func)()
+
+ pad = DataFrame([[fill_value] * 4], index=[3], columns=["A", "B", "C", "D"])
+ expected = pd.concat([normal_result, pad])
+ expected = expected.sort_index()
+ dti = date_range(start="2013-01-01", freq="D", periods=5, name="key")
+ expected.index = dti._with_freq(None) # TODO: is this desired?
+ tm.assert_frame_equal(expected, dt_result)
+ assert dt_result.index.name == "key"
+
+
+def test_aggregate_with_nat_size():
+ # GH 9925
+ n = 20
+ data = np.random.default_rng(2).standard_normal((n, 4)).astype("int64")
+ normal_df = DataFrame(data, columns=["A", "B", "C", "D"])
+ normal_df["key"] = [1, 2, np.nan, 4, 5] * 4
+
+ dt_df = DataFrame(data, columns=["A", "B", "C", "D"])
+ dt_df["key"] = [
+ datetime(2013, 1, 1),
+ datetime(2013, 1, 2),
+ pd.NaT,
+ datetime(2013, 1, 4),
+ datetime(2013, 1, 5),
+ ] * 4
+
+ normal_grouped = normal_df.groupby("key")
+ dt_grouped = dt_df.groupby(Grouper(key="key", freq="D"))
+
+ normal_result = normal_grouped.size()
+ dt_result = dt_grouped.size()
+
+ pad = Series([0], index=[3])
+ expected = pd.concat([normal_result, pad])
+ expected = expected.sort_index()
+ expected.index = date_range(
+ start="2013-01-01", freq="D", periods=5, name="key"
+ )._with_freq(None)
+ tm.assert_series_equal(expected, dt_result)
+ assert dt_result.index.name == "key"
+
+
+def test_repr():
+ # GH18203
+ result = repr(Grouper(key="A", freq="H"))
+ expected = (
+ "TimeGrouper(key='A', freq=, axis=0, sort=True, dropna=True, "
+ "closed='left', label='left', how='mean', "
+ "convention='e', origin='start_day')"
+ )
+ assert result == expected
+
+ result = repr(Grouper(key="A", freq="H", origin="2000-01-01"))
+ expected = (
+ "TimeGrouper(key='A', freq=, axis=0, sort=True, dropna=True, "
+ "closed='left', label='left', how='mean', "
+ "convention='e', origin=Timestamp('2000-01-01 00:00:00'))"
+ )
+ assert result == expected
+
+
+@pytest.mark.parametrize(
+ "method, method_args, expected_values",
+ [
+ ("sum", {}, [1, 0, 1]),
+ ("sum", {"min_count": 0}, [1, 0, 1]),
+ ("sum", {"min_count": 1}, [1, np.nan, 1]),
+ ("sum", {"min_count": 2}, [np.nan, np.nan, np.nan]),
+ ("prod", {}, [1, 1, 1]),
+ ("prod", {"min_count": 0}, [1, 1, 1]),
+ ("prod", {"min_count": 1}, [1, np.nan, 1]),
+ ("prod", {"min_count": 2}, [np.nan, np.nan, np.nan]),
+ ],
+)
+def test_upsample_sum(method, method_args, expected_values):
+ s = Series(1, index=date_range("2017", periods=2, freq="H"))
+ resampled = s.resample("30T")
+ index = pd.DatetimeIndex(
+ ["2017-01-01T00:00:00", "2017-01-01T00:30:00", "2017-01-01T01:00:00"],
+ freq="30T",
+ )
+ result = methodcaller(method, **method_args)(resampled)
+ expected = Series(expected_values, index=index)
+ tm.assert_series_equal(result, expected)
+
+
+def test_groupby_resample_interpolate():
+ # GH 35325
+ d = {"price": [10, 11, 9], "volume": [50, 60, 50]}
+
+ df = DataFrame(d)
+
+ df["week_starting"] = date_range("01/01/2018", periods=3, freq="W")
+
+ result = (
+ df.set_index("week_starting")
+ .groupby("volume")
+ .resample("1D")
+ .interpolate(method="linear")
+ )
+
+ expected_ind = pd.MultiIndex.from_tuples(
+ [
+ (50, Timestamp("2018-01-07")),
+ (50, Timestamp("2018-01-08")),
+ (50, Timestamp("2018-01-09")),
+ (50, Timestamp("2018-01-10")),
+ (50, Timestamp("2018-01-11")),
+ (50, Timestamp("2018-01-12")),
+ (50, Timestamp("2018-01-13")),
+ (50, Timestamp("2018-01-14")),
+ (50, Timestamp("2018-01-15")),
+ (50, Timestamp("2018-01-16")),
+ (50, Timestamp("2018-01-17")),
+ (50, Timestamp("2018-01-18")),
+ (50, Timestamp("2018-01-19")),
+ (50, Timestamp("2018-01-20")),
+ (50, Timestamp("2018-01-21")),
+ (60, Timestamp("2018-01-14")),
+ ],
+ names=["volume", "week_starting"],
+ )
+
+ expected = DataFrame(
+ data={
+ "price": [
+ 10.0,
+ 9.928571428571429,
+ 9.857142857142858,
+ 9.785714285714286,
+ 9.714285714285714,
+ 9.642857142857142,
+ 9.571428571428571,
+ 9.5,
+ 9.428571428571429,
+ 9.357142857142858,
+ 9.285714285714286,
+ 9.214285714285714,
+ 9.142857142857142,
+ 9.071428571428571,
+ 9.0,
+ 11.0,
+ ],
+ "volume": [50.0] * 15 + [60],
+ },
+ index=expected_ind,
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_timedelta.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_timedelta.py
new file mode 100644
index 0000000000000000000000000000000000000000..a119a911e5fbe6bd200e8334e32ef811489b3f33
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/test_timedelta.py
@@ -0,0 +1,206 @@
+from datetime import timedelta
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Series,
+)
+import pandas._testing as tm
+from pandas.core.indexes.timedeltas import timedelta_range
+
+
+def test_asfreq_bug():
+ df = DataFrame(data=[1, 3], index=[timedelta(), timedelta(minutes=3)])
+ result = df.resample("1T").asfreq()
+ expected = DataFrame(
+ data=[1, np.nan, np.nan, 3],
+ index=timedelta_range("0 day", periods=4, freq="1T"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_with_nat():
+ # GH 13223
+ index = pd.to_timedelta(["0s", pd.NaT, "2s"])
+ result = DataFrame({"value": [2, 3, 5]}, index).resample("1s").mean()
+ expected = DataFrame(
+ {"value": [2.5, np.nan, 5.0]},
+ index=timedelta_range("0 day", periods=3, freq="1S"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_as_freq_with_subperiod():
+ # GH 13022
+ index = timedelta_range("00:00:00", "00:10:00", freq="5T")
+ df = DataFrame(data={"value": [1, 5, 10]}, index=index)
+ result = df.resample("2T").asfreq()
+ expected_data = {"value": [1, np.nan, np.nan, np.nan, np.nan, 10]}
+ expected = DataFrame(
+ data=expected_data, index=timedelta_range("00:00:00", "00:10:00", freq="2T")
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_with_timedeltas():
+ expected = DataFrame({"A": np.arange(1480)})
+ expected = expected.groupby(expected.index // 30).sum()
+ expected.index = timedelta_range("0 days", freq="30min", periods=50)
+
+ df = DataFrame(
+ {"A": np.arange(1480)}, index=pd.to_timedelta(np.arange(1480), unit="min")
+ )
+ result = df.resample("30min").sum()
+
+ tm.assert_frame_equal(result, expected)
+
+ s = df["A"]
+ result = s.resample("30min").sum()
+ tm.assert_series_equal(result, expected["A"])
+
+
+def test_resample_single_period_timedelta():
+ s = Series(list(range(5)), index=timedelta_range("1 day", freq="s", periods=5))
+ result = s.resample("2s").sum()
+ expected = Series([1, 5, 4], index=timedelta_range("1 day", freq="2s", periods=3))
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_timedelta_idempotency():
+ # GH 12072
+ index = timedelta_range("0", periods=9, freq="10L")
+ series = Series(range(9), index=index)
+ result = series.resample("10L").mean()
+ expected = series.astype(float)
+ tm.assert_series_equal(result, expected)
+
+
+def test_resample_offset_with_timedeltaindex():
+ # GH 10530 & 31809
+ rng = timedelta_range(start="0s", periods=25, freq="s")
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ with_base = ts.resample("2s", offset="5s").mean()
+ without_base = ts.resample("2s").mean()
+
+ exp_without_base = timedelta_range(start="0s", end="25s", freq="2s")
+ exp_with_base = timedelta_range(start="5s", end="29s", freq="2s")
+
+ tm.assert_index_equal(without_base.index, exp_without_base)
+ tm.assert_index_equal(with_base.index, exp_with_base)
+
+
+def test_resample_categorical_data_with_timedeltaindex():
+ # GH #12169
+ df = DataFrame({"Group_obj": "A"}, index=pd.to_timedelta(list(range(20)), unit="s"))
+ df["Group"] = df["Group_obj"].astype("category")
+ result = df.resample("10s").agg(lambda x: (x.value_counts().index[0]))
+ expected = DataFrame(
+ {"Group_obj": ["A", "A"], "Group": ["A", "A"]},
+ index=pd.TimedeltaIndex([0, 10], unit="s", freq="10s"),
+ )
+ expected = expected.reindex(["Group_obj", "Group"], axis=1)
+ expected["Group"] = expected["Group_obj"]
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_timedelta_values():
+ # GH 13119
+ # check that timedelta dtype is preserved when NaT values are
+ # introduced by the resampling
+
+ times = timedelta_range("1 day", "6 day", freq="4D")
+ df = DataFrame({"time": times}, index=times)
+
+ times2 = timedelta_range("1 day", "6 day", freq="2D")
+ exp = Series(times2, index=times2, name="time")
+ exp.iloc[1] = pd.NaT
+
+ res = df.resample("2D").first()["time"]
+ tm.assert_series_equal(res, exp)
+ res = df["time"].resample("2D").first()
+ tm.assert_series_equal(res, exp)
+
+
+@pytest.mark.parametrize(
+ "start, end, freq, resample_freq",
+ [
+ ("8H", "21h59min50s", "10S", "3H"), # GH 30353 example
+ ("3H", "22H", "1H", "5H"),
+ ("527D", "5006D", "3D", "10D"),
+ ("1D", "10D", "1D", "2D"), # GH 13022 example
+ # tests that worked before GH 33498:
+ ("8H", "21h59min50s", "10S", "2H"),
+ ("0H", "21h59min50s", "10S", "3H"),
+ ("10D", "85D", "D", "2D"),
+ ],
+)
+def test_resample_timedelta_edge_case(start, end, freq, resample_freq):
+ # GH 33498
+ # check that the timedelta bins does not contains an extra bin
+ idx = timedelta_range(start=start, end=end, freq=freq)
+ s = Series(np.arange(len(idx)), index=idx)
+ result = s.resample(resample_freq).min()
+ expected_index = timedelta_range(freq=resample_freq, start=start, end=end)
+ tm.assert_index_equal(result.index, expected_index)
+ assert result.index.freq == expected_index.freq
+ assert not np.isnan(result.iloc[-1])
+
+
+@pytest.mark.parametrize("duplicates", [True, False])
+def test_resample_with_timedelta_yields_no_empty_groups(duplicates):
+ # GH 10603
+ df = DataFrame(
+ np.random.default_rng(2).normal(size=(10000, 4)),
+ index=timedelta_range(start="0s", periods=10000, freq="3906250n"),
+ )
+ if duplicates:
+ # case with non-unique columns
+ df.columns = ["A", "B", "A", "C"]
+
+ result = df.loc["1s":, :].resample("3s").apply(lambda x: len(x))
+
+ expected = DataFrame(
+ [[768] * 4] * 12 + [[528] * 4],
+ index=timedelta_range(start="1s", periods=13, freq="3s"),
+ )
+ expected.columns = df.columns
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
+def test_resample_quantile_timedelta(unit):
+ # GH: 29485
+ dtype = np.dtype(f"m8[{unit}]")
+ df = DataFrame(
+ {"value": pd.to_timedelta(np.arange(4), unit="s").astype(dtype)},
+ index=pd.date_range("20200101", periods=4, tz="UTC"),
+ )
+ result = df.resample("2D").quantile(0.99)
+ expected = DataFrame(
+ {
+ "value": [
+ pd.Timedelta("0 days 00:00:00.990000"),
+ pd.Timedelta("0 days 00:00:02.990000"),
+ ]
+ },
+ index=pd.date_range("20200101", periods=2, tz="UTC", freq="2D"),
+ ).astype(dtype)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_resample_closed_right():
+ # GH#45414
+ idx = pd.Index([pd.Timedelta(seconds=120 + i * 30) for i in range(10)])
+ ser = Series(range(10), index=idx)
+ result = ser.resample("T", closed="right", label="right").sum()
+ expected = Series(
+ [0, 3, 7, 11, 15, 9],
+ index=pd.TimedeltaIndex(
+ [pd.Timedelta(seconds=120 + i * 60) for i in range(6)], freq="T"
+ ),
+ )
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_crosstab.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_crosstab.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b6ebded3d325d1274b7dd6b5f153ebf005e65d3
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_crosstab.py
@@ -0,0 +1,893 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ CategoricalDtype,
+ CategoricalIndex,
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ crosstab,
+)
+import pandas._testing as tm
+
+
+@pytest.fixture
+def df():
+ df = DataFrame(
+ {
+ "A": [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ "foo",
+ "foo",
+ "foo",
+ ],
+ "B": [
+ "one",
+ "one",
+ "one",
+ "two",
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "two",
+ "one",
+ ],
+ "C": [
+ "dull",
+ "dull",
+ "shiny",
+ "dull",
+ "dull",
+ "shiny",
+ "shiny",
+ "dull",
+ "shiny",
+ "shiny",
+ "shiny",
+ ],
+ "D": np.random.default_rng(2).standard_normal(11),
+ "E": np.random.default_rng(2).standard_normal(11),
+ "F": np.random.default_rng(2).standard_normal(11),
+ }
+ )
+
+ return pd.concat([df, df], ignore_index=True)
+
+
+class TestCrosstab:
+ def test_crosstab_single(self, df):
+ result = crosstab(df["A"], df["C"])
+ expected = df.groupby(["A", "C"]).size().unstack()
+ tm.assert_frame_equal(result, expected.fillna(0).astype(np.int64))
+
+ def test_crosstab_multiple(self, df):
+ result = crosstab(df["A"], [df["B"], df["C"]])
+ expected = df.groupby(["A", "B", "C"]).size()
+ expected = expected.unstack("B").unstack("C").fillna(0).astype(np.int64)
+ tm.assert_frame_equal(result, expected)
+
+ result = crosstab([df["B"], df["C"]], df["A"])
+ expected = df.groupby(["B", "C", "A"]).size()
+ expected = expected.unstack("A").fillna(0).astype(np.int64)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("box", [np.array, list, tuple])
+ def test_crosstab_ndarray(self, box):
+ # GH 44076
+ a = box(np.random.default_rng(2).integers(0, 5, size=100))
+ b = box(np.random.default_rng(2).integers(0, 3, size=100))
+ c = box(np.random.default_rng(2).integers(0, 10, size=100))
+
+ df = DataFrame({"a": a, "b": b, "c": c})
+
+ result = crosstab(a, [b, c], rownames=["a"], colnames=("b", "c"))
+ expected = crosstab(df["a"], [df["b"], df["c"]])
+ tm.assert_frame_equal(result, expected)
+
+ result = crosstab([b, c], a, colnames=["a"], rownames=("b", "c"))
+ expected = crosstab([df["b"], df["c"]], df["a"])
+ tm.assert_frame_equal(result, expected)
+
+ # assign arbitrary names
+ result = crosstab(a, c)
+ expected = crosstab(df["a"], df["c"])
+ expected.index.names = ["row_0"]
+ expected.columns.names = ["col_0"]
+ tm.assert_frame_equal(result, expected)
+
+ def test_crosstab_non_aligned(self):
+ # GH 17005
+ a = Series([0, 1, 1], index=["a", "b", "c"])
+ b = Series([3, 4, 3, 4, 3], index=["a", "b", "c", "d", "f"])
+ c = np.array([3, 4, 3], dtype=np.int64)
+
+ expected = DataFrame(
+ [[1, 0], [1, 1]],
+ index=Index([0, 1], name="row_0"),
+ columns=Index([3, 4], name="col_0"),
+ )
+
+ result = crosstab(a, b)
+ tm.assert_frame_equal(result, expected)
+
+ result = crosstab(a, c)
+ tm.assert_frame_equal(result, expected)
+
+ def test_crosstab_margins(self):
+ a = np.random.default_rng(2).integers(0, 7, size=100)
+ b = np.random.default_rng(2).integers(0, 3, size=100)
+ c = np.random.default_rng(2).integers(0, 5, size=100)
+
+ df = DataFrame({"a": a, "b": b, "c": c})
+
+ result = crosstab(a, [b, c], rownames=["a"], colnames=("b", "c"), margins=True)
+
+ assert result.index.names == ("a",)
+ assert result.columns.names == ["b", "c"]
+
+ all_cols = result["All", ""]
+ exp_cols = df.groupby(["a"]).size().astype("i8")
+ # to keep index.name
+ exp_margin = Series([len(df)], index=Index(["All"], name="a"))
+ exp_cols = pd.concat([exp_cols, exp_margin])
+ exp_cols.name = ("All", "")
+
+ tm.assert_series_equal(all_cols, exp_cols)
+
+ all_rows = result.loc["All"]
+ exp_rows = df.groupby(["b", "c"]).size().astype("i8")
+ exp_rows = pd.concat([exp_rows, Series([len(df)], index=[("All", "")])])
+ exp_rows.name = "All"
+
+ exp_rows = exp_rows.reindex(all_rows.index)
+ exp_rows = exp_rows.fillna(0).astype(np.int64)
+ tm.assert_series_equal(all_rows, exp_rows)
+
+ def test_crosstab_margins_set_margin_name(self):
+ # GH 15972
+ a = np.random.default_rng(2).integers(0, 7, size=100)
+ b = np.random.default_rng(2).integers(0, 3, size=100)
+ c = np.random.default_rng(2).integers(0, 5, size=100)
+
+ df = DataFrame({"a": a, "b": b, "c": c})
+
+ result = crosstab(
+ a,
+ [b, c],
+ rownames=["a"],
+ colnames=("b", "c"),
+ margins=True,
+ margins_name="TOTAL",
+ )
+
+ assert result.index.names == ("a",)
+ assert result.columns.names == ["b", "c"]
+
+ all_cols = result["TOTAL", ""]
+ exp_cols = df.groupby(["a"]).size().astype("i8")
+ # to keep index.name
+ exp_margin = Series([len(df)], index=Index(["TOTAL"], name="a"))
+ exp_cols = pd.concat([exp_cols, exp_margin])
+ exp_cols.name = ("TOTAL", "")
+
+ tm.assert_series_equal(all_cols, exp_cols)
+
+ all_rows = result.loc["TOTAL"]
+ exp_rows = df.groupby(["b", "c"]).size().astype("i8")
+ exp_rows = pd.concat([exp_rows, Series([len(df)], index=[("TOTAL", "")])])
+ exp_rows.name = "TOTAL"
+
+ exp_rows = exp_rows.reindex(all_rows.index)
+ exp_rows = exp_rows.fillna(0).astype(np.int64)
+ tm.assert_series_equal(all_rows, exp_rows)
+
+ msg = "margins_name argument must be a string"
+ for margins_name in [666, None, ["a", "b"]]:
+ with pytest.raises(ValueError, match=msg):
+ crosstab(
+ a,
+ [b, c],
+ rownames=["a"],
+ colnames=("b", "c"),
+ margins=True,
+ margins_name=margins_name,
+ )
+
+ def test_crosstab_pass_values(self):
+ a = np.random.default_rng(2).integers(0, 7, size=100)
+ b = np.random.default_rng(2).integers(0, 3, size=100)
+ c = np.random.default_rng(2).integers(0, 5, size=100)
+ values = np.random.default_rng(2).standard_normal(100)
+
+ table = crosstab(
+ [a, b], c, values, aggfunc="sum", rownames=["foo", "bar"], colnames=["baz"]
+ )
+
+ df = DataFrame({"foo": a, "bar": b, "baz": c, "values": values})
+
+ expected = df.pivot_table(
+ "values", index=["foo", "bar"], columns="baz", aggfunc="sum"
+ )
+ tm.assert_frame_equal(table, expected)
+
+ def test_crosstab_dropna(self):
+ # GH 3820
+ a = np.array(["foo", "foo", "foo", "bar", "bar", "foo", "foo"], dtype=object)
+ b = np.array(["one", "one", "two", "one", "two", "two", "two"], dtype=object)
+ c = np.array(
+ ["dull", "dull", "dull", "dull", "dull", "shiny", "shiny"], dtype=object
+ )
+ res = crosstab(a, [b, c], rownames=["a"], colnames=["b", "c"], dropna=False)
+ m = MultiIndex.from_tuples(
+ [("one", "dull"), ("one", "shiny"), ("two", "dull"), ("two", "shiny")],
+ names=["b", "c"],
+ )
+ tm.assert_index_equal(res.columns, m)
+
+ def test_crosstab_no_overlap(self):
+ # GS 10291
+
+ s1 = Series([1, 2, 3], index=[1, 2, 3])
+ s2 = Series([4, 5, 6], index=[4, 5, 6])
+
+ actual = crosstab(s1, s2)
+ expected = DataFrame(
+ index=Index([], dtype="int64", name="row_0"),
+ columns=Index([], dtype="int64", name="col_0"),
+ )
+
+ tm.assert_frame_equal(actual, expected)
+
+ def test_margin_dropna(self):
+ # GH 12577
+ # pivot_table counts null into margin ('All')
+ # when margins=true and dropna=true
+
+ df = DataFrame({"a": [1, 2, 2, 2, 2, np.nan], "b": [3, 3, 4, 4, 4, 4]})
+ actual = crosstab(df.a, df.b, margins=True, dropna=True)
+ expected = DataFrame([[1, 0, 1], [1, 3, 4], [2, 3, 5]])
+ expected.index = Index([1.0, 2.0, "All"], name="a")
+ expected.columns = Index([3, 4, "All"], name="b")
+ tm.assert_frame_equal(actual, expected)
+
+ def test_margin_dropna2(self):
+ df = DataFrame(
+ {"a": [1, np.nan, np.nan, np.nan, 2, np.nan], "b": [3, np.nan, 4, 4, 4, 4]}
+ )
+ actual = crosstab(df.a, df.b, margins=True, dropna=True)
+ expected = DataFrame([[1, 0, 1], [0, 1, 1], [1, 1, 2]])
+ expected.index = Index([1.0, 2.0, "All"], name="a")
+ expected.columns = Index([3.0, 4.0, "All"], name="b")
+ tm.assert_frame_equal(actual, expected)
+
+ def test_margin_dropna3(self):
+ df = DataFrame(
+ {"a": [1, np.nan, np.nan, np.nan, np.nan, 2], "b": [3, 3, 4, 4, 4, 4]}
+ )
+ actual = crosstab(df.a, df.b, margins=True, dropna=True)
+ expected = DataFrame([[1, 0, 1], [0, 1, 1], [1, 1, 2]])
+ expected.index = Index([1.0, 2.0, "All"], name="a")
+ expected.columns = Index([3, 4, "All"], name="b")
+ tm.assert_frame_equal(actual, expected)
+
+ def test_margin_dropna4(self):
+ # GH 12642
+ # _add_margins raises KeyError: Level None not found
+ # when margins=True and dropna=False
+ # GH: 10772: Keep np.nan in result with dropna=False
+ df = DataFrame({"a": [1, 2, 2, 2, 2, np.nan], "b": [3, 3, 4, 4, 4, 4]})
+ actual = crosstab(df.a, df.b, margins=True, dropna=False)
+ expected = DataFrame([[1, 0, 1.0], [1, 3, 4.0], [0, 1, np.nan], [2, 4, 6.0]])
+ expected.index = Index([1.0, 2.0, np.nan, "All"], name="a")
+ expected.columns = Index([3, 4, "All"], name="b")
+ tm.assert_frame_equal(actual, expected)
+
+ def test_margin_dropna5(self):
+ # GH: 10772: Keep np.nan in result with dropna=False
+ df = DataFrame(
+ {"a": [1, np.nan, np.nan, np.nan, 2, np.nan], "b": [3, np.nan, 4, 4, 4, 4]}
+ )
+ actual = crosstab(df.a, df.b, margins=True, dropna=False)
+ expected = DataFrame(
+ [[1, 0, 0, 1.0], [0, 1, 0, 1.0], [0, 3, 1, np.nan], [1, 4, 0, 6.0]]
+ )
+ expected.index = Index([1.0, 2.0, np.nan, "All"], name="a")
+ expected.columns = Index([3.0, 4.0, np.nan, "All"], name="b")
+ tm.assert_frame_equal(actual, expected)
+
+ def test_margin_dropna6(self):
+ # GH: 10772: Keep np.nan in result with dropna=False
+ a = np.array(["foo", "foo", "foo", "bar", "bar", "foo", "foo"], dtype=object)
+ b = np.array(["one", "one", "two", "one", "two", np.nan, "two"], dtype=object)
+ c = np.array(
+ ["dull", "dull", "dull", "dull", "dull", "shiny", "shiny"], dtype=object
+ )
+
+ actual = crosstab(
+ a, [b, c], rownames=["a"], colnames=["b", "c"], margins=True, dropna=False
+ )
+ m = MultiIndex.from_arrays(
+ [
+ ["one", "one", "two", "two", np.nan, np.nan, "All"],
+ ["dull", "shiny", "dull", "shiny", "dull", "shiny", ""],
+ ],
+ names=["b", "c"],
+ )
+ expected = DataFrame(
+ [[1, 0, 1, 0, 0, 0, 2], [2, 0, 1, 1, 0, 1, 5], [3, 0, 2, 1, 0, 0, 7]],
+ columns=m,
+ )
+ expected.index = Index(["bar", "foo", "All"], name="a")
+ tm.assert_frame_equal(actual, expected)
+
+ actual = crosstab(
+ [a, b], c, rownames=["a", "b"], colnames=["c"], margins=True, dropna=False
+ )
+ m = MultiIndex.from_arrays(
+ [
+ ["bar", "bar", "bar", "foo", "foo", "foo", "All"],
+ ["one", "two", np.nan, "one", "two", np.nan, ""],
+ ],
+ names=["a", "b"],
+ )
+ expected = DataFrame(
+ [
+ [1, 0, 1.0],
+ [1, 0, 1.0],
+ [0, 0, np.nan],
+ [2, 0, 2.0],
+ [1, 1, 2.0],
+ [0, 1, np.nan],
+ [5, 2, 7.0],
+ ],
+ index=m,
+ )
+ expected.columns = Index(["dull", "shiny", "All"], name="c")
+ tm.assert_frame_equal(actual, expected)
+
+ actual = crosstab(
+ [a, b], c, rownames=["a", "b"], colnames=["c"], margins=True, dropna=True
+ )
+ m = MultiIndex.from_arrays(
+ [["bar", "bar", "foo", "foo", "All"], ["one", "two", "one", "two", ""]],
+ names=["a", "b"],
+ )
+ expected = DataFrame(
+ [[1, 0, 1], [1, 0, 1], [2, 0, 2], [1, 1, 2], [5, 1, 6]], index=m
+ )
+ expected.columns = Index(["dull", "shiny", "All"], name="c")
+ tm.assert_frame_equal(actual, expected)
+
+ def test_crosstab_normalize(self):
+ # Issue 12578
+ df = DataFrame(
+ {"a": [1, 2, 2, 2, 2], "b": [3, 3, 4, 4, 4], "c": [1, 1, np.nan, 1, 1]}
+ )
+
+ rindex = Index([1, 2], name="a")
+ cindex = Index([3, 4], name="b")
+ full_normal = DataFrame([[0.2, 0], [0.2, 0.6]], index=rindex, columns=cindex)
+ row_normal = DataFrame([[1.0, 0], [0.25, 0.75]], index=rindex, columns=cindex)
+ col_normal = DataFrame([[0.5, 0], [0.5, 1.0]], index=rindex, columns=cindex)
+
+ # Check all normalize args
+ tm.assert_frame_equal(crosstab(df.a, df.b, normalize="all"), full_normal)
+ tm.assert_frame_equal(crosstab(df.a, df.b, normalize=True), full_normal)
+ tm.assert_frame_equal(crosstab(df.a, df.b, normalize="index"), row_normal)
+ tm.assert_frame_equal(crosstab(df.a, df.b, normalize="columns"), col_normal)
+ tm.assert_frame_equal(
+ crosstab(df.a, df.b, normalize=1),
+ crosstab(df.a, df.b, normalize="columns"),
+ )
+ tm.assert_frame_equal(
+ crosstab(df.a, df.b, normalize=0), crosstab(df.a, df.b, normalize="index")
+ )
+
+ row_normal_margins = DataFrame(
+ [[1.0, 0], [0.25, 0.75], [0.4, 0.6]],
+ index=Index([1, 2, "All"], name="a", dtype="object"),
+ columns=Index([3, 4], name="b", dtype="object"),
+ )
+ col_normal_margins = DataFrame(
+ [[0.5, 0, 0.2], [0.5, 1.0, 0.8]],
+ index=Index([1, 2], name="a", dtype="object"),
+ columns=Index([3, 4, "All"], name="b", dtype="object"),
+ )
+
+ all_normal_margins = DataFrame(
+ [[0.2, 0, 0.2], [0.2, 0.6, 0.8], [0.4, 0.6, 1]],
+ index=Index([1, 2, "All"], name="a", dtype="object"),
+ columns=Index([3, 4, "All"], name="b", dtype="object"),
+ )
+ tm.assert_frame_equal(
+ crosstab(df.a, df.b, normalize="index", margins=True), row_normal_margins
+ )
+ tm.assert_frame_equal(
+ crosstab(df.a, df.b, normalize="columns", margins=True), col_normal_margins
+ )
+ tm.assert_frame_equal(
+ crosstab(df.a, df.b, normalize=True, margins=True), all_normal_margins
+ )
+
+ def test_crosstab_normalize_arrays(self):
+ # GH#12578
+ df = DataFrame(
+ {"a": [1, 2, 2, 2, 2], "b": [3, 3, 4, 4, 4], "c": [1, 1, np.nan, 1, 1]}
+ )
+
+ # Test arrays
+ crosstab(
+ [np.array([1, 1, 2, 2]), np.array([1, 2, 1, 2])], np.array([1, 2, 1, 2])
+ )
+
+ # Test with aggfunc
+ norm_counts = DataFrame(
+ [[0.25, 0, 0.25], [0.25, 0.5, 0.75], [0.5, 0.5, 1]],
+ index=Index([1, 2, "All"], name="a", dtype="object"),
+ columns=Index([3, 4, "All"], name="b"),
+ )
+ test_case = crosstab(
+ df.a, df.b, df.c, aggfunc="count", normalize="all", margins=True
+ )
+ tm.assert_frame_equal(test_case, norm_counts)
+
+ df = DataFrame(
+ {"a": [1, 2, 2, 2, 2], "b": [3, 3, 4, 4, 4], "c": [0, 4, np.nan, 3, 3]}
+ )
+
+ norm_sum = DataFrame(
+ [[0, 0, 0.0], [0.4, 0.6, 1], [0.4, 0.6, 1]],
+ index=Index([1, 2, "All"], name="a", dtype="object"),
+ columns=Index([3, 4, "All"], name="b", dtype="object"),
+ )
+ msg = "using DataFrameGroupBy.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ test_case = crosstab(
+ df.a, df.b, df.c, aggfunc=np.sum, normalize="all", margins=True
+ )
+ tm.assert_frame_equal(test_case, norm_sum)
+
+ def test_crosstab_with_empties(self, using_array_manager):
+ # Check handling of empties
+ df = DataFrame(
+ {
+ "a": [1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4],
+ "c": [np.nan, np.nan, np.nan, np.nan, np.nan],
+ }
+ )
+
+ empty = DataFrame(
+ [[0.0, 0.0], [0.0, 0.0]],
+ index=Index([1, 2], name="a", dtype="int64"),
+ columns=Index([3, 4], name="b"),
+ )
+
+ for i in [True, "index", "columns"]:
+ calculated = crosstab(df.a, df.b, values=df.c, aggfunc="count", normalize=i)
+ tm.assert_frame_equal(empty, calculated)
+
+ nans = DataFrame(
+ [[0.0, np.nan], [0.0, 0.0]],
+ index=Index([1, 2], name="a", dtype="int64"),
+ columns=Index([3, 4], name="b"),
+ )
+ if using_array_manager:
+ # INFO(ArrayManager) column without NaNs can preserve int dtype
+ nans[3] = nans[3].astype("int64")
+
+ calculated = crosstab(df.a, df.b, values=df.c, aggfunc="count", normalize=False)
+ tm.assert_frame_equal(nans, calculated)
+
+ def test_crosstab_errors(self):
+ # Issue 12578
+
+ df = DataFrame(
+ {"a": [1, 2, 2, 2, 2], "b": [3, 3, 4, 4, 4], "c": [1, 1, np.nan, 1, 1]}
+ )
+
+ error = "values cannot be used without an aggfunc."
+ with pytest.raises(ValueError, match=error):
+ crosstab(df.a, df.b, values=df.c)
+
+ error = "aggfunc cannot be used without values"
+ with pytest.raises(ValueError, match=error):
+ crosstab(df.a, df.b, aggfunc=np.mean)
+
+ error = "Not a valid normalize argument"
+ with pytest.raises(ValueError, match=error):
+ crosstab(df.a, df.b, normalize="42")
+
+ with pytest.raises(ValueError, match=error):
+ crosstab(df.a, df.b, normalize=42)
+
+ error = "Not a valid margins argument"
+ with pytest.raises(ValueError, match=error):
+ crosstab(df.a, df.b, normalize="all", margins=42)
+
+ def test_crosstab_with_categorial_columns(self):
+ # GH 8860
+ df = DataFrame(
+ {
+ "MAKE": ["Honda", "Acura", "Tesla", "Honda", "Honda", "Acura"],
+ "MODEL": ["Sedan", "Sedan", "Electric", "Pickup", "Sedan", "Sedan"],
+ }
+ )
+ categories = ["Sedan", "Electric", "Pickup"]
+ df["MODEL"] = df["MODEL"].astype("category").cat.set_categories(categories)
+ result = crosstab(df["MAKE"], df["MODEL"])
+
+ expected_index = Index(["Acura", "Honda", "Tesla"], name="MAKE")
+ expected_columns = CategoricalIndex(
+ categories, categories=categories, ordered=False, name="MODEL"
+ )
+ expected_data = [[2, 0, 0], [2, 0, 1], [0, 1, 0]]
+ expected = DataFrame(
+ expected_data, index=expected_index, columns=expected_columns
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_crosstab_with_numpy_size(self):
+ # GH 4003
+ df = DataFrame(
+ {
+ "A": ["one", "one", "two", "three"] * 6,
+ "B": ["A", "B", "C"] * 8,
+ "C": ["foo", "foo", "foo", "bar", "bar", "bar"] * 4,
+ "D": np.random.default_rng(2).standard_normal(24),
+ "E": np.random.default_rng(2).standard_normal(24),
+ }
+ )
+ result = crosstab(
+ index=[df["A"], df["B"]],
+ columns=[df["C"]],
+ margins=True,
+ aggfunc=np.size,
+ values=df["D"],
+ )
+ expected_index = MultiIndex(
+ levels=[["All", "one", "three", "two"], ["", "A", "B", "C"]],
+ codes=[[1, 1, 1, 2, 2, 2, 3, 3, 3, 0], [1, 2, 3, 1, 2, 3, 1, 2, 3, 0]],
+ names=["A", "B"],
+ )
+ expected_column = Index(["bar", "foo", "All"], dtype="object", name="C")
+ expected_data = np.array(
+ [
+ [2.0, 2.0, 4.0],
+ [2.0, 2.0, 4.0],
+ [2.0, 2.0, 4.0],
+ [2.0, np.nan, 2.0],
+ [np.nan, 2.0, 2.0],
+ [2.0, np.nan, 2.0],
+ [np.nan, 2.0, 2.0],
+ [2.0, np.nan, 2.0],
+ [np.nan, 2.0, 2.0],
+ [12.0, 12.0, 24.0],
+ ]
+ )
+ expected = DataFrame(
+ expected_data, index=expected_index, columns=expected_column
+ )
+ # aggfunc is np.size, resulting in integers
+ expected["All"] = expected["All"].astype("int64")
+ tm.assert_frame_equal(result, expected)
+
+ def test_crosstab_duplicate_names(self):
+ # GH 13279 / 22529
+
+ s1 = Series(range(3), name="foo")
+ s2_foo = Series(range(1, 4), name="foo")
+ s2_bar = Series(range(1, 4), name="bar")
+ s3 = Series(range(3), name="waldo")
+
+ # check result computed with duplicate labels against
+ # result computed with unique labels, then relabelled
+ mapper = {"bar": "foo"}
+
+ # duplicate row, column labels
+ result = crosstab(s1, s2_foo)
+ expected = crosstab(s1, s2_bar).rename_axis(columns=mapper, axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ # duplicate row, unique column labels
+ result = crosstab([s1, s2_foo], s3)
+ expected = crosstab([s1, s2_bar], s3).rename_axis(index=mapper, axis=0)
+ tm.assert_frame_equal(result, expected)
+
+ # unique row, duplicate column labels
+ result = crosstab(s3, [s1, s2_foo])
+ expected = crosstab(s3, [s1, s2_bar]).rename_axis(columns=mapper, axis=1)
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("names", [["a", ("b", "c")], [("a", "b"), "c"]])
+ def test_crosstab_tuple_name(self, names):
+ s1 = Series(range(3), name=names[0])
+ s2 = Series(range(1, 4), name=names[1])
+
+ mi = MultiIndex.from_arrays([range(3), range(1, 4)], names=names)
+ expected = Series(1, index=mi).unstack(1, fill_value=0)
+
+ result = crosstab(s1, s2)
+ tm.assert_frame_equal(result, expected)
+
+ def test_crosstab_both_tuple_names(self):
+ # GH 18321
+ s1 = Series(range(3), name=("a", "b"))
+ s2 = Series(range(3), name=("c", "d"))
+
+ expected = DataFrame(
+ np.eye(3, dtype="int64"),
+ index=Index(range(3), name=("a", "b")),
+ columns=Index(range(3), name=("c", "d")),
+ )
+ result = crosstab(s1, s2)
+ tm.assert_frame_equal(result, expected)
+
+ def test_crosstab_unsorted_order(self):
+ df = DataFrame({"b": [3, 1, 2], "a": [5, 4, 6]}, index=["C", "A", "B"])
+ result = crosstab(df.index, [df.b, df.a])
+ e_idx = Index(["A", "B", "C"], name="row_0")
+ e_columns = MultiIndex.from_tuples([(1, 4), (2, 6), (3, 5)], names=["b", "a"])
+ expected = DataFrame(
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]], index=e_idx, columns=e_columns
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_crosstab_normalize_multiple_columns(self):
+ # GH 15150
+ df = DataFrame(
+ {
+ "A": ["one", "one", "two", "three"] * 6,
+ "B": ["A", "B", "C"] * 8,
+ "C": ["foo", "foo", "foo", "bar", "bar", "bar"] * 4,
+ "D": [0] * 24,
+ "E": [0] * 24,
+ }
+ )
+
+ msg = "using DataFrameGroupBy.sum"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = crosstab(
+ [df.A, df.B],
+ df.C,
+ values=df.D,
+ aggfunc=np.sum,
+ normalize=True,
+ margins=True,
+ )
+ expected = DataFrame(
+ np.array([0] * 29 + [1], dtype=float).reshape(10, 3),
+ columns=Index(["bar", "foo", "All"], dtype="object", name="C"),
+ index=MultiIndex.from_tuples(
+ [
+ ("one", "A"),
+ ("one", "B"),
+ ("one", "C"),
+ ("three", "A"),
+ ("three", "B"),
+ ("three", "C"),
+ ("two", "A"),
+ ("two", "B"),
+ ("two", "C"),
+ ("All", ""),
+ ],
+ names=["A", "B"],
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_margin_normalize(self):
+ # GH 27500
+ df = DataFrame(
+ {
+ "A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
+ "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"],
+ "C": [
+ "small",
+ "large",
+ "large",
+ "small",
+ "small",
+ "large",
+ "small",
+ "small",
+ "large",
+ ],
+ "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
+ "E": [2, 4, 5, 5, 6, 6, 8, 9, 9],
+ }
+ )
+ # normalize on index
+ result = crosstab(
+ [df.A, df.B], df.C, margins=True, margins_name="Sub-Total", normalize=0
+ )
+ expected = DataFrame(
+ [[0.5, 0.5], [0.5, 0.5], [0.666667, 0.333333], [0, 1], [0.444444, 0.555556]]
+ )
+ expected.index = MultiIndex(
+ levels=[["Sub-Total", "bar", "foo"], ["", "one", "two"]],
+ codes=[[1, 1, 2, 2, 0], [1, 2, 1, 2, 0]],
+ names=["A", "B"],
+ )
+ expected.columns = Index(["large", "small"], dtype="object", name="C")
+ tm.assert_frame_equal(result, expected)
+
+ # normalize on columns
+ result = crosstab(
+ [df.A, df.B], df.C, margins=True, margins_name="Sub-Total", normalize=1
+ )
+ expected = DataFrame(
+ [
+ [0.25, 0.2, 0.222222],
+ [0.25, 0.2, 0.222222],
+ [0.5, 0.2, 0.333333],
+ [0, 0.4, 0.222222],
+ ]
+ )
+ expected.columns = Index(
+ ["large", "small", "Sub-Total"], dtype="object", name="C"
+ )
+ expected.index = MultiIndex(
+ levels=[["bar", "foo"], ["one", "two"]],
+ codes=[[0, 0, 1, 1], [0, 1, 0, 1]],
+ names=["A", "B"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # normalize on both index and column
+ result = crosstab(
+ [df.A, df.B], df.C, margins=True, margins_name="Sub-Total", normalize=True
+ )
+ expected = DataFrame(
+ [
+ [0.111111, 0.111111, 0.222222],
+ [0.111111, 0.111111, 0.222222],
+ [0.222222, 0.111111, 0.333333],
+ [0.000000, 0.222222, 0.222222],
+ [0.444444, 0.555555, 1],
+ ]
+ )
+ expected.columns = Index(
+ ["large", "small", "Sub-Total"], dtype="object", name="C"
+ )
+ expected.index = MultiIndex(
+ levels=[["Sub-Total", "bar", "foo"], ["", "one", "two"]],
+ codes=[[1, 1, 2, 2, 0], [1, 2, 1, 2, 0]],
+ names=["A", "B"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_margin_normalize_multiple_columns(self):
+ # GH 35144
+ # use multiple columns with margins and normalization
+ df = DataFrame(
+ {
+ "A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
+ "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"],
+ "C": [
+ "small",
+ "large",
+ "large",
+ "small",
+ "small",
+ "large",
+ "small",
+ "small",
+ "large",
+ ],
+ "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
+ "E": [2, 4, 5, 5, 6, 6, 8, 9, 9],
+ }
+ )
+ result = crosstab(
+ index=df.C,
+ columns=[df.A, df.B],
+ margins=True,
+ margins_name="margin",
+ normalize=True,
+ )
+ expected = DataFrame(
+ [
+ [0.111111, 0.111111, 0.222222, 0.000000, 0.444444],
+ [0.111111, 0.111111, 0.111111, 0.222222, 0.555556],
+ [0.222222, 0.222222, 0.333333, 0.222222, 1.0],
+ ],
+ index=["large", "small", "margin"],
+ )
+ expected.columns = MultiIndex(
+ levels=[["bar", "foo", "margin"], ["", "one", "two"]],
+ codes=[[0, 0, 1, 1, 2], [1, 2, 1, 2, 0]],
+ names=["A", "B"],
+ )
+ expected.index.name = "C"
+ tm.assert_frame_equal(result, expected)
+
+ def test_margin_support_Float(self):
+ # GH 50313
+ # use Float64 formats and function aggfunc with margins
+ df = DataFrame(
+ {"A": [1, 2, 2, 1], "B": [3, 3, 4, 5], "C": [-1.0, 10.0, 1.0, 10.0]},
+ dtype="Float64",
+ )
+ result = crosstab(
+ df["A"],
+ df["B"],
+ values=df["C"],
+ aggfunc="sum",
+ margins=True,
+ )
+ expected = DataFrame(
+ [
+ [-1.0, pd.NA, 10.0, 9.0],
+ [10.0, 1.0, pd.NA, 11.0],
+ [9.0, 1.0, 10.0, 20.0],
+ ],
+ index=Index([1.0, 2.0, "All"], dtype="object", name="A"),
+ columns=Index([3.0, 4.0, 5.0, "All"], dtype="object", name="B"),
+ dtype="Float64",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_margin_with_ordered_categorical_column(self):
+ # GH 25278
+ df = DataFrame(
+ {
+ "First": ["B", "B", "C", "A", "B", "C"],
+ "Second": ["C", "B", "B", "B", "C", "A"],
+ }
+ )
+ df["First"] = df["First"].astype(CategoricalDtype(ordered=True))
+ customized_categories_order = ["C", "A", "B"]
+ df["First"] = df["First"].cat.reorder_categories(customized_categories_order)
+ result = crosstab(df["First"], df["Second"], margins=True)
+
+ expected_index = Index(["C", "A", "B", "All"], name="First")
+ expected_columns = Index(["A", "B", "C", "All"], name="Second")
+ expected_data = [[1, 1, 0, 2], [0, 1, 0, 1], [0, 1, 2, 3], [1, 3, 2, 6]]
+ expected = DataFrame(
+ expected_data, index=expected_index, columns=expected_columns
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("a_dtype", ["category", "int64"])
+@pytest.mark.parametrize("b_dtype", ["category", "int64"])
+def test_categoricals(a_dtype, b_dtype):
+ # https://github.com/pandas-dev/pandas/issues/37465
+ g = np.random.default_rng(2)
+ a = Series(g.integers(0, 3, size=100)).astype(a_dtype)
+ b = Series(g.integers(0, 2, size=100)).astype(b_dtype)
+ result = crosstab(a, b, margins=True, dropna=False)
+ columns = Index([0, 1, "All"], dtype="object", name="col_0")
+ index = Index([0, 1, 2, "All"], dtype="object", name="row_0")
+ values = [[10, 18, 28], [23, 16, 39], [17, 16, 33], [50, 50, 100]]
+ expected = DataFrame(values, index, columns)
+ tm.assert_frame_equal(result, expected)
+
+ # Verify when categorical does not have all values present
+ a.loc[a == 1] = 2
+ a_is_cat = isinstance(a.dtype, CategoricalDtype)
+ assert not a_is_cat or a.value_counts().loc[1] == 0
+ result = crosstab(a, b, margins=True, dropna=False)
+ values = [[10, 18, 28], [0, 0, 0], [40, 32, 72], [50, 50, 100]]
+ expected = DataFrame(values, index, columns)
+ if not a_is_cat:
+ expected = expected.loc[[0, 2, "All"]]
+ expected["All"] = expected["All"].astype("int64")
+ repr(result)
+ repr(expected)
+ repr(expected.loc[[0, 2, "All"]])
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_cut.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_cut.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2a6ac49fdff2a26f659211294168af19eb4c403
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_cut.py
@@ -0,0 +1,761 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ Interval,
+ IntervalIndex,
+ Series,
+ TimedeltaIndex,
+ Timestamp,
+ cut,
+ date_range,
+ interval_range,
+ isna,
+ qcut,
+ timedelta_range,
+ to_datetime,
+)
+import pandas._testing as tm
+from pandas.api.types import CategoricalDtype as CDT
+import pandas.core.reshape.tile as tmod
+
+
+def test_simple():
+ data = np.ones(5, dtype="int64")
+ result = cut(data, 4, labels=False)
+
+ expected = np.array([1, 1, 1, 1, 1])
+ tm.assert_numpy_array_equal(result, expected, check_dtype=False)
+
+
+@pytest.mark.parametrize("func", [list, np.array])
+def test_bins(func):
+ data = func([0.2, 1.4, 2.5, 6.2, 9.7, 2.1])
+ result, bins = cut(data, 3, retbins=True)
+
+ intervals = IntervalIndex.from_breaks(bins.round(3))
+ intervals = intervals.take([0, 0, 0, 1, 2, 0])
+ expected = Categorical(intervals, ordered=True)
+
+ tm.assert_categorical_equal(result, expected)
+ tm.assert_almost_equal(bins, np.array([0.1905, 3.36666667, 6.53333333, 9.7]))
+
+
+def test_right():
+ data = np.array([0.2, 1.4, 2.5, 6.2, 9.7, 2.1, 2.575])
+ result, bins = cut(data, 4, right=True, retbins=True)
+
+ intervals = IntervalIndex.from_breaks(bins.round(3))
+ expected = Categorical(intervals, ordered=True)
+ expected = expected.take([0, 0, 0, 2, 3, 0, 0])
+
+ tm.assert_categorical_equal(result, expected)
+ tm.assert_almost_equal(bins, np.array([0.1905, 2.575, 4.95, 7.325, 9.7]))
+
+
+def test_no_right():
+ data = np.array([0.2, 1.4, 2.5, 6.2, 9.7, 2.1, 2.575])
+ result, bins = cut(data, 4, right=False, retbins=True)
+
+ intervals = IntervalIndex.from_breaks(bins.round(3), closed="left")
+ intervals = intervals.take([0, 0, 0, 2, 3, 0, 1])
+ expected = Categorical(intervals, ordered=True)
+
+ tm.assert_categorical_equal(result, expected)
+ tm.assert_almost_equal(bins, np.array([0.2, 2.575, 4.95, 7.325, 9.7095]))
+
+
+def test_bins_from_interval_index():
+ c = cut(range(5), 3)
+ expected = c
+ result = cut(range(5), bins=expected.categories)
+ tm.assert_categorical_equal(result, expected)
+
+ expected = Categorical.from_codes(
+ np.append(c.codes, -1), categories=c.categories, ordered=True
+ )
+ result = cut(range(6), bins=expected.categories)
+ tm.assert_categorical_equal(result, expected)
+
+
+def test_bins_from_interval_index_doc_example():
+ # Make sure we preserve the bins.
+ ages = np.array([10, 15, 13, 12, 23, 25, 28, 59, 60])
+ c = cut(ages, bins=[0, 18, 35, 70])
+ expected = IntervalIndex.from_tuples([(0, 18), (18, 35), (35, 70)])
+ tm.assert_index_equal(c.categories, expected)
+
+ result = cut([25, 20, 50], bins=c.categories)
+ tm.assert_index_equal(result.categories, expected)
+ tm.assert_numpy_array_equal(result.codes, np.array([1, 1, 2], dtype="int8"))
+
+
+def test_bins_not_overlapping_from_interval_index():
+ # see gh-23980
+ msg = "Overlapping IntervalIndex is not accepted"
+ ii = IntervalIndex.from_tuples([(0, 10), (2, 12), (4, 14)])
+
+ with pytest.raises(ValueError, match=msg):
+ cut([5, 6], bins=ii)
+
+
+def test_bins_not_monotonic():
+ msg = "bins must increase monotonically"
+ data = [0.2, 1.4, 2.5, 6.2, 9.7, 2.1]
+
+ with pytest.raises(ValueError, match=msg):
+ cut(data, [0.1, 1.5, 1, 10])
+
+
+@pytest.mark.parametrize(
+ "x, bins, expected",
+ [
+ (
+ date_range("2017-12-31", periods=3),
+ [Timestamp.min, Timestamp("2018-01-01"), Timestamp.max],
+ IntervalIndex.from_tuples(
+ [
+ (Timestamp.min, Timestamp("2018-01-01")),
+ (Timestamp("2018-01-01"), Timestamp.max),
+ ]
+ ),
+ ),
+ (
+ [-1, 0, 1],
+ np.array(
+ [np.iinfo(np.int64).min, 0, np.iinfo(np.int64).max], dtype="int64"
+ ),
+ IntervalIndex.from_tuples(
+ [(np.iinfo(np.int64).min, 0), (0, np.iinfo(np.int64).max)]
+ ),
+ ),
+ (
+ [
+ np.timedelta64(-1, "ns"),
+ np.timedelta64(0, "ns"),
+ np.timedelta64(1, "ns"),
+ ],
+ np.array(
+ [
+ np.timedelta64(-np.iinfo(np.int64).max, "ns"),
+ np.timedelta64(0, "ns"),
+ np.timedelta64(np.iinfo(np.int64).max, "ns"),
+ ]
+ ),
+ IntervalIndex.from_tuples(
+ [
+ (
+ np.timedelta64(-np.iinfo(np.int64).max, "ns"),
+ np.timedelta64(0, "ns"),
+ ),
+ (
+ np.timedelta64(0, "ns"),
+ np.timedelta64(np.iinfo(np.int64).max, "ns"),
+ ),
+ ]
+ ),
+ ),
+ ],
+)
+def test_bins_monotonic_not_overflowing(x, bins, expected):
+ # GH 26045
+ result = cut(x, bins)
+ tm.assert_index_equal(result.categories, expected)
+
+
+def test_wrong_num_labels():
+ msg = "Bin labels must be one fewer than the number of bin edges"
+ data = [0.2, 1.4, 2.5, 6.2, 9.7, 2.1]
+
+ with pytest.raises(ValueError, match=msg):
+ cut(data, [0, 1, 10], labels=["foo", "bar", "baz"])
+
+
+@pytest.mark.parametrize(
+ "x,bins,msg",
+ [
+ ([], 2, "Cannot cut empty array"),
+ ([1, 2, 3], 0.5, "`bins` should be a positive integer"),
+ ],
+)
+def test_cut_corner(x, bins, msg):
+ with pytest.raises(ValueError, match=msg):
+ cut(x, bins)
+
+
+@pytest.mark.parametrize("arg", [2, np.eye(2), DataFrame(np.eye(2))])
+@pytest.mark.parametrize("cut_func", [cut, qcut])
+def test_cut_not_1d_arg(arg, cut_func):
+ msg = "Input array must be 1 dimensional"
+ with pytest.raises(ValueError, match=msg):
+ cut_func(arg, 2)
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ [0, 1, 2, 3, 4, np.inf],
+ [-np.inf, 0, 1, 2, 3, 4],
+ [-np.inf, 0, 1, 2, 3, 4, np.inf],
+ ],
+)
+def test_int_bins_with_inf(data):
+ # GH 24314
+ msg = "cannot specify integer `bins` when input data contains infinity"
+ with pytest.raises(ValueError, match=msg):
+ cut(data, bins=3)
+
+
+def test_cut_out_of_range_more():
+ # see gh-1511
+ name = "x"
+
+ ser = Series([0, -1, 0, 1, -3], name=name)
+ ind = cut(ser, [0, 1], labels=False)
+
+ exp = Series([np.nan, np.nan, np.nan, 0, np.nan], name=name)
+ tm.assert_series_equal(ind, exp)
+
+
+@pytest.mark.parametrize(
+ "right,breaks,closed",
+ [
+ (True, [-1e-3, 0.25, 0.5, 0.75, 1], "right"),
+ (False, [0, 0.25, 0.5, 0.75, 1 + 1e-3], "left"),
+ ],
+)
+def test_labels(right, breaks, closed):
+ arr = np.tile(np.arange(0, 1.01, 0.1), 4)
+
+ result, bins = cut(arr, 4, retbins=True, right=right)
+ ex_levels = IntervalIndex.from_breaks(breaks, closed=closed)
+ tm.assert_index_equal(result.categories, ex_levels)
+
+
+def test_cut_pass_series_name_to_factor():
+ name = "foo"
+ ser = Series(np.random.default_rng(2).standard_normal(100), name=name)
+
+ factor = cut(ser, 4)
+ assert factor.name == name
+
+
+def test_label_precision():
+ arr = np.arange(0, 0.73, 0.01)
+ result = cut(arr, 4, precision=2)
+
+ ex_levels = IntervalIndex.from_breaks([-0.00072, 0.18, 0.36, 0.54, 0.72])
+ tm.assert_index_equal(result.categories, ex_levels)
+
+
+@pytest.mark.parametrize("labels", [None, False])
+def test_na_handling(labels):
+ arr = np.arange(0, 0.75, 0.01)
+ arr[::3] = np.nan
+
+ result = cut(arr, 4, labels=labels)
+ result = np.asarray(result)
+
+ expected = np.where(isna(arr), np.nan, result)
+ tm.assert_almost_equal(result, expected)
+
+
+def test_inf_handling():
+ data = np.arange(6)
+ data_ser = Series(data, dtype="int64")
+
+ bins = [-np.inf, 2, 4, np.inf]
+ result = cut(data, bins)
+ result_ser = cut(data_ser, bins)
+
+ ex_uniques = IntervalIndex.from_breaks(bins)
+ tm.assert_index_equal(result.categories, ex_uniques)
+
+ assert result[5] == Interval(4, np.inf)
+ assert result[0] == Interval(-np.inf, 2)
+ assert result_ser[5] == Interval(4, np.inf)
+ assert result_ser[0] == Interval(-np.inf, 2)
+
+
+def test_cut_out_of_bounds():
+ arr = np.random.default_rng(2).standard_normal(100)
+ result = cut(arr, [-1, 0, 1])
+
+ mask = isna(result)
+ ex_mask = (arr < -1) | (arr > 1)
+ tm.assert_numpy_array_equal(mask, ex_mask)
+
+
+@pytest.mark.parametrize(
+ "get_labels,get_expected",
+ [
+ (
+ lambda labels: labels,
+ lambda labels: Categorical(
+ ["Medium"] + 4 * ["Small"] + ["Medium", "Large"],
+ categories=labels,
+ ordered=True,
+ ),
+ ),
+ (
+ lambda labels: Categorical.from_codes([0, 1, 2], labels),
+ lambda labels: Categorical.from_codes([1] + 4 * [0] + [1, 2], labels),
+ ),
+ ],
+)
+def test_cut_pass_labels(get_labels, get_expected):
+ bins = [0, 25, 50, 100]
+ arr = [50, 5, 10, 15, 20, 30, 70]
+ labels = ["Small", "Medium", "Large"]
+
+ result = cut(arr, bins, labels=get_labels(labels))
+ tm.assert_categorical_equal(result, get_expected(labels))
+
+
+def test_cut_pass_labels_compat():
+ # see gh-16459
+ arr = [50, 5, 10, 15, 20, 30, 70]
+ labels = ["Good", "Medium", "Bad"]
+
+ result = cut(arr, 3, labels=labels)
+ exp = cut(arr, 3, labels=Categorical(labels, categories=labels, ordered=True))
+ tm.assert_categorical_equal(result, exp)
+
+
+@pytest.mark.parametrize("x", [np.arange(11.0), np.arange(11.0) / 1e10])
+def test_round_frac_just_works(x):
+ # It works.
+ cut(x, 2)
+
+
+@pytest.mark.parametrize(
+ "val,precision,expected",
+ [
+ (-117.9998, 3, -118),
+ (117.9998, 3, 118),
+ (117.9998, 2, 118),
+ (0.000123456, 2, 0.00012),
+ ],
+)
+def test_round_frac(val, precision, expected):
+ # see gh-1979
+ result = tmod._round_frac(val, precision=precision)
+ assert result == expected
+
+
+def test_cut_return_intervals():
+ ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8])
+ result = cut(ser, 3)
+
+ exp_bins = np.linspace(0, 8, num=4).round(3)
+ exp_bins[0] -= 0.008
+
+ expected = Series(
+ IntervalIndex.from_breaks(exp_bins, closed="right").take(
+ [0, 0, 0, 1, 1, 1, 2, 2, 2]
+ )
+ ).astype(CDT(ordered=True))
+ tm.assert_series_equal(result, expected)
+
+
+def test_series_ret_bins():
+ # see gh-8589
+ ser = Series(np.arange(4))
+ result, bins = cut(ser, 2, retbins=True)
+
+ expected = Series(
+ IntervalIndex.from_breaks([-0.003, 1.5, 3], closed="right").repeat(2)
+ ).astype(CDT(ordered=True))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "kwargs,msg",
+ [
+ ({"duplicates": "drop"}, None),
+ ({}, "Bin edges must be unique"),
+ ({"duplicates": "raise"}, "Bin edges must be unique"),
+ ({"duplicates": "foo"}, "invalid value for 'duplicates' parameter"),
+ ],
+)
+def test_cut_duplicates_bin(kwargs, msg):
+ # see gh-20947
+ bins = [0, 2, 4, 6, 10, 10]
+ values = Series(np.array([1, 3, 5, 7, 9]), index=["a", "b", "c", "d", "e"])
+
+ if msg is not None:
+ with pytest.raises(ValueError, match=msg):
+ cut(values, bins, **kwargs)
+ else:
+ result = cut(values, bins, **kwargs)
+ expected = cut(values, pd.unique(np.asarray(bins)))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("data", [9.0, -9.0, 0.0])
+@pytest.mark.parametrize("length", [1, 2])
+def test_single_bin(data, length):
+ # see gh-14652, gh-15428
+ ser = Series([data] * length)
+ result = cut(ser, 1, labels=False)
+
+ expected = Series([0] * length, dtype=np.intp)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "array_1_writeable,array_2_writeable", [(True, True), (True, False), (False, False)]
+)
+def test_cut_read_only(array_1_writeable, array_2_writeable):
+ # issue 18773
+ array_1 = np.arange(0, 100, 10)
+ array_1.flags.writeable = array_1_writeable
+
+ array_2 = np.arange(0, 100, 10)
+ array_2.flags.writeable = array_2_writeable
+
+ hundred_elements = np.arange(100)
+ tm.assert_categorical_equal(
+ cut(hundred_elements, array_1), cut(hundred_elements, array_2)
+ )
+
+
+@pytest.mark.parametrize(
+ "conv",
+ [
+ lambda v: Timestamp(v),
+ lambda v: to_datetime(v),
+ lambda v: np.datetime64(v),
+ lambda v: Timestamp(v).to_pydatetime(),
+ ],
+)
+def test_datetime_bin(conv):
+ data = [np.datetime64("2012-12-13"), np.datetime64("2012-12-15")]
+ bin_data = ["2012-12-12", "2012-12-14", "2012-12-16"]
+
+ expected = Series(
+ IntervalIndex(
+ [
+ Interval(Timestamp(bin_data[0]), Timestamp(bin_data[1])),
+ Interval(Timestamp(bin_data[1]), Timestamp(bin_data[2])),
+ ]
+ )
+ ).astype(CDT(ordered=True))
+
+ bins = [conv(v) for v in bin_data]
+ result = Series(cut(data, bins=bins))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ to_datetime(Series(["2013-01-01", "2013-01-02", "2013-01-03"])),
+ [
+ np.datetime64("2013-01-01"),
+ np.datetime64("2013-01-02"),
+ np.datetime64("2013-01-03"),
+ ],
+ np.array(
+ [
+ np.datetime64("2013-01-01"),
+ np.datetime64("2013-01-02"),
+ np.datetime64("2013-01-03"),
+ ]
+ ),
+ DatetimeIndex(["2013-01-01", "2013-01-02", "2013-01-03"]),
+ ],
+)
+def test_datetime_cut(data):
+ # see gh-14714
+ #
+ # Testing time data when it comes in various collection types.
+ result, _ = cut(data, 3, retbins=True)
+ expected = Series(
+ IntervalIndex(
+ [
+ Interval(
+ Timestamp("2012-12-31 23:57:07.200000"),
+ Timestamp("2013-01-01 16:00:00"),
+ ),
+ Interval(
+ Timestamp("2013-01-01 16:00:00"), Timestamp("2013-01-02 08:00:00")
+ ),
+ Interval(
+ Timestamp("2013-01-02 08:00:00"), Timestamp("2013-01-03 00:00:00")
+ ),
+ ]
+ )
+ ).astype(CDT(ordered=True))
+ tm.assert_series_equal(Series(result), expected)
+
+
+@pytest.mark.parametrize(
+ "bins",
+ [
+ 3,
+ [
+ Timestamp("2013-01-01 04:57:07.200000"),
+ Timestamp("2013-01-01 21:00:00"),
+ Timestamp("2013-01-02 13:00:00"),
+ Timestamp("2013-01-03 05:00:00"),
+ ],
+ ],
+)
+@pytest.mark.parametrize("box", [list, np.array, Index, Series])
+def test_datetime_tz_cut(bins, box):
+ # see gh-19872
+ tz = "US/Eastern"
+ s = Series(date_range("20130101", periods=3, tz=tz))
+
+ if not isinstance(bins, int):
+ bins = box(bins)
+
+ result = cut(s, bins)
+ expected = Series(
+ IntervalIndex(
+ [
+ Interval(
+ Timestamp("2012-12-31 23:57:07.200000", tz=tz),
+ Timestamp("2013-01-01 16:00:00", tz=tz),
+ ),
+ Interval(
+ Timestamp("2013-01-01 16:00:00", tz=tz),
+ Timestamp("2013-01-02 08:00:00", tz=tz),
+ ),
+ Interval(
+ Timestamp("2013-01-02 08:00:00", tz=tz),
+ Timestamp("2013-01-03 00:00:00", tz=tz),
+ ),
+ ]
+ )
+ ).astype(CDT(ordered=True))
+ tm.assert_series_equal(result, expected)
+
+
+def test_datetime_nan_error():
+ msg = "bins must be of datetime64 dtype"
+
+ with pytest.raises(ValueError, match=msg):
+ cut(date_range("20130101", periods=3), bins=[0, 2, 4])
+
+
+def test_datetime_nan_mask():
+ result = cut(
+ date_range("20130102", periods=5), bins=date_range("20130101", periods=2)
+ )
+
+ mask = result.categories.isna()
+ tm.assert_numpy_array_equal(mask, np.array([False]))
+
+ mask = result.isna()
+ tm.assert_numpy_array_equal(mask, np.array([False, True, True, True, True]))
+
+
+@pytest.mark.parametrize("tz", [None, "UTC", "US/Pacific"])
+def test_datetime_cut_roundtrip(tz):
+ # see gh-19891
+ ser = Series(date_range("20180101", periods=3, tz=tz))
+ result, result_bins = cut(ser, 2, retbins=True)
+
+ expected = cut(ser, result_bins)
+ tm.assert_series_equal(result, expected)
+
+ expected_bins = DatetimeIndex(
+ ["2017-12-31 23:57:07.200000", "2018-01-02 00:00:00", "2018-01-03 00:00:00"]
+ )
+ expected_bins = expected_bins.tz_localize(tz)
+ tm.assert_index_equal(result_bins, expected_bins)
+
+
+def test_timedelta_cut_roundtrip():
+ # see gh-19891
+ ser = Series(timedelta_range("1day", periods=3))
+ result, result_bins = cut(ser, 2, retbins=True)
+
+ expected = cut(ser, result_bins)
+ tm.assert_series_equal(result, expected)
+
+ expected_bins = TimedeltaIndex(
+ ["0 days 23:57:07.200000", "2 days 00:00:00", "3 days 00:00:00"]
+ )
+ tm.assert_index_equal(result_bins, expected_bins)
+
+
+@pytest.mark.parametrize("bins", [6, 7])
+@pytest.mark.parametrize(
+ "box, compare",
+ [
+ (Series, tm.assert_series_equal),
+ (np.array, tm.assert_categorical_equal),
+ (list, tm.assert_equal),
+ ],
+)
+def test_cut_bool_coercion_to_int(bins, box, compare):
+ # issue 20303
+ data_expected = box([0, 1, 1, 0, 1] * 10)
+ data_result = box([False, True, True, False, True] * 10)
+ expected = cut(data_expected, bins, duplicates="drop")
+ result = cut(data_result, bins, duplicates="drop")
+ compare(result, expected)
+
+
+@pytest.mark.parametrize("labels", ["foo", 1, True])
+def test_cut_incorrect_labels(labels):
+ # GH 13318
+ values = range(5)
+ msg = "Bin labels must either be False, None or passed in as a list-like argument"
+ with pytest.raises(ValueError, match=msg):
+ cut(values, 4, labels=labels)
+
+
+@pytest.mark.parametrize("bins", [3, [0, 5, 15]])
+@pytest.mark.parametrize("right", [True, False])
+@pytest.mark.parametrize("include_lowest", [True, False])
+def test_cut_nullable_integer(bins, right, include_lowest):
+ a = np.random.default_rng(2).integers(0, 10, size=50).astype(float)
+ a[::2] = np.nan
+ result = cut(
+ pd.array(a, dtype="Int64"), bins, right=right, include_lowest=include_lowest
+ )
+ expected = cut(a, bins, right=right, include_lowest=include_lowest)
+ tm.assert_categorical_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, bins, labels, expected_codes, expected_labels",
+ [
+ ([15, 17, 19], [14, 16, 18, 20], ["A", "B", "A"], [0, 1, 0], ["A", "B"]),
+ ([1, 3, 5], [0, 2, 4, 6, 8], [2, 0, 1, 2], [2, 0, 1], [0, 1, 2]),
+ ],
+)
+def test_cut_non_unique_labels(data, bins, labels, expected_codes, expected_labels):
+ # GH 33141
+ result = cut(data, bins=bins, labels=labels, ordered=False)
+ expected = Categorical.from_codes(
+ expected_codes, categories=expected_labels, ordered=False
+ )
+ tm.assert_categorical_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, bins, labels, expected_codes, expected_labels",
+ [
+ ([15, 17, 19], [14, 16, 18, 20], ["C", "B", "A"], [0, 1, 2], ["C", "B", "A"]),
+ ([1, 3, 5], [0, 2, 4, 6, 8], [3, 0, 1, 2], [0, 1, 2], [3, 0, 1, 2]),
+ ],
+)
+def test_cut_unordered_labels(data, bins, labels, expected_codes, expected_labels):
+ # GH 33141
+ result = cut(data, bins=bins, labels=labels, ordered=False)
+ expected = Categorical.from_codes(
+ expected_codes, categories=expected_labels, ordered=False
+ )
+ tm.assert_categorical_equal(result, expected)
+
+
+def test_cut_unordered_with_missing_labels_raises_error():
+ # GH 33141
+ msg = "'labels' must be provided if 'ordered = False'"
+ with pytest.raises(ValueError, match=msg):
+ cut([0.5, 3], bins=[0, 1, 2], ordered=False)
+
+
+def test_cut_unordered_with_series_labels():
+ # https://github.com/pandas-dev/pandas/issues/36603
+ s = Series([1, 2, 3, 4, 5])
+ bins = Series([0, 2, 4, 6])
+ labels = Series(["a", "b", "c"])
+ result = cut(s, bins=bins, labels=labels, ordered=False)
+ expected = Series(["a", "a", "b", "b", "c"], dtype="category")
+ tm.assert_series_equal(result, expected)
+
+
+def test_cut_no_warnings():
+ df = DataFrame({"value": np.random.default_rng(2).integers(0, 100, 20)})
+ labels = [f"{i} - {i + 9}" for i in range(0, 100, 10)]
+ with tm.assert_produces_warning(False):
+ df["group"] = cut(df.value, range(0, 105, 10), right=False, labels=labels)
+
+
+def test_cut_with_duplicated_index_lowest_included():
+ # GH 42185
+ expected = Series(
+ [Interval(-0.001, 2, closed="right")] * 3
+ + [Interval(2, 4, closed="right"), Interval(-0.001, 2, closed="right")],
+ index=[0, 1, 2, 3, 0],
+ dtype="category",
+ ).cat.as_ordered()
+
+ s = Series([0, 1, 2, 3, 0], index=[0, 1, 2, 3, 0])
+ result = cut(s, bins=[0, 2, 4], include_lowest=True)
+ tm.assert_series_equal(result, expected)
+
+
+def test_cut_with_nonexact_categorical_indices():
+ # GH 42424
+
+ ser = Series(range(0, 100))
+ ser1 = cut(ser, 10).value_counts().head(5)
+ ser2 = cut(ser, 10).value_counts().tail(5)
+ result = DataFrame({"1": ser1, "2": ser2})
+
+ index = pd.CategoricalIndex(
+ [
+ Interval(-0.099, 9.9, closed="right"),
+ Interval(9.9, 19.8, closed="right"),
+ Interval(19.8, 29.7, closed="right"),
+ Interval(29.7, 39.6, closed="right"),
+ Interval(39.6, 49.5, closed="right"),
+ Interval(49.5, 59.4, closed="right"),
+ Interval(59.4, 69.3, closed="right"),
+ Interval(69.3, 79.2, closed="right"),
+ Interval(79.2, 89.1, closed="right"),
+ Interval(89.1, 99, closed="right"),
+ ],
+ ordered=True,
+ )
+
+ expected = DataFrame(
+ {"1": [10] * 5 + [np.nan] * 5, "2": [np.nan] * 5 + [10] * 5}, index=index
+ )
+
+ tm.assert_frame_equal(expected, result)
+
+
+def test_cut_with_timestamp_tuple_labels():
+ # GH 40661
+ labels = [(Timestamp(10),), (Timestamp(20),), (Timestamp(30),)]
+ result = cut([2, 4, 6], bins=[1, 3, 5, 7], labels=labels)
+
+ expected = Categorical.from_codes([0, 1, 2], labels, ordered=True)
+ tm.assert_categorical_equal(result, expected)
+
+
+def test_cut_bins_datetime_intervalindex():
+ # https://github.com/pandas-dev/pandas/issues/46218
+ bins = interval_range(Timestamp("2022-02-25"), Timestamp("2022-02-27"), freq="1D")
+ # passing Series instead of list is important to trigger bug
+ result = cut(Series([Timestamp("2022-02-26")]), bins=bins)
+ expected = Categorical.from_codes([0], bins, ordered=True)
+ tm.assert_categorical_equal(result.array, expected)
+
+
+def test_cut_with_nullable_int64():
+ # GH 30787
+ series = Series([0, 1, 2, 3, 4, pd.NA, 6, 7], dtype="Int64")
+ bins = [0, 2, 4, 6, 8]
+ intervals = IntervalIndex.from_breaks(bins)
+
+ expected = Series(
+ Categorical.from_codes([-1, 0, 0, 1, 1, -1, 2, 3], intervals, ordered=True)
+ )
+
+ result = cut(series, bins=bins)
+
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_from_dummies.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_from_dummies.py
new file mode 100644
index 0000000000000000000000000000000000000000..0074a90d7a51e992b750bf1b249e0f521443f70e
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_from_dummies.py
@@ -0,0 +1,443 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Series,
+ from_dummies,
+ get_dummies,
+)
+import pandas._testing as tm
+
+
+@pytest.fixture
+def dummies_basic():
+ return DataFrame(
+ {
+ "col1_a": [1, 0, 1],
+ "col1_b": [0, 1, 0],
+ "col2_a": [0, 1, 0],
+ "col2_b": [1, 0, 0],
+ "col2_c": [0, 0, 1],
+ },
+ )
+
+
+@pytest.fixture
+def dummies_with_unassigned():
+ return DataFrame(
+ {
+ "col1_a": [1, 0, 0],
+ "col1_b": [0, 1, 0],
+ "col2_a": [0, 1, 0],
+ "col2_b": [0, 0, 0],
+ "col2_c": [0, 0, 1],
+ },
+ )
+
+
+def test_error_wrong_data_type():
+ dummies = [0, 1, 0]
+ with pytest.raises(
+ TypeError,
+ match=r"Expected 'data' to be a 'DataFrame'; Received 'data' of type: list",
+ ):
+ from_dummies(dummies)
+
+
+def test_error_no_prefix_contains_unassigned():
+ dummies = DataFrame({"a": [1, 0, 0], "b": [0, 1, 0]})
+ with pytest.raises(
+ ValueError,
+ match=(
+ r"Dummy DataFrame contains unassigned value\(s\); "
+ r"First instance in row: 2"
+ ),
+ ):
+ from_dummies(dummies)
+
+
+def test_error_no_prefix_wrong_default_category_type():
+ dummies = DataFrame({"a": [1, 0, 1], "b": [0, 1, 1]})
+ with pytest.raises(
+ TypeError,
+ match=(
+ r"Expected 'default_category' to be of type 'None', 'Hashable', or 'dict'; "
+ r"Received 'default_category' of type: list"
+ ),
+ ):
+ from_dummies(dummies, default_category=["c", "d"])
+
+
+def test_error_no_prefix_multi_assignment():
+ dummies = DataFrame({"a": [1, 0, 1], "b": [0, 1, 1]})
+ with pytest.raises(
+ ValueError,
+ match=(
+ r"Dummy DataFrame contains multi-assignment\(s\); "
+ r"First instance in row: 2"
+ ),
+ ):
+ from_dummies(dummies)
+
+
+def test_error_no_prefix_contains_nan():
+ dummies = DataFrame({"a": [1, 0, 0], "b": [0, 1, np.nan]})
+ with pytest.raises(
+ ValueError, match=r"Dummy DataFrame contains NA value in column: 'b'"
+ ):
+ from_dummies(dummies)
+
+
+def test_error_contains_non_dummies():
+ dummies = DataFrame(
+ {"a": [1, 6, 3, 1], "b": [0, 1, 0, 2], "c": ["c1", "c2", "c3", "c4"]}
+ )
+ with pytest.raises(
+ TypeError,
+ match=r"Passed DataFrame contains non-dummy data",
+ ):
+ from_dummies(dummies)
+
+
+def test_error_with_prefix_multiple_seperators():
+ dummies = DataFrame(
+ {
+ "col1_a": [1, 0, 1],
+ "col1_b": [0, 1, 0],
+ "col2-a": [0, 1, 0],
+ "col2-b": [1, 0, 1],
+ },
+ )
+ with pytest.raises(
+ ValueError,
+ match=(r"Separator not specified for column: col2-a"),
+ ):
+ from_dummies(dummies, sep="_")
+
+
+def test_error_with_prefix_sep_wrong_type(dummies_basic):
+ with pytest.raises(
+ TypeError,
+ match=(
+ r"Expected 'sep' to be of type 'str' or 'None'; "
+ r"Received 'sep' of type: list"
+ ),
+ ):
+ from_dummies(dummies_basic, sep=["_"])
+
+
+def test_error_with_prefix_contains_unassigned(dummies_with_unassigned):
+ with pytest.raises(
+ ValueError,
+ match=(
+ r"Dummy DataFrame contains unassigned value\(s\); "
+ r"First instance in row: 2"
+ ),
+ ):
+ from_dummies(dummies_with_unassigned, sep="_")
+
+
+def test_error_with_prefix_default_category_wrong_type(dummies_with_unassigned):
+ with pytest.raises(
+ TypeError,
+ match=(
+ r"Expected 'default_category' to be of type 'None', 'Hashable', or 'dict'; "
+ r"Received 'default_category' of type: list"
+ ),
+ ):
+ from_dummies(dummies_with_unassigned, sep="_", default_category=["x", "y"])
+
+
+def test_error_with_prefix_default_category_dict_not_complete(
+ dummies_with_unassigned,
+):
+ with pytest.raises(
+ ValueError,
+ match=(
+ r"Length of 'default_category' \(1\) did not match "
+ r"the length of the columns being encoded \(2\)"
+ ),
+ ):
+ from_dummies(dummies_with_unassigned, sep="_", default_category={"col1": "x"})
+
+
+def test_error_with_prefix_contains_nan(dummies_basic):
+ # Set float64 dtype to avoid upcast when setting np.nan
+ dummies_basic["col2_c"] = dummies_basic["col2_c"].astype("float64")
+ dummies_basic.loc[2, "col2_c"] = np.nan
+ with pytest.raises(
+ ValueError, match=r"Dummy DataFrame contains NA value in column: 'col2_c'"
+ ):
+ from_dummies(dummies_basic, sep="_")
+
+
+def test_error_with_prefix_contains_non_dummies(dummies_basic):
+ # Set object dtype to avoid upcast when setting "str"
+ dummies_basic["col2_c"] = dummies_basic["col2_c"].astype(object)
+ dummies_basic.loc[2, "col2_c"] = "str"
+ with pytest.raises(TypeError, match=r"Passed DataFrame contains non-dummy data"):
+ from_dummies(dummies_basic, sep="_")
+
+
+def test_error_with_prefix_double_assignment():
+ dummies = DataFrame(
+ {
+ "col1_a": [1, 0, 1],
+ "col1_b": [1, 1, 0],
+ "col2_a": [0, 1, 0],
+ "col2_b": [1, 0, 0],
+ "col2_c": [0, 0, 1],
+ },
+ )
+ with pytest.raises(
+ ValueError,
+ match=(
+ r"Dummy DataFrame contains multi-assignment\(s\); "
+ r"First instance in row: 0"
+ ),
+ ):
+ from_dummies(dummies, sep="_")
+
+
+def test_roundtrip_series_to_dataframe():
+ categories = Series(["a", "b", "c", "a"])
+ dummies = get_dummies(categories)
+ result = from_dummies(dummies)
+ expected = DataFrame({"": ["a", "b", "c", "a"]})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_roundtrip_single_column_dataframe():
+ categories = DataFrame({"": ["a", "b", "c", "a"]})
+ dummies = get_dummies(categories)
+ result = from_dummies(dummies, sep="_")
+ expected = categories
+ tm.assert_frame_equal(result, expected)
+
+
+def test_roundtrip_with_prefixes():
+ categories = DataFrame({"col1": ["a", "b", "a"], "col2": ["b", "a", "c"]})
+ dummies = get_dummies(categories)
+ result = from_dummies(dummies, sep="_")
+ expected = categories
+ tm.assert_frame_equal(result, expected)
+
+
+def test_no_prefix_string_cats_basic():
+ dummies = DataFrame({"a": [1, 0, 0, 1], "b": [0, 1, 0, 0], "c": [0, 0, 1, 0]})
+ expected = DataFrame({"": ["a", "b", "c", "a"]})
+ result = from_dummies(dummies)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_no_prefix_string_cats_basic_bool_values():
+ dummies = DataFrame(
+ {
+ "a": [True, False, False, True],
+ "b": [False, True, False, False],
+ "c": [False, False, True, False],
+ }
+ )
+ expected = DataFrame({"": ["a", "b", "c", "a"]})
+ result = from_dummies(dummies)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_no_prefix_string_cats_basic_mixed_bool_values():
+ dummies = DataFrame(
+ {"a": [1, 0, 0, 1], "b": [False, True, False, False], "c": [0, 0, 1, 0]}
+ )
+ expected = DataFrame({"": ["a", "b", "c", "a"]})
+ result = from_dummies(dummies)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_no_prefix_int_cats_basic():
+ dummies = DataFrame(
+ {1: [1, 0, 0, 0], 25: [0, 1, 0, 0], 2: [0, 0, 1, 0], 5: [0, 0, 0, 1]}
+ )
+ expected = DataFrame({"": [1, 25, 2, 5]})
+ result = from_dummies(dummies)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_no_prefix_float_cats_basic():
+ dummies = DataFrame(
+ {1.0: [1, 0, 0, 0], 25.0: [0, 1, 0, 0], 2.5: [0, 0, 1, 0], 5.84: [0, 0, 0, 1]}
+ )
+ expected = DataFrame({"": [1.0, 25.0, 2.5, 5.84]})
+ result = from_dummies(dummies)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_no_prefix_mixed_cats_basic():
+ dummies = DataFrame(
+ {
+ 1.23: [1, 0, 0, 0, 0],
+ "c": [0, 1, 0, 0, 0],
+ 2: [0, 0, 1, 0, 0],
+ False: [0, 0, 0, 1, 0],
+ None: [0, 0, 0, 0, 1],
+ }
+ )
+ expected = DataFrame({"": [1.23, "c", 2, False, None]}, dtype="object")
+ result = from_dummies(dummies)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_no_prefix_string_cats_contains_get_dummies_NaN_column():
+ dummies = DataFrame({"a": [1, 0, 0], "b": [0, 1, 0], "NaN": [0, 0, 1]})
+ expected = DataFrame({"": ["a", "b", "NaN"]})
+ result = from_dummies(dummies)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "default_category, expected",
+ [
+ pytest.param(
+ "c",
+ DataFrame({"": ["a", "b", "c"]}),
+ id="default_category is a str",
+ ),
+ pytest.param(
+ 1,
+ DataFrame({"": ["a", "b", 1]}),
+ id="default_category is a int",
+ ),
+ pytest.param(
+ 1.25,
+ DataFrame({"": ["a", "b", 1.25]}),
+ id="default_category is a float",
+ ),
+ pytest.param(
+ 0,
+ DataFrame({"": ["a", "b", 0]}),
+ id="default_category is a 0",
+ ),
+ pytest.param(
+ False,
+ DataFrame({"": ["a", "b", False]}),
+ id="default_category is a bool",
+ ),
+ pytest.param(
+ (1, 2),
+ DataFrame({"": ["a", "b", (1, 2)]}),
+ id="default_category is a tuple",
+ ),
+ ],
+)
+def test_no_prefix_string_cats_default_category(default_category, expected):
+ dummies = DataFrame({"a": [1, 0, 0], "b": [0, 1, 0]})
+ result = from_dummies(dummies, default_category=default_category)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_with_prefix_basic(dummies_basic):
+ expected = DataFrame({"col1": ["a", "b", "a"], "col2": ["b", "a", "c"]})
+ result = from_dummies(dummies_basic, sep="_")
+ tm.assert_frame_equal(result, expected)
+
+
+def test_with_prefix_contains_get_dummies_NaN_column():
+ dummies = DataFrame(
+ {
+ "col1_a": [1, 0, 0],
+ "col1_b": [0, 1, 0],
+ "col1_NaN": [0, 0, 1],
+ "col2_a": [0, 1, 0],
+ "col2_b": [0, 0, 0],
+ "col2_c": [0, 0, 1],
+ "col2_NaN": [1, 0, 0],
+ },
+ )
+ expected = DataFrame({"col1": ["a", "b", "NaN"], "col2": ["NaN", "a", "c"]})
+ result = from_dummies(dummies, sep="_")
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "default_category, expected",
+ [
+ pytest.param(
+ "x",
+ DataFrame({"col1": ["a", "b", "x"], "col2": ["x", "a", "c"]}),
+ id="default_category is a str",
+ ),
+ pytest.param(
+ 0,
+ DataFrame({"col1": ["a", "b", 0], "col2": [0, "a", "c"]}),
+ id="default_category is a 0",
+ ),
+ pytest.param(
+ False,
+ DataFrame({"col1": ["a", "b", False], "col2": [False, "a", "c"]}),
+ id="default_category is a False",
+ ),
+ pytest.param(
+ {"col2": 1, "col1": 2.5},
+ DataFrame({"col1": ["a", "b", 2.5], "col2": [1, "a", "c"]}),
+ id="default_category is a dict with int and float values",
+ ),
+ pytest.param(
+ {"col2": None, "col1": False},
+ DataFrame({"col1": ["a", "b", False], "col2": [None, "a", "c"]}),
+ id="default_category is a dict with bool and None values",
+ ),
+ pytest.param(
+ {"col2": (1, 2), "col1": [1.25, False]},
+ DataFrame({"col1": ["a", "b", [1.25, False]], "col2": [(1, 2), "a", "c"]}),
+ id="default_category is a dict with list and tuple values",
+ ),
+ ],
+)
+def test_with_prefix_default_category(
+ dummies_with_unassigned, default_category, expected
+):
+ result = from_dummies(
+ dummies_with_unassigned, sep="_", default_category=default_category
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_ea_categories():
+ # GH 54300
+ df = DataFrame({"a": [1, 0, 0, 1], "b": [0, 1, 0, 0], "c": [0, 0, 1, 0]})
+ df.columns = df.columns.astype("string[python]")
+ result = from_dummies(df)
+ expected = DataFrame({"": Series(list("abca"), dtype="string[python]")})
+ tm.assert_frame_equal(result, expected)
+
+
+def test_ea_categories_with_sep():
+ # GH 54300
+ df = DataFrame(
+ {
+ "col1_a": [1, 0, 1],
+ "col1_b": [0, 1, 0],
+ "col2_a": [0, 1, 0],
+ "col2_b": [1, 0, 0],
+ "col2_c": [0, 0, 1],
+ }
+ )
+ df.columns = df.columns.astype("string[python]")
+ result = from_dummies(df, sep="_")
+ expected = DataFrame(
+ {
+ "col1": Series(list("aba"), dtype="string[python]"),
+ "col2": Series(list("bac"), dtype="string[python]"),
+ }
+ )
+ expected.columns = expected.columns.astype("string[python]")
+ tm.assert_frame_equal(result, expected)
+
+
+def test_maintain_original_index():
+ # GH 54300
+ df = DataFrame(
+ {"a": [1, 0, 0, 1], "b": [0, 1, 0, 0], "c": [0, 0, 1, 0]}, index=list("abcd")
+ )
+ result = from_dummies(df)
+ expected = DataFrame({"": list("abca")}, index=list("abcd"))
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_get_dummies.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_get_dummies.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bfff56cfedf2e1a50db67d9494ce0fe5f0579aa
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_get_dummies.py
@@ -0,0 +1,695 @@
+import re
+import unicodedata
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.common import is_integer_dtype
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ DataFrame,
+ RangeIndex,
+ Series,
+ SparseDtype,
+ get_dummies,
+)
+import pandas._testing as tm
+from pandas.core.arrays.sparse import SparseArray
+
+
+class TestGetDummies:
+ @pytest.fixture
+ def df(self):
+ return DataFrame({"A": ["a", "b", "a"], "B": ["b", "b", "c"], "C": [1, 2, 3]})
+
+ @pytest.fixture(params=["uint8", "i8", np.float64, bool, None])
+ def dtype(self, request):
+ return np.dtype(request.param)
+
+ @pytest.fixture(params=["dense", "sparse"])
+ def sparse(self, request):
+ # params are strings to simplify reading test results,
+ # e.g. TestGetDummies::test_basic[uint8-sparse] instead of [uint8-True]
+ return request.param == "sparse"
+
+ def effective_dtype(self, dtype):
+ if dtype is None:
+ return np.uint8
+ return dtype
+
+ def test_get_dummies_raises_on_dtype_object(self, df):
+ msg = "dtype=object is not a valid dtype for get_dummies"
+ with pytest.raises(ValueError, match=msg):
+ get_dummies(df, dtype="object")
+
+ def test_get_dummies_basic(self, sparse, dtype):
+ s_list = list("abc")
+ s_series = Series(s_list)
+ s_series_index = Series(s_list, list("ABC"))
+
+ expected = DataFrame(
+ {"a": [1, 0, 0], "b": [0, 1, 0], "c": [0, 0, 1]},
+ dtype=self.effective_dtype(dtype),
+ )
+ if sparse:
+ if dtype.kind == "b":
+ expected = expected.apply(SparseArray, fill_value=False)
+ else:
+ expected = expected.apply(SparseArray, fill_value=0.0)
+ result = get_dummies(s_list, sparse=sparse, dtype=dtype)
+ tm.assert_frame_equal(result, expected)
+
+ result = get_dummies(s_series, sparse=sparse, dtype=dtype)
+ tm.assert_frame_equal(result, expected)
+
+ expected.index = list("ABC")
+ result = get_dummies(s_series_index, sparse=sparse, dtype=dtype)
+ tm.assert_frame_equal(result, expected)
+
+ def test_get_dummies_basic_types(self, sparse, dtype):
+ # GH 10531
+ s_list = list("abc")
+ s_series = Series(s_list)
+ s_df = DataFrame(
+ {"a": [0, 1, 0, 1, 2], "b": ["A", "A", "B", "C", "C"], "c": [2, 3, 3, 3, 2]}
+ )
+
+ expected = DataFrame(
+ {"a": [1, 0, 0], "b": [0, 1, 0], "c": [0, 0, 1]},
+ dtype=self.effective_dtype(dtype),
+ columns=list("abc"),
+ )
+ if sparse:
+ if is_integer_dtype(dtype):
+ fill_value = 0
+ elif dtype == bool:
+ fill_value = False
+ else:
+ fill_value = 0.0
+
+ expected = expected.apply(SparseArray, fill_value=fill_value)
+ result = get_dummies(s_list, sparse=sparse, dtype=dtype)
+ tm.assert_frame_equal(result, expected)
+
+ result = get_dummies(s_series, sparse=sparse, dtype=dtype)
+ tm.assert_frame_equal(result, expected)
+
+ result = get_dummies(s_df, columns=s_df.columns, sparse=sparse, dtype=dtype)
+ if sparse:
+ dtype_name = f"Sparse[{self.effective_dtype(dtype).name}, {fill_value}]"
+ else:
+ dtype_name = self.effective_dtype(dtype).name
+
+ expected = Series({dtype_name: 8}, name="count")
+ result = result.dtypes.value_counts()
+ result.index = [str(i) for i in result.index]
+ tm.assert_series_equal(result, expected)
+
+ result = get_dummies(s_df, columns=["a"], sparse=sparse, dtype=dtype)
+
+ expected_counts = {"int64": 1, "object": 1}
+ expected_counts[dtype_name] = 3 + expected_counts.get(dtype_name, 0)
+
+ expected = Series(expected_counts, name="count").sort_index()
+ result = result.dtypes.value_counts()
+ result.index = [str(i) for i in result.index]
+ result = result.sort_index()
+ tm.assert_series_equal(result, expected)
+
+ def test_get_dummies_just_na(self, sparse):
+ just_na_list = [np.nan]
+ just_na_series = Series(just_na_list)
+ just_na_series_index = Series(just_na_list, index=["A"])
+
+ res_list = get_dummies(just_na_list, sparse=sparse)
+ res_series = get_dummies(just_na_series, sparse=sparse)
+ res_series_index = get_dummies(just_na_series_index, sparse=sparse)
+
+ assert res_list.empty
+ assert res_series.empty
+ assert res_series_index.empty
+
+ assert res_list.index.tolist() == [0]
+ assert res_series.index.tolist() == [0]
+ assert res_series_index.index.tolist() == ["A"]
+
+ def test_get_dummies_include_na(self, sparse, dtype):
+ s = ["a", "b", np.nan]
+ res = get_dummies(s, sparse=sparse, dtype=dtype)
+ exp = DataFrame(
+ {"a": [1, 0, 0], "b": [0, 1, 0]}, dtype=self.effective_dtype(dtype)
+ )
+ if sparse:
+ if dtype.kind == "b":
+ exp = exp.apply(SparseArray, fill_value=False)
+ else:
+ exp = exp.apply(SparseArray, fill_value=0.0)
+ tm.assert_frame_equal(res, exp)
+
+ # Sparse dataframes do not allow nan labelled columns, see #GH8822
+ res_na = get_dummies(s, dummy_na=True, sparse=sparse, dtype=dtype)
+ exp_na = DataFrame(
+ {np.nan: [0, 0, 1], "a": [1, 0, 0], "b": [0, 1, 0]},
+ dtype=self.effective_dtype(dtype),
+ )
+ exp_na = exp_na.reindex(["a", "b", np.nan], axis=1)
+ # hack (NaN handling in assert_index_equal)
+ exp_na.columns = res_na.columns
+ if sparse:
+ if dtype.kind == "b":
+ exp_na = exp_na.apply(SparseArray, fill_value=False)
+ else:
+ exp_na = exp_na.apply(SparseArray, fill_value=0.0)
+ tm.assert_frame_equal(res_na, exp_na)
+
+ res_just_na = get_dummies([np.nan], dummy_na=True, sparse=sparse, dtype=dtype)
+ exp_just_na = DataFrame(
+ Series(1, index=[0]), columns=[np.nan], dtype=self.effective_dtype(dtype)
+ )
+ tm.assert_numpy_array_equal(res_just_na.values, exp_just_na.values)
+
+ def test_get_dummies_unicode(self, sparse):
+ # See GH 6885 - get_dummies chokes on unicode values
+ e = "e"
+ eacute = unicodedata.lookup("LATIN SMALL LETTER E WITH ACUTE")
+ s = [e, eacute, eacute]
+ res = get_dummies(s, prefix="letter", sparse=sparse)
+ exp = DataFrame(
+ {"letter_e": [True, False, False], f"letter_{eacute}": [False, True, True]}
+ )
+ if sparse:
+ exp = exp.apply(SparseArray, fill_value=False)
+ tm.assert_frame_equal(res, exp)
+
+ def test_dataframe_dummies_all_obj(self, df, sparse):
+ df = df[["A", "B"]]
+ result = get_dummies(df, sparse=sparse)
+ expected = DataFrame(
+ {"A_a": [1, 0, 1], "A_b": [0, 1, 0], "B_b": [1, 1, 0], "B_c": [0, 0, 1]},
+ dtype=bool,
+ )
+ if sparse:
+ expected = DataFrame(
+ {
+ "A_a": SparseArray([1, 0, 1], dtype="bool"),
+ "A_b": SparseArray([0, 1, 0], dtype="bool"),
+ "B_b": SparseArray([1, 1, 0], dtype="bool"),
+ "B_c": SparseArray([0, 0, 1], dtype="bool"),
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_string_dtype(self, df):
+ # GH44965
+ df = df[["A", "B"]]
+ df = df.astype({"A": "object", "B": "string"})
+ result = get_dummies(df)
+ expected = DataFrame(
+ {
+ "A_a": [1, 0, 1],
+ "A_b": [0, 1, 0],
+ "B_b": [1, 1, 0],
+ "B_c": [0, 0, 1],
+ },
+ dtype=bool,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_mix_default(self, df, sparse, dtype):
+ result = get_dummies(df, sparse=sparse, dtype=dtype)
+ if sparse:
+ arr = SparseArray
+ if dtype.kind == "b":
+ typ = SparseDtype(dtype, False)
+ else:
+ typ = SparseDtype(dtype, 0)
+ else:
+ arr = np.array
+ typ = dtype
+ expected = DataFrame(
+ {
+ "C": [1, 2, 3],
+ "A_a": arr([1, 0, 1], dtype=typ),
+ "A_b": arr([0, 1, 0], dtype=typ),
+ "B_b": arr([1, 1, 0], dtype=typ),
+ "B_c": arr([0, 0, 1], dtype=typ),
+ }
+ )
+ expected = expected[["C", "A_a", "A_b", "B_b", "B_c"]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_prefix_list(self, df, sparse):
+ prefixes = ["from_A", "from_B"]
+ result = get_dummies(df, prefix=prefixes, sparse=sparse)
+ expected = DataFrame(
+ {
+ "C": [1, 2, 3],
+ "from_A_a": [True, False, True],
+ "from_A_b": [False, True, False],
+ "from_B_b": [True, True, False],
+ "from_B_c": [False, False, True],
+ },
+ )
+ expected[["C"]] = df[["C"]]
+ cols = ["from_A_a", "from_A_b", "from_B_b", "from_B_c"]
+ expected = expected[["C"] + cols]
+
+ typ = SparseArray if sparse else Series
+ expected[cols] = expected[cols].apply(lambda x: typ(x))
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_prefix_str(self, df, sparse):
+ # not that you should do this...
+ result = get_dummies(df, prefix="bad", sparse=sparse)
+ bad_columns = ["bad_a", "bad_b", "bad_b", "bad_c"]
+ expected = DataFrame(
+ [
+ [1, True, False, True, False],
+ [2, False, True, True, False],
+ [3, True, False, False, True],
+ ],
+ columns=["C"] + bad_columns,
+ )
+ expected = expected.astype({"C": np.int64})
+ if sparse:
+ # work around astyping & assigning with duplicate columns
+ # https://github.com/pandas-dev/pandas/issues/14427
+ expected = pd.concat(
+ [
+ Series([1, 2, 3], name="C"),
+ Series([True, False, True], name="bad_a", dtype="Sparse[bool]"),
+ Series([False, True, False], name="bad_b", dtype="Sparse[bool]"),
+ Series([True, True, False], name="bad_b", dtype="Sparse[bool]"),
+ Series([False, False, True], name="bad_c", dtype="Sparse[bool]"),
+ ],
+ axis=1,
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_subset(self, df, sparse):
+ result = get_dummies(df, prefix=["from_A"], columns=["A"], sparse=sparse)
+ expected = DataFrame(
+ {
+ "B": ["b", "b", "c"],
+ "C": [1, 2, 3],
+ "from_A_a": [1, 0, 1],
+ "from_A_b": [0, 1, 0],
+ },
+ )
+ cols = expected.columns
+ expected[cols[1:]] = expected[cols[1:]].astype(bool)
+ expected[["C"]] = df[["C"]]
+ if sparse:
+ cols = ["from_A_a", "from_A_b"]
+ expected[cols] = expected[cols].astype(SparseDtype("bool", False))
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_prefix_sep(self, df, sparse):
+ result = get_dummies(df, prefix_sep="..", sparse=sparse)
+ expected = DataFrame(
+ {
+ "C": [1, 2, 3],
+ "A..a": [True, False, True],
+ "A..b": [False, True, False],
+ "B..b": [True, True, False],
+ "B..c": [False, False, True],
+ },
+ )
+ expected[["C"]] = df[["C"]]
+ expected = expected[["C", "A..a", "A..b", "B..b", "B..c"]]
+ if sparse:
+ cols = ["A..a", "A..b", "B..b", "B..c"]
+ expected[cols] = expected[cols].astype(SparseDtype("bool", False))
+
+ tm.assert_frame_equal(result, expected)
+
+ result = get_dummies(df, prefix_sep=["..", "__"], sparse=sparse)
+ expected = expected.rename(columns={"B..b": "B__b", "B..c": "B__c"})
+ tm.assert_frame_equal(result, expected)
+
+ result = get_dummies(df, prefix_sep={"A": "..", "B": "__"}, sparse=sparse)
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_prefix_bad_length(self, df, sparse):
+ msg = re.escape(
+ "Length of 'prefix' (1) did not match the length of the columns being "
+ "encoded (2)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ get_dummies(df, prefix=["too few"], sparse=sparse)
+
+ def test_dataframe_dummies_prefix_sep_bad_length(self, df, sparse):
+ msg = re.escape(
+ "Length of 'prefix_sep' (1) did not match the length of the columns being "
+ "encoded (2)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ get_dummies(df, prefix_sep=["bad"], sparse=sparse)
+
+ def test_dataframe_dummies_prefix_dict(self, sparse):
+ prefixes = {"A": "from_A", "B": "from_B"}
+ df = DataFrame({"C": [1, 2, 3], "A": ["a", "b", "a"], "B": ["b", "b", "c"]})
+ result = get_dummies(df, prefix=prefixes, sparse=sparse)
+
+ expected = DataFrame(
+ {
+ "C": [1, 2, 3],
+ "from_A_a": [1, 0, 1],
+ "from_A_b": [0, 1, 0],
+ "from_B_b": [1, 1, 0],
+ "from_B_c": [0, 0, 1],
+ }
+ )
+
+ columns = ["from_A_a", "from_A_b", "from_B_b", "from_B_c"]
+ expected[columns] = expected[columns].astype(bool)
+ if sparse:
+ expected[columns] = expected[columns].astype(SparseDtype("bool", False))
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_with_na(self, df, sparse, dtype):
+ df.loc[3, :] = [np.nan, np.nan, np.nan]
+ result = get_dummies(df, dummy_na=True, sparse=sparse, dtype=dtype).sort_index(
+ axis=1
+ )
+
+ if sparse:
+ arr = SparseArray
+ if dtype.kind == "b":
+ typ = SparseDtype(dtype, False)
+ else:
+ typ = SparseDtype(dtype, 0)
+ else:
+ arr = np.array
+ typ = dtype
+
+ expected = DataFrame(
+ {
+ "C": [1, 2, 3, np.nan],
+ "A_a": arr([1, 0, 1, 0], dtype=typ),
+ "A_b": arr([0, 1, 0, 0], dtype=typ),
+ "A_nan": arr([0, 0, 0, 1], dtype=typ),
+ "B_b": arr([1, 1, 0, 0], dtype=typ),
+ "B_c": arr([0, 0, 1, 0], dtype=typ),
+ "B_nan": arr([0, 0, 0, 1], dtype=typ),
+ }
+ ).sort_index(axis=1)
+
+ tm.assert_frame_equal(result, expected)
+
+ result = get_dummies(df, dummy_na=False, sparse=sparse, dtype=dtype)
+ expected = expected[["C", "A_a", "A_b", "B_b", "B_c"]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_with_categorical(self, df, sparse, dtype):
+ df["cat"] = Categorical(["x", "y", "y"])
+ result = get_dummies(df, sparse=sparse, dtype=dtype).sort_index(axis=1)
+ if sparse:
+ arr = SparseArray
+ if dtype.kind == "b":
+ typ = SparseDtype(dtype, False)
+ else:
+ typ = SparseDtype(dtype, 0)
+ else:
+ arr = np.array
+ typ = dtype
+
+ expected = DataFrame(
+ {
+ "C": [1, 2, 3],
+ "A_a": arr([1, 0, 1], dtype=typ),
+ "A_b": arr([0, 1, 0], dtype=typ),
+ "B_b": arr([1, 1, 0], dtype=typ),
+ "B_c": arr([0, 0, 1], dtype=typ),
+ "cat_x": arr([1, 0, 0], dtype=typ),
+ "cat_y": arr([0, 1, 1], dtype=typ),
+ }
+ ).sort_index(axis=1)
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "get_dummies_kwargs,expected",
+ [
+ (
+ {"data": DataFrame({"ä": ["a"]})},
+ DataFrame({"ä_a": [True]}),
+ ),
+ (
+ {"data": DataFrame({"x": ["ä"]})},
+ DataFrame({"x_ä": [True]}),
+ ),
+ (
+ {"data": DataFrame({"x": ["a"]}), "prefix": "ä"},
+ DataFrame({"ä_a": [True]}),
+ ),
+ (
+ {"data": DataFrame({"x": ["a"]}), "prefix_sep": "ä"},
+ DataFrame({"xäa": [True]}),
+ ),
+ ],
+ )
+ def test_dataframe_dummies_unicode(self, get_dummies_kwargs, expected):
+ # GH22084 get_dummies incorrectly encodes unicode characters
+ # in dataframe column names
+ result = get_dummies(**get_dummies_kwargs)
+ tm.assert_frame_equal(result, expected)
+
+ def test_get_dummies_basic_drop_first(self, sparse):
+ # GH12402 Add a new parameter `drop_first` to avoid collinearity
+ # Basic case
+ s_list = list("abc")
+ s_series = Series(s_list)
+ s_series_index = Series(s_list, list("ABC"))
+
+ expected = DataFrame({"b": [0, 1, 0], "c": [0, 0, 1]}, dtype=bool)
+
+ result = get_dummies(s_list, drop_first=True, sparse=sparse)
+ if sparse:
+ expected = expected.apply(SparseArray, fill_value=False)
+ tm.assert_frame_equal(result, expected)
+
+ result = get_dummies(s_series, drop_first=True, sparse=sparse)
+ tm.assert_frame_equal(result, expected)
+
+ expected.index = list("ABC")
+ result = get_dummies(s_series_index, drop_first=True, sparse=sparse)
+ tm.assert_frame_equal(result, expected)
+
+ def test_get_dummies_basic_drop_first_one_level(self, sparse):
+ # Test the case that categorical variable only has one level.
+ s_list = list("aaa")
+ s_series = Series(s_list)
+ s_series_index = Series(s_list, list("ABC"))
+
+ expected = DataFrame(index=RangeIndex(3))
+
+ result = get_dummies(s_list, drop_first=True, sparse=sparse)
+ tm.assert_frame_equal(result, expected)
+
+ result = get_dummies(s_series, drop_first=True, sparse=sparse)
+ tm.assert_frame_equal(result, expected)
+
+ expected = DataFrame(index=list("ABC"))
+ result = get_dummies(s_series_index, drop_first=True, sparse=sparse)
+ tm.assert_frame_equal(result, expected)
+
+ def test_get_dummies_basic_drop_first_NA(self, sparse):
+ # Test NA handling together with drop_first
+ s_NA = ["a", "b", np.nan]
+ res = get_dummies(s_NA, drop_first=True, sparse=sparse)
+ exp = DataFrame({"b": [0, 1, 0]}, dtype=bool)
+ if sparse:
+ exp = exp.apply(SparseArray, fill_value=False)
+
+ tm.assert_frame_equal(res, exp)
+
+ res_na = get_dummies(s_NA, dummy_na=True, drop_first=True, sparse=sparse)
+ exp_na = DataFrame({"b": [0, 1, 0], np.nan: [0, 0, 1]}, dtype=bool).reindex(
+ ["b", np.nan], axis=1
+ )
+ if sparse:
+ exp_na = exp_na.apply(SparseArray, fill_value=False)
+ tm.assert_frame_equal(res_na, exp_na)
+
+ res_just_na = get_dummies(
+ [np.nan], dummy_na=True, drop_first=True, sparse=sparse
+ )
+ exp_just_na = DataFrame(index=RangeIndex(1))
+ tm.assert_frame_equal(res_just_na, exp_just_na)
+
+ def test_dataframe_dummies_drop_first(self, df, sparse):
+ df = df[["A", "B"]]
+ result = get_dummies(df, drop_first=True, sparse=sparse)
+ expected = DataFrame({"A_b": [0, 1, 0], "B_c": [0, 0, 1]}, dtype=bool)
+ if sparse:
+ expected = expected.apply(SparseArray, fill_value=False)
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_drop_first_with_categorical(self, df, sparse, dtype):
+ df["cat"] = Categorical(["x", "y", "y"])
+ result = get_dummies(df, drop_first=True, sparse=sparse)
+ expected = DataFrame(
+ {"C": [1, 2, 3], "A_b": [0, 1, 0], "B_c": [0, 0, 1], "cat_y": [0, 1, 1]}
+ )
+ cols = ["A_b", "B_c", "cat_y"]
+ expected[cols] = expected[cols].astype(bool)
+ expected = expected[["C", "A_b", "B_c", "cat_y"]]
+ if sparse:
+ for col in cols:
+ expected[col] = SparseArray(expected[col])
+ tm.assert_frame_equal(result, expected)
+
+ def test_dataframe_dummies_drop_first_with_na(self, df, sparse):
+ df.loc[3, :] = [np.nan, np.nan, np.nan]
+ result = get_dummies(
+ df, dummy_na=True, drop_first=True, sparse=sparse
+ ).sort_index(axis=1)
+ expected = DataFrame(
+ {
+ "C": [1, 2, 3, np.nan],
+ "A_b": [0, 1, 0, 0],
+ "A_nan": [0, 0, 0, 1],
+ "B_c": [0, 0, 1, 0],
+ "B_nan": [0, 0, 0, 1],
+ }
+ )
+ cols = ["A_b", "A_nan", "B_c", "B_nan"]
+ expected[cols] = expected[cols].astype(bool)
+ expected = expected.sort_index(axis=1)
+ if sparse:
+ for col in cols:
+ expected[col] = SparseArray(expected[col])
+
+ tm.assert_frame_equal(result, expected)
+
+ result = get_dummies(df, dummy_na=False, drop_first=True, sparse=sparse)
+ expected = expected[["C", "A_b", "B_c"]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_get_dummies_int_int(self):
+ data = Series([1, 2, 1])
+ result = get_dummies(data)
+ expected = DataFrame([[1, 0], [0, 1], [1, 0]], columns=[1, 2], dtype=bool)
+ tm.assert_frame_equal(result, expected)
+
+ data = Series(Categorical(["a", "b", "a"]))
+ result = get_dummies(data)
+ expected = DataFrame(
+ [[1, 0], [0, 1], [1, 0]], columns=Categorical(["a", "b"]), dtype=bool
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_get_dummies_int_df(self, dtype):
+ data = DataFrame(
+ {
+ "A": [1, 2, 1],
+ "B": Categorical(["a", "b", "a"]),
+ "C": [1, 2, 1],
+ "D": [1.0, 2.0, 1.0],
+ }
+ )
+ columns = ["C", "D", "A_1", "A_2", "B_a", "B_b"]
+ expected = DataFrame(
+ [[1, 1.0, 1, 0, 1, 0], [2, 2.0, 0, 1, 0, 1], [1, 1.0, 1, 0, 1, 0]],
+ columns=columns,
+ )
+ expected[columns[2:]] = expected[columns[2:]].astype(dtype)
+ result = get_dummies(data, columns=["A", "B"], dtype=dtype)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("ordered", [True, False])
+ def test_dataframe_dummies_preserve_categorical_dtype(self, dtype, ordered):
+ # GH13854
+ cat = Categorical(list("xy"), categories=list("xyz"), ordered=ordered)
+ result = get_dummies(cat, dtype=dtype)
+
+ data = np.array([[1, 0, 0], [0, 1, 0]], dtype=self.effective_dtype(dtype))
+ cols = CategoricalIndex(
+ cat.categories, categories=cat.categories, ordered=ordered
+ )
+ expected = DataFrame(data, columns=cols, dtype=self.effective_dtype(dtype))
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("sparse", [True, False])
+ def test_get_dummies_dont_sparsify_all_columns(self, sparse):
+ # GH18914
+ df = DataFrame.from_dict({"GDP": [1, 2], "Nation": ["AB", "CD"]})
+ df = get_dummies(df, columns=["Nation"], sparse=sparse)
+ df2 = df.reindex(columns=["GDP"])
+
+ tm.assert_frame_equal(df[["GDP"]], df2)
+
+ def test_get_dummies_duplicate_columns(self, df):
+ # GH20839
+ df.columns = ["A", "A", "A"]
+ result = get_dummies(df).sort_index(axis=1)
+
+ expected = DataFrame(
+ [
+ [1, True, False, True, False],
+ [2, False, True, True, False],
+ [3, True, False, False, True],
+ ],
+ columns=["A", "A_a", "A_b", "A_b", "A_c"],
+ ).sort_index(axis=1)
+
+ expected = expected.astype({"A": np.int64})
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_get_dummies_all_sparse(self):
+ df = DataFrame({"A": [1, 2]})
+ result = get_dummies(df, columns=["A"], sparse=True)
+ dtype = SparseDtype("bool", False)
+ expected = DataFrame(
+ {
+ "A_1": SparseArray([1, 0], dtype=dtype),
+ "A_2": SparseArray([0, 1], dtype=dtype),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("values", ["baz"])
+ def test_get_dummies_with_string_values(self, values):
+ # issue #28383
+ df = DataFrame(
+ {
+ "bar": [1, 2, 3, 4, 5, 6],
+ "foo": ["one", "one", "one", "two", "two", "two"],
+ "baz": ["A", "B", "C", "A", "B", "C"],
+ "zoo": ["x", "y", "z", "q", "w", "t"],
+ }
+ )
+
+ msg = "Input must be a list-like for parameter `columns`"
+
+ with pytest.raises(TypeError, match=msg):
+ get_dummies(df, columns=values)
+
+ def test_get_dummies_ea_dtype_series(self, any_numeric_ea_and_arrow_dtype):
+ # GH#32430
+ ser = Series(list("abca"))
+ result = get_dummies(ser, dtype=any_numeric_ea_and_arrow_dtype)
+ expected = DataFrame(
+ {"a": [1, 0, 0, 1], "b": [0, 1, 0, 0], "c": [0, 0, 1, 0]},
+ dtype=any_numeric_ea_and_arrow_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_get_dummies_ea_dtype_dataframe(self, any_numeric_ea_and_arrow_dtype):
+ # GH#32430
+ df = DataFrame({"x": list("abca")})
+ result = get_dummies(df, dtype=any_numeric_ea_and_arrow_dtype)
+ expected = DataFrame(
+ {"x_a": [1, 0, 0, 1], "x_b": [0, 1, 0, 0], "x_c": [0, 0, 1, 0]},
+ dtype=any_numeric_ea_and_arrow_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_melt.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_melt.py
new file mode 100644
index 0000000000000000000000000000000000000000..941478066a7d804c3e45e227db2de78f7f9c0153
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_melt.py
@@ -0,0 +1,1145 @@
+import re
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ lreshape,
+ melt,
+ wide_to_long,
+)
+import pandas._testing as tm
+
+
+@pytest.fixture
+def df():
+ res = tm.makeTimeDataFrame()[:10]
+ res["id1"] = (res["A"] > 0).astype(np.int64)
+ res["id2"] = (res["B"] > 0).astype(np.int64)
+ return res
+
+
+@pytest.fixture
+def df1():
+ res = DataFrame(
+ [
+ [1.067683, -1.110463, 0.20867],
+ [-1.321405, 0.368915, -1.055342],
+ [-0.807333, 0.08298, -0.873361],
+ ]
+ )
+ res.columns = [list("ABC"), list("abc")]
+ res.columns.names = ["CAP", "low"]
+ return res
+
+
+@pytest.fixture
+def var_name():
+ return "var"
+
+
+@pytest.fixture
+def value_name():
+ return "val"
+
+
+class TestMelt:
+ def test_top_level_method(self, df):
+ result = melt(df)
+ assert result.columns.tolist() == ["variable", "value"]
+
+ def test_method_signatures(self, df, df1, var_name, value_name):
+ tm.assert_frame_equal(df.melt(), melt(df))
+
+ tm.assert_frame_equal(
+ df.melt(id_vars=["id1", "id2"], value_vars=["A", "B"]),
+ melt(df, id_vars=["id1", "id2"], value_vars=["A", "B"]),
+ )
+
+ tm.assert_frame_equal(
+ df.melt(var_name=var_name, value_name=value_name),
+ melt(df, var_name=var_name, value_name=value_name),
+ )
+
+ tm.assert_frame_equal(df1.melt(col_level=0), melt(df1, col_level=0))
+
+ def test_default_col_names(self, df):
+ result = df.melt()
+ assert result.columns.tolist() == ["variable", "value"]
+
+ result1 = df.melt(id_vars=["id1"])
+ assert result1.columns.tolist() == ["id1", "variable", "value"]
+
+ result2 = df.melt(id_vars=["id1", "id2"])
+ assert result2.columns.tolist() == ["id1", "id2", "variable", "value"]
+
+ def test_value_vars(self, df):
+ result3 = df.melt(id_vars=["id1", "id2"], value_vars="A")
+ assert len(result3) == 10
+
+ result4 = df.melt(id_vars=["id1", "id2"], value_vars=["A", "B"])
+ expected4 = DataFrame(
+ {
+ "id1": df["id1"].tolist() * 2,
+ "id2": df["id2"].tolist() * 2,
+ "variable": ["A"] * 10 + ["B"] * 10,
+ "value": (df["A"].tolist() + df["B"].tolist()),
+ },
+ columns=["id1", "id2", "variable", "value"],
+ )
+ tm.assert_frame_equal(result4, expected4)
+
+ @pytest.mark.parametrize("type_", (tuple, list, np.array))
+ def test_value_vars_types(self, type_, df):
+ # GH 15348
+ expected = DataFrame(
+ {
+ "id1": df["id1"].tolist() * 2,
+ "id2": df["id2"].tolist() * 2,
+ "variable": ["A"] * 10 + ["B"] * 10,
+ "value": (df["A"].tolist() + df["B"].tolist()),
+ },
+ columns=["id1", "id2", "variable", "value"],
+ )
+ result = df.melt(id_vars=["id1", "id2"], value_vars=type_(("A", "B")))
+ tm.assert_frame_equal(result, expected)
+
+ def test_vars_work_with_multiindex(self, df1):
+ expected = DataFrame(
+ {
+ ("A", "a"): df1[("A", "a")],
+ "CAP": ["B"] * len(df1),
+ "low": ["b"] * len(df1),
+ "value": df1[("B", "b")],
+ },
+ columns=[("A", "a"), "CAP", "low", "value"],
+ )
+
+ result = df1.melt(id_vars=[("A", "a")], value_vars=[("B", "b")])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "id_vars, value_vars, col_level, expected",
+ [
+ (
+ ["A"],
+ ["B"],
+ 0,
+ DataFrame(
+ {
+ "A": {0: 1.067683, 1: -1.321405, 2: -0.807333},
+ "CAP": {0: "B", 1: "B", 2: "B"},
+ "value": {0: -1.110463, 1: 0.368915, 2: 0.08298},
+ }
+ ),
+ ),
+ (
+ ["a"],
+ ["b"],
+ 1,
+ DataFrame(
+ {
+ "a": {0: 1.067683, 1: -1.321405, 2: -0.807333},
+ "low": {0: "b", 1: "b", 2: "b"},
+ "value": {0: -1.110463, 1: 0.368915, 2: 0.08298},
+ }
+ ),
+ ),
+ ],
+ )
+ def test_single_vars_work_with_multiindex(
+ self, id_vars, value_vars, col_level, expected, df1
+ ):
+ result = df1.melt(id_vars, value_vars, col_level=col_level)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "id_vars, value_vars",
+ [
+ [("A", "a"), [("B", "b")]],
+ [[("A", "a")], ("B", "b")],
+ [("A", "a"), ("B", "b")],
+ ],
+ )
+ def test_tuple_vars_fail_with_multiindex(self, id_vars, value_vars, df1):
+ # melt should fail with an informative error message if
+ # the columns have a MultiIndex and a tuple is passed
+ # for id_vars or value_vars.
+ msg = r"(id|value)_vars must be a list of tuples when columns are a MultiIndex"
+ with pytest.raises(ValueError, match=msg):
+ df1.melt(id_vars=id_vars, value_vars=value_vars)
+
+ def test_custom_var_name(self, df, var_name):
+ result5 = df.melt(var_name=var_name)
+ assert result5.columns.tolist() == ["var", "value"]
+
+ result6 = df.melt(id_vars=["id1"], var_name=var_name)
+ assert result6.columns.tolist() == ["id1", "var", "value"]
+
+ result7 = df.melt(id_vars=["id1", "id2"], var_name=var_name)
+ assert result7.columns.tolist() == ["id1", "id2", "var", "value"]
+
+ result8 = df.melt(id_vars=["id1", "id2"], value_vars="A", var_name=var_name)
+ assert result8.columns.tolist() == ["id1", "id2", "var", "value"]
+
+ result9 = df.melt(
+ id_vars=["id1", "id2"], value_vars=["A", "B"], var_name=var_name
+ )
+ expected9 = DataFrame(
+ {
+ "id1": df["id1"].tolist() * 2,
+ "id2": df["id2"].tolist() * 2,
+ var_name: ["A"] * 10 + ["B"] * 10,
+ "value": (df["A"].tolist() + df["B"].tolist()),
+ },
+ columns=["id1", "id2", var_name, "value"],
+ )
+ tm.assert_frame_equal(result9, expected9)
+
+ def test_custom_value_name(self, df, value_name):
+ result10 = df.melt(value_name=value_name)
+ assert result10.columns.tolist() == ["variable", "val"]
+
+ result11 = df.melt(id_vars=["id1"], value_name=value_name)
+ assert result11.columns.tolist() == ["id1", "variable", "val"]
+
+ result12 = df.melt(id_vars=["id1", "id2"], value_name=value_name)
+ assert result12.columns.tolist() == ["id1", "id2", "variable", "val"]
+
+ result13 = df.melt(
+ id_vars=["id1", "id2"], value_vars="A", value_name=value_name
+ )
+ assert result13.columns.tolist() == ["id1", "id2", "variable", "val"]
+
+ result14 = df.melt(
+ id_vars=["id1", "id2"], value_vars=["A", "B"], value_name=value_name
+ )
+ expected14 = DataFrame(
+ {
+ "id1": df["id1"].tolist() * 2,
+ "id2": df["id2"].tolist() * 2,
+ "variable": ["A"] * 10 + ["B"] * 10,
+ value_name: (df["A"].tolist() + df["B"].tolist()),
+ },
+ columns=["id1", "id2", "variable", value_name],
+ )
+ tm.assert_frame_equal(result14, expected14)
+
+ def test_custom_var_and_value_name(self, df, value_name, var_name):
+ result15 = df.melt(var_name=var_name, value_name=value_name)
+ assert result15.columns.tolist() == ["var", "val"]
+
+ result16 = df.melt(id_vars=["id1"], var_name=var_name, value_name=value_name)
+ assert result16.columns.tolist() == ["id1", "var", "val"]
+
+ result17 = df.melt(
+ id_vars=["id1", "id2"], var_name=var_name, value_name=value_name
+ )
+ assert result17.columns.tolist() == ["id1", "id2", "var", "val"]
+
+ result18 = df.melt(
+ id_vars=["id1", "id2"],
+ value_vars="A",
+ var_name=var_name,
+ value_name=value_name,
+ )
+ assert result18.columns.tolist() == ["id1", "id2", "var", "val"]
+
+ result19 = df.melt(
+ id_vars=["id1", "id2"],
+ value_vars=["A", "B"],
+ var_name=var_name,
+ value_name=value_name,
+ )
+ expected19 = DataFrame(
+ {
+ "id1": df["id1"].tolist() * 2,
+ "id2": df["id2"].tolist() * 2,
+ var_name: ["A"] * 10 + ["B"] * 10,
+ value_name: (df["A"].tolist() + df["B"].tolist()),
+ },
+ columns=["id1", "id2", var_name, value_name],
+ )
+ tm.assert_frame_equal(result19, expected19)
+
+ df20 = df.copy()
+ df20.columns.name = "foo"
+ result20 = df20.melt()
+ assert result20.columns.tolist() == ["foo", "value"]
+
+ @pytest.mark.parametrize("col_level", [0, "CAP"])
+ def test_col_level(self, col_level, df1):
+ res = df1.melt(col_level=col_level)
+ assert res.columns.tolist() == ["CAP", "value"]
+
+ def test_multiindex(self, df1):
+ res = df1.melt()
+ assert res.columns.tolist() == ["CAP", "low", "value"]
+
+ @pytest.mark.parametrize(
+ "col",
+ [
+ pd.Series(pd.date_range("2010", periods=5, tz="US/Pacific")),
+ pd.Series(["a", "b", "c", "a", "d"], dtype="category"),
+ pd.Series([0, 1, 0, 0, 0]),
+ ],
+ )
+ def test_pandas_dtypes(self, col):
+ # GH 15785
+ df = DataFrame(
+ {"klass": range(5), "col": col, "attr1": [1, 0, 0, 0, 0], "attr2": col}
+ )
+ expected_value = pd.concat([pd.Series([1, 0, 0, 0, 0]), col], ignore_index=True)
+ result = melt(
+ df, id_vars=["klass", "col"], var_name="attribute", value_name="value"
+ )
+ expected = DataFrame(
+ {
+ 0: list(range(5)) * 2,
+ 1: pd.concat([col] * 2, ignore_index=True),
+ 2: ["attr1"] * 5 + ["attr2"] * 5,
+ 3: expected_value,
+ }
+ )
+ expected.columns = ["klass", "col", "attribute", "value"]
+ tm.assert_frame_equal(result, expected)
+
+ def test_preserve_category(self):
+ # GH 15853
+ data = DataFrame({"A": [1, 2], "B": pd.Categorical(["X", "Y"])})
+ result = melt(data, ["B"], ["A"])
+ expected = DataFrame(
+ {"B": pd.Categorical(["X", "Y"]), "variable": ["A", "A"], "value": [1, 2]}
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_melt_missing_columns_raises(self):
+ # GH-23575
+ # This test is to ensure that pandas raises an error if melting is
+ # attempted with column names absent from the dataframe
+
+ # Generate data
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 4)), columns=list("abcd")
+ )
+
+ # Try to melt with missing `value_vars` column name
+ msg = "The following '{Var}' are not present in the DataFrame: {Col}"
+ with pytest.raises(
+ KeyError, match=msg.format(Var="value_vars", Col="\\['C'\\]")
+ ):
+ df.melt(["a", "b"], ["C", "d"])
+
+ # Try to melt with missing `id_vars` column name
+ with pytest.raises(KeyError, match=msg.format(Var="id_vars", Col="\\['A'\\]")):
+ df.melt(["A", "b"], ["c", "d"])
+
+ # Multiple missing
+ with pytest.raises(
+ KeyError,
+ match=msg.format(Var="id_vars", Col="\\['not_here', 'or_there'\\]"),
+ ):
+ df.melt(["a", "b", "not_here", "or_there"], ["c", "d"])
+
+ # Multiindex melt fails if column is missing from multilevel melt
+ multi = df.copy()
+ multi.columns = [list("ABCD"), list("abcd")]
+ with pytest.raises(KeyError, match=msg.format(Var="id_vars", Col="\\['E'\\]")):
+ multi.melt([("E", "a")], [("B", "b")])
+ # Multiindex fails if column is missing from single level melt
+ with pytest.raises(
+ KeyError, match=msg.format(Var="value_vars", Col="\\['F'\\]")
+ ):
+ multi.melt(["A"], ["F"], col_level=0)
+
+ def test_melt_mixed_int_str_id_vars(self):
+ # GH 29718
+ df = DataFrame({0: ["foo"], "a": ["bar"], "b": [1], "d": [2]})
+ result = melt(df, id_vars=[0, "a"], value_vars=["b", "d"])
+ expected = DataFrame(
+ {0: ["foo"] * 2, "a": ["bar"] * 2, "variable": list("bd"), "value": [1, 2]}
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_melt_mixed_int_str_value_vars(self):
+ # GH 29718
+ df = DataFrame({0: ["foo"], "a": ["bar"]})
+ result = melt(df, value_vars=[0, "a"])
+ expected = DataFrame({"variable": [0, "a"], "value": ["foo", "bar"]})
+ tm.assert_frame_equal(result, expected)
+
+ def test_ignore_index(self):
+ # GH 17440
+ df = DataFrame({"foo": [0], "bar": [1]}, index=["first"])
+ result = melt(df, ignore_index=False)
+ expected = DataFrame(
+ {"variable": ["foo", "bar"], "value": [0, 1]}, index=["first", "first"]
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_ignore_multiindex(self):
+ # GH 17440
+ index = pd.MultiIndex.from_tuples(
+ [("first", "second"), ("first", "third")], names=["baz", "foobar"]
+ )
+ df = DataFrame({"foo": [0, 1], "bar": [2, 3]}, index=index)
+ result = melt(df, ignore_index=False)
+
+ expected_index = pd.MultiIndex.from_tuples(
+ [("first", "second"), ("first", "third")] * 2, names=["baz", "foobar"]
+ )
+ expected = DataFrame(
+ {"variable": ["foo"] * 2 + ["bar"] * 2, "value": [0, 1, 2, 3]},
+ index=expected_index,
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_ignore_index_name_and_type(self):
+ # GH 17440
+ index = pd.Index(["foo", "bar"], dtype="category", name="baz")
+ df = DataFrame({"x": [0, 1], "y": [2, 3]}, index=index)
+ result = melt(df, ignore_index=False)
+
+ expected_index = pd.Index(["foo", "bar"] * 2, dtype="category", name="baz")
+ expected = DataFrame(
+ {"variable": ["x", "x", "y", "y"], "value": [0, 1, 2, 3]},
+ index=expected_index,
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_melt_with_duplicate_columns(self):
+ # GH#41951
+ df = DataFrame([["id", 2, 3]], columns=["a", "b", "b"])
+ result = df.melt(id_vars=["a"], value_vars=["b"])
+ expected = DataFrame(
+ [["id", "b", 2], ["id", "b", 3]], columns=["a", "variable", "value"]
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["Int8", "Int64"])
+ def test_melt_ea_dtype(self, dtype):
+ # GH#41570
+ df = DataFrame(
+ {
+ "a": pd.Series([1, 2], dtype="Int8"),
+ "b": pd.Series([3, 4], dtype=dtype),
+ }
+ )
+ result = df.melt()
+ expected = DataFrame(
+ {
+ "variable": ["a", "a", "b", "b"],
+ "value": pd.Series([1, 2, 3, 4], dtype=dtype),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_melt_ea_columns(self):
+ # GH 54297
+ df = DataFrame(
+ {
+ "A": {0: "a", 1: "b", 2: "c"},
+ "B": {0: 1, 1: 3, 2: 5},
+ "C": {0: 2, 1: 4, 2: 6},
+ }
+ )
+ df.columns = df.columns.astype("string[python]")
+ result = df.melt(id_vars=["A"], value_vars=["B"])
+ expected = DataFrame(
+ {
+ "A": list("abc"),
+ "variable": pd.Series(["B"] * 3, dtype="string[python]"),
+ "value": [1, 3, 5],
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+class TestLreshape:
+ def test_pairs(self):
+ data = {
+ "birthdt": [
+ "08jan2009",
+ "20dec2008",
+ "30dec2008",
+ "21dec2008",
+ "11jan2009",
+ ],
+ "birthwt": [1766, 3301, 1454, 3139, 4133],
+ "id": [101, 102, 103, 104, 105],
+ "sex": ["Male", "Female", "Female", "Female", "Female"],
+ "visitdt1": [
+ "11jan2009",
+ "22dec2008",
+ "04jan2009",
+ "29dec2008",
+ "20jan2009",
+ ],
+ "visitdt2": ["21jan2009", np.nan, "22jan2009", "31dec2008", "03feb2009"],
+ "visitdt3": ["05feb2009", np.nan, np.nan, "02jan2009", "15feb2009"],
+ "wt1": [1823, 3338, 1549, 3298, 4306],
+ "wt2": [2011.0, np.nan, 1892.0, 3338.0, 4575.0],
+ "wt3": [2293.0, np.nan, np.nan, 3377.0, 4805.0],
+ }
+
+ df = DataFrame(data)
+
+ spec = {
+ "visitdt": [f"visitdt{i:d}" for i in range(1, 4)],
+ "wt": [f"wt{i:d}" for i in range(1, 4)],
+ }
+ result = lreshape(df, spec)
+
+ exp_data = {
+ "birthdt": [
+ "08jan2009",
+ "20dec2008",
+ "30dec2008",
+ "21dec2008",
+ "11jan2009",
+ "08jan2009",
+ "30dec2008",
+ "21dec2008",
+ "11jan2009",
+ "08jan2009",
+ "21dec2008",
+ "11jan2009",
+ ],
+ "birthwt": [
+ 1766,
+ 3301,
+ 1454,
+ 3139,
+ 4133,
+ 1766,
+ 1454,
+ 3139,
+ 4133,
+ 1766,
+ 3139,
+ 4133,
+ ],
+ "id": [101, 102, 103, 104, 105, 101, 103, 104, 105, 101, 104, 105],
+ "sex": [
+ "Male",
+ "Female",
+ "Female",
+ "Female",
+ "Female",
+ "Male",
+ "Female",
+ "Female",
+ "Female",
+ "Male",
+ "Female",
+ "Female",
+ ],
+ "visitdt": [
+ "11jan2009",
+ "22dec2008",
+ "04jan2009",
+ "29dec2008",
+ "20jan2009",
+ "21jan2009",
+ "22jan2009",
+ "31dec2008",
+ "03feb2009",
+ "05feb2009",
+ "02jan2009",
+ "15feb2009",
+ ],
+ "wt": [
+ 1823.0,
+ 3338.0,
+ 1549.0,
+ 3298.0,
+ 4306.0,
+ 2011.0,
+ 1892.0,
+ 3338.0,
+ 4575.0,
+ 2293.0,
+ 3377.0,
+ 4805.0,
+ ],
+ }
+ exp = DataFrame(exp_data, columns=result.columns)
+ tm.assert_frame_equal(result, exp)
+
+ result = lreshape(df, spec, dropna=False)
+ exp_data = {
+ "birthdt": [
+ "08jan2009",
+ "20dec2008",
+ "30dec2008",
+ "21dec2008",
+ "11jan2009",
+ "08jan2009",
+ "20dec2008",
+ "30dec2008",
+ "21dec2008",
+ "11jan2009",
+ "08jan2009",
+ "20dec2008",
+ "30dec2008",
+ "21dec2008",
+ "11jan2009",
+ ],
+ "birthwt": [
+ 1766,
+ 3301,
+ 1454,
+ 3139,
+ 4133,
+ 1766,
+ 3301,
+ 1454,
+ 3139,
+ 4133,
+ 1766,
+ 3301,
+ 1454,
+ 3139,
+ 4133,
+ ],
+ "id": [
+ 101,
+ 102,
+ 103,
+ 104,
+ 105,
+ 101,
+ 102,
+ 103,
+ 104,
+ 105,
+ 101,
+ 102,
+ 103,
+ 104,
+ 105,
+ ],
+ "sex": [
+ "Male",
+ "Female",
+ "Female",
+ "Female",
+ "Female",
+ "Male",
+ "Female",
+ "Female",
+ "Female",
+ "Female",
+ "Male",
+ "Female",
+ "Female",
+ "Female",
+ "Female",
+ ],
+ "visitdt": [
+ "11jan2009",
+ "22dec2008",
+ "04jan2009",
+ "29dec2008",
+ "20jan2009",
+ "21jan2009",
+ np.nan,
+ "22jan2009",
+ "31dec2008",
+ "03feb2009",
+ "05feb2009",
+ np.nan,
+ np.nan,
+ "02jan2009",
+ "15feb2009",
+ ],
+ "wt": [
+ 1823.0,
+ 3338.0,
+ 1549.0,
+ 3298.0,
+ 4306.0,
+ 2011.0,
+ np.nan,
+ 1892.0,
+ 3338.0,
+ 4575.0,
+ 2293.0,
+ np.nan,
+ np.nan,
+ 3377.0,
+ 4805.0,
+ ],
+ }
+ exp = DataFrame(exp_data, columns=result.columns)
+ tm.assert_frame_equal(result, exp)
+
+ spec = {
+ "visitdt": [f"visitdt{i:d}" for i in range(1, 3)],
+ "wt": [f"wt{i:d}" for i in range(1, 4)],
+ }
+ msg = "All column lists must be same length"
+ with pytest.raises(ValueError, match=msg):
+ lreshape(df, spec)
+
+
+class TestWideToLong:
+ def test_simple(self):
+ x = np.random.default_rng(2).standard_normal(3)
+ df = DataFrame(
+ {
+ "A1970": {0: "a", 1: "b", 2: "c"},
+ "A1980": {0: "d", 1: "e", 2: "f"},
+ "B1970": {0: 2.5, 1: 1.2, 2: 0.7},
+ "B1980": {0: 3.2, 1: 1.3, 2: 0.1},
+ "X": dict(zip(range(3), x)),
+ }
+ )
+ df["id"] = df.index
+ exp_data = {
+ "X": x.tolist() + x.tolist(),
+ "A": ["a", "b", "c", "d", "e", "f"],
+ "B": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1],
+ "year": [1970, 1970, 1970, 1980, 1980, 1980],
+ "id": [0, 1, 2, 0, 1, 2],
+ }
+ expected = DataFrame(exp_data)
+ expected = expected.set_index(["id", "year"])[["X", "A", "B"]]
+ result = wide_to_long(df, ["A", "B"], i="id", j="year")
+ tm.assert_frame_equal(result, expected)
+
+ def test_stubs(self):
+ # GH9204 wide_to_long call should not modify 'stubs' list
+ df = DataFrame([[0, 1, 2, 3, 8], [4, 5, 6, 7, 9]])
+ df.columns = ["id", "inc1", "inc2", "edu1", "edu2"]
+ stubs = ["inc", "edu"]
+
+ wide_to_long(df, stubs, i="id", j="age")
+
+ assert stubs == ["inc", "edu"]
+
+ def test_separating_character(self):
+ # GH14779
+
+ x = np.random.default_rng(2).standard_normal(3)
+ df = DataFrame(
+ {
+ "A.1970": {0: "a", 1: "b", 2: "c"},
+ "A.1980": {0: "d", 1: "e", 2: "f"},
+ "B.1970": {0: 2.5, 1: 1.2, 2: 0.7},
+ "B.1980": {0: 3.2, 1: 1.3, 2: 0.1},
+ "X": dict(zip(range(3), x)),
+ }
+ )
+ df["id"] = df.index
+ exp_data = {
+ "X": x.tolist() + x.tolist(),
+ "A": ["a", "b", "c", "d", "e", "f"],
+ "B": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1],
+ "year": [1970, 1970, 1970, 1980, 1980, 1980],
+ "id": [0, 1, 2, 0, 1, 2],
+ }
+ expected = DataFrame(exp_data)
+ expected = expected.set_index(["id", "year"])[["X", "A", "B"]]
+ result = wide_to_long(df, ["A", "B"], i="id", j="year", sep=".")
+ tm.assert_frame_equal(result, expected)
+
+ def test_escapable_characters(self):
+ x = np.random.default_rng(2).standard_normal(3)
+ df = DataFrame(
+ {
+ "A(quarterly)1970": {0: "a", 1: "b", 2: "c"},
+ "A(quarterly)1980": {0: "d", 1: "e", 2: "f"},
+ "B(quarterly)1970": {0: 2.5, 1: 1.2, 2: 0.7},
+ "B(quarterly)1980": {0: 3.2, 1: 1.3, 2: 0.1},
+ "X": dict(zip(range(3), x)),
+ }
+ )
+ df["id"] = df.index
+ exp_data = {
+ "X": x.tolist() + x.tolist(),
+ "A(quarterly)": ["a", "b", "c", "d", "e", "f"],
+ "B(quarterly)": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1],
+ "year": [1970, 1970, 1970, 1980, 1980, 1980],
+ "id": [0, 1, 2, 0, 1, 2],
+ }
+ expected = DataFrame(exp_data)
+ expected = expected.set_index(["id", "year"])[
+ ["X", "A(quarterly)", "B(quarterly)"]
+ ]
+ result = wide_to_long(df, ["A(quarterly)", "B(quarterly)"], i="id", j="year")
+ tm.assert_frame_equal(result, expected)
+
+ def test_unbalanced(self):
+ # test that we can have a varying amount of time variables
+ df = DataFrame(
+ {
+ "A2010": [1.0, 2.0],
+ "A2011": [3.0, 4.0],
+ "B2010": [5.0, 6.0],
+ "X": ["X1", "X2"],
+ }
+ )
+ df["id"] = df.index
+ exp_data = {
+ "X": ["X1", "X2", "X1", "X2"],
+ "A": [1.0, 2.0, 3.0, 4.0],
+ "B": [5.0, 6.0, np.nan, np.nan],
+ "id": [0, 1, 0, 1],
+ "year": [2010, 2010, 2011, 2011],
+ }
+ expected = DataFrame(exp_data)
+ expected = expected.set_index(["id", "year"])[["X", "A", "B"]]
+ result = wide_to_long(df, ["A", "B"], i="id", j="year")
+ tm.assert_frame_equal(result, expected)
+
+ def test_character_overlap(self):
+ # Test we handle overlapping characters in both id_vars and value_vars
+ df = DataFrame(
+ {
+ "A11": ["a11", "a22", "a33"],
+ "A12": ["a21", "a22", "a23"],
+ "B11": ["b11", "b12", "b13"],
+ "B12": ["b21", "b22", "b23"],
+ "BB11": [1, 2, 3],
+ "BB12": [4, 5, 6],
+ "BBBX": [91, 92, 93],
+ "BBBZ": [91, 92, 93],
+ }
+ )
+ df["id"] = df.index
+ expected = DataFrame(
+ {
+ "BBBX": [91, 92, 93, 91, 92, 93],
+ "BBBZ": [91, 92, 93, 91, 92, 93],
+ "A": ["a11", "a22", "a33", "a21", "a22", "a23"],
+ "B": ["b11", "b12", "b13", "b21", "b22", "b23"],
+ "BB": [1, 2, 3, 4, 5, 6],
+ "id": [0, 1, 2, 0, 1, 2],
+ "year": [11, 11, 11, 12, 12, 12],
+ }
+ )
+ expected = expected.set_index(["id", "year"])[["BBBX", "BBBZ", "A", "B", "BB"]]
+ result = wide_to_long(df, ["A", "B", "BB"], i="id", j="year")
+ tm.assert_frame_equal(result.sort_index(axis=1), expected.sort_index(axis=1))
+
+ def test_invalid_separator(self):
+ # if an invalid separator is supplied a empty data frame is returned
+ sep = "nope!"
+ df = DataFrame(
+ {
+ "A2010": [1.0, 2.0],
+ "A2011": [3.0, 4.0],
+ "B2010": [5.0, 6.0],
+ "X": ["X1", "X2"],
+ }
+ )
+ df["id"] = df.index
+ exp_data = {
+ "X": "",
+ "A2010": [],
+ "A2011": [],
+ "B2010": [],
+ "id": [],
+ "year": [],
+ "A": [],
+ "B": [],
+ }
+ expected = DataFrame(exp_data).astype({"year": np.int64})
+ expected = expected.set_index(["id", "year"])[
+ ["X", "A2010", "A2011", "B2010", "A", "B"]
+ ]
+ expected.index = expected.index.set_levels([0, 1], level=0)
+ result = wide_to_long(df, ["A", "B"], i="id", j="year", sep=sep)
+ tm.assert_frame_equal(result.sort_index(axis=1), expected.sort_index(axis=1))
+
+ def test_num_string_disambiguation(self):
+ # Test that we can disambiguate number value_vars from
+ # string value_vars
+ df = DataFrame(
+ {
+ "A11": ["a11", "a22", "a33"],
+ "A12": ["a21", "a22", "a23"],
+ "B11": ["b11", "b12", "b13"],
+ "B12": ["b21", "b22", "b23"],
+ "BB11": [1, 2, 3],
+ "BB12": [4, 5, 6],
+ "Arating": [91, 92, 93],
+ "Arating_old": [91, 92, 93],
+ }
+ )
+ df["id"] = df.index
+ expected = DataFrame(
+ {
+ "Arating": [91, 92, 93, 91, 92, 93],
+ "Arating_old": [91, 92, 93, 91, 92, 93],
+ "A": ["a11", "a22", "a33", "a21", "a22", "a23"],
+ "B": ["b11", "b12", "b13", "b21", "b22", "b23"],
+ "BB": [1, 2, 3, 4, 5, 6],
+ "id": [0, 1, 2, 0, 1, 2],
+ "year": [11, 11, 11, 12, 12, 12],
+ }
+ )
+ expected = expected.set_index(["id", "year"])[
+ ["Arating", "Arating_old", "A", "B", "BB"]
+ ]
+ result = wide_to_long(df, ["A", "B", "BB"], i="id", j="year")
+ tm.assert_frame_equal(result.sort_index(axis=1), expected.sort_index(axis=1))
+
+ def test_invalid_suffixtype(self):
+ # If all stubs names end with a string, but a numeric suffix is
+ # assumed, an empty data frame is returned
+ df = DataFrame(
+ {
+ "Aone": [1.0, 2.0],
+ "Atwo": [3.0, 4.0],
+ "Bone": [5.0, 6.0],
+ "X": ["X1", "X2"],
+ }
+ )
+ df["id"] = df.index
+ exp_data = {
+ "X": "",
+ "Aone": [],
+ "Atwo": [],
+ "Bone": [],
+ "id": [],
+ "year": [],
+ "A": [],
+ "B": [],
+ }
+ expected = DataFrame(exp_data).astype({"year": np.int64})
+
+ expected = expected.set_index(["id", "year"])
+ expected.index = expected.index.set_levels([0, 1], level=0)
+ result = wide_to_long(df, ["A", "B"], i="id", j="year")
+ tm.assert_frame_equal(result.sort_index(axis=1), expected.sort_index(axis=1))
+
+ def test_multiple_id_columns(self):
+ # Taken from http://www.ats.ucla.edu/stat/stata/modules/reshapel.htm
+ df = DataFrame(
+ {
+ "famid": [1, 1, 1, 2, 2, 2, 3, 3, 3],
+ "birth": [1, 2, 3, 1, 2, 3, 1, 2, 3],
+ "ht1": [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],
+ "ht2": [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9],
+ }
+ )
+ expected = DataFrame(
+ {
+ "ht": [
+ 2.8,
+ 3.4,
+ 2.9,
+ 3.8,
+ 2.2,
+ 2.9,
+ 2.0,
+ 3.2,
+ 1.8,
+ 2.8,
+ 1.9,
+ 2.4,
+ 2.2,
+ 3.3,
+ 2.3,
+ 3.4,
+ 2.1,
+ 2.9,
+ ],
+ "famid": [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3],
+ "birth": [1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3],
+ "age": [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
+ }
+ )
+ expected = expected.set_index(["famid", "birth", "age"])[["ht"]]
+ result = wide_to_long(df, "ht", i=["famid", "birth"], j="age")
+ tm.assert_frame_equal(result, expected)
+
+ def test_non_unique_idvars(self):
+ # GH16382
+ # Raise an error message if non unique id vars (i) are passed
+ df = DataFrame(
+ {"A_A1": [1, 2, 3, 4, 5], "B_B1": [1, 2, 3, 4, 5], "x": [1, 1, 1, 1, 1]}
+ )
+ msg = "the id variables need to uniquely identify each row"
+ with pytest.raises(ValueError, match=msg):
+ wide_to_long(df, ["A_A", "B_B"], i="x", j="colname")
+
+ def test_cast_j_int(self):
+ df = DataFrame(
+ {
+ "actor_1": ["CCH Pounder", "Johnny Depp", "Christoph Waltz"],
+ "actor_2": ["Joel David Moore", "Orlando Bloom", "Rory Kinnear"],
+ "actor_fb_likes_1": [1000.0, 40000.0, 11000.0],
+ "actor_fb_likes_2": [936.0, 5000.0, 393.0],
+ "title": ["Avatar", "Pirates of the Caribbean", "Spectre"],
+ }
+ )
+
+ expected = DataFrame(
+ {
+ "actor": [
+ "CCH Pounder",
+ "Johnny Depp",
+ "Christoph Waltz",
+ "Joel David Moore",
+ "Orlando Bloom",
+ "Rory Kinnear",
+ ],
+ "actor_fb_likes": [1000.0, 40000.0, 11000.0, 936.0, 5000.0, 393.0],
+ "num": [1, 1, 1, 2, 2, 2],
+ "title": [
+ "Avatar",
+ "Pirates of the Caribbean",
+ "Spectre",
+ "Avatar",
+ "Pirates of the Caribbean",
+ "Spectre",
+ ],
+ }
+ ).set_index(["title", "num"])
+ result = wide_to_long(
+ df, ["actor", "actor_fb_likes"], i="title", j="num", sep="_"
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_identical_stubnames(self):
+ df = DataFrame(
+ {
+ "A2010": [1.0, 2.0],
+ "A2011": [3.0, 4.0],
+ "B2010": [5.0, 6.0],
+ "A": ["X1", "X2"],
+ }
+ )
+ msg = "stubname can't be identical to a column name"
+ with pytest.raises(ValueError, match=msg):
+ wide_to_long(df, ["A", "B"], i="A", j="colname")
+
+ def test_nonnumeric_suffix(self):
+ df = DataFrame(
+ {
+ "treatment_placebo": [1.0, 2.0],
+ "treatment_test": [3.0, 4.0],
+ "result_placebo": [5.0, 6.0],
+ "A": ["X1", "X2"],
+ }
+ )
+ expected = DataFrame(
+ {
+ "A": ["X1", "X2", "X1", "X2"],
+ "colname": ["placebo", "placebo", "test", "test"],
+ "result": [5.0, 6.0, np.nan, np.nan],
+ "treatment": [1.0, 2.0, 3.0, 4.0],
+ }
+ )
+ expected = expected.set_index(["A", "colname"])
+ result = wide_to_long(
+ df, ["result", "treatment"], i="A", j="colname", suffix="[a-z]+", sep="_"
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_mixed_type_suffix(self):
+ df = DataFrame(
+ {
+ "A": ["X1", "X2"],
+ "result_1": [0, 9],
+ "result_foo": [5.0, 6.0],
+ "treatment_1": [1.0, 2.0],
+ "treatment_foo": [3.0, 4.0],
+ }
+ )
+ expected = DataFrame(
+ {
+ "A": ["X1", "X2", "X1", "X2"],
+ "colname": ["1", "1", "foo", "foo"],
+ "result": [0.0, 9.0, 5.0, 6.0],
+ "treatment": [1.0, 2.0, 3.0, 4.0],
+ }
+ ).set_index(["A", "colname"])
+ result = wide_to_long(
+ df, ["result", "treatment"], i="A", j="colname", suffix=".+", sep="_"
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_float_suffix(self):
+ df = DataFrame(
+ {
+ "treatment_1.1": [1.0, 2.0],
+ "treatment_2.1": [3.0, 4.0],
+ "result_1.2": [5.0, 6.0],
+ "result_1": [0, 9],
+ "A": ["X1", "X2"],
+ }
+ )
+ expected = DataFrame(
+ {
+ "A": ["X1", "X2", "X1", "X2", "X1", "X2", "X1", "X2"],
+ "colname": [1.2, 1.2, 1.0, 1.0, 1.1, 1.1, 2.1, 2.1],
+ "result": [5.0, 6.0, 0.0, 9.0, np.nan, np.nan, np.nan, np.nan],
+ "treatment": [np.nan, np.nan, np.nan, np.nan, 1.0, 2.0, 3.0, 4.0],
+ }
+ )
+ expected = expected.set_index(["A", "colname"])
+ result = wide_to_long(
+ df, ["result", "treatment"], i="A", j="colname", suffix="[0-9.]+", sep="_"
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_col_substring_of_stubname(self):
+ # GH22468
+ # Don't raise ValueError when a column name is a substring
+ # of a stubname that's been passed as a string
+ wide_data = {
+ "node_id": {0: 0, 1: 1, 2: 2, 3: 3, 4: 4},
+ "A": {0: 0.80, 1: 0.0, 2: 0.25, 3: 1.0, 4: 0.81},
+ "PA0": {0: 0.74, 1: 0.56, 2: 0.56, 3: 0.98, 4: 0.6},
+ "PA1": {0: 0.77, 1: 0.64, 2: 0.52, 3: 0.98, 4: 0.67},
+ "PA3": {0: 0.34, 1: 0.70, 2: 0.52, 3: 0.98, 4: 0.67},
+ }
+ wide_df = DataFrame.from_dict(wide_data)
+ expected = wide_to_long(wide_df, stubnames=["PA"], i=["node_id", "A"], j="time")
+ result = wide_to_long(wide_df, stubnames="PA", i=["node_id", "A"], j="time")
+ tm.assert_frame_equal(result, expected)
+
+ def test_raise_of_column_name_value(self):
+ # GH34731, enforced in 2.0
+ # raise a ValueError if the resultant value column name matches
+ # a name in the dataframe already (default name is "value")
+ df = DataFrame({"col": list("ABC"), "value": range(10, 16, 2)})
+
+ with pytest.raises(
+ ValueError, match=re.escape("value_name (value) cannot match")
+ ):
+ df.melt(id_vars="value", value_name="value")
+
+ @pytest.mark.parametrize("dtype", ["O", "string"])
+ def test_missing_stubname(self, dtype):
+ # GH46044
+ df = DataFrame({"id": ["1", "2"], "a-1": [100, 200], "a-2": [300, 400]})
+ df = df.astype({"id": dtype})
+ result = wide_to_long(
+ df,
+ stubnames=["a", "b"],
+ i="id",
+ j="num",
+ sep="-",
+ )
+ index = pd.Index(
+ [("1", 1), ("2", 1), ("1", 2), ("2", 2)],
+ name=("id", "num"),
+ )
+ expected = DataFrame(
+ {"a": [100, 200, 300, 400], "b": [np.nan] * 4},
+ index=index,
+ )
+ new_level = expected.index.levels[0].astype(dtype)
+ expected.index = expected.index.set_levels(new_level, level=0)
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_pivot.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_pivot.py
new file mode 100644
index 0000000000000000000000000000000000000000..46da18445e13569b103ee23ff0afa80c9af4eb1f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_pivot.py
@@ -0,0 +1,2663 @@
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
+from itertools import product
+import re
+
+import numpy as np
+import pytest
+
+from pandas.errors import PerformanceWarning
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DataFrame,
+ Grouper,
+ Index,
+ MultiIndex,
+ Series,
+ concat,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.api.types import CategoricalDtype as CDT
+from pandas.core.reshape import reshape as reshape_lib
+from pandas.core.reshape.pivot import pivot_table
+
+
+@pytest.fixture(params=[True, False])
+def dropna(request):
+ return request.param
+
+
+@pytest.fixture(params=[([0] * 4, [1] * 4), (range(0, 3), range(1, 4))])
+def interval_values(request, closed):
+ left, right = request.param
+ return Categorical(pd.IntervalIndex.from_arrays(left, right, closed))
+
+
+class TestPivotTable:
+ @pytest.fixture
+ def data(self):
+ return DataFrame(
+ {
+ "A": [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ "foo",
+ "foo",
+ "foo",
+ ],
+ "B": [
+ "one",
+ "one",
+ "one",
+ "two",
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "two",
+ "one",
+ ],
+ "C": [
+ "dull",
+ "dull",
+ "shiny",
+ "dull",
+ "dull",
+ "shiny",
+ "shiny",
+ "dull",
+ "shiny",
+ "shiny",
+ "shiny",
+ ],
+ "D": np.random.default_rng(2).standard_normal(11),
+ "E": np.random.default_rng(2).standard_normal(11),
+ "F": np.random.default_rng(2).standard_normal(11),
+ }
+ )
+
+ def test_pivot_table(self, observed, data):
+ index = ["A", "B"]
+ columns = "C"
+ table = pivot_table(
+ data, values="D", index=index, columns=columns, observed=observed
+ )
+
+ table2 = data.pivot_table(
+ values="D", index=index, columns=columns, observed=observed
+ )
+ tm.assert_frame_equal(table, table2)
+
+ # this works
+ pivot_table(data, values="D", index=index, observed=observed)
+
+ if len(index) > 1:
+ assert table.index.names == tuple(index)
+ else:
+ assert table.index.name == index[0]
+
+ if len(columns) > 1:
+ assert table.columns.names == columns
+ else:
+ assert table.columns.name == columns[0]
+
+ expected = data.groupby(index + [columns])["D"].agg("mean").unstack()
+ tm.assert_frame_equal(table, expected)
+
+ def test_pivot_table_categorical_observed_equal(self, observed):
+ # issue #24923
+ df = DataFrame(
+ {"col1": list("abcde"), "col2": list("fghij"), "col3": [1, 2, 3, 4, 5]}
+ )
+
+ expected = df.pivot_table(
+ index="col1", values="col3", columns="col2", aggfunc="sum", fill_value=0
+ )
+
+ expected.index = expected.index.astype("category")
+ expected.columns = expected.columns.astype("category")
+
+ df.col1 = df.col1.astype("category")
+ df.col2 = df.col2.astype("category")
+
+ result = df.pivot_table(
+ index="col1",
+ values="col3",
+ columns="col2",
+ aggfunc="sum",
+ fill_value=0,
+ observed=observed,
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_nocols(self):
+ df = DataFrame(
+ {"rows": ["a", "b", "c"], "cols": ["x", "y", "z"], "values": [1, 2, 3]}
+ )
+ rs = df.pivot_table(columns="cols", aggfunc="sum")
+ xp = df.pivot_table(index="cols", aggfunc="sum").T
+ tm.assert_frame_equal(rs, xp)
+
+ rs = df.pivot_table(columns="cols", aggfunc={"values": "mean"})
+ xp = df.pivot_table(index="cols", aggfunc={"values": "mean"}).T
+ tm.assert_frame_equal(rs, xp)
+
+ def test_pivot_table_dropna(self):
+ df = DataFrame(
+ {
+ "amount": {0: 60000, 1: 100000, 2: 50000, 3: 30000},
+ "customer": {0: "A", 1: "A", 2: "B", 3: "C"},
+ "month": {0: 201307, 1: 201309, 2: 201308, 3: 201310},
+ "product": {0: "a", 1: "b", 2: "c", 3: "d"},
+ "quantity": {0: 2000000, 1: 500000, 2: 1000000, 3: 1000000},
+ }
+ )
+ pv_col = df.pivot_table(
+ "quantity", "month", ["customer", "product"], dropna=False
+ )
+ pv_ind = df.pivot_table(
+ "quantity", ["customer", "product"], "month", dropna=False
+ )
+
+ m = MultiIndex.from_tuples(
+ [
+ ("A", "a"),
+ ("A", "b"),
+ ("A", "c"),
+ ("A", "d"),
+ ("B", "a"),
+ ("B", "b"),
+ ("B", "c"),
+ ("B", "d"),
+ ("C", "a"),
+ ("C", "b"),
+ ("C", "c"),
+ ("C", "d"),
+ ],
+ names=["customer", "product"],
+ )
+ tm.assert_index_equal(pv_col.columns, m)
+ tm.assert_index_equal(pv_ind.index, m)
+
+ def test_pivot_table_categorical(self):
+ cat1 = Categorical(
+ ["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True
+ )
+ cat2 = Categorical(
+ ["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True
+ )
+ df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]})
+ result = pivot_table(df, values="values", index=["A", "B"], dropna=True)
+
+ exp_index = MultiIndex.from_arrays([cat1, cat2], names=["A", "B"])
+ expected = DataFrame({"values": [1.0, 2.0, 3.0, 4.0]}, index=exp_index)
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_dropna_categoricals(self, dropna):
+ # GH 15193
+ categories = ["a", "b", "c", "d"]
+
+ df = DataFrame(
+ {
+ "A": ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
+ "B": [1, 2, 3, 1, 2, 3, 1, 2, 3],
+ "C": range(0, 9),
+ }
+ )
+
+ df["A"] = df["A"].astype(CDT(categories, ordered=False))
+ result = df.pivot_table(index="B", columns="A", values="C", dropna=dropna)
+ expected_columns = Series(["a", "b", "c"], name="A")
+ expected_columns = expected_columns.astype(CDT(categories, ordered=False))
+ expected_index = Series([1, 2, 3], name="B")
+ expected = DataFrame(
+ [[0.0, 3.0, 6.0], [1.0, 4.0, 7.0], [2.0, 5.0, 8.0]],
+ index=expected_index,
+ columns=expected_columns,
+ )
+ if not dropna:
+ # add back the non observed to compare
+ expected = expected.reindex(columns=Categorical(categories)).astype("float")
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_with_non_observable_dropna(self, dropna):
+ # gh-21133
+ df = DataFrame(
+ {
+ "A": Categorical(
+ [np.nan, "low", "high", "low", "high"],
+ categories=["low", "high"],
+ ordered=True,
+ ),
+ "B": [0.0, 1.0, 2.0, 3.0, 4.0],
+ }
+ )
+
+ result = df.pivot_table(index="A", values="B", dropna=dropna)
+ if dropna:
+ values = [2.0, 3.0]
+ codes = [0, 1]
+ else:
+ # GH: 10772
+ values = [2.0, 3.0, 0.0]
+ codes = [0, 1, -1]
+ expected = DataFrame(
+ {"B": values},
+ index=Index(
+ Categorical.from_codes(
+ codes, categories=["low", "high"], ordered=dropna
+ ),
+ name="A",
+ ),
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_with_non_observable_dropna_multi_cat(self, dropna):
+ # gh-21378
+ df = DataFrame(
+ {
+ "A": Categorical(
+ ["left", "low", "high", "low", "high"],
+ categories=["low", "high", "left"],
+ ordered=True,
+ ),
+ "B": range(5),
+ }
+ )
+
+ result = df.pivot_table(index="A", values="B", dropna=dropna)
+ expected = DataFrame(
+ {"B": [2.0, 3.0, 0.0]},
+ index=Index(
+ Categorical.from_codes(
+ [0, 1, 2], categories=["low", "high", "left"], ordered=True
+ ),
+ name="A",
+ ),
+ )
+ if not dropna:
+ expected["B"] = expected["B"].astype(float)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_with_interval_index(self, interval_values, dropna):
+ # GH 25814
+ df = DataFrame({"A": interval_values, "B": 1})
+ result = df.pivot_table(index="A", values="B", dropna=dropna)
+ expected = DataFrame(
+ {"B": 1.0}, index=Index(interval_values.unique(), name="A")
+ )
+ if not dropna:
+ expected = expected.astype(float)
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_with_interval_index_margins(self):
+ # GH 25815
+ ordered_cat = pd.IntervalIndex.from_arrays([0, 0, 1, 1], [1, 1, 2, 2])
+ df = DataFrame(
+ {
+ "A": np.arange(4, 0, -1, dtype=np.intp),
+ "B": ["a", "b", "a", "b"],
+ "C": Categorical(ordered_cat, ordered=True).sort_values(
+ ascending=False
+ ),
+ }
+ )
+
+ pivot_tab = pivot_table(
+ df, index="C", columns="B", values="A", aggfunc="sum", margins=True
+ )
+
+ result = pivot_tab["All"]
+ expected = Series(
+ [3, 7, 10],
+ index=Index([pd.Interval(0, 1), pd.Interval(1, 2), "All"], name="C"),
+ name="All",
+ dtype=np.intp,
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_pass_array(self, data):
+ result = data.pivot_table("D", index=data.A, columns=data.C)
+ expected = data.pivot_table("D", index="A", columns="C")
+ tm.assert_frame_equal(result, expected)
+
+ def test_pass_function(self, data):
+ result = data.pivot_table("D", index=lambda x: x // 5, columns=data.C)
+ expected = data.pivot_table("D", index=data.index // 5, columns="C")
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_multiple(self, data):
+ index = ["A", "B"]
+ columns = "C"
+ table = pivot_table(data, index=index, columns=columns)
+ expected = data.groupby(index + [columns]).agg("mean").unstack()
+ tm.assert_frame_equal(table, expected)
+
+ def test_pivot_dtypes(self):
+ # can convert dtypes
+ f = DataFrame(
+ {
+ "a": ["cat", "bat", "cat", "bat"],
+ "v": [1, 2, 3, 4],
+ "i": ["a", "b", "a", "b"],
+ }
+ )
+ assert f.dtypes["v"] == "int64"
+
+ z = pivot_table(
+ f, values="v", index=["a"], columns=["i"], fill_value=0, aggfunc="sum"
+ )
+ result = z.dtypes
+ expected = Series([np.dtype("int64")] * 2, index=Index(list("ab"), name="i"))
+ tm.assert_series_equal(result, expected)
+
+ # cannot convert dtypes
+ f = DataFrame(
+ {
+ "a": ["cat", "bat", "cat", "bat"],
+ "v": [1.5, 2.5, 3.5, 4.5],
+ "i": ["a", "b", "a", "b"],
+ }
+ )
+ assert f.dtypes["v"] == "float64"
+
+ z = pivot_table(
+ f, values="v", index=["a"], columns=["i"], fill_value=0, aggfunc="mean"
+ )
+ result = z.dtypes
+ expected = Series([np.dtype("float64")] * 2, index=Index(list("ab"), name="i"))
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "columns,values",
+ [
+ ("bool1", ["float1", "float2"]),
+ ("bool1", ["float1", "float2", "bool1"]),
+ ("bool2", ["float1", "float2", "bool1"]),
+ ],
+ )
+ def test_pivot_preserve_dtypes(self, columns, values):
+ # GH 7142 regression test
+ v = np.arange(5, dtype=np.float64)
+ df = DataFrame(
+ {"float1": v, "float2": v + 2.0, "bool1": v <= 2, "bool2": v <= 3}
+ )
+
+ df_res = df.reset_index().pivot_table(
+ index="index", columns=columns, values=values
+ )
+
+ result = dict(df_res.dtypes)
+ expected = {col: np.dtype("float64") for col in df_res}
+ assert result == expected
+
+ def test_pivot_no_values(self):
+ # GH 14380
+ idx = pd.DatetimeIndex(
+ ["2011-01-01", "2011-02-01", "2011-01-02", "2011-01-01", "2011-01-02"]
+ )
+ df = DataFrame({"A": [1, 2, 3, 4, 5]}, index=idx)
+ res = df.pivot_table(index=df.index.month, columns=df.index.day)
+
+ exp_columns = MultiIndex.from_tuples([("A", 1), ("A", 2)])
+ exp_columns = exp_columns.set_levels(
+ exp_columns.levels[1].astype(np.int32), level=1
+ )
+ exp = DataFrame(
+ [[2.5, 4.0], [2.0, np.nan]],
+ index=Index([1, 2], dtype=np.int32),
+ columns=exp_columns,
+ )
+ tm.assert_frame_equal(res, exp)
+
+ df = DataFrame(
+ {
+ "A": [1, 2, 3, 4, 5],
+ "dt": date_range("2011-01-01", freq="D", periods=5),
+ },
+ index=idx,
+ )
+ res = df.pivot_table(index=df.index.month, columns=Grouper(key="dt", freq="M"))
+ exp_columns = MultiIndex.from_tuples([("A", pd.Timestamp("2011-01-31"))])
+ exp_columns.names = [None, "dt"]
+ exp = DataFrame(
+ [3.25, 2.0], index=Index([1, 2], dtype=np.int32), columns=exp_columns
+ )
+ tm.assert_frame_equal(res, exp)
+
+ res = df.pivot_table(
+ index=Grouper(freq="A"), columns=Grouper(key="dt", freq="M")
+ )
+ exp = DataFrame(
+ [3.0], index=pd.DatetimeIndex(["2011-12-31"], freq="A"), columns=exp_columns
+ )
+ tm.assert_frame_equal(res, exp)
+
+ def test_pivot_multi_values(self, data):
+ result = pivot_table(
+ data, values=["D", "E"], index="A", columns=["B", "C"], fill_value=0
+ )
+ expected = pivot_table(
+ data.drop(["F"], axis=1), index="A", columns=["B", "C"], fill_value=0
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_multi_functions(self, data):
+ f = lambda func: pivot_table(
+ data, values=["D", "E"], index=["A", "B"], columns="C", aggfunc=func
+ )
+ result = f(["mean", "std"])
+ means = f("mean")
+ stds = f("std")
+ expected = concat([means, stds], keys=["mean", "std"], axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ # margins not supported??
+ f = lambda func: pivot_table(
+ data,
+ values=["D", "E"],
+ index=["A", "B"],
+ columns="C",
+ aggfunc=func,
+ margins=True,
+ )
+ result = f(["mean", "std"])
+ means = f("mean")
+ stds = f("std")
+ expected = concat([means, stds], keys=["mean", "std"], axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("method", [True, False])
+ def test_pivot_index_with_nan(self, method):
+ # GH 3588
+ nan = np.nan
+ df = DataFrame(
+ {
+ "a": ["R1", "R2", nan, "R4"],
+ "b": ["C1", "C2", "C3", "C4"],
+ "c": [10, 15, 17, 20],
+ }
+ )
+ if method:
+ result = df.pivot(index="a", columns="b", values="c")
+ else:
+ result = pd.pivot(df, index="a", columns="b", values="c")
+ expected = DataFrame(
+ [
+ [nan, nan, 17, nan],
+ [10, nan, nan, nan],
+ [nan, 15, nan, nan],
+ [nan, nan, nan, 20],
+ ],
+ index=Index([nan, "R1", "R2", "R4"], name="a"),
+ columns=Index(["C1", "C2", "C3", "C4"], name="b"),
+ )
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(df.pivot(index="b", columns="a", values="c"), expected.T)
+
+ @pytest.mark.parametrize("method", [True, False])
+ def test_pivot_index_with_nan_dates(self, method):
+ # GH9491
+ df = DataFrame(
+ {
+ "a": date_range("2014-02-01", periods=6, freq="D"),
+ "c": 100 + np.arange(6),
+ }
+ )
+ df["b"] = df["a"] - pd.Timestamp("2014-02-02")
+ df.loc[1, "a"] = df.loc[3, "a"] = np.nan
+ df.loc[1, "b"] = df.loc[4, "b"] = np.nan
+
+ if method:
+ pv = df.pivot(index="a", columns="b", values="c")
+ else:
+ pv = pd.pivot(df, index="a", columns="b", values="c")
+ assert pv.notna().values.sum() == len(df)
+
+ for _, row in df.iterrows():
+ assert pv.loc[row["a"], row["b"]] == row["c"]
+
+ if method:
+ result = df.pivot(index="b", columns="a", values="c")
+ else:
+ result = pd.pivot(df, index="b", columns="a", values="c")
+ tm.assert_frame_equal(result, pv.T)
+
+ @pytest.mark.parametrize("method", [True, False])
+ def test_pivot_with_tz(self, method):
+ # GH 5878
+ df = DataFrame(
+ {
+ "dt1": [
+ datetime(2013, 1, 1, 9, 0),
+ datetime(2013, 1, 2, 9, 0),
+ datetime(2013, 1, 1, 9, 0),
+ datetime(2013, 1, 2, 9, 0),
+ ],
+ "dt2": [
+ datetime(2014, 1, 1, 9, 0),
+ datetime(2014, 1, 1, 9, 0),
+ datetime(2014, 1, 2, 9, 0),
+ datetime(2014, 1, 2, 9, 0),
+ ],
+ "data1": np.arange(4, dtype="int64"),
+ "data2": np.arange(4, dtype="int64"),
+ }
+ )
+
+ df["dt1"] = df["dt1"].apply(lambda d: pd.Timestamp(d, tz="US/Pacific"))
+ df["dt2"] = df["dt2"].apply(lambda d: pd.Timestamp(d, tz="Asia/Tokyo"))
+
+ exp_col1 = Index(["data1", "data1", "data2", "data2"])
+ exp_col2 = pd.DatetimeIndex(
+ ["2014/01/01 09:00", "2014/01/02 09:00"] * 2, name="dt2", tz="Asia/Tokyo"
+ )
+ exp_col = MultiIndex.from_arrays([exp_col1, exp_col2])
+ expected = DataFrame(
+ [[0, 2, 0, 2], [1, 3, 1, 3]],
+ index=pd.DatetimeIndex(
+ ["2013/01/01 09:00", "2013/01/02 09:00"], name="dt1", tz="US/Pacific"
+ ),
+ columns=exp_col,
+ )
+
+ if method:
+ pv = df.pivot(index="dt1", columns="dt2")
+ else:
+ pv = pd.pivot(df, index="dt1", columns="dt2")
+ tm.assert_frame_equal(pv, expected)
+
+ expected = DataFrame(
+ [[0, 2], [1, 3]],
+ index=pd.DatetimeIndex(
+ ["2013/01/01 09:00", "2013/01/02 09:00"], name="dt1", tz="US/Pacific"
+ ),
+ columns=pd.DatetimeIndex(
+ ["2014/01/01 09:00", "2014/01/02 09:00"], name="dt2", tz="Asia/Tokyo"
+ ),
+ )
+
+ if method:
+ pv = df.pivot(index="dt1", columns="dt2", values="data1")
+ else:
+ pv = pd.pivot(df, index="dt1", columns="dt2", values="data1")
+ tm.assert_frame_equal(pv, expected)
+
+ def test_pivot_tz_in_values(self):
+ # GH 14948
+ df = DataFrame(
+ [
+ {
+ "uid": "aa",
+ "ts": pd.Timestamp("2016-08-12 13:00:00-0700", tz="US/Pacific"),
+ },
+ {
+ "uid": "aa",
+ "ts": pd.Timestamp("2016-08-12 08:00:00-0700", tz="US/Pacific"),
+ },
+ {
+ "uid": "aa",
+ "ts": pd.Timestamp("2016-08-12 14:00:00-0700", tz="US/Pacific"),
+ },
+ {
+ "uid": "aa",
+ "ts": pd.Timestamp("2016-08-25 11:00:00-0700", tz="US/Pacific"),
+ },
+ {
+ "uid": "aa",
+ "ts": pd.Timestamp("2016-08-25 13:00:00-0700", tz="US/Pacific"),
+ },
+ ]
+ )
+
+ df = df.set_index("ts").reset_index()
+ mins = df.ts.map(lambda x: x.replace(hour=0, minute=0, second=0, microsecond=0))
+
+ result = pivot_table(
+ df.set_index("ts").reset_index(),
+ values="ts",
+ index=["uid"],
+ columns=[mins],
+ aggfunc="min",
+ )
+ expected = DataFrame(
+ [
+ [
+ pd.Timestamp("2016-08-12 08:00:00-0700", tz="US/Pacific"),
+ pd.Timestamp("2016-08-25 11:00:00-0700", tz="US/Pacific"),
+ ]
+ ],
+ index=Index(["aa"], name="uid"),
+ columns=pd.DatetimeIndex(
+ [
+ pd.Timestamp("2016-08-12 00:00:00", tz="US/Pacific"),
+ pd.Timestamp("2016-08-25 00:00:00", tz="US/Pacific"),
+ ],
+ name="ts",
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("method", [True, False])
+ def test_pivot_periods(self, method):
+ df = DataFrame(
+ {
+ "p1": [
+ pd.Period("2013-01-01", "D"),
+ pd.Period("2013-01-02", "D"),
+ pd.Period("2013-01-01", "D"),
+ pd.Period("2013-01-02", "D"),
+ ],
+ "p2": [
+ pd.Period("2013-01", "M"),
+ pd.Period("2013-01", "M"),
+ pd.Period("2013-02", "M"),
+ pd.Period("2013-02", "M"),
+ ],
+ "data1": np.arange(4, dtype="int64"),
+ "data2": np.arange(4, dtype="int64"),
+ }
+ )
+
+ exp_col1 = Index(["data1", "data1", "data2", "data2"])
+ exp_col2 = pd.PeriodIndex(["2013-01", "2013-02"] * 2, name="p2", freq="M")
+ exp_col = MultiIndex.from_arrays([exp_col1, exp_col2])
+ expected = DataFrame(
+ [[0, 2, 0, 2], [1, 3, 1, 3]],
+ index=pd.PeriodIndex(["2013-01-01", "2013-01-02"], name="p1", freq="D"),
+ columns=exp_col,
+ )
+ if method:
+ pv = df.pivot(index="p1", columns="p2")
+ else:
+ pv = pd.pivot(df, index="p1", columns="p2")
+ tm.assert_frame_equal(pv, expected)
+
+ expected = DataFrame(
+ [[0, 2], [1, 3]],
+ index=pd.PeriodIndex(["2013-01-01", "2013-01-02"], name="p1", freq="D"),
+ columns=pd.PeriodIndex(["2013-01", "2013-02"], name="p2", freq="M"),
+ )
+ if method:
+ pv = df.pivot(index="p1", columns="p2", values="data1")
+ else:
+ pv = pd.pivot(df, index="p1", columns="p2", values="data1")
+ tm.assert_frame_equal(pv, expected)
+
+ def test_pivot_periods_with_margins(self):
+ # GH 28323
+ df = DataFrame(
+ {
+ "a": [1, 1, 2, 2],
+ "b": [
+ pd.Period("2019Q1"),
+ pd.Period("2019Q2"),
+ pd.Period("2019Q1"),
+ pd.Period("2019Q2"),
+ ],
+ "x": 1.0,
+ }
+ )
+
+ expected = DataFrame(
+ data=1.0,
+ index=Index([1, 2, "All"], name="a"),
+ columns=Index([pd.Period("2019Q1"), pd.Period("2019Q2"), "All"], name="b"),
+ )
+
+ result = df.pivot_table(index="a", columns="b", values="x", margins=True)
+ tm.assert_frame_equal(expected, result)
+
+ @pytest.mark.parametrize(
+ "values",
+ [
+ ["baz", "zoo"],
+ np.array(["baz", "zoo"]),
+ Series(["baz", "zoo"]),
+ Index(["baz", "zoo"]),
+ ],
+ )
+ @pytest.mark.parametrize("method", [True, False])
+ def test_pivot_with_list_like_values(self, values, method):
+ # issue #17160
+ df = DataFrame(
+ {
+ "foo": ["one", "one", "one", "two", "two", "two"],
+ "bar": ["A", "B", "C", "A", "B", "C"],
+ "baz": [1, 2, 3, 4, 5, 6],
+ "zoo": ["x", "y", "z", "q", "w", "t"],
+ }
+ )
+
+ if method:
+ result = df.pivot(index="foo", columns="bar", values=values)
+ else:
+ result = pd.pivot(df, index="foo", columns="bar", values=values)
+
+ data = [[1, 2, 3, "x", "y", "z"], [4, 5, 6, "q", "w", "t"]]
+ index = Index(data=["one", "two"], name="foo")
+ columns = MultiIndex(
+ levels=[["baz", "zoo"], ["A", "B", "C"]],
+ codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]],
+ names=[None, "bar"],
+ )
+ expected = DataFrame(data=data, index=index, columns=columns, dtype="object")
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "values",
+ [
+ ["bar", "baz"],
+ np.array(["bar", "baz"]),
+ Series(["bar", "baz"]),
+ Index(["bar", "baz"]),
+ ],
+ )
+ @pytest.mark.parametrize("method", [True, False])
+ def test_pivot_with_list_like_values_nans(self, values, method):
+ # issue #17160
+ df = DataFrame(
+ {
+ "foo": ["one", "one", "one", "two", "two", "two"],
+ "bar": ["A", "B", "C", "A", "B", "C"],
+ "baz": [1, 2, 3, 4, 5, 6],
+ "zoo": ["x", "y", "z", "q", "w", "t"],
+ }
+ )
+
+ if method:
+ result = df.pivot(index="zoo", columns="foo", values=values)
+ else:
+ result = pd.pivot(df, index="zoo", columns="foo", values=values)
+
+ data = [
+ [np.nan, "A", np.nan, 4],
+ [np.nan, "C", np.nan, 6],
+ [np.nan, "B", np.nan, 5],
+ ["A", np.nan, 1, np.nan],
+ ["B", np.nan, 2, np.nan],
+ ["C", np.nan, 3, np.nan],
+ ]
+ index = Index(data=["q", "t", "w", "x", "y", "z"], name="zoo")
+ columns = MultiIndex(
+ levels=[["bar", "baz"], ["one", "two"]],
+ codes=[[0, 0, 1, 1], [0, 1, 0, 1]],
+ names=[None, "foo"],
+ )
+ expected = DataFrame(data=data, index=index, columns=columns, dtype="object")
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_columns_none_raise_error(self):
+ # GH 30924
+ df = DataFrame({"col1": ["a", "b", "c"], "col2": [1, 2, 3], "col3": [1, 2, 3]})
+ msg = r"pivot\(\) missing 1 required keyword-only argument: 'columns'"
+ with pytest.raises(TypeError, match=msg):
+ df.pivot(index="col1", values="col3") # pylint: disable=missing-kwoa
+
+ @pytest.mark.xfail(
+ reason="MultiIndexed unstack with tuple names fails with KeyError GH#19966"
+ )
+ @pytest.mark.parametrize("method", [True, False])
+ def test_pivot_with_multiindex(self, method):
+ # issue #17160
+ index = Index(data=[0, 1, 2, 3, 4, 5])
+ data = [
+ ["one", "A", 1, "x"],
+ ["one", "B", 2, "y"],
+ ["one", "C", 3, "z"],
+ ["two", "A", 4, "q"],
+ ["two", "B", 5, "w"],
+ ["two", "C", 6, "t"],
+ ]
+ columns = MultiIndex(
+ levels=[["bar", "baz"], ["first", "second"]],
+ codes=[[0, 0, 1, 1], [0, 1, 0, 1]],
+ )
+ df = DataFrame(data=data, index=index, columns=columns, dtype="object")
+ if method:
+ result = df.pivot(
+ index=("bar", "first"),
+ columns=("bar", "second"),
+ values=("baz", "first"),
+ )
+ else:
+ result = pd.pivot(
+ df,
+ index=("bar", "first"),
+ columns=("bar", "second"),
+ values=("baz", "first"),
+ )
+
+ data = {
+ "A": Series([1, 4], index=["one", "two"]),
+ "B": Series([2, 5], index=["one", "two"]),
+ "C": Series([3, 6], index=["one", "two"]),
+ }
+ expected = DataFrame(data)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("method", [True, False])
+ def test_pivot_with_tuple_of_values(self, method):
+ # issue #17160
+ df = DataFrame(
+ {
+ "foo": ["one", "one", "one", "two", "two", "two"],
+ "bar": ["A", "B", "C", "A", "B", "C"],
+ "baz": [1, 2, 3, 4, 5, 6],
+ "zoo": ["x", "y", "z", "q", "w", "t"],
+ }
+ )
+ with pytest.raises(KeyError, match=r"^\('bar', 'baz'\)$"):
+ # tuple is seen as a single column name
+ if method:
+ df.pivot(index="zoo", columns="foo", values=("bar", "baz"))
+ else:
+ pd.pivot(df, index="zoo", columns="foo", values=("bar", "baz"))
+
+ def _check_output(
+ self,
+ result,
+ values_col,
+ data,
+ index=["A", "B"],
+ columns=["C"],
+ margins_col="All",
+ ):
+ col_margins = result.loc[result.index[:-1], margins_col]
+ expected_col_margins = data.groupby(index)[values_col].mean()
+ tm.assert_series_equal(col_margins, expected_col_margins, check_names=False)
+ assert col_margins.name == margins_col
+
+ result = result.sort_index()
+ index_margins = result.loc[(margins_col, "")].iloc[:-1]
+
+ expected_ix_margins = data.groupby(columns)[values_col].mean()
+ tm.assert_series_equal(index_margins, expected_ix_margins, check_names=False)
+ assert index_margins.name == (margins_col, "")
+
+ grand_total_margins = result.loc[(margins_col, ""), margins_col]
+ expected_total_margins = data[values_col].mean()
+ assert grand_total_margins == expected_total_margins
+
+ def test_margins(self, data):
+ # column specified
+ result = data.pivot_table(
+ values="D", index=["A", "B"], columns="C", margins=True, aggfunc="mean"
+ )
+ self._check_output(result, "D", data)
+
+ # Set a different margins_name (not 'All')
+ result = data.pivot_table(
+ values="D",
+ index=["A", "B"],
+ columns="C",
+ margins=True,
+ aggfunc="mean",
+ margins_name="Totals",
+ )
+ self._check_output(result, "D", data, margins_col="Totals")
+
+ # no column specified
+ table = data.pivot_table(
+ index=["A", "B"], columns="C", margins=True, aggfunc="mean"
+ )
+ for value_col in table.columns.levels[0]:
+ self._check_output(table[value_col], value_col, data)
+
+ def test_no_col(self, data):
+ # no col
+
+ # to help with a buglet
+ data.columns = [k * 2 for k in data.columns]
+ msg = re.escape("agg function failed [how->mean,dtype->object]")
+ with pytest.raises(TypeError, match=msg):
+ data.pivot_table(index=["AA", "BB"], margins=True, aggfunc="mean")
+ table = data.drop(columns="CC").pivot_table(
+ index=["AA", "BB"], margins=True, aggfunc="mean"
+ )
+ for value_col in table.columns:
+ totals = table.loc[("All", ""), value_col]
+ assert totals == data[value_col].mean()
+
+ with pytest.raises(TypeError, match=msg):
+ data.pivot_table(index=["AA", "BB"], margins=True, aggfunc="mean")
+ table = data.drop(columns="CC").pivot_table(
+ index=["AA", "BB"], margins=True, aggfunc="mean"
+ )
+ for item in ["DD", "EE", "FF"]:
+ totals = table.loc[("All", ""), item]
+ assert totals == data[item].mean()
+
+ @pytest.mark.parametrize(
+ "columns, aggfunc, values, expected_columns",
+ [
+ (
+ "A",
+ "mean",
+ [[5.5, 5.5, 2.2, 2.2], [8.0, 8.0, 4.4, 4.4]],
+ Index(["bar", "All", "foo", "All"], name="A"),
+ ),
+ (
+ ["A", "B"],
+ "sum",
+ [
+ [9, 13, 22, 5, 6, 11],
+ [14, 18, 32, 11, 11, 22],
+ ],
+ MultiIndex.from_tuples(
+ [
+ ("bar", "one"),
+ ("bar", "two"),
+ ("bar", "All"),
+ ("foo", "one"),
+ ("foo", "two"),
+ ("foo", "All"),
+ ],
+ names=["A", "B"],
+ ),
+ ),
+ ],
+ )
+ def test_margin_with_only_columns_defined(
+ self, columns, aggfunc, values, expected_columns
+ ):
+ # GH 31016
+ df = DataFrame(
+ {
+ "A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
+ "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"],
+ "C": [
+ "small",
+ "large",
+ "large",
+ "small",
+ "small",
+ "large",
+ "small",
+ "small",
+ "large",
+ ],
+ "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
+ "E": [2, 4, 5, 5, 6, 6, 8, 9, 9],
+ }
+ )
+ if aggfunc != "sum":
+ msg = re.escape("agg function failed [how->mean,dtype->object]")
+ with pytest.raises(TypeError, match=msg):
+ df.pivot_table(columns=columns, margins=True, aggfunc=aggfunc)
+ if "B" not in columns:
+ df = df.drop(columns="B")
+ result = df.drop(columns="C").pivot_table(
+ columns=columns, margins=True, aggfunc=aggfunc
+ )
+ expected = DataFrame(values, index=Index(["D", "E"]), columns=expected_columns)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_margins_dtype(self, data):
+ # GH 17013
+
+ df = data.copy()
+ df[["D", "E", "F"]] = np.arange(len(df) * 3).reshape(len(df), 3).astype("i8")
+
+ mi_val = list(product(["bar", "foo"], ["one", "two"])) + [("All", "")]
+ mi = MultiIndex.from_tuples(mi_val, names=("A", "B"))
+ expected = DataFrame(
+ {"dull": [12, 21, 3, 9, 45], "shiny": [33, 0, 36, 51, 120]}, index=mi
+ ).rename_axis("C", axis=1)
+ expected["All"] = expected["dull"] + expected["shiny"]
+
+ result = df.pivot_table(
+ values="D",
+ index=["A", "B"],
+ columns="C",
+ margins=True,
+ aggfunc="sum",
+ fill_value=0,
+ )
+
+ tm.assert_frame_equal(expected, result)
+
+ def test_margins_dtype_len(self, data):
+ mi_val = list(product(["bar", "foo"], ["one", "two"])) + [("All", "")]
+ mi = MultiIndex.from_tuples(mi_val, names=("A", "B"))
+ expected = DataFrame(
+ {"dull": [1, 1, 2, 1, 5], "shiny": [2, 0, 2, 2, 6]}, index=mi
+ ).rename_axis("C", axis=1)
+ expected["All"] = expected["dull"] + expected["shiny"]
+
+ result = data.pivot_table(
+ values="D",
+ index=["A", "B"],
+ columns="C",
+ margins=True,
+ aggfunc=len,
+ fill_value=0,
+ )
+
+ tm.assert_frame_equal(expected, result)
+
+ @pytest.mark.parametrize("cols", [(1, 2), ("a", "b"), (1, "b"), ("a", 1)])
+ def test_pivot_table_multiindex_only(self, cols):
+ # GH 17038
+ df2 = DataFrame({cols[0]: [1, 2, 3], cols[1]: [1, 2, 3], "v": [4, 5, 6]})
+
+ result = df2.pivot_table(values="v", columns=cols)
+ expected = DataFrame(
+ [[4.0, 5.0, 6.0]],
+ columns=MultiIndex.from_tuples([(1, 1), (2, 2), (3, 3)], names=cols),
+ index=Index(["v"]),
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_retains_tz(self):
+ dti = date_range("2016-01-01", periods=3, tz="Europe/Amsterdam")
+ df = DataFrame(
+ {
+ "A": np.random.default_rng(2).standard_normal(3),
+ "B": np.random.default_rng(2).standard_normal(3),
+ "C": dti,
+ }
+ )
+ result = df.pivot_table(index=["B", "C"], dropna=False)
+
+ # check tz retention
+ assert result.index.levels[1].equals(dti)
+
+ def test_pivot_integer_columns(self):
+ # caused by upstream bug in unstack
+
+ d = date.min
+ data = list(
+ product(
+ ["foo", "bar"],
+ ["A", "B", "C"],
+ ["x1", "x2"],
+ [d + timedelta(i) for i in range(20)],
+ [1.0],
+ )
+ )
+ df = DataFrame(data)
+ table = df.pivot_table(values=4, index=[0, 1, 3], columns=[2])
+
+ df2 = df.rename(columns=str)
+ table2 = df2.pivot_table(values="4", index=["0", "1", "3"], columns=["2"])
+
+ tm.assert_frame_equal(table, table2, check_names=False)
+
+ def test_pivot_no_level_overlap(self):
+ # GH #1181
+
+ data = DataFrame(
+ {
+ "a": ["a", "a", "a", "a", "b", "b", "b", "b"] * 2,
+ "b": [0, 0, 0, 0, 1, 1, 1, 1] * 2,
+ "c": (["foo"] * 4 + ["bar"] * 4) * 2,
+ "value": np.random.default_rng(2).standard_normal(16),
+ }
+ )
+
+ table = data.pivot_table("value", index="a", columns=["b", "c"])
+
+ grouped = data.groupby(["a", "b", "c"])["value"].mean()
+ expected = grouped.unstack("b").unstack("c").dropna(axis=1, how="all")
+ tm.assert_frame_equal(table, expected)
+
+ def test_pivot_columns_lexsorted(self):
+ n = 10000
+
+ dtype = np.dtype(
+ [
+ ("Index", object),
+ ("Symbol", object),
+ ("Year", int),
+ ("Month", int),
+ ("Day", int),
+ ("Quantity", int),
+ ("Price", float),
+ ]
+ )
+
+ products = np.array(
+ [
+ ("SP500", "ADBE"),
+ ("SP500", "NVDA"),
+ ("SP500", "ORCL"),
+ ("NDQ100", "AAPL"),
+ ("NDQ100", "MSFT"),
+ ("NDQ100", "GOOG"),
+ ("FTSE", "DGE.L"),
+ ("FTSE", "TSCO.L"),
+ ("FTSE", "GSK.L"),
+ ],
+ dtype=[("Index", object), ("Symbol", object)],
+ )
+ items = np.empty(n, dtype=dtype)
+ iproduct = np.random.default_rng(2).integers(0, len(products), n)
+ items["Index"] = products["Index"][iproduct]
+ items["Symbol"] = products["Symbol"][iproduct]
+ dr = date_range(date(2000, 1, 1), date(2010, 12, 31))
+ dates = dr[np.random.default_rng(2).integers(0, len(dr), n)]
+ items["Year"] = dates.year
+ items["Month"] = dates.month
+ items["Day"] = dates.day
+ items["Price"] = np.random.default_rng(2).lognormal(4.0, 2.0, n)
+
+ df = DataFrame(items)
+
+ pivoted = df.pivot_table(
+ "Price",
+ index=["Month", "Day"],
+ columns=["Index", "Symbol", "Year"],
+ aggfunc="mean",
+ )
+
+ assert pivoted.columns.is_monotonic_increasing
+
+ def test_pivot_complex_aggfunc(self, data):
+ f = {"D": ["std"], "E": ["sum"]}
+ expected = data.groupby(["A", "B"]).agg(f).unstack("B")
+ result = data.pivot_table(index="A", columns="B", aggfunc=f)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_margins_no_values_no_cols(self, data):
+ # Regression test on pivot table: no values or cols passed.
+ result = data[["A", "B"]].pivot_table(
+ index=["A", "B"], aggfunc=len, margins=True
+ )
+ result_list = result.tolist()
+ assert sum(result_list[:-1]) == result_list[-1]
+
+ def test_margins_no_values_two_rows(self, data):
+ # Regression test on pivot table: no values passed but rows are a
+ # multi-index
+ result = data[["A", "B", "C"]].pivot_table(
+ index=["A", "B"], columns="C", aggfunc=len, margins=True
+ )
+ assert result.All.tolist() == [3.0, 1.0, 4.0, 3.0, 11.0]
+
+ def test_margins_no_values_one_row_one_col(self, data):
+ # Regression test on pivot table: no values passed but row and col
+ # defined
+ result = data[["A", "B"]].pivot_table(
+ index="A", columns="B", aggfunc=len, margins=True
+ )
+ assert result.All.tolist() == [4.0, 7.0, 11.0]
+
+ def test_margins_no_values_two_row_two_cols(self, data):
+ # Regression test on pivot table: no values passed but rows and cols
+ # are multi-indexed
+ data["D"] = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
+ result = data[["A", "B", "C", "D"]].pivot_table(
+ index=["A", "B"], columns=["C", "D"], aggfunc=len, margins=True
+ )
+ assert result.All.tolist() == [3.0, 1.0, 4.0, 3.0, 11.0]
+
+ @pytest.mark.parametrize("margin_name", ["foo", "one", 666, None, ["a", "b"]])
+ def test_pivot_table_with_margins_set_margin_name(self, margin_name, data):
+ # see gh-3335
+ msg = (
+ f'Conflicting name "{margin_name}" in margins|'
+ "margins_name argument must be a string"
+ )
+ with pytest.raises(ValueError, match=msg):
+ # multi-index index
+ pivot_table(
+ data,
+ values="D",
+ index=["A", "B"],
+ columns=["C"],
+ margins=True,
+ margins_name=margin_name,
+ )
+ with pytest.raises(ValueError, match=msg):
+ # multi-index column
+ pivot_table(
+ data,
+ values="D",
+ index=["C"],
+ columns=["A", "B"],
+ margins=True,
+ margins_name=margin_name,
+ )
+ with pytest.raises(ValueError, match=msg):
+ # non-multi-index index/column
+ pivot_table(
+ data,
+ values="D",
+ index=["A"],
+ columns=["B"],
+ margins=True,
+ margins_name=margin_name,
+ )
+
+ def test_pivot_timegrouper(self, using_array_manager):
+ df = DataFrame(
+ {
+ "Branch": "A A A A A A A B".split(),
+ "Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(),
+ "Quantity": [1, 3, 5, 1, 8, 1, 9, 3],
+ "Date": [
+ datetime(2013, 1, 1),
+ datetime(2013, 1, 1),
+ datetime(2013, 10, 1),
+ datetime(2013, 10, 2),
+ datetime(2013, 10, 1),
+ datetime(2013, 10, 2),
+ datetime(2013, 12, 2),
+ datetime(2013, 12, 2),
+ ],
+ }
+ ).set_index("Date")
+
+ expected = DataFrame(
+ np.array([10, 18, 3], dtype="int64").reshape(1, 3),
+ index=pd.DatetimeIndex([datetime(2013, 12, 31)], freq="A"),
+ columns="Carl Joe Mark".split(),
+ )
+ expected.index.name = "Date"
+ expected.columns.name = "Buyer"
+
+ result = pivot_table(
+ df,
+ index=Grouper(freq="A"),
+ columns="Buyer",
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(
+ df,
+ index="Buyer",
+ columns=Grouper(freq="A"),
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected.T)
+
+ expected = DataFrame(
+ np.array([1, np.nan, 3, 9, 18, np.nan]).reshape(2, 3),
+ index=pd.DatetimeIndex(
+ [datetime(2013, 1, 1), datetime(2013, 7, 1)], freq="6MS"
+ ),
+ columns="Carl Joe Mark".split(),
+ )
+ expected.index.name = "Date"
+ expected.columns.name = "Buyer"
+ if using_array_manager:
+ # INFO(ArrayManager) column without NaNs can preserve int dtype
+ expected["Carl"] = expected["Carl"].astype("int64")
+
+ result = pivot_table(
+ df,
+ index=Grouper(freq="6MS"),
+ columns="Buyer",
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(
+ df,
+ index="Buyer",
+ columns=Grouper(freq="6MS"),
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected.T)
+
+ # passing the name
+ df = df.reset_index()
+ result = pivot_table(
+ df,
+ index=Grouper(freq="6MS", key="Date"),
+ columns="Buyer",
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(
+ df,
+ index="Buyer",
+ columns=Grouper(freq="6MS", key="Date"),
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected.T)
+
+ msg = "'The grouper name foo is not found'"
+ with pytest.raises(KeyError, match=msg):
+ pivot_table(
+ df,
+ index=Grouper(freq="6MS", key="foo"),
+ columns="Buyer",
+ values="Quantity",
+ aggfunc="sum",
+ )
+ with pytest.raises(KeyError, match=msg):
+ pivot_table(
+ df,
+ index="Buyer",
+ columns=Grouper(freq="6MS", key="foo"),
+ values="Quantity",
+ aggfunc="sum",
+ )
+
+ # passing the level
+ df = df.set_index("Date")
+ result = pivot_table(
+ df,
+ index=Grouper(freq="6MS", level="Date"),
+ columns="Buyer",
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(
+ df,
+ index="Buyer",
+ columns=Grouper(freq="6MS", level="Date"),
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected.T)
+
+ msg = "The level foo is not valid"
+ with pytest.raises(ValueError, match=msg):
+ pivot_table(
+ df,
+ index=Grouper(freq="6MS", level="foo"),
+ columns="Buyer",
+ values="Quantity",
+ aggfunc="sum",
+ )
+ with pytest.raises(ValueError, match=msg):
+ pivot_table(
+ df,
+ index="Buyer",
+ columns=Grouper(freq="6MS", level="foo"),
+ values="Quantity",
+ aggfunc="sum",
+ )
+
+ def test_pivot_timegrouper_double(self):
+ # double grouper
+ df = DataFrame(
+ {
+ "Branch": "A A A A A A A B".split(),
+ "Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(),
+ "Quantity": [1, 3, 5, 1, 8, 1, 9, 3],
+ "Date": [
+ datetime(2013, 11, 1, 13, 0),
+ datetime(2013, 9, 1, 13, 5),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 2, 10, 0),
+ datetime(2013, 11, 1, 20, 0),
+ datetime(2013, 10, 2, 10, 0),
+ datetime(2013, 10, 2, 12, 0),
+ datetime(2013, 12, 5, 14, 0),
+ ],
+ "PayDay": [
+ datetime(2013, 10, 4, 0, 0),
+ datetime(2013, 10, 15, 13, 5),
+ datetime(2013, 9, 5, 20, 0),
+ datetime(2013, 11, 2, 10, 0),
+ datetime(2013, 10, 7, 20, 0),
+ datetime(2013, 9, 5, 10, 0),
+ datetime(2013, 12, 30, 12, 0),
+ datetime(2013, 11, 20, 14, 0),
+ ],
+ }
+ )
+
+ result = pivot_table(
+ df,
+ index=Grouper(freq="M", key="Date"),
+ columns=Grouper(freq="M", key="PayDay"),
+ values="Quantity",
+ aggfunc="sum",
+ )
+ expected = DataFrame(
+ np.array(
+ [
+ np.nan,
+ 3,
+ np.nan,
+ np.nan,
+ 6,
+ np.nan,
+ 1,
+ 9,
+ np.nan,
+ 9,
+ np.nan,
+ np.nan,
+ np.nan,
+ np.nan,
+ 3,
+ np.nan,
+ ]
+ ).reshape(4, 4),
+ index=pd.DatetimeIndex(
+ [
+ datetime(2013, 9, 30),
+ datetime(2013, 10, 31),
+ datetime(2013, 11, 30),
+ datetime(2013, 12, 31),
+ ],
+ freq="M",
+ ),
+ columns=pd.DatetimeIndex(
+ [
+ datetime(2013, 9, 30),
+ datetime(2013, 10, 31),
+ datetime(2013, 11, 30),
+ datetime(2013, 12, 31),
+ ],
+ freq="M",
+ ),
+ )
+ expected.index.name = "Date"
+ expected.columns.name = "PayDay"
+
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(
+ df,
+ index=Grouper(freq="M", key="PayDay"),
+ columns=Grouper(freq="M", key="Date"),
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected.T)
+
+ tuples = [
+ (datetime(2013, 9, 30), datetime(2013, 10, 31)),
+ (datetime(2013, 10, 31), datetime(2013, 9, 30)),
+ (datetime(2013, 10, 31), datetime(2013, 11, 30)),
+ (datetime(2013, 10, 31), datetime(2013, 12, 31)),
+ (datetime(2013, 11, 30), datetime(2013, 10, 31)),
+ (datetime(2013, 12, 31), datetime(2013, 11, 30)),
+ ]
+ idx = MultiIndex.from_tuples(tuples, names=["Date", "PayDay"])
+ expected = DataFrame(
+ np.array(
+ [3, np.nan, 6, np.nan, 1, np.nan, 9, np.nan, 9, np.nan, np.nan, 3]
+ ).reshape(6, 2),
+ index=idx,
+ columns=["A", "B"],
+ )
+ expected.columns.name = "Branch"
+
+ result = pivot_table(
+ df,
+ index=[Grouper(freq="M", key="Date"), Grouper(freq="M", key="PayDay")],
+ columns=["Branch"],
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(
+ df,
+ index=["Branch"],
+ columns=[Grouper(freq="M", key="Date"), Grouper(freq="M", key="PayDay")],
+ values="Quantity",
+ aggfunc="sum",
+ )
+ tm.assert_frame_equal(result, expected.T)
+
+ def test_pivot_datetime_tz(self):
+ dates1 = [
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ ]
+ dates2 = [
+ "2013-01-01 15:00:00",
+ "2013-01-01 15:00:00",
+ "2013-01-01 15:00:00",
+ "2013-02-01 15:00:00",
+ "2013-02-01 15:00:00",
+ "2013-02-01 15:00:00",
+ ]
+ df = DataFrame(
+ {
+ "label": ["a", "a", "a", "b", "b", "b"],
+ "dt1": dates1,
+ "dt2": dates2,
+ "value1": np.arange(6, dtype="int64"),
+ "value2": [1, 2] * 3,
+ }
+ )
+ df["dt1"] = df["dt1"].apply(lambda d: pd.Timestamp(d, tz="US/Pacific"))
+ df["dt2"] = df["dt2"].apply(lambda d: pd.Timestamp(d, tz="Asia/Tokyo"))
+
+ exp_idx = pd.DatetimeIndex(
+ ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"],
+ tz="US/Pacific",
+ name="dt1",
+ )
+ exp_col1 = Index(["value1", "value1"])
+ exp_col2 = Index(["a", "b"], name="label")
+ exp_col = MultiIndex.from_arrays([exp_col1, exp_col2])
+ expected = DataFrame(
+ [[0.0, 3.0], [1.0, 4.0], [2.0, 5.0]], index=exp_idx, columns=exp_col
+ )
+ result = pivot_table(df, index=["dt1"], columns=["label"], values=["value1"])
+ tm.assert_frame_equal(result, expected)
+
+ exp_col1 = Index(["sum", "sum", "sum", "sum", "mean", "mean", "mean", "mean"])
+ exp_col2 = Index(["value1", "value1", "value2", "value2"] * 2)
+ exp_col3 = pd.DatetimeIndex(
+ ["2013-01-01 15:00:00", "2013-02-01 15:00:00"] * 4,
+ tz="Asia/Tokyo",
+ name="dt2",
+ )
+ exp_col = MultiIndex.from_arrays([exp_col1, exp_col2, exp_col3])
+ expected1 = DataFrame(
+ np.array(
+ [
+ [
+ 0,
+ 3,
+ 1,
+ 2,
+ ],
+ [1, 4, 2, 1],
+ [2, 5, 1, 2],
+ ],
+ dtype="int64",
+ ),
+ index=exp_idx,
+ columns=exp_col[:4],
+ )
+ expected2 = DataFrame(
+ np.array(
+ [
+ [0.0, 3.0, 1.0, 2.0],
+ [1.0, 4.0, 2.0, 1.0],
+ [2.0, 5.0, 1.0, 2.0],
+ ],
+ ),
+ index=exp_idx,
+ columns=exp_col[4:],
+ )
+ expected = concat([expected1, expected2], axis=1)
+
+ result = pivot_table(
+ df,
+ index=["dt1"],
+ columns=["dt2"],
+ values=["value1", "value2"],
+ aggfunc=["sum", "mean"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_dtaccessor(self):
+ # GH 8103
+ dates1 = [
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ "2011-07-19 07:00:00",
+ "2011-07-19 08:00:00",
+ "2011-07-19 09:00:00",
+ ]
+ dates2 = [
+ "2013-01-01 15:00:00",
+ "2013-01-01 15:00:00",
+ "2013-01-01 15:00:00",
+ "2013-02-01 15:00:00",
+ "2013-02-01 15:00:00",
+ "2013-02-01 15:00:00",
+ ]
+ df = DataFrame(
+ {
+ "label": ["a", "a", "a", "b", "b", "b"],
+ "dt1": dates1,
+ "dt2": dates2,
+ "value1": np.arange(6, dtype="int64"),
+ "value2": [1, 2] * 3,
+ }
+ )
+ df["dt1"] = df["dt1"].apply(lambda d: pd.Timestamp(d))
+ df["dt2"] = df["dt2"].apply(lambda d: pd.Timestamp(d))
+
+ result = pivot_table(
+ df, index="label", columns=df["dt1"].dt.hour, values="value1"
+ )
+
+ exp_idx = Index(["a", "b"], name="label")
+ expected = DataFrame(
+ {7: [0.0, 3.0], 8: [1.0, 4.0], 9: [2.0, 5.0]},
+ index=exp_idx,
+ columns=Index([7, 8, 9], dtype=np.int32, name="dt1"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(
+ df, index=df["dt2"].dt.month, columns=df["dt1"].dt.hour, values="value1"
+ )
+
+ expected = DataFrame(
+ {7: [0.0, 3.0], 8: [1.0, 4.0], 9: [2.0, 5.0]},
+ index=Index([1, 2], dtype=np.int32, name="dt2"),
+ columns=Index([7, 8, 9], dtype=np.int32, name="dt1"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(
+ df,
+ index=df["dt2"].dt.year.values,
+ columns=[df["dt1"].dt.hour, df["dt2"].dt.month],
+ values="value1",
+ )
+
+ exp_col = MultiIndex.from_arrays(
+ [
+ np.array([7, 7, 8, 8, 9, 9], dtype=np.int32),
+ np.array([1, 2] * 3, dtype=np.int32),
+ ],
+ names=["dt1", "dt2"],
+ )
+ expected = DataFrame(
+ np.array([[0.0, 3.0, 1.0, 4.0, 2.0, 5.0]]),
+ index=Index([2013], dtype=np.int32),
+ columns=exp_col,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(
+ df,
+ index=np.array(["X", "X", "X", "X", "Y", "Y"]),
+ columns=[df["dt1"].dt.hour, df["dt2"].dt.month],
+ values="value1",
+ )
+ expected = DataFrame(
+ np.array(
+ [[0, 3, 1, np.nan, 2, np.nan], [np.nan, np.nan, np.nan, 4, np.nan, 5]]
+ ),
+ index=["X", "Y"],
+ columns=exp_col,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("i", range(1, 367))
+ def test_daily(self, i):
+ rng = date_range("1/1/2000", "12/31/2004", freq="D")
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ annual = pivot_table(
+ DataFrame(ts), index=ts.index.year, columns=ts.index.dayofyear
+ )
+ annual.columns = annual.columns.droplevel(0)
+
+ doy = np.asarray(ts.index.dayofyear)
+
+ subset = ts[doy == i]
+ subset.index = subset.index.year
+
+ result = annual[i].dropna()
+ tm.assert_series_equal(result, subset, check_names=False)
+ assert result.name == i
+
+ @pytest.mark.parametrize("i", range(1, 13))
+ def test_monthly(self, i):
+ rng = date_range("1/1/2000", "12/31/2004", freq="M")
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ annual = pivot_table(DataFrame(ts), index=ts.index.year, columns=ts.index.month)
+ annual.columns = annual.columns.droplevel(0)
+
+ month = ts.index.month
+ subset = ts[month == i]
+ subset.index = subset.index.year
+ result = annual[i].dropna()
+ tm.assert_series_equal(result, subset, check_names=False)
+ assert result.name == i
+
+ def test_pivot_table_with_iterator_values(self, data):
+ # GH 12017
+ aggs = {"D": "sum", "E": "mean"}
+
+ pivot_values_list = pivot_table(
+ data, index=["A"], values=list(aggs.keys()), aggfunc=aggs
+ )
+
+ pivot_values_keys = pivot_table(
+ data, index=["A"], values=aggs.keys(), aggfunc=aggs
+ )
+ tm.assert_frame_equal(pivot_values_keys, pivot_values_list)
+
+ agg_values_gen = (value for value in aggs)
+ pivot_values_gen = pivot_table(
+ data, index=["A"], values=agg_values_gen, aggfunc=aggs
+ )
+ tm.assert_frame_equal(pivot_values_gen, pivot_values_list)
+
+ def test_pivot_table_margins_name_with_aggfunc_list(self):
+ # GH 13354
+ margins_name = "Weekly"
+ costs = DataFrame(
+ {
+ "item": ["bacon", "cheese", "bacon", "cheese"],
+ "cost": [2.5, 4.5, 3.2, 3.3],
+ "day": ["M", "M", "T", "T"],
+ }
+ )
+ table = costs.pivot_table(
+ index="item",
+ columns="day",
+ margins=True,
+ margins_name=margins_name,
+ aggfunc=["mean", "max"],
+ )
+ ix = Index(["bacon", "cheese", margins_name], dtype="object", name="item")
+ tups = [
+ ("mean", "cost", "M"),
+ ("mean", "cost", "T"),
+ ("mean", "cost", margins_name),
+ ("max", "cost", "M"),
+ ("max", "cost", "T"),
+ ("max", "cost", margins_name),
+ ]
+ cols = MultiIndex.from_tuples(tups, names=[None, None, "day"])
+ expected = DataFrame(table.values, index=ix, columns=cols)
+ tm.assert_frame_equal(table, expected)
+
+ def test_categorical_margins(self, observed):
+ # GH 10989
+ df = DataFrame(
+ {"x": np.arange(8), "y": np.arange(8) // 4, "z": np.arange(8) % 2}
+ )
+
+ expected = DataFrame([[1.0, 2.0, 1.5], [5, 6, 5.5], [3, 4, 3.5]])
+ expected.index = Index([0, 1, "All"], name="y")
+ expected.columns = Index([0, 1, "All"], name="z")
+
+ table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
+ tm.assert_frame_equal(table, expected)
+
+ def test_categorical_margins_category(self, observed):
+ df = DataFrame(
+ {"x": np.arange(8), "y": np.arange(8) // 4, "z": np.arange(8) % 2}
+ )
+
+ expected = DataFrame([[1.0, 2.0, 1.5], [5, 6, 5.5], [3, 4, 3.5]])
+ expected.index = Index([0, 1, "All"], name="y")
+ expected.columns = Index([0, 1, "All"], name="z")
+
+ df.y = df.y.astype("category")
+ df.z = df.z.astype("category")
+ table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
+ tm.assert_frame_equal(table, expected)
+
+ def test_margins_casted_to_float(self):
+ # GH 24893
+ df = DataFrame(
+ {
+ "A": [2, 4, 6, 8],
+ "B": [1, 4, 5, 8],
+ "C": [1, 3, 4, 6],
+ "D": ["X", "X", "Y", "Y"],
+ }
+ )
+
+ result = pivot_table(df, index="D", margins=True)
+ expected = DataFrame(
+ {"A": [3.0, 7.0, 5], "B": [2.5, 6.5, 4.5], "C": [2.0, 5.0, 3.5]},
+ index=Index(["X", "Y", "All"], name="D"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_with_categorical(self, observed, ordered):
+ # gh-21370
+ idx = [np.nan, "low", "high", "low", np.nan]
+ col = [np.nan, "A", "B", np.nan, "A"]
+ df = DataFrame(
+ {
+ "In": Categorical(idx, categories=["low", "high"], ordered=ordered),
+ "Col": Categorical(col, categories=["A", "B"], ordered=ordered),
+ "Val": range(1, 6),
+ }
+ )
+ # case with index/columns/value
+ result = df.pivot_table(
+ index="In", columns="Col", values="Val", observed=observed
+ )
+
+ expected_cols = pd.CategoricalIndex(["A", "B"], ordered=ordered, name="Col")
+
+ expected = DataFrame(data=[[2.0, np.nan], [np.nan, 3.0]], columns=expected_cols)
+ expected.index = Index(
+ Categorical(["low", "high"], categories=["low", "high"], ordered=ordered),
+ name="In",
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ # case with columns/value
+ result = df.pivot_table(columns="Col", values="Val", observed=observed)
+
+ expected = DataFrame(
+ data=[[3.5, 3.0]], columns=expected_cols, index=Index(["Val"])
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_categorical_aggfunc(self, observed):
+ # GH 9534
+ df = DataFrame(
+ {"C1": ["A", "B", "C", "C"], "C2": ["a", "a", "b", "b"], "V": [1, 2, 3, 4]}
+ )
+ df["C1"] = df["C1"].astype("category")
+ result = df.pivot_table(
+ "V", index="C1", columns="C2", dropna=observed, aggfunc="count"
+ )
+
+ expected_index = pd.CategoricalIndex(
+ ["A", "B", "C"], categories=["A", "B", "C"], ordered=False, name="C1"
+ )
+ expected_columns = Index(["a", "b"], name="C2")
+ expected_data = np.array([[1, 0], [1, 0], [0, 2]], dtype=np.int64)
+ expected = DataFrame(
+ expected_data, index=expected_index, columns=expected_columns
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_categorical_pivot_index_ordering(self, observed):
+ # GH 8731
+ df = DataFrame(
+ {
+ "Sales": [100, 120, 220],
+ "Month": ["January", "January", "January"],
+ "Year": [2013, 2014, 2013],
+ }
+ )
+ months = [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December",
+ ]
+ df["Month"] = df["Month"].astype("category").cat.set_categories(months)
+ result = df.pivot_table(
+ values="Sales",
+ index="Month",
+ columns="Year",
+ observed=observed,
+ aggfunc="sum",
+ )
+ expected_columns = Index([2013, 2014], name="Year", dtype="int64")
+ expected_index = pd.CategoricalIndex(
+ months, categories=months, ordered=False, name="Month"
+ )
+ expected_data = [[320, 120]] + [[0, 0]] * 11
+ expected = DataFrame(
+ expected_data, index=expected_index, columns=expected_columns
+ )
+ if observed:
+ expected = expected.loc[["January"]]
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_not_series(self):
+ # GH 4386
+ # pivot_table always returns a DataFrame
+ # when values is not list like and columns is None
+ # and aggfunc is not instance of list
+ df = DataFrame({"col1": [3, 4, 5], "col2": ["C", "D", "E"], "col3": [1, 3, 9]})
+
+ result = df.pivot_table("col1", index=["col3", "col2"], aggfunc="sum")
+ m = MultiIndex.from_arrays([[1, 3, 9], ["C", "D", "E"]], names=["col3", "col2"])
+ expected = DataFrame([3, 4, 5], index=m, columns=["col1"])
+
+ tm.assert_frame_equal(result, expected)
+
+ result = df.pivot_table("col1", index="col3", columns="col2", aggfunc="sum")
+ expected = DataFrame(
+ [[3, np.nan, np.nan], [np.nan, 4, np.nan], [np.nan, np.nan, 5]],
+ index=Index([1, 3, 9], name="col3"),
+ columns=Index(["C", "D", "E"], name="col2"),
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ result = df.pivot_table("col1", index="col3", aggfunc=["sum"])
+ m = MultiIndex.from_arrays([["sum"], ["col1"]])
+ expected = DataFrame([3, 4, 5], index=Index([1, 3, 9], name="col3"), columns=m)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_margins_name_unicode(self):
+ # issue #13292
+ greek = "\u0394\u03bf\u03ba\u03b9\u03bc\u03ae"
+ frame = DataFrame({"foo": [1, 2, 3]})
+ table = pivot_table(
+ frame, index=["foo"], aggfunc=len, margins=True, margins_name=greek
+ )
+ index = Index([1, 2, 3, greek], dtype="object", name="foo")
+ expected = DataFrame(index=index, columns=[])
+ tm.assert_frame_equal(table, expected)
+
+ def test_pivot_string_as_func(self):
+ # GH #18713
+ # for correctness purposes
+ data = DataFrame(
+ {
+ "A": [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ "foo",
+ "foo",
+ "foo",
+ ],
+ "B": [
+ "one",
+ "one",
+ "one",
+ "two",
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "two",
+ "one",
+ ],
+ "C": range(11),
+ }
+ )
+
+ result = pivot_table(data, index="A", columns="B", aggfunc="sum")
+ mi = MultiIndex(
+ levels=[["C"], ["one", "two"]], codes=[[0, 0], [0, 1]], names=[None, "B"]
+ )
+ expected = DataFrame(
+ {("C", "one"): {"bar": 15, "foo": 13}, ("C", "two"): {"bar": 7, "foo": 20}},
+ columns=mi,
+ ).rename_axis("A")
+ tm.assert_frame_equal(result, expected)
+
+ result = pivot_table(data, index="A", columns="B", aggfunc=["sum", "mean"])
+ mi = MultiIndex(
+ levels=[["sum", "mean"], ["C"], ["one", "two"]],
+ codes=[[0, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 1]],
+ names=[None, None, "B"],
+ )
+ expected = DataFrame(
+ {
+ ("mean", "C", "one"): {"bar": 5.0, "foo": 3.25},
+ ("mean", "C", "two"): {"bar": 7.0, "foo": 6.666666666666667},
+ ("sum", "C", "one"): {"bar": 15, "foo": 13},
+ ("sum", "C", "two"): {"bar": 7, "foo": 20},
+ },
+ columns=mi,
+ ).rename_axis("A")
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "f, f_numpy",
+ [
+ ("sum", np.sum),
+ ("mean", np.mean),
+ ("std", np.std),
+ (["sum", "mean"], [np.sum, np.mean]),
+ (["sum", "std"], [np.sum, np.std]),
+ (["std", "mean"], [np.std, np.mean]),
+ ],
+ )
+ def test_pivot_string_func_vs_func(self, f, f_numpy, data):
+ # GH #18713
+ # for consistency purposes
+ data = data.drop(columns="C")
+ result = pivot_table(data, index="A", columns="B", aggfunc=f)
+ ops = "|".join(f) if isinstance(f, list) else f
+ msg = f"using DataFrameGroupBy.[{ops}]"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ expected = pivot_table(data, index="A", columns="B", aggfunc=f_numpy)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.slow
+ def test_pivot_number_of_levels_larger_than_int32(self, monkeypatch):
+ # GH 20601
+ # GH 26314: Change ValueError to PerformanceWarning
+ class MockUnstacker(reshape_lib._Unstacker):
+ def __init__(self, *args, **kwargs) -> None:
+ # __init__ will raise the warning
+ super().__init__(*args, **kwargs)
+ raise Exception("Don't compute final result.")
+
+ with monkeypatch.context() as m:
+ m.setattr(reshape_lib, "_Unstacker", MockUnstacker)
+ df = DataFrame(
+ {"ind1": np.arange(2**16), "ind2": np.arange(2**16), "count": 0}
+ )
+
+ msg = "The following operation may generate"
+ with tm.assert_produces_warning(PerformanceWarning, match=msg):
+ with pytest.raises(Exception, match="Don't compute final result."):
+ df.pivot_table(
+ index="ind1", columns="ind2", values="count", aggfunc="count"
+ )
+
+ def test_pivot_table_aggfunc_dropna(self, dropna):
+ # GH 22159
+ df = DataFrame(
+ {
+ "fruit": ["apple", "peach", "apple"],
+ "size": [1, 1, 2],
+ "taste": [7, 6, 6],
+ }
+ )
+
+ def ret_one(x):
+ return 1
+
+ def ret_sum(x):
+ return sum(x)
+
+ def ret_none(x):
+ return np.nan
+
+ result = pivot_table(
+ df, columns="fruit", aggfunc=[ret_sum, ret_none, ret_one], dropna=dropna
+ )
+
+ data = [[3, 1, np.nan, np.nan, 1, 1], [13, 6, np.nan, np.nan, 1, 1]]
+ col = MultiIndex.from_product(
+ [["ret_sum", "ret_none", "ret_one"], ["apple", "peach"]],
+ names=[None, "fruit"],
+ )
+ expected = DataFrame(data, index=["size", "taste"], columns=col)
+
+ if dropna:
+ expected = expected.dropna(axis="columns")
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_aggfunc_scalar_dropna(self, dropna):
+ # GH 22159
+ df = DataFrame(
+ {"A": ["one", "two", "one"], "x": [3, np.nan, 2], "y": [1, np.nan, np.nan]}
+ )
+
+ result = pivot_table(df, columns="A", aggfunc="mean", dropna=dropna)
+
+ data = [[2.5, np.nan], [1, np.nan]]
+ col = Index(["one", "two"], name="A")
+ expected = DataFrame(data, index=["x", "y"], columns=col)
+
+ if dropna:
+ expected = expected.dropna(axis="columns")
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("margins", [True, False])
+ def test_pivot_table_empty_aggfunc(self, margins):
+ # GH 9186 & GH 13483 & GH 49240
+ df = DataFrame(
+ {
+ "A": [2, 2, 3, 3, 2],
+ "id": [5, 6, 7, 8, 9],
+ "C": ["p", "q", "q", "p", "q"],
+ "D": [None, None, None, None, None],
+ }
+ )
+ result = df.pivot_table(
+ index="A", columns="D", values="id", aggfunc=np.size, margins=margins
+ )
+ exp_cols = Index([], name="D")
+ expected = DataFrame(index=Index([], dtype="int64", name="A"), columns=exp_cols)
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_no_column_raises(self):
+ # GH 10326
+ def agg(arr):
+ return np.mean(arr)
+
+ df = DataFrame({"X": [0, 0, 1, 1], "Y": [0, 1, 0, 1], "Z": [10, 20, 30, 40]})
+ with pytest.raises(KeyError, match="notpresent"):
+ df.pivot_table("notpresent", "X", "Y", aggfunc=agg)
+
+ def test_pivot_table_multiindex_columns_doctest_case(self):
+ # The relevant characteristic is that the call
+ # to maybe_downcast_to_dtype(agged[v], data[v].dtype) in
+ # __internal_pivot_table has `agged[v]` a DataFrame instead of Series,
+ # In this case this is because agged.columns is a MultiIndex and 'v'
+ # is only indexing on its first level.
+ df = DataFrame(
+ {
+ "A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
+ "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"],
+ "C": [
+ "small",
+ "large",
+ "large",
+ "small",
+ "small",
+ "large",
+ "small",
+ "small",
+ "large",
+ ],
+ "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
+ "E": [2, 4, 5, 5, 6, 6, 8, 9, 9],
+ }
+ )
+
+ table = pivot_table(
+ df,
+ values=["D", "E"],
+ index=["A", "C"],
+ aggfunc={"D": "mean", "E": ["min", "max", "mean"]},
+ )
+ cols = MultiIndex.from_tuples(
+ [("D", "mean"), ("E", "max"), ("E", "mean"), ("E", "min")]
+ )
+ index = MultiIndex.from_tuples(
+ [("bar", "large"), ("bar", "small"), ("foo", "large"), ("foo", "small")],
+ names=["A", "C"],
+ )
+ vals = np.array(
+ [
+ [5.5, 9.0, 7.5, 6.0],
+ [5.5, 9.0, 8.5, 8.0],
+ [2.0, 5.0, 4.5, 4.0],
+ [2.33333333, 6.0, 4.33333333, 2.0],
+ ]
+ )
+ expected = DataFrame(vals, columns=cols, index=index)
+ expected[("E", "min")] = expected[("E", "min")].astype(np.int64)
+ expected[("E", "max")] = expected[("E", "max")].astype(np.int64)
+ tm.assert_frame_equal(table, expected)
+
+ def test_pivot_table_sort_false(self):
+ # GH#39143
+ df = DataFrame(
+ {
+ "a": ["d1", "d4", "d3"],
+ "col": ["a", "b", "c"],
+ "num": [23, 21, 34],
+ "year": ["2018", "2018", "2019"],
+ }
+ )
+ result = df.pivot_table(
+ index=["a", "col"], columns="year", values="num", aggfunc="sum", sort=False
+ )
+ expected = DataFrame(
+ [[23, np.nan], [21, np.nan], [np.nan, 34]],
+ columns=Index(["2018", "2019"], name="year"),
+ index=MultiIndex.from_arrays(
+ [["d1", "d4", "d3"], ["a", "b", "c"]], names=["a", "col"]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_nullable_margins(self):
+ # GH#48681
+ df = DataFrame(
+ {"a": "A", "b": [1, 2], "sales": Series([10, 11], dtype="Int64")}
+ )
+
+ result = df.pivot_table(index="b", columns="a", margins=True, aggfunc="sum")
+ expected = DataFrame(
+ [[10, 10], [11, 11], [21, 21]],
+ index=Index([1, 2, "All"], name="b"),
+ columns=MultiIndex.from_tuples(
+ [("sales", "A"), ("sales", "All")], names=[None, "a"]
+ ),
+ dtype="Int64",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_sort_false_with_multiple_values(self):
+ df = DataFrame(
+ {
+ "firstname": ["John", "Michael"],
+ "lastname": ["Foo", "Bar"],
+ "height": [173, 182],
+ "age": [47, 33],
+ }
+ )
+ result = df.pivot_table(
+ index=["lastname", "firstname"], values=["height", "age"], sort=False
+ )
+ expected = DataFrame(
+ [[173.0, 47.0], [182.0, 33.0]],
+ columns=["height", "age"],
+ index=MultiIndex.from_tuples(
+ [("Foo", "John"), ("Bar", "Michael")],
+ names=["lastname", "firstname"],
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_with_margins_and_numeric_columns(self):
+ # GH 26568
+ df = DataFrame([["a", "x", 1], ["a", "y", 2], ["b", "y", 3], ["b", "z", 4]])
+ df.columns = [10, 20, 30]
+
+ result = df.pivot_table(
+ index=10, columns=20, values=30, aggfunc="sum", fill_value=0, margins=True
+ )
+
+ expected = DataFrame([[1, 2, 0, 3], [0, 3, 4, 7], [1, 5, 4, 10]])
+ expected.columns = ["x", "y", "z", "All"]
+ expected.index = ["a", "b", "All"]
+ expected.columns.name = 20
+ expected.index.name = 10
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dropna", [True, False])
+ def test_pivot_ea_dtype_dropna(self, dropna):
+ # GH#47477
+ df = DataFrame({"x": "a", "y": "b", "age": Series([20, 40], dtype="Int64")})
+ result = df.pivot_table(
+ index="x", columns="y", values="age", aggfunc="mean", dropna=dropna
+ )
+ expected = DataFrame(
+ [[30]],
+ index=Index(["a"], name="x"),
+ columns=Index(["b"], name="y"),
+ dtype="Float64",
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_datetime_warning(self):
+ # GH#48683
+ df = DataFrame(
+ {
+ "a": "A",
+ "b": [1, 2],
+ "date": pd.Timestamp("2019-12-31"),
+ "sales": [10.0, 11],
+ }
+ )
+ with tm.assert_produces_warning(None):
+ result = df.pivot_table(
+ index=["b", "date"], columns="a", margins=True, aggfunc="sum"
+ )
+ expected = DataFrame(
+ [[10.0, 10.0], [11.0, 11.0], [21.0, 21.0]],
+ index=MultiIndex.from_arrays(
+ [
+ Index([1, 2, "All"], name="b"),
+ Index(
+ [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31"), ""],
+ dtype=object,
+ name="date",
+ ),
+ ]
+ ),
+ columns=MultiIndex.from_tuples(
+ [("sales", "A"), ("sales", "All")], names=[None, "a"]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_with_mixed_nested_tuples(self, using_array_manager):
+ # GH 50342
+ df = DataFrame(
+ {
+ "A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
+ "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"],
+ "C": [
+ "small",
+ "large",
+ "large",
+ "small",
+ "small",
+ "large",
+ "small",
+ "small",
+ "large",
+ ],
+ "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
+ "E": [2, 4, 5, 5, 6, 6, 8, 9, 9],
+ ("col5",): [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ ],
+ ("col6", 6): [
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "one",
+ "one",
+ "two",
+ "two",
+ ],
+ (7, "seven"): [
+ "small",
+ "large",
+ "large",
+ "small",
+ "small",
+ "large",
+ "small",
+ "small",
+ "large",
+ ],
+ }
+ )
+ result = pivot_table(
+ df, values="D", index=["A", "B"], columns=[(7, "seven")], aggfunc="sum"
+ )
+ expected = DataFrame(
+ [[4.0, 5.0], [7.0, 6.0], [4.0, 1.0], [np.nan, 6.0]],
+ columns=Index(["large", "small"], name=(7, "seven")),
+ index=MultiIndex.from_arrays(
+ [["bar", "bar", "foo", "foo"], ["one", "two"] * 2], names=["A", "B"]
+ ),
+ )
+ if using_array_manager:
+ # INFO(ArrayManager) column without NaNs can preserve int dtype
+ expected["small"] = expected["small"].astype("int64")
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_table_aggfunc_nunique_with_different_values(self):
+ test = DataFrame(
+ {
+ "a": range(10),
+ "b": range(10),
+ "c": range(10),
+ "d": range(10),
+ }
+ )
+
+ columnval = MultiIndex.from_arrays(
+ [
+ ["nunique" for i in range(10)],
+ ["c" for i in range(10)],
+ range(10),
+ ],
+ names=(None, None, "b"),
+ )
+ nparr = np.full((10, 10), np.nan)
+ np.fill_diagonal(nparr, 1.0)
+
+ expected = DataFrame(nparr, index=Index(range(10), name="a"), columns=columnval)
+ result = test.pivot_table(
+ index=[
+ "a",
+ ],
+ columns=[
+ "b",
+ ],
+ values=[
+ "c",
+ ],
+ aggfunc=["nunique"],
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
+class TestPivot:
+ def test_pivot(self):
+ data = {
+ "index": ["A", "B", "C", "C", "B", "A"],
+ "columns": ["One", "One", "One", "Two", "Two", "Two"],
+ "values": [1.0, 2.0, 3.0, 3.0, 2.0, 1.0],
+ }
+
+ frame = DataFrame(data)
+ pivoted = frame.pivot(index="index", columns="columns", values="values")
+
+ expected = DataFrame(
+ {
+ "One": {"A": 1.0, "B": 2.0, "C": 3.0},
+ "Two": {"A": 1.0, "B": 2.0, "C": 3.0},
+ }
+ )
+
+ expected.index.name, expected.columns.name = "index", "columns"
+ tm.assert_frame_equal(pivoted, expected)
+
+ # name tracking
+ assert pivoted.index.name == "index"
+ assert pivoted.columns.name == "columns"
+
+ # don't specify values
+ pivoted = frame.pivot(index="index", columns="columns")
+ assert pivoted.index.name == "index"
+ assert pivoted.columns.names == (None, "columns")
+
+ def test_pivot_duplicates(self):
+ data = DataFrame(
+ {
+ "a": ["bar", "bar", "foo", "foo", "foo"],
+ "b": ["one", "two", "one", "one", "two"],
+ "c": [1.0, 2.0, 3.0, 3.0, 4.0],
+ }
+ )
+ with pytest.raises(ValueError, match="duplicate entries"):
+ data.pivot(index="a", columns="b", values="c")
+
+ def test_pivot_empty(self):
+ df = DataFrame(columns=["a", "b", "c"])
+ result = df.pivot(index="a", columns="b", values="c")
+ expected = DataFrame(index=[], columns=[])
+ tm.assert_frame_equal(result, expected, check_names=False)
+
+ def test_pivot_integer_bug(self):
+ df = DataFrame(data=[("A", "1", "A1"), ("B", "2", "B2")])
+
+ result = df.pivot(index=1, columns=0, values=2)
+ repr(result)
+ tm.assert_index_equal(result.columns, Index(["A", "B"], name=0))
+
+ def test_pivot_index_none(self):
+ # GH#3962
+ data = {
+ "index": ["A", "B", "C", "C", "B", "A"],
+ "columns": ["One", "One", "One", "Two", "Two", "Two"],
+ "values": [1.0, 2.0, 3.0, 3.0, 2.0, 1.0],
+ }
+
+ frame = DataFrame(data).set_index("index")
+ result = frame.pivot(columns="columns", values="values")
+ expected = DataFrame(
+ {
+ "One": {"A": 1.0, "B": 2.0, "C": 3.0},
+ "Two": {"A": 1.0, "B": 2.0, "C": 3.0},
+ }
+ )
+
+ expected.index.name, expected.columns.name = "index", "columns"
+ tm.assert_frame_equal(result, expected)
+
+ # omit values
+ result = frame.pivot(columns="columns")
+
+ expected.columns = MultiIndex.from_tuples(
+ [("values", "One"), ("values", "Two")], names=[None, "columns"]
+ )
+ expected.index.name = "index"
+ tm.assert_frame_equal(result, expected, check_names=False)
+ assert result.index.name == "index"
+ assert result.columns.names == (None, "columns")
+ expected.columns = expected.columns.droplevel(0)
+ result = frame.pivot(columns="columns", values="values")
+
+ expected.columns.name = "columns"
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_index_list_values_none_immutable_args(self):
+ # GH37635
+ df = DataFrame(
+ {
+ "lev1": [1, 1, 1, 2, 2, 2],
+ "lev2": [1, 1, 2, 1, 1, 2],
+ "lev3": [1, 2, 1, 2, 1, 2],
+ "lev4": [1, 2, 3, 4, 5, 6],
+ "values": [0, 1, 2, 3, 4, 5],
+ }
+ )
+ index = ["lev1", "lev2"]
+ columns = ["lev3"]
+ result = df.pivot(index=index, columns=columns)
+
+ expected = DataFrame(
+ np.array(
+ [
+ [1.0, 2.0, 0.0, 1.0],
+ [3.0, np.nan, 2.0, np.nan],
+ [5.0, 4.0, 4.0, 3.0],
+ [np.nan, 6.0, np.nan, 5.0],
+ ]
+ ),
+ index=MultiIndex.from_arrays(
+ [(1, 1, 2, 2), (1, 2, 1, 2)], names=["lev1", "lev2"]
+ ),
+ columns=MultiIndex.from_arrays(
+ [("lev4", "lev4", "values", "values"), (1, 2, 1, 2)],
+ names=[None, "lev3"],
+ ),
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ assert index == ["lev1", "lev2"]
+ assert columns == ["lev3"]
+
+ def test_pivot_columns_not_given(self):
+ # GH#48293
+ df = DataFrame({"a": [1], "b": 1})
+ with pytest.raises(TypeError, match="missing 1 required keyword-only argument"):
+ df.pivot() # pylint: disable=missing-kwoa
+
+ def test_pivot_columns_is_none(self):
+ # GH#48293
+ df = DataFrame({None: [1], "b": 2, "c": 3})
+ result = df.pivot(columns=None)
+ expected = DataFrame({("b", 1): [2], ("c", 1): 3})
+ tm.assert_frame_equal(result, expected)
+
+ result = df.pivot(columns=None, index="b")
+ expected = DataFrame({("c", 1): 3}, index=Index([2], name="b"))
+ tm.assert_frame_equal(result, expected)
+
+ result = df.pivot(columns=None, index="b", values="c")
+ expected = DataFrame({1: 3}, index=Index([2], name="b"))
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_index_is_none(self):
+ # GH#48293
+ df = DataFrame({None: [1], "b": 2, "c": 3})
+
+ result = df.pivot(columns="b", index=None)
+ expected = DataFrame({("c", 2): 3}, index=[1])
+ expected.columns.names = [None, "b"]
+ tm.assert_frame_equal(result, expected)
+
+ result = df.pivot(columns="b", index=None, values="c")
+ expected = DataFrame(3, index=[1], columns=Index([2], name="b"))
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_values_is_none(self):
+ # GH#48293
+ df = DataFrame({None: [1], "b": 2, "c": 3})
+
+ result = df.pivot(columns="b", index="c", values=None)
+ expected = DataFrame(
+ 1, index=Index([3], name="c"), columns=Index([2], name="b")
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.pivot(columns="b", values=None)
+ expected = DataFrame(1, index=[0], columns=Index([2], name="b"))
+ tm.assert_frame_equal(result, expected)
+
+ def test_pivot_not_changing_index_name(self):
+ # GH#52692
+ df = DataFrame({"one": ["a"], "two": 0, "three": 1})
+ expected = df.copy(deep=True)
+ df.pivot(index="one", columns="two", values="three")
+ tm.assert_frame_equal(df, expected)
+
+ def test_pivot_table_empty_dataframe_correct_index(self):
+ # GH 21932
+ df = DataFrame([], columns=["a", "b", "value"])
+ pivot = df.pivot_table(index="a", columns="b", values="value", aggfunc="count")
+
+ expected = Index([], dtype="object", name="b")
+ tm.assert_index_equal(pivot.columns, expected)
+
+ def test_pivot_table_handles_explicit_datetime_types(self):
+ # GH#43574
+ df = DataFrame(
+ [
+ {"a": "x", "date_str": "2023-01-01", "amount": 1},
+ {"a": "y", "date_str": "2023-01-02", "amount": 2},
+ {"a": "z", "date_str": "2023-01-03", "amount": 3},
+ ]
+ )
+ df["date"] = pd.to_datetime(df["date_str"])
+
+ with tm.assert_produces_warning(False):
+ pivot = df.pivot_table(
+ index=["a", "date"], values=["amount"], aggfunc="sum", margins=True
+ )
+
+ expected = MultiIndex.from_tuples(
+ [
+ ("x", datetime.strptime("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")),
+ ("y", datetime.strptime("2023-01-02 00:00:00", "%Y-%m-%d %H:%M:%S")),
+ ("z", datetime.strptime("2023-01-03 00:00:00", "%Y-%m-%d %H:%M:%S")),
+ ("All", ""),
+ ],
+ names=["a", "date"],
+ )
+ tm.assert_index_equal(pivot.index, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_pivot_multilevel.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_pivot_multilevel.py
new file mode 100644
index 0000000000000000000000000000000000000000..08ef29440825f006bf53eea7f21f0809bff99908
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_pivot_multilevel.py
@@ -0,0 +1,254 @@
+import numpy as np
+import pytest
+
+from pandas._libs import lib
+
+import pandas as pd
+from pandas import (
+ Index,
+ MultiIndex,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize(
+ "input_index, input_columns, input_values, "
+ "expected_values, expected_columns, expected_index",
+ [
+ (
+ ["lev4"],
+ "lev3",
+ "values",
+ [
+ [0.0, np.nan],
+ [np.nan, 1.0],
+ [2.0, np.nan],
+ [np.nan, 3.0],
+ [4.0, np.nan],
+ [np.nan, 5.0],
+ [6.0, np.nan],
+ [np.nan, 7.0],
+ ],
+ Index([1, 2], name="lev3"),
+ Index([1, 2, 3, 4, 5, 6, 7, 8], name="lev4"),
+ ),
+ (
+ ["lev4"],
+ "lev3",
+ lib.no_default,
+ [
+ [1.0, np.nan, 1.0, np.nan, 0.0, np.nan],
+ [np.nan, 1.0, np.nan, 1.0, np.nan, 1.0],
+ [1.0, np.nan, 2.0, np.nan, 2.0, np.nan],
+ [np.nan, 1.0, np.nan, 2.0, np.nan, 3.0],
+ [2.0, np.nan, 1.0, np.nan, 4.0, np.nan],
+ [np.nan, 2.0, np.nan, 1.0, np.nan, 5.0],
+ [2.0, np.nan, 2.0, np.nan, 6.0, np.nan],
+ [np.nan, 2.0, np.nan, 2.0, np.nan, 7.0],
+ ],
+ MultiIndex.from_tuples(
+ [
+ ("lev1", 1),
+ ("lev1", 2),
+ ("lev2", 1),
+ ("lev2", 2),
+ ("values", 1),
+ ("values", 2),
+ ],
+ names=[None, "lev3"],
+ ),
+ Index([1, 2, 3, 4, 5, 6, 7, 8], name="lev4"),
+ ),
+ (
+ ["lev1", "lev2"],
+ "lev3",
+ "values",
+ [[0, 1], [2, 3], [4, 5], [6, 7]],
+ Index([1, 2], name="lev3"),
+ MultiIndex.from_tuples(
+ [(1, 1), (1, 2), (2, 1), (2, 2)], names=["lev1", "lev2"]
+ ),
+ ),
+ (
+ ["lev1", "lev2"],
+ "lev3",
+ lib.no_default,
+ [[1, 2, 0, 1], [3, 4, 2, 3], [5, 6, 4, 5], [7, 8, 6, 7]],
+ MultiIndex.from_tuples(
+ [("lev4", 1), ("lev4", 2), ("values", 1), ("values", 2)],
+ names=[None, "lev3"],
+ ),
+ MultiIndex.from_tuples(
+ [(1, 1), (1, 2), (2, 1), (2, 2)], names=["lev1", "lev2"]
+ ),
+ ),
+ ],
+)
+def test_pivot_list_like_index(
+ input_index,
+ input_columns,
+ input_values,
+ expected_values,
+ expected_columns,
+ expected_index,
+):
+ # GH 21425, test when index is given a list
+ df = pd.DataFrame(
+ {
+ "lev1": [1, 1, 1, 1, 2, 2, 2, 2],
+ "lev2": [1, 1, 2, 2, 1, 1, 2, 2],
+ "lev3": [1, 2, 1, 2, 1, 2, 1, 2],
+ "lev4": [1, 2, 3, 4, 5, 6, 7, 8],
+ "values": [0, 1, 2, 3, 4, 5, 6, 7],
+ }
+ )
+
+ result = df.pivot(index=input_index, columns=input_columns, values=input_values)
+ expected = pd.DataFrame(
+ expected_values, columns=expected_columns, index=expected_index
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "input_index, input_columns, input_values, "
+ "expected_values, expected_columns, expected_index",
+ [
+ (
+ "lev4",
+ ["lev3"],
+ "values",
+ [
+ [0.0, np.nan],
+ [np.nan, 1.0],
+ [2.0, np.nan],
+ [np.nan, 3.0],
+ [4.0, np.nan],
+ [np.nan, 5.0],
+ [6.0, np.nan],
+ [np.nan, 7.0],
+ ],
+ Index([1, 2], name="lev3"),
+ Index([1, 2, 3, 4, 5, 6, 7, 8], name="lev4"),
+ ),
+ (
+ ["lev1", "lev2"],
+ ["lev3"],
+ "values",
+ [[0, 1], [2, 3], [4, 5], [6, 7]],
+ Index([1, 2], name="lev3"),
+ MultiIndex.from_tuples(
+ [(1, 1), (1, 2), (2, 1), (2, 2)], names=["lev1", "lev2"]
+ ),
+ ),
+ (
+ ["lev1"],
+ ["lev2", "lev3"],
+ "values",
+ [[0, 1, 2, 3], [4, 5, 6, 7]],
+ MultiIndex.from_tuples(
+ [(1, 1), (1, 2), (2, 1), (2, 2)], names=["lev2", "lev3"]
+ ),
+ Index([1, 2], name="lev1"),
+ ),
+ (
+ ["lev1", "lev2"],
+ ["lev3", "lev4"],
+ "values",
+ [
+ [0.0, 1.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
+ [np.nan, np.nan, 2.0, 3.0, np.nan, np.nan, np.nan, np.nan],
+ [np.nan, np.nan, np.nan, np.nan, 4.0, 5.0, np.nan, np.nan],
+ [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 6.0, 7.0],
+ ],
+ MultiIndex.from_tuples(
+ [(1, 1), (2, 2), (1, 3), (2, 4), (1, 5), (2, 6), (1, 7), (2, 8)],
+ names=["lev3", "lev4"],
+ ),
+ MultiIndex.from_tuples(
+ [(1, 1), (1, 2), (2, 1), (2, 2)], names=["lev1", "lev2"]
+ ),
+ ),
+ ],
+)
+def test_pivot_list_like_columns(
+ input_index,
+ input_columns,
+ input_values,
+ expected_values,
+ expected_columns,
+ expected_index,
+):
+ # GH 21425, test when columns is given a list
+ df = pd.DataFrame(
+ {
+ "lev1": [1, 1, 1, 1, 2, 2, 2, 2],
+ "lev2": [1, 1, 2, 2, 1, 1, 2, 2],
+ "lev3": [1, 2, 1, 2, 1, 2, 1, 2],
+ "lev4": [1, 2, 3, 4, 5, 6, 7, 8],
+ "values": [0, 1, 2, 3, 4, 5, 6, 7],
+ }
+ )
+
+ result = df.pivot(index=input_index, columns=input_columns, values=input_values)
+ expected = pd.DataFrame(
+ expected_values, columns=expected_columns, index=expected_index
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_pivot_multiindexed_rows_and_cols(using_array_manager):
+ # GH 36360
+
+ df = pd.DataFrame(
+ data=np.arange(12).reshape(4, 3),
+ columns=MultiIndex.from_tuples(
+ [(0, 0), (0, 1), (0, 2)], names=["col_L0", "col_L1"]
+ ),
+ index=MultiIndex.from_tuples(
+ [(0, 0, 0), (0, 0, 1), (1, 1, 1), (1, 0, 0)],
+ names=["idx_L0", "idx_L1", "idx_L2"],
+ ),
+ )
+
+ res = df.pivot_table(
+ index=["idx_L0"],
+ columns=["idx_L1"],
+ values=[(0, 1)],
+ aggfunc=lambda col: col.values.sum(),
+ )
+
+ expected = pd.DataFrame(
+ data=[[5, np.nan], [10, 7.0]],
+ columns=MultiIndex.from_tuples(
+ [(0, 1, 0), (0, 1, 1)], names=["col_L0", "col_L1", "idx_L1"]
+ ),
+ index=Index([0, 1], dtype="int64", name="idx_L0"),
+ )
+ if not using_array_manager:
+ # BlockManager does not preserve the dtypes
+ expected = expected.astype("float64")
+
+ tm.assert_frame_equal(res, expected)
+
+
+def test_pivot_df_multiindex_index_none():
+ # GH 23955
+ df = pd.DataFrame(
+ [
+ ["A", "A1", "label1", 1],
+ ["A", "A2", "label2", 2],
+ ["B", "A1", "label1", 3],
+ ["B", "A2", "label2", 4],
+ ],
+ columns=["index_1", "index_2", "label", "value"],
+ )
+ df = df.set_index(["index_1", "index_2"])
+
+ result = df.pivot(columns="label", values="value")
+ expected = pd.DataFrame(
+ [[1.0, np.nan], [np.nan, 2.0], [3.0, np.nan], [np.nan, 4.0]],
+ index=df.index,
+ columns=Index(["label1", "label2"], name="label"),
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_qcut.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_qcut.py
new file mode 100644
index 0000000000000000000000000000000000000000..907eeca6e9b5e6eb036e9582dbb32fbc724d90d6
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_qcut.py
@@ -0,0 +1,302 @@
+import os
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DatetimeIndex,
+ Interval,
+ IntervalIndex,
+ NaT,
+ Series,
+ TimedeltaIndex,
+ Timestamp,
+ cut,
+ date_range,
+ isna,
+ qcut,
+ timedelta_range,
+)
+import pandas._testing as tm
+from pandas.api.types import CategoricalDtype as CDT
+
+from pandas.tseries.offsets import (
+ Day,
+ Nano,
+)
+
+
+def test_qcut():
+ arr = np.random.default_rng(2).standard_normal(1000)
+
+ # We store the bins as Index that have been
+ # rounded to comparisons are a bit tricky.
+ labels, _ = qcut(arr, 4, retbins=True)
+ ex_bins = np.quantile(arr, [0, 0.25, 0.5, 0.75, 1.0])
+
+ result = labels.categories.left.values
+ assert np.allclose(result, ex_bins[:-1], atol=1e-2)
+
+ result = labels.categories.right.values
+ assert np.allclose(result, ex_bins[1:], atol=1e-2)
+
+ ex_levels = cut(arr, ex_bins, include_lowest=True)
+ tm.assert_categorical_equal(labels, ex_levels)
+
+
+def test_qcut_bounds():
+ arr = np.random.default_rng(2).standard_normal(1000)
+
+ factor = qcut(arr, 10, labels=False)
+ assert len(np.unique(factor)) == 10
+
+
+def test_qcut_specify_quantiles():
+ arr = np.random.default_rng(2).standard_normal(100)
+ factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0])
+
+ expected = qcut(arr, 4)
+ tm.assert_categorical_equal(factor, expected)
+
+
+def test_qcut_all_bins_same():
+ with pytest.raises(ValueError, match="edges.*unique"):
+ qcut([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3)
+
+
+def test_qcut_include_lowest():
+ values = np.arange(10)
+ ii = qcut(values, 4)
+
+ ex_levels = IntervalIndex(
+ [
+ Interval(-0.001, 2.25),
+ Interval(2.25, 4.5),
+ Interval(4.5, 6.75),
+ Interval(6.75, 9),
+ ]
+ )
+ tm.assert_index_equal(ii.categories, ex_levels)
+
+
+def test_qcut_nas():
+ arr = np.random.default_rng(2).standard_normal(100)
+ arr[:20] = np.nan
+
+ result = qcut(arr, 4)
+ assert isna(result[:20]).all()
+
+
+def test_qcut_index():
+ result = qcut([0, 2], 2)
+ intervals = [Interval(-0.001, 1), Interval(1, 2)]
+
+ expected = Categorical(intervals, ordered=True)
+ tm.assert_categorical_equal(result, expected)
+
+
+def test_qcut_binning_issues(datapath):
+ # see gh-1978, gh-1979
+ cut_file = datapath(os.path.join("reshape", "data", "cut_data.csv"))
+ arr = np.loadtxt(cut_file)
+ result = qcut(arr, 20)
+
+ starts = []
+ ends = []
+
+ for lev in np.unique(result):
+ s = lev.left
+ e = lev.right
+ assert s != e
+
+ starts.append(float(s))
+ ends.append(float(e))
+
+ for (sp, sn), (ep, en) in zip(
+ zip(starts[:-1], starts[1:]), zip(ends[:-1], ends[1:])
+ ):
+ assert sp < sn
+ assert ep < en
+ assert ep <= sn
+
+
+def test_qcut_return_intervals():
+ ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8])
+ res = qcut(ser, [0, 0.333, 0.666, 1])
+
+ exp_levels = np.array(
+ [Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)]
+ )
+ exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype(CDT(ordered=True))
+ tm.assert_series_equal(res, exp)
+
+
+@pytest.mark.parametrize("labels", ["foo", 1, True])
+def test_qcut_incorrect_labels(labels):
+ # GH 13318
+ values = range(5)
+ msg = "Bin labels must either be False, None or passed in as a list-like argument"
+ with pytest.raises(ValueError, match=msg):
+ qcut(values, 4, labels=labels)
+
+
+@pytest.mark.parametrize("labels", [["a", "b", "c"], list(range(3))])
+def test_qcut_wrong_length_labels(labels):
+ # GH 13318
+ values = range(10)
+ msg = "Bin labels must be one fewer than the number of bin edges"
+ with pytest.raises(ValueError, match=msg):
+ qcut(values, 4, labels=labels)
+
+
+@pytest.mark.parametrize(
+ "labels, expected",
+ [
+ (["a", "b", "c"], Categorical(["a", "b", "c"], ordered=True)),
+ (list(range(3)), Categorical([0, 1, 2], ordered=True)),
+ ],
+)
+def test_qcut_list_like_labels(labels, expected):
+ # GH 13318
+ values = range(3)
+ result = qcut(values, 3, labels=labels)
+ tm.assert_categorical_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "kwargs,msg",
+ [
+ ({"duplicates": "drop"}, None),
+ ({}, "Bin edges must be unique"),
+ ({"duplicates": "raise"}, "Bin edges must be unique"),
+ ({"duplicates": "foo"}, "invalid value for 'duplicates' parameter"),
+ ],
+)
+def test_qcut_duplicates_bin(kwargs, msg):
+ # see gh-7751
+ values = [0, 0, 0, 0, 1, 2, 3]
+
+ if msg is not None:
+ with pytest.raises(ValueError, match=msg):
+ qcut(values, 3, **kwargs)
+ else:
+ result = qcut(values, 3, **kwargs)
+ expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)])
+ tm.assert_index_equal(result.categories, expected)
+
+
+@pytest.mark.parametrize(
+ "data,start,end", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)]
+)
+@pytest.mark.parametrize("length", [1, 2])
+@pytest.mark.parametrize("labels", [None, False])
+def test_single_quantile(data, start, end, length, labels):
+ # see gh-15431
+ ser = Series([data] * length)
+ result = qcut(ser, 1, labels=labels)
+
+ if labels is None:
+ intervals = IntervalIndex([Interval(start, end)] * length, closed="right")
+ expected = Series(intervals).astype(CDT(ordered=True))
+ else:
+ expected = Series([0] * length, dtype=np.intp)
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "ser",
+ [
+ Series(DatetimeIndex(["20180101", NaT, "20180103"])),
+ Series(TimedeltaIndex(["0 days", NaT, "2 days"])),
+ ],
+ ids=lambda x: str(x.dtype),
+)
+def test_qcut_nat(ser):
+ # see gh-19768
+ intervals = IntervalIndex.from_tuples(
+ [(ser[0] - Nano(), ser[2] - Day()), np.nan, (ser[2] - Day(), ser[2])]
+ )
+ expected = Series(Categorical(intervals, ordered=True))
+
+ result = qcut(ser, 2)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("bins", [3, np.linspace(0, 1, 4)])
+def test_datetime_tz_qcut(bins):
+ # see gh-19872
+ tz = "US/Eastern"
+ ser = Series(date_range("20130101", periods=3, tz=tz))
+
+ result = qcut(ser, bins)
+ expected = Series(
+ IntervalIndex(
+ [
+ Interval(
+ Timestamp("2012-12-31 23:59:59.999999999", tz=tz),
+ Timestamp("2013-01-01 16:00:00", tz=tz),
+ ),
+ Interval(
+ Timestamp("2013-01-01 16:00:00", tz=tz),
+ Timestamp("2013-01-02 08:00:00", tz=tz),
+ ),
+ Interval(
+ Timestamp("2013-01-02 08:00:00", tz=tz),
+ Timestamp("2013-01-03 00:00:00", tz=tz),
+ ),
+ ]
+ )
+ ).astype(CDT(ordered=True))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "arg,expected_bins",
+ [
+ [
+ timedelta_range("1day", periods=3),
+ TimedeltaIndex(["1 days", "2 days", "3 days"]),
+ ],
+ [
+ date_range("20180101", periods=3),
+ DatetimeIndex(["2018-01-01", "2018-01-02", "2018-01-03"]),
+ ],
+ ],
+)
+def test_date_like_qcut_bins(arg, expected_bins):
+ # see gh-19891
+ ser = Series(arg)
+ result, result_bins = qcut(ser, 2, retbins=True)
+ tm.assert_index_equal(result_bins, expected_bins)
+
+
+@pytest.mark.parametrize("bins", [6, 7])
+@pytest.mark.parametrize(
+ "box, compare",
+ [
+ (Series, tm.assert_series_equal),
+ (np.array, tm.assert_categorical_equal),
+ (list, tm.assert_equal),
+ ],
+)
+def test_qcut_bool_coercion_to_int(bins, box, compare):
+ # issue 20303
+ data_expected = box([0, 1, 1, 0, 1] * 10)
+ data_result = box([False, True, True, False, True] * 10)
+ expected = qcut(data_expected, bins, duplicates="drop")
+ result = qcut(data_result, bins, duplicates="drop")
+ compare(result, expected)
+
+
+@pytest.mark.parametrize("q", [2, 5, 10])
+def test_qcut_nullable_integer(q, any_numeric_ea_dtype):
+ arr = pd.array(np.arange(100), dtype=any_numeric_ea_dtype)
+ arr[::2] = pd.NA
+
+ result = qcut(arr, q)
+ expected = qcut(arr.astype(float), q)
+
+ tm.assert_categorical_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_union_categoricals.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_union_categoricals.py
new file mode 100644
index 0000000000000000000000000000000000000000..7505d69aee134a1d29818b9faa2bbbe28f2af695
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_union_categoricals.py
@@ -0,0 +1,363 @@
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.concat import union_categoricals
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ Series,
+)
+import pandas._testing as tm
+
+
+class TestUnionCategoricals:
+ @pytest.mark.parametrize(
+ "a, b, combined",
+ [
+ (list("abc"), list("abd"), list("abcabd")),
+ ([0, 1, 2], [2, 3, 4], [0, 1, 2, 2, 3, 4]),
+ ([0, 1.2, 2], [2, 3.4, 4], [0, 1.2, 2, 2, 3.4, 4]),
+ (
+ ["b", "b", np.nan, "a"],
+ ["a", np.nan, "c"],
+ ["b", "b", np.nan, "a", "a", np.nan, "c"],
+ ),
+ (
+ pd.date_range("2014-01-01", "2014-01-05"),
+ pd.date_range("2014-01-06", "2014-01-07"),
+ pd.date_range("2014-01-01", "2014-01-07"),
+ ),
+ (
+ pd.date_range("2014-01-01", "2014-01-05", tz="US/Central"),
+ pd.date_range("2014-01-06", "2014-01-07", tz="US/Central"),
+ pd.date_range("2014-01-01", "2014-01-07", tz="US/Central"),
+ ),
+ (
+ pd.period_range("2014-01-01", "2014-01-05"),
+ pd.period_range("2014-01-06", "2014-01-07"),
+ pd.period_range("2014-01-01", "2014-01-07"),
+ ),
+ ],
+ )
+ @pytest.mark.parametrize("box", [Categorical, CategoricalIndex, Series])
+ def test_union_categorical(self, a, b, combined, box):
+ # GH 13361
+ result = union_categoricals([box(Categorical(a)), box(Categorical(b))])
+ expected = Categorical(combined)
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categorical_ordered_appearance(self):
+ # new categories ordered by appearance
+ s = Categorical(["x", "y", "z"])
+ s2 = Categorical(["a", "b", "c"])
+ result = union_categoricals([s, s2])
+ expected = Categorical(
+ ["x", "y", "z", "a", "b", "c"], categories=["x", "y", "z", "a", "b", "c"]
+ )
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categorical_ordered_true(self):
+ s = Categorical([0, 1.2, 2], ordered=True)
+ s2 = Categorical([0, 1.2, 2], ordered=True)
+ result = union_categoricals([s, s2])
+ expected = Categorical([0, 1.2, 2, 0, 1.2, 2], ordered=True)
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categorical_match_types(self):
+ # must exactly match types
+ s = Categorical([0, 1.2, 2])
+ s2 = Categorical([2, 3, 4])
+ msg = "dtype of categories must be the same"
+ with pytest.raises(TypeError, match=msg):
+ union_categoricals([s, s2])
+
+ def test_union_categorical_empty(self):
+ msg = "No Categoricals to union"
+ with pytest.raises(ValueError, match=msg):
+ union_categoricals([])
+
+ def test_union_categoricals_nan(self):
+ # GH 13759
+ res = union_categoricals(
+ [Categorical([1, 2, np.nan]), Categorical([3, 2, np.nan])]
+ )
+ exp = Categorical([1, 2, np.nan, 3, 2, np.nan])
+ tm.assert_categorical_equal(res, exp)
+
+ res = union_categoricals(
+ [Categorical(["A", "B"]), Categorical(["B", "B", np.nan])]
+ )
+ exp = Categorical(["A", "B", "B", "B", np.nan])
+ tm.assert_categorical_equal(res, exp)
+
+ val1 = [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-03-01"), pd.NaT]
+ val2 = [pd.NaT, pd.Timestamp("2011-01-01"), pd.Timestamp("2011-02-01")]
+
+ res = union_categoricals([Categorical(val1), Categorical(val2)])
+ exp = Categorical(
+ val1 + val2,
+ categories=[
+ pd.Timestamp("2011-01-01"),
+ pd.Timestamp("2011-03-01"),
+ pd.Timestamp("2011-02-01"),
+ ],
+ )
+ tm.assert_categorical_equal(res, exp)
+
+ # all NaN
+ res = union_categoricals(
+ [
+ Categorical(np.array([np.nan, np.nan], dtype=object)),
+ Categorical(["X"]),
+ ]
+ )
+ exp = Categorical([np.nan, np.nan, "X"])
+ tm.assert_categorical_equal(res, exp)
+
+ res = union_categoricals(
+ [Categorical([np.nan, np.nan]), Categorical([np.nan, np.nan])]
+ )
+ exp = Categorical([np.nan, np.nan, np.nan, np.nan])
+ tm.assert_categorical_equal(res, exp)
+
+ @pytest.mark.parametrize("val", [[], ["1"]])
+ def test_union_categoricals_empty(self, val):
+ # GH 13759
+ res = union_categoricals([Categorical([]), Categorical(val)])
+ exp = Categorical(val)
+ tm.assert_categorical_equal(res, exp)
+
+ def test_union_categorical_same_category(self):
+ # check fastpath
+ c1 = Categorical([1, 2, 3, 4], categories=[1, 2, 3, 4])
+ c2 = Categorical([3, 2, 1, np.nan], categories=[1, 2, 3, 4])
+ res = union_categoricals([c1, c2])
+ exp = Categorical([1, 2, 3, 4, 3, 2, 1, np.nan], categories=[1, 2, 3, 4])
+ tm.assert_categorical_equal(res, exp)
+
+ def test_union_categorical_same_category_str(self):
+ c1 = Categorical(["z", "z", "z"], categories=["x", "y", "z"])
+ c2 = Categorical(["x", "x", "x"], categories=["x", "y", "z"])
+ res = union_categoricals([c1, c2])
+ exp = Categorical(["z", "z", "z", "x", "x", "x"], categories=["x", "y", "z"])
+ tm.assert_categorical_equal(res, exp)
+
+ def test_union_categorical_same_categories_different_order(self):
+ # https://github.com/pandas-dev/pandas/issues/19096
+ c1 = Categorical(["a", "b", "c"], categories=["a", "b", "c"])
+ c2 = Categorical(["a", "b", "c"], categories=["b", "a", "c"])
+ result = union_categoricals([c1, c2])
+ expected = Categorical(
+ ["a", "b", "c", "a", "b", "c"], categories=["a", "b", "c"]
+ )
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categoricals_ordered(self):
+ c1 = Categorical([1, 2, 3], ordered=True)
+ c2 = Categorical([1, 2, 3], ordered=False)
+
+ msg = "Categorical.ordered must be the same"
+ with pytest.raises(TypeError, match=msg):
+ union_categoricals([c1, c2])
+
+ res = union_categoricals([c1, c1])
+ exp = Categorical([1, 2, 3, 1, 2, 3], ordered=True)
+ tm.assert_categorical_equal(res, exp)
+
+ c1 = Categorical([1, 2, 3, np.nan], ordered=True)
+ c2 = Categorical([3, 2], categories=[1, 2, 3], ordered=True)
+
+ res = union_categoricals([c1, c2])
+ exp = Categorical([1, 2, 3, np.nan, 3, 2], ordered=True)
+ tm.assert_categorical_equal(res, exp)
+
+ c1 = Categorical([1, 2, 3], ordered=True)
+ c2 = Categorical([1, 2, 3], categories=[3, 2, 1], ordered=True)
+
+ msg = "to union ordered Categoricals, all categories must be the same"
+ with pytest.raises(TypeError, match=msg):
+ union_categoricals([c1, c2])
+
+ def test_union_categoricals_ignore_order(self):
+ # GH 15219
+ c1 = Categorical([1, 2, 3], ordered=True)
+ c2 = Categorical([1, 2, 3], ordered=False)
+
+ res = union_categoricals([c1, c2], ignore_order=True)
+ exp = Categorical([1, 2, 3, 1, 2, 3])
+ tm.assert_categorical_equal(res, exp)
+
+ msg = "Categorical.ordered must be the same"
+ with pytest.raises(TypeError, match=msg):
+ union_categoricals([c1, c2], ignore_order=False)
+
+ res = union_categoricals([c1, c1], ignore_order=True)
+ exp = Categorical([1, 2, 3, 1, 2, 3])
+ tm.assert_categorical_equal(res, exp)
+
+ res = union_categoricals([c1, c1], ignore_order=False)
+ exp = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3], ordered=True)
+ tm.assert_categorical_equal(res, exp)
+
+ c1 = Categorical([1, 2, 3, np.nan], ordered=True)
+ c2 = Categorical([3, 2], categories=[1, 2, 3], ordered=True)
+
+ res = union_categoricals([c1, c2], ignore_order=True)
+ exp = Categorical([1, 2, 3, np.nan, 3, 2])
+ tm.assert_categorical_equal(res, exp)
+
+ c1 = Categorical([1, 2, 3], ordered=True)
+ c2 = Categorical([1, 2, 3], categories=[3, 2, 1], ordered=True)
+
+ res = union_categoricals([c1, c2], ignore_order=True)
+ exp = Categorical([1, 2, 3, 1, 2, 3])
+ tm.assert_categorical_equal(res, exp)
+
+ res = union_categoricals([c2, c1], ignore_order=True, sort_categories=True)
+ exp = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3])
+ tm.assert_categorical_equal(res, exp)
+
+ c1 = Categorical([1, 2, 3], ordered=True)
+ c2 = Categorical([4, 5, 6], ordered=True)
+ result = union_categoricals([c1, c2], ignore_order=True)
+ expected = Categorical([1, 2, 3, 4, 5, 6])
+ tm.assert_categorical_equal(result, expected)
+
+ msg = "to union ordered Categoricals, all categories must be the same"
+ with pytest.raises(TypeError, match=msg):
+ union_categoricals([c1, c2], ignore_order=False)
+
+ with pytest.raises(TypeError, match=msg):
+ union_categoricals([c1, c2])
+
+ def test_union_categoricals_sort(self):
+ # GH 13846
+ c1 = Categorical(["x", "y", "z"])
+ c2 = Categorical(["a", "b", "c"])
+ result = union_categoricals([c1, c2], sort_categories=True)
+ expected = Categorical(
+ ["x", "y", "z", "a", "b", "c"], categories=["a", "b", "c", "x", "y", "z"]
+ )
+ tm.assert_categorical_equal(result, expected)
+
+ # fastpath
+ c1 = Categorical(["a", "b"], categories=["b", "a", "c"])
+ c2 = Categorical(["b", "c"], categories=["b", "a", "c"])
+ result = union_categoricals([c1, c2], sort_categories=True)
+ expected = Categorical(["a", "b", "b", "c"], categories=["a", "b", "c"])
+ tm.assert_categorical_equal(result, expected)
+
+ c1 = Categorical(["a", "b"], categories=["c", "a", "b"])
+ c2 = Categorical(["b", "c"], categories=["c", "a", "b"])
+ result = union_categoricals([c1, c2], sort_categories=True)
+ expected = Categorical(["a", "b", "b", "c"], categories=["a", "b", "c"])
+ tm.assert_categorical_equal(result, expected)
+
+ # fastpath - skip resort
+ c1 = Categorical(["a", "b"], categories=["a", "b", "c"])
+ c2 = Categorical(["b", "c"], categories=["a", "b", "c"])
+ result = union_categoricals([c1, c2], sort_categories=True)
+ expected = Categorical(["a", "b", "b", "c"], categories=["a", "b", "c"])
+ tm.assert_categorical_equal(result, expected)
+
+ c1 = Categorical(["x", np.nan])
+ c2 = Categorical([np.nan, "b"])
+ result = union_categoricals([c1, c2], sort_categories=True)
+ expected = Categorical(["x", np.nan, np.nan, "b"], categories=["b", "x"])
+ tm.assert_categorical_equal(result, expected)
+
+ c1 = Categorical([np.nan])
+ c2 = Categorical([np.nan])
+ result = union_categoricals([c1, c2], sort_categories=True)
+ expected = Categorical([np.nan, np.nan])
+ tm.assert_categorical_equal(result, expected)
+
+ c1 = Categorical([])
+ c2 = Categorical([])
+ result = union_categoricals([c1, c2], sort_categories=True)
+ expected = Categorical([])
+ tm.assert_categorical_equal(result, expected)
+
+ c1 = Categorical(["b", "a"], categories=["b", "a", "c"], ordered=True)
+ c2 = Categorical(["a", "c"], categories=["b", "a", "c"], ordered=True)
+ msg = "Cannot use sort_categories=True with ordered Categoricals"
+ with pytest.raises(TypeError, match=msg):
+ union_categoricals([c1, c2], sort_categories=True)
+
+ def test_union_categoricals_sort_false(self):
+ # GH 13846
+ c1 = Categorical(["x", "y", "z"])
+ c2 = Categorical(["a", "b", "c"])
+ result = union_categoricals([c1, c2], sort_categories=False)
+ expected = Categorical(
+ ["x", "y", "z", "a", "b", "c"], categories=["x", "y", "z", "a", "b", "c"]
+ )
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categoricals_sort_false_fastpath(self):
+ # fastpath
+ c1 = Categorical(["a", "b"], categories=["b", "a", "c"])
+ c2 = Categorical(["b", "c"], categories=["b", "a", "c"])
+ result = union_categoricals([c1, c2], sort_categories=False)
+ expected = Categorical(["a", "b", "b", "c"], categories=["b", "a", "c"])
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categoricals_sort_false_skipresort(self):
+ # fastpath - skip resort
+ c1 = Categorical(["a", "b"], categories=["a", "b", "c"])
+ c2 = Categorical(["b", "c"], categories=["a", "b", "c"])
+ result = union_categoricals([c1, c2], sort_categories=False)
+ expected = Categorical(["a", "b", "b", "c"], categories=["a", "b", "c"])
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categoricals_sort_false_one_nan(self):
+ c1 = Categorical(["x", np.nan])
+ c2 = Categorical([np.nan, "b"])
+ result = union_categoricals([c1, c2], sort_categories=False)
+ expected = Categorical(["x", np.nan, np.nan, "b"], categories=["x", "b"])
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categoricals_sort_false_only_nan(self):
+ c1 = Categorical([np.nan])
+ c2 = Categorical([np.nan])
+ result = union_categoricals([c1, c2], sort_categories=False)
+ expected = Categorical([np.nan, np.nan])
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categoricals_sort_false_empty(self):
+ c1 = Categorical([])
+ c2 = Categorical([])
+ result = union_categoricals([c1, c2], sort_categories=False)
+ expected = Categorical([])
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categoricals_sort_false_ordered_true(self):
+ c1 = Categorical(["b", "a"], categories=["b", "a", "c"], ordered=True)
+ c2 = Categorical(["a", "c"], categories=["b", "a", "c"], ordered=True)
+ result = union_categoricals([c1, c2], sort_categories=False)
+ expected = Categorical(
+ ["b", "a", "a", "c"], categories=["b", "a", "c"], ordered=True
+ )
+ tm.assert_categorical_equal(result, expected)
+
+ def test_union_categorical_unwrap(self):
+ # GH 14173
+ c1 = Categorical(["a", "b"])
+ c2 = Series(["b", "c"], dtype="category")
+ result = union_categoricals([c1, c2])
+ expected = Categorical(["a", "b", "b", "c"])
+ tm.assert_categorical_equal(result, expected)
+
+ c2 = CategoricalIndex(c2)
+ result = union_categoricals([c1, c2])
+ tm.assert_categorical_equal(result, expected)
+
+ c1 = Series(c1)
+ result = union_categoricals([c1, c2])
+ tm.assert_categorical_equal(result, expected)
+
+ msg = "all components to combine must be Categorical"
+ with pytest.raises(TypeError, match=msg):
+ union_categoricals([c1, ["a", "b", "c"]])
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_util.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d0be7464cb3d97697323faef5b4e7cd0d9b6df0
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/reshape/test_util.py
@@ -0,0 +1,79 @@
+import numpy as np
+import pytest
+
+from pandas import (
+ Index,
+ date_range,
+)
+import pandas._testing as tm
+from pandas.core.reshape.util import cartesian_product
+
+
+class TestCartesianProduct:
+ def test_simple(self):
+ x, y = list("ABC"), [1, 22]
+ result1, result2 = cartesian_product([x, y])
+ expected1 = np.array(["A", "A", "B", "B", "C", "C"])
+ expected2 = np.array([1, 22, 1, 22, 1, 22])
+ tm.assert_numpy_array_equal(result1, expected1)
+ tm.assert_numpy_array_equal(result2, expected2)
+
+ def test_datetimeindex(self):
+ # regression test for GitHub issue #6439
+ # make sure that the ordering on datetimeindex is consistent
+ x = date_range("2000-01-01", periods=2)
+ result1, result2 = (Index(y).day for y in cartesian_product([x, x]))
+ expected1 = Index([1, 1, 2, 2], dtype=np.int32)
+ expected2 = Index([1, 2, 1, 2], dtype=np.int32)
+ tm.assert_index_equal(result1, expected1)
+ tm.assert_index_equal(result2, expected2)
+
+ def test_tzaware_retained(self):
+ x = date_range("2000-01-01", periods=2, tz="US/Pacific")
+ y = np.array([3, 4])
+ result1, result2 = cartesian_product([x, y])
+
+ expected = x.repeat(2)
+ tm.assert_index_equal(result1, expected)
+
+ def test_tzaware_retained_categorical(self):
+ x = date_range("2000-01-01", periods=2, tz="US/Pacific").astype("category")
+ y = np.array([3, 4])
+ result1, result2 = cartesian_product([x, y])
+
+ expected = x.repeat(2)
+ tm.assert_index_equal(result1, expected)
+
+ @pytest.mark.parametrize("x, y", [[[], []], [[0, 1], []], [[], ["a", "b", "c"]]])
+ def test_empty(self, x, y):
+ # product of empty factors
+ expected1 = np.array([], dtype=np.asarray(x).dtype)
+ expected2 = np.array([], dtype=np.asarray(y).dtype)
+ result1, result2 = cartesian_product([x, y])
+ tm.assert_numpy_array_equal(result1, expected1)
+ tm.assert_numpy_array_equal(result2, expected2)
+
+ def test_empty_input(self):
+ # empty product (empty input):
+ result = cartesian_product([])
+ expected = []
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "X", [1, [1], [1, 2], [[1], 2], "a", ["a"], ["a", "b"], [["a"], "b"]]
+ )
+ def test_invalid_input(self, X):
+ msg = "Input must be a list-like of list-likes"
+
+ with pytest.raises(TypeError, match=msg):
+ cartesian_product(X=X)
+
+ def test_exceed_product_space(self):
+ # GH31355: raise useful error when produce space is too large
+ msg = "Product space too large to allocate arrays!"
+
+ with pytest.raises(ValueError, match=msg):
+ dims = [np.arange(0, 22, dtype=np.int16) for i in range(12)] + [
+ (np.arange(15128, dtype=np.int16)),
+ ]
+ cartesian_product(X=dims)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/scalar/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/scalar/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/scalar/test_na_scalar.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/scalar/test_na_scalar.py
new file mode 100644
index 0000000000000000000000000000000000000000..287b7557f50f9f6a81763f86d0eb616cfd730f8c
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/scalar/test_na_scalar.py
@@ -0,0 +1,316 @@
+from datetime import (
+ date,
+ time,
+ timedelta,
+)
+import pickle
+
+import numpy as np
+import pytest
+
+from pandas._libs.missing import NA
+
+from pandas.core.dtypes.common import is_scalar
+
+import pandas as pd
+import pandas._testing as tm
+
+
+def test_singleton():
+ assert NA is NA
+ new_NA = type(NA)()
+ assert new_NA is NA
+
+
+def test_repr():
+ assert repr(NA) == ""
+ assert str(NA) == ""
+
+
+def test_format():
+ # GH-34740
+ assert format(NA) == ""
+ assert format(NA, ">10") == " "
+ assert format(NA, "xxx") == "" # NA is flexible, accept any format spec
+
+ assert f"{NA}" == ""
+ assert f"{NA:>10}" == " "
+ assert f"{NA:xxx}" == ""
+
+
+def test_truthiness():
+ msg = "boolean value of NA is ambiguous"
+
+ with pytest.raises(TypeError, match=msg):
+ bool(NA)
+
+ with pytest.raises(TypeError, match=msg):
+ not NA
+
+
+def test_hashable():
+ assert hash(NA) == hash(NA)
+ d = {NA: "test"}
+ assert d[NA] == "test"
+
+
+@pytest.mark.parametrize(
+ "other", [NA, 1, 1.0, "a", b"a", np.int64(1), np.nan], ids=repr
+)
+def test_arithmetic_ops(all_arithmetic_functions, other):
+ op = all_arithmetic_functions
+
+ if op.__name__ in ("pow", "rpow", "rmod") and isinstance(other, (str, bytes)):
+ pytest.skip(reason=f"{op.__name__} with NA and {other} not defined.")
+ if op.__name__ in ("divmod", "rdivmod"):
+ assert op(NA, other) is (NA, NA)
+ else:
+ if op.__name__ == "rpow":
+ # avoid special case
+ other += 1
+ assert op(NA, other) is NA
+
+
+@pytest.mark.parametrize(
+ "other",
+ [
+ NA,
+ 1,
+ 1.0,
+ "a",
+ b"a",
+ np.int64(1),
+ np.nan,
+ np.bool_(True),
+ time(0),
+ date(1, 2, 3),
+ timedelta(1),
+ pd.NaT,
+ ],
+)
+def test_comparison_ops(comparison_op, other):
+ assert comparison_op(NA, other) is NA
+ assert comparison_op(other, NA) is NA
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ 0,
+ 0.0,
+ -0,
+ -0.0,
+ False,
+ np.bool_(False),
+ np.int_(0),
+ np.float64(0),
+ np.int_(-0),
+ np.float64(-0),
+ ],
+)
+@pytest.mark.parametrize("asarray", [True, False])
+def test_pow_special(value, asarray):
+ if asarray:
+ value = np.array([value])
+ result = NA**value
+
+ if asarray:
+ result = result[0]
+ else:
+ # this assertion isn't possible for ndarray.
+ assert isinstance(result, type(value))
+ assert result == 1
+
+
+@pytest.mark.parametrize(
+ "value", [1, 1.0, True, np.bool_(True), np.int_(1), np.float64(1)]
+)
+@pytest.mark.parametrize("asarray", [True, False])
+def test_rpow_special(value, asarray):
+ if asarray:
+ value = np.array([value])
+ result = value**NA
+
+ if asarray:
+ result = result[0]
+ elif not isinstance(value, (np.float64, np.bool_, np.int_)):
+ # this assertion isn't possible with asarray=True
+ assert isinstance(result, type(value))
+
+ assert result == value
+
+
+@pytest.mark.parametrize("value", [-1, -1.0, np.int_(-1), np.float64(-1)])
+@pytest.mark.parametrize("asarray", [True, False])
+def test_rpow_minus_one(value, asarray):
+ if asarray:
+ value = np.array([value])
+ result = value**NA
+
+ if asarray:
+ result = result[0]
+
+ assert pd.isna(result)
+
+
+def test_unary_ops():
+ assert +NA is NA
+ assert -NA is NA
+ assert abs(NA) is NA
+ assert ~NA is NA
+
+
+def test_logical_and():
+ assert NA & True is NA
+ assert True & NA is NA
+ assert NA & False is False
+ assert False & NA is False
+ assert NA & NA is NA
+
+ msg = "unsupported operand type"
+ with pytest.raises(TypeError, match=msg):
+ NA & 5
+
+
+def test_logical_or():
+ assert NA | True is True
+ assert True | NA is True
+ assert NA | False is NA
+ assert False | NA is NA
+ assert NA | NA is NA
+
+ msg = "unsupported operand type"
+ with pytest.raises(TypeError, match=msg):
+ NA | 5
+
+
+def test_logical_xor():
+ assert NA ^ True is NA
+ assert True ^ NA is NA
+ assert NA ^ False is NA
+ assert False ^ NA is NA
+ assert NA ^ NA is NA
+
+ msg = "unsupported operand type"
+ with pytest.raises(TypeError, match=msg):
+ NA ^ 5
+
+
+def test_logical_not():
+ assert ~NA is NA
+
+
+@pytest.mark.parametrize("shape", [(3,), (3, 3), (1, 2, 3)])
+def test_arithmetic_ndarray(shape, all_arithmetic_functions):
+ op = all_arithmetic_functions
+ a = np.zeros(shape)
+ if op.__name__ == "pow":
+ a += 5
+ result = op(NA, a)
+ expected = np.full(a.shape, NA, dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_is_scalar():
+ assert is_scalar(NA) is True
+
+
+def test_isna():
+ assert pd.isna(NA) is True
+ assert pd.notna(NA) is False
+
+
+def test_series_isna():
+ s = pd.Series([1, NA], dtype=object)
+ expected = pd.Series([False, True])
+ tm.assert_series_equal(s.isna(), expected)
+
+
+def test_ufunc():
+ assert np.log(NA) is NA
+ assert np.add(NA, 1) is NA
+ result = np.divmod(NA, 1)
+ assert result[0] is NA and result[1] is NA
+
+ result = np.frexp(NA)
+ assert result[0] is NA and result[1] is NA
+
+
+def test_ufunc_raises():
+ msg = "ufunc method 'at'"
+ with pytest.raises(ValueError, match=msg):
+ np.log.at(NA, 0)
+
+
+def test_binary_input_not_dunder():
+ a = np.array([1, 2, 3])
+ expected = np.array([NA, NA, NA], dtype=object)
+ result = np.logaddexp(a, NA)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = np.logaddexp(NA, a)
+ tm.assert_numpy_array_equal(result, expected)
+
+ # all NA, multiple inputs
+ assert np.logaddexp(NA, NA) is NA
+
+ result = np.modf(NA, NA)
+ assert len(result) == 2
+ assert all(x is NA for x in result)
+
+
+def test_divmod_ufunc():
+ # binary in, binary out.
+ a = np.array([1, 2, 3])
+ expected = np.array([NA, NA, NA], dtype=object)
+
+ result = np.divmod(a, NA)
+ assert isinstance(result, tuple)
+ for arr in result:
+ tm.assert_numpy_array_equal(arr, expected)
+ tm.assert_numpy_array_equal(arr, expected)
+
+ result = np.divmod(NA, a)
+ for arr in result:
+ tm.assert_numpy_array_equal(arr, expected)
+ tm.assert_numpy_array_equal(arr, expected)
+
+
+def test_integer_hash_collision_dict():
+ # GH 30013
+ result = {NA: "foo", hash(NA): "bar"}
+
+ assert result[NA] == "foo"
+ assert result[hash(NA)] == "bar"
+
+
+def test_integer_hash_collision_set():
+ # GH 30013
+ result = {NA, hash(NA)}
+
+ assert len(result) == 2
+ assert NA in result
+ assert hash(NA) in result
+
+
+def test_pickle_roundtrip():
+ # https://github.com/pandas-dev/pandas/issues/31847
+ result = pickle.loads(pickle.dumps(NA))
+ assert result is NA
+
+
+def test_pickle_roundtrip_pandas():
+ result = tm.round_trip_pickle(NA)
+ assert result is NA
+
+
+@pytest.mark.parametrize(
+ "values, dtype", [([1, 2, NA], "Int64"), (["A", "B", NA], "string")]
+)
+@pytest.mark.parametrize("as_frame", [True, False])
+def test_pickle_roundtrip_containers(as_frame, values, dtype):
+ s = pd.Series(pd.array(values, dtype=dtype))
+ if as_frame:
+ s = s.to_frame(name="A")
+ result = tm.round_trip_pickle(s)
+ tm.assert_equal(result, s)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/scalar/test_nat.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/scalar/test_nat.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5a94099523fb264250788fb0d4abaf9057ae60d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/scalar/test_nat.py
@@ -0,0 +1,695 @@
+from datetime import (
+ datetime,
+ timedelta,
+)
+import operator
+
+import numpy as np
+import pytest
+import pytz
+
+from pandas._libs.tslibs import iNaT
+from pandas.compat.numpy import np_version_gte1p24p3
+
+from pandas import (
+ DatetimeIndex,
+ DatetimeTZDtype,
+ Index,
+ NaT,
+ Period,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ Timestamp,
+ isna,
+ offsets,
+)
+import pandas._testing as tm
+from pandas.core import roperator
+from pandas.core.arrays import (
+ DatetimeArray,
+ PeriodArray,
+ TimedeltaArray,
+)
+
+
+@pytest.mark.parametrize(
+ "nat,idx",
+ [
+ (Timestamp("NaT"), DatetimeArray),
+ (Timedelta("NaT"), TimedeltaArray),
+ (Period("NaT", freq="M"), PeriodArray),
+ ],
+)
+def test_nat_fields(nat, idx):
+ for field in idx._field_ops:
+ # weekday is a property of DTI, but a method
+ # on NaT/Timestamp for compat with datetime
+ if field == "weekday":
+ continue
+
+ result = getattr(NaT, field)
+ assert np.isnan(result)
+
+ result = getattr(nat, field)
+ assert np.isnan(result)
+
+ for field in idx._bool_ops:
+ result = getattr(NaT, field)
+ assert result is False
+
+ result = getattr(nat, field)
+ assert result is False
+
+
+def test_nat_vector_field_access():
+ idx = DatetimeIndex(["1/1/2000", None, None, "1/4/2000"])
+
+ for field in DatetimeArray._field_ops:
+ # weekday is a property of DTI, but a method
+ # on NaT/Timestamp for compat with datetime
+ if field == "weekday":
+ continue
+
+ result = getattr(idx, field)
+ expected = Index([getattr(x, field) for x in idx])
+ tm.assert_index_equal(result, expected)
+
+ ser = Series(idx)
+
+ for field in DatetimeArray._field_ops:
+ # weekday is a property of DTI, but a method
+ # on NaT/Timestamp for compat with datetime
+ if field == "weekday":
+ continue
+
+ result = getattr(ser.dt, field)
+ expected = [getattr(x, field) for x in idx]
+ tm.assert_series_equal(result, Series(expected))
+
+ for field in DatetimeArray._bool_ops:
+ result = getattr(ser.dt, field)
+ expected = [getattr(x, field) for x in idx]
+ tm.assert_series_equal(result, Series(expected))
+
+
+@pytest.mark.parametrize("klass", [Timestamp, Timedelta, Period])
+@pytest.mark.parametrize(
+ "value", [None, np.nan, iNaT, float("nan"), NaT, "NaT", "nat", "", "NAT"]
+)
+def test_identity(klass, value):
+ assert klass(value) is NaT
+
+
+@pytest.mark.parametrize("klass", [Timestamp, Timedelta])
+@pytest.mark.parametrize("method", ["round", "floor", "ceil"])
+@pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"])
+def test_round_nat(klass, method, freq):
+ # see gh-14940
+ ts = klass("nat")
+
+ round_method = getattr(ts, method)
+ assert round_method(freq) is ts
+
+
+@pytest.mark.parametrize(
+ "method",
+ [
+ "astimezone",
+ "combine",
+ "ctime",
+ "dst",
+ "fromordinal",
+ "fromtimestamp",
+ "fromisocalendar",
+ "isocalendar",
+ "strftime",
+ "strptime",
+ "time",
+ "timestamp",
+ "timetuple",
+ "timetz",
+ "toordinal",
+ "tzname",
+ "utcfromtimestamp",
+ "utcnow",
+ "utcoffset",
+ "utctimetuple",
+ "timestamp",
+ ],
+)
+def test_nat_methods_raise(method):
+ # see gh-9513, gh-17329
+ msg = f"NaTType does not support {method}"
+
+ with pytest.raises(ValueError, match=msg):
+ getattr(NaT, method)()
+
+
+@pytest.mark.parametrize("method", ["weekday", "isoweekday"])
+def test_nat_methods_nan(method):
+ # see gh-9513, gh-17329
+ assert np.isnan(getattr(NaT, method)())
+
+
+@pytest.mark.parametrize(
+ "method", ["date", "now", "replace", "today", "tz_convert", "tz_localize"]
+)
+def test_nat_methods_nat(method):
+ # see gh-8254, gh-9513, gh-17329
+ assert getattr(NaT, method)() is NaT
+
+
+@pytest.mark.parametrize(
+ "get_nat", [lambda x: NaT, lambda x: Timedelta(x), lambda x: Timestamp(x)]
+)
+def test_nat_iso_format(get_nat):
+ # see gh-12300
+ assert get_nat("NaT").isoformat() == "NaT"
+ assert get_nat("NaT").isoformat(timespec="nanoseconds") == "NaT"
+
+
+@pytest.mark.parametrize(
+ "klass,expected",
+ [
+ (Timestamp, ["normalize", "to_julian_date", "to_period", "unit"]),
+ (
+ Timedelta,
+ [
+ "components",
+ "resolution_string",
+ "to_pytimedelta",
+ "to_timedelta64",
+ "unit",
+ "view",
+ ],
+ ),
+ ],
+)
+def test_missing_public_nat_methods(klass, expected):
+ # see gh-17327
+ #
+ # NaT should have *most* of the Timestamp and Timedelta methods.
+ # Here, we check which public methods NaT does not have. We
+ # ignore any missing private methods.
+ nat_names = dir(NaT)
+ klass_names = dir(klass)
+
+ missing = [x for x in klass_names if x not in nat_names and not x.startswith("_")]
+ missing.sort()
+
+ assert missing == expected
+
+
+def _get_overlap_public_nat_methods(klass, as_tuple=False):
+ """
+ Get overlapping public methods between NaT and another class.
+
+ Parameters
+ ----------
+ klass : type
+ The class to compare with NaT
+ as_tuple : bool, default False
+ Whether to return a list of tuples of the form (klass, method).
+
+ Returns
+ -------
+ overlap : list
+ """
+ nat_names = dir(NaT)
+ klass_names = dir(klass)
+
+ overlap = [
+ x
+ for x in nat_names
+ if x in klass_names and not x.startswith("_") and callable(getattr(klass, x))
+ ]
+
+ # Timestamp takes precedence over Timedelta in terms of overlap.
+ if klass is Timedelta:
+ ts_names = dir(Timestamp)
+ overlap = [x for x in overlap if x not in ts_names]
+
+ if as_tuple:
+ overlap = [(klass, method) for method in overlap]
+
+ overlap.sort()
+ return overlap
+
+
+@pytest.mark.parametrize(
+ "klass,expected",
+ [
+ (
+ Timestamp,
+ [
+ "as_unit",
+ "astimezone",
+ "ceil",
+ "combine",
+ "ctime",
+ "date",
+ "day_name",
+ "dst",
+ "floor",
+ "fromisocalendar",
+ "fromisoformat",
+ "fromordinal",
+ "fromtimestamp",
+ "isocalendar",
+ "isoformat",
+ "isoweekday",
+ "month_name",
+ "now",
+ "replace",
+ "round",
+ "strftime",
+ "strptime",
+ "time",
+ "timestamp",
+ "timetuple",
+ "timetz",
+ "to_datetime64",
+ "to_numpy",
+ "to_pydatetime",
+ "today",
+ "toordinal",
+ "tz_convert",
+ "tz_localize",
+ "tzname",
+ "utcfromtimestamp",
+ "utcnow",
+ "utcoffset",
+ "utctimetuple",
+ "weekday",
+ ],
+ ),
+ (Timedelta, ["total_seconds"]),
+ ],
+)
+def test_overlap_public_nat_methods(klass, expected):
+ # see gh-17327
+ #
+ # NaT should have *most* of the Timestamp and Timedelta methods.
+ # In case when Timestamp, Timedelta, and NaT are overlap, the overlap
+ # is considered to be with Timestamp and NaT, not Timedelta.
+ assert _get_overlap_public_nat_methods(klass) == expected
+
+
+@pytest.mark.parametrize(
+ "compare",
+ (
+ _get_overlap_public_nat_methods(Timestamp, True)
+ + _get_overlap_public_nat_methods(Timedelta, True)
+ ),
+ ids=lambda x: f"{x[0].__name__}.{x[1]}",
+)
+def test_nat_doc_strings(compare):
+ # see gh-17327
+ #
+ # The docstrings for overlapping methods should match.
+ klass, method = compare
+ klass_doc = getattr(klass, method).__doc__
+
+ if klass == Timestamp and method == "isoformat":
+ pytest.skip(
+ "Ignore differences with Timestamp.isoformat() as they're intentional"
+ )
+
+ if method == "to_numpy":
+ # GH#44460 can return either dt64 or td64 depending on dtype,
+ # different docstring is intentional
+ pytest.skip(f"different docstring for {method} is intentional")
+
+ nat_doc = getattr(NaT, method).__doc__
+ assert klass_doc == nat_doc
+
+
+_ops = {
+ "left_plus_right": lambda a, b: a + b,
+ "right_plus_left": lambda a, b: b + a,
+ "left_minus_right": lambda a, b: a - b,
+ "right_minus_left": lambda a, b: b - a,
+ "left_times_right": lambda a, b: a * b,
+ "right_times_left": lambda a, b: b * a,
+ "left_div_right": lambda a, b: a / b,
+ "right_div_left": lambda a, b: b / a,
+}
+
+
+@pytest.mark.parametrize("op_name", list(_ops.keys()))
+@pytest.mark.parametrize(
+ "value,val_type",
+ [
+ (2, "scalar"),
+ (1.5, "floating"),
+ (np.nan, "floating"),
+ ("foo", "str"),
+ (timedelta(3600), "timedelta"),
+ (Timedelta("5s"), "timedelta"),
+ (datetime(2014, 1, 1), "timestamp"),
+ (Timestamp("2014-01-01"), "timestamp"),
+ (Timestamp("2014-01-01", tz="UTC"), "timestamp"),
+ (Timestamp("2014-01-01", tz="US/Eastern"), "timestamp"),
+ (pytz.timezone("Asia/Tokyo").localize(datetime(2014, 1, 1)), "timestamp"),
+ ],
+)
+def test_nat_arithmetic_scalar(op_name, value, val_type):
+ # see gh-6873
+ invalid_ops = {
+ "scalar": {"right_div_left"},
+ "floating": {
+ "right_div_left",
+ "left_minus_right",
+ "right_minus_left",
+ "left_plus_right",
+ "right_plus_left",
+ },
+ "str": set(_ops.keys()),
+ "timedelta": {"left_times_right", "right_times_left"},
+ "timestamp": {
+ "left_times_right",
+ "right_times_left",
+ "left_div_right",
+ "right_div_left",
+ },
+ }
+
+ op = _ops[op_name]
+
+ if op_name in invalid_ops.get(val_type, set()):
+ if (
+ val_type == "timedelta"
+ and "times" in op_name
+ and isinstance(value, Timedelta)
+ ):
+ typs = "(Timedelta|NaTType)"
+ msg = rf"unsupported operand type\(s\) for \*: '{typs}' and '{typs}'"
+ elif val_type == "str":
+ # un-specific check here because the message comes from str
+ # and varies by method
+ msg = "|".join(
+ [
+ "can only concatenate str",
+ "unsupported operand type",
+ "can't multiply sequence",
+ "Can't convert 'NaTType'",
+ "must be str, not NaTType",
+ ]
+ )
+ else:
+ msg = "unsupported operand type"
+
+ with pytest.raises(TypeError, match=msg):
+ op(NaT, value)
+ else:
+ if val_type == "timedelta" and "div" in op_name:
+ expected = np.nan
+ else:
+ expected = NaT
+
+ assert op(NaT, value) is expected
+
+
+@pytest.mark.parametrize(
+ "val,expected", [(np.nan, NaT), (NaT, np.nan), (np.timedelta64("NaT"), np.nan)]
+)
+def test_nat_rfloordiv_timedelta(val, expected):
+ # see gh-#18846
+ #
+ # See also test_timedelta.TestTimedeltaArithmetic.test_floordiv
+ td = Timedelta(hours=3, minutes=4)
+ assert td // val is expected
+
+
+@pytest.mark.parametrize(
+ "op_name",
+ ["left_plus_right", "right_plus_left", "left_minus_right", "right_minus_left"],
+)
+@pytest.mark.parametrize(
+ "value",
+ [
+ DatetimeIndex(["2011-01-01", "2011-01-02"], name="x"),
+ DatetimeIndex(["2011-01-01", "2011-01-02"], tz="US/Eastern", name="x"),
+ DatetimeArray._from_sequence(["2011-01-01", "2011-01-02"]),
+ DatetimeArray._from_sequence(
+ ["2011-01-01", "2011-01-02"], dtype=DatetimeTZDtype(tz="US/Pacific")
+ ),
+ TimedeltaIndex(["1 day", "2 day"], name="x"),
+ ],
+)
+def test_nat_arithmetic_index(op_name, value):
+ # see gh-11718
+ exp_name = "x"
+ exp_data = [NaT] * 2
+
+ if value.dtype.kind == "M" and "plus" in op_name:
+ expected = DatetimeIndex(exp_data, tz=value.tz, name=exp_name)
+ else:
+ expected = TimedeltaIndex(exp_data, name=exp_name)
+
+ if not isinstance(value, Index):
+ expected = expected.array
+
+ op = _ops[op_name]
+ result = op(NaT, value)
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "op_name",
+ ["left_plus_right", "right_plus_left", "left_minus_right", "right_minus_left"],
+)
+@pytest.mark.parametrize("box", [TimedeltaIndex, Series, TimedeltaArray._from_sequence])
+def test_nat_arithmetic_td64_vector(op_name, box):
+ # see gh-19124
+ vec = box(["1 day", "2 day"], dtype="timedelta64[ns]")
+ box_nat = box([NaT, NaT], dtype="timedelta64[ns]")
+ tm.assert_equal(_ops[op_name](vec, NaT), box_nat)
+
+
+@pytest.mark.parametrize(
+ "dtype,op,out_dtype",
+ [
+ ("datetime64[ns]", operator.add, "datetime64[ns]"),
+ ("datetime64[ns]", roperator.radd, "datetime64[ns]"),
+ ("datetime64[ns]", operator.sub, "timedelta64[ns]"),
+ ("datetime64[ns]", roperator.rsub, "timedelta64[ns]"),
+ ("timedelta64[ns]", operator.add, "datetime64[ns]"),
+ ("timedelta64[ns]", roperator.radd, "datetime64[ns]"),
+ ("timedelta64[ns]", operator.sub, "datetime64[ns]"),
+ ("timedelta64[ns]", roperator.rsub, "timedelta64[ns]"),
+ ],
+)
+def test_nat_arithmetic_ndarray(dtype, op, out_dtype):
+ other = np.arange(10).astype(dtype)
+ result = op(NaT, other)
+
+ expected = np.empty(other.shape, dtype=out_dtype)
+ expected.fill("NaT")
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_nat_pinned_docstrings():
+ # see gh-17327
+ assert NaT.ctime.__doc__ == Timestamp.ctime.__doc__
+
+
+def test_to_numpy_alias():
+ # GH 24653: alias .to_numpy() for scalars
+ expected = NaT.to_datetime64()
+ result = NaT.to_numpy()
+
+ assert isna(expected) and isna(result)
+
+ # GH#44460
+ result = NaT.to_numpy("M8[s]")
+ assert isinstance(result, np.datetime64)
+ assert result.dtype == "M8[s]"
+
+ result = NaT.to_numpy("m8[ns]")
+ assert isinstance(result, np.timedelta64)
+ assert result.dtype == "m8[ns]"
+
+ result = NaT.to_numpy("m8[s]")
+ assert isinstance(result, np.timedelta64)
+ assert result.dtype == "m8[s]"
+
+ with pytest.raises(ValueError, match="NaT.to_numpy dtype must be a "):
+ NaT.to_numpy(np.int64)
+
+
+@pytest.mark.parametrize(
+ "other",
+ [
+ Timedelta(0),
+ Timedelta(0).to_pytimedelta(),
+ pytest.param(
+ Timedelta(0).to_timedelta64(),
+ marks=pytest.mark.xfail(
+ not np_version_gte1p24p3,
+ reason="td64 doesn't return NotImplemented, see numpy#17017",
+ ),
+ ),
+ Timestamp(0),
+ Timestamp(0).to_pydatetime(),
+ pytest.param(
+ Timestamp(0).to_datetime64(),
+ marks=pytest.mark.xfail(
+ not np_version_gte1p24p3,
+ reason="dt64 doesn't return NotImplemented, see numpy#17017",
+ ),
+ ),
+ Timestamp(0).tz_localize("UTC"),
+ NaT,
+ ],
+)
+def test_nat_comparisons(compare_operators_no_eq_ne, other):
+ # GH 26039
+ opname = compare_operators_no_eq_ne
+
+ assert getattr(NaT, opname)(other) is False
+
+ op = getattr(operator, opname.strip("_"))
+ assert op(NaT, other) is False
+ assert op(other, NaT) is False
+
+
+@pytest.mark.parametrize("other", [np.timedelta64(0, "ns"), np.datetime64("now", "ns")])
+def test_nat_comparisons_numpy(other):
+ # Once numpy#17017 is fixed and the xfailed cases in test_nat_comparisons
+ # pass, this test can be removed
+ assert not NaT == other
+ assert NaT != other
+ assert not NaT < other
+ assert not NaT > other
+ assert not NaT <= other
+ assert not NaT >= other
+
+
+@pytest.mark.parametrize("other_and_type", [("foo", "str"), (2, "int"), (2.0, "float")])
+@pytest.mark.parametrize(
+ "symbol_and_op",
+ [("<=", operator.le), ("<", operator.lt), (">=", operator.ge), (">", operator.gt)],
+)
+def test_nat_comparisons_invalid(other_and_type, symbol_and_op):
+ # GH#35585
+ other, other_type = other_and_type
+ symbol, op = symbol_and_op
+
+ assert not NaT == other
+ assert not other == NaT
+
+ assert NaT != other
+ assert other != NaT
+
+ msg = f"'{symbol}' not supported between instances of 'NaTType' and '{other_type}'"
+ with pytest.raises(TypeError, match=msg):
+ op(NaT, other)
+
+ msg = f"'{symbol}' not supported between instances of '{other_type}' and 'NaTType'"
+ with pytest.raises(TypeError, match=msg):
+ op(other, NaT)
+
+
+@pytest.mark.parametrize(
+ "other",
+ [
+ np.array(["foo"] * 2, dtype=object),
+ np.array([2, 3], dtype="int64"),
+ np.array([2.0, 3.5], dtype="float64"),
+ ],
+ ids=["str", "int", "float"],
+)
+def test_nat_comparisons_invalid_ndarray(other):
+ # GH#40722
+ expected = np.array([False, False])
+ result = NaT == other
+ tm.assert_numpy_array_equal(result, expected)
+ result = other == NaT
+ tm.assert_numpy_array_equal(result, expected)
+
+ expected = np.array([True, True])
+ result = NaT != other
+ tm.assert_numpy_array_equal(result, expected)
+ result = other != NaT
+ tm.assert_numpy_array_equal(result, expected)
+
+ for symbol, op in [
+ ("<=", operator.le),
+ ("<", operator.lt),
+ (">=", operator.ge),
+ (">", operator.gt),
+ ]:
+ msg = f"'{symbol}' not supported between"
+
+ with pytest.raises(TypeError, match=msg):
+ op(NaT, other)
+
+ if other.dtype == np.dtype("object"):
+ # uses the reverse operator, so symbol changes
+ msg = None
+ with pytest.raises(TypeError, match=msg):
+ op(other, NaT)
+
+
+def test_compare_date(fixed_now_ts):
+ # GH#39151 comparing NaT with date object is deprecated
+ # See also: tests.scalar.timestamps.test_comparisons::test_compare_date
+
+ dt = fixed_now_ts.to_pydatetime().date()
+
+ msg = "Cannot compare NaT with datetime.date object"
+ for left, right in [(NaT, dt), (dt, NaT)]:
+ assert not left == right
+ assert left != right
+
+ with pytest.raises(TypeError, match=msg):
+ left < right
+ with pytest.raises(TypeError, match=msg):
+ left <= right
+ with pytest.raises(TypeError, match=msg):
+ left > right
+ with pytest.raises(TypeError, match=msg):
+ left >= right
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ offsets.YearEnd(2),
+ offsets.YearBegin(2),
+ offsets.MonthBegin(1),
+ offsets.MonthEnd(2),
+ offsets.MonthEnd(12),
+ offsets.Day(2),
+ offsets.Day(5),
+ offsets.Hour(24),
+ offsets.Hour(3),
+ offsets.Minute(),
+ np.timedelta64(3, "h"),
+ np.timedelta64(4, "h"),
+ np.timedelta64(3200, "s"),
+ np.timedelta64(3600, "s"),
+ np.timedelta64(3600 * 24, "s"),
+ np.timedelta64(2, "D"),
+ np.timedelta64(365, "D"),
+ timedelta(-2),
+ timedelta(365),
+ timedelta(minutes=120),
+ timedelta(days=4, minutes=180),
+ timedelta(hours=23),
+ timedelta(hours=23, minutes=30),
+ timedelta(hours=48),
+ ],
+)
+def test_nat_addsub_tdlike_scalar(obj):
+ assert NaT + obj is NaT
+ assert obj + NaT is NaT
+ assert NaT - obj is NaT
+
+
+def test_pickle():
+ # GH#4606
+ p = tm.round_trip_pickle(NaT)
+ assert p is NaT
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_api.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..be63d9500ce732ae7eafaf06c184f7004ad92923
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_api.py
@@ -0,0 +1,296 @@
+import inspect
+import pydoc
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ date_range,
+)
+import pandas._testing as tm
+
+
+class TestSeriesMisc:
+ def test_tab_completion(self):
+ # GH 9910
+ s = Series(list("abcd"))
+ # Series of str values should have .str but not .dt/.cat in __dir__
+ assert "str" in dir(s)
+ assert "dt" not in dir(s)
+ assert "cat" not in dir(s)
+
+ def test_tab_completion_dt(self):
+ # similarly for .dt
+ s = Series(date_range("1/1/2015", periods=5))
+ assert "dt" in dir(s)
+ assert "str" not in dir(s)
+ assert "cat" not in dir(s)
+
+ def test_tab_completion_cat(self):
+ # Similarly for .cat, but with the twist that str and dt should be
+ # there if the categories are of that type first cat and str.
+ s = Series(list("abbcd"), dtype="category")
+ assert "cat" in dir(s)
+ assert "str" in dir(s) # as it is a string categorical
+ assert "dt" not in dir(s)
+
+ def test_tab_completion_cat_str(self):
+ # similar to cat and str
+ s = Series(date_range("1/1/2015", periods=5)).astype("category")
+ assert "cat" in dir(s)
+ assert "str" not in dir(s)
+ assert "dt" in dir(s) # as it is a datetime categorical
+
+ def test_tab_completion_with_categorical(self):
+ # test the tab completion display
+ ok_for_cat = [
+ "categories",
+ "codes",
+ "ordered",
+ "set_categories",
+ "add_categories",
+ "remove_categories",
+ "rename_categories",
+ "reorder_categories",
+ "remove_unused_categories",
+ "as_ordered",
+ "as_unordered",
+ ]
+
+ s = Series(list("aabbcde")).astype("category")
+ results = sorted({r for r in s.cat.__dir__() if not r.startswith("_")})
+ tm.assert_almost_equal(results, sorted(set(ok_for_cat)))
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ tm.makeStringIndex(10),
+ tm.makeCategoricalIndex(10),
+ Index(["foo", "bar", "baz"] * 2),
+ tm.makeDateIndex(10),
+ tm.makePeriodIndex(10),
+ tm.makeTimedeltaIndex(10),
+ tm.makeIntIndex(10),
+ tm.makeUIntIndex(10),
+ tm.makeIntIndex(10),
+ tm.makeFloatIndex(10),
+ Index([True, False]),
+ Index([f"a{i}" for i in range(101)]),
+ pd.MultiIndex.from_tuples(zip("ABCD", "EFGH")),
+ pd.MultiIndex.from_tuples(zip([0, 1, 2, 3], "EFGH")),
+ ],
+ )
+ def test_index_tab_completion(self, index):
+ # dir contains string-like values of the Index.
+ s = Series(index=index, dtype=object)
+ dir_s = dir(s)
+ for i, x in enumerate(s.index.unique(level=0)):
+ if i < 100:
+ assert not isinstance(x, str) or not x.isidentifier() or x in dir_s
+ else:
+ assert x not in dir_s
+
+ @pytest.mark.parametrize("ser", [Series(dtype=object), Series([1])])
+ def test_not_hashable(self, ser):
+ msg = "unhashable type: 'Series'"
+ with pytest.raises(TypeError, match=msg):
+ hash(ser)
+
+ def test_contains(self, datetime_series):
+ tm.assert_contains_all(datetime_series.index, datetime_series)
+
+ def test_axis_alias(self):
+ s = Series([1, 2, np.nan])
+ tm.assert_series_equal(s.dropna(axis="rows"), s.dropna(axis="index"))
+ assert s.dropna().sum("rows") == 3
+ assert s._get_axis_number("rows") == 0
+ assert s._get_axis_name("rows") == "index"
+
+ def test_class_axis(self):
+ # https://github.com/pandas-dev/pandas/issues/18147
+ # no exception and no empty docstring
+ assert pydoc.getdoc(Series.index)
+
+ def test_ndarray_compat(self):
+ # test numpy compat with Series as sub-class of NDFrame
+ tsdf = DataFrame(
+ np.random.default_rng(2).standard_normal((1000, 3)),
+ columns=["A", "B", "C"],
+ index=date_range("1/1/2000", periods=1000),
+ )
+
+ def f(x):
+ return x[x.idxmax()]
+
+ result = tsdf.apply(f)
+ expected = tsdf.max()
+ tm.assert_series_equal(result, expected)
+
+ def test_ndarray_compat_like_func(self):
+ # using an ndarray like function
+ s = Series(np.random.default_rng(2).standard_normal(10))
+ result = Series(np.ones_like(s))
+ expected = Series(1, index=range(10), dtype="float64")
+ tm.assert_series_equal(result, expected)
+
+ def test_ndarray_compat_ravel(self):
+ # ravel
+ s = Series(np.random.default_rng(2).standard_normal(10))
+ tm.assert_almost_equal(s.ravel(order="F"), s.values.ravel(order="F"))
+
+ def test_empty_method(self):
+ s_empty = Series(dtype=object)
+ assert s_empty.empty
+
+ @pytest.mark.parametrize("dtype", ["int64", object])
+ def test_empty_method_full_series(self, dtype):
+ full_series = Series(index=[1], dtype=dtype)
+ assert not full_series.empty
+
+ @pytest.mark.parametrize("dtype", [None, "Int64"])
+ def test_integer_series_size(self, dtype):
+ # GH 25580
+ s = Series(range(9), dtype=dtype)
+ assert s.size == 9
+
+ def test_attrs(self):
+ s = Series([0, 1], name="abc")
+ assert s.attrs == {}
+ s.attrs["version"] = 1
+ result = s + 1
+ assert result.attrs == {"version": 1}
+
+ def test_inspect_getmembers(self):
+ # GH38782
+ pytest.importorskip("jinja2")
+ ser = Series(dtype=object)
+ msg = "Series._data is deprecated"
+ with tm.assert_produces_warning(
+ DeprecationWarning, match=msg, check_stacklevel=False
+ ):
+ inspect.getmembers(ser)
+
+ def test_unknown_attribute(self):
+ # GH#9680
+ tdi = pd.timedelta_range(start=0, periods=10, freq="1s")
+ ser = Series(np.random.default_rng(2).normal(size=10), index=tdi)
+ assert "foo" not in ser.__dict__
+ msg = "'Series' object has no attribute 'foo'"
+ with pytest.raises(AttributeError, match=msg):
+ ser.foo
+
+ @pytest.mark.parametrize("op", ["year", "day", "second", "weekday"])
+ def test_datetime_series_no_datelike_attrs(self, op, datetime_series):
+ # GH#7206
+ msg = f"'Series' object has no attribute '{op}'"
+ with pytest.raises(AttributeError, match=msg):
+ getattr(datetime_series, op)
+
+ def test_series_datetimelike_attribute_access(self):
+ # attribute access should still work!
+ ser = Series({"year": 2000, "month": 1, "day": 10})
+ assert ser.year == 2000
+ assert ser.month == 1
+ assert ser.day == 10
+
+ def test_series_datetimelike_attribute_access_invalid(self):
+ ser = Series({"year": 2000, "month": 1, "day": 10})
+ msg = "'Series' object has no attribute 'weekday'"
+ with pytest.raises(AttributeError, match=msg):
+ ser.weekday
+
+ @pytest.mark.parametrize(
+ "kernel, has_numeric_only",
+ [
+ ("skew", True),
+ ("var", True),
+ ("all", False),
+ ("prod", True),
+ ("any", False),
+ ("idxmin", False),
+ ("quantile", False),
+ ("idxmax", False),
+ ("min", True),
+ ("sem", True),
+ ("mean", True),
+ ("nunique", False),
+ ("max", True),
+ ("sum", True),
+ ("count", False),
+ ("median", True),
+ ("std", True),
+ ("backfill", False),
+ ("rank", True),
+ ("pct_change", False),
+ ("cummax", False),
+ ("shift", False),
+ ("diff", False),
+ ("cumsum", False),
+ ("cummin", False),
+ ("cumprod", False),
+ ("fillna", False),
+ ("ffill", False),
+ ("pad", False),
+ ("bfill", False),
+ ("sample", False),
+ ("tail", False),
+ ("take", False),
+ ("head", False),
+ ("cov", False),
+ ("corr", False),
+ ],
+ )
+ @pytest.mark.parametrize("dtype", [bool, int, float, object])
+ def test_numeric_only(self, kernel, has_numeric_only, dtype):
+ # GH#47500
+ ser = Series([0, 1, 1], dtype=dtype)
+ if kernel == "corrwith":
+ args = (ser,)
+ elif kernel == "corr":
+ args = (ser,)
+ elif kernel == "cov":
+ args = (ser,)
+ elif kernel == "nth":
+ args = (0,)
+ elif kernel == "fillna":
+ args = (True,)
+ elif kernel == "fillna":
+ args = ("ffill",)
+ elif kernel == "take":
+ args = ([0],)
+ elif kernel == "quantile":
+ args = (0.5,)
+ else:
+ args = ()
+ method = getattr(ser, kernel)
+ if not has_numeric_only:
+ msg = (
+ "(got an unexpected keyword argument 'numeric_only'"
+ "|too many arguments passed in)"
+ )
+ with pytest.raises(TypeError, match=msg):
+ method(*args, numeric_only=True)
+ elif dtype is object:
+ msg = f"Series.{kernel} does not allow numeric_only=True with non-numeric"
+ with pytest.raises(TypeError, match=msg):
+ method(*args, numeric_only=True)
+ else:
+ result = method(*args, numeric_only=True)
+ expected = method(*args, numeric_only=False)
+ if isinstance(expected, Series):
+ # transformer
+ tm.assert_series_equal(result, expected)
+ else:
+ # reducer
+ assert result == expected
+
+
+@pytest.mark.parametrize("converter", [int, float, complex])
+def test_float_int_deprecated(converter):
+ # GH 51101
+ with tm.assert_produces_warning(FutureWarning):
+ assert converter(Series([1])) == converter(1)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_arithmetic.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_arithmetic.py
new file mode 100644
index 0000000000000000000000000000000000000000..80fd2fd7c0a064b9958f96c9522370371d3f870d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_arithmetic.py
@@ -0,0 +1,955 @@
+from datetime import (
+ date,
+ timedelta,
+ timezone,
+)
+from decimal import Decimal
+import operator
+
+import numpy as np
+import pytest
+
+from pandas._libs import lib
+from pandas._libs.tslibs import IncompatibleFrequency
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DatetimeTZDtype,
+ Index,
+ Series,
+ Timedelta,
+ bdate_range,
+ date_range,
+ isna,
+)
+import pandas._testing as tm
+from pandas.core import ops
+from pandas.core.computation import expressions as expr
+from pandas.core.computation.check import NUMEXPR_INSTALLED
+
+
+@pytest.fixture(autouse=True, params=[0, 1000000], ids=["numexpr", "python"])
+def switch_numexpr_min_elements(request):
+ _MIN_ELEMENTS = expr._MIN_ELEMENTS
+ expr._MIN_ELEMENTS = request.param
+ yield request.param
+ expr._MIN_ELEMENTS = _MIN_ELEMENTS
+
+
+def _permute(obj):
+ return obj.take(np.random.default_rng(2).permutation(len(obj)))
+
+
+class TestSeriesFlexArithmetic:
+ @pytest.mark.parametrize(
+ "ts",
+ [
+ (lambda x: x, lambda x: x * 2, False),
+ (lambda x: x, lambda x: x[::2], False),
+ (lambda x: x, lambda x: 5, True),
+ (lambda x: tm.makeFloatSeries(), lambda x: tm.makeFloatSeries(), True),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "opname", ["add", "sub", "mul", "floordiv", "truediv", "pow"]
+ )
+ def test_flex_method_equivalence(self, opname, ts):
+ # check that Series.{opname} behaves like Series.__{opname}__,
+ tser = tm.makeTimeSeries().rename("ts")
+
+ series = ts[0](tser)
+ other = ts[1](tser)
+ check_reverse = ts[2]
+
+ op = getattr(Series, opname)
+ alt = getattr(operator, opname)
+
+ result = op(series, other)
+ expected = alt(series, other)
+ tm.assert_almost_equal(result, expected)
+ if check_reverse:
+ rop = getattr(Series, "r" + opname)
+ result = rop(series, other)
+ expected = alt(other, series)
+ tm.assert_almost_equal(result, expected)
+
+ def test_flex_method_subclass_metadata_preservation(self, all_arithmetic_operators):
+ # GH 13208
+ class MySeries(Series):
+ _metadata = ["x"]
+
+ @property
+ def _constructor(self):
+ return MySeries
+
+ opname = all_arithmetic_operators
+ op = getattr(Series, opname)
+ m = MySeries([1, 2, 3], name="test")
+ m.x = 42
+ result = op(m, 1)
+ assert result.x == 42
+
+ def test_flex_add_scalar_fill_value(self):
+ # GH12723
+ ser = Series([0, 1, np.nan, 3, 4, 5])
+
+ exp = ser.fillna(0).add(2)
+ res = ser.add(2, fill_value=0)
+ tm.assert_series_equal(res, exp)
+
+ pairings = [(Series.div, operator.truediv, 1), (Series.rdiv, ops.rtruediv, 1)]
+ for op in ["add", "sub", "mul", "pow", "truediv", "floordiv"]:
+ fv = 0
+ lop = getattr(Series, op)
+ lequiv = getattr(operator, op)
+ rop = getattr(Series, "r" + op)
+ # bind op at definition time...
+ requiv = lambda x, y, op=op: getattr(operator, op)(y, x)
+ pairings.append((lop, lequiv, fv))
+ pairings.append((rop, requiv, fv))
+
+ @pytest.mark.parametrize("op, equiv_op, fv", pairings)
+ def test_operators_combine(self, op, equiv_op, fv):
+ def _check_fill(meth, op, a, b, fill_value=0):
+ exp_index = a.index.union(b.index)
+ a = a.reindex(exp_index)
+ b = b.reindex(exp_index)
+
+ amask = isna(a)
+ bmask = isna(b)
+
+ exp_values = []
+ for i in range(len(exp_index)):
+ with np.errstate(all="ignore"):
+ if amask[i]:
+ if bmask[i]:
+ exp_values.append(np.nan)
+ continue
+ exp_values.append(op(fill_value, b[i]))
+ elif bmask[i]:
+ if amask[i]:
+ exp_values.append(np.nan)
+ continue
+ exp_values.append(op(a[i], fill_value))
+ else:
+ exp_values.append(op(a[i], b[i]))
+
+ result = meth(a, b, fill_value=fill_value)
+ expected = Series(exp_values, exp_index)
+ tm.assert_series_equal(result, expected)
+
+ a = Series([np.nan, 1.0, 2.0, 3.0, np.nan], index=np.arange(5))
+ b = Series([np.nan, 1, np.nan, 3, np.nan, 4.0], index=np.arange(6))
+
+ result = op(a, b)
+ exp = equiv_op(a, b)
+ tm.assert_series_equal(result, exp)
+ _check_fill(op, equiv_op, a, b, fill_value=fv)
+ # should accept axis=0 or axis='rows'
+ op(a, b, axis=0)
+
+
+class TestSeriesArithmetic:
+ # Some of these may end up in tests/arithmetic, but are not yet sorted
+
+ def test_add_series_with_period_index(self):
+ rng = pd.period_range("1/1/2000", "1/1/2010", freq="A")
+ ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ result = ts + ts[::2]
+ expected = ts + ts
+ expected.iloc[1::2] = np.nan
+ tm.assert_series_equal(result, expected)
+
+ result = ts + _permute(ts[::2])
+ tm.assert_series_equal(result, expected)
+
+ msg = "Input has different freq=D from Period\\(freq=A-DEC\\)"
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ ts + ts.asfreq("D", how="end")
+
+ @pytest.mark.parametrize(
+ "target_add,input_value,expected_value",
+ [
+ ("!", ["hello", "world"], ["hello!", "world!"]),
+ ("m", ["hello", "world"], ["hellom", "worldm"]),
+ ],
+ )
+ def test_string_addition(self, target_add, input_value, expected_value):
+ # GH28658 - ensure adding 'm' does not raise an error
+ a = Series(input_value)
+
+ result = a + target_add
+ expected = Series(expected_value)
+ tm.assert_series_equal(result, expected)
+
+ def test_divmod(self):
+ # GH#25557
+ a = Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"])
+ b = Series([2, np.nan, 1, np.nan], index=["a", "b", "d", "e"])
+
+ result = a.divmod(b)
+ expected = divmod(a, b)
+ tm.assert_series_equal(result[0], expected[0])
+ tm.assert_series_equal(result[1], expected[1])
+
+ result = a.rdivmod(b)
+ expected = divmod(b, a)
+ tm.assert_series_equal(result[0], expected[0])
+ tm.assert_series_equal(result[1], expected[1])
+
+ @pytest.mark.parametrize("index", [None, range(9)])
+ def test_series_integer_mod(self, index):
+ # GH#24396
+ s1 = Series(range(1, 10))
+ s2 = Series("foo", index=index)
+
+ msg = "not all arguments converted during string formatting"
+
+ with pytest.raises(TypeError, match=msg):
+ s2 % s1
+
+ def test_add_with_duplicate_index(self):
+ # GH14227
+ s1 = Series([1, 2], index=[1, 1])
+ s2 = Series([10, 10], index=[1, 2])
+ result = s1 + s2
+ expected = Series([11, 12, np.nan], index=[1, 1, 2])
+ tm.assert_series_equal(result, expected)
+
+ def test_add_na_handling(self):
+ ser = Series(
+ [Decimal("1.3"), Decimal("2.3")], index=[date(2012, 1, 1), date(2012, 1, 2)]
+ )
+
+ result = ser + ser.shift(1)
+ result2 = ser.shift(1) + ser
+ assert isna(result.iloc[0])
+ assert isna(result2.iloc[0])
+
+ def test_add_corner_cases(self, datetime_series):
+ empty = Series([], index=Index([]), dtype=np.float64)
+
+ result = datetime_series + empty
+ assert np.isnan(result).all()
+
+ result = empty + empty.copy()
+ assert len(result) == 0
+
+ def test_add_float_plus_int(self, datetime_series):
+ # float + int
+ int_ts = datetime_series.astype(int)[:-5]
+ added = datetime_series + int_ts
+ expected = Series(
+ datetime_series.values[:-5] + int_ts.values,
+ index=datetime_series.index[:-5],
+ name="ts",
+ )
+ tm.assert_series_equal(added[:-5], expected)
+
+ def test_mul_empty_int_corner_case(self):
+ s1 = Series([], [], dtype=np.int32)
+ s2 = Series({"x": 0.0})
+ tm.assert_series_equal(s1 * s2, Series([np.nan], index=["x"]))
+
+ def test_sub_datetimelike_align(self):
+ # GH#7500
+ # datetimelike ops need to align
+ dt = Series(date_range("2012-1-1", periods=3, freq="D"))
+ dt.iloc[2] = np.nan
+ dt2 = dt[::-1]
+
+ expected = Series([timedelta(0), timedelta(0), pd.NaT])
+ # name is reset
+ result = dt2 - dt
+ tm.assert_series_equal(result, expected)
+
+ expected = Series(expected, name=0)
+ result = (dt2.to_frame() - dt.to_frame())[0]
+ tm.assert_series_equal(result, expected)
+
+ def test_alignment_doesnt_change_tz(self):
+ # GH#33671
+ dti = date_range("2016-01-01", periods=10, tz="CET")
+ dti_utc = dti.tz_convert("UTC")
+ ser = Series(10, index=dti)
+ ser_utc = Series(10, index=dti_utc)
+
+ # we don't care about the result, just that original indexes are unchanged
+ ser * ser_utc
+
+ assert ser.index is dti
+ assert ser_utc.index is dti_utc
+
+ def test_alignment_categorical(self):
+ # GH13365
+ cat = Categorical(["3z53", "3z53", "LoJG", "LoJG", "LoJG", "N503"])
+ ser1 = Series(2, index=cat)
+ ser2 = Series(2, index=cat[:-1])
+ result = ser1 * ser2
+
+ exp_index = ["3z53"] * 4 + ["LoJG"] * 9 + ["N503"]
+ exp_index = pd.CategoricalIndex(exp_index, categories=cat.categories)
+ exp_values = [4.0] * 13 + [np.nan]
+ expected = Series(exp_values, exp_index)
+
+ tm.assert_series_equal(result, expected)
+
+ def test_arithmetic_with_duplicate_index(self):
+ # GH#8363
+ # integer ops with a non-unique index
+ index = [2, 2, 3, 3, 4]
+ ser = Series(np.arange(1, 6, dtype="int64"), index=index)
+ other = Series(np.arange(5, dtype="int64"), index=index)
+ result = ser - other
+ expected = Series(1, index=[2, 2, 3, 3, 4])
+ tm.assert_series_equal(result, expected)
+
+ # GH#8363
+ # datetime ops with a non-unique index
+ ser = Series(date_range("20130101 09:00:00", periods=5), index=index)
+ other = Series(date_range("20130101", periods=5), index=index)
+ result = ser - other
+ expected = Series(Timedelta("9 hours"), index=[2, 2, 3, 3, 4])
+ tm.assert_series_equal(result, expected)
+
+ def test_masked_and_non_masked_propagate_na(self):
+ # GH#45810
+ ser1 = Series([0, np.nan], dtype="float")
+ ser2 = Series([0, 1], dtype="Int64")
+ result = ser1 * ser2
+ expected = Series([0, pd.NA], dtype="Float64")
+ tm.assert_series_equal(result, expected)
+
+ def test_mask_div_propagate_na_for_non_na_dtype(self):
+ # GH#42630
+ ser1 = Series([15, pd.NA, 5, 4], dtype="Int64")
+ ser2 = Series([15, 5, np.nan, 4])
+ result = ser1 / ser2
+ expected = Series([1.0, pd.NA, pd.NA, 1.0], dtype="Float64")
+ tm.assert_series_equal(result, expected)
+
+ result = ser2 / ser1
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("val, dtype", [(3, "Int64"), (3.5, "Float64")])
+ def test_add_list_to_masked_array(self, val, dtype):
+ # GH#22962
+ ser = Series([1, None, 3], dtype="Int64")
+ result = ser + [1, None, val]
+ expected = Series([2, None, 3 + val], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+ result = [1, None, val] + ser
+ tm.assert_series_equal(result, expected)
+
+ def test_add_list_to_masked_array_boolean(self, request):
+ # GH#22962
+ warning = (
+ UserWarning
+ if request.node.callspec.id == "numexpr" and NUMEXPR_INSTALLED
+ else None
+ )
+ ser = Series([True, None, False], dtype="boolean")
+ with tm.assert_produces_warning(warning):
+ result = ser + [True, None, True]
+ expected = Series([True, None, True], dtype="boolean")
+ tm.assert_series_equal(result, expected)
+
+ with tm.assert_produces_warning(warning):
+ result = [True, None, True] + ser
+ tm.assert_series_equal(result, expected)
+
+
+# ------------------------------------------------------------------
+# Comparisons
+
+
+class TestSeriesFlexComparison:
+ @pytest.mark.parametrize("axis", [0, None, "index"])
+ def test_comparison_flex_basic(self, axis, comparison_op):
+ left = Series(np.random.default_rng(2).standard_normal(10))
+ right = Series(np.random.default_rng(2).standard_normal(10))
+ result = getattr(left, comparison_op.__name__)(right, axis=axis)
+ expected = comparison_op(left, right)
+ tm.assert_series_equal(result, expected)
+
+ def test_comparison_bad_axis(self, comparison_op):
+ left = Series(np.random.default_rng(2).standard_normal(10))
+ right = Series(np.random.default_rng(2).standard_normal(10))
+
+ msg = "No axis named 1 for object type"
+ with pytest.raises(ValueError, match=msg):
+ getattr(left, comparison_op.__name__)(right, axis=1)
+
+ @pytest.mark.parametrize(
+ "values, op",
+ [
+ ([False, False, True, False], "eq"),
+ ([True, True, False, True], "ne"),
+ ([False, False, True, False], "le"),
+ ([False, False, False, False], "lt"),
+ ([False, True, True, False], "ge"),
+ ([False, True, False, False], "gt"),
+ ],
+ )
+ def test_comparison_flex_alignment(self, values, op):
+ left = Series([1, 3, 2], index=list("abc"))
+ right = Series([2, 2, 2], index=list("bcd"))
+ result = getattr(left, op)(right)
+ expected = Series(values, index=list("abcd"))
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "values, op, fill_value",
+ [
+ ([False, False, True, True], "eq", 2),
+ ([True, True, False, False], "ne", 2),
+ ([False, False, True, True], "le", 0),
+ ([False, False, False, True], "lt", 0),
+ ([True, True, True, False], "ge", 0),
+ ([True, True, False, False], "gt", 0),
+ ],
+ )
+ def test_comparison_flex_alignment_fill(self, values, op, fill_value):
+ left = Series([1, 3, 2], index=list("abc"))
+ right = Series([2, 2, 2], index=list("bcd"))
+ result = getattr(left, op)(right, fill_value=fill_value)
+ expected = Series(values, index=list("abcd"))
+ tm.assert_series_equal(result, expected)
+
+
+class TestSeriesComparison:
+ def test_comparison_different_length(self):
+ a = Series(["a", "b", "c"])
+ b = Series(["b", "a"])
+ msg = "only compare identically-labeled Series"
+ with pytest.raises(ValueError, match=msg):
+ a < b
+
+ a = Series([1, 2])
+ b = Series([2, 3, 4])
+ with pytest.raises(ValueError, match=msg):
+ a == b
+
+ @pytest.mark.parametrize("opname", ["eq", "ne", "gt", "lt", "ge", "le"])
+ def test_ser_flex_cmp_return_dtypes(self, opname):
+ # GH#15115
+ ser = Series([1, 3, 2], index=range(3))
+ const = 2
+ result = getattr(ser, opname)(const).dtypes
+ expected = np.dtype("bool")
+ assert result == expected
+
+ @pytest.mark.parametrize("opname", ["eq", "ne", "gt", "lt", "ge", "le"])
+ def test_ser_flex_cmp_return_dtypes_empty(self, opname):
+ # GH#15115 empty Series case
+ ser = Series([1, 3, 2], index=range(3))
+ empty = ser.iloc[:0]
+ const = 2
+ result = getattr(empty, opname)(const).dtypes
+ expected = np.dtype("bool")
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "names", [(None, None, None), ("foo", "bar", None), ("baz", "baz", "baz")]
+ )
+ def test_ser_cmp_result_names(self, names, comparison_op):
+ # datetime64 dtype
+ op = comparison_op
+ dti = date_range("1949-06-07 03:00:00", freq="H", periods=5, name=names[0])
+ ser = Series(dti).rename(names[1])
+ result = op(ser, dti)
+ assert result.name == names[2]
+
+ # datetime64tz dtype
+ dti = dti.tz_localize("US/Central")
+ dti = pd.DatetimeIndex(dti, freq="infer") # freq not preserved by tz_localize
+ ser = Series(dti).rename(names[1])
+ result = op(ser, dti)
+ assert result.name == names[2]
+
+ # timedelta64 dtype
+ tdi = dti - dti.shift(1)
+ ser = Series(tdi).rename(names[1])
+ result = op(ser, tdi)
+ assert result.name == names[2]
+
+ # interval dtype
+ if op in [operator.eq, operator.ne]:
+ # interval dtype comparisons not yet implemented
+ ii = pd.interval_range(start=0, periods=5, name=names[0])
+ ser = Series(ii).rename(names[1])
+ result = op(ser, ii)
+ assert result.name == names[2]
+
+ # categorical
+ if op in [operator.eq, operator.ne]:
+ # categorical dtype comparisons raise for inequalities
+ cidx = tdi.astype("category")
+ ser = Series(cidx).rename(names[1])
+ result = op(ser, cidx)
+ assert result.name == names[2]
+
+ def test_comparisons(self):
+ s = Series(["a", "b", "c"])
+ s2 = Series([False, True, False])
+
+ # it works!
+ exp = Series([False, False, False])
+ tm.assert_series_equal(s == s2, exp)
+ tm.assert_series_equal(s2 == s, exp)
+
+ # -----------------------------------------------------------------
+ # Categorical Dtype Comparisons
+
+ def test_categorical_comparisons(self):
+ # GH#8938
+ # allow equality comparisons
+ a = Series(list("abc"), dtype="category")
+ b = Series(list("abc"), dtype="object")
+ c = Series(["a", "b", "cc"], dtype="object")
+ d = Series(list("acb"), dtype="object")
+ e = Categorical(list("abc"))
+ f = Categorical(list("acb"))
+
+ # vs scalar
+ assert not (a == "a").all()
+ assert ((a != "a") == ~(a == "a")).all()
+
+ assert not ("a" == a).all()
+ assert (a == "a")[0]
+ assert ("a" == a)[0]
+ assert not ("a" != a)[0]
+
+ # vs list-like
+ assert (a == a).all()
+ assert not (a != a).all()
+
+ assert (a == list(a)).all()
+ assert (a == b).all()
+ assert (b == a).all()
+ assert ((~(a == b)) == (a != b)).all()
+ assert ((~(b == a)) == (b != a)).all()
+
+ assert not (a == c).all()
+ assert not (c == a).all()
+ assert not (a == d).all()
+ assert not (d == a).all()
+
+ # vs a cat-like
+ assert (a == e).all()
+ assert (e == a).all()
+ assert not (a == f).all()
+ assert not (f == a).all()
+
+ assert (~(a == e) == (a != e)).all()
+ assert (~(e == a) == (e != a)).all()
+ assert (~(a == f) == (a != f)).all()
+ assert (~(f == a) == (f != a)).all()
+
+ # non-equality is not comparable
+ msg = "can only compare equality or not"
+ with pytest.raises(TypeError, match=msg):
+ a < b
+ with pytest.raises(TypeError, match=msg):
+ b < a
+ with pytest.raises(TypeError, match=msg):
+ a > b
+ with pytest.raises(TypeError, match=msg):
+ b > a
+
+ def test_unequal_categorical_comparison_raises_type_error(self):
+ # unequal comparison should raise for unordered cats
+ cat = Series(Categorical(list("abc")))
+ msg = "can only compare equality or not"
+ with pytest.raises(TypeError, match=msg):
+ cat > "b"
+
+ cat = Series(Categorical(list("abc"), ordered=False))
+ with pytest.raises(TypeError, match=msg):
+ cat > "b"
+
+ # https://github.com/pandas-dev/pandas/issues/9836#issuecomment-92123057
+ # and following comparisons with scalars not in categories should raise
+ # for unequal comps, but not for equal/not equal
+ cat = Series(Categorical(list("abc"), ordered=True))
+
+ msg = "Invalid comparison between dtype=category and str"
+ with pytest.raises(TypeError, match=msg):
+ cat < "d"
+ with pytest.raises(TypeError, match=msg):
+ cat > "d"
+ with pytest.raises(TypeError, match=msg):
+ "d" < cat
+ with pytest.raises(TypeError, match=msg):
+ "d" > cat
+
+ tm.assert_series_equal(cat == "d", Series([False, False, False]))
+ tm.assert_series_equal(cat != "d", Series([True, True, True]))
+
+ # -----------------------------------------------------------------
+
+ def test_comparison_tuples(self):
+ # GH#11339
+ # comparisons vs tuple
+ s = Series([(1, 1), (1, 2)])
+
+ result = s == (1, 2)
+ expected = Series([False, True])
+ tm.assert_series_equal(result, expected)
+
+ result = s != (1, 2)
+ expected = Series([True, False])
+ tm.assert_series_equal(result, expected)
+
+ result = s == (0, 0)
+ expected = Series([False, False])
+ tm.assert_series_equal(result, expected)
+
+ result = s != (0, 0)
+ expected = Series([True, True])
+ tm.assert_series_equal(result, expected)
+
+ s = Series([(1, 1), (1, 1)])
+
+ result = s == (1, 1)
+ expected = Series([True, True])
+ tm.assert_series_equal(result, expected)
+
+ result = s != (1, 1)
+ expected = Series([False, False])
+ tm.assert_series_equal(result, expected)
+
+ def test_comparison_frozenset(self):
+ ser = Series([frozenset([1]), frozenset([1, 2])])
+
+ result = ser == frozenset([1])
+ expected = Series([True, False])
+ tm.assert_series_equal(result, expected)
+
+ def test_comparison_operators_with_nas(self, comparison_op):
+ ser = Series(bdate_range("1/1/2000", periods=10), dtype=object)
+ ser[::2] = np.nan
+
+ # test that comparisons work
+ val = ser[5]
+
+ result = comparison_op(ser, val)
+ expected = comparison_op(ser.dropna(), val).reindex(ser.index)
+
+ if comparison_op is operator.ne:
+ expected = expected.fillna(True).astype(bool)
+ else:
+ expected = expected.fillna(False).astype(bool)
+
+ tm.assert_series_equal(result, expected)
+
+ def test_ne(self):
+ ts = Series([3, 4, 5, 6, 7], [3, 4, 5, 6, 7], dtype=float)
+ expected = [True, True, False, True, True]
+ assert tm.equalContents(ts.index != 5, expected)
+ assert tm.equalContents(~(ts.index == 5), expected)
+
+ @pytest.mark.parametrize(
+ "left, right",
+ [
+ (
+ Series([1, 2, 3], index=list("ABC"), name="x"),
+ Series([2, 2, 2], index=list("ABD"), name="x"),
+ ),
+ (
+ Series([1, 2, 3], index=list("ABC"), name="x"),
+ Series([2, 2, 2, 2], index=list("ABCD"), name="x"),
+ ),
+ ],
+ )
+ def test_comp_ops_df_compat(self, left, right, frame_or_series):
+ # GH 1134
+ # GH 50083 to clarify that index and columns must be identically labeled
+ if frame_or_series is not Series:
+ msg = (
+ rf"Can only compare identically-labeled \(both index and columns\) "
+ f"{frame_or_series.__name__} objects"
+ )
+ left = left.to_frame()
+ right = right.to_frame()
+ else:
+ msg = (
+ f"Can only compare identically-labeled {frame_or_series.__name__} "
+ f"objects"
+ )
+
+ with pytest.raises(ValueError, match=msg):
+ left == right
+ with pytest.raises(ValueError, match=msg):
+ right == left
+
+ with pytest.raises(ValueError, match=msg):
+ left != right
+ with pytest.raises(ValueError, match=msg):
+ right != left
+
+ with pytest.raises(ValueError, match=msg):
+ left < right
+ with pytest.raises(ValueError, match=msg):
+ right < left
+
+ def test_compare_series_interval_keyword(self):
+ # GH#25338
+ ser = Series(["IntervalA", "IntervalB", "IntervalC"])
+ result = ser == "IntervalA"
+ expected = Series([True, False, False])
+ tm.assert_series_equal(result, expected)
+
+
+# ------------------------------------------------------------------
+# Unsorted
+# These arithmetic tests were previously in other files, eventually
+# should be parametrized and put into tests.arithmetic
+
+
+class TestTimeSeriesArithmetic:
+ def test_series_add_tz_mismatch_converts_to_utc(self):
+ rng = date_range("1/1/2011", periods=100, freq="H", tz="utc")
+
+ perm = np.random.default_rng(2).permutation(100)[:90]
+ ser1 = Series(
+ np.random.default_rng(2).standard_normal(90),
+ index=rng.take(perm).tz_convert("US/Eastern"),
+ )
+
+ perm = np.random.default_rng(2).permutation(100)[:90]
+ ser2 = Series(
+ np.random.default_rng(2).standard_normal(90),
+ index=rng.take(perm).tz_convert("Europe/Berlin"),
+ )
+
+ result = ser1 + ser2
+
+ uts1 = ser1.tz_convert("utc")
+ uts2 = ser2.tz_convert("utc")
+ expected = uts1 + uts2
+
+ assert result.index.tz is timezone.utc
+ tm.assert_series_equal(result, expected)
+
+ def test_series_add_aware_naive_raises(self):
+ rng = date_range("1/1/2011", periods=10, freq="H")
+ ser = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
+
+ ser_utc = ser.tz_localize("utc")
+
+ msg = "Cannot join tz-naive with tz-aware DatetimeIndex"
+ with pytest.raises(Exception, match=msg):
+ ser + ser_utc
+
+ with pytest.raises(Exception, match=msg):
+ ser_utc + ser
+
+ def test_datetime_understood(self):
+ # Ensures it doesn't fail to create the right series
+ # reported in issue#16726
+ series = Series(date_range("2012-01-01", periods=3))
+ offset = pd.offsets.DateOffset(days=6)
+ result = series - offset
+ expected = Series(pd.to_datetime(["2011-12-26", "2011-12-27", "2011-12-28"]))
+ tm.assert_series_equal(result, expected)
+
+ def test_align_date_objects_with_datetimeindex(self):
+ rng = date_range("1/1/2000", periods=20)
+ ts = Series(np.random.default_rng(2).standard_normal(20), index=rng)
+
+ ts_slice = ts[5:]
+ ts2 = ts_slice.copy()
+ ts2.index = [x.date() for x in ts2.index]
+
+ result = ts + ts2
+ result2 = ts2 + ts
+ expected = ts + ts[5:]
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(result, expected)
+ tm.assert_series_equal(result2, expected)
+
+
+class TestNamePreservation:
+ @pytest.mark.parametrize("box", [list, tuple, np.array, Index, Series, pd.array])
+ @pytest.mark.parametrize("flex", [True, False])
+ def test_series_ops_name_retention(self, flex, box, names, all_binary_operators):
+ # GH#33930 consistent name renteiton
+ op = all_binary_operators
+
+ left = Series(range(10), name=names[0])
+ right = Series(range(10), name=names[1])
+
+ name = op.__name__.strip("_")
+ is_logical = name in ["and", "rand", "xor", "rxor", "or", "ror"]
+
+ msg = (
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
+ "dtype-less sequences"
+ )
+ warn = None
+ if box in [list, tuple] and is_logical:
+ warn = FutureWarning
+
+ right = box(right)
+ if flex:
+ if is_logical:
+ # Series doesn't have these as flex methods
+ return
+ result = getattr(left, name)(right)
+ else:
+ # GH#37374 logical ops behaving as set ops deprecated
+ with tm.assert_produces_warning(warn, match=msg):
+ result = op(left, right)
+
+ assert isinstance(result, Series)
+ if box in [Index, Series]:
+ assert result.name is names[2] or result.name == names[2]
+ else:
+ assert result.name is names[0] or result.name == names[0]
+
+ def test_binop_maybe_preserve_name(self, datetime_series):
+ # names match, preserve
+ result = datetime_series * datetime_series
+ assert result.name == datetime_series.name
+ result = datetime_series.mul(datetime_series)
+ assert result.name == datetime_series.name
+
+ result = datetime_series * datetime_series[:-2]
+ assert result.name == datetime_series.name
+
+ # names don't match, don't preserve
+ cp = datetime_series.copy()
+ cp.name = "something else"
+ result = datetime_series + cp
+ assert result.name is None
+ result = datetime_series.add(cp)
+ assert result.name is None
+
+ ops = ["add", "sub", "mul", "div", "truediv", "floordiv", "mod", "pow"]
+ ops = ops + ["r" + op for op in ops]
+ for op in ops:
+ # names match, preserve
+ ser = datetime_series.copy()
+ result = getattr(ser, op)(ser)
+ assert result.name == datetime_series.name
+
+ # names don't match, don't preserve
+ cp = datetime_series.copy()
+ cp.name = "changed"
+ result = getattr(ser, op)(cp)
+ assert result.name is None
+
+ def test_scalarop_preserve_name(self, datetime_series):
+ result = datetime_series * 2
+ assert result.name == datetime_series.name
+
+
+class TestInplaceOperations:
+ @pytest.mark.parametrize(
+ "dtype1, dtype2, dtype_expected, dtype_mul",
+ (
+ ("Int64", "Int64", "Int64", "Int64"),
+ ("float", "float", "float", "float"),
+ ("Int64", "float", "Float64", "Float64"),
+ ("Int64", "Float64", "Float64", "Float64"),
+ ),
+ )
+ def test_series_inplace_ops(self, dtype1, dtype2, dtype_expected, dtype_mul):
+ # GH 37910
+
+ ser1 = Series([1], dtype=dtype1)
+ ser2 = Series([2], dtype=dtype2)
+ ser1 += ser2
+ expected = Series([3], dtype=dtype_expected)
+ tm.assert_series_equal(ser1, expected)
+
+ ser1 -= ser2
+ expected = Series([1], dtype=dtype_expected)
+ tm.assert_series_equal(ser1, expected)
+
+ ser1 *= ser2
+ expected = Series([2], dtype=dtype_mul)
+ tm.assert_series_equal(ser1, expected)
+
+
+def test_none_comparison(request, series_with_simple_index):
+ series = series_with_simple_index
+
+ if len(series) < 1:
+ request.node.add_marker(
+ pytest.mark.xfail(reason="Test doesn't make sense on empty data")
+ )
+
+ # bug brought up by #1079
+ # changed from TypeError in 0.17.0
+ series.iloc[0] = np.nan
+
+ # noinspection PyComparisonWithNone
+ result = series == None # noqa: E711
+ assert not result.iat[0]
+ assert not result.iat[1]
+
+ # noinspection PyComparisonWithNone
+ result = series != None # noqa: E711
+ assert result.iat[0]
+ assert result.iat[1]
+
+ result = None == series # noqa: E711
+ assert not result.iat[0]
+ assert not result.iat[1]
+
+ result = None != series # noqa: E711
+ assert result.iat[0]
+ assert result.iat[1]
+
+ if lib.is_np_dtype(series.dtype, "M") or isinstance(series.dtype, DatetimeTZDtype):
+ # Following DatetimeIndex (and Timestamp) convention,
+ # inequality comparisons with Series[datetime64] raise
+ msg = "Invalid comparison"
+ with pytest.raises(TypeError, match=msg):
+ None > series
+ with pytest.raises(TypeError, match=msg):
+ series > None
+ else:
+ result = None > series
+ assert not result.iat[0]
+ assert not result.iat[1]
+
+ result = series < None
+ assert not result.iat[0]
+ assert not result.iat[1]
+
+
+def test_series_varied_multiindex_alignment():
+ # GH 20414
+ s1 = Series(
+ range(8),
+ index=pd.MultiIndex.from_product(
+ [list("ab"), list("xy"), [1, 2]], names=["ab", "xy", "num"]
+ ),
+ )
+ s2 = Series(
+ [1000 * i for i in range(1, 5)],
+ index=pd.MultiIndex.from_product([list("xy"), [1, 2]], names=["xy", "num"]),
+ )
+ result = s1.loc[pd.IndexSlice[["a"], :, :]] + s2
+ expected = Series(
+ [1000, 2001, 3002, 4003],
+ index=pd.MultiIndex.from_tuples(
+ [("x", 1, "a"), ("x", 2, "a"), ("y", 1, "a"), ("y", 2, "a")],
+ names=["xy", "num", "ab"],
+ ),
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_rmod_consistent_large_series():
+ # GH 29602
+ result = Series([2] * 10001).rmod(-1)
+ expected = Series([1] * 10001)
+
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_constructors.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_constructors.py
new file mode 100644
index 0000000000000000000000000000000000000000..b74ee5cf8f2bccb7d9d4caf4347d88547ecf5dfa
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_constructors.py
@@ -0,0 +1,2242 @@
+from collections import OrderedDict
+from collections.abc import Iterator
+from datetime import (
+ datetime,
+ timedelta,
+)
+
+from dateutil.tz import tzoffset
+import numpy as np
+from numpy import ma
+import pytest
+
+from pandas._libs import (
+ iNaT,
+ lib,
+)
+from pandas.errors import IntCastingNaNError
+import pandas.util._test_decorators as td
+
+from pandas.core.dtypes.common import is_categorical_dtype
+from pandas.core.dtypes.dtypes import CategoricalDtype
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DataFrame,
+ DatetimeIndex,
+ DatetimeTZDtype,
+ Index,
+ Interval,
+ IntervalIndex,
+ MultiIndex,
+ NaT,
+ Period,
+ RangeIndex,
+ Series,
+ Timestamp,
+ date_range,
+ isna,
+ period_range,
+ timedelta_range,
+)
+import pandas._testing as tm
+from pandas.core.arrays import (
+ IntegerArray,
+ IntervalArray,
+ period_array,
+)
+from pandas.core.internals.blocks import NumpyBlock
+
+
+class TestSeriesConstructors:
+ def test_from_ints_with_non_nano_dt64_dtype(self, index_or_series):
+ values = np.arange(10)
+
+ res = index_or_series(values, dtype="M8[s]")
+ expected = index_or_series(values.astype("M8[s]"))
+ tm.assert_equal(res, expected)
+
+ res = index_or_series(list(values), dtype="M8[s]")
+ tm.assert_equal(res, expected)
+
+ def test_from_na_value_and_interval_of_datetime_dtype(self):
+ # GH#41805
+ ser = Series([None], dtype="interval[datetime64[ns]]")
+ assert ser.isna().all()
+ assert ser.dtype == "interval[datetime64[ns], right]"
+
+ def test_infer_with_date_and_datetime(self):
+ # GH#49341 pre-2.0 we inferred datetime-and-date to datetime64, which
+ # was inconsistent with Index behavior
+ ts = Timestamp(2016, 1, 1)
+ vals = [ts.to_pydatetime(), ts.date()]
+
+ ser = Series(vals)
+ expected = Series(vals, dtype=object)
+ tm.assert_series_equal(ser, expected)
+
+ idx = Index(vals)
+ expected = Index(vals, dtype=object)
+ tm.assert_index_equal(idx, expected)
+
+ def test_unparsable_strings_with_dt64_dtype(self):
+ # pre-2.0 these would be silently ignored and come back with object dtype
+ vals = ["aa"]
+ msg = "^Unknown datetime string format, unable to parse: aa, at position 0$"
+ with pytest.raises(ValueError, match=msg):
+ Series(vals, dtype="datetime64[ns]")
+
+ with pytest.raises(ValueError, match=msg):
+ Series(np.array(vals, dtype=object), dtype="datetime64[ns]")
+
+ @pytest.mark.parametrize(
+ "constructor",
+ [
+ # NOTE: some overlap with test_constructor_empty but that test does not
+ # test for None or an empty generator.
+ # test_constructor_pass_none tests None but only with the index also
+ # passed.
+ (lambda idx: Series(index=idx)),
+ (lambda idx: Series(None, index=idx)),
+ (lambda idx: Series({}, index=idx)),
+ (lambda idx: Series((), index=idx)),
+ (lambda idx: Series([], index=idx)),
+ (lambda idx: Series((_ for _ in []), index=idx)),
+ (lambda idx: Series(data=None, index=idx)),
+ (lambda idx: Series(data={}, index=idx)),
+ (lambda idx: Series(data=(), index=idx)),
+ (lambda idx: Series(data=[], index=idx)),
+ (lambda idx: Series(data=(_ for _ in []), index=idx)),
+ ],
+ )
+ @pytest.mark.parametrize("empty_index", [None, []])
+ def test_empty_constructor(self, constructor, empty_index):
+ # GH 49573 (addition of empty_index parameter)
+ expected = Series(index=empty_index)
+ result = constructor(empty_index)
+
+ assert result.dtype == object
+ assert len(result.index) == 0
+ tm.assert_series_equal(result, expected, check_index_type=True)
+
+ def test_invalid_dtype(self):
+ # GH15520
+ msg = "not understood"
+ invalid_list = [Timestamp, "Timestamp", list]
+ for dtype in invalid_list:
+ with pytest.raises(TypeError, match=msg):
+ Series([], name="time", dtype=dtype)
+
+ def test_invalid_compound_dtype(self):
+ # GH#13296
+ c_dtype = np.dtype([("a", "i8"), ("b", "f4")])
+ cdt_arr = np.array([(1, 0.4), (256, -13)], dtype=c_dtype)
+
+ with pytest.raises(ValueError, match="Use DataFrame instead"):
+ Series(cdt_arr, index=["A", "B"])
+
+ def test_scalar_conversion(self):
+ # Pass in scalar is disabled
+ scalar = Series(0.5)
+ assert not isinstance(scalar, float)
+
+ def test_scalar_extension_dtype(self, ea_scalar_and_dtype):
+ # GH 28401
+
+ ea_scalar, ea_dtype = ea_scalar_and_dtype
+
+ ser = Series(ea_scalar, index=range(3))
+ expected = Series([ea_scalar] * 3, dtype=ea_dtype)
+
+ assert ser.dtype == ea_dtype
+ tm.assert_series_equal(ser, expected)
+
+ def test_constructor(self, datetime_series):
+ empty_series = Series()
+ assert datetime_series.index._is_all_dates
+
+ # Pass in Series
+ derived = Series(datetime_series)
+ assert derived.index._is_all_dates
+
+ assert tm.equalContents(derived.index, datetime_series.index)
+ # Ensure new index is not created
+ assert id(datetime_series.index) == id(derived.index)
+
+ # Mixed type Series
+ mixed = Series(["hello", np.nan], index=[0, 1])
+ assert mixed.dtype == np.object_
+ assert np.isnan(mixed[1])
+
+ assert not empty_series.index._is_all_dates
+ assert not Series().index._is_all_dates
+
+ # exception raised is of type ValueError GH35744
+ with pytest.raises(
+ ValueError,
+ match=r"Data must be 1-dimensional, got ndarray of shape \(3, 3\) instead",
+ ):
+ Series(np.random.default_rng(2).standard_normal((3, 3)), index=np.arange(3))
+
+ mixed.name = "Series"
+ rs = Series(mixed).name
+ xp = "Series"
+ assert rs == xp
+
+ # raise on MultiIndex GH4187
+ m = MultiIndex.from_arrays([[1, 2], [3, 4]])
+ msg = "initializing a Series from a MultiIndex is not supported"
+ with pytest.raises(NotImplementedError, match=msg):
+ Series(m)
+
+ def test_constructor_index_ndim_gt_1_raises(self):
+ # GH#18579
+ df = DataFrame([[1, 2], [3, 4], [5, 6]], index=[3, 6, 9])
+ with pytest.raises(ValueError, match="Index data must be 1-dimensional"):
+ Series([1, 3, 2], index=df)
+
+ @pytest.mark.parametrize("input_class", [list, dict, OrderedDict])
+ def test_constructor_empty(self, input_class):
+ empty = Series()
+ empty2 = Series(input_class())
+
+ # these are Index() and RangeIndex() which don't compare type equal
+ # but are just .equals
+ tm.assert_series_equal(empty, empty2, check_index_type=False)
+
+ # With explicit dtype:
+ empty = Series(dtype="float64")
+ empty2 = Series(input_class(), dtype="float64")
+ tm.assert_series_equal(empty, empty2, check_index_type=False)
+
+ # GH 18515 : with dtype=category:
+ empty = Series(dtype="category")
+ empty2 = Series(input_class(), dtype="category")
+ tm.assert_series_equal(empty, empty2, check_index_type=False)
+
+ if input_class is not list:
+ # With index:
+ empty = Series(index=range(10))
+ empty2 = Series(input_class(), index=range(10))
+ tm.assert_series_equal(empty, empty2)
+
+ # With index and dtype float64:
+ empty = Series(np.nan, index=range(10))
+ empty2 = Series(input_class(), index=range(10), dtype="float64")
+ tm.assert_series_equal(empty, empty2)
+
+ # GH 19853 : with empty string, index and dtype str
+ empty = Series("", dtype=str, index=range(3))
+ empty2 = Series("", index=range(3))
+ tm.assert_series_equal(empty, empty2)
+
+ @pytest.mark.parametrize("input_arg", [np.nan, float("nan")])
+ def test_constructor_nan(self, input_arg):
+ empty = Series(dtype="float64", index=range(10))
+ empty2 = Series(input_arg, index=range(10))
+
+ tm.assert_series_equal(empty, empty2, check_index_type=False)
+
+ @pytest.mark.parametrize(
+ "dtype",
+ ["f8", "i8", "M8[ns]", "m8[ns]", "category", "object", "datetime64[ns, UTC]"],
+ )
+ @pytest.mark.parametrize("index", [None, Index([])])
+ def test_constructor_dtype_only(self, dtype, index):
+ # GH-20865
+ result = Series(dtype=dtype, index=index)
+ assert result.dtype == dtype
+ assert len(result) == 0
+
+ def test_constructor_no_data_index_order(self):
+ result = Series(index=["b", "a", "c"])
+ assert result.index.tolist() == ["b", "a", "c"]
+
+ def test_constructor_no_data_string_type(self):
+ # GH 22477
+ result = Series(index=[1], dtype=str)
+ assert np.isnan(result.iloc[0])
+
+ @pytest.mark.parametrize("item", ["entry", "ѐ", 13])
+ def test_constructor_string_element_string_type(self, item):
+ # GH 22477
+ result = Series(item, index=[1], dtype=str)
+ assert result.iloc[0] == str(item)
+
+ def test_constructor_dtype_str_na_values(self, string_dtype):
+ # https://github.com/pandas-dev/pandas/issues/21083
+ ser = Series(["x", None], dtype=string_dtype)
+ result = ser.isna()
+ expected = Series([False, True])
+ tm.assert_series_equal(result, expected)
+ assert ser.iloc[1] is None
+
+ ser = Series(["x", np.nan], dtype=string_dtype)
+ assert np.isnan(ser.iloc[1])
+
+ def test_constructor_series(self):
+ index1 = ["d", "b", "a", "c"]
+ index2 = sorted(index1)
+ s1 = Series([4, 7, -5, 3], index=index1)
+ s2 = Series(s1, index=index2)
+
+ tm.assert_series_equal(s2, s1.sort_index())
+
+ def test_constructor_iterable(self):
+ # GH 21987
+ class Iter:
+ def __iter__(self) -> Iterator:
+ yield from range(10)
+
+ expected = Series(list(range(10)), dtype="int64")
+ result = Series(Iter(), dtype="int64")
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_sequence(self):
+ # GH 21987
+ expected = Series(list(range(10)), dtype="int64")
+ result = Series(range(10), dtype="int64")
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_single_str(self):
+ # GH 21987
+ expected = Series(["abc"])
+ result = Series("abc")
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_list_like(self):
+ # make sure that we are coercing different
+ # list-likes to standard dtypes and not
+ # platform specific
+ expected = Series([1, 2, 3], dtype="int64")
+ for obj in [[1, 2, 3], (1, 2, 3), np.array([1, 2, 3], dtype="int64")]:
+ result = Series(obj, index=[0, 1, 2])
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_boolean_index(self):
+ # GH#18579
+ s1 = Series([1, 2, 3], index=[4, 5, 6])
+
+ index = s1 == 2
+ result = Series([1, 3, 2], index=index)
+ expected = Series([1, 3, 2], index=[False, True, False])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["bool", "int32", "int64", "float64"])
+ def test_constructor_index_dtype(self, dtype):
+ # GH 17088
+
+ s = Series(Index([0, 2, 4]), dtype=dtype)
+ assert s.dtype == dtype
+
+ @pytest.mark.parametrize(
+ "input_vals",
+ [
+ ([1, 2]),
+ (["1", "2"]),
+ (list(date_range("1/1/2011", periods=2, freq="H"))),
+ (list(date_range("1/1/2011", periods=2, freq="H", tz="US/Eastern"))),
+ ([Interval(left=0, right=5)]),
+ ],
+ )
+ def test_constructor_list_str(self, input_vals, string_dtype):
+ # GH 16605
+ # Ensure that data elements from a list are converted to strings
+ # when dtype is str, 'str', or 'U'
+ result = Series(input_vals, dtype=string_dtype)
+ expected = Series(input_vals).astype(string_dtype)
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_list_str_na(self, string_dtype):
+ result = Series([1.0, 2.0, np.nan], dtype=string_dtype)
+ expected = Series(["1.0", "2.0", np.nan], dtype=object)
+ tm.assert_series_equal(result, expected)
+ assert np.isnan(result[2])
+
+ def test_constructor_generator(self):
+ gen = (i for i in range(10))
+
+ result = Series(gen)
+ exp = Series(range(10))
+ tm.assert_series_equal(result, exp)
+
+ # same but with non-default index
+ gen = (i for i in range(10))
+ result = Series(gen, index=range(10, 20))
+ exp.index = range(10, 20)
+ tm.assert_series_equal(result, exp)
+
+ def test_constructor_map(self):
+ # GH8909
+ m = (x for x in range(10))
+
+ result = Series(m)
+ exp = Series(range(10))
+ tm.assert_series_equal(result, exp)
+
+ # same but with non-default index
+ m = (x for x in range(10))
+ result = Series(m, index=range(10, 20))
+ exp.index = range(10, 20)
+ tm.assert_series_equal(result, exp)
+
+ def test_constructor_categorical(self):
+ cat = Categorical([0, 1, 2, 0, 1, 2], ["a", "b", "c"])
+ res = Series(cat)
+ tm.assert_categorical_equal(res.values, cat)
+
+ # can cast to a new dtype
+ result = Series(Categorical([1, 2, 3]), dtype="int64")
+ expected = Series([1, 2, 3], dtype="int64")
+ tm.assert_series_equal(result, expected)
+
+ def test_construct_from_categorical_with_dtype(self):
+ # GH12574
+ cat = Series(Categorical([1, 2, 3]), dtype="category")
+ msg = "is_categorical_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert is_categorical_dtype(cat)
+ assert is_categorical_dtype(cat.dtype)
+
+ def test_construct_intlist_values_category_dtype(self):
+ ser = Series([1, 2, 3], dtype="category")
+ msg = "is_categorical_dtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert is_categorical_dtype(ser)
+ assert is_categorical_dtype(ser.dtype)
+
+ def test_constructor_categorical_with_coercion(self):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"])
+ # test basic creation / coercion of categoricals
+ s = Series(factor, name="A")
+ assert s.dtype == "category"
+ assert len(s) == len(factor)
+ str(s.values)
+ str(s)
+
+ # in a frame
+ df = DataFrame({"A": factor})
+ result = df["A"]
+ tm.assert_series_equal(result, s)
+ result = df.iloc[:, 0]
+ tm.assert_series_equal(result, s)
+ assert len(df) == len(factor)
+ str(df.values)
+ str(df)
+
+ df = DataFrame({"A": s})
+ result = df["A"]
+ tm.assert_series_equal(result, s)
+ assert len(df) == len(factor)
+ str(df.values)
+ str(df)
+
+ # multiples
+ df = DataFrame({"A": s, "B": s, "C": 1})
+ result1 = df["A"]
+ result2 = df["B"]
+ tm.assert_series_equal(result1, s)
+ tm.assert_series_equal(result2, s, check_names=False)
+ assert result2.name == "B"
+ assert len(df) == len(factor)
+ str(df.values)
+ str(df)
+
+ def test_constructor_categorical_with_coercion2(self):
+ # GH8623
+ x = DataFrame(
+ [[1, "John P. Doe"], [2, "Jane Dove"], [1, "John P. Doe"]],
+ columns=["person_id", "person_name"],
+ )
+ x["person_name"] = Categorical(x.person_name) # doing this breaks transform
+
+ expected = x.iloc[0].person_name
+ result = x.person_name.iloc[0]
+ assert result == expected
+
+ result = x.person_name[0]
+ assert result == expected
+
+ result = x.person_name.loc[0]
+ assert result == expected
+
+ def test_constructor_series_to_categorical(self):
+ # see GH#16524: test conversion of Series to Categorical
+ series = Series(["a", "b", "c"])
+
+ result = Series(series, dtype="category")
+ expected = Series(["a", "b", "c"], dtype="category")
+
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_categorical_dtype(self):
+ result = Series(
+ ["a", "b"], dtype=CategoricalDtype(["a", "b", "c"], ordered=True)
+ )
+ assert isinstance(result.dtype, CategoricalDtype)
+ tm.assert_index_equal(result.cat.categories, Index(["a", "b", "c"]))
+ assert result.cat.ordered
+
+ result = Series(["a", "b"], dtype=CategoricalDtype(["b", "a"]))
+ assert isinstance(result.dtype, CategoricalDtype)
+ tm.assert_index_equal(result.cat.categories, Index(["b", "a"]))
+ assert result.cat.ordered is False
+
+ # GH 19565 - Check broadcasting of scalar with Categorical dtype
+ result = Series(
+ "a", index=[0, 1], dtype=CategoricalDtype(["a", "b"], ordered=True)
+ )
+ expected = Series(
+ ["a", "a"], index=[0, 1], dtype=CategoricalDtype(["a", "b"], ordered=True)
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_categorical_string(self):
+ # GH 26336: the string 'category' maintains existing CategoricalDtype
+ cdt = CategoricalDtype(categories=list("dabc"), ordered=True)
+ expected = Series(list("abcabc"), dtype=cdt)
+
+ # Series(Categorical, dtype='category') keeps existing dtype
+ cat = Categorical(list("abcabc"), dtype=cdt)
+ result = Series(cat, dtype="category")
+ tm.assert_series_equal(result, expected)
+
+ # Series(Series[Categorical], dtype='category') keeps existing dtype
+ result = Series(result, dtype="category")
+ tm.assert_series_equal(result, expected)
+
+ def test_categorical_sideeffects_free(self):
+ # Passing a categorical to a Series and then changing values in either
+ # the series or the categorical should not change the values in the
+ # other one, IF you specify copy!
+ cat = Categorical(["a", "b", "c", "a"])
+ s = Series(cat, copy=True)
+ assert s.cat is not cat
+ s = s.cat.rename_categories([1, 2, 3])
+ exp_s = np.array([1, 2, 3, 1], dtype=np.int64)
+ exp_cat = np.array(["a", "b", "c", "a"], dtype=np.object_)
+ tm.assert_numpy_array_equal(s.__array__(), exp_s)
+ tm.assert_numpy_array_equal(cat.__array__(), exp_cat)
+
+ # setting
+ s[0] = 2
+ exp_s2 = np.array([2, 2, 3, 1], dtype=np.int64)
+ tm.assert_numpy_array_equal(s.__array__(), exp_s2)
+ tm.assert_numpy_array_equal(cat.__array__(), exp_cat)
+
+ # however, copy is False by default
+ # so this WILL change values
+ cat = Categorical(["a", "b", "c", "a"])
+ s = Series(cat, copy=False)
+ assert s.values is cat
+ s = s.cat.rename_categories([1, 2, 3])
+ assert s.values is not cat
+ exp_s = np.array([1, 2, 3, 1], dtype=np.int64)
+ tm.assert_numpy_array_equal(s.__array__(), exp_s)
+
+ s[0] = 2
+ exp_s2 = np.array([2, 2, 3, 1], dtype=np.int64)
+ tm.assert_numpy_array_equal(s.__array__(), exp_s2)
+
+ def test_unordered_compare_equal(self):
+ left = Series(["a", "b", "c"], dtype=CategoricalDtype(["a", "b"]))
+ right = Series(Categorical(["a", "b", np.nan], categories=["a", "b"]))
+ tm.assert_series_equal(left, right)
+
+ def test_constructor_maskedarray(self):
+ data = ma.masked_all((3,), dtype=float)
+ result = Series(data)
+ expected = Series([np.nan, np.nan, np.nan])
+ tm.assert_series_equal(result, expected)
+
+ data[0] = 0.0
+ data[2] = 2.0
+ index = ["a", "b", "c"]
+ result = Series(data, index=index)
+ expected = Series([0.0, np.nan, 2.0], index=index)
+ tm.assert_series_equal(result, expected)
+
+ data[1] = 1.0
+ result = Series(data, index=index)
+ expected = Series([0.0, 1.0, 2.0], index=index)
+ tm.assert_series_equal(result, expected)
+
+ data = ma.masked_all((3,), dtype=int)
+ result = Series(data)
+ expected = Series([np.nan, np.nan, np.nan], dtype=float)
+ tm.assert_series_equal(result, expected)
+
+ data[0] = 0
+ data[2] = 2
+ index = ["a", "b", "c"]
+ result = Series(data, index=index)
+ expected = Series([0, np.nan, 2], index=index, dtype=float)
+ tm.assert_series_equal(result, expected)
+
+ data[1] = 1
+ result = Series(data, index=index)
+ expected = Series([0, 1, 2], index=index, dtype=int)
+ tm.assert_series_equal(result, expected)
+
+ data = ma.masked_all((3,), dtype=bool)
+ result = Series(data)
+ expected = Series([np.nan, np.nan, np.nan], dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ data[0] = True
+ data[2] = False
+ index = ["a", "b", "c"]
+ result = Series(data, index=index)
+ expected = Series([True, np.nan, False], index=index, dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ data[1] = True
+ result = Series(data, index=index)
+ expected = Series([True, True, False], index=index, dtype=bool)
+ tm.assert_series_equal(result, expected)
+
+ data = ma.masked_all((3,), dtype="M8[ns]")
+ result = Series(data)
+ expected = Series([iNaT, iNaT, iNaT], dtype="M8[ns]")
+ tm.assert_series_equal(result, expected)
+
+ data[0] = datetime(2001, 1, 1)
+ data[2] = datetime(2001, 1, 3)
+ index = ["a", "b", "c"]
+ result = Series(data, index=index)
+ expected = Series(
+ [datetime(2001, 1, 1), iNaT, datetime(2001, 1, 3)],
+ index=index,
+ dtype="M8[ns]",
+ )
+ tm.assert_series_equal(result, expected)
+
+ data[1] = datetime(2001, 1, 2)
+ result = Series(data, index=index)
+ expected = Series(
+ [datetime(2001, 1, 1), datetime(2001, 1, 2), datetime(2001, 1, 3)],
+ index=index,
+ dtype="M8[ns]",
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_maskedarray_hardened(self):
+ # Check numpy masked arrays with hard masks -- from GH24574
+ data = ma.masked_all((3,), dtype=float).harden_mask()
+ result = Series(data)
+ expected = Series([np.nan, np.nan, np.nan])
+ tm.assert_series_equal(result, expected)
+
+ def test_series_ctor_plus_datetimeindex(self, using_copy_on_write):
+ rng = date_range("20090415", "20090519", freq="B")
+ data = {k: 1 for k in rng}
+
+ result = Series(data, index=rng)
+ if using_copy_on_write:
+ assert result.index.is_(rng)
+ else:
+ assert result.index is rng
+
+ def test_constructor_default_index(self):
+ s = Series([0, 1, 2])
+ tm.assert_index_equal(s.index, Index(range(3)), exact=True)
+
+ @pytest.mark.parametrize(
+ "input",
+ [
+ [1, 2, 3],
+ (1, 2, 3),
+ list(range(3)),
+ Categorical(["a", "b", "a"]),
+ (i for i in range(3)),
+ (x for x in range(3)),
+ ],
+ )
+ def test_constructor_index_mismatch(self, input):
+ # GH 19342
+ # test that construction of a Series with an index of different length
+ # raises an error
+ msg = r"Length of values \(3\) does not match length of index \(4\)"
+ with pytest.raises(ValueError, match=msg):
+ Series(input, index=np.arange(4))
+
+ def test_constructor_numpy_scalar(self):
+ # GH 19342
+ # construction with a numpy scalar
+ # should not raise
+ result = Series(np.array(100), index=np.arange(4), dtype="int64")
+ expected = Series(100, index=np.arange(4), dtype="int64")
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_broadcast_list(self):
+ # GH 19342
+ # construction with single-element container and index
+ # should raise
+ msg = r"Length of values \(1\) does not match length of index \(3\)"
+ with pytest.raises(ValueError, match=msg):
+ Series(["foo"], index=["a", "b", "c"])
+
+ def test_constructor_corner(self):
+ df = tm.makeTimeDataFrame()
+ objs = [df, df]
+ s = Series(objs, index=[0, 1])
+ assert isinstance(s, Series)
+
+ def test_constructor_sanitize(self):
+ s = Series(np.array([1.0, 1.0, 8.0]), dtype="i8")
+ assert s.dtype == np.dtype("i8")
+
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
+ with pytest.raises(IntCastingNaNError, match=msg):
+ Series(np.array([1.0, 1.0, np.nan]), copy=True, dtype="i8")
+
+ def test_constructor_copy(self):
+ # GH15125
+ # test dtype parameter has no side effects on copy=True
+ for data in [[1.0], np.array([1.0])]:
+ x = Series(data)
+ y = Series(x, copy=True, dtype=float)
+
+ # copy=True maintains original data in Series
+ tm.assert_series_equal(x, y)
+
+ # changes to origin of copy does not affect the copy
+ x[0] = 2.0
+ assert not x.equals(y)
+ assert x[0] == 2.0
+ assert y[0] == 1.0
+
+ @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite test
+ @pytest.mark.parametrize(
+ "index",
+ [
+ date_range("20170101", periods=3, tz="US/Eastern"),
+ date_range("20170101", periods=3),
+ timedelta_range("1 day", periods=3),
+ period_range("2012Q1", periods=3, freq="Q"),
+ Index(list("abc")),
+ Index([1, 2, 3]),
+ RangeIndex(0, 3),
+ ],
+ ids=lambda x: type(x).__name__,
+ )
+ def test_constructor_limit_copies(self, index):
+ # GH 17449
+ # limit copies of input
+ s = Series(index)
+
+ # we make 1 copy; this is just a smoke test here
+ assert s._mgr.blocks[0].values is not index
+
+ def test_constructor_shallow_copy(self):
+ # constructing a Series from Series with copy=False should still
+ # give a "shallow" copy (share data, not attributes)
+ # https://github.com/pandas-dev/pandas/issues/49523
+ s = Series([1, 2, 3])
+ s_orig = s.copy()
+ s2 = Series(s)
+ assert s2._mgr is not s._mgr
+ # Overwriting index of s2 doesn't change s
+ s2.index = ["a", "b", "c"]
+ tm.assert_series_equal(s, s_orig)
+
+ def test_constructor_pass_none(self):
+ s = Series(None, index=range(5))
+ assert s.dtype == np.float64
+
+ s = Series(None, index=range(5), dtype=object)
+ assert s.dtype == np.object_
+
+ # GH 7431
+ # inference on the index
+ s = Series(index=np.array([None]))
+ expected = Series(index=Index([None]))
+ tm.assert_series_equal(s, expected)
+
+ def test_constructor_pass_nan_nat(self):
+ # GH 13467
+ exp = Series([np.nan, np.nan], dtype=np.float64)
+ assert exp.dtype == np.float64
+ tm.assert_series_equal(Series([np.nan, np.nan]), exp)
+ tm.assert_series_equal(Series(np.array([np.nan, np.nan])), exp)
+
+ exp = Series([NaT, NaT])
+ assert exp.dtype == "datetime64[ns]"
+ tm.assert_series_equal(Series([NaT, NaT]), exp)
+ tm.assert_series_equal(Series(np.array([NaT, NaT])), exp)
+
+ tm.assert_series_equal(Series([NaT, np.nan]), exp)
+ tm.assert_series_equal(Series(np.array([NaT, np.nan])), exp)
+
+ tm.assert_series_equal(Series([np.nan, NaT]), exp)
+ tm.assert_series_equal(Series(np.array([np.nan, NaT])), exp)
+
+ def test_constructor_cast(self):
+ msg = "could not convert string to float"
+ with pytest.raises(ValueError, match=msg):
+ Series(["a", "b", "c"], dtype=float)
+
+ def test_constructor_signed_int_overflow_raises(self):
+ # GH#41734 disallow silent overflow, enforced in 2.0
+ msg = "Values are too large to be losslessly converted"
+ with pytest.raises(ValueError, match=msg):
+ Series([1, 200, 923442], dtype="int8")
+
+ with pytest.raises(ValueError, match=msg):
+ Series([1, 200, 923442], dtype="uint8")
+
+ @pytest.mark.parametrize(
+ "values",
+ [
+ np.array([1], dtype=np.uint16),
+ np.array([1], dtype=np.uint32),
+ np.array([1], dtype=np.uint64),
+ [np.uint16(1)],
+ [np.uint32(1)],
+ [np.uint64(1)],
+ ],
+ )
+ def test_constructor_numpy_uints(self, values):
+ # GH#47294
+ value = values[0]
+ result = Series(values)
+
+ assert result[0].dtype == value.dtype
+ assert result[0] == value
+
+ def test_constructor_unsigned_dtype_overflow(self, any_unsigned_int_numpy_dtype):
+ # see gh-15832
+ msg = "Trying to coerce negative values to unsigned integers"
+ with pytest.raises(OverflowError, match=msg):
+ Series([-1], dtype=any_unsigned_int_numpy_dtype)
+
+ def test_constructor_floating_data_int_dtype(self, frame_or_series):
+ # GH#40110
+ arr = np.random.default_rng(2).standard_normal(2)
+
+ # Long-standing behavior (for Series, new in 2.0 for DataFrame)
+ # has been to ignore the dtype on these;
+ # not clear if this is what we want long-term
+ # expected = frame_or_series(arr)
+
+ # GH#49599 as of 2.0 we raise instead of silently retaining float dtype
+ msg = "Trying to coerce float values to integer"
+ with pytest.raises(ValueError, match=msg):
+ frame_or_series(arr, dtype="i8")
+
+ with pytest.raises(ValueError, match=msg):
+ frame_or_series(list(arr), dtype="i8")
+
+ # pre-2.0, when we had NaNs, we silently ignored the integer dtype
+ arr[0] = np.nan
+ # expected = frame_or_series(arr)
+
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
+ with pytest.raises(IntCastingNaNError, match=msg):
+ frame_or_series(arr, dtype="i8")
+
+ exc = IntCastingNaNError
+ if frame_or_series is Series:
+ # TODO: try to align these
+ exc = ValueError
+ msg = "cannot convert float NaN to integer"
+ with pytest.raises(exc, match=msg):
+ # same behavior if we pass list instead of the ndarray
+ frame_or_series(list(arr), dtype="i8")
+
+ # float array that can be losslessly cast to integers
+ arr = np.array([1.0, 2.0], dtype="float64")
+ expected = frame_or_series(arr.astype("i8"))
+
+ obj = frame_or_series(arr, dtype="i8")
+ tm.assert_equal(obj, expected)
+
+ obj = frame_or_series(list(arr), dtype="i8")
+ tm.assert_equal(obj, expected)
+
+ def test_constructor_coerce_float_fail(self, any_int_numpy_dtype):
+ # see gh-15832
+ # Updated: make sure we treat this list the same as we would treat
+ # the equivalent ndarray
+ # GH#49599 pre-2.0 we silently retained float dtype, in 2.0 we raise
+ vals = [1, 2, 3.5]
+
+ msg = "Trying to coerce float values to integer"
+ with pytest.raises(ValueError, match=msg):
+ Series(vals, dtype=any_int_numpy_dtype)
+ with pytest.raises(ValueError, match=msg):
+ Series(np.array(vals), dtype=any_int_numpy_dtype)
+
+ def test_constructor_coerce_float_valid(self, float_numpy_dtype):
+ s = Series([1, 2, 3.5], dtype=float_numpy_dtype)
+ expected = Series([1, 2, 3.5]).astype(float_numpy_dtype)
+ tm.assert_series_equal(s, expected)
+
+ def test_constructor_invalid_coerce_ints_with_float_nan(self, any_int_numpy_dtype):
+ # GH 22585
+ # Updated: make sure we treat this list the same as we would treat the
+ # equivalent ndarray
+ vals = [1, 2, np.nan]
+ # pre-2.0 this would return with a float dtype, in 2.0 we raise
+
+ msg = "cannot convert float NaN to integer"
+ with pytest.raises(ValueError, match=msg):
+ Series(vals, dtype=any_int_numpy_dtype)
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
+ with pytest.raises(IntCastingNaNError, match=msg):
+ Series(np.array(vals), dtype=any_int_numpy_dtype)
+
+ def test_constructor_dtype_no_cast(self, using_copy_on_write):
+ # see gh-1572
+ s = Series([1, 2, 3])
+ s2 = Series(s, dtype=np.int64)
+
+ s2[1] = 5
+ if using_copy_on_write:
+ assert s[1] == 2
+ else:
+ assert s[1] == 5
+
+ def test_constructor_datelike_coercion(self):
+ # GH 9477
+ # incorrectly inferring on dateimelike looking when object dtype is
+ # specified
+ s = Series([Timestamp("20130101"), "NOV"], dtype=object)
+ assert s.iloc[0] == Timestamp("20130101")
+ assert s.iloc[1] == "NOV"
+ assert s.dtype == object
+
+ def test_constructor_datelike_coercion2(self):
+ # the dtype was being reset on the slicing and re-inferred to datetime
+ # even thought the blocks are mixed
+ belly = "216 3T19".split()
+ wing1 = "2T15 4H19".split()
+ wing2 = "416 4T20".split()
+ mat = pd.to_datetime("2016-01-22 2019-09-07".split())
+ df = DataFrame({"wing1": wing1, "wing2": wing2, "mat": mat}, index=belly)
+
+ result = df.loc["3T19"]
+ assert result.dtype == object
+ result = df.loc["216"]
+ assert result.dtype == object
+
+ def test_constructor_mixed_int_and_timestamp(self, frame_or_series):
+ # specifically Timestamp with nanos, not datetimes
+ objs = [Timestamp(9), 10, NaT._value]
+ result = frame_or_series(objs, dtype="M8[ns]")
+
+ expected = frame_or_series([Timestamp(9), Timestamp(10), NaT])
+ tm.assert_equal(result, expected)
+
+ def test_constructor_datetimes_with_nulls(self):
+ # gh-15869
+ for arr in [
+ np.array([None, None, None, None, datetime.now(), None]),
+ np.array([None, None, datetime.now(), None]),
+ ]:
+ result = Series(arr)
+ assert result.dtype == "M8[ns]"
+
+ def test_constructor_dtype_datetime64(self):
+ s = Series(iNaT, dtype="M8[ns]", index=range(5))
+ assert isna(s).all()
+
+ # in theory this should be all nulls, but since
+ # we are not specifying a dtype is ambiguous
+ s = Series(iNaT, index=range(5))
+ assert not isna(s).all()
+
+ s = Series(np.nan, dtype="M8[ns]", index=range(5))
+ assert isna(s).all()
+
+ s = Series([datetime(2001, 1, 2, 0, 0), iNaT], dtype="M8[ns]")
+ assert isna(s[1])
+ assert s.dtype == "M8[ns]"
+
+ s = Series([datetime(2001, 1, 2, 0, 0), np.nan], dtype="M8[ns]")
+ assert isna(s[1])
+ assert s.dtype == "M8[ns]"
+
+ def test_constructor_dtype_datetime64_10(self):
+ # GH3416
+ pydates = [datetime(2013, 1, 1), datetime(2013, 1, 2), datetime(2013, 1, 3)]
+ dates = [np.datetime64(x) for x in pydates]
+
+ ser = Series(dates)
+ assert ser.dtype == "M8[ns]"
+
+ ser.iloc[0] = np.nan
+ assert ser.dtype == "M8[ns]"
+
+ # GH3414 related
+ expected = Series(pydates, dtype="datetime64[ms]")
+
+ result = Series(Series(dates).view(np.int64) / 1000000, dtype="M8[ms]")
+ tm.assert_series_equal(result, expected)
+
+ result = Series(dates, dtype="datetime64[ms]")
+ tm.assert_series_equal(result, expected)
+
+ expected = Series(
+ [NaT, datetime(2013, 1, 2), datetime(2013, 1, 3)], dtype="datetime64[ns]"
+ )
+ result = Series([np.nan] + dates[1:], dtype="datetime64[ns]")
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_dtype_datetime64_11(self):
+ pydates = [datetime(2013, 1, 1), datetime(2013, 1, 2), datetime(2013, 1, 3)]
+ dates = [np.datetime64(x) for x in pydates]
+
+ dts = Series(dates, dtype="datetime64[ns]")
+
+ # valid astype
+ dts.astype("int64")
+
+ # invalid casting
+ msg = r"Converting from datetime64\[ns\] to int32 is not supported"
+ with pytest.raises(TypeError, match=msg):
+ dts.astype("int32")
+
+ # ints are ok
+ # we test with np.int64 to get similar results on
+ # windows / 32-bit platforms
+ result = Series(dts, dtype=np.int64)
+ expected = Series(dts.astype(np.int64))
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_dtype_datetime64_9(self):
+ # invalid dates can be help as object
+ result = Series([datetime(2, 1, 1)])
+ assert result[0] == datetime(2, 1, 1, 0, 0)
+
+ result = Series([datetime(3000, 1, 1)])
+ assert result[0] == datetime(3000, 1, 1, 0, 0)
+
+ def test_constructor_dtype_datetime64_8(self):
+ # don't mix types
+ result = Series([Timestamp("20130101"), 1], index=["a", "b"])
+ assert result["a"] == Timestamp("20130101")
+ assert result["b"] == 1
+
+ def test_constructor_dtype_datetime64_7(self):
+ # GH6529
+ # coerce datetime64 non-ns properly
+ dates = date_range("01-Jan-2015", "01-Dec-2015", freq="M")
+ values2 = dates.view(np.ndarray).astype("datetime64[ns]")
+ expected = Series(values2, index=dates)
+
+ for unit in ["s", "D", "ms", "us", "ns"]:
+ dtype = np.dtype(f"M8[{unit}]")
+ values1 = dates.view(np.ndarray).astype(dtype)
+ result = Series(values1, dates)
+ if unit == "D":
+ # for unit="D" we cast to nearest-supported reso, i.e. "s"
+ dtype = np.dtype("M8[s]")
+ assert result.dtype == dtype
+ tm.assert_series_equal(result, expected.astype(dtype))
+
+ # GH 13876
+ # coerce to non-ns to object properly
+ expected = Series(values2, index=dates, dtype=object)
+ for dtype in ["s", "D", "ms", "us", "ns"]:
+ values1 = dates.view(np.ndarray).astype(f"M8[{dtype}]")
+ result = Series(values1, index=dates, dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ # leave datetime.date alone
+ dates2 = np.array([d.date() for d in dates.to_pydatetime()], dtype=object)
+ series1 = Series(dates2, dates)
+ tm.assert_numpy_array_equal(series1.values, dates2)
+ assert series1.dtype == object
+
+ def test_constructor_dtype_datetime64_6(self):
+ # as of 2.0, these no longer infer datetime64 based on the strings,
+ # matching the Index behavior
+
+ ser = Series([None, NaT, "2013-08-05 15:30:00.000001"])
+ assert ser.dtype == object
+
+ ser = Series([np.nan, NaT, "2013-08-05 15:30:00.000001"])
+ assert ser.dtype == object
+
+ ser = Series([NaT, None, "2013-08-05 15:30:00.000001"])
+ assert ser.dtype == object
+
+ ser = Series([NaT, np.nan, "2013-08-05 15:30:00.000001"])
+ assert ser.dtype == object
+
+ def test_constructor_dtype_datetime64_5(self):
+ # tz-aware (UTC and other tz's)
+ # GH 8411
+ dr = date_range("20130101", periods=3)
+ assert Series(dr).iloc[0].tz is None
+ dr = date_range("20130101", periods=3, tz="UTC")
+ assert str(Series(dr).iloc[0].tz) == "UTC"
+ dr = date_range("20130101", periods=3, tz="US/Eastern")
+ assert str(Series(dr).iloc[0].tz) == "US/Eastern"
+
+ def test_constructor_dtype_datetime64_4(self):
+ # non-convertible
+ s = Series([1479596223000, -1479590, NaT])
+ assert s.dtype == "object"
+ assert s[2] is NaT
+ assert "NaT" in str(s)
+
+ def test_constructor_dtype_datetime64_3(self):
+ # if we passed a NaT it remains
+ s = Series([datetime(2010, 1, 1), datetime(2, 1, 1), NaT])
+ assert s.dtype == "object"
+ assert s[2] is NaT
+ assert "NaT" in str(s)
+
+ def test_constructor_dtype_datetime64_2(self):
+ # if we passed a nan it remains
+ s = Series([datetime(2010, 1, 1), datetime(2, 1, 1), np.nan])
+ assert s.dtype == "object"
+ assert s[2] is np.nan
+ assert "NaN" in str(s)
+
+ def test_constructor_with_datetime_tz(self):
+ # 8260
+ # support datetime64 with tz
+
+ dr = date_range("20130101", periods=3, tz="US/Eastern")
+ s = Series(dr)
+ assert s.dtype.name == "datetime64[ns, US/Eastern]"
+ assert s.dtype == "datetime64[ns, US/Eastern]"
+ assert isinstance(s.dtype, DatetimeTZDtype)
+ assert "datetime64[ns, US/Eastern]" in str(s)
+
+ # export
+ result = s.values
+ assert isinstance(result, np.ndarray)
+ assert result.dtype == "datetime64[ns]"
+
+ exp = DatetimeIndex(result)
+ exp = exp.tz_localize("UTC").tz_convert(tz=s.dt.tz)
+ tm.assert_index_equal(dr, exp)
+
+ # indexing
+ result = s.iloc[0]
+ assert result == Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern")
+ result = s[0]
+ assert result == Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern")
+
+ result = s[Series([True, True, False], index=s.index)]
+ tm.assert_series_equal(result, s[0:2])
+
+ result = s.iloc[0:1]
+ tm.assert_series_equal(result, Series(dr[0:1]))
+
+ # concat
+ result = pd.concat([s.iloc[0:1], s.iloc[1:]])
+ tm.assert_series_equal(result, s)
+
+ # short str
+ assert "datetime64[ns, US/Eastern]" in str(s)
+
+ # formatting with NaT
+ result = s.shift()
+ assert "datetime64[ns, US/Eastern]" in str(result)
+ assert "NaT" in str(result)
+
+ # long str
+ t = Series(date_range("20130101", periods=1000, tz="US/Eastern"))
+ assert "datetime64[ns, US/Eastern]" in str(t)
+
+ result = DatetimeIndex(s, freq="infer")
+ tm.assert_index_equal(result, dr)
+
+ def test_constructor_with_datetime_tz4(self):
+ # inference
+ s = Series(
+ [
+ Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"),
+ Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"),
+ ]
+ )
+ assert s.dtype == "datetime64[ns, US/Pacific]"
+ assert lib.infer_dtype(s, skipna=True) == "datetime64"
+
+ def test_constructor_with_datetime_tz3(self):
+ s = Series(
+ [
+ Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"),
+ Timestamp("2013-01-02 14:00:00-0800", tz="US/Eastern"),
+ ]
+ )
+ assert s.dtype == "object"
+ assert lib.infer_dtype(s, skipna=True) == "datetime"
+
+ def test_constructor_with_datetime_tz2(self):
+ # with all NaT
+ s = Series(NaT, index=[0, 1], dtype="datetime64[ns, US/Eastern]")
+ expected = Series(DatetimeIndex(["NaT", "NaT"], tz="US/Eastern"))
+ tm.assert_series_equal(s, expected)
+
+ def test_constructor_no_partial_datetime_casting(self):
+ # GH#40111
+ vals = [
+ "nan",
+ Timestamp("1990-01-01"),
+ "2015-03-14T16:15:14.123-08:00",
+ "2019-03-04T21:56:32.620-07:00",
+ None,
+ ]
+ ser = Series(vals)
+ assert all(ser[i] is vals[i] for i in range(len(vals)))
+
+ @pytest.mark.parametrize("arr_dtype", [np.int64, np.float64])
+ @pytest.mark.parametrize("kind", ["M", "m"])
+ @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
+ def test_construction_to_datetimelike_unit(self, arr_dtype, kind, unit):
+ # tests all units
+ # gh-19223
+ # TODO: GH#19223 was about .astype, doesn't belong here
+ dtype = f"{kind}8[{unit}]"
+ arr = np.array([1, 2, 3], dtype=arr_dtype)
+ ser = Series(arr)
+ result = ser.astype(dtype)
+
+ expected = Series(arr.astype(dtype))
+
+ if unit in ["ns", "us", "ms", "s"]:
+ assert result.dtype == dtype
+ assert expected.dtype == dtype
+ else:
+ # Otherwise we cast to nearest-supported unit, i.e. seconds
+ assert result.dtype == f"{kind}8[s]"
+ assert expected.dtype == f"{kind}8[s]"
+
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("arg", ["2013-01-01 00:00:00", NaT, np.nan, None])
+ def test_constructor_with_naive_string_and_datetimetz_dtype(self, arg):
+ # GH 17415: With naive string
+ result = Series([arg], dtype="datetime64[ns, CET]")
+ expected = Series(Timestamp(arg)).dt.tz_localize("CET")
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_datetime64_bigendian(self):
+ # GH#30976
+ ms = np.datetime64(1, "ms")
+ arr = np.array([np.datetime64(1, "ms")], dtype=">M8[ms]")
+
+ result = Series(arr)
+ expected = Series([Timestamp(ms)]).astype("M8[ms]")
+ assert expected.dtype == "M8[ms]"
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("interval_constructor", [IntervalIndex, IntervalArray])
+ def test_construction_interval(self, interval_constructor):
+ # construction from interval & array of intervals
+ intervals = interval_constructor.from_breaks(np.arange(3), closed="right")
+ result = Series(intervals)
+ assert result.dtype == "interval[int64, right]"
+ tm.assert_index_equal(Index(result.values), Index(intervals))
+
+ @pytest.mark.parametrize(
+ "data_constructor", [list, np.array], ids=["list", "ndarray[object]"]
+ )
+ def test_constructor_infer_interval(self, data_constructor):
+ # GH 23563: consistent closed results in interval dtype
+ data = [Interval(0, 1), Interval(0, 2), None]
+ result = Series(data_constructor(data))
+ expected = Series(IntervalArray(data))
+ assert result.dtype == "interval[float64, right]"
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "data_constructor", [list, np.array], ids=["list", "ndarray[object]"]
+ )
+ def test_constructor_interval_mixed_closed(self, data_constructor):
+ # GH 23563: mixed closed results in object dtype (not interval dtype)
+ data = [Interval(0, 1, closed="both"), Interval(0, 2, closed="neither")]
+ result = Series(data_constructor(data))
+ assert result.dtype == object
+ assert result.tolist() == data
+
+ def test_construction_consistency(self):
+ # make sure that we are not re-localizing upon construction
+ # GH 14928
+ ser = Series(date_range("20130101", periods=3, tz="US/Eastern"))
+
+ result = Series(ser, dtype=ser.dtype)
+ tm.assert_series_equal(result, ser)
+
+ result = Series(ser.dt.tz_convert("UTC"), dtype=ser.dtype)
+ tm.assert_series_equal(result, ser)
+
+ # Pre-2.0 dt64 values were treated as utc, which was inconsistent
+ # with DatetimeIndex, which treats them as wall times, see GH#33401
+ result = Series(ser.values, dtype=ser.dtype)
+ expected = Series(ser.values).dt.tz_localize(ser.dtype.tz)
+ tm.assert_series_equal(result, expected)
+
+ with tm.assert_produces_warning(None):
+ # one suggested alternative to the deprecated (changed in 2.0) usage
+ middle = Series(ser.values).dt.tz_localize("UTC")
+ result = middle.dt.tz_convert(ser.dtype.tz)
+ tm.assert_series_equal(result, ser)
+
+ with tm.assert_produces_warning(None):
+ # the other suggested alternative to the deprecated usage
+ result = Series(ser.values.view("int64"), dtype=ser.dtype)
+ tm.assert_series_equal(result, ser)
+
+ @pytest.mark.parametrize(
+ "data_constructor", [list, np.array], ids=["list", "ndarray[object]"]
+ )
+ def test_constructor_infer_period(self, data_constructor):
+ data = [Period("2000", "D"), Period("2001", "D"), None]
+ result = Series(data_constructor(data))
+ expected = Series(period_array(data))
+ tm.assert_series_equal(result, expected)
+ assert result.dtype == "Period[D]"
+
+ @pytest.mark.xfail(reason="PeriodDtype Series not supported yet")
+ def test_construct_from_ints_including_iNaT_scalar_period_dtype(self):
+ series = Series([0, 1000, 2000, pd._libs.iNaT], dtype="period[D]")
+
+ val = series[3]
+ assert isna(val)
+
+ series[2] = val
+ assert isna(series[2])
+
+ def test_constructor_period_incompatible_frequency(self):
+ data = [Period("2000", "D"), Period("2001", "A")]
+ result = Series(data)
+ assert result.dtype == object
+ assert result.tolist() == data
+
+ def test_constructor_periodindex(self):
+ # GH7932
+ # converting a PeriodIndex when put in a Series
+
+ pi = period_range("20130101", periods=5, freq="D")
+ s = Series(pi)
+ assert s.dtype == "Period[D]"
+ expected = Series(pi.astype(object))
+ tm.assert_series_equal(s, expected)
+
+ def test_constructor_dict(self):
+ d = {"a": 0.0, "b": 1.0, "c": 2.0}
+
+ result = Series(d)
+ expected = Series(d, index=sorted(d.keys()))
+ tm.assert_series_equal(result, expected)
+
+ result = Series(d, index=["b", "c", "d", "a"])
+ expected = Series([1, 2, np.nan, 0], index=["b", "c", "d", "a"])
+ tm.assert_series_equal(result, expected)
+
+ pidx = tm.makePeriodIndex(100)
+ d = {pidx[0]: 0, pidx[1]: 1}
+ result = Series(d, index=pidx)
+ expected = Series(np.nan, pidx, dtype=np.float64)
+ expected.iloc[0] = 0
+ expected.iloc[1] = 1
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_dict_list_value_explicit_dtype(self):
+ # GH 18625
+ d = {"a": [[2], [3], [4]]}
+ result = Series(d, index=["a"], dtype="object")
+ expected = Series(d, index=["a"])
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_dict_order(self):
+ # GH19018
+ # initialization ordering: by insertion order
+ d = {"b": 1, "a": 0, "c": 2}
+ result = Series(d)
+ expected = Series([1, 0, 2], index=list("bac"))
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_dict_extension(self, ea_scalar_and_dtype, request):
+ ea_scalar, ea_dtype = ea_scalar_and_dtype
+ if isinstance(ea_scalar, Timestamp):
+ mark = pytest.mark.xfail(
+ reason="Construction from dict goes through "
+ "maybe_convert_objects which casts to nano"
+ )
+ request.node.add_marker(mark)
+ d = {"a": ea_scalar}
+ result = Series(d, index=["a"])
+ expected = Series(ea_scalar, index=["a"], dtype=ea_dtype)
+
+ assert result.dtype == ea_dtype
+
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("value", [2, np.nan, None, float("nan")])
+ def test_constructor_dict_nan_key(self, value):
+ # GH 18480
+ d = {1: "a", value: "b", float("nan"): "c", 4: "d"}
+ result = Series(d).sort_values()
+ expected = Series(["a", "b", "c", "d"], index=[1, value, np.nan, 4])
+ tm.assert_series_equal(result, expected)
+
+ # MultiIndex:
+ d = {(1, 1): "a", (2, np.nan): "b", (3, value): "c"}
+ result = Series(d).sort_values()
+ expected = Series(
+ ["a", "b", "c"], index=Index([(1, 1), (2, np.nan), (3, value)])
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_dict_datetime64_index(self):
+ # GH 9456
+
+ dates_as_str = ["1984-02-19", "1988-11-06", "1989-12-03", "1990-03-15"]
+ values = [42544017.198965244, 1234565, 40512335.181958228, -1]
+
+ def create_data(constructor):
+ return dict(zip((constructor(x) for x in dates_as_str), values))
+
+ data_datetime64 = create_data(np.datetime64)
+ data_datetime = create_data(lambda x: datetime.strptime(x, "%Y-%m-%d"))
+ data_Timestamp = create_data(Timestamp)
+
+ expected = Series(values, (Timestamp(x) for x in dates_as_str))
+
+ result_datetime64 = Series(data_datetime64)
+ result_datetime = Series(data_datetime)
+ result_Timestamp = Series(data_Timestamp)
+
+ tm.assert_series_equal(result_datetime64, expected)
+ tm.assert_series_equal(result_datetime, expected)
+ tm.assert_series_equal(result_Timestamp, expected)
+
+ def test_constructor_dict_tuple_indexer(self):
+ # GH 12948
+ data = {(1, 1, None): -1.0}
+ result = Series(data)
+ expected = Series(
+ -1.0, index=MultiIndex(levels=[[1], [1], [np.nan]], codes=[[0], [0], [-1]])
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_mapping(self, non_dict_mapping_subclass):
+ # GH 29788
+ ndm = non_dict_mapping_subclass({3: "three"})
+ result = Series(ndm)
+ expected = Series(["three"], index=[3])
+
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_list_of_tuples(self):
+ data = [(1, 1), (2, 2), (2, 3)]
+ s = Series(data)
+ assert list(s) == data
+
+ def test_constructor_tuple_of_tuples(self):
+ data = ((1, 1), (2, 2), (2, 3))
+ s = Series(data)
+ assert tuple(s) == data
+
+ def test_constructor_dict_of_tuples(self):
+ data = {(1, 2): 3, (None, 5): 6}
+ result = Series(data).sort_values()
+ expected = Series([3, 6], index=MultiIndex.from_tuples([(1, 2), (None, 5)]))
+ tm.assert_series_equal(result, expected)
+
+ # https://github.com/pandas-dev/pandas/issues/22698
+ @pytest.mark.filterwarnings("ignore:elementwise comparison:FutureWarning")
+ def test_fromDict(self):
+ data = {"a": 0, "b": 1, "c": 2, "d": 3}
+
+ series = Series(data)
+ tm.assert_is_sorted(series.index)
+
+ data = {"a": 0, "b": "1", "c": "2", "d": datetime.now()}
+ series = Series(data)
+ assert series.dtype == np.object_
+
+ data = {"a": 0, "b": "1", "c": "2", "d": "3"}
+ series = Series(data)
+ assert series.dtype == np.object_
+
+ data = {"a": "0", "b": "1"}
+ series = Series(data, dtype=float)
+ assert series.dtype == np.float64
+
+ def test_fromValue(self, datetime_series):
+ nans = Series(np.nan, index=datetime_series.index, dtype=np.float64)
+ assert nans.dtype == np.float64
+ assert len(nans) == len(datetime_series)
+
+ strings = Series("foo", index=datetime_series.index)
+ assert strings.dtype == np.object_
+ assert len(strings) == len(datetime_series)
+
+ d = datetime.now()
+ dates = Series(d, index=datetime_series.index)
+ assert dates.dtype == "M8[us]"
+ assert len(dates) == len(datetime_series)
+
+ # GH12336
+ # Test construction of categorical series from value
+ categorical = Series(0, index=datetime_series.index, dtype="category")
+ expected = Series(0, index=datetime_series.index).astype("category")
+ assert categorical.dtype == "category"
+ assert len(categorical) == len(datetime_series)
+ tm.assert_series_equal(categorical, expected)
+
+ def test_constructor_dtype_timedelta64(self):
+ # basic
+ td = Series([timedelta(days=i) for i in range(3)])
+ assert td.dtype == "timedelta64[ns]"
+
+ td = Series([timedelta(days=1)])
+ assert td.dtype == "timedelta64[ns]"
+
+ td = Series([timedelta(days=1), timedelta(days=2), np.timedelta64(1, "s")])
+
+ assert td.dtype == "timedelta64[ns]"
+
+ # mixed with NaT
+ td = Series([timedelta(days=1), NaT], dtype="m8[ns]")
+ assert td.dtype == "timedelta64[ns]"
+
+ td = Series([timedelta(days=1), np.nan], dtype="m8[ns]")
+ assert td.dtype == "timedelta64[ns]"
+
+ td = Series([np.timedelta64(300000000), NaT], dtype="m8[ns]")
+ assert td.dtype == "timedelta64[ns]"
+
+ # improved inference
+ # GH5689
+ td = Series([np.timedelta64(300000000), NaT])
+ assert td.dtype == "timedelta64[ns]"
+
+ # because iNaT is int, not coerced to timedelta
+ td = Series([np.timedelta64(300000000), iNaT])
+ assert td.dtype == "object"
+
+ td = Series([np.timedelta64(300000000), np.nan])
+ assert td.dtype == "timedelta64[ns]"
+
+ td = Series([NaT, np.timedelta64(300000000)])
+ assert td.dtype == "timedelta64[ns]"
+
+ td = Series([np.timedelta64(1, "s")])
+ assert td.dtype == "timedelta64[ns]"
+
+ # valid astype
+ td.astype("int64")
+
+ # invalid casting
+ msg = r"Converting from timedelta64\[ns\] to int32 is not supported"
+ with pytest.raises(TypeError, match=msg):
+ td.astype("int32")
+
+ # this is an invalid casting
+ msg = "|".join(
+ [
+ "Could not convert object to NumPy timedelta",
+ "Could not convert 'foo' to NumPy timedelta",
+ ]
+ )
+ with pytest.raises(ValueError, match=msg):
+ Series([timedelta(days=1), "foo"], dtype="m8[ns]")
+
+ # leave as object here
+ td = Series([timedelta(days=i) for i in range(3)] + ["foo"])
+ assert td.dtype == "object"
+
+ # as of 2.0, these no longer infer timedelta64 based on the strings,
+ # matching Index behavior
+ ser = Series([None, NaT, "1 Day"])
+ assert ser.dtype == object
+
+ ser = Series([np.nan, NaT, "1 Day"])
+ assert ser.dtype == object
+
+ ser = Series([NaT, None, "1 Day"])
+ assert ser.dtype == object
+
+ ser = Series([NaT, np.nan, "1 Day"])
+ assert ser.dtype == object
+
+ # GH 16406
+ def test_constructor_mixed_tz(self):
+ s = Series([Timestamp("20130101"), Timestamp("20130101", tz="US/Eastern")])
+ expected = Series(
+ [Timestamp("20130101"), Timestamp("20130101", tz="US/Eastern")],
+ dtype="object",
+ )
+ tm.assert_series_equal(s, expected)
+
+ def test_NaT_scalar(self):
+ series = Series([0, 1000, 2000, iNaT], dtype="M8[ns]")
+
+ val = series[3]
+ assert isna(val)
+
+ series[2] = val
+ assert isna(series[2])
+
+ def test_NaT_cast(self):
+ # GH10747
+ result = Series([np.nan]).astype("M8[ns]")
+ expected = Series([NaT])
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_name_hashable(self):
+ for n in [777, 777.0, "name", datetime(2001, 11, 11), (1,), "\u05D0"]:
+ for data in [[1, 2, 3], np.ones(3), {"a": 0, "b": 1}]:
+ s = Series(data, name=n)
+ assert s.name == n
+
+ def test_constructor_name_unhashable(self):
+ msg = r"Series\.name must be a hashable type"
+ for n in [["name_list"], np.ones(2), {1: 2}]:
+ for data in [["name_list"], np.ones(2), {1: 2}]:
+ with pytest.raises(TypeError, match=msg):
+ Series(data, name=n)
+
+ def test_auto_conversion(self):
+ series = Series(list(date_range("1/1/2000", periods=10)))
+ assert series.dtype == "M8[ns]"
+
+ def test_convert_non_ns(self):
+ # convert from a numpy array of non-ns timedelta64
+ arr = np.array([1, 2, 3], dtype="timedelta64[s]")
+ ser = Series(arr)
+ assert ser.dtype == arr.dtype
+
+ tdi = timedelta_range("00:00:01", periods=3, freq="s").as_unit("s")
+ expected = Series(tdi)
+ assert expected.dtype == arr.dtype
+ tm.assert_series_equal(ser, expected)
+
+ # convert from a numpy array of non-ns datetime64
+ arr = np.array(
+ ["2013-01-01", "2013-01-02", "2013-01-03"], dtype="datetime64[D]"
+ )
+ ser = Series(arr)
+ expected = Series(date_range("20130101", periods=3, freq="D"), dtype="M8[s]")
+ assert expected.dtype == "M8[s]"
+ tm.assert_series_equal(ser, expected)
+
+ arr = np.array(
+ ["2013-01-01 00:00:01", "2013-01-01 00:00:02", "2013-01-01 00:00:03"],
+ dtype="datetime64[s]",
+ )
+ ser = Series(arr)
+ expected = Series(
+ date_range("20130101 00:00:01", periods=3, freq="s"), dtype="M8[s]"
+ )
+ assert expected.dtype == "M8[s]"
+ tm.assert_series_equal(ser, expected)
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ date_range("1/1/2000", periods=10),
+ timedelta_range("1 day", periods=10),
+ period_range("2000-Q1", periods=10, freq="Q"),
+ ],
+ ids=lambda x: type(x).__name__,
+ )
+ def test_constructor_cant_cast_datetimelike(self, index):
+ # floats are not ok
+ # strip Index to convert PeriodIndex -> Period
+ # We don't care whether the error message says
+ # PeriodIndex or PeriodArray
+ msg = f"Cannot cast {type(index).__name__.rstrip('Index')}.*? to "
+
+ with pytest.raises(TypeError, match=msg):
+ Series(index, dtype=float)
+
+ # ints are ok
+ # we test with np.int64 to get similar results on
+ # windows / 32-bit platforms
+ result = Series(index, dtype=np.int64)
+ expected = Series(index.astype(np.int64))
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "index",
+ [
+ date_range("1/1/2000", periods=10),
+ timedelta_range("1 day", periods=10),
+ period_range("2000-Q1", periods=10, freq="Q"),
+ ],
+ ids=lambda x: type(x).__name__,
+ )
+ def test_constructor_cast_object(self, index):
+ s = Series(index, dtype=object)
+ exp = Series(index).astype(object)
+ tm.assert_series_equal(s, exp)
+
+ s = Series(Index(index, dtype=object), dtype=object)
+ exp = Series(index).astype(object)
+ tm.assert_series_equal(s, exp)
+
+ s = Series(index.astype(object), dtype=object)
+ exp = Series(index).astype(object)
+ tm.assert_series_equal(s, exp)
+
+ @pytest.mark.parametrize("dtype", [np.datetime64, np.timedelta64])
+ def test_constructor_generic_timestamp_no_frequency(self, dtype, request):
+ # see gh-15524, gh-15987
+ msg = "dtype has no unit. Please pass in"
+
+ if np.dtype(dtype).name not in ["timedelta64", "datetime64"]:
+ mark = pytest.mark.xfail(reason="GH#33890 Is assigned ns unit")
+ request.node.add_marker(mark)
+
+ with pytest.raises(ValueError, match=msg):
+ Series([], dtype=dtype)
+
+ @pytest.mark.parametrize("unit", ["ps", "as", "fs", "Y", "M", "W", "D", "h", "m"])
+ @pytest.mark.parametrize("kind", ["m", "M"])
+ def test_constructor_generic_timestamp_bad_frequency(self, kind, unit):
+ # see gh-15524, gh-15987
+ # as of 2.0 we raise on any non-supported unit rather than silently
+ # cast to nanos; previously we only raised for frequencies higher
+ # than ns
+ dtype = f"{kind}8[{unit}]"
+
+ msg = "dtype=.* is not supported. Supported resolutions are"
+ with pytest.raises(TypeError, match=msg):
+ Series([], dtype=dtype)
+
+ with pytest.raises(TypeError, match=msg):
+ # pre-2.0 the DataFrame cast raised but the Series case did not
+ DataFrame([[0]], dtype=dtype)
+
+ @pytest.mark.parametrize("dtype", [None, "uint8", "category"])
+ def test_constructor_range_dtype(self, dtype):
+ # GH 16804
+ expected = Series([0, 1, 2, 3, 4], dtype=dtype or "int64")
+ result = Series(range(5), dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_range_overflows(self):
+ # GH#30173 range objects that overflow int64
+ rng = range(2**63, 2**63 + 4)
+ ser = Series(rng)
+ expected = Series(list(rng))
+ tm.assert_series_equal(ser, expected)
+ assert list(ser) == list(rng)
+ assert ser.dtype == np.uint64
+
+ rng2 = range(2**63 + 4, 2**63, -1)
+ ser2 = Series(rng2)
+ expected2 = Series(list(rng2))
+ tm.assert_series_equal(ser2, expected2)
+ assert list(ser2) == list(rng2)
+ assert ser2.dtype == np.uint64
+
+ rng3 = range(-(2**63), -(2**63) - 4, -1)
+ ser3 = Series(rng3)
+ expected3 = Series(list(rng3))
+ tm.assert_series_equal(ser3, expected3)
+ assert list(ser3) == list(rng3)
+ assert ser3.dtype == object
+
+ rng4 = range(2**73, 2**73 + 4)
+ ser4 = Series(rng4)
+ expected4 = Series(list(rng4))
+ tm.assert_series_equal(ser4, expected4)
+ assert list(ser4) == list(rng4)
+ assert ser4.dtype == object
+
+ def test_constructor_tz_mixed_data(self):
+ # GH 13051
+ dt_list = [
+ Timestamp("2016-05-01 02:03:37"),
+ Timestamp("2016-04-30 19:03:37-0700", tz="US/Pacific"),
+ ]
+ result = Series(dt_list)
+ expected = Series(dt_list, dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("pydt", [True, False])
+ def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture, pydt):
+ # GH#25843, GH#41555, GH#33401
+ tz = tz_aware_fixture
+ ts = Timestamp("2019", tz=tz)
+ if pydt:
+ ts = ts.to_pydatetime()
+
+ msg = (
+ "Cannot convert timezone-aware data to timezone-naive dtype. "
+ r"Use pd.Series\(values\).dt.tz_localize\(None\) instead."
+ )
+ with pytest.raises(ValueError, match=msg):
+ Series([ts], dtype="datetime64[ns]")
+
+ with pytest.raises(ValueError, match=msg):
+ Series(np.array([ts], dtype=object), dtype="datetime64[ns]")
+
+ with pytest.raises(ValueError, match=msg):
+ Series({0: ts}, dtype="datetime64[ns]")
+
+ msg = "Cannot unbox tzaware Timestamp to tznaive dtype"
+ with pytest.raises(TypeError, match=msg):
+ Series(ts, index=[0], dtype="datetime64[ns]")
+
+ def test_constructor_datetime64(self):
+ rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s")
+ dates = np.asarray(rng)
+
+ series = Series(dates)
+ assert np.issubdtype(series.dtype, np.dtype("M8[ns]"))
+
+ def test_constructor_datetimelike_scalar_to_string_dtype(
+ self, nullable_string_dtype
+ ):
+ # https://github.com/pandas-dev/pandas/pull/33846
+ result = Series("M", index=[1, 2, 3], dtype=nullable_string_dtype)
+ expected = Series(["M", "M", "M"], index=[1, 2, 3], dtype=nullable_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "values",
+ [
+ [np.datetime64("2012-01-01"), np.datetime64("2013-01-01")],
+ ["2012-01-01", "2013-01-01"],
+ ],
+ )
+ def test_constructor_sparse_datetime64(self, values):
+ # https://github.com/pandas-dev/pandas/issues/35762
+ dtype = pd.SparseDtype("datetime64[ns]")
+ result = Series(values, dtype=dtype)
+ arr = pd.arrays.SparseArray(values, dtype=dtype)
+ expected = Series(arr)
+ tm.assert_series_equal(result, expected)
+
+ def test_construction_from_ordered_collection(self):
+ # https://github.com/pandas-dev/pandas/issues/36044
+ result = Series({"a": 1, "b": 2}.keys())
+ expected = Series(["a", "b"])
+ tm.assert_series_equal(result, expected)
+
+ result = Series({"a": 1, "b": 2}.values())
+ expected = Series([1, 2])
+ tm.assert_series_equal(result, expected)
+
+ def test_construction_from_large_int_scalar_no_overflow(self):
+ # https://github.com/pandas-dev/pandas/issues/36291
+ n = 1_000_000_000_000_000_000_000
+ result = Series(n, index=[0])
+ expected = Series(n)
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_list_of_periods_infers_period_dtype(self):
+ series = Series(list(period_range("2000-01-01", periods=10, freq="D")))
+ assert series.dtype == "Period[D]"
+
+ series = Series(
+ [Period("2011-01-01", freq="D"), Period("2011-02-01", freq="D")]
+ )
+ assert series.dtype == "Period[D]"
+
+ def test_constructor_subclass_dict(self, dict_subclass):
+ data = dict_subclass((x, 10.0 * x) for x in range(10))
+ series = Series(data)
+ expected = Series(dict(data.items()))
+ tm.assert_series_equal(series, expected)
+
+ def test_constructor_ordereddict(self):
+ # GH3283
+ data = OrderedDict(
+ (f"col{i}", np.random.default_rng(2).random()) for i in range(12)
+ )
+
+ series = Series(data)
+ expected = Series(list(data.values()), list(data.keys()))
+ tm.assert_series_equal(series, expected)
+
+ # Test with subclass
+ class A(OrderedDict):
+ pass
+
+ series = Series(A(data))
+ tm.assert_series_equal(series, expected)
+
+ def test_constructor_dict_multiindex(self):
+ d = {("a", "a"): 0.0, ("b", "a"): 1.0, ("b", "c"): 2.0}
+ _d = sorted(d.items())
+ result = Series(d)
+ expected = Series(
+ [x[1] for x in _d], index=MultiIndex.from_tuples([x[0] for x in _d])
+ )
+ tm.assert_series_equal(result, expected)
+
+ d["z"] = 111.0
+ _d.insert(0, ("z", d["z"]))
+ result = Series(d)
+ expected = Series(
+ [x[1] for x in _d], index=Index([x[0] for x in _d], tupleize_cols=False)
+ )
+ result = result.reindex(index=expected.index)
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_dict_multiindex_reindex_flat(self):
+ # construction involves reindexing with a MultiIndex corner case
+ data = {("i", "i"): 0, ("i", "j"): 1, ("j", "i"): 2, "j": np.nan}
+ expected = Series(data)
+
+ result = Series(expected[:-1].to_dict(), index=expected.index)
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_dict_timedelta_index(self):
+ # GH #12169 : Resample category data with timedelta index
+ # construct Series from dict as data and TimedeltaIndex as index
+ # will result NaN in result Series data
+ expected = Series(
+ data=["A", "B", "C"], index=pd.to_timedelta([0, 10, 20], unit="s")
+ )
+
+ result = Series(
+ data={
+ pd.to_timedelta(0, unit="s"): "A",
+ pd.to_timedelta(10, unit="s"): "B",
+ pd.to_timedelta(20, unit="s"): "C",
+ },
+ index=pd.to_timedelta([0, 10, 20], unit="s"),
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_infer_index_tz(self):
+ values = [188.5, 328.25]
+ tzinfo = tzoffset(None, 7200)
+ index = [
+ datetime(2012, 5, 11, 11, tzinfo=tzinfo),
+ datetime(2012, 5, 11, 12, tzinfo=tzinfo),
+ ]
+ series = Series(data=values, index=index)
+
+ assert series.index.tz == tzinfo
+
+ # it works! GH#2443
+ repr(series.index[0])
+
+ def test_constructor_with_pandas_dtype(self):
+ # going through 2D->1D path
+ vals = [(1,), (2,), (3,)]
+ ser = Series(vals)
+ dtype = ser.array.dtype # NumpyEADtype
+ ser2 = Series(vals, dtype=dtype)
+ tm.assert_series_equal(ser, ser2)
+
+ def test_constructor_int_dtype_missing_values(self):
+ # GH#43017
+ result = Series(index=[0], dtype="int64")
+ expected = Series(np.nan, index=[0], dtype="float64")
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_bool_dtype_missing_values(self):
+ # GH#43018
+ result = Series(index=[0], dtype="bool")
+ expected = Series(True, index=[0], dtype="bool")
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_int64_dtype(self, any_int_dtype):
+ # GH#44923
+ result = Series(["0", "1", "2"], dtype=any_int_dtype)
+ expected = Series([0, 1, 2], dtype=any_int_dtype)
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_raise_on_lossy_conversion_of_strings(self):
+ # GH#44923
+ with pytest.raises(
+ ValueError, match="string values cannot be losslessly cast to int8"
+ ):
+ Series(["128"], dtype="int8")
+
+ def test_constructor_dtype_timedelta_alternative_construct(self):
+ # GH#35465
+ result = Series([1000000, 200000, 3000000], dtype="timedelta64[ns]")
+ expected = Series(pd.to_timedelta([1000000, 200000, 3000000], unit="ns"))
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.xfail(
+ reason="Not clear what the correct expected behavior should be with "
+ "integers now that we support non-nano. ATM (2022-10-08) we treat ints "
+ "as nanoseconds, then cast to the requested dtype. xref #48312"
+ )
+ def test_constructor_dtype_timedelta_ns_s(self):
+ # GH#35465
+ result = Series([1000000, 200000, 3000000], dtype="timedelta64[ns]")
+ expected = Series([1000000, 200000, 3000000], dtype="timedelta64[s]")
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.xfail(
+ reason="Not clear what the correct expected behavior should be with "
+ "integers now that we support non-nano. ATM (2022-10-08) we treat ints "
+ "as nanoseconds, then cast to the requested dtype. xref #48312"
+ )
+ def test_constructor_dtype_timedelta_ns_s_astype_int64(self):
+ # GH#35465
+ result = Series([1000000, 200000, 3000000], dtype="timedelta64[ns]").astype(
+ "int64"
+ )
+ expected = Series([1000000, 200000, 3000000], dtype="timedelta64[s]").astype(
+ "int64"
+ )
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.filterwarnings(
+ "ignore:elementwise comparison failed:DeprecationWarning"
+ )
+ @pytest.mark.parametrize("func", [Series, DataFrame, Index, pd.array])
+ def test_constructor_mismatched_null_nullable_dtype(
+ self, func, any_numeric_ea_dtype
+ ):
+ # GH#44514
+ msg = "|".join(
+ [
+ "cannot safely cast non-equivalent object",
+ r"int\(\) argument must be a string, a bytes-like object "
+ "or a (real )?number",
+ r"Cannot cast array data from dtype\('O'\) to dtype\('float64'\) "
+ "according to the rule 'safe'",
+ "object cannot be converted to a FloatingDtype",
+ "'values' contains non-numeric NA",
+ ]
+ )
+
+ for null in tm.NP_NAT_OBJECTS + [NaT]:
+ with pytest.raises(TypeError, match=msg):
+ func([null, 1.0, 3.0], dtype=any_numeric_ea_dtype)
+
+ def test_series_constructor_ea_int_from_bool(self):
+ # GH#42137
+ result = Series([True, False, True, pd.NA], dtype="Int64")
+ expected = Series([1, 0, 1, pd.NA], dtype="Int64")
+ tm.assert_series_equal(result, expected)
+
+ result = Series([True, False, True], dtype="Int64")
+ expected = Series([1, 0, 1], dtype="Int64")
+ tm.assert_series_equal(result, expected)
+
+ def test_series_constructor_ea_int_from_string_bool(self):
+ # GH#42137
+ with pytest.raises(ValueError, match="invalid literal"):
+ Series(["True", "False", "True", pd.NA], dtype="Int64")
+
+ @pytest.mark.parametrize("val", [1, 1.0])
+ def test_series_constructor_overflow_uint_ea(self, val):
+ # GH#38798
+ max_val = np.iinfo(np.uint64).max - 1
+ result = Series([max_val, val], dtype="UInt64")
+ expected = Series(np.array([max_val, 1], dtype="uint64"), dtype="UInt64")
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("val", [1, 1.0])
+ def test_series_constructor_overflow_uint_ea_with_na(self, val):
+ # GH#38798
+ max_val = np.iinfo(np.uint64).max - 1
+ result = Series([max_val, val, pd.NA], dtype="UInt64")
+ expected = Series(
+ IntegerArray(
+ np.array([max_val, 1, 0], dtype="uint64"),
+ np.array([0, 0, 1], dtype=np.bool_),
+ )
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_series_constructor_overflow_uint_with_nan(self):
+ # GH#38798
+ max_val = np.iinfo(np.uint64).max - 1
+ result = Series([max_val, np.nan], dtype="UInt64")
+ expected = Series(
+ IntegerArray(
+ np.array([max_val, 1], dtype="uint64"),
+ np.array([0, 1], dtype=np.bool_),
+ )
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_series_constructor_ea_all_na(self):
+ # GH#38798
+ result = Series([np.nan, np.nan], dtype="UInt64")
+ expected = Series(
+ IntegerArray(
+ np.array([1, 1], dtype="uint64"),
+ np.array([1, 1], dtype=np.bool_),
+ )
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_series_from_index_dtype_equal_does_not_copy(self):
+ # GH#52008
+ idx = Index([1, 2, 3])
+ expected = idx.copy(deep=True)
+ ser = Series(idx, dtype="int64")
+ ser.iloc[0] = 100
+ tm.assert_index_equal(idx, expected)
+
+ def test_series_string_inference(self):
+ # GH#54430
+ pytest.importorskip("pyarrow")
+ dtype = "string[pyarrow_numpy]"
+ expected = Series(["a", "b"], dtype=dtype)
+ with pd.option_context("future.infer_string", True):
+ ser = Series(["a", "b"])
+ tm.assert_series_equal(ser, expected)
+
+ expected = Series(["a", 1], dtype="object")
+ with pd.option_context("future.infer_string", True):
+ ser = Series(["a", 1])
+ tm.assert_series_equal(ser, expected)
+
+ @pytest.mark.parametrize("na_value", [None, np.nan, pd.NA])
+ def test_series_string_with_na_inference(self, na_value):
+ # GH#54430
+ pytest.importorskip("pyarrow")
+ dtype = "string[pyarrow_numpy]"
+ expected = Series(["a", na_value], dtype=dtype)
+ with pd.option_context("future.infer_string", True):
+ ser = Series(["a", na_value])
+ tm.assert_series_equal(ser, expected)
+
+ def test_series_string_inference_scalar(self):
+ # GH#54430
+ pytest.importorskip("pyarrow")
+ expected = Series("a", index=[1], dtype="string[pyarrow_numpy]")
+ with pd.option_context("future.infer_string", True):
+ ser = Series("a", index=[1])
+ tm.assert_series_equal(ser, expected)
+
+ def test_series_string_inference_array_string_dtype(self):
+ # GH#54496
+ pytest.importorskip("pyarrow")
+ expected = Series(["a", "b"], dtype="string[pyarrow_numpy]")
+ with pd.option_context("future.infer_string", True):
+ ser = Series(np.array(["a", "b"]))
+ tm.assert_series_equal(ser, expected)
+
+ def test_series_string_inference_storage_definition(self):
+ # GH#54793
+ pytest.importorskip("pyarrow")
+ expected = Series(["a", "b"], dtype="string[pyarrow_numpy]")
+ with pd.option_context("future.infer_string", True):
+ result = Series(["a", "b"], dtype="string")
+ tm.assert_series_equal(result, expected)
+
+ def test_series_constructor_infer_string_scalar(self):
+ # GH#55537
+ with pd.option_context("future.infer_string", True):
+ ser = Series("a", index=[1, 2], dtype="string[python]")
+ expected = Series(["a", "a"], index=[1, 2], dtype="string[python]")
+ tm.assert_series_equal(ser, expected)
+ assert ser.dtype.storage == "python"
+
+ def test_series_string_inference_na_first(self):
+ # GH#55655
+ pytest.importorskip("pyarrow")
+ expected = Series([pd.NA, "b"], dtype="string[pyarrow_numpy]")
+ with pd.option_context("future.infer_string", True):
+ result = Series([pd.NA, "b"])
+ tm.assert_series_equal(result, expected)
+
+
+class TestSeriesConstructorIndexCoercion:
+ def test_series_constructor_datetimelike_index_coercion(self):
+ idx = tm.makeDateIndex(10000)
+ ser = Series(
+ np.random.default_rng(2).standard_normal(len(idx)), idx.astype(object)
+ )
+ # as of 2.0, we no longer silently cast the object-dtype index
+ # to DatetimeIndex GH#39307, GH#23598
+ assert not isinstance(ser.index, DatetimeIndex)
+
+ def test_series_constructor_infer_multiindex(self):
+ index_lists = [["a", "a", "b", "b"], ["x", "y", "x", "y"]]
+
+ multi = Series(1.0, index=[np.array(x) for x in index_lists])
+ assert isinstance(multi.index, MultiIndex)
+
+ multi = Series(1.0, index=index_lists)
+ assert isinstance(multi.index, MultiIndex)
+
+ multi = Series(range(4), index=index_lists)
+ assert isinstance(multi.index, MultiIndex)
+
+
+class TestSeriesConstructorInternals:
+ def test_constructor_no_pandas_array(self, using_array_manager):
+ ser = Series([1, 2, 3])
+ result = Series(ser.array)
+ tm.assert_series_equal(ser, result)
+ if not using_array_manager:
+ assert isinstance(result._mgr.blocks[0], NumpyBlock)
+ assert result._mgr.blocks[0].is_numeric
+
+ @td.skip_array_manager_invalid_test
+ def test_from_array(self):
+ result = Series(pd.array(["1H", "2H"], dtype="timedelta64[ns]"))
+ assert result._mgr.blocks[0].is_extension is False
+
+ result = Series(pd.array(["2015"], dtype="datetime64[ns]"))
+ assert result._mgr.blocks[0].is_extension is False
+
+ @td.skip_array_manager_invalid_test
+ def test_from_list_dtype(self):
+ result = Series(["1H", "2H"], dtype="timedelta64[ns]")
+ assert result._mgr.blocks[0].is_extension is False
+
+ result = Series(["2015"], dtype="datetime64[ns]")
+ assert result._mgr.blocks[0].is_extension is False
+
+
+def test_constructor(rand_series_with_duplicate_datetimeindex):
+ dups = rand_series_with_duplicate_datetimeindex
+ assert isinstance(dups, Series)
+ assert isinstance(dups.index, DatetimeIndex)
+
+
+@pytest.mark.parametrize(
+ "input_dict,expected",
+ [
+ ({0: 0}, np.array([[0]], dtype=np.int64)),
+ ({"a": "a"}, np.array([["a"]], dtype=object)),
+ ({1: 1}, np.array([[1]], dtype=np.int64)),
+ ],
+)
+def test_numpy_array(input_dict, expected):
+ result = np.array([Series(input_dict)])
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_index_ordered_dict_keys():
+ # GH 22077
+
+ param_index = OrderedDict(
+ [
+ ((("a", "b"), ("c", "d")), 1),
+ ((("a", None), ("c", "d")), 2),
+ ]
+ )
+ series = Series([1, 2], index=param_index.keys())
+ expected = Series(
+ [1, 2],
+ index=MultiIndex.from_tuples(
+ [(("a", "b"), ("c", "d")), (("a", None), ("c", "d"))]
+ ),
+ )
+ tm.assert_series_equal(series, expected)
+
+
+@pytest.mark.parametrize(
+ "input_list",
+ [
+ [1, complex("nan"), 2],
+ [1 + 1j, complex("nan"), 2 + 2j],
+ ],
+)
+def test_series_with_complex_nan(input_list):
+ # GH#53627
+ ser = Series(input_list)
+ result = Series(ser.array)
+ assert ser.dtype == "complex128"
+ tm.assert_series_equal(ser, result)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_cumulative.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_cumulative.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6f7b2a5e69e0a97e2f898c6a665372ba3ec2a6b
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_cumulative.py
@@ -0,0 +1,157 @@
+"""
+Tests for Series cumulative operations.
+
+See also
+--------
+tests.frame.test_cumulative
+"""
+
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+methods = {
+ "cumsum": np.cumsum,
+ "cumprod": np.cumprod,
+ "cummin": np.minimum.accumulate,
+ "cummax": np.maximum.accumulate,
+}
+
+
+class TestSeriesCumulativeOps:
+ @pytest.mark.parametrize("func", [np.cumsum, np.cumprod])
+ def test_datetime_series(self, datetime_series, func):
+ tm.assert_numpy_array_equal(
+ func(datetime_series).values,
+ func(np.array(datetime_series)),
+ check_dtype=True,
+ )
+
+ # with missing values
+ ts = datetime_series.copy()
+ ts[::2] = np.nan
+
+ result = func(ts)[1::2]
+ expected = func(np.array(ts.dropna()))
+
+ tm.assert_numpy_array_equal(result.values, expected, check_dtype=False)
+
+ @pytest.mark.parametrize("method", ["cummin", "cummax"])
+ def test_cummin_cummax(self, datetime_series, method):
+ ufunc = methods[method]
+
+ result = getattr(datetime_series, method)().values
+ expected = ufunc(np.array(datetime_series))
+
+ tm.assert_numpy_array_equal(result, expected)
+ ts = datetime_series.copy()
+ ts[::2] = np.nan
+ result = getattr(ts, method)()[1::2]
+ expected = ufunc(ts.dropna())
+
+ result.index = result.index._with_freq(None)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "ts",
+ [
+ pd.Timedelta(0),
+ pd.Timestamp("1999-12-31"),
+ pd.Timestamp("1999-12-31").tz_localize("US/Pacific"),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "method, skipna, exp_tdi",
+ [
+ ["cummax", True, ["NaT", "2 days", "NaT", "2 days", "NaT", "3 days"]],
+ ["cummin", True, ["NaT", "2 days", "NaT", "1 days", "NaT", "1 days"]],
+ [
+ "cummax",
+ False,
+ ["NaT", "NaT", "NaT", "NaT", "NaT", "NaT"],
+ ],
+ [
+ "cummin",
+ False,
+ ["NaT", "NaT", "NaT", "NaT", "NaT", "NaT"],
+ ],
+ ],
+ )
+ def test_cummin_cummax_datetimelike(self, ts, method, skipna, exp_tdi):
+ # with ts==pd.Timedelta(0), we are testing td64; with naive Timestamp
+ # we are testing datetime64[ns]; with Timestamp[US/Pacific]
+ # we are testing dt64tz
+ tdi = pd.to_timedelta(["NaT", "2 days", "NaT", "1 days", "NaT", "3 days"])
+ ser = pd.Series(tdi + ts)
+
+ exp_tdi = pd.to_timedelta(exp_tdi)
+ expected = pd.Series(exp_tdi + ts)
+ result = getattr(ser, method)(skipna=skipna)
+ tm.assert_series_equal(expected, result)
+
+ @pytest.mark.parametrize(
+ "func, exp",
+ [
+ ("cummin", pd.Period("2012-1-1", freq="D")),
+ ("cummax", pd.Period("2012-1-2", freq="D")),
+ ],
+ )
+ def test_cummin_cummax_period(self, func, exp):
+ # GH#28385
+ ser = pd.Series(
+ [pd.Period("2012-1-1", freq="D"), pd.NaT, pd.Period("2012-1-2", freq="D")]
+ )
+ result = getattr(ser, func)(skipna=False)
+ expected = pd.Series([pd.Period("2012-1-1", freq="D"), pd.NaT, pd.NaT])
+ tm.assert_series_equal(result, expected)
+
+ result = getattr(ser, func)(skipna=True)
+ expected = pd.Series([pd.Period("2012-1-1", freq="D"), pd.NaT, exp])
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "arg",
+ [
+ [False, False, False, True, True, False, False],
+ [False, False, False, False, False, False, False],
+ ],
+ )
+ @pytest.mark.parametrize(
+ "func", [lambda x: x, lambda x: ~x], ids=["identity", "inverse"]
+ )
+ @pytest.mark.parametrize("method", methods.keys())
+ def test_cummethods_bool(self, arg, func, method):
+ # GH#6270
+ # checking Series method vs the ufunc applied to the values
+
+ ser = func(pd.Series(arg))
+ ufunc = methods[method]
+
+ exp_vals = ufunc(ser.values)
+ expected = pd.Series(exp_vals)
+
+ result = getattr(ser, method)()
+
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "method, expected",
+ [
+ ["cumsum", pd.Series([0, 1, np.nan, 1], dtype=object)],
+ ["cumprod", pd.Series([False, 0, np.nan, 0])],
+ ["cummin", pd.Series([False, False, np.nan, False])],
+ ["cummax", pd.Series([False, True, np.nan, True])],
+ ],
+ )
+ def test_cummethods_bool_in_object_dtype(self, method, expected):
+ ser = pd.Series([False, True, np.nan, False])
+ result = getattr(ser, method)()
+ tm.assert_series_equal(result, expected)
+
+ def test_cumprod_timedelta(self):
+ # GH#48111
+ ser = pd.Series([pd.Timedelta(days=1), pd.Timedelta(days=3)])
+ with pytest.raises(TypeError, match="cumprod not supported for Timedelta"):
+ ser.cumprod()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_iteration.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_iteration.py
new file mode 100644
index 0000000000000000000000000000000000000000..edc82455234bba0203d817417e7bf122c876bfff
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_iteration.py
@@ -0,0 +1,35 @@
+class TestIteration:
+ def test_keys(self, datetime_series):
+ assert datetime_series.keys() is datetime_series.index
+
+ def test_iter_datetimes(self, datetime_series):
+ for i, val in enumerate(datetime_series):
+ # pylint: disable-next=unnecessary-list-index-lookup
+ assert val == datetime_series.iloc[i]
+
+ def test_iter_strings(self, string_series):
+ for i, val in enumerate(string_series):
+ # pylint: disable-next=unnecessary-list-index-lookup
+ assert val == string_series.iloc[i]
+
+ def test_iteritems_datetimes(self, datetime_series):
+ for idx, val in datetime_series.items():
+ assert val == datetime_series[idx]
+
+ def test_iteritems_strings(self, string_series):
+ for idx, val in string_series.items():
+ assert val == string_series[idx]
+
+ # assert is lazy (generators don't define reverse, lists do)
+ assert not hasattr(string_series.items(), "reverse")
+
+ def test_items_datetimes(self, datetime_series):
+ for idx, val in datetime_series.items():
+ assert val == datetime_series[idx]
+
+ def test_items_strings(self, string_series):
+ for idx, val in string_series.items():
+ assert val == string_series[idx]
+
+ # assert is lazy (generators don't define reverse, lists do)
+ assert not hasattr(string_series.items(), "reverse")
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_logical_ops.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_logical_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..26046ef9ba295554a0ce11cf728ccff384cda9e6
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_logical_ops.py
@@ -0,0 +1,515 @@
+from datetime import datetime
+import operator
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ bdate_range,
+)
+import pandas._testing as tm
+from pandas.core import ops
+
+
+class TestSeriesLogicalOps:
+ @pytest.mark.parametrize("bool_op", [operator.and_, operator.or_, operator.xor])
+ def test_bool_operators_with_nas(self, bool_op):
+ # boolean &, |, ^ should work with object arrays and propagate NAs
+ ser = Series(bdate_range("1/1/2000", periods=10), dtype=object)
+ ser[::2] = np.nan
+
+ mask = ser.isna()
+ filled = ser.fillna(ser[0])
+
+ result = bool_op(ser < ser[9], ser > ser[3])
+
+ expected = bool_op(filled < filled[9], filled > filled[3])
+ expected[mask] = False
+ tm.assert_series_equal(result, expected)
+
+ def test_logical_operators_bool_dtype_with_empty(self):
+ # GH#9016: support bitwise op for integer types
+ index = list("bca")
+
+ s_tft = Series([True, False, True], index=index)
+ s_fff = Series([False, False, False], index=index)
+ s_empty = Series([], dtype=object)
+
+ res = s_tft & s_empty
+ expected = s_fff
+ tm.assert_series_equal(res, expected)
+
+ res = s_tft | s_empty
+ expected = s_tft
+ tm.assert_series_equal(res, expected)
+
+ def test_logical_operators_int_dtype_with_int_dtype(self):
+ # GH#9016: support bitwise op for integer types
+
+ s_0123 = Series(range(4), dtype="int64")
+ s_3333 = Series([3] * 4)
+ s_4444 = Series([4] * 4)
+
+ res = s_0123 & s_3333
+ expected = Series(range(4), dtype="int64")
+ tm.assert_series_equal(res, expected)
+
+ res = s_0123 | s_4444
+ expected = Series(range(4, 8), dtype="int64")
+ tm.assert_series_equal(res, expected)
+
+ s_1111 = Series([1] * 4, dtype="int8")
+ res = s_0123 & s_1111
+ expected = Series([0, 1, 0, 1], dtype="int64")
+ tm.assert_series_equal(res, expected)
+
+ res = s_0123.astype(np.int16) | s_1111.astype(np.int32)
+ expected = Series([1, 1, 3, 3], dtype="int32")
+ tm.assert_series_equal(res, expected)
+
+ def test_logical_operators_int_dtype_with_int_scalar(self):
+ # GH#9016: support bitwise op for integer types
+ s_0123 = Series(range(4), dtype="int64")
+
+ res = s_0123 & 0
+ expected = Series([0] * 4)
+ tm.assert_series_equal(res, expected)
+
+ res = s_0123 & 1
+ expected = Series([0, 1, 0, 1])
+ tm.assert_series_equal(res, expected)
+
+ def test_logical_operators_int_dtype_with_float(self):
+ # GH#9016: support bitwise op for integer types
+ s_0123 = Series(range(4), dtype="int64")
+
+ warn_msg = (
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
+ "dtype-less sequences"
+ )
+
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
+ with pytest.raises(TypeError, match=msg):
+ s_0123 & np.nan
+ with pytest.raises(TypeError, match=msg):
+ s_0123 & 3.14
+ msg = "unsupported operand type.+for &:"
+ with pytest.raises(TypeError, match=msg):
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ s_0123 & [0.1, 4, 3.14, 2]
+ with pytest.raises(TypeError, match=msg):
+ s_0123 & np.array([0.1, 4, 3.14, 2])
+ with pytest.raises(TypeError, match=msg):
+ s_0123 & Series([0.1, 4, -3.14, 2])
+
+ def test_logical_operators_int_dtype_with_str(self):
+ s_1111 = Series([1] * 4, dtype="int8")
+
+ warn_msg = (
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
+ "dtype-less sequences"
+ )
+
+ msg = "Cannot perform 'and_' with a dtyped.+array and scalar of type"
+ with pytest.raises(TypeError, match=msg):
+ s_1111 & "a"
+ with pytest.raises(TypeError, match="unsupported operand.+for &"):
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ s_1111 & ["a", "b", "c", "d"]
+
+ def test_logical_operators_int_dtype_with_bool(self):
+ # GH#9016: support bitwise op for integer types
+ s_0123 = Series(range(4), dtype="int64")
+
+ expected = Series([False] * 4)
+
+ result = s_0123 & False
+ tm.assert_series_equal(result, expected)
+
+ warn_msg = (
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
+ "dtype-less sequences"
+ )
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ result = s_0123 & [False]
+ tm.assert_series_equal(result, expected)
+
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ result = s_0123 & (False,)
+ tm.assert_series_equal(result, expected)
+
+ result = s_0123 ^ False
+ expected = Series([False, True, True, True])
+ tm.assert_series_equal(result, expected)
+
+ def test_logical_operators_int_dtype_with_object(self):
+ # GH#9016: support bitwise op for integer types
+ s_0123 = Series(range(4), dtype="int64")
+
+ result = s_0123 & Series([False, np.nan, False, False])
+ expected = Series([False] * 4)
+ tm.assert_series_equal(result, expected)
+
+ s_abNd = Series(["a", "b", np.nan, "d"])
+ with pytest.raises(TypeError, match="unsupported.* 'int' and 'str'"):
+ s_0123 & s_abNd
+
+ def test_logical_operators_bool_dtype_with_int(self):
+ index = list("bca")
+
+ s_tft = Series([True, False, True], index=index)
+ s_fff = Series([False, False, False], index=index)
+
+ res = s_tft & 0
+ expected = s_fff
+ tm.assert_series_equal(res, expected)
+
+ res = s_tft & 1
+ expected = s_tft
+ tm.assert_series_equal(res, expected)
+
+ def test_logical_ops_bool_dtype_with_ndarray(self):
+ # make sure we operate on ndarray the same as Series
+ left = Series([True, True, True, False, True])
+ right = [True, False, None, True, np.nan]
+
+ msg = (
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
+ "dtype-less sequences"
+ )
+
+ expected = Series([True, False, False, False, False])
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = left & right
+ tm.assert_series_equal(result, expected)
+ result = left & np.array(right)
+ tm.assert_series_equal(result, expected)
+ result = left & Index(right)
+ tm.assert_series_equal(result, expected)
+ result = left & Series(right)
+ tm.assert_series_equal(result, expected)
+
+ expected = Series([True, True, True, True, True])
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = left | right
+ tm.assert_series_equal(result, expected)
+ result = left | np.array(right)
+ tm.assert_series_equal(result, expected)
+ result = left | Index(right)
+ tm.assert_series_equal(result, expected)
+ result = left | Series(right)
+ tm.assert_series_equal(result, expected)
+
+ expected = Series([False, True, True, True, True])
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = left ^ right
+ tm.assert_series_equal(result, expected)
+ result = left ^ np.array(right)
+ tm.assert_series_equal(result, expected)
+ result = left ^ Index(right)
+ tm.assert_series_equal(result, expected)
+ result = left ^ Series(right)
+ tm.assert_series_equal(result, expected)
+
+ def test_logical_operators_int_dtype_with_bool_dtype_and_reindex(self):
+ # GH#9016: support bitwise op for integer types
+
+ index = list("bca")
+
+ s_tft = Series([True, False, True], index=index)
+ s_tft = Series([True, False, True], index=index)
+ s_tff = Series([True, False, False], index=index)
+
+ s_0123 = Series(range(4), dtype="int64")
+
+ # s_0123 will be all false now because of reindexing like s_tft
+ expected = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"])
+ with tm.assert_produces_warning(FutureWarning):
+ result = s_tft & s_0123
+ tm.assert_series_equal(result, expected)
+
+ # GH 52538: Deprecate casting to object type when reindex is needed;
+ # matches DataFrame behavior
+ expected = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"])
+ with tm.assert_produces_warning(FutureWarning):
+ result = s_0123 & s_tft
+ tm.assert_series_equal(result, expected)
+
+ s_a0b1c0 = Series([1], list("b"))
+
+ with tm.assert_produces_warning(FutureWarning):
+ res = s_tft & s_a0b1c0
+ expected = s_tff.reindex(list("abc"))
+ tm.assert_series_equal(res, expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ res = s_tft | s_a0b1c0
+ expected = s_tft.reindex(list("abc"))
+ tm.assert_series_equal(res, expected)
+
+ def test_scalar_na_logical_ops_corners(self):
+ s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10])
+
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
+ with pytest.raises(TypeError, match=msg):
+ s & datetime(2005, 1, 1)
+
+ s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)])
+ s[::2] = np.nan
+
+ expected = Series(True, index=s.index)
+ expected[::2] = False
+
+ msg = (
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
+ "dtype-less sequences"
+ )
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = s & list(s)
+ tm.assert_series_equal(result, expected)
+
+ def test_scalar_na_logical_ops_corners_aligns(self):
+ s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)])
+ s[::2] = np.nan
+ d = DataFrame({"A": s})
+
+ expected = DataFrame(False, index=range(9), columns=["A"] + list(range(9)))
+
+ result = s & d
+ tm.assert_frame_equal(result, expected)
+
+ result = d & s
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("op", [operator.and_, operator.or_, operator.xor])
+ def test_logical_ops_with_index(self, op):
+ # GH#22092, GH#19792
+ ser = Series([True, True, False, False])
+ idx1 = Index([True, False, True, False])
+ idx2 = Index([1, 0, 1, 0])
+
+ expected = Series([op(ser[n], idx1[n]) for n in range(len(ser))])
+
+ result = op(ser, idx1)
+ tm.assert_series_equal(result, expected)
+
+ expected = Series([op(ser[n], idx2[n]) for n in range(len(ser))], dtype=bool)
+
+ result = op(ser, idx2)
+ tm.assert_series_equal(result, expected)
+
+ def test_reversed_xor_with_index_returns_series(self):
+ # GH#22092, GH#19792 pre-2.0 these were aliased to setops
+ ser = Series([True, True, False, False])
+ idx1 = Index([True, False, True, False], dtype=bool)
+ idx2 = Index([1, 0, 1, 0])
+
+ expected = Series([False, True, True, False])
+ result = idx1 ^ ser
+ tm.assert_series_equal(result, expected)
+
+ result = idx2 ^ ser
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "op",
+ [
+ ops.rand_,
+ ops.ror_,
+ ],
+ )
+ def test_reversed_logical_op_with_index_returns_series(self, op):
+ # GH#22092, GH#19792
+ ser = Series([True, True, False, False])
+ idx1 = Index([True, False, True, False])
+ idx2 = Index([1, 0, 1, 0])
+
+ expected = Series(op(idx1.values, ser.values))
+ result = op(ser, idx1)
+ tm.assert_series_equal(result, expected)
+
+ expected = op(ser, Series(idx2))
+ result = op(ser, idx2)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "op, expected",
+ [
+ (ops.rand_, Series([False, False])),
+ (ops.ror_, Series([True, True])),
+ (ops.rxor, Series([True, True])),
+ ],
+ )
+ def test_reverse_ops_with_index(self, op, expected):
+ # https://github.com/pandas-dev/pandas/pull/23628
+ # multi-set Index ops are buggy, so let's avoid duplicates...
+ # GH#49503
+ ser = Series([True, False])
+ idx = Index([False, True])
+
+ result = op(ser, idx)
+ tm.assert_series_equal(result, expected)
+
+ def test_logical_ops_label_based(self):
+ # GH#4947
+ # logical ops should be label based
+
+ a = Series([True, False, True], list("bca"))
+ b = Series([False, True, False], list("abc"))
+
+ expected = Series([False, True, False], list("abc"))
+ result = a & b
+ tm.assert_series_equal(result, expected)
+
+ expected = Series([True, True, False], list("abc"))
+ result = a | b
+ tm.assert_series_equal(result, expected)
+
+ expected = Series([True, False, False], list("abc"))
+ result = a ^ b
+ tm.assert_series_equal(result, expected)
+
+ # rhs is bigger
+ a = Series([True, False, True], list("bca"))
+ b = Series([False, True, False, True], list("abcd"))
+
+ expected = Series([False, True, False, False], list("abcd"))
+ result = a & b
+ tm.assert_series_equal(result, expected)
+
+ expected = Series([True, True, False, False], list("abcd"))
+ result = a | b
+ tm.assert_series_equal(result, expected)
+
+ # filling
+
+ # vs empty
+ empty = Series([], dtype=object)
+
+ result = a & empty.copy()
+ expected = Series([False, False, False], list("bca"))
+ tm.assert_series_equal(result, expected)
+
+ result = a | empty.copy()
+ expected = Series([True, False, True], list("bca"))
+ tm.assert_series_equal(result, expected)
+
+ # vs non-matching
+ with tm.assert_produces_warning(FutureWarning):
+ result = a & Series([1], ["z"])
+ expected = Series([False, False, False, False], list("abcz"))
+ tm.assert_series_equal(result, expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = a | Series([1], ["z"])
+ expected = Series([True, True, False, False], list("abcz"))
+ tm.assert_series_equal(result, expected)
+
+ # identity
+ # we would like s[s|e] == s to hold for any e, whether empty or not
+ with tm.assert_produces_warning(FutureWarning):
+ for e in [
+ empty.copy(),
+ Series([1], ["z"]),
+ Series(np.nan, b.index),
+ Series(np.nan, a.index),
+ ]:
+ result = a[a | e]
+ tm.assert_series_equal(result, a[a])
+
+ for e in [Series(["z"])]:
+ result = a[a | e]
+ tm.assert_series_equal(result, a[a])
+
+ # vs scalars
+ index = list("bca")
+ t = Series([True, False, True])
+
+ for v in [True, 1, 2]:
+ result = Series([True, False, True], index=index) | v
+ expected = Series([True, True, True], index=index)
+ tm.assert_series_equal(result, expected)
+
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
+ for v in [np.nan, "foo"]:
+ with pytest.raises(TypeError, match=msg):
+ t | v
+
+ for v in [False, 0]:
+ result = Series([True, False, True], index=index) | v
+ expected = Series([True, False, True], index=index)
+ tm.assert_series_equal(result, expected)
+
+ for v in [True, 1]:
+ result = Series([True, False, True], index=index) & v
+ expected = Series([True, False, True], index=index)
+ tm.assert_series_equal(result, expected)
+
+ for v in [False, 0]:
+ result = Series([True, False, True], index=index) & v
+ expected = Series([False, False, False], index=index)
+ tm.assert_series_equal(result, expected)
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
+ for v in [np.nan]:
+ with pytest.raises(TypeError, match=msg):
+ t & v
+
+ def test_logical_ops_df_compat(self):
+ # GH#1134
+ s1 = Series([True, False, True], index=list("ABC"), name="x")
+ s2 = Series([True, True, False], index=list("ABD"), name="x")
+
+ exp = Series([True, False, False, False], index=list("ABCD"), name="x")
+ tm.assert_series_equal(s1 & s2, exp)
+ tm.assert_series_equal(s2 & s1, exp)
+
+ # True | np.nan => True
+ exp_or1 = Series([True, True, True, False], index=list("ABCD"), name="x")
+ tm.assert_series_equal(s1 | s2, exp_or1)
+ # np.nan | True => np.nan, filled with False
+ exp_or = Series([True, True, False, False], index=list("ABCD"), name="x")
+ tm.assert_series_equal(s2 | s1, exp_or)
+
+ # DataFrame doesn't fill nan with False
+ tm.assert_frame_equal(s1.to_frame() & s2.to_frame(), exp.to_frame())
+ tm.assert_frame_equal(s2.to_frame() & s1.to_frame(), exp.to_frame())
+
+ exp = DataFrame({"x": [True, True, np.nan, np.nan]}, index=list("ABCD"))
+ tm.assert_frame_equal(s1.to_frame() | s2.to_frame(), exp_or1.to_frame())
+ tm.assert_frame_equal(s2.to_frame() | s1.to_frame(), exp_or.to_frame())
+
+ # different length
+ s3 = Series([True, False, True], index=list("ABC"), name="x")
+ s4 = Series([True, True, True, True], index=list("ABCD"), name="x")
+
+ exp = Series([True, False, True, False], index=list("ABCD"), name="x")
+ tm.assert_series_equal(s3 & s4, exp)
+ tm.assert_series_equal(s4 & s3, exp)
+
+ # np.nan | True => np.nan, filled with False
+ exp_or1 = Series([True, True, True, False], index=list("ABCD"), name="x")
+ tm.assert_series_equal(s3 | s4, exp_or1)
+ # True | np.nan => True
+ exp_or = Series([True, True, True, True], index=list("ABCD"), name="x")
+ tm.assert_series_equal(s4 | s3, exp_or)
+
+ tm.assert_frame_equal(s3.to_frame() & s4.to_frame(), exp.to_frame())
+ tm.assert_frame_equal(s4.to_frame() & s3.to_frame(), exp.to_frame())
+
+ tm.assert_frame_equal(s3.to_frame() | s4.to_frame(), exp_or1.to_frame())
+ tm.assert_frame_equal(s4.to_frame() | s3.to_frame(), exp_or.to_frame())
+
+ @pytest.mark.xfail(reason="Will pass once #52839 deprecation is enforced")
+ def test_int_dtype_different_index_not_bool(self):
+ # GH 52500
+ ser1 = Series([1, 2, 3], index=[10, 11, 23], name="a")
+ ser2 = Series([10, 20, 30], index=[11, 10, 23], name="a")
+ result = np.bitwise_xor(ser1, ser2)
+ expected = Series([21, 8, 29], index=[10, 11, 23], name="a")
+ tm.assert_series_equal(result, expected)
+
+ result = ser1 ^ ser2
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_missing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_missing.py
new file mode 100644
index 0000000000000000000000000000000000000000..cafc69c4d0f20f42dc184366db0ac8933a512f54
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_missing.py
@@ -0,0 +1,105 @@
+from datetime import timedelta
+
+import numpy as np
+import pytest
+
+from pandas._libs import iNaT
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ Index,
+ NaT,
+ Series,
+ isna,
+)
+import pandas._testing as tm
+
+
+class TestSeriesMissingData:
+ def test_categorical_nan_handling(self):
+ # NaNs are represented as -1 in labels
+ s = Series(Categorical(["a", "b", np.nan, "a"]))
+ tm.assert_index_equal(s.cat.categories, Index(["a", "b"]))
+ tm.assert_numpy_array_equal(
+ s.values.codes, np.array([0, 1, -1, 0], dtype=np.int8)
+ )
+
+ def test_isna_for_inf(self):
+ s = Series(["a", np.inf, np.nan, pd.NA, 1.0])
+ msg = "use_inf_as_na option is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ with pd.option_context("mode.use_inf_as_na", True):
+ r = s.isna()
+ dr = s.dropna()
+ e = Series([False, True, True, True, False])
+ de = Series(["a", 1.0], index=[0, 4])
+ tm.assert_series_equal(r, e)
+ tm.assert_series_equal(dr, de)
+
+ def test_timedelta64_nan(self):
+ td = Series([timedelta(days=i) for i in range(10)])
+
+ # nan ops on timedeltas
+ td1 = td.copy()
+ td1[0] = np.nan
+ assert isna(td1[0])
+ assert td1[0]._value == iNaT
+ td1[0] = td[0]
+ assert not isna(td1[0])
+
+ # GH#16674 iNaT is treated as an integer when given by the user
+ with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
+ td1[1] = iNaT
+ assert not isna(td1[1])
+ assert td1.dtype == np.object_
+ assert td1[1] == iNaT
+ td1[1] = td[1]
+ assert not isna(td1[1])
+
+ td1[2] = NaT
+ assert isna(td1[2])
+ assert td1[2]._value == iNaT
+ td1[2] = td[2]
+ assert not isna(td1[2])
+
+ # boolean setting
+ # GH#2899 boolean setting
+ td3 = np.timedelta64(timedelta(days=3))
+ td7 = np.timedelta64(timedelta(days=7))
+ td[(td > td3) & (td < td7)] = np.nan
+ assert isna(td).sum() == 3
+
+ @pytest.mark.xfail(
+ reason="Chained inequality raises when trying to define 'selector'"
+ )
+ def test_logical_range_select(self, datetime_series):
+ # NumPy limitation =(
+ # https://github.com/pandas-dev/pandas/commit/9030dc021f07c76809848925cb34828f6c8484f3
+
+ selector = -0.5 <= datetime_series <= 0.5
+ expected = (datetime_series >= -0.5) & (datetime_series <= 0.5)
+ tm.assert_series_equal(selector, expected)
+
+ def test_valid(self, datetime_series):
+ ts = datetime_series.copy()
+ ts.index = ts.index._with_freq(None)
+ ts[::2] = np.nan
+
+ result = ts.dropna()
+ assert len(result) == ts.count()
+ tm.assert_series_equal(result, ts[1::2])
+ tm.assert_series_equal(result, ts[pd.notna(ts)])
+
+
+def test_hasnans_uncached_for_series():
+ # GH#19700
+ # set float64 dtype to avoid upcast when setting nan
+ idx = Index([0, 1], dtype="float64")
+ assert idx.hasnans is False
+ assert "hasnans" in idx._cache
+ ser = idx.to_series()
+ assert ser.hasnans is False
+ assert not hasattr(ser, "_cache")
+ ser.iloc[-1] = np.nan
+ assert ser.hasnans is True
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_npfuncs.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_npfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..08950db25b28200f7b0bffc2010826c16979572a
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_npfuncs.py
@@ -0,0 +1,35 @@
+"""
+Tests for np.foo applied to Series, not necessarily ufuncs.
+"""
+
+import numpy as np
+import pytest
+
+from pandas import Series
+import pandas._testing as tm
+
+
+class TestPtp:
+ def test_ptp(self):
+ # GH#21614
+ N = 1000
+ arr = np.random.default_rng(2).standard_normal(N)
+ ser = Series(arr)
+ assert np.ptp(ser) == np.ptp(arr)
+
+
+def test_numpy_unique(datetime_series):
+ # it works!
+ np.unique(datetime_series)
+
+
+@pytest.mark.parametrize("index", [["a", "b", "c", "d", "e"], None])
+def test_numpy_argwhere(index):
+ # GH#35331
+
+ s = Series(range(5), index=index, dtype=np.int64)
+
+ result = np.argwhere(s > 2).astype(np.int64)
+ expected = np.array([[3], [4]], dtype=np.int64)
+
+ tm.assert_numpy_array_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_reductions.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_reductions.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e1ac100b21bfc140a7608a337806b1d41590eef
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_reductions.py
@@ -0,0 +1,180 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import Series
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize("operation, expected", [("min", "a"), ("max", "b")])
+def test_reductions_series_strings(operation, expected):
+ # GH#31746
+ ser = Series(["a", "b"], dtype="string")
+ res_operation_serie = getattr(ser, operation)()
+ assert res_operation_serie == expected
+
+
+@pytest.mark.parametrize("as_period", [True, False])
+def test_mode_extension_dtype(as_period):
+ # GH#41927 preserve dt64tz dtype
+ ser = Series([pd.Timestamp(1979, 4, n) for n in range(1, 5)])
+
+ if as_period:
+ ser = ser.dt.to_period("D")
+ else:
+ ser = ser.dt.tz_localize("US/Central")
+
+ res = ser.mode()
+ assert res.dtype == ser.dtype
+ tm.assert_series_equal(res, ser)
+
+
+def test_reductions_td64_with_nat():
+ # GH#8617
+ ser = Series([0, pd.NaT], dtype="m8[ns]")
+ exp = ser[0]
+ assert ser.median() == exp
+ assert ser.min() == exp
+ assert ser.max() == exp
+
+
+@pytest.mark.parametrize("skipna", [True, False])
+def test_td64_sum_empty(skipna):
+ # GH#37151
+ ser = Series([], dtype="timedelta64[ns]")
+
+ result = ser.sum(skipna=skipna)
+ assert isinstance(result, pd.Timedelta)
+ assert result == pd.Timedelta(0)
+
+
+def test_td64_summation_overflow():
+ # GH#9442
+ ser = Series(pd.date_range("20130101", periods=100000, freq="H"))
+ ser[0] += pd.Timedelta("1s 1ms")
+
+ # mean
+ result = (ser - ser.min()).mean()
+ expected = pd.Timedelta((pd.TimedeltaIndex(ser - ser.min()).asi8 / len(ser)).sum())
+
+ # the computation is converted to float so
+ # might be some loss of precision
+ assert np.allclose(result._value / 1000, expected._value / 1000)
+
+ # sum
+ msg = "overflow in timedelta operation"
+ with pytest.raises(ValueError, match=msg):
+ (ser - ser.min()).sum()
+
+ s1 = ser[0:10000]
+ with pytest.raises(ValueError, match=msg):
+ (s1 - s1.min()).sum()
+ s2 = ser[0:1000]
+ (s2 - s2.min()).sum()
+
+
+def test_prod_numpy16_bug():
+ ser = Series([1.0, 1.0, 1.0], index=range(3))
+ result = ser.prod()
+
+ assert not isinstance(result, Series)
+
+
+@pytest.mark.parametrize("func", [np.any, np.all])
+@pytest.mark.parametrize("kwargs", [{"keepdims": True}, {"out": object()}])
+def test_validate_any_all_out_keepdims_raises(kwargs, func):
+ ser = Series([1, 2])
+ param = next(iter(kwargs))
+ name = func.__name__
+
+ msg = (
+ f"the '{param}' parameter is not "
+ "supported in the pandas "
+ rf"implementation of {name}\(\)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ func(ser, **kwargs)
+
+
+def test_validate_sum_initial():
+ ser = Series([1, 2])
+ msg = (
+ r"the 'initial' parameter is not "
+ r"supported in the pandas "
+ r"implementation of sum\(\)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ np.sum(ser, initial=10)
+
+
+def test_validate_median_initial():
+ ser = Series([1, 2])
+ msg = (
+ r"the 'overwrite_input' parameter is not "
+ r"supported in the pandas "
+ r"implementation of median\(\)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ # It seems like np.median doesn't dispatch, so we use the
+ # method instead of the ufunc.
+ ser.median(overwrite_input=True)
+
+
+def test_validate_stat_keepdims():
+ ser = Series([1, 2])
+ msg = (
+ r"the 'keepdims' parameter is not "
+ r"supported in the pandas "
+ r"implementation of sum\(\)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ np.sum(ser, keepdims=True)
+
+
+def test_mean_with_convertible_string_raises(using_array_manager):
+ # GH#44008
+ ser = Series(["1", "2"])
+ assert ser.sum() == "12"
+ msg = "Could not convert string '12' to numeric"
+ with pytest.raises(TypeError, match=msg):
+ ser.mean()
+
+ df = ser.to_frame()
+ if not using_array_manager:
+ msg = r"Could not convert \['12'\] to numeric"
+ with pytest.raises(TypeError, match=msg):
+ df.mean()
+
+
+def test_mean_dont_convert_j_to_complex(using_array_manager):
+ # GH#36703
+ df = pd.DataFrame([{"db": "J", "numeric": 123}])
+ if using_array_manager:
+ msg = "Could not convert string 'J' to numeric"
+ else:
+ msg = r"Could not convert \['J'\] to numeric"
+ with pytest.raises(TypeError, match=msg):
+ df.mean()
+
+ with pytest.raises(TypeError, match=msg):
+ df.agg("mean")
+
+ msg = "Could not convert string 'J' to numeric"
+ with pytest.raises(TypeError, match=msg):
+ df["db"].mean()
+ with pytest.raises(TypeError, match=msg):
+ np.mean(df["db"].astype("string").array)
+
+
+def test_median_with_convertible_string_raises(using_array_manager):
+ # GH#34671 this _could_ return a string "2", but definitely not float 2.0
+ msg = r"Cannot convert \['1' '2' '3'\] to numeric"
+ ser = Series(["1", "2", "3"])
+ with pytest.raises(TypeError, match=msg):
+ ser.median()
+
+ if not using_array_manager:
+ msg = r"Cannot convert \[\['1' '2' '3'\]\] to numeric"
+ df = ser.to_frame()
+ with pytest.raises(TypeError, match=msg):
+ df.median()
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_repr.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_repr.py
new file mode 100644
index 0000000000000000000000000000000000000000..be68918d2a3802b0fb1a368ffbe57b40328ae949
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_repr.py
@@ -0,0 +1,551 @@
+from datetime import (
+ datetime,
+ timedelta,
+)
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+ Categorical,
+ DataFrame,
+ Index,
+ Series,
+ date_range,
+ option_context,
+ period_range,
+ timedelta_range,
+)
+import pandas._testing as tm
+
+
+class TestSeriesRepr:
+ def test_multilevel_name_print(self, lexsorted_two_level_string_multiindex):
+ index = lexsorted_two_level_string_multiindex
+ ser = Series(range(len(index)), index=index, name="sth")
+ expected = [
+ "first second",
+ "foo one 0",
+ " two 1",
+ " three 2",
+ "bar one 3",
+ " two 4",
+ "baz two 5",
+ " three 6",
+ "qux one 7",
+ " two 8",
+ " three 9",
+ "Name: sth, dtype: int64",
+ ]
+ expected = "\n".join(expected)
+ assert repr(ser) == expected
+
+ def test_small_name_printing(self):
+ # Test small Series.
+ s = Series([0, 1, 2])
+
+ s.name = "test"
+ assert "Name: test" in repr(s)
+
+ s.name = None
+ assert "Name:" not in repr(s)
+
+ def test_big_name_printing(self):
+ # Test big Series (diff code path).
+ s = Series(range(1000))
+
+ s.name = "test"
+ assert "Name: test" in repr(s)
+
+ s.name = None
+ assert "Name:" not in repr(s)
+
+ def test_empty_name_printing(self):
+ s = Series(index=date_range("20010101", "20020101"), name="test", dtype=object)
+ assert "Name: test" in repr(s)
+
+ @pytest.mark.parametrize("args", [(), (0, -1)])
+ def test_float_range(self, args):
+ str(
+ Series(
+ np.random.default_rng(2).standard_normal(1000),
+ index=np.arange(1000, *args),
+ )
+ )
+
+ def test_empty_object(self):
+ # empty
+ str(Series(dtype=object))
+
+ def test_string(self, string_series):
+ str(string_series)
+ str(string_series.astype(int))
+
+ # with NaNs
+ string_series[5:7] = np.nan
+ str(string_series)
+
+ def test_object(self, object_series):
+ str(object_series)
+
+ def test_datetime(self, datetime_series):
+ str(datetime_series)
+ # with Nones
+ ots = datetime_series.astype("O")
+ ots[::2] = None
+ repr(ots)
+
+ @pytest.mark.parametrize(
+ "name",
+ [
+ "",
+ 1,
+ 1.2,
+ "foo",
+ "\u03B1\u03B2\u03B3",
+ "loooooooooooooooooooooooooooooooooooooooooooooooooooong",
+ ("foo", "bar", "baz"),
+ (1, 2),
+ ("foo", 1, 2.3),
+ ("\u03B1", "\u03B2", "\u03B3"),
+ ("\u03B1", "bar"),
+ ],
+ )
+ def test_various_names(self, name, string_series):
+ # various names
+ string_series.name = name
+ repr(string_series)
+
+ def test_tuple_name(self):
+ biggie = Series(
+ np.random.default_rng(2).standard_normal(1000),
+ index=np.arange(1000),
+ name=("foo", "bar", "baz"),
+ )
+ repr(biggie)
+
+ @pytest.mark.parametrize("arg", [100, 1001])
+ def test_tidy_repr_name_0(self, arg):
+ # tidy repr
+ ser = Series(np.random.default_rng(2).standard_normal(arg), name=0)
+ rep_str = repr(ser)
+ assert "Name: 0" in rep_str
+
+ def test_newline(self):
+ ser = Series(["a\n\r\tb"], name="a\n\r\td", index=["a\n\r\tf"])
+ assert "\t" not in repr(ser)
+ assert "\r" not in repr(ser)
+ assert "a\n" not in repr(ser)
+
+ @pytest.mark.parametrize(
+ "name, expected",
+ [
+ ["foo", "Series([], Name: foo, dtype: int64)"],
+ [None, "Series([], dtype: int64)"],
+ ],
+ )
+ def test_empty_int64(self, name, expected):
+ # with empty series (#4651)
+ s = Series([], dtype=np.int64, name=name)
+ assert repr(s) == expected
+
+ def test_tidy_repr(self):
+ a = Series(["\u05d0"] * 1000)
+ a.name = "title1"
+ repr(a) # should not raise exception
+
+ def test_repr_bool_fails(self, capsys):
+ s = Series(
+ [
+ DataFrame(np.random.default_rng(2).standard_normal((2, 2)))
+ for i in range(5)
+ ]
+ )
+
+ # It works (with no Cython exception barf)!
+ repr(s)
+
+ captured = capsys.readouterr()
+ assert captured.err == ""
+
+ def test_repr_name_iterable_indexable(self):
+ s = Series([1, 2, 3], name=np.int64(3))
+
+ # it works!
+ repr(s)
+
+ s.name = ("\u05d0",) * 2
+ repr(s)
+
+ def test_repr_should_return_str(self):
+ # https://docs.python.org/3/reference/datamodel.html#object.__repr__
+ # ...The return value must be a string object.
+
+ # (str on py2.x, str (unicode) on py3)
+
+ data = [8, 5, 3, 5]
+ index1 = ["\u03c3", "\u03c4", "\u03c5", "\u03c6"]
+ df = Series(data, index=index1)
+ assert type(df.__repr__() == str) # both py2 / 3
+
+ def test_repr_max_rows(self):
+ # GH 6863
+ with option_context("display.max_rows", None):
+ str(Series(range(1001))) # should not raise exception
+
+ def test_unicode_string_with_unicode(self):
+ df = Series(["\u05d0"], name="\u05d1")
+ str(df)
+
+ def test_str_to_bytes_raises(self):
+ # GH 26447
+ df = Series(["abc"], name="abc")
+ msg = "^'str' object cannot be interpreted as an integer$"
+ with pytest.raises(TypeError, match=msg):
+ bytes(df)
+
+ def test_timeseries_repr_object_dtype(self):
+ index = Index(
+ [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)], dtype=object
+ )
+ ts = Series(np.random.default_rng(2).standard_normal(len(index)), index)
+ repr(ts)
+
+ ts = tm.makeTimeSeries(1000)
+ assert repr(ts).splitlines()[-1].startswith("Freq:")
+
+ ts2 = ts.iloc[np.random.default_rng(2).integers(0, len(ts) - 1, 400)]
+ repr(ts2).splitlines()[-1]
+
+ def test_latex_repr(self):
+ pytest.importorskip("jinja2") # uses Styler implementation
+ result = r"""\begin{tabular}{ll}
+\toprule
+ & 0 \\
+\midrule
+0 & $\alpha$ \\
+1 & b \\
+2 & c \\
+\bottomrule
+\end{tabular}
+"""
+ with option_context(
+ "styler.format.escape", None, "styler.render.repr", "latex"
+ ):
+ s = Series([r"$\alpha$", "b", "c"])
+ assert result == s._repr_latex_()
+
+ assert s._repr_latex_() is None
+
+ def test_index_repr_in_frame_with_nan(self):
+ # see gh-25061
+ i = Index([1, np.nan])
+ s = Series([1, 2], index=i)
+ exp = """1.0 1\nNaN 2\ndtype: int64"""
+
+ assert repr(s) == exp
+
+ def test_format_pre_1900_dates(self):
+ rng = date_range("1/1/1850", "1/1/1950", freq="A-DEC")
+ rng.format()
+ ts = Series(1, index=rng)
+ repr(ts)
+
+ def test_series_repr_nat(self):
+ series = Series([0, 1000, 2000, pd.NaT._value], dtype="M8[ns]")
+
+ result = repr(series)
+ expected = (
+ "0 1970-01-01 00:00:00.000000\n"
+ "1 1970-01-01 00:00:00.000001\n"
+ "2 1970-01-01 00:00:00.000002\n"
+ "3 NaT\n"
+ "dtype: datetime64[ns]"
+ )
+ assert result == expected
+
+ def test_float_repr(self):
+ # GH#35603
+ # check float format when cast to object
+ ser = Series([1.0]).astype(object)
+ expected = "0 1.0\ndtype: object"
+ assert repr(ser) == expected
+
+ def test_different_null_objects(self):
+ # GH#45263
+ ser = Series([1, 2, 3, 4], [True, None, np.nan, pd.NaT])
+ result = repr(ser)
+ expected = "True 1\nNone 2\nNaN 3\nNaT 4\ndtype: int64"
+ assert result == expected
+
+
+class TestCategoricalRepr:
+ def test_categorical_repr_unicode(self):
+ # see gh-21002
+
+ class County:
+ name = "San Sebastián"
+ state = "PR"
+
+ def __repr__(self) -> str:
+ return self.name + ", " + self.state
+
+ cat = Categorical([County() for _ in range(61)])
+ idx = Index(cat)
+ ser = idx.to_series()
+
+ repr(ser)
+ str(ser)
+
+ def test_categorical_repr(self):
+ a = Series(Categorical([1, 2, 3, 4]))
+ exp = (
+ "0 1\n1 2\n2 3\n3 4\n"
+ "dtype: category\nCategories (4, int64): [1, 2, 3, 4]"
+ )
+
+ assert exp == a.__str__()
+
+ a = Series(Categorical(["a", "b"] * 25))
+ exp = (
+ "0 a\n1 b\n"
+ " ..\n"
+ "48 a\n49 b\n"
+ "Length: 50, dtype: category\nCategories (2, object): ['a', 'b']"
+ )
+ with option_context("display.max_rows", 5):
+ assert exp == repr(a)
+
+ levs = list("abcdefghijklmnopqrstuvwxyz")
+ a = Series(Categorical(["a", "b"], categories=levs, ordered=True))
+ exp = (
+ "0 a\n1 b\n"
+ "dtype: category\n"
+ "Categories (26, object): ['a' < 'b' < 'c' < 'd' ... 'w' < 'x' < 'y' < 'z']"
+ )
+ assert exp == a.__str__()
+
+ def test_categorical_series_repr(self):
+ s = Series(Categorical([1, 2, 3]))
+ exp = """0 1
+1 2
+2 3
+dtype: category
+Categories (3, int64): [1, 2, 3]"""
+
+ assert repr(s) == exp
+
+ s = Series(Categorical(np.arange(10)))
+ exp = f"""0 0
+1 1
+2 2
+3 3
+4 4
+5 5
+6 6
+7 7
+8 8
+9 9
+dtype: category
+Categories (10, {np.dtype(int)}): [0, 1, 2, 3, ..., 6, 7, 8, 9]"""
+
+ assert repr(s) == exp
+
+ def test_categorical_series_repr_ordered(self):
+ s = Series(Categorical([1, 2, 3], ordered=True))
+ exp = """0 1
+1 2
+2 3
+dtype: category
+Categories (3, int64): [1 < 2 < 3]"""
+
+ assert repr(s) == exp
+
+ s = Series(Categorical(np.arange(10), ordered=True))
+ exp = f"""0 0
+1 1
+2 2
+3 3
+4 4
+5 5
+6 6
+7 7
+8 8
+9 9
+dtype: category
+Categories (10, {np.dtype(int)}): [0 < 1 < 2 < 3 ... 6 < 7 < 8 < 9]"""
+
+ assert repr(s) == exp
+
+ def test_categorical_series_repr_datetime(self):
+ idx = date_range("2011-01-01 09:00", freq="H", periods=5)
+ s = Series(Categorical(idx))
+ exp = """0 2011-01-01 09:00:00
+1 2011-01-01 10:00:00
+2 2011-01-01 11:00:00
+3 2011-01-01 12:00:00
+4 2011-01-01 13:00:00
+dtype: category
+Categories (5, datetime64[ns]): [2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00,
+ 2011-01-01 12:00:00, 2011-01-01 13:00:00]""" # noqa: E501
+
+ assert repr(s) == exp
+
+ idx = date_range("2011-01-01 09:00", freq="H", periods=5, tz="US/Eastern")
+ s = Series(Categorical(idx))
+ exp = """0 2011-01-01 09:00:00-05:00
+1 2011-01-01 10:00:00-05:00
+2 2011-01-01 11:00:00-05:00
+3 2011-01-01 12:00:00-05:00
+4 2011-01-01 13:00:00-05:00
+dtype: category
+Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,
+ 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,
+ 2011-01-01 13:00:00-05:00]""" # noqa: E501
+
+ assert repr(s) == exp
+
+ def test_categorical_series_repr_datetime_ordered(self):
+ idx = date_range("2011-01-01 09:00", freq="H", periods=5)
+ s = Series(Categorical(idx, ordered=True))
+ exp = """0 2011-01-01 09:00:00
+1 2011-01-01 10:00:00
+2 2011-01-01 11:00:00
+3 2011-01-01 12:00:00
+4 2011-01-01 13:00:00
+dtype: category
+Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
+ 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
+
+ assert repr(s) == exp
+
+ idx = date_range("2011-01-01 09:00", freq="H", periods=5, tz="US/Eastern")
+ s = Series(Categorical(idx, ordered=True))
+ exp = """0 2011-01-01 09:00:00-05:00
+1 2011-01-01 10:00:00-05:00
+2 2011-01-01 11:00:00-05:00
+3 2011-01-01 12:00:00-05:00
+4 2011-01-01 13:00:00-05:00
+dtype: category
+Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
+ 2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
+ 2011-01-01 13:00:00-05:00]""" # noqa: E501
+
+ assert repr(s) == exp
+
+ def test_categorical_series_repr_period(self):
+ idx = period_range("2011-01-01 09:00", freq="H", periods=5)
+ s = Series(Categorical(idx))
+ exp = """0 2011-01-01 09:00
+1 2011-01-01 10:00
+2 2011-01-01 11:00
+3 2011-01-01 12:00
+4 2011-01-01 13:00
+dtype: category
+Categories (5, period[H]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
+ 2011-01-01 13:00]""" # noqa: E501
+
+ assert repr(s) == exp
+
+ idx = period_range("2011-01", freq="M", periods=5)
+ s = Series(Categorical(idx))
+ exp = """0 2011-01
+1 2011-02
+2 2011-03
+3 2011-04
+4 2011-05
+dtype: category
+Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]"""
+
+ assert repr(s) == exp
+
+ def test_categorical_series_repr_period_ordered(self):
+ idx = period_range("2011-01-01 09:00", freq="H", periods=5)
+ s = Series(Categorical(idx, ordered=True))
+ exp = """0 2011-01-01 09:00
+1 2011-01-01 10:00
+2 2011-01-01 11:00
+3 2011-01-01 12:00
+4 2011-01-01 13:00
+dtype: category
+Categories (5, period[H]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
+ 2011-01-01 13:00]""" # noqa: E501
+
+ assert repr(s) == exp
+
+ idx = period_range("2011-01", freq="M", periods=5)
+ s = Series(Categorical(idx, ordered=True))
+ exp = """0 2011-01
+1 2011-02
+2 2011-03
+3 2011-04
+4 2011-05
+dtype: category
+Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]"""
+
+ assert repr(s) == exp
+
+ def test_categorical_series_repr_timedelta(self):
+ idx = timedelta_range("1 days", periods=5)
+ s = Series(Categorical(idx))
+ exp = """0 1 days
+1 2 days
+2 3 days
+3 4 days
+4 5 days
+dtype: category
+Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]"""
+
+ assert repr(s) == exp
+
+ idx = timedelta_range("1 hours", periods=10)
+ s = Series(Categorical(idx))
+ exp = """0 0 days 01:00:00
+1 1 days 01:00:00
+2 2 days 01:00:00
+3 3 days 01:00:00
+4 4 days 01:00:00
+5 5 days 01:00:00
+6 6 days 01:00:00
+7 7 days 01:00:00
+8 8 days 01:00:00
+9 9 days 01:00:00
+dtype: category
+Categories (10, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
+ 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00,
+ 8 days 01:00:00, 9 days 01:00:00]""" # noqa: E501
+
+ assert repr(s) == exp
+
+ def test_categorical_series_repr_timedelta_ordered(self):
+ idx = timedelta_range("1 days", periods=5)
+ s = Series(Categorical(idx, ordered=True))
+ exp = """0 1 days
+1 2 days
+2 3 days
+3 4 days
+4 5 days
+dtype: category
+Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]"""
+
+ assert repr(s) == exp
+
+ idx = timedelta_range("1 hours", periods=10)
+ s = Series(Categorical(idx, ordered=True))
+ exp = """0 0 days 01:00:00
+1 1 days 01:00:00
+2 2 days 01:00:00
+3 3 days 01:00:00
+4 4 days 01:00:00
+5 5 days 01:00:00
+6 6 days 01:00:00
+7 7 days 01:00:00
+8 8 days 01:00:00
+9 9 days 01:00:00
+dtype: category
+Categories (10, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
+ 3 days 01:00:00 ... 6 days 01:00:00 < 7 days 01:00:00 <
+ 8 days 01:00:00 < 9 days 01:00:00]""" # noqa: E501
+
+ assert repr(s) == exp
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_subclass.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_subclass.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2d5afcf884b12b3007905061b7c503359e71a5d
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_subclass.py
@@ -0,0 +1,82 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+pytestmark = pytest.mark.filterwarnings(
+ "ignore:Passing a BlockManager|Passing a SingleBlockManager:DeprecationWarning"
+)
+
+
+class TestSeriesSubclassing:
+ @pytest.mark.parametrize(
+ "idx_method, indexer, exp_data, exp_idx",
+ [
+ ["loc", ["a", "b"], [1, 2], "ab"],
+ ["iloc", [2, 3], [3, 4], "cd"],
+ ],
+ )
+ def test_indexing_sliced(self, idx_method, indexer, exp_data, exp_idx):
+ s = tm.SubclassedSeries([1, 2, 3, 4], index=list("abcd"))
+ res = getattr(s, idx_method)[indexer]
+ exp = tm.SubclassedSeries(exp_data, index=list(exp_idx))
+ tm.assert_series_equal(res, exp)
+
+ def test_to_frame(self):
+ s = tm.SubclassedSeries([1, 2, 3, 4], index=list("abcd"), name="xxx")
+ res = s.to_frame()
+ exp = tm.SubclassedDataFrame({"xxx": [1, 2, 3, 4]}, index=list("abcd"))
+ tm.assert_frame_equal(res, exp)
+
+ def test_subclass_unstack(self):
+ # GH 15564
+ s = tm.SubclassedSeries([1, 2, 3, 4], index=[list("aabb"), list("xyxy")])
+
+ res = s.unstack()
+ exp = tm.SubclassedDataFrame({"x": [1, 3], "y": [2, 4]}, index=["a", "b"])
+
+ tm.assert_frame_equal(res, exp)
+
+ def test_subclass_empty_repr(self):
+ sub_series = tm.SubclassedSeries()
+ assert "SubclassedSeries" in repr(sub_series)
+
+ def test_asof(self):
+ N = 3
+ rng = pd.date_range("1/1/1990", periods=N, freq="53s")
+ s = tm.SubclassedSeries({"A": [np.nan, np.nan, np.nan]}, index=rng)
+
+ result = s.asof(rng[-2:])
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_explode(self):
+ s = tm.SubclassedSeries([[1, 2, 3], "foo", [], [3, 4]])
+ result = s.explode()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_equals(self):
+ # https://github.com/pandas-dev/pandas/pull/34402
+ # allow subclass in both directions
+ s1 = pd.Series([1, 2, 3])
+ s2 = tm.SubclassedSeries([1, 2, 3])
+ assert s1.equals(s2)
+ assert s2.equals(s1)
+
+
+class SubclassedSeries(pd.Series):
+ @property
+ def _constructor(self):
+ def _new(*args, **kwargs):
+ # some constructor logic that accesses the Series' name
+ if self.name == "test":
+ return pd.Series(*args, **kwargs)
+ return SubclassedSeries(*args, **kwargs)
+
+ return _new
+
+
+def test_constructor_from_dict():
+ # https://github.com/pandas-dev/pandas/issues/52445
+ result = SubclassedSeries({"a": 1, "b": 2, "c": 3})
+ assert isinstance(result, SubclassedSeries)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_ufunc.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_ufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..698c727f1beb81340dab6768d597a922cdfa9deb
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_ufunc.py
@@ -0,0 +1,460 @@
+from collections import deque
+import re
+import string
+
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.arrays import SparseArray
+
+
+@pytest.fixture(params=[np.add, np.logaddexp])
+def ufunc(request):
+ # dunder op
+ return request.param
+
+
+@pytest.fixture(params=[True, False], ids=["sparse", "dense"])
+def sparse(request):
+ return request.param
+
+
+@pytest.fixture
+def arrays_for_binary_ufunc():
+ """
+ A pair of random, length-100 integer-dtype arrays, that are mostly 0.
+ """
+ a1 = np.random.default_rng(2).integers(0, 10, 100, dtype="int64")
+ a2 = np.random.default_rng(2).integers(0, 10, 100, dtype="int64")
+ a1[::3] = 0
+ a2[::4] = 0
+ return a1, a2
+
+
+@pytest.mark.parametrize("ufunc", [np.positive, np.floor, np.exp])
+def test_unary_ufunc(ufunc, sparse):
+ # Test that ufunc(pd.Series) == pd.Series(ufunc)
+ arr = np.random.default_rng(2).integers(0, 10, 10, dtype="int64")
+ arr[::2] = 0
+ if sparse:
+ arr = SparseArray(arr, dtype=pd.SparseDtype("int64", 0))
+
+ index = list(string.ascii_letters[:10])
+ name = "name"
+ series = pd.Series(arr, index=index, name=name)
+
+ result = ufunc(series)
+ expected = pd.Series(ufunc(arr), index=index, name=name)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("flip", [True, False], ids=["flipped", "straight"])
+def test_binary_ufunc_with_array(flip, sparse, ufunc, arrays_for_binary_ufunc):
+ # Test that ufunc(pd.Series(a), array) == pd.Series(ufunc(a, b))
+ a1, a2 = arrays_for_binary_ufunc
+ if sparse:
+ a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0))
+ a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
+
+ name = "name" # op(pd.Series, array) preserves the name.
+ series = pd.Series(a1, name=name)
+ other = a2
+
+ array_args = (a1, a2)
+ series_args = (series, other) # ufunc(series, array)
+
+ if flip:
+ array_args = reversed(array_args)
+ series_args = reversed(series_args) # ufunc(array, series)
+
+ expected = pd.Series(ufunc(*array_args), name=name)
+ result = ufunc(*series_args)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("flip", [True, False], ids=["flipped", "straight"])
+def test_binary_ufunc_with_index(flip, sparse, ufunc, arrays_for_binary_ufunc):
+ # Test that
+ # * func(pd.Series(a), pd.Series(b)) == pd.Series(ufunc(a, b))
+ # * ufunc(Index, pd.Series) dispatches to pd.Series (returns a pd.Series)
+ a1, a2 = arrays_for_binary_ufunc
+ if sparse:
+ a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0))
+ a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
+
+ name = "name" # op(pd.Series, array) preserves the name.
+ series = pd.Series(a1, name=name)
+
+ other = pd.Index(a2, name=name).astype("int64")
+
+ array_args = (a1, a2)
+ series_args = (series, other) # ufunc(series, array)
+
+ if flip:
+ array_args = reversed(array_args)
+ series_args = reversed(series_args) # ufunc(array, series)
+
+ expected = pd.Series(ufunc(*array_args), name=name)
+ result = ufunc(*series_args)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("shuffle", [True, False], ids=["unaligned", "aligned"])
+@pytest.mark.parametrize("flip", [True, False], ids=["flipped", "straight"])
+def test_binary_ufunc_with_series(
+ flip, shuffle, sparse, ufunc, arrays_for_binary_ufunc
+):
+ # Test that
+ # * func(pd.Series(a), pd.Series(b)) == pd.Series(ufunc(a, b))
+ # with alignment between the indices
+ a1, a2 = arrays_for_binary_ufunc
+ if sparse:
+ a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0))
+ a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
+
+ name = "name" # op(pd.Series, array) preserves the name.
+ series = pd.Series(a1, name=name)
+ other = pd.Series(a2, name=name)
+
+ idx = np.random.default_rng(2).permutation(len(a1))
+
+ if shuffle:
+ other = other.take(idx)
+ if flip:
+ index = other.align(series)[0].index
+ else:
+ index = series.align(other)[0].index
+ else:
+ index = series.index
+
+ array_args = (a1, a2)
+ series_args = (series, other) # ufunc(series, array)
+
+ if flip:
+ array_args = tuple(reversed(array_args))
+ series_args = tuple(reversed(series_args)) # ufunc(array, series)
+
+ expected = pd.Series(ufunc(*array_args), index=index, name=name)
+ result = ufunc(*series_args)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("flip", [True, False])
+def test_binary_ufunc_scalar(ufunc, sparse, flip, arrays_for_binary_ufunc):
+ # Test that
+ # * ufunc(pd.Series, scalar) == pd.Series(ufunc(array, scalar))
+ # * ufunc(pd.Series, scalar) == ufunc(scalar, pd.Series)
+ arr, _ = arrays_for_binary_ufunc
+ if sparse:
+ arr = SparseArray(arr)
+ other = 2
+ series = pd.Series(arr, name="name")
+
+ series_args = (series, other)
+ array_args = (arr, other)
+
+ if flip:
+ series_args = tuple(reversed(series_args))
+ array_args = tuple(reversed(array_args))
+
+ expected = pd.Series(ufunc(*array_args), name="name")
+ result = ufunc(*series_args)
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("ufunc", [np.divmod]) # TODO: np.modf, np.frexp
+@pytest.mark.parametrize("shuffle", [True, False])
+@pytest.mark.filterwarnings("ignore:divide by zero:RuntimeWarning")
+def test_multiple_output_binary_ufuncs(ufunc, sparse, shuffle, arrays_for_binary_ufunc):
+ # Test that
+ # the same conditions from binary_ufunc_scalar apply to
+ # ufuncs with multiple outputs.
+
+ a1, a2 = arrays_for_binary_ufunc
+ # work around https://github.com/pandas-dev/pandas/issues/26987
+ a1[a1 == 0] = 1
+ a2[a2 == 0] = 1
+
+ if sparse:
+ a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0))
+ a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
+
+ s1 = pd.Series(a1)
+ s2 = pd.Series(a2)
+
+ if shuffle:
+ # ensure we align before applying the ufunc
+ s2 = s2.sample(frac=1)
+
+ expected = ufunc(a1, a2)
+ assert isinstance(expected, tuple)
+
+ result = ufunc(s1, s2)
+ assert isinstance(result, tuple)
+ tm.assert_series_equal(result[0], pd.Series(expected[0]))
+ tm.assert_series_equal(result[1], pd.Series(expected[1]))
+
+
+def test_multiple_output_ufunc(sparse, arrays_for_binary_ufunc):
+ # Test that the same conditions from unary input apply to multi-output
+ # ufuncs
+ arr, _ = arrays_for_binary_ufunc
+
+ if sparse:
+ arr = SparseArray(arr)
+
+ series = pd.Series(arr, name="name")
+ result = np.modf(series)
+ expected = np.modf(arr)
+
+ assert isinstance(result, tuple)
+ assert isinstance(expected, tuple)
+
+ tm.assert_series_equal(result[0], pd.Series(expected[0], name="name"))
+ tm.assert_series_equal(result[1], pd.Series(expected[1], name="name"))
+
+
+def test_binary_ufunc_drops_series_name(ufunc, sparse, arrays_for_binary_ufunc):
+ # Drop the names when they differ.
+ a1, a2 = arrays_for_binary_ufunc
+ s1 = pd.Series(a1, name="a")
+ s2 = pd.Series(a2, name="b")
+
+ result = ufunc(s1, s2)
+ assert result.name is None
+
+
+def test_object_series_ok():
+ class Dummy:
+ def __init__(self, value) -> None:
+ self.value = value
+
+ def __add__(self, other):
+ return self.value + other.value
+
+ arr = np.array([Dummy(0), Dummy(1)])
+ ser = pd.Series(arr)
+ tm.assert_series_equal(np.add(ser, ser), pd.Series(np.add(ser, arr)))
+ tm.assert_series_equal(np.add(ser, Dummy(1)), pd.Series(np.add(ser, Dummy(1))))
+
+
+@pytest.fixture(
+ params=[
+ pd.array([1, 3, 2], dtype=np.int64),
+ pd.array([1, 3, 2], dtype="Int64"),
+ pd.array([1, 3, 2], dtype="Float32"),
+ pd.array([1, 10, 2], dtype="Sparse[int]"),
+ pd.to_datetime(["2000", "2010", "2001"]),
+ pd.to_datetime(["2000", "2010", "2001"]).tz_localize("CET"),
+ pd.to_datetime(["2000", "2010", "2001"]).to_period(freq="D"),
+ pd.to_timedelta(["1 Day", "3 Days", "2 Days"]),
+ pd.IntervalIndex([pd.Interval(0, 1), pd.Interval(2, 3), pd.Interval(1, 2)]),
+ ],
+ ids=lambda x: str(x.dtype),
+)
+def values_for_np_reduce(request):
+ # min/max tests assume that these are monotonic increasing
+ return request.param
+
+
+class TestNumpyReductions:
+ # TODO: cases with NAs, axis kwarg for DataFrame
+
+ def test_multiply(self, values_for_np_reduce, box_with_array, request):
+ box = box_with_array
+ values = values_for_np_reduce
+
+ with tm.assert_produces_warning(None):
+ obj = box(values)
+
+ if isinstance(values, pd.core.arrays.SparseArray):
+ mark = pytest.mark.xfail(reason="SparseArray has no 'prod'")
+ request.node.add_marker(mark)
+
+ if values.dtype.kind in "iuf":
+ result = np.multiply.reduce(obj)
+ if box is pd.DataFrame:
+ expected = obj.prod(numeric_only=False)
+ tm.assert_series_equal(result, expected)
+ elif box is pd.Index:
+ # Index has no 'prod'
+ expected = obj._values.prod()
+ assert result == expected
+ else:
+ expected = obj.prod()
+ assert result == expected
+ else:
+ msg = "|".join(
+ [
+ "does not support reduction",
+ "unsupported operand type",
+ "ufunc 'multiply' cannot use operands",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ np.multiply.reduce(obj)
+
+ def test_add(self, values_for_np_reduce, box_with_array):
+ box = box_with_array
+ values = values_for_np_reduce
+
+ with tm.assert_produces_warning(None):
+ obj = box(values)
+
+ if values.dtype.kind in "miuf":
+ result = np.add.reduce(obj)
+ if box is pd.DataFrame:
+ expected = obj.sum(numeric_only=False)
+ tm.assert_series_equal(result, expected)
+ elif box is pd.Index:
+ # Index has no 'sum'
+ expected = obj._values.sum()
+ assert result == expected
+ else:
+ expected = obj.sum()
+ assert result == expected
+ else:
+ msg = "|".join(
+ [
+ "does not support reduction",
+ "unsupported operand type",
+ "ufunc 'add' cannot use operands",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ np.add.reduce(obj)
+
+ def test_max(self, values_for_np_reduce, box_with_array):
+ box = box_with_array
+ values = values_for_np_reduce
+
+ same_type = True
+ if box is pd.Index and values.dtype.kind in ["i", "f"]:
+ # ATM Index casts to object, so we get python ints/floats
+ same_type = False
+
+ with tm.assert_produces_warning(None):
+ obj = box(values)
+
+ result = np.maximum.reduce(obj)
+ if box is pd.DataFrame:
+ # TODO: cases with axis kwarg
+ expected = obj.max(numeric_only=False)
+ tm.assert_series_equal(result, expected)
+ else:
+ expected = values[1]
+ assert result == expected
+ if same_type:
+ # check we have e.g. Timestamp instead of dt64
+ assert type(result) == type(expected)
+
+ def test_min(self, values_for_np_reduce, box_with_array):
+ box = box_with_array
+ values = values_for_np_reduce
+
+ same_type = True
+ if box is pd.Index and values.dtype.kind in ["i", "f"]:
+ # ATM Index casts to object, so we get python ints/floats
+ same_type = False
+
+ with tm.assert_produces_warning(None):
+ obj = box(values)
+
+ result = np.minimum.reduce(obj)
+ if box is pd.DataFrame:
+ expected = obj.min(numeric_only=False)
+ tm.assert_series_equal(result, expected)
+ else:
+ expected = values[0]
+ assert result == expected
+ if same_type:
+ # check we have e.g. Timestamp instead of dt64
+ assert type(result) == type(expected)
+
+
+@pytest.mark.parametrize("type_", [list, deque, tuple])
+def test_binary_ufunc_other_types(type_):
+ a = pd.Series([1, 2, 3], name="name")
+ b = type_([3, 4, 5])
+
+ result = np.add(a, b)
+ expected = pd.Series(np.add(a.to_numpy(), b), name="name")
+ tm.assert_series_equal(result, expected)
+
+
+def test_object_dtype_ok():
+ class Thing:
+ def __init__(self, value) -> None:
+ self.value = value
+
+ def __add__(self, other):
+ other = getattr(other, "value", other)
+ return type(self)(self.value + other)
+
+ def __eq__(self, other) -> bool:
+ return type(other) is Thing and self.value == other.value
+
+ def __repr__(self) -> str:
+ return f"Thing({self.value})"
+
+ s = pd.Series([Thing(1), Thing(2)])
+ result = np.add(s, Thing(1))
+ expected = pd.Series([Thing(2), Thing(3)])
+ tm.assert_series_equal(result, expected)
+
+
+def test_outer():
+ # https://github.com/pandas-dev/pandas/issues/27186
+ ser = pd.Series([1, 2, 3])
+ obj = np.array([1, 2, 3])
+
+ with pytest.raises(NotImplementedError, match=tm.EMPTY_STRING_PATTERN):
+ np.subtract.outer(ser, obj)
+
+
+def test_np_matmul():
+ # GH26650
+ df1 = pd.DataFrame(data=[[-1, 1, 10]])
+ df2 = pd.DataFrame(data=[-1, 1, 10])
+ expected = pd.DataFrame(data=[102])
+
+ result = np.matmul(df1, df2)
+ tm.assert_frame_equal(expected, result)
+
+
+def test_array_ufuncs_for_many_arguments():
+ # GH39853
+ def add3(x, y, z):
+ return x + y + z
+
+ ufunc = np.frompyfunc(add3, 3, 1)
+ ser = pd.Series([1, 2])
+
+ result = ufunc(ser, ser, 1)
+ expected = pd.Series([3, 5], dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ df = pd.DataFrame([[1, 2]])
+
+ msg = (
+ "Cannot apply ufunc "
+ "to mixed DataFrame and Series inputs."
+ )
+ with pytest.raises(NotImplementedError, match=re.escape(msg)):
+ ufunc(ser, ser, df)
+
+
+# TODO(CoW) see https://github.com/pandas-dev/pandas/pull/51082
+@td.skip_copy_on_write_not_yet_implemented
+def test_np_fix():
+ # np.fix is not a ufunc but is composed of several ufunc calls under the hood
+ # with `out` and `where` keywords
+ ser = pd.Series([-1.5, -0.5, 0.5, 1.5])
+ result = np.fix(ser)
+ expected = pd.Series([-1.0, -0.0, 0.0, 1.0])
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_unary.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_unary.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad0e344fa4420dadeb33976db85a1e108427c65f
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_unary.py
@@ -0,0 +1,52 @@
+import pytest
+
+from pandas import Series
+import pandas._testing as tm
+
+
+class TestSeriesUnaryOps:
+ # __neg__, __pos__, __invert__
+
+ def test_neg(self):
+ ser = tm.makeStringSeries()
+ ser.name = "series"
+ tm.assert_series_equal(-ser, -1 * ser)
+
+ def test_invert(self):
+ ser = tm.makeStringSeries()
+ ser.name = "series"
+ tm.assert_series_equal(-(ser < 0), ~(ser < 0))
+
+ @pytest.mark.parametrize(
+ "source, neg_target, abs_target",
+ [
+ ([1, 2, 3], [-1, -2, -3], [1, 2, 3]),
+ ([1, 2, None], [-1, -2, None], [1, 2, None]),
+ ],
+ )
+ def test_all_numeric_unary_operators(
+ self, any_numeric_ea_dtype, source, neg_target, abs_target
+ ):
+ # GH38794
+ dtype = any_numeric_ea_dtype
+ ser = Series(source, dtype=dtype)
+ neg_result, pos_result, abs_result = -ser, +ser, abs(ser)
+ if dtype.startswith("U"):
+ neg_target = -Series(source, dtype=dtype)
+ else:
+ neg_target = Series(neg_target, dtype=dtype)
+
+ abs_target = Series(abs_target, dtype=dtype)
+
+ tm.assert_series_equal(neg_result, neg_target)
+ tm.assert_series_equal(pos_result, ser)
+ tm.assert_series_equal(abs_result, abs_target)
+
+ @pytest.mark.parametrize("op", ["__neg__", "__abs__"])
+ def test_unary_float_op_mask(self, float_ea_dtype, op):
+ dtype = float_ea_dtype
+ ser = Series([1.1, 2.2, 3.3], dtype=dtype)
+ result = getattr(ser, op)()
+ target = result.copy(deep=True)
+ ser[0] = None
+ tm.assert_series_equal(result, target)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_validate.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_validate.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c867f7582b7d3250bf5e009ffbf7545da404712
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/test_validate.py
@@ -0,0 +1,26 @@
+import pytest
+
+
+@pytest.mark.parametrize(
+ "func",
+ [
+ "reset_index",
+ "_set_name",
+ "sort_values",
+ "sort_index",
+ "rename",
+ "dropna",
+ "drop_duplicates",
+ ],
+)
+@pytest.mark.parametrize("inplace", [1, "True", [1, 2, 3], 5.0])
+def test_validate_bool_args(string_series, func, inplace):
+ """Tests for error handling related to data types of method arguments."""
+ msg = 'For argument "inplace" expected type bool'
+ kwargs = {"inplace": inplace}
+
+ if func == "_set_name":
+ kwargs["name"] = "hello"
+
+ with pytest.raises(ValueError, match=msg):
+ getattr(string_series, func)(**kwargs)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01b49b5e5b63323b065ec11fc34f6c247a7b0350
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/__init__.py
@@ -0,0 +1,15 @@
+import numpy as np
+
+import pandas as pd
+
+object_pyarrow_numpy = ("object", "string[pyarrow_numpy]")
+
+
+def _convert_na_value(ser, expected):
+ if ser.dtype != object:
+ if ser.dtype.storage == "pyarrow_numpy":
+ expected = expected.fillna(np.nan)
+ else:
+ # GH#18463
+ expected = expected.fillna(pd.NA)
+ return expected
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/conftest.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e1ee89e9a8410b3da44370034c0bdabfe388a05
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/conftest.py
@@ -0,0 +1,175 @@
+import numpy as np
+import pytest
+
+from pandas import Series
+from pandas.core.strings.accessor import StringMethods
+
+_any_string_method = [
+ ("cat", (), {"sep": ","}),
+ ("cat", (Series(list("zyx")),), {"sep": ",", "join": "left"}),
+ ("center", (10,), {}),
+ ("contains", ("a",), {}),
+ ("count", ("a",), {}),
+ ("decode", ("UTF-8",), {}),
+ ("encode", ("UTF-8",), {}),
+ ("endswith", ("a",), {}),
+ ("endswith", ("a",), {"na": True}),
+ ("endswith", ("a",), {"na": False}),
+ ("extract", ("([a-z]*)",), {"expand": False}),
+ ("extract", ("([a-z]*)",), {"expand": True}),
+ ("extractall", ("([a-z]*)",), {}),
+ ("find", ("a",), {}),
+ ("findall", ("a",), {}),
+ ("get", (0,), {}),
+ # because "index" (and "rindex") fail intentionally
+ # if the string is not found, search only for empty string
+ ("index", ("",), {}),
+ ("join", (",",), {}),
+ ("ljust", (10,), {}),
+ ("match", ("a",), {}),
+ ("fullmatch", ("a",), {}),
+ ("normalize", ("NFC",), {}),
+ ("pad", (10,), {}),
+ ("partition", (" ",), {"expand": False}),
+ ("partition", (" ",), {"expand": True}),
+ ("repeat", (3,), {}),
+ ("replace", ("a", "z"), {}),
+ ("rfind", ("a",), {}),
+ ("rindex", ("",), {}),
+ ("rjust", (10,), {}),
+ ("rpartition", (" ",), {"expand": False}),
+ ("rpartition", (" ",), {"expand": True}),
+ ("slice", (0, 1), {}),
+ ("slice_replace", (0, 1, "z"), {}),
+ ("split", (" ",), {"expand": False}),
+ ("split", (" ",), {"expand": True}),
+ ("startswith", ("a",), {}),
+ ("startswith", ("a",), {"na": True}),
+ ("startswith", ("a",), {"na": False}),
+ ("removeprefix", ("a",), {}),
+ ("removesuffix", ("a",), {}),
+ # translating unicode points of "a" to "d"
+ ("translate", ({97: 100},), {}),
+ ("wrap", (2,), {}),
+ ("zfill", (10,), {}),
+] + list(
+ zip(
+ [
+ # methods without positional arguments: zip with empty tuple and empty dict
+ "capitalize",
+ "cat",
+ "get_dummies",
+ "isalnum",
+ "isalpha",
+ "isdecimal",
+ "isdigit",
+ "islower",
+ "isnumeric",
+ "isspace",
+ "istitle",
+ "isupper",
+ "len",
+ "lower",
+ "lstrip",
+ "partition",
+ "rpartition",
+ "rsplit",
+ "rstrip",
+ "slice",
+ "slice_replace",
+ "split",
+ "strip",
+ "swapcase",
+ "title",
+ "upper",
+ "casefold",
+ ],
+ [()] * 100,
+ [{}] * 100,
+ )
+)
+ids, _, _ = zip(*_any_string_method) # use method name as fixture-id
+missing_methods = {f for f in dir(StringMethods) if not f.startswith("_")} - set(ids)
+
+# test that the above list captures all methods of StringMethods
+assert not missing_methods
+
+
+@pytest.fixture(params=_any_string_method, ids=ids)
+def any_string_method(request):
+ """
+ Fixture for all public methods of `StringMethods`
+
+ This fixture returns a tuple of the method name and sample arguments
+ necessary to call the method.
+
+ Returns
+ -------
+ method_name : str
+ The name of the method in `StringMethods`
+ args : tuple
+ Sample values for the positional arguments
+ kwargs : dict
+ Sample values for the keyword arguments
+
+ Examples
+ --------
+ >>> def test_something(any_string_method):
+ ... s = Series(['a', 'b', np.nan, 'd'])
+ ...
+ ... method_name, args, kwargs = any_string_method
+ ... method = getattr(s.str, method_name)
+ ... # will not raise
+ ... method(*args, **kwargs)
+ """
+ return request.param
+
+
+# subset of the full set from pandas/conftest.py
+_any_allowed_skipna_inferred_dtype = [
+ ("string", ["a", np.nan, "c"]),
+ ("bytes", [b"a", np.nan, b"c"]),
+ ("empty", [np.nan, np.nan, np.nan]),
+ ("empty", []),
+ ("mixed-integer", ["a", np.nan, 2]),
+]
+ids, _ = zip(*_any_allowed_skipna_inferred_dtype) # use inferred type as id
+
+
+@pytest.fixture(params=_any_allowed_skipna_inferred_dtype, ids=ids)
+def any_allowed_skipna_inferred_dtype(request):
+ """
+ Fixture for all (inferred) dtypes allowed in StringMethods.__init__
+
+ The covered (inferred) types are:
+ * 'string'
+ * 'empty'
+ * 'bytes'
+ * 'mixed'
+ * 'mixed-integer'
+
+ Returns
+ -------
+ inferred_dtype : str
+ The string for the inferred dtype from _libs.lib.infer_dtype
+ values : np.ndarray
+ An array of object dtype that will be inferred to have
+ `inferred_dtype`
+
+ Examples
+ --------
+ >>> from pandas._libs import lib
+ >>>
+ >>> def test_something(any_allowed_skipna_inferred_dtype):
+ ... inferred_dtype, values = any_allowed_skipna_inferred_dtype
+ ... # will pass
+ ... assert lib.infer_dtype(values, skipna=True) == inferred_dtype
+ ...
+ ... # constructor for .str-accessor will also pass
+ ... Series(values).str
+ """
+ inferred_dtype, values = request.param
+ values = np.array(values, dtype=object) # object dtype to avoid casting
+
+ # correctness of inference tested in tests/dtypes/test_inference.py
+ return inferred_dtype, values
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_api.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..c439a5f00692262161983ba7b39f58043e2f7f4a
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_api.py
@@ -0,0 +1,144 @@
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ _testing as tm,
+)
+from pandas.core.strings.accessor import StringMethods
+
+
+def test_api(any_string_dtype):
+ # GH 6106, GH 9322
+ assert Series.str is StringMethods
+ assert isinstance(Series([""], dtype=any_string_dtype).str, StringMethods)
+
+
+def test_api_mi_raises():
+ # GH 23679
+ mi = MultiIndex.from_arrays([["a", "b", "c"]])
+ msg = "Can only use .str accessor with Index, not MultiIndex"
+ with pytest.raises(AttributeError, match=msg):
+ mi.str
+ assert not hasattr(mi, "str")
+
+
+@pytest.mark.parametrize("dtype", [object, "category"])
+def test_api_per_dtype(index_or_series, dtype, any_skipna_inferred_dtype):
+ # one instance of parametrized fixture
+ box = index_or_series
+ inferred_dtype, values = any_skipna_inferred_dtype
+
+ t = box(values, dtype=dtype) # explicit dtype to avoid casting
+
+ types_passing_constructor = [
+ "string",
+ "unicode",
+ "empty",
+ "bytes",
+ "mixed",
+ "mixed-integer",
+ ]
+ if inferred_dtype in types_passing_constructor:
+ # GH 6106
+ assert isinstance(t.str, StringMethods)
+ else:
+ # GH 9184, GH 23011, GH 23163
+ msg = "Can only use .str accessor with string values.*"
+ with pytest.raises(AttributeError, match=msg):
+ t.str
+ assert not hasattr(t, "str")
+
+
+@pytest.mark.parametrize("dtype", [object, "category"])
+def test_api_per_method(
+ index_or_series,
+ dtype,
+ any_allowed_skipna_inferred_dtype,
+ any_string_method,
+ request,
+):
+ # this test does not check correctness of the different methods,
+ # just that the methods work on the specified (inferred) dtypes,
+ # and raise on all others
+ box = index_or_series
+
+ # one instance of each parametrized fixture
+ inferred_dtype, values = any_allowed_skipna_inferred_dtype
+ method_name, args, kwargs = any_string_method
+
+ reason = None
+ if box is Index and values.size == 0:
+ if method_name in ["partition", "rpartition"] and kwargs.get("expand", True):
+ raises = TypeError
+ reason = "Method cannot deal with empty Index"
+ elif method_name == "split" and kwargs.get("expand", None):
+ raises = TypeError
+ reason = "Split fails on empty Series when expand=True"
+ elif method_name == "get_dummies":
+ raises = ValueError
+ reason = "Need to fortify get_dummies corner cases"
+
+ elif (
+ box is Index
+ and inferred_dtype == "empty"
+ and dtype == object
+ and method_name == "get_dummies"
+ ):
+ raises = ValueError
+ reason = "Need to fortify get_dummies corner cases"
+
+ if reason is not None:
+ mark = pytest.mark.xfail(raises=raises, reason=reason)
+ request.node.add_marker(mark)
+
+ t = box(values, dtype=dtype) # explicit dtype to avoid casting
+ method = getattr(t.str, method_name)
+
+ bytes_allowed = method_name in ["decode", "get", "len", "slice"]
+ # as of v0.23.4, all methods except 'cat' are very lenient with the
+ # allowed data types, just returning NaN for entries that error.
+ # This could be changed with an 'errors'-kwarg to the `str`-accessor,
+ # see discussion in GH 13877
+ mixed_allowed = method_name not in ["cat"]
+
+ allowed_types = (
+ ["string", "unicode", "empty"]
+ + ["bytes"] * bytes_allowed
+ + ["mixed", "mixed-integer"] * mixed_allowed
+ )
+
+ if inferred_dtype in allowed_types:
+ # xref GH 23555, GH 23556
+ method(*args, **kwargs) # works!
+ else:
+ # GH 23011, GH 23163
+ msg = (
+ f"Cannot use .str.{method_name} with values of "
+ f"inferred dtype {repr(inferred_dtype)}."
+ )
+ with pytest.raises(TypeError, match=msg):
+ method(*args, **kwargs)
+
+
+def test_api_for_categorical(any_string_method, any_string_dtype):
+ # https://github.com/pandas-dev/pandas/issues/10661
+ s = Series(list("aabb"), dtype=any_string_dtype)
+ s = s + " " + s
+ c = s.astype("category")
+ assert isinstance(c.str, StringMethods)
+
+ method_name, args, kwargs = any_string_method
+
+ result = getattr(c.str, method_name)(*args, **kwargs)
+ expected = getattr(s.astype("object").str, method_name)(*args, **kwargs)
+
+ if isinstance(result, DataFrame):
+ tm.assert_frame_equal(result, expected)
+ elif isinstance(result, Series):
+ tm.assert_series_equal(result, expected)
+ else:
+ # str.cat(others=None) returns string, for example
+ assert result == expected
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_case_justify.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_case_justify.py
new file mode 100644
index 0000000000000000000000000000000000000000..1dee25e6316488d0f718bddd5d181c38eb729986
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_case_justify.py
@@ -0,0 +1,414 @@
+from datetime import datetime
+import operator
+
+import numpy as np
+import pytest
+
+from pandas import (
+ Series,
+ _testing as tm,
+)
+
+
+def test_title(any_string_dtype):
+ s = Series(["FOO", "BAR", np.nan, "Blah", "blurg"], dtype=any_string_dtype)
+ result = s.str.title()
+ expected = Series(["Foo", "Bar", np.nan, "Blah", "Blurg"], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_title_mixed_object():
+ s = Series(["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0])
+ result = s.str.title()
+ expected = Series(
+ ["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", None, np.nan, np.nan]
+ )
+ tm.assert_almost_equal(result, expected)
+
+
+def test_lower_upper(any_string_dtype):
+ s = Series(["om", np.nan, "nom", "nom"], dtype=any_string_dtype)
+
+ result = s.str.upper()
+ expected = Series(["OM", np.nan, "NOM", "NOM"], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+ result = result.str.lower()
+ tm.assert_series_equal(result, s)
+
+
+def test_lower_upper_mixed_object():
+ s = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0])
+
+ result = s.str.upper()
+ expected = Series(["A", np.nan, "B", np.nan, np.nan, "FOO", None, np.nan, np.nan])
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.lower()
+ expected = Series(["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan])
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, expected",
+ [
+ (
+ ["FOO", "BAR", np.nan, "Blah", "blurg"],
+ ["Foo", "Bar", np.nan, "Blah", "Blurg"],
+ ),
+ (["a", "b", "c"], ["A", "B", "C"]),
+ (["a b", "a bc. de"], ["A b", "A bc. de"]),
+ ],
+)
+def test_capitalize(data, expected, any_string_dtype):
+ s = Series(data, dtype=any_string_dtype)
+ result = s.str.capitalize()
+ expected = Series(expected, dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_capitalize_mixed_object():
+ s = Series(["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0])
+ result = s.str.capitalize()
+ expected = Series(
+ ["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", None, np.nan, np.nan]
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_swapcase(any_string_dtype):
+ s = Series(["FOO", "BAR", np.nan, "Blah", "blurg"], dtype=any_string_dtype)
+ result = s.str.swapcase()
+ expected = Series(["foo", "bar", np.nan, "bLAH", "BLURG"], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_swapcase_mixed_object():
+ s = Series(["FOO", np.nan, "bar", True, datetime.today(), "Blah", None, 1, 2.0])
+ result = s.str.swapcase()
+ expected = Series(
+ ["foo", np.nan, "BAR", np.nan, np.nan, "bLAH", None, np.nan, np.nan]
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_casefold():
+ # GH25405
+ expected = Series(["ss", np.nan, "case", "ssd"])
+ s = Series(["ß", np.nan, "case", "ßd"])
+ result = s.str.casefold()
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_casemethods(any_string_dtype):
+ values = ["aaa", "bbb", "CCC", "Dddd", "eEEE"]
+ s = Series(values, dtype=any_string_dtype)
+ assert s.str.lower().tolist() == [v.lower() for v in values]
+ assert s.str.upper().tolist() == [v.upper() for v in values]
+ assert s.str.title().tolist() == [v.title() for v in values]
+ assert s.str.capitalize().tolist() == [v.capitalize() for v in values]
+ assert s.str.swapcase().tolist() == [v.swapcase() for v in values]
+
+
+def test_pad(any_string_dtype):
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
+
+ result = s.str.pad(5, side="left")
+ expected = Series(
+ [" a", " b", np.nan, " c", np.nan, "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.pad(5, side="right")
+ expected = Series(
+ ["a ", "b ", np.nan, "c ", np.nan, "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.pad(5, side="both")
+ expected = Series(
+ [" a ", " b ", np.nan, " c ", np.nan, "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_pad_mixed_object():
+ s = Series(["a", np.nan, "b", True, datetime.today(), "ee", None, 1, 2.0])
+
+ result = s.str.pad(5, side="left")
+ expected = Series(
+ [" a", np.nan, " b", np.nan, np.nan, " ee", None, np.nan, np.nan]
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.pad(5, side="right")
+ expected = Series(
+ ["a ", np.nan, "b ", np.nan, np.nan, "ee ", None, np.nan, np.nan]
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.pad(5, side="both")
+ expected = Series(
+ [" a ", np.nan, " b ", np.nan, np.nan, " ee ", None, np.nan, np.nan]
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_pad_fillchar(any_string_dtype):
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
+
+ result = s.str.pad(5, side="left", fillchar="X")
+ expected = Series(
+ ["XXXXa", "XXXXb", np.nan, "XXXXc", np.nan, "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.pad(5, side="right", fillchar="X")
+ expected = Series(
+ ["aXXXX", "bXXXX", np.nan, "cXXXX", np.nan, "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.pad(5, side="both", fillchar="X")
+ expected = Series(
+ ["XXaXX", "XXbXX", np.nan, "XXcXX", np.nan, "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_pad_fillchar_bad_arg_raises(any_string_dtype):
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
+
+ msg = "fillchar must be a character, not str"
+ with pytest.raises(TypeError, match=msg):
+ s.str.pad(5, fillchar="XY")
+
+ msg = "fillchar must be a character, not int"
+ with pytest.raises(TypeError, match=msg):
+ s.str.pad(5, fillchar=5)
+
+
+@pytest.mark.parametrize("method_name", ["center", "ljust", "rjust", "zfill", "pad"])
+def test_pad_width_bad_arg_raises(method_name, any_string_dtype):
+ # see gh-13598
+ s = Series(["1", "22", "a", "bb"], dtype=any_string_dtype)
+ op = operator.methodcaller(method_name, "f")
+
+ msg = "width must be of integer type, not str"
+ with pytest.raises(TypeError, match=msg):
+ op(s.str)
+
+
+def test_center_ljust_rjust(any_string_dtype):
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
+
+ result = s.str.center(5)
+ expected = Series(
+ [" a ", " b ", np.nan, " c ", np.nan, "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.ljust(5)
+ expected = Series(
+ ["a ", "b ", np.nan, "c ", np.nan, "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.rjust(5)
+ expected = Series(
+ [" a", " b", np.nan, " c", np.nan, "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_center_ljust_rjust_mixed_object():
+ s = Series(["a", np.nan, "b", True, datetime.today(), "c", "eee", None, 1, 2.0])
+
+ result = s.str.center(5)
+ expected = Series(
+ [
+ " a ",
+ np.nan,
+ " b ",
+ np.nan,
+ np.nan,
+ " c ",
+ " eee ",
+ None,
+ np.nan,
+ np.nan,
+ ]
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.ljust(5)
+ expected = Series(
+ [
+ "a ",
+ np.nan,
+ "b ",
+ np.nan,
+ np.nan,
+ "c ",
+ "eee ",
+ None,
+ np.nan,
+ np.nan,
+ ]
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.rjust(5)
+ expected = Series(
+ [
+ " a",
+ np.nan,
+ " b",
+ np.nan,
+ np.nan,
+ " c",
+ " eee",
+ None,
+ np.nan,
+ np.nan,
+ ]
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_center_ljust_rjust_fillchar(any_string_dtype):
+ if any_string_dtype == "string[pyarrow_numpy]":
+ pytest.skip(
+ "Arrow logic is different, "
+ "see https://github.com/pandas-dev/pandas/pull/54533/files#r1299808126",
+ )
+ s = Series(["a", "bb", "cccc", "ddddd", "eeeeee"], dtype=any_string_dtype)
+
+ result = s.str.center(5, fillchar="X")
+ expected = Series(
+ ["XXaXX", "XXbbX", "Xcccc", "ddddd", "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+ expected = np.array([v.center(5, "X") for v in np.array(s)], dtype=np.object_)
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
+
+ result = s.str.ljust(5, fillchar="X")
+ expected = Series(
+ ["aXXXX", "bbXXX", "ccccX", "ddddd", "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+ expected = np.array([v.ljust(5, "X") for v in np.array(s)], dtype=np.object_)
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
+
+ result = s.str.rjust(5, fillchar="X")
+ expected = Series(
+ ["XXXXa", "XXXbb", "Xcccc", "ddddd", "eeeeee"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+ expected = np.array([v.rjust(5, "X") for v in np.array(s)], dtype=np.object_)
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
+
+
+def test_center_ljust_rjust_fillchar_bad_arg_raises(any_string_dtype):
+ s = Series(["a", "bb", "cccc", "ddddd", "eeeeee"], dtype=any_string_dtype)
+
+ # If fillchar is not a character, normal str raises TypeError
+ # 'aaa'.ljust(5, 'XY')
+ # TypeError: must be char, not str
+ template = "fillchar must be a character, not {dtype}"
+
+ with pytest.raises(TypeError, match=template.format(dtype="str")):
+ s.str.center(5, fillchar="XY")
+
+ with pytest.raises(TypeError, match=template.format(dtype="str")):
+ s.str.ljust(5, fillchar="XY")
+
+ with pytest.raises(TypeError, match=template.format(dtype="str")):
+ s.str.rjust(5, fillchar="XY")
+
+ with pytest.raises(TypeError, match=template.format(dtype="int")):
+ s.str.center(5, fillchar=1)
+
+ with pytest.raises(TypeError, match=template.format(dtype="int")):
+ s.str.ljust(5, fillchar=1)
+
+ with pytest.raises(TypeError, match=template.format(dtype="int")):
+ s.str.rjust(5, fillchar=1)
+
+
+def test_zfill(any_string_dtype):
+ s = Series(["1", "22", "aaa", "333", "45678"], dtype=any_string_dtype)
+
+ result = s.str.zfill(5)
+ expected = Series(
+ ["00001", "00022", "00aaa", "00333", "45678"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+ expected = np.array([v.zfill(5) for v in np.array(s)], dtype=np.object_)
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
+
+ result = s.str.zfill(3)
+ expected = Series(["001", "022", "aaa", "333", "45678"], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+ expected = np.array([v.zfill(3) for v in np.array(s)], dtype=np.object_)
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
+
+ s = Series(["1", np.nan, "aaa", np.nan, "45678"], dtype=any_string_dtype)
+ result = s.str.zfill(5)
+ expected = Series(
+ ["00001", np.nan, "00aaa", np.nan, "45678"], dtype=any_string_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_wrap(any_string_dtype):
+ # test values are: two words less than width, two words equal to width,
+ # two words greater than width, one word less than width, one word
+ # equal to width, one word greater than width, multiple tokens with
+ # trailing whitespace equal to width
+ s = Series(
+ [
+ "hello world",
+ "hello world!",
+ "hello world!!",
+ "abcdefabcde",
+ "abcdefabcdef",
+ "abcdefabcdefa",
+ "ab ab ab ab ",
+ "ab ab ab ab a",
+ "\t",
+ ],
+ dtype=any_string_dtype,
+ )
+
+ # expected values
+ expected = Series(
+ [
+ "hello world",
+ "hello world!",
+ "hello\nworld!!",
+ "abcdefabcde",
+ "abcdefabcdef",
+ "abcdefabcdef\na",
+ "ab ab ab ab",
+ "ab ab ab ab\na",
+ "",
+ ],
+ dtype=any_string_dtype,
+ )
+
+ result = s.str.wrap(12, break_long_words=True)
+ tm.assert_series_equal(result, expected)
+
+
+def test_wrap_unicode(any_string_dtype):
+ # test with pre and post whitespace (non-unicode), NaN, and non-ascii Unicode
+ s = Series(
+ [" pre ", np.nan, "\xac\u20ac\U00008000 abadcafe"], dtype=any_string_dtype
+ )
+ expected = Series(
+ [" pre", np.nan, "\xac\u20ac\U00008000 ab\nadcafe"], dtype=any_string_dtype
+ )
+ result = s.str.wrap(6)
+ tm.assert_series_equal(result, expected)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_cat.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_cat.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6303610b2037a1fbdcd0663e5c260113f9b4e04
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_cat.py
@@ -0,0 +1,393 @@
+import re
+
+import numpy as np
+import pytest
+
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ _testing as tm,
+ concat,
+)
+
+
+@pytest.mark.parametrize("other", [None, Series, Index])
+def test_str_cat_name(index_or_series, other):
+ # GH 21053
+ box = index_or_series
+ values = ["a", "b"]
+ if other:
+ other = other(values)
+ else:
+ other = values
+ result = box(values, name="name").str.cat(other, sep=",")
+ assert result.name == "name"
+
+
+def test_str_cat(index_or_series):
+ box = index_or_series
+ # test_cat above tests "str_cat" from ndarray;
+ # here testing "str.cat" from Series/Index to ndarray/list
+ s = box(["a", "a", "b", "b", "c", np.nan])
+
+ # single array
+ result = s.str.cat()
+ expected = "aabbc"
+ assert result == expected
+
+ result = s.str.cat(na_rep="-")
+ expected = "aabbc-"
+ assert result == expected
+
+ result = s.str.cat(sep="_", na_rep="NA")
+ expected = "a_a_b_b_c_NA"
+ assert result == expected
+
+ t = np.array(["a", np.nan, "b", "d", "foo", np.nan], dtype=object)
+ expected = box(["aa", "a-", "bb", "bd", "cfoo", "--"])
+
+ # Series/Index with array
+ result = s.str.cat(t, na_rep="-")
+ tm.assert_equal(result, expected)
+
+ # Series/Index with list
+ result = s.str.cat(list(t), na_rep="-")
+ tm.assert_equal(result, expected)
+
+ # errors for incorrect lengths
+ rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
+ z = Series(["1", "2", "3"])
+
+ with pytest.raises(ValueError, match=rgx):
+ s.str.cat(z.values)
+
+ with pytest.raises(ValueError, match=rgx):
+ s.str.cat(list(z))
+
+
+def test_str_cat_raises_intuitive_error(index_or_series):
+ # GH 11334
+ box = index_or_series
+ s = box(["a", "b", "c", "d"])
+ message = "Did you mean to supply a `sep` keyword?"
+ with pytest.raises(ValueError, match=message):
+ s.str.cat("|")
+ with pytest.raises(ValueError, match=message):
+ s.str.cat(" ")
+
+
+@pytest.mark.parametrize("sep", ["", None])
+@pytest.mark.parametrize("dtype_target", ["object", "category"])
+@pytest.mark.parametrize("dtype_caller", ["object", "category"])
+def test_str_cat_categorical(index_or_series, dtype_caller, dtype_target, sep):
+ box = index_or_series
+
+ s = Index(["a", "a", "b", "a"], dtype=dtype_caller)
+ s = s if box == Index else Series(s, index=s)
+ t = Index(["b", "a", "b", "c"], dtype=dtype_target)
+
+ expected = Index(["ab", "aa", "bb", "ac"])
+ expected = expected if box == Index else Series(expected, index=s)
+
+ # Series/Index with unaligned Index -> t.values
+ result = s.str.cat(t.values, sep=sep)
+ tm.assert_equal(result, expected)
+
+ # Series/Index with Series having matching Index
+ t = Series(t.values, index=s)
+ result = s.str.cat(t, sep=sep)
+ tm.assert_equal(result, expected)
+
+ # Series/Index with Series.values
+ result = s.str.cat(t.values, sep=sep)
+ tm.assert_equal(result, expected)
+
+ # Series/Index with Series having different Index
+ t = Series(t.values, index=t.values)
+ expected = Index(["aa", "aa", "aa", "bb", "bb"])
+ expected = expected if box == Index else Series(expected, index=expected.str[:1])
+
+ result = s.str.cat(t, sep=sep)
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data",
+ [[1, 2, 3], [0.1, 0.2, 0.3], [1, 2, "b"]],
+ ids=["integers", "floats", "mixed"],
+)
+# without dtype=object, np.array would cast [1, 2, 'b'] to ['1', '2', 'b']
+@pytest.mark.parametrize(
+ "box",
+ [Series, Index, list, lambda x: np.array(x, dtype=object)],
+ ids=["Series", "Index", "list", "np.array"],
+)
+def test_str_cat_wrong_dtype_raises(box, data):
+ # GH 22722
+ s = Series(["a", "b", "c"])
+ t = box(data)
+
+ msg = "Concatenation requires list-likes containing only strings.*"
+ with pytest.raises(TypeError, match=msg):
+ # need to use outer and na_rep, as otherwise Index would not raise
+ s.str.cat(t, join="outer", na_rep="-")
+
+
+def test_str_cat_mixed_inputs(index_or_series):
+ box = index_or_series
+ s = Index(["a", "b", "c", "d"])
+ s = s if box == Index else Series(s, index=s)
+
+ t = Series(["A", "B", "C", "D"], index=s.values)
+ d = concat([t, Series(s, index=s)], axis=1)
+
+ expected = Index(["aAa", "bBb", "cCc", "dDd"])
+ expected = expected if box == Index else Series(expected.values, index=s.values)
+
+ # Series/Index with DataFrame
+ result = s.str.cat(d)
+ tm.assert_equal(result, expected)
+
+ # Series/Index with two-dimensional ndarray
+ result = s.str.cat(d.values)
+ tm.assert_equal(result, expected)
+
+ # Series/Index with list of Series
+ result = s.str.cat([t, s])
+ tm.assert_equal(result, expected)
+
+ # Series/Index with mixed list of Series/array
+ result = s.str.cat([t, s.values])
+ tm.assert_equal(result, expected)
+
+ # Series/Index with list of Series; different indexes
+ t.index = ["b", "c", "d", "a"]
+ expected = box(["aDa", "bAb", "cBc", "dCd"])
+ expected = expected if box == Index else Series(expected.values, index=s.values)
+ result = s.str.cat([t, s])
+ tm.assert_equal(result, expected)
+
+ # Series/Index with mixed list; different index
+ result = s.str.cat([t, s.values])
+ tm.assert_equal(result, expected)
+
+ # Series/Index with DataFrame; different indexes
+ d.index = ["b", "c", "d", "a"]
+ expected = box(["aDd", "bAa", "cBb", "dCc"])
+ expected = expected if box == Index else Series(expected.values, index=s.values)
+ result = s.str.cat(d)
+ tm.assert_equal(result, expected)
+
+ # errors for incorrect lengths
+ rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
+ z = Series(["1", "2", "3"])
+ e = concat([z, z], axis=1)
+
+ # two-dimensional ndarray
+ with pytest.raises(ValueError, match=rgx):
+ s.str.cat(e.values)
+
+ # list of list-likes
+ with pytest.raises(ValueError, match=rgx):
+ s.str.cat([z.values, s.values])
+
+ # mixed list of Series/list-like
+ with pytest.raises(ValueError, match=rgx):
+ s.str.cat([z.values, s])
+
+ # errors for incorrect arguments in list-like
+ rgx = "others must be Series, Index, DataFrame,.*"
+ # make sure None/NaN do not crash checks in _get_series_list
+ u = Series(["a", np.nan, "c", None])
+
+ # mix of string and Series
+ with pytest.raises(TypeError, match=rgx):
+ s.str.cat([u, "u"])
+
+ # DataFrame in list
+ with pytest.raises(TypeError, match=rgx):
+ s.str.cat([u, d])
+
+ # 2-dim ndarray in list
+ with pytest.raises(TypeError, match=rgx):
+ s.str.cat([u, d.values])
+
+ # nested lists
+ with pytest.raises(TypeError, match=rgx):
+ s.str.cat([u, [u, d]])
+
+ # forbidden input type: set
+ # GH 23009
+ with pytest.raises(TypeError, match=rgx):
+ s.str.cat(set(u))
+
+ # forbidden input type: set in list
+ # GH 23009
+ with pytest.raises(TypeError, match=rgx):
+ s.str.cat([u, set(u)])
+
+ # other forbidden input type, e.g. int
+ with pytest.raises(TypeError, match=rgx):
+ s.str.cat(1)
+
+ # nested list-likes
+ with pytest.raises(TypeError, match=rgx):
+ s.str.cat(iter([t.values, list(s)]))
+
+
+@pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
+def test_str_cat_align_indexed(index_or_series, join):
+ # https://github.com/pandas-dev/pandas/issues/18657
+ box = index_or_series
+
+ s = Series(["a", "b", "c", "d"], index=["a", "b", "c", "d"])
+ t = Series(["D", "A", "E", "B"], index=["d", "a", "e", "b"])
+ sa, ta = s.align(t, join=join)
+ # result after manual alignment of inputs
+ expected = sa.str.cat(ta, na_rep="-")
+
+ if box == Index:
+ s = Index(s)
+ sa = Index(sa)
+ expected = Index(expected)
+
+ result = s.str.cat(t, join=join, na_rep="-")
+ tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
+def test_str_cat_align_mixed_inputs(join):
+ s = Series(["a", "b", "c", "d"])
+ t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
+ d = concat([t, t], axis=1)
+
+ expected_outer = Series(["aaa", "bbb", "c--", "ddd", "-ee"])
+ expected = expected_outer.loc[s.index.join(t.index, how=join)]
+
+ # list of Series
+ result = s.str.cat([t, t], join=join, na_rep="-")
+ tm.assert_series_equal(result, expected)
+
+ # DataFrame
+ result = s.str.cat(d, join=join, na_rep="-")
+ tm.assert_series_equal(result, expected)
+
+ # mixed list of indexed/unindexed
+ u = np.array(["A", "B", "C", "D"])
+ expected_outer = Series(["aaA", "bbB", "c-C", "ddD", "-e-"])
+ # joint index of rhs [t, u]; u will be forced have index of s
+ rhs_idx = (
+ t.index.intersection(s.index)
+ if join == "inner"
+ else t.index.union(s.index)
+ if join == "outer"
+ else t.index.append(s.index.difference(t.index))
+ )
+
+ expected = expected_outer.loc[s.index.join(rhs_idx, how=join)]
+ result = s.str.cat([t, u], join=join, na_rep="-")
+ tm.assert_series_equal(result, expected)
+
+ with pytest.raises(TypeError, match="others must be Series,.*"):
+ # nested lists are forbidden
+ s.str.cat([t, list(u)], join=join)
+
+ # errors for incorrect lengths
+ rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
+ z = Series(["1", "2", "3"]).values
+
+ # unindexed object of wrong length
+ with pytest.raises(ValueError, match=rgx):
+ s.str.cat(z, join=join)
+
+ # unindexed object of wrong length in list
+ with pytest.raises(ValueError, match=rgx):
+ s.str.cat([t, z], join=join)
+
+
+def test_str_cat_all_na(index_or_series, index_or_series2):
+ # GH 24044
+ box = index_or_series
+ other = index_or_series2
+
+ # check that all NaNs in caller / target work
+ s = Index(["a", "b", "c", "d"])
+ s = s if box == Index else Series(s, index=s)
+ t = other([np.nan] * 4, dtype=object)
+ # add index of s for alignment
+ t = t if other == Index else Series(t, index=s)
+
+ # all-NA target
+ if box == Series:
+ expected = Series([np.nan] * 4, index=s.index, dtype=object)
+ else: # box == Index
+ expected = Index([np.nan] * 4, dtype=object)
+ result = s.str.cat(t, join="left")
+ tm.assert_equal(result, expected)
+
+ # all-NA caller (only for Series)
+ if other == Series:
+ expected = Series([np.nan] * 4, dtype=object, index=t.index)
+ result = t.str.cat(s, join="left")
+ tm.assert_series_equal(result, expected)
+
+
+def test_str_cat_special_cases():
+ s = Series(["a", "b", "c", "d"])
+ t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
+
+ # iterator of elements with different types
+ expected = Series(["aaa", "bbb", "c-c", "ddd", "-e-"])
+ result = s.str.cat(iter([t, s.values]), join="outer", na_rep="-")
+ tm.assert_series_equal(result, expected)
+
+ # right-align with different indexes in others
+ expected = Series(["aa-", "d-d"], index=[0, 3])
+ result = s.str.cat([t.loc[[0]], t.loc[[3]]], join="right", na_rep="-")
+ tm.assert_series_equal(result, expected)
+
+
+def test_cat_on_filtered_index():
+ df = DataFrame(
+ index=MultiIndex.from_product(
+ [[2011, 2012], [1, 2, 3]], names=["year", "month"]
+ )
+ )
+
+ df = df.reset_index()
+ df = df[df.month > 1]
+
+ str_year = df.year.astype("str")
+ str_month = df.month.astype("str")
+ str_both = str_year.str.cat(str_month, sep=" ")
+
+ assert str_both.loc[1] == "2011 2"
+
+ str_multiple = str_year.str.cat([str_month, str_month], sep=" ")
+
+ assert str_multiple.loc[1] == "2011 2 2"
+
+
+@pytest.mark.parametrize("klass", [tuple, list, np.array, Series, Index])
+def test_cat_different_classes(klass):
+ # https://github.com/pandas-dev/pandas/issues/33425
+ s = Series(["a", "b", "c"])
+ result = s.str.cat(klass(["x", "y", "z"]))
+ expected = Series(["ax", "by", "cz"])
+ tm.assert_series_equal(result, expected)
+
+
+def test_cat_on_series_dot_str():
+ # GH 28277
+ ps = Series(["AbC", "de", "FGHI", "j", "kLLLm"])
+
+ message = re.escape(
+ "others must be Series, Index, DataFrame, np.ndarray "
+ "or list-like (either containing only strings or "
+ "containing only objects of type Series/Index/"
+ "np.ndarray[1-dim])"
+ )
+ with pytest.raises(TypeError, match=message):
+ ps.str.cat(others=ps.str)
diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_extract.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8319e90e09a8c5c2d6bb42a3bcc814e3622fb84
--- /dev/null
+++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_extract.py
@@ -0,0 +1,719 @@
+from datetime import datetime
+import re
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.dtypes import ArrowDtype
+
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ _testing as tm,
+)
+
+
+def test_extract_expand_kwarg_wrong_type_raises(any_string_dtype):
+ # TODO: should this raise TypeError
+ values = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
+ with pytest.raises(ValueError, match="expand must be True or False"):
+ values.str.extract(".*(BAD[_]+).*(BAD)", expand=None)
+
+
+def test_extract_expand_kwarg(any_string_dtype):
+ s = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
+ expected = DataFrame(["BAD__", np.nan, np.nan], dtype=any_string_dtype)
+
+ result = s.str.extract(".*(BAD[_]+).*")
+ tm.assert_frame_equal(result, expected)
+
+ result = s.str.extract(".*(BAD[_]+).*", expand=True)
+ tm.assert_frame_equal(result, expected)
+
+ expected = DataFrame(
+ [["BAD__", "BAD"], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
+ )
+ result = s.str.extract(".*(BAD[_]+).*(BAD)", expand=False)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extract_expand_False_mixed_object():
+ ser = Series(
+ ["aBAD_BAD", np.nan, "BAD_b_BAD", True, datetime.today(), "foo", None, 1, 2.0]
+ )
+
+ # two groups
+ result = ser.str.extract(".*(BAD[_]+).*(BAD)", expand=False)
+ er = [np.nan, np.nan] # empty row
+ expected = DataFrame([["BAD_", "BAD"], er, ["BAD_", "BAD"], er, er, er, er, er, er])
+ tm.assert_frame_equal(result, expected)
+
+ # single group
+ result = ser.str.extract(".*(BAD[_]+).*BAD", expand=False)
+ expected = Series(
+ ["BAD_", np.nan, "BAD_", np.nan, np.nan, np.nan, None, np.nan, np.nan]
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_extract_expand_index_raises():
+ # GH9980
+ # Index only works with one regex group since
+ # multi-group would expand to a frame
+ idx = Index(["A1", "A2", "A3", "A4", "B5"])
+ msg = "only one regex group is supported with Index"
+ with pytest.raises(ValueError, match=msg):
+ idx.str.extract("([AB])([123])", expand=False)
+
+
+def test_extract_expand_no_capture_groups_raises(index_or_series, any_string_dtype):
+ s_or_idx = index_or_series(["A1", "B2", "C3"], dtype=any_string_dtype)
+ msg = "pattern contains no capture groups"
+
+ # no groups
+ with pytest.raises(ValueError, match=msg):
+ s_or_idx.str.extract("[ABC][123]", expand=False)
+
+ # only non-capturing groups
+ with pytest.raises(ValueError, match=msg):
+ s_or_idx.str.extract("(?:[AB]).*", expand=False)
+
+
+def test_extract_expand_single_capture_group(index_or_series, any_string_dtype):
+ # single group renames series/index properly
+ s_or_idx = index_or_series(["A1", "A2"], dtype=any_string_dtype)
+ result = s_or_idx.str.extract(r"(?PA)\d", expand=False)
+
+ expected = index_or_series(["A", "A"], name="uno", dtype=any_string_dtype)
+ if index_or_series == Series:
+ tm.assert_series_equal(result, expected)
+ else:
+ tm.assert_index_equal(result, expected)
+
+
+def test_extract_expand_capture_groups(any_string_dtype):
+ s = Series(["A1", "B2", "C3"], dtype=any_string_dtype)
+ # one group, no matches
+ result = s.str.extract("(_)", expand=False)
+ expected = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+ # two groups, no matches
+ result = s.str.extract("(_)(_)", expand=False)
+ expected = DataFrame(
+ [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one group, some matches
+ result = s.str.extract("([AB])[123]", expand=False)
+ expected = Series(["A", "B", np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+ # two groups, some matches
+ result = s.str.extract("([AB])([123])", expand=False)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one named group
+ result = s.str.extract("(?P[AB])", expand=False)
+ expected = Series(["A", "B", np.nan], name="letter", dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+ # two named groups
+ result = s.str.extract("(?P[AB])(?P[123])", expand=False)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
+ columns=["letter", "number"],
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # mix named and unnamed groups
+ result = s.str.extract("([AB])(?P[123])", expand=False)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
+ columns=[0, "number"],
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one normal group, one non-capturing group
+ result = s.str.extract("([AB])(?:[123])", expand=False)
+ expected = Series(["A", "B", np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+ # two normal groups, one non-capturing group
+ s = Series(["A11", "B22", "C33"], dtype=any_string_dtype)
+ result = s.str.extract("([AB])([123])(?:[123])", expand=False)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one optional group followed by one normal group
+ s = Series(["A1", "B2", "3"], dtype=any_string_dtype)
+ result = s.str.extract("(?P[AB])?(?P[123])", expand=False)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, "3"]],
+ columns=["letter", "number"],
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one normal group followed by one optional group
+ s = Series(["A1", "B2", "C"], dtype=any_string_dtype)
+ result = s.str.extract("(?P[ABC])(?P[123])?", expand=False)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
+ columns=["letter", "number"],
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extract_expand_capture_groups_index(index, any_string_dtype):
+ # https://github.com/pandas-dev/pandas/issues/6348
+ # not passing index to the extractor
+ data = ["A1", "B2", "C"]
+
+ if len(index) == 0:
+ pytest.skip("Test requires len(index) > 0")
+ while len(index) < len(data):
+ index = index.repeat(2)
+
+ index = index[: len(data)]
+ ser = Series(data, index=index, dtype=any_string_dtype)
+
+ result = ser.str.extract(r"(\d)", expand=False)
+ expected = Series(["1", "2", np.nan], index=index, dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+ result = ser.str.extract(r"(?P\D)(?P\d)?", expand=False)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
+ columns=["letter", "number"],
+ index=index,
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extract_single_series_name_is_preserved(any_string_dtype):
+ s = Series(["a3", "b3", "c2"], name="bob", dtype=any_string_dtype)
+ result = s.str.extract(r"(?P[a-z])", expand=False)
+ expected = Series(["a", "b", "c"], name="sue", dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_extract_expand_True(any_string_dtype):
+ # Contains tests like those in test_match and some others.
+ s = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
+
+ result = s.str.extract(".*(BAD[_]+).*(BAD)", expand=True)
+ expected = DataFrame(
+ [["BAD__", "BAD"], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extract_expand_True_mixed_object():
+ er = [np.nan, np.nan] # empty row
+ mixed = Series(
+ [
+ "aBAD_BAD",
+ np.nan,
+ "BAD_b_BAD",
+ True,
+ datetime.today(),
+ "foo",
+ None,
+ 1,
+ 2.0,
+ ]
+ )
+
+ result = mixed.str.extract(".*(BAD[_]+).*(BAD)", expand=True)
+ expected = DataFrame([["BAD_", "BAD"], er, ["BAD_", "BAD"], er, er, er, er, er, er])
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extract_expand_True_single_capture_group_raises(
+ index_or_series, any_string_dtype
+):
+ # these should work for both Series and Index
+ # no groups
+ s_or_idx = index_or_series(["A1", "B2", "C3"], dtype=any_string_dtype)
+ msg = "pattern contains no capture groups"
+ with pytest.raises(ValueError, match=msg):
+ s_or_idx.str.extract("[ABC][123]", expand=True)
+
+ # only non-capturing groups
+ with pytest.raises(ValueError, match=msg):
+ s_or_idx.str.extract("(?:[AB]).*", expand=True)
+
+
+def test_extract_expand_True_single_capture_group(index_or_series, any_string_dtype):
+ # single group renames series/index properly
+ s_or_idx = index_or_series(["A1", "A2"], dtype=any_string_dtype)
+ result = s_or_idx.str.extract(r"(?PA)\d", expand=True)
+ expected = DataFrame({"uno": ["A", "A"]}, dtype=any_string_dtype)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("name", [None, "series_name"])
+def test_extract_series(name, any_string_dtype):
+ # extract should give the same result whether or not the series has a name.
+ s = Series(["A1", "B2", "C3"], name=name, dtype=any_string_dtype)
+
+ # one group, no matches
+ result = s.str.extract("(_)", expand=True)
+ expected = DataFrame([np.nan, np.nan, np.nan], dtype=any_string_dtype)
+ tm.assert_frame_equal(result, expected)
+
+ # two groups, no matches
+ result = s.str.extract("(_)(_)", expand=True)
+ expected = DataFrame(
+ [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one group, some matches
+ result = s.str.extract("([AB])[123]", expand=True)
+ expected = DataFrame(["A", "B", np.nan], dtype=any_string_dtype)
+ tm.assert_frame_equal(result, expected)
+
+ # two groups, some matches
+ result = s.str.extract("([AB])([123])", expand=True)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one named group
+ result = s.str.extract("(?P[AB])", expand=True)
+ expected = DataFrame({"letter": ["A", "B", np.nan]}, dtype=any_string_dtype)
+ tm.assert_frame_equal(result, expected)
+
+ # two named groups
+ result = s.str.extract("(?P[AB])(?P[123])", expand=True)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
+ columns=["letter", "number"],
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # mix named and unnamed groups
+ result = s.str.extract("([AB])(?P[123])", expand=True)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
+ columns=[0, "number"],
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one normal group, one non-capturing group
+ result = s.str.extract("([AB])(?:[123])", expand=True)
+ expected = DataFrame(["A", "B", np.nan], dtype=any_string_dtype)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extract_optional_groups(any_string_dtype):
+ # two normal groups, one non-capturing group
+ s = Series(["A11", "B22", "C33"], dtype=any_string_dtype)
+ result = s.str.extract("([AB])([123])(?:[123])", expand=True)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one optional group followed by one normal group
+ s = Series(["A1", "B2", "3"], dtype=any_string_dtype)
+ result = s.str.extract("(?P[AB])?(?P[123])", expand=True)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], [np.nan, "3"]],
+ columns=["letter", "number"],
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one normal group followed by one optional group
+ s = Series(["A1", "B2", "C"], dtype=any_string_dtype)
+ result = s.str.extract("(?P[ABC])(?P[123])?", expand=True)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
+ columns=["letter", "number"],
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extract_dataframe_capture_groups_index(index, any_string_dtype):
+ # GH6348
+ # not passing index to the extractor
+
+ data = ["A1", "B2", "C"]
+
+ if len(index) < len(data):
+ pytest.skip("Index too short")
+
+ index = index[: len(data)]
+ s = Series(data, index=index, dtype=any_string_dtype)
+
+ result = s.str.extract(r"(\d)", expand=True)
+ expected = DataFrame(["1", "2", np.nan], index=index, dtype=any_string_dtype)
+ tm.assert_frame_equal(result, expected)
+
+ result = s.str.extract(r"(?P\D)(?P\d)?", expand=True)
+ expected = DataFrame(
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
+ columns=["letter", "number"],
+ index=index,
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extract_single_group_returns_frame(any_string_dtype):
+ # GH11386 extract should always return DataFrame, even when
+ # there is only one group. Prior to v0.18.0, extract returned
+ # Series when there was only one group in the regex.
+ s = Series(["a3", "b3", "c2"], name="series_name", dtype=any_string_dtype)
+ result = s.str.extract(r"(?P[a-z])", expand=True)
+ expected = DataFrame({"letter": ["a", "b", "c"]}, dtype=any_string_dtype)
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extractall(any_string_dtype):
+ data = [
+ "dave@google.com",
+ "tdhock5@gmail.com",
+ "maudelaperriere@gmail.com",
+ "rob@gmail.com some text steve@gmail.com",
+ "a@b.com some text c@d.com and e@f.com",
+ np.nan,
+ "",
+ ]
+ expected_tuples = [
+ ("dave", "google", "com"),
+ ("tdhock5", "gmail", "com"),
+ ("maudelaperriere", "gmail", "com"),
+ ("rob", "gmail", "com"),
+ ("steve", "gmail", "com"),
+ ("a", "b", "com"),
+ ("c", "d", "com"),
+ ("e", "f", "com"),
+ ]
+ pat = r"""
+ (?P[a-z0-9]+)
+ @
+ (?P[a-z]+)
+ \.
+ (?P[a-z]{2,4})
+ """
+ expected_columns = ["user", "domain", "tld"]
+ s = Series(data, dtype=any_string_dtype)
+ # extractall should return a DataFrame with one row for each match, indexed by the
+ # subject from which the match came.
+ expected_index = MultiIndex.from_tuples(
+ [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 0), (4, 1), (4, 2)],
+ names=(None, "match"),
+ )
+ expected = DataFrame(
+ expected_tuples, expected_index, expected_columns, dtype=any_string_dtype
+ )
+ result = s.str.extractall(pat, flags=re.VERBOSE)
+ tm.assert_frame_equal(result, expected)
+
+ # The index of the input Series should be used to construct the index of the output
+ # DataFrame:
+ mi = MultiIndex.from_tuples(
+ [
+ ("single", "Dave"),
+ ("single", "Toby"),
+ ("single", "Maude"),
+ ("multiple", "robAndSteve"),
+ ("multiple", "abcdef"),
+ ("none", "missing"),
+ ("none", "empty"),
+ ]
+ )
+ s = Series(data, index=mi, dtype=any_string_dtype)
+ expected_index = MultiIndex.from_tuples(
+ [
+ ("single", "Dave", 0),
+ ("single", "Toby", 0),
+ ("single", "Maude", 0),
+ ("multiple", "robAndSteve", 0),
+ ("multiple", "robAndSteve", 1),
+ ("multiple", "abcdef", 0),
+ ("multiple", "abcdef", 1),
+ ("multiple", "abcdef", 2),
+ ],
+ names=(None, None, "match"),
+ )
+ expected = DataFrame(
+ expected_tuples, expected_index, expected_columns, dtype=any_string_dtype
+ )
+ result = s.str.extractall(pat, flags=re.VERBOSE)
+ tm.assert_frame_equal(result, expected)
+
+ # MultiIndexed subject with names.
+ s = Series(data, index=mi, dtype=any_string_dtype)
+ s.index.names = ("matches", "description")
+ expected_index.names = ("matches", "description", "match")
+ expected = DataFrame(
+ expected_tuples, expected_index, expected_columns, dtype=any_string_dtype
+ )
+ result = s.str.extractall(pat, flags=re.VERBOSE)
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pat,expected_names",
+ [
+ # optional groups.
+ ("(?P[AB])?(?P[123])", ["letter", "number"]),
+ # only one of two groups has a name.
+ ("([AB])?(?P[123])", [0, "number"]),
+ ],
+)
+def test_extractall_column_names(pat, expected_names, any_string_dtype):
+ s = Series(["", "A1", "32"], dtype=any_string_dtype)
+
+ result = s.str.extractall(pat)
+ expected = DataFrame(
+ [("A", "1"), (np.nan, "3"), (np.nan, "2")],
+ index=MultiIndex.from_tuples([(1, 0), (2, 0), (2, 1)], names=(None, "match")),
+ columns=expected_names,
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extractall_single_group(any_string_dtype):
+ s = Series(["a3", "b3", "d4c2"], name="series_name", dtype=any_string_dtype)
+ expected_index = MultiIndex.from_tuples(
+ [(0, 0), (1, 0), (2, 0), (2, 1)], names=(None, "match")
+ )
+
+ # extractall(one named group) returns DataFrame with one named column.
+ result = s.str.extractall(r"(?P[a-z])")
+ expected = DataFrame(
+ {"letter": ["a", "b", "d", "c"]}, index=expected_index, dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # extractall(one un-named group) returns DataFrame with one un-named column.
+ result = s.str.extractall(r"([a-z])")
+ expected = DataFrame(
+ ["a", "b", "d", "c"], index=expected_index, dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extractall_single_group_with_quantifier(any_string_dtype):
+ # GH#13382
+ # extractall(one un-named group with quantifier) returns DataFrame with one un-named
+ # column.
+ s = Series(["ab3", "abc3", "d4cd2"], name="series_name", dtype=any_string_dtype)
+ result = s.str.extractall(r"([a-z]+)")
+ expected = DataFrame(
+ ["ab", "abc", "d", "cd"],
+ index=MultiIndex.from_tuples(
+ [(0, 0), (1, 0), (2, 0), (2, 1)], names=(None, "match")
+ ),
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, names",
+ [
+ ([], (None,)),
+ ([], ("i1",)),
+ ([], (None, "i2")),
+ ([], ("i1", "i2")),
+ (["a3", "b3", "d4c2"], (None,)),
+ (["a3", "b3", "d4c2"], ("i1", "i2")),
+ (["a3", "b3", "d4c2"], (None, "i2")),
+ (["a3", "b3", "d4c2"], ("i1", "i2")),
+ ],
+)
+def test_extractall_no_matches(data, names, any_string_dtype):
+ # GH19075 extractall with no matches should return a valid MultiIndex
+ n = len(data)
+ if len(names) == 1:
+ index = Index(range(n), name=names[0])
+ else:
+ tuples = (tuple([i] * (n - 1)) for i in range(n))
+ index = MultiIndex.from_tuples(tuples, names=names)
+ s = Series(data, name="series_name", index=index, dtype=any_string_dtype)
+ expected_index = MultiIndex.from_tuples([], names=(names + ("match",)))
+
+ # one un-named group.
+ result = s.str.extractall("(z)")
+ expected = DataFrame(columns=[0], index=expected_index, dtype=any_string_dtype)
+ tm.assert_frame_equal(result, expected)
+
+ # two un-named groups.
+ result = s.str.extractall("(z)(z)")
+ expected = DataFrame(columns=[0, 1], index=expected_index, dtype=any_string_dtype)
+ tm.assert_frame_equal(result, expected)
+
+ # one named group.
+ result = s.str.extractall("(?Pz)")
+ expected = DataFrame(
+ columns=["first"], index=expected_index, dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # two named groups.
+ result = s.str.extractall("(?Pz)(?Pz)")
+ expected = DataFrame(
+ columns=["first", "second"], index=expected_index, dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # one named, one un-named.
+ result = s.str.extractall("(z)(?Pz)")
+ expected = DataFrame(
+ columns=[0, "second"], index=expected_index, dtype=any_string_dtype
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extractall_stringindex(any_string_dtype):
+ s = Series(["a1a2", "b1", "c1"], name="xxx", dtype=any_string_dtype)
+ result = s.str.extractall(r"[ab](?P\d)")
+ expected = DataFrame(
+ {"digit": ["1", "2", "1"]},
+ index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 0)], names=[None, "match"]),
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # index should return the same result as the default index without name thus
+ # index.name doesn't affect to the result
+ if any_string_dtype == "object":
+ for idx in [
+ Index(["a1a2", "b1", "c1"]),
+ Index(["a1a2", "b1", "c1"], name="xxx"),
+ ]:
+ result = idx.str.extractall(r"[ab](?P\d)")
+ tm.assert_frame_equal(result, expected)
+
+ s = Series(
+ ["a1a2", "b1", "c1"],
+ name="s_name",
+ index=Index(["XX", "yy", "zz"], name="idx_name"),
+ dtype=any_string_dtype,
+ )
+ result = s.str.extractall(r"[ab](?P\d)")
+ expected = DataFrame(
+ {"digit": ["1", "2", "1"]},
+ index=MultiIndex.from_tuples(
+ [("XX", 0), ("XX", 1), ("yy", 0)], names=["idx_name", "match"]
+ ),
+ dtype=any_string_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_extractall_no_capture_groups_raises(any_string_dtype):
+ # Does not make sense to use extractall with a regex that has no capture groups.
+ # (it returns DataFrame with one column for each capture group)
+ s = Series(["a3", "b3", "d4c2"], name="series_name", dtype=any_string_dtype)
+ with pytest.raises(ValueError, match="no capture groups"):
+ s.str.extractall(r"[a-z]")
+
+
+def test_extract_index_one_two_groups():
+ s = Series(["a3", "b3", "d4c2"], index=["A3", "B3", "D4"], name="series_name")
+ r = s.index.str.extract(r"([A-Z])", expand=True)
+ e = DataFrame(["A", "B", "D"])
+ tm.assert_frame_equal(r, e)
+
+ # Prior to v0.18.0, index.str.extract(regex with one group)
+ # returned Index. With more than one group, extract raised an
+ # error (GH9980). Now extract always returns DataFrame.
+ r = s.index.str.extract(r"(?P[A-Z])(?P[0-9])", expand=True)
+ e_list = [("A", "3"), ("B", "3"), ("D", "4")]
+ e = DataFrame(e_list, columns=["letter", "digit"])
+ tm.assert_frame_equal(r, e)
+
+
+def test_extractall_same_as_extract(any_string_dtype):
+ s = Series(["a3", "b3", "c2"], name="series_name", dtype=any_string_dtype)
+
+ pattern_two_noname = r"([a-z])([0-9])"
+ extract_two_noname = s.str.extract(pattern_two_noname, expand=True)
+ has_multi_index = s.str.extractall(pattern_two_noname)
+ no_multi_index = has_multi_index.xs(0, level="match")
+ tm.assert_frame_equal(extract_two_noname, no_multi_index)
+
+ pattern_two_named = r"(?P[a-z])(?P[0-9])"
+ extract_two_named = s.str.extract(pattern_two_named, expand=True)
+ has_multi_index = s.str.extractall(pattern_two_named)
+ no_multi_index = has_multi_index.xs(0, level="match")
+ tm.assert_frame_equal(extract_two_named, no_multi_index)
+
+ pattern_one_named = r"(?P[a-z])"
+ extract_one_named = s.str.extract(pattern_one_named, expand=True)
+ has_multi_index = s.str.extractall(pattern_one_named)
+ no_multi_index = has_multi_index.xs(0, level="match")
+ tm.assert_frame_equal(extract_one_named, no_multi_index)
+
+ pattern_one_noname = r"([a-z])"
+ extract_one_noname = s.str.extract(pattern_one_noname, expand=True)
+ has_multi_index = s.str.extractall(pattern_one_noname)
+ no_multi_index = has_multi_index.xs(0, level="match")
+ tm.assert_frame_equal(extract_one_noname, no_multi_index)
+
+
+def test_extractall_same_as_extract_subject_index(any_string_dtype):
+ # same as above tests, but s has an MultiIndex.
+ mi = MultiIndex.from_tuples(
+ [("A", "first"), ("B", "second"), ("C", "third")],
+ names=("capital", "ordinal"),
+ )
+ s = Series(["a3", "b3", "c2"], index=mi, name="series_name", dtype=any_string_dtype)
+
+ pattern_two_noname = r"([a-z])([0-9])"
+ extract_two_noname = s.str.extract(pattern_two_noname, expand=True)
+ has_match_index = s.str.extractall(pattern_two_noname)
+ no_match_index = has_match_index.xs(0, level="match")
+ tm.assert_frame_equal(extract_two_noname, no_match_index)
+
+ pattern_two_named = r"(?P[a-z])(?P