diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/INSTALLER b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/METADATA b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8acaf884b1a18b9d9b4259727c7cb9febbc52ae5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/METADATA @@ -0,0 +1,308 @@ +Metadata-Version: 2.4 +Name: pandas +Version: 3.1.1 +Summary: Powerful data structures for data analysis, time series, and statistics +Author-Email: The Pandas Development Team +License-Expression: BSD-3-Clause +License-File: LICENSE +License-File: LICENSES/BOTTLENECK_LICENCE +License-File: LICENSES/DATEUTIL_LICENSE +License-File: LICENSES/HAVEN_LICENSE +License-File: LICENSES/HAVEN_MIT +License-File: LICENSES/KLIB_LICENSE +License-File: LICENSES/MUSL_LICENSE +License-File: LICENSES/NUMPY_LICENSE +License-File: LICENSES/PACKAGING_LICENSE +License-File: LICENSES/PSF_LICENSE +License-File: LICENSES/PYPERCLIP_LICENSE +License-File: LICENSES/PYUPGRADE_LICENSE +License-File: LICENSES/SAS7BDAT_LICENSE +License-File: LICENSES/STATSBASE_JL_LICENSE +License-File: LICENSES/ULTRAJSON_LICENSE +License-File: LICENSES/XSIMD_LICENSE +License-File: subprojects/fast_float-8.2.10/LICENSE-APACHE +License-File: subprojects/fast_float-8.2.10/LICENSE-BOOST +License-File: subprojects/fast_float-8.2.10/LICENSE-MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Science/Research +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Topic :: Scientific/Engineering +Project-URL: homepage, https://pandas.pydata.org +Project-URL: source, https://github.com/pandas-dev/pandas +Project-URL: documentation, https://pandas.pydata.org/docs/ +Project-URL: changelog, https://pandas.pydata.org/docs/whatsnew/index.html +Project-URL: issues, https://github.com/pandas-dev/pandas/issues +Project-URL: funding, https://opencollective.com/pandas +Requires-Python: >=3.11 +Requires-Dist: numpy>=2.0.2; python_version < "3.14" +Requires-Dist: numpy>=2.3.3; python_version >= "3.14" +Requires-Dist: python-dateutil>=2.9.0 +Requires-Dist: tzdata; sys_platform == "win32" +Requires-Dist: tzdata; sys_platform == "emscripten" +Provides-Extra: test +Requires-Dist: pytest>=8.3.4; extra == "test" +Requires-Dist: pytest-xdist>=3.6.1; extra == "test" +Provides-Extra: pyarrow +Requires-Dist: pyarrow>=16.0.0; extra == "pyarrow" +Provides-Extra: performance +Requires-Dist: bottleneck>=1.5.0; extra == "performance" +Requires-Dist: numba>=0.61.2; extra == "performance" +Requires-Dist: numexpr!=2.14.1,>=2.11.0; extra == "performance" +Provides-Extra: computation +Requires-Dist: scipy>=1.16.1; extra == "computation" +Requires-Dist: xarray>=2025.7.1; extra == "computation" +Provides-Extra: fss +Requires-Dist: fsspec>=2025.7.0; extra == "fss" +Provides-Extra: aws +Requires-Dist: s3fs>=2025.7.0; extra == "aws" +Provides-Extra: gcp +Requires-Dist: gcsfs>=2025.7.0; extra == "gcp" +Provides-Extra: excel +Requires-Dist: odfpy>=1.4.1; extra == "excel" +Requires-Dist: openpyxl>=3.1.5; extra == "excel" +Requires-Dist: python-calamine>=0.4.0; extra == "excel" +Requires-Dist: pyxlsb>=1.0.10; extra == "excel" +Requires-Dist: xlrd>=2.0.2; extra == "excel" +Requires-Dist: xlsxwriter>=3.2.5; extra == "excel" +Provides-Extra: parquet +Requires-Dist: pandas[pyarrow]; extra == "parquet" +Provides-Extra: feather +Requires-Dist: pandas[pyarrow]; extra == "feather" +Provides-Extra: iceberg +Requires-Dist: pyiceberg>=0.9.1; extra == "iceberg" +Provides-Extra: hdf5 +Requires-Dist: tables>=3.10.2; extra == "hdf5" +Provides-Extra: spss +Requires-Dist: pyreadstat>=1.3.0; extra == "spss" +Provides-Extra: postgresql +Requires-Dist: SQLAlchemy>=2.0.42; extra == "postgresql" +Requires-Dist: psycopg2>=2.9.10; extra == "postgresql" +Requires-Dist: adbc-driver-postgresql>=1.7.0; extra == "postgresql" +Provides-Extra: mysql +Requires-Dist: SQLAlchemy>=2.0.42; extra == "mysql" +Requires-Dist: pymysql>=1.1.1; extra == "mysql" +Provides-Extra: sql-other +Requires-Dist: SQLAlchemy>=2.0.42; extra == "sql-other" +Requires-Dist: adbc-driver-postgresql>=1.7.0; extra == "sql-other" +Requires-Dist: adbc-driver-sqlite>=1.7.0; extra == "sql-other" +Provides-Extra: html +Requires-Dist: beautifulsoup4>=4.13.4; extra == "html" +Requires-Dist: html5lib>=1.1; extra == "html" +Requires-Dist: lxml>=6.0.0; extra == "html" +Provides-Extra: xml +Requires-Dist: lxml>=6.0.0; extra == "xml" +Provides-Extra: plot +Requires-Dist: matplotlib>=3.10.5; extra == "plot" +Provides-Extra: output-formatting +Requires-Dist: jinja2>=3.1.6; extra == "output-formatting" +Requires-Dist: tabulate>=0.9.0; extra == "output-formatting" +Provides-Extra: clipboard +Requires-Dist: PyQt5>=5.15.11; extra == "clipboard" +Requires-Dist: qtpy>=2.4.3; extra == "clipboard" +Provides-Extra: compression +Requires-Dist: zstandard>=0.23.0; extra == "compression" +Provides-Extra: timezone +Requires-Dist: pytz>=2020.1; extra == "timezone" +Provides-Extra: all +Requires-Dist: pandas[aws,clipboard,compression,computation,excel,feather,fss,gcp,hdf5,html,iceberg,mysql,output-formatting,parquet,performance,plot,postgresql,pyarrow,spss,sql-other,test,timezone,xml]; extra == "all" +Requires-Dist: fastparquet>=2024.11.0; extra == "all" +Description-Content-Type: text/markdown + + + + Pandas Logo + + +----------------- + +# pandas: A Powerful Python Data Analysis Toolkit + +| | | +| --- | --- | +| Testing | [![CI - Test](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml/badge.svg)](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml) [![Coverage](https://codecov.io/github/pandas-dev/pandas/coverage.svg?branch=main)](https://codecov.io/gh/pandas-dev/pandas) | +| Package | [![PyPI Latest Release](https://img.shields.io/pypi/v/pandas.svg)](https://pypi.org/project/pandas/) [![PyPI Downloads](https://img.shields.io/pypi/dm/pandas.svg?label=PyPI%20downloads)](https://pypi.org/project/pandas/) [![Conda Latest Release](https://anaconda.org/conda-forge/pandas/badges/version.svg)](https://anaconda.org/conda-forge/pandas) [![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/pandas.svg?label=Conda%20downloads)](https://anaconda.org/conda-forge/pandas) | +| Meta | [![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3509134.svg)](https://doi.org/10.5281/zenodo.3509134) [![License - BSD 3-Clause](https://img.shields.io/pypi/l/pandas.svg)](https://github.com/pandas-dev/pandas/blob/main/LICENSE) [![Slack](https://img.shields.io/badge/join_Slack-information-brightgreen.svg?logo=slack)](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) [![LFX Health Score](https://insights.linuxfoundation.org/api/badge/health-score?project=pandas-dev-pandas)](https://insights.linuxfoundation.org/project/pandas-dev-pandas) | + + +## What is it? + +**pandas** is a Python package that provides fast, flexible, and expressive data +structures designed to make working with "relational" or "labeled" data both +easy and intuitive. It aims to be the fundamental high-level building block for +doing practical, **real-world** data analysis in Python. Additionally, it has +the broader goal of becoming **the most powerful and flexible open-source data +analysis/manipulation tool available in any language**. It is already well on +its way towards this goal. + +## Table of Contents + +- [Main Features](#main-features) +- [Where to get it](#where-to-get-it) +- [Dependencies](#dependencies) +- [Installation from sources](#installation-from-sources) +- [License](#license) +- [Documentation](#documentation) +- [Background](#background) +- [Getting Help](#getting-help) +- [Discussion and Development](#discussion-and-development) +- [Contributing to pandas](#contributing-to-pandas) + +## Main Features +Here are just a few of the things that pandas does well: + + - Easy handling of [**missing data**][missing-data] (represented as + `NaN`, `NA`, or `NaT`) in floating point as well as non-floating point data + - Size mutability: columns can be [**inserted and + deleted**][insertion-deletion] from DataFrame and higher dimensional + objects + - Automatic and explicit [**data alignment**][alignment]: objects can + be explicitly aligned to a set of labels, or the user can simply + ignore the labels and let `Series`, `DataFrame`, etc. automatically + align the data for you in computations + - Powerful, flexible [**group by**][groupby] functionality to perform + split-apply-combine operations on data sets, for both aggregating + and transforming data + - Make it [**easy to convert**][conversion] ragged, + differently-indexed data in other Python and NumPy data structures + into DataFrame objects + - Intelligent label-based [**slicing**][slicing], [**fancy + indexing**][fancy-indexing], and [**subsetting**][subsetting] of + large data sets + - Intuitive [**merging**][merging] and [**joining**][joining] data + sets + - Flexible [**reshaping**][reshape] and [**pivoting**][pivot-table] of + data sets + - [**Hierarchical**][mi] labeling of axes (possible to have multiple + labels per tick) + - Robust I/O tools for loading data from [**flat files**][flat-files] + (CSV and delimited), [**Excel files**][excel], [**databases**][db], + and saving/loading data from the ultrafast [**HDF5 format**][hdfstore] + - [**Time series**][timeseries]-specific functionality: date range + generation and frequency conversion, moving window statistics, + date shifting and lagging + + + [missing-data]: https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html + [insertion-deletion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#column-selection-addition-deletion + [alignment]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html?highlight=alignment#intro-to-data-structures + [groupby]: https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#group-by-split-apply-combine + [conversion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#dataframe + [slicing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#slicing-ranges + [fancy-indexing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced + [subsetting]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing + [merging]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging + [joining]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#joining-on-index + [reshape]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html + [pivot-table]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html + [mi]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#hierarchical-indexing-multiindex + [flat-files]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#csv-text-files + [excel]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#excel-files + [db]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#sql-queries + [hdfstore]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#hdf5-pytables + [timeseries]: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#time-series-date-functionality + +## Where to get it +The source code is currently hosted on GitHub at: +https://github.com/pandas-dev/pandas + +Binary installers for the latest released version are available at the [Python +Package Index (PyPI)](https://pypi.org/project/pandas) and on [Conda](https://anaconda.org/conda-forge/pandas). + +```sh +# conda +conda install -c conda-forge pandas +``` + +```sh +# or PyPI +pip install pandas +``` + +The list of changes to pandas between each release can be found +[here](https://pandas.pydata.org/pandas-docs/stable/whatsnew/index.html). For full +details, see the commit logs at https://github.com/pandas-dev/pandas. + +## Dependencies +- [NumPy - Adds support for large, multi-dimensional arrays, matrices and high-level mathematical functions to operate on these arrays](https://www.numpy.org) +- [python-dateutil - Provides powerful extensions to the standard datetime module](https://dateutil.readthedocs.io/en/stable/index.html) +- [tzdata - Provides an IANA time zone database](https://tzdata.python.org) (Only required on Windows/Emscripten) + +See the [full installation instructions](https://pandas.pydata.org/pandas-docs/stable/install.html#dependencies) for minimum supported versions of required, recommended and optional dependencies. + +## Installation from sources +To install pandas from source you need [Cython](https://cython.org/) in addition to the normal +dependencies above. Cython can be installed from PyPI: + +```sh +pip install cython +``` + +In the `pandas` directory (same one where you found this file after +cloning the git repo), execute: + +```sh +pip install . +``` + +or for installing in [development mode](https://pip.pypa.io/en/latest/cli/pip_install/#install-editable): + + +```sh +python -m pip install -ve . --no-build-isolation --config-settings editable-verbose=true +``` + +See the full instructions for [installing from source](https://pandas.pydata.org/docs/dev/development/contributing_environment.html). + +## License +[BSD 3](LICENSE) + +## Documentation +The official documentation is hosted on [PyData.org](https://pandas.pydata.org/pandas-docs/stable/). + +## Background +Work on ``pandas`` started at [AQR](https://www.aqr.com/) (a quantitative hedge fund) in 2008 and +has been under active development since then. + +## Getting Help + +For usage questions, the best place to go to is [Stack Overflow](https://stackoverflow.com/questions/tagged/pandas). +Further, general questions and discussions can also take place on the [pydata mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata). + +## Discussion and Development +Most development discussions take place on GitHub in this repo, via the [GitHub issue tracker](https://github.com/pandas-dev/pandas/issues). + +Further, the [pandas-dev mailing list](https://mail.python.org/mailman/listinfo/pandas-dev) can also be used for specialized discussions or design issues, and a [Slack channel](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) is available for quick development related questions. + +There are also frequent [community meetings](https://pandas.pydata.org/docs/dev/development/community.html#community-meeting) for project maintainers open to the community as well as monthly [new contributor meetings](https://pandas.pydata.org/docs/dev/development/community.html#new-contributor-meeting) to help support new contributors. + +Additional information on the communication channels can be found on the [contributor community](https://pandas.pydata.org/docs/development/community.html) page. + +## Contributing to pandas + +[![Open Source Helpers](https://www.codetriage.com/pandas-dev/pandas/badges/users.svg)](https://www.codetriage.com/pandas-dev/pandas) + +All contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome. + +A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**. + +You can also triage issues which may include reproducing bug reports, or asking for vital information such as version numbers or reproduction instructions. If you would like to start triaging issues, one easy way to get started is to [subscribe to pandas on CodeTriage](https://www.codetriage.com/pandas-dev/pandas). + +Or maybe through using pandas you have an idea of your own or are looking for something in the documentation and thinking ‘this can be improved’... you can do something about it! + +Feel free to ask questions on the [mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata) or on [Slack](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack). + +As contributors and maintainers to this project, you are expected to abide by pandas' code of conduct. More information can be found at: [Contributor Code of Conduct](https://github.com/pandas-dev/.github/blob/master/CODE_OF_CONDUCT.md) + +
+ +[Go to Top](#table-of-contents) diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/RECORD b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..93b82d6da17d9e023f7367b0495953e91faecc1e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/RECORD @@ -0,0 +1,2999 @@ +pandas-3.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pandas-3.1.1.dist-info/METADATA,sha256=ytjYPSzLkqQq5YwBZBcOwOIVF77C_6rU2E9f6koq0JY,16693 +pandas-3.1.1.dist-info/RECORD,, +pandas-3.1.1.dist-info/WHEEL,sha256=8clXq6559___8OT-Dqw6mstDohSK2pkaZ2rYUsMpAq8,122 +pandas-3.1.1.dist-info/entry_points.txt,sha256=OVLKNEPs-Q7IWypWBL6fxv56_zt4sRnEI7zawo6y_0w,69 +pandas-3.1.1.dist-info/licenses/LICENSE,sha256=mFD2tb3vc0ZQMGWAe4eN64BYuXbFwyn0xNI79Hls6a4,1634 +pandas-3.1.1.dist-info/licenses/LICENSES/BOTTLENECK_LICENCE,sha256=BTqQ4wWA9dnXmBet0VZ_iLSj7rEbze2ez3RhnRd2gGY,1360 +pandas-3.1.1.dist-info/licenses/LICENSES/DATEUTIL_LICENSE,sha256=ugD1Gg2SgjtaHN4n2LW50jIeZ-2NqbwWPv-W1eF-V34,2889 +pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_LICENSE,sha256=SCFrQLPRsZRSkj3W_XRlW_XA3512tR6w763n4LiL-8w,1099 +pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_MIT,sha256=hyF9CnkZVEGrYVo6uzq2d3UC5XgE6oP5c9-XWmfr1yA,1264 +pandas-3.1.1.dist-info/licenses/LICENSES/KLIB_LICENSE,sha256=dGMXLDojMhwYOIluukN_cKbegKxahAspYJZsjFREq_E,1104 +pandas-3.1.1.dist-info/licenses/LICENSES/MUSL_LICENSE,sha256=UKNDwc6eJ81sWAI_E7kdLNZ5hh_n-2u7v77D3K_DWD8,6203 +pandas-3.1.1.dist-info/licenses/LICENSES/NUMPY_LICENSE,sha256=gdQtoCpWthHDWryD0iQVZLRr7DpbGWCzldVc68po-28,1542 +pandas-3.1.1.dist-info/licenses/LICENSES/PACKAGING_LICENSE,sha256=GHEzAGihjx8Hw_FHpBwAjlnzZ_IXBBym6yCwKYY5oSg,11519 +pandas-3.1.1.dist-info/licenses/LICENSES/PSF_LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936 +pandas-3.1.1.dist-info/licenses/LICENSES/PYPERCLIP_LICENSE,sha256=6vzUQONXDGvHt33OwV3sOY0TvJteiXM2siH_gf8Z80U,1486 +pandas-3.1.1.dist-info/licenses/LICENSES/PYUPGRADE_LICENSE,sha256=cK7c1pKCcr0Xbk_cM4SvIu51nQBvsVEF2ZR1bk8tG3o,1058 +pandas-3.1.1.dist-info/licenses/LICENSES/SAS7BDAT_LICENSE,sha256=RY1f1BdYJUQK0y1r9q9F0aGdStsxa1V9hpxlYLZpLgA,1059 +pandas-3.1.1.dist-info/licenses/LICENSES/STATSBASE_JL_LICENSE,sha256=83HM8PuJKkzZ8uVQxLjPQ2J5PRcCjcZCrVXB4BpB3-E,1249 +pandas-3.1.1.dist-info/licenses/LICENSES/ULTRAJSON_LICENSE,sha256=K_u1u47GbRNuxi2DbdwMABnUTvTZOJ8fbKscEQnXdKI,5974 +pandas-3.1.1.dist-info/licenses/LICENSES/XSIMD_LICENSE,sha256=UBNSrLpizFTo49KTdU1gb5Gcm0JbliGTwhH5-inNmUA,1606 +pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-APACHE,sha256=CXqImqlU0E4Ii3kLEKQBTWGJVh0KYBOTWnPOPU3arwY,10767 +pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-BOOST,sha256=jYKRyvHO4m0jrPPrZ8n5otWPHGgbFqT76Mv7njwLWps,1337 +pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-MIT,sha256=5WLz-XTO1-ad0dt3uCCza8-PMDd_GqEFcj-6RJxTxOY,1079 +pandas/__init__.py,sha256=T7ZXEw0W7FodZ_U4iGLc36OKXP-BkejSFA8NXg3ID1s,8007 +pandas/__pycache__/__init__.cpython-314.pyc,, +pandas/__pycache__/_typing.cpython-314.pyc,, +pandas/__pycache__/_version_meson.cpython-314.pyc,, +pandas/__pycache__/conftest.cpython-314.pyc,, +pandas/__pycache__/testing.cpython-314.pyc,, +pandas/_config/__init__.py,sha256=xkmBFWSb3Gsh4MXmu53ApHibiAH53Z9BoUZtxNTDJMo,1068 +pandas/_config/__pycache__/__init__.cpython-314.pyc,, +pandas/_config/__pycache__/config.cpython-314.pyc,, +pandas/_config/__pycache__/dates.cpython-314.pyc,, +pandas/_config/__pycache__/display.cpython-314.pyc,, +pandas/_config/__pycache__/localization.cpython-314.pyc,, +pandas/_config/config.py,sha256=G3apR1twZeB1fITQ62aRgEpBNP6T3npvLSUzoItsTVw,28674 +pandas/_config/dates.py,sha256=fhSwVX46JO222KR4lLuwsvN_0MwKVFMN8NMSyhLuMdE,1162 +pandas/_config/display.py,sha256=ZsAU0fbywSG39uXPUJG4jqm3VA-oxGplWxdDN20SacE,1799 +pandas/_config/localization.py,sha256=rcw8qYwkxfuueF_VIixXUsEn-DUFx27-cosXVkCOTT8,6043 +pandas/_libs/__init__.py,sha256=sWDA_DczzT-1wEBE4Xf5wRL2tB7d2RKtbbHrwCNZyeM,673 +pandas/_libs/__pycache__/__init__.cpython-314.pyc,, +pandas/_libs/_cyutility.cpython-314-darwin.so,sha256=DmbI2nBtL9A65IX9TkRNaq9lGepRBRwBcdP5VEXmIWY,221968 +pandas/_libs/_ujson.cpython-314-darwin.so,sha256=WIYZwk-BU3urhpRW2KVBblaTiFxT68ubScymAjdpcKE,94112 +pandas/_libs/_ujson.pyi,sha256=gHlK8bL3Gk_zC8AdI-3so42_XCencoLfkZZ6tEBQDZo,546 +pandas/_libs/algos.cpython-314-darwin.so,sha256=OIQjnd8WpNv3UB383kdnqYqt4g_0ApkrP4I3nd4EVPw,1937768 +pandas/_libs/algos.pyi,sha256=sSJQKfXpSPl8DWy-iMthMc8VXFsdMkN86e6Xy_mL6G0,22056 +pandas/_libs/arrays.cpython-314-darwin.so,sha256=nqCnO-TgpwUU7Um67ewxPCqgapK2uXYzAo_jQQsRBgQ,144272 +pandas/_libs/arrays.pyi,sha256=xYEJXc_4qeY8lV35lC6otEl9vcCQQCYEn0wyhY4eVrQ,1208 +pandas/_libs/byteswap.cpython-314-darwin.so,sha256=jIzDtydCJ14E2XjRKEcSE0520Wgh51dcsF7nt4SwcHI,75648 +pandas/_libs/byteswap.pyi,sha256=SxL2I1rKqe73WZgkO511PWJx20P160V4hrws1TG0JTk,423 +pandas/_libs/groupby.cpython-314-darwin.so,sha256=jUXZ7_vwEg8fZ648O6ae52NZpzuyA_hNhaupSskp5Hk,2075264 +pandas/_libs/groupby.pyi,sha256=h7_A9wOnTX2_U_upI_leuwT4qWMLka5lxcRSnvYdIkQ,7997 +pandas/_libs/hashing.cpython-314-darwin.so,sha256=Ffg7AbdWUM9467Ooln8y5001M86145HuIiCdBJepKJs,95344 +pandas/_libs/hashing.pyi,sha256=cdNwppEilaMnVN77ABt3TBadjUawMtMFgSQb1PCqwQk,181 +pandas/_libs/hashtable.cpython-314-darwin.so,sha256=zoUspUIqETUo-4Qftn30fFtATRv0klf4PePHyykK3bc,2238128 +pandas/_libs/hashtable.pyi,sha256=YgzWXS1QPYGqoT4zbQGK7ij39V8NYXXf0imy07h0vho,8378 +pandas/_libs/index.cpython-314-darwin.so,sha256=FZF98zDz1RUsZY31RyjTpZt-9oV0o8faHvS8es2MpsA,771944 +pandas/_libs/index.pyi,sha256=vygrxiaawiC_7J-icdG_xGRYR7nOul1RGNoqgz_Rstg,3848 +pandas/_libs/indexing.cpython-314-darwin.so,sha256=3HUle71rtkvqiZrGF0WV05HBIP1qWZawdRVsfC2k3qI,78784 +pandas/_libs/indexing.pyi,sha256=hlJwakbofPRdt1Lm31bfQ3CvHW-nMxm0nrInSWAey58,427 +pandas/_libs/internals.cpython-314-darwin.so,sha256=vKl6eGalBA8RDf0-h5C0EIIDdLbkZyzgE-fm4fIKmC4,304480 +pandas/_libs/internals.pyi,sha256=goZh3AqJR_2vwKzPzMe0K4zfoU_VpcbAsfFHSwEqQIw,3000 +pandas/_libs/interval.cpython-314-darwin.so,sha256=npROxuBKCazl0AKdf7vs3rRGlgIHmq_1hndTp73BQzo,1084192 +pandas/_libs/interval.pyi,sha256=tRyqqa59O-EYOrOk-LZUT4aWXG5_E6ZCKBo_3DFUOIY,5479 +pandas/_libs/join.cpython-314-darwin.so,sha256=8WTs5-HPdrcf04p1sIIZzhpMVNWwei0NFzRBzUCO6Jk,945528 +pandas/_libs/join.pyi,sha256=O61ZOIYi-I3gZJjDpLYIWWEe3iG0pogEQIB0ZxJ_E3Y,2780 +pandas/_libs/lib.cpython-314-darwin.so,sha256=m384bHjxkuLdE__nCHlzv5BNoCXf7Xc7VLb1FccEeFU,634136 +pandas/_libs/lib.pyi,sha256=7KYAWrgyAo0Knpv36m-TabU1ifNfrcMSXb7Zm2zLV7c,7769 +pandas/_libs/missing.cpython-314-darwin.so,sha256=AlH8mUPzErfFYzP73suQZTW5ExWWy8iN5k-Mnxp70_0,201040 +pandas/_libs/missing.pyi,sha256=LUE8HYuXdmX_mF6C3aQDmEYqvCIW9FDATACg-fFTLVI,672 +pandas/_libs/ops.cpython-314-darwin.so,sha256=7OIAAAEiSMjjYlYOtLzhGX1k6NN5F11XWZ9Iy_rCvsc,131576 +pandas/_libs/ops.pyi,sha256=DWKn3Wd-CBqnNI--MIlEuerLjm_FMWoPGiyuGgiDNr0,1404 +pandas/_libs/ops_dispatch.cpython-314-darwin.so,sha256=ItnAs-SIeHVYCV6ROtJU_Ec1WW-_hCivC4xP1mcvQhI,75248 +pandas/_libs/ops_dispatch.pyi,sha256=DzIH5A_Q0p219NJxVsH4oZ1E-o0V1cog-Hz8Qv4jDuw,246 +pandas/_libs/pandas_datetime.cpython-314-darwin.so,sha256=ctekaRdvf1n23njGqK5keVvRak2YagBq8ZztJnNj2og,70088 +pandas/_libs/pandas_parser.cpython-314-darwin.so,sha256=4mJSA7ZML1X6OsubBVEGna_NMbQLbRTvM_w8j_bYzLM,106160 +pandas/_libs/parsers.cpython-314-darwin.so,sha256=03HldsgU4ZZ0mpiyo5FHZcHaVMabaJCkI8eHJsSRAgY,616912 +pandas/_libs/parsers.pyi,sha256=iW-bT8Y0LKiv9nWKe6lxGN5vls89HS5dxj44_3GghDg,3673 +pandas/_libs/properties.cpython-314-darwin.so,sha256=l-wZP8lHuUHKzLhgJvnyzeACVqwefOJdl7kb-koyExU,98864 +pandas/_libs/properties.pyi,sha256=AVAIwBCC3Pee9HwrwYa5jvdokyvsZnk6Znu_BjWmS74,769 +pandas/_libs/reshape.cpython-314-darwin.so,sha256=lzxDUcpGVDNir4K7FNUiUR2hcfYN5Fb9ZJmjkhvBYCE,153344 +pandas/_libs/reshape.pyi,sha256=5TIGFXD8RdeVxkV_jssTvYI-GaTXSmRV8OC3z-riDPY,376 +pandas/_libs/sas.cpython-314-darwin.so,sha256=mjRpC6uEGnBuhO-QTdRr1OlHkKSsVxR2D05HZWrxKqk,178104 +pandas/_libs/sas.pyi,sha256=vvixysPFIr4KvUW9DUoa0ikqKsYAs7lC8YrbnrjYnvk,307 +pandas/_libs/sparse.cpython-314-darwin.so,sha256=oo8JQrQ8fNsudDGgDZLmbm2kGt2MXQJn5GY8n_yB9-0,789536 +pandas/_libs/sparse.pyi,sha256=QxwyVOThtebJmhmBza_IhA7Fc5pPzfXTtqtr4t_5mRA,1514 +pandas/_libs/testing.cpython-314-darwin.so,sha256=YrWtMxCNsDrJxPjLtYnGJ9HUw4sFo2xkArkrK59zNSY,153648 +pandas/_libs/testing.pyi,sha256=n93qQsAeSUOagmzwNpcK93U_k2IYYUtNdKbxRLSU9XU,484 +pandas/_libs/tslib.cpython-314-darwin.so,sha256=KC9TUBmOcVoFFohsE5qlnyQULIf2MwnlkiVYNORqylU,190264 +pandas/_libs/tslib.pyi,sha256=jl89BBom6moorKEG6WfLWvKMpqCu6zfPVrMfx7tHGmY,885 +pandas/_libs/tslibs/__init__.py,sha256=nmTPPGRp4F4gD8HXfx3Hz-dzhHKuPm46j6WIBvz_HPk,2160 +pandas/_libs/tslibs/__pycache__/__init__.cpython-314.pyc,, +pandas/_libs/tslibs/base.cpython-314-darwin.so,sha256=ZkRVd0UH8V6LqzKN4imxztghMOPIW-aKX_2AaoPGerM,75672 +pandas/_libs/tslibs/ccalendar.cpython-314-darwin.so,sha256=tzrmKL3ilZKpYNvgHlnjNHdNQFX89-aoYwzZXOBgKPc,96688 +pandas/_libs/tslibs/ccalendar.pyi,sha256=f2uBhKVhbVqM0qV1mSsYKIHYVAqz4WQdTvoJdQdlhQo,546 +pandas/_libs/tslibs/conversion.cpython-314-darwin.so,sha256=7ea5UYuCFo8YkthvIEeEVfTDkQfMfDVyA3dumMLpSlY,216560 +pandas/_libs/tslibs/conversion.pyi,sha256=9LJohU5-St916zirJgU46D3qq87b5wQ_IX4CpP2h_es,629 +pandas/_libs/tslibs/dtypes.cpython-314-darwin.so,sha256=gGGxBbAPscQmzWBMdzzOSQD2RTakG6ew7nt1XmWze7w,178320 +pandas/_libs/tslibs/dtypes.pyi,sha256=lOmVBAKEbxQc9anDrg8VKtFh_4MVh_7gf-0PtpliFWw,2091 +pandas/_libs/tslibs/fields.cpython-314-darwin.so,sha256=9fui0-KqAOiBJqShDkMzDssJl8fDinzesH2vSiRNzaE,198160 +pandas/_libs/tslibs/fields.pyi,sha256=Q7Z0Bz_2gP6j-HTx9HgXlyZfjPZDyY89L4qBhZGaPQM,1907 +pandas/_libs/tslibs/nattype.cpython-314-darwin.so,sha256=CUu4aURUmG1tMxX-14paLGCYR9Zn2rPEiMNW4LV8P38,227968 +pandas/_libs/tslibs/nattype.pyi,sha256=7cdFo-UH-dFY1QtCWLZpXl_r9APs-gWB4oSWcFvPkfk,6081 +pandas/_libs/tslibs/np_datetime.cpython-314-darwin.so,sha256=pjS0IX6JONTXsWZihCtc8mnqMrRITjd9BSZwiCAIjjI,177888 +pandas/_libs/tslibs/np_datetime.pyi,sha256=li65E2Y_IN-mxmRWyOPNp_a92o41w3i-2B1xuY6CFBk,1188 +pandas/_libs/tslibs/offsets.cpython-314-darwin.so,sha256=_S9ttlUqOVwTUqq_acNsQCWWAfkOeHTPcriGrmvrS54,1190192 +pandas/_libs/tslibs/offsets.pyi,sha256=NS0DVU4haq4DxGUHmVSeLwb8BHW-GB-aeNtyBR2kN7o,10218 +pandas/_libs/tslibs/parsing.cpython-314-darwin.so,sha256=IwN6SduKG9BjQtlBprdvifJh9fIJEDM60vu-6AwrSzo,285392 +pandas/_libs/tslibs/parsing.pyi,sha256=yPO3yRjs9V56Z7s4rBL2EQ0T6bd4e3YX4iyZRGUmwGk,948 +pandas/_libs/tslibs/period.cpython-314-darwin.so,sha256=hDwTH4uOFAVxTKfNM4-ckji6o_Z59RgmE09I_kaT3yg,424752 +pandas/_libs/tslibs/period.pyi,sha256=_lvFmqcyUEbxUFzUHE36B_xcGuTPjsYYGaR4w1dPRUU,4341 +pandas/_libs/tslibs/strptime.cpython-314-darwin.so,sha256=W_Ya07C9RCBrIZmmFrLF_ugs1gCdyLogqKFj27WaajA,235984 +pandas/_libs/tslibs/strptime.pyi,sha256=egLDsDpFzWHRqe9J5cM-F9WW5YVcZyxKoz7Sz2biLq0,366 +pandas/_libs/tslibs/timedeltas.cpython-314-darwin.so,sha256=_4UqtWymsu_mus9-jbgnqrdavC2o_D7N_PSJhdG663k,570544 +pandas/_libs/tslibs/timedeltas.pyi,sha256=m36ZmmXfG9BQus0JtwwDz4k79sa4Sla4YS7CogTPZyk,5259 +pandas/_libs/tslibs/timestamps.cpython-314-darwin.so,sha256=44urIXTCsGUPHuvT0NO5hjUAMFXkdxEtyfDyz7tal4Y,549168 +pandas/_libs/tslibs/timestamps.pyi,sha256=GHQxItiug7PQTapW7MGRBDJWjUrjz6lgZMRLYnhxtME,8983 +pandas/_libs/tslibs/timezones.cpython-314-darwin.so,sha256=bafdoWVGwW7_323N1rcNYj4LWuo2LOcYQq1EE8jPyNk,192688 +pandas/_libs/tslibs/timezones.pyi,sha256=eH4wh111hhQhTtqIDcrKd9qZO3SVzgfMlcvydIGtHUU,609 +pandas/_libs/tslibs/tzconversion.cpython-314-darwin.so,sha256=A5uv5X_xGeKDnEkIv03VLHxWEZyivets6WzecE8t_0s,194000 +pandas/_libs/tslibs/tzconversion.pyi,sha256=Pdvbn49SNuHeY3CrrHHmVT-Jn5BCb5KEOdXILsf6Bso,569 +pandas/_libs/tslibs/vectorized.cpython-314-darwin.so,sha256=jJSQxf-IBMiTGbdqdW5gfF0GiEH02Hde2y6Ld8OR5es,118928 +pandas/_libs/tslibs/vectorized.pyi,sha256=SY5nxyTfloF0NaWIkdgcJbDsfjQw-2D24P1WvsEqO7I,1235 +pandas/_libs/window/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/_libs/window/__pycache__/__init__.cpython-314.pyc,, +pandas/_libs/window/aggregations.cpython-314-darwin.so,sha256=ZepSq5IQufwfVXHq4gj7ZXHdVTbNgkZZ1x0dUyAkmPc,314656 +pandas/_libs/window/aggregations.pyi,sha256=frK-V6rXnH3ktlYXyA2I5yMiqtFhIVBtdRxk454VPIg,5295 +pandas/_libs/window/indexers.cpython-314-darwin.so,sha256=H4H6N_Ar01XC2Vi4OYjbaHKVZNVRBSkk8MYK_IfyR5c,92816 +pandas/_libs/window/indexers.pyi,sha256=r0LEFpWxGN6haDorjlx0n4IDtg0gWcBrugUEpJnnHU8,368 +pandas/_libs/writers.cpython-314-darwin.so,sha256=sAlVwp3a3iZBm7W6GY3WiS0pKQwqPB87phUwq18KrC4,116384 +pandas/_libs/writers.pyi,sha256=RvwFCzrsU4RkKm7Mc3wo12RqdGdo-PuANkMo3Z9hLiU,516 +pandas/_testing/__init__.py,sha256=QTzkZ-RWRalyuzaErtHfhhEiXFqyxGjoXeODkgvD7xg,18541 +pandas/_testing/__pycache__/__init__.cpython-314.pyc,, +pandas/_testing/__pycache__/_io.cpython-314.pyc,, +pandas/_testing/__pycache__/_warnings.cpython-314.pyc,, +pandas/_testing/__pycache__/asserters.cpython-314.pyc,, +pandas/_testing/__pycache__/compat.cpython-314.pyc,, +pandas/_testing/__pycache__/contexts.cpython-314.pyc,, +pandas/_testing/_io.py,sha256=-E2MnGNRdILVnZwk2eBfvQuwK_VobZjRJPgMWNLL7VU,3519 +pandas/_testing/_warnings.py,sha256=kzQLARZPqOjMyiKdlOX4zpZsYxknA89JRX0fMvTyopw,10805 +pandas/_testing/asserters.py,sha256=pbEgtUaQ6UcT8ie7xH4T7EuTeGrNYXkaiNWFLub7a_U,61072 +pandas/_testing/compat.py,sha256=CnVcixFumeB11UXkcPGRnWrx0dLkF8fExO1q25SCfww,737 +pandas/_testing/contexts.py,sha256=zSLdLULxPWAIsgPLBU8cnAzBhOxRLBLFspKU-R1kxuU,3829 +pandas/_typing.py,sha256=dwzUM2MmHooizSDomw4hEDjwRTNaC5J97cGe2VJ6WUQ,16711 +pandas/_version_meson.py,sha256=ystvm6yehY4a_bpHmPqWFEwZQndoNwGVT94KdT2JJ2A,79 +pandas/api/__init__.py,sha256=_aIsEKkl2kibZv64VCYBLre4jnB23Gny2aZ4VoHWLPA,282 +pandas/api/__pycache__/__init__.cpython-314.pyc,, +pandas/api/__pycache__/internals.cpython-314.pyc,, +pandas/api/executors/__init__.py,sha256=WFC8QAIJNaa1DXzf-1ulnrZvOzoAIwLx1PflPoNxGsg,174 +pandas/api/executors/__pycache__/__init__.cpython-314.pyc,, +pandas/api/extensions/__init__.py,sha256=PBbwJsFSUIz0tsK91qCRVb_fJLkX6XB2UjNfyKPvoHQ,685 +pandas/api/extensions/__pycache__/__init__.cpython-314.pyc,, +pandas/api/indexers/__init__.py,sha256=oJ_ks5iNyfEwsOHsS1n0PQMxmkpBe9r1LqJvzWpPb1w,357 +pandas/api/indexers/__pycache__/__init__.cpython-314.pyc,, +pandas/api/interchange/__init__.py,sha256=6btvqA-HE759VF7sTKt31BY-mXUEWVKyqdiJ6dbytBU,230 +pandas/api/interchange/__pycache__/__init__.cpython-314.pyc,, +pandas/api/internals.py,sha256=9gYwWFBy6LyN0GtjpIseuADGQtszxJJtpXmV4Ac501w,2371 +pandas/api/types/__init__.py,sha256=MP0Vbhd9MsZU_8w_L8VzcrJgCFp5IlJ5-WakcsjB35Q,447 +pandas/api/types/__pycache__/__init__.cpython-314.pyc,, +pandas/api/typing/__init__.py,sha256=O7JHlubZOGe97vGtvbuL8uxg-WztP9ApCI8dj0Z3FzI,3304 +pandas/api/typing/__pycache__/__init__.cpython-314.pyc,, +pandas/api/typing/__pycache__/aliases.cpython-314.pyc,, +pandas/api/typing/aliases.py,sha256=gmNIc_bJgdhlNhjsIuTsVG6d5ACeCA1Xu9lVq-0BTs0,2808 +pandas/arrays/__init__.py,sha256=Ehjr9BiyGbZcncVrrE7mwsplgnaFcbfvnjEQKeY3MHo,671 +pandas/arrays/__pycache__/__init__.cpython-314.pyc,, +pandas/compat/__init__.py,sha256=fgTeB0zWlF--sPL6_QDhHN2ZnGkz3kgZKiLmTz_vsRA,3266 +pandas/compat/__pycache__/__init__.cpython-314.pyc,, +pandas/compat/__pycache__/_constants.cpython-314.pyc,, +pandas/compat/__pycache__/_cpu.cpython-314.pyc,, +pandas/compat/__pycache__/_optional.cpython-314.pyc,, +pandas/compat/__pycache__/pickle_compat.cpython-314.pyc,, +pandas/compat/__pycache__/pyarrow.cpython-314.pyc,, +pandas/compat/_constants.py,sha256=BUxjtWJgYqORzSluyjT2-7NXUAUxgDR6PVGOEY1AXDs,849 +pandas/compat/_cpu.py,sha256=Fng-2XLqiVzVx-Vs2LSWA_OP6Yo1MZVkTBUpLhlFJYg,3768 +pandas/compat/_optional.py,sha256=GrrUG-EhPJlDEEW0giswqEuPdVmZHPqCf8gcaItAly8,5635 +pandas/compat/numpy/__init__.py,sha256=95J0qSpsixy56n5AscDuyRKe_Pr4Xnw6UD7ZCXUD7uY,684 +pandas/compat/numpy/__pycache__/__init__.cpython-314.pyc,, +pandas/compat/numpy/__pycache__/function.cpython-314.pyc,, +pandas/compat/numpy/function.py,sha256=RGgUYlsqlYzfmpt-eM9HVb6R-gDqry87O1lE_9z6vhk,11791 +pandas/compat/pickle_compat.py,sha256=Jb4UiRDYuTeMnENm-1_L8EltPj8I_vCZgO0aDnTCNmA,5200 +pandas/compat/pyarrow.py,sha256=NwAH23ZR4y6BD_527kzStklS1YH_oNgp-SCXkDZmyxo,3121 +pandas/conftest.py,sha256=ZyexXNpLO6f-KvU2dBI48nAqMsausJmUsI7v2ejwpXI,53687 +pandas/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/__pycache__/__init__.cpython-314.pyc,, +pandas/core/__pycache__/accessor.cpython-314.pyc,, +pandas/core/__pycache__/algorithms.cpython-314.pyc,, +pandas/core/__pycache__/api.cpython-314.pyc,, +pandas/core/__pycache__/apply.cpython-314.pyc,, +pandas/core/__pycache__/arraylike.cpython-314.pyc,, +pandas/core/__pycache__/base.cpython-314.pyc,, +pandas/core/__pycache__/col.cpython-314.pyc,, +pandas/core/__pycache__/common.cpython-314.pyc,, +pandas/core/__pycache__/config_init.cpython-314.pyc,, +pandas/core/__pycache__/construction.cpython-314.pyc,, +pandas/core/__pycache__/flags.cpython-314.pyc,, +pandas/core/__pycache__/frame.cpython-314.pyc,, +pandas/core/__pycache__/generic.cpython-314.pyc,, +pandas/core/__pycache__/indexing.cpython-314.pyc,, +pandas/core/__pycache__/missing.cpython-314.pyc,, +pandas/core/__pycache__/nanops.cpython-314.pyc,, +pandas/core/__pycache__/resample.cpython-314.pyc,, +pandas/core/__pycache__/roperator.cpython-314.pyc,, +pandas/core/__pycache__/sample.cpython-314.pyc,, +pandas/core/__pycache__/series.cpython-314.pyc,, +pandas/core/__pycache__/sorting.cpython-314.pyc,, +pandas/core/_numba/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/_numba/__pycache__/__init__.cpython-314.pyc,, +pandas/core/_numba/__pycache__/executor.cpython-314.pyc,, +pandas/core/_numba/__pycache__/extensions.cpython-314.pyc,, +pandas/core/_numba/executor.py,sha256=oKz5n6mI34mvz_MMnP0GkD39AK2k_AKdpw0zwuciawM,8175 +pandas/core/_numba/extensions.py,sha256=s-we6z1X-cAMy7nzPVzrsNR0rPM1kFUMnpj_IBjOxY0,18513 +pandas/core/_numba/kernels/__init__.py,sha256=0qDqF5R8ykYS8CAsLgb3_Jsr4XQ7pgcQRltGxypW8gk,520 +pandas/core/_numba/kernels/__pycache__/__init__.cpython-314.pyc,, +pandas/core/_numba/kernels/__pycache__/mean_.cpython-314.pyc,, +pandas/core/_numba/kernels/__pycache__/min_max_.cpython-314.pyc,, +pandas/core/_numba/kernels/__pycache__/shared.cpython-314.pyc,, +pandas/core/_numba/kernels/__pycache__/sum_.cpython-314.pyc,, +pandas/core/_numba/kernels/__pycache__/var_.cpython-314.pyc,, +pandas/core/_numba/kernels/mean_.py,sha256=h5gdfbMopMzJn3vnyKaZ4Lfc6nvDxW4-sEcHpfgX4AE,5603 +pandas/core/_numba/kernels/min_max_.py,sha256=ql3rnDDFGLXsPOMIQ0K9pSCiRJHwUc-g8bI-0oPFgJQ,5176 +pandas/core/_numba/kernels/shared.py,sha256=ipkLSMOxQ4KeBo-az-Tzt-ZjzAMLlS4QJybI2S9Hyow,539 +pandas/core/_numba/kernels/sum_.py,sha256=C04fcYsHNafxUwFhldDvov6ajb_IdHFRANd6Dw5BXTc,6649 +pandas/core/_numba/kernels/var_.py,sha256=3zfrxhY7Auhor7MoLDYCH3GFlQ4XBEgmY4Wl5RsBqEo,7060 +pandas/core/accessor.py,sha256=1zfSwCOeBpPZkqJuHunlb3PdB-X6Bf9geecNnDZ3KZ4,15837 +pandas/core/algorithms.py,sha256=5NIDZwLfoZFwnmdjwWq2ymiBw5694yJvgaKad_lKMks,67521 +pandas/core/api.py,sha256=Pz8Y29VbnqsutjX1O7csKQP09qQWmtAavp_CaAloSeg,2951 +pandas/core/apply.py,sha256=2wnyYrXN3E8bbvvBgIrLgmiDsdsaaxgea90ZTQ6VqoE,81576 +pandas/core/array_algos/__init__.py,sha256=8YLlO6TysEPxltfbNKdG9MlVXeDLfTIGNo2nUR-Zwl0,408 +pandas/core/array_algos/__pycache__/__init__.cpython-314.pyc,, +pandas/core/array_algos/__pycache__/datetimelike_accumulations.cpython-314.pyc,, +pandas/core/array_algos/__pycache__/masked_accumulations.cpython-314.pyc,, +pandas/core/array_algos/__pycache__/masked_reductions.cpython-314.pyc,, +pandas/core/array_algos/__pycache__/putmask.cpython-314.pyc,, +pandas/core/array_algos/__pycache__/quantile.cpython-314.pyc,, +pandas/core/array_algos/__pycache__/replace.cpython-314.pyc,, +pandas/core/array_algos/__pycache__/take.cpython-314.pyc,, +pandas/core/array_algos/__pycache__/transforms.cpython-314.pyc,, +pandas/core/array_algos/datetimelike_accumulations.py,sha256=d2IHDOp9SadH0gY-2dL1jnCwcwg-Z90T81eSxzxC4TY,3287 +pandas/core/array_algos/masked_accumulations.py,sha256=rcnqRRE0miFR4S3tYdx4zetnlXOx6ANNlHWBYTFcKJs,2914 +pandas/core/array_algos/masked_reductions.py,sha256=RLNSMbc4aABMZq7ojAHydegZgiYZwaP_bvuey0Fi-ak,7010 +pandas/core/array_algos/putmask.py,sha256=2-w-PKG7fWALtNewz0-lWEHdd5DgpKP9iD1cVjwLP9M,4606 +pandas/core/array_algos/quantile.py,sha256=zTw0LAxJj7JW_S84QWyxSye87jHLtoArCe8AhFyVfTA,6724 +pandas/core/array_algos/replace.py,sha256=0hdPl8JcbSQOJkg8NWr_FldnQpufkBES-y3TiOm9soU,4154 +pandas/core/array_algos/take.py,sha256=wdf3MGOew5gxW1NnotHCV_qBid8b2lanrBOzRTEAja0,22407 +pandas/core/array_algos/transforms.py,sha256=X2-Cf1m84VwnOsda1FGbVny_ojEkYJGHJxlS0cV049o,1096 +pandas/core/arraylike.py,sha256=bwyH7jsYp8bhmaPRXOuzi0l4m3vuifibnlj-skOnTnA,19347 +pandas/core/arrays/__init__.py,sha256=f00N1VdEGdOEuLUDpw2o1vLInlUeR-rjeuUVL5h9Hwk,1314 +pandas/core/arrays/__pycache__/__init__.cpython-314.pyc,, +pandas/core/arrays/__pycache__/_arrow_string_mixins.cpython-314.pyc,, +pandas/core/arrays/__pycache__/_mixins.cpython-314.pyc,, +pandas/core/arrays/__pycache__/_ranges.cpython-314.pyc,, +pandas/core/arrays/__pycache__/_utils.cpython-314.pyc,, +pandas/core/arrays/__pycache__/base.cpython-314.pyc,, +pandas/core/arrays/__pycache__/boolean.cpython-314.pyc,, +pandas/core/arrays/__pycache__/categorical.cpython-314.pyc,, +pandas/core/arrays/__pycache__/datetimelike.cpython-314.pyc,, +pandas/core/arrays/__pycache__/datetimes.cpython-314.pyc,, +pandas/core/arrays/__pycache__/floating.cpython-314.pyc,, +pandas/core/arrays/__pycache__/integer.cpython-314.pyc,, +pandas/core/arrays/__pycache__/interval.cpython-314.pyc,, +pandas/core/arrays/__pycache__/masked.cpython-314.pyc,, +pandas/core/arrays/__pycache__/numeric.cpython-314.pyc,, +pandas/core/arrays/__pycache__/numpy_.cpython-314.pyc,, +pandas/core/arrays/__pycache__/period.cpython-314.pyc,, +pandas/core/arrays/__pycache__/string_.cpython-314.pyc,, +pandas/core/arrays/__pycache__/string_arrow.cpython-314.pyc,, +pandas/core/arrays/__pycache__/timedeltas.cpython-314.pyc,, +pandas/core/arrays/_arrow_string_mixins.py,sha256=GXDT2DnaaKQSdsFpefC1fdfGe6fgQxkmIHDtQ31Khx8,26113 +pandas/core/arrays/_mixins.py,sha256=W4P94Xs9UYwJrlSchr5LOpb23Grg6xf6TTsva4R3CyI,21479 +pandas/core/arrays/_ranges.py,sha256=lBHHF_irCJJTygF4kjQJSYaLmEM8PLO5pOZ2D9Vz8es,10000 +pandas/core/arrays/_utils.py,sha256=5q3vTseZtpI1dO-euu001dU_bSmb56HaqhERn-hGH-I,2485 +pandas/core/arrays/arrow/__init__.py,sha256=OK9PZIFiJ1GrLpplKHJ6gV5Zfhex20P_avvdO5ZXzc4,221 +pandas/core/arrays/arrow/__pycache__/__init__.cpython-314.pyc,, +pandas/core/arrays/arrow/__pycache__/_arrow_utils.cpython-314.pyc,, +pandas/core/arrays/arrow/__pycache__/accessors.cpython-314.pyc,, +pandas/core/arrays/arrow/__pycache__/array.cpython-314.pyc,, +pandas/core/arrays/arrow/__pycache__/extension_types.cpython-314.pyc,, +pandas/core/arrays/arrow/_arrow_utils.py,sha256=RulRjyWzUn9gVFVeypndUwDLezpR2SWACD6_BYmxKDg,1586 +pandas/core/arrays/arrow/accessors.py,sha256=VafU0NSq0rICwg7UX0Wj5WK8HCIX8jQ8v63fa3fPlCU,16120 +pandas/core/arrays/arrow/array.py,sha256=qpA7glf8YSSy4TxrXc6BTeubXnJUmg5CLfeekg8Wip4,178192 +pandas/core/arrays/arrow/extension_types.py,sha256=lmSVV8kxMZF4Czj--AzmNFJChcN5CVnysYvYmoQuhDU,3968 +pandas/core/arrays/base.py,sha256=wumlwYX-rOrXfXSz2KrpPIYjm2Xy-Pm9EgpatSmh3NA,115479 +pandas/core/arrays/boolean.py,sha256=4K80vV9nK5Gz2h3JiWY5kL6-QbaRvYNc1LSLztilQ1c,14211 +pandas/core/arrays/categorical.py,sha256=Aea5JA8CKxoNiRGi6uD9K19DW_-mKwikNiv862RP--I,112983 +pandas/core/arrays/datetimelike.py,sha256=i4pQnOdhVc4vC8lhM7TFd525ZEjGVqeYgI1KT7-jNb4,92379 +pandas/core/arrays/datetimes.py,sha256=hM9FkFmFl17yXjVMZXFNYwCWnAw-DiWTIcOCSYNxyDs,109182 +pandas/core/arrays/floating.py,sha256=F4yboqyamt45RZaurIdKUxQROSI_udNBirrNGE3O3Ss,4765 +pandas/core/arrays/integer.py,sha256=SGzJwr44OAF9yrOBDILIDA5emPNQ2d0peWgegAseyGk,7084 +pandas/core/arrays/interval.py,sha256=gGwzFYxC9Y6PdJpJbYBuryDyGlWRR21lqkxOjGOrxho,68448 +pandas/core/arrays/masked.py,sha256=SyHx3cVBCC2G4DNRNMI65-aYlj7Mj2j7h6Q8O2AAfKk,78245 +pandas/core/arrays/numeric.py,sha256=E57pL2ZfWFjaebnop8SYIkHmpjf-AKis1viq5IhbWHE,10345 +pandas/core/arrays/numpy_.py,sha256=S5h-08Cy9kAQIHoLtIqEOZyzfFTRjwmZ6U3Qh6i1AOI,22334 +pandas/core/arrays/period.py,sha256=j21zpwU4NwHxu3F1HPfQnOng5ASsTQCpjSb5IYuExtc,54359 +pandas/core/arrays/sparse/__init__.py,sha256=M9tMvwNfj9ATInGPo450gjvvrznKiCfJtXjTaH0CidM,356 +pandas/core/arrays/sparse/__pycache__/__init__.cpython-314.pyc,, +pandas/core/arrays/sparse/__pycache__/accessor.cpython-314.pyc,, +pandas/core/arrays/sparse/__pycache__/array.cpython-314.pyc,, +pandas/core/arrays/sparse/__pycache__/scipy_sparse.cpython-314.pyc,, +pandas/core/arrays/sparse/accessor.py,sha256=4XTOsShHRStZjd4T2uitj_Qvsy6c1UbicGCzVqk76Yg,16749 +pandas/core/arrays/sparse/array.py,sha256=9u0ffivLJDM12v_InumENdimeige_W_Wb5ftuPlwDvM,114085 +pandas/core/arrays/sparse/scipy_sparse.py,sha256=UNZ8dE4RTHq7ElLovH9ApNibOrXx6XLvkG0JaRiIsZ0,6546 +pandas/core/arrays/string_.py,sha256=R2UIXBRwLuUVwDZ5j60nn5cVsUtQ2bdUjWEpkXZUiM4,45366 +pandas/core/arrays/string_arrow.py,sha256=OMwQsX08IDPXM2X_NLdAUXwNOdT3BC5HYcOpoeyFoa8,24301 +pandas/core/arrays/timedeltas.py,sha256=YPkKnEI6ODbPGyBk_4KDWHbTadxOqsaNgqIwHRKmnD4,52859 +pandas/core/base.py,sha256=_LQtuk3aQO3mDHyMlqmY16VHdcYdumFCAxfeI_69W_0,53241 +pandas/core/col.py,sha256=4pYfS-kOQnEv0kgtm1hLCtSBEgC3eUN2WtzF6n0XsuM,16431 +pandas/core/common.py,sha256=lEPaBDt5AJLivdmfMfB3gq5rREBIn_PJTJ6WHye6ZXc,19923 +pandas/core/computation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/computation/__pycache__/__init__.cpython-314.pyc,, +pandas/core/computation/__pycache__/align.cpython-314.pyc,, +pandas/core/computation/__pycache__/api.cpython-314.pyc,, +pandas/core/computation/__pycache__/check.cpython-314.pyc,, +pandas/core/computation/__pycache__/common.cpython-314.pyc,, +pandas/core/computation/__pycache__/engines.cpython-314.pyc,, +pandas/core/computation/__pycache__/eval.cpython-314.pyc,, +pandas/core/computation/__pycache__/expr.cpython-314.pyc,, +pandas/core/computation/__pycache__/expressions.cpython-314.pyc,, +pandas/core/computation/__pycache__/ops.cpython-314.pyc,, +pandas/core/computation/__pycache__/parsing.cpython-314.pyc,, +pandas/core/computation/__pycache__/pytables.cpython-314.pyc,, +pandas/core/computation/__pycache__/scope.cpython-314.pyc,, +pandas/core/computation/align.py,sha256=4Pfxuz_cXnvYGt-HSUjwW_YXrLjezFMdRk_5q1T1Kic,6805 +pandas/core/computation/api.py,sha256=CQ2AF0hwydcgTHycMCFiyZIAU57RcZT-TVid17SIsV4,65 +pandas/core/computation/check.py,sha256=0yeIwc-AZe3iwb6BO1_eVO_Af64zeTai6aJkoWcfSfE,1756 +pandas/core/computation/common.py,sha256=SHSWCAQnpllMl64nNeaKd3UrmqORwOPwcwMh4-UsYGg,1602 +pandas/core/computation/engines.py,sha256=IrCaW-O43mdOlP6ilFwhky9JnbL6zBaUxAIosOUPsvY,3409 +pandas/core/computation/eval.py,sha256=1s2ZSUQqssTFUqzVHsL--2WPinjqoiT5UDeCNaEHVB8,17355 +pandas/core/computation/expr.py,sha256=-8cbcxLamtAi42esfczEEFaTolY1IYTFizSkgaE8dic,27288 +pandas/core/computation/expressions.py,sha256=-H72_t4G2z9Sq9V_jUhA9HNd9zIpR2LP1Q3iI20mpG0,9377 +pandas/core/computation/ops.py,sha256=EleXyXnldipCReIDe9O-XqHZ2_PKhuoH1FXxcdfaC20,14768 +pandas/core/computation/parsing.py,sha256=VPH2Vn799V5VQRTwuY6xlZMaoUso7-adtTTgxaxcgjA,7711 +pandas/core/computation/pytables.py,sha256=ghWD0n904KNvyQv3nZ_mPQl9UtrXgEhGFs0nVoWWyNQ,24921 +pandas/core/computation/scope.py,sha256=WdN1n69F8dp5xntAJKPjr9LFwxw0ZKfbAkIoQmfOtRg,10019 +pandas/core/config_init.py,sha256=4NrYvz8NO4aog0X3AD3rKydBlnnfIJZRMt7TFw2s9Xc,32735 +pandas/core/construction.py,sha256=MuxXBJQ6ZXJWju3dpK2K8aZvPwqwBWjeH_2KqE9moQo,29906 +pandas/core/dtypes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/dtypes/__pycache__/__init__.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/api.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/astype.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/base.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/cast.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/common.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/concat.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/dtypes.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/generic.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/inference.cpython-314.pyc,, +pandas/core/dtypes/__pycache__/missing.cpython-314.pyc,, +pandas/core/dtypes/api.py,sha256=lkEgxy5kKaA2rU7XpWfSgd4vsQcVUr3Nduddvd_STp4,1783 +pandas/core/dtypes/astype.py,sha256=a_a_vLifcSWPJyLcYE7RnYkW3d0FUIsbC_pVrVs77F0,10597 +pandas/core/dtypes/base.py,sha256=Lg0UOL3Lb_dd3BDMMl3F93WoeUuYPpTxExwHE0n46Gs,19800 +pandas/core/dtypes/cast.py,sha256=bIb2jyPaJ2kPzeMjk2bss7PF0WYecYk9PFvMGXQ1gGU,64515 +pandas/core/dtypes/common.py,sha256=uw3jBZJk_xtR1SHvreQ4oIDIeZerGmhKTR6qPDDlDek,57977 +pandas/core/dtypes/concat.py,sha256=h1-aX46F-gFOuIMiMXJx-e8R7x4jZ1-YyGl484hzzsM,14556 +pandas/core/dtypes/dtypes.py,sha256=oN8QlVnNLDU0ISbNUWBgzej_T7x2c2KkT28fxRMKgAU,86051 +pandas/core/dtypes/generic.py,sha256=GBDF_WHJnhz-AFg2MxomXdS1WqDWEd-fgWXWROlt1Xg,4202 +pandas/core/dtypes/inference.py,sha256=jNeUUkXC5ZPd3wmh6W8dMAgF_XymoBw0PW9Bnqc40Dg,12915 +pandas/core/dtypes/missing.py,sha256=NFw8I1JIOLYG3Wf4t_MPu4Bbo5Bn-Fe4fshQyXsmLUc,21929 +pandas/core/flags.py,sha256=-bL75S-J7dpIuvLTKbHrqfAF5Ny_9gJwGo5YhQ5EaWc,4233 +pandas/core/frame.py,sha256=nCjNZdAppkCR79LSPoKB8t5Nja4Ref-SsOruhxKoR7k,725069 +pandas/core/generic.py,sha256=f3ZSEvDJzKlJh2uw1lRbc2OOA_SQa9xaUd1eBR24fQ0,455443 +pandas/core/groupby/__init__.py,sha256=nyZsjyVF-bFx52HYbK4SQMfDNusvYZ1ANGJVxEeAkfQ,301 +pandas/core/groupby/__pycache__/__init__.cpython-314.pyc,, +pandas/core/groupby/__pycache__/base.cpython-314.pyc,, +pandas/core/groupby/__pycache__/categorical.cpython-314.pyc,, +pandas/core/groupby/__pycache__/generic.cpython-314.pyc,, +pandas/core/groupby/__pycache__/groupby.cpython-314.pyc,, +pandas/core/groupby/__pycache__/grouper.cpython-314.pyc,, +pandas/core/groupby/__pycache__/indexing.cpython-314.pyc,, +pandas/core/groupby/__pycache__/numba_.cpython-314.pyc,, +pandas/core/groupby/__pycache__/ops.cpython-314.pyc,, +pandas/core/groupby/base.py,sha256=E3J2X0Tz_xjUhzsH4zg5aA6qBX8zJ_2ANsDgN000gaM,2721 +pandas/core/groupby/categorical.py,sha256=ud4ibWxFBtWuET1Ovri8DkI9q_v4VJxU8IK9qwBOOEI,2781 +pandas/core/groupby/generic.py,sha256=Amk8RXQC9RaKfLgIdEZsIYzVNvC9iuFY9kcUMw6hQuE,148110 +pandas/core/groupby/groupby.py,sha256=dwaXAbD2FfY9f5mfUYUBGpd_HdRrAU7Q5k0vxtB938o,189101 +pandas/core/groupby/grouper.py,sha256=qbZnp52iST9seAyS2IkCy1yYFfNCtqQAvasKxKcp1Og,35976 +pandas/core/groupby/indexing.py,sha256=XeUF7iTutH2eHYtKrk72iGmo17wM6-oWlTrgWEM1Fck,12294 +pandas/core/groupby/numba_.py,sha256=af82xovrJfBDcFmMh48DoTVvGJtScDINO-jtJ7Jc8Q8,4725 +pandas/core/groupby/ops.py,sha256=gtEs50COR0NHUyGToRnBMaqKXUUzFk9kzqjtu5qmy3o,49186 +pandas/core/indexers/__init__.py,sha256=pgaa2DUC74IpoYQN0EbWzFkjj-3GsdfvQxRDlXKCYXk,790 +pandas/core/indexers/__pycache__/__init__.cpython-314.pyc,, +pandas/core/indexers/__pycache__/objects.cpython-314.pyc,, +pandas/core/indexers/__pycache__/utils.cpython-314.pyc,, +pandas/core/indexers/objects.py,sha256=gLFF7IUJdmKLs6C-FmdXrlYpxo7fHuWgJZdWwvfLqOo,22685 +pandas/core/indexers/utils.py,sha256=K7gmiFz_udwHAPnBYmNh6OeO9DQUFxszzbyTSCoGaCQ,17355 +pandas/core/indexes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/indexes/__pycache__/__init__.cpython-314.pyc,, +pandas/core/indexes/__pycache__/accessors.cpython-314.pyc,, +pandas/core/indexes/__pycache__/api.cpython-314.pyc,, +pandas/core/indexes/__pycache__/base.cpython-314.pyc,, +pandas/core/indexes/__pycache__/category.cpython-314.pyc,, +pandas/core/indexes/__pycache__/datetimelike.cpython-314.pyc,, +pandas/core/indexes/__pycache__/datetimes.cpython-314.pyc,, +pandas/core/indexes/__pycache__/extension.cpython-314.pyc,, +pandas/core/indexes/__pycache__/frozen.cpython-314.pyc,, +pandas/core/indexes/__pycache__/interval.cpython-314.pyc,, +pandas/core/indexes/__pycache__/multi.cpython-314.pyc,, +pandas/core/indexes/__pycache__/period.cpython-314.pyc,, +pandas/core/indexes/__pycache__/range.cpython-314.pyc,, +pandas/core/indexes/__pycache__/timedeltas.cpython-314.pyc,, +pandas/core/indexes/accessors.py,sha256=Z4E_Dr4cxNVWaCmFNRSbspkvGJHu0JhGkUuBL7ej7yM,26423 +pandas/core/indexes/api.py,sha256=9GG_5niPY9bbHLyCHvsB9nuMU2_iCLax7kL4SeBQlFY,10067 +pandas/core/indexes/base.py,sha256=Ra4BZhDOPWPoS1IKXM9eKq8c6tck5TF2KZO0g-FUA1U,304041 +pandas/core/indexes/category.py,sha256=GF6UXT_735ArCkrwSF0UR5zDf-CahsNscXTy1hQoamM,37406 +pandas/core/indexes/datetimelike.py,sha256=2wHOS5ZXV2LjcFW75Ke9e24NFdrYanjx2KALFVglYtQ,60596 +pandas/core/indexes/datetimes.py,sha256=Ll8eedEWgMcYBAkz6OszpLzyEJ1wKYlzuJeOuhrAs78,105794 +pandas/core/indexes/extension.py,sha256=3SDIl6HDlt4WFLqW7Jto2tNOgZutWckZMbmK5-IR2fE,5303 +pandas/core/indexes/frozen.py,sha256=H5DAmwJbFVXcsO3pgkU9FoOGW5RVk4IbubFIPo32RAQ,3642 +pandas/core/indexes/interval.py,sha256=kcyy_kflkAgyxkkPKWHzlGqW2oeArPnbEGqLgkt8mN8,64410 +pandas/core/indexes/multi.py,sha256=HQ9Wa78_ozYMlBP6QajWayI2De7ZoM9Fwc8f7GASBSs,189635 +pandas/core/indexes/period.py,sha256=VE6BqAJ0g3CX62Cg77U9tfJOKNX4yidZFVCNoKWmS_w,39344 +pandas/core/indexes/range.py,sha256=gf1Cj5PRradGogX8xf97cul3FjMYZGYld2JgCTm5tDI,59145 +pandas/core/indexes/timedeltas.py,sha256=LuoJ_yFjTH3Y5LrI7f8exEIbGbf60l4j1caEZAm27QU,37919 +pandas/core/indexing.py,sha256=CV4UFweQ7MAPjRefHSnxua7rg6veNUV6jh3YfjproHc,137156 +pandas/core/interchange/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/interchange/__pycache__/__init__.cpython-314.pyc,, +pandas/core/interchange/__pycache__/buffer.cpython-314.pyc,, +pandas/core/interchange/__pycache__/column.cpython-314.pyc,, +pandas/core/interchange/__pycache__/dataframe.cpython-314.pyc,, +pandas/core/interchange/__pycache__/dataframe_protocol.cpython-314.pyc,, +pandas/core/interchange/__pycache__/from_dataframe.cpython-314.pyc,, +pandas/core/interchange/__pycache__/utils.cpython-314.pyc,, +pandas/core/interchange/buffer.py,sha256=eTiReDShvrTHZLrnbMuH3SUWoMO_vi1jgmSOtqzUKmo,3428 +pandas/core/interchange/column.py,sha256=AFBrsmVHWzaXUJtl9C5NktCqpDPChjiir_YNrELSyt0,17947 +pandas/core/interchange/dataframe.py,sha256=1-DL5KRZo3psA49tl2SE-rzAHPYXs_8-eESL5wAH4uc,3867 +pandas/core/interchange/dataframe_protocol.py,sha256=gm53R0mzHevPrbGAJB7BdOu5HuTXE3lCZo2VRv0hRe4,16263 +pandas/core/interchange/from_dataframe.py,sha256=Y7HACCn7qoA-NgAY4RlsZjsX_UNK3tWB7RDzN_SaejY,19979 +pandas/core/interchange/utils.py,sha256=TNyR-uXm7J_-wU0CLpIf9ih_bq8p5aBuUv6O_41wKK8,5051 +pandas/core/internals/__init__.py,sha256=L5o11_EzV-SrVsFgueb1m7cUCAuO_3oKYtxZwCOAZQw,2113 +pandas/core/internals/__pycache__/__init__.cpython-314.pyc,, +pandas/core/internals/__pycache__/api.cpython-314.pyc,, +pandas/core/internals/__pycache__/blocks.cpython-314.pyc,, +pandas/core/internals/__pycache__/concat.cpython-314.pyc,, +pandas/core/internals/__pycache__/construction.cpython-314.pyc,, +pandas/core/internals/__pycache__/managers.cpython-314.pyc,, +pandas/core/internals/__pycache__/ops.cpython-314.pyc,, +pandas/core/internals/api.py,sha256=wj4jsXvuMi_c4FhalNUZKPK02gz0h1YRQbdgElBO4MQ,6031 +pandas/core/internals/blocks.py,sha256=z3EbVgrsVXGp7ho0VEcOddiI1H00IUtbYk3YxisV9W8,90589 +pandas/core/internals/concat.py,sha256=_Ppc5m7as8PHu2pLTHo6kcz1Ol9QRS3D3VXilUpoQck,14278 +pandas/core/internals/construction.py,sha256=BWwy18zrg7TqUf2oYukrrTw5L1w-yluyBMMRUWITdSc,35315 +pandas/core/internals/managers.py,sha256=l-BTFcQfU-WAKclDwJetpjgNr7VIfqCDD3yiJ3-CzSg,90986 +pandas/core/internals/ops.py,sha256=OaHE4jFBVqkoKiR_DNdFfVHRmCftTKSXETO0Q0wFFDk,5382 +pandas/core/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/methods/__pycache__/__init__.cpython-314.pyc,, +pandas/core/methods/__pycache__/describe.cpython-314.pyc,, +pandas/core/methods/__pycache__/filter.cpython-314.pyc,, +pandas/core/methods/__pycache__/select.cpython-314.pyc,, +pandas/core/methods/__pycache__/selectn.cpython-314.pyc,, +pandas/core/methods/__pycache__/to_dict.cpython-314.pyc,, +pandas/core/methods/describe.py,sha256=ygCsSb7rfLkZI5vOoCL-F8auQj4TjFOFWV4ALh67nU4,11174 +pandas/core/methods/filter.py,sha256=FwxzpMvtiOIWG2PNnkCynUwEwtyRNHcvLyQMfg7vfLY,3095 +pandas/core/methods/select.py,sha256=mjKKgmYAMiF2pNqp8LWB-klNSJcqb1mr3TqeAG0eTE0,6465 +pandas/core/methods/selectn.py,sha256=TM_E5m3R5wH3kRZN1Kpi3g3H7AYKJ0gqedivVi0bwDs,8783 +pandas/core/methods/to_dict.py,sha256=i0-uEsHyZ3-0ZwEZjvN-Xkm8rTWU1VCpmgROIWWM4Do,9578 +pandas/core/missing.py,sha256=ZYig6PhA43Z4a2eDOGb6RayXkL7q0siAm_jRn1AacB0,35297 +pandas/core/nanops.py,sha256=wEX0107-JCnrR_4h9YqmBl02MJB6JRfuO2TRlNEzfq4,68294 +pandas/core/ops/__init__.py,sha256=yQf8xz14i9qAbHPgBXfBFcCezAooAmtmxvycXrdy2g4,1854 +pandas/core/ops/__pycache__/__init__.cpython-314.pyc,, +pandas/core/ops/__pycache__/array_ops.cpython-314.pyc,, +pandas/core/ops/__pycache__/common.cpython-314.pyc,, +pandas/core/ops/__pycache__/dispatch.cpython-314.pyc,, +pandas/core/ops/__pycache__/invalid.cpython-314.pyc,, +pandas/core/ops/__pycache__/mask_ops.cpython-314.pyc,, +pandas/core/ops/__pycache__/missing.cpython-314.pyc,, +pandas/core/ops/array_ops.py,sha256=A3aEH04rZnVX6qrpBlwrDPEsiZEOpYUgdohbEqV5Wlg,19796 +pandas/core/ops/common.py,sha256=qWMagahRU5_va39y8mn4zkzgz7lDhSq4Y0YY9S6UBZk,5638 +pandas/core/ops/dispatch.py,sha256=YPhnM8c7C9rikrUujv0Ut27fZ70yABBp_pdCikGAOA8,636 +pandas/core/ops/invalid.py,sha256=nftlpJTDnopvsZ4wcCafja86q7yAIFa7JY5cAR2KlxI,8021 +pandas/core/ops/mask_ops.py,sha256=BVJ4-n6aw8mpOk2zau6HNrRWm3S-ksfHKvP0FV0xDjQ,5638 +pandas/core/ops/missing.py,sha256=FnKTIe6qyJFgUyIwAmrhrz0yC650q15wEF0yWANFqOA,5067 +pandas/core/resample.py,sha256=ZtwMnHi_1ZofiuAwJ1hZXQ-WuLdJ_iF6uZMyAC0-Jco,105529 +pandas/core/reshape/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/reshape/__pycache__/__init__.cpython-314.pyc,, +pandas/core/reshape/__pycache__/api.cpython-314.pyc,, +pandas/core/reshape/__pycache__/concat.cpython-314.pyc,, +pandas/core/reshape/__pycache__/encoding.cpython-314.pyc,, +pandas/core/reshape/__pycache__/melt.cpython-314.pyc,, +pandas/core/reshape/__pycache__/merge.cpython-314.pyc,, +pandas/core/reshape/__pycache__/pivot.cpython-314.pyc,, +pandas/core/reshape/__pycache__/reshape.cpython-314.pyc,, +pandas/core/reshape/__pycache__/tile.cpython-314.pyc,, +pandas/core/reshape/api.py,sha256=Qk5y-D5-OdRYKkCgc-ktcxKGNGSCPteISEsByXFWI9M,680 +pandas/core/reshape/concat.py,sha256=aMJS4blJNjnrmMmO0-tY-qT8XRu0Gqf614BDliWMUCY,32986 +pandas/core/reshape/encoding.py,sha256=uYO6GX5bcpnoF6POeICcg-TTArCEeoidU4bEj_w3lVQ,21350 +pandas/core/reshape/melt.py,sha256=nA7HVPyxYcL4jeSxEMbDIrwtgjuHgHkuDF8q0SPqjwc,22406 +pandas/core/reshape/merge.py,sha256=JB7kZf6xwtUZ-0rKLvaU6Yvfpy-F7xfaP9eIzdMwWSc,125754 +pandas/core/reshape/pivot.py,sha256=MuKHX43bIYOW0UxU3nSsRyXsacCHPskhO_tZjW5cfo0,43940 +pandas/core/reshape/reshape.py,sha256=eBNRFkr3kLwpyRa2NPTRhIBmUDcDkXYaG8N3S1q3vWY,42943 +pandas/core/reshape/tile.py,sha256=PxDVKXZwB90eMHoU9dN6dhGIjLus0dh4DnshlMtqGaY,24425 +pandas/core/roperator.py,sha256=CKAlCk1V8Ual0lgR5pLGYzlRmvVdCFYDpezUpQvZIPo,1354 +pandas/core/sample.py,sha256=gNF9YluNGiq-rD7Rm4mT_eIjqY-nCMMgBINgUz5h_XQ,5099 +pandas/core/series.py,sha256=94Bjio1Ge0B1cxsi35MC-0_Kc3eBDvJoJHnq0N4IbKY,340463 +pandas/core/sorting.py,sha256=pxM4Io2x6TauvYlSXWLgH6pD-BQM2Vl0c111ZOjPqrM,23824 +pandas/core/sparse/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/sparse/__pycache__/__init__.cpython-314.pyc,, +pandas/core/sparse/__pycache__/api.cpython-314.pyc,, +pandas/core/sparse/api.py,sha256=y0onCpBKCj_5Iaybw5e-gxk8zAa9d1p5Zu58RLzPT1k,143 +pandas/core/strings/__init__.py,sha256=TRw-H0s6qCbXoQKM01_SixgPOCRmrahYKpljDyHwWkI,807 +pandas/core/strings/__pycache__/__init__.cpython-314.pyc,, +pandas/core/strings/__pycache__/accessor.cpython-314.pyc,, +pandas/core/strings/__pycache__/object_array.cpython-314.pyc,, +pandas/core/strings/accessor.py,sha256=AX1ngeO0BnHK3Zhdyl8OouLZ0M0YPAEvVSFiCFUP9f8,167727 +pandas/core/strings/object_array.py,sha256=nbhMnnX__1laq4vyXSxmks-sy76N2dq768PsF7BJXKY,17089 +pandas/core/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/tools/__pycache__/__init__.cpython-314.pyc,, +pandas/core/tools/__pycache__/datetimes.cpython-314.pyc,, +pandas/core/tools/__pycache__/numeric.cpython-314.pyc,, +pandas/core/tools/__pycache__/timedeltas.cpython-314.pyc,, +pandas/core/tools/__pycache__/times.cpython-314.pyc,, +pandas/core/tools/datetimes.py,sha256=WFt7IQzKo0dy7-Wc2JKEiOPep09kTb57xmEsqDnhIfM,56477 +pandas/core/tools/numeric.py,sha256=_KhJPq9E07dV70Wrog0QmRy3uTxcVrIUHkX-Xi6Ew84,11830 +pandas/core/tools/timedeltas.py,sha256=pofAREiKJPIlioRg2dNM7jMX2PdCnii-52OcVMEgYUk,7328 +pandas/core/tools/times.py,sha256=jzIYF3PhQ4k8pKCxeVunXEqBuUTnPhVn4BJzdj0jN3o,4943 +pandas/core/util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/util/__pycache__/__init__.cpython-314.pyc,, +pandas/core/util/__pycache__/hashing.cpython-314.pyc,, +pandas/core/util/__pycache__/numba_.cpython-314.pyc,, +pandas/core/util/hashing.py,sha256=-26nMmDkavDDun94Rr9D6RGMPnIweQeGvlk649I3WjE,12664 +pandas/core/util/numba_.py,sha256=O63iCmDp4JVK7-Nmvkii-5AMNqWnbBzHOaplkSpjJRI,4269 +pandas/core/window/__init__.py,sha256=FbFEoJJNkKvAlsR4OO5i99QpOlwkGAyI9yqr4ZDeLko,450 +pandas/core/window/__pycache__/__init__.cpython-314.pyc,, +pandas/core/window/__pycache__/common.cpython-314.pyc,, +pandas/core/window/__pycache__/ewm.cpython-314.pyc,, +pandas/core/window/__pycache__/expanding.cpython-314.pyc,, +pandas/core/window/__pycache__/numba_.cpython-314.pyc,, +pandas/core/window/__pycache__/online.cpython-314.pyc,, +pandas/core/window/__pycache__/rolling.cpython-314.pyc,, +pandas/core/window/common.py,sha256=uDmYV6eDo_U378lmUvu7WnZtpR2lvRkfsG4YJpxA6wM,6787 +pandas/core/window/ewm.py,sha256=KriS-eosiy2aeIZXBYzl7Fb4rstjKHNaly78s6IZ2nI,41124 +pandas/core/window/expanding.py,sha256=vEZUHzQcEN5Emsn7-MdLDjyUG8Qj7O_4SrPGpIXqVHU,47540 +pandas/core/window/numba_.py,sha256=TtLuNud6e6T3t1F_YU7cTsODci-xINusxGOGWtnyN1U,10835 +pandas/core/window/online.py,sha256=HZPdXDqAJgBaU1vE3jfMR-LOdxOptG7WENr5paDyulg,4165 +pandas/core/window/rolling.py,sha256=-bEaCKEMxort_Jia8jZYZ4qL4op3i1taiKSx41zvnk0,120047 +pandas/errors/__init__.py,sha256=ra71S7jtYg4xtLpcLHg78vEC3dRSwPm6TlB2qP_txlg,35610 +pandas/errors/__pycache__/__init__.cpython-314.pyc,, +pandas/errors/__pycache__/cow.cpython-314.pyc,, +pandas/errors/cow.py,sha256=uWWrk6unzGD58tdpZK-zz20Iy_dZ47gyN7AzsU31nSc,2147 +pandas/io/__init__.py,sha256=Q1gCoXMCnbUHZxFo7xbUmQbB4g1ySkrXkCm26Jf4xwM,292 +pandas/io/__pycache__/__init__.cpython-314.pyc,, +pandas/io/__pycache__/_util.cpython-314.pyc,, +pandas/io/__pycache__/api.cpython-314.pyc,, +pandas/io/__pycache__/clipboards.cpython-314.pyc,, +pandas/io/__pycache__/common.cpython-314.pyc,, +pandas/io/__pycache__/feather_format.cpython-314.pyc,, +pandas/io/__pycache__/html.cpython-314.pyc,, +pandas/io/__pycache__/iceberg.cpython-314.pyc,, +pandas/io/__pycache__/orc.cpython-314.pyc,, +pandas/io/__pycache__/parquet.cpython-314.pyc,, +pandas/io/__pycache__/pickle.cpython-314.pyc,, +pandas/io/__pycache__/pytables.cpython-314.pyc,, +pandas/io/__pycache__/spss.cpython-314.pyc,, +pandas/io/__pycache__/sql.cpython-314.pyc,, +pandas/io/__pycache__/stata.cpython-314.pyc,, +pandas/io/__pycache__/xml.cpython-314.pyc,, +pandas/io/_util.py,sha256=kAq0CpYEwmIaFPzN2-fHFAE5EQp7Nb42aRpNVmejEEA,13476 +pandas/io/api.py,sha256=inNGQ7iKk-dnLeEGWZO2_8q9r9VbUADx15K0uRY8j28,1277 +pandas/io/clipboard/__init__.py,sha256=FCleFoG_TANtNf1P-p85FaaITubfxuZ6ZOTP4pU4fi0,24680 +pandas/io/clipboard/__pycache__/__init__.cpython-314.pyc,, +pandas/io/clipboards.py,sha256=ZJC2jPVkm3VchIlMjBei1nleoOTGJ0vmrSSE3rBnbmI,6621 +pandas/io/common.py,sha256=jaINQhUTtTwxEyqNeDxxjWU67QaX3qOVlvbwNFXZMuE,49485 +pandas/io/excel/__init__.py,sha256=XEr1lNxnxdf0Mt9eiWCmStxqbwqaaPrBDaVzNQrfLdU,486 +pandas/io/excel/__pycache__/__init__.cpython-314.pyc,, +pandas/io/excel/__pycache__/_base.cpython-314.pyc,, +pandas/io/excel/__pycache__/_calamine.cpython-314.pyc,, +pandas/io/excel/__pycache__/_odfreader.cpython-314.pyc,, +pandas/io/excel/__pycache__/_odswriter.cpython-314.pyc,, +pandas/io/excel/__pycache__/_openpyxl.cpython-314.pyc,, +pandas/io/excel/__pycache__/_pyxlsb.cpython-314.pyc,, +pandas/io/excel/__pycache__/_util.cpython-314.pyc,, +pandas/io/excel/__pycache__/_xlrd.cpython-314.pyc,, +pandas/io/excel/__pycache__/_xlsxwriter.cpython-314.pyc,, +pandas/io/excel/_base.py,sha256=cwfjyMWglTu6BYEkzPsN5e_9jWgqupoN645P_TcG_3A,76477 +pandas/io/excel/_calamine.py,sha256=fbw77fRPugmI2t4Eb7snZ9U00JPqfmayItf5LHQOAQE,4280 +pandas/io/excel/_odfreader.py,sha256=Wg7ASpYrIHLyaHbIcsm-hWAvGgsJPX8JWe06v80jkPA,9754 +pandas/io/excel/_odswriter.py,sha256=rVUaQJo2yFqn-Zs7KAhm-DLQYwdSdB6Blsm3voxwTBU,12029 +pandas/io/excel/_openpyxl.py,sha256=o2BOVE2KdcWrFMoKpraY4X7FxMSvd5oKt9V5V4ybKjU,25394 +pandas/io/excel/_pyxlsb.py,sha256=qDVnTpHYRB8JQ0OGtus7OIrAQBByaZ7Np3k0OgsmmDY,5380 +pandas/io/excel/_util.py,sha256=RlOEX39Tk2zCXEsXd6PFYaBCFl9WPsnWCn0DfIMFHI8,8429 +pandas/io/excel/_xlrd.py,sha256=QqI9GcA1YLsp7qZ-_46huf5oPYQrgQAejygOLGwxVqs,5536 +pandas/io/excel/_xlsxwriter.py,sha256=aqakc4B4J6j66slFE_11dXIMS-pJpLlVp_zcvSvvfm0,9446 +pandas/io/feather_format.py,sha256=1kRro8ZaSdxVQ-U1KLEBXV0h2L1sgbBCNK-PwP_qJXE,6904 +pandas/io/formats/__init__.py,sha256=chUI3ziL_IxkmSVTJap9ome3pdLgN038xeeCAJ7HLVc,237 +pandas/io/formats/__pycache__/__init__.cpython-314.pyc,, +pandas/io/formats/__pycache__/_color_data.cpython-314.pyc,, +pandas/io/formats/__pycache__/console.cpython-314.pyc,, +pandas/io/formats/__pycache__/css.cpython-314.pyc,, +pandas/io/formats/__pycache__/csvs.cpython-314.pyc,, +pandas/io/formats/__pycache__/excel.cpython-314.pyc,, +pandas/io/formats/__pycache__/format.cpython-314.pyc,, +pandas/io/formats/__pycache__/html.cpython-314.pyc,, +pandas/io/formats/__pycache__/info.cpython-314.pyc,, +pandas/io/formats/__pycache__/printing.cpython-314.pyc,, +pandas/io/formats/__pycache__/string.cpython-314.pyc,, +pandas/io/formats/__pycache__/style.cpython-314.pyc,, +pandas/io/formats/__pycache__/style_render.cpython-314.pyc,, +pandas/io/formats/__pycache__/xml.cpython-314.pyc,, +pandas/io/formats/_color_data.py,sha256=fZ_QluvMFUNKUE4-T32x7Pn0nulQgxmsEMHB9URcBOY,4332 +pandas/io/formats/console.py,sha256=mHk4lOd7olsA-Cz5MvvwjhYEgRPnvtAnB8nlM8bAz6U,2811 +pandas/io/formats/css.py,sha256=h_mdPw29YvMP8Q6Ozi-6ifCaPuBqoxH4xgoQbhrqNgE,13924 +pandas/io/formats/csvs.py,sha256=W0dsc8eY94ZswBST3CPwP9ujkb-soeXdLV9YL6yaVuw,10793 +pandas/io/formats/excel.py,sha256=j8LIDUce5cHv9C25I4LD-NT15gpyikM65JPFemxT6To,35592 +pandas/io/formats/format.py,sha256=c3Rm2ezuFamFTmcBARuKQsjDbu9Ojct35rzwaIA3qHo,67817 +pandas/io/formats/html.py,sha256=x93sE_gwjU6QIpkwV4OwBRKBKuFrOXT8IbUoFE9sFBo,24671 +pandas/io/formats/info.py,sha256=AvGwPtlSMmkaxven4pESgfM1I25bTZ0GeNXNJ-Q8R8g,24503 +pandas/io/formats/printing.py,sha256=5jD26_zWmh0PnngjIRz3zsmHuzIQpr1XUnSbfwySgY0,20109 +pandas/io/formats/string.py,sha256=fofa0wqH6Y4dwdDT1hDcaF2O5R_sCF4eKj1hXT1qAdM,7556 +pandas/io/formats/style.py,sha256=3JS5-g34-bqfm3v_n5OK1rCmI0AExWtiihwJA6W8hps,181669 +pandas/io/formats/style_render.py,sha256=wXvOdrGB7m7R3mRTIntV0JAsknRkhAdwizl16p651wY,101196 +pandas/io/formats/templates/html.tpl,sha256=KA-w_npfnHM_1c5trtJtkd3OD9j8hqtoQAY4GCC5UgI,412 +pandas/io/formats/templates/html_style.tpl,sha256=_gCqktLyUGAo5TzL3I-UCp1Njj8KyeLCWunHz4nYHsE,694 +pandas/io/formats/templates/html_table.tpl,sha256=MJxwJFwOa4KNli-ix7vYAGjRzw59FLAmYKHMy9nC32k,1811 +pandas/io/formats/templates/latex.tpl,sha256=m-YMxqKVJ52kLd61CA9V2MiC_Dtwwa-apvU8YtH8TYU,127 +pandas/io/formats/templates/latex_longtable.tpl,sha256=opn-JNfuMX81g1UOWYFJLKdQSUwoSP_UAKbK4kYRph4,2877 +pandas/io/formats/templates/latex_table.tpl,sha256=YNvnvjtwYXrWFVXndQZdJqKFIXYTUj8f1YOUdMmxXmQ,2221 +pandas/io/formats/templates/string.tpl,sha256=Opr87f1tY8yp_G7GOY8ouFllR_7vffN_ok7Ndf98joE,344 +pandas/io/formats/templates/typst.tpl,sha256=4KPnaNFnqUmh6CPJMhlnAvutNZuGmK1pQQ3t6pgJwog,410 +pandas/io/formats/xml.py,sha256=oWn2nPqQUpAQuHhk03bmPE9SgBJDHhHUbjbA-BAwLN8,17432 +pandas/io/html.py,sha256=fGirtAUW6-LyP9mhVfalUEEOhq4UN7VRz2bpNHDWk5U,40426 +pandas/io/iceberg.py,sha256=baT93aPzXNFdn0t4wucbXplYbqENsq-ouE4J5s3bFnw,5324 +pandas/io/json/__init__.py,sha256=RVdWuAEVioOHPyC4Gr9YXHA3UWA4KJKKlYon8pZJITo,270 +pandas/io/json/__pycache__/__init__.cpython-314.pyc,, +pandas/io/json/__pycache__/_json.cpython-314.pyc,, +pandas/io/json/__pycache__/_normalize.cpython-314.pyc,, +pandas/io/json/__pycache__/_table_schema.cpython-314.pyc,, +pandas/io/json/_json.py,sha256=JHgU6i-Sa93ildp41QRQiHc-3RRa2AZnpzhmoaxCl68,66955 +pandas/io/json/_normalize.py,sha256=iyfhoJeuF-YF1RJ2enYr495AzORj8zYmZzn5Gh26Ats,21274 +pandas/io/json/_table_schema.py,sha256=DbaHpdHweilU7Ek9gmjixZn3NAp7BsG3d4hPBQ1Gszw,12369 +pandas/io/orc.py,sha256=Lq2XzKqUyfmplGBqIv69e6smRy4QI-qtc33DMILnPrg,9333 +pandas/io/parquet.py,sha256=UVAx4mk_XPJPRXx4iKoaAtJJunczLuZa3hW4FG2NP-k,28475 +pandas/io/parsers/__init__.py,sha256=7BLx4kn9y5ipgfZUWZ4y_MLEUNgX6MQ5DyDwshhJxVM,204 +pandas/io/parsers/__pycache__/__init__.cpython-314.pyc,, +pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-314.pyc,, +pandas/io/parsers/__pycache__/base_parser.cpython-314.pyc,, +pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-314.pyc,, +pandas/io/parsers/__pycache__/python_parser.cpython-314.pyc,, +pandas/io/parsers/__pycache__/readers.cpython-314.pyc,, +pandas/io/parsers/arrow_parser_wrapper.py,sha256=GfiIatThPYvFpE8aYwxlgAJSrTEg78zwS7zxTgB0Els,26912 +pandas/io/parsers/base_parser.py,sha256=XMFBQpxw6IGmpZ11cLsxeyIGs0p5qOi38jHb1xV2Xa4,33496 +pandas/io/parsers/c_parser_wrapper.py,sha256=cy1h31GMBgkZcFczpIZ4Ft2FifAo1av1AY5BlYfO6Ao,20705 +pandas/io/parsers/python_parser.py,sha256=BWUXc7XWmkpWBPV5-psno_mIJhb35cuiRiIPftrgiLA,58730 +pandas/io/parsers/readers.py,sha256=dFPDSWEB9bUV2Xv4ztTnoj6NyFekKxDWekXzbzVgfBw,144926 +pandas/io/pickle.py,sha256=NjYhK-ckY3nNE7mgteJK_XpiptSBv4rsgpae2kSjBzs,9618 +pandas/io/pytables.py,sha256=HYDb9YY2fjbPcp-BAq1dta9kiadiV10dVrQhLDqNUbw,243100 +pandas/io/sas/__init__.py,sha256=AIAudC9f784kcEzuho8GiXU63vj2ThRitKznl7Imkq4,69 +pandas/io/sas/__pycache__/__init__.cpython-314.pyc,, +pandas/io/sas/__pycache__/sas7bdat.cpython-314.pyc,, +pandas/io/sas/__pycache__/sas_constants.cpython-314.pyc,, +pandas/io/sas/__pycache__/sas_xport.cpython-314.pyc,, +pandas/io/sas/__pycache__/sasreader.cpython-314.pyc,, +pandas/io/sas/sas7bdat.py,sha256=TIiudy-ty2K8lie38QWIs-_b2dGISPCfDIIPukirCH8,45788 +pandas/io/sas/sas_constants.py,sha256=cDtiAQroSs4KS9FKSvoS5aUYdmbmLN9KeO-4J3F-q2o,10310 +pandas/io/sas/sas_xport.py,sha256=eH2t8gPhBHb8zp3heNmHME3Kr-9GlCXF9WcX71hiBAM,16480 +pandas/io/sas/sasreader.py,sha256=VrhLnmyVU_afseBBukUTxDnTaF3ewL_tKyEPRlVUOHA,7117 +pandas/io/spss.py,sha256=iEWbRgxvMRtCKC5KNOmrPe63Ds-NzIKyuKUUMK81408,3061 +pandas/io/sql.py,sha256=y3F7IleLXaMq-fTzPH9jCZcnvHCp45yd1YkZrXn4298,110040 +pandas/io/stata.py,sha256=bfS91ofcI5eQELplTukBzdrU3BeSwJ_i1_xpMhMr94I,148776 +pandas/io/xml.py,sha256=wjJfGHsgXwLIKvlL5fGgD5D8DYrV8GKCG4aJeNvCflE,42324 +pandas/plotting/__init__.py,sha256=EpCQRlt1yUZEdqTLwXktnDi7brJY7jpg6BzZiK4Ou4I,2407 +pandas/plotting/__pycache__/__init__.cpython-314.pyc,, +pandas/plotting/__pycache__/_core.cpython-314.pyc,, +pandas/plotting/__pycache__/_misc.cpython-314.pyc,, +pandas/plotting/_core.py,sha256=HwwD0WQn33dZeXnv0qhty0SObJ8Pqn2Hc4i84gN6-Nw,91691 +pandas/plotting/_matplotlib/__init__.py,sha256=kt_h14Dlhyyfjy4_hUYmQBnYCxocknZoEPDi2Jg8tgs,2054 +pandas/plotting/_matplotlib/__pycache__/__init__.cpython-314.pyc,, +pandas/plotting/_matplotlib/__pycache__/boxplot.cpython-314.pyc,, +pandas/plotting/_matplotlib/__pycache__/converter.cpython-314.pyc,, +pandas/plotting/_matplotlib/__pycache__/core.cpython-314.pyc,, +pandas/plotting/_matplotlib/__pycache__/groupby.cpython-314.pyc,, +pandas/plotting/_matplotlib/__pycache__/hist.cpython-314.pyc,, +pandas/plotting/_matplotlib/__pycache__/misc.cpython-314.pyc,, +pandas/plotting/_matplotlib/__pycache__/style.cpython-314.pyc,, +pandas/plotting/_matplotlib/__pycache__/timeseries.cpython-314.pyc,, +pandas/plotting/_matplotlib/__pycache__/tools.cpython-314.pyc,, +pandas/plotting/_matplotlib/boxplot.py,sha256=FNs4y9vxkwjgRqJkZofmk-vm_wbAvWvobJP-f0lKBr4,18072 +pandas/plotting/_matplotlib/converter.py,sha256=M_gteqHbt7-NcM-QB8YaCACWDnvBHZfuz9vebQybo1w,42327 +pandas/plotting/_matplotlib/core.py,sha256=-efve08ih2QfuqhApAlhQKzmIpWle8xc0XhEqVeInqA,85018 +pandas/plotting/_matplotlib/groupby.py,sha256=kJAESSTkTkhO_GVfT6O3BIENBv_nJPPLQ6HcsXdBRlM,4363 +pandas/plotting/_matplotlib/hist.py,sha256=z0LYg48YJIK8BCWSpBDVorZofpNcdfsea9DaP8LBkII,16926 +pandas/plotting/_matplotlib/misc.py,sha256=Yvz5Pesx9dEquO9-ZKhG1Ov7U2TETFdJ6vlpbagVkEU,13353 +pandas/plotting/_matplotlib/style.py,sha256=I7H2zER0ep0a4N0LGjox_z87ZJemvad2oDsuuLuP_jE,8562 +pandas/plotting/_matplotlib/timeseries.py,sha256=APxMARwMFQn4g74tUirp0GQf4JaWNhXA2oGtsfvco-M,17426 +pandas/plotting/_matplotlib/tools.py,sha256=EMM-rA7kqEwfIdmeuzePs3CA4bcTYG1I36uOtXqD56Q,15649 +pandas/plotting/_misc.py,sha256=V-Y_Y31Fkh24i1Sk2koTy05IVzYniDc_pVvohs6SbA8,26637 +pandas/pyproject.toml,sha256=8E37VlzttRUmblNQCQTtjpXtC5wOICLMOgsoOseLHTg,22480 +pandas/testing.py,sha256=qJIhuQwaEy671kEAwnww5MuLzH6M6S92mp9Ptv_1xaY,312 +pandas/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/__pycache__/test_aggregation.cpython-314.pyc,, +pandas/tests/__pycache__/test_algos.cpython-314.pyc,, +pandas/tests/__pycache__/test_col.cpython-314.pyc,, +pandas/tests/__pycache__/test_common.cpython-314.pyc,, +pandas/tests/__pycache__/test_cpu.cpython-314.pyc,, +pandas/tests/__pycache__/test_downstream.cpython-314.pyc,, +pandas/tests/__pycache__/test_errors.cpython-314.pyc,, +pandas/tests/__pycache__/test_expressions.cpython-314.pyc,, +pandas/tests/__pycache__/test_flags.cpython-314.pyc,, +pandas/tests/__pycache__/test_multilevel.cpython-314.pyc,, +pandas/tests/__pycache__/test_nanops.cpython-314.pyc,, +pandas/tests/__pycache__/test_optional_dependency.cpython-314.pyc,, +pandas/tests/__pycache__/test_register_accessor.cpython-314.pyc,, +pandas/tests/__pycache__/test_sorting.cpython-314.pyc,, +pandas/tests/__pycache__/test_take.cpython-314.pyc,, +pandas/tests/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/api/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/api/__pycache__/test_api.cpython-314.pyc,, +pandas/tests/api/__pycache__/test_types.cpython-314.pyc,, +pandas/tests/api/test_api.py,sha256=V7rQOAmUUgLpKgzHNe2yxIXp-oYN0TRQdfcu2hk3Go4,16170 +pandas/tests/api/test_types.py,sha256=Ha3dacJvVFirO-e-7t6XTbj_lV66evw6fyIXWTiN5Yg,1708 +pandas/tests/apply/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/apply/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/apply/__pycache__/common.cpython-314.pyc,, +pandas/tests/apply/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/apply/__pycache__/test_frame_apply.cpython-314.pyc,, +pandas/tests/apply/__pycache__/test_frame_apply_relabeling.cpython-314.pyc,, +pandas/tests/apply/__pycache__/test_frame_transform.cpython-314.pyc,, +pandas/tests/apply/__pycache__/test_invalid_arg.cpython-314.pyc,, +pandas/tests/apply/__pycache__/test_numba.cpython-314.pyc,, +pandas/tests/apply/__pycache__/test_series_apply.cpython-314.pyc,, +pandas/tests/apply/__pycache__/test_series_apply_relabeling.cpython-314.pyc,, +pandas/tests/apply/__pycache__/test_series_transform.cpython-314.pyc,, +pandas/tests/apply/__pycache__/test_str.cpython-314.pyc,, +pandas/tests/apply/common.py,sha256=A8TqjvKR4h4WaLtovGR9hDULpWs4rV-1Jx_Q4Zz5Dew,298 +pandas/tests/apply/conftest.py,sha256=sfJircDctIdZtbihRb5fhZQ0eKryur6DED0wLgzKO4s,2024 +pandas/tests/apply/test_frame_apply.py,sha256=7UN3x2m2TneEG6zU2FSQSQW1zDCTmgWGi_6rZAlX-as,72782 +pandas/tests/apply/test_frame_apply_relabeling.py,sha256=3olJEWLodXn7qFCCCmiBYoB4OwlY2nUf2m0CsvkyX4s,4825 +pandas/tests/apply/test_frame_transform.py,sha256=hSX14yNMDZ3-BDi-P594u6yVGeZdM_hKktZvDYgwxf8,8431 +pandas/tests/apply/test_invalid_arg.py,sha256=nURlyMsgNuUHku7TvG-hNMV4pYGw9qiAQiK_zNxvVV4,10899 +pandas/tests/apply/test_numba.py,sha256=R2GiSWJXEa9Y4mKhI7wyqMmc6c09WPFjgLWYzJ1ThwU,4174 +pandas/tests/apply/test_series_apply.py,sha256=qHLqy2mqVYOQdLMS0YBUyKg1HrFDCmCLYcTiCgIFBHQ,22883 +pandas/tests/apply/test_series_apply_relabeling.py,sha256=AMKpxNA0r-YvExVkO7KxkfQX9OhF8Orz2LARZzAcqBc,1202 +pandas/tests/apply/test_series_transform.py,sha256=nTFeRZQWNg6ql92VNEOL5P2r1-nOkWw6RuW9cAAUWMY,2373 +pandas/tests/apply/test_str.py,sha256=K7N4NAFA29JZNwdce0AcdlTY4fO0QSeENhNNNFBlP5I,8853 +pandas/tests/arithmetic/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arithmetic/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/common.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_array_ops.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_bool.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_categorical.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_datetime64.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_interval.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_numeric.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_object.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_period.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_string.cpython-314.pyc,, +pandas/tests/arithmetic/__pycache__/test_timedelta64.cpython-314.pyc,, +pandas/tests/arithmetic/common.py,sha256=OC8X96huFmlnSZZu5OJ1UhJKmZ66UOkHur8Bdzo1ngI,4284 +pandas/tests/arithmetic/conftest.py,sha256=Oi2KVHlIAP6Wlp18jYUVDVqKp3dHoUY0dd4Yqo6Xvuw,3516 +pandas/tests/arithmetic/test_array_ops.py,sha256=K5_P3RAA6NOSK77HKvxWx6Ge3f5Cv8V8NOjHD-UlVN4,2639 +pandas/tests/arithmetic/test_bool.py,sha256=lnfCQWkJY4ufM_3NH4BgjugsA7_-r-Z1Pc-_F7G9IDg,757 +pandas/tests/arithmetic/test_categorical.py,sha256=se1tOR65CI9Yr-d7J1ZGkCOmev2Rc2AU3AjOv4HAXF4,725 +pandas/tests/arithmetic/test_datetime64.py,sha256=wKkiXJ1uS_Uml2jjwrrVHBA1vXFZjwBZKbX5TjUe6xQ,101338 +pandas/tests/arithmetic/test_interval.py,sha256=CzwSG46ve7uJ7_cWByOa4OVxKpXJ6nM-2zx56OFSMf4,11103 +pandas/tests/arithmetic/test_numeric.py,sha256=Wu_02RNN41L3PZ6ulGOBD0yStFi5eObEUi6OfN1kJFM,57426 +pandas/tests/arithmetic/test_object.py,sha256=1SNyek2WoqEVn7xbvbHJKzLIOxNNVtsaY2IvqWUFSpM,14935 +pandas/tests/arithmetic/test_period.py,sha256=W3btX3oszowkUrIAL4yIdBJbQ7c1fUwmhvy766n5C5o,59123 +pandas/tests/arithmetic/test_string.py,sha256=5o--4dc2FXprD_S-sOEG4mRn3Gct_L3Q_8nuMug3uZY,19970 +pandas/tests/arithmetic/test_timedelta64.py,sha256=IV8tqWDcs_claHtDReV6OxMnoBfqwrl0hRgpdIHen0U,98318 +pandas/tests/arrays/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/__pycache__/masked_shared.cpython-314.pyc,, +pandas/tests/arrays/__pycache__/test_array.cpython-314.pyc,, +pandas/tests/arrays/__pycache__/test_datetimelike.cpython-314.pyc,, +pandas/tests/arrays/__pycache__/test_datetimes.cpython-314.pyc,, +pandas/tests/arrays/__pycache__/test_ndarray_backed.cpython-314.pyc,, +pandas/tests/arrays/__pycache__/test_period.cpython-314.pyc,, +pandas/tests/arrays/__pycache__/test_timedeltas.cpython-314.pyc,, +pandas/tests/arrays/arrow/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/arrow/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/common.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_concat.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_conversion.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_datetimelike.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_dtype.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_function.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_groupby.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_ops.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_pickle.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_reductions.cpython-314.pyc,, +pandas/tests/arrays/arrow/__pycache__/test_string.cpython-314.pyc,, +pandas/tests/arrays/arrow/common.py,sha256=ha7GoiwQtrK2nFl65HKJPnk1BaU175R4892-dweYadw,579 +pandas/tests/arrays/arrow/conftest.py,sha256=6q-rh4r7QtkGin0WSjsS8bhNGUoDlwyNo2csDFH8dm8,4803 +pandas/tests/arrays/arrow/test_concat.py,sha256=6A3kpjY03gZWbRxr8Fjr4ZChTA2wogfVt5qYb27Wa0M,5030 +pandas/tests/arrays/arrow/test_conversion.py,sha256=0TJdlgPhsfT8ilik8gMnpNhQ_N2NesF-lDldyBN9Ghk,17570 +pandas/tests/arrays/arrow/test_datetimelike.py,sha256=q4vcVMUHnsJeFuooTxuyDqOGc0lsTgV6Rf4y2qQ-v1A,46602 +pandas/tests/arrays/arrow/test_dtype.py,sha256=U-DykfL0dHJ_LQrXN8O9Favh2JGgl1jn3rZsIIxwlAY,6368 +pandas/tests/arrays/arrow/test_function.py,sha256=O_MXUcIwp4EtXwSzBm9LdyAAXDFcoSMLqdYnOp-_Rqo,16141 +pandas/tests/arrays/arrow/test_groupby.py,sha256=BzHDeqg1JQTfoKwr-ZIo2Uv43fKi3uwG5Dr-77hI4mI,27103 +pandas/tests/arrays/arrow/test_indexing.py,sha256=v7kxF85cDJGdAEaPSwMa_7c_oSr5FkdQXWjmZuxJogU,22921 +pandas/tests/arrays/arrow/test_ops.py,sha256=cjQdWyUWqJummji1cD6f2Yp5s0mlbTdGkT6H2F6YflY,16964 +pandas/tests/arrays/arrow/test_pickle.py,sha256=MOiB42OFf1BWAWU52rmnRFeLXf2OzBfOLDWE0cKzhlc,1209 +pandas/tests/arrays/arrow/test_reductions.py,sha256=kXX5dduLOX0tHJkByqPgMbC6LBkGTTVB2OX8QaoRLzg,5534 +pandas/tests/arrays/arrow/test_string.py,sha256=sYIMGA6kbuyp6nCEGYe2ixdoEkSwrioAmsKOkWRThuI,36771 +pandas/tests/arrays/boolean/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/boolean/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_comparison.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_construction.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_function.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_logical.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_ops.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_reduction.cpython-314.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_repr.cpython-314.pyc,, +pandas/tests/arrays/boolean/test_arithmetic.py,sha256=M92HDEVkbyMf8PeZi4m4vDGCmpCvPE6v4M4W0PPxhe8,4299 +pandas/tests/arrays/boolean/test_astype.py,sha256=CWuoHBqqPdF9AqIYQ7_dtA87a1QOYlQbaRNKi_WMFIA,1849 +pandas/tests/arrays/boolean/test_comparison.py,sha256=37LaO6uUTdnH7KW3rTFrxOvaU16uBhmGTNaFEDYevoQ,1859 +pandas/tests/arrays/boolean/test_construction.py,sha256=S8AkB035aS8_1EHO70nvE1wqmPFAWRq79IQFU_33u6k,12614 +pandas/tests/arrays/boolean/test_function.py,sha256=eAVsu1XUeokLh7Ko0-bDNUQqmVrGAyOvv9vJdWCQj0M,4061 +pandas/tests/arrays/boolean/test_indexing.py,sha256=BorrK8_ZJbN5HWcIX9fCP-BbTCaJsgAGUiza5IwhYr4,361 +pandas/tests/arrays/boolean/test_logical.py,sha256=sBSx56okaj6zR2Dz7ULyQIOUlpWJiOgdLHBsTd7DCQk,10004 +pandas/tests/arrays/boolean/test_ops.py,sha256=iM_FRYMtvvdEpMtLUSuBd_Ww5nHr284v2fRxHaydvIM,975 +pandas/tests/arrays/boolean/test_reduction.py,sha256=rI9tiEAkFZ-HyKKqXvIfzNfQ84fVhq5YLbr8Ehm_NVg,2232 +pandas/tests/arrays/boolean/test_repr.py,sha256=RRljPIDi6jDNhUdbjKMc75Mst-wm92l-H6b5Y-lCCJA,437 +pandas/tests/arrays/categorical/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/categorical/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_algos.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_analytics.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_api.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_dtypes.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_map.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_missing.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_operators.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_replace.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_repr.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_sorting.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_subclass.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_take.cpython-314.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_warnings.cpython-314.pyc,, +pandas/tests/arrays/categorical/test_algos.py,sha256=vDKfu4nvTowYGlX3yIftUOjvqsEfDG3ZZdEMbMunvFM,2915 +pandas/tests/arrays/categorical/test_analytics.py,sha256=GGiT8M-gi5TdJ73NxfAhSKStQAsgf6GxYO55iZDyFI0,13444 +pandas/tests/arrays/categorical/test_api.py,sha256=9ds8QgATDhuXWg9WPe57Vc1_jcoidke7X3TkBMIoqns,20067 +pandas/tests/arrays/categorical/test_astype.py,sha256=aBBdW9uc-xmdQ8gzFJI7a-zhg3x7Xpx4ExFk8KS25mQ,6056 +pandas/tests/arrays/categorical/test_constructors.py,sha256=smzN3LK8FpRykn4-h0Xdn-5U3L8OTK12ZY8fMdF6hio,33754 +pandas/tests/arrays/categorical/test_dtypes.py,sha256=kj0AJ4gJZak1mI0y30QfA583ugYMMdyxjyEhG2k5gNg,6201 +pandas/tests/arrays/categorical/test_indexing.py,sha256=WMftstrMu4E8IO-V5enBDE1-n-LXnS3Iyh6gSDMBC6c,12793 +pandas/tests/arrays/categorical/test_map.py,sha256=HJiLnxcy1n9gYeQgMZbqFT2iuZ25-ui4kGIqYXaReQs,6266 +pandas/tests/arrays/categorical/test_missing.py,sha256=zfbf_KWbFjM7QZr23AKu9IVMO4So4b3-AVsSHVvUtn4,4851 +pandas/tests/arrays/categorical/test_operators.py,sha256=HMyHhiFb4muBdUpQrsFp62KywzD3Hdy55aEVrH4-zaY,16072 +pandas/tests/arrays/categorical/test_replace.py,sha256=aQ6otk2yfvL1xjUWPpOBEdwb0_ivJsry1gnWdniaAvo,3945 +pandas/tests/arrays/categorical/test_repr.py,sha256=-KevXeNWxNqz78qxWblvLtN7Jptv5ElE7_T8HS8ler0,34015 +pandas/tests/arrays/categorical/test_sorting.py,sha256=ERj4TYyp5NTBYzTANrO8-DDO6BNjrYAmtC37VxJBIf0,5060 +pandas/tests/arrays/categorical/test_subclass.py,sha256=z_Rihcg8zVQKQIeRmORdtlui9oP-tCKeDiERjaagx88,904 +pandas/tests/arrays/categorical/test_take.py,sha256=vctyw6ZeFsavUXqBbH7vRI-fibfi33Hn77EtbaZ7_0Q,3579 +pandas/tests/arrays/categorical/test_warnings.py,sha256=XqvGeAb9lrXP1VdwKSOvbDuytqDuJ5VSDsLKQAa5gIk,682 +pandas/tests/arrays/datetimes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/datetimes/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/datetimes/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/arrays/datetimes/__pycache__/test_cumulative.cpython-314.pyc,, +pandas/tests/arrays/datetimes/__pycache__/test_reductions.cpython-314.pyc,, +pandas/tests/arrays/datetimes/test_constructors.py,sha256=hJE8TqQsLnEUmumo9HYvPaKZIsHJPzT8w9tYQ-hs1is,6576 +pandas/tests/arrays/datetimes/test_cumulative.py,sha256=NCXerEX4MokNjsSU3e2tWVekWtCuhAy6GLqIbOOK6uA,1267 +pandas/tests/arrays/datetimes/test_reductions.py,sha256=42a-rD5f-F4SNFxB0iiH8GKRfSplo7Wm-eLgXG7pznA,5495 +pandas/tests/arrays/floating/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/floating/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/test_comparison.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/test_concat.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/test_construction.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/test_contains.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/test_function.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/test_repr.cpython-314.pyc,, +pandas/tests/arrays/floating/__pycache__/test_to_numpy.cpython-314.pyc,, +pandas/tests/arrays/floating/conftest.py,sha256=gDYuKNRevHwie7NDZ4QLnYxevt6sZxHWCi6oyIElYig,1069 +pandas/tests/arrays/floating/test_arithmetic.py,sha256=LYcdSlXg_hjHqKKNerY99Ci-iL3tV6gbcFd7ZDZKJcA,8673 +pandas/tests/arrays/floating/test_astype.py,sha256=EOcBIsfc44V7lUkNFQwqPnHSBtyEj38nhvNOStBbIcc,4337 +pandas/tests/arrays/floating/test_comparison.py,sha256=eV3cojE37nmhIKjUA086IrHngewcjxOAzpu1ZWc5OTs,2395 +pandas/tests/arrays/floating/test_concat.py,sha256=-RO-pwRRY93FQnOjBLs1fMVf7uBCoEGRkGWPAdX8ltU,573 +pandas/tests/arrays/floating/test_construction.py,sha256=2Wx3Vc6Y_-bBsyDVBQjX6UOjqnjdAMFtiBrtva3JWDE,7407 +pandas/tests/arrays/floating/test_contains.py,sha256=rKyb6MRgH3_mirazXcdpknLbwMkk1TJKozio8QEaFPY,824 +pandas/tests/arrays/floating/test_function.py,sha256=1qAicHj40NRodFWGG8Rw0XyHVn1EBUXa-2bK0X5eYIo,9271 +pandas/tests/arrays/floating/test_repr.py,sha256=N_BX7NbU8Pljiz2bouWMzrP22xh_6w_8pHePEB2ycVw,1157 +pandas/tests/arrays/floating/test_to_numpy.py,sha256=4qPRBKFguglyBCHFahd9-uYx7BE3A8Xmce1SKMS43U8,6282 +pandas/tests/arrays/integer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/integer/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/test_comparison.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/test_concat.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/test_construction.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/test_dtypes.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/test_function.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/test_reduction.cpython-314.pyc,, +pandas/tests/arrays/integer/__pycache__/test_repr.cpython-314.pyc,, +pandas/tests/arrays/integer/conftest.py,sha256=DzWpyqSXKVFJmXAxpUGnexmqDVsccXKr7YdAiWqfehI,1508 +pandas/tests/arrays/integer/test_arithmetic.py,sha256=whrs5Ro9KX9XoAxxt_hjjz8Fd_yczJcgW_sX7oKnt0Y,11126 +pandas/tests/arrays/integer/test_comparison.py,sha256=jUr8dmk_6FQsTNjDkYsazWnioHis4cLi94noy4txG54,1212 +pandas/tests/arrays/integer/test_concat.py,sha256=TmHNsCxxvp-KDLD5SaTmeEuWJDzUS51Eg04uSWet9Pg,2351 +pandas/tests/arrays/integer/test_construction.py,sha256=ivQqqgaONzpUBvxr7lzBUhZw1U_qYHtxxpXh3If0cgM,9643 +pandas/tests/arrays/integer/test_dtypes.py,sha256=FFqeQIUVMyPOwlw4pqbRAYYE89qA4dcOXNyl8b9bQ5Y,9396 +pandas/tests/arrays/integer/test_function.py,sha256=WM_iJaSEywbO1ZN2R3tQRANl0nijr7z7SEMT2uZYA8M,7359 +pandas/tests/arrays/integer/test_indexing.py,sha256=aVk3G9DUSd2jX11bYwF2AGo15H8nEfcYMFx6FlKeCdY,491 +pandas/tests/arrays/integer/test_reduction.py,sha256=PTX8VOo7Rs-iWHwnv0zLnrpr-OfhFPzgmrJ93o-XHSI,4954 +pandas/tests/arrays/integer/test_repr.py,sha256=fLTZusgFHPXO4orpygmHIOG6JQLzYcdbTJHRvvsN0sM,1652 +pandas/tests/arrays/interval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/interval/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/interval/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/arrays/interval/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/arrays/interval/__pycache__/test_interval.cpython-314.pyc,, +pandas/tests/arrays/interval/__pycache__/test_interval_pyarrow.cpython-314.pyc,, +pandas/tests/arrays/interval/__pycache__/test_overlaps.cpython-314.pyc,, +pandas/tests/arrays/interval/test_astype.py,sha256=cqHldw4YWb37lInCeRwWhdu1xcaN2Lf5JllmRUgRLhM,716 +pandas/tests/arrays/interval/test_formats.py,sha256=RgxzrQYmHX5b1CZ2tN2mNSppFJzzeOcXq5d7QPdKZsM,295 +pandas/tests/arrays/interval/test_interval.py,sha256=-P6HAUID--WzwLwbjbJNL6o-PXZNq8prlkkqRPOVKl0,10208 +pandas/tests/arrays/interval/test_interval_pyarrow.py,sha256=WB5z--cclXDUNc4bK1MPvrLcVHEzTJ3v52_yd6sZc9M,6033 +pandas/tests/arrays/interval/test_overlaps.py,sha256=CxmfkE45H7MxKeEtTZy2qg3rthp1WKi-5aRwbFpGDHY,4235 +pandas/tests/arrays/masked/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/masked/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/masked/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/arrays/masked/__pycache__/test_arrow_compat.cpython-314.pyc,, +pandas/tests/arrays/masked/__pycache__/test_function.cpython-314.pyc,, +pandas/tests/arrays/masked/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/arrays/masked/test_arithmetic.py,sha256=dIE0xRILQAVXwciCKehzjvjWOvICCMxXWsYXccgF6ho,8921 +pandas/tests/arrays/masked/test_arrow_compat.py,sha256=F_0Rfin3br3mxej1jaPgwxasjxhSKRbqDaA2M2GVsvk,7081 +pandas/tests/arrays/masked/test_function.py,sha256=9QZ1tDLwPklCVUUjOrD7eRHY3AAyjcXsJPaYpJbi5i4,12489 +pandas/tests/arrays/masked/test_indexing.py,sha256=MN5-XYWMlcqOzHiKFvcvKYpBD8rRXOqZoWSr8W2FFaI,6027 +pandas/tests/arrays/masked_shared.py,sha256=cRBGnGMOsN_8L6t1InE-BeCcQZhs3GrNuhCAh1L-8Eo,5195 +pandas/tests/arrays/numpy_/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/numpy_/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/numpy_/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/arrays/numpy_/__pycache__/test_numpy.cpython-314.pyc,, +pandas/tests/arrays/numpy_/test_indexing.py,sha256=-0lB-Mw-gzM4Mpe-SRCj-w4C6QxLfp3BH65U_DVULNY,1452 +pandas/tests/arrays/numpy_/test_numpy.py,sha256=8XzJUSZ0Ahai2XiqLD9BrKP1SKVgPNSi9ZKyItz3ioY,12726 +pandas/tests/arrays/period/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/period/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/period/__pycache__/test_arrow_compat.cpython-314.pyc,, +pandas/tests/arrays/period/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/arrays/period/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/arrays/period/__pycache__/test_reductions.cpython-314.pyc,, +pandas/tests/arrays/period/test_arrow_compat.py,sha256=K8BgEe5UKoWF4A6T9A7td909azRCNJqz3g7_HNWSgZU,3329 +pandas/tests/arrays/period/test_astype.py,sha256=cm8t0aTC4S7tvOtp6FrxSZjskW9q634MQxGvLDX9oSk,2348 +pandas/tests/arrays/period/test_constructors.py,sha256=3Jxxp3IHfkueNTuIZwNpy4tVWM3OQ6T8RP8O-QGjmvU,11155 +pandas/tests/arrays/period/test_reductions.py,sha256=P_1IExzkvlMkTfkRKHYPb0m_ohEJepoMkFLt0hpDIjY,953 +pandas/tests/arrays/sparse/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/sparse/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_accessor.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_arithmetics.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_array.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_combine_concat.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_dtype.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_libsparse.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_reductions.cpython-314.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_unary.cpython-314.pyc,, +pandas/tests/arrays/sparse/test_accessor.py,sha256=VvoZbV_KLIasYvwpnd8ypvOvYqrWbOG1MypoX0y029c,10190 +pandas/tests/arrays/sparse/test_arithmetics.py,sha256=j5vMyx_tmVp9wbUtG83aTURvY5fR-C29OQ5GADxTB-U,45136 +pandas/tests/arrays/sparse/test_array.py,sha256=HIjibH-dJqkFdC9jMYDJ00AB9A4Q7DgC8LRfMtSREEs,44086 +pandas/tests/arrays/sparse/test_astype.py,sha256=P4yaukUxlIddtF7rkxfDmqZr3wchjz8ma2FvGmzwnrg,17255 +pandas/tests/arrays/sparse/test_combine_concat.py,sha256=tdyPuy2xzZ6tVRZnSuV3klwmylMBapC4h9GtQNW4hhY,4334 +pandas/tests/arrays/sparse/test_constructors.py,sha256=ZainMNTRbrX88uIbi2427t2RLTbIsodqA3tD-j7opQ8,16737 +pandas/tests/arrays/sparse/test_dtype.py,sha256=D-ndnI2Lj_GeVkT6U5ayofOVXJ0TIJGmmFErOiPiIrw,9889 +pandas/tests/arrays/sparse/test_indexing.py,sha256=_RuTo8jDXJuifSVtSO4Ci-LRnlsrI6f3VJr_t5yeX3U,21822 +pandas/tests/arrays/sparse/test_libsparse.py,sha256=I7vRNwPYiI8oi_6027zMfXoanF2OtVTT94gzVC3JwEM,19043 +pandas/tests/arrays/sparse/test_reductions.py,sha256=HSE7-nYrB5kjOp1TLoJh7C-YkqrxHczvdYAhN1XYmRw,40037 +pandas/tests/arrays/sparse/test_unary.py,sha256=0ncXzR4SBbStZn9ALI_14I3aZ28UtKRhy56I1XXgDac,2777 +pandas/tests/arrays/string_/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/string_/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/string_/__pycache__/test_concat.cpython-314.pyc,, +pandas/tests/arrays/string_/__pycache__/test_string.cpython-314.pyc,, +pandas/tests/arrays/string_/__pycache__/test_string_arrow.cpython-314.pyc,, +pandas/tests/arrays/string_/test_concat.py,sha256=sMjBRMxHK6G8m83t-CEzA8a7eR05wa-F47xl8TjhVhQ,2648 +pandas/tests/arrays/string_/test_string.py,sha256=GEjB7w3YcgBQ-20rE7vOC9obxgznWH0WLFEzKaQje1U,23847 +pandas/tests/arrays/string_/test_string_arrow.py,sha256=dSiCAs_ksdVHCfH1h-dGoy5rNTuuvKkwmcURJhnCnvc,12274 +pandas/tests/arrays/test_array.py,sha256=WIF8AnbetAE1oQH6MW4rpRqZDay9jew5AkRpEc9Qtdw,23905 +pandas/tests/arrays/test_datetimelike.py,sha256=Ux-PXnQvD7beXBK6Ziwzz_LgfCtFffR8gaAnc7Q6mNg,50844 +pandas/tests/arrays/test_datetimes.py,sha256=_o8rbJ7pHn5WOO3dZXHfAxinM8YUu7nUKn6gEAaeT4s,31529 +pandas/tests/arrays/test_ndarray_backed.py,sha256=P5WwUxi8jbuGo-uT6MlRdl12ATNPtWs7sOexKIuy74I,3395 +pandas/tests/arrays/test_period.py,sha256=dGMfL6rFUoVesEKHY0dV8WDKfxqjIfK4qXc-L6jtqLc,6043 +pandas/tests/arrays/test_timedeltas.py,sha256=5t0SMlEswO5dBf6iGyeq6dRvd0eevSye54vfJuMSIAo,13612 +pandas/tests/arrays/timedeltas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/timedeltas/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/arrays/timedeltas/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/arrays/timedeltas/__pycache__/test_cumulative.cpython-314.pyc,, +pandas/tests/arrays/timedeltas/__pycache__/test_reductions.cpython-314.pyc,, +pandas/tests/arrays/timedeltas/test_constructors.py,sha256=RojocsP1BQH6eGbgusaw0o1r3WT5Bi5gAZjPtAgzU-I,4636 +pandas/tests/arrays/timedeltas/test_cumulative.py,sha256=cRR6I-lIsefG95vEZb8TuXdvmw7pdPFedpBneLVKBG8,692 +pandas/tests/arrays/timedeltas/test_reductions.py,sha256=eX8RXckSgFWd2C4fBfjz0tdyzjH3KtSpiCKV0rrsVtE,6573 +pandas/tests/base/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/base/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/base/__pycache__/common.cpython-314.pyc,, +pandas/tests/base/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/base/__pycache__/test_conversion.cpython-314.pyc,, +pandas/tests/base/__pycache__/test_fillna.cpython-314.pyc,, +pandas/tests/base/__pycache__/test_misc.cpython-314.pyc,, +pandas/tests/base/__pycache__/test_transpose.cpython-314.pyc,, +pandas/tests/base/__pycache__/test_unique.cpython-314.pyc,, +pandas/tests/base/__pycache__/test_value_counts.cpython-314.pyc,, +pandas/tests/base/common.py,sha256=Uvc2UZvktf4WC0uywbQLJdYt79AYmqS_i6BzMjHxZaY,264 +pandas/tests/base/test_constructors.py,sha256=N787Dngz5f75lj7UJ36g5Th0Dpsk83sG2iT3JMyz4Eo,5859 +pandas/tests/base/test_conversion.py,sha256=1nCSAsFE4ITJsAJWe5c1NSglvF_4ax9jqh08OKBL3Ws,19384 +pandas/tests/base/test_fillna.py,sha256=rw8q3yEsw1-Tnw_HpDTTV03JHj0tYcBrGqqAAV5dmTQ,1872 +pandas/tests/base/test_misc.py,sha256=j5DwOZ7QQTx063HfStZMKsRbLt6duKxtoeRrDB3FfrA,6520 +pandas/tests/base/test_transpose.py,sha256=4xvr5oa5Jbk3FZnFjfgCp5uAbUJZeCKXWZPLxtTLf6A,1669 +pandas/tests/base/test_unique.py,sha256=JoaqSxCKeqs521gccxqKx1AtV1Fd00qLDNdN_Z1ejl8,6177 +pandas/tests/base/test_value_counts.py,sha256=AVaJK69DFUxyCO6OJj-jE8FmpTgen-xoVdx5WvOpGRk,14244 +pandas/tests/computation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/computation/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/computation/__pycache__/test_compat.cpython-314.pyc,, +pandas/tests/computation/__pycache__/test_eval.cpython-314.pyc,, +pandas/tests/computation/test_compat.py,sha256=gX0IqClglB8PQlbL9oGDiqCRwuH32fm3t-RFY_oraMo,6172 +pandas/tests/computation/test_eval.py,sha256=V5rcLbWL1_wj5lMor_ZjHmCzNLU_QOkcisZGNzaj9mE,78352 +pandas/tests/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/config/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/config/__pycache__/test_config.cpython-314.pyc,, +pandas/tests/config/__pycache__/test_localization.cpython-314.pyc,, +pandas/tests/config/test_config.py,sha256=4wb482Ii0Nv5LHaxu2a2TAmr039jqXYvbMzMzuncFg4,22456 +pandas/tests/config/test_localization.py,sha256=FHwnXyBEpuKTh_ENP0iKp7b5R_k9DLgllOoZd6sU5mQ,4828 +pandas/tests/construction/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/construction/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/construction/__pycache__/test_extract_array.cpython-314.pyc,, +pandas/tests/construction/test_extract_array.py,sha256=gvinGeTI34FElugtSp6h3hi1aNqk-ZS-wb0jxuas-ss,635 +pandas/tests/copy_view/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/copy_view/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_array.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_chained_assignment_deprecation.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_clip.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_copy_deprecation.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_core_functionalities.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_functions.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_internals.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_interp_fillna.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_methods.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_replace.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_setitem.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/test_util.cpython-314.pyc,, +pandas/tests/copy_view/__pycache__/util.cpython-314.pyc,, +pandas/tests/copy_view/index/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/copy_view/index/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/copy_view/index/__pycache__/test_datetimeindex.cpython-314.pyc,, +pandas/tests/copy_view/index/__pycache__/test_index.cpython-314.pyc,, +pandas/tests/copy_view/index/__pycache__/test_intervalindex.cpython-314.pyc,, +pandas/tests/copy_view/index/__pycache__/test_periodindex.cpython-314.pyc,, +pandas/tests/copy_view/index/__pycache__/test_timedeltaindex.cpython-314.pyc,, +pandas/tests/copy_view/index/test_datetimeindex.py,sha256=sD7JGO1CpsmpA355i8ud_E0p0N3A8qxLxN825kL4Lm8,2511 +pandas/tests/copy_view/index/test_index.py,sha256=hGuToZphP5xxsAo8tK4N3YPWlpXTi4D3vy542Io9Tcw,9614 +pandas/tests/copy_view/index/test_intervalindex.py,sha256=VLWa_d37Bsr7JHzjB9eKKWZZQ5bojxBxHBQyzWhci7Q,842 +pandas/tests/copy_view/index/test_periodindex.py,sha256=xr5cXzB37BgORa4f1zYY7g1VN5JbrzYc6gTXKnxpPlw,1200 +pandas/tests/copy_view/index/test_timedeltaindex.py,sha256=5H95QSZuJKB5hXP6QDlGlYd8oFKt2zI2lH0eRzmB-NU,1408 +pandas/tests/copy_view/test_array.py,sha256=lqa0j7Awy-390W7-rOiF3axZeGsULnnWzJ9ePX96078,6838 +pandas/tests/copy_view/test_astype.py,sha256=OVohv9cdSzBhOEbyM-bvNkWp43BsDfzXcWW7w1IF2Ns,8760 +pandas/tests/copy_view/test_chained_assignment_deprecation.py,sha256=jiJ4ajfxN7SusK6RePhRVNaijdzA3sUXTZauC-rxoW0,3841 +pandas/tests/copy_view/test_clip.py,sha256=k_6Lfjzz43kShvuGMOfhVN5UeSmEruUk2cbYx8HPtOo,1937 +pandas/tests/copy_view/test_constructors.py,sha256=ZwIKhpvCH0347jbpsTUpH8723R43P8iktNXL5pArQBw,13645 +pandas/tests/copy_view/test_copy_deprecation.py,sha256=S-WqfWDVoTxfMNGtspAo-WRYNwqVPyyS6Nus1NhMPEQ,3097 +pandas/tests/copy_view/test_core_functionalities.py,sha256=nSzlbXK0vpcFUkHaS30082GmZtqr2BDv9W0AELtTUrw,2911 +pandas/tests/copy_view/test_functions.py,sha256=8v0-9mKDQiY-eJ3Jh3p6bmrsQAF6n0yoe2_DDBfROZM,12386 +pandas/tests/copy_view/test_indexing.py,sha256=OqAIEdSGTXNLYEt_wOW7wx2eXcZ7EU17ZgAyJHAcmF8,28386 +pandas/tests/copy_view/test_internals.py,sha256=5rmBXRldK7iN5A3b2bIfA_Ov4G2LPPoNP1pwvw_snNE,3573 +pandas/tests/copy_view/test_interp_fillna.py,sha256=_Voah6CIhdKAUwnBvOhLu1r8XEPj3wHJ6v4UNN70dHc,10553 +pandas/tests/copy_view/test_methods.py,sha256=q7rS9etkePZ565G4HvVk1iQJpPSo_zATi4zAbQ4nwA0,54766 +pandas/tests/copy_view/test_replace.py,sha256=0783KSioPWH9gNj4MyAp_Wts4NeqJR68v6xkbYYU_Uo,17473 +pandas/tests/copy_view/test_setitem.py,sha256=qj_jsrU9wP1-qJsBRcfdjim67XuawKKlOZPFqSSgC5s,4160 +pandas/tests/copy_view/test_util.py,sha256=muZ5ZpeWC442WiFZnTxl6pB1YditthTN0lOb_FKqTsU,382 +pandas/tests/copy_view/util.py,sha256=0fIv9Iyt5guual2ORaf_Ee3WQ8SEE1WP9qUleHFYDmY,865 +pandas/tests/dtypes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/dtypes/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/dtypes/__pycache__/test_common.cpython-314.pyc,, +pandas/tests/dtypes/__pycache__/test_concat.cpython-314.pyc,, +pandas/tests/dtypes/__pycache__/test_dtypes.cpython-314.pyc,, +pandas/tests/dtypes/__pycache__/test_generic.cpython-314.pyc,, +pandas/tests/dtypes/__pycache__/test_inference.cpython-314.pyc,, +pandas/tests/dtypes/__pycache__/test_missing.cpython-314.pyc,, +pandas/tests/dtypes/cast/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/dtypes/cast/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_box_unbox.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_can_hold_element.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_construct_from_scalar.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_construct_ndarray.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_construct_object_arr.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_dict_compat.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_downcast.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_find_common_type.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_infer_datetimelike.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_infer_dtype.cpython-314.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_promote.cpython-314.pyc,, +pandas/tests/dtypes/cast/test_box_unbox.py,sha256=GYvZbbf0xYhlNJnAf2IU-n5CbMW44B8xvYal49gxk2A,3695 +pandas/tests/dtypes/cast/test_can_hold_element.py,sha256=lKiw29N6HVOHJ780exMpaP4GURHKDvBg1cwLqqe03gc,5549 +pandas/tests/dtypes/cast/test_construct_from_scalar.py,sha256=Rbh8ixOfKy2vRwSBcPOvjeVd2iPNz5crfnWn2XK5aEs,1754 +pandas/tests/dtypes/cast/test_construct_ndarray.py,sha256=D52osZAHEuY2w3GdzH05y9WD_ghLIySgfKaIJpnLZAw,1316 +pandas/tests/dtypes/cast/test_construct_object_arr.py,sha256=eOmUu4q0ihGTbYpCleoCnYtvwh1TBCEZQQjLeJaUMNA,717 +pandas/tests/dtypes/cast/test_dict_compat.py,sha256=LfYHgMtwlkkFulhfiYvhUkq4YE5Bj9884t_ndXlMIeM,473 +pandas/tests/dtypes/cast/test_downcast.py,sha256=GH_qMXvOknx7OfuRwrGh0L72yyDOD3jQvxYlWdQFJ0o,4660 +pandas/tests/dtypes/cast/test_find_common_type.py,sha256=sGakd4hcasN_LWvHv-QwY8_ndiAODEM1rLDM39eZzdc,5964 +pandas/tests/dtypes/cast/test_infer_datetimelike.py,sha256=hoTq7rOjTrZkZNQOgvWUoNcQj2RFmmtld8691Z59xZw,570 +pandas/tests/dtypes/cast/test_infer_dtype.py,sha256=y67wNgwLZiq3zRJer7PIQyOOanXG6BJaqy0ECEO_AtE,6025 +pandas/tests/dtypes/cast/test_promote.py,sha256=_n5llT2cDg6V2nC4ryq671cWWzGkW-pA00fhojcxaHM,20779 +pandas/tests/dtypes/test_common.py,sha256=VtU8qLFHtEkGjewn1QTAU9P0DcyIJg8cGUsHqVuWkJw,30897 +pandas/tests/dtypes/test_concat.py,sha256=QkDfYIyZvALvaCX1M3Bpy0jz-0GKbtp-w-FwoQH76R0,2072 +pandas/tests/dtypes/test_dtypes.py,sha256=CGCXJj9Y7L95AFlqURrlGwSufM4bd9I6Yoey3MYOYVE,45212 +pandas/tests/dtypes/test_generic.py,sha256=CK4oZubxCE4kOaOWtalRt_n_glMFV4QNskNVwQs9oi8,4794 +pandas/tests/dtypes/test_inference.py,sha256=LajQR0pP4OBUSZYUrxDz9Jh7AxQBuclOPc_2mMJAKJA,79541 +pandas/tests/dtypes/test_missing.py,sha256=gRo3xIKPGsc1NeUSK4z_TiJ-rvwUbzU5VRpVd3kD22o,31640 +pandas/tests/extension/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/extension/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/extension/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_arrow.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_categorical.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_common.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_datetime.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_extension.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_interval.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_masked.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_numpy.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_period.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_sparse.cpython-314.pyc,, +pandas/tests/extension/__pycache__/test_string.cpython-314.pyc,, +pandas/tests/extension/array_with_attr/__init__.py,sha256=bXkwWSW6GRX8Xw221iMyaQOQVaWmyuRP3tGhvjXtiV8,149 +pandas/tests/extension/array_with_attr/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/extension/array_with_attr/__pycache__/array.cpython-314.pyc,, +pandas/tests/extension/array_with_attr/__pycache__/test_array_with_attr.cpython-314.pyc,, +pandas/tests/extension/array_with_attr/array.py,sha256=_C4NxQhPjuK6JLPrf6HKFDLdXRQnTG9OTU5dR3uyw3w,2481 +pandas/tests/extension/array_with_attr/test_array_with_attr.py,sha256=TuuBA1lCxjVOgWsWM9jhgc-PyGuXzajO3UWWKZEquZA,1373 +pandas/tests/extension/base/__init__.py,sha256=G-HBRW2r_8R4qZtFwijBtvSnc3SNkikrH5By4VkSz7E,2960 +pandas/tests/extension/base/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/accumulate.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/base.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/casting.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/constructors.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/dim2.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/dtype.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/getitem.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/groupby.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/index.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/interface.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/io.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/methods.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/missing.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/ops.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/plotting.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/printing.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/reduce.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/reshaping.cpython-314.pyc,, +pandas/tests/extension/base/__pycache__/setitem.cpython-314.pyc,, +pandas/tests/extension/base/accumulate.py,sha256=JHnjvzM2WPD93_WXeay6efj1Pr1vso0llfr5RvQFdAI,1501 +pandas/tests/extension/base/base.py,sha256=aSfTPvuvzzQUxEIrGUASWuwcVv6Uw5bvkFXvqjhRV1M,35 +pandas/tests/extension/base/casting.py,sha256=_w7J_Hpw-CiJcDyuppEtk7ECPgZ1_OrmaHhJ6TtgRPY,3254 +pandas/tests/extension/base/constructors.py,sha256=EfQrYciCho5LOAAxbNOlIuneBnASOkoYiYqGe6t5AWw,5623 +pandas/tests/extension/base/dim2.py,sha256=j4x3g1PZS4-XsK2g-PdMnUeubm3evI1tSD1YznyyQqE,12349 +pandas/tests/extension/base/dtype.py,sha256=e-juPziIeeg11WBHRmAa_zVi5fe-NhMKsiM1kSW--OA,4005 +pandas/tests/extension/base/getitem.py,sha256=2xCQGFomHftxHnHAswYO84TFbR-Hto1Vc3uBVBhcGlY,16942 +pandas/tests/extension/base/groupby.py,sha256=AKRTAiBTBQB4r2Ty-nGL_qyuWkt72zSTDEF8tE6chrg,6544 +pandas/tests/extension/base/index.py,sha256=TkBotnkl4bzF99PUaBQDQgzZTJTeOW1J8J6lEjLnNNA,518 +pandas/tests/extension/base/interface.py,sha256=g2FJTBDlTH1cdut4xHxZlEJ5eWgjv4vDp_mWHZcVOcs,6929 +pandas/tests/extension/base/io.py,sha256=GKIjiAhtPXOJVDTuXmVU5O76CFKYkp_yQrQTKh1cpMw,1474 +pandas/tests/extension/base/methods.py,sha256=zSyjOIvI_w74wamuCcS43idGv2XKRyCOSn8JyFhvLT4,36529 +pandas/tests/extension/base/missing.py,sha256=bE-DftLXyn8vKYvffo8ee2wQv-Ko-ZfiSME_2tHjI9w,7420 +pandas/tests/extension/base/ops.py,sha256=Jp8zZPkbZ4l_FntTAd_ogGdJBXjLTvWhxdEk2Em8cdc,12669 +pandas/tests/extension/base/plotting.py,sha256=vA9kpi4eIIPhEcl-cuiI3XmyaTNEBxvJp1ouZL6X314,4650 +pandas/tests/extension/base/printing.py,sha256=cNghjo7KwrNv4Atd729LQazrOd8cs3P4DOk7a80HCTk,1110 +pandas/tests/extension/base/reduce.py,sha256=NMdAaJbsa-ksZI_h3gXsTvyIFoSUkrToOqN8pcPxdz0,7722 +pandas/tests/extension/base/reshaping.py,sha256=A3Fdz2pDhdKxrew1jORQg29_Sh3Q7DEV7qF-Ovr9RUQ,14477 +pandas/tests/extension/base/setitem.py,sha256=MU2wknANmtbQaSCqPr6z_Owz_26g8l7RIQjq6MqKVek,18269 +pandas/tests/extension/conftest.py,sha256=w8063D56wOb2hmCT92GdoJHYbOmW67aRZ-ncery49hc,6233 +pandas/tests/extension/date/__init__.py,sha256=-pIaBe_vmgnM_ok6T_-t-wVHetXtNw30SOMWVWNDqLI,118 +pandas/tests/extension/date/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/extension/date/__pycache__/array.cpython-314.pyc,, +pandas/tests/extension/date/array.py,sha256=qB0TYgZ91bVYRE0qp6zE_930uf2e7HqGMnIryFCRqj8,6184 +pandas/tests/extension/decimal/__init__.py,sha256=Dv6omEVqBNzcg5SDDhX_cyzt8wYjq3NbuSvmmHzoq8A,191 +pandas/tests/extension/decimal/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/extension/decimal/__pycache__/array.cpython-314.pyc,, +pandas/tests/extension/decimal/__pycache__/test_decimal.cpython-314.pyc,, +pandas/tests/extension/decimal/array.py,sha256=4yWeGqMK4mlInaOaKqvlLtSt2LgK-sTYAGbjxe3TD-s,10030 +pandas/tests/extension/decimal/test_decimal.py,sha256=jwpnnYCKQYFoK21CrFFVdImDkLzS5kWXI2jVDzBSgJo,16241 +pandas/tests/extension/json/__init__.py,sha256=JvjCnVMfzIUSoHKL-umrkT9H5T8J3Alt8-QoKXMSB4I,146 +pandas/tests/extension/json/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/extension/json/__pycache__/array.cpython-314.pyc,, +pandas/tests/extension/json/__pycache__/test_json.cpython-314.pyc,, +pandas/tests/extension/json/array.py,sha256=-zDshhlWjstv07yDxNiNB6Yny5U6bxfrBcPYZ_ER5T0,9410 +pandas/tests/extension/json/test_json.py,sha256=Jx2Vs5rFxpuCYRho4RKMdr1naObnq34vwOrFaELaMIc,18634 +pandas/tests/extension/list/__init__.py,sha256=FlpTrgdAMl_5puN2zDjvdmosw8aTvaCD-Hi2GtIK-k0,146 +pandas/tests/extension/list/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/extension/list/__pycache__/array.cpython-314.pyc,, +pandas/tests/extension/list/__pycache__/test_list.cpython-314.pyc,, +pandas/tests/extension/list/array.py,sha256=wwIDGwpkBPPtfhd6fol2NiK9Hn0b0QYfFrBcZVawoEs,3973 +pandas/tests/extension/list/test_list.py,sha256=-RHIcoqYfZ6f6XJuKlFxthInoJDKDJg7HJSDpy95msk,1072 +pandas/tests/extension/test_arrow.py,sha256=3GyYvuColA8PLPFV2kAZaYyGKP-4HnNFLD5JWc43Z6o,39395 +pandas/tests/extension/test_categorical.py,sha256=lWDr8bp_QkPVZUDuTo9_froO-utfOyX6elaT1mazFH4,6742 +pandas/tests/extension/test_common.py,sha256=kaG_5luKu6f1p0WCcs4xzQZ7U1gCWqbf8KQUkyW2to8,3071 +pandas/tests/extension/test_datetime.py,sha256=RudGxEqFwIjGV3iY3SotNNWQxMuTibTymmewJo3oL38,5768 +pandas/tests/extension/test_extension.py,sha256=wF8q3HwXA6XXXLAt4tNHBgbzX_Xrigc_PuoxCCGrbLA,560 +pandas/tests/extension/test_interval.py,sha256=8KR4X-u0Ie4_y_4KOh-nC89kCFk_M8ECQ9cojscPLWM,4419 +pandas/tests/extension/test_masked.py,sha256=f9Jc_RgF76qaN2Z97lFb0BnGR2ZIIg-lLrWh1F9-R2M,11633 +pandas/tests/extension/test_numpy.py,sha256=nqai5lOHjGmlizDtmB8c49Ej0xckIsjttjoWnBhZJPg,20123 +pandas/tests/extension/test_period.py,sha256=TQk-7_tIeJ9NC28uY8lzjBDUWBw60jrNFa6UagomOZY,4422 +pandas/tests/extension/test_sparse.py,sha256=OMTkZ5iD4kqcPK0qZcKRYayL89vb8a9KdZl1ZZRGJdU,18054 +pandas/tests/extension/test_string.py,sha256=gXluuSseOZO0ZuiZH-vSFzIFhRI0yR38vrCJEt6cg3k,11851 +pandas/tests/extension/uuid/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/extension/uuid/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/extension/uuid/__pycache__/test_uuid.cpython-314.pyc,, +pandas/tests/extension/uuid/test_uuid.py,sha256=Nfws8V-fi4P2qFkSAeWpBnF_kUl8tc4RQpy4y5ReXTE,4483 +pandas/tests/frame/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/frame/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/frame/__pycache__/common.cpython-314.pyc,, +pandas/tests/frame/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_alter_axes.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_api.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_arrow_interface.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_block_internals.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_cumulative.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_iteration.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_logical_ops.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_nonunique_indexes.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_npfuncs.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_query_eval.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_reductions.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_repr.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_stack_unstack.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_subclass.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_ufunc.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_unary.cpython-314.pyc,, +pandas/tests/frame/__pycache__/test_validate.cpython-314.pyc,, +pandas/tests/frame/common.py,sha256=EX4_5J3wNjPyA-gGj3hdq6npZm1kKkQvLoUg_gK4eZ8,1855 +pandas/tests/frame/conftest.py,sha256=hwYU7l4WXJl1fqXY1g9xWYARKuUJPW93YUBEYiM3paU,2700 +pandas/tests/frame/constructors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/frame/constructors/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/frame/constructors/__pycache__/test_from_dict.cpython-314.pyc,, +pandas/tests/frame/constructors/__pycache__/test_from_records.cpython-314.pyc,, +pandas/tests/frame/constructors/test_from_dict.py,sha256=kOZTB8nFqteGRuQHQ8G42iRjetyk6lo0z-sTGAEu8bE,9633 +pandas/tests/frame/constructors/test_from_records.py,sha256=JtUnvc2Qm90r5YBV26vHRUhIN4iSa6AULeOb7XhSero,23030 +pandas/tests/frame/indexing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/frame/indexing/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_coercion.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_delitem.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_get.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_get_value.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_getitem.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_insert.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_mask.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_set_value.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_setitem.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_take.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_where.cpython-314.pyc,, +pandas/tests/frame/indexing/__pycache__/test_xs.cpython-314.pyc,, +pandas/tests/frame/indexing/test_coercion.py,sha256=48HDYN9-HwlvMtGhzNiBfmsJNN9i4GgwxMnyMDOBD1U,5087 +pandas/tests/frame/indexing/test_delitem.py,sha256=Qavunk49AAvID0lcLstwYo7mkEW7wi8VZB95H7k91S8,1873 +pandas/tests/frame/indexing/test_get.py,sha256=L1dfoIj3wabzjs9u4DiUGC4V91YCx6xWzzUrF9X9L-Y,684 +pandas/tests/frame/indexing/test_get_value.py,sha256=Vh6aPdviyLfwBl3BDk9kIOaVWqAH8OI6Z9hBipKawZ4,651 +pandas/tests/frame/indexing/test_getitem.py,sha256=BrwRD184po9cO78KRo5OprfFEXMMlvRobkhRYZ1ym7Y,18228 +pandas/tests/frame/indexing/test_indexing.py,sha256=xpF2RYmbutESPVsySJlB3QHlTt1hx8uHOLmYJ2Tv3Gk,68261 +pandas/tests/frame/indexing/test_insert.py,sha256=zHaRIXxFwIr3Ik98KmirqZGVoo48T_YSZii43wpseDI,4057 +pandas/tests/frame/indexing/test_mask.py,sha256=DMzgP2uEKN52pe1hFl9wjWVGmV8MWRKJryR1aiWvLVM,4959 +pandas/tests/frame/indexing/test_set_value.py,sha256=HWQAH9AGkec57GVJvlejOy53Z6snv0P4d9MQ1WbTu24,2470 +pandas/tests/frame/indexing/test_setitem.py,sha256=9NN5AvE6oZuJFUAA1QgFuGPOT3SePJ9G20hA4wkb8nY,56852 +pandas/tests/frame/indexing/test_take.py,sha256=T2UkOudAk18icTag1S8f4MOiIFQfOb8BWEh2uXCS1XI,3229 +pandas/tests/frame/indexing/test_where.py,sha256=7XkxH2iasvTgcZ2PDaH00tqRADj5EVfCZ2lDWdRboeU,42871 +pandas/tests/frame/indexing/test_xs.py,sha256=EB2IbqS7tImsBEuWbiHcROQGl8J6oNiW_6BlFcEv39I,14143 +pandas/tests/frame/methods/__init__.py,sha256=M6dCS5d750Fzf9GX7xyNka-SZ2wJFCL66y5j-moHhwo,229 +pandas/tests/frame/methods/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_add_prefix_suffix.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_align.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_asfreq.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_asof.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_assign.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_at_time.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_between_time.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_clip.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_combine.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_combine_first.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_compare.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_convert_dtypes.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_copy.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_count.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_cov_corr.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_describe.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_diff.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_dot.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_drop.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_drop_duplicates.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_droplevel.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_dropna.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_dtypes.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_duplicated.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_equals.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_explode.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_fillna.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_filter.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_first_valid_index.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_get_numeric_data.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_head_tail.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_infer_objects.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_info.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_interpolate.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_is_homogeneous_dtype.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_isetitem.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_isin.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_iterrows.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_map.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_matmul.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_nlargest.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_pct_change.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_pipe.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_pop.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_quantile.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_rank.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_reindex.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_reindex_like.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_rename.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_rename_axis.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_reorder_levels.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_replace.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_reset_index.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_round.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_sample.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_select.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_select_dtypes.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_set_axis.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_set_index.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_shift.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_size.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_sort_index.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_sort_values.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_swaplevel.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_csv.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_dict.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_dict_of_blocks.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_numpy.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_period.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_records.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_timestamp.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_transpose.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_truncate.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_tz_convert.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_tz_localize.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_update.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_value_counts.cpython-314.pyc,, +pandas/tests/frame/methods/__pycache__/test_values.cpython-314.pyc,, +pandas/tests/frame/methods/test_add_prefix_suffix.py,sha256=DVtygeAbnmbu0XA_qp2JFluINOP5H9aZ_fMIzBndAu8,1929 +pandas/tests/frame/methods/test_align.py,sha256=NH_Si0bjD54G2VY9kxgbSiTH_li4cFjVt4iB9Yas1_c,12373 +pandas/tests/frame/methods/test_asfreq.py,sha256=3WWLagXBg_FPUb4gdqCAnBoOXjiQelMh1ZWsXI6aM6c,10710 +pandas/tests/frame/methods/test_asof.py,sha256=PW4kgUN0wnfQVskXmbxepnh_fhw_Agj-rs4mznHqAZ4,6263 +pandas/tests/frame/methods/test_assign.py,sha256=gb-qMoTxNSi0XztYQKOc1nOhYQ3EktUjGCeH8JRb81w,3003 +pandas/tests/frame/methods/test_astype.py,sha256=2y5vmAjeJd1STN0NPy5_gb-xY80Z8nvOfcBCyWocn4Q,33790 +pandas/tests/frame/methods/test_at_time.py,sha256=M05qOmZ3PjUKy0fgZPNo28Dbjzt1xGoWboPqmeX1cZo,5535 +pandas/tests/frame/methods/test_between_time.py,sha256=yRDMkhu4_aDBZOZY7PauZQ3ZMkEJHFYEoov2oV5CVuQ,8657 +pandas/tests/frame/methods/test_clip.py,sha256=VoVxr9L6pddUR3rxUUkNxRmSkYcT3QVtmJpX93gEjZE,8691 +pandas/tests/frame/methods/test_combine.py,sha256=VnLjEF22Rh8mUdGiHGo0PvxaJz2Z3QwuJbeRtB0TbpI,2718 +pandas/tests/frame/methods/test_combine_first.py,sha256=e0jYvMNPBTgLVsjhlhdMR02d4B_WcTwwVDzdo8k3dYc,21764 +pandas/tests/frame/methods/test_compare.py,sha256=hu5O6nJMAUw7Te3mWb4h6Z6A2gCIURJrN9Sb93dz3uE,9758 +pandas/tests/frame/methods/test_convert_dtypes.py,sha256=VtT-8uHWFYUFE_WEECYsPlQKcXyyUMYimDmI_abdpQE,11301 +pandas/tests/frame/methods/test_copy.py,sha256=EjeN-pA_JT9nBPXa3uLyjx-6t7oe7YLApG_0KDzznDg,1260 +pandas/tests/frame/methods/test_count.py,sha256=Kb7j9MSv9O3gU8zsYDvHatYHbkCvcKlzcQIv21J5Kf0,1086 +pandas/tests/frame/methods/test_cov_corr.py,sha256=7_O-wmw09Kt7eBjNWwlrY0pDegbWMiRXKhfq5BporcE,19836 +pandas/tests/frame/methods/test_describe.py,sha256=Rs8W6vYnY1tGOnUzlEI3ZUOdTuI5S0XqZyVZ5oL546Y,17760 +pandas/tests/frame/methods/test_diff.py,sha256=gm535k2dgRDbbK3Ikyi-fw-w0etG1FmaDIoeq7vHnnA,10306 +pandas/tests/frame/methods/test_dot.py,sha256=dOgEWKoDP1O4E6jppVqsLwp0OvhwAu4wPEsXhUeGAMA,5128 +pandas/tests/frame/methods/test_drop.py,sha256=vkqGbJ6YGuMy9SR1TEOFnwol0OzrqONkiw6gESp4lEU,22676 +pandas/tests/frame/methods/test_drop_duplicates.py,sha256=IcWriWRjJumTp4QIdhnqbK9YKl81WntGDLd8IRuC_bc,17380 +pandas/tests/frame/methods/test_droplevel.py,sha256=t5WWbzDuY3l6Xm4LQNj6K6TbWCWEli5aPVuU7pjvm8U,1226 +pandas/tests/frame/methods/test_dropna.py,sha256=WgliFM2u5D4qEvpXjvuVO5Hqa16v14BY_UpyXfwI-r0,11873 +pandas/tests/frame/methods/test_dtypes.py,sha256=1GZ02DhiWo2sSw6U-nAYcNHuHmUtjpd1PV0FroAMju0,4734 +pandas/tests/frame/methods/test_duplicated.py,sha256=QGYdRMcTVbal_hsdPCT6iW2it788dzAHFiPaF2xNFNs,4405 +pandas/tests/frame/methods/test_equals.py,sha256=IK09gEU6ngQysUkhFgA8XmEXmg51BmJu4AZnC821q8U,3956 +pandas/tests/frame/methods/test_explode.py,sha256=b4Q5DAGmecPEsRXM_cNTPPyeR1GX88NwHAqWRFQzcXQ,8952 +pandas/tests/frame/methods/test_fillna.py,sha256=EmtY_Hu32nXBB7DIlA6EMpdGyPZob3-tCS2TGGrjY_g,33136 +pandas/tests/frame/methods/test_filter.py,sha256=guMqG16GEUeIm-VvndKYf8yEycdt8IY9Q4lmjNa3-H4,16275 +pandas/tests/frame/methods/test_first_valid_index.py,sha256=EdT3Swp7MFe8zvHCLndh0IJkCz5Lb8cWr_-tPz8cX4U,3361 +pandas/tests/frame/methods/test_get_numeric_data.py,sha256=1lhAW6Tv7SKr-HsHSGGC3cDwaF2L9d69KCVzy4IrPJg,3372 +pandas/tests/frame/methods/test_head_tail.py,sha256=L64Ac5mg6kxJ45xE0q2FxqjbXEAjux0YoRtBC6KQv5M,1932 +pandas/tests/frame/methods/test_infer_objects.py,sha256=nlkCfRVHIB_RmFk_M5JgmglVDZtfNCF0u9zHqsRDGeQ,1238 +pandas/tests/frame/methods/test_info.py,sha256=bbiCLqMbfmTMnFioQlwz5qTaTqdkvx-MujKZPHfwUWI,19022 +pandas/tests/frame/methods/test_interpolate.py,sha256=wWcvZBFJktPrh8BDLJCo3XJlcAF8AJ5YtAsUG1jF8mQ,17116 +pandas/tests/frame/methods/test_is_homogeneous_dtype.py,sha256=iWqB6b_Ry5jd_94PUDPaBC4F0oKvVeneau3FaN8-oEc,1361 +pandas/tests/frame/methods/test_isetitem.py,sha256=DTDF3fRkwD_anYxksxeb6HjAVT1bFOcuTHUOr8WlTzA,2228 +pandas/tests/frame/methods/test_isin.py,sha256=d1Dqp-RYpI12TMcfSjR-0ODQz65jdANA0KzaAQS8I1s,7672 +pandas/tests/frame/methods/test_iterrows.py,sha256=Tfw-DI4-sgJkFxaXnSf3EltblaZGo6ICGWb6KTR6MPU,311 +pandas/tests/frame/methods/test_join.py,sha256=rEMmomPqgdrdPMVkvet8GJwBqAa9eh9PxN3Hf_FwA3w,19164 +pandas/tests/frame/methods/test_map.py,sha256=BnYJuA4KgB7aN1l00l-9TbhbwOuv5nhx65Ovm8ItEdc,5715 +pandas/tests/frame/methods/test_matmul.py,sha256=9QGW3GPGx4zWzTfh2Era7xowCQ7JEP-osI2Z65qnNIw,3132 +pandas/tests/frame/methods/test_nlargest.py,sha256=QpPDbc6wLsNCP-Xry76iX-OxoQM_3Adiw7SJmWMie6I,7631 +pandas/tests/frame/methods/test_pct_change.py,sha256=4d22BBJ56M0PyGtn5KdzE8qHEV1ceovlb36jp9un2ws,3654 +pandas/tests/frame/methods/test_pipe.py,sha256=xIPcY5H0ivUBQLQafqBA3fJz654f-HoZGTUpXvbml5M,1008 +pandas/tests/frame/methods/test_pop.py,sha256=1hDUDSK7Tdt0MIUQ7bJE3WT0hzNfErziRR9zzZ_1jyc,2175 +pandas/tests/frame/methods/test_quantile.py,sha256=Jh0cQg3ZcSCNEHqnbaf6IyKPXfSejWbwamlbiQDJneQ,34363 +pandas/tests/frame/methods/test_rank.py,sha256=uHr4JRYURUm7eEQDUPloo0C_7aKj8U0OkqiVElOAcsA,17515 +pandas/tests/frame/methods/test_reindex.py,sha256=X7yMJfHAFFYuTwbvnLw5K8E1o0Yhxvwx5eILXbD6r0E,49247 +pandas/tests/frame/methods/test_reindex_like.py,sha256=lXcYM97RPuDE6aJs9wJNJMpHnkPxC6TyPqVXtXbpBro,1424 +pandas/tests/frame/methods/test_rename.py,sha256=P2YQPyB-_BFTnWQUf1f0HHP72Ta0Klas-qTlFw8YOak,19576 +pandas/tests/frame/methods/test_rename_axis.py,sha256=hhi4aS_EqQ3EFsSuL1uItMUBWzygiPmfUbaHuHjmiMM,5550 +pandas/tests/frame/methods/test_reorder_levels.py,sha256=6t2HHwzx6GfrwmFZvmEF5amIYOWuxOFJr7SMs1L6Ab8,2713 +pandas/tests/frame/methods/test_replace.py,sha256=ro7Ou7i-DVw2Jo8BhM6FSITJ0yR8chheqhJjaagb1wM,64538 +pandas/tests/frame/methods/test_reset_index.py,sha256=S0jSDOWpmjO-JFoiBVbnw-ZEELnvVaxCOAU8OI3RdRo,31258 +pandas/tests/frame/methods/test_round.py,sha256=gamm919FmIzHzyVD0MP7miCZ2THLoJk90_pvDZnWCMU,8377 +pandas/tests/frame/methods/test_sample.py,sha256=bSSLJyKMtO1n8uOl1m1W6KkFItqjC6Na_1SgpxPuKBE,14242 +pandas/tests/frame/methods/test_select.py,sha256=S-7DC-EfjMjEbDG6vNQeqbydXoliAyOTmwaUoHy8sJs,18768 +pandas/tests/frame/methods/test_select_dtypes.py,sha256=UlksaH18LacEcS-tem1Z4-NT28lY6MY0Qm4lBImrSDg,57608 +pandas/tests/frame/methods/test_set_axis.py,sha256=I70ashbraUe1WiAMPfgcSjLkFuzaOBa_yJG1O8CT1wI,4100 +pandas/tests/frame/methods/test_set_index.py,sha256=2xJKiTzOr5hw8tWtN3p3Zn7POvNn4JakhqtfQ0csfYk,28178 +pandas/tests/frame/methods/test_shift.py,sha256=Onuac4ieRL9fzEennObGdc3Mog1L0bOo7f-Ht4zuKbQ,32869 +pandas/tests/frame/methods/test_size.py,sha256=HXRpK4qDmQm4qjXGqLLK0jjruM7W3CMN-Jro7_17ZFM,565 +pandas/tests/frame/methods/test_sort_index.py,sha256=33LY202oa1h50MDT1cEcD28yMPfNYyZxliPbMp_Vrtk,39340 +pandas/tests/frame/methods/test_sort_values.py,sha256=EwEaoJZvJpTE8S1yMB5C2SO1J-qYQ-g2FYaEGa1Z7Zk,34047 +pandas/tests/frame/methods/test_swaplevel.py,sha256=S6LS9NFNsQCpQXhFds8LLh5LS5I3zt9-uMT_06SFauc,1271 +pandas/tests/frame/methods/test_to_csv.py,sha256=L3WTA-NFLeh0szYNMksXIelD45UiTUtgKQdngRToyig,52524 +pandas/tests/frame/methods/test_to_dict.py,sha256=Ax1tU1LdEwUjyVVfkNtIq6z8epzav9OPw0wj6aI3Am4,20052 +pandas/tests/frame/methods/test_to_dict_of_blocks.py,sha256=oDN6mMNp3x0F1VDkhaRIK0_rdq7asNa_ASbYgyeS2SI,1090 +pandas/tests/frame/methods/test_to_numpy.py,sha256=4mqgrOvxeZsioRwvve_6ssHPzNGyJvnlYv4Uw9M2GaA,3265 +pandas/tests/frame/methods/test_to_period.py,sha256=Q2eurZBTFmRZQJPQPVrUr22otaOIYfDdSlV0iGwj2KU,2852 +pandas/tests/frame/methods/test_to_records.py,sha256=zlj96Jn42LKGETg4Wch2Lqg621EdA40ESUcs4eQW_-k,19172 +pandas/tests/frame/methods/test_to_timestamp.py,sha256=qWBs9jEPYYuIVOpt37kavLASX7A3mzB_tG5GyEAGGpo,5899 +pandas/tests/frame/methods/test_transpose.py,sha256=q2l05v3a4MXC9vz4pwiZ4vXKBTEBSmJOQpxULMYCnxk,6423 +pandas/tests/frame/methods/test_truncate.py,sha256=CQHWoXBK8TfQ8N_8hJ-7TRBwkTBYTdTpjS-FI9RJzE0,5570 +pandas/tests/frame/methods/test_tz_convert.py,sha256=LQI9H-zugIcTk3P0jOptSUZf9ur_h4qsCrwTFMXrVMg,4732 +pandas/tests/frame/methods/test_tz_localize.py,sha256=83oo-VB5Gz50kcIEUpNEvgssEREmj3jQueF_qwf4-1g,1989 +pandas/tests/frame/methods/test_update.py,sha256=b1ZIP7O5iZDytKQxJ4A5UafpwyudE3_p70HLwj6kJq8,9172 +pandas/tests/frame/methods/test_value_counts.py,sha256=rpxC1EaCQyrQPEOmTIYXpTxt8oAvhS-9no4KpoqLnE0,5556 +pandas/tests/frame/methods/test_values.py,sha256=dMD6OcvAPe6Qpj7jMGl3HZb4mMAuFio5qP8WJoWbLMM,8769 +pandas/tests/frame/test_alter_axes.py,sha256=isZW9BTW4zoblyZq9DQPphi5TC_EPIjS3EIg_6P6BSs,867 +pandas/tests/frame/test_api.py,sha256=L9sixkv0NOkxy0CGK9blXgXUPj023tg288i1wMQRQWA,13221 +pandas/tests/frame/test_arithmetic.py,sha256=BTI-F4IP1AL3jgUs9p8NjZOR7lvnzvK1-Ae4-puQTDU,86181 +pandas/tests/frame/test_arrow_interface.py,sha256=bKPWLvMStfUV0zFM7TiPwLLYAaLYtPMXwwYwMIn5R48,4195 +pandas/tests/frame/test_block_internals.py,sha256=57Ye7HJAtq-YGdA-jPbUulZqHQBbGup2030DNbsp9WE,16510 +pandas/tests/frame/test_constructors.py,sha256=y62XuzvJhQy901r5DlPC7thJOYsywls0WG6h_2fvvO0,135223 +pandas/tests/frame/test_cumulative.py,sha256=StsZ9JjpnmJPl3-onuwnzkVkRP-uFVddqOTfG9kASwc,3980 +pandas/tests/frame/test_iteration.py,sha256=jQoa1ox2h7nvz2QVclU6nVLByvd8Ix9tG-wupX7lTq0,5953 +pandas/tests/frame/test_logical_ops.py,sha256=NAom8g2b7HkMB1sByMzKEpLXB7dosPNqgNBBGGdV7t8,7733 +pandas/tests/frame/test_nonunique_indexes.py,sha256=bt419IdH64yzHfG9YxVIW_qmAzAprnmt7oHF6vucGe0,12069 +pandas/tests/frame/test_npfuncs.py,sha256=n4oEN43d2zi_P-YoJGuNo5JPlXIfmgfkASCTUoDFJKo,2485 +pandas/tests/frame/test_query_eval.py,sha256=yInfIJ4Tkf5MY0IljCpMnIMjUQPKqKuqwX3yfFqgjYs,80676 +pandas/tests/frame/test_reductions.py,sha256=xjpptcPLDghPtPQxkSseyrZ8cGwg0IZWTQ9_KRKZpfA,122411 +pandas/tests/frame/test_repr.py,sha256=2_EdKxtR4hySakHvd-7CWK0bJHLJcrb-t4_n7Z5WF10,16844 +pandas/tests/frame/test_stack_unstack.py,sha256=ibLP27EpLzY0_AsYHouLffgFIt8OZGrWZwlqDVrEGxk,113844 +pandas/tests/frame/test_subclass.py,sha256=V7jIsY2P_TT_MCMimber3YGH7QzNUVv5G4InIRS-dnQ,28828 +pandas/tests/frame/test_ufunc.py,sha256=OzhEhzdn3K3_C6N6ipVc-k9karX4Ht2NcpCLo0hBkUA,13209 +pandas/tests/frame/test_unary.py,sha256=f7OE-JWTsgBt9ngJtcAXTNi00414aNVUdYQ_omeuDaY,5722 +pandas/tests/frame/test_validate.py,sha256=v0NhMoPDca_TKYHJwayOt8U2gAySFdSi6629FDexVIE,1162 +pandas/tests/generic/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/generic/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/generic/__pycache__/test_duplicate_labels.cpython-314.pyc,, +pandas/tests/generic/__pycache__/test_finalize.cpython-314.pyc,, +pandas/tests/generic/__pycache__/test_frame.cpython-314.pyc,, +pandas/tests/generic/__pycache__/test_generic.cpython-314.pyc,, +pandas/tests/generic/__pycache__/test_label_or_level_utils.cpython-314.pyc,, +pandas/tests/generic/__pycache__/test_series.cpython-314.pyc,, +pandas/tests/generic/__pycache__/test_to_xarray.cpython-314.pyc,, +pandas/tests/generic/test_duplicate_labels.py,sha256=MrZt1-wmIBPP6wIIkoeQjle8PblIBFBTuF66fsmy5cg,14356 +pandas/tests/generic/test_finalize.py,sha256=32zG9KZmoAblJcLqDqePkfkloYvB_TAP6X53iBi5zW0,29366 +pandas/tests/generic/test_frame.py,sha256=_neN0eFMjunDeXRr6-WUU8b8whgABWKEGL__yIStyZI,7012 +pandas/tests/generic/test_generic.py,sha256=xqrzkp8sx3zRKjfj9MgmDj_9CJLv6HXhzTF0bMivKZ4,17090 +pandas/tests/generic/test_label_or_level_utils.py,sha256=TM1MiZddd3EiMIuu-hbN4n1nPonbxhq0IVbGyd3-z-M,10122 +pandas/tests/generic/test_series.py,sha256=WrVErEFPU0TT2buaMds5SeYeA99I4YvGI8pC9SX5p48,3966 +pandas/tests/generic/test_to_xarray.py,sha256=6LMrI-wLuE-bfuZbbo173HF5Pf_s9UinxjLdg1DI8rU,4077 +pandas/tests/groupby/__init__.py,sha256=zHEFNACJrOe_gq6EAbRv3-fQwdTMBHxx5MTk7lOvrko,639 +pandas/tests/groupby/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_all_methods.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_api.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_apply.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_bin_groupby.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_categorical.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_counting.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_cumulative.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_filters.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_groupby.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_groupby_dropna.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_groupby_subclass.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_grouping.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_index_as_string.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_libgroupby.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_missing.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_numba.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_numeric_only.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_pipe.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_raises.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_reductions.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_sparse.cpython-314.pyc,, +pandas/tests/groupby/__pycache__/test_timegrouper.cpython-314.pyc,, +pandas/tests/groupby/aggregate/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/groupby/aggregate/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/groupby/aggregate/__pycache__/test_aggregate.cpython-314.pyc,, +pandas/tests/groupby/aggregate/__pycache__/test_cython.cpython-314.pyc,, +pandas/tests/groupby/aggregate/__pycache__/test_numba.cpython-314.pyc,, +pandas/tests/groupby/aggregate/__pycache__/test_other.cpython-314.pyc,, +pandas/tests/groupby/aggregate/test_aggregate.py,sha256=XHDSV_pLkX2KCcPCVdOetIdxRAzHC0Pho3pkDaZFr0U,75081 +pandas/tests/groupby/aggregate/test_cython.py,sha256=YilqZCcaPtxl1xgGGTw6WFwtAMKo0WQg-JARfBqZT_4,11915 +pandas/tests/groupby/aggregate/test_numba.py,sha256=SzAqX4Q1JFrjCDpMm5EFwddlaL4T8tshm2ZoUEkgiNw,14915 +pandas/tests/groupby/aggregate/test_other.py,sha256=X11yOV_BfVFWeV9X7KOCNmU_3bFOI5IC2n3GGJvYMFg,20161 +pandas/tests/groupby/conftest.py,sha256=MUj7-UVP9AUQuLr1kzbayOHtNQzeEDIZ_d0xg8KOqP0,3860 +pandas/tests/groupby/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/groupby/methods/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_describe.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_groupby_shift_diff.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_is_monotonic.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_kurt.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_nlargest_nsmallest.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_nth.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_quantile.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_rank.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_sample.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_size.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_skew.cpython-314.pyc,, +pandas/tests/groupby/methods/__pycache__/test_value_counts.cpython-314.pyc,, +pandas/tests/groupby/methods/test_describe.py,sha256=c2RSIXFPLJ5FCr94TAE5OY-ON_WSear6IStzwrxg4to,9052 +pandas/tests/groupby/methods/test_groupby_shift_diff.py,sha256=lcix8a8g_QrhebwYSB4zIRg4zBjNuAyA8BUL-DBoSrs,8449 +pandas/tests/groupby/methods/test_is_monotonic.py,sha256=RShFSvpdm1O038-CowjKKKqxhXwmY9ygAQjHY0Gth-s,2543 +pandas/tests/groupby/methods/test_kurt.py,sha256=WMArUkgrVsBS7PQLHAi8_CJNO-PdaLXESzFnFxoHiOk,2393 +pandas/tests/groupby/methods/test_nlargest_nsmallest.py,sha256=R4iuwtxctNbuC9_BApZlz6DKl9Hsa97jp0HFTiH3nN0,3428 +pandas/tests/groupby/methods/test_nth.py,sha256=e5ZRswsMAoOZGPYgxuwY3r7Gyi7caS4G2fuPiZ5kktk,26469 +pandas/tests/groupby/methods/test_quantile.py,sha256=dwa005S9jDIIfd2QdGlV-A-2-F8KYrcZWnjQt1lq7Ak,17669 +pandas/tests/groupby/methods/test_rank.py,sha256=Cd4SFxVyBJT_NPl7SJuV1sno2YXQm5Ma4bQEIUc3TQ8,21538 +pandas/tests/groupby/methods/test_sample.py,sha256=sIUVD8cjKm0wxDpY4tR1kbX6Q1geC_kcisMrBZ7Kg9U,5195 +pandas/tests/groupby/methods/test_size.py,sha256=DIiz1xCjUs3wH_p_2aLnC05yS6igJC3CAlkAUhltQmI,3015 +pandas/tests/groupby/methods/test_skew.py,sha256=nfZNzIMufFZQ3K-e2zKP-uaoQQWjLTt0qYaA-D_koRM,1506 +pandas/tests/groupby/methods/test_value_counts.py,sha256=q7bHH5Yt_hiTVLqdjJ37N5cNBGzruKBJ30NMc5_OcXo,37712 +pandas/tests/groupby/test_all_methods.py,sha256=U5_NpkIRh_GqmbFr1aXTdtb-RoD9x3UJNGXPpA0H8K0,3567 +pandas/tests/groupby/test_api.py,sha256=LcCImZHiQL1a1iv5x7D6wITiNr6iUDGgSxDXKJCw1d8,8501 +pandas/tests/groupby/test_apply.py,sha256=ckNgekmQxLppryNB2_-qvxf13s5-XklcdmUz-n1ccUQ,47931 +pandas/tests/groupby/test_bin_groupby.py,sha256=wn54JkD906d-bLPiu0xwkaDVPfwcbm_m_Dd7ZtW4L40,1553 +pandas/tests/groupby/test_categorical.py,sha256=Dtuzig0GCzohu4BcMyPRytaevSE-jleXek2JIltCdiI,79362 +pandas/tests/groupby/test_counting.py,sha256=dXAUzsGr30dwttH2wlCfdsV1o8icjv3Grb6ZilrTq4k,13629 +pandas/tests/groupby/test_cumulative.py,sha256=6kMDD0I226MrrBHxpWhPZ-8e2WMewsjH-718yulSFJI,13148 +pandas/tests/groupby/test_filters.py,sha256=KMhvcyC04bEBueTgeDfmKRgpovRSUB6vDs9C53ZqSwY,21475 +pandas/tests/groupby/test_groupby.py,sha256=XVKFk3xz5D9amxGzFwwi9vmdVVfgs2c41L9XDYoTSoU,98025 +pandas/tests/groupby/test_groupby_dropna.py,sha256=jr0u-pJI-InSln0fyhIMzfiFHQkUVIO1RnC8NOPd3rc,22715 +pandas/tests/groupby/test_groupby_subclass.py,sha256=mU4guKMYHF2zBUCXPR6hSMFTM6VXG5XZ6e8Cf8SPplY,5037 +pandas/tests/groupby/test_grouping.py,sha256=sMvWWpANZXnY0-ChfFiuAx3WbpubscuKnqiFYGeSLXQ,47993 +pandas/tests/groupby/test_index_as_string.py,sha256=QM5ye0lc9GMrdNwdfF-8EAwbpiliNpPagV1AC1RmoYo,2162 +pandas/tests/groupby/test_indexing.py,sha256=cp3WHS9tkGFsaeIqL9nAN0ur36-2wBXivqGdwD-rmvs,8970 +pandas/tests/groupby/test_libgroupby.py,sha256=kmOqGiMK6EUPih9l0OPNyAPlyfI8T76f7X4Ig4rcDFE,11155 +pandas/tests/groupby/test_missing.py,sha256=ymqWYLSVgiZXFMiFP8tVp-0R-PuCh3GIrHINyuqkO_I,3232 +pandas/tests/groupby/test_numba.py,sha256=G4YGl8ZNHDxcj0l20SgUM9YAneXzbJ_oORrNP9NXUHY,3077 +pandas/tests/groupby/test_numeric_only.py,sha256=DVPmjV9BCwEOfI5TN-Mz-lbyldMBcBj4TV_w88aWxvs,15194 +pandas/tests/groupby/test_pipe.py,sha256=1mtWUhaM0fChirAYNonc76nv3WS_SrMcZiMjCB3K8v0,2048 +pandas/tests/groupby/test_raises.py,sha256=LDxShV_PD9FctX-90sO2Qu9Z8cuyqCFHvJ0NZhpDPN4,21663 +pandas/tests/groupby/test_reductions.py,sha256=MFgWG_eF7rPz_VzZ5EH1ffTdJdy3Ti_uKnE4ttycAl0,62095 +pandas/tests/groupby/test_sparse.py,sha256=nf0Fz22-597r67drXJORB_fItz-t_cTC5t6A7D6Few8,12933 +pandas/tests/groupby/test_timegrouper.py,sha256=26arV8JtcHpbqTjxPvdgoLpdf398Y59NgYjyx2fGB7c,36115 +pandas/tests/groupby/transform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/groupby/transform/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/groupby/transform/__pycache__/test_numba.cpython-314.pyc,, +pandas/tests/groupby/transform/__pycache__/test_transform.cpython-314.pyc,, +pandas/tests/groupby/transform/test_numba.py,sha256=gaAHyzLU-tBcS6XUc3szsjQupB6zPcWplQj4IR3UX_Y,11273 +pandas/tests/groupby/transform/test_transform.py,sha256=0zNJYeT3wZdEoLNCO8mJva4j5VklK6MzBjJUKERSiXA,56473 +pandas/tests/indexes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_any_index.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_base.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_common.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_datetimelike.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_engines.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_frozen.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_index_new.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_numpy_compat.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_old_base.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/__pycache__/test_subclass.cpython-314.pyc,, +pandas/tests/indexes/base_class/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/base_class/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_pickle.cpython-314.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_reshape.cpython-314.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_where.cpython-314.pyc,, +pandas/tests/indexes/base_class/test_constructors.py,sha256=7sCrmf53rTfrId4goYELRX88BYztsYy2rjVK8EMfrH4,2436 +pandas/tests/indexes/base_class/test_formats.py,sha256=VMnP8EBw812ijlL5VrmxMB75id6cz1Fv5xGlCzX-XfM,5912 +pandas/tests/indexes/base_class/test_indexing.py,sha256=uQAo6GPq9xzLv8oJa7BggYrqdQu6UT6UoCvfsrU0a8Q,6287 +pandas/tests/indexes/base_class/test_pickle.py,sha256=vg0tDc3CGrFUaPlZ3qqfgOxrPef0_c_R_oFYeubAi-A,327 +pandas/tests/indexes/base_class/test_reshape.py,sha256=VlkbESpQUFPEkGojsHXqs4Hu8ei-SFU_5bHVriR_g8M,5451 +pandas/tests/indexes/base_class/test_setops.py,sha256=kjcX6QGXrFi79zbLKadckcu9gslxfLK1BAKBg2wQ0gw,10275 +pandas/tests/indexes/base_class/test_where.py,sha256=DOl7gEI1vOVjwS5fkCAYUAumwuOUkhZWGvXppckRlQY,1425 +pandas/tests/indexes/categorical/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/categorical/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_append.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_category.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_equals.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_fillna.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_map.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_reindex.cpython-314.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/categorical/test_append.py,sha256=Dxh5hJVzcTaaFQePO1Z7cZaEMaWP1nUVSwTlkOVNJ_4,2239 +pandas/tests/indexes/categorical/test_astype.py,sha256=ocaw2_-VWlv7yLnzJ-ouXKJg76SH-nWt5nUUppy0q9s,3098 +pandas/tests/indexes/categorical/test_category.py,sha256=39wy57Cm4TqHw2oamyQZ59OU-tjr1zwh-u6HyyJrHXI,15100 +pandas/tests/indexes/categorical/test_constructors.py,sha256=34lC3i8R_ycUsyeLJLzVkxBLZYmf9Jj-8zBAnFm3AGo,6022 +pandas/tests/indexes/categorical/test_equals.py,sha256=6iXnDEuZq-Uo0GgujICijn_pjh5vUsX9uDy-kjVAoMc,3589 +pandas/tests/indexes/categorical/test_fillna.py,sha256=Dfp65A8oma1Nrh_aLd5Z5F1wzkmbjNlq_wkclw_hoD8,2744 +pandas/tests/indexes/categorical/test_formats.py,sha256=z_xbfvjJbWjD0FqiFSWO43TnW065G0kke9Oz_whHmSQ,8056 +pandas/tests/indexes/categorical/test_indexing.py,sha256=waviQzMCWM4cm2uODckOtsGvkh4vZVxWf3E8hLUyryE,15047 +pandas/tests/indexes/categorical/test_map.py,sha256=QRMwIHfGIKSfh3WB0mejOxb2QLkmdlNh6c51Pft3k6c,4731 +pandas/tests/indexes/categorical/test_reindex.py,sha256=uCkyLa--RIdrEziSndzHZGQpW1lvUnCcJ_pe6t6U3nM,2931 +pandas/tests/indexes/categorical/test_setops.py,sha256=p3EGzVSwI9tPXNNCsNlss6Czh4RvQy5PE7mz51wDOvc,1879 +pandas/tests/indexes/conftest.py,sha256=ZnytnoHrEzVOBgespNrt-RjtmbpyKxBwAN2GSbk3m1w,939 +pandas/tests/indexes/datetimelike_/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/datetimelike_/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_drop_duplicates.cpython-314.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_equals.cpython-314.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_is_monotonic.cpython-314.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_nat.cpython-314.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_sort_values.cpython-314.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_value_counts.cpython-314.pyc,, +pandas/tests/indexes/datetimelike_/test_drop_duplicates.py,sha256=98JK-eIAFfg5rGnLZoH-bLBC3YIfVrlifgelIVmZRkQ,2930 +pandas/tests/indexes/datetimelike_/test_equals.py,sha256=dbiRYiaJj_Ljtd4OmMdzi8VnKd9HwYwxAcXxmYLPYHo,6484 +pandas/tests/indexes/datetimelike_/test_indexing.py,sha256=3hs9zbn077KZTTKyKNi3EkiqgtMnHVcKeYKDRjwguwg,1263 +pandas/tests/indexes/datetimelike_/test_is_monotonic.py,sha256=jbxv8w1M2-7FZQTt8Lvq1wJBfqcOXp37eiTvV4XYYOI,1510 +pandas/tests/indexes/datetimelike_/test_nat.py,sha256=yBnZBSVWCk6t_lC8kYfzrf6GGjAPl6GZP4I8xBV4jpE,996 +pandas/tests/indexes/datetimelike_/test_sort_values.py,sha256=P1fF8GdtjYSlljmguiYTSsqxK6Yu2fRiz6MhMBlWDs8,11332 +pandas/tests/indexes/datetimelike_/test_value_counts.py,sha256=nG8cSIE6W9yLnLj-hi4r0Y3gm3jbOMrAsBpR8GSjRn8,3103 +pandas/tests/indexes/datetimes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/datetimes/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_date_range.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_datetime.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_freq_attr.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_iter.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_npfuncs.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_ops.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_partial_slicing.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_pickle.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_reindex.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_scalar_compat.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_timezones.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/datetimes/methods/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_asof.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_delete.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_factorize.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_fillna.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_insert.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_isocalendar.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_map.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_normalize.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_repeat.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_resolution.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_round.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_shift.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_snap.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_frame.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_julian_date.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_period.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_pydatetime.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_series.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_tz_convert.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_tz_localize.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_unique.cpython-314.pyc,, +pandas/tests/indexes/datetimes/methods/test_asof.py,sha256=VY7rJDs_XNPjqBISEIDS0YDvfc2qAqh-Ho08m53V8GE,1105 +pandas/tests/indexes/datetimes/methods/test_astype.py,sha256=xX3Tu-WHF5b-8eK3aVmz5cyuRfl-ZS2fyemg5yAac_A,12639 +pandas/tests/indexes/datetimes/methods/test_delete.py,sha256=h9PMD3zvTwhPwGo6dPm7ae2MnvwjmoDC4JZq6RVaHT0,3497 +pandas/tests/indexes/datetimes/methods/test_factorize.py,sha256=qY-bGM1W_7dIyU_-TYY2benbkyp6dp0z1i-D0xuzhHs,5355 +pandas/tests/indexes/datetimes/methods/test_fillna.py,sha256=FqFQkrfHjtaA6azLoirbMsODdc642CwwGcWR7g4shAs,2739 +pandas/tests/indexes/datetimes/methods/test_insert.py,sha256=AKzhkPasSAlwVbcUaa0l8DVXTztduu_1bDfaOlcy4nk,9713 +pandas/tests/indexes/datetimes/methods/test_isocalendar.py,sha256=i0Zmo3YP9GauCEnEQLVS9Xt1cJ8iz4zJbD8uct0IkhU,1429 +pandas/tests/indexes/datetimes/methods/test_map.py,sha256=p58aziDykzJ3oP11X7kQwciolSwVgOGxqve9jpnUp6c,1864 +pandas/tests/indexes/datetimes/methods/test_normalize.py,sha256=FSGSY9w4gEFHMR-z9pxbdJd0WYAantcrzpeC3w0gQlk,3227 +pandas/tests/indexes/datetimes/methods/test_repeat.py,sha256=UtVPgEU22aS6WsxKSwcdiQOk2yw6SvWikWan5u_WGrA,2770 +pandas/tests/indexes/datetimes/methods/test_resolution.py,sha256=jlm5ikAquCtaCuhdvpzQcjYNbqVqMJnVblWixMuS0rU,876 +pandas/tests/indexes/datetimes/methods/test_round.py,sha256=IjcffywEEUDeIZx5j9GeCnc6wCpwRiGO-TgTay0sFDs,9602 +pandas/tests/indexes/datetimes/methods/test_shift.py,sha256=UTAE13UtV-SM9jFxFE06ChXl4xzvPb9WTFTUrOTRngE,6303 +pandas/tests/indexes/datetimes/methods/test_snap.py,sha256=8afsz3vnqolxhcMO7nkxT0CNjgx25lEUZWa85IHzTTM,1564 +pandas/tests/indexes/datetimes/methods/test_to_frame.py,sha256=GmUWtelxPqG6IcB0ThIrLGn6JQmE3SwXX6r_JDWumaE,968 +pandas/tests/indexes/datetimes/methods/test_to_julian_date.py,sha256=qbx7M9Wsx3uDbkGOnEz1Ge1lhKtYxKfvWYcmub_3cH0,2241 +pandas/tests/indexes/datetimes/methods/test_to_period.py,sha256=KyGZPF2irbSHeBjD7bTKCU_FJYFL0QVxjqEYJzHiG4o,10878 +pandas/tests/indexes/datetimes/methods/test_to_pydatetime.py,sha256=o-Wqm-wkIG8fz1SQki1RqDjAtbvXBxahQx1fug6MLvo,1279 +pandas/tests/indexes/datetimes/methods/test_to_series.py,sha256=6QgwN52vK3aqMn0fveE4fmUc83H1bpbQangpyhoP0I0,467 +pandas/tests/indexes/datetimes/methods/test_tz_convert.py,sha256=oksZM4t49_t7vZNsEKfQUiL_IxOtJ_DhpNUMsbs88tQ,17493 +pandas/tests/indexes/datetimes/methods/test_tz_localize.py,sha256=2SSTsZOEB-hEFYDnYx4I-LduiHNqxPTsxVE1sfMLDxM,26251 +pandas/tests/indexes/datetimes/methods/test_unique.py,sha256=D0ESfJND6MeUTqwYOYmwrJsfDeYIQIpW2CNaBzB9KNI,2083 +pandas/tests/indexes/datetimes/test_arithmetic.py,sha256=HYMAAQ0KzfGNlfOFZ5rEGslD42urYMAq1PWoJT5jT90,2537 +pandas/tests/indexes/datetimes/test_constructors.py,sha256=SOy-DcWSaWU8U9_w1F_6liKQVmeR7HWvSQ9Cw1PtlPQ,51585 +pandas/tests/indexes/datetimes/test_date_range.py,sha256=UOGC9gqzO8tU6u4P478VEGBJ7VjVSStR5rj4Ja9HQl0,78846 +pandas/tests/indexes/datetimes/test_datetime.py,sha256=me3KluI9hOLEQh8iPkkZ3Gz5QlPibT4szmNiy9u3LKA,5629 +pandas/tests/indexes/datetimes/test_formats.py,sha256=GmYDx8CNdtu6rWln58h-TG8sxQpo3azWJeOnI3O6bRI,11516 +pandas/tests/indexes/datetimes/test_freq_attr.py,sha256=48mHzNHpjzvELh7H7hsLYUBK92cAvidd0ug9XNmZynA,1683 +pandas/tests/indexes/datetimes/test_indexing.py,sha256=IDhZUvIqj0OjRCcrSC4cp1VcSxNicLPt_WZJ5X2oJak,30453 +pandas/tests/indexes/datetimes/test_iter.py,sha256=CpuXdlGccazgDue5bVqY9iKnn_x382-nU69K_sQAdv0,2559 +pandas/tests/indexes/datetimes/test_join.py,sha256=fKWv4sZZsrErqWJw_Jg_XoUvEaUm7EXggbGLK6but68,6127 +pandas/tests/indexes/datetimes/test_npfuncs.py,sha256=IMv2QrQKJ3vNxA0bvkOCGPd_cZNdRxnTb5MvdnZXan0,377 +pandas/tests/indexes/datetimes/test_ops.py,sha256=aBDPnqB5gwYbemQIz0xrEMN-MLYqJwWjuhPv_sBsESY,1319 +pandas/tests/indexes/datetimes/test_partial_slicing.py,sha256=W0oeud91KYpfZIromKi4SirHAgc5C8reIP6LeHZZv0U,21783 +pandas/tests/indexes/datetimes/test_pickle.py,sha256=LHR8-FmqH4PZzZm-D0pF8QfJuYe4r-WA9ZztExV3poQ,1444 +pandas/tests/indexes/datetimes/test_reindex.py,sha256=sILWxEbkuEifV66gSiz1w-sMNxdfsp6ERQOAoMyIn3M,2196 +pandas/tests/indexes/datetimes/test_scalar_compat.py,sha256=_uDb4Vfeg3KOXsYKQNV76CsLGZrzmGNvlgo8tCJ4SVU,19625 +pandas/tests/indexes/datetimes/test_setops.py,sha256=7BdbM8isruQRY8zkNvZTUSFcsciirh57iplrnLZjqo4,36886 +pandas/tests/indexes/datetimes/test_timezones.py,sha256=cyPSOWi8SRrKR91i5_djPaFj7_G0JQHp8tY3t7NHF-A,7871 +pandas/tests/indexes/interval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/interval/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_equals.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_interval.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_interval_range.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_interval_tree.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_pickle.cpython-314.pyc,, +pandas/tests/indexes/interval/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/interval/test_astype.py,sha256=FloQbbHAvg0azcGxOJI9QxCQU4rj6WsZlrVgAFwTE3w,9243 +pandas/tests/indexes/interval/test_constructors.py,sha256=KiBwdBkR9NcbBu9ThCec1bGJjsgQsJjjB7o2l4wSc9Y,21060 +pandas/tests/indexes/interval/test_equals.py,sha256=_4TtyJ1qQ9pD6X9k5e1oQurKA7YsswhpQBBni584U2Q,1203 +pandas/tests/indexes/interval/test_formats.py,sha256=pc9RGclY_25hL_S95SRPogzSqmTQGZoQY0xtLaFX6j8,3737 +pandas/tests/indexes/interval/test_indexing.py,sha256=UeHZBh4goKTTZ6634mL_z72iUeXmCb7iM_fvPVirl9k,30849 +pandas/tests/indexes/interval/test_interval.py,sha256=O4mX16BT6cINEhBlh9cIHThxMFMEUoqvQMsLXKhOuvk,36234 +pandas/tests/indexes/interval/test_interval_range.py,sha256=j-KgbAc2CbMQe2-35VFbmdXebGbXxn0gjT-hXYV4qoY,14921 +pandas/tests/indexes/interval/test_interval_tree.py,sha256=xueiA1459FNQ9e4t_7EDhumfidfEZ8hvSYyxAnqj634,7999 +pandas/tests/indexes/interval/test_join.py,sha256=oFivhWs-D0QBUY-ljtoSo_lwU1WVN1EgK-4qHhBFbWI,1106 +pandas/tests/indexes/interval/test_pickle.py,sha256=2zvVJNlFcuy8zFitgUljZqQvQMZerKc5AhRa7QwEZpk,366 +pandas/tests/indexes/interval/test_setops.py,sha256=VK0wVmUaXgJEXdcrxtbMNN6fZ2yuuA_A2iTTHrLVzQM,8358 +pandas/tests/indexes/multi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/multi/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_analytics.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_compat.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_conversion.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_copy.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_drop.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_duplicates.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_equivalence.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_get_level_values.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_get_set.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_integrity.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_isin.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_lexsort.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_missing.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_monotonic.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_names.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_partial_indexing.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_pickle.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_reindex.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_reshape.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_sorting.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_take.cpython-314.pyc,, +pandas/tests/indexes/multi/__pycache__/test_util.cpython-314.pyc,, +pandas/tests/indexes/multi/conftest.py,sha256=YDesA4Lcl1hyvmQjZpy4L1ldReSyicUaUjz89iIbUL4,677 +pandas/tests/indexes/multi/test_analytics.py,sha256=WUdolD0IB2oT1fdc7gluJfd0X12X2SgFzFEzl4XzmQw,8274 +pandas/tests/indexes/multi/test_astype.py,sha256=YmTnPF6qXwvYY82wZfQ8XFwVwOYYsIls3LSrdADDW-4,924 +pandas/tests/indexes/multi/test_compat.py,sha256=xX8OV2kj_pCTuavC3ImVBbR5zuJNuRtjTNyh6a6gXtA,3897 +pandas/tests/indexes/multi/test_constructors.py,sha256=yH6g1Kn3dIkclA5VvPAUP7lrJMwrYAnHL6PtV31InMA,28273 +pandas/tests/indexes/multi/test_conversion.py,sha256=k59WW9c1CS2jwAv0YxoDNIbir9g4xQhdp1Rt0NEAnnw,6167 +pandas/tests/indexes/multi/test_copy.py,sha256=ClJM1zl4jT2y9rBQSJFTbKKhjOII9Sh0YXXgIm7TEPU,2407 +pandas/tests/indexes/multi/test_drop.py,sha256=BquWeYqNc4IDa7qTa1SMnT0KkuxUdHZDVrF9IteGs-A,6159 +pandas/tests/indexes/multi/test_duplicates.py,sha256=7M13W0IOcMaeK_dmCe097xNiG-NUaeJxxq7Q1lFNrGA,12358 +pandas/tests/indexes/multi/test_equivalence.py,sha256=p8jUi81IuRflwC0ifVIfFNC9Nmc9ABcOtEnTAEHQ6hU,9207 +pandas/tests/indexes/multi/test_formats.py,sha256=w1aEunqmvTYmgGP212bSYYeGnqd1Hs-lDDD4WMwSefo,8299 +pandas/tests/indexes/multi/test_get_level_values.py,sha256=54RE70Uajj7zSz489NMBR5f4kJ4H2wy6m0hZfGfnLk0,4246 +pandas/tests/indexes/multi/test_get_set.py,sha256=nOzE61dvs6tYMSxpYzAlYCJiB6fyJ05qm9DsL-q_Gb0,14160 +pandas/tests/indexes/multi/test_indexing.py,sha256=wBKNs0sjxiDKtskiBgKy2e5MNhte-KRr_O_gOt3Bp9c,63460 +pandas/tests/indexes/multi/test_integrity.py,sha256=CTCNEj0vUGqSnZku7hCMre4SBSGv9kEe4Z5Mdbs21JM,8958 +pandas/tests/indexes/multi/test_isin.py,sha256=yKuFVY9fxb8muoHXgVU1thcj_04OXwjfvC47We7vfvw,4663 +pandas/tests/indexes/multi/test_join.py,sha256=GHVTCNwC3IyuzeHk0OjUB9XOHH1Mar0mjZb-8YNd2_0,8705 +pandas/tests/indexes/multi/test_lexsort.py,sha256=qf5PG3CNrieBNrBycS9Pf-7YrwfHvappakBkTbejYU0,1366 +pandas/tests/indexes/multi/test_missing.py,sha256=jz86wyeWzwHPJUc-dhejo5Lki0278e7_AcZOd1RxUy0,3361 +pandas/tests/indexes/multi/test_monotonic.py,sha256=pjMerJs4oa4RSkkJ7drJAlQXFVJ11r3x_jjWN6SvJw0,7109 +pandas/tests/indexes/multi/test_names.py,sha256=bsksY4H68nNAg9vFt1Oq2YqgfaZY8Vj0PwTVxSXJXMo,6618 +pandas/tests/indexes/multi/test_partial_indexing.py,sha256=q2uhDM1FrA7Um6GvzO1BmSTUtxxH8L09y12JYUElhLk,4717 +pandas/tests/indexes/multi/test_pickle.py,sha256=GIVgZ2Pn87gwc1c2VpR0eBWcv0Hx5c3dEUadunBPWNM,768 +pandas/tests/indexes/multi/test_reindex.py,sha256=oGXeQ6LQ6k-5pAcrOH7VK1hyshquZcJh-dKll8czKls,6316 +pandas/tests/indexes/multi/test_reshape.py,sha256=sWbZZ4r7QEqcJWF2PHC7A1nCNL8vE7DmYRK8lWb-CDI,7376 +pandas/tests/indexes/multi/test_setops.py,sha256=Ec_259jmhyB4nSvpDwV1cco3L29T__y1gEes8cimcUM,28656 +pandas/tests/indexes/multi/test_sorting.py,sha256=YipYjhW5bKNDFhDqGLvl9BMyudRf0rsMxqcS7mih2aY,11191 +pandas/tests/indexes/multi/test_take.py,sha256=p-TutbGbH-SV30IAB4OOarAZnu-gbBZ2CrndSEke_uI,2176 +pandas/tests/indexes/multi/test_util.py,sha256=zp9tqhnIE5XyNHPCfvkog8Kyb1mwrH_NNo0ZVCxSRBA,2305 +pandas/tests/indexes/numeric/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/numeric/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_numeric.cpython-314.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/numeric/test_astype.py,sha256=M3PZ1vE8o8XedaTGfB7BtmQhzqntQGCswMiExEVHnTw,3623 +pandas/tests/indexes/numeric/test_indexing.py,sha256=IJ27FFV9gGakV66sGLnZXMIInE1KiXsXEyT7S9ZUhFk,23957 +pandas/tests/indexes/numeric/test_join.py,sha256=jEnNYOB5yQxpTAYuONbmMYsI36QGV0c5FnSLTGud1ao,14982 +pandas/tests/indexes/numeric/test_numeric.py,sha256=jOSIUkGGIuu53pT1g-crb_WC1-aX15qsZtwrCAxkaVo,18771 +pandas/tests/indexes/numeric/test_setops.py,sha256=T_kyqidaQr71wnpjxSi4_FFRMY4LpfIELqPFZLhlB8g,5996 +pandas/tests/indexes/object/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/object/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/object/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/indexes/object/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/object/test_astype.py,sha256=Fq6u8MHTi12J3wOXvTOtR7eYNVjgg3lVyMl6_3m_AgA,351 +pandas/tests/indexes/object/test_indexing.py,sha256=aLVOmsT2NU3tY0M-TEOvsMk2Yge1Kt_JfS5Av8DETwg,8730 +pandas/tests/indexes/period/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/period/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_freq_attr.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_monotonic.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_partial_slicing.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_period.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_period_range.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_pickle.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_resolution.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_scalar_compat.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_searchsorted.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/period/__pycache__/test_tools.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/period/methods/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_asfreq.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_factorize.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_fillna.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_insert.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_is_full.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_repeat.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_shift.cpython-314.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_to_timestamp.cpython-314.pyc,, +pandas/tests/indexes/period/methods/test_asfreq.py,sha256=JRx0dQ3DO3muJKipy1nKxwSMS5yXjbAUVjiu-Pcvl5w,7181 +pandas/tests/indexes/period/methods/test_astype.py,sha256=xGsBnOhp9_gEBiW-GOqz_8W0_QTT7rCVe6-ROlygmOg,5787 +pandas/tests/indexes/period/methods/test_factorize.py,sha256=Enae4uc-Q7z7yXZY2zv1QdDafm9_rQS2yowLn0mUB_Y,1429 +pandas/tests/indexes/period/methods/test_fillna.py,sha256=OAzPivlcW0EsaBf25BPL5OVgHfZuNBtOgAUSUm8DesA,1443 +pandas/tests/indexes/period/methods/test_insert.py,sha256=XJ72Jq7Zp03pJsD2Oy-7f-ZqFiBU2eSOkW9MAbzzWD8,469 +pandas/tests/indexes/period/methods/test_is_full.py,sha256=b9jmgPo78ipe3nVz-cQbUZb-uws8rj_icOhqfanfaok,870 +pandas/tests/indexes/period/methods/test_repeat.py,sha256=0N9y4bvNUpKwDHlKmpSLaceIWJXSZooSf1Mk_YpBmLk,746 +pandas/tests/indexes/period/methods/test_shift.py,sha256=6QhJZrge0PCgF-hqQRAu0IhegO_8D3zuj7ilIbux4-U,4439 +pandas/tests/indexes/period/methods/test_to_timestamp.py,sha256=FpnUpX4vvY20o89FWlk7pDW01Fg1jD95g2A6E_k0PhY,7504 +pandas/tests/indexes/period/test_constructors.py,sha256=FVMlYptb9s4tr_NqgxZUvUTzaINtTAi2jNi1NeSTCq8,35643 +pandas/tests/indexes/period/test_formats.py,sha256=OuPzVE-mX8ac1WtkkgBi7-iOULKDu6RWdPAvhhDXb30,6459 +pandas/tests/indexes/period/test_freq_attr.py,sha256=r1p_fh5dJt4K60LumxcqIAkd-OHqGSYkUMYQiHSt7II,535 +pandas/tests/indexes/period/test_indexing.py,sha256=EQXKwkiZl8Uah5hUmtvLh3IufBdtv9CgfU2DdM5MikI,28047 +pandas/tests/indexes/period/test_join.py,sha256=aHTeUtcMsGTInz1G_b06Cyu0BrjbmzUFf9eKXGh9f14,1744 +pandas/tests/indexes/period/test_monotonic.py,sha256=bad4sHMQCW93kUt81XBBBwn8COKSNTkWfQGgGofZzeg,1274 +pandas/tests/indexes/period/test_partial_slicing.py,sha256=RpO2kSSgTpyvyvhPtkS0HSO04mij4cDqbwNmBFnIIDM,8606 +pandas/tests/indexes/period/test_period.py,sha256=TTRjLmd3TOdmKzUF-xNkNWSSJ_44jXDFQitp0UkrHsI,8299 +pandas/tests/indexes/period/test_period_range.py,sha256=QHLzNgrHEHvob1l2ajXfWfSm54FTSaAbKfkHJvAJg3k,9064 +pandas/tests/indexes/period/test_pickle.py,sha256=jYdfNk6tq-6NkRiUBiBihwaQxAakCXs4ixMg8Op14Q0,698 +pandas/tests/indexes/period/test_resolution.py,sha256=0TmnJeZCOaTWneeWA66DlxKgaUZJTfP0jKgLAY1jiyg,571 +pandas/tests/indexes/period/test_scalar_compat.py,sha256=I2TU8sXDpFRkywOpqJcS67BEoeg4GtX16JUh_eyJxKs,2314 +pandas/tests/indexes/period/test_searchsorted.py,sha256=RikUuovyQdR7Q_gc38XNZw5WpUKLPr6LgMcjOigWl3U,2460 +pandas/tests/indexes/period/test_setops.py,sha256=wWzsqUfrsZUz08ifPsNVALms6Au_8gvfGUHX3xSTnIk,12590 +pandas/tests/indexes/period/test_tools.py,sha256=rtQ-SPsQOkscns-SJkD4VVyTNTgAIH9pI6e6TeLdqtI,1325 +pandas/tests/indexes/ranges/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/ranges/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_range.cpython-314.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/ranges/test_constructors.py,sha256=Mf_i4cFUWIGIesobNEKnd9o413_pjhCxk7-02IYJ6eE,7438 +pandas/tests/indexes/ranges/test_indexing.py,sha256=X0-i9LzNmVt2NlWeeoilofwhu49QqgyOIYK1CRQRtAE,7698 +pandas/tests/indexes/ranges/test_join.py,sha256=0EtkQEoM04aigr6Lo8LjTNeUURFlJ8L42vRw57thybw,11546 +pandas/tests/indexes/ranges/test_range.py,sha256=Z9uhSEsCXd8uigy-mrANQMcXz5OuGBFhUN9y2VB-WxI,31614 +pandas/tests/indexes/ranges/test_setops.py,sha256=u0ZQL_JbnRdkBI2MEzAIlEkc8T9mamheUsuxOFE7FO0,18879 +pandas/tests/indexes/string/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/string/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/string/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/indexes/string/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/string/test_astype.py,sha256=oC76hxl1fKP7zNOqOaSguuMrkjZjLWl_awyvlM_8EQ8,708 +pandas/tests/indexes/string/test_indexing.py,sha256=q27FFthdUQOXOpIl6_cKYvuaMDsW5VToUvMCXrDCLwU,7483 +pandas/tests/indexes/test_any_index.py,sha256=5m1t4k9BbenqOpngYtsJ0OKp3sn2XxJJMzkWAUZDH2c,5495 +pandas/tests/indexes/test_base.py,sha256=ZB-FcR-GnsQYqAgTwlBhaWeP_k3F0IzhPp1oj4Mw6R4,69926 +pandas/tests/indexes/test_common.py,sha256=bB8xnH47i8lMeYvRtMVFmP3uezPJlQcVU3Skk_eN5bg,18673 +pandas/tests/indexes/test_datetimelike.py,sha256=M4gYXwvf_4yRUE24VmGRH2uREENQ8qdWvVBZKuKSM1U,5305 +pandas/tests/indexes/test_engines.py,sha256=rq3JzDXNc2mZS5ZC2mQLpTeydheOX9OLoq1FLR53wbI,6699 +pandas/tests/indexes/test_frozen.py,sha256=lxYJsV1jpfhyn3lUmX_e5WTNr2YofPrgoWlHZvx47XM,3221 +pandas/tests/indexes/test_index_new.py,sha256=ZsmUucnk3kU8QZR5Unn4K4w2vbffJ1cxdw6d_fBaRBI,15571 +pandas/tests/indexes/test_indexing.py,sha256=TjVSLmIDHJKEuLmM9XlcDqpT_I9xKKPiRScGnEdMO3I,16230 +pandas/tests/indexes/test_numpy_compat.py,sha256=ueFU2efMOHuaHxopBI5BTqEB2n7mF3Uu7g4AxV2Af6w,5707 +pandas/tests/indexes/test_old_base.py,sha256=3WGRM179GolTSgKsPHbFXHzduo-OqGg3Vo1eCYgnV2E,37817 +pandas/tests/indexes/test_setops.py,sha256=i0yMPEn1Y5xk4MNT52CofGi_8mKl0qtGHVadq2Nc9b4,35234 +pandas/tests/indexes/test_subclass.py,sha256=hY1YNjOmQi5Q93K3ZURDZOD8OfORwtHif33m35uk_Fo,1042 +pandas/tests/indexes/timedeltas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/timedeltas/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_delete.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_freq_attr.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_ops.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_pickle.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_scalar_compat.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_searchsorted.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_setops.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_timedelta.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_timedelta_range.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/timedeltas/methods/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_factorize.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_fillna.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_insert.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_repeat.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_resolution.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_shift.cpython-314.pyc,, +pandas/tests/indexes/timedeltas/methods/test_astype.py,sha256=D_W3JLGA8iIDuENsOste864sYGPMJdwkY_4jUhxhutE,6437 +pandas/tests/indexes/timedeltas/methods/test_factorize.py,sha256=JXiv1rGX2m1yoDEfw-uMMNI6Wp7Hji4HqEoURGbDF98,2032 +pandas/tests/indexes/timedeltas/methods/test_fillna.py,sha256=sE-D1EHQ5M4BvP9NKcnnJW_aXj_ICTvdTBqthCY2jng,800 +pandas/tests/indexes/timedeltas/methods/test_insert.py,sha256=eT5Kn8d_wxHGZnNdh4KzJiVqn6VmRcxeZ364ejINSgo,4804 +pandas/tests/indexes/timedeltas/methods/test_repeat.py,sha256=TWrot98yFEcLuXFX-oUiWZibpEk0rP_54MFrWW9aRzU,894 +pandas/tests/indexes/timedeltas/methods/test_resolution.py,sha256=uwYTAJVYuRxBscmsskHrHsYn2qTACsh_WNDTd-QPMZo,741 +pandas/tests/indexes/timedeltas/methods/test_shift.py,sha256=eMB6pfDtCcb6fi7t6O-1NdzDdGn11c8ToUWwW81013A,2808 +pandas/tests/indexes/timedeltas/test_arithmetic.py,sha256=3KtaEKQZ9ERkOUUBj9QVNeyivweMNXtWOdQnPtngtN4,1525 +pandas/tests/indexes/timedeltas/test_constructors.py,sha256=zaN2BeFteE6h_CxTfuwIhpE1rStlvzl2YmmzrhJl2ss,9854 +pandas/tests/indexes/timedeltas/test_delete.py,sha256=z9oxRJnVSwKQwWRM_t3b_o8CLqwP8mGjdIQqyvvmdGc,2425 +pandas/tests/indexes/timedeltas/test_formats.py,sha256=y8F5CNNXls8iOBuU_U0ErwfYWDvK-e4XQjtNvwOg6xo,3959 +pandas/tests/indexes/timedeltas/test_freq_attr.py,sha256=oNDCUy8CPnOoFIsehBlZIAVOxsw-QuJbOXjqCXVvN3A,2059 +pandas/tests/indexes/timedeltas/test_indexing.py,sha256=GhKSHcnTMc_v3lMoYavcInZWUC63UmZ0VmlphwXO_2A,20764 +pandas/tests/indexes/timedeltas/test_join.py,sha256=kUBOMoz8zPFoPNP3F9XJ1vD6viX2JHkH0nMojAFLCkg,1374 +pandas/tests/indexes/timedeltas/test_ops.py,sha256=OniSy3fHblZXUzvwnmlZWRdvpvlwnqKnfX5zJdEf8eE,355 +pandas/tests/indexes/timedeltas/test_pickle.py,sha256=RqcqQXi0Fnv3W-_kpsV4VYnQPQxhko4BV6RicQEKADU,312 +pandas/tests/indexes/timedeltas/test_scalar_compat.py,sha256=Ipmtvew0RjWXxHlZ97BGkgONIzBoyvW4xNSqcSy_j4w,4841 +pandas/tests/indexes/timedeltas/test_searchsorted.py,sha256=CqBcusng3X9HEGYe-8ZFscqmVDKCpWLG4Q-HgiSATQA,947 +pandas/tests/indexes/timedeltas/test_setops.py,sha256=XqQ-zVJIfP5k1po9DN0hL1IEy_WF7CjQJCun4KNMVXw,10781 +pandas/tests/indexes/timedeltas/test_timedelta.py,sha256=Z2s2pJMeEst6rBka84vIqtsjuni2vQIaLWk65WmuU90,1942 +pandas/tests/indexes/timedeltas/test_timedelta_range.py,sha256=hYHtIkn9tzxZE0HMmB4P0tftpYh9qqAMWYMI5O-nj9M,6905 +pandas/tests/indexing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexing/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/common.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_at.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_categorical.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_chaining_and_caching.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_check_indexer.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_coercion.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_datetime.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_floats.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_iat.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_iloc.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_indexers.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_loc.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_na_indexing.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_partial.cpython-314.pyc,, +pandas/tests/indexing/__pycache__/test_scalar.cpython-314.pyc,, +pandas/tests/indexing/common.py,sha256=lS9CUBwhlyWFtosnA3XoI8IKckguhvQB8tfd738ql0M,1020 +pandas/tests/indexing/interval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexing/interval/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexing/interval/__pycache__/test_interval.cpython-314.pyc,, +pandas/tests/indexing/interval/__pycache__/test_interval_new.cpython-314.pyc,, +pandas/tests/indexing/interval/test_interval.py,sha256=nEnWO62T3WAtypC3IWL528saX4yVFDAAiy4OonimYJY,8559 +pandas/tests/indexing/interval/test_interval_new.py,sha256=5bGOXxgycjK7Ypq7FeMjja_wLDX0T52MYvptGOwwS00,8131 +pandas/tests/indexing/multiindex/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexing/multiindex/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_chaining_and_caching.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_datetime.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_getitem.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_iloc.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_indexing_slow.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_loc.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_multiindex.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_partial.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_setitem.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_slice.cpython-314.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_sorted.cpython-314.pyc,, +pandas/tests/indexing/multiindex/test_chaining_and_caching.py,sha256=I8y9zTAr0dBeehMRQo7ZHnpvclmLF2DE33axTkvWmqI,2747 +pandas/tests/indexing/multiindex/test_datetime.py,sha256=Pm-T1OKlBq4knoYLJCXfkUOycjIFrE6xtepRHra8IaE,1179 +pandas/tests/indexing/multiindex/test_getitem.py,sha256=t6Xpx--WnzcH-Ef0mtuP5g_pfuvmEMjB6loA5TfPBjs,13463 +pandas/tests/indexing/multiindex/test_iloc.py,sha256=SDVZJ_zo-rzsEmEX6R5unfj8yyCuTWvEfyVyVZgwCC0,4973 +pandas/tests/indexing/multiindex/test_indexing_slow.py,sha256=93ViMPh0fmm7--PXHWzu9Z-_paJ2pg4xgyApWoqA-zE,3140 +pandas/tests/indexing/multiindex/test_loc.py,sha256=JBb2-nWEtQUFFTEsWuAWA5Cu5ZDtjansgvDf4zlY7i8,38729 +pandas/tests/indexing/multiindex/test_multiindex.py,sha256=C0ukbPFkFh7xgYrhA6zMH08MT_v2YVpGrbXyww9y0V8,11598 +pandas/tests/indexing/multiindex/test_partial.py,sha256=veuLJpby0CRlDGTV_RaurkAwOaQEnTL9W5OpHwqRwhs,8349 +pandas/tests/indexing/multiindex/test_setitem.py,sha256=BSl60t-qTKWghoH8-43UKUHkuUO1ycGw-UcG7f6hsDc,25035 +pandas/tests/indexing/multiindex/test_slice.py,sha256=92Yr3GVauIgFOXCXeCmA_AxND_XfTsDtJHEEMHcB0NM,27434 +pandas/tests/indexing/multiindex/test_sorted.py,sha256=yaNVA3Zt6ATqkTMwd6LEeZzKQlHHi4GTHU87yMZz628,5264 +pandas/tests/indexing/test_at.py,sha256=DqzA5DyeR6h2FILpzg4yE3s0Ta4lmILA3Y79-AqwSYo,12890 +pandas/tests/indexing/test_categorical.py,sha256=-uET1ry-vLm6J0PauXIaWfIBLz5KHADAF-fPHJn20Fk,21148 +pandas/tests/indexing/test_chaining_and_caching.py,sha256=1mMSYZVbetKLyt1KTSPEwVJ5mLLhvxv0PQgw24HTgMQ,12484 +pandas/tests/indexing/test_check_indexer.py,sha256=tfr2a1h6uokN2MJDE7TKiZ0iRaHvfSWPPC-86RqaaDU,3159 +pandas/tests/indexing/test_coercion.py,sha256=iC7fBwIR0jMY6gyj5XAceWhtFOB2Nt_tY83TnPgjC7k,31302 +pandas/tests/indexing/test_datetime.py,sha256=8rTBrbJuyO3Ah83AxBWqP9hKdOqkQV7brNzYHIIKH5w,6456 +pandas/tests/indexing/test_floats.py,sha256=NZeeX_4vs9wwXPK3G614-IzDDD34GQ3FU-QelOx8VX4,20185 +pandas/tests/indexing/test_iat.py,sha256=maJ9pRi1sTRT5tRJyBTatnVmT6B-uEhdvhDnNny1O-g,778 +pandas/tests/indexing/test_iloc.py,sha256=jTEE2aJMZcWW-aUt5GhsqWipG_bZ00QvWWbV5lQkMKo,93400 +pandas/tests/indexing/test_indexers.py,sha256=uBE0HzTrHN3zwTACjcLQGq7V92qJIV__7fSZTZC6Des,3435 +pandas/tests/indexing/test_indexing.py,sha256=rijcDRSiLmAjQbGIsRy0X-ct9l5bwHITcyVu1W2rsvQ,45475 +pandas/tests/indexing/test_loc.py,sha256=4XdmeUbjnRulW58hmX7zf_GKB4vWKspz6JrD2jrSbQA,156553 +pandas/tests/indexing/test_na_indexing.py,sha256=IZmiYBUUQrmILzd3lE0AiLwyBQHTmpbdKU4LhrW5a7o,2276 +pandas/tests/indexing/test_partial.py,sha256=wWTLSOdmWr-6g2zdlgptvMru3-eXc5s4DXwQCWIRXw0,26295 +pandas/tests/indexing/test_scalar.py,sha256=XDM29YBRGMXkl0IsmWCyjl5lAQgqSWI8da94F0M9G4U,9802 +pandas/tests/interchange/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/interchange/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/interchange/__pycache__/test_impl.cpython-314.pyc,, +pandas/tests/interchange/__pycache__/test_spec_conformance.cpython-314.pyc,, +pandas/tests/interchange/__pycache__/test_utils.cpython-314.pyc,, +pandas/tests/interchange/test_impl.py,sha256=RTaEa97Czf3QcXGr6pKxFl33Doffz6UZw_Tnw4OSm8c,25033 +pandas/tests/interchange/test_spec_conformance.py,sha256=_5mi7XG3_hx4T-6jZneptZSWkRYP3LkCV3YjWKpkWTw,6445 +pandas/tests/interchange/test_utils.py,sha256=15liIDJirQDoP7TxxQkmZJ9gCAVNCd2BwShW_GlwL2A,2965 +pandas/tests/internals/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/internals/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/internals/__pycache__/test_api.cpython-314.pyc,, +pandas/tests/internals/__pycache__/test_internals.cpython-314.pyc,, +pandas/tests/internals/test_api.py,sha256=y_L-6pdpFZhSHX8yAS0X4eBLntNhNV5gRbqUiem1ARI,5461 +pandas/tests/internals/test_internals.py,sha256=4rMMt_eWVCb3F99Wr4nS99V_ASRZX7z85jpMBnd_lFg,56491 +pandas/tests/io/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/io/__pycache__/generate_legacy_storage_files.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_clipboard.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_common.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_compression.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_feather.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_fsspec.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_gcs.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_html.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_http_headers.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_iceberg.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_orc.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_parquet.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_pickle.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_s3.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_spss.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_sql.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_stata.cpython-314.pyc,, +pandas/tests/io/__pycache__/test_util.cpython-314.pyc,, +pandas/tests/io/conftest.py,sha256=mpkTphWZp1zE4tsDPW__AV2pE2uz1IR1mIUiFUvbYGU,4778 +pandas/tests/io/excel/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/excel/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/excel/__pycache__/test_odf.cpython-314.pyc,, +pandas/tests/io/excel/__pycache__/test_odswriter.cpython-314.pyc,, +pandas/tests/io/excel/__pycache__/test_openpyxl.cpython-314.pyc,, +pandas/tests/io/excel/__pycache__/test_readers.cpython-314.pyc,, +pandas/tests/io/excel/__pycache__/test_style.cpython-314.pyc,, +pandas/tests/io/excel/__pycache__/test_writers.cpython-314.pyc,, +pandas/tests/io/excel/__pycache__/test_xlrd.cpython-314.pyc,, +pandas/tests/io/excel/__pycache__/test_xlsxwriter.cpython-314.pyc,, +pandas/tests/io/excel/test_odf.py,sha256=zoXUYoeWb-5df1tz01I0IMswdOJoFBNPerUkmHAusug,4926 +pandas/tests/io/excel/test_odswriter.py,sha256=wF644m6wx7tJzd3pVVsuea_EGLO_tJqK26tidqFMv6M,4394 +pandas/tests/io/excel/test_openpyxl.py,sha256=cxGJ-Blu_Z1b1V45gvH7nDNmXoleF379sA_vgbr-WR4,20345 +pandas/tests/io/excel/test_readers.py,sha256=GNHzOdD1TqvzIYaTnFxkUMI0194BHy6yv1vaJUifgN4,70485 +pandas/tests/io/excel/test_style.py,sha256=5BDgby5ukEV0HhmC9Md5HJnod1OduUrYtyh5v58RkTc,13605 +pandas/tests/io/excel/test_writers.py,sha256=SDSdAUsYn8UarWFWBcMgBCAunpbo-0yPV1QYvLCA5Ck,64878 +pandas/tests/io/excel/test_xlrd.py,sha256=xMUT5b8Fm_soWBv1P92-meLX0E9zPJt3xp6YB4QWHRs,3367 +pandas/tests/io/excel/test_xlsxwriter.py,sha256=h4IprL2olo2Eh2Iu6ZRyrdUN8sHZSiOqMiECYV1QG98,2553 +pandas/tests/io/formats/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/formats/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_console.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_css.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_eng_formatting.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_format.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_ipython_compat.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_printing.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_to_csv.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_to_excel.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_to_html.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_to_latex.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_to_markdown.cpython-314.pyc,, +pandas/tests/io/formats/__pycache__/test_to_string.cpython-314.pyc,, +pandas/tests/io/formats/style/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/formats/style/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_bar.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_exceptions.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_format.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_highlight.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_html.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_matplotlib.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_non_unique.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_style.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_to_latex.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_to_string.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_to_typst.cpython-314.pyc,, +pandas/tests/io/formats/style/__pycache__/test_tooltip.cpython-314.pyc,, +pandas/tests/io/formats/style/test_bar.py,sha256=mhxA9qOiU9mhweGR7dOA1GoCcrZFbq4oh9WWpAil4SA,12206 +pandas/tests/io/formats/style/test_exceptions.py,sha256=XIMiRp96ftdqdJ2ciNi8tWeXX7QG-cj4aCRN2kZMdaE,980 +pandas/tests/io/formats/style/test_format.py,sha256=9tQ85pWPwdQKBju-k6_MNh0PbJZKngKxuKDbym-3FN8,25903 +pandas/tests/io/formats/style/test_highlight.py,sha256=L7bYjLQcZJ8eI5XQbymXy0Bg35oobLDy5NJVpqt0wBU,6985 +pandas/tests/io/formats/style/test_html.py,sha256=-GOBHN3hyIy7bHohzXLCwP5ESHzAGviH2OdHrlqxeAg,34074 +pandas/tests/io/formats/style/test_matplotlib.py,sha256=-JE1YMLD2tRpqokibFtoEbN3IWpJpM5XUNBH9pm8d4Q,10864 +pandas/tests/io/formats/style/test_non_unique.py,sha256=N41bSqJvQ1aCSxmRDYFbuqjb4j9cpr7hBHIbCy5jtU0,4398 +pandas/tests/io/formats/style/test_style.py,sha256=3CWDKGOUk485_cLNLnUBREq4OEvoiucWqcs7PgCTtyc,59282 +pandas/tests/io/formats/style/test_to_latex.py,sha256=SUZ2AMK_g1FfauFTPxP-5iOPPT0y61VENMUa9-3Q6sI,33555 +pandas/tests/io/formats/style/test_to_string.py,sha256=R48TCo92k3ImhZFqxC4177WJ4C4WNEU6NwC_-Ddv3W4,1886 +pandas/tests/io/formats/style/test_to_typst.py,sha256=wK2Tn3WtahwSPU-bJiRwnKoc5sr3wpS662Af6SmzZoM,6732 +pandas/tests/io/formats/style/test_tooltip.py,sha256=E8-22hGgsz6x06Z-6GxscvKNA2WsV4z9vA4kMR2aZmQ,7321 +pandas/tests/io/formats/test_console.py,sha256=jAk1wudhPiLBhhtydTNRlZ43961LqFu3uYt6cVA_jV0,2435 +pandas/tests/io/formats/test_css.py,sha256=IUW49HPLPWK_uhFaRCSXHko8JZhw4YkZ_EbKqk1XayE,10266 +pandas/tests/io/formats/test_eng_formatting.py,sha256=MC5BzYrbv3cNJnyIgoGFbXfWL8q0Io7WWyVM4-0oruk,8929 +pandas/tests/io/formats/test_format.py,sha256=iSbpraWCoETfLKeBeVh04lBcfakEn5MlLpdDD_wTekU,90414 +pandas/tests/io/formats/test_ipython_compat.py,sha256=oxMllU62yzZCQHq26antb3y_V3CSTg4KOgPe8F6Boxg,3312 +pandas/tests/io/formats/test_printing.py,sha256=kFEaui9y-ExJagejAdVY8Pmw0yi7he-ae6IvHsfIc90,7290 +pandas/tests/io/formats/test_to_csv.py,sha256=nVMmGCjw7Q941IxzmcTqa2IovC1o5FkqJ4KAYgOSZdI,39542 +pandas/tests/io/formats/test_to_excel.py,sha256=FAr9Pl9XpNwYFpZZAm56mOmEnAWi-ctw6hVuHAcnBCc,16811 +pandas/tests/io/formats/test_to_html.py,sha256=p-LhJ9fSbB7z6heHgqx2RQeROXXufPwrkZ2qCjoGgW0,38761 +pandas/tests/io/formats/test_to_latex.py,sha256=-8Da11mtjSk6Ft7n6Hu9Bk6iN0uTPbsLumRNilrGoC0,44839 +pandas/tests/io/formats/test_to_markdown.py,sha256=HDmvYFMZWPnzwps5ubX2XHUf-8EVel_dTcY34h7YXn8,2690 +pandas/tests/io/formats/test_to_string.py,sha256=VXg47u2hZsqewqzd32mmuylqee7y1cM1kfdnXxwXZCk,41647 +pandas/tests/io/generate_legacy_storage_files.py,sha256=dzYBnB6u9DI4rIfC4TKgS6NMtkbVe4MRGfxDV8989G0,13122 +pandas/tests/io/json/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/json/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/json/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/io/json/__pycache__/test_compression.cpython-314.pyc,, +pandas/tests/io/json/__pycache__/test_deprecated_kwargs.cpython-314.pyc,, +pandas/tests/io/json/__pycache__/test_json_table_schema.cpython-314.pyc,, +pandas/tests/io/json/__pycache__/test_json_table_schema_ext_dtype.cpython-314.pyc,, +pandas/tests/io/json/__pycache__/test_normalize.cpython-314.pyc,, +pandas/tests/io/json/__pycache__/test_pandas.cpython-314.pyc,, +pandas/tests/io/json/__pycache__/test_readlines.cpython-314.pyc,, +pandas/tests/io/json/__pycache__/test_ujson.cpython-314.pyc,, +pandas/tests/io/json/conftest.py,sha256=Zp83o90PvZ56MbhNRr1NZEPTpho7jRHcLYiEA9R_BZw,205 +pandas/tests/io/json/test_compression.py,sha256=jdE5JG9Vq9Y83IZZbg-iI0KmTAMvKPUiGVTv-Q8xO1E,4014 +pandas/tests/io/json/test_deprecated_kwargs.py,sha256=Il6ipNRHvrrkER_7BrnQXg3HU8h9pe-5VCXWqDKEn9Q,1767 +pandas/tests/io/json/test_json_table_schema.py,sha256=ozNmX3LwMQ3c48fhwnYTcRZz05n5-RLQiT6tkNMTHQA,32553 +pandas/tests/io/json/test_json_table_schema_ext_dtype.py,sha256=LZso4A1unaYI3TmYo7rt9UTvyKbwUGxR-0jRSJ5icf4,9329 +pandas/tests/io/json/test_normalize.py,sha256=-FIBVQtMmFxdO1YIpDuL4lo40Khk9kE8vCAfag99_Ok,32794 +pandas/tests/io/json/test_pandas.py,sha256=l1hlozby0It4bJ3bmp63DD3Gw-ibkv26NwYmkCsCBjI,104370 +pandas/tests/io/json/test_readlines.py,sha256=uMSH7jfHqYCw9WaEKG8tpK2s3X2AnMeaEzXWewhJ8AU,27578 +pandas/tests/io/json/test_ujson.py,sha256=KeVqOMlmVXY9uIynvB0R9yqouBOtGB4Sr7SWwbliVAw,46559 +pandas/tests/io/parser/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/parser/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_c_parser_only.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_comment.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_compression.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_concatenate_chunks.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_converters.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_dialect.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_encoding.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_header.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_index_col.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_mangle_dupes.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_multi_thread.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_na_values.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_network.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_parallel_read.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_parse_dates.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_python_parser_only.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_quoting.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_read_fwf.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_skiprows.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_textreader.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_unsupported.cpython-314.pyc,, +pandas/tests/io/parser/__pycache__/test_upcast.cpython-314.pyc,, +pandas/tests/io/parser/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/parser/common/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_chunksize.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_common_basic.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_data_list.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_decimal.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_file_buffer_url.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_float.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_index.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_inf.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_ints.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_iterator.cpython-314.pyc,, +pandas/tests/io/parser/common/__pycache__/test_read_errors.cpython-314.pyc,, +pandas/tests/io/parser/common/test_chunksize.py,sha256=03ni9MxE9BOwHFQKoaO7GQcbu7c8FIbKOljD59Ua42A,15088 +pandas/tests/io/parser/common/test_common_basic.py,sha256=KYr03RcHsYYZu-mqXWehYcdCN3lbYQYi_L3gejuWTHU,31555 +pandas/tests/io/parser/common/test_data_list.py,sha256=RlaIu_zyr0M9h1xC-xETBpEgwljGabAmrgdi7w_uqPA,3126 +pandas/tests/io/parser/common/test_decimal.py,sha256=_eGbq0ECFZ_jx4I3evxZqGFaoQu9UgoLS4x30RlNhJY,3094 +pandas/tests/io/parser/common/test_file_buffer_url.py,sha256=IR4UnhcSgJ1-9aky9iAseG3wXHQogVxbxJSFdKCAPsY,13501 +pandas/tests/io/parser/common/test_float.py,sha256=xc2s_lbXwWmUDvV7eIeurYkVjF9URd-NaxTrvqtB5K8,10373 +pandas/tests/io/parser/common/test_index.py,sha256=F_hD8EujCAW0gm9neZM5i1lp6D-kp9nry4zfkcCmni0,8663 +pandas/tests/io/parser/common/test_inf.py,sha256=ZVU9R8rZofaKpd8HU1kUhedJeOb2r6jPIdjgXGb9Gg4,2305 +pandas/tests/io/parser/common/test_ints.py,sha256=PacGO6moatFMMmakDFY5va-FJDaCVsUte8-KkmGmrik,8526 +pandas/tests/io/parser/common/test_iterator.py,sha256=A0FvRTvOzLRobXvegPmOBcBQV1CG7QKMiIgvN8e82wc,4212 +pandas/tests/io/parser/common/test_read_errors.py,sha256=R9bgL1vNbhLPZnoJyg6XnQV5cVII0Qe1ZbVAtRtfn8w,14225 +pandas/tests/io/parser/conftest.py,sha256=zYZQhyyfzITHjjT-6s8WQeIEPknqN2yvTqVePWwKR_A,8964 +pandas/tests/io/parser/dtypes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/parser/dtypes/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/parser/dtypes/__pycache__/test_categorical.cpython-314.pyc,, +pandas/tests/io/parser/dtypes/__pycache__/test_dtypes_basic.cpython-314.pyc,, +pandas/tests/io/parser/dtypes/__pycache__/test_empty.cpython-314.pyc,, +pandas/tests/io/parser/dtypes/test_categorical.py,sha256=sro0wt1wYzfx5xacrMSTKQT7ZI_I3iMQiisz0JjVyso,31376 +pandas/tests/io/parser/dtypes/test_dtypes_basic.py,sha256=l8KMMjimcqJIkBJ-L0n4S2onE105C6CReUT26LFYWDY,34075 +pandas/tests/io/parser/dtypes/test_empty.py,sha256=gIvCKWBAESkcLr40e54rDzSyWZj-61QMWeSylsHhSX0,5432 +pandas/tests/io/parser/test_c_parser_only.py,sha256=ue3refPSImzoZu-LfJ6pGcKgjeh6z5UrfdiFiCVIbWM,73227 +pandas/tests/io/parser/test_comment.py,sha256=7NtnCKxrnxC83yepLiiIZnd1ABf9gjqVmHc3Qepwqgo,7079 +pandas/tests/io/parser/test_compression.py,sha256=cVOupmPID0eSdmZFUEybVPXG9sLVI8v_KsnPCvBqRUI,6133 +pandas/tests/io/parser/test_concatenate_chunks.py,sha256=A5wrCCTZMy2qIbp1VTRZBmkoasDtX8B7fabWd39qbBY,1220 +pandas/tests/io/parser/test_converters.py,sha256=oSM5Oobhhis25ReN8wHSnnHIKC3Xe3xXMZTXXN8l5Vg,14293 +pandas/tests/io/parser/test_dialect.py,sha256=2bonepXZdczjcfGQY6pmOnF6yhXspOlqhp10s6T37rM,7276 +pandas/tests/io/parser/test_encoding.py,sha256=aVSZEeg1PLwu5ISHRXn8-ED5oFazjYpSesp7q8cYXf8,13699 +pandas/tests/io/parser/test_header.py,sha256=QR1fO13tFanWEJJsbG4UKtxqtDUSIJYNonJGhIJGd6w,23547 +pandas/tests/io/parser/test_index_col.py,sha256=_-hhhWxY_ofSL3G3P5sHr2MGPVzDj9U54fdDnMtBNOg,13695 +pandas/tests/io/parser/test_mangle_dupes.py,sha256=eKc07iAC1zM9Il6vVlXcGn6y_fUhHbmR9KnPOg1yrYY,4916 +pandas/tests/io/parser/test_multi_thread.py,sha256=LWBAmYo9iJEWan7f2McV3Veb4zP5cP27gyUDCfU2F2k,4059 +pandas/tests/io/parser/test_na_values.py,sha256=ecs78OblpjDqanBoe-2VB7KwadhVfNEaMUoQiRQbYLw,28342 +pandas/tests/io/parser/test_network.py,sha256=mQ7act1__mbN_vpoTfNdiVaHx9crGArkgK0S54a-9xk,7967 +pandas/tests/io/parser/test_parallel_read.py,sha256=qW5MiHxDHUMrDJOF91TpKpcTHcFmpqef_9OwRTpP1Gw,97284 +pandas/tests/io/parser/test_parse_dates.py,sha256=beIZasOwsl_rZgHIsp55FgDWkzIgN4Nkfi46AOm-9Cc,37835 +pandas/tests/io/parser/test_python_parser_only.py,sha256=_CiWAFoizvmaPGe0VCQF7qVz4nWci2GVKWSA37K-C3o,22548 +pandas/tests/io/parser/test_quoting.py,sha256=U_nG35HHXYyhptl0SCjw-y4FsUi3Gk3HH4yQyU42KQ4,7117 +pandas/tests/io/parser/test_read_fwf.py,sha256=eP15ag6nPjAB3zsp1Kb6l_iQiBAaTVxCqvmV5MmmcaA,29796 +pandas/tests/io/parser/test_skiprows.py,sha256=dWKOFVJOCWNp1H0-KZyEZC0t3Ny2jSJUygu5r7Zbl-M,14908 +pandas/tests/io/parser/test_textreader.py,sha256=LA553pBOLaHYxNBaUHzJpcl9c43Qdn0N7S8_HBo1wPk,12659 +pandas/tests/io/parser/test_unsupported.py,sha256=ebso_fL4yVomLhGS64fim-58gqzqVnURf5aC1sqNChk,9000 +pandas/tests/io/parser/test_upcast.py,sha256=AdZJaIDcFPC1ci4AqX2ULcnoKDdqhVoaDkaBkRTFEI4,3098 +pandas/tests/io/parser/usecols/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/parser/usecols/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/parser/usecols/__pycache__/test_parse_dates.cpython-314.pyc,, +pandas/tests/io/parser/usecols/__pycache__/test_strings.cpython-314.pyc,, +pandas/tests/io/parser/usecols/__pycache__/test_usecols_basic.cpython-314.pyc,, +pandas/tests/io/parser/usecols/test_parse_dates.py,sha256=CydemBv7JAP0-6jcEXgJrDiJgkQj-C1OBNnS23Of0Qc,1969 +pandas/tests/io/parser/usecols/test_strings.py,sha256=ObAfzKVP-ADABOAhNwvC9IfWqSitAv4XQ1zWKIIYNwg,2396 +pandas/tests/io/parser/usecols/test_usecols_basic.py,sha256=kpOBOm_IvkndptXqz0xHJ1COdvoYes3415URTT0Z9wE,16748 +pandas/tests/io/pytables/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/pytables/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/common.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_append.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_categorical.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_compat.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_complex.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_errors.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_file_handling.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_keys.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_put.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_pytables_missing.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_read.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_retain_attributes.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_round_trip.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_select.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_store.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_subclass.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_time_series.cpython-314.pyc,, +pandas/tests/io/pytables/__pycache__/test_timezones.cpython-314.pyc,, +pandas/tests/io/pytables/common.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/pytables/conftest.py,sha256=ByKTV58anIb_BmFOaGwkhv3raeZduwF7f6rRfc9zw8E,569 +pandas/tests/io/pytables/test_append.py,sha256=qOv3bYTofDEZiw34LApfR5n2P9AhtPteio7ySepeeVA,38477 +pandas/tests/io/pytables/test_categorical.py,sha256=CZvj20uMLa4A3V9d8x4ImlqfLJ3TeqGKMoy5Z2je8Rc,20166 +pandas/tests/io/pytables/test_compat.py,sha256=pc5IdbXljiOcviWLphdyqLH2VKtukAdD6qIlcA_Lqqc,5945 +pandas/tests/io/pytables/test_complex.py,sha256=k3UEd8YRiF6g2uLO6Qct7QJNhwqemMQxsTt5UeRxHY0,6055 +pandas/tests/io/pytables/test_errors.py,sha256=jEtIzi6zIKyzEF77QYtaN-tzvZfASTqTeNyszR02--A,15094 +pandas/tests/io/pytables/test_file_handling.py,sha256=5TwVA4vK4f9R5L_V0iCyzou9p1mO7Fk3IollTZAf62U,16699 +pandas/tests/io/pytables/test_keys.py,sha256=GGFTPBwE1fKlaZO290mLbKZn46ksm3bEvHRIokM88O8,2426 +pandas/tests/io/pytables/test_put.py,sha256=SV8ybIiGTyrhMdtWT6wmltWZc9ecCX2bMUgB9C67leM,18577 +pandas/tests/io/pytables/test_pytables_missing.py,sha256=O5EhDR708gZUweiXussIAc8p0ohoGmQj5O92gve3G60,284 +pandas/tests/io/pytables/test_read.py,sha256=xFsD75A0XxzV4oS_R0oimziDceoB_PMsdv_apUurot8,11289 +pandas/tests/io/pytables/test_retain_attributes.py,sha256=5G0jokoAfN-jjq4BQS3RFYzKuoyejtYBZlSFmtU2gLs,3466 +pandas/tests/io/pytables/test_round_trip.py,sha256=zAAu1r8nZamGCIhRLekDDPRdejAysiHAM6uzmQY55eg,48055 +pandas/tests/io/pytables/test_select.py,sha256=hrqOXuwthZ8uHtx0KiYJJh-FVqGYehEn0t-Ha1SZYbc,59474 +pandas/tests/io/pytables/test_store.py,sha256=qxPm01WFXx9TdO8farv7jNotdy7GRxYvU4KJUBpChJM,41706 +pandas/tests/io/pytables/test_subclass.py,sha256=tuYPRBAJ-vFS3Jlpib4QRkxAp7MpcNj_j9NUiaBZrM8,1311 +pandas/tests/io/pytables/test_time_series.py,sha256=XcE-QaiVmWH2JnMcN3Nq2mXzlUK8Xks5r3SF4Ze_lCA,3803 +pandas/tests/io/pytables/test_timezones.py,sha256=REvDQIojy5_Qksv_2Pxgh2Y7emY7wpeJZFrqgApd2b0,11314 +pandas/tests/io/sas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/sas/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/sas/__pycache__/test_byteswap.cpython-314.pyc,, +pandas/tests/io/sas/__pycache__/test_sas.cpython-314.pyc,, +pandas/tests/io/sas/__pycache__/test_sas7bdat.cpython-314.pyc,, +pandas/tests/io/sas/__pycache__/test_xport.cpython-314.pyc,, +pandas/tests/io/sas/test_byteswap.py,sha256=WwBIjqhZGnQsfnMlEJbBw0pceBcCgKBee48m6hHdKQc,2108 +pandas/tests/io/sas/test_sas.py,sha256=mKRpIzJIAi6Gf9LjgP2O4Da5YrhsBj3iSgKPTFO06fE,1005 +pandas/tests/io/sas/test_sas7bdat.py,sha256=BUUQM9qho_7DFVZniU4iBxXUkGMsWRUJsSzrNKBozsM,48897 +pandas/tests/io/sas/test_xport.py,sha256=3Q3_YLfrPdawlwsdQ6CxkMYq8SSzXKhI7nb5HUplzYw,6785 +pandas/tests/io/test_clipboard.py,sha256=TaJuC5stz3zMipVdIaASAtP8lpXbFKV0fB1PrwT4DE0,16008 +pandas/tests/io/test_common.py,sha256=AePjGY9rqVB2GtLRRd0_qy_j6Dd3wnX8HSNV6C8RDB8,28445 +pandas/tests/io/test_compression.py,sha256=jgydoVhL_o9K8eFoX-i-yozKZUdE3hzBlrFQ4WwBo1g,14158 +pandas/tests/io/test_feather.py,sha256=1WpJxt0J6ZoMQ5xTs75MeAxqTyU-NMWDqRdGB2TbFJY,10803 +pandas/tests/io/test_fsspec.py,sha256=WaQTAjqrxSOxXCauRg0GuqLKJcNOWvbI84HCkDxGrkc,14597 +pandas/tests/io/test_gcs.py,sha256=zKBi_1DMl1LbSxSYDPOZPTd7Ecd2Qs9u42Y4bDtCvKw,7739 +pandas/tests/io/test_html.py,sha256=FJViFGS5hEiGME0dLHjBSUwgU2bnDrhS8qtg-rC6-iU,60313 +pandas/tests/io/test_http_headers.py,sha256=U31kZYk8SyFb9V44yduh1mdZSDOUaUwwDaWHDyHYXfM,4822 +pandas/tests/io/test_iceberg.py,sha256=vHKLUs7AZTre11MEgwEZgjXIcBMk7JfibuU3E8OKYKs,6624 +pandas/tests/io/test_orc.py,sha256=jAyVA9_2On4gYX5QA-6I6FcZpMixq789QTfDHGUptqY,14155 +pandas/tests/io/test_parquet.py,sha256=VISUU1GgAnB9W-8dDUbJKBfiZpYMtYOTXZkYXyn06d8,58236 +pandas/tests/io/test_pickle.py,sha256=2qdULKIKlAl-jqj436M1nKlL-FRY2xo7OOF7fSKaKqg,26989 +pandas/tests/io/test_s3.py,sha256=F4zxVIyiEaudqYYvjPWSNHK4BZIpCb85-J9pkqxnzUw,906 +pandas/tests/io/test_spss.py,sha256=DuLb1bH0S8HKCPMZhOgwU4lVbgjHpW1kAkOtUXuv5cE,4824 +pandas/tests/io/test_sql.py,sha256=gVCWCQgaCK5MzObTV9fT_iW5oec-_uAB2xMFlyvFxgU,154623 +pandas/tests/io/test_stata.py,sha256=CamqiFG0Ry48v7Pm_aMRZtUGPm-C8N8jP5HtwjwDqy0,108262 +pandas/tests/io/test_util.py,sha256=S4bPE6C6xNsJDkTFI1MMLZ3aUvXUCPdoKfRlxmdQtM0,2241 +pandas/tests/io/xml/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/xml/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/io/xml/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/io/xml/__pycache__/test_to_xml.cpython-314.pyc,, +pandas/tests/io/xml/__pycache__/test_xml.cpython-314.pyc,, +pandas/tests/io/xml/__pycache__/test_xml_dtypes.cpython-314.pyc,, +pandas/tests/io/xml/conftest.py,sha256=gra94hruWijDpMIaUuubUeMObhYdCZDZHanN999-wjw,2668 +pandas/tests/io/xml/test_to_xml.py,sha256=tbiW9hv6J5aPS_EeahDes4ZeqCV-_Lh9BIlWJoPbnnE,35756 +pandas/tests/io/xml/test_xml.py,sha256=PpdSwNKKhn6ixfRGfYnOew_-4EoMVC1kicOQDLCRl9Y,62006 +pandas/tests/io/xml/test_xml_dtypes.py,sha256=iawKC1xDC3jsHiraCLub7S9xGCEfJI8n_0s00zhI_Ks,12386 +pandas/tests/libs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/libs/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/libs/__pycache__/test_hashtable.cpython-314.pyc,, +pandas/tests/libs/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/libs/__pycache__/test_lib.cpython-314.pyc,, +pandas/tests/libs/__pycache__/test_libalgos.cpython-314.pyc,, +pandas/tests/libs/test_hashtable.py,sha256=Sm3P8xc6y0EpvTgQbAk0il81yb9IwueytGiXKr9F5x0,30975 +pandas/tests/libs/test_join.py,sha256=MiNaWCAggAJ09u7JCJvnDuQa9tRJYHeOTcBF-kgERg8,10736 +pandas/tests/libs/test_lib.py,sha256=W8GgmHUSoNyh_OsKtNN3elVLOBFqZj8x3_sN54KhrZM,14494 +pandas/tests/libs/test_libalgos.py,sha256=saDyCbchGU690HmrfZUJ6q1iCLNeW4x50Y-A2o1fgrg,5322 +pandas/tests/plotting/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/plotting/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/common.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_backend.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_boxplot_method.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_common.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_converter.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_datetimelike.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_groupby.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_hist_method.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_misc.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_series.cpython-314.pyc,, +pandas/tests/plotting/__pycache__/test_style.cpython-314.pyc,, +pandas/tests/plotting/common.py,sha256=x0CDd37rWnimge3RTzdv65DC18315BW3x0CY0dgX3ZQ,17611 +pandas/tests/plotting/conftest.py,sha256=Ymi5zdU4oradAyRoxOCkPnX_M1IprbVDbeAhEQiON58,853 +pandas/tests/plotting/frame/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/plotting/frame/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame.cpython-314.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame_color.cpython-314.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame_groupby.cpython-314.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame_legend.cpython-314.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame_subplots.cpython-314.pyc,, +pandas/tests/plotting/frame/__pycache__/test_hist_box_by.cpython-314.pyc,, +pandas/tests/plotting/frame/test_frame.py,sha256=u8OhzBODxOEI8Ra5kNlIF9YxlUG6UzS65nI5xPEwarQ,103609 +pandas/tests/plotting/frame/test_frame_color.py,sha256=4mvhsoS4vg4OREiEVe4_ryfyCthzNlXSWG-7hIims2E,31896 +pandas/tests/plotting/frame/test_frame_groupby.py,sha256=SByI0exUtjZSwPb78SaM19q-HAVZNWoroAsGitCLXxw,2568 +pandas/tests/plotting/frame/test_frame_legend.py,sha256=ayWTnlzjus31rVw6Oh6gxIUhlDjLjrzdFoB54Ob5fuo,10221 +pandas/tests/plotting/frame/test_frame_subplots.py,sha256=ZYLQoZpvvKLcctQX-HDqa84rikyepw-jRtWIEfTrAfw,30875 +pandas/tests/plotting/frame/test_hist_box_by.py,sha256=1Xjmm9Y9Hko3i0fSgWhYfdhI6tzqcdJaOH5K6mM0ouY,11045 +pandas/tests/plotting/test_backend.py,sha256=M7EYCAPKyrei6x-UKmWiUb0ucptwjqgeE93OfMKmFWE,3341 +pandas/tests/plotting/test_boxplot_method.py,sha256=RFd6Na0dTIxcEns7MVzZcZ2PKhLUizcgf66QuUTQgzs,31406 +pandas/tests/plotting/test_common.py,sha256=DWvlpeWcLgqWPyxOkLsT_EEvKGj3MFsrCkzJJxY6gJg,1866 +pandas/tests/plotting/test_converter.py,sha256=eJHzsMlonfXrBUNLXWuFOtTTtRmxBS_qGqg7eIPVOzc,12901 +pandas/tests/plotting/test_datetimelike.py,sha256=-ty3HI0hAOEuoMqaWoyYZ0u47Mx9-jJLSVoB_sWGUj8,91555 +pandas/tests/plotting/test_groupby.py,sha256=_Yw6AnR3x40j21Fub5UHheETVsq4K4N1U8sBrS-3_Ys,7378 +pandas/tests/plotting/test_hist_method.py,sha256=AnYnL0j2HSBaJb0KQ_0GL8FBTUHArw9UV3iCrrN_8QQ,36168 +pandas/tests/plotting/test_misc.py,sha256=H3rUkB8PD-Xh3-WVSfk9msw6TszpUIx-af7TFBejRKo,34827 +pandas/tests/plotting/test_series.py,sha256=c0-y1gbYaDaaf-dmCX8cgvOaTa_kb-Ia45FBgo9jhzg,37220 +pandas/tests/plotting/test_style.py,sha256=Rciui6PsZeU45uf5X8mCqgi5yJLTcohx9KSy1F0WARc,4981 +pandas/tests/reductions/__init__.py,sha256=vflo8yMcocx2X1Rdw9vt8NpiZ4ZFq9xZRC3PW6Gp-Cs,125 +pandas/tests/reductions/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/reductions/__pycache__/test_reductions.cpython-314.pyc,, +pandas/tests/reductions/__pycache__/test_stat_reductions.cpython-314.pyc,, +pandas/tests/reductions/test_reductions.py,sha256=oWXcsbdSodIwFU_SZrDP9e4kPOqTd-MxTW4YWukNRPM,69032 +pandas/tests/reductions/test_stat_reductions.py,sha256=_4LJwTmYBJwvkpJQkQFMr6FH9Hm4q0C9CjwBTjm6Mv4,13600 +pandas/tests/resample/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/resample/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/resample/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/resample/__pycache__/test_base.cpython-314.pyc,, +pandas/tests/resample/__pycache__/test_datetime_index.cpython-314.pyc,, +pandas/tests/resample/__pycache__/test_period_index.cpython-314.pyc,, +pandas/tests/resample/__pycache__/test_resample_api.cpython-314.pyc,, +pandas/tests/resample/__pycache__/test_resampler_grouper.cpython-314.pyc,, +pandas/tests/resample/__pycache__/test_time_grouper.cpython-314.pyc,, +pandas/tests/resample/__pycache__/test_timedelta.cpython-314.pyc,, +pandas/tests/resample/conftest.py,sha256=Yr1zDF2xNxcULKbgBv4QvUBeEaLRx3f1ENm2S-Cmp_Q,706 +pandas/tests/resample/test_base.py,sha256=SJHpqJUBPyKe1A5rQuF6o8TMuUDaiQoN5OzYYkM1x_A,18175 +pandas/tests/resample/test_datetime_index.py,sha256=SUpBRc-mbG11o-TWJdiAhO7qe6eyy68UaPvE3ZnGhHU,82764 +pandas/tests/resample/test_period_index.py,sha256=PiagfdrtXX8ecAMAxLgUEEjwAb0y8itcjmB0AE-5mVk,43925 +pandas/tests/resample/test_resample_api.py,sha256=wYNxVUaYA57FGNLHB_nmzhZpkj_5DTS1LyIiF4BBGuQ,34285 +pandas/tests/resample/test_resampler_grouper.py,sha256=X2Z0VzukwKDsgA78CgQFwdo81mviKOmZT7eUU68VJQM,21883 +pandas/tests/resample/test_time_grouper.py,sha256=7MfVJa6jOlyQpZhmSNBKSZCKnraENuG-lL5jNBFGz-s,13560 +pandas/tests/resample/test_timedelta.py,sha256=Ih7Fq8PXZ9IRlf8O3GITBQcyler5LAKJsSxlNr309n4,8818 +pandas/tests/reshape/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/reshape/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/reshape/__pycache__/test_crosstab.cpython-314.pyc,, +pandas/tests/reshape/__pycache__/test_cut.cpython-314.pyc,, +pandas/tests/reshape/__pycache__/test_from_dummies.cpython-314.pyc,, +pandas/tests/reshape/__pycache__/test_get_dummies.cpython-314.pyc,, +pandas/tests/reshape/__pycache__/test_melt.cpython-314.pyc,, +pandas/tests/reshape/__pycache__/test_pivot.cpython-314.pyc,, +pandas/tests/reshape/__pycache__/test_pivot_multilevel.cpython-314.pyc,, +pandas/tests/reshape/__pycache__/test_qcut.cpython-314.pyc,, +pandas/tests/reshape/__pycache__/test_union_categoricals.cpython-314.pyc,, +pandas/tests/reshape/concat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/reshape/concat/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_append.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_append_common.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_categorical.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_concat.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_dataframe.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_datetimes.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_empty.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_index.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_invalid.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_series.cpython-314.pyc,, +pandas/tests/reshape/concat/__pycache__/test_sort.cpython-314.pyc,, +pandas/tests/reshape/concat/test_append.py,sha256=bSdRHH_4Huw_AiWhwUqJt13qupZi6CNKWYKmKDUDu5s,14425 +pandas/tests/reshape/concat/test_append_common.py,sha256=1m56Wl6JW_PyevWeSOFQuuzOE-ctgd_NF1q9tvzQKNQ,25893 +pandas/tests/reshape/concat/test_categorical.py,sha256=69OILzuAZTFn6R3ooCMELTIbKPgcXMffL2Yi6vhNKUc,22615 +pandas/tests/reshape/concat/test_concat.py,sha256=szgbKEumPOhUO1XoGaibyTcfNhMhTkMH3XQBollPBDI,40368 +pandas/tests/reshape/concat/test_dataframe.py,sha256=zu51GaFQhyJXMmyOiAKebBkj5DpukMHV6n-IAUI4rI8,9366 +pandas/tests/reshape/concat/test_datetimes.py,sha256=JK9wXW72RzEvOrqqwyI4cwhjUDtPhDY6ktZQigUwJ8I,26116 +pandas/tests/reshape/concat/test_empty.py,sha256=Ajy3OrcjqSxIGyeiAE46aks7VPKUGfFoaBayOiHno0Y,10915 +pandas/tests/reshape/concat/test_index.py,sha256=RTUGl-80rSgNRgDTxJ8N9Q16U2J7eiUYWh-AsAzbF7A,16648 +pandas/tests/reshape/concat/test_invalid.py,sha256=6rqWtOkDtSdbr3NkyzyvYCFHt8sN4Aor6woSbab35FY,1614 +pandas/tests/reshape/concat/test_series.py,sha256=OcKfi949ItCQ_WbgzKvTpb7mwaRR7c54UMHMgH3EWUY,6547 +pandas/tests/reshape/concat/test_sort.py,sha256=lOFDPeAeMh83rGxclvgz61NObehBa90gjiD8chHAtiY,4752 +pandas/tests/reshape/merge/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/reshape/merge/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/reshape/merge/__pycache__/test_join.cpython-314.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge.cpython-314.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge_antijoin.cpython-314.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge_asof.cpython-314.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge_cross.cpython-314.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge_index_as_string.cpython-314.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge_ordered.cpython-314.pyc,, +pandas/tests/reshape/merge/__pycache__/test_multi.cpython-314.pyc,, +pandas/tests/reshape/merge/test_join.py,sha256=9juepTGae8JhcwlnhNSZc0RylH_z33lUrHFKp0rmkOg,41449 +pandas/tests/reshape/merge/test_merge.py,sha256=dyfI9yExAZT8DiHij53gbe7m_Vz-noMpYYTezmCFJ8A,123561 +pandas/tests/reshape/merge/test_merge_antijoin.py,sha256=mxVtEEAPHYU18GQJR4RYPK9AGmvvQvcRmHnaiPR3VmI,8788 +pandas/tests/reshape/merge/test_merge_asof.py,sha256=L-Mz_S3yzYADgxuNzENxY-7dtqDXyDkfiGNLfj9DOpg,123877 +pandas/tests/reshape/merge/test_merge_cross.py,sha256=tEuw6xDEmvPAVamsUyaRkXoxjA8znLecVUgRCeQ0BkY,3176 +pandas/tests/reshape/merge/test_merge_index_as_string.py,sha256=yThG5ZgF0aWgy2hX4sMkK-VyVnTjiT0MnjcAZPnzwNg,5322 +pandas/tests/reshape/merge/test_merge_ordered.py,sha256=QO2f-MOerAMt7PGjXk1882wy-C5DPQlkoAbWuKKtLuE,7515 +pandas/tests/reshape/merge/test_multi.py,sha256=YuTGEzLCldrc8q7LDm-11KyXSAvSKXKtLd6HGUlLb8c,44364 +pandas/tests/reshape/test_crosstab.py,sha256=oIRusZpoI_9Ol9vGB6QA25JFI5eo_gTtSVOmt2Csbg4,32769 +pandas/tests/reshape/test_cut.py,sha256=9m37DXH_iVnD0NoppmCvsyqtcl490ir5nlGQ_DfI7Xk,30816 +pandas/tests/reshape/test_from_dummies.py,sha256=yxiM1g8eodJvjzsD4NnCyZfUeIBfRwQeptsAmUIIer0,14268 +pandas/tests/reshape/test_get_dummies.py,sha256=yHy-8xjIJlXGNHC-ul1U3aH1G5FQuZXvoQVdUSeW8aA,30177 +pandas/tests/reshape/test_melt.py,sha256=Sce4wjTWwtqvhYqcxyT71GWy6viqNw5yVVluSwdqA8s,45992 +pandas/tests/reshape/test_pivot.py,sha256=ZoQMffMaiDM6JWQ3WrFbZXLnTyR4MeQAYCRRn60geHg,114014 +pandas/tests/reshape/test_pivot_multilevel.py,sha256=jSdz34kFhY2TMpDOcCCkyI7_boMhnw-u6eeg7e4IwuU,8935 +pandas/tests/reshape/test_qcut.py,sha256=Ijc3SI5euGLZV_et_R9kQ0LMNxr37VebVReFmeg_fh4,8984 +pandas/tests/reshape/test_union_categoricals.py,sha256=CgJdDhOOpXiTbU_vZV6cYxzQnAHJiHMOUoFsfUoiQ1Y,15566 +pandas/tests/scalar/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/scalar/__pycache__/test_na_scalar.cpython-314.pyc,, +pandas/tests/scalar/__pycache__/test_nat.cpython-314.pyc,, +pandas/tests/scalar/interval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/interval/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/scalar/interval/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/scalar/interval/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/scalar/interval/__pycache__/test_contains.cpython-314.pyc,, +pandas/tests/scalar/interval/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/scalar/interval/__pycache__/test_interval.cpython-314.pyc,, +pandas/tests/scalar/interval/__pycache__/test_overlaps.cpython-314.pyc,, +pandas/tests/scalar/interval/test_arithmetic.py,sha256=sdewS54AJbUaEx6fmEhvca6EMU1bc32txc-eo3v0t7I,6147 +pandas/tests/scalar/interval/test_constructors.py,sha256=TqsHzvSP1fRoHYCVDHvi45QpMlhv5gk9KswWZUmqcAY,1585 +pandas/tests/scalar/interval/test_contains.py,sha256=6vKdptGvwxoQ3na03it_OiGIMnO_-CKfBdkpnA8mjdI,2367 +pandas/tests/scalar/interval/test_formats.py,sha256=Gzkr0XWyROJZX9LveUKUEnMjzXFX8tC2GTT8ubDZx4E,342 +pandas/tests/scalar/interval/test_interval.py,sha256=SNuVdq1rq2GPcT-g_exAattByJ84r-NgdqYAuun3rKo,2687 +pandas/tests/scalar/interval/test_overlaps.py,sha256=Jj80rmGLdaf_ps1CDErsTQ0AkJoRCyaVu6vDfP3QMB4,3380 +pandas/tests/scalar/period/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/period/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/scalar/period/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/scalar/period/__pycache__/test_asfreq.cpython-314.pyc,, +pandas/tests/scalar/period/__pycache__/test_period.cpython-314.pyc,, +pandas/tests/scalar/period/test_arithmetic.py,sha256=Iis_MhbKRy1L94IzP7y-GcVZ5JFqhiIWMDiFVbAhFa8,18187 +pandas/tests/scalar/period/test_asfreq.py,sha256=DEiCTDTV8omWax1kKfGV90K_9QzGARugntxjVJ2u5Z8,38470 +pandas/tests/scalar/period/test_period.py,sha256=rXEoBByHpY19d5i64Z47d1M24QL6mME8Acy8qFzVzj4,53585 +pandas/tests/scalar/test_na_scalar.py,sha256=RsihQHlCgnHRr9HODFVUGVwacqYjshcLHBFoiQB6xkc,8067 +pandas/tests/scalar/test_nat.py,sha256=uqX9m9nt-SbFRktcsFx9CO_P4IUrfK3nn06KUqIG1Ss,19820 +pandas/tests/scalar/timedelta/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/timedelta/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/scalar/timedelta/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/scalar/timedelta/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/scalar/timedelta/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/scalar/timedelta/__pycache__/test_timedelta.cpython-314.pyc,, +pandas/tests/scalar/timedelta/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/timedelta/methods/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/scalar/timedelta/methods/__pycache__/test_as_unit.cpython-314.pyc,, +pandas/tests/scalar/timedelta/methods/__pycache__/test_round.cpython-314.pyc,, +pandas/tests/scalar/timedelta/methods/test_as_unit.py,sha256=XPNrO0pi5m5uTJoud-hjIxxM5xJDkV7Wkwi4fHZ1UX0,2515 +pandas/tests/scalar/timedelta/methods/test_round.py,sha256=FHcOThvDqNmbHT7NIcRW5oZO7RZ4ABDGWo8fYiNGc50,12431 +pandas/tests/scalar/timedelta/test_arithmetic.py,sha256=5NivEGgulIV47_lN4iV6Yxj2FvaTY-pAbc7bEOAqKtI,64457 +pandas/tests/scalar/timedelta/test_constructors.py,sha256=YyCSb38Wgc1H64HLWSk-v5b2gWewXGohnc_9GzQJitc,32319 +pandas/tests/scalar/timedelta/test_formats.py,sha256=hgoQqysMMRGvzZJ6tipVCmtA6IG0t7F3r1hugqpDpTw,4227 +pandas/tests/scalar/timedelta/test_timedelta.py,sha256=A2PmgwnVW4ZjAJYivj1mL92B6dm70vrkVuTqjP1iIyo,30583 +pandas/tests/scalar/timestamp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/timestamp/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_comparisons.cpython-314.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_timestamp.cpython-314.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_timezones.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/timestamp/methods/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_as_unit.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_normalize.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_replace.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_round.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_timestamp_method.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_to_julian_date.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_to_pydatetime.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_tz_convert.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_tz_localize.cpython-314.pyc,, +pandas/tests/scalar/timestamp/methods/test_as_unit.py,sha256=X4kbn-GC_qi0949mLKP75vR_sbDjyI-J3yFcPm9VtmY,2734 +pandas/tests/scalar/timestamp/methods/test_normalize.py,sha256=ppzmweVYFoszEXcArKPc8Q0UPhXMmBe1sWNBj7DlxpQ,1009 +pandas/tests/scalar/timestamp/methods/test_replace.py,sha256=IEZo5JXo7B6zzzj_6W-Z7DrgJ_aI-qEkuzt4INZ7zR0,8384 +pandas/tests/scalar/timestamp/methods/test_round.py,sha256=p58LOem4-wSA1pqQajtCXjtrvWGIaGZWQJwhChTYp78,18414 +pandas/tests/scalar/timestamp/methods/test_timestamp_method.py,sha256=LcwYfFmRcFsaHyQwVmF3MnYvYNJCbAXNqPzDkcaz3Z0,1137 +pandas/tests/scalar/timestamp/methods/test_to_julian_date.py,sha256=Ux2eWPZ-QZDs0sEW68phXybV3SDP6JpDyTeeM56kItI,1713 +pandas/tests/scalar/timestamp/methods/test_to_pydatetime.py,sha256=kUxvt4-l1aqdnc_c6wPCIM-pXJKNPw5k0ff9wzd-_Gs,3129 +pandas/tests/scalar/timestamp/methods/test_tz_convert.py,sha256=oFXDNFB9VkXdLLdavbKuqx3YWz52rtGbw52FRXaEFCk,1719 +pandas/tests/scalar/timestamp/methods/test_tz_localize.py,sha256=yoKGlleaTSsqGV_5pqv_q3akTBPfkhPAGCeDPeE0ZCs,17220 +pandas/tests/scalar/timestamp/test_arithmetic.py,sha256=NdVlXGbSnPbdYMeE1cDgYK-IpiiYTlU0FMNnK9tR8JU,16052 +pandas/tests/scalar/timestamp/test_comparisons.py,sha256=TawjpkUYoJtxnXxIzyL3RAna7oYVGgF_Xn5Pj4ovuVU,10140 +pandas/tests/scalar/timestamp/test_constructors.py,sha256=QhVuNKOyoEojxWCPIK09PIT1R70knrvHZUzqz_YIJTc,63483 +pandas/tests/scalar/timestamp/test_formats.py,sha256=W_3mcE7OM2CkyIMvt_BZ_nkoOGhNLGP23wi9UbLzREY,10943 +pandas/tests/scalar/timestamp/test_timestamp.py,sha256=ZXcy0X1jlDmZ4AhgrEoMIkWyFZW3-sX_9A3yb9U5o8g,34253 +pandas/tests/scalar/timestamp/test_timezones.py,sha256=qoL5HhW1IOz_VhyntZdwvM-Mk2h6ceSjdOM682Zq-Jo,661 +pandas/tests/series/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/series/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_api.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_arithmetic.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_arrow_interface.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_constructors.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_cumulative.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_formats.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_iteration.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_logical_ops.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_missing.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_npfuncs.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_reductions.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_subclass.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_ufunc.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_unary.cpython-314.pyc,, +pandas/tests/series/__pycache__/test_validate.cpython-314.pyc,, +pandas/tests/series/accessors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/series/accessors/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/series/accessors/__pycache__/test_cat_accessor.cpython-314.pyc,, +pandas/tests/series/accessors/__pycache__/test_dt_accessor.cpython-314.pyc,, +pandas/tests/series/accessors/__pycache__/test_list_accessor.cpython-314.pyc,, +pandas/tests/series/accessors/__pycache__/test_sparse_accessor.cpython-314.pyc,, +pandas/tests/series/accessors/__pycache__/test_str_accessor.cpython-314.pyc,, +pandas/tests/series/accessors/__pycache__/test_struct_accessor.cpython-314.pyc,, +pandas/tests/series/accessors/test_cat_accessor.py,sha256=4p4zNnhxh8_YLBmETkE0yFRpUJDewu-Etz2dtvIyRvM,10684 +pandas/tests/series/accessors/test_dt_accessor.py,sha256=MsdtnXtGkFnHPHpe6hihiedEPyxzjFdZU6O5zuXFUaM,39107 +pandas/tests/series/accessors/test_list_accessor.py,sha256=b6xxGD7Tdlb1CcwumU2C2cPpPU0mv7KQFkGXGqACXP4,5224 +pandas/tests/series/accessors/test_sparse_accessor.py,sha256=GZUZLTcVYkwKIp2KDgTta2SQl3NDpRhRn6L6N1Y0C1Q,385 +pandas/tests/series/accessors/test_str_accessor.py,sha256=MUaizFfv8hC0YJzgp0VS0B5jbjH44u_zeZeE7Ibn9LI,878 +pandas/tests/series/accessors/test_struct_accessor.py,sha256=6CCSsS6bD-OOSKZ8TfOY_k0YIxrkqs7tBwzXdKrsz0g,5178 +pandas/tests/series/indexing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/series/indexing/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_datetime.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_delitem.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_get.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_getitem.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_indexing.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_mask.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_set_value.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_setitem.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_take.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_where.cpython-314.pyc,, +pandas/tests/series/indexing/__pycache__/test_xs.cpython-314.pyc,, +pandas/tests/series/indexing/test_datetime.py,sha256=Wwlp8FJux31V5ulH6WxFqaTVZ3DnTlScn-SF4_Vn-4c,14519 +pandas/tests/series/indexing/test_delitem.py,sha256=HDuXgc9oaQMkzsn5UzU4UkbXfUAII1QA7MFVVTWIy0Q,2078 +pandas/tests/series/indexing/test_get.py,sha256=JWZGa6R97McR1iOzFPtLA5Sv9sMhVzzMVmVA6jb7PkE,5112 +pandas/tests/series/indexing/test_getitem.py,sha256=HtyMoobw_LVLyEyJbC14tCBgRCEdaaLbFb26oaZ_92k,24840 +pandas/tests/series/indexing/test_indexing.py,sha256=fQjB1rBZqG2NP9gJgx8FRWaknNSPQhFegoXS52qd33k,15849 +pandas/tests/series/indexing/test_mask.py,sha256=LF54NRY2vNr1K9stwO9Y9pBUUtIoRUfGBZ-4d_6Q26U,1726 +pandas/tests/series/indexing/test_set_value.py,sha256=dUrYw9PTKWHSMFo7MIQ-8S_RazfhxxWNbG5sAjlTOOs,1130 +pandas/tests/series/indexing/test_setitem.py,sha256=e_QwgL95WBnY7Ygqmwdv9oA1GHgO40SIm8cLmD5XD_w,67571 +pandas/tests/series/indexing/test_take.py,sha256=u8BxQQjkn8f8sQ7ILlMUIdPpM_5zNE0CbdZ1g5O9wr0,1348 +pandas/tests/series/indexing/test_where.py,sha256=6C3x8oIpuz22fDQ7YQ3aG10Zd7dNb1GCX3iySJCyKSg,13761 +pandas/tests/series/indexing/test_xs.py,sha256=HfOsfKvKyjRL_NJ6HTJqV3mW6tFZ2Dh4KX2Mm5u7hws,2758 +pandas/tests/series/methods/__init__.py,sha256=zVXqGxDIQ-ebxxcetI9KcJ9ZEHeIC4086CoDvyc8CNM,225 +pandas/tests/series/methods/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_add_prefix_suffix.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_align.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_argsort.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_asof.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_astype.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_autocorr.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_between.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_case_when.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_clip.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_combine.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_combine_first.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_compare.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_convert_dtypes.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_copy.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_count.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_cov_corr.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_describe.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_diff.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_drop.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_drop_duplicates.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_dropna.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_dtypes.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_duplicated.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_equals.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_explode.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_fillna.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_filter.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_get_numeric_data.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_head_tail.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_infer_objects.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_info.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_interpolate.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_is_monotonic.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_is_unique.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_isin.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_isna.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_item.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_map.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_matmul.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_nlargest.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_nunique.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_pct_change.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_pop.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_quantile.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_rank.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_reindex.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_reindex_like.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_rename.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_rename_axis.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_repeat.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_replace.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_reset_index.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_round.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_searchsorted.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_set_name.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_size.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_sort_index.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_sort_values.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_to_csv.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_to_dict.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_to_frame.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_to_numpy.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_tolist.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_truncate.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_tz_localize.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_unique.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_unstack.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_update.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_value_counts.cpython-314.pyc,, +pandas/tests/series/methods/__pycache__/test_values.cpython-314.pyc,, +pandas/tests/series/methods/test_add_prefix_suffix.py,sha256=C_l8t00L-n8bLk_Xj93N1_i4xIdXRyDORG8r_TuZsGY,1569 +pandas/tests/series/methods/test_align.py,sha256=R8hC4uSPuJdKmGKpyQMhytsvxqTF2JnRi1FO1WbXb1M,5994 +pandas/tests/series/methods/test_argsort.py,sha256=oMHpakXYnoyYRkoWkwLZGfkUd60nMHSXtKJewn_7rsQ,2529 +pandas/tests/series/methods/test_asof.py,sha256=cdXLBXCV8O988r3ltPnTW34eTK-EDVt2ydKnLKiV_sI,7086 +pandas/tests/series/methods/test_astype.py,sha256=aBQ1PrrJRyhPfy7BDW_i0_JNv-vF9Eq1LwRUgEVQd-8,30064 +pandas/tests/series/methods/test_autocorr.py,sha256=InRYf_2a-CLprLKb-51oGlw4LNpML5tyGlZ5IF11OcA,1300 +pandas/tests/series/methods/test_between.py,sha256=BwjOKhePFwBI7R4oTNBWOqGkXctL-fZE8EGMGicMwzI,2535 +pandas/tests/series/methods/test_case_when.py,sha256=BqGdN9b34z_dZCc17XoUuab68wkKZ13ll3XoZ6eshdI,6461 +pandas/tests/series/methods/test_clip.py,sha256=cBIJS4EOJ8n0-OaZRM9fiUjtVw-L9WneaiGvmixvi2c,6323 +pandas/tests/series/methods/test_combine.py,sha256=C6hNaSW4pasbGqfJLxx7Qgc5gU10i1nzF2YUxazXg54,6716 +pandas/tests/series/methods/test_combine_first.py,sha256=i5PsvrCCJpTGE8ybQHj_jfjO6_jcZU58qsnY_hMR7zc,6329 +pandas/tests/series/methods/test_compare.py,sha256=qg5mmTYwbnxV7tHV4R1yKvkRc8eqgZMfONuu6JgWODw,4514 +pandas/tests/series/methods/test_convert_dtypes.py,sha256=SgZN0EgGGluNS2eeg3-uYafL-cLeJwY07ugD-K5JmwY,14879 +pandas/tests/series/methods/test_copy.py,sha256=g9DOsChIFsvsAG9uyVMi0KWYn_26YdrEmysUaPVNQO8,2445 +pandas/tests/series/methods/test_count.py,sha256=nLlgg-nr38jL9BXunDLP9pt1iVs1QGa_92jt7k90Jw4,541 +pandas/tests/series/methods/test_cov_corr.py,sha256=_ZxdeGDNFciTFL3b24t5iECVPzdFSfV-oKoNgPd9umk,5769 +pandas/tests/series/methods/test_describe.py,sha256=L5PlLbd6KktudQCbXnoPycn9QoxNg0PVAOXxXScQTUw,7381 +pandas/tests/series/methods/test_diff.py,sha256=NsnlSusNeG_ceEHCpQgrwgJBdCGlVGObm4JXe2bgPmU,2694 +pandas/tests/series/methods/test_drop.py,sha256=sy2QaYirexsrLaBTjuo9uUJXpWjs4oxvL8lkYiULXTg,5039 +pandas/tests/series/methods/test_drop_duplicates.py,sha256=GIVXFRZknlNIxrOTpfiN2q_N2zGeO6b1Aj_PaKK-mPI,11246 +pandas/tests/series/methods/test_dropna.py,sha256=K17kH46xc3II205MPBUvpV6JtUcxRsMxaJqSVndMb44,4774 +pandas/tests/series/methods/test_dtypes.py,sha256=IkYkFl0o2LQ5qurobwoPgp4jqi2uKU7phoAk3oZtiYo,209 +pandas/tests/series/methods/test_duplicated.py,sha256=hupTNX4ZE0LEsuMOmfb4YJ2poqzOs1JJ2yWfvszfelQ,2054 +pandas/tests/series/methods/test_equals.py,sha256=1zRo237U9kzP7XAkmomKA1sP7uY5-ZSgMQFDP1bTrAw,3779 +pandas/tests/series/methods/test_explode.py,sha256=Kd1CxulicyqBE-OgQdDOAjJWS5hAwnx3xRY0yo6grMk,5438 +pandas/tests/series/methods/test_fillna.py,sha256=2cRL3srcz0d1Zl0WYqDAZKfKHAsJg9pYxeA1asa6MgU,39155 +pandas/tests/series/methods/test_filter.py,sha256=InpM-CI_EZ01Q8NAyGSJJUOFsOvS--Av8QS-Z_ydE7A,4619 +pandas/tests/series/methods/test_get_numeric_data.py,sha256=bs1W1WcjPDLMzttFnY9KkyM1m3LZ-9MdJn_BNA68UKE,905 +pandas/tests/series/methods/test_head_tail.py,sha256=1EWojjTzcLvYH34VvyvEHxczDy7zL3dMTyayFHsVSzY,343 +pandas/tests/series/methods/test_infer_objects.py,sha256=263CzPc_qv97WKqHx6ePojANYsr6aW1N2j9P2GnYpGo,1854 +pandas/tests/series/methods/test_info.py,sha256=hUByebsgC1TPo7lKrweR1KNcB7El97blYPlc8oNhkr0,5659 +pandas/tests/series/methods/test_interpolate.py,sha256=7vusj7jC271S_4Wy0D8iMGgmGdWyCA9MesL_6qYDl1E,35122 +pandas/tests/series/methods/test_is_monotonic.py,sha256=K0m66V8Vb7tyhUQSmKZbPsOBe5WHkNreULuV37v9T7o,825 +pandas/tests/series/methods/test_is_unique.py,sha256=45x_bTuo9QznbLmq9ih6Z3cb3lMw8hh-PmpOSLiKhgI,953 +pandas/tests/series/methods/test_isin.py,sha256=O_302RE3CR8M9AB09Pyfo_g3G3BLLL68IheG7iAETKM,11776 +pandas/tests/series/methods/test_isna.py,sha256=-TZT1lP05qf0fNphJMExNEDqKCOPWb2uqUmxV5Ifwac,938 +pandas/tests/series/methods/test_item.py,sha256=mKPe7Z11n3q9Dck0Q1Du28P--rbvnALOZbXcYW9ulz0,1602 +pandas/tests/series/methods/test_map.py,sha256=iBsuloX-MpI-GbXAkH8gQ_U2tVJq92gaDVYmOUDtFYA,26311 +pandas/tests/series/methods/test_matmul.py,sha256=Q-m-kSUhvzdugMGOrV_QpHOQYHjcmwZgee3e-2a8gVY,2755 +pandas/tests/series/methods/test_nlargest.py,sha256=-KiwcmlOWcIYi236n9OGGGq2mCxMRDdY__ycPMLryR4,8063 +pandas/tests/series/methods/test_nunique.py,sha256=Lh0NmYCGBwOuqY8AAh_ohoOIILKDCLJnCBnBU4RVZK4,464 +pandas/tests/series/methods/test_pct_change.py,sha256=HXmahP3QvGBvYl48X31_Ct49RqW3wtGTOxBPweooFms,2604 +pandas/tests/series/methods/test_pop.py,sha256=k1g8XdENV7kDNKEgwJRvKfWw_zlH7EVTP48S18IY4-8,627 +pandas/tests/series/methods/test_quantile.py,sha256=WDulYRKjvXax3kWDJcI4OhcBd06liew9jNupGFPT-eE,8878 +pandas/tests/series/methods/test_rank.py,sha256=0fqZ45Zj3iEJ2tCanPYVZ9uSMuPDLrQsJ1uC8niOk-M,22026 +pandas/tests/series/methods/test_reindex.py,sha256=owa_VsP7s2ONS2K5yQG0LkciSuMfW0pnHLKOStXRv60,15355 +pandas/tests/series/methods/test_reindex_like.py,sha256=IzsOq0nENI7_YHAVI-SiZfHycW7LRXZ9a6T_tu0KHZc,1662 +pandas/tests/series/methods/test_rename.py,sha256=EivwNMBWtDhckKu3QcAIl3pplaklAkbgAOf3ySXJgaU,7669 +pandas/tests/series/methods/test_rename_axis.py,sha256=x0x5Iz874G90WO6lHHncgA7mqO4P0ZjE_oSJI2kiBH4,2514 +pandas/tests/series/methods/test_repeat.py,sha256=k4nmHb1KMjrkBW5uAOXslA7pANNEIU1K8B0tI6YmFWY,1308 +pandas/tests/series/methods/test_replace.py,sha256=fRZgz4eaV4b4Ln08kXHDnm4AtiF61b4nmW2UA3GGzkQ,30014 +pandas/tests/series/methods/test_reset_index.py,sha256=l0OCKC0pdIHsB6asqeA4oPzPJGA1jtJ0I_JK1ipp_N8,8972 +pandas/tests/series/methods/test_round.py,sha256=2kNtCwP4BNuSqvingyG9TH_ePWIB8l9TiaCfY5icK4E,3998 +pandas/tests/series/methods/test_searchsorted.py,sha256=K1xr_BBhC0yRZiSNoxEepAjvO7HaUf_Bis5hZYmKXUU,2472 +pandas/tests/series/methods/test_set_name.py,sha256=BihOxVC_z5xchNL9RMZ7lbkQVFTw5E_tqMv6jMb_w80,598 +pandas/tests/series/methods/test_size.py,sha256=P2kEAFDJ65uJOks93xOK6mlsF-YsOtRNYPl51pvO-ow,492 +pandas/tests/series/methods/test_sort_index.py,sha256=LhGqMuoQ-iTGeDoD9ug3O2Z08voqlHS9AAKlt6Kebo0,14172 +pandas/tests/series/methods/test_sort_values.py,sha256=Z4kfV7WH9ijYj_ayP5tKAtOplzylJ8nHA9vdQUb8ltc,10846 +pandas/tests/series/methods/test_to_csv.py,sha256=nZQtvGd4ZYAfQ2CVzzowPdQdyQt5YFUrodgwDxSN6zU,6059 +pandas/tests/series/methods/test_to_dict.py,sha256=lyPTU_-mn7D25j2cVr-ryrlS7fbF2zEY6asyknbOhLM,1184 +pandas/tests/series/methods/test_to_frame.py,sha256=CS8P5a-Z_zoLCPPlp720hv8AI2K7iwKpC6mbP2nDo34,1833 +pandas/tests/series/methods/test_to_numpy.py,sha256=o_5CSoS_SEttfJA3lqdAeH2KYrS6x7aY7qU0PJaCIPg,1618 +pandas/tests/series/methods/test_tolist.py,sha256=jRiQ0ztKQBhW8mHZZ0cKrHK6lZmS_hH_CzyLQ8Ztl1k,1071 +pandas/tests/series/methods/test_truncate.py,sha256=ohf_xX2TRMtlwP1e93WawB9QlLW0cByINkF6HN6Evv4,3689 +pandas/tests/series/methods/test_tz_localize.py,sha256=93EHSDruvxt7Y_Tlbh2bd8IZf7aieJZqoICmH7XJjmA,5668 +pandas/tests/series/methods/test_unique.py,sha256=2bJLrWE-ugGMS2_B5YC4FtehOf6FxuTIqOktFBTYtuk,2203 +pandas/tests/series/methods/test_unstack.py,sha256=bKmqyaWuKWmSWsmrARee3d3y2j7UVjAaQYhNjpXCg74,5111 +pandas/tests/series/methods/test_update.py,sha256=oEW-nBGXGmIP6FFRgfzNRdWbn9f00tiW5EdP32dLqm4,5029 +pandas/tests/series/methods/test_value_counts.py,sha256=20zdmj-_c7TqGd7Z08AHttIeID7glSVUPE7ZW2oDz-M,9869 +pandas/tests/series/methods/test_values.py,sha256=3OfWD8mpFou5wDJdwf4ut73hiN09oaItUqRyfE2L9ZE,1322 +pandas/tests/series/test_api.py,sha256=Kq1LBABTG8gju4iy_e16utDw39LekRcKidYcUPLQ6w0,9479 +pandas/tests/series/test_arithmetic.py,sha256=BitN5rf563iX7EGtdRjjyVuG2rWQ3TQT9iEA2KkqwmQ,42933 +pandas/tests/series/test_arrow_interface.py,sha256=KxiY5oy9A6WyFR7DlxmPEpCzLhuc8RCdOgqyQrnzQ70,4537 +pandas/tests/series/test_constructors.py,sha256=k_xXj8WTuCxROc9FDBqC_zXLaU_rzbdTQUL_ASc5EY0,90023 +pandas/tests/series/test_cumulative.py,sha256=0Cj9lT3FvGn0NjwMk0we4kmIM-Wo-yz2d9Dul3JeRZI,13036 +pandas/tests/series/test_formats.py,sha256=gjAkF9N8aTU528m3RmG5bc-oqlMNFmrRLmfKcPxqErE,17975 +pandas/tests/series/test_iteration.py,sha256=IN_TP52Gb6BWbbeDNBVJmeHy8y-DyxylgaCffXit5Hg,1346 +pandas/tests/series/test_logical_ops.py,sha256=Ay_gIQ9QuPalgdD5a-NuF25Bu6Ox9ojYIZhOtfO5PK4,26872 +pandas/tests/series/test_missing.py,sha256=z6nELrVAx54tTmJShynCRy_kZUgMWc2hF0IclHHsPwo,2544 +pandas/tests/series/test_npfuncs.py,sha256=nM0dohKvviTqBIzCUKHS3psS29088G_PO0PGmGe6lyY,1133 +pandas/tests/series/test_reductions.py,sha256=IK8UNiBWrdaEqT7BpWgXFhYiO0wXyuDA4Wk2W1bw-UA,9975 +pandas/tests/series/test_subclass.py,sha256=PoKvUL8tgv_6Ls34juXwHt_S_1JKtMOIrYmysizQKi0,2539 +pandas/tests/series/test_ufunc.py,sha256=ChQb-ZRc3IaHak0rfk8m_lY6Hozb1KSKH1l3z1T1uuA,31171 +pandas/tests/series/test_unary.py,sha256=1xyXOd1qVMCsQcih4yIJlj_6Ngra4SwcI9Rw0vLwFTQ,1635 +pandas/tests/series/test_validate.py,sha256=350aZfKLgal-5xriFt92un0OLrJvjIkDQylg1M_rYG8,755 +pandas/tests/strings/__init__.py,sha256=bXy3OI--skxWsx5XSeisvRlIrXiyNmNvUZPzTSa-82s,587 +pandas/tests/strings/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/strings/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/strings/__pycache__/test_api.cpython-314.pyc,, +pandas/tests/strings/__pycache__/test_case_justify.cpython-314.pyc,, +pandas/tests/strings/__pycache__/test_cat.cpython-314.pyc,, +pandas/tests/strings/__pycache__/test_extract.cpython-314.pyc,, +pandas/tests/strings/__pycache__/test_find_replace.cpython-314.pyc,, +pandas/tests/strings/__pycache__/test_get_dummies.cpython-314.pyc,, +pandas/tests/strings/__pycache__/test_split_partition.cpython-314.pyc,, +pandas/tests/strings/__pycache__/test_string_array.cpython-314.pyc,, +pandas/tests/strings/__pycache__/test_strings.cpython-314.pyc,, +pandas/tests/strings/conftest.py,sha256=qscV44ObUp_xMvUJrt9WbB48L3jMHg8YfinM6iwrRLU,3996 +pandas/tests/strings/test_api.py,sha256=M9eeZsxOzjhVmtVARHz_5gmxvZvzy-eIR8LHbgkNPuc,6838 +pandas/tests/strings/test_case_justify.py,sha256=jIuxiwV0BTT5vKevrbf4y08peN0zAGHn8_KQQQL44og,15031 +pandas/tests/strings/test_cat.py,sha256=n34L89RchaG49SjeqjE4OV0Dccgjw1ksxf1S2jvccOY,14837 +pandas/tests/strings/test_extract.py,sha256=RkzniQ30uqg3HU0CoZplSE3zd7cHeiRenX_FthSLmvg,29455 +pandas/tests/strings/test_find_replace.py,sha256=jzX_Xs0bEORRz7_iB_RlpGZ8Qj5bIRO0E8d_a9upk2w,77644 +pandas/tests/strings/test_get_dummies.py,sha256=ZP8LBjSICsJNOgyE-UuItRyl4InQXBOtg68hcVc1sxo,2614 +pandas/tests/strings/test_split_partition.py,sha256=M_ldfvy4nnB-x62p7EvEmTBC5sO_AyVtvVMJrBCXYCo,31952 +pandas/tests/strings/test_string_array.py,sha256=RV1jJEcWb5jQBUSvPN-HjfJrkYA-w9ClWMG8oD69-iM,4029 +pandas/tests/strings/test_strings.py,sha256=nsG6b0vBX3fxNl1E7h2oi1QVyWP8h3rLTNrqI_pIWZc,39123 +pandas/tests/test_aggregation.py,sha256=uxU70uDtpfDvtl5hcgvFIKCl2OxtaE65kFcHG-pf6i0,2779 +pandas/tests/test_algos.py,sha256=7yDZjWFwK63mJjXnaLOzFaAWlL6JhOvaK2_t81DPRt0,91894 +pandas/tests/test_col.py,sha256=qGvMzT8EGsgaHW80nVN-4QScavpNeZuSk7QQ2kQJ8Dg,12707 +pandas/tests/test_common.py,sha256=6TgWRzGoRjyMa0o4lHtP0F1phLB1046uaWMBudJkhds,8944 +pandas/tests/test_cpu.py,sha256=MiFlLr4mpUs44mazEVL9-WY9jn_AcMhAKP6ArHirH-o,4314 +pandas/tests/test_downstream.py,sha256=YLSubI6HEYMY-eEQmnV0L89XfG9IyhN5NwsUbm6PyBI,8596 +pandas/tests/test_errors.py,sha256=x96IVcaeOCXmOOnL4j8F_dOxEXFiQoL1REjQNSga3ww,3974 +pandas/tests/test_expressions.py,sha256=3kFK-VzZFm30WWlWB7XYP2fqSfdJOlYmt7-2rLm3BbY,15466 +pandas/tests/test_flags.py,sha256=Dsu6pvQ5A6Manyt1VlQLK8pRpZtr-S2T3ubJvRQaRlA,1550 +pandas/tests/test_multilevel.py,sha256=tRK7KAe-hLYmJriJLhpiWF7TnrO4w-fsLk8Af7SSUMY,12933 +pandas/tests/test_nanops.py,sha256=sKBFZbxz982fIH_iK2ND4ijXr8csgdB3PG9F0k67YpI,63862 +pandas/tests/test_optional_dependency.py,sha256=ygJ6TR1GobrFAXfWygdkVXOTTj3rnkjN3bsvM0_wO1Q,3212 +pandas/tests/test_register_accessor.py,sha256=Cmi7_VUjdu7dP3L8PQ69lfD2acIoN849ieGf6t6atmg,3545 +pandas/tests/test_sorting.py,sha256=X2fnDQLpGHdQAarfjZs3Mvkr_or0uPd-aMIDwLLBR90,23800 +pandas/tests/test_take.py,sha256=PomBNfvE22fN2pY6TfDBzettQqieJ8XtJCiwl8StAfU,15496 +pandas/tests/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tools/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/tools/__pycache__/test_to_datetime.cpython-314.pyc,, +pandas/tests/tools/__pycache__/test_to_numeric.cpython-314.pyc,, +pandas/tests/tools/__pycache__/test_to_time.cpython-314.pyc,, +pandas/tests/tools/__pycache__/test_to_timedelta.cpython-314.pyc,, +pandas/tests/tools/test_to_datetime.py,sha256=0lKZ_WNxcnqVyeYLVah-tjDMs3KQQtwxdS6XF3Q2GZU,194190 +pandas/tests/tools/test_to_numeric.py,sha256=ij-_myXKR9L2z47W4j10f6K0Ol8ZTA731PkYCPklSxk,30421 +pandas/tests/tools/test_to_time.py,sha256=BgQZfsBpSnerm0cnfmj1xrMY3FkuXaV7L2Ty1KRqejE,2224 +pandas/tests/tools/test_to_timedelta.py,sha256=FfTj0cRep4Oc_eFOLEzCqWkHTJhf09LafMebekp0DmI,28877 +pandas/tests/tseries/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tseries/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/tseries/frequencies/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tseries/frequencies/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/tseries/frequencies/__pycache__/test_freq_code.cpython-314.pyc,, +pandas/tests/tseries/frequencies/__pycache__/test_frequencies.cpython-314.pyc,, +pandas/tests/tseries/frequencies/__pycache__/test_inference.cpython-314.pyc,, +pandas/tests/tseries/frequencies/test_freq_code.py,sha256=BDg24tzG-9MaqXNjb6IE2ZVEaQolB8WS-pROqZIFgNQ,1774 +pandas/tests/tseries/frequencies/test_frequencies.py,sha256=7nhdXSoX2B1vKyyxv5QdMZp4PQFrlAVgNDkgXkLD_ag,1636 +pandas/tests/tseries/frequencies/test_inference.py,sha256=pS9fbnGTKyKuc1RX3_OuoskzjWaz1cC4sbthl2ecdzc,21968 +pandas/tests/tseries/holiday/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tseries/holiday/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/tseries/holiday/__pycache__/test_calendar.cpython-314.pyc,, +pandas/tests/tseries/holiday/__pycache__/test_federal.cpython-314.pyc,, +pandas/tests/tseries/holiday/__pycache__/test_holiday.cpython-314.pyc,, +pandas/tests/tseries/holiday/__pycache__/test_observance.cpython-314.pyc,, +pandas/tests/tseries/holiday/test_calendar.py,sha256=Byc41z20j2fDa85JrccFGZVydDc-ULNk-8k8koAKcUM,3588 +pandas/tests/tseries/holiday/test_federal.py,sha256=hNLtkZ5PH-50gg5wNVbe18GCLG42dOxkgpw2W8h4ZqM,1938 +pandas/tests/tseries/holiday/test_holiday.py,sha256=TS4LriYVL7ahe8_MpWXP81tf4Uzu7UpEDMD8etlNxc0,15340 +pandas/tests/tseries/holiday/test_observance.py,sha256=GJBqIF4W6QG4k3Yzz6_13WMOR4nHSVzPbixHxO8Tukw,2723 +pandas/tests/tseries/offsets/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tseries/offsets/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/common.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_day.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_halfyear.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_hour.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_month.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_quarter.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_year.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_common.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_custom_business_day.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_custom_business_hour.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_custom_business_month.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_dst.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_easter.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_fiscal.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_halfyear.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_index.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_month.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_offsets.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_offsets_properties.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_quarter.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_ticks.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_week.cpython-314.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_year.cpython-314.pyc,, +pandas/tests/tseries/offsets/common.py,sha256=uJIIZyQ4do9e3h5KJTcBZu84kNjEbRiXU97e0WK8xhM,822 +pandas/tests/tseries/offsets/test_business_day.py,sha256=yeTGGOhbAuFvR1Rdi8vJcfDGKZPt-jcJGXeXMtHJ8eM,7774 +pandas/tests/tseries/offsets/test_business_halfyear.py,sha256=ZF7Bd15yXnB5kCPvWfBu_oRNgy62YZGgh_CaI3nJ8OQ,13968 +pandas/tests/tseries/offsets/test_business_hour.py,sha256=2pWvr-h9pZe9gayR_MhJnLfFy8xOjx2ReTXV4WTYrs8,58866 +pandas/tests/tseries/offsets/test_business_month.py,sha256=RsZ4ubtWtHG5xVJz0jwEdtubplASW3VwAYNOicHHHoA,6718 +pandas/tests/tseries/offsets/test_business_quarter.py,sha256=CTzWcqHIS1plmhteZ6wzfeUKhTFtwdzyKAe5HmL5LxU,11887 +pandas/tests/tseries/offsets/test_business_year.py,sha256=zpQpxiUdiD7CZChuiVJLPLPrdWhElTZPa9v_1pv5MGE,6437 +pandas/tests/tseries/offsets/test_common.py,sha256=SAfsAiDmmWS_qEss5NnAir9BZGjrnEoFDAteVcsI7Xk,15640 +pandas/tests/tseries/offsets/test_custom_business_day.py,sha256=NmfYk0EYQyJSX_8y5RzCym3KYumFPlPCy47WiXTN1-c,3349 +pandas/tests/tseries/offsets/test_custom_business_hour.py,sha256=36zhlN8iIdqOsAcXW-6VpWISKt6DkiiPo18ey5P_fYk,12210 +pandas/tests/tseries/offsets/test_custom_business_month.py,sha256=TLRofF7nZrHrStflruDQdpZzawpfYW7PsCj-TIr-BCk,12939 +pandas/tests/tseries/offsets/test_dst.py,sha256=1bh2xWk84_7WzGuQ0rCrZLf00oC-q6SlzZZLyPzrMPA,9405 +pandas/tests/tseries/offsets/test_easter.py,sha256=w89tUAe0bzkcrj9sxP7bvSaZLrK9t5rIuyA-r6gIzOc,4675 +pandas/tests/tseries/offsets/test_fiscal.py,sha256=VsNDEfxh3BIo4McKcJdsJZS51iEMGzMZPkbU66UXX_w,26052 +pandas/tests/tseries/offsets/test_halfyear.py,sha256=8TsQ5aLU4nvFQFCbdG9zn5b350uTVQKDKo5GF8NX6T8,13836 +pandas/tests/tseries/offsets/test_index.py,sha256=gsOvPWMeGv_4aZskSsPljy6fl_bwNDM5fIz8mJ1OnIU,1123 +pandas/tests/tseries/offsets/test_month.py,sha256=V-Nd-LQmUzpa2UnqsazO2JoKC59w5BaibqfCz9W-VqQ,23264 +pandas/tests/tseries/offsets/test_offsets.py,sha256=WxcGNEKSC5C3FR-i8r0Em-70dKkdksSYFshtbfmx8ug,51517 +pandas/tests/tseries/offsets/test_offsets_properties.py,sha256=LegzSCBurF7JNteUnpof9DEbXhMhRvlfCmMlneWmxew,2002 +pandas/tests/tseries/offsets/test_quarter.py,sha256=BJBFPJEnpIpRUE-4XAxaJ-wOSYXRe6YQWo7B5XW8QJE,11143 +pandas/tests/tseries/offsets/test_ticks.py,sha256=mQcfMNG1Qg2i0OZsmVYlKLN2U2wFPn1r-5YACL9eY3c,10929 +pandas/tests/tseries/offsets/test_week.py,sha256=fcNcT1EFxEhOub3HyPNqm4wER0vsNKKqIRlHJvWhfh4,13275 +pandas/tests/tseries/offsets/test_year.py,sha256=lQHaYeVsBflOsBcV2gsyAtYL2JxoCwlf1T8U_xSjN90,10140 +pandas/tests/tslibs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tslibs/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_api.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_array_to_datetime.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_ccalendar.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_conversion.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_fields.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_libfrequencies.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_liboffsets.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_np_datetime.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_npy_units.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_parse_iso8601.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_parsing.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_period.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_resolution.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_strptime.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_timedeltas.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_timezones.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_to_offset.cpython-314.pyc,, +pandas/tests/tslibs/__pycache__/test_tzconversion.cpython-314.pyc,, +pandas/tests/tslibs/test_api.py,sha256=mSE0M-i9WEhJukZr_WwE801URcAqE9v88kEwYwakx_c,1568 +pandas/tests/tslibs/test_array_to_datetime.py,sha256=g41shs1UOLGrz9WDs7Smf1iG-PjYsi9_M17PypOloyw,10846 +pandas/tests/tslibs/test_ccalendar.py,sha256=-mOl3BwK5toeKtjX9Ky6l4tndIWjNgulrr2ZOVsm26Y,2171 +pandas/tests/tslibs/test_conversion.py,sha256=A2cBK-OEvlDqGDhkYm0Vp0brgu1l8O1fKFYXOmZIDOw,6386 +pandas/tests/tslibs/test_fields.py,sha256=BQKlBXOC4LsXe7eT2CK5mRGR_25g9qYykQZ6ojoGjbE,1352 +pandas/tests/tslibs/test_libfrequencies.py,sha256=Ai6deDiGlwUHR9mVvlkIbXYzWZADHuPLlaBjDK0R2wU,717 +pandas/tests/tslibs/test_liboffsets.py,sha256=LPOR6Maej3t84C88K1yLY-iuLpO7U4jeexwCy028SAs,5118 +pandas/tests/tslibs/test_np_datetime.py,sha256=ZW8MbrwbPQqIB81Y2X-LkEh_GQc22NgU3Pfbx4vcBPE,11885 +pandas/tests/tslibs/test_npy_units.py,sha256=d9NFsygcKGtp-pw-ZpOvIxMhpsRqd1uPBVlqejHkNmU,922 +pandas/tests/tslibs/test_parse_iso8601.py,sha256=rlsDmoa1iab5fWl3Pgpa5CQXTuOYlBLQMOw8TsQz1DY,4532 +pandas/tests/tslibs/test_parsing.py,sha256=F2mxwpNACi5pgUBtaBkNLPj2w7-lIpGgD2Hru8sJeJE,18892 +pandas/tests/tslibs/test_period.py,sha256=k5Q9WLdNTn-UId1gjBLz5dtl--t3YaU2nAPMj4-Fvp0,3601 +pandas/tests/tslibs/test_resolution.py,sha256=MQ9kZTg__f_58twLxAiQFYY3ybN1X-XnRfDwsu3tR9k,1404 +pandas/tests/tslibs/test_strptime.py,sha256=NwCg5uO25l5UKF6v6Y41DbcFP6zhXezAYwFSZiyuNIY,3921 +pandas/tests/tslibs/test_timedeltas.py,sha256=4rsPJOg3kzKuEnq1x69NKQd79zyaQnPpWA33NPlTbEM,6587 +pandas/tests/tslibs/test_timezones.py,sha256=QFWyAquIOJkkyhFzTvnASKnw0mSR1tI8Rxk21naV_Io,29139 +pandas/tests/tslibs/test_to_offset.py,sha256=43Ze3Y8QGhkloX0KtHIShNs3WWzeo_Vv80R3PUw9cGs,7071 +pandas/tests/tslibs/test_tzconversion.py,sha256=vCNHPVEzzA-3R2fBRlCorZeVC3UfTgrPFt3L4gd7a6I,961 +pandas/tests/util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/util/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/util/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_almost_equal.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_attr_equal.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_categorical_equal.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_extension_array_equal.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_frame_equal.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_index_equal.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_interval_array_equal.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_numpy_array_equal.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_produces_warning.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_assert_series_equal.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_deprecate.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_deprecate_kwarg.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_deprecate_nonkeyword_arguments.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_find_stack_level.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_hashing.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_numba.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_rewrite_warning.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_shares_memory.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_show_versions.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_util.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_validate_args.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_validate_args_and_kwargs.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_validate_inclusive.cpython-314.pyc,, +pandas/tests/util/__pycache__/test_validate_kwargs.cpython-314.pyc,, +pandas/tests/util/conftest.py,sha256=X-ANfN5vkNQFDPKKvKsb3XvF7JAghJo7yA_7NGcyzSg,1183 +pandas/tests/util/test_assert_almost_equal.py,sha256=-s8p23SfJ8pj8NHmu2cMQGbcvq_6zSU57tKtIoBEssU,29307 +pandas/tests/util/test_assert_attr_equal.py,sha256=_e9j4seFkwkHSaj28QDxiyP22zvyIDkz8zWeERVw7vw,2268 +pandas/tests/util/test_assert_categorical_equal.py,sha256=uPZ2ilJ6y1VUvjdHDorKeLYJvFg6tXkGQQ7o6iZdgTg,5253 +pandas/tests/util/test_assert_extension_array_equal.py,sha256=XOJD1c4T-W9-bKcDh9xs2mtgUXvdrGAZvaAzqh43bMU,5648 +pandas/tests/util/test_assert_frame_equal.py,sha256=SgbJPWd5qJIh1dR6RxPditrDHs0Owvn8R4ObxVMfJiU,24264 +pandas/tests/util/test_assert_index_equal.py,sha256=TvjsHkKaqoab6Ob6hvZhoalIX-LJ53-OwixzmO74G80,13409 +pandas/tests/util/test_assert_interval_array_equal.py,sha256=83JxBLiuLfihqzbjB9Vf5xDeR9xfcGqgX7ZYmx3GpTo,2653 +pandas/tests/util/test_assert_numpy_array_equal.py,sha256=s-PAOY77CSYjzWCz1rFBwXa3gH7anJJF4_tZsne5_VA,7091 +pandas/tests/util/test_assert_produces_warning.py,sha256=4Rzn1UbI901m_LbPgGdyL6TYCtQaFnx-C8EKhAr3gWc,10729 +pandas/tests/util/test_assert_series_equal.py,sha256=CQ3gq3EkuW7Rw-bExHdUYKfbYiLL9iIz7QlZxI6CTyQ,24988 +pandas/tests/util/test_deprecate.py,sha256=RA4FPkKs_D1VYnKJ60jaW0riCJiB4pBuEDg1Kze0w6o,1846 +pandas/tests/util/test_deprecate_kwarg.py,sha256=Y9t1JnTmHL4Xw4zxMQueHauI8c7AJzHAWCJGndZksWQ,2551 +pandas/tests/util/test_deprecate_nonkeyword_arguments.py,sha256=RvoveT1LA9ztVx3cTHUr53THtqDNEQyMmQeGsgueA4I,3868 +pandas/tests/util/test_find_stack_level.py,sha256=BEzVAy3HHVgsPYxrnrDakgIzLY6-oDsgHCrzJ2PXS1E,1953 +pandas/tests/util/test_hashing.py,sha256=NlP3c2ToPV3f2xr_CDvov5eP1I6H8QFsF8F9hbgeci4,19872 +pandas/tests/util/test_numba.py,sha256=n_9gvZHKd4UzIuxhirhq37UwWcx6761DRhdbOr3ryd8,302 +pandas/tests/util/test_rewrite_warning.py,sha256=kjw3QoXXML7s_mG3TxJ701Y5FD1rfGyTHJJTlKqVdwk,1231 +pandas/tests/util/test_shares_memory.py,sha256=vwuse0suAlmSBpZU2JirfXna9hfG8kEOAba4IElSaaI,7260 +pandas/tests/util/test_show_versions.py,sha256=FjYUrUMAF7hOzphaXED__8yjeF0HTccZS6q05__rH44,2096 +pandas/tests/util/test_util.py,sha256=ZBog1GEDPUx-01hRzuFinWSN6SYWax88Zse5JA6elXc,1483 +pandas/tests/util/test_validate_args.py,sha256=9Z4zTqnKAWn1q9KZNvuO3DF6oszHjQrQgtOOimurWcs,1907 +pandas/tests/util/test_validate_args_and_kwargs.py,sha256=d_XcMRAQ9r--yIAAWSdJML6KeWgksy5qRNFXaY1BMQA,2456 +pandas/tests/util/test_validate_inclusive.py,sha256=w2twetJgIedm6KGQ4WmdmGC_6-RShFjXBMBVxR0gcME,896 +pandas/tests/util/test_validate_kwargs.py,sha256=0YhkYN4KhU2qxMRSbOuK7BiGt5nqPYjW3ydCLfjThYo,1821 +pandas/tests/window/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/window/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/window/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_api.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_apply.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_base_indexer.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_cython_aggregations.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_dtypes.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_ewm.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_expanding.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_groupby.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_numba.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_online.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_pairwise.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_rolling.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_rolling_functions.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_rolling_quantile.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_rolling_skew_kurt.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_timeseries_window.cpython-314.pyc,, +pandas/tests/window/__pycache__/test_win_type.cpython-314.pyc,, +pandas/tests/window/conftest.py,sha256=tZuf49sAnqQBdPXM2wL835Yl70884JK0ViMC7uH5jJ8,2560 +pandas/tests/window/moments/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/window/moments/__pycache__/__init__.cpython-314.pyc,, +pandas/tests/window/moments/__pycache__/conftest.cpython-314.pyc,, +pandas/tests/window/moments/__pycache__/test_moments_consistency_ewm.cpython-314.pyc,, +pandas/tests/window/moments/__pycache__/test_moments_consistency_expanding.cpython-314.pyc,, +pandas/tests/window/moments/__pycache__/test_moments_consistency_rolling.cpython-314.pyc,, +pandas/tests/window/moments/conftest.py,sha256=tpU07-EDtPiRILsoBr9HehKtg8yoKV_Gnf7d5iFi6PQ,1590 +pandas/tests/window/moments/test_moments_consistency_ewm.py,sha256=4s4vvgsFkZ0HL00qUeMYSxhIELMLMEpJuf1FfCeECxA,8095 +pandas/tests/window/moments/test_moments_consistency_expanding.py,sha256=xLIxgVEa6wXcDMuyhX4ifjJsecHJA-m-mjnlw6SXnbs,5156 +pandas/tests/window/moments/test_moments_consistency_rolling.py,sha256=WjXp_zCgGPRflsuNwk4kvA4yzrGWuJtzLobeRJmiOag,7434 +pandas/tests/window/test_api.py,sha256=4xqLZE9229BZqk0fPIKweYUyl4pMlU_9YDp-XFWQF3w,12081 +pandas/tests/window/test_apply.py,sha256=z7Sq7a6q7hz2SsdLpyyp54X4cdo5l4gMwgaf97WTKpE,9537 +pandas/tests/window/test_base_indexer.py,sha256=pH3j5j6eWM3XBOudynmuRsjRBIEFBz8D-fe7CgMFlA4,15991 +pandas/tests/window/test_cython_aggregations.py,sha256=CwN-PHygeAda8e9k6fttBq4u9lx-OkQdw6oPZrlB4qY,4168 +pandas/tests/window/test_dtypes.py,sha256=onsstnaPigoP7si4t5qsltDgRDxgL6o_A9UK3zd-Oh8,7905 +pandas/tests/window/test_ewm.py,sha256=GdSOht8RlNRvR4hZAr6RbYvddzxU3uo2ZaKAdCrwm3w,23857 +pandas/tests/window/test_expanding.py,sha256=I03SQhuAkqdiGc0cw8CLTjHkl7Eu-_dlndezBe_ZV18,27258 +pandas/tests/window/test_groupby.py,sha256=6dv49IFb8uynLX1wJYqGPb4TwvR1YQaRNXEBggIbtVk,47682 +pandas/tests/window/test_numba.py,sha256=W6XLLbKdwZFkzsXDuMGFRspiKnNQlWRmu5sV5D4YNsM,21880 +pandas/tests/window/test_online.py,sha256=KTWyq36CpagAUlPCCsDqUQAiLrPPpLQKfTIwj2XXSBY,3731 +pandas/tests/window/test_pairwise.py,sha256=1sggGyle10JJ0quOSY4uSp7TsVen523svviwMENtsV8,22722 +pandas/tests/window/test_rolling.py,sha256=ll9ZA20xcw8awaNdDvM-Q5W27iwJk-pBQn_0Eqrwq30,65352 +pandas/tests/window/test_rolling_functions.py,sha256=PrnZQYlS2AGQPi6HAM17UK8HbB_cVHYtRrfpa2NR3ng,18218 +pandas/tests/window/test_rolling_quantile.py,sha256=Nu4ll6E_sXMKGRmUKNnVqlwHSm4-krTbW70q1jCadlg,5315 +pandas/tests/window/test_rolling_skew_kurt.py,sha256=IWy2n_2F3Moop2AcGxk5zWZD7XS39wP-QLKALS4rN04,12528 +pandas/tests/window/test_timeseries_window.py,sha256=ZO9q8tCGuwT-67U651LxGIKYJ5w2u6vRQt6tjh58itc,25389 +pandas/tests/window/test_win_type.py,sha256=Paunct7_8FpeXxB16-mcvljbWu-7Y3IxUxLJffpXMO0,16990 +pandas/tseries/__init__.py,sha256=EPx-FGPBq4Vw6aC-wjVI0u5ucWvjPhid58AwyVM3Et4,292 +pandas/tseries/__pycache__/__init__.cpython-314.pyc,, +pandas/tseries/__pycache__/api.cpython-314.pyc,, +pandas/tseries/__pycache__/frequencies.cpython-314.pyc,, +pandas/tseries/__pycache__/holiday.cpython-314.pyc,, +pandas/tseries/__pycache__/offsets.cpython-314.pyc,, +pandas/tseries/api.py,sha256=73akBLVhbceRBzQejKM5yQRzWkDDYggs-8Qx6irT5vo,234 +pandas/tseries/frequencies.py,sha256=Km-yt_1Vw7PT9kS8MIQBEHLpgCOANzMo71SVOh_V-b4,21695 +pandas/tseries/holiday.py,sha256=H_8ndzZp6mkwjGqDqoLRQU6XqT4rILRO-VK300qArPE,40509 +pandas/tseries/offsets.py,sha256=pfmrqsT3oZW9CfDfbIAxTo2eXzKidgmF0XYhJ7stglc,1687 +pandas/util/__init__.py,sha256=jpCaZykE55P7PgfyHFV0JKqKJAxU3IJTFO7-MiMVCAw,873 +pandas/util/__pycache__/__init__.cpython-314.pyc,, +pandas/util/__pycache__/_decorators.cpython-314.pyc,, +pandas/util/__pycache__/_doctools.cpython-314.pyc,, +pandas/util/__pycache__/_exceptions.cpython-314.pyc,, +pandas/util/__pycache__/_print_versions.cpython-314.pyc,, +pandas/util/__pycache__/_test_decorators.cpython-314.pyc,, +pandas/util/__pycache__/_tester.cpython-314.pyc,, +pandas/util/__pycache__/_validators.cpython-314.pyc,, +pandas/util/_decorators.py,sha256=vEAGReG14fkNhc0x3Wwd3SrFzGnQBEkipupXYw8QdqE,16264 +pandas/util/_doctools.py,sha256=djN6rhnmWz7vPP0RTTFss-WtEbsiW_ua7WvYsbXuYZQ,7384 +pandas/util/_exceptions.py,sha256=c4IUBpwv3lGBZKQ7EdYhxzC_wTOgQB7QT98QzffB344,3152 +pandas/util/_print_versions.py,sha256=XmuHVRNMEk5ImzvrirIgADf1TUVkxTemi2CzANSdT9A,4648 +pandas/util/_test_decorators.py,sha256=OguIdqYRtqgebMOaoVFdimbU96A9fMNgfyS_TJu7a1U,4314 +pandas/util/_tester.py,sha256=jhQVJognPvk7gcLzNAJbC6PfeWO8amRrY8zKaZvEXcc,1598 +pandas/util/_validators.py,sha256=-oVrmRwdcq9GMuZUUSDymnDShDKoyiuTc5LTYyYs6-0,14059 +pandas/util/version/__init__.py,sha256=W2PyOE79hfQvJPphuu3wvsqpoZh1ZOG7wqHDx5n3e3k,13142 +pandas/util/version/__pycache__/__init__.cpython-314.pyc,, diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/WHEEL b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4e8c2b1e72a78d8df99e13266f4dbc451736a2b0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: meson +Root-Is-Purelib: false +Tag: cp314-cp314-macosx_11_0_arm64 +Generator: delocate 0.13.0 + diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/entry_points.txt b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..3c1b523d70758fbd0080e21ca4c7ce6d9c9d9bd5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[pandas_plotting_backends] +matplotlib = pandas:plotting._matplotlib + diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bd1cc2a30c626d0bbe43ab6ec1c4744c2e2df831 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSE @@ -0,0 +1,31 @@ +BSD 3-Clause License + +Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team +All rights reserved. + +Copyright (c) 2011-2026, Open source contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/BOTTLENECK_LICENCE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/BOTTLENECK_LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..f4bdbb1647ee6be9b3a84916fd05ed66546869c7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/BOTTLENECK_LICENCE @@ -0,0 +1,25 @@ +Copyright (c) 2010-2019 Keith Goodman +Copyright (c) 2019 Bottleneck Developers +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/DATEUTIL_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/DATEUTIL_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e65815cf0b3132689485874a93034ede7206bf4 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/DATEUTIL_LICENSE @@ -0,0 +1,54 @@ +Copyright 2017- Paul Ganssle +Copyright 2017- dateutil contributors (see AUTHORS file) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +The above license applies to all contributions after 2017-12-01, as well as +all contributions that have been re-licensed (see AUTHORS file for the list of +contributors who have re-licensed their code). +-------------------------------------------------------------------------------- +dateutil - Extensions to the standard Python datetime module. + +Copyright (c) 2003-2011 - Gustavo Niemeyer +Copyright (c) 2012-2014 - Tomi Pieviläinen +Copyright (c) 2014-2016 - Yaron de Leeuw +Copyright (c) 2015- - Paul Ganssle +Copyright (c) 2015- - dateutil contributors (see AUTHORS file) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The above BSD License Applies to all code, even that also covered by Apache 2.0. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ce1b07b783e7400b48159c237fd46f3420a771b7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_LICENSE @@ -0,0 +1,21 @@ +# MIT License + +Copyright (c) 2019 Hadley Wickham; RStudio; and Evan Miller + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_MIT b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_MIT new file mode 100644 index 0000000000000000000000000000000000000000..b03d0e640627ae415b14b79faf95e4b39f191a6d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_MIT @@ -0,0 +1,32 @@ +Based on http://opensource.org/licenses/MIT + +This is a template. Complete and ship as file LICENSE the following 2 +lines (only) + +YEAR: +COPYRIGHT HOLDER: + +and specify as + +License: MIT + file LICENSE + +Copyright (c) , + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/KLIB_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/KLIB_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2de13e402643bcc76353552eb6cb2e32d9db916f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/KLIB_LICENSE @@ -0,0 +1,23 @@ +The MIT License + +Copyright (c) 2008- Attractive Chaos + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/MUSL_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/MUSL_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5ff71b5f5a7fe4ff302f61e1a9eb87cd3c191a18 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/MUSL_LICENSE @@ -0,0 +1,193 @@ +musl as a whole is licensed under the following standard MIT license: + +---------------------------------------------------------------------- +Copyright © 2005-2020 Rich Felker, et al. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +---------------------------------------------------------------------- + +Authors/contributors include: + +A. Wilcox +Ada Worcester +Alex Dowad +Alex Suykov +Alexander Monakov +Andre McCurdy +Andrew Kelley +Anthony G. Basile +Aric Belsito +Arvid Picciani +Bartosz Brachaczek +Benjamin Peterson +Bobby Bingham +Boris Brezillon +Brent Cook +Chris Spiegel +Clément Vasseur +Daniel Micay +Daniel Sabogal +Daurnimator +David Carlier +David Edelsohn +Denys Vlasenko +Dmitry Ivanov +Dmitry V. Levin +Drew DeVault +Emil Renner Berthing +Fangrui Song +Felix Fietkau +Felix Janda +Gianluca Anzolin +Hauke Mehrtens +He X +Hiltjo Posthuma +Isaac Dunham +Jaydeep Patil +Jens Gustedt +Jeremy Huntwork +Jo-Philipp Wich +Joakim Sindholt +John Spencer +Julien Ramseier +Justin Cormack +Kaarle Ritvanen +Khem Raj +Kylie McClain +Leah Neukirchen +Luca Barbato +Luka Perkov +M Farkas-Dyck (Strake) +Mahesh Bodapati +Markus Wichmann +Masanori Ogino +Michael Clark +Michael Forney +Mikhail Kremnyov +Natanael Copa +Nicholas J. Kain +orc +Pascal Cuoq +Patrick Oppenlander +Petr Hosek +Petr Skocik +Pierre Carrier +Reini Urban +Rich Felker +Richard Pennington +Ryan Fairfax +Samuel Holland +Segev Finer +Shiz +sin +Solar Designer +Stefan Kristiansson +Stefan O'Rear +Szabolcs Nagy +Timo Teräs +Trutz Behn +Valentin Ochs +Will Dietz +William Haddon +William Pitcock + +Portions of this software are derived from third-party works licensed +under terms compatible with the above MIT license: + +The TRE regular expression implementation (src/regex/reg* and +src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed +under a 2-clause BSD license (license text in the source files). The +included version has been heavily modified by Rich Felker in 2012, in +the interests of size, simplicity, and namespace cleanliness. + +Much of the math library code (src/math/* and src/complex/*) is +Copyright © 1993,2004 Sun Microsystems or +Copyright © 2003-2011 David Schultz or +Copyright © 2003-2009 Steven G. Kargl or +Copyright © 2003-2009 Bruce D. Evans or +Copyright © 2008 Stephen L. Moshier or +Copyright © 2017-2018 Arm Limited +and labelled as such in comments in the individual source files. All +have been licensed under extremely permissive terms. + +The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008 +The Android Open Source Project and is licensed under a two-clause BSD +license. It was taken from Bionic libc, used on Android. + +The AArch64 memcpy and memset code (src/string/aarch64/*) are +Copyright © 1999-2019, Arm Limited. + +The implementation of DES for crypt (src/crypt/crypt_des.c) is +Copyright © 1994 David Burren. It is licensed under a BSD license. + +The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was +originally written by Solar Designer and placed into the public +domain. The code also comes with a fallback permissive license for use +in jurisdictions that may not recognize the public domain. + +The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011 +Valentin Ochs and is licensed under an MIT-style license. + +The x86_64 port was written by Nicholas J. Kain and is licensed under +the standard MIT terms. + +The mips and microblaze ports were originally written by Richard +Pennington for use in the ellcc project. The original code was adapted +by Rich Felker for build system and code conventions during upstream +integration. It is licensed under the standard MIT terms. + +The mips64 port was contributed by Imagination Technologies and is +licensed under the standard MIT terms. + +The powerpc port was also originally written by Richard Pennington, +and later supplemented and integrated by John Spencer. It is licensed +under the standard MIT terms. + +All other files which have no copyright comments are original works +produced specifically for use as part of this library, written either +by Rich Felker, the main author of the library, or by one or more +contibutors listed above. Details on authorship of individual files +can be found in the git version control history of the project. The +omission of copyright and license comments in each file is in the +interest of source tree size. + +In addition, permission is hereby granted for all public header files +(include/* and arch/*/bits/*) and crt files intended to be linked into +applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit +the copyright notice and permission notice otherwise required by the +license, and to use these files without any requirement of +attribution. These files include substantial contributions from: + +Bobby Bingham +John Spencer +Nicholas J. Kain +Rich Felker +Richard Pennington +Stefan Kristiansson +Szabolcs Nagy + +all of whom have explicitly granted such permission. + +This file previously contained text expressing a belief that most of +the files covered by the above exception were sufficiently trivial not +to be subject to copyright, resulting in confusion over whether it +negated the permissions granted in the license. In the spirit of +permissive licensing, and of not having licensing issues being an +obstacle to adoption, that text has been removed. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/NUMPY_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/NUMPY_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f2d647bf0bc48403c1d15b48aeddbf93a11b458f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/NUMPY_LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2005-2023, NumPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the NumPy Developers nor the names of any + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PACKAGING_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PACKAGING_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2bfcd5297c4700c43a9cde66f82c9c875025241d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PACKAGING_LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + +Copyright (c) Donald Stufft and individual contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PSF_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PSF_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f26bcf4d2de6eb136e31006ca3ab447d5e488adf --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PSF_LICENSE @@ -0,0 +1,279 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the Zero-Clause BSD license. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. + + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +---------------------------------------------------------------------- + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYPERCLIP_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYPERCLIP_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..07cc746cd5ad6f7e90bf5289c7fef026f7a114cb --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYPERCLIP_LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014, Al Sweigart +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the {organization} nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYUPGRADE_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYUPGRADE_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..edeac73dade049c4e5b05c822c5ae92944ab6e00 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYUPGRADE_LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 Anthony Sottile + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/SAS7BDAT_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/SAS7BDAT_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..94b7fe934e85cc742d20f9299c829b530d1a13db --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/SAS7BDAT_LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-2019 Jared Hobbs + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/STATSBASE_JL_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/STATSBASE_JL_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..875a16717e8bac7195fa6b3a8d831deb5f9ac03f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/STATSBASE_JL_LICENSE @@ -0,0 +1,23 @@ +StatsBase.jl is licensed under the MIT License: + +> Copyright (c) 2012-2016: Dahua Lin, Simon Byrne, Andreas Noack, +> Douglas Bates, John Myles White, Simon Kornblith, and other contributors. + +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> "Software"), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/ULTRAJSON_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/ULTRAJSON_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..58fc9dfc0a35bd100de44a4f091d83a2749bd7f5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/ULTRAJSON_LICENSE @@ -0,0 +1,114 @@ +Developed by ESN, an Electronic Arts Inc. studio. +Copyright (c) 2014, Electronic Arts Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. +* Neither the name of ESN, Electronic Arts Inc. nor the +names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS INC. BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +---- + +Portions of code from MODP_ASCII - Ascii transformations (upper/lower, etc) +https://github.com/client9/stringencoders + + Copyright 2005, 2006, 2007 + Nick Galbreath -- nickg [at] modp [dot] com + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + Neither the name of the modp.com nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This is the standard "new" BSD license: + http://www.opensource.org/licenses/bsd-license.php + +https://github.com/client9/stringencoders/blob/cfd5c1507325ae497ea9bacdacba12c0ffd79d30/COPYING + +---- + +Numeric decoder derived from from TCL library +https://opensource.apple.com/source/tcl/tcl-14/tcl/license.terms + * Copyright (c) 1988-1993 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + + This software is copyrighted by the Regents of the University of + California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState + Corporation and other parties. The following terms apply to all files + associated with the software unless explicitly disclaimed in + individual files. + + The authors hereby grant permission to use, copy, modify, distribute, + and license this software and its documentation for any purpose, provided + that existing copyright notices are retained in all copies and that this + notice is included verbatim in any distributions. No written agreement, + license, or royalty fee is required for any of the authorized uses. + Modifications to this software may be copyrighted by their authors + and need not follow the licensing terms described here, provided that + the new terms are clearly indicated on the first page of each file where + they apply. + + IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY + FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY + DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE + IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE + NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR + MODIFICATIONS. + + GOVERNMENT USE: If you are acquiring this software on behalf of the + U.S. government, the Government shall have only "Restricted Rights" + in the software and related documentation as defined in the Federal + Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you + are acquiring the software on behalf of the Department of Defense, the + software shall be classified as "Commercial Computer Software" and the + Government shall have only "Restricted Rights" as defined in Clause + 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the + authors grant the U.S. Government and others acting in its behalf + permission to use and distribute the software in accordance with the + terms specified in this license. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/XSIMD_LICENSE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/XSIMD_LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eee7a54bc956b609b075059bcb7a9105ab04a218 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/XSIMD_LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2016, Johan Mabille, Sylvain Corlay, Wolf Vollprecht and Martin Renou +Copyright (c) 2016, QuantStack +Copyright (c) 2018, Serge Guelton +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-APACHE b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-APACHE new file mode 100644 index 0000000000000000000000000000000000000000..26f4398f24999c3908a11653e3b5ba6f9d681123 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-APACHE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2021 The fast_float authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-BOOST b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-BOOST new file mode 100644 index 0000000000000000000000000000000000000000..127a5bc39ba030c7cb99cc0aedc4f280ffe27310 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-BOOST @@ -0,0 +1,23 @@ +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-MIT b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-MIT new file mode 100644 index 0000000000000000000000000000000000000000..2fb2a37ad7fda521092c8b7b16911176c3f8a81b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-MIT @@ -0,0 +1,27 @@ +MIT License + +Copyright (c) 2021 The fast_float authors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_diff.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..a964482c7aa31423d56bc0a613c26aef56421967 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_diff.py @@ -0,0 +1,304 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameDiff: + def test_diff_requires_integer(self): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((2, 2))) + with pytest.raises(ValueError, match="periods must be an integer"): + df.diff(1.5) + + # GH#44572 np.int64 is accepted + @pytest.mark.parametrize("num", [1, np.int64(1)]) + def test_diff(self, datetime_frame, num): + df = datetime_frame + the_diff = df.diff(num) + + expected = df["A"] - df["A"].shift(num) + tm.assert_series_equal(the_diff["A"], expected) + + def test_diff_int_dtype(self): + # int dtype + a = 10_000_000_000_000_000 + b = a + 1 + ser = pd.Series([a, b]) + + rs = pd.DataFrame({"s": ser}).diff() + assert rs.s[1] == 1 + + def test_diff_mixed_numeric(self, datetime_frame): + # mixed numeric + tf = datetime_frame.astype("float32") + the_diff = tf.diff(1) + tm.assert_series_equal(the_diff["A"], tf["A"] - tf["A"].shift(1)) + + def test_diff_axis1_nonconsolidated(self): + # GH#10907 + df = pd.DataFrame({"y": pd.Series([2]), "z": pd.Series([3])}) + df.insert(0, "x", 1) + result = df.diff(axis=1) + expected = pd.DataFrame({"x": np.nan, "y": pd.Series(1), "z": pd.Series(1)}) + tm.assert_frame_equal(result, expected) + + def test_diff_timedelta64_with_nat(self): + # GH#32441 + arr = np.arange(6).reshape(3, 2).astype("timedelta64[ns]") + arr[:, 0] = np.timedelta64("NaT", "ns") + + df = pd.DataFrame(arr) + result = df.diff(1, axis=0) + + expected = pd.DataFrame( + {0: df[0], 1: [pd.NaT, pd.Timedelta(2), pd.Timedelta(2)]} + ) + tm.assert_equal(result, expected) + + result = df.diff(0) + expected = df - df + assert expected[0].isna().all() + tm.assert_equal(result, expected) + + result = df.diff(-1, axis=1) + expected = df * np.nan + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "UTC"]) + def test_diff_datetime_axis0_with_nat(self, tz, unit): + # GH#32441 + dti = pd.DatetimeIndex(["NaT", "2019-01-01", "2019-01-02"], tz=tz).as_unit(unit) + ser = pd.Series(dti) + + df = ser.to_frame() + + result = df.diff() + ex_index = pd.TimedeltaIndex([pd.NaT, pd.NaT, pd.Timedelta(days=1)]).as_unit( + unit + ) + expected = pd.Series(ex_index).to_frame() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "UTC"]) + def test_diff_datetime_with_nat_zero_periods(self, tz): + # diff on NaT values should give NaT, not timedelta64(0) + dti = pd.date_range("2016-01-01", periods=4, tz=tz) + ser = pd.Series(dti) + df = ser.to_frame().copy() + + df[1] = ser.copy() + + df.iloc[:, 0] = pd.NaT + + expected = df - df + assert expected[0].isna().all() + + result = df.diff(0, axis=0) + tm.assert_frame_equal(result, expected) + + result = df.diff(0, axis=1) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "UTC"]) + def test_diff_datetime_axis0(self, tz): + # GH#18578 + df = pd.DataFrame( + { + 0: pd.date_range("2010", freq="D", periods=2, tz=tz), + 1: pd.date_range("2010", freq="D", periods=2, tz=tz), + } + ) + + result = df.diff(axis=0) + expected = pd.DataFrame( + { + 0: pd.TimedeltaIndex(["NaT", "1 days"]), + 1: pd.TimedeltaIndex(["NaT", "1 days"]), + } + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "UTC"]) + def test_diff_datetime_axis1(self, tz): + # GH#18578 + df = pd.DataFrame( + { + 0: pd.date_range("2010", freq="D", periods=2, tz=tz), + 1: pd.date_range("2010", freq="D", periods=2, tz=tz), + } + ) + + result = df.diff(axis=1) + expected = pd.DataFrame( + { + 0: pd.TimedeltaIndex(["NaT", "NaT"], dtype="m8[us]"), + 1: pd.TimedeltaIndex(["0 days", "0 days"]), + } + ) + tm.assert_frame_equal(result, expected) + + def test_diff_timedelta(self, unit): + # GH#4533 + df = pd.DataFrame( + { + "time": [pd.Timestamp("20130101 9:01"), pd.Timestamp("20130101 9:02")], + "value": [1.0, 2.0], + } + ) + df["time"] = df["time"].dt.as_unit(unit) + + res = df.diff() + exp = pd.DataFrame( + [[pd.NaT, np.nan], [pd.Timedelta("00:01:00"), 1]], columns=["time", "value"] + ) + exp["time"] = exp["time"].dt.as_unit(unit) + tm.assert_frame_equal(res, exp) + + def test_diff_mixed_dtype(self): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + df["A"] = np.array([1, 2, 3, 4, 5], dtype=object) + + result = df.diff() + assert result[0].dtype == np.float64 + + def test_diff_neg_n(self, datetime_frame): + rs = datetime_frame.diff(-1) + xp = datetime_frame - datetime_frame.shift(-1) + tm.assert_frame_equal(rs, xp) + + def test_diff_float_n(self, datetime_frame): + rs = datetime_frame.diff(1.0) + xp = datetime_frame.diff(1) + tm.assert_frame_equal(rs, xp) + + def test_diff_axis(self): + # GH#9727 + df = pd.DataFrame([[1.0, 2.0], [3.0, 4.0]]) + tm.assert_frame_equal( + df.diff(axis=1), pd.DataFrame([[np.nan, 1.0], [np.nan, 1.0]]) + ) + tm.assert_frame_equal( + df.diff(axis=0), pd.DataFrame([[np.nan, np.nan], [2.0, 2.0]]) + ) + + def test_diff_period(self): + # GH#32995 Don't pass an incorrect axis + pi = pd.date_range("2016-01-01", periods=3).to_period("D") + df = pd.DataFrame({"A": pi}) + + result = df.diff(1, axis=1) + + expected = (df - pd.NaT).astype(object) + tm.assert_frame_equal(result, expected) + + def test_diff_axis1_mixed_dtypes(self): + # GH#32995 operate column-wise when we have mixed dtypes and axis=1 + df = pd.DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)}) + + expected = pd.DataFrame({"A": [np.nan, np.nan, np.nan], "B": df["B"] / 2}) + + result = df.diff(axis=1) + tm.assert_frame_equal(result, expected) + + # GH#21437 mixed-float-dtypes + df = pd.DataFrame( + {"a": np.arange(3, dtype="float32"), "b": np.arange(3, dtype="float64")} + ) + result = df.diff(axis=1) + expected = pd.DataFrame({"a": df["a"] * np.nan, "b": df["b"] * 0}) + tm.assert_frame_equal(result, expected) + + def test_diff_axis1_mixed_dtypes_large_periods(self): + # GH#32995 operate column-wise when we have mixed dtypes and axis=1 + df = pd.DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)}) + + expected = df * np.nan + + result = df.diff(axis=1, periods=3) + tm.assert_frame_equal(result, expected) + + def test_diff_axis1_mixed_dtypes_negative_periods(self): + # GH#32995 operate column-wise when we have mixed dtypes and axis=1 + df = pd.DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)}) + + expected = pd.DataFrame({"A": -1.0 * df["A"], "B": df["B"] * np.nan}) + + result = df.diff(axis=1, periods=-1) + tm.assert_frame_equal(result, expected) + + def test_diff_sparse(self): + # GH#28813 .diff() should work for sparse dataframes as well + sparse_df = pd.DataFrame([[0, 1], [1, 0]], dtype="Sparse[int]") + + result = sparse_df.diff() + expected = pd.DataFrame( + [[np.nan, np.nan], [1.0, -1.0]], dtype=pd.SparseDtype("float", 0.0) + ) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "axis,expected", + [ + ( + 0, + pd.DataFrame( + { + "a": [pd.NA, 0, 1, 0, pd.NA, pd.NA, pd.NA, 0], + "b": [pd.NA, 1, pd.NA, pd.NA, -2, 1, pd.NA, pd.NA], + "c": np.repeat(pd.NA, 8), # type: ignore[call-overload] + "d": [pd.NA, 3, 5, 7, 9, 11, 13, 15], + }, + dtype="Int64", + ), + ), + ( + 1, + pd.DataFrame( + { + "a": np.repeat(pd.NA, 8), # type: ignore[call-overload] + "b": [0, 1, pd.NA, 1, pd.NA, pd.NA, pd.NA, 0], + "c": np.repeat(pd.NA, 8), # type: ignore[call-overload] + "d": np.repeat(pd.NA, 8), # type: ignore[call-overload] + }, + dtype="Int64", + ), + ), + ], + ) + def test_diff_integer_na(self, axis, expected): + # GH#24171 IntegerNA Support for DataFrame.diff() + df = pd.DataFrame( + { + "a": np.repeat([0, 1, pd.NA, 2], 2), + "b": np.tile([0, 1, pd.NA, 2], 2), + "c": np.repeat(pd.NA, 8), + "d": np.arange(1, 9) ** 2, + }, + dtype="Int64", + ) + + # Test case for default behaviour of diff + result = df.diff(axis=axis) + tm.assert_frame_equal(result, expected) + + def test_diff_readonly(self): + # https://github.com/pandas-dev/pandas/issues/35559 + arr = np.random.default_rng(2).standard_normal((5, 2)) + arr.flags.writeable = False + df = pd.DataFrame(arr) + result = df.diff() + expected = pd.DataFrame(np.array(df)).diff() + tm.assert_frame_equal(result, expected) + + def test_diff_all_int_dtype(self, any_int_numpy_dtype): + # GH 14773 + df = pd.DataFrame(range(5)) + df = df.astype(any_int_numpy_dtype) + result = df.diff() + expected_dtype = ( + "float32" if any_int_numpy_dtype in ("int8", "int16") else "float64" + ) + expected = pd.DataFrame([np.nan, 1.0, 1.0, 1.0, 1.0], dtype=expected_dtype) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_dot.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_dot.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab0c22710d18ec7f23784dddb92336ababd9379 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_dot.py @@ -0,0 +1,168 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class DotSharedTests: + @pytest.fixture + def obj(self): + raise NotImplementedError + + @pytest.fixture + def other(self) -> pd.DataFrame: + """ + other is a DataFrame that is indexed so that obj.dot(other) is valid + """ + raise NotImplementedError + + @pytest.fixture + def expected(self, obj, other) -> pd.DataFrame: + """ + The expected result of obj.dot(other) + """ + raise NotImplementedError + + @classmethod + def reduced_dim_assert(cls, result, expected): + """ + Assertion about results with 1 fewer dimension that self.obj + """ + raise NotImplementedError + + def test_dot_equiv_values_dot(self, obj, other, expected): + # `expected` is constructed from obj.values.dot(other.values) + result = obj.dot(other) + tm.assert_equal(result, expected) + + def test_dot_2d_ndarray(self, obj, other, expected): + # Check ndarray argument; in this case we get matching values, + # but index/columns may not match + result = obj.dot(other.values) + assert np.all(result == expected.values) + + def test_dot_1d_ndarray(self, obj, expected): + # can pass correct-length array + row = obj.iloc[0] if obj.ndim == 2 else obj + + result = obj.dot(row.values) + expected = obj.dot(row) + self.reduced_dim_assert(result, expected) + + def test_dot_series(self, obj, other, expected): + # Check series argument + result = obj.dot(other["1"]) + self.reduced_dim_assert(result, expected["1"]) + + def test_dot_series_alignment(self, obj, other, expected): + result = obj.dot(other.iloc[::-1]["1"]) + self.reduced_dim_assert(result, expected["1"]) + + def test_dot_aligns(self, obj, other, expected): + # Check index alignment + other2 = other.iloc[::-1] + result = obj.dot(other2) + tm.assert_equal(result, expected) + + def test_dot_shape_mismatch(self, obj): + msg = "Dot product shape mismatch" + # exception raised is of type Exception + with pytest.raises(Exception, match=msg): + obj.dot(obj.values[:3]) + + def test_dot_misaligned(self, obj, other): + msg = "matrices are not aligned" + with pytest.raises(ValueError, match=msg): + obj.dot(other.T) + + +class TestSeriesDot(DotSharedTests): + @pytest.fixture + def obj(self): + return pd.Series( + np.random.default_rng(2).standard_normal(4), index=["p", "q", "r", "s"] + ) + + @pytest.fixture + def other(self): + return pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 4)), + index=["1", "2", "3"], + columns=["p", "q", "r", "s"], + ).T + + @pytest.fixture + def expected(self, obj, other): + return pd.Series(np.dot(obj.values, other.values), index=other.columns) + + @classmethod + def reduced_dim_assert(cls, result, expected): + """ + Assertion about results with 1 fewer dimension that self.obj + """ + tm.assert_almost_equal(result, expected) + + +class TestDataFrameDot(DotSharedTests): + @pytest.fixture + def obj(self): + return pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 4)), + index=["a", "b", "c"], + columns=["p", "q", "r", "s"], + ) + + @pytest.fixture + def other(self): + return pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 2)), + index=["p", "q", "r", "s"], + columns=["1", "2"], + ) + + @pytest.fixture + def expected(self, obj, other): + return pd.DataFrame( + np.dot(obj.values, other.values), index=obj.index, columns=other.columns + ) + + @classmethod + def reduced_dim_assert(cls, result, expected): + """ + Assertion about results with 1 fewer dimension that self.obj + """ + tm.assert_series_equal(result, expected, check_names=False) + assert result.name is None + + +@pytest.mark.parametrize( + "dtype,exp_dtype", + [("Float32", "Float64"), ("Int16", "Int32"), ("float[pyarrow]", "double[pyarrow]")], +) +def test_arrow_dtype(dtype, exp_dtype): + pytest.importorskip("pyarrow") + + cols = ["a", "b"] + df_a = pd.DataFrame([[1, 2], [3, 4], [5, 6]], columns=cols, dtype="int32") + df_b = pd.DataFrame([[1, 0], [0, 1]], index=cols, dtype=dtype) + result = df_a.dot(df_b) + expected = pd.DataFrame([[1, 2], [3, 4], [5, 6]], dtype=exp_dtype) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "dtype,exp_dtype", + [("Float32", "Float64"), ("Int16", "Int32"), ("float[pyarrow]", "double[pyarrow]")], +) +def test_arrow_dtype_series(dtype, exp_dtype): + pytest.importorskip("pyarrow") + + cols = ["a", "b"] + series_a = pd.Series([1, 2], index=cols, dtype="int32") + df_b = pd.DataFrame([[1, 0], [0, 1]], index=cols, dtype=dtype) + result = series_a.dot(df_b) + expected = pd.Series([1, 2], dtype=exp_dtype) + + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_drop.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_drop.py new file mode 100644 index 0000000000000000000000000000000000000000..79bf97fa89c96786bc97774ab188b5ac16e47c8a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_drop.py @@ -0,0 +1,590 @@ +import re + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize( + "msg,labels,level", + [ + (r"labels \[4\] not found in level", 4, "a"), + (r"labels \[7\] not found in level", 7, "b"), + ], +) +def test_drop_raise_exception_if_labels_not_in_level(msg, labels, level): + # GH 8594 + mi = pd.MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"]) + s = pd.Series([10, 20, 30], index=mi) + df = pd.DataFrame([10, 20, 30], index=mi) + + with pytest.raises(KeyError, match=msg): + s.drop(labels, level=level) + with pytest.raises(KeyError, match=msg): + df.drop(labels, level=level) + + +@pytest.mark.parametrize("labels,level", [(4, "a"), (7, "b")]) +def test_drop_errors_ignore(labels, level): + # GH 8594 + mi = pd.MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"]) + s = pd.Series([10, 20, 30], index=mi) + df = pd.DataFrame([10, 20, 30], index=mi) + + expected_s = s.drop(labels, level=level, errors="ignore") + tm.assert_series_equal(s, expected_s) + + expected_df = df.drop(labels, level=level, errors="ignore") + tm.assert_frame_equal(df, expected_df) + + +def test_drop_with_non_unique_datetime_index_and_invalid_keys(): + # GH 30399 + + # define dataframe with unique datetime index + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), + columns=["a", "b", "c"], + index=pd.date_range("2012", freq="h", periods=5), + ) + # create dataframe with non-unique datetime index + df = df.iloc[[0, 2, 2, 3]].copy() + + with pytest.raises(KeyError, match="not found in axis"): + df.drop(["a", "b"]) # Dropping with labels not exist in the index + + +class TestDataFrameDrop: + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.drop is") + def test_drop_names(self): + df = pd.DataFrame( + [[1, 2, 3], [3, 4, 5], [5, 6, 7]], + index=["a", "b", "c"], + columns=["d", "e", "f"], + ) + df.index.name, df.columns.name = "first", "second" + df_dropped_b = df.drop("b") + df_dropped_e = df.drop("e", axis=1) + df_inplace_b, df_inplace_e = df.copy(), df.copy() + return_value = df_inplace_b.drop("b", inplace=True) + assert return_value is None + return_value = df_inplace_e.drop("e", axis=1, inplace=True) + assert return_value is None + for obj in (df_dropped_b, df_dropped_e, df_inplace_b, df_inplace_e): + assert obj.index.name == "first" + assert obj.columns.name == "second" + assert list(df.columns) == ["d", "e", "f"] + + msg = r"\['g'\] not found in axis" + with pytest.raises(KeyError, match=msg): + df.drop(["g"]) + with pytest.raises(KeyError, match=msg): + df.drop(["g"], axis=1) + + # errors = 'ignore' + dropped = df.drop(["g"], errors="ignore") + expected = pd.Index(["a", "b", "c"], name="first") + tm.assert_index_equal(dropped.index, expected) + + dropped = df.drop(["b", "g"], errors="ignore") + expected = pd.Index(["a", "c"], name="first") + tm.assert_index_equal(dropped.index, expected) + + dropped = df.drop(["g"], axis=1, errors="ignore") + expected = pd.Index(["d", "e", "f"], name="second") + tm.assert_index_equal(dropped.columns, expected) + + dropped = df.drop(["d", "g"], axis=1, errors="ignore") + expected = pd.Index(["e", "f"], name="second") + tm.assert_index_equal(dropped.columns, expected) + + # GH 16398 + dropped = df.drop([], errors="ignore") + expected = pd.Index(["a", "b", "c"], name="first") + tm.assert_index_equal(dropped.index, expected) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.drop is") + def test_drop(self): + simple = pd.DataFrame({"A": [1, 2, 3, 4], "B": [0, 1, 2, 3]}) + tm.assert_frame_equal(simple.drop("A", axis=1), simple[["B"]]) + tm.assert_frame_equal(simple.drop(["A", "B"], axis="columns"), simple[[]]) + tm.assert_frame_equal(simple.drop([0, 1, 3], axis=0), simple.loc[[2], :]) + tm.assert_frame_equal(simple.drop([0, 3], axis="index"), simple.loc[[1, 2], :]) + + with pytest.raises(KeyError, match=r"\[5\] not found in axis"): + simple.drop(5) + with pytest.raises(KeyError, match=r"\['C'\] not found in axis"): + simple.drop("C", axis=1) + with pytest.raises(KeyError, match=r"\[5\] not found in axis"): + simple.drop([1, 5]) + with pytest.raises(KeyError, match=r"\['C'\] not found in axis"): + simple.drop(["A", "C"], axis=1) + + # GH 42881 + with pytest.raises(KeyError, match=r"\['C', 'D', 'F'\] not found in axis"): + simple.drop(["C", "D", "F"], axis=1) + + # errors = 'ignore' + tm.assert_frame_equal(simple.drop(5, errors="ignore"), simple) + tm.assert_frame_equal( + simple.drop([0, 5], errors="ignore"), simple.loc[[1, 2, 3], :] + ) + tm.assert_frame_equal(simple.drop("C", axis=1, errors="ignore"), simple) + tm.assert_frame_equal( + simple.drop(["A", "C"], axis=1, errors="ignore"), simple[["B"]] + ) + + # non-unique - wheee! + nu_df = pd.DataFrame( + list(zip(range(3), range(-3, 0), list("abc"), strict=True)), + columns=["a", "a", "b"], + ) + tm.assert_frame_equal(nu_df.drop("a", axis=1), nu_df[["b"]]) + tm.assert_frame_equal(nu_df.drop("b", axis="columns"), nu_df["a"]) + tm.assert_frame_equal(nu_df.drop([]), nu_df) # GH 16398 + + nu_df = nu_df.set_index(pd.Index(["X", "Y", "X"])) + nu_df.columns = list("abc") + tm.assert_frame_equal(nu_df.drop("X", axis="rows"), nu_df.loc[["Y"], :]) + tm.assert_frame_equal(nu_df.drop(["X", "Y"], axis=0), nu_df.loc[[], :]) + + # inplace cache issue + # GH#5628 + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 3)), columns=list("abc") + ) + expected = df[~(df.b > 0)] + return_value = df.drop(labels=df[df.b > 0].index, inplace=True) + assert return_value is None + tm.assert_frame_equal(df, expected) + + def test_drop_multiindex_not_lexsorted(self, performance_warning): + # GH#11640 + + # define the lexsorted version + lexsorted_mi = pd.MultiIndex.from_tuples( + [("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"] + ) + lexsorted_df = pd.DataFrame([[1, 3, 4]], columns=lexsorted_mi) + assert lexsorted_df.columns._is_lexsorted() + + # define the non-lexsorted version + not_lexsorted_df = pd.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.drop("a", axis=1).astype(float) + msg = "dropping on a non-lexsorted multi-index without a level parameter" + with tm.assert_produces_warning(performance_warning, match=msg): + result = not_lexsorted_df.drop("a", axis=1) + + tm.assert_frame_equal(result, expected) + + def test_drop_api_equivalence(self): + # equivalence of the labels/axis and index/columns API's (GH#12392) + df = pd.DataFrame( + [[1, 2, 3], [3, 4, 5], [5, 6, 7]], + index=["a", "b", "c"], + columns=["d", "e", "f"], + ) + + res1 = df.drop("a") + res2 = df.drop(index="a") + tm.assert_frame_equal(res1, res2) + + res1 = df.drop("d", axis=1) + res2 = df.drop(columns="d") + tm.assert_frame_equal(res1, res2) + + res1 = df.drop(labels="e", axis=1) + res2 = df.drop(columns="e") + tm.assert_frame_equal(res1, res2) + + res1 = df.drop(["a"], axis=0) + res2 = df.drop(index=["a"]) + tm.assert_frame_equal(res1, res2) + + res1 = df.drop(["a"], axis=0).drop(["d"], axis=1) + res2 = df.drop(index=["a"], columns=["d"]) + tm.assert_frame_equal(res1, res2) + + msg = "Cannot specify both 'labels' and 'index'/'columns'" + with pytest.raises(ValueError, match=msg): + df.drop(labels="a", index="b") + + with pytest.raises(ValueError, match=msg): + df.drop(labels="a", columns="b") + + msg = "Need to specify at least one of 'labels', 'index' or 'columns'" + with pytest.raises(ValueError, match=msg): + df.drop(axis=1) + + @pytest.mark.parametrize( + "actual", + [ + pd.DataFrame([[1, 2, 3], [1, 2, 3]], index=["a", "a"]), + pd.DataFrame([[1, 2, 3], [1, 2, 3]], index=["a", "b"]), + pd.DataFrame([[1, 2, 3], [1, 2, 3]], index=["a", "b"]).set_index([0, 1]), + pd.DataFrame([[1, 2, 3], [1, 2, 3]], index=["a", "a"]).set_index([0, 1]), + ], + ) + def test_raise_on_drop_duplicate_index(self, actual): + # GH#19186 + level = 0 if isinstance(actual.index, pd.MultiIndex) else None + msg = re.escape("\"['c'] not found in axis\"") + with pytest.raises(KeyError, match=msg): + actual.drop("c", level=level, axis=0) + with pytest.raises(KeyError, match=msg): + actual.T.drop("c", level=level, axis=1) + expected_no_err = actual.drop("c", axis=0, level=level, errors="ignore") + tm.assert_frame_equal(expected_no_err, actual) + expected_no_err = actual.T.drop("c", axis=1, level=level, errors="ignore") + tm.assert_frame_equal(expected_no_err.T, actual) + + @pytest.mark.parametrize("index", [[1, 2, 3], [1, 1, 2]]) + @pytest.mark.parametrize("drop_labels", [[], [1], [2]]) + def test_drop_empty_list(self, index, drop_labels): + # GH#21494 + expected_index = [i for i in index if i not in drop_labels] + frame = pd.DataFrame(index=index).drop(drop_labels) + tm.assert_frame_equal(frame, pd.DataFrame(index=expected_index)) + + @pytest.mark.parametrize("index", [[1, 2, 3], [1, 2, 2]]) + @pytest.mark.parametrize("drop_labels", [[1, 4], [4, 5]]) + def test_drop_non_empty_list(self, index, drop_labels): + # GH# 21494 + with pytest.raises(KeyError, match="not found in axis"): + pd.DataFrame(index=index).drop(drop_labels) + + @pytest.mark.parametrize( + "empty_listlike", + [ + [], + {}, + np.array([]), + pd.Series([], dtype="datetime64[ns]"), + pd.Index([]), + pd.DatetimeIndex([]), + ], + ) + def test_drop_empty_listlike_non_unique_datetime_index(self, empty_listlike): + # GH#27994 + data = {"column_a": [5, 10], "column_b": ["one", "two"]} + index = [pd.Timestamp("2021-01-01"), pd.Timestamp("2021-01-01")] + df = pd.DataFrame(data, index=index) + + # Passing empty list-like should return the same DataFrame. + expected = df.copy() + result = df.drop(empty_listlike) + tm.assert_frame_equal(result, expected) + + def test_mixed_depth_drop(self): + arrays = [ + ["a", "top", "top", "routine1", "routine1", "routine2"], + ["", "OD", "OD", "result1", "result2", "result1"], + ["", "wx", "wy", "", "", ""], + ] + + tuples = sorted(zip(*arrays, strict=True)) + index = pd.MultiIndex.from_tuples(tuples) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 6)), columns=index + ) + + result = df.drop("a", axis=1) + expected = df.drop([("a", "", "")], axis=1) + tm.assert_frame_equal(expected, result) + + result = df.drop(["top"], axis=1) + expected = df.drop([("top", "OD", "wx")], axis=1) + expected = expected.drop([("top", "OD", "wy")], axis=1) + tm.assert_frame_equal(expected, result) + + result = df.drop(("top", "OD", "wx"), axis=1) + expected = df.drop([("top", "OD", "wx")], axis=1) + tm.assert_frame_equal(expected, result) + + expected = df.drop([("top", "OD", "wy")], axis=1) + expected = df.drop("top", axis=1) + + result = df.drop("result1", level=1, axis=1) + expected = df.drop( + [("routine1", "result1", ""), ("routine2", "result1", "")], axis=1 + ) + tm.assert_frame_equal(expected, result) + + def test_drop_multiindex_other_level_nan(self): + # GH#12754 + df = ( + pd.DataFrame( + { + "A": ["one", "one", "two", "two"], + "B": [np.nan, 0.0, 1.0, 2.0], + "C": ["a", "b", "c", "c"], + "D": [1, 2, 3, 4], + } + ) + .set_index(["A", "B", "C"]) + .sort_index() + ) + result = df.drop("c", level="C") + expected = pd.DataFrame( + [2, 1], + columns=["D"], + index=pd.MultiIndex.from_tuples( + [("one", 0.0, "b"), ("one", np.nan, "a")], names=["A", "B", "C"] + ), + ) + tm.assert_frame_equal(result, expected) + + def test_drop_raise_with_both_axis_and_index(self): + # GH#61823 + df = pd.DataFrame( + [[1, 2, 3], [3, 4, 5], [5, 6, 7]], + index=["a", "b", "c"], + columns=["d", "e", "f"], + ) + + msg = "Cannot specify both 'axis' and 'index'/'columns'" + with pytest.raises(ValueError, match=msg): + df.drop(index="b", axis=1) + + def test_drop_nonunique(self): + df = pd.DataFrame( + [ + ["x-a", "x", "a", 1.5], + ["x-a", "x", "a", 1.2], + ["z-c", "z", "c", 3.1], + ["x-a", "x", "a", 4.1], + ["x-b", "x", "b", 5.1], + ["x-b", "x", "b", 4.1], + ["x-b", "x", "b", 2.2], + ["y-a", "y", "a", 1.2], + ["z-b", "z", "b", 2.1], + ], + columns=["var1", "var2", "var3", "var4"], + ) + + grp_size = df.groupby("var1").size() + drop_idx = grp_size.loc[grp_size == 1] + + idf = df.set_index(["var1", "var2", "var3"]) + + # it works! GH#2101 + result = idf.drop(drop_idx.index, level=0).reset_index() + expected = df[-df.var1.isin(drop_idx.index)] + + result.index = expected.index + + tm.assert_frame_equal(result, expected) + + def test_drop_level(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + result = frame.drop(["bar", "qux"], level="first") + expected = frame.iloc[[0, 1, 2, 5, 6]] + tm.assert_frame_equal(result, expected) + + result = frame.drop(["two"], level="second") + expected = frame.iloc[[0, 2, 3, 6, 7, 9]] + tm.assert_frame_equal(result, expected) + + result = frame.T.drop(["bar", "qux"], axis=1, level="first") + expected = frame.iloc[[0, 1, 2, 5, 6]].T + tm.assert_frame_equal(result, expected) + + result = frame.T.drop(["two"], axis=1, level="second") + expected = frame.iloc[[0, 2, 3, 6, 7, 9]].T + tm.assert_frame_equal(result, expected) + + def test_drop_level_nonunique_datetime(self): + # GH#12701 + idx = pd.Index([2, 3, 4, 4, 5], name="id") + idxdt = pd.to_datetime( + [ + "2016-03-23 14:00", + "2016-03-23 15:00", + "2016-03-23 16:00", + "2016-03-23 16:00", + "2016-03-23 17:00", + ] + ) + df = pd.DataFrame(np.arange(10).reshape(5, 2), columns=list("ab"), index=idx) + df["tstamp"] = idxdt + df = df.set_index("tstamp", append=True) + ts = pd.Timestamp("201603231600") + assert df.index.is_unique is False + + result = df.drop(ts, level="tstamp") + expected = df.loc[idx != 4] + tm.assert_frame_equal(result, expected) + + def test_drop_tz_aware_timestamp_across_dst(self, frame_or_series): + # GH#21761 + start = pd.Timestamp("2017-10-29", tz="Europe/Berlin") + end = pd.Timestamp("2017-10-29 04:00:00", tz="Europe/Berlin") + index = pd.date_range(start, end, freq="15min") + data = frame_or_series(data=[1] * len(index), index=index) + result = data.drop(start) + expected_start = pd.Timestamp("2017-10-29 00:15:00", tz="Europe/Berlin") + expected_idx = pd.date_range(expected_start, end, freq="15min") + expected = frame_or_series(data=[1] * len(expected_idx), index=expected_idx) + tm.assert_equal(result, expected) + + def test_drop_preserve_names(self): + index = pd.MultiIndex.from_arrays( + [[0, 0, 0, 1, 1, 1], [1, 2, 3, 1, 2, 3]], names=["one", "two"] + ) + + df = pd.DataFrame(np.random.default_rng(2).standard_normal((6, 3)), index=index) + + result = df.drop([(0, 2)]) + assert result.index.names == ("one", "two") + + @pytest.mark.parametrize( + "operation", ["__iadd__", "__isub__", "__imul__", "__ipow__"] + ) + @pytest.mark.parametrize("inplace", [False, True]) + def test_inplace_drop_and_operation(self, operation, inplace): + # GH#30484 + df = pd.DataFrame({"x": range(5)}) + expected = df.copy() + df["y"] = range(5) + y = df["y"] + + # For GH 63207 since pytest.mark.filterwarning did not filter warning here + msg = "The inplace keyword in DataFrame.drop is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + if inplace: + df.drop("y", axis=1, inplace=inplace) + else: + df = df.drop("y", axis=1, inplace=inplace) + + # Perform operation and check result + getattr(y, operation)(1) + tm.assert_frame_equal(df, expected) + + def test_drop_with_non_unique_multiindex(self): + # GH#36293 + mi = pd.MultiIndex.from_arrays([["x", "y", "x"], ["i", "j", "i"]]) + df = pd.DataFrame([1, 2, 3], index=mi) + result = df.drop(index="x") + expected = pd.DataFrame([2], index=pd.MultiIndex.from_arrays([["y"], ["j"]])) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("indexer", [("a", "a"), [("a", "a")]]) + def test_drop_tuple_with_non_unique_multiindex(self, indexer): + # GH#42771 + idx = pd.MultiIndex.from_product([["a", "b"], ["a", "a"]]) + df = pd.DataFrame({"x": range(len(idx))}, index=idx) + result = df.drop(index=[("a", "a")]) + expected = pd.DataFrame( + {"x": [2, 3]}, index=pd.MultiIndex.from_tuples([("b", "a"), ("b", "a")]) + ) + tm.assert_frame_equal(result, expected) + + def test_drop_with_duplicate_columns(self): + df = pd.DataFrame( + [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"] + ) + result = df.drop(["a"], axis=1) + expected = pd.DataFrame([[1], [1], [1]], columns=["bar"]) + tm.assert_frame_equal(result, expected) + result = df.drop("a", axis=1) + tm.assert_frame_equal(result, expected) + + def test_drop_with_duplicate_columns2(self): + # drop buggy GH#6240 + df = pd.DataFrame( + { + "A": np.random.default_rng(2).standard_normal(5), + "B": np.random.default_rng(2).standard_normal(5), + "C": np.random.default_rng(2).standard_normal(5), + "D": ["a", "b", "c", "d", "e"], + } + ) + + expected = df.take([0, 1, 1], axis=1) + df2 = df.take([2, 0, 1, 2, 1], axis=1) + result = df2.drop("C", axis=1) + tm.assert_frame_equal(result, expected) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.drop is") + def test_drop_inplace_no_leftover_column_reference(self): + # GH 13934 + df = pd.DataFrame({"a": [1, 2, 3]}, columns=pd.Index(["a"], dtype="object")) + a = df.a + df.drop(["a"], axis=1, inplace=True) + tm.assert_index_equal(df.columns, pd.Index([], dtype="object")) + a -= a.mean() + tm.assert_index_equal(df.columns, pd.Index([], dtype="object")) + + def test_drop_level_missing_label_multiindex(self): + # GH 18561 + df = pd.DataFrame(index=pd.MultiIndex.from_product([range(3), range(3)])) + with pytest.raises(KeyError, match="labels \\[5\\] not found in level"): + df.drop(5, level=0) + + @pytest.mark.parametrize("idx, level", [(["a", "b"], 0), (["a"], None)]) + def test_drop_index_ea_dtype(self, any_numeric_ea_dtype, idx, level): + # GH#45860 + df = pd.DataFrame( + {"a": [1, 2, 2, pd.NA], "b": 100}, dtype=any_numeric_ea_dtype + ).set_index(idx) + result = df.drop(pd.Index([2, pd.NA]), level=level) + expected = pd.DataFrame( + {"a": [1], "b": 100}, dtype=any_numeric_ea_dtype + ).set_index(idx) + tm.assert_frame_equal(result, expected) + + def test_drop_index_arrow_binary_dtype_na(self): + # GH#63304 + pytest.importorskip("pyarrow") + + idx = pd.Index( + [None, b"\xe3", b"\xe3"], dtype="binary[pyarrow]", name="bytes_col" + ) + df = pd.DataFrame(index=idx) + + result = df.drop(index=[pd.NA]) + idx = pd.Index([b"\xe3", b"\xe3"], dtype="binary[pyarrow]", name="bytes_col") + expected = pd.DataFrame(index=idx) + tm.assert_frame_equal(result, expected) + + def test_drop_parse_strings_datetime_index(self): + # GH #5355 + df = pd.DataFrame( + {"a": [1, 2], "b": [1, 2]}, + index=[pd.Timestamp("2000-01-03"), pd.Timestamp("2000-01-04")], + ) + result = df.drop("2000-01-03", axis=0) + expected = pd.DataFrame( + {"a": [2], "b": [2]}, index=[pd.Timestamp("2000-01-04")] + ) + tm.assert_frame_equal(result, expected) + + def test_drop_inplace_depr(self): + # GH 63207 + df = pd.DataFrame( + {"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9], "d": [10, 11, 12]} + ) + msg = "The inplace keyword in DataFrame.drop is deprecated" + + # uses keyword, sets to true, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.drop(columns=["a"], inplace=True) + # uses keyword, sets to false, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.drop(columns=["b"], inplace=False) + # does not use keyword, no warning + with tm.assert_produces_warning(False): + df.drop(columns=["c"]) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_drop_duplicates.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_drop_duplicates.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf80b4e621619a1189d1ab09bef54712d986d44 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_drop_duplicates.py @@ -0,0 +1,553 @@ +from datetime import datetime +import re + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize("subset", ["a", ["a"], ["a", "B"]]) +def test_drop_duplicates_with_misspelled_column_name(subset): + # GH 19730 + df = pd.DataFrame({"A": [0, 0, 1], "B": [0, 0, 1], "C": [0, 0, 1]}) + msg = re.escape("Index(['a'], dtype=") + + with pytest.raises(KeyError, match=msg): + df.drop_duplicates(subset) + + +def test_drop_duplicates(): + df = pd.DataFrame( + { + "AAA": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": [1, 1, 2, 2, 2, 2, 1, 2], + "D": range(8), + } + ) + # single column + result = df.drop_duplicates("AAA") + expected = df[:2] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("AAA", keep="last") + expected = df.loc[[6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("AAA", keep=False) + expected = df.loc[[]] + tm.assert_frame_equal(result, expected) + assert len(result) == 0 + + # multi column + expected = df.loc[[0, 1, 2, 3]] + result = df.drop_duplicates(np.array(["AAA", "B"])) + tm.assert_frame_equal(result, expected) + result = df.drop_duplicates(["AAA", "B"]) + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(("AAA", "B"), keep="last") + expected = df.loc[[0, 5, 6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(("AAA", "B"), keep=False) + expected = df.loc[[0]] + tm.assert_frame_equal(result, expected) + + # consider everything + df2 = df.loc[:, ["AAA", "B", "C"]] + + result = df2.drop_duplicates() + # in this case only + expected = df2.drop_duplicates(["AAA", "B"]) + tm.assert_frame_equal(result, expected) + + result = df2.drop_duplicates(keep="last") + expected = df2.drop_duplicates(["AAA", "B"], keep="last") + tm.assert_frame_equal(result, expected) + + result = df2.drop_duplicates(keep=False) + expected = df2.drop_duplicates(["AAA", "B"], keep=False) + tm.assert_frame_equal(result, expected) + + # integers + result = df.drop_duplicates("C") + expected = df.iloc[[0, 2]] + tm.assert_frame_equal(result, expected) + result = df.drop_duplicates("C", keep="last") + expected = df.iloc[[-2, -1]] + tm.assert_frame_equal(result, expected) + + df["E"] = df["C"].astype("int8") + result = df.drop_duplicates("E") + expected = df.iloc[[0, 2]] + tm.assert_frame_equal(result, expected) + result = df.drop_duplicates("E", keep="last") + expected = df.iloc[[-2, -1]] + tm.assert_frame_equal(result, expected) + + # GH 11376 + df = pd.DataFrame({"x": [7, 6, 3, 3, 4, 8, 0], "y": [0, 6, 5, 5, 9, 1, 2]}) + expected = df.loc[df.index != 3] + tm.assert_frame_equal(df.drop_duplicates(), expected) + + df = pd.DataFrame([[1, 0], [0, 2]]) + tm.assert_frame_equal(df.drop_duplicates(), df) + + df = pd.DataFrame([[-2, 0], [0, -4]]) + tm.assert_frame_equal(df.drop_duplicates(), df) + + x = np.iinfo(np.int64).max / 3 * 2 + df = pd.DataFrame([[-x, x], [0, x + 4]]) + tm.assert_frame_equal(df.drop_duplicates(), df) + + df = pd.DataFrame([[-x, x], [x, x + 4]]) + tm.assert_frame_equal(df.drop_duplicates(), df) + + # GH 11864 + df = pd.DataFrame([i] * 9 for i in range(16)) + df = pd.concat([df, pd.DataFrame([[1] + [0] * 8])], ignore_index=True) + + for keep in ["first", "last", False]: + assert df.duplicated(keep=keep).sum() == 0 + + +def test_drop_duplicates_with_duplicate_column_names(): + # GH17836 + df = pd.DataFrame([[1, 2, 5], [3, 4, 6], [3, 4, 7]], columns=["a", "a", "b"]) + + result0 = df.drop_duplicates() + tm.assert_frame_equal(result0, df) + + result1 = df.drop_duplicates("a") + expected1 = df[:2] + tm.assert_frame_equal(result1, expected1) + + +def test_drop_duplicates_for_take_all(): + df = pd.DataFrame( + { + "AAA": ["foo", "bar", "baz", "bar", "foo", "bar", "qux", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": [1, 1, 2, 2, 2, 2, 1, 2], + "D": range(8), + } + ) + # single column + result = df.drop_duplicates("AAA") + expected = df.iloc[[0, 1, 2, 6]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("AAA", keep="last") + expected = df.iloc[[2, 5, 6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("AAA", keep=False) + expected = df.iloc[[2, 6]] + tm.assert_frame_equal(result, expected) + + # multiple columns + result = df.drop_duplicates(["AAA", "B"]) + expected = df.iloc[[0, 1, 2, 3, 4, 6]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(["AAA", "B"], keep="last") + expected = df.iloc[[0, 1, 2, 5, 6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(["AAA", "B"], keep=False) + expected = df.iloc[[0, 1, 2, 6]] + tm.assert_frame_equal(result, expected) + + +def test_drop_duplicates_tuple(): + df = pd.DataFrame( + { + ("AA", "AB"): ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": [1, 1, 2, 2, 2, 2, 1, 2], + "D": range(8), + } + ) + # single column + result = df.drop_duplicates(("AA", "AB")) + expected = df[:2] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(("AA", "AB"), keep="last") + expected = df.loc[[6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(("AA", "AB"), keep=False) + expected = df.loc[[]] # empty df + assert len(result) == 0 + tm.assert_frame_equal(result, expected) + + # multi column + expected = df.loc[[0, 1, 2, 3]] + result = df.drop_duplicates((("AA", "AB"), "B")) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.drop_duplicates") +@pytest.mark.parametrize( + "df", + [ + pd.DataFrame(), + pd.DataFrame(columns=[]), + pd.DataFrame(columns=["A", "B", "C"]), + pd.DataFrame(index=[]), + pd.DataFrame(index=["A", "B", "C"]), + ], +) +def test_drop_duplicates_empty(df): + # GH 20516 + result = df.drop_duplicates() + tm.assert_frame_equal(result, df) + + result = df.copy() + result.drop_duplicates(inplace=True) + tm.assert_frame_equal(result, df) + + +def test_drop_duplicates_NA(): + # none + df = pd.DataFrame( + { + "A": [None, None, "foo", "bar", "foo", "bar", "bar", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": [1.0, np.nan, np.nan, np.nan, 1.0, 1.0, 1, 1.0], + "D": range(8), + } + ) + # single column + result = df.drop_duplicates("A") + expected = df.loc[[0, 2, 3]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("A", keep="last") + expected = df.loc[[1, 6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("A", keep=False) + expected = df.loc[[]] # empty df + tm.assert_frame_equal(result, expected) + assert len(result) == 0 + + # multi column + result = df.drop_duplicates(["A", "B"]) + expected = df.loc[[0, 2, 3, 6]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(["A", "B"], keep="last") + expected = df.loc[[1, 5, 6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(["A", "B"], keep=False) + expected = df.loc[[6]] + tm.assert_frame_equal(result, expected) + + # nan + df = pd.DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": [1.0, np.nan, np.nan, np.nan, 1.0, 1.0, 1, 1.0], + "D": range(8), + } + ) + # single column + result = df.drop_duplicates("C") + expected = df[:2] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("C", keep="last") + expected = df.loc[[3, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("C", keep=False) + expected = df.loc[[]] # empty df + tm.assert_frame_equal(result, expected) + assert len(result) == 0 + + # multi column + result = df.drop_duplicates(["C", "B"]) + expected = df.loc[[0, 1, 2, 4]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(["C", "B"], keep="last") + expected = df.loc[[1, 3, 6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates(["C", "B"], keep=False) + expected = df.loc[[1]] + tm.assert_frame_equal(result, expected) + + +def test_drop_duplicates_NA_for_take_all(): + # none + df = pd.DataFrame( + { + "A": [None, None, "foo", "bar", "foo", "baz", "bar", "qux"], + "C": [1.0, np.nan, np.nan, np.nan, 1.0, 2.0, 3, 1.0], + } + ) + + # single column + result = df.drop_duplicates("A") + expected = df.iloc[[0, 2, 3, 5, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("A", keep="last") + expected = df.iloc[[1, 4, 5, 6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("A", keep=False) + expected = df.iloc[[5, 7]] + tm.assert_frame_equal(result, expected) + + # nan + + # single column + result = df.drop_duplicates("C") + expected = df.iloc[[0, 1, 5, 6]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("C", keep="last") + expected = df.iloc[[3, 5, 6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates("C", keep=False) + expected = df.iloc[[5, 6]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.drop_duplicates") +def test_drop_duplicates_inplace(): + orig = pd.DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": [1, 1, 2, 2, 2, 2, 1, 2], + "D": range(8), + } + ) + # single column + df = orig.copy() + return_value = df.drop_duplicates("A", inplace=True) + expected = orig[:2] + result = df + tm.assert_frame_equal(result, expected) + assert return_value is None + + df = orig.copy() + return_value = df.drop_duplicates("A", keep="last", inplace=True) + expected = orig.loc[[6, 7]] + result = df + tm.assert_frame_equal(result, expected) + assert return_value is None + + df = orig.copy() + return_value = df.drop_duplicates("A", keep=False, inplace=True) + expected = orig.loc[[]] + result = df + tm.assert_frame_equal(result, expected) + assert len(df) == 0 + assert return_value is None + + # multi column + df = orig.copy() + return_value = df.drop_duplicates(["A", "B"], inplace=True) + expected = orig.loc[[0, 1, 2, 3]] + result = df + tm.assert_frame_equal(result, expected) + assert return_value is None + + df = orig.copy() + return_value = df.drop_duplicates(["A", "B"], keep="last", inplace=True) + expected = orig.loc[[0, 5, 6, 7]] + result = df + tm.assert_frame_equal(result, expected) + assert return_value is None + + df = orig.copy() + return_value = df.drop_duplicates(["A", "B"], keep=False, inplace=True) + expected = orig.loc[[0]] + result = df + tm.assert_frame_equal(result, expected) + assert return_value is None + + # consider everything + orig2 = orig.loc[:, ["A", "B", "C"]].copy() + + df2 = orig2.copy() + return_value = df2.drop_duplicates(inplace=True) + # in this case only + expected = orig2.drop_duplicates(["A", "B"]) + result = df2 + tm.assert_frame_equal(result, expected) + assert return_value is None + + df2 = orig2.copy() + return_value = df2.drop_duplicates(keep="last", inplace=True) + expected = orig2.drop_duplicates(["A", "B"], keep="last") + result = df2 + tm.assert_frame_equal(result, expected) + assert return_value is None + + df2 = orig2.copy() + return_value = df2.drop_duplicates(keep=False, inplace=True) + expected = orig2.drop_duplicates(["A", "B"], keep=False) + result = df2 + tm.assert_frame_equal(result, expected) + assert return_value is None + + +@pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.drop_duplicates") +@pytest.mark.parametrize("inplace", [True, False]) +@pytest.mark.parametrize( + "origin_dict, output_dict, ignore_index, output_index", + [ + ({"A": [2, 2, 3]}, {"A": [2, 3]}, True, range(2)), + ({"A": [2, 2, 3]}, {"A": [2, 3]}, False, range(0, 4, 2)), + ({"A": [2, 2, 3], "B": [2, 2, 4]}, {"A": [2, 3], "B": [2, 4]}, True, range(2)), + ( + {"A": [2, 2, 3], "B": [2, 2, 4]}, + {"A": [2, 3], "B": [2, 4]}, + False, + range(0, 4, 2), + ), + ], +) +def test_drop_duplicates_ignore_index( + inplace, origin_dict, output_dict, ignore_index, output_index +): + # GH 30114 + df = pd.DataFrame(origin_dict) + expected = pd.DataFrame(output_dict, index=output_index) + + if inplace: + result_df = df.copy() + result_df.drop_duplicates(ignore_index=ignore_index, inplace=inplace) + else: + result_df = df.drop_duplicates(ignore_index=ignore_index, inplace=inplace) + + tm.assert_frame_equal(result_df, expected) + tm.assert_frame_equal(df, pd.DataFrame(origin_dict)) + + +def test_drop_duplicates_null_in_object_column(nulls_fixture): + # https://github.com/pandas-dev/pandas/issues/32992 + df = pd.DataFrame([[1, nulls_fixture], [2, "a"]], dtype=object) + result = df.drop_duplicates() + tm.assert_frame_equal(result, df) + + +def test_drop_duplicates_series_vs_dataframe(keep): + # GH#14192 + df = pd.DataFrame( + { + "a": [1, 1, 1, "one", "one"], + "b": [2, 2, np.nan, np.nan, np.nan], + "c": [3, 3, np.nan, np.nan, "three"], + "d": [1, 2, 3, 4, 4], + "e": [ + datetime(2015, 1, 1), + datetime(2015, 1, 1), + datetime(2015, 2, 1), + pd.NaT, + pd.NaT, + ], + } + ) + for column in df.columns: + dropped_frame = df[[column]].drop_duplicates(keep=keep) + dropped_series = df[column].drop_duplicates(keep=keep) + tm.assert_frame_equal(dropped_frame, dropped_series.to_frame()) + + +@pytest.mark.parametrize("arg", [[1], 1, "True", [], 0]) +def test_drop_duplicates_non_boolean_ignore_index(arg): + # GH#38274 + df = pd.DataFrame({"a": [1, 2, 1, 3]}) + msg = '^For argument "ignore_index" expected type bool, received type .*.$' + with pytest.raises(ValueError, match=msg): + df.drop_duplicates(ignore_index=arg) + + +def test_drop_duplicates_set(): + # GH#59237 + df = pd.DataFrame( + { + "AAA": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": [1, 1, 2, 2, 2, 2, 1, 2], + "D": range(8), + } + ) + # single column + result = df.drop_duplicates({"AAA"}) + expected = df[:2] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates({"AAA"}, keep="last") + expected = df.loc[[6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates({"AAA"}, keep=False) + expected = df.loc[[]] + tm.assert_frame_equal(result, expected) + assert len(result) == 0 + + # multi column + expected = df.loc[[0, 1, 2, 3]] + result = df.drop_duplicates({"AAA", "B"}) + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates({"AAA", "B"}, keep="last") + expected = df.loc[[0, 5, 6, 7]] + tm.assert_frame_equal(result, expected) + + result = df.drop_duplicates({"AAA", "B"}, keep=False) + expected = df.loc[[0]] + tm.assert_frame_equal(result, expected) + + +def test_drop_duplicates_with_empty_missing(): + # https://github.com/pandas-dev/pandas/issues/62611 - specific bug with pyarrow + df = pd.DataFrame(data={"A": ["a", "b", "", "a", None, "b"]}) + df["B"] = "b" + result = df.drop_duplicates() + expected = pd.DataFrame( + data={"A": ["a", "b", "", None], "B": ["b", "b", "b", "b"]}, index=[0, 1, 2, 4] + ) + tm.assert_frame_equal(result, expected) + + +def test_drop_duplicates_inplace_depr(): + msg = "The inplace keyword in DataFrame.drop_duplicates is deprecated" + + df = pd.DataFrame({"A": [1, 2, 2, 3]}) + df_orig = df.copy() + expected = pd.DataFrame({"A": [1, 2, 3]}, index=[0, 1, 3]) + + # does not use keyword, no warning + with tm.assert_produces_warning(False): + result = df.drop_duplicates() + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to false, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.drop_duplicates(inplace=False) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to true, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.drop_duplicates(inplace=True) + tm.assert_frame_equal(df, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_droplevel.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_droplevel.py new file mode 100644 index 0000000000000000000000000000000000000000..a6fad22b113c6276a7583c30b89776f711bf1f50 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_droplevel.py @@ -0,0 +1,32 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDropLevel: + def test_droplevel(self, frame_or_series): + # GH#20342 + cols = pd.MultiIndex.from_tuples( + [("c", "e"), ("d", "f")], names=["level_1", "level_2"] + ) + mi = pd.MultiIndex.from_tuples([(1, 2), (5, 6), (9, 10)], names=["a", "b"]) + df = pd.DataFrame([[3, 4], [7, 8], [11, 12]], index=mi, columns=cols) + if frame_or_series is not pd.DataFrame: + df = df.iloc[:, 0] + + # test that dropping of a level in index works + expected = df.reset_index("a", drop=True) + result = df.droplevel("a", axis="index") + tm.assert_equal(result, expected) + + if frame_or_series is pd.DataFrame: + # test that dropping of a level in columns works + expected = df.copy() + expected.columns = pd.Index(["c", "d"], name="level_1") + result = df.droplevel("level_2", axis="columns") + tm.assert_equal(result, expected) + else: + # test that droplevel raises ValueError on axis != 0 + with pytest.raises(ValueError, match="No axis named columns"): + df.droplevel(1, axis="columns") diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_dropna.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_dropna.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc777df95cd42f49cc6611d81890d5c4b201990 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_dropna.py @@ -0,0 +1,319 @@ +import datetime + +import dateutil +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameMissingData: + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.dropna") + def test_dropEmptyRows(self, float_frame): + N = len(float_frame.index) + mat = np.random.default_rng(2).standard_normal(N) + mat[:5] = np.nan + + frame = pd.DataFrame({"foo": mat}, index=float_frame.index) + original = pd.Series(mat, index=float_frame.index, name="foo") + expected = original.dropna() + inplace_frame1, inplace_frame2 = frame.copy(), frame.copy() + + smaller_frame = frame.dropna(how="all") + # check that original was preserved + tm.assert_series_equal(frame["foo"], original) + return_value = inplace_frame1.dropna(how="all", inplace=True) + tm.assert_series_equal(smaller_frame["foo"], expected) + tm.assert_series_equal(inplace_frame1["foo"], expected) + assert return_value is None + + smaller_frame = frame.dropna(how="all", subset=["foo"]) + return_value = inplace_frame2.dropna(how="all", subset=["foo"], inplace=True) + tm.assert_series_equal(smaller_frame["foo"], expected) + tm.assert_series_equal(inplace_frame2["foo"], expected) + assert return_value is None + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.dropna") + def test_dropIncompleteRows(self, float_frame): + N = len(float_frame.index) + mat = np.random.default_rng(2).standard_normal(N) + mat[:5] = np.nan + + frame = pd.DataFrame({"foo": mat}, index=float_frame.index) + frame["bar"] = 5 + original = pd.Series(mat, index=float_frame.index, name="foo") + inp_frame1, inp_frame2 = frame.copy(), frame.copy() + + smaller_frame = frame.dropna() + tm.assert_series_equal(frame["foo"], original) + return_value = inp_frame1.dropna(inplace=True) + + exp = pd.Series(mat[5:], index=float_frame.index[5:], name="foo") + tm.assert_series_equal(smaller_frame["foo"], exp) + tm.assert_series_equal(inp_frame1["foo"], exp) + assert return_value is None + + samesize_frame = frame.dropna(subset=["bar"]) + tm.assert_series_equal(frame["foo"], original) + assert (frame["bar"] == 5).all() + return_value = inp_frame2.dropna(subset=["bar"], inplace=True) + tm.assert_index_equal(samesize_frame.index, float_frame.index) + tm.assert_index_equal(inp_frame2.index, float_frame.index) + assert return_value is None + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.dropna") + def test_dropna(self): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((6, 4))) + df.iloc[:2, 2] = np.nan + + dropped = df.dropna(axis=1) + expected = df.loc[:, [0, 1, 3]] + inp = df.copy() + return_value = inp.dropna(axis=1, inplace=True) + tm.assert_frame_equal(dropped, expected) + tm.assert_frame_equal(inp, expected) + assert return_value is None + + dropped = df.dropna(axis=0) + expected = df.loc[list(range(2, 6))] + inp = df.copy() + return_value = inp.dropna(axis=0, inplace=True) + tm.assert_frame_equal(dropped, expected) + tm.assert_frame_equal(inp, expected) + assert return_value is None + + # threshold + dropped = df.dropna(axis=1, thresh=5) + expected = df.loc[:, [0, 1, 3]] + inp = df.copy() + return_value = inp.dropna(axis=1, thresh=5, inplace=True) + tm.assert_frame_equal(dropped, expected) + tm.assert_frame_equal(inp, expected) + assert return_value is None + + dropped = df.dropna(axis=0, thresh=4) + expected = df.loc[range(2, 6)] + inp = df.copy() + return_value = inp.dropna(axis=0, thresh=4, inplace=True) + tm.assert_frame_equal(dropped, expected) + tm.assert_frame_equal(inp, expected) + assert return_value is None + + dropped = df.dropna(axis=1, thresh=4) + tm.assert_frame_equal(dropped, df) + + dropped = df.dropna(axis=1, thresh=3) + tm.assert_frame_equal(dropped, df) + + # subset + dropped = df.dropna(axis=0, subset=[0, 1, 3]) + inp = df.copy() + return_value = inp.dropna(axis=0, subset=[0, 1, 3], inplace=True) + tm.assert_frame_equal(dropped, df) + tm.assert_frame_equal(inp, df) + assert return_value is None + + # all + dropped = df.dropna(axis=1, how="all") + tm.assert_frame_equal(dropped, df) + + df[2] = np.nan + dropped = df.dropna(axis=1, how="all") + expected = df.loc[:, [0, 1, 3]] + tm.assert_frame_equal(dropped, expected) + + # bad input + msg = "No axis named 3 for object type DataFrame" + with pytest.raises(ValueError, match=msg): + df.dropna(axis=3) + + @pytest.mark.filterwarnings( + "ignore:The inplace keyword in (Series|DataFrame).dropna" + ) + @pytest.mark.filterwarnings( + "ignore:The inplace keyword in (Series|DataFrame).drop is" + ) + def test_drop_and_dropna_caching(self): + # tst that cacher updates + original = pd.Series([1, 2, np.nan], name="A") + expected = pd.Series([1, 2], dtype=original.dtype, name="A") + df = pd.DataFrame({"A": original.values.copy()}) + df2 = df.copy() + df["A"].dropna() + tm.assert_series_equal(df["A"], original) + + ser = df["A"] + return_value = ser.dropna(inplace=True) + tm.assert_series_equal(ser, expected) + tm.assert_series_equal(df["A"], original) + assert return_value is None + + df2["A"].drop([1]) + tm.assert_series_equal(df2["A"], original) + + ser = df2["A"] + return_value = ser.drop([1], inplace=True) + tm.assert_series_equal(ser, original.drop([1])) + tm.assert_series_equal(df2["A"], original) + assert return_value is None + + def test_dropna_corner(self, float_frame): + # bad input + msg = "invalid how option: foo" + with pytest.raises(ValueError, match=msg): + float_frame.dropna(how="foo") + # non-existent column - 8303 + with pytest.raises(KeyError, match=r"^\['X'\]$"): + float_frame.dropna(subset=["A", "X"]) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.dropna") + def test_dropna_multiple_axes(self): + df = pd.DataFrame( + [ + [1, np.nan, 2, 3], + [4, np.nan, 5, 6], + [np.nan, np.nan, np.nan, np.nan], + [7, np.nan, 8, 9], + ] + ) + + # GH20987 + with pytest.raises(TypeError, match="supplying multiple axes"): + df.dropna(how="all", axis=[0, 1]) + with pytest.raises(TypeError, match="supplying multiple axes"): + df.dropna(how="all", axis=(0, 1)) + + inp = df.copy() + with pytest.raises(TypeError, match="supplying multiple axes"): + inp.dropna(how="all", axis=(0, 1), inplace=True) + + def test_dropna_tz_aware_datetime(self): + # GH13407 + df = pd.DataFrame() + dt1 = datetime.datetime(2015, 1, 1, tzinfo=dateutil.tz.tzutc()) + dt2 = datetime.datetime(2015, 2, 2, tzinfo=dateutil.tz.tzutc()) + df["Time"] = [dt1] + result = df.dropna(axis=0) + expected = pd.DataFrame({"Time": [dt1]}) + tm.assert_frame_equal(result, expected) + + # Ex2 + df = pd.DataFrame({"Time": [dt1, None, np.nan, dt2]}) + result = df.dropna(axis=0) + expected = pd.DataFrame([dt1, dt2], columns=["Time"], index=range(0, 6, 3)) + tm.assert_frame_equal(result, expected) + + def test_dropna_categorical_interval_index(self): + # GH 25087 + ii = pd.IntervalIndex.from_breaks([0, 2.78, 3.14, 6.28]) + ci = pd.CategoricalIndex(ii) + df = pd.DataFrame({"A": list("abc")}, index=ci) + + expected = df + result = df.dropna() + tm.assert_frame_equal(result, expected) + + def test_dropna_with_duplicate_columns(self): + df = pd.DataFrame( + { + "A": np.random.default_rng(2).standard_normal(5), + "B": np.random.default_rng(2).standard_normal(5), + "C": np.random.default_rng(2).standard_normal(5), + "D": ["a", "b", "c", "d", "e"], + } + ) + df.iloc[2, [0, 1, 2]] = np.nan + df.iloc[0, 0] = np.nan + df.iloc[1, 1] = np.nan + df.iloc[:, 3] = np.nan + expected = df.dropna(subset=["A", "B", "C"], how="all") + expected.columns = ["A", "A", "B", "C"] + + df.columns = ["A", "A", "B", "C"] + + result = df.dropna(subset=["A", "C"], how="all") + tm.assert_frame_equal(result, expected) + + def test_set_single_column_subset(self): + # GH 41021 + df = pd.DataFrame({"A": [1, 2, 3], "B": list("abc"), "C": [4, np.nan, 5]}) + expected = pd.DataFrame( + {"A": [1, 3], "B": list("ac"), "C": [4.0, 5.0]}, index=range(0, 4, 2) + ) + result = df.dropna(subset="C") + tm.assert_frame_equal(result, expected) + + def test_single_column_not_present_in_axis(self): + # GH 41021 + df = pd.DataFrame({"A": [1, 2, 3]}) + + # Column not present + with pytest.raises(KeyError, match="['D']"): + df.dropna(subset="D", axis=0) + + def test_subset_is_nparray(self): + # GH 41021 + df = pd.DataFrame({"A": [1, 2, np.nan], "B": list("abc"), "C": [4, np.nan, 5]}) + expected = pd.DataFrame({"A": [1.0], "B": ["a"], "C": [4.0]}) + result = df.dropna(subset=np.array(["A", "C"])) + tm.assert_frame_equal(result, expected) + + def test_no_nans_in_frame(self, axis): + # GH#41965 + df = pd.DataFrame([[1, 2], [3, 4]], columns=pd.RangeIndex(0, 2)) + expected = df.copy() + result = df.dropna(axis=axis) + tm.assert_frame_equal(result, expected, check_index_type=True) + + def test_how_thresh_param_incompatible(self): + # GH46575 + df = pd.DataFrame([1, 2, pd.NA]) + msg = "You cannot set both the how and thresh arguments at the same time" + with pytest.raises(TypeError, match=msg): + df.dropna(how="all", thresh=2) + + with pytest.raises(TypeError, match=msg): + df.dropna(how="any", thresh=2) + + with pytest.raises(TypeError, match=msg): + df.dropna(how=None, thresh=None) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.dropna") + @pytest.mark.parametrize("val", [1, 1.5]) + def test_dropna_ignore_index(self, val): + # GH#31725 + df = pd.DataFrame({"a": [1, 2, val]}, index=[3, 2, 1]) + result = df.dropna(ignore_index=True) + expected = pd.DataFrame({"a": [1, 2, val]}) + tm.assert_frame_equal(result, expected) + + df.dropna(ignore_index=True, inplace=True) + tm.assert_frame_equal(df, expected) + + +def test_dropna_inplace_depr(): + msg = "The inplace keyword in DataFrame.dropna is deprecated" + + df = pd.DataFrame({"a": [1.0, 1.5, np.nan, 2.0]}) + df_orig = df.copy() + expected = pd.DataFrame({"a": [1.0, 1.5, 2.0]}, index=[0, 1, 3]) + + # does not use keyword, no warning + with tm.assert_produces_warning(False): + result = df.dropna() + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to false, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.dropna(inplace=False) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to true, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.dropna(inplace=True) + tm.assert_frame_equal(df, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_dtypes.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..0eee1fa0aef59e35ac1b82dea01a70e97f4851f8 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_dtypes.py @@ -0,0 +1,138 @@ +from datetime import timedelta + +import numpy as np +import pytest + +from pandas.core.dtypes.dtypes import DatetimeTZDtype + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameDataTypes: + def test_empty_frame_dtypes(self): + empty_df = pd.DataFrame() + tm.assert_series_equal(empty_df.dtypes, pd.Series(dtype=object)) + + nocols_df = pd.DataFrame(index=[1, 2, 3]) + tm.assert_series_equal(nocols_df.dtypes, pd.Series(dtype=object)) + + norows_df = pd.DataFrame(columns=list("abc")) + tm.assert_series_equal(norows_df.dtypes, pd.Series(object, index=list("abc"))) + + norows_int_df = pd.DataFrame(columns=list("abc")).astype(np.int32) + tm.assert_series_equal( + norows_int_df.dtypes, pd.Series(np.dtype("int32"), index=list("abc")) + ) + + df = pd.DataFrame({"a": 1, "b": True, "c": 1.0}, index=[1, 2, 3]) + ex_dtypes = pd.Series({"a": np.int64, "b": np.bool_, "c": np.float64}) + tm.assert_series_equal(df.dtypes, ex_dtypes) + + # same but for empty slice of df + tm.assert_series_equal(df[:0].dtypes, ex_dtypes) + + def test_datetime_with_tz_dtypes(self): + tzframe = pd.DataFrame( + { + "A": pd.date_range("20130101", periods=3, unit="ns"), + "B": pd.date_range("20130101", periods=3, tz="US/Eastern", unit="ns"), + "C": pd.date_range("20130101", periods=3, tz="CET", unit="ns"), + } + ) + tzframe.iloc[1, 1] = pd.NaT + tzframe.iloc[1, 2] = pd.NaT + result = tzframe.dtypes.sort_index() + expected = pd.Series( + [ + np.dtype("datetime64[ns]"), + DatetimeTZDtype("ns", "US/Eastern"), + DatetimeTZDtype("ns", "CET"), + ], + ["A", "B", "C"], + ) + + tm.assert_series_equal(result, expected) + + def test_dtypes_are_correct_after_column_slice(self): + # GH6525 + df = pd.DataFrame(index=range(5), columns=list("abc"), dtype=np.float64) + tm.assert_series_equal( + df.dtypes, + pd.Series({"a": np.float64, "b": np.float64, "c": np.float64}), + ) + tm.assert_series_equal(df.iloc[:, 2:].dtypes, pd.Series({"c": np.float64})) + tm.assert_series_equal( + df.dtypes, + pd.Series({"a": np.float64, "b": np.float64, "c": np.float64}), + ) + + @pytest.mark.parametrize( + "data", + [pd.NA, True], + ) + def test_dtypes_are_correct_after_groupby_last(self, data): + # GH46409 + df = pd.DataFrame( + {"id": [1, 2, 3, 4], "test": [True, pd.NA, data, False]} + ).convert_dtypes() + result = df.groupby("id").last().test + expected = df.set_index("id").test + assert result.dtype == pd.BooleanDtype() + tm.assert_series_equal(expected, result) + + def test_dtypes_gh8722(self, float_string_frame): + float_string_frame["bool"] = float_string_frame["A"] > 0 + result = float_string_frame.dtypes + expected = pd.Series( + {k: v.dtype for k, v in float_string_frame.items()}, index=result.index + ) + tm.assert_series_equal(result, expected) + + def test_dtypes_timedeltas(self): + df = pd.DataFrame( + { + "A": pd.Series( + pd.date_range("2012-1-1", periods=3, freq="D", unit="ns") + ), + "B": pd.Series([timedelta(days=i) for i in range(3)]), + } + ) + result = df.dtypes + expected = pd.Series( + [np.dtype("datetime64[ns]"), np.dtype("timedelta64[us]")], index=list("AB") + ) + tm.assert_series_equal(result, expected) + + df["C"] = df["A"] + df["B"] + result = df.dtypes + expected = pd.Series( + [ + np.dtype("datetime64[ns]"), + np.dtype("timedelta64[us]"), + np.dtype("datetime64[ns]"), + ], + index=list("ABC"), + ) + tm.assert_series_equal(result, expected) + + # mixed int types + df["D"] = 1 + result = df.dtypes + expected = pd.Series( + [ + np.dtype("datetime64[ns]"), + np.dtype("timedelta64[us]"), + np.dtype("datetime64[ns]"), + np.dtype("int64"), + ], + index=list("ABCD"), + ) + tm.assert_series_equal(result, expected) + + def test_frame_apply_np_array_return_type(self, using_infer_string): + # GH 35517 + df = pd.DataFrame([["foo"]]) + result = df.apply(lambda col: np.array("bar")) + expected = pd.Series(np.array("bar")) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_duplicated.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_duplicated.py new file mode 100644 index 0000000000000000000000000000000000000000..cf4f882ed3c2559ae8ccfb7214fb1453065ba0a7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_duplicated.py @@ -0,0 +1,145 @@ +import re +import sys + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize("subset", ["a", ["a"], ["a", "B"]]) +def test_duplicated_with_misspelled_column_name(subset): + # GH 19730 + df = pd.DataFrame({"A": [0, 0, 1], "B": [0, 0, 1], "C": [0, 0, 1]}) + msg = re.escape("Index(['a'], dtype=") + + with pytest.raises(KeyError, match=msg): + df.duplicated(subset) + + +def test_duplicated_implemented_no_recursion(): + # gh-21524 + # Ensure duplicated isn't implemented using recursion that + # can fail on wide frames + df = pd.DataFrame(np.random.default_rng(2).integers(0, 1000, (10, 1000))) + rec_limit = sys.getrecursionlimit() + try: + sys.setrecursionlimit(100) + result = df.duplicated() + finally: + sys.setrecursionlimit(rec_limit) + + # Then duplicates produce the bool Series as a result and don't fail during + # calculation. Actual values doesn't matter here, though usually it's all + # False in this case + assert isinstance(result, pd.Series) + assert result.dtype == np.bool_ + + +@pytest.mark.parametrize( + "keep, expected", + [ + ("first", pd.Series([False, False, True, False, True])), + ("last", pd.Series([True, True, False, False, False])), + (False, pd.Series([True, True, True, False, True])), + ], +) +def test_duplicated_keep(keep, expected): + df = pd.DataFrame({"A": [0, 1, 1, 2, 0], "B": ["a", "b", "b", "c", "a"]}) + + result = df.duplicated(keep=keep) + tm.assert_series_equal(result, expected) + + +@pytest.mark.xfail(reason="GH#21720; nan/None falsely considered equal") +@pytest.mark.parametrize( + "keep, expected", + [ + ("first", pd.Series([False, False, True, False, True])), + ("last", pd.Series([True, True, False, False, False])), + (False, pd.Series([True, True, True, False, True])), + ], +) +def test_duplicated_nan_none(keep, expected): + df = pd.DataFrame({"C": [np.nan, 3, 3, None, np.nan], "x": 1}, dtype=object) + + result = df.duplicated(keep=keep) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("subset", [None, ["A", "B"], "A"]) +def test_duplicated_subset(subset, keep): + df = pd.DataFrame( + { + "A": [0, 1, 1, 2, 0], + "B": ["a", "b", "b", "c", "a"], + "C": [np.nan, 3, 3, None, np.nan], + } + ) + + if subset is None: + subset = list(df.columns) + elif isinstance(subset, str): + # need to have a DataFrame, not a Series + # -> select columns with singleton list, not string + subset = [subset] + + expected = df[subset].duplicated(keep=keep) + result = df.duplicated(keep=keep, subset=subset) + tm.assert_series_equal(result, expected) + + +def test_duplicated_on_empty_frame(): + # GH 25184 + + df = pd.DataFrame(columns=["a", "b"]) + dupes = df.duplicated("a") + + result = df[dupes] + expected = df.copy() + tm.assert_frame_equal(result, expected) + + +def test_duplicated_on_empty_frame_with_index(): + # GH#61191 + df = pd.DataFrame(index=[0, 1]) + result = df.duplicated() + expected = pd.Series(False, dtype=bool, index=df.index) + tm.assert_series_equal(result, expected) + + # Boolean indexing with the result should work + result = df[df.duplicated()] + expected = df.iloc[:0] + tm.assert_frame_equal(result, expected) + + +def test_frame_datetime64_duplicated(): + dates = pd.date_range("2010-07-01", end="2010-08-05") + + tst = pd.DataFrame({"symbol": "AAA", "date": dates}) + result = tst.duplicated(["date", "symbol"]) + assert (-result).all() + + tst = pd.DataFrame({"date": dates}) + result = tst.date.duplicated() + assert (-result).all() + + +@pytest.mark.parametrize( + "values", + [ + pd.to_datetime(["2020-01-01", "2020-01-01", None]).tz_localize("UTC"), + pd.PeriodIndex(["2020-01-01", "2020-01-01", None], freq="D"), + pd.arrays.IntervalArray.from_tuples([(0.0, 1.0), (0.0, 1.0), None]), + ], +) +def test_duplicated_no_values_deprecation(values): + # GH#69025 the multi-column path must not self-trigger the .values deprecation + df = pd.DataFrame({"a": values, "b": [1, 1, 1]}) + with tm.assert_produces_warning(None): + result = df.duplicated() + dropped = df.drop_duplicates() + + tm.assert_series_equal(result, pd.Series([False, True, False])) + tm.assert_frame_equal(dropped, df.iloc[[0, 2]]) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_equals.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_equals.py new file mode 100644 index 0000000000000000000000000000000000000000..a581589094e22754d64401eb72b575beee4558cd --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_equals.py @@ -0,0 +1,109 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestEquals: + def test_dataframe_not_equal(self): + # see GH#28839 + df1 = pd.DataFrame({"a": [1, 2], "b": ["s", "d"]}) + df2 = pd.DataFrame({"a": ["s", "d"], "b": [1, 2]}) + assert df1.equals(df2) is False + + def test_equals_object_array_vs_scalar(self): + # GH#43867 one object-dtype element is a numpy array, the other a + # scalar; these must not compare equal + df = pd.DataFrame({"x": ["a"]}, dtype=object) + other = df.copy() + other["x"] = [np.array(["a"], dtype=object)] + assert df["x"].dtype == other["x"].dtype == object + assert not df.equals(other) + assert not other.equals(df) + + def test_equals_different_blocks(self): + # GH#9330 + df0 = pd.DataFrame( + {"A": [1.0, 2.0], "B": np.array([1, 2], dtype=np.int64), "C": [3.0, 4.0]} + ) + # build df1 via sequential __setitem__ so the float columns end up + # in separate blocks instead of being consolidated upfront + df1 = pd.DataFrame({"A": [1.0, 2.0]}) + df1["B"] = np.array([1, 2], dtype=np.int64) + df1["C"] = np.array([3.0, 4.0]) + assert len(df0._mgr.blocks) == 2 + assert len(df1._mgr.blocks) == 3 + + # do the real tests + tm.assert_frame_equal(df0, df1) + assert df0.equals(df1) + assert df1.equals(df0) + + def test_equals(self): + # Add object dtype column with nans + index = np.random.default_rng(2).random(10) + df1 = pd.DataFrame( + np.random.default_rng(2).random(10), index=index, columns=["floats"] + ) + df1["text"] = "the sky is so blue. we could use more chocolate.".split() + df1["start"] = pd.date_range("2000-1-1", periods=10, freq="min") + df1["end"] = pd.date_range("2000-1-1", periods=10, freq="D") + df1["diff"] = df1["end"] - df1["start"] + # Explicitly cast to object, to avoid implicit cast when setting np.nan + df1["bool"] = (np.arange(10) % 3 == 0).astype(object) + df1.loc[::2] = np.nan + df2 = df1.copy() + assert df1["text"].equals(df2["text"]) + assert df1["start"].equals(df2["start"]) + assert df1["end"].equals(df2["end"]) + assert df1["diff"].equals(df2["diff"]) + assert df1["bool"].equals(df2["bool"]) + assert df1.equals(df2) + assert not df1.equals(object) + + # different dtype + different = df1.copy() + different["floats"] = different["floats"].astype("float32") + assert not df1.equals(different) + + # different index + different_index = -index + different = df2.set_index(different_index) + assert not df1.equals(different) + + # different columns + different = df2.copy() + different.columns = df2.columns[::-1] + assert not df1.equals(different) + + # DatetimeIndex + index = pd.date_range("2000-1-1", periods=10, freq="min") + df1 = df1.set_index(index) + df2 = df1.copy() + assert df1.equals(df2) + + # MultiIndex + df3 = df1.set_index(["text"], append=True) + df2 = df1.set_index(["text"], append=True) + assert df3.equals(df2) + + df2 = df1.set_index(["floats"], append=True) + assert not df3.equals(df2) + + # NaN in index + df3 = df1.set_index(["floats"], append=True) + df2 = df1.set_index(["floats"], append=True) + assert df3.equals(df2) + + def test_equals_categorical_categories_order(self): + cat1 = pd.Categorical(["a", "b", "a"], categories=["a", "b"]) + cat2 = pd.Categorical(["a", "b", "a"], categories=["b", "a"]) + df1 = pd.DataFrame({"c": cat1}) + df2 = pd.DataFrame({"c": cat2}) + + assert df1.equals(df2) + + cat3 = pd.Categorical(["a", "b", "a"], categories=["a", "b", "c"]) + df3 = pd.DataFrame({"c": cat3}) + + assert not df1.equals(df3) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_explode.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_explode.py new file mode 100644 index 0000000000000000000000000000000000000000..cfb85d261d07a31df969c11ad0bc16f3cae37575 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_explode.py @@ -0,0 +1,307 @@ +import re + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_error(): + df = pd.DataFrame( + {"A": pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list("abcd")), "B": 1} + ) + with pytest.raises( + ValueError, match="column must be a scalar, tuple, or list thereof" + ): + df.explode([list("AA")]) + + with pytest.raises(ValueError, match="column must be unique"): + df.explode(list("AA")) + + df.columns = list("AA") + with pytest.raises( + ValueError, + match=re.escape("DataFrame columns must be unique. Duplicate columns: ['A']"), + ): + df.explode("A") + + +@pytest.mark.parametrize( + "input_subset, error_message", + [ + ( + list("AC"), + "columns must have matching element counts", + ), + ( + [], + "column must be nonempty", + ), + ], +) +def test_error_multi_columns(input_subset, error_message): + # GH 39240 + df = pd.DataFrame( + { + "A": [[0, 1, 2], np.nan, [], (3, 4)], + "B": 1, + "C": [["a", "b", "c"], "foo", [], ["d", "e", "f"]], + }, + index=list("abcd"), + ) + with pytest.raises(ValueError, match=error_message): + df.explode(input_subset) + + +@pytest.mark.parametrize( + "scalar", + ["a", 0, 1.5, pd.Timedelta("1 days"), pd.Timestamp("2019-12-31")], +) +def test_basic(scalar): + df = pd.DataFrame( + {scalar: pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list("abcd")), "B": 1} + ) + result = df.explode(scalar) + expected = pd.DataFrame( + { + scalar: pd.Series( + [0, 1, 2, np.nan, np.nan, 3, 4], index=list("aaabcdd"), dtype=object + ), + "B": 1, + } + ) + tm.assert_frame_equal(result, expected) + + +def test_multi_index_rows(): + df = pd.DataFrame( + {"A": np.array([[0, 1, 2], np.nan, [], (3, 4)], dtype=object), "B": 1}, + index=pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), ("b", 2)]), + ) + + result = df.explode("A") + expected = pd.DataFrame( + { + "A": pd.Series( + [0, 1, 2, np.nan, np.nan, 3, 4], + index=pd.MultiIndex.from_tuples( + [ + ("a", 1), + ("a", 1), + ("a", 1), + ("a", 2), + ("b", 1), + ("b", 2), + ("b", 2), + ] + ), + dtype=object, + ), + "B": 1, + } + ) + tm.assert_frame_equal(result, expected) + + +def test_multi_index_columns(): + df = pd.DataFrame( + {("A", 1): np.array([[0, 1, 2], np.nan, [], (3, 4)], dtype=object), ("A", 2): 1} + ) + + result = df.explode(("A", 1)) + expected = pd.DataFrame( + { + ("A", 1): pd.Series( + [0, 1, 2, np.nan, np.nan, 3, 4], + index=pd.Index([0, 0, 0, 1, 2, 3, 3]), + dtype=object, + ), + ("A", 2): 1, + } + ) + tm.assert_frame_equal(result, expected) + + +def test_usecase(): + # explode a single column + # gh-10511 + df = pd.DataFrame( + [[11, range(5), 10], [22, range(3), 20]], columns=list("ABC") + ).set_index("C") + result = df.explode("B") + + expected = pd.DataFrame( + { + "A": [11, 11, 11, 11, 11, 22, 22, 22], + "B": np.array([0, 1, 2, 3, 4, 0, 1, 2], dtype=object), + "C": [10, 10, 10, 10, 10, 20, 20, 20], + }, + columns=list("ABC"), + ).set_index("C") + + tm.assert_frame_equal(result, expected) + + # gh-8517 + df = pd.DataFrame( + [["2014-01-01", "Alice", "A B"], ["2014-01-02", "Bob", "C D"]], + columns=["dt", "name", "text"], + ) + result = df.assign(text=df.text.str.split(" ")).explode("text") + expected = pd.DataFrame( + [ + ["2014-01-01", "Alice", "A"], + ["2014-01-01", "Alice", "B"], + ["2014-01-02", "Bob", "C"], + ["2014-01-02", "Bob", "D"], + ], + columns=["dt", "name", "text"], + index=[0, 0, 1, 1], + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "input_dict, input_index, expected_dict, expected_index", + [ + ( + {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]}, + [0, 0], + {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]}, + [0, 0, 0, 0], + ), + ( + {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]}, + pd.Index([0, 0], name="my_index"), + {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]}, + pd.Index([0, 0, 0, 0], name="my_index"), + ), + ( + {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]}, + pd.MultiIndex.from_arrays( + [[0, 0], [1, 1]], names=["my_first_index", "my_second_index"] + ), + {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]}, + pd.MultiIndex.from_arrays( + [[0, 0, 0, 0], [1, 1, 1, 1]], + names=["my_first_index", "my_second_index"], + ), + ), + ( + {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]}, + pd.MultiIndex.from_arrays([[0, 0], [1, 1]], names=["my_index", None]), + {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]}, + pd.MultiIndex.from_arrays( + [[0, 0, 0, 0], [1, 1, 1, 1]], names=["my_index", None] + ), + ), + ], +) +def test_duplicate_index(input_dict, input_index, expected_dict, expected_index): + # GH 28005 + df = pd.DataFrame(input_dict, index=input_index, dtype=object) + result = df.explode("col1") + expected = pd.DataFrame(expected_dict, index=expected_index, dtype=object) + tm.assert_frame_equal(result, expected) + + +def test_ignore_index(): + # GH 34932 + df = pd.DataFrame({"id": range(0, 20, 10), "values": [list("ab"), list("cd")]}) + result = df.explode("values", ignore_index=True) + expected = pd.DataFrame( + {"id": [0, 0, 10, 10], "values": list("abcd")}, index=range(4) + ) + tm.assert_frame_equal(result, expected) + + +def test_explode_sets(): + # https://github.com/pandas-dev/pandas/issues/35614 + df = pd.DataFrame({"a": [{"x", "y"}], "b": [1]}, index=[1]) + result = df.explode(column="a").sort_values(by="a") + expected = pd.DataFrame({"a": ["x", "y"], "b": [1, 1]}, index=[1, 1]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "input_subset, expected_dict, expected_index", + [ + ( + list("AC"), + { + "A": pd.Series( + [0, 1, 2, np.nan, np.nan, 3, 4, np.nan], + index=list("aaabcdde"), + dtype=object, + ), + "B": 1, + "C": ["a", "b", "c", "foo", np.nan, "d", "e", np.nan], + }, + list("aaabcdde"), + ), + ( + list("A"), + { + "A": pd.Series( + [0, 1, 2, np.nan, np.nan, 3, 4, np.nan], + index=list("aaabcdde"), + dtype=object, + ), + "B": 1, + "C": [ + ["a", "b", "c"], + ["a", "b", "c"], + ["a", "b", "c"], + "foo", + [], + ["d", "e"], + ["d", "e"], + np.nan, + ], + }, + list("aaabcdde"), + ), + ], +) +def test_multi_columns(input_subset, expected_dict, expected_index): + # GH 39240 + df = pd.DataFrame( + { + "A": [[0, 1, 2], np.nan, [], (3, 4), np.nan], + "B": 1, + "C": [["a", "b", "c"], "foo", [], ["d", "e"], np.nan], + }, + index=list("abcde"), + ) + result = df.explode(input_subset) + expected = pd.DataFrame(expected_dict, expected_index) + tm.assert_frame_equal(result, expected) + + +def test_multi_columns_nan_empty(): + # GH 46084 + df = pd.DataFrame( + { + "A": [[0, 1], [5], [], [2, 3]], + "B": [9, 8, 7, 6], + "C": [[1, 2], np.nan, [], [3, 4]], + } + ) + result = df.explode(["A", "C"]) + expected = pd.DataFrame( + { + "A": np.array([0, 1, 5, np.nan, 2, 3], dtype=object), + "B": [9, 9, 8, 7, 6, 6], + "C": np.array([1, 2, np.nan, np.nan, 3, 4], dtype=object), + }, + index=[0, 0, 1, 2, 3, 3], + ) + tm.assert_frame_equal(result, expected) + + +def test_str_dtype(): + # https://github.com/pandas-dev/pandas/pull/61623 + df = pd.DataFrame({"a": ["x", "y"]}, dtype="str") + result = df.explode(column="a") + assert result is not df + tm.assert_frame_equal(result, df) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_fillna.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_fillna.py new file mode 100644 index 0000000000000000000000000000000000000000..d70da8ea447eccda73cf174ccb687adc7ba8f8c8 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_fillna.py @@ -0,0 +1,935 @@ +import numpy as np +import pytest + +from pandas.errors import ( + InvalidIndexError, + OutOfBoundsDatetime, + Pandas4Warning, +) + +import pandas as pd +import pandas._testing as tm +from pandas.tests.frame.common import _check_mixed_float + + +class TestFillNA: + def test_fillna_dict_inplace_nonunique_columns(self): + # GH#38966 + df = pd.DataFrame( + { + "A": [np.nan] * 3, + "B": [pd.NaT, pd.Timestamp(1), pd.NaT], + "C": [np.nan, "foo", 2], + } + ) + df.columns = ["A", "A", "A"] + orig = df[:] + + # GH#45153 filling datetime with int is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + df.fillna({"A": 2}, inplace=True) + # The first and third columns can be set inplace, while the second cannot. + + expected = pd.DataFrame( + {"A": [2.0] * 3, "B": [2, pd.Timestamp(1), 2], "C": [2, "foo", 2]} + ) + expected.columns = ["A", "A", "A"] + tm.assert_frame_equal(df, expected) + assert not tm.shares_memory(df.iloc[:, 1], orig.iloc[:, 1]) + + def test_fillna_on_column_view(self): + # GH#46149 avoid unnecessary copies + arr = np.full((40, 50), np.nan) + df = pd.DataFrame(arr, copy=False) + + with tm.raises_chained_assignment_error(): + df[0].fillna(-1, inplace=True) + assert np.isnan(arr[:, 0]).all() + + # i.e. we didn't create a new 49-column block + assert len(df._mgr.blocks) == 1 + assert np.shares_memory(df.values, arr) + + def test_fillna_datetime(self, datetime_frame): + tf = datetime_frame + tf.loc[tf.index[:5], "A"] = np.nan + tf.loc[tf.index[-5:], "A"] = np.nan + + zero_filled = datetime_frame.fillna(0) + assert (zero_filled.loc[zero_filled.index[:5], "A"] == 0).all() + + padded = datetime_frame.ffill() + assert np.isnan(padded.loc[padded.index[:5], "A"]).all() + + msg = r"missing 1 required positional argument: 'value'" + with pytest.raises(TypeError, match=msg): + datetime_frame.fillna() + + def test_fillna_mixed_type(self, float_string_frame, using_infer_string): + mf = float_string_frame + mf.loc[mf.index[5:20], "foo"] = np.nan + mf.loc[mf.index[-10:], "A"] = np.nan + + result = mf.ffill() + assert ( + result.loc[result.index[-10:], "A"] == result.loc[result.index[-11], "A"] + ).all() + assert (result.loc[result.index[5:20], "foo"] == "bar").all() + + # GH#45153 filling string column with int is deprecated + warn = Pandas4Warning if using_infer_string else None + with tm.assert_produces_warning(warn, match="fill value"): + result = mf.fillna(value=0) + assert (result.loc[result.index[-10:], "A"] == 0).all() + assert (result.loc[result.index[5:20], "foo"] == 0).all() + + def test_fillna_mixed_float(self, mixed_float_frame): + # mixed numeric (but no float16) + mf = mixed_float_frame.reindex(columns=["A", "B", "D"]) + mf.loc[mf.index[-10:], "A"] = np.nan + result = mf.fillna(value=0) + _check_mixed_float(result, dtype={"C": None}) + result = mf.ffill() + _check_mixed_float(result, dtype={"C": None}) + + def test_fillna_different_dtype(self): + # with different dtype (GH#3386) + df = pd.DataFrame( + [["a", "a", np.nan, "a"], ["b", "b", np.nan, "b"], ["c", "c", np.nan, "c"]] + ) + + # GH#45153 filling float with string is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = df.fillna({2: "foo"}) + expected = pd.DataFrame( + [["a", "a", "foo", "a"], ["b", "b", "foo", "b"], ["c", "c", "foo", "c"]] + ) + # column is originally float (all-NaN) -> filling with string gives object dtype + expected[2] = expected[2].astype("object") + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = df.fillna({2: "foo"}, inplace=True) + assert result is df + tm.assert_frame_equal(df, expected) + + def test_fillna_limit_and_value(self): + # limit and value + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 3))) + df.iloc[2:7, 0] = np.nan + df.iloc[3:5, 2] = np.nan + + expected = df.copy() + expected.iloc[2, 0] = 999 + expected.iloc[3, 2] = 999 + result = df.fillna(999, limit=1) + tm.assert_frame_equal(result, expected) + + def test_fillna_datelike(self): + # with datelike + # GH#6344 + df = pd.DataFrame( + { + "Date": [pd.NaT, pd.Timestamp("2014-1-1")], + "Date2": [pd.Timestamp("2013-1-1"), pd.NaT], + } + ) + + expected = df.copy() + expected["Date"] = expected["Date"].fillna(df.loc[df.index[0], "Date2"]) + result = df.fillna(value={"Date": df["Date2"]}) + tm.assert_frame_equal(result, expected) + + def test_fillna_tzaware(self): + # with timezone + # GH#15855 + df = pd.DataFrame({"A": [pd.Timestamp("2012-11-11 00:00:00+01:00"), pd.NaT]}) + exp = pd.DataFrame( + { + "A": [ + pd.Timestamp("2012-11-11 00:00:00+01:00"), + pd.Timestamp("2012-11-11 00:00:00+01:00"), + ] + } + ) + res = df.ffill() + tm.assert_frame_equal(res, exp) + + df = pd.DataFrame({"A": [pd.NaT, pd.Timestamp("2012-11-11 00:00:00+01:00")]}) + exp = pd.DataFrame( + { + "A": [ + pd.Timestamp("2012-11-11 00:00:00+01:00"), + pd.Timestamp("2012-11-11 00:00:00+01:00"), + ] + } + ) + res = df.bfill() + tm.assert_frame_equal(res, exp) + + def test_fillna_tzaware_different_column(self): + # with timezone in another column + # GH#15522 + df = pd.DataFrame( + { + "A": pd.date_range("20130101", periods=4, tz="US/Eastern"), + "B": [1, 2, np.nan, np.nan], + } + ) + result = df.ffill() + expected = pd.DataFrame( + { + "A": pd.date_range("20130101", periods=4, tz="US/Eastern"), + "B": [1.0, 2.0, 2.0, 2.0], + } + ) + tm.assert_frame_equal(result, expected) + + def test_na_actions_categorical(self): + cat = pd.Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) + vals = ["a", "b", np.nan, "d"] + df = pd.DataFrame({"cats": cat, "vals": vals}) + cat2 = pd.Categorical([1, 2, 3, 3], categories=[1, 2, 3]) + vals2 = ["a", "b", "b", "d"] + df_exp_fill = pd.DataFrame({"cats": cat2, "vals": vals2}) + cat3 = pd.Categorical([1, 2, 3], categories=[1, 2, 3]) + vals3 = ["a", "b", np.nan] + df_exp_drop_cats = pd.DataFrame({"cats": cat3, "vals": vals3}) + cat4 = pd.Categorical([1, 2], categories=[1, 2, 3]) + vals4 = ["a", "b"] + df_exp_drop_all = pd.DataFrame({"cats": cat4, "vals": vals4}) + + # fillna + res = df.fillna(value={"cats": 3, "vals": "b"}) + tm.assert_frame_equal(res, df_exp_fill) + + msg = "Cannot setitem on a Categorical with a new category" + with pytest.raises(TypeError, match=msg): + df.fillna(value={"cats": 4, "vals": "c"}) + + res = df.ffill() + tm.assert_frame_equal(res, df_exp_fill) + + # dropna + res = df.dropna(subset=["cats"]) + tm.assert_frame_equal(res, df_exp_drop_cats) + + res = df.dropna() + tm.assert_frame_equal(res, df_exp_drop_all) + + # make sure that fillna takes missing values into account + c = pd.Categorical([np.nan, "b", np.nan], categories=["a", "b"]) + df = pd.DataFrame({"cats": c, "vals": [1, 2, 3]}) + + cat_exp = pd.Categorical(["a", "b", "a"], categories=["a", "b"]) + df_exp = pd.DataFrame({"cats": cat_exp, "vals": [1, 2, 3]}) + + res = df.fillna("a") + tm.assert_frame_equal(res, df_exp) + + def test_fillna_categorical_nan(self): + # GH#14021 + # np.nan should always be a valid filler + cat = pd.Categorical([np.nan, 2, np.nan]) + val = pd.Categorical([np.nan, np.nan, np.nan]) + df = pd.DataFrame({"cats": cat, "vals": val}) + + # GH#32950 df.median() is poorly behaved because there is no + # Categorical.median + median = pd.Series({"cats": 2.0, "vals": np.nan}) + + res = df.fillna(median) + v_exp = [np.nan, np.nan, np.nan] + df_exp = pd.DataFrame({"cats": [2, 2, 2], "vals": v_exp}, dtype="category") + tm.assert_frame_equal(res, df_exp) + + result = df.cats.fillna(np.nan) + tm.assert_series_equal(result, df.cats) + + result = df.vals.fillna(np.nan) + tm.assert_series_equal(result, df.vals) + + idx = pd.DatetimeIndex( + ["2011-01-01 09:00", "2016-01-01 23:45", "2011-01-01 09:00", pd.NaT, pd.NaT] + ) + df = pd.DataFrame({"a": pd.Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=pd.NaT), df) + + idx = pd.PeriodIndex( + ["2011-01", "2011-01", "2011-01", pd.NaT, pd.NaT], freq="M" + ) + df = pd.DataFrame({"a": pd.Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=pd.NaT), df) + + idx = pd.TimedeltaIndex(["1 days", "2 days", "1 days", pd.NaT, pd.NaT]) + df = pd.DataFrame({"a": pd.Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=pd.NaT), df) + + def test_fillna_with_categorical_series(self): + # https://github.com/pandas-dev/pandas/issues/56329 + df = pd.DataFrame( + {"cats": pd.Categorical(["A", "B", "C"]), "ints": [1.0, 2.0, np.nan]} + ) + + filler = pd.Series(pd.Categorical([10.0, 20.0, 30.0])) + result = df.fillna({"ints": filler}) + + expected = pd.DataFrame( + {"cats": pd.Categorical(["A", "B", "C"]), "ints": [1.0, 2.0, 30.0]} + ) + tm.assert_frame_equal(result, expected) + + def test_fillna_no_downcast(self, frame_or_series): + # GH#45603 preserve object dtype + obj = frame_or_series([1, 2, 3], dtype="object") + result = obj.fillna("") + tm.assert_equal(result, obj) + + @pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]]) + def test_fillna_dictlike_value_duplicate_colnames(self, columns): + # GH#43476 + df = pd.DataFrame(np.nan, index=[0, 1], columns=columns) + with tm.assert_produces_warning(None): + result = df.fillna({"A": 0}) + + expected = df.copy() + expected["A"] = 0.0 + tm.assert_frame_equal(result, expected) + + def test_fillna_dtype_conversion(self): + # make sure that fillna on an empty frame works + df = pd.DataFrame(index=["A", "B", "C"], columns=[1, 2, 3, 4, 5]) + result = df.dtypes + expected = pd.Series([np.dtype("object")] * 5, index=[1, 2, 3, 4, 5]) + tm.assert_series_equal(result, expected) + result = df.fillna(1) + expected = pd.DataFrame( + 1, index=["A", "B", "C"], columns=[1, 2, 3, 4, 5], dtype=object + ) + tm.assert_frame_equal(result, expected) + + # empty block + df = pd.DataFrame(index=range(3), columns=["A", "B"], dtype="float64") + # GH#45153 filling float with string is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = df.fillna("nan") + expected = pd.DataFrame( + "nan", dtype="object", index=range(3), columns=["A", "B"] + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("val", ["", 1, np.nan, 1.0]) + def test_fillna_dtype_conversion_equiv_replace(self, val): + df = pd.DataFrame({"A": [1, np.nan], "B": [1.0, 2.0]}) + expected = df.replace(np.nan, val) + # GH#45153 filling with incompatible value is deprecated + warn = Pandas4Warning if isinstance(val, str) else None + with tm.assert_produces_warning(warn, match="fill value"): + result = df.fillna(val) + tm.assert_frame_equal(result, expected) + + def test_fillna_datetime_columns(self): + # GH#7095 + df = pd.DataFrame( + { + "A": [-1, -2, np.nan], + "B": pd.date_range("20130101", periods=3), + "C": ["foo", "bar", None], + "D": ["foo2", "bar2", None], + }, + index=pd.date_range("20130110", periods=3), + ) + # GH#45153 filling float with string is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = df.fillna("?") + expected = pd.DataFrame( + { + "A": [-1, -2, "?"], + "B": pd.date_range("20130101", periods=3), + "C": ["foo", "bar", "?"], + "D": ["foo2", "bar2", "?"], + }, + index=pd.date_range("20130110", periods=3), + ) + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame( + { + "A": [-1, -2, np.nan], + "B": [pd.Timestamp("2013-01-01"), pd.Timestamp("2013-01-02"), pd.NaT], + "C": ["foo", "bar", None], + "D": ["foo2", "bar2", None], + }, + index=pd.date_range("20130110", periods=3), + ) + # GH#45153 filling datetime with string is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = df.fillna("?") + expected = pd.DataFrame( + { + "A": [-1, -2, "?"], + "B": [pd.Timestamp("2013-01-01"), pd.Timestamp("2013-01-02"), "?"], + "C": ["foo", "bar", "?"], + "D": ["foo2", "bar2", "?"], + }, + index=pd.date_range("20130110", periods=3), + ) + tm.assert_frame_equal(result, expected) + + def test_ffill(self, datetime_frame): + datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan + + alt = datetime_frame.ffill() + tm.assert_frame_equal(datetime_frame.ffill(), alt) + + def test_bfill(self, datetime_frame): + datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan + + alt = datetime_frame.bfill() + tm.assert_frame_equal(datetime_frame.bfill(), alt) + + def test_frame_pad_backfill_limit(self): + index = np.arange(10) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), index=index + ) + + result = df[:2].reindex(index, method="pad", limit=5) + + expected = df[:2].reindex(index).ffill() + expected.iloc[-3:] = np.nan + tm.assert_frame_equal(result, expected) + + result = df[-2:].reindex(index, method="backfill", limit=5) + + expected = df[-2:].reindex(index).bfill() + expected.iloc[:3] = np.nan + tm.assert_frame_equal(result, expected) + + def test_frame_fillna_limit(self): + index = np.arange(10) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), index=index + ) + + result = df[:2].reindex(index) + result = result.ffill(limit=5) + + expected = df[:2].reindex(index).ffill() + expected.iloc[-3:] = np.nan + tm.assert_frame_equal(result, expected) + + result = df[-2:].reindex(index) + result = result.bfill(limit=5) + + expected = df[-2:].reindex(index).bfill() + expected.iloc[:3] = np.nan + tm.assert_frame_equal(result, expected) + + def test_fillna_skip_certain_blocks(self): + # don't try to fill boolean, int blocks + + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 4)).astype(int)) + + # it works! + df.fillna(np.nan) + + @pytest.mark.parametrize("type", [int, float]) + def test_fillna_positive_limit(self, type): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype( + type + ) + + msg = "Limit must be greater than 0" + with pytest.raises(ValueError, match=msg): + df.fillna(0, limit=-5) + + @pytest.mark.parametrize("type", [int, float]) + def test_fillna_integer_limit(self, type): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype( + type + ) + + msg = "Limit must be an integer" + with pytest.raises(ValueError, match=msg): + df.fillna(0, limit=0.5) + + def test_fillna_inplace(self): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 4))) + df.loc[:4, 1] = np.nan + df.loc[-4:, 3] = np.nan + + expected = df.fillna(value=0) + assert expected is not df + + result = df.fillna(value=0, inplace=True) + assert result is df + tm.assert_frame_equal(df, expected) + + result = df.fillna(value={0: 0}, inplace=True) + assert result is df + + df.loc[:4, 1] = np.nan + df.loc[-4:, 3] = np.nan + expected = df.ffill() + assert expected is not df + + df.ffill(inplace=True) + tm.assert_frame_equal(df, expected) + + def test_fillna_dict_series(self): + df = pd.DataFrame( + { + "a": [np.nan, 1, 2, np.nan, np.nan], + "b": [1, 2, 3, np.nan, np.nan], + "c": [np.nan, 1, 2, 3, 4], + } + ) + + result = df.fillna({"a": 0, "b": 5}) + + expected = df.copy() + expected["a"] = expected["a"].fillna(0) + expected["b"] = expected["b"].fillna(5) + tm.assert_frame_equal(result, expected) + + # it works + result = df.fillna({"a": 0, "b": 5, "d": 7}) + + # Series treated same as dict + result = df.fillna(df.max()) + expected = df.fillna(df.max().to_dict()) + tm.assert_frame_equal(result, expected) + + def test_fillna_dict_series_axis_1(self): + df = pd.DataFrame( + { + "a": [np.nan, 1, 2, np.nan, np.nan], + "b": [1, 2, 3, np.nan, np.nan], + "c": [np.nan, 1, 2, 3, 4], + } + ) + result = df.fillna(df.max(axis=1), axis=1) + result = df.fillna(df.max(axis=1), axis=1, inplace=True) + assert result is df + expected = pd.DataFrame( + { + "a": [1.0, 1.0, 2.0, 3.0, 4.0], + "b": [1.0, 2.0, 3.0, 3.0, 4.0], + "c": [1.0, 1.0, 2.0, 3.0, 4.0], + } + ) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, expected) + + def test_fillna_dict_series_axis_1_mismatch_cols(self): + df = pd.DataFrame( + { + "a": ["abc", "def", np.nan, "ghi", "jkl"], + "b": [1, 2, 3, np.nan, np.nan], + "c": [np.nan, 1, 2, 3, 4], + } + ) + with pytest.raises(ValueError, match="All columns must have the same dtype"): + df.fillna(pd.Series({"a": "abc", "b": "def", "c": "hij"}), axis=1) + + def test_fillna_dict_series_axis_1_value_mismatch_with_cols(self): + df = pd.DataFrame( + { + "a": [np.nan, 1, 2, np.nan, np.nan], + "b": [1, 2, 3, np.nan, np.nan], + "c": [np.nan, 1, 2, 3, 4], + } + ) + with pytest.raises(ValueError, match=".* not a suitable type to fill into .*"): + df.fillna(pd.Series({"a": "abc", "b": "def", "c": "hij"}), axis=1) + + def test_fillna_dataframe(self): + # GH#8377 + df = pd.DataFrame( + { + "a": [np.nan, 1, 2, np.nan, np.nan], + "b": [1, 2, 3, np.nan, np.nan], + "c": [np.nan, 1, 2, 3, 4], + }, + index=list("VWXYZ"), + ) + + # df2 may have different index and columns + df2 = pd.DataFrame( + { + "a": [np.nan, 10, 20, 30, 40], + "b": [50, 60, 70, 80, 90], + "foo": ["bar"] * 5, + }, + index=list("VWXuZ"), + ) + + result = df.fillna(df2) + + # only those columns and indices which are shared get filled + expected = pd.DataFrame( + { + "a": [np.nan, 1, 2, np.nan, 40], + "b": [1, 2, 3, np.nan, 90], + "c": [np.nan, 1, 2, 3, 4], + }, + index=list("VWXYZ"), + ) + + tm.assert_frame_equal(result, expected) + + def test_fillna_columns(self): + arr = np.random.default_rng(2).standard_normal((10, 10)) + arr[:, ::2] = np.nan + df = pd.DataFrame(arr) + + result = df.ffill(axis=1) + expected = df.T.ffill().T + tm.assert_frame_equal(result, expected) + + df.insert(6, "foo", 5) + result = df.ffill(axis=1) + expected = df.astype(float).ffill(axis=1) + tm.assert_frame_equal(result, expected) + + def test_fillna_invalid_value(self, float_frame): + # list + msg = '"value" parameter must be a scalar or dict, but you passed a "{}"' + with pytest.raises(TypeError, match=msg.format("list")): + float_frame.fillna([1, 2]) + # tuple + with pytest.raises(TypeError, match=msg.format("tuple")): + float_frame.fillna((1, 2)) + # frame with series + msg = ( + '"value" parameter must be a scalar, dict or Series, but you ' + 'passed a "DataFrame"' + ) + with pytest.raises(TypeError, match=msg): + float_frame.iloc[:, 0].fillna(float_frame) + + def test_fillna_col_reordering(self): + cols = ["COL." + str(i) for i in range(5, 0, -1)] + data = np.random.default_rng(2).random((20, 5)) + df = pd.DataFrame(index=range(20), columns=cols, data=data) + filled = df.ffill() + assert df.columns.tolist() == filled.columns.tolist() + + def test_fill_empty(self, float_frame): + df = float_frame.reindex(columns=[]) + result = df.fillna(value=0) + tm.assert_frame_equal(result, df) + + def test_fillna_with_columns_and_limit(self): + # GH40989 + df = pd.DataFrame( + [ + [np.nan, 2, np.nan, 0], + [3, 4, np.nan, 1], + [np.nan, np.nan, np.nan, 5], + [np.nan, 3, np.nan, 4], + ], + columns=list("ABCD"), + ) + result = df.fillna(axis=1, value=100, limit=1) + result2 = df.fillna(axis=1, value=100, limit=2) + + expected = pd.DataFrame( + { + "A": pd.Series([100, 3, 100, 100], dtype="float64"), + "B": [2, 4, np.nan, 3], + "C": [np.nan, 100, np.nan, np.nan], + "D": pd.Series([0, 1, 5, 4], dtype="float64"), + }, + index=[0, 1, 2, 3], + ) + expected2 = pd.DataFrame( + { + "A": pd.Series([100, 3, 100, 100], dtype="float64"), + "B": pd.Series([2, 4, 100, 3], dtype="float64"), + "C": [100, 100, np.nan, 100], + "D": pd.Series([0, 1, 5, 4], dtype="float64"), + }, + index=[0, 1, 2, 3], + ) + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected2) + + def test_fillna_datetime_inplace(self): + # GH#48863 + df = pd.DataFrame( + { + "date1": pd.to_datetime(["2018-05-30", None]), + "date2": pd.to_datetime(["2018-09-30", None]), + } + ) + expected = df.copy() + df.fillna(np.nan, inplace=True) + tm.assert_frame_equal(df, expected) + + def test_fillna_inplace_with_columns_limit_and_value(self): + # GH40989 + df = pd.DataFrame( + [ + [np.nan, 2, np.nan, 0], + [3, 4, np.nan, 1], + [np.nan, np.nan, np.nan, 5], + [np.nan, 3, np.nan, 4], + ], + columns=list("ABCD"), + ) + + expected = df.fillna(axis=1, value=100, limit=1) + assert expected is not df + + result = df.fillna(axis=1, value=100, limit=1, inplace=True) + assert result is df + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("val", [-1, {"x": -1, "y": -1}]) + def test_inplace_dict_update_view(self, val): + # GH#47188 + df = pd.DataFrame({"x": [np.nan, 2], "y": [np.nan, 2]}) + df_orig = df.copy() + result_view = df[:] + df.fillna(val, inplace=True) + expected = pd.DataFrame({"x": [-1, 2.0], "y": [-1.0, 2]}) + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(result_view, df_orig) + + def test_single_block_df_with_horizontal_axis(self): + # GH 47713 + df = pd.DataFrame( + { + "col1": [5, 0, np.nan, 10, np.nan], + "col2": [7, np.nan, np.nan, 5, 3], + "col3": [12, np.nan, 1, 2, 0], + "col4": [np.nan, 1, 1, np.nan, 18], + } + ) + result = df.fillna(50, limit=1, axis=1) + expected = pd.DataFrame( + [ + [5.0, 7.0, 12.0, 50.0], + [0.0, 50.0, np.nan, 1.0], + [50.0, np.nan, 1.0, 1.0], + [10.0, 5.0, 2.0, 50.0], + [50.0, 3.0, 0.0, 18.0], + ], + columns=["col1", "col2", "col3", "col4"], + ) + tm.assert_frame_equal(result, expected) + + def test_fillna_with_multi_index_frame(self): + # GH 47649 + pdf = pd.DataFrame( + { + ("x", "a"): [np.nan, 2.0, 3.0], + ("x", "b"): [1.0, 2.0, np.nan], + ("y", "c"): [1.0, 2.0, np.nan], + } + ) + expected = pd.DataFrame( + { + ("x", "a"): [-1.0, 2.0, 3.0], + ("x", "b"): [1.0, 2.0, -1.0], + ("y", "c"): [1.0, 2.0, np.nan], + } + ) + tm.assert_frame_equal(pdf.fillna({"x": -1}), expected) + tm.assert_frame_equal(pdf.fillna({"x": -1, ("x", "b"): -2}), expected) + + expected = pd.DataFrame( + { + ("x", "a"): [-1.0, 2.0, 3.0], + ("x", "b"): [1.0, 2.0, -2.0], + ("y", "c"): [1.0, 2.0, np.nan], + } + ) + tm.assert_frame_equal(pdf.fillna({("x", "b"): -2, "x": -1}), expected) + + def test_fillna_multiindex_with_duplicate_columns(self): + # GH#53498 + data = [[np.nan, 2, 3], [4, np.nan, 6], [7, 8, np.nan]] + df = pd.DataFrame( + data, + columns=pd.MultiIndex.from_tuples([("x", "a"), ("x", "a"), ("y", "b")]), + ) + result = df.fillna({("x", "a"): 0}) + expected = pd.DataFrame( + [[0.0, 2.0, 3.0], [4.0, 0.0, 6.0], [7.0, 8.0, np.nan]], + columns=pd.MultiIndex.from_tuples([("x", "a"), ("x", "a"), ("y", "b")]), + ) + tm.assert_frame_equal(result, expected) + + +def test_fillna_nonconsolidated_frame(): + # https://github.com/pandas-dev/pandas/issues/36495 + df = pd.DataFrame( + [ + [1, 1, 1, 1.0], + [2, 2, 2, 2.0], + [3, 3, 3, 3.0], + ], + columns=["i1", "i2", "i3", "f1"], + ) + df_nonconsol = df.pivot(index="i1", columns="i2") + result = df_nonconsol.fillna(0) + assert result.isna().sum().sum() == 0 + + +def test_fillna_nones_inplace(): + # GH 48480 + df = pd.DataFrame( + [[None, None], [None, None]], + columns=["A", "B"], + ) + result = df.fillna(value={"A": 1, "B": 2}, inplace=True) + assert result is df + + expected = pd.DataFrame([[1, 2], [1, 2]], columns=["A", "B"], dtype=object) + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize( + "data, expected_data, method, kwargs", + ( + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan], + "ffill", + {"limit_area": "inside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan], + "ffill", + {"limit_area": "inside", "limit": 1}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0], + "ffill", + {"limit_area": "outside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan], + "ffill", + {"limit_area": "outside", "limit": 1}, + ), + ( + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], + "ffill", + {"limit_area": "outside", "limit": 1}, + ), + ( + range(5), + range(5), + "ffill", + {"limit_area": "outside", "limit": 1}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "inside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "inside", "limit": 1}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "outside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "outside", "limit": 1}, + ), + ), +) +def test_ffill_bfill_limit_area(data, expected_data, method, kwargs): + # GH#56492 + df = pd.DataFrame(data) + expected = pd.DataFrame(expected_data) + result = getattr(df, method)(**kwargs) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("test_frame", [True, False]) +@pytest.mark.parametrize("dtype", ["float", "object"]) +def test_fillna_with_none_object(test_frame, dtype): + # GH#57723 + obj = pd.Series([1, np.nan, 3], dtype=dtype) + if test_frame: + obj = obj.to_frame() + result = obj.fillna(value=None) + expected = pd.Series([1, None, 3], dtype=dtype) + if test_frame: + expected = expected.to_frame() + tm.assert_equal(result, expected) + + +def test_fillna_out_of_bounds_datetime(): + # GH#61208 + df = pd.DataFrame( + { + "datetime": pd.date_range("1/1/2011", periods=3, freq="h", unit="ns"), + "value": [1, 2, 3], + } + ) + df.iloc[0, 0] = None + + msg = "Cannot cast 0001-01-01 00:00:00 to unit='ns' without overflow" + # GH#45153 the Pandas4Warning fires before the OutOfBoundsDatetime + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + with pytest.raises(OutOfBoundsDatetime, match=msg): + df.fillna(pd.Timestamp("0001-01-01")) + + +def test_fillna_dtype_preservation_after_apply(): + # GH#14407 - fillna after apply should preserve dtypes correctly + # (block splitting should occur for mixed-dtype results) + df = pd.DataFrame( + {"c1": list("ABC"), "c2": list("123"), "c3": [1.5, 2.5, 3.5], "c4": [0, 1, 2]} + ) + result = df.apply(lambda x: pd.to_numeric(x, errors="coerce")).fillna(df) + assert result["c1"].dtype == object + assert result["c2"].dtype == np.int64 + assert result["c3"].dtype == np.float64 + assert result["c4"].dtype == np.int64 + + +def test_fillna_with_duplicate_index_and_unique_fill_frame(): + # GH#36974 filling a frame that has a duplicated index from a frame with a + # unique index must align by label instead of raising InvalidIndexError + df = pd.DataFrame({"a": [np.nan, np.nan, 5.0]}, index=[0, 1, 0]) + df_fillna = pd.DataFrame({"a": [10.0, 20.0]}, index=[0, 1]) + result = df.fillna(df_fillna) + expected = pd.DataFrame({"a": [10.0, 20.0, 5.0]}, index=[0, 1, 0]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("axis", ["index", "columns"]) +def test_fillna_fill_frame_with_duplicate_labels_raises(axis): + # GH#27672 + df = pd.DataFrame({"A": [1.0, np.nan], "B": [np.nan, 2.0]}, index=["a", "b"]) + if axis == "index": + value = pd.DataFrame({"A": [1, 0, 2], "B": [1, 2, 3]}, index=["b", "a", "b"]) + else: + value = pd.DataFrame([[1, 2, 3]] * 2, index=["a", "b"], columns=["A", "B", "B"]) + msg = "Cannot align with an object that has duplicate labels" + with pytest.raises(InvalidIndexError, match=msg): + df.fillna(value) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_filter.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1b7eb1686123afcb047ac1b59846b43151e363 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_filter.py @@ -0,0 +1,510 @@ +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameFilter: + def test_filter(self, float_frame, float_string_frame): + # Items + filtered = float_frame.filter(["A", "B", "E"]) + assert len(filtered.columns) == 2 + assert "E" not in filtered + + filtered = float_frame.filter(["A", "B", "E"], axis="columns") + assert len(filtered.columns) == 2 + assert "E" not in filtered + + # Other axis + idx = float_frame.index[0:4] + filtered = float_frame.filter(idx, axis="index") + expected = float_frame.reindex(index=idx) + tm.assert_frame_equal(filtered, expected) + + # like + fcopy = float_frame.copy() + fcopy["AA"] = 1 + + filtered = fcopy.filter(like="A") + assert len(filtered.columns) == 2 + assert "AA" in filtered + + # like with ints in column names + df = pd.DataFrame(0.0, index=[0, 1, 2], columns=[0, 1, "_A", "_B"]) + filtered = df.filter(like="_") + assert len(filtered.columns) == 2 + + # regex with ints in column names + # from PR #10384 + df = pd.DataFrame(0.0, index=[0, 1, 2], columns=["A1", 1, "B", 2, "C"]) + expected = pd.DataFrame( + 0.0, index=[0, 1, 2], columns=pd.Index([1, 2], dtype=object) + ) + filtered = df.filter(regex="^[0-9]+$") + tm.assert_frame_equal(filtered, expected) + + expected = pd.DataFrame(0.0, index=[0, 1, 2], columns=[0, "0", 1, "1"]) + # shouldn't remove anything + filtered = expected.filter(regex="^[0-9]+$") + tm.assert_frame_equal(filtered, expected) + + # pass in None + no_arg_msg = "Must pass a positional argument or one of `items`, `cond`" + with pytest.raises(TypeError, match=no_arg_msg): + float_frame.filter() + with pytest.raises(TypeError, match=no_arg_msg): + float_frame.filter(items=None) + with pytest.raises(TypeError, match=no_arg_msg): + float_frame.filter(axis=1) + + # test mutually exclusive arguments + with pytest.raises(TypeError, match="mutually exclusive"): + float_frame.filter(items=["one", "three"], regex="e$", like="bbi") + with pytest.raises(TypeError, match="mutually exclusive"): + float_frame.filter(items=["one", "three"], regex="e$", axis=1) + with pytest.raises(TypeError, match="mutually exclusive"): + float_frame.filter(items=["one", "three"], regex="e$") + with pytest.raises(TypeError, match="mutually exclusive"): + float_frame.filter(items=["one", "three"], like="bbi", axis=0) + with pytest.raises(TypeError, match="mutually exclusive"): + float_frame.filter(items=["one", "three"], like="bbi") + + # objects + filtered = float_string_frame.filter(like="foo") + assert "foo" in filtered + + # unicode columns, won't ascii-encode + df = float_frame.rename(columns={"B": "\u2202"}) + filtered = df.filter(like="C") + assert "C" in filtered + + def test_filter_regex_search(self, float_frame): + fcopy = float_frame.copy() + fcopy["AA"] = 1 + + # regex + filtered = fcopy.filter(regex="[A]+") + assert len(filtered.columns) == 2 + assert "AA" in filtered + + # doesn't have to be at beginning + df = pd.DataFrame( + {"aBBa": [1, 2], "BBaBB": [1, 2], "aCCa": [1, 2], "aCCaBB": [1, 2]} + ) + + result = df.filter(regex="BB") + exp = df[[x for x in df.columns if "BB" in x]] + tm.assert_frame_equal(result, exp) + + @pytest.mark.parametrize( + "name,expected_data", + [ + ("a", {"a": [1, 2]}), + ("あ", {"あ": [3, 4]}), + ], + ) + def test_filter_unicode(self, name, expected_data): + # GH13101 + df = pd.DataFrame({"a": [1, 2], "あ": [3, 4]}) + expected = pd.DataFrame(expected_data) + + tm.assert_frame_equal(df.filter(like=name), expected) + tm.assert_frame_equal(df.filter(regex=name), expected) + + def test_filter_bytestring(self): + # GH13101 + name = "a" + df = pd.DataFrame({b"a": [1, 2], b"b": [3, 4]}) + expected = pd.DataFrame({b"a": [1, 2]}) + + tm.assert_frame_equal(df.filter(like=name), expected) + tm.assert_frame_equal(df.filter(regex=name), expected) + + def test_filter_corner(self): + empty = pd.DataFrame() + + result = empty.filter([]) + tm.assert_frame_equal(result, empty) + + result = empty.filter(like="foo") + tm.assert_frame_equal(result, empty) + + def test_filter_regex_non_string(self): + # GH#5798 trying to filter on non-string columns should drop, + # not raise + df = pd.DataFrame( + np.random.default_rng(2).random((3, 2)), columns=["STRING", 123] + ) + result = df.filter(regex="STRING") + expected = df[["STRING"]] + tm.assert_frame_equal(result, expected) + + def test_filter_keep_order(self): + # GH#54980 + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + result = df.filter(items=["B", "A"]) + expected = df[["B", "A"]] + tm.assert_frame_equal(result, expected) + + def test_filter_different_dtype(self): + # GH#54980 + df = pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6]}) + result = df.filter(items=["B", "A"]) + expected = df[[]] + tm.assert_frame_equal(result, expected) + + +@pytest.fixture +def df(): + return pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, index=["x", "y", "z"]) + + +@pytest.mark.parametrize( + "mask", + [ + [False, True, True], + np.array([False, True, True]), + pd.array([False, True, True], dtype="boolean"), + pd.Index([False, True, True]), + pd.Series([False, True, True], index=["x", "y", "z"]), + lambda df: df["a"] > 1, + pd.col("a") > 1, + ], +) +def test_filter_cond_rows(df, mask): + # GH#61317 + result = df.filter(cond=mask) + expected = df.iloc[1:] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("mask", [lambda df: df["a"] > 1, pd.col("a") > 1]) +def test_filter_positional_callable_is_mask(df, mask): + # GH#61317 + result = df.filter(mask) + expected = df.iloc[1:] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "mask", + [ + [True, False, True], + [True, None, False], + np.array([True, False, True]), + pd.array([True, False, True], dtype="boolean"), + pd.Index([True, False, True]), + pd.Series([True, False, True], index=["x", "y", "z"]), + ], +) +def test_filter_positional_bools_select_labels(df, mask): + # GH#61317 + # A list-like of booleans passed positionally selects labels, as it did + # before masks were supported, but warns since it is likely meant as a mask + msg = "A list-like of booleans passed positionally to DataFrame.filter" + with tm.assert_produces_warning(UserWarning, match=msg): + result = df.filter(mask) + expected = df.iloc[:, []] + tm.assert_frame_equal(result, expected) + + # the explicit keyword does not warn + result = df.filter(items=mask) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "arg, cols", + [ + (["b", "a"], ["b", "a"]), + (("b", "a"), ["b", "a"]), + ((True, False, True), []), + ], +) +def test_filter_positional_labels_no_warning(df, arg, cols): + # GH#61317 + # tuples are never masks + result = df.filter(arg) + expected = df[cols] + tm.assert_frame_equal(result, expected) + + +def test_filter_na_label(): + # GH#61317 + df = pd.DataFrame({np.nan: [1], "a": [2]}) + result = df.filter(items=[np.nan]) + expected = df.iloc[:, [0]] + tm.assert_frame_equal(result, expected, check_column_type=False) + + df = pd.DataFrame({"a": [1, 2]}, index=[np.nan, "x"]) + result = df.filter(items=[np.nan], axis=0) + expected = df.iloc[[0]] + tm.assert_frame_equal(result, expected, check_index_type=False) + + +def test_filter_tuple_labels_multiindex(): + # GH#61317 + mi = pd.MultiIndex.from_tuples([(True, False), (False, True)]) + df = pd.DataFrame({"a": [1, 2]}, index=mi) + result = df.filter([(True, False)], axis=0) + expected = df.iloc[[0]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "dtype", + [ + "bool", + "boolean", + pytest.param("bool[pyarrow]", marks=td.skip_if_no("pyarrow")), + ], +) +def test_filter_bool_labels(dtype): + # GH#61317 + df = pd.DataFrame({"a": [1, 2]}, index=pd.Index([True, False], dtype=dtype)) + result = df.filter(items=[True], axis=0) + expected = df.iloc[[0]] + tm.assert_frame_equal(result, expected) + + msg = "A list-like of booleans passed positionally to DataFrame.filter" + with tm.assert_produces_warning(UserWarning, match=msg): + result = df.filter([True], axis=0) + tm.assert_frame_equal(result, expected) + + result = df.filter(cond=[False, True], axis=0) + expected = df.iloc[[1]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"items": ["a"]}, + {"cond": [True, False, True]}, + {"like": "a"}, + {"regex": "a"}, + ], +) +def test_filter_positional_and_keyword_mutually_exclusive(df, kwargs): + # GH#61317 + msg = "mutually exclusive" + with pytest.raises(TypeError, match=msg): + df.filter(["a"], **kwargs) + with pytest.raises(TypeError, match=msg): + df.filter(cond=[True, False, True], items=["a"]) + + +@pytest.mark.parametrize( + "cond", + [["a"], [1, 0, 1], (True, False, True), "abc", np.array([1.0, 0.0, 1.0])], +) +def test_filter_cond_not_mask_raises(df, cond): + # GH#61317 + msg = "cond passed to DataFrame.filter must be a one-dimensional boolean mask" + with pytest.raises(TypeError, match=msg): + df.filter(cond=cond) + + +def test_filter_cond_series_aligns(df): + # GH#61317 + mask = pd.Series([True, True, False], index=["z", "y", "x"]) + result = df.filter(cond=mask) + expected = df.iloc[1:] + tm.assert_frame_equal(result, expected) + + +def test_filter_cond_series_unalignable(df): + # GH#61317 + mask = pd.Series([True, True, False], index=["z", "y", "w"]) + msg = "Unalignable boolean Series provided as indexer" + with pytest.raises(pd.errors.IndexingError, match=msg): + df.filter(cond=mask) + + +def test_filter_cond_wrong_length(df): + # GH#61317 + msg = "Boolean index has wrong length: 2 instead of 3" + with pytest.raises(IndexError, match=msg): + df.filter(cond=np.array([True, False])) + + +@pytest.mark.parametrize("axis", [1, "columns"]) +def test_filter_cond_columns(df, axis): + # GH#61317 + result = df.filter(cond=[False, True], axis=axis) + expected = df[["b"]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("axis", [1, "columns"]) +def test_filter_callable_columns(df, axis): + # GH#61317 + result = df.filter(lambda df: df.columns == "b", axis=axis) + expected = df[["b"]] + tm.assert_frame_equal(result, expected) + + result = df.filter(cond=lambda df: df.columns == "b", axis=axis) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("axis", [1, "columns"]) +def test_filter_expression_columns_raises(df, axis): + # GH#61317 + cond = pd.col("a") > 1 + msg = ( + "Expressions such as pd.col\\(...\\) are only supported by DataFrame.filter " + "with axis=0" + ) + with pytest.raises(ValueError, match=msg): + df.filter(cond, axis=axis) + with pytest.raises(ValueError, match=msg): + df.filter(cond=cond, axis=axis) + + +def test_filter_cond_2d_raises(df): + # GH#61317 + msg = "cond passed to DataFrame.filter must be a one-dimensional boolean mask" + with pytest.raises(TypeError, match=msg): + df.filter(cond=df > 1) + msg = "must evaluate to a one-dimensional boolean mask" + with pytest.raises(TypeError, match=msg): + df.filter(lambda df: df > 1) + + msg = "The mask passed to DataFrame.filter must be one-dimensional" + with pytest.raises(ValueError, match=msg): + df.filter(cond=np.array([[True, False, True]])) + + +def test_filter_positional_frame_selects_labels(df): + # GH#61317 + # a DataFrame is not a mask positionally; it fails as a list of labels + # without warning + msg = "Index data must be 1-dimensional" + with pytest.raises(ValueError, match=msg): + df.filter(df > 1) + + +def test_filter_callable_must_return_mask(df): + # GH#61317 + msg = "The callable passed to DataFrame.filter must evaluate to a one-dimensional" + with pytest.raises(TypeError, match=msg): + df.filter(lambda df: ["a"]) + with pytest.raises(TypeError, match=msg): + df.filter(cond=lambda df: ["a"]) + + +def test_filter_expression_must_return_mask(df): + # GH#61317 + msg = "The expression passed to DataFrame.filter must evaluate to a one-dimensional" + with pytest.raises(TypeError, match=msg): + df.filter(pd.col("a")) + + +@pytest.mark.parametrize( + "mask", + [ + [True, None, False], + np.array([True, None, False], dtype=object), + pd.array([True, None, False], dtype="boolean"), + pd.Series([True, None, False], dtype="boolean", index=["x", "y", "z"]), + pd.Index([True, None, False], dtype=object), + ], +) +def test_filter_cond_na(df, mask): + # GH#61317 + # missing values are treated as False by default, matching df[mask] + # for a nullable boolean mask + result = df.filter(cond=mask) + expected = df.iloc[[0]] + tm.assert_frame_equal(result, expected) + + result = df.filter(cond=mask, na=False) + tm.assert_frame_equal(result, expected) + + msg = "The mask contains missing values" + with pytest.raises(ValueError, match=msg): + df.filter(cond=mask, na="raise") + + result = df.filter(cond=mask, na=True) + expected = df.iloc[[0, 1]] + tm.assert_frame_equal(result, expected) + + +@td.skip_if_no("pyarrow") +def test_filter_cond_na_pyarrow(df): + # GH#61317 + mask = pd.array([True, None, False], dtype="bool[pyarrow]") + result = df.filter(cond=mask) + expected = df.iloc[[0]] + tm.assert_frame_equal(result, expected) + + msg = "The mask contains missing values" + with pytest.raises(ValueError, match=msg): + df.filter(cond=mask, na="raise") + + result = df.filter(cond=mask, na=True) + expected = df.iloc[[0, 1]] + tm.assert_frame_equal(result, expected) + + +def test_filter_cond_all_na(df): + # GH#61317 + result = df.filter(cond=[None, None, None]) + expected = df.iloc[[]] + tm.assert_frame_equal(result, expected) + + result = df.filter(cond=[None, None, None], na=True) + tm.assert_frame_equal(result, df) + + with pytest.raises(ValueError, match="The mask contains missing values"): + df.filter(cond=[None, None, None], na="raise") + + +def test_filter_invalid_na(df): + # GH#61317 + msg = "na must be 'raise', True, or False, got 'ignore'" + with pytest.raises(ValueError, match=msg): + df.filter(cond=[True, False, True], na="ignore") + + +@pytest.mark.parametrize( + "kwargs", + [ + {"items": ["a"]}, + {"items": ["x"], "axis": 0}, + {"like": "a"}, + {"like": "x", "axis": "index"}, + {"regex": "a"}, + {"regex": "x", "axis": 0}, + ], +) +def test_filter_labels(df, kwargs): + # GH#61317 + # label-based usage keeps working and defaults to the columns + result = df.filter(**kwargs) + if kwargs.get("axis") in (0, "index"): + expected = df.iloc[[0]] + else: + expected = df[["a"]] + tm.assert_frame_equal(result, expected) + + +def test_filter_cond_default_axis_is_index(df): + # GH#61317 + # unlike the label-based usage, a mask defaults to the index + result = df.filter(cond=[True, False, True]) + expected = df.iloc[[0, 2]] + tm.assert_frame_equal(result, expected) + + +def test_filter_like_regex_positional(): + # GH#61317 + # like, regex, and axis remain positional-or-keyword after the + # positional-only first argument + df = pd.DataFrame({"a": [1]}, index=["x"]) + result = df.filter(None, "x", None, 0) + tm.assert_frame_equal(result, df) + result = df.filter(None, None, "^x", 0) + tm.assert_frame_equal(result, df) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_first_valid_index.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_first_valid_index.py new file mode 100644 index 0000000000000000000000000000000000000000..a2b7ca40bc5283b34b4d777147241af8f9160d67 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_first_valid_index.py @@ -0,0 +1,103 @@ +""" +Includes test for last_valid_index. +""" + +import numpy as np +import pytest + +import pandas as pd + + +class TestFirstValidIndex: + def test_first_valid_index_single_nan(self, frame_or_series): + # GH#9752 Series/DataFrame should both return None, not raise + obj = frame_or_series([np.nan]) + + assert obj.first_valid_index() is None + assert obj.iloc[:0].first_valid_index() is None + + @pytest.mark.parametrize( + "dtype, expected_type", [("int64", int), ("float64", float), ("Int64", int)] + ) + @pytest.mark.parametrize("method", ["first_valid_index", "last_valid_index"]) + def test_first_last_valid_result_type( + self, frame_or_series, dtype, expected_type, method, using_python_scalars + ): + # GH#64266 + obj = frame_or_series( + [np.nan, 1.0, np.nan], index=pd.Index([10, 20, 30], dtype=dtype) + ) + result = getattr(obj, method)() + assert result == 20 + if using_python_scalars: + assert type(result) is expected_type + else: + assert isinstance(result, np.generic) + + @pytest.mark.parametrize( + "empty", + [ + pd.DataFrame(), + pd.Series(dtype=object), + pd.Series([], index=[], dtype=object), + ], + ) + def test_first_valid_index_empty(self, empty): + # GH#12800 + assert empty.last_valid_index() is None + assert empty.first_valid_index() is None + + @pytest.mark.parametrize( + "data,idx,expected_first,expected_last", + [ + ({"A": [1, 2, 3]}, [1, 1, 2], 1, 2), + ({"A": [1, 2, 3]}, [1, 2, 2], 1, 2), + ({"A": [1, 2, 3, 4]}, ["d", "d", "d", "d"], "d", "d"), + ({"A": [1, np.nan, 3]}, [1, 1, 2], 1, 2), + ({"A": [np.nan, np.nan, 3]}, [1, 1, 2], 2, 2), + ({"A": [1, np.nan, 3]}, [1, 2, 2], 1, 2), + ], + ) + def test_first_last_valid_frame(self, data, idx, expected_first, expected_last): + # GH#21441 + df = pd.DataFrame(data, index=idx) + assert expected_first == df.first_valid_index() + assert expected_last == df.last_valid_index() + + @pytest.mark.parametrize( + "index", + [ + pd.Index([str(i) for i in range(20)]), + pd.date_range("2020-01-01", periods=20), + ], + ) + def test_first_last_valid(self, index): + mat = np.random.default_rng(2).standard_normal(len(index)) + mat[:5] = np.nan + mat[-5:] = np.nan + + frame = pd.DataFrame({"foo": mat}, index=index) + assert frame.first_valid_index() == frame.index[5] + assert frame.last_valid_index() == frame.index[-6] + + ser = frame["foo"] + assert ser.first_valid_index() == frame.index[5] + assert ser.last_valid_index() == frame.index[-6] + + @pytest.mark.parametrize( + "index", + [ + pd.Index([str(i) for i in range(10)]), + pd.date_range("2020-01-01", periods=10), + ], + ) + def test_first_last_valid_all_nan(self, index): + # GH#17400: no valid entries + frame = pd.DataFrame(np.nan, columns=["foo"], index=index) + + assert frame.last_valid_index() is None + assert frame.first_valid_index() is None + + ser = frame["foo"] + assert ser.first_valid_index() is None + assert ser.last_valid_index() is None diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_get_numeric_data.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_get_numeric_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c841048b65d6bc9cb87d4537ef182b4265b85ed6 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_get_numeric_data.py @@ -0,0 +1,101 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import IntervalArray + + +class TestGetNumericData: + def test_get_numeric_data_preserve_dtype(self): + # get the numeric data + obj = pd.DataFrame( + {"A": [1, "2", 3.0]}, columns=pd.Index(["A"], dtype="object") + ) + result = obj._get_numeric_data() + expected = pd.DataFrame(dtype=object, index=pd.RangeIndex(3), columns=[]) + tm.assert_frame_equal(result, expected) + + def test_get_numeric_data(self, using_infer_string): + datetime64name = np.dtype("M8[s]").name + objectname = np.dtype(np.object_).name + + df = pd.DataFrame( + {"a": 1.0, "b": 2, "c": "foo", "f": pd.Timestamp("20010102").as_unit("s")}, + index=np.arange(10), + ) + result = df.dtypes + expected = pd.Series( + [ + np.dtype("float64"), + np.dtype("int64"), + np.dtype(objectname) + if not using_infer_string + else pd.StringDtype(na_value=np.nan), + np.dtype(datetime64name), + ], + index=["a", "b", "c", "f"], + ) + tm.assert_series_equal(result, expected) + + df = pd.DataFrame( + { + "a": 1.0, + "b": 2, + "c": "foo", + "d": np.array([1.0] * 10, dtype="float32"), + "e": np.array([1] * 10, dtype="int32"), + "f": np.array([1] * 10, dtype="int16"), + "g": pd.Timestamp("20010102"), + }, + index=np.arange(10), + ) + + result = df._get_numeric_data() + expected = df.loc[:, ["a", "b", "d", "e", "f"]] + tm.assert_frame_equal(result, expected) + + only_obj = df.loc[:, ["c", "g"]] + result = only_obj._get_numeric_data() + expected = df.loc[:, []] + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame.from_dict( + {"a": [1, 2], "b": ["foo", "bar"], "c": [np.pi, np.e]} + ) + result = df._get_numeric_data() + expected = pd.DataFrame.from_dict({"a": [1, 2], "c": [np.pi, np.e]}) + tm.assert_frame_equal(result, expected) + + df = result.copy() + result = df._get_numeric_data() + expected = df + tm.assert_frame_equal(result, expected) + + def test_get_numeric_data_mixed_dtype(self): + # numeric and object columns + + df = pd.DataFrame( + { + "a": [1, 2, 3], + "b": [True, False, True], + "c": ["foo", "bar", "baz"], + "d": [None, None, None], + "e": [3.14, 0.577, 2.773], + } + ) + result = df._get_numeric_data() + tm.assert_index_equal(result.columns, pd.Index(["a", "b", "e"])) + + def test_get_numeric_data_extension_dtype(self): + # GH#22290 + df = pd.DataFrame( + { + "A": pd.array([-10, pd.NA, 0, 10, 20, 30], dtype="Int64"), + "B": pd.Categorical(list("abcabc")), + "C": pd.array([0, 1, 2, 3, pd.NA, 5], dtype="UInt8"), + "D": IntervalArray.from_breaks(range(7)), + } + ) + result = df._get_numeric_data() + expected = df.loc[:, ["A", "C"]] + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_head_tail.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_head_tail.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6177814c20c9cd3b2ffb77baa9f10597b65343 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_head_tail.py @@ -0,0 +1,57 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +def test_head_tail_generic(index, frame_or_series): + # GH#5370 + + ndim = 2 if frame_or_series is pd.DataFrame else 1 + shape = (len(index),) * ndim + vals = np.random.default_rng(2).standard_normal(shape) + obj = frame_or_series(vals, index=index) + + tm.assert_equal(obj.head(), obj.iloc[:5]) + tm.assert_equal(obj.tail(), obj.iloc[-5:]) + + # 0-len + tm.assert_equal(obj.head(0), obj.iloc[0:0]) + tm.assert_equal(obj.tail(0), obj.iloc[0:0]) + + # bounded + tm.assert_equal(obj.head(len(obj) + 1), obj) + tm.assert_equal(obj.tail(len(obj) + 1), obj) + + # neg index + tm.assert_equal(obj.head(-3), obj.head(len(index) - 3)) + tm.assert_equal(obj.tail(-3), obj.tail(len(index) - 3)) + + +def test_head_tail(float_frame): + tm.assert_frame_equal(float_frame.head(), float_frame[:5]) + tm.assert_frame_equal(float_frame.tail(), float_frame[-5:]) + + tm.assert_frame_equal(float_frame.head(0), float_frame[0:0]) + tm.assert_frame_equal(float_frame.tail(0), float_frame[0:0]) + + tm.assert_frame_equal(float_frame.head(-1), float_frame[:-1]) + tm.assert_frame_equal(float_frame.tail(-1), float_frame[1:]) + tm.assert_frame_equal(float_frame.head(1), float_frame[:1]) + tm.assert_frame_equal(float_frame.tail(1), float_frame[-1:]) + # with a float index + df = float_frame.copy() + df.index = np.arange(len(float_frame)) + 0.1 + tm.assert_frame_equal(df.head(), df.iloc[:5]) + tm.assert_frame_equal(df.tail(), df.iloc[-5:]) + tm.assert_frame_equal(df.head(0), df[0:0]) + tm.assert_frame_equal(df.tail(0), df[0:0]) + tm.assert_frame_equal(df.head(-1), df.iloc[:-1]) + tm.assert_frame_equal(df.tail(-1), df.iloc[1:]) + + +def test_head_tail_empty(): + # test empty dataframe + empty_df = pd.DataFrame() + tm.assert_frame_equal(empty_df.tail(), empty_df) + tm.assert_frame_equal(empty_df.head(), empty_df) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_infer_objects.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_infer_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..92a0b0d42ed60117697dc7077cd8026aec2354b9 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_infer_objects.py @@ -0,0 +1,42 @@ +from datetime import datetime + +import pandas as pd +import pandas._testing as tm + + +class TestInferObjects: + def test_infer_objects(self): + # GH#11221 + df = pd.DataFrame( + { + "a": ["a", 1, 2, 3], + "b": ["b", 2.0, 3.0, 4.1], + "c": [ + "c", + datetime(2016, 1, 1), + datetime(2016, 1, 2), + datetime(2016, 1, 3), + ], + "d": [1, 2, 3, "d"], + }, + columns=["a", "b", "c", "d"], + ) + df = df.iloc[1:].infer_objects() + + assert df["a"].dtype == "int64" + assert df["b"].dtype == "float64" + assert df["c"].dtype == "M8[us]" + assert df["d"].dtype == "object" + + expected = pd.DataFrame( + { + "a": [1, 2, 3], + "b": [2.0, 3.0, 4.1], + "c": [datetime(2016, 1, 1), datetime(2016, 1, 2), datetime(2016, 1, 3)], + "d": [2, 3, "d"], + }, + columns=["a", "b", "c", "d"], + ) + # reconstruct frame to verify inference is same + result = df.reset_index(drop=True) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_info.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_info.py new file mode 100644 index 0000000000000000000000000000000000000000..efe7bb9d77e133182d1ea9711f42905572b275f3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_info.py @@ -0,0 +1,619 @@ +from io import StringIO +import re +from string import ascii_uppercase +import sys +import textwrap + +import numpy as np +import pytest + +from pandas.compat import ( + HAS_PYARROW, + IS64, + PYPY, + is_platform_arm, +) + +import pandas as pd +import pandas._testing as tm +from pandas.util.version import Version + + +@pytest.fixture +def duplicate_columns_frame(): + """Dataframe with duplicate column names.""" + return pd.DataFrame( + np.random.default_rng(2).standard_normal((1500, 4)), + columns=["a", "a", "b", "b"], + ) + + +def test_info_empty(): + # GH #45494 + df = pd.DataFrame() + buf = StringIO() + df.info(buf=buf) + result = buf.getvalue() + expected = textwrap.dedent( + """\ + + RangeIndex: 0 entries + Empty DataFrame\n""" + ) + assert result == expected + + +def test_info_categorical_column_smoke_test(): + n = 2500 + df = pd.DataFrame( + {"int64": np.random.default_rng(2).integers(100, size=n, dtype=int)} + ) + df["category"] = pd.Series( + np.array(list("abcdefghij")).take( + np.random.default_rng(2).integers(0, 10, size=n, dtype=int) + ) + ).astype("category") + df.isna() + buf = StringIO() + df.info(buf=buf) + + df2 = df[df["category"] == "d"] + buf = StringIO() + df2.info(buf=buf) + + +@pytest.mark.parametrize( + "fixture_func_name", + [ + "int_frame", + "float_frame", + "datetime_frame", + "duplicate_columns_frame", + "float_string_frame", + ], +) +def test_info_smoke_test(fixture_func_name, request): + frame = request.getfixturevalue(fixture_func_name) + buf = StringIO() + frame.info(buf=buf) + result = buf.getvalue().splitlines() + assert len(result) > 10 + + buf = StringIO() + frame.info(buf=buf, verbose=False) + + +def test_info_smoke_test2(float_frame): + # pretty useless test, used to be mixed into the repr tests + buf = StringIO() + float_frame.reindex(columns=["A"]).info(verbose=False, buf=buf) + float_frame.reindex(columns=["A", "B"]).info(verbose=False, buf=buf) + + # no columns or index + pd.DataFrame().info(buf=buf) + + +@pytest.mark.parametrize( + "num_columns, max_info_columns, verbose", + [ + (10, 100, True), + (10, 11, True), + (10, 10, True), + (10, 9, False), + (10, 1, False), + ], +) +def test_info_default_verbose_selection(num_columns, max_info_columns, verbose): + frame = pd.DataFrame(np.random.default_rng(2).standard_normal((5, num_columns))) + with pd.option_context("display.max_info_columns", max_info_columns): + io_default = StringIO() + frame.info(buf=io_default) + result = io_default.getvalue() + + io_explicit = StringIO() + frame.info(buf=io_explicit, verbose=verbose) + expected = io_explicit.getvalue() + + assert result == expected + + +def test_info_verbose_check_header_separator_body(): + buf = StringIO() + size = 1001 + start = 5 + frame = pd.DataFrame(np.random.default_rng(2).standard_normal((3, size))) + frame.info(verbose=True, buf=buf) + + res = buf.getvalue() + header = " # Column Dtype \n--- ------ ----- " + assert header in res + + frame.info(verbose=True, buf=buf) + buf.seek(0) + lines = buf.readlines() + assert len(lines) > 0 + + for i, line in enumerate(lines): + if start <= i < start + size: + line_nr = f" {i - start} " + assert line.startswith(line_nr) + + +@pytest.mark.parametrize( + "size, header_exp, separator_exp, first_line_exp, last_line_exp", + [ + ( + 4, + " # Column Non-Null Count Dtype ", + "--- ------ -------------- ----- ", + " 0 0 3 non-null float64", + " 3 3 3 non-null float64", + ), + ( + 11, + " # Column Non-Null Count Dtype ", + "--- ------ -------------- ----- ", + " 0 0 3 non-null float64", + " 10 10 3 non-null float64", + ), + ( + 101, + " # Column Non-Null Count Dtype ", + "--- ------ -------------- ----- ", + " 0 0 3 non-null float64", + " 100 100 3 non-null float64", + ), + ( + 1001, + " # Column Non-Null Count Dtype ", + "--- ------ -------------- ----- ", + " 0 0 3 non-null float64", + " 1000 1000 3 non-null float64", + ), + ( + 10001, + " # Column Non-Null Count Dtype ", + "--- ------ -------------- ----- ", + " 0 0 3 non-null float64", + " 10000 10000 3 non-null float64", + ), + ], +) +def test_info_verbose_with_counts_spacing( + size, header_exp, separator_exp, first_line_exp, last_line_exp +): + """Test header column, spacer, first line and last line in verbose mode.""" + frame = pd.DataFrame(np.random.default_rng(2).standard_normal((3, size))) + with StringIO() as buf: + frame.info(verbose=True, show_counts=True, buf=buf) + all_lines = buf.getvalue().splitlines() + # Here table would contain only header, separator and table lines + # dframe repr, index summary, memory usage and dtypes are excluded + table = all_lines[3:-2] + header, separator, first_line, *rest, last_line = table + assert header == header_exp + assert separator == separator_exp + assert first_line == first_line_exp + assert last_line == last_line_exp + + +def test_info_memory(): + # https://github.com/pandas-dev/pandas/issues/21056 + df = pd.DataFrame({"a": pd.Series([1, 2], dtype="i8")}) + buf = StringIO() + df.info(buf=buf) + result = buf.getvalue() + bytes = float(df.memory_usage().sum()) + expected = textwrap.dedent( + f"""\ + + RangeIndex: 2 entries, 0 to 1 + Data columns (total 1 columns): + # Column Non-Null Count Dtype + --- ------ -------------- ----- + 0 a 2 non-null int64 + dtypes: int64(1) + memory usage: {bytes} bytes + """ + ) + assert result == expected + + +def test_info_wide(): + io = StringIO() + df = pd.DataFrame(np.random.default_rng(2).standard_normal((5, 101))) + df.info(buf=io) + + io = StringIO() + df.info(buf=io, max_cols=101) + result = io.getvalue() + assert len(result.splitlines()) > 100 + + expected = result + with pd.option_context("display.max_info_columns", 101): + io = StringIO() + df.info(buf=io) + result = io.getvalue() + assert result == expected + + +def test_info_duplicate_columns_shows_correct_dtypes(): + # GH11761 + io = StringIO() + frame = pd.DataFrame([[1, 2.0]], columns=["a", "a"]) + frame.info(buf=io) + lines = io.getvalue().splitlines(True) + assert " 0 a 1 non-null int64 \n" == lines[5] + assert " 1 a 1 non-null float64\n" == lines[6] + + +def test_info_shows_column_dtypes(): + dtypes = [ + "int64", + "float64", + "datetime64[ns]", + "timedelta64[ns]", + "complex128", + "object", + "bool", + ] + data = {} + n = 10 + for i, dtype in enumerate(dtypes): + data[i] = np.random.default_rng(2).integers(2, size=n).astype(dtype) + df = pd.DataFrame(data) + buf = StringIO() + df.info(buf=buf) + res = buf.getvalue() + header = ( + " # Column Non-Null Count Dtype \n" + "--- ------ -------------- ----- " + ) + assert header in res + for i, dtype in enumerate(dtypes): + name = f" {i:d} {i:d} {n:d} non-null {dtype}" + assert name in res + + +def test_info_max_cols(): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 5))) + for len_, verbose in [(5, None), (5, False), (12, True)]: + # For verbose always ^ setting ^ summarize ^ full output + with pd.option_context("max_info_columns", 4): + buf = StringIO() + df.info(buf=buf, verbose=verbose) + res = buf.getvalue() + assert len(res.strip().split("\n")) == len_ + + for len_, verbose in [(12, None), (5, False), (12, True)]: + # max_cols not exceeded + with pd.option_context("max_info_columns", 5): + buf = StringIO() + df.info(buf=buf, verbose=verbose) + res = buf.getvalue() + assert len(res.strip().split("\n")) == len_ + + for len_, max_cols in [(12, 5), (5, 4)]: + # setting truncates + with pd.option_context("max_info_columns", 4): + buf = StringIO() + df.info(buf=buf, max_cols=max_cols) + res = buf.getvalue() + assert len(res.strip().split("\n")) == len_ + + # setting wouldn't truncate + with pd.option_context("max_info_columns", 5): + buf = StringIO() + df.info(buf=buf, max_cols=max_cols) + res = buf.getvalue() + assert len(res.strip().split("\n")) == len_ + + +def test_info_memory_usage(): + # Ensure memory usage is displayed, when asserted, on the last line + dtypes = [ + "int64", + "float64", + "datetime64[ns]", + "timedelta64[ns]", + "complex128", + "object", + "bool", + ] + data = {} + n = 10 + for i, dtype in enumerate(dtypes): + data[i] = np.random.default_rng(2).integers(2, size=n).astype(dtype) + df = pd.DataFrame(data) + buf = StringIO() + + # display memory usage case + df.info(buf=buf, memory_usage=True) + res = buf.getvalue().splitlines() + assert "memory usage: " in res[-1] + + # do not display memory usage case + df.info(buf=buf, memory_usage=False) + res = buf.getvalue().splitlines() + assert "memory usage: " not in res[-1] + + df.info(buf=buf, memory_usage=True) + res = buf.getvalue().splitlines() + + # memory usage is a lower bound, so print it as XYZ+ MB + assert re.match(r"memory usage: [^+]+\+", res[-1]) + + df.iloc[:, :5].info(buf=buf, memory_usage=True) + res = buf.getvalue().splitlines() + + # excluded column with object dtype, so estimate is accurate + assert not re.match(r"memory usage: [^+]+\+", res[-1]) + + # Test a DataFrame with duplicate columns + dtypes = ["int64", "int64", "int64", "float64"] + data = {} + n = 100 + for i, dtype in enumerate(dtypes): + data[i] = np.random.default_rng(2).integers(2, size=n).astype(dtype) + df = pd.DataFrame(data) + df.columns = dtypes + + df_with_object_index = pd.DataFrame( + {"a": [1]}, index=pd.Index(["foo"], dtype=object) + ) + df_with_object_index.info(buf=buf, memory_usage=True) + res = buf.getvalue().splitlines() + assert re.match(r"memory usage: [^+]+\+", res[-1]) + + df_with_object_index.info(buf=buf, memory_usage="deep") + res = buf.getvalue().splitlines() + assert re.match(r"memory usage: [^+]+$", res[-1]) + + # Ensure df size is as expected + # (cols * rows * bytes) + index size + df_size = df.memory_usage().sum() + exp_size = len(dtypes) * n * 8 + df.index.nbytes + assert df_size == exp_size + + # Ensure number of cols in memory_usage is the same as df + size_df = np.size(df.columns.values) + 1 # index=True; default + assert size_df == np.size(df.memory_usage()) + + # assert deep works only on object + assert df.memory_usage().sum() == df.memory_usage(deep=True).sum() + + # test for validity + pd.DataFrame(1, index=["a"], columns=["A"]).memory_usage(index=True) + pd.DataFrame(1, index=["a"], columns=["A"]).index.nbytes + df = pd.DataFrame( + data=1, index=pd.MultiIndex.from_product([["a"], range(1000)]), columns=["A"] + ) + df.index.nbytes + df.memory_usage(index=True) + df.index.values.nbytes + + mem = df.memory_usage(deep=True).sum() + assert mem > 0 + + +@pytest.mark.skipif(PYPY, reason="on PyPy deep=True doesn't change result") +def test_info_memory_usage_deep_not_pypy(): + df_with_object_index = pd.DataFrame( + {"a": [1]}, index=pd.Index(["foo"], dtype=object) + ) + assert ( + df_with_object_index.memory_usage(index=True, deep=True).sum() + > df_with_object_index.memory_usage(index=True).sum() + ) + + df_object = pd.DataFrame({"a": pd.Series(["a"], dtype=object)}) + assert df_object.memory_usage(deep=True).sum() > df_object.memory_usage().sum() + + +@pytest.mark.xfail(not PYPY, reason="on PyPy deep=True does not change result") +def test_info_memory_usage_deep_pypy(): + df_with_object_index = pd.DataFrame( + {"a": [1]}, index=pd.Index(["foo"], dtype=object) + ) + assert ( + df_with_object_index.memory_usage(index=True, deep=True).sum() + == df_with_object_index.memory_usage(index=True).sum() + ) + + df_object = pd.DataFrame({"a": pd.Series(["a"], dtype=object)}) + assert df_object.memory_usage(deep=True).sum() == df_object.memory_usage().sum() + + +@pytest.mark.skipif(PYPY, reason="PyPy getsizeof() fails by design") +def test_usage_via_getsizeof(): + df = pd.DataFrame( + data=1, index=pd.MultiIndex.from_product([["a"], range(1000)]), columns=["A"] + ) + mem = df.memory_usage(deep=True).sum() + # sys.getsizeof will call the .memory_usage with + # deep=True, and add on some GC overhead + diff = mem - sys.getsizeof(df) + assert abs(diff) < 100 + + +def test_info_memory_usage_qualified(using_infer_string): + buf = StringIO() + df = pd.DataFrame(1, columns=list("ab"), index=[1, 2, 3]) + df.info(buf=buf) + assert "+" not in buf.getvalue() + + buf = StringIO() + df = pd.DataFrame(1, columns=list("ab"), index=pd.Index(list("ABC"), dtype=object)) + df.info(buf=buf) + assert "+" in buf.getvalue() + + buf = StringIO() + df = pd.DataFrame(1, columns=list("ab"), index=pd.Index(list("ABC"), dtype="str")) + df.info(buf=buf) + if using_infer_string and HAS_PYARROW: + assert "+" not in buf.getvalue() + else: + assert "+" in buf.getvalue() + + buf = StringIO() + df = pd.DataFrame( + 1, columns=list("ab"), index=pd.MultiIndex.from_product([range(3), range(3)]) + ) + df.info(buf=buf) + assert "+" not in buf.getvalue() + + buf = StringIO() + df = pd.DataFrame( + 1, + columns=list("ab"), + index=pd.MultiIndex.from_product([range(3), ["foo", "bar"]]), + ) + df.info(buf=buf) + if using_infer_string and HAS_PYARROW: + assert "+" not in buf.getvalue() + else: + assert "+" in buf.getvalue() + + +def test_info_memory_usage_bug_on_multiindex(): + # GH 14308 + # memory usage introspection should not materialize .values + + def memory_usage(f): + return f.memory_usage(deep=True).sum() + + N = 100 + M = len(ascii_uppercase) + index = pd.MultiIndex.from_product( + [list(ascii_uppercase), pd.date_range("20160101", periods=N)], + names=["id", "date"], + ) + df = pd.DataFrame( + {"value": np.random.default_rng(2).standard_normal(N * M)}, index=index + ) + + unstacked = df.unstack("id") + assert df.values.nbytes == unstacked.values.nbytes + assert memory_usage(df) > memory_usage(unstacked) + + # high upper bound + assert memory_usage(unstacked) - memory_usage(df) < 2000 + + +def test_info_categorical(): + # GH14298 + idx = pd.CategoricalIndex(["a", "b"]) + df = pd.DataFrame(np.zeros((2, 2)), index=idx, columns=idx) + + buf = StringIO() + df.info(buf=buf) + + +@pytest.mark.xfail(not IS64, reason="GH 36579: fail on 32-bit system") +def test_info_int_columns(using_infer_string): + # GH#37245 + df = pd.DataFrame({1: [1, 2], 2: [2, 3]}, index=["A", "B"]) + buf = StringIO() + df.info(show_counts=True, buf=buf) + result = buf.getvalue() + expected = textwrap.dedent( + f"""\ + + Index: 2 entries, A to B + Data columns (total 2 columns): + # Column Non-Null Count Dtype + --- ------ -------------- ----- + 0 1 2 non-null int64 + 1 2 2 non-null int64 + dtypes: int64(2) + memory usage: {"50.0" if using_infer_string and HAS_PYARROW else "48.0+"} bytes + """ + ) + assert result == expected + + +def test_memory_usage_empty_no_warning(using_infer_string): + # GH#50066 + df = pd.DataFrame(index=["a", "b"]) + with tm.assert_produces_warning(None): + result = df.memory_usage() + if using_infer_string and HAS_PYARROW: + value = 18 + else: + value = 16 if IS64 else 8 + expected = pd.Series(value, index=["Index"]) + tm.assert_series_equal(result, expected) + + +@pytest.mark.single_cpu +def test_info_compute_numba(): + # GH#51922 + numba = pytest.importorskip("numba") + if Version(numba.__version__) == Version("0.61") and is_platform_arm(): + pytest.skip(f"Segfaults on ARM platforms with numba {numba.__version__}") + df = pd.DataFrame([[1, 2], [3, 4]]) + + with pd.option_context("compute.use_numba", True): + buf = StringIO() + df.info(buf=buf) + result = buf.getvalue() + + buf = StringIO() + df.info(buf=buf) + expected = buf.getvalue() + assert result == expected + + +@pytest.mark.parametrize( + "row, columns, show_counts, result", + [ + [20, 20, None, True], + [20, 20, True, True], + [20, 20, False, False], + [5, 5, None, False], + [5, 5, True, False], + [5, 5, False, False], + ], +) +def test_info_show_counts(row, columns, show_counts, result): + # Explicit cast to float to avoid implicit cast when setting nan + df = pd.DataFrame(1, columns=range(10), index=range(10)).astype({1: "float"}) + df.iloc[1, 1] = np.nan + + with pd.option_context( + "display.max_info_rows", row, "display.max_info_columns", columns + ): + with StringIO() as buf: + df.info(buf=buf, show_counts=show_counts) + assert ("non-null" in buf.getvalue()) is result + + +def test_info_dtype_after_datetime_to_pydatetime(): + # GH#55136 + # After converting datetime64 column to python datetime objects, + # .info() should report dtype as object, not datetime64 + df = pd.DataFrame({"a": pd.to_datetime(["2023-01-01", "2023-01-02"])}) + df["a"] = df["a"].dt.to_pydatetime() + assert df["a"].dtype == np.dtype("object") + with StringIO() as buf: + df.info(buf=buf) + info_str = buf.getvalue() + assert "object" in info_str + assert "datetime64" not in info_str + + +def test_info_east_asian_width(): + # GH#46082 + df = pd.DataFrame({"열이름": [1], "列名": [2], "column": [3]}) + with pd.option_context("display.unicode.east_asian_width", True): + with StringIO() as buf: + df.info(buf=buf) + lines = buf.getvalue().splitlines() + expected = [ + " # Column Non-Null Count Dtype", + "--- ------ -------------- -----", + " 0 열이름 1 non-null int64", + " 1 列名 1 non-null int64", + " 2 column 1 non-null int64", + ] + assert lines[3:8] == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_interpolate.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_interpolate.py new file mode 100644 index 0000000000000000000000000000000000000000..e49b0d75d2c27a056a58fd02c8a691a3fa4c0ef3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_interpolate.py @@ -0,0 +1,492 @@ +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameInterpolate: + def test_interpolate_complex(self): + # GH#53635 + ser = pd.Series([complex("1+1j"), float("nan"), complex("2+2j")]) + assert ser.dtype.kind == "c" + + res = ser.interpolate() + expected = pd.Series([ser[0], ser[0] * 1.5, ser[2]]) + tm.assert_series_equal(res, expected) + + df = ser.to_frame() + res = df.interpolate() + expected = expected.to_frame() + tm.assert_frame_equal(res, expected) + + def test_interpolate_datetimelike_values(self, frame_or_series): + # GH#11312, GH#51005 + orig = pd.Series(pd.date_range("2012-01-01", periods=5)) + ser = orig.copy() + ser[2] = pd.NaT + + res = frame_or_series(ser).interpolate() + expected = frame_or_series(orig) + tm.assert_equal(res, expected) + + # datetime64tz cast + ser_tz = ser.dt.tz_localize("US/Pacific") + res_tz = frame_or_series(ser_tz).interpolate() + expected_tz = frame_or_series(orig.dt.tz_localize("US/Pacific")) + tm.assert_equal(res_tz, expected_tz) + + # timedelta64 cast + ser_td = ser - ser[0] + res_td = frame_or_series(ser_td).interpolate() + expected_td = frame_or_series(orig - orig[0]) + tm.assert_equal(res_td, expected_td) + + def test_interpolate_inplace(self, frame_or_series, request): + # GH#44749 + obj = frame_or_series([1, np.nan, 2]) + orig = obj.values + + result = obj.interpolate(inplace=True) + assert result is obj + expected = frame_or_series([1, 1.5, 2]) + tm.assert_equal(obj, expected) + + # check we operated *actually* inplace + assert np.shares_memory(orig, obj.values) + assert orig.squeeze()[1] == 1.5 + + @pytest.mark.parametrize("dtype", ["str", "object"]) + def test_interp_with_non_numeric(self, dtype, using_infer_string): + if not using_infer_string: + dtype = "object" + df = pd.DataFrame( + { + "A": [1, 2, np.nan, 4], + "B": [1, 4, 9, np.nan], + "C": [1, 2, 3, 5], + "D": list("abcd"), + } + ) + df["D"] = df["D"].astype(dtype) + df_orig = df.copy() + expected = pd.DataFrame( + { + "A": [1.0, 2.0, 3.0, 4.0], + "B": [1.0, 4.0, 9.0, 9.0], + "C": [1, 2, 3, 5], + "D": list("abcd"), + } + ) + expected["D"] = expected["D"].astype(dtype) + + # the EA path (str dtype) and the object-block path word the error + # differently; pin each to its dtype rather than hedging the case + if dtype == "object": + msg = "cannot interpolate with object dtype" + else: + msg = f"Cannot interpolate with {dtype} dtype" + with pytest.raises(TypeError, match=msg): + df.interpolate() + tm.assert_frame_equal(df, df_orig) + + with pytest.raises(TypeError, match=msg): + df.interpolate(inplace=True) + # columns A and B already get interpolated before we hit the error + tm.assert_frame_equal(df, expected) + + def test_interp_basic(self): + df = pd.DataFrame( + { + "A": [1, 2, np.nan, 4], + "B": [1, 4, 9, np.nan], + "C": [1, 2, 3, 5], + } + ) + df_orig = df.copy() + expected = pd.DataFrame( + { + "A": [1.0, 2.0, 3.0, 4.0], + "B": [1.0, 4.0, 9.0, 9.0], + "C": [1, 2, 3, 5], + } + ) + result = df.interpolate() + tm.assert_frame_equal(result, expected) + + # check we didn't operate inplace GH#45791 + tm.assert_frame_equal(df, df_orig) + bvalues = df["B"]._values + cvalues = df["C"]._values + assert not tm.shares_memory(bvalues, result["B"]._values) + assert tm.shares_memory(cvalues, result["C"]._values) + + res = df.interpolate(inplace=True) + assert res is df + tm.assert_frame_equal(df, expected) + + # check we DID operate inplace + assert tm.shares_memory(df["B"]._values, bvalues) + assert tm.shares_memory(df["C"]._values, cvalues) + + def test_interp_basic_with_non_range_index(self): + df = pd.DataFrame( + { + "A": [1, 2, np.nan, 4], + "B": [1, 4, 9, np.nan], + "C": [1, 2, 3, 5], + } + ) + result = df.set_index("C").interpolate() + expected = df.set_index("C") + expected.loc[3, "A"] = 3 + expected.loc[5, "B"] = 9 + tm.assert_frame_equal(result, expected) + + def test_interp_empty(self): + # https://github.com/pandas-dev/pandas/issues/35598 + df = pd.DataFrame() + result = df.interpolate() + assert result is not df + expected = df + tm.assert_frame_equal(result, expected) + + def test_interp_bad_method(self): + df = pd.DataFrame( + { + "A": [1, 2, np.nan, 4], + "B": [1, 4, 9, np.nan], + "C": [1, 2, 3, 5], + } + ) + msg = "Can not interpolate with method=not_a_method" + with pytest.raises(ValueError, match=msg): + df.interpolate(method="not_a_method") + + def test_interp_combo(self): + df = pd.DataFrame( + { + "A": [1.0, 2.0, np.nan, 4.0], + "B": [1, 4, 9, np.nan], + "C": [1, 2, 3, 5], + "D": list("abcd"), + } + ) + + result = df["A"].interpolate() + expected = pd.Series([1.0, 2.0, 3.0, 4.0], name="A") + tm.assert_series_equal(result, expected) + + def test_interp_nan_idx(self): + df = pd.DataFrame({"A": [1, 2, np.nan, 4], "B": [np.nan, 2, 3, 4]}) + df = df.set_index("A") + msg = ( + "Interpolation with NaNs in the index has not been implemented. " + "Try filling those NaNs before interpolating." + ) + with pytest.raises(NotImplementedError, match=msg): + df.interpolate(method="values") + + def test_interp_various(self): + pytest.importorskip("scipy") + df = pd.DataFrame( + {"A": [1, 2, np.nan, 4, 5, np.nan, 7], "C": [1, 2, 3, 5, 8, 13, 21]} + ) + df = df.set_index("C") + expected = df.copy() + result = df.interpolate(method="polynomial", order=1) + + expected.loc[3, "A"] = 2.66666667 + expected.loc[13, "A"] = 5.76923076 + tm.assert_frame_equal(result, expected) + + result = df.interpolate(method="cubic") + # GH #15662. + expected.loc[3, "A"] = 2.81547781 + expected.loc[13, "A"] = 5.52964175 + tm.assert_frame_equal(result, expected) + + result = df.interpolate(method="nearest") + expected.loc[3, "A"] = 2 + expected.loc[13, "A"] = 5 + tm.assert_frame_equal(result, expected, check_dtype=False) + + result = df.interpolate(method="quadratic") + expected.loc[3, "A"] = 2.82150771 + expected.loc[13, "A"] = 6.12648668 + tm.assert_frame_equal(result, expected) + + result = df.interpolate(method="slinear") + expected.loc[3, "A"] = 2.66666667 + expected.loc[13, "A"] = 5.76923077 + tm.assert_frame_equal(result, expected) + + result = df.interpolate(method="zero") + expected.loc[3, "A"] = 2.0 + expected.loc[13, "A"] = 5 + tm.assert_frame_equal(result, expected, check_dtype=False) + + def test_interp_alt_scipy(self): + pytest.importorskip("scipy") + df = pd.DataFrame( + {"A": [1, 2, np.nan, 4, 5, np.nan, 7], "C": [1, 2, 3, 5, 8, 13, 21]} + ) + result = df.interpolate(method="barycentric") + expected = df.copy() + expected.loc[2, "A"] = 3 + expected.loc[5, "A"] = 6 + tm.assert_frame_equal(result, expected) + + result = df.interpolate(method="krogh") + expectedk = df.copy() + expectedk["A"] = expected["A"] + tm.assert_frame_equal(result, expectedk) + + result = df.interpolate(method="pchip") + expected.loc[2, "A"] = 3 + expected.loc[5, "A"] = 6.0 + + tm.assert_frame_equal(result, expected) + + def test_interp_rowwise(self): + df = pd.DataFrame( + { + 0: [1, 2, np.nan, 4], + 1: [2, 3, 4, np.nan], + 2: [np.nan, 4, 5, 6], + 3: [4, np.nan, 6, 7], + 4: [1, 2, 3, 4], + } + ) + result = df.interpolate(axis=1) + expected = df.copy() + expected.loc[3, 1] = 5 + expected.loc[0, 2] = 3 + expected.loc[1, 3] = 3 + expected[4] = expected[4].astype(np.float64) + tm.assert_frame_equal(result, expected) + + result = df.interpolate(axis=1, method="values") + tm.assert_frame_equal(result, expected) + + result = df.interpolate(axis=0) + expected = df.interpolate() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "axis_name, axis_number", + [ + pytest.param("rows", 0, id="rows_0"), + pytest.param("index", 0, id="index_0"), + pytest.param("columns", 1, id="columns_1"), + ], + ) + def test_interp_axis_names(self, axis_name, axis_number): + # GH 29132: test axis names + data = {0: [0, np.nan, 6], 1: [1, np.nan, 7], 2: [2, 5, 8]} + + df = pd.DataFrame(data, dtype=np.float64) + result = df.interpolate(axis=axis_name, method="linear") + expected = df.interpolate(axis=axis_number, method="linear") + tm.assert_frame_equal(result, expected) + + def test_rowwise_alt(self): + df = pd.DataFrame( + { + 0: [0, 0.5, 1.0, np.nan, 4, 8, np.nan, np.nan, 64], + 1: [1, 2, 3, 4, 3, 2, 1, 0, -1], + } + ) + df.interpolate(axis=0) + # TODO: assert something? + + @pytest.mark.parametrize( + "check_scipy", [False, pytest.param(True, marks=td.skip_if_no("scipy"))] + ) + def test_interp_leading_nans(self, check_scipy): + df = pd.DataFrame( + {"A": [np.nan, np.nan, 0.5, 0.25, 0], "B": [np.nan, -3, -3.5, np.nan, -4]} + ) + result = df.interpolate() + expected = df.copy() + expected.loc[3, "B"] = -3.75 + tm.assert_frame_equal(result, expected) + + if check_scipy: + result = df.interpolate(method="polynomial", order=1) + tm.assert_frame_equal(result, expected) + + def test_interp_raise_on_only_mixed(self, axis): + df = pd.DataFrame( + { + "A": [1, 2, np.nan, 4], + "B": ["a", "b", "c", "d"], + "C": [np.nan, 2, 5, 7], + "D": [np.nan, np.nan, 9, 9], + "E": [1, 2, 3, 4], + } + ) + msg = "DataFrame cannot interpolate with object dtype" + with pytest.raises(TypeError, match=msg): + df.astype("object").interpolate(axis=axis) + + def test_interp_raise_on_all_object_dtype(self): + # GH 22985 + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, dtype="object") + msg = "DataFrame cannot interpolate with object dtype" + with pytest.raises(TypeError, match=msg): + df.interpolate() + + def test_interp_inplace(self): + df = pd.DataFrame({"a": [1.0, 2.0, np.nan, 4.0]}) + df_orig = df.copy() + expected = df.copy().interpolate() + + with tm.raises_chained_assignment_error(): + result = df["a"].interpolate(inplace=True) + tm.assert_series_equal(result, expected["a"]) + tm.assert_frame_equal(df, df_orig) + + def test_interp_inplace_row(self): + # GH 10395 + df = pd.DataFrame( + {"a": [1.0, 2.0, 3.0, 4.0], "b": [np.nan, 2.0, 3.0, 4.0], "c": [3, 2, 2, 2]} + ) + expected = df.interpolate(method="linear", axis=1, inplace=False) + result = df.interpolate(method="linear", axis=1, inplace=True) + assert result is df + tm.assert_frame_equal(result, expected) + + def test_interp_ignore_all_good(self): + # GH#6290 + df = pd.DataFrame( + { + "A": [1, 2, np.nan, 4], + "B": [1, 2, 3, 4], + "C": [1.0, 2.0, np.nan, 4.0], + "D": [1.0, 2.0, 3.0, 4.0], + } + ) + expected = pd.DataFrame( + { + "A": np.array([1, 2, 3, 4], dtype="float64"), + "B": np.array([1, 2, 3, 4], dtype="int64"), + "C": np.array([1.0, 2.0, 3, 4.0], dtype="float64"), + "D": np.array([1.0, 2.0, 3.0, 4.0], dtype="float64"), + } + ) + result = df.interpolate() + tm.assert_frame_equal(result, expected) + + # all good + result = df[["B", "D"]].interpolate() + tm.assert_frame_equal(result, df[["B", "D"]]) + + def test_interp_time_inplace_axis(self): + # GH 9687 + periods = 5 + idx = pd.date_range(start="2014-01-01", periods=periods) + data = np.random.default_rng(2).random((periods, periods)) + data[data < 0.5] = np.nan + df = pd.DataFrame(index=idx, columns=idx, data=data) + + expected = df.interpolate(axis=0, method="time") + result = df.interpolate(axis=0, method="time", inplace=True) + assert result is df + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("axis_name, axis_number", [("index", 0), ("columns", 1)]) + def test_interp_string_axis(self, axis_name, axis_number): + # https://github.com/pandas-dev/pandas/issues/25190 + x = np.linspace(0, 100, 3) + y = np.sin(x) + df = pd.DataFrame( + data=np.tile(y, (10, 1)), index=np.arange(10), columns=x + ).reindex(columns=x * 1.005) + result = df.interpolate(method="linear", axis=axis_name) + expected = df.interpolate(method="linear", axis=axis_number) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("multiblock", [True, False]) + @pytest.mark.parametrize("method", ["ffill", "bfill", "pad"]) + def test_interp_fillna_methods(self, axis, multiblock, method): + # GH 12918 + df = pd.DataFrame( + { + "A": [1.0, 2.0, 3.0, 4.0, np.nan, 5.0], + "B": [2.0, 4.0, 6.0, np.nan, 8.0, 10.0], + "C": [3.0, 6.0, 9.0, np.nan, np.nan, 30.0], + } + ) + if multiblock: + df["D"] = np.nan + df["E"] = 1.0 + + msg = f"Can not interpolate with method={method}" + with pytest.raises(ValueError, match=msg): + df.interpolate(method=method, axis=axis) + + def test_interpolate_empty_df(self): + # GH#53199 + df = pd.DataFrame() + expected = df.copy() + result = df.interpolate(inplace=True) + assert result is df + tm.assert_frame_equal(result, expected) + + def test_interpolate_ea(self, any_int_ea_dtype): + # GH#55347 + df = pd.DataFrame({"a": [1, None, None, None, 3]}, dtype=any_int_ea_dtype) + orig = df.copy() + result = df.interpolate(limit=2) + expected = pd.DataFrame({"a": [1, 1.5, 2.0, None, 3]}, dtype="Float64") + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, orig) + + @pytest.mark.parametrize( + "dtype", + [ + "Float64", + "Float32", + pytest.param("float32[pyarrow]", marks=td.skip_if_no("pyarrow")), + pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow")), + ], + ) + def test_interpolate_ea_float(self, dtype): + # GH#55347 + df = pd.DataFrame({"a": [1, None, None, None, 3]}, dtype=dtype) + orig = df.copy() + result = df.interpolate(limit=2) + expected = pd.DataFrame({"a": [1, 1.5, 2.0, None, 3]}, dtype=dtype) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, orig) + + @pytest.mark.parametrize( + "dtype", + ["int64", "uint64", "int32", "int16", "int8", "uint32", "uint16", "uint8"], + ) + def test_interpolate_arrow(self, dtype): + # GH#55347 + pytest.importorskip("pyarrow") + df = pd.DataFrame({"a": [1, None, None, None, 3]}, dtype=dtype + "[pyarrow]") + result = df.interpolate(limit=2) + expected = pd.DataFrame({"a": [1, 1.5, 2.0, None, 3]}, dtype="float64[pyarrow]") + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "dtype", + [ + "Int64", + "Float64", + ], + ) + def test_interpolate_time_nullable_int_float(self, dtype): + # GH#40252 + idx = pd.date_range("1970-01-02", periods=3, freq="D") + + df = pd.DataFrame({"a": [1, None, 2]}, index=idx, dtype=dtype) + result = df.interpolate(method="time") + expected = pd.DataFrame({"a": [1.0, 1.5, 2.0]}, index=idx, dtype="Float64") + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_is_homogeneous_dtype.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_is_homogeneous_dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2cf12ff123d3289164d0a653329e2308d2721f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_is_homogeneous_dtype.py @@ -0,0 +1,54 @@ +import numpy as np +import pytest + +import pandas as pd + + +@pytest.mark.parametrize( + "data, expected", + [ + # empty + (pd.DataFrame(), True), + # multi-same + (pd.DataFrame({"A": [1, 2], "B": [1, 2]}), True), + # multi-object + ( + pd.DataFrame( + { + "A": np.array([1, 2], dtype=object), + "B": np.array(["a", "b"], dtype=object), + }, + dtype="object", + ), + True, + ), + # multi-extension + ( + pd.DataFrame( + {"A": pd.Categorical(["a", "b"]), "B": pd.Categorical(["a", "b"])} + ), + True, + ), + # differ types + (pd.DataFrame({"A": [1, 2], "B": [1.0, 2.0]}), False), + # differ sizes + ( + pd.DataFrame( + { + "A": np.array([1, 2], dtype=np.int32), + "B": np.array([1, 2], dtype=np.int64), + } + ), + False, + ), + # multi-extension differ + ( + pd.DataFrame( + {"A": pd.Categorical(["a", "b"]), "B": pd.Categorical(["b", "c"])} + ), + False, + ), + ], +) +def test_is_homogeneous_type(data, expected): + assert data._is_homogeneous_type is expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_isetitem.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_isetitem.py new file mode 100644 index 0000000000000000000000000000000000000000..8f7e7b221e492be4d449e843cbb6298abae4974f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_isetitem.py @@ -0,0 +1,64 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameSetItem: + def test_isetitem_ea_df(self): + # GH#49922 + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]]) + rhs = pd.DataFrame([[11, 12], [13, 14]], dtype="Int64") + + df.isetitem([0, 1], rhs) + expected = pd.DataFrame( + { + 0: pd.Series([11, 13], dtype="Int64"), + 1: pd.Series([12, 14], dtype="Int64"), + 2: [3, 6], + } + ) + tm.assert_frame_equal(df, expected) + + def test_isetitem_ea_df_scalar_indexer(self): + # GH#49922 + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]]) + rhs = pd.DataFrame([[11], [13]], dtype="Int64") + + df.isetitem(2, rhs) + expected = pd.DataFrame( + { + 0: [1, 4], + 1: [2, 5], + 2: pd.Series([11, 13], dtype="Int64"), + } + ) + tm.assert_frame_equal(df, expected) + + def test_isetitem_dimension_mismatch(self): + # GH#51701 + df = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}) + value = df.copy() + with pytest.raises(ValueError, match="Got 2 positions but value has 3 columns"): + df.isetitem([1, 2], value) + + value = df.copy() + with pytest.raises(ValueError, match="Got 2 positions but value has 1 columns"): + df.isetitem([1, 2], value[["a"]]) + + @pytest.mark.parametrize("loc", [[1, 0], [2, 0, 1], [3, 1, 0]]) + def test_isetitem_unsorted_loc(self, loc): + # GH#68930 Block.delete assumes increasing locs, so an out-of-order loc + # that replaces only part of a block used to leave stale blocks behind + df = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6], "d": [7, 8]}) + value = np.arange(100, 100 + 2 * len(loc)).reshape(len(loc), 2).T + + df.isetitem(loc, value) + + expected = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6], "d": [7, 8]}) + for i, pos in enumerate(loc): + expected.isetitem(pos, value[:, i]) + tm.assert_frame_equal(df, expected) + # values read back fine even when corrupt; this is what fails on revert + df.describe() diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_isin.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_isin.py new file mode 100644 index 0000000000000000000000000000000000000000..626ac0237ad4a56c285e393facdf7d099a1decbd --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_isin.py @@ -0,0 +1,222 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameIsIn: + def test_isin(self): + # GH#4211 + df = pd.DataFrame( + { + "vals": [1, 2, 3, 4], + "ids": ["a", "b", "f", "n"], + "ids2": ["a", "n", "c", "n"], + }, + index=["foo", "bar", "baz", "qux"], + ) + other = ["a", "b", "c"] + + result = df.isin(other) + expected = pd.DataFrame([df.loc[s].isin(other) for s in df.index]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("empty", [[], pd.Series(dtype=object), np.array([])]) + def test_isin_empty(self, empty): + # GH#16991 + df = pd.DataFrame({"A": ["a", "b", "c"], "B": ["a", "e", "f"]}) + expected = pd.DataFrame(False, df.index, df.columns) + + result = df.isin(empty) + tm.assert_frame_equal(result, expected) + + def test_isin_dict(self): + df = pd.DataFrame({"A": ["a", "b", "c"], "B": ["a", "e", "f"]}) + d = {"A": ["a"]} + + expected = pd.DataFrame(False, df.index, df.columns) + expected.loc[0, "A"] = True + + result = df.isin(d) + tm.assert_frame_equal(result, expected) + + # non unique columns + df = pd.DataFrame({"A": ["a", "b", "c"], "B": ["a", "e", "f"]}) + df.columns = ["A", "A"] + expected = pd.DataFrame(False, df.index, df.columns) + expected.loc[0, "A"] = True + result = df.isin(d) + tm.assert_frame_equal(result, expected) + + def test_isin_with_string_scalar(self): + # GH#4763 + df = pd.DataFrame( + { + "vals": [1, 2, 3, 4], + "ids": ["a", "b", "f", "n"], + "ids2": ["a", "n", "c", "n"], + }, + index=["foo", "bar", "baz", "qux"], + ) + msg = ( + r"only list-like or dict-like objects are allowed " + r"to be passed to DataFrame.isin\(\), you passed a 'str'" + ) + with pytest.raises(TypeError, match=msg): + df.isin("a") + + with pytest.raises(TypeError, match=msg): + df.isin("aaa") + + def test_isin_df(self): + df1 = pd.DataFrame({"A": [1, 2, 3, 4], "B": [2, np.nan, 4, 4]}) + df2 = pd.DataFrame({"A": [0, 2, 12, 4], "B": [2, np.nan, 4, 5]}) + expected = pd.DataFrame(False, df1.index, df1.columns) + result = df1.isin(df2) + expected.loc[[1, 3], "A"] = True + expected.loc[[0, 2], "B"] = True + tm.assert_frame_equal(result, expected) + + # partial overlapping columns + df2.columns = ["A", "C"] + result = df1.isin(df2) + expected["B"] = False + tm.assert_frame_equal(result, expected) + + def test_isin_tuples(self): + # GH#16394 + df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "f"]}) + df["C"] = list(zip(df["A"], df["B"], strict=True)) + result = df["C"].isin([(1, "a")]) + tm.assert_series_equal(result, pd.Series([True, False, False], name="C")) + + def test_isin_df_dupe_values(self): + df1 = pd.DataFrame({"A": [1, 2, 3, 4], "B": [2, np.nan, 4, 4]}) + # just cols duped + df2 = pd.DataFrame([[0, 2], [12, 4], [2, np.nan], [4, 5]], columns=["B", "B"]) + msg = r"cannot compute isin with a duplicate axis\." + with pytest.raises(ValueError, match=msg): + df1.isin(df2) + + # just index duped + df2 = pd.DataFrame( + [[0, 2], [12, 4], [2, np.nan], [4, 5]], + columns=["A", "B"], + index=[0, 0, 1, 1], + ) + with pytest.raises(ValueError, match=msg): + df1.isin(df2) + + # cols and index: + df2.columns = ["B", "B"] + with pytest.raises(ValueError, match=msg): + df1.isin(df2) + + def test_isin_dupe_self(self): + other = pd.DataFrame({"A": [1, 0, 1, 0], "B": [1, 1, 0, 0]}) + df = pd.DataFrame([[1, 1], [1, 0], [0, 0]], columns=["A", "A"]) + result = df.isin(other) + expected = pd.DataFrame(False, index=df.index, columns=df.columns) + expected.loc[0] = True + expected.iloc[1, 1] = True + tm.assert_frame_equal(result, expected) + + def test_isin_against_series(self): + df = pd.DataFrame( + {"A": [1, 2, 3, 4], "B": [2, np.nan, 4, 4]}, index=["a", "b", "c", "d"] + ) + s = pd.Series([1, 3, 11, 4], index=["a", "b", "c", "d"]) + expected = pd.DataFrame(False, index=df.index, columns=df.columns) + expected.loc["a", "A"] = True + expected.loc["d"] = True + result = df.isin(s) + tm.assert_frame_equal(result, expected) + + def test_isin_multiIndex(self): + idx = pd.MultiIndex.from_tuples( + [ + (0, "a", "foo"), + (0, "a", "bar"), + (0, "b", "bar"), + (0, "b", "baz"), + (2, "a", "foo"), + (2, "a", "bar"), + (2, "c", "bar"), + (2, "c", "baz"), + (1, "b", "foo"), + (1, "b", "bar"), + (1, "c", "bar"), + (1, "c", "baz"), + ] + ) + df1 = pd.DataFrame({"A": np.ones(12), "B": np.zeros(12)}, index=idx) + df2 = pd.DataFrame( + { + "A": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], + "B": [1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1], + } + ) + # against regular index + expected = pd.DataFrame(False, index=df1.index, columns=df1.columns) + result = df1.isin(df2) + tm.assert_frame_equal(result, expected) + + df2.index = idx + expected = df2.values.astype(bool) + expected[:, 1] = ~expected[:, 1] + expected = pd.DataFrame(expected, columns=["A", "B"], index=idx) + + result = df1.isin(df2) + tm.assert_frame_equal(result, expected) + + def test_isin_empty_datetimelike(self): + # GH#15473 + df1_ts = pd.DataFrame({"date": pd.to_datetime(["2014-01-01", "2014-01-02"])}) + df1_td = pd.DataFrame({"date": [pd.Timedelta(1, "s"), pd.Timedelta(2, "s")]}) + df2 = pd.DataFrame({"date": []}) + df3 = pd.DataFrame() + + expected = pd.DataFrame({"date": [False, False]}) + + result = df1_ts.isin(df2) + tm.assert_frame_equal(result, expected) + result = df1_ts.isin(df3) + tm.assert_frame_equal(result, expected) + + result = df1_td.isin(df2) + tm.assert_frame_equal(result, expected) + result = df1_td.isin(df3) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "values", + [ + pd.DataFrame({"a": [1, 2, 3]}, dtype="category"), + pd.Series([1, 2, 3], dtype="category"), + ], + ) + def test_isin_category_frame(self, values): + # GH#34256 + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + expected = pd.DataFrame({"a": [True, True, True], "b": [False, False, False]}) + + result = df.isin(values) + tm.assert_frame_equal(result, expected) + + def test_isin_read_only(self): + # https://github.com/pandas-dev/pandas/issues/37174 + arr = np.array([1, 2, 3]) + arr.setflags(write=False) + df = pd.DataFrame([1, 2, 3]) + result = df.isin(arr) + expected = pd.DataFrame([True, True, True]) + tm.assert_frame_equal(result, expected) + + def test_isin_not_lossy(self): + # GH 53514 + val = 1666880195890293744 + df = pd.DataFrame({"a": [val], "b": [1.0]}) + result = df.isin([val]) + expected = pd.DataFrame({"a": [True], "b": [False]}) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_iterrows.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_iterrows.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1be2c888738bc0accd43f7c1c3bdb274303acf --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_iterrows.py @@ -0,0 +1,13 @@ +import pandas as pd + + +def test_no_overflow_of_freq_and_time_in_dataframe(): + # GH 35665 + df = pd.DataFrame( + { + "some_string": ["2222Y3"], + "time": [pd.Timedelta("0 days 00:00:00.990000")], + } + ) + for _, row in df.iterrows(): + assert row.dtype == "object" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_join.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..ac6862e5024d6db0d200fa2e14cdfb65e93d7080 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_join.py @@ -0,0 +1,599 @@ +from datetime import datetime +import re +import zoneinfo + +import numpy as np +import pytest + +from pandas.errors import MergeError + +import pandas as pd +import pandas._testing as tm +from pandas.core.reshape.concat import concat + + +@pytest.fixture +def left_no_dup(): + return pd.DataFrame( + {"a": ["a", "b", "c", "d"], "b": ["cat", "dog", "weasel", "horse"]}, + index=range(4), + ) + + +@pytest.fixture +def right_no_dup(): + return pd.DataFrame( + { + "a": ["a", "b", "c", "d", "e"], + "c": ["meow", "bark", "um... weasel noise?", "nay", "chirp"], + }, + index=range(5), + ).set_index("a") + + +@pytest.fixture +def left_w_dups(left_no_dup): + return concat( + [left_no_dup, pd.DataFrame({"a": ["a"], "b": ["cow"]}, index=[3])], sort=True + ) + + +@pytest.fixture +def right_w_dups(right_no_dup): + return concat( + [right_no_dup, pd.DataFrame({"a": ["e"], "c": ["moo"]}, index=[3])] + ).set_index("a") + + +@pytest.mark.parametrize( + "how, sort, expected", + [ + ("inner", False, pd.DataFrame({"a": [20, 10], "b": [200, 100]}, index=[2, 1])), + ("inner", True, pd.DataFrame({"a": [10, 20], "b": [100, 200]}, index=[1, 2])), + ( + "left", + False, + pd.DataFrame({"a": [20, 10, 0], "b": [200, 100, np.nan]}, index=[2, 1, 0]), + ), + ( + "left", + True, + pd.DataFrame({"a": [0, 10, 20], "b": [np.nan, 100, 200]}, index=[0, 1, 2]), + ), + ( + "right", + False, + pd.DataFrame( + {"a": [np.nan, 10, 20], "b": [300, 100, 200]}, index=[3, 1, 2] + ), + ), + ( + "right", + True, + pd.DataFrame( + {"a": [10, 20, np.nan], "b": [100, 200, 300]}, index=[1, 2, 3] + ), + ), + ( + "outer", + False, + pd.DataFrame( + {"a": [0, 10, 20, np.nan], "b": [np.nan, 100, 200, 300]}, + index=[0, 1, 2, 3], + ), + ), + ( + "outer", + True, + pd.DataFrame( + {"a": [0, 10, 20, np.nan], "b": [np.nan, 100, 200, 300]}, + index=[0, 1, 2, 3], + ), + ), + ], +) +def test_join(how, sort, expected): + left = pd.DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0]) + right = pd.DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2]) + result = left.join(right, how=how, sort=sort, validate="1:1") + tm.assert_frame_equal(result, expected) + + +def test_suffix_on_list_join(): + first = pd.DataFrame({"key": [1, 2, 3, 4, 5]}) + second = pd.DataFrame({"key": [1, 8, 3, 2, 5], "v1": [1, 2, 3, 4, 5]}) + third = pd.DataFrame({"keys": [5, 2, 3, 4, 1], "v2": [1, 2, 3, 4, 5]}) + + # check proper errors are raised + msg = "Suffixes not supported when joining multiple DataFrames" + with pytest.raises(ValueError, match=msg): + first.join([second], suffixes=("y", "")) + with pytest.raises(ValueError, match=msg): + first.join([second, third], suffixes=("", "x")) + with pytest.raises(ValueError, match=msg): + first.join([second, third], suffixes=("y", "x")) + with pytest.raises(ValueError, match="Indexes have overlapping values"): + first.join([second, third]) + + # no errors should be raised + arr_joined = first.join([third]) + norm_joined = first.join(third) + tm.assert_frame_equal(arr_joined, norm_joined) + + +def test_join_lsuffix_rsuffix_deprecated(): + # GH#46046, GH#22231 + df1 = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + df2 = pd.DataFrame({"b": [5, 6], "c": [7, 8]}) + + msg = "The 'lsuffix' and 'rsuffix' keywords in DataFrame.join are deprecated" + with tm.assert_produces_warning(pd.errors.Pandas4Warning, match=msg): + result = df1.join(df2, lsuffix="_left", rsuffix="_right") + expected = df1.join(df2, suffixes=("_left", "_right")) + tm.assert_frame_equal(result, expected) + + # only lsuffix + with tm.assert_produces_warning(pd.errors.Pandas4Warning, match=msg): + result = df1.join(df2, lsuffix="_left") + expected = df1.join(df2, suffixes=("_left", "")) + tm.assert_frame_equal(result, expected) + + # Cannot specify both + with pytest.raises(ValueError, match="Cannot specify both"): + df1.join(df2, lsuffix="_left", suffixes=("_left", "_right")) + + +def test_join_invalid_validate(left_no_dup, right_no_dup): + # GH 46622 + # Check invalid arguments + msg = ( + '"invalid" is not a valid argument. ' + "Valid arguments are:\n" + '- "1:1"\n' + '- "1:m"\n' + '- "m:1"\n' + '- "m:m"\n' + '- "one_to_one"\n' + '- "one_to_many"\n' + '- "many_to_one"\n' + '- "many_to_many"' + ) + with pytest.raises(ValueError, match=msg): + left_no_dup.merge(right_no_dup, on="a", validate="invalid") + + +@pytest.mark.parametrize("dtype", ["object", "string[pyarrow]"]) +def test_join_on_single_col_dup_on_right(left_no_dup, right_w_dups, dtype): + # GH 46622 + # Dups on right allowed by one_to_many constraint + if dtype == "string[pyarrow]": + pytest.importorskip("pyarrow") + left_no_dup = left_no_dup.astype(dtype) + right_w_dups.index = right_w_dups.index.astype(dtype) + left_no_dup.join( + right_w_dups, + on="a", + validate="one_to_many", + ) + + # Dups on right not allowed by one_to_one constraint + msg = "Merge keys are not unique in right dataset; not a one-to-one merge" + with pytest.raises(MergeError, match=msg): + left_no_dup.join( + right_w_dups, + on="a", + validate="one_to_one", + ) + + +def test_join_on_single_col_dup_on_left(left_w_dups, right_no_dup): + # GH 46622 + # Dups on left allowed by many_to_one constraint + left_w_dups.join( + right_no_dup, + on="a", + validate="many_to_one", + ) + + # Dups on left not allowed by one_to_one constraint + msg = "Merge keys are not unique in left dataset; not a one-to-one merge" + with pytest.raises(MergeError, match=msg): + left_w_dups.join( + right_no_dup, + on="a", + validate="one_to_one", + ) + + +def test_join_on_single_col_dup_on_both(left_w_dups, right_w_dups): + # GH 46622 + # Dups on both allowed by many_to_many constraint + left_w_dups.join(right_w_dups, on="a", validate="many_to_many") + + # Dups on both not allowed by many_to_one constraint + msg = "Merge keys are not unique in right dataset; not a many-to-one merge" + with pytest.raises(MergeError, match=msg): + left_w_dups.join( + right_w_dups, + on="a", + validate="many_to_one", + ) + + # Dups on both not allowed by one_to_many constraint + msg = "Merge keys are not unique in left dataset; not a one-to-many merge" + with pytest.raises(MergeError, match=msg): + left_w_dups.join( + right_w_dups, + on="a", + validate="one_to_many", + ) + + +def test_join_on_multi_col_check_dup(): + # GH 46622 + # Two column join, dups in both, but jointly no dups + left = pd.DataFrame( + { + "a": ["a", "a", "b", "b"], + "b": [0, 1, 0, 1], + "c": ["cat", "dog", "weasel", "horse"], + }, + index=range(4), + ).set_index(["a", "b"]) + + right = pd.DataFrame( + { + "a": ["a", "a", "b"], + "b": [0, 1, 0], + "d": ["meow", "bark", "um... weasel noise?"], + }, + index=range(3), + ).set_index(["a", "b"]) + + expected_multi = pd.DataFrame( + { + "a": ["a", "a", "b"], + "b": [0, 1, 0], + "c": ["cat", "dog", "weasel"], + "d": ["meow", "bark", "um... weasel noise?"], + }, + index=range(3), + ).set_index(["a", "b"]) + + # Jointly no dups allowed by one_to_one constraint + result = left.join(right, how="inner", validate="1:1") + tm.assert_frame_equal(result, expected_multi) + + +def test_join_index(float_frame): + # left / right + + f = float_frame.loc[float_frame.index[:10], ["A", "B"]] + f2 = float_frame.loc[float_frame.index[5:], ["C", "D"]].iloc[::-1] + + joined = f.join(f2) + tm.assert_index_equal(f.index, joined.index) + expected_columns = pd.Index(["A", "B", "C", "D"]) + tm.assert_index_equal(joined.columns, expected_columns) + + joined = f.join(f2, how="left") + tm.assert_index_equal(joined.index, f.index) + tm.assert_index_equal(joined.columns, expected_columns) + + joined = f.join(f2, how="right") + tm.assert_index_equal(joined.index, f2.index) + tm.assert_index_equal(joined.columns, expected_columns) + + # inner + + joined = f.join(f2, how="inner") + tm.assert_index_equal(joined.index, f.index[5:10]) + tm.assert_index_equal(joined.columns, expected_columns) + + # outer + + joined = f.join(f2, how="outer") + tm.assert_index_equal(joined.index, float_frame.index.sort_values()) + tm.assert_index_equal(joined.columns, expected_columns) + + # left anti + joined = f.join(f2, how="left_anti") + tm.assert_index_equal(joined.index, float_frame.index[:5]) + tm.assert_index_equal(joined.columns, expected_columns) + + # right anti + joined = f.join(f2, how="right_anti") + tm.assert_index_equal(joined.index, float_frame.index[10:][::-1]) + tm.assert_index_equal(joined.columns, expected_columns) + + join_msg = ( + "'foo' is not a valid Merge type: left, right, inner, outer, " + "left_anti, right_anti, cross, asof" + ) + with pytest.raises(ValueError, match=re.escape(join_msg)): + f.join(f2, how="foo") + + # corner case - overlapping columns + msg = "columns overlap but no suffix" + for how in ("outer", "left", "inner"): + with pytest.raises(ValueError, match=msg): + float_frame.join(float_frame, how=how) + + +def test_join_index_more(float_frame): + af = float_frame.loc[:, ["A", "B"]] + bf = float_frame.loc[::2, ["C", "D"]] + + expected = af.copy() + expected["C"] = float_frame["C"][::2] + expected["D"] = float_frame["D"][::2] + + result = af.join(bf) + tm.assert_frame_equal(result, expected) + + result = af.join(bf, how="right") + tm.assert_frame_equal(result, expected[::2]) + + result = bf.join(af, how="right") + tm.assert_frame_equal(result, expected.loc[:, result.columns]) + + +def test_join_index_series(float_frame): + df = float_frame.copy() + ser = df.pop(float_frame.columns[-1]) + joined = df.join(ser) + + tm.assert_frame_equal(joined, float_frame) + + ser.name = None + with pytest.raises(ValueError, match="must have a name"): + df.join(ser) + + +def test_join_overlap(float_frame): + df1 = float_frame.loc[:, ["A", "B", "C"]] + df2 = float_frame.loc[:, ["B", "C", "D"]] + + joined = df1.join(df2, suffixes=("_df1", "_df2")) + df1_suf = df1.loc[:, ["B", "C"]].add_suffix("_df1") + df2_suf = df2.loc[:, ["B", "C"]].add_suffix("_df2") + + no_overlap = float_frame.loc[:, ["A", "D"]] + expected = df1_suf.join(df2_suf).join(no_overlap) + + # column order not necessarily sorted + tm.assert_frame_equal(joined, expected.loc[:, joined.columns]) + + +def test_join_period_index(): + frame_with_period_index = pd.DataFrame( + data=np.arange(20).reshape(4, 5), + columns=list("abcde"), + index=pd.period_range(start="2000", freq="Y", periods=4), + ) + other = frame_with_period_index.rename(columns=lambda key: f"{key}{key}") + + joined_values = np.concatenate([frame_with_period_index.values] * 2, axis=1) + + joined_cols = frame_with_period_index.columns.append(other.columns) + + joined = frame_with_period_index.join(other) + expected = pd.DataFrame( + data=joined_values, columns=joined_cols, index=frame_with_period_index.index + ) + + tm.assert_frame_equal(joined, expected) + + +def test_join_left_sequence_non_unique_index(): + # https://github.com/pandas-dev/pandas/issues/19607 + df1 = pd.DataFrame({"a": [0, 10, 20]}, index=[1, 2, 3]) + df2 = pd.DataFrame({"b": [100, 200, 300]}, index=[4, 3, 2]) + df3 = pd.DataFrame({"c": [400, 500, 600]}, index=[2, 2, 4]) + + joined = df1.join([df2, df3], how="left") + + expected = pd.DataFrame( + { + "a": [0, 10, 10, 20], + "b": [np.nan, 300, 300, 200], + "c": [np.nan, 400, 500, np.nan], + }, + index=[1, 2, 2, 3], + ) + + tm.assert_frame_equal(joined, expected) + + +def test_join_list_series(float_frame): + # GH#46850 + # Join a DataFrame with a list containing both a Series and a DataFrame + left = float_frame.A.to_frame() + right = [float_frame.B, float_frame[["C", "D"]]] + result = left.join(right) + tm.assert_frame_equal(result, float_frame) + + +class TestDataFrameJoin: + def test_join(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + a = frame.loc[frame.index[:5], ["A"]] + b = frame.loc[frame.index[2:], ["B", "C"]] + + joined = a.join(b, how="outer").reindex(frame.index) + expected = frame.copy().values.copy() + expected[np.isnan(joined.values)] = np.nan + expected = pd.DataFrame(expected, index=frame.index, columns=frame.columns) + + assert not np.isnan(joined.values).all() + + tm.assert_frame_equal(joined, expected) + + def test_join_segfault(self): + # GH#1532 + df1 = pd.DataFrame({"a": [1, 1], "b": [1, 2], "x": [1, 2]}) + df2 = pd.DataFrame({"a": [2, 2], "b": [1, 2], "y": [1, 2]}) + df1 = df1.set_index(["a", "b"]) + df2 = df2.set_index(["a", "b"]) + # it works! + for how in ["left", "right", "outer"]: + df1.join(df2, how=how) + + def test_join_str_datetime(self): + str_dates = ["20120209", "20120222"] + dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)] + + A = pd.DataFrame(str_dates, index=range(2), columns=["aa"]) + C = pd.DataFrame([[1, 2], [3, 4]], index=str_dates, columns=dt_dates) + + tst = A.join(C, on="aa") + + assert len(tst.columns) == 3 + + def test_join_multiindex_leftright(self): + # GH 10741 + df1 = pd.DataFrame( + [ + ["a", "x", 0.471780], + ["a", "y", 0.774908], + ["a", "z", 0.563634], + ["b", "x", -0.353756], + ["b", "y", 0.368062], + ["b", "z", -1.721840], + ["c", "x", 1], + ["c", "y", 2], + ["c", "z", 3], + ], + columns=["first", "second", "value1"], + ).set_index(["first", "second"]) + + df2 = pd.DataFrame( + [["a", 10], ["b", 20]], columns=["first", "value2"] + ).set_index(["first"]) + + exp = pd.DataFrame( + [ + [0.471780, 10], + [0.774908, 10], + [0.563634, 10], + [-0.353756, 20], + [0.368062, 20], + [-1.721840, 20], + [1.000000, np.nan], + [2.000000, np.nan], + [3.000000, np.nan], + ], + index=df1.index, + columns=["value1", "value2"], + ) + + # these must be the same results (but columns are flipped) + tm.assert_frame_equal(df1.join(df2, how="left"), exp) + tm.assert_frame_equal(df2.join(df1, how="right"), exp[["value2", "value1"]]) + + exp_idx = pd.MultiIndex.from_product( + [["a", "b"], ["x", "y", "z"]], names=["first", "second"] + ) + exp = pd.DataFrame( + [ + [0.471780, 10], + [0.774908, 10], + [0.563634, 10], + [-0.353756, 20], + [0.368062, 20], + [-1.721840, 20], + ], + index=exp_idx, + columns=["value1", "value2"], + ) + + tm.assert_frame_equal(df1.join(df2, how="right"), exp) + tm.assert_frame_equal(df2.join(df1, how="left"), exp[["value2", "value1"]]) + + def test_join_multiindex_dates(self): + # GH 33692 + date = pd.Timestamp(2000, 1, 1).date() + + df1_index = pd.MultiIndex.from_tuples([(0, date)], names=["index_0", "date"]) + df1 = pd.DataFrame({"col1": [0]}, index=df1_index) + df2_index = pd.MultiIndex.from_tuples([(0, date)], names=["index_0", "date"]) + df2 = pd.DataFrame({"col2": [0]}, index=df2_index) + df3_index = pd.MultiIndex.from_tuples([(0, date)], names=["index_0", "date"]) + df3 = pd.DataFrame({"col3": [0]}, index=df3_index) + + result = df1.join([df2, df3]) + + expected_index = pd.MultiIndex.from_tuples( + [(0, date)], names=["index_0", "date"] + ) + expected = pd.DataFrame( + {"col1": [0], "col2": [0], "col3": [0]}, index=expected_index + ) + + tm.assert_equal(result, expected) + + def test_merge_join_different_levels_raises(self): + # GH#9455 + # GH 40993: For raising, enforced in 2.0 + + # first dataframe + df1 = pd.DataFrame(columns=["a", "b"], data=[[1, 11], [0, 22]]) + + # second dataframe + columns = pd.MultiIndex.from_tuples([("a", ""), ("c", "c1")]) + df2 = pd.DataFrame(columns=columns, data=[[1, 33], [0, 44]]) + + # merge + with pytest.raises( + MergeError, match="Not allowed to merge between different levels" + ): + pd.merge(df1, df2, on="a") + + # join, see discussion in GH#12219 + with pytest.raises( + MergeError, match="Not allowed to merge between different levels" + ): + df1.join(df2, on="a") + + def test_frame_join_tzaware(self): + tz = zoneinfo.ZoneInfo("US/Central") + test1 = pd.DataFrame( + np.zeros((6, 3)), + index=pd.date_range("2012-11-15 00:00:00", periods=6, freq="100ms", tz=tz), + ) + test2 = pd.DataFrame( + np.zeros((3, 3)), + index=pd.date_range("2012-11-15 00:00:00", periods=3, freq="250ms", tz=tz), + columns=range(3, 6), + ) + + result = test1.join(test2, how="outer") + expected = test1.index.union(test2.index) + + tm.assert_index_equal(result.index, expected) + assert result.index.tz.key == "US/Central" + + def test_frame_join_categorical_index(self): + # GH 61675 + cat_data = pd.Categorical( + [3, 4], + categories=pd.Series([2, 3, 4, 5], dtype="Int64"), + ordered=True, + ) + values1 = "a b".split() + values2 = "foo bar".split() + df1 = pd.DataFrame({"hr": cat_data, "values1": values1}).set_index("hr") + df2 = pd.DataFrame({"hr": cat_data, "values2": values2}).set_index("hr") + df1.columns = pd.CategoricalIndex([4], dtype=cat_data.dtype, name="other_hr") + df2.columns = pd.CategoricalIndex([3], dtype=cat_data.dtype, name="other_hr") + + df_joined = df1.join(df2) + expected = pd.DataFrame( + {"hr": cat_data, "values1": values1, "values2": values2} + ).set_index("hr") + expected.columns = pd.CategoricalIndex( + [4, 3], dtype=cat_data.dtype, name="other_hr" + ) + + tm.assert_frame_equal(df_joined, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_map.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_map.py new file mode 100644 index 0000000000000000000000000000000000000000..e3539033186bf952840b118d642e036d4672e12c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_map.py @@ -0,0 +1,202 @@ +from datetime import datetime + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + +from pandas.tseries.offsets import BDay + + +def test_map(float_frame): + result = float_frame.map(lambda x: x * 2) + tm.assert_frame_equal(result, float_frame * 2) + float_frame.map(type) + + # GH 465: function returning tuples + result = float_frame.map(lambda x: (x, x))["A"].iloc[0] + assert isinstance(result, tuple) + + +@pytest.mark.parametrize("val", [1, 1.0]) +def test_map_float_object_conversion(val): + # GH 2909: object conversion to float in constructor? + df = pd.DataFrame(data=[val, "a"]) + result = df.map(lambda x: x).dtypes[0] + assert result == object + + +def test_map_keeps_dtype(na_action): + # GH52219 + arr = pd.Series(["a", np.nan, "b"]) + sparse_arr = arr.astype(pd.SparseDtype(object)) + df = pd.DataFrame(data={"a": arr, "b": sparse_arr}) + + def func(x): + return str.upper(x) if not pd.isna(x) else x + + result = df.map(func, na_action=na_action) + + expected_sparse = pd.array(["A", np.nan, "B"], dtype=pd.SparseDtype(object)) + expected_arr = expected_sparse.astype(object) + expected = pd.DataFrame({"a": expected_arr, "b": expected_sparse}) + + tm.assert_frame_equal(result, expected) + + result_empty = df.iloc[:0, :].map(func, na_action=na_action) + expected_empty = expected.iloc[:0, :] + tm.assert_frame_equal(result_empty, expected_empty) + + +def test_map_str(): + # GH 2786 + df = pd.DataFrame(np.random.default_rng(2).random((3, 4))) + df2 = df.copy() + cols = ["a", "a", "a", "a"] + df.columns = cols + + expected = df2.map(str) + expected.columns = cols + result = df.map(str) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "col, val", + [["datetime", pd.Timestamp("20130101")], ["timedelta", pd.Timedelta("1 min")]], +) +def test_map_datetimelike(col, val): + # datetime/timedelta + df = pd.DataFrame(np.random.default_rng(2).random((3, 4))) + df[col] = val + result = df.map(str) + assert result.loc[0, col] == str(df.loc[0, col]) + + +@pytest.mark.parametrize( + "expected", + [ + pd.DataFrame(), + pd.DataFrame(columns=list("ABC")), + pd.DataFrame(index=list("ABC")), + pd.DataFrame({"A": [], "B": [], "C": []}), + ], +) +@pytest.mark.parametrize("func", [round, lambda x: x]) +def test_map_empty(expected, func): + # GH 8222 + result = expected.map(func) + tm.assert_frame_equal(result, expected) + + +def test_map_kwargs(): + # GH 40652 + result = pd.DataFrame([[1, 2], [3, 4]]).map(lambda x, y: x + y, y=2) + expected = pd.DataFrame([[3, 4], [5, 6]]) + tm.assert_frame_equal(result, expected) + + +def test_map_na_ignore(float_frame): + # GH 23803 + strlen_frame = float_frame.map(lambda x: len(str(x))) + float_frame_with_na = float_frame.copy() + mask = np.random.default_rng(2).integers(0, 2, size=float_frame.shape, dtype=bool) + float_frame_with_na[mask] = pd.NA + strlen_frame_na_ignore = float_frame_with_na.map( + lambda x: len(str(x)), na_action="ignore" + ) + # Set float64 type to avoid upcast when setting NA below + strlen_frame_with_na = strlen_frame.copy().astype("float64") + strlen_frame_with_na[mask] = pd.NA + tm.assert_frame_equal(strlen_frame_na_ignore, strlen_frame_with_na) + + +def test_map_box_timestamps(): + # GH 2689, GH 2627 + ser = pd.Series(pd.date_range("1/1/2000", periods=10)) + + def func(x): + return (x.hour, x.day, x.month) + + # it works! + pd.DataFrame(ser).map(func) + + +def test_map_box(): + # ufunc will not be boxed. Same test cases as the test_map_box + df = pd.DataFrame( + { + "a": [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")], + "b": [ + pd.Timestamp("2011-01-01", tz="US/Eastern"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + ], + "c": [pd.Timedelta("1 days"), pd.Timedelta("2 days")], + "d": [ + pd.Period("2011-01-01", freq="M"), + pd.Period("2011-01-02", freq="M"), + ], + } + ) + + result = df.map(lambda x: type(x).__name__) + expected = pd.DataFrame( + { + "a": ["Timestamp", "Timestamp"], + "b": ["Timestamp", "Timestamp"], + "c": ["Timedelta", "Timedelta"], + "d": ["Period", "Period"], + } + ) + tm.assert_frame_equal(result, expected) + + +def test_frame_map_dont_convert_datetime64(unit): + dtype = f"M8[{unit}]" + df = pd.DataFrame({"x1": [datetime(1996, 1, 1)]}, dtype=dtype) + + df = df.map(lambda x: x + BDay()) + df = df.map(lambda x: x + BDay()) + + result = df.x1.dtype + assert result == dtype + + +def test_map_function_runs_once(): + df = pd.DataFrame({"a": [1, 2, 3]}) + values = [] # Save values function is applied to + + def reducing_function(val): + values.append(val) + + def non_reducing_function(val): + values.append(val) + return val + + for func in [reducing_function, non_reducing_function]: + del values[:] + + df.map(func) + assert values == df.a.to_list() + + +def test_map_type(): + # GH 46719 + df = pd.DataFrame( + {"col1": [3, "string", float], "col2": [0.25, datetime(2020, 1, 1), np.nan]}, + index=["a", "b", "c"], + ) + + result = df.map(type) + expected = pd.DataFrame( + {"col1": [int, str, type], "col2": [float, datetime, float]}, + index=["a", "b", "c"], + ) + tm.assert_frame_equal(result, expected) + + +def test_map_invalid_na_action(float_frame): + # GH 23803 + with pytest.raises(ValueError, match="na_action must be .*Got 'abc'"): + float_frame.map(lambda x: len(str(x)), na_action="abc") diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_matmul.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_matmul.py new file mode 100644 index 0000000000000000000000000000000000000000..6c6ff4a028b5b8167b3bd0eb92325456a6f8f338 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_matmul.py @@ -0,0 +1,94 @@ +import operator + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestMatMul: + def test_matmul(self): + # matmul test is for GH#10259 + a = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 4)), + index=["a", "b", "c"], + columns=["p", "q", "r", "s"], + ) + b = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 2)), + index=["p", "q", "r", "s"], + columns=["one", "two"], + ) + + # DataFrame @ DataFrame + result = operator.matmul(a, b) + expected = pd.DataFrame( + np.dot(a.values, b.values), index=["a", "b", "c"], columns=["one", "two"] + ) + tm.assert_frame_equal(result, expected) + + # DataFrame @ Series + result = operator.matmul(a, b.one) + expected = pd.Series(np.dot(a.values, b.one.values), index=["a", "b", "c"]) + tm.assert_series_equal(result, expected) + + # np.array @ DataFrame + result = operator.matmul(a.values, b) + assert isinstance(result, pd.DataFrame) + assert result.columns.equals(b.columns) + assert result.index.equals(pd.Index(range(3))) + expected = np.dot(a.values, b.values) + tm.assert_almost_equal(result.values, expected) + + # nested list @ DataFrame (__rmatmul__) + result = operator.matmul(a.values.tolist(), b) + expected = pd.DataFrame( + np.dot(a.values, b.values), index=["a", "b", "c"], columns=["one", "two"] + ) + tm.assert_almost_equal(result.values, expected.values) + + # mixed dtype DataFrame @ DataFrame + a["q"] = a.q.round().astype(int) + result = operator.matmul(a, b) + expected = pd.DataFrame( + np.dot(a.values, b.values), index=["a", "b", "c"], columns=["one", "two"] + ) + tm.assert_frame_equal(result, expected) + + # different dtypes DataFrame @ DataFrame + a = a.astype(int) + result = operator.matmul(a, b) + expected = pd.DataFrame( + np.dot(a.values, b.values), index=["a", "b", "c"], columns=["one", "two"] + ) + tm.assert_frame_equal(result, expected) + + # unaligned + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 4)), + index=[1, 2, 3], + columns=range(4), + ) + df2 = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), + index=range(5), + columns=[1, 2, 3], + ) + + with pytest.raises(ValueError, match="aligned"): + operator.matmul(df, df2) + + def test_matmul_message_shapes(self): + # GH#21581 exception message should reflect original shapes, + # not transposed shapes + a = np.random.default_rng(2).random((10, 4)) + b = np.random.default_rng(2).random((5, 3)) + + df = pd.DataFrame(b) + + msg = r"shapes \(10, 4\) and \(5, 3\) not aligned" + with pytest.raises(ValueError, match=msg): + a @ df + with pytest.raises(ValueError, match=msg): + a.tolist() @ df diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_nlargest.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_nlargest.py new file mode 100644 index 0000000000000000000000000000000000000000..8a13174be3587c2e7e4c62f576ed06ca7db209b8 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_nlargest.py @@ -0,0 +1,231 @@ +""" +Note: for naming purposes, most tests are title with as e.g. "test_nlargest_foo" +but are implicitly also testing nsmallest_foo. +""" + +from string import ascii_lowercase + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def df_main_dtypes(): + return pd.DataFrame( + { + "group": [1, 1, 2], + "int": [1, 2, 3], + "float": [4.0, 5.0, 6.0], + "string": list("abc"), + "category_string": pd.Series(list("abc")).astype("category"), + "category_int": [7, 8, 9], + "datetime": pd.date_range("20130101", periods=3), + "datetimetz": pd.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", + ], + ) + + +class TestNLargestNSmallest: + # ---------------------------------------------------------------------- + # Top / bottom + @pytest.mark.parametrize( + "order", + [ + ["a"], + ["c"], + ["a", "b"], + ["a", "c"], + ["b", "a"], + ["b", "c"], + ["a", "b", "c"], + ["c", "a", "b"], + ["c", "b", "a"], + ["b", "c", "a"], + ["b", "a", "c"], + # dups! + ["b", "c", "c"], + ], + ) + @pytest.mark.parametrize("n", range(1, 11)) + def test_nlargest_n(self, nselect_method, n, order): + # GH#10393 + df = pd.DataFrame( + { + "a": np.random.default_rng(2).permutation(10), + "b": list(ascii_lowercase[:10]), + "c": np.random.default_rng(2).permutation(10).astype("float64"), + } + ) + if "b" in order: + error_msg = ( + f"Column 'b' has dtype (object|str), " + f"cannot use method '{nselect_method}' with this dtype" + ) + with pytest.raises(TypeError, match=error_msg): + getattr(df, nselect_method)(n, order) + else: + ascending = nselect_method == "nsmallest" + result = getattr(df, nselect_method)(n, order) + result.index = pd.Index(list(result.index)) + expected = df.sort_values(order, ascending=ascending).head(n) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "columns", [["group", "category_string"], ["group", "string"]] + ) + def test_nlargest_error(self, df_main_dtypes, nselect_method, columns): + df = df_main_dtypes + col = columns[1] + error_msg = ( + f"Column '{col}' has dtype {df[col].dtype}, " + f"cannot use method '{nselect_method}' with this dtype" + ) + # escape some characters that may be in the repr + error_msg = ( + error_msg.replace("(", "\\(") + .replace(")", "\\)") + .replace("[", "\\[") + .replace("]", "\\]") + ) + with pytest.raises(TypeError, match=error_msg): + getattr(df, nselect_method)(2, columns) + + def test_nlargest_all_dtypes(self, df_main_dtypes): + df = df_main_dtypes + df.nsmallest(2, list(set(df) - {"category_string", "string"})) + df.nlargest(2, list(set(df) - {"category_string", "string"})) + + def test_nlargest_duplicates_on_starter_columns(self): + # regression test for GH#22752 + + df = pd.DataFrame({"a": [2, 2, 2, 1, 1, 1], "b": [1, 2, 3, 3, 2, 1]}) + + result = df.nlargest(4, columns=["a", "b"]) + expected = pd.DataFrame( + {"a": [2, 2, 2, 1], "b": [3, 2, 1, 3]}, index=[2, 1, 0, 3] + ) + tm.assert_frame_equal(result, expected) + + result = df.nsmallest(4, columns=["a", "b"]) + expected = pd.DataFrame( + {"a": [1, 1, 1, 2], "b": [1, 2, 3, 1]}, index=[5, 4, 3, 0] + ) + tm.assert_frame_equal(result, expected) + + def test_nlargest_n_identical_values(self): + # GH#15297 + df = pd.DataFrame({"a": [1] * 5, "b": [1, 2, 3, 4, 5]}) + + result = df.nlargest(3, "a") + expected = pd.DataFrame({"a": [1] * 3, "b": [1, 2, 3]}, index=range(3)) + tm.assert_frame_equal(result, expected) + + result = df.nsmallest(3, "a") + expected = pd.DataFrame({"a": [1] * 3, "b": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "order", + [["a", "b", "c"], ["c", "b", "a"], ["a"], ["b"], ["a", "b"], ["c", "b"]], + ) + @pytest.mark.parametrize("n", range(1, 6)) + def test_nlargest_n_duplicate_index(self, n, order): + # GH#13412 + + df = pd.DataFrame( + {"a": [1, 2, 3, 4, 4], "b": [1, 1, 1, 1, 1], "c": [0, 1, 2, 5, 4]}, + index=[0, 0, 1, 1, 1], + ) + result = df.nsmallest(n, order) + expected = df.sort_values(order, kind="stable").head(n) + tm.assert_frame_equal(result, expected) + + result = df.nlargest(n, order) + expected = df.sort_values(order, ascending=False, kind="stable").head(n) + tm.assert_frame_equal(result, expected) + + def test_nlargest_duplicate_keep_all_ties(self): + # GH#16818 + df = pd.DataFrame( + {"a": [5, 4, 4, 2, 3, 3, 3, 3], "b": [10, 9, 8, 7, 5, 50, 10, 20]} + ) + result = df.nlargest(4, "a", keep="all") + expected = pd.DataFrame( + { + "a": [5, 4, 4, 3, 3, 3, 3], + "b": [10, 9, 8, 5, 50, 10, 20], + }, + index=[0, 1, 2, 4, 5, 6, 7], + ) + tm.assert_frame_equal(result, expected) + + result = df.nsmallest(2, "a", keep="all") + expected = pd.DataFrame( + { + "a": [2, 3, 3, 3, 3], + "b": [7, 5, 50, 10, 20], + }, + index=range(3, 8), + ) + tm.assert_frame_equal(result, expected) + + def test_nlargest_multiindex_column_lookup(self): + # Check whether tuples are correctly treated as multi-level lookups. + # GH#23033 + df = pd.DataFrame( + columns=pd.MultiIndex.from_product([["x"], ["a", "b"]]), + data=[[0.33, 0.13], [0.86, 0.25], [0.25, 0.70], [0.85, 0.91]], + ) + + # nsmallest + result = df.nsmallest(3, ("x", "a")) + expected = df.iloc[[2, 0, 3]] + tm.assert_frame_equal(result, expected) + + # nlargest + result = df.nlargest(3, ("x", "b")) + expected = df.iloc[[3, 2, 1]] + tm.assert_frame_equal(result, expected) + + def test_nlargest_nan(self): + # GH#43060 + df = pd.DataFrame([np.nan, np.nan, 0, 1, 2, 3]) + result = df.nlargest(5, 0) + expected = df.sort_values(0, ascending=False).head(5) + tm.assert_frame_equal(result, expected) + + def test_nsmallest_nan_after_n_element(self): + # GH#46589 + df = pd.DataFrame( + { + "a": [1, 2, 3, 4, 5, None, 7], + "b": [7, 6, 5, 4, 3, 2, 1], + "c": [1, 1, 2, 2, 3, 3, 3], + }, + index=range(7), + ) + result = df.nsmallest(5, columns=["a", "b"]) + expected = pd.DataFrame( + { + "a": [1, 2, 3, 4, 5], + "b": [7, 6, 5, 4, 3], + "c": [1, 1, 2, 2, 3], + }, + index=range(5), + ).astype({"a": "float"}) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_pct_change.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_pct_change.py new file mode 100644 index 0000000000000000000000000000000000000000..456d535dbcfb742e4bb4ef69b7fcd9f0b42961c6 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_pct_change.py @@ -0,0 +1,124 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFramePctChange: + @pytest.mark.parametrize( + "periods, exp", + [ + (1, [np.nan, np.nan, np.nan, 1, 1, 1.5, np.nan, np.nan]), + (-1, [np.nan, np.nan, -0.5, -0.5, -0.6, np.nan, np.nan, np.nan]), + ], + ) + def test_pct_change_with_nas(self, periods, exp, frame_or_series): + vals = [np.nan, np.nan, 1, 2, 4, 10, np.nan, np.nan] + obj = frame_or_series(vals) + + res = obj.pct_change(periods=periods) + tm.assert_equal(res, frame_or_series(exp)) + + def test_pct_change_numeric(self): + # GH#11150 + pnl = pd.DataFrame( + [np.arange(0, 40, 10), np.arange(0, 40, 10), np.arange(0, 40, 10)] + ).astype(np.float64) + pnl.iat[1, 0] = np.nan + pnl.iat[1, 1] = np.nan + pnl.iat[2, 3] = 60 + + for axis in range(2): + expected = pnl / pnl.shift(axis=axis) - 1 + result = pnl.pct_change(axis=axis) + tm.assert_frame_equal(result, expected) + + def test_pct_change(self, datetime_frame): + rs = datetime_frame.pct_change() + tm.assert_frame_equal(rs, datetime_frame / datetime_frame.shift(1) - 1) + + rs = datetime_frame.pct_change(2) + filled = datetime_frame.ffill() + tm.assert_frame_equal(rs, filled / filled.shift(2) - 1) + + rs = datetime_frame.pct_change() + tm.assert_frame_equal(rs, datetime_frame / datetime_frame.shift(1) - 1) + + rs = datetime_frame.pct_change(freq="5D") + tm.assert_frame_equal( + rs, + (datetime_frame / datetime_frame.shift(freq="5D") - 1).reindex_like( + datetime_frame + ), + ) + + def test_pct_change_shift_over_nas(self): + s = pd.Series([1.0, 1.5, np.nan, 2.5, 3.0]) + + df = pd.DataFrame({"a": s, "b": s}) + + chg = df.pct_change() + expected = pd.Series([np.nan, 0.5, np.nan, np.nan, 0.2]) + edf = pd.DataFrame({"a": expected, "b": expected}) + tm.assert_frame_equal(chg, edf) + + @pytest.mark.parametrize( + "freq, periods", + [ + ("5B", 5), + ("3B", 3), + ("14B", 14), + ], + ) + def test_pct_change_periods_freq( + self, + datetime_frame, + freq, + periods, + ): + # GH#7292 + rs_freq = datetime_frame.pct_change(freq=freq) + rs_periods = datetime_frame.pct_change(periods) + tm.assert_frame_equal(rs_freq, rs_periods) + + empty_ts = pd.DataFrame( + index=datetime_frame.index, columns=datetime_frame.columns + ) + rs_freq = empty_ts.pct_change(freq=freq) + rs_periods = empty_ts.pct_change(periods) + tm.assert_frame_equal(rs_freq, rs_periods) + + +def test_pct_change_with_duplicated_indices(): + # GH30463 + data = pd.DataFrame( + {0: [np.nan, 1, 2, 3, 9, 18], 1: [0, 1, np.nan, 3, 9, 18]}, index=["a", "b"] * 3 + ) + + result = data.pct_change() + + second_column = [np.nan, np.inf, np.nan, np.nan, 2.0, 1.0] + expected = pd.DataFrame( + {0: [np.nan, np.nan, 1.0, 0.5, 2.0, 1.0], 1: second_column}, + index=["a", "b"] * 3, + ) + tm.assert_frame_equal(result, expected) + + +def test_pct_change_none_beginning(): + # GH#54481 + df = pd.DataFrame( + [ + [1, None], + [2, 1], + [3, 2], + [4, 3], + [5, 4], + ] + ) + result = df.pct_change() + expected = pd.DataFrame( + {0: [np.nan, 1, 0.5, 1 / 3, 0.25], 1: [np.nan, np.nan, 1, 0.5, 1 / 3]} + ) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_pipe.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..49d50eb71cdaed911ba82ddd06efb917a3e0679e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_pipe.py @@ -0,0 +1,36 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestPipe: + def test_pipe(self, frame_or_series): + obj = pd.DataFrame({"A": [1, 2, 3]}) + expected = pd.DataFrame({"A": [1, 4, 9]}) + if frame_or_series is pd.Series: + obj = obj["A"] + expected = expected["A"] + + f = lambda x, y: x**y + result = obj.pipe(f, 2) + tm.assert_equal(result, expected) + + def test_pipe_tuple(self, frame_or_series): + obj = pd.DataFrame({"A": [1, 2, 3]}) + obj = tm.get_obj(obj, frame_or_series) + + f = lambda x, y: y + result = obj.pipe((f, "y"), 0) + tm.assert_equal(result, obj) + + def test_pipe_tuple_error(self, frame_or_series): + obj = pd.DataFrame({"A": [1, 2, 3]}) + obj = tm.get_obj(obj, frame_or_series) + + f = lambda x, y: y + + msg = "y is both the pipe target and a keyword argument" + + with pytest.raises(ValueError, match=msg): + obj.pipe((f, "y"), x=1, y=0) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_pop.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_pop.py new file mode 100644 index 0000000000000000000000000000000000000000..5498061aa482e9aee7d0a4a6378be433e9438820 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_pop.py @@ -0,0 +1,71 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestDataFramePop: + def test_pop(self, float_frame): + float_frame.columns.name = "baz" + + float_frame.pop("A") + assert "A" not in float_frame + + float_frame["foo"] = "bar" + float_frame.pop("foo") + assert "foo" not in float_frame + assert float_frame.columns.name == "baz" + + # gh-10912: inplace ops cause caching issue + a = pd.DataFrame( + [[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"], index=["X", "Y"] + ) + b = a.pop("B") + b += 1 + + # original frame + expected = pd.DataFrame([[1, 3], [4, 6]], columns=["A", "C"], index=["X", "Y"]) + tm.assert_frame_equal(a, expected) + + # result + expected = pd.Series([2, 5], index=["X", "Y"], name="B") + 1 + tm.assert_series_equal(b, expected) + + def test_pop_non_unique_cols(self): + df = pd.DataFrame({0: [0, 1], 1: [0, 1], 2: [4, 5]}) + df.columns = ["a", "b", "a"] + + res = df.pop("a") + assert type(res) == pd.DataFrame + assert len(res) == 2 + assert len(df.columns) == 1 + assert "b" in df.columns + assert "a" not in df.columns + assert len(df.index) == 2 + + def test_mixed_depth_pop(self): + arrays = [ + ["a", "top", "top", "routine1", "routine1", "routine2"], + ["", "OD", "OD", "result1", "result2", "result1"], + ["", "wx", "wy", "", "", ""], + ] + + tuples = sorted(zip(*arrays, strict=True)) + index = pd.MultiIndex.from_tuples(tuples) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 6)), columns=index + ) + + df1 = df.copy() + df2 = df.copy() + result = df1.pop("a") + expected = df2.pop(("a", "", "")) + tm.assert_series_equal(expected, result, check_names=False) + tm.assert_frame_equal(df1, df2) + assert result.name == "a" + + expected = df1["top"] + df1 = df1.drop(["top"], axis=1) + result = df2.pop("top") + tm.assert_frame_equal(expected, result) + tm.assert_frame_equal(df1, df2) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_quantile.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_quantile.py new file mode 100644 index 0000000000000000000000000000000000000000..2f8b904d64d21fe2e4bc991e593c5426311258d1 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_quantile.py @@ -0,0 +1,940 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture( + params=[["linear", "single"], ["nearest", "table"]], ids=lambda x: "-".join(x) +) +def interp_method(request): + """(interpolation, method) arguments for quantile""" + return request.param + + +class TestDataFrameQuantile: + @pytest.mark.parametrize( + "df,expected", + [ + [ + pd.DataFrame( + { + 0: pd.Series(pd.arrays.SparseArray([1, 2])), + 1: pd.Series(pd.arrays.SparseArray([3, 4])), + } + ), + pd.Series([1.5, 3.5], name=0.5), + ], + [ + pd.DataFrame(pd.Series([0.0, None, 1.0, 2.0], dtype="Sparse[float]")), + pd.Series([1.0], name=0.5), + ], + ], + ) + def test_quantile_sparse(self, df, expected): + # GH#17198 + # GH#24600 + result = df.quantile() + expected = expected.astype("Sparse[float]") + tm.assert_series_equal(result, expected) + + def test_quantile(self, datetime_frame, interp_method, request): + interpolation, method = interp_method + df = datetime_frame + result = df.quantile( + 0.1, axis=0, numeric_only=True, interpolation=interpolation, method=method + ) + expected = pd.Series( + [np.percentile(df[col], 10) for col in df.columns], + index=df.columns, + name=0.1, + ) + if interpolation == "linear": + # np.percentile values only comparable to linear interpolation + tm.assert_series_equal(result, expected) + else: + tm.assert_index_equal(result.index, expected.index) + assert result.name == expected.name + + result = df.quantile( + 0.9, axis=1, numeric_only=True, interpolation=interpolation, method=method + ) + expected = pd.Series( + [np.percentile(df.loc[date], 90) for date in df.index], + index=df.index, + name=0.9, + ) + if interpolation == "linear": + # np.percentile values only comparable to linear interpolation + tm.assert_series_equal(result, expected) + else: + tm.assert_index_equal(result.index, expected.index) + assert result.name == expected.name + + def test_empty(self, interp_method): + interpolation, method = interp_method + q = pd.DataFrame({"x": [], "y": []}).quantile( + 0.1, axis=0, numeric_only=True, interpolation=interpolation, method=method + ) + assert np.isnan(q["x"]) and np.isnan(q["y"]) + + def test_non_numeric_exclusion(self, interp_method, request): + interpolation, method = interp_method + df = pd.DataFrame({"col1": ["A", "A", "B", "B"], "col2": [1, 2, 3, 4]}) + rs = df.quantile( + 0.5, numeric_only=True, interpolation=interpolation, method=method + ) + xp = df.median(numeric_only=True).rename(0.5) + if interpolation == "nearest": + xp = (xp + 0.5).astype(np.int64) + tm.assert_series_equal(rs, xp) + + def test_axis(self, interp_method): + # axis + interpolation, method = interp_method + df = pd.DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3]) + result = df.quantile(0.5, axis=1, interpolation=interpolation, method=method) + expected = pd.Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5) + if interpolation == "nearest": + expected = expected.astype(np.int64) + tm.assert_series_equal(result, expected) + + result = df.quantile( + [0.5, 0.75], axis=1, interpolation=interpolation, method=method + ) + expected = pd.DataFrame( + {1: [1.5, 1.75], 2: [2.5, 2.75], 3: [3.5, 3.75]}, index=[0.5, 0.75] + ) + if interpolation == "nearest": + expected.iloc[0, :] -= 0.5 + expected.iloc[1, :] += 0.25 + expected = expected.astype(np.int64) + tm.assert_frame_equal(result, expected, check_index_type=True) + + def test_axis_numeric_only_true(self, interp_method): + # We may want to break API in the future to change this + # so that we exclude non-numeric along the same axis + # See GH #7312 + interpolation, method = interp_method + df = pd.DataFrame([[1, 2, 3], ["a", "b", 4]]) + result = df.quantile( + 0.5, axis=1, numeric_only=True, interpolation=interpolation, method=method + ) + expected = pd.Series([3.0, 4.0], index=range(2), name=0.5) + if interpolation == "nearest": + expected = expected.astype(np.int64) + tm.assert_series_equal(result, expected) + + def test_quantile_date_range(self, interp_method): + # GH 2460 + interpolation, method = interp_method + dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific", unit="ns") + ser = pd.Series(dti) + df = pd.DataFrame(ser) + + result = df.quantile( + numeric_only=False, interpolation=interpolation, method=method + ) + expected = pd.Series( + ["2016-01-02 00:00:00"], name=0.5, dtype="datetime64[ns, US/Pacific]" + ) + + tm.assert_series_equal(result, expected) + + def test_quantile_axis_mixed(self, interp_method): + # mixed on axis=1 + interpolation, method = interp_method + df = pd.DataFrame( + { + "A": [1, 2, 3], + "B": [2.0, 3.0, 4.0], + "C": pd.date_range("20130101", periods=3), + "D": ["foo", "bar", "baz"], + } + ) + result = df.quantile( + 0.5, axis=1, numeric_only=True, interpolation=interpolation, method=method + ) + expected = pd.Series([1.5, 2.5, 3.5], name=0.5) + if interpolation == "nearest": + expected -= 0.5 + tm.assert_series_equal(result, expected) + + # must raise + msg = "'<' not supported between instances of 'Timestamp' and 'float'" + with pytest.raises(TypeError, match=msg): + df.quantile(0.5, axis=1, numeric_only=False) + + def test_quantile_axis_parameter(self, interp_method): + # GH 9543/9544 + interpolation, method = interp_method + df = pd.DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3]) + + result = df.quantile(0.5, axis=0, interpolation=interpolation, method=method) + + expected = pd.Series([2.0, 3.0], index=["A", "B"], name=0.5) + if interpolation == "nearest": + expected = expected.astype(np.int64) + tm.assert_series_equal(result, expected) + + expected = df.quantile( + 0.5, axis="index", interpolation=interpolation, method=method + ) + if interpolation == "nearest": + expected = expected.astype(np.int64) + tm.assert_series_equal(result, expected) + + result = df.quantile(0.5, axis=1, interpolation=interpolation, method=method) + + expected = pd.Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5) + if interpolation == "nearest": + expected = expected.astype(np.int64) + tm.assert_series_equal(result, expected) + + result = df.quantile( + 0.5, axis="columns", interpolation=interpolation, method=method + ) + tm.assert_series_equal(result, expected) + + msg = "No axis named -1 for object type DataFrame" + with pytest.raises(ValueError, match=msg): + df.quantile(0.1, axis=-1, interpolation=interpolation, method=method) + msg = "No axis named column for object type DataFrame" + with pytest.raises(ValueError, match=msg): + df.quantile(0.1, axis="column") + + def test_quantile_interpolation(self): + # see gh-10174 + + # interpolation method other than default linear + df = pd.DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3]) + result = df.quantile(0.5, axis=1, interpolation="nearest") + expected = pd.Series([1, 2, 3], index=[1, 2, 3], name=0.5) + tm.assert_series_equal(result, expected) + + # cross-check interpolation=nearest results in original dtype + exp = np.percentile( + np.array([[1, 2, 3], [2, 3, 4]]), + 0.5, + axis=0, + method="nearest", + ) + expected = pd.Series(exp, index=[1, 2, 3], name=0.5, dtype="int64") + tm.assert_series_equal(result, expected) + + # float + df = pd.DataFrame({"A": [1.0, 2.0, 3.0], "B": [2.0, 3.0, 4.0]}, index=[1, 2, 3]) + result = df.quantile(0.5, axis=1, interpolation="nearest") + expected = pd.Series([1.0, 2.0, 3.0], index=[1, 2, 3], name=0.5) + tm.assert_series_equal(result, expected) + exp = np.percentile( + np.array([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]]), + 0.5, + axis=0, + method="nearest", + ) + expected = pd.Series(exp, index=[1, 2, 3], name=0.5, dtype="float64") + tm.assert_series_equal(result, expected) + + # axis + result = df.quantile([0.5, 0.75], axis=1, interpolation="lower") + expected = pd.DataFrame( + {1: [1.0, 1.0], 2: [2.0, 2.0], 3: [3.0, 3.0]}, index=[0.5, 0.75] + ) + tm.assert_frame_equal(result, expected) + + # test degenerate case + df = pd.DataFrame({"x": [], "y": []}) + q = df.quantile(0.1, axis=0, interpolation="higher") + assert np.isnan(q["x"]) and np.isnan(q["y"]) + + # multi + df = pd.DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"]) + result = df.quantile([0.25, 0.5], interpolation="midpoint") + + # https://github.com/numpy/numpy/issues/7163 + expected = pd.DataFrame( + [[1.5, 1.5, 1.5], [2.0, 2.0, 2.0]], + index=[0.25, 0.5], + columns=["a", "b", "c"], + ) + tm.assert_frame_equal(result, expected) + + def test_quantile_interpolation_datetime(self, datetime_frame): + # see gh-10174 + + # interpolation = linear (default case) + df = datetime_frame + q = df.quantile(0.1, axis=0, numeric_only=True, interpolation="linear") + assert q["A"] == np.percentile(df["A"], 10) + + def test_quantile_interpolation_int(self, int_frame): + # see gh-10174 + + df = int_frame + # interpolation = linear (default case) + q = df.quantile(0.1) + assert q["A"] == np.percentile(df["A"], 10) + + # test with and without interpolation keyword + q1 = df.quantile(0.1, axis=0, interpolation="linear") + assert q1["A"] == np.percentile(df["A"], 10) + tm.assert_series_equal(q, q1) + + def test_quantile_multi(self, interp_method): + interpolation, method = interp_method + df = pd.DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"]) + result = df.quantile([0.25, 0.5], interpolation=interpolation, method=method) + expected = pd.DataFrame( + [[1.5, 1.5, 1.5], [2.0, 2.0, 2.0]], + index=[0.25, 0.5], + columns=["a", "b", "c"], + ) + if interpolation == "nearest": + expected = expected.astype(np.int64) + tm.assert_frame_equal(result, expected) + + def test_quantile_multi_axis_1(self, interp_method): + interpolation, method = interp_method + df = pd.DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"]) + result = df.quantile( + [0.25, 0.5], axis=1, interpolation=interpolation, method=method + ) + expected = pd.DataFrame( + [[1.0, 2.0, 3.0]] * 2, index=[0.25, 0.5], columns=[0, 1, 2] + ) + if interpolation == "nearest": + expected = expected.astype(np.int64) + tm.assert_frame_equal(result, expected) + + def test_quantile_multi_empty(self, interp_method): + interpolation, method = interp_method + result = pd.DataFrame({"x": [], "y": []}).quantile( + [0.1, 0.9], axis=0, interpolation=interpolation, method=method + ) + expected = pd.DataFrame( + {"x": [np.nan, np.nan], "y": [np.nan, np.nan]}, index=[0.1, 0.9] + ) + tm.assert_frame_equal(result, expected) + + def test_quantile_datetime(self, unit): + dti = pd.to_datetime(["2010", "2011"]).as_unit(unit) + df = pd.DataFrame({"a": dti, "b": [0, 5]}) + + # exclude datetime + result = df.quantile(0.5, numeric_only=True) + expected = pd.Series([2.5], index=["b"], name=0.5) + tm.assert_series_equal(result, expected) + + # datetime + result = df.quantile(0.5, numeric_only=False) + expected = pd.Series( + [pd.Timestamp("2010-07-02 12:00:00"), 2.5], index=["a", "b"], name=0.5 + ) + tm.assert_series_equal(result, expected) + + # datetime w/ multi + result = df.quantile([0.5], numeric_only=False) + expected = pd.DataFrame( + {"a": pd.Timestamp("2010-07-02 12:00:00").as_unit(unit), "b": 2.5}, + index=[0.5], + ) + tm.assert_frame_equal(result, expected) + + # axis = 1 + df["c"] = pd.to_datetime(["2011", "2012"]).as_unit(unit) + result = df[["a", "c"]].quantile(0.5, axis=1, numeric_only=False) + expected = pd.Series( + [pd.Timestamp("2010-07-02 12:00:00"), pd.Timestamp("2011-07-02 12:00:00")], + index=[0, 1], + name=0.5, + dtype=f"M8[{unit}]", + ) + tm.assert_series_equal(result, expected) + + result = df[["a", "c"]].quantile([0.5], axis=1, numeric_only=False) + expected = pd.DataFrame( + [ + [ + pd.Timestamp("2010-07-02 12:00:00"), + pd.Timestamp("2011-07-02 12:00:00"), + ] + ], + index=[0.5], + columns=[0, 1], + dtype=f"M8[{unit}]", + ) + tm.assert_frame_equal(result, expected) + + # empty when numeric_only=True + result = df[["a", "c"]].quantile(0.5, numeric_only=True) + expected = pd.Series( + [], index=pd.Index([], dtype="str"), dtype=np.float64, name=0.5 + ) + tm.assert_series_equal(result, expected) + + result = df[["a", "c"]].quantile([0.5], numeric_only=True) + expected = pd.DataFrame(index=[0.5], columns=pd.Index([], dtype="str")) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "dtype", + [ + "datetime64[ns]", + "datetime64[ns, US/Pacific]", + "timedelta64[ns]", + "Period[D]", + ], + ) + def test_quantile_dt64_empty(self, dtype, interp_method): + # GH#41544 + interpolation, method = interp_method + df = pd.DataFrame(columns=["a", "b"], dtype=dtype) + + res = df.quantile( + 0.5, axis=1, numeric_only=False, interpolation=interpolation, method=method + ) + expected = pd.Series([], index=pd.Index([], dtype="str"), name=0.5, dtype=dtype) + tm.assert_series_equal(res, expected) + + # no columns in result, so no dtype preservation + res = df.quantile( + [0.5], + axis=1, + numeric_only=False, + interpolation=interpolation, + method=method, + ) + expected = pd.DataFrame(index=[0.5], columns=pd.Index([], dtype="str")) + tm.assert_frame_equal(res, expected) + + @pytest.mark.parametrize("invalid", [-1, 2, [0.5, -1], [0.5, 2]]) + def test_quantile_invalid(self, invalid, datetime_frame, interp_method): + msg = "percentiles should all be in the interval \\[0, 1\\]" + interpolation, method = interp_method + with pytest.raises(ValueError, match=msg): + datetime_frame.quantile(invalid, interpolation=interpolation, method=method) + + def test_quantile_box(self, interp_method): + interpolation, method = interp_method + df = pd.DataFrame( + { + "A": [ + pd.Timestamp("2011-01-01"), + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-03"), + ], + "B": [ + pd.Timestamp("2011-01-01", tz="US/Eastern"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.Timestamp("2011-01-03", tz="US/Eastern"), + ], + "C": [ + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + pd.Timedelta("3 days"), + ], + } + ) + + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) + + exp = pd.Series( + [ + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.Timedelta("2 days"), + ], + name=0.5, + index=["A", "B", "C"], + ) + tm.assert_series_equal(res, exp) + + res = df.quantile( + [0.5], numeric_only=False, interpolation=interpolation, method=method + ) + exp = pd.DataFrame( + [ + [ + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.Timedelta("2 days"), + ] + ], + index=[0.5], + columns=["A", "B", "C"], + ) + tm.assert_frame_equal(res, exp) + + def test_quantile_box_nat(self): + # DatetimeLikeBlock may be consolidated and contain NaT in different loc + df = pd.DataFrame( + { + "A": [ + pd.Timestamp("2011-01-01"), + pd.NaT, + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-03"), + ], + "a": [ + pd.Timestamp("2011-01-01"), + pd.Timestamp("2011-01-02"), + pd.NaT, + pd.Timestamp("2011-01-03"), + ], + "B": [ + pd.Timestamp("2011-01-01", tz="US/Eastern"), + pd.NaT, + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.Timestamp("2011-01-03", tz="US/Eastern"), + ], + "b": [ + pd.Timestamp("2011-01-01", tz="US/Eastern"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.NaT, + pd.Timestamp("2011-01-03", tz="US/Eastern"), + ], + "C": [ + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + pd.Timedelta("3 days"), + pd.NaT, + ], + "c": [ + pd.NaT, + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + pd.Timedelta("3 days"), + ], + }, + columns=list("AaBbCc"), + ) + + res = df.quantile(0.5, numeric_only=False) + exp = pd.Series( + [ + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.Timedelta("2 days"), + pd.Timedelta("2 days"), + ], + name=0.5, + index=list("AaBbCc"), + ) + tm.assert_series_equal(res, exp) + + res = df.quantile([0.5], numeric_only=False) + exp = pd.DataFrame( + [ + [ + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.Timedelta("2 days"), + pd.Timedelta("2 days"), + ] + ], + index=[0.5], + columns=list("AaBbCc"), + ) + tm.assert_frame_equal(res, exp) + + def test_quantile_nan(self, interp_method): + interpolation, method = interp_method + # GH 14357 - float block where some cols have missing values + df = pd.DataFrame({"a": np.arange(1, 6.0), "b": np.arange(1, 6.0)}) + df.iloc[-1, 1] = np.nan + + res = df.quantile(0.5, interpolation=interpolation, method=method) + exp = pd.Series( + [3.0, 2.5 if interpolation == "linear" else 3.0], index=["a", "b"], name=0.5 + ) + tm.assert_series_equal(res, exp) + + res = df.quantile([0.5, 0.75], interpolation=interpolation, method=method) + exp = pd.DataFrame( + { + "a": [3.0, 4.0], + "b": [2.5, 3.25] if interpolation == "linear" else [3.0, 4.0], + }, + index=[0.5, 0.75], + ) + tm.assert_frame_equal(res, exp) + + res = df.quantile(0.5, axis=1, interpolation=interpolation, method=method) + exp = pd.Series(np.arange(1.0, 6.0), name=0.5) + tm.assert_series_equal(res, exp) + + res = df.quantile( + [0.5, 0.75], axis=1, interpolation=interpolation, method=method + ) + exp = pd.DataFrame([np.arange(1.0, 6.0)] * 2, index=[0.5, 0.75]) + if interpolation == "nearest": + exp.iloc[1, -1] = np.nan + tm.assert_frame_equal(res, exp) + + # full-nan column + df["b"] = np.nan + + res = df.quantile(0.5, interpolation=interpolation, method=method) + exp = pd.Series([3.0, np.nan], index=["a", "b"], name=0.5) + tm.assert_series_equal(res, exp) + + res = df.quantile([0.5, 0.75], interpolation=interpolation, method=method) + exp = pd.DataFrame({"a": [3.0, 4.0], "b": [np.nan, np.nan]}, index=[0.5, 0.75]) + tm.assert_frame_equal(res, exp) + + def test_quantile_nat(self, interp_method, unit): + interpolation, method = interp_method + # full NaT column + df = pd.DataFrame({"a": [pd.NaT, pd.NaT, pd.NaT]}, dtype=f"M8[{unit}]") + + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) + exp = pd.Series([pd.NaT], index=["a"], name=0.5, dtype=f"M8[{unit}]") + tm.assert_series_equal(res, exp) + + res = df.quantile( + [0.5], numeric_only=False, interpolation=interpolation, method=method + ) + exp = pd.DataFrame({"a": [pd.NaT]}, index=[0.5], dtype=f"M8[{unit}]") + tm.assert_frame_equal(res, exp) + + # mixed non-null / full null column + df = pd.DataFrame( + { + "a": [ + pd.Timestamp("2012-01-01"), + pd.Timestamp("2012-01-02"), + pd.Timestamp("2012-01-03"), + ], + "b": [pd.NaT, pd.NaT, pd.NaT], + }, + dtype=f"M8[{unit}]", + ) + + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) + exp = pd.Series( + [pd.Timestamp("2012-01-02"), pd.NaT], + index=["a", "b"], + name=0.5, + dtype=f"M8[{unit}]", + ) + tm.assert_series_equal(res, exp) + + res = df.quantile( + [0.5], numeric_only=False, interpolation=interpolation, method=method + ) + exp = pd.DataFrame( + [[pd.Timestamp("2012-01-02"), pd.NaT]], + index=[0.5], + columns=["a", "b"], + dtype=f"M8[{unit}]", + ) + tm.assert_frame_equal(res, exp) + + def test_quantile_empty_no_rows_floats(self, interp_method): + interpolation, method = interp_method + + df = pd.DataFrame(columns=["a", "b"], dtype="float64") + + res = df.quantile(0.5, interpolation=interpolation, method=method) + exp = pd.Series([np.nan, np.nan], index=["a", "b"], name=0.5) + tm.assert_series_equal(res, exp) + + res = df.quantile([0.5], interpolation=interpolation, method=method) + exp = pd.DataFrame([[np.nan, np.nan]], columns=["a", "b"], index=[0.5]) + tm.assert_frame_equal(res, exp) + + res = df.quantile(0.5, axis=1, interpolation=interpolation, method=method) + exp = pd.Series([], index=pd.Index([], dtype="str"), dtype="float64", name=0.5) + tm.assert_series_equal(res, exp) + + res = df.quantile([0.5], axis=1, interpolation=interpolation, method=method) + exp = pd.DataFrame(columns=pd.Index([], dtype="str"), index=[0.5]) + tm.assert_frame_equal(res, exp) + + def test_quantile_empty_no_rows_ints(self, interp_method): + interpolation, method = interp_method + df = pd.DataFrame(columns=["a", "b"], dtype="int64") + + res = df.quantile(0.5, interpolation=interpolation, method=method) + exp = pd.Series([np.nan, np.nan], index=["a", "b"], name=0.5) + tm.assert_series_equal(res, exp) + + def test_quantile_empty_no_rows_dt64(self, interp_method): + interpolation, method = interp_method + # datetimes + df = pd.DataFrame(columns=["a", "b"], dtype="datetime64[ns]") + + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) + exp = pd.Series( + [pd.NaT, pd.NaT], index=["a", "b"], dtype="datetime64[ns]", name=0.5 + ) + tm.assert_series_equal(res, exp) + + # Mixed dt64/dt64tz + df["a"] = df["a"].dt.tz_localize("US/Central") + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) + exp = exp.astype(object) + if interpolation == "nearest": + # GH#18463 TODO: would we prefer NaTs here? + exp = exp.fillna(np.nan) + tm.assert_series_equal(res, exp) + + # both dt64tz + df["b"] = df["b"].dt.tz_localize("US/Central") + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) + exp = exp.astype(df["b"].dtype) + tm.assert_series_equal(res, exp) + + def test_quantile_empty_no_columns(self, interp_method): + # GH#23925 _get_numeric_data may drop all columns + interpolation, method = interp_method + df = pd.DataFrame(pd.date_range("1/1/18", periods=5)) + df.columns.name = "captain tightpants" + result = df.quantile( + 0.5, numeric_only=True, interpolation=interpolation, method=method + ) + expected = pd.Series([], name=0.5, dtype=np.float64) + expected.index.name = "captain tightpants" + tm.assert_series_equal(result, expected) + + result = df.quantile( + [0.5], numeric_only=True, interpolation=interpolation, method=method + ) + expected = pd.DataFrame([], index=[0.5]) + expected.columns.name = "captain tightpants" + tm.assert_frame_equal(result, expected) + + def test_invalid_method(self): + with pytest.raises(ValueError, match="Invalid method: foo"): + pd.DataFrame(range(1)).quantile(0.5, method="foo") + + def test_table_invalid_interpolation(self): + with pytest.raises(ValueError, match="Invalid interpolation: foo"): + pd.DataFrame(range(1)).quantile(0.5, method="table", interpolation="foo") + + +class TestQuantileExtensionDtype: + # TODO: tests for axis=1? + # TODO: empty case? + + @pytest.fixture( + params=[ + pytest.param( + pd.IntervalIndex.from_breaks(range(10)), + marks=pytest.mark.xfail(reason="raises when trying to add Intervals"), + ), + pd.period_range("2016-01-01", periods=9, freq="D"), + pd.date_range("2016-01-01", periods=9, tz="US/Pacific"), + pd.timedelta_range("1 Day", periods=9), + pd.array(np.arange(9), dtype="Int64"), + pd.array(np.arange(9), dtype="Float64"), + ], + ids=lambda x: str(x.dtype), + ) + def index(self, request): + # NB: not actually an Index object + idx = request.param + idx.name = "A" + return idx + + @pytest.fixture + def obj(self, index, frame_or_series): + # bc index is not always an Index (yet), we need to re-patch .name + obj = frame_or_series(index).copy() + + if frame_or_series is pd.Series: + obj.name = "A" + else: + obj.columns = ["A"] + return obj + + def compute_quantile(self, obj, qs): + if isinstance(obj, pd.Series): + result = obj.quantile(qs) + else: + result = obj.quantile(qs, numeric_only=False) + return result + + def test_quantile_ea(self, request, obj, index): + # result should be invariant to shuffling + indexer = np.arange(len(index), dtype=np.intp) + np.random.default_rng(2).shuffle(indexer) + obj = obj.iloc[indexer] + + qs = [0.5, 0, 1] + result = self.compute_quantile(obj, qs) + + exp_dtype = index.dtype + if index.dtype == "Int64": + # match non-nullable casting behavior + exp_dtype = "Float64" + + # expected here assumes len(index) == 9 + expected = pd.Series( + [index[4], index[0], index[-1]], dtype=exp_dtype, index=qs, name="A" + ) + expected = type(obj)(expected) + + tm.assert_equal(result, expected) + + def test_quantile_ea_with_na(self, obj, index): + obj.iloc[0] = index._na_value + obj.iloc[-1] = index._na_value + + # result should be invariant to shuffling + indexer = np.arange(len(index), dtype=np.intp) + np.random.default_rng(2).shuffle(indexer) + obj = obj.iloc[indexer] + + qs = [0.5, 0, 1] + result = self.compute_quantile(obj, qs) + + # expected here assumes len(index) == 9 + expected = pd.Series( + [index[4], index[1], index[-2]], dtype=index.dtype, index=qs, name="A" + ) + expected = type(obj)(expected) + tm.assert_equal(result, expected) + + def test_quantile_ea_all_na(self, request, obj, index): + obj.iloc[:] = index._na_value + # Check dtypes were preserved; this was once a problem see GH#39763 + assert np.all(obj.dtypes == index.dtype) + + # result should be invariant to shuffling + indexer = np.arange(len(index), dtype=np.intp) + np.random.default_rng(2).shuffle(indexer) + obj = obj.iloc[indexer] + + qs = [0.5, 0, 1] + result = self.compute_quantile(obj, qs) + + expected = index.take([-1, -1, -1], allow_fill=True, fill_value=index._na_value) + expected = pd.Series(expected, index=qs, name="A") + expected = type(obj)(expected) + tm.assert_equal(result, expected) + + def test_quantile_ea_scalar(self, request, obj, index): + # scalar qs + + # result should be invariant to shuffling + indexer = np.arange(len(index), dtype=np.intp) + np.random.default_rng(2).shuffle(indexer) + obj = obj.iloc[indexer] + + qs = 0.5 + result = self.compute_quantile(obj, qs) + + exp_dtype = index.dtype + if index.dtype == "Int64": + exp_dtype = "Float64" + + expected = pd.Series({"A": index[4]}, dtype=exp_dtype, name=0.5) + if isinstance(obj, pd.Series): + expected = expected["A"] + assert result == expected + else: + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "dtype, expected_data, expected_index, axis", + [ + ["float64", [], [], 1], + ["int64", [], [], 1], + ["float64", [np.nan, np.nan], ["a", "b"], 0], + ["int64", [np.nan, np.nan], ["a", "b"], 0], + ], + ) + def test_empty_numeric(self, dtype, expected_data, expected_index, axis): + # GH 14564 + df = pd.DataFrame(columns=["a", "b"], dtype=dtype) + result = df.quantile(0.5, axis=axis) + expected = pd.Series( + expected_data, + name=0.5, + index=pd.Index(expected_index, dtype="str"), + dtype="float64", + ) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "dtype, expected_data, expected_index, axis, expected_dtype", + [ + ["datetime64[ns]", [], [], 1, "datetime64[ns]"], + ["datetime64[ns]", [pd.NaT, pd.NaT], ["a", "b"], 0, "datetime64[ns]"], + ], + ) + def test_empty_datelike( + self, dtype, expected_data, expected_index, axis, expected_dtype + ): + # GH 14564 + df = pd.DataFrame(columns=["a", "b"], dtype=dtype) + result = df.quantile(0.5, axis=axis, numeric_only=False) + expected = pd.Series( + expected_data, + name=0.5, + index=pd.Index(expected_index, dtype="str"), + dtype=expected_dtype, + ) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "expected_data, expected_index, axis", + [ + [[np.nan, np.nan], range(2), 1], + [[], [], 0], + ], + ) + def test_datelike_numeric_only(self, expected_data, expected_index, axis): + # GH 14564 + df = pd.DataFrame( + { + "a": pd.to_datetime(["2010", "2011"]), + "b": [0, 5], + "c": pd.to_datetime(["2011", "2012"]), + } + ) + result = df[["a", "c"]].quantile(0.5, axis=axis, numeric_only=True) + expected = pd.Series( + expected_data, + name=0.5, + index=pd.Index(expected_index, dtype="str" if axis == 0 else "int64"), + dtype=np.float64, + ) + tm.assert_series_equal(result, expected) + + +def test_multi_quantile_numeric_only_retains_columns(): + df = pd.DataFrame(list("abc")) + result = df.quantile([0.5, 0.7], numeric_only=True) + expected = pd.DataFrame(index=[0.5, 0.7]) + tm.assert_frame_equal( + result, expected, check_index_type=True, check_column_type=True + ) + + +@pytest.mark.parametrize("typ", ["datetime64", "timedelta64"]) +def test_quantile_empty_datetimelike(typ, unit): + dtype = f"{typ}[{unit}]" + df = pd.DataFrame(np.array([], dtype=dtype)) + result = df.quantile() + expected = pd.Series([pd.NaT], name=0.5, dtype=dtype) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_rank.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..800187b7472876f0bae0d336398400109e10ccda --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_rank.py @@ -0,0 +1,498 @@ +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest + +from pandas._libs.algos import ( + Infinity, + NegInfinity, +) + +import pandas as pd +import pandas._testing as tm + + +class TestRank: + s = pd.Series([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3]) + df = pd.DataFrame({"A": s, "B": s}) + + results = { + "average": np.array([1.5, 5.5, 7.0, 3.5, np.nan, 3.5, 1.5, 8.0, np.nan, 5.5]), + "min": np.array([1, 5, 7, 3, np.nan, 3, 1, 8, np.nan, 5]), + "max": np.array([2, 6, 7, 4, np.nan, 4, 2, 8, np.nan, 6]), + "first": np.array([1, 5, 7, 3, np.nan, 4, 2, 8, np.nan, 6]), + "dense": np.array([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3]), + } + + def test_rank(self, float_frame): + sp_stats = pytest.importorskip("scipy.stats") + + float_frame.loc[::2, "A"] = np.nan + float_frame.loc[::3, "B"] = np.nan + float_frame.loc[::4, "C"] = np.nan + float_frame.loc[::5, "D"] = np.nan + + ranks0 = float_frame.rank() + ranks1 = float_frame.rank(1) + mask = np.isnan(float_frame.values) + + fvals = float_frame.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, fvals) + exp0[mask] = np.nan + + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, fvals) + exp1[mask] = np.nan + + tm.assert_almost_equal(ranks0.values, exp0) + tm.assert_almost_equal(ranks1.values, exp1) + + # integers + df = pd.DataFrame( + np.random.default_rng(2).integers(0, 5, size=40).reshape((10, 4)) + ) + + result = df.rank() + exp = df.astype(float).rank() + tm.assert_frame_equal(result, exp) + + result = df.rank(1) + exp = df.astype(float).rank(1) + tm.assert_frame_equal(result, exp) + + def test_rank2(self): + df = pd.DataFrame([[1, 3, 2], [1, 2, 3]]) + expected = pd.DataFrame([[1.0, 3.0, 2.0], [1, 2, 3]]) / 3.0 + result = df.rank(1, pct=True) + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame([[1, 3, 2], [1, 2, 3]]) + expected = df.rank(0) / 2.0 + result = df.rank(0, pct=True) + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame([["b", "c", "a"], ["a", "c", "b"]]) + expected = pd.DataFrame([[2.0, 3.0, 1.0], [1, 3, 2]]) + result = df.rank(1, numeric_only=False) + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame([[2.0, 1.5, 1.0], [1, 1.5, 2]]) + result = df.rank(0, numeric_only=False) + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame([["b", np.nan, "a"], ["a", "c", "b"]]) + expected = pd.DataFrame([[2.0, np.nan, 1.0], [1.0, 3.0, 2.0]]) + result = df.rank(1, numeric_only=False) + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame([[2.0, np.nan, 1.0], [1.0, 1.0, 2.0]]) + result = df.rank(0, numeric_only=False) + tm.assert_frame_equal(result, expected) + + # 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 = pd.DataFrame(data) + + # check the rank + expected = pd.DataFrame([[2.0, np.nan, 1.0], [2.0, 3.0, 1.0]]) + result = df.rank(1, numeric_only=False, ascending=True) + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame([[1.0, np.nan, 2.0], [2.0, 1.0, 3.0]]) + result = df.rank(1, numeric_only=False, ascending=False) + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame({"a": [1e-20, -5, 1e-20 + 1e-40, 10, 1e60, 1e80, 1e-30]}) + exp = pd.DataFrame({"a": [3.5, 1.0, 3.5, 5.0, 6.0, 7.0, 2.0]}) + tm.assert_frame_equal(df.rank(), exp) + + def test_rank_does_not_mutate(self): + # GH#18521 + # Check rank does not mutate DataFrame + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 3)), dtype="float64" + ) + expected = df.copy() + df.rank() + result = df + tm.assert_frame_equal(result, expected) + + def test_rank_mixed_frame(self, float_string_frame): + float_string_frame["datetime"] = datetime(2011, 1, 1) + float_string_frame["timedelta"] = timedelta(days=1, seconds=1) + + float_string_frame.rank(numeric_only=False) + with pytest.raises(TypeError, match="not supported between instances of"): + float_string_frame.rank(axis=1) + + def test_rank_na_option(self, float_frame): + sp_stats = pytest.importorskip("scipy.stats") + + float_frame.loc[::2, "A"] = np.nan + float_frame.loc[::3, "B"] = np.nan + float_frame.loc[::4, "C"] = np.nan + float_frame.loc[::5, "D"] = np.nan + + # bottom + ranks0 = float_frame.rank(na_option="bottom") + ranks1 = float_frame.rank(1, na_option="bottom") + + fvals = float_frame.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, fvals) + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, fvals) + + tm.assert_almost_equal(ranks0.values, exp0) + tm.assert_almost_equal(ranks1.values, exp1) + + # top + ranks0 = float_frame.rank(na_option="top") + ranks1 = float_frame.rank(1, na_option="top") + + fval0 = float_frame.fillna((float_frame.min() - 1).to_dict()).values + fval1 = float_frame.T + fval1 = fval1.fillna((fval1.min() - 1).to_dict()).T + fval1 = fval1.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, fval0) + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, fval1) + + tm.assert_almost_equal(ranks0.values, exp0) + tm.assert_almost_equal(ranks1.values, exp1) + + # descending + + # bottom + ranks0 = float_frame.rank(na_option="top", ascending=False) + ranks1 = float_frame.rank(1, na_option="top", ascending=False) + + fvals = float_frame.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, -fvals) + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, -fvals) + + tm.assert_almost_equal(ranks0.values, exp0) + tm.assert_almost_equal(ranks1.values, exp1) + + # descending + + # top + ranks0 = float_frame.rank(na_option="bottom", ascending=False) + ranks1 = float_frame.rank(1, na_option="bottom", ascending=False) + + fval0 = float_frame.fillna((float_frame.min() - 1).to_dict()).values + fval1 = float_frame.T + fval1 = fval1.fillna((fval1.min() - 1).to_dict()).T + fval1 = fval1.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, -fval0) + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, -fval1) + + tm.assert_numpy_array_equal(ranks0.values, exp0) + tm.assert_numpy_array_equal(ranks1.values, exp1) + + # bad values throw error + msg = "na_option must be one of 'keep', 'top', or 'bottom'" + + with pytest.raises(ValueError, match=msg): + float_frame.rank(na_option="bad", ascending=False) + + # invalid type + with pytest.raises(ValueError, match=msg): + float_frame.rank(na_option=True, ascending=False) + + def test_rank_axis(self): + # check if using axes' names gives the same result + df = pd.DataFrame([[2, 1], [4, 3]]) + tm.assert_frame_equal(df.rank(axis=0), df.rank(axis="index")) + tm.assert_frame_equal(df.rank(axis=1), df.rank(axis="columns")) + + @pytest.mark.parametrize("ax", [0, 1]) + def test_rank_methods_frame(self, ax, rank_method): + sp_stats = pytest.importorskip("scipy.stats") + + xs = np.random.default_rng(2).integers(0, 21, (100, 26)) + xs = (xs - 10.0) / 10.0 + cols = [chr(ord("z") - i) for i in range(xs.shape[1])] + + for vals in [xs, xs + 1e6, xs * 1e-6]: + df = pd.DataFrame(vals, columns=cols) + + result = df.rank(axis=ax, method=rank_method) + sprank = np.apply_along_axis( + sp_stats.rankdata, + ax, + vals, + rank_method if rank_method != "first" else "ordinal", + ) + sprank = sprank.astype(np.float64) + expected = pd.DataFrame(sprank, columns=cols).astype("float64") + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["O", "f8", "i8"]) + def test_rank_descending(self, rank_method, dtype): + if "i" in dtype: + df = self.df.dropna().astype(dtype) + else: + df = self.df.astype(dtype) + + res = df.rank(ascending=False) + expected = (df.max() - df).rank() + tm.assert_frame_equal(res, expected) + + expected = (df.max() - df).rank(method=rank_method) + + if dtype != "O": + res2 = df.rank(method=rank_method, ascending=False, numeric_only=True) + tm.assert_frame_equal(res2, expected) + + res3 = df.rank(method=rank_method, ascending=False, numeric_only=False) + tm.assert_frame_equal(res3, expected) + + @pytest.mark.parametrize("axis", [0, 1]) + @pytest.mark.parametrize("dtype", [None, object]) + def test_rank_2d_tie_methods(self, rank_method, axis, dtype): + df = self.df + + def _check2d(df, expected, method="average", axis=0): + exp_df = pd.DataFrame({"A": expected, "B": expected}) + + if axis == 1: + df = df.T + exp_df = exp_df.T + + result = df.rank(method=rank_method, axis=axis) + tm.assert_frame_equal(result, exp_df) + + frame = df if dtype is None else df.astype(dtype) + _check2d(frame, self.results[rank_method], method=rank_method, axis=axis) + + @pytest.mark.parametrize( + "rank_method,exp", + [ + ("dense", [[1.0, 1.0, 1.0], [1.0, 0.5, 2.0 / 3], [1.0, 0.5, 1.0 / 3]]), + ( + "min", + [ + [1.0 / 3, 1.0, 1.0], + [1.0 / 3, 1.0 / 3, 2.0 / 3], + [1.0 / 3, 1.0 / 3, 1.0 / 3], + ], + ), + ( + "max", + [[1.0, 1.0, 1.0], [1.0, 2.0 / 3, 2.0 / 3], [1.0, 2.0 / 3, 1.0 / 3]], + ), + ( + "average", + [[2.0 / 3, 1.0, 1.0], [2.0 / 3, 0.5, 2.0 / 3], [2.0 / 3, 0.5, 1.0 / 3]], + ), + ( + "first", + [ + [1.0 / 3, 1.0, 1.0], + [2.0 / 3, 1.0 / 3, 2.0 / 3], + [3.0 / 3, 2.0 / 3, 1.0 / 3], + ], + ), + ], + ) + def test_rank_pct_true(self, rank_method, exp): + # see gh-15630. + + df = pd.DataFrame([[2012, 66, 3], [2012, 65, 2], [2012, 65, 1]]) + result = df.rank(method=rank_method, pct=True) + + expected = pd.DataFrame(exp) + tm.assert_frame_equal(result, expected) + + @pytest.mark.single_cpu + def test_pct_max_many_rows(self): + # GH 18271 + df = pd.DataFrame({"A": np.arange(2**24 + 1), "B": np.arange(2**24 + 1, 0, -1)}) + result = df.rank(pct=True).max() + assert (result == 1).all() + + @pytest.mark.parametrize( + "contents,dtype", + [ + ( + [ + -np.inf, + -50, + -1, + -1e-20, + -1e-25, + -1e-50, + 0, + 1e-40, + 1e-20, + 1e-10, + 2, + 40, + np.inf, + ], + "float64", + ), + ( + [ + -np.inf, + -50, + -1, + -1e-20, + -1e-25, + -1e-45, + 0, + 1e-40, + 1e-20, + 1e-10, + 2, + 40, + np.inf, + ], + "float32", + ), + ([np.iinfo(np.uint8).min, 1, 2, 100, np.iinfo(np.uint8).max], "uint8"), + ( + [ + np.iinfo(np.int64).min, + -100, + 0, + 1, + 9999, + 100000, + 1e10, + np.iinfo(np.int64).max, + ], + "int64", + ), + ([NegInfinity(), "1", "A", "BA", "Ba", "C", Infinity()], "object"), + ( + [datetime(2001, 1, 1), datetime(2001, 1, 2), datetime(2001, 1, 5)], + "datetime64", + ), + ], + ) + def test_rank_inf_and_nan(self, contents, dtype, frame_or_series): + dtype_na_map = { + "float64": np.nan, + "float32": np.nan, + "object": None, + "datetime64": np.datetime64("nat", "ns"), + } + # Insert nans at random positions if underlying dtype has missing + # value. Then adjust the expected order by adding nans accordingly + # This is for testing whether rank calculation is affected + # when values are intertwined with nan values. + values = np.array(contents, dtype=dtype) + exp_order = np.array(range(len(values)), dtype="float64") + 1.0 + if dtype in dtype_na_map: + na_value = dtype_na_map[dtype] + nan_indices = np.random.default_rng(2).choice(range(len(values)), 5) + values = np.insert(values, nan_indices, na_value) + exp_order = np.insert(exp_order, nan_indices, np.nan) + + # Shuffle the testing array and expected results in the same way + random_order = np.random.default_rng(2).permutation(len(values)) + obj = frame_or_series(values[random_order]) + expected = frame_or_series(exp_order[random_order], dtype="float64") + result = obj.rank() + tm.assert_equal(result, expected) + + def test_df_series_inf_nan_consistency(self): + # GH#32593 + index = [5, 4, 3, 2, 1, 6, 7, 8, 9, 10] + col1 = [5, 4, 3, 5, 8, 5, 2, 1, 6, 6] + col2 = [5, 4, np.nan, 5, 8, 5, np.inf, np.nan, 6, -np.inf] + df = pd.DataFrame( + data={ + "col1": col1, + "col2": col2, + }, + index=index, + dtype="f8", + ) + df_result = df.rank() + + series_result = df.copy() + series_result["col1"] = df["col1"].rank() + series_result["col2"] = df["col2"].rank() + + tm.assert_frame_equal(df_result, series_result) + + def test_rank_both_inf(self): + # GH#32593 + df = pd.DataFrame({"a": [-np.inf, 0, np.inf]}) + expected = pd.DataFrame({"a": [1.0, 2.0, 3.0]}) + result = df.rank() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "na_option,ascending,expected", + [ + ("top", True, [3.0, 1.0, 2.0]), + ("top", False, [2.0, 1.0, 3.0]), + ("bottom", True, [2.0, 3.0, 1.0]), + ("bottom", False, [1.0, 3.0, 2.0]), + ], + ) + def test_rank_inf_nans_na_option( + self, frame_or_series, rank_method, na_option, ascending, expected + ): + obj = frame_or_series([np.inf, np.nan, -np.inf]) + result = obj.rank(method=rank_method, na_option=na_option, ascending=ascending) + expected = frame_or_series(expected) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize( + "na_option,ascending,expected", + [ + ("bottom", True, [1.0, 2.0, 4.0, 3.0]), + ("bottom", False, [1.0, 2.0, 4.0, 3.0]), + ("top", True, [2.0, 3.0, 1.0, 4.0]), + ("top", False, [2.0, 3.0, 1.0, 4.0]), + ], + ) + def test_rank_object_first(self, frame_or_series, na_option, ascending, expected): + obj = frame_or_series(["foo", "foo", None, "foo"]) + result = obj.rank(method="first", na_option=na_option, ascending=ascending) + expected = frame_or_series(expected) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize( + "data,expected", + [ + ( + {"a": [1, 2, "a"], "b": [4, 5, 6]}, + pd.DataFrame( + {"b": [1.0, 2.0, 3.0]}, columns=pd.Index(["b"], dtype=object) + ), + ), + ({"a": [1, 2, "a"]}, pd.DataFrame(index=range(3), columns=[])), + ], + ) + def test_rank_mixed_axis_zero(self, data, expected): + df = pd.DataFrame(data, columns=pd.Index(list(data.keys()), dtype=object)) + with pytest.raises(TypeError, match="'<' not supported between instances of"): + df.rank() + result = df.rank(numeric_only=True) + tm.assert_frame_equal(result, expected) + + def test_rank_string_dtype(self, string_dtype_no_object): + # GH#55362 + obj = pd.Series(["foo", "foo", None, "foo"], dtype=string_dtype_no_object) + result = obj.rank(method="first") + exp_dtype = ( + "Float64" if string_dtype_no_object == "string[pyarrow]" else "float64" + ) + if string_dtype_no_object.storage == "python": + # TODO nullable string[python] should also return nullable Int64 + exp_dtype = "float64" + expected = pd.Series([1, 2, None, 3], dtype=exp_dtype) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reindex.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reindex.py new file mode 100644 index 0000000000000000000000000000000000000000..8f965a486d7169183a7abf8c8278c550a59fe85a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reindex.py @@ -0,0 +1,1316 @@ +from datetime import ( + datetime, + timedelta, +) +import inspect + +import numpy as np +import pytest + +from pandas._libs.tslibs.timezones import dateutil_gettz as gettz +from pandas.compat import IS64 +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.api.types import CategoricalDtype + + +class TestReindexSetIndex: + # Tests that check both reindex and set_index + + def test_dti_set_index_reindex_datetimeindex(self): + # GH#6631 + df = pd.DataFrame(np.random.default_rng(2).random(6)) + idx1 = pd.date_range("2011/01/01", periods=6, freq="ME", tz="US/Eastern") + idx2 = pd.date_range("2013", periods=6, freq="YE", tz="Asia/Tokyo") + + df = df.set_index(idx1) + tm.assert_index_equal(df.index, idx1) + df = df.reindex(idx2) + tm.assert_index_equal(df.index, idx2) + + def test_dti_set_index_reindex_freq_with_tz(self): + # GH#11314 with tz + index = pd.date_range( + datetime(2015, 10, 1), datetime(2015, 10, 1, 23), freq="h", tz="US/Eastern" + ) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((24, 1)), + columns=["a"], + index=index, + ) + new_index = pd.date_range( + datetime(2015, 10, 2), datetime(2015, 10, 2, 23), freq="h", tz="US/Eastern" + ) + + result = df.set_index(new_index) + assert result.index.freq == index.freq + + def test_set_reset_index_intervalindex(self): + df = pd.DataFrame({"A": range(10)}) + ser = pd.cut(df.A, 5) + df["B"] = ser + df = df.set_index("B") + + df = df.reset_index() + + def test_setitem_reset_index_dtypes(self): + # GH 22060 + df = pd.DataFrame(columns=["a", "b", "c"]).astype( + {"a": "datetime64[ns]", "b": np.int64, "c": np.float64} + ) + df1 = df.set_index(["a"]) + df1["d"] = [] + result = df1.reset_index() + expected = pd.DataFrame(columns=["a", "b", "c", "d"], index=range(0)).astype( + {"a": "datetime64[ns]", "b": np.int64, "c": np.float64, "d": np.float64} + ) + tm.assert_frame_equal(result, expected) + + df2 = df.set_index(["a", "b"]) + df2["d"] = [] + result = df2.reset_index() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "timezone, year, month, day, hour", + [["America/Chicago", 2013, 11, 3, 1], ["America/Santiago", 2021, 4, 3, 23]], + ) + def test_reindex_timestamp_with_fold(self, timezone, year, month, day, hour): + # see gh-40817 + test_timezone = gettz(timezone) + transition_1 = pd.Timestamp( + year=year, + month=month, + day=day, + hour=hour, + minute=0, + fold=0, + tzinfo=test_timezone, + ) + transition_2 = pd.Timestamp( + year=year, + month=month, + day=day, + hour=hour, + minute=0, + fold=1, + tzinfo=test_timezone, + ) + df = ( + pd.DataFrame({"index": [transition_1, transition_2], "vals": ["a", "b"]}) + .set_index("index") + .reindex(["1", "2"]) + ) + exp = pd.DataFrame({"index": ["1", "2"], "vals": [np.nan, np.nan]}).set_index( + "index" + ) + exp = exp.astype(df.vals.dtype) + tm.assert_frame_equal( + df, + exp, + ) + + +class TestDataFrameSelectReindex: + # These are specific reindex-based tests; other indexing tests should go in + # test_indexing + + @pytest.mark.xfail( + not IS64, + reason="Passes int32 values to DatetimeArray in make_na_array on " + "windows, 32bit linux builds", + ) + def test_reindex_tzaware_fill_value(self): + # GH#52586 + df = pd.DataFrame([[1]]) + + ts = pd.Timestamp("2023-04-10 17:32", tz="US/Pacific").as_unit("s") + res = df.reindex([0, 1], axis=1, fill_value=ts) + assert res.dtypes[1] == pd.DatetimeTZDtype(unit="s", tz="US/Pacific") + expected = pd.DataFrame({0: [1], 1: [ts]}) + expected[1] = expected[1].astype(res.dtypes[1]) + tm.assert_frame_equal(res, expected) + + per = ts.tz_localize(None).to_period("s") + res = df.reindex([0, 1], axis=1, fill_value=per) + assert res.dtypes[1] == pd.PeriodDtype("s") + expected = pd.DataFrame({0: [1], 1: [per]}) + tm.assert_frame_equal(res, expected) + + interval = pd.Interval(ts, ts + pd.Timedelta(seconds=1)) + res = df.reindex([0, 1], axis=1, fill_value=interval) + assert res.dtypes[1] == pd.IntervalDtype("datetime64[s, US/Pacific]", "right") + expected = pd.DataFrame({0: [1], 1: [interval]}) + expected[1] = expected[1].astype(res.dtypes[1]) + tm.assert_frame_equal(res, expected) + + def test_reindex_date_fill_value(self): + # passing date to dt64 is deprecated; enforced in 2.0 to cast to object + arr = pd.date_range("2016-01-01", periods=6, unit="ns").values.reshape(3, 2) + df = pd.DataFrame(arr, columns=["A", "B"], index=range(3)) + + ts = df.iloc[0, 0] + fv = ts.date() + + msg = "reindexing with a fill_value that cannot be held" + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + res = df.reindex(index=range(4), columns=["A", "B", "C"], fill_value=fv) + + expected = pd.DataFrame( + {"A": [*df["A"].tolist(), fv], "B": [*df["B"].tolist(), fv], "C": [fv] * 4}, + dtype=object, + ) + tm.assert_frame_equal(res, expected) + + # only reindexing rows + with tm.assert_produces_warning(Pandas4Warning, match=msg): + res = df.reindex(index=range(4), fill_value=fv) + tm.assert_frame_equal(res, expected[["A", "B"]]) + + # same with a datetime-castable str + res = df.reindex( + index=range(4), columns=["A", "B", "C"], fill_value="2016-01-01" + ) + expected = pd.DataFrame( + {"A": [*df["A"].tolist(), ts], "B": [*df["B"].tolist(), ts], "C": [ts] * 4}, + ) + tm.assert_frame_equal(res, expected) + + def test_reindex_with_multi_index(self): + # https://github.com/pandas-dev/pandas/issues/29896 + # tests for reindexing a multi-indexed DataFrame with a new MultiIndex + # + # confirms that we can reindex a multi-indexed DataFrame with a new + # MultiIndex object correctly when using no filling, backfilling, and + # padding + # + # The DataFrame, `df`, used in this test is: + # c + # a b + # -1 0 A + # 1 B + # 2 C + # 3 D + # 4 E + # 5 F + # 6 G + # 0 0 A + # 1 B + # 2 C + # 3 D + # 4 E + # 5 F + # 6 G + # 1 0 A + # 1 B + # 2 C + # 3 D + # 4 E + # 5 F + # 6 G + # + # and the other MultiIndex, `new_multi_index`, is: + # 0: 0 0.5 + # 1: 2.0 + # 2: 5.0 + # 3: 5.8 + df = pd.DataFrame( + { + "a": [-1] * 7 + [0] * 7 + [1] * 7, + "b": list(range(7)) * 3, + "c": ["A", "B", "C", "D", "E", "F", "G"] * 3, + } + ).set_index(["a", "b"]) + new_index = [0.5, 2.0, 5.0, 5.8] + new_multi_index = pd.MultiIndex.from_product([[0], new_index], names=["a", "b"]) + + # reindexing w/o a `method` value + reindexed = df.reindex(new_multi_index) + expected = pd.DataFrame( + {"a": [0] * 4, "b": new_index, "c": [np.nan, "C", "F", np.nan]} + ).set_index(["a", "b"]) + tm.assert_frame_equal(expected, reindexed) + + # reindexing with backfilling + expected = pd.DataFrame( + {"a": [0] * 4, "b": new_index, "c": ["B", "C", "F", "G"]} + ).set_index(["a", "b"]) + reindexed_with_backfilling = df.reindex(new_multi_index, method="bfill") + tm.assert_frame_equal(expected, reindexed_with_backfilling) + + reindexed_with_backfilling = df.reindex(new_multi_index, method="backfill") + tm.assert_frame_equal(expected, reindexed_with_backfilling) + + # reindexing with padding + expected = pd.DataFrame( + {"a": [0] * 4, "b": new_index, "c": ["A", "C", "F", "F"]} + ).set_index(["a", "b"]) + reindexed_with_padding = df.reindex(new_multi_index, method="pad") + tm.assert_frame_equal(expected, reindexed_with_padding) + + reindexed_with_padding = df.reindex(new_multi_index, method="ffill") + tm.assert_frame_equal(expected, reindexed_with_padding) + + @pytest.mark.parametrize( + "method,expected_values", + [ + ("nearest", [0, 1, 1, 2]), + ("pad", [np.nan, 0, 1, 1]), + ("backfill", [0, 1, 2, 2]), + ], + ) + def test_reindex_methods(self, method, expected_values): + df = pd.DataFrame({"x": list(range(5))}) + target = np.array([-0.1, 0.9, 1.1, 1.5]) + + expected = pd.DataFrame({"x": expected_values}, index=target) + actual = df.reindex(target, method=method) + tm.assert_frame_equal(expected, actual) + + actual = df.reindex(target, method=method, tolerance=1) + tm.assert_frame_equal(expected, actual) + actual = df.reindex(target, method=method, tolerance=[1, 1, 1, 1]) + tm.assert_frame_equal(expected, actual) + + e2 = expected[::-1] + actual = df.reindex(target[::-1], method=method) + tm.assert_frame_equal(e2, actual) + + new_order = [3, 0, 2, 1] + e2 = expected.iloc[new_order] + actual = df.reindex(target[new_order], method=method) + tm.assert_frame_equal(e2, actual) + + switched_method = ( + "pad" if method == "backfill" else "backfill" if method == "pad" else method + ) + actual = df[::-1].reindex(target, method=switched_method) + tm.assert_frame_equal(expected, actual) + + def test_reindex_methods_nearest_special(self): + df = pd.DataFrame({"x": list(range(5))}) + target = np.array([-0.1, 0.9, 1.1, 1.5]) + + expected = pd.DataFrame({"x": [0, 1, 1, np.nan]}, index=target) + actual = df.reindex(target, method="nearest", tolerance=0.2) + tm.assert_frame_equal(expected, actual) + + expected = pd.DataFrame({"x": [0, np.nan, 1, np.nan]}, index=target) + actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1]) + tm.assert_frame_equal(expected, actual) + + def test_reindex_nearest_tz(self, tz_aware_fixture): + # GH26683 + tz = tz_aware_fixture + idx = pd.date_range("2019-01-01", periods=5, tz=tz) + df = pd.DataFrame({"x": list(range(5))}, index=idx) + + expected = df.head(3) + actual = df.reindex(idx[:3], method="nearest") + tm.assert_frame_equal(expected, actual) + + def test_reindex_nearest_tz_empty_frame(self): + # https://github.com/pandas-dev/pandas/issues/31964 + dti = pd.DatetimeIndex(["2016-06-26 14:27:26+00:00"]) + df = pd.DataFrame(index=pd.DatetimeIndex(["2016-07-04 14:00:59+00:00"])) + expected = pd.DataFrame(index=dti) + result = df.reindex(dti, method="nearest") + tm.assert_frame_equal(result, expected) + + def test_reindex_frame_add_nat(self): + rng = pd.date_range("1/1/2000 00:00:00", periods=10, freq="10s") + df = pd.DataFrame( + {"A": np.random.default_rng(2).standard_normal(len(rng)), "B": rng} + ) + + result = df.reindex(range(15)) + assert np.issubdtype(result["B"].dtype, np.dtype("M8[ns]")) + + mask = pd.isna(result)["B"] + assert mask[-5:].all() + assert not mask[:-5].any() + + @pytest.mark.parametrize( + "method, exp_values", + [("ffill", [0, 1, 2, 3]), ("bfill", [1.0, 2.0, 3.0, np.nan])], + ) + def test_reindex_frame_tz_ffill_bfill(self, frame_or_series, method, exp_values): + # GH#38566 + obj = frame_or_series( + [0, 1, 2, 3], + index=pd.date_range("2020-01-01 00:00:00", periods=4, freq="h", tz="UTC"), + ) + new_index = pd.date_range("2020-01-01 00:01:00", periods=4, freq="h", tz="UTC") + result = obj.reindex(new_index, method=method, tolerance=pd.Timedelta("1 hour")) + expected = frame_or_series(exp_values, index=new_index) + tm.assert_equal(result, expected) + + def test_reindex_limit(self): + # GH 28631 + data = [["A", "A", "A"], ["B", "B", "B"], ["C", "C", "C"], ["D", "D", "D"]] + exp_data = [ + ["A", "A", "A"], + ["B", "B", "B"], + ["C", "C", "C"], + ["D", "D", "D"], + ["D", "D", "D"], + [np.nan, np.nan, np.nan], + ] + df = pd.DataFrame(data) + result = df.reindex([0, 1, 2, 3, 4, 5], method="ffill", limit=1) + expected = pd.DataFrame(exp_data) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "idx, check_index_type", + [ + [["C", "B", "A"], True], + [["F", "C", "A", "D"], True], + [["A"], True], + [["A", "B", "C"], True], + [["C", "A", "B"], True], + [["C", "B"], True], + [["C", "A"], True], + [["A", "B"], True], + [["B", "A", "C"], True], + # reindex by these causes different MultiIndex levels + [["D", "F"], False], + [["A", "C", "B"], False], + ], + ) + def test_reindex_level_verify_first_level(self, idx, check_index_type): + df = pd.DataFrame( + { + "jim": list("B" * 4 + "A" * 2 + "C" * 3), + "joe": list("abcdeabcd")[::-1], + "jolie": [10, 20, 30] * 3, + "joline": np.random.default_rng(2).integers(0, 1000, 9), + } + ) + icol = ["jim", "joe", "jolie"] + + def f(val): + return np.nonzero((df["jim"] == val).to_numpy())[0] + + i = np.concatenate(list(map(f, idx))) + left = df.set_index(icol).reindex(idx, level="jim") + right = df.iloc[i].set_index(icol) + tm.assert_frame_equal(left, right, check_index_type=check_index_type) + + @pytest.mark.parametrize( + "idx", + [ + ("mid",), + ("mid", "btm"), + ("mid", "btm", "top"), + ("mid", "top"), + ("mid", "top", "btm"), + ("btm",), + ("btm", "mid"), + ("btm", "mid", "top"), + ("btm", "top"), + ("btm", "top", "mid"), + ("top",), + ("top", "mid"), + ("top", "mid", "btm"), + ("top", "btm"), + ("top", "btm", "mid"), + ], + ) + def test_reindex_level_verify_first_level_repeats(self, idx): + df = pd.DataFrame( + { + "jim": ["mid"] * 5 + ["btm"] * 8 + ["top"] * 7, + "joe": ["3rd"] * 2 + + ["1st"] * 3 + + ["2nd"] * 3 + + ["1st"] * 2 + + ["3rd"] * 3 + + ["1st"] * 2 + + ["3rd"] * 3 + + ["2nd"] * 2, + # this needs to be jointly unique with jim and joe or + # reindexing will fail ~1.5% of the time, this works + # out to needing unique groups of same size as joe + "jolie": np.concatenate( + [ + np.random.default_rng(2).choice(1000, x, replace=False) + for x in [2, 3, 3, 2, 3, 2, 3, 2] + ] + ), + "joline": np.random.default_rng(2).standard_normal(20).round(3) * 10, + } + ) + icol = ["jim", "joe", "jolie"] + + def f(val): + return np.nonzero((df["jim"] == val).to_numpy())[0] + + i = np.concatenate(list(map(f, idx))) + left = df.set_index(icol).reindex(idx, level="jim") + right = df.iloc[i].set_index(icol) + tm.assert_frame_equal(left, right) + + @pytest.mark.parametrize( + "idx, indexer", + [ + [ + ["1st", "2nd", "3rd"], + [2, 3, 4, 0, 1, 8, 9, 5, 6, 7, 10, 11, 12, 13, 14, 18, 19, 15, 16, 17], + ], + [ + ["3rd", "2nd", "1st"], + [0, 1, 2, 3, 4, 10, 11, 12, 5, 6, 7, 8, 9, 15, 16, 17, 18, 19, 13, 14], + ], + [["2nd", "3rd"], [0, 1, 5, 6, 7, 10, 11, 12, 18, 19, 15, 16, 17]], + [["3rd", "1st"], [0, 1, 2, 3, 4, 10, 11, 12, 8, 9, 15, 16, 17, 13, 14]], + ], + ) + def test_reindex_level_verify_repeats(self, idx, indexer): + df = pd.DataFrame( + { + "jim": ["mid"] * 5 + ["btm"] * 8 + ["top"] * 7, + "joe": ["3rd"] * 2 + + ["1st"] * 3 + + ["2nd"] * 3 + + ["1st"] * 2 + + ["3rd"] * 3 + + ["1st"] * 2 + + ["3rd"] * 3 + + ["2nd"] * 2, + # this needs to be jointly unique with jim and joe or + # reindexing will fail ~1.5% of the time, this works + # out to needing unique groups of same size as joe + "jolie": np.concatenate( + [ + np.random.default_rng(2).choice(1000, x, replace=False) + for x in [2, 3, 3, 2, 3, 2, 3, 2] + ] + ), + "joline": np.random.default_rng(2).standard_normal(20).round(3) * 10, + } + ) + icol = ["jim", "joe", "jolie"] + left = df.set_index(icol).reindex(idx, level="joe") + right = df.iloc[indexer].set_index(icol) + tm.assert_frame_equal(left, right) + + @pytest.mark.parametrize( + "idx, indexer, check_index_type", + [ + [list("abcde"), [3, 2, 1, 0, 5, 4, 8, 7, 6], True], + [list("abcd"), [3, 2, 1, 0, 5, 8, 7, 6], True], + [list("abc"), [3, 2, 1, 8, 7, 6], True], + [list("eca"), [1, 3, 4, 6, 8], True], + [list("edc"), [0, 1, 4, 5, 6], True], + [list("eadbc"), [3, 0, 2, 1, 4, 5, 8, 7, 6], True], + [list("edwq"), [0, 4, 5], True], + [list("wq"), [], False], + ], + ) + def test_reindex_level_verify(self, idx, indexer, check_index_type): + df = pd.DataFrame( + { + "jim": list("B" * 4 + "A" * 2 + "C" * 3), + "joe": list("abcdeabcd")[::-1], + "jolie": [10, 20, 30] * 3, + "joline": np.random.default_rng(2).integers(0, 1000, 9), + } + ) + icol = ["jim", "joe", "jolie"] + left = df.set_index(icol).reindex(idx, level="joe") + right = df.iloc[indexer].set_index(icol) + tm.assert_frame_equal(left, right, check_index_type=check_index_type) + + def test_non_monotonic_reindex_methods(self): + dr = pd.date_range("2013-08-01", periods=6, freq="B") + data = np.random.default_rng(2).standard_normal((6, 1)) + df = pd.DataFrame(data, index=dr, columns=list("A")) + df_rev = pd.DataFrame(data, index=dr[[3, 4, 5, 0, 1, 2]], columns=list("A")) + # index is not monotonic increasing or decreasing + msg = "index must be monotonic increasing or decreasing" + with pytest.raises(ValueError, match=msg): + df_rev.reindex(df.index, method="pad") + with pytest.raises(ValueError, match=msg): + df_rev.reindex(df.index, method="ffill") + with pytest.raises(ValueError, match=msg): + df_rev.reindex(df.index, method="bfill") + with pytest.raises(ValueError, match=msg): + df_rev.reindex(df.index, method="nearest") + + def test_reindex_sparse(self): + # https://github.com/pandas-dev/pandas/issues/35286 + df = pd.DataFrame( + {"A": [0, 1], "B": pd.array([0, 1], dtype=pd.SparseDtype("int64", 0))} + ) + result = df.reindex([0, 2]) + expected = pd.DataFrame( + { + "A": [0.0, np.nan], + "B": pd.array([0.0, np.nan], dtype=pd.SparseDtype("float64", 0.0)), + }, + index=[0, 2], + ) + tm.assert_frame_equal(result, expected) + + def test_reindex(self, float_frame): + datetime_series = pd.Series( + np.arange(30, dtype=np.float64), + index=pd.date_range("2020-01-01", periods=30), + ) + + newFrame = float_frame.reindex(datetime_series.index) + + for col in newFrame.columns: + for idx, val in newFrame[col].items(): + if idx in float_frame.index: + if np.isnan(val): + assert np.isnan(float_frame[col][idx]) + else: + assert val == float_frame[col][idx] + else: + assert np.isnan(val) + + for col, series in newFrame.items(): + tm.assert_index_equal(series.index, newFrame.index) + emptyFrame = float_frame.reindex(pd.Index([])) + assert len(emptyFrame.index) == 0 + + # Cython code should be unit-tested directly + nonContigFrame = float_frame.reindex(datetime_series.index[::2]) + + for col in nonContigFrame.columns: + for idx, val in nonContigFrame[col].items(): + if idx in float_frame.index: + if np.isnan(val): + assert np.isnan(float_frame[col][idx]) + else: + assert val == float_frame[col][idx] + else: + assert np.isnan(val) + + for col, series in nonContigFrame.items(): + tm.assert_index_equal(series.index, nonContigFrame.index) + + # corner cases + newFrame = float_frame.reindex(float_frame.index) + assert newFrame.index.is_(float_frame.index) + + # length zero + newFrame = float_frame.reindex([]) + assert newFrame.empty + assert len(newFrame.columns) == len(float_frame.columns) + + # length zero with columns reindexed with non-empty index + newFrame = float_frame.reindex([]) + newFrame = newFrame.reindex(float_frame.index) + assert len(newFrame.index) == len(float_frame.index) + assert len(newFrame.columns) == len(float_frame.columns) + + # pass non-Index + newFrame = float_frame.reindex(list(datetime_series.index)) + expected = datetime_series.index._with_freq(None) + tm.assert_index_equal(newFrame.index, expected) + + # copy with no axes + result = float_frame.reindex() + tm.assert_frame_equal(result, float_frame) + assert result is not float_frame + + def test_reindex_nan(self): + df = pd.DataFrame( + [[1, 2], [3, 5], [7, 11], [9, 23]], + index=[2, np.nan, 1, 5], + columns=["joe", "jim"], + ) + + i, j = [np.nan, 5, 5, np.nan, 1, 2, np.nan], [1, 3, 3, 1, 2, 0, 1] + tm.assert_frame_equal(df.reindex(i), df.iloc[j]) + + df.index = df.index.astype("object") + tm.assert_frame_equal(df.reindex(i), df.iloc[j], check_index_type=False) + + # GH10388 + df = pd.DataFrame( + { + "other": ["a", "b", np.nan, "c"], + "date": ["2015-03-22", np.nan, "2012-01-08", np.nan], + "amount": [2, 3, 4, 5], + } + ) + + df["date"] = pd.to_datetime(df.date) + df["delta"] = (pd.to_datetime("2015-06-18") - df["date"]).shift(1) + + left = df.set_index(["delta", "other", "date"]).reset_index() + right = df.reindex(columns=["delta", "other", "date", "amount"]) + tm.assert_frame_equal(left, right) + + def test_reindex_name_remains(self): + s = pd.Series(np.random.default_rng(2).random(10)) + df = pd.DataFrame(s, index=np.arange(len(s))) + i = pd.Series(np.arange(10), name="iname") + + df = df.reindex(i) + assert df.index.name == "iname" + + df = df.reindex(pd.Index(np.arange(10), name="tmpname")) + assert df.index.name == "tmpname" + + s = pd.Series(np.random.default_rng(2).random(10)) + df = pd.DataFrame(s.T, index=np.arange(len(s))) + i = pd.Series(np.arange(10), name="iname") + df = df.reindex(columns=i) + assert df.columns.name == "iname" + + def test_reindex_int(self, int_frame): + smaller = int_frame.reindex(int_frame.index[::2]) + + assert smaller["A"].dtype == np.int64 + + bigger = smaller.reindex(int_frame.index) + assert bigger["A"].dtype == np.float64 + + smaller = int_frame.reindex(columns=["A", "B"]) + assert smaller["A"].dtype == np.int64 + + def test_reindex_columns(self, float_frame): + new_frame = float_frame.reindex(columns=["A", "B", "E"]) + + tm.assert_series_equal(new_frame["B"], float_frame["B"]) + assert np.isnan(new_frame["E"]).all() + assert "C" not in new_frame + + # Length zero + new_frame = float_frame.reindex(columns=[]) + assert new_frame.empty + + def test_reindex_columns_method(self): + # GH 14992, reindexing over columns ignored method + df = pd.DataFrame( + data=[[11, 12, 13], [21, 22, 23], [31, 32, 33]], + index=[1, 2, 4], + columns=[1, 2, 4], + dtype=float, + ) + + # default method + result = df.reindex(columns=range(6)) + expected = pd.DataFrame( + data=[ + [np.nan, 11, 12, np.nan, 13, np.nan], + [np.nan, 21, 22, np.nan, 23, np.nan], + [np.nan, 31, 32, np.nan, 33, np.nan], + ], + index=[1, 2, 4], + columns=range(6), + dtype=float, + ) + tm.assert_frame_equal(result, expected) + + # method='ffill' + result = df.reindex(columns=range(6), method="ffill") + expected = pd.DataFrame( + data=[ + [np.nan, 11, 12, 12, 13, 13], + [np.nan, 21, 22, 22, 23, 23], + [np.nan, 31, 32, 32, 33, 33], + ], + index=[1, 2, 4], + columns=range(6), + dtype=float, + ) + tm.assert_frame_equal(result, expected) + + # method='bfill' + result = df.reindex(columns=range(6), method="bfill") + expected = pd.DataFrame( + data=[ + [11, 11, 12, 13, 13, np.nan], + [21, 21, 22, 23, 23, np.nan], + [31, 31, 32, 33, 33, np.nan], + ], + index=[1, 2, 4], + columns=range(6), + dtype=float, + ) + tm.assert_frame_equal(result, expected) + + def test_reindex_axes(self): + # GH 3317, reindexing by both axes loses freq of the index + df = pd.DataFrame( + np.ones((3, 3)), + index=[datetime(2012, 1, 1), datetime(2012, 1, 2), datetime(2012, 1, 3)], + columns=["a", "b", "c"], + ) + + msg = "'d' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(Pandas4Warning, match=msg): + time_freq = pd.date_range("2012-01-01", "2012-01-03", freq="d") + some_cols = ["a", "b"] + + index_freq = df.reindex(index=time_freq).index.freq + both_freq = df.reindex(index=time_freq, columns=some_cols).index.freq + seq_freq = df.reindex(index=time_freq).reindex(columns=some_cols).index.freq + assert index_freq == both_freq + assert index_freq == seq_freq + + def test_reindex_fill_value(self): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 4))) + + # axis=0 + result = df.reindex(list(range(15))) + assert np.isnan(result.values[-5:]).all() + + result = df.reindex(range(15), fill_value=0) + expected = df.reindex(range(15)).fillna(0) + tm.assert_frame_equal(result, expected) + + # axis=1 + result = df.reindex(columns=range(5), fill_value=0.0) + expected = df.copy() + expected[4] = 0.0 + tm.assert_frame_equal(result, expected) + + result = df.reindex(columns=range(5), fill_value=0) + expected = df.copy() + expected[4] = 0 + tm.assert_frame_equal(result, expected) + + result = df.reindex(columns=range(5), fill_value="foo") + expected = df.copy() + expected[4] = "foo" + tm.assert_frame_equal(result, expected) + + # other dtypes + df["foo"] = "foo" + msg = "reindexing with a fill_value that cannot be held" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.reindex(range(15), fill_value="0") + # GH#45153 filling float with string is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + expected = df.reindex(range(15)).fillna("0") + tm.assert_frame_equal(result, expected) + + def test_reindex_uint_dtypes_fill_value(self, any_unsigned_int_numpy_dtype): + # GH#48184 + df = pd.DataFrame( + {"a": [1, 2], "b": [1, 2]}, dtype=any_unsigned_int_numpy_dtype + ) + result = df.reindex(columns=list("abcd"), index=[0, 1, 2, 3], fill_value=10) + expected = pd.DataFrame( + {"a": [1, 2, 10, 10], "b": [1, 2, 10, 10], "c": 10, "d": 10}, + dtype=any_unsigned_int_numpy_dtype, + ) + tm.assert_frame_equal(result, expected) + + def test_reindex_single_column_ea_index_and_columns(self, any_numeric_ea_dtype): + # GH#48190 + df = pd.DataFrame({"a": [1, 2]}, dtype=any_numeric_ea_dtype) + result = df.reindex(columns=list("ab"), index=[0, 1, 2], fill_value=10) + expected = pd.DataFrame( + {"a": pd.Series([1, 2, 10], dtype=any_numeric_ea_dtype), "b": 10} + ) + tm.assert_frame_equal(result, expected) + + def test_reindex_with_string_fill_value(self): + # GH#63993 + df = pd.DataFrame({"a": [0]}) + result = df.reindex(columns=["a", "b", "c"], fill_value="missing") + expected = pd.DataFrame({"a": [0], "b": ["missing"], "c": ["missing"]}) + tm.assert_frame_equal(result, expected) + + def test_reindex_dups(self): + # GH4746, reindex on duplicate index error messages + arr = np.random.default_rng(2).standard_normal(10) + df = pd.DataFrame(arr, index=[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]) + + # set index is ok + result = df.copy() + result.index = list(range(len(df))) + expected = pd.DataFrame(arr, index=list(range(len(df)))) + tm.assert_frame_equal(result, expected) + + # reindex fails + msg = "cannot reindex on an axis with duplicate labels" + with pytest.raises(ValueError, match=msg): + df.reindex(index=list(range(len(df)))) + + def test_reindex_with_duplicate_columns(self): + # reindex is invalid! + df = pd.DataFrame( + [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"] + ) + msg = "cannot reindex on an axis with duplicate labels" + with pytest.raises(ValueError, match=msg): + df.reindex(columns=["bar"]) + with pytest.raises(ValueError, match=msg): + df.reindex(columns=["bar", "foo"]) + + def test_reindex_axis_style(self): + # https://github.com/pandas-dev/pandas/issues/12392 + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + expected = pd.DataFrame( + {"A": [1, 2, np.nan], "B": [4, 5, np.nan]}, index=[0, 1, 3] + ) + result = df.reindex([0, 1, 3]) + tm.assert_frame_equal(result, expected) + + result = df.reindex([0, 1, 3], axis=0) + tm.assert_frame_equal(result, expected) + + result = df.reindex([0, 1, 3], axis="index") + tm.assert_frame_equal(result, expected) + + def test_reindex_positional_raises(self): + # https://github.com/pandas-dev/pandas/issues/12392 + # Enforced in 2.0 + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + msg = r"reindex\(\) takes from 1 to 2 positional arguments but 3 were given" + with pytest.raises(TypeError, match=msg): + df.reindex([0, 1], ["A", "B", "C"]) + + def test_reindex_axis_style_raises(self): + # https://github.com/pandas-dev/pandas/issues/12392 + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + with pytest.raises(TypeError, match="Cannot specify both 'axis'"): + df.reindex([0, 1], columns=["A"], axis=1) + + with pytest.raises(TypeError, match="Cannot specify both 'axis'"): + df.reindex([0, 1], columns=["A"], axis="index") + + with pytest.raises(TypeError, match="Cannot specify both 'axis'"): + df.reindex(index=[0, 1], axis="index") + + with pytest.raises(TypeError, match="Cannot specify both 'axis'"): + df.reindex(index=[0, 1], axis="columns") + + with pytest.raises(TypeError, match="Cannot specify both 'axis'"): + df.reindex(columns=[0, 1], axis="columns") + + with pytest.raises(TypeError, match="Cannot specify both 'axis'"): + df.reindex(index=[0, 1], columns=[0, 1], axis="columns") + + with pytest.raises(TypeError, match="Cannot specify all"): + df.reindex(labels=[0, 1], index=[0], columns=["A"]) + + # Mixing styles + with pytest.raises(TypeError, match="Cannot specify both 'axis'"): + df.reindex(index=[0, 1], axis="index") + + with pytest.raises(TypeError, match="Cannot specify both 'axis'"): + df.reindex(index=[0, 1], axis="columns") + + # Duplicates + with pytest.raises(TypeError, match="multiple values"): + df.reindex([0, 1], labels=[0, 1]) + + def test_reindex_single_named_indexer(self): + # https://github.com/pandas-dev/pandas/issues/12392 + df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}) + result = df.reindex([0, 1], columns=["A"]) + expected = pd.DataFrame({"A": [1, 2]}) + tm.assert_frame_equal(result, expected) + + def test_reindex_api_equivalence(self): + # https://github.com/pandas-dev/pandas/issues/12392 + # equivalence of the labels/axis and index/columns API's + df = pd.DataFrame( + [[1, 2, 3], [3, 4, 5], [5, 6, 7]], + index=["a", "b", "c"], + columns=["d", "e", "f"], + ) + + res1 = df.reindex(["b", "a"]) + res2 = df.reindex(index=["b", "a"]) + res3 = df.reindex(labels=["b", "a"]) + res4 = df.reindex(labels=["b", "a"], axis=0) + res5 = df.reindex(["b", "a"], axis=0) + for res in [res2, res3, res4, res5]: + tm.assert_frame_equal(res1, res) + + res1 = df.reindex(columns=["e", "d"]) + res2 = df.reindex(["e", "d"], axis=1) + res3 = df.reindex(labels=["e", "d"], axis=1) + for res in [res2, res3]: + tm.assert_frame_equal(res1, res) + + res1 = df.reindex(index=["b", "a"], columns=["e", "d"]) + res2 = df.reindex(columns=["e", "d"], index=["b", "a"]) + res3 = df.reindex(labels=["b", "a"], axis=0).reindex(labels=["e", "d"], axis=1) + for res in [res2, res3]: + tm.assert_frame_equal(res1, res) + + def test_reindex_boolean(self): + frame = pd.DataFrame( + np.ones((10, 2), dtype=bool), index=np.arange(0, 20, 2), columns=[0, 2] + ) + + reindexed = frame.reindex(np.arange(10)) + assert reindexed.values.dtype == np.object_ + assert pd.isna(reindexed[0][1]) + + reindexed = frame.reindex(columns=range(3)) + assert reindexed.values.dtype == np.object_ + assert pd.isna(reindexed[1]).all() + + def test_reindex_objects(self, float_string_frame): + reindexed = float_string_frame.reindex(columns=["foo", "A", "B"]) + assert "foo" in reindexed + + reindexed = float_string_frame.reindex(columns=["A", "B"]) + assert "foo" not in reindexed + + def test_reindex_corner(self, int_frame): + index = pd.Index(["a", "b", "c"]) + dm = pd.DataFrame({}).reindex(index=[1, 2, 3]) + reindexed = dm.reindex(columns=index) + tm.assert_index_equal(reindexed.columns, index) + + # ints are weird + smaller = int_frame.reindex(columns=["A", "B", "E"]) + assert smaller["E"].dtype == np.float64 + + def test_reindex_with_nans(self): + df = pd.DataFrame( + [[1, 2], [3, 4], [np.nan, np.nan], [7, 8], [9, 10]], + columns=["a", "b"], + index=[100.0, 101.0, np.nan, 102.0, 103.0], + ) + + result = df.reindex(index=[101.0, 102.0, 103.0]) + expected = df.iloc[[1, 3, 4]] + tm.assert_frame_equal(result, expected) + + result = df.reindex(index=[103.0]) + expected = df.iloc[[4]] + tm.assert_frame_equal(result, expected) + + result = df.reindex(index=[101.0]) + expected = df.iloc[[1]] + tm.assert_frame_equal(result, expected) + + def test_reindex_without_upcasting(self): + # GH45857 + df = pd.DataFrame(np.zeros((10, 10), dtype=np.float32)) + result = df.reindex(columns=np.arange(5, 15)) + assert result.dtypes.eq(np.float32).all() + + def test_reindex_multi(self): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((3, 3))) + + result = df.reindex(index=range(4), columns=range(4)) + expected = df.reindex(list(range(4))).reindex(columns=range(4)) + + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame(np.random.default_rng(2).integers(0, 10, (3, 3))) + + result = df.reindex(index=range(4), columns=range(4)) + expected = df.reindex(list(range(4))).reindex(columns=range(4)) + + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame(np.random.default_rng(2).integers(0, 10, (3, 3))) + + result = df.reindex(index=range(2), columns=range(2)) + expected = df.reindex(range(2)).reindex(columns=range(2)) + + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 3)) + 1j, + columns=["a", "b", "c"], + ) + + result = df.reindex(index=[0, 1], columns=["a", "b"]) + expected = df.reindex([0, 1]).reindex(columns=["a", "b"]) + + tm.assert_frame_equal(result, expected) + + def test_reindex_multi_promotes_dtype_for_missing_columns(self): + # GH#58517 reindexing both axes at once takes the take_2d_multi + # fastpath; a missing column must promote the result dtype so that + # the fill value fits, even when every row label is present + df = pd.DataFrame(np.arange(6).reshape(2, 3), index=[0, 1], columns=[0, 1, 2]) + + result = df.reindex(index=[1, 0], columns=[0, 1, 5]) + expected = pd.DataFrame( + {0: [3.0, 0.0], 1: [4.0, 1.0], 5: [np.nan, np.nan]}, index=[1, 0] + ) + tm.assert_frame_equal(result, expected) + + def test_reindex_multi_categorical_time(self): + # https://github.com/pandas-dev/pandas/issues/21390 + midx = pd.MultiIndex.from_product( + [ + pd.Categorical(["a", "b", "c"]), + pd.Categorical(pd.date_range("2012-01-01", periods=3, freq="h")), + ] + ) + df = pd.DataFrame({"a": range(len(midx))}, index=midx) + df2 = df.iloc[[0, 1, 2, 3, 4, 5, 6, 8]] + + result = df2.reindex(midx) + expected = pd.DataFrame({"a": [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx) + tm.assert_frame_equal(result, expected) + + def test_reindex_with_categoricalindex(self): + df = pd.DataFrame( + { + "A": np.arange(3, dtype="int64"), + }, + index=pd.CategoricalIndex( + list("abc"), dtype=CategoricalDtype(list("cabe")), name="B" + ), + ) + + # reindexing + # convert to a regular index + result = df.reindex(["a", "b", "e"]) + expected = pd.DataFrame( + {"A": [0, 1, np.nan], "B": pd.Series(list("abe"))} + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["a", "b"]) + expected = pd.DataFrame({"A": [0, 1], "B": pd.Series(list("ab"))}).set_index( + "B" + ) + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["e"]) + expected = pd.DataFrame({"A": [np.nan], "B": pd.Series(["e"])}).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["d"]) + expected = pd.DataFrame({"A": [np.nan], "B": pd.Series(["d"])}).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + # since we are actually reindexing with a Categorical + # then return a Categorical + cats = list("cabe") + + result = df.reindex(pd.Categorical(["a", "e"], categories=cats)) + expected = pd.DataFrame( + { + "A": [0, np.nan], + "B": pd.Series(list("ae")).astype(CategoricalDtype(cats)), + } + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(pd.Categorical(["a"], categories=cats)) + expected = pd.DataFrame( + {"A": [0], "B": pd.Series(list("a")).astype(CategoricalDtype(cats))} + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["a", "b", "e"]) + expected = pd.DataFrame( + {"A": [0, 1, np.nan], "B": pd.Series(list("abe"))} + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["a", "b"]) + expected = pd.DataFrame({"A": [0, 1], "B": pd.Series(list("ab"))}).set_index( + "B" + ) + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["e"]) + expected = pd.DataFrame({"A": [np.nan], "B": pd.Series(["e"])}).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + # give back the type of categorical that we received + result = df.reindex(pd.Categorical(["a", "e"], categories=cats, ordered=True)) + expected = pd.DataFrame( + { + "A": [0, np.nan], + "B": pd.Series(list("ae")).astype(CategoricalDtype(cats, ordered=True)), + } + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(pd.Categorical(["a", "d"], categories=["a", "d"])) + expected = pd.DataFrame( + { + "A": [0, np.nan], + "B": pd.Series(list("ad")).astype(CategoricalDtype(["a", "d"])), + } + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + df2 = pd.DataFrame( + { + "A": np.arange(6, dtype="int64"), + }, + index=pd.CategoricalIndex( + list("aabbca"), dtype=CategoricalDtype(list("cabe")), name="B" + ), + ) + # passed duplicate indexers are not allowed + msg = "cannot reindex on an axis with duplicate labels" + with pytest.raises(ValueError, match=msg): + df2.reindex(["a", "b"]) + + # args NotImplemented ATM + msg = r"argument {} is not implemented for CategoricalIndex\.reindex" + with pytest.raises(NotImplementedError, match=msg.format("method")): + df.reindex(["a"], method="ffill") + with pytest.raises(NotImplementedError, match=msg.format("level")): + df.reindex(["a"], level=1) + with pytest.raises(NotImplementedError, match=msg.format("limit")): + df.reindex(["a"], limit=2) + + def test_reindex_signature(self): + sig = inspect.signature(pd.DataFrame.reindex) + parameters = set(sig.parameters) + assert parameters == { + "self", + "labels", + "index", + "columns", + "axis", + "limit", + "copy", + "level", + "method", + "fill_value", + "tolerance", + } + + def test_reindex_multiindex_ffill_added_rows(self): + # GH#23693 + # reindex added rows with nan values even when fill method was specified + mi = pd.MultiIndex.from_tuples([("a", "b"), ("d", "e")]) + df = pd.DataFrame([[0, 7], [3, 4]], index=mi, columns=["x", "y"]) + mi2 = pd.MultiIndex.from_tuples([("a", "b"), ("d", "e"), ("h", "i")]) + result = df.reindex(mi2, axis=0, method="ffill") + expected = pd.DataFrame([[0, 7], [3, 4], [3, 4]], index=mi2, columns=["x", "y"]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "kwargs", + [ + {"method": "pad", "tolerance": timedelta(seconds=9)}, + {"method": "backfill", "tolerance": timedelta(seconds=9)}, + {"method": "nearest"}, + {"method": None}, + ], + ) + def test_reindex_empty_frame(self, kwargs): + # GH#27315 + idx = pd.date_range(start="2020", freq="30s", periods=3) + df = pd.DataFrame([], index=pd.Index([], name="time"), columns=["a"]) + result = df.reindex(idx, **kwargs) + expected = pd.DataFrame({"a": [np.nan] * 3}, index=idx, dtype=object) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("src_idx", [pd.Index, pd.CategoricalIndex]) + @pytest.mark.parametrize( + "cat_idx", + [ + # No duplicates + pd.Index([]), + pd.CategoricalIndex([]), + pd.Index(["A", "B"]), + pd.CategoricalIndex(["A", "B"]), + # Duplicates: GH#38906 + pd.Index(["A", "A"]), + pd.CategoricalIndex(["A", "A"]), + ], + ) + def test_reindex_empty(self, src_idx, cat_idx): + df = pd.DataFrame(columns=src_idx([]), index=["K"], dtype="f8") + + result = df.reindex(columns=cat_idx) + expected = pd.DataFrame(index=["K"], columns=cat_idx, dtype="f8") + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]"]) + def test_reindex_datetimelike_to_object(self, dtype): + # GH#39755 dont cast dt64/td64 to ints + mi = pd.MultiIndex.from_product([list("ABCDE"), range(2)]) + + dti = pd.date_range("2016-01-01", periods=10) + fv = np.timedelta64("NaT", "ns") + if dtype == "m8[ns]": + dti = dti - dti[0] + fv = np.datetime64("NaT", "ns") + + ser = pd.Series(dti, index=mi) + ser[::3] = pd.NaT + + df = ser.unstack() + + index = df.index.append(pd.Index([1])) + columns = df.columns.append(pd.Index(["foo"])) + + msg = "reindexing with a fill_value that cannot be held" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + res = df.reindex(index=index, columns=columns, fill_value=fv) + + expected = pd.DataFrame( + { + 0: [*df[0].tolist(), fv], + 1: [*df[1].tolist(), fv], + "foo": np.array(["NaT"] * 6, dtype=fv.dtype), + }, + index=index, + ) + assert (res.dtypes[[0, 1]] == object).all() + assert res.iloc[0, 0] is pd.NaT + assert res.iloc[-1, 0] is fv + assert res.iloc[-1, 1] is fv + tm.assert_frame_equal(res, expected) + + @pytest.mark.parametrize("klass", [pd.Index, pd.CategoricalIndex]) + @pytest.mark.parametrize("data", ["A", "B"]) + def test_reindex_not_category(self, klass, data): + # GH#28690 + df = pd.DataFrame(index=pd.CategoricalIndex([], categories=["A"])) + idx = klass([data]) + result = df.reindex(index=idx) + expected = pd.DataFrame(index=idx) + tm.assert_frame_equal(result, expected) + + def test_invalid_method(self): + df = pd.DataFrame({"A": [1, np.nan, 2]}) + + msg = "Invalid fill method" + with pytest.raises(ValueError, match=msg): + df.reindex([1, 0, 2], method="asfreq") + + def test_reindex_index_name_matches_multiindex_level(self): + df = pd.DataFrame( + {"value": [1, 2], "other": ["A", "B"]}, + index=pd.Index([10, 20], name="a"), + ) + target = pd.MultiIndex.from_product( + [[10, 20], ["x", "y"]], + names=["a", "b"], + ) + + result = df.reindex(index=target) + expected = pd.DataFrame( + data={"value": [1, 1, 2, 2], "other": ["A", "A", "B", "B"]}, + index=pd.MultiIndex.from_product([[10, 20], ["x", "y"]], names=["a", "b"]), + ) + tm.assert_frame_equal(result, expected) + + def test_reindex_index_name_no_match_multiindex_level(self): + df = pd.DataFrame( + {"value": [1, 2]}, index=pd.Index([10, 20], name="different_name") + ) + target = pd.MultiIndex.from_product([[10, 20], ["x", "y"]], names=["a", "b"]) + + result = df.reindex(index=target) + expected = pd.DataFrame( + data={"value": [np.nan] * 4}, + index=pd.MultiIndex.from_product([[10, 20], ["x", "y"]], names=["a", "b"]), + ) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reindex_like.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reindex_like.py new file mode 100644 index 0000000000000000000000000000000000000000..3dc7c730b7a443f70787b78c2f21924299954437 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reindex_like.py @@ -0,0 +1,44 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameReindexLike: + def test_reindex_like(self, float_frame): + other = float_frame.reindex(index=float_frame.index[:10], columns=["C", "B"]) + + tm.assert_frame_equal(other, float_frame.reindex_like(other)) + + @pytest.mark.parametrize( + "method,expected_values", + [ + ("nearest", [0, 1, 1, 2]), + ("pad", [np.nan, 0, 1, 1]), + ("backfill", [0, 1, 2, 2]), + ], + ) + def test_reindex_like_methods(self, method, expected_values): + df = pd.DataFrame({"x": list(range(5))}) + + msg = "the 'method' keyword is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.reindex_like(df, method=method, tolerance=0) + tm.assert_frame_equal(df, result) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.reindex_like(df, method=method, tolerance=[0, 0, 0, 0]) + tm.assert_frame_equal(df, result) + + def test_reindex_like_subclass(self): + # https://github.com/pandas-dev/pandas/issues/31925 + class MyDataFrame(pd.DataFrame): + pass + + expected = pd.DataFrame() + df = MyDataFrame() + result = df.reindex_like(expected) + + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_rename.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_rename.py new file mode 100644 index 0000000000000000000000000000000000000000..1dc0aef1671eb402b07f7bc091dc49efaa740764 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_rename.py @@ -0,0 +1,516 @@ +from collections import ChainMap +import inspect + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestRename: + def test_rename_signature(self): + sig = inspect.signature(pd.DataFrame.rename) + parameters = set(sig.parameters) + assert parameters == { + "self", + "mapper", + "index", + "columns", + "axis", + "inplace", + "copy", + "level", + "errors", + } + + def test_rename_mi(self, frame_or_series): + obj = frame_or_series( + [11, 21, 31], + index=pd.MultiIndex.from_tuples([("A", x) for x in ["a", "B", "c"]]), + ) + obj.rename(str.lower) + + def test_rename(self, float_frame): + mapping = {"A": "a", "B": "b", "C": "c", "D": "d"} + + renamed = float_frame.rename(columns=mapping) + renamed2 = float_frame.rename(columns=str.lower) + + tm.assert_frame_equal(renamed, renamed2) + tm.assert_frame_equal( + renamed2.rename(columns=str.upper), float_frame, check_names=False + ) + + # index + data = {"A": {"foo": 0, "bar": 1}} + + df = pd.DataFrame(data) + renamed = df.rename(index={"foo": "bar", "bar": "foo"}) + tm.assert_index_equal(renamed.index, pd.Index(["bar", "foo"])) + + renamed = df.rename(index=str.upper) + tm.assert_index_equal(renamed.index, pd.Index(["FOO", "BAR"])) + + # have to pass something + with pytest.raises(TypeError, match="must pass an index to rename"): + float_frame.rename() + + # partial columns + renamed = float_frame.rename(columns={"C": "foo", "D": "bar"}) + tm.assert_index_equal(renamed.columns, pd.Index(["A", "B", "foo", "bar"])) + + # other axis + renamed = float_frame.T.rename(index={"C": "foo", "D": "bar"}) + tm.assert_index_equal(renamed.index, pd.Index(["A", "B", "foo", "bar"])) + + # index with name + index = pd.Index(["foo", "bar"], name="name") + renamer = pd.DataFrame(data, index=index) + renamed = renamer.rename(index={"foo": "bar", "bar": "foo"}) + tm.assert_index_equal(renamed.index, pd.Index(["bar", "foo"], name="name")) + assert renamed.index.name == renamer.index.name + + @pytest.mark.parametrize( + "args,kwargs", + [ + ((ChainMap({"A": "a"}, {"B": "b"}),), {"axis": "columns"}), + ((), {"columns": ChainMap({"A": "a"}, {"B": "b"})}), + ], + ) + def test_rename_chainmap(self, args, kwargs): + # see gh-23859 + colAData = range(1, 11) + colBdata = np.random.default_rng(2).standard_normal(10) + + df = pd.DataFrame({"A": colAData, "B": colBdata}) + result = df.rename(*args, **kwargs) + + expected = pd.DataFrame({"a": colAData, "b": colBdata}) + tm.assert_frame_equal(result, expected) + + def test_rename_multiindex(self): + tuples_index = [("foo1", "bar1"), ("foo2", "bar2")] + tuples_columns = [("fizz1", "buzz1"), ("fizz2", "buzz2")] + index = pd.MultiIndex.from_tuples(tuples_index, names=["foo", "bar"]) + columns = pd.MultiIndex.from_tuples(tuples_columns, names=["fizz", "buzz"]) + df = pd.DataFrame([(0, 0), (1, 1)], index=index, columns=columns) + + # + # without specifying level -> across all levels + + renamed = df.rename( + index={"foo1": "foo3", "bar2": "bar3"}, + columns={"fizz1": "fizz3", "buzz2": "buzz3"}, + ) + new_index = pd.MultiIndex.from_tuples( + [("foo3", "bar1"), ("foo2", "bar3")], names=["foo", "bar"] + ) + new_columns = pd.MultiIndex.from_tuples( + [("fizz3", "buzz1"), ("fizz2", "buzz3")], names=["fizz", "buzz"] + ) + tm.assert_index_equal(renamed.index, new_index) + tm.assert_index_equal(renamed.columns, new_columns) + assert renamed.index.names == df.index.names + assert renamed.columns.names == df.columns.names + + # + # with specifying a level (GH13766) + + # dict + new_columns = pd.MultiIndex.from_tuples( + [("fizz3", "buzz1"), ("fizz2", "buzz2")], names=["fizz", "buzz"] + ) + renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level=0) + tm.assert_index_equal(renamed.columns, new_columns) + renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level="fizz") + tm.assert_index_equal(renamed.columns, new_columns) + + new_columns = pd.MultiIndex.from_tuples( + [("fizz1", "buzz1"), ("fizz2", "buzz3")], names=["fizz", "buzz"] + ) + renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level=1) + tm.assert_index_equal(renamed.columns, new_columns) + renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level="buzz") + tm.assert_index_equal(renamed.columns, new_columns) + + # function + func = str.upper + new_columns = pd.MultiIndex.from_tuples( + [("FIZZ1", "buzz1"), ("FIZZ2", "buzz2")], names=["fizz", "buzz"] + ) + renamed = df.rename(columns=func, level=0) + tm.assert_index_equal(renamed.columns, new_columns) + renamed = df.rename(columns=func, level="fizz") + tm.assert_index_equal(renamed.columns, new_columns) + + new_columns = pd.MultiIndex.from_tuples( + [("fizz1", "BUZZ1"), ("fizz2", "BUZZ2")], names=["fizz", "buzz"] + ) + renamed = df.rename(columns=func, level=1) + tm.assert_index_equal(renamed.columns, new_columns) + renamed = df.rename(columns=func, level="buzz") + tm.assert_index_equal(renamed.columns, new_columns) + + # index + new_index = pd.MultiIndex.from_tuples( + [("foo3", "bar1"), ("foo2", "bar2")], names=["foo", "bar"] + ) + renamed = df.rename(index={"foo1": "foo3", "bar2": "bar3"}, level=0) + tm.assert_index_equal(renamed.index, new_index) + + def test_rename_nocopy(self, float_frame): + renamed = float_frame.rename(columns={"C": "foo"}) + + assert np.shares_memory(renamed["foo"]._values, float_frame["C"]._values) + + renamed.loc[:, "foo"] = 1.0 + assert not (float_frame["C"] == 1.0).all() + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.rename is") + def test_rename_inplace(self, float_frame): + float_frame.rename(columns={"C": "foo"}) + assert "C" in float_frame + assert "foo" not in float_frame + + c_values = float_frame["C"] + float_frame = float_frame.copy() + return_value = float_frame.rename(columns={"C": "foo"}, inplace=True) + assert return_value is None + + assert "C" not in float_frame + assert "foo" in float_frame + # GH 44153 + # Used to be id(float_frame["foo"]) != c_id, but flaky in the CI + assert float_frame["foo"] is not c_values + + def test_rename_inplace_depr(self, float_frame): + msg = "The inplace keyword in DataFrame.rename is deprecated" + + # uses keyword, sets to true, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + float_frame.rename(columns={"C": "foo"}, inplace=True) + # uses keyword, sets to false, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + float_frame.rename(columns={"C": "foo"}, inplace=False) + # does not use keyword, no warning + with tm.assert_produces_warning(False): + float_frame.rename(columns={"C": "foo"}) + + def test_rename_bug(self): + # GH 5344 + # rename set ref_locs, and set_index was not resetting + df = pd.DataFrame({0: ["foo", "bar"], 1: ["bah", "bas"], 2: [1, 2]}) + df = df.rename(columns={0: "a"}) + df = df.rename(columns={1: "b"}) + df = df.set_index(["a", "b"]) + df.columns = ["2001-01-01"] + expected = pd.DataFrame( + [[1], [2]], + index=pd.MultiIndex.from_tuples( + [("foo", "bah"), ("bar", "bas")], names=["a", "b"] + ), + columns=["2001-01-01"], + ) + tm.assert_frame_equal(df, expected) + + def test_rename_bug2(self): + # GH 19497 + # rename was changing Index to MultiIndex if Index contained tuples + + df = pd.DataFrame( + data=np.arange(3), index=[(0, 0), (1, 1), (2, 2)], columns=["a"] + ) + df = df.rename({(1, 1): (5, 4)}, axis="index") + expected = pd.DataFrame( + data=np.arange(3), index=[(0, 0), (5, 4), (2, 2)], columns=["a"] + ) + tm.assert_frame_equal(df, expected) + + def test_rename_errors_raises(self): + df = pd.DataFrame(columns=["A", "B", "C", "D"]) + with pytest.raises(KeyError, match="'E'] not found in axis"): + df.rename(columns={"A": "a", "E": "e"}, errors="raise") + + @pytest.mark.parametrize( + "mapper, errors, expected_columns", + [ + ({"A": "a", "E": "e"}, "ignore", ["a", "B", "C", "D"]), + ({"A": "a"}, "raise", ["a", "B", "C", "D"]), + (str.lower, "raise", ["a", "b", "c", "d"]), + ], + ) + def test_rename_errors(self, mapper, errors, expected_columns): + # GH 13473 + # rename now works with errors parameter + df = pd.DataFrame(columns=["A", "B", "C", "D"]) + result = df.rename(columns=mapper, errors=errors) + expected = pd.DataFrame(columns=expected_columns) + tm.assert_frame_equal(result, expected) + + def test_rename_objects(self, float_string_frame): + renamed = float_string_frame.rename(columns=str.upper) + + assert "FOO" in renamed + assert "foo" not in renamed + + def test_rename_axis_style(self): + # https://github.com/pandas-dev/pandas/issues/12392 + df = pd.DataFrame({"A": [1, 2], "B": [1, 2]}, index=["X", "Y"]) + expected = pd.DataFrame({"a": [1, 2], "b": [1, 2]}, index=["X", "Y"]) + + result = df.rename(str.lower, axis=1) + tm.assert_frame_equal(result, expected) + + result = df.rename(str.lower, axis="columns") + tm.assert_frame_equal(result, expected) + + result = df.rename({"A": "a", "B": "b"}, axis=1) + tm.assert_frame_equal(result, expected) + + result = df.rename({"A": "a", "B": "b"}, axis="columns") + tm.assert_frame_equal(result, expected) + + # Index + expected = pd.DataFrame({"A": [1, 2], "B": [1, 2]}, index=["x", "y"]) + result = df.rename(str.lower, axis=0) + tm.assert_frame_equal(result, expected) + + result = df.rename(str.lower, axis="index") + tm.assert_frame_equal(result, expected) + + result = df.rename({"X": "x", "Y": "y"}, axis=0) + tm.assert_frame_equal(result, expected) + + result = df.rename({"X": "x", "Y": "y"}, axis="index") + tm.assert_frame_equal(result, expected) + + result = df.rename(mapper=str.lower, axis="index") + tm.assert_frame_equal(result, expected) + + def test_rename_mapper_multi(self): + df = pd.DataFrame({"A": ["a", "b"], "B": ["c", "d"], "C": [1, 2]}).set_index( + ["A", "B"] + ) + result = df.rename(str.upper) + expected = df.rename(index=str.upper) + tm.assert_frame_equal(result, expected) + + def test_rename_positional_named(self): + # https://github.com/pandas-dev/pandas/issues/12392 + df = pd.DataFrame({"a": [1, 2], "b": [1, 2]}, index=["X", "Y"]) + result = df.rename(index=str.lower, columns=str.upper) + expected = pd.DataFrame({"A": [1, 2], "B": [1, 2]}, index=["x", "y"]) + tm.assert_frame_equal(result, expected) + + def test_rename_axis_style_raises(self): + # see gh-12392 + df = pd.DataFrame({"A": [1, 2], "B": [1, 2]}, index=["0", "1"]) + + # Named target and axis + over_spec_msg = "Cannot specify both 'axis' and any of 'index' or 'columns'" + with pytest.raises(TypeError, match=over_spec_msg): + df.rename(index=str.lower, axis=1) + + with pytest.raises(TypeError, match=over_spec_msg): + df.rename(index=str.lower, axis="columns") + + with pytest.raises(TypeError, match=over_spec_msg): + df.rename(columns=str.lower, axis="columns") + + with pytest.raises(TypeError, match=over_spec_msg): + df.rename(index=str.lower, axis=0) + + # Multiple targets and axis + with pytest.raises(TypeError, match=over_spec_msg): + df.rename(str.lower, index=str.lower, axis="columns") + + # Too many targets + over_spec_msg = "Cannot specify both 'mapper' and any of 'index' or 'columns'" + with pytest.raises(TypeError, match=over_spec_msg): + df.rename(str.lower, index=str.lower, columns=str.lower) + + # Duplicates + with pytest.raises(TypeError, match="multiple values"): + df.rename(id, mapper=id) + + def test_rename_positional_raises(self): + # GH 29136 + df = pd.DataFrame(columns=["A", "B"]) + msg = r"rename\(\) takes from 1 to 2 positional arguments" + + with pytest.raises(TypeError, match=msg): + df.rename(None, str.lower) + + def test_rename_no_mappings_raises(self): + # GH 29136 + df = pd.DataFrame([[1]]) + msg = "must pass an index to rename" + with pytest.raises(TypeError, match=msg): + df.rename() + + with pytest.raises(TypeError, match=msg): + df.rename(None, index=None) + + with pytest.raises(TypeError, match=msg): + df.rename(None, columns=None) + + with pytest.raises(TypeError, match=msg): + df.rename(None, columns=None, index=None) + + def test_rename_mapper_and_positional_arguments_raises(self): + # GH 29136 + df = pd.DataFrame([[1]]) + msg = "Cannot specify both 'mapper' and any of 'index' or 'columns'" + with pytest.raises(TypeError, match=msg): + df.rename({}, index={}) + + with pytest.raises(TypeError, match=msg): + df.rename({}, columns={}) + + with pytest.raises(TypeError, match=msg): + df.rename({}, columns={}, index={}) + + def test_rename_with_duplicate_columns(self): + # GH#4403 + df4 = pd.DataFrame( + {"RT": [0.0454], "TClose": [22.02], "TExg": [0.0422]}, + index=pd.MultiIndex.from_tuples( + [(600809, 20130331)], names=["STK_ID", "RPT_Date"] + ), + ) + + df5 = pd.DataFrame( + { + "RPT_Date": [20120930, 20121231, 20130331], + "STK_ID": [600809] * 3, + "STK_Name": ["饡驦", "饡驦", "饡驦"], + "TClose": [38.05, 41.66, 30.01], + }, + index=pd.MultiIndex.from_tuples( + [(600809, 20120930), (600809, 20121231), (600809, 20130331)], + names=["STK_ID", "RPT_Date"], + ), + ) + # TODO: can we construct this without merge? + k = pd.merge(df4, df5, how="inner", left_index=True, right_index=True) + result = k.rename(columns={"TClose_x": "TClose", "TClose_y": "QT_Close"}) + + expected = pd.DataFrame( + [[0.0454, 22.02, 0.0422, 20130331, 600809, "饡驦", 30.01]], + columns=[ + "RT", + "TClose", + "TExg", + "RPT_Date", + "STK_ID", + "STK_Name", + "QT_Close", + ], + ).set_index(["STK_ID", "RPT_Date"], drop=False) + tm.assert_frame_equal(result, expected) + + def test_rename_boolean_index(self): + df = pd.DataFrame(np.arange(15).reshape(3, 5), columns=[False, True, 2, 3, 4]) + mapper = {0: "foo", 1: "bar", 2: "bah"} + res = df.rename(index=mapper) + exp = pd.DataFrame( + np.arange(15).reshape(3, 5), + columns=[False, True, 2, 3, 4], + index=["foo", "bar", "bah"], + ) + tm.assert_frame_equal(res, exp) + + def test_rename_preserves_nullable_int_index(self): + # GH#65315 + df = pd.DataFrame( + {"val": [1, 2, 3]}, + index=pd.Index(pd.array([1, 2, 3], dtype="Int64"), name="id"), + ) + result = df.rename({1: 9}) + expected = pd.Index(pd.array([9, 2, 3], dtype="Int64"), name="id") + tm.assert_index_equal(result.index, expected) + + def test_rename_preserves_nullable_float_columns(self): + # GH#65315 + df = pd.DataFrame( + [[1, 2, 3]], + columns=pd.Index(pd.array([1.0, 2.0, 3.0], dtype="Float64")), + ) + result = df.rename(columns={1.0: 9.0}) + expected = pd.Index(pd.array([9.0, 2.0, 3.0], dtype="Float64")) + tm.assert_index_equal(result.columns, expected) + + def test_rename_nullable_index_to_na(self): + # GH#65315 + df = pd.DataFrame( + {"val": [1, 2, 3]}, + index=pd.Index(pd.array([1, 2, 3], dtype="Int64")), + ) + result = df.rename({1: pd.NA}) + expected = pd.Index(pd.array([pd.NA, 2, 3], dtype="Int64")) + tm.assert_index_equal(result.index, expected) + + def test_rename_empty_nullable_index(self): + # GH#65315 + df = pd.DataFrame({"val": []}, index=pd.Index(pd.array([], dtype="Int64"))) + result = df.rename(index={}) + tm.assert_index_equal(result.index, df.index) + + def test_rename_nullable_index_type_change_widens(self): + # GH#65315 + df = pd.DataFrame( + {"val": [1, 2, 3]}, + index=pd.Index(pd.array([1, 2, 3], dtype="Int64")), + ) + result = df.rename(lambda x: f"label_{x}") + assert list(result.index) == ["label_1", "label_2", "label_3"] + assert result.index.dtype != "Int64" + + def test_rename_tuple_columns_not_multiindex(self): + # GH#65315 + df = pd.DataFrame( + [[1, 2]], + columns=pd.Index(pd.array([1, 2], dtype="Int64")), + ) + result = df.rename(columns=lambda x: (x, x)) + assert not isinstance(result.columns, pd.MultiIndex) + tm.assert_index_equal( + result.columns, pd.Index([(1, 1), (2, 2)], tupleize_cols=False) + ) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.rename is") + @pytest.mark.filterwarnings( + "ignore:The inplace keyword in (Series|DataFrame).rename is" + ) + def test_rename_non_unique_index_series(self): + # GH#58621 + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) + orig = df.copy(deep=True) + + rename_series = pd.Series(["X", "Y", "Z", "W"], index=["A", "B", "B", "C"]) + + msg = "Cannot rename with a Series with non-unique index" + with pytest.raises(ValueError, match=msg): + df.rename(rename_series) + with pytest.raises(ValueError, match=msg): + df.rename(columns=rename_series) + with pytest.raises(ValueError, match=msg): + df.rename(columns=rename_series, inplace=True) + + # check we didn't corrupt the original + tm.assert_frame_equal(df, orig) + + # Check the Series method while we're here + ser = df.iloc[0] + with pytest.raises(ValueError, match=msg): + ser.rename(rename_series) + with pytest.raises(ValueError, match=msg): + ser.rename(index=rename_series) + with pytest.raises(ValueError, match=msg): + ser.rename(index=rename_series, inplace=True) + + # check we didn't corrupt the original + tm.assert_series_equal(ser, orig.iloc[0]) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_rename_axis.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_rename_axis.py new file mode 100644 index 0000000000000000000000000000000000000000..c3295d8c1398b469db4206365445d53e40e67a22 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_rename_axis.py @@ -0,0 +1,147 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameRenameAxis: + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.rename_axis") + def test_rename_axis_inplace(self, float_frame): + # GH#15704 + expected = float_frame.rename_axis("foo") + result = float_frame.copy() + return_value = no_return = result.rename_axis("foo", inplace=True) + assert return_value is None + + assert no_return is None + tm.assert_frame_equal(result, expected) + + expected = float_frame.rename_axis("bar", axis=1) + result = float_frame.copy() + return_value = no_return = result.rename_axis("bar", axis=1, inplace=True) + assert return_value is None + + assert no_return is None + tm.assert_frame_equal(result, expected) + + def test_rename_axis_with_allows_duplicate_labels_false(self): + # GH#44958 + df = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"]).set_flags( + allows_duplicate_labels=False + ) + + result = df.rename_axis("idx", axis=0) + expected = pd.DataFrame( + [[1, 2], [3, 4]], index=pd.Index([0, 1], name="idx"), columns=["a", "b"] + ) + tm.assert_frame_equal(result, expected, check_flags=False) + + def test_rename_axis_raises(self): + # GH#17833 + df = pd.DataFrame({"A": [1, 2], "B": [1, 2]}) + with pytest.raises(ValueError, match="Use `.rename`"): + df.rename_axis(id, axis=0) + + with pytest.raises(ValueError, match="Use `.rename`"): + df.rename_axis({0: 10, 1: 20}, axis=0) + + with pytest.raises(ValueError, match="Use `.rename`"): + df.rename_axis(id, axis=1) + + with pytest.raises(ValueError, match="Use `.rename`"): + df["A"].rename_axis(id) + + def test_rename_axis_mapper(self): + # GH#19978 + mi = pd.MultiIndex.from_product([["a", "b", "c"], [1, 2]], names=["ll", "nn"]) + df = pd.DataFrame( + {"x": list(range(len(mi))), "y": [i * 10 for i in range(len(mi))]}, index=mi + ) + + # Test for rename of the Index object of columns + result = df.rename_axis("cols", axis=1) + tm.assert_index_equal(result.columns, pd.Index(["x", "y"], name="cols")) + + # Test for rename of the Index object of columns using dict + result = result.rename_axis(columns={"cols": "new"}, axis=1) + tm.assert_index_equal(result.columns, pd.Index(["x", "y"], name="new")) + + # Test for renaming index using dict + result = df.rename_axis(index={"ll": "foo"}) + assert result.index.names == ["foo", "nn"] + + # Test for renaming index using a function + result = df.rename_axis(index=str.upper, axis=0) + assert result.index.names == ["LL", "NN"] + + # Test for renaming index providing complete list + result = df.rename_axis(index=["foo", "goo"]) + assert result.index.names == ["foo", "goo"] + + # Test for changing index and columns at same time + sdf = df.reset_index().set_index("nn").drop(columns=["ll", "y"]) + result = sdf.rename_axis(index="foo", columns="meh") + assert result.index.name == "foo" + assert result.columns.name == "meh" + + # Test different error cases + with pytest.raises(TypeError, match="Must pass"): + df.rename_axis(index="wrong") + + with pytest.raises(ValueError, match="Length of names"): + df.rename_axis(index=["wrong"]) + + with pytest.raises(TypeError, match="bogus"): + df.rename_axis(bogus=None) + + @pytest.mark.parametrize( + "kwargs, rename_index, rename_columns", + [ + ({"mapper": None, "axis": 0}, True, False), + ({"mapper": None, "axis": 1}, False, True), + ({"index": None}, True, False), + ({"columns": None}, False, True), + ({"index": None, "columns": None}, True, True), + ({}, False, False), + ], + ) + def test_rename_axis_none(self, kwargs, rename_index, rename_columns): + # GH 25034 + index = pd.Index(list("abc"), name="foo") + columns = pd.Index(["col1", "col2"], name="bar") + data = np.arange(6).reshape(3, 2) + df = pd.DataFrame(data, index, columns) + + result = df.rename_axis(**kwargs) + expected_index = index.rename(None) if rename_index else index + expected_columns = columns.rename(None) if rename_columns else columns + expected = pd.DataFrame(data, expected_index, expected_columns) + tm.assert_frame_equal(result, expected) + + +def test_rename_axis_inplace_depr(): + msg = "The inplace keyword in DataFrame.rename_axis is deprecated" + + df = pd.DataFrame({"a": [1, 2, 3]}, index=pd.Index([0, 1, 2], name="idx")) + df_orig = df.copy() + expected = df.rename_axis("foo") + + # does not use keyword, no warning + with tm.assert_produces_warning(False): + result = df.rename_axis("foo") + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to false, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.rename_axis("foo", inplace=False) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to true, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.rename_axis("foo", inplace=True) + tm.assert_frame_equal(df, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reorder_levels.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reorder_levels.py new file mode 100644 index 0000000000000000000000000000000000000000..c8df7bbc131c3d02dd4e269dd12a65c2631bd2cf --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reorder_levels.py @@ -0,0 +1,71 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestReorderLevels: + def test_reorder_levels(self, frame_or_series): + index = pd.MultiIndex( + levels=[["bar"], ["one", "two", "three"], [0, 1]], + codes=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]], + names=["L0", "L1", "L2"], + ) + df = pd.DataFrame({"A": np.arange(6), "B": np.arange(6)}, index=index) + obj = tm.get_obj(df, frame_or_series) + + # no change, position + result = obj.reorder_levels([0, 1, 2]) + tm.assert_equal(obj, result) + + # no change, labels + result = obj.reorder_levels(["L0", "L1", "L2"]) + tm.assert_equal(obj, result) + + # rotate, position + result = obj.reorder_levels([1, 2, 0]) + e_idx = pd.MultiIndex( + levels=[["one", "two", "three"], [0, 1], ["bar"]], + codes=[[0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0]], + names=["L1", "L2", "L0"], + ) + expected = pd.DataFrame({"A": np.arange(6), "B": np.arange(6)}, index=e_idx) + expected = tm.get_obj(expected, frame_or_series) + tm.assert_equal(result, expected) + + result = obj.reorder_levels([0, 0, 0]) + e_idx = pd.MultiIndex( + levels=[["bar"], ["bar"], ["bar"]], + codes=[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]], + names=["L0", "L0", "L0"], + ) + expected = pd.DataFrame({"A": np.arange(6), "B": np.arange(6)}, index=e_idx) + expected = tm.get_obj(expected, frame_or_series) + tm.assert_equal(result, expected) + + result = obj.reorder_levels(["L0", "L0", "L0"]) + tm.assert_equal(result, expected) + + def test_reorder_levels_swaplevel_equivalence( + self, multiindex_year_month_day_dataframe_random_data + ): + ymd = multiindex_year_month_day_dataframe_random_data + + result = ymd.reorder_levels(["month", "day", "year"]) + expected = ymd.swaplevel(0, 1).swaplevel(1, 2) + tm.assert_frame_equal(result, expected) + + result = ymd["A"].reorder_levels(["month", "day", "year"]) + expected = ymd["A"].swaplevel(0, 1).swaplevel(1, 2) + tm.assert_series_equal(result, expected) + + result = ymd.T.reorder_levels(["month", "day", "year"], axis=1) + expected = ymd.T.swaplevel(0, 1, axis=1).swaplevel(1, 2, axis=1) + tm.assert_frame_equal(result, expected) + + with pytest.raises(TypeError, match="hierarchical axis"): + ymd.reorder_levels([1, 2], axis=1) + + with pytest.raises(IndexError, match="Too many levels"): + ymd.index.reorder_levels([1, 2, 3]) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_replace.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_replace.py new file mode 100644 index 0000000000000000000000000000000000000000..78e2b906ba51b8200a992765da1a29491d9243a8 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_replace.py @@ -0,0 +1,1733 @@ +from __future__ import annotations + +from datetime import datetime +import re + +import numpy as np +import pytest + +from pandas.errors import OutOfBoundsDatetime +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def mix_ab() -> dict[str, list[int | str]]: + return {"a": list(range(4)), "b": list("ab..")} + + +@pytest.fixture +def mix_abc() -> dict[str, list[float | str]]: + return {"a": list(range(4)), "b": list("ab.."), "c": ["a", "b", np.nan, "d"]} + + +class TestDataFrameReplace: + def test_replace_nan_and_infs_with_none_single_call(self): + # GH#31414 replacing NaN and +/-inf with None in a single dict call + # must replace all of them and produce object dtype + df = pd.DataFrame( + {"foo": [np.nan, np.inf, 1.1, 2.2], "bar": [1.0, -np.inf, 2.1, 3.2]} + ) + result = df.replace({np.nan: None, np.inf: None, -np.inf: None}) + expected = pd.DataFrame( + { + "foo": [None, None, 1.1, 2.2], + "bar": [1.0, None, 2.1, 3.2], + }, + dtype=object, + ) + tm.assert_frame_equal(result, expected) + + def test_replace_nan_to_none_alongside_value_replacement(self): + # GH#31414 a dict mixing a NaN->None entry with a real value + # replacement must not undo the None (replace used to revert None->NaN) + df = pd.DataFrame( + {"foo": [np.nan, np.inf, 1.1, 2.2], "bar": [1.0, -np.inf, 2.1, 3.2]} + ) + result = df.replace({np.nan: None, 1: 2}) + assert result["foo"].iloc[0] is None + assert result["bar"].iloc[0] == 2 + assert result["foo"].dtype == object + + def test_replace_nan_with_none_mixed_dtypes(self): + # GH#44485 replacing NaN with None must be idempotent: applying it an + # *even* number of times used to revert and re-introduce NaN (the second + # replace should be a no-op) + df = pd.DataFrame( + { + "age": [5, 6, np.nan], + "born": [ + pd.NaT, + pd.Timestamp("1939-05-27"), + pd.Timestamp("1940-04-25"), + ], + "name": ["Alfred", "Batman", ""], + "toy": [None, "Batmobile", "Joker"], + } + ) + once = df.replace({np.nan: None}) + twice = once.replace({np.nan: None}) + remaining = [ + value + for record in twice.to_dict(orient="records") + for value in record.values() + if isinstance(value, float) and np.isnan(value) + ] + assert remaining == [] + tm.assert_frame_equal(once, twice) + assert twice["age"].dtype == object + + @pytest.mark.parametrize("null", [None, pd.NA]) + def test_replace_regex_list_with_all_null_object_column(self, null): + # GH#54399 replace with a list of regexes must not raise when a column + # is object dtype containing only null values (None and pd.NA both + # regressed; the single-regex form was fine) + df = pd.DataFrame( + {"a": pd.Series([1], dtype="int64"), "b": pd.Series([null], dtype="object")} + ) + result = df.replace(regex=[r"^a$", r"\d{4}"], value="dude") + tm.assert_frame_equal(result, df) + + def test_replace_regex_list_all_null_frame_and_match(self): + # GH#54399 an all-null object frame (no non-null column at all) must not + # raise, and a genuine match alongside an all-null column still replaces + all_null = pd.DataFrame( + { + "a": pd.Series([None], dtype="object"), + "b": pd.Series([None], dtype="object"), + } + ) + tm.assert_frame_equal( + all_null.replace(regex=[r"^a$", r"\d{4}"], value="dude"), all_null + ) + + df = pd.DataFrame( + { + "a": pd.Series(["1234"], dtype="object"), + "b": pd.Series([None], dtype="object"), + } + ) + result = df.replace(regex=[r"^a$", r"\d{4}"], value="dude") + expected = pd.DataFrame( + { + "a": pd.Series(["dude"], dtype="object"), + "b": pd.Series([None], dtype="object"), + } + ) + tm.assert_frame_equal(result, expected) + + def test_replace_inplace(self, datetime_frame, float_string_frame): + datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan + + tsframe = datetime_frame.copy() + result = tsframe.replace(np.nan, 0, inplace=True) + assert result is tsframe + tm.assert_frame_equal(tsframe, datetime_frame.fillna(0)) + + # mixed type + mf = float_string_frame + mf.iloc[5:20, mf.columns.get_loc("foo")] = np.nan + mf.iloc[-10:, mf.columns.get_loc("A")] = np.nan + + result = float_string_frame.replace(np.nan, 0) + expected = float_string_frame.copy() + expected["foo"] = expected["foo"].astype(object) + expected = expected.fillna(value=0) + tm.assert_frame_equal(result, expected) + + tsframe = datetime_frame.copy() + result = tsframe.replace([np.nan], [0], inplace=True) + assert result is tsframe + tm.assert_frame_equal(tsframe, datetime_frame.fillna(0)) + + @pytest.mark.parametrize( + "to_replace,values,expected", + [ + # lists of regexes and values + # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN] + ( + [r"\s*\.\s*", r"e|f|g"], + [np.nan, "crap"], + { + "a": ["a", "b", np.nan, np.nan], + "b": ["crap"] * 3 + ["h"], + "c": ["h", "crap", "l", "o"], + }, + ), + # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] + ( + [r"\s*(\.)\s*", r"(e|f|g)"], + [r"\1\1", r"\1_crap"], + { + "a": ["a", "b", "..", ".."], + "b": ["e_crap", "f_crap", "g_crap", "h"], + "c": ["h", "e_crap", "l", "o"], + }, + ), + # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN + # or vN)] + ( + [r"\s*(\.)\s*", r"e"], + [r"\1\1", r"crap"], + { + "a": ["a", "b", "..", ".."], + "b": ["crap", "f", "g", "h"], + "c": ["h", "crap", "l", "o"], + }, + ), + ], + ) + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize("use_value_regex_args", [True, False]) + def test_regex_replace_list_obj( + self, to_replace, values, expected, inplace, use_value_regex_args + ): + df = pd.DataFrame({"a": list("ab.."), "b": list("efgh"), "c": list("helo")}) + + if use_value_regex_args: + result = df.replace(value=values, regex=to_replace, inplace=inplace) + else: + result = df.replace(to_replace, values, regex=True, inplace=inplace) + + if inplace: + assert result is df + + expected = pd.DataFrame(expected) + tm.assert_frame_equal(result, expected) + + def test_regex_replace_list_mixed(self, mix_ab): + # mixed frame to make sure this doesn't break things + dfmix = pd.DataFrame(mix_ab) + + # lists of regexes and values + # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN] + to_replace_res = [r"\s*\.\s*", r"a"] + values = [np.nan, "crap"] + mix2 = {"a": list(range(4)), "b": list("ab.."), "c": list("halo")} + dfmix2 = pd.DataFrame(mix2) + res = dfmix2.replace(to_replace_res, values, regex=True) + expec = pd.DataFrame( + { + "a": mix2["a"], + "b": ["crap", "b", np.nan, np.nan], + "c": ["h", "crap", "l", "o"], + } + ) + tm.assert_frame_equal(res, expec) + + # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] + to_replace_res = [r"\s*(\.)\s*", r"(a|b)"] + values = [r"\1\1", r"\1_crap"] + res = dfmix.replace(to_replace_res, values, regex=True) + expec = pd.DataFrame({"a": mix_ab["a"], "b": ["a_crap", "b_crap", "..", ".."]}) + tm.assert_frame_equal(res, expec) + + # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN + # or vN)] + to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"] + values = [r"\1\1", r"crap", r"\1_crap"] + res = dfmix.replace(to_replace_res, values, regex=True) + expec = pd.DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]}) + tm.assert_frame_equal(res, expec) + + to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"] + values = [r"\1\1", r"crap", r"\1_crap"] + res = dfmix.replace(regex=to_replace_res, value=values) + expec = pd.DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]}) + tm.assert_frame_equal(res, expec) + + def test_regex_replace_list_mixed_inplace(self, mix_ab): + dfmix = pd.DataFrame(mix_ab) + # the same inplace + # lists of regexes and values + # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN] + to_replace_res = [r"\s*\.\s*", r"a"] + values = [np.nan, "crap"] + res = dfmix.copy() + result = res.replace(to_replace_res, values, inplace=True, regex=True) + assert result is res + expec = pd.DataFrame({"a": mix_ab["a"], "b": ["crap", "b", np.nan, np.nan]}) + tm.assert_frame_equal(res, expec) + + # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] + to_replace_res = [r"\s*(\.)\s*", r"(a|b)"] + values = [r"\1\1", r"\1_crap"] + res = dfmix.copy() + result = res.replace(to_replace_res, values, inplace=True, regex=True) + assert result is res + expec = pd.DataFrame({"a": mix_ab["a"], "b": ["a_crap", "b_crap", "..", ".."]}) + tm.assert_frame_equal(res, expec) + + # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN + # or vN)] + to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"] + values = [r"\1\1", r"crap", r"\1_crap"] + res = dfmix.copy() + result = res.replace(to_replace_res, values, inplace=True, regex=True) + assert result is res + expec = pd.DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]}) + tm.assert_frame_equal(res, expec) + + to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"] + values = [r"\1\1", r"crap", r"\1_crap"] + res = dfmix.copy() + result = res.replace(regex=to_replace_res, value=values, inplace=True) + assert result is res + expec = pd.DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]}) + tm.assert_frame_equal(res, expec) + + def test_regex_replace_dict_mixed(self, mix_abc): + dfmix = pd.DataFrame(mix_abc) + + # dicts + # single dict {re1: v1}, search the whole frame + # need test for this... + + # list of dicts {re1: v1, re2: v2, ..., re3: v3}, search the whole + # frame + res = dfmix.replace({"b": r"\s*\.\s*"}, {"b": np.nan}, regex=True) + res2 = dfmix.copy() + result = res2.replace( + {"b": r"\s*\.\s*"}, {"b": np.nan}, inplace=True, regex=True + ) + assert result is res2 + expec = pd.DataFrame( + {"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]} + ) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + + # list of dicts {re1: re11, re2: re12, ..., reN: re1N}, search the + # whole frame + res = dfmix.replace({"b": r"\s*(\.)\s*"}, {"b": r"\1ty"}, regex=True) + res2 = dfmix.copy() + result = res2.replace( + {"b": r"\s*(\.)\s*"}, {"b": r"\1ty"}, inplace=True, regex=True + ) + assert result is res2 + expec = pd.DataFrame( + {"a": mix_abc["a"], "b": ["a", "b", ".ty", ".ty"], "c": mix_abc["c"]} + ) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + + res = dfmix.replace(regex={"b": r"\s*(\.)\s*"}, value={"b": r"\1ty"}) + res2 = dfmix.copy() + result = res2.replace( + regex={"b": r"\s*(\.)\s*"}, value={"b": r"\1ty"}, inplace=True + ) + assert result is res2 + expec = pd.DataFrame( + {"a": mix_abc["a"], "b": ["a", "b", ".ty", ".ty"], "c": mix_abc["c"]} + ) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + + # scalar -> dict + # to_replace regex, {value: value} + expec = pd.DataFrame( + {"a": mix_abc["a"], "b": [np.nan, "b", ".", "."], "c": mix_abc["c"]} + ) + res = dfmix.replace("a", {"b": np.nan}, regex=True) + res2 = dfmix.copy() + result = res2.replace("a", {"b": np.nan}, regex=True, inplace=True) + assert result is res2 + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + + res = dfmix.replace("a", {"b": np.nan}, regex=True) + res2 = dfmix.copy() + result = res2.replace(regex="a", value={"b": np.nan}, inplace=True) + assert result is res2 + expec = pd.DataFrame( + {"a": mix_abc["a"], "b": [np.nan, "b", ".", "."], "c": mix_abc["c"]} + ) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + + def test_regex_replace_dict_nested(self, mix_abc): + # nested dicts will not work until this is implemented for Series + dfmix = pd.DataFrame(mix_abc) + res = dfmix.replace({"b": {r"\s*\.\s*": np.nan}}, regex=True) + res2 = dfmix.copy() + res4 = dfmix.copy() + result = res2.replace({"b": {r"\s*\.\s*": np.nan}}, inplace=True, regex=True) + assert result is res2 + res3 = dfmix.replace(regex={"b": {r"\s*\.\s*": np.nan}}) + result = res4.replace(regex={"b": {r"\s*\.\s*": np.nan}}, inplace=True) + assert result is res4 + expec = pd.DataFrame( + {"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]} + ) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) + tm.assert_frame_equal(res4, expec) + + def test_regex_replace_dict_nested_non_first_character( + self, any_string_dtype, using_infer_string + ): + # GH 25259 + dtype = any_string_dtype + df = pd.DataFrame({"first": ["abc", "bca", "cab"]}, dtype=dtype) + result = df.replace({"a": "."}, regex=True) + expected = pd.DataFrame({"first": [".bc", "bc.", "c.b"]}, dtype=dtype) + tm.assert_frame_equal(result, expected) + + def test_regex_replace_dict_nested_gh4115(self): + df = pd.DataFrame( + {"Type": pd.Series(["Q", "T", "Q", "Q", "T"], dtype=object), "tmp": 2} + ) + expected = pd.DataFrame( + {"Type": pd.Series([0, 1, 0, 0, 1], dtype=object), "tmp": 2} + ) + result = df.replace({"Type": {"Q": 0, "T": 1}}) + tm.assert_frame_equal(result, expected) + + def test_regex_replace_list_to_scalar(self, mix_abc): + df = pd.DataFrame(mix_abc) + expec = pd.DataFrame( + { + "a": mix_abc["a"], + "b": pd.Series([np.nan] * 4, dtype="str"), + "c": [np.nan, np.nan, np.nan, "d"], + } + ) + + res = df.replace([r"\s*\.\s*", "a|b"], np.nan, regex=True) + res2 = df.copy() + res3 = df.copy() + result = res2.replace([r"\s*\.\s*", "a|b"], np.nan, regex=True, inplace=True) + assert result is res2 + result = res3.replace(regex=[r"\s*\.\s*", "a|b"], value=np.nan, inplace=True) + assert result is res3 + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) + + def test_regex_replace_str_to_numeric(self, mix_abc): + # what happens when you try to replace a numeric value with a regex? + df = pd.DataFrame(mix_abc) + res = df.replace(r"\s*\.\s*", 0, regex=True) + res2 = df.copy() + result = res2.replace(r"\s*\.\s*", 0, inplace=True, regex=True) + assert result is res2 + res3 = df.copy() + result = res3.replace(regex=r"\s*\.\s*", value=0, inplace=True) + assert result is res3 + expec = pd.DataFrame( + {"a": mix_abc["a"], "b": ["a", "b", 0, 0], "c": mix_abc["c"]} + ) + expec["c"] = expec["c"].astype(object) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) + + def test_regex_replace_regex_list_to_numeric(self, mix_abc): + df = pd.DataFrame(mix_abc) + res = df.replace([r"\s*\.\s*", "b"], 0, regex=True) + res2 = df.copy() + result = res2.replace([r"\s*\.\s*", "b"], 0, regex=True, inplace=True) + assert result is res2 + res3 = df.copy() + result = res3.replace(regex=[r"\s*\.\s*", "b"], value=0, inplace=True) + assert result is res3 + expec = pd.DataFrame( + {"a": mix_abc["a"], "b": ["a", 0, 0, 0], "c": ["a", 0, np.nan, "d"]} + ) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) + + def test_regex_replace_series_of_regexes(self, mix_abc): + df = pd.DataFrame(mix_abc) + s1 = pd.Series({"b": r"\s*\.\s*"}) + s2 = pd.Series({"b": np.nan}) + res = df.replace(s1, s2, regex=True) + res2 = df.copy() + result = res2.replace(s1, s2, inplace=True, regex=True) + assert result is res2 + res3 = df.copy() + result = res3.replace(regex=s1, value=s2, inplace=True) + assert result is res3 + expec = pd.DataFrame( + {"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]} + ) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) + + def test_regex_replace_numeric_to_object_conversion(self, mix_abc): + df = pd.DataFrame(mix_abc) + expec = pd.DataFrame( + {"a": ["a", 1, 2, 3], "b": mix_abc["b"], "c": mix_abc["c"]} + ) + res = df.replace(0, "a") + tm.assert_frame_equal(res, expec) + assert res.a.dtype == np.object_ + + @pytest.mark.parametrize( + "to_replace", [{"": np.nan, ",": ""}, {",": "", "": np.nan}] + ) + def test_joint_simple_replace_and_regex_replace(self, to_replace): + # GH-39338 + df = pd.DataFrame( + { + "col1": ["1,000", "a", "3"], + "col2": ["a", "", "b"], + "col3": ["a", "b", "c"], + } + ) + result = df.replace(regex=to_replace) + expected = pd.DataFrame( + { + "col1": ["1000", "a", "3"], + "col2": ["a", np.nan, "b"], + "col3": ["a", "b", "c"], + } + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("metachar", ["[]", "()", r"\d", r"\w", r"\s"]) + def test_replace_regex_metachar(self, metachar): + df = pd.DataFrame({"a": [metachar, "else"]}) + result = df.replace({"a": {metachar: "paren"}}) + expected = pd.DataFrame({"a": ["paren", "else"]}) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "data,to_replace,expected", + [ + (["xax", "xbx"], {"a": "c", "b": "d"}, ["xcx", "xdx"]), + (["d", "", ""], {r"^\s*$": pd.NA}, ["d", pd.NA, pd.NA]), + ], + ) + def test_regex_replace_string_types( + self, + data, + to_replace, + expected, + frame_or_series, + any_string_dtype, + using_infer_string, + request, + ): + # GH-41333, GH-35977 + dtype = any_string_dtype + obj = frame_or_series(data, dtype=dtype) + result = obj.replace(to_replace, regex=True) + expected = frame_or_series(expected, dtype=dtype) + + tm.assert_equal(result, expected) + + def test_replace(self, datetime_frame): + datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan + + zero_filled = datetime_frame.replace(np.nan, -1e8) + tm.assert_frame_equal(zero_filled, datetime_frame.fillna(-1e8)) + tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), datetime_frame) + + datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[:5], "B"] = -1e8 + + # empty + df = pd.DataFrame(index=["a", "b"]) + tm.assert_frame_equal(df, df.replace(5, 7)) + + # GH 11698 + # test for mixed data types. + df = pd.DataFrame( + [("-", pd.to_datetime("20150101")), ("a", pd.to_datetime("20150102"))] + ) + df1 = df.replace("-", np.nan) + expected_df = pd.DataFrame( + [(np.nan, pd.to_datetime("20150101")), ("a", pd.to_datetime("20150102"))] + ) + tm.assert_frame_equal(df1, expected_df) + + def test_replace_list(self): + obj = {"a": list("ab.."), "b": list("efgh"), "c": list("helo")} + dfobj = pd.DataFrame(obj) + + # lists of regexes and values + # list of [v1, v2, ..., vN] -> [v1, v2, ..., vN] + to_replace_res = [r".", r"e"] + values = [np.nan, "crap"] + res = dfobj.replace(to_replace_res, values) + expec = pd.DataFrame( + { + "a": ["a", "b", np.nan, np.nan], + "b": ["crap", "f", "g", "h"], + "c": ["h", "crap", "l", "o"], + } + ) + tm.assert_frame_equal(res, expec) + + # list of [v1, v2, ..., vN] -> [v1, v2, .., vN] + to_replace_res = [r".", r"f"] + values = [r"..", r"crap"] + res = dfobj.replace(to_replace_res, values) + expec = pd.DataFrame( + { + "a": ["a", "b", "..", ".."], + "b": ["e", "crap", "g", "h"], + "c": ["h", "e", "l", "o"], + } + ) + tm.assert_frame_equal(res, expec) + + def test_replace_with_empty_list(self, frame_or_series): + # GH 21977 + ser = pd.Series([["a", "b"], [], np.nan, [1]]) + obj = pd.DataFrame({"col": ser}) + obj = tm.get_obj(obj, frame_or_series) + expected = obj + result = obj.replace([], np.nan) + tm.assert_equal(result, expected) + + # GH 19266 + msg = ( + "NumPy boolean array indexing assignment cannot assign {size} " + "input values to the 1 output values where the mask is true" + ) + with pytest.raises(ValueError, match=msg.format(size=0)): + obj.replace({np.nan: []}) + with pytest.raises(ValueError, match=msg.format(size=2)): + obj.replace({np.nan: ["dummy", "alt"]}) + + def test_replace_series_dict(self): + # from GH 3064 + df = pd.DataFrame({"zero": {"a": 0.0, "b": 1}, "one": {"a": 2.0, "b": 0}}) + result = df.replace(0, {"zero": 0.5, "one": 1.0}) + expected = pd.DataFrame( + {"zero": {"a": 0.5, "b": 1}, "one": {"a": 2.0, "b": 1.0}} + ) + tm.assert_frame_equal(result, expected) + + result = df.replace(0, df.mean()) + tm.assert_frame_equal(result, expected) + + # series to series/dict + df = pd.DataFrame({"zero": {"a": 0.0, "b": 1}, "one": {"a": 2.0, "b": 0}}) + s = pd.Series({"zero": 0.0, "one": 2.0}) + result = df.replace(s, {"zero": 0.5, "one": 1.0}) + expected = pd.DataFrame( + {"zero": {"a": 0.5, "b": 1}, "one": {"a": 1.0, "b": 0.0}} + ) + tm.assert_frame_equal(result, expected) + + result = df.replace(s, df.mean()) + tm.assert_frame_equal(result, expected) + + def test_replace_convert(self, any_string_dtype): + # gh 3907 (pandas >= 3.0 no longer converts dtypes) + df = pd.DataFrame( + [["foo", "bar", "bah"], ["bar", "foo", "bah"]], dtype=any_string_dtype + ) + m = {"foo": 1, "bar": 2, "bah": 3} + rep = df.replace(m) + assert (rep.dtypes == object).all() + + def test_replace_mixed(self, float_string_frame): + mf = float_string_frame + mf.iloc[5:20, mf.columns.get_loc("foo")] = np.nan + mf.iloc[-10:, mf.columns.get_loc("A")] = np.nan + + result = float_string_frame.replace(np.nan, -18) + expected = float_string_frame.copy() + expected["foo"] = expected["foo"].astype(object) + expected = expected.fillna(value=-18) + tm.assert_frame_equal(result, expected) + expected2 = float_string_frame.copy() + expected2["foo"] = expected2["foo"].astype(object) + tm.assert_frame_equal(result.replace(-18, np.nan), expected2) + + result = float_string_frame.replace(np.nan, -1e8) + expected = float_string_frame.copy() + expected["foo"] = expected["foo"].astype(object) + expected = expected.fillna(value=-1e8) + tm.assert_frame_equal(result, expected) + expected2 = float_string_frame.copy() + expected2["foo"] = expected2["foo"].astype(object) + tm.assert_frame_equal(result.replace(-1e8, np.nan), expected2) + + def test_replace_mixed_int_block_upcasting(self): + # int block upcasting + df = pd.DataFrame( + { + "A": pd.Series([1.0, 2.0], dtype="float64"), + "B": pd.Series([0, 1], dtype="int64"), + } + ) + expected = pd.DataFrame( + { + "A": pd.Series([1.0, 2.0], dtype="float64"), + "B": pd.Series([0.5, 1], dtype="float64"), + } + ) + result = df.replace(0, 0.5) + tm.assert_frame_equal(result, expected) + + result = df.replace(0, 0.5, inplace=True) + assert result is df + tm.assert_frame_equal(df, expected) + + def test_replace_mixed_int_block_splitting(self): + # int block splitting + df = pd.DataFrame( + { + "A": pd.Series([1.0, 2.0], dtype="float64"), + "B": pd.Series([0, 1], dtype="int64"), + "C": pd.Series([1, 2], dtype="int64"), + } + ) + expected = pd.DataFrame( + { + "A": pd.Series([1.0, 2.0], dtype="float64"), + "B": pd.Series([0.5, 1], dtype="float64"), + "C": pd.Series([1, 2], dtype="int64"), + } + ) + result = df.replace(0, 0.5) + tm.assert_frame_equal(result, expected) + + def test_replace_mixed2(self): + # to object block upcasting + df = pd.DataFrame( + { + "A": pd.Series([1.0, 2.0], dtype="float64"), + "B": pd.Series([0, 1], dtype="int64"), + } + ) + expected = pd.DataFrame( + { + "A": pd.Series([1, "foo"], dtype="object"), + "B": pd.Series([0, 1], dtype="int64"), + } + ) + result = df.replace(2, "foo") + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame( + { + "A": pd.Series(["foo", "bar"], dtype="object"), + "B": pd.Series([0, "foo"], dtype="object"), + } + ) + result = df.replace([1, 2], ["foo", "bar"]) + tm.assert_frame_equal(result, expected) + + def test_replace_mixed3(self): + # test case from + df = pd.DataFrame( + { + "A": pd.Series([3, 0], dtype="int64"), + "B": pd.Series([0, 3], dtype="int64"), + } + ) + result = df.replace(3, df.mean().to_dict()) + expected = df.copy().astype("float64") + m = df.mean() + expected.iloc[0, 0] = m.iloc[0] + expected.iloc[1, 1] = m.iloc[1] + tm.assert_frame_equal(result, expected) + + def test_replace_nullable_int_with_string_doesnt_cast(self): + # GH#25438 don't cast df['a'] to float64 + df = pd.DataFrame( + {"a": [1, 2, 3, pd.NA], "b": ["some", "strings", "here", "he"]} + ) + df["a"] = df["a"].astype("Int64") + + res = df.replace("", np.nan) + tm.assert_series_equal(res["a"], df["a"]) + + @pytest.mark.parametrize("dtype", ["boolean", "Int64", "Float64"]) + def test_replace_with_nullable_column(self, dtype): + # GH-44499 + nullable_ser = pd.Series([1, 0, 1], dtype=dtype) + df = pd.DataFrame({"A": ["A", "B", "x"], "B": nullable_ser}) + result = df.replace("x", "X") + expected = pd.DataFrame({"A": ["A", "B", "X"], "B": nullable_ser}) + tm.assert_frame_equal(result, expected) + + def test_replace_simple_nested_dict(self): + df = pd.DataFrame({"col": range(1, 5)}) + expected = pd.DataFrame({"col": ["a", 2, 3, "b"]}) + + result = df.replace({"col": {1: "a", 4: "b"}}) + tm.assert_frame_equal(expected, result) + + # in this case, should be the same as the not nested version + result = df.replace({1: "a", 4: "b"}) + tm.assert_frame_equal(expected, result) + + def test_replace_simple_nested_dict_with_nonexistent_value(self): + df = pd.DataFrame({"col": range(1, 5)}) + expected = pd.DataFrame({"col": ["a", 2, 3, "b"]}) + + result = df.replace({-1: "-", 1: "a", 4: "b"}) + tm.assert_frame_equal(expected, result) + + result = df.replace({"col": {-1: "-", 1: "a", 4: "b"}}) + tm.assert_frame_equal(expected, result) + + def test_replace_NA_with_None(self): + # gh-45601 + df = pd.DataFrame({"value": [42, pd.NA]}, dtype="Int64") + result = df.replace({pd.NA: None}) + expected = pd.DataFrame({"value": [42, None]}, dtype=object) + tm.assert_frame_equal(result, expected) + + def test_replace_NAT_with_None(self): + # gh-45836 + df = pd.DataFrame([pd.NaT, pd.NaT]) + result = df.replace({pd.NaT: None, np.nan: None}) + expected = pd.DataFrame([None, None]) + tm.assert_frame_equal(result, expected) + + def test_replace_with_None_keeps_categorical(self): + # gh-46634 + cat_series = pd.Series(["b", "b", "b", "d"], dtype="category") + df = pd.DataFrame( + { + "id": pd.Series([5, 4, 3, 2], dtype="float64"), + "col": cat_series, + } + ) + result = df.replace({3: None}) + + expected = pd.DataFrame( + { + "id": pd.Series([5.0, 4.0, None, 2.0], dtype="object"), + "col": cat_series, + } + ) + tm.assert_frame_equal(result, expected) + + def test_replace_all_NA(self): + # GH#60688 + df = pd.DataFrame({"ticker": ["#1234#"], "name": [None]}) + result = df.replace({col: {r"^#": "$"} for col in df.columns}, regex=True) + expected = pd.DataFrame({"ticker": ["$1234#"], "name": [None]}) + tm.assert_frame_equal(result, expected) + + def test_replace_value_is_none(self, datetime_frame): + orig_value = datetime_frame.iloc[0, 0] + orig2 = datetime_frame.iloc[1, 0] + + datetime_frame.iloc[0, 0] = np.nan + datetime_frame.iloc[1, 0] = 1 + + result = datetime_frame.replace(to_replace={np.nan: 0}) + expected = datetime_frame.T.replace(to_replace={np.nan: 0}).T + tm.assert_frame_equal(result, expected) + + result = datetime_frame.replace(to_replace={np.nan: 0, 1: -1e8}) + tsframe = datetime_frame.copy() + tsframe.iloc[0, 0] = 0 + tsframe.iloc[1, 0] = -1e8 + expected = tsframe + tm.assert_frame_equal(expected, result) + datetime_frame.iloc[0, 0] = orig_value + datetime_frame.iloc[1, 0] = orig2 + + def test_replace_for_new_dtypes(self, datetime_frame): + # dtypes + tsframe = datetime_frame.copy().astype(np.float32) + tsframe.loc[tsframe.index[:5], "A"] = np.nan + tsframe.loc[tsframe.index[-5:], "A"] = np.nan + + zero_filled = tsframe.replace(np.nan, -1e8) + tm.assert_frame_equal(zero_filled, tsframe.fillna(-1e8)) + tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), tsframe) + + tsframe.loc[tsframe.index[:5], "A"] = np.nan + tsframe.loc[tsframe.index[-5:], "A"] = np.nan + tsframe.loc[tsframe.index[:5], "B"] = np.nan + + @pytest.mark.parametrize( + "frame, to_replace, value, expected", + [ + ( + pd.DataFrame({"ints": [1, 2, 3]}), + 1, + 0, + pd.DataFrame({"ints": [0, 2, 3]}), + ), + ( + pd.DataFrame({"ints": [1, 2, 3]}, dtype=np.int32), + 1, + 0, + pd.DataFrame({"ints": [0, 2, 3]}, dtype=np.int32), + ), + ( + pd.DataFrame({"ints": [1, 2, 3]}, dtype=np.int16), + 1, + 0, + pd.DataFrame({"ints": [0, 2, 3]}, dtype=np.int16), + ), + ( + pd.DataFrame({"bools": [True, False, True]}), + False, + True, + pd.DataFrame({"bools": [True, True, True]}), + ), + ( + pd.DataFrame({"complex": [1j, 2j, 3j]}), + 1j, + 0, + pd.DataFrame({"complex": [0j, 2j, 3j]}), + ), + ( + pd.DataFrame( + { + "datetime64": pd.Index( + [ + datetime(2018, 5, 28), + datetime(2018, 7, 28), + datetime(2018, 5, 28), + ] + ) + } + ), + datetime(2018, 5, 28), + datetime(2018, 7, 28), + pd.DataFrame({"datetime64": pd.Index([datetime(2018, 7, 28)] * 3)}), + ), + # GH 20380 + ( + pd.DataFrame({"dt": [datetime(3017, 12, 20)], "str": ["foo"]}), + "foo", + "bar", + pd.DataFrame({"dt": [datetime(3017, 12, 20)], "str": ["bar"]}), + ), + ( + pd.DataFrame( + { + "A": pd.date_range( + "20130101", periods=3, tz="US/Eastern", unit="ns" + ), + "B": [0, np.nan, 2], + } + ), + pd.Timestamp("20130102", tz="US/Eastern"), + pd.Timestamp("20130104", tz="US/Eastern"), + pd.DataFrame( + { + "A": pd.DatetimeIndex( + [ + pd.Timestamp("20130101", tz="US/Eastern"), + pd.Timestamp("20130104", tz="US/Eastern"), + pd.Timestamp("20130103", tz="US/Eastern"), + ] + ).as_unit("ns"), + "B": [0, np.nan, 2], + } + ), + ), + # GH 35376 + ( + pd.DataFrame([[1, 1.0], [2, 2.0]]), + 1.0, + 5, + pd.DataFrame([[5, 5.0], [2, 2.0]]), + ), + ( + pd.DataFrame([[1, 1.0], [2, 2.0]]), + 1, + 5, + pd.DataFrame([[5, 5.0], [2, 2.0]]), + ), + ( + pd.DataFrame([[1, 1.0], [2, 2.0]]), + 1.0, + 5.0, + pd.DataFrame([[5, 5.0], [2, 2.0]]), + ), + ( + pd.DataFrame([[1, 1.0], [2, 2.0]]), + 1, + 5.0, + pd.DataFrame([[5, 5.0], [2, 2.0]]), + ), + ], + ) + def test_replace_dtypes(self, frame, to_replace, value, expected): + result = frame.replace(to_replace, value) + tm.assert_frame_equal(result, expected) + + def test_replace_input_formats_listlike(self): + # both dicts + to_rep = {"A": np.nan, "B": 0, "C": ""} + values = {"A": 0, "B": -1, "C": "missing"} + df = pd.DataFrame( + {"A": [np.nan, 0, np.inf], "B": [0, 2, 5], "C": ["", "asdf", "fd"]} + ) + filled = df.replace(to_rep, values) + expected = {k: v.replace(to_rep[k], values[k]) for k, v in df.items()} + tm.assert_frame_equal(filled, pd.DataFrame(expected)) + + result = df.replace([0, 2, 5], [5, 2, 0]) + expected = pd.DataFrame( + {"A": [np.nan, 5, np.inf], "B": [5, 2, 0], "C": ["", "asdf", "fd"]} + ) + tm.assert_frame_equal(result, expected) + + # scalar to dict + values = {"A": 0, "B": -1, "C": "missing"} + df = pd.DataFrame( + {"A": [np.nan, 0, np.nan], "B": [0, 2, 5], "C": ["", "asdf", "fd"]} + ) + filled = df.replace(np.nan, values) + expected = {k: v.replace(np.nan, values[k]) for k, v in df.items()} + tm.assert_frame_equal(filled, pd.DataFrame(expected)) + + # list to list + to_rep = [np.nan, 0, ""] + values = [-2, -1, "missing"] + result = df.replace(to_rep, values) + expected = df.copy() + for rep, value in zip(to_rep, values, strict=True): + result = expected.replace(rep, value, inplace=True) + assert result is expected + tm.assert_frame_equal(result, expected) + + msg = r"Replacement lists must match in length\. Expecting 3 got 2" + with pytest.raises(ValueError, match=msg): + df.replace(to_rep, values[1:]) + + def test_replace_input_formats_scalar(self): + df = pd.DataFrame( + {"A": [np.nan, 0, np.inf], "B": [0, 2, 5], "C": ["", "asdf", "fd"]} + ) + + # dict to scalar + to_rep = {"A": np.nan, "B": 0, "C": ""} + filled = df.replace(to_rep, 0) + expected = {k: v.replace(to_rep[k], 0) for k, v in df.items()} + tm.assert_frame_equal(filled, pd.DataFrame(expected)) + + msg = "value argument must be scalar, dict, or Series" + with pytest.raises(TypeError, match=msg): + df.replace(to_rep, [np.nan, 0, ""]) + + # list to scalar + to_rep = [np.nan, 0, ""] + result = df.replace(to_rep, -1) + expected = df.copy() + for rep in to_rep: + result = expected.replace(rep, -1, inplace=True) + assert result is expected + tm.assert_frame_equal(result, expected) + + def test_replace_limit(self): + # TODO + pass + + def test_replace_dict_no_regex(self, any_string_dtype): + answer = pd.Series( + { + 0: "Strongly Agree", + 1: "Agree", + 2: "Neutral", + 3: "Disagree", + 4: "Strongly Disagree", + }, + dtype=any_string_dtype, + ) + weights = { + "Agree": 4, + "Disagree": 2, + "Neutral": 3, + "Strongly Agree": 5, + "Strongly Disagree": 1, + } + expected = pd.Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1}, dtype=object) + result = answer.replace(weights) + tm.assert_series_equal(result, expected) + + def test_replace_series_no_regex(self, any_string_dtype): + answer = pd.Series( + { + 0: "Strongly Agree", + 1: "Agree", + 2: "Neutral", + 3: "Disagree", + 4: "Strongly Disagree", + }, + dtype=any_string_dtype, + ) + weights = pd.Series( + { + "Agree": 4, + "Disagree": 2, + "Neutral": 3, + "Strongly Agree": 5, + "Strongly Disagree": 1, + } + ) + expected = pd.Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1}, dtype=object) + result = answer.replace(weights) + tm.assert_series_equal(result, expected) + + def test_replace_dict_tuple_list_ordering_remains_the_same(self): + df = pd.DataFrame({"A": [np.nan, 1]}) + res1 = df.replace(to_replace={np.nan: 0, 1: -1e8}) + res2 = df.replace(to_replace=(1, np.nan), value=[-1e8, 0]) + res3 = df.replace(to_replace=[1, np.nan], value=[-1e8, 0]) + + expected = pd.DataFrame({"A": [0, -1e8]}) + tm.assert_frame_equal(res1, res2) + tm.assert_frame_equal(res2, res3) + tm.assert_frame_equal(res3, expected) + + def test_replace_doesnt_replace_without_regex(self): + df = pd.DataFrame( + { + "fol": [1, 2, 2, 3], + "T_opp": ["0", "vr", "0", "0"], + "T_Dir": ["0", "0", "0", "bt"], + "T_Enh": ["vo", "0", "0", "0"], + } + ) + res = df.replace({r"\D": 1}) + tm.assert_frame_equal(df, res) + + def test_replace_bool_with_string(self): + df = pd.DataFrame({"a": [True, False], "b": list("ab")}) + result = df.replace(True, "a") + expected = pd.DataFrame({"a": ["a", False], "b": df.b}) + tm.assert_frame_equal(result, expected) + + def test_replace_pure_bool_with_string_no_op(self): + df = pd.DataFrame(np.random.default_rng(2).random((2, 2)) > 0.5) + result = df.replace("asdf", "fdsa") + tm.assert_frame_equal(df, result) + + def test_replace_bool_with_bool(self): + df = pd.DataFrame(np.random.default_rng(2).random((2, 2)) > 0.5) + result = df.replace(False, True) + expected = pd.DataFrame(np.ones((2, 2), dtype=bool)) + tm.assert_frame_equal(result, expected) + + def test_replace_with_dict_with_bool_keys(self): + df = pd.DataFrame({0: [True, False], 1: [False, True]}) + result = df.replace({"asdf": "asdb", True: "yes"}) + expected = pd.DataFrame({0: ["yes", False], 1: [False, "yes"]}) + tm.assert_frame_equal(result, expected) + + def test_replace_dict_strings_vs_ints(self): + # GH#34789 + df = pd.DataFrame({"Y0": [1, 2], "Y1": [3, 4]}) + result = df.replace({"replace_string": "test"}) + + tm.assert_frame_equal(result, df) + + result = df["Y0"].replace({"replace_string": "test"}) + tm.assert_series_equal(result, df["Y0"]) + + def test_replace_truthy(self): + df = pd.DataFrame({"a": [True, True]}) + r = df.replace([np.inf, -np.inf], np.nan) + e = df + tm.assert_frame_equal(r, e) + + def test_nested_dict_overlapping_keys_replace_int(self): + # GH 27660 keep behaviour consistent for simple dictionary and + # nested dictionary replacement + df = pd.DataFrame({"a": list(range(1, 5))}) + + result = df.replace({"a": dict(zip(range(1, 5), range(2, 6), strict=True))}) + expected = df.replace(dict(zip(range(1, 5), range(2, 6), strict=True))) + tm.assert_frame_equal(result, expected) + + def test_nested_dict_overlapping_keys_replace_str(self): + # GH 27660 + a = np.arange(1, 5) + astr = a.astype(str) + bstr = np.arange(2, 6).astype(str) + df = pd.DataFrame({"a": astr}) + result = df.replace(dict(zip(astr, bstr, strict=True))) + expected = df.replace({"a": dict(zip(astr, bstr, strict=True))}) + tm.assert_frame_equal(result, expected) + + def test_replace_swapping_bug(self): + df = pd.DataFrame({"a": [True, False, True]}) + res = df.replace({"a": {True: "Y", False: "N"}}) + expect = pd.DataFrame({"a": ["Y", "N", "Y"]}, dtype=object) + tm.assert_frame_equal(res, expect) + + df = pd.DataFrame({"a": [0, 1, 0]}) + res = df.replace({"a": {0: "Y", 1: "N"}}) + expect = pd.DataFrame({"a": ["Y", "N", "Y"]}, dtype=object) + tm.assert_frame_equal(res, expect) + + def test_replace_datetimetz(self): + # GH 11326 + # behaving poorly when presented with a datetime64[ns, tz] + df = pd.DataFrame( + { + "A": pd.date_range("20130101", periods=3, tz="US/Eastern", unit="ns"), + "B": [0, np.nan, 2], + } + ) + result = df.replace(np.nan, 1) + expected = pd.DataFrame( + { + "A": pd.date_range("20130101", periods=3, tz="US/Eastern", unit="ns"), + "B": pd.Series([0, 1, 2], dtype="float64"), + } + ) + tm.assert_frame_equal(result, expected) + + result = df.fillna(1) + tm.assert_frame_equal(result, expected) + + result = df.replace(0, np.nan) + expected = pd.DataFrame( + { + "A": pd.date_range("20130101", periods=3, tz="US/Eastern", unit="ns"), + "B": [np.nan, np.nan, 2], + } + ) + tm.assert_frame_equal(result, expected) + + result = df.replace( + pd.Timestamp("20130102", tz="US/Eastern"), + pd.Timestamp("20130104", tz="US/Eastern"), + ) + expected = pd.DataFrame( + { + "A": [ + pd.Timestamp("20130101", tz="US/Eastern"), + pd.Timestamp("20130104", tz="US/Eastern"), + pd.Timestamp("20130103", tz="US/Eastern"), + ], + "B": [0, np.nan, 2], + } + ) + expected["A"] = expected["A"].dt.as_unit("ns") + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.iloc[1, 0] = np.nan + result = result.replace( + {"A": pd.NaT}, pd.Timestamp("20130104", tz="US/Eastern") + ) + tm.assert_frame_equal(result, expected) + + # pre-2.0 this would coerce to object with mismatched tzs + result = df.copy() + result.iloc[1, 0] = np.nan + result = result.replace( + {"A": pd.NaT}, pd.Timestamp("20130104", tz="US/Pacific") + ) + expected = pd.DataFrame( + { + "A": [ + pd.Timestamp("20130101", tz="US/Eastern"), + pd.Timestamp("20130104", tz="US/Pacific").tz_convert("US/Eastern"), + pd.Timestamp("20130103", tz="US/Eastern"), + ], + "B": [0, np.nan, 2], + } + ) + expected["A"] = expected["A"].dt.as_unit("ns") + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.iloc[1, 0] = np.nan + result = result.replace({"A": np.nan}, pd.Timestamp("20130104")) + expected = pd.DataFrame( + { + "A": [ + pd.Timestamp("20130101", tz="US/Eastern"), + pd.Timestamp("20130104"), + pd.Timestamp("20130103", tz="US/Eastern"), + ], + "B": [0, np.nan, 2], + } + ) + tm.assert_frame_equal(result, expected) + + def test_replace_with_empty_dictlike(self, mix_abc): + # GH 15289 + df = pd.DataFrame(mix_abc) + tm.assert_frame_equal(df, df.replace({})) + tm.assert_frame_equal(df, df.replace(pd.Series([], dtype=object))) + + tm.assert_frame_equal(df, df.replace({"b": {}})) + tm.assert_frame_equal(df, df.replace(pd.Series({"b": {}}))) + + @pytest.mark.parametrize( + "df, to_replace, exp", + [ + ( + {"col1": [1, 2, 3], "col2": [4, 5, 6]}, + {4: 5, 5: 6, 6: 7}, + {"col1": [1, 2, 3], "col2": [5, 6, 7]}, + ), + ( + {"col1": [1, 2, 3], "col2": ["4", "5", "6"]}, + {"4": "5", "5": "6", "6": "7"}, + {"col1": [1, 2, 3], "col2": ["5", "6", "7"]}, + ), + ], + ) + def test_replace_commutative(self, df, to_replace, exp): + # GH 16051 + # DataFrame.replace() overwrites when values are non-numeric + # also added to data frame whilst issue was for series + + df = pd.DataFrame(df) + + expected = pd.DataFrame(exp) + result = df.replace(to_replace) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "replacer", + [ + pd.Timestamp("20170827"), + np.int8(1), + np.int16(1), + np.float32(1), + np.float64(1), + ], + ) + def test_replace_replacer_dtype(self, replacer): + # GH26632 + df = pd.DataFrame(["a"], dtype=object) + result = df.replace({"a": replacer, "b": replacer}) + expected = pd.DataFrame([replacer], dtype=object) + tm.assert_frame_equal(result, expected) + + def test_replace_after_convert_dtypes(self): + # GH31517 + df = pd.DataFrame({"grp": [1, 2, 3, 4, 5]}, dtype="Int64") + result = df.replace(1, 10) + expected = pd.DataFrame({"grp": [10, 2, 3, 4, 5]}, dtype="Int64") + tm.assert_frame_equal(result, expected) + + def test_replace_invalid_to_replace(self): + # GH 18634 + # API: replace() should raise an exception if invalid argument is given + df = pd.DataFrame({"one": ["a", "b ", "c"], "two": ["d ", "e ", "f "]}) + msg = ( + r"Expecting 'to_replace' to be either a scalar, array-like, " + r"dict or None, got invalid type.*" + ) + with pytest.raises(TypeError, match=msg): + df.replace(lambda x: x.strip()) + + def test_replace_ellipsis(self): + # GH#50373 Ellipsis should be accepted as a scalar to_replace + df = pd.DataFrame({"a": [1, 2, 3], "b": [..., ..., ...]}) + result = df.replace(..., 1) + expected = pd.DataFrame( + {"a": [1, 2, 3], "b": pd.Series([1, 1, 1], dtype=object)} + ) + tm.assert_frame_equal(result, expected) + + # Ellipsis is equivalent to the spelled-out singleton + tm.assert_frame_equal(df.replace(Ellipsis, 1), expected) + + def test_replace_arbitrary_object(self): + # GH#36522 non-scalar, non-list-like objects are valid to_replace values + o1, o2, o3 = object(), object(), object() + df = pd.DataFrame({"a": [o1, o2], "b": [o2, o1]}) + + result = df.replace(to_replace={"a": o1}, value={"a": o3}) + expected = pd.DataFrame({"a": [o3, o2], "b": [o2, o1]}) + tm.assert_frame_equal(result, expected) + + result = df.replace(o1, o3) + expected = pd.DataFrame({"a": [o3, o2], "b": [o2, o3]}) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["float", "float64", "int64", "Int64", "boolean"]) + @pytest.mark.parametrize("value", [np.nan, pd.NA]) + def test_replace_no_replacement_dtypes(self, dtype, value): + # https://github.com/pandas-dev/pandas/issues/32988 + df = pd.DataFrame(np.eye(2), dtype=dtype) + result = df.replace(to_replace=[None, -np.inf, np.inf], value=value) + tm.assert_frame_equal(result, df) + + @pytest.mark.parametrize("replacement", [np.nan, 5]) + def test_replace_with_duplicate_columns(self, replacement): + # GH 24798 + result = pd.DataFrame({"A": [1, 2, 3], "A1": [4, 5, 6], "B": [7, 8, 9]}) + result.columns = list("AAB") + + expected = pd.DataFrame( + {"A": [1, 2, 3], "A1": [4, 5, 6], "B": [replacement, 8, 9]} + ) + expected.columns = list("AAB") + + result["B"] = result["B"].replace(7, replacement) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("value", [pd.Period("2020-01"), pd.Interval(0, 5)]) + def test_replace_ea_ignore_float(self, frame_or_series, value): + # GH#34871 + obj = pd.DataFrame({"Per": [value] * 3}) + obj = tm.get_obj(obj, frame_or_series) + + expected = obj.copy() + result = obj.replace(1.0, 0.0) + tm.assert_equal(expected, result) + + @pytest.mark.parametrize( + "replace_dict, final_data", + [({"a": 1, "b": 1}, [[2, 2], [2, 2]]), ({"a": 1, "b": 2}, [[2, 1], [2, 2]])], + ) + def test_categorical_replace_with_dict(self, replace_dict, final_data): + # GH 26988 + df = pd.DataFrame([[1, 1], [2, 2]], columns=["a", "b"], dtype="category") + + final_data = np.array(final_data) + + a = pd.Categorical(final_data[:, 0], categories=[1, 2]) + b = pd.Categorical(final_data[:, 1], categories=[1, 2]) + + expected = pd.DataFrame({"a": a, "b": b}) + result = df.replace(replace_dict, 2) + tm.assert_frame_equal(result, expected) + msg = r"DataFrame.iloc\[:, 0\] \(column name=\"a\"\) are " "different" + with pytest.raises(AssertionError, match=msg): + # ensure non-inplace call does not affect original + tm.assert_frame_equal(df, expected) + result = df.replace(replace_dict, 2, inplace=True) + assert result is df + tm.assert_frame_equal(df, expected) + + def test_replace_value_category_type(self): + """ + Test for #23305: to ensure category dtypes are maintained + after replace with direct values + """ + + # create input data + input_dict = { + "col1": [1, 2, 3, 4], + "col2": ["a", "b", "c", "d"], + "col3": [1.5, 2.5, 3.5, 4.5], + "col4": ["cat1", "cat2", "cat3", "cat4"], + "col5": ["obj1", "obj2", "obj3", "obj4"], + } + # explicitly cast columns as category and order them + input_df = pd.DataFrame(data=input_dict).astype( + {"col2": "category", "col4": "category"} + ) + input_df["col2"] = input_df["col2"].cat.reorder_categories( + ["a", "b", "c", "d"], ordered=True + ) + input_df["col4"] = input_df["col4"].cat.reorder_categories( + ["cat1", "cat2", "cat3", "cat4"], ordered=True + ) + + # create expected dataframe + expected_dict = { + "col1": [1, 2, 3, 4], + "col2": ["a", "b", "c", "z"], + "col3": [1.5, 2.5, 3.5, 4.5], + "col4": ["cat1", "catX", "cat3", "cat4"], + "col5": ["obj9", "obj2", "obj3", "obj4"], + } + # explicitly cast columns as category and order them + expected = pd.DataFrame(data=expected_dict).astype( + {"col2": "category", "col4": "category"} + ) + expected["col2"] = expected["col2"].cat.reorder_categories( + ["a", "b", "c", "z"], ordered=True + ) + expected["col4"] = expected["col4"].cat.reorder_categories( + ["cat1", "catX", "cat3", "cat4"], ordered=True + ) + + # replace values in input dataframe + input_df = input_df.apply( + lambda x: x.astype("category").cat.rename_categories({"d": "z"}) + ) + input_df = input_df.apply( + lambda x: x.astype("category").cat.rename_categories({"obj1": "obj9"}) + ) + result = input_df.apply( + lambda x: x.astype("category").cat.rename_categories({"cat2": "catX"}) + ) + + result = result.astype({"col1": "int64", "col3": "float64", "col5": "str"}) + tm.assert_frame_equal(result, expected) + + def test_replace_dict_category_type(self): + """ + Test to ensure category dtypes are maintained + after replace with dict values + """ + # GH#35268, GH#44940 + + # create input dataframe + input_dict = {"col1": ["a"], "col2": ["obj1"], "col3": ["cat1"]} + # explicitly cast columns as category + input_df = pd.DataFrame(data=input_dict).astype( + {"col1": "category", "col2": "category", "col3": "category"} + ) + + # create expected dataframe + expected_dict = {"col1": ["z"], "col2": ["obj9"], "col3": ["catX"]} + # explicitly cast columns as category + expected = pd.DataFrame(data=expected_dict).astype( + {"col1": "category", "col2": "category", "col3": "category"} + ) + + # replace values in input dataframe using a dict + result = input_df.apply( + lambda x: x.cat.rename_categories( + {"a": "z", "obj1": "obj9", "cat1": "catX"} + ) + ) + + tm.assert_frame_equal(result, expected) + + def test_replace_with_compiled_regex(self): + # https://github.com/pandas-dev/pandas/issues/35680 + df = pd.DataFrame(["a", "b", "c"]) + regex = re.compile("^a$") + result = df.replace({regex: "z"}, regex=True) + expected = pd.DataFrame(["z", "b", "c"]) + tm.assert_frame_equal(result, expected) + + def test_replace_intervals(self): + # https://github.com/pandas-dev/pandas/issues/35931 + df = pd.DataFrame({"a": [pd.Interval(0, 1), pd.Interval(0, 1)]}) + result = df.replace({"a": {pd.Interval(0, 1): "x"}}) + expected = pd.DataFrame({"a": ["x", "x"]}, dtype=object) + tm.assert_frame_equal(result, expected) + + def test_replace_unicode(self): + # GH: 16784 + columns_values_map = {"positive": {"正面": 1, "中立": 1, "负面": 0}} + df1 = pd.DataFrame({"positive": np.ones(3)}) + result = df1.replace(columns_values_map) + expected = pd.DataFrame({"positive": np.ones(3)}) + tm.assert_frame_equal(result, expected) + + def test_replace_bytes(self, frame_or_series): + # GH#38900 + obj = frame_or_series(["o"]).astype("|S") + expected = obj.copy() + obj = obj.replace({None: np.nan}) + tm.assert_equal(obj, expected) + + @pytest.mark.parametrize( + "data, to_replace, value, expected", + [ + ([1], [1.0], [0], [0]), + ([1], [1], [0], [0]), + ([1.0], [1.0], [0], [0.0]), + ([1.0], [1], [0], [0.0]), + ], + ) + @pytest.mark.parametrize("box", [list, tuple, np.array]) + def test_replace_list_with_mixed_type( + self, data, to_replace, value, expected, box, frame_or_series + ): + # GH#40371 + obj = frame_or_series(data) + expected = frame_or_series(expected) + result = obj.replace(box(to_replace), value) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("val", [2, np.nan, 2.0]) + def test_replace_value_none_dtype_numeric(self, val): + # GH#48231 + df = pd.DataFrame({"a": [1, val]}) + result = df.replace(val, None) + expected = pd.DataFrame({"a": [1, None]}, dtype=object) + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame({"a": [1, val]}) + result = df.replace({val: None}) + tm.assert_frame_equal(result, expected) + + def test_replace_with_nil_na(self): + # GH 32075 + ser = pd.DataFrame({"a": ["nil", pd.NA]}) + expected = pd.DataFrame({"a": ["anything else", pd.NA]}, index=[0, 1]) + result = ser.replace("nil", "anything else") + tm.assert_frame_equal(expected, result) + + @pytest.mark.parametrize( + "dtype", + [ + "Float64", + pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow")), + ], + ) + def test_replace_na_to_nan_nullable_floats(self, dtype, using_nan_is_na): + # GH#55127 + df = pd.DataFrame({0: [1, np.nan, 1], 1: pd.Series([0, pd.NA, 1], dtype=dtype)}) + + result = df.replace(pd.NA, np.nan) + + if using_nan_is_na: + expected = result + else: + expected = pd.DataFrame( + {0: [1, np.nan, 1], 1: pd.Series([0, np.nan, 1], dtype=dtype)} + ) + assert np.isnan(expected.loc[1, 1]) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "dtype", + [ + "Int64", + pytest.param("int64[pyarrow]", marks=td.skip_if_no("pyarrow")), + ], + ) + def test_replace_nan_nullable_ints(self, dtype, using_nan_is_na): + # GH#51237 with nan_is_na=False, replacing NaN should be a no-op here + ser = pd.Series([1, 2, None], dtype=dtype) + + result = ser.replace(np.nan, -1) + + if using_nan_is_na: + # np.nan is equivalent to pd.NA here + expected = pd.Series([1, 2, -1], dtype=dtype) + else: + expected = ser + tm.assert_series_equal(result, expected) + + def test_replace_datetime_out_of_bounds_for_ns(self): + # GH#61671 + df = pd.DataFrame([np.nan], dtype="datetime64[ns]") + with pytest.raises(OutOfBoundsDatetime, match="Explicitly cast"): + df.replace(np.nan, datetime(3000, 1, 1)) + + +class TestDataFrameReplaceRegex: + @pytest.mark.parametrize( + "data", + [ + {"a": list("ab.."), "b": list("efgh")}, + {"a": list("ab.."), "b": list(range(4))}, + ], + ) + @pytest.mark.parametrize( + "to_replace,value", [(r"\s*\.\s*", np.nan), (r"\s*(\.)\s*", r"\1\1\1")] + ) + @pytest.mark.parametrize("compile_regex", [True, False]) + @pytest.mark.parametrize("regex_kwarg", [True, False]) + @pytest.mark.parametrize("inplace", [True, False]) + def test_regex_replace_scalar( + self, data, to_replace, value, compile_regex, regex_kwarg, inplace + ): + df = pd.DataFrame(data) + expected = df.copy() + + if compile_regex: + to_replace = re.compile(to_replace) + + if regex_kwarg: + regex = to_replace + to_replace = None + else: + regex = True + + result = df.replace(to_replace, value, inplace=inplace, regex=regex) + + if inplace: + assert result is df + result = df + + if value is np.nan: + expected_replace_val = np.nan + else: + expected_replace_val = "..." + + expected.loc[expected["a"] == ".", "a"] = expected_replace_val + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("regex", [False, True]) + @pytest.mark.parametrize("value", [1, "1"]) + def test_replace_regex_dtype_frame(self, regex, value): + # GH-48644 + df1 = pd.DataFrame({"A": ["0"], "B": ["0"]}) + # When value is an integer, coerce result to object. + # When value is a string, infer the correct string dtype. + dtype = object if value == 1 else None + + expected_df1 = pd.DataFrame({"A": [value], "B": [value]}, dtype=dtype) + result_df1 = df1.replace(to_replace="0", value=value, regex=regex) + tm.assert_frame_equal(result_df1, expected_df1) + + df2 = pd.DataFrame({"A": ["0"], "B": ["1"]}) + if regex: + expected_df2 = pd.DataFrame({"A": [value], "B": ["1"]}, dtype=dtype) + else: + expected_df2 = pd.DataFrame( + {"A": pd.Series([value], dtype=dtype), "B": ["1"]} + ) + result_df2 = df2.replace(to_replace="0", value=value, regex=regex) + tm.assert_frame_equal(result_df2, expected_df2) + + def test_replace_with_value_also_being_replaced(self): + # GH46306 + df = pd.DataFrame({"A": [0, 1, 2], "B": [1, 0, 2]}) + result = df.replace({0: 1, 1: np.nan}) + expected = pd.DataFrame({"A": [1, np.nan, 2], "B": [np.nan, 1, 2]}) + tm.assert_frame_equal(result, expected) + + def test_replace_categorical_no_replacement(self): + # GH#46672 + df = pd.DataFrame( + { + "a": ["one", "two", None, "three"], + "b": ["one", None, "two", "three"], + }, + dtype="category", + ) + expected = df.copy() + + result = df.replace(to_replace=[".", "def"], value=["_", None]) + tm.assert_frame_equal(result, expected) + + def test_replace_object_splitting(self, using_infer_string): + # GH#53977 + df = pd.DataFrame({"a": ["a"], "b": "b"}) + if using_infer_string: + assert len(df._mgr.blocks) == 2 + else: + assert len(df._mgr.blocks) == 1 + df.replace(to_replace=r"^\s*$", value="", inplace=True, regex=True) + if using_infer_string: + assert len(df._mgr.blocks) == 2 + else: + assert len(df._mgr.blocks) == 1 + + +@pytest.mark.parametrize( + "replace_kwargs", + [ + {"to_replace": {1: "x", 99: "y"}}, + {"to_replace": [1, 99], "value": ["x", "y"]}, + {"to_replace": [1, 99, 98], "value": ["x", "y", "z"]}, + ], +) +def test_replace_list_multiple_unchanged_columns(replace_kwargs): + # GH#61972 dropping the temporary blocks from the refs popped by stale + # indices, so two or more unchanged columns raised IndexError + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) + result = df.replace(**replace_kwargs) + + expected = pd.DataFrame({"a": ["x", 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reset_index.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reset_index.py new file mode 100644 index 0000000000000000000000000000000000000000..5421d4102fc932e4491a34e46593c2523ad8c8e8 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_reset_index.py @@ -0,0 +1,856 @@ +from datetime import datetime +from itertools import product + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +from pandas.core.dtypes.common import ( + is_float_dtype, + is_integer_dtype, +) + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def multiindex_df(): + levels = [["A", ""], ["B", "b"]] + return pd.DataFrame([[0, 2], [1, 3]], columns=pd.MultiIndex.from_tuples(levels)) + + +class TestResetIndex: + def test_reset_index_empty_rangeindex(self): + # GH#45230 + df = pd.DataFrame( + columns=["brand"], dtype=np.int64, index=pd.RangeIndex(0, 0, 1, name="foo") + ) + + df2 = df.set_index([df.index, "brand"]) + + result = df2.reset_index([1], drop=True) + tm.assert_frame_equal(result, df[[]], check_index_type=True) + + def test_set_reset(self): + idx = pd.Index([2**63, 2**63 + 5, 2**63 + 10], name="foo") + + # set/reset + df = pd.DataFrame({"A": [0, 1, 2]}, index=idx) + result = df.reset_index() + assert result["foo"].dtype == np.dtype("uint64") + + df = result.set_index("foo") + tm.assert_index_equal(df.index, idx) + + def test_set_index_reset_index_dt64tz(self): + idx = pd.Index( + pd.date_range("20130101", periods=3, tz="US/Eastern", unit="ns"), name="foo" + ) + + # set/reset + df = pd.DataFrame({"A": [0, 1, 2]}, index=idx) + result = df.reset_index() + assert result["foo"].dtype == "datetime64[ns, US/Eastern]" + + df = result.set_index("foo") + tm.assert_index_equal(df.index, idx, check_freq=False) + + def test_reset_index_tz(self, tz_aware_fixture): + # GH 3950 + # reset_index with single level + tz = tz_aware_fixture + idx = pd.date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx") + df = pd.DataFrame({"a": range(5), "b": ["A", "B", "C", "D", "E"]}, index=idx) + + expected = pd.DataFrame( + { + "idx": idx, + "a": range(5), + "b": ["A", "B", "C", "D", "E"], + }, + columns=["idx", "a", "b"], + ) + result = df.reset_index() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) + def test_frame_reset_index_tzaware_index(self, tz): + dr = pd.date_range("2012-06-02", periods=10, tz=tz) + df = pd.DataFrame(np.random.default_rng(2).standard_normal(len(dr)), dr) + roundtripped = df.reset_index().set_index("index") + xp = df.index.tz + rs = roundtripped.index.tz + assert xp == rs + + def test_reset_index_with_intervals(self): + idx = pd.IntervalIndex.from_breaks(np.arange(11), name="x") + original = pd.DataFrame({"x": idx, "y": np.arange(10)})[["x", "y"]] + + result = original.set_index("x") + expected = pd.DataFrame({"y": np.arange(10)}, index=idx) + tm.assert_frame_equal(result, expected) + + result2 = result.reset_index() + tm.assert_frame_equal(result2, original) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.reset_index") + def test_reset_index(self, float_frame): + stacked = float_frame.stack()[::2] + stacked = pd.DataFrame({"foo": stacked, "bar": stacked}) + + names = ["first", "second"] + stacked.index.names = names + deleveled = stacked.reset_index() + for i, (lev, level_codes) in enumerate( + zip(stacked.index.levels, stacked.index.codes, strict=True) + ): + values = lev.take(level_codes) + name = names[i] + tm.assert_index_equal(values, pd.Index(deleveled[name])) + + stacked.index.names = [None, None] + deleveled2 = stacked.reset_index() + tm.assert_series_equal( + deleveled["first"], deleveled2["level_0"], check_names=False + ) + tm.assert_series_equal( + deleveled["second"], deleveled2["level_1"], check_names=False + ) + + # default name assigned + rdf = float_frame.reset_index() + exp = pd.Series(float_frame.index.values, name="index") + tm.assert_series_equal(rdf["index"], exp) + + # default name assigned, corner case + df = float_frame.copy() + df["index"] = "foo" + rdf = df.reset_index() + exp = pd.Series(float_frame.index.values, name="level_0") + tm.assert_series_equal(rdf["level_0"], exp) + + # but this is ok + float_frame.index.name = "index" + deleveled = float_frame.reset_index() + tm.assert_series_equal(deleveled["index"], pd.Series(float_frame.index)) + tm.assert_index_equal( + deleveled.index, pd.Index(range(len(deleveled))), exact=True + ) + + # preserve column names + float_frame.columns.name = "columns" + reset = float_frame.reset_index() + assert reset.columns.name == "columns" + + # only remove certain columns + df = float_frame.reset_index().set_index(["index", "A", "B"]) + rs = df.reset_index(["A", "B"]) + + tm.assert_frame_equal(rs, float_frame) + + rs = df.reset_index(["index", "A", "B"]) + tm.assert_frame_equal(rs, float_frame.reset_index()) + + rs = df.reset_index(["index", "A", "B"]) + tm.assert_frame_equal(rs, float_frame.reset_index()) + + rs = df.reset_index("A") + xp = float_frame.reset_index().set_index(["index", "B"]) + tm.assert_frame_equal(rs, xp) + + # test resetting in place + df = float_frame.copy() + reset = float_frame.reset_index() + return_value = df.reset_index(inplace=True) + assert return_value is None + tm.assert_frame_equal(df, reset) + + df = float_frame.reset_index().set_index(["index", "A", "B"]) + rs = df.reset_index("A", drop=True) + xp = float_frame.copy() + del xp["A"] + xp = xp.set_index(["B"], append=True) + tm.assert_frame_equal(rs, xp) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.reset_index") + def test_reset_index_name(self): + df = pd.DataFrame( + [[1, 2, 3, 4], [5, 6, 7, 8]], + columns=["A", "B", "C", "D"], + index=pd.Index(range(2), name="x"), + ) + assert df.reset_index().index.name is None + assert df.reset_index(drop=True).index.name is None + return_value = df.reset_index(inplace=True) + assert return_value is None + assert df.index.name is None + + @pytest.mark.parametrize("levels", [["A", "B"], [0, 1]]) + def test_reset_index_level(self, levels): + df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "C", "D"]) + + # With MultiIndex + result = df.set_index(["A", "B"]).reset_index(level=levels[0]) + tm.assert_frame_equal(result, df.set_index("B")) + + result = df.set_index(["A", "B"]).reset_index(level=levels[:1]) + tm.assert_frame_equal(result, df.set_index("B")) + + result = df.set_index(["A", "B"]).reset_index(level=levels) + tm.assert_frame_equal(result, df) + + result = df.set_index(["A", "B"]).reset_index(level=levels, drop=True) + tm.assert_frame_equal(result, df[["C", "D"]]) + + # With single-level Index (GH 16263) + result = df.set_index("A").reset_index(level=levels[0]) + tm.assert_frame_equal(result, df) + + result = df.set_index("A").reset_index(level=levels[:1]) + tm.assert_frame_equal(result, df) + + result = df.set_index(["A"]).reset_index(level=levels[0], drop=True) + tm.assert_frame_equal(result, df[["B", "C", "D"]]) + + @pytest.mark.parametrize("idx_lev", [["A", "B"], ["A"]]) + def test_reset_index_level_missing(self, idx_lev): + # Missing levels - for both MultiIndex and single-level Index: + df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "C", "D"]) + + with pytest.raises(KeyError, match=r"(L|l)evel \(?E\)?"): + df.set_index(idx_lev).reset_index(level=["A", "E"]) + with pytest.raises(IndexError, match="Too many levels"): + df.set_index(idx_lev).reset_index(level=[0, 1, 2]) + + def test_reset_index_right_dtype(self): + time = np.arange(0.0, 10, np.sqrt(2) / 2) + s1 = pd.Series( + (9.81 * time**2) / 2, index=pd.Index(time, name="time"), name="speed" + ) + df = pd.DataFrame(s1) + + reset = s1.reset_index() + assert reset["time"].dtype == np.float64 + + reset = df.reset_index() + assert reset["time"].dtype == np.float64 + + def test_reset_index_multiindex_col(self): + vals = np.random.default_rng(2).standard_normal((3, 3)).astype(object) + idx = ["x", "y", "z"] + full = np.hstack(([[x] for x in idx], vals)) + df = pd.DataFrame( + vals, + pd.Index(idx, name="a"), + columns=[["b", "b", "c"], ["mean", "median", "mean"]], + ) + rs = df.reset_index() + xp = pd.DataFrame( + full, columns=[["a", "b", "b", "c"], ["", "mean", "median", "mean"]] + ) + tm.assert_frame_equal(rs, xp) + + rs = df.reset_index(col_fill=None) + xp = pd.DataFrame( + full, columns=[["a", "b", "b", "c"], ["a", "mean", "median", "mean"]] + ) + tm.assert_frame_equal(rs, xp) + + rs = df.reset_index(col_level=1, col_fill="blah") + xp = pd.DataFrame( + full, columns=[["blah", "b", "b", "c"], ["a", "mean", "median", "mean"]] + ) + tm.assert_frame_equal(rs, xp) + + df = pd.DataFrame( + vals, + pd.MultiIndex.from_arrays([[0, 1, 2], ["x", "y", "z"]], names=["d", "a"]), + columns=[["b", "b", "c"], ["mean", "median", "mean"]], + ) + rs = df.reset_index("a") + xp = pd.DataFrame( + full, + pd.Index([0, 1, 2], name="d"), + columns=[["a", "b", "b", "c"], ["", "mean", "median", "mean"]], + ) + tm.assert_frame_equal(rs, xp) + + rs = df.reset_index("a", col_fill=None) + xp = pd.DataFrame( + full, + pd.Index(range(3), name="d"), + columns=[["a", "b", "b", "c"], ["a", "mean", "median", "mean"]], + ) + tm.assert_frame_equal(rs, xp) + + rs = df.reset_index("a", col_fill="blah", col_level=1) + xp = pd.DataFrame( + full, + pd.Index(range(3), name="d"), + columns=[["blah", "b", "b", "c"], ["a", "mean", "median", "mean"]], + ) + tm.assert_frame_equal(rs, xp) + + def test_reset_index_multiindex_nan(self): + # GH#6322, testing reset_index on MultiIndexes + # when we have a nan or all nan + df = pd.DataFrame( + { + "A": ["a", "b", "c"], + "B": [0, 1, np.nan], + "C": np.random.default_rng(2).random(3), + } + ) + rs = df.set_index(["A", "B"]).reset_index() + tm.assert_frame_equal(rs, df) + + df = pd.DataFrame( + { + "A": [np.nan, "b", "c"], + "B": [0, 1, 2], + "C": np.random.default_rng(2).random(3), + } + ) + rs = df.set_index(["A", "B"]).reset_index() + tm.assert_frame_equal(rs, df) + + df = pd.DataFrame( + {"A": ["a", "b", "c"], "B": [0, 1, 2], "C": [np.nan, 1.1, 2.2]} + ) + rs = df.set_index(["A", "B"]).reset_index() + tm.assert_frame_equal(rs, df) + + df = pd.DataFrame( + { + "A": ["a", "b", "c"], + "B": [np.nan, np.nan, np.nan], + "C": np.random.default_rng(2).random(3), + } + ) + rs = df.set_index(["A", "B"]).reset_index() + tm.assert_frame_equal(rs, df) + + @pytest.mark.parametrize( + "name", + [ + None, + "foo", + 2, + 3.0, + pd.Timedelta(6), + pd.Timestamp("2012-12-30", tz="UTC"), + "2012-12-31", + ], + ) + def test_reset_index_with_datetimeindex_cols(self, name): + # GH#5818 + df = pd.DataFrame( + [[1, 2], [3, 4]], + columns=pd.date_range("1/1/2013", "1/2/2013", unit="ns"), + index=["A", "B"], + ) + df.index.name = name + + result = df.reset_index() + + item = name if name is not None else "index" + columns = pd.Index([item, datetime(2013, 1, 1), datetime(2013, 1, 2)]) + if isinstance(item, str) and item == "2012-12-31": + columns = pd.DatetimeIndex(columns, dtype="datetime64[ns]", freq="D") + else: + assert columns.dtype == object + + expected = pd.DataFrame( + [["A", 1, 2], ["B", 3, 4]], + columns=columns, + ) + tm.assert_frame_equal(result, expected) + + def test_reset_index_range(self): + # GH#12071 + df = pd.DataFrame( + [[0, 0], [1, 1]], columns=["A", "B"], index=pd.RangeIndex(stop=2) + ) + result = df.reset_index() + assert isinstance(result.index, pd.RangeIndex) + expected = pd.DataFrame( + [[0, 0, 0], [1, 1, 1]], + columns=["index", "A", "B"], + index=pd.RangeIndex(stop=2), + ) + tm.assert_frame_equal(result, expected) + + def test_reset_index_multiindex_columns(self, multiindex_df): + result = multiindex_df[["B"]].rename_axis("A").reset_index() + tm.assert_frame_equal(result, multiindex_df) + + # GH#16120: already existing column + msg = r"cannot insert \('A', ''\), already exists" + with pytest.raises(ValueError, match=msg): + multiindex_df.rename_axis("A").reset_index() + + # GH#16164: multiindex (tuple) full key + result = multiindex_df.set_index([("A", "")]).reset_index() + tm.assert_frame_equal(result, multiindex_df) + + # with additional (unnamed) index level + idx_col = pd.DataFrame( + [[0], [1]], columns=pd.MultiIndex.from_tuples([("level_0", "")]) + ) + expected = pd.concat([idx_col, multiindex_df[[("B", "b"), ("A", "")]]], axis=1) + result = multiindex_df.set_index([("B", "b")], append=True).reset_index() + tm.assert_frame_equal(result, expected) + + # with index name which is a too long tuple... + msg = "Item must have length equal to number of levels." + with pytest.raises(ValueError, match=msg): + multiindex_df.rename_axis([("C", "c", "i")]).reset_index() + + # or too short... + levels = [["A", "a", ""], ["B", "b", "i"]] + df2 = pd.DataFrame([[0, 2], [1, 3]], columns=pd.MultiIndex.from_tuples(levels)) + idx_col = pd.DataFrame( + [[0], [1]], columns=pd.MultiIndex.from_tuples([("C", "c", "ii")]) + ) + expected = pd.concat([idx_col, df2], axis=1) + result = df2.rename_axis([("C", "c")]).reset_index(col_fill="ii") + tm.assert_frame_equal(result, expected) + + # ... which is incompatible with col_fill=None + with pytest.raises( + ValueError, + match=( + "col_fill=None is incompatible with " + r"incomplete column name \('C', 'c'\)" + ), + ): + df2.rename_axis([("C", "c")]).reset_index(col_fill=None) + + # with col_level != 0 + result = df2.rename_axis([("c", "ii")]).reset_index(col_level=1, col_fill="C") + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("flag", [False, True]) + @pytest.mark.parametrize("allow_duplicates", [False, True]) + def test_reset_index_duplicate_columns_allow( + self, multiindex_df, flag, allow_duplicates + ): + # GH#44755 reset_index with duplicate column labels + df = multiindex_df.rename_axis("A") + df = df.set_flags(allows_duplicate_labels=flag) + + if flag and allow_duplicates: + result = df.reset_index(allow_duplicates=allow_duplicates) + levels = [["A", ""], ["A", ""], ["B", "b"]] + expected = pd.DataFrame( + [[0, 0, 2], [1, 1, 3]], columns=pd.MultiIndex.from_tuples(levels) + ) + tm.assert_frame_equal(result, expected) + else: + if not flag and allow_duplicates: + msg = ( + "Cannot specify 'allow_duplicates=True' when " + "'self.flags.allows_duplicate_labels' is False" + ) + else: + msg = r"cannot insert \('A', ''\), already exists" + with pytest.raises(ValueError, match=msg): + df.reset_index(allow_duplicates=allow_duplicates) + + @pytest.mark.parametrize("flag", [False, True]) + def test_reset_index_duplicate_columns_default(self, multiindex_df, flag): + df = multiindex_df.rename_axis("A") + df = df.set_flags(allows_duplicate_labels=flag) + + msg = r"cannot insert \('A', ''\), already exists" + with pytest.raises(ValueError, match=msg): + df.reset_index() + + @pytest.mark.parametrize("allow_duplicates", ["bad value"]) + def test_reset_index_allow_duplicates_check(self, multiindex_df, allow_duplicates): + with pytest.raises(ValueError, match="expected type bool"): + multiindex_df.reset_index(allow_duplicates=allow_duplicates) + + def test_reset_index_datetime(self, tz_naive_fixture): + # GH#3950 + tz = tz_naive_fixture + idx1 = pd.date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx1") + idx2 = pd.Index(range(5), name="idx2", dtype="int64") + idx = pd.MultiIndex.from_arrays([idx1, idx2]) + df = pd.DataFrame( + {"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]}, + index=idx, + ) + + expected = pd.DataFrame( + { + "idx1": idx1, + "idx2": np.arange(5, dtype="int64"), + "a": np.arange(5, dtype="int64"), + "b": ["A", "B", "C", "D", "E"], + }, + columns=["idx1", "idx2", "a", "b"], + ) + + tm.assert_frame_equal(df.reset_index(), expected) + + def test_reset_index_datetime2(self, tz_naive_fixture): + tz = tz_naive_fixture + idx1 = pd.date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx1") + idx2 = pd.Index(range(5), name="idx2", dtype="int64") + idx3 = pd.date_range( + "1/1/2012", periods=5, freq="MS", tz="Europe/Paris", name="idx3" + ) + idx = pd.MultiIndex.from_arrays([idx1, idx2, idx3]) + df = pd.DataFrame( + {"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]}, + index=idx, + ) + + expected = pd.DataFrame( + { + "idx1": idx1, + "idx2": np.arange(5, dtype="int64"), + "idx3": idx3, + "a": np.arange(5, dtype="int64"), + "b": ["A", "B", "C", "D", "E"], + }, + columns=["idx1", "idx2", "idx3", "a", "b"], + ) + result = df.reset_index() + tm.assert_frame_equal(result, expected) + + def test_reset_index_datetime3(self, tz_naive_fixture): + # GH#7793 + tz = tz_naive_fixture + dti = pd.date_range("20130101", periods=3, tz=tz) + idx = pd.MultiIndex.from_product([["a", "b"], dti]) + df = pd.DataFrame( + np.arange(6, dtype="int64").reshape(6, 1), columns=["a"], index=idx + ) + + expected = pd.DataFrame( + { + "level_0": "a a a b b b".split(), + "level_1": dti.append(dti), + "a": np.arange(6, dtype="int64"), + }, + columns=["level_0", "level_1", "a"], + ) + result = df.reset_index() + tm.assert_frame_equal(result, expected) + + def test_reset_index_period(self): + # GH#7746 + idx = pd.MultiIndex.from_product( + [pd.period_range("20130101", periods=3, freq="M"), list("abc")], + names=["month", "feature"], + ) + + df = pd.DataFrame( + np.arange(9, dtype="int64").reshape(-1, 1), index=idx, columns=["a"] + ) + expected = pd.DataFrame( + { + "month": ( + [pd.Period("2013-01", freq="M")] * 3 + + [pd.Period("2013-02", freq="M")] * 3 + + [pd.Period("2013-03", freq="M")] * 3 + ), + "feature": ["a", "b", "c"] * 3, + "a": np.arange(9, dtype="int64"), + }, + columns=["month", "feature", "a"], + ) + result = df.reset_index() + tm.assert_frame_equal(result, expected) + + def test_reset_index_delevel_infer_dtype(self): + tuples = list(product(["foo", "bar"], [10, 20], [1.0, 1.1])) + index = pd.MultiIndex.from_tuples(tuples, names=["prm0", "prm1", "prm2"]) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((8, 3)), + columns=["A", "B", "C"], + index=index, + ) + deleveled = df.reset_index() + assert is_integer_dtype(deleveled["prm1"]) + assert is_float_dtype(deleveled["prm2"]) + + def test_reset_index_with_drop( + self, multiindex_year_month_day_dataframe_random_data + ): + ymd = multiindex_year_month_day_dataframe_random_data + + deleveled = ymd.reset_index(drop=True) + assert len(deleveled.columns) == len(ymd.columns) + assert deleveled.index.name == ymd.index.name + + @pytest.mark.parametrize( + "ix_data, exp_data", + [ + ( + [(pd.NaT, 1), (pd.NaT, 2)], + {"a": [pd.NaT, pd.NaT], "b": [1, 2], "x": [11, 12]}, + ), + ( + [(pd.NaT, 1), (pd.Timestamp("2020-01-01"), 2)], + {"a": [pd.NaT, pd.Timestamp("2020-01-01")], "b": [1, 2], "x": [11, 12]}, + ), + ( + [(pd.NaT, 1), (pd.Timedelta(123, "D"), 2)], + {"a": [pd.NaT, pd.Timedelta(123, "D")], "b": [1, 2], "x": [11, 12]}, + ), + ], + ) + def test_reset_index_nat_multiindex(self, ix_data, exp_data): + # GH#36541: that reset_index() does not raise ValueError + ix = pd.MultiIndex.from_tuples(ix_data, names=["a", "b"]) + result = pd.DataFrame({"x": [11, 12]}, index=ix) + result = result.reset_index() + + expected = pd.DataFrame(exp_data) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "codes", ([[0, 0, 1, 1], [0, 1, 0, 1]], [[0, 0, -1, 1], [0, 1, 0, 1]]) + ) + def test_rest_index_multiindex_categorical_with_missing_values(self, codes): + # GH#24206 + + index = pd.MultiIndex( + [pd.CategoricalIndex(["A", "B"]), pd.CategoricalIndex(["a", "b"])], codes + ) + data = {"col": range(len(index))} + df = pd.DataFrame(data=data, index=index) + + expected = pd.DataFrame( + { + "level_0": pd.Categorical.from_codes(codes[0], categories=["A", "B"]), + "level_1": pd.Categorical.from_codes(codes[1], categories=["a", "b"]), + "col": range(4), + } + ) + + res = df.reset_index() + tm.assert_frame_equal(res, expected) + + # roundtrip + res = expected.set_index(["level_0", "level_1"]).reset_index() + tm.assert_frame_equal(res, expected) + + +@pytest.mark.parametrize( + "array, dtype", + [ + (["a", "b"], object), + ( + pd.period_range("12-1-2000", periods=2, freq="Q-DEC"), + pd.PeriodDtype(freq="Q-DEC"), + ), + ], +) +def test_reset_index_dtypes_on_empty_frame_with_multiindex( + array, dtype, using_infer_string +): + # GH 19602 - Preserve dtype on empty DataFrame with MultiIndex + idx = pd.MultiIndex.from_product([[0, 1], [0.5, 1.0], array]) + result = pd.DataFrame(index=idx)[:0].reset_index().dtypes + if using_infer_string and dtype == object: + dtype = pd.StringDtype(na_value=np.nan) + expected = pd.Series({"level_0": np.int64, "level_1": np.float64, "level_2": dtype}) + tm.assert_series_equal(result, expected) + + +def test_reset_index_infers_dtype_from_object_levels(): + # GH#58517 object-dtype MultiIndex levels are inferred to concrete dtypes + # when they are moved into columns + mi = pd.MultiIndex.from_arrays( + [ + pd.Index([1, 2], dtype=object), + pd.Index([1.5, 2.5], dtype=object), + pd.Index([True, False], dtype=object), + ], + names=["i", "f", "b"], + ) + result = pd.DataFrame({"v": [1, 2]}, index=mi).reset_index() + expected = pd.DataFrame( + {"i": [1, 2], "f": [1.5, 2.5], "b": [True, False], "v": [1, 2]} + ) + tm.assert_frame_equal(result, expected) + + +def test_reset_index_empty_frame_with_datetime64_multiindex(): + # https://github.com/pandas-dev/pandas/issues/35606 + dti = pd.DatetimeIndex(["2020-07-20 00:00:00"], dtype="M8[ns]") + idx = pd.MultiIndex.from_product([dti, [3, 4]], names=["a", "b"])[:0] + df = pd.DataFrame(index=idx, columns=["c", "d"]) + result = df.reset_index() + expected = pd.DataFrame( + columns=list("abcd"), index=pd.RangeIndex(start=0, stop=0, step=1) + ) + expected["a"] = expected["a"].astype("datetime64[ns]") + expected["b"] = expected["b"].astype("int64") + tm.assert_frame_equal(result, expected) + + +def test_reset_index_empty_frame_with_datetime64_multiindex_from_groupby( + using_infer_string, +): + # https://github.com/pandas-dev/pandas/issues/35657 + dti = pd.DatetimeIndex(["2020-01-01"], dtype="M8[ns]") + df = pd.DataFrame({"c1": [10.0], "c2": ["a"], "c3": dti}) + df = df.head(0).groupby(["c2", "c3"])[["c1"]].sum() + result = df.reset_index() + expected = pd.DataFrame( + columns=["c2", "c3", "c1"], index=pd.RangeIndex(start=0, stop=0, step=1) + ) + expected["c3"] = expected["c3"].astype("datetime64[ns]") + expected["c1"] = expected["c1"].astype("float64") + if using_infer_string: + expected["c2"] = expected["c2"].astype("str") + tm.assert_frame_equal(result, expected) + + +def test_reset_index_multiindex_nat(): + # GH 11479 + idx = range(3) + tstamp = pd.date_range("2015-07-01", freq="D", periods=3, unit="ns") + df = pd.DataFrame({"id": idx, "tstamp": tstamp, "a": list("abc")}) + df.loc[2, "tstamp"] = pd.NaT + result = df.set_index(["id", "tstamp"]).reset_index("id") + exp_dti = pd.DatetimeIndex( + ["2015-07-01", "2015-07-02", "NaT"], dtype="M8[ns]", name="tstamp" + ) + expected = pd.DataFrame( + {"id": range(3), "a": list("abc")}, + index=exp_dti, + ) + tm.assert_frame_equal(result, expected) + + +def test_reset_index_interval_columns_object_cast(): + # GH 19136 + df = pd.DataFrame( + np.eye(2), + index=pd.Index([1, 2], name="Year"), + columns=pd.cut([1, 2], [0, 1, 2]), + ) + result = df.reset_index() + expected = pd.DataFrame( + [[1, 1.0, 0.0], [2, 0.0, 1.0]], + columns=pd.Index(["Year", pd.Interval(0, 1), pd.Interval(1, 2)]), + ) + tm.assert_frame_equal(result, expected) + + +def test_reset_index_rename(float_frame): + # GH 6878 + result = float_frame.reset_index(names="new_name") + expected = pd.Series(float_frame.index.values, name="new_name") + tm.assert_series_equal(result["new_name"], expected) + + result = float_frame.reset_index(names=123) + expected = pd.Series(float_frame.index.values, name=123) + tm.assert_series_equal(result[123], expected) + + +def test_reset_index_rename_multiindex(float_frame): + # GH 6878 + stacked_df = float_frame.stack()[::2] + stacked_df = pd.DataFrame({"foo": stacked_df, "bar": stacked_df}) + + names = ["first", "second"] + stacked_df.index.names = names + + result = stacked_df.reset_index() + expected = stacked_df.reset_index(names=["new_first", "new_second"]) + tm.assert_series_equal(result["first"], expected["new_first"], check_names=False) + tm.assert_series_equal(result["second"], expected["new_second"], check_names=False) + + +def test_errorreset_index_rename(float_frame): + # GH 6878 + stacked_df = float_frame.stack()[::2] + stacked_df = pd.DataFrame({"first": stacked_df, "second": stacked_df}) + + with pytest.raises( + ValueError, match="Index names must be str or 1-dimensional list" + ): + stacked_df.reset_index(names={"first": "new_first", "second": "new_second"}) + + with pytest.raises(IndexError, match="list index out of range"): + stacked_df.reset_index(names=["new_first"]) + + +def test_reset_index_false_index_name(): + result_series = pd.Series(data=range(5, 10), index=range(5)) + result_series.index.name = False + result_series.reset_index() + expected_series = pd.Series(range(5, 10), pd.RangeIndex(range(5), name=False)) + tm.assert_series_equal(result_series, expected_series) + + # GH 38147 + result_frame = pd.DataFrame(data=range(5, 10), index=range(5)) + result_frame.index.name = False + result_frame.reset_index() + expected_frame = pd.DataFrame(range(5, 10), pd.RangeIndex(range(5), name=False)) + tm.assert_frame_equal(result_frame, expected_frame) + + +@pytest.mark.parametrize("columns", [None, pd.Index([])]) +def test_reset_index_with_empty_frame(columns): + # Currently empty DataFrame has RangeIndex or object dtype Index, but when + # resetting the index we still want to end up with the default string dtype + # https://github.com/pandas-dev/pandas/issues/60338 + + index = pd.Index([], name="foo") + df = pd.DataFrame(index=index, columns=columns) + result = df.reset_index() + expected = pd.DataFrame(columns=["foo"]) + tm.assert_frame_equal(result, expected) + + index = pd.Index([1, 2, 3], name="foo") + df = pd.DataFrame(index=index, columns=columns) + result = df.reset_index() + expected = pd.DataFrame({"foo": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) + + index = pd.MultiIndex.from_tuples([], names=["foo", "bar"]) + df = pd.DataFrame(index=index, columns=columns) + result = df.reset_index() + expected = pd.DataFrame(columns=["foo", "bar"]) + tm.assert_frame_equal(result, expected) + + index = pd.MultiIndex.from_tuples([(1, 2), (2, 3)], names=["foo", "bar"]) + df = pd.DataFrame(index=index, columns=columns) + result = df.reset_index() + expected = pd.DataFrame({"foo": [1, 2], "bar": [2, 3]}) + tm.assert_frame_equal(result, expected) + + +def test_reset_index_inplace_depr(): + msg = "The inplace keyword in DataFrame.reset_index is deprecated" + + df = pd.DataFrame({"a": [1, 2, 3]}, index=pd.Index([0, 1, 2], name="idx")) + df_orig = df.copy() + expected = pd.DataFrame({"idx": [0, 1, 2], "a": [1, 2, 3]}) + + # does not use keyword, no warning + with tm.assert_produces_warning(False): + result = df.reset_index() + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to false, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.reset_index(inplace=False) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to true, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.reset_index(inplace=True) + tm.assert_frame_equal(df, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_round.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_round.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa7449d75263863e0e9688d3abc0c9ed24b8674 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_round.py @@ -0,0 +1,232 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameRound: + def test_round(self): + # GH#2665 + + # Test that rounding an empty DataFrame does nothing + df = pd.DataFrame() + tm.assert_frame_equal(df, df.round()) + + # Here's the test frame we'll be working with + df = pd.DataFrame( + {"col1": [1.123, 2.123, 3.123], "col2": [1.234, 2.234, 3.234]} + ) + + # Default round to integer (i.e. decimals=0) + expected_rounded = pd.DataFrame( + {"col1": [1.0, 2.0, 3.0], "col2": [1.0, 2.0, 3.0]} + ) + tm.assert_frame_equal(df.round(), expected_rounded) + + # Round with an integer + decimals = 2 + expected_rounded = pd.DataFrame( + {"col1": [1.12, 2.12, 3.12], "col2": [1.23, 2.23, 3.23]} + ) + tm.assert_frame_equal(df.round(decimals), expected_rounded) + + # This should also work with np.round (since np.round dispatches to + # df.round) + tm.assert_frame_equal(np.round(df, decimals), expected_rounded) + + # Round with a list + round_list = [1, 2] + msg = "decimals must be an integer, a dict-like or a Series" + with pytest.raises(TypeError, match=msg): + df.round(round_list) + + # Round with a dictionary + expected_rounded = pd.DataFrame( + {"col1": [1.1, 2.1, 3.1], "col2": [1.23, 2.23, 3.23]} + ) + round_dict = {"col1": 1, "col2": 2} + tm.assert_frame_equal(df.round(round_dict), expected_rounded) + + # Incomplete dict + expected_partially_rounded = pd.DataFrame( + {"col1": [1.123, 2.123, 3.123], "col2": [1.2, 2.2, 3.2]} + ) + partial_round_dict = {"col2": 1} + tm.assert_frame_equal(df.round(partial_round_dict), expected_partially_rounded) + + # Dict with unknown elements + wrong_round_dict = {"col3": 2, "col2": 1} + tm.assert_frame_equal(df.round(wrong_round_dict), expected_partially_rounded) + + # float input to `decimals` + non_int_round_dict = {"col1": 1, "col2": 0.5} + msg = "Values in decimals must be integers" + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_dict) + + # String input + non_int_round_dict = {"col1": 1, "col2": "foo"} + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_dict) + + non_int_round_Series = pd.Series(non_int_round_dict) + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_Series) + + # List input + non_int_round_dict = {"col1": 1, "col2": [1, 2]} + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_dict) + + non_int_round_Series = pd.Series(non_int_round_dict) + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_Series) + + # Non integer Series inputs + non_int_round_Series = pd.Series(non_int_round_dict) + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_Series) + + non_int_round_Series = pd.Series(non_int_round_dict) + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_Series) + + # Negative numbers + negative_round_dict = {"col1": -1, "col2": -2} + big_df = df * 100 + expected_neg_rounded = pd.DataFrame( + {"col1": [110.0, 210, 310], "col2": [100.0, 200, 300]} + ) + tm.assert_frame_equal(big_df.round(negative_round_dict), expected_neg_rounded) + + # nan in Series round + nan_round_Series = pd.Series({"col1": np.nan, "col2": 1}) + + with pytest.raises(TypeError, match=msg): + df.round(nan_round_Series) + + # Make sure this doesn't break existing Series.round + tm.assert_series_equal(df["col1"].round(1), expected_rounded["col1"]) + + # named columns + # GH#11986 + decimals = 2 + expected_rounded = pd.DataFrame( + {"col1": [1.12, 2.12, 3.12], "col2": [1.23, 2.23, 3.23]} + ) + df.columns.name = "cols" + expected_rounded.columns.name = "cols" + tm.assert_frame_equal(df.round(decimals), expected_rounded) + + # interaction of named columns & series + tm.assert_series_equal(df["col1"].round(decimals), expected_rounded["col1"]) + tm.assert_series_equal(df.round(decimals)["col1"], expected_rounded["col1"]) + + def test_round_numpy(self): + # GH#12600 + df = pd.DataFrame([[1.53, 1.36], [0.06, 7.01]]) + out = np.round(df, decimals=0) + expected = pd.DataFrame([[2.0, 1.0], [0.0, 7.0]]) + tm.assert_frame_equal(out, expected) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.round(df, decimals=0, out=df) + + def test_round_numpy_with_nan(self): + # See GH#14197 + df = pd.Series([1.53, np.nan, 0.06]).to_frame() + with tm.assert_produces_warning(None): + result = df.round() + expected = pd.Series([2.0, np.nan, 0.0]).to_frame() + tm.assert_frame_equal(result, expected) + + def test_round_mixed_type(self): + # GH#11885 + df = pd.DataFrame( + { + "col1": [1.1, 2.2, 3.3, 4.4], + "col2": ["1", "a", "c", "f"], + "col3": pd.date_range("20111111", periods=4), + } + ) + round_0 = pd.DataFrame( + { + "col1": [1.0, 2.0, 3.0, 4.0], + "col2": ["1", "a", "c", "f"], + "col3": pd.date_range("20111111", periods=4), + } + ) + msg = "obj.round has no effect with datetime, timedelta, or period dtypes" + with tm.assert_produces_warning(UserWarning, match=msg): + tm.assert_frame_equal(df.round(), round_0) + with tm.assert_produces_warning(UserWarning, match=msg): + tm.assert_frame_equal(df.round(1), df) + tm.assert_frame_equal(df.round({"col1": 1}), df) + tm.assert_frame_equal(df.round({"col1": 0}), round_0) + tm.assert_frame_equal(df.round({"col1": 0, "col2": 1}), round_0) + with tm.assert_produces_warning(UserWarning, match=msg): + tm.assert_frame_equal(df.round({"col3": 1}), df) + + def test_round_with_duplicate_columns(self): + # GH#11611 + + df = pd.DataFrame( + np.random.default_rng(2).random([3, 3]), + columns=["A", "B", "C"], + index=["first", "second", "third"], + ) + + dfs = pd.concat((df, df), axis=1) + rounded = dfs.round() + tm.assert_index_equal(rounded.index, dfs.index) + + decimals = pd.Series([1, 0, 2], index=["A", "B", "A"]) + msg = "Index of decimals must be unique" + with pytest.raises(ValueError, match=msg): + df.round(decimals) + + def test_round_builtin(self): + # GH#11763 + # Here's the test frame we'll be working with + df = pd.DataFrame( + {"col1": [1.123, 2.123, 3.123], "col2": [1.234, 2.234, 3.234]} + ) + + # Default round to integer (i.e. decimals=0) + expected_rounded = pd.DataFrame( + {"col1": [1.0, 2.0, 3.0], "col2": [1.0, 2.0, 3.0]} + ) + tm.assert_frame_equal(round(df), expected_rounded) + + def test_round_nonunique_categorical(self): + # See GH#21809 + idx = pd.CategoricalIndex(["low"] * 3 + ["hi"] * 3) + df = pd.DataFrame(np.random.default_rng(2).random((6, 3)), columns=list("abc")) + + expected = df.round(3) + expected.index = idx + + df_categorical = df.copy().set_index(idx) + assert df_categorical.shape == (6, 3) + result = df_categorical.round(3) + assert result.shape == (6, 3) + + tm.assert_frame_equal(result, expected) + + def test_round_interval_category_columns(self): + # GH#30063 + columns = pd.CategoricalIndex(pd.interval_range(0, 2)) + df = pd.DataFrame([[0.66, 1.1], [0.3, 0.25]], columns=columns) + + result = df.round() + expected = pd.DataFrame([[1.0, 1.0], [0.0, 0.0]], columns=columns) + tm.assert_frame_equal(result, expected) + + def test_round_empty_not_input(self): + # GH#51032 + df = pd.DataFrame() + result = df.round() + tm.assert_frame_equal(df, result) + assert df is not result diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_sample.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c3bbb1396be269d76f9ea6898c830f53b0ec49 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_sample.py @@ -0,0 +1,389 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +import pandas.core.common as com + + +class TestSample: + @pytest.fixture + def obj(self, frame_or_series): + if frame_or_series is pd.Series: + arr = np.random.default_rng(2).standard_normal(10) + else: + arr = np.random.default_rng(2).standard_normal((10, 10)) + return frame_or_series(arr, dtype=None) + + @pytest.mark.parametrize("test", list(range(10))) + def test_sample(self, test, obj): + # Fixes issue: 2419 + # Check behavior of random_state argument + # Check for stability when receives seed or random state -- run 10 + # times. + + seed = np.random.default_rng(2).integers(0, 100) + tm.assert_equal( + obj.sample(n=4, random_state=seed), obj.sample(n=4, random_state=seed) + ) + + tm.assert_equal( + obj.sample(frac=0.7, random_state=seed), + obj.sample(frac=0.7, random_state=seed), + ) + + tm.assert_equal( + obj.sample(n=4, random_state=np.random.default_rng(test)), + obj.sample(n=4, random_state=np.random.default_rng(test)), + ) + + tm.assert_equal( + obj.sample(frac=0.7, random_state=np.random.default_rng(test)), + obj.sample(frac=0.7, random_state=np.random.default_rng(test)), + ) + + tm.assert_equal( + obj.sample( + frac=2, + replace=True, + random_state=np.random.default_rng(test), + ), + obj.sample( + frac=2, + replace=True, + random_state=np.random.default_rng(test), + ), + ) + + os1, os2 = [], [] + for _ in range(2): + os1.append(obj.sample(n=4, random_state=test)) + os2.append(obj.sample(frac=0.7, random_state=test)) + tm.assert_equal(*os1) + tm.assert_equal(*os2) + + def test_sample_lengths(self, obj): + # Check lengths are right + assert len(obj.sample(n=4) == 4) + assert len(obj.sample(frac=0.34) == 3) + assert len(obj.sample(frac=0.36) == 4) + + def test_sample_invalid_random_state(self, obj): + # Check for error when random_state argument invalid. + msg = ( + "random_state must be an integer, array-like, a BitGenerator, Generator, " + "a numpy RandomState, or None" + ) + with pytest.raises(ValueError, match=msg): + obj.sample(random_state="a_string") + + def test_sample_wont_accept_n_and_frac(self, obj): + # Giving both frac and N throws error + msg = "Please enter a value for `frac` OR `n`, not both" + with pytest.raises(ValueError, match=msg): + obj.sample(n=3, frac=0.3) + + def test_sample_requires_positive_n_frac(self, obj): + with pytest.raises( + ValueError, + match="A negative number of rows requested. Please provide `n` >= 0", + ): + obj.sample(n=-3) + with pytest.raises( + ValueError, + match="A negative number of rows requested. Please provide `frac` >= 0", + ): + obj.sample(frac=-0.3) + + def test_sample_requires_integer_n(self, obj): + # Make sure float values of `n` give error + with pytest.raises(ValueError, match="Only integers accepted as `n` values"): + obj.sample(n=3.2) + + def test_sample_invalid_weight_lengths(self, obj): + # Weight length must be right + msg = "Weights and axis to be sampled must be of same length" + with pytest.raises(ValueError, match=msg): + obj.sample(n=3, weights=[0, 1]) + + with pytest.raises(ValueError, match=msg): + obj.sample(n=3, weights=[0.5] * 11) + + def test_sample_negative_weights(self, obj): + # Check won't accept negative weights + bad_weights = [-0.1] * 10 + msg = "weights vector may not include negative values" + with pytest.raises(ValueError, match=msg): + obj.sample(n=3, weights=bad_weights) + + def test_sample_inf_weights(self, obj): + # Check inf and -inf throw errors: + + weights_with_inf = [0.1] * 10 + weights_with_inf[0] = np.inf + msg = "weights vector may not include `inf` values" + with pytest.raises(ValueError, match=msg): + obj.sample(n=3, weights=weights_with_inf) + + weights_with_ninf = [0.1] * 10 + weights_with_ninf[0] = -np.inf + with pytest.raises(ValueError, match=msg): + obj.sample(n=3, weights=weights_with_ninf) + + def test_sample_unit_probabilities_raises(self, obj): + # GH#61516 + high_variance_weights = [1] * 10 + high_variance_weights[0] = 100 + msg = ( + "Weighted sampling cannot be achieved with replace=False. Either " + "set replace=True or use smaller weights. See the docstring of " + "sample for details." + ) + with pytest.raises(ValueError, match=msg): + obj.sample(n=2, weights=high_variance_weights, replace=False) + + def test_sample_unit_probabilities_edge_case_do_not_raise(self, obj): + # GH#61516 + # edge case, n*max(weights)/sum(weights) == 1 + edge_variance_weights = [1] * 10 + edge_variance_weights[0] = 9 + # should not raise + obj.sample(n=2, weights=edge_variance_weights, replace=False) + + def test_sample_unit_normal_probabilities_do_not_raise(self, obj): + # GH#61516 + low_variance_weights = [1] * 10 + low_variance_weights[0] = 8 + # should not raise + obj.sample(n=2, weights=low_variance_weights, replace=False) + + def test_sample_zero_weights(self, obj): + # All zeros raises errors + + zero_weights = [0] * 10 + with pytest.raises(ValueError, match="Invalid weights: weights sum to zero"): + obj.sample(n=3, weights=zero_weights) + + def test_sample_missing_weights(self, obj): + # All missing weights + + nan_weights = [np.nan] * 10 + with pytest.raises(ValueError, match="Invalid weights: weights sum to zero"): + obj.sample(n=3, weights=nan_weights) + + def test_sample_none_weights(self, obj): + # Check None are also replaced by zeros. + weights_with_None = [None] * 10 + weights_with_None[5] = 0.5 + tm.assert_equal( + obj.sample(n=1, axis=0, weights=weights_with_None), obj.iloc[5:6] + ) + + @pytest.mark.parametrize( + "func_str,arg", + [ + ("np.array", [2, 3, 1, 0]), + ("np.random.MT19937", 3), + ("np.random.PCG64", 11), + ], + ) + def test_sample_random_state(self, func_str, arg, frame_or_series): + # GH#32503 + obj = pd.DataFrame({"col1": range(10, 20), "col2": range(20, 30)}) + obj = tm.get_obj(obj, frame_or_series) + result = obj.sample(n=3, random_state=eval(func_str)(arg)) + expected = obj.sample(n=3, random_state=com.random_state(eval(func_str)(arg))) + tm.assert_equal(result, expected) + + def test_sample_generator(self, frame_or_series): + # GH#38100 + obj = frame_or_series(np.arange(100)) + rng = np.random.default_rng(2) + + # Consecutive calls should advance the seed + result1 = obj.sample(n=50, random_state=rng) + result2 = obj.sample(n=50, random_state=rng) + assert not (result1.index.values == result2.index.values).all() + + # Matching generator initialization must give same result + # Consecutive calls should advance the seed + result1 = obj.sample(n=50, random_state=np.random.default_rng(11)) + result2 = obj.sample(n=50, random_state=np.random.default_rng(11)) + tm.assert_equal(result1, result2) + + def test_sample_upsampling_without_replacement(self, frame_or_series): + # GH#27451 + + obj = pd.DataFrame({"A": list("abc")}) + obj = tm.get_obj(obj, frame_or_series) + + msg = ( + "Replace has to be set to `True` when upsampling the population `frac` > 1." + ) + with pytest.raises(ValueError, match=msg): + obj.sample(frac=2, replace=False) + + +class TestSampleDataFrame: + # Tests which are relevant only for DataFrame, so these are + # as fully parametrized as they can get. + + def test_sample(self): + # GH#2419 + # additional specific object based tests + + # A few dataframe test with degenerate weights. + easy_weight_list = [0] * 10 + easy_weight_list[5] = 1 + + df = pd.DataFrame( + { + "col1": range(10, 20), + "col2": range(20, 30), + "colString": ["a"] * 10, + "easyweights": easy_weight_list, + } + ) + sample1 = df.sample(n=1, weights="easyweights") + tm.assert_frame_equal(sample1, df.iloc[5:6]) + + # Ensure proper error if string given as weight for Series or + # DataFrame with axis = 1. + ser = pd.Series(range(10)) + msg = "Strings cannot be passed as weights when sampling from a Series." + with pytest.raises(ValueError, match=msg): + ser.sample(n=3, weights="weight_column") + + msg = ( + "Strings can only be passed to weights when sampling from rows on a " + "DataFrame" + ) + with pytest.raises(ValueError, match=msg): + df.sample(n=1, weights="weight_column", axis=1) + + # Check weighting key error + with pytest.raises( + KeyError, match="'String passed to weights not a valid column'" + ): + df.sample(n=3, weights="not_a_real_column_name") + + # Check that re-normalizes weights that don't sum to one. + weights_less_than_1 = [0] * 10 + weights_less_than_1[0] = 0.5 + tm.assert_frame_equal(df.sample(n=1, weights=weights_less_than_1), df.iloc[:1]) + + ### + # Test axis argument + ### + + # Test axis argument + df = pd.DataFrame({"col1": range(10), "col2": ["a"] * 10}) + second_column_weight = [0, 1] + tm.assert_frame_equal( + df.sample(n=1, axis=1, weights=second_column_weight), df[["col2"]] + ) + + # Different axis arg types + tm.assert_frame_equal( + df.sample(n=1, axis="columns", weights=second_column_weight), df[["col2"]] + ) + + weight = [0] * 10 + weight[5] = 0.5 + tm.assert_frame_equal(df.sample(n=1, axis="rows", weights=weight), df.iloc[5:6]) + tm.assert_frame_equal( + df.sample(n=1, axis="index", weights=weight), df.iloc[5:6] + ) + + # Check out of range axis values + msg = "No axis named 2 for object type DataFrame" + with pytest.raises(ValueError, match=msg): + df.sample(n=1, axis=2) + + msg = "No axis named not_a_name for object type DataFrame" + with pytest.raises(ValueError, match=msg): + df.sample(n=1, axis="not_a_name") + + ser = pd.Series(range(10)) + with pytest.raises(ValueError, match="No axis named 1 for object type Series"): + ser.sample(n=1, axis=1) + + # Test weight length compared to correct axis + msg = "Weights and axis to be sampled must be of same length" + with pytest.raises(ValueError, match=msg): + df.sample(n=1, axis=1, weights=[0.5] * 10) + + def test_sample_axis1(self): + # Check weights with axis = 1 + easy_weight_list = [0] * 3 + easy_weight_list[2] = 1 + + df = pd.DataFrame( + {"col1": range(10, 20), "col2": range(20, 30), "colString": ["a"] * 10} + ) + sample1 = df.sample(n=1, axis=1, weights=easy_weight_list) + tm.assert_frame_equal(sample1, df[["colString"]]) + + # Test default axes + tm.assert_frame_equal( + df.sample(n=3, random_state=42), df.sample(n=3, axis=0, random_state=42) + ) + + def test_sample_aligns_weights_with_frame(self): + # Test that function aligns weights with frame + df = pd.DataFrame({"col1": [5, 6, 7], "col2": ["a", "b", "c"]}, index=[9, 5, 3]) + ser = pd.Series([1, 0, 0], index=[3, 5, 9]) + tm.assert_frame_equal(df.loc[[3]], df.sample(1, weights=ser)) + + # Weights have index values to be dropped because not in + # sampled DataFrame + ser2 = pd.Series([0.001, 0, 10000], index=[3, 5, 10]) + tm.assert_frame_equal(df.loc[[3]], df.sample(1, weights=ser2)) + + # Weights have empty values to be filed with zeros + ser3 = pd.Series([0.01, 0], index=[3, 5]) + tm.assert_frame_equal(df.loc[[3]], df.sample(1, weights=ser3)) + + # No overlap in weight and sampled DataFrame indices + ser4 = pd.Series([1, 0], index=[1, 2]) + + with pytest.raises(ValueError, match="Invalid weights: weights sum to zero"): + df.sample(1, weights=ser4) + + def test_sample_is_copy(self): + # GH#27357, GH#30784: ensure the result of sample is an actual copy and + # doesn't track the parent dataframe + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 3)), columns=["a", "b", "c"] + ) + df2 = df.sample(3) + + with tm.assert_produces_warning(None): + df2["d"] = 1 + + def test_sample_does_not_modify_weights(self): + # GH-42843 + result = np.array([np.nan, 1, np.nan]) + expected = result.copy() + ser = pd.Series([1, 2, 3]) + + # Test numpy array weights won't be modified in place + ser.sample(weights=result) + tm.assert_numpy_array_equal(result, expected) + + # Test DataFrame column won't be modified in place + df = pd.DataFrame({"values": [1, 1, 1], "weights": [1, np.nan, np.nan]}) + expected = df["weights"].copy() + + df.sample(frac=1.0, replace=True, weights="weights") + result = df["weights"] + tm.assert_series_equal(result, expected) + + def test_sample_ignore_index(self): + # GH 38581 + df = pd.DataFrame( + {"col1": range(10, 20), "col2": range(20, 30), "colString": ["a"] * 10} + ) + result = df.sample(3, ignore_index=True) + expected_index = pd.Index(range(3)) + tm.assert_index_equal(result.index, expected_index, exact=True) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_select.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_select.py new file mode 100644 index 0000000000000000000000000000000000000000..21dba1fa2af8cbedfcad958f72874183e2e86879 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_select.py @@ -0,0 +1,534 @@ +import re + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def df(): + return pd.DataFrame( + { + "a": [1, 2, 3], + "b": [4.0, 5.0, 6.0], + "c": ["x", "y", "z"], + } + ) + + +@pytest.fixture +def mi_df(): + return pd.DataFrame( + [[1, 2, 3], [4, 5, 6]], + columns=pd.MultiIndex.from_tuples([("one", "a"), ("one", "b"), ("two", "a")]), + ) + + +def test_select(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a", "c") + expected = df[["a", "c"]] + tm.assert_frame_equal(result, expected) + + +def test_select_single_label_returns_frame(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a") + expected = df[["a"]] + tm.assert_frame_equal(result, expected) + + +def test_select_list(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(["b", "a"]) + expected = df[["b", "a"]] + tm.assert_frame_equal(result, expected) + + +def test_select_index(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(df.columns[:2]) + expected = df[df.columns[:2]] + tm.assert_frame_equal(result, expected) + + +def test_select_ndarray(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(np.array(["b", "a"])) + expected = df[["b", "a"]] + tm.assert_frame_equal(result, expected) + + +def test_select_generator(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(c for c in ["a", "c"]) + expected = df[["a", "c"]] + tm.assert_frame_equal(result, expected) + + +def test_select_set_raises(df): + # https://github.com/pandas-dev/pandas/issues/61522 + msg = "`select` does not support sets" + with pytest.raises(TypeError, match=msg): + df.select({"a", "b"}) + + +def test_select_list_mixed_with_args_raises(df): + # https://github.com/pandas-dev/pandas/issues/61522 + msg = "`select` supports individual columns .* or a single list .*, but not both" + with pytest.raises(TypeError, match=msg): + df.select(["a", "b"], "c") + with pytest.raises(TypeError, match=msg): + df.select("c", ["a", "b"]) + with pytest.raises(TypeError, match=msg): + df.select(df.columns[:2], "c") + + +def test_select_reorder(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("c", "a", "b") + expected = df[["c", "a", "b"]] + tm.assert_frame_equal(result, expected) + + +def test_select_label_twice(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a", "a") + expected = df[["a", "a"]] + tm.assert_frame_equal(result, expected) + + +def test_select_duplicate_columns(): + # https://github.com/pandas-dev/pandas/issues/61522 + df = pd.DataFrame([[1, 2, 3]], columns=["a", "b", "a"]) + result = df.select("a") + expected = df[["a"]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("columns", [["a", "a", "b"], ["a", "b", "a"]]) +def test_select_kwarg_duplicate_label(columns): + # https://github.com/pandas-dev/pandas/issues/61522 + # a keyword argument defines a single output column even when its + # name is duplicated in the DataFrame's columns + df = pd.DataFrame([[1, 2, 3]], columns=columns) + result = df.select("b", a=99) + expected = pd.DataFrame({"b": df["b"], "a": [99]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("columns", [["b", "b", "a"], ["b", "a", "b"]]) +def test_select_expression_duplicate_label(columns): + # https://github.com/pandas-dev/pandas/issues/61522 + # a renamed expression defines a single output column even when its + # name is duplicated in the DataFrame's columns + df = pd.DataFrame([[1, 2, 3]], columns=columns) + result = df.select(pd.col("a").rename("b")) + expected = pd.DataFrame({"b": df["a"]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "columns", + [ + ["b", "b", "a"], + ["b", "a", "b"], + [np.nan, np.nan, "a"], + [np.nan, "a", np.nan], + ], +) +@pytest.mark.parametrize("dtype", [None, object]) +def test_select_expression_duplicate_label_length_matches(columns, dtype): + # GH#69412 + # the number of rows equals the number of duplicates of the name + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=pd.Index(columns, dtype=dtype)) + label = columns[0] + result = df.select(pd.col("a").rename(label), label) + expected = pd.concat([df["a"]] * 3, axis=1) + expected.columns = df.columns[[0, 0, 0]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "value", + [ + pd.col("a"), + pd.Series([6, 3], index=[1, 0]), + np.array([3, 6], dtype=np.int64), + [3, 6], + ], +) +def test_select_kwarg_duplicate_label_length_matches(value): + # GH#69412 + # the number of rows equals the number of duplicates of the name + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["b", "b", "a"]) + result = df.select(b=value) + expected = pd.DataFrame({"b": [3, 6]}) + tm.assert_frame_equal(result, expected) + + +def test_select_missing_raises(df): + # https://github.com/pandas-dev/pandas/issues/61522 + with pytest.raises(KeyError, match=r"\['nope'\] not in index"): + df.select("a", "nope") + + +def test_select_empty(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select() + expected = df[[]] + tm.assert_frame_equal(result, expected) + + +def test_select_empty_multiindex_columns(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + # the empty result keeps the columns' type, levels, and names + result = mi_df.select() + expected = mi_df[[]] + tm.assert_frame_equal(result, expected) + + +def test_select_empty_preserves_columns_name(df): + # https://github.com/pandas-dev/pandas/issues/61522 + df.columns.name = "cols" + result = df.select() + expected = df[[]] + tm.assert_frame_equal(result, expected) + + +def test_select_index_preserved(): + # https://github.com/pandas-dev/pandas/issues/61522 + df = pd.DataFrame({"a": [1, 2]}, index=["x", "y"]) + result = df.select("a") + expected = pd.DataFrame({"a": [1, 2]}, index=["x", "y"]) + tm.assert_frame_equal(result, expected) + + +def test_select_returns_copy(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a", "b") + result.iloc[0, 0] = 100 + expected = pd.DataFrame( + {"a": [1, 2, 3], "b": [4.0, 5.0, 6.0], "c": ["x", "y", "z"]} + ) + tm.assert_frame_equal(df, expected) + + +def test_select_tuple_label(): + # https://github.com/pandas-dev/pandas/issues/61522 + df = pd.DataFrame([[1, 2]], columns=pd.Index([("a", "b"), "c"], dtype=object)) + result = df.select(("a", "b")) + expected = df[[("a", "b")]] + tm.assert_frame_equal(result, expected) + + +def test_select_multiindex_first_level(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = mi_df.select("one") + expected = mi_df[["one"]] + tm.assert_frame_equal(result, expected) + + +def test_select_multiindex_tuples(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = mi_df.select(("one", "b"), ("two", "a")) + expected = mi_df[[("one", "b"), ("two", "a")]] + tm.assert_frame_equal(result, expected) + + +def test_select_multiindex_mixed_depth(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + # each label resolves independently, so first-level keys and full + # tuples can be mixed even though df[list] rejects the combination + result = mi_df.select("one", ("two", "a")) + expected = mi_df[[("one", "a"), ("one", "b"), ("two", "a")]] + tm.assert_frame_equal(result, expected) + + +def test_select_multiindex_mixed_depth_list(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = mi_df.select([("two", "a"), "one"]) + expected = mi_df[[("two", "a"), ("one", "a"), ("one", "b")]] + tm.assert_frame_equal(result, expected) + + +def test_select_multiindex_mixed_depth_expression_position(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + # an interleaved expression does not change how labels resolve + expr = (pd.col(("one", "a")) * 2).rename(("one", "X")) + result = mi_df.select("one", expr, ("two", "a")) + expected = mi_df.select("one", ("two", "a"), expr)[ + [("one", "a"), ("one", "b"), ("one", "X"), ("two", "a")] + ] + tm.assert_frame_equal(result, expected) + + +def test_select_expression_multiindex(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = mi_df.select(pd.col(("one", "a")) * 2) + expected = pd.DataFrame( + [[2], [8]], columns=pd.MultiIndex.from_tuples([("one", "a")]) + ) + tm.assert_frame_equal(result, expected) + + +def test_select_multiindex_label_and_expression(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = mi_df.select(("one", "b"), pd.col(("two", "a")) + 1) + expected = pd.DataFrame( + [[2, 4], [5, 7]], + columns=pd.MultiIndex.from_tuples([("one", "b"), ("two", "a")]), + ) + tm.assert_frame_equal(result, expected) + + +def test_select_expression_multiindex_rename(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + expr = (pd.col(("one", "a")) + pd.col(("one", "b"))).rename(("one", "total")) + result = mi_df.select(expr) + expected = pd.DataFrame( + [[3], [9]], columns=pd.MultiIndex.from_tuples([("one", "total")]) + ) + tm.assert_frame_equal(result, expected) + + +def test_select_expression_multiindex_str_name_raises(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + msg = "use .rename(...) with a tuple of length 2" + with pytest.raises(TypeError, match=re.escape(msg)): + mi_df.select((pd.col(("one", "a")) * 2).rename("x")) + + +def test_select_expression_multiindex_wrong_length_name_raises(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + msg = "use .rename(...) with a tuple of length 2" + with pytest.raises(TypeError, match=re.escape(msg)): + mi_df.select((pd.col(("one", "a")) * 2).rename(("x",))) + + +def test_select_expression_multiindex_frame_result(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + # to_frame on a tuple-named Series produces MultiIndex columns + result = mi_df.select(pd.col(("one", "a")).to_frame()) + expected = mi_df[[("one", "a")]] + tm.assert_frame_equal(result, expected) + + +def test_select_expression_multiindex_frame_nlevels_mismatch_raises(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + msg = "columns have 1 levels, but the DataFrame's columns have 2 levels" + with pytest.raises(TypeError, match=re.escape(msg)): + mi_df.select(pd.col(("one", "a")).astype(str).str.get_dummies()) + + +def test_select_kwargs_multiindex_raises(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + msg = "cannot create column 'extra' from a keyword argument" + with pytest.raises(TypeError, match=re.escape(msg)): + mi_df.select(("one", "a"), extra=1) + + +def test_select_kwargs_preserves_columns_name(df): + # https://github.com/pandas-dev/pandas/issues/61522 + df.columns.name = "cols" + result = df.select("a", double=pd.col("a") * 2) + expected = pd.DataFrame({"a": [1, 2, 3], "double": [2, 4, 6]}) + expected.columns.name = "cols" + tm.assert_frame_equal(result, expected) + + +def test_select_expression(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(pd.col("a")) + expected = df[["a"]] + tm.assert_frame_equal(result, expected) + + +def test_select_expression_computed(df): + # https://github.com/pandas-dev/pandas/issues/61522 + # binary ops with scalars keep the column name + result = df.select(pd.col("a") * 2) + expected = pd.DataFrame({"a": [2, 4, 6]}) + tm.assert_frame_equal(result, expected) + + +def test_select_expression_method_call(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(pd.col("c").str.upper()) + expected = pd.DataFrame({"c": ["X", "Y", "Z"]}) + tm.assert_frame_equal(result, expected) + + +def test_select_expression_rename(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select((pd.col("a") + pd.col("b")).rename("total")) + expected = pd.DataFrame({"total": [5.0, 7.0, 9.0]}) + tm.assert_frame_equal(result, expected) + + +def test_select_expression_unnamed_raises(df): + # https://github.com/pandas-dev/pandas/issues/61522 + msg = re.escape("expression col('a') + col('b') evaluated to an unnamed Series") + with pytest.raises(TypeError, match=msg): + df.select(pd.col("a") + pd.col("b")) + + +def test_select_expression_scalar_raises(df, using_python_scalars): + # https://github.com/pandas-dev/pandas/issues/61522 + if using_python_scalars: + result_type = "float" + else: + result_type = "float64" + msg = re.escape( + f"expression col('b').sum() evaluated to an object of type {result_type}" + ) + with pytest.raises(TypeError, match=msg): + df.select(pd.col("b").sum()) + + +def test_select_expression_frame_result(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a", pd.col("c").str.get_dummies()) + expected = df[["a"]].join(df["c"].str.get_dummies()) + tm.assert_frame_equal(result, expected) + + +def test_select_interleaved(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("b", pd.col("a") * 2, "c") + expected = pd.DataFrame( + {"b": [4.0, 5.0, 6.0], "a": [2, 4, 6], "c": ["x", "y", "z"]} + ) + tm.assert_frame_equal(result, expected) + + +def test_select_kwargs_expression(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a", total=pd.col("a") + pd.col("b")) + expected = pd.DataFrame({"a": [1, 2, 3], "total": [5.0, 7.0, 9.0]}) + tm.assert_frame_equal(result, expected) + + +def test_select_kwargs_callable(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a", double=lambda x: x["a"] * 2) + expected = pd.DataFrame({"a": [1, 2, 3], "double": [2, 4, 6]}) + tm.assert_frame_equal(result, expected) + + +def test_select_kwargs_series_aligns(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a", extra=pd.Series([10.0], index=[1])) + expected = pd.DataFrame({"a": [1, 2, 3], "extra": [np.nan, 10.0, np.nan]}) + tm.assert_frame_equal(result, expected) + + +def test_select_kwargs_scalar_broadcasts(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a", flag=True) + expected = pd.DataFrame({"a": [1, 2, 3], "flag": [True, True, True]}) + tm.assert_frame_equal(result, expected) + + +def test_select_kwargs_dict_aligns(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select("a", extra={0: 1.0, 2: 3.0}) + expected = pd.DataFrame({"a": [1, 2, 3], "extra": [1.0, np.nan, 3.0]}) + tm.assert_frame_equal(result, expected) + + +def test_select_kwargs_wrong_length_raises(df): + # https://github.com/pandas-dev/pandas/issues/61522 + msg = re.escape("Length of values (2) does not match length of index (3)") + with pytest.raises(ValueError, match=msg): + df.select("a", extra=[1, 2]) + + +def test_select_kwargs_sequential(df): + # https://github.com/pandas-dev/pandas/issues/61522 + # like assign, later kwargs can refer to columns computed earlier + result = df.select(double=pd.col("a") * 2, quadruple=pd.col("double") * 2) + expected = pd.DataFrame({"double": [2, 4, 6], "quadruple": [4, 8, 12]}) + tm.assert_frame_equal(result, expected) + + +def test_select_kwargs_sequential_callable(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(double=lambda x: x["a"] * 2, quadruple=lambda x: x["double"] * 2) + expected = pd.DataFrame({"double": [2, 4, 6], "quadruple": [4, 8, 12]}) + tm.assert_frame_equal(result, expected) + + +def test_select_kwargs_see_positional_expression(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(pd.col("a") * 2, b=pd.col("a") + 1) + expected = pd.DataFrame({"a": [2, 4, 6], "b": [3, 5, 7]}) + tm.assert_frame_equal(result, expected) + + +def test_select_label_after_computed_column(df): + # https://github.com/pandas-dev/pandas/issues/61522 + # a label refers to the column as it is at that point in the call + result = df.select("a", pd.col("a") * 2, "a") + expected = pd.DataFrame([[1, 2, 2], [2, 4, 4], [3, 6, 6]], columns=["a", "a", "a"]) + tm.assert_frame_equal(result, expected) + + +def test_select_replaced_column_seen_by_later_kwarg(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(a=pd.col("a") * 2, c=pd.col("a") + 1) + expected = pd.DataFrame({"a": [2, 4, 6], "c": [3, 5, 7]}) + tm.assert_frame_equal(result, expected) + + +def test_select_swap_uses_replaced_column(df): + # https://github.com/pandas-dev/pandas/issues/61522 + # like assign, the second kwarg sees the already replaced column + result = df.select(a=pd.col("b"), b=pd.col("a")) + expected = pd.DataFrame({"a": [4.0, 5.0, 6.0], "b": [4.0, 5.0, 6.0]}) + tm.assert_frame_equal(result, expected) + + +def test_select_frame_result_seen_by_later_kwarg(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(pd.col("c").str.get_dummies(), total=pd.col("x") + pd.col("y")) + expected = df["c"].str.get_dummies().assign(total=lambda d: d["x"] + d["y"]) + tm.assert_frame_equal(result, expected) + + +def test_select_expression_multiindex_sequential(mi_df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = mi_df.select( + (pd.col(("one", "a")) * 2).rename(("three", "a")), + (pd.col(("three", "a")) + 1).rename(("three", "b")), + ) + expected = pd.DataFrame( + [[2, 3], [8, 9]], + columns=pd.MultiIndex.from_tuples([("three", "a"), ("three", "b")]), + ) + tm.assert_frame_equal(result, expected) + + +def test_select_does_not_modify_original(df): + # https://github.com/pandas-dev/pandas/issues/61522 + expected = df.copy() + df.select(a=pd.col("a") * 2, d=pd.col("a")) + tm.assert_frame_equal(df, expected) + + +def test_select_duplicate_output_names(df): + # https://github.com/pandas-dev/pandas/issues/61522 + # a computed column does not replace an already selected column + # in the result; both are returned + result = df.select("a", a=pd.col("b")) + expected = df[["a", "b"]].set_axis(["a", "a"], axis=1) + tm.assert_frame_equal(result, expected) + + +def test_select_kwargs_only(df): + # https://github.com/pandas-dev/pandas/issues/61522 + result = df.select(total=pd.col("a") + pd.col("b")) + expected = pd.DataFrame({"total": [5.0, 7.0, 9.0]}) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_select_dtypes.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_select_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..08639769a97b7e986e570527778c3457fd524b3d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_select_dtypes.py @@ -0,0 +1,1481 @@ +import datetime +import decimal +import re + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +from pandas.core.dtypes.dtypes import ExtensionDtype + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import ExtensionArray + + +class DummyDtype(ExtensionDtype): + type = int + + def __init__(self, numeric) -> None: + self._numeric = numeric + + @property + def name(self): + return "Dummy" + + @property + def _is_numeric(self): + return self._numeric + + +class DummyArray(ExtensionArray): + def __init__(self, data, dtype) -> None: + self.data = data + self._dtype = dtype + + def __array__(self, dtype=None, copy=None): + return np.asarray(self.data, dtype=dtype) + + @property + def dtype(self): + return self._dtype + + def __len__(self) -> int: + return len(self.data) + + def __getitem__(self, item): + pass + + def copy(self): + return self + + def view(self): + return self + + +class TestSelectDtypes: + def test_select_dtypes_include_using_list_like(self, using_infer_string): + 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.Categorical(list("abc")), + "g": pd.date_range("20130101", periods=3), + "h": pd.date_range("20130101", periods=3, tz="US/Eastern"), + "i": pd.date_range("20130101", periods=3, tz="CET"), + "j": pd.period_range("2013-01", periods=3, freq="M"), + "k": pd.timedelta_range("1 day", periods=3), + } + ) + + ri = df.select_dtypes(include=[np.number]) + ei = df[["b", "c", "d", "k"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include=[np.number], exclude=["timedelta"]) + ei = df[["b", "c", "d"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include=[np.number, "category"], exclude=["timedelta"]) + ei = df[["b", "c", "d", "f"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include=["datetime"]) + ei = df[["g"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include=["datetime64"]) + ei = df[["g"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include=[pd.DatetimeTZDtype]) + ei = df[["h", "i"]] + tm.assert_frame_equal(ri, ei) + + with pytest.raises(TypeError, match="does not support the 'period' string"): + df.select_dtypes(include=["period"]) + + if using_infer_string: + ri = df.select_dtypes(include=["str"]) + ei = df[["a"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include=[str]) + tm.assert_frame_equal(ri, ei) + + msg = "For backward compatibility, 'str' dtypes are included" + warn = None + if using_infer_string: + warn = Pandas4Warning + with tm.assert_produces_warning(warn, match=msg): + ri = df.select_dtypes(include=["object"]) + ei = df[["a"]] + tm.assert_frame_equal(ri, ei) + + def test_select_dtypes_exclude_using_list_like(self): + 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], + } + ) + re = df.select_dtypes(exclude=[np.number]) + ee = df[["a", "e"]] + tm.assert_frame_equal(re, ee) + + def test_select_dtypes_exclude_include_using_list_like(self): + df = pd.DataFrame( + { + "a": list("abc"), + "b": list(range(1, 4)), + "c": np.arange(3, 6, dtype="u1"), + "d": np.arange(4.0, 7.0, dtype="float64"), + "e": [True, False, True], + "f": pd.date_range("2011-01-01", periods=3).values, + } + ) + exclude = (np.datetime64,) + include = np.bool_, "integer" + r = df.select_dtypes(include=include, exclude=exclude) + e = df[["b", "c", "e"]] + tm.assert_frame_equal(r, e) + + exclude = ("datetime",) + include = "bool", "int64", "int32" + r = df.select_dtypes(include=include, exclude=exclude) + e = df[["b", "e"]] + tm.assert_frame_equal(r, e) + + @pytest.mark.parametrize( + "include", [(np.bool_, "int"), (np.bool_, "integer"), ("bool", int)] + ) + def test_select_dtypes_exclude_include_int(self, include): + # Fix select_dtypes(include='int') for Windows, FYI #36596 + df = pd.DataFrame( + { + "a": list("abc"), + "b": list(range(1, 4)), + "c": np.arange(3, 6, dtype="int32"), + "d": np.arange(4.0, 7.0, dtype="float64"), + "e": [True, False, True], + "f": pd.date_range("2011-01-01", periods=3).values, + } + ) + exclude = (np.datetime64,) + result = df.select_dtypes(include=include, exclude=exclude) + expected = df[["b", "c", "e"]] + tm.assert_frame_equal(result, expected) + + def test_select_dtypes_include_using_scalars(self, using_infer_string): + 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.Categorical(list("abc")), + "g": pd.date_range("20130101", periods=3), + "h": pd.date_range("20130101", periods=3, tz="US/Eastern"), + "i": pd.date_range("20130101", periods=3, tz="CET"), + "j": pd.period_range("2013-01", periods=3, freq="M"), + "k": pd.timedelta_range("1 day", periods=3), + } + ) + + ri = df.select_dtypes(include=np.number) + ei = df[["b", "c", "d", "k"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include="datetime") + ei = df[["g"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include="datetime64") + ei = df[["g"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include="category") + ei = df[["f"]] + tm.assert_frame_equal(ri, ei) + + with pytest.raises(TypeError, match="does not support the 'period' string"): + df.select_dtypes(include="period") + + if using_infer_string: + ri = df.select_dtypes(include="str") + ei = df[["a"]] + tm.assert_frame_equal(ri, ei) + + def test_select_dtypes_exclude_using_scalars(self): + 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.Categorical(list("abc")), + "g": pd.date_range("20130101", periods=3), + "h": pd.date_range("20130101", periods=3, tz="US/Eastern"), + "i": pd.date_range("20130101", periods=3, tz="CET"), + "j": pd.period_range("2013-01", periods=3, freq="M"), + "k": pd.timedelta_range("1 day", periods=3), + } + ) + + ri = df.select_dtypes(exclude=np.number) + ei = df[["a", "e", "f", "g", "h", "i", "j"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(exclude="category") + ei = df[["a", "b", "c", "d", "e", "g", "h", "i", "j", "k"]] + tm.assert_frame_equal(ri, ei) + + with pytest.raises(TypeError, match="does not support the 'period' string"): + df.select_dtypes(exclude="period") + + def test_select_dtypes_include_exclude_using_scalars(self): + 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.Categorical(list("abc")), + "g": pd.date_range("20130101", periods=3), + "h": pd.date_range("20130101", periods=3, tz="US/Eastern"), + "i": pd.date_range("20130101", periods=3, tz="CET"), + "j": pd.period_range("2013-01", periods=3, freq="M"), + "k": pd.timedelta_range("1 day", periods=3), + } + ) + + ri = df.select_dtypes(include=np.number, exclude="floating") + ei = df[["b", "c", "k"]] + tm.assert_frame_equal(ri, ei) + + def test_select_dtypes_include_exclude_mixed_scalars_lists(self): + 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.Categorical(list("abc")), + "g": pd.date_range("20130101", periods=3), + "h": pd.date_range("20130101", periods=3, tz="US/Eastern"), + "i": pd.date_range("20130101", periods=3, tz="CET"), + "j": pd.period_range("2013-01", periods=3, freq="M"), + "k": pd.timedelta_range("1 day", periods=3), + } + ) + + ri = df.select_dtypes(include=np.number, exclude=["floating", "timedelta"]) + ei = df[["b", "c"]] + tm.assert_frame_equal(ri, ei) + + ri = df.select_dtypes(include=[np.number, "category"], exclude="floating") + ei = df[["b", "c", "f", "k"]] + tm.assert_frame_equal(ri, ei) + + def test_select_dtypes_duplicate_columns(self): + # GH20839 + df = pd.DataFrame( + { + "a": ["a", "b", "c"], + "b": [1, 2, 3], + "c": np.arange(3, 6).astype("u1"), + "d": np.arange(4.0, 7.0, dtype="float64"), + "e": [True, False, True], + "f": pd.date_range("2011-01-01", periods=3).values, + } + ) + df.columns = ["a", "a", "b", "b", "b", "c"] + + expected = pd.DataFrame( + {"a": list(range(1, 4)), "b": np.arange(3, 6).astype("u1")} + ) + + result = df.select_dtypes(include=[np.number], exclude=["floating"]) + tm.assert_frame_equal(result, expected) + + def test_select_dtypes_not_an_attr_but_still_valid_dtype(self, using_infer_string): + 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("2011-01-01", periods=3).values, + } + ) + df["g"] = df.f.diff() + assert not hasattr(np, "u8") + + msg = "For backward compatibility, 'str' dtypes are included" + warn = None + if using_infer_string: + warn = Pandas4Warning + with tm.assert_produces_warning(warn, match=msg): + r = df.select_dtypes(include=["i8", "O"], exclude=["timedelta"]) + e = df[["a", "b"]] + tm.assert_frame_equal(r, e) + + with tm.assert_produces_warning(warn, match=msg): + r = df.select_dtypes(include=["i8", "O", "timedelta64[us]"]) + e = df[["a", "b", "g"]] + tm.assert_frame_equal(r, e) + + def test_select_dtypes_empty(self): + df = pd.DataFrame({"a": list("abc"), "b": list(range(1, 4))}) + msg = "at least one of include or exclude must be nonempty" + with pytest.raises(ValueError, match=msg): + df.select_dtypes() + + def test_select_dtypes_bad_datetime64(self): + 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("2011-01-01", periods=3).values, + } + ) + # units that pandas cannot represent are rejected; only 's', 'ms', + # 'us', 'ns' (or a unitless spec) are accepted + with pytest.raises(ValueError, match="is not a supported"): + df.select_dtypes(include=["datetime64[D]"]) + + with pytest.raises(ValueError, match="is not a supported"): + df.select_dtypes(exclude=["datetime64[as]"]) + + @pytest.mark.parametrize("kind", ["datetime64", "timedelta64"]) + @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) + def test_select_dtypes_dt64_td64_specific_unit(self, kind, unit): + # GH#40234 a datetime64/timedelta64 spec with a specific (supported) + # unit selects only columns with exactly that resolution + units = ["s", "ms", "us", "ns"] + if kind == "datetime64": + base = pd.date_range("2020-01-01", periods=3) + else: + base = pd.timedelta_range("1 day", periods=3) + df = pd.DataFrame({other: base.as_unit(other) for other in units}) + + expected = df[[unit]] + # spelled as a string ... + result = df.select_dtypes(include=[f"{kind}[{unit}]"]) + tm.assert_frame_equal(result, expected) + # ... and as a numpy dtype instance + result = df.select_dtypes(include=[np.dtype(f"{kind}[{unit}]")]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "kind, cls", [("datetime64", np.datetime64), ("timedelta64", np.timedelta64)] + ) + def test_select_dtypes_dt64_td64_unitless_matches_all(self, kind, cls): + # GH#40234 a unitless datetime64/timedelta64 spec still matches every + # resolution + units = ["s", "ms", "us", "ns"] + if kind == "datetime64": + base = pd.date_range("2020-01-01", periods=3) + else: + base = pd.timedelta_range("1 day", periods=3) + df = pd.DataFrame({unit: base.as_unit(unit) for unit in units}) + + for spec in (kind, cls, np.dtype(kind)): + result = df.select_dtypes(include=[spec]) + tm.assert_frame_equal(result, df) + + def test_select_dtypes_dt64_unit_exclude_and_overlap(self): + # GH#40234 excluding one resolution leaves the others, and pairing a + # unit-specific include/exclude does not trip the overlap check + base = pd.date_range("2020-01-01", periods=3) + df = pd.DataFrame({unit: base.as_unit(unit) for unit in ["s", "us", "ns"]}) + expected = df[["s", "ns"]] + + result = df.select_dtypes(exclude=["datetime64[us]"]) + tm.assert_frame_equal(result, expected) + + result = df.select_dtypes(include="datetime64", exclude="datetime64[us]") + tm.assert_frame_equal(result, expected) + + def test_select_dtypes_datetime_with_tz(self): + df2 = pd.DataFrame( + { + "A": pd.Timestamp("20130102", tz="US/Eastern"), + "B": pd.Timestamp("20130603", tz="CET"), + }, + index=range(5), + ) + df3 = pd.concat([df2.A.to_frame(), df2.B.to_frame()], axis=1) + result = df3.select_dtypes(include=["datetime64[ns]"]) + expected = df3.reindex(columns=[]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype", [str, "str", np.bytes_, "S1", np.str_, "U1"]) + @pytest.mark.parametrize("arg", ["include", "exclude"]) + def test_select_dtypes_str_raises(self, dtype, arg, using_infer_string): + if using_infer_string and (dtype == "str" or dtype is str): + # this is tested below + pytest.skip("Selecting string columns works with future strings") + df = pd.DataFrame( + { + "a": list("abc"), + "g": 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("2011-01-01", periods=3).values, + } + ) + msg = "string dtypes are not allowed" + kwargs = {arg: [dtype]} + + with pytest.raises(TypeError, match=msg): + df.select_dtypes(**kwargs) + + def test_select_dtypes_bad_arg_raises(self): + df = pd.DataFrame( + { + "a": list("abc"), + "g": 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("2011-01-01", periods=3).values, + } + ) + + msg = "data type.*not understood" + with pytest.raises(TypeError, match=msg): + df.select_dtypes(["blargy, blarg, blarg"]) + + def test_select_dtypes_typecodes(self): + # GH 11990 + df = pd.DataFrame(np.random.default_rng(2).random((5, 3))) + FLOAT_TYPES = list(np.typecodes["AllFloat"]) + tm.assert_frame_equal(df.select_dtypes(FLOAT_TYPES), df) + + @pytest.mark.parametrize( + "arr,expected", + ( + (np.array([1, 2], dtype=np.int32), True), + (pd.array([1, 2], dtype="Int32"), True), + (DummyArray([1, 2], dtype=DummyDtype(numeric=True)), True), + (DummyArray([1, 2], dtype=DummyDtype(numeric=False)), False), + ), + ) + def test_select_dtypes_numeric(self, arr, expected): + # GH 35340 + + df = pd.DataFrame(arr) + is_selected = df.select_dtypes(np.number).shape == df.shape + assert is_selected == expected + + def test_select_dtypes_numeric_nullable_string(self, nullable_string_dtype): + arr = pd.array(["a", "b"], dtype=nullable_string_dtype) + df = pd.DataFrame(arr) + is_selected = df.select_dtypes(np.number).shape == df.shape + assert not is_selected + + @pytest.mark.parametrize( + "expected, float_dtypes", + [ + [ + pd.DataFrame( + {"A": range(3), "B": range(5, 8), "C": range(10, 7, -1)} + ).astype(dtype={"A": float, "B": np.float64, "C": np.float32}), + float, + ], + [ + pd.DataFrame( + {"A": range(3), "B": range(5, 8), "C": range(10, 7, -1)} + ).astype(dtype={"A": float, "B": np.float64, "C": np.float32}), + "float", + ], + [pd.DataFrame({"C": range(10, 7, -1)}, dtype=np.float32), np.float32], + [ + pd.DataFrame({"A": range(3), "B": range(5, 8)}).astype( + dtype={"A": float, "B": np.float64} + ), + np.float64, + ], + ], + ) + def test_select_dtypes_float_dtype(self, expected, float_dtypes): + # GH#42452 + dtype_dict = {"A": float, "B": np.float64, "C": np.float32} + df = pd.DataFrame( + {"A": range(3), "B": range(5, 8), "C": range(10, 7, -1)}, + ) + df = df.astype(dtype_dict) + result = df.select_dtypes(include=float_dtypes) + tm.assert_frame_equal(result, expected) + + def test_np_bool_ea_boolean_include_number(self): + # GH 46870 + df = pd.DataFrame( + { + "a": [1, 2, 3], + "b": pd.Series([True, False, True], dtype="boolean"), + "c": np.array([True, False, True]), + "d": pd.Categorical([True, False, True]), + "e": pd.arrays.SparseArray([True, False, True]), + } + ) + result = df.select_dtypes(include="number") + expected = pd.DataFrame({"a": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) + + def test_select_dtypes_no_view(self): + # https://github.com/pandas-dev/pandas/issues/48090 + # result of this method is not a view on the original dataframe + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + df_orig = df.copy() + result = df.select_dtypes(include=["number"]) + result.iloc[0, 0] = 0 + tm.assert_frame_equal(df, df_orig) + + def test_select_dtype_object_and_str(self, using_infer_string): + # https://github.com/pandas-dev/pandas/issues/61916 + df = pd.DataFrame( + { + "a": ["a", "b", "c"], + "b": [1, 2, 3], + "c": pd.array(["a", "b", "c"], dtype="string"), + } + ) + + # with "object" -> only select the object or default str dtype column + msg = "For backward compatibility, 'str' dtypes are included" + warn = None + if using_infer_string: + warn = Pandas4Warning + with tm.assert_produces_warning(warn, match=msg): + result = df.select_dtypes(include=["object"]) + expected = df[["a"]] + tm.assert_frame_equal(result, expected) + + # with "string" -> select both the default 'str' and the nullable 'string' + result = df.select_dtypes(include=["string"]) + if using_infer_string: + expected = df[["a", "c"]] + else: + expected = df[["c"]] + tm.assert_frame_equal(result, expected) + + +def test_select_dtypes_numpy_instance_exact(): + # GH#40234: a dtype instance matches only columns with exactly that + # dtype, not everything with matching dtype.type + df = pd.DataFrame( + { + "a": np.array([1, 2], dtype=np.int64), + "b": np.array([1, 2], dtype=np.int32), + "c": pd.array([1, 2], dtype="Int64"), + "d": [1.0, 2.0], + } + ) + result = df.select_dtypes(include=np.dtype("int64")) + tm.assert_frame_equal(result, df[["a"]]) + + result = df.select_dtypes(exclude=np.dtype("int64")) + tm.assert_frame_equal(result, df[["b", "c", "d"]]) + + +def test_select_dtypes_masked_instance_exact(): + # GH#40234 + df = pd.DataFrame( + { + "a": np.array([1, 2], dtype=np.int64), + "b": pd.array([1, 2], dtype="Int64"), + "c": pd.array([1.0, 2.0], dtype="Float64"), + } + ) + result = df.select_dtypes(include=pd.Int64Dtype()) + tm.assert_frame_equal(result, df[["b"]]) + + result = df.select_dtypes(exclude=pd.Int64Dtype()) + tm.assert_frame_equal(result, df[["a", "c"]]) + + +def test_select_dtypes_arrow_instance_exact(): + # GH#40234 + pa = pytest.importorskip("pyarrow") + df = pd.DataFrame( + { + "a": pd.array([1, 2], dtype=pd.ArrowDtype(pa.int64())), + "b": pd.array([1, 2], dtype=pd.ArrowDtype(pa.int32())), + "c": np.array([1, 2], dtype=np.int64), + "d": pd.array([1, 2], dtype="Int64"), + } + ) + result = df.select_dtypes(include=pd.ArrowDtype(pa.int64())) + tm.assert_frame_equal(result, df[["a"]]) + + # nor does a numpy instance match ArrowDtype columns + result = df.select_dtypes(include=np.dtype("int64")) + tm.assert_frame_equal(result, df[["c"]]) + + +def test_select_dtypes_tz_instance_exact(): + # GH#40234 + df = pd.DataFrame( + { + "a": pd.date_range("2016-01-01", periods=2, tz="US/Eastern", unit="ns"), + "b": pd.date_range("2016-01-01", periods=2, tz="UTC", unit="ns"), + "c": pd.date_range("2016-01-01", periods=2, unit="ns"), + } + ) + result = df.select_dtypes(include=pd.DatetimeTZDtype(tz="UTC")) + tm.assert_frame_equal(result, df[["b"]]) + + result = df.select_dtypes(exclude=pd.DatetimeTZDtype(tz="UTC")) + tm.assert_frame_equal(result, df[["a", "c"]]) + + # the unit is part of the dtype + result = df.select_dtypes(include=pd.DatetimeTZDtype("us", tz="UTC")) + tm.assert_frame_equal(result, df[[]]) + + +def test_select_dtypes_datetime64_instance_unit(): + # GH#40234: a specific-unit instance selects only that unit, while the + # unitless np.dtype("datetime64") selects the whole family + df = pd.DataFrame( + { + "a": pd.date_range("2016-01-01", periods=2).as_unit("ns"), + "b": pd.date_range("2016-01-01", periods=2).as_unit("s"), + } + ) + result = df.select_dtypes(include=np.dtype("datetime64[s]")) + tm.assert_frame_equal(result, df[["b"]]) + + result = df.select_dtypes(include=np.dtype("datetime64")) + tm.assert_frame_equal(result, df) + + # a unit that no column can have still raises + with pytest.raises(ValueError, match="is not a supported"): + df.select_dtypes(include=np.dtype("datetime64[D]")) + + +@pytest.mark.parametrize("kind", ["datetime64", "timedelta64"]) +@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) +@pytest.mark.parametrize("byteorder", ["<", ">"]) +def test_select_dtypes_dt64_td64_string_byteorder(kind, unit, byteorder): + # GH#40234 byteorder is not part of what a string spec selects, matching + # how ">i8" selects every int64 column, so a byteswapped string selects + # that resolution rather than silently selecting nothing + if kind == "datetime64": + base = pd.date_range("2020-01-01", periods=3) + else: + base = pd.timedelta_range("1 day", periods=3) + df = pd.DataFrame({other: base.as_unit(other) for other in ["s", "ms", "us", "ns"]}) + + result = df.select_dtypes(include=[f"{byteorder}{kind}[{unit}]"]) + tm.assert_frame_equal(result, df[[unit]]) + + result = df.select_dtypes(exclude=[f"{byteorder}{kind}[{unit}]"]) + tm.assert_frame_equal(result, df.drop(columns=[unit])) + + +@pytest.mark.parametrize("kind", ["datetime64", "timedelta64"]) +def test_select_dtypes_dt64_td64_string_byteorder_unitless(kind): + # GH#40234 a byteswapped but unitless string still matches every resolution + if kind == "datetime64": + base = pd.date_range("2020-01-01", periods=3) + else: + base = pd.timedelta_range("1 day", periods=3) + df = pd.DataFrame({other: base.as_unit(other) for other in ["s", "ms", "us", "ns"]}) + + result = df.select_dtypes(include=[f">{kind}"]) + tm.assert_frame_equal(result, df) + + +def test_select_dtypes_td64_non_native_column(): + # GH#40234 a string spec matches by resolution, an instance spec stays exact. + # Construction normalizes byteorder and GH#68565 stopped astype producing a + # non-native column, so ``view`` plus setitem is the route left -- the + # byteorder assert is a tripwire for that becoming unreachable too + df = pd.DataFrame( + { + "le": pd.Series(np.array([1, 2], dtype="m8[s]")), + "ms": pd.Series(np.array([1, 2], dtype="m8[ms]")), + } + ) + df["be"] = pd.Series(np.array([1, 2], dtype="m8[s]")).array.view(">m8[s]") + assert df["be"].dtype.byteorder == ">" + + # a string spec is byteorder-agnostic on both sides + for spec in ("timedelta64[s]", ">timedelta64[s]", "m8[s]")]) + tm.assert_frame_equal(result, df[["be"]]) + + result = df.select_dtypes(include=[np.dtype("datetime64[D]"]) + + +@pytest.mark.parametrize("spec", ["datetime64[10s]", "timedelta64[2ns]"]) +def test_select_dtypes_dt64_td64_unit_multiple_raises(spec): + # GH#40234 a multiple of a supported unit (e.g. "10s") is not a resolution + # any column can have, so it raises rather than selecting nothing + df = pd.DataFrame( + { + "a": pd.date_range("2020-01-01", periods=3), + "b": pd.timedelta_range("1 day", periods=3), + } + ) + msg = "is not a supported datetime64/timedelta64 resolution" + with pytest.raises(ValueError, match=msg): + df.select_dtypes(include=[spec]) + with pytest.raises(ValueError, match=msg): + df.select_dtypes(include=[np.dtype(spec)]) + + +def test_select_dtypes_categorical_instance_exact(): + # GH#40234: a CategoricalDtype instance selects only its own categories, + # and ordered is part of the dtype + df = pd.DataFrame( + { + "unord": pd.Categorical(["a", "b"]), + "ord_ab": pd.Categorical(["a", "b"], ordered=True), + "other": pd.Categorical(["x", "y"]), + "i": [1, 2], + } + ) + result = df.select_dtypes(include=pd.CategoricalDtype(["a", "b"])) + tm.assert_frame_equal(result, df[["unord"]]) + + result = df.select_dtypes(include=pd.CategoricalDtype(["a", "b"], ordered=True)) + tm.assert_frame_equal(result, df[["ord_ab"]]) + + +@pytest.mark.parametrize("kwarg", ["include", "exclude"]) +def test_select_dtypes_categorical_ordered_no_categories_raises(kwarg): + # GH#40234: a spec giving ordered but no categories names no dtype a + # column can have; it used to select every categorical column + df = pd.DataFrame({"unord": pd.Categorical(["a", "b"]), "i": [1, 2]}) + msg = "a CategoricalDtype spec giving 'ordered' must give categories too" + with pytest.raises(ValueError, match=msg): + df.select_dtypes(**{kwarg: pd.CategoricalDtype(ordered=True)}) + + +@pytest.mark.parametrize( + "spec", + [ + pd.CategoricalDtype, + "category", + pd.CategoricalDtype(), + # ordered=False is the constructor default, so this cannot be told + # apart from a bare CategoricalDtype() + pd.CategoricalDtype(ordered=False), + ], +) +def test_select_dtypes_categorical_family(spec): + # GH#40234: the class, the "category" string and an instance that gives + # no attribute all select every categorical column + df = pd.DataFrame( + { + "unord": pd.Categorical(["a", "b"]), + "ord_ab": pd.Categorical(["a", "b"], ordered=True), + "i": [1, 2], + } + ) + result = df.select_dtypes(include=spec) + tm.assert_frame_equal(result, df[["unord", "ord_ab"]]) + + +def test_select_dtypes_period_instance_exact(): + # GH#40234: a PeriodDtype instance matches only its own freq, whereas + # the PeriodDtype class matches every period column + df = pd.DataFrame( + { + "a": pd.period_range("2016-01-01", periods=2, freq="D"), + "b": pd.period_range("2016-01-01", periods=2, freq="M"), + } + ) + result = df.select_dtypes(include=pd.PeriodDtype("D")) + tm.assert_frame_equal(result, df[["a"]]) + + +def test_select_dtypes_object_instance_exact(using_infer_string): + # GH#40234: np.dtype(object) as an instance selects only object-dtype + # columns; the GH#61916 str-backcompat (and its deprecation warning) + # applies only to "object"/np.object_ specs + df = pd.DataFrame({"a": ["x", "y"], "b": np.array([1, "y"], dtype=object)}) + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=np.dtype(object)) + if using_infer_string: + expected = df[["b"]] + else: + expected = df[["a", "b"]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", [np.dtype("U5"), np.dtype("S5")]) +@pytest.mark.parametrize("arg", ["include", "exclude"]) +def test_select_dtypes_numpy_str_instance_raises(dtype, arg): + df = pd.DataFrame({"a": [1, 2]}) + msg = "string dtypes are not allowed" + with pytest.raises(TypeError, match=msg): + df.select_dtypes(**{arg: [dtype]}) + + +def test_select_dtypes_instance_overlap_raises(): + df = pd.DataFrame({"a": [1, 2]}) + msg = "include and exclude overlap" + with pytest.raises(ValueError, match=msg): + df.select_dtypes(include=[np.dtype("int64")], exclude=[np.dtype("int64")]) + + +def test_select_dtypes_ea_class_categorical(): + # GH#65366: an ExtensionDtype subclass matches every instance of that + # subclass, regardless of parametrization + df = pd.DataFrame( + { + "a": pd.Categorical(["x", "y"]), + "b": pd.Categorical([1, 2], categories=[1, 2, 3], ordered=True), + "c": [1, 2], + } + ) + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=pd.CategoricalDtype) + tm.assert_frame_equal(result, df[["a", "b"]]) + + result = df.select_dtypes(exclude=pd.CategoricalDtype) + tm.assert_frame_equal(result, df[["c"]]) + + +def test_select_dtypes_ea_class_arrow(): + # GH#65366 + pa = pytest.importorskip("pyarrow") + df = pd.DataFrame( + { + "a": pd.array([1, 2], dtype="int64[pyarrow]"), + "b": pd.array(["x", "y"], dtype=pd.ArrowDtype(pa.string())), + "c": [1, 2], + "d": pd.array([1, 2], dtype="Int64"), + } + ) + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=pd.ArrowDtype) + tm.assert_frame_equal(result, df[["a", "b"]]) + + result = df.select_dtypes(exclude=pd.ArrowDtype) + tm.assert_frame_equal(result, df[["c", "d"]]) + + +def test_select_dtypes_str_matches_arrow_strings(using_infer_string): + # GH#54898: the builtin str selects StringDtype and pyarrow string columns, + # while the "str" spec names StringDtype alone + if not using_infer_string: + pytest.skip("'str' is a numpy string dtype under the legacy string config") + pa = pytest.importorskip("pyarrow") + df = pd.DataFrame( + { + "a": pd.array(["x", "y"], dtype=pd.ArrowDtype(pa.string())), + "b": pd.array(["x", "y"], dtype=pd.ArrowDtype(pa.large_string())), + "c": pd.array(["x", "y"], dtype=pd.StringDtype(na_value=np.nan)), + "d": pd.array(["x", "y"], dtype=pd.StringDtype("python", na_value=pd.NA)), + "e": [1, 2], + } + ) + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=str) + tm.assert_frame_equal(result, df[["a", "b", "c", "d"]]) + + result = df.select_dtypes(include="str") + tm.assert_frame_equal(result, df[["c", "d"]]) + + +def test_select_dtypes_ea_class_masked_does_not_match_numpy(): + # GH#40234: Int64Dtype class matches only the masked dtype, not numpy int64 + df = pd.DataFrame({"a": pd.array([1, 2], dtype="Int64"), "b": [1, 2]}) + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=pd.Int64Dtype) + tm.assert_frame_equal(result, df[["a"]]) + + +def test_select_dtypes_ea_class_datetimetz(): + # GH#65366 + df = pd.DataFrame( + { + "a": pd.date_range("2016-01-01", periods=2, tz="US/Pacific"), + "b": pd.date_range("2016-01-01", periods=2, tz="UTC"), + "c": pd.date_range("2016-01-01", periods=2), + "d": [1, 2], + } + ) + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=pd.DatetimeTZDtype) + tm.assert_frame_equal(result, df[["a", "b"]]) + + +@pytest.mark.parametrize("spec", ["datetimetz", "datetime64tz"]) +@pytest.mark.parametrize("arg", ["include", "exclude"]) +def test_select_dtypes_datetimetz_string(spec, arg): + # GH#24558 + df = pd.DataFrame( + { + "a": pd.date_range("2016-01-01", periods=2, tz="US/Pacific"), + "b": pd.date_range("2016-01-01", periods=2), + } + ) + with tm.assert_produces_warning(None): + result = df.select_dtypes(**{arg: spec}) + expected = df[["a"]] if arg == "include" else df[["b"]] + tm.assert_frame_equal(result, expected) + + # the class spec selects the same columns + alt = df.select_dtypes(**{arg: pd.DatetimeTZDtype}) + tm.assert_frame_equal(alt, expected) + + +def test_select_dtypes_datetimetz_string_overlaps_class(): + # GH#24558: the string and the class resolve to the same spec, so + # contradictory include/exclude is caught rather than silently + # returning an empty frame + df = pd.DataFrame({"a": pd.date_range("2016-01-01", periods=2, tz="UTC")}) + with pytest.raises(ValueError, match="include and exclude overlap"): + df.select_dtypes(include="datetimetz", exclude=pd.DatetimeTZDtype) + + +def test_select_dtypes_period_string_raises(): + # GH#24558: the "period" string was never implemented; the error points at + # the class spec, which selects every period column + df = pd.DataFrame( + { + "a": pd.period_range("2016-01-01", periods=2, freq="D"), + "b": pd.period_range("2016-01-01", periods=2, freq="M"), + "c": [1, 2], + } + ) + with pytest.raises(TypeError, match="does not support the 'period' string"): + df.select_dtypes(include="period") + + result = df.select_dtypes(include=pd.PeriodDtype) + tm.assert_frame_equal(result, df[["a", "b"]]) + + +def test_select_dtypes_ea_class_string(using_infer_string): + # GH#65366 + df = pd.DataFrame( + { + "a": ["x", "y"], + "b": [1, 2], + "c": pd.array(["x", "y"], dtype="string"), + } + ) + result = df.select_dtypes(include=pd.StringDtype) + if using_infer_string: + expected = df[["a", "c"]] + else: + expected = df[["c"]] + tm.assert_frame_equal(result, expected) + + +def test_select_dtypes_ea_class_string_with_object_no_warning(): + # GH#61916: explicitly passing StringDtype alongside object counts as + # handling 'str' columns, so no deprecation warning is emitted + df = pd.DataFrame({"a": ["x", "y"], "b": [1, 2]}) + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=[object, pd.StringDtype]) + tm.assert_frame_equal(result, df[["a"]]) + + +@pytest.mark.parametrize( + "kwargs, expected", + [ + ({"include": object, "exclude": pd.StringDtype(na_value=np.nan)}, ["o"]), + ({"include": object, "exclude": ExtensionDtype}, ["o"]), + ({"include": [object, pd.StringDtype(na_value=np.nan)]}, ["s", "o"]), + ({"include": [object, ExtensionDtype]}, ["s", "o"]), + ], +) +def test_select_dtypes_str_dtype_named_by_instance_or_base_no_warning(kwargs, expected): + # GH#61916: a StringDtype instance or the ExtensionDtype base class names the + # str columns just as str and the StringDtype class do, so nothing to warn about + df = pd.DataFrame( + { + "s": pd.array(["x", "y"], dtype=pd.StringDtype(na_value=np.nan)), + "o": np.array([{"k": 1}, None], dtype=object), + } + ) + with tm.assert_produces_warning(None): + result = df.select_dtypes(**kwargs) + tm.assert_frame_equal(result, df[expected]) + + +@pytest.mark.parametrize( + "kwargs", + [ + # the pd.NA flavor of StringDtype matches no column here + {"include": [object, pd.StringDtype()]}, + # an extension dtype class, but not one the str column is an instance of + {"include": [object, pd.CategoricalDtype]}, + {"include": object, "exclude": pd.CategoricalDtype}, + ], +) +def test_select_dtypes_str_dtype_not_named_still_warns(kwargs): + # GH#61916: none of these specs match "s", so 'object' is still the only + # thing selecting it and the result will change + df = pd.DataFrame( + { + "s": pd.array(["x", "y"], dtype=pd.StringDtype(na_value=np.nan)), + "o": np.array([{"k": 1}, None], dtype=object), + } + ) + msg = "For backward compatibility, 'str' dtypes are included" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.select_dtypes(**kwargs) + tm.assert_frame_equal(result, df) + + +def test_select_dtypes_str_dtype_one_storage_named_still_warns(): + # GH#61916: the spec names only the python-backed column, so "b" is still + # selected by 'object' alone and its fate does change + pytest.importorskip("pyarrow") + df = pd.DataFrame( + { + "a": pd.array( + ["x", "y"], dtype=pd.StringDtype(storage="python", na_value=np.nan) + ), + "b": pd.array( + ["x", "y"], dtype=pd.StringDtype(storage="pyarrow", na_value=np.nan) + ), + } + ) + msg = "For backward compatibility, 'str' dtypes are included" + spec = pd.StringDtype(storage="python", na_value=np.nan) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.select_dtypes(include=[object, spec]) + tm.assert_frame_equal(result, df) + + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=[object, pd.StringDtype]) + tm.assert_frame_equal(result, df) + + +def test_select_dtypes_ea_base_class(): + # GH#65366: the ExtensionDtype base class matches all extension dtypes + df = pd.DataFrame( + { + "a": pd.Categorical(["x", "y"]), + "b": pd.array([1, 2], dtype="Int64"), + "c": [1, 2], + } + ) + result = df.select_dtypes(include=ExtensionDtype) + tm.assert_frame_equal(result, df[["a", "b"]]) + + +def test_select_dtypes_ea_class_mixed_with_other_specs(): + # GH#65366 + df = pd.DataFrame({"a": pd.Categorical(["x", "y"]), "b": [1, 2], "c": [1.5, 2.5]}) + result = df.select_dtypes(include=[pd.CategoricalDtype, "int64"]) + tm.assert_frame_equal(result, df[["a", "b"]]) + + +def test_select_dtypes_ea_class_include_exclude_overlap_raises(): + # GH#65366 + df = pd.DataFrame({"a": pd.Categorical(["x"]), "b": [1]}) + msg = "include and exclude overlap" + with pytest.raises(ValueError, match=msg): + df.select_dtypes(include=pd.CategoricalDtype, exclude=pd.CategoricalDtype) + + +@pytest.mark.parametrize( + "string, np_dtype, ea_dtype, values", + [ + ("Int64", "int64", "Int64", [1, 2]), + ("Int32", "int32", "Int32", [1, 2]), + ("Float64", "float64", "Float64", [1.0, 2.0]), + ("boolean", "bool", "boolean", [True, False]), + ], +) +def test_select_dtypes_masked_name_string_matches_only_masked( + string, np_dtype, ea_dtype, values +): + # GH#40234: a nullable-dtype name (e.g. "Int64") selects only that extension + # dtype, not the numpy dtype that shares its ``dtype.type`` + df = pd.DataFrame( + { + "numpy": np.array(values, dtype=np_dtype), + "masked": pd.array(values, dtype=ea_dtype), + } + ) + tm.assert_frame_equal(df.select_dtypes(include=string), df[["masked"]]) + tm.assert_frame_equal(df.select_dtypes(exclude=string), df[["numpy"]]) + + +@pytest.mark.parametrize( + "string, np_dtype, masked_dtype, values", + [ + ("int64[pyarrow]", "int64", "Int64", [1, 2]), + ("float64[pyarrow]", "float64", "Float64", [1.0, 2.0]), + ("bool[pyarrow]", "bool", "boolean", [True, False]), + ], +) +def test_select_dtypes_arrow_name_string_matches_only_arrow( + string, np_dtype, masked_dtype, values +): + # GH#59888: the string form of an Arrow dtype matches only Arrow columns of + # that exact dtype. Previously "int64[pyarrow]" matched nothing and + # "float64[pyarrow]" matched every float column via ``dtype.type``. + pytest.importorskip("pyarrow") + df = pd.DataFrame( + { + "numpy": np.array(values, dtype=np_dtype), + "masked": pd.array(values, dtype=masked_dtype), + "arrow": pd.array(values, dtype=string), + } + ) + tm.assert_frame_equal(df.select_dtypes(include=string), df[["arrow"]]) + + +def test_select_dtypes_arrow_timestamp_string_matches_only_arrow(): + # GH#59888: previously "timestamp[ns][pyarrow]" matched a tz-aware numpy + # column (both have ``dtype.type`` Timestamp) and missed the Arrow column + pytest.importorskip("pyarrow") + dti = pd.to_datetime(["2020-01-01", "2020-01-02"]).as_unit("ns") + df = pd.DataFrame( + { + "naive": dti, + "tz": dti.tz_localize("UTC"), + "arrow": pd.array(dti, dtype="timestamp[ns][pyarrow]"), + } + ) + result = df.select_dtypes(include=["timestamp[ns][pyarrow]"]) + tm.assert_frame_equal(result, df[["arrow"]]) + + +@pytest.mark.parametrize( + "spec", ["datetime64[s]", "datetime64", "datetime", np.datetime64] +) +def test_select_dtypes_naive_spec_skips_tz_aware_arrow(spec): + # GH#68075: ArrowDtype columns are matched through their numpy_dtype, which + # drops the tz, so a naive spec used to select a tz-aware Arrow column -- + # the tz-aware numpy column it mirrors is correctly not selected + pa = pytest.importorskip("pyarrow") + dti = pd.date_range("2020-01-01", periods=2, tz="UTC").as_unit("s") + df = pd.DataFrame( + { + "arrow_tz": pd.array(dti, dtype=pd.ArrowDtype(pa.timestamp("s", tz="UTC"))), + "np_tz": dti, + "arrow_naive": pd.array( + dti.tz_localize(None), dtype=pd.ArrowDtype(pa.timestamp("s")) + ), + "np_naive": dti.tz_localize(None), + } + ) + expected = df[["arrow_naive", "np_naive"]] + tm.assert_frame_equal(df.select_dtypes(include=[spec]), expected) + tm.assert_frame_equal(df.select_dtypes(exclude=[spec]), df[["arrow_tz", "np_tz"]]) + + +def test_select_dtypes_tz_aware_arrow_still_matched_by_arrow_spec(): + # GH#68075: the specs that do name the tz-aware Arrow dtype keep working + pa = pytest.importorskip("pyarrow") + dti = pd.date_range("2020-01-01", periods=2, tz="UTC").as_unit("s") + dtype = pd.ArrowDtype(pa.timestamp("s", tz="UTC")) + df = pd.DataFrame({"arrow_tz": pd.array(dti, dtype=dtype), "np_tz": dti}) + expected = df[["arrow_tz"]] + for spec in [dtype, dtype.name, pd.ArrowDtype]: + tm.assert_frame_equal(df.select_dtypes(include=[spec]), expected) + + +@pytest.mark.parametrize("pa_type", ["date32", "date64"]) +def test_select_dtypes_arrow_date_no_tz_attribute(pa_type): + # GH#68075: the tz guard must not assume every kind "M" ArrowDtype is a + # timestamp -- date32/date64 have no tz attribute + pa = pytest.importorskip("pyarrow") + dtype = pd.ArrowDtype(getattr(pa, pa_type)()) + df = pd.DataFrame({"num": [1, 2], "date": pd.array([1, 2], dtype=dtype)}) + tm.assert_frame_equal(df.select_dtypes(include="number"), df[["num"]]) + tm.assert_frame_equal(df.select_dtypes(exclude="number"), df[["date"]]) + tm.assert_frame_equal(df.select_dtypes(include=dtype), df[["date"]]) + # the guard must skip these columns, not reject them: their numpy_dtype is + # a datetime64, so a naive datetime spec selects them + for spec in ["datetime", np.datetime64]: + tm.assert_frame_equal(df.select_dtypes(include=spec), df[["date"]]) + tm.assert_frame_equal(df.select_dtypes(exclude=spec), df[["num"]]) + + +@pytest.mark.parametrize("pa_type", ["date32", "date64"]) +def test_select_dtypes_arrow_date_skipped_by_unit_spec(pa_type): + # GH#68488: a date column is day-resolution, but numpy_dtype reports a + # datetime64 of whatever unit pyarrow picks, so a unit-qualified spec used + # to select it at a resolution it does not have + pa = pytest.importorskip("pyarrow") + dtype = pd.ArrowDtype(getattr(pa, pa_type)()) + df = pd.DataFrame( + { + "date": pd.array([1, 2], dtype=dtype), + "ts": pd.array([1, 2], dtype=pd.ArrowDtype(pa.timestamp("ms"))), + } + ) + for spec in ["datetime64[s]", "datetime64[ms]", "datetime64[us]", "datetime64[ns]"]: + result = df.select_dtypes(include=spec) + expected = df[["ts"]] if spec == "datetime64[ms]" else df[[]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "spec", ["interval[int64, right]", pd.IntervalDtype("int64", "right")] +) +def test_select_dtypes_interval_closed_matches_exact(spec): + # GH#66119, GH#66120: a fully specified interval spec (subtype and closed) + # still matches only that exact closed value + df = pd.DataFrame( + { + "int_right": pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3]), + "int_left": pd.arrays.IntervalArray.from_breaks( + [0, 1, 2, 3], closed="left" + ), + } + ) + result = df.select_dtypes(include=spec) + tm.assert_frame_equal(result, df[["int_right"]]) + + +@pytest.mark.parametrize("spec", ["interval", pd.IntervalDtype, pd.IntervalDtype()]) +def test_select_dtypes_interval_family(spec): + # GH#40234: the "interval" string, the IntervalDtype class and an instance + # that gives neither subtype nor closed all select every interval column + df = pd.DataFrame( + { + "int_right": pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3]), + "float_left": pd.arrays.IntervalArray.from_breaks( + [0.0, 1.0, 2.0, 3.0], closed="left" + ), + "other": [1, 2, 3], + } + ) + expected = df[["int_right", "float_left"]] + tm.assert_frame_equal(df.select_dtypes(include=spec), expected) + + +def _interval_unit_frame(): + dti = pd.to_datetime(["2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04"]) + tdi = pd.to_timedelta([1, 2, 3, 4], unit="D") + return pd.DataFrame( + { + "dt_ns": pd.arrays.IntervalArray.from_breaks(dti.as_unit("ns")), + "dt_us_left": pd.arrays.IntervalArray.from_breaks( + dti.as_unit("us"), closed="left" + ), + "dt_tz": pd.arrays.IntervalArray.from_breaks(dti.tz_localize("UTC")), + "td_s": pd.arrays.IntervalArray.from_breaks(tdi.as_unit("s")), + "int_right": pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3]), + } + ) + + +@pytest.mark.parametrize( + "spec, msg", + [ + (pd.IntervalDtype(closed="left"), "e.g. pd.IntervalDtype('int64', 'left')"), + (pd.IntervalDtype(closed="right"), "e.g. pd.IntervalDtype('int64', 'right')"), + ("interval[int64]", "e.g. 'interval[int64, right]'"), + (pd.IntervalDtype("int64"), "e.g. 'interval[int64, right]'"), + ("interval[datetime64]", "e.g. 'interval[datetime64[us], right]'"), + (pd.IntervalDtype(np.dtype("M8")), "e.g. 'interval[datetime64[us], right]'"), + ("interval[timedelta64, left]", "e.g. 'interval[timedelta64[us], left]'"), + ( + pd.IntervalDtype(np.dtype("M8"), "left"), + "e.g. 'interval[datetime64[us], left]'", + ), + ], +) +@pytest.mark.parametrize("kwarg", ["include", "exclude"]) +def test_select_dtypes_partial_interval_raises(spec, msg, kwarg): + # GH#40234: an interval spec that gives one attribute names one exact + # dtype, so leaving another open names no dtype a column can have + df = _interval_unit_frame() + with pytest.raises(ValueError, match=re.escape(msg)): + df.select_dtypes(**{kwarg: spec}) + + +@pytest.mark.parametrize( + "spec", + [ + "interval[datetime64[10s]]", + "interval[datetime64[Y], left]", + "interval[timedelta64[2ns]]", + pd.IntervalDtype(np.dtype("M8[10s]")), + pd.IntervalDtype(np.dtype("M8[Y]"), "left"), + pd.IntervalDtype(np.dtype("m8[2ns]")), + ], +) +@pytest.mark.parametrize("kwarg", ["include", "exclude"]) +def test_select_dtypes_interval_unsupported_subtype_resolution_raises(spec, kwarg): + # GH#40234 a subtype naming a resolution no column can have raises, as the + # same resolution does at the top level, instead of selecting nothing + df = _interval_unit_frame() + msg = ( + f"{str(spec)!r} is not a supported datetime64/timedelta64 resolution; " + "pass 's', 'ms', 'us', 'ns', or 'interval'" + ) + with pytest.raises(ValueError, match=re.escape(msg)): + df.select_dtypes(**{kwarg: spec}) + + # the remedy the message names selects interval columns + assert not df.select_dtypes(include="interval").empty + + +@pytest.mark.parametrize("kwarg", ["include", "exclude"]) +def test_select_dtypes_none_in_listlike_deprecated(kwarg): + # GH#28943: None inside the list-like reaches np.dtype(None) and selects + # float64 columns, unlike a bare include=None/exclude=None + df = pd.DataFrame({"a": [1, 2], "b": [True, False], "c": [1.0, 2.0]}) + msg = "Passing None in the include/exclude list to select_dtypes" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.select_dtypes(**{kwarg: [None]}) + + expected = df[["c"]] if kwarg == "include" else df[["a", "b"]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "spec", [decimal.Decimal, datetime.date, datetime.timedelta, pd.Timestamp, list] +) +@pytest.mark.parametrize("kwarg", ["include", "exclude"]) +def test_select_dtypes_non_dtype_class_raises(spec, kwarg): + # GH#68443 these resolved to object before 3.1, selecting every object column + df = pd.DataFrame({"a": [decimal.Decimal("1")], "b": [1]}) + msg = ( + f"select_dtypes does not support the class {spec.__name__}; " + "pass 'object' to select all object-dtype columns" + ) + with pytest.raises(TypeError, match=msg): + df.select_dtypes(**{kwarg: [spec]}) + + +@pytest.mark.parametrize( + "box", + [np.array, pd.Index, pd.Series, iter], + ids=["ndarray", "index", "series", "iterator"], +) +@pytest.mark.parametrize("kwarg", ["include", "exclude"]) +def test_select_dtypes_listlike_spec_container(box, kwarg): + # GH#68448: any list-like is accepted as the spec container. An ndarray/Index/ + # Series has no usable truthiness for the guards in ``predicate``, and a one-shot + # iterator is consumed by the frozensets before ``to_callable`` iterates it. + df = pd.DataFrame({"a": [1, 2], "b": [1.0, 2.0], "c": ["x", "y"]}) + result = df.select_dtypes(**{kwarg: box(["int64", "float64"])}) + + expected = df[["a", "b"]] if kwarg == "include" else df[["c"]] + tm.assert_frame_equal(result, expected) + + +def _object_str_frame(): + # both dtypes are spelled explicitly so these tests hold under the legacy + # string config too; a plain list of strings would be inferred to str dtype + return pd.DataFrame( + { + "a": pd.array(["x", "y"], dtype=pd.StringDtype(na_value=np.nan)), + "b": pd.Series(["p", "q"], dtype=object), + "c": [1, 2], + } + ) + + +@pytest.mark.parametrize("object_spec", ["object", np.object_, "O"]) +def test_select_dtypes_exclude_object_str_backcompat_deprecated(object_spec): + # GH#62718: excluding "object" also drops the default str dtype through the + # GH#61916 backwards-compat matching, so the exclude path needs the + # deprecation warning that the include path already emits + df = _object_str_frame() + msg = "For backward compatibility, 'str' dtypes are excluded" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.select_dtypes(exclude=object_spec) + tm.assert_frame_equal(result, df[["c"]]) + + +@pytest.mark.parametrize( + "str_spec", ["str", str, pd.StringDtype, pd.StringDtype(na_value=np.nan)] +) +def test_select_dtypes_explicit_str_not_matched_by_object(str_spec, using_infer_string): + # GH#62718: naming str explicitly means the caller is handling string + # columns, so an "object" spec on the other side must not claim them + if not using_infer_string and (str_spec is str or isinstance(str_spec, str)): + # a StringDtype instance compares equal to "str", so don't use == + pytest.skip("'str' is a numpy string dtype under the legacy string config") + df = _object_str_frame() + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=[str_spec, "number"], exclude="object") + tm.assert_frame_equal(result, df[["a", "c"]]) + + +@pytest.mark.parametrize( + "str_spec", ["str", str, pd.StringDtype, pd.StringDtype(na_value=np.nan)] +) +def test_select_dtypes_include_object_with_explicit_str_no_warning( + str_spec, using_infer_string +): + # GH#62718: "str" and the builtin str count as naming the string columns, + # like the StringDtype class and instance spellings, so nothing to warn about + if not using_infer_string and (str_spec is str or isinstance(str_spec, str)): + # a StringDtype instance compares equal to "str", so don't use == + pytest.skip("'str' is a numpy string dtype under the legacy string config") + df = _object_str_frame() + with tm.assert_produces_warning(None): + result = df.select_dtypes(include=["object", str_spec]) + tm.assert_frame_equal(result, df[["a", "b"]]) + + +@pytest.mark.parametrize("object_spec", [object, "object", np.object_]) +def test_select_dtypes_sparse_object_subtype(object_spec): + # GH#68494: a Sparse[object] column is an object column, but SparseDtype + # does not compare equal to np.dtype(object) + df = pd.DataFrame( + { + "a": pd.arrays.SparseArray(["x", "y"], dtype=object), + "b": pd.arrays.SparseArray([1, 2], dtype="int64"), + "c": pd.Series([1, "z"], dtype=object), + } + ) + tm.assert_frame_equal(df.select_dtypes(include=object_spec), df[["a", "c"]]) + tm.assert_frame_equal(df.select_dtypes(exclude=object_spec), df[["b"]]) + + +def test_select_dtypes_sparse_na_fill_value(): + # GH#68567: "Sparse[float64]" names the NaN-fill parametrization, so it must + # not also match a column whose fill_value is a real number + df = pd.DataFrame( + { + "a": pd.arrays.SparseArray([1.0, np.nan]), + "b": pd.arrays.SparseArray([1.0, 0.0], fill_value=0.0), + } + ) + tm.assert_frame_equal(df.select_dtypes(include="Sparse[float64]"), df[["a"]]) + tm.assert_frame_equal(df.select_dtypes(exclude="Sparse[float64]"), df[["b"]]) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_set_axis.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_set_axis.py new file mode 100644 index 0000000000000000000000000000000000000000..4a7a520fea6691e038431965899faddd2eea00ae --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_set_axis.py @@ -0,0 +1,127 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class SharedSetAxisTests: + @pytest.fixture + def obj(self): + raise NotImplementedError("Implemented by subclasses") + + def test_set_axis(self, obj): + # GH14636; this tests setting index for both Series and DataFrame + new_index = list("abcd")[: len(obj)] + expected = obj.copy() + expected.index = new_index + result = obj.set_axis(new_index, axis=0) + tm.assert_equal(expected, result) + + def test_set_axis_copy(self, obj): + # Test copy keyword GH#47932 + new_index = list("abcd")[: len(obj)] + + orig = obj.iloc[:] + expected = obj.copy() + expected.index = new_index + + result = obj.set_axis(new_index, axis=0) + tm.assert_equal(expected, result) + assert result is not obj + # check we did NOT make a copy + if obj.ndim == 1: + assert tm.shares_memory(result, obj) + else: + assert all( + tm.shares_memory(result.iloc[:, i], obj.iloc[:, i]) + for i in range(obj.shape[1]) + ) + + result = obj.set_axis(new_index, axis=0) + tm.assert_equal(expected, result) + assert result is not obj + # check we DID NOT make a copy + if obj.ndim == 1: + assert tm.shares_memory(result, obj) + else: + assert any( + tm.shares_memory(result.iloc[:, i], obj.iloc[:, i]) + for i in range(obj.shape[1]) + ) + + res = obj.set_axis(new_index) + tm.assert_equal(expected, res) + # check we did NOT make a copy + if res.ndim == 1: + assert tm.shares_memory(res, orig) + else: + assert all( + tm.shares_memory(res.iloc[:, i], orig.iloc[:, i]) + for i in range(res.shape[1]) + ) + + def test_set_axis_unnamed_kwarg_warns(self, obj): + # omitting the "axis" parameter + new_index = list("abcd")[: len(obj)] + + expected = obj.copy() + expected.index = new_index + + result = obj.set_axis(new_index) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("axis", [3, "foo"]) + def test_set_axis_invalid_axis_name(self, axis, obj): + # wrong values for the "axis" parameter + with pytest.raises(ValueError, match="No axis named"): + obj.set_axis(list("abc"), axis=axis) + + def test_set_axis_setattr_index_not_collection(self, obj): + # wrong type + msg = ( + r"Index\(\.\.\.\) must be called with a collection of some " + r"kind, None was passed" + ) + with pytest.raises(TypeError, match=msg): + obj.index = None + + def test_set_axis_setattr_index_wrong_length(self, obj): + # wrong length + msg = ( + f"Length mismatch: Expected axis has {len(obj)} elements, " + f"new values have {len(obj) - 1} elements" + ) + with pytest.raises(ValueError, match=msg): + obj.index = np.arange(len(obj) - 1) + + if obj.ndim == 2: + with pytest.raises(ValueError, match="Length mismatch"): + obj.columns = obj.columns[::2] + + +class TestDataFrameSetAxis(SharedSetAxisTests): + @pytest.fixture + def obj(self): + df = pd.DataFrame( + {"A": [1.1, 2.2, 3.3], "B": [5.0, 6.1, 7.2], "C": [4.4, 5.5, 6.6]}, + index=[2010, 2011, 2012], + ) + return df + + def test_set_axis_with_allows_duplicate_labels_false(self): + # GH#44958 + df = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"]).set_flags( + allows_duplicate_labels=False + ) + + result = df.set_axis(labels=["x", "y"], axis=0) + expected = pd.DataFrame([[1, 2], [3, 4]], index=["x", "y"], columns=["a", "b"]) + tm.assert_frame_equal(result, expected, check_flags=False) + + +class TestSeriesSetAxis(SharedSetAxisTests): + @pytest.fixture + def obj(self): + ser = pd.Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64") + return ser diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_set_index.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_set_index.py new file mode 100644 index 0000000000000000000000000000000000000000..f51e01d71299cd9a3a4228f2241058cbb3b74d14 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_set_index.py @@ -0,0 +1,761 @@ +""" +See also: test_reindex.py:TestReindexSetIndex +""" + +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +@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 = pd.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 + + +class TestSetIndex: + def test_set_index_multiindex(self): + # segfault in GH#3308 + d = {"t1": [2, 2.5, 3], "t2": [4, 5, 6]} + df = pd.DataFrame(d) + tuples = [(0, 1), (0, 2), (1, 2)] + df["tuples"] = tuples + + index = pd.MultiIndex.from_tuples(df["tuples"]) + # it works! + df.set_index(index) + + def test_set_index_empty_column(self): + # GH#1971 + df = pd.DataFrame( + [ + {"a": 1, "p": 0}, + {"a": 2, "m": 10}, + {"a": 3, "m": 11, "p": 20}, + {"a": 4, "m": 12, "p": 21}, + ], + columns=["a", "m", "p", "x"], + ) + + result = df.set_index(["a", "x"]) + + expected = df[["m", "p"]] + expected.index = pd.MultiIndex.from_arrays([df["a"], df["x"]], names=["a", "x"]) + tm.assert_frame_equal(result, expected) + + def test_set_index_empty_dataframe(self): + # GH#38419 + df1 = pd.DataFrame( + { + "a": pd.Series(dtype="datetime64[ns]"), + "b": pd.Series(dtype="int64"), + "c": [], + } + ) + + df2 = df1.set_index(["a", "b"]) + result = df2.index.to_frame().dtypes + expected = df1[["a", "b"]].dtypes + tm.assert_series_equal(result, expected) + + def test_set_index_multiindexcolumns(self): + columns = pd.MultiIndex.from_tuples([("foo", 1), ("foo", 2), ("bar", 1)]) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), columns=columns + ) + + result = df.set_index(df.columns[0]) + + expected = df.iloc[:, 1:] + expected.index = df.iloc[:, 0].values + expected.index.names = [df.columns[0]] + tm.assert_frame_equal(result, expected) + + def test_set_index_timezone(self): + # GH#12358 + # tz-aware Series should retain the tz + idx = pd.DatetimeIndex(["2014-01-01 10:10:10"], tz="UTC").tz_convert( + "Europe/Rome" + ) + df = pd.DataFrame({"A": idx}) + assert df.set_index(idx).index[0].hour == 11 + assert pd.DatetimeIndex(pd.Series(df.A))[0].hour == 11 + assert df.set_index(df.A).index[0].hour == 11 + + def test_set_index_cast_datetimeindex(self): + df = pd.DataFrame( + { + "A": [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)], + "B": np.random.default_rng(2).standard_normal(1000), + } + ) + + idf = df.set_index("A") + assert isinstance(idf.index, pd.DatetimeIndex) + + def test_set_index_dst(self): + di = pd.date_range("2006-10-29 00:00:00", periods=3, freq="h", tz="US/Pacific") + + df = pd.DataFrame(data={"a": [0, 1, 2], "b": [3, 4, 5]}, index=di).reset_index() + # single level + res = df.set_index("index") + exp = pd.DataFrame( + data={"a": [0, 1, 2], "b": [3, 4, 5]}, + index=pd.Index(di, name="index"), + ) + exp.index = exp.index._with_freq(None) + tm.assert_frame_equal(res, exp) + + # GH#12920 + res = df.set_index(["index", "a"]) + exp_index = pd.MultiIndex.from_arrays([di, [0, 1, 2]], names=["index", "a"]) + exp = pd.DataFrame({"b": [3, 4, 5]}, index=exp_index) + tm.assert_frame_equal(res, exp, check_freq=False) + + def test_set_index(self, float_string_frame): + df = float_string_frame + idx = pd.RangeIndex(start=29, stop=-1, step=-1) + + df = df.set_index(idx) + tm.assert_index_equal(df.index, idx) + with pytest.raises(ValueError, match="Length mismatch"): + df.set_index(idx[::2]) + + def test_set_index_names(self): + df = pd.DataFrame( + np.ones((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(10)], dtype=object), + ) + df.index.name = "name" + + assert df.set_index(df.index).index.names == ["name"] + + mi = pd.MultiIndex.from_arrays(df[["A", "B"]].T.values, names=["A", "B"]) + mi2 = pd.MultiIndex.from_arrays( + df[["A", "B", "A", "B"]].T.values, names=["A", "B", "C", "D"] + ) + + df = df.set_index(["A", "B"]) + + assert df.set_index(df.index).index.names == ["A", "B"] + + # Check that set_index isn't converting a MultiIndex into an Index + assert isinstance(df.set_index(df.index).index, pd.MultiIndex) + + # Check actual equality + tm.assert_index_equal(df.set_index(df.index).index, mi) + + idx2 = df.index.rename(["C", "D"]) + + # Check that [MultiIndex, MultiIndex] yields a MultiIndex rather + # than a pair of tuples + assert isinstance(df.set_index([df.index, idx2]).index, pd.MultiIndex) + + # Check equality + tm.assert_index_equal(df.set_index([df.index, idx2]).index, mi2) + + # A has duplicate values, C does not + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.set_index is") + @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")]) + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_drop_inplace(self, frame_of_index_cols, drop, inplace, keys): + df = frame_of_index_cols + + if isinstance(keys, list): + idx = pd.MultiIndex.from_arrays([df[x] for x in keys], names=keys) + else: + idx = pd.Index(df[keys], name=keys) + expected = df.drop(keys, axis=1) if drop else df + expected.index = idx + + if inplace: + result = df.copy() + return_value = result.set_index(keys, drop=drop, inplace=True) + assert return_value is None + else: + result = df.set_index(keys, drop=drop) + + tm.assert_frame_equal(result, expected) + + def test_set_index_inplace_depr(self): + df1 = pd.DataFrame(data=[[1, 2, 3], [2, 4, 6]], columns=["a", "b", "c"]) + msg = "The inplace keyword in DataFrame.set_index is deprecated" + + with tm.assert_produces_warning(False): + df1.set_index("a") + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df1.set_index("a", inplace=False) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df1.set_index("a", inplace=True) + + # A has duplicate values, C does not + @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")]) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_append(self, frame_of_index_cols, drop, keys): + df = frame_of_index_cols + + keys = keys if isinstance(keys, list) else [keys] + idx = pd.MultiIndex.from_arrays( + [df.index] + [df[x] for x in keys], names=[None, *keys] + ) + expected = df.drop(keys, axis=1) if drop else df.copy() + expected.index = idx + + result = df.set_index(keys, drop=drop, append=True) + + tm.assert_frame_equal(result, expected) + + # A has duplicate values, C does not + @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")]) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_append_to_multiindex(self, frame_of_index_cols, drop, keys): + # append to existing multiindex + df = frame_of_index_cols.set_index(["D"], drop=drop, append=True) + + keys = keys if isinstance(keys, list) else [keys] + expected = frame_of_index_cols.set_index(["D", *keys], drop=drop, append=True) + + result = df.set_index(keys, drop=drop, append=True) + + tm.assert_frame_equal(result, expected) + + def test_set_index_after_mutation(self): + # GH#1590 + df = pd.DataFrame({"val": [0, 1, 2], "key": ["a", "b", "c"]}) + expected = pd.DataFrame({"val": [1, 2]}, pd.Index(["b", "c"], name="key")) + + df2 = df.loc[df.index.map(lambda indx: indx >= 1)] + result = df2.set_index("key") + tm.assert_frame_equal(result, expected) + + # MultiIndex constructor does not work directly on Series -> lambda + # Add list-of-list constructor because list is ambiguous -> lambda + # also test index name if append=True (name is duplicate here for B) + @pytest.mark.parametrize( + "box", + [ + pd.Series, + pd.Index, + np.array, + list, + lambda x: [list(x)], + lambda x: pd.MultiIndex.from_arrays([x]), + ], + ) + @pytest.mark.parametrize( + "append, index_name", [(True, None), (True, "B"), (True, "test"), (False, None)] + ) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_pass_single_array( + self, frame_of_index_cols, drop, append, index_name, box + ): + df = frame_of_index_cols + df.index.name = index_name + + key = box(df["B"]) + if box == list: + # list of strings gets interpreted as list of keys + msg = "['one', 'two', 'three', 'one', 'two']" + with pytest.raises(KeyError, match=msg): + df.set_index(key, drop=drop, append=append) + else: + # np.array/list-of-list "forget" the name of B + name_mi = getattr(key, "names", None) + name = [getattr(key, "name", None)] if name_mi is None else name_mi + + result = df.set_index(key, drop=drop, append=append) + + # only valid column keys are dropped + # since B is always passed as array above, nothing is dropped + expected = df.set_index(["B"], drop=False, append=append) + expected.index.names = [index_name, *name] if append else name + + tm.assert_frame_equal(result, expected) + + # MultiIndex constructor does not work directly on Series -> lambda + # also test index name if append=True (name is duplicate here for A & B) + @pytest.mark.parametrize( + "box", + [pd.Series, pd.Index, np.array, list, lambda x: pd.MultiIndex.from_arrays([x])], + ) + @pytest.mark.parametrize( + "append, index_name", + [(True, None), (True, "A"), (True, "B"), (True, "test"), (False, None)], + ) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_pass_arrays( + self, frame_of_index_cols, drop, append, index_name, box + ): + df = frame_of_index_cols + df.index.name = index_name + + keys = ["A", box(df["B"])] + # np.array/list "forget" the name of B + names = ["A", None if box in [np.array, list, tuple, iter] else "B"] + + result = df.set_index(keys, drop=drop, append=append) + + # only valid column keys are dropped + # since B is always passed as array above, only A is dropped, if at all + expected = df.set_index(["A", "B"], drop=False, append=append) + expected = expected.drop("A", axis=1) if drop else expected + expected.index.names = [index_name, *names] if append else names + + tm.assert_frame_equal(result, expected) + + # MultiIndex constructor does not work directly on Series -> lambda + # We also emulate a "constructor" for the label -> lambda + # also test index name if append=True (name is duplicate here for A) + @pytest.mark.parametrize( + "box2", + [ + pd.Series, + pd.Index, + np.array, + list, + iter, + lambda x: pd.MultiIndex.from_arrays([x]), + lambda x: x.name, + ], + ) + @pytest.mark.parametrize( + "box1", + [ + pd.Series, + pd.Index, + np.array, + list, + iter, + lambda x: pd.MultiIndex.from_arrays([x]), + lambda x: x.name, + ], + ) + @pytest.mark.parametrize( + "append, index_name", [(True, None), (True, "A"), (True, "test"), (False, None)] + ) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_pass_arrays_duplicate( + self, frame_of_index_cols, drop, append, index_name, box1, box2 + ): + df = frame_of_index_cols + df.index.name = index_name + + keys = [box1(df["A"]), box2(df["A"])] + result = df.set_index(keys, drop=drop, append=append) + + # if either box is iter, it has been consumed; re-read + keys = [box1(df["A"]), box2(df["A"])] + + # need to adapt first drop for case that both keys are 'A' -- + # cannot drop the same column twice; + # plain == would give ambiguous Boolean error for containers + first_drop = ( + False + if ( + isinstance(keys[0], str) + and keys[0] == "A" + and isinstance(keys[1], str) + and keys[1] == "A" + ) + else drop + ) + # to test against already-tested behaviour, we add sequentially, + # hence second append always True; must wrap keys in list, otherwise + # box = list would be interpreted as keys + expected = df.set_index([keys[0]], drop=first_drop, append=append) + expected = expected.set_index([keys[1]], drop=drop, append=True) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("append", [True, False]) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_pass_multiindex(self, frame_of_index_cols, drop, append): + df = frame_of_index_cols + keys = pd.MultiIndex.from_arrays([df["A"], df["B"]], names=["A", "B"]) + + result = df.set_index(keys, drop=drop, append=append) + + # setting with a MultiIndex will never drop columns + expected = df.set_index(["A", "B"], drop=False, append=append) + + tm.assert_frame_equal(result, expected) + + def test_construction_with_categorical_index(self): + ci = pd.CategoricalIndex(list("ab") * 5, name="B") + + # with Categorical + df = pd.DataFrame( + {"A": np.random.default_rng(2).standard_normal(10), "B": ci.values} + ) + idf = df.set_index("B") + tm.assert_index_equal(idf.index, ci) + + # from a CategoricalIndex + df = pd.DataFrame({"A": np.random.default_rng(2).standard_normal(10), "B": ci}) + idf = df.set_index("B") + tm.assert_index_equal(idf.index, ci) + + # round-trip + idf = idf.reset_index().set_index("B") + tm.assert_index_equal(idf.index, ci) + + def test_set_index_preserve_object_dtype_after_query(self): + # GH#30517 set_index must not re-infer a subset that happens to be numeric; + # reset_index still does, so the round trip is not yet lossless + df = pd.DataFrame({"mixed": [1, 2, "abc", "def"], "ints": [100, 200, 300, 400]}) + + result = df.query("ints < 300").set_index("mixed").index + expected = pd.Index([1, 2], dtype=object, name="mixed") + + tm.assert_index_equal(result, expected) + + def test_set_index_preserve_categorical_dtype(self): + # GH#13743, GH#13854 + df = pd.DataFrame( + { + "A": [1, 2, 1, 1, 2], + "B": [10, 16, 22, 28, 34], + "C1": pd.Categorical( + list("abaab"), categories=list("bac"), ordered=False + ), + "C2": pd.Categorical( + list("abaab"), categories=list("bac"), ordered=True + ), + } + ) + for cols in ["C1", "C2", ["A", "C1"], ["A", "C2"], ["C1", "C2"]]: + result = df.set_index(cols).reset_index() + result = result.reindex(columns=df.columns) + tm.assert_frame_equal(result, df) + + def test_set_index_datetime(self): + # GH#3950 + df = pd.DataFrame( + { + "label": ["a", "a", "a", "b", "b", "b"], + "datetime": [ + "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", + ], + "value": range(6), + } + ) + df.index = pd.to_datetime(df.pop("datetime"), utc=True) + df.index = df.index.tz_convert("US/Pacific") + + expected = pd.DatetimeIndex( + ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"], + name="datetime", + ) + expected = expected.tz_localize("UTC").tz_convert("US/Pacific") + + df = df.set_index("label", append=True) + tm.assert_index_equal(df.index.levels[0], expected) + tm.assert_index_equal(df.index.levels[1], pd.Index(["a", "b"], name="label")) + assert df.index.names == ["datetime", "label"] + + df = df.swaplevel(0, 1) + tm.assert_index_equal(df.index.levels[0], pd.Index(["a", "b"], name="label")) + tm.assert_index_equal(df.index.levels[1], expected) + assert df.index.names == ["label", "datetime"] + + df = pd.DataFrame(np.random.default_rng(2).random(6)) + idx1 = pd.DatetimeIndex( + [ + "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", + ], + tz="US/Eastern", + ) + idx2 = pd.DatetimeIndex( + [ + "2012-04-01 09:00", + "2012-04-01 09:00", + "2012-04-01 09:00", + "2012-04-02 09:00", + "2012-04-02 09:00", + "2012-04-02 09:00", + ], + tz="US/Eastern", + ) + idx3 = pd.date_range("2011-01-01 09:00", periods=6, tz="Asia/Tokyo") + idx3 = idx3._with_freq(None) + + df = df.set_index(idx1) + df = df.set_index(idx2, append=True) + df = df.set_index(idx3, append=True) + + expected1 = pd.DatetimeIndex( + ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"], + tz="US/Eastern", + ) + expected2 = pd.DatetimeIndex( + ["2012-04-01 09:00", "2012-04-02 09:00"], tz="US/Eastern" + ) + + tm.assert_index_equal(df.index.levels[0], expected1) + tm.assert_index_equal(df.index.levels[1], expected2) + tm.assert_index_equal(df.index.levels[2], idx3) + + # GH#7092 + tm.assert_index_equal(df.index.get_level_values(0), idx1) + tm.assert_index_equal(df.index.get_level_values(1), idx2) + tm.assert_index_equal(df.index.get_level_values(2), idx3) + + def test_set_index_period(self): + # GH#6631 + df = pd.DataFrame(np.random.default_rng(2).random(6)) + idx1 = pd.period_range("2011-01-01", periods=3, freq="M") + idx1 = idx1.append(idx1) + idx2 = pd.period_range("2013-01-01 09:00", periods=2, freq="h") + idx2 = idx2.append(idx2).append(idx2) + idx3 = pd.period_range("2005", periods=6, freq="Y") + + df = df.set_index(idx1) + df = df.set_index(idx2, append=True) + df = df.set_index(idx3, append=True) + + expected1 = pd.period_range("2011-01-01", periods=3, freq="M") + expected2 = pd.period_range("2013-01-01 09:00", periods=2, freq="h") + + tm.assert_index_equal(df.index.levels[0], expected1) + tm.assert_index_equal(df.index.levels[1], expected2) + tm.assert_index_equal(df.index.levels[2], idx3) + + tm.assert_index_equal(df.index.get_level_values(0), idx1) + tm.assert_index_equal(df.index.get_level_values(1), idx2) + tm.assert_index_equal(df.index.get_level_values(2), idx3) + + +class TestSetIndexInvalid: + def test_set_index_verify_integrity(self, frame_of_index_cols): + df = frame_of_index_cols + + msg = "The 'verify_integrity' keyword in DataFrame.set_index" + with pytest.raises(ValueError, match="Index has duplicate keys"): + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.set_index("A", verify_integrity=True) + # with MultiIndex + with pytest.raises(ValueError, match="Index has duplicate keys"): + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.set_index([df["A"], df["A"]], verify_integrity=True) + + @pytest.mark.parametrize("append", [True, False]) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_raise_keys(self, frame_of_index_cols, drop, append): + df = frame_of_index_cols + + with pytest.raises(KeyError, match="['foo', 'bar', 'baz']"): + # column names are A-E, as well as one tuple + df.set_index(["foo", "bar", "baz"], drop=drop, append=append) + + # non-existent key in list with arrays + with pytest.raises(KeyError, match="X"): + df.set_index([df["A"], df["B"], "X"], drop=drop, append=append) + + msg = "[('foo', 'foo', 'foo', 'bar', 'bar')]" + # tuples always raise KeyError + with pytest.raises(KeyError, match=msg): + df.set_index(tuple(df["A"]), drop=drop, append=append) + + # also within a list + with pytest.raises(KeyError, match=msg): + df.set_index(["A", df["A"], tuple(df["A"])], drop=drop, append=append) + + @pytest.mark.parametrize("append", [True, False]) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_raise_on_type(self, frame_of_index_cols, drop, append): + box = set + df = frame_of_index_cols + + msg = 'The parameter "keys" may be a column key, .*' + # forbidden type, e.g. set + with pytest.raises(TypeError, match=msg): + df.set_index(box(df["A"]), drop=drop, append=append) + + # forbidden type in list, e.g. set + with pytest.raises(TypeError, match=msg): + df.set_index(["A", df["A"], box(df["A"])], drop=drop, append=append) + + # MultiIndex constructor does not work directly on Series -> lambda + @pytest.mark.parametrize( + "box", + [pd.Series, pd.Index, np.array, iter, lambda x: pd.MultiIndex.from_arrays([x])], + ids=["Series", "Index", "np.array", "iter", "MultiIndex"], + ) + @pytest.mark.parametrize("length", [4, 6], ids=["too_short", "too_long"]) + @pytest.mark.parametrize("append", [True, False]) + @pytest.mark.parametrize("drop", [True, False]) + def test_set_index_raise_on_len( + self, frame_of_index_cols, box, length, drop, append + ): + # GH 24984 + df = frame_of_index_cols # has length 5 + + values = np.random.default_rng(2).integers(0, 10, (length,)) + + msg = "Length mismatch: Expected 5 rows, received array of length.*" + + # wrong length directly + with pytest.raises(ValueError, match=msg): + df.set_index(box(values), drop=drop, append=append) + + # wrong length in list + with pytest.raises(ValueError, match=msg): + df.set_index(["A", df.A, box(values)], drop=drop, append=append) + + +class TestSetIndexCustomLabelType: + def test_set_index_custom_label_type(self): + # GH#24969 + + class Thing: + def __init__(self, name, color) -> None: + self.name = name + self.color = color + + def __str__(self) -> str: + return f"" + + # necessary for pretty KeyError + __repr__ = __str__ + + thing1 = Thing("One", "red") + thing2 = Thing("Two", "blue") + df = pd.DataFrame({thing1: [0, 1], thing2: [2, 3]}) + expected = pd.DataFrame({thing1: [0, 1]}, index=pd.Index([2, 3], name=thing2)) + + # use custom label directly + result = df.set_index(thing2) + tm.assert_frame_equal(result, expected) + + # custom label wrapped in list + result = df.set_index([thing2]) + tm.assert_frame_equal(result, expected) + + # missing key + thing3 = Thing("Three", "pink") + msg = "" + with pytest.raises(KeyError, match=msg): + # missing label directly + df.set_index(thing3) + + with pytest.raises(KeyError, match=msg): + # missing label in list + df.set_index([thing3]) + + def test_set_index_custom_label_hashable_iterable(self): + # GH#24969 + + # actual example discussed in GH 24984 was e.g. for shapely.geometry + # objects (e.g. a collection of Points) that can be both hashable and + # iterable; using frozenset as a stand-in for testing here + + class Thing(frozenset): + # need to stabilize repr for KeyError (due to random order in sets) + def __repr__(self) -> str: + tmp = sorted(self) + joined_reprs = ", ".join(map(repr, tmp)) + # double curly brace prints one brace in format string + return f"frozenset({{{joined_reprs}}})" + + thing1 = Thing(["One", "red"]) + thing2 = Thing(["Two", "blue"]) + df = pd.DataFrame({thing1: [0, 1], thing2: [2, 3]}) + expected = pd.DataFrame({thing1: [0, 1]}, index=pd.Index([2, 3], name=thing2)) + + # use custom label directly + result = df.set_index(thing2) + tm.assert_frame_equal(result, expected) + + # custom label wrapped in list + result = df.set_index([thing2]) + tm.assert_frame_equal(result, expected) + + # missing key + thing3 = Thing(["Three", "pink"]) + msg = r"frozenset\(\{'Three', 'pink'\}\)" + with pytest.raises(KeyError, match=msg): + # missing label directly + df.set_index(thing3) + + with pytest.raises(KeyError, match=msg): + # missing label in list + df.set_index([thing3]) + + def test_set_index_custom_label_type_raises(self): + # GH#24969 + + # purposefully inherit from something unhashable + class Thing(set): + def __init__(self, name, color) -> None: + self.name = name + self.color = color + + def __str__(self) -> str: + return f"" + + thing1 = Thing("One", "red") + thing2 = Thing("Two", "blue") + df = pd.DataFrame([[0, 2], [1, 3]], columns=[thing1, thing2]) + + msg = 'The parameter "keys" may be a column key, .*' + + with pytest.raises(TypeError, match=msg): + # use custom label directly + df.set_index(thing2) + + with pytest.raises(TypeError, match=msg): + # custom label wrapped in list + df.set_index([thing2]) + + def test_set_index_periodindex(self): + # GH#6631 + df = pd.DataFrame(np.random.default_rng(2).random(6)) + idx1 = pd.period_range("2011/01/01", periods=6, freq="M") + idx2 = pd.period_range("2013", periods=6, freq="Y") + + df = df.set_index(idx1) + tm.assert_index_equal(df.index, idx1) + df = df.set_index(idx2) + tm.assert_index_equal(df.index, idx2) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_shift.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..df75783a9ea663d9d514a549db80bfe64eda1c43 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_shift.py @@ -0,0 +1,889 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameShift: + def test_shift_axis1_with_valid_fill_value_one_array(self): + # Case with axis=1 that does not go through the "len(arrays)>1" path + # in DataFrame.shift + data = np.random.default_rng(2).standard_normal((5, 3)) + df = pd.DataFrame(data) + res = df.shift(axis=1, periods=1, fill_value=12345) + expected = df.T.shift(periods=1, fill_value=12345).T + tm.assert_frame_equal(res, expected) + + # same but with a 1D ExtensionArray backing it + df2 = df[[0]].astype("Float64") + res2 = df2.shift(axis=1, periods=1, fill_value=12345) + expected2 = pd.DataFrame([12345] * 5, dtype="Float64") + tm.assert_frame_equal(res2, expected2) + + def test_shift_disallow_freq_and_fill_value(self, frame_or_series): + # Can't pass both! + obj = frame_or_series( + np.random.default_rng(2).standard_normal(5), + index=pd.date_range("1/1/2000", periods=5, freq="h"), + ) + + msg = "Passing a 'freq' together with a 'fill_value'" + with pytest.raises(ValueError, match=msg): + obj.shift(1, fill_value=1, freq="h") + + if frame_or_series is pd.DataFrame: + obj.columns = pd.date_range("1/1/2000", periods=1, freq="h") + with pytest.raises(ValueError, match=msg): + obj.shift(1, axis=1, fill_value=1, freq="h") + + @pytest.mark.parametrize( + "input_data, output_data", + [(np.empty(shape=(0,)), []), (np.ones(shape=(2,)), [np.nan, 1.0])], + ) + def test_shift_non_writable_array(self, input_data, output_data, frame_or_series): + # GH21049 Verify whether non writable numpy array is shiftable + input_data.setflags(write=False) + + result = frame_or_series(input_data).shift(1) + if frame_or_series is not pd.Series: + # need to explicitly specify columns in the empty case + expected = frame_or_series( + output_data, + index=range(len(output_data)), + columns=range(1), + dtype="float64", + ) + else: + expected = frame_or_series(output_data, dtype="float64") + + tm.assert_equal(result, expected) + + def test_shift_mismatched_freq(self, frame_or_series): + ts = frame_or_series( + np.random.default_rng(2).standard_normal(5), + index=pd.date_range("1/1/2000", periods=5, freq="h"), + ) + + result = ts.shift(1, freq="5min") + exp_index = ts.index.shift(1, freq="5min") + tm.assert_index_equal(result.index, exp_index) + + # GH#1063, multiple of same base + result = ts.shift(1, freq="4h") + exp_index = ts.index + pd.offsets.Hour(4) + tm.assert_index_equal(result.index, exp_index) + + @pytest.mark.parametrize( + "obj", + [ + pd.Series([np.arange(5)]), + pd.date_range("1/1/2011", periods=24, freq="h"), + pd.Series(range(5), index=pd.date_range("2017", periods=5)), + ], + ) + @pytest.mark.parametrize("shift_size", [0, 1, 2]) + def test_shift_always_copy(self, obj, shift_size, frame_or_series): + # GH#22397 + if frame_or_series is not pd.Series: + obj = obj.to_frame() + assert obj.shift(shift_size) is not obj + + def test_shift_object_non_scalar_fill(self): + # shift requires scalar fill_value except for object dtype + ser = pd.Series(range(3)) + with pytest.raises(ValueError, match="fill_value must be a scalar"): + ser.shift(1, fill_value=[]) + + df = ser.to_frame() + with pytest.raises(ValueError, match="fill_value must be a scalar"): + df.shift(1, fill_value=np.arange(3)) + + obj_ser = ser.astype(object) + result = obj_ser.shift(1, fill_value={}) + assert result[0] == {} + + obj_df = obj_ser.to_frame() + result = obj_df.shift(1, fill_value={}) + assert result.iloc[0, 0] == {} + + def test_shift_int(self, datetime_frame, frame_or_series): + ts = tm.get_obj(datetime_frame, frame_or_series).astype(int) + shifted = ts.shift(1) + expected = ts.astype(float).shift(1) + tm.assert_equal(shifted, expected) + + @pytest.mark.parametrize("dtype", ["int32", "int64"]) + def test_shift_32bit_take(self, frame_or_series, dtype): + # 32-bit taking + # GH#8129 + index = pd.date_range("2000-01-01", periods=5) + arr = np.arange(5, dtype=dtype) + s1 = frame_or_series(arr, index=index) + p = arr[1] + result = s1.shift(periods=p) + expected = frame_or_series([np.nan, 0, 1, 2, 3], index=index) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("periods", [1, 2, 3, 4]) + def test_shift_preserve_freqstr(self, periods, frame_or_series): + # GH#21275 + obj = frame_or_series( + range(periods), + index=pd.date_range("2016-1-1 00:00:00", periods=periods, freq="h"), + ) + + result = obj.shift(1, "2h") + + expected = frame_or_series( + range(periods), + index=pd.date_range("2016-1-1 02:00:00", periods=periods, freq="h"), + ) + tm.assert_equal(result, expected) + + def test_shift_dst(self, frame_or_series): + # GH#13926 + dates = pd.date_range( + "2016-11-06", freq="h", periods=10, tz="US/Eastern", unit="ns" + ) + obj = frame_or_series(dates) + + res = obj.shift(0) + tm.assert_equal(res, obj) + assert tm.get_dtype(res) == "datetime64[ns, US/Eastern]" + + res = obj.shift(1) + exp_vals = [pd.NaT, *dates.astype(object).values.tolist()[:9]] + exp = frame_or_series(exp_vals) + tm.assert_equal(res, exp) + assert tm.get_dtype(res) == "datetime64[ns, US/Eastern]" + + res = obj.shift(-2) + exp_vals = [*dates.astype(object).values.tolist()[2:], pd.NaT, pd.NaT] + exp = frame_or_series(exp_vals) + tm.assert_equal(res, exp) + assert tm.get_dtype(res) == "datetime64[ns, US/Eastern]" + + def test_shift_2d_dta_block(self): + # Ensure shift works correctly with a multi-row 2D DatetimeArray block, + # which does not arise via normal consolidation. + dta = pd.date_range("2016-01-01", periods=9)._values.reshape(3, 3) + df = pd.DataFrame(dta) + + # Verify we actually have a 2D EA block + assert df._mgr.blocks[0].values.shape == (3, 3) + + result = df.shift(1) + expected = pd.DataFrame( + { + 0: [pd.NaT, dta[0, 0], dta[1, 0]], + 1: [pd.NaT, dta[0, 1], dta[1, 1]], + 2: [pd.NaT, dta[0, 2], dta[1, 2]], + } + ) + tm.assert_frame_equal(result, expected) + + result = df.shift(-2) + expected = pd.DataFrame( + { + 0: [dta[2, 0], pd.NaT, pd.NaT], + 1: [dta[2, 1], pd.NaT, pd.NaT], + 2: [dta[2, 2], pd.NaT, pd.NaT], + } + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("ex", [10, -10, 20, -20]) + def test_shift_dst_beyond(self, frame_or_series, ex): + # GH#13926 + dates = pd.date_range( + "2016-11-06", freq="h", periods=10, tz="US/Eastern", unit="ns" + ) + obj = frame_or_series(dates) + res = obj.shift(ex) + exp = frame_or_series([pd.NaT] * 10, dtype="datetime64[ns, US/Eastern]") + tm.assert_equal(res, exp) + assert tm.get_dtype(res) == "datetime64[ns, US/Eastern]" + + def test_shift_by_zero(self, datetime_frame, frame_or_series): + # shift by 0 + obj = tm.get_obj(datetime_frame, frame_or_series) + unshifted = obj.shift(0) + tm.assert_equal(unshifted, obj) + + def test_shift(self, datetime_frame): + # naive shift + ser = datetime_frame["A"] + + shifted = datetime_frame.shift(5) + tm.assert_index_equal(shifted.index, datetime_frame.index) + + shifted_ser = ser.shift(5) + tm.assert_series_equal(shifted["A"], shifted_ser) + + shifted = datetime_frame.shift(-5) + tm.assert_index_equal(shifted.index, datetime_frame.index) + + shifted_ser = ser.shift(-5) + tm.assert_series_equal(shifted["A"], shifted_ser) + + unshifted = datetime_frame.shift(5).shift(-5) + tm.assert_numpy_array_equal( + unshifted.dropna().values, datetime_frame.values[:-5] + ) + + unshifted_ser = ser.shift(5).shift(-5) + tm.assert_numpy_array_equal(unshifted_ser.dropna().values, ser.values[:-5]) + + def test_shift_by_offset(self, datetime_frame, frame_or_series): + # shift by DateOffset + obj = tm.get_obj(datetime_frame, frame_or_series) + offset = pd.offsets.BDay() + + shifted = obj.shift(5, freq=offset) + assert len(shifted) == len(obj) + unshifted = shifted.shift(-5, freq=offset) + tm.assert_equal(unshifted, obj) + + shifted2 = obj.shift(5, freq="B") + tm.assert_equal(shifted, shifted2) + + unshifted = obj.shift(0, freq=offset) + tm.assert_equal(unshifted, obj) + + d = obj.index[0] + shifted_d = d + offset * 5 + if frame_or_series is pd.DataFrame: + tm.assert_series_equal(obj.xs(d), shifted.xs(shifted_d), check_names=False) + else: + tm.assert_almost_equal(obj.at[d], shifted.at[shifted_d]) + + def test_shift_with_periodindex(self, frame_or_series): + # Shifting with PeriodIndex + ps = pd.DataFrame( + np.arange(4, dtype=float), index=pd.period_range("2020-01-01", periods=4) + ) + ps = tm.get_obj(ps, frame_or_series) + + shifted = ps.shift(1) + unshifted = shifted.shift(-1) + tm.assert_index_equal(shifted.index, ps.index) + tm.assert_index_equal(unshifted.index, ps.index) + if frame_or_series is pd.DataFrame: + tm.assert_numpy_array_equal( + unshifted.iloc[:, 0].dropna().values, ps.iloc[:-1, 0].values + ) + else: + tm.assert_numpy_array_equal(unshifted.dropna().values, ps.values[:-1]) + + shifted2 = ps.shift(1, "D") + shifted3 = ps.shift(1, pd.offsets.Day()) + tm.assert_equal(shifted2, shifted3) + tm.assert_equal(ps, shifted2.shift(-1, "D")) + + msg = "does not match PeriodIndex freq" + with pytest.raises(ValueError, match=msg): + ps.shift(freq="W") + + # legacy support + shifted4 = ps.shift(1, freq="D") + tm.assert_equal(shifted2, shifted4) + + shifted5 = ps.shift(1, freq=pd.offsets.Day()) + tm.assert_equal(shifted5, shifted4) + + def test_shift_other_axis(self): + # shift other axis + # GH#6371 + df = pd.DataFrame(np.random.default_rng(2).random((10, 5))) + expected = pd.concat( + [pd.DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], + ignore_index=True, + axis=1, + ) + result = df.shift(1, axis=1) + tm.assert_frame_equal(result, expected) + + def test_shift_named_axis(self): + # shift named axis + df = pd.DataFrame(np.random.default_rng(2).random((10, 5))) + expected = pd.concat( + [pd.DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], + ignore_index=True, + axis=1, + ) + result = df.shift(1, axis="columns") + tm.assert_frame_equal(result, expected) + + def test_shift_other_axis_with_freq(self, datetime_frame): + obj = datetime_frame.T + offset = pd.offsets.BDay() + + # GH#47039 + shifted = obj.shift(5, freq=offset, axis=1) + assert len(shifted) == len(obj) + unshifted = shifted.shift(-5, freq=offset, axis=1) + tm.assert_equal(unshifted, obj) + + def test_shift_bool(self): + df = pd.DataFrame({"high": [True, False], "low": [False, False]}) + rs = df.shift(1) + xp = pd.DataFrame( + np.array([[np.nan, np.nan], [True, False]], dtype=object), + columns=["high", "low"], + ) + tm.assert_frame_equal(rs, xp) + + def test_shift_categorical1(self, frame_or_series): + # GH#9416 + obj = frame_or_series(["a", "b", "c", "d"], dtype="category") + + rt = obj.shift(1).shift(-1) + tm.assert_equal(obj.iloc[:-1], rt.dropna()) + + def get_cat_values(ndframe): + # For Series we could just do ._values; for DataFrame + # we may be able to do this if we ever have 2D Categoricals + return ndframe._mgr.blocks[0].values + + cat = get_cat_values(obj) + + sp1 = obj.shift(1) + tm.assert_index_equal(obj.index, sp1.index) + assert np.all(get_cat_values(sp1).codes[:1] == -1) + assert np.all(cat.codes[:-1] == get_cat_values(sp1).codes[1:]) + + sn2 = obj.shift(-2) + tm.assert_index_equal(obj.index, sn2.index) + assert np.all(get_cat_values(sn2).codes[-2:] == -1) + assert np.all(cat.codes[2:] == get_cat_values(sn2).codes[:-2]) + + tm.assert_index_equal(cat.categories, get_cat_values(sp1).categories) + tm.assert_index_equal(cat.categories, get_cat_values(sn2).categories) + + def test_shift_categorical(self): + # GH#9416 + s1 = pd.Series(["a", "b", "c"], dtype="category") + s2 = pd.Series(["A", "B", "C"], dtype="category") + df = pd.DataFrame({"one": s1, "two": s2}) + rs = df.shift(1) + xp = pd.DataFrame({"one": s1.shift(1), "two": s2.shift(1)}) + tm.assert_frame_equal(rs, xp) + + def test_shift_categorical_fill_value(self, frame_or_series): + ts = frame_or_series(["a", "b", "c", "d"], dtype="category") + res = ts.shift(1, fill_value="a") + expected = frame_or_series( + pd.Categorical( + ["a", "a", "b", "c"], categories=["a", "b", "c", "d"], ordered=False + ) + ) + tm.assert_equal(res, expected) + + # check for incorrect fill_value + msg = r"Cannot setitem on a Categorical with a new category \(f\)" + with pytest.raises(TypeError, match=msg): + ts.shift(1, fill_value="f") + + def test_shift_fill_value(self, frame_or_series): + # GH#24128 + dti = pd.date_range("1/1/2000", periods=5, freq="h") + + ts = frame_or_series([1.0, 2.0, 3.0, 4.0, 5.0], index=dti) + exp = frame_or_series([0.0, 1.0, 2.0, 3.0, 4.0], index=dti) + # check that fill value works + result = ts.shift(1, fill_value=0.0) + tm.assert_equal(result, exp) + + exp = frame_or_series([0.0, 0.0, 1.0, 2.0, 3.0], index=dti) + result = ts.shift(2, fill_value=0.0) + tm.assert_equal(result, exp) + + ts = frame_or_series([1, 2, 3]) + res = ts.shift(2, fill_value=0) + assert tm.get_dtype(res) == tm.get_dtype(ts) + + # retain integer dtype + obj = frame_or_series([1, 2, 3, 4, 5], index=dti) + exp = frame_or_series([0, 1, 2, 3, 4], index=dti) + result = obj.shift(1, fill_value=0) + tm.assert_equal(result, exp) + + exp = frame_or_series([0, 0, 1, 2, 3], index=dti) + result = obj.shift(2, fill_value=0) + tm.assert_equal(result, exp) + + def test_shift_empty(self): + # Regression test for GH#8019 + df = pd.DataFrame({"foo": []}) + rs = df.shift(-1) + + tm.assert_frame_equal(df, rs) + + def test_shift_duplicate_columns(self): + # GH#9092; verify that position-based shifting works + # in the presence of duplicate columns + column_lists = [list(range(5)), [1] * 5, [1, 1, 2, 2, 1]] + data = np.random.default_rng(2).standard_normal((20, 5)) + + shifted = [] + for columns in column_lists: + df = pd.DataFrame(data.copy(), columns=columns) + for s in range(5): + df.iloc[:, s] = df.iloc[:, s].shift(s + 1) + df.columns = range(5) + shifted.append(df) + + # sanity check the base case + nulls = shifted[0].isna().sum() + tm.assert_series_equal(nulls, pd.Series(range(1, 6), dtype="int64")) + + # check all answers are the same + tm.assert_frame_equal(shifted[0], shifted[1]) + tm.assert_frame_equal(shifted[0], shifted[2]) + + def test_shift_axis1_multiple_blocks(self): + # GH#35488 + df1 = pd.DataFrame(np.random.default_rng(2).integers(1000, size=(5, 3))) + df2 = pd.DataFrame(np.random.default_rng(2).integers(1000, size=(5, 2))) + df3 = pd.concat([df1, df2], axis=1) + assert len(df3._mgr.blocks) == 2 + + result = df3.shift(2, axis=1) + + expected = df3.take([-1, -1, 0, 1, 2], axis=1) + # Explicit cast to float to avoid implicit cast when setting nan. + # Column names aren't unique, so directly calling `expected.astype` won't work. + expected = expected.pipe( + lambda df: ( + df.set_axis(range(df.shape[1]), axis=1) + .astype({0: "float", 1: "float"}) + .set_axis(df.columns, axis=1) + ) + ) + expected.iloc[:, :2] = np.nan + expected.columns = df3.columns + + tm.assert_frame_equal(result, expected) + + # Case with periods < 0 + # rebuild df3 because `take` call above consolidated + df3 = pd.concat([df1, df2], axis=1) + assert len(df3._mgr.blocks) == 2 + result = df3.shift(-2, axis=1) + + expected = df3.take([2, 3, 4, -1, -1], axis=1) + # Explicit cast to float to avoid implicit cast when setting nan. + # Column names aren't unique, so directly calling `expected.astype` won't work. + expected = expected.pipe( + lambda df: ( + df.set_axis(range(df.shape[1]), axis=1) + .astype({3: "float", 4: "float"}) + .set_axis(df.columns, axis=1) + ) + ) + expected.iloc[:, -2:] = np.nan + expected.columns = df3.columns + + tm.assert_frame_equal(result, expected) + + def test_shift_axis1_multiple_blocks_with_int_fill(self): + # GH#42719 + rng = np.random.default_rng(2) + df1 = pd.DataFrame(rng.integers(1000, size=(5, 3), dtype=int)) + df2 = pd.DataFrame(rng.integers(1000, size=(5, 2), dtype=int)) + df3 = pd.concat([df1.iloc[:4, 1:3], df2.iloc[:4, :]], axis=1) + result = df3.shift(2, axis=1, fill_value=np.int_(0)) + assert len(df3._mgr.blocks) == 2 + + expected = df3.take([-1, -1, 0, 1], axis=1) + expected.iloc[:, :2] = np.int_(0) + expected.columns = df3.columns + + tm.assert_frame_equal(result, expected) + + # Case with periods < 0 + df3 = pd.concat([df1.iloc[:4, 1:3], df2.iloc[:4, :]], axis=1) + result = df3.shift(-2, axis=1, fill_value=np.int_(0)) + assert len(df3._mgr.blocks) == 2 + + expected = df3.take([2, 3, -1, -1], axis=1) + expected.iloc[:, -2:] = np.int_(0) + expected.columns = df3.columns + + tm.assert_frame_equal(result, expected) + + def test_period_index_frame_shift_with_freq(self, frame_or_series): + ps = pd.DataFrame(range(4), index=pd.period_range("2020-01-01", periods=4)) + ps = tm.get_obj(ps, frame_or_series) + + shifted = ps.shift(1, freq="infer") + unshifted = shifted.shift(-1, freq="infer") + tm.assert_equal(unshifted, ps) + + shifted2 = ps.shift(freq="D") + tm.assert_equal(shifted, shifted2) + + shifted3 = ps.shift(freq=pd.offsets.Day()) + tm.assert_equal(shifted, shifted3) + + def test_datetime_frame_shift_with_freq(self, datetime_frame, frame_or_series): + dtobj = tm.get_obj(datetime_frame, frame_or_series) + shifted = dtobj.shift(1, freq="infer") + unshifted = shifted.shift(-1, freq="infer") + tm.assert_equal(dtobj, unshifted) + + shifted2 = dtobj.shift(freq=dtobj.index.freq) + tm.assert_equal(shifted, shifted2) + + inferred_ts = pd.DataFrame( + datetime_frame.values, + pd.Index(np.asarray(datetime_frame.index)), + columns=datetime_frame.columns, + ) + inferred_ts = tm.get_obj(inferred_ts, frame_or_series) + shifted = inferred_ts.shift(1, freq="infer") + expected = dtobj.shift(1, freq="infer") + expected.index = expected.index._with_freq(None) + tm.assert_equal(shifted, expected) + + unshifted = shifted.shift(-1, freq="infer") + tm.assert_equal(unshifted, inferred_ts) + + def test_period_index_frame_shift_with_freq_error(self, frame_or_series): + ps = pd.DataFrame(range(4), index=pd.period_range("2020-01-01", periods=4)) + ps = tm.get_obj(ps, frame_or_series) + msg = "Given freq M does not match PeriodIndex freq D" + with pytest.raises(ValueError, match=msg): + ps.shift(freq="M") + + def test_shift_freq_infer_after_float_to_datetime(self): + # GH#40799 - shift(freq="infer") should work on DatetimeIndex + # created from float seconds via to_datetime(unit="s") + idx = pd.to_datetime( + np.array([f"{x:0.3f}" for x in np.arange(0, 10.1, 0.1)], dtype="float64"), + unit="s", + ) + ser = pd.Series(range(len(idx)), index=idx) + result = ser.shift(1, freq="infer") + expected = ser.shift(1, freq="100ms") + tm.assert_series_equal(result, expected) + + def test_datetime_frame_shift_with_freq_error( + self, datetime_frame, frame_or_series + ): + dtobj = tm.get_obj(datetime_frame, frame_or_series) + no_freq = dtobj.iloc[[0, 5, 7]] + msg = "Freq was not set in the index hence cannot be inferred" + with pytest.raises(ValueError, match=msg): + no_freq.shift(freq="infer") + + def test_shift_dt64values_int_fill_deprecated(self): + # GH#31971 + ser = pd.Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")]) + + with pytest.raises(TypeError, match="value should be a"): + ser.shift(1, fill_value=0) + + df = ser.to_frame() + with pytest.raises(TypeError, match="value should be a"): + df.shift(1, fill_value=0) + + # axis = 1 + df2 = pd.DataFrame({"A": ser, "B": ser}) + df2._consolidate_inplace() + + result = df2.shift(1, axis=1, fill_value=0) + expected = pd.DataFrame({"A": [0, 0], "B": df2["A"]}) + tm.assert_frame_equal(result, expected) + + # same thing but not consolidated; pre-2.0 we got different behavior + df3 = pd.DataFrame({"A": ser}) + df3["B"] = ser + assert len(df3._mgr.blocks) == 2 + result = df3.shift(1, axis=1, fill_value=0) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "as_cat", + [ + pytest.param( + True, + marks=pytest.mark.xfail( + reason="_can_hold_element incorrectly always returns True" + ), + ), + False, + ], + ) + @pytest.mark.parametrize( + "vals", + [ + pd.date_range("2020-01-01", periods=2), + pd.date_range("2020-01-01", periods=2, tz="US/Pacific"), + pd.period_range("2020-01-01", periods=2, freq="D"), + pd.timedelta_range("2020 Days", periods=2, freq="D"), + pd.interval_range(0, 3, periods=2), + pytest.param( + pd.array([1, 2], dtype="Int64"), + marks=pytest.mark.xfail( + reason="_can_hold_element incorrectly always returns True" + ), + ), + pytest.param( + pd.array([1, 2], dtype="Float32"), + marks=pytest.mark.xfail( + reason="_can_hold_element incorrectly always returns True" + ), + ), + ], + ids=lambda x: str(x.dtype), + ) + def test_shift_dt64values_axis1_invalid_fill(self, vals, as_cat): + # GH#44564 + ser = pd.Series(vals) + if as_cat: + ser = ser.astype("category") + + df = pd.DataFrame({"A": ser}) + result = df.shift(-1, axis=1, fill_value="foo") + expected = pd.DataFrame({"A": ["foo", "foo"]}) + tm.assert_frame_equal(result, expected) + + # same thing but multiple blocks + df2 = pd.DataFrame({"A": ser, "B": ser}) + df2._consolidate_inplace() + + result = df2.shift(-1, axis=1, fill_value="foo") + expected = pd.DataFrame({"A": df2["B"], "B": ["foo", "foo"]}) + tm.assert_frame_equal(result, expected) + + # same thing but not consolidated + df3 = pd.DataFrame({"A": ser}) + df3["B"] = ser + assert len(df3._mgr.blocks) == 2 + result = df3.shift(-1, axis=1, fill_value="foo") + tm.assert_frame_equal(result, expected) + + def test_shift_axis1_categorical_columns(self): + # GH#38434 + ci = pd.CategoricalIndex(["a", "b", "c"]) + df = pd.DataFrame( + {"a": [1, 3], "b": [2, 4], "c": [5, 6]}, index=ci[:-1], columns=ci + ) + result = df.shift(axis=1) + + expected = pd.DataFrame( + {"a": [np.nan, np.nan], "b": [1, 3], "c": [2, 4]}, index=ci[:-1], columns=ci + ) + tm.assert_frame_equal(result, expected) + + # periods != 1 + result = df.shift(2, axis=1) + expected = pd.DataFrame( + {"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 3]}, + index=ci[:-1], + columns=ci, + ) + tm.assert_frame_equal(result, expected) + + def test_shift_axis1_many_periods(self): + # GH#44978 periods > len(columns) + df = pd.DataFrame(np.random.default_rng(2).random((5, 3))) + shifted = df.shift(6, axis=1, fill_value=None) + + expected = df * np.nan + tm.assert_frame_equal(shifted, expected) + + shifted2 = df.shift(-6, axis=1, fill_value=None) + tm.assert_frame_equal(shifted2, expected) + + def test_shift_with_offsets_freq(self): + df = pd.DataFrame({"x": [1, 2, 3]}, index=pd.date_range("2000", periods=3)) + shifted = df.shift(freq="1MS") + expected = pd.DataFrame( + {"x": [1, 2, 3]}, + index=pd.date_range(start="02/01/2000", end="02/01/2000", periods=3), + ) + tm.assert_frame_equal(shifted, expected) + + def test_shift_with_iterable_basic_functionality(self): + # GH#44424 + data = {"a": [1, 2, 3], "b": [4, 5, 6]} + shifts = [0, 1, 2] + + df = pd.DataFrame(data) + shifted = df.shift(shifts) + + expected = pd.DataFrame( + { + "a_0": [1, 2, 3], + "b_0": [4, 5, 6], + "a_1": [np.nan, 1.0, 2.0], + "b_1": [np.nan, 4.0, 5.0], + "a_2": [np.nan, np.nan, 1.0], + "b_2": [np.nan, np.nan, 4.0], + } + ) + tm.assert_frame_equal(expected, shifted) + + def test_shift_with_iterable_series(self): + # GH#44424 + data = {"a": [1, 2, 3]} + shifts = [0, 1, 2] + + df = pd.DataFrame(data) + s = df["a"] + tm.assert_frame_equal(s.shift(shifts), df.shift(shifts)) + + def test_shift_with_iterable_series_suffix(self): + # GH#54806 + ser = pd.Series([1, 2, 3], name="a") + result = ser.shift([0, 1], suffix="_suffix") + expected = pd.DataFrame( + {"a_suffix_0": [1, 2, 3], "a_suffix_1": [np.nan, 1.0, 2.0]} + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("periods", [0, 1, -1]) + def test_shift_with_int_periods_series_suffix_raises(self, periods): + # GH#54806 + ser = pd.Series([1, 2, 3], name="a") + msg = "Cannot specify `suffix` if `periods` is an int." + with pytest.raises(ValueError, match=msg): + ser.shift(periods, suffix="_suffix") + + @pytest.mark.parametrize( + "periods", + [np.array([0]), pd.Index([0]), pd.Series([0]), np.array([0, 1])], + ) + def test_shift_with_array_like_periods_series(self, periods): + # GH#68942 an ndarray/Index of shifts returned an unshifted copy for a + # single 0 and raised for more than one; a Series of shifts always raised + df = pd.DataFrame({"a": [1, 2, 3]}) + ser = df["a"] + tm.assert_frame_equal(ser.shift(periods), df.shift(list(periods))) + + def test_shift_with_iterable_freq_and_fill_value(self): + # GH#44424 + df = pd.DataFrame( + np.random.default_rng(2).standard_normal(5), + index=pd.date_range("1/1/2000", periods=5, freq="h"), + ) + + tm.assert_frame_equal( + # rename because shift with an iterable leads to str column names + df.shift([1], fill_value=1).rename(columns=lambda x: int(x[0])), + df.shift(1, fill_value=1), + ) + + tm.assert_frame_equal( + df.shift([1], freq="h").rename(columns=lambda x: int(x[0])), + df.shift(1, freq="h"), + ) + + def test_shift_with_iterable_check_other_arguments(self): + # GH#44424 + data = {"a": [1, 2], "b": [4, 5]} + shifts = [0, 1] + df = pd.DataFrame(data) + + # test suffix + shifted = df[["a"]].shift(shifts, suffix="_suffix") + expected = pd.DataFrame({"a_suffix_0": [1, 2], "a_suffix_1": [np.nan, 1.0]}) + tm.assert_frame_equal(shifted, expected) + + # check bad inputs when doing multiple shifts + msg = "If `periods` contains multiple shifts, `axis` cannot be 1." + with pytest.raises(ValueError, match=msg): + df.shift(shifts, axis=1) + + msg = "Periods must be integer, but s is ." + with pytest.raises(TypeError, match=msg): + df.shift(["s"]) + + msg = "If `periods` is an iterable, it cannot be empty." + with pytest.raises(ValueError, match=msg): + df.shift([]) + + msg = "Cannot specify `suffix` if `periods` is an int." + with pytest.raises(ValueError, match=msg): + df.shift(1, suffix="fails") + + def test_shift_axis_one_empty(self): + # GH#57301 + df = pd.DataFrame() + result = df.shift(1, axis=1) + tm.assert_frame_equal(result, df) + + def test_shift_with_offsets_freq_empty(self): + # GH#60102 + dates = pd.date_range("2020-01-01", periods=3, freq="D") + offset = pd.offsets.Day() + shifted_dates = dates + offset + df = pd.DataFrame(index=dates) + df_shifted = pd.DataFrame(index=shifted_dates) + result = df.shift(freq=offset) + tm.assert_frame_equal(result, df_shifted) + + def test_series_shift_interval_preserves_closed(self): + # GH#60389 + ser = pd.Series( + [pd.Interval(1, 2, closed="right"), pd.Interval(2, 3, closed="right")] + ) + result = ser.shift(1) + expected = pd.Series([np.nan, pd.Interval(1, 2, closed="right")]) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["S1", "V1"]) + def test_series_shift_cannot_hold_na_dtype(self, dtype): + # GH#52373 + ser = pd.Series(np.array([b"a", b"b", b"c"], dtype=dtype)) + + with tm.assert_produces_warning(None): + result = ser.shift(1) + + expected = pd.Series([np.nan, b"a", b"b"], dtype=object) + tm.assert_series_equal(result, expected) + + def test_shift_invalid_fill_value_deprecation(self): + # GH#53802 + df = pd.DataFrame( + { + "a": [1, 2, 3], + "b": [True, False, True], + } + ) + + msg = "shifting with a fill value that cannot" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.shift(1, fill_value="foo") + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df["a"].shift(1, fill_value="foo") + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df["b"].shift(1, fill_value="foo") + + # An incompatible null value + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.shift(1, fill_value=pd.NaT) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df["a"].shift(1, fill_value=pd.NaT) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df["b"].shift(1, fill_value=pd.NaT) + + def test_shift_dt_index_multiple_periods_unsorted(self): + # https://github.com/pandas-dev/pandas/pull/62843 + values = pd.date_range("1/1/2000", periods=4, freq="D") + df = pd.DataFrame({"a": [1, 2]}, index=[values[1], values[0]]) + result = df.shift(periods=[1, 2], freq="D") + expected = pd.DataFrame( + { + "a_1": [1.0, 2.0, np.nan], + "a_2": [2.0, np.nan, 1.0], + }, + index=[values[2], values[1], values[3]], + ) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_size.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_size.py new file mode 100644 index 0000000000000000000000000000000000000000..f6037f52e2cdd2d06aea46276a965cfe2882c55b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_size.py @@ -0,0 +1,21 @@ +import numpy as np +import pytest + +import pandas as pd + + +@pytest.mark.parametrize( + "data, index, expected", + [ + ({"col1": [1], "col2": [3]}, None, 2), + ({}, None, 0), + ({"col1": [1, np.nan], "col2": [3, 4]}, None, 4), + ({"col1": [1, 2], "col2": [3, 4]}, [["a", "b"], [1, 2]], 4), + ({"col1": [1, 2, 3, 4], "col2": [3, 4, 5, 6]}, ["x", "y", "a", "b"], 8), + ], +) +def test_size(data, index, expected): + # GH#52897 + df = pd.DataFrame(data, index=index) + assert df.size == expected + assert isinstance(df.size, int) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_sort_index.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_sort_index.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e56fa0f526b72070423d023997bea3913c1cee --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_sort_index.py @@ -0,0 +1,1124 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameSortIndex: + def test_sort_index_and_reconstruction_doc_example(self): + # doc example + df = pd.DataFrame( + {"value": [1, 2, 3, 4]}, + index=pd.MultiIndex( + levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] + ), + ) + assert df.index._is_lexsorted() + assert not df.index.is_monotonic_increasing + + # sort it + expected = pd.DataFrame( + {"value": [2, 1, 4, 3]}, + index=pd.MultiIndex( + levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] + ), + ) + result = df.sort_index() + assert result.index.is_monotonic_increasing + tm.assert_frame_equal(result, expected) + + # reconstruct + result = df.sort_index().copy() + result.index = result.index._sort_levels_monotonic() + assert result.index.is_monotonic_increasing + tm.assert_frame_equal(result, expected) + + def test_sort_index_non_existent_label_multiindex(self): + # GH#12261 + df = pd.DataFrame(0, columns=[], index=pd.MultiIndex.from_product([[], []])) + msg = "Setting a new row on a DataFrame with a MultiIndex" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.loc["b", "2"] = 1 + df.loc["a", "3"] = 1 + result = df.sort_index().index.is_monotonic_increasing + assert result is True + + def test_sort_index_reorder_on_ops(self): + # GH#15687 + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((8, 2)), + index=pd.MultiIndex.from_product( + [["a", "b"], ["big", "small"], ["red", "blu"]], + names=["letter", "size", "color"], + ), + columns=["near", "far"], + ) + df = df.sort_index() + + def my_func(group): + group.index = ["newz", "newa"] + return group + + result = df.groupby(level=["letter", "size"]).apply(my_func).sort_index() + expected = pd.MultiIndex.from_product( + [["a", "b"], ["big", "small"], ["newa", "newz"]], + names=["letter", "size", None], + ) + + tm.assert_index_equal(result.index, expected) + + def test_sort_index_nan_multiindex(self): + # GH#14784 + # incorrect sorting w.r.t. nans + tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]] + mi = pd.MultiIndex.from_tuples(tuples) + + df = pd.DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list("ABCD")) + s = pd.Series(np.arange(4), index=mi) + + df2 = pd.DataFrame( + { + "date": pd.DatetimeIndex( + [ + "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, + np.nan, + 280, + 259, + np.nan, + 623, + 90, + 312, + np.nan, + 301, + 359, + 801, + ], + "cost": [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12], + } + ).set_index(["date", "user_id"]) + + # sorting frame, default nan position is last + result = df.sort_index() + expected = df.iloc[[3, 0, 2, 1], :] + tm.assert_frame_equal(result, expected) + + # sorting frame, nan position last + result = df.sort_index(na_position="last") + expected = df.iloc[[3, 0, 2, 1], :] + tm.assert_frame_equal(result, expected) + + # sorting frame, nan position first + result = df.sort_index(na_position="first") + expected = df.iloc[[1, 2, 3, 0], :] + tm.assert_frame_equal(result, expected) + + # sorting frame with removed rows + result = df2.dropna().sort_index() + expected = df2.sort_index().dropna() + tm.assert_frame_equal(result, expected) + + # sorting series, default nan position is last + result = s.sort_index() + expected = s.iloc[[3, 0, 2, 1]] + tm.assert_series_equal(result, expected) + + # sorting series, nan position last + result = s.sort_index(na_position="last") + expected = s.iloc[[3, 0, 2, 1]] + tm.assert_series_equal(result, expected) + + # sorting series, nan position first + result = s.sort_index(na_position="first") + expected = s.iloc[[1, 2, 3, 0]] + tm.assert_series_equal(result, expected) + + def test_sort_index_nan(self): + # GH#3917 + + # Test DataFrame with nan label + df = pd.DataFrame( + {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]}, + index=[1, 2, 3, 4, 5, 6, np.nan], + ) + + # NaN label, ascending=True, na_position='last' + sorted_df = df.sort_index(kind="quicksort", ascending=True, na_position="last") + expected = pd.DataFrame( + {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]}, + index=[1, 2, 3, 4, 5, 6, np.nan], + ) + tm.assert_frame_equal(sorted_df, expected) + + # NaN label, ascending=True, na_position='first' + sorted_df = df.sort_index(na_position="first") + expected = pd.DataFrame( + {"A": [4, 1, 2, np.nan, 1, 6, 8], "B": [5, 9, np.nan, 5, 2, 5, 4]}, + index=[np.nan, 1, 2, 3, 4, 5, 6], + ) + tm.assert_frame_equal(sorted_df, expected) + + # NaN label, ascending=False, na_position='last' + sorted_df = df.sort_index(kind="quicksort", ascending=False) + expected = pd.DataFrame( + {"A": [8, 6, 1, np.nan, 2, 1, 4], "B": [4, 5, 2, 5, np.nan, 9, 5]}, + index=[6, 5, 4, 3, 2, 1, np.nan], + ) + tm.assert_frame_equal(sorted_df, expected) + + # NaN label, ascending=False, na_position='first' + sorted_df = df.sort_index( + kind="quicksort", ascending=False, na_position="first" + ) + expected = pd.DataFrame( + {"A": [4, 8, 6, 1, np.nan, 2, 1], "B": [5, 4, 5, 2, 5, np.nan, 9]}, + index=[np.nan, 6, 5, 4, 3, 2, 1], + ) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_index_multi_index(self): + # GH#25775, testing that sorting by index works with a multi-index. + df = pd.DataFrame( + {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")} + ) + result = df.set_index(list("abc")).sort_index(level=list("ba")) + + expected = pd.DataFrame( + {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")} + ) + expected = expected.set_index(list("abc")) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_index") + def test_sort_index_inplace(self): + frame = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), + index=[1, 2, 3, 4], + columns=["A", "B", "C", "D"], + ) + + # axis=0 + unordered = frame.loc[[3, 2, 4, 1]] + a_values = unordered["A"] + df = unordered.copy() + return_value = df.sort_index(inplace=True) + assert return_value is None + expected = frame + tm.assert_frame_equal(df, expected) + # GH 44153 related + # Used to be a_id != id(df["A"]), but flaky in the CI + assert a_values is not df["A"] + + df = unordered.copy() + return_value = df.sort_index(ascending=False, inplace=True) + assert return_value is None + expected = frame[::-1] + tm.assert_frame_equal(df, expected) + + # axis=1 + unordered = frame.loc[:, ["D", "B", "C", "A"]] + df = unordered.copy() + return_value = df.sort_index(axis=1, inplace=True) + assert return_value is None + expected = frame + tm.assert_frame_equal(df, expected) + + df = unordered.copy() + return_value = df.sort_index(axis=1, ascending=False, inplace=True) + assert return_value is None + expected = frame.iloc[:, ::-1] + tm.assert_frame_equal(df, expected) + + def test_sort_index_different_sortorder(self): + A = np.arange(20).repeat(5) + B = np.tile(np.arange(5), 20) + + indexer = np.random.default_rng(2).permutation(100) + A = A.take(indexer) + B = B.take(indexer) + + df = pd.DataFrame( + {"A": A, "B": B, "C": np.random.default_rng(2).standard_normal(100)} + ) + + ex_indexer = np.lexsort((df.B.max() - df.B, df.A)) + expected = df.take(ex_indexer) + + # test with multiindex, too + idf = df.set_index(["A", "B"]) + + result = idf.sort_index(ascending=[1, 0]) + expected = idf.take(ex_indexer) + tm.assert_frame_equal(result, expected) + + # also, Series! + result = idf["C"].sort_index(ascending=[1, 0]) + tm.assert_series_equal(result, expected["C"]) + + def test_sort_index_level(self): + mi = pd.MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC")) + df = pd.DataFrame([[1, 2], [3, 4]], mi) + + result = df.sort_index(level="A", sort_remaining=False) + expected = df + tm.assert_frame_equal(result, expected) + + result = df.sort_index(level=["A", "B"], sort_remaining=False) + expected = df + tm.assert_frame_equal(result, expected) + + # Error thrown by sort_index when + # first index is sorted last (GH#26053) + result = df.sort_index(level=["C", "B", "A"]) + expected = df.iloc[[1, 0]] + tm.assert_frame_equal(result, expected) + + result = df.sort_index(level=["B", "C", "A"]) + expected = df.iloc[[1, 0]] + tm.assert_frame_equal(result, expected) + + result = df.sort_index(level=["C", "A"]) + expected = df.iloc[[1, 0]] + tm.assert_frame_equal(result, expected) + + def test_sort_index_categorical_index(self): + df = pd.DataFrame( + { + "A": np.arange(6, dtype="int64"), + "B": pd.Series(list("aabbca")).astype(pd.CategoricalDtype(list("cab"))), + } + ).set_index("B") + + result = df.sort_index() + expected = df.iloc[[4, 0, 1, 5, 2, 3]] + tm.assert_frame_equal(result, expected) + + result = df.sort_index(ascending=False) + expected = df.iloc[[2, 3, 0, 1, 5, 4]] + tm.assert_frame_equal(result, expected) + + def test_sort_index(self): + # GH#13496 + + frame = pd.DataFrame( + np.arange(16).reshape(4, 4), + index=[1, 2, 3, 4], + columns=["A", "B", "C", "D"], + ) + + # axis=0 : sort rows by index labels + unordered = frame.loc[[3, 2, 4, 1]] + result = unordered.sort_index(axis=0) + expected = frame + tm.assert_frame_equal(result, expected) + + result = unordered.sort_index(ascending=False) + expected = frame[::-1] + tm.assert_frame_equal(result, expected) + + # axis=1 : sort columns by column names + unordered = frame.iloc[:, [2, 1, 3, 0]] + result = unordered.sort_index(axis=1) + tm.assert_frame_equal(result, frame) + + result = unordered.sort_index(axis=1, ascending=False) + expected = frame.iloc[:, ::-1] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("level", ["A", 0]) # GH#21052 + def test_sort_index_multiindex(self, level): + # GH#13496 + + # sort rows by specified level of multi-index + mi = pd.MultiIndex.from_tuples( + [[2, 1, 3], [2, 1, 2], [1, 1, 1]], names=list("ABC") + ) + df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], index=mi) + + expected_mi = pd.MultiIndex.from_tuples( + [[1, 1, 1], [2, 1, 2], [2, 1, 3]], names=list("ABC") + ) + expected = pd.DataFrame([[5, 6], [3, 4], [1, 2]], index=expected_mi) + result = df.sort_index(level=level) + tm.assert_frame_equal(result, expected) + + # sort_remaining=False + expected_mi = pd.MultiIndex.from_tuples( + [[1, 1, 1], [2, 1, 3], [2, 1, 2]], names=list("ABC") + ) + expected = pd.DataFrame([[5, 6], [1, 2], [3, 4]], index=expected_mi) + result = df.sort_index(level=level, sort_remaining=False) + tm.assert_frame_equal(result, expected) + + def test_sort_index_intervalindex(self): + # this is a de-facto sort via unstack + # confirming that we sort in the order of the bins + y = pd.Series(np.random.default_rng(2).standard_normal(100)) + x1 = pd.Series(np.sign(np.random.default_rng(2).standard_normal(100))) + x2 = pd.cut( + pd.Series(np.random.default_rng(2).standard_normal(100)), + bins=[-3, -0.5, 0, 0.5, 3], + ) + model = pd.concat([y, x1, x2], axis=1, keys=["Y", "X1", "X2"]) + + result = model.groupby(["X1", "X2"], observed=True).mean().unstack() + expected = pd.IntervalIndex.from_tuples( + [(-3.0, -0.5), (-0.5, 0.0), (0.0, 0.5), (0.5, 3.0)], closed="right" + ) + result = result.columns.levels[1].categories + tm.assert_index_equal(result, expected) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_index") + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize( + "original_dict, sorted_dict, ascending, ignore_index, output_index", + [ + ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, True, [0, 1, 2]), + ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, True, [0, 1, 2]), + ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, False, [5, 3, 2]), + ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, False, [2, 3, 5]), + ], + ) + def test_sort_index_ignore_index( + self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index + ): + # GH 30114 + original_index = [2, 5, 3] + df = pd.DataFrame(original_dict, index=original_index) + expected_df = pd.DataFrame(sorted_dict, index=output_index) + kwargs = { + "ascending": ascending, + "ignore_index": ignore_index, + "inplace": inplace, + } + + if inplace: + result_df = df.copy() + result_df.sort_index(**kwargs) + else: + result_df = df.sort_index(**kwargs) + + tm.assert_frame_equal(result_df, expected_df) + tm.assert_frame_equal(df, pd.DataFrame(original_dict, index=original_index)) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_index") + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize("ignore_index", [True, False]) + def test_respect_ignore_index(self, inplace, ignore_index): + # GH 43591 + df = pd.DataFrame({"a": [1, 2, 3]}, index=pd.RangeIndex(4, -1, -2)) + result = df.sort_index( + ascending=False, ignore_index=ignore_index, inplace=inplace + ) + + if inplace: + result = df + if ignore_index: + expected = pd.DataFrame({"a": [1, 2, 3]}) + else: + expected = pd.DataFrame({"a": [1, 2, 3]}, index=pd.RangeIndex(4, -1, -2)) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_index") + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize( + "original_dict, sorted_dict, ascending, ignore_index, output_index", + [ + ( + {"M1": [1, 2], "M2": [3, 4]}, + {"M1": [1, 2], "M2": [3, 4]}, + True, + True, + [0, 1], + ), + ( + {"M1": [1, 2], "M2": [3, 4]}, + {"M1": [2, 1], "M2": [4, 3]}, + False, + True, + [0, 1], + ), + ( + {"M1": [1, 2], "M2": [3, 4]}, + {"M1": [1, 2], "M2": [3, 4]}, + True, + False, + pd.MultiIndex.from_tuples([(2, 1), (3, 4)], names=list("AB")), + ), + ( + {"M1": [1, 2], "M2": [3, 4]}, + {"M1": [2, 1], "M2": [4, 3]}, + False, + False, + pd.MultiIndex.from_tuples([(3, 4), (2, 1)], names=list("AB")), + ), + ], + ) + def test_sort_index_ignore_index_multi_index( + self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index + ): + # GH 30114, this is to test ignore_index on MultiIndex of index + mi = pd.MultiIndex.from_tuples([(2, 1), (3, 4)], names=list("AB")) + df = pd.DataFrame(original_dict, index=mi) + expected_df = pd.DataFrame(sorted_dict, index=output_index) + + kwargs = { + "ascending": ascending, + "ignore_index": ignore_index, + "inplace": inplace, + } + + if inplace: + result_df = df.copy() + result_df.sort_index(**kwargs) + else: + result_df = df.sort_index(**kwargs) + + tm.assert_frame_equal(result_df, expected_df) + tm.assert_frame_equal(df, pd.DataFrame(original_dict, index=mi)) + + def test_sort_index_categorical_multiindex(self): + # GH#15058 + df = pd.DataFrame( + { + "a": range(6), + "l1": pd.Categorical( + ["a", "a", "b", "b", "c", "c"], + categories=["c", "a", "b"], + ordered=True, + ), + "l2": [0, 1, 0, 1, 0, 1], + } + ) + result = df.set_index(["l1", "l2"]).sort_index() + expected = pd.DataFrame( + [4, 5, 0, 1, 2, 3], + columns=["a"], + index=pd.MultiIndex( + levels=[ + pd.CategoricalIndex( + ["c", "a", "b"], + categories=["c", "a", "b"], + ordered=True, + name="l1", + dtype="category", + ), + [0, 1], + ], + codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], + names=["l1", "l2"], + ), + ) + tm.assert_frame_equal(result, expected) + + def test_sort_index_and_reconstruction(self): + # GH#15622 + # lexsortedness should be identical + # across MultiIndex construction methods + + df = pd.DataFrame([[1, 1], [2, 2]], index=list("ab")) + expected = pd.DataFrame( + [[1, 1], [2, 2], [1, 1], [2, 2]], + index=pd.MultiIndex.from_tuples( + [(0.5, "a"), (0.5, "b"), (0.8, "a"), (0.8, "b")] + ), + ) + assert expected.index._is_lexsorted() + + result = pd.DataFrame( + [[1, 1], [2, 2], [1, 1], [2, 2]], + index=pd.MultiIndex.from_product([[0.5, 0.8], list("ab")]), + ) + result = result.sort_index() + assert result.index.is_monotonic_increasing + + tm.assert_frame_equal(result, expected) + + result = pd.DataFrame( + [[1, 1], [2, 2], [1, 1], [2, 2]], + index=pd.MultiIndex( + levels=[[0.5, 0.8], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] + ), + ) + result = result.sort_index() + assert result.index._is_lexsorted() + + tm.assert_frame_equal(result, expected) + + concatted = pd.concat([df, df], keys=[0.8, 0.5]) + result = concatted.sort_index() + + assert result.index.is_monotonic_increasing + + tm.assert_frame_equal(result, expected) + + # GH#14015 + df = pd.DataFrame( + [[1, 2], [6, 7]], + columns=pd.MultiIndex.from_tuples( + [(0, "20160811 12:00:00"), (0, "20160809 12:00:00")], + names=["l1", "Date"], + ), + ) + + df.columns = df.columns.set_levels( + pd.to_datetime(df.columns.levels[1]), level=1 + ) + assert not df.columns.is_monotonic_increasing + result = df.sort_index(axis=1) + assert result.columns.is_monotonic_increasing + result = df.sort_index(axis=1, level=1) + assert result.columns.is_monotonic_increasing + + # TODO: better name, de-duplicate with test_sort_index_level above + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_index") + def test_sort_index_level2(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + df = frame.copy() + df.index = np.arange(len(df)) + + # axis=1 + + # series + a_sorted = frame["A"].sort_index(level=0) + + # preserve names + assert a_sorted.index.names == frame.index.names + + # inplace + rs = frame.copy() + return_value = rs.sort_index(level=0, inplace=True) + assert return_value is None + tm.assert_frame_equal(rs, frame.sort_index(level=0)) + + def test_sort_index_level_large_cardinality(self): + # GH#2684 (int64) + index = pd.MultiIndex.from_arrays([np.arange(4000)] * 3) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal(4000).astype("int64"), index=index + ) + + # it works! + result = df.sort_index(level=0) + assert result.index._lexsort_depth == 3 + + # GH#2684 (int32) + index = pd.MultiIndex.from_arrays([np.arange(4000)] * 3) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal(4000).astype("int32"), index=index + ) + + # it works! + result = df.sort_index(level=0) + assert (result.dtypes.values == df.dtypes.values).all() + assert result.index._lexsort_depth == 3 + + def test_sort_index_level_by_name(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + frame.index.names = ["first", "second"] + result = frame.sort_index(level="second") + expected = frame.sort_index(level=1) + tm.assert_frame_equal(result, expected) + + def test_sort_index_level_mixed(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + sorted_before = frame.sort_index(level=1) + + df = frame.copy() + df["foo"] = "bar" + sorted_after = df.sort_index(level=1) + tm.assert_frame_equal(sorted_before, sorted_after.drop(["foo"], axis=1)) + + dft = frame.T + sorted_before = dft.sort_index(level=1, axis=1) + dft["foo", "three"] = "bar" + + sorted_after = dft.sort_index(level=1, axis=1) + tm.assert_frame_equal( + sorted_before.drop([("foo", "three")], axis=1), + sorted_after.drop([("foo", "three")], axis=1), + ) + + def test_sort_index_preserve_levels(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + result = frame.sort_index() + assert result.index.names == frame.index.names + + @pytest.mark.parametrize( + "gen,extra", + [ + ([1.0, 3.0, 2.0, 5.0], 4.0), + ([1, 3, 2, 5], 4), + ( + [ + pd.Timestamp("20130101"), + pd.Timestamp("20130103"), + pd.Timestamp("20130102"), + pd.Timestamp("20130105"), + ], + pd.Timestamp("20130104"), + ), + (["1one", "3one", "2one", "5one"], "4one"), + ], + ) + def test_sort_index_multilevel_repr_8017(self, gen, extra): + data = np.random.default_rng(2).standard_normal((3, 4)) + + columns = pd.MultiIndex.from_tuples([("red", i) for i in gen]) + df = pd.DataFrame(data, index=list("def"), columns=columns) + df2 = pd.concat( + [ + df, + pd.DataFrame( + "world", + index=list("def"), + columns=pd.MultiIndex.from_tuples([("red", extra)]), + ), + ], + axis=1, + ) + + # check that the repr is good + # make sure that we have a correct sparsified repr + # e.g. only 1 header of read + assert str(df2).splitlines()[0].split() == ["red"] + + # GH 8017 + # sorting fails after columns added + + # construct single-dtype then sort + result = df.copy().sort_index(axis=1) + expected = df.iloc[:, [0, 2, 1, 3]] + tm.assert_frame_equal(result, expected) + + result = df2.sort_index(axis=1) + expected = df2.iloc[:, [0, 2, 1, 4, 3]] + tm.assert_frame_equal(result, expected) + + # setitem then sort + result = df.copy() + result[("red", extra)] = "world" + + result = result.sort_index(axis=1) + tm.assert_frame_equal(result, expected, check_freq=False) + + @pytest.mark.parametrize( + "categories", + [ + pytest.param(["a", "b", "c"], id="str"), + pytest.param( + [pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(2, 3)], + id="pd.Interval", + ), + ], + ) + def test_sort_index_with_categories(self, categories): + # GH#23452 + df = pd.DataFrame( + {"foo": range(len(categories))}, + index=pd.CategoricalIndex( + data=categories, categories=categories, ordered=True + ), + ) + df.index = df.index.reorder_categories(df.index.categories[::-1]) + result = df.sort_index() + expected = pd.DataFrame( + {"foo": reversed(range(len(categories)))}, + index=pd.CategoricalIndex( + data=categories[::-1], categories=categories[::-1], ordered=True + ), + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "ascending", + [ + None, + [True, None], + [False, "True"], + ], + ) + def test_sort_index_ascending_bad_value_raises(self, ascending): + # GH 39434 + df = pd.DataFrame(np.arange(64)) + length = len(df.index) + df.index = [(i - length / 2) % length for i in range(length)] + match = 'For argument "ascending" expected type bool' + with pytest.raises(ValueError, match=match): + df.sort_index(axis=0, ascending=ascending, na_position="first") + + @pytest.mark.parametrize( + "ascending", + [(True, False), [True, False]], + ) + def test_sort_index_ascending_tuple(self, ascending): + df = pd.DataFrame( + { + "legs": [4, 2, 4, 2, 2], + }, + index=pd.MultiIndex.from_tuples( + [ + ("mammal", "dog"), + ("bird", "duck"), + ("mammal", "horse"), + ("bird", "penguin"), + ("mammal", "kangaroo"), + ], + names=["class", "animal"], + ), + ) + + # parameter `ascending`` is a tuple + result = df.sort_index(level=(0, 1), ascending=ascending) + + expected = pd.DataFrame( + { + "legs": [2, 2, 2, 4, 4], + }, + index=pd.MultiIndex.from_tuples( + [ + ("bird", "penguin"), + ("bird", "duck"), + ("mammal", "kangaroo"), + ("mammal", "horse"), + ("mammal", "dog"), + ], + names=["class", "animal"], + ), + ) + + tm.assert_frame_equal(result, expected) + + def test_sort_index_level_on_range_index(self): + # GH#64383: sort_index with level= on a RangeIndex raised AssertionError + df = pd.DataFrame({"a": [1, 2, 3]}) + df.index.names = ["foo"] + result = df.sort_index(level="foo") + tm.assert_frame_equal(result, df) + + def test_sort_index_level_monotonic_no_copy(self): + # GH#64883: sort_index(level=...) on a monotonic non-MultiIndex + # should short-circuit and not copy data blocks + df = pd.DataFrame( + {"a": np.arange(5, dtype=np.float64)}, index=pd.Index(range(5)) + ) + df.index.name = "foo" + result = df.sort_index(level="foo") + tm.assert_frame_equal(result, df) + assert np.shares_memory(result["a"].values, df["a"].values) + + # descending on a decreasing index also short-circuits + df2 = pd.DataFrame( + {"a": np.arange(5, dtype=np.float64)}, + index=pd.Index([5, 4, 3, 2, 1], name="foo"), + ) + result2 = df2.sort_index(level="foo", ascending=False) + tm.assert_frame_equal(result2, df2) + assert np.shares_memory(result2["a"].values, df2["a"].values) + + +class TestDataFrameSortIndexKey: + def test_sort_multi_index_key(self): + # GH 25775, testing that sorting by index works with a multi-index. + df = pd.DataFrame( + {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")} + ).set_index(list("abc")) + + result = df.sort_index(level=list("ac"), key=lambda x: x) + + expected = pd.DataFrame( + {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")} + ).set_index(list("abc")) + tm.assert_frame_equal(result, expected) + + result = df.sort_index(level=list("ac"), key=lambda x: -x) + expected = pd.DataFrame( + {"a": [3, 2, 1], "b": [0, 0, 0], "c": [0, 2, 1], "d": list("acb")} + ).set_index(list("abc")) + + tm.assert_frame_equal(result, expected) + + def test_sort_index_key(self): # issue 27237 + df = pd.DataFrame(np.arange(6, dtype="int64"), index=list("aaBBca")) + + result = df.sort_index() + expected = df.iloc[[2, 3, 0, 1, 5, 4]] + tm.assert_frame_equal(result, expected) + + result = df.sort_index(key=lambda x: x.str.lower()) + expected = df.iloc[[0, 1, 5, 2, 3, 4]] + tm.assert_frame_equal(result, expected) + + result = df.sort_index(key=lambda x: x.str.lower(), ascending=False) + expected = df.iloc[[4, 2, 3, 0, 1, 5]] + tm.assert_frame_equal(result, expected) + + def test_sort_index_key_int(self): + df = pd.DataFrame( + np.arange(6, dtype="int64"), index=np.arange(6, dtype="int64") + ) + + result = df.sort_index() + tm.assert_frame_equal(result, df) + + result = df.sort_index(key=lambda x: -x) + expected = df.sort_index(ascending=False) + tm.assert_frame_equal(result, expected) + + result = df.sort_index(key=lambda x: 2 * x) + tm.assert_frame_equal(result, df) + + def test_sort_multi_index_key_str(self): + # GH 25775, testing that sorting by index works with a multi-index. + df = pd.DataFrame( + {"a": ["B", "a", "C"], "b": [0, 1, 0], "c": list("abc"), "d": [0, 1, 2]} + ).set_index(list("abc")) + + result = df.sort_index(level="a", key=lambda x: x.str.lower()) + + expected = pd.DataFrame( + {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]} + ).set_index(list("abc")) + tm.assert_frame_equal(result, expected) + + result = df.sort_index( + level=list("abc"), # can refer to names + key=lambda x: x.str.lower() if x.name in ["a", "c"] else -x, + ) + + expected = pd.DataFrame( + {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]} + ).set_index(list("abc")) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("axis", [0, 1]) + def test_sort_multi_index_key_level_name(self, axis): + # GH#62361 + mi = pd.MultiIndex.from_product([["a"], ["top10", "top2"]], names=["A", "B"]) + df = pd.DataFrame([[1, 2], [3, 4]], index=mi, columns=mi) + + result = df.sort_index( + axis=axis, level="B", key=lambda x: x.str.len().to_numpy() + ) + + expected = df.iloc[[1, 0]] if axis == 0 else df.iloc[:, [1, 0]] + tm.assert_frame_equal(result, expected) + + def test_changes_length_raises(self): + df = pd.DataFrame({"A": [1, 2, 3]}) + with pytest.raises(ValueError, match="change the shape"): + df.sort_index(key=lambda x: x[:1]) + + def test_sort_index_multiindex_sparse_column(self): + # GH 29735, testing that sort_index on a multiindexed frame with sparse + # columns fills with 0. + expected = pd.DataFrame( + { + i: pd.array([0.0, 0.0, 0.0, 0.0], dtype=pd.SparseDtype("float64", 0.0)) + for i in range(4) + }, + index=pd.MultiIndex.from_product([[1, 2], [1, 2]]), + ) + + result = expected.sort_index(level=0) + + tm.assert_frame_equal(result, expected) + + def test_sort_index_na_position(self): + # GH#51612 + df = pd.DataFrame([1, 2], index=pd.MultiIndex.from_tuples([(1, 1), (1, pd.NA)])) + expected = df.copy() + result = df.sort_index(level=[0, 1], na_position="last") + tm.assert_frame_equal(result, expected) + + def test_sort_index_multiindex_sort_remaining(self, ascending): + # GH #24247 + df = pd.DataFrame( + {"A": [1, 2, 3, 4, 5], "B": [10, 20, 30, 40, 50]}, + index=pd.MultiIndex.from_tuples( + [("a", "x"), ("a", "y"), ("b", "x"), ("b", "y"), ("c", "x")] + ), + ) + + result = df.sort_index(level=1, sort_remaining=False, ascending=ascending) + + if ascending: + expected = pd.DataFrame( + {"A": [1, 3, 5, 2, 4], "B": [10, 30, 50, 20, 40]}, + index=pd.MultiIndex.from_tuples( + [("a", "x"), ("b", "x"), ("c", "x"), ("a", "y"), ("b", "y")] + ), + ) + else: + expected = pd.DataFrame( + {"A": [2, 4, 1, 3, 5], "B": [20, 40, 10, 30, 50]}, + index=pd.MultiIndex.from_tuples( + [("a", "y"), ("b", "y"), ("a", "x"), ("b", "x"), ("c", "x")] + ), + ) + + tm.assert_frame_equal(result, expected) + + +def test_sort_index_with_sliced_multiindex(): + # GH 55379 + mi = pd.MultiIndex.from_tuples( + [ + ("a", "10"), + ("a", "18"), + ("a", "25"), + ("b", "16"), + ("b", "26"), + ("a", "45"), + ("b", "28"), + ("a", "5"), + ("a", "50"), + ("a", "51"), + ("b", "4"), + ], + names=["group", "str"], + ) + + df = pd.DataFrame({"x": range(len(mi))}, index=mi) + result = df.iloc[0:6].sort_index() + + expected = pd.DataFrame( + {"x": [0, 1, 2, 5, 3, 4]}, + index=pd.MultiIndex.from_tuples( + [ + ("a", "10"), + ("a", "18"), + ("a", "25"), + ("a", "45"), + ("b", "16"), + ("b", "26"), + ], + names=["group", "str"], + ), + ) + tm.assert_frame_equal(result, expected) + + +def test_axis_columns_ignore_index(): + # GH 56478 + df = pd.DataFrame([[1, 2]], columns=["d", "c"]) + result = df.sort_index(axis="columns", ignore_index=True) + expected = pd.DataFrame([[2, 1]]) + tm.assert_frame_equal(result, expected) + + +def test_axis_columns_ignore_index_ascending_false(): + # GH 57293 + df = pd.DataFrame( + { + "b": [1.0, 3.0, np.nan], + "a": [1, 4, 3], + 1: ["a", "b", "c"], + "e": [3, 1, 4], + "d": [1, 2, 8], + } + ).set_index(["b", "a", 1]) + result = df.sort_index(axis="columns", ignore_index=True, ascending=False) + expected = df.copy() + expected.columns = pd.RangeIndex(2) + tm.assert_frame_equal(result, expected) + + +def test_sort_index_stable_sort(): + # GH 57151 + df = pd.DataFrame( + data=[ + (pd.Timestamp("2024-01-30 13:00:00"), 13.0), + (pd.Timestamp("2024-01-30 13:00:00"), 13.1), + (pd.Timestamp("2024-01-30 12:00:00"), 12.0), + (pd.Timestamp("2024-01-30 12:00:00"), 12.1), + ], + columns=["dt", "value"], + ).set_index(["dt"]) + result = df.sort_index(level="dt", kind="stable") + expected = pd.DataFrame( + data=[ + (pd.Timestamp("2024-01-30 12:00:00"), 12.0), + (pd.Timestamp("2024-01-30 12:00:00"), 12.1), + (pd.Timestamp("2024-01-30 13:00:00"), 13.0), + (pd.Timestamp("2024-01-30 13:00:00"), 13.1), + ], + columns=["dt", "value"], + ).set_index(["dt"]) + tm.assert_frame_equal(result, expected) + + +def test_sort_index_multiindex_reordered_level_keeps_nan(): + # GH#25818 sorting a MultiIndex whose level values were reordered must not + # fill a missing (NaN) label with an arbitrary category from that level + mi = pd.MultiIndex.from_tuples( + [["A0", "B0"], ["A0", "B1"], ["A1", "B0"], ["A1", "B1"], ["A3", np.nan]], + names=["ia", "ib"], + ) + df = pd.DataFrame(np.arange(10).reshape(5, 2), index=mi, columns=["bar", "foo"]) + df.index = df.index.set_levels(["B1", "B0"], level=1) + result = df.sort_index() + a3_ib = [tup[1] for tup in result.index if tup[0] == "A3"] + assert len(a3_ib) == 1 and pd.isna(a3_ib[0]) + + +def test_sort_index_axis1_multiindex_reordered_level_keeps_nan(): + # GH#25818 the same NaN-preservation must hold when sorting a columns + # MultiIndex that carries NaN codes (axis=1); the NaN labels were filled + # with a real category (4.0) instead of being kept + idx = pd.MultiIndex( + levels=[["a", "b", "c"], [16.0, 32.0, 4.0]], + codes=[[0, 1, 2, 2], [-1, -1, 1, 1]], + ) + df = pd.DataFrame(np.arange(16).reshape(4, 4), columns=idx) + result = df.sort_index(axis=1) + assert sum(pd.isna(tup[1]) for tup in result.columns) == 2 + + +def test_sort_index_inplace_depr(): + msg = "The inplace keyword in DataFrame.sort_index is deprecated" + + df = pd.DataFrame({"a": [3, 1, 2]}, index=[2, 0, 1]) + df_orig = df.copy() + expected = pd.DataFrame({"a": [1, 2, 3]}, index=[0, 1, 2]) + + # does not use keyword, no warning + with tm.assert_produces_warning(False): + result = df.sort_index() + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to false, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.sort_index(inplace=False) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to true, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.sort_index(inplace=True) + tm.assert_frame_equal(df, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_sort_values.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_sort_values.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2ec4b9b0242dd4bf39db4cdb80d69c496fa7e0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_sort_values.py @@ -0,0 +1,948 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameSortValues: + @pytest.mark.parametrize("dtype", [np.uint8, bool]) + def test_sort_values_sparse_no_warning(self, dtype): + # GH#45618 + ser = pd.Series(pd.Categorical(["a", "b", "a"], categories=["a", "b", "c"])) + df = pd.get_dummies(ser, dtype=dtype, sparse=True) + + with tm.assert_produces_warning(None): + # No warnings about constructing Index from SparseArray + df.sort_values(by=df.columns.tolist()) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_values") + def test_sort_values(self): + frame = pd.DataFrame( + [[1, 1, 2], [3, 1, 0], [4, 5, 6]], index=[1, 2, 3], columns=list("ABC") + ) + + # by column (axis=0) + sorted_df = frame.sort_values(by="A") + indexer = frame["A"].argsort().values + expected = frame.loc[frame.index[indexer]] + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by="A", ascending=False) + indexer = indexer[::-1] + expected = frame.loc[frame.index[indexer]] + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by="A", ascending=False) + tm.assert_frame_equal(sorted_df, expected) + + # GH4839 + sorted_df = frame.sort_values(by=["A"], ascending=[False]) + tm.assert_frame_equal(sorted_df, expected) + + # multiple bys + sorted_df = frame.sort_values(by=["B", "C"]) + expected = frame.loc[[2, 1, 3]] + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=["B", "C"], ascending=False) + tm.assert_frame_equal(sorted_df, expected[::-1]) + + sorted_df = frame.sort_values(by=["B", "A"], ascending=[True, False]) + tm.assert_frame_equal(sorted_df, expected) + + msg = "No axis named 2 for object type DataFrame" + with pytest.raises(ValueError, match=msg): + frame.sort_values(by=["A", "B"], axis=2, inplace=True) + + # by row (axis=1): GH#10806 + sorted_df = frame.sort_values(by=3, axis=1) + expected = frame + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=3, axis=1, ascending=False) + expected = frame.reindex(columns=["C", "B", "A"]) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=[1, 2], axis="columns") + expected = frame.reindex(columns=["B", "A", "C"]) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=[1, 3], axis=1, ascending=[True, False]) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=[1, 3], axis=1, ascending=False) + expected = frame.reindex(columns=["C", "B", "A"]) + tm.assert_frame_equal(sorted_df, expected) + + msg = r"Length of ascending \(5\) != length of by \(2\)" + with pytest.raises(ValueError, match=msg): + frame.sort_values(by=["A", "B"], axis=0, ascending=[True] * 5) + + def test_sort_values_by_empty_list(self): + # https://github.com/pandas-dev/pandas/issues/40258 + expected = pd.DataFrame({"a": [1, 4, 2, 5, 3, 6]}) + result = expected.sort_values(by=[]) + tm.assert_frame_equal(result, expected) + assert result is not expected + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_values") + def test_sort_values_inplace(self): + frame = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), + index=[1, 2, 3, 4], + columns=["A", "B", "C", "D"], + ) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values(by="A", inplace=True) + assert return_value is None + expected = frame.sort_values(by="A") + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values(by=1, axis=1, inplace=True) + assert return_value is None + expected = frame.sort_values(by=1, axis=1) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values(by="A", ascending=False, inplace=True) + assert return_value is None + expected = frame.sort_values(by="A", ascending=False) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values( + by=["A", "B"], ascending=False, inplace=True + ) + assert return_value is None + expected = frame.sort_values(by=["A", "B"], ascending=False) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_multicolumn(self): + A = np.arange(5).repeat(20) + B = np.tile(np.arange(5), 20) + np.random.default_rng(2).shuffle(A) + np.random.default_rng(2).shuffle(B) + frame = pd.DataFrame( + {"A": A, "B": B, "C": np.random.default_rng(2).standard_normal(100)} + ) + + result = frame.sort_values(by=["A", "B"]) + indexer = np.lexsort((frame["B"], frame["A"])) + expected = frame.take(indexer) + tm.assert_frame_equal(result, expected) + + result = frame.sort_values(by=["A", "B"], ascending=False) + indexer = np.lexsort( + (frame["B"].rank(ascending=False), frame["A"].rank(ascending=False)) + ) + expected = frame.take(indexer) + tm.assert_frame_equal(result, expected) + + result = frame.sort_values(by=["B", "A"]) + indexer = np.lexsort((frame["A"], frame["B"])) + expected = frame.take(indexer) + tm.assert_frame_equal(result, expected) + + def test_sort_values_multicolumn_uint64(self): + # GH#9918 + # uint64 multicolumn sort + + df = pd.DataFrame( + { + "a": pd.Series([18446637057563306014, 1162265347240853609]), + "b": pd.Series([1, 2]), + } + ) + df["a"] = df["a"].astype(np.uint64) + result = df.sort_values(["a", "b"]) + + expected = pd.DataFrame( + { + "a": pd.Series([18446637057563306014, 1162265347240853609]), + "b": pd.Series([1, 2]), + }, + index=range(1, -1, -1), + ) + + tm.assert_frame_equal(result, expected) + + def test_sort_values_nan(self): + # GH#3917 + df = pd.DataFrame( + {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]} + ) + + # sort one column only + expected = pd.DataFrame( + {"A": [np.nan, 1, 1, 2, 4, 6, 8], "B": [5, 9, 2, np.nan, 5, 5, 4]}, + index=[2, 0, 3, 1, 6, 4, 5], + ) + sorted_df = df.sort_values(["A"], na_position="first") + tm.assert_frame_equal(sorted_df, expected) + + expected = pd.DataFrame( + {"A": [np.nan, 8, 6, 4, 2, 1, 1], "B": [5, 4, 5, 5, np.nan, 9, 2]}, + index=[2, 5, 4, 6, 1, 0, 3], + ) + sorted_df = df.sort_values(["A"], na_position="first", ascending=False) + tm.assert_frame_equal(sorted_df, expected) + + expected = df.reindex(columns=["B", "A"]) + sorted_df = df.sort_values(by=1, axis=1, na_position="first") + tm.assert_frame_equal(sorted_df, expected) + + # na_position='last', order + expected = pd.DataFrame( + {"A": [1, 1, 2, 4, 6, 8, np.nan], "B": [2, 9, np.nan, 5, 5, 4, 5]}, + index=[3, 0, 1, 6, 4, 5, 2], + ) + sorted_df = df.sort_values(["A", "B"]) + tm.assert_frame_equal(sorted_df, expected) + + # na_position='first', order + expected = pd.DataFrame( + {"A": [np.nan, 1, 1, 2, 4, 6, 8], "B": [5, 2, 9, np.nan, 5, 5, 4]}, + index=[2, 3, 0, 1, 6, 4, 5], + ) + sorted_df = df.sort_values(["A", "B"], na_position="first") + tm.assert_frame_equal(sorted_df, expected) + + # na_position='first', not order + expected = pd.DataFrame( + {"A": [np.nan, 1, 1, 2, 4, 6, 8], "B": [5, 9, 2, np.nan, 5, 5, 4]}, + index=[2, 0, 3, 1, 6, 4, 5], + ) + sorted_df = df.sort_values(["A", "B"], ascending=[1, 0], na_position="first") + tm.assert_frame_equal(sorted_df, expected) + + # na_position='last', not order + expected = pd.DataFrame( + {"A": [8, 6, 4, 2, 1, 1, np.nan], "B": [4, 5, 5, np.nan, 2, 9, 5]}, + index=[5, 4, 6, 1, 3, 0, 2], + ) + sorted_df = df.sort_values(["A", "B"], ascending=[0, 1], na_position="last") + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_stable_descending_sort(self): + # GH#6399 + df = pd.DataFrame( + [[2, "first"], [2, "second"], [1, "a"], [1, "b"]], + columns=["sort_col", "order"], + ) + sorted_df = df.sort_values(by="sort_col", kind="mergesort", ascending=False) + tm.assert_frame_equal(df, sorted_df) + + @pytest.mark.parametrize( + "expected_idx_non_na, ascending", + [ + [ + [3, 4, 5, 0, 1, 8, 6, 9, 7, 10, 13, 14], + [True, True], + ], + [ + [0, 3, 4, 5, 1, 8, 6, 7, 10, 13, 14, 9], + [True, False], + ], + [ + [9, 7, 10, 13, 14, 6, 8, 1, 3, 4, 5, 0], + [False, True], + ], + [ + [7, 10, 13, 14, 9, 6, 8, 1, 0, 3, 4, 5], + [False, False], + ], + ], + ) + @pytest.mark.parametrize("na_position", ["first", "last"]) + def test_sort_values_stable_multicolumn_sort( + self, expected_idx_non_na, ascending, na_position + ): + # GH#38426 Clarify sort_values with mult. columns / labels is stable + df = pd.DataFrame( + { + "A": [1, 2, np.nan, 1, 1, 1, 6, 8, 4, 8, 8, np.nan, np.nan, 8, 8], + "B": [9, np.nan, 5, 2, 2, 2, 5, 4, 5, 3, 4, np.nan, np.nan, 4, 4], + } + ) + # All rows with NaN in col "B" only have unique values in "A", therefore, + # only the rows with NaNs in "A" have to be treated individually: + expected_idx = ( + [11, 12, 2, *expected_idx_non_na] + if na_position == "first" + else [*expected_idx_non_na, 2, 11, 12] + ) + expected = df.take(expected_idx) + sorted_df = df.sort_values( + ["A", "B"], ascending=ascending, na_position=na_position + ) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_stable_categorical(self): + # GH#16793 + df = pd.DataFrame( + {"x": pd.Categorical(np.repeat([1, 2, 3, 4], 5), ordered=True)} + ) + expected = df.copy() + sorted_df = df.sort_values("x", kind="mergesort") + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_datetimes(self): + # GH#3461, argsort / lexsort differences for a datetime column + df = pd.DataFrame( + ["a", "a", "a", "b", "c", "d", "e", "f", "g"], + columns=["A"], + index=pd.date_range("20130101", periods=9), + ) + dts = [ + pd.Timestamp(x) + for x in [ + "2004-02-11", + "2004-01-21", + "2004-01-26", + "2005-09-20", + "2010-10-04", + "2009-05-12", + "2008-11-12", + "2010-09-28", + "2010-09-28", + ] + ] + df["B"] = dts[::2] + dts[1::2] + df["C"] = 2.0 + df["A1"] = 3.0 + + df1 = df.sort_values(by="A") + df2 = df.sort_values(by=["A"]) + tm.assert_frame_equal(df1, df2) + + df1 = df.sort_values(by="B") + df2 = df.sort_values(by=["B"]) + tm.assert_frame_equal(df1, df2) + + df1 = df.sort_values(by="B") + + df2 = df.sort_values(by=["C", "B"]) + tm.assert_frame_equal(df1, df2) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in Series.sort_values") + def test_sort_values_frame_column_inplace_sort_exception(self, float_frame): + s = float_frame["A"] + float_frame_orig = float_frame.copy() + # INFO(CoW) Series is a new object, so can be changed inplace + # without modifying original datafame + s.sort_values(inplace=True) + tm.assert_series_equal(s, float_frame_orig["A"].sort_values()) + # column in dataframe is not changed + tm.assert_frame_equal(float_frame, float_frame_orig) + + cp = s.copy() + cp.sort_values() # it works! + + def test_sort_values_nat_values_in_int_column(self): + # GH#14922: "sorting with large float and multiple columns incorrect" + + # cause was that the int64 value NaT was considered as "na". Which is + # only correct for datetime64 columns. + + int_values = (2, int(pd.NaT._value)) + float_values = (2.0, -1.797693e308) + + df = pd.DataFrame( + {"int": int_values, "float": float_values}, columns=["int", "float"] + ) + + df_reversed = pd.DataFrame( + {"int": int_values[::-1], "float": float_values[::-1]}, + columns=["int", "float"], + index=range(1, -1, -1), + ) + + # NaT is not a "na" for int64 columns, so na_position must not + # influence the result: + df_sorted = df.sort_values(["int", "float"], na_position="last") + tm.assert_frame_equal(df_sorted, df_reversed) + + df_sorted = df.sort_values(["int", "float"], na_position="first") + tm.assert_frame_equal(df_sorted, df_reversed) + + # reverse sorting order + df_sorted = df.sort_values(["int", "float"], ascending=False) + tm.assert_frame_equal(df_sorted, df) + + # and now check if NaT is still considered as "na" for datetime64 + # columns: + df = pd.DataFrame( + {"datetime": [pd.Timestamp("2016-01-01"), pd.NaT], "float": float_values}, + columns=["datetime", "float"], + ) + + df_reversed = pd.DataFrame( + { + "datetime": [pd.NaT, pd.Timestamp("2016-01-01")], + "float": float_values[::-1], + }, + columns=["datetime", "float"], + index=range(1, -1, -1), + ) + + df_sorted = df.sort_values(["datetime", "float"], na_position="first") + tm.assert_frame_equal(df_sorted, df_reversed) + + df_sorted = df.sort_values(["datetime", "float"], na_position="last") + tm.assert_frame_equal(df_sorted, df) + + # Ascending should not affect the results. + df_sorted = df.sort_values(["datetime", "float"], ascending=False) + tm.assert_frame_equal(df_sorted, df) + + def test_sort_nat(self): + # GH 16836 + + d1 = [ + pd.Timestamp(x) for x in ["2016-01-01", "2015-01-01", np.nan, "2016-01-01"] + ] + d2 = [ + pd.Timestamp(x) + for x in ["2017-01-01", "2014-01-01", "2016-01-01", "2015-01-01"] + ] + df = pd.DataFrame({"a": d1, "b": d2}, index=[0, 1, 2, 3]) + + d3 = [ + pd.Timestamp(x) for x in ["2015-01-01", "2016-01-01", "2016-01-01", np.nan] + ] + d4 = [ + pd.Timestamp(x) + for x in ["2014-01-01", "2015-01-01", "2017-01-01", "2016-01-01"] + ] + expected = pd.DataFrame({"a": d3, "b": d4}, index=[1, 3, 0, 2]) + sorted_df = df.sort_values(by=["a", "b"]) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_na_position_with_categories(self): + # GH#22556 + # Positioning missing value properly when column is Categorical. + categories = ["A", "B", "C"] + category_indices = [0, 2, 4] + list_of_nans = [np.nan, np.nan] + na_indices = [1, 3] + na_position_first = "first" + na_position_last = "last" + column_name = "c" + + reversed_categories = sorted(categories, reverse=True) + reversed_category_indices = sorted(category_indices, reverse=True) + reversed_na_indices = sorted(na_indices) + + df = pd.DataFrame( + { + column_name: pd.Categorical( + ["A", np.nan, "B", np.nan, "C"], categories=categories, ordered=True + ) + } + ) + # sort ascending with na first + result = df.sort_values( + by=column_name, ascending=True, na_position=na_position_first + ) + expected = pd.DataFrame( + { + column_name: pd.Categorical( + list_of_nans + categories, categories=categories, ordered=True + ) + }, + index=na_indices + category_indices, + ) + + tm.assert_frame_equal(result, expected) + + # sort ascending with na last + result = df.sort_values( + by=column_name, ascending=True, na_position=na_position_last + ) + expected = pd.DataFrame( + { + column_name: pd.Categorical( + categories + list_of_nans, categories=categories, ordered=True + ) + }, + index=category_indices + na_indices, + ) + + tm.assert_frame_equal(result, expected) + + # sort descending with na first + result = df.sort_values( + by=column_name, ascending=False, na_position=na_position_first + ) + expected = pd.DataFrame( + { + column_name: pd.Categorical( + list_of_nans + reversed_categories, + categories=categories, + ordered=True, + ) + }, + index=reversed_na_indices + reversed_category_indices, + ) + + tm.assert_frame_equal(result, expected) + + # sort descending with na last + result = df.sort_values( + by=column_name, ascending=False, na_position=na_position_last + ) + expected = pd.DataFrame( + { + column_name: pd.Categorical( + reversed_categories + list_of_nans, + categories=categories, + ordered=True, + ) + }, + index=reversed_category_indices + reversed_na_indices, + ) + + tm.assert_frame_equal(result, expected) + + def test_sort_values_nat(self): + # GH#16836 + + d1 = [ + pd.Timestamp(x) for x in ["2016-01-01", "2015-01-01", np.nan, "2016-01-01"] + ] + d2 = [ + pd.Timestamp(x) + for x in ["2017-01-01", "2014-01-01", "2016-01-01", "2015-01-01"] + ] + df = pd.DataFrame({"a": d1, "b": d2}, index=[0, 1, 2, 3]) + + d3 = [ + pd.Timestamp(x) for x in ["2015-01-01", "2016-01-01", "2016-01-01", np.nan] + ] + d4 = [ + pd.Timestamp(x) + for x in ["2014-01-01", "2015-01-01", "2017-01-01", "2016-01-01"] + ] + expected = pd.DataFrame({"a": d3, "b": d4}, index=[1, 3, 0, 2]) + sorted_df = df.sort_values(by=["a", "b"]) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_na_position_with_categories_raises(self): + df = pd.DataFrame( + { + "c": pd.Categorical( + ["A", np.nan, "B", np.nan, "C"], + categories=["A", "B", "C"], + ordered=True, + ) + } + ) + + with pytest.raises(ValueError, match="invalid na_position: bad_position"): + df.sort_values(by="c", ascending=False, na_position="bad_position") + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_values") + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize( + "original_dict, sorted_dict, ignore_index, output_index", + [ + ({"A": [1, 2, 3]}, {"A": [3, 2, 1]}, True, range(3)), + ({"A": [1, 2, 3]}, {"A": [3, 2, 1]}, False, range(2, -1, -1)), + ( + {"A": [1, 2, 3], "B": [2, 3, 4]}, + {"A": [3, 2, 1], "B": [4, 3, 2]}, + True, + range(3), + ), + ( + {"A": [1, 2, 3], "B": [2, 3, 4]}, + {"A": [3, 2, 1], "B": [4, 3, 2]}, + False, + range(2, -1, -1), + ), + ], + ) + def test_sort_values_ignore_index( + self, inplace, original_dict, sorted_dict, ignore_index, output_index + ): + # GH 30114 + df = pd.DataFrame(original_dict) + expected = pd.DataFrame(sorted_dict, index=output_index) + kwargs = {"ignore_index": ignore_index, "inplace": inplace} + + if inplace: + result_df = df.copy() + result_df.sort_values("A", ascending=False, **kwargs) + else: + result_df = df.sort_values("A", ascending=False, **kwargs) + + tm.assert_frame_equal(result_df, expected) + tm.assert_frame_equal(df, pd.DataFrame(original_dict)) + + def test_sort_values_nat_na_position_default(self): + # GH 13230 + expected = pd.DataFrame( + { + "A": [1, 2, 3, 4, 4], + "date": pd.DatetimeIndex( + [ + "2010-01-01 09:00:00", + "2010-01-01 09:00:01", + "2010-01-01 09:00:02", + "2010-01-01 09:00:03", + "NaT", + ] + ), + } + ) + result = expected.sort_values(["A", "date"]) + tm.assert_frame_equal(result, expected) + + def test_sort_values_reshaping(self): + # GH 39426 + values = list(range(21)) + expected = pd.DataFrame([values], columns=values) + df = expected.sort_values(expected.index[0], axis=1, ignore_index=True) + + tm.assert_frame_equal(df, expected) + + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_values") + def test_sort_values_no_by_inplace(self): + # GH#50643 + df = pd.DataFrame({"a": [1, 2, 3]}) + expected = df.copy() + result = df.sort_values(by=[], inplace=True) + tm.assert_frame_equal(df, expected) + assert result is None + + def test_sort_values_no_op_reset_index(self): + # GH#52553 + df = pd.DataFrame({"A": [10, 20], "B": [1, 5]}, index=[2, 3]) + result = df.sort_values(by="A", ignore_index=True) + expected = pd.DataFrame({"A": [10, 20], "B": [1, 5]}) + tm.assert_frame_equal(result, expected) + + def test_sort_by_column_named_none(self): + # GH#61512 + df = pd.DataFrame([[3, 1], [2, 2]], columns=[None, "C1"]) + result = df.sort_values(by=None) + expected = pd.DataFrame([[2, 2], [3, 1]], columns=[None, "C1"], index=[1, 0]) + tm.assert_frame_equal(result, expected) + + +class TestDataFrameSortKey: # test key sorting (issue 27237) + @pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.sort_values") + def test_sort_values_inplace_key(self, sort_by_key): + frame = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), + index=[1, 2, 3, 4], + columns=["A", "B", "C", "D"], + ) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values(by="A", inplace=True, key=sort_by_key) + assert return_value is None + expected = frame.sort_values(by="A", key=sort_by_key) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values( + by=1, axis=1, inplace=True, key=sort_by_key + ) + assert return_value is None + expected = frame.sort_values(by=1, axis=1, key=sort_by_key) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values( + by="A", ascending=False, inplace=True, key=sort_by_key + ) + assert return_value is None + expected = frame.sort_values(by="A", ascending=False, key=sort_by_key) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + sorted_df.sort_values( + by=["A", "B"], ascending=False, inplace=True, key=sort_by_key + ) + expected = frame.sort_values(by=["A", "B"], ascending=False, key=sort_by_key) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_key(self): + df = pd.DataFrame(np.array([0, 5, np.nan, 3, 2, np.nan])) + + result = df.sort_values(0) + expected = df.iloc[[0, 4, 3, 1, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(0, key=lambda x: x + 5) + expected = df.iloc[[0, 4, 3, 1, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(0, key=lambda x: -x, ascending=False) + expected = df.iloc[[0, 4, 3, 1, 2, 5]] + tm.assert_frame_equal(result, expected) + + def test_sort_values_by_key(self): + df = pd.DataFrame( + { + "a": np.array([0, 3, np.nan, 3, 2, np.nan]), + "b": np.array([0, 2, np.nan, 5, 2, np.nan]), + } + ) + + result = df.sort_values("a", key=lambda x: -x) + expected = df.iloc[[1, 3, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by=["a", "b"], key=lambda x: -x) + expected = df.iloc[[3, 1, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by=["a", "b"], key=lambda x: -x, ascending=False) + expected = df.iloc[[0, 4, 1, 3, 2, 5]] + tm.assert_frame_equal(result, expected) + + def test_sort_values_by_key_by_name(self): + df = pd.DataFrame( + { + "a": np.array([0, 3, np.nan, 3, 2, np.nan]), + "b": np.array([0, 2, np.nan, 5, 2, np.nan]), + } + ) + + def key(col): + if col.name == "a": + return -col + else: + return col + + result = df.sort_values(by="a", key=key) + expected = df.iloc[[1, 3, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by=["a"], key=key) + expected = df.iloc[[1, 3, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by="b", key=key) + expected = df.iloc[[0, 1, 4, 3, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by=["a", "b"], key=key) + expected = df.iloc[[1, 3, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + def test_sort_values_key_string(self): + df = pd.DataFrame(np.array([["hello", "goodbye"], ["hello", "Hello"]])) + + result = df.sort_values(1) + expected = df[::-1] + tm.assert_frame_equal(result, expected) + + result = df.sort_values([0, 1], key=lambda col: col.str.lower()) + tm.assert_frame_equal(result, df) + + result = df.sort_values( + [0, 1], key=lambda col: col.str.lower(), ascending=False + ) + expected = df.sort_values(1, key=lambda col: col.str.lower(), ascending=False) + tm.assert_frame_equal(result, expected) + + def test_sort_values_key_empty(self, sort_by_key): + df = pd.DataFrame(np.array([])) + + df.sort_values(0, key=sort_by_key) + df.sort_index(key=sort_by_key) + + def test_changes_length_raises(self): + df = pd.DataFrame({"A": [1, 2, 3]}) + with pytest.raises(ValueError, match="change the shape"): + df.sort_values("A", key=lambda x: x[:1]) + + def test_sort_values_key_axes(self): + df = pd.DataFrame({0: ["Hello", "goodbye"], 1: [0, 1]}) + + result = df.sort_values(0, key=lambda col: col.str.lower()) + expected = df[::-1] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(1, key=lambda col: -col) + expected = df[::-1] + tm.assert_frame_equal(result, expected) + + def test_sort_values_key_dict_axis(self): + df = pd.DataFrame({0: ["Hello", 0], 1: ["goodbye", 1]}) + + result = df.sort_values(0, key=lambda col: col.str.lower(), axis=1) + expected = df.loc[:, ::-1] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(1, key=lambda col: -col, axis=1) + expected = df.loc[:, ::-1] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("ordered", [True, False]) + def test_sort_values_key_casts_to_categorical(self, ordered): + # https://github.com/pandas-dev/pandas/issues/36383 + categories = ["c", "b", "a"] + df = pd.DataFrame({"x": [1, 1, 1], "y": ["a", "b", "c"]}) + + def sorter(key): + if key.name == "y": + return pd.Series( + pd.Categorical(key, categories=categories, ordered=ordered) + ) + return key + + result = df.sort_values(by=["x", "y"], key=sorter) + expected = pd.DataFrame( + {"x": [1, 1, 1], "y": ["c", "b", "a"]}, index=pd.Index([2, 1, 0]) + ) + + tm.assert_frame_equal(result, expected) + + +@pytest.fixture +def df_none(): + return pd.DataFrame( + { + "outer": ["a", "a", "a", "b", "b", "b"], + "inner": [1, 2, 2, 2, 1, 1], + "A": np.arange(6, 0, -1), + ("B", 5): ["one", "one", "two", "two", "one", "one"], + } + ) + + +@pytest.fixture(params=[["outer"], ["outer", "inner"]]) +def df_idx(request, df_none): + levels = request.param + return df_none.set_index(levels) + + +@pytest.fixture( + params=[ + "inner", # index level + ["outer"], # list of index level + "A", # column + [("B", 5)], # list of column + ["inner", "outer"], # two index levels + [("B", 5), "outer"], # index level and column + ["A", ("B", 5)], # Two columns + ["inner", "outer"], # two index levels and column + ] +) +def sort_names(request): + return request.param + + +class TestSortValuesLevelAsStr: + def test_sort_index_level_and_column_label( + self, df_none, df_idx, sort_names, ascending + ): + # GH#14353 + + # Get index levels from df_idx + levels = df_idx.index.names + + # Compute expected by sorting on columns and the setting index + expected = df_none.sort_values( + by=sort_names, ascending=ascending, axis=0 + ).set_index(levels) + + # Compute result sorting on mix on columns and index levels + result = df_idx.sort_values(by=sort_names, ascending=ascending, axis=0) + + sort_keys = [sort_names] if isinstance(sort_names, str) else sort_names + if df_none[sort_keys].duplicated().any(): + # Unstable sort: tie-breaking among equal keys is + # platform-dependent. Compare using all columns as a + # deterministic tiebreaker. + tm.assert_frame_equal( + result.sort_values(list(result.columns)), + expected.sort_values(list(expected.columns)), + ) + else: + tm.assert_frame_equal(result, expected) + + def test_sort_column_level_and_index_label( + self, df_none, df_idx, sort_names, ascending + ): + # GH#14353 + + # Get levels from df_idx + levels = df_idx.index.names + + # Compute expected by sorting on axis=0, setting index levels, and then + # transposing. For some cases this will result in a frame with + # multiple column levels + expected = ( + df_none.sort_values(by=sort_names, ascending=ascending, axis=0) + .set_index(levels) + .T + ) + + # Compute result by transposing and sorting on axis=1. + result = df_idx.T.sort_values(by=sort_names, ascending=ascending, axis=1) + + sort_keys = [sort_names] if isinstance(sort_names, str) else sort_names + if df_none[sort_keys].duplicated().any(): + # Unstable sort: tie-breaking among equal keys is + # platform-dependent. Compare using all columns as a + # deterministic tiebreaker (transposing to sort rows). + tm.assert_frame_equal( + result.T.sort_values(list(result.T.columns)).T, + expected.T.sort_values(list(expected.T.columns)).T, + ) + else: + tm.assert_frame_equal(result, expected) + + def test_sort_values_validate_ascending_for_value_error(self): + # GH41634 + df = pd.DataFrame({"D": [23, 7, 21]}) + + msg = 'For argument "ascending" expected type bool, received type str.' + with pytest.raises(ValueError, match=msg): + df.sort_values(by="D", ascending="False") + + def test_sort_values_validate_ascending_functional(self, ascending): + df = pd.DataFrame({"D": [23, 7, 21]}) + indexer = df["D"].argsort().values + + if not ascending: + indexer = indexer[::-1] + + expected = df.loc[df.index[indexer]] + result = df.sort_values(by="D", ascending=ascending) + tm.assert_frame_equal(result, expected) + + +def test_sort_values_inplace_depr(): + msg = "The inplace keyword in DataFrame.sort_values is deprecated" + + df = pd.DataFrame({"a": [3, 1, 2]}) + df_orig = df.copy() + expected = pd.DataFrame({"a": [1, 2, 3]}, index=[1, 2, 0]) + + # does not use keyword, no warning + with tm.assert_produces_warning(False): + result = df.sort_values(by="a") + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to false, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.sort_values(by="a", inplace=False) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, df_orig) + + # uses keyword, set to true, warning + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.sort_values(by="a", inplace=True) + tm.assert_frame_equal(df, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_swaplevel.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_swaplevel.py new file mode 100644 index 0000000000000000000000000000000000000000..e630220721a9ba9ef8c4fb603ac44f692636c3d7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_swaplevel.py @@ -0,0 +1,36 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestSwaplevel: + def test_swaplevel(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + swapped = frame["A"].swaplevel() + swapped2 = frame["A"].swaplevel(0) + swapped3 = frame["A"].swaplevel(0, 1) + swapped4 = frame["A"].swaplevel("first", "second") + assert not swapped.index.equals(frame.index) + tm.assert_series_equal(swapped, swapped2) + tm.assert_series_equal(swapped, swapped3) + tm.assert_series_equal(swapped, swapped4) + + back = swapped.swaplevel() + back2 = swapped.swaplevel(0) + back3 = swapped.swaplevel(0, 1) + back4 = swapped.swaplevel("second", "first") + assert back.index.equals(frame.index) + tm.assert_series_equal(back, back2) + tm.assert_series_equal(back, back3) + tm.assert_series_equal(back, back4) + + ft = frame.T + swapped = ft.swaplevel("first", "second", axis=1) + exp = frame.swaplevel("first", "second").T + tm.assert_frame_equal(swapped, exp) + + msg = "Can only swap levels on a hierarchical axis." + with pytest.raises(TypeError, match=msg): + pd.DataFrame(range(3)).swaplevel() diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_csv.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..2ca25a23fff0716d0ba2185643abbd00dfc95c60 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_csv.py @@ -0,0 +1,1480 @@ +import csv +from io import StringIO +import os + +import numpy as np +import pytest + +from pandas.errors import ParserError + +import pandas as pd +import pandas._testing as tm +import pandas.core.common as com + +from pandas.io.common import get_handle + + +class TestDataFrameToCSV: + def read_csv(self, path, **kwargs): + params = {"index_col": 0} + params.update(**kwargs) + + return pd.read_csv(path, **params) + + def test_to_csv_from_csv1(self, temp_file, float_frame): + path = str(temp_file) + float_frame.iloc[:5, float_frame.columns.get_loc("A")] = np.nan + + float_frame.to_csv(path) + float_frame.to_csv(path, columns=["A", "B"]) + float_frame.to_csv(path, header=False) + float_frame.to_csv(path, index=False) + + def test_to_csv_from_csv1_datetime(self, temp_file, datetime_frame): + path = str(temp_file) + # test roundtrip + # freq does not roundtrip + datetime_frame.index = datetime_frame.index._with_freq(None) + datetime_frame.to_csv(path) + recons = self.read_csv(path, parse_dates=True) + expected = datetime_frame.copy() + expected.index = expected.index.as_unit("us") + tm.assert_frame_equal(expected, recons) + + datetime_frame.to_csv(path, index_label="index") + recons = self.read_csv(path, index_col=None, parse_dates=True) + + assert len(recons.columns) == len(datetime_frame.columns) + 1 + + # no index + datetime_frame.to_csv(path, index=False) + recons = self.read_csv(path, index_col=None, parse_dates=True) + tm.assert_almost_equal(datetime_frame.values, recons.values) + + def test_to_csv_from_csv1_corner_case(self, temp_file): + path = str(temp_file) + dm = pd.DataFrame( + { + "s1": pd.Series(range(3), index=np.arange(3, dtype=np.int64)), + "s2": pd.Series(range(2), index=np.arange(2, dtype=np.int64)), + } + ) + dm.to_csv(path) + + recons = self.read_csv(path) + tm.assert_frame_equal(dm, recons) + + def test_to_csv_from_csv2(self, temp_file, float_frame): + path = str(temp_file) + # duplicate index + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + index=["a", "a", "b"], + columns=["x", "y", "z"], + ) + df.to_csv(path) + result = self.read_csv(path) + tm.assert_frame_equal(result, df) + + midx = pd.MultiIndex.from_tuples([("A", 1, 2), ("A", 1, 2), ("B", 1, 2)]) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + index=midx, + columns=["x", "y", "z"], + ) + + df.to_csv(path) + result = self.read_csv(path, index_col=[0, 1, 2], parse_dates=False) + tm.assert_frame_equal(result, df, check_names=False) + + # column aliases + col_aliases = pd.Index(["AA", "X", "Y", "Z"]) + float_frame.to_csv(path, header=col_aliases) + + rs = self.read_csv(path) + xp = float_frame.copy() + xp.columns = col_aliases + tm.assert_frame_equal(xp, rs) + + msg = "Writing 4 cols but got 2 aliases" + with pytest.raises(ValueError, match=msg): + float_frame.to_csv(path, header=["AA", "X"]) + + def test_to_csv_from_csv3(self, temp_file): + path = str(temp_file) + df1 = pd.DataFrame(np.random.default_rng(2).standard_normal((3, 1))) + df2 = pd.DataFrame(np.random.default_rng(2).standard_normal((3, 1))) + + df1.to_csv(path) + df2.to_csv(path, mode="a", header=False) + xp = pd.concat([df1, df2]) + rs = pd.read_csv(path, index_col=0) + rs.columns = [int(label) for label in rs.columns] + xp.columns = [int(label) for label in xp.columns] + tm.assert_frame_equal(xp, rs) + + def test_to_csv_from_csv4(self, temp_file): + path = str(temp_file) + # GH 10833 (TimedeltaIndex formatting) + dt = pd.Timedelta(seconds=1).as_unit("us") + df = pd.DataFrame( + {"dt_data": [i * dt for i in range(3)]}, + index=pd.Index([i * dt for i in range(3)], name="dt_index"), + ) + df.to_csv(path) + + result = pd.read_csv(path, index_col="dt_index") + result.index = pd.to_timedelta(result.index) + result["dt_data"] = pd.to_timedelta(result["dt_data"]) + + tm.assert_frame_equal(df, result, check_index_type=True) + + def test_to_csv_from_csv5(self, temp_file, timezone_frame): + # tz, 8260 + path = str(temp_file) + timezone_frame.to_csv(path) + result = pd.read_csv(path, index_col=0, parse_dates=["A"]) + + converter = lambda c: ( + pd.to_datetime(result[c]) + .dt.tz_convert("UTC") + .dt.tz_convert(timezone_frame[c].dt.tz) + .dt.as_unit("ns") + ) + result["B"] = converter("B") + result["C"] = converter("C") + result["A"] = result["A"].dt.as_unit("ns") + tm.assert_frame_equal(result, timezone_frame) + + def test_to_csv_cols_reordering(self, temp_file): + # GH3454 + chunksize = 5 + N = int(chunksize * 2.5) + + df = pd.DataFrame( + np.ones((N, 3)), + index=pd.Index([f"i-{i}" for i in range(N)], name="a"), + columns=pd.Index([f"i-{i}" for i in range(3)], name="a"), + ) + cs = df.columns + cols = [cs[2], cs[0]] + + path = str(temp_file) + df.to_csv(path, columns=cols, chunksize=chunksize) + rs_c = pd.read_csv(path, index_col=0) + + tm.assert_frame_equal(df[cols], rs_c, check_names=False) + + @pytest.mark.parametrize("cols", [None, ["b", "a"]]) + def test_to_csv_new_dupe_cols(self, temp_file, cols): + chunksize = 5 + N = int(chunksize * 2.5) + + # dupe cols + df = pd.DataFrame( + np.ones((N, 3)), + index=pd.Index([f"i-{i}" for i in range(N)], name="a"), + columns=["a", "a", "b"], + ) + path = str(temp_file) + df.to_csv(path, columns=cols, chunksize=chunksize) + rs_c = pd.read_csv(path, index_col=0) + + # we wrote them in a different order + # so compare them in that order + if cols is not None: + if df.columns.is_unique: + rs_c.columns = cols + else: + indexer, missing = df.columns.get_indexer_non_unique(cols) + rs_c.columns = df.columns.take(indexer) + + for c in cols: + obj_df = df[c] + obj_rs = rs_c[c] + if isinstance(obj_df, pd.Series): + tm.assert_series_equal(obj_df, obj_rs) + else: + tm.assert_frame_equal(obj_df, obj_rs, check_names=False) + + # wrote in the same order + else: + rs_c.columns = df.columns + tm.assert_frame_equal(df, rs_c, check_names=False) + + @pytest.mark.slow + def test_to_csv_dtnat(self, temp_file): + # GH3437 + def make_dtnat_arr(n, nnat=None): + if nnat is None: + nnat = int(n * 0.1) # 10% + s = list(pd.date_range("2000", freq="5min", periods=n)) + if nnat: + for i in np.random.default_rng(2).integers(0, len(s), nnat): + s[i] = pd.NaT + i = np.random.default_rng(2).integers(100) + s[-i] = pd.NaT + s[i] = pd.NaT + return s + + chunksize = 1000 + s1 = make_dtnat_arr(chunksize + 5) + s2 = make_dtnat_arr(chunksize + 5, 0) + + path = str(temp_file) + df = pd.DataFrame({"a": s1, "b": s2}) + df.to_csv(path, chunksize=chunksize) + + result = self.read_csv(path).apply(pd.to_datetime) + + expected = df[:] + expected["a"] = expected["a"].astype("M8[us]") + expected["b"] = expected["b"].astype("M8[us]") + tm.assert_frame_equal(result, expected, check_names=False) + + def _return_result_expected( + self, + df, + chunksize, + temp_file, + r_dtype=None, + c_dtype=None, + rnlvl=None, + cnlvl=None, + dupe_col=False, + ): + kwargs = {"parse_dates": False} + if cnlvl: + if rnlvl is not None: + kwargs["index_col"] = list(range(rnlvl)) + kwargs["header"] = list(range(cnlvl)) + + df.to_csv(temp_file, encoding="utf8", chunksize=chunksize) + recons = self.read_csv(temp_file, **kwargs) + else: + kwargs["header"] = 0 + + df.to_csv(temp_file, encoding="utf8", chunksize=chunksize) + recons = self.read_csv(temp_file, **kwargs) + + def _to_uni(x): + if not isinstance(x, str): + return x.decode("utf8") + return x + + if dupe_col: + # read_Csv disambiguates the columns by + # labeling them dupe.1,dupe.2, etc'. monkey patch columns + recons.columns = df.columns + if rnlvl and not cnlvl: + delta_lvl = [recons.iloc[:, i].values for i in range(rnlvl - 1)] + ix = pd.MultiIndex.from_arrays([list(recons.index), *delta_lvl]) + recons.index = ix + recons = recons.iloc[:, rnlvl - 1 :] + + type_map = {"i": "i", "f": "f", "s": "O", "u": "O", "dt": "O", "p": "O"} + if r_dtype: + if r_dtype == "u": # unicode + r_dtype = "O" + recons.index = np.array( + [_to_uni(label) for label in recons.index], dtype=r_dtype + ) + df.index = np.array( + [_to_uni(label) for label in df.index], dtype=r_dtype + ) + elif r_dtype == "dt": # unicode + r_dtype = "O" + recons.index = np.array( + [pd.Timestamp(label) for label in recons.index], dtype=r_dtype + ) + df.index = np.array( + [pd.Timestamp(label) for label in df.index], dtype=r_dtype + ) + elif r_dtype == "p": + r_dtype = "O" + idx_list = pd.to_datetime(recons.index) + recons.index = np.array( + [pd.Timestamp(label) for label in idx_list], dtype=r_dtype + ) + df.index = np.array( + list(map(pd.Timestamp, df.index.to_timestamp())), dtype=r_dtype + ) + else: + r_dtype = type_map.get(r_dtype) + recons.index = np.array(recons.index, dtype=r_dtype) + df.index = np.array(df.index, dtype=r_dtype) + if c_dtype: + if c_dtype == "u": + c_dtype = "O" + recons.columns = np.array( + [_to_uni(label) for label in recons.columns], dtype=c_dtype + ) + df.columns = np.array( + [_to_uni(label) for label in df.columns], dtype=c_dtype + ) + elif c_dtype == "dt": + c_dtype = "O" + recons.columns = np.array( + [pd.Timestamp(label) for label in recons.columns], dtype=c_dtype + ) + df.columns = np.array( + [pd.Timestamp(label) for label in df.columns], dtype=c_dtype + ) + elif c_dtype == "p": + c_dtype = "O" + col_list = pd.to_datetime(recons.columns) + recons.columns = np.array( + [pd.Timestamp(label) for label in col_list], dtype=c_dtype + ) + col_list = df.columns.to_timestamp() + df.columns = np.array( + [pd.Timestamp(label) for label in col_list], dtype=c_dtype + ) + else: + c_dtype = type_map.get(c_dtype) + recons.columns = np.array(recons.columns, dtype=c_dtype) + df.columns = np.array(df.columns, dtype=c_dtype) + return df, recons + + @pytest.mark.slow + @pytest.mark.parametrize( + "nrows", [2, 10, 99, 100, 101, 102, 198, 199, 200, 201, 202, 249, 250, 251] + ) + def test_to_csv_nrows(self, nrows, temp_file): + df = pd.DataFrame( + np.ones((nrows, 4)), + index=pd.date_range("2020-01-01", periods=nrows), + columns=pd.Index(list("abcd"), dtype=object), + ) + result, expected = self._return_result_expected(df, 1000, temp_file, "dt", "s") + expected.index = expected.index.astype("M8[us]") + tm.assert_frame_equal(result, expected, check_names=False) + + @pytest.mark.slow + @pytest.mark.parametrize( + "nrows", [2, 10, 99, 100, 101, 102, 198, 199, 200, 201, 202, 249, 250, 251] + ) + @pytest.mark.parametrize( + "r_idx_type, c_idx_type", [("i", "i"), ("s", "s"), ("s", "dt"), ("p", "p")] + ) + @pytest.mark.parametrize("ncols", [1, 2, 3, 4]) + def test_to_csv_idx_types(self, nrows, r_idx_type, c_idx_type, ncols, temp_file): + axes = { + "i": lambda n: pd.Index(np.arange(n), dtype=np.int64), + "s": lambda n: pd.Index([f"{i}_{chr(i)}" for i in range(97, 97 + n)]), + "dt": lambda n: pd.date_range("2020-01-01", periods=n), + "p": lambda n: pd.period_range("2020-01-01", periods=n, freq="D"), + } + df = pd.DataFrame( + np.ones((nrows, ncols)), + index=axes[r_idx_type](nrows), + columns=axes[c_idx_type](ncols), + ) + result, expected = self._return_result_expected( + df, + 1000, + temp_file, + r_idx_type, + c_idx_type, + ) + if r_idx_type == "dt": + expected.index = expected.index.astype("M8[us]") + elif r_idx_type == "p": + expected.index = expected.index.astype("M8[us]") + if c_idx_type == "dt": + expected.columns = expected.columns.astype("M8[us]") + elif c_idx_type == "p": + expected.columns = expected.columns.astype("M8[us]") + tm.assert_frame_equal(result, expected, check_names=False) + + @pytest.mark.slow + @pytest.mark.parametrize( + "nrows", [10, 98, 99, 100, 101, 102, 198, 199, 200, 201, 202, 249, 250, 251] + ) + @pytest.mark.parametrize("ncols", [1, 2, 3, 4]) + def test_to_csv_idx_ncols(self, nrows, ncols, temp_file): + df = pd.DataFrame( + np.ones((nrows, ncols)), + index=pd.Index([f"i-{i}" for i in range(nrows)], name="a"), + columns=pd.Index([f"i-{i}" for i in range(ncols)], name="a"), + ) + result, expected = self._return_result_expected(df, 1000, temp_file) + tm.assert_frame_equal(result, expected, check_names=False) + + @pytest.mark.slow + @pytest.mark.parametrize("nrows", [10, 98, 99, 100, 101, 102]) + def test_to_csv_dup_cols(self, nrows, temp_file): + df = pd.DataFrame( + np.ones((nrows, 3)), + index=pd.Index([f"i-{i}" for i in range(nrows)], name="a"), + columns=pd.Index([f"i-{i}" for i in range(3)], name="a"), + ) + + cols = list(df.columns) + cols[:2] = ["dupe", "dupe"] + cols[-2:] = ["dupe", "dupe"] + ix = list(df.index) + ix[:2] = ["rdupe", "rdupe"] + ix[-2:] = ["rdupe", "rdupe"] + df.index = ix + df.columns = cols + result, expected = self._return_result_expected( + df, 1000, temp_file, dupe_col=True + ) + tm.assert_frame_equal(result, expected, check_names=False) + + @pytest.mark.slow + def test_to_csv_empty(self, temp_file): + df = pd.DataFrame(index=np.arange(10, dtype=np.int64)) + result, expected = self._return_result_expected(df, 1000, temp_file) + tm.assert_frame_equal(result, expected, check_column_type=False) + + @pytest.mark.slow + def test_to_csv_chunksize(self, temp_file): + chunksize = 1000 + rows = chunksize // 2 + 1 + df = pd.DataFrame( + np.ones((rows, 2)), + columns=pd.Index(list("ab")), + index=pd.MultiIndex.from_arrays([range(rows) for _ in range(2)]), + ) + result, expected = self._return_result_expected( + df, chunksize, temp_file, rnlvl=2 + ) + tm.assert_frame_equal(result, expected, check_names=False) + + @pytest.mark.slow + @pytest.mark.parametrize( + "nrows", [2, 10, 99, 100, 101, 102, 198, 199, 200, 201, 202, 249, 250, 251] + ) + @pytest.mark.parametrize("ncols", [2, 3, 4]) + @pytest.mark.parametrize( + "df_params, func_params", + [ + [{"r_idx_nlevels": 2}, {"rnlvl": 2}], + [{"c_idx_nlevels": 2}, {"cnlvl": 2}], + [{"r_idx_nlevels": 2, "c_idx_nlevels": 2}, {"rnlvl": 2, "cnlvl": 2}], + ], + ) + def test_to_csv_params(self, nrows, df_params, func_params, ncols, temp_file): + if df_params.get("r_idx_nlevels"): + index = pd.MultiIndex.from_arrays( + [f"i-{i}" for i in range(nrows)] + for _ in range(df_params["r_idx_nlevels"]) + ) + else: + index = None + + if df_params.get("c_idx_nlevels"): + columns = pd.MultiIndex.from_arrays( + [f"i-{i}" for i in range(ncols)] + for _ in range(df_params["c_idx_nlevels"]) + ) + else: + columns = pd.Index([f"i-{i}" for i in range(ncols)]) + df = pd.DataFrame(np.ones((nrows, ncols)), index=index, columns=columns) + result, expected = self._return_result_expected( + df, 1000, temp_file, **func_params + ) + tm.assert_frame_equal(result, expected, check_names=False) + + def test_to_csv_from_csv_w_some_infs(self, temp_file, float_frame): + # test roundtrip with inf, -inf, nan, as full columns and mix + float_frame["G"] = np.nan + f = lambda x: [np.inf, np.nan][np.random.default_rng(2).random() < 0.5] + float_frame["h"] = float_frame.index.map(f) + + path = str(temp_file) + float_frame.to_csv(path) + recons = self.read_csv(path) + + tm.assert_frame_equal(float_frame, recons) + tm.assert_frame_equal(np.isinf(float_frame), np.isinf(recons)) + + def test_to_csv_from_csv_w_all_infs(self, temp_file, float_frame): + # test roundtrip with inf, -inf, nan, as full columns and mix + float_frame["E"] = np.inf + float_frame["F"] = -np.inf + + path = str(temp_file) + float_frame.to_csv(path) + recons = self.read_csv(path) + + tm.assert_frame_equal(float_frame, recons) + tm.assert_frame_equal(np.isinf(float_frame), np.isinf(recons)) + + def test_to_csv_no_index(self, temp_file): + # GH 3624, after appending columns, to_csv fails + path = str(temp_file) + df = pd.DataFrame({"c1": [1, 2, 3], "c2": [4, 5, 6]}) + df.to_csv(path, index=False) + result = pd.read_csv(path) + tm.assert_frame_equal(df, result) + df["c3"] = pd.Series([7, 8, 9], dtype="int64") + df.to_csv(path, index=False) + result = pd.read_csv(path) + tm.assert_frame_equal(df, result) + + def test_to_csv_with_mix_columns(self): + # gh-11637: incorrect output when a mix of integer and string column + # names passed as columns parameter in to_csv + + df = pd.DataFrame({0: ["a", "b", "c"], 1: ["aa", "bb", "cc"]}) + df["test"] = "txt" + assert df.to_csv() == df.to_csv(columns=[0, 1, "test"]) + + def test_to_csv_headers(self, temp_file): + # GH6186, the presence or absence of `index` incorrectly + # causes to_csv to have different header semantics. + from_df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + to_df = pd.DataFrame([[1, 2], [3, 4]], columns=["X", "Y"]) + path = str(temp_file) + from_df.to_csv(path, header=["X", "Y"]) + recons = self.read_csv(path) + + tm.assert_frame_equal(to_df, recons) + + from_df.to_csv(path, index=False, header=["X", "Y"]) + recons = self.read_csv(path) + + recons = recons.reset_index() + tm.assert_frame_equal(to_df, recons) + + def test_to_csv_multiindex(self, temp_file, float_frame, datetime_frame): + frame = float_frame + old_index = frame.index + arrays = np.arange(len(old_index) * 2, dtype=np.int64).reshape(2, -1) + new_index = pd.MultiIndex.from_arrays(arrays, names=["first", "second"]) + frame.index = new_index + + path = str(temp_file) + frame.to_csv(path, header=False) + frame.to_csv(path, columns=["A", "B"]) + + # round trip + frame.to_csv(path) + + df = self.read_csv(path, index_col=[0, 1], parse_dates=False) + + # TODO to_csv drops column name + tm.assert_frame_equal(frame, df, check_names=False) + assert frame.index.names == df.index.names + + # needed if setUp becomes a class method + float_frame.index = old_index + + # try multiindex with dates + tsframe = datetime_frame + old_index = tsframe.index + new_index = [old_index, np.arange(len(old_index), dtype=np.int64)] + tsframe.index = pd.MultiIndex.from_arrays(new_index) + + tsframe.to_csv(path, index_label=["time", "foo"]) + with tm.assert_produces_warning(UserWarning, match="Could not infer format"): + recons = self.read_csv(path, index_col=[0, 1], parse_dates=True) + + # TODO to_csv drops column name + expected = tsframe.copy() + expected.index = pd.MultiIndex.from_arrays( + [old_index.as_unit("us"), new_index[1]] + ) + tm.assert_frame_equal(recons, expected, check_names=False, check_freq=False) + + # do not load index + tsframe.to_csv(path) + recons = self.read_csv(path, index_col=None) + assert len(recons.columns) == len(tsframe.columns) + 2 + + # no index + tsframe.to_csv(path, index=False) + recons = self.read_csv(path, index_col=None) + tm.assert_almost_equal(recons.values, datetime_frame.values) + + # needed if setUp becomes class method + datetime_frame.index = old_index + + def _make_frame(names=None): + if names is True: + names = ["first", "second"] + return pd.DataFrame( + np.random.default_rng(2).integers(0, 10, size=(3, 3)), + columns=pd.MultiIndex.from_tuples( + [("bah", "foo"), ("bah", "bar"), ("ban", "baz")], names=names + ), + dtype="int64", + ) + + # column & index are multi-index + df = pd.DataFrame( + np.ones((5, 3)), + columns=pd.MultiIndex.from_arrays( + [[f"i-{i}" for i in range(3)] for _ in range(4)], names=list("abcd") + ), + index=pd.MultiIndex.from_arrays( + [[f"i-{i}" for i in range(5)] for _ in range(2)], names=list("ab") + ), + ) + df.to_csv(temp_file) + result = pd.read_csv(temp_file, header=[0, 1, 2, 3], index_col=[0, 1]) + tm.assert_frame_equal(df, result) + + # column is mi + df = pd.DataFrame( + np.ones((5, 3)), + columns=pd.MultiIndex.from_arrays( + [[f"i-{i}" for i in range(3)] for _ in range(4)], names=list("abcd") + ), + ) + df.to_csv(temp_file) + result = pd.read_csv(temp_file, header=[0, 1, 2, 3], index_col=0) + tm.assert_frame_equal(df, result) + + # dup column names? + df = pd.DataFrame( + np.ones((5, 3)), + columns=pd.MultiIndex.from_arrays( + [[f"i-{i}" for i in range(3)] for _ in range(4)], names=list("abcd") + ), + index=pd.MultiIndex.from_arrays( + [[f"i-{i}" for i in range(5)] for _ in range(3)], names=list("abc") + ), + ) + df.to_csv(temp_file) + result = pd.read_csv(temp_file, header=[0, 1, 2, 3], index_col=[0, 1, 2]) + tm.assert_frame_equal(df, result) + + # writing with no index + df = _make_frame() + df.to_csv(temp_file, index=False) + result = pd.read_csv(temp_file, header=[0, 1]) + tm.assert_frame_equal(df, result) + + # we lose the names here + df = _make_frame(True) + df.to_csv(temp_file, index=False) + result = pd.read_csv(temp_file, header=[0, 1]) + assert com.all_none(*result.columns.names) + result.columns.names = df.columns.names + tm.assert_frame_equal(df, result) + + # whatsnew example + df = _make_frame() + df.to_csv(temp_file) + result = pd.read_csv(temp_file, header=[0, 1], index_col=[0]) + tm.assert_frame_equal(df, result) + + df = _make_frame(True) + df.to_csv(temp_file) + result = pd.read_csv(temp_file, header=[0, 1], index_col=[0]) + tm.assert_frame_equal(df, result) + + # invalid options + df = _make_frame(True) + df.to_csv(temp_file) + + for i in [6, 7]: + msg = f"len of {i}, but only 5 lines in file" + with pytest.raises(ParserError, match=msg): + pd.read_csv(temp_file, header=list(range(i)), index_col=0) + + # write with cols + msg = "cannot specify cols with a MultiIndex" + with pytest.raises(TypeError, match=msg): + df.to_csv(temp_file, columns=["foo", "bar"]) + + # empty + tsframe[:0].to_csv(temp_file) + recons = self.read_csv(temp_file) + + exp = tsframe[:0] + exp.index = [] + + tm.assert_index_equal(recons.columns, exp.columns) + assert len(recons) == 0 + + def test_to_csv_interval_index(self, temp_file, using_infer_string): + # GH 28210 + df = pd.DataFrame( + {"A": list("abc"), "B": range(3)}, index=pd.interval_range(0, 3) + ) + + path = str(temp_file) + df.to_csv(path) + result = self.read_csv(path, index_col=0) + + # can't roundtrip intervalindex via read_csv so check string repr (GH 23595) + expected = df.copy() + expected.index = expected.index.astype("str") + + tm.assert_frame_equal(result, expected) + + def test_to_csv_float32_nanrep(self, temp_file): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((1, 4)).astype(np.float32) + ) + df[1] = np.nan + + path = str(temp_file) + df.to_csv(path, na_rep=999) + + with open(path, encoding="utf-8") as f: + lines = f.readlines() + assert lines[1].split(",")[2] == "999" + + def test_to_csv_withcommas(self, temp_file): + # Commas inside fields should be correctly escaped when saving as CSV. + df = pd.DataFrame({"A": [1, 2, 3], "B": ["5,6", "7,8", "9,0"]}) + + path = str(temp_file) + df.to_csv(path) + df2 = self.read_csv(path) + tm.assert_frame_equal(df2, df) + + def test_to_csv_mixed(self, temp_file): + def create_cols(name): + return [f"{name}{i:03d}" for i in range(5)] + + df_float = pd.DataFrame( + np.random.default_rng(2).standard_normal((100, 5)), + dtype="float64", + columns=create_cols("float"), + ) + df_int = pd.DataFrame( + np.random.default_rng(2).standard_normal((100, 5)).astype("int64"), + dtype="int64", + columns=create_cols("int"), + ) + df_bool = pd.DataFrame(True, index=df_float.index, columns=create_cols("bool")) + df_object = pd.DataFrame( + "foo", index=df_float.index, columns=create_cols("object"), dtype="object" + ) + df_dt = pd.DataFrame( + pd.Timestamp("20010101"), + index=df_float.index, + columns=create_cols("date"), + ) + + # add in some nans + df_float.iloc[30:50, 1:3] = np.nan + df_dt.iloc[30:50, 1:3] = np.nan + + df = pd.concat([df_float, df_int, df_bool, df_object, df_dt], axis=1) + + # dtype + dtypes = {} + for n, dtype in [ + ("float", np.float64), + ("int", np.int64), + ("bool", np.bool_), + ("object", object), + ]: + for c in create_cols(n): + dtypes[c] = dtype + + path = str(temp_file) + df.to_csv(path) + rs = pd.read_csv( + path, index_col=0, dtype=dtypes, parse_dates=create_cols("date") + ) + tm.assert_frame_equal(rs, df) + + def test_to_csv_dups_cols(self, temp_file): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((1000, 30)), + columns=list(range(15)) + list(range(15)), + dtype="float64", + ) + + path = str(temp_file) + df.to_csv(path) # single dtype, fine + result = pd.read_csv(path, index_col=0) + result.columns = df.columns + tm.assert_frame_equal(result, df) + + df_float = pd.DataFrame( + np.random.default_rng(2).standard_normal((1000, 3)), dtype="float64" + ) + df_int = pd.DataFrame( + np.random.default_rng(2).standard_normal((1000, 3)) + ).astype("int64") + df_bool = pd.DataFrame(True, index=df_float.index, columns=range(3)) + df_object = pd.DataFrame("foo", index=df_float.index, columns=range(3)) + df_dt = pd.DataFrame( + pd.Timestamp("20010101"), index=df_float.index, columns=range(3) + ) + df = pd.concat( + [df_float, df_int, df_bool, df_object, df_dt], axis=1, ignore_index=True + ) + + df.columns = [0, 1, 2] * 5 + + df.to_csv(temp_file) + result = pd.read_csv(temp_file, index_col=0) + + # date cols + for i in ["0.4", "1.4", "2.4"]: + result[i] = pd.to_datetime(result[i]) + + result.columns = df.columns + tm.assert_frame_equal(result, df) + + def test_to_csv_dups_cols2(self, temp_file): + # GH3457 + df = pd.DataFrame( + np.ones((5, 3)), + index=pd.Index([f"i-{i}" for i in range(5)], name="foo"), + columns=pd.Index(["a", "a", "b"]), + ) + + path = str(temp_file) + df.to_csv(path) + + # read_csv will rename the dups columns + result = pd.read_csv(path, index_col=0) + result = result.rename(columns={"a.1": "a"}) + tm.assert_frame_equal(result, df) + + @pytest.mark.parametrize("chunksize", [1, 5, 10]) + def test_to_csv_chunking(self, chunksize, temp_file): + aa = pd.DataFrame({"A": range(10)}) + aa["B"] = aa.A + 1.0 + aa["C"] = aa.A + 2.0 + aa["D"] = aa.A + 3.0 + + path = str(temp_file) + aa.to_csv(path, chunksize=chunksize) + rs = pd.read_csv(path, index_col=0) + tm.assert_frame_equal(rs, aa) + + @pytest.mark.slow + def test_to_csv_wide_frame_formatting(self, temp_file, monkeypatch): + # Issue #8621 + chunksize = 100 + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((1, chunksize + 10)), + columns=None, + index=None, + ) + path = str(temp_file) + with monkeypatch.context() as m: + m.setattr("pandas.io.formats.csvs._DEFAULT_CHUNKSIZE_CELLS", chunksize) + df.to_csv(path, header=False, index=False) + rs = pd.read_csv(path, header=None) + tm.assert_frame_equal(rs, df) + + def test_to_csv_bug(self, temp_file): + f1 = StringIO("a,1.0\nb,2.0") + df = self.read_csv(f1, header=None) + newdf = pd.DataFrame({"t": df[df.columns[0]]}) + + path = str(temp_file) + newdf.to_csv(path) + + recons = pd.read_csv(path, index_col=0) + # don't check_names as t != 1 + tm.assert_frame_equal(recons, newdf, check_names=False) + + def test_to_csv_unicode(self, temp_file): + df = pd.DataFrame({"c/\u03c3": [1, 2, 3]}) + path = str(temp_file) + df.to_csv(path, encoding="UTF-8") + df2 = pd.read_csv(path, index_col=0, encoding="UTF-8") + tm.assert_frame_equal(df, df2) + + df.to_csv(path, encoding="UTF-8", index=False) + df2 = pd.read_csv(path, index_col=None, encoding="UTF-8") + tm.assert_frame_equal(df, df2) + + def test_to_csv_unicode_index_col(self): + buf = StringIO("") + df = pd.DataFrame( + [["\u05d0", "d2", "d3", "d4"], ["a1", "a2", "a3", "a4"]], + columns=["\u05d0", "\u05d1", "\u05d2", "\u05d3"], + index=["\u05d0", "\u05d1"], + ) + + df.to_csv(buf, encoding="UTF-8") + buf.seek(0) + + df2 = pd.read_csv(buf, index_col=0, encoding="UTF-8") + tm.assert_frame_equal(df, df2) + + def test_to_csv_stringio(self, float_frame): + buf = StringIO() + float_frame.to_csv(buf) + buf.seek(0) + recons = pd.read_csv(buf, index_col=0) + tm.assert_frame_equal(recons, float_frame) + + def test_to_csv_float_format(self, temp_file): + df = pd.DataFrame( + [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + + path = str(temp_file) + df.to_csv(path, float_format="%.2f") + + rs = pd.read_csv(path, index_col=0) + xp = pd.DataFrame( + [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + tm.assert_frame_equal(rs, xp) + + def test_to_csv_float_format_over_decimal(self): + # GH#47436 + df = pd.DataFrame({"a": [0.5, 1.0]}) + result = df.to_csv( + decimal=",", + float_format=lambda x: np.format_float_positional(x, trim="-"), + index=False, + ) + expected_rows = ["a", "0.5", "1"] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected + + def test_to_csv_unicodewriter_quoting(self): + df = pd.DataFrame({"A": [1, 2, 3], "B": ["foo", "bar", "baz"]}) + + buf = StringIO() + df.to_csv(buf, index=False, quoting=csv.QUOTE_NONNUMERIC, encoding="utf-8") + + result = buf.getvalue() + expected_rows = ['"A","B"', '1,"foo"', '2,"bar"', '3,"baz"'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected + + @pytest.mark.parametrize("encoding", [None, "utf-8"]) + def test_to_csv_quote_none(self, encoding): + # GH4328 + df = pd.DataFrame({"A": ["hello", '{"hello"}']}) + buf = StringIO() + df.to_csv(buf, quoting=csv.QUOTE_NONE, encoding=encoding, index=False) + + result = buf.getvalue() + expected_rows = ["A", "hello", '{"hello"}'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected + + def test_to_csv_index_no_leading_comma(self): + df = pd.DataFrame( + {"A": [1, 2, 3], "B": [4, 5, 6]}, index=["one", "two", "three"] + ) + + buf = StringIO() + df.to_csv(buf, index_label=False) + + expected_rows = ["A,B", "one,1,4", "two,2,5", "three,3,6"] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert buf.getvalue() == expected + + def test_to_csv_lineterminators(self, temp_file): + # see gh-20353 + df = pd.DataFrame( + {"A": [1, 2, 3], "B": [4, 5, 6]}, index=["one", "two", "three"] + ) + + path = str(temp_file) + # case 1: CRLF as line terminator + df.to_csv(path, lineterminator="\r\n") + expected = b",A,B\r\none,1,4\r\ntwo,2,5\r\nthree,3,6\r\n" + + with open(path, mode="rb") as f: + assert f.read() == expected + + def test_to_csv_lineterminators2(self, temp_file): + # see gh-20353 + df = pd.DataFrame( + {"A": [1, 2, 3], "B": [4, 5, 6]}, index=["one", "two", "three"] + ) + + path = str(temp_file) + # case 2: LF as line terminator + df.to_csv(path, lineterminator="\n") + expected = b",A,B\none,1,4\ntwo,2,5\nthree,3,6\n" + + with open(path, mode="rb") as f: + assert f.read() == expected + + def test_to_csv_lineterminators3(self, temp_file): + # see gh-20353 + df = pd.DataFrame( + {"A": [1, 2, 3], "B": [4, 5, 6]}, index=["one", "two", "three"] + ) + path = str(temp_file) + # case 3: The default line terminator(=os.linesep)(gh-21406) + df.to_csv(path) + os_linesep = os.linesep.encode("utf-8") + expected = ( + b",A,B" + + os_linesep + + b"one,1,4" + + os_linesep + + b"two,2,5" + + os_linesep + + b"three,3,6" + + os_linesep + ) + + with open(path, mode="rb") as f: + assert f.read() == expected + + def test_to_csv_from_csv_categorical(self): + # CSV with categoricals should result in the same output + # as when one would add a "normal" Series/DataFrame. + s = pd.Series(pd.Categorical(["a", "b", "b", "a", "a", "c", "c", "c"])) + s2 = pd.Series(["a", "b", "b", "a", "a", "c", "c", "c"]) + res = StringIO() + + s.to_csv(res, header=False) + exp = StringIO() + + s2.to_csv(exp, header=False) + assert res.getvalue() == exp.getvalue() + + df = pd.DataFrame({"s": s}) + df2 = pd.DataFrame({"s": s2}) + + res = StringIO() + df.to_csv(res) + + exp = StringIO() + df2.to_csv(exp) + + assert res.getvalue() == exp.getvalue() + + def test_to_csv_path_is_none(self, float_frame): + # GH 8215 + # Make sure we return string for consistency with + # Series.to_csv() + csv_str = float_frame.to_csv(path_or_buf=None) + assert isinstance(csv_str, str) + recons = pd.read_csv(StringIO(csv_str), index_col=0) + tm.assert_frame_equal(float_frame, recons) + + @pytest.mark.parametrize( + "df,encoding", + [ + ( + pd.DataFrame( + [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ), + None, + ), + # GH 21241, 21118 + (pd.DataFrame([["abc", "def", "ghi"]], columns=["X", "Y", "Z"]), "ascii"), + ( + pd.DataFrame(5 * [[123, "你好", "世界"]], columns=["X", "Y", "Z"]), + "gb2312", + ), + ( + pd.DataFrame( + 5 * [[123, "Γειά σου", "Κόσμε"]], # noqa: RUF001 + columns=["X", "Y", "Z"], + ), + "cp737", + ), + ], + ) + def test_to_csv_compression(self, temp_file, df, encoding, compression): + path = str(temp_file) + df.to_csv(path, compression=compression, encoding=encoding) + # test the round trip - to_csv -> read_csv + result = pd.read_csv( + path, compression=compression, index_col=0, encoding=encoding + ) + tm.assert_frame_equal(df, result) + + # test the round trip using file handle - to_csv -> read_csv + with get_handle( + path, "w", compression=compression, encoding=encoding + ) as handles: + df.to_csv(handles.handle, encoding=encoding) + assert not handles.handle.closed + + result = pd.read_csv( + path, + compression=compression, + encoding=encoding, + index_col=0, + ).squeeze("columns") + tm.assert_frame_equal(df, result) + + # explicitly make sure file is compressed + with tm.decompress_file(path, compression) as fh: + text = fh.read().decode(encoding or "utf8") + for col in df.columns: + assert col in text + + with tm.decompress_file(path, compression) as fh: + tm.assert_frame_equal(df, pd.read_csv(fh, index_col=0, encoding=encoding)) + + def test_to_csv_date_format(self, temp_file, datetime_frame): + path = str(temp_file) + dt_index = datetime_frame.index + datetime_frame = pd.DataFrame( + {"A": dt_index, "B": dt_index.shift(1)}, index=dt_index + ) + datetime_frame.to_csv(path, date_format="%Y%m%d") + + # Check that the data was put in the specified format + test = pd.read_csv(path, index_col=0) + + datetime_frame_int = datetime_frame.map(lambda x: int(x.strftime("%Y%m%d"))) + datetime_frame_int.index = datetime_frame_int.index.map( + lambda x: int(x.strftime("%Y%m%d")) + ) + + tm.assert_frame_equal(test, datetime_frame_int) + + datetime_frame.to_csv(path, date_format="%Y-%m-%d") + + # Check that the data was put in the specified format + test = pd.read_csv(path, index_col=0) + datetime_frame_str = datetime_frame.map(lambda x: x.strftime("%Y-%m-%d")) + datetime_frame_str.index = datetime_frame_str.index.map( + lambda x: x.strftime("%Y-%m-%d") + ) + + tm.assert_frame_equal(test, datetime_frame_str) + + # Check that columns get converted + datetime_frame_columns = datetime_frame.T + datetime_frame_columns.to_csv(path, date_format="%Y%m%d") + + test = pd.read_csv(path, index_col=0) + + datetime_frame_columns = datetime_frame_columns.map( + lambda x: int(x.strftime("%Y%m%d")) + ) + # Columns don't get converted to ints by read_csv + datetime_frame_columns.columns = datetime_frame_columns.columns.map( + lambda x: x.strftime("%Y%m%d") + ) + + tm.assert_frame_equal(test, datetime_frame_columns) + + # test NaTs + nat_index = pd.to_datetime( + ["NaT"] * 10 + ["2000-01-01", "2000-01-01", "2000-01-01"] + ) + nat_frame = pd.DataFrame({"A": nat_index}, index=nat_index) + nat_frame.to_csv(path, date_format="%Y-%m-%d") + + test = pd.read_csv(path, parse_dates=[0, 1], index_col=0) + + tm.assert_frame_equal(test, nat_frame) + + @pytest.mark.parametrize("td", [pd.Timedelta(0).as_unit("us"), pd.Timedelta("10s")]) + def test_to_csv_with_dst_transitions(self, td, temp_file): + path = str(temp_file) + # make sure we are not failing on transitions + times = pd.date_range( + "2013-10-26 23:00", + "2013-10-27 01:00", + tz="Europe/London", + freq="h", + ambiguous="infer", + ) + i = times + td + i = i._with_freq(None) # freq is not preserved by read_csv + time_range = np.array(range(len(i)), dtype="int64") + df = pd.DataFrame({"A": time_range}, index=i) + df.to_csv(path, index=True) + # we have to reconvert the index as we + # don't parse the tz's + result = pd.read_csv(path, index_col=0) + result.index = pd.to_datetime(result.index, utc=True).tz_convert( + "Europe/London" + ) + tm.assert_frame_equal(result, df) + + @pytest.mark.parametrize( + "start,end", + [ + ["2015-03-29", "2015-03-30"], + ["2015-10-25", "2015-10-26"], + ], + ) + def test_to_csv_with_dst_transitions_with_pickle(self, start, end, temp_file): + # GH11619 + idx = pd.date_range(start, end, freq="h", tz="Europe/Paris", unit="ns") + idx = idx._with_freq(None) # freq does not round-trip + df = pd.DataFrame({"values": 1, "idx": idx}, index=idx) + + df.to_csv(temp_file, index=True) + result = pd.read_csv(temp_file, index_col=0) + result.index = ( + pd.to_datetime(result.index, utc=True) + .tz_convert("Europe/Paris") + .as_unit("ns") + ) + result["idx"] = pd.to_datetime(result["idx"], utc=True).astype( + "datetime64[ns, Europe/Paris]" + ) + tm.assert_frame_equal(result, df) + + # assert working + df.astype(str) + + path = str(temp_file) + df.to_pickle(path) + result = pd.read_pickle(path) + tm.assert_frame_equal(result, df) + + def test_to_csv_quoting(self): + df = pd.DataFrame( + { + "c_bool": [True, False], + "c_float": [1.0, 3.2], + "c_int": [42, np.nan], + "c_string": ["a", "b,c"], + } + ) + + expected_rows = [ + ",c_bool,c_float,c_int,c_string", + "0,True,1.0,42.0,a", + '1,False,3.2,,"b,c"', + ] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + + result = df.to_csv() + assert result == expected + + result = df.to_csv(quoting=None) + assert result == expected + + expected_rows = [ + ",c_bool,c_float,c_int,c_string", + "0,True,1.0,42.0,a", + '1,False,3.2,,"b,c"', + ] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + + result = df.to_csv(quoting=csv.QUOTE_MINIMAL) + assert result == expected + + expected_rows = [ + '"","c_bool","c_float","c_int","c_string"', + '"0","True","1.0","42.0","a"', + '"1","False","3.2","","b,c"', + ] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + + result = df.to_csv(quoting=csv.QUOTE_ALL) + assert result == expected + + # see gh-12922, gh-13259: make sure changes to + # the formatters do not break this behaviour + expected_rows = [ + '"","c_bool","c_float","c_int","c_string"', + '0,True,1.0,42.0,"a"', + '1,False,3.2,"","b,c"', + ] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + result = df.to_csv(quoting=csv.QUOTE_NONNUMERIC) + assert result == expected + + msg = "need to escape, but no escapechar set" + with pytest.raises(csv.Error, match=msg): + df.to_csv(quoting=csv.QUOTE_NONE) + + with pytest.raises(csv.Error, match=msg): + df.to_csv(quoting=csv.QUOTE_NONE, escapechar=None) + + expected_rows = [ + ",c_bool,c_float,c_int,c_string", + "0,True,1.0,42.0,a", + "1,False,3.2,,b!,c", + ] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + result = df.to_csv(quoting=csv.QUOTE_NONE, escapechar="!") + assert result == expected + + expected_rows = [ + ",c_bool,c_ffloat,c_int,c_string", + "0,True,1.0,42.0,a", + "1,False,3.2,,bf,c", + ] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + result = df.to_csv(quoting=csv.QUOTE_NONE, escapechar="f") + assert result == expected + + # see gh-3503: quoting Windows line terminators + # presents with encoding? + text_rows = ["a,b,c", '1,"test \r\n",3'] + text = tm.convert_rows_list_to_csv_str(text_rows) + df = pd.read_csv(StringIO(text)) + + buf = StringIO() + df.to_csv(buf, encoding="utf-8", index=False) + assert buf.getvalue() == text + + # xref gh-7791: make sure the quoting parameter is passed through + # with multi-indexes + df = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}) + df = df.set_index(["a", "b"]) + + expected_rows = ['"a","b","c"', '"1","3","5"', '"2","4","6"'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert df.to_csv(quoting=csv.QUOTE_ALL) == expected + + def test_period_index_date_overflow(self): + # see gh-15982 + + dates = ["1990-01-01", "2000-01-01", "3005-01-01"] + index = pd.PeriodIndex(dates, freq="D") + + df = pd.DataFrame([4, 5, 6], index=index) + result = df.to_csv() + + expected_rows = [",0", "1990-01-01,4", "2000-01-01,5", "3005-01-01,6"] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected + + date_format = "%m-%d-%Y" + result = df.to_csv(date_format=date_format) + + expected_rows = [",0", "01-01-1990,4", "01-01-2000,5", "01-01-3005,6"] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected + + # Overflow with pd.NaT + dates = ["1990-01-01", pd.NaT, "3005-01-01"] + index = pd.PeriodIndex(dates, freq="D") + + df = pd.DataFrame([4, 5, 6], index=index) + result = df.to_csv() + + expected_rows = [",0", "1990-01-01,4", ",5", "3005-01-01,6"] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected + + def test_multi_index_header(self): + # see gh-5539 + columns = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), ("b", 2)]) + df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]]) + df.columns = columns + + header = ["a", "b", "c", "d"] + result = df.to_csv(header=header) + + expected_rows = [",a,b,c,d", "0,1,2,3,4", "1,5,6,7,8"] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected + + def test_to_csv_single_level_multi_index(self): + # see gh-26303 + index = pd.Index([(1,), (2,), (3,)]) + df = pd.DataFrame([[1, 2, 3]], columns=index) + df = df.reindex(columns=[(1,), (3,)]) + expected = ",1,3\n0,1,3\n" + result = df.to_csv(lineterminator="\n") + tm.assert_almost_equal(result, expected) + + def test_gz_lineend(self, tmp_path): + # GH 25311 + df = pd.DataFrame({"a": [1, 2]}) + expected_rows = ["a", "1", "2"] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + file_path = tmp_path / "__test_gz_lineend.csv.gz" + file_path.touch() + path = str(file_path) + df.to_csv(path, index=False) + with tm.decompress_file(path, compression="gzip") as f: + result = f.read().decode("utf-8") + + assert result == expected + + def test_to_csv_numpy_16_bug(self): + frame = pd.DataFrame({"a": pd.date_range("1/1/2000", periods=10)}) + + buf = StringIO() + frame.to_csv(buf) + + result = buf.getvalue() + assert "2000-01-01" in result + + def test_to_csv_na_quoting(self): + # GH 15891 + # Normalize carriage return for Windows OS + result = ( + pd.DataFrame([None, None]) + .to_csv(None, header=False, index=False, na_rep="") + .replace("\r\n", "\n") + ) + expected = '""\n""\n' + assert result == expected + + def test_to_csv_categorical_and_ea(self): + # GH#46812 + df = pd.DataFrame({"a": "x", "b": [1, pd.NA]}) + df["b"] = df["b"].astype("Int16") + df["b"] = df["b"].astype("category") + result = df.to_csv() + expected_rows = [",a,b", "0,x,1", "1,x,"] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected + + def test_to_csv_categorical_and_interval(self): + # GH#46297 + df = pd.DataFrame( + { + "a": [ + pd.Interval( + pd.Timestamp("2020-01-01"), + pd.Timestamp("2020-01-02"), + closed="both", + ) + ] + } + ) + df["a"] = df["a"].astype("category") + result = df.to_csv() + expected_rows = [",a", '0,"[2020-01-01 00:00:00, 2020-01-02 00:00:00]"'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected + + def test_to_csv_warn_when_zip_tar_and_append_mode(self, tmp_path): + # GH57875 + df = pd.DataFrame({"a": [1, 2, 3]}) + msg = ( + "zip and tar do not support mode 'a' properly. This combination will " + "result in multiple files with same name being added to the archive" + ) + zip_path = tmp_path / "test.zip" + tar_path = tmp_path / "test.tar" + with tm.assert_produces_warning( + RuntimeWarning, match=msg, raise_on_extra_warnings=False + ): + df.to_csv(zip_path, mode="a") + + with tm.assert_produces_warning( + RuntimeWarning, match=msg, raise_on_extra_warnings=False + ): + df.to_csv(tar_path, mode="a") + + def test_to_csv_escape_quotechar(self): + # GH61514 + df = pd.DataFrame( + { + "col_a": ["a", "a2"], + "col_b": ['b"c', None], + "col_c": ['de,f"', '"c'], + } + ) + + result = df.to_csv(quotechar='"', escapechar="\\", quoting=csv.QUOTE_NONE) + expected_rows = [ + ",col_a,col_b,col_c", + '0,a,b\\"c,de\\,f\\"', + '1,a2,,\\"c', + ] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert result == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_dict.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..d5fe06f95f814f6fadfbaf54e9f806eb5316aa12 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_dict.py @@ -0,0 +1,571 @@ +from collections import ( + OrderedDict, + defaultdict, +) +from datetime import ( + UTC, + datetime, +) + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameToDict: + def test_to_dict_timestamp(self): + # GH#11247 + # split/records producing np.datetime64 rather than Timestamps + # on datetime64[ns] dtypes only + + tsmp = pd.Timestamp("20130101") + test_data = pd.DataFrame({"A": [tsmp, tsmp], "B": [tsmp, tsmp]}) + test_data_mixed = pd.DataFrame({"A": [tsmp, tsmp], "B": [1, 2]}) + + expected_records = [{"A": tsmp, "B": tsmp}, {"A": tsmp, "B": tsmp}] + expected_records_mixed = [{"A": tsmp, "B": 1}, {"A": tsmp, "B": 2}] + + assert test_data.to_dict(orient="records") == expected_records + assert test_data_mixed.to_dict(orient="records") == expected_records_mixed + + expected_series = { + "A": pd.Series([tsmp, tsmp], name="A"), + "B": pd.Series([tsmp, tsmp], name="B"), + } + expected_series_mixed = { + "A": pd.Series([tsmp, tsmp], name="A"), + "B": pd.Series([1, 2], name="B"), + } + + tm.assert_dict_equal(test_data.to_dict(orient="series"), expected_series) + tm.assert_dict_equal( + test_data_mixed.to_dict(orient="series"), expected_series_mixed + ) + + expected_split = { + "index": [0, 1], + "data": [[tsmp, tsmp], [tsmp, tsmp]], + "columns": ["A", "B"], + } + expected_split_mixed = { + "index": [0, 1], + "data": [[tsmp, 1], [tsmp, 2]], + "columns": ["A", "B"], + } + + tm.assert_dict_equal(test_data.to_dict(orient="split"), expected_split) + tm.assert_dict_equal( + test_data_mixed.to_dict(orient="split"), expected_split_mixed + ) + + def test_to_dict_index_not_unique_with_index_orient(self): + # GH#22801 + # Data loss when indexes are not unique. Raise ValueError. + df = pd.DataFrame({"a": [1, 2], "b": [0.5, 0.75]}, index=["A", "A"]) + msg = "DataFrame index must be unique for orient='index'" + with pytest.raises(ValueError, match=msg): + df.to_dict(orient="index") + + def test_to_dict_invalid_orient(self): + df = pd.DataFrame({"A": [0, 1]}) + msg = "orient 'xinvalid' not understood" + with pytest.raises(ValueError, match=msg): + df.to_dict(orient="xinvalid") + + @pytest.mark.parametrize("orient", ["d", "l", "r", "sp", "s", "i"]) + def test_to_dict_short_orient_raises(self, orient): + # GH#32515 + df = pd.DataFrame({"A": [0, 1]}) + with pytest.raises(ValueError, match="not understood"): + df.to_dict(orient=orient) + + @pytest.mark.parametrize("mapping", [dict, defaultdict(list), OrderedDict]) + def test_to_dict(self, mapping): + # orient= should only take the listed options + # see GH#32515 + test_data = {"A": {"1": 1, "2": 2}, "B": {"1": "1", "2": "2", "3": "3"}} + + # GH#16122 + recons_data = pd.DataFrame(test_data).to_dict(into=mapping) + + for k, v in test_data.items(): + for k2, v2 in v.items(): + assert v2 == recons_data[k][k2] + + recons_data = pd.DataFrame(test_data).to_dict("list", into=mapping) + + for k, v in test_data.items(): + for k2, v2 in v.items(): + assert v2 == recons_data[k][int(k2) - 1] + + recons_data = pd.DataFrame(test_data).to_dict("series", into=mapping) + + for k, v in test_data.items(): + for k2, v2 in v.items(): + assert v2 == recons_data[k][k2] + + recons_data = pd.DataFrame(test_data).to_dict("split", into=mapping) + expected_split = { + "columns": ["A", "B"], + "index": ["1", "2", "3"], + "data": [[1.0, "1"], [2.0, "2"], [np.nan, "3"]], + } + tm.assert_dict_equal(recons_data, expected_split) + + recons_data = pd.DataFrame(test_data).to_dict("records", into=mapping) + expected_records = [ + {"A": 1.0, "B": "1"}, + {"A": 2.0, "B": "2"}, + {"A": np.nan, "B": "3"}, + ] + assert isinstance(recons_data, list) + assert len(recons_data) == 3 + for left, right in zip(recons_data, expected_records, strict=True): + tm.assert_dict_equal(left, right) + + # GH#10844 + recons_data = pd.DataFrame(test_data).to_dict("index") + + for k, v in test_data.items(): + for k2, v2 in v.items(): + assert v2 == recons_data[k2][k] + + df = pd.DataFrame(test_data) + df["duped"] = df[df.columns[0]] + recons_data = df.to_dict("index") + comp_data = test_data.copy() + comp_data["duped"] = comp_data[df.columns[0]] + for k, v in comp_data.items(): + for k2, v2 in v.items(): + assert v2 == recons_data[k2][k] + + @pytest.mark.parametrize("mapping", [list, defaultdict, []]) + def test_to_dict_errors(self, mapping): + # GH#16122 + df = pd.DataFrame(np.random.default_rng(2).standard_normal((3, 3))) + msg = "|".join( + [ + "unsupported type: ", + r"to_dict\(\) only accepts initialized defaultdicts", + ] + ) + with pytest.raises(TypeError, match=msg): + df.to_dict(into=mapping) + + def test_to_dict_not_unique_warning(self): + # GH#16927: When converting to a dict, if a column has a non-unique name + # it will be dropped, throwing a warning. + df = pd.DataFrame([[1, 2, 3]], columns=["a", "a", "b"]) + with tm.assert_produces_warning(UserWarning, match="columns will be omitted"): + df.to_dict() + + @pytest.mark.filterwarnings("ignore::UserWarning") + @pytest.mark.parametrize( + "orient,expected", + [ + ("list", {"A": [2, 5], "B": [3, 6]}), + ("dict", {"A": {0: 2, 1: 5}, "B": {0: 3, 1: 6}}), + ], + ) + def test_to_dict_not_unique(self, orient, expected): + # GH#54824: This is to make sure that dataframes with non-unique column + # would have uniform behavior throughout different orients + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "A", "B"]) + result = df.to_dict(orient) + assert result == expected + + # orient - orient argument to to_dict function + # item_getter - function for extracting value from + # the resulting dict using column name and index + @pytest.mark.parametrize( + "orient,item_getter", + [ + ("dict", lambda d, col, idx: d[col][idx]), + ("records", lambda d, col, idx: d[idx][col]), + ("list", lambda d, col, idx: d[col][idx]), + ("split", lambda d, col, idx: d["data"][idx][d["columns"].index(col)]), + ("index", lambda d, col, idx: d[idx][col]), + ], + ) + def test_to_dict_box_scalars(self, orient, item_getter): + # GH#14216, GH#23753 + # make sure that we are boxing properly + df = pd.DataFrame({"a": [1, 2], "b": [0.1, 0.2]}) + result = df.to_dict(orient=orient) + assert isinstance(item_getter(result, "a", 0), int) + assert isinstance(item_getter(result, "b", 0), float) + + def test_to_dict_tz(self): + # GH#18372 When converting to dict with orient='records' columns of + # datetime that are tz-aware were not converted to required arrays + data = [ + (datetime(2017, 11, 18, 21, 53, 0, 219225, tzinfo=UTC),), + (datetime(2017, 11, 18, 22, 6, 30, 61810, tzinfo=UTC),), + ] + df = pd.DataFrame(list(data), columns=["d"]) + + result = df.to_dict(orient="records") + expected = [ + {"d": pd.Timestamp("2017-11-18 21:53:00.219225+0000", tz=UTC)}, + {"d": pd.Timestamp("2017-11-18 22:06:30.061810+0000", tz=UTC)}, + ] + tm.assert_dict_equal(result[0], expected[0]) + tm.assert_dict_equal(result[1], expected[1]) + + @pytest.mark.parametrize( + "into, expected", + [ + ( + dict, + { + 0: {"int_col": 1, "float_col": 1.0}, + 1: {"int_col": 2, "float_col": 2.0}, + 2: {"int_col": 3, "float_col": 3.0}, + }, + ), + ( + OrderedDict, + OrderedDict( + [ + (0, {"int_col": 1, "float_col": 1.0}), + (1, {"int_col": 2, "float_col": 2.0}), + (2, {"int_col": 3, "float_col": 3.0}), + ] + ), + ), + ( + defaultdict(dict), + defaultdict( + dict, + { + 0: {"int_col": 1, "float_col": 1.0}, + 1: {"int_col": 2, "float_col": 2.0}, + 2: {"int_col": 3, "float_col": 3.0}, + }, + ), + ), + ], + ) + def test_to_dict_index_dtypes(self, into, expected): + # GH#18580 + # When using to_dict(orient='index') on a dataframe with int + # and float columns only the int columns were cast to float + + df = pd.DataFrame({"int_col": [1, 2, 3], "float_col": [1.0, 2.0, 3.0]}) + + result = df.to_dict(orient="index", into=into) + cols = ["int_col", "float_col"] + result = pd.DataFrame.from_dict(result, orient="index")[cols] + expected = pd.DataFrame.from_dict(expected, orient="index")[cols] + tm.assert_frame_equal(result, expected) + + def test_to_dict_numeric_names(self): + # GH#24940 + df = pd.DataFrame({str(i): [i] for i in range(5)}) + result = set(df.to_dict("records")[0].keys()) + expected = set(df.columns) + assert result == expected + + def test_to_dict_wide(self): + # GH#24939 + df = pd.DataFrame({(f"A_{i:d}"): [i] for i in range(256)}) + result = df.to_dict("records")[0] + expected = {f"A_{i:d}": i for i in range(256)} + assert result == expected + + @pytest.mark.parametrize( + "data,dtype", + ( + ([True, True, False], bool), + [ + [ + datetime(2018, 1, 1), + datetime(2019, 2, 2), + datetime(2020, 3, 3), + ], + pd.Timestamp, + ], + [[1.0, 2.0, 3.0], float], + [[1, 2, 3], int], + [["X", "Y", "Z"], str], + ), + ) + def test_to_dict_orient_dtype(self, data, dtype): + # GH22620 & GH21256 + + df = pd.DataFrame({"a": data}) + d = df.to_dict(orient="records") + assert all(type(record["a"]) is dtype for record in d) + + @pytest.mark.parametrize( + "data,expected_dtype", + ( + [np.uint64(2), int], + [np.int64(-9), int], + [np.float64(1.1), float], + [np.bool_(True), bool], + [np.datetime64("2005-02-25"), pd.Timestamp], + ), + ) + def test_to_dict_scalar_constructor_orient_dtype(self, data, expected_dtype): + # GH22620 & GH21256 + + df = pd.DataFrame({"a": data}, index=[0]) + d = df.to_dict(orient="records") + result = type(d[0]["a"]) + assert result is expected_dtype + + def test_to_dict_mixed_numeric_frame(self): + # GH 12859 + df = pd.DataFrame({"a": [1.0], "b": [9.0]}) + result = df.reset_index().to_dict("records") + expected = [{"index": 0, "a": 1.0, "b": 9.0}] + assert result == expected + + @pytest.mark.parametrize( + "index", + [ + None, + pd.Index(["aa", "bb"]), + pd.Index(["aa", "bb"], name="cc"), + pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")]), + pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")], names=["n1", "n2"]), + ], + ) + @pytest.mark.parametrize( + "columns", + [ + ["x", "y"], + pd.Index(["x", "y"]), + pd.Index(["x", "y"], name="z"), + pd.MultiIndex.from_tuples([("x", 1), ("y", 2)]), + pd.MultiIndex.from_tuples([("x", 1), ("y", 2)], names=["z1", "z2"]), + ], + ) + def test_to_dict_orient_tight(self, index, columns): + df = pd.DataFrame.from_records( + [[1, 3], [2, 4]], + columns=columns, + index=index, + ) + roundtrip = pd.DataFrame.from_dict(df.to_dict(orient="tight"), orient="tight") + + tm.assert_frame_equal(df, roundtrip) + + @pytest.mark.parametrize( + "orient", + ["dict", "list", "split", "records", "index", "tight"], + ) + @pytest.mark.parametrize( + "data,expected_types", + ( + ( + { + "a": [np.int64(1), 1, np.int64(3)], + "b": [np.float64(1.0), 2.0, np.float64(3.0)], + "c": [np.float64(1.0), 2, np.int64(3)], + "d": [np.float64(1.0), "a", np.int64(3)], + "e": [np.float64(1.0), ["a"], np.int64(3)], + "f": [np.float64(1.0), ("a",), np.int64(3)], + }, + { + "a": [int, int, int], + "b": [float, float, float], + "c": [float, float, float], + "d": [float, str, int], + "e": [float, list, int], + "f": [float, tuple, int], + }, + ), + ( + { + "a": [1, 2, 3], + "b": [1.1, 2.2, 3.3], + }, + { + "a": [int, int, int], + "b": [float, float, float], + }, + ), + ( # Make sure we have one df which is all object type cols + { + "a": [1, "hello", 3], + "b": [1.1, "world", 3.3], + }, + { + "a": [int, str, int], + "b": [float, str, float], + }, + ), + ), + ) + def test_to_dict_returns_native_types(self, orient, data, expected_types): + # GH 46751 + # Tests we get back native types for all orient types + df = pd.DataFrame(data) + result = df.to_dict(orient) + if orient == "dict": + assertion_iterator = ( + (i, key, value) + for key, index_value_map in result.items() + for i, value in index_value_map.items() + ) + elif orient == "list": + assertion_iterator = ( + (i, key, value) + for key, values in result.items() + for i, value in enumerate(values) + ) + elif orient in {"split", "tight"}: + assertion_iterator = ( + (i, key, result["data"][i][j]) + for i in result["index"] + for j, key in enumerate(result["columns"]) + ) + elif orient == "records": + assertion_iterator = ( + (i, key, value) + for i, record in enumerate(result) + for key, value in record.items() + ) + elif orient == "index": + assertion_iterator = ( + (i, key, value) + for i, record in result.items() + for key, value in record.items() + ) + + for i, key, value in assertion_iterator: + assert value == data[key][i] + assert type(value) is expected_types[key][i] + + @pytest.mark.parametrize("orient", ["dict", "list", "series", "records", "index"]) + def test_to_dict_index_false_error(self, orient): + # GH#46398 + df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}, index=["row1", "row2"]) + msg = "'index=False' is only valid when 'orient' is 'split' or 'tight'" + with pytest.raises(ValueError, match=msg): + df.to_dict(orient=orient, index=False) + + @pytest.mark.parametrize( + "orient, expected", + [ + ("split", {"columns": ["col1", "col2"], "data": [[1, 3], [2, 4]]}), + ( + "tight", + { + "columns": ["col1", "col2"], + "data": [[1, 3], [2, 4]], + "column_names": [None], + }, + ), + ], + ) + def test_to_dict_index_false(self, orient, expected): + # GH#46398 + df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}, index=["row1", "row2"]) + result = df.to_dict(orient=orient, index=False) + tm.assert_dict_equal(result, expected) + + @pytest.mark.parametrize( + "orient, expected", + [ + ("dict", {"a": {0: 1, 1: None}}), + ("list", {"a": [1, None]}), + ("split", {"index": [0, 1], "columns": ["a"], "data": [[1], [None]]}), + ( + "tight", + { + "index": [0, 1], + "columns": ["a"], + "data": [[1], [None]], + "index_names": [None], + "column_names": [None], + }, + ), + ("records", [{"a": 1}, {"a": None}]), + ("index", {0: {"a": 1}, 1: {"a": None}}), + ], + ) + def test_to_dict_na_to_none(self, orient, expected): + # GH#50795 + df = pd.DataFrame({"a": [1, pd.NA]}, dtype="Int64") + result = df.to_dict(orient=orient) + assert result == expected + + def test_to_dict_masked_native_python(self): + # GH#34665 + df = pd.DataFrame({"a": pd.Series([1, 2], dtype="Int64"), "B": 1}) + result = df.to_dict(orient="records") + assert isinstance(result[0]["a"], int) + + df = pd.DataFrame({"a": pd.Series([1, pd.NA], dtype="Int64"), "B": 1}) + result = df.to_dict(orient="records") + assert isinstance(result[0]["a"], int) + + def test_to_dict_tight_no_warning_with_duplicate_column(self): + # GH#58281 + df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "A"]) + with tm.assert_produces_warning(None): + result = df.to_dict(orient="tight") + expected = { + "index": [0, 1, 2], + "columns": ["A", "A"], + "data": [[1, 2], [3, 4], [5, 6]], + "index_names": [None], + "column_names": [None], + } + assert result == expected + + @pytest.mark.parametrize( + "df", + [ + pd.DataFrame({"B": ["x", "y"], "A": ["a", "b"]}), # all EA cols + pd.DataFrame({"B": [1, 2], "A": ["x", "y"]}), # mixed EA/non-EA + pd.DataFrame({"B": [1, 2], "A": [3, 4]}), # no EA cols + ], + ) + def test_to_dict_index_into_applies_to_nested_mappings(self, df: pd.DataFrame): + # https://github.com/pandas-dev/pandas/issues/65778 + + result = df.to_dict(orient="index", into=OrderedDict) + + assert isinstance(result, OrderedDict) + assert all(isinstance(row, OrderedDict) for row in result.values()) + + +@pytest.mark.parametrize( + "val", + [pd.Timestamp(2020, 1, 1), pd.Timedelta(1), pd.Period("2020"), pd.Interval(1, 2)], +) +def test_to_dict_list_pd_scalars(val): + # GH 54824 + df = pd.DataFrame({"a": [val]}) + result = df.to_dict(orient="list") + expected = {"a": [val]} + assert result == expected + + +@pytest.mark.parametrize( + "orient, expected", + [ + ("split", {"index": ["A", "B"], "columns": [], "data": [[], []]}), + ( + "tight", + { + "index": ["A", "B"], + "columns": [], + "data": [[], []], + "index_names": [None], + "column_names": [None], + }, + ), + ("records", [{}, {}]), + ], +) +def test_to_dict_no_columns(orient, expected): + # GH#25408 + df = pd.DataFrame(index=["A", "B"]) + assert df.to_dict(orient=orient) == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_dict_of_blocks.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_dict_of_blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf3560037c8b608832824348296b4d482dbe5e3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_dict_of_blocks.py @@ -0,0 +1,32 @@ +import pandas as pd +import pandas._testing as tm + + +class TestToDictOfBlocks: + def test_no_copy_blocks(self, float_frame): + # GH#9607 + df = pd.DataFrame(float_frame, copy=True) + column = df.columns[0] + + _last_df = None + # use the copy=False, change a column + blocks = df._to_dict_of_blocks() + for _df in blocks.values(): + _last_df = _df + if column in _df: + _df.loc[:, column] = _df[column] + 1 + assert _last_df is not None and not _last_df[column].equals(df[column]) + + +def test_set_change_dtype_slice(): + # GH#8850 + cols = pd.MultiIndex.from_tuples([("1st", "a"), ("2nd", "b"), ("3rd", "c")]) + df = pd.DataFrame([[1.0, 2, 3], [4.0, 5, 6]], columns=cols) + df["2nd"] = df["2nd"] * 2.0 + + blocks = df._to_dict_of_blocks() + assert sorted(blocks.keys()) == ["float64", "int64"] + tm.assert_frame_equal( + blocks["float64"], pd.DataFrame([[1.0, 4.0], [4.0, 10.0]], columns=cols[:2]) + ) + tm.assert_frame_equal(blocks["int64"], pd.DataFrame([[3], [6]], columns=cols[2:])) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_numpy.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..8f7e6b121e5ef1d8a7f442ed8dcd8f13046457a2 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_numpy.py @@ -0,0 +1,91 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestToNumpy: + def test_to_numpy(self): + df = pd.DataFrame({"A": [1, 2], "B": [3, 4.5]}) + expected = np.array([[1, 3], [2, 4.5]]) + result = df.to_numpy() + tm.assert_numpy_array_equal(result, expected) + + def test_to_numpy_dtype(self): + df = pd.DataFrame({"A": [1, 2], "B": [3, 4.5]}) + expected = np.array([[1, 3], [2, 4]], dtype="int64") + result = df.to_numpy(dtype="int64") + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "data, dtype", + [ + ({"a": [1, 2, 3]}, "Int64"), + ({"a": [1, 2, 3], "b": [4, 5, 6]}, "Int64"), + ({"a": [1, 2, 3]}, "int64"), + ], + ) + def test_to_numpy_na_value_no_missing(self, data, dtype): + # GH#56233 assigning na_value is a no-op when there is no NA, even + # when the na_value cannot be cast to the target dtype + df = pd.DataFrame(data, dtype=dtype) + result = df.to_numpy(na_value=float("nan")) + expected = df.to_numpy() + tm.assert_numpy_array_equal(result, expected) + + def test_to_numpy_copy(self): + arr = np.random.default_rng(2).standard_normal((4, 3)) + df = pd.DataFrame(arr) + assert df.values.base is not arr + assert df.to_numpy(copy=False).base is df.values.base + assert df.to_numpy(copy=True).base is not arr + + # we still don't want a copy when na_value=np.nan is passed, + # and that can be respected because we are already numpy-float + assert df.to_numpy(copy=False).base is df.values.base + + def test_to_numpy_mixed_dtype_to_str(self): + # https://github.com/pandas-dev/pandas/issues/35455 + df = pd.DataFrame([[pd.Timestamp("2020-01-01 00:00:00"), 100.0]]) + result = df.to_numpy(dtype=str) + expected = np.array([["2020-01-01 00:00:00", "100.0"]], dtype=str) + tm.assert_numpy_array_equal(result, expected) + + def test_to_numpy_datetime_with_na(self): + # GH #53115 + dti = pd.date_range("2016-01-01", periods=3, unit="ns") + df = pd.DataFrame(dti) + df.iloc[0, 0] = pd.NaT + expected = np.array([[np.nan], [1.45169280e18], [1.45177920e18]]) + result = df.to_numpy(float, na_value=np.nan) + tm.assert_numpy_array_equal(result, expected) + + df = pd.DataFrame( + { + "a": [ + pd.Timestamp("1970-01-01").as_unit("s"), + pd.Timestamp("1970-01-02").as_unit("s"), + pd.NaT, + ], + "b": [ + pd.Timestamp("1970-01-01").as_unit("s"), + np.nan, + pd.Timestamp("1970-01-02").as_unit("s"), + ], + "c": [ + 1, + np.nan, + 2, + ], + } + ) + expected = np.array( + [ + [0.00e00, 0.00e00, 1.00e00], + [8.64e04, np.nan, np.nan], + [np.nan, 8.64e04, 2.00e00], + ] + ) + result = df.to_numpy(float, na_value=np.nan) + tm.assert_numpy_array_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_period.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_period.py new file mode 100644 index 0000000000000000000000000000000000000000..440a7d583bc40ad4392d1d328467c24fa3c1ca29 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_period.py @@ -0,0 +1,86 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestToPeriod: + def test_to_period(self, frame_or_series): + K = 5 + + dr = pd.date_range("1/1/2000", "1/1/2001", freq="D") + obj = pd.DataFrame( + np.random.default_rng(2).standard_normal((len(dr), K)), + index=dr, + columns=["A", "B", "C", "D", "E"], + ) + obj["mix"] = "a" + obj = tm.get_obj(obj, frame_or_series) + + pts = obj.to_period() + exp = obj.copy() + exp.index = pd.period_range("1/1/2000", "1/1/2001") + tm.assert_equal(pts, exp) + + pts = obj.to_period("M") + exp.index = exp.index.asfreq("M") + tm.assert_equal(pts, exp) + + def test_to_period_without_freq(self, frame_or_series): + # GH#7606 without freq + idx = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"]) + exp_idx = pd.PeriodIndex( + ["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], freq="D" + ) + + obj = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), index=idx, columns=idx + ) + obj = tm.get_obj(obj, frame_or_series) + expected = obj.copy() + expected.index = exp_idx + tm.assert_equal(obj.to_period(), expected) + + if frame_or_series is pd.DataFrame: + expected = obj.copy() + expected.columns = exp_idx + tm.assert_frame_equal(obj.to_period(axis=1), expected) + + def test_to_period_columns(self): + dr = pd.date_range("1/1/2000", "1/1/2001") + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((len(dr), 5)), index=dr + ) + df["mix"] = "a" + + df = df.T + pts = df.to_period(axis=1) + exp = df.copy() + exp.columns = pd.period_range("1/1/2000", "1/1/2001") + tm.assert_frame_equal(pts, exp) + + pts = df.to_period("M", axis=1) + tm.assert_index_equal(pts.columns, exp.columns.asfreq("M")) + + def test_to_period_invalid_axis(self): + dr = pd.date_range("1/1/2000", "1/1/2001") + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((len(dr), 5)), index=dr + ) + df["mix"] = "a" + + msg = "No axis named 2 for object type DataFrame" + with pytest.raises(ValueError, match=msg): + df.to_period(axis=2) + + def test_to_period_raises(self, index, frame_or_series): + # https://github.com/pandas-dev/pandas/issues/33327 + obj = pd.Series(index=index, dtype=object) + if frame_or_series is pd.DataFrame: + obj = obj.to_frame() + + if not isinstance(index, pd.DatetimeIndex): + msg = f"unsupported Type {type(index).__name__}" + with pytest.raises(TypeError, match=msg): + obj.to_period() diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_records.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_records.py new file mode 100644 index 0000000000000000000000000000000000000000..78515755963b577ba1d2804b23031b457a2d382c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_records.py @@ -0,0 +1,530 @@ +from collections import abc +import email +from email.parser import Parser + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameToRecords: + def test_to_records_timeseries(self): + index = pd.date_range("1/1/2000", periods=10, unit="ns") + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 3)), + index=index, + columns=["a", "b", "c"], + ) + + result = df.to_records() + assert result["index"].dtype == "M8[ns]" + + result = df.to_records(index=False) + + def test_to_records_empty_multiindex(self): + # GH#21064 to_records on an empty frame with a MultiIndex must not raise + df = pd.DataFrame({"A": [10, -10], "B": [400, 400], "C": ["bla", "bla"]}) + grouped = pd.DataFrame(df.groupby(["B", "C"])["A"].sum()) + empty = grouped[grouped["A"] > 1e18] # no rows match -> empty MI frame + result = empty.to_records() + assert len(result) == 0 + assert result.dtype.names == ("B", "C", "A") + + def test_to_records_dt64(self): + df = pd.DataFrame( + [["one", "two", "three"], ["four", "five", "six"]], + index=pd.date_range("2012-01-01", "2012-01-02"), + ) + + expected = df.index.values[0] + result = df.to_records()["index"][0] + assert expected == result + + def test_to_records_dt64tz_column(self): + # GH#32535 dont less tz in to_records + df = pd.DataFrame( + {"A": pd.date_range("2012-01-01", "2012-01-02", tz="US/Eastern")} + ) + + result = df.to_records() + + assert result.dtype["A"] == object + val = result[0][1] + assert isinstance(val, pd.Timestamp) + assert val == df.loc[0, "A"] + + def test_to_records_with_multindex(self): + # GH#3189 + index = [ + ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + ] + data = np.zeros((8, 4)) + df = pd.DataFrame(data, index=index) + r = df.to_records(index=True)["level_0"] + assert "bar" in r + assert "one" not in r + + def test_to_records_with_Mapping_type(self): + abc.Mapping.register(email.message.Message) + + headers = Parser().parsestr( + "From: \n" + "To: \n" + "Subject: Test message\n" + "\n" + "Body would go here\n" + ) + + frame = pd.DataFrame.from_records([headers]) + all(x in frame for x in ["Type", "Subject", "From"]) + + def test_to_records_floats(self): + df = pd.DataFrame(np.random.default_rng(2).random((10, 10))) + df.to_records() + + def test_to_records_index_name(self): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((3, 3))) + df.index.name = "X" + rs = df.to_records() + assert "X" in rs.dtype.fields + + df = pd.DataFrame(np.random.default_rng(2).standard_normal((3, 3))) + rs = df.to_records() + assert "index" in rs.dtype.fields + + df.index = pd.MultiIndex.from_tuples([("a", "x"), ("a", "y"), ("b", "z")]) + df.index.names = ["A", None] + result = df.to_records() + expected = np.rec.fromarrays( + [np.array(["a", "a", "b"]), np.array(["x", "y", "z"])] + + [np.asarray(df.iloc[:, i]) for i in range(3)], + dtype={ + "names": ["A", "level_1", "0", "1", "2"], + "formats": [ + "O", + "O", + f"{tm.ENDIAN}f8", + f"{tm.ENDIAN}f8", + f"{tm.ENDIAN}f8", + ], + }, + ) + tm.assert_numpy_array_equal(result, expected) + + def test_to_records_with_unicode_index(self): + # GH#13172 + # unicode_literals conflict with to_records + result = pd.DataFrame([{"a": "x", "b": "y"}]).set_index("a").to_records() + expected = np.rec.array([("x", "y")], dtype=[("a", "O"), ("b", "O")]) + tm.assert_almost_equal(result, expected) + + def test_to_records_index_dtype(self): + # GH 47263: consistent data types for Index and MultiIndex + df = pd.DataFrame( + { + 1: pd.date_range("2022-01-01", periods=2, unit="ns"), + 2: pd.date_range("2022-01-01", periods=2, unit="ns"), + 3: pd.date_range("2022-01-01", periods=2, unit="ns"), + } + ) + + expected = np.rec.array( + [ + ("2022-01-01", "2022-01-01", "2022-01-01"), + ("2022-01-02", "2022-01-02", "2022-01-02"), + ], + dtype=[ + ("1", f"{tm.ENDIAN}M8[ns]"), + ("2", f"{tm.ENDIAN}M8[ns]"), + ("3", f"{tm.ENDIAN}M8[ns]"), + ], + ) + + result = df.to_records(index=False) + tm.assert_almost_equal(result, expected) + + result = df.set_index(1).to_records(index=True) + tm.assert_almost_equal(result, expected) + + result = df.set_index([1, 2]).to_records(index=True) + tm.assert_almost_equal(result, expected) + + def test_to_records_with_unicode_column_names(self): + # xref issue: https://github.com/numpy/numpy/issues/2407 + # Issue GH#11879. to_records used to raise an exception when used + # with column names containing non-ascii characters in Python 2 + result = pd.DataFrame(data={"accented_name_é": [1.0]}).to_records() + + # Note that numpy allows for unicode field names but dtypes need + # to be specified using dictionary instead of list of tuples. + expected = np.rec.array( + [(0, 1.0)], + dtype={"names": ["index", "accented_name_é"], "formats": ["=i8", "=f8"]}, + ) + tm.assert_almost_equal(result, expected) + + def test_to_records_with_categorical(self): + # GH#8626 + + # dict creation + df = pd.DataFrame({"A": list("abc")}, dtype="category") + expected = pd.Series(list("abc"), dtype="category", name="A") + tm.assert_series_equal(df["A"], expected) + + # list-like creation + df = pd.DataFrame(list("abc"), dtype="category") + expected = pd.Series(list("abc"), dtype="category", name=0) + tm.assert_series_equal(df[0], expected) + + # to record array + # this coerces + result = df.to_records() + expected = np.rec.array( + [(0, "a"), (1, "b"), (2, "c")], dtype=[("index", "=i8"), ("0", "O")] + ) + tm.assert_almost_equal(result, expected) + + @pytest.mark.parametrize( + "kwargs,expected", + [ + # No dtypes --> default to array dtypes. + ( + {}, + np.rec.array( + [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}i8"), + ("A", f"{tm.ENDIAN}i8"), + ("B", f"{tm.ENDIAN}f8"), + ("C", "O"), + ], + ), + ), + # Should have no effect in this case. + ( + {"index": True}, + np.rec.array( + [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}i8"), + ("A", f"{tm.ENDIAN}i8"), + ("B", f"{tm.ENDIAN}f8"), + ("C", "O"), + ], + ), + ), + # Column dtype applied across the board. Index unaffected. + ( + {"column_dtypes": f"{tm.ENDIAN}U4"}, + np.rec.array( + [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}i8"), + ("A", f"{tm.ENDIAN}U4"), + ("B", f"{tm.ENDIAN}U4"), + ("C", f"{tm.ENDIAN}U4"), + ], + ), + ), + # Index dtype applied across the board. Columns unaffected. + ( + {"index_dtypes": f"{tm.ENDIAN}U1"}, + np.rec.array( + [("0", 1, 0.2, "a"), ("1", 2, 1.5, "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}U1"), + ("A", f"{tm.ENDIAN}i8"), + ("B", f"{tm.ENDIAN}f8"), + ("C", "O"), + ], + ), + ), + # Pass in a type instance. + ( + {"column_dtypes": str}, + np.rec.array( + [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}i8"), + ("A", f"{tm.ENDIAN}U"), + ("B", f"{tm.ENDIAN}U"), + ("C", f"{tm.ENDIAN}U"), + ], + ), + ), + # Pass in a dtype instance. + ( + {"column_dtypes": np.dtype(np.str_)}, + np.rec.array( + [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}i8"), + ("A", f"{tm.ENDIAN}U"), + ("B", f"{tm.ENDIAN}U"), + ("C", f"{tm.ENDIAN}U"), + ], + ), + ), + # Pass in a dictionary (name-only). + ( + { + "column_dtypes": { + "A": np.int8, + "B": np.float32, + "C": f"{tm.ENDIAN}U2", + } + }, + np.rec.array( + [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}i8"), + ("A", "i1"), + ("B", f"{tm.ENDIAN}f4"), + ("C", f"{tm.ENDIAN}U2"), + ], + ), + ), + # Pass in a dictionary (indices-only). + ( + {"index_dtypes": {0: "int16"}}, + np.rec.array( + [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")], + dtype=[ + ("index", "i2"), + ("A", f"{tm.ENDIAN}i8"), + ("B", f"{tm.ENDIAN}f8"), + ("C", "O"), + ], + ), + ), + # Ignore index mappings if index is not True. + ( + {"index": False, "index_dtypes": f"{tm.ENDIAN}U2"}, + np.rec.array( + [(1, 0.2, "a"), (2, 1.5, "bc")], + dtype=[ + ("A", f"{tm.ENDIAN}i8"), + ("B", f"{tm.ENDIAN}f8"), + ("C", "O"), + ], + ), + ), + # Non-existent names / indices in mapping should not error. + ( + {"index_dtypes": {0: "int16", "not-there": "float32"}}, + np.rec.array( + [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")], + dtype=[ + ("index", "i2"), + ("A", f"{tm.ENDIAN}i8"), + ("B", f"{tm.ENDIAN}f8"), + ("C", "O"), + ], + ), + ), + # Names / indices not in mapping default to array dtype. + ( + {"column_dtypes": {"A": np.int8, "B": np.float32}}, + np.rec.array( + [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}i8"), + ("A", "i1"), + ("B", f"{tm.ENDIAN}f4"), + ("C", "O"), + ], + ), + ), + # Names / indices not in dtype mapping default to array dtype. + ( + {"column_dtypes": {"A": np.dtype("int8"), "B": np.dtype("float32")}}, + np.rec.array( + [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}i8"), + ("A", "i1"), + ("B", f"{tm.ENDIAN}f4"), + ("C", "O"), + ], + ), + ), + # Mixture of everything. + ( + { + "column_dtypes": {"A": np.int8, "B": np.float32}, + "index_dtypes": f"{tm.ENDIAN}U2", + }, + np.rec.array( + [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}U2"), + ("A", "i1"), + ("B", f"{tm.ENDIAN}f4"), + ("C", "O"), + ], + ), + ), + # Invalid dype values. + ( + {"index": False, "column_dtypes": []}, + (ValueError, "Invalid dtype \\[\\] specified for column A"), + ), + ( + {"index": False, "column_dtypes": {"A": "int32", "B": 5}}, + (ValueError, "Invalid dtype 5 specified for column B"), + ), + # Numpy can't handle EA types, so check error is raised + ( + { + "index": False, + "column_dtypes": { + "A": "int32", + "B": pd.CategoricalDtype(["a", "b"]), + }, + }, + (ValueError, "Invalid dtype category specified for column B"), + ), + # Check that bad types raise + ( + {"index": False, "column_dtypes": {"A": "int32", "B": "foo"}}, + (TypeError, "data type [\"']foo[\"'] not understood"), + ), + ], + ) + def test_to_records_dtype(self, kwargs, expected): + # see GH#18146 + df = pd.DataFrame({"A": [1, 2], "B": [0.2, 1.5], "C": ["a", "bc"]}) + + if not isinstance(expected, np.rec.recarray): + with pytest.raises(expected[0], match=expected[1]): + df.to_records(**kwargs) + else: + result = df.to_records(**kwargs) + tm.assert_almost_equal(result, expected) + + @pytest.mark.parametrize( + "df,kwargs,expected", + [ + # MultiIndex in the index. + ( + pd.DataFrame( + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("abc") + ).set_index(["a", "b"]), + {"column_dtypes": "float64", "index_dtypes": {0: "int32", 1: "int8"}}, + np.rec.array( + [(1, 2, 3.0), (4, 5, 6.0), (7, 8, 9.0)], + dtype=[ + ("a", f"{tm.ENDIAN}i4"), + ("b", "i1"), + ("c", f"{tm.ENDIAN}f8"), + ], + ), + ), + # MultiIndex in the columns. + ( + pd.DataFrame( + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], + columns=pd.MultiIndex.from_tuples( + [("a", "d"), ("b", "e"), ("c", "f")] + ), + ), + { + "column_dtypes": {0: f"{tm.ENDIAN}U1", 2: "float32"}, + "index_dtypes": "float32", + }, + np.rec.array( + [(0.0, "1", 2, 3.0), (1.0, "4", 5, 6.0), (2.0, "7", 8, 9.0)], + dtype=[ + ("index", f"{tm.ENDIAN}f4"), + ("('a', 'd')", f"{tm.ENDIAN}U1"), + ("('b', 'e')", f"{tm.ENDIAN}i8"), + ("('c', 'f')", f"{tm.ENDIAN}f4"), + ], + ), + ), + # MultiIndex in both the columns and index. + ( + pd.DataFrame( + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], + columns=pd.MultiIndex.from_tuples( + [("a", "d"), ("b", "e"), ("c", "f")], names=list("ab") + ), + index=pd.MultiIndex.from_tuples( + [("d", -4), ("d", -5), ("f", -6)], names=list("cd") + ), + ), + { + "column_dtypes": "float64", + "index_dtypes": {0: f"{tm.ENDIAN}U2", 1: "int8"}, + }, + np.rec.array( + [ + ("d", -4, 1.0, 2.0, 3.0), + ("d", -5, 4.0, 5.0, 6.0), + ("f", -6, 7, 8, 9.0), + ], + dtype=[ + ("c", f"{tm.ENDIAN}U2"), + ("d", "i1"), + ("('a', 'd')", f"{tm.ENDIAN}f8"), + ("('b', 'e')", f"{tm.ENDIAN}f8"), + ("('c', 'f')", f"{tm.ENDIAN}f8"), + ], + ), + ), + ], + ) + def test_to_records_dtype_mi(self, df, kwargs, expected): + # see GH#18146 + result = df.to_records(**kwargs) + tm.assert_almost_equal(result, expected) + + def test_to_records_dict_like(self): + # see GH#18146 + class DictLike: + def __init__(self, **kwargs) -> None: + self.d = kwargs.copy() + + def __getitem__(self, key): + return self.d.__getitem__(key) + + def __contains__(self, key) -> bool: + return key in self.d + + def keys(self): + return self.d.keys() + + df = pd.DataFrame({"A": [1, 2], "B": [0.2, 1.5], "C": ["a", "bc"]}) + + dtype_mappings = { + "column_dtypes": DictLike(A=np.int8, B=np.float32), + "index_dtypes": f"{tm.ENDIAN}U2", + } + + result = df.to_records(**dtype_mappings) + expected = np.rec.array( + [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], + dtype=[ + ("index", f"{tm.ENDIAN}U2"), + ("A", "i1"), + ("B", f"{tm.ENDIAN}f4"), + ("C", "O"), + ], + ) + tm.assert_almost_equal(result, expected) + + @pytest.mark.parametrize("tz", ["UTC", "GMT", "US/Eastern"]) + def test_to_records_datetimeindex_with_tz(self, tz): + # GH#13937 + dr = pd.date_range("2016-01-01", periods=10, freq="s", tz=tz) + + df = pd.DataFrame({"datetime": dr}, index=dr) + + expected = df.to_records() + result = df.tz_convert("UTC").to_records() + + # both converted to UTC, so they are equal + tm.assert_numpy_array_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_timestamp.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_timestamp.py new file mode 100644 index 0000000000000000000000000000000000000000..9cb0577182dee5c56fe26d8586c66ebd5df3dd02 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_to_timestamp.py @@ -0,0 +1,147 @@ +from datetime import timedelta + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def _get_with_delta(delta, freq="YE-DEC"): + return pd.date_range( + pd.to_datetime("1/1/2001") + delta, + pd.to_datetime("12/31/2009") + delta, + freq=freq, + ) + + +class TestToTimestamp: + def test_to_timestamp(self, frame_or_series): + K = 5 + index = pd.period_range(freq="Y", start="1/1/2001", end="12/1/2009") + obj = pd.DataFrame( + np.random.default_rng(2).standard_normal((len(index), K)), + index=index, + columns=["A", "B", "C", "D", "E"], + ) + obj["mix"] = "a" + obj = tm.get_obj(obj, frame_or_series) + + exp_index = pd.date_range("1/1/2001", end="12/31/2009", freq="YE-DEC") + exp_index = exp_index + pd.Timedelta(1, "D") - pd.Timedelta(1, "us") + result = obj.to_timestamp("D", "end") + tm.assert_index_equal(result.index, exp_index) + tm.assert_numpy_array_equal(result.values, obj.values) + if frame_or_series is pd.Series: + assert result.name == "A" + + exp_index = pd.date_range("1/1/2001", end="1/1/2009", freq="YS-JAN") + result = obj.to_timestamp("D", "start") + tm.assert_index_equal(result.index, exp_index) + + result = obj.to_timestamp(how="start") + tm.assert_index_equal(result.index, exp_index) + + delta = timedelta(hours=23) + result = obj.to_timestamp("h", "end") + exp_index = _get_with_delta(delta) + exp_index = exp_index + pd.Timedelta(1, "h") - pd.Timedelta(1, "us") + tm.assert_index_equal(result.index, exp_index) + + delta = timedelta(hours=23, minutes=59) + result = obj.to_timestamp("min", "end") + exp_index = _get_with_delta(delta) + exp_index = exp_index + pd.Timedelta(1, "m") - pd.Timedelta(1, "us") + tm.assert_index_equal(result.index, exp_index) + + result = obj.to_timestamp("s", "end") + delta = timedelta(hours=23, minutes=59, seconds=59) + exp_index = _get_with_delta(delta) + exp_index = exp_index + pd.Timedelta(1, "s") - pd.Timedelta(1, "us") + tm.assert_index_equal(result.index, exp_index) + + def test_to_timestamp_columns(self): + K = 5 + index = pd.period_range(freq="Y", start="1/1/2001", end="12/1/2009") + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((len(index), K)), + index=index, + columns=["A", "B", "C", "D", "E"], + ) + df["mix"] = "a" + + # columns + df = df.T + + exp_index = pd.date_range("1/1/2001", end="12/31/2009", freq="YE-DEC") + exp_index = exp_index + pd.Timedelta(1, "D") - pd.Timedelta(1, "us") + result = df.to_timestamp("D", "end", axis=1) + tm.assert_index_equal(result.columns, exp_index) + tm.assert_numpy_array_equal(result.values, df.values) + + exp_index = pd.date_range("1/1/2001", end="1/1/2009", freq="YS-JAN") + result = df.to_timestamp("D", "start", axis=1) + tm.assert_index_equal(result.columns, exp_index) + + delta = timedelta(hours=23) + result = df.to_timestamp("h", "end", axis=1) + exp_index = _get_with_delta(delta) + exp_index = exp_index + pd.Timedelta(1, "h") - pd.Timedelta(1, "us") + tm.assert_index_equal(result.columns, exp_index) + + delta = timedelta(hours=23, minutes=59) + result = df.to_timestamp("min", "end", axis=1) + exp_index = _get_with_delta(delta) + exp_index = exp_index + pd.Timedelta(1, "m") - pd.Timedelta(1, "us") + tm.assert_index_equal(result.columns, exp_index) + + result = df.to_timestamp("s", "end", axis=1) + delta = timedelta(hours=23, minutes=59, seconds=59) + exp_index = _get_with_delta(delta) + exp_index = exp_index + pd.Timedelta(1, "s") - pd.Timedelta(1, "us") + tm.assert_index_equal(result.columns, exp_index) + + result1 = df.to_timestamp("5min", axis=1) + result2 = df.to_timestamp("min", axis=1) + expected = pd.date_range("2001-01-01", "2009-01-01", freq="YS") + assert isinstance(result1.columns, pd.DatetimeIndex) + assert isinstance(result2.columns, pd.DatetimeIndex) + tm.assert_numpy_array_equal(result1.columns.asi8, expected.asi8) + tm.assert_numpy_array_equal(result2.columns.asi8, expected.asi8) + # PeriodIndex.to_timestamp always use 'infer' + assert result1.columns.freqstr == "YS-JAN" + assert result2.columns.freqstr == "YS-JAN" + + def test_to_timestamp_invalid_axis(self): + index = pd.period_range(freq="Y", start="1/1/2001", end="12/1/2009") + obj = pd.DataFrame( + np.random.default_rng(2).standard_normal((len(index), 5)), index=index + ) + + # invalid axis + with pytest.raises(ValueError, match="axis"): + obj.to_timestamp(axis=2) + + def test_to_timestamp_hourly(self, frame_or_series): + index = pd.period_range(freq="h", start="1/1/2001", end="1/2/2001") + obj = pd.Series(1, index=index, name="foo") + if frame_or_series is not pd.Series: + obj = obj.to_frame() + + exp_index = pd.date_range( + "1/1/2001 00:59:59", end="1/2/2001 00:59:59", freq="h" + ) + result = obj.to_timestamp(how="end") + exp_index = exp_index + pd.Timedelta(1, "s") - pd.Timedelta(1, "us") + tm.assert_index_equal(result.index, exp_index, check_freq=False) + if frame_or_series is pd.Series: + assert result.name == "foo" + + def test_to_timestamp_raises(self, index, frame_or_series): + # GH#33327 + obj = frame_or_series(index=index, dtype=object) + + if not isinstance(index, pd.PeriodIndex): + msg = f"unsupported Type {type(index).__name__}" + with pytest.raises(TypeError, match=msg): + obj.to_timestamp() diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_transpose.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_transpose.py new file mode 100644 index 0000000000000000000000000000000000000000..311b7b6fc1b4ee8835c6d2b54e1d32f5fb4446bf --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_transpose.py @@ -0,0 +1,187 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestTranspose: + def test_transpose_td64_intervals(self): + # GH#44917 + tdi = pd.timedelta_range("0 Days", "3 Days") + ii = pd.IntervalIndex.from_breaks(tdi) + ii = ii.insert(-1, np.nan) + df = pd.DataFrame(ii) + + result = df.T + result.columns = pd.Index(list(range(len(ii)))) + expected = pd.DataFrame({i: ii[i : i + 1] for i in range(len(ii))}) + tm.assert_frame_equal(result, expected) + + def test_transpose_empty_preserves_datetimeindex(self): + # GH#41382 + dti = pd.DatetimeIndex([], dtype="M8[ns]") + df = pd.DataFrame(index=dti) + + expected = pd.DatetimeIndex([], dtype="datetime64[ns]", freq=None) + + result1 = df.T.sum().index + result2 = df.sum(axis=1).index + + tm.assert_index_equal(result1, expected) + tm.assert_index_equal(result2, expected) + + def test_transpose_tzaware_1col_single_tz(self): + # GH#26825 + dti = pd.date_range("2016-04-05 04:30", periods=3, tz="UTC") + + df = pd.DataFrame(dti) + assert (df.dtypes == dti.dtype).all() + res = df.T + assert (res.dtypes == dti.dtype).all() + + def test_transpose_tzaware_2col_single_tz(self): + # GH#26825 + dti = pd.date_range("2016-04-05 04:30", periods=3, tz="UTC") + + df3 = pd.DataFrame({"A": dti, "B": dti}) + assert (df3.dtypes == dti.dtype).all() + res3 = df3.T + assert (res3.dtypes == dti.dtype).all() + + def test_transpose_tzaware_2col_mixed_tz(self): + # GH#26825 + dti = pd.date_range("2016-04-05 04:30", periods=3, tz="UTC") + dti2 = dti.tz_convert("US/Pacific") + + df4 = pd.DataFrame({"A": dti, "B": dti2}) + assert (df4.dtypes == [dti.dtype, dti2.dtype]).all() + assert (df4.T.dtypes == object).all() + tm.assert_frame_equal(df4.T.T, df4.astype(object)) + + @pytest.mark.parametrize("tz", [None, "America/New_York"]) + def test_transpose_preserves_dtindex_equality_with_dst(self, tz): + # GH#19970 + idx = pd.date_range("20161101", "20161130", freq="4h", tz=tz) + df = pd.DataFrame({"a": range(len(idx)), "b": range(len(idx))}, index=idx) + result = df.T == df.T + expected = pd.DataFrame(True, index=list("ab"), columns=idx) + tm.assert_frame_equal(result, expected) + + def test_transpose_object_to_tzaware_mixed_tz(self): + # GH#26825 + dti = pd.date_range("2016-04-05 04:30", periods=3, tz="UTC") + dti2 = dti.tz_convert("US/Pacific") + + # mixed all-tzaware dtypes + df2 = pd.DataFrame([dti, dti2]) + assert (df2.dtypes == object).all() + res2 = df2.T + assert (res2.dtypes == object).all() + + def test_transpose_uint64(self): + df = pd.DataFrame( + {"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]}, + dtype=np.uint64, + ) + result = df.T + expected = pd.DataFrame(df.values.T) + expected.index = ["A", "B"] + tm.assert_frame_equal(result, expected) + + def test_transpose_float(self, float_frame): + frame = float_frame + dft = frame.T + for idx, series in dft.items(): + for col, value in series.items(): + if np.isnan(value): + assert np.isnan(frame[col][idx]) + else: + assert value == frame[col][idx] + + def test_transpose_mixed(self): + # mixed type + mixed = pd.DataFrame( + { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": ["foo1", "foo2", "foo3", "foo4", "foo5"], + "D": pd.bdate_range("1/1/2009", periods=5), + }, + index=pd.Index(["a", "b", "c", "d", "e"], dtype=object), + ) + + mixed_T = mixed.T + for col, s in mixed_T.items(): + assert s.dtype == np.object_ + + def test_transpose_get_view(self, float_frame): + dft = float_frame.T + dft.iloc[:, 5:10] = 5 + assert (float_frame.values[5:10] != 5).all() + + def test_transpose_get_view_dt64tzget_view(self): + dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific") + arr = dti._data.reshape(3, 2) + df = pd.DataFrame(arr) + assert df._mgr.nblocks == 1 + + result = df.T + assert result._mgr.nblocks == 1 + + rtrip = result._mgr.blocks[0].values + assert np.shares_memory(df._mgr.blocks[0].values._ndarray, rtrip._ndarray) + + def test_transpose_not_inferring_dt(self): + # GH#51546 + df = pd.DataFrame( + { + "a": [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31")], + }, + dtype=object, + ) + result = df.T + expected = pd.DataFrame( + [[pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31")]], + index=["a"], + dtype=object, + ) + tm.assert_frame_equal(result, expected) + + def test_transpose_not_inferring_dt_mixed_blocks(self): + # GH#51546 + df = pd.DataFrame( + { + "a": pd.Series( + [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31")], + dtype=object, + ), + "b": [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31")], + } + ) + result = df.T + expected = pd.DataFrame( + [ + [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31")], + [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31")], + ], + index=["a", "b"], + dtype=object, + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype1", ["Int64", "Float64"]) + @pytest.mark.parametrize("dtype2", ["Int64", "Float64"]) + def test_transpose(self, dtype1, dtype2): + # GH#57315 - transpose should have F contiguous blocks + df = pd.DataFrame( + { + "a": pd.array([1, 1, 2], dtype=dtype1), + "b": pd.array([3, 4, 5], dtype=dtype2), + } + ) + result = df.T + for blk in result._mgr.blocks: + # When dtypes are unequal, we get NumPy object array + data = blk.values._data if dtype1 == dtype2 else blk.values + assert data.flags["F_CONTIGUOUS"] diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_truncate.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_truncate.py new file mode 100644 index 0000000000000000000000000000000000000000..5f288dba6a9f0a09054cdb24458253ebfb9aa131 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_truncate.py @@ -0,0 +1,158 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameTruncate: + def test_truncate(self, datetime_frame, frame_or_series): + ts = datetime_frame[::3] + ts = tm.get_obj(ts, frame_or_series) + + start, end = datetime_frame.index[3], datetime_frame.index[6] + + start_missing = datetime_frame.index[2] + end_missing = datetime_frame.index[7] + + # neither specified + truncated = ts.truncate() + tm.assert_equal(truncated, ts) + + # both specified + expected = ts[1:3] + + truncated = ts.truncate(start, end) + tm.assert_equal(truncated, expected) + + truncated = ts.truncate(start_missing, end_missing) + tm.assert_equal(truncated, expected) + + # start specified + expected = ts[1:] + + truncated = ts.truncate(before=start) + tm.assert_equal(truncated, expected) + + truncated = ts.truncate(before=start_missing) + tm.assert_equal(truncated, expected) + + # end specified + expected = ts[:3] + + truncated = ts.truncate(after=end) + tm.assert_equal(truncated, expected) + + truncated = ts.truncate(after=end_missing) + tm.assert_equal(truncated, expected) + + # corner case, empty series/frame returned + truncated = ts.truncate(after=ts.index[0] - ts.index.freq) + assert len(truncated) == 0 + + truncated = ts.truncate(before=ts.index[-1] + ts.index.freq) + assert len(truncated) == 0 + + msg = "Truncate: 2000-01-06 00:00:00 must be after 2000-01-11 00:00:00" + with pytest.raises(ValueError, match=msg): + ts.truncate( + before=ts.index[-1] - ts.index.freq, after=ts.index[0] + ts.index.freq + ) + + def test_truncate_nonsortedindex(self, frame_or_series): + # GH#17935 + + obj = pd.DataFrame({"A": ["a", "b", "c", "d", "e"]}, index=[5, 3, 2, 9, 0]) + obj = tm.get_obj(obj, frame_or_series) + + msg = "truncate requires a sorted index" + with pytest.raises(ValueError, match=msg): + obj.truncate(before=3, after=9) + + def test_sort_values_nonsortedindex(self): + rng = pd.date_range("2011-01-01", "2012-01-01", freq="W") + ts = pd.DataFrame( + { + "A": np.random.default_rng(2).standard_normal(len(rng)), + "B": np.random.default_rng(2).standard_normal(len(rng)), + }, + index=rng, + ) + + decreasing = ts.sort_values("A", ascending=False) + + msg = "truncate requires a sorted index" + with pytest.raises(ValueError, match=msg): + decreasing.truncate(before="2011-11", after="2011-12") + + def test_truncate_nonsortedindex_axis1(self): + # GH#17935 + + df = pd.DataFrame( + { + 3: np.random.default_rng(2).standard_normal(5), + 20: np.random.default_rng(2).standard_normal(5), + 2: np.random.default_rng(2).standard_normal(5), + 0: np.random.default_rng(2).standard_normal(5), + }, + columns=[3, 20, 2, 0], + ) + msg = "truncate requires a sorted index" + with pytest.raises(ValueError, match=msg): + df.truncate(before=2, after=20, axis=1) + + @pytest.mark.parametrize("axis", [0, "index", 1, "columns"]) + def test_truncate_axis_by_name(self, axis): + # GH#58517 + df = pd.DataFrame(np.arange(16).reshape(4, 4)) + result = df.truncate(before=1, after=2, axis=axis) + if axis in [0, "index"]: + expected = df.iloc[1:3] + else: + expected = df.iloc[:, 1:3] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "before, after, indices", + [(1, 2, [2, 1]), (None, 2, [2, 1, 0]), (1, None, [3, 2, 1])], + ) + @pytest.mark.parametrize("dtyp", [*tm.ALL_REAL_NUMPY_DTYPES, "datetime64[ns]"]) + def test_truncate_decreasing_index( + self, before, after, indices, dtyp, frame_or_series + ): + # https://github.com/pandas-dev/pandas/issues/33756 + idx = pd.Index([3, 2, 1, 0], dtype=dtyp) + if isinstance(idx, pd.DatetimeIndex): + before = pd.Timestamp(before) if before is not None else None + after = pd.Timestamp(after) if after is not None else None + indices = [pd.Timestamp(i) for i in indices] + values = frame_or_series(range(len(idx)), index=idx) + result = values.truncate(before=before, after=after) + expected = values.loc[indices] + tm.assert_equal(result, expected) + + def test_truncate_multiindex(self, frame_or_series): + # GH 34564 + mi = pd.MultiIndex.from_product([[1, 2, 3, 4], ["A", "B"]], names=["L1", "L2"]) + s1 = pd.DataFrame(range(mi.shape[0]), index=mi, columns=["col"]) + s1 = tm.get_obj(s1, frame_or_series) + + result = s1.truncate(before=2, after=3) + + df = pd.DataFrame.from_dict( + {"L1": [2, 2, 3, 3], "L2": ["A", "B", "A", "B"], "col": [2, 3, 4, 5]} + ) + expected = df.set_index(["L1", "L2"]) + expected = tm.get_obj(expected, frame_or_series) + + tm.assert_equal(result, expected) + + def test_truncate_index_only_one_unique_value(self, frame_or_series): + # GH 42365 + obj = pd.Series(0, index=pd.date_range("2021-06-30", "2021-06-30")).repeat(5) + if frame_or_series is pd.DataFrame: + obj = obj.to_frame(name="a") + + truncated = obj.truncate("2021-06-28", "2021-07-01") + + tm.assert_equal(truncated, obj) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_tz_convert.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_tz_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..d53308bb2bb1dd0d46663a1226fdf92dee55563d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_tz_convert.py @@ -0,0 +1,128 @@ +import zoneinfo + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestTZConvert: + def test_tz_convert(self, frame_or_series): + rng = pd.date_range( + "1/1/2011", periods=200, freq="D", tz=zoneinfo.ZoneInfo("US/Eastern") + ) + + obj = pd.DataFrame({"a": 1}, index=rng) + obj = tm.get_obj(obj, frame_or_series) + + berlin = zoneinfo.ZoneInfo("Europe/Berlin") + result = obj.tz_convert(berlin) + expected = pd.DataFrame({"a": 1}, rng.tz_convert(berlin)) + expected = tm.get_obj(expected, frame_or_series) + + assert result.index.tz.key == "Europe/Berlin" + tm.assert_equal(result, expected) + + def test_tz_convert_axis1(self): + rng = pd.date_range( + "1/1/2011", periods=200, freq="D", tz=zoneinfo.ZoneInfo("US/Eastern") + ) + + obj = pd.DataFrame({"a": 1}, index=rng) + + obj = obj.T + berlin = zoneinfo.ZoneInfo("Europe/Berlin") + result = obj.tz_convert(berlin, axis=1) + assert result.columns.tz.key == "Europe/Berlin" + + expected = pd.DataFrame({"a": 1}, rng.tz_convert(berlin)) + + tm.assert_equal(result, expected.T) + + def test_tz_convert_naive(self, frame_or_series): + # can't convert tz-naive + rng = pd.date_range("1/1/2011", periods=200, freq="D") + ts = pd.Series(1, index=rng) + ts = frame_or_series(ts) + + with pytest.raises(TypeError, match="Cannot convert tz-naive"): + ts.tz_convert("US/Eastern") + + @pytest.mark.parametrize("fn", ["tz_localize", "tz_convert"]) + def test_tz_convert_and_localize(self, fn): + l0 = pd.date_range("20140701", periods=5, freq="D") + l1 = pd.date_range("20140701", periods=5, freq="D") + + int_idx = pd.Index(range(5)) + + if fn == "tz_convert": + l0 = l0.tz_localize("UTC") + l1 = l1.tz_localize("UTC") + + for idx in [l0, l1]: + l0_expected = getattr(idx, fn)("US/Pacific") + l1_expected = getattr(idx, fn)("US/Pacific") + + df1 = pd.DataFrame(np.ones(5), index=l0) + df1 = getattr(df1, fn)("US/Pacific") + tm.assert_index_equal(df1.index, l0_expected) + + # MultiIndex + # GH7846 + df2 = pd.DataFrame(np.ones(5), pd.MultiIndex.from_arrays([l0, l1])) + + df3 = getattr(df2, fn)("US/Pacific", level=0) + assert not df3.index.levels[0].equals(l0) + tm.assert_index_equal(df3.index.levels[0], l0_expected) + tm.assert_index_equal(df3.index.levels[1], l1) + assert not df3.index.levels[1].equals(l1_expected) + + df3 = getattr(df2, fn)("US/Pacific", level=1) + tm.assert_index_equal(df3.index.levels[0], l0) + assert not df3.index.levels[0].equals(l0_expected) + tm.assert_index_equal(df3.index.levels[1], l1_expected) + assert not df3.index.levels[1].equals(l1) + + df4 = pd.DataFrame(np.ones(5), pd.MultiIndex.from_arrays([int_idx, l0])) + + # TODO: untested + getattr(df4, fn)("US/Pacific", level=1) + + tm.assert_index_equal(df3.index.levels[0], l0) + assert not df3.index.levels[0].equals(l0_expected) + tm.assert_index_equal(df3.index.levels[1], l1_expected) + assert not df3.index.levels[1].equals(l1) + + @pytest.mark.parametrize("fn", ["tz_localize", "tz_convert"]) + def test_tz_convert_and_localize_bad_input(self, fn): + int_idx = pd.Index(range(5)) + l0 = pd.date_range("20140701", periods=5, freq="D") + # Not DatetimeIndex / PeriodIndex + df = pd.DataFrame(index=int_idx) + with pytest.raises(TypeError, match="DatetimeIndex"): + getattr(df, fn)("US/Pacific") + + # Not DatetimeIndex / PeriodIndex + df = pd.DataFrame(np.ones(5), pd.MultiIndex.from_arrays([int_idx, l0])) + with pytest.raises(TypeError, match="DatetimeIndex"): + getattr(df, fn)("US/Pacific", level=0) + + # Invalid level + df = pd.DataFrame(index=l0) + with pytest.raises(ValueError, match="not valid"): + getattr(df, fn)("US/Pacific", level=1) + + def test_tz_convert_copy_inplace_mutate(self, frame_or_series): + # GH#6326 + obj = frame_or_series( + np.arange(0, 5), + index=pd.date_range("20131027", periods=5, freq="h", tz="Europe/Berlin"), + ) + orig = obj.copy() + result = obj.tz_convert("UTC") + expected = frame_or_series(np.arange(0, 5), index=obj.index.tz_convert("UTC")) + tm.assert_equal(result, expected) + tm.assert_equal(obj, orig) + assert result.index is not obj.index + assert result is not obj diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_tz_localize.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_tz_localize.py new file mode 100644 index 0000000000000000000000000000000000000000..eea9dabb6f266a2e87dac15942151b5b7485a347 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_tz_localize.py @@ -0,0 +1,64 @@ +from datetime import UTC + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestTZLocalize: + # See also: + # test_tz_convert_and_localize in test_tz_convert + + def test_tz_localize(self, frame_or_series): + rng = pd.date_range("1/1/2011", periods=100, freq="h") + + obj = pd.DataFrame({"a": 1}, index=rng) + obj = tm.get_obj(obj, frame_or_series) + + result = obj.tz_localize("utc") + expected = pd.DataFrame({"a": 1}, rng.tz_localize("UTC")) + expected = tm.get_obj(expected, frame_or_series) + + assert result.index.tz is UTC + tm.assert_equal(result, expected) + + def test_tz_localize_axis1(self): + rng = pd.date_range("1/1/2011", periods=100, freq="h") + + df = pd.DataFrame({"a": 1}, index=rng) + + df = df.T + result = df.tz_localize("utc", axis=1) + assert result.columns.tz is UTC + + expected = pd.DataFrame({"a": 1}, rng.tz_localize("UTC")) + + tm.assert_frame_equal(result, expected.T) + + def test_tz_localize_naive(self, frame_or_series): + # Can't localize if already tz-aware + rng = pd.date_range("1/1/2011", periods=100, freq="h", tz="utc") + ts = pd.Series(1, index=rng) + ts = frame_or_series(ts) + + with pytest.raises(TypeError, match="Already tz-aware"): + ts.tz_localize("US/Eastern") + + def test_tz_localize_copy_inplace_mutate(self, frame_or_series): + # GH#6326 + obj = frame_or_series( + np.arange(0, 5), + index=pd.date_range("20131027", periods=5, freq="1h", tz=None), + ) + orig = obj.copy() + result = obj.tz_localize("UTC") + expected = frame_or_series( + np.arange(0, 5), + index=pd.date_range("20131027", periods=5, freq="1h", tz="UTC"), + ) + tm.assert_equal(result, expected) + tm.assert_equal(obj, orig) + assert result.index is not obj.index + assert result is not obj diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_update.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_update.py new file mode 100644 index 0000000000000000000000000000000000000000..e943d6a3d2688c4873e3aa152df16a490e730d1f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_update.py @@ -0,0 +1,262 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameUpdate: + def test_update_nan(self): + # #15593 #15617 + # test 1 + df1 = pd.DataFrame({"A": [1.0, 2, 3], "B": pd.date_range("2000", periods=3)}) + df2 = pd.DataFrame({"A": [None, 2, 3]}) + expected = df1.copy() + df1.update(df2, overwrite=False) + + tm.assert_frame_equal(df1, expected) + + # test 2 + df1 = pd.DataFrame({"A": [1.0, None, 3], "B": pd.date_range("2000", periods=3)}) + df2 = pd.DataFrame({"A": [None, 2, 3]}) + expected = pd.DataFrame( + {"A": [1.0, 2, 3], "B": pd.date_range("2000", periods=3)} + ) + df1.update(df2, overwrite=False) + + tm.assert_frame_equal(df1, expected) + + def test_update(self): + df = pd.DataFrame( + [[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]] + ) + + other = pd.DataFrame([[3.6, 2.0, np.nan], [np.nan, np.nan, 7]], index=[1, 3]) + + df.update(other) + + expected = pd.DataFrame( + [[1.5, np.nan, 3], [3.6, 2, 3], [1.5, np.nan, 3], [1.5, np.nan, 7.0]] + ) + tm.assert_frame_equal(df, expected) + + def test_update_dtypes(self): + # gh 3016 + df = pd.DataFrame( + [[1.0, 2.0, False, True], [4.0, 5.0, True, False]], + columns=["A", "B", "bool1", "bool2"], + ) + + other = pd.DataFrame([[45, 45]], index=[0], columns=["A", "B"]) + df.update(other) + + expected = pd.DataFrame( + [[45.0, 45.0, False, True], [4.0, 5.0, True, False]], + columns=["A", "B", "bool1", "bool2"], + ) + tm.assert_frame_equal(df, expected) + + def test_update_nooverwrite(self): + df = pd.DataFrame( + [[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]] + ) + + other = pd.DataFrame([[3.6, 2.0, np.nan], [np.nan, np.nan, 7]], index=[1, 3]) + + df.update(other, overwrite=False) + + expected = pd.DataFrame( + [[1.5, np.nan, 3], [1.5, 2, 3], [1.5, np.nan, 3], [1.5, np.nan, 3.0]] + ) + tm.assert_frame_equal(df, expected) + + def test_update_filtered(self): + df = pd.DataFrame( + [[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]] + ) + + other = pd.DataFrame([[3.6, 2.0, np.nan], [np.nan, np.nan, 7]], index=[1, 3]) + + df.update(other, filter_func=lambda x: x > 2) + + expected = pd.DataFrame( + [[1.5, np.nan, 3], [1.5, np.nan, 3], [1.5, np.nan, 3], [1.5, np.nan, 7.0]] + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "bad_kwarg, exception, msg", + [ + # errors must be 'ignore' or 'raise' + ({"errors": "something"}, ValueError, "The parameter errors must.*"), + ({"join": "inner"}, NotImplementedError, "Only left join is supported"), + ], + ) + def test_update_raise_bad_parameter(self, bad_kwarg, exception, msg): + df = pd.DataFrame([[1.5, 1, 3.0]]) + with pytest.raises(exception, match=msg): + df.update(df, **bad_kwarg) + + def test_update_raise_on_overlap(self): + df = pd.DataFrame( + [[1.5, 1, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]] + ) + + other = pd.DataFrame([[2.0, np.nan], [np.nan, 7]], index=[1, 3], columns=[1, 2]) + with pytest.raises(ValueError, match="Data overlaps"): + df.update(other, errors="raise") + + def test_update_from_non_df(self): + d = {"a": pd.Series([1, 2, 3, 4]), "b": pd.Series([5, 6, 7, 8])} + df = pd.DataFrame(d) + + d["a"] = pd.Series([5, 6, 7, 8]) + df.update(d) + + expected = pd.DataFrame(d) + + tm.assert_frame_equal(df, expected) + + d = {"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]} + df = pd.DataFrame(d) + + d["a"] = [5, 6, 7, 8] + df.update(d) + + expected = pd.DataFrame(d) + + tm.assert_frame_equal(df, expected) + + def test_update_datetime_tz(self): + # GH 25807 + result = pd.DataFrame([pd.Timestamp("2019", tz="UTC")]) + with tm.assert_produces_warning(None): + result.update(result) + expected = pd.DataFrame([pd.Timestamp("2019", tz="UTC")]) + tm.assert_frame_equal(result, expected) + + def test_update_datetime_tz_in_place(self): + # https://github.com/pandas-dev/pandas/issues/56227 + result = pd.DataFrame([pd.Timestamp("2019", tz="UTC")]) + orig = result.copy() + view = result[:] + result.update(result + pd.Timedelta(days=1)) + expected = pd.DataFrame([pd.Timestamp("2019-01-02", tz="UTC")]) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(view, orig) + + def test_update_with_different_dtype(self): + # GH#3217 + df = pd.DataFrame({"a": [1, 3], "b": [np.nan, 2]}) + df["c"] = np.nan + with pytest.raises(TypeError, match="Invalid value"): + df.update({"c": pd.Series(["foo"], index=[0])}) + + @pytest.mark.parametrize("dtype", ["str", object]) + def test_update_modify_view(self, dtype): + # GH#47188 + df = pd.DataFrame({"A": ["1", np.nan], "B": ["100", np.nan]}, dtype=dtype) + df2 = pd.DataFrame({"A": ["a", "x"], "B": ["100", "200"]}, dtype=dtype) + df2_orig = df2.copy() + result_view = df2[:] + df2.update(df) + expected = pd.DataFrame({"A": ["1", "x"], "B": ["100", "200"]}, dtype=dtype) + tm.assert_frame_equal(df2, expected) + tm.assert_frame_equal(result_view, df2_orig) + + def test_update_dt_column_with_NaT_create_column(self): + # GH#16713 + df = pd.DataFrame({"A": [1, None], "B": [pd.NaT, pd.to_datetime("2016-01-01")]}) + df2 = pd.DataFrame({"A": [2, 3]}) + df.update(df2, overwrite=False) + expected = pd.DataFrame( + {"A": [1.0, 3.0], "B": [pd.NaT, pd.to_datetime("2016-01-01")]} + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "value_df, value_other, dtype", + [ + (True, False, bool), + (1, 2, int), + (1.0, 2.0, float), + (1.0 + 1j, 2.0 + 2j, complex), + (np.uint64(1), np.uint(2), np.dtype("ubyte")), + (np.uint64(1), np.uint(2), np.dtype("intc")), + ("a", "b", pd.StringDtype()), + ( + pd.to_timedelta("1 ms"), + pd.to_timedelta("2 ms"), + np.dtype("timedelta64[ns]"), + ), + ( + np.datetime64("2000-01-01T00:00:00"), + np.datetime64("2000-01-02T00:00:00"), + np.dtype("datetime64[ns]"), + ), + (1, 2, pd.Int64Dtype()), + ], + ) + def test_update_preserve_dtype(self, value_df, value_other, dtype): + # GH#55509 + df = pd.DataFrame({"a": [value_df] * 2}, index=[1, 2], dtype=dtype) + other = pd.DataFrame({"a": [value_other]}, index=[1], dtype=dtype) + expected = pd.DataFrame( + {"a": [value_other, value_df]}, index=[1, 2], dtype=dtype + ) + df.update(other) + tm.assert_frame_equal(df, expected) + + def test_update_raises_on_duplicate_argument_index(self): + # GH#55509 + df = pd.DataFrame({"a": [1, 1]}, index=[1, 2]) + other = pd.DataFrame({"a": [2, 3]}, index=[1, 1]) + with pytest.raises(ValueError, match="duplicate index"): + df.update(other) + + def test_update_without_intersection(self): + # GH#63452 + orig = pd.DataFrame({"a": [1]}, index=[1]) + df = orig.copy() + other = pd.DataFrame({"a": [2]}, index=[2]) + df.update(other) + tm.assert_frame_equal(df, orig) + + def test_update_on_duplicate_frame_unique_argument_index(self): + # GH#55509 + df = pd.DataFrame({"a": [1, 1, 1]}, index=[1, 1, 2], dtype=np.dtype("intc")) + other = pd.DataFrame({"a": [2, 3]}, index=[1, 2], dtype=np.dtype("intc")) + expected = pd.DataFrame( + {"a": [2, 2, 3]}, index=[1, 1, 2], dtype=np.dtype("intc") + ) + df.update(other) + tm.assert_frame_equal(df, expected) + + def test_update_preserve_mixed_dtypes(self): + # GH#44104 + dtype1 = pd.Int64Dtype() + dtype2 = pd.StringDtype() + df = pd.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]}) + df = df.astype({"a": dtype1, "b": dtype2}) + + other = pd.DataFrame({"a": [4, 5], "b": ["a", "b"]}) + other = other.astype({"a": dtype1, "b": dtype2}) + + expected = pd.DataFrame({"a": [4, 5, 3], "b": ["a", "b", "z"]}) + expected = expected.astype({"a": dtype1, "b": dtype2}) + + df.update(other) + tm.assert_frame_equal(df, expected) + + def test_update_datetime_column_after_setting_none(self): + # GH#29462 + + df = pd.DataFrame({"date": [pd.Timestamp("2026-02-05")]}) + + other = df.copy() + other["date"] = None + + other.update(df) + expected = pd.DataFrame({"date": [pd.Timestamp("2026-02-05")]}, dtype=object) + + tm.assert_frame_equal(other, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_value_counts.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_value_counts.py new file mode 100644 index 0000000000000000000000000000000000000000..43db234267f21f6cd8c98d222d634b3a6b4d364b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_value_counts.py @@ -0,0 +1,205 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_data_frame_value_counts_unsorted(): + df = pd.DataFrame( + {"num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + + result = df.value_counts(sort=False) + expected = pd.Series( + data=[1, 2, 1], + index=pd.MultiIndex.from_arrays( + [(2, 4, 6), (2, 0, 0)], names=["num_legs", "num_wings"] + ), + name="count", + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_ascending(): + df = pd.DataFrame( + {"num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + + result = df.value_counts(ascending=True) + expected = pd.Series( + data=[1, 1, 2], + index=pd.MultiIndex.from_arrays( + [(2, 6, 4), (2, 0, 0)], names=["num_legs", "num_wings"] + ), + name="count", + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_default(): + df = pd.DataFrame( + {"num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + + result = df.value_counts() + expected = pd.Series( + data=[2, 1, 1], + index=pd.MultiIndex.from_arrays( + [(4, 2, 6), (0, 2, 0)], names=["num_legs", "num_wings"] + ), + name="count", + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_normalize(): + df = pd.DataFrame( + {"num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + + result = df.value_counts(normalize=True) + expected = pd.Series( + data=[0.5, 0.25, 0.25], + index=pd.MultiIndex.from_arrays( + [(4, 2, 6), (0, 2, 0)], names=["num_legs", "num_wings"] + ), + name="proportion", + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_single_col_default(): + df = pd.DataFrame({"num_legs": [2, 4, 4, 6]}) + + result = df.value_counts() + expected = pd.Series( + data=[2, 1, 1], + index=pd.MultiIndex.from_arrays([[4, 2, 6]], names=["num_legs"]), + name="count", + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_empty(): + df_no_cols = pd.DataFrame() + + result = df_no_cols.value_counts() + expected = pd.Series( + [], dtype=np.int64, name="count", index=np.array([], dtype=np.intp) + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_empty_normalize(): + df_no_cols = pd.DataFrame() + + result = df_no_cols.value_counts(normalize=True) + expected = pd.Series( + [], dtype=np.float64, name="proportion", index=np.array([], dtype=np.intp) + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_dropna_true(nulls_fixture): + # GH 41334 + df = pd.DataFrame( + { + "first_name": ["John", "Anne", "John", "Beth"], + "middle_name": ["Smith", nulls_fixture, nulls_fixture, "Louise"], + }, + ) + result = df.value_counts() + expected = pd.Series( + data=[1, 1], + index=pd.MultiIndex.from_arrays( + [("John", "Beth"), ("Smith", "Louise")], names=["first_name", "middle_name"] + ), + name="count", + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_dropna_false(nulls_fixture): + # GH 41334 + df = pd.DataFrame( + { + "first_name": ["John", "Anne", "John", "Beth"], + "middle_name": ["Smith", nulls_fixture, nulls_fixture, "Louise"], + }, + ) + + result = df.value_counts(dropna=False) + expected = pd.Series( + data=[1, 1, 1, 1], + index=pd.MultiIndex( + levels=[ + pd.Index(["Anne", "Beth", "John"]), + pd.Index(["Louise", "Smith", np.nan]), + ], + codes=[[2, 0, 2, 1], [1, 2, 2, 0]], + names=["first_name", "middle_name"], + ), + name="count", + ) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("columns", (["first_name", "middle_name"], [0, 1])) +def test_data_frame_value_counts_subset(nulls_fixture, columns): + # GH 50829 + df = pd.DataFrame( + { + columns[0]: ["John", "Anne", "John", "Beth"], + columns[1]: ["Smith", nulls_fixture, nulls_fixture, "Louise"], + }, + ) + result = df.value_counts(columns[0]) + expected = pd.Series( + data=[2, 1, 1], + index=pd.Index(["John", "Anne", "Beth"], name=columns[0]), + name="count", + ) + + tm.assert_series_equal(result, expected) + + +def test_value_counts_categorical_future_warning(): + # GH#54775 + df = pd.DataFrame({"a": [1, 2, 3]}, dtype="category") + result = df.value_counts() + expected = pd.Series( + 1, + index=pd.MultiIndex.from_arrays( + [pd.Index([1, 2, 3], name="a", dtype="category")] + ), + name="count", + ) + tm.assert_series_equal(result, expected) + + +def test_value_counts_with_missing_category(): + # GH-54836 + df = pd.DataFrame({"a": pd.Categorical([1, 2, 4], categories=[1, 2, 3, 4])}) + result = df.value_counts() + expected = pd.Series( + [1, 1, 1, 0], + index=pd.MultiIndex.from_arrays( + [pd.CategoricalIndex([1, 2, 4, 3], categories=[1, 2, 3, 4], name="a")] + ), + name="count", + ) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_values.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_values.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0e19779892f587315fb4c5ef5acf25242104dc --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/methods/test_values.py @@ -0,0 +1,256 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameValues: + def test_values(self, float_frame): + with pytest.raises(ValueError, match="read-only"): + float_frame.values[:, 0] = 5.0 + assert (float_frame.values[:, 0] != 5).all() + + def test_more_values(self, float_string_frame): + values = float_string_frame.values + assert values.shape[1] == len(float_string_frame.columns) + + def test_values_mixed_dtypes(self, float_frame, float_string_frame): + frame = float_frame + arr = frame.values + + frame_cols = frame.columns + for i, row in enumerate(arr): + for j, value in enumerate(row): + col = frame_cols[j] + if np.isnan(value): + assert np.isnan(frame[col].iloc[i]) + else: + assert value == frame[col].iloc[i] + + # mixed type + arr = float_string_frame[["foo", "A"]].values + assert arr[0, 0] == "bar" + + df = pd.DataFrame({"complex": [1j, 2j, 3j], "real": [1, 2, 3]}) + arr = df.values + assert arr[0, 0] == 1j + + def test_values_duplicates(self): + df = pd.DataFrame( + [[1, 2, "a", "b"], [1, 2, "a", "b"]], columns=["one", "one", "two", "two"] + ) + + result = df.values + expected = np.array([[1, 2, "a", "b"], [1, 2, "a", "b"]], dtype=object) + + tm.assert_numpy_array_equal(result, expected) + + def test_values_with_duplicate_columns(self): + df = pd.DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=["x", "x"]) + result = df.values + expected = np.array([[1, 2.5], [3, 4.5]]) + assert (result == expected).all().all() + + @pytest.mark.parametrize("constructor", [pd.date_range, pd.period_range]) + def test_values_casts_datetimelike_to_object(self, constructor): + series = pd.Series(constructor("2000-01-01", periods=10, freq="D")) + + expected = series.astype("object") + + df = pd.DataFrame( + {"a": series, "b": np.random.default_rng(2).standard_normal(len(series))} + ) + + result = df.values.squeeze() + assert (result[:, 0] == expected.values).all() + + df = pd.DataFrame({"a": series, "b": ["foo"] * len(series)}) + + result = df.values.squeeze() + assert (result[:, 0] == expected.values).all() + + def test_frame_values_with_tz(self): + tz = "US/Central" + df = pd.DataFrame({"A": pd.date_range("2000", periods=4, tz=tz)}) + result = df.values + expected = np.array( + [ + [pd.Timestamp("2000-01-01", tz=tz)], + [pd.Timestamp("2000-01-02", tz=tz)], + [pd.Timestamp("2000-01-03", tz=tz)], + [pd.Timestamp("2000-01-04", tz=tz)], + ] + ) + tm.assert_numpy_array_equal(result, expected) + + # two columns, homogeneous + + df["B"] = df["A"] + result = df.values + expected = np.concatenate([expected, expected], axis=1) + tm.assert_numpy_array_equal(result, expected) + + # three columns, heterogeneous + est = "US/Eastern" + df["C"] = df["A"].dt.tz_convert(est) + + new = np.array( + [ + [pd.Timestamp("2000-01-01T01:00:00", tz=est)], + [pd.Timestamp("2000-01-02T01:00:00", tz=est)], + [pd.Timestamp("2000-01-03T01:00:00", tz=est)], + [pd.Timestamp("2000-01-04T01:00:00", tz=est)], + ] + ) + expected = np.concatenate([expected, new], axis=1) + result = df.values + tm.assert_numpy_array_equal(result, expected) + + def test_interleave_with_tzaware(self, timezone_frame): + # interleave with object + result = timezone_frame.assign(D="foo").values + expected = np.array( + [ + [ + pd.Timestamp("2013-01-01 00:00:00"), + pd.Timestamp("2013-01-02 00:00:00"), + pd.Timestamp("2013-01-03 00:00:00"), + ], + [ + pd.Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"), + pd.NaT, + pd.Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"), + ], + [ + pd.Timestamp("2013-01-01 00:00:00+0100", tz="CET"), + pd.NaT, + pd.Timestamp("2013-01-03 00:00:00+0100", tz="CET"), + ], + ["foo", "foo", "foo"], + ], + dtype=object, + ).T + tm.assert_numpy_array_equal(result, expected) + + # interleave with only datetime64[ns] + result = timezone_frame.values + expected = np.array( + [ + [ + pd.Timestamp("2013-01-01 00:00:00"), + pd.Timestamp("2013-01-02 00:00:00"), + pd.Timestamp("2013-01-03 00:00:00"), + ], + [ + pd.Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"), + pd.NaT, + pd.Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"), + ], + [ + pd.Timestamp("2013-01-01 00:00:00+0100", tz="CET"), + pd.NaT, + pd.Timestamp("2013-01-03 00:00:00+0100", tz="CET"), + ], + ], + dtype=object, + ).T + tm.assert_numpy_array_equal(result, expected) + + def test_values_interleave_non_unique_cols(self): + df = pd.DataFrame( + [[pd.Timestamp("20130101"), 3.5], [pd.Timestamp("20130102"), 4.5]], + columns=["x", "x"], + index=[1, 2], + ) + + df_unique = df.copy() + df_unique.columns = ["x", "y"] + assert df_unique.values.shape == df.values.shape + tm.assert_numpy_array_equal(df_unique.values[0], df.values[0]) + tm.assert_numpy_array_equal(df_unique.values[1], df.values[1]) + + def test_values_numeric_cols(self, float_frame): + float_frame["foo"] = "bar" + + values = float_frame[["A", "B", "C", "D"]].values + assert values.dtype == np.float64 + + def test_values_lcd(self, mixed_float_frame, mixed_int_frame): + # mixed lcd + values = mixed_float_frame[["A", "B", "C", "D"]].values + assert values.dtype == np.float64 + + values = mixed_float_frame[["A", "B", "C"]].values + assert values.dtype == np.float32 + + values = mixed_float_frame[["C"]].values + assert values.dtype == np.float16 + + # GH#10364 + # B uint64 forces float because there are other signed int types + values = mixed_int_frame[["A", "B", "C", "D"]].values + assert values.dtype == np.float64 + + values = mixed_int_frame[["A", "D"]].values + assert values.dtype == np.int64 + + # B uint64 forces float because there are other signed int types + values = mixed_int_frame[["A", "B", "C"]].values + assert values.dtype == np.float64 + + # as B and C are both unsigned, no forcing to float is needed + values = mixed_int_frame[["B", "C"]].values + assert values.dtype == np.uint64 + + values = mixed_int_frame[["A", "C"]].values + assert values.dtype == np.int32 + + values = mixed_int_frame[["C", "D"]].values + assert values.dtype == np.int64 + + values = mixed_int_frame[["A"]].values + assert values.dtype == np.int32 + + values = mixed_int_frame[["C"]].values + assert values.dtype == np.uint8 + + +class TestPrivateValues: + def test_private_values_dt64tz(self): + dta = pd.date_range("2000", periods=4, tz="US/Central")._data.reshape(-1, 1) + + df = pd.DataFrame(dta, columns=["A"]) + tm.assert_equal(df._values, dta) + + assert not np.shares_memory(df._values._ndarray, dta._ndarray) + + # TimedeltaArray + tda = dta - dta + df2 = df - df + tm.assert_equal(df2._values, tda) + + def test_private_values_dt64tz_multicol(self): + dta = pd.date_range("2000", periods=8, tz="US/Central")._data.reshape(-1, 2) + + df = pd.DataFrame(dta, columns=["A", "B"]) + tm.assert_equal(df._values, dta) + + assert not np.shares_memory(df._values._ndarray, dta._ndarray) + + # TimedeltaArray + tda = dta - dta + df2 = df - df + tm.assert_equal(df2._values, tda) + + def test_private_values_dt64_multiblock(self): + dta = pd.date_range("2000", periods=8)._data + + df = pd.DataFrame({"A": dta[:4]}, copy=False) + df["B"] = dta[4:] + + assert len(df._mgr.blocks) == 2 + + result = df._values + expected = dta.reshape(2, 4).T + tm.assert_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_alter_axes.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_alter_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..e9bbb0c0f0e7210667745017557d5105a6f8180e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_alter_axes.py @@ -0,0 +1,31 @@ +from datetime import ( + UTC, + datetime, +) + +import pandas as pd +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 = pd.DataFrame([{"ts": datetime(2014, 4, 1, tzinfo=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/venv/lib/python3.14/site-packages/pandas/tests/frame/test_api.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8895de2baf0651fd58a7ba9bfbcc164117d932 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_api.py @@ -0,0 +1,405 @@ +from copy import deepcopy +import inspect +import pydoc + +import numpy as np +import pytest + +from pandas._config import using_string_dtype +from pandas._config.config import option_context + +from pandas.compat import HAS_PYARROW + +import pandas as pd +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 = pd.DataFrame([list("abcd"), list("efgh")], columns=list("ABCD")) + for key in list("ABCD"): + assert key in dir(df) + assert isinstance(df.__getitem__("A"), pd.Series) + + # DataFrame whose first-level columns are identifiers shall have + # them in __dir__. + df = pd.DataFrame( + [list("abcd"), list("efgh")], + columns=pd.MultiIndex.from_tuples(list(zip("ABCD", "EFGH", strict=True))), + ) + 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"), pd.DataFrame) + + def test_display_max_dir_items(self): + # display.max_dir_items increases the number of columns that are in __dir__. + columns = ["a" + str(i) for i in range(420)] + values = [range(420), range(420)] + df = pd.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 = pd.DataFrame(values, columns=columns) + assert "a299" in dir(df) + assert "a300" not in dir(df) + + with option_context("display.max_dir_items", None): + df = pd.DataFrame(values, columns=columns) + assert "a419" in dir(df) + + def test_not_hashable(self): + empty_frame = pd.DataFrame() + + df = pd.DataFrame([1]) + msg = "unhashable type: 'DataFrame'" + with pytest.raises(TypeError, match=msg): + hash(df) + with pytest.raises(TypeError, match=msg): + hash(empty_frame) + + @pytest.mark.xfail( + using_string_dtype() and HAS_PYARROW, reason="surrogates not allowed" + ) + def test_column_name_contains_unicode_surrogate(self): + # GH 25509 + colname = "\ud83d" + df = pd.DataFrame({colname: []}) + # this should not crash + assert colname not in dir(df) + assert df.columns[0] == colname + + def test_new_empty_index(self): + df1 = pd.DataFrame(np.random.default_rng(2).standard_normal((0, 3))) + df2 = pd.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 = pd.DataFrame() + assert empty_frame.empty + + assert not float_frame.empty + assert not float_string_frame.empty + + # corner case + df = pd.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(pd.DataFrame.index) + assert pydoc.getdoc(pd.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 = pd.DataFrame([1, 2, 3]) + assert not df.empty + df = pd.DataFrame(index=[1], columns=[1]) + assert not df.empty + df = pd.DataFrame(index=["a", "b"], columns=["c", "d"]).dropna() + assert df.empty + assert df.T.empty + + @pytest.mark.parametrize( + "df", + [ + pd.DataFrame(), + pd.DataFrame(index=[1]), + pd.DataFrame(columns=[1]), + pd.DataFrame({1: []}), + ], + ) + def test_empty_like(self, df): + assert df.empty + assert df.T.empty + + def test_with_datetimelikes(self): + df = pd.DataFrame( + { + "A": pd.date_range("20130101", periods=10), + "B": pd.timedelta_range("1 day", periods=10), + } + ) + t = df.T + + result = t.dtypes.value_counts() + expected = pd.Series({np.dtype("object"): 10}, name="count") + tm.assert_series_equal(result, expected) + + def test_deepcopy(self, float_frame): + cp = deepcopy(float_frame) + cp.loc[0, "A"] = 10 + assert not float_frame.equals(cp) + + @pytest.mark.filterwarnings("ignore:The inplace keyword") + def test_inplace_return_self(self): + # GH 1893 + + data = pd.DataFrame( + {"a": ["foo", "bar", "baz", "qux"], "b": [0, 0, 1, 1], "c": [1, 2, 3, 4]} + ) + + def _check_none(base, f): + result = f(base) + assert result is None + + def _check_return(base, f): + result = f(base) + assert result is base + + # -----DataFrame----- + + # set_index + f = lambda x: x.set_index("a", inplace=True) + _check_none(data.copy(), f) + + # reset_index + f = lambda x: x.reset_index(inplace=True) + _check_none(data.set_index("a"), f) + + # drop_duplicates + f = lambda x: x.drop_duplicates(inplace=True) + _check_none(data.copy(), f) + + # sort + f = lambda x: x.sort_values("b", inplace=True) + _check_none(data.copy(), f) + + # sort_index + f = lambda x: x.sort_index(inplace=True) + _check_none(data.copy(), f) + + # fillna + f = lambda x: x.fillna(0, inplace=True) + _check_return(data.copy(), f) + + # replace + f = lambda x: x.replace(1, 0, inplace=True) + _check_return(data.copy(), f) + + # rename + f = lambda x: x.rename({1: "foo"}, inplace=True) + _check_none(data.copy(), f) + + # -----Series----- + d = data.copy()["c"] + + # reset_index + f = lambda x: x.reset_index(inplace=True, drop=True) + _check_none(data.set_index("a")["c"], f) + + # fillna + f = lambda x: x.fillna(0, inplace=True) + _check_return(d.copy(), f) + + # replace + f = lambda x: x.replace(1, 0, inplace=True) + _check_return(d.copy(), f) + + # rename + f = lambda x: x.rename({1: "foo"}, inplace=True) + _check_none(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 pd.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 = pd.DataFrame({"A": [2, 3]}) + assert df.attrs == {} + df.attrs["version"] = 1 + + result = df.rename(columns=str) + assert result.attrs == {"version": 1} + + def test_attrs_is_deepcopy(self): + df = pd.DataFrame({"A": [2, 3]}) + assert df.attrs == {} + df.attrs["tags"] = {"spam", "ham"} + + result = df.rename(columns=str) + assert result.attrs == df.attrs + assert result.attrs["tags"] is not df.attrs["tags"] + + def test_attrs_concat(self): + # concat propagates attrs if all input attrs are equal + df1 = pd.DataFrame({"A": [2, 3]}) + df1.attrs = {"a": 1, "b": 2} + df2 = pd.DataFrame({"A": [4, 5]}) + df2.attrs = df1.attrs.copy() + df3 = pd.DataFrame({"A": [6, 7]}) + df3.attrs = df1.attrs.copy() + assert pd.concat([df1, df2, df3]).attrs == df1.attrs + # concat does not propagate attrs if input attrs are different + df2.attrs = {"c": 3} + assert pd.concat([df1, df2, df3]).attrs == {} + + def test_attrs_merge(self): + # merge propagates attrs if all input attrs are equal + df1 = pd.DataFrame({"key": ["a", "b"], "val1": [1, 2]}) + df1.attrs = {"a": 1, "b": 2} + df2 = pd.DataFrame({"key": ["a", "b"], "val2": [3, 4]}) + df2.attrs = df1.attrs.copy() + assert pd.merge(df1, df2).attrs == df1.attrs + # merge does not propagate attrs if input attrs are different + df2.attrs = {"c": 3} + assert pd.merge(df1, df2).attrs == {} + + @pytest.mark.parametrize("allows_duplicate_labels", [True, False, None]) + def test_set_flags( + self, + allows_duplicate_labels, + frame_or_series, + ): + obj = pd.DataFrame({"A": [1, 2]}) + key = (0, 0) + if frame_or_series is pd.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 pd.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 + assert obj.iloc[key] == 1 + + # Now we do copy. + result = obj.set_flags(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 = pd.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 + df = pd.DataFrame() + inspect.getmembers(df) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_arithmetic.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_arithmetic.py new file mode 100644 index 0000000000000000000000000000000000000000..59d27212d908b2dcfa6300580f55618bfbd699fe --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_arithmetic.py @@ -0,0 +1,2484 @@ +from collections import deque +from datetime import ( + UTC, + datetime, +) +from enum import Enum +import functools +import operator +import re + +import numpy as np +import pytest + +from pandas.compat._optional import import_optional_dependency +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.core.computation import expressions as expr +from pandas.tests.frame.common import ( + _check_mixed_float, + _check_mixed_int, +) +from pandas.util.version import Version + + +@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 pd.DataFrame(arr, columns=["one", "two", "three"], index=["a", "b", "c"]) + + +@pytest.fixture(autouse=True, params=[0, 100], ids=["numexpr", "python"]) +def switch_numexpr_min_elements(request, monkeypatch): + with monkeypatch.context() as m: + m.setattr(expr, "_MIN_ELEMENTS", request.param) + yield request.param + + +class DummyElement: + def __init__(self, value, dtype) -> None: + self.value = value + self.dtype = np.dtype(dtype) + + def __array__(self, dtype=None, copy=None): + 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 = pd.DataFrame({"A": ["foo", "bar", "baz"]}) + exp = pd.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 = pd.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, unit="ns"), + }, + { + "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, unit="ns"), + }, + ], + [ + { + "a": pd.date_range("20010101", periods=10, unit="ns"), + "b": pd.date_range("20010101", periods=10, unit="ns"), + }, + { + "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, unit="ns"), + }, + { + "a": pd.date_range("20010101", periods=10, unit="ns"), + "b": pd.date_range("20010101", periods=10, unit="ns"), + }, + ], + ], + ) + def test_comparison_invalid(self, arg, arg2): + # GH4968 + # invalid date/int comparisons + x = pd.DataFrame(arg) + y = pd.DataFrame(arg2) + # we expect the result to match Series comparisons for + # == and !=, inequalities should raise + result = x == y + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame([["1989-08-01", 1], ["1989-08-01", 2]]) + other = pd.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 = pd.DataFrame(np.arange(6).reshape((3, 2))) + + expected = pd.DataFrame([[False, False], [True, False], [False, False]]) + + depr_msg = "In a future version these will be treated as scalar-like" + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + 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 = pd.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 = pd.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 + def test_bool_flex_frame(self, comparison_op): + data = np.random.default_rng(2).standard_normal((5, 3)) + other_data = np.random.default_rng(2).standard_normal((5, 3)) + df = pd.DataFrame(data) + other = pd.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, comparison_op.__name__) + o = comparison_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, pd.Series]) + def test_bool_flex_series(self, box): + # Series + # list/tuple + data = np.random.default_rng(2).standard_normal((5, 3)) + df = pd.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 == pd.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(pd.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 > pd.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 >= pd.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 = pd.Series(np.random.default_rng(2).standard_normal(5)) + col_ser = pd.Series(np.random.default_rng(2).standard_normal(3)) + + def test_bool_flex_frame_na(self): + df = pd.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 = pd.DataFrame({"a": arr}) + df2 = pd.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 = pd.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 = pd.DataFrame({"col": ["foo", np.nan, "bar"]}, dtype=object) + df2 = pd.DataFrame({"col": ["foo", datetime(2011, 1, 1), "bar"]}, dtype=object) + result = df1.ne(df2) + exp = pd.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 = pd.DataFrame([pd.NaT]) + + result = df == pd.NaT + expected = pd.DataFrame([False]) + tm.assert_frame_equal(result, expected) + + result = df.eq(pd.NaT) + tm.assert_frame_equal(result, expected) + + result = df != pd.NaT + expected = pd.DataFrame([True]) + tm.assert_frame_equal(result, expected) + + result = df.ne(pd.NaT) + tm.assert_frame_equal(result, expected) + + def test_df_flex_cmp_constant_return_types(self, comparison_op): + # GH 15077, non-empty DataFrame + df = pd.DataFrame({"x": [1, 2, 3], "y": [1.0, 2.0, 3.0]}) + const = 2 + + result = getattr(df, comparison_op.__name__)(const).dtypes.value_counts() + tm.assert_series_equal( + result, pd.Series([2], index=[np.dtype(bool)], name="count") + ) + + def test_df_flex_cmp_constant_return_types_empty(self, comparison_op): + # GH 15077 empty DataFrame + df = pd.DataFrame({"x": [1, 2, 3], "y": [1.0, 2.0, 3.0]}) + const = 2 + + empty = df.iloc[:0] + result = getattr(empty, comparison_op.__name__)(const).dtypes.value_counts() + tm.assert_series_equal( + result, pd.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 = pd.DataFrame({"A": ii, "B": ii}) + + ser = pd.Series([0, 0]) + res = df.eq(ser, axis=0) + + expected = pd.DataFrame({"A": [False, False], "B": [False, False]}) + tm.assert_frame_equal(res, expected) + + ser2 = pd.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 = pd.Series(arr) + df = pd.DataFrame({"A": ser, "B": ser}) + + result = df.floordiv(ser, axis=0) + + expected = pd.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) + + 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 = pd.Series(tdi) + df = pd.DataFrame({0: dti, 1: tdi}) + + result = df.add(tser, axis=0) + expected = pd.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 = pd.Series(["1 Day", "NaT", "2 Days"], dtype="timedelta64[ns]") + df = pd.DataFrame({"A": dti, "B": ser}) + other = pd.DataFrame({"A": ser, "B": ser}) + fill = pd.Timedelta(days=1).to_timedelta64() + result = df.add(other, fill_value=fill) + + expected = pd.DataFrame( + { + "A": pd.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]) + expected = float_frame.sort_index() * np.nan + tm.assert_frame_equal(result, expected) + + result = float_frame[:0].add(float_frame) + expected = float_frame.sort_index() * np.nan + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("axis", [0, 1]) + def test_arith_flex_frame_fill_value_series(self, axis): + # GH#61581 + df = pd.DataFrame({"A": [1.0, np.nan], "B": [np.nan, 4.0]}) + if axis == 0: + ser = pd.Series([np.nan, 2.0]) + expected = pd.DataFrame({"A": [11.0, 12.0], "B": [np.nan, 6.0]}) + else: + ser = pd.Series([np.nan, 2.0], index=["A", "B"]) + expected = pd.DataFrame({"A": [11.0, np.nan], "B": [12.0, 6.0]}) + result = df.add(ser, axis=axis, fill_value=10) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("axis", [0, 1]) + def test_arith_flex_frame_fill_value_series_mismatched_index(self, axis): + # GH#61581 + ser = pd.Series([10.0, np.nan], index=["A", "C"]) + if axis == 0: + df = pd.DataFrame( + {"A": [1.0, np.nan], "B": [np.nan, 4.0]}, index=["A", "B"] + ) + expected = pd.DataFrame( + {"A": [11.0, np.nan, np.nan], "B": [15.0, 9.0, np.nan]}, + index=["A", "B", "C"], + ) + else: + df = pd.DataFrame({"A": [1.0, np.nan], "B": [np.nan, 4.0]}, index=[0, 1]) + expected = pd.DataFrame( + {"A": [11.0, 15.0], "B": [np.nan, 9.0], "C": [np.nan, np.nan]}, + index=[0, 1], + ) + result = df.add(ser, axis=axis, fill_value=5) + tm.assert_frame_equal(result, expected) + + @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) + + def test_arith_flex_series_broadcasting(self, any_real_numpy_dtype): + # broadcasting issue in GH 7325 + df = pd.DataFrame(np.arange(3 * 2).reshape((3, 2)), dtype=any_real_numpy_dtype) + expected = pd.DataFrame([[np.nan, np.inf], [1.0, 1.5], [1.0, 1.25]]) + if any_real_numpy_dtype == "float32": + expected = expected.astype(any_real_numpy_dtype) + result = df.div(df[0], axis="index") + tm.assert_frame_equal(result, expected) + + def test_arith_flex_zero_len_fill_value(self): + ser_len0 = pd.Series([], dtype=object) + df_len0 = pd.DataFrame(columns=["A", "B"]) + df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + + msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'" + with pytest.raises(TypeError, match=msg): + df.add(ser_len0, fill_value="E") + + result = df_len0.sub(df, axis=None, fill_value=3) + expected = pd.DataFrame([[2, 1], [0, -1]], columns=["A", "B"]) + tm.assert_frame_equal(result, expected, check_dtype=False) + + result = df_len0.sub(df["A"], axis=0, fill_value=3) + expected = pd.DataFrame([[2, 2], [0, 0]], columns=["A", "B"]) + tm.assert_frame_equal(result, expected, check_dtype=False) + + result = df_len0.sub(df["A"], axis=1, fill_value=3) + expected = pd.DataFrame([], columns=["A", "B", 0, 1]) + tm.assert_frame_equal(result, expected, check_dtype=False) + + def test_flex_add_scalar_fill_value(self): + # GH#12723 + dat = np.array([0, 1, np.nan, 3, 4, 5], dtype="float") + df = pd.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 = pd.DataFrame([1, 2, 3, 4, 5], index=[1, 2, 1, 2, 3]) + df2 = pd.DataFrame([1, 2, 3], index=[1, 2, 3]) + expected = pd.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 = pd.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) + + @pytest.mark.parametrize("level", [0, None]) + def test_broadcast_multiindex(self, level): + # GH34388 + df1 = pd.DataFrame({"A": [0, 1, 2], "B": [1, 2, 3]}) + df1.columns = df1.columns.set_names("L1") + + df2 = pd.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 = pd.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 = pd.DataFrame( + {2010: [1, 2, 3], 2020: [3, 4, 5]}, + index=pd.MultiIndex.from_product( + [["a"], ["b"], [0, 1, 2]], names=["scen", "mod", "id"] + ), + ) + + series = pd.Series( + [0.4], + index=pd.MultiIndex.from_product([["b"], ["a"]], names=["mod", "scen"]), + ) + + expected = pd.DataFrame( + {2010: [1.4, 2.4, 3.4], 2020: [3.4, 4.4, 5.4]}, + index=pd.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 = pd.DataFrame( + {2010: [1], 2020: [3]}, + index=pd.MultiIndex.from_product([["a"], ["b"]], names=["scen", "mod"]), + ) + + series = pd.Series( + [10.0, 20.0, 30.0], + index=pd.MultiIndex.from_product( + [["a"], ["b"], [0, 1, 2]], names=["scen", "mod", "id"] + ), + ) + + expected = pd.DataFrame( + {2010: [11.0, 21, 31.0], 2020: [13.0, 23.0, 33.0]}, + index=pd.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 = pd.DataFrame( + {2010: [1, 2, 3], 2020: [3, 4, 5]}, + index=pd.MultiIndex.from_product( + [["a"], ["b"], [0, 1, 2]], names=["scen", "mod", "id"] + ), + ) + + series = pd.Series( + [0.4], + index=pd.MultiIndex.from_product([["c"], ["a"]], names=["mod", "scen"]), + ) + + expected = pd.DataFrame( + {2010: np.nan, 2020: np.nan}, + index=pd.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 = pd.DataFrame( + {2010: [1, 2, 3], 2020: [3, 4, 5]}, + index=pd.MultiIndex.from_tuples( + [ + ("a", "b", 0), + ("a", "b", 1), + ("a", "c", 2), + ], + names=["scen", "mod", "id"], + ), + ) + + series = pd.Series( + [0.4], + index=pd.MultiIndex.from_product([["b"], ["a"]], names=["mod", "scen"]), + ) + + expected = pd.DataFrame( + {2010: [1.4, 2.4, np.nan], 2020: [3.4, 4.4, np.nan]}, + index=pd.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) + + def test_frame_multiindex_operations_part_align_axis1(self): + # GH#61009 Test DataFrame-Series arithmetic operation + # with partly aligned MultiIndex and axis = 1 + df = pd.DataFrame( + [[1, 2, 3], [3, 4, 5]], + index=[2010, 2020], + columns=pd.MultiIndex.from_tuples( + [ + ("a", "b", 0), + ("a", "b", 1), + ("a", "c", 2), + ], + names=["scen", "mod", "id"], + ), + ) + + series = pd.Series( + [0.4], + index=pd.MultiIndex.from_product([["b"], ["a"]], names=["mod", "scen"]), + ) + + expected = pd.DataFrame( + [[1.4, 2.4, np.nan], [3.4, 4.4, np.nan]], + index=[2010, 2020], + columns=pd.MultiIndex.from_tuples( + [ + ("a", "b", 0), + ("a", "b", 1), + ("a", "c", 2), + ], + names=["scen", "mod", "id"], + ), + ) + result = df.add(series, axis=1) + + 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 = pd.Series(["NaT", "NaT"], dtype="timedelta64[ns]") + df = pd.DataFrame([[1, 2], [3, 4]]) + + result = df * ser + expected = pd.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 = pd.DataFrame(arr, columns=[True, False], index=["A", "B", "C"]) + + rowlike = arr[[1], :] # shape --> (1, ncols) + assert rowlike.shape == (1, df.shape[1]) + + expected = pd.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 = pd.DataFrame(arr, columns=[True, False], index=["A", "B", "C"]) + + collike = arr[:, [1]] # shape --> (nrows, 1) + assert collike.shape == (df.shape[0], 1) + + expected = pd.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 + ): + # GH#23000 + opname = all_arithmetic_operators + arr = np.arange(6).reshape(3, 2) + df = pd.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 = pd.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 + ): + # GH#23000 + opname = all_arithmetic_operators + arr = np.arange(6).reshape(3, 2) + df = pd.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 = pd.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 = pd.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 = pd.DataFrame({"A": ["a", "b", "c"], "B": [1, 2, 3]}) + + result = left + left + expected = pd.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 = pd.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 = pd.DataFrame({"A": [1, 1], "B": [1, 1]}) + expected = pd.DataFrame({"A": [2, 2], "B": [3, 3]}) + + depr_msg = "In a future version these will be treated as scalar-like" + warn = None + if isinstance(values, (range, deque, tuple)): + warn = Pandas4Warning + + with tm.assert_produces_warning(warn, match=depr_msg): + result = df + values + tm.assert_frame_equal(result, expected) + + def test_arith_non_pandas_object(self): + df = pd.DataFrame( + np.arange(1, 10, dtype="f8").reshape(3, 3), + columns=["one", "two", "three"], + index=["a", "b", "c"], + ) + + val1 = df.xs("a").values + added = pd.DataFrame(df.values + val1, index=df.index, columns=df.columns) + tm.assert_frame_equal(df + val1, added) + + added = pd.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 = pd.DataFrame(df.values + val2, index=df.index, columns=df.columns) + tm.assert_frame_equal(df + val2, added) + + added = pd.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 = pd.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 = pd.DataFrame([data], columns=ind) + num = 10 + result = getattr(df, op)(num) + expected = pd.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 = pd.DataFrame( + { + "foo": [pd.Timestamp("2019"), pd.Timestamp("2020")], + "bar": [pd.Timestamp("2018"), pd.Timestamp("2021")], + }, + columns=["foo", "bar"], + dtype="M8[ns]", + ) + df2 = df[["foo"]] + + result = df - df2 + + expected = pd.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"), "]=?' not supported between instances of 'str' and 'int'", + "Invalid comparison between dtype=str and int", + ] + ) + with pytest.raises(TypeError, match=msg): + f(df, 0) + + def test_comparison_protected_from_errstate(self): + missing_df = pd.DataFrame( + np.ones((10, 4), dtype=np.float64), + columns=pd.Index(list("ABCD"), dtype=object), + ) + missing_df.loc[missing_df.index[0], "A"] = np.nan + with np.errstate(invalid="ignore"): + expected = missing_df.values < 0 + with np.errstate(invalid="raise"): + result = (missing_df < 0).values + tm.assert_numpy_array_equal(result, expected) + + def test_boolean_comparison(self): + # GH 4576 + # boolean comparisons with a tuple/list give unexpected results + df = pd.DataFrame(np.arange(6).reshape((3, 2))) + b = np.array([2, 2]) + b_r = np.atleast_2d([2, 2]) + b_c = b_r.T + lst = [2, 2, 2] + tup = tuple(lst) + + # gt + expected = pd.DataFrame([[False, False], [False, True], [True, True]]) + result = df > 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 + + depr_msg = "In a future version these will be treated as scalar-like" + with pytest.raises(ValueError, match=msg1d): + # wrong shape + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + 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 = pd.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): + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + 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 = pd.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): + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + df == tup + + def test_inplace_ops_alignment(self): + # inplace ops / ops alignment + # GH 8511 + + columns = list("abcdefg") + X_orig = pd.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 = pd.Series([1, 2, 3]) + df_orig = pd.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 = pd.DataFrame({"A": arr.copy(), "B": "foo"}) + df = df_orig.copy() + df2 = df + df["A"] += 1 + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + index=index, + columns=columns, + ) + + align = pd.DataFrame._align_for_op + + depr_msg = "In a future version these will be treated as scalar-like" + warn = None + if isinstance(val, (tuple, range)): + warn = Pandas4Warning + + with tm.assert_produces_warning(warn, match=depr_msg): + result = align(df, val, axis=0)[1] + expected = pd.DataFrame({"X": val, "Y": val, "Z": val}, index=df.index) + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame( + {"X": [1, 1, 1], "Y": [2, 2, 2], "Z": [3, 3, 3]}, index=df.index + ) + with tm.assert_produces_warning(warn, match=depr_msg): + result = align(df, val, axis=1)[1] + tm.assert_frame_equal(result, 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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + index=index, + columns=columns, + ) + + depr_msg = "In a future version these will be treated as scalar-like" + warn = None + if isinstance(val, (tuple, range)): + warn = Pandas4Warning + + align = pd.DataFrame._align_for_op + # length mismatch + msg = "Unable to coerce to Series, length must be 3: given 2" + with pytest.raises(ValueError, match=msg): + with tm.assert_produces_warning(warn, match=depr_msg): + align(df, val, axis=0) + + with pytest.raises(ValueError, match=msg): + with tm.assert_produces_warning(warn, match=depr_msg): + align(df, val, axis=1) + + def test_alignment_non_pandas_index_columns(self): + index = ["A", "B", "C"] + columns = ["X", "Y", "Z"] + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + index=index, + columns=columns, + ) + + align = pd.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], + pd.DataFrame(val, index=df.index, columns=df.columns), + ) + tm.assert_frame_equal( + align(df, val, axis=1)[1], + pd.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 = pd.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#36796 frame.__foo__ should only accept one argument + df = pd.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 = pd.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 = pd.DataFrame({"A": [0, 1, 2]}) + right = pd.DataFrame(index=[0, 1, 2]) + + result = left**right + expected = pd.DataFrame({"A": [np.nan, 1.0, np.nan]}) + tm.assert_frame_equal(result, expected) + + +def test_dataframe_series_extension_dtypes(): + # https://github.com/pandas-dev/pandas/issues/34311 + df = pd.DataFrame( + np.random.default_rng(2).integers(0, 100, (10, 3)), columns=["a", "b", "c"] + ) + ser = pd.Series([1, 2, 3], index=["a", "b", "c"]) + + expected = df.to_numpy("int64") + ser.to_numpy("int64").reshape(-1, 3) + expected = pd.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 = pd.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 = pd.DataFrame({i: left[i] + right[i] for i in left.columns}) + tm.assert_frame_equal(res, expected) + + +@pytest.mark.parametrize( + "df, col_dtype", + [ + (pd.DataFrame([[1.0, 2.0], [4.0, 5.0]], columns=list("ab")), "float64"), + ( + pd.DataFrame([[1.0, "b"], [4.0, "b"]], columns=list("ab")).astype( + {"b": object} + ), + "object", + ), + ], +) +def test_dataframe_operation_with_non_numeric_types(df, col_dtype): + # GH #22663 + expected = pd.DataFrame([[0.0, np.nan], [3.0, np.nan]], columns=list("ab")) + expected = expected.astype({"b": col_dtype}) + result = df + pd.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 = pd.DataFrame(data=[[0]], columns=["second"]) + df2 = pd.DataFrame(data=[[0, 0, 0]], columns=["first", "second", "second"]) + result = df1 + df2 + expected = pd.DataFrame([[np.nan, 0, 0]], columns=["first", "second", "second"]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "to_add", [[pd.Series([1, 1])], [pd.Series([1, 1]), pd.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 = pd.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(): + # https://github.com/pandas-dev/pandas/issues/36373 + df = pd.DataFrame({"A": [1, 2, 3]}) + df_orig = df.copy() + series = df["A"] + vals = series._values + + series += 1 + assert series._values is not vals + tm.assert_frame_equal(df, df_orig) + + +def test_arithmetic_multiindex_align(): + """ + Regression test for: https://github.com/pandas-dev/pandas/issues/33765 + """ + df1 = pd.DataFrame( + [[1]], + index=["a"], + columns=pd.MultiIndex.from_product([[0], [1]], names=["a", "b"]), + ) + df2 = pd.DataFrame([[1]], index=["a"], columns=pd.Index([0], name="a")) + expected = pd.DataFrame( + [[0]], + index=["a"], + columns=pd.MultiIndex.from_product([[0], [1]], names=["a", "b"]), + ) + result = df1 - df2 + tm.assert_frame_equal(result, expected) + + +def test_arithmetic_multiindex_column_align(): + # GH#60498 + df1 = pd.DataFrame( + data=100, + columns=pd.MultiIndex.from_product( + [["1A", "1B"], ["2A", "2B"]], names=["Lev1", "Lev2"] + ), + index=["C1", "C2"], + ) + df2 = pd.DataFrame( + data=np.array([[0.1, 0.25], [0.2, 0.45]]), + columns=pd.MultiIndex.from_product([["1A", "1B"]], names=["Lev1"]), + index=["C1", "C2"], + ) + expected = pd.DataFrame( + data=np.array([[10.0, 10.0, 25.0, 25.0], [20.0, 20.0, 45.0, 45.0]]), + columns=pd.MultiIndex.from_product( + [["1A", "1B"], ["2A", "2B"]], names=["Lev1", "Lev2"] + ), + index=["C1", "C2"], + ) + result = df1 * df2 + tm.assert_frame_equal(result, expected) + + +def test_arithmetic_multiindex_column_align_with_fillvalue(): + # GH#60903 + df1 = pd.DataFrame( + data=[[1.0, 2.0]], + columns=pd.MultiIndex.from_tuples([("A", "one"), ("A", "two")]), + ) + df2 = pd.DataFrame( + data=[[3.0, 4.0]], + columns=pd.MultiIndex.from_tuples([("B", "one"), ("B", "two")]), + ) + expected = pd.DataFrame( + data=[[1.0, 2.0, 3.0, 4.0]], + columns=pd.MultiIndex.from_tuples( + [("A", "one"), ("A", "two"), ("B", "one"), ("B", "two")] + ), + ) + result = df1.add(df2, fill_value=0) + tm.assert_frame_equal(result, expected) + + +def test_arithmetic_multiindex_with_nan_index_and_fill_value(): + # GH#30857 partially-overlapping MultiIndexes with NaN entries on both + # sides plus fill_value used to align onto a non-unique index because + # MultiIndex.union failed to deduplicate NaN-bearing rows. + df0 = pd.DataFrame( + data=np.arange(1, 19).reshape(9, 2), + columns=["happy", "sad"], + index=pd.MultiIndex.from_product( + [["a", "b", None], [0, 1, np.nan]], names=["l0", "l1"] + ), + ) + df1 = pd.DataFrame( + data=np.arange(1, 19).reshape(9, 2), + columns=["happy", "sad"], + index=pd.MultiIndex.from_product( + [["b", "c", None], [1, 2, np.nan]], names=["l0", "l1"] + ), + ) + + result = df0.subtract(df1, fill_value=0) + + expected = pd.DataFrame( + [ + [1.0, 2.0], + [3.0, 4.0], + [5.0, 6.0], + [7.0, 8.0], + [8.0, 8.0], + [-3.0, -4.0], + [6.0, 6.0], + [-7.0, -8.0], + [-9.0, -10.0], + [-11.0, -12.0], + [13.0, 14.0], + [2.0, 2.0], + [-15.0, -16.0], + [0.0, 0.0], + ], + columns=["happy", "sad"], + index=df0.index.union(df1.index), + ) + + tm.assert_frame_equal(result, expected) + assert result.index.is_unique + + +def test_arithmetic_multiindex_add_with_mixed_string_datetime_index(): + # GH#26558 + df1 = pd.DataFrame( + data=[10], + index=pd.MultiIndex.from_tuples([("Z", "2019-05-31")]), + columns=["A"], + ) + df2 = pd.DataFrame( + data=[20], + index=pd.MultiIndex.from_tuples([("Z", datetime(2019, 5, 31))]), + columns=["A"], + ) + + expected = pd.DataFrame( + data=[20.0, 10.0], + index=pd.MultiIndex.from_tuples( + [("Z", datetime(2019, 5, 31)), ("Z", "2019-05-31")] + ), + columns=["A"], + ) + + with tm.assert_produces_warning(RuntimeWarning, match="are unorderable"): + result = df1.add(df2, fill_value=0) + + tm.assert_frame_equal(result, expected) + + +def test_bool_frame_mult_float(): + # GH 18549 + df = pd.DataFrame(True, list("ab"), list("cd")) + result = df * 1.0 + expected = pd.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 = pd.Series([1, 2, None], dtype=any_int_ea_dtype) + series2 = pd.Series([1, 2, 3], dtype=any_int_ea_dtype) + expected = pd.DataFrame([0, 0, None], dtype=any_int_ea_dtype) + result = series1.to_frame() - series2.to_frame() + tm.assert_frame_equal(result, expected) + + +def test_frame_op_subclass_nonclass_constructor(): + # GH#43201 subclass._constructor is a function, not the subclass itself + + class SubclassedSeries(pd.Series): + @property + def _constructor(self): + return SubclassedSeries + + @property + def _constructor_expanddim(self): + return SubclassedDataFrame + + class SubclassedDataFrame(pd.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 = pd.DataFrame({Cols.col1: [1, 2, 3]}) + q2 = pd.DataFrame({Cols.col1: [1, 2, 3]}) + + result = q1[Cols.col1] == q2[Cols.col1] + expected = pd.Series([True, True, True], name=Cols.col1) + + tm.assert_series_equal(result, expected) + + +def test_mixed_col_index_dtype(string_dtype_no_object): + # GH 47382 + df1 = pd.DataFrame(columns=list("abc"), data=1.0, index=[0]) + df2 = pd.DataFrame(columns=list("abc"), data=0.0, index=[0]) + df1.columns = df2.columns.astype(string_dtype_no_object) + result = df1 + df2 + expected = pd.DataFrame(columns=list("abc"), data=1.0, index=[0]) + + expected.columns = expected.columns.astype(string_dtype_no_object) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize( + "dtype, fill_val", + [ + (tm.ALL_INT_EA_DTYPES[0], 10), + (tm.FLOAT_NUMPY_DTYPES[0], 4.9), + (tm.FLOAT_EA_DTYPES[0], 4.9), + ], +) +def test_df_mul_array_fill_value(dtype, fill_val, axis, request): + # GH 61581 + df = pd.DataFrame([[np.nan, 1, 2], [3, np.nan, 5]], dtype=dtype) + if axis == 0: + mult = pd.array([np.nan, 1.0], dtype=dtype) + expected = pd.DataFrame( + [[np.nan, fill_val, fill_val * 2], [3.0, fill_val, 5.0]] + ).astype(dtype) + else: + mult = pd.array([np.nan, 1.0, 2.0], dtype=dtype) + expected = pd.DataFrame( + [[np.nan, 1.0, 2.0 * 2.0], [3.0 * fill_val, fill_val, 5.0 * 2.0]] + ).astype(dtype) + result = df.mul(mult, axis=axis, fill_value=fill_val) + tm.assert_frame_equal(result, expected) + + +def test_sum_mixed_empty(any_string_dtype): + # GH 64657 + # for actual string dtype, sum gives "", for object dtype we get 0 + expected = pd.Series( + {"col1": "" if any_string_dtype == "string" else 0, "col2": 0}, dtype=object + ) + empty_df = pd.DataFrame(columns=["col1", "col2"]).astype( + {"col1": any_string_dtype, "col2": int} + ) + result = empty_df.sum() + tm.assert_series_equal(result, expected) + + +def test_frame_with_ea_series_keeps_dtype(any_numeric_ea_dtype): + # GH#61828 the Series used to be dispatched element-wise, so its dtype + # never reached the op and the result came back as numpy + df = pd.DataFrame([[10, 20], [30, 40]]) + ser = pd.Series([1, 2], dtype=any_numeric_ea_dtype) + + # the Series-with-Series result dtype is what the broadcast should give + dtype = (df[0] + ser).dtype + expected = pd.DataFrame([[11, 22], [31, 42]], dtype=dtype) + tm.assert_frame_equal(df + ser, expected) + tm.assert_frame_equal(df.add(ser), expected) + + # comparisons keep it too, so the result is boolean rather than bool. + # the operand overlaps df so the result is not uniform, pinning the broadcast axis + overlapping = pd.Series([10, 40], dtype=any_numeric_ea_dtype) + dtype = (df[0] > overlapping).dtype + expected = pd.DataFrame([[False, False], [True, False]], dtype=dtype) + tm.assert_frame_equal(df > overlapping, expected) + expected = pd.DataFrame([[True, False], [False, True]], dtype=dtype) + tm.assert_frame_equal(df == overlapping, expected) + + +def test_frame_with_categorical_series_raises_like_series(): + # GH#61828 arithmetic against a Categorical used to operate on the + # categories as scalars instead of raising the way every other box does + df = pd.DataFrame([[10, 20], [30, 40]]) + ser = pd.Series(pd.Categorical([10, 40])) + + msg = "Object with dtype category cannot perform the numpy op add" + with pytest.raises(TypeError, match=msg): + df + ser + with pytest.raises(TypeError, match=msg): + df.add(ser) + with pytest.raises(TypeError, match=msg): + df[0] + ser + + msg = "Unordered Categoricals can only compare equality or not" + with pytest.raises(TypeError, match=msg): + df.lt(ser) + with pytest.raises(TypeError, match=msg): + df[0].lt(ser) + + # logical ops go through the same path (_logical_method is _arith_method) + bool_df = pd.DataFrame([[True, False], [False, True]]) + with pytest.raises(TypeError, match="cannot perform the numpy op bitwise_and"): + bool_df & pd.Series(pd.Categorical([True, False])) + + # an ordered Categorical is rejected as well, with its own message + ordered = pd.Series(pd.Categorical([1, 2], ordered=True)) + msg = "Cannot compare a Categorical for op" + with pytest.raises(TypeError, match=msg): + df.lt(ordered) + with pytest.raises(TypeError, match=msg): + df[0].lt(ordered) + + # equality is still defined for an unordered Categorical + expected = pd.DataFrame([[True, False], [False, True]]) + tm.assert_frame_equal(df == ser, expected) + + +def test_frame_with_ea_series_propagates_na(): + # GH#61828 the Series used to be dispatched element-wise, so NA compared as + # an ordinary scalar instead of propagating + df = pd.DataFrame([[10, 20], [30, 40]]) + ser = pd.Series([1, None], dtype="Int64") + + result = df > ser + expected = pd.DataFrame([[True, None], [True, None]], dtype="boolean") + tm.assert_frame_equal(result, expected) + + result = df == ser + expected = pd.DataFrame([[False, None], [False, None]], dtype="boolean") + tm.assert_frame_equal(result, expected) + + +def test_frame_with_period_series(): + # GH#61828 adding a period Series to an integer frame used to raise + df = pd.DataFrame([[10, 20], [30, 40]]) + ser = pd.Series(pd.period_range("2020-01-01", periods=2, freq="D")) + + result = df + ser + expected = pd.DataFrame( + { + 0: pd.PeriodIndex(["2020-01-11", "2020-01-31"], freq="D"), + 1: pd.PeriodIndex(["2020-01-22", "2020-02-11"], freq="D"), + } + ) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_arrow_interface.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_arrow_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..932fffc35dfcfa145baf7577e0d35ae446e7e3b8 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_arrow_interface.py @@ -0,0 +1,123 @@ +import ctypes +import zoneinfo + +import pytest + +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + +pa = pytest.importorskip("pyarrow") + + +@td.skip_if_no("pyarrow") +def test_dataframe_arrow_interface(using_infer_string): + df = pd.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]}) + + capsule = df.__arrow_c_stream__() + assert ( + ctypes.pythonapi.PyCapsule_IsValid( + ctypes.py_object(capsule), b"arrow_array_stream" + ) + == 1 + ) + + table = pa.table(df) + string_type = pa.large_string() if using_infer_string else pa.string() + expected = pa.table({"a": [1, 2, 3], "b": pa.array(["a", "b", "c"], string_type)}) + assert table.equals(expected) + + schema = pa.schema([("a", pa.int8()), ("b", pa.string())]) + table = pa.table(df, schema=schema) + expected = expected.cast(schema) + assert table.equals(expected) + + +def test_dataframe_arrow_interface_tz_aware(): + # GH#68426 pyarrow reading .values should not surface a deprecation warning + dti = pd.date_range("2025-01-01", periods=3, tz="US/Eastern", name="idx") + df = pd.DataFrame({"a": dti}, index=dti) + + # pa.table(df) bypasses __arrow_c_stream__ for pandas objects + with tm.assert_produces_warning(None): + table = pa.RecordBatchReader.from_stream(df).read_all() + expected_type = pa.timestamp("us", tz="US/Eastern") + assert table.schema.field("a").type == expected_type + assert table.schema.field("idx").type == expected_type + + +@td.skip_if_no("pyarrow") +def test_dataframe_to_arrow(using_infer_string): + df = pd.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]}) + + table = pa.RecordBatchReader.from_stream(df).read_all() + string_type = pa.large_string() if using_infer_string else pa.string() + expected = pa.table({"a": [1, 2, 3], "b": pa.array(["a", "b", "c"], string_type)}) + assert table.equals(expected) + + schema = pa.schema([("a", pa.int8()), ("b", pa.string())]) + table = pa.RecordBatchReader.from_stream(df, schema=schema).read_all() + expected = expected.cast(schema) + assert table.equals(expected) + + +class ArrowArrayWrapper: + def __init__(self, batch): + self.array = batch + + def __arrow_c_array__(self, requested_schema=None): + return self.array.__arrow_c_array__(requested_schema) + + +class ArrowStreamWrapper: + def __init__(self, table): + self.stream = table + + def __arrow_c_stream__(self, requested_schema=None): + return self.stream.__arrow_c_stream__(requested_schema) + + +@td.skip_if_no("pyarrow") +def test_dataframe_from_arrow(): + # objects with __arrow_c_stream__ + table = pa.table({"a": [1, 2, 3], "b": ["a", "b", "c"]}) + + result = pd.DataFrame.from_arrow(table) + expected = pd.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]}) + tm.assert_frame_equal(result, expected) + + # not only pyarrow object are supported + result = pd.DataFrame.from_arrow(ArrowStreamWrapper(table)) + tm.assert_frame_equal(result, expected) + + # objects with __arrow_c_array__ + batch = pa.record_batch([[1, 2, 3], ["a", "b", "c"]], names=["a", "b"]) + + result = pd.DataFrame.from_arrow(table) + tm.assert_frame_equal(result, expected) + + result = pd.DataFrame.from_arrow(ArrowArrayWrapper(batch)) + tm.assert_frame_equal(result, expected) + + # only accept actual Arrow objects + with pytest.raises(TypeError, match="Expected an Arrow-compatible tabular object"): + pd.DataFrame.from_arrow({"a": [1, 2, 3], "b": ["a", "b", "c"]}) + + +@td.skip_if_no("pyarrow") +@pytest.mark.filterwarnings( + "ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning" +) +def test_dataframe_from_arrow_custom_conversion(): + # ensuring that we use our custom conversion and not the default pyarrow to_pandas + table = pa.table( + {"a": pa.array([1, 2, 3], type=pa.timestamp("ns", tz="America/New_York"))} + ) + result = pd.DataFrame.from_arrow(table) + assert isinstance(result["a"].dtype.tz, zoneinfo.ZoneInfo) + + table = pa.table({"a": pa.array(["a", "b", "c"])}) + with pd.option_context("future.infer_string", False): + result = pd.DataFrame.from_arrow(table) + assert result["a"].dtype == "object" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_block_internals.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_block_internals.py new file mode 100644 index 0000000000000000000000000000000000000000..f524fe3a7f3b54d90c88c90ac4dcae4712a27801 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_block_internals.py @@ -0,0 +1,450 @@ +from datetime import ( + datetime, + timedelta, +) +from io import StringIO +import itertools +from textwrap import dedent + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm +from pandas.core.internals.blocks import NumpyBlock + +# Segregated collection of methods that require the BlockManager internal data +# structure + + +class TestDataFrameBlockInternals: + def test_setitem_invalidates_datetime_index_freq(self): + # GH#24096 altering a datetime64tz column inplace doesn't propagate + # freq onto the original DatetimeIndex + + dti = pd.date_range("20130101", periods=3, tz="US/Eastern") + ts = dti[1] + + df = pd.DataFrame({"B": dti}) + df.iloc[1, 0] = pd.NaT + + # check that the DatetimeIndex was not altered in place + assert dti.freq == "D" + assert dti[1] == ts + + def test_cast_internals(self, float_frame): + msg = "Passing a BlockManager to DataFrame" + with tm.assert_produces_warning( + Pandas4Warning, match=msg, check_stacklevel=False + ): + casted = pd.DataFrame(float_frame._mgr, dtype=int) + expected = pd.DataFrame(float_frame._series, dtype=int) + tm.assert_frame_equal(casted, expected) + + with tm.assert_produces_warning( + Pandas4Warning, match=msg, check_stacklevel=False + ): + casted = pd.DataFrame(float_frame._mgr, dtype=np.int32) + expected = pd.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): + with pytest.raises(ValueError, match="read-only"): + float_frame.values[5] = 5 + assert (float_frame.values[5] != 5).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 = pd.DataFrame({"A": [2**63 - 1]}) + result = df["A"] + expected = pd.Series(np.asarray([2**63 - 1], np.int64), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [2**63]}) + result = df["A"] + expected = pd.Series(np.asarray([2**63], np.uint64), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [datetime(2005, 1, 1), True]}) + result = df["A"] + expected = pd.Series( + np.asarray([datetime(2005, 1, 1), True], np.object_), name="A" + ) + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [None, 1]}) + result = df["A"] + expected = pd.Series(np.asarray([np.nan, 1], np.float64), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [1.0, 2]}) + result = df["A"] + expected = pd.Series(np.asarray([1.0, 2], np.float64), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [1.0 + 2.0j, 3]}) + result = df["A"] + expected = pd.Series(np.asarray([1.0 + 2.0j, 3], np.complex128), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [1.0 + 2.0j, 3.0]}) + result = df["A"] + expected = pd.Series(np.asarray([1.0 + 2.0j, 3.0], np.complex128), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [1.0 + 2.0j, True]}) + result = df["A"] + expected = pd.Series(np.asarray([1.0 + 2.0j, True], np.object_), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [1.0, None]}) + result = df["A"] + expected = pd.Series(np.asarray([1.0, np.nan], np.float64), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [1.0 + 2.0j, None]}) + result = df["A"] + expected = pd.Series(np.asarray([1.0 + 2.0j, np.nan], np.complex128), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [2.0, 1, True, None]}) + result = df["A"] + expected = pd.Series(np.asarray([2.0, 1, True, None], np.object_), name="A") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [2.0, 1, datetime(2006, 1, 1), None]}) + result = df["A"] + expected = pd.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, using_infer_string): + # mixed-type frames + float_string_frame["datetime"] = datetime(2011, 1, 1) + 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 = pd.Series( + [np.dtype("float64")] * 4 + + [ + np.dtype("object") + if not using_infer_string + else pd.StringDtype(na_value=np.nan), + 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 = pd.DataFrame({"A": arr}) + expected = pd.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 = pd.DataFrame( + { + "dt1": pd.Timestamp("20130101").as_unit("s"), + "dt2": pd.date_range("20130101", periods=3).astype("M8[s]"), + "dt3": pd.date_range("20130101 00:00:01", periods=3, freq="s").astype( + "M8[s]" + ), + }, + index=range(3), + ) + assert expected.dtypes["dt1"] == "M8[s]" + assert expected.dtypes["dt2"] == "M8[s]" + assert expected.dtypes["dt3"] == "M8[s]" + + dt1 = np.datetime64("2013-01-01") + dt2 = np.array( + ["2013-01-01", "2013-01-02", "2013-01-03"], dtype="datetime64[D]" + ) + dt3 = np.array( + [ + "2013-01-01 00:00:01", + "2013-01-01 00:00:02", + "2013-01-01 00:00:03", + ], + dtype="datetime64[s]", + ) + df = pd.DataFrame({"dt1": dt1, "dt2": dt2, "dt3": dt3}) + + 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 pd.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$" + with pytest.raises(ValueError, match=msg): + f("M8[ns]") + + def test_pickle_float_string_frame(self, float_string_frame, temp_file): + unpickled = tm.round_trip_pickle(float_string_frame, temp_file) + tm.assert_frame_equal(float_string_frame, unpickled) + + # buglet + float_string_frame._mgr.ndim + + def test_pickle_empty(self, temp_file): + empty_frame = pd.DataFrame() + unpickled = tm.round_trip_pickle(empty_frame, temp_file) + repr(unpickled) + + def test_pickle_empty_tz_frame(self, timezone_frame, temp_file): + unpickled = tm.round_trip_pickle(timezone_frame, temp_file) + tm.assert_frame_equal(timezone_frame, unpickled) + + def test_consolidate_datetime64(self): + # numpy vstack bug + + df = pd.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): + # this is chained, but ok + Y = pd.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") + with tm.raises_chained_assignment_error(): + Y["g"]["c"] = np.nan + repr(Y) + Y.sum() + Y["g"].sum() + assert not pd.isna(Y["g"]["c"]) + + def test_strange_column_corruption_issue(self, performance_warning): + # TODO(wesm): Unclear how exactly this is related to internal matters + df = pd.DataFrame(index=[0, 1]) + df[0] = np.nan + wasCol = {} + + msg = "DataFrame is highly fragmented" + with tm.assert_produces_warning( + performance_warning, raise_on_extra_warnings=False, match=msg + ): + 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 + df.loc[dt, col] = 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 = pd.Series([1, 2, 3]).array + result = pd.DataFrame({"A": arr}) + expected = pd.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 = pd.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 = pd.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(): + # https://github.com/pandas-dev/pandas/issues/33457 + df = pd.DataFrame({"a": pd.Series([1, 2, None], dtype="category")}) + + # inplace update of a single column + with tm.raises_chained_assignment_error(): + df["a"].fillna(1, inplace=True) + + # check we haven't put a Series into any block.values + assert isinstance(df._mgr.blocks[0].values, pd.Categorical) + + +def get_longley_data(): + # From statsmodels.datasets.longley + # This specific dataset seems to trigger races in Pandas 3.0.0 more readily + # than data frames used elsewhere in the tests + longley_csv = StringIO( + dedent( + """"Obs","GNPDEFL","GNP","UNEMP","ARMED","POP","YEAR" + 1,83,234289,2356,1590,107608,1947 + 2,88.5,259426,2325,1456,108632,1948 + 3,88.2,258054,3682,1616,109773,1949 + 4,89.5,284599,3351,1650,110929,1950 + 5,96.2,328975,2099,3099,112075,1951 + 6,98.1,346999,1932,3594,113270,1952 + 7,99,365385,1870,3547,115094,1953 + 8,100,363112,3578,3350,116219,1954 + 9,101.2,397469,2904,3048,117388,1955 + 10,104.6,419180,2822,2857,118734,1956 + 11,108.4,442769,2936,2798,120445,1957 + 12,110.8,444546,4681,2637,121950,1958 + 13,112.6,482704,3813,2552,123366,1959 + 14,114.2,502601,3931,2514,125368,1960 + 15,115.7,518173,4806,2572,127852,1961 + 16,116.9,554894,4007,2827,130081,1962 + """ + ) + ) + + return pd.read_csv(longley_csv).iloc[:, [1, 2, 3, 4, 5, 6]].astype(float) + + +# See gh-63685, comparisons and copying led to races in statsmodels tests +# +# This test spawns a thread pool, so it shouldn't run under xdist. +# It generates warnings, so it needs warnings to be thread-safe as well +@td.skip_if_thread_unsafe_warnings +@pytest.mark.single_cpu +def test_multithreaded_reading(): + def numpy_assert(data, b): + b.wait() + tm.assert_almost_equal((data + 1) - 1, data.copy()) + + tm.run_multithreaded( + numpy_assert, max_workers=8, arguments=(get_longley_data(),), pass_barrier=True + ) + + def safe_is_const(s): + try: + return np.ptp(s) == 0.0 and np.any(s != 0.0) + except Exception: + return False + + def concat(data, b): + b.wait() + x = data.copy() + nobs = len(x) + trendarr = np.fliplr(np.vander(np.arange(1, nobs + 1, dtype=np.float64), 1)) + x.apply(safe_is_const, 0) + trendarr = pd.DataFrame(trendarr, index=x.index, columns=["const"]) + x = [trendarr, x] + x = pd.concat(x[::1], axis=1) + tm.assert_frame_equal(x, x) + + tm.run_multithreaded( + concat, max_workers=8, arguments=(get_longley_data(),), pass_barrier=True + ) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_constructors.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..01fef66d846ffe85ae81501d89819bd6cd6b797d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_constructors.py @@ -0,0 +1,3583 @@ +import array +from collections import ( + OrderedDict, + UserList, + abc, + defaultdict, + namedtuple, +) +from collections.abc import Iterator +from dataclasses import ( + dataclass, + make_dataclass, +) +from datetime import ( + date, + datetime, + timedelta, +) +import functools +import re +import zoneinfo + +import numpy as np +from numpy import ma +from numpy.ma import mrecords +import pytest + +from pandas._libs import lib +from pandas.errors import ( + IntCastingNaNError, + Pandas4Warning, +) +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 +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 = pd.DataFrame(arr, dtype=str) + expected = pd.DataFrame(arr.astype(str), dtype="str") + tm.assert_frame_equal(df, expected) + + def test_constructor_from_2d_datetimearray(self): + dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific") + dta = dti._data.reshape(3, 2) + + df = pd.DataFrame(dta) + expected = pd.DataFrame({0: dta[:, 0], 1: dta[:, 1]}) + tm.assert_frame_equal(df, expected) + # 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 = pd.Timestamp("2019-11-03 01:00:00-0700").tz_convert("America/Los_Angeles") + dt = dt.as_unit("ns") + + df = pd.DataFrame({"dt": dt}, index=[0]) + expected = pd.DataFrame({"dt": [dt]}) + tm.assert_frame_equal(df, expected, check_index_type=False) + + # Non-homogeneous + df = pd.DataFrame({"dt": dt, "value": [1]}) + expected = pd.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): + pd.DataFrame(arr, dtype="i8") + + # check this matches Series behavior + with pytest.raises(IntCastingNaNError, match=msg): + pd.Series(arr[0], dtype="i8", name=0) + + def test_construct_from_list_of_datetimes(self): + df = pd.DataFrame([datetime(2011, 1, 1), datetime(2011, 1, 2)]) + assert df[0].dtype == np.dtype("M8[us]") + + def test_constructor_from_tzaware_datetimeindex(self): + # don't cast a DatetimeIndex WITH a tz, leave as object + # GH#6032 + naive = pd.DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B") + idx = naive.tz_localize("US/Pacific") + + expected = pd.Series(np.array(idx.tolist(), dtype="object"), name="B") + assert expected.dtype == idx.dtype + + # convert index to series + result = pd.Series(idx) + tm.assert_series_equal(result, expected) + + def test_columns_with_leading_underscore_work_with_to_dict(self): + col_underscore = "_b" + df = pd.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 = pd.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 pd.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 = pd.Timestamp + else: + dtype = "m8[ns]" + scalar_type = pd.Timedelta + + arr = np.arange(6, dtype="i8").view(dtype).reshape(3, 2) + if frame_or_series is pd.Series: + arr = arr[:, 0] + + obj = frame_or_series(arr, dtype=object) + assert obj._mgr.blocks[0].values.dtype == object + assert isinstance(obj._mgr.blocks[0].values.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.blocks[0].values.dtype == object + assert isinstance(obj._mgr.blocks[0].values.ravel()[0], scalar_type) + + obj = frame_or_series(frame_or_series(arr), dtype=NumpyEADtype(object)) + assert obj._mgr.blocks[0].values.dtype == object + assert isinstance(obj._mgr.blocks[0].values.ravel()[0], scalar_type) + + if frame_or_series is pd.DataFrame: + # other paths through internals.construction + sers = [pd.Series(x) for x in arr] + obj = frame_or_series(sers, dtype=object) + assert obj._mgr.blocks[0].values.dtype == object + assert isinstance(obj._mgr.blocks[0].values.ravel()[0], scalar_type) + + def test_series_with_name_not_matching_column(self): + # GH#9232 + x = pd.Series(range(5), name=1) + y = pd.Series(range(5), name=0) + + result = pd.DataFrame(x, columns=[0]) + expected = pd.DataFrame([], columns=[0]) + tm.assert_frame_equal(result, expected) + + result = pd.DataFrame(y, columns=[1]) + expected = pd.DataFrame([], columns=[1]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "constructor", + [ + lambda: pd.DataFrame(), + lambda: pd.DataFrame(None), + lambda: pd.DataFrame(()), + lambda: pd.DataFrame([]), + lambda: pd.DataFrame(_ for _ in []), + lambda: pd.DataFrame(range(0)), + lambda: pd.DataFrame(data=None), + lambda: pd.DataFrame(data=()), + lambda: pd.DataFrame(data=[]), + lambda: pd.DataFrame(data=(_ for _ in [])), + lambda: pd.DataFrame(data=range(0)), + ], + ) + def test_empty_constructor(self, constructor): + expected = pd.DataFrame() + result = constructor() + assert len(result.index) == 0 + assert len(result.columns) == 0 + tm.assert_frame_equal(result, expected) + + def test_empty_constructor_object_index(self): + expected = pd.DataFrame(index=pd.RangeIndex(0), columns=pd.RangeIndex(0)) + result = pd.DataFrame({}) + 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", + [ + ([[]], pd.RangeIndex(1), pd.RangeIndex(0)), + ([[], []], pd.RangeIndex(2), pd.RangeIndex(0)), + ([(_ for _ in [])], pd.RangeIndex(1), pd.RangeIndex(0)), + ], + ) + def test_emptylike_constructor(self, emptylike, expected_index, expected_columns): + expected = pd.DataFrame(index=expected_index, columns=expected_columns) + result = pd.DataFrame(emptylike) + tm.assert_frame_equal(result, expected) + + def test_constructor_mixed(self, float_string_frame, using_infer_string): + dtype = "str" if using_infer_string else np.object_ + assert float_string_frame["foo"].dtype == dtype + + 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): + pd.DataFrame({"a": ["a", "b", "c"]}, dtype=np.float64) + + # GH 3010, constructing with odd arrays + df = pd.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 = pd.DataFrame({"col1": [1.0], "col2": [2.0], "col3": [3.0]}) + + new_df = pd.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): + df = pd.DataFrame([[1, 2]]) + should_be_view = pd.DataFrame(df, dtype=df[0].dtype) + should_be_view.iloc[0, 0] = 99 + assert df.values[0, 0] == 1 + + def test_constructor_dtype_nocast_view_2d_array(self): + df = pd.DataFrame([[1, 2], [3, 4]], dtype="int64") + df2 = pd.DataFrame(df.values, dtype=df[0].dtype) + assert df2._mgr.blocks[0].values.flags.c_contiguous + + def test_1d_object_array_does_not_copy(self, using_infer_string): + # https://github.com/pandas-dev/pandas/issues/39272 + arr = np.array(["a", "b"], dtype="object") + df = pd.DataFrame(arr, copy=False) + if using_infer_string: + if df[0].dtype.storage == "pyarrow": + # object dtype strings are converted to arrow memory, + # no numpy arrays to compare + pass + else: + assert np.shares_memory(df[0].to_numpy(), arr) + else: + assert np.shares_memory(df.values, arr) + + df = pd.DataFrame(arr, dtype=object, copy=False) + assert np.shares_memory(df.values, arr) + + def test_2d_object_array_does_not_copy(self, using_infer_string): + # https://github.com/pandas-dev/pandas/issues/39272 + arr = np.array([["a", "b"], ["c", "d"]], dtype="object") + df = pd.DataFrame(arr, copy=False) + if using_infer_string: + if df[0].dtype.storage == "pyarrow": + # object dtype strings are converted to arrow memory, + # no numpy arrays to compare + pass + else: + assert np.shares_memory(df[0].to_numpy(), arr) + else: + assert np.shares_memory(df.values, arr) + + df = pd.DataFrame(arr, dtype=object, copy=False) + assert np.shares_memory(df.values, arr) + + def test_constructor_dtype_list_data(self): + df = pd.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 = pd.DataFrame() + b = np.empty((0, 0)) + with pytest.raises(ValueError, match=r"shape=\(1, 0, 0\)"): + pd.DataFrame([a]) + + with pytest.raises(ValueError, match=r"shape=\(1, 0, 0\)"): + pd.DataFrame([b]) + + a = pd.DataFrame({"A": [1, 2]}) + with pytest.raises(ValueError, match=r"shape=\(2, 2, 1\)"): + pd.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, strict=True): + assert a.dtype == d + ad.update(dict(zip(dtypes, arrays, strict=True))) + df = pd.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 = pd.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 = pd.DataFrame({"A": ["x", None]}, dtype=string_dtype) + result = df.isna() + expected = pd.DataFrame({"A": [False, True]}) + tm.assert_frame_equal(result, expected) + assert df.iloc[1, 0] is None + + df = pd.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 = pd.DataFrame(rec) + tm.assert_index_equal(df.columns, pd.Index(rec.dtype.names)) + + df2 = pd.DataFrame(rec, index=index) + tm.assert_index_equal(df2.columns, pd.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 = pd.DataFrame(rec, index=rng, columns=["C", "B"]) + expected = pd.DataFrame(rec, index=rng).reindex(columns=["C", "B"]) + tm.assert_frame_equal(df3, expected) + + def test_constructor_bool(self): + df = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame(OrderedDict(zip(expected, [[0]] * nitems, strict=True))) + assert expected == list(df.columns) + + def test_constructor_dict(self): + datetime_series = pd.Series( + np.arange(30, dtype=np.float64), + index=pd.date_range("2020-01-01", periods=30), + ) + # test expects index shifted by 5 + datetime_series_short = datetime_series[5:] + + frame = pd.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 = pd.Series( + np.concatenate([[np.nan] * 5, datetime_series_short.values]), + index=datetime_series.index, + name="col2", + ) + tm.assert_series_equal(exp, frame["col2"]) + + frame = pd.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 pd.isna(frame["col3"]).all() + + # Corner cases + assert len(pd.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): + pd.DataFrame({"A": {"a": "a", "b": "b"}, "B": ["a", "b", "c"]}) + + def test_constructor_dict_length1(self): + # Length-one dict micro-optimization + frame = pd.DataFrame({"A": {"1": 1, "2": 2}}) + tm.assert_index_equal(frame.index, pd.Index(["1", "2"])) + + def test_constructor_dict_with_index(self): + # empty dict plus index + idx = pd.Index([0, 1, 2]) + frame = pd.DataFrame({}, index=idx) + assert frame.index is idx + + def test_constructor_dict_with_index_and_columns(self): + # empty dict with index and columns + idx = pd.Index([0, 1, 2]) + frame = pd.DataFrame({}, index=idx, columns=idx) + tm.assert_index_equal(frame.index, idx) + tm.assert_index_equal(frame.columns, idx) + # GH#42934 the two axes must not be the same object, otherwise mutating + # metadata on one (e.g. names) would silently affect the other + assert frame.index is not frame.columns + assert len(frame._series) == 3 + + def test_constructor_same_index_and_columns_no_alias(self): + # GH#42934 passing one Index as both index and columns should not + # alias the two axes, so mutating names on one leaves the other intact + idx = pd.Index(["a", "b"]) + frame = pd.DataFrame([[1, 2], [3, 4]], index=idx, columns=idx) + assert frame.index is not frame.columns + + frame.index.names = ["zzz"] + assert frame.columns.names == [None] + assert idx.names == [None] + + def test_constructor_dict_of_empty_lists(self): + # with dict of empty list and Series + frame = pd.DataFrame({"A": [], "B": []}, columns=["A", "B"]) + tm.assert_index_equal(frame.index, pd.RangeIndex(0), exact=True) + + def test_constructor_dict_with_none(self): + # GH 14381 + # Dict with None value + frame_none = pd.DataFrame({"a": None}, index=[0]) + frame_none_list = pd.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): + pd.DataFrame({"a": 0.7}) + + with pytest.raises(ValueError, match=msg): + pd.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 = pd.DataFrame({"a": scalar}, columns=["b"]) + expected = pd.DataFrame(columns=["b"]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("value", [4, 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]: pd.Series(values[c], index=idx) for c in range(3)} + result = pd.DataFrame(data).sort_values(1).sort_values("a", axis=1) + expected = pd.DataFrame( + np.arange(6, dtype="int64").reshape(2, 3), index=idx, columns=cols + ) + tm.assert_frame_equal(result, expected) + + result = pd.DataFrame(data, index=idx).sort_values("a", axis=1) + tm.assert_frame_equal(result, expected) + + result = pd.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 = pd.Index([(11, 21), (value, 22), (13, value)]) + idx = pd.Index([("a", value), (value, 2)]) + values = [[0, 3], [1, 4], [2, 5]] + data = {cols[c]: pd.Series(values[c], index=idx) for c in range(3)} + result = ( + pd.DataFrame(data).sort_values((11, 21)).sort_values(("a", value), axis=1) + ) + expected = pd.DataFrame( + np.arange(6, dtype="int64").reshape(2, 3), index=idx, columns=cols + ) + tm.assert_frame_equal(result, expected) + + result = pd.DataFrame(data, index=idx).sort_values(("a", value), axis=1) + tm.assert_frame_equal(result, expected) + + result = pd.DataFrame(data, index=idx, columns=cols) + tm.assert_frame_equal(result, expected) + + def test_constructor_dict_order_insertion(self): + datetime_series = pd.Series( + np.arange(10, dtype=np.float64), + index=pd.date_range("2020-01-01", periods=10), + ) + datetime_series_short = datetime_series[:5] + + # GH19018 + # initialization ordering: by insertion order if python>= 3.6 + d = {"b": datetime_series_short, "a": datetime_series} + frame = pd.DataFrame(data=d) + expected = pd.DataFrame(data=d, columns=list("ba")) + tm.assert_frame_equal(frame, expected) + + def test_constructor_dict_nan_key_and_columns(self): + # GH 16894 + result = pd.DataFrame({np.nan: [1, 2], 2: [2, 3]}, columns=[np.nan, 2]) + expected = pd.DataFrame([[1, 2], [2, 3]], columns=[np.nan, 2]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("missing_value", [None, np.nan, pd.NA]) + def test_constructor_list_of_dict_with_str_na_key( + self, missing_value, using_infer_string + ): + # https://github.com/pandas-dev/pandas/issues/63889 + # preserve values when None key is converted to NaN column name + dict_data = [ + {"colA": 1, missing_value: 2}, + {"colA": 3, missing_value: 4}, + ] + result = pd.DataFrame(dict_data) + expected = pd.DataFrame( + [[1, 2], [3, 4]], + columns=["colA", np.nan if using_infer_string else missing_value], + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("missing_value", [None, np.nan, pd.NA]) + def test_constructor_dict_of_dict_with_str_na_key( + self, missing_value, using_infer_string + ): + # https://github.com/pandas-dev/pandas/issues/63889 + dict_data = {"col": {"row1": 1, missing_value: 2, "row3": 3}} + result = pd.DataFrame(dict_data) + expected = pd.DataFrame( + {"col": [1, 2, 3]}, + index=pd.Index( + ["row1", np.nan if using_infer_string else missing_value, "row3"] + ), + ) + 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 = pd.MultiIndex.from_tuples(tuples) + df = pd.DataFrame(index=mi, columns=mi) + assert pd.isna(df).values.ravel().all() + + tuples = [(3, 3), (2, 3), (3, 3)] + mi = pd.MultiIndex.from_tuples(tuples) + df = pd.DataFrame(index=mi, columns=mi) + assert pd.isna(df).values.ravel().all() + + def test_constructor_2d_index(self): + # GH 25416 + # handling of 2d index in construction + df = pd.DataFrame([[1]], columns=[[1]], index=[1, 2]) + expected = pd.DataFrame( + [1, 1], + index=pd.Index([1, 2], dtype="int64"), + columns=pd.MultiIndex(levels=[[1]], codes=[[0]]), + ) + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame([[1]], columns=[[1]], index=[[1, 2]]) + expected = pd.DataFrame( + [1, 1], + index=pd.MultiIndex(levels=[[1, 2]], codes=[[0, 1]]), + columns=pd.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): + pd.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): + pd.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): + pd.DataFrame( + np.arange(12).reshape((4, 3)), + columns=["foo", "bar", "baz"], + index=pd.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): + pd.DataFrame(index=[0], columns=range(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): + pd.DataFrame(index=[0], columns=range(4), data=arr) + + # higher dim raise exception + with pytest.raises(ValueError, match="Must pass 2-d input"): + pd.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): + pd.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): + pd.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): + pd.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): + pd.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 = pd.DataFrame(data) + refdf = pd.DataFrame({col: dict(val.items()) for col, val in data.items()}) + tm.assert_frame_equal(refdf, df) + + data = dict_subclass(data.items()) + df = pd.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 = pd.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 = pd.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, using_infer_string): + # cast float tests + test_data = {"A": {"1": 1, "2": 2}, "B": {"1": "1", "2": "2", "3": "3"}} + frame = pd.DataFrame(test_data, dtype=float) + assert len(frame) == 3 + assert frame["B"].dtype == np.float64 + assert frame["A"].dtype == np.float64 + + frame = pd.DataFrame(test_data) + assert len(frame) == 3 + assert frame["B"].dtype == np.object_ if not using_infer_string else "str" + assert frame["A"].dtype == np.float64 + + def test_constructor_dict_cast2(self): + # can't cast to float + test_data = { + "A": dict(zip(range(20), [f"word_{i}" for i in range(20)], strict=True)), + "B": dict( + zip( + range(15), np.random.default_rng(2).standard_normal(15), strict=True + ) + ), + } + with pytest.raises(ValueError, match="could not convert string"): + pd.DataFrame(test_data, dtype=float) + + def test_constructor_dict_dont_upcast(self): + d = {"Col1": {"Row1": "A String", "Row2": np.nan}} + df = pd.DataFrame(d) + assert isinstance(df["Col1"]["Row2"], float) + + def test_constructor_dict_dont_upcast2(self): + dm = pd.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 = pd.DataFrame(data) + expected = pd.DataFrame({k: list(v) for k, v in data.items()}) + tm.assert_frame_equal(result, expected) + + def test_constructor_dict_of_ranges(self): + # GH 26356 + data = {"a": range(3), "b": range(3, 6)} + + result = pd.DataFrame(data) + expected = pd.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 = pd.DataFrame(data) + expected = pd.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 = pd.DataFrame(data) + expected = pd.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 = pd.DataFrame(d) + expected = pd.DataFrame( + [x[1] for x in _d], index=pd.MultiIndex.from_tuples([x[0] for x in _d]) + ).T + expected.index = pd.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 = pd.DataFrame( + [x[1] for x in _d], index=pd.Index([x[0] for x in _d], tupleize_cols=False) + ).T + expected.index = pd.Index(expected.index, tupleize_cols=False) + df = pd.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(pd.Timestamp) + + expected = pd.DataFrame( + [ + [0, None, None, None], + [None, 2, None, None], + [None, None, 4, None], + [None, None, None, 6], + ], + index=[pd.Timestamp(dt) for dt in dates_as_str], + ) + + result_datetime64 = pd.DataFrame(data_datetime64) + assert result_datetime64.index.unit == "s" + result_datetime64.index = result_datetime64.index.as_unit("us") + result_datetime = pd.DataFrame(data_datetime) + assert result_datetime.index.unit == "us" + result_Timestamp = pd.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,exp_dtype", + [ + (lambda x: np.timedelta64(x, "D"), "m8[s]"), + (lambda x: timedelta(days=x), "m8[us]"), + (lambda x: pd.Timedelta(x, "D"), "m8[us]"), + (lambda x: pd.Timedelta(x, "D").as_unit("ms"), "m8[ms]"), + ], + ) + def test_constructor_dict_timedelta64_index(self, klass, exp_dtype): + # GH 10160 + td_as_int = [1, 2, 3, 4] + + data = {i: {klass(s): 2 * i} for i, s in enumerate(td_as_int)} + + expected = pd.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=[pd.Timedelta(td, "D") for td in td_as_int], + ) + expected.index = expected.index.astype(exp_dtype) + + result = pd.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 = pd.DataFrame({"a": a, "b": b}) + assert df["a"].dtype == a.dtype + assert df["b"].dtype == b.dtype + + # list of periods + df = pd.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 = pd.DataFrame({"a": ea_scalar}, index=[0]) + assert df["a"].dtype == ea_dtype + + expected = pd.DataFrame(index=[0], columns=["a"], data=ea_scalar) + + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "data,dtype", + [ + (pd.Period("2020-01"), PeriodDtype("M")), + (pd.Interval(left=0, right=5), IntervalDtype("int64", "right")), + ( + pd.Timestamp("2011-01-01", tz="US/Eastern").as_unit("s"), + DatetimeTZDtype(unit="s", tz="US/Eastern"), + ), + ], + ) + def test_constructor_extension_scalar_data(self, data, dtype): + # GH 34832 + df = pd.DataFrame(index=range(2), columns=["a", "b"], data=data) + + assert df["a"].dtype == dtype + assert df["b"].dtype == dtype + + arr = pd.array([data] * 2, dtype=dtype) + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame(mat, columns=["A", "B", "C"], index=[1, 2]) + + assert len(frame.index) == 2 + assert len(frame.columns) == 3 + + # 1-D input + frame = pd.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): + pd.DataFrame(mat, columns=["A", "B", "C"], index=[1, 2], dtype=np.int64) + return + else: + frame = pd.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): + pd.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): + pd.DataFrame(mat, columns=["A", "B"], index=[1, 2]) + + # higher dim raise exception + with pytest.raises(ValueError, match="Must pass 2-d input"): + pd.DataFrame(empty((3, 3, 3)), columns=["A", "B", "C"], index=[1]) + + # automatic labeling + frame = pd.DataFrame(mat) + tm.assert_index_equal(frame.index, pd.Index(range(2)), exact=True) + tm.assert_index_equal(frame.columns, pd.Index(range(3)), exact=True) + + frame = pd.DataFrame(mat, index=[1, 2]) + tm.assert_index_equal(frame.columns, pd.Index(range(3)), exact=True) + + frame = pd.DataFrame(mat, columns=["A", "B", "C"]) + tm.assert_index_equal(frame.index, pd.Index(range(2)), exact=True) + + # 0-length axis + frame = pd.DataFrame(empty((0, 3))) + assert len(frame.index) == 0 + + frame = pd.DataFrame(empty((3, 0))) + assert len(frame.columns) == 0 + + def test_constructor_ndarray(self): + self._check_basic_constructor(np.ones) + + frame = pd.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 = pd.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 = pd.DataFrame(mat, columns=["A", "B", "C"], index=[1, 2]) + assert np.all(~np.asarray(frame == frame)) + + def test_constructor_maskedarray_nonfloat(self): + # masked int promoted to float + mat = ma.masked_all((2, 3), dtype=int) + # 2-D input + frame = pd.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 = pd.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 = pd.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 = pd.DataFrame(mat, columns=["A", "B", "C"], index=[1, 2]) + + assert len(frame.index) == 2 + assert len(frame.columns) == 3 + assert pd.isna(frame).values.all() + + # cast type + msg = r"datetime64\[ns\] values and dtype=int64 is not supported" + with pytest.raises(TypeError, match=msg): + pd.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 = pd.DataFrame(mat2, columns=["A", "B", "C"], index=[1, 2]) + assert 1 == frame["A"].astype("i8")[1] + assert 2 == frame["C"].astype("i8")[2] + + # masked bool promoted to object + mat = ma.masked_all((2, 3), dtype=bool) + # 2-D input + frame = pd.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 = pd.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 = pd.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 = pd.DataFrame(mat_hard, columns=["A", "B"], index=[1, 2]) + expected = pd.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 = pd.DataFrame(mat_hard, columns=["A", "B"], index=[1, 2]) + expected = pd.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 = pd.DataFrame(lst_containers, columns=columns) + expected = pd.DataFrame([[1, "a"], [2, "b"]], columns=columns) + tm.assert_frame_equal(result, expected) + + def test_constructor_stdlib_array(self): + # GH 4297 + # support Array + result = pd.DataFrame({"A": array.array("i", range(10))}) + expected = pd.DataFrame({"A": list(range(10))}) + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame([list(range(10)), list(range(10))]) + result = pd.DataFrame( + [array.array("i", range(10)), array.array("i", range(10))] + ) + tm.assert_frame_equal(result, expected) + + def test_constructor_range(self): + # GH26342 + result = pd.DataFrame(range(10)) + expected = pd.DataFrame(list(range(10))) + tm.assert_frame_equal(result, expected) + + def test_constructor_list_of_ranges(self): + result = pd.DataFrame([range(10), range(10)]) + expected = pd.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 = pd.DataFrame([[1, 2, 3]] * 10) + result = pd.DataFrame(Iter()) + tm.assert_frame_equal(result, expected) + + def test_constructor_iterator(self): + result = pd.DataFrame(iter(range(10))) + expected = pd.DataFrame(list(range(10))) + tm.assert_frame_equal(result, expected) + + def test_constructor_list_of_iterators(self): + result = pd.DataFrame([iter(range(10)), iter(range(10))]) + expected = pd.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 = pd.DataFrame([list(range(10)), list(range(10))]) + result = pd.DataFrame([gen1, gen2]) + tm.assert_frame_equal(result, expected) + + gen = ([i, "a"] for i in range(10)) + result = pd.DataFrame(gen) + expected = pd.DataFrame({0: range(10), 1: "a"}) + tm.assert_frame_equal(result, expected) + + def test_constructor_list_of_dicts(self): + result = pd.DataFrame([{}]) + expected = pd.DataFrame(index=pd.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 = pd.DataFrame(data) + data = {"col2": [1, 2], "col1": [2, 5]} + expected = pd.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 = pd.DataFrame([[2, 1]], columns=["b", "a"]) + + data = dict_type() + data["b"] = [2] + data["a"] = [1] + + result = pd.DataFrame(data) + tm.assert_frame_equal(result, expected) + + data = dict_type() + data["b"] = 2 + data["a"] = 1 + + result = pd.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 = pd.DataFrame([[2, 1], [2, 1]], columns=["b", "a"]) + result = pd.DataFrame([row_one, row_two]) + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame([[2, 1], [2, 1], [2, 1]], columns=["b", "a"]) + result = pd.DataFrame([row_one, row_two, row_three]) + tm.assert_frame_equal(result, expected) + + def test_constructor_list_of_series_aligned_index(self): + series = [pd.Series(i, index=["b", "a", "c"], name=str(i)) for i in range(3)] + result = pd.DataFrame(series) + expected = pd.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 = pd.DataFrame(data_custom) + result = pd.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"): + pd.DataFrame(data) + + def test_constructor_scalar(self): + idx = pd.Index(range(3)) + df = pd.DataFrame({"a": 0}, index=idx) + expected = pd.DataFrame({"a": [0, 0, 0]}, index=idx) + tm.assert_frame_equal(df, expected) + + def test_constructor_Series_copy_bug(self, float_frame): + df = pd.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"] = pd.Series([4, 3, 2, 1], index=["bar", "qux", "baz", "foo"]) + + result = pd.DataFrame(data) + assert result.index.is_monotonic_increasing + + # ordering ambiguous, raise exception + with pytest.raises(ValueError, match="ambiguous ordering"): + pd.DataFrame({"A": ["a", "b"], "B": {"a": "a", "b": "b"}}) + + # this is OK though + result = pd.DataFrame( + {"A": ["a", "b"], "B": pd.Series(["a", "b"], index=["a", "b"])} + ) + expected = pd.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 = pd.DataFrame(data) + expected = pd.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 = pd.DataFrame(tuples) + expected = pd.DataFrame(lists) + tm.assert_frame_equal(result, expected) + + def test_constructor_list_of_tuples(self): + result = pd.DataFrame({"A": [(1, 2), (3, 4)]}) + expected = pd.DataFrame({"A": pd.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 = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + result = pd.DataFrame(tuples) + tm.assert_frame_equal(result, expected) + + # with columns + expected = pd.DataFrame({"y": [1, 2], "z": [3, 4]}) + result = pd.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 = pd.DataFrame({"x": [0, 1], "y": [3, 3]}) + result = pd.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 = pd.DataFrame( + {"x": [0, np.nan], "y": [3, 3], "x0": [np.nan, 1], "x1": [np.nan, 3]} + ) + result = pd.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)): + pd.DataFrame([Point(0, 0), {"x": 1, "y": 0}]) + + def test_constructor_list_of_list_like_dataclasses(self): + # GH#41682 a dataclass that is also list-like (e.g. a UserList subclass) + # is treated as list-like, not converted to a dict of its fields + @dataclass(frozen=True) + class MyList(UserList): + data: list + + result = pd.DataFrame([MyList([1, 2, 3]), [4, 5, 6]]) + expected = pd.DataFrame([[1, 2, 3], [4, 5, 6]]) + tm.assert_frame_equal(result, expected) + + 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 = pd.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 = pd.DataFrame(data) + tm.assert_frame_equal(result, expected) + + def test_constructor_Series_named(self): + a = pd.Series([1, 2, 3], index=["a", "b", "c"], name="x") + df = pd.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 = pd.Series(arr, name="x") + df = pd.DataFrame(s) + expected = pd.DataFrame({"x": s}) + tm.assert_frame_equal(df, expected) + + s = pd.Series(arr, index=range(3, 13)) + df = pd.DataFrame(s) + expected = pd.DataFrame({0: s}) + tm.assert_frame_equal(df, expected, check_column_type=False) + + msg = r"Shape of passed values is \(10, 1\), indices imply \(10, 2\)" + with pytest.raises(ValueError, match=msg): + pd.DataFrame(s, columns=[1, 2]) + + # #2234 + a = pd.Series([], name="x", dtype=object) + df = pd.DataFrame(a) + assert df.columns[0] == "x" + + # series with name and w/o + s1 = pd.Series(arr, name="x") + df = pd.DataFrame([s1, arr]).T + expected = pd.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 = pd.DataFrame([arr, s1]).T + expected = pd.DataFrame({1: s1, 0: arr}, columns=range(2)) + tm.assert_frame_equal(df, expected) + + def test_constructor_Series_named_and_columns(self): + # GH 9232 validation + + s0 = pd.Series(range(5), name=0) + s1 = pd.Series(range(5), name=1) + + # matching name and column gives standard frame + tm.assert_frame_equal(pd.DataFrame(s0, columns=[0]), s0.to_frame()) + tm.assert_frame_equal(pd.DataFrame(s1, columns=[1]), s1.to_frame()) + + # non-matching produces empty frame + assert pd.DataFrame(s0, columns=[1]).empty + assert pd.DataFrame(s1, columns=[0]).empty + + def test_constructor_Series_differently_indexed(self): + # name + s1 = pd.Series([1, 2, 3], index=["a", "b", "c"], name="x") + + # no name + s2 = pd.Series([1, 2, 3], index=["a", "b", "c"]) + + other_index = pd.Index(["a", "b"]) + + df1 = pd.DataFrame(s1, index=other_index) + exp1 = pd.DataFrame(s1.reindex(other_index)) + assert df1.columns[0] == "x" + tm.assert_frame_equal(df1, exp1) + + df2 = pd.DataFrame(s2, index=other_index) + exp2 = pd.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 = [ + pd.Index(["a", "b", "c"], name=name_in1), + pd.Index(["b", "c", "d"], name=name_in2), + pd.Index(["c", "d", "e"], name=name_in3), + ] + series = { + c: pd.Series([0, 1, 2], index=i) + for i, c in zip(indices, ["x", "y", "z"], strict=True) + } + result = pd.DataFrame(series) + + exp_ind = pd.Index(["a", "b", "c", "d", "e"], name=name_out) + expected = pd.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]) + + msg = "Passing a BlockManager to DataFrame" + with tm.assert_produces_warning( + DeprecationWarning, match=msg, check_stacklevel=False + ): + result = pd.DataFrame(float_frame._mgr, index=index, columns=columns) + tm.assert_index_equal(result.index, pd.Index(index)) + tm.assert_index_equal(result.columns, pd.Index(columns)) + + def test_constructor_mix_series_nonseries(self, float_frame): + df = pd.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): + pd.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): + pd.DataFrame([[np.nan, 1], [1, 0]], dtype=np.int64) + + def test_constructor_column_duplicates(self): + # it works! #2079 + df = pd.DataFrame([[8, 5]], columns=["a", "a"]) + edf = pd.DataFrame([[8, 5]]) + edf.columns = ["a", "a"] + + tm.assert_frame_equal(df, edf) + + idf = pd.DataFrame.from_records([(8, 5)], columns=["a", "a"]) + + tm.assert_frame_equal(idf, edf) + + def test_constructor_empty_with_string_dtype(self, using_infer_string): + # GH 9428 + expected = pd.DataFrame(index=[0, 1], columns=[0, 1], dtype=object) + expected_str = pd.DataFrame( + index=[0, 1], columns=[0, 1], dtype=pd.StringDtype(na_value=np.nan) + ) + + df = pd.DataFrame(index=[0, 1], columns=[0, 1], dtype=str) + if using_infer_string: + tm.assert_frame_equal(df, expected_str) + else: + tm.assert_frame_equal(df, expected) + df = pd.DataFrame(index=[0, 1], columns=[0, 1], dtype=np.str_) + tm.assert_frame_equal(df, expected) + df = pd.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 = pd.DataFrame(columns=["c1"], dtype=nullable_string_dtype) + df = pd.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 = pd.DataFrame(0.0, index=[1, 2, 3], columns=["a", "b", "c"]) + tm.assert_frame_equal( + df, pd.DataFrame(np.zeros(df.shape).astype("float64"), df.index, df.columns) + ) + + df = pd.DataFrame(0, index=[1, 2, 3], columns=["a", "b", "c"]) + tm.assert_frame_equal( + df, pd.DataFrame(np.zeros(df.shape).astype("int64"), df.index, df.columns) + ) + + df = pd.DataFrame("a", index=[1, 2], columns=["a", "c"]) + tm.assert_frame_equal( + df, + pd.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): + pd.DataFrame("a", [1, 2]) + with pytest.raises(ValueError, match=msg): + pd.DataFrame("a", columns=["a", "c"]) + + msg = "incompatible data and dtype" + with pytest.raises(TypeError, match=msg): + pd.DataFrame("a", [1, 2], ["a", "c"], float) + + def test_constructor_with_datetimes(self, using_infer_string): + intname = np.dtype(int).name + floatname = np.dtype(np.float64).name + objectname = np.dtype(np.object_).name + + # single item + df = pd.DataFrame( + { + "A": 1, + "B": "foo", + "C": "bar", + "D": pd.Timestamp("20010101").as_unit("s"), + "E": datetime(2001, 1, 2, 0, 0), + }, + index=np.arange(10), + ) + result = df.dtypes + expected = pd.Series( + [np.dtype("int64")] + + [ + np.dtype(objectname) + if not using_infer_string + else pd.StringDtype(na_value=np.nan) + ] + * 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 an ndim 0 + # ndarray with a dtype specified) + df = pd.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 = pd.Series( + [ + np.dtype("float64"), + np.dtype("int64"), + np.dtype("object") + if not using_infer_string + else pd.StringDtype(na_value=np.nan), + 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 = pd.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 = pd.Series( + [ + np.dtype("float64"), + np.dtype("int64"), + np.dtype("object") + if not using_infer_string + else pd.StringDtype(na_value=np.nan), + 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 = pd.date_range(start="2000-01-01", freq="D", periods=10) + datetimes = [ts.to_pydatetime() for ts in ind] + datetime_s = pd.Series(datetimes) + assert datetime_s.dtype == "M8[us]" + + def test_constructor_with_datetimes2(self): + # GH 2810 + ind = pd.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 = pd.DataFrame(datetimes, columns=["datetimes"]) + df["dates"] = dates + result = df.dtypes + expected = pd.Series( + [np.dtype("datetime64[us]"), 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 + dt = datetime(2012, 1, 1, tzinfo=zoneinfo.ZoneInfo("US/Eastern")) + + df = pd.DataFrame({"End Date": dt}, index=[0]) + assert df.iat[0, 0] == dt + tm.assert_series_equal( + df.dtypes, + pd.Series({"End Date": "datetime64[us, US/Eastern]"}, dtype=object), + ) + + df = pd.DataFrame([{"End Date": dt}]) + assert df.iat[0, 0] == dt + tm.assert_series_equal( + df.dtypes, + pd.Series({"End Date": "datetime64[us, US/Eastern]"}, dtype=object), + ) + + def test_constructor_with_datetimes4(self): + # tz-aware (UTC and other tz's) + # GH 8411 + dr = pd.date_range("20130101", periods=3) + df = pd.DataFrame({"value": dr}) + assert df.iat[0, 0].tz is None + dr = pd.date_range("20130101", periods=3, tz="UTC") + df = pd.DataFrame({"value": dr}) + assert str(df.iat[0, 0].tz) == "UTC" + dr = pd.date_range("20130101", periods=3, tz="US/Eastern") + df = pd.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 = pd.date_range("1/1/2011", periods=5, freq="10s", tz="US/Eastern") + + expected = pd.DataFrame({"a": i.to_series().reset_index(drop=True)}) + df = pd.DataFrame() + df["a"] = i + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame({"a": i}) + tm.assert_frame_equal(df, expected) + + def test_constructor_with_datetimes6(self): + # multiples + i = pd.date_range("1/1/2011", periods=5, freq="10s", tz="US/Eastern") + i_no_tz = pd.date_range("1/1/2011", periods=5, freq="10s") + df = pd.DataFrame({"a": i, "b": i_no_tz}) + expected = pd.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(2011, 1, 1), None]), + np.array([None, None, datetime(2011, 1, 1), None]), + [[np.datetime64("NaT", "ns")], [None]], + [[np.datetime64("NaT", "ns")], [pd.NaT]], + [[None], [np.datetime64("NaT", "ns")]], + [[None], [pd.NaT]], + [[pd.NaT], [np.datetime64("NaT", "ns")]], + [[pd.NaT], [None]], + ], + ) + def test_constructor_datetimes_with_nulls(self, arr): + # gh-15869, GH#11220 + result = pd.DataFrame(arr).dtypes + unit = "ns" + if isinstance(arr, np.ndarray): + # inferred from a pydatetime object + unit = "us" + elif not any(isinstance(x, np.datetime64) for y in arr for x in y): + # TODO: this condition is not clear about why we have different behavior + unit = "s" + expected = pd.Series([np.dtype(f"datetime64[{unit}]")]) + 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 = pd.DataFrame(na) + expected = pd.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 = pd.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 = pd.DataFrame( + [ + [pd.Timedelta(1, "D"), pd.Timedelta(2, "D")], + [pd.Timedelta(4, "D"), pd.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_list_of_timedeltaindex_with_nat(self): + # GH#23985 NaT in TimedeltaIndex should not be cast to datetime64 + tdi = pd.TimedeltaIndex(["1 Day", "NaT"]) + result = pd.DataFrame([tdi]) + expected = pd.DataFrame( + [[pd.Timedelta("1 Day"), pd.NaT]], dtype="timedelta64[us]" + ) + tm.assert_frame_equal(result, expected) + + def test_constructor_list_of_datetimeindex_with_nat(self): + # GH#23985 + dti = pd.DatetimeIndex(["2020-01-01", "NaT"]) + result = pd.DataFrame([dti]) + expected = pd.DataFrame( + [[pd.Timestamp("2020-01-01"), pd.NaT]], dtype="datetime64[us]" + ) + tm.assert_frame_equal(result, expected) + + @td.skip_if_no("pyarrow") + def test_constructor_list_of_ea_preserves_dtype(self): + # GH#49593 uniform EA dtypes should be preserved + arrs = [ + pd.array([1, 2, 3], dtype="int64[pyarrow]"), + pd.array([4, 5, 6], dtype="int64[pyarrow]"), + ] + result = pd.DataFrame(arrs) + expected = pd.DataFrame( + { + 0: pd.array([1, 4], dtype="int64[pyarrow]"), + 1: pd.array([2, 5], dtype="int64[pyarrow]"), + 2: pd.array([3, 6], dtype="int64[pyarrow]"), + } + ) + tm.assert_frame_equal(result, expected) + + def test_constructor_dict_of_series_preserves_byteorder(self): + # GH#43042 same-dtype Series get consolidated into one block; the + # non-native byteorder (and the values) must be preserved + df = pd.DataFrame( + { + "a": pd.Series([0, 256], dtype=">i8"), + "b": pd.Series([1, 257], dtype=">i4"), + "c": pd.Series([2, 258], dtype=">i8"), + } + ) + assert df["a"].dtype == np.dtype(">i8") + assert df["b"].dtype == np.dtype(">i4") + assert df["c"].dtype == np.dtype(">i8") + assert df["a"].tolist() == [0, 256] + assert df["b"].tolist() == [1, 257] + assert df["c"].tolist() == [2, 258] + + def test_constructor_list_of_ragged_arrays_first_shortest(self): + # GH#64958 the uniform-dtype fast path must not silently truncate + # ragged rows; they should be padded to max width with NaN + # (pin int64 so the result dtype matches on 32- and 64-bit platforms) + # GH#65751 the ragged padding itself is deprecated + msg = "Constructing a DataFrame from a list of sequences with mismatched" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = pd.DataFrame( + [np.array([1, 2], dtype=np.int64), np.array([3, 4, 5], dtype=np.int64)] + ) + expected = pd.DataFrame([[1, 2, np.nan], [3, 4, 5]]) + tm.assert_frame_equal(result, expected) + + def test_constructor_list_of_ragged_arrays_first_longest(self): + # GH#64958 a longer first row must not raise IndexError; ragged rows + # should be padded to max width with NaN + # GH#65751 the ragged padding itself is deprecated + msg = "Constructing a DataFrame from a list of sequences with mismatched" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = pd.DataFrame( + [np.array([1, 2, 3], dtype=np.int64), np.array([4, 5], dtype=np.int64)] + ) + expected = pd.DataFrame([[1, 2, 3], [4, 5, np.nan]]) + tm.assert_frame_equal(result, expected) + + def test_constructor_for_list_with_dtypes(self, using_infer_string): + # test list of lists/ndarrays + df = pd.DataFrame([np.arange(5) for x in range(5)]) + result = df.dtypes + expected = pd.Series([np.dtype("int")] * 5) + tm.assert_series_equal(result, expected) + + df = pd.DataFrame([np.array(np.arange(5), dtype="int32") for x in range(5)]) + result = df.dtypes + expected = pd.Series([np.dtype("int32")] * 5) + tm.assert_series_equal(result, expected) + + # overflow issue? (we always expected int64 upcasting here) + df = pd.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 = pd.DataFrame([1, 2]) + assert df.dtypes.iloc[0] == np.dtype("int64") + + df = pd.DataFrame([1.0, 2.0]) + assert df.dtypes.iloc[0] == np.dtype("float64") + + df = pd.DataFrame({"a": [1, 2]}) + assert df.dtypes.iloc[0] == np.dtype("int64") + + df = pd.DataFrame({"a": [1.0, 2.0]}) + assert df.dtypes.iloc[0] == np.dtype("float64") + + df = pd.DataFrame({"a": 1}, index=range(3)) + assert df.dtypes.iloc[0] == np.dtype("int64") + + df = pd.DataFrame({"a": 1.0}, index=range(3)) + assert df.dtypes.iloc[0] == np.dtype("float64") + + # with object list + df = pd.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 = pd.Series( + [ + np.dtype("int64"), + np.dtype("float64"), + np.dtype("object") + if not using_infer_string + else pd.StringDtype(na_value=np.nan), + np.dtype("datetime64[us]"), + np.dtype("float64"), + ], + index=list("abcde"), + ) + tm.assert_series_equal(result, expected) + + def test_constructor_frame_copy(self, float_frame): + cop = pd.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 = pd.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): + arr = float_frame.values.copy() + df = pd.DataFrame(arr) + + arr[5] = 5 + assert not (df.values[5] == 5).all() + df = pd.DataFrame(arr, copy=True) + arr[6] = 6 + assert not (df.values[6] == 6).all() + + def test_constructor_series_copy(self, float_frame): + series = float_frame._series + + df = pd.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", + [ + pd.DataFrame([[1, 2, 3], [4, 5, 6]], index=[1, np.nan]), + pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1.1, 2.2, np.nan]), + pd.DataFrame( + [[0, 1, 2, 3], [4, 5, 6, 7]], columns=[np.nan, 1.1, 2.2, np.nan] + ), + pd.DataFrame( + [[0.0, 1, 2, 3.0], [4, 5, 6, 7]], columns=[np.nan, 1.1, 2.2, np.nan] + ), + pd.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))[pd.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 = pd.DataFrame({"a": [np.nan, False]}) + assert d["a"].dtype == np.object_ + assert not d["a"][1] + + def test_constructor_ndarray_categorical_dtype(self): + cat = pd.Categorical(["A", "B", "C"]) + arr = np.array(cat).reshape(-1, 1) + arr = np.broadcast_to(arr, (3, 4)) + + result = pd.DataFrame(arr, dtype=cat.dtype) + + expected = pd.DataFrame({0: cat, 1: cat, 2: cat, 3: cat}) + tm.assert_frame_equal(result, expected) + + def test_constructor_categorical(self): + # GH8626 + + # dict creation + df = pd.DataFrame({"A": list("abc")}, dtype="category") + expected = pd.Series(list("abc"), dtype="category", name="A") + tm.assert_series_equal(df["A"], expected) + + # to_frame + s = pd.Series(list("abc"), dtype="category") + result = s.to_frame() + expected = pd.Series(list("abc"), dtype="category", name=0) + tm.assert_series_equal(result[0], expected) + result = s.to_frame(name="foo") + expected = pd.Series(list("abc"), dtype="category", name="foo") + tm.assert_series_equal(result["foo"], expected) + + # list-like creation + df = pd.DataFrame(list("abc"), dtype="category") + expected = pd.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 + # pre-3.1 this lost the Categorical dtype, going through object + # inference; GH#49593 preserves uniform EA dtypes + cat = pd.Categorical(list("abc")) + df = pd.DataFrame([cat]) + expected = pd.DataFrame( + {idx: pd.Categorical([val], dtype=cat.dtype) for idx, val in enumerate(cat)} + ) + 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 = pd.DataFrame([pd.Categorical(list("abc")), pd.Categorical(list("abd"))]) + expected = pd.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 = pd.DataFrame([pd.Categorical(list("abc")), list("def")]) + expected = pd.DataFrame([["a", "b", "c"], ["d", "e", "f"]]) + tm.assert_frame_equal(df, expected) + + def test_construct_from_listlikes_mismatched_lengths(self): + # GH#65751 ragged input is padded with NaN, which is deprecated + msg = "Constructing a DataFrame from a list of sequences with mismatched" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df = pd.DataFrame( + [pd.Categorical(list("abc")), pd.Categorical(list("abdefg"))] + ) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = pd.DataFrame([list("abc"), list("abdefg")]) + tm.assert_frame_equal(df, expected) + + def test_construct_ragged_list_deprecated(self): + # GH#65751 constructing from sequences of mismatched lengths pads the + # shorter ones with NaN out to the longest, which is deprecated + msg = "Constructing a DataFrame from a list of sequences with mismatched" + expected = pd.DataFrame({0: [1, 3], 1: [2, 4], 2: [np.nan, 5]}) + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = pd.DataFrame([[1, 2], [3, 4, 5]]) + tm.assert_frame_equal(result, expected) + + # list of tuples takes the same code path + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = pd.DataFrame([(1, 2), (3, 4, 5)]) + tm.assert_frame_equal(result, expected) + + # equal-length sequences are unaffected + with tm.assert_produces_warning(None): + pd.DataFrame([[1, 2], [3, 4]]) + + def test_constructor_categorical_series(self): + items = [1, 2, 3, 1] + exp = pd.Series(items).astype("category") + res = pd.Series(items, dtype="category") + tm.assert_series_equal(res, exp) + + items = ["a", "b", "c", "a"] + exp = pd.Series(items).astype("category") + res = pd.Series(items, dtype="category") + tm.assert_series_equal(res, exp) + + # insert into frame with different index + # GH 8076 + index = pd.date_range("20000101", periods=3) + expected = pd.Series( + pd.Categorical(values=[np.nan, np.nan, np.nan], categories=["a", "b", "c"]) + ) + expected.index = index + + expected = pd.DataFrame({"x": expected}) + df = pd.DataFrame( + {"x": pd.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 = pd.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, dtype): + # GH24386: Ensure dtypes are set correctly for an empty DataFrame. + # Empty DataFrame is generated via dictionary data with non-overlapping columns. + data = pd.DataFrame({"a": [1, 2]}, columns=["b"], dtype=dtype) + assert data.b.dtype.name == "object" + + def test_to_frame_with_falsey_names(self): + # GH 16114 + result = pd.Series(name=0, dtype=object).to_frame().dtypes + expected = pd.Series({0: object}) + tm.assert_series_equal(result, expected) + + result = pd.DataFrame(pd.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 = pd.DataFrame({"A": [0, 1, 2, 3, 4]}, dtype=dtype or "int64") + + # GH 26342 + result = pd.DataFrame(range(5), columns=["A"], dtype=dtype) + tm.assert_frame_equal(result, expected) + + # GH 16804 + result = pd.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 = pd.DataFrame([[1, 2, 3], [4, 5, 6]]) + result = pd.DataFrame(List([List([1, 2, 3]), List([4, 5, 6])])) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "extension_arr", + [ + pd.Categorical(list("aabbc")), + SparseArray([1, np.nan, np.nan, np.nan]), + IntervalArray([pd.Interval(0, 1), pd.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 = pd.DataFrame(pd.Series(extension_arr)) + result = pd.DataFrame(extension_arr) + tm.assert_frame_equal(result, expected) + + def test_datetime_date_tuple_columns_from_dict(self): + # GH 10863 + v = date(2011, 1, 1) + tup = v, v + result = pd.DataFrame({tup: pd.Series(range(3), index=range(3))}, columns=[tup]) + expected = pd.DataFrame([0, 1, 2], columns=pd.Index(pd.Series([tup]))) + tm.assert_frame_equal(result, expected) + + def test_datetime_date_tuple_columns_from_dict_timestamp_keys(self): + # GH#36131 a Timestamp key does not match a date column, so this behaves + # like any other non-matching key and gives an empty frame + day = date(2011, 1, 1) + tup = day, day + ts = pd.Timestamp(day) + timedelta(hours=1) + result = pd.DataFrame( + {(ts, ts): pd.Series(range(3), index=range(3))}, columns=[tup] + ) + expected = pd.DataFrame(columns=pd.Index(pd.Series([tup]))) + tm.assert_frame_equal(result, expected) + + def test_construct_with_two_categoricalindex_series(self): + # GH 14600 + s1 = pd.Series( + [39, 6, 4], index=pd.CategoricalIndex(["female", "male", "unknown"]) + ) + s2 = pd.Series( + [2, 152, 2, 242, 150], + index=pd.CategoricalIndex(["f", "female", "m", "male", "unknown"]), + ) + result = pd.DataFrame([s1, s2]) + expected = pd.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 = pd.Series(range(100)) + ser1 = pd.cut(ser, 10).value_counts().head(5) + ser2 = pd.cut(ser, 10).value_counts().tail(5) + result = pd.DataFrame({"1": ser1, "2": ser2}) + index = pd.CategoricalIndex( + [ + pd.Interval(-0.099, 9.9, closed="right"), + pd.Interval(9.9, 19.8, closed="right"), + pd.Interval(19.8, 29.7, closed="right"), + pd.Interval(29.7, 39.6, closed="right"), + pd.Interval(39.6, 49.5, closed="right"), + pd.Interval(49.5, 59.4, closed="right"), + pd.Interval(59.4, 69.3, closed="right"), + pd.Interval(69.3, 79.2, closed="right"), + pd.Interval(79.2, 89.1, closed="right"), + pd.Interval(89.1, 99, closed="right"), + ], + ordered=True, + ) + expected = pd.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 = pd.DataFrame(arr) + + assert df["Date"][0] == dates[0][0] + assert df["Forecasting"][0] == dates[0][1] + + s = pd.Series(arr["Date"]) + assert isinstance(s[0], pd.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 = pd.DataFrame({"datetime": [DatetimeSubclass(2020, 1, 1, 1, 1)]}) + assert data.datetime.dtype == "datetime64[us]" + + def test_with_mismatched_index_length_raises(self): + # GH#33437 + dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") + msg = "|".join( + ["Shape of passed values", "Passed arrays should have the same length"] + ) + with pytest.raises(ValueError, match=msg): + pd.DataFrame(dti, index=range(4)) + + def test_frame_ctor_datetime64_column(self): + rng = pd.date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s") + dates = np.asarray(rng) + + df = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), + index=[np.array(x) for x in index_lists], + ) + assert isinstance(multi.index, pd.MultiIndex) + assert not isinstance(multi.columns, pd.MultiIndex) + + multi = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), columns=index_lists + ) + assert isinstance(multi.columns, pd.MultiIndex) + + def test_constructor_reindex_integer_multiindex_to_flat(self): + # GH#26460 constructing from a unique integer-MultiIndex DataFrame with a + # flat integer index reindexes rather than raising a buffer-dtype error + df = pd.DataFrame( + np.arange(9.0).reshape(3, 3), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + result = pd.DataFrame(df.iloc[[0, 1]], index=[8, 10]) + expected = pd.DataFrame(np.nan, index=pd.Index([8, 10]), columns=df.columns) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "input_vals", + [ + ([1, 2]), + (["1", "2"]), + (list(pd.date_range("1/1/2011", periods=2, freq="h"))), + (list(pd.date_range("1/1/2011", periods=2, freq="h", tz="US/Eastern"))), + ([pd.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 = pd.DataFrame({"A": input_vals}, dtype=string_dtype) + expected = pd.DataFrame({"A": input_vals}).astype({"A": string_dtype}) + tm.assert_frame_equal(result, expected) + + def test_constructor_list_str_na(self, string_dtype): + result = pd.DataFrame({"A": [1.0, 2.0, None]}, dtype=string_dtype) + expected = pd.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, + copy, + any_numeric_ea_dtype, + any_numpy_dtype, + ): + 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 = pd.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): + # 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.blocks corresponds to df["c"], we just check that exactly + # one of these arrays is `c`. GH#38939 + assert sum(x.values is c for x in df._mgr.blocks) == 1 + if c_only: + # If we ever stop consolidating in setitem_with_indexer, + # this will become unnecessary. + return + + assert ( + sum( + get_base(x.values) is a + for x in df._mgr.blocks + if isinstance(x.values.dtype, np.dtype) + ) + == 1 + ) + assert ( + sum( + get_base(x.values) is b + for x in df._mgr.blocks + if isinstance(x.values.dtype, np.dtype) + ) + == 1 + ) + + if not copy: + # constructor preserves views + check_views() + + # TODO: most of the rest of this test belongs in indexing tests + should_raise = not lib.is_np_dtype(df.dtypes.iloc[0], "fciuO") + if should_raise: + with pytest.raises(TypeError, match="Invalid value"): + df.iloc[0, 0] = 0 + df.iloc[0, 1] = 0 + return + else: + 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 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 + + def test_construct_from_dict_ea_series(self): + # GH#53744 - default of copy=True should also apply for Series with + # extension dtype + ser = pd.Series([1, 2, 3], dtype="Int64") + df = pd.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 = pd.DataFrame(pd.Series(1, name="foo"), columns=["bar"]) + expected = pd.DataFrame(columns=["bar"]) + tm.assert_frame_equal(result, expected) + + def test_nested_list_columns(self): + # GH 14467 + result = pd.DataFrame( + [[1, 2, 3], [4, 5, 6]], columns=[["A", "A", "A"], ["a", "b", "c"]] + ) + expected = pd.DataFrame( + [[1, 2, 3], [4, 5, 6]], + columns=pd.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 = pd.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 = pd.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 = pd.DataFrame(data3) + expected = pd.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): + pd.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 = pd.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 = pd.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): + pd.DataFrame(data=np.array([]), columns=["a", "b"]) + + def test_construct_with_strings_and_none(self): + # GH#32218 + df = pd.DataFrame(["1", "2", None], columns=["a"], dtype="str") + expected = pd.DataFrame({"a": ["1", "2", None]}, dtype="str") + tm.assert_frame_equal(df, expected) + + @pytest.mark.filterwarnings( + "ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning" + ) + def test_frame_string_inference(self): + # GH#54430 + dtype = pd.StringDtype(na_value=np.nan) + expected = pd.DataFrame( + {"a": ["a", "b"]}, dtype=dtype, columns=pd.Index(["a"], dtype=dtype) + ) + with pd.option_context("future.infer_string", True): + df = pd.DataFrame({"a": ["a", "b"]}) + tm.assert_frame_equal(df, expected) + + expected = pd.DataFrame( + {"a": ["a", "b"]}, + dtype=dtype, + columns=pd.Index(["a"], dtype=dtype), + index=pd.Index(["x", "y"], dtype=dtype), + ) + with pd.option_context("future.infer_string", True): + df = pd.DataFrame({"a": ["a", "b"]}, index=["x", "y"]) + tm.assert_frame_equal(df, expected) + + expected = pd.DataFrame( + {"a": ["a", 1]}, dtype="object", columns=pd.Index(["a"], dtype=dtype) + ) + with pd.option_context("future.infer_string", True): + df = pd.DataFrame({"a": ["a", 1]}) + tm.assert_frame_equal(df, expected) + + expected = pd.DataFrame( + {"a": ["a", "b"]}, dtype="object", columns=pd.Index(["a"], dtype=dtype) + ) + with pd.option_context("future.infer_string", True): + df = pd.DataFrame({"a": ["a", "b"]}, dtype="object") + tm.assert_frame_equal(df, expected) + + @pytest.mark.filterwarnings( + "ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning" + ) + def test_frame_string_inference_array_string_dtype(self): + # GH#54496 + dtype = pd.StringDtype(na_value=np.nan) + expected = pd.DataFrame( + {"a": ["a", "b"]}, dtype=dtype, columns=pd.Index(["a"], dtype=dtype) + ) + with pd.option_context("future.infer_string", True): + df = pd.DataFrame({"a": np.array(["a", "b"])}) + tm.assert_frame_equal(df, expected) + + expected = pd.DataFrame({0: ["a", "b"], 1: ["c", "d"]}, dtype=dtype) + with pd.option_context("future.infer_string", True): + df = pd.DataFrame(np.array([["a", "c"], ["b", "d"]])) + tm.assert_frame_equal(df, expected) + + expected = pd.DataFrame( + {"a": ["a", "b"], "b": ["c", "d"]}, + dtype=dtype, + columns=pd.Index(["a", "b"], dtype=dtype), + ) + with pd.option_context("future.infer_string", True): + df = pd.DataFrame(np.array([["a", "c"], ["b", "d"]]), columns=["a", "b"]) + tm.assert_frame_equal(df, expected) + + @pytest.mark.filterwarnings( + "ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning" + ) + def test_frame_string_inference_block_dim(self): + # GH#55363 + with pd.option_context("future.infer_string", True): + df = pd.DataFrame(np.array([["hello", "goodbye"], ["hello", "Hello"]])) + assert df._mgr.blocks[0].ndim == 2 + + @pytest.mark.parametrize("klass", [pd.Series, pd.Index]) + def test_inference_on_pandas_objects(self, klass): + # GH#56012 + obj = klass([pd.Timestamp("2019-12-31")], dtype=object) + result = pd.DataFrame(obj, columns=["a"]) + assert result.dtypes.iloc[0] == np.object_ + + result = pd.DataFrame({"a": obj}) + assert result.dtypes.iloc[0] == np.object_ + + def test_dict_keys_returns_rangeindex(self): + result = pd.DataFrame({0: [1], 1: [2]}).columns + expected = pd.RangeIndex(2) + tm.assert_index_equal(result, expected, exact=True) + + @pytest.mark.parametrize( + "cons", + [pd.Series, pd.Index, pd.DatetimeIndex, pd.DataFrame, pd.array, pd.to_datetime], + ) + def test_construction_datetime_resolution_inference(self, cons): + ts = pd.Timestamp(2999, 1, 1) + ts2 = ts.tz_localize("US/Pacific") + + obj = cons([ts]) + res_dtype = tm.get_dtype(obj) + assert res_dtype == "M8[us]", res_dtype + + obj2 = cons([ts2]) + res_dtype2 = tm.get_dtype(obj2) + assert res_dtype2 == "M8[us, US/Pacific]", res_dtype2 + + def test_construction_nan_value_timedelta64_dtype(self): + # GH#60064 + result = pd.DataFrame([None, 1], dtype="timedelta64[ns]") + expected = pd.DataFrame( + ["NaT", "0 days 00:00:00.000000001"], dtype="timedelta64[ns]" + ) + tm.assert_frame_equal(result, expected) + + def test_dataframe_from_array_like_with_name_attribute(self): + # GH#61443 + class DummyArray(np.ndarray): + def __new__(cls, input_array): + obj = np.asarray(input_array).view(cls) + obj.name = "foo" + return obj + + dummy = DummyArray(np.eye(3)) + df = pd.DataFrame(dummy) + expected = pd.DataFrame(np.eye(3)) + tm.assert_frame_equal(df, expected) + + +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 = pd.Series(np.random.default_rng(2).standard_normal(len(rng1)), rng1) + + rng2 = pd.period_range("1/1/1980", "12/1/2001", freq="M") + s2 = pd.Series(np.random.default_rng(2).standard_normal(len(rng2)), rng2) + df = pd.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 = pd.date_range("2016-01-01", periods=3) + + ser1 = pd.Series(range(3), index=dti) + ser2 = pd.Series(range(3), index=dti.tz_localize("UTC")) + ser3 = pd.Series(range(3), index=dti.tz_localize("US/Central")) + ser4 = pd.Series(range(3)) + + # no tz-naive, but we do have mixed tzs and a non-DTI + df1 = pd.DataFrame({"A": ser2, "B": ser3, "C": ser4}) + exp_index = pd.Index( + list(ser2.index) + list(ser3.index) + list(ser4.index), dtype=object + ) + tm.assert_index_equal(df1.index, exp_index) + + df2 = pd.DataFrame({"A": ser2, "C": ser4, "B": ser3}) + exp_index3 = pd.Index( + list(ser2.index) + list(ser4.index) + list(ser3.index), dtype=object + ) + tm.assert_index_equal(df2.index, exp_index3) + + df3 = pd.DataFrame({"B": ser3, "A": ser2, "C": ser4}) + exp_index3 = pd.Index( + list(ser3.index) + list(ser2.index) + list(ser4.index), dtype=object + ) + tm.assert_index_equal(df3.index, exp_index3) + + df4 = pd.DataFrame({"C": ser4, "B": ser3, "A": ser2}) + exp_index4 = pd.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): + pd.DataFrame({"A": ser2, "B": ser3, "C": ser4, "D": ser1}) + with pytest.raises(TypeError, match=msg): + pd.DataFrame({"A": ser2, "B": ser3, "D": ser1}) + with pytest.raises(TypeError, match=msg): + pd.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 = pd.DataFrame({key_val: [1, 2]}, columns=cols) + expected = pd.DataFrame([[1, np.nan], [2, np.nan]], columns=cols) + expected.isetitem(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): + pd.DataFrame(arr, dtype="i8") + + df = pd.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): + pd.DataFrame(arr, dtype="i8") + with pytest.raises(IntCastingNaNError, match=msg): + pd.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): + pd.DataFrame(arr).astype("i8") + with pytest.raises(IntCastingNaNError, match=msg): + pd.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 = pd.date_range("2011/1/1", "2012/1/1", freq="W-FRI", unit="ns") + dr_tz = dr.tz_localize(tz) + df = pd.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 = pd.DataFrame({"dr": dr}) + df["dr_tz"] = dr_tz + df["datetimes_naive"] = datetimes_naive + df["datetimes_with_tz"] = datetimes_with_tz + result = df.dtypes + expected = pd.Series( + [ + np.dtype("datetime64[ns]"), + DatetimeTZDtype(tz=tz), + np.dtype("datetime64[us]"), + DatetimeTZDtype(tz=tz, unit="us"), + ], + 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 = pd.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): + pd.DataFrame({0: [ts]}, dtype="datetime64[ns]") + + msg2 = "Cannot unbox tzaware Timestamp to tznaive dtype" + with pytest.raises(TypeError, match=msg2): + pd.DataFrame({0: ts}, index=[0], dtype="datetime64[ns]") + + with pytest.raises(ValueError, match=msg): + pd.DataFrame([ts], dtype="datetime64[ns]") + + with pytest.raises(ValueError, match=msg): + pd.DataFrame(np.array([ts], dtype=object), dtype="datetime64[ns]") + + with pytest.raises(TypeError, match=msg2): + pd.DataFrame(ts, index=[0], columns=[0], dtype="datetime64[ns]") + + with pytest.raises(ValueError, match=msg): + pd.DataFrame([pd.Series([ts])], dtype="datetime64[ns]") + + with pytest.raises(ValueError, match=msg): + pd.DataFrame([[ts]], columns=[0], dtype="datetime64[ns]") + + def test_from_dict(self): + # 8260 + # support datetime64 with tz + + idx = pd.Index( + pd.date_range("20130101", periods=3, tz="US/Eastern"), name="foo" + ) + dr = pd.date_range("20130110", periods=3) + + # construction + df = pd.DataFrame({"A": idx, "B": dr}) + assert df["A"].dtype, "M8[ns, US/Eastern" + assert df["A"].name == "A" + tm.assert_series_equal(df["A"], pd.Series(idx, name="A")) + tm.assert_series_equal(df["B"], pd.Series(dr, name="B")) + + def test_from_index(self): + # from index + idx2 = pd.date_range("20130101", periods=3, tz="US/Eastern", name="foo") + df2 = pd.DataFrame(idx2) + tm.assert_series_equal(df2["foo"], pd.Series(idx2, name="foo")) + df2 = pd.DataFrame(pd.Series(idx2)) + tm.assert_series_equal(df2["foo"], pd.Series(idx2, name="foo")) + + idx2 = pd.date_range("20130101", periods=3, tz="US/Eastern") + df2 = pd.DataFrame(idx2) + tm.assert_series_equal(df2[0], pd.Series(idx2, name=0)) + df2 = pd.DataFrame(pd.Series(idx2)) + tm.assert_series_equal(df2[0], pd.Series(idx2, name=0)) + + def test_frame_dict_constructor_datetime64_1680(self): + dr = pd.date_range("1/1/2012", periods=10) + s = pd.Series(dr, index=dr) + + # it works! + pd.DataFrame({"a": "foo", "b": s}, index=dr) + pd.DataFrame({"a": "foo", "b": s.values}, index=dr) + + def test_frame_datetime64_mixed_index_ctor_1681(self): + dr = pd.date_range("2011/1/1", "2012/1/1", freq="W-FRI") + ts = pd.Series(dr) + + # it works! + d = pd.DataFrame({"A": "foo", "B": ts}, index=dr) + assert d["B"].isna().all() + + def test_frame_timeseries_column(self): + # GH19157 + dr = pd.date_range( + start="20130101T10:00:00", periods=3, freq="min", tz="US/Eastern", unit="ns" + ) + result = pd.DataFrame(dr, columns=["timestamps"]) + expected = pd.DataFrame( + { + "timestamps": [ + pd.Timestamp("20130101T10:00:00", tz="US/Eastern"), + pd.Timestamp("20130101T10:01:00", tz="US/Eastern"), + pd.Timestamp("20130101T10:02:00", tz="US/Eastern"), + ] + }, + dtype="M8[ns, 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 = pd.DataFrame(pop, index=[2001, 2002, 2003], columns=columns) + expected = pd.DataFrame( + [(2.4, 1.7), (2.9, 3.6), (np.nan, np.nan)], + columns=columns, + index=pd.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 = pd.date_range("2016-04-05 04:30", periods=3, tz="UTC") + data = dti._data.astype(object).reshape(1, -1) + df = pd.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( + [ + [ + pd.Timestamp("2013-01-01 00:00:00"), + pd.Timestamp("2013-01-02 00:00:00"), + pd.Timestamp("2013-01-03 00:00:00"), + ], + [ + pd.Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"), + pd.NaT, + pd.Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"), + ], + [ + pd.Timestamp("2013-01-01 00:00:00+0100", tz="CET"), + pd.NaT, + pd.Timestamp("2013-01-03 00:00:00+0100", tz="CET"), + ], + ], + dtype=object, + ).T + res = pd.DataFrame(arr, columns=["A", "B", "C"]) + + expected_dtypes = [ + "datetime64[us]", + "datetime64[us, US/Eastern]", + "datetime64[us, 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 = pd.DataFrame(array_dim2, dtype="datetime64[ns, UTC]") + + expected = pd.DataFrame(array_dim2).astype("datetime64[ns, UTC]") + tm.assert_frame_equal(df, expected) + + def test_from_2d_dt64_ndarray_with_tz_dtype(self): + # GH#58517 + arr = np.array( + ["2020-01-01", "2020-06-01", "2021-01-01", "2021-06-01"], dtype="M8[ns]" + ).reshape(2, 2) + result = pd.DataFrame(arr, dtype="datetime64[ns, US/Eastern]") + + expected = pd.DataFrame( + {i: pd.DatetimeIndex(arr[:, i]).tz_localize("US/Eastern") for i in range(2)} + ) + tm.assert_frame_equal(result, 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): + pd.DataFrame({"a": values}) + + with pytest.raises(TypeError, match=msg): + pd.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 = pd.DataFrame(arr) + assert all(isinstance(block.values, DatetimeArray) for block in df._mgr.blocks) + + 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): + pd.DataFrame(arr, columns=["foo"], dtype=dtype) + + arr2 = pd.array([2.0, 3.0, 4.0]) + with pytest.raises(ValueError, match=msg): + pd.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"): + pd.DataFrame(data, index={"a", "b"}) + with pytest.raises(ValueError, match="columns cannot be a set"): + pd.DataFrame(data, columns={"a", "b", "c"}) + + def test_from_dict_with_columns_na_scalar(self): + result = pd.DataFrame({"a": pd.NaT}, columns=["a"], index=range(2)) + expected = pd.DataFrame({"a": pd.Series([pd.NaT, pd.NaT])}) + tm.assert_frame_equal(result, expected) + + # TODO: make this not cast to object in pandas 3.0 + @pytest.mark.parametrize( + "data", + [ + {"a": ["a", "b", "c"], "b": [1.0, 2.0, 3.0], "c": ["d", "e", "f"]}, + ], + ) + def test_np_string_array_object_cast(self, data): + from numpy.dtypes import StringDType + + data["a"] = np.array(data["a"], dtype=StringDType()) + res = pd.DataFrame(data) + assert res["a"].dtype == np.object_ + assert (res["a"] == data["a"]).all() + + def test_2d_ea_with_dtype_cast(self): + # GH#64634 - Constructing a DataFrame from a 2D tz-aware DatetimeArray + # with a different dtype + dta = pd.array(pd.date_range("2020-01-01", periods=6, tz="UTC")) + arr2d = dta.reshape(3, 2) + + result = pd.DataFrame(arr2d, dtype="datetime64[ns, US/Eastern]") + expected = pd.DataFrame( + { + 0: arr2d[:, 0].astype("datetime64[ns, US/Eastern]"), + 1: arr2d[:, 1].astype("datetime64[ns, US/Eastern]"), + } + ) + tm.assert_frame_equal(result, expected) + + +def get1(obj): # TODO: make a helper in tm? + if isinstance(obj, pd.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 pd.DataFrame: + extra["columns"] = ["A"] + + if box is None: + return functools.partial(frame_or_series, **extra) + + elif box is dict: + if frame_or_series is pd.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 pd.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 = pd.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 + pd.Timedelta(1) + + obj = constructor(ts, dtype="M8[ns]") + assert get1(obj) == ts + + def test_from_timedelta64_scalar_object(self, constructor): + td = pd.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 = "Invalid type for timedelta scalar: " + else: + msg1 = " is not convertible to datetime" + 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 + 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 pd.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, box, frame_or_series + ): + 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 pd.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 = pd.Timestamp("2019", tz=tz) + + if box is None or (frame_or_series is pd.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 = pd.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 = pd.DatetimeIndex(arr) + assert idx.dtype == arr.dtype + + def test_series_allow_non_nano(self, arr): + ser = pd.Series(arr) + assert ser.dtype == arr.dtype + + def test_frame_allow_non_nano(self, arr): + df = pd.DataFrame(arr) + assert df.dtypes[0] == arr.dtype + + def test_frame_from_dict_allow_non_nano(self, arr): + df = pd.DataFrame({0: arr}) + assert df.dtypes[0] == arr.dtype diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_cumulative.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_cumulative.py new file mode 100644 index 0000000000000000000000000000000000000000..d23e5c42a7b12cb18367a5cafed4ab7e77a5bd92 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_cumulative.py @@ -0,0 +1,124 @@ +""" +Tests for DataFrame cumulative operations + +See also +-------- +tests.series.test_cumulative +""" + +import numpy as np +import pytest + +from pandas.errors import OutOfBoundsTimedelta + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameCumulativeOps: + # --------------------------------------------------------------------- + # Cumulative Operations - cumsum, cummax, ... + + def test_cumulative_ops_smoke(self): + # it works + df = pd.DataFrame({"A": np.arange(20)}, index=np.arange(20)) + df.cummax() + df.cummin() + df.cumsum() + + dm = pd.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) + + def test_cumulative_ops_match_series_apply( + self, datetime_frame, all_numeric_accumulations + ): + 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, all_numeric_accumulations)() + expected = datetime_frame.apply(getattr(pd.Series, all_numeric_accumulations)) + tm.assert_frame_equal(result, expected) + + # axis = 1 + result = getattr(datetime_frame, all_numeric_accumulations)(axis=1) + expected = datetime_frame.apply( + getattr(pd.Series, all_numeric_accumulations), 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 = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3.0], "C": [True, False, False]}) + + result = df.cumsum() + + expected = pd.DataFrame( + { + "A": pd.Series([1, 3, 6], dtype=np.int64), + "B": pd.Series([1, 3, 6], dtype=np.float64), + "C": df["C"].cumsum(), + } + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("method", ["cumsum", "cumprod", "cummin", "cummax"]) + @pytest.mark.parametrize("axis", [0, 1]) + def test_numeric_only_flag(self, method, axis): + df = pd.DataFrame( + { + "int": [1, 2, 3], + "bool": [True, False, False], + "string": ["a", "b", "c"], + "float": [1.0, 3.5, 4.0], + "datetime": [ + pd.Timestamp(2018, 1, 1), + pd.Timestamp(2019, 1, 1), + pd.Timestamp(2020, 1, 1), + ], + } + ) + df_numeric_only = df.drop(["string", "datetime"], axis=1) + + result = getattr(df, method)(axis=axis, numeric_only=True) + expected = getattr(df_numeric_only, method)(axis) + tm.assert_frame_equal(result, expected) + + def test_cummax_pyarrow_float_negative(self): + # GH#66257 + pytest.importorskip("pyarrow") + df = pd.DataFrame({"a": [-4.0, -3.0, -2.0]}, dtype="float64[pyarrow]") + + result = df.cummax() + expected = pd.DataFrame({"a": [-4.0, -3.0, -2.0]}, dtype="float64[pyarrow]") + tm.assert_frame_equal(result, expected) + + +def test_td64_cumsum_overflow(): + # GH#66551: the check applies per column + df = pd.DataFrame( + {"a": [pd.Timedelta(1, "D")] * 2, "b": [pd.Timedelta.max] * 2}, + dtype="m8[ns]", + ) + with pytest.raises(OutOfBoundsTimedelta, match="overflow in timedelta operation"): + df.cumsum() diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_iteration.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_iteration.py new file mode 100644 index 0000000000000000000000000000000000000000..f40f88f0db68c5a92e702c2f762bf47da33d3b36 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_iteration.py @@ -0,0 +1,178 @@ +import datetime + +import numpy as np +import pytest + +from pandas.compat import ( + IS64, + is_platform_windows, +) + +import pandas as pd +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 = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) + for k, v in df.items(): + assert isinstance(v, pd.DataFrame._constructor_sliced) + + def test_items(self): + # GH#17213, GH#13918 + cols = ["a", "b", "c"] + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=cols) + for c, (k, v) in zip(cols, df.items(), strict=True): + assert c == k + assert isinstance(v, pd.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 list(float_frame) == list(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 = pd.DataFrame( + { + "non_iso8601": ["M1701", "M1802", "M1903", "M2004"], + "iso8601": pd.date_range("2000-01-01", periods=4, freq="ME"), + } + ) + for k, v in s.iterrows(): + exp = s.loc[k] + tm.assert_series_equal(v, exp) + + def test_iterrows_no_datetime_coercion(self): + # GH#26427 - string that looks like a year should not be coerced + # to Timestamp when row also contains a datetime + df = pd.DataFrame( + { + "a": ["1801", "11801"], + "b": pd.date_range("2020-01-01", periods=2), + } + ) + df["a"] = df["a"].astype(object) + for idx, row in df.iterrows(): + assert isinstance(row["a"], str), ( + f"row {idx}: 'a' was coerced to {type(row['a'])}" + ) + + def test_iterrows_corner(self): + # GH#12222 + df = pd.DataFrame( + { + "a": [datetime.datetime(2015, 1, 1)], + "b": [None], + "c": [None], + "d": [""], + "e": [[]], + "f": [set()], + "g": [{}], + } + ) + expected = pd.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 = pd.DataFrame._constructor_sliced(tup[1:]) + ser.name = tup[0] + expected = float_frame.iloc[i, :].reset_index(drop=True) + tm.assert_series_equal(ser, expected) + + def test_itertuples_index_false(self): + df = pd.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) + + def test_itertuples_duplicate_cols(self): + df = pd.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)]" + ) + + def test_itertuples_tuple_name(self): + df = pd.DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 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" + + def test_itertuples_no_columns_index_false(self): + # GH#25408 + df = pd.DataFrame(index=["A", "B"]) + assert list(df.itertuples(index=False, name=None)) == [(), ()] + result = list(df.itertuples(index=False)) + assert result == [(), ()] + assert all(tup._fields == () for tup in result) + + def test_itertuples_disallowed_col_labels(self): + df = pd.DataFrame(data={"def": [1, 2, 3], "return": [4, 5, 6]}) + tup2 = next(df.itertuples(name="TestName")) + assert tup2 == (0, 1, 4) + assert tup2._fields == ("Index", "_1", "_2") + + @pytest.mark.parametrize("limit", [254, 255, 1024]) + @pytest.mark.parametrize("index", [True, False]) + def test_itertuples_field_limit_namedtuple(self, limit, index): + # GH#28282 + df = pd.DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(limit)}]) + result = next(df.itertuples(index=index)) + assert isinstance(result, tuple) + assert hasattr(result, "_fields") + + def test_sequence_like_with_categorical(self): + # GH#7839 + # make sure can iterate + df = pd.DataFrame( + {"id": [1, 2, 3, 4, 5, 6], "raw_grade": ["a", "b", "b", "a", "a", "e"]} + ) + df["grade"] = pd.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/venv/lib/python3.14/site-packages/pandas/tests/frame/test_logical_ops.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_logical_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..af9f4ebc226881bf57b4d93db27cdc6bda8cf54e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_logical_ops.py @@ -0,0 +1,221 @@ +import operator +import re + +import numpy as np +import pytest + +import pandas as pd +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 = pd.DataFrame(index=[1]) + + result = df & df + tm.assert_frame_equal(result, df) + + result = df | df + tm.assert_frame_equal(result, df) + + df2 = pd.DataFrame(index=[1, 2]) + result = df & df2 + tm.assert_frame_equal(result, df2) + + dfa = pd.DataFrame(index=[1], columns=["A"]) + + result = dfa & dfa + expected = pd.DataFrame(False, index=[1], columns=["A"]) + tm.assert_frame_equal(result, expected) + + def test_logical_ops_bool_frame(self): + # GH#5808 + df1a_bool = pd.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 = pd.DataFrame(1, index=[1], columns=["A"]) + df1a_bool = pd.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, using_infer_string): + # GH#5808 + + df1 = pd.DataFrame(1.0, index=[1], columns=["A"]) + df2 = pd.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 = pd.DataFrame("foo", index=[1], columns=["A"]) + df2 = pd.DataFrame(True, index=[1], columns=["A"]) + if using_infer_string and df1["A"].dtype.storage == "pyarrow": + msg = "operation 'or_' not supported for dtype 'str'" + else: + 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 = pd.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 = pd.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 = pd.DataFrame(df1) + df2 = pd.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 = pd.DataFrame({"a": [np.nan, False], "b": [True, True]}) + + # GH4947 + # bool comparisons should return bool + result = d["a"] | d["b"] + expected = pd.Series([False, True]) + tm.assert_series_equal(result, expected) + + # GH4604, automatic casting here + result = d["a"].fillna(False) | d["b"] + expected = pd.Series([True, True]) + tm.assert_series_equal(result, expected) + result = d["a"].fillna(False) | d["b"] + expected = pd.Series([True, True]) + tm.assert_series_equal(result, expected) + + def test_logical_ops_categorical_columns(self): + # GH#38367 + intervals = [pd.Interval(1, 2), pd.Interval(3, 4)] + data = pd.DataFrame( + [[1, np.nan], [2, np.nan]], + columns=pd.CategoricalIndex( + intervals, categories=[*intervals, pd.Interval(5, 6)] + ), + ) + mask = pd.DataFrame( + [[False, False], [False, False]], columns=data.columns, dtype=bool + ) + result = mask | pd.isnull(data) + expected = pd.DataFrame( + [[False, True], [False, True]], + columns=pd.CategoricalIndex( + intervals, categories=[*intervals, pd.Interval(5, 6)] + ), + ) + tm.assert_frame_equal(result, expected) + + def test_int_dtype_different_index_not_bool(self): + # GH 52500 + df1 = pd.DataFrame([1, 2, 3], index=[10, 11, 23], columns=["a"]) + df2 = pd.DataFrame([10, 20, 30], index=[11, 10, 23], columns=["a"]) + result = np.bitwise_xor(df1, df2) + expected = pd.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 = pd.DataFrame([1, 2], index=["a", "b"]) + df2 = pd.DataFrame([3, 4], index=["b", "c"]) + with pytest.raises(TypeError, match="unsupported operand type"): + df1 & df2 + + +@pytest.mark.parametrize("op", [operator.and_, operator.or_, operator.xor]) +@pytest.mark.parametrize("dtype", ["datetime64[ns]", "timedelta64[ns]"]) +def test_logical_op_datetimelike_raises(op, dtype): + # GH#68452 the frame path goes through _dispatch_frame_op, not the Series one + left = pd.DataFrame({"a": [True, False, True]}) + right = pd.DataFrame({"a": np.array(["NaT", 1, 2], dtype=dtype)}) + + msg = f"operation 'r?{op.__name__}' not supported for dtype" + with pytest.raises(TypeError, match=msg): + op(left, right) + with pytest.raises(TypeError, match=msg): + op(right, left) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_nonunique_indexes.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_nonunique_indexes.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ffbe4aed99f54d0a4d059058ccb93df55e0c67 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_nonunique_indexes.py @@ -0,0 +1,337 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +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 = pd.DataFrame(arr, columns=["A", "A"]) + df.columns = idx + expected = pd.DataFrame(arr, columns=idx) + tm.assert_frame_equal(df, expected) + + def test_setattr_columns_vs_construct_with_columns_datetimeindx(self): + idx = pd.date_range("20130101", periods=4, freq="QE-NOV") + df = pd.DataFrame( + [[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], columns=["a", "a", "a", "a"] + ) + df.columns = idx + expected = pd.DataFrame([[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], columns=idx) + tm.assert_frame_equal(df, expected) + + def test_insert_with_duplicate_columns(self): + # insert + df = pd.DataFrame( + [[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], + columns=["foo", "bar", "foo", "hello"], + ) + df["string"] = "bah" + expected = pd.DataFrame( + [[1, 1, 1, 5, "bah"], [1, 1, 2, 5, "bah"], [2, 1, 3, 5, "bah"]], + columns=["foo", "bar", "foo", "hello", "string"], + ) + tm.assert_frame_equal(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 = pd.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"], + ) + tm.assert_frame_equal(df, expected) + + # set (non-dup) + df["foo2"] = 4 + expected = pd.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"], + ) + tm.assert_frame_equal(df, expected) + df["foo2"] = 3 + + # delete (non dup) + del df["bar"] + expected = pd.DataFrame( + [[1, 1, 5, "bah", 3], [1, 2, 5, "bah", 3], [2, 3, 5, "bah", 3]], + columns=["foo", "foo", "hello", "string", "foo2"], + ) + tm.assert_frame_equal(df, expected) + + # try to delete again (its not consolidated) + del df["hello"] + expected = pd.DataFrame( + [[1, 1, "bah", 3], [1, 2, "bah", 3], [2, 3, "bah", 3]], + columns=["foo", "foo", "string", "foo2"], + ) + tm.assert_frame_equal(df, expected) + + # consolidate + df = df._consolidate() + expected = pd.DataFrame( + [[1, 1, "bah", 3], [1, 2, "bah", 3], [2, 3, "bah", 3]], + columns=["foo", "foo", "string", "foo2"], + ) + tm.assert_frame_equal(df, expected) + + # insert + df.insert(2, "new_col", 5.0) + expected = pd.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"], + ) + tm.assert_frame_equal(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 = pd.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"], + ) + tm.assert_frame_equal(df, expected) + + # delete (dup) + del df["foo"] + expected = pd.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 = pd.DataFrame( + [[1, 1, 1.0, 5], [1, 1, 2.0, 5], [2, 1, 3.0, 5]], + columns=["foo", "bar", "foo", "hello"], + ) + + df["foo2"] = 7.0 + expected = pd.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"], + ) + tm.assert_frame_equal(df, expected) + + result = df["foo"] + expected = pd.DataFrame([[1, 1.0], [1, 2.0], [2, 3.0]], columns=["foo", "foo"]) + tm.assert_frame_equal(result, expected) + + # multiple replacements + df["foo"] = "string" + expected = pd.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"], + ) + tm.assert_frame_equal(df, expected) + + del df["foo"] + expected = pd.DataFrame( + [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "hello", "foo2"] + ) + tm.assert_frame_equal(df, expected) + + def test_column_dups_indexes(self): + # check column dups with index equal and not equal to df's index + df = pd.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 = pd.Series(index.values, index=this_df.index) + expected_df = pd.DataFrame( + {"A": expected_ser, "B": this_df["B"]}, + columns=["A", "B", "A"], + ) + this_df["A"] = index + tm.assert_frame_equal(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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=["that", "that"] + ) + expected = pd.DataFrame(1.0, index=range(5), columns=["that", "that"]) + + df["that"] = 1.0 + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame( + np.random.default_rng(2).random((5, 2)), columns=["that", "that"] + ) + expected = pd.DataFrame(1, index=range(5), columns=["that", "that"]) + + df["that"] = 1 + tm.assert_frame_equal(df, expected) + + def test_dup_columns_comparisons(self): + # equality + df1 = pd.DataFrame([[1, 2], [2, np.nan], [3, 4], [4, 4]], columns=["A", "B"]) + df2 = pd.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 = pd.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 = pd.DataFrame( + { + "one": pd.Series([True, True, False], index=["a", "b", "c"]), + "two": pd.Series( + [False, False, True, False], index=["a", "b", "c", "d"] + ), + "three": pd.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"]] + tm.assert_frame_equal(result, expected) + + def test_multi_axis_dups(self): + # multi-axis dups + # GH 6121 + df = pd.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 = pd.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"]] + tm.assert_frame_equal(result, expected) + + def test_columns_with_dups(self): + # GH 3468 related + + # basic + df = pd.DataFrame([[1, 2]], columns=["a", "a"]) + df.columns = ["a", "a.1"] + expected = pd.DataFrame([[1, 2]], columns=["a", "a.1"]) + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame([[1, 2, 3]], columns=["b", "a", "a"]) + df.columns = ["b", "a", "a.1"] + expected = pd.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 = pd.DataFrame([[1, 2]], columns=["a", "a"]) + df.columns = ["b", "b"] + expected = pd.DataFrame([[1, 2]], columns=["b", "b"]) + tm.assert_frame_equal(df, expected) + + def test_multi_dtype(self): + # multi-dtype + df = pd.DataFrame( + [[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], + columns=["a", "a", "b", "b", "d", "c", "c"], + ) + df.columns = list("ABCDEFG") + expected = pd.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 = pd.DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a", "a", "a"]) + df.columns = ["a", "a.1", "a.2", "a.3"] + expected = pd.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): + # dups across blocks + df_float = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 3)), dtype="float64" + ) + df_int = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 3)).astype("int64") + ) + df_bool = pd.DataFrame(True, index=df_float.index, columns=df_float.columns) + df_object = pd.DataFrame("foo", index=df_float.index, columns=df_float.columns) + df_dt = pd.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) + + 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 = pd.DataFrame(vals, columns=["A", "A", "B"]) + xp = pd.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 = pd.DataFrame(np.arange(9).reshape(3, 3).T) + df.columns = list("AAA") + expected = df.iloc[:, 2].copy() + + with tm.assert_produces_warning(warn, match=msg): + df.iloc[:, 0] = 3 + tm.assert_series_equal(df.iloc[:, 2], expected) + + df = pd.DataFrame(np.arange(9).reshape(3, 3).T) + df.columns = [2, float(2), str(2)] + expected = df.iloc[:, 1].copy() + + with tm.assert_produces_warning(warn, match=msg): + df.iloc[:, 0] = 3 + tm.assert_series_equal(df.iloc[:, 1], expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_npfuncs.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_npfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..852d567551b80f48da482f3186b249763ddd4abd --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_npfuncs.py @@ -0,0 +1,83 @@ +""" +Tests for np.foo applied to DataFrame, not necessarily ufuncs. +""" + +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestAsArray: + def test_asarray_homogeneous(self): + df = pd.DataFrame({"A": pd.Categorical([1, 2]), "B": pd.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_axis_behavior(self): + # GH#52042 df.sum(axis=None) now reduces over both axes, which gets + # called when we do np.sum(df) + + arr = np.random.default_rng(2).standard_normal((4, 3)) + df = pd.DataFrame(arr) + + res = np.sum(df) + expected = df.to_numpy().sum(axis=None) + assert 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([pd.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( + pd.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( + [ + pd.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/venv/lib/python3.14/site-packages/pandas/tests/frame/test_query_eval.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_query_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..761a4ce509b631f309d8345751e870e186d4f94b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_query_eval.py @@ -0,0 +1,2030 @@ +import operator +from tokenize import TokenError + +import numpy as np +import pytest + +from pandas.errors import ( + NumExprClobberingError, + UndefinedVariableError, +) +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm +from pandas.core.computation.check import ( + NUMEXPR_BLOCKED_VERSION, + NUMEXPR_INSTALLED, +) + +skip_if_no_numexpr = pytest.mark.skipif( + not NUMEXPR_INSTALLED, reason="numexpr not installed or an unsupported version" +) + + +def skip_if_no_numexpr_fixture(): + # Applied inside the engine fixture rather than as a class-level mark: the + # python-engine subclasses override that fixture, but pytest collects marks + # from the whole MRO, so a class mark would skip them too. + if not NUMEXPR_INSTALLED: + pytest.skip("numexpr not installed or an unsupported version") + + +@pytest.fixture(params=["python", "pandas"], ids=lambda x: x) +def parser(request): + return request.param + + +@pytest.fixture( + params=["python", pytest.param("numexpr", marks=skip_if_no_numexpr)], + 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={parser}") + + +class TestCompat: + @pytest.fixture + def df(self): + return pd.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) + + 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) + + 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) + + 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) + return + + if NUMEXPR_BLOCKED_VERSION is not None: + msg = ( + rf"numexpr {NUMEXPR_BLOCKED_VERSION} is installed, but can " + r"silently return incorrect results" + ) + 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 = pd.DataFrame(1, index=range(n), columns=list("abcd")) + df.iloc[0] = 2 + m = df.mean() + + base = pd.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 = pd.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_eval_method_call_fillna(self): + # GH#34045 eval must handle a chained method call such as .fillna(0) + df = pd.DataFrame([1, 2], columns=["a"]) + result = df.eval("((a - 1) / (a - 1)).fillna(0)") + expected = pd.Series([0.0, 1.0], name="a") + tm.assert_series_equal(result, expected) + + def test_query_method_call_isnull(self, engine): + # GH#34251 query must support a method call such as name.isnull(). + # The crash was numexpr-engine-specific, so exercise both engines + # explicitly (the default silently falls back to python without numexpr) + df = pd.DataFrame({"id": [0, 1, 2], "name": ["a", None, None]}) + result = df.query("name.isnull()", engine=engine) + expected = df.iloc[[1, 2]] + tm.assert_frame_equal(result, expected) + + def test_query_non_str(self): + # GH 11485 + df = pd.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 = pd.DataFrame({"A": [1, 2, 3]}) + + msg = "expr cannot be an empty string" + with pytest.raises(ValueError, match=msg): + df.query("") + + def test_query_duplicate_column_name(self, engine, parser): + df = pd.DataFrame({"A": range(3), "B": range(3), "C": range(3)}).rename( + columns={"B": "A"} + ) + + res = df.query("C == 1", engine=engine, parser=parser) + + expect = pd.DataFrame([[1, 1, 1]], columns=["A", "A", "C"], index=[1]) + + tm.assert_frame_equal(res, expect) + + def test_query_duplicate_column_name_referenced(self, engine, parser): + # GH#65588 the eval fix made a duplicated label resolve to a DataFrame; + # query cannot use that as a row mask, so it raises instead of masking. + df = pd.DataFrame({"A": range(3), "B": range(10, 13), "C": range(3)}).rename( + columns={"B": "A"} + ) + + msg = "expr referenced a duplicated column label" + with pytest.raises(ValueError, match=msg): + df.query("A == 1", engine=engine, parser=parser) + + # every column duplicated -> the mask needs no reindexing, so nothing + # but this check stops query from silently returning a NaN-masked frame + df2 = pd.DataFrame({"A": range(3), "B": range(10, 13)}).rename( + columns={"B": "A"} + ) + with pytest.raises(ValueError, match=msg): + df2.query("A == 1", engine=engine, parser=parser) + + def test_query_duplicate_column_name_local_not_shadowed(self, engine, parser): + # GH#65588 the duplicate-label recorder must not capture an @local whose + # name matches a duplicated column: Scope.swapkey rewrites the local by + # writing into the first resolver that *contains* the name + skip_if_no_pandas_parser(parser) + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["AA", "AA", "B"]) + AA = 4 # noqa: F841 + + result = df.query("B > @AA", engine=engine, parser=parser) + + tm.assert_frame_equal(result, df.iloc[[1]]) + + @pytest.mark.parametrize("name", ["Timestamp", "datetime", "list", "tuple"]) + def test_query_index_name_shadowing_default_global(self, name, engine, parser): + # GH#34958, GH#35595 an index level wins over the type-valued + # DEFAULT_GLOBALS; test_eval.py::test_eval_no_support_column_name + # covers the column side + df = pd.DataFrame({"b": [3, 4]}, index=pd.Index([1, 20], name=name)) + + result = df.query(f"{name} < 10", engine=engine, parser=parser) + + tm.assert_frame_equal(result, df.iloc[[0]]) + + def test_query_eval_local_class_attribute(self, engine, parser): + # GH#48694 an @-prefixed name is local even when it refers to a class + skip_if_no_pandas_parser(parser) + + class A: + a = 2 + + df = pd.DataFrame({"x": [1, 2, 3]}) + result = df.query("x == @A.a", engine=engine, parser=parser) + tm.assert_frame_equal(result, df.iloc[[1]]) + result = df.eval("x == @A.a", engine=engine, parser=parser) + tm.assert_series_equal(result, df["x"] == 2) + + def test_query_duplicate_column_name_cleaned_name_collision(self, engine, parser): + # GH#65588 clean_column_name is not injective, so the recorder has to + # ask which label the cleaned name actually resolves to (the last one + # wins) rather than whether any label sharing it is duplicated + skip_if_no_pandas_parser(parser) + + # `1` resolves to the unique str column, so this is not ambiguous + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1, 1, "1"]) + result = df.query("`1` == 3", engine=engine, parser=parser) + tm.assert_frame_equal(result, df.iloc[[0]]) + + # reversed, `1` resolves to the duplicated int label instead + df2 = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1, "1", 1]) + with pytest.raises(ValueError, match="referenced a duplicated column label"): + df2.query("`1` == 3", engine=engine, parser=parser) + + def test_query_duplicate_column_name_reduced_to_mask(self, engine, parser): + # GH#65588 a duplicated label is only a problem when the expression + # leaves the result 2-D; reducing it back to a row mask is valid and + # worked before this guard existed + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) + df.columns = ["a", "a", "c"] + + result = df.query("(a == 1).any(axis=1)", engine=engine, parser=parser) + tm.assert_frame_equal(result, df.iloc[[0]]) + + result = df.query("a.max(axis=1) > 4", engine=engine, parser=parser) + tm.assert_frame_equal(result, df.iloc[[1, 2]]) + + def test_query_duplicate_column_name_whole_frame_mask(self, engine, parser): + # GH#65588 a 2-D mask that does not come from a duplicated label is + # still a valid query, whether or not it references a unique label + skip_if_no_pandas_parser(parser) + df = pd.DataFrame(np.arange(-3, 3).reshape(2, 3), columns=["a", "a", "b"]) + + result = df.query("@df > 0", engine=engine, parser=parser) + tm.assert_frame_equal(result, df[df > 0]) + + # referencing the unique label exercises the recorder's negative branch + expected = df[df > df["b"].min()] + assert expected.notna().any().any() # not vacuously all-NaN + result = df.query("@df > b.min()", engine=engine, parser=parser) + tm.assert_frame_equal(result, expected) + + def test_query_duplicate_index_label(self, engine, parser): + # GH#51815 aligning the terms against a frame whose index has duplicate + # labels raised "cannot reindex on an axis with duplicate labels" + df = pd.Series([1, 2, 3], index=[1, 1, 2], name="col").to_frame() + + result = df.query("(index == 1) & (col == 2)", engine=engine, parser=parser) + + expected = pd.DataFrame({"col": [2]}, index=[1]) + tm.assert_frame_equal(result, expected) + + def test_query_datetime_compared_to_string_no_warning(self, engine, parser): + # GH#57028 comparing a datetime64 column to a string warned about the + # behavior of 'isin', which the expression does not use. + # Comparing against a string literal is rewritten to a membership op, + # which the python parser does not implement. + skip_if_no_pandas_parser(parser) + df = pd.DataFrame({"sent": [pd.Timestamp("2024-01-14"), pd.NaT, pd.NaT]}) + + with tm.assert_produces_warning(None): + result = df.query("sent == ''", engine=engine, parser=parser) + + tm.assert_frame_equal(result, df.iloc[:0]) + + def test_query_datetime_in_strings_no_warning(self, engine, parser): + # GH#57028 the `in` operator does go through isin, and strings no longer + # match datetime64 values there, but neither should warn + skip_if_no_pandas_parser(parser) + df = pd.DataFrame({"sent": [pd.Timestamp("2024-01-14"), pd.NaT, pd.NaT]}) + + with tm.assert_produces_warning(None): + result = df.query("sent in ['2024-01-14']", engine=engine, parser=parser) + + tm.assert_frame_equal(result, df.iloc[:0]) + + def test_eval_duplicate_column_name(self, engine, parser): + # GH#65588 + df = pd.DataFrame({"a": range(3), "b": range(10, 13), "c": range(3)}).rename( + columns={"b": "a"} + ) + + result_frame = df.eval("a == 1", engine=engine, parser=parser) + result_func = pd.eval("a == 1", resolvers=(df,), engine=engine, parser=parser) + + expected = pd.DataFrame( + [[False, False], [True, False], [False, False]], + columns=["a", "a"], + ) + + tm.assert_frame_equal(result_frame, expected) + tm.assert_frame_equal(result_func, expected) + + def test_eval_resolvers_as_list(self): + # GH 14095 + df = pd.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 = pd.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 = pd.DataFrame({"a1": ["Y", "N"]}) + res = df.eval("c = ((a1 == 'Y') & True)") + expected = pd.DataFrame({"a1": ["Y", "N"], "c": [True, False]}) + tm.assert_frame_equal(res, expected) + + def test_using_numpy(self, engine, parser): + # GH 58041 + skip_if_no_pandas_parser(parser) + df = pd.Series([0.2, 1.5, 2.8], name="a").to_frame() + res = df.eval("@np.floor(a)", engine=engine, parser=parser) + expected = np.floor(df["a"]) + tm.assert_series_equal(expected, res) + + def test_using_local_function_with_scalar_arg(self, engine, parser): + # GH#22649 the bare-name branch of visit_Call; test_using_numpy covers + # the same fix through the attribute branch + skip_if_no_pandas_parser(parser) + around = np.around # noqa: F841 + df = pd.Series([1.12, 2.76], name="a").to_frame() + result = df.eval("@around(a, 1)", engine=engine, parser=parser) + expected = np.around(df["a"], 1) + tm.assert_series_equal(result, expected) + + def test_eval_simple(self, engine, parser): + df = pd.Series([0.2, 1.5, 2.8], name="a").to_frame() + res = df.eval("a", engine=engine, parser=parser) + expected = df["a"] + tm.assert_series_equal(expected, res) + + def test_extension_array_eval(self, engine, parser, request): + # GH#58748 + if engine == "numexpr": + mark = pytest.mark.xfail( + reason="numexpr does not support extension array dtypes" + ) + request.applymarker(mark) + df = pd.DataFrame({"a": pd.array([1, 2, 3]), "b": pd.array([4, 5, 6])}) + result = df.eval("a / b", engine=engine, parser=parser) + expected = pd.Series(pd.array([0.25, 0.40, 0.50])) + tm.assert_series_equal(result, expected) + + def test_complex_eval(self, engine, parser): + # GH#21374 + df = pd.DataFrame({"a": [1 + 2j], "b": [1 + 1j]}) + result = df.eval("a/b", engine=engine, parser=parser) + expected = pd.Series([1.5 + 0.5j]) + tm.assert_series_equal(result, expected) + + def test_query_period_dtype(self, engine, parser): + # GH#35247 + df = pd.DataFrame( + { + "year": pd.period_range("2018", periods=5, freq="Y"), + "val": range(5), + } + ) + result = df.query("year > '2020'", engine=engine, parser=parser) + expected = df[df["year"] > "2020"] + tm.assert_frame_equal(result, expected) + + def test_query_interval_dtype(self, engine, parser): + # GH#35247 + idx = pd.IntervalIndex.from_breaks(range(6)) + df = pd.DataFrame({"a": idx, "b": idx}) + result = df.query("a == b", engine=engine, parser=parser) + tm.assert_frame_equal(result, df) + + +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 = pd.MultiIndex.from_arrays([a, b], names=["color", "food"]) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 2)), index=index + ) + ind = pd.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 = pd.MultiIndex.from_arrays([a, b]) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 2)), index=index + ) + ind = pd.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 = pd.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 = pd.MultiIndex.from_arrays([a, b]) + index.names = [None, "rating"] + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 2)), index=index + ) + res = df.query("rating == 1", parser=parser, engine=engine) + ind = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame( + np.ones((10, 3)), + index=pd.MultiIndex.from_arrays( + [range(10) for _ in range(2)], 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"), + "clevel_0": col_series, + } + for k, v in resolvers.items(): + if isinstance(v, pd.Index): + assert v.is_(expected[k]) + elif isinstance(v, pd.Series): + tm.assert_series_equal(v, expected[k]) + else: + raise AssertionError("object must be a Series or Index") + + +class TestDataFrameQueryNumExprPandas: + @pytest.fixture + def engine(self): + skip_if_no_numexpr_fixture() + 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 = pd.DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + df["dates1"] = pd.date_range("1/1/2012", periods=5) + df["dates2"] = pd.date_range("1/1/2013", periods=5) + df["dates3"] = pd.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 = pd.DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + df["dates1"] = pd.date_range("1/1/2012", periods=5) + df["dates2"] = pd.date_range("1/1/2013", periods=5) + df["dates3"] = pd.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 = pd.DataFrame(np.random.default_rng(2).standard_normal((n, 3))) + df["dates1"] = pd.date_range("1/1/2012", periods=n) + df["dates2"] = pd.date_range("1/1/2013", periods=n) + df["dates3"] = pd.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 = pd.DataFrame(np.random.default_rng(2).standard_normal((n, 3))) + df["dates1"] = pd.date_range("1/1/2012", periods=n) + df["dates3"] = pd.date_range("1/1/2014", periods=n) + df = df.set_index("dates1") + 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 = pd.DataFrame(np.random.default_rng(2).standard_normal((n, 3))).astype( + {0: object} + ) + df["dates1"] = pd.date_range("1/1/2012", periods=n) + df["dates3"] = pd.date_range("1/1/2014", periods=n) + df.iloc[0, 0] = pd.NaT + df = df.set_index("dates1") + 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"] = pd.date_range("1/1/2012", periods=n) + d["dates3"] = pd.date_range("1/1/2014", periods=n) + df = pd.DataFrame(d) + df.loc[np.random.default_rng(2).random(n) > 0.5, "dates1"] = pd.NaT + df = df.set_index("dates1") + 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 = pd.DataFrame( + { + "dates": pd.date_range("1/1/2012", periods=n, unit="ns"), + "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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame( + np.random.default_rng(2).integers(10, size=(10, 3)), + index=pd.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 = pd.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 = pd.DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + df2 = pd.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 = pd.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 = pd.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 = pd.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 = pd.Series(np.random.default_rng(2).integers(3, size=15), name="a") + b = pd.Series(np.random.default_rng(2).integers(10, size=15), name="b") + df = pd.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 = pd.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 = pd.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): + skip_if_no_pandas_parser(parser) + + df = pd.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 = pd.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 = pd.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 = pd.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 = pd.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, engine, parser): + # https://github.com/pandas-dev/pandas/issues/29463 + tz = tz_aware_fixture + df_index = pd.date_range( + start="2019-01-01", freq="1D", periods=10, tz=tz, name="time" + ) + expected = pd.DataFrame(index=df_index) + df = pd.DataFrame(index=df_index) + result = df.query( + '"2018-01-03 00:00:00+00" < time', engine=engine, parser=parser + ) + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame(df_index) + result = df.reset_index().query( + '"2018-01-03 00:00:00+00" < time', engine=engine, parser=parser + ) + 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 = pd.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 = pd.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) + + +class TestDataFrameQueryNumExprPython(TestDataFrameQueryNumExprPandas): + @pytest.fixture + def engine(self): + skip_if_no_numexpr_fixture() + return "numexpr" + + @pytest.fixture + def parser(self): + return "python" + + def test_date_query_no_attribute_access(self, engine, parser): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + df["dates1"] = pd.date_range("1/1/2012", periods=5) + df["dates2"] = pd.date_range("1/1/2013", periods=5) + df["dates3"] = pd.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 = pd.DataFrame(np.random.default_rng(2).standard_normal((n, 3))) + df["dates1"] = pd.date_range("1/1/2012", periods=n) + df["dates2"] = pd.date_range("1/1/2013", periods=n) + df["dates3"] = pd.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 = pd.DataFrame(np.random.default_rng(2).standard_normal((n, 3))) + df["dates1"] = pd.date_range("1/1/2012", periods=n) + df["dates3"] = pd.date_range("1/1/2014", periods=n) + df = df.set_index("dates1") + 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 = pd.DataFrame(np.random.default_rng(2).standard_normal((n, 3))).astype( + {0: object} + ) + df["dates1"] = pd.date_range("1/1/2012", periods=n) + df["dates3"] = pd.date_range("1/1/2014", periods=n) + df.iloc[0, 0] = pd.NaT + df = df.set_index("dates1") + 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 = pd.DataFrame(np.random.default_rng(2).standard_normal((n, 3))) + df["dates1"] = pd.date_range("1/1/2012", periods=n) + df["dates3"] = pd.date_range("1/1/2014", periods=n) + df.loc[np.random.default_rng(2).random(n) > 0.5, "dates1"] = pd.NaT + df = df.set_index("dates1") + 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 = pd.DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + df2 = pd.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) + + @skip_if_no_numexpr + def test_query_numexpr_with_min_and_max_columns(self): + df = pd.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 = pd.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 = pd.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_query_ordered_categorical_comparison(self, parser, engine): + # GH#15186 comparing an ordered categorical column against a scalar + # string in .query should work for all engines/parsers + bands = [f"{i}AM" for i in range(10)] + df = pd.DataFrame({"Time": bands}) + df["Time"] = df["Time"].astype(pd.CategoricalDtype(bands, ordered=True)) + result = df.query("Time >= '5AM'", parser=parser, engine=engine) + expected = df[df["Time"] >= "5AM"] + tm.assert_frame_equal(result, expected) + + def test_str_query_method(self, parser, engine): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 1)), columns=["b"] + ) + df["strings"] = pd.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 lh, op_, rh in zip(lhs, ops, rhs, strict=True): + ex = f"{lh} {op_} {rh}" + 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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 1)), columns=["b"] + ) + df["strings"] = pd.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 lh, ops_, rh in zip(lhs, ops, rhs, strict=True): + ex = f"{lh} {ops_} {rh}" + 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_str_accessor_method(self, parser, engine): + # GH#26549 + df = pd.DataFrame({"colA": list("0123456789")}) + + result = df.query('colA.str.contains("0")', engine=engine, parser=parser) + + tm.assert_frame_equal(result, df[df["colA"].str.contains("0")]) + + def test_query_str_contains_word_boundary(self, parser, engine): + # GH#32589 was a non-raw outer string, not a pandas bug; this pins that + # _preparse leaves a backslash escape inside a string literal alone + df = pd.DataFrame({"A": ["A test case", "Another Testing Case"]}) + pat = r"\btest\b" + + result = df.query( + f"A.str.contains(r'{pat}', regex=True, case=False)", + engine=engine, + parser=parser, + ) + + expected = df[df["A"].str.contains(pat, regex=True, case=False)] + tm.assert_frame_equal(result, expected) + + def test_query_str_slice_negative_index(self, parser, engine): + # GH#49905 visit_Call's unary argument, as in + # test_eval.py::test_unary_in_function; the a.str[-1:] spelling in the + # same issue is test_eval.py::test_slice_subscript_with_unary_bound + df = pd.DataFrame({"a": ["example", "zzz"]}) + + result = df.query( + 'a.str.slice(0, -1).str.contains("e")', engine=engine, parser=parser + ) + + expected = df[df["a"].str.slice(0, -1).str.contains("e")] + tm.assert_frame_equal(result, expected) + + def test_query_with_string_columns(self, parser, engine): + df = pd.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 = pd.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 = pd.date_range("2014-01-01 0:00:01", freq="30s", periods=6) + stamps2 = pd.date_range("2014-02-01 1:00:01", freq="30s", periods=6) + df = pd.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 = pd.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 = pd.Series(np.random.default_rng(2).choice(list("abcde"), 20)) + b = pd.Series(np.arange(a.size)) + df = pd.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 = pd.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 = pd.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 = pd.DataFrame({"a": expected}, dtype="string") + df_expected.index = df_expected.index.astype("int64") + df = pd.DataFrame({"a": in_list}, dtype="string") + df.index = pd.Index(list(df.index), dtype=df.index.dtype) + 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 pd.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 = pd.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. + """ + return pd.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], + "xy (z)": [1, 2, 3], # noqa: RUF001 + "xy (z\\uff09": [4, 5, 6], # noqa: RUF001 + "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_ints(self, df): + res = df.query("`1` == 7") + expect = df[df[1] == 7] + tm.assert_frame_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_quote(self, df): + res = df.query("`it's` > `that's`") + expect = df[df["it's"] > df["that's"]] + tm.assert_frame_equal(res, expect) + + def test_character_outside_range_smiley(self, df): + res = df.query("`☺` > 4") + expect = df[df["☺"] > 4] + tm.assert_frame_equal(res, expect) + + def test_character_outside_range_2_byte_parens(self, df): + # GH 49633 + res = df.query("`xy (z)` == 2") # noqa: RUF001 + expect = df[df["xy (z)"] == 2] # noqa: RUF001 + tm.assert_frame_equal(res, expect) + + def test_character_outside_range_and_actual_backslash(self, df): + # GH 49633 + res = df.query("`xy (z\\uff09` == 2") # noqa: RUF001 + expect = df[df["xy \uff08z\\uff09"] == 2] + tm.assert_frame_equal(res, expect) + + def test_hashtag(self, df): + res = df.query("`foo#bar` > 4") + expect = df[df["foo#bar"] > 4] + tm.assert_frame_equal(res, expect) + + def test_expr_with_column_name_with_hashtag_character(self): + # GH 59285 + df = pd.DataFrame((1, 2, 3), columns=["a#"]) + result = df.query("`a#` < 2") + expected = df[df["a#"] < 2] + tm.assert_frame_equal(result, expected) + + def test_expr_with_comment(self): + # GH 59285 + df = pd.DataFrame((1, 2, 3), columns=["a#"]) + result = df.query("`a#` < 2 # This is a comment") + expected = df[df["a#"] < 2] + tm.assert_frame_equal(result, expected) + + def test_expr_with_column_name_with_backtick_and_hash(self): + # GH 59285 + df = pd.DataFrame((1, 2, 3), columns=["a`#b"]) + result = df.query("`a``#b` < 2") + expected = df[df["a`#b"] < 2] + tm.assert_frame_equal(result, expected) + + def test_expr_with_column_name_with_backtick(self): + # GH 59285 + df = pd.DataFrame({"a`b": (1, 2, 3), "ab": (4, 5, 6)}) + result = df.query("`a``b` < 2") + # Note: Formatting checks may wrongly consider the above ``inline code``. + expected = df[df["a`b"] < 2] + tm.assert_frame_equal(result, expected) + + def test_expr_with_string_with_backticks(self): + # GH 59285 + df = pd.DataFrame(("`", "`````", "``````````"), columns=["#backticks"]) + result = df.query("'```' < `#backticks`") + expected = df["```" < df["#backticks"]] + tm.assert_frame_equal(result, expected) + + def test_expr_with_string_with_backticked_substring_same_as_column_name(self): + # GH 59285 + df = pd.DataFrame(("`", "`````", "``````````"), columns=["#backticks"]) + result = df.query("'`#backticks`' < `#backticks`") + expected = df["`#backticks`" < df["#backticks"]] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "col1,col2,expr", + [ + ("it's", "that's", "`it's` < `that's`"), + ('it"s', 'that"s', '`it"s` < `that"s`'), + ("it's", 'that\'s "nice"', "`it's` < `that's \"nice\"`"), + ("it's", "that's #cool", "`it's` < `that's #cool` # This is a comment"), + ], + ) + def test_expr_with_column_names_with_special_characters(self, col1, col2, expr): + # GH 59285 + df = pd.DataFrame( + [ + {col1: 1, col2: 2}, + {col1: 3, col2: 4}, + {col1: -1, col2: -2}, + {col1: -3, col2: -4}, + ] + ) + result = df.query(expr) + expected = df[df[col1] < df[col2]] + tm.assert_frame_equal(result, expected) + + def test_expr_with_no_backticks(self): + # GH 59285 + df = pd.DataFrame(("aaa", "vvv", "zzz"), columns=["column_name"]) + result = df.query("'value' < column_name") + expected = df["value" < df["column_name"]] + tm.assert_frame_equal(result, expected) + + def test_expr_with_no_quotes_and_backtick_is_unmatched(self): + # GH 59285 + df = pd.DataFrame((1, 5, 10), columns=["column-name"]) + with pytest.raises((SyntaxError, TokenError), match="invalid syntax"): + df.query("5 < `column-name") + + def test_expr_with_no_quotes_and_backtick_is_matched(self): + # GH 59285 + df = pd.DataFrame((1, 5, 10), columns=["column-name"]) + result = df.query("5 < `column-name`") + expected = df[5 < df["column-name"]] + tm.assert_frame_equal(result, expected) + + def test_expr_with_backtick_opened_before_quote_and_backtick_is_unmatched(self): + # GH 59285 + df = pd.DataFrame((1, 5, 10), columns=["It's"]) + with pytest.raises( + (SyntaxError, TokenError), match="unterminated string literal" + ): + df.query("5 < `It's") + + def test_expr_with_backtick_opened_before_quote_and_backtick_is_matched(self): + # GH 59285 + df = pd.DataFrame((1, 5, 10), columns=["It's"]) + result = df.query("5 < `It's`") + expected = df[5 < df["It's"]] + tm.assert_frame_equal(result, expected) + + def test_expr_with_quote_opened_before_backtick_and_quote_is_unmatched(self): + # GH 59285 + df = pd.DataFrame(("aaa", "vvv", "zzz"), columns=["column-name"]) + with pytest.raises( + (SyntaxError, TokenError), match="unterminated string literal" + ): + df.query("`column-name` < 'It`s that\\'s \"quote\" #hash") + + def test_expr_with_quote_opened_before_backtick_and_quote_is_matched_at_end(self): + # GH 59285 + df = pd.DataFrame(("aaa", "vvv", "zzz"), columns=["column-name"]) + result = df.query("`column-name` < 'It`s that\\'s \"quote\" #hash'") + expected = df[df["column-name"] < 'It`s that\'s "quote" #hash'] + tm.assert_frame_equal(result, expected) + + def test_expr_with_quote_opened_before_backtick_and_quote_is_matched_in_mid(self): + # GH 59285 + df = pd.DataFrame(("aaa", "vvv", "zzz"), columns=["column-name"]) + result = df.query("'It`s that\\'s \"quote\" #hash' < `column-name`") + expected = df['It`s that\'s "quote" #hash' < df["column-name"]] + tm.assert_frame_equal(result, expected) + + 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 = pd.DataFrame( + [[1, 2], [3, 4]], columns=["a", "b"], dtype=any_numeric_ea_and_arrow_dtype + ) + warning = RuntimeWarning if NUMEXPR_INSTALLED else None + msg = ( + "Engine has switched to 'python' because numexpr does not " + "support extension array dtypes. Please set your engine " + "to python manually." + ) + with tm.assert_produces_warning(warning, match=msg): + result = df.eval("c = b - a") + expected = pd.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 = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"], dtype="Float64") + warning = RuntimeWarning if NUMEXPR_INSTALLED else None + msg = ( + "Engine has switched to 'python' because numexpr does not " + "support extension array dtypes. Please set your engine " + "to python manually." + ) + with tm.assert_produces_warning(warning, match=msg): + result = df.eval("c = b - 1") + expected = pd.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 = pd.DataFrame( + [[1, 2], [3, 4]], columns=["a", "b"], dtype=any_numeric_ea_and_arrow_dtype + ) + result = df.eval("c = 2 - 1") + expected = pd.DataFrame( + { + "a": pd.Series([1, 3], dtype=any_numeric_ea_and_arrow_dtype), + "b": pd.Series([2, 4], dtype=any_numeric_ea_and_arrow_dtype), + "c": pd.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 = pd.DataFrame({"a": [1, 2]}, dtype=dtype) + ref = {2} # noqa: F841 + warning = RuntimeWarning if dtype == "Int64" and NUMEXPR_INSTALLED else None + msg = ( + "Engine has switched to 'python' because numexpr does not " + "support extension array dtypes. Please set your engine " + "to python manually." + ) + with tm.assert_produces_warning(warning, match=msg): + result = df.query("a in @ref") + expected = pd.DataFrame({"a": [2]}, index=range(1, 2), dtype=dtype) + tm.assert_frame_equal(result, expected) + + def test_query_ea_dtype_scalar_comparison(self, any_numeric_ea_and_arrow_dtype): + # GH#25369 + df = pd.DataFrame( + {"col_test": [4, None, 6]}, dtype=any_numeric_ea_and_arrow_dtype + ) + warning = RuntimeWarning if NUMEXPR_INSTALLED else None + msg = ( + "Engine has switched to 'python' because numexpr does not " + "support extension array dtypes. Please set your engine " + "to python manually." + ) + with tm.assert_produces_warning(warning, match=msg): + result = df.query("col_test != 6") + + tm.assert_frame_equal(result, df.iloc[:1]) + + @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 = pd.DataFrame( + { + "A": pd.Series([1, 1, 2], dtype="Int64"), + "B": pd.Series([1, 2, 2], dtype=dtype), + } + ) + msg = ( + "Engine has switched to 'python' because numexpr does not " + "support extension array dtypes. Please set your engine " + "to python manually." + ) + with tm.assert_produces_warning(warning, match=msg): + result = df.query("A == B", engine=engine) + expected = pd.DataFrame( + { + "A": pd.Series([1, 2], dtype="Int64", index=range(0, 4, 2)), + "B": pd.Series([1, 2], dtype=dtype, index=range(0, 4, 2)), + } + ) + tm.assert_frame_equal(result, expected) + + def test_all_nat_in_object(self): + # GH#57068 + now = pd.Timestamp("2011-01-01", tz="UTC") # noqa: F841 + df = pd.DataFrame({"a": pd.to_datetime([None, None], utc=True)}, dtype=object) + result = df.query("a > @now") + expected = pd.DataFrame({"a": []}, dtype=object) + tm.assert_frame_equal(result, expected) + + +class TestDataFrameQueryInWithColumnRefs: + # GH#65357 - df.query('col in (col1, col2)') with column references. + + @pytest.fixture(autouse=True) + def skip_if_no_pandas_parser(self, parser): + if parser != "pandas": + pytest.skip(f"cannot evaluate with parser={parser}") + + def test_in_column_refs_numeric_first_row(self, engine, parser): + df = pd.DataFrame({"a": [1, 2, 3], "b": [1, 4, 9], "c": [1, 8, 27]}) + result = df.query("b in (a, c)", engine=engine, parser=parser) + expected = df[(df["b"] == df["a"]) | (df["b"] == df["c"])] + tm.assert_frame_equal(result, expected) + + def test_in_column_refs_numeric_all_rows(self, engine, parser): + df = pd.DataFrame({"a": [1, 2, 3], "b": [1, 2, 3], "c": [10, 20, 30]}) + result = df.query("b in (a, c)", engine=engine, parser=parser) + expected = df + tm.assert_frame_equal(result, expected) + + def test_in_column_refs_numeric_no_match(self, engine, parser): + df = pd.DataFrame({"a": [1, 2, 3], "b": [5, 6, 7], "c": [10, 20, 30]}) + result = df.query("b in (a, c)", engine=engine, parser=parser) + expected = df.iloc[:0] + tm.assert_frame_equal(result, expected) + + def test_in_column_refs_string(self, engine, parser): + df = pd.DataFrame( + {"a": ["a", "a", "b"], "b": ["a", "b", "c"], "c": ["b", "b", "c"]} + ) + result = df.query("b in (a, c)", engine=engine, parser=parser) + expected = df[(df["b"] == df["a"]) | (df["b"] == df["c"])] + tm.assert_frame_equal(result, expected) + + @td.skip_if_no("pyarrow") + def test_in_column_refs_string_pyarrow(self, engine, parser): + df = pd.DataFrame( + {"a": ["a", "a", "b"], "b": ["a", "b", "c"], "c": ["b", "b", "c"]}, + dtype="string[pyarrow]", + ) + + warning = RuntimeWarning if engine == "numexpr" else None + msg = ( + "Engine has switched to 'python' because numexpr does not " + "support extension array dtypes. Please set your engine " + "to python manually." + ) + with tm.assert_produces_warning(warning, match=msg): + result = df.query("b in (a, c)", engine=engine, parser=parser) + + expected = df[(df["b"] == df["a"]) | (df["b"] == df["c"])] + tm.assert_frame_equal(result, expected) + + def test_not_in_column_refs_numeric(self, engine, parser): + df = pd.DataFrame({"a": [1, 2, 3], "b": [1, 4, 9], "c": [1, 8, 27]}) + result = df.query("b not in (a, c)", engine=engine, parser=parser) + expected = df[(df["b"] != df["a"]) & (df["b"] != df["c"])] + tm.assert_frame_equal(result, expected) + + def test_not_in_column_refs_string(self, engine, parser): + df = pd.DataFrame( + {"a": ["x", "y", "z"], "b": ["a", "y", "z"], "c": ["b", "b", "c"]} + ) + result = df.query("b not in (a, c)", engine=engine, parser=parser) + expected = df[(df["b"] != df["a"]) & (df["b"] != df["c"])] + tm.assert_frame_equal(result, expected) + + def test_in_column_ref_and_literal(self, engine, parser): + df = pd.DataFrame({"a": [1, 2, 3], "b": [1, 99, 5]}) + result = df.query("b in (a, 99)", engine=engine, parser=parser) + expected = df[(df["b"] == df["a"]) | (df["b"] == 99)] + tm.assert_frame_equal(result, expected) + + def test_in_pure_literals(self, engine, parser): + df = pd.DataFrame({"a": [1, 2, 3, 4]}) + result = df.query("a in (2, 3)", engine=engine, parser=parser) + expected = df[df["a"].isin([2, 3])] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "dtype, values", + [ + ("datetime64[ns]", ["2020-01-01", "2020-01-02"]), + ("timedelta64[ns]", ["5 days", "3 days"]), + ("period[D]", ["2020-01-01", "2020-01-02"]), + ], +) +@pytest.mark.xfail( + reason="GH#23420, GH#35595 _rewrite_membership_op turns == into isin, " + "which does not parse the string" +) +def test_query_datetimelike_eq_string(dtype, values, engine, parser): + skip_if_no_pandas_parser(parser) + df = pd.DataFrame({"a": pd.array(values, dtype=dtype)}) + + result = df.query(f'a == "{values[0]}"', engine=engine, parser=parser) + + tm.assert_frame_equal(result, df.iloc[[0]]) + + +@pytest.mark.parametrize( + "op, func", + [("<", operator.lt), ("<=", operator.le), (">", operator.gt), (">=", operator.ge)], +) +def test_query_timedelta_compared_to_string(op, func, engine, parser): + # GH#23420 the ordered comparisons raised ValueError on timedelta; + # == is still wrong, see test_query_datetimelike_eq_string + df = pd.DataFrame({"dt": pd.to_timedelta(["5 days", "3 days"])}) + + result = df.query(f'dt {op} "4 days"', engine=engine, parser=parser) + + expected = df[func(df["dt"], pd.Timedelta("4 days"))] + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_reductions.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_reductions.py new file mode 100644 index 0000000000000000000000000000000000000000..c8965fa64eee9968a4e4fb2ee2b2e8c442f56bd2 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_reductions.py @@ -0,0 +1,3335 @@ +from datetime import ( + date, + 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.errors import Pandas4Warning +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm +from pandas.core import ( + algorithms, + nanops, +) +from pandas.tests.extension.decimal import DecimalArray + +is_windows_np2_or_is32 = not IS64 +is_windows_or_is32 = is_platform_windows() or not IS64 + + +def _make_2d_ea_df(col_arrays, col_names): + """ + Construct a DataFrame with a single 2D ExtensionArray block. + + Used for dt64tz and period types which support 2D blocks but don't + consolidate automatically. + """ + ea_type = type(col_arrays[0]) + ea_2d = ea_type._simple_new( + np.stack([arr._ndarray for arr in col_arrays]), + dtype=col_arrays[0].dtype, + ) + return pd.DataFrame(ea_2d.T, columns=col_names) + + +def make_skipna_wrapper(alternative, skipna_alternative=None): + """ + Create a function for calling on an array. + + Parameters + ---------- + alternative : function + The function to be called on the array with no NaNs. + Only used when 'skipna_alternative' is None. + skipna_alternative : function + The function to be called on the original array + + Returns + ------- + function + """ + if skipna_alternative: + + def skipna_wrapper(x): + return skipna_alternative(x.values) + + else: + + def skipna_wrapper(x): + nona = x.dropna() + if len(nona) == 0: + return np.nan + return alternative(nona) + + return skipna_wrapper + + +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 "skipna" + 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 = pd.DataFrame({"b": pd.date_range("1/1/2001", periods=2)}) + with tm.assert_produces_warning(None): + result = getattr(df, opname)() + assert isinstance(result, pd.Series) + + df["a"] = range(len(df)) + with tm.assert_produces_warning(None): + result = getattr(df, opname)() + assert isinstance(result, pd.Series) + assert len(result) + + if has_skipna: + + def wrapper(x): + return alternative(x.values) + + skipna_wrapper = 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 = pd.Series(unit, index=r0.index, dtype=r0.dtype) + tm.assert_series_equal(r0, expected) + expected = pd.Series(unit, index=r1.index, dtype=r1.dtype) + tm.assert_series_equal(r1, expected) + + +@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 + """ + df = pd.DataFrame( + np.concatenate( + [np.ones((15, 4), dtype=bool), np.zeros((15, 4), dtype=bool)], axis=0 + ), + index=pd.Index([f"foo_{i}" for i in range(30)], dtype=object), + columns=pd.Index(list("ABCD"), dtype=object), + dtype=object, + ) + # set some NAs + df.iloc[5:10] = np.nan + df.iloc[15:20, -2:] = np.nan + return df + + +@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 + """ + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + index=pd.Index([f"foo_{i}" for i in range(30)], dtype=object), + columns=pd.Index(list("ABCD"), dtype=object), + ) + # set some NAs + df.iloc[5:10] = np.nan + df.iloc[15:20, -2:] = np.nan + return df + + +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 ["mean", "median", "var", "std", "sem", "skew", "kurt"]: + # GH#66302 every statistic rejects the string column the same way + msg = "Could not convert 'bar' to numeric" + 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 in ["min", "max"]: + msg = "'[><]=' not supported between instances of 'float' and 'str'" + msg = "|".join([msg, "does not support", "Cannot perform reduction"]) + 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 pd.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 pd.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", + [ + pd.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", + ), + pd.DataFrame( + {0: [np.nan, 2], 1: [np.nan, 3], 2: [np.nan, 4]}, dtype=object + ), + ], + ) + 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 = pd.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", + "does not support", + "Cannot perform", + ] + ) + with pytest.raises(TypeError, match=msg): + getattr(df, op)() + + with pd.option_context("use_bottleneck", False): + with pytest.raises(TypeError, match=msg): + getattr(df, op)() + + def test_reduce_mixed_frame(self): + # GH 6806 + df = pd.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 = pd.DataFrame({"A": [1, 1, 1], "B": [1, 2, 3], "C": [1, np.nan, 3]}) + tm.assert_series_equal(df.nunique(), pd.Series({"A": 1, "B": 3, "C": 2})) + tm.assert_series_equal( + df.nunique(dropna=False), pd.Series({"A": 1, "B": 3, "C": 3}) + ) + tm.assert_series_equal(df.nunique(axis=1), pd.Series([1, 2, 2])) + tm.assert_series_equal(df.nunique(axis=1, dropna=False), pd.Series([1, 3, 2])) + + @pytest.mark.parametrize("tz", [None, "UTC"]) + def test_mean_mixed_datetime_numeric(self, tz): + # https://github.com/pandas-dev/pandas/issues/24752 + df = pd.DataFrame({"A": [1, 1], "B": [pd.Timestamp("2000", tz=tz)] * 2}) + result = df.mean() + expected = pd.Series([1.0, pd.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 = pd.DataFrame({"A": [pd.Timestamp("2000", tz=tz)] * 2}) + result = df.mean() + + expected = pd.Series([pd.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 = pd.DataFrame(d) + + with pytest.raises( + TypeError, + match="|".join( + [ + "unsupported operand type", + "does not support", + "Cannot perform", + "Could not convert", + ] + ), + ): + df.mean() + result = df[["A", "C"]].mean() + expected = pd.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", "mean", "median", "skew"]) + def test_numeric_only_flag(self, meth): + # GH 9201 + df1 = pd.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 = pd.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) + + # GH#66302 a numeric string is no more acceptable than any other string + msg = "Could not convert '100' to numeric" + with pytest.raises(TypeError, match=msg): + getattr(df1, meth)(axis=1, numeric_only=False) + msg = "Could not convert 'a' to numeric" + 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": pd.Categorical(["a"], categories=["a"]), + "F": pd.DatetimeIndex(["2000-01-02"], dtype="M8[ns]"), + "G": pd.to_timedelta(["1 days"]), + }, + ), + ( + False, + { + "A": [12], + "B": [10.0], + "C": [np.nan], + "D": pd.Series([np.nan], dtype="str"), + "E": pd.Categorical([np.nan], categories=["a"]), + "F": pd.DatetimeIndex([pd.NaT], dtype="M8[ns]"), + "G": pd.to_timedelta([pd.NaT]).as_unit("us"), + }, + ), + ( + True, + { + "H": [8, 9, np.nan, np.nan], + "I": [8, 9, np.nan, np.nan], + "J": [1, np.nan, np.nan, np.nan], + "K": pd.Categorical( + ["a", np.nan, np.nan, np.nan], categories=["a"] + ), + "L": pd.DatetimeIndex( + ["2000-01-02", "NaT", "NaT", "NaT"], dtype="M8[ns]" + ), + "M": pd.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": pd.Categorical( + [np.nan, "a", np.nan, np.nan], categories=["a"] + ), + "L": pd.DatetimeIndex( + ["NaT", "2000-01-02", "NaT", "NaT"], dtype="M8[ns]" + ), + "M": pd.to_timedelta(["nan", "1 days", "nan", "nan"]), + "N": [0, 1, 2, 3], + }, + ), + ], + ) + def test_mode_dropna(self, dropna, expected): + df = pd.DataFrame( + { + "A": [12, 12, 19, 11], + "B": [10, 10, np.nan, 3], + "C": [1, np.nan, np.nan, np.nan], + "D": pd.Series([np.nan, np.nan, "a", np.nan], dtype="str"), + "E": pd.Categorical([np.nan, np.nan, "a", np.nan]), + "F": pd.DatetimeIndex( + ["NaT", "2000-01-02", "NaT", "NaT"], dtype="M8[ns]" + ), + "G": pd.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": pd.Categorical(["a", np.nan, "a", np.nan]), + "L": pd.DatetimeIndex( + ["2000-01-02", "2000-01-02", "NaT", "NaT"], dtype="M8[ns]" + ), + "M": pd.to_timedelta(["1 days", "nan", "1 days", "nan"]), + "N": np.arange(4, dtype="int64"), + } + ) + + result = df[sorted(expected.keys())].mode(dropna=dropna) + expected = pd.DataFrame(expected) + tm.assert_frame_equal(result, expected) + + def test_mode_sort_with_na(self, using_infer_string): + df = pd.DataFrame({"A": [np.nan, np.nan, "a", "a"]}) + expected = pd.DataFrame({"A": ["a", np.nan]}) + result = df.mode(dropna=False) + tm.assert_frame_equal(result, expected) + + def test_mode_empty_df(self): + df = pd.DataFrame([], columns=["a", "b"]) + expected = df.copy() + result = df.mode() + tm.assert_frame_equal(result, expected) + + def test_operators_timedelta64(self): + df = pd.DataFrame( + { + "A": pd.date_range("2012-1-1", periods=3, freq="D", unit="ns"), + "B": pd.date_range("2012-1-2", periods=3, freq="D", unit="ns"), + "C": pd.Timestamp("20120101") - timedelta(minutes=5, seconds=5), + } + ) + + diffs = pd.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 = pd.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"] = pd.Timestamp("20130101") + + # results in an object array + result = mixed.min() + expected = pd.Series( + [ + pd.Timedelta(timedelta(seconds=5 * 60 + 5)), + pd.Timedelta(timedelta(days=-1)), + "foo", + 1, + 1.0, + pd.Timestamp("20130101"), + ], + index=mixed.columns, + ) + tm.assert_series_equal(result, expected) + + # excludes non-numeric + result = mixed.min(axis=1, numeric_only=True) + expected = pd.Series([1, 1, 1.0]) + tm.assert_series_equal(result, expected) + + # works when only those columns are selected + result = mixed[["A", "B"]].min(axis=1) + expected = pd.Series([timedelta(days=-1)] * 3, dtype="m8[ns]") + tm.assert_series_equal(result, expected) + + result = mixed[["A", "B"]].min() + expected = pd.Series( + [timedelta(seconds=5 * 60 + 5), timedelta(days=-1)], + index=["A", "B"], + dtype="m8[ns]", + ) + tm.assert_series_equal(result, expected) + + # GH 3106 + df = pd.DataFrame( + { + "time": pd.date_range("20130102", periods=5, unit="ns"), + "time2": pd.date_range("20130105", periods=5, unit="ns"), + } + ) + 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 = pd.DataFrame({"A": tdi, "B": tdi}, copy=True) + df.iloc[-2, -1] = pd.NaT + + result = df.std(skipna=False) + expected = pd.Series( + [df["A"].std(), pd.NaT], index=["A", "B"], dtype="timedelta64[us]" + ) + tm.assert_series_equal(result, expected) + + result = df.std(axis=1, skipna=False) + expected = pd.Series( + [pd.Timedelta(0)] * 8 + [pd.NaT, pd.Timedelta(0)], dtype="m8[us]" + ) + 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, request, unit): + # GH#51335 + dti = pd.to_datetime(values).as_unit(unit) + df = pd.DataFrame({"a": dti}) + result = df.std(skipna=skipna) + if not skipna or all(value is pd.NaT for value in values): + expected = pd.Series({"a": pd.NaT}, dtype=f"timedelta64[{unit}]") + else: + expected = pd.Series({"a": "1 days"}, dtype=f"timedelta64[{unit}]") + tm.assert_series_equal(result, expected) + + def test_sum_corner(self): + empty_frame = pd.DataFrame() + + axis0 = empty_frame.sum(axis=0) + axis1 = empty_frame.sum(axis=1) + assert isinstance(axis0, pd.Series) + assert isinstance(axis1, pd.Series) + assert len(axis0) == 0 + assert len(axis1) == 0 + + @pytest.mark.parametrize( + "index", + [ + pd.RangeIndex(0), + pd.DatetimeIndex([]), + pd.Index([], dtype=np.int64), + pd.Index([], dtype=np.float64), + pd.DatetimeIndex([], freq="ME"), + pd.PeriodIndex([], freq="D"), + ], + ) + def test_axis_1_empty(self, all_reductions, index): + df = pd.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 = pd.Series([], index=index, dtype=expected_dtype) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("min_count", [0, 1]) + def test_axis_1_sum_na(self, string_dtype_no_object, skipna, min_count): + # https://github.com/pandas-dev/pandas/issues/60229 + dtype = string_dtype_no_object + df = pd.DataFrame({"a": [pd.NA]}, dtype=dtype) + result = df.sum(axis=1, skipna=skipna, min_count=min_count) + value = "" if skipna and min_count == 0 else pd.NA + expected = pd.Series([value], dtype=dtype) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "min_count, expected", + [ + (1, [7.0, 3.0, np.nan]), + (2, [7.0, np.nan, np.nan]), + (3, [np.nan, np.nan, np.nan]), + ], + ) + def test_axis_1_sum_min_count_sparse(self, min_count, expected): + # https://github.com/pandas-dev/pandas/issues/55123 + df = pd.DataFrame({"A": [2.0, 3.0, np.nan], "B": [5.0, np.nan, np.nan]}).astype( + pd.SparseDtype("float64") + ) + result = df.sum(axis=1, skipna=True, min_count=min_count) + expected = pd.Series(expected, dtype="float64") + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("method, unit", [("sum", 0), ("prod", 1)]) + @pytest.mark.parametrize("numeric_only", [True, False]) + def test_sum_prod_nanops(self, method, unit, numeric_only): + idx = ["a", "b", "c"] + df = pd.DataFrame( + {"a": [unit, unit], "b": [unit, np.nan], "c": [np.nan, np.nan]} + ) + # The default + result = getattr(df, method)(numeric_only=numeric_only) + expected = pd.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 = pd.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 = pd.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 = pd.Series([unit, np.nan, np.nan], index=idx) + tm.assert_series_equal(result, expected) + + # min_count > 1 + df = pd.DataFrame({"A": [unit] * 10, "B": [unit] * 5 + [np.nan] * 5}) + result = getattr(df, method)(numeric_only=numeric_only, min_count=5) + expected = pd.Series(result, index=["A", "B"]) + tm.assert_series_equal(result, expected) + + result = getattr(df, method)(numeric_only=numeric_only, min_count=6) + expected = pd.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 = pd.DataFrame({"a": [0, 0], "b": [0, np.nan], "c": [np.nan, np.nan]}) + + df2 = df.apply(pd.to_timedelta) + + # 0 by default + result = df2.sum() + expected = pd.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 = pd.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 = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) + result = df.sum(min_count=10) + expected = pd.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 = pd.DataFrame( + {"a": [1.0, 2.3, 4.4], "b": [2.2, 3, np.nan]}, dtype=float_type + ) + result = df.sum(**kwargs) + # GH#43929 float16 upcasts to float64 in nansum to avoid overflow + expected = pd.Series(expected_result, dtype=float_type) + if float_type == "float16": + expected = expected.astype("float64") + 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 = pd.DataFrame( + {"a": [1.0, 2.0, 4.4], "b": [2.0, 2.0, np.nan]}, dtype=float_type + ) + result = df.prod(**kwargs) + expected = pd.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 = pd.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(axis=1) + bools.sum(axis=0) + + def test_sum_mixed_datetime(self): + # GH#30886 + df = pd.DataFrame( + {"A": pd.date_range("2000", periods=4), "B": [1, 2, 3, 4]} + ).reindex([2, 3, 4]) + with pytest.raises(TypeError, match="does not support operation 'sum'"): + df.sum() + + def test_mean_corner(self, float_frame): + # take mean of boolean column + float_frame["bool"] = float_frame["A"] > 0 + means = float_frame.mean(axis=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 = pd.DataFrame( + { + "A": np.arange(3), + "B": pd.date_range("2016-01-01", periods=3), + "C": pd.timedelta_range("1D", periods=3), + "D": pd.period_range("2016", periods=3, freq="Y"), + } + ) + result = df.mean(numeric_only=True) + expected = pd.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 = pd.DataFrame( + { + "A": np.arange(3), + "B": pd.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 = pd.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="Y") + + 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 = pd.DataFrame(arr, dtype="Int64") + result = df.mean(numeric_only=True) + expected = pd.DataFrame(arr).mean().astype("Float64") + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "meth", ["std", "var", "mean", "median", "sem", "skew", "kurt"] + ) + def test_stats_mixed_type(self, float_string_frame, meth): + msg = "Could not convert 'bar' to numeric" + with pytest.raises(TypeError, match=msg): + getattr(float_string_frame, meth)(axis=1) + + def test_sum_bools(self): + df = pd.DataFrame(index=range(1), columns=range(10)) + bools = pd.isna(df) + assert bools.sum(axis=1)[0] == 10 + + @pytest.mark.parametrize( + "input_data, expected_data", + [ + ({"a": ["483", "3"], "b": ["94", "759"]}, ["48394", "3759"]), + ( + {"a": ["483.948", "3.0"], "b": ["94.2", "759.93"]}, + ["483.94894.2", "3.0759.93"], + ), + ({"a": ["483", "3.0"], "b": ["94.2", "79"]}, ["48394.2", "3.079"]), + ], + ) + def test_sum_string_dtype_coercion(self, input_data, expected_data): + # GH#22642 + # Check that summing numeric strings results in concatenation + # and not conversion to dtype int64 or float64 + df = pd.DataFrame(input_data) + expected = pd.Series(expected_data) + result = df.sum(axis=1) + tm.assert_series_equal(result, expected) + + # ---------------------------------------------------------------------- + # Index of max / min + + @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]: + if (not skipna or axis == 1) and df is not int_frame: + if skipna: + msg = "Encountered all NA values" + else: + msg = "Encountered an NA value" + with pytest.raises(ValueError, match=msg): + df.idxmin(axis=axis, skipna=skipna) + with pytest.raises(ValueError, match=msg): + df.idxmin(axis=axis, skipna=skipna) + else: + result = df.idxmin(axis=axis, skipna=skipna) + expected = df.apply(pd.Series.idxmin, axis=axis, skipna=skipna) + expected = expected.astype(df.index.dtype) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("axis", [0, 1]) + def test_idxmin_empty(self, index, skipna, axis): + # GH53265 + if axis == 0: + frame = pd.DataFrame(index=index) + else: + frame = pd.DataFrame(columns=index) + + result = frame.idxmin(axis=axis, skipna=skipna) + expected = pd.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 = pd.DataFrame({"a": [2, 3, 1], "b": [2, 1, 1], "c": list("xyx")}) + result = df.idxmin(numeric_only=numeric_only) + if numeric_only: + expected = pd.Series([2, 1], index=["a", "b"]) + else: + expected = pd.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("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]: + if (skipna is False or axis == 1) and df is frame: + if skipna: + msg = "Encountered all NA values" + else: + msg = "Encountered an NA value" + with pytest.raises(ValueError, match=msg): + df.idxmax(axis=axis, skipna=skipna) + return + + result = df.idxmax(axis=axis, skipna=skipna) + expected = df.apply(pd.Series.idxmax, axis=axis, skipna=skipna) + expected = expected.astype(df.index.dtype) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("axis", [0, 1]) + def test_idxmax_empty(self, index, skipna, axis): + # GH53265 + if axis == 0: + frame = pd.DataFrame(index=index) + else: + frame = pd.DataFrame(columns=index) + + result = frame.idxmax(axis=axis, skipna=skipna) + expected = pd.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 = pd.DataFrame({"a": [2, 3, 1], "b": [2, 1, 1], "c": list("xyx")}) + result = df.idxmax(numeric_only=numeric_only) + if numeric_only: + expected = pd.Series([1, 0], index=["a", "b"]) + else: + expected = pd.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 = pd.DataFrame({"a": [2, 3, 1], "b": [2, 1, 1]}, dtype="int64[pyarrow]") + result = df.idxmax() + expected = pd.Series([1, 0], index=["a", "b"]) + tm.assert_series_equal(result, expected) + + result = df.idxmin() + expected = pd.Series([2, 1], index=["a", "b"]) + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"a": ["b", "c", "a"]}, dtype="string[pyarrow]") + result = df.idxmax(numeric_only=False) + expected = pd.Series([1], index=["a"]) + tm.assert_series_equal(result, expected) + + result = df.idxmin(numeric_only=False) + expected = pd.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 = pd.date_range("2016-01-01", periods=3) + df = pd.DataFrame({1: [0, 2, 1], 2: range(3)[::-1], 3: dti}) + + result = df.idxmax() + expected = pd.Series([1, 0, 2], index=range(1, 4)) + tm.assert_series_equal(result, expected) + + result = df.idxmin() + expected = pd.Series([0, 2, 0], index=range(1, 4)) + tm.assert_series_equal(result, expected) + + # with NaTs + df.loc[0, 3] = pd.NaT + result = df.idxmax() + expected = pd.Series([1, 0, 2], index=range(1, 4)) + tm.assert_series_equal(result, expected) + + result = df.idxmin() + expected = pd.Series([0, 2, 1], index=range(1, 4)) + tm.assert_series_equal(result, expected) + + # with multi-column dt64 block + df[4] = dti[::-1] + df._consolidate_inplace() + + result = df.idxmax() + expected = pd.Series([1, 0, 2, 0], index=range(1, 5)) + tm.assert_series_equal(result, expected) + + result = df.idxmin() + expected = pd.Series([0, 2, 1, 2], index=range(1, 5)) + 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 = pd.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 = pd.DataFrame( + {"value": expected_value}, + index=pd.Index([100, 200], name="ID", dtype="Int64"), + ) + tm.assert_frame_equal(result, expected) + + def test_idxmax_dt64_multicolumn_axis1(self): + dti = pd.date_range("2016-01-01", periods=3) + df = pd.DataFrame({3: dti, 4: dti[::-1]}, copy=True) + df.iloc[0, 0] = pd.NaT + + df._consolidate_inplace() + + result = df.idxmax(axis=1) + expected = pd.Series([4, 3, 3]) + tm.assert_series_equal(result, expected) + + result = df.idxmin(axis=1) + expected = pd.Series([4, 3, 4]) + tm.assert_series_equal(result, expected) + + # ---------------------------------------------------------------------- + # Logical reductions + + @pytest.mark.parametrize("axis", [0, 1]) + @pytest.mark.parametrize("bool_only", [False, True]) + def test_any_all_mixed_float( + self, all_boolean_reductions, 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, all_boolean_reductions)(axis=axis, bool_only=bool_only) + + @pytest.mark.parametrize("axis", [0, 1]) + def test_any_all_bool_with_na( + self, all_boolean_reductions, axis, bool_frame_with_na + ): + getattr(bool_frame_with_na, all_boolean_reductions)(axis=axis, bool_only=False) + + def test_any_all_bool_frame(self, all_boolean_reductions, 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, all_boolean_reductions) + f = getattr(frame, all_boolean_reductions) + + 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, all_boolean_reductions)(axis=0) + r1 = getattr(all_na, all_boolean_reductions)(axis=1) + if all_boolean_reductions == "any": + assert not r0.any() + assert not r1.any() + else: + assert r0.all() + assert r1.all() + + def test_any_all_extra(self, using_python_scalars): + df = pd.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 = pd.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(axis=1) + expected = pd.Series([True, False, False], index=["a", "b", "c"]) + tm.assert_series_equal(result, expected) + + result = df.all(axis=1, bool_only=True) + tm.assert_series_equal(result, expected) + + # Axis is None + result = df.all(axis=None) + if not using_python_scalars: + result = result.item() + assert result is False + + result = df.any(axis=None) + if not using_python_scalars: + result = result.item() + assert result is True + + result = df[["C"]].all(axis=None) + if not using_python_scalars: + result = result.item() + assert result is True + + @pytest.mark.parametrize("axis", [0, 1]) + def test_any_all_object_dtype(self, axis, all_boolean_reductions, skipna): + # GH#35450 + df = pd.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, all_boolean_reductions)(axis=axis, skipna=skipna) + expected = pd.Series([True, True, True, True]) + tm.assert_series_equal(result, expected) + + def test_any_datetime(self): + # GH 23070 + float_data = [1, np.nan, 3, np.nan] + datetime_data = [ + pd.Timestamp("1960-02-15"), + pd.Timestamp("1960-02-16"), + pd.NaT, + pd.NaT, + ] + df = pd.DataFrame({"A": float_data, "B": datetime_data}) + + msg = "'any' with datetime64 dtypes is not supported" + with pytest.raises(TypeError, match=msg): + df.any(axis=1) + + def test_any_all_bool_only(self): + # GH 25101 + df = pd.DataFrame( + {"col1": [1, 2, 3], "col2": [4, 5, 6], "col3": [None, None, None]}, + columns=pd.Index(["col1", "col2", "col3"], dtype=object), + ) + + result = df.all(bool_only=True) + expected = pd.Series(dtype=np.bool_, index=[]) + tm.assert_series_equal(result, expected) + + df = pd.DataFrame( + { + "col1": [1, 2, 3], + "col2": [4, 5, 6], + "col3": [None, None, None], + "col4": [False, False, True], + } + ) + + result = df.all(bool_only=True) + expected = pd.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": pd.Series([0.0, 1.0], dtype="float")}, False), + (np.any, {"A": pd.Series([0.0, 1.0], dtype="float")}, True), + (np.all, {"A": pd.Series([0, 1], dtype=int)}, False), + (np.any, {"A": pd.Series([0, 1], dtype=int)}, True), + pytest.param(np.all, {"A": pd.Series([0, 1], dtype="M8[ns]")}, False), + pytest.param(np.all, {"A": pd.Series([0, 1], dtype="M8[ns, UTC]")}, False), + pytest.param(np.any, {"A": pd.Series([0, 1], dtype="M8[ns]")}, True), + pytest.param(np.any, {"A": pd.Series([0, 1], dtype="M8[ns, UTC]")}, True), + pytest.param(np.all, {"A": pd.Series([1, 2], dtype="M8[ns]")}, True), + pytest.param(np.all, {"A": pd.Series([1, 2], dtype="M8[ns, UTC]")}, True), + pytest.param(np.any, {"A": pd.Series([1, 2], dtype="M8[ns]")}, True), + pytest.param(np.any, {"A": pd.Series([1, 2], dtype="M8[ns, UTC]")}, True), + pytest.param(np.all, {"A": pd.Series([0, 1], dtype="m8[ns]")}, False), + pytest.param(np.any, {"A": pd.Series([0, 1], dtype="m8[ns]")}, True), + pytest.param(np.all, {"A": pd.Series([1, 2], dtype="m8[ns]")}, True), + pytest.param(np.any, {"A": pd.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": pd.Series([0, 1], dtype="category")}, True), + (np.any, {"A": pd.Series([0, 1], dtype="category")}, False), + (np.all, {"A": pd.Series([1, 2], dtype="category")}, True), + (np.any, {"A": pd.Series([1, 2], dtype="category")}, False), + # Mix GH#21484 + pytest.param( + np.all, + { + "A": pd.Series([10, 20], dtype="M8[ns]"), + "B": pd.Series([10, 20], dtype="m8[ns]"), + }, + True, + ), + ], + ) + def test_any_all_np_func(self, func, data, expected, using_python_scalars): + # GH 19976 + data = pd.DataFrame(data) + + if any(isinstance(x, pd.CategoricalDtype) for x in data.dtypes): + with pytest.raises( + TypeError, match=".* dtype category does not support operation" + ): + func(data) + + # method version + with pytest.raises( + TypeError, match=".* dtype category does not support operation" + ): + getattr(pd.DataFrame(data), func.__name__)(axis=None) + if data.dtypes.apply(lambda x: x.kind == "M").any(): + # GH#34479 + msg = "'(any|all)' with datetime64 dtypes is not supported" + with pytest.raises(TypeError, match=msg): + func(data) + + # method version + with pytest.raises(TypeError, match=msg): + getattr(pd.DataFrame(data), func.__name__)(axis=None) + + elif data.dtypes.apply(lambda x: x != "category").any(): + result = func(data) + if using_python_scalars: + assert result is expected + else: + assert isinstance(result, np.bool_) + assert result.item() is expected + + # method version + result = getattr(pd.DataFrame(data), func.__name__)(axis=None) + if using_python_scalars: + assert result is expected + else: + assert isinstance(result, np.bool_) + assert result.item() is expected + + def test_any_all_object(self, using_python_scalars): + # GH 19976 + result = np.all(pd.DataFrame(columns=["a", "b"])) + if not using_python_scalars: + result = result.item() + assert result is True + + result = np.any(pd.DataFrame(columns=["a", "b"])) + if not using_python_scalars: + result = result.item() + assert result is False + + def test_any_all_object_bool_only(self): + df = pd.DataFrame({"A": ["foo", 2], "B": [True, False]}).astype(object) + df._consolidate_inplace() + df["C"] = pd.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 = pd.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 = pd.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) + + @pytest.mark.parametrize( + "dtype", + [ + "boolean", + "Int8", + "Int16", + "Int32", + "Int64", + "UInt8", + "UInt16", + "UInt32", + "UInt64", + "Float32", + "Float64", + ], + ) + @pytest.mark.parametrize( + "data, op, expected_value", + [ + ([False, None], "any", pd.NA), + ([True, None], "all", pd.NA), + ([None, None], "any", pd.NA), + ([None, None], "all", pd.NA), + ([True, None], "any", True), + ], + ) + def test_any_all_skipna_false_nullable(self, dtype, data, op, expected_value): + # GH#65710 + if dtype != "boolean": + data = [(0 if v is False else 1 if v is True else None) for v in data] + arr = pd.array(data, dtype=dtype) + df = pd.DataFrame({"a": arr}) + + result = getattr(df, op)(skipna=False) + expected = pd.Series([expected_value], index=["a"], dtype="boolean") + tm.assert_series_equal(result, expected) + + ser_result = getattr(pd.Series(arr), op)(skipna=False) + if expected_value is pd.NA: + assert ser_result is pd.NA + else: + assert ser_result == expected_value + + def test_any_skipna_false_axis_none_nullable(self): + # GH#65710 + df = pd.DataFrame({"a": pd.array([False, None], dtype="boolean")}) + assert df.any(skipna=False, axis=None) is pd.NA + + # --------------------------------------------------------------------- + # Unsorted + + def test_series_broadcasting(self): + # smoke test for numpy warnings + # GH 16378, GH 16306 + df = pd.DataFrame([1.0, 1.0, 1.0]) + df_nan = pd.DataFrame({"A": [np.nan, 2.0, np.nan]}) + s = pd.Series([1, 1, 1]) + s_nan = pd.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 = pd.DataFrame({"foo": [pd.NaT, pd.NaT, pd.Timestamp("2012-05-01")]}) + + res = df.min() + exp = pd.Series([pd.Timestamp("2012-05-01")], index=["foo"]) + tm.assert_series_equal(res, exp) + + res = df.max() + exp = pd.Series([pd.Timestamp("2012-05-01")], index=["foo"]) + tm.assert_series_equal(res, exp) + + # GH12941, only NaTs are in DataFrame. + df = pd.DataFrame({"foo": [pd.NaT, pd.NaT]}) + + res = df.min() + exp = pd.Series([pd.NaT], index=["foo"]) + tm.assert_series_equal(res, exp) + + res = df.max() + exp = pd.Series([pd.NaT], index=["foo"]) + tm.assert_series_equal(res, exp) + + def test_min_max_dt64_with_NaT_precision(self): + # GH#60646 Make sure the reduction doesn't cast input timestamps to + # float and lose precision. + df = pd.DataFrame( + {"foo": [pd.NaT, pd.NaT, pd.Timestamp("2012-05-01 09:20:00.123456789")]}, + dtype="datetime64[ns]", + ) + + res = df.min(axis=1) + exp = df.foo.rename(None) + tm.assert_series_equal(res, exp) + + res = df.max(axis=1) + exp = df.foo.rename(None) + tm.assert_series_equal(res, exp) + + def test_min_max_td64_with_NaT_precision(self): + # GH#60646 Make sure the reduction doesn't cast input timedeltas to + # float and lose precision. + df = pd.DataFrame( + { + "foo": [ + pd.NaT, + pd.NaT, + pd.to_timedelta("10000 days 06:05:01.123456789"), + ], + }, + dtype="timedelta64[ns]", + ) + + res = df.min(axis=1) + exp = df.foo.rename(None) + tm.assert_series_equal(res, exp) + + res = df.max(axis=1) + exp = df.foo.rename(None) + 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 = pd.DataFrame( + { + "a": [ + pd.Timestamp("2020-01-01 08:00:00", tz=tz), + pd.Timestamp("1920-02-01 09:00:00", tz=tz), + ], + "b": [pd.Timestamp("2020-02-01 08:00:00", tz=tz), pd.NaT], + } + ) + res = df.min(axis=1, skipna=False) + expected = pd.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 = pd.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 = pd.DataFrame({"x": pd.to_datetime([])}) + expected_dt_series = pd.Series(pd.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 = pd.DataFrame({"x": []}) + expected_float_series = pd.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 = pd.to_datetime(initial) + expected = pd.Series([initial_dt]) + df = pd.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 = pd.to_datetime("1900-01-01", utc=True) + df = pd.DataFrame( + {"a": pd.Series([pd.NaT, pd.NaT, val]), "b": pd.Series([pd.NaT, val, val])} + ) + op = getattr(df, method) + result = op(axis=1, skipna=skipna) + if skipna: + expected = pd.Series([pd.NaT, val, val]) + else: + expected = pd.Series([pd.NaT, pd.NaT, val]) + tm.assert_series_equal(result, expected) + + @pytest.fixture( + params=[ + pd.DataFrame( + { + "i1": np.array([1, 2, 3], dtype="int64"), + "i2": np.array([4, 5, 6], dtype="int64"), + } + ), + pd.DataFrame( + { + "f1": np.array([1.0, np.nan, 3.0], dtype="float64"), + "f2": np.array([4.0, 5.0, np.nan], dtype="float64"), + } + ), + pd.DataFrame( + { + "b1": np.array([True, False, True], dtype="bool"), + "b2": np.array([False, True, False], dtype="bool"), + } + ), + pd.DataFrame( + { + "d1": pd.to_datetime(["2020-01-01", pd.NaT, "2020-01-05"]), + "d2": pd.to_datetime(["2020-01-03", "2020-01-02", "2020-01-04"]), + } + ), + _make_2d_ea_df( + [ + pd.to_datetime(["2020-01-01", pd.NaT, "2020-01-05"]) + .as_unit("us") + .tz_localize("UTC") + ._data, + pd.to_datetime(["2020-01-03", "2020-01-02", "2020-01-04"]) + .as_unit("us") + .tz_localize("UTC") + ._data, + ], + ["dz1", "dz2"], + ), + pd.DataFrame( + { + "td1": pd.to_timedelta(["1 day", pd.NaT, "3 days"]), + "td2": pd.to_timedelta(["4 days", "5 days", pd.NaT]), + } + ), + pd.DataFrame( + { + "I1": pd.array([1, 2, pd.NA], dtype="Int64"), + "I2": pd.array([4, pd.NA, 6], dtype="Int64"), + } + ), + pd.DataFrame( + { + "F1": pd.array([1.0, pd.NA, 3.0], dtype="Float64"), + "F2": pd.array([4.0, 5.0, pd.NA], dtype="Float64"), + } + ), + pd.DataFrame( + { + "B1": pd.array([True, pd.NA, True], dtype="boolean"), + "B2": pd.array([False, True, pd.NA], dtype="boolean"), + } + ), + _make_2d_ea_df( + [ + pd.period_range("2020-01-01", periods=3, freq="D")._data, + pd.period_range("2020-01-04", periods=3, freq="D")._data, + ], + ["p1", "p2"], + ), + ], + ids=[ + "int64", + "float64", + "bool", + "dt64", + "dt64tz", + "td64", + "Int64", + "Float64", + "boolean", + "period", + ], + ) + def reduction_block_1(self, request): + return request.param + + @pytest.fixture( + params=[ + pd.DataFrame( + { + "i3": np.array([7, 8, 9], dtype="int64"), + "i4": np.array([10, 11, 12], dtype="int64"), + } + ), + pd.DataFrame( + { + "f3": np.array([7.0, 8.0, np.nan], dtype="float64"), + "f4": np.array([np.nan, 11.0, 12.0], dtype="float64"), + } + ), + pd.DataFrame( + { + "b3": np.array([True, True, False], dtype="bool"), + "b4": np.array([False, False, True], dtype="bool"), + } + ), + pd.DataFrame( + { + "d3": pd.to_datetime(["2020-02-01", "2020-02-02", pd.NaT]), + "d4": pd.to_datetime([pd.NaT, "2020-02-04", "2020-02-05"]), + } + ), + _make_2d_ea_df( + [ + pd.to_datetime(["2020-02-01", "2020-02-02", pd.NaT]) + .as_unit("us") + .tz_localize("UTC") + ._data, + pd.to_datetime([pd.NaT, "2020-02-04", "2020-02-05"]) + .as_unit("us") + .tz_localize("UTC") + ._data, + ], + ["dz3", "dz4"], + ), + pd.DataFrame( + { + "td3": pd.to_timedelta([pd.NaT, "8 days", "9 days"]), + "td4": pd.to_timedelta(["10 days", pd.NaT, "12 days"]), + } + ), + pd.DataFrame( + { + "I3": pd.array([7, pd.NA, 9], dtype="Int64"), + "I4": pd.array([pd.NA, 11, 12], dtype="Int64"), + } + ), + pd.DataFrame( + { + "F3": pd.array([pd.NA, 8.0, 9.0], dtype="Float64"), + "F4": pd.array([10.0, pd.NA, 12.0], dtype="Float64"), + } + ), + pd.DataFrame( + { + "B3": pd.array([pd.NA, True, False], dtype="boolean"), + "B4": pd.array([True, pd.NA, True], dtype="boolean"), + } + ), + _make_2d_ea_df( + [ + pd.period_range("2020-02-01", periods=3, freq="D")._data, + pd.period_range("2020-02-04", periods=3, freq="D")._data, + ], + ["p3", "p4"], + ), + ], + ids=[ + "int64", + "float64", + "bool", + "dt64", + "dt64tz", + "td64", + "Int64", + "Float64", + "boolean", + "period", + ], + ) + def reduction_block_2(self, request): + return request.param + + @pytest.mark.parametrize( + "method", ["sum", "prod", "min", "max", "mean", "any", "all"] + ) + @pytest.mark.parametrize( + "kwargs", [{}, {"min_count": 2}], ids=["default", "min_count"] + ) + def test_reduce_axis1_multiblock_exhaustive( + self, reduction_block_1, reduction_block_2, method, skipna, kwargs + ): + # GH#51474 - exhaustive test: axis=1 result must match transpose path, + # whether that is a successful result or a raised exception. + if "min_count" in kwargs and method not in ("sum", "prod"): + pytest.skip("min_count only applies to sum/prod") + + df = pd.concat([reduction_block_1, reduction_block_2], axis=1) + assert len(df._mgr.blocks) > 1 + kw = {"skipna": skipna, **kwargs} + + transpose_err = None + try: + expected = getattr(df.T, method)(**kw) + except (TypeError, ValueError, AttributeError, RuntimeWarning) as err: + transpose_err = err + + axis1_err = None + try: + result = getattr(df, method)(axis=1, **kw) + except (TypeError, ValueError, AttributeError, RuntimeWarning) as err: + axis1_err = err + + if transpose_err is not None or axis1_err is not None: + # At least one path raises — acceptable. Mixed-dtype frames + # may raise on one path (e.g. axis=1 with datetime64 + any) + # but succeed on the other (transpose coerces to object first). + return + # Compare values, treating NaN and pd.NA as equivalent. + # check_dtype=False because the transpose path may coerce to + # object (e.g. mixed int64+bool) where axis=1 preserves + # the numeric dtype. check_names=False because the transpose + # path names the result after the index. + result_na = pd.isna(result) + expected_na = pd.isna(expected) + # axis=1 may correctly propagate NAs that the transpose path + # drops (e.g. skipna=False with mixed float+bool where transpose + # coerces to a common dtype first), so only require that result + # NAs are a superset of expected NAs. + assert (result_na | ~expected_na).all(), ( + f"axis=1 missing NAs that transpose has:\n" + f"result NAs: {result_na.values}\nexpected NAs: {expected_na.values}" + ) + both_valid = ~result_na & ~expected_na + if both_valid.any(): + tm.assert_series_equal( + result[both_valid].reset_index(drop=True), + expected[both_valid].reset_index(drop=True), + check_dtype=False, + check_names=False, + ) + + @pytest.mark.parametrize( + "method", + [ + "sum", + "prod", + "min", + "max", + "mean", + "any", + "all", + "median", + "std", + "var", + "sem", + "skew", + "kurt", + ], + ) + @pytest.mark.parametrize( + "kwargs", + [{}, {"min_count": 2}, {"min_count": 5}], + ids=["default", "min_count", "min_count_high"], + ) + def test_reduce_axis1_single_block_exhaustive( + self, reduction_block_1, method, skipna, kwargs + ): + # GH#51474: single-block fastpath must match the transpose path, + # result or raised exception alike. + if "min_count" in kwargs and method not in ("sum", "prod"): + pytest.skip("min_count only applies to sum/prod") + df = reduction_block_1 + if len(df._mgr.blocks) != 1: + # 1D EA columns don't consolidate; covered by the multiblock test + pytest.skip("fixture frame is not single-block") + kw = {"skipna": skipna, **kwargs} + + transpose_err = None + expected = None + try: + expected = getattr(df.T, method)(**kw) + except (TypeError, ValueError) as err: + transpose_err = err + + if isinstance(df._mgr.blocks[0].values, np.ndarray): + # numpy block: identical computation, so match exactly incl. dtype + if transpose_err is not None: + with pytest.raises( + type(transpose_err), match=re.escape(str(transpose_err)) + ): + getattr(df, method)(axis=1, **kw) + else: + result = getattr(df, method)(axis=1, **kw) + tm.assert_series_equal(result, expected, check_names=False) + else: + # 2D EA block: paths differ; mirror the multiblock test's lax compare + axis1_err = None + result = None + try: + result = getattr(df, method)(axis=1, **kw) + except (TypeError, ValueError) as err: + axis1_err = err + if transpose_err is not None or axis1_err is not None: + return + result_na = pd.isna(result) + expected_na = pd.isna(expected) + assert (result_na == expected_na).all() + both_valid = ~result_na & ~expected_na + if both_valid.any(): + tm.assert_series_equal( + result[both_valid].reset_index(drop=True), + expected[both_valid].reset_index(drop=True), + check_dtype=False, + check_names=False, + ) + + @pytest.mark.parametrize("method", ["min", "max"]) + def test_reduce_axis1_dt64tz_with_nat(self, method): + # GH#65500: axis=1 min/max on multi-block dt64tz frames with NaT + # must skip NaT under skipna=True, matching the transpose path. + ts = pd.Timestamp("2026-01-01 15:13:44", tz="Europe/Budapest") + df = pd.DataFrame({"a": [ts, ts], "b": [ts, pd.NaT]}) + # Two separate blocks (CoW), same EA dtype. + assert len(df._mgr.blocks) == 2 + + result = getattr(df, method)(axis=1) + expected = pd.Series([ts, ts], dtype=df["a"].dtype) + tm.assert_series_equal(result, expected) + + # skipna=False propagates NaT. + result = getattr(df, method)(axis=1, skipna=False) + expected = pd.Series([ts, pd.NaT], dtype=df["a"].dtype) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("method", ["min", "max"]) + def test_reduce_axis1_single_block_dt64tz_with_nat(self, method): + # GH#51474, GH#65500: 2D EA block fastpath must skip NaT (skipna=True) + # and propagate it (skipna=False) without raising or changing dtype. + df = _make_2d_ea_df( + [ + pd.to_datetime(["2020-01-01", "2020-01-02"]) + .as_unit("us") + .tz_localize("UTC") + ._data, + pd.to_datetime(["2020-01-02", pd.NaT]) + .as_unit("us") + .tz_localize("UTC") + ._data, + ], + ["dz1", "dz2"], + ) + # the fastpath only applies to a single 2D EA block + assert len(df._mgr.blocks) == 1 + assert df._mgr.blocks[0].values.ndim == 2 + + first = pd.Timestamp("2020-01-01", tz="UTC") + second = pd.Timestamp("2020-01-02", tz="UTC") + # row 0 is [first, second]; row 1 is [second, NaT] + winner = first if method == "min" else second + + result = getattr(df, method)(axis=1) + expected = pd.Series([winner, second], dtype=df["dz1"].dtype) + tm.assert_series_equal(result, expected) + + result = getattr(df, method)(axis=1, skipna=False) + expected = pd.Series([winner, pd.NaT], dtype=df["dz1"].dtype) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "values", + [ + pd.date_range("2020-01-01", periods=1), + pd.date_range("2020-01-01", periods=1, tz="US/Pacific"), + pd.timedelta_range("1 day", periods=1), + pd.period_range("2020-01-01", periods=1, freq="D"), + ], + ids=["dt64", "dt64tz", "td64", "period"], + ) + def test_reduce_axis1_median_single_row_single_col(self, values): + # GH#68191: the result held a 0-dim array that repr could not render + df = pd.DataFrame({"a": values}) + result = df.median(axis=1) + tm.assert_series_equal(result, df["a"], check_names=False) + + def test_reduce_axis1_dt64tz_mixed_tz_falls_back(self): + # GH#65500: different tz across blocks must not enter the EA fast + # path (which would silently produce a wrong-dtype result); fall + # through to the slow path so the result has object dtype. + ts1 = pd.Timestamp("2026-01-01 15:13:44", tz="Europe/Budapest") + ts2 = pd.Timestamp("2026-01-01 15:13:44", tz="Europe/Moscow") + # ts2 is the earlier of the two in UTC terms + df = pd.DataFrame({"a": [ts1, ts1], "b": [ts2, ts2]}) + + result = df.max(axis=1) + expected = pd.Series([ts1, ts1], dtype=object) + tm.assert_series_equal(result, expected) + + result = df.min(axis=1) + expected = pd.Series([ts2, ts2], dtype=object) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("method", ["min", "max"]) + def test_reduce_axis1_dt64tz_mixed_tz_with_nat(self, method): + # GH#65500: mixed-tz frames reduce via the object path; NaT must + # be skipped under skipna=True instead of raising TypeError on + # comparison with the NA fill value. + ts1 = pd.Timestamp("2026-01-01 15:13:44", tz="Europe/Budapest") + ts2 = pd.Timestamp("2026-01-01 15:13:44", tz="Europe/Moscow") + # ts2 is the earlier of the two in UTC terms + df = pd.DataFrame({"a": [ts1, ts1], "b": [ts2, pd.NaT]}) + winner = ts2 if method == "min" else ts1 + + result = getattr(df, method)(axis=1) + expected = pd.Series([winner, ts1], dtype=object) + tm.assert_series_equal(result, expected) + + # GH#4147: the NaT row holds an NA, so skipna=False propagates it. + # object-dtype reductions use None as the NA sentinel. + result = getattr(df, method)(axis=1, skipna=False) + expected = pd.Series([winner, None], dtype=object) + tm.assert_series_equal(result, expected) + + def test_frame_any_with_timedelta(self): + # GH#17667 + df = pd.DataFrame( + { + "a": pd.Series([0, 0]), + "t": pd.Series([pd.to_timedelta(0, "s"), pd.to_timedelta(1, "ms")]), + } + ) + + result = df.any(axis=0) + expected = pd.Series(data=[False, True], index=["a", "t"]) + tm.assert_series_equal(result, expected) + + result = df.any(axis=1) + expected = pd.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.applymarker( + 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) + + def test_reduction_timestamp_smallest_unit(self): + # GH#52524 + df = pd.DataFrame( + { + "a": pd.Series([pd.Timestamp("2019-12-31")], dtype="datetime64[s]"), + "b": pd.Series( + [pd.Timestamp("2019-12-31 00:00:00.123")], dtype="datetime64[ms]" + ), + } + ) + result = df.max() + expected = pd.Series( + [pd.Timestamp("2019-12-31"), pd.Timestamp("2019-12-31 00:00:00.123")], + dtype="datetime64[ms]", + index=["a", "b"], + ) + tm.assert_series_equal(result, expected) + + def test_reduction_timedelta_smallest_unit(self): + # GH#52524 + df = pd.DataFrame( + { + "a": pd.Series([pd.Timedelta("1 days")], dtype="timedelta64[s]"), + "b": pd.Series([pd.Timedelta("1 days")], dtype="timedelta64[ms]"), + } + ) + result = df.max() + expected = pd.Series( + [pd.Timedelta("1 days"), pd.Timedelta("1 days")], + dtype="timedelta64[ms]", + index=["a", "b"], + ) + tm.assert_series_equal(result, expected) + + +class TestNuisanceColumns: + def test_any_all_categorical_dtype_nuisance_column(self, all_boolean_reductions): + # GH#36076 DataFrame should match Series behavior + ser = pd.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 operation"): + getattr(ser, all_boolean_reductions)() + + with pytest.raises(TypeError, match="does not support operation"): + getattr(np, all_boolean_reductions)(ser) + + with pytest.raises(TypeError, match="does not support operation"): + getattr(df, all_boolean_reductions)(bool_only=False) + + with pytest.raises(TypeError, match="does not support operation"): + getattr(df, all_boolean_reductions)(bool_only=None) + + with pytest.raises(TypeError, match="does not support operation"): + getattr(np, all_boolean_reductions)(df, axis=0) + + def test_median_categorical_dtype_nuisance_column(self): + # GH#21020 DataFrame.median should match Series.median + df = pd.DataFrame({"A": pd.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 operation"): + ser.median() + + with pytest.raises(TypeError, match="does not support operation"): + df.median(numeric_only=False) + + with pytest.raises(TypeError, match="does not support operation"): + 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 operation"): + df.median(numeric_only=False) + + with pytest.raises(TypeError, match="does not support operation"): + 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 = pd.Categorical(["a", "b", "c", "b"], ordered=False) + ser = pd.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 = pd.DataFrame({0: [], 1: []}, dtype=dtype) + result = getattr(df, opname)(min_count=0) + + expected = pd.Series([exp_value, exp_value], dtype=exp_dtype, index=range(2)) + 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 = pd.DataFrame({0: [], 1: []}, dtype=dtype) + result = getattr(df, opname)(min_count=1) + + expected = pd.Series([np.nan, np.nan], dtype=exp_dtype, index=pd.Index([0, 1])) + 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")), + ("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 = pd.DataFrame({0: [], 1: []}, dtype=dtype) + result = getattr(df, opname)(min_count=0) + + expected = pd.Series( + [exp_value, exp_value], dtype=exp_dtype, index=pd.Index([0, 1]) + ) + 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 = pd.DataFrame({0: [], 1: []}, dtype=dtype) + result = getattr(df, opname)(min_count=1) + + expected = pd.Series([pd.NA, pd.NA], dtype=exp_dtype, index=pd.Index([0, 1])) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "data", + [ + {"a": [0, 1, 2], "b": [pd.NaT, pd.NaT, pd.NaT]}, + {"a": [0, 1, 2], "b": [pd.Timestamp("1990-01-01"), pd.NaT, pd.NaT]}, + { + "a": [0, 1, 2], + "b": [ + pd.Timestamp("1990-01-01"), + pd.Timestamp("1991-01-01"), + pd.Timestamp("1992-01-01"), + ], + }, + { + "a": [0, 1, 2], + "b": [pd.Timedelta("1 days"), pd.Timedelta("2 days"), pd.NaT], + }, + { + "a": [0, 1, 2], + "b": [ + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + pd.Timedelta("3 days"), + ], + }, + ], + ) + def test_df_cov_pd_nat(self, data): + # GH #53115 + df = pd.DataFrame(data) + with pytest.raises(TypeError, match="not supported for cov"): + df.cov() + + +def test_sum_timedelta64_skipna_false(): + # GH#17235 + arr = np.arange(8).astype(np.int64).view("m8[s]").reshape(4, 2) + arr[-1, -1] = "Nat" + + df = pd.DataFrame(arr) + assert (df.dtypes == arr.dtype).all() + + result = df.sum(skipna=False) + expected = pd.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 = pd.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_sum_empty_timedelta_column(): + # GH#50628 summing an empty timedelta column used to raise + # "Cannot cast TimedeltaArray to dtype float64" + df = pd.DataFrame({"b": np.array([], dtype="m8[ns]")}) + result = df.sum() + expected = pd.Series([pd.Timedelta(0)], index=["b"], dtype="m8[ns]") + tm.assert_series_equal(result, expected) + + +def test_sum_empty_mixed_with_timedelta_column(): + # GH#50628 sum over an empty mixed-dtype frame keeps per-column dtypes + # rather than force-casting to float64 (which raised for timedelta) + df = pd.DataFrame( + { + "a": np.array([], dtype="float64"), + "b": np.array([], dtype="m8[ns]"), + "c": np.array([], dtype="int64"), + } + ) + result = df.sum() + expected = pd.Series([0.0, pd.Timedelta(0), 0], index=["a", "b", "c"], dtype=object) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("skipna", [True, False]) +def test_sum_timedelta64_overflow_raises(axis, skipna): + # GH#43178: DataFrame.sum on an overflowing timedelta64 frame should raise + # OutOfBoundsTimedelta, consistent with Series.sum, rather than silently + # returning a saturated result. + half = np.iinfo(np.int64).max // 2 + arr = np.array([half, half, half], dtype="m8[ns]") + df = pd.DataFrame({"a": arr, "b": arr, "c": arr}) + + msg = "overflow in timedelta operation" + with pytest.raises(pd.errors.OutOfBoundsTimedelta, match=msg): + df.sum(axis=axis, skipna=skipna) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_sum_timedelta64_all_nat_skipna_false(axis): + # GH#43178: an all-NaT reduction with skipna=False must return NaT, not be + # mistaken for an overflow (the NaT sentinels accumulate past int64 bounds) + nat = np.array(["NaT", "NaT", "NaT"], dtype="m8[ns]") + df = pd.DataFrame({"a": nat, "b": nat, "c": nat}) + + result = df.sum(axis=axis, skipna=False) + assert result.dtype == "m8[ns]" + assert result.isna().all() + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_sum_timedelta64_exact(axis): + # GH#66551: the sum used to accumulate in float64, whose 53-bit mantissa + # silently rounded results above 2**53 + arr = np.array([2**53 + 1, 0], dtype="m8[ns]") + df = pd.DataFrame({"a": arr, "b": arr[::-1]}) + + result = df.sum(axis=axis) + expected = pd.Series( + np.array([2**53 + 1] * 2, dtype="m8[ns]"), index=df.axes[1 - axis] + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_sum_timedelta64_overflow_only_in_exempt_slice(axis): + # GH#66551: the check applies per reduced slice, and a slice that reduces to + # NaT under skipna=False is exempt even though its entries overflow + df = pd.DataFrame( + { + "a": [pd.Timedelta(1, "ns"), pd.Timedelta(2, "ns")], + "b": [pd.Timedelta.max, pd.NaT], + } + ) + if axis == 1: + df = df.T + + result = df.sum(axis=axis, skipna=False) + expected = pd.Series( + [pd.Timedelta(3, "ns"), pd.NaT], index=df.axes[1 - axis], dtype="m8[ns]" + ) + tm.assert_series_equal(result, expected) + + +def test_mixed_frame_with_integer_sum(): + # https://github.com/pandas-dev/pandas/issues/34520 + df = pd.DataFrame([["a", 1]], columns=list("ab")) + df = df.astype({"b": "Int64"}) + result = df.sum() + expected = pd.Series(["a", 1], index=["a", "b"]) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("numeric_only", [True, False]) +@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 = pd.Series([int64_info.max, None, int64_info.min], dtype=pd.Int64Dtype()) + df = pd.DataFrame({"Int64": ser}) + result = getattr(df, method)(numeric_only=numeric_only) + expected = pd.Series( + [getattr(int64_info, method)], + dtype="Int64", + index=pd.Index(["Int64"]), + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("dtype", [object, "str"]) +def test_minmax_axis0_string_columns_with_na(dtype): + # GH#18588: the string columns were silently dropped as nuisance columns, + # and once numeric_only stopped dropping them the +/-inf NA fill raised + df = pd.DataFrame( + { + "col1": [0, 1, 2, 3], + "col2": pd.Series(["a", "b", None, "d"], dtype=dtype), + "col3": pd.Series(["e", "f", None, "h"], dtype=dtype), + } + ) + index = pd.Index(["col1", "col2", "col3"]) + + result = df.min(axis=0) + tm.assert_series_equal(result, pd.Series([0, "a", "e"], index=index, dtype=object)) + + result = df.max(axis=0) + tm.assert_series_equal(result, pd.Series([3, "d", "h"], index=index, dtype=object)) + + +def test_minmax_axis0_object_date_with_na(): + # GH#61204 + df = pd.DataFrame( + {"dates": [np.nan, np.nan, date(2025, 1, 3), date(2025, 1, 4)]}, dtype=object + ) + index = pd.Index(["dates"]) + + result = df.min(axis=0) + tm.assert_series_equal( + result, pd.Series([date(2025, 1, 3)], index=index, dtype=object) + ) + + result = df.max(axis=0) + tm.assert_series_equal( + result, pd.Series([date(2025, 1, 4)], index=index, dtype=object) + ) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_minmax_object_na_positions_differ_per_slice(axis): + # GH#18588: the NA fill is taken per reduction slice, so slices whose NAs + # sit in different positions do not borrow each other's values, and an + # all-NA slice reduces to NA rather than poisoning its neighbours + df = pd.DataFrame( + { + "a": ["x", None, "b"], + "b": [None, "q", "p"], + "c": [None, None, None], + }, + dtype=object, + ) + if axis == 0: + exp_min = pd.Series( + ["b", "p", None], index=pd.Index(["a", "b", "c"]), dtype=object + ) + exp_max = pd.Series( + ["x", "q", None], index=pd.Index(["a", "b", "c"]), dtype=object + ) + else: + exp_min = pd.Series(["x", "q", "b"], dtype=object) + exp_max = pd.Series(["x", "q", "p"], dtype=object) + + tm.assert_series_equal(df.min(axis=axis), exp_min) + tm.assert_series_equal(df.max(axis=axis), exp_max) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_minmax_object_skipna_false_propagates_per_slice(axis): + # GH#4147: only the slices that actually hold an NA reduce to NA + df = pd.DataFrame( + { + "a": ["x", None, "b"], + "b": ["r", "q", "p"], + }, + dtype=object, + ) + if axis == 0: + exp_min = pd.Series([None, "p"], index=pd.Index(["a", "b"]), dtype=object) + exp_max = pd.Series([None, "r"], index=pd.Index(["a", "b"]), dtype=object) + else: + exp_min = pd.Series(["r", None, "b"], dtype=object) + exp_max = pd.Series(["x", None, "p"], dtype=object) + + tm.assert_series_equal(df.min(axis=axis, skipna=False), exp_min) + tm.assert_series_equal(df.max(axis=axis, skipna=False), exp_max) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_idxminmax_object_with_na(axis): + # GH#4147: idxmin/idxmax raised TypeError on object data holding NAs even + # though min/max on the same data works + # the NA fill is taken per slice, so the data has to be one where a global + # fill (the frame's first non-NA) would give a different answer + df = pd.DataFrame( + { + "a": ["d", None, "a"], + "b": ["z", "y", None], + "c": ["a", "b", None], + }, + dtype=object, + ) + if axis == 0: + exp_min = pd.Series([2, 1, 0], index=pd.Index(["a", "b", "c"])) + exp_max = pd.Series([0, 0, 1], index=pd.Index(["a", "b", "c"])) + else: + exp_min = pd.Series(["c", "c", "a"]) + exp_max = pd.Series(["b", "b", "a"]) + + tm.assert_series_equal(df.idxmin(axis=axis), exp_min) + tm.assert_series_equal(df.idxmax(axis=axis), exp_max) + + +@pytest.mark.parametrize( + "dtype", + [object, "str", pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow"))], +) +@pytest.mark.parametrize("method", ["min", "max"]) +def test_string_reduction_skipna_false_axis1(dtype, method): + # GH#18588: string columns reduce along axis=1 via the EA _groupby_op + # fastpath, whose python fallback used to drop skipna and return a non-NA + # answer. object is not an ExtensionDtype, so it transposes onto nanops + # instead, where the NA used to raise TypeError. + df = pd.DataFrame( + { + "a": pd.Series(["x", None], dtype=dtype), + "b": pd.Series(["y", "z"], dtype=dtype), + } + ) + result = getattr(df, method)(axis=1, skipna=False) + expected = pd.Series([("x" if method == "min" else "y"), None], dtype=dtype) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_sum_prod_object_skipna_false(axis): + # GH#4147: only the slices holding an NA are nulled out; the others still + # reduce normally. Deliberately non-square, so that nulling along the + # wrong axis is distinguishable. + df = pd.DataFrame({"a": [1, 2, None], "b": [3, 4, 5]}, dtype=object) + if axis == 0: + exp_sum = pd.Series([None, 12], index=pd.Index(["a", "b"]), dtype=object) + exp_prod = pd.Series([None, 60], index=pd.Index(["a", "b"]), dtype=object) + else: + exp_sum = pd.Series([4, 6, None], dtype=object) + exp_prod = pd.Series([3, 8, None], dtype=object) + + tm.assert_series_equal(df.sum(axis=axis, skipna=False), exp_sum) + tm.assert_series_equal(df.prod(axis=axis, skipna=False), exp_prod) + + +@pytest.mark.parametrize( + "method, exp_skipna, exp_no_na", + [("min", 1, 1), ("max", 4, 4), ("sum", 8, 10), ("prod", 12, 24)], +) +def test_object_reduction_axis_none(method, exp_skipna, exp_no_na): + # GH#4147: axis=None reduces over the whole frame, so one NA anywhere + # makes the skipna=False result NA + df = pd.DataFrame({"a": [1, None], "b": [3, 4]}, dtype=object) + assert pd.isna(getattr(df, method)(axis=None, skipna=False)) + # ... while skipna=True reduces over the rest + assert getattr(df, method)(axis=None) == exp_skipna + + # without an NA it still reduces normally + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}, dtype=object) + assert getattr(df, method)(axis=None, skipna=False) == exp_no_na + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("method", ["sum", "prod"]) +def test_sum_prod_object_skipna_false_min_count(axis, method): + # GH#4147: a min_count larger than the slice still nulls out the slices + # that hold no NA, i.e. skipna=False must not weaken it + df = pd.DataFrame({"a": [1, None], "b": [3, 4]}, dtype=object) + result = getattr(df, method)(axis=axis, skipna=False, min_count=5) + # column/row "b" holds no NA, so only min_count nulls it out + index = pd.Index(["a", "b"]) if axis == 0 else pd.Index([0, 1]) + expected = pd.Series([None, None], index=index, dtype=object) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("method", ["min", "max"]) +def test_minmax_object_incomparable_skipna_false_axis1(method): + # GH#4147: every row holds an NA, so every row is nulled out and the + # mutually-incomparable values must never be compared + df = pd.DataFrame({"a": [1, "p"], "b": ["a", "q"], "c": [None, None]}, dtype=object) + result = getattr(df, method)(axis=1, skipna=False) + tm.assert_series_equal(result, pd.Series([None, None], dtype=object)) + + +@pytest.mark.parametrize("method", ["sum", "prod"]) +def test_sum_prod_ea_skipna_false_axis1(method): + # GH#18588: an extension dtype reduces along axis=1 through the same python + # fallback, which used to drop skipna. object does not reach it (not an + # ExtensionDtype), so it needs an actual EA to cover. + df = pd.DataFrame( + { + "a": DecimalArray([Decimal(2), Decimal("NaN")]), + "b": DecimalArray([Decimal(3), Decimal(4)]), + } + ) + result = getattr(df, method)(axis=1, skipna=False) + assert result.iloc[0] == (5 if method == "sum" else 6) + assert pd.isna(result.iloc[1]) + + +@pytest.mark.parametrize("method", ["min", "max"]) +def test_interval_reduction_skipna_false_axis1(method): + # GH#18588: IntervalDtype takes the same python fallback as the string dtypes + df = pd.DataFrame( + { + "a": pd.arrays.IntervalArray.from_tuples([(0, 1), (4, 5)]), + "b": pd.arrays.IntervalArray.from_tuples([(2, 3), None]), + } + ) + result = getattr(df, method)(axis=1, skipna=False) + expected = pd.Series( + pd.arrays.IntervalArray.from_tuples( + [(0, 1) if method == "min" else (2, 3), None] + ) + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("ts_value", [pd.Timestamp("2000-01-01"), pd.NaT]) +def test_frame_mixed_numeric_object_with_timestamp(ts_value): + # GH 13912 + df = pd.DataFrame({"a": [1], "b": [1.1], "c": ["foo"], "d": [ts_value]}) + msg = "|".join(["does not support operation", "Cannot perform"]) + with pytest.raises(TypeError, match=msg): + df.sum() + + +def test_prod_sum_min_count_mixed_object(): + # https://github.com/pandas-dev/pandas/issues/41074 + df = pd.DataFrame([1, "a", True]) + + result = df.prod(axis=0, min_count=1, numeric_only=False) + expected = pd.Series(["a"], dtype=object) + 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 = pd.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 + + +def test_reduction_axis_none_object_dtype_preserves_numpy_scalars(): + # GH#64266 + left = np.int8(1) + df = pd.DataFrame({"a": [left], "b": [np.int8(5)]}, dtype=object) + result = df.min(axis=None) + assert result is left + + result = np.minimum.reduce(df, axis=None) + assert result is left + + +@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 = pd.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", + "Could not convert to numeric", + ] + ) + 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, using_nan_is_na +): + # GH 54341 + df = pd.DataFrame( + { + "a": pd.Series([0, 1, 2, 3], dtype=any_numeric_ea_dtype), + "b": pd.Series([0, 1, pd.NA, 3], dtype=any_numeric_ea_dtype), + }, + ) + expected_df = pd.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 + + if not skipna and method in ("idxmax", "idxmin"): + with pytest.raises(ValueError, match="encountered an NA value"): + getattr(df, method)(axis=1, **kwargs) + with pytest.raises(ValueError, match="Encountered an NA value"): + getattr(expected_df, method)(axis=1, **kwargs) + return + result = getattr(df, method)(axis=1, **kwargs) + expected = getattr(expected_df, method)(axis=1, **kwargs) + if method not in ("idxmax", "idxmin"): + if using_nan_is_na: + expected = expected.astype(expected_dtype) + else: + mask = np.isnan(expected) + expected[mask] = 0 + expected = expected.astype(expected_dtype) + expected[mask] = pd.NA + if not skipna and method == "all": + # GH#65710 Kleene "all" on (truthy, NA) row returns NA + expected.iloc[2] = pd.NA + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmax", "idxmin"]) +@pytest.mark.parametrize("skipna", [True, False]) +@pytest.mark.parametrize( + "dtype", ["Int64", "Float64", "UInt32", "boolean", "int64[pyarrow]"] +) +def test_idxmax_idxmin_axis_1_ea_matches_numpy(how, skipna, dtype): + # GH#56903 the EA-backed axis=1 path must agree with the numpy-backed path, + # including skipna=False when there are no NA values (previously the cython + # kernel returned the all-NA sentinel for every row). + if "pyarrow" in dtype: + pytest.importorskip("pyarrow") + if dtype == "boolean": + values = [[True, False, True], [False, False, True], [True, True, False]] + np_dtype = bool + else: + values = [[1, 4, 0], [5, 2, 9], [2, 8, 1], [3, 3, 7]] + np_dtype = "float64" + df_ea = pd.DataFrame(values, columns=["a", "b", "c"]).astype(dtype) + df_np = pd.DataFrame(values, columns=["a", "b", "c"]).astype(np_dtype) + + result = getattr(df_ea, how)(axis=1, skipna=skipna) + expected = getattr(df_np, how)(axis=1, skipna=skipna) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmax", "idxmin"]) +@pytest.mark.parametrize("skipna", [True, False]) +@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean", "int64[pyarrow]"]) +def test_idxmax_idxmin_axis_1_ea_all_na_row_raises(how, skipna, dtype): + # GH#56903 a fully-NA row must raise (matching the numpy-backed path) rather + # than leak the -1 cython sentinel as a column label. + if "pyarrow" in dtype: + pytest.importorskip("pyarrow") + if dtype == "boolean": + values = [[True, False], [pd.NA, pd.NA], [False, True]] + else: + values = [[1, 4], [pd.NA, pd.NA], [3, 9]] + df = pd.DataFrame(values, columns=["a", "b"]).astype(dtype) + with pytest.raises(ValueError, match="[Ee]ncountered an?.*NA value"): + getattr(df, how)(axis=1, skipna=skipna) + + +@pytest.mark.parametrize("skipna", [True, False]) +@pytest.mark.parametrize("dtype", ["boolean", "bool[pyarrow]"]) +def test_logical_reductions_axis_1_ea_matches_numpy(dtype, skipna): + # GH#56903 any/all axis=1 fastpath for boolean-like EA dtypes + if "pyarrow" in dtype: + pytest.importorskip("pyarrow") + values = [[True, False, True], [False, False, False], [True, True, True]] + df_ea = pd.DataFrame(values, columns=["a", "b", "c"]).astype(dtype) + df_np = pd.DataFrame(values, columns=["a", "b", "c"]) + for how in ["any", "all"]: + result = getattr(df_ea, how)(axis=1, skipna=skipna) + expected = getattr(df_np, how)(axis=1, skipna=skipna).astype(dtype) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["str", "string"]) +@pytest.mark.parametrize("how", ["min", "max"]) +def test_str_min_max_axis_1(how, dtype): + # GH#56903 no cython groupby op for object-backed str min/max; the + # axis=1 EA fastpath must fall back to python aggregation + df = pd.DataFrame({"a": ["x", "b"], "b": ["c", "d"]}, dtype=dtype) + result = getattr(df, how)(axis=1) + values = ["c", "b"] if how == "min" else ["x", "d"] + expected = pd.Series(values, dtype=dtype) + tm.assert_series_equal(result, expected) + + +def test_third_party_ea_axis_1(): + # GH#56903 EAs without a _groupby_op override must fall back to + # python aggregation in the axis=1 EA fastpath + df = pd.DataFrame( + { + "a": DecimalArray([Decimal("1"), Decimal("2")]), + "b": DecimalArray([Decimal("3"), Decimal("4")]), + } + ) + result = df.sum(axis=1) + expected = pd.Series(DecimalArray([Decimal("4"), Decimal("6")])) + tm.assert_series_equal(result, expected) + + +def test_mean_nullable_int_axis_1(): + # GH##36585 + df = pd.DataFrame( + {"a": [1, 2, 3, 4], "b": pd.Series([1, 2, 4, None], dtype=pd.Int64Dtype())} + ) + + result = df.mean(axis=1, skipna=True) + expected = pd.Series([1.0, 2.0, 3.5, 4.0], dtype="Float64") + tm.assert_series_equal(result, expected) + + result = df.mean(axis=1, skipna=False) + expected = pd.Series([1.0, 2.0, 3.5, pd.NA], dtype="Float64") + tm.assert_series_equal(result, expected) + + +def test_numeric_only_validates_bool(): + # GH#53098 + df = pd.DataFrame({"A": [1, 2, 3], "B": [1.0, 2.0, 3.0], "C": ["x", "y", "z"]}) + df_num = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + msg = "Passing non-boolean values for 'numeric_only' is deprecated" + + # _stat_function family: mean, min, max, median, skew, kurt + for method in ["mean", "min", "max", "median", "skew", "kurt"]: + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(df, method)(numeric_only=1) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(df, method)(numeric_only="yes") + # None is falsy so _reduce includes all columns; use numeric-only df + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(df_num, method)(numeric_only=None) + + # _stat_function_ddof family: std, var, sem + for method in ["std", "var", "sem"]: + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(df, method)(numeric_only=1) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(df, method)(numeric_only="yes") + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(df_num, method)(numeric_only=None) + + # _min_count_stat_function family: sum, prod + for method in ["sum", "prod"]: + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(df, method)(numeric_only=1) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(df, method)(numeric_only="yes") + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(df_num, method)(numeric_only=None) + + # Valid boolean values must still work (regression guard) + df_num.mean(numeric_only=True) + df_num.mean(numeric_only=False) + df_num.sum(numeric_only=True) + df_num.std(numeric_only=True) + + +@pytest.mark.parametrize("na_first", [True, False]) +def test_median_skipna_false_keeps_complex(na_first): + # GH#68487 the NaN propagated for a column holding an NA was real, so + # whenever that column was reduced first the others were cast down to it + # and lost their imaginary part + cols = {"a": [1 + 2j, np.nan], "b": [1 + 2j, 3 + 4j]} + if not na_first: + cols = dict(reversed(cols.items())) + df = pd.DataFrame(cols) + + expected = pd.Series( + [complex(np.nan), 2 + 3j] if na_first else [2 + 3j, complex(np.nan)], + index=list(cols), + ) + tm.assert_series_equal(df.median(skipna=False), expected) + tm.assert_series_equal(df.T.median(axis=1, skipna=False), expected) + + +@pytest.mark.parametrize( + "method, expected", + [ + ("sum", float(2**63) + 0.5), + ("prod", float(2**62) * float(2**62) * 0.5), + ("mean", (float(2**63) + 0.5) / 3), + ], +) +def test_reduce_axis1_int_block_does_not_wrap(method, expected): + # GH#68641: the int block used to be accumulated in int64, silently + # wrapping, while the transpose path accumulates in float64 + df = pd.DataFrame({"a": [2**62], "b": [2**62], "c": [0.5]}) + assert len(df._mgr.blocks) > 1 + + result = getattr(df, method)(axis=1) + tm.assert_series_equal(result, pd.Series([expected])) + tm.assert_series_equal(result, getattr(df.T, method)(), check_names=False) + + +def test_reduce_axis1_int_only_mean_widens_to_float64(): + # GH#68641: with no float column the common dtype is int64, so mean has to + # widen it the way nanmean does or the sum wraps and flips sign + df = pd.DataFrame({"a": [2**62], "b": [2**62], "c": np.array([1], dtype="uint8")}) + assert len(df._mgr.blocks) > 1 + + result = df.mean(axis=1) + tm.assert_series_equal(result, pd.Series([(float(2**63) + 1) / 3])) + tm.assert_series_equal(result, df.T.mean(), check_names=False) + + +@pytest.mark.parametrize("method", ["sum", "prod", "mean"]) +def test_reduce_axis1_uint64_block_does_not_wrap(method): + # GH#68641 + df = pd.DataFrame( + { + "a": np.array([2**63], dtype="uint64"), + "b": np.array([2**63], dtype="uint64"), + "c": [0.5], + } + ) + assert len(df._mgr.blocks) > 1 + + result = getattr(df, method)(axis=1) + tm.assert_series_equal(result, getattr(df.T, method)(), check_names=False) + # without the fix the uint64 block wrapped to 0, leaving just the float + assert result.iloc[0] > 2**62 + + +def test_reduce_axis1_int_uint_combine_stays_exact(): + # GH#68641: combining an int64 block result with a uint64 one promoted + # the result to a lossy float64 + df = pd.DataFrame( + {"a": np.array([2**62 + 1], dtype="int64"), "b": np.array([1], dtype="uint8")} + ) + assert len(df._mgr.blocks) > 1 + + result = df.sum(axis=1) + tm.assert_series_equal(result, pd.Series([2**62 + 2], dtype="int64")) + + +@pytest.mark.parametrize("method", ["sum", "prod", "mean"]) +def test_reduce_axis1_float32_not_upcast(method): + # GH#68641: reducing in the common dtype keeps float32 out of float64 + df = pd.DataFrame( + { + "a": np.array([1.5, 2.5], dtype="float32"), + "b": np.array([1, 2], dtype="int8"), + } + ) + assert len(df._mgr.blocks) > 1 + + result = getattr(df, method)(axis=1) + assert result.dtype == "float32" + tm.assert_series_equal(result, getattr(df.T, method)(), check_names=False) + + +@pytest.mark.parametrize( + "method, expected", + [ + ("sum", float(2**63)), + ("prod", float(2**62) * float(2**62) * 0.5), + ("mean", float(2**63) / 4), + ], +) +def test_reduce_axis1_bool_block_keeps_common_dtype(method, expected): + # GH#68641: find_common_type would collapse to object here, which is why + # the accumulation dtype comes from np.result_type instead + df = pd.DataFrame({"a": [2**62], "b": [2**62], "c": [0.5], "d": [True]}) + assert len(df._mgr.blocks) == 3 + + result = getattr(df, method)(axis=1) + tm.assert_series_equal(result, pd.Series([expected])) + + +def test_reduce_axis1_complex64_matches_transpose(): + # GH#68641 nanmean accumulates in the input dtype and widens only for the + # division, so complex64 must not be summed as complex128 here either + df = pd.DataFrame( + { + "a": np.array([32767], dtype="int16"), + "b": np.array([2**62], dtype="complex64"), + } + ) + assert len(df._mgr.blocks) > 1 + + tm.assert_series_equal(df.mean(axis=1), df.T.mean()) + + +@pytest.mark.parametrize("skipna", [True, False]) +def test_reduce_axis1_min_count_complex64_matches_transpose(skipna): + # GH#68641 _maybe_null_out widens complex64 before writing NaN; the axis=1 + # path has to widen the same way, and only where nanops does -- under + # skipna=False it builds no mask, so nothing counts as missing + df = pd.DataFrame( + { + "a": np.array([1 + 2j, np.nan], dtype="complex64"), + "b": np.array([1.0, 2.0], dtype="float32"), + } + ) + assert len(df._mgr.blocks) > 1 + + result = df.sum(axis=1, min_count=2, skipna=skipna) + assert result.dtype == ("complex128" if skipna else "complex64") + tm.assert_series_equal(result, df.T.sum(min_count=2, skipna=skipna)) + + +def test_reduce_axis1_mean_complex_keeps_imaginary_part(): + # GH#68641: mean unconditionally cast the combined result to float64, + # silently discarding the imaginary part + df = pd.DataFrame( + {"a": [True, False], "b": np.array([1 + 2j, 3 + 4j], dtype="complex64")} + ) + assert len(df._mgr.blocks) > 1 + + result = df.mean(axis=1) + tm.assert_series_equal(result, pd.Series([1 + 1j, 1.5 + 2j], dtype="complex128")) + + +def test_reduce_axis1_bool_block_keeps_numpy_int_semantics(): + # GH#51474: a bool column no longer routes the reduction through object + # dtype, so an integer result wraps like numpy instead of staying exact + df = pd.DataFrame({"a": [2**62], "b": [2**62], "c": [True]}) + assert len(df._mgr.blocks) > 1 + + result = df.sum(axis=1) + expected = pd.Series([-(2**63) + 1]) + assert expected.dtype == "int64" + tm.assert_series_equal(result, expected) + + +def test_reduce_axis1_float32_block_does_not_overflow(): + # GH#68641: the float32 block was accumulated in float32, overflowing to + # inf where the transpose path accumulated in the common float64 + df = pd.DataFrame( + { + "a": np.array([3e38], dtype="float32"), + "b": np.array([3e38], dtype="float32"), + "c": [1.0], + } + ) + assert len(df._mgr.blocks) > 1 + + result = df.sum(axis=1) + tm.assert_series_equal(result, pd.Series([float(np.float32(3e38)) * 2 + 1.0])) + tm.assert_series_equal(result, df.T.sum(), check_names=False) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_repr.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_repr.py new file mode 100644 index 0000000000000000000000000000000000000000..f73900dc97293fb610c09507ec88a271f9f90daa --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_repr.py @@ -0,0 +1,515 @@ +from datetime import ( + datetime, + timedelta, +) +from io import StringIO + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameRepr: + 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." + data = [8, 5, 3, 5] + index1 = ["\u03c3", "\u03c4", "\u03c5", "\u03c6"] + cols = ["\u03c8"] + df = pd.DataFrame(data, columns=cols, index=index1) + assert type(df.__repr__()) is str + + ser = df[cols[0]] + assert type(ser.__repr__()) is str + + def test_repr_bytes_61_lines(self): + # GH#12857 + lets = list("ACDEFGHIJKLMNOP") + words = np.random.default_rng(2).choice(lets, (1000, 50)) + df = pd.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 = pd.MultiIndex.from_tuples([(0, 0), (1, 1)], names=["\u0394", "i1"]) + + obj = pd.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 = pd.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 = pd.DataFrame( + {"X": [1, 2]}, index=[[pd.NaT, pd.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 = pd.DataFrame([1, 2, 3, 4], [True, None, np.nan, pd.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], pd.NaT: [6, 7], True: [8, 9]} + df = pd.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 = pd.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 = pd.MultiIndex.from_tuples( + [("a", 0, "foo"), ("b", 1, "bar")], names=["a", "b", "c"] + ) + + df = pd.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(pd.DataFrame()) + + # empty with index + frame = pd.DataFrame(index=np.arange(1000)) + repr(frame) + + def test_repr_mixed(self, float_string_frame): + # mixed + repr(float_string_frame) + + @pytest.mark.slow + def test_repr_mixed_big(self): + # big mixed + biggie = pd.DataFrame( + { + "A": np.random.default_rng(2).standard_normal(200), + "B": [str(i) for i in range(200)], + }, + index=range(200), + ) + biggie.loc[:20, "A"] = np.nan + biggie.loc[:20, "B"] = np.nan + + repr(biggie) + + def test_repr(self): + # columns but no index + no_index = pd.DataFrame(columns=[0, 1, 3]) + repr(no_index) + + df = pd.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 = pd.DataFrame([[1, 2], [3, 4]]) + with pd.option_context("display.show_dimensions", True): + assert "2 rows x 2 columns" in repr(df) + + with pd.option_context("display.show_dimensions", False): + assert "2 rows x 2 columns" not in repr(df) + + with pd.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 = pd.DataFrame(np.zeros((200, 4)), columns=range(4), index=range(200)) + repr(biggie) + + def test_repr_unsortable(self): + # columns are not sortable + + unsortable = pd.DataFrame( + { + "foo": [1] * 50, + datetime(2011, 1, 1): [1] * 50, + "bar": ["bar"] * 50, + datetime(2011, 1, 1) + timedelta(1): ["bar"] * 50, + }, + index=np.arange(50), + ) + repr(unsortable) + + def test_repr_float_frame_options(self, float_frame): + repr(float_frame) + + with pd.option_context("display.precision", 3): + repr(float_frame) + + with pd.option_context("display.max_rows", 10, "display.max_columns", 2): + repr(float_frame) + + with pd.option_context("display.max_rows", 1000, "display.max_columns", 1000): + repr(float_frame) + + def test_repr_unicode(self): + uval = "\u03c3\u03c3\u03c3\u03c3" + + df = pd.DataFrame({"A": [uval, uval]}) + + result = repr(df) + ex_top = " A" + assert result.split("\n")[0].rstrip() == ex_top + + df = pd.DataFrame({"A": [uval, uval]}) + result = repr(df) + assert result.split("\n")[0].rstrip() == ex_top + + def test_unicode_string_with_unicode(self): + df = pd.DataFrame({"A": ["\u05d0"]}) + str(df) + + def test_repr_unicode_columns(self): + df = pd.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 = pd.DataFrame({"A": ["abc"]}) + msg = "^'str' object cannot be interpreted as an integer$" + with pytest.raises(TypeError, match=msg): + bytes(df) + + def test_very_wide_repr(self): + df = pd.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 = pd.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 pd.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 pd.option_context( + "styler.format.escape", None, "styler.render.repr", "latex" + ): + df = pd.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_with_datetimeindex(self): + df = pd.DataFrame({"A": [1, 2, 3]}, index=pd.date_range("2000", periods=3)) + result = repr(df) + expected = " A\n2000-01-01 1\n2000-01-02 2\n2000-01-03 3" + assert result == expected + + def test_repr_with_intervalindex(self): + # https://github.com/pandas-dev/pandas/pull/24134/files + df = pd.DataFrame( + {"A": [1, 2, 3, 4]}, index=pd.IntervalIndex.from_breaks([0, 1, 2, 3, 4]) + ) + result = repr(df) + expected = " A\n(0, 1] 1\n(1, 2] 2\n(2, 3] 3\n(3, 4] 4" + assert result == expected + + def test_repr_with_categorical_index(self): + df = pd.DataFrame({"A": [1, 2, 3]}, index=pd.CategoricalIndex(["a", "b", "c"])) + result = repr(df) + expected = " A\na 1\nb 2\nc 3" + assert result == expected + + def test_repr_categorical_dates_periods(self): + # normal DataFrame + dt = pd.date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern") + p = pd.period_range("2011-01", freq="M", periods=5) + df = pd.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 = pd.DataFrame({"dt": pd.Categorical(dt), "p": pd.Categorical(p)}) + assert repr(df2) == exp + + @pytest.mark.parametrize( + "nat", + [np.datetime64("NaT", "ns"), np.timedelta64("NaT", "ns")], + ) + @pytest.mark.parametrize( + "box, expected", + [[pd.Series, "0 NaT\ndtype: object"], [pd.DataFrame, " 0\n0 NaT"]], + ) + def test_repr_np_nat_with_object(self, nat, box, expected): + # GH 25445 + result = repr(box([nat], dtype=object)) + assert result == expected + + def test_frame_datetime64_pre1900_repr(self): + df = pd.DataFrame( + {"year": pd.date_range("1/1/1700", periods=50, freq="YE-DEC")} + ) + # it works! + repr(df) + + def test_frame_to_string_with_periodindex(self): + index = pd.PeriodIndex(["2011-1", "2011-2", "2011-3"], freq="M") + frame = pd.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 = pd.DataFrame( + {"a": [1, 2]}, + index=pd.MultiIndex.from_arrays([pd.Series([pd.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 = pd.DataFrame({"x": pd.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 = pd.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 = pd.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 = pd.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_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]""" + df = pd.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_from_records_with_nested_structured_dtype_repr(self): + # GH#55011 structured ndarray (not np.rec.recarray) with a nested + # field-of-fields dtype + ar = np.array( + [((255, 0),), ((255, 1),), ((255, 2),)], + dtype=[("x", [("null", "u1"), ("val", "{len(reprs[0])}}\n" + "\n".join(reprs) + else: + reprs = [f"{i} {val}" for i, val in enumerate(output)] + expected = "\n".join(reprs) + "\ndtype: complex128" + assert str(obj) == expected, f"\n{obj!s}\n\n{expected}" + + +@pytest.mark.parametrize("nrows", [60, 61]) +def test_repr_truncated_na_shows_na_not_nan(nrows): + # GH#33065 pd.NA in an object column must render as , not NaN, even + # when the repr is truncated (nrows above the display limit) + df = pd.DataFrame(np.full((nrows, 1), pd.NA)) + result = repr(df) + assert "" in result + assert "NaN" not in result diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_stack_unstack.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_stack_unstack.py new file mode 100644 index 0000000000000000000000000000000000000000..76a514da4ab51b8e34491bf29eda5d35b42c7a87 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_stack_unstack.py @@ -0,0 +1,3103 @@ +from datetime import datetime +import itertools + +import numpy as np +import pytest + +from pandas._libs import lib +from pandas.errors import Pandas4Warning + +import pandas as pd +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 + + +@pytest.fixture +def mock_unstacker(monkeypatch): + """Stop _Unstacker as soon as __init__ has emitted the size warning.""" + + class MockUnstacker(reshape_lib._Unstacker): + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + raise Exception("Don't compute final result.") + + def _make_selectors(self) -> None: + pass + + monkeypatch.setattr(reshape_lib, "_Unstacker", MockUnstacker) + + +class TestDataFrameReshape: + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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 = pd.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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_mixed_level(self, future_stack): + # GH 18310 + levels = [range(3), [3, "a", "b"], [1, 2]] + + # flat columns: + df = pd.DataFrame(1, index=levels[0], columns=levels[1]) + result = df.stack(future_stack=future_stack) + expected = pd.Series(1, index=pd.MultiIndex.from_product(levels[:2])) + tm.assert_series_equal(result, expected) + + # MultiIndex columns: + df = pd.DataFrame( + 1, index=levels[0], columns=pd.MultiIndex.from_product(levels[1:]) + ) + result = df.stack(1, future_stack=future_stack) + expected = pd.DataFrame( + 1, + index=pd.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): + # Gh#34708 + df = pd.DataFrame({"x": [1, 2, np.nan], "y": [3.0, 4, np.nan]}) + df2 = df[["x"]] + df2["y"] = df["y"] + assert len(df2._mgr.blocks) == 2 + + res = df2.unstack() + expected = df.unstack() + tm.assert_series_equal(res, expected) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_unstack_fill(self, future_stack): + # GH #9746: fill_value keyword argument for Series + # and DataFrame unstack + + # From a series + data = pd.Series([1, 2, 4, 5], dtype=np.int16) + data.index = pd.MultiIndex.from_tuples( + [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")] + ) + + result = data.unstack(fill_value=-1) + expected = pd.DataFrame( + {"a": [1, -1, 5], "b": [2, 4, -1]}, index=["x", "y", "z"], dtype=np.int16 + ) + tm.assert_frame_equal(result, expected) + + msg = ( + "Using a fill_value that cannot be held in the existing dtype is deprecated" + ) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + # From a series with incorrect data type for fill_value + result = data.unstack(fill_value=0.5) + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame(rows, columns=list("AB"), dtype=np.int32) + df.index = pd.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 = pd.DataFrame(rows, index=list("xyz"), dtype=np.int32) + expected.columns = pd.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) + + msg = ( + "Using a fill_value that cannot be held in the existing dtype is deprecated" + ) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + # 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 = pd.DataFrame(rows, index=list("xyz"), dtype=float) + expected.columns = pd.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 = pd.date_range("2012-01-01", periods=4).values + data = pd.Series(dv) + data.index = pd.MultiIndex.from_tuples( + [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")] + ) + + result = data.unstack() + expected = pd.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 = pd.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 = [pd.Timedelta(days=i) for i in range(4)] + data = pd.Series(td) + data.index = pd.MultiIndex.from_tuples( + [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")] + ) + + result = data.unstack() + expected = pd.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 = pd.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 = [ + pd.Period("2012-01"), + pd.Period("2012-02"), + pd.Period("2012-03"), + pd.Period("2012-04"), + ] + data = pd.Series(periods) + data.index = pd.MultiIndex.from_tuples( + [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")] + ) + + result = data.unstack() + expected = pd.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 = pd.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 = pd.Series(["a", "b", "c", "a"], dtype="category") + data.index = pd.MultiIndex.from_tuples( + [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")] + ) + + # By default missing values will be NaN + result = data.unstack() + expected = pd.DataFrame( + { + "a": pd.Categorical(["a", None, "a"], categories=list("abc")), + "b": pd.Categorical(["b", "c", None], 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 = pd.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 = pd.MultiIndex.from_product( + [["a", "b", "c"], [1, 2, 3]], names=[("A", "a"), ("B", "b")] + ) + df = pd.DataFrame({"d": [1] * 9, "e": [2] * 9}, index=idx) + result = df.unstack(("A", "a")) + + expected = pd.DataFrame( + [[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2]], + columns=pd.MultiIndex.from_tuples( + [ + ("d", "a"), + ("d", "b"), + ("d", "c"), + ("e", "a"), + ("e", "b"), + ("e", "c"), + ], + names=[None, ("A", "a")], + ), + index=pd.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]], + pd.MultiIndex.from_tuples( + [(1, 3), (1, 4), (2, 3), (2, 4)], names=["B", "C"] + ), + pd.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]], + pd.Index([3, 4], name="C"), + pd.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 = pd.MultiIndex.from_product( + [["a", "b"], [1, 2], [3, 4]], names=[("A", "a"), "B", "C"] + ) + df = pd.DataFrame({"d": [1] * 8, "e": [2] * 8}, index=idx) + result = df.unstack(unstack_idx) + + expected = pd.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 = pd.DataFrame( + { + "state": ["IL", "MI", "NC"], + "index": ["a", "b", "c"], + "some_categories": pd.Series(["a", "b", "c"]).astype("category"), + "A": np.random.default_rng(2).random(3), + "B": 1, + "C": "foo", + "D": pd.Timestamp("20010102"), + "E": pd.Series([1.0, 50.0, 100.0]).astype("float32"), + "F": pd.Series([3.0, 4.0, 5.0]).astype("float64"), + "G": False, + "H": pd.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") + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_ints(self, future_stack): + columns = pd.MultiIndex.from_tuples(list(itertools.product(range(3), repeat=3))) + df = pd.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 + ), + ) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_mixed_levels(self, future_stack): + columns = pd.MultiIndex.from_tuples( + [ + ("A", "cat", "long"), + ("B", "cat", "long"), + ("A", "dog", "short"), + ("B", "dog", "short"), + ], + names=["exp", "animal", "hair_length"], + ) + df = pd.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, + ) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_int_level_names(self, future_stack): + columns = pd.MultiIndex.from_tuples( + [ + ("A", "cat", "long"), + ("B", "cat", "long"), + ("A", "dog", "short"), + ("B", "dog", "short"), + ], + names=["exp", "animal", "hair_length"], + ) + df = pd.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 = pd.DataFrame( + [False, False], + index=pd.MultiIndex.from_arrays([["a", "b"], ["c", "l"]]), + columns=["col"], + ) + rs = df.unstack() + xp = pd.DataFrame( + np.array([[False, np.nan], [np.nan, False]], dtype=object), + index=["a", "b"], + columns=pd.MultiIndex.from_arrays([["col", "col"], ["c", "l"]]), + ) + tm.assert_frame_equal(rs, xp) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_unstack_level_binding(self, future_stack): + # GH9856 + mi = pd.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 = pd.Series(0, index=mi) + result = s.unstack([1, 2]).stack(0, future_stack=future_stack) + + expected_mi = pd.MultiIndex( + levels=[["foo", "bar"], ["one", "two"]], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=["first", "second"], + ) + + expected = pd.DataFrame( + np.array( + [[0, np.nan], [np.nan, 0], [0, np.nan], [np.nan, 0]], dtype=np.float64 + ), + index=expected_mi, + columns=pd.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, pd.Series) + undo = data.unstack().T + tm.assert_frame_equal(undo, float_frame) + + # check NA handling + data = pd.DataFrame({"x": [1, 2, np.nan], "y": [3.0, 4, np.nan]}) + data.index = pd.Index(["a", "b", "c"]) + result = data.unstack() + + midx = pd.MultiIndex( + levels=[["x", "y"], ["a", "b", "c"]], + codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], + ) + expected = pd.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, using_infer_string): + # GH 2929 + rows = [[1, 1, 3, 4], [1, 2, 3, 4], [2, 1, 3, 4], [2, 2, 3, 4]] + + df = pd.DataFrame(rows, columns=list("ABCD")) + result = df.dtypes + expected = pd.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 = pd.Series( + [np.dtype("int64")] * 4, + index=pd.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 = pd.Series( + [np.dtype("float64")] * 2 + [np.dtype("int64")] * 2, + index=pd.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 + dtype = ( + pd.StringDtype(na_value=np.nan) + if using_infer_string + else np.dtype("object") + ) + expected = pd.Series( + [np.dtype("float64")] * 2 + [dtype] * 2, + index=pd.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 = pd.DataFrame( + { + "A": ["a"] * 5, + "C": c, + "D": d, + "B": pd.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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_unstack_non_unique_index_names(self, future_stack): + idx = pd.MultiIndex.from_tuples([("a", "b"), ("c", "d")], names=["c1", "c1"]) + df = pd.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 = pd.MultiIndex.from_product([["a"], ["A", "B", "C", "D"]])[:-1] + df = pd.DataFrame([[1, 0]] * 3, index=idx) + + result = df.unstack() + exp_col = pd.MultiIndex.from_product([range(2), ["A", "B", "C"]]) + expected = pd.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 = [range(3), range(4)] + codes = [[0, 0, 1, 1], [0, 2, 0, 2]] + idx = pd.MultiIndex(levels, codes) + block = np.arange(4).reshape(2, 2) + df = pd.DataFrame(np.concatenate([block, block + 4]), index=idx) + result = df.unstack() + expected = pd.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 = pd.MultiIndex(levels, codes) + data = np.arange(8) + df = pd.DataFrame(data.reshape(4, 2), index=idx) + + result = df.unstack(level=level) + exp_data = np.zeros(18) * np.nan + exp_data[idces] = data + cols = pd.MultiIndex.from_product([range(2), col_level]) + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame( + [[1]], + columns=pd.MultiIndex.from_tuples([[0]], names=["c1"]), + index=pd.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 = pd.DataFrame( + [[1]], + columns=pd.MultiIndex.from_tuples( + [[0, 0, 1, 0, 0, 0, 1]], + names=["c1", "i2", "i3", "i4", "i5", "i6", "i7"], + ), + index=pd.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 = pd.DataFrame( + [[0.0, 0.0], [0.0, 0.0]], + columns=pd.MultiIndex.from_tuples( + [["B", "C"], ["B", "D"]], names=["c1", "c2"] + ), + index=pd.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 = pd.DataFrame( + [[1, 2], [3, 4], [-1, -2], [-3, -4]], + columns=pd.MultiIndex.from_tuples([["a", "b", "c"], ["d", "e", "f"]]), + index=pd.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 = pd.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, strict=True): + 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", list(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 = pd.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, strict=True): + 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 = pd.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, strict=True))) + idx = pd.Index([np.nan, 0, 1, 2, 4, 5, 6, 7], name="B") + cols = pd.MultiIndex( + levels=[["C"], ["a", "b"]], codes=[[0, 0], [0, 1]], names=[None, "A"] + ) + + right = pd.DataFrame(vals, columns=cols, index=idx) + tm.assert_frame_equal(left, right) + + df = pd.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 = pd.MultiIndex( + levels=[["C"], ["a", "b"]], codes=[[0, 0], [0, 1]], names=[None, "A"] + ) + idx = pd.Index([np.nan, 0, 1, 2, 3], name="B") + right = pd.DataFrame(vals, columns=cols, index=idx) + tm.assert_frame_equal(left, right) + + df = pd.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 = pd.MultiIndex( + levels=[["C"], ["a", "b"]], codes=[[0, 0], [0, 1]], names=[None, "A"] + ) + idx = pd.Index([np.nan, 0, 1, 2, 3], name="B") + right = pd.DataFrame(vals, columns=cols, index=idx) + tm.assert_frame_equal(left, right) + + def test_unstack_nan_index3(self): + # GH7401 + df = pd.DataFrame( + { + "A": list("aaaaabbbbb"), + "B": (pd.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 = pd.Index(["a", "b"], name="A") + cols = pd.MultiIndex( + levels=[["C"], pd.date_range("2012-01-01", periods=5)], + codes=[[0, 0, 0, 0, 0, 0], [-1, 0, 1, 2, 3, 4]], + names=[None, "B"], + ) + + right = pd.DataFrame(vals, columns=cols, index=idx) + 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 = pd.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 = pd.MultiIndex( + levels=[[680585148, 680607017], [0.0133]], + codes=[[0, 1], [-1, 0]], + names=["s_id", "dosage"], + ) + + cols = pd.MultiIndex( + levels=[["change"], ["Ag", "Hg", "Pb", "Sn", "U"]], + codes=[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4]], + names=[None, "agent"], + ) + + right = pd.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 = pd.DataFrame( + { + "1st": [1, 2, 1, 2, 1, 2], + "2nd": pd.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 = pd.DataFrame( + [1, 2, 3, 4], columns=pd.MultiIndex.from_tuples([(t, "A", "B")]) + ) + warn = None if future_stack else Pandas4Warning + msg = "The previous implementation of stack is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = df.stack(future_stack=future_stack) + + eidx = pd.MultiIndex.from_product([range(4), ("B",)]) + ecols = pd.MultiIndex.from_tuples([(t, "A")]) + expected = pd.DataFrame([1, 2, 3, 4], index=eidx, columns=ecols) + tm.assert_frame_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + @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 = pd.MultiIndex.from_tuples( + [("B", "x"), ("B", "z"), ("A", "y"), ("C", "x"), ("C", "u")], + names=["Upper", "Lower"], + ) + multiindex = full_multiindex[multiindex_columns] + df = pd.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, pd.Series): + tm.assert_series_equal(result, expected) + else: + tm.assert_frame_equal(result, expected) + + df.columns = pd.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, pd.Series): + tm.assert_series_equal(result, expected) + else: + tm.assert_frame_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_full_multiIndex(self, future_stack): + # GH 8844 + full_multiindex = pd.MultiIndex.from_tuples( + [("B", "x"), ("B", "z"), ("A", "y"), ("C", "x"), ("C", "u")], + names=["Upper", "Lower"], + ) + df = pd.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 = pd.DataFrame( + [[0, 2], [1, np.nan], [3, 5], [4, np.nan]], + index=pd.MultiIndex( + levels=[range(2), ["u", "x", "y", "z"]], + codes=[[0, 0, 1, 1], [1, 3, 1, 3]], + names=[None, "Lower"], + ), + columns=pd.Index(["B", "C"], name="Upper"), + ) + expected["B"] = expected["B"].astype(df.dtypes.iloc[0]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + @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 = pd.DataFrame([[10, 11, 12]], columns=cidx) + result = df.stack(future_stack=future_stack) + + # `MultiIndex.from_product` preserves categorical dtype - + # it's tested elsewhere. + midx = pd.MultiIndex.from_product([df.index, cidx]) + expected = pd.Series([10, 11, 12], index=midx) + + tm.assert_series_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + @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 = pd.MultiIndex.from_product([cidx, cidx2]) + df = pd.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 = pd.Series( + expected_data, index=pd.MultiIndex.from_product([range(1), s_cidx, cidx2]) + ) + + tm.assert_series_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_preserve_categorical_dtype_values(self, future_stack): + # GH-23077 + cat = pd.Categorical(["a", "a", "b", "c"]) + df = pd.DataFrame({"A": cat, "B": cat}) + result = df.stack(future_stack=future_stack) + index = pd.MultiIndex.from_product([range(4), ["A", "B"]]) + expected = pd.Series( + pd.Categorical(["a", "a", "a", "a", "b", "b", "c", "c"]), index=index + ) + tm.assert_series_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + @pytest.mark.parametrize( + "index", + [ + [0, 0, 1, 1], + [0, 0, 2, 3], + [0, 1, 2, 3], + ], + ) + def test_stack_multi_columns_non_unique_index(self, index, future_stack): + # GH-28301 + columns = pd.MultiIndex.from_product([[1, 2], ["a", "b"]]) + df = pd.DataFrame(index=index, columns=columns).fillna(1) + stacked = df.stack(future_stack=future_stack) + new_index = pd.MultiIndex.from_tuples(stacked.index.to_numpy()) + expected = pd.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.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + @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 = pd.DataFrame( + { + ("A", 1): pd.Series(vals1, dtype=dtype1), + ("A", 2): pd.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 = pd.MultiIndex.from_tuples( + [("A", 0), ("A", 1), ("B", 1)], names=["a", "b"] + ) + df = pd.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 = pd.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 = pd.MultiIndex.from_product([range(1), ["d", "c"]], names=["bar", "baz"]) + df = pd.DataFrame([[0, 2], [1, 3]], index=mi, columns=["B", "A"]) + df.columns.name = "foo" + + expected = pd.DataFrame( + [[3, 1, 2, 0]], + columns=pd.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 = pd.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=0, sort=False) + + if frame_or_series is pd.DataFrame: + expected_columns = pd.MultiIndex.from_tuples([(0, "two"), (0, "one")]) + else: + expected_columns = ["two", "one"] + expected = pd.DataFrame( + [[1.0, 3.0], [2.0, 4.0]], + index=pd.MultiIndex.from_tuples([("z", "b"), ("y", "a")]), + columns=expected_columns, + dtype=dtype, + ) + tm.assert_frame_equal(result, expected) + + result = obj.unstack(level=-1, sort=False) + + if frame_or_series is pd.DataFrame: + expected_columns = pd.MultiIndex( + levels=[range(1), ["b", "a"]], codes=[[0, 0], [0, 1]] + ) + else: + expected_columns = ["b", "a"] + + item = pd.NA if dtype == "Float64" else np.nan + expected = pd.DataFrame( + [[1.0, item], [item, 2.0], [3.0, item], [item, 4.0]], + columns=expected_columns, + index=pd.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 pd.DataFrame: + expected_columns = pd.MultiIndex( + levels=[range(1), ["z", "y"], ["b", "a"]], codes=[[0, 0], [0, 1], [0, 1]] + ) + else: + expected_columns = pd.MultiIndex.from_tuples([("z", "b"), ("y", "a")]) + expected = pd.DataFrame( + [[1.0, 2.0], [3.0, 4.0]], + index=["two", "one"], + columns=expected_columns, + dtype=dtype, + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "levels2, expected_columns", + [ + ( + [None, 1, 2, 3], + [("value", np.nan), ("value", 1), ("value", 2), ("value", 3)], + ), + ( + [1, None, 2, 3], + [("value", 1), ("value", np.nan), ("value", 2), ("value", 3)], + ), + ( + [1, 2, None, 3], + [("value", 1), ("value", 2), ("value", np.nan), ("value", 3)], + ), + ( + [1, 2, 3, None], + [("value", 1), ("value", 2), ("value", 3), ("value", np.nan)], + ), + ], + ids=["nan=first", "nan=second", "nan=third", "nan=last"], +) +def test_unstack_sort_false_nan(levels2, expected_columns): + # GH#61221 + levels1 = ["b", "a"] + index = pd.MultiIndex.from_product([levels1, levels2], names=["level1", "level2"]) + df = pd.DataFrame({"value": [0, 1, 2, 3, 4, 5, 6, 7]}, index=index) + result = df.unstack(level="level2", sort=False) + expected_data = [[0, 4], [1, 5], [2, 6], [3, 7]] + expected = pd.DataFrame( + dict(zip(expected_columns, expected_data, strict=True)), + index=pd.Index(["b", "a"], name="level1"), + columns=pd.MultiIndex.from_tuples(expected_columns, names=[None, "level2"]), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "levels2", + [ + [np.nan, 8.0, 7.0], + [8.0, np.nan, 7.0], + [8.0, 7.0, np.nan], + ], + ids=["nan=first", "nan=second", "nan=last"], +) +def test_unstack_sort_false_nan_series(levels2): + # GH#66672 + index = pd.MultiIndex.from_product([["r"], levels2], names=["x", "z"]) + ser = pd.Series([1.0, 2.0, 3.0], index=index) + + result = ser.unstack(level="z", sort=False) + + expected = pd.DataFrame( + [[1.0, 2.0, 3.0]], + index=pd.Index(["r"], name="x"), + columns=pd.Index(levels2, name="z"), + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_sort_false_unsorted_with_gaps(): + # Unsorted MI with missing combinations, unstacking non-last level + # with sort=False. Exercises the identity=False, mask_all=False, + # sort=False path through _Unstacker.get_new_values. + index = pd.MultiIndex.from_tuples([("b", 1), ("a", 2), ("b", 2)], names=["x", "y"]) + ser = pd.Series([10, 20, 30], index=index) + result = ser.unstack(level=0, sort=False) + expected = pd.DataFrame( + {"b": [10.0, 30.0], "a": [np.nan, 20.0]}, + index=pd.Index([1, 2], name="y"), + columns=pd.Index(["b", "a"], name="x"), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("frame", [False, True]) +@pytest.mark.parametrize("dtype", ["int64", "Int64", "int64[pyarrow]"]) +def test_unstack_sort_false_multiple_remaining_levels(frame, dtype): + # GH#62816 With two or more levels left over, the result rows + # follow first appearance, but the values were laid out in lexicographic + # order of the remaining codes, so they landed under the wrong labels. + # The extension dtypes go through BlockManager.unstack instead of + # _Unstacker.get_result, which consumes the same machinery differently. + if dtype == "int64[pyarrow]": + pytest.importorskip("pyarrow") + index = pd.MultiIndex.from_tuples( + [(2, "a", 9), (1, "c", 9), (2, "c", 9)], names=["x", "y", "z"] + ) + obj = pd.Series([10, 20, 30], index=index, dtype=dtype) + expected_index = pd.MultiIndex.from_tuples( + [(2, "a"), (1, "c"), (2, "c")], names=["x", "y"] + ) + if frame: + obj = obj.to_frame("val") + expected_columns = pd.MultiIndex.from_tuples([("val", 9)], names=[None, "z"]) + else: + expected_columns = pd.Index([9], name="z") + + result = obj.unstack(level=2, sort=False) + + expected = pd.DataFrame( + [[10], [20], [30]], + index=expected_index, + columns=expected_columns, + dtype=dtype, + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_sort_false_multiple_remaining_levels_with_gaps(): + # GH#62816 As above, but with missing combinations so the values go through + # the masked fill path rather than the plain reshape. + index = pd.MultiIndex.from_tuples( + [(2, "a", 9), (1, "c", 8), (2, "c", 9), (1, "c", 9)], names=["x", "y", "z"] + ) + ser = pd.Series([10.0, 20.0, 30.0, 40.0], index=index) + + result = ser.unstack(level=2, sort=False) + + expected = pd.DataFrame( + [[10.0, np.nan], [40.0, 20.0], [30.0, np.nan]], + index=pd.MultiIndex.from_tuples( + [(2, "a"), (1, "c"), (2, "c")], names=["x", "y"] + ), + columns=pd.Index([9, 8], name="z"), + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_sort_false_nan_in_unstacked_level_one_remaining_level(): + # GH#62816 A single remaining level is enough to misplace values once the + # unstacked level holds NaN: the sort indexer sized that level from its + # length while renumbering its codes, so the NaN column collided with the + # next row. Distinct mechanism from the >=2-remaining-levels case. + index = pd.MultiIndex.from_tuples( + [("r0", np.nan), ("r1", np.nan), ("r0", "u0")], names=["r", "u"] + ) + ser = pd.Series([1.0, 2.0, 3.0], index=index) + + result = ser.unstack(sort=False) + + expected = pd.DataFrame( + [[1.0, 3.0], [2.0, np.nan]], + index=pd.Index(["r0", "r1"], name="r"), + columns=pd.Index([np.nan, "u0"], name="u"), + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_sort_false_does_not_collapse_rows(): + # GH#62816 Distinct index combinations were merged into a single result + # row, silently dropping data rather than only mislabelling it. + index = pd.MultiIndex.from_tuples([(np.nan, np.nan, np.nan), ("a0", "b0", np.nan)]) + ser = pd.Series([1.0, 2.0], index=index) + + result = ser.unstack(0, sort=False) + + expected = pd.DataFrame( + [[1.0, np.nan], [np.nan, 2.0]], + index=pd.MultiIndex.from_tuples([(np.nan, np.nan), ("b0", np.nan)]), + columns=pd.Index([np.nan, "a0"]), + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_multiple_sort_false_multiple_remaining_levels(): + # GH#62816 _unstack_multiple routes through the same _Unstacker, so + # unstacking several levels at once and leaving two or more behind hit + # the same misplacement. + index = pd.MultiIndex.from_tuples( + [(2, "a", 9, "p"), (1, "c", 9, "p"), (2, "c", 9, "p")], + names=["x", "y", "z", "w"], + ) + ser = pd.Series([10.0, 20.0, 30.0], index=index) + + result = ser.unstack(["z", "w"], sort=False) + + expected = pd.DataFrame( + [[10.0], [20.0], [30.0]], + index=pd.MultiIndex.from_tuples( + [(2, "a"), (1, "c"), (2, "c")], names=["x", "y"] + ), + columns=pd.MultiIndex.from_tuples([(9, "p")], names=["z", "w"]), + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_monotonic_values_unsorted_codes(): + # GH#65107 An MI whose tuple *values* are monotonic but whose codes are + # unsorted (here level 0 has unsorted levels ['b', 'a']) must still be + # reordered before reshaping. Previously the identity-indexer fast path + # keyed off index.is_monotonic_increasing, which reflects values not + # codes, so it skipped the take and placed values under the wrong labels. + index = pd.MultiIndex( + levels=[["b", "a"], [1, 2]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]] + ) + # tuples are ("a", 1), ("a", 2), ("b", 1), ("b", 2) + ser = pd.Series([10, 20, 30, 40], index=index) + result = ser.unstack() + expected = pd.DataFrame( + {1: [30, 10], 2: [40, 20]}, + index=pd.Index(["b", "a"]), + columns=pd.Index([1, 2]), + ) + tm.assert_frame_equal(result, expected) + # ("a", 1) -> 10 must land under row "a", not row "b" + assert result.loc["a", 1] == 10 + + +@pytest.mark.parametrize("sort", [True, False]) +@pytest.mark.parametrize("dtype", ["int64", "Int64", "mixed"]) +@pytest.mark.parametrize( + "level, level_codes", + [(["x", np.nan], [0, -1]), ([np.nan, "x"], [1, -1])], + ids=["unused-last", "unused-first"], +) +def test_unstack_level_with_unused_entry(sort, dtype, level, level_codes): + # GH#68588 remove_unused_levels returns the index unpruned when a level holds + # NaN as a value (GH#37510), so the unstacked level can keep a value no row + # uses. That entry used to get a column of its own, duplicating the NaN + # column under sort=True and leaving the blocks out of step with the columns + # under sort=False. + index = pd.MultiIndex( + levels=[["a", "b"], level], codes=[[0, 1], level_codes], names=["i", "j"] + ) + if dtype == "mixed": + # two numpy blocks: the one shape that used to corrupt silently rather + # than raise, so the to_numpy check below has something to catch + df = pd.DataFrame({"A": [1, 2], "B": [3.0, 4.0]}, index=index) + else: + df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=index, dtype=dtype) + + result = df.unstack("j", sort=sort) + + if sort: + # the unused entry stays in the level, but no code points at it + col_level, x_pos = level, level.index("x") + codes = [-1, x_pos, -1, x_pos] + values = [[np.nan, 1.0, np.nan, 3.0], [2.0, np.nan, 4.0, np.nan]] + else: + col_level = ["x"] + codes = [0, -1, 0, -1] + values = [[1.0, np.nan, 3.0, np.nan], [np.nan, 2.0, np.nan, 4.0]] + expected = pd.DataFrame( + values, + index=pd.Index(["a", "b"], name="i"), + columns=pd.MultiIndex( + levels=[["A", "B"], col_level], + codes=[[0, 0, 1, 1], codes], + names=[None, "j"], + ), + ) + if dtype == "Int64": + # an EA column keeps its dtype, and unstacks through ExtensionBlock + expected = expected.astype(dtype) + tm.assert_frame_equal(result, expected) + # assert_frame_equal reads the columns one at a time, so it does not notice + # blocks that are wider than the placement they were given + tm.assert_numpy_array_equal(result.to_numpy(), expected.to_numpy()) + + +@pytest.mark.parametrize("sort", [True, False]) +def test_unstack_unused_entry_from_nan_in_other_level(sort): + # GH#68588 The NaN that stops remove_unused_levels can sit in a different + # level, leaving the unstacked level holding an ordinary unused value. + index = pd.MultiIndex( + levels=[["x", np.nan], ["a", "b", "c"]], + codes=[[0, -1, 0], [0, 1, 1]], + names=["i", "j"], + ) + ser = pd.Series([1.0, 2.0, 3.0], index=index) + + result = ser.unstack("j", sort=sort) + + order = [np.nan, "x"] if sort else ["x", np.nan] + expected = pd.DataFrame( + [[np.nan, 2.0], [1.0, 3.0]] if sort else [[1.0, 3.0], [np.nan, 2.0]], + index=pd.Index(order, name="i"), + columns=pd.Index(["a", "b"], name="j"), + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_fill_frame_object(): + # GH12815 Test unstacking with object. + data = pd.Series(["a", "b", "c", "a"], dtype="object") + data.index = pd.MultiIndex.from_tuples( + [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")] + ) + + # By default missing values will be NaN + result = data.unstack() + expected = pd.DataFrame( + {"a": ["a", np.nan, "a"], "b": ["b", "c", np.nan]}, + index=list("xyz"), + dtype=object, + ) + tm.assert_frame_equal(result, expected) + + # Fill with any value replaces missing values as expected + result = data.unstack(fill_value="d") + expected = pd.DataFrame( + {"a": ["a", "d", "a"], "b": ["b", "c", "d"]}, index=list("xyz"), dtype=object + ) + tm.assert_frame_equal(result, expected) + + +def test_unstack_timezone_aware_values(): + # GH 18338 + df = pd.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 = pd.DataFrame( + [[pd.Timestamp("2017-08-27 01:00:00.709949+0000", tz="UTC"), "c"]], + index=pd.Index(["a"], name="a"), + columns=pd.MultiIndex( + levels=[["timestamp", "c"], ["b"]], + codes=[[0, 1], [0, 0]], + names=[None, "b"], + ), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore:The previous implementation of stack is deprecated") +def test_stack_timezone_aware_values(future_stack): + # GH 19420 + ts = pd.date_range( + freq="D", start="20180101", end="20180103", tz="America/New_York" + ) + df = pd.DataFrame({"A": ts}, index=["a", "b", "c"]) + result = df.stack(future_stack=future_stack) + expected = pd.Series( + ts, + index=pd.MultiIndex( + levels=[["a", "b", "c"], ["A"]], codes=[[0, 1, 2], [0, 0, 0]] + ), + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore:The previous implementation of stack is deprecated") +@pytest.mark.parametrize("dropna", [True, False, lib.no_default]) +def test_stack_empty_frame(dropna, future_stack): + # GH 36113 + levels = [pd.RangeIndex(0), pd.RangeIndex(0)] + expected = pd.Series( + dtype=np.float64, index=pd.MultiIndex(levels=levels, codes=[[], []]) + ) + if future_stack and dropna is not lib.no_default: + with pytest.raises(ValueError, match="dropna must be unspecified"): + pd.DataFrame(dtype=np.float64).stack( + dropna=dropna, future_stack=future_stack + ) + else: + result = pd.DataFrame(dtype=np.float64).stack( + dropna=dropna, future_stack=future_stack + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore:The previous implementation of stack is deprecated") +@pytest.mark.parametrize("dropna", [True, False, lib.no_default]) +def test_stack_empty_level(dropna, future_stack, int_frame): + # GH 60740 + if future_stack and dropna is not lib.no_default: + with pytest.raises(ValueError, match="dropna must be unspecified"): + pd.DataFrame(dtype=np.int64).stack(dropna=dropna, future_stack=future_stack) + else: + expected = int_frame + result = int_frame.copy().stack( + level=[], dropna=dropna, future_stack=future_stack + ) + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame() + result = pd.DataFrame().stack( + level=[], dropna=dropna, future_stack=future_stack + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore:The previous implementation of stack is deprecated") +@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"): + pd.DataFrame(dtype=np.int64).stack( + dropna=dropna, future_stack=future_stack + ).unstack(fill_value=fill_value) + else: + result = ( + pd.DataFrame(dtype=np.int64) + .stack(dropna=dropna, future_stack=future_stack) + .unstack(fill_value=fill_value) + ) + expected = pd.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): + pd.Series(dtype=np.int64).unstack() + + +def test_unstacking_multi_index_df(): + # see gh-30740 + df = pd.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 = pd.DataFrame( + [[9.5, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 8.0]], + index=pd.Index(["Alice", "Bob"], name="name"), + columns=pd.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) + + +@pytest.mark.filterwarnings("ignore:The previous implementation of stack is deprecated") +def test_stack_positional_level_duplicate_column_names(future_stack): + # https://github.com/pandas-dev/pandas/issues/36353 + columns = pd.MultiIndex.from_product([("x", "y"), ("y", "z")], names=["a", "a"]) + df = pd.DataFrame([[1, 1, 1, 1]], columns=columns) + result = df.stack(0, future_stack=future_stack) + + new_columns = pd.Index(["y", "z"], name="a") + new_index = pd.MultiIndex( + levels=[range(1), ["x", "y"]], codes=[[0, 0], [0, 1]], names=[None, "a"] + ) + expected = pd.DataFrame([[1, 1], [1, 1]], index=new_index, columns=new_columns) + + tm.assert_frame_equal(result, expected) + + +def test_unstack_non_slice_like_blocks(): + # Case where the mgr_locs of a DataFrame's underlying blocks are not slice-like + + mi = pd.MultiIndex.from_product([range(5), ["A", "B", "C"]]) + df = pd.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, + ) + 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) + + +@pytest.mark.filterwarnings("ignore:The previous implementation of stack is deprecated") +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 = pd.DataFrame( + data, + columns=pd.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 = pd.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=pd.MultiIndex.from_arrays( + [[0, 0, 1, 1, 2, 2], ["B", "A", "B", "A", "B", "A"]] + ), + ) + else: + expected = pd.DataFrame( + {"x": [1.0, 3.0, 2.0, 4.0, 3.0], "y": [2.0, 4.0, 3.0, 5.0, 4.0]}, + index=pd.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 = pd.DataFrame( + data, + columns=pd.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) + + +@pytest.mark.filterwarnings("ignore:The previous implementation of stack is deprecated") +def test_stack_sort_false_multi_level(future_stack): + # GH 15105 + idx = pd.MultiIndex.from_tuples([("weight", "kg"), ("height", "m")]) + df = pd.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 = pd.MultiIndex.from_tuples( + [ + ("cat", "weight", "kg"), + ("cat", "height", "m"), + ("dog", "weight", "kg"), + ("dog", "height", "m"), + ] + ) + expected = pd.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 = pd.DataFrame(result_rows, columns=result_columns).set_index( + ["ix1", "ix2"] + ) + result = result.iloc[1:2].unstack("ix2") + expected = pd.DataFrame( + [expected_row], + columns=pd.MultiIndex.from_product( + [result_columns[2:], [index_product]], names=[None, "ix2"] + ), + index=pd.Index([2], name="ix1"), + ) + tm.assert_frame_equal(result, expected) + + def test_unstack_multiple_no_empty_columns(self): + index = pd.MultiIndex.from_tuples( + [(0, "foo", 0), (0, "bar", 0), (1, "baz", 1), (1, "qux", 1)] + ) + + s = pd.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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + @pytest.mark.parametrize( + "idx, exp_idx", + [ + [ + list("abab"), + pd.MultiIndex( + levels=[["a", "b"], ["1st", "2nd"]], + codes=[np.tile(np.arange(2).repeat(3), 2), np.tile([0, 1, 0], 4)], + ), + ], + [ + pd.MultiIndex.from_tuples((("a", 2), ("b", 1), ("a", 1), ("b", 2))), + pd.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, exp_idx, future_stack): + # GH10417 + df = pd.DataFrame( + np.arange(12).reshape(4, 3), + index=idx, + columns=["1st", "2nd", "1st"], + ) + 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 = pd.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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_unstack_odd_failure(self, future_stack): + mi = pd.MultiIndex.from_arrays( + [ + ["Fri"] * 4 + ["Sat"] * 2 + ["Sun"] * 2 + ["Thu"] * 3, + ["Dinner"] * 2 + ["Lunch"] * 2 + ["Dinner"] * 5 + ["Lunch"] * 2, + ["No", "Yes"] * 4 + ["No", "No", "Yes"], + ], + names=["day", "time", "smoker"], + ) + df = pd.DataFrame( + { + "sum": np.arange(11, dtype="float64"), + "len": np.arange(11, dtype="float64"), + }, + index=mi, + ) + # 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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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 + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_unstack_bug(self, future_stack): + df = pd.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)) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + @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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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]) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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) + + @pytest.mark.parametrize("level", [[0, 0], ["l0", "l0"], [2, -1], [1, -2]]) + def test_stack_duplicate_levels(self, level): + # GH#66588 + columns = pd.MultiIndex.from_product( + [["A", "B"], ["c", "d"], ["e", "f"]], names=["l0", "l1", "l2"] + ) + df = pd.DataFrame(np.arange(8).reshape(1, 8), columns=columns) + + with pytest.raises(ValueError, match="level should not contain duplicate"): + df.stack(level) + + 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 = pd.Index(["A", "B"] * 3, name="str") + value = [1, 2, 3, 4, 5, 6] + + idx = pd.MultiIndex.from_arrays([idx1, idx2]) + s = pd.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 = pd.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 = pd.MultiIndex.from_arrays([idx1, idx2]) + s = pd.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 = pd.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 = pd.MultiIndex.from_arrays([idx1, idx2]) + df = pd.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 = pd.MultiIndex.from_arrays(["A A A B B B".split(), e_2]) + expected = pd.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 = pd.MultiIndex.from_arrays(["A A B B".split(), e_1]) + expected = pd.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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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 = pd.DataFrame({"ID": id_col, "NAME": name, "DATE": date, "VAR1": var1}) + + multi = df.set_index(["DATE", "ID"]) + multi.columns.name = "Params" + unst = multi.unstack("ID") + 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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_dropna(self, future_stack): + # GH#3997 + df = pd.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 = pd.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 = pd.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") + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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 = pd.MultiIndex(levels, codes) + + df = pd.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) + + def test_unstack_number_of_levels_larger_than_int32_warns( + self, performance_warning, mock_unstacker + ): + # GH#20601 + # GH#26314: Change ValueError to PerformanceWarning + df = pd.DataFrame( + np.zeros((2**16, 1)), + index=[np.arange(2**16), np.arange(2**16)], + ) + msg = f"may generate {2**32} cells" + with tm.assert_produces_warning(performance_warning, match=msg): + with pytest.raises(Exception, match="Don't compute final result."): + df.unstack() + + def test_unstack_number_of_levels_larger_than_int32_warns_multi_level( + self, performance_warning, mock_unstacker + ): + # GH#10582 the rows are the observed combinations of the remaining + # levels, not the size of the largest of them + # 16 two-valued levels, so 2**16 combinations, times 2**16 columns + codes = np.arange(2**16) + bits = (codes[:, None] >> np.arange(16)) & 1 + index = pd.MultiIndex.from_arrays([*bits.T, codes]) + df = pd.DataFrame(np.zeros((2**16, 1)), index=index) + msg = f"may generate {2**32} cells" + with tm.assert_produces_warning(performance_warning, match=msg): + with pytest.raises(Exception, match="Don't compute final result."): + df.unstack() + + def test_unstack_number_of_levels_larger_than_int32_warns_nan_column( + self, performance_warning, mock_unstacker + ): + # GH#10582 the NaN in the unstacked level gets a column of its own, + # which is what tips this just over the threshold + rows = np.arange(2**16 - 1) + columns = (rows % 2**15).astype(float) + columns[0] = np.nan + index = pd.MultiIndex.from_arrays([rows, columns]) + df = pd.DataFrame(np.zeros((2**16 - 1, 1)), index=index) + msg = f"may generate {(2**16 - 1) * (2**15 + 1)} cells" + with tm.assert_produces_warning(performance_warning, match=msg): + with pytest.raises(Exception, match="Don't compute final result."): + df.unstack() + + def test_unstack_number_of_levels_larger_than_int32_warns_nan_row( + self, performance_warning, mock_unstacker + ): + # GH#10582 the NaN in a level that is kept gets a row of its own, + # which is what tips this just over the threshold + columns = np.arange(2**16 - 1) + rows = (columns % 2**15).astype(float) + rows[0] = np.nan + index = pd.MultiIndex.from_arrays([rows, columns]) + df = pd.DataFrame(np.zeros((2**16 - 1, 1)), index=index) + msg = f"may generate {(2**15 + 1) * (2**16 - 1)} cells" + with tm.assert_produces_warning(performance_warning, match=msg): + with pytest.raises(Exception, match="Don't compute final result."): + df.unstack() + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + @pytest.mark.parametrize( + "levels", + list( + 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)) + def test_stack_order_with_unsorted_levels( + self, levels, stack_lev, sort, future_stack + ): + # GH#16323 + # deep check for 1-row case + columns = pd.MultiIndex(levels=levels, codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) + df = pd.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 + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_order_with_unsorted_levels_multi_row(self, future_stack): + # GH#16323 + + # check multi-row case + mi = pd.MultiIndex( + levels=[["A", "C", "B"], ["B", "A", "C"]], + codes=[np.repeat(range(3), 3), np.tile(range(3), 3)], + ) + df = pd.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 + ) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_order_with_unsorted_levels_multi_row_2(self, future_stack): + # GH#53636 + levels = ((0, 1), (1, 0)) + stack_lev = 1 + columns = pd.MultiIndex(levels=levels, codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) + df = pd.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 = pd.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 = pd.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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + 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 = pd.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 = pd.DataFrame( + [["a0", "b0"], ["a1", "b1"], ["a2", "b2"], ["a3", "b3"], ["a4", "b4"]], + index=range(5), + columns=pd.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, using_infer_string + ): + # 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_ + if not using_infer_string + else "string" + ) + assert unstacked["F", 1].dtype == np.float64 + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_unstack_group_index_overflow(self, future_stack): + codes = np.tile(np.arange(500), 2) + level = np.arange(500) + + index = pd.MultiIndex( + levels=[level] * 8 + [[0, 1]], + codes=[codes] * 8 + [np.arange(2).repeat(500)], + ) + + s = pd.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 = pd.MultiIndex( + levels=[[0, 1]] + [level] * 8, + codes=[np.arange(2).repeat(500)] + [codes] * 8, + ) + + s = pd.Series(np.arange(1000), index=index) + result = s.unstack(0) + assert result.shape == (500, 2) + + # put it in middle + index = pd.MultiIndex( + levels=[level] * 4 + [[0, 1]] + [level] * 4, + codes=([codes] * 4 + [np.arange(2).repeat(500)] + [codes] * 4), + ) + + s = pd.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): + # https://github.com/pandas-dev/pandas/issues/37115 + df = pd.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 + assert len(df._mgr.blocks) == 2 + + result = df.unstack("b") + result[("is_", "ca")] = result[("is_", "ca")].fillna(0) + + expected = pd.DataFrame( + [[10.0, 10.0, 1.0, 1.0], [np.nan, 10.0, 0.0, 1.0]], + index=pd.Index(["A", "B"], name="a"), + columns=pd.MultiIndex.from_tuples( + [("v", "ca"), ("v", "cb"), ("is_", "ca"), ("is_", "cb")], + names=[None, "b"], + ), + ) + tm.assert_frame_equal(result, expected) + + def test_unstack_with_level_has_nan(self): + # GH 37510 + df1 = pd.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 = pd.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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_nan_in_multiindex_columns(self, future_stack): + # GH#39481 + df = pd.DataFrame( + np.zeros([1, 5]), + columns=pd.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 = pd.MultiIndex( + levels=[[0], [0.0, 1.0]], codes=[[0, 0, 0], [-1, 0, 1]] + ) + columns = pd.MultiIndex(levels=[[0], [2, 3]], codes=[[0, 0, 0], [-1, 0, 1]]) + else: + index = pd.Index([(0, None), (0, 0), (0, 1)]) + columns = pd.Index([(0, None), (0, 2), (0, 3)]) + expected = pd.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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_multi_level_stack_categorical(self, future_stack): + # GH 15239 + midx = pd.MultiIndex.from_arrays( + [ + ["A"] * 2 + ["B"] * 2, + pd.Categorical(list("abab")), + pd.Categorical(list("ccdd")), + ] + ) + df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=midx) + result = df.stack([1, 2], future_stack=future_stack) + if future_stack: + expected = pd.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=pd.MultiIndex.from_arrays( + [ + [0] * 4 + [1] * 4, + pd.Categorical(list("abababab")), + pd.Categorical(list("ccddccdd")), + ] + ), + ) + else: + expected = pd.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=pd.MultiIndex.from_arrays( + [ + [0] * 4 + [1] * 4, + pd.Categorical(list("aabbaabb")), + pd.Categorical(list("cdcdcdcd")), + ] + ), + ) + tm.assert_frame_equal(result, expected, check_index_type=False) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_nan_level(self, future_stack): + # GH 9406 + df_nan = pd.DataFrame( + np.arange(4).reshape(2, 2), + columns=pd.MultiIndex.from_tuples( + [("A", np.nan), ("B", "b")], names=["Upper", "Lower"] + ), + index=pd.Index([0, 1], name="Num"), + dtype=np.float64, + ) + result = df_nan.stack(future_stack=future_stack) + if future_stack: + index = pd.MultiIndex( + levels=[[0, 1], [np.nan, "b"]], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=["Num", "Lower"], + ) + else: + index = pd.MultiIndex.from_tuples( + [(0, np.nan), (0, "b"), (1, np.nan), (1, "b")], names=["Num", "Lower"] + ) + expected = pd.DataFrame( + [[0.0, np.nan], [np.nan, 1], [2.0, np.nan], [np.nan, 3.0]], + columns=pd.Index(["A", "B"], name="Upper"), + index=index, + ) + tm.assert_frame_equal(result, expected) + + def test_unstack_categorical_columns(self): + # GH 14018 + idx = pd.MultiIndex.from_product([["A"], [0, 1]]) + df = pd.DataFrame({"cat": pd.Categorical(["a", "b"])}, index=idx) + result = df.unstack() + expected = pd.DataFrame( + { + 0: pd.Categorical(["a"], categories=["a", "b"]), + 1: pd.Categorical(["b"], categories=["a", "b"]), + }, + index=["A"], + ) + expected.columns = pd.MultiIndex.from_tuples([("cat", 0), ("cat", 1)]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_unsorted(self, future_stack): + # GH 16925 + PAE = ["ITA", "FRA"] + VAR = ["A1", "A2"] + TYP = ["CRT", "DBT", "NET"] + MI = pd.MultiIndex.from_product([PAE, VAR, TYP], names=["PAE", "VAR", "TYP"]) + + V = list(range(len(MI))) + DF = pd.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) + + @pytest.mark.filterwarnings( + "ignore:The previous implementation of stack is deprecated" + ) + def test_stack_nullable_dtype(self, future_stack): + # GH#43561 + columns = pd.MultiIndex.from_product( + [["54511", "54515"], ["r", "t_mean"]], names=["station", "element"] + ) + index = pd.Index([1, 2, 3], name="time") + + arr = np.array([[50, 226, 10, 215], [10, 215, 9, 220], [305, 232, 111, 220]]) + df = pd.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 = pd.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=pd.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 = pd.MultiIndex.from_arrays(arrays, names=("x", 0, "y")) + df = pd.DataFrame({"m": [1, 2]}, index=idx) + result = df.unstack("x") + expected = pd.DataFrame( + [[1], [2]], + columns=pd.MultiIndex.from_tuples([("m", "a")], names=[None, "x"]), + index=pd.MultiIndex.from_tuples([(1, "red"), (2, "blue")], names=[0, "y"]), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore:The previous implementation of stack is deprecated") +def test_stack_tuple_columns(future_stack): + # GH#54948 - test stack when the input has a non-MultiIndex with tuples + df = pd.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 = pd.Series( + [1, 2, 3, 4, 5, 6, 7, 8, 9], + index=pd.MultiIndex( + levels=[range(3), [("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) + + +@pytest.mark.parametrize( + "dtype, na_value", + [ + ("float64", np.nan), + ("Float64", np.nan), + ("Float64", pd.NA), + ("Int64", pd.NA), + ], +) +@pytest.mark.parametrize("test_multiindex", [True, False]) +def test_stack_preserves_na(dtype, na_value, test_multiindex): + # GH#56573 + if test_multiindex: + index = pd.MultiIndex.from_arrays(2 * [pd.Index([na_value], dtype=dtype)]) + else: + index = pd.Index([na_value], dtype=dtype) + df = pd.DataFrame({"a": [1]}, index=index) + result = df.stack() + + if test_multiindex: + expected_index = pd.MultiIndex.from_arrays( + [ + pd.Index([na_value], dtype=dtype), + pd.Index([na_value], dtype=dtype), + pd.Index(["a"]), + ] + ) + else: + expected_index = pd.MultiIndex.from_arrays( + [ + pd.Index([na_value], dtype=dtype), + pd.Index(["a"]), + ] + ) + expected = pd.Series(1, index=expected_index) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_subclass.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_subclass.py new file mode 100644 index 0000000000000000000000000000000000000000..9adba415628f99919802b941d1f2f078ffa4832a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_subclass.py @@ -0,0 +1,863 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameSubclassing: + def test_no_warning_on_mgr(self): + # GH#57032 + df = tm.SubclassedDataFrame( + {"X": [1, 2, 3], "Y": [1, 2, 3]}, index=["a", "b", "c"] + ) + with tm.assert_produces_warning(None): + # df.isna() goes through _constructor_from_mgr, which we want to + # *not* pass a Manager do __init__ + df.isna() + df["X"].isna() + + 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(pd.Series): + @property + def _constructor(self): + return CustomSeries + + def custom_series_function(self): + return "OK" + + class CustomDataFrame(pd.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 = pd.MultiIndex.from_tuples([("A", "A"), ("A", "B")]) + cdf_multi = CustomDataFrame([[0, 1], [2, 3]], columns=mcol) + assert isinstance(cdf_multi["A"], CustomDataFrame) + + mcol = pd.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, temp_file): + 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, temp_file) + 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(pd.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() + 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=pd.MultiIndex.from_tuples( + list(zip(list("AABB"), list("cdcd"), strict=True)), names=["aaa", "ccc"] + ), + columns=pd.MultiIndex.from_tuples( + list(zip(list("WWXX"), list("yzyz"), strict=True)), names=["www", "yyy"] + ), + ) + + exp = tm.SubclassedDataFrame( + [ + [10, 12], + [11, 13], + [20, 22], + [21, 23], + [30, 32], + [31, 33], + [40, 42], + [41, 43], + ], + index=pd.MultiIndex.from_tuples( + list( + zip( + list("AAAABBBB"), + list("ccddccdd"), + list("yzyzyzyz"), + strict=True, + ) + ), + names=["aaa", "ccc", "yyy"], + ), + columns=pd.Index(["W", "X"], name="www"), + ) + + res = df.stack() + tm.assert_frame_equal(res, exp) + + res = df.stack("yyy") + 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=pd.MultiIndex.from_tuples( + list( + zip( + list("AAAABBBB"), + list("ccddccdd"), + list("WXWXWXWX"), + strict=True, + ) + ), + names=["aaa", "ccc", "www"], + ), + columns=pd.Index(["y", "z"], name="yyy"), + ) + + res = df.stack("www") + 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=pd.MultiIndex.from_tuples( + list(zip(list("AABB"), list("cdcd"), strict=True)), names=["aaa", "ccc"] + ), + columns=pd.MultiIndex.from_tuples( + list(zip(list("WWXX"), list("yzyz"), strict=True)), 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=pd.MultiIndex.from_tuples( + list( + zip( + list("AAAABBBB"), + list("ccddccdd"), + list("yzyzyzyz"), + strict=True, + ) + ), + names=["aaa", "ccc", "yyy"], + ), + columns=pd.Index(["W", "X"], name="www"), + ) + + res = df.stack() + tm.assert_frame_equal(res, exp) + + res = df.stack("yyy") + 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=pd.MultiIndex.from_tuples( + list( + zip( + list("AAAABBBB"), + list("ccddccdd"), + list("WXWXWXWX"), + strict=True, + ) + ), + names=["aaa", "ccc", "www"], + ), + columns=pd.Index(["y", "z"], name="yyy"), + ) + + res = df.stack("www") + 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=pd.MultiIndex.from_tuples( + list(zip(list("AABB"), list("cdcd"), strict=True)), names=["aaa", "ccc"] + ), + columns=pd.MultiIndex.from_tuples( + list(zip(list("WWXX"), list("yzyz"), strict=True)), names=["www", "yyy"] + ), + ) + + exp = tm.SubclassedDataFrame( + [[10, 20, 11, 21, 12, 22, 13, 23], [30, 40, 31, 41, 32, 42, 33, 43]], + index=pd.Index(["A", "B"], name="aaa"), + columns=pd.MultiIndex.from_tuples( + list( + zip( + list("WWWWXXXX"), + list("yyzzyyzz"), + list("cdcdcdcd"), + strict=True, + ) + ), + 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=pd.Index(["c", "d"], name="ccc"), + columns=pd.MultiIndex.from_tuples( + list( + zip( + list("WWWWXXXX"), + list("yyzzyyzz"), + list("ABABABAB"), + strict=True, + ) + ), + 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=pd.MultiIndex.from_tuples( + list(zip(list("AABB"), list("cdcd"), strict=True)), names=["aaa", "ccc"] + ), + columns=pd.MultiIndex.from_tuples( + list(zip(list("WWXX"), list("yzyz"), strict=True)), 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=pd.Index(["A", "B"], name="aaa"), + columns=pd.MultiIndex.from_tuples( + list( + zip( + list("WWWWXXXX"), + list("yyzzyyzz"), + list("cdcdcdcd"), + strict=True, + ) + ), + 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=pd.Index(["c", "d"], name="ccc"), + columns=pd.MultiIndex.from_tuples( + list( + zip( + list("WWWWXXXX"), + list("yyzzyyzz"), + list("ABABABAB"), + strict=True, + ) + ), + 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, strict=True)), + } + ) + + 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=pd.MultiIndex.from_tuples( + list(zip(list("AABB"), list("cdcd"), strict=True)), names=["aaa", "ccc"] + ), + columns=pd.MultiIndex.from_tuples( + list(zip(list("WWXX"), list("yzyz"), strict=True)), 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): + # 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) + + def test_convert_dtypes_preserves_subclass_with_constructor(self): + class SubclassedDataFrame(pd.DataFrame): + @property + def _constructor(self): + return SubclassedDataFrame + + df = SubclassedDataFrame({"a": [1, 2, 3]}) + result = df.convert_dtypes() + assert isinstance(result, SubclassedDataFrame) + + 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 = pd.DataFrame({"a": [1, 2, 3]}) + df2 = tm.SubclassedDataFrame({"a": [1, 2, 3]}) + assert df1.equals(df2) + assert df2.equals(df1) + + +class MySubclassWithMetadata(pd.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) + + +def test_constructor_with_metadata_from_records(): + # GH#57008 + df = MySubclassWithMetadata.from_records([{"a": 1, "b": 2}]) + assert df.my_metadata is None + assert type(df) is MySubclassWithMetadata + + +class SimpleDataFrameSubClass(pd.DataFrame): + """A subclass of DataFrame that does not define a constructor.""" + + +class SimpleSeriesSubClass(pd.Series): + """A subclass of Series that does not define a constructor.""" + + +class TestSubclassWithoutConstructor: + def test_copy_df(self): + expected = pd.DataFrame({"a": [1, 2, 3]}) + result = SimpleDataFrameSubClass(expected).copy() + + assert ( + type(result) is pd.DataFrame + ) # assert_frame_equal only checks isinstance(lhs, type(rhs)) + tm.assert_frame_equal(result, expected) + + def test_copy_series(self): + expected = pd.Series([1, 2, 3]) + result = SimpleSeriesSubClass(expected).copy() + + tm.assert_series_equal(result, expected) + + def test_series_to_frame(self): + orig = pd.Series([1, 2, 3]) + expected = orig.to_frame() + result = SimpleSeriesSubClass(orig).to_frame() + + assert ( + type(result) is pd.DataFrame + ) # assert_frame_equal only checks isinstance(lhs, type(rhs)) + tm.assert_frame_equal(result, expected) + + def test_groupby(self): + df = SimpleDataFrameSubClass(pd.DataFrame({"a": [1, 2, 3]})) + + for _, v in df.groupby("a"): + assert type(v) is pd.DataFrame diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_ufunc.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_ufunc.py new file mode 100644 index 0000000000000000000000000000000000000000..7c189b2bbd274ca80c801d8f163c9f9cfa1f35e7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_ufunc.py @@ -0,0 +1,377 @@ +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.applymarker( + 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, strict=True): + 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) + + +def test_binary_ufunc_out_pandas_object(): + # GH#43190 passing a DataFrame as the ufunc `out` argument used to recurse + # infinitely (RecursionError / segfault) instead of writing the result. + a = pd.DataFrame([[1, 2]]) + b = pd.DataFrame([[3, 4]]) + out = pd.DataFrame([[0, 0]]) + + result = np.fmin(a, b, out=out) + + expected = pd.DataFrame([[1, 2]]) + tm.assert_frame_equal(result, expected) + # the result is also written into `out` in place + tm.assert_frame_equal(out, 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.applymarker( + 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.applymarker( + 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_input_aligns_duplicate_labels(): + # GH#54416 + df1 = pd.DataFrame([[1.0, 2.0], [3.0, 4.0]], columns=["A", "B"], index=[0, 0]) + df2 = pd.DataFrame([[5.0, 6.0], [7.0, 8.0]], columns=["C", "C"], index=[0, 1]) + result = np.heaviside(df1, df2) + expected = pd.DataFrame( + [[1.0, 1.0, np.nan, np.nan]] * 2 + [[np.nan] * 4], + index=[0, 0, 1], + columns=["A", "B", "C", "C"], + ) + 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) + + +@pytest.mark.single_cpu +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) + + +@pytest.mark.parametrize("func", [np.logical_and, np.logical_or, np.logical_xor]) +@pytest.mark.parametrize("dtype", ["datetime64[ns]", "period[D]"]) +def test_binary_logical_ufunc_datetimelike_raises(func, dtype): + # GH#68524 with two inputs a DataFrame np.asarray()s its columns before the + # ufunc runs, so the column's own guard never sees them + df = pd.DataFrame({"A": pd.array(["2016-01-01", "2016-01-02"], dtype=dtype)}) + other = pd.DataFrame({"A": [True, False]}) + + msg = f"cannot perform the numpy op {func.__name__}" + with pytest.raises(TypeError, match=msg): + func(other, df) + with pytest.raises(TypeError, match=msg): + func(df, other) + + +@pytest.mark.parametrize("func", [np.logical_and, np.logical_or, np.logical_xor]) +def test_binary_logical_ufunc_categorical_column_raises(func): + # GH#68524 the frame scan reads each block's dtype, and a Categorical hides + # its datetimes behind kind "O" + values = pd.Categorical(pd.to_datetime(["2016-01-01", "2016-01-02"])) + df = pd.DataFrame({"A": values}) + + msg = f"cannot perform the numpy op {func.__name__}" + with pytest.raises(TypeError, match=msg): + func(df, True) + + +@pytest.mark.parametrize("dtype", ["datetime64[ns, US/Pacific]", "period[D]"]) +def test_logical_not_ufunc_datetimelike_raises(dtype): + # GH#68524 one input takes the BlockManager.apply path instead, and these two + # dtypes returned a frame of False + df = pd.DataFrame({"A": pd.array(["2016-01-01", "2016-01-02"], dtype=dtype)}) + + with pytest.raises(TypeError, match="cannot perform the numpy op logical_not"): + np.logical_not(df) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/frame/test_unary.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_unary.py new file mode 100644 index 0000000000000000000000000000000000000000..4ca9612783892c3f28b7c28c5c7607adec4825f9 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_unary.py @@ -0,0 +1,181 @@ +from decimal import Decimal + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrameUnaryOperators: + # __pos__, __neg__, __invert__ + + @pytest.mark.parametrize( + "df_data,expected_data", + [ + ([-1, 1], [1, -1]), + ([False, True], [True, False]), + (pd.to_timedelta([-1, 1]), pd.to_timedelta([1, -1])), + ], + ) + def test_neg_numeric(self, df_data, expected_data): + df = pd.DataFrame({"a": df_data}) + expected = pd.DataFrame({"a": expected_data}) + 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_data", + [ + ["a", "b"], + pd.to_datetime(["2017-01-22", "1970-01-01"]), + ], + ) + def test_neg_raises(self, df_data, using_infer_string): + df = pd.DataFrame({"a": df_data}) + msg = "|".join( + [ + "bad operand type for unary -: 'str'", + "bad operand type for unary -: 'DatetimeArray'", + "unary '-' not supported for dtype", + ] + ) + 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_data", + [ + [-1, 1], + [False, True], + pd.to_timedelta([-1, 1]), + ], + ) + def test_pos_numeric(self, df_data): + # GH#16073 + df = pd.DataFrame({"a": df_data}) + tm.assert_frame_equal(+df, df) + tm.assert_series_equal(+df["a"], df["a"]) + + @pytest.mark.parametrize( + "df_data", + [ + np.array([-1, 2], dtype=object), + [Decimal("-1.0"), Decimal("2.0")], + ], + ) + def test_pos_object(self, df_data): + # GH#21380 + df = pd.DataFrame({"a": df_data}) + tm.assert_frame_equal(+df, df) + tm.assert_series_equal(+df["a"], df["a"]) + + def test_pos_object_raises(self): + # GH#21380 + df = pd.DataFrame({"a": ["a", "b"]}) + with pytest.raises( + TypeError, match=r"^bad operand type for unary \+: \'str\'$" + ): + tm.assert_frame_equal(+df, df) + + def test_pos_raises(self): + df = pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])}) + 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/venv/lib/python3.14/site-packages/pandas/tests/frame/test_validate.py b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..412f297ccf26d4b78e2b1e2878d8f3721f69a70d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/frame/test_validate.py @@ -0,0 +1,40 @@ +import pytest + +from pandas.core.frame import DataFrame + + +class TestDataFrameValidate: + """Tests for error handling related to data types of method arguments.""" + + @pytest.mark.filterwarnings( + "ignore:The inplace keyword:pandas.errors.Pandas4Warning" + ) + @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, func, inplace): + dataframe = DataFrame({"a": [1, 2], "b": [3, 4]}) + 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/venv/lib/python3.14/site-packages/pandas/tests/generic/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/generic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/generic/test_duplicate_labels.py b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_duplicate_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..4d65539a96d87b4fb2b6af69f9729924fbbc9100 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_duplicate_labels.py @@ -0,0 +1,405 @@ +"""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("index", [["a", "b", "c"], ["a", "b"]]) + # TODO: frame + @not_implemented + def test_align(self, index): + other = pd.Series(0, index=index) + 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 + + @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 + + def test_concat_mixed_allows_duplicate_labels(self): + # GH#57431 - when any input has allows_duplicate_labels=False, + # the result should also have it False + df_no_dups = pd.DataFrame({"A": [1, 2]}).set_flags( + allows_duplicate_labels=False + ) + df_allows_dups = pd.DataFrame({"A": [3, 4]}) + result = pd.concat([df_no_dups, df_allows_dups], ignore_index=True) + 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, + ), + # 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, + ), + # 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): + # Note: 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) + + def test_concat_raises(self): + objs = [ + pd.Series(1, index=[0, 1], name="a"), + pd.Series(2, index=[0, 1], name="a"), + ] + 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, axis=1) + + 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), + ], +) +@pytest.mark.filterwarnings( + "ignore:The inplace keyword in (Series|DataFrame).rename is" +) +@pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.reset_index is") +@pytest.mark.filterwarnings("ignore:The inplace keyword in DataFrame.set_index is") +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(temp_file): + a = pd.Series([1, 2]).set_flags(allows_duplicate_labels=False) + b = tm.round_trip_pickle(a, temp_file) + tm.assert_series_equal(a, b) + + a = pd.DataFrame({"A": []}).set_flags(allows_duplicate_labels=False) + b = tm.round_trip_pickle(a, temp_file) + tm.assert_frame_equal(a, b) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/generic/test_finalize.py b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..871f79f368d07a9a9d99a8ff55d0d5d3a3a5f19b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_finalize.py @@ -0,0 +1,813 @@ +""" +An exhaustive list of pandas methods exercising NDFrame.__finalize__. +""" + +from copy import deepcopy +from datetime import time +import operator +import re + +import numpy as np +import pytest + +from pandas._typing import MergeHow + +import pandas as pd +from pandas.core.computation.check import NUMEXPR_INSTALLED + +# 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, ([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("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)), + (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", time(12)), + ), + ( + pd.DataFrame, + ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)), + operator.methodcaller("at_time", time(12)), + ), + ( + 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, 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.mark.parametrize("ndframe_method", _all_methods, ids=lambda x: idfn(x[-1])) +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.skipif( + not NUMEXPR_INSTALLED, reason="numexpr not installed or an unsupported version" +) +@not_implemented_mark +def test_finalize_called_eval_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 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) + elif is_cmp and isinstance(left, pd.Series) and isinstance(right, pd.DataFrame): + right, left = right.align(left, axis=1) + + result = all_binary_operators(left, right) + assert result.attrs == {"a": 1} + + +@pytest.mark.parametrize("left", [pd.Series, pd.DataFrame]) +@pytest.mark.parametrize("right", [pd.Series, pd.DataFrame]) +def test_attrs_binary_operations(all_binary_operators, left, right): + # GH 51607 + attrs = {"a": 1} + left = left([1]) + left.attrs = attrs + right = right([2]) + assert all_binary_operators(left, right).attrs == attrs + assert all_binary_operators(right, left).attrs == attrs + + +# ---------------------------------------------------------------------------- +# 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", + "day_of_week", + "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", + "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: 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("prod"), + lambda x: x.agg("min"), + lambda x: x.agg("max"), + lambda x: x.agg("first"), + lambda x: x.agg("last"), + lambda x: x.agg("idxmin"), + lambda x: x.agg("idxmax"), + lambda x: x.agg("any"), + lambda x: x.agg("all"), + lambda x: x.agg("mean"), + lambda x: x.agg("median"), + lambda x: x.agg("std"), + lambda x: x.agg("var"), + lambda x: x.agg("sem"), + lambda x: x.agg("skew"), + lambda x: x.agg("kurt"), + ], +) +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]})] +) +def test_groupby_finalize_duplicate_labels(obj): + # GH#46505 ensure allows_duplicate_labels propagates through groupby splitter + obj = obj.set_flags(allows_duplicate_labels=False) + result = obj.groupby([0, 0]).sum() + assert result.flags.allows_duplicate_labels is False + + +@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("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 + + +# ---------------------------------------------------------------------------- +# Merge + + +@pytest.mark.parametrize( + ["allow_on_left", "allow_on_right"], + [(False, False), (False, True), (True, False), (True, True)], +) +@pytest.mark.parametrize( + "how", + [ + "left", + "right", + "inner", + "outer", + "left_anti", + "right_anti", + "cross", + ], +) +def test_merge_correctly_sets_duplication_allowance_flag( + how: MergeHow, + allow_on_left: bool, + allow_on_right: bool, +): + left = pd.DataFrame({"test": [1]}).set_flags(allows_duplicate_labels=allow_on_left) + right = pd.DataFrame({"test": [1]}).set_flags( + allows_duplicate_labels=allow_on_right, + ) + + if not how == "cross": + result = left.merge(right, how=how, on="test") + else: + result = left.merge(right, how=how) + + expected_duplication_allowance = allow_on_left and allow_on_right + assert result.flags.allows_duplicate_labels == expected_duplication_allowance + + +@pytest.mark.parametrize( + ["allow_on_left", "allow_on_right"], + [(False, False), (False, True), (True, False), (True, True)], +) +def test_merge_asof_correctly_sets_duplication_allowance_flag( + allow_on_left: bool, + allow_on_right: bool, +): + left = pd.DataFrame({"test": [1]}).set_flags(allows_duplicate_labels=allow_on_left) + right = pd.DataFrame({"test": [1]}).set_flags( + allows_duplicate_labels=allow_on_right, + ) + + result = pd.merge_asof(left, right) + + expected_duplication_allowance = allow_on_left and allow_on_right + assert result.flags.allows_duplicate_labels == expected_duplication_allowance + + +def test_merge_propagates_metadata_from_equal_input_metadata(): + metadata = {"a": [1, 2]} + left = pd.DataFrame({"test": [1]}) + left.attrs = metadata + right = pd.DataFrame({"test": [1]}) + right.attrs = deepcopy(metadata) + + result = left.merge(right, how="inner", on="test") + + assert result.attrs == metadata + + # Verify that merge deep-copies the attr dictionary. + assert result.attrs is not left.attrs + assert result.attrs is not right.attrs + assert result.attrs["a"] is not left.attrs["a"] + assert result.attrs["a"] is not right.attrs["a"] + + +def test_merge_does_not_propagate_metadata_from_unequal_input_metadata(): + left = pd.DataFrame({"test": [1]}) + left.attrs = {"a": 2} + right = pd.DataFrame({"test": [1]}) + right.attrs = {"b": 3} + + result = left.merge(right, how="inner", on="test") + + assert result.attrs == {} + + +@pytest.mark.parametrize( + ["left_has_metadata", "right_has_metadata", "expected"], + [ + (False, True, {}), + (True, False, {}), + (False, False, {}), + ], + ids=["left-empty", "right-empty", "both-empty"], +) +def test_merge_does_not_propagate_metadata_if_one_input_has_no_metadata( + left_has_metadata: bool, + right_has_metadata: bool, + expected: dict, +): + left = pd.DataFrame({"test": [1]}) + right = pd.DataFrame({"test": [1]}) + + if left_has_metadata: + left.attrs = {"a": [1, 2]} + else: + left.attrs = {} + + if right_has_metadata: + right.attrs = {"a": [1, 2]} + else: + right.attrs = {} + + result = left.merge(right, how="inner", on="test") + + assert result.attrs == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/generic/test_frame.py b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..2217bae8d5ae6f2b1d152bb702d5777ff293c140 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_frame.py @@ -0,0 +1,197 @@ +from copy import deepcopy +from operator import methodcaller +from typing import Literal + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDataFrame: + @pytest.mark.parametrize("func", ["_set_axis_name", "rename_axis"]) + def test_set_axis_name(self, func): + df = pd.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 = pd.DataFrame( + np.empty((3, 3)), + index=pd.MultiIndex.from_tuples([("A", x) for x in list("aBc")]), + columns=pd.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): + df = pd.DataFrame([[False, False]]) + msg_err = "The truth value of a DataFrame is ambiguous" + with pytest.raises(ValueError, match=msg_err): + bool(df) + + def test_metadata_propagation_indiv_groupby(self): + # groupby + df = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((1000, 2)), + index=pd.date_range("20130101", periods=1000, freq="s"), + ) + result = df.resample("1min") + tm.assert_metadata_equivalent(df, result) + + def test_metadata_propagation_indiv(self, monkeypatch): + # merging with override + # GH 6923 + + def finalize( + self: pd.DataFrame, + other: pd.DataFrame, + method: Literal["merge", "concat"] | None = None, + **kwargs, + ): + for name in self._metadata: + if method == "merge": + left, right = other.input_objs + value = getattr(left, name, "") + "|" + getattr(right, name, "") + object.__setattr__(self, name, value) + elif method == "concat": + value = "+".join( + [ + getattr(o, name) + for o in other.input_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(pd.DataFrame, "_metadata", ["filename"]) + m.setattr(pd.DataFrame, "__finalize__", finalize) + + df1 = pd.DataFrame( + np.random.default_rng(2).integers(0, 4, (3, 2)), columns=["a", "b"] + ) + df2 = pd.DataFrame( + np.random.default_rng(2).integers(0, 4, (3, 2)), columns=["c", "d"] + ) + pd.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 = pd.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 = pd.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"], pd.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 = pd.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.filterwarnings("ignore:The inplace keyword in") + @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0]) + def test_validate_bool_args(self, value): + df = pd.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 = pd.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/venv/lib/python3.14/site-packages/pandas/tests/generic/test_generic.py b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_generic.py new file mode 100644 index 0000000000000000000000000000000000000000..6385cbdf3052fe9620d87fb3149116ec882de938 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_generic.py @@ -0,0 +1,489 @@ +from copy import ( + copy, + deepcopy, +) + +import numpy as np +import pytest + +from pandas.core.dtypes.common import is_scalar + +import pandas as pd +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")}, + pd.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, pd.DataFrame): + # preserve columns dtype + expected.columns = o.columns[:0] + tm.assert_equal(result, 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_get_bool_data_empty_preserve_index(self): + expected = pd.Series([], dtype="bool") + result = expected._get_bool_data() + tm.assert_series_equal(result, expected, check_index_type=True) + + 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) + 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_stdlib_copy_shallow_copies(self, frame_or_series): + obj = frame_or_series(range(3)) + obj_copy = copy(obj) + assert tm.shares_memory(obj, obj_copy) + + +class TestNDFrame: + # tests that don't fit elsewhere + + @pytest.mark.parametrize( + "ser", + [ + pd.Series(range(10), dtype=np.float64), + pd.Series([str(i) for i in range(10)], dtype=object), + ], + ) + def test_squeeze_series_noop(self, ser): + # noop + tm.assert_series_equal(ser.squeeze(), ser) + + def test_squeeze_frame_noop(self): + # noop + df = pd.DataFrame(np.eye(2)) + tm.assert_frame_equal(df.squeeze(), df) + + def test_squeeze_frame_reindex(self): + # squeezing + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ).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 = pd.Series([], name="five", dtype=np.float64) + empty_frame = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((1, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=1, freq="B"), + ).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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=3, freq="B"), + ) + tm.assert_frame_equal(df.squeeze(axis=0), df) + + def test_numpy_squeeze(self): + s = pd.Series(range(2), dtype=np.float64) + tm.assert_series_equal(np.squeeze(s), s) + + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ).reindex(columns=["A"]) + tm.assert_series_equal(np.squeeze(df), df["A"]) + + @pytest.mark.parametrize( + "ser", + [ + pd.Series(range(10), dtype=np.float64), + pd.Series([str(i) for i in range(10)], dtype=object), + ], + ) + 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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ) + tm.assert_frame_equal(df.transpose().transpose(), df) + + def test_numpy_transpose(self, frame_or_series): + obj = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ) + obj = tm.get_obj(obj, frame_or_series) + + if frame_or_series is pd.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", + [ + pd.Series(range(10), dtype=np.float64), + pd.Series([str(i) for i in range(10)], dtype=object), + ], + ) + def test_take_series(self, ser): + indices = [1, 5, -2, 6, 3, -1] + out = ser.take(indices) + expected = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ) + out = df.take(indices) + expected = pd.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 = pd.DataFrame(range(5)) + 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 = pd.Series([1, 2]) + if frame_or_series is pd.DataFrame: + obj = obj.to_frame() + + assert obj.flags is obj.flags + obj2 = obj.copy() + assert obj2.flags is not obj.flags diff --git a/venv/lib/python3.14/site-packages/pandas/tests/generic/test_label_or_level_utils.py b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_label_or_level_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..797f3d488ab18285fd2a829075f5bd06985b25a3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_label_or_level_utils.py @@ -0,0 +1,329 @@ +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 + + +# 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 a level reference + assert_level_reference(df_ambig, ["L2"], axis=axis) + + # df has a column named L3 and it is not a 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, axis): + df = df.set_index(["L1"]) + df_duplabels = pd.concat([df, df["L2"]], axis=1) + 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/venv/lib/python3.14/site-packages/pandas/tests/generic/test_series.py b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_series.py new file mode 100644 index 0000000000000000000000000000000000000000..e60ed4acac20f5b4014c38323da17d3b527601ab --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_series.py @@ -0,0 +1,114 @@ +from operator import methodcaller + +import numpy as np +import pytest + +import pandas as pd +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 = pd.Series( + [11, 21, 31], + index=pd.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 = pd.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 = pd.Series([True, False, True]) + result = ser._get_bool_data() + tm.assert_series_equal(result, ser) + + @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 = pd.Series([data]) + + msg = "The truth value of a Series is ambiguous" + with pytest.raises(ValueError, match=msg): + bool(series) + + @pytest.mark.parametrize("data", [(True, True), (False, False)]) + def test_nonzero_multiple_element_raise(self, data): + # multiple bool are still an error + msg_err = "The truth value of a Series is ambiguous" + series = pd.Series([data]) + with pytest.raises(ValueError, match=msg_err): + bool(series) + + @pytest.mark.parametrize("data", [1, 0, "a", 0.0]) + def test_nonbool_single_element_raise(self, data): + # single non-bool are an error + msg_err1 = "The truth value of a Series is ambiguous" + series = pd.Series([data]) + with pytest.raises(ValueError, match=msg_err1): + bool(series) + + def test_metadata_propagation_indiv_resample(self): + # resample + ts = pd.Series( + np.random.default_rng(2).random(1000), + index=pd.date_range("20130101", periods=1000, freq="s"), + name="foo", + ) + result = ts.resample("1min").mean() + tm.assert_metadata_equivalent(ts, result) + + result = ts.resample("1min").min() + tm.assert_metadata_equivalent(ts, result) + + result = ts.resample("1min").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 = pd.Series(range(3), range(3)) + ser.name = "foo" + ser2 = pd.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.input_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(pd.Series, "_metadata", ["name", "filename"]) + m.setattr(pd.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/venv/lib/python3.14/site-packages/pandas/tests/generic/test_to_xarray.py b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_to_xarray.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce951785f2b5223812c82948d47193268c78db6 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/generic/test_to_xarray.py @@ -0,0 +1,112 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.util.version import Version + +xarray = pytest.importorskip("xarray") + + +class TestDataFrameToXArray: + @pytest.fixture + def df(self): + return pd.DataFrame( + { + "a": list("abcd"), + "b": list(range(1, 5)), + "c": np.arange(3, 7).astype("u1"), + "d": np.arange(4.0, 8.0, dtype="float64"), + "e": [True, False, True, False], + "f": pd.Categorical(list("abcd")), + "g": pd.date_range("20130101", periods=4), + "h": pd.date_range("20130101", periods=4, tz="US/Eastern"), + } + ) + + def test_to_xarray_index_types(self, index_flat, df, request): + 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") + if Version(xarray.__version__) < Version("2025.9.0"): + pytest.skip("Xarray bug https://github.com/pydata/xarray/issues/9661") + + df.index = index[:4] + df.index.name = "foo" + df.columns.name = "bar" + result = df.to_xarray() + assert result.sizes["foo"] == 4 + assert len(result.coords) == 1 + assert len(result.data_vars) == 8 + tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) + assert isinstance(result, xarray.Dataset) + + # idempotency + # datetimes w/tz are preserved + # column names are lost + expected = df.copy() + expected.columns.name = None + tm.assert_frame_equal(result.to_dataframe(), expected) + + def test_to_xarray_empty(self, df): + df.index.name = "foo" + result = df[0:0].to_xarray() + assert result.sizes["foo"] == 0 + assert isinstance(result, xarray.Dataset) + + def test_to_xarray_with_multiindex(self, df, using_infer_string): + # MultiIndex + df.index = pd.MultiIndex.from_product([["a"], range(4)], names=["one", "two"]) + result = df.to_xarray() + assert result.sizes["one"] == 1 + assert result.sizes["two"] == 4 + assert len(result.coords) == 2 + assert len(result.data_vars) == 8 + tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) + assert isinstance(result, xarray.Dataset) + + result = result.to_dataframe() + expected = df.copy() + expected["f"] = expected["f"].astype( + object if not using_infer_string else "str" + ) + expected.columns.name = None + tm.assert_frame_equal(result, expected) + + +class TestSeriesToXArray: + def test_to_xarray_index_types(self, index_flat, request): + # MultiIndex is tested in test_to_xarray_with_multiindex + index = index_flat + + ser = pd.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, xarray.DataArray) + + # idempotency + tm.assert_series_equal(result.to_series(), ser) + + def test_to_xarray_empty(self): + ser = pd.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, xarray.DataArray) + + def test_to_xarray_with_multiindex(self): + mi = pd.MultiIndex.from_product([["a", "b"], range(3)], names=["one", "two"]) + ser = pd.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, xarray.DataArray) + res = result.to_series() + tm.assert_series_equal(res, ser) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..79046cd7ed415166e0c81ff645174015fc48eaf6 --- /dev/null +++ b/venv/lib/python3.14/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"), + 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", "take"): + return (0,) + if name == "quantile": + return (0.5,) + if name == "corrwith": + return (obj,) + return () diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_aggregate.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_aggregate.py new file mode 100644 index 0000000000000000000000000000000000000000..55e4a3a5b24af5c051d9a5fb5ef58924c611389d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_aggregate.py @@ -0,0 +1,2256 @@ +""" +test .agg behavior / note that .apply is tested generally in test_groupby.py +""" + +import datetime +import functools +from functools import partial + +import numpy as np +import pytest + +from pandas.errors import ( + Pandas4Warning, + SpecificationError, +) +import pandas.util._test_decorators as td + +from pandas.core.dtypes.common import is_integer_dtype + +import pandas as pd +import pandas._testing as tm +from pandas.arrays import ArrowExtensionArray +from pandas.core.groupby.grouper import Grouping + + +def test_groupby_agg_no_extra_calls(): + # GH#31760 + df = pd.DataFrame({"key": ["a", "b", "c", "c"], "value": [1, 2, 3, 4]}) + gb = df.groupby("key")["value"] + + def dummy_func(x): + assert len(x) != 0 + return x.sum() + + gb.agg(dummy_func) + + +def test_agg_regression1(tsframe): + grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month]) + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + +def test_agg_must_agg(df): + # https://github.com/pandas-dev/pandas/pull/63957 + grouped = df.groupby("A")["C"] + expected = pd.Series( + { + "bar": df[df.A == "bar"]["C"].describe().tolist(), + "foo": df[df.A == "foo"]["C"].describe().tolist(), + }, + index=pd.Index(["bar", "foo"], name="A"), + name="C", + ) + result = grouped.agg(lambda x: x.describe()) + tm.assert_series_equal(result, expected) + + expected = pd.Series( + { + "bar": df[df.A == "bar"]["C"].index[:2], + "foo": df[df.A == "foo"]["C"].index[:2], + }, + index=pd.Index(["bar", "foo"], name="A"), + name="C", + ) + result = grouped.agg(lambda x: x.index[:2]) + tm.assert_series_equal(result, expected) + + expected = pd.Series( + { + "bar": np.array(df[df.A == "bar"]["C"]), + "foo": np.array(df[df.A == "foo"]["C"]), + }, + index=pd.Index(["bar", "foo"], name="A"), + name="C", + ) + result = grouped.agg(lambda x: np.array(x)) + tm.assert_series_equal(result, expected) + + +def test_agg_ser_multi_key(df): + f = lambda x: x.sum() + results = df.C.groupby([df.A, df.B]).aggregate(f) + expected = df.groupby(["A", "B"]).sum()["C"] + tm.assert_series_equal(results, expected) + + +def test_agg_with_missing_values(): + # GH#58810 + missing_df = pd.DataFrame( + { + "nan": [np.nan, np.nan, np.nan, np.nan], + "na": [pd.NA, pd.NA, pd.NA, pd.NA], + "nat": [pd.NaT, pd.NaT, pd.NaT, pd.NaT], + "none": [None, None, None, None], + "values": [1, 2, 3, 4], + } + ) + + result = missing_df.agg(x=("nan", "min"), y=("na", "min"), z=("values", "sum")) + + expected = pd.DataFrame( + { + "nan": [np.nan, np.nan, np.nan], + "na": [np.nan, np.nan, np.nan], + "values": [np.nan, np.nan, 10.0], + }, + index=["x", "y", "z"], + ) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_mixed_dtype(): + # GH 6212 + expected = pd.DataFrame( + { + "v1": [5, 5, 7, np.nan, 3, 3, 4, 1], + "v2": [55, 55, 77, np.nan, 33, 33, 44, 11], + }, + index=pd.MultiIndex.from_tuples( + [ + (1, 95), + (1, 99), + (2, 95), + (2, 99), + ("big", "damp"), + ("blue", "dry"), + ("red", "red"), + ("red", "wet"), + ], + names=["by1", "by2"], + ), + ) + + df = pd.DataFrame( + { + "v1": [1, 3, 5, 7, 8, 3, 5, np.nan, 4, 5, 7, 9], + "v2": [11, 33, 55, 77, 88, 33, 55, np.nan, 44, 55, 77, 99], + "by1": ["red", "blue", 1, 2, np.nan, "big", 1, 2, "red", 1, np.nan, 12], + "by2": [ + "wet", + "dry", + 99, + 95, + np.nan, + "damp", + 95, + 99, + "red", + 99, + np.nan, + np.nan, + ], + } + ) + + g = df.groupby(["by1", "by2"]) + result = g[["v1", "v2"]].mean() + tm.assert_frame_equal(result, expected) + + +def test_agg_apply_corner(ts, tsframe): + # nothing to group, all NA + grouped = ts.groupby(ts * np.nan, group_keys=False) + assert ts.dtype == np.float64 + + # groupby float64 values results in a float64 Index + exp = pd.Series([], dtype=np.float64, index=pd.Index([], dtype=np.float64)) + tm.assert_series_equal(grouped.sum(), exp) + tm.assert_series_equal(grouped.agg("sum"), exp) + tm.assert_series_equal(grouped.apply("sum"), exp, check_index_type=False) + + # DataFrame + grouped = tsframe.groupby(tsframe["A"] * np.nan, group_keys=False) + exp_df = pd.DataFrame( + columns=tsframe.columns, + dtype=float, + index=pd.Index([], name="A", dtype=np.float64), + ) + tm.assert_frame_equal(grouped.sum(), exp_df) + tm.assert_frame_equal(grouped.agg("sum"), exp_df) + + res = grouped.apply(np.sum, axis=0) + exp_df = exp_df.reset_index(drop=True) + tm.assert_frame_equal(res, exp_df) + + +def test_with_na_groups(any_real_numpy_dtype): + index = pd.Index(np.arange(10)) + values = pd.Series(np.ones(10), index, dtype=any_real_numpy_dtype) + labels = pd.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 = pd.Series([4, 2], index=["bar", "foo"]) + + tm.assert_series_equal(agged, expected, check_dtype=False) + + # explicitly return a float from my function + def f(x): + return float(len(x)) + + agged = grouped.agg(f) + expected = pd.Series([4.0, 2.0], index=["bar", "foo"]) + if values.dtype == np.float32: + expected = expected.astype(np.float32) + + tm.assert_series_equal(agged, expected) + + +def test_agg_grouping_is_list_tuple(ts): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=30, freq="B"), + ) + + grouped = df.groupby(lambda x: x.year) + grouper = grouped._grouper.groupings[0].grouping_vector + grouped._grouper.groupings[0] = Grouping(ts.index, list(grouper)) + + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + grouped._grouper.groupings[0] = Grouping(ts.index, tuple(grouper)) + + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + +def test_agg_python_multiindex(multiindex_dataframe_random_data): + grouped = multiindex_dataframe_random_data.groupby(["A", "B"]) + + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "groupbyfunc", [lambda x: x.weekday(), [lambda x: x.month, lambda x: x.weekday()]] +) +def test_aggregate_str_func(tsframe, groupbyfunc): + grouped = tsframe.groupby(groupbyfunc) + + # single series + result = grouped["A"].agg("std") + expected = grouped["A"].std() + tm.assert_series_equal(result, expected) + + # group frame by function name + result = grouped.aggregate("var") + expected = grouped.var() + tm.assert_frame_equal(result, expected) + + # group frame by function dict + result = grouped.agg({"A": "var", "B": "std", "C": "mean", "D": "sem"}) + expected = pd.DataFrame( + { + "A": grouped["A"].var(), + "B": grouped["B"].std(), + "C": grouped["C"].mean(), + "D": grouped["D"].sem(), + } + ) + tm.assert_frame_equal(result, expected) + + +def test_std_masked_dtype(any_numeric_ea_dtype): + # GH#35516 + df = pd.DataFrame( + { + "a": [2, 1, 1, 1, 2, 2, 1], + "b": pd.Series([pd.NA, 1, 2, 1, 1, 1, 2], dtype="Float64"), + } + ) + result = df.groupby("a").std() + expected = pd.DataFrame( + {"b": [0.57735, 0]}, index=pd.Index([1, 2], name="a"), dtype="Float64" + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_str_with_kwarg_axis_1_raises(df, reduction_func): + gb = df.groupby(level=0) + msg = f"Operation {reduction_func} does not support axis=1" + with pytest.raises(ValueError, match=msg): + gb.agg(reduction_func, axis=1) + + +def test_aggregate_item_by_item(df): + grouped = df.groupby("A") + + aggfun_0 = lambda ser: ser.size + result = grouped.agg(aggfun_0) + foosum = (df.A == "foo").sum() + barsum = (df.A == "bar").sum() + K = len(result.columns) + + # GH5782 + exp = pd.Series(np.array([foosum] * K), index=list("BCD"), name="foo") + tm.assert_series_equal(result.xs("foo"), exp) + + exp = pd.Series(np.array([barsum] * K), index=list("BCD"), name="bar") + tm.assert_almost_equal(result.xs("bar"), exp) + + def aggfun_1(ser): + return ser.size + + result = pd.DataFrame().groupby(df.A).agg(aggfun_1) + assert isinstance(result, pd.DataFrame) + assert len(result) == 0 + + +def test_wrap_agg_out(three_group): + grouped = three_group.groupby(["A", "B"]) + + def func(ser): + if ser.dtype in (object, "string"): + raise TypeError("Test error message") + return ser.sum() + + with pytest.raises(TypeError, match="Test error message"): + grouped.aggregate(func) + result = grouped[["D", "E", "F"]].aggregate(func) + exp_grouped = three_group.loc[:, ["A", "B", "D", "E", "F"]] + expected = exp_grouped.groupby(["A", "B"]).aggregate(func) + tm.assert_frame_equal(result, expected) + + +def test_agg_multiple_functions_maintain_order(df): + # GH #610 + funcs = [("mean", np.mean), ("max", np.max), ("min", np.min)] + result = df.groupby("A")["C"].agg(funcs) + exp_cols = pd.Index(["mean", "max", "min"]) + + tm.assert_index_equal(result.columns, exp_cols) + + +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_agg_multiple_functions_same_name(): + # GH 30880 + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((1000, 3)), + index=pd.date_range("1/1/2012", freq="s", periods=1000), + columns=["A", "B", "C"], + ) + result = df.resample("3min").agg( + {"A": [partial(np.quantile, q=0.9999), partial(np.quantile, q=0.1111)]} + ) + expected_index = pd.date_range("1/1/2012", freq="3min", periods=6) + expected_columns = pd.MultiIndex.from_tuples([("A", "quantile"), ("A", "quantile")]) + expected_values = np.array( + [df.resample("3min").A.quantile(q=q).values for q in [0.9999, 0.1111]] + ).T + expected = pd.DataFrame( + expected_values, columns=expected_columns, index=expected_index + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_multiple_functions_same_name_with_ohlc_present(): + # GH 30880 + # ohlc expands dimensions, so different test to the above is required. + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((1000, 3)), + index=pd.date_range("1/1/2012", freq="s", periods=1000, name="dti"), + columns=pd.Index(["A", "B", "C"], name="alpha"), + ) + result = df.resample("3min").agg( + {"A": ["ohlc", partial(np.quantile, q=0.9999), partial(np.quantile, q=0.1111)]} + ) + expected_index = pd.date_range("1/1/2012", freq="3min", periods=6, name="dti") + expected_columns = pd.MultiIndex.from_tuples( + [ + ("A", "ohlc", "open"), + ("A", "ohlc", "high"), + ("A", "ohlc", "low"), + ("A", "ohlc", "close"), + ("A", "quantile", "A"), + ("A", "quantile", "A"), + ], + names=["alpha", None, None], + ) + non_ohlc_expected_values = np.array( + [df.resample("3min").A.quantile(q=q).values for q in [0.9999, 0.1111]] + ).T + expected_values = np.hstack( + [df.resample("3min").A.ohlc(), non_ohlc_expected_values] + ) + expected = pd.DataFrame( + expected_values, columns=expected_columns, index=expected_index + ) + tm.assert_frame_equal(result, expected) + + +def test_multiple_functions_tuples_and_non_tuples(df): + # #1359 + # Columns B and C would cause partial failure + df = df.drop(columns=["B", "C"]) + + funcs = [("foo", "mean"), "std"] + ex_funcs = [("foo", "mean"), ("std", "std")] + + result = df.groupby("A")["D"].agg(funcs) + expected = df.groupby("A")["D"].agg(ex_funcs) + tm.assert_frame_equal(result, expected) + + result = df.groupby("A").agg(funcs) + expected = df.groupby("A").agg(ex_funcs) + tm.assert_frame_equal(result, expected) + + +def test_more_flexible_frame_multi_function(df): + grouped = df.groupby("A") + + exmean = grouped.agg({"C": "mean", "D": "mean"}) + exstd = grouped.agg({"C": "std", "D": "std"}) + + expected = pd.concat([exmean, exstd], keys=["mean", "std"], axis=1) + expected = expected.swaplevel(0, 1, axis=1).sort_index(level=0, axis=1) + + d = {"C": ["mean", "std"], "D": ["mean", "std"]} + result = grouped.aggregate(d) + + tm.assert_frame_equal(result, expected) + + # be careful + result = grouped.aggregate({"C": "mean", "D": ["mean", "std"]}) + expected = grouped.aggregate({"C": "mean", "D": ["mean", "std"]}) + tm.assert_frame_equal(result, expected) + + def numpymean(x): + return np.mean(x) + + def numpystd(x): + return np.std(x, ddof=1) + + # this uses column selection & renaming + msg = r"nested renamer is not supported" + d = {"C": "mean", "D": {"foo": "mean", "bar": "std"}} + with pytest.raises(SpecificationError, match=msg): + grouped.aggregate(d) + + # But without renaming, these functions are OK + d = {"C": ["mean"], "D": [numpymean, numpystd]} + grouped.aggregate(d) + + +def test_multi_function_flexible_mix(df): + # GH #1268 + grouped = df.groupby("A") + + # Expected + d = {"C": {"foo": "mean", "bar": "std"}, "D": {"sum": "sum"}} + # this uses column selection & renaming + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + grouped.aggregate(d) + + # Test 1 + d = {"C": {"foo": "mean", "bar": "std"}, "D": "sum"} + # this uses column selection & renaming + with pytest.raises(SpecificationError, match=msg): + grouped.aggregate(d) + + # Test 2 + d = {"C": {"foo": "mean", "bar": "std"}, "D": "sum"} + # this uses column selection & renaming + with pytest.raises(SpecificationError, match=msg): + grouped.aggregate(d) + + +def test_groupby_agg_coercing_bools(): + # issue 14873 + dat = pd.DataFrame({"a": [1, 1, 2, 2], "b": [0, 1, 2, 3], "c": [None, None, 1, 1]}) + gp = dat.groupby("a") + + index = pd.Index([1, 2], name="a") + + result = gp["b"].aggregate(lambda x: (x != 0).all()) + expected = pd.Series([False, True], index=index, name="b") + tm.assert_series_equal(result, expected) + + result = gp["c"].aggregate(lambda x: x.isnull().all()) + expected = pd.Series([True, False], index=index, name="c") + tm.assert_series_equal(result, expected) + + +def test_groupby_agg_dict_with_getitem(): + # issue 25471 + dat = pd.DataFrame({"A": ["A", "A", "B", "B", "B"], "B": [1, 2, 1, 1, 2]}) + result = dat.groupby("A")[["B"]].agg({"B": "sum"}) + + expected = pd.DataFrame({"B": [3, 4]}, index=["A", "B"]).rename_axis("A", axis=0) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_dict_dup_columns(): + # GH#55006 + df = pd.DataFrame( + [[1, 2, 3, 4], [1, 3, 4, 5], [2, 4, 5, 6]], + columns=["a", "b", "c", "c"], + ) + gb = df.groupby("a") + result = gb.agg({"b": "sum"}) + expected = pd.DataFrame({"b": [5, 4]}, index=pd.Index([1, 2], name="a")) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op", + [ + lambda x: x.sum(), + lambda x: x.cumsum(), + lambda x: x.transform("sum"), + lambda x: x.transform("cumsum"), + lambda x: x.agg("sum"), + lambda x: x.agg("cumsum"), + ], +) +def test_bool_agg_dtype(op): + # GH 7001 + # Bool sum aggregations result in int + df = pd.DataFrame({"a": [1, 1], "b": [False, True]}) + s = df.set_index("a")["b"] + + result = op(df.groupby("a"))["b"].dtype + assert is_integer_dtype(result) + + result = op(s.groupby("a")).dtype + assert is_integer_dtype(result) + + +@pytest.mark.parametrize( + "keys, agg_index", + [ + (["a"], pd.Index([1], name="a")), + (["a", "b"], pd.MultiIndex([[1], [2]], [[0], [0]], names=["a", "b"])), + ], +) +@pytest.mark.parametrize( + "input_dtype", ["bool", "int32", "int64", "float32", "float64"] +) +@pytest.mark.parametrize( + "result_dtype", ["bool", "int32", "int64", "float32", "float64"] +) +@pytest.mark.parametrize("method", ["apply", "aggregate", "transform"]) +def test_callable_result_dtype_frame( + keys, agg_index, input_dtype, result_dtype, method, using_python_scalars +): + # GH 21240 + df = pd.DataFrame({"a": [1], "b": [2], "c": [True]}) + df["c"] = df["c"].astype(input_dtype) + op = getattr(df.groupby(keys)[["c"]], method) + result = op(lambda x: x.astype(result_dtype).iloc[0]) + expected_index = pd.RangeIndex(0, 1) if method == "transform" else agg_index + + if method != "apply": + if using_python_scalars: + # iloc in the callable returns Python scalars, which infer at + # the default width + if result_dtype in ("int32", "int64"): + result_dtype = "int64" + elif result_dtype in ("float32", "float64"): + result_dtype = "float64" + if method == "aggregate": + # _cast_pointwise_result retains the input's dtype where feasible + if input_dtype == "float32" and result_dtype == "float64": + result_dtype = "float32" + if input_dtype == "int32" and result_dtype == "int64": + result_dtype = "int32" + + expected = pd.DataFrame({"c": [df["c"].iloc[0]]}, index=expected_index).astype( + result_dtype + ) + if method == "apply": + expected.columns.names = [0] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "keys, agg_index", + [ + (["a"], pd.Index([1], name="a")), + (["a", "b"], pd.MultiIndex([[1], [2]], [[0], [0]], names=["a", "b"])), + ], +) +@pytest.mark.parametrize("input", [True, 1, 1.0]) +@pytest.mark.parametrize("dtype", [bool, int, float]) +@pytest.mark.parametrize("method", ["apply", "aggregate", "transform"]) +def test_callable_result_dtype_series(keys, agg_index, input, dtype, method): + # GH 21240 + df = pd.DataFrame({"a": [1], "b": [2], "c": [input]}) + op = getattr(df.groupby(keys)["c"], method) + result = op(lambda x: x.astype(dtype).iloc[0]) + expected_index = pd.RangeIndex(0, 1) if method == "transform" else agg_index + expected = pd.Series([df["c"].iloc[0]], index=expected_index, name="c").astype( + dtype + ) + tm.assert_series_equal(result, expected) + + +def test_order_aggregate_multiple_funcs(): + # GH 25692 + df = pd.DataFrame({"A": [1, 1, 2, 2], "B": [1, 2, 3, 4]}) + + res = df.groupby("A").agg(["sum", "max", "mean", "ohlc", "min"]) + result = res.columns.levels[1] + + expected = pd.Index(["sum", "max", "mean", "ohlc", "min"]) + + tm.assert_index_equal(result, expected) + + +def test_ohlc_ea_dtypes(any_numeric_ea_dtype): + # GH#37493 + df = pd.DataFrame( + {"a": [1, 1, 2, 3, 4, 4], "b": [22, 11, pd.NA, 10, 20, pd.NA]}, + dtype=any_numeric_ea_dtype, + ) + gb = df.groupby("a") + result = gb.ohlc() + expected = pd.DataFrame( + [[22, 22, 11, 11], [pd.NA] * 4, [10] * 4, [20] * 4], + columns=pd.MultiIndex.from_product([["b"], ["open", "high", "low", "close"]]), + index=pd.Index([1, 2, 3, 4], dtype=any_numeric_ea_dtype, name="a"), + dtype=any_numeric_ea_dtype, + ) + tm.assert_frame_equal(result, expected) + + gb2 = df.groupby("a", as_index=False) + result2 = gb2.ohlc() + expected2 = expected.reset_index() + tm.assert_frame_equal(result2, expected2) + + +@pytest.mark.parametrize("dtype", [np.int64, np.uint64]) +@pytest.mark.parametrize("how", ["first", "last", "min", "max", "mean", "median"]) +def test_uint64_type_handling(dtype, how): + # GH 26310 + df = pd.DataFrame({"x": 6903052872240755750, "y": [1, 2]}) + expected = df.groupby("y").agg({"x": how}) + df.x = df.x.astype(dtype) + result = df.groupby("y").agg({"x": how}) + if how not in ("mean", "median"): + # mean and median always result in floats + result.x = result.x.astype(np.int64) + tm.assert_frame_equal(result, expected, check_exact=True) + + +def test_func_duplicates_raises(): + # GH28426 + msg = "Function names" + df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) + with pytest.raises(SpecificationError, match=msg): + df.groupby("A").agg(["min", "min"]) + + +@pytest.mark.parametrize( + "index", + [ + pd.CategoricalIndex(list("abc")), + pd.interval_range(0, 3), + pd.period_range("2020", periods=3, freq="D"), + pd.MultiIndex.from_tuples([("a", 0), ("a", 1), ("b", 0)]), + ], +) +def test_agg_index_has_complex_internals(index): + # GH 31223 + df = pd.DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index) + result = df.groupby("group").agg({"value": pd.Series.nunique}) + expected = pd.DataFrame({"group": [1, 2], "value": [2, 1]}).set_index("group") + tm.assert_frame_equal(result, expected) + + +def test_agg_split_block(): + # https://github.com/pandas-dev/pandas/issues/31522 + df = pd.DataFrame( + { + "key1": ["a", "a", "b", "b", "a"], + "key2": ["one", "two", "one", "two", "one"], + "key3": ["three", "three", "three", "six", "six"], + } + ) + result = df.groupby("key1").min() + expected = pd.DataFrame( + {"key2": ["one", "one"], "key3": ["six", "six"]}, + index=pd.Index(["a", "b"], name="key1"), + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_split_object_part_datetime(): + # https://github.com/pandas-dev/pandas/pull/31616 + df = pd.DataFrame( + { + "A": pd.date_range("2000", periods=4), + "B": ["a", "b", "c", "d"], + "C": [1, 2, 3, 4], + "D": ["b", "c", "d", "e"], + "E": pd.date_range("2000", periods=4), + "F": [1, 2, 3, 4], + } + ).astype(object) + result = df.groupby([0, 0, 0, 0]).min() + expected = pd.DataFrame( + { + "A": [pd.Timestamp("2000")], + "B": ["a"], + "C": [1], + "D": ["b"], + "E": [pd.Timestamp("2000")], + "F": [1], + }, + index=np.array([0]), + dtype=object, + ) + tm.assert_frame_equal(result, expected) + + +class TestNamedAggregationSeries: + def test_series_named_agg(self): + df = pd.Series([1, 2, 3, 4]) + gr = df.groupby([0, 0, 1, 1]) + result = gr.agg(a="sum", b="min") + expected = pd.DataFrame( + {"a": [3, 7], "b": [1, 3]}, columns=["a", "b"], index=np.array([0, 1]) + ) + tm.assert_frame_equal(result, expected) + + result = gr.agg(b="min", a="sum") + expected = expected[["b", "a"]] + tm.assert_frame_equal(result, expected) + + def test_no_args_raises(self): + gr = pd.Series([1, 2]).groupby([0, 1]) + with pytest.raises(TypeError, match="Must provide"): + gr.agg() + + # but we do allow this + result = gr.agg([]) + expected = pd.DataFrame(index=np.array([0, 1]), columns=[]) + tm.assert_frame_equal(result, expected) + + def test_series_named_agg_duplicates_no_raises(self): + # GH28426 + gr = pd.Series([1, 2, 3]).groupby([0, 0, 1]) + grouped = gr.agg(a="sum", b="sum") + expected = pd.DataFrame({"a": [3, 3], "b": [3, 3]}, index=np.array([0, 1])) + tm.assert_frame_equal(expected, grouped) + + def test_mangled(self): + gr = pd.Series([1, 2, 3]).groupby([0, 0, 1]) + result = gr.agg(a=lambda x: 0, b=lambda x: 1) + expected = pd.DataFrame({"a": [0, 0], "b": [1, 1]}, index=np.array([0, 1])) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "inp", + [ + pd.NamedAgg(column="anything", aggfunc="min"), + ("anything", "min"), + ["anything", "min"], + ], + ) + def test_named_agg_nametuple(self, inp): + # GH34422 + s = pd.Series([1, 1, 2, 2, 3, 3, 4, 5]) + msg = f"func is expected but received {type(inp).__name__}" + with pytest.raises(TypeError, match=msg): + s.groupby(s.values).agg(a=inp) + + +class TestNamedAggregationDataFrame: + def test_agg_relabel(self): + df = pd.DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + result = df.groupby("group").agg(a_max=("A", "max"), b_max=("B", "max")) + expected = pd.DataFrame( + {"a_max": [1, 3], "b_max": [6, 8]}, + index=pd.Index(["a", "b"], name="group"), + columns=["a_max", "b_max"], + ) + tm.assert_frame_equal(result, expected) + + # order invariance + p98 = functools.partial(np.percentile, q=98) + result = df.groupby("group").agg( + b_min=("B", "min"), + a_min=("A", "min"), + a_mean=("A", "mean"), + a_max=("A", "max"), + b_max=("B", "max"), + a_98=("A", p98), + ) + expected = pd.DataFrame( + { + "b_min": [5, 7], + "a_min": [0, 2], + "a_mean": [0.5, 2.5], + "a_max": [1, 3], + "b_max": [6, 8], + "a_98": [0.98, 2.98], + }, + index=pd.Index(["a", "b"], name="group"), + columns=["b_min", "a_min", "a_mean", "a_max", "b_max", "a_98"], + ) + tm.assert_frame_equal(result, expected) + + def test_agg_relabel_non_identifier(self): + df = pd.DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + + result = df.groupby("group").agg(**{"my col": ("A", "max")}) + expected = pd.DataFrame( + {"my col": [1, 3]}, index=pd.Index(["a", "b"], name="group") + ) + tm.assert_frame_equal(result, expected) + + def test_duplicate_no_raises(self): + # GH 28426, if use same input function on same column, + # no error should raise + df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) + + grouped = df.groupby("A").agg(a=("B", "min"), b=("B", "min")) + expected = pd.DataFrame( + {"a": [1, 3], "b": [1, 3]}, index=pd.Index([0, 1], name="A") + ) + tm.assert_frame_equal(grouped, expected) + + quant50 = functools.partial(np.percentile, q=50) + quant70 = functools.partial(np.percentile, q=70) + quant50.__name__ = "quant50" + quant70.__name__ = "quant70" + + test = pd.DataFrame( + {"col1": ["a", "a", "b", "b", "b"], "col2": [1, 2, 3, 4, 5]} + ) + + grouped = test.groupby("col1").agg( + quantile_50=("col2", quant50), quantile_70=("col2", quant70) + ) + expected = pd.DataFrame( + {"quantile_50": [1.5, 4.0], "quantile_70": [1.7, 4.4]}, + index=pd.Index(["a", "b"], name="col1"), + ) + tm.assert_frame_equal(grouped, expected) + + def test_agg_relabel_with_level(self): + df = pd.DataFrame( + {"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}, + index=pd.MultiIndex.from_product([["A", "B"], ["a", "b"]]), + ) + result = df.groupby(level=0).agg( + aa=("A", "max"), bb=("A", "min"), cc=("B", "mean") + ) + expected = pd.DataFrame( + {"aa": [0, 1], "bb": [0, 1], "cc": [1.5, 3.5]}, index=["A", "B"] + ) + tm.assert_frame_equal(result, expected) + + def test_agg_relabel_other_raises(self): + df = pd.DataFrame({"A": [0, 0, 1], "B": [1, 2, 3]}) + grouped = df.groupby("A") + match = "Must provide" + with pytest.raises(TypeError, match=match): + grouped.agg(foo=1) + + with pytest.raises(TypeError, match=match): + grouped.agg() + + with pytest.raises(TypeError, match=match): + grouped.agg(a=("B", "max"), b=(1, 2, 3)) + + def test_missing_raises(self): + df = pd.DataFrame({"A": [0, 1], "B": [1, 2]}) + msg = r"Label\(s\) \['C'\] do not exist" + with pytest.raises(KeyError, match=msg): + df.groupby("A").agg(c=("C", "sum")) + + def test_agg_namedtuple(self): + df = pd.DataFrame({"A": [0, 1], "B": [1, 2]}) + result = df.groupby("A").agg( + b=pd.NamedAgg("B", "sum"), c=pd.NamedAgg(column="B", aggfunc="count") + ) + expected = df.groupby("A").agg(b=("B", "sum"), c=("B", "count")) + tm.assert_frame_equal(result, expected) + + def n_between(self, ser, low, high, **kwargs): + return ser.between(low, high, **kwargs).sum() + + def test_namedagg_args(self): + # https://github.com/pandas-dev/pandas/issues/58283 + df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [-1, 0, 1, 2]}) + + result = df.groupby("A").agg( + count_between=pd.NamedAgg("B", self.n_between, 0, 1) + ) + expected = pd.DataFrame( + {"count_between": [1, 1]}, index=pd.Index([0, 1], name="A") + ) + tm.assert_frame_equal(result, expected) + + def test_namedagg_kwargs(self): + # https://github.com/pandas-dev/pandas/issues/58283 + df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [-1, 0, 1, 2]}) + + result = df.groupby("A").agg( + count_between_kw=pd.NamedAgg("B", self.n_between, 0, 1, inclusive="both") + ) + expected = pd.DataFrame( + {"count_between_kw": [1, 1]}, index=pd.Index([0, 1], name="A") + ) + tm.assert_frame_equal(result, expected) + + def test_namedagg_args_and_kwargs(self): + # https://github.com/pandas-dev/pandas/issues/58283 + df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [-1, 0, 1, 2]}) + + result = df.groupby("A").agg( + count_between_mix=pd.NamedAgg( + "B", self.n_between, 0, 1, inclusive="neither" + ) + ) + expected = pd.DataFrame( + {"count_between_mix": [0, 0]}, index=pd.Index([0, 1], name="A") + ) + tm.assert_frame_equal(result, expected) + + def test_multiple_named_agg_with_args_and_kwargs(self): + # https://github.com/pandas-dev/pandas/issues/58283 + df = pd.DataFrame({"A": [0, 1, 2, 3], "B": [1, 2, 3, 4]}) + + result = df.groupby("A").agg( + n_between01=pd.NamedAgg("B", self.n_between, 0, 1), + n_between13=pd.NamedAgg("B", self.n_between, 1, 3), + n_between02=pd.NamedAgg("B", self.n_between, 0, 2), + ) + expected = pd.DataFrame( + { + "n_between01": [1, 0, 0, 0], + "n_between13": [1, 1, 1, 0], + "n_between02": [1, 1, 0, 0], + }, + index=pd.Index([0, 1, 2, 3], name="A"), + ) + tm.assert_frame_equal(result, expected) + + def test_mangled(self): + df = pd.DataFrame({"A": [0, 1], "B": [1, 2], "C": [3, 4]}) + result = df.groupby("A").agg(b=("B", lambda x: 0), c=("C", lambda x: 1)) + expected = pd.DataFrame( + {"b": [0, 0], "c": [1, 1]}, index=pd.Index([0, 1], name="A") + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "agg_col1, agg_col2, agg_col3, agg_result1, agg_result2, agg_result3", + [ + ( + (("y", "A"), "max"), + (("y", "A"), np.mean), + (("y", "B"), "mean"), + [1, 3], + [0.5, 2.5], + [5.5, 7.5], + ), + ( + (("y", "A"), lambda x: max(x)), + (("y", "A"), lambda x: 1), + (("y", "B"), np.mean), + [1, 3], + [1, 1], + [5.5, 7.5], + ), + ( + pd.NamedAgg(("y", "A"), "max"), + pd.NamedAgg(("y", "B"), np.mean), + pd.NamedAgg(("y", "A"), lambda x: 1), + [1, 3], + [5.5, 7.5], + [1, 1], + ), + ], +) +def test_agg_relabel_multiindex_column( + agg_col1, agg_col2, agg_col3, agg_result1, agg_result2, agg_result3 +): + # GH 29422, add tests for multiindex column cases + df = pd.DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + df.columns = pd.MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")]) + idx = pd.Index(["a", "b"], name=("x", "group")) + + result = df.groupby(("x", "group")).agg(a_max=(("y", "A"), "max")) + expected = pd.DataFrame({"a_max": [1, 3]}, index=idx) + tm.assert_frame_equal(result, expected) + + result = df.groupby(("x", "group")).agg( + col_1=agg_col1, col_2=agg_col2, col_3=agg_col3 + ) + expected = pd.DataFrame( + {"col_1": agg_result1, "col_2": agg_result2, "col_3": agg_result3}, index=idx + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_relabel_multiindex_raises_not_exist(): + # GH 29422, add test for raises scenario when aggregate column does not exist + df = pd.DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + df.columns = pd.MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")]) + + with pytest.raises(KeyError, match="do not exist"): + df.groupby(("x", "group")).agg(a=(("Y", "a"), "max")) + + +def test_agg_relabel_multiindex_duplicates(): + # GH29422, add test for raises scenario when getting duplicates + # GH28426, after this change, duplicates should also work if the relabelling is + # different + df = pd.DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + df.columns = pd.MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")]) + + result = df.groupby(("x", "group")).agg( + a=(("y", "A"), "min"), b=(("y", "A"), "min") + ) + idx = pd.Index(["a", "b"], name=("x", "group")) + expected = pd.DataFrame({"a": [0, 2], "b": [0, 2]}, index=idx) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("kwargs", [{"c": ["min"]}, {"b": [], "c": ["min"]}]) +def test_groupby_aggregate_empty_key(kwargs): + # GH: 32580 + df = pd.DataFrame({"a": [1, 1, 2], "b": [1, 2, 3], "c": [1, 2, 4]}) + result = df.groupby("a").agg(kwargs) + expected = pd.DataFrame( + [1, 4], + index=pd.Index([1, 2], dtype="int64", name="a"), + columns=pd.MultiIndex.from_tuples([["c", "min"]]), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregate_empty_key_empty_return(): + # GH: 32580 Check if everything works, when return is empty + df = pd.DataFrame({"a": [1, 1, 2], "b": [1, 2, 3], "c": [1, 2, 4]}) + result = df.groupby("a").agg({"b": []}) + expected = pd.DataFrame( + index=pd.Index([1, 2], name="a"), + columns=pd.MultiIndex(levels=[["b"], []], codes=[[], []]), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", [[], {}]) +def test_groupby_aggregate_empty_func(func): + # GH#39609 + df = pd.DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + result = df.groupby("a").agg(func) + if func == []: + columns = pd.MultiIndex(levels=[["b"], []], codes=[[], []]) + else: + columns = df.columns[:0] + expected = pd.DataFrame(index=pd.Index([1, 2], name="a"), columns=columns) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", [[], {}]) +def test_groupby_aggregate_empty_func_as_index_false(func): + # GH#39609 + df = pd.DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + result = df.groupby("a", as_index=False).agg(func) + expected = pd.DataFrame({"a": [1, 2]}) + if func == []: + expected.columns = pd.MultiIndex.from_tuples([("a", "")]) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregate_empty_with_multiindex_frame_single(as_index): + # GH 39178, 51445 + df = pd.DataFrame(columns=["a", "b", "c"]) + gb = df.groupby(["a", "b"], group_keys=False, as_index=as_index) + result = gb.agg(lambda x: x.sum()) + expected = pd.DataFrame( + columns=["c"], index=pd.MultiIndex([[], []], [[], []], names=["a", "b"]) + ) + if not as_index: + expected = expected.reset_index() + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregate_empty_with_multiindex_frame_multi(as_index): + # GH 39178 + df = pd.DataFrame(columns=["a", "b", "c"]) + result = df.groupby(["a", "b"], group_keys=False, as_index=as_index).agg( + d=("c", list) + ) + expected = pd.DataFrame( + columns=["d"], index=pd.MultiIndex([[], []], [[], []], names=["a", "b"]) + ) + if not as_index: + expected = expected.reset_index() + + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_loses_results_with_as_index_false_relabel(): + # GH 32240: When the aggregate function relabels column names and + # as_index=False is specified, the results are dropped. + + df = pd.DataFrame( + {"key": ["x", "y", "z", "x", "y", "z"], "val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75]} + ) + + grouped = df.groupby("key", as_index=False) + result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min")) + expected = pd.DataFrame({"key": ["x", "y", "z"], "min_val": [1.0, 0.8, 0.75]}) + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_loses_results_with_as_index_false_relabel_multiindex(): + # GH 32240: When the aggregate function relabels column names and + # as_index=False is specified, the results are dropped. Check if + # multiindex is returned in the right order + + df = pd.DataFrame( + { + "key": ["x", "y", "x", "y", "x", "x"], + "key1": ["a", "b", "c", "b", "a", "c"], + "val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75], + } + ) + + grouped = df.groupby(["key", "key1"], as_index=False) + result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min")) + expected = pd.DataFrame( + {"key": ["x", "x", "y"], "key1": ["a", "c", "b"], "min_val": [1.0, 0.75, 0.8]} + ) + tm.assert_frame_equal(result, 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 = pd.DataFrame(expected3).rename(columns={"C": "Q"}) + msg = "nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + grouped["C"].agg({"Q": "sum"}) + + # GH7115 & GH8112 & GH8582 + df = pd.DataFrame( + np.random.default_rng(2).integers(0, 100, (50, 3)), + columns=["jim", "joe", "jolie"], + ) + ts = pd.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 + + 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) + + +@pytest.mark.parametrize( + "func", [lambda s: s.mean(), lambda s: np.mean(s), lambda s: np.nanmean(s)] +) +def test_multiindex_custom_func(func): + # GH 31777 + data = [[1, 4, 2], [5, 7, 1]] + df = pd.DataFrame( + data, + columns=pd.MultiIndex.from_arrays( + [[1, 1, 2], [3, 4, 3]], names=["Sisko", "Janeway"] + ), + ) + result = df.groupby(np.array([0, 1])).agg(func) + expected_dict = { + (1, 3): {0: 1.0, 1: 5.0}, + (1, 4): {0: 4.0, 1: 7.0}, + (2, 3): {0: 2.0, 1: 1.0}, + } + expected = pd.DataFrame(expected_dict, index=np.array([0, 1]), columns=df.columns) + tm.assert_frame_equal(result, expected) + + +def myfunc(s): + return np.percentile(s, q=0.90) + + +@pytest.mark.parametrize("func", [lambda s: np.percentile(s, q=0.90), myfunc]) +def test_lambda_named_agg(func): + # see gh-28467 + animals = pd.DataFrame( + { + "kind": ["cat", "dog", "cat", "dog"], + "height": [9.1, 6.0, 9.5, 34.0], + "weight": [7.9, 7.5, 9.9, 198.0], + } + ) + + result = animals.groupby("kind").agg( + mean_height=("height", "mean"), perc90=("height", func) + ) + expected = pd.DataFrame( + [[9.3, 9.1036], [20.0, 6.252]], + columns=["mean_height", "perc90"], + index=pd.Index(["cat", "dog"], name="kind"), + ) + + tm.assert_frame_equal(result, expected) + + +def test_aggregate_mixed_types(): + # GH 16916 + df = pd.DataFrame( + data=np.array([0] * 9).reshape(3, 3), columns=list("XYZ"), index=list("abc") + ) + df["grouping"] = ["group 1", "group 1", 2] + result = df.groupby("grouping").aggregate(lambda x: x.tolist()) + expected_data = [[[0], [0], [0]], [[0, 0], [0, 0], [0, 0]]] + expected = pd.DataFrame( + expected_data, + index=pd.Index([2, "group 1"], dtype="object", name="grouping"), + columns=pd.Index(["X", "Y", "Z"]), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.xfail(reason="Not implemented;see GH 31256") +def test_aggregate_udf_na_extension_type(): + # https://github.com/pandas-dev/pandas/pull/31359 + # This is currently failing to cast back to Int64Dtype. + # The presence of the NA causes two problems + # 1. NA is not an instance of Int64Dtype.type (numpy.int64) + # 2. The presence of an NA forces object type, so the non-NA values is + # a Python int rather than a NumPy int64. Python ints aren't + # instances of numpy.int64. + def aggfunc(x): + if all(x > 2): + return 1 + else: + return pd.NA + + df = pd.DataFrame({"A": pd.array([1, 2, 3])}) + result = df.groupby([1, 1, 2]).agg(aggfunc) + expected = pd.DataFrame({"A": pd.array([1, pd.NA], dtype="Int64")}, index=[1, 2]) + tm.assert_frame_equal(result, expected) + + +class TestLambdaMangling: + def test_basic(self): + df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) + result = df.groupby("A").agg({"B": [lambda x: 0, lambda x: 1]}) + + expected = pd.DataFrame( + {("B", ""): [0, 0], ("B", ""): [1, 1]}, + index=pd.Index([0, 1], name="A"), + ) + tm.assert_frame_equal(result, expected) + + def test_mangle_series_groupby(self): + gr = pd.Series([1, 2, 3, 4]).groupby([0, 0, 1, 1]) + result = gr.agg([lambda x: 0, lambda x: 1]) + exp_data = {"": [0, 0], "": [1, 1]} + expected = pd.DataFrame(exp_data, index=np.array([0, 1])) + tm.assert_frame_equal(result, expected) + + @pytest.mark.xfail(reason="GH-26611. kwargs for multi-agg.") + def test_with_kwargs(self): + f1 = lambda x, y, b=1: x.sum() + y + b + f2 = lambda x, y, b=2: x.sum() + y * b + result = pd.Series([1, 2]).groupby([0, 0]).agg([f1, f2], 0) + expected = pd.DataFrame({"": [4], "": [6]}) + tm.assert_frame_equal(result, expected) + + result = pd.Series([1, 2]).groupby([0, 0]).agg([f1, f2], 0, b=10) + expected = pd.DataFrame({"": [13], "": [30]}) + tm.assert_frame_equal(result, expected) + + def test_unused_kwargs(self): + # https://github.com/pandas-dev/pandas/issues/39169 + # agg behavior should not change in the presence of unused args. + func = lambda data, **kwargs: np.sum(np.sum(data)) + + df = pd.DataFrame([[1, 2], [3, 4]]) + expected = pd.DataFrame({0: [1, 3], 1: [2, 4]}) + + result = df.groupby(level=0).agg(func) + tm.assert_frame_equal(result, expected) + + result = df.groupby(level=0).agg(func, foo=42) + tm.assert_frame_equal(result, expected) + + def test_agg_with_one_lambda(self): + # GH 25719, write tests for DataFrameGroupby.agg with only one lambda + df = pd.DataFrame( + { + "kind": ["cat", "dog", "cat", "dog"], + "height": [9.1, 6.0, 9.5, 34.0], + "weight": [7.9, 7.5, 9.9, 198.0], + } + ) + + columns = ["height_sqr_min", "height_max", "weight_max"] + expected = pd.DataFrame( + { + "height_sqr_min": [82.81, 36.00], + "height_max": [9.5, 34.0], + "weight_max": [9.9, 198.0], + }, + index=pd.Index(["cat", "dog"], name="kind"), + columns=columns, + ) + + # check pd.NameAgg case + result1 = df.groupby(by="kind").agg( + height_sqr_min=pd.NamedAgg(column="height", aggfunc=lambda x: np.min(x**2)), + height_max=pd.NamedAgg(column="height", aggfunc="max"), + weight_max=pd.NamedAgg(column="weight", aggfunc="max"), + ) + tm.assert_frame_equal(result1, expected) + + # check agg(key=(col, aggfunc)) case + result2 = df.groupby(by="kind").agg( + height_sqr_min=("height", lambda x: np.min(x**2)), + height_max=("height", "max"), + weight_max=("weight", "max"), + ) + tm.assert_frame_equal(result2, expected) + + def test_agg_multiple_lambda(self): + # GH25719, test for DataFrameGroupby.agg with multiple lambdas + # with mixed aggfunc + df = pd.DataFrame( + { + "kind": ["cat", "dog", "cat", "dog"], + "height": [9.1, 6.0, 9.5, 34.0], + "weight": [7.9, 7.5, 9.9, 198.0], + } + ) + columns = [ + "height_sqr_min", + "height_max", + "weight_max", + "height_max_2", + "weight_min", + ] + expected = pd.DataFrame( + { + "height_sqr_min": [82.81, 36.00], + "height_max": [9.5, 34.0], + "weight_max": [9.9, 198.0], + "height_max_2": [9.5, 34.0], + "weight_min": [7.9, 7.5], + }, + index=pd.Index(["cat", "dog"], name="kind"), + columns=columns, + ) + + # check agg(key=(col, aggfunc)) case + result1 = df.groupby(by="kind").agg( + height_sqr_min=("height", lambda x: np.min(x**2)), + height_max=("height", "max"), + weight_max=("weight", "max"), + height_max_2=("height", lambda x: np.max(x)), + weight_min=("weight", lambda x: np.min(x)), + ) + tm.assert_frame_equal(result1, expected) + + # check pd.NamedAgg case + result2 = df.groupby(by="kind").agg( + height_sqr_min=pd.NamedAgg(column="height", aggfunc=lambda x: np.min(x**2)), + height_max=pd.NamedAgg(column="height", aggfunc="max"), + weight_max=pd.NamedAgg(column="weight", aggfunc="max"), + height_max_2=pd.NamedAgg(column="height", aggfunc=lambda x: np.max(x)), + weight_min=pd.NamedAgg(column="weight", aggfunc=lambda x: np.min(x)), + ) + tm.assert_frame_equal(result2, expected) + + @pytest.mark.parametrize("use_kwargs", [True, False]) + def test_multiple_udf_with_args(self, use_kwargs): + # https://github.com/pandas-dev/pandas/issues/26611 + def func(x, y): + return x.sum() + y + + df = pd.DataFrame({"A": [1, 2]}) + expected = pd.DataFrame({"A": [13]}, index=pd.Index([0], dtype="intp")) + gb = df.groupby([0, 0]) + if use_kwargs: + args, kwargs = (), {"y": 10} + else: + args, kwargs = (10,), {} + result = gb.agg(func, *args, **kwargs) + tm.assert_frame_equal(result, expected) + + +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) + + 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 = pd.DataFrame(ex_data).T + if not as_index: + expected.insert(0, "index", [1, 2]) + expected.index = pd.Index(range(2)) + + tm.assert_frame_equal(res, expected) + + +def test_groupby_get_by_index(): + # GH 33439 + df = pd.DataFrame({"A": ["S", "W", "W"], "B": [1.0, 1.0, 2.0]}) + res = df.groupby("A").agg({"B": lambda x: x.get(x.index[-1])}) + expected = pd.DataFrame({"A": ["S", "W"], "B": [1.0, 2.0]}).set_index("A") + tm.assert_frame_equal(res, expected) + + +@pytest.mark.parametrize( + "grp_col_dict, exp_data", + [ + ({"nr": "min", "cat_ord": "min"}, {"nr": [1, 5], "cat_ord": ["a", "c"]}), + ({"cat_ord": "min"}, {"cat_ord": ["a", "c"]}), + ({"nr": "min"}, {"nr": [1, 5]}), + ], +) +def test_groupby_single_agg_cat_cols(grp_col_dict, exp_data): + # test single aggregations on ordered categorical cols GHGH27800 + + # create the result dataframe + input_df = pd.DataFrame( + { + "nr": [1, 2, 3, 4, 5, 6, 7, 8], + "cat_ord": list("aabbccdd"), + "cat": list("aaaabbbb"), + } + ) + + input_df = input_df.astype({"cat": "category", "cat_ord": "category"}) + input_df["cat_ord"] = input_df["cat_ord"].cat.as_ordered() + result_df = input_df.groupby("cat", observed=False).agg(grp_col_dict) + + # create expected dataframe + cat_index = pd.CategoricalIndex( + ["a", "b"], categories=["a", "b"], ordered=False, name="cat", dtype="category" + ) + + expected_df = pd.DataFrame(data=exp_data, index=cat_index) + + if "cat_ord" in expected_df: + # ordered categorical columns should be preserved + dtype = input_df["cat_ord"].dtype + expected_df["cat_ord"] = expected_df["cat_ord"].astype(dtype) + + tm.assert_frame_equal(result_df, expected_df) + + +@pytest.mark.parametrize( + "grp_col_dict, exp_data", + [ + ({"nr": ["min", "max"], "cat_ord": "min"}, [(1, 4, "a"), (5, 8, "c")]), + ({"nr": "min", "cat_ord": ["min", "max"]}, [(1, "a", "b"), (5, "c", "d")]), + ({"cat_ord": ["min", "max"]}, [("a", "b"), ("c", "d")]), + ], +) +def test_groupby_combined_aggs_cat_cols(grp_col_dict, exp_data): + # test combined aggregations on ordered categorical cols GH27800 + + # create the result dataframe + input_df = pd.DataFrame( + { + "nr": [1, 2, 3, 4, 5, 6, 7, 8], + "cat_ord": list("aabbccdd"), + "cat": list("aaaabbbb"), + } + ) + + input_df = input_df.astype({"cat": "category", "cat_ord": "category"}) + input_df["cat_ord"] = input_df["cat_ord"].cat.as_ordered() + result_df = input_df.groupby("cat", observed=False).agg(grp_col_dict) + + # create expected dataframe + cat_index = pd.CategoricalIndex( + ["a", "b"], categories=["a", "b"], ordered=False, name="cat", dtype="category" + ) + + # unpack the grp_col_dict to create the multi-index tuple + # this tuple will be used to create the expected dataframe index + multi_index_list = [] + for k, v in grp_col_dict.items(): + if isinstance(v, list): + multi_index_list.extend([k, value] for value in v) + else: + multi_index_list.append([k, v]) + multi_index = pd.MultiIndex.from_tuples(tuple(multi_index_list)) + + expected_df = pd.DataFrame(data=exp_data, columns=multi_index, index=cat_index) + for col in expected_df.columns: + if isinstance(col, tuple) and "cat_ord" in col: + # ordered categorical should be preserved + expected_df[col] = expected_df[col].astype(input_df["cat_ord"].dtype) + + tm.assert_frame_equal(result_df, expected_df) + + +def test_nonagg_agg(): + # GH 35490 - Single/Multiple agg of non-agg function give same results + # TODO: agg should raise for functions that don't aggregate + df = pd.DataFrame({"a": [1, 1, 2, 2], "b": [1, 2, 2, 1]}) + g = df.groupby("a") + + result = g.agg(["cumsum"]) + result.columns = result.columns.droplevel(-1) + expected = g.agg("cumsum") + + tm.assert_frame_equal(result, expected) + + +def test_aggregate_datetime_objects(): + # https://github.com/pandas-dev/pandas/issues/36003 + # ensure we don't raise an error but keep object dtype for out-of-bounds + # datetimes + df = pd.DataFrame( + { + "A": ["X", "Y"], + "B": [ + datetime.datetime(2005, 1, 1, 10, 30, 23, 540000), + datetime.datetime(3005, 1, 1, 10, 30, 23, 540000), + ], + } + ) + result = df.groupby("A").B.max() + expected = df.set_index("A")["B"] + tm.assert_series_equal(result, expected) + + +def test_groupby_index_object_dtype(): + # GH 40014 + df = pd.DataFrame({"c0": ["x", "x", "x"], "c1": ["x", "x", "y"], "p": [0, 1, 2]}) + df.index = df.index.astype("O") + grouped = df.groupby(["c0", "c1"]) + res = grouped.p.agg(lambda x: all(x > 0)) + # Check that providing a user-defined function in agg() + # produces the correct index shape when using an object-typed index. + expected_index = pd.MultiIndex.from_tuples( + [("x", "x"), ("x", "y")], names=("c0", "c1") + ) + expected = pd.Series([False, True], index=expected_index, name="p") + tm.assert_series_equal(res, expected) + + +def test_timeseries_groupby_agg(): + # GH#43290 + + def func(ser): + if ser.isna().all(): + return None + return np.sum(ser) + + df = pd.DataFrame([1.0], index=[pd.Timestamp("2018-01-16 00:00:00+00:00")]) + res = df.groupby(lambda x: 1).agg(func) + + expected = pd.DataFrame([[1.0]], index=[1]) + tm.assert_frame_equal(res, expected) + + +def test_groupby_agg_precision(any_real_numeric_dtype): + if any_real_numeric_dtype in tm.ALL_INT_NUMPY_DTYPES: + max_value = np.iinfo(any_real_numeric_dtype).max + if any_real_numeric_dtype in tm.FLOAT_NUMPY_DTYPES: + max_value = np.finfo(any_real_numeric_dtype).max + if any_real_numeric_dtype in tm.FLOAT_EA_DTYPES: + max_value = np.finfo(any_real_numeric_dtype.lower()).max + if any_real_numeric_dtype in tm.ALL_INT_EA_DTYPES: + max_value = np.iinfo(any_real_numeric_dtype.lower()).max + + df = pd.DataFrame( + { + "key1": ["a"], + "key2": ["b"], + "key3": pd.array([max_value], dtype=any_real_numeric_dtype), + } + ) + arrays = [["a"], ["b"]] + index = pd.MultiIndex.from_arrays(arrays, names=("key1", "key2")) + + expected = pd.DataFrame( + {"key3": pd.array([max_value], dtype=any_real_numeric_dtype)}, index=index + ) + msg = "Converting a Series or array of length 1 into a scalar" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.groupby(["key1", "key2"]).agg(lambda x: x) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregate_directory(reduction_func): + # GH#32793 + if reduction_func in ["corrwith", "nth"]: + return None + + obj = pd.DataFrame([[0, 1], [0, np.nan]]) + + result_reduced_series = obj.groupby(0).agg(reduction_func) + result_reduced_frame = obj.groupby(0).agg({1: reduction_func}) + + if reduction_func in ["size", "ngroup"]: + # names are different: None / 1 + tm.assert_series_equal( + result_reduced_series, result_reduced_frame[1], check_names=False + ) + else: + tm.assert_frame_equal(result_reduced_series, result_reduced_frame) + tm.assert_series_equal( + result_reduced_series.dtypes, result_reduced_frame.dtypes + ) + + +def test_group_mean_timedelta_nat(): + # GH43132 + data = pd.Series(["1 day", "3 days", "NaT"], dtype="timedelta64[ns]") + expected = pd.Series(["2 days"], dtype="timedelta64[ns]", index=np.array([0])) + + result = data.groupby([0, 0, 0]).mean() + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "input_data, expected_output", + [ + ( # no timezone + ["2021-01-01T00:00", "NaT", "2021-01-01T02:00"], + ["2021-01-01T01:00"], + ), + ( # timezone + ["2021-01-01T00:00-0100", "NaT", "2021-01-01T02:00-0100"], + ["2021-01-01T01:00-0100"], + ), + ], +) +def test_group_mean_datetime64_nat(input_data, expected_output): + # GH43132 + data = pd.to_datetime(pd.Series(input_data)) + expected = pd.to_datetime(pd.Series(expected_output, index=np.array([0]))) + + result = data.groupby([0, 0, 0]).mean() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "func, output", [("mean", [8 + 18j, 10 + 22j]), ("sum", [40 + 90j, 50 + 110j])] +) +def test_groupby_complex(func, output): + # GH#43701 + data = pd.Series(np.arange(20).reshape(10, 2).dot([1, 2j])) + result = data.groupby(data.index % 2).agg(func) + expected = pd.Series(output) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("func", ["min", "max", "var"]) +def test_groupby_complex_raises(func): + # GH#43701 + data = pd.Series(np.arange(20).reshape(10, 2).dot([1, 2j])) + msg = "No matching signature found" + with pytest.raises(TypeError, match=msg): + data.groupby(data.index % 2).agg(func) + + +@pytest.mark.parametrize( + "test, constant", + [ + ([[20, "A"], [20, "B"], [10, "C"]], {0: [10, 20], 1: ["C", ["A", "B"]]}), + ([[20, "A"], [20, "B"], [30, "C"]], {0: [20, 30], 1: [["A", "B"], "C"]}), + ([["a", 1], ["a", 1], ["b", 2], ["b", 3]], {0: ["a", "b"], 1: [1, [2, 3]]}), + ([["a", 1], ["a", 2], ["b", 3], ["b", 3]], {0: ["a", "b"], 1: [[1, 2], 3]}), + ], +) +def test_agg_of_mode_list(test, constant): + # GH#25581 + df1 = pd.DataFrame(test) + msg = "Converting a Series or array of length 1 into a scalar" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df1.groupby(0).agg(pd.Series.mode) + # Mode usually only returns 1 value, but can return a list in the case of a tie. + + expected = pd.DataFrame(constant) + expected = expected.set_index(0) + + tm.assert_frame_equal(result, expected) + + +def test_dataframe_groupy_agg_list_like_func_with_args(): + # GH#50624 + df = pd.DataFrame({"x": [1, 2, 3], "y": ["a", "b", "c"]}) + gb = df.groupby("y") + + def foo1(x, a=1, c=0): + return x.sum() + a + c + + def foo2(x, b=2, c=0): + return x.sum() + b + c + + msg = r"foo1\(\) got an unexpected keyword argument 'b'" + with pytest.raises(TypeError, match=msg): + gb.agg([foo1, foo2], 3, b=3, c=4) + + result = gb.agg([foo1, foo2], 3, c=4) + expected = pd.DataFrame( + [[8, 8], [9, 9], [10, 10]], + index=pd.Index(["a", "b", "c"], name="y"), + columns=pd.MultiIndex.from_tuples([("x", "foo1"), ("x", "foo2")]), + ) + tm.assert_frame_equal(result, expected) + + +def test_series_groupy_agg_list_like_func_with_args(): + # GH#50624 + s = pd.Series([1, 2, 3]) + sgb = s.groupby(s) + + def foo1(x, a=1, c=0): + return x.sum() + a + c + + def foo2(x, b=2, c=0): + return x.sum() + b + c + + msg = r"foo1\(\) got an unexpected keyword argument 'b'" + with pytest.raises(TypeError, match=msg): + sgb.agg([foo1, foo2], 3, b=3, c=4) + + result = sgb.agg([foo1, foo2], 3, c=4) + expected = pd.DataFrame( + [[8, 8], [9, 9], [10, 10]], index=pd.Index([1, 2, 3]), columns=["foo1", "foo2"] + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_groupings_selection(): + # GH#51186 - a selected grouping should be in the output of agg + df = pd.DataFrame({"a": [1, 1, 2], "b": [3, 3, 4], "c": [5, 6, 7]}) + gb = df.groupby(["a", "b"]) + selected_gb = gb[["b", "c"]] + result = selected_gb.agg(lambda x: x.sum()) + index = pd.MultiIndex( + levels=[[1, 2], [3, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"] + ) + expected = pd.DataFrame({"b": [6, 4], "c": [11, 7]}, index=index) + tm.assert_frame_equal(result, expected) + + +def test_agg_multiple_with_as_index_false_subset_to_a_single_column(): + # GH#50724 + df = pd.DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + gb = df.groupby("a", as_index=False)["b"] + result = gb.agg(["sum", "mean"]) + expected = pd.DataFrame({"a": [1, 2], "sum": [7, 5], "mean": [3.5, 5.0]}) + tm.assert_frame_equal(result, expected) + + +def test_agg_with_as_index_false_with_list(): + # GH#52849 + df = pd.DataFrame({"a1": [0, 0, 1], "a2": [2, 3, 3], "b": [4, 5, 6]}) + gb = df.groupby(by=["a1", "a2"], as_index=False) + result = gb.agg(["sum"]) + + expected = pd.DataFrame( + data=[[0, 2, 4], [0, 3, 5], [1, 3, 6]], + columns=pd.MultiIndex.from_tuples([("a1", ""), ("a2", ""), ("b", "sum")]), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_extension_timedelta_cumsum_with_named_aggregation(): + # GH#41720 + expected = pd.DataFrame( + { + "td": { + 0: pd.Timedelta("0 days 01:00:00"), + 1: pd.Timedelta("0 days 01:15:00"), + 2: pd.Timedelta("0 days 01:15:00"), + } + } + ) + df = pd.DataFrame( + { + "td": pd.Series( + ["0 days 01:00:00", "0 days 00:15:00", "0 days 01:15:00"], + dtype="timedelta64[us]", + ), + "grps": ["a", "a", "b"], + } + ) + gb = df.groupby("grps") + result = gb.agg(td=("td", "cumsum")) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_empty_group(): + # https://github.com/pandas-dev/pandas/issues/18869 + def func(x): + if len(x) == 0: + raise ValueError("length must not be 0") + return len(x) + + df = pd.DataFrame( + {"A": pd.Categorical(["a", "a"], categories=["a", "b", "c"]), "B": [1, 1]} + ) + msg = "length must not be 0" + with pytest.raises(ValueError, match=msg): + df.groupby("A", observed=False).agg(func) + + +def test_groupby_aggregation_duplicate_columns_single_dict_value(): + # GH#55041 + df = pd.DataFrame( + [[1, 2, 3, 4], [1, 3, 4, 5], [2, 4, 5, 6]], + columns=["a", "b", "c", "c"], + ) + gb = df.groupby("a") + result = gb.agg({"c": "sum"}) + + expected = pd.DataFrame( + [[7, 9], [5, 6]], columns=["c", "c"], index=pd.Index([1, 2], name="a") + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_duplicate_columns_multiple_dict_values(): + # GH#55041 + df = pd.DataFrame( + [[1, 2, 3, 4], [1, 3, 4, 5], [2, 4, 5, 6]], + columns=["a", "b", "c", "c"], + ) + gb = df.groupby("a") + result = gb.agg({"c": ["sum", "min", "max", "min"]}) + + expected = pd.DataFrame( + [[7, 3, 4, 3, 9, 4, 5, 4], [5, 5, 5, 5, 6, 6, 6, 6]], + columns=pd.MultiIndex( + levels=[["c"], ["sum", "min", "max"]], + codes=[[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 1, 0, 1, 2, 1]], + ), + index=pd.Index([1, 2], name="a"), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_duplicate_columns_some_empty_result(): + # GH#55041 + df = pd.DataFrame( + [ + [1, 9843, 43, 54, 7867], + [2, 940, 9, -34, 44], + [1, -34, -546, -549358, 0], + [2, 244, -33, -100, 44], + ], + columns=["a", "b", "b", "c", "c"], + ) + gb = df.groupby("a") + result = gb.agg({"b": [], "c": ["var"]}) + + expected = pd.DataFrame( + [[1.509268e11, 30944844.5], [2.178000e03, 0.0]], + columns=pd.MultiIndex(levels=[["c"], ["var"]], codes=[[0, 0], [0, 0]]), + index=pd.Index([1, 2], name="a"), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_multi_index_duplicate_columns(): + # GH#55041 + df = pd.DataFrame( + [ + [1, -9843, 43, 54, 7867], + [2, 940, 9, -34, 44], + [1, -34, 546, -549358, 0], + [2, 244, -33, -100, 44], + ], + columns=pd.MultiIndex( + levels=[["level1.1", "level1.2"], ["level2.1", "level2.2"]], + codes=[[0, 0, 0, 1, 1], [0, 1, 1, 0, 1]], + ), + index=pd.MultiIndex( + levels=[["level1.1", "level1.2"], ["level2.1", "level2.2"]], + codes=[[0, 0, 0, 1], [0, 1, 1, 0]], + ), + ) + gb = df.groupby(level=0) + result = gb.agg({("level1.1", "level2.2"): "min"}) + + expected = pd.DataFrame( + [[-9843, 9], [244, -33]], + columns=pd.MultiIndex( + levels=[["level1.1"], ["level2.2"]], codes=[[0, 0], [0, 0]] + ), + index=pd.Index(["level1.1", "level1.2"]), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_func_list_multi_index_duplicate_columns(): + # GH#55041 + df = pd.DataFrame( + [ + [1, -9843, 43, 54, 7867], + [2, 940, 9, -34, 44], + [1, -34, 546, -549358, 0], + [2, 244, -33, -100, 44], + ], + columns=pd.MultiIndex( + levels=[["level1.1", "level1.2"], ["level2.1", "level2.2"]], + codes=[[0, 0, 0, 1, 1], [0, 1, 1, 0, 1]], + ), + index=pd.MultiIndex( + levels=[["level1.1", "level1.2"], ["level2.1", "level2.2"]], + codes=[[0, 0, 0, 1], [0, 1, 1, 0]], + ), + ) + gb = df.groupby(level=0) + result = gb.agg({("level1.1", "level2.2"): ["min", "max"]}) + + expected = pd.DataFrame( + [[-9843, 940, 9, 546], [244, 244, -33, -33]], + columns=pd.MultiIndex( + levels=[["level1.1"], ["level2.2"], ["min", "max"]], + codes=[[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 1]], + ), + index=pd.Index(["level1.1", "level1.2"]), + ) + tm.assert_frame_equal(result, expected) + + +@td.skip_if_no("pyarrow") +@pytest.mark.parametrize( + "dtype", + ["float[pyarrow]", "int64[pyarrow]", "uint64[pyarrow]", "bool[pyarrow]"], +) +def test_agg_lambda_pyarrow_dtype_conversion(dtype): + # GH#59601 + # Test PyArrow dtype conversion back to PyArrow dtype + df = pd.DataFrame( + { + "A": ["c1", "c2", "c3", "c1", "c2", "c3"], + "B": pd.array([100, 200, 255, 0, 199, 40392], dtype=dtype), + } + ) + gb = df.groupby("A") + result = gb.agg(lambda x: x.min()) + + expected = pd.DataFrame( + {"B": pd.array([0, 199, 255], dtype=dtype)}, + index=pd.Index(["c1", "c2", "c3"], name="A"), + ) + tm.assert_frame_equal(result, expected) + + +@td.skip_if_no("pyarrow") +def test_agg_lambda_complex128_dtype_conversion(): + # GH#59601 + df = pd.DataFrame( + {"A": ["c1", "c2", "c3"], "B": pd.array([100, 200, 255], "int64[pyarrow]")} + ) + gb = df.groupby("A") + result = gb.agg(lambda x: complex(x.sum(), x.count())) + + expected = pd.DataFrame( + { + "B": pd.array( + [complex(100, 1), complex(200, 1), complex(255, 1)], dtype="complex128" + ), + }, + index=pd.Index(["c1", "c2", "c3"], name="A"), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "dtype, value, expected_dtype", + [ + (pd.StringDtype(na_value=np.nan), 2**70, object), + pytest.param("string[pyarrow]", 2**70, object, marks=td.skip_if_no("pyarrow")), + pytest.param("int64[pyarrow]", 2**70, object, marks=td.skip_if_no("pyarrow")), + ("Int64", pd.NaT, "M8[s]"), + ("Float64", pd.NaT, "M8[s]"), + ("boolean", pd.NaT, "M8[s]"), + ], +) +def test_agg_lambda_result_dtype_cannot_hold(dtype, value, expected_dtype): + # GH#70233 used to raise instead of inferring the result dtype + df = pd.DataFrame({"key": [1, 1, 2], "val": pd.Series([1, 0, 1], dtype=dtype)}) + result = df.groupby("key")["val"].agg(lambda x: value) + expected = pd.Series( + [value, value], + index=pd.Index([1, 2], name="key"), + name="val", + dtype=expected_dtype, + ) + tm.assert_series_equal(result, expected) + + +@td.skip_if_no("pyarrow") +def test_agg_lambda_numpy_uint64_to_pyarrow_dtype_conversion(): + # GH#59601 + df = pd.DataFrame( + { + "A": ["c1", "c2", "c3"], + "B": pd.array([100, 200, 255], dtype="uint64[pyarrow]"), + } + ) + gb = df.groupby("A") + result = gb.agg(lambda x: np.uint64(x.sum())) + + expected = pd.DataFrame( + { + "B": pd.array([100, 200, 255], dtype="uint64[pyarrow]"), + }, + index=pd.Index(["c1", "c2", "c3"], name="A"), + ) + tm.assert_frame_equal(result, expected) + + +@td.skip_if_no("pyarrow") +def test_agg_lambda_pyarrow_struct_to_object_dtype_conversion(): + # GH#59601 + import pyarrow as pa + + df = pd.DataFrame( + { + "A": ["c1", "c2", "c3"], + "B": pd.array([100, 200, 255], dtype="int64[pyarrow]"), + } + ) + gb = df.groupby("A") + result = gb.agg(lambda x: {"number": 1}) + + arr = pa.array([{"number": 1}, {"number": 1}, {"number": 1}]) + expected = pd.DataFrame( + {"B": ArrowExtensionArray(arr)}, + index=pd.Index(["c1", "c2", "c3"], name="A"), + ) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregate_empty_builtin_sum(): + df = pd.DataFrame(columns=["Group", "Data"]) + result = df.groupby(["Group"], as_index=False)["Data"].agg("sum") + expected = pd.DataFrame(columns=["Group", "Data"]) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregate_empty_udf(): + def func(x): + return sum(x) + + df = pd.DataFrame(columns=["Group", "Data"]) + result = df.groupby(["Group"], as_index=False)["Data"].agg(func) + expected = pd.DataFrame(columns=["Group", "Data"]) + tm.assert_frame_equal(result, expected) + + +def test_agg_relabel_with_name_match(): + # GH-63742 + df = pd.DataFrame( + { + "group": ["a", "a", "b", "b"], + "value": [1, 2, 3, 4], + "count": [10, 20, 30, 40], + } + ) + + # Test with tuple format where output names match column names + result = df.groupby("group").agg(value=("value", "sum"), count=("count", "max")) + + # Should produce same result as dict format + expected = df.groupby("group").agg({"value": "sum", "count": "max"}) + + tm.assert_frame_equal(result, expected) + + +def test_agg_relabel_with_name_match_and_namedagg(): + # GH-63742 + df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) + + result = df.groupby("A").agg(B=pd.NamedAgg("B", "sum")) + + expected = pd.DataFrame({"B": [3, 7]}, index=pd.Index([0, 1], name="A")) + tm.assert_frame_equal(result, expected) + + +def test_agg_relabel_with_name_match_listlike_aggfunc(): + # GH#63743 a list-like aggfunc takes the same path whether or not the output + # name matches the column name + df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) + + with pytest.raises(TypeError, match="unhashable"): + df.groupby("A").agg(B=("B", ["sum", "max"])) + + with pytest.raises(TypeError, match="unhashable"): + df.groupby("A").agg(x=("B", ["sum", "max"])) + + # a tuple aggfunc is read as a single (name, func) pair, not two aggfuncs + result = df.groupby("A").agg(B=("B", ("sum", "max"))) + expected = df.groupby("A").agg(x=("B", ("sum", "max"))) + expected.columns = ["B"] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("aggfunc", ["describe", "ohlc"]) +def test_agg_relabel_with_name_match_non_reduction(aggfunc): + # GH#63743 a string aggfunc that is not a reduction gives a frame per group, + # so it must still produce one output column per keyword when the output + # name matches the column name + df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) + + result = df.groupby("A").agg(B=("B", aggfunc)) + expected = df.groupby("A").agg(z=("B", aggfunc)) + expected.columns = ["B"] + tm.assert_frame_equal(result, expected) + + result = df.groupby("A").agg(B=pd.NamedAgg("B", aggfunc)) + tm.assert_frame_equal(result, expected) + + +def test_agg_relabel_with_name_match_duplicate_columns(): + # GH#63743 named aggregation gives one output column per keyword even when + # the source label is duplicated and the output name matches it + df = pd.DataFrame( + [[0, 1, 2], [0, 3, 4], [1, 5, 6], [1, 7, 8]], columns=["A", "B", "B"] + ) + + result = df.groupby("A").agg(B=("B", "sum")) + expected = df.groupby("A").agg(x=("B", "sum")) + expected.columns = ["B"] + tm.assert_frame_equal(result, expected) + + result = df.groupby("A").agg(B=pd.NamedAgg("B", "sum")) + tm.assert_frame_equal(result, expected) + + +def test_agg_relabel_with_name_match_named_columns(): + # GH#68000 the result's columns are unnamed whether or not the output name + # matches the column name + df = pd.DataFrame({"A": [0, 0, 1], "B": [1, 2, 3]}) + df.columns.name = "metric" + + result = df.groupby("A").agg(B=("B", "sum")) + expected = df.groupby("A").agg(x=("B", "sum")) + expected.columns = ["B"] + tm.assert_frame_equal(result, expected) + + result = df.groupby("A").agg(B=pd.NamedAgg("B", "sum")) + tm.assert_frame_equal(result, expected) + + +def test_multiple_partial_functions_same_name(): + # GH#28570 + quant50 = partial(np.percentile, q=50) + quant70 = partial(np.percentile, q=70) + + df = pd.DataFrame({"col1": ["a", "a", "b", "b", "b"], "col2": [1, 2, 3, 4, 5]}) + expected = pd.DataFrame( + [[1.5, 1.7], [4.0, 4.4]], + index=pd.Index(["a", "b"], name="col1"), + columns=pd.MultiIndex( + levels=[["col2"], ["percentile"]], + codes=[[0, 0], [0, 0]], + ), + ) + gb = df.groupby("col1") + result = gb.agg({"col2": [quant50, quant70]}) + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_dict_with_duplicate_multiindex_columns(): + # GH#50402 aggregating with a dict when the frame has duplicate MultiIndex + # columns must not raise AttributeError + df = pd.DataFrame( + [[1, 2, 3], [4, 5, 6]], + columns=pd.MultiIndex.from_tuples([("a", 0), ("b", 0), ("b", 0)]), + ) + # pin the grouping key dtype: a list key goes through np.asarray, which is + # platform-dependent, while Index([1, 2]) always infers int64 + result = df.groupby(by=np.array([1, 2], dtype=np.int64)).agg({("a", 0): "sum"}) + expected = pd.DataFrame( + [[1], [4]], + index=pd.Index([1, 2], dtype=np.int64), + columns=pd.MultiIndex.from_tuples([("a", 0)]), + ) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_cython.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_cython.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b2c2ff926b7d53c190df54291c09963199fc11 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_cython.py @@ -0,0 +1,406 @@ +""" +test cython .agg behavior +""" + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +from pandas.core.dtypes.common import ( + is_float_dtype, + is_integer_dtype, +) + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize( + "op_name", + [ + "count", + "sum", + "std", + "var", + "sem", + "mean", + "median", + "prod", + "min", + "max", + ], +) +def test_cythonized_aggers(op_name): + data = { + "A": [0, 0, 0, 0, 1, 1, 1, 1, 1, 1.0, np.nan, np.nan], + "B": ["A", "B"] * 6, + "C": np.random.default_rng(2).standard_normal(12), + } + df = pd.DataFrame(data) + df.loc[2:10:2, "C"] = np.nan + + op = lambda x: getattr(x, op_name)() + + # single column + grouped = df.drop(["B"], axis=1).groupby("A") + exp = {cat: op(group["C"]) for cat, group in grouped} + exp = pd.DataFrame({"C": exp}) + exp.index.name = "A" + result = op(grouped) + tm.assert_frame_equal(result, exp) + + # multiple columns + grouped = df.groupby(["A", "B"]) + expd = {} + for (cat1, cat2), group in grouped: + expd.setdefault(cat1, {})[cat2] = op(group["C"]) + exp = pd.DataFrame(expd).T.stack() + exp.index.names = ["A", "B"] + exp.name = "C" + + result = op(grouped)["C"] + if op_name in ["sum", "prod"]: + tm.assert_series_equal(result, exp) + + +def test_cython_agg_boolean(): + frame = pd.DataFrame( + { + "a": np.random.default_rng(2).integers(0, 5, 50), + "b": np.random.default_rng(2).integers(0, 2, 50).astype("bool"), + } + ) + result = frame.groupby("a")["b"].mean() + # GH#53425 + expected = frame.groupby("a")["b"].agg(np.mean) + + tm.assert_series_equal(result, expected) + + +def test_cython_agg_nothing_to_agg(): + frame = pd.DataFrame( + {"a": np.random.default_rng(2).integers(0, 5, 50), "b": ["foo", "bar"] * 25} + ) + + msg = "Cannot use numeric_only=True with SeriesGroupBy.mean and non-numeric dtypes" + with pytest.raises(TypeError, match=msg): + frame.groupby("a")["b"].mean(numeric_only=True) + + frame = pd.DataFrame( + {"a": np.random.default_rng(2).integers(0, 5, 50), "b": ["foo", "bar"] * 25} + ) + + result = frame[["b"]].groupby(frame["a"]).mean(numeric_only=True) + expected = pd.DataFrame( + [], + index=frame["a"].sort_values().drop_duplicates(), + columns=pd.Index([], dtype="str"), + ) + tm.assert_frame_equal(result, expected) + + +def test_cython_agg_nothing_to_agg_with_dates(): + frame = pd.DataFrame( + { + "a": np.random.default_rng(2).integers(0, 5, 50), + "b": ["foo", "bar"] * 25, + "dates": pd.date_range("2011-01-01", periods=50, freq="min"), + } + ) + msg = "Cannot use numeric_only=True with SeriesGroupBy.mean and non-numeric dtypes" + with pytest.raises(TypeError, match=msg): + frame.groupby("b").dates.mean(numeric_only=True) + + +def test_cython_agg_return_dict(): + # GH 16741 + df = pd.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), + } + ) + + ts = df.groupby("A")["B"].agg(lambda x: x.value_counts().to_dict()) + expected = pd.Series( + [{"two": 1, "one": 1, "three": 1}, {"two": 2, "one": 2, "three": 1}], + index=pd.Index(["bar", "foo"], name="A"), + name="B", + ) + tm.assert_series_equal(ts, expected) + + +def test_cython_fail_agg(): + dr = pd.bdate_range("1/1/2000", periods=50) + ts = pd.Series(["A", "B", "C", "D", "E"] * 10, dtype=object, index=dr) + + grouped = ts.groupby(lambda x: x.month) + summed = grouped.sum() + expected = grouped.agg(np.sum).astype(object) + tm.assert_series_equal(summed, expected) + + +@pytest.mark.parametrize( + "op, targop", + [ + ("mean", np.mean), + ("median", np.median), + ("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]), + ], +) +def test__cython_agg_general(op, targop): + df = pd.DataFrame(np.random.default_rng(2).standard_normal(1000)) + labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) + kwargs = {"ddof": 1} if op == "var" else {} + if op not in ["first", "last"]: + kwargs["axis"] = 0 + + result = df.groupby(labels)._cython_agg_general(op, alt=None, numeric_only=True) + expected = df.groupby(labels).agg(targop, **kwargs) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op, targop", + [ + ("mean", np.mean), + ("median", lambda x: np.median(x) if len(x) > 0 else np.nan), + ("var", lambda x: np.var(x, ddof=1)), + ("min", np.min), + ("max", np.max), + ], +) +def test_cython_agg_empty_buckets(op, targop, observed): + df = pd.DataFrame([11, 12, 13]) + grps = range(0, 55, 5) + + # calling _cython_agg_general directly, instead of via the user API + # which sets different values for min_count, so do that here. + g = df.groupby(pd.cut(df[0], grps), observed=observed) + result = g._cython_agg_general(op, alt=None, numeric_only=True) + + g = df.groupby(pd.cut(df[0], grps), observed=observed) + expected = g.agg(lambda x: targop(x)) + tm.assert_frame_equal(result, expected) + + +def test_cython_agg_empty_buckets_nanops(observed): + # GH-18869 can't call nanops on empty groups, so hardcode expected + # for these + df = pd.DataFrame([11, 12, 13], columns=["a"]) + grps = np.arange(0, 25, 5, dtype=int) + # add / sum + result = df.groupby(pd.cut(df["a"], grps), observed=observed)._cython_agg_general( + "sum", alt=None, numeric_only=True + ) + intervals = pd.interval_range(0, 20, freq=5) + expected = pd.DataFrame( + {"a": [0, 0, 36, 0]}, + index=pd.CategoricalIndex(intervals, name="a", ordered=True), + ) + if observed: + expected = expected[expected.a != 0] + + tm.assert_frame_equal(result, expected) + + # prod + result = df.groupby(pd.cut(df["a"], grps), observed=observed)._cython_agg_general( + "prod", alt=None, numeric_only=True + ) + expected = pd.DataFrame( + {"a": [1, 1, 1716, 1]}, + index=pd.CategoricalIndex(intervals, name="a", ordered=True), + ) + if observed: + expected = expected[expected.a != 1] + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("op", ["first", "last", "max", "min"]) +@pytest.mark.parametrize( + "data", + [pd.Timestamp("2016-10-14 21:00:44.557"), pd.Timedelta("17088 days 21:00:44.557")], +) +def test_cython_with_timestamp_and_nat(op, data): + # https://github.com/pandas-dev/pandas/issues/19526 + df = pd.DataFrame({"a": [0, 1], "b": [data, pd.NaT]}) + index = pd.Index([0, 1], name="a") + + # We will group by a and test the cython aggregations + expected = pd.DataFrame({"b": [data, pd.NaT]}, index=index) + + result = df.groupby("a").aggregate(op) + tm.assert_frame_equal(expected, result) + + +@pytest.mark.parametrize( + "agg", + [ + "min", + "max", + "count", + "sum", + "prod", + "var", + "mean", + "median", + "ohlc", + "cumprod", + "cumsum", + "shift", + "any", + "all", + "quantile", + "first", + "last", + "rank", + "cummin", + "cummax", + ], +) +def test_read_only_buffer_source_agg(agg): + # https://github.com/pandas-dev/pandas/issues/36014 + df = pd.DataFrame( + { + "sepal_length": [5.1, 4.9, 4.7, 4.6, 5.0], + "species": ["setosa", "setosa", "setosa", "setosa", "setosa"], + } + ) + df._mgr.blocks[0].values.flags.writeable = False + + result = df.groupby(["species"]).agg({"sepal_length": agg}) + expected = df.copy().groupby(["species"]).agg({"sepal_length": agg}) + + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "op_name", + [ + "count", + "sum", + "std", + "var", + "sem", + "mean", + "median", + "prod", + "min", + "max", + ], +) +def test_cython_agg_nullable_int(op_name): + # ensure that the cython-based aggregations don't fail for nullable dtype + # (eg https://github.com/pandas-dev/pandas/issues/37415) + df = pd.DataFrame( + { + "A": ["A", "B"] * 5, + "B": pd.array([1, 2, 3, 4, 5, 6, 7, 8, 9, pd.NA], dtype="Int64"), + } + ) + result = getattr(df.groupby("A")["B"], op_name)() + df2 = df.assign(B=df["B"].astype("float64")) + expected = getattr(df2.groupby("A")["B"], op_name)() + if op_name in ("mean", "median"): + convert_integer = False + else: + convert_integer = True + msg = "The convert_integer keyword in Series.convert_dtypes is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = expected.convert_dtypes(convert_integer=convert_integer) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"]) +def test_count_masked_returns_masked_dtype(dtype): + df = pd.DataFrame( + { + "A": [1, 1], + "B": pd.array([1, pd.NA], dtype=dtype), + "C": pd.array([1, 1], dtype=dtype), + } + ) + result = df.groupby("A").count() + expected = pd.DataFrame( + [[1, 2]], index=pd.Index([1], name="A"), columns=["B", "C"], dtype="Int64" + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("with_na", [True, False]) +@pytest.mark.parametrize( + "op_name, action", + [ + # ("count", "always_int"), + ("sum", "large_int"), + # ("std", "always_float"), + ("var", "always_float"), + # ("sem", "always_float"), + ("mean", "always_float"), + ("median", "always_float"), + ("prod", "large_int"), + ("min", "preserve"), + ("max", "preserve"), + ("first", "preserve"), + ("last", "preserve"), + ], +) +@pytest.mark.parametrize( + "data", + [ + pd.array([1, 2, 3, 4], dtype="Int64"), + pd.array([1, 2, 3, 4], dtype="Int8"), + pd.array([0.1, 0.2, 0.3, 0.4], dtype="Float32"), + pd.array([0.1, 0.2, 0.3, 0.4], dtype="Float64"), + pd.array([True, True, False, False], dtype="boolean"), + ], +) +def test_cython_agg_EA_known_dtypes(data, op_name, action, with_na): + if with_na: + data[3] = pd.NA + + df = pd.DataFrame({"key": ["a", "a", "b", "b"], "col": data}) + grouped = df.groupby("key") + + if action == "always_int": + # always Int64 + expected_dtype = pd.Int64Dtype() + elif action == "large_int": + # for any int/bool use Int64, for float preserve dtype + if is_float_dtype(data.dtype): + expected_dtype = data.dtype + elif is_integer_dtype(data.dtype): + # match the numpy dtype we'd get with the non-nullable analogue + expected_dtype = data.dtype + else: + expected_dtype = pd.Int64Dtype() + elif action == "always_float": + # for any int/bool use Float64, for float preserve dtype + if is_float_dtype(data.dtype): + expected_dtype = data.dtype + else: + expected_dtype = pd.Float64Dtype() + elif action == "preserve": + expected_dtype = data.dtype + + result = getattr(grouped, op_name)() + assert result["col"].dtype == expected_dtype + + result = grouped.aggregate(op_name) + assert result["col"].dtype == expected_dtype + + result = getattr(grouped["col"], op_name)() + assert result.dtype == expected_dtype + + result = grouped["col"].aggregate(op_name) + assert result.dtype == expected_dtype diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_numba.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_numba.py new file mode 100644 index 0000000000000000000000000000000000000000..017fde531cc7c4f0685aec96f5877aa69a7879c2 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_numba.py @@ -0,0 +1,441 @@ +import numpy as np +import pytest + +from pandas.compat import is_platform_arm +from pandas.errors import NumbaUtilError + +import pandas as pd +import pandas._testing as tm +from pandas.util.version import Version + +pytestmark = [pytest.mark.single_cpu] + +numba = pytest.importorskip("numba") +pytestmark.append( + pytest.mark.skipif( + Version(numba.__version__) == Version("0.61") and is_platform_arm(), + reason=f"Segfaults on ARM platforms with numba {numba.__version__}", + ) +) + + +def test_correct_function_signature(): + pytest.importorskip("numba") + + def incorrect_function(x): + return sum(x) * 2.7 + + data = pd.DataFrame( + {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, + columns=["key", "data"], + ) + with pytest.raises(NumbaUtilError, match="The first 2"): + data.groupby("key").agg(incorrect_function, engine="numba") + + with pytest.raises(NumbaUtilError, match="The first 2"): + data.groupby("key")["data"].agg(incorrect_function, engine="numba") + + +def test_check_nopython_kwargs(): + pytest.importorskip("numba") + + def incorrect_function(values, index, *, a): + return sum(values) * 2.7 + a + + def correct_function(values, index, a): + return sum(values) * 2.7 + a + + data = pd.DataFrame( + {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, + columns=["key", "data"], + ) + expected = data.groupby("key").sum() * 2.7 + + # py signature binding + with pytest.raises( + TypeError, match="missing a required (keyword-only argument|argument): 'a'" + ): + data.groupby("key").agg(incorrect_function, engine="numba", b=1) + with pytest.raises(TypeError, match="missing a required argument: 'a'"): + data.groupby("key").agg(correct_function, engine="numba", b=1) + + with pytest.raises( + TypeError, match="missing a required (keyword-only argument|argument): 'a'" + ): + data.groupby("key")["data"].agg(incorrect_function, engine="numba", b=1) + with pytest.raises(TypeError, match="missing a required argument: 'a'"): + data.groupby("key")["data"].agg(correct_function, engine="numba", b=1) + + # numba signature check after binding + with pytest.raises(NumbaUtilError, match="numba does not support"): + data.groupby("key").agg(incorrect_function, engine="numba", a=1) + actual = data.groupby("key").agg(correct_function, engine="numba", a=1) + tm.assert_frame_equal(expected + 1, actual) + + with pytest.raises(NumbaUtilError, match="numba does not support"): + data.groupby("key")["data"].agg(incorrect_function, engine="numba", a=1) + actual = data.groupby("key")["data"].agg(correct_function, engine="numba", a=1) + tm.assert_series_equal(expected["data"] + 1, actual) + + +@pytest.mark.filterwarnings("ignore") +# Filter warnings when parallel=True and the function can't be parallelized by Numba +@pytest.mark.parametrize("jit", [True, False]) +def test_numba_vs_cython(jit, frame_or_series, nogil, parallel, as_index): + pytest.importorskip("numba") + + def func_numba(values, index): + return np.mean(values) * 2.7 + + if jit: + # Test accepted jitted functions + import numba + + func_numba = numba.jit(func_numba) + + data = pd.DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] + ) + engine_kwargs = { + "nogil": nogil, + "parallel": parallel, + } + grouped = data.groupby(0, as_index=as_index) + if frame_or_series is pd.Series: + grouped = grouped[1] + + result = grouped.agg(func_numba, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.agg(lambda x: np.mean(x) * 2.7, engine="cython") + + tm.assert_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore") +# Filter warnings when parallel=True and the function can't be parallelized by Numba +@pytest.mark.parametrize("jit", [True, False]) +def test_cache(jit, frame_or_series, nogil, parallel): + # Test that the functions are cached correctly if we switch functions + pytest.importorskip("numba") + + def func_1(values, index): + return np.mean(values) - 3.4 + + def func_2(values, index): + return np.mean(values) * 2.7 + + if jit: + import numba + + func_1 = numba.jit(func_1) + func_2 = numba.jit(func_2) + + data = pd.DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] + ) + engine_kwargs = { + "nogil": nogil, + "parallel": parallel, + } + grouped = data.groupby(0) + if frame_or_series is pd.Series: + grouped = grouped[1] + + result = grouped.agg(func_1, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.agg(lambda x: np.mean(x) - 3.4, engine="cython") + tm.assert_equal(result, expected) + + # Add func_2 to the cache + result = grouped.agg(func_2, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.agg(lambda x: np.mean(x) * 2.7, engine="cython") + tm.assert_equal(result, expected) + + # Retest func_1 which should use the cache + result = grouped.agg(func_1, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.agg(lambda x: np.mean(x) - 3.4, engine="cython") + tm.assert_equal(result, expected) + + +def test_use_global_config(): + pytest.importorskip("numba") + + def func_1(values, index): + return np.mean(values) - 3.4 + + data = pd.DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] + ) + grouped = data.groupby(0) + expected = grouped.agg(func_1, engine="numba") + with pd.option_context("compute.use_numba", True): + result = grouped.agg(func_1, engine=None) + tm.assert_frame_equal(expected, result) + + +@pytest.mark.parametrize( + "agg_kwargs", + [ + {"func": ["min", "max"]}, + {"func": "min"}, + {"func": {1: ["min", "max"], 2: "sum"}}, + {"bmin": pd.NamedAgg(column=1, aggfunc="min")}, + ], +) +def test_multifunc_numba_vs_cython_frame(agg_kwargs): + pytest.importorskip("numba") + data = pd.DataFrame( + { + 0: ["a", "a", "b", "b", "a"], + 1: [1.0, 2.0, 3.0, 4.0, 5.0], + 2: [1, 2, 3, 4, 5], + }, + columns=[0, 1, 2], + ) + grouped = data.groupby(0) + result = grouped.agg(**agg_kwargs, engine="numba") + expected = grouped.agg(**agg_kwargs, engine="cython") + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["sum", "mean", "var", "std", "min", "max"]) +def test_multifunc_numba_vs_cython_frame_noskipna(func): + pytest.importorskip("numba") + data = pd.DataFrame( + { + 0: ["a", "a", "b", "b", "a"], + 1: [1.0, np.nan, 3.0, 4.0, 5.0], + 2: [1, 2, 3, 4, 5], + }, + columns=[0, 1, 2], + ) + grouped = data.groupby(0) + result = grouped.agg(func, skipna=False, engine="numba") + expected = grouped.agg(func, skipna=False, engine="cython") + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "agg_kwargs,expected_func", + [ + ({"func": lambda values, index: values.sum()}, "sum"), + pytest.param( + { + "func": [ + lambda values, index: values.sum(), + lambda values, index: values.min(), + ] + }, + ["sum", "min"], + marks=pytest.mark.xfail( + reason="This doesn't work yet! Fails in nopython pipeline!" + ), + ), + ], +) +def test_multifunc_numba_udf_frame(agg_kwargs, expected_func): + pytest.importorskip("numba") + data = pd.DataFrame( + { + 0: ["a", "a", "b", "b", "a"], + 1: [1.0, 2.0, 3.0, 4.0, 5.0], + 2: [1, 2, 3, 4, 5], + }, + columns=[0, 1, 2], + ) + grouped = data.groupby(0) + result = grouped.agg(**agg_kwargs, engine="numba") + expected = grouped.agg(expected_func, engine="cython") + # check_dtype can be removed if GH 44952 is addressed + # Currently, UDFs still always return float64 while reductions can preserve dtype + tm.assert_frame_equal(result, expected, check_dtype=False) + + +@pytest.mark.parametrize( + "agg_kwargs", + [{"func": ["min", "max"]}, {"func": "min"}, {"min_val": "min", "max_val": "max"}], +) +def test_multifunc_numba_vs_cython_series(agg_kwargs): + pytest.importorskip("numba") + labels = ["a", "a", "b", "b", "a"] + data = pd.Series([1.0, 2.0, 3.0, 4.0, 5.0]) + grouped = data.groupby(labels) + agg_kwargs["engine"] = "numba" + result = grouped.agg(**agg_kwargs) + agg_kwargs["engine"] = "cython" + expected = grouped.agg(**agg_kwargs) + if isinstance(expected, pd.DataFrame): + tm.assert_frame_equal(result, expected) + else: + tm.assert_series_equal(result, expected) + + +@pytest.mark.single_cpu +# numba.core.errors.NumbaTypeSafetyWarning: unsafe cast from uint64 to int64. +@pytest.mark.filterwarnings("ignore") +@pytest.mark.parametrize( + "data,agg_kwargs", + [ + (pd.Series([1.0, 2.0, 3.0, 4.0, 5.0]), {"func": ["min", "max"]}), + (pd.Series([1.0, 2.0, 3.0, 4.0, 5.0]), {"func": "min"}), + ( + pd.DataFrame( + {1: [1.0, 2.0, 3.0, 4.0, 5.0], 2: [1, 2, 3, 4, 5]}, columns=[1, 2] + ), + {"func": ["min", "max"]}, + ), + ( + pd.DataFrame( + {1: [1.0, 2.0, 3.0, 4.0, 5.0], 2: [1, 2, 3, 4, 5]}, columns=[1, 2] + ), + {"func": "min"}, + ), + ( + pd.DataFrame( + {1: [1.0, 2.0, 3.0, 4.0, 5.0], 2: [1, 2, 3, 4, 5]}, columns=[1, 2] + ), + {"func": {1: ["min", "max"], 2: "sum"}}, + ), + ( + pd.DataFrame( + {1: [1.0, 2.0, 3.0, 4.0, 5.0], 2: [1, 2, 3, 4, 5]}, columns=[1, 2] + ), + {"min_col": pd.NamedAgg(column=1, aggfunc="min")}, + ), + ], +) +def test_multifunc_numba_kwarg_propagation(data, agg_kwargs): + pytest.importorskip("numba") + labels = ["a", "a", "b", "b", "a"] + grouped = data.groupby(labels) + result = grouped.agg(**agg_kwargs, engine="numba", engine_kwargs={"parallel": True}) + expected = grouped.agg(**agg_kwargs, engine="numba") + if isinstance(expected, pd.DataFrame): + tm.assert_frame_equal(result, expected) + else: + tm.assert_series_equal(result, expected) + + +def test_args_not_cached(): + # GH 41647 + pytest.importorskip("numba") + + def sum_last(values, index, n): + return values[-n:].sum() + + df = pd.DataFrame({"id": [0, 0, 1, 1], "x": [1, 1, 1, 1]}) + grouped_x = df.groupby("id")["x"] + result = grouped_x.agg(sum_last, 1, engine="numba") + expected = pd.Series([1.0] * 2, name="x", index=pd.Index([0, 1], name="id")) + tm.assert_series_equal(result, expected) + + result = grouped_x.agg(sum_last, 2, engine="numba") + expected = pd.Series([2.0] * 2, name="x", index=pd.Index([0, 1], name="id")) + tm.assert_series_equal(result, expected) + + +def test_index_data_correctly_passed(): + # GH 43133 + pytest.importorskip("numba") + + def f(values, index): + return np.mean(index) + + df = pd.DataFrame({"group": ["A", "A", "B"], "v": [4, 5, 6]}, index=[-1, -2, -3]) + result = df.groupby("group").aggregate(f, engine="numba") + expected = pd.DataFrame( + [-1.5, -3.0], columns=["v"], index=pd.Index(["A", "B"], name="group") + ) + tm.assert_frame_equal(result, expected) + + +def test_engine_kwargs_not_cached(): + # If the user passes a different set of engine_kwargs don't return the same + # jitted function + pytest.importorskip("numba") + nogil = True + parallel = False + + def func_kwargs(values, index): + return nogil + parallel + + engine_kwargs = {"nogil": nogil, "parallel": parallel} + df = pd.DataFrame({"value": [0, 0, 0]}) + result = df.groupby(level=0).aggregate( + func_kwargs, engine="numba", engine_kwargs=engine_kwargs + ) + expected = pd.DataFrame({"value": [1.0, 1.0, 1.0]}) + tm.assert_frame_equal(result, expected) + + nogil = False + engine_kwargs = {"nogil": nogil, "parallel": parallel} + result = df.groupby(level=0).aggregate( + func_kwargs, engine="numba", engine_kwargs=engine_kwargs + ) + expected = pd.DataFrame({"value": [0.0, 0.0, 0.0]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore") +def test_multiindex_one_key(nogil, parallel): + pytest.importorskip("numba") + + def numba_func(values, index): + return 1 + + df = pd.DataFrame([{"A": 1, "B": 2, "C": 3}]).set_index(["A", "B"]) + engine_kwargs = {"nogil": nogil, "parallel": parallel} + result = df.groupby("A").agg( + numba_func, engine="numba", engine_kwargs=engine_kwargs + ) + expected = pd.DataFrame([1.0], index=pd.Index([1], name="A"), columns=["C"]) + tm.assert_frame_equal(result, expected) + + +def test_multiindex_multi_key_not_supported(nogil, parallel): + pytest.importorskip("numba") + + def numba_func(values, index): + return 1 + + df = pd.DataFrame([{"A": 1, "B": 2, "C": 3}]).set_index(["A", "B"]) + engine_kwargs = {"nogil": nogil, "parallel": parallel} + with pytest.raises(NotImplementedError, match="more than 1 grouping labels"): + df.groupby(["A", "B"]).agg( + numba_func, engine="numba", engine_kwargs=engine_kwargs + ) + + +def test_multilabel_numba_vs_cython(numba_supported_reductions): + pytest.importorskip("numba") + reduction, kwargs = numba_supported_reductions + df = pd.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), + } + ) + gb = df.groupby(["A", "B"]) + res_agg = gb.agg(reduction, engine="numba", **kwargs) + expected_agg = gb.agg(reduction, engine="cython", **kwargs) + tm.assert_frame_equal(res_agg, expected_agg) + # Test that calling the aggregation directly also works + direct_res = getattr(gb, reduction)(engine="numba", **kwargs) + direct_expected = getattr(gb, reduction)(engine="cython", **kwargs) + tm.assert_frame_equal(direct_res, direct_expected) + + +def test_multilabel_udf_numba_vs_cython(): + pytest.importorskip("numba") + df = pd.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), + } + ) + gb = df.groupby(["A", "B"]) + result = gb.agg(lambda values, index: values.min(), engine="numba") + expected = gb.agg(lambda x: x.min(), engine="cython") + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_other.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_other.py new file mode 100644 index 0000000000000000000000000000000000000000..e941b2308ecdffbaf56042bbc86032a6f3f482a4 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/aggregate/test_other.py @@ -0,0 +1,679 @@ +""" +test all other .agg behavior +""" + +import datetime as dt +from functools import partial + +import numpy as np +import pytest + +from pandas.errors import ( + Pandas4Warning, + SpecificationError, +) + +import pandas as pd +import pandas._testing as tm + +from pandas.io.formats.printing import pprint_thing + + +def test_agg_partial_failure_raises(): + # GH#43741 + + df = pd.DataFrame( + { + "data1": np.random.default_rng(2).standard_normal(5), + "data2": np.random.default_rng(2).standard_normal(5), + "key1": ["a", "a", "b", "b", "a"], + "key2": ["one", "two", "one", "two", "one"], + } + ) + grouped = df.groupby("key1") + + def peak_to_peak(arr): + return arr.max() - arr.min() + + with pytest.raises(TypeError, match="unsupported operand type"): + grouped.agg([peak_to_peak]) + + with pytest.raises(TypeError, match="unsupported operand type"): + grouped.agg(peak_to_peak) + + +def test_agg_datetimes_mixed(): + data = [[1, "2012-01-01", 1.0], [2, "2012-01-02", 2.0], [3, None, 3.0]] + + df1 = pd.DataFrame( + { + "key": [x[0] for x in data], + "date": [x[1] for x in data], + "value": [x[2] for x in data], + } + ) + + data = [ + [ + row[0], + (dt.datetime.strptime(row[1], "%Y-%m-%d").date() if row[1] else None), + row[2], + ] + for row in data + ] + + df2 = pd.DataFrame( + { + "key": [x[0] for x in data], + "date": [x[1] for x in data], + "value": [x[2] for x in data], + } + ) + + df1["weights"] = df1["value"] / df1["value"].sum() + gb1 = df1.groupby("date").aggregate("sum") + + df2["weights"] = df1["value"] / df1["value"].sum() + gb2 = df2.groupby("date").aggregate("sum") + + assert len(gb1) == len(gb2) + + +def test_agg_period_index(): + prng = pd.period_range("2012-1-1", freq="M", periods=3) + df = pd.DataFrame(np.random.default_rng(2).standard_normal((3, 2)), index=prng) + rs = df.groupby(level=0).sum() + assert isinstance(rs.index, pd.PeriodIndex) + + # GH 3579 + index = pd.period_range(start="1999-01", periods=5, freq="M") + s1 = pd.Series(np.random.default_rng(2).random(len(index)), index=index) + s2 = pd.Series(np.random.default_rng(2).random(len(index)), index=index) + df = pd.DataFrame.from_dict({"s1": s1, "s2": s2}) + grouped = df.groupby(df.index.month) + list(grouped) + + +def test_agg_dict_parameter_cast_result_dtypes(): + # GH 12821 + + df = pd.DataFrame( + { + "class": ["A", "A", "B", "B", "C", "C", "D", "D"], + "time": pd.date_range("1/1/2011", periods=8, freq="h"), + } + ) + df.loc[[0, 1, 2, 5], "time"] = None + + # test for `first` function + exp = df.loc[[0, 3, 4, 6]].set_index("class") + grouped = df.groupby("class") + tm.assert_frame_equal(grouped.first(), exp) + tm.assert_frame_equal(grouped.agg("first"), exp) + tm.assert_frame_equal(grouped.agg({"time": "first"}), exp) + tm.assert_series_equal(grouped.time.first(), exp["time"]) + tm.assert_series_equal(grouped.time.agg("first"), exp["time"]) + + # test for `last` function + exp = df.loc[[0, 3, 4, 7]].set_index("class") + grouped = df.groupby("class") + tm.assert_frame_equal(grouped.last(), exp) + tm.assert_frame_equal(grouped.agg("last"), exp) + tm.assert_frame_equal(grouped.agg({"time": "last"}), exp) + tm.assert_series_equal(grouped.time.last(), exp["time"]) + tm.assert_series_equal(grouped.time.agg("last"), exp["time"]) + + # count + exp = pd.Series( + [2, 2, 2, 2], index=pd.Index(list("ABCD"), name="class"), name="time" + ) + tm.assert_series_equal(grouped.time.agg(len), exp) + tm.assert_series_equal(grouped.time.size(), exp) + + exp = pd.Series( + [0, 1, 1, 2], index=pd.Index(list("ABCD"), name="class"), name="time" + ) + tm.assert_series_equal(grouped.time.count(), exp) + + +def test_agg_cast_results_dtypes(): + # similar to GH12821 + # xref #11444 + u = [dt.datetime(2015, x + 1, 1) for x in range(12)] + v = list("aaabbbbbbccd") + df = pd.DataFrame({"X": v, "Y": u}) + + result = df.groupby("X")["Y"].agg(len) + expected = df.groupby("X")["Y"].count() + tm.assert_series_equal(result, expected) + + +def test_aggregate_float64_no_int64(): + # see gh-11199 + df = pd.DataFrame( + {"a": [1, 2, 3, 4, 5], "b": [1, 2, 2, 4, 5], "c": [1, 2, 3, 4, 5]} + ) + + expected = pd.DataFrame({"a": [1, 2.5, 4, 5]}, index=[1, 2, 4, 5]) + expected.index.name = "b" + + result = df.groupby("b")[["a"]].mean() + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame( + {"a": [1, 2.5, 4, 5], "c": [1, 2.5, 4, 5]}, index=[1, 2, 4, 5] + ) + expected.index.name = "b" + + result = df.groupby("b")[["a", "c"]].mean() + tm.assert_frame_equal(result, expected) + + +def test_aggregate_api_consistency(): + # GH 9052 + # make sure that the aggregates via dict + # are consistent + df = pd.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), + } + ) + + grouped = df.groupby(["A", "B"]) + c_mean = grouped["C"].mean() + c_sum = grouped["C"].sum() + d_mean = grouped["D"].mean() + d_sum = grouped["D"].sum() + + result = grouped["D"].agg(["sum", "mean"]) + expected = pd.concat([d_sum, d_mean], axis=1) + expected.columns = ["sum", "mean"] + tm.assert_frame_equal(result, expected, check_like=True) + + result = grouped.agg(["sum", "mean"]) + expected = pd.concat([c_sum, c_mean, d_sum, d_mean], axis=1) + expected.columns = pd.MultiIndex.from_product([["C", "D"], ["sum", "mean"]]) + tm.assert_frame_equal(result, expected, check_like=True) + + result = grouped[["D", "C"]].agg(["sum", "mean"]) + expected = pd.concat([d_sum, d_mean, c_sum, c_mean], axis=1) + expected.columns = pd.MultiIndex.from_product([["D", "C"], ["sum", "mean"]]) + tm.assert_frame_equal(result, expected, check_like=True) + + result = grouped.agg({"C": "mean", "D": "sum"}) + expected = pd.concat([d_sum, c_mean], axis=1) + tm.assert_frame_equal(result, expected, check_like=True) + + result = grouped.agg({"C": ["mean", "sum"], "D": ["mean", "sum"]}) + expected = pd.concat([c_mean, c_sum, d_mean, d_sum], axis=1) + expected.columns = pd.MultiIndex.from_product([["C", "D"], ["mean", "sum"]]) + + msg = r"Label\(s\) \['r', 'r2'\] do not exist" + with pytest.raises(KeyError, match=msg): + grouped[["D", "C"]].agg({"r": "sum", "r2": "mean"}) + + +def test_agg_dict_renaming_deprecation(): + # 15931 + df = pd.DataFrame({"A": [1, 1, 1, 2, 2], "B": range(5), "C": range(5)}) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + df.groupby("A").agg( + {"B": {"foo": ["sum", "max"]}, "C": {"bar": ["count", "min"]}} + ) + + msg = r"Label\(s\) \['ma'\] do not exist" + with pytest.raises(KeyError, match=msg): + df.groupby("A")[["B", "C"]].agg({"ma": "max"}) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + df.groupby("A").B.agg({"foo": "count"}) + + +def test_agg_compat(): + # GH 12334 + df = pd.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), + } + ) + + g = df.groupby(["A", "B"]) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + g["D"].agg({"C": ["sum", "std"]}) + + with pytest.raises(SpecificationError, match=msg): + g["D"].agg({"C": "sum", "D": "std"}) + + +def test_agg_nested_dicts(): + # API change for disallowing these types of nested dicts + df = pd.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), + } + ) + + g = df.groupby(["A", "B"]) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + g.aggregate({"r1": {"C": ["mean", "sum"]}, "r2": {"D": ["mean", "sum"]}}) + + with pytest.raises(SpecificationError, match=msg): + g.agg({"C": {"ra": ["mean", "std"]}, "D": {"rb": ["mean", "std"]}}) + + # same name as the original column + # GH9052 + with pytest.raises(SpecificationError, match=msg): + g["D"].agg({"result1": np.sum, "result2": np.mean}) + + with pytest.raises(SpecificationError, match=msg): + g["D"].agg({"D": np.sum, "result2": np.mean}) + + +def test_agg_item_by_item_raise_typeerror(): + df = pd.DataFrame(np.random.default_rng(2).integers(10, size=(20, 10))) + + def raiseException(df): + pprint_thing("----------------------------------------") + pprint_thing(df.to_string()) + raise TypeError("test") + + with pytest.raises(TypeError, match="test"): + df.groupby(0).agg(raiseException) + + +def test_series_agg_multikey(): + ts = pd.Series( + np.arange(10, dtype=np.float64), index=pd.date_range("2020-01-01", periods=10) + ) + grouped = ts.groupby([lambda x: x.year, lambda x: x.month]) + + result = grouped.agg("sum") + expected = grouped.sum() + tm.assert_series_equal(result, expected) + + +def test_series_agg_multi_pure_python(): + data = pd.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 bad(x): + if isinstance(x.values, np.ndarray): + assert len(x.values.base) > 0 + return "foo" + + result = data.groupby(["A", "B"]).agg(bad) + expected = data.groupby(["A", "B"]).agg(lambda x: "foo") + tm.assert_frame_equal(result, expected) + + +def test_agg_consistency(): + # agg with ([]) and () not consistent + # GH 6715 + def P1(a): + return np.percentile(a.dropna(), q=1) + + df = pd.DataFrame( + { + "col1": [1, 2, 3, 4], + "col2": [10, 25, 26, 31], + "date": [ + dt.date(2013, 2, 10), + dt.date(2013, 2, 10), + dt.date(2013, 2, 11), + dt.date(2013, 2, 11), + ], + } + ) + + g = df.groupby("date") + + expected = g.agg([P1]) + expected.columns = expected.columns.levels[0] + + result = g.agg(P1) + tm.assert_frame_equal(result, expected) + + +def test_agg_callables(): + # GH 7929 + df = pd.DataFrame({"foo": [1, 2], "bar": [3, 4]}).astype(np.int64) + + class fn_class: + def __call__(self, x): + return sum(x) + + equiv_callables = [ + sum, + np.sum, + lambda x: sum(x), + lambda x: x.sum(), + partial(sum), + fn_class(), + ] + + expected = df.groupby("foo").agg("sum") + for ecall in equiv_callables: + result = df.groupby("foo").agg(ecall) + tm.assert_frame_equal(result, expected) + + +def test_agg_over_numpy_arrays(): + # GH 3788 + df = pd.DataFrame( + [ + [1, np.array([10, 20, 30])], + [1, np.array([40, 50, 60])], + [2, np.array([20, 30, 40])], + ], + columns=["category", "arraydata"], + ) + gb = df.groupby("category") + + expected_data = [[np.array([50, 70, 90])], [np.array([20, 30, 40])]] + expected_index = pd.Index([1, 2], name="category") + expected_column = ["arraydata"] + expected = pd.DataFrame( + expected_data, index=expected_index, columns=expected_column + ) + + alt = gb.sum(numeric_only=False) + tm.assert_frame_equal(alt, expected) + + result = gb.agg("sum", numeric_only=False) + tm.assert_frame_equal(result, expected) + + result = gb.agg(sum) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("as_period", [True, False]) +def test_agg_tzaware_non_datetime_result(as_period): + # discussed in GH#29589, fixed in GH#29641, operating on tzaware values + # with function that is not dtype-preserving + dti = pd.date_range("2012-01-01", periods=4, tz="UTC") + if as_period: + dti = dti.tz_localize(None).to_period("D") + + df = pd.DataFrame({"a": [0, 0, 1, 1], "b": dti}) + gb = df.groupby("a") + + # Case that _does_ preserve the dtype + result = gb["b"].agg(lambda x: x.iloc[0]) + expected = pd.Series(dti[::2], name="b") + expected.index.name = "a" + tm.assert_series_equal(result, expected) + + # Cases that do _not_ preserve the dtype + result = gb["b"].agg(lambda x: x.iloc[0].year) + expected = pd.Series([2012, 2012], name="b") + expected.index.name = "a" + tm.assert_series_equal(result, expected) + + result = gb["b"].agg(lambda x: x.iloc[-1] - x.iloc[0]) + expected = pd.Series( + [pd.Timedelta(days=1), pd.Timedelta(days=1)], name="b", dtype="m8[us]" + ) + expected.index.name = "a" + if as_period: + expected = pd.Series([pd.offsets.Day(1), pd.offsets.Day(1)], name="b") + expected.index.name = "a" + tm.assert_series_equal(result, expected) + + +def test_agg_timezone_round_trip(): + # GH 15426 + ts = pd.Timestamp("2016-01-01 12:00:00", tz="US/Pacific") + df = pd.DataFrame( + {"a": 1, "b": [ts + dt.timedelta(minutes=nn) for nn in range(10)]} + ) + + result1 = df.groupby("a")["b"].agg("min").iloc[0] + result2 = df.groupby("a")["b"].agg(lambda x: np.min(x)).iloc[0] + result3 = df.groupby("a")["b"].min().iloc[0] + + assert result1 == ts + assert result2 == ts + assert result3 == ts + + dates = [ + pd.Timestamp(f"2016-01-0{i:d} 12:00:00", tz="US/Pacific") for i in range(1, 5) + ] + df = pd.DataFrame({"A": ["a", "b"] * 2, "B": dates}) + grouped = df.groupby("A") + + ts = df["B"].iloc[0] + assert ts == grouped.nth(0)["B"].iloc[0] + assert ts == grouped.head(1)["B"].iloc[0] + assert ts == grouped.first()["B"].iloc[0] + + # GH#27110 applying iloc should return a DataFrame + assert ts == grouped.apply(lambda x: x.iloc[0])["B"].iloc[0] + + ts = df["B"].iloc[2] + assert ts == grouped.last()["B"].iloc[0] + + # GH#27110 applying iloc should return a DataFrame + assert ts == grouped.apply(lambda x: x.iloc[-1])["B"].iloc[0] + + +def test_sum_uint64_overflow(): + # see gh-14758 + # Convert to uint64 and don't overflow + df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], dtype=object) + df = df + 9223372036854775807 + + index = pd.Index( + [9223372036854775808, 9223372036854775810, 9223372036854775812], dtype=np.uint64 + ) + expected = pd.DataFrame( + {1: [9223372036854775809, 9223372036854775811, 9223372036854775813]}, + index=index, + dtype=object, + ) + + expected.index.name = 0 + result = df.groupby(0).sum(numeric_only=False) + tm.assert_frame_equal(result, expected) + + # out column is non-numeric, so with numeric_only=True it is dropped + result2 = df.groupby(0).sum(numeric_only=True) + expected2 = expected[[]] + tm.assert_frame_equal(result2, expected2) + + +@pytest.mark.parametrize( + "structure, cast_as", + [ + (tuple, tuple), + (list, list), + (lambda x: tuple(x), tuple), + (lambda x: list(x), list), + ], +) +def test_agg_structs_dataframe(structure, cast_as): + df = pd.DataFrame( + {"A": [1, 1, 1, 3, 3, 3], "B": [1, 1, 1, 4, 4, 4], "C": [1, 1, 1, 3, 4, 4]} + ) + + result = df.groupby(["A", "B"]).aggregate(structure) + expected = pd.DataFrame( + {"C": {(1, 1): cast_as([1, 1, 1]), (3, 4): cast_as([3, 4, 4])}} + ) + expected.index.names = ["A", "B"] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "structure, cast_as", + [ + (tuple, tuple), + (list, list), + (lambda x: tuple(x), tuple), + (lambda x: list(x), list), + ], +) +def test_agg_structs_series(structure, cast_as): + # Issue #18079 + df = pd.DataFrame( + {"A": [1, 1, 1, 3, 3, 3], "B": [1, 1, 1, 4, 4, 4], "C": [1, 1, 1, 3, 4, 4]} + ) + + result = df.groupby("A")["C"].aggregate(structure) + expected = pd.Series( + [cast_as([1, 1, 1]), cast_as([3, 4, 4])], index=[1, 3], name="C" + ) + expected.index.name = "A" + tm.assert_series_equal(result, expected) + + +def test_agg_category_nansum(observed): + categories = ["a", "b", "c"] + df = pd.DataFrame( + {"A": pd.Categorical(["a", "a", "b"], categories=categories), "B": [1, 2, 3]} + ) + result = df.groupby("A", observed=observed).B.agg(np.nansum) + expected = pd.Series( + [3, 3, 0], + index=pd.CategoricalIndex(["a", "b", "c"], categories=categories, name="A"), + name="B", + ) + if observed: + expected = expected[expected != 0] + tm.assert_series_equal(result, expected) + + +def test_agg_list_like_func(): + # GH 18473 + df = pd.DataFrame( + {"A": [str(x) for x in range(3)], "B": [str(x) for x in range(3)]} + ) + grouped = df.groupby("A", as_index=False, sort=False) + result = grouped.agg({"B": lambda x: list(x)}) + expected = pd.DataFrame( + {"A": [str(x) for x in range(3)], "B": [[str(x)] for x in range(3)]} + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_lambda_with_timezone(): + # GH 23683 + df = pd.DataFrame( + { + "tag": [1, 1], + "date": [ + pd.Timestamp("2018-01-01", tz="UTC"), + pd.Timestamp("2018-01-02", tz="UTC"), + ], + } + ) + msg = "Converting a Series or array of length 1 into a scalar" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.groupby("tag").agg({"date": lambda e: e.head(1)}) + expected = pd.DataFrame( + [pd.Timestamp("2018-01-01", tz="UTC")], + index=pd.Index([1], name="tag"), + columns=["date"], + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "err_cls", + [ + NotImplementedError, + RuntimeError, + KeyError, + IndexError, + OSError, + ValueError, + ArithmeticError, + AttributeError, + ], +) +def test_groupby_agg_err_catching(err_cls): + # make sure we suppress anything other than TypeError or AssertionError + # in _python_agg_general + + # Use a non-standard EA to make sure we don't go down ndarray paths + from pandas.tests.extension.decimal.array import ( + DecimalArray, + make_data, + to_decimal, + ) + + data = make_data(5) + df = pd.DataFrame( + {"id1": [0, 0, 0, 1, 1], "id2": [0, 1, 0, 1, 1], "decimals": DecimalArray(data)} + ) + + expected = pd.Series(to_decimal([data[0], data[3]])) + + def weird_func(x): + # weird function that raise something other than TypeError or IndexError + # in _python_agg_general + if len(x) == 0: + raise err_cls + return x.iloc[0] + + result = df["decimals"].groupby(df["id1"]).agg(weird_func) + tm.assert_series_equal(result, expected, check_names=False) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/conftest.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..18a142fa9de8cc3c27ca2485046f9e5f8d586182 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/conftest.py @@ -0,0 +1,161 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas.core.groupby.base import ( + reduction_kernels, + transformation_kernels, +) + + +@pytest.fixture +def df(): + return pd.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 pd.Series( + np.random.default_rng(2).standard_normal(30), + index=pd.date_range("2000-01-01", periods=30, freq="B"), + ) + + +@pytest.fixture +def tsframe(): + return pd.DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=30, freq="B"), + ) + + +@pytest.fixture +def three_group(): + return pd.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 = pd.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=[ + ("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/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_describe.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_describe.py new file mode 100644 index 0000000000000000000000000000000000000000..8c341191198cbbf81c167df4f88d35f8c1b17efa --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_describe.py @@ -0,0 +1,266 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +def test_apply_describe_bug(multiindex_dataframe_random_data): + grouped = multiindex_dataframe_random_data.groupby(level="first") + grouped.describe() # it works! + + +def test_series_describe_multikey(): + ts = pd.Series( + np.arange(10, dtype=np.float64), index=pd.date_range("2020-01-01", periods=10) + ) + 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 = pd.Series( + np.arange(10, dtype=np.float64), index=pd.date_range("2020-01-01", periods=10) + ) + grouped = ts.groupby(lambda x: x.month) + result = grouped.apply(lambda x: x.describe()) + expected = grouped.describe().stack() + 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 = pd.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 = pd.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_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 = pd.MultiIndex( + levels=[pd.Index([col], dtype=tsframe.columns.dtype), group.columns], + codes=[[0] * len(group.columns), range(len(group.columns))], + ) + group = pd.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) + + +def test_frame_describe_tupleindex(): + # GH 14848 - regression from 0.19.0 to 0.19.1 + name = "k" + df = pd.DataFrame( + { + "x": [1, 2, 3, 4, 5] * 3, + name: [(0, 0, 1), (0, 1, 0), (1, 0, 0)] * 5, + } + ) + result = df.groupby(name).describe() + expected = pd.DataFrame( + [[5.0, 3.0, 1.581139, 1.0, 2.0, 3.0, 4.0, 5.0]] * 3, + index=pd.Index( + [(0, 0, 1), (0, 1, 0), (1, 0, 0)], tupleize_cols=False, name=name + ), + columns=pd.MultiIndex.from_arrays( + [["x"] * 8, ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]] + ), + ) + tm.assert_frame_equal(result, expected) + + +def test_frame_describe_unstacked_format(): + # GH 4792 + prices = { + pd.Timestamp("2011-01-06 10:59:05", tz=None): 24990, + pd.Timestamp("2011-01-06 12:43:33", tz=None): 25499, + pd.Timestamp("2011-01-06 12:54:09", tz=None): 25499, + } + volumes = { + pd.Timestamp("2011-01-06 10:59:05", tz=None): 1500000000, + pd.Timestamp("2011-01-06 12:43:33", tz=None): 5000000000, + pd.Timestamp("2011-01-06 12:54:09", tz=None): 100000000, + } + df = pd.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 = pd.DataFrame( + data, + index=pd.Index([24990, 25499], name="PRICE"), + columns=["count", "mean", "std", "min", "25%", "50%", "75%", "max"], + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) +def test_describe_with_duplicate_output_column_names(as_index, keys): + # GH 35314 + df = pd.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 = ( + pd.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 = pd.MultiIndex( + levels=[[88, 99], [88, 99]], codes=[[0, 1], [0, 1]], names=["a1", "a2"] + ) + else: + expected.index = pd.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 = pd.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", "max"] + frames = [ + pd.DataFrame([[1.0, val, np.nan, val, val]], index=[1], columns=columns) + for val in (0.0, 2.0, 3.0) + ] + expected = pd.concat(frames, axis=1) + expected.columns = pd.MultiIndex( + levels=[[0, 2], columns], + codes=[5 * [0] + 5 * [1] + 5 * [0], 3 * list(range(5))], + ) + expected.index.names = [1] + tm.assert_frame_equal(result, expected) + + +def test_describe_non_cython_paths(): + # GH#5610 non-cython calls should not include the grouper + # Tests for code not expected to go through cython paths. + df = pd.DataFrame( + [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], + columns=["A", "B", "C"], + ) + gb = df.groupby("A") + expected_index = pd.Index([1, 3], name="A") + expected_col = pd.MultiIndex( + levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]], + codes=[[0] * 8, list(range(8))], + ) + expected = pd.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) + + gni = df.groupby("A", as_index=False) + expected = expected.reset_index() + result = gni.describe() + tm.assert_frame_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 = pd.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) + + # GH#54193: include/exclude on Series.describe is deprecated + msg = "'include' and 'exclude' arguments are deprecated for Series.describe" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.iloc[:0].groupby("A").B.describe(**kwargs) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = df.groupby("A").B.describe(**kwargs).reset_index(drop=True).iloc[:0] + expected.index = pd.Index([], dtype=df.columns.dtype) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_groupby_shift_diff.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_groupby_shift_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..08d1ffe804a00543ea98d40c3af1cce1b9854db5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_groupby_shift_diff.py @@ -0,0 +1,263 @@ +import numpy as np +import pytest + +import pandas as pd +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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.Timestamp("2011-01-01", tz="UTC").as_unit("ns") + df = pd.DataFrame({"a": [1, 1], "date": now_dt}) + result = df.groupby("a").shift(0).iloc[0] + expected = pd.Series({"date": now_dt}, name=result.name) + tm.assert_series_equal(result, expected) + + +def test_group_diff_real_series(any_real_numpy_dtype): + df = pd.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 = pd.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 = pd.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 = pd.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", + [ + [ + pd.Timestamp("2013-01-01"), + pd.Timestamp("2013-01-02"), + pd.Timestamp("2013-01-03"), + ], + [pd.Timedelta("5 days"), pd.Timedelta("6 days"), pd.Timedelta("7 days")], + ], +) +def test_group_diff_datetimelike(data, unit): + df = pd.DataFrame({"a": [1, 2, 2], "b": data}) + df["b"] = df["b"].dt.as_unit(unit) + result = df.groupby("a")["b"].diff() + expected = pd.Series([pd.NaT, pd.NaT, pd.Timedelta("1 days")], name="b").dt.as_unit( + unit + ) + tm.assert_series_equal(result, expected) + + +def test_group_diff_bool(): + df = pd.DataFrame({"a": [1, 2, 3, 3, 2], "b": [True, True, False, False, True]}) + result = df.groupby("a")["b"].diff() + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame(data, index=pd.date_range(start="20100101", periods=6)) + result = df.groupby(df.index).shift(periods=-2, freq="D") + expected = pd.DataFrame(data, index=pd.date_range(start="2009-12-30", periods=6)) + tm.assert_frame_equal(result, expected) + + +def test_shift_disallow_freq_and_fill_value(): + # GH 53832 + data = {"a": [1, 2, 3, 4, 5, 6], "b": [0, 0, 0, 1, 1, 1]} + df = pd.DataFrame(data, index=pd.date_range(start="20100101", periods=6)) + msg = "Passing a 'freq' together with a 'fill_value'" + with pytest.raises(ValueError, 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 = pd.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 = pd.DataFrame({"a": [1, 2, 3, 3, 2], "b": [True, True, False, False, True]}) + + shifted_df = df.groupby("b")[["a"]].shift([0, 1]) + expected_df = pd.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 = pd.DataFrame( + {"a": [1, 2, 3, 4, 5], "b": [True, True, False, False, True]}, + index=pd.date_range("1/1/2000", periods=5, freq="h"), + ) + shifted_df = df.groupby("b")[["a"]].shift( + [0, 1], + freq="h", + ) + expected_df = pd.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=pd.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 = pd.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 = pd.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 = pd.DataFrame( + {"a": [1, 2, 3, 4, 5], "b": [True, True, False, False, True]}, + index=pd.date_range("1/1/2000", periods=5, freq="h"), + ) + msg = "Passing a 'freq' together with a 'fill_value'" + with pytest.raises(ValueError, match=msg): + df.groupby("b")[["a"]].shift([1, 2], fill_value=1, freq="h") + + +def test_groupby_shift_multiple_periods_unsorted_index(): + # https://github.com/pandas-dev/pandas/pull/62843 + idx = pd.date_range("1/1/2000", periods=4, freq="h") + df = pd.DataFrame( + {"a": [1, 2, 3], "b": [True, True, False]}, + index=[idx[2], idx[0], idx[1]], + ) + result = df.groupby("b")[["a"]].shift([0, 1], freq="h") + expected = pd.DataFrame( + { + "a_0": [1.0, 2.0, 3.0, np.nan], + "a_1": [3.0, np.nan, 2.0, 1.0], + }, + index=[idx[2], idx[0], idx[1], idx[3]], + ) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_is_monotonic.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_is_monotonic.py new file mode 100644 index 0000000000000000000000000000000000000000..65033c0ec6531ebb05c7f8730c65f3a58d965dbc --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_is_monotonic.py @@ -0,0 +1,74 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@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 = pd.DataFrame(source_dict) + result = df.groupby("B").C.is_monotonic_increasing + index = pd.Index(list("abcd"), name="B") + expected = pd.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 = pd.DataFrame(source_dict) + result = df.groupby("B").C.is_monotonic_decreasing + index = pd.Index(list("abcd"), name="B") + expected = pd.Series(index=index, data=out_vals, name="C") + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_kurt.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_kurt.py new file mode 100644 index 0000000000000000000000000000000000000000..8c7bdff9b664e1b52c4cf36bd58387c032bafa3e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_kurt.py @@ -0,0 +1,90 @@ +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +def test_groupby_kurt_equivalence(): + # GH#40139 + # Test that the groupby kurt method (which uses libgroupby.group_kurt) + # matches the results of operating group-by-group (which uses nanops.nankurt) + 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.kurt() + + grpwise = [grp.kurt().to_frame(i).T for i, grp in gb] + expected = pd.concat(grpwise, axis=0) + expected.index = expected.index.astype("int64") # 32bit builds + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "dtype", + [ + pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow")), + "Float64", + ], +) +def test_groupby_kurt_arrow_float64(dtype): + # GH#40139 + # Test groupby.kurt() with float64[pyarrow] and Float64 dtypes + df = pd.DataFrame( + { + "x": [1.0, pd.NA, 3.2, 4.8, 2.3, 1.9, 8.9], + "y": [1.6, 3.3, 3.2, 6.8, 1.3, 2.9, 9.0], + }, + dtype=dtype, + ) + gb = df.groupby(by=lambda x: 0) + + result = gb.kurt() + expected = pd.DataFrame({"x": [2.1644713], "y": [0.1513969]}, dtype=dtype) + tm.assert_almost_equal(result, expected) + + +def test_groupby_kurt_noskipna(): + # GH#40139 + # Test groupby.kurt() with skipna = False + df = pd.DataFrame( + { + "x": [1.0, np.nan, 3.2, 4.8, 2.3, 1.9, 8.9], + "y": [1.6, 3.3, 3.2, 6.8, 1.3, 2.9, 9.0], + } + ) + gb = df.groupby(by=lambda x: 0) + + result = gb.kurt(skipna=False) + expected = pd.DataFrame({"x": [np.nan], "y": [0.1513969]}) + tm.assert_almost_equal(result, expected) + + +def test_groupby_kurt_all_ones(): + # GH#40139 + # Test groupby.kurt() with constant values + df = pd.DataFrame( + { + "x": [1.0] * 10, + } + ) + gb = df.groupby(by=lambda x: 0) + + result = gb.kurt(skipna=False) + expected = pd.DataFrame( + { + "x": [np.nan], # Same behavior as pd.DataFrame.kurt() + } + ) + tm.assert_almost_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_nlargest_nsmallest.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_nlargest_nsmallest.py new file mode 100644 index 0000000000000000000000000000000000000000..cf4f0f6e4a058cda365d1e568c06479869c676f3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_nlargest_nsmallest.py @@ -0,0 +1,114 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_nlargest(): + a = pd.Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10]) + b = pd.Series(list("a" * 5 + "b" * 5)) + gb = a.groupby(b) + r = gb.nlargest(3) + e = pd.Series( + [7, 5, 3, 10, 9, 6], + index=pd.MultiIndex.from_arrays([list("aaabbb"), [3, 2, 1, 9, 5, 8]]), + ) + tm.assert_series_equal(r, e) + + a = pd.Series([1, 1, 3, 2, 0, 3, 3, 2, 1, 0]) + gb = a.groupby(b) + e = pd.Series( + [3, 2, 1, 3, 3, 2], + index=pd.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 = pd.date_range("20180101", periods=10) + iterables = [dts, ["one", "two"]] + + idx = pd.MultiIndex.from_product(iterables, names=["first", "second"]) + s = pd.Series(npr.standard_normal(20), index=idx) + + result = s.groupby("first").nlargest(1) + + exp_idx = pd.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 = pd.Series(exp_values, index=exp_idx) + tm.assert_series_equal( + result, expected, check_exact=False, rtol=1e-3, check_freq=False + ) + + +def test_nsmallest(): + a = pd.Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10]) + b = pd.Series(list("a" * 5 + "b" * 5)) + gb = a.groupby(b) + r = gb.nsmallest(3) + e = pd.Series( + [1, 2, 3, 0, 4, 6], + index=pd.MultiIndex.from_arrays([list("aaabbb"), [0, 4, 1, 6, 7, 8]]), + ) + tm.assert_series_equal(r, e) + + a = pd.Series([1, 1, 3, 2, 0, 3, 3, 2, 1, 0]) + gb = a.groupby(b) + e = pd.Series( + [0, 1, 1, 0, 1, 2], + index=pd.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]) +def test_nlargest_and_smallest_noop(data, groups, dtype, nselect_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 nselect_method == "nlargest": + data = list(reversed(data)) + ser = pd.Series(data, name="a") + result = getattr(ser.groupby(groups), nselect_method)(n=2) + expidx = np.array(groups, dtype=int) if isinstance(groups, list) else groups + expected = pd.Series( + data, index=pd.MultiIndex.from_arrays([expidx, ser.index]), name="a" + ) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_nth.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_nth.py new file mode 100644 index 0000000000000000000000000000000000000000..410f3b2eb2090544a3f77d69ddb21f5a5be2d70e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_nth.py @@ -0,0 +1,856 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +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 = pd.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 = pd.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 = df.copy() + df.loc[df["A"] == "foo", "B"] = np.nan + grouped = df.groupby("A") + assert pd.isna(grouped["B"].first()["foo"]) + assert pd.isna(grouped["B"].last()["foo"]) + assert pd.isna(grouped["B"].nth(0).iloc[0]) + + # v0.14.0 whatsnew + df = pd.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 = pd.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 = pd.Index([1, 2], name="a") + expected = pd.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 = pd.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 = pd.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", + [ + ( + pd.DataFrame({"id": "a", "value": [None, "foo", np.nan]}), + pd.DataFrame({"value": ["foo"]}, index=pd.Index(["a"], name="id")), + ), + ( + pd.DataFrame({"id": "a", "value": [np.nan]}, dtype=object), + pd.DataFrame({"value": [None]}, index=pd.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 = pd.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"), + } + ) + 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 = pd.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 = pd.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) + + +def test_first_last_nth_dtypes2(): + # GH 2763, first/last shifting dtypes + idx = list(range(10)) + idx.append(9) + ser = pd.Series(data=range(11), index=idx, name="IntCol") + assert ser.dtype == "int64" + f = ser.groupby(level=0).first() + assert f.dtype == "int64" + + +def test_first_last_nth_nan_dtype(): + # GH 33591 + df = pd.DataFrame({"data": ["A"], "nans": pd.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 = pd.DataFrame( + { + pd.Timestamp("2012-01-01 00:00:00"): ["a", "b"], + pd.Timestamp("2012-01-02 00:00:00"): ["c", "d"], + "name": ["e", "e"], + "aaaa": ["f", "g"], + } + ) + result = test.groupby("name").first() + expected = pd.DataFrame( + [["a", "c", "f"]], + columns=pd.Index( + [pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-02"), "aaaa"] + ), + index=pd.Index(["e"], name="name"), + ) + tm.assert_frame_equal(result, expected) + + +def test_nth(): + df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"]) + gb = df.groupby("A") + + tm.assert_frame_equal(gb.nth(0), df.iloc[[0, 2]]) + tm.assert_frame_equal(gb.nth(1), df.iloc[[1]]) + tm.assert_frame_equal(gb.nth(2), df.loc[[]]) + tm.assert_frame_equal(gb.nth(-1), df.iloc[[1, 2]]) + tm.assert_frame_equal(gb.nth(-2), df.iloc[[0]]) + tm.assert_frame_equal(gb.nth(-3), df.loc[[]]) + tm.assert_series_equal(gb.B.nth(0), df.B.iloc[[0, 2]]) + tm.assert_series_equal(gb.B.nth(1), df.B.iloc[[1]]) + tm.assert_frame_equal(gb[["B"]].nth(0), df[["B"]].iloc[[0, 2]]) + + tm.assert_frame_equal(gb.nth(0, dropna="any"), df.iloc[[1, 2]]) + tm.assert_frame_equal(gb.nth(-1, dropna="any"), df.iloc[[1, 2]]) + + tm.assert_frame_equal(gb.nth(7, dropna="any"), df.iloc[:0]) + tm.assert_frame_equal(gb.nth(2, dropna="any"), df.iloc[:0]) + + +def test_nth2(): + # out of bounds, regression from 0.13.1 + # GH 6621 + df = pd.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) + + +def test_nth3(): + # GH 7559 + # from the vbench + df = pd.DataFrame(np.random.default_rng(2).integers(1, 10, (100, 2)), dtype="int64") + ser = df[1] + gb = df[0] + expected = ser.groupby(gb).first() + expected2 = ser.groupby(gb).apply(lambda x: x.iloc[0]) + tm.assert_series_equal(expected2, expected) + assert expected.name == 1 + assert expected2.name == 1 + + # validate first + v = ser[gb == 1].iloc[0] + assert expected.iloc[0] == v + assert expected2.iloc[0] == v + + with pytest.raises(ValueError, match="For a DataFrame"): + ser.groupby(gb, sort=False).nth(0, dropna=True) + + +def test_nth4(): + # doc example + df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"]) + gb = df.groupby("A") + result = gb.B.nth(0, dropna="all") + expected = df.B.iloc[[1, 2]] + tm.assert_series_equal(result, expected) + + +def test_nth5(): + # test multiple nth values + df = pd.DataFrame([[1, np.nan], [1, 3], [1, 4], [5, 6], [5, 7]], columns=["A", "B"]) + gb = df.groupby("A") + + tm.assert_frame_equal(gb.nth(0), df.iloc[[0, 3]]) + tm.assert_frame_equal(gb.nth([0]), df.iloc[[0, 3]]) + tm.assert_frame_equal(gb.nth([0, 1]), df.iloc[[0, 1, 3, 4]]) + tm.assert_frame_equal(gb.nth([0, -1]), df.iloc[[0, 2, 3, 4]]) + tm.assert_frame_equal(gb.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]]) + tm.assert_frame_equal(gb.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]]) + tm.assert_frame_equal(gb.nth([2]), df.iloc[[2]]) + tm.assert_frame_equal(gb.nth([3, 4]), df.loc[[]]) + + +def test_nth_bdays(unit): + business_dates = pd.date_range( + start="4/1/2014", end="6/30/2014", freq="B", unit=unit + ) + df = pd.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", + ] + ).as_unit(unit) + expected = pd.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": pd.Timestamp("2012-02-01 14:00:00", tz="US/Central"), + "foo": [1], + }, + { + "id": ["A"], + "time": pd.Timestamp("2012-02-01 14:00:00", tz="US/Central"), + "foo": [1], + }, + { + "id": ["A"], + "time": pd.Timestamp("2012-02-01 14:00:00", tz="US/Central"), + "foo": [1], + }, + ), + ( + { + "id": ["A", "B", "A"], + "time": [ + pd.Timestamp("2012-01-01 13:00:00", tz="America/New_York"), + pd.Timestamp("2012-02-01 14:00:00", tz="US/Central"), + pd.Timestamp("2012-03-01 12:00:00", tz="Europe/London"), + ], + "foo": [1, 2, 3], + }, + { + "id": ["A", "B"], + "time": [ + pd.Timestamp("2012-01-01 13:00:00", tz="America/New_York"), + pd.Timestamp("2012-02-01 14:00:00", tz="US/Central"), + ], + "foo": [1, 2], + }, + { + "id": ["A", "B"], + "time": [ + pd.Timestamp("2012-03-01 12:00:00", tz="Europe/London"), + pd.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 = pd.DataFrame(data) + + result = df.groupby("id", as_index=False).first() + expected = pd.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 = pd.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", pd.Timestamp("2013-01-01", tz="US/Eastern"), "a"], + ["last", pd.Timestamp("2013-01-02", tz="US/Eastern"), "b"], + ], +) +def test_first_last_tz_multi_column(method, ts, alpha, unit): + # GH 21603 + category_string = pd.Series(list("abc")).astype("category") + dti = pd.date_range("20130101", periods=3, tz="US/Eastern", unit=unit) + df = pd.DataFrame( + { + "group": [1, 1, 2], + "category_string": category_string, + "datetimetz": dti, + } + ) + result = getattr(df.groupby("group"), method)() + expected = pd.DataFrame( + { + "category_string": pd.Categorical( + [alpha, "c"], dtype=category_string.dtype + ), + "datetimetz": [ts, pd.Timestamp("2013-01-03", tz="US/Eastern")], + }, + index=pd.Index([1, 2], name="group"), + ) + expected["datetimetz"] = expected["datetimetz"].dt.as_unit(unit) + 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 = pd.DataFrame({"a": [1, 2], "b": values}) + grouped = df.groupby("a") + idx = pd.Index([1, 2], name="a") + expected_series = pd.Series(values, name="b", index=idx) + expected_frame = pd.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 = pd.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"]]) +def test_groupby_head_tail(op, n, expected_rows, columns, as_index): + df = pd.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) + + +def test_group_selection_cache(): + # GH 12839 nth, head, and tail should return same result consistently + df = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame( + { + "group": ["first", "first", "second", "third", "third"], + "time": 5 * [np.datetime64("NaT", "ns")], + "categories": pd.Series(["a", "b", "c", "a", "b"], dtype="category"), + } + ) + result = df.groupby("group").first() + expected = pd.DataFrame( + { + "time": 3 * [np.datetime64("NaT", "ns")], + "categories": pd.Series(["a", "c", "a"]).astype( + pd.CategoricalDtype(["a", "b", "c"]) + ), + } + ) + expected.index = pd.Index(["first", "second", "third"], name="group") + tm.assert_frame_equal(result, expected) + + +def test_first_multi_key_groupby_categorical(): + # GH 22512 + df = pd.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 = pd.DataFrame( + { + "C": ["apple", "mango", "mango"], + "D": pd.Series(["jupiter", "mars", "venus"]).astype( + pd.CategoricalDtype(["jupiter", "mars", "mercury", "venus"]) + ), + } + ) + expected.index = pd.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 = pd.Series(["y"], dtype=object) + data = pd.Series( + [nulls_fixture, nulls_fixture, nulls_fixture, "y", nulls_fixture], + index=[0, 0, 0, 0, 0], + dtype=object, + ).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 + + msg = "GroupBy.nth\\[...\\] is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + 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 + + msg = "GroupBy.nth\\[...\\] is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + 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_nth_getitem_deprecated(slice_test_grouped): + # GH#66346 + msg = "GroupBy.nth\\[...\\] is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + slice_test_grouped.nth[0] + + +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_interval(): + # GH#24205 + idx_result = pd.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 = pd.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 = pd.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 = pd.DataFrame(val_expected, index=idx_expected, columns=["col"]) + tm.assert_frame_equal(result, expected) + + +def test_head_tail_dropna_true(): + # GH#45089 + df = pd.DataFrame( + [["a", "z"], ["b", np.nan], ["c", np.nan], ["c", np.nan]], columns=["X", "Y"] + ) + expected = pd.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 = pd.DataFrame([["a", "z"], ["b", np.nan], ["c", np.nan]], columns=["X", "Y"]) + expected = pd.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 = pd.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) + + +@pytest.mark.parametrize( + "data", + [ + ( + pd.Timestamp("2011-01-15 12:50:28.502376"), + pd.Timestamp("2011-01-20 12:50:28.593448"), + ), + (24650000000000001, 24650000000000002), + ], +) +def test_groupby_nth_int_like_precision(data): + # GH#6620, GH#9311 + df = pd.DataFrame({"a": [1, 1], "b": data}) + + grouped = df.groupby("a") + result = grouped.nth(0) + expected = pd.DataFrame({"a": 1, "b": [data[0]]}) + + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_quantile.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_quantile.py new file mode 100644 index 0000000000000000000000000000000000000000..1a195d076ced81f3fe30ea90853c3ccf7bb3c998 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_quantile.py @@ -0,0 +1,521 @@ +import numpy as np +import pytest + +import pandas as pd +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): + 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 = pd.DataFrame( + {"key": ["a"] * len(a_vals) + ["b"] * len(b_vals), "val": all_vals} + ) + + expected = pd.DataFrame( + [a_expected, b_expected], + columns=["val"], + index=pd.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 = pd.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 = pd.DataFrame({"A": [0.25, 2.50]}, index=index) + tm.assert_frame_equal(result, expected) + + df = pd.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 = pd.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 = pd.DataFrame(arr, columns=list("ABC")) + result = df.groupby("A").quantile([0.3, 0.7]) + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame( + [["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"] + ) + + msg = "dtype '(object|str)' does not support operation 'quantile'" + with pytest.raises(TypeError, match=msg): + df.groupby("key").quantile() + + +def test_quantile_out_of_bounds_q_raises(): + # https://github.com/pandas-dev/pandas/issues/27470 + df = pd.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 = pd.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 = pd.DataFrame({"key": key, "val": val}) + + expected = pd.DataFrame( + expected_val, index=pd.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 = pd.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 = pd.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 = pd.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: + msg = "dtype '.*' does not support operation 'quantile'" + with pytest.raises(TypeError, match=msg): + df.groupby("a").quantile(q, numeric_only=numeric_only) + + +def test_groupby_quantile_NA_float(any_float_dtype): + # GH#42849 + dtype = pd.Series([], dtype=any_float_dtype).dtype + item = np.nan if isinstance(dtype, np.dtype) else pd.NA + df = pd.DataFrame({"x": [1, 1], "y": [0.2, item]}, dtype=any_float_dtype) + result = df.groupby("x")["y"].quantile(0.5) + exp_index = pd.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 = pd.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=pd.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 = pd.DataFrame( + {"y": 3.5}, + dtype="Float64", + index=pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame({"x": [1, 1], "y": [pd.NA] * 2}, dtype=dtype) + result = df.groupby("x")["y"].quantile(0.5) + expected = pd.Series( + [pd.NA], dtype=dtype, index=pd.Index([1.0], dtype=dtype), name="y" + ) + expected.index.name = "x" + tm.assert_series_equal(expected, result) + + +def test_groupby_timedelta_quantile(): + # GH: 29485 + tdi = pd.to_timedelta(np.arange(4), unit="s").as_unit("us") + df = pd.DataFrame({"value": tdi, "group": [1, 1, 2, 2]}) + result = df.groupby("group").quantile(0.99) + expected = pd.DataFrame( + { + "value": [ + pd.Timedelta("0 days 00:00:00.990000"), + pd.Timedelta("0 days 00:00:02.990000"), + ] + }, + index=pd.Index([1, 2], name="group"), + ) + tm.assert_frame_equal(result, expected) + + +def test_timestamp_groupby_quantile(unit): + # GH 33168 + dti = pd.date_range( + start="2020-04-19 00:00:00", freq="1min", periods=100, tz="UTC", unit=unit + ).floor("1h") + df = pd.DataFrame( + { + "timestamp": dti, + "category": list(range(1, 101)), + "value": list(range(101, 201)), + } + ) + + result = df.groupby("timestamp").quantile([0.2, 0.8]) + + mi = pd.MultiIndex.from_product([dti[::99], [0.2, 0.8]], names=("timestamp", None)) + expected = pd.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=mi, + ) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_quantile_dt64tz_period(): + # GH#51373 + dti = pd.date_range("2016-01-01", periods=1000, unit="ns") + df = pd.Series(dti).to_frame().copy() + 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 = pd.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) + + +def test_groupby_quantile_nonnull_nan_pyarrow(): + # GH#64330 a non-null NaN (mask == 0) must be treated as NA, otherwise it + # corrupts the quickselect buffer and yields non-monotonic quantiles. + pa = pytest.importorskip("pyarrow") + + pa_arr = pa.array( + [5.0, float("nan"), 1.0, 3.0, 2.0, 4.0], type=pa.float64(), from_pandas=False + ) + arr = pd.arrays.ArrowExtensionArray(pa_arr) + assert not arr.isna().any() # the NaN is a value, not null + + df = pd.DataFrame({"key": ["a"] * 6, "val": arr}) + qs = [0.0, 0.25, 0.5, 0.75, 1.0] + result = df.groupby("key")["val"].quantile(qs) + + # The NaN is skipped, matching the non-grouped Series.quantile result. + expected_vals = pd.Series(arr).quantile(qs).to_numpy() + tm.assert_numpy_array_equal(result.to_numpy().astype(float), expected_vals) + + +def test_groupby_quantile_nonnull_nan_masked(): + # GH#64330 same as above for a masked float array carrying a non-null NaN. + arr = pd.arrays.FloatingArray( + np.array([5.0, np.nan, 1.0, 3.0, 2.0, 4.0]), np.zeros(6, dtype=bool) + ) + df = pd.DataFrame({"key": ["a"] * 6, "val": arr}) + result = df.groupby("key")["val"].quantile([0.0, 0.25, 0.5, 0.75, 1.0]) + expected = pd.Series( + [1.0, 2.0, 3.0, 4.0, 5.0], + dtype="Float64", + index=pd.MultiIndex.from_product( + [["a"], [0.0, 0.25, 0.5, 0.75, 1.0]], names=["key", None] + ), + name="val", + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_quantile_all_nat_group(): + # GH#64330 an all-NaT group must return NaT; casting NaN -> i8 is platform + # dependent (epoch on some architectures) if not mapped to iNaT explicitly. + df = pd.DataFrame( + { + "key": ["a", "a", "b", "b"], + "val": pd.to_datetime(["NaT", "NaT", "2020-01-01", "2020-01-02"]), + } + ) + result = df.groupby("key")["val"].quantile(0.5) + expected = pd.Series( + [pd.NaT, pd.Timestamp("2020-01-01 12:00:00")], + index=pd.Index(["a", "b"], name="key"), + name="val", + ) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_rank.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..7fb004397addb492353629e27d00afaf41b67cbc --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_rank.py @@ -0,0 +1,637 @@ +from datetime import datetime + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_rank_unordered_categorical_typeerror(): + # GH#51034 should be TypeError, not NotImplementedError + cat = pd.Categorical([], ordered=False) + ser = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame({"key": key, "val": vals}) + result = df.groupby("key").rank(method=ties_method, ascending=ascending, pct=pct) + + exp_df = pd.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 = pd.DataFrame({"key": key, "val": vals}) + result = df.groupby("key").rank( + method=ties_method, ascending=ascending, na_option=na_option + ) + exp_df = pd.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 = pd.DataFrame({"key": key, "val": vals}) + result = df.groupby("key").rank( + method=ties_method, ascending=ascending, na_option=na_option, pct=pct + ) + + exp_df = pd.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 = pd.DataFrame( + {"key": ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"], "val": [1] * 10} + ) + result = df.groupby("key").rank(pct=pct) + exp_df = pd.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 = pd.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 = pd.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("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(rank_method, ascending, na_option, pct, vals): + df = pd.DataFrame({"key": ["foo"] * 5, "val": vals}) + mask = df["val"].isna() + + gb = df.groupby("key") + res = gb.rank(method=rank_method, ascending=ascending, na_option=na_option, pct=pct) + + # construct our expected by using numeric values with the same ordering + if mask.any(): + df2 = pd.DataFrame({"key": ["foo"] * 5, "val": [0, np.nan, 2, np.nan, 1]}) + else: + df2 = pd.DataFrame({"key": ["foo"] * 5, "val": [0, 0, 2, 0, 1]}) + + gb2 = df2.groupby("key") + alt = gb2.rank( + method=rank_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("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(rank_method, ascending, na_option, pct, vals): + df = pd.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=rank_method, ascending=ascending, na_option=na_option, pct=pct + ) + + +def test_rank_empty_group(): + # see gh-22519 + column = "A" + df = pd.DataFrame({"A": [0, 1, 0], "B": [1.0, np.nan, 2.0]}) + + result = df.groupby(column).B.rank(pct=True) + expected = pd.Series([0.5, np.nan, 1.0], name="B") + tm.assert_series_equal(result, expected) + + result = df.groupby(column).rank(pct=True) + expected = pd.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 = pd.DataFrame({"A": input_key, "B": input_value}) + + result = df.groupby("A").rank(method="dense", pct=True) + expected = pd.DataFrame({"B": output_value}) + tm.assert_frame_equal(result, expected) + + +def test_rank_min_int(): + # GH-32859 + df = pd.DataFrame( + { + "grp": [1, 1, 2], + "int_col": [ + np.iinfo(np.int64).min, + np.iinfo(np.int64).max, + np.iinfo(np.int64).min, + ], + "datetimelike": [pd.NaT, datetime(2001, 1, 1), pd.NaT], + } + ) + + result = df.groupby("grp").rank() + expected = pd.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 = pd.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 = pd.Series([0.5, 1, np.nan, np.nan], name="val") + else: + expected = pd.Series([1 / 3, 2 / 3, 1, 1], name="val") + + tm.assert_series_equal(result, expected) + + +def test_non_unique_index(): + # GH 16577 + df = pd.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 = pd.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 = pd.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) + + +@pytest.mark.parametrize("na_option", ["top", "bottom"]) +def test_groupby_op_with_nullables(na_option): + # GH 54206 + df = pd.DataFrame({"x": [None]}, dtype="Float64") + result = df.groupby("x", dropna=False)["x"].rank(method="min", na_option=na_option) + expected = pd.Series([1.0], dtype="Float64", name=result.name) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_sample.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa5babe760f71a47f7ad1028d8f237534f63100 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_sample.py @@ -0,0 +1,150 @@ +import pytest + +import pandas as pd +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 = pd.DataFrame({"a": values, "b": values}) + + result = df.groupby("a").sample(n=n, frac=frac) + values = [1] * 2 + [2] * 2 + expected = pd.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 = pd.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 = pd.DataFrame({"a": values, "b": values}) + + result = df.groupby("a").sample(n=5) + values = [1] * 5 + [2] * 5 + expected = pd.DataFrame({"a": values, "b": values}, index=result.index) + tm.assert_frame_equal(result, expected) + + result = df.groupby("a")["b"].sample(n=5) + expected = pd.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 = pd.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 = pd.DataFrame({"a": values, "b": values}, index=result.index) + tm.assert_frame_equal(result, expected) + + result = df.groupby("a")["b"].sample(n=2) + expected = pd.Series(values, name="b", index=result.index) + tm.assert_series_equal(result, expected) + + +def test_groupby_sample_n_and_frac_raises(): + df = pd.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 = pd.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 = pd.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 = pd.DataFrame({"a": values, "b": values}) + + result = df.groupby("a").sample(frac=2.0, replace=True) + values = [1] * 20 + [2] * 20 + expected = pd.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 = pd.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 = pd.DataFrame({"a": values, "b": values}) + + result = df.groupby("a").sample(n=None, frac=None) + expected = pd.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 = pd.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 = pd.DataFrame({"a": values, "b": values}, index=pd.Index(index)) + + result = df.groupby("a").sample(n=2, replace=True, weights=[1, 0, 1, 0]) + expected = pd.DataFrame({"a": values, "b": values}, index=pd.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 = pd.Series(values, name="b", index=pd.Index(expected_index)) + tm.assert_series_equal(result, expected) + + +def test_groupby_sample_with_selections(): + # GH 39928 + values = [1] * 10 + [2] * 10 + df = pd.DataFrame({"a": values, "b": values, "c": values}) + + result = df.groupby("a")[["b", "c"]].sample(n=None, frac=None) + expected = pd.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 = pd.DataFrame({"a": [], "b": []}) + groupby_df = df.groupby("a") + + result = groupby_df.sample() + expected = df + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_size.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_size.py new file mode 100644 index 0000000000000000000000000000000000000000..65dfe159b5308333d22a3310022adb0a23e33783 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_size.py @@ -0,0 +1,87 @@ +import numpy as np +import pytest + +import pandas as pd +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", ["A", "B", ["A", "B"]]) +def test_size_sort(sort, by): + df = pd.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 = pd.DataFrame(columns=["A", "B"]) + out = pd.Series(dtype="int64", index=pd.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 = pd.DataFrame({"A": [None, None]}) # all-null groups + result = df.groupby("A").size() + expected = pd.Series(dtype="int64", index=pd.Index([], name="A")) + tm.assert_series_equal(result, expected) + + +def test_size_period_index(): + # https://github.com/pandas-dev/pandas/issues/34010 + ser = pd.Series([1], index=pd.PeriodIndex(["2000"], name="A", freq="D")) + grp = ser.groupby(level="A") + result = grp.size() + tm.assert_series_equal(result, ser) + + +def test_size_on_categorical(as_index): + df = pd.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 = pd.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 = pd.Series([1, 1, 1], index=["a", "a", "b"], dtype=dtype) + result = ser.groupby(level=0).size() + expected = pd.Series([2, 1], dtype="Int64", index=["a", "b"]) + tm.assert_series_equal(result, expected) + + +def test_size_strings(any_string_dtype, using_infer_string): + # GH#55627 + dtype = any_string_dtype + df = pd.DataFrame({"a": ["a", "a", "b"], "b": "a"}, dtype=dtype) + result = df.groupby("a")["b"].size() + exp_dtype = "Int64" if dtype == "string[pyarrow]" else "int64" + exp_index_dtype = "str" if using_infer_string and dtype == "object" else dtype + expected = pd.Series( + [2, 1], + index=pd.Index(["a", "b"], name="a", dtype=exp_index_dtype), + name="b", + dtype=exp_dtype, + ) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_skew.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_skew.py new file mode 100644 index 0000000000000000000000000000000000000000..296b10886b83d3f96d2f8de42a93feb0ed54cf06 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_skew.py @@ -0,0 +1,46 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +def test_groupby_skew_equivalence(): + # Test that the 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) + + +@pytest.mark.parametrize("klass", ["SeriesGroupBy", "DataFrameGroupBy"]) +def test_skew_kwargs_deprecated(klass): + # GH#50407 + df = pd.DataFrame({"a": [1, 1, 2], "b": [1.0, 2.0, 3.0]}) + if klass == "SeriesGroupBy": + gb = df.groupby("a")["b"] + msg = "Passing additional arguments to SeriesGroupBy.skew" + else: + gb = df.groupby("a") + msg = "Passing additional arguments to DataFrameGroupBy.skew" + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + with pytest.raises(TypeError, match="got an unexpected keyword argument"): + gb.skew(foo=1) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_value_counts.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_value_counts.py new file mode 100644 index 0000000000000000000000000000000000000000..766de5549f8c7dd582a7b20731a83572f2457f76 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/methods/test_value_counts.py @@ -0,0 +1,1161 @@ +""" +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 +""" + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def tests_value_counts_index_names_category_column(): + # GH44324 Missing name of index category column + df = pd.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 = pd.DataFrame([["US", "female"]], columns=["country", "gender"]) + df_mi_expected["gender"] = df_mi_expected["gender"].astype("category") + mi_expected = pd.MultiIndex.from_frame(df_mi_expected) + expected = pd.Series([1], index=mi_expected, name="count") + + tm.assert_series_equal(result, expected) + + +def seed_df(seed_nans, n, m): + days = pd.date_range("2015-08-24", periods=10) + + frame = pd.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 + + +@pytest.mark.slow +@pytest.mark.parametrize("seed_nans", [True, False]) +@pytest.mark.parametrize("num_rows", [10, 50]) +@pytest.mark.parametrize("max_int", [5, 20]) +@pytest.mark.parametrize("keys", ["1st", "2nd", ["1st", "2nd"]], ids=repr) +@pytest.mark.parametrize("bins", [None, [0, 5]], ids=repr) +@pytest.mark.parametrize("isort", [True, False]) +@pytest.mark.parametrize("normalize, name", [(True, "proportion"), (False, "count")]) +def test_series_groupby_value_counts( + seed_nans, + num_rows, + max_int, + keys, + bins, + isort, + normalize, + name, + sort, + ascending, + dropna, +): + df = seed_df(seed_nans, num_rows, max_int) + + def rebuild_index(df): + arr = list(map(df.index.get_level_values, range(df.index.nlevels))) + df.index = pd.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(pd.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 = pd.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"] = pd.to_datetime(df["Timestamp"], utc=utc, unit="s") + dfg = df.groupby(pd.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(pd.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 = pd.DataFrame(columns=columns) + dfg = df.groupby(columns[:-1]) + + result = dfg[columns[-1]].value_counts() + expected = pd.Series([], dtype=result.dtype, name="count") + expected.index = pd.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 = pd.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 = pd.Series(pd.Categorical(["a"], categories=["a", "b"])) + result = s.groupby([0]).value_counts() + + expected = pd.Series( + data=[1, 0], + index=pd.MultiIndex.from_arrays( + [ + np.array([0, 0]), + pd.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 = pd.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 = pd.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 = pd.Series([1, 1, 1, 2, 1], index=index, name="count") + tm.assert_series_equal(result, expected) + + +@pytest.fixture +def education_df(): + return pd.DataFrame( + { + "gender": ["male", "male", "female", "male", "female", "male"], + "education": ["low", "medium", "high", "low", "high", "low"], + "country": ["US", "FR", "US", "FR", "FR", "FR"], + } + ) + + +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): + # gh43564 + result = education_df.groupby("country")[["gender", "education"]].value_counts( + normalize=True + ) + expected = pd.Series( + data=[0.5, 0.25, 0.25, 0.5, 0.5], + index=pd.MultiIndex.from_tuples( + [ + ("FR", "male", "low"), + ("FR", "male", "medium"), + ("FR", "female", "high"), + ("US", "male", "low"), + ("US", "female", "high"), + ], + 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("frame", [True, False]) +def test_against_frame_and_seriesgroupby( + education_df, + groupby, + normalize, + name, + sort, + ascending, + as_index, + frame, + using_infer_string, +): + # 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` + 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 in ["array", "function"] and (not as_index and frame): + expected.insert(loc=0, column="level_0", value=result["level_0"]) + else: + expected.insert(loc=0, column="country", value=result["country"]) + 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) + both_dtype = index_frame["both"].dtype + index_frame = index_frame.astype( + {"gender": both_dtype, "education": both_dtype} + ) + del index_frame["both"] + index_frame2 = index_frame.rename({0: None}, axis=1) + expected.index = pd.MultiIndex.from_frame(index_frame2) + + if index_frame2.columns.isna()[0]: + # with using_infer_string, the columns in index_frame are string + # dtype, which makes the rename({0: None}) above use np.nan + # instead of None, so we need to set None more explicitly. + expected.index.names = [None, *expected.index.names[1:]] + 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)) + if using_infer_string: + expected = expected.astype({"gender": "str", "education": "str"}) + del expected["both"] + tm.assert_frame_equal(result, expected) + + +@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, [3, 0, 1, 2, 4], [2, 1, 1, 1, 1], [3, 1, 3, 1, 1]), + (True, True, [0, 1, 2, 4, 3], [1, 1, 1, 1, 2], [1, 3, 1, 1, 3]), + ], +) +def test_compound( + education_df, + normalize, + sort, + ascending, + expected_rows, + expected_count, + expected_group_size, + any_string_dtype, + using_infer_string, +): + dtype = any_string_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 = pd.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]": + # TODO(nullable) also string[python] should return nullable dtypes + expected["proportion"] = expected["proportion"].convert_dtypes() + else: + expected["count"] = expected_count + if dtype == "string[pyarrow]": + expected["count"] = expected["count"].convert_dtypes() + if using_infer_string and dtype == object: + expected = expected.astype( + {"country": "str", "gender": "str", "education": "str"} + ) + + tm.assert_frame_equal(result, expected) + + +@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( + sort, ascending, normalize, name, expected_data, expected_index +): + # 3-way compare with :meth:`~DataFrame.value_counts` + # Tests from frame/methods/test_value_counts.py + animals_df = pd.DataFrame( + {"key": [1, 1, 1, 1], "num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + result_frame = animals_df.value_counts( + sort=sort, ascending=ascending, normalize=normalize + ) + expected = pd.Series( + data=expected_data, + index=pd.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.mark.parametrize( + "group_dropna, count_dropna, expected_rows, expected_values", + [ + ( + False, + False, + [0, 1, 3, 5, 6, 7, 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, 6, 7, 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( + group_dropna, count_dropna, expected_rows, expected_values +): + nulls_df = pd.DataFrame( + { + "A": [1, 1, np.nan, 4, np.nan, 6, 6, 6, 6], + "B": [1, 1, 3, np.nan, np.nan, 6, 6, 6, 6], + "C": [1, 2, 3, 4, 5, 6, np.nan, 8, np.nan], + "D": [1, 2, 3, 4, 5, 6, 7, np.nan, np.nan], + } + ) + gp = nulls_df.groupby(["A", "B"], dropna=group_dropna) + result = gp.value_counts(normalize=True, sort=True, dropna=count_dropna) + columns = pd.DataFrame() + for column in nulls_df.columns: + columns[column] = [nulls_df[column][row] for row in expected_rows] + index = pd.MultiIndex.from_frame(columns) + expected = pd.Series(data=expected_values, index=index, name="proportion") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "dropna, expected_data, expected_index", + [ + ( + True, + [1, 1], + pd.MultiIndex.from_arrays( + [(1, 1), ("John", "Beth"), ("Smith", "Louise")], + names=["key", "first_name", "middle_name"], + ), + ), + ( + False, + [1, 1, 1, 1], + pd.MultiIndex( + levels=[ + pd.Index([1]), + pd.Index(["Anne", "Beth", "John"]), + pd.Index(["Louise", "Smith", np.nan]), + ], + codes=[[0, 0, 0, 0], [2, 0, 2, 1], [1, 2, 2, 0]], + names=["key", "first_name", "middle_name"], + ), + ), + ], +) +@pytest.mark.parametrize("normalize, name", [(False, "count"), (True, "proportion")]) +def test_data_frame_value_counts_dropna( + nulls_fixture, 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 + names_with_nulls_df = pd.DataFrame( + { + "key": [1, 1, 1, 1], + "first_name": ["John", "Anne", "John", "Beth"], + "middle_name": ["Smith", nulls_fixture, nulls_fixture, "Louise"], + }, + ) + result_frame = names_with_nulls_df.value_counts(dropna=dropna, normalize=normalize) + expected = pd.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("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 +): + # Test single categorical grouper with only observed grouping categories + # when non-groupers are also categorical + + gp = education_df.astype("category").groupby( + "country", as_index=as_index, observed=observed + ) + result = gp.value_counts(normalize=normalize) + + expected_index = pd.MultiIndex.from_tuples( + [ + ("FR", "male", "low"), + ("FR", "male", "medium"), + ("FR", "female", "high"), + ("FR", "male", "high"), + ("FR", "female", "low"), + ("FR", "female", "medium"), + ("US", "male", "low"), + ("US", "female", "high"), + ("US", "male", "medium"), + ("US", "male", "high"), + ("US", "female", "low"), + ("US", "female", "medium"), + ], + names=["country", "gender", "education"], + ) + + expected_series = pd.Series( + data=expected_data, + index=expected_index, + name=name, + ) + for i in range(3): + expected_series.index = expected_series.index.set_levels( + pd.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 = pd.Series( + data=expected_data, + index=pd.MultiIndex.from_tuples( + expected_index, + names=["country", "gender", "education"], + ), + name=name, + ) + for i in range(3): + index_level = pd.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( + "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 +): + # GH#46357 + + expected_index = [ + ("FR", "male", "low"), + ("FR", "male", "medium"), + ("FR", "female", "high"), + ("FR", "male", "high"), + ("FR", "female", "low"), + ("FR", "female", "medium"), + ("US", "male", "low"), + ("US", "female", "high"), + ("US", "male", "medium"), + ("US", "male", "high"), + ("US", "female", "low"), + ("US", "female", "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( + "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 +): + # GH#46357 + + expected_index = [ + ("FR", "male", "low"), + ("FR", "male", "medium"), + ("FR", "female", "high"), + ("FR", "male", "high"), + ("FR", "female", "low"), + ("FR", "female", "medium"), + ("US", "male", "low"), + ("US", "female", "high"), + ("US", "male", "medium"), + ("US", "male", "high"), + ("US", "female", "low"), + ("US", "female", "medium"), + ("ASIA", "male", "low"), + ("ASIA", "male", "medium"), + ("ASIA", "male", "high"), + ("ASIA", "female", "low"), + ("ASIA", "female", "medium"), + ("ASIA", "female", "high"), + ] + + 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( + "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", "male"), + ("US", "medium", "female"), + ], + ), + ( + 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 = pd.Series( + data=expected_data[expected_data > 0.0] if observed else expected_data, + index=pd.MultiIndex.from_tuples( + expected_index, + names=["country", "education", "gender"], + ), + name=name, + ) + for i in range(2): + expected_series.index = expected_series.index.set_levels( + pd.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("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 +): + # GH#46357 Test non-observed categories are included in the result, + # regardless of `observed` + + 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", "male", "medium"), + ("FR", "female", "high"), + ("FR", "male", "high"), + ("FR", "female", "low"), + ("FR", "female", "medium"), + ("US", "male", "low"), + ("US", "female", "high"), + ("US", "male", "medium"), + ("US", "male", "high"), + ("US", "female", "low"), + ("US", "female", "medium"), + ] + expected_series = pd.Series( + data=expected_data, + index=pd.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( + pd.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 = pd.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 = pd.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"]), + ], +) +def test_column_label_duplicates(test, columns, expected_names, as_index): + # GH 44992 + # Test for duplicate input column labels and generated duplicate labels + df = pd.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 = pd.Series( + data=(1, 1), + index=pd.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 = pd.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 = pd.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 = pd.DataFrame({"a": [1, 1]}) + gb = df.groupby(np.array([1, 1], dtype=np.int64)) + result = gb.value_counts() + expected = pd.Series( + [2], index=pd.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 = pd.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 = pd.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 = pd.DataFrame({"c1": ["a", "b", "c"], "c2": ["x", "y", "y"]}, index=[0, 1, 1]) + result = df.groupby(level=0).value_counts(subset=["c2"]) + expected = pd.Series( + [1, 2], + index=pd.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 = pd.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 = pd.Series( + [1, 2], + index=pd.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, unit): + # GH#50486 + df = pd.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"] = pd.to_datetime(df["Timestamp"], utc=utc, unit="s").dt.as_unit(unit) + gb = df.groupby(pd.Grouper(freq="1D", key="Datetime")) + result = gb.value_counts() + dates = pd.to_datetime( + ["2019-08-06", "2019-08-07", "2019-08-09", "2019-08-10"], utc=utc + ).as_unit(unit) + timestamps = df["Timestamp"].unique() + index = pd.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 = pd.Series(1, index=index, name="count") + tm.assert_series_equal(result, expected) + + +def test_value_counts_integer_columns(): + # GH#55627 + df = pd.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 = pd.DataFrame( + {1: ["a", "a", "a"], 2: ["a", "a", "d"], 3: ["a", "b", "c"], "count": 1} + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("vc_sort", [True, False]) +@pytest.mark.parametrize("normalize", [True, False]) +def test_value_counts_sort(sort, vc_sort, normalize): + # GH#55951 + df = pd.DataFrame({"a": [2, 1, 1, 1], 0: [3, 4, 3, 3]}) + gb = df.groupby("a", sort=sort) + result = gb.value_counts(sort=vc_sort, normalize=normalize) + + if normalize: + values = [2 / 3, 1 / 3, 1.0] + else: + values = [2, 1, 1] + index = pd.MultiIndex( + levels=[[1, 2], [3, 4]], codes=[[0, 0, 1], [0, 1, 0]], names=["a", 0] + ) + expected = pd.Series( + values, index=index, name="proportion" if normalize else "count" + ) + if sort and vc_sort: + taker = [0, 1, 2] + elif sort and not vc_sort: + taker = [1, 0, 2] + elif not sort and vc_sort: + taker = [0, 2, 1] + else: + taker = [2, 1, 0] + expected = expected.take(taker) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("vc_sort", [True, False]) +@pytest.mark.parametrize("normalize", [True, False]) +def test_value_counts_sort_categorical(sort, vc_sort, normalize): + # GH#55951 + df = pd.DataFrame({"a": [2, 1, 1, 1], 0: [3, 4, 3, 3]}, dtype="category") + gb = df.groupby("a", sort=sort, observed=True) + result = gb.value_counts(sort=vc_sort, normalize=normalize) + + if normalize: + values = [2 / 3, 1 / 3, 1.0, 0.0] + else: + values = [2, 1, 1, 0] + name = "proportion" if normalize else "count" + expected = pd.DataFrame( + { + "a": pd.Categorical([1, 1, 2, 2]), + 0: pd.Categorical([3, 4, 3, 4]), + name: values, + } + ).set_index(["a", 0])[name] + if sort and vc_sort: + taker = [0, 1, 2, 3] + elif sort and not vc_sort: + taker = [0, 1, 2, 3] + elif not sort and vc_sort: + taker = [0, 2, 1, 3] + else: + taker = [2, 1, 0, 3] + expected = expected.take(taker) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("groupby_sort", [True, False]) +def test_value_counts_all_na(sort, dropna, groupby_sort): + # GH#59989 + df = pd.DataFrame({"a": [2, 1, 1], "b": np.nan}) + gb = df.groupby("a", sort=groupby_sort) + result = gb.value_counts(sort=sort, dropna=dropna) + + kwargs = {"levels": [[1, 2], [np.nan]], "names": ["a", "b"]} + if dropna: + data = [] + index = pd.MultiIndex(codes=[[], []], **kwargs) + elif not groupby_sort and not sort: + data = [1, 2] + index = pd.MultiIndex(codes=[[1, 0], [0, 0]], **kwargs) + else: + data = [2, 1] + index = pd.MultiIndex(codes=[[0, 1], [0, 0]], **kwargs) + expected = pd.Series(data, index=index, dtype="int64", name="count") + + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_all_methods.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_all_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..d80850c0ed3ea7bdf8b468d6f6a480ba526cca0d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_all_methods.py @@ -0,0 +1,104 @@ +""" +Tests that apply to all groupby operation methods. + +The only tests that should appear here are those that use the `groupby_func` fixture. +Even if it does use that fixture, prefer a more specific test file if it available +such as: + + - test_categorical + - test_groupby_dropna + - test_groupby_subclass + - test_raises +""" + +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +def test_multiindex_group_all_columns_when_empty(groupby_func): + # GH 32464 + df = pd.DataFrame({"a": [], "b": [], "c": []}).set_index(["a", "b", "c"]) + gb = df.groupby(["a", "b", "c"], group_keys=True) + method = getattr(gb, groupby_func) + args = get_groupby_method_args(groupby_func, df) + if groupby_func == "corrwith": + warn = Pandas4Warning + warn_msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + warn_msg = "" + with tm.assert_produces_warning(warn, match=warn_msg): + 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.applymarker(pytest.mark.xfail(reason=msg)) + df = pd.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( + "idx", + [ + pd.Index(["a", "a"], name="foo"), + pd.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 = pd.DataFrame([[1, 1]], columns=idx) + grp_by = df.groupby([0]) + + args = get_groupby_method_args(groupby_func, df) + if groupby_func == "corrwith": + warn = Pandas4Warning + warn_msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + warn_msg = "" + with tm.assert_produces_warning(warn, match=warn_msg): + result = getattr(grp_by, groupby_func)(*args) + + assert result.shape == (1, 2) + tm.assert_index_equal(result.columns, idx) + + +def test_not_c_contiguous_mask(groupby_func): + # https://github.com/pandas-dev/pandas/issues/61031 + if groupby_func == "corrwith": + # corrwith is deprecated + return + df = pd.DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}, dtype="Int64", index=[0, 1, 2]) + reversed = pd.DataFrame( + {"a": [2, 1, 1], "b": [5, 4, 3]}, dtype="Int64", index=[2, 1, 0] + )[::-1] + assert not reversed["b"].array._mask.flags["C_CONTIGUOUS"] + args = get_groupby_method_args(groupby_func, df) + + gb_reversed = reversed.groupby("a") + result = getattr(gb_reversed, groupby_func)(*args) + gb = df.groupby("a") + expected = getattr(gb, groupby_func)(*args) + tm.assert_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_api.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..d7d3b93930a509cecbd07c87de02a8b12a58dbda --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_api.py @@ -0,0 +1,271 @@ +""" +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 + +import pandas as pd +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(multiindex_dataframe_random_data): + grp = multiindex_dataframe_random_data.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", + "cumsum", + "cumcount", + "ngroup", + "all", + "shift", + "skew", + "kurt", + "take", + "pct_change", + "any", + "corr", + "corrwith", + "cov", + "ndim", + "diff", + "idxmax", + "idxmin", + "ffill", + "bfill", + "rolling", + "expanding", + "pipe", + "sample", + "ewm", + "value_counts", + } + assert results == expected + + +def test_all_methods_categorized(multiindex_dataframe_random_data): + grp = multiindex_dataframe_random_data.groupby( + multiindex_dataframe_random_data.iloc[:, 0] + ) + names = {_ for _ in dir(grp) if not _.startswith("_")} - set( + multiindex_dataframe_random_data.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 don't exist for DataFrame anymore" + pytest.skip(reason=msg) + + if groupby_func in ("cumcount", "ngroup"): + assert not hasattr(pd.DataFrame, groupby_func) + return + + frame_method = getattr(pd.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"} + exclude_result = {"min_count", "engine", "engine_kwargs"} + elif groupby_func in ("sum", "mean", "std", "var"): + exclude_expected = {"axis", "kwargs"} + exclude_result = {"engine", "engine_kwargs"} + elif groupby_func in ("median", "prod", "sem"): + exclude_expected = {"axis", "kwargs"} + elif groupby_func in ("bfill", "ffill"): + exclude_expected = {"inplace", "axis", "limit_area"} + elif groupby_func in ("cummax", "cummin"): + exclude_expected = {"axis", "args"} + elif groupby_func in ("cumprod", "cumsum"): + exclude_expected = {"axis"} + elif groupby_func in ("pct_change",): + exclude_expected = {"kwargs"} + elif groupby_func in ("rank",): + exclude_expected = {"numeric_only"} + elif groupby_func in ("quantile",): + exclude_expected = {"method", "axis"} + elif groupby_func in ["corrwith"]: + exclude_expected = {"min_periods"} + if groupby_func not in ["pct_change", "size"]: + exclude_expected |= {"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"): + msg = "first and last don't exist for Series anymore" + pytest.skip(msg) + + if groupby_func in ("cumcount", "corrwith", "ngroup"): + assert not hasattr(pd.Series, groupby_func) + return + + series_method = getattr(pd.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 ("max", "min"): + exclude_expected = {"axis", "kwargs"} + exclude_result = {"min_count", "engine", "engine_kwargs"} + elif groupby_func in ("sum", "mean", "std", "var"): + exclude_expected = {"axis", "kwargs"} + exclude_result = {"engine", "engine_kwargs"} + elif groupby_func in ("median", "prod", "sem"): + exclude_expected = {"axis", "kwargs"} + elif groupby_func in ("bfill", "ffill"): + exclude_expected = {"inplace", "axis", "limit_area"} + elif groupby_func in ("cummax", "cummin"): + exclude_expected = {"args"} + exclude_result = {"numeric_only"} + elif groupby_func in ("cumprod", "cumsum"): + exclude_expected = set() + exclude_result = {"numeric_only"} + elif groupby_func in ("pct_change",): + exclude_expected = {"kwargs"} + 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"} + if groupby_func not in [ + "diff", + "pct_change", + "count", + "nunique", + "quantile", + "size", + ]: + exclude_expected |= {"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 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_apply.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_apply.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9ca8f1eab604cf656485c599749588b3e754d4 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_apply.py @@ -0,0 +1,1588 @@ +from datetime import ( + date, + datetime, + time, +) + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +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 = pd.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 = pd.DataFrame({0: [1] * 10}, index=pd.RangeIndex(0, 100, 10)) + expected_value.columns = expected_value.columns.astype(object) + + tm.assert_frame_equal(groups[0], expected_value) + + +def test_apply_index_date(using_infer_string): + # GH 5788 + ts = [ + "2011-05-16 00:00", + "2011-05-16 01:00", + "2011-05-16 02:00", + "2011-05-16 03:00", + "2011-05-17 02:00", + "2011-05-17 03:00", + "2011-05-17 04:00", + "2011-05-17 05:00", + "2011-05-18 02:00", + "2011-05-18 03:00", + "2011-05-18 04:00", + "2011-05-18 05:00", + ] + df = pd.DataFrame( + { + "value": [ + 1.40893, + 1.40760, + 1.40750, + 1.40649, + 1.40893, + 1.40760, + 1.40750, + 1.40649, + 1.40893, + 1.40760, + 1.40750, + 1.40649, + ], + }, + index=pd.Index(pd.to_datetime(ts), name="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) + + +def test_apply_index_date_object(): + # GH 5789 + # don't auto coerce dates + ts = [ + "2011-05-16 00:00", + "2011-05-16 01:00", + "2011-05-16 02:00", + "2011-05-16 03:00", + "2011-05-17 02:00", + "2011-05-17 03:00", + "2011-05-17 04:00", + "2011-05-17 05:00", + "2011-05-18 02:00", + "2011-05-18 03:00", + "2011-05-18 04:00", + "2011-05-18 05:00", + ] + df = pd.DataFrame([row.split() for row in ts], columns=["date", "time"]) + df["value"] = [ + 1.40893, + 1.40760, + 1.40750, + 1.40649, + 1.40893, + 1.40760, + 1.40750, + 1.40649, + 1.40893, + 1.40760, + 1.40750, + 1.40649, + ] + exp_idx = pd.Index(["2011-05-16", "2011-05-17", "2011-05-18"], name="date") + expected = pd.Series(["00:00", "02:00", "02:00"], index=exp_idx) + result = df.groupby("date").apply(lambda x: x["time"][x["value"].idxmax()]) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "df, group_names", + [ + ( + pd.DataFrame({"a": [1, 1, 1, 2, 3], "b": ["a", "a", "a", "b", "c"]}), + [1, 2, 3], + ), + (pd.DataFrame({"a": [0, 0, 1, 1], "b": [0, 1, 0, 1]}), [0, 1]), + (pd.DataFrame({"a": [1]}), [1]), + (pd.DataFrame({"a": [1, 1, 1, 2, 2, 1, 1, 2], "b": range(8)}), [1, 2]), + (pd.DataFrame({"a": [1, 2, 3, 1, 2, 3], "two": [4, 5, 6, 7, 8, 9]}), [1, 2, 3]), + ( + pd.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"], + ), + (pd.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 pd.DataFrame({"a": [1], "b": [1]}) + + for func in [f_copy, f_nocopy, f_scalar, f_none, f_constant_df]: + del names[:] + + df.groupby("a").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 = pd.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 = pd.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) + + +def test_apply_fast_slow_identical_index(): + # 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) + + +@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 = pd.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[["a", "b"]]) + + +def test_apply_with_mixed_dtype(): + # GH3480, apply with mixed dtype on axis=1 breaks in 0.11 + df = pd.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) + expected = df + tm.assert_frame_equal(result, expected) + + # GH 3610 incorrect dtype conversion with as_index=False + df = pd.DataFrame({"c1": [1, 2, 6, 6, 8]}) + df["c2"] = df.c1 / 2.0 + result1 = df.groupby("c2").mean().reset_index() + result2 = df.groupby("c2", as_index=False).mean() + tm.assert_frame_equal(result1, result2) + + +def test_groupby_as_index_apply(as_index): + # GH #4648 and #3417 + df = pd.DataFrame( + { + "item_id": ["b", "b", "a", "c", "a", "b"], + "user_id": [1, 2, 1, 1, 3, 1], + "time": range(6), + } + ) + gb = df.groupby("user_id", as_index=as_index) + + expected = pd.DataFrame( + { + "item_id": ["b", "b", "a", "a"], + "user_id": [1, 2, 1, 3], + "time": [0, 1, 2, 4], + }, + index=[0, 1, 2, 4], + ) + result = gb.head(2) + tm.assert_frame_equal(result, expected) + + # apply doesn't maintain the original ordering + # changed in GH5610 as the as_index=False returns a MI here + if as_index: + tp = [(1, 0), (1, 2), (2, 1), (3, 4)] + index = pd.MultiIndex.from_tuples(tp, names=["user_id", None]) + else: + index = pd.Index([0, 2, 1, 4]) + expected = pd.DataFrame( + { + "item_id": list("baba"), + "time": [0, 2, 1, 4], + }, + index=index, + ) + result = gb.apply(lambda x: x.head(2)) + tm.assert_frame_equal(result, expected) + + +def test_groupby_as_index_apply_str(): + ind = pd.Index(list("abcde")) + df = pd.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 pd.DataFrame( + {"value": piece, "demeaned": piece - piece.mean(), "logged": logged} + ) + + dr = pd.bdate_range("1/1/2000", periods=10) + ts = pd.Series(np.random.default_rng(2).standard_normal(10), index=dr) + + grouped = ts.groupby(lambda x: x.month, group_keys=False) + result = grouped.apply(f) + + assert isinstance(result, pd.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, pd.Series) + assert result.name is None + + result = df.groupby(["A", "B"])[["C", "D"]].apply(len) + assert isinstance(result, pd.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 = pd.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) + 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 = pd.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[["value"]].take([0, 1, 3, 4, 6, 7]) + if group_keys: + expected.index = pd.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 = pd.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")) + + +def test_apply_typecast_fail(): + df = pd.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[["c", "v"]] + expected["v2"] = np.tile([0.0, 0.5, 1], 2) + + tm.assert_frame_equal(result, expected) + + +def test_apply_multiindex_fail(): + index = pd.MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1], [1, 2, 3, 1, 2, 3]]) + df = pd.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[["c", "v"]] + 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 = pd.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 = pd.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) + expected = ser + tm.assert_series_equal(result, expected) + else: + result = df.groupby("Y", group_keys=False).apply(lambda x: x) + expected = df[["X"]] + 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 = pd.DataFrame( + {"group": ["Group1", "Group2"] * 2, "value": values}, index=indices + ) + expected = pd.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 = 10 + labels = np.random.default_rng(2).integers(0, 100, size=N) + df = pd.DataFrame( + { + "key": labels, + "value1": np.random.default_rng(2).standard_normal(N), + "value2": ["foo", "bar", "baz", "qux", "a"] * (N // 5), + } + ) + + 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 = pd.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"]) + + +def test_apply_numeric_coercion_when_datetime_getitem(): + # GH 15421 + df = pd.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) + + +def test_apply_numeric_coercion_when_datetime_with_nat(): + # GH 14423 + def predictions(tool): + out = pd.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 = pd.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 = pd.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: pd.Series( + {"clientid_age": ddf.time_delta_zero.min(), "date": ddf.datetime.min()} + ) + ) + expected = pd.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 = pd.DataFrame( + data, columns=["Name", "Value"], index=pd.date_range("2020-09-01", "2020-09-05") + ) + + result = df.groupby("Name").sum() + + expected = pd.DataFrame({"Name": ["A", "B", "C"], "Value": [10, 50, 90]}) + expected = expected.set_index("Name") + + 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 = pd.DataFrame({"a": 1, "b": [datetime(2011, 1, 1)] * 10}) + + def func_with_no_date(batch): + return pd.Series({"c": 2}) + + def func_with_date(batch): + return pd.Series({"b": datetime(2015, 1, 1), "c": 2}) + + dfg_no_conversion = df.groupby(by=["a"]).apply(func_with_no_date) + dfg_no_conversion_expected = pd.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 = pd.DataFrame( + {"b": pd.Timestamp(2015, 1, 1), "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 = pd.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 = pd.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 = pd.DataFrame(columns=["random_vars"], dtype="int64") + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "in_data, out_idx, out_data", + [ + [ + {"groups": [1, 1, 1, 2], "vars": [0, 1, 2, 3]}, + [[1, 1], [0, 2]], + {"vars": [0, 2]}, + ], + [ + {"groups": [1, 2, 2, 2], "vars": [0, 1, 2, 3]}, + [[2, 2], [1, 3]], + {"vars": [1, 3]}, + ], + ], +) +def test_groupby_apply_none_first(in_data, out_idx, out_data): + # GH 12824. Tests if apply returns None first. + test_df1 = pd.DataFrame(in_data) + + def test_func(x): + if x.shape[0] < 2: + return None + return x.iloc[[0, -1]] + + result1 = test_df1.groupby("groups").apply(test_func) + index1 = pd.MultiIndex.from_arrays(out_idx, names=["groups", None]) + expected1 = pd.DataFrame(out_data, index=index1) + tm.assert_frame_equal(result1, expected1) + + +def test_groupby_apply_return_empty_chunk(): + # GH 22221: apply filter which returns some empty groups + df = pd.DataFrame({"value": [0, 1], "group": ["filled", "empty"]}) + groups = df.groupby("group") + result = groups.apply(lambda group: group[group.value != 1]["value"]) + expected = pd.Series( + [0], + name="value", + index=pd.MultiIndex.from_product( + [["empty", "filled"], [0]], names=["group", None] + ).drop("empty"), + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("meth", ["apply", "transform"]) +def test_apply_with_mixed_types(meth): + # gh-20949 + df = pd.DataFrame({"A": "a a b".split(), "B": [1, 2, 3], "C": [4, 6, 5]}) + g = df.groupby("A", group_keys=False) + + result = getattr(g, meth)(lambda x: x / x.sum()) + expected = pd.DataFrame({"B": [1 / 3.0, 2 / 3.0, 1], "C": [0.4, 0.6, 1.0]}) + tm.assert_frame_equal(result, expected) + + +def test_func_returns_object(): + # GH 28652 + df = pd.DataFrame({"a": [1, 2]}, index=pd.Index([1, 2])) + result = df.groupby("a").apply(lambda g: g.index) + expected = pd.Series( + [pd.Index([1]), pd.Index([2])], index=pd.Index([1, 2], name="a") + ) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "group_column_dtlike", + [datetime(2011, 1, 1, 9), date(2011, 1, 1), time(9, 0)], +) +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 = pd.DataFrame({"a": ["foo"], "b": [group_column_dtlike]}) + result = df.groupby("a").apply(lambda x: pd.Series(["spam"], index=[42])) + + expected = pd.DataFrame( + ["spam"], pd.Index(["foo"], dtype="str", name="a"), columns=[42] + ) + tm.assert_frame_equal(result, expected) + + +def test_apply_series_return_dataframe_groups(): + # GH 10078 + tdf = pd.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 pd.Series({c: s.value_counts().index[0] for c, s in df.items()}) + + result = tdf.groupby("day").apply(most_common_values)["userId"] + expected = pd.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 = pd.Index([1, 2], name="B") + expected_values = [20, 25] + expected = pd.DataFrame( + {"C": expected_values, "D": expected_values}, index=expected_index + ) + + df = pd.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(using_infer_string): + # GH 14849 + data = pd.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 + dtype = pd.StringDtype(na_value=np.nan) if using_infer_string else object + expected = pd.Series( + [np.dtype("datetime64[us]"), dtype, np.int64, dtype], + index=["observation", "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"), + pd.MultiIndex.from_tuples([("a", 0), ("a", 1), ("b", 0)]), + ], +) +def test_apply_index_has_complex_internals(index): + # GH 31248 + df = pd.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[["value"]]) + + +@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 = pd.DataFrame(["A", "A", "B", "B"], columns=["groups"]) + result = df.groupby("groups").apply(function) + expected = pd.Series(expected_values, index=pd.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 = pd.DataFrame({"A": ["a", "a", "b", "none"], "B": [1, 2, 3, np.nan]}) + + result = df.groupby("A").apply(fct) + expected = pd.Series( + [[1.0, 2.0], [3.0], [np.nan]], index=pd.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 = pd.DataFrame([1, 2, 2, 2, 1, 2, 3, 1, 3, 1], columns=["id"]) + result = df.groupby("id").apply(function) + expected = pd.Series( + [pd.Index([0, 4, 7, 9]), pd.Index([1, 2, 3, 5]), pd.Index([6, 8])], + index=pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame({"x": list(range(2)) * 3, "y": range(6), "t": index_no_tz}) + df2 = pd.DataFrame({"x": list(range(2)) * 3, "y": range(6), "t": index_tz}) + + result1 = df1.groupby("x", group_keys=False).apply(lambda df: df[["y"]].copy()) + result2 = df2.groupby("x", group_keys=False).apply(lambda df: df[["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 = pd.DataFrame( + { + "a": [99, 99, 99, 88, 88, 88], + "b": [1, 2, 3, 4, 5, 6], + "c": [10, 20, 30, 40, 50, 60], + } + ) + + expected = pd.DataFrame( + {"b": [15, 6], "c": [150, 60]}, + index=pd.Index([88, 99], name="a"), + ) + + # Check output when no other methods are called before .apply() + grp = df.groupby(by="a") + result = grp.apply(np.sum, axis=0) + 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) + if reduction_func == "corrwith": + warn = Pandas4Warning + msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + msg = "" + with tm.assert_produces_warning(warn, match=msg): + _ = getattr(grp, reduction_func)(*args) + result = grp.apply(np.sum, axis=0) + tm.assert_frame_equal(result, expected) + + +def test_apply_with_date_in_multiindex_does_not_convert_to_timestamp(): + # GH 29617 + + df = pd.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=pd.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 = pd.MultiIndex.from_frame(expected[["A", "B", "idx"]]) + expected = expected.drop(columns=["A", "B", "idx"]) + + tm.assert_frame_equal(result, expected) + for val in result.index.levels[1]: + assert type(val) is date + + +def test_apply_dropna_with_indexed_same(dropna): + # GH 38227 + # GH#43205 + df = pd.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()[["col"]] if dropna else df[["col"]].iloc[[0, 3, 1, 2, 4]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "as_index, expected", + [ + [ + False, + pd.DataFrame( + [[1, 1, 1], [2, 2, 1]], columns=pd.Index(["a", "b", None], dtype=object) + ), + ], + [ + True, + pd.Series( + [1, 1], + index=pd.MultiIndex.from_tuples([(1, 1), (2, 2)], names=["a", "b"]), + ), + ], + ], +) +def test_apply_as_index_constant_lambda(as_index, expected): + # GH 13217 + df = pd.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 = pd.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 = pd.Series( + range(1, 6), + index=pd.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 = pd.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[["date", "vals"]]) + + +def test_groupby_apply_shape_cache_safety(): + # GH#42702 this fails if we cache_readonly Block.shape + df = pd.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 = pd.DataFrame( + {"B": [1.0, 0.0], "C": [2.0, 0.0]}, index=pd.Index(["a", "b"], name="A") + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_apply_to_series_name(): + # GH52444 + df = pd.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 = pd.MultiIndex.from_arrays( + arrays=[["a", "a", "b", "b", "b"], ["aa", "ac", "ac", "ad", "aa"]], + names=["a", None], + ) + expected = pd.Series([3, 1, 2, 1, 1], index=expected_idx, name="count") + tm.assert_series_equal(result, expected) + + +def test_apply_na(dropna): + # GH#28984 + df = pd.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 = ( + pd.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 = pd.DataFrame( + [[pd.to_datetime(2, unit="s")], [pd.to_datetime(4, unit="s")]], + columns=["c"], + index=pd.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 = pd.DataFrame( + { + "a": ["aa", "a2", "a3"], + "b": [1, 2, 3], + }, + index=pd.Index(index_values), + ) + expected = pd.DataFrame( + { + "b_mean": [2.0, 3.0, 1.0], + }, + index=pd.Index(["a2", "a3", "aa"], name="a"), + ) + result = result.groupby("a").apply( + lambda df: pd.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 + df = pd.DataFrame({"grp": arg, "col": arg}, index=idx) + result = df.groupby("grp", group_keys=False).apply(lambda x: x) + expected = df[["col"]] + 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 = pd.Series([1, 2], name=name) + result = ser.groupby(["a", "a"], group_keys=False).apply(lambda x: x) + expected = pd.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", "kurt"), + ("agg", "prod"), + ("agg", "sum"), + ], +) +def test_empty_df(method, op): + # GH 47985 + empty_df = pd.DataFrame({"a": [], "b": []}) + gb = empty_df.groupby("a", group_keys=True) + group = gb.b + + result = getattr(group, method)(op) + expected = pd.Series( + [], name="b", dtype="float64", index=pd.Index([], dtype="float64", name="a") + ) + + tm.assert_series_equal(result, expected) + + +def test_include_groups(): + # GH#7155 + df = pd.DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + gb = df.groupby("a") + with pytest.raises(ValueError, match="include_groups=True is no longer allowed"): + gb.apply(lambda x: x.sum(), include_groups=True) + + +@pytest.mark.parametrize("func, value", [(max, 2), (min, 1), (sum, 3)]) +def test_builtins_apply(func, value): + # GH#8155, GH#53974 + # Builtins act as e.g. sum(group), which sums the column labels of group + df = pd.DataFrame({0: [1, 1, 2], 1: [3, 4, 5], 2: [3, 4, 5]}) + gb = df.groupby(0) + result = gb.apply(func) + + expected = pd.Series([value, value], index=pd.Index([1, 2], name=0)) + tm.assert_series_equal(result, expected) + + +def test_inconsistent_return_type(): + # GH5592 + # inconsistent return type + df = pd.DataFrame( + { + "A": ["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"], + "B": pd.Series(np.arange(7), dtype="int64"), + "C": pd.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"]] + e = expected.copy() + 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"]] + e = expected.copy() + 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_nonreducer_nonstransform(): + # GH3380, GH60619 + # Was originally testing mutating in a UDF; now kept as an example + # of using apply with a nonreducer and nontransformer. + df = pd.DataFrame( + { + "cat1": ["a"] * 8 + ["b"] * 6, + "cat2": ["c"] * 2 + + ["d"] * 2 + + ["e"] * 2 + + ["f"] * 2 + + ["c"] * 2 + + ["d"] * 2 + + ["e"] * 2, + "val": np.random.default_rng(2).integers(100, size=14), + } + ) + + def f(x): + x = x.copy() + x["rank"] = x.val.rank(method="min") + return x.groupby("cat2")["rank"].min() + + expected = pd.DataFrame( + { + "cat1": list("aaaabbb"), + "cat2": list("cdefcde"), + "rank": [3.0, 2.0, 5.0, 1.0, 2.0, 4.0, 1.0], + } + ).set_index(["cat1", "cat2"])["rank"] + result = df.groupby("cat1").apply(f) + tm.assert_series_equal(result, expected) + + +def test_groupby_apply_store_copy(): + # GH40673 + rng = np.random.default_rng(seed=42) + + df = pd.DataFrame( + { + "A": rng.normal(10, 12, size=(4,)), + "B": [1, 2, 1, 2], + } + ) + + store = {} + + def addstore(x): + store[len(store)] = x.copy() + + df.groupby("B").apply(addstore) + + expected_out_0 = df.iloc[[0, 2], [0]] + expected_out_1 = df.iloc[[1, 3], [0]] + + tm.assert_frame_equal(store[0], expected_out_0) + tm.assert_frame_equal(store[1], expected_out_1) + + +def test_groupby_apply_return_object_holding_index(): + # GH#41477 when the UDF returns an arbitrary object that holds a reference + # to the group's Index, each result must keep its own group's Index + # rather than all sharing a single one. + class Wrapper: + def __init__(self, value): + self.value = value + + df = pd.DataFrame({"key": ["a", "b"]}, index=["foo", "bar"]) + result = df.groupby("key").apply(lambda group: Wrapper(group.index)) + + tm.assert_index_equal(result.loc["a"].value, pd.Index(["foo"])) + tm.assert_index_equal(result.loc["b"].value, pd.Index(["bar"])) + + +@pytest.mark.parametrize("test_empty", [False, True]) +def test_apply_as_index_false_empty_index_name(test_empty): + # https://github.com/pandas-dev/pandas/issues/48135 + df = pd.DataFrame({"A": [4, 4, 4], "B": [9, 9, 9]}) + + if test_empty: + df = df.iloc[:0] + + gb = df.groupby("A", as_index=False) + result = gb.apply(lambda x: x) + + if test_empty: + expected = pd.DataFrame( + {"B": pd.Series([], dtype="int64")}, + index=pd.Index([], dtype="int64"), + ) + else: + expected = pd.DataFrame( + {"B": [9, 9, 9]}, + index=pd.Index([0, 1, 2], dtype="int64"), + ) + + expected.index.name = None + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_bin_groupby.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_bin_groupby.py new file mode 100644 index 0000000000000000000000000000000000000000..07d52308e308ad637fad8df5802b8e79985b8127 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_bin_groupby.py @@ -0,0 +1,67 @@ +import numpy as np +import pytest + +from pandas._libs import lib + +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, + assert_block_lengths, + ], +) +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", + [ + ( + [0, 3, 6, 9], + "left", + [2, 5, 6], + ), + ( + [0, 3, 6, 9], + "right", + [3, 6, 6], + ), + ([0, 3, 6], "left", [2, 5]), + ( + [0, 3, 6], + "right", + [3, 6], + ), + ], +) +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, np.array(binner, dtype=np.int64), closed=closed + ) + expected = np.array(expected, dtype=np.int64) + tm.assert_numpy_array_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_categorical.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..33809eb94408ba7a840752660216d3111b21d8e3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_categorical.py @@ -0,0 +1,2355 @@ +from datetime import datetime + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +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 product for the groupers, + preserving the nature (Categorical) of each grouper + """ + + def f(a): + if isinstance(a, (pd.CategoricalIndex, pd.Categorical)): + categories = a.categories + a = pd.Categorical.from_codes( + np.arange(len(categories)), categories=categories, ordered=a.ordered + ) + return a + + index = pd.MultiIndex.from_product(map(f, args), names=names) + if isinstance(fill_value, dict): + # fill_value is a dict mapping column names to fill values + # -> reindex column by column (reindex itself does not support this) + res = {} + for col in result.columns: + res[col] = result[col].reindex(index, fill_value=fill_value[col]) + return pd.DataFrame(res, index=index).sort_index() + + 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": True, + "any": False, + "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": 1, + "quantile": np.nan, + "sem": np.nan, + "size": 0, + "skew": np.nan, + "kurt": np.nan, + "std": np.nan, + "sum": 0, + "var": np.nan, +} + + +def test_apply_use_categorical_name(df): + cats = pd.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(): + cats = pd.Categorical( + ["a", "a", "a", "b", "b", "b", "c", "c", "c"], + categories=["a", "b", "c", "d"], + ordered=True, + ) + data = pd.DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats}) + + exp_index = pd.CategoricalIndex(list("abcd"), name="b", ordered=True) + expected = pd.DataFrame({"a": [1, 2, 4, np.nan]}, index=exp_index) + result = data.groupby("b", observed=False).mean() + tm.assert_frame_equal(result, expected) + + +def test_basic_single_grouper(): + cat1 = pd.Categorical( + ["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True + ) + cat2 = pd.Categorical( + ["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True + ) + df = pd.DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) + + gb = df.groupby("A", observed=False) + exp_idx = pd.CategoricalIndex(["a", "b", "z"], name="A", ordered=True) + expected = pd.DataFrame({"values": pd.Series([3, 7, 0], index=exp_idx)}) + result = gb.sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + +def test_basic_string(using_infer_string): + # GH 8623 + x = pd.DataFrame( + [[1, "John P. Doe"], [2, "Jane Dove"], [1, "John P. Doe"]], + columns=["person_id", "person_name"], + ) + x["person_name"] = pd.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[["person_name"]].iloc[[0, 1]] + expected.index = pd.Index([1, 2], name="person_id") + dtype = "str" if using_infer_string else object + expected["person_name"] = expected["person_name"].astype(dtype) + tm.assert_frame_equal(result, expected) + + +def test_basic_monotonic(): + # GH 9921 + df = pd.DataFrame({"a": [5, 15, 25]}) + c = pd.cut(df.a, bins=[0, 10, 20, 30, 40]) + + 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"] + ) + 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)) + 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"]]) + tm.assert_frame_equal(result3, df[["a"]]) + 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) + + +def test_basic_non_monotonic(): + df = pd.DataFrame({"a": [5, 15, 25, -5]}) + c = pd.cut(df.a, bins=[-10, 0, 10, 20, 30, 40]) + + 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"] + ) + 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"]] + ) + + +def test_basic_cut_grouping(): + # GH 9603 + df = pd.DataFrame({"a": [1, 0, 0, 0]}) + c = pd.cut(df.a, [0, 1, 2, 3, 4], labels=pd.Categorical(list("abcd"))) + result = df.groupby(c, observed=False).apply(len) + + exp_index = pd.CategoricalIndex(c.values.categories, ordered=c.values.ordered) + expected = pd.Series([1, 0, 0, 0], index=exp_index) + expected.index.name = "a" + tm.assert_series_equal(result, expected) + + +def test_more_basic(): + levels = ["foo", "bar", "baz", "qux"] + codes = np.random.default_rng(2).integers(0, 4, size=10) + + cats = pd.Categorical.from_codes(codes, levels, ordered=True) + + data = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 4))) + + result = data.groupby(cats, observed=False).mean() + + expected = data.groupby(np.asarray(cats), observed=False).mean() + exp_idx = pd.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 = pd.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 = pd.Categorical.from_codes(np.arange(4).repeat(8), levels, ordered=True) + exp = pd.CategoricalIndex(expc) + tm.assert_index_equal(desc_result.stack().index.get_level_values(0), exp) + exp = pd.Index(["count", "mean", "std", "min", "25%", "50%", "75%", "max"] * 4) + tm.assert_index_equal(desc_result.stack().index.get_level_values(1), exp) + + +def test_level_get_group(observed): + # GH15155 + df = pd.DataFrame( + data=np.arange(2, 22, 2), + index=pd.MultiIndex( + levels=[pd.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 = pd.DataFrame( + data=np.arange(2, 12, 2), + index=pd.MultiIndex( + levels=[pd.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 = pd.DataFrame( + { + "group": ["A"] * 6 + ["B"] * 6, + "dose": ["high", "med", "low"] * 4, + "outcomes": np.arange(12.0), + } + ) + + df.dose = pd.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 = pd.Categorical(index, categories=["low", "med", "high"], ordered=True) + index = [["A", "A", "A", "B", "B", "B"], pd.CategoricalIndex(index)] + index = pd.MultiIndex.from_arrays(index, names=["group", "dose"]) + expected = pd.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 = pd.Categorical(list("abc"), ordered=ordered) + + # 'b' is in the categories but not in the list + missing = pd.Categorical(list("aaa"), categories=["a", "b"], ordered=ordered) + values = np.arange(len(dense)) + df = pd.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 = pd.MultiIndex.from_arrays([missing, dense], names=["missing", "dense"]) + expected = pd.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) + + result = grouped.agg(np.mean) + tm.assert_frame_equal(result, expected) + + # but for transform we should still get back the original index + idx = pd.MultiIndex.from_arrays([missing, dense], names=["missing", "dense"]) + expected = pd.Series(1, index=idx) + result = grouped.apply(lambda x: 1) + tm.assert_series_equal(result, expected) + + +def test_observed(observed, using_infer_string): + # 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 = pd.Categorical( + ["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True + ) + cat2 = pd.Categorical( + ["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True + ) + df = pd.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 = pd.MultiIndex.from_arrays( + [cat1, cat2, ["foo", "bar"] * 2], names=["A", "B", "C"] + ) + expected = pd.DataFrame( + {"values": pd.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 = pd.MultiIndex.from_arrays([cat1, cat2], names=["A", "B"]) + expected = pd.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={"values": 0, "C": ""} if using_infer_string else 0, + ) + + tm.assert_frame_equal(result, expected) + + +def test_observed_single_column(observed): + # https://github.com/pandas-dev/pandas/issues/8138 + d = { + "cat": pd.Categorical( + ["a", "b", "a", "b"], categories=["a", "b", "c"], ordered=True + ), + "ints": [1, 1, 2, 2], + "val": [10, 20, 30, 40], + } + df = pd.DataFrame(d) + + groups_single_key = df.groupby("cat", observed=observed) + result = groups_single_key.mean() + + exp_index = pd.CategoricalIndex( + list("ab"), name="cat", categories=list("abc"), ordered=True + ) + expected = pd.DataFrame({"ints": [1.5, 1.5], "val": [20.0, 30]}, index=exp_index) + if not observed: + index = pd.CategoricalIndex( + list("abc"), name="cat", categories=list("abc"), ordered=True + ) + expected = expected.reindex(index) + + tm.assert_frame_equal(result, expected) + + +def test_observed_two_columns(observed): + # https://github.com/pandas-dev/pandas/issues/8138 + d = { + "cat": pd.Categorical( + ["a", "b", "a", "b"], categories=["a", "b", "c"], ordered=True + ), + "ints": [1, 1, 2, 2], + "val": [10, 20, 30, 40], + } + df = pd.DataFrame(d) + groups_double_key = df.groupby(["cat", "ints"], observed=observed) + result = groups_double_key.agg("mean") + expected = pd.DataFrame( + { + "val": [10.0, 30.0, 20.0, 40.0], + "cat": pd.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) + + +def test_observed_with_as_index(observed): + # 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 = pd.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 = pd.DataFrame(d) + values = pd.cut(df["C1"], [1, 2, 3, 6]) + values.name = "cat" + groups_double_key = df.groupby([values, "C2"], observed=observed) + + idx = pd.MultiIndex.from_arrays([values, [1, 2, 3, 4]], names=["cat", "C2"]) + expected = pd.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 = pd.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 = pd.Categorical(["a", "c", "a"], categories=["a", "b", "c"]) + df = pd.DataFrame({"cat": cat, "vals": [1, 2, 3]}) + g = df.groupby("cat", observed=observed) + + result = g.groups + if observed: + expected = { + "a": pd.Index([0, 2], dtype="int64"), + "c": pd.Index([1], dtype="int64"), + } + else: + expected = { + "a": pd.Index([0, 2], dtype="int64"), + "b": pd.Index([], dtype="int64"), + "c": pd.Index([1], dtype="int64"), + } + + tm.assert_dict_equal(result, expected) + + +def test_groups_na_category(dropna, observed): + # https://github.com/pandas-dev/pandas/issues/61356 + df = pd.DataFrame( + {"cat": pd.Categorical(["a", np.nan, "a"], categories=list("adb"))}, + index=list("xyz"), + ) + g = df.groupby("cat", observed=observed, dropna=dropna) + + result = g.groups + expected = {"a": pd.Index(["x", "z"])} + if not dropna: + expected |= {np.nan: pd.Index(["y"])} + if not observed: + expected |= {"b": pd.Index([]), "d": pd.Index([])} + tm.assert_dict_equal(result, expected) + + +@pytest.mark.parametrize( + "keys, expected_values, expected_index_levels", + [ + ("a", [15, 9, 0], pd.CategoricalIndex([1, 2, 3], name="a")), + ( + ["a", "b"], + [7, 8, 0, 0, 0, 9, 0, 0, 0], + [pd.CategoricalIndex([1, 2, 3], name="a"), pd.Index([4, 5, 6])], + ), + ( + ["a", "a2"], + [15, 0, 0, 0, 9, 0, 0, 0, 0], + [ + pd.CategoricalIndex([1, 2, 3], name="a"), + pd.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 = pd.DataFrame( + { + "a": pd.Categorical([1, 1, 2], categories=[1, 2, 3]), + "a2": pd.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 = pd.MultiIndex( + expected_index_levels, + codes=codes, + names=keys, + ) + expected = pd.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 = pd.DataFrame( + { + "cat": pd.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": pd.Index([0, 2], dtype="int64")} + else: + expected = { + "a": pd.Index([0, 2], dtype="int64"), + "b": pd.Index([], dtype="int64"), + "d": pd.Index([], dtype="int64"), + } + tm.assert_dict_equal(result, expected) + + +def test_observed_nth(): + # GH 26385 + cat = pd.Categorical(["a", np.nan, np.nan], categories=["a", "b", "c"]) + ser = pd.Series([1, 2, 3]) + df = pd.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 = pd.Categorical([np.nan, "a", np.nan, "a"], categories=["a", "b", "c"]) + s2 = pd.Series([1, 2, 3, 4]) + df = pd.DataFrame({"s1": s1, "s2": s2}) + result = df.groupby("s1", observed=observed).first().reset_index() + if observed: + expected = pd.DataFrame( + {"s1": pd.Categorical(["a"], categories=["a", "b", "c"]), "s2": [2]} + ) + else: + expected = pd.DataFrame( + { + "s1": pd.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]) +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 = pd.Categorical( + ["d", "a", "b", "a", "d", "b"], + categories=["a", "b", "missing", "d"], + ordered=ordered, + ) + val = pd.Series(["d", "a", "b", "a", "d", "b"]) + df = pd.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 = pd.Series(result.index.array, dtype="object") + aggr = pd.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}" + ) + pytest.fail(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=10) + + cats = pd.Categorical.from_codes(codes, levels, ordered=True) + + data = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 4))) + result = data.groupby(cats, observed=False).mean() + + expected = data.groupby(np.asarray(cats), observed=False).mean() + expected = expected.reindex(levels) + expected.index = pd.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 = pd.Categorical.from_codes(np.arange(4).repeat(8), levels, ordered=True) + exp = pd.CategoricalIndex(expc) + tm.assert_index_equal((desc_result.stack().index.get_level_values(0)), exp) + exp = pd.Index(["count", "mean", "std", "min", "25%", "50%", "75%", "max"] * 4) + tm.assert_index_equal((desc_result.stack().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 = pd.Categorical.from_codes(codes, levels, ordered=True) + df = pd.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 = pd.CategoricalIndex( + pd.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 = pd.CategoricalIndex( + pd.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 = pd.CategoricalIndex( + ["qux", "foo", "baz", "bar"], + categories=["foo", "bar", "baz", "qux"], + ordered=True, + ) + df = pd.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().columns, cats) + tm.assert_categorical_equal(result.stack().columns.values, cats.values) + + +def test_unstack_categorical(): + # GH11558 (example is taken from the original issue) + df = pd.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 = pd.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 = pd.Series([6, 4], index=pd.Index(["X", "Y"], name="artist")) + tm.assert_series_equal(result, expected) + + +def test_bins_unequal_len(): + # GH3011 + series = pd.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. + (pd.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. + (pd.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. + (pd.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(pd.Series(list("ABBA"), dtype="category"), observed=False) + result = groupby.aggregate(list) + expected = pd.Series(data, index=pd.CategoricalIndex(data.keys())) + tm.assert_series_equal(result, expected) + + +def test_as_index(): + # GH13204 + df = pd.DataFrame( + { + "cat": pd.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 = pd.DataFrame( + { + "cat": pd.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"] + result = df.groupby(["cat", f], as_index=False, observed=True).sum() + expected = pd.DataFrame( + { + "cat": pd.Categorical([1, 2], categories=df.cat.cat.categories), + "level_1": [10, 11], + "A": [10, 22], + "B": [101, 205], + }, + ) + tm.assert_frame_equal(result, expected) + + # another not in-axis grouper (conflicting names in index) + s = pd.Series(["a", "b", "b"], name="cat") + result = df.groupby(["cat", s], as_index=False, observed=True).sum() + expected = pd.DataFrame( + { + "cat": ["a", "b"], + "A": [10, 22], + "B": [101, 205], + }, + ) + tm.assert_frame_equal(result, expected) + + # is original index dropped? + group_columns = ["cat", "A"] + expected = pd.DataFrame( + { + "cat": pd.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 = pd.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 = pd.DataFrame( + {"A": pd.Categorical(list("ba"), categories=categories, ordered=True)} + ) + sort_index = pd.CategoricalIndex(categories, categories, ordered=True, name="A") + nosort_index = pd.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 + ) + + +def test_preserve_categories_ordered_false(): + # GH-13179 + categories = list("abc") + df = pd.DataFrame( + {"A": pd.Categorical(list("ba"), categories=categories, ordered=False)} + ) + sort_index = pd.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 = pd.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 + ) + + +@pytest.mark.parametrize("col", ["C1", "C2"]) +def test_preserve_categorical_dtype(col): + # GH13743, GH13854 + df = pd.DataFrame( + { + "A": [1, 2, 1, 1, 2], + "B": [10, 16, 22, 28, 34], + "C1": pd.Categorical(list("abaab"), categories=list("bac"), ordered=False), + "C2": pd.Categorical(list("abaab"), categories=list("bac"), ordered=True), + } + ) + # single grouper + exp_full = pd.DataFrame( + { + "A": [2.0, 1.0, np.nan], + "B": [25.0, 20.0, np.nan], + "C1": pd.Categorical(list("bac"), categories=list("bac"), ordered=False), + "C2": pd.Categorical(list("bac"), categories=list("bac"), ordered=True), + } + ) + 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 = pd.Categorical(["first", "second", "third", "fourth"], ordered=True) + df = pd.DataFrame({"payload": [-1, -2, -1, -2], "col": c}) + g = df.groupby("payload") + result = getattr(g, func)() + expected = pd.DataFrame( + {"payload": [-2, -1], "col": pd.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 = pd.Series(np.random.default_rng(2).standard_normal(9)) + + codes = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]) + cats = pd.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 = pd.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 = pd.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 = pd.CategoricalIndex( + exp.index, categories=cats.categories, ordered=cats.ordered + ) + tm.assert_series_equal(result, exp) + + +def test_categorical_no_compress_string(): + cats = pd.Categorical( + ["a", "a", "a", "b", "b", "b", "c", "c", "c"], + categories=["a", "b", "c", "d"], + ordered=True, + ) + data = pd.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 = pd.DataFrame( + {"A": [None] * 3, "B": pd.Categorical(["train", "train", "test"])} + ) + result = df.groupby("A").first()["B"] + expected = pd.Series( + pd.Categorical([], categories=["test", "train"]), + index=pd.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 = pd.DataFrame({"value": np.random.default_rng(2).integers(0, 10000, 10)}) + labels = [f"{i} - {i + 499}" for i in range(0, 10000, 500)] + cat_labels = pd.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 = pd.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 = pd.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"] = pd.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 = pd.DataFrame( + data_values, + columns=["foo", "bar"], + index=pd.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 = pd.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"] = pd.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 = pd.DataFrame( + data_values, + columns=["foo", "bar"], + index=pd.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 = pd.DataFrame( + { + "A": pd.Categorical(["a", "a", "b"], categories=["a", "b", "c"]), + "B": [1, 2, 1], + } + ) + expected_idx = pd.CategoricalIndex(["a", "b", "c"], name="A") + + # 0 by default + result = df.groupby("A", observed=False).B.sum() + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame( + { + "A": pd.Categorical(["a", "a", "b"], categories=["a", "b", "c"]), + "B": [1, 2, 1], + } + ) + + expected_idx = pd.CategoricalIndex(["a", "b", "c"], name="A") + + # 1 by default + result = df.groupby("A", observed=False).B.prod() + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame( + { + "key1": pd.Categorical(list("abcbabcba")), + "key2": pd.Categorical( + list(pd.date_range("2018-06-01 00", freq="1min", periods=3)) * 3 + ), + "values": np.arange(9), + } + ) + result = df.groupby(["key1", "key2"], observed=False).mean() + + idx = pd.MultiIndex.from_product( + [ + pd.Categorical(["a", "b", "c"]), + pd.Categorical(pd.date_range("2018-06-01 00", freq="1min", periods=3)), + ], + names=["key1", "key2"], + ) + expected = pd.DataFrame({"values": [0, 4, 8, 3, 4, 5, 6, np.nan, 2]}, index=idx) + tm.assert_frame_equal(result, expected, check_freq=False) + + +@pytest.mark.parametrize( + "as_index, expected", + [ + ( + True, + pd.Series( + index=pd.MultiIndex.from_arrays( + [pd.Series([1, 1, 2], dtype="category"), [1, 2, 2]], + names=["a", "b"], + ), + data=[1, 2, 3], + name="x", + ), + ), + ( + False, + pd.DataFrame( + { + "a": pd.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 = pd.DataFrame( + {"a": pd.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 = pd.Categorical( + ["a", "b", "c", "d"], categories=["a", "b", "c", "d"], ordered=False + ) + expected = pd.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"] = pd.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 = pd.Index(["bar", "bar", "foo", "foo"], dtype=df_cat["A"].dtype, name="A") + lev_b = pd.Index(["one", "three", "one", "two"], dtype=df_cat["B"].dtype, name="B") + index = pd.MultiIndex.from_arrays([lev_a, lev_b]) + expected = pd.Series(data=[2, 4, 1, 3], index=index, name="C").sort_index() + + grouped = df_cat.groupby(["A", "B"], observed=True)["C"] + 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, _ = pd.MultiIndex.from_product( + [ + pd.CategoricalIndex(["bar", "foo"], ordered=False), + pd.CategoricalIndex(["one", "three", "two"], ordered=False), + ], + names=["A", "B"], + ).sortlevel() + + expected = pd.Series(data=[2, 4, 0, 1, 0, 3], index=index, name="C") + grouped = df_cat.groupby(["A", "B"], observed=observed)["C"] + result = getattr(grouped, operation)(sum) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "observed, index, data", + [ + ( + True, + pd.MultiIndex.from_arrays( + [ + pd.Index(["bar"] * 4 + ["foo"] * 4, dtype="category", name="A"), + pd.Index( + ["one", "one", "three", "three", "one", "one", "two", "two"], + dtype="category", + name="B", + ), + pd.Index(["min", "max"] * 4), + ] + ), + [2, 2, 4, 4, 1, 1, 3, 3], + ), + ( + False, + pd.MultiIndex.from_product( + [ + pd.CategoricalIndex(["bar", "foo"], ordered=False), + pd.CategoricalIndex(["one", "three", "two"], ordered=False), + pd.Index(["min", "max"]), + ], + names=["A", "B", None], + ), + [2, 2, 4, 4, np.nan, np.nan, 1, 1, np.nan, np.nan, 3, 3], + ), + ( + None, + pd.MultiIndex.from_product( + [ + pd.CategoricalIndex(["bar", "foo"], ordered=False), + pd.CategoricalIndex(["one", "three", "two"], ordered=False), + pd.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 = pd.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) + + +def test_groupby_cat_preserves_structure(observed, ordered): + # GH 28787 + df = pd.DataFrame( + {"Name": pd.Categorical(["Bob", "Greg"], ordered=ordered), "Item": [1, 2]}, + columns=["Name", "Item"], + ) + expected = df.copy() + + result = ( + df.groupby("Name", observed=observed) + .agg(pd.Series.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 = pd.DataFrame({"var": ["a", "a", "b", "b"], "val": range(4)}) + with pytest.raises(KeyError, match="'vau'"): + df.groupby("var").apply( + lambda rows: pd.DataFrame({"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 = pd.DataFrame( + { + "cat_1": pd.Categorical(list("AABB"), categories=list("ABCD")), + "cat_2": pd.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) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + agg(*args) + return + + 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.applymarker(mark) + + df = pd.DataFrame( + { + "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), + "cat_2": pd.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) + + if reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + agg(*args) + return + + result = agg(*args) + + missing_fillin = _results_for_groupbys_with_missing_categories[reduction_func] + + for idx in unobserved: + val = result.loc[idx] + assert (pd.isna(missing_fillin) and pd.isna(val)) or (val == missing_fillin) + + # 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 missing_fillin == 0: + if reduction_func in ["count", "nunique", "size"]: + assert np.issubdtype(result.dtype, np.integer) + else: + assert reduction_func in ["sum", "any"] + + +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 = pd.DataFrame( + { + "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), + "cat_2": pd.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) + if reduction_func == "corrwith": + warn = Pandas4Warning + warn_msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + warn_msg = "" + with tm.assert_produces_warning(warn, match=warn_msg): + 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, using_python_scalars +): + # 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 = pd.DataFrame( + { + "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), + "cat_2": pd.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) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + getattr(df_grp, reduction_func)(*args) + return + + if reduction_func == "corrwith": + warn = Pandas4Warning + warn_msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + warn_msg = "" + with tm.assert_produces_warning(warn, match=warn_msg): + res = getattr(df_grp, reduction_func)(*args) + + expected = _results_for_groupbys_with_missing_categories[reduction_func] + + if using_python_scalars and reduction_func == "size": + assert (res.loc[unobserved_cats] == expected).all() is True + elif 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 = pd.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", + [(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])], +) +def test_groupby_agg_categorical_columns(func, expected_values): + # 31256 + df = pd.DataFrame( + { + "id": [0, 1, 2, 3, 4], + "groups": [0, 1, 1, 2, 2], + "value": pd.Categorical([0, 0, 0, 0, 1]), + } + ).set_index("id") + result = df.groupby("groups").agg(func) + + expected = pd.DataFrame( + {"value": expected_values}, index=pd.Index([0, 1, 2], name="groups") + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_non_numeric(): + df = pd.DataFrame( + {"A": pd.Categorical(["a", "a", "b"], categories=["a", "b", "c"])} + ) + expected = pd.DataFrame({"A": [2, 1]}, index=np.array([1, 2])) + + result = df.groupby([1, 2, 1]).agg(pd.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 = pd.DataFrame( + {"A": [1997], "B": pd.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 = pd.Series( + ["b"], index=pd.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 = pd.DataFrame( + { + "a": [1, 3, 5, 7], + "b": pd.Categorical([1, 1, 2, 2], categories=pd.Index(cats)), + } + ) + expected = pd.DataFrame( + data={"a": [2.0, 6.0]}, index=pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.Series( + [1, 2, 3], + index=pd.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 = pd.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 = pd.MultiIndex.from_arrays([[1, 1], [1, 2]], names=("A", "B")) + expected = pd.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 = pd.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) + df["last_status"] = df.groupby("package_id")["status"].transform(max) + result = df.copy() + + expected = pd.DataFrame( + { + "package_id": [1, 1, 1, 2, 2, 3], + "status": [ + "Waiting", + "OnTheWay", + "Delivered", + "Waiting", + "OnTheWay", + "Waiting", + ], + "last_status": [ + "Waiting", + "Waiting", + "Waiting", + "Waiting", + "Waiting", + "Waiting", + ], + } + ) + + expected["status"] = expected["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 = pd.Categorical([0, 0, 1, 1]) + val = [0, 1, 1, 0] + df = pd.DataFrame({"a": cat, "b": cat, "c": val}) + + cat2 = pd.Categorical([0, 1]) + idx = pd.MultiIndex.from_product([cat2, cat2], names=["a", "b"]) + expected_dict = { + "first": pd.Series([0, np.nan, np.nan, 1], idx, name="c"), + "last": pd.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 = pd.Categorical([0, 0, 1, 1]) + val = [0, 1, 1, 0] + df = pd.DataFrame({"a": cat, "b": cat, "c": val}) + + cat2 = pd.Categorical([0, 1]) + idx = pd.MultiIndex.from_product([cat2, cat2], names=["a", "b"]) + expected_dict = { + "first": pd.Series([0, np.nan, np.nan, 1], idx, name="c"), + "last": pd.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 = pd.DataFrame( + { + "key": pd.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]) + + +def test_groupby_categorical_indices_sort_false_multi_key(): + # GH#66893 + cats = ["low", "mid"] + df = pd.DataFrame( + { + "x": [0, 0, 1, 1, 2, 2], + "g": pd.Categorical(["mid", "low"] * 3, categories=cats, ordered=True), + } + ) + gb = df.groupby(["x", "g"], sort=False, observed=False) + + result = gb.indices + expected = { + (0, "mid"): np.array([0], dtype="intp"), + (0, "low"): np.array([1], dtype="intp"), + (1, "mid"): np.array([2], dtype="intp"), + (1, "low"): np.array([3], dtype="intp"), + (2, "mid"): np.array([4], dtype="intp"), + (2, "low"): np.array([5], dtype="intp"), + } + assert result.keys() == expected.keys() + for key in result.keys(): + tm.assert_numpy_array_equal(result[key], expected[key]) + + +def test_groupby_categorical_get_group_sort_false_multi_key(): + # GH#66893 + cats = ["low", "mid"] + df = pd.DataFrame( + { + "x": [0, 0, 1, 1, 2, 2], + "g": pd.Categorical(["mid", "low"] * 3, categories=cats, ordered=True), + } + ) + gb = df.groupby(["x", "g"], sort=False, observed=False) + + result = gb.get_group((1, "mid")) + expected = df.iloc[[2]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_groupby_last_first_preserve_categoricaldtype(func): + # GH#33090 + df = pd.DataFrame({"a": [1, 2, 3]}) + df["b"] = df["a"].astype("category") + result = getattr(df.groupby("a")["b"], func)() + expected = pd.Series( + pd.Categorical([1, 2, 3]), name="b", index=pd.Index([1, 2, 3], name="a") + ) + tm.assert_series_equal(expected, result) + + +def test_groupby_categorical_observed_nunique(): + # GH#45128 + df = pd.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 = pd.Series( + [1, 1], + index=pd.MultiIndex.from_arrays( + [ + pd.CategoricalIndex([1, 2], name="a"), + pd.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 = pd.DataFrame( + [[1, "small"], [1, "big"], [2, "small"]], columns=["grp", "description"] + ).astype({"description": dtype}) + + result = df.groupby("grp")["description"].max() + expected = pd.Series( + ["big", "small"], + index=pd.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 = pd.Categorical([1, 2], categories=[1, 2, 3]) + df = pd.DataFrame({"x": pd.Categorical([1, 2], categories=[1, 2, 3]), "y": [3, 4]}) + gb = df.groupby("x", observed=observed, dropna=dropna) + result = gb.sum() + + if observed: + expected = pd.DataFrame({"y": [3, 4]}, index=cat) + else: + index = pd.CategoricalIndex([1, 2, 3], [1, 2, 3]) + expected = pd.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 == "corrwith" and not as_index and index_kind != "single": + msg = "GH#49950 - corrwith with as_index=False may not have grouping column" + request.applymarker(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 = pd.DataFrame( + { + "a": pd.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) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + getattr(gb, reduction_func)(*args) + return + if reduction_func == "corrwith": + warn = Pandas4Warning + warn_msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + warn_msg = "" + with tm.assert_produces_warning(warn, match=warn_msg): + 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 = pd.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 = pd.DataFrame( + { + "a": pd.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 = pd.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 = pd.DataFrame( + { + "a": pd.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 = pd.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 = pd.DataFrame( + { + "a": pd.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 = pd.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 = pd.Categorical([2, 1, 2, 3], categories=categories, ordered=ordered) + df = pd.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 = pd.CategoricalIndex( + data, categories=grouper.categories, ordered=ordered, name="a" + ) + if as_index: + expected = pd.DataFrame({"b": data}) + if index_kind == "multi": + expected.index = pd.MultiIndex.from_frame( + pd.DataFrame({"a": index, "a2": index}) + ) + else: + expected.index = index + elif index_kind == "multi": + expected = pd.DataFrame( + {"a": pd.Series(index), "a2": pd.Series(index), "b": data} + ) + else: + expected = pd.DataFrame({"a": pd.Series(index), "b": data}) + + tm.assert_frame_equal(result, expected) + + +@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.applymarker(pytest.mark.xfail(reason=msg)) + + df = pd.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) + + if not observed and reduction_func in ["idxmin", "idxmax"] and keys == ["a1", "a2"]: + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + gb.agg([reduction_func], *args) + return + + 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 = pd.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) + + +def test_categorical_with_noncategorical_na(observed, sort): + # https://github.com/pandas-dev/pandas/issues/63920 + df = pd.DataFrame( + { + "dates": list("YXXYY"), + "sector": pd.Categorical( + [2, 1, 2, 1, np.nan], categories=[1, 2, 3], ordered=True + ), + "metric": [1, 2, 3, 4, 5], + } + ) + gb = df.groupby(["dates", "sector"], observed=observed, sort=sort) + # Only testing the ids/result_index, okay to just use one kernel + result = gb.sum() + + if sort and observed: + taker = [0, 1, 2, 3] + elif not sort and observed: + taker = [3, 0, 1, 2] + elif sort and not observed: + taker = [0, 1, 4, 2, 3, 5] + elif not sort and not observed: + taker = [3, 0, 1, 2, 5, 4] + expected = ( + pd.DataFrame( + { + "dates": list("XXYYXY"), + "sector": pd.Categorical( + [1, 2, 1, 2, 3, 3], categories=[1, 2, 3], ordered=True + ), + "metric": [2, 3, 4, 1, 0, 0], + } + ) + .set_index(["dates", "sector"]) + .take(taker) + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_observed_false_expands_only_categorical_levels(): + # GH#24592 with observed=False only categorical groupers are expanded to + # all their categories; non-categorical levels keep only observed values + df = pd.DataFrame( + { + "L0": [1, 1, 2], + "L1": ["a", "b", "a"], + "L2": pd.Categorical(["X", "X", "X"], categories=["X", "Y"]), + } + ) + result = df.groupby(["L0", "L1", "L2"], observed=False).size() + # observed (L0, L1) pairs are (1, a), (1, b), (2, a); each is crossed with + # the two L2 categories -- crucially (2, b) is absent (never observed) + assert result.index.tolist() == [ + (1, "a", "X"), + (1, "a", "Y"), + (1, "b", "X"), + (1, "b", "Y"), + (2, "a", "X"), + (2, "a", "Y"), + ] + assert result.tolist() == [1, 0, 1, 0, 1, 0] + + +def test_categorical_with_noncategorical_na_dropna_sort(): + # GH#68931 dropping NA keys left the group ids negative, which sort=True + # then used to index + df = pd.DataFrame( + { + "dates": ["X", None], + "sector": pd.Categorical([1, np.nan], categories=[1, 2, 3]), + "metric": [10, 20], + } + ) + result = df.groupby(["dates", "sector"], observed=False).sum() + expected = pd.DataFrame( + { + "dates": ["X"] * 3, + "sector": pd.Categorical([1, 2, 3], categories=[1, 2, 3]), + "metric": [10, 0, 0], + } + ).set_index(["dates", "sector"]) + tm.assert_frame_equal(result, expected) + + +def test_categorical_with_noncategorical_na_dropna_no_sort(): + # GH#68931 the same bad ids, which sort=False instead folded into the + # observed groups, duplicating ("X", 3) in the result + df = pd.DataFrame( + { + "dates": [None, None, "X"], + "sector": pd.Categorical([2, 3, 3], categories=[1, 2, 3, 4]), + "metric": [10, 20, 30], + } + ) + result = df.groupby(["dates", "sector"], observed=False, sort=False).sum() + expected = pd.DataFrame( + { + # observed group first, then the unobserved categories in order + # of appearance + "dates": ["X"] * 4, + "sector": pd.Categorical([3, 2, 1, 4], categories=[1, 2, 3, 4]), + "metric": [30, 0, 0, 0], + } + ).set_index(["dates", "sector"]) + tm.assert_frame_equal(result, expected) + + +def test_categorical_with_noncategorical_all_na_dropna(sort): + # GH#68931 every row has an NA key, so no group survives dropna=True + df = pd.DataFrame( + { + "dates": [None, None], + "sector": pd.Categorical([1, np.nan], categories=[1, 2, 3]), + "metric": [10, 20], + } + ) + result = df.groupby(["dates", "sector"], observed=False, sort=sort).sum() + expected = pd.DataFrame( + { + "dates": pd.Index([], dtype=object), + "sector": pd.Categorical([], categories=[1, 2, 3]), + "metric": pd.Index([], dtype="int64"), + } + ).set_index(["dates", "sector"]) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_counting.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_counting.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8cbce58518e2b11dc3903839cfba1b2e1b1f24 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_counting.py @@ -0,0 +1,385 @@ +from itertools import product +from string import ascii_lowercase + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestCounting: + def test_cumcount(self): + df = pd.DataFrame([["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"]) + g = df.groupby("A") + sg = g.A + + expected = pd.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 = pd.DataFrame().groupby(level=0) + se = pd.Series(dtype=object).groupby(level=0) + + # edge case, as this is usually considered float + e = pd.Series(dtype="int64") + + tm.assert_series_equal(e, ge.cumcount()) + tm.assert_series_equal(e, se.cumcount()) + + def test_cumcount_dupe_index(self): + df = pd.DataFrame( + [["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=[0] * 5 + ) + g = df.groupby("A") + sg = g.A + + expected = pd.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 = pd.MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]]) + df = pd.DataFrame([["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=mi) + g = df.groupby("A") + sg = g.A + + expected = pd.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 = pd.DataFrame( + [["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=[0] * 5 + ) + g = df.groupby([0, 0, 0, 1, 0]) + sg = g.A + + expected = pd.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 = pd.DataFrame({"A": list("aaaba")}) + g = df.groupby("A") + sg = g.A + + expected = pd.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 = pd.DataFrame({"A": list("abcde")}) + g = df.groupby("A") + sg = g.A + + expected = pd.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 = pd.DataFrame({"A": [0] * 5}) + g = df.groupby("A") + sg = g.A + + expected = pd.Series([0] * 5) + + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) + + def test_ngroup_empty(self): + ge = pd.DataFrame().groupby(level=0) + se = pd.Series(dtype=object).groupby(level=0) + + # edge case, as this is usually considered float + e = pd.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 = pd.DataFrame({"A": list("aaaba")}) + s = pd.Series(list("aaaba")) + + tm.assert_series_equal(df.groupby(s).ngroup(), s.groupby(s).ngroup()) + + def test_ngroup_dupe_index(self): + df = pd.DataFrame({"A": list("aaaba")}, index=[0] * 5) + g = df.groupby("A") + sg = g.A + + expected = pd.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 = pd.MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]]) + df = pd.DataFrame({"A": list("aaaba")}, index=mi) + g = df.groupby("A") + sg = g.A + expected = pd.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 = pd.DataFrame({"A": list("aaaba")}, index=[0] * 5) + g = df.groupby([0, 0, 0, 1, 0]) + sg = g.A + + expected = pd.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 = pd.DataFrame(["a", "a", "b", "a", "b"], columns=["A"]) + g = df.groupby(["A"]) + + ascending = pd.Series([0, 0, 1, 0, 1]) + descending = pd.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 = pd.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 = pd.Series([0, 1, 2, 0, 3]) + expected_cumcount = pd.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 = pd.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(), pd.Series(ngroupd)) + tm.assert_series_equal(g.cumcount(), pd.Series(cumcounted)) + + def test_ngroup_respects_groupby_order(self, sort): + df = pd.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(pd.Series(df["group_id"].values), g.ngroup()) + tm.assert_series_equal(pd.Series(df["group_index"].values), g.cumcount()) + + @pytest.mark.parametrize( + "datetimelike", + [ + [pd.Timestamp(f"2016-05-{i:02d} 20:09:25+00:00") for i in range(1, 4)], + [pd.Timestamp(f"2016-05-{i:02d} 20:09:25") for i in range(1, 4)], + [pd.Timestamp(f"2016-05-{i:02d} 20:09:25", tz="UTC") for i in range(1, 4)], + [pd.Timedelta(x, unit="h") for x in range(1, 4)], + [pd.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 = pd.DataFrame({"x": ["a", "a", "b"], "y": datetimelike}) + res = df.groupby("x").count() + expected = pd.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 = pd.DataFrame({"A": [np.nan, np.nan], "B": ["a", "b"], "C": [1, 2]}) + result = df.groupby(["A", "B"]).C.count() + mi = pd.MultiIndex(levels=[[], ["a", "b"]], codes=[[], []], names=["A", "B"]) + expected = pd.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 = pd.DataFrame({"A": [1, 1, 1, 1, 1], "B": [5, 4, np.nan, 3, 0]}) + res = df.groupby(["B"]).count() + expected = pd.DataFrame( + index=pd.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 = pd.date_range(start="1/1/2012", freq="5min", periods=10) + + # BAD Example, datetimes first + ser = pd.Series(np.arange(10), index=[dr, np.arange(10)]) + grouped = ser.groupby(lambda x: x[1] % 2 == 0) + result = grouped.count() + + ser = pd.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 = pd.DataFrame( + {"g": list("ab" * 2), "delta": np.arange(4).astype("timedelta64[ns]")} + ) + expected = pd.Series([2, 2], index=pd.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 = pd.date_range("2015-08-30", periods=n // 10, freq="min") + + df = pd.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(pd.DataFrame.count) + tm.assert_frame_equal(left, right) + + +def test_count_non_nulls(): + # GH#5610 + # count counts non-nulls + df = pd.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 = pd.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 = pd.DataFrame({"a": ["a"] * 3 + ["b"] * 3, "c": [2] * 3 + [3] * 3}) + result = df.groupby("c").a.count() + expected = pd.Series([3, 3], index=pd.Index([2, 3], name="c"), name="a") + tm.assert_series_equal(result, expected) + + +def test_count_object_nan(): + df = pd.DataFrame({"a": ["a", np.nan, np.nan] + ["b"] * 3, "c": [2] * 3 + [3] * 3}) + result = df.groupby("c").a.count() + expected = pd.Series([1, 3], index=pd.Index([2, 3], name="c"), name="a") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("typ", ["object", "float32"]) +def test_count_cross_type(typ): + # GH8169 + # Set float64 dtype to avoid upcast when setting nan below + vals = np.hstack( + ( + np.random.default_rng(2).integers(0, 5, (10, 2)), + np.random.default_rng(2).integers(0, 2, (10, 2)), + ) + ).astype("float64") + + df = pd.DataFrame(vals, columns=["a", "b", "c", "d"]) + df[df == 2] = np.nan + expected = df.groupby(["c", "d"]).count() + + df["a"] = df["a"].astype(typ) + df["b"] = df["b"].astype(typ) + result = df.groupby(["c", "d"]).count() + tm.assert_frame_equal(result, expected) + + +def test_lower_int_prec_count(): + df = pd.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 = pd.DataFrame( + {"a": [2, 2], "b": [2, 2], "c": [2, 2]}, index=pd.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 = pd.DataFrame({"a": [RaisingObject() for _ in range(4)], "grp": list("ab" * 2)}) + result = df.groupby("grp").count() + expected = pd.DataFrame({"a": [2, 2]}, index=pd.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 = pd.DataFrame( + {"a": [1, 2, 3], "b": pd.Series(["a", "b", "a"], dtype=any_string_dtype)} + ) + result = df.groupby("a").count() + expected = pd.DataFrame({"b": 1}, index=pd.Index([1, 2, 3], name="a")) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_cumulative.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_cumulative.py new file mode 100644 index 0000000000000000000000000000000000000000..1b8d4a143f189fe9a6033a74ec31ccb0cecdf8d3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_cumulative.py @@ -0,0 +1,411 @@ +import numpy as np +import pytest + +from pandas.errors import ( + Pandas4Warning, + UnsupportedFunctionCall, +) +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +@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_groupby_cumprod(): + # GH 4095 + df = pd.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 = pd.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 = pd.DataFrame({"key": ["b"] * 4, "value": 100_000}) + actual = df.groupby("key")["value"].cumprod() + expected = pd.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 = pd.DataFrame( + { + "a": 1, + "b": [1, np.nan, 2], + "c": [1, 2, 3.0], + } + ) + result = df.groupby("a").cumprod(numeric_only=True, skipna=False) + expected = pd.DataFrame({"b": [1, np.nan, np.nan], "c": [1, 2, 6.0]}) + tm.assert_frame_equal(result, expected) + + +def test_cummin(dtypes_for_minmax): + dtype = dtypes_for_minmax[0] + + # GH 15048 + base_df = pd.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 = pd.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) + + +def test_cummin_min_value_for_dtype(dtypes_for_minmax): + dtype = dtypes_for_minmax[0] + min_val = dtypes_for_minmax[1] + + # GH 15048 + base_df = pd.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] + expected = pd.DataFrame({"B": expected_mins}).astype(dtype) + df = base_df.astype(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) + + +def test_cummin_nan_in_some_values(dtypes_for_minmax): + # Explicit cast to float to avoid implicit cast when setting nan + base_df = pd.DataFrame( + {"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]} + ) + base_df = base_df.astype({"B": "float"}) + base_df.loc[[0, 2, 4, 6], "B"] = np.nan + expected = pd.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) + + +def test_cummin_datetime(): + # GH 15561 + df = pd.DataFrame({"a": [1], "b": pd.to_datetime(["2001"])}) + expected = pd.Series(pd.to_datetime("2001"), index=[0], name="b") + + result = df.groupby("a")["b"].cummin() + tm.assert_series_equal(expected, result) + + +def test_cummin_getattr_series(): + # GH 15635 + df = pd.DataFrame({"a": [1, 2, 1], "b": [1, 2, 2]}) + result = df.groupby("a").b.cummin() + expected = pd.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): + item = np.nan if dtype == "float" else pd.NA + base_df = pd.DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [item] * 8}) + base_df["B"] = base_df["B"].astype(dtype) + grouped = base_df.groupby("A") + + expected = pd.DataFrame({"B": [item] * 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] + + # GH 15048 + base_df = pd.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 = pd.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) + + +def test_cummax_min_value_for_dtype(dtypes_for_minmax): + dtype = dtypes_for_minmax[0] + max_val = dtypes_for_minmax[2] + + # GH 15048 + base_df = pd.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) + df.loc[[2, 6], "B"] = max_val + expected = pd.DataFrame({"B": expected_maxs}).astype(dtype) + 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) + + +def test_cummax_nan_in_some_values(dtypes_for_minmax): + # Test nan in some values + # Explicit cast to float to avoid implicit cast when setting nan + base_df = pd.DataFrame( + {"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]} + ) + base_df = base_df.astype({"B": "float"}) + base_df.loc[[0, 2, 4, 6], "B"] = np.nan + expected = pd.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) + + +def test_cummax_datetime(): + # GH 15561 + df = pd.DataFrame({"a": [1], "b": pd.to_datetime(["2001"])}) + expected = pd.Series(pd.to_datetime("2001"), index=[0], name="b") + + result = df.groupby("a")["b"].cummax() + tm.assert_series_equal(expected, result) + + +def test_cummax_getattr_series(): + # GH 15635 + df = pd.DataFrame({"a": [1, 2, 1], "b": [2, 1, 1]}) + result = df.groupby("a").b.cummax() + expected = pd.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 = pd.Series([pd.NaT._value + n for n in range(5)]) + df = pd.DataFrame({"A": 1, "B": ser, "C": ser._values.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 = pd.DataFrame({"a": pd.Series([1, None, 2], dtype=dtype)}) + orig = df.copy() + gb = df.groupby(groups)["a"] + + result = getattr(gb, method)(skipna=False) + expected = pd.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 = pd.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 = pd.DataFrame({"a": [np.nan, np.nan, np.nan], "b": [2.0, 2.0, 2.0]}) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["cumprod", "cumsum"]) +def test_numpy_compat(func): + # see gh-12811 + df = pd.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) + + +@pytest.mark.parametrize("func", ["cummin", "cummax"]) +def test_kwargs_deprecated(func): + # GH#50407 + df = pd.DataFrame({"A": [1, 2, 1], "B": [1, 2, 3]}) + gb = df.groupby("A") + + msg = "Passing additional arguments to GroupBy" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(gb, func)(foo=1) + + +@pytest.mark.parametrize( + "klass,msg", + [ + ("SeriesGroupBy", "Passing additional arguments to SeriesGroupBy.take"), + ("DataFrameGroupBy", "Passing additional arguments to DataFrameGroupBy.take"), + ], +) +def test_take_kwargs_deprecated(klass, msg): + # GH#50407 + df = pd.DataFrame({"a": [1, 1, 2], "b": [1, 2, 3]}) + if klass == "SeriesGroupBy": + gb = df.groupby("a")["b"] + else: + gb = df.groupby("a") + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + with pytest.raises(TypeError, match="got an unexpected keyword argument"): + gb.take([0], foo=1) + + +@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 = pd.DataFrame({"grp": [1, 1], "b": data}, dtype=dtype) + grouped = df.groupby("grp") + + result = grouped.transform(method) + expected = pd.DataFrame({"b": data}, dtype=dtype) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "method,expected_values", + [ + ("cumprod", [2, pd.NA, 8]), + ("cummin", [2, pd.NA, 2]), + ("cummax", [2, pd.NA, 4]), + ], +) +def test_nullable_int_dtype_preserved_with_na_group_key(method, expected_values): + # GH#65550 + df = pd.DataFrame( + {"key": ["a", None, "a"], "val": pd.Series([2, 3, 4], dtype="Int64")} + ) + gb = df.groupby("key")["val"] + + result = getattr(gb, method)() + expected = pd.Series(expected_values, dtype="Int64", name="val") + tm.assert_series_equal(result, expected) + + +def test_cumprod_nullable_int_no_precision_loss_with_na_group_key(): + # GH#65550 + df = pd.DataFrame( + { + "key": ["a", pd.NA], + "val": pd.array([9007199254740993, 0], dtype="Int64"), + } + ) + gb = df.groupby("key")["val"] + + result = gb.cumprod() + expected = pd.Series([9007199254740993, pd.NA], dtype="Int64", name="val") + tm.assert_series_equal(result, expected) + + +def test_cython_api2(as_index): + # this takes the fast apply path + + # cumsum (GH5614) + # GH 5755 - cumsum is a transformer and should ignore as_index + df = pd.DataFrame( + [[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=["A", "B", "C"] + ) + expected = pd.DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=["B", "C"]) + result = df.groupby("A", as_index=as_index).cumsum() + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_filters.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8ac21bc3597e7647012411003bd2cb828649fe --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_filters.py @@ -0,0 +1,643 @@ +from string import ascii_lowercase + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_filter_series(): + s = pd.Series([1, 3, 20, 5, 22, 24, 7]) + expected_odd = pd.Series([1, 3, 5, 7], index=[0, 1, 3, 6]) + expected_even = pd.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 = pd.DataFrame([1, 3, 20, 5, 22, 24, 7]) + expected_odd = pd.DataFrame([1, 3, 5, 7], index=[0, 1, 3, 6]) + expected_even = pd.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 = pd.DataFrame({"A": [1, 12, 12, 1], "B": [1, 1, 1, 1]}) + grouper = df["A"].apply(lambda x: x % 2) + grouped = df.groupby(grouper) + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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) + + +def test_filter_out_no_groups_dataframe(): + df = pd.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 = pd.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 = pd.DataFrame({"a": [np.nan] * 3, "b": [np.nan] * 3}) + tm.assert_frame_equal(expected, res) + + +def test_filter_out_all_groups_in_df_dropna_true(): + # GH12768 + df = pd.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 = pd.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 = pd.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_bad_shapes(): + df = pd.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 = pd.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 = pd.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_ints(): + # Series of ints + s = pd.Series(np.random.default_rng(2).integers(0, 100, 10)) + 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()) + + +def test_filter_against_workaround_floats(): + # Series of floats + s = 100 * pd.Series(np.random.default_rng(2).random(10)) + 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()) + + +def test_filter_against_workaround_dataframe(): + # Set up DataFrame of ints, floats, strings. + letters = np.array(list(ascii_lowercase)) + N = 10 + random_letters = letters.take( + np.random.default_rng(2).integers(0, 26, N, dtype=int) + ) + df = pd.DataFrame( + { + "ints": pd.Series(np.random.default_rng(2).integers(0, 10, N)), + "floats": N / 10 * pd.Series(np.random.default_rng(2).random(N)), + "letters": pd.Series(random_letters), + } + ) + + # Group by ints; filter on floats. + grouped = df.groupby("ints") + old_way = df[grouped.floats.transform(lambda x: x.mean() > N / 2).astype("bool")] + new_way = grouped.filter(lambda x: x["floats"].mean() > N / 2) + 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 / 2).astype("bool")] + new_way = grouped.filter(lambda x: len(x.letters) < N / 2) + 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 / 2).astype("bool")] + new_way = grouped.filter(lambda x: x["ints"].mean() > N / 2) + tm.assert_frame_equal(new_way, old_way) + + +def test_filter_using_len(): + # GH 4447 + df = pd.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 = pd.DataFrame( + {"A": np.arange(2, 6), "B": list("bbbb"), "C": np.arange(2, 6)}, + index=range(2, 6), + ) + tm.assert_frame_equal(actual, expected) + + actual = grouped.filter(lambda x: len(x) > 4) + expected = df.loc[[]] + tm.assert_frame_equal(actual, expected) + + +def test_filter_using_len_series(): + # GH 4447 + s = pd.Series(list("aabbbbcc"), name="B") + grouped = s.groupby(s) + actual = grouped.filter(lambda x: len(x) > 2) + expected = pd.Series(4 * ["b"], index=range(2, 6), name="B") + tm.assert_series_equal(actual, expected) + + actual = grouped.filter(lambda x: len(x) > 4) + expected = s[[]] + tm.assert_series_equal(actual, expected) + + +@pytest.mark.parametrize( + "index", [range(8), range(7, -1, -1), [0, 2, 1, 3, 4, 6, 5, 7]] +) +def test_filter_maintains_ordering(index): + # GH 4621 + df = pd.DataFrame( + {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]}, + index=index, + ) + 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 = pd.DataFrame( + { + "A": np.arange(5, dtype="int64"), + "B": ["foo", "bar", "foo", "bar", "bar"], + "C": pd.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 = pd.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 = pd.DataFrame({"A": [2, 8, 2, 8, 8]}) + tm.assert_frame_equal(result, expected) + + result = grouped.transform(len) + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.Timestamp("2013-09-30 00:05:00") + t1 = pd.Timestamp("2013-10-30 00:05:00") + t2 = pd.Timestamp("2013-11-30 00:05:00") + index = [t1, t1, t1, t2, t1, t1, t0, t1] + df = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame([[1, 2], [1, 3], [5, 6]], columns=["A", "B"]) + g = df.groupby("A") + # previously didn't have access to col A GH#6512 + filt = g.filter(lambda x: x["A"].sum() == 2) + tm.assert_frame_equal(filt, df.iloc[[0, 1]]) + + +def test_filter_enforces_scalarness(): + df = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame({"data": range(6), "key": list("ABCABC")}) + grouper = df.groupby("key") + result = grouper.filter(lambda x: True) + expected = pd.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) + + +def test_filter_with_non_values(): + # GH 62501 + df = pd.DataFrame( + [ + [1], + [None], + ], + columns=["a"], + ) + + result = df.groupby("a", dropna=False).filter(lambda x: True) + tm.assert_frame_equal(result, df) + + +def test_filter_with_non_values_multi_index(): + # GH 62501 + df = pd.DataFrame( + [ + [1, 2], + [3, None], + [None, 4], + [None, None], + ], + columns=["a", "b"], + ) + + result = df.groupby(["a", "b"], dropna=False).filter(lambda x: True) + tm.assert_frame_equal(result, df) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_groupby.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_groupby.py new file mode 100644 index 0000000000000000000000000000000000000000..deb70dcc1d24a17ab8a046b5626946f7be5eb069 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_groupby.py @@ -0,0 +1,3061 @@ +from datetime import datetime +import decimal +from decimal import Decimal +import re + +import numpy as np +import pytest + +from pandas.errors import ( + Pandas4Warning, + SpecificationError, +) + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import BooleanArray +import pandas.core.common as com + + +def test_repr(): + # GH18203 + result = repr(pd.Grouper(key="A", level="B")) + expected = "Grouper(key='A', level='B', sort=False, dropna=True)" + assert result == expected + + +def test_groupby_nonobject_dtype(multiindex_dataframe_random_data): + key = multiindex_dataframe_random_data.index.codes[0] + grouped = multiindex_dataframe_random_data.groupby(key) + result = grouped.sum() + + expected = multiindex_dataframe_random_data.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) + + +def test_groupby_nonobject_dtype_mixed(): + # GH 3911, mixed frame non-conversion + df = pd.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"), + } + ) + 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.drop(columns="A").dtypes + tm.assert_series_equal(result, expected) + + +def test_groupby_masked_array_column_values_type_consistent(): + # GH#65458 a MaskedArray column is normalized on assignment, so every + # group has ndarray values regardless of how the rows are split + df = pd.DataFrame({"y": ["a", "a", "b"]}) + df["x"] = np.ma.array([0.1, 0.2, 0.3]) + + for _, group in df.groupby("y"): + assert type(group["x"].values) is np.ndarray + + +def test_pass_args_kwargs(ts): + 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) + + +def test_pass_args_kwargs_dataframe(tsframe, as_index): + def f(x, q=None, axis=0): + return np.percentile(x, q, axis=axis) + + df_grouped = tsframe.groupby(lambda x: x.month, as_index=as_index) + agg_result = df_grouped.agg(np.percentile, 80, axis=0) + apply_result = df_grouped.apply(pd.DataFrame.quantile, 0.8) + 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(pd.DataFrame.quantile, [0.4, 0.8]) + expected_seq = df_grouped.quantile([0.4, 0.8]) + if not as_index: + # apply treats the op as a transform; .quantile knows it's a reduction + apply_result.index = range(4) + apply_result.insert(loc=0, column="level_0", value=[1, 1, 2, 2]) + apply_result.insert(loc=1, column="level_1", value=[0.4, 0.8, 0.4, 0.8]) + tm.assert_frame_equal(apply_result, expected_seq, check_names=False) + + agg_result = df_grouped.agg(f, q=80) + apply_result = df_grouped.apply(pd.DataFrame.quantile, q=0.8) + tm.assert_frame_equal(agg_result, expected) + tm.assert_frame_equal(apply_result, expected, check_names=False) + + +def test_len(): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ) + 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 + + +def test_len_nan_group(): + # issue 11016 + df = pd.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"])) == 0 + + +def test_groupby_timedelta_median(): + # issue 57926 + expected = pd.Series(data=pd.Timedelta("1D"), index=["foo"], dtype="m8[us]") + df = pd.DataFrame( + {"label": ["foo", "foo"], "timedelta": [pd.NaT, pd.Timedelta("1D")]} + ) + gb = df.groupby("label")["timedelta"] + actual = gb.median() + tm.assert_series_equal(actual, expected, check_names=False) + + +@pytest.mark.parametrize("keys", [["a"], ["a", "b"]]) +def test_len_categorical(dropna, observed, keys): + # GH#57595 + df = pd.DataFrame( + { + "a": pd.Categorical([1, 1, 2, np.nan], categories=[1, 2, 3]), + "b": pd.Categorical([1, 1, 2, np.nan], categories=[1, 2, 3]), + "c": 1, + } + ) + gb = df.groupby(keys, observed=observed, dropna=dropna) + result = len(gb) + if observed and dropna: + expected = 2 + elif observed and not dropna: + expected = 3 + elif len(keys) == 1: + expected = 3 if dropna else 4 + else: + expected = 9 if dropna else 16 + assert result == expected, f"{result} vs {expected}" + + +def test_basic_regression(): + # regression + result = pd.Series([1.0 * x for x in list(range(1, 10)) * 10]) + + data = np.random.default_rng(2).random(1100) * 10.0 + groupings = pd.Series(data) + + grouped = result.groupby(groupings) + grouped.mean() + + +def test_indices_concatenation_order(): + # GH 2808 + + def f1(x): + y = x[(x.b % 2) == 1] ** 2 + if y.empty: + multiindex = pd.MultiIndex( + levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"] + ) + res = pd.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 pd.DataFrame() + else: + y = y.set_index(["b", "c"]) + return y + + def f3(x): + y = x[(x.b % 2) == 1] ** 2 + if y.empty: + multiindex = pd.MultiIndex( + levels=[[]] * 2, codes=[[]] * 2, names=["foo", "bar"] + ) + res = pd.DataFrame(columns=["a", "b"], index=multiindex) + return res + else: + return y + + df = pd.DataFrame({"a": [1, 2, 2, 2], "b": range(4), "c": range(5, 9)}) + + df2 = pd.DataFrame({"a": [3, 2, 2, 2], "b": range(4), "c": range(5, 9)}) + + # 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(ValueError, match=msg): + df.groupby("a").apply(f2) + with pytest.raises(ValueError, match=msg): + df2.groupby("a").apply(f2) + + # should fail (incorrect shape) + with pytest.raises(ValueError, match=msg): + df.groupby("a").apply(f3) + with pytest.raises(ValueError, match=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 = pd.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): + 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_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 = pd.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 = pd.DataFrame({"mean": grouped.agg("mean"), "std": grouped.agg("std")}) + tm.assert_frame_equal(agged, expected) + + +def test_frame_multi_key_function_list(): + data = pd.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, pd.MultiIndex) + assert isinstance(expected.index, pd.MultiIndex) + tm.assert_frame_equal(agged, expected) + + +def test_frame_multi_key_function_list_partial_failure(using_infer_string): + data = pd.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->") + if using_infer_string: + msg = "dtype 'str' does not support operation 'mean'" + 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 = pd.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 = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"]) + result = df.groupby("A", as_index=False)["B"].get_group(1) + expected = pd.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 = pd.Series([2, 6, 6], name="B", index=range(3)) + tm.assert_series_equal(result, expected) + + +def test_groupby_as_index_select_column_sum_empty_df(): + # GH 35246 + df = pd.DataFrame(columns=pd.Index(["A", "B", "C"], name="alpha")) + left = df.groupby(by="A", as_index=False)["B"].sum(numeric_only=False) + + expected = pd.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_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 = pd.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, pd.DataFrame) + tm.assert_frame_equal(result, expected) + + result2 = grouped2["C"].agg("sum") + expected2 = grouped2.agg("sum").loc[:, ["A", "B", "C"]] + assert isinstance(result2, pd.DataFrame) + tm.assert_frame_equal(result2, expected2) + + result = grouped["C"].sum() + expected = grouped.sum().loc[:, ["A", "C"]] + assert isinstance(result, pd.DataFrame) + tm.assert_frame_equal(result, expected) + + result2 = grouped2["C"].sum() + expected2 = grouped2.sum().loc[:, ["A", "B", "C"]] + assert isinstance(result2, pd.DataFrame) + tm.assert_frame_equal(result2, expected2) + + +def test_as_index_series_ohlc(df): + # GH#65140 + grouped = df.groupby("A", as_index=False) + grouped2 = df.groupby(["A", "B"], as_index=False) + + result = grouped["C"].ohlc() + expected = df.groupby("A")["C"].ohlc().reset_index() + tm.assert_frame_equal(result, expected) + + result2 = grouped2["C"].ohlc() + expected2 = df.groupby(["A", "B"])["C"].ohlc().reset_index() + tm.assert_frame_equal(result2, expected2) + + df_conflict = pd.DataFrame( + {"open": ["A", "A", "B", "B"], "price": [1.0, 2.0, 3.0, 4.0]} + ) + with pytest.raises(ValueError, match="cannot insert open, already exists"): + df_conflict.groupby("open", as_index=False)["price"].ohlc() + + +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 = pd.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, strict=True)) + expected.insert(0, "A", arrays[0]) + expected.insert(1, "B", arrays[1]) + expected.index = pd.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_multiple_key(): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ) + 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) + + +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, using_infer_string): + grouped = df.groupby("A") + msg = re.escape("agg function failed [how->mean,dtype->") + if using_infer_string: + msg = "dtype 'str' does not support operation 'mean'" + 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(2011, 1, 1) + grouped = df.groupby("A") + msg = "datetime64 type does not support operation 'sum'" + with pytest.raises(TypeError, match=msg): + grouped.agg("sum") + with pytest.raises(TypeError, match=msg): + grouped.sum() + + +@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, using_infer_string): + # 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 using_infer_string: + msg = f"dtype 'str' does not support operation '{agg_function}'" + klass = TypeError + elif 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->") + 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, using_infer_string): + # GH 38815 + grouped = df.groupby("A") + + err = ValueError + msg = "could not convert" + if using_infer_string: + err = TypeError + msg = "dtype 'str' does not support operation 'skew'" + with pytest.raises(err, match=msg): + grouped.skew() + + +def test_raise_on_nuisance_python_multiple(three_group, using_infer_string): + grouped = three_group.groupby(["A", "B"]) + msg = re.escape("agg function failed [how->mean,dtype->") + if using_infer_string: + msg = "dtype 'str' does not support operation 'mean'" + with pytest.raises(TypeError, match=msg): + grouped.agg("mean") + with pytest.raises(TypeError, match=msg): + grouped.mean() + + +def test_empty_groups_corner(multiindex_dataframe_random_data): + # handle empty groups + df = pd.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 = multiindex_dataframe_random_data[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 = pd.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(multiindex_dataframe_random_data): + df = multiindex_dataframe_random_data.T + + keys = [np.array([0, 0, 1]), np.array([0, 0, 1])] + agged = df.groupby(keys).agg("mean") + assert isinstance(agged.columns, pd.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(multiindex_dataframe_random_data): + result = multiindex_dataframe_random_data.groupby(level=0).count() + assert result.index.name == "first" + result = multiindex_dataframe_random_data.groupby(level=1).count() + assert result.index.name == "second" + + result = multiindex_dataframe_random_data["A"].groupby(level=0).count() + assert result.index.name == "first" + + +def test_groupby_level_mapper(multiindex_dataframe_random_data): + deleveled = multiindex_dataframe_random_data.reset_index() + + mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1} + mapper1 = {"one": 0, "two": 0, "three": 1} + + result0 = multiindex_dataframe_random_data.groupby(mapper0, level=0).sum() + result1 = multiindex_dataframe_random_data.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 = multiindex_dataframe_random_data.groupby(mapped_level0).sum() + expected1 = multiindex_dataframe_random_data.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 = pd.Series( + [1, 2, 3, 10, 4, 5, 20, 6], pd.Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo") + ) + expected = pd.Series([11, 22, 3, 4, 5, 6], pd.Index(list(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 = pd.Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1]) + expected = pd.Series((1 + 2j, 5 + 10j), index=pd.Index([0, 1])) + + result = a.groupby(level=0).sum() + tm.assert_series_equal(result, expected) + + +def test_groupby_complex_mean(): + # GH 26475 + df = pd.DataFrame( + [ + {"a": 2, "b": 1 + 2j}, + {"a": 1, "b": 1 + 1j}, + {"a": 1, "b": 1 + 2j}, + ] + ) + result = df.groupby("b").mean() + expected = pd.DataFrame( + [[1.0], [1.5]], + index=pd.Index([(1 + 1j), (1 + 2j)], name="b"), + columns=pd.Index(["a"]), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_complex_numbers(): + # GH 17927 + df = pd.DataFrame( + [ + {"a": 1, "b": 1 + 1j}, + {"a": 1, "b": 1 + 2j}, + {"a": 4, "b": 1}, + ] + ) + expected = pd.DataFrame( + np.array([1, 1, 1], dtype=np.int64), + index=pd.Index([(1 + 1j), (1 + 2j), (1 + 0j)], name="b"), + columns=pd.Index(["a"]), + ) + result = df.groupby("b", sort=False).count() + tm.assert_frame_equal(result, expected) + + # Sorted by the magnitude of the complex numbers + expected.index = pd.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 = pd.Series( + [5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7], + index=pd.Index(["a", "b", "c", "d", "e", "f", "g"]), + ) + s2 = pd.Series( + [1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=pd.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"], + ], + strict=True, + ) + ) + index = pd.MultiIndex.from_tuples(tuples) + columns = pd.MultiIndex.from_tuples( + [("A", "cat"), ("B", "dog"), ("B", "cat"), ("A", "dog")] + ) + df = pd.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) + + 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) + + # 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) + grouped2 = df.groupby(df["A"].rename(None)) + + result = grouped.sum() + expected = grouped2.sum() + tm.assert_frame_equal(result, expected) + + +def test_groupby_wrong_multi_labels(): + index = pd.Index([0, 1, 2, 3, 4], name="index") + data = pd.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 = pd.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 pd.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 pd.Series({"count": 1, "mean": 2, "omissions": 3}, name=df.iloc[0]["C"]) + + 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 = pd.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 = pd.DataFrame([[0, 1, 2]], columns=["A", "B", 0]) + expected = pd.DataFrame([[1, 2]], columns=["B", 0], index=pd.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 = pd.Series(arr[:, 0]) + inds = np.tile(range(10), 10) + + result = obj.groupby(inds).agg(pd.Series.median) + assert result.isna().all() + + +def test_series_grouper_noncontig_index(): + index = pd.Index(["a" * 10] * 100) + + values = pd.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 = pd.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 = pd.DataFrame({"x": [], "range": np.arange(0, dtype="int64")}) + assert df["x"].dtype == np.float64 + + result = df.groupby("x").first() + exp_index = pd.Index([], name="x", dtype=np.float64) + expected = pd.DataFrame({"range": pd.Series([], index=exp_index, dtype="int64")}) + tm.assert_frame_equal(result, expected) + + +def test_groupby_unit64_float_conversion(): + # GH: 30859 groupby converts unit64 to floats sometimes + df = pd.DataFrame({"first": [1], "second": [1], "value": [16148277970000000000]}) + result = df.groupby(["first", "second"])["value"].max() + expected = pd.Series( + [16148277970000000000], + pd.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 = pd.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 = pd.date_range( + start=pd.Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq + ) + df = pd.DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index) + result = df.groupby([pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((1, 4)), columns=list("ABCD") + ) + with pytest.raises(KeyError, match=msg): + df1.groupby("Z") + df2 = pd.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 = pd.DataFrame( + { + "values": np.random.default_rng(2).standard_normal(8), + "dt": [ + np.nan, + pd.Timestamp("2013-01-01"), + np.nan, + pd.Timestamp("2013-02-01"), + np.nan, + pd.Timestamp("2013-02-01"), + np.nan, + pd.Timestamp("2013-01-01"), + ], + "str": [np.nan, "a", np.nan, "a", np.nan, "a", np.nan, "b"], + } + ) + grouped = df.groupby("dt") + + expected = [ + pd.RangeIndex(start=1, stop=13, step=6), + pd.RangeIndex(start=3, stop=7, step=2), + ] + keys = sorted(grouped.groups.keys()) + assert len(keys) == 2 + for k, e in zip(keys, expected, strict=True): + # 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 = { + pd.Timestamp("2013-01-01 00:00:00"): np.array([1, 7], dtype=np.intp), + pd.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(pd.Timestamp("2013-01-01")), df.iloc[[1, 7]] + ) + tm.assert_frame_equal( + grouped.get_group(pd.Timestamp("2013-02-01")), df.iloc[[3, 5]] + ) + + with pytest.raises(KeyError, match=r"^NaT$"): + grouped.get_group(pd.NaT) + + nan_df = pd.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[s]" + + 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 = pd.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 = pd.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, pd.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 = pd.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 = pd.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 = pd.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 = pd.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[["name"]]) + + +def test_skip_group_keys(): + tsf = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ) + + 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 = pd.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 pd.Series({"max": group.max(), "min": group.min()}) + + result = df.groupby("A")["C"].apply(f) + expected = df.groupby("A")["C"].apply(g) + + assert isinstance(result, pd.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 = pd.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 + + result2 = df.groupby([df["A"].values, df["B"].values]).sum() + assert result2.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 = pd.MultiIndex( + levels=[[1, 2], [1, 2]], + codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]], + names=["a", "b"], + ) + mseries = pd.Series([0, 1, 2, 3, 4, 5], index=index) + index = pd.MultiIndex( + levels=[[1, 2], [1, 2]], codes=[[0, 0, 1], [1, 0, 0]], names=["a", "b"] + ) + mseries_result = pd.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 = pd.date_range(start="2012/1/1", freq="5min", periods=periods) + df = pd.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 = pd.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 = pd.MultiIndex.from_tuples( + [("a", "c"), ("a", "d"), ("b", "c")], names=["group1", "group2"] + ) + exp = pd.DataFrame([[2], [1], [5]], index=idx, columns=["value"]) + + tm.assert_frame_equal(res, exp) + + +def test_groupby_multiindex_not_lexsorted(performance_warning): + # GH 11640 + + # define the lexsorted version + lexsorted_mi = pd.MultiIndex.from_tuples( + [("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"] + ) + lexsorted_df = pd.DataFrame([[1, 3, 4]], columns=lexsorted_mi) + assert lexsorted_df.columns._is_lexsorted() + + # define the non-lexsorted version + not_lexsorted_df = pd.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() + msg = "dropping on a non-lexsorted multi-index without a level parameter" + with tm.assert_produces_warning(performance_warning, match=msg): + result = not_lexsorted_df.groupby("a").mean() + tm.assert_frame_equal(expected, result) + + # a transforming function should work regardless of sort + # GH 14776 + df = pd.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( + pd.DataFrame.drop_duplicates + ) + expected = df + tm.assert_frame_equal(expected, result) + + result = ( + df.sort_index() + .groupby(level=level, sort=sort, group_keys=False) + .apply(pd.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 = pd.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 = pd.DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x}) + df2 = pd.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 = pd.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 = pd.DataFrame( + { + "eventDate": pd.date_range( + datetime(2011, 1, 1), periods=20, freq="ME" + ).tolist(), + "thename": range(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"], + pd.Categorical([0]), + [pd.to_datetime(0)], + pd.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", "kurt"] +) +def test_empty_groupby(columns, keys, values, method, op, dropna, using_infer_string): + # GH8093 & GH26411 + override_dtype = None + + 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 = pd.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 a 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 = pd.Categorical([0], dtype=values.dtype) + if len(keys) != 1: + idx = pd.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 = pd.Index(lev, name=keys[0]) + + if using_infer_string: + columns = pd.Index([], dtype="str") + else: + columns = [] + expected = pd.DataFrame([], columns=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, pd.Categorical) + is_str = isinstance(df.dtypes.iloc[0], pd.StringDtype) + + if ( + isinstance(values, pd.Categorical) + and not values.ordered + and op in ["min", "max", "idxmin", "idxmax"] + ): + if op in ["min", "max"]: + msg = f"Cannot perform {op} with non-ordered Categorical" + klass = TypeError + else: + msg = f"Can't get {op} of an empty group due to unobserved categories" + klass = ValueError + with pytest.raises(klass, match=msg): + get_result() + + if op in ["min", "max", "idxmin", "idxmax"] and 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", "kurt"]: + # ops that require more than just ordered-ness + if is_dt64 or is_cat or is_per or (is_str and op != "sum"): + # 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" + elif is_str: + msg = f"dtype 'str' does not support operation '{op}'" + else: + msg = "category type does not support" + if op in ["skew", "kurt"]: + msg = "|".join([msg, f"does not support operation '{op}'"]) + with pytest.raises(TypeError, match=msg): + get_result() + + if not isinstance(columns, list): + # i.e. SeriesGroupBy + return + elif op in ["skew", "kurt"]: + # 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 = pd.Index([], dtype=df[keys[0]].dtype, name=keys[0]) + expected.index.name = keys[0] + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("method_name", ["agg", "apply"]) +@pytest.mark.parametrize("keys", [[1], [1, 2]]) +def test_empty_groupby_apply_nonunique_columns(method_name, keys): + # GH#44417 & GH#63975 + df = pd.DataFrame(np.random.default_rng(2).standard_normal((0, 5))) + df[4] = df[4].astype(np.int64) + df.columns = [0, 1, 2, 3, 0] + gb = df.groupby(keys, group_keys=False) + method = getattr(gb, method_name) + result = method(lambda x: x) + expected = pd.DataFrame(dtype="float64", columns=range(5)) + expected[4] = expected[4].astype("int64") + expected.columns = [0, 1, 2, 3, 0] + if method_name == "agg": + expected = expected.set_index(keys) + else: + expected = expected.drop(columns=keys) + tm.assert_frame_equal(result, expected) + + +def test_tuple_as_grouping(): + # https://github.com/pandas-dev/pandas/issues/18314 + df = pd.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 = pd.Series([4], name="c", index=pd.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 = pd.DataFrame( + 1, index=range(3), columns=pd.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 = pd.DataFrame( + [[1], [1]], + columns=pd.Index(["foo"], name="mycols"), + index=pd.date_range("2018-01-01", periods=2, freq="D", name="dti"), + ) + + expected = pd.DataFrame( + [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], + columns=pd.MultiIndex.from_tuples( + ( + ("foo", "sum", "foo"), + ("foo", "ohlc", "open"), + ("foo", "ohlc", "high"), + ("foo", "ohlc", "low"), + ("foo", "ohlc", "close"), + ), + names=["mycols", None, None], + ), + index=pd.date_range("2018-01-01", periods=2, freq="D", name="dti"), + ) + + result = df.groupby(pd.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 = pd.MultiIndex.from_tuples(values, names=["date", None]) + ser = pd.Series([3, 2, 2.5, 4], index=mi) + + result = ser.groupby(level=1).mean() + expected = pd.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), strict=True) + df = pd.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 = pd.MultiIndex.from_arrays(index_array, names=index_names) + s = pd.Series(data=[1, 2], index=ri) + result = s.groupby(["first", "third"]).sum() + + index_array = [["x"], ["k"]] + index_names = ["first", "third"] + ei = pd.MultiIndex.from_arrays(index_array, names=index_names) + expected = pd.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 = pd.MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"]) + df = pd.DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi) + result = df.groupby([pd.Grouper(level="alpha"), "beta"]) + expected = df.groupby(["alpha", "beta"]) + assert result.groups == expected.groups + + result = df.groupby(["beta", pd.Grouper(level="alpha")]) + expected = df.groupby(["beta", "alpha"]) + assert result.groups == expected.groups + + +def test_groups_sort_dropna(sort, dropna): + # GH#56966, GH#56851 + df = pd.DataFrame([[2.0, 1.0], [np.nan, 4.0], [0.0, 3.0]]) + keys = [(2.0, 1.0), (np.nan, 4.0), (0.0, 3.0)] + values = [ + pd.RangeIndex(0, 1), + pd.RangeIndex(1, 2), + pd.RangeIndex(2, 3), + ] + if sort: + taker = [2, 0] if dropna else [2, 0, 1] + else: + taker = [0, 2] if dropna else [0, 1, 2] + expected = {keys[idx]: values[idx] for idx in taker} + + gb = df.groupby([0, 1], sort=sort, dropna=dropna) + result = gb.groups + + for result_key, expected_key in zip(result.keys(), expected.keys(), strict=True): + # Compare as NumPy arrays to handle np.nan + result_key = np.array(result_key) + expected_key = np.array(expected_key) + tm.assert_numpy_array_equal(result_key, expected_key) + for result_value, expected_value in zip( + result.values(), expected.values(), strict=True + ): + tm.assert_index_equal(result_value, expected_value) + + +@pytest.mark.parametrize( + "op, expected", + [ + ( + "shift", + { + "time": [ + None, + None, + pd.Timestamp("2019-01-01 12:00:00"), + pd.Timestamp("2019-01-01 12:30:00"), + None, + None, + ] + }, + ), + ( + "bfill", + { + "time": [ + pd.Timestamp("2019-01-01 12:00:00"), + pd.Timestamp("2019-01-01 12:30:00"), + pd.Timestamp("2019-01-01 14:00:00"), + pd.Timestamp("2019-01-01 14:30:00"), + pd.Timestamp("2019-01-01 14:00:00"), + pd.Timestamp("2019-01-01 14:30:00"), + ] + }, + ), + ( + "ffill", + { + "time": [ + pd.Timestamp("2019-01-01 12:00:00"), + pd.Timestamp("2019-01-01 12:30:00"), + pd.Timestamp("2019-01-01 12:00:00"), + pd.Timestamp("2019-01-01 12:30:00"), + pd.Timestamp("2019-01-01 14:00:00"), + pd.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": [ + pd.Timestamp("2019-01-01 12:00:00"), + pd.Timestamp("2019-01-01 12:30:00"), + None, + None, + pd.Timestamp("2019-01-01 14:00:00"), + pd.Timestamp("2019-01-01 14:30:00"), + ], + } + df = pd.DataFrame(data).assign(time=lambda x: x.time.dt.tz_localize(tz)) + + grouped = df.groupby("id") + result = getattr(grouped, op)() + expected = pd.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 = pd.DataFrame({"g": [None], "x": 1}) + actual = df.groupby("g")["x"].transform("sum") + expected = pd.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 = pd.Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0]) + gb = ser.groupby(level=0) + + result = gb.mean() + expected = pd.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 = pd.DataFrame( + data=[[1, pd.Timestamp("2011-01-01"), 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"]) + result = df.iloc[:0].groupby(["col_1"]).transform(transformation_func) + expected = df.groupby(["col_1"]).transform(transformation_func).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) + expected = df["col_3"].groupby(["col_1"]).transform(transformation_func).iloc[:0] + if transformation_func in ("diff", "shift"): + expected = expected.astype(int) + tm.assert_equal(result, expected) + + +def test_groupby_crash_on_nunique(): + # Fix following 30253 + dti = pd.date_range("2016-01-01", periods=2, name="foo") + df = pd.DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]}) + df.columns.names = ("bar", "baz") + df.index = dti + + df = df.T + gb = df.groupby(level=0) + result = gb.nunique() + + expected = pd.DataFrame({"A": [1, 2], "D": [1, 1]}, index=dti) + expected.columns.name = "bar" + expected = expected.T + + tm.assert_frame_equal(result, expected) + + # same thing, but empty columns + gb2 = df[[]].groupby(level=0) + exp = expected[[]] + + res = gb2.nunique() + tm.assert_frame_equal(res, exp) + + +def test_groupby_list_level(): + # GH 9790 + expected = pd.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 = pd.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 = pd.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", + [ + (pd.DataFrame, "level", "a"), + (pd.DataFrame, "as_index", False), + (pd.DataFrame, "sort", False), + (pd.DataFrame, "group_keys", False), + (pd.DataFrame, "observed", True), + (pd.DataFrame, "dropna", False), + (pd.Series, "level", "a"), + (pd.Series, "as_index", False), + (pd.Series, "sort", False), + (pd.Series, "group_keys", False), + (pd.Series, "observed", True), + (pd.Series, "dropna", False), + ], +) +def test_subsetting_columns_keeps_attrs(klass, attr, value): + # GH 9959 - When subsetting columns, don't drop attributes + df = pd.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 pd.DataFrame else expected["b"] + assert getattr(result, attr) == getattr(expected, attr) + + +@pytest.mark.parametrize("func", ["sum", "any", "shift"]) +def test_groupby_column_index_name_lost(func): + # GH: 29764 groupby loses index sometimes + expected = pd.Index(["a"], name="idx") + df = pd.DataFrame([[1]], columns=expected) + df_grouped = df.groupby([1]) + result = getattr(df_grouped, func)().columns + tm.assert_index_equal(result, expected) + + +def test_groupby_duplicate_columns(): + # GH: 31735 + df = pd.DataFrame( + {"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]} + ).astype(object) + df.columns = ["A", "B", "B"] + result = df.groupby([0, 0, 0, 0]).min() + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) + result = getattr(df.groupby("group"), func)() + expected = pd.DataFrame( + {"a": values, "b": values}, index=pd.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 = pd.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 = pd.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 = pd.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 = pd.date_range("2016-01-01", periods=5, unit="ns") + ser = pd.Series(dti) - dti[0] + ser[2] = pd.NaT + + df = pd.DataFrame({"A": 1, "B": ser}) + gb = df.groupby("A") + + res = gb.cumsum(numeric_only=False, skipna=True) + exp = pd.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 = pd.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 = pd.Series([1, 2, 3], [np.nan, np.nan, np.nan]) + result = s.groupby(s.index).sum() + expected = pd.Series([], index=pd.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 = pd.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 = pd.MultiIndex([[], []], [[], []], names=["A", "B"]) + columns = ["C"] if not numeric_only else pd.Index([], dtype="str") + else: + index = pd.RangeIndex(0) + columns = ["A", "B", "C"] if not numeric_only else ["A", "B"] + expected = pd.DataFrame([], columns=columns, index=index) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_non_numeric_dtype(): + # GH #43108 + df = pd.DataFrame( + [["M", [1]], ["M", [1]], ["W", [10]], ["W", [20]]], columns=["MW", "v"] + ) + + expected = pd.DataFrame( + { + "v": [[1, 1], [10, 20]], + }, + index=pd.Index(["M", "W"], 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 = pd.DataFrame( + { + "x": [1, 0, 1, 1, 0], + "y": [pd.Timedelta(i, "days") for i in range(1, 6)], + "z": [pd.Timedelta(i * 10, "days") for i in range(1, 6)], + } + ) + + expected = pd.DataFrame( + { + "y": [pd.Timedelta(i, "days") for i in range(7, 9)], + "z": [pd.Timedelta(i * 10, "days") for i in range(7, 9)], + }, + index=pd.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 = pd.DataFrame( + { + "x": [1, 0, 1, 1, 0], + "y": [pd.Timedelta(i, "days") for i in range(1, 6)], + "z": list(range(1, 6)), + } + ) + + expected = pd.DataFrame( + {"y": [pd.Timedelta(7, "days"), pd.Timedelta(8, "days")], "z": [7, 8]}, + index=pd.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 = pd.DataFrame(dicts) + + df_filter = df[df["filter_col"] == True] # noqa: E712 + dfgb = df_filter.groupby("groupby_col") + result = dfgb.std() + expected = pd.DataFrame( + [[0.0, 0.0, 7.071068]], + columns=["filter_col", "bool_col", "float_col"], + index=pd.Index([True], name="groupby_col"), + ) + tm.assert_frame_equal(result, expected) + + +def test_datetime_categorical_multikey_groupby_indices(): + # GH 26859 + df = pd.DataFrame( + { + "a": pd.Series(list("abc")), + "b": pd.Series( + pd.to_datetime(["2018-01-01", "2018-02-01", "2018-03-01"]), + dtype="category", + ), + "c": pd.Categorical.from_codes([-1, 0, 1], categories=[0, 1]), + } + ) + result = df.groupby(["a", "b"], observed=False).indices + expected = { + ("a", pd.Timestamp("2018-01-01 00:00:00")): np.array([0]), + ("b", pd.Timestamp("2018-02-01 00:00:00")): np.array([1]), + ("c", pd.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 = pd.DataFrame([name_l, val_l]).T + test_df.columns = ["name", "val"] + + result_error_msg = ( + r"^[a-zA-Z._]*\(\) 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() + + +def test_by_column_values_with_same_starting_value(any_string_dtype): + # GH29635 + dtype = any_string_dtype + df = pd.DataFrame( + { + "Name": ["Thomas", "Thomas", "Thomas John"], + "Credit": [1200, 1300, 900], + "Mood": pd.Series(["sad", "happy", "happy"], dtype=dtype), + } + ) + aggregate_details = {"Mood": pd.Series.mode, "Credit": "sum"} + + msg = "Converting a Series or array of length 1 into a scalar" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.groupby(["Name"]).agg(aggregate_details) + expected = pd.DataFrame( + { + "Mood": [["happy", "sad"], "happy"], + "Credit": [2500, 900], + "Name": ["Thomas", "Thomas John"], + }, + ).set_index("Name") + if getattr(dtype, "storage", None) == "pyarrow": + mood_values = pd.array(["happy", "sad"], dtype=dtype) + expected["Mood"] = [mood_values, "happy"] + tm.assert_frame_equal(result, expected) + + +def test_groupby_none_in_first_mi_level(): + # GH#47348 + arr = [[None, 1, 0, 1], [2, 3, 2, 3]] + ser = pd.Series(1, index=pd.MultiIndex.from_arrays(arr, names=["a", "b"])) + result = ser.groupby(level=[0, 1]).sum() + expected = pd.Series( + [1, 2], pd.MultiIndex.from_tuples([(0.0, 2), (1.0, 3)], names=["a", "b"]) + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_none_column_name(using_infer_string): + # GH#47348 + df = pd.DataFrame({None: [1, 1, 2, 2], "b": [1, 1, 2, 3], "c": [4, 5, 6, 7]}) + by = [np.nan] if using_infer_string else [None] + gb = df.groupby(by=by) + result = gb.sum() + expected = pd.DataFrame( + {"b": [2, 5], "c": [9, 13]}, index=pd.Index([1, 2], name=by[0]) + ) + 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 = pd.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 = pd.DataFrame({"str_col": ["a", "b", "c", "a"], "num_col": [1, 2, 3, 2]}) + df["str_col"] = df["str_col"].astype("string") + expected = pd.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(level_arg, multiindex): + # GH 51583 + df = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"]) + if multiindex: + df = df.set_index(["a", "b"]) + result = [key for key, _ in df.groupby(level=level_arg)] + expected = [(1,), (2,)] if multiindex else [("x",), ("y",)] + assert result == expected + + +@pytest.mark.parametrize("func", ["sum", "cumsum", "cumprod", "prod"]) +def test_groupby_avoid_casting_to_float(func): + # GH#37493 + val = 922337203685477580 + df = pd.DataFrame({"a": 1, "b": [val]}) + result = getattr(df.groupby("a"), func)() - val + expected = pd.DataFrame({"b": [0]}, index=pd.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 = pd.DataFrame({"a": 1, "b": [1, 2, pd.NA]}, dtype=any_numeric_ea_dtype) + result = getattr(df.groupby("a"), func)() + expected = pd.DataFrame( + {"b": [val]}, + index=pd.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 = pd.DataFrame({"a": 1, "b": [val, val]}, dtype=f"{dtype}8") + result = df.groupby("a").sum() + expected = pd.DataFrame( + {"b": [val * 2]}, + index=pd.Index([1], name="a", dtype=f"{dtype}8"), + dtype=f"{dtype}64", + ) + tm.assert_frame_equal(result, expected) + + result = df.groupby("a").cumsum() + expected = pd.DataFrame({"b": [val, val * 2]}, dtype=f"{dtype}64") + tm.assert_frame_equal(result, expected) + + result = df.groupby("a").prod() + expected = pd.DataFrame( + {"b": [val * val]}, + index=pd.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 = pd.DataFrame({"a": 1, "b": [1, pd.NA, 2]}, dtype=any_numeric_ea_dtype) + result = df.groupby("a").cumsum(skipna=skipna) + expected = pd.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 = pd.Series(data=val_in, name="values", index=pd.Index(index, name="blah")) + result = series.groupby("blah").sum() + expected = pd.Series( + data=val_out, + name="values", + index=pd.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 = pd.DataFrame({"groupby_col": 1, "bool": [True] * n}) + df["bool"] = df["bool"].eq(True) + result = df.groupby("groupby_col").sum() + expected = pd.DataFrame({"bool": [n]}, index=pd.Index([1], name="groupby_col")) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("method", ["head", "tail", "nth", "first", "last"]) +def test_groupby_method_drop_na(method): + # GH 21755 + df = pd.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 = pd.DataFrame({"B": [0, 2, 4]}).set_index( + pd.Series(["a", "b", "c"], name="A") + ) + else: + expected = pd.DataFrame( + {"A": ["a", "b", "c"], "B": [0, 2, 4]}, index=range(0, 6, 2) + ) + 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 = pd.Index(range(10), dtype=int) + tm.assert_series_equal(res, expected) + + res = gb.min() + expected = ser[:10] + expected.index = pd.Index(range(10), dtype=int) + tm.assert_series_equal(res, expected) + + +def test_obj_with_exclusions_duplicate_columns(): + # GH#50806 + df = pd.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 = pd.DataFrame(dicts_non_numeric, dtype=object) + dfgb = df.groupby("a", as_index=False, sort=False) + + if numeric_only: + result = dfgb.std(numeric_only=True) + expected_df = pd.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 = pd.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 = pd.Categorical( + [ + pd.Interval(-0.401, 0.1, closed="right"), + pd.Interval(0.1, 0.2, closed="right"), + pd.Interval(0.2, 0.3, closed="right"), + pd.Interval(0.3, 0.5, closed="right"), + ], + ordered=True, + ) + index_level_2 = ["a", "b", "c"] + mi = pd.MultiIndex.from_product( + [categorical_index_level_1, index_level_2], names=["x", "w"] + ) + expected = pd.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 = pd.DataFrame({"A": [bug_var, bug_var, bug_var, np.nan]}) + if isinstance(bug_var, str): + df = df.astype(object) + dfgb = df.groupby(lambda x: x) + result = dfgb.sum(min_count=1) + + expected_df = pd.DataFrame( + [bug_var, bug_var, bug_var, None], columns=["A"], dtype=df["A"].dtype + ) + 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 = pd.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 = pd.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.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(unit): + idx2 = pd.to_datetime( + [ + "2016-08-31 22:08:12.000", + "2016-08-31 22:09:12.200", + "2016-08-31 22:20:12.400", + ] + ).as_unit(unit) + + test_data = pd.DataFrame( + {"quant": [1.0, 1.0, 3.0], "quant2": [1.0, 1.0, 3.0], "time2": idx2} + ) + + time2 = pd.date_range("2016-08-31 22:08:00", periods=13, freq="1min", unit=unit) + expected_output = pd.DataFrame( + { + "time2": time2, + "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], + } + ) + + gb = test_data.groupby(pd.Grouper(key="time2", freq="1min")) + result = gb.count().reset_index() + + tm.assert_frame_equal(result, expected_output) + + +def test_groupby_series_with_datetimeindex_month_name(): + # GH 48509 + s = pd.Series([0, 1, 0], index=pd.date_range("2022-01-01", periods=3), name="jan") + result = s.groupby(s).count() + expected = pd.Series([2, 1], name="jan") + expected.index.name = "jan" + tm.assert_series_equal(result, expected) + + +def test_groupby_series_with_datetimeindex_numeric_name(): + # GH 51818 - a name parseable as an out-of-bounds datetime (e.g. "09") + # should not make groupby(self) raise OutOfBoundsDatetime + ser = pd.Series( + [0, 1, 0], + index=pd.date_range("2013-06-07", periods=3, freq="15min"), + name="09", + ) + result = ser.groupby(ser).count() + expected = pd.Series([2, 1], name="09") + expected.index.name = "09" + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("test_series", [True, False]) +@pytest.mark.parametrize( + "kwarg, value, name, warn", + [ + ("by", "a", 1, None), + ("by", ["a"], (1,), None), + ("level", 0, 1, None), + ("level", [0], (1,), None), + ], +) +def test_get_group_len_1_list_likes(test_series, kwarg, value, name, warn): + # GH#25971 + obj = pd.DataFrame({"b": [3, 4, 5]}, index=pd.Index([1, 1, 2], name="a")) + if test_series: + obj = obj["b"] + gb = obj.groupby(**{kwarg: value}) + result = gb.get_group(name) + if test_series: + expected = pd.Series([3, 4], index=pd.Index([1, 1], name="a"), name="b") + else: + expected = pd.DataFrame({"b": [3, 4]}, index=pd.Index([1, 1], name="a")) + tm.assert_equal(result, expected) + + +def test_groupby_ngroup_with_nan(): + # GH#50100 + df = pd.DataFrame({"a": pd.Categorical([np.nan]), "b": [1]}) + result = df.groupby(["a", "b"], dropna=False, observed=False).ngroup() + expected = pd.Series([0]) + tm.assert_series_equal(result, expected) + + +def test_groupby_ffill_with_duplicated_index(): + # GH#43412 + df = pd.DataFrame({"a": [1, 2, 3, 4, np.nan, np.nan]}, index=[0, 1, 2, 0, 1, 2]) + + result = df.groupby(level=0).ffill() + expected = pd.DataFrame({"a": [1, 2, 3, 4, 2, 3]}, index=[0, 1, 2, 0, 1, 2]) + tm.assert_frame_equal(result, expected, check_dtype=False) + + +@pytest.mark.parametrize("test_series", [True, False]) +def test_decimal_na_sort(test_series): + # GH#54847 + # We catch both TypeError and decimal.InvalidOperation exceptions in safe_sort. + # If this next assert raises, we can just catch TypeError + assert not isinstance(decimal.InvalidOperation, TypeError) + df = pd.DataFrame( + { + "key": [Decimal(1), Decimal(1), None, None], + "value": [Decimal(2), Decimal(3), Decimal(4), Decimal(5)], + } + ) + gb = df.groupby("key", dropna=False) + if test_series: + gb = gb["value"] + result = gb._grouper.result_index + expected = pd.Index([Decimal(1), None], name="key") + tm.assert_index_equal(result, expected) + + +def test_groupby_dropna_with_nunique_unique(): + # GH#42016 + df = [[1, 1, 1, "A"], [1, None, 1, "A"], [1, None, 2, "A"], [1, None, 3, "A"]] + df_dropna = pd.DataFrame(df, columns=["a", "b", "c", "partner"]) + result = df_dropna.groupby(["a", "b", "c"], dropna=False).agg( + {"partner": ["nunique", "unique"]} + ) + + index = pd.MultiIndex.from_tuples( + [(1, 1.0, 1), (1, np.nan, 1), (1, np.nan, 2), (1, np.nan, 3)], + names=["a", "b", "c"], + ) + columns = pd.MultiIndex.from_tuples([("partner", "nunique"), ("partner", "unique")]) + expected = pd.DataFrame( + [(1, ["A"]), (1, ["A"]), (1, ["A"]), (1, ["A"])], index=index, columns=columns + ) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_namedagg_with_duplicate_columns(): + # GH#58446 + df = pd.DataFrame( + { + "col1": [2, 1, 1, 0, 2, 0], + "col2": [4, 5, 36, 7, 4, 5], + "col3": [3.1, 8.0, 12, 10, 4, 1.1], + "col4": [17, 3, 16, 15, 5, 6], + "col5": [-1, 3, -1, 3, -2, -1], + } + ) + + result = df.groupby(by=["col1", "col1", "col2"], as_index=False).agg( + new_col=pd.NamedAgg(column="col1", aggfunc="min"), + new_col1=pd.NamedAgg(column="col1", aggfunc="max"), + new_col2=pd.NamedAgg(column="col2", aggfunc="count"), + ) + + expected = pd.DataFrame( + { + "col1": [0, 0, 1, 1, 2], + "col2": [5, 7, 5, 36, 4], + "new_col": [0, 0, 1, 1, 2], + "new_col1": [0, 0, 1, 1, 2], + "new_col2": [1, 1, 1, 1, 2], + } + ) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_multi_index_codes(): + # GH#54347 + df = pd.DataFrame( + {"A": [1, 2, 3, 4], "B": [1, float("nan"), 2, float("nan")], "C": [2, 4, 6, 8]} + ) + df_grouped = df.groupby(["A", "B"], dropna=False).sum() + + index = df_grouped.index + tm.assert_index_equal(index, pd.MultiIndex.from_frame(index.to_frame())) + + +def test_groupby_datetime_with_nat(): + # GH##35202 + df = pd.DataFrame( + { + "a": [ + pd.to_datetime("2019-02-12"), + pd.to_datetime("2019-02-12"), + pd.to_datetime("2019-02-13"), + pd.NaT, + ], + "b": [1, 2, 3, 4], + } + ) + grouped = df.groupby("a", dropna=False) + result = len(grouped) + assert result == 3 + + +def test_groupby_function_tuple_1677(): + # GH#1677 + df = pd.DataFrame( + np.random.default_rng(2).random(100), + index=pd.date_range("1/1/2000", periods=100), + ) + monthly_group = df.groupby(lambda x: (x.year, x.month)) + + result = monthly_group.mean() + assert isinstance(result.index[0], tuple) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_groupby_dropna.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_groupby_dropna.py new file mode 100644 index 0000000000000000000000000000000000000000..1ddeefedc217ff960b957d92a2f7ca169b2f9ba5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_groupby_dropna.py @@ -0,0 +1,692 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning +import pandas.util._test_decorators as td + +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, 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) + + +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"], strict=False)) + 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(), strict=True + ): + 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) + + +# y >x and z is the missing value +@pytest.mark.parametrize( + "sequence", + [ + "xyzy", + "xxyz", + "yzxz", + "zzzz", + "zyzx", + "yyyy", + "zzxy", + "xyxy", + ], +) +@pytest.mark.parametrize( + "dtype", + [ + None, + "UInt8", + "Int8", + "UInt16", + "Int16", + "UInt32", + "Int32", + "UInt64", + "Int64", + "Float32", + "Float64", + "category", + "string", + pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")), + "datetime64[ns]", + "period[D]", + "Sparse[float]", + ], +) +@pytest.mark.parametrize("test_series", [True, False]) +def test_no_sort_keep_na(sequence, dtype, test_series, as_index): + # GH#46584, GH#48794 + + # 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} + elif dtype is not None and dtype.startswith(("I", "U", "F")): + uniques = {"x": 1, "y": 2, "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(reduction_func, observed, sort, as_index, index_kind): + # 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_keepna = df.groupby( + keys, dropna=False, observed=observed, sort=sort, as_index=as_index + ) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + getattr(gb_keepna, reduction_func)(*args) + return + + gb_filled = df_filled.groupby(keys, observed=observed, sort=sort, as_index=True) + if reduction_func == "corrwith": + warn = Pandas4Warning + msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + msg = "" + with tm.assert_produces_warning(warn, match=msg): + expected = getattr(gb_filled, reduction_func)(*args_filled).reset_index() + expected["x"] = expected["x"].cat.remove_categories([4]) + if index_kind == "multi": + expected["x2"] = expected["x2"].cat.remove_categories([4]) + if as_index: + if index_kind == "multi": + expected = expected.set_index(["x", "x2"]) + else: + expected = expected.set_index("x") + 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] + expected["y"] = pd.Categorical(values, categories=[1, 2, 3]) + 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) + + if reduction_func == "corrwith": + warn = Pandas4Warning + msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + msg = "" + 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(transformation_func, observed, sort, as_index): + # GH#36327 + 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) + + 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(), + strict=True, + ): + 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/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_groupby_subclass.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_groupby_subclass.py new file mode 100644 index 0000000000000000000000000000000000000000..1b5cbffd41fd1345b0f629de1e5540ec9eb3acaa --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_groupby_subclass.py @@ -0,0 +1,144 @@ +from datetime import datetime + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +@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, pd.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) + + warn = Pandas4Warning if groupby_func == "corrwith" else None + msg = f"{type(grouped).__name__}.corrwith is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result1 = getattr(grouped, groupby_func)(*args) + with tm.assert_produces_warning(warn, match=msg): + result2 = grouped.agg(groupby_func, *args) + + # Reduction or transformation kernels should preserve type + slices = {"ngroup", "cumcount", "size"} + if isinstance(obj, pd.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, pd.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") + assert group.testattr == "hello" + return group.testattr + + result = custom_df.groupby("c").apply(func) + expected = tm.SubclassedSeries(["hello"] * 3, index=pd.Index([7, 8, 9], name="c")) + tm.assert_series_equal(result, expected) + + result = custom_df.groupby("c").apply(func) + tm.assert_series_equal(result, expected) + + # https://github.com/pandas-dev/pandas/pull/56761 + result = custom_df.groupby("c")[["a", "b"]].apply(func) + 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) + + +def test_groupby_apply_preserves_metadata(): + # GH#62134 - Test that apply() preserves metadata when returning DataFrames/Series + custom_df = tm.SubclassedDataFrame({"a": [1, 2, 3], "b": [1, 1, 2], "c": [7, 8, 9]}) + custom_df.testattr = "hello" + + def sum_func(group): + assert isinstance(group, tm.SubclassedDataFrame) + assert hasattr(group, "testattr") + assert group.testattr == "hello" + return group.sum() + + result = custom_df.groupby("c").apply(sum_func) + assert hasattr(result, "testattr"), "DataFrame apply() should preserve metadata" + assert result.testattr == "hello" + + custom_series = tm.SubclassedSeries([1, 2, 3]) + custom_series.testattr = "hello" + + def sum_series_func(group): + assert isinstance(group, tm.SubclassedSeries) + assert hasattr(group, "testattr") + assert group.testattr == "hello" + return group.sum() + + result = custom_series.groupby(custom_df["c"]).apply(sum_series_func) + assert hasattr(result, "testattr"), "Series apply() should preserve metadata" + assert result.testattr == "hello" + + +@pytest.mark.parametrize("obj", [pd.DataFrame, tm.SubclassedDataFrame]) +def test_groupby_resample_preserves_subclass(obj): + # GH28330 -- preserve subclass through groupby.resample() + + df = obj( + { + "Buyer": pd.Series("Carl Carl Carl Carl Joe Carl".split(), dtype=object), + "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/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_grouping.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..82867ec393f193f5c38d88b1ff75a30bc3d3ed46 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_grouping.py @@ -0,0 +1,1303 @@ +""" +test where we are determining what we are grouping, or getting groups +""" + +from datetime import ( + date, + timedelta, +) + +import numpy as np +import pytest + +from pandas.errors import ( + Pandas4Warning, + SpecificationError, +) + +import pandas as pd +import pandas._testing as tm +from pandas.core.groupby.grouper import Grouping + +# selection +# -------------------------------- + + +class TestSelection: + def test_select_bad_cols(self): + df = pd.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 = pd.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 = pd.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 = pd.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 = pd.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) + + @pytest.mark.parametrize( + "func", [lambda x: x.sum(), lambda x: x.agg(lambda y: y.sum())] + ) + def test_getitem_from_grouper(self, func): + # GH 50383 + df = pd.DataFrame({"a": [1, 1, 2], "b": 3, "c": 4, "d": 5}) + gb = df.groupby(["a", "b"])[["a", "c"]] + + idx = pd.MultiIndex.from_tuples([(1, 3), (2, 3)], names=["a", "b"]) + expected = pd.DataFrame({"a": [2, 2], "c": [8, 4]}, index=idx) + result = func(gb) + + tm.assert_frame_equal(result, expected) + + def test_indices_grouped_by_tuple_with_lambda(self): + # GH 36158 + df = pd.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", + [ + pd.Index(list("abcde")), + pd.Index(np.arange(5)), + pd.Index(np.arange(5, dtype=float)), + pd.date_range("2020-01-01", periods=5), + pd.period_range("2020-01-01", periods=5), + ], + ) + def test_grouper_index_types(self, index): + # related GH5375 + # groupby misbehaving when using a Floatlike index + df = pd.DataFrame(np.arange(10).reshape(5, 2), columns=list("AB"), index=index) + + df.groupby(list("abcde"), group_keys=False).apply(lambda x: x) + + df.index = df.index[::-1] + 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(2011, 1, 1) + dates = pd.date_range(d0, d0 + timedelta(days=14)) + date_index = pd.MultiIndex.from_product([dates, dates], names=["foo", "bar"]) + df = pd.DataFrame( + np.random.default_rng(2).integers(0, 100, 225), index=date_index + ) + + # Check string level + expected = ( + df.reset_index() + .groupby([pd.Grouper(key="foo", freq="W"), pd.Grouper(key="bar", freq="W")]) + .sum() + ) + # reset index changes columns dtype to object + expected.columns = pd.Index([0], dtype="int64") + + result = df.groupby( + [pd.Grouper(level="foo", freq="W"), pd.Grouper(level="bar", freq="W")] + ).sum() + tm.assert_frame_equal(result, expected) + + # Check integer level + result = df.groupby( + [pd.Grouper(level=0, freq="W"), pd.Grouper(level=1, freq="W")] + ).sum() + tm.assert_frame_equal(result, expected) + + def test_grouper_creation_bug(self): + # GH 8795 + df = pd.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(pd.Grouper(key="A")) + result = g.sum() + tm.assert_frame_equal(result, expected) + + result = g.apply(lambda x: x.sum()) + tm.assert_frame_equal(result, expected) + + def test_grouper_creation_bug2(self): + # GH14334 + # Grouper(key=...) may be passed in a list + df = pd.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([pd.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([pd.Grouper(key="A"), pd.Grouper(key="B")]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + # Group with a string and a Grouper object + g = df.groupby(["A", pd.Grouper(key="B")]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + # Group with a Grouper object and a string + g = df.groupby([pd.Grouper(key="A"), "B"]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + def test_grouper_creation_bug3(self, unit): + # GH8866 + dti = pd.date_range("20130101", periods=2, unit=unit) + mi = pd.MultiIndex.from_product( + [list("ab"), range(2), dti], + names=["one", "two", "three"], + ) + ser = pd.Series( + np.arange(8, dtype="int64"), + index=mi, + ) + result = ser.groupby(pd.Grouper(level="three", freq="ME")).sum() + exp_dti = pd.DatetimeIndex( + [pd.Timestamp("2013-01-31")], freq="ME", name="three" + ).as_unit(unit) + expected = pd.Series( + [28], + index=exp_dti, + ) + tm.assert_series_equal(result, expected) + + # just specifying a level breaks + result = ser.groupby(pd.Grouper(level="one")).sum() + expected = ser.groupby(level="one").sum() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("func", [False, True]) + def test_grouper_returning_tuples(self, func): + # GH 22257 , both with dict and with callable + df = pd.DataFrame({"X": ["A", "B", "A", "B"], "Y": [1, 4, 3, 2]}) + mapping = dict(zip(range(4), [("C", 5), ("D", 6)] * 2, strict=True)) + + if func: + gb = df.groupby(by=lambda idx: mapping[idx], sort=False) + else: + gb = df.groupby(by=mapping, sort=False) + + name, expected = next(iter(gb)) + assert name == ("C", 5) + result = gb.get_group(name) + + tm.assert_frame_equal(result, expected) + + def test_grouper_func_returning_tz_naive(self): + # GH#57192 grouping by a function that strips the tz should give + # tz-naive group keys, not keys re-localized to the original tz + index = pd.date_range("2024-02-01", "2024-02-03", freq="8h", tz="UTC") + df = pd.DataFrame({"A": 1}, index=index) + + gb = df.groupby(by=lambda ts: ts.normalize().tz_convert(None)) + keys = list(gb.groups.keys()) + assert all(key.tz is None for key in keys) + expected = [ + pd.Timestamp("2024-02-01"), + pd.Timestamp("2024-02-02"), + pd.Timestamp("2024-02-03"), + ] + assert keys == 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 = pd.MultiIndex.from_tuples( + [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)] + ) + idx.names = ["outer", "inner"] + df_multi = pd.DataFrame( + {"A": np.arange(6), "B": ["one", "one", "two", "two", "one", "one"]}, + index=idx, + ) + result = df_multi.groupby(["B", pd.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([pd.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", pd.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([pd.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 = pd.MultiIndex.from_tuples( + [(1, 1), (1, 2), (3, 4), (5, 6)], names=idx_names + ) + df = pd.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 = pd.CategoricalIndex(columns, categories=categories, ordered=True) + expected_data = np.array([[4, 2], [4, 2], [4, 2], [4, 2], [4, 2]], int) + expected_columns = pd.CategoricalIndex( + categories, categories=categories, ordered=True + ) + + # test transposed version + df = pd.DataFrame(data.T, index=cat_columns) + result = df.groupby(level=0, observed=observed).sum() + expected = pd.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 = pd.DataFrame( + {"A": 1}, + index=pd.MultiIndex.from_product( + [list("ab"), pd.date_range("20130101", periods=80)], + names=["one", "two"], + ), + ) + result = df.groupby( + [pd.Grouper(level="one"), pd.Grouper(level="two", freq="ME")] + ).sum() + expected = pd.DataFrame( + {"A": [31, 28, 21, 31, 28, 21]}, + index=pd.MultiIndex.from_product( + [list("ab"), pd.date_range("20130101", freq="ME", periods=3)], + names=["one", "two"], + ), + ) + tm.assert_frame_equal(result, expected) + + def test_grouper_iter(self, df): + gb = df.groupby("A") + grouper = gb._grouper + result = sorted(grouper) + expected = ["bar", "foo"] + assert result == expected + + 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") + grouper = grouped._grouper + result = df.groupby(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 = pd.Series({"T1": 5}) + result = s.groupby({"T1": "T2"}).agg("sum") + expected = s.groupby(["T2"]).agg("sum") + tm.assert_series_equal(result, expected) + + s = pd.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"], + [pd.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 = pd.Series([1, 0, 1, 0], index=index, name=("a", "a")) + result = obj.groupby(groups).last() + expected = frame_or_series([4, 3], index=pd.Index([0, 1])) + expected.index.name = ("a", "a") + tm.assert_equal(result, expected) + + def test_groupby_grouper_f_sanity_checked(self): + dates = pd.date_range("01-Jan-2013", periods=12, freq="MS") + ts = pd.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 = pd.DataFrame( + { + "id": ["a", "b"] * 3, + "b": pd.date_range("2000-01-01", "2000-01-03", freq="9h"), + } + ) + grouper = pd.Grouper(key="b", freq="D") + gb = df.groupby([grouper, "id"]) + + # test number of groups + expected = { + (pd.Timestamp("2000-01-01"), "a"): [0, 2], + (pd.Timestamp("2000-01-01"), "b"): [1], + (pd.Timestamp("2000-01-02"), "a"): [4], + (pd.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_negative_level(self, multiindex_dataframe_random_data): + # GH 13901 + result = multiindex_dataframe_random_data.groupby(level=-1).sum() + expected = multiindex_dataframe_random_data.groupby(level="second").sum() + tm.assert_frame_equal(result, expected) + + result = multiindex_dataframe_random_data.groupby(level=-2).sum() + expected = multiindex_dataframe_random_data.groupby(level="first").sum() + tm.assert_frame_equal(result, expected) + + result = multiindex_dataframe_random_data.groupby(level=[-2, -1]).sum() + expected = multiindex_dataframe_random_data.sort_index() + tm.assert_frame_equal(result, expected) + + result = multiindex_dataframe_random_data.groupby(level=[-1, "first"]).sum() + expected = multiindex_dataframe_random_data.groupby( + level=["second", "first"] + ).sum() + tm.assert_frame_equal(result, expected) + + def test_agg_with_dict_raises(self, df): + df.columns = np.arange(len(df.columns)) + msg = "nested renamer is not supported" + with pytest.raises(SpecificationError, 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 = pd.MultiIndex.from_tuples(lst) + + df = pd.DataFrame([[1, "A"]], columns=midx) + + msg = "In a future version, the keys" + grouped = df.groupby("to filter").groups + assert grouped["A"] == [0] + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + grouped = df.groupby([("to filter", "")]).groups + assert grouped["A"] == [0] + + df = pd.DataFrame([[1, "A"], [2, "B"]], columns=midx) + + expected = df.groupby("to filter").groups + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.groupby([("to filter", "")]).groups + assert result == expected + + df = pd.DataFrame([[1, "A"], [2, "A"]], columns=midx) + + expected = df.groupby("to filter").groups + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.groupby([("to filter", "")]).groups + tm.assert_dict_equal(result, expected) + + def test_groupby_multiindex_tuple(self): + # GH 17979, GH#59179 + df = pd.DataFrame( + [[1, 2, 3, 4], [3, 4, 5, 6], [1, 4, 2, 3]], + columns=pd.MultiIndex.from_arrays([["a", "b", "b", "c"], [1, 1, 2, 2]]), + ) + + msg = "In a future version, the keys" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = df.groupby([("b", 1)]).groups + result = df.groupby(("b", 1)).groups + tm.assert_dict_equal(expected, result) + + df2 = pd.DataFrame( + df.values, + columns=pd.MultiIndex.from_arrays( + [["a", "b", "b", "c"], ["d", "d", "e", "e"]] + ), + ) + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = df2.groupby([("b", "d")]).groups + result = df.groupby(("b", 1)).groups + tm.assert_dict_equal(expected, result) + + df3 = pd.DataFrame(df.values, columns=[("a", "d"), ("b", "d"), ("b", "e"), "c"]) + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + 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, GH#59179 + df = pd.DataFrame( + [[1, 2, 3, 4], [3, 4, 5, 6], [1, 4, 2, 3]], + columns=pd.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) + + msg = "In a future version, the keys" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + 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) + + def test_groupby_level(self, sort, multiindex_dataframe_random_data, df): + # GH 17537 + frame = multiindex_dataframe_random_data + 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) + + # 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): + # GH4014 this used to raise ValueError since 'exp'>1 (in py2) + df = pd.DataFrame({"exp": ["A"] * 3 + ["B"] * 3, "var1": range(6)}).set_index( + "exp" + ) + df.groupby(level="exp") + msg = "level name foo is not the name of the index" + with pytest.raises(ValueError, match=msg): + df.groupby(level="foo") + + def test_groupby_duplicate_index_level_names(self): + # GH#49434 + df = pd.DataFrame( + {"a": [1, 1, 2], "b": [3, 4, 5]}, + index=pd.MultiIndex.from_tuples([(1, 1), (1, 2), (1, 3)], names=["f", "f"]), + ) + msg = "Grouping by index level 'f' which matches multiple index levels" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.groupby("f").sum() + expected = pd.DataFrame( + {"a": [4], "b": [12]}, + index=pd.Index([1], name="f"), + ) + tm.assert_frame_equal(result, expected) + + def test_groupby_level_with_nas(self, sort): + # GH 17537 + index = pd.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 = pd.Series(np.arange(8.0), index=index) + result = s.groupby(level=0, sort=sort).sum() + expected = pd.Series([6.0, 22.0], index=[0, 1]) + tm.assert_series_equal(result, expected) + + index = pd.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 = pd.Series(np.arange(8.0), index=index) + result = s.groupby(level=0, sort=sort).sum() + expected = pd.Series([6.0, 18.0], index=[0.0, 1.0]) + tm.assert_series_equal(result, expected) + + def test_groupby_args(self, multiindex_dataframe_random_data): + # PR8618 and issue 8015 + frame = multiindex_dataframe_random_data + + 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, multiindex_dataframe_random_data): + # GH 17537 + grouped = multiindex_dataframe_random_data.groupby(level=0, sort=sort) + exp_labels = np.array(labels, np.intp) + tm.assert_almost_equal(grouped._grouper.ids, exp_labels) + + def test_grouping_labels(self, multiindex_dataframe_random_data): + grouped = multiindex_dataframe_random_data.groupby( + multiindex_dataframe_random_data.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, GH#59179 + df = pd.DataFrame({"date": pd.date_range("1/1/2011", periods=365, freq="D")}) + df.iloc[-1] = pd.NaT + grouper = pd.Grouper(key="date", freq="YS") + msg = "In a future version, the keys" + + # Grouper in a list grouping + gb = df.groupby([grouper]) + expected = {pd.Timestamp("2011-01-01"): pd.Index(list(range(364)))} + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = gb.groups + tm.assert_dict_equal(result, expected) + + # Test case without a list + result = df.groupby(grouper) + expected = {pd.Timestamp("2011-01-01"): 365} + tm.assert_dict_equal(result.groups, expected) + + @pytest.mark.parametrize( + "func,expected", + [ + ( + "transform", + pd.Series(name=2, dtype=np.float64), + ), + ( + "agg", + pd.Series( + name=2, + dtype=np.float64, + index=pd.Index([], dtype=np.float64, name=1), + ), + ), + ( + "apply", + pd.Series( + name=2, + dtype=np.float64, + index=pd.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 = pd.DataFrame({1: [], 2: []}) + g = df.groupby(1, group_keys=True) + result = getattr(g[2], func)(lambda x: x) + tm.assert_series_equal(result, expected) + + def test_groupby_apply_empty_with_group_keys_false(self): + # 60471 + # test apply'ing empty groups with group_keys False + # (not testing other agg fns, because they return + # different index objects. + df = pd.DataFrame({"A": [], "B": [], "C": []}) + g = df.groupby("A", group_keys=False) + result = g.apply(lambda x: x / x.sum()) + expected = pd.DataFrame({"B": [], "C": []}, index=None) + tm.assert_frame_equal(result, expected) + + def test_groupby_empty(self): + # https://github.com/pandas-dev/pandas/issues/27190 + s = pd.Series([], name="name", dtype="float64") + gr = s.groupby([]) + + result = gr.mean() + expected = s.set_axis(pd.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.ids, np.array([], dtype=np.dtype(np.intp)) + ) + + assert gr._grouper.ngroups == 0 + + # check name + gb = s.groupby(s) + grouper = gb._grouper + result = grouper.names + expected = ["name"] + assert result == expected + + def test_groupby_level_index_value_all_na(self): + # issue 20519 + df = pd.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 = pd.DataFrame( + data=[], + index=pd.MultiIndex( + levels=[pd.Index(["x"], dtype="str"), pd.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 = pd.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 = pd.DataFrame( + dtype="float64", + columns=["value"], + index=pd.Index([], dtype=np.int64, name="id"), + ) + tm.assert_frame_equal(result, expected) + + def test_groupby_tuple_keys_handle_multiindex(self): + # https://github.com/pandas-dev/pandas/issues/21340 + df = pd.DataFrame( + { + "num1": [0, 8, 9, 4, 3, 3, 5, 9, 3, 6], + "num2": [3, 8, 6, 4, 9, 2, 1, 7, 0, 9], + "num3": [6, 5, 7, 8, 5, 1, 1, 10, 7, 8], + "category_tuple": [ + (0, 1), + (0, 1), + (0, 1), + (0, 4), + (2, 3), + (2, 3), + (2, 3), + (2, 3), + (5,), + (6,), + ], + "category_string": list("aaabbbbcde"), + } + ) + expected = df.sort_values(by=["category_tuple", "num1"]) + result = df.groupby("category_tuple").apply(lambda x: x.sort_values(by="num1")) + expected = expected[result.columns] + tm.assert_frame_equal(result.reset_index(drop=True), expected) + + def test_groupby_grouper_immutable_list_item(self): + # GH 26564 - prevent 'ValueError: all keys need to be the same shape' + # when reusing a list of groupers + df1 = pd.DataFrame([["05/29/2019"], ["05/28/2019"]], columns=["date"]).assign( + date=lambda df: pd.to_datetime(df["date"]) + ) + df2 = pd.DataFrame(columns=["date"]).assign( + date=lambda df: pd.to_datetime(df["date"]) + ) + + groupers = [pd.Grouper(key="date", freq="1D")] + + df1.groupby(groupers).head() + # no error + df2.groupby(groupers).head() + + +# get_group +# -------------------------------- + + +class TestGetGroup: + def test_get_group(self): + # GH 5267 + # be datelike friendly + df = pd.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(pd.Timestamp(key).to_pydatetime()) + result3 = g.get_group(str(pd.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((pd.Timestamp(key[0]).to_pydatetime(), key[1])) + result3 = g.get_group((str(pd.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 = pd.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 = pd.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 = pd.DataFrame([[(1,), (1, 2), (1,), (1, 2)]], index=["ids"]).T + gr = df.groupby("ids") + expected = pd.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 = pd.DataFrame({"ids": [(x,) for x in dt]}) + gr = df.groupby("ids") + result = gr.get_group(("2010-01-01",)) + expected = pd.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 = pd.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 = pd.Series(data, index, dtype=object) + grouper = pd.Grouper(freq="D") + grouped = series.groupby(grouper) + assert next(iter(grouped), None) is None + + def test_groupby_with_single_column(self): + df = pd.DataFrame({"a": list("abssbab")}) + tm.assert_frame_equal(df.groupby("a").get_group("a"), df.iloc[[0, 5]]) + # GH 13530 + exp = pd.DataFrame( + index=pd.Index(["a", "b", "s"], name="a"), columns=pd.Index([], dtype="str") + ) + 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 = pd.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"]) + msg = "In a future version, the keys" + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + groups = grouped.groups + assert groups is grouped.groups # caching works + + for k, v in 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 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 = pd.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 = pd.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 + groups = {key: gp for key, gp in grouped} # noqa: C416 + assert len(groups) == 2 + + 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 = pd.DataFrame( + {"event": ["start", "start"], "change": [1234, 5678]}, + index=pd.DatetimeIndex(["2014-09-10", "2013-10-10"]), + ) + grouped = df.groupby([pd.Grouper(freq="ME"), "event"]) + assert len(grouped.groups) == 2 + assert grouped.ngroups == 2 + assert (pd.Timestamp("2014-09-30"), "start") in grouped.groups + assert (pd.Timestamp("2013-10-31"), "start") in grouped.groups + + res = grouped.get_group((pd.Timestamp("2014-09-30"), "start")) + tm.assert_frame_equal(res, df.iloc[[0], :]) + res = grouped.get_group((pd.Timestamp("2013-10-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[1], :]) + + df = pd.DataFrame( + {"event": ["start", "start", "start"], "change": [1234, 5678, 9123]}, + index=pd.DatetimeIndex(["2014-09-10", "2013-10-10", "2014-09-15"]), + ) + grouped = df.groupby([pd.Grouper(freq="ME"), "event"]) + assert len(grouped.groups) == 2 + assert grouped.ngroups == 2 + assert (pd.Timestamp("2014-09-30"), "start") in grouped.groups + assert (pd.Timestamp("2013-10-31"), "start") in grouped.groups + + res = grouped.get_group((pd.Timestamp("2014-09-30"), "start")) + tm.assert_frame_equal(res, df.iloc[[0, 2], :]) + res = grouped.get_group((pd.Timestamp("2013-10-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[1], :]) + + # length=3 + df = pd.DataFrame( + {"event": ["start", "start", "start"], "change": [1234, 5678, 9123]}, + index=pd.DatetimeIndex(["2014-09-10", "2013-10-10", "2014-08-05"]), + ) + grouped = df.groupby([pd.Grouper(freq="ME"), "event"]) + assert len(grouped.groups) == 3 + assert grouped.ngroups == 3 + assert (pd.Timestamp("2014-09-30"), "start") in grouped.groups + assert (pd.Timestamp("2013-10-31"), "start") in grouped.groups + assert (pd.Timestamp("2014-08-31"), "start") in grouped.groups + + res = grouped.get_group((pd.Timestamp("2014-09-30"), "start")) + tm.assert_frame_equal(res, df.iloc[[0], :]) + res = grouped.get_group((pd.Timestamp("2013-10-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[1], :]) + res = grouped.get_group((pd.Timestamp("2014-08-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[2], :]) + + def test_grouping_string_repr(self): + # GH 13394 + mi = pd.MultiIndex.from_arrays([list("AAB"), list("aba")]) + df = pd.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 = pd.DataFrame({"a": [1, 1, 2], "b": [1, 1, 2], "c": [3, 4, 5]}).set_index("a") + gb = df.groupby([pd.Grouper(level="a"), pd.Grouper(key="b")], as_index=False) + assert not gb._grouper.groupings[0].in_axis + assert gb._grouper.groupings[1].in_axis + + result = gb.sum() + expected = pd.DataFrame({"a": [1, 2], "b": [1, 2], "c": [7, 5]}) + tm.assert_frame_equal(result, expected) + + +def test_groupby_any_with_timedelta(): + # GH#59712 + df = pd.DataFrame({"value": [pd.Timedelta(1), pd.NaT]}) + + result = df.groupby(np.array([0, 1], dtype=np.int64))["value"].any() + + expected = pd.Series({0: True, 1: False}, name="value", dtype=bool) + expected.index = expected.index.astype(np.int64) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("sort", [True, False]) +@pytest.mark.parametrize( + "idx", + [ + pd.date_range("2020-01-01", periods=5, freq="D"), + pd.date_range("2020-01-05", periods=5, freq="-1D"), + pd.timedelta_range("1 day", periods=5, freq="D"), + pd.timedelta_range("5 days", periods=5, freq="-1D"), + ], +) +def test_groupby_index_with_freq_retains_freq(idx, sort): + # GH#66046 - grouping by a DatetimeIndex/TimedeltaIndex with a freq + # retains the freq on the result index + df = pd.DataFrame({"a": range(5)}) + + result = df.groupby(idx, sort=sort).sum() + + expected_index = idx.sort_values() if sort else idx + assert result.index.freq == expected_index.freq + tm.assert_index_equal(result.index, expected_index) + + +@pytest.mark.parametrize("sort", [True, False]) +@pytest.mark.parametrize("ascending", [True, False]) +@pytest.mark.parametrize( + "klass, values", + [ + ( + pd.DatetimeIndex, + ["2020-01-01", "2020-01-01", "2020-01-03", "2020-01-07"], + ), + (pd.TimedeltaIndex, ["1 day", "1 day", "3 days", "7 days"]), + ], +) +def test_groupby_monotonic_datetimelike_no_freq(klass, values, ascending, sort): + # GH#66046 - monotonic DatetimeIndex/TimedeltaIndex without a freq + # with duplicates + idx = klass(values) + if not ascending: + idx = idx[::-1] + assert idx.freq is None + df = pd.DataFrame({"a": [1, 2, 4, 8]}) + + result = df.groupby(idx, sort=sort).sum() + + if ascending: + expected = pd.DataFrame({"a": [3, 4, 8]}, index=klass(values[1:])) + elif sort: + expected = pd.DataFrame({"a": [12, 2, 1]}, index=klass(values[1:])) + else: + expected = pd.DataFrame({"a": [1, 2, 12]}, index=klass(values[1:])[::-1]) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_index_as_string.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_index_as_string.py new file mode 100644 index 0000000000000000000000000000000000000000..743db7e70b14b7f8c2d047e403884bdbf1b878a4 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_index_as_string.py @@ -0,0 +1,72 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@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 + ], +) +@pytest.mark.parametrize("levels", [["inner"], ["inner", "outer"]]) +def test_grouper_index_level_as_string(levels, key_strs, groupers): + frame = 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"], + } + ) + frame = frame.set_index(levels) + 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(levels): + # Compute expected result + 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"], + } + ) + series = df.set_index(["outer", "inner", "B"])["A"] + 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/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..a3d3f509e186ac8099dd5fd1c50e8265753fe16c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_indexing.py @@ -0,0 +1,310 @@ +# 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) + + +def test_multiindex(): + # Test the multiindex mentioned as the use-case in the documentation + + 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 + + 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)] + + multiindex_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]) + multiindex_data[date] = levels + + df = _make_df_from_data(multiindex_data) + result = df.groupby("Date", as_index=False).nth(slice(3, -3)) + + sliced = {date: values[3:-3] for date, values in multiindex_data.items()} + 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) + + +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/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_libgroupby.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_libgroupby.py new file mode 100644 index 0000000000000000000000000000000000000000..d2e30e0f622caf8dc9341a3c2330781b1353286f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_libgroupby.py @@ -0,0 +1,348 @@ +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 + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize("dtype, rtol", [("float32", 1e-2), ("float64", 1e-5)]) +class TestGroupVar: + def test_group_var_generic_1d(self, dtype, rtol): + prng = np.random.default_rng(2) + + out = (np.nan * np.ones((5, 1))).astype(dtype) + counts = np.zeros(5, dtype="int64") + values = 10 * prng.random((15, 1)).astype(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 + + group_var(out, counts, values, labels) + assert np.allclose(out, expected_out, rtol) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_generic_1d_flat_labels(self, dtype, rtol): + prng = np.random.default_rng(2) + + out = (np.nan * np.ones((1, 1))).astype(dtype) + counts = np.zeros(1, dtype="int64") + values = 10 * prng.random((5, 1)).astype(dtype) + labels = np.zeros(5, dtype="intp") + + expected_out = np.array([[values.std(ddof=1) ** 2]]) + expected_counts = counts + 5 + + group_var(out, counts, values, labels) + + assert np.allclose(out, expected_out, rtol) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_generic_2d_all_finite(self, dtype, rtol): + prng = np.random.default_rng(2) + + out = (np.nan * np.ones((5, 2))).astype(dtype) + counts = np.zeros(5, dtype="int64") + values = 10 * prng.random((10, 2)).astype(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 + + group_var(out, counts, values, labels) + assert np.allclose(out, expected_out, rtol) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_generic_2d_some_nan(self, dtype, rtol): + prng = np.random.default_rng(2) + + out = (np.nan * np.ones((5, 2))).astype(dtype) + counts = np.zeros(5, dtype="int64") + values = 10 * prng.random((10, 2)).astype(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(dtype) + expected_counts = counts + 2 + + group_var(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, dtype, rtol): + # Regression test from GH 10448. + + out = np.array([[np.nan]], dtype=dtype) + counts = np.array([0], dtype="int64") + values = 0.832845131556193 * np.ones((3, 1), dtype=dtype) + labels = np.zeros(3, dtype="intp") + + group_var(out, counts, values, labels) + + assert counts[0] == 3 + assert out[0, 0] >= 0 + tm.assert_almost_equal(out[0, 0], 0.0) + + +def test_group_var_large_inputs(): + dtype = np.float64 + prng = np.random.default_rng(2) + + out = np.array([[np.nan]], dtype=dtype) + counts = np.array([0], dtype="int64") + values = (prng.random((10**6, 1)) + 10**12).astype(dtype) + labels = np.zeros(10**6, dtype="intp") + + group_var(out, counts, values, labels) + + assert counts[0] == 10**6 + tm.assert_almost_equal(out[0, 0], 1.0 / 12, rtol=0.5e-3) + + +@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 pd.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) + + +@pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float32, np.float64]) +@pytest.mark.parametrize( + "pd_op, np_op", + [ + (group_cumsum, np.cumsum), + (group_cumprod, np.cumprod), + ], +) +def test_cython_group_transform(dtype, pd_op, np_op): + # see gh-4095 + 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) + + +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", "ns"), + ], + 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", "ns"), np.timedelta64("NaT", "ns")], + 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_beginning_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_beginning_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, + ) + + +@pytest.mark.parametrize( + "values, expected_values", + [ + (np.finfo(np.float64).max, [[np.inf]]), + (np.finfo(np.float64).min, [[-np.inf]]), + ( + np.complex128(np.finfo(np.float64).min + np.finfo(np.float64).max * 1j), + [[complex(-np.inf, np.inf)]], + ), + ( + np.complex128(np.finfo(np.float64).max + np.finfo(np.float64).min * 1j), + [[complex(np.inf, -np.inf)]], + ), + ( + np.complex128(np.finfo(np.float64).max + np.finfo(np.float64).max * 1j), + [[complex(np.inf, np.inf)]], + ), + ( + np.complex128(np.finfo(np.float64).min + np.finfo(np.float64).min * 1j), + [[complex(-np.inf, -np.inf)]], + ), + ( + np.complex128(3.0 + np.finfo(np.float64).min * 1j), + [[complex(9.0, -np.inf)]], + ), + ( + np.complex128(np.finfo(np.float64).max + 3 * 1j), + [[complex(np.inf, 9.0)]], + ), + ], +) +def test_cython_group_sum_overflow(values, expected_values): + # GH-60303 + data = np.array([[values] for _ in range(3)]) + labels = np.array([0, 0, 0], dtype=np.intp) + counts = np.array([0], dtype="int64") + + expected = np.array(expected_values, dtype=values.dtype) + actual = np.zeros_like(expected) + + group_sum(actual, counts, data, labels, None, is_datetimelike=False) + + tm.assert_numpy_array_equal(actual, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_missing.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_missing.py new file mode 100644 index 0000000000000000000000000000000000000000..4f5d7d10c26b3db613488f1405b5b1b522803190 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_missing.py @@ -0,0 +1,87 @@ +import numpy as np +import pytest + +import pandas as pd +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 = pd.DataFrame( + [[1, 1.0, -1.0], [1, np.nan, np.nan], [1, 2.0, -2.0]], + columns=pd.Index(["type", "a", "b"], name="idx"), + ) + df_grouped = df.groupby(["type"])[["a", "b"]] + result = getattr(df_grouped, func)().columns + expected = pd.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 = pd.DataFrame({"field1": [1, 3, 4], "field2": [1, 3, 4]}) + df2 = pd.DataFrame({"field1": [1, np.nan, 4]}) + df_grouped = pd.concat([df1, df2], axis=1).groupby(by=["field2"]) + expected = pd.DataFrame( + [[1, 1.0], [3, np.nan], [4, 4.0]], columns=["field1", "field1"] + ) + result = getattr(df_grouped, func)() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("method", ["ffill", "bfill"]) +@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 = pd.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 = pd.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 = pd.DataFrame( + {"b": [value], "c": [np.nan]}, index=pd.Index([1], name="a") + ) + tm.assert_frame_equal(result, expected) + + +def test_indices_with_missing(): + # GH 9304 + df = pd.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/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_numba.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_numba.py new file mode 100644 index 0000000000000000000000000000000000000000..4069850386a52225dbf1baf6e524350b5665b1a7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_numba.py @@ -0,0 +1,78 @@ +import pytest + +from pandas.compat import is_platform_arm + +import pandas as pd +import pandas._testing as tm +from pandas.util.version import Version + +pytestmark = [pytest.mark.single_cpu] + +numba = pytest.importorskip("numba") +pytestmark.append( + pytest.mark.skipif( + Version(numba.__version__) == Version("0.61") and is_platform_arm(), + reason=f"Segfaults on ARM platforms with numba {numba.__version__}", + ) +) + + +@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, numba_supported_reductions + ): + func, kwargs = numba_supported_reductions + df = pd.DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)}) + engine_kwargs = {"nogil": nogil, "parallel": parallel} + 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, numba_supported_reductions + ): + func, kwargs = numba_supported_reductions + df = pd.DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)}) + engine_kwargs = {"nogil": nogil, "parallel": parallel} + 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, numba_supported_reductions + ): + func, kwargs = numba_supported_reductions + ser = pd.Series(range(3), index=[1, 2, 1], name="foo") + engine_kwargs = {"nogil": nogil, "parallel": parallel} + 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 = pd.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_no_engine_doesnt_raise(self): + # GH55520 + df = pd.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 pd.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/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_numeric_only.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_numeric_only.py new file mode 100644 index 0000000000000000000000000000000000000000..f81becd966ba8c9f45db507704fc0d932524dbce --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_numeric_only.py @@ -0,0 +1,437 @@ +import re + +import pytest + +from pandas._libs import lib +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +class TestNumericOnly: + # make sure that we are passing thru kwargs to our agg functions + + @pytest.fixture + def df(self): + # GH3668 + # GH5724 + df = pd.DataFrame( + { + "group": [1, 1, 2], + "int": [1, 2, 3], + "float": [4.0, 5.0, 6.0], + "string": pd.Series(["a", "b", "c"], dtype="str"), + "object": pd.Series(["a", "b", "c"], dtype=object), + "category_string": pd.Series(list("abc")).astype("category"), + "category_int": [7, 8, 9], + "datetime": pd.date_range("20130101", periods=3), + "datetimetz": pd.date_range("20130101", periods=3, tz="US/Eastern"), + "timedelta": pd.timedelta_range("1 s", periods=3, freq="s"), + }, + columns=[ + "group", + "int", + "float", + "string", + "object", + "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 = pd.Index(["int", "float", "category_int"]) + + gb = df.groupby("group") + expected = pd.DataFrame( + { + "category_int": [7.5, 9], + "float": [4.5, 6.0], + "timedelta": [pd.Timedelta("1.5s"), pd.Timedelta("3s")], + "int": [1.5, 3], + "datetime": [ + pd.Timestamp("2013-01-01 12:00:00"), + pd.Timestamp("2013-01-03 00:00:00"), + ], + "datetimetz": [ + pd.Timestamp("2013-01-01 12:00:00", tz="US/Eastern"), + pd.Timestamp("2013-01-03 00:00:00", tz="US/Eastern"), + ], + }, + index=pd.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 = pd.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 = pd.Index( + [ + "int", + "float", + "string", + "object", + "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 = pd.Index(["int", "float", "category_int"]) + expected_columns = pd.Index( + ["int", "float", "string", "category_int", "timedelta"] + ) + if method == "cumsum": + # cumsum loses string + expected_columns = pd.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 = pd.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 = pd.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, TypeError) 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", + f"dtype 'str' does not support operation '{method}'", + ] + ) + 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]"), + re.escape(f"agg function failed [how->{method},dtype->string]"), + f"dtype 'str' does not support operation '{method}'", + ] + ) + 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]"), + re.escape(f"agg function failed [how->{method},dtype->string]"), + f"dtype 'str' does not support operation '{method}'", + ] + ) + 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) + + +@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), + ("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), + ("kurt", 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 = pd.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 + if kernel == "corrwith": + warn = Pandas4Warning + msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + msg = "" + with tm.assert_produces_warning(warn, match=msg): + 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", "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", + "must be a string or a real number", + "unsupported operand type", + "function is not implemented for this dtype", + re.escape(f"agg function failed [how->{kernel},dtype->object]"), + ] + ) + if kernel == "quantile": + msg = "dtype 'object' does not support operation 'quantile'" + elif 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): + if kernel == "corrwith": + warn = Pandas4Warning + msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + msg = "" + with tm.assert_produces_warning(warn, 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 = pd.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 = pd.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", + "kurt", + ) + + # 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 = "dtype 'object' does not support operation 'quantile'" + 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", + "kurt", + "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", + "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 = "Cannot use quantile with bool dtype" + with pytest.raises(TypeError, match=msg): + # GH#51424 + method(*args, numeric_only=False) + else: + result = method(*args, numeric_only=True) + expected = method(*args, numeric_only=False) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_pipe.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..9025b5e971ecec99b8ae86d6d5f5d43795409589 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_pipe.py @@ -0,0 +1,76 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +def test_pipe(): + # Test the pipe method of DataFrameGroupBy. + # Issue #17871 + + random_state = np.random.default_rng(2) + + df = pd.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 = pd.Index(["bar", "foo"], 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 = pd.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 = pd.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=pd.Index([1, 2, 3], dtype=np.int64)) + + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_raises.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_raises.py new file mode 100644 index 0000000000000000000000000000000000000000..104f4f2997453b385db140e7310d9d581bd34e69 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_raises.py @@ -0,0 +1,689 @@ +# 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.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +@pytest.fixture( + params=[ + "a", + ["a"], + ["a", "b"], + pd.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], strict=True)), + pd.Series([1, 1, 1, 1, 1, 2, 2, 2, 2]), + [ + pd.Series([1, 1, 1, 1, 1, 2, 2, 2, 2]), + pd.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 = pd.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 = pd.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_cat_col(): + df = pd.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": pd.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, warn_category=None, warn_msg="" +): + with tm.assert_produces_warning( + warn_category, match=warn_msg, check_stacklevel=False + ): + 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, using_infer_string +): + 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, ""), + "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, "dtype 'object' does not support operation 'quantile'"), + "rank": (None, ""), + "sem": (ValueError, "could not convert string to float"), + "shift": (None, ""), + "size": (None, ""), + "skew": (ValueError, "could not convert string to float"), + "kurt": (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->"), + ), + }[groupby_func] + + if using_infer_string: + if groupby_func in [ + "prod", + "mean", + "median", + "cumsum", + "cumprod", + "std", + "sem", + "var", + "skew", + "kurt", + "quantile", + ]: + msg = f"dtype 'str' does not support operation '{groupby_func}'" + if groupby_func in ["sem", "std", "skew", "kurt"]: + # The object-dtype raises ValueError when trying to convert to numeric. + klass = TypeError + elif groupby_func == "pct_change" and df["d"].dtype.storage == "pyarrow": + # This doesn't go through EA._groupby_op so the message isn't controlled + # there. + msg = "operation 'truediv' not supported for dtype 'str' with dtype 'str'" + elif groupby_func == "diff" and df["d"].dtype.storage == "pyarrow": + # This doesn't go through EA._groupby_op so the message isn't controlled + # there. + msg = "operation 'sub' not supported for dtype 'str' with dtype 'str'" + + elif groupby_func in ["cummin", "cummax"]: + msg = msg.replace("object", "str") + elif groupby_func == "corrwith": + msg = "Cannot perform reduction 'mean' with string dtype" + + if groupby_func == "corrwith": + warn_category = Pandas4Warning + warn_msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn_category = None + warn_msg = "" + _call_and_check(klass, msg, how, gb, groupby_func, args, warn_category, warn_msg) + + +@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, + using_infer_string, +): + # 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, + "Could not convert .* to numeric|" + "Cannot perform reduction 'mean' with string dtype", + ), + }[groupby_func_np] + + if using_infer_string: + if groupby_func_np is np.mean: + klass = TypeError + msg = f"Cannot perform reduction '{groupby_func_np.__name__}' with string dtype" + + _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": (TypeError, "'all' with datetime64 dtypes is not supported"), + "any": (TypeError, "'any' with datetime64 dtypes is not supported"), + "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 operation 'cumprod'"), + "cumsum": (TypeError, "datetime64 type does not support operation 'cumsum'"), + "diff": (None, ""), + "ffill": (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 operation 'prod'"), + "quantile": (None, ""), + "rank": (None, ""), + "sem": (None, ""), + "shift": (None, ""), + "size": (None, ""), + "skew": ( + TypeError, + "|".join( + [ + r"dtype datetime64\[ns\] does not support operation", + "datetime64 type does not support operation 'skew'", + ] + ), + ), + "kurt": ( + TypeError, + "|".join( + [ + r"dtype datetime64\[ns\] does not support operation", + "datetime64 type does not support operation 'kurt'", + ] + ), + ), + "std": (None, ""), + "sum": (TypeError, "datetime64 type does not support operation 'sum"), + "var": (TypeError, "datetime64 type does not support operation 'var'"), + }[groupby_func] + + if groupby_func == "corrwith": + warn_category = Pandas4Warning + warn_msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn_category = None + warn_msg = "" + _call_and_check(klass, msg, how, gb, groupby_func, args, warn_category, warn_msg) + + +@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, + re.escape("datetime64[us] does not support operation 'sum'"), + ), + np.mean: (None, ""), + }[groupby_func_np] + _call_and_check(klass, msg, how, gb, groupby_func_np, ()) + + +@pytest.mark.parametrize( + "func", ["any", "all", "std", "sem", "skew", "idxmin", "idxmax"] +) +def test_groupby_raises_interval(func): + # GH#69717 used to raise NotImplementedError + ser = pd.Series(pd.interval_range(0, 4)) + with pytest.raises(TypeError, match=f"{func} is not supported for interval"): + getattr(ser.groupby([0, 0, 1, 1]), func)() + + +@pytest.mark.parametrize("func", ["prod", "cumprod", "skew", "kurt", "var"]) +def test_groupby_raises_timedelta(func): + df = pd.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), + } + ) + 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, 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, ""), + "first": (None, ""), + "idxmax": (None, ""), + "idxmin": (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, + 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, + "category dtype does not support aggregation 'sem'", + ), + "shift": (None, ""), + "size": (None, ""), + "skew": ( + TypeError, + "category type does not support skew operations", + ), + "kurt": ( + TypeError, + "category type does not support kurt operations", + ), + "std": ( + TypeError, + "category dtype does not support aggregation 'std'", + ), + "sum": (TypeError, "category type does not support sum operations"), + "var": ( + TypeError, + "category dtype does not support aggregation 'var'", + ), + }[groupby_func] + + if groupby_func == "corrwith": + warn_category = Pandas4Warning + warn_msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn_category = None + warn_msg = "" + _call_and_check(klass, msg, how, gb, groupby_func, args, warn_category, warn_msg) + + +@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, "dtype category does not support operation 'sum'"), + np.mean: ( + TypeError, + "dtype category does not support operation 'mean'", + ), + }[groupby_func_np] + _call_and_check(klass, msg, how, gb, groupby_func_np, ()) + + +@pytest.mark.filterwarnings("ignore:In a future version, the keys") +@pytest.mark.parametrize("how", ["method", "agg", "transform"]) +def test_groupby_raises_category_on_category( + how, + by, + groupby_series, + groupby_func, + observed, + df_with_cat_col, +): + # GH#50749 + df = df_with_cat_col + df["a"] = pd.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 = not observed and any(group.empty for group in gb.groups.values()) + if how == "transform": + # empty groups will be ignored + empty_groups = False + + 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, ""), + "first": (None, ""), + "idxmax": (ValueError, "empty group due to unobserved categories") + if empty_groups + else (None, ""), + "idxmin": (ValueError, "empty group due to unobserved categories") + 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, "No matching signature found"), + "rank": (None, ""), + "sem": ( + TypeError, + "category dtype does not support aggregation 'sem'", + ), + "shift": (None, ""), + "size": (None, ""), + "skew": ( + TypeError, + "category type does not support skew operations", + ), + "kurt": ( + TypeError, + "category type does not support kurt operations", + ), + "std": ( + TypeError, + "category dtype does not support aggregation 'std'", + ), + "sum": (TypeError, "category type does not support sum operations"), + "var": ( + TypeError, + "category dtype does not support aggregation 'var'", + ), + }[groupby_func] + + if groupby_func == "corrwith": + warn_category = Pandas4Warning + warn_msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn_category = None + warn_msg = "" + _call_and_check(klass, msg, how, gb, groupby_func, args, warn_category, warn_msg) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_reductions.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_reductions.py new file mode 100644 index 0000000000000000000000000000000000000000..36d3cdb150fc61ef9e5e112a3dabc11f1fa81a07 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_reductions.py @@ -0,0 +1,1877 @@ +import builtins +import datetime as dt +from decimal import Decimal +from string import ascii_lowercase + +import numpy as np +import pytest + +from pandas._libs.tslibs import iNaT +import pandas.util._test_decorators as td + +from pandas.core.dtypes.common import pandas_dtype +from pandas.core.dtypes.missing import na_value_for_dtype + +import pandas as pd +import pandas._testing as tm +from pandas.tests.extension.decimal import DecimalArray +from pandas.tests.groupby import get_groupby_method_args + + +@pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"]) +def test_basic_aggregations(dtype): + data = pd.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 + + agged = grouped.aggregate(np.mean) + assert agged[1] == 1 + + expected = grouped.agg(np.mean) + tm.assert_series_equal(agged, expected) # shorthand + tm.assert_series_equal(agged, grouped.mean()) + result = grouped.sum() + expected = grouped.agg(np.sum) + if dtype == "int32": + # NumPy's sum returns int64 + expected = expected.astype("int32") + 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) + result = value_grouped.aggregate(np.mean) + tm.assert_series_equal(result, agged, check_index_type=False) + + # complex agg + agged = grouped.aggregate([np.mean, np.std]) + + msg = r"nested renamer is not supported" + with pytest.raises(pd.errors.SpecificationError, match=msg): + grouped.aggregate({"one": np.mean, "two": np.std}) + + # corner cases + result = grouped.aggregate(lambda x: x * 2) + expected = pd.Series( + [ + (data[data.index // 3 == 0] * 2).to_numpy(), + (data[data.index // 3 == 1] * 2).to_numpy(), + (data[data.index // 3 == 2] * 2).to_numpy(), + ], + index=pd.Index([0, 1, 2], dtype="intp"), + ) + tm.assert_series_equal(result, expected) + + +@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, all_boolean_reductions, vals): + df = pd.DataFrame({"key": ["a"] * 3 + ["b"] * 3, "val": vals * 2}) + + # Figure out expectation using Python builtin + exp = getattr(builtins, all_boolean_reductions)(vals) + + # edge case for missing data with skipna and 'any' + if skipna and all(pd.isna(vals)) and all_boolean_reductions == "any": + exp = False + + expected = pd.DataFrame( + [exp] * 2, columns=["val"], index=pd.Index(["a", "b"], name="key") + ) + result = getattr(df.groupby("key"), all_boolean_reductions)(skipna=skipna) + tm.assert_frame_equal(result, expected) + + +def test_any(): + df = pd.DataFrame( + [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], + columns=["A", "B", "C"], + ) + expected = pd.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) + + +def test_bool_aggs_dup_column_labels(all_boolean_reductions): + # GH#21668 + df = pd.DataFrame([[True, True]], columns=["a", "a"]) + grp_by = df.groupby([0]) + result = getattr(grp_by, all_boolean_reductions)() + + expected = df.set_axis(np.array([0])) + tm.assert_frame_equal(result, expected) + + +@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(all_boolean_reductions, skipna, data): + # GH#37506 + ser = pd.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, all_boolean_reductions)(skipna=skipna) + expected = pd.Series(expected_data, index=np.array([0]), dtype="boolean") + + result = ser.groupby([0, 0, 0]).agg(all_boolean_reductions, 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 + data1 = [1.0, np.nan] if dtype1.startswith("f") else [1.0, pd.NA] + data2 = [1.0, np.nan] if dtype2.startswith("f") else [1.0, pd.NA] + df = pd.DataFrame( + {"col1": pd.array(data1, dtype=dtype1), "col2": pd.array(data2, dtype=dtype2)} + ) + result = df.groupby([1, 1]).agg("all", skipna=False) + + expected = pd.DataFrame({"col1": exp_col1, "col2": exp_col2}, index=np.array([1])) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"]) +def test_masked_bool_aggs_skipna( + all_boolean_reductions, dtype, skipna, frame_or_series +): + # GH#40585 + obj = frame_or_series([pd.NA, 1], dtype=dtype) + expected_res = True + if not skipna and all_boolean_reductions == "all": + expected_res = pd.NA + expected = frame_or_series([expected_res], index=np.array([1]), dtype="boolean") + + result = obj.groupby([1, 1]).agg(all_boolean_reductions, 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) + + +def test_object_NA_raises_with_skipna_false(all_boolean_reductions): + # GH#37501 + ser = pd.Series([pd.NA], dtype=object) + with pytest.raises(TypeError, match="boolean value of NA is ambiguous"): + ser.groupby([1]).agg(all_boolean_reductions, skipna=False) + + +def test_empty(frame_or_series, all_boolean_reductions): + # GH 45231 + kwargs = {"columns": ["a"]} if frame_or_series is pd.DataFrame else {"name": "a"} + obj = frame_or_series(**kwargs, dtype=object) + result = getattr(obj.groupby(obj.index), all_boolean_reductions)() + expected = frame_or_series(**kwargs, dtype=bool) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("method,fill_value", [("any", False), ("all", True)]) +def test_numpy_bool_unobserved_categorical_group_returns_identity(method, fill_value): + # GH#65100 + key = pd.Categorical(["A", "B"], categories=["A", "B", "C"]) + ser = pd.Series(np.array([True, False], dtype=bool)) + + result = getattr(ser.groupby(key, observed=False), method)() + + expected = pd.Series( + [True, False, fill_value], + index=pd.CategoricalIndex(["A", "B", "C"], categories=["A", "B", "C"]), + dtype=bool, + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmin", "idxmax"]) +def test_idxmin_idxmax_extremes(how, any_real_numpy_dtype): + # GH#57040 + if any_real_numpy_dtype is int or any_real_numpy_dtype is float: + # No need to test + return + info = np.iinfo if "int" in any_real_numpy_dtype else np.finfo + min_value = info(any_real_numpy_dtype).min + max_value = info(any_real_numpy_dtype).max + df = pd.DataFrame( + {"a": [2, 1, 1, 2], "b": [min_value, max_value, max_value, min_value]}, + dtype=any_real_numpy_dtype, + ) + gb = df.groupby("a") + result = getattr(gb, how)() + expected = pd.DataFrame( + {"b": [1, 0]}, index=pd.Index([1, 2], name="a", dtype=any_real_numpy_dtype) + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmin", "idxmax"]) +def test_idxmin_idxmax_extremes_skipna(skipna, how, float_numpy_dtype): + # GH#57040 + min_value = np.finfo(float_numpy_dtype).min + max_value = np.finfo(float_numpy_dtype).max + df = pd.DataFrame( + { + "a": pd.Series(np.repeat(range(1, 5), repeats=2), dtype="intp"), + "b": pd.Series( + [ + np.nan, + min_value, + np.nan, + max_value, + min_value, + np.nan, + max_value, + np.nan, + ], + dtype=float_numpy_dtype, + ), + }, + ) + gb = df.groupby("a") + + if not skipna: + msg = f"{how} with skipna=False" + with pytest.raises(ValueError, match=msg): + getattr(gb, how)(skipna=skipna) + return + result = getattr(gb, how)(skipna=skipna) + expected = pd.DataFrame( + {"b": [1, 3, 4, 6]}, index=pd.Index(range(1, 5), name="a", dtype="intp") + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmin", "idxmax"]) +@pytest.mark.parametrize("dtype", ["int64", "float64", "Int64", "Float64"]) +def test_idxmin_idxmax_skipna_false_no_na(how, dtype): + # GH#56903 with skipna=False and no NA values, the group_idxmin_idxmax + # kernel previously skipped every group and returned the all-NA sentinel. + df = pd.DataFrame( + {"a": [1, 1, 2, 2, 2], "b": [3, 1, 4, 9, 2]}, + index=[10, 11, 12, 13, 14], + ).astype({"b": dtype}) + gb = df.groupby("a") + result = getattr(gb, how)(skipna=False) + # No NA is present, so skipna is irrelevant; result must match skipna=True. + expected = getattr(gb, how)(skipna=True) + tm.assert_frame_equal(result, 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 = pd.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 = pd.DataFrame(values, index=pd.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) + + +@pytest.mark.parametrize( + "data", + [ + ( + pd.Timestamp("2011-01-15 12:50:28.502376"), + pd.Timestamp("2011-01-20 12:50:28.593448"), + ), + (24650000000000001, 24650000000000002), + ], +) +@pytest.mark.parametrize("method", ["count", "min", "max", "first", "last"]) +def test_groupby_non_arithmetic_agg_int_like_precision(method, data): + # GH#6620, GH#9311 + df = pd.DataFrame({"a": [1, 1], "b": data}) + + grouped = df.groupby("a") + result = getattr(grouped, method)() + if method == "count": + expected_value = 2 + elif method == "first": + expected_value = data[0] + elif method == "last": + expected_value = data[1] + else: + expected_value = getattr(df["b"], method)() + expected = pd.DataFrame({"b": [expected_value]}, index=pd.Index([1], name="a")) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["first", "last"]) +def test_first_last_skipna(any_real_nullable_dtype, sort, skipna, how): + # GH#57019 + na_value = na_value_for_dtype(pandas_dtype(any_real_nullable_dtype)) + df = pd.DataFrame( + { + "a": [2, 1, 1, 2, 3, 3], + # TODO: test that has mixed na_value and NaN either working for + # float or raising for int? + "b": [na_value, 3.0, na_value, 4.0, na_value, na_value], + "c": [na_value, 3.0, na_value, 4.0, na_value, na_value], + }, + dtype=any_real_nullable_dtype, + ) + gb = df.groupby("a", sort=sort) + method = getattr(gb, how) + result = method(skipna=skipna) + + ilocs = { + ("first", True): [3, 1, 4], + ("first", False): [0, 1, 4], + ("last", True): [3, 1, 5], + ("last", False): [3, 2, 5], + }[how, skipna] + expected = df.iloc[ilocs].set_index("a") + if sort: + expected = expected.sort_index() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["first", "last"]) +def test_first_last_ea_min_count(any_real_nullable_dtype, how): + # GH#57591 + na_val = na_value_for_dtype(pandas_dtype(any_real_nullable_dtype)) + df = pd.DataFrame( + { + "a": [1, 1, 2, 2, 3], + "b": pd.array([1, 2, na_val, na_val, 5], dtype=any_real_nullable_dtype), + }, + ) + gb = df.groupby("a") + result = getattr(gb, how)(min_count=2) + + # Group 1 has 2 valid values -> passes min_count=2 + # Group 2 has 0 valid values -> fails min_count=2 + # Group 3 has 1 valid value -> fails min_count=2 + if how == "first": + expected_vals = pd.array([1, na_val, na_val], dtype=any_real_nullable_dtype) + else: + expected_vals = pd.array([2, na_val, na_val], dtype=any_real_nullable_dtype) + expected = pd.DataFrame( + {"b": expected_vals}, + index=pd.Index([1, 2, 3], name="a"), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["first", "last"]) +def test_first_last_ea_all_na_group(how): + # GH#57591 + df = pd.DataFrame( + { + "a": [1, 1, 2, 2], + "b": pd.array([pd.NA, pd.NA, 3, 4], dtype="Int64"), + }, + ) + result = getattr(df.groupby("a"), how)() + if how == "first": + expected_vals = pd.array([pd.NA, 3], dtype="Int64") + else: + expected_vals = pd.array([pd.NA, 4], dtype="Int64") + expected = pd.DataFrame( + {"b": expected_vals}, + index=pd.Index([1, 2], name="a"), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["first", "last"]) +@pytest.mark.parametrize("skipna", [True, False]) +def test_first_last_skipna_ea_types(how, skipna): + # GH#57591 - test skipna with various non-numeric EA types + intervals = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3]) + cat_dtype = pd.CategoricalDtype(categories=["b", "c"]) + df = pd.DataFrame( + { + "g": [1, 1, 2], + "cat": pd.Categorical([pd.NA, "b", "c"], dtype=cat_dtype), + "interval": intervals, + }, + ) + result = getattr(df.groupby("g"), how)(skipna=skipna) + + if how == "first" and not skipna: + # cat column: first element is NA, skipna=False keeps it + expected = pd.DataFrame( + { + "cat": pd.Categorical([pd.NA, "c"], dtype=cat_dtype), + "interval": intervals[[0, 2]], + }, + index=pd.Index([1, 2], name="g"), + ) + elif how == "first": + expected = pd.DataFrame( + { + "cat": pd.Categorical(["b", "c"], dtype=cat_dtype), + "interval": intervals[[0, 2]], + }, + index=pd.Index([1, 2], name="g"), + ) + elif how == "last": + expected = pd.DataFrame( + { + "cat": pd.Categorical(["b", "c"], dtype=cat_dtype), + "interval": intervals[[1, 2]], + }, + index=pd.Index([1, 2], name="g"), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["min", "max"]) +@pytest.mark.parametrize( + "dtype", + [object, "str", pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow"))], +) +def test_min_max_skipna_false_string_dtypes(how, dtype): + # GH#18588: string and object dtypes have no cython group_min_max, so they + # reduce through the pure-python fallback, which used to drop skipna + df = pd.DataFrame( + {"g": [1, 1, 2, 2], "v": pd.Series(["a", None, "y", "z"], dtype=dtype)} + ) + result = getattr(df.groupby("g")["v"], how)(skipna=False) + expected = pd.Series( + # np.nan rather than None: each group reduces to a scalar NA, which + # matters when "str" is plain object + [np.nan, "y" if how == "min" else "z"], + # the fallback re-infers an object result, so strings come back as str + dtype="str" if dtype is object else dtype, + index=pd.Index([1, 2], name="g"), + name="v", + ) + tm.assert_series_equal(result, expected) + + +def test_prod_skipna_false_object(): + # GH#4147/GH#18588: object has no cython group_prod, so it takes the + # pure-python fallback, which dropped skipna; the underlying Series.prod + # then raised on the object NA. (object *sum* has a cython implementation + # and already honoured skipna.) + df = pd.DataFrame( + {"g": [1, 1, 2, 2], "v": pd.Series([2, None, 3, 4], dtype=object)} + ) + result = df.groupby("g")["v"].prod(skipna=False) + assert pd.isna(result.loc[1]) + assert result.loc[2] == 12 + + +@pytest.mark.parametrize("how", ["sum", "prod"]) +def test_sum_prod_skipna_false_ea_fallback(how): + # GH#18588: an extension dtype whose _groupby_op raises NotImplementedError + # reduces through the same fallback for sum as well as prod + values = DecimalArray( + [Decimal(2), Decimal("NaN"), Decimal(3), Decimal(4)], + ) + df = pd.DataFrame({"g": [1, 1, 2, 2], "v": values}) + result = getattr(df.groupby("g")["v"], how)(skipna=False) + assert pd.isna(result.loc[1]) + assert result.loc[2] == (7 if how == "sum" else 12) + + +@pytest.mark.parametrize("how", ["min", "max"]) +def test_min_max_skipna_false_frame_object_block(how): + # GH#18588: DataFrameGroupBy on an object column reaches _agg_py_fallback + # through its 2D branch, unlike the 1D SeriesGroupBy one. That branch also + # keeps object dtype rather than re-inferring str, as it does for skipna=True. + df = pd.DataFrame( + {"g": [1, 1, 2, 2], "v": pd.Series(["a", None, "y", "z"], dtype=object)} + ) + result = getattr(df.groupby("g"), how)(skipna=False) + expected = pd.DataFrame( + {"v": [np.nan, "y" if how == "min" else "z"]}, + index=pd.Index([1, 2], name="g"), + dtype=object, + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["min", "max"]) +def test_min_max_skipna_false_interval_dtype(how): + # GH#18588: any EA whose _groupby_op raises NotImplementedError takes the + # same pure-python fallback + intervals = pd.arrays.IntervalArray.from_tuples([(0, 1), None, (2, 3), (4, 5)]) + df = pd.DataFrame({"g": [1, 1, 2, 2], "v": intervals}) + result = getattr(df.groupby("g")["v"], how)(skipna=False) + expected = pd.Series( + pd.arrays.IntervalArray.from_tuples([None, (2, 3) if how == "min" else (4, 5)]), + index=pd.Index([1, 2], name="g"), + name="v", + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_mean_no_overflow(): + # Regression test for (#22487) + df = pd.DataFrame( + { + "user": ["A", "A", "A", "A", "A"], + "connections": [4970, 4749, 4719, 4704, 18446744073699999744], + } + ) + assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840 + + +def test_mean_on_timedelta(): + # GH 17382 + df = pd.DataFrame({"time": pd.to_timedelta(range(10)), "cat": ["A", "B"] * 5}) + result = df.groupby("cat")["time"].mean() + expected = pd.Series( + pd.to_timedelta([4, 5]), name="time", index=pd.Index(["A", "B"], name="cat") + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "values, dtype, result_dtype", + [ + ([0, 1, np.nan, 3, 4, 5, 6, 7, 8, 9], "float64", "float64"), + ([0, 1, pd.NA, 3, 4, 5, 6, 7, 8, 9], "Float64", "Float64"), + ([0, 1, pd.NA, 3, 4, 5, 6, 7, 8, 9], "Int64", "Float64"), + ([0, 1, np.nan, 3, 4, 5, 6, 7, 8, 9], "timedelta64[ns]", "timedelta64[ns]"), + ( + pd.to_datetime( + [ + "2019-05-09", + pd.NaT, + "2019-05-11", + "2019-05-12", + "2019-05-13", + "2019-05-14", + "2019-05-15", + "2019-05-16", + "2019-05-17", + "2019-05-18", + ] + ), + "datetime64[ns]", + "datetime64[ns]", + ), + ], +) +def test_mean_skipna(values, dtype, result_dtype, skipna): + # GH#15675 + df = pd.DataFrame( + { + "val": values, + "cat": ["A", "B"] * 5, + } + ).astype({"val": dtype}) + # We need to recast the expected values to the result_dtype because + # Series.mean() changes the dtype to float64/object depending on the input dtype + expected = ( + df.groupby("cat")["val"] + .apply(lambda x: x.mean(skipna=skipna)) + .astype(result_dtype) + ) + result = df.groupby("cat")["val"].mean(skipna=skipna) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "values, dtype", + [ + ([0, 1, np.nan, 3, 4, 5, 6, 7, 8, 9], "float64"), + ([0, 1, pd.NA, 3, 4, 5, 6, 7, 8, 9], "Float64"), + ([0, 1, pd.NA, 3, 4, 5, 6, 7, 8, 9], "Int64"), + ([0, 1, np.nan, 3, 4, 5, 6, 7, 8, 9], "timedelta64[ns]"), + ], +) +def test_sum_skipna(values, dtype, skipna): + # GH#15675 + df = pd.DataFrame( + { + "val": values, + "cat": ["A", "B"] * 5, + } + ).astype({"val": dtype}) + # We need to recast the expected values to the original dtype because + # Series.sum() changes the dtype + expected = ( + df.groupby("cat")["val"].apply(lambda x: x.sum(skipna=skipna)).astype(dtype) + ) + result = df.groupby("cat")["val"].sum(skipna=skipna) + tm.assert_series_equal(result, expected) + + +def test_sum_skipna_object(skipna): + # GH#15675 + df = pd.DataFrame( + { + "val": ["a", "b", np.nan, "d", "e", "f", "g", "h", "i", "j"], + "cat": ["A", "B"] * 5, + } + ).astype({"val": object}) + if skipna: + expected = pd.Series( + ["aegi", "bdfhj"], index=pd.Index(["A", "B"], name="cat"), name="val" + ).astype(object) + else: + expected = pd.Series( + [np.nan, "bdfhj"], index=pd.Index(["A", "B"], name="cat"), name="val" + ).astype(object) + result = df.groupby("cat")["val"].sum(skipna=skipna) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "func, values, dtype, result_dtype", + [ + ("prod", [0, 1, 3, np.nan, 4, 5, 6, 7, -8, 9], "float64", "float64"), + ("prod", [0, -1, 3, 4, 5, pd.NA, 6, 7, 8, 9], "Float64", "Float64"), + ("prod", [0, 1, 3, -4, 5, 6, 7, -8, pd.NA, 9], "Int64", "Int64"), + ("prod", [np.nan] * 10, "float64", "float64"), + ("prod", [pd.NA] * 10, "Float64", "Float64"), + ("prod", [pd.NA] * 10, "Int64", "Int64"), + ("var", [0, -1, 3, 4, np.nan, 5, 6, 7, 8, 9], "float64", "float64"), + ("var", [0, 1, 3, -4, 5, 6, 7, -8, 9, pd.NA], "Float64", "Float64"), + ("var", [0, -1, 3, 4, 5, -6, 7, pd.NA, 8, 9], "Int64", "Float64"), + ("var", [np.nan] * 10, "float64", "float64"), + ("var", [pd.NA] * 10, "Float64", "Float64"), + ("var", [pd.NA] * 10, "Int64", "Float64"), + ("std", [0, 1, 3, -4, 5, 6, 7, -8, np.nan, 9], "float64", "float64"), + ("std", [0, -1, 3, 4, 5, -6, 7, pd.NA, 8, 9], "Float64", "Float64"), + ("std", [0, 1, 3, -4, 5, 6, 7, -8, 9, pd.NA], "Int64", "Float64"), + ("std", [np.nan] * 10, "float64", "float64"), + ("std", [pd.NA] * 10, "Float64", "Float64"), + ("std", [pd.NA] * 10, "Int64", "Float64"), + ("sem", [0, -1, 3, 4, 5, -6, 7, np.nan, 8, 9], "float64", "float64"), + ("sem", [0, 1, 3, -4, 5, 6, 7, -8, pd.NA, 9], "Float64", "Float64"), + ("sem", [0, -1, 3, 4, 5, -6, 7, 8, 9, pd.NA], "Int64", "Float64"), + ("sem", [np.nan] * 10, "float64", "float64"), + ("sem", [pd.NA] * 10, "Float64", "Float64"), + ("sem", [pd.NA] * 10, "Int64", "Float64"), + ("min", [0, -1, 3, 4, 5, -6, 7, np.nan, 8, 9], "float64", "float64"), + ("min", [0, 1, 3, -4, 5, 6, 7, -8, pd.NA, 9], "Float64", "Float64"), + ("min", [0, -1, 3, 4, 5, -6, 7, 8, 9, pd.NA], "Int64", "Int64"), + ( + "min", + [0, 1, np.nan, 3, 4, 5, 6, 7, 8, 9], + "timedelta64[ns]", + "timedelta64[ns]", + ), + ( + "min", + pd.to_datetime( + [ + "2019-05-09", + pd.NaT, + "2019-05-11", + "2019-05-12", + "2019-05-13", + "2019-05-14", + "2019-05-15", + "2019-05-16", + "2019-05-17", + "2019-05-18", + ] + ), + "datetime64[ns]", + "datetime64[ns]", + ), + ("min", [np.nan] * 10, "float64", "float64"), + ("min", [pd.NA] * 10, "Float64", "Float64"), + ("min", [pd.NA] * 10, "Int64", "Int64"), + ("max", [0, -1, 3, 4, 5, -6, 7, np.nan, 8, 9], "float64", "float64"), + ("max", [0, 1, 3, -4, 5, 6, 7, -8, pd.NA, 9], "Float64", "Float64"), + ("max", [0, -1, 3, 4, 5, -6, 7, 8, 9, pd.NA], "Int64", "Int64"), + ( + "max", + [0, 1, np.nan, 3, 4, 5, 6, 7, 8, 9], + "timedelta64[ns]", + "timedelta64[ns]", + ), + ( + "max", + pd.to_datetime( + [ + "2019-05-09", + pd.NaT, + "2019-05-11", + "2019-05-12", + "2019-05-13", + "2019-05-14", + "2019-05-15", + "2019-05-16", + "2019-05-17", + "2019-05-18", + ] + ), + "datetime64[ns]", + "datetime64[ns]", + ), + ("max", [np.nan] * 10, "float64", "float64"), + ("max", [pd.NA] * 10, "Float64", "Float64"), + ("max", [pd.NA] * 10, "Int64", "Int64"), + ("median", [0, -1, 3, 4, 5, -6, 7, np.nan, 8, 9], "float64", "float64"), + ("median", [0, 1, 3, -4, 5, 6, 7, -8, pd.NA, 9], "Float64", "Float64"), + ("median", [0, -1, 3, 4, 5, -6, 7, 8, 9, pd.NA], "Int64", "Float64"), + ( + "median", + [0, 1, np.nan, 3, 4, 5, 6, 7, 8, 9], + "timedelta64[ns]", + "timedelta64[ns]", + ), + ( + "median", + pd.to_datetime( + [ + "2019-05-09", + pd.NaT, + "2019-05-11", + "2019-05-12", + "2019-05-13", + "2019-05-14", + "2019-05-15", + "2019-05-16", + "2019-05-17", + "2019-05-18", + ] + ), + "datetime64[ns]", + "datetime64[ns]", + ), + ("median", [np.nan] * 10, "float64", "float64"), + ("median", [pd.NA] * 10, "Float64", "Float64"), + ("median", [pd.NA] * 10, "Int64", "Float64"), + ], +) +def test_multifunc_skipna(func, values, dtype, result_dtype, skipna): + # GH#15675 + df = pd.DataFrame( + { + "val": values, + "cat": ["A", "B"] * 5, + } + ).astype({"val": dtype}) + # We need to recast the expected values to the result_dtype as some operations + # change the dtype + expected = ( + df.groupby("cat")["val"] + .apply(lambda x: getattr(x, func)(skipna=skipna)) + .astype(result_dtype) + ) + result = getattr(df.groupby("cat")["val"], func)(skipna=skipna) + tm.assert_series_equal(result, expected) + + +def test_cython_median(): + arr = np.random.default_rng(2).standard_normal(1000) + arr[::2] = np.nan + df = pd.DataFrame(arr) + + labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) + labels[::17] = np.nan + + result = df.groupby(labels).median() + exp = df.groupby(labels).agg(np.nanmedian) + tm.assert_frame_equal(result, exp) + + df = pd.DataFrame(np.random.default_rng(2).standard_normal((1000, 5))) + 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 = pd.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) + + +def test_max_min_non_numeric(): + # #2700 + aa = pd.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_infer_string): + # 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 = pd.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 + assert len(df._mgr.blocks) == 3 if using_infer_string else 2 + + gb = df.groupby("A") + + result = gb[["C"]].max() + # "max" is valid for column "C" but not for "B" + ei = pd.Index([1, 2, 3], name="A") + expected = pd.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 = pd.Index([1, 2, 3], name="A") + expected = pd.DataFrame({"C": ["a", "c", "e"]}, index=ei) + tm.assert_frame_equal(result, expected) + + +def test_min_date_with_nans(): + # GH26321 + dates = pd.to_datetime( + pd.Series(["2019-05-09", "2019-05-09", "2019-05-09"]), format="%Y-%m-%d" + ).dt.date + df = pd.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( + pd.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 = pd.Series([1, iNaT]) + key = np.array([1, 1], dtype=np.int64) + gb = ser.groupby(key) + + result = gb.max(min_count=2) + expected = pd.Series({1: 1}, dtype=np.int64) + tm.assert_series_equal(result, expected, check_exact=True) + + result = gb.min(min_count=2) + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame({"a": groups, "b": periods}) + + result = getattr(df.groupby("a")["b"], func)() + idx = pd.Index([1, 2], name="a") + expected = pd.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 = pd.DataFrame({"a": groups, "b": periods}) + + result = getattr(df.groupby("a"), func)() + idx = pd.Index([1, 2], name="a") + expected = pd.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 = pd.DataFrame( + {"key": ["A", "A", "B", "B"], "col1": list("abcd"), "col2": [np.nan] * 4}, + ).astype(object) + result = df.groupby("key").min() + expected = ( + pd.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 = pd.DataFrame( + {"key": ["A", "A", "B", "B"], "col1": list("abcd"), "col2": range(4)}, + ).astype(object) + result = df.groupby("key").min() + expected = ( + pd.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 = pd.Series(["b"], dtype="category").cat.as_ordered() + df = pd.DataFrame({"A": [1997], "B": ds}) + result = df.groupby("A").agg({"B": func}) + expected = pd.DataFrame({"B": ["b"]}, index=pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame( + { + "col2": pd.Categorical([1, None], categories=[1, 2], ordered=True), + "value": [0.1, None], + }, + index=idx, + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["min", "max"]) +def test_min_empty_string_dtype(func, string_dtype_no_object): + # GH#55619 + dtype = string_dtype_no_object + df = pd.DataFrame({"a": ["a"], "b": "a", "c": "a"}, dtype=dtype).iloc[:0] + result = getattr(df.groupby("a"), func)() + expected = pd.DataFrame( + columns=["b", "c"], dtype=dtype, index=pd.Index([], dtype=dtype, name="a") + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("min_count", [0, 1]) +@pytest.mark.parametrize("test_series", [True, False]) +def test_string_dtype_all_na( + string_dtype_no_object, reduction_func, skipna, min_count, test_series +): + # https://github.com/pandas-dev/pandas/issues/60985 + if reduction_func == "corrwith": + # corrwith is deprecated. + return + + dtype = string_dtype_no_object + + if reduction_func in [ + "any", + "all", + "idxmin", + "idxmax", + "mean", + "median", + "skew", + "std", + "var", + ]: + kwargs = {"skipna": skipna} + elif reduction_func in ["kurt"]: + kwargs = {"min_count": min_count} + elif reduction_func in ["count", "nunique", "quantile", "sem", "size"]: + kwargs = {} + else: + kwargs = {"skipna": skipna, "min_count": min_count} + + expected_dtype, expected_value = dtype, pd.NA + if reduction_func in ["all", "any"]: + expected_dtype = "bool" + # TODO: For skipna=False, bool(pd.NA) raises; should groupby? + expected_value = not skipna if reduction_func == "any" else True + elif reduction_func in ["count", "nunique", "size"]: + # TODO: Should be more consistent - return Int64 when dtype.na_value is pd.NA? + if ( + test_series + and reduction_func == "size" + and dtype.storage == "pyarrow" + and dtype.na_value is pd.NA + ): + expected_dtype = "Int64" + else: + expected_dtype = "int64" + expected_value = 1 if reduction_func == "size" else 0 + elif not skipna or min_count > 0: + expected_value = pd.NA + elif reduction_func == "sum": + # https://github.com/pandas-dev/pandas/pull/60936 + expected_value = "" + + df = pd.DataFrame({"a": ["x"], "b": [pd.NA]}, dtype=dtype) + obj = df["b"] if test_series else df + args = get_groupby_method_args(reduction_func, obj) + gb = obj.groupby(df["a"]) + method = getattr(gb, reduction_func) + + if reduction_func in [ + "mean", + "median", + "kurt", + "prod", + "quantile", + "sem", + "skew", + "std", + "var", + ]: + msg = f"dtype '{dtype}' does not support operation '{reduction_func}'" + with pytest.raises(TypeError, match=msg): + method(*args, **kwargs) + return + elif reduction_func in ["idxmin", "idxmax"]: + if skipna: + msg = f"{reduction_func} with skipna=True encountered all NA values" + else: + msg = f"{reduction_func} with skipna=False encountered an NA value." + with pytest.raises(ValueError, match=msg): + method(*args, **kwargs) + return + + result = method(*args, **kwargs) + index = pd.Index(["x"], name="a", dtype=dtype) + if test_series or reduction_func == "size": + name = None if not test_series and reduction_func == "size" else "b" + expected = pd.Series( + expected_value, index=index, dtype=expected_dtype, name=name + ) + else: + expected = pd.DataFrame( + {"b": expected_value}, index=index, dtype=expected_dtype + ) + tm.assert_equal(result, expected) + + +def test_max_nan_bug(): + df = pd.DataFrame( + { + "Unnamed: 0": ["-04-23", "-05-06", "-05-07"], + "Date": [ + "2013-04-23 00:00:00", + "2013-05-06 00:00:00", + "2013-05-07 00:00:00", + ], + "app": pd.Series([np.nan, np.nan, "OE"]), + "File": ["log080001.log", "log.log", "xlsx"], + } + ) + 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() + + +@pytest.mark.slow +@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 = pd.date_range("2015-08-23", periods=10) + df = pd.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(pd.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 = pd.DataFrame({"A": list("abbacc"), "B": list("abxacc"), "C": list("abbacx")}) + + expected = pd.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 = pd.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 = pd.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 = pd.MultiIndex.from_arrays([data.id, data.amount]) + expected = pd.Series([1] * 5, name="name", index=index) + tm.assert_series_equal(result, expected) + + +def test_nunique_with_empty_series(): + # GH 12553 + data = pd.Series(name="name", dtype=object) + result = data.groupby(level=0).nunique() + expected = pd.Series(name="name", dtype="int64") + tm.assert_series_equal(result, expected) + + +def test_nunique_with_timegrouper(): + # GH 13453 + test = pd.DataFrame( + { + "time": [ + pd.Timestamp("2016-06-28 09:35:35"), + pd.Timestamp("2016-06-28 16:09:30"), + pd.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(pd.Series.nunique) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "key, data, dropna, expected", + [ + ( + ["x", "x", "x"], + [pd.Timestamp("2019-01-01"), pd.NaT, pd.Timestamp("2019-01-01")], + True, + pd.Series([1], index=pd.Index(["x"], name="key"), name="data"), + ), + ( + ["x", "x", "x"], + [dt.date(2019, 1, 1), pd.NaT, dt.date(2019, 1, 1)], + True, + pd.Series([1], index=pd.Index(["x"], name="key"), name="data"), + ), + ( + ["x", "x", "x", "y", "y"], + [ + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + ], + False, + pd.Series([2, 2], index=pd.Index(["x", "y"], name="key"), name="data"), + ), + ( + ["x", "x", "x", "x", "y"], + [ + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + ], + False, + pd.Series([2, 1], index=pd.Index(["x", "y"], name="key"), name="data"), + ), + ], +) +def test_nunique_with_NaT(key, data, dropna, expected): + # GH 27951 + df = pd.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 = pd.DataFrame([1, 2, 2], columns=pd.Index(["A"], name="level_0")) + result = test.groupby([0, 0, 0]).nunique() + expected = pd.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 = pd.DataFrame(pd.date_range("2008-12-31", "2009-01-02"), columns=["date"]) + result = df.groupby([0, 0, 1])["date"].transform("nunique") + expected = pd.Series([2, 2, 1], name="date") + tm.assert_series_equal(result, expected) + + +def test_empty_categorical(observed): + # GH#21334 + cat = pd.Series([1]).astype("category") + ser = cat[:0] + gb = ser.groupby(ser, observed=observed) + result = gb.nunique() + if observed: + expected = pd.Series([], index=cat[:0], dtype="int64") + else: + expected = pd.Series([0], index=cat, dtype="int64") + tm.assert_series_equal(result, expected) + + +def test_intercept_builtin_sum(): + s = pd.Series([1.0, 2.0, np.nan, 3.0]) + grouped = s.groupby([0, 1, 2, 2]) + + # GH#53425 + result = grouped.agg(builtins.sum) + # GH#53425 + result2 = grouped.apply(builtins.sum) + expected = pd.Series([1.0, 2.0, np.nan], index=np.array([0, 1, 2])) + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result2, 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 = pd.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 = pd.DataFrame( + {"B": pd.array([3, 0, 0], dtype="Int64")}, + index=pd.Index([1, 2, 3], name="A"), + ) + tm.assert_frame_equal(result, expected) + else: + expected = pd.DataFrame( + {"B": pd.array([pd.NA] * 3, dtype="Int64")}, + index=pd.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 = pd.DataFrame({"a": [0, 1, 2], "b": [0, 1, 2], "c": [0, 1, 2]}, dtype="Int64") + grouped = df.groupby("a") + idx = pd.Index([0, 1, 2], name="a", dtype="Int64") + + result = grouped["b"].sum(min_count=2) + expected = pd.Series([pd.NA] * 3, dtype="Int64", index=idx, name="b") + tm.assert_series_equal(result, expected) + + result = grouped.sum(min_count=2) + expected = pd.DataFrame( + {"b": [pd.NA] * 3, "c": [pd.NA] * 3}, dtype="Int64", index=idx + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_sum_timedelta_with_nat(): + # GH#42659 + df = pd.DataFrame( + { + "a": [1, 1, 2, 2], + "b": [pd.Timedelta("1D"), pd.Timedelta("2D"), pd.Timedelta("3D"), pd.NaT], + } + ) + td3 = pd.Timedelta(days=3).as_unit("us") + + gb = df.groupby("a") + + res = gb.sum() + expected = pd.DataFrame({"b": [td3, td3]}, index=pd.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 = pd.Series([td3, pd.NaT], dtype="m8[us]", name="b", index=expected.index) + tm.assert_series_equal(res, expected) + + +def test_groupby_sum_timedelta_overflow(): + # GH#66551: a running total that leaves the int64 range used to wrap + # silently; Series.sum on the same group already raised + msg = "overflow in timedelta operation" + ser = pd.Series([pd.Timedelta.max, pd.Timedelta.max, pd.Timedelta("1D")]) + + with pytest.raises(pd.errors.OutOfBoundsTimedelta, match=msg): + ser.groupby([0, 0, 1]).sum() + + # the group that does not overflow is not enough to make the whole + # aggregation succeed, matching DataFrame.sum + with pytest.raises(pd.errors.OutOfBoundsTimedelta, match=msg): + pd.DataFrame({"a": ser}).groupby([0, 0, 1]).sum() + + # groups that stay in range are unaffected + ser = pd.Series([pd.Timedelta.max, pd.Timedelta("1D"), pd.Timedelta("2D")]) + res = ser.groupby([0, 1, 1]).sum() + expected = pd.Series( + [pd.Timedelta.max, pd.Timedelta("3D")], index=pd.Index([0, 1], dtype=np.intp) + ) + tm.assert_series_equal(res, expected) + + +def test_groupby_sum_timedelta_overflow_sentinel(): + # GH#66551: a total landing exactly on iNaT is not a missing value + mx, mn = pd.Timedelta.max, pd.Timedelta.min + ser = pd.Series([mn, pd.Timedelta(-1, "ns")]) + with pytest.raises(pd.errors.OutOfBoundsTimedelta, match="overflow"): + ser.groupby([0, 0]).sum() + + # ... but an intermediate that merely passes through the sentinel is fine, + # so the result must not depend on the order values arrive in + for order in ([mx, mn, mx], [mx, mx, mn], [mn, mx, mx]): + res = pd.Series(order).groupby([0, 0, 0]).sum() + tm.assert_series_equal( + res, + pd.Series([mx + mn + mx], index=pd.Index([0], dtype=np.intp)), + check_dtype=False, + ) + + +def test_groupby_sum_timedelta_overflow_na_result(): + # GH#66551: a group whose result is NA anyway must not raise, matching + # Series.sum + ser = pd.Series([pd.Timedelta.max, pd.Timedelta.max]) + + res = ser.groupby([0, 0]).sum(min_count=3) + tm.assert_series_equal( + res, pd.Series([pd.NaT], dtype="m8[ns]", index=pd.Index([0], dtype=np.intp)) + ) + + ser = pd.Series([pd.Timedelta.max, pd.Timedelta.max, pd.NaT]) + res = ser.groupby([0, 0, 0]).sum(skipna=False) + tm.assert_series_equal( + res, pd.Series([pd.NaT], dtype="m8[ns]", index=pd.Index([0], dtype=np.intp)) + ) + + +def test_groupby_sum_int64_still_wraps(): + # GH#66551: only the datetimelike path is checked; plain int64 keeps + # wrapping like NumPy + ser = pd.Series([2**62] * 4) + res = ser.groupby([0] * 4).sum() + tm.assert_series_equal(res, pd.Series([0], index=pd.Index([0], dtype=np.intp))) + + +@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 = pd.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 = pd.DataFrame(exp) + + df_out["b"] = df_out.b.astype(out_type) + df_out = df_out.set_index("a") + + grpd = df.groupby("a") + t = getattr(grpd, method)(*data["args"]) + tm.assert_frame_equal(t, df_out) + + +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 = pd.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)() + kwargs = {"ddof": 1, "axis": 0} if op in ["std", "var"] else {} + expected = df.groupby(labels).agg(targop, **kwargs) + tm.assert_frame_equal(result, expected) + + +@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 = pd.Index([1, 2, 3], name="a", dtype="Int64") + expected = pd.DataFrame({"b": arr}, index=idx).astype("Float64") + + groups = pd.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 = pd.MultiIndex.from_tuples([("b", function)]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op", + [ + "sum", + "prod", + "min", + "max", + "median", + "mean", + "skew", + "kurt", + "std", + "var", + "sem", + ], +) +def test_regression_allowlist_methods(op, skipna, sort): + # GH6944 + # GH 17537 + # explicitly test the allowlist methods + frame = pd.DataFrame([0]) + + grouped = frame.groupby(level=0, sort=sort) + + if op in ["skew", "kurt", "sum", "mean"]: + # skew, kurt, sum, mean have skipna + result = getattr(grouped, op)(skipna=skipna) + expected = frame.groupby(level=0).apply(lambda h: getattr(h, op)(skipna=skipna)) + if sort: + expected = expected.sort_index() + tm.assert_frame_equal(result, expected) + else: + result = getattr(grouped, op)() + expected = frame.groupby(level=0).apply(lambda h: getattr(h, op)()) + if sort: + expected = expected.sort_index() + tm.assert_frame_equal(result, expected) + + +def test_groupby_prod_with_int64_dtype(): + # GH#46573 + data = [ + [1, 11], + [1, 41], + [1, 17], + [1, 37], + [1, 7], + [1, 29], + [1, 31], + [1, 2], + [1, 3], + [1, 43], + [1, 5], + [1, 47], + [1, 19], + [1, 88], + ] + df = pd.DataFrame(data, columns=["A", "B"], dtype="int64") + result = df.groupby(["A"]).prod().reset_index() + expected = pd.DataFrame({"A": [1], "B": [180970905912331920]}, dtype="int64") + tm.assert_frame_equal(result, expected) + + +def test_groupby_std_datetimelike(): + # GH#48481 + tdi = pd.timedelta_range("1 Day", periods=10000, unit="ns") + ser = pd.Series(tdi) + ser[::5] *= 2 # get different std for different groups + + df = ser.to_frame("A").copy() + + df["B"] = ser + pd.Timestamp(0) + df["C"] = ser + pd.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 = pd.Timedelta("2887 days 11:21:02.326710176") + td4 = pd.Timedelta("2886 days 00:42:34.664668096") + exp_ser = pd.Series([td1 * 2, td1, td1, td1, td4], index=np.arange(5)) + expected = pd.DataFrame({"A": exp_ser, "B": exp_ser, "C": exp_ser}) + tm.assert_frame_equal(result, expected) + + +def test_mean_numeric_only_validates_bool(): + # GH#62778 + + df = pd.DataFrame({"A": range(5), "B": range(5)}) + + msg = "numeric_only accepts only Boolean values" + with pytest.raises(ValueError, match=msg): + df.groupby(["A"]).mean(["B"]) + + with pytest.raises(ValueError, match=msg): + df.groupby(["A"]).mean(numeric_only="True") + + with pytest.raises(ValueError, match=msg): + df.groupby(["A"]).mean(numeric_only=1) + + +@pytest.mark.parametrize( + "method", + [ + "sum", + "mean", + "std", + "var", + "sem", + "skew", + "kurt", + "prod", + ], +) +def test_groupby_reductions_dont_skip_nan_with_mask(method, skipna, using_nan_is_na): + values = np.array([1.0, 2.0, 3.0, 4.0, np.nan], dtype="float64") + mask = np.array([False, False, False, False, False], dtype="bool") + + ser = pd.Series(pd.arrays.FloatingArray(values, mask)) + df = pd.DataFrame({"A": [1] * 5, "B": ser}) + + gb = df.groupby("A")["B"] + result = getattr(gb, method)(skipna=skipna) + + if using_nan_is_na: + expected = pd.Series( + [pd.NA], index=pd.Index([1], name="A"), name="B", dtype="Float64" + ) + else: + expected = pd.Series( + [np.nan], index=pd.Index([1], name="A"), name="B", dtype="Float64" + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "method", + [ + "sum", + "mean", + "std", + "var", + "sem", + "skew", + "kurt", + "prod", + ], +) +def test_groupby_skipna_false_propagates_na_when_distinguish_nan_and_na(method): + # GH-65372: under future.distinguish_nan_and_na, a genuine NA with + # skipna=False must propagate to NA. + with pd.option_context("future.distinguish_nan_and_na", True): + ser = pd.Series([1.0, 2.0, 3.0, 4.0, pd.NA], dtype="Float64") + df = pd.DataFrame({"A": [1] * 5, "B": ser}) + gb = df.groupby("A")["B"] + expected = pd.Series( + [pd.NA], index=pd.Index([1], name="A"), name="B", dtype="Float64" + ) + result = getattr(gb, method)(skipna=False) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_sparse.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..bd56fbf4211aa63f6e31cd8fbceb6c3737a1deb7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_sparse.py @@ -0,0 +1,288 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays.sparse import SparseArray + + +@pytest.fixture(params=[0, np.nan]) +def fill_value(request): + return request.param + + +@pytest.fixture +def sparse_df(fill_value): + """DataFrame with sparse int columns and a dense grouping column.""" + dense = pd.DataFrame( + { + "key": ["a", "a", "b", "b", "a", "b"], + "val1": [1, 0, 0, 3, 0, 5], + "val2": [0, 2, 0, 0, 4, 0], + } + ) + sparse = dense.copy() + sparse["val1"] = sparse["val1"].astype(pd.SparseDtype(np.int64, fill_value)) + sparse["val2"] = sparse["val2"].astype(pd.SparseDtype(np.int64, fill_value)) + return dense, sparse + + +class TestSparseGroupby: + """Tests for groupby operations on SparseArray columns (GH#36123).""" + + @pytest.mark.parametrize("op", ["sum", "mean", "min", "max", "std", "var"]) + def test_sparse_groupby_agg(self, sparse_df, op): + dense, sparse = sparse_df + result = getattr(sparse.groupby("key"), op)() + expected = getattr(dense.groupby("key"), op)() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("op", ["first", "last"]) + def test_sparse_groupby_first_last(self, sparse_df, op): + # first/last preserve the SparseArray dtype + dense, sparse = sparse_df + result = getattr(sparse.groupby("key"), op)() + expected = getattr(dense.groupby("key"), op)() + tm.assert_frame_equal(result, expected, check_dtype=False) + + @pytest.mark.parametrize("op", ["any", "all"]) + def test_sparse_groupby_any_all(self, sparse_df, op): + dense, sparse = sparse_df + result = getattr(sparse.groupby("key"), op)() + expected = getattr(dense.groupby("key"), op)() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("op", ["sem", "prod", "median"]) + def test_sparse_groupby_other_aggs(self, sparse_df, op): + dense, sparse = sparse_df + result = getattr(sparse.groupby("key"), op)() + expected = getattr(dense.groupby("key"), op)() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("op", ["cumsum", "cummin", "cummax", "cumprod"]) + def test_sparse_groupby_transform(self, sparse_df, op): + dense, sparse = sparse_df + result = getattr(sparse.groupby("key"), op)() + expected = getattr(dense.groupby("key"), op)() + tm.assert_frame_equal(result, expected) + + def test_sparse_groupby_rank(self, sparse_df): + dense, sparse = sparse_df + result = sparse.groupby("key").rank() + expected = dense.groupby("key").rank() + tm.assert_frame_equal(result, expected) + + def test_sparse_groupby_idxmin_idxmax(self, sparse_df): + dense, sparse = sparse_df + for op in ["idxmin", "idxmax"]: + result = getattr(sparse.groupby("key"), op)() + expected = getattr(dense.groupby("key"), op)() + tm.assert_frame_equal(result, expected) + + def test_sparse_groupby_nan_fill_value(self): + # When fill_value=NaN, gap positions are NaN and should be + # excluded from aggregations. + dense = pd.DataFrame( + { + "key": ["a", "a", "b", "b"], + "val": [1.0, np.nan, np.nan, 4.0], + } + ) + sparse = dense.copy() + sparse["val"] = pd.array(dense["val"], dtype=pd.SparseDtype(float, np.nan)) + result = sparse.groupby("key").mean() + expected = dense.groupby("key").mean() + tm.assert_frame_equal(result, expected) + + def test_sparse_groupby_series(self, fill_value): + # Groupby on a single sparse Series. + vals = [1, 0, 0, 3, 0, 5] + keys = ["a", "a", "b", "b", "a", "b"] + dense_ser = pd.Series(vals, name="val") + sparse_ser = dense_ser.astype(pd.SparseDtype(np.int64, fill_value)) + result = sparse_ser.groupby(keys).mean() + expected = dense_ser.groupby(keys).mean() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("op", ["min", "max", "sum", "mean", "cumsum", "any"]) + def test_sparse_groupby_nan_fill_value_gaps(self, op): + # GH#64758 the NaN fill_value must be materialized rather than + # unsafely cast to the int64 subtype + keys = ["a", "a", "b", "b"] + sparse_ser = pd.Series( + SparseArray([1, np.nan, 1, np.nan], dtype=pd.SparseDtype(np.int64, np.nan)) + ) + assert sparse_ser.array.sp_index.ngaps == 2 + + dense_ser = pd.Series([1.0, np.nan, 1.0, np.nan]) + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("op", ["sum", "any", "all"]) + def test_sparse_groupby_bool_nan_fill_value(self, op): + # GH#64758 a NaN fill_value on a bool subtype was cast to True; the gaps + # are missing values, so the dense equivalent is object dtype + keys = ["a", "a", "b", "b"] + dtype = pd.SparseDtype(bool, np.nan) + sparse_ser = pd.Series(SparseArray([True, np.nan, True, np.nan], dtype=dtype)) + assert sparse_ser.array.sp_index.ngaps == 2 + + dense_ser = pd.Series([True, np.nan, True, np.nan]) + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "subtype", ["int8", "int32", "uint16", "uint64", "float32"] + ) + @pytest.mark.parametrize("op", ["min", "max", "sum", "cumsum"]) + def test_sparse_groupby_preserves_subtype(self, subtype, op): + # GH#64758 densifying must give the subtype's own dense dtype; widening + # uint64 to float64 would round values above 2**53 + keys = ["a", "a", "b", "b"] + big = 2**63 + 12345 if subtype == "uint64" else 3 + dense_ser = pd.Series(np.array([1, 0, big, 0], dtype=subtype)) + sparse_ser = dense_ser.astype(pd.SparseDtype(subtype, 0)) + assert sparse_ser.array.sp_index.ngaps == 2 + + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("op", ["min", "max", "sum", "cumsum"]) + def test_sparse_groupby_wider_fill_value(self, op): + # GH#64758 SparseDtype allows a fill_value whose type is wider than the + # subtype as long as it round-trips; the result still follows the subtype + keys = ["a", "a", "b", "b"] + dense_ser = pd.Series(np.array([1, 0, 3, 0], dtype="int64")) + sparse_ser = dense_ser.astype(pd.SparseDtype("int64", 0.0)) + assert sparse_ser.array.sp_index.ngaps == 2 + + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("op", ["first", "last"]) + @pytest.mark.parametrize( + "subtype", ["int8", "int32", "uint16", "uint64", "float32"] + ) + def test_sparse_groupby_first_last_preserves_subtype(self, subtype, op): + # GH#68469 first/last keep the SparseDtype rather than densifying, so + # they reach the gaps through take + keys = ["a", "a", "b", "b", "a", "b"] + big = 2**63 + 12345 if subtype == "uint64" else 3 + dense_ser = pd.Series(np.array([0, 1, big, 0, big, 0], dtype=subtype)) + sparse_ser = dense_ser.astype(pd.SparseDtype(subtype, 0)) + assert sparse_ser.array.sp_index.ngaps == 3 + + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + expected = expected.astype(pd.SparseDtype(subtype, 0)) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("op", ["first", "last"]) + @pytest.mark.parametrize("unit", ["M8[s]", "M8[ns]", "m8[s]", "m8[ns]"]) + def test_sparse_groupby_first_last_datetimelike(self, unit, op): + # GH#68469 same for a datetimelike subtype: a nanosecond unit was + # promoted to object and read back as raw integers, a coarser one + # was widened + keys = ["a", "a", "b", "b", "a", "b"] + dense_ser = pd.Series(np.array([3, 1, 5, 3, 5, 3], dtype=unit)) + fill = dense_ser[0] if unit[0] == "M" else pd.Timedelta(dense_ser[0]) + sparse_ser = dense_ser.astype(pd.SparseDtype(unit, fill)) + assert sparse_ser.array.sp_index.ngaps == 3 + + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + expected = expected.astype(pd.SparseDtype(unit, fill)) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("nat_fill", [None, pd.NaT]) + @pytest.mark.parametrize( + "unit", + ["datetime64[ns]", "datetime64[s]", "timedelta64[ns]", "timedelta64[us]"], + ) + @pytest.mark.parametrize("op", ["min", "max", "mean", "median", "cummax", "rank"]) + def test_sparse_groupby_datetimelike(self, unit, op, nat_fill): + # GH#64758 datetimelike subtypes must not be treated as raw integers, + # and the result must keep the subtype's unit + keys = ["a", "a", "b", "b"] + dense_ser = pd.Series(np.array([1, 2, 3, "NaT"], dtype=unit)) + sparse_ser = dense_ser.astype(pd.SparseDtype(unit, nat_fill)) + assert sparse_ser.array.sp_index.ngaps == 1 + + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("op", ["min", "max", "mean", "cummax"]) + def test_sparse_groupby_datetimelike_subsecond_fill_value(self, op): + # GH#64758 a sub-microsecond Timestamp fill_value must not be truncated + # when the gaps are materialized + keys = ["a", "a", "b", "b"] + dense_ser = pd.Series(np.array([1, 2, 3, 4], dtype="M8[ns]")) + sparse_ser = dense_ser.astype(pd.SparseDtype("M8[ns]", pd.Timestamp(3))) + assert sparse_ser.array.sp_index.ngaps == 1 + + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("op", ["min", "sum", "cumsum"]) + def test_sparse_groupby_timedelta_subsecond_fill_value(self, op): + # GH#64758 same for a sub-microsecond Timedelta fill_value + keys = ["a", "a", "b", "b"] + dense_ser = pd.Series(np.array([1, 2, 3, 4], dtype="m8[ns]")) + sparse_ser = dense_ser.astype(pd.SparseDtype("m8[ns]", pd.Timedelta(3))) + assert sparse_ser.array.sp_index.ngaps == 1 + + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("nat_fill", [None, pd.NaT]) + @pytest.mark.parametrize("op", ["sum", "cumsum"]) + def test_sparse_groupby_timedelta_sum(self, op, nat_fill): + # GH#64758 adding timedeltas is valid, unlike adding datetimes + keys = ["a", "a", "b", "b"] + dense_ser = pd.Series(np.array([1, 2, 3, "NaT"], dtype="m8[ns]")) + sparse_ser = dense_ser.astype(pd.SparseDtype("m8[ns]", nat_fill)) + + result = getattr(sparse_ser.groupby(keys), op)() + expected = getattr(dense_ser.groupby(keys), op)() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("nat_fill", [None, pd.NaT]) + @pytest.mark.parametrize( + "unit, op", + [ + ("datetime64[ns]", "sum"), + ("datetime64[ns]", "prod"), + ("datetime64[ns]", "var"), + ("datetime64[ns]", "skew"), + ("datetime64[ns]", "kurt"), + ("datetime64[ns]", "cumsum"), + ("datetime64[ns]", "cumprod"), + # any/all raise with a different message than the arithmetic ops + ("datetime64[ns]", "any"), + ("datetime64[ns]", "all"), + ("timedelta64[ns]", "prod"), + ("timedelta64[ns]", "var"), + ("timedelta64[ns]", "skew"), + ("timedelta64[ns]", "kurt"), + ("timedelta64[ns]", "cumprod"), + ], + ) + def test_sparse_groupby_datetimelike_invalid(self, unit, op, nat_fill): + # GH#64758 operations that are invalid for the subtype must raise + # instead of silently returning garbage + keys = ["a", "a", "b", "b"] + dense_ser = pd.Series(np.array([1, 2, 3, "NaT"], dtype=unit)) + sparse_ser = dense_ser.astype(pd.SparseDtype(unit, nat_fill)) + + with pytest.raises(TypeError) as sparse_err: + getattr(sparse_ser.groupby(keys), op)() + with pytest.raises(TypeError) as dense_err: + getattr(dense_ser.groupby(keys), op)() + assert str(sparse_err.value) == str(dense_err.value) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_timegrouper.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_timegrouper.py new file mode 100644 index 0000000000000000000000000000000000000000..998ba0d717aadce72760c15cb09d970678bfca97 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/test_timegrouper.py @@ -0,0 +1,1004 @@ +""" +test with the TimeGrouper / grouping with datetimes +""" + +from datetime import ( + UTC, + datetime, + timedelta, +) + +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +import pandas as pd +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 reuse in + test_groupby_apply_timegrouper_with_nat_apply_squeeze + """ + df = pd.DataFrame( + { + "Quantity": [18, 3, 5, 1, 9, 3], + "Date": [ + pd.Timestamp(2013, 9, 1, 13, 0), + pd.Timestamp(2013, 9, 1, 13, 5), + pd.Timestamp(2013, 10, 1, 20, 0), + pd.Timestamp(2013, 10, 3, 10, 0), + pd.NaT, + pd.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.codes) + + return gb + + +class TestGroupBy: + def test_groupby_with_timegrouper(self, using_infer_string): + # GH 4161 + # TimeGrouper requires a sorted index + # also verifies that the resultant index has the correct name + df_original = pd.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"]) + + exp_dti = pd.date_range( + "20130901", + "20131205", + freq="5D", + name="Date", + inclusive="left", + unit=df.index.unit, + ) + expected = pd.DataFrame( + {"Buyer": "" if using_infer_string else 0, "Quantity": 0}, + index=exp_dti, + ) + # Cast to object/str to avoid implicit cast when setting + # entry to "CarlCarlCarl" + expected = expected.astype({"Buyer": object}) + if using_infer_string: + expected = expected.astype({"Buyer": "str"}) + 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 = pd.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="6ME")) + 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 = pd.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 = pd.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="YE"), "Buyer"]).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + expected = pd.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 = pd.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 = pd.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="1ME"), "Buyer"]).sum(numeric_only=True) + expected = pd.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="1ME", 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="1ME", key="foo"), "Buyer"]).sum() + + # passing the level + df = df.set_index("Date") + result = df.groupby([Grouper(freq="1ME", level="Date"), "Buyer"]).sum( + numeric_only=True + ) + tm.assert_frame_equal(result, expected) + result = df.groupby([Grouper(freq="1ME", 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="1ME", level="foo"), "Buyer"]).sum() + + # multi names + df = df.copy() + df["Date"] = df.index + pd.offsets.MonthEnd(2) + result = df.groupby([Grouper(freq="1ME", key="Date"), "Buyer"]).sum( + numeric_only=True + ) + expected = pd.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="1ME", key="Date", level="Date"), "Buyer"] + ).sum() + + # single groupers + expected = pd.DataFrame( + [[31]], + columns=["Quantity"], + index=pd.DatetimeIndex( + [datetime(2013, 10, 31, 0, 0)], + freq=pd.offsets.MonthEnd(), + name="Date", + ), + ) + result = df.groupby(Grouper(freq="1ME")).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + result = df.groupby([Grouper(freq="1ME")]).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + expected.index = expected.index.shift(1) + assert expected.index.freq == pd.offsets.MonthEnd() + result = df.groupby(Grouper(freq="1ME", key="Date")).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + result = df.groupby([Grouper(freq="1ME", key="Date")]).sum( + numeric_only=True + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("freq", ["D", "ME", "YE", "QE-APR"]) + def test_timegrouper_with_reg_groups_freq(self, freq): + # GH 6764 multiple grouping with/without sort + df = pd.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) # TODO: can we drop min_count=1 + dropna() below? + .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 = pd.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="ME", key="Date")) + for t, expected in zip(dt_list, expected_list, strict=True): + dt = pd.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="ME", key="Date")]) + for (b, t), expected in zip(g_list, expected_list, strict=True): + dt = pd.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="ME")) + for t, expected in zip(dt_list, expected_list, strict=True): + dt = pd.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 = pd.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 pd.Series([x["value"].sum()], ("sum",)) + + expected = df.groupby(Grouper(key="date")).apply(sumfunc_series) + result = df_dt.groupby(Grouper(freq="ME", 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 = pd.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="ME", 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 = pd.date_range(start="2012/1/1", freq="5min", periods=periods) + df = pd.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) + + def test_groupby_groups_datetimeindex2(self): + # GH#11442 + index = pd.date_range("2015/01/01", periods=5, name="date") + df = pd.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 = { + pd.Timestamp(date): pd.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 = pd.DatetimeIndex( + [date], name="date", freq="D", dtype=index.dtype + ) + expected = pd.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 = pd.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: pd.Timestamp(d, tz="US/Pacific") + ) + + exp_idx1 = pd.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 = pd.Index(["a", "b"] * 3, name="label") + exp_idx = pd.MultiIndex.from_arrays([exp_idx1, exp_idx2]) + expected = pd.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 = pd.DatetimeIndex(dates, tz="Asia/Tokyo") + df = pd.DataFrame( + {"value1": np.arange(6, dtype="int64"), "value2": [1, 2, 3, 1, 2, 3]}, + index=didx, + ) + + exp_idx = pd.DatetimeIndex( + ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"], + tz="Asia/Tokyo", + ) + expected = pd.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 = pd.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] == pd.Timestamp("2012-07-03") + + def test_groupby_multi_timezone(self): + # combining multiple / different timezones yields UTC + df = pd.DataFrame( + { + "value": range(5), + "date": [ + "2000-01-28 16:47:00", + "2000-01-29 16:48:00", + "2000-01-30 16:49:00", + "2000-01-31 16:50:00", + "2000-01-01 16:50:00", + ], + "tz": [ + "America/Chicago", + "America/Chicago", + "America/Los_Angeles", + "America/Chicago", + "America/New_York", + ], + } + ) + + result = df.groupby("tz", group_keys=False).date.apply( + lambda x: pd.to_datetime(x).dt.tz_localize(x.name) + ) + + expected = pd.Series( + [ + pd.Timestamp("2000-01-28 16:47:00-0600", tz="America/Chicago"), + pd.Timestamp("2000-01-29 16:48:00-0600", tz="America/Chicago"), + pd.Timestamp("2000-01-30 16:49:00-0800", tz="America/Los_Angeles"), + pd.Timestamp("2000-01-31 16:50:00-0600", tz="America/Chicago"), + pd.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 = pd.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 = pd.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 = pd.Index(["a", "b"] * 3, name="label") + exp_idx = pd.MultiIndex.from_arrays([exp_idx1, exp_idx2]) + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame([(1, 1351036800000000000), (2, 1351036800000000000)]) + df[1] = df[1].astype("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 = pd.DataFrame( + {"A": pd.Timestamp("20130101").as_unit("s"), "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 = pd.DataFrame({"A": range(2), "B": [pd.Timestamp("2000-01-1")] * 2}) + result = df.groupby("A")["B"].transform("min") + expected = pd.Series([pd.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 = pd.DataFrame( + { + "factor": np.random.default_rng(2).integers(0, 3, size=60), + "time": pd.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 + utc = UTC + df = pd.DataFrame({"a": [1], "b": [datetime(2011, 1, 1, tzinfo=utc)]}) + assert df["b"][0].tzinfo == utc + df = pd.DataFrame({"a": [1, 2, 3]}) + df["b"] = datetime(2011, 1, 1, tzinfo=utc) + assert df["b"][0].tzinfo == utc + + def test_datetime_count(self): + df = pd.DataFrame( + { + "a": [1, 2, 3] * 2, + "dates": pd.date_range("2011-01-01", periods=6, freq="min"), + } + ) + result = df.groupby("a").dates.count() + expected = pd.Series( + [2, 2, 2], index=pd.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 = pd.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 = pd.DataFrame( + { + "time": [ + pd.Timestamp("2016-06-28 09:35:35"), + pd.NaT, + pd.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": pd.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 = pd.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 = pd.Series(range(periods), index=index) + result = period_series.groupby(period_series.index.month).sum() + + expected = pd.Series( + range(periods), index=pd.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)}) + + df = gb.obj + unit = df["Date"]._values.unit + dti = pd.date_range( + "2013-09-01", "2013-10-01", freq="5D", name="Date", unit=unit + ) + mi = pd.MultiIndex.from_arrays([dti, ["foo"] * len(dti)]) + expected = pd.Series([3, 0, 0, 0, 0, 0, 2], index=mi, name="Quantity") + tm.assert_series_equal(res, expected, check_freq=False) + + 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) + + df = gb.obj + unit = df["Date"]._values.unit + dti = pd.date_range( + "2013-09-01", "2013-10-01", freq="5D", name="Date", unit=unit + ) + expected = pd.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="100YE") + 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.index.nlevels == 1 + + # function that returns a Series + res = gb.apply(lambda x: x["Quantity"] * 2) + + dti = pd.Index( + [pd.Timestamp("2013-12-31")], dtype=df["Date"].dtype, name="Date" + ) + expected = pd.DataFrame( + [[36, 6, 6, 10, 2]], + index=dti, + columns=pd.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) + + def test_groupby_all_nat_timegrouper(self): + # GH#43486 + df = pd.DataFrame({"date": [pd.NaT, pd.NaT], "value": [1, 2]}) + gb = df.groupby(Grouper(freq="ME", key="date")) + result = gb.sum() + expected = pd.DataFrame( + {"value": np.array([], dtype="int64")}, + index=pd.DatetimeIndex([], dtype="datetime64[s]", name="date"), + ) + tm.assert_frame_equal(result, expected) + + @td.skip_if_no("pyarrow") + def test_pyarrow_index_retention(self): + # https://github.com/pandas-dev/pandas/issues/63518 + df = pd.DataFrame( + { + "a": [1, 2, 3], + }, + index=pd.Index( + [ + pd.Timestamp("2013-01-01"), + pd.Timestamp("2013-01-01"), + pd.Timestamp("2013-01-02"), + ], + dtype="timestamp[ns, America/Denver][pyarrow]", + ), + ) + gb = df.groupby(Grouper(freq="D")) + result = gb._grouper.result_index + expected = pd.Index( + [pd.Timestamp("2013-01-01"), pd.Timestamp("2013-01-02")], + dtype="timestamp[ns, America/Denver][pyarrow]", + ) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/transform/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/transform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/transform/test_numba.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/transform/test_numba.py new file mode 100644 index 0000000000000000000000000000000000000000..403d7ae7abe2595045002831419b188b2f6f79ea --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/transform/test_numba.py @@ -0,0 +1,326 @@ +import numpy as np +import pytest + +from pandas.compat import is_platform_arm +from pandas.errors import NumbaUtilError + +import pandas as pd +import pandas._testing as tm +from pandas.util.version import Version + +pytestmark = [pytest.mark.single_cpu] + +numba = pytest.importorskip("numba") +pytestmark.append( + pytest.mark.skipif( + Version(numba.__version__) == Version("0.61") and is_platform_arm(), + reason=f"Segfaults on ARM platforms with numba {numba.__version__}", + ) +) + + +def test_correct_function_signature(): + pytest.importorskip("numba") + + def incorrect_function(x): + return x + 1 + + data = pd.DataFrame( + {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, + columns=["key", "data"], + ) + with pytest.raises(NumbaUtilError, match="The first 2"): + data.groupby("key").transform(incorrect_function, engine="numba") + + with pytest.raises(NumbaUtilError, match="The first 2"): + data.groupby("key")["data"].transform(incorrect_function, engine="numba") + + +def test_check_nopython_kwargs(): + pytest.importorskip("numba") + + def incorrect_function(values, index, *, a): + return values + a + + def correct_function(values, index, a): + return values + a + + data = pd.DataFrame( + {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, + columns=["key", "data"], + ) + # py signature binding + with pytest.raises( + TypeError, match="missing a required (keyword-only argument|argument): 'a'" + ): + data.groupby("key").transform(incorrect_function, engine="numba", b=1) + with pytest.raises(TypeError, match="missing a required argument: 'a'"): + data.groupby("key").transform(correct_function, engine="numba", b=1) + + with pytest.raises( + TypeError, match="missing a required (keyword-only argument|argument): 'a'" + ): + data.groupby("key")["data"].transform(incorrect_function, engine="numba", b=1) + with pytest.raises(TypeError, match="missing a required argument: 'a'"): + data.groupby("key")["data"].transform(correct_function, engine="numba", b=1) + + # numba signature check after binding + with pytest.raises(NumbaUtilError, match="numba does not support"): + data.groupby("key").transform(incorrect_function, engine="numba", a=1) + actual = data.groupby("key").transform(correct_function, engine="numba", a=1) + tm.assert_frame_equal(data[["data"]] + 1, actual) + + with pytest.raises(NumbaUtilError, match="numba does not support"): + data.groupby("key")["data"].transform(incorrect_function, engine="numba", a=1) + actual = data.groupby("key")["data"].transform( + correct_function, engine="numba", a=1 + ) + tm.assert_series_equal(data["data"] + 1, actual) + + +@pytest.mark.filterwarnings("ignore") +# Filter warnings when parallel=True and the function can't be parallelized by Numba +@pytest.mark.parametrize("jit", [True, False]) +def test_numba_vs_cython(jit, frame_or_series, nogil, parallel, as_index): + pytest.importorskip("numba") + + def func(values, index): + return values + 1 + + if jit: + # Test accepted jitted functions + import numba + + func = numba.jit(func) + + data = pd.DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] + ) + engine_kwargs = {"nogil": nogil, "parallel": parallel} + grouped = data.groupby(0, as_index=as_index) + if frame_or_series is pd.Series: + grouped = grouped[1] + + result = grouped.transform(func, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.transform(lambda x: x + 1, engine="cython") + + tm.assert_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore") +# Filter warnings when parallel=True and the function can't be parallelized by Numba +@pytest.mark.parametrize("jit", [True, False]) +def test_cache(jit, frame_or_series, nogil, parallel): + # Test that the functions are cached correctly if we switch functions + pytest.importorskip("numba") + + def func_1(values, index): + return values + 1 + + def func_2(values, index): + return values * 5 + + if jit: + import numba + + func_1 = numba.jit(func_1) + func_2 = numba.jit(func_2) + + data = pd.DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] + ) + engine_kwargs = {"nogil": nogil, "parallel": parallel} + grouped = data.groupby(0) + if frame_or_series is pd.Series: + grouped = grouped[1] + + result = grouped.transform(func_1, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.transform(lambda x: x + 1, engine="cython") + tm.assert_equal(result, expected) + + result = grouped.transform(func_2, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.transform(lambda x: x * 5, engine="cython") + tm.assert_equal(result, expected) + + # Retest func_1 which should use the cache + result = grouped.transform(func_1, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.transform(lambda x: x + 1, engine="cython") + tm.assert_equal(result, expected) + + +def test_use_global_config(): + pytest.importorskip("numba") + + def func_1(values, index): + return values + 1 + + data = pd.DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] + ) + grouped = data.groupby(0) + expected = grouped.transform(func_1, engine="numba") + with pd.option_context("compute.use_numba", True): + result = grouped.transform(func_1, engine=None) + tm.assert_frame_equal(expected, result) + + +# TODO: Test more than just reductions (e.g. actually test transformations once we have +@pytest.mark.parametrize( + "agg_func", [["min", "max"], "min", {"B": ["min", "max"], "C": "sum"}] +) +def test_string_cython_vs_numba(agg_func, numba_supported_reductions): + pytest.importorskip("numba") + agg_func, kwargs = numba_supported_reductions + data = pd.DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] + ) + grouped = data.groupby(0) + + result = grouped.transform(agg_func, engine="numba", **kwargs) + expected = grouped.transform(agg_func, engine="cython", **kwargs) + tm.assert_frame_equal(result, expected) + + result = grouped[1].transform(agg_func, engine="numba", **kwargs) + expected = grouped[1].transform(agg_func, engine="cython", **kwargs) + tm.assert_series_equal(result, expected) + + +def test_args_not_cached(): + # GH 41647 + pytest.importorskip("numba") + + def sum_last(values, index, n): + return values[-n:].sum() + + df = pd.DataFrame({"id": [0, 0, 1, 1], "x": [1, 1, 1, 1]}) + grouped_x = df.groupby("id")["x"] + result = grouped_x.transform(sum_last, 1, engine="numba") + expected = pd.Series([1.0] * 4, name="x") + tm.assert_series_equal(result, expected) + + result = grouped_x.transform(sum_last, 2, engine="numba") + expected = pd.Series([2.0] * 4, name="x") + tm.assert_series_equal(result, expected) + + +def test_index_data_correctly_passed(): + # GH 43133 + pytest.importorskip("numba") + + def f(values, index): + return index - 1 + + df = pd.DataFrame({"group": ["A", "A", "B"], "v": [4, 5, 6]}, index=[-1, -2, -3]) + result = df.groupby("group").transform(f, engine="numba") + expected = pd.DataFrame([-2.0, -3.0, -4.0], columns=["v"], index=[-1, -2, -3]) + tm.assert_frame_equal(result, expected) + + +def test_index_order_consistency_preserved(): + # GH 57069 + pytest.importorskip("numba") + + def f(values, index): + return values + + df = pd.DataFrame( + {"vals": [0.0, 1.0, 2.0, 3.0], "group": [0, 1, 0, 1]}, index=range(3, -1, -1) + ) + result = df.groupby("group")["vals"].transform(f, engine="numba") + expected = pd.Series([0.0, 1.0, 2.0, 3.0], index=range(3, -1, -1), name="vals") + tm.assert_series_equal(result, expected) + + +def test_engine_kwargs_not_cached(): + # If the user passes a different set of engine_kwargs don't return the same + # jitted function + pytest.importorskip("numba") + nogil = True + parallel = False + + def func_kwargs(values, index): + return nogil + parallel + + engine_kwargs = {"nogil": nogil, "parallel": parallel} + df = pd.DataFrame({"value": [0, 0, 0]}) + result = df.groupby(level=0).transform( + func_kwargs, engine="numba", engine_kwargs=engine_kwargs + ) + expected = pd.DataFrame({"value": [1.0, 1.0, 1.0]}) + tm.assert_frame_equal(result, expected) + + nogil = False + engine_kwargs = {"nogil": nogil, "parallel": parallel} + result = df.groupby(level=0).transform( + func_kwargs, engine="numba", engine_kwargs=engine_kwargs + ) + expected = pd.DataFrame({"value": [0.0, 0.0, 0.0]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore") +def test_multiindex_one_key(nogil, parallel): + pytest.importorskip("numba") + + def numba_func(values, index): + return 1 + + df = pd.DataFrame([{"A": 1, "B": 2, "C": 3}]).set_index(["A", "B"]) + engine_kwargs = {"nogil": nogil, "parallel": parallel} + result = df.groupby("A").transform( + numba_func, engine="numba", engine_kwargs=engine_kwargs + ) + expected = pd.DataFrame([{"A": 1, "B": 2, "C": 1.0}]).set_index(["A", "B"]) + tm.assert_frame_equal(result, expected) + + +def test_multiindex_multi_key_not_supported(nogil, parallel): + pytest.importorskip("numba") + + def numba_func(values, index): + return 1 + + df = pd.DataFrame([{"A": 1, "B": 2, "C": 3}]).set_index(["A", "B"]) + engine_kwargs = {"nogil": nogil, "parallel": parallel} + with pytest.raises(NotImplementedError, match="more than 1 grouping labels"): + df.groupby(["A", "B"]).transform( + numba_func, engine="numba", engine_kwargs=engine_kwargs + ) + + +def test_multilabel_numba_vs_cython(numba_supported_reductions): + pytest.importorskip("numba") + reduction, kwargs = numba_supported_reductions + df = pd.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), + } + ) + gb = df.groupby(["A", "B"]) + res_agg = gb.transform(reduction, engine="numba", **kwargs) + expected_agg = gb.transform(reduction, engine="cython", **kwargs) + tm.assert_frame_equal(res_agg, expected_agg) + + +def test_multilabel_udf_numba_vs_cython(): + pytest.importorskip("numba") + df = pd.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), + } + ) + gb = df.groupby(["A", "B"]) + result = gb.transform( + lambda values, index: (values - values.min()) / (values.max() - values.min()), + engine="numba", + ) + expected = gb.transform( + lambda x: (x - x.min()) / (x.max() - x.min()), engine="cython" + ) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/groupby/transform/test_transform.py b/venv/lib/python3.14/site-packages/pandas/tests/groupby/transform/test_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..1364347fe0d54c1fb873bad9fd77e772368d8927 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/groupby/transform/test_transform.py @@ -0,0 +1,1703 @@ +"""test with the .transform""" + +import numpy as np +import pytest + +from pandas._libs import lib +from pandas.errors import Pandas4Warning + +from pandas.core.dtypes.common import ensure_platform_int + +import pandas as pd +import pandas._testing as tm +from pandas.core.groupby import NamedAgg +from pandas.tests.groupby import get_groupby_method_args + + +def assert_fp_equal(a, b): + assert (np.abs(a - b) < 1e-12).all() + + +def test_transform(): + data = pd.Series(np.arange(9) // 3, index=np.arange(9)) + + index = np.arange(9) + np.random.default_rng(2).shuffle(index) + data = data.reindex(index) + + grouped = data.groupby(lambda x: x // 3) + + transformed = grouped.transform(lambda x: x * x.sum()) + assert transformed[7] == 12 + + # GH 8046 + # make sure that we preserve the input order + + df = pd.DataFrame( + np.arange(6, dtype="int64").reshape(3, 2), columns=["a", "b"], index=[0, 2, 1] + ) + key = [0, 0, 1] + expected = ( + df.sort_index() + .groupby(key) + .transform(lambda x: x - x.mean()) + .groupby(key) + .mean() + ) + result = df.groupby(key).transform(lambda x: x - x.mean()).groupby(key).mean() + tm.assert_frame_equal(result, expected) + + def demean(arr): + return arr - arr.mean(axis=0) + + people = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 5)), + columns=["a", "b", "c", "d", "e"], + index=["Joe", "Steve", "Wes", "Jim", "Travis"], + ) + key = ["one", "two", "one", "two", "one"] + result = people.groupby(key).transform(demean).groupby(key).mean() + expected = people.groupby(key, group_keys=False).apply(demean).groupby(key).mean() + tm.assert_frame_equal(result, expected) + + # GH 8430 + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((50, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=50, freq="B"), + ) + g = df.groupby(pd.Grouper(freq="ME")) + g.transform(lambda x: x - 1) + + # GH 9700 + df = pd.DataFrame({"a": range(5, 10), "b": range(5)}) + result = df.groupby("a").transform(max) + expected = pd.DataFrame({"b": range(5)}) + tm.assert_frame_equal(result, expected) + + +def test_transform_with_list_like(): + # GH#58318 + df = pd.DataFrame({"col": list("aab"), "val": range(3), "another": range(3)}) + result = df.groupby("col").transform(["sum", "min"]) + expected = pd.DataFrame( + { + ("val", "sum"): [1, 1, 2], + ("val", "min"): [0, 0, 2], + ("another", "sum"): [1, 1, 2], + ("another", "min"): [0, 0, 2], + } + ) + expected.columns = pd.MultiIndex.from_tuples( + [("val", "sum"), ("val", "min"), ("another", "sum"), ("another", "min")] + ) + tm.assert_frame_equal(result, expected) + + +def test_transform_with_list_like_single_column(): + # GH#58318 - only one non-key column + df = pd.DataFrame({"col": list("aab"), "val": range(3)}) + result = df.groupby("col").transform(["sum", "min"]) + expected = pd.DataFrame({("val", "sum"): [1, 1, 2], ("val", "min"): [0, 0, 2]}) + expected.columns = pd.MultiIndex.from_tuples([("val", "sum"), ("val", "min")]) + tm.assert_frame_equal(result, expected) + + +def test_transform_with_dict(): + # GH#58318 - plain {"col": "func"} dict selects specific columns only + df = pd.DataFrame({"col": list("aab"), "val": range(3), "another": range(3)}) + result = df.groupby("col").transform({"val": "sum", "another": "min"}) + expected = pd.DataFrame({"val": [1, 1, 2], "another": [0, 0, 2]}) + tm.assert_frame_equal(result, expected) + + +def test_transform_with_dict_subset_columns(): + # GH#58318 - dict only touches the listed columns (not all non-key cols) + df = pd.DataFrame( + {"col": list("aab"), "val": range(3), "other": range(3), "extra": range(3)} + ) + result = df.groupby("col").transform({"val": "sum"}) + expected = pd.DataFrame({"val": [1, 1, 2]}) + tm.assert_frame_equal(result, expected) + + +def test_transform_with_dict_of_lists_raises(): + # GH#58318 - dict-of-lists is not yet implemented; should raise clearly + df = pd.DataFrame({"col": list("aab"), "val": range(3)}) + with pytest.raises(NotImplementedError, match="dict of lists"): + df.groupby("col").transform({"val": ["sum", "min"]}) + + +def test_transform_with_namedagg(): + # GH#58318 - NamedAgg lets user rename output columns and select source col + df = pd.DataFrame({"A": list("aaabbbccc"), "B": range(9), "D": range(9, 18)}) + result = df.groupby("A").transform( + b_min=NamedAgg(column="B", aggfunc="min"), + d_sum=NamedAgg(column="D", aggfunc="sum"), + ) + expected = pd.DataFrame( + { + "b_min": [0, 0, 0, 3, 3, 3, 6, 6, 6], + "d_sum": [30, 30, 30, 39, 39, 39, 48, 48, 48], + } + ) + tm.assert_frame_equal(result, expected) + + +def test_transform_with_namedagg_same_source_column(): + # GH#58318 - multiple NamedAgg targeting the same source column + df = pd.DataFrame({"A": list("aaabbbccc"), "B": range(9, 18)}) + result = df.groupby("A").transform( + b_min=NamedAgg(column="B", aggfunc="min"), + b_max=NamedAgg(column="B", aggfunc="max"), + ) + expected = pd.DataFrame( + { + "b_min": [9, 9, 9, 12, 12, 12, 15, 15, 15], + "b_max": [11, 11, 11, 14, 14, 14, 17, 17, 17], + } + ) + tm.assert_frame_equal(result, expected) + + +def test_transform_with_namedagg_plain_tuple(): + # GH#58318 - plain tuples are accepted just like NamedAgg (namedtuple) + df = pd.DataFrame({"A": list("aaabbb"), "B": range(6)}) + result = df.groupby("A").transform( + b_sum=NamedAgg(column="B", aggfunc="sum"), + ) + # Plain tuple equivalent: + result2 = df.groupby("A").transform( + b_sum=("B", "sum"), + ) + tm.assert_frame_equal(result, result2) + + +def test_transform_series_groupby_list_raises(): + # GH#58318 - SeriesGroupBy.transform with list not yet implemented + g = pd.DataFrame({"col": list("aaabbb"), "val": range(6)}).groupby("col")["val"] + with pytest.raises(NotImplementedError, match="SeriesGroupBy"): + g.transform(["sum", "min"]) + + +def test_transform_fast(): + df = pd.DataFrame( + { + "id": np.arange(10) / 3, + "val": np.random.default_rng(2).standard_normal(10), + } + ) + + grp = df.groupby("id")["val"] + + values = np.repeat(grp.mean().values, ensure_platform_int(grp.count().values)) + expected = pd.Series(values, index=df.index, name="val") + + result = grp.transform(np.mean) + tm.assert_series_equal(result, expected) + + result = grp.transform("mean") + tm.assert_series_equal(result, expected) + + +def test_transform_fast2(): + # GH 12737 + df = pd.DataFrame( + { + "grouping": [0, 1, 1, 3], + "f": [1.1, 2.1, 3.1, 4.5], + "d": pd.date_range("2014-1-1", "2014-1-4", unit="ns"), + "i": [1, 2, 3, 4], + }, + columns=["grouping", "f", "i", "d"], + ) + result = df.groupby("grouping").transform("first") + + dates = pd.Index( + [ + pd.Timestamp("2014-1-1"), + pd.Timestamp("2014-1-2"), + pd.Timestamp("2014-1-2"), + pd.Timestamp("2014-1-4"), + ], + dtype="M8[ns]", + ) + expected = pd.DataFrame( + {"f": [1.1, 2.1, 2.1, 4.5], "d": dates, "i": [1, 2, 2, 4]}, + columns=["f", "i", "d"], + ) + tm.assert_frame_equal(result, expected) + + # selection + result = df.groupby("grouping")[["f", "i"]].transform("first") + expected = expected[["f", "i"]] + tm.assert_frame_equal(result, expected) + + +def test_transform_fast3(): + # dup columns + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["g", "a", "a"]) + result = df.groupby("g").transform("first") + expected = df.drop("g", axis=1) + tm.assert_frame_equal(result, expected) + + +def test_transform_broadcast(tsframe, ts): + grouped = ts.groupby(lambda x: x.month) + result = grouped.transform(np.mean) + + tm.assert_index_equal(result.index, ts.index) + for _, gp in grouped: + assert_fp_equal(result.reindex(gp.index), gp.mean()) + + grouped = tsframe.groupby(lambda x: x.month) + result = grouped.transform(np.mean) + tm.assert_index_equal(result.index, tsframe.index) + for _, gp in grouped: + agged = gp.mean(axis=0) + res = result.reindex(gp.index) + for col in tsframe: + assert_fp_equal(res[col], agged[col]) + + +def test_transform_axis_ts(tsframe): + # make sure that we are setting the axes correctly + # in the presence of a non-monotonic indexer + # GH12713 + + base = tsframe.iloc[0:5] + r = len(base.index) + c = len(base.columns) + tso = pd.DataFrame( + np.random.default_rng(2).standard_normal((r, c)), + index=base.index, + columns=base.columns, + dtype="float64", + ) + # monotonic + ts = tso + grouped = ts.groupby(lambda x: x.weekday(), group_keys=False) + result = ts - grouped.transform("mean") + expected = grouped.apply(lambda x: x - x.mean(axis=0)) + tm.assert_frame_equal(result, expected) + + # non-monotonic + ts = tso.iloc[[1, 0, *list(range(2, len(base)))]] + grouped = ts.groupby(lambda x: x.weekday(), group_keys=False) + result = ts - grouped.transform("mean") + expected = grouped.apply(lambda x: x - x.mean(axis=0)) + tm.assert_frame_equal(result, expected) + + +def test_transform_dtype(): + # GH 9807 + # Check transform dtype output is preserved + df = pd.DataFrame([[1, 3], [2, 3]]) + result = df.groupby(1).transform("mean") + expected = pd.DataFrame([[1.5], [1.5]]) + tm.assert_frame_equal(result, expected) + + +def test_transform_bug(): + # GH 5712 + # transforming on a datetime column + df = pd.DataFrame({"A": pd.Timestamp("20130101"), "B": np.arange(5)}) + result = df.groupby("A")["B"].transform(lambda x: x.rank(ascending=False)) + expected = pd.Series(np.arange(5, 0, step=-1), name="B", dtype="float64") + tm.assert_series_equal(result, expected) + + +def test_transform_numeric_to_boolean(): + # GH 16875 + # inconsistency in transforming boolean values + expected = pd.Series([True, True], name="A") + + df = pd.DataFrame({"A": [1.1, 2.2], "B": [1, 2]}) + result = df.groupby("B").A.transform(lambda x: True) + tm.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": [1, 2], "B": [1, 2]}) + result = df.groupby("B").A.transform(lambda x: True) + tm.assert_series_equal(result, expected) + + +def test_transform_datetime_to_timedelta(): + # GH 15429 + # transforming a datetime to timedelta + df = pd.DataFrame({"A": pd.Timestamp("20130101"), "B": np.arange(5)}) + expected = pd.Series( + pd.Timestamp("20130101") - pd.Timestamp("20130101"), index=range(5), name="A" + ) + + # this does date math without changing result type in transform + base_time = df["A"][0] + result = ( + df.groupby("A")["A"].transform(lambda x: x.max() - x.min() + base_time) + - base_time + ) + tm.assert_series_equal(result, expected) + + # this does date math and causes the transform to return timedelta + result = df.groupby("A")["A"].transform(lambda x: x.max() - x.min()) + tm.assert_series_equal(result, expected) + + +def test_transform_datetime_to_numeric(): + # GH 10972 + # convert dt to float + df = pd.DataFrame({"a": 1, "b": pd.date_range("2015-01-01", periods=2, freq="D")}) + result = df.groupby("a").b.transform( + lambda x: x.dt.day_of_week - x.dt.day_of_week.mean() + ) + + expected = pd.Series([-0.5, 0.5], name="b") + tm.assert_series_equal(result, expected) + + # convert dt to int + df = pd.DataFrame({"a": 1, "b": pd.date_range("2015-01-01", periods=2, freq="D")}) + result = df.groupby("a").b.transform( + lambda x: x.dt.day_of_week - x.dt.day_of_week.min() + ) + + expected = pd.Series([0, 1], dtype=np.int32, name="b") + tm.assert_series_equal(result, expected) + + +def test_transform_casting(): + # 13046 + times = [ + "13:43:27", + "14:26:19", + "14:29:01", + "18:39:34", + "18:40:18", + "18:44:30", + "18:46:00", + "18:52:15", + "18:59:59", + "19:17:48", + "19:21:38", + ] + df = pd.DataFrame( + { + "A": [f"B-{i}" for i in range(11)], + "ID3": np.take( + ["a", "b", "c", "d", "e"], [0, 1, 2, 1, 3, 1, 1, 1, 4, 1, 1] + ), + "DATETIME": pd.to_datetime([f"2014-10-08 {time}" for time in times]), + }, + index=pd.RangeIndex(11, name="idx"), + ) + + result = df.groupby("ID3")["DATETIME"].transform(lambda x: x.diff()) + assert lib.is_np_dtype(result.dtype, "m") + + result = df[["ID3", "DATETIME"]].groupby("ID3").transform(lambda x: x.diff()) + assert lib.is_np_dtype(result.DATETIME.dtype, "m") + + +def test_transform_multiple(ts): + grouped = ts.groupby([lambda x: x.year, lambda x: x.month]) + grouped.transform(lambda x: x * 2) + grouped.transform(np.mean) + + +def test_dispatch_transform(tsframe): + df = tsframe[::5].reindex(tsframe.index) + + grouped = df.groupby(lambda x: x.month) + + filled = grouped.ffill() + fillit = lambda x: x.ffill() + expected = df.groupby(lambda x: x.month).transform(fillit) + tm.assert_frame_equal(filled, expected) + + +def test_transform_transformation_func(transformation_func): + # GH 30918 + df = pd.DataFrame( + { + "A": ["foo", "foo", "foo", "foo", "bar", "bar", "baz"], + "B": [1, 2, np.nan, 3, 3, np.nan, 4], + }, + index=pd.date_range("2020-01-01", "2020-01-07"), + ) + if transformation_func == "cumcount": + test_op = lambda x: x.transform("cumcount") + mock_op = lambda x: pd.Series(range(len(x)), x.index) + elif transformation_func == "ngroup": + test_op = lambda x: x.transform("ngroup") + counter = -1 + + def mock_op(x): + nonlocal counter + counter += 1 + return pd.Series(counter, index=x.index) + + else: + test_op = lambda x: x.transform(transformation_func) + mock_op = lambda x: getattr(x, transformation_func)() + + result = test_op(df.groupby("A")) + + # pass the group in same order as iterating `for ... in df.groupby(...)` + # but reorder to match df's index since this is a transform + groups = [df[["B"]].iloc[4:6], df[["B"]].iloc[6:], df[["B"]].iloc[:4]] + expected = pd.concat([mock_op(g) for g in groups]).sort_index() + # sort_index does not preserve the freq + expected = expected.set_axis(df.index) + + if transformation_func in ("cumcount", "ngroup"): + tm.assert_series_equal(result, expected) + else: + tm.assert_frame_equal(result, expected) + + +def test_transform_select_columns(df): + f = lambda x: x.mean() + result = df.groupby("A")[["C", "D"]].transform(f) + + selection = df[["C", "D"]] + expected = selection.groupby(df["A"]).transform(f) + + tm.assert_frame_equal(result, expected) + + +def test_transform_nuisance_raises(df, using_infer_string): + # case that goes through _transform_item_by_item + + df.columns = ["A", "B", "B", "D"] + + # this also tests orderings in transform between + # series/frame to make sure it's consistent + grouped = df.groupby("A") + + gbc = grouped["B"] + msg = "Could not convert" + if using_infer_string: + msg = "Cannot perform reduction 'mean' with string dtype" + with pytest.raises(TypeError, match=msg): + gbc.transform(lambda x: np.mean(x)) + + with pytest.raises(TypeError, match=msg): + df.groupby("A").transform(lambda x: np.mean(x)) + + +def test_transform_function_aliases(df): + result = df.groupby("A").transform("mean", numeric_only=True) + expected = df.groupby("A")[["C", "D"]].transform(np.mean) + tm.assert_frame_equal(result, expected) + + result = df.groupby("A")["C"].transform("mean") + expected = df.groupby("A")["C"].transform(np.mean) + tm.assert_series_equal(result, expected) + + +def test_series_fast_transform_date(): + # GH 13191 + df = pd.DataFrame( + { + "grouping": [np.nan, 1, 1, 3], + "d": pd.date_range("2014-1-1", "2014-1-4", unit="ns"), + } + ) + result = df.groupby("grouping")["d"].transform("first") + dates = [ + pd.NaT, + pd.Timestamp("2014-1-2"), + pd.Timestamp("2014-1-2"), + pd.Timestamp("2014-1-4"), + ] + expected = pd.Series(dates, name="d", dtype="M8[ns]") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("func", [lambda x: np.nansum(x), sum]) +def test_transform_length(func): + # GH 9697 + df = pd.DataFrame({"col1": [1, 1, 2, 2], "col2": [1, 2, 3, np.nan]}) + if func is sum: + expected = pd.Series([3.0, 3.0, np.nan, np.nan]) + else: + expected = pd.Series([3.0] * 4) + + results = [ + df.groupby("col1").transform(func)["col2"], + df.groupby("col1")["col2"].transform(func), + ] + for result in results: + tm.assert_series_equal(result, expected, check_names=False) + + +def test_transform_coercion(): + # 14457 + # when we are transforming be sure to not coerce + # via assignment + df = pd.DataFrame({"A": ["a", "a", "b", "b"], "B": [0, 1, 3, 4]}) + g = df.groupby("A") + + expected = g.transform(np.mean) + result = g.transform(lambda x: np.mean(x, axis=0)) + tm.assert_frame_equal(result, expected) + + +def test_groupby_transform_with_int(using_infer_string): + # GH 3740, make sure that we might upcast on item-by-item transform + + # floats + df = pd.DataFrame( + { + "A": [1, 1, 1, 2, 2, 2], + "B": pd.Series(1, dtype="float64"), + "C": pd.Series([1, 2, 3, 1, 2, 3], dtype="float64"), + "D": "foo", + } + ) + with np.errstate(all="ignore"): + result = df.groupby("A")[["B", "C"]].transform( + lambda x: (x - x.mean()) / x.std() + ) + expected = pd.DataFrame( + {"B": np.nan, "C": pd.Series([-1, 0, 1, -1, 0, 1], dtype="float64")} + ) + tm.assert_frame_equal(result, expected) + + # int case + df = pd.DataFrame( + { + "A": [1, 1, 1, 2, 2, 2], + "B": 1, + "C": [1, 2, 3, 1, 2, 3], + "D": "foo", + } + ) + msg = "Could not convert" + if using_infer_string: + msg = "Cannot perform reduction 'mean' with string dtype" + with np.errstate(all="ignore"): + with pytest.raises(TypeError, match=msg): + df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) + result = df.groupby("A")[["B", "C"]].transform( + lambda x: (x - x.mean()) / x.std() + ) + expected = pd.DataFrame({"B": np.nan, "C": [-1.0, 0.0, 1.0, -1.0, 0.0, 1.0]}) + tm.assert_frame_equal(result, expected) + + # int that needs float conversion + s = pd.Series([2, 3, 4, 10, 5, -1]) + df = pd.DataFrame({"A": [1, 1, 1, 2, 2, 2], "B": 1, "C": s, "D": "foo"}) + with np.errstate(all="ignore"): + with pytest.raises(TypeError, match=msg): + df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) + result = df.groupby("A")[["B", "C"]].transform( + lambda x: (x - x.mean()) / x.std() + ) + + s1 = s.iloc[0:3] + s1 = (s1 - s1.mean()) / s1.std() + s2 = s.iloc[3:6] + s2 = (s2 - s2.mean()) / s2.std() + expected = pd.DataFrame({"B": np.nan, "C": pd.concat([s1, s2])}) + tm.assert_frame_equal(result, expected) + + # int doesn't get downcasted + result = df.groupby("A")[["B", "C"]].transform(lambda x: x * 2 / 2) + expected = pd.DataFrame({"B": 1.0, "C": [2.0, 3.0, 4.0, 10.0, 5.0, -1.0]}) + tm.assert_frame_equal(result, expected) + + +def test_groupby_transform_with_nan_group(): + # GH 9941 + df = pd.DataFrame({"a": range(10), "b": [1, 1, 2, 3, np.nan, 4, 4, 5, 5, 5]}) + result = df.groupby(df.b)["a"].transform(max) + expected = pd.Series( + [1.0, 1.0, 2.0, 3.0, np.nan, 6.0, 6.0, 9.0, 9.0, 9.0], name="a" + ) + tm.assert_series_equal(result, expected) + + +def test_transform_mixed_type(): + index = pd.MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1], [1, 2, 3, 1, 2, 3]]) + df = pd.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): + group["g"] = group["d"] * 2 + return group[:1] + + grouped = df.groupby("c") + result = grouped.apply(f) + + assert result["d"].dtype == np.float64 + + # this is by definition a mutating operation! + for key, group in grouped: + res = f(group.drop(columns="c")) + tm.assert_frame_equal(res, result.loc[key]) + + +@pytest.mark.parametrize( + "op, args, targop", + [ + ("cumprod", (), lambda x: x.cumprod()), + ("cumsum", (), lambda x: x.cumsum()), + ("shift", (-1,), lambda x: x.shift(-1)), + ("shift", (1,), lambda x: x.shift()), + ], +) +def test_cython_transform_series(op, args, targop): + # GH 4095 + s = pd.Series(np.random.default_rng(2).standard_normal(1000)) + s_missing = s.copy() + s_missing.iloc[2:10] = np.nan + labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) + + # series + for data in [s, s_missing]: + # print(data.head()) + expected = data.groupby(labels).transform(targop) + + tm.assert_series_equal(expected, data.groupby(labels).transform(op, *args)) + tm.assert_series_equal(expected, getattr(data.groupby(labels), op)(*args)) + + +@pytest.mark.parametrize("op", ["cumprod", "cumsum"]) +@pytest.mark.parametrize( + "input, exp", + [ + # When everything is NaN + ({"key": ["b"] * 10, "value": np.nan}, pd.Series([np.nan] * 10, name="value")), + # When there is a single NaN + ( + {"key": ["b"] * 10 + ["a"] * 2, "value": [3] * 3 + [np.nan] + [3] * 8}, + { + ("cumprod", False): [3.0, 9.0, 27.0] + [np.nan] * 7 + [3.0, 9.0], + ("cumprod", True): [ + 3.0, + 9.0, + 27.0, + np.nan, + 81.0, + 243.0, + 729.0, + 2187.0, + 6561.0, + 19683.0, + 3.0, + 9.0, + ], + ("cumsum", False): [3.0, 6.0, 9.0] + [np.nan] * 7 + [3.0, 6.0], + ("cumsum", True): [ + 3.0, + 6.0, + 9.0, + np.nan, + 12.0, + 15.0, + 18.0, + 21.0, + 24.0, + 27.0, + 3.0, + 6.0, + ], + }, + ), + ], +) +def test_groupby_cum_skipna(op, skipna, input, exp): + df = pd.DataFrame(input) + result = df.groupby("key")["value"].transform(op, skipna=skipna) + if isinstance(exp, dict): + expected = exp[(op, skipna)] + else: + expected = exp + expected = pd.Series(expected, name="value") + tm.assert_series_equal(expected, result) + + +@pytest.fixture +def frame(): + floating = pd.Series(np.random.default_rng(2).standard_normal(10)) + floating_missing = floating.copy() + floating_missing.iloc[2:7] = np.nan + strings = list("abcde") * 2 + strings_missing = strings[:] + strings_missing[5] = np.nan + + df = pd.DataFrame( + { + "float": floating, + "float_missing": floating_missing, + "int": [1, 1, 1, 1, 2] * 2, + "datetime": pd.date_range("1990-1-1", periods=10), + "timedelta": pd.timedelta_range(1, freq="s", periods=10), + "string": strings, + "string_missing": strings_missing, + "cat": pd.Categorical(strings), + }, + ) + return df + + +@pytest.fixture +def frame_mi(frame): + frame.index = pd.MultiIndex.from_product([range(5), range(2)]) + return frame + + +@pytest.mark.slow +@pytest.mark.parametrize( + "op, args, targop", + [ + ("cumprod", (), lambda x: x.cumprod()), + ("cumsum", (), lambda x: x.cumsum()), + ("shift", (-1,), lambda x: x.shift(-1)), + ("shift", (1,), lambda x: x.shift()), + ], +) +@pytest.mark.parametrize("df_fix", ["frame", "frame_mi"]) +@pytest.mark.parametrize( + "gb_target", + [ + {"by": np.random.default_rng(2).integers(0, 50, size=10).astype(float)}, + {"level": 0}, + {"by": "string"}, + pytest.param({"by": "string_missing"}, marks=pytest.mark.xfail), + {"by": ["int", "string"]}, + ], +) +def test_cython_transform_frame(request, op, args, targop, df_fix, gb_target): + df = request.getfixturevalue(df_fix) + gb = df.groupby(group_keys=False, **gb_target) + + if op != "shift" and "int" not in gb_target: + # numeric apply fastpath promotes dtype so have + # to apply separately and concat + i = gb[["int"]].apply(targop) + f = gb[["float", "float_missing"]].apply(targop) + expected = pd.concat([f, i], axis=1) + else: + expected = gb.apply(targop) + + expected = expected.sort_index(axis=1) + if op == "shift": + expected["string_missing"] = expected["string_missing"].fillna(np.nan) + by = gb_target.get("by") + if not isinstance(by, (str, list)) or (by != "string" and "string" not in by): + expected["string"] = expected["string"].fillna(np.nan) + + result = gb[expected.columns].transform(op, *args).sort_index(axis=1) + tm.assert_frame_equal(result, expected) + result = getattr(gb[expected.columns], op)(*args).sort_index(axis=1) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.slow +@pytest.mark.parametrize( + "op, args, targop", + [ + ("cumprod", (), lambda x: x.cumprod()), + ("cumsum", (), lambda x: x.cumsum()), + ("shift", (-1,), lambda x: x.shift(-1)), + ("shift", (1,), lambda x: x.shift()), + ], +) +@pytest.mark.parametrize("df_fix", ["frame", "frame_mi"]) +@pytest.mark.parametrize( + "gb_target", + [ + {"by": np.random.default_rng(2).integers(0, 50, size=10).astype(float)}, + {"level": 0}, + {"by": "string"}, + # TODO: create xfail condition given other params + # {"by": 'string_missing'}, + {"by": ["int", "string"]}, + ], +) +@pytest.mark.parametrize( + "column", + [ + "float", + "float_missing", + "int", + "datetime", + "timedelta", + "string", + "string_missing", + ], +) +def test_cython_transform_frame_column( + request, op, args, targop, df_fix, gb_target, column, using_infer_string +): + df = request.getfixturevalue(df_fix) + gb = df.groupby(group_keys=False, **gb_target) + c = column + if ( + c not in ["float", "int", "float_missing"] + and op != "shift" + and not (c == "timedelta" and op == "cumsum") + ): + if c == "timedelta": + msg = f"timedelta64 type does not support {op} operations" + elif c in ("string", "string_missing") and not using_infer_string: + msg = f"{op} is not supported for object dtype" + else: + # datetime, or the string columns under the str dtype + msg = "does not support operation" + with pytest.raises(TypeError, match=msg): + gb[c].transform(op) + with pytest.raises(TypeError, match=msg): + getattr(gb[c], op)() + else: + expected = gb[c].apply(targop) + expected.name = c + if c in ["string_missing", "string"]: + expected = expected.fillna(np.nan) + + res = gb[c].transform(op, *args) + tm.assert_series_equal(expected, res) + res2 = getattr(gb[c], op)(*args) + tm.assert_series_equal(expected, res2) + + +@pytest.mark.parametrize( + "cols,expected", + [ + ("a", pd.Series([1, 1, 1], name="a")), + ( + ["a", "c"], + pd.DataFrame({"a": [1, 1, 1], "c": [1, 1, 1]}), + ), + ], +) +@pytest.mark.parametrize("agg_func", ["count", "rank", "size"]) +def test_transform_numeric_ret(cols, expected, agg_func): + # GH#19200 and GH#27469 + df = pd.DataFrame( + {"a": pd.date_range("2018-01-01", periods=3), "b": range(3), "c": range(7, 10)} + ) + result = df.groupby("b")[cols].transform(agg_func) + + if agg_func == "rank": + expected = expected.astype("float") + elif agg_func == "size" and cols == ["a", "c"]: + # transform("size") returns a Series + expected = expected["a"].rename(None) + tm.assert_equal(result, expected) + + +def test_transform_ffill(): + # GH 24211 + data = [["a", 0.0], ["a", float("nan")], ["b", 1.0], ["b", float("nan")]] + df = pd.DataFrame(data, columns=["key", "values"]) + result = df.groupby("key").transform("ffill") + expected = pd.DataFrame({"values": [0.0, 0.0, 1.0, 1.0]}) + tm.assert_frame_equal(result, expected) + result = df.groupby("key")["values"].transform("ffill") + expected = pd.Series([0.0, 0.0, 1.0, 1.0], name="values") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("mix_groupings", [True, False]) +@pytest.mark.parametrize("as_series", [True, False]) +@pytest.mark.parametrize("val1,val2", [("foo", "bar"), (1, 2), (1.0, 2.0)]) +@pytest.mark.parametrize( + "fill_method,limit,exp_vals", + [ + ( + "ffill", + None, + [np.nan, np.nan, "val1", "val1", "val1", "val2", "val2", "val2"], + ), + ("ffill", 1, [np.nan, np.nan, "val1", "val1", np.nan, "val2", "val2", np.nan]), + ( + "bfill", + None, + ["val1", "val1", "val1", "val2", "val2", "val2", np.nan, np.nan], + ), + ("bfill", 1, [np.nan, "val1", "val1", np.nan, "val2", "val2", np.nan, np.nan]), + ], +) +def test_group_fill_methods( + mix_groupings, as_series, val1, val2, fill_method, limit, exp_vals +): + vals = [np.nan, np.nan, val1, np.nan, np.nan, val2, np.nan, np.nan] + _exp_vals = list(exp_vals) + # Overwrite placeholder values + for index, exp_val in enumerate(_exp_vals): + if exp_val == "val1": + _exp_vals[index] = val1 + elif exp_val == "val2": + _exp_vals[index] = val2 + + # Need to modify values and expectations depending on the + # Series / DataFrame that we ultimately want to generate + if mix_groupings: # ['a', 'b', 'a, 'b', ...] + keys = ["a", "b"] * len(vals) + + def interweave(list_obj): + temp = [] + for x in list_obj: + temp.extend([x, x]) + + return temp + + _exp_vals = interweave(_exp_vals) + vals = interweave(vals) + else: # ['a', 'a', 'a', ... 'b', 'b', 'b'] + keys = ["a"] * len(vals) + ["b"] * len(vals) + _exp_vals = _exp_vals * 2 + vals = vals * 2 + + df = pd.DataFrame({"key": keys, "val": vals}) + if as_series: + result = getattr(df.groupby("key")["val"], fill_method)(limit=limit) + exp = pd.Series(_exp_vals, name="val") + tm.assert_series_equal(result, exp) + else: + result = getattr(df.groupby("key"), fill_method)(limit=limit) + exp = pd.DataFrame({"val": _exp_vals}) + tm.assert_frame_equal(result, exp) + + +@pytest.mark.parametrize("fill_method", ["ffill", "bfill"]) +def test_pad_stable_sorting(fill_method): + # GH 21207 + x = [0] * 20 + y = [np.nan] * 10 + [1] * 10 + + if fill_method == "bfill": + y = y[::-1] + + df = pd.DataFrame({"x": x, "y": y}) + expected = df.drop("x", axis=1) + + result = getattr(df.groupby("x"), fill_method)() + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "freq", + [ + None, + pytest.param( + "D", + marks=pytest.mark.xfail( + reason="GH#23918 before method uses freq in vectorized approach" + ), + ), + ], +) +@pytest.mark.parametrize("periods", [1, -1]) +def test_pct_change(frame_or_series, freq, periods): + # GH 21200, 21621, 30463 + vals = [3, np.nan, np.nan, np.nan, 1, 2, 4, 10, np.nan, 4] + keys = ["a", "b"] + key_v = np.repeat(keys, len(vals)) + df = pd.DataFrame({"key": key_v, "vals": vals * 2}) + + df_g = df + grp = df_g.groupby(df.key) + + expected = grp["vals"].obj / grp["vals"].shift(periods) - 1 + + gb = df.groupby("key") + + if frame_or_series is pd.Series: + gb = gb["vals"] + else: + expected = expected.to_frame("vals") + + result = gb.pct_change(periods=periods, freq=freq) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "func, expected_status", + [ + ("ffill", ["shrt", "shrt", "lng", np.nan, "shrt", "ntrl", "ntrl"]), + ("bfill", ["shrt", "lng", "lng", "shrt", "shrt", "ntrl", np.nan]), + ], +) +def test_ffill_bfill_non_unique_multilevel(func, expected_status): + # GH 19437 + date = pd.to_datetime( + [ + "2018-01-01", + "2018-01-01", + "2018-01-01", + "2018-01-01", + "2018-01-02", + "2018-01-01", + "2018-01-02", + ] + ) + symbol = ["MSFT", "MSFT", "MSFT", "AAPL", "AAPL", "TSLA", "TSLA"] + status = ["shrt", np.nan, "lng", np.nan, "shrt", "ntrl", np.nan] + + df = pd.DataFrame({"date": date, "symbol": symbol, "status": status}) + df = df.set_index(["date", "symbol"]) + result = getattr(df.groupby("symbol")["status"], func)() + + index = pd.MultiIndex.from_tuples( + tuples=list(zip(*[date, symbol], strict=True)), names=["date", "symbol"] + ) + expected = pd.Series(expected_status, index=index, name="status") + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("func", [np.any, np.all]) +def test_any_all_np_func(func): + # GH 20653 + df = pd.DataFrame( + [["foo", True], [np.nan, True], ["foo", True]], columns=["key", "val"] + ) + + exp = pd.Series([True, np.nan, True], name="val") + + res = df.groupby("key")["val"].transform(func) + tm.assert_series_equal(res, exp) + + +def test_groupby_transform_rename(): + # https://github.com/pandas-dev/pandas/issues/23461 + def demean_rename(x): + result = x - x.mean() + + if isinstance(x, pd.Series): + return result + + result = result.rename(columns={c: f"{c}_demeaned" for c in result.columns}) + + return result + + df = pd.DataFrame({"group": list("ababa"), "value": [1, 1, 1, 2, 2]}) + expected = pd.DataFrame({"value": [-1.0 / 3, -0.5, -1.0 / 3, 0.5, 2.0 / 3]}) + + result = df.groupby("group").transform(demean_rename) + tm.assert_frame_equal(result, expected) + result_single = df.groupby("group").value.transform(demean_rename) + tm.assert_series_equal(result_single, expected["value"]) + + +@pytest.mark.parametrize("func", [min, max, np.min, np.max, "first", "last"]) +def test_groupby_transform_timezone_column(func): + # GH 24198 + ts = pd.Timestamp("2011-01-01", tz="UTC").tz_convert("Asia/Singapore") + result = pd.DataFrame({"end_time": [ts], "id": [1]}) + result["max_end_time"] = result.groupby("id").end_time.transform(func) + expected = pd.DataFrame([[ts, 1, ts]], columns=["end_time", "id", "max_end_time"]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "func, values", + [ + ("idxmin", ["1/1/2011"] * 2 + ["1/3/2011"] * 7 + ["1/10/2011"]), + ("idxmax", ["1/2/2011"] * 2 + ["1/9/2011"] * 7 + ["1/10/2011"]), + ], +) +def test_groupby_transform_with_datetimes(func, values): + # GH 15306 + dates = pd.date_range("1/1/2011", periods=10, freq="D", unit="ns") + + stocks = pd.DataFrame({"price": np.arange(10.0)}, index=dates) + stocks["week_id"] = dates.isocalendar().week + + result = stocks.groupby(stocks["week_id"])["price"].transform(func) + + expected = pd.Series( + data=pd.to_datetime(values).as_unit("ns"), index=dates, name="price" + ) + + tm.assert_series_equal(result, expected) + + +def test_groupby_transform_dtype(): + # GH 22243 + df = pd.DataFrame({"a": [1], "val": [1.35]}) + + result = df["val"].transform(lambda x: x.map(lambda y: f"+{y}")) + expected1 = pd.Series(["+1.35"], name="val") + tm.assert_series_equal(result, expected1) + + result = df.groupby("a")["val"].transform(lambda x: x.map(lambda y: f"+{y}")) + tm.assert_series_equal(result, expected1) + + result = df.groupby("a")["val"].transform(lambda x: x.map(lambda y: f"+({y})")) + expected2 = pd.Series(["+(1.35)"], name="val") + tm.assert_series_equal(result, expected2) + + df["val"] = df["val"].astype(object) + result = df.groupby("a")["val"].transform(lambda x: x.map(lambda y: f"+{y}")) + tm.assert_series_equal(result, expected1) + + +def test_transform_absent_categories(all_numeric_accumulations): + # GH 16771 + # cython transforms with more groups than rows + x_vals = [1] + x_cats = range(2) + y = [1] + df = pd.DataFrame({"x": pd.Categorical(x_vals, x_cats), "y": y}) + result = getattr(df.y.groupby(df.x, observed=False), all_numeric_accumulations)() + expected = df.y + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("func", ["ffill", "bfill", "shift"]) +@pytest.mark.parametrize("key, val", [("level", 0), ("by", pd.Series([0]))]) +def test_ffill_not_in_axis(func, key, val): + # GH 21521 + df = pd.DataFrame([[np.nan]]) + result = getattr(df.groupby(**{key: val}), func)() + expected = df + + tm.assert_frame_equal(result, expected) + + +def test_transform_invalid_name_raises(): + # GH#27486 + df = pd.DataFrame({"a": [0, 1, 1, 2]}) + g = df.groupby(["a", "b", "b", "c"]) + with pytest.raises(ValueError, match="not a valid function name"): + g.transform("some_arbitrary_name") + + # method exists on the object, but is not a valid transformation/agg + assert hasattr(g, "aggregate") # make sure the method exists + with pytest.raises(ValueError, match="not a valid function name"): + g.transform("aggregate") + + # Test SeriesGroupBy + g = df["a"].groupby(["a", "b", "b", "c"]) + with pytest.raises(ValueError, match="not a valid function name"): + g.transform("some_arbitrary_name") + + +def test_transform_agg_by_name(request, reduction_func, frame_or_series): + func = reduction_func + + obj = pd.DataFrame( + {"a": [0, 0, 0, 0, 1, 1, 1, 1], "b": range(8)}, + index=["A", "B", "C", "D", "E", "F", "G", "H"], + ) + if frame_or_series is pd.Series: + obj = obj["a"] + + g = obj.groupby(np.repeat([0, 1], 4)) + + if func == "corrwith" and isinstance(obj, pd.Series): # GH#32293 + # TODO: implement SeriesGroupBy.corrwith + assert not hasattr(g, func) + return + + args = get_groupby_method_args(reduction_func, obj) + if func == "corrwith": + warn = Pandas4Warning + msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + msg = "" + with tm.assert_produces_warning(warn, match=msg): + result = g.transform(func, *args) + + # this is the *definition* of a transformation + tm.assert_index_equal(result.index, obj.index) + + if func not in ("ngroup", "size") and obj.ndim == 2: + # size/ngroup return a Series, unlike other transforms + tm.assert_index_equal(result.columns, obj.columns) + + # verify that values were broadcasted across each group + second_group_values = pd.DataFrame(result).iloc[-4:, -1] + expected = pd.Series([second_group_values.iloc[0]] * 4) + tm.assert_series_equal( + second_group_values, expected, check_index=False, check_names=False + ) + + +def test_transform_lambda_with_datetimetz(): + # GH 27496 + df = pd.DataFrame( + { + "time": [ + pd.Timestamp("2010-07-15 03:14:45"), + pd.Timestamp("2010-11-19 18:47:06"), + ], + "timezone": ["Etc/GMT+4", "US/Eastern"], + } + ) + result = df.groupby(["timezone"])["time"].transform( + lambda x: x.dt.tz_localize(x.name) + ) + expected = pd.Series( + [ + pd.Timestamp("2010-07-15 03:14:45", tz="Etc/GMT+4"), + pd.Timestamp("2010-11-19 18:47:06", tz="US/Eastern"), + ], + name="time", + ) + tm.assert_series_equal(result, expected) + + +def test_transform_fastpath_raises(): + # GH#29631 case where fastpath defined in groupby.generic _choose_path + # raises, but slow_path does not + + df = pd.DataFrame({"A": [1, 1, 2, 2], "B": [1, -1, 1, 2]}) + gb = df.groupby("A") + + def func(grp): + # we want a function such that func(frame) fails but func.apply(frame) + # works + if grp.ndim == 2: + # Ensure that fast_path fails + raise NotImplementedError("Don't cross the streams") + return grp * 2 + + # Check that the fastpath raises, see _transform_general + obj = gb._obj_with_exclusions + gen = gb._grouper.get_iterator(obj) + fast_path, slow_path = gb._define_paths(func) + _, group = next(gen) + + with pytest.raises(NotImplementedError, match="Don't cross the streams"): + fast_path(group) + + result = gb.transform(func) + + expected = pd.DataFrame([2, -2, 2, 4], columns=["B"]) + tm.assert_frame_equal(result, expected) + + +def test_transform_lambda_indexing(): + # GH 7883 + df = pd.DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "flux", "foo", "flux"], + "B": ["one", "one", "two", "three", "two", "six", "five", "three"], + "C": range(8), + "D": range(8), + "E": range(8), + } + ) + df = df.set_index(["A", "B"]) + df = df.sort_index() + result = df.groupby(level="A").transform(lambda x: x.iloc[-1]) + expected = pd.DataFrame( + { + "C": [3, 3, 7, 7, 4, 4, 4, 4], + "D": [3, 3, 7, 7, 4, 4, 4, 4], + "E": [3, 3, 7, 7, 4, 4, 4, 4], + }, + index=pd.MultiIndex.from_tuples( + [ + ("bar", "one"), + ("bar", "three"), + ("flux", "six"), + ("flux", "three"), + ("foo", "five"), + ("foo", "one"), + ("foo", "two"), + ("foo", "two"), + ], + names=["A", "B"], + ), + ) + tm.assert_frame_equal(result, expected) + + +def test_categorical_and_not_categorical_key(observed): + # Checks that groupby-transform, when grouping by both a categorical + # and a non-categorical key, doesn't try to expand the output to include + # non-observed categories but instead matches the input shape. + # GH 32494 + df_with_categorical = pd.DataFrame( + { + "A": pd.Categorical(["a", "b", "a"], categories=["a", "b", "c"]), + "B": [1, 2, 3], + "C": ["a", "b", "a"], + } + ) + df_without_categorical = pd.DataFrame( + {"A": ["a", "b", "a"], "B": [1, 2, 3], "C": ["a", "b", "a"]} + ) + + # DataFrame case + result = df_with_categorical.groupby(["A", "C"], observed=observed).transform("sum") + expected = df_without_categorical.groupby(["A", "C"]).transform("sum") + tm.assert_frame_equal(result, expected) + expected_explicit = pd.DataFrame({"B": [4, 2, 4]}) + tm.assert_frame_equal(result, expected_explicit) + + # Series case + gb = df_with_categorical.groupby(["A", "C"], observed=observed) + gbp = gb["B"] + result = gbp.transform("sum") + expected = df_without_categorical.groupby(["A", "C"])["B"].transform("sum") + tm.assert_series_equal(result, expected) + expected_explicit = pd.Series([4, 2, 4], name="B") + tm.assert_series_equal(result, expected_explicit) + + +def test_string_rank_grouping(): + # GH 19354 + df = pd.DataFrame({"A": [1, 1, 2], "B": [1, 2, 3]}) + result = df.groupby("A").transform("rank") + expected = pd.DataFrame({"B": [1.0, 2.0, 1.0]}) + tm.assert_frame_equal(result, expected) + + +def test_transform_cumcount(): + # GH 27472 + df = pd.DataFrame({"a": [0, 0, 0, 1, 1, 1], "b": range(6)}) + grp = df.groupby(np.repeat([0, 1], 3)) + + result = grp.cumcount() + expected = pd.Series([0, 1, 2, 0, 1, 2]) + tm.assert_series_equal(result, expected) + + result = grp.transform("cumcount") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("keys", [["A1"], ["A1", "A2"]]) +def test_null_group_lambda_self(sort, dropna, keys): + # GH 17093 + size = 50 + nulls1 = np.random.default_rng(2).choice([False, True], size) + nulls2 = np.random.default_rng(2).choice([False, True], size) + # Whether a group contains a null value or not + nulls_grouper = nulls1 if len(keys) == 1 else nulls1 | nulls2 + + a1 = np.random.default_rng(2).integers(0, 5, size=size).astype(float) + a1[nulls1] = np.nan + a2 = np.random.default_rng(2).integers(0, 5, size=size).astype(float) + a2[nulls2] = np.nan + values = np.random.default_rng(2).integers(0, 5, size=a1.shape) + df = pd.DataFrame({"A1": a1, "A2": a2, "B": values}) + + expected_values = values + if dropna and nulls_grouper.any(): + expected_values = expected_values.astype(float) + expected_values[nulls_grouper] = np.nan + expected = pd.DataFrame(expected_values, columns=["B"]) + + gb = df.groupby(keys, dropna=dropna, sort=sort) + result = gb[["B"]].transform(lambda x: x) + tm.assert_frame_equal(result, expected) + + +def test_null_group_str_reducer(request, dropna, reduction_func): + # GH 17093 + if reduction_func == "corrwith": + msg = "incorrectly raises" + request.applymarker(pytest.mark.xfail(reason=msg)) + + index = [1, 2, 3, 4] # test transform preserves non-standard index + df = pd.DataFrame({"A": [1, 1, np.nan, np.nan], "B": [1, 2, 2, 3]}, index=index) + gb = df.groupby("A", dropna=dropna) + + args = get_groupby_method_args(reduction_func, df) + + # Manually handle reducers that don't fit the generic pattern + # Set expected with dropna=False, then replace if necessary + if reduction_func == "first": + expected = pd.DataFrame({"B": [1, 1, 2, 2]}, index=index) + elif reduction_func == "last": + expected = pd.DataFrame({"B": [2, 2, 3, 3]}, index=index) + elif reduction_func == "nth": + expected = pd.DataFrame({"B": [1, 1, 2, 2]}, index=index) + elif reduction_func == "size": + expected = pd.Series([2, 2, 2, 2], index=index) + elif reduction_func == "corrwith": + expected = pd.DataFrame({"B": [1.0, 1.0, 1.0, 1.0]}, index=index) + else: + expected_gb = df.groupby("A", dropna=False) + buffer = [] + for idx, group in expected_gb: + res = getattr(group["B"], reduction_func)() + buffer.append(pd.Series(res, index=group.index)) + expected = pd.concat(buffer).to_frame("B") + if dropna: + dtype = object if reduction_func in ("any", "all") else float + expected = expected.astype(dtype) + if expected.ndim == 2: + expected.iloc[[2, 3], 0] = np.nan + else: + expected.iloc[[2, 3]] = np.nan + + result = gb.transform(reduction_func, *args) + tm.assert_equal(result, expected) + + +def test_null_group_str_transformer(dropna, transformation_func): + # GH 17093 + df = pd.DataFrame({"A": [1, 1, np.nan], "B": [1, 2, 2]}, index=[1, 2, 3]) + args = get_groupby_method_args(transformation_func, df) + gb = df.groupby("A", dropna=dropna) + + buffer = [] + for k, (idx, group) in enumerate(gb): + if transformation_func == "cumcount": + # DataFrame has no cumcount method + res = pd.DataFrame({"B": range(len(group))}, index=group.index) + elif transformation_func == "ngroup": + res = pd.DataFrame(len(group) * [k], index=group.index, columns=["B"]) + else: + res = getattr(group[["B"]], transformation_func)(*args) + buffer.append(res) + if dropna: + dtype = object if transformation_func in ("any", "all") else None + buffer.append(pd.DataFrame([[np.nan]], index=[3], dtype=dtype, columns=["B"])) + expected = pd.concat(buffer) + + if transformation_func in ("cumcount", "ngroup"): + # ngroup/cumcount always returns a Series as it counts the groups, not values + expected = expected["B"].rename(None) + + result = gb.transform(transformation_func, *args) + tm.assert_equal(result, expected) + + +def test_null_group_str_reducer_series(request, dropna, reduction_func): + # GH 17093 + index = [1, 2, 3, 4] # test transform preserves non-standard index + ser = pd.Series([1, 2, 2, 3], index=index) + gb = ser.groupby([1, 1, np.nan, np.nan], dropna=dropna) + + if reduction_func == "corrwith": + # corrwith not implemented for SeriesGroupBy + assert not hasattr(gb, reduction_func) + return + + args = get_groupby_method_args(reduction_func, ser) + + # Manually handle reducers that don't fit the generic pattern + # Set expected with dropna=False, then replace if necessary + if reduction_func == "first": + expected = pd.Series([1, 1, 2, 2], index=index) + elif reduction_func == "last": + expected = pd.Series([2, 2, 3, 3], index=index) + elif reduction_func == "nth": + expected = pd.Series([1, 1, 2, 2], index=index) + elif reduction_func == "size": + expected = pd.Series([2, 2, 2, 2], index=index) + elif reduction_func == "corrwith": + expected = pd.Series([1, 1, 2, 2], index=index) + else: + expected_gb = ser.groupby([1, 1, np.nan, np.nan], dropna=False) + buffer = [] + for idx, group in expected_gb: + res = getattr(group, reduction_func)() + buffer.append(pd.Series(res, index=group.index)) + expected = pd.concat(buffer) + if dropna: + dtype = object if reduction_func in ("any", "all") else float + expected = expected.astype(dtype) + expected.iloc[[2, 3]] = np.nan + + result = gb.transform(reduction_func, *args) + tm.assert_series_equal(result, expected) + + +def test_null_group_str_transformer_series(dropna, transformation_func): + # GH 17093 + ser = pd.Series([1, 2, 2], index=[1, 2, 3]) + args = get_groupby_method_args(transformation_func, ser) + gb = ser.groupby([1, 1, np.nan], dropna=dropna) + + buffer = [] + for k, (idx, group) in enumerate(gb): + if transformation_func == "cumcount": + # Series has no cumcount method + res = pd.Series(range(len(group)), index=group.index) + elif transformation_func == "ngroup": + res = pd.Series(k, index=group.index) + else: + res = getattr(group, transformation_func)(*args) + buffer.append(res) + if dropna: + dtype = object if transformation_func in ("any", "all") else None + buffer.append(pd.Series([np.nan], index=[3], dtype=dtype)) + expected = pd.concat(buffer) + result = gb.transform(transformation_func, *args) + + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "func, expected_values", + [ + (pd.Series.sort_values, [5, 4, 3, 2, 1]), + (lambda x: x.head(1), [5.0, np.nan, 3, 2, np.nan]), + ], +) +@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) +@pytest.mark.parametrize("keys_in_index", [True, False]) +def test_transform_aligns(func, frame_or_series, expected_values, keys, keys_in_index): + # GH#45648 - transform should align with the input's index + df = pd.DataFrame({"a1": [1, 1, 3, 2, 2], "b": [5, 4, 3, 2, 1]}) + if "a2" in keys: + df["a2"] = df["a1"] + if keys_in_index: + df = df.set_index(keys, append=True) + + gb = df.groupby(keys) + if frame_or_series is pd.Series: + gb = gb["b"] + + result = gb.transform(func) + expected = pd.DataFrame({"b": expected_values}, index=df.index) + if frame_or_series is pd.Series: + expected = expected["b"] + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("keys", ["A", ["A", "B"]]) +def test_as_index_no_change(keys, df, groupby_func): + # GH#49834 - as_index should have no impact on DataFrameGroupBy.transform + if keys == "A": + # Column B is string dtype; will fail on some ops + df = df.drop(columns="B") + args = get_groupby_method_args(groupby_func, df) + gb_as_index_true = df.groupby(keys, as_index=True) + gb_as_index_false = df.groupby(keys, as_index=False) + if groupby_func == "corrwith": + warn = Pandas4Warning + msg = "DataFrameGroupBy.corrwith is deprecated" + else: + warn = None + msg = "" + with tm.assert_produces_warning(warn, match=msg): + result = gb_as_index_true.transform(groupby_func, *args) + with tm.assert_produces_warning(warn, match=msg): + expected = gb_as_index_false.transform(groupby_func, *args) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmax", "idxmin"]) +@pytest.mark.parametrize("numeric_only", [True, False]) +def test_idxmin_idxmax_transform_args(how, skipna, numeric_only): + # GH#55268 - ensure *args are passed through when calling transform + df = pd.DataFrame( + {"a": [1, 1, 1, 2], "b": [3.0, 4.0, np.nan, 6.0], "c": list("abcd")} + ) + gb = df.groupby("a") + if skipna: + result = gb.transform(how, skipna, numeric_only) + expected = gb.transform(how, skipna=skipna, numeric_only=numeric_only) + tm.assert_frame_equal(result, expected) + else: + msg = f"{how} with skipna=False encountered an NA value" + with pytest.raises(ValueError, match=msg): + gb.transform(how, skipna, numeric_only) + + +def test_transform_sum_one_column_no_matching_labels(): + df = pd.DataFrame({"X": [1.0]}) + series = pd.Series(["Y"]) + result = df.groupby(series, as_index=False).transform("sum") + expected = pd.DataFrame({"X": [1.0]}) + tm.assert_frame_equal(result, expected) + + +def test_transform_sum_no_matching_labels(): + df = pd.DataFrame({"X": [1.0, -93204, 4935]}) + series = pd.Series(["A", "B", "C"]) + + result = df.groupby(series, as_index=False).transform("sum") + expected = pd.DataFrame({"X": [1.0, -93204, 4935]}) + tm.assert_frame_equal(result, expected) + + +def test_transform_sum_one_column_with_matching_labels(): + df = pd.DataFrame({"X": [1.0, -93204, 4935]}) + series = pd.Series(["A", "B", "A"]) + + result = df.groupby(series, as_index=False).transform("sum") + expected = pd.DataFrame({"X": [4936.0, -93204, 4936.0]}) + tm.assert_frame_equal(result, expected) + + +def test_transform_sum_one_column_with_missing_labels(): + df = pd.DataFrame({"X": [1.0, -93204, 4935]}) + series = pd.Series(["A", "C"]) + + result = df.groupby(series, as_index=False).transform("sum") + expected = pd.DataFrame({"X": [1.0, -93204, np.nan]}) + tm.assert_frame_equal(result, expected) + + +def test_transform_sum_one_column_with_matching_labels_and_missing_labels(): + df = pd.DataFrame({"X": [1.0, -93204, 4935]}) + series = pd.Series(["A", "A"]) + + result = df.groupby(series, as_index=False).transform("sum") + expected = pd.DataFrame({"X": [-93203.0, -93203.0, np.nan]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["int32", "float32"]) +def test_min_one_unobserved_category_no_type_coercion(dtype): + # GH#58084 + df = pd.DataFrame( + {"A": pd.Categorical([1, 1, 2], categories=[1, 2, 3]), "B": [3, 4, 5]} + ) + df["B"] = df["B"].astype(dtype) + gb = df.groupby("A", observed=False) + result = gb.transform("min") + + expected = pd.DataFrame({"B": [3, 3, 5]}, dtype=dtype) + tm.assert_frame_equal(expected, result) + + +def test_min_all_empty_data_no_type_coercion(): + # GH#58084 + df = pd.DataFrame( + { + "X": pd.Categorical( + [], + categories=[1, "randomcat", 100], + ), + "Y": [], + } + ) + df["Y"] = df["Y"].astype("int32") + + gb = df.groupby("X", observed=False) + result = gb.transform("min") + + expected = pd.DataFrame({"Y": []}, dtype="int32") + tm.assert_frame_equal(expected, result) + + +def test_min_one_dim_no_type_coercion(): + # GH#58084 + df = pd.DataFrame({"Y": [9435, -5465765, 5055, 0, 954960]}) + df["Y"] = df["Y"].astype("int32") + categories = pd.Categorical([1, 2, 2, 5, 1], categories=[1, 2, 3, 4, 5]) + + gb = df.groupby(categories, observed=False) + result = gb.transform("min") + + expected = pd.DataFrame({"Y": [9435, -5465765, -5465765, 0, 9435]}, dtype="int32") + tm.assert_frame_equal(expected, result) + + +def test_nan_in_cumsum_group_label(): + # GH#58811 + df = pd.DataFrame({"A": [1, None], "B": [2, 3]}, dtype="Int16") + gb = df.groupby("A")["B"] + result = gb.cumsum() + expected = pd.Series([2, None], dtype="Int16", name="B") + tm.assert_series_equal(expected, result) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_constructors.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..cb83816a027552414b8b56e1263fe5d3e15a02a5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_constructors.py @@ -0,0 +1,68 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestIndexConstructor: + # Tests for the Index constructor, specifically for cases that do + # not return a subclass + + @pytest.mark.parametrize("value", [1, np.int64(1)]) + def test_constructor_corner(self, value): + # corner case + msg = ( + r"Index\(\.\.\.\) must be called with a collection of some " + f"kind, {value} was passed" + ) + with pytest.raises(TypeError, match=msg): + pd.Index(value) + + @pytest.mark.parametrize("index_vals", [[("A", 1), "B"], ["B", ("A", 1)]]) + def test_construction_list_mixed_tuples(self, index_vals): + # see gh-10697: if we are constructing from a mixed list of tuples, + # make sure that we are independent of the sorting order. + index = pd.Index(index_vals) + assert isinstance(index, pd.Index) + assert not isinstance(index, pd.MultiIndex) + + def test_constructor_cast(self): + msg = "could not convert string to float" + with pytest.raises(ValueError, match=msg): + pd.Index(["a", "b", "c"], dtype=float) + + @pytest.mark.parametrize("tuple_list", [[()], [(), ()]]) + def test_construct_empty_tuples(self, tuple_list): + # GH #45608 + result = pd.Index(tuple_list) + expected = pd.MultiIndex.from_tuples(tuple_list) + + tm.assert_index_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning" + ) + def test_index_string_inference(self): + # GH#54430 + expected = pd.Index(["a", "b"], dtype=pd.StringDtype(na_value=np.nan)) + with pd.option_context("future.infer_string", True): + ser = pd.Index(["a", "b"]) + tm.assert_index_equal(ser, expected) + + expected = pd.Index(["a", 1], dtype="object") + ser = pd.Index(["a", 1]) + tm.assert_index_equal(ser, expected) + + @pytest.mark.parametrize("klass", [pd.Series, pd.Index]) + def test_inference_on_pandas_objects(self, klass): + # GH#56012 + obj = klass([pd.Timestamp("2019-12-31")], dtype=object) + result = pd.Index(obj) + assert result.dtype == np.object_ + + def test_constructor_not_read_only(self): + # GH#57130 + ser = pd.Series([1, 2], dtype=object) + idx = pd.Index(ser) + assert idx._values.flags.writeable diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_formats.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_formats.py new file mode 100644 index 0000000000000000000000000000000000000000..4320c22b7ae58dbcebe1464a0e85382f27302057 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_formats.py @@ -0,0 +1,154 @@ +import numpy as np +import pytest + +import pandas._config.config as cf + +import pandas as pd +import pandas._testing as tm + + +class TestIndexRendering: + def test_repr_is_valid_construction_code(self): + # for the case of Index, where the repr is traditional rather than + # stylized + idx = pd.Index(["a", "b"]) + res = eval(repr(idx), dict(vars(pd))) + tm.assert_index_equal(res, idx) + + @pytest.mark.parametrize( + "index,expected", + [ + # ASCII + # short + ( + pd.Index(["a", "bb", "ccc"]), + """Index(['a', 'bb', 'ccc'], dtype='object')""", + ), + # multiple lines + ( + pd.Index(["a", "bb", "ccc"] * 10), + "Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', " + "'bb', 'ccc', 'a', 'bb', 'ccc',\n" + " 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', " + "'bb', 'ccc', 'a', 'bb', 'ccc',\n" + " 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],\n" + " dtype='object')", + ), + # truncated + ( + pd.Index(["a", "bb", "ccc"] * 100), + "Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',\n" + " ...\n" + " 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],\n" + " dtype='object', length=300)", + ), + # Non-ASCII + # short + ( + pd.Index(["あ", "いい", "ううう"]), + """Index(['あ', 'いい', 'ううう'], dtype='object')""", + ), + # multiple lines + ( + pd.Index(["あ", "いい", "ううう"] * 10), + ( + "Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " + "'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n" + " 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " + "'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n" + " 'あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう'],\n" + " dtype='object')" + ), + ), + # truncated + ( + pd.Index(["あ", "いい", "ううう"] * 100), + ( + "Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " + "'あ', 'いい', 'ううう', 'あ',\n" + " ...\n" + " 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい', 'ううう'],\n" + " dtype='object', length=300)" + ), + ), + ], + ) + def test_string_index_repr(self, index, expected, using_infer_string): + result = repr(index) + if using_infer_string: + expected = expected.replace("dtype='object'", "dtype='str'") + + assert result == expected + + @pytest.mark.parametrize( + "index,expected", + [ + # short + ( + pd.Index(["あ", "いい", "ううう"]), + ("Index(['あ', 'いい', 'ううう'], dtype='object')"), + ), + # multiple lines + ( + pd.Index(["あ", "いい", "ううう"] * 10), + ( + "Index(['あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい', 'ううう',\n" + " 'あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい', 'ううう',\n" + " 'あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい', 'ううう',\n" + " 'あ', 'いい', 'ううう'],\n" + " dtype='object')" + "" + ), + ), + # truncated + ( + pd.Index(["あ", "いい", "ううう"] * 100), + ( + "Index(['あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい', 'ううう',\n" + " 'あ',\n" + " ...\n" + " 'ううう', 'あ', 'いい', 'ううう', 'あ', " + "'いい', 'ううう', 'あ', 'いい',\n" + " 'ううう'],\n" + " dtype='object', length=300)" + ), + ), + ], + ) + def test_string_index_repr_with_unicode_option( + self, index, expected, using_infer_string + ): + # Enable Unicode option ----------------------------------------- + with cf.option_context("display.unicode.east_asian_width", True): + result = repr(index) + + if using_infer_string: + expected = expected.replace("dtype='object'", "dtype='str'") + assert result == expected + + def test_repr_summary(self): + with cf.option_context("display.max_seq_items", 10): + result = repr(pd.Index(np.arange(1000))) + assert len(result) < 200 + assert "..." in result + + def test_summary_bug(self): + # GH#3869 + ind = pd.Index(["{other}%s", "~:{range}:0"], name="A") + result = ind._summary() + # shouldn't be formatted accidentally. + assert "~:{range}:0" in result + assert "{other}%s" in result + + def test_index_repr_bool_nan(self): + # GH32146 + arr = pd.Index([True, False, np.nan], dtype=object) + exp2 = repr(arr) + out2 = "Index([True, False, nan], dtype='object')" + assert out2 == exp2 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..0b76019220837ff0d387a29e807b7f9fb2450a45 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_indexing.py @@ -0,0 +1,174 @@ +import numpy as np +import pytest + +from pandas._libs import index as libindex + +import pandas as pd +import pandas._testing as tm + + +class TestGetSliceBounds: + @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)]) + def test_get_slice_bounds_within(self, side, expected): + index = pd.Index(list("abcdef")) + result = index.get_slice_bound("e", side=side) + assert result == expected + + @pytest.mark.parametrize("side", ["left", "right"]) + @pytest.mark.parametrize( + "data, bound, expected", [(list("abcdef"), "x", 6), (list("bcdefg"), "a", 0)] + ) + def test_get_slice_bounds_outside(self, side, expected, data, bound): + index = pd.Index(data) + result = index.get_slice_bound(bound, side=side) + assert result == expected + + def test_get_slice_bounds_invalid_side(self): + with pytest.raises(ValueError, match="Invalid value for side kwarg"): + pd.Index([]).get_slice_bound("a", side="middle") + + +class TestGetIndexerNonUnique: + def test_get_indexer_non_unique_dtype_mismatch(self): + # GH#25459 + indexes, missing = pd.Index(["A", "B"]).get_indexer_non_unique(pd.Index([0])) + tm.assert_numpy_array_equal(np.array([-1], dtype=np.intp), indexes) + tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), missing) + + @pytest.mark.parametrize( + "idx_values,idx_non_unique", + [ + ([np.nan, 100, 200, 100], [np.nan, 100]), + ([np.nan, 100.0, 200.0, 100.0], [np.nan, 100.0]), + ], + ) + def test_get_indexer_non_unique_int_index(self, idx_values, idx_non_unique): + indexes, missing = pd.Index(idx_values).get_indexer_non_unique( + pd.Index([np.nan]) + ) + tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), indexes) + tm.assert_numpy_array_equal(np.array([], dtype=np.intp), missing) + + indexes, missing = pd.Index(idx_values).get_indexer_non_unique( + pd.Index(idx_non_unique) + ) + tm.assert_numpy_array_equal(np.array([0, 1, 3], dtype=np.intp), indexes) + tm.assert_numpy_array_equal(np.array([], dtype=np.intp), missing) + + +class TestGetLoc: + @pytest.mark.slow # to_flat_index takes a while + def test_get_loc_tuple_monotonic_above_size_cutoff(self, monkeypatch): + # Go through the libindex path for which using + # _bin_search vs ndarray.searchsorted makes a difference + + with monkeypatch.context(): + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 100) + lev = list("ABCD") + dti = pd.date_range("2016-01-01", periods=10) + + mi = pd.MultiIndex.from_product([lev, range(5), dti]) + oidx = mi.to_flat_index() + + loc = len(oidx) // 2 + tup = oidx[loc] + + res = oidx.get_loc(tup) + assert res == loc + + def test_get_loc_tuple_monotonic_with_duplicates(self): + # GH#37800 _get_loc_duplicates should not use ndarray.searchsorted + # with tuple keys, as searchsorted interprets tuples as array-like + values = np.empty(3, dtype=object) + values[0] = (1, 1) + values[1] = (1, 1) + values[2] = (2, 2) + idx = pd.Index(values) + result = idx.get_loc((1, 1)) + assert result == slice(0, 2) + + result = idx.get_loc((2, 2)) + assert result == 2 + + with pytest.raises(KeyError, match=r"\(3, 3\)"): + idx.get_loc((3, 3)) + + def test_get_loc_nan_object_dtype_nonmonotonic_nonunique(self): + # case that goes through _maybe_get_bool_indexer + idx = pd.Index(["foo", np.nan, None, "foo", 1.0, None], dtype=object) + + # we dont raise KeyError on nan + res = idx.get_loc(np.nan) + assert res == 1 + + # we only match on None, not on np.nan + res = idx.get_loc(None) + expected = np.array([False, False, True, False, False, True]) + tm.assert_numpy_array_equal(res, expected) + + # we don't match at all on mismatched NA + with pytest.raises(KeyError, match="NaT"): + idx.get_loc(pd.NaT) + + +def test_get_indexer_monotonic_above_size_cutoff(monkeypatch): + # GH#14273 get_indexer should avoid building a hash table for large + # monotonic indices. + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 100) + idx = pd.Index(np.arange(200, dtype=np.int64)) + + target = pd.Index([10, 50, 150, 999]) + result = idx.get_indexer(target) + expected = np.array([10, 50, 150, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + # Verify hash table was NOT built + assert not idx._engine.is_mapping_populated + + +def test_get_indexer_monotonic_above_size_cutoff_datetime(monkeypatch): + # GH#14273 + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 100) + dti = pd.date_range("2000-01-01", periods=200) + + target = dti[[5, 100, 199]] + result = dti.get_indexer(target) + expected = np.array([5, 100, 199], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + assert not dti._engine.is_mapping_populated + + +def test_get_indexer_monotonic_above_size_cutoff_not_found(monkeypatch): + # GH#14273 + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 100) + idx = pd.Index(np.arange(0, 400, 2, dtype=np.int64)) # even numbers only + + target = pd.Index([1, 3, 5]) # odd numbers, not in index + result = idx.get_indexer(target) + expected = np.array([-1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + assert not idx._engine.is_mapping_populated + + +def test_get_indexer_monotonic_above_size_cutoff_mixed(monkeypatch): + # GH#14273 + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 100) + idx = pd.Index(np.arange(0, 400, 2, dtype=np.int64)) + + # Mix of found and not found, including values beyond the range + target = pd.Index([0, 1, 398, 399, -1, 500]) + result = idx.get_indexer(target) + expected = np.array([0, -1, 199, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + assert not idx._engine.is_mapping_populated + + +def test_getitem_boolean_ea_indexer(): + # GH#45806 + ser = pd.Series([True, False, pd.NA], dtype="boolean") + result = ser.index[ser] + expected = pd.RangeIndex(start=0, stop=1, step=1) + tm.assert_index_equal(result, expected, exact=True) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_pickle.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..723b3625fe1067c19e4437e5652bd47f7d37847a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_pickle.py @@ -0,0 +1,11 @@ +import pandas as pd +import pandas._testing as tm + + +def test_pickle_preserves_object_dtype(temp_file): + # GH#43188, GH#43155 don't infer numeric dtype + index = pd.Index([1, 2, 3], dtype=object) + + result = tm.round_trip_pickle(index, temp_file) + assert result.dtype == object + tm.assert_index_equal(index, result) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_reshape.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_reshape.py new file mode 100644 index 0000000000000000000000000000000000000000..a8856edf952c26cfe6a08e26a96e447097edab6b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_reshape.py @@ -0,0 +1,148 @@ +""" +Tests for ndarray-like method on the base Index class +""" + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.arrays import SparseArray + + +class TestReshape: + def test_repeat(self): + repeats = 2 + index = pd.Index([1, 2, 3]) + expected = pd.Index([1, 1, 2, 2, 3, 3]) + + result = index.repeat(repeats) + tm.assert_index_equal(result, expected) + + def test_insert(self): + # GH 7256 + # validate neg/pos inserts + result = pd.Index(["b", "c", "d"]) + + # test 0th element + tm.assert_index_equal(pd.Index(["a", "b", "c", "d"]), result.insert(0, "a")) + + # test Nth element that follows Python list behavior + tm.assert_index_equal(pd.Index(["b", "c", "e", "d"]), result.insert(-1, "e")) + + # test loc +/- neq (0, -1) + tm.assert_index_equal(result.insert(1, "z"), result.insert(-2, "z")) + + # test empty + null_index = pd.Index([]) + tm.assert_index_equal(pd.Index(["a"]), null_index.insert(0, "a")) + + @pytest.mark.parametrize("val", [True, False]) + def test_insert_bool_into_numeric_ea(self, val): + # GH#61709 - bool should not be silently cast to numeric + float_idx = pd.Index([1.0, 2.0, 3.0], dtype="Float64") + result = float_idx.insert(1, val) + expected = pd.Index([1.0, val, 2.0, 3.0], dtype=object) + tm.assert_index_equal(result, expected) + + int_idx = pd.Index([1, 2, 3], dtype="Int64") + result = int_idx.insert(1, val) + expected = pd.Index([1, val, 2, 3], dtype=object) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "item, expected", + [ + (1.5, SparseArray([1.5, 1.0, 2.0, 3.0], fill_value=0)), + (True, SparseArray([True, 1, 2, 3], dtype=pd.SparseDtype(object, 0))), + ( + pd.Timestamp("2016-01-01"), + SparseArray( + [pd.Timestamp("2016-01-01"), 1, 2, 3], + dtype=pd.SparseDtype(object, 0), + ), + ), + ], + ) + def test_insert_into_sparse_int_widens(self, item, expected): + # GH#69028 - a value the subtype cannot hold widens, it is not cast + idx = pd.Index(SparseArray([1, 2, 3])) + tm.assert_index_equal(idx.insert(0, item), pd.Index(expected)) + + def test_insert_into_all_fill_value_sparse(self): + # GH#69028 - with no stored values the widened result is all-datetimelike, + # which the concat behind insert used to re-infer back to M8 + idx = pd.Index(SparseArray([0, 0, 0])) + result = idx.insert(0, pd.Timestamp("2016-01-01")) + expected = pd.Index( + SparseArray( + [pd.Timestamp("2016-01-01"), 0, 0, 0], dtype=pd.SparseDtype(object, 0) + ) + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("val", [0, 1]) + def test_insert_int_into_boolean_ea(self, val): + # GH#61709 - int should not be silently cast to bool + bool_idx = pd.Index([True, False, True], dtype="boolean") + result = bool_idx.insert(1, val) + expected = pd.Index([True, val, False, True], dtype=object) + tm.assert_index_equal(result, expected) + + def test_insert_missing(self, nulls_fixture, using_infer_string): + # GH#22295 + # test there is no mangling of NA values + expected = pd.Index(["a", nulls_fixture, "b", "c"], dtype=object) + result = pd.Index(list("abc"), dtype=object).insert( + 1, pd.Index([nulls_fixture], dtype=object) + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "val", [(1, 2), np.datetime64("2019-12-31"), np.timedelta64(1, "D")] + ) + @pytest.mark.parametrize("loc", [-1, 2]) + def test_insert_datetime_into_object(self, loc, val): + # GH#44509 + idx = pd.Index(["1", "2", "3"]) + result = idx.insert(loc, val) + expected = pd.Index(["1", "2", val, "3"]) + tm.assert_index_equal(result, expected) + assert type(expected[2]) is type(val) + + def test_insert_none_into_string_numpy(self, string_dtype_no_object): + # GH#55365 + index = pd.Index(["a", "b", "c"], dtype=string_dtype_no_object) + result = index.insert(-1, None) + expected = pd.Index(["a", "b", None, "c"], dtype=string_dtype_no_object) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "pos,expected", + [ + (0, pd.Index(["b", "c", "d"], name="index")), + (-1, pd.Index(["a", "b", "c"], name="index")), + ], + ) + def test_delete(self, pos, expected): + index = pd.Index(["a", "b", "c", "d"], name="index") + result = index.delete(pos) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + + def test_delete_raises(self): + index = pd.Index(["a", "b", "c", "d"], name="index") + msg = "index 5 is out of bounds for axis 0 with size 4" + with pytest.raises(IndexError, match=msg): + index.delete(5) + + def test_append_multiple(self): + index = pd.Index(["a", "b", "c", "d", "e", "f"]) + + foos = [index[:2], index[2:4], index[4:]] + result = foos[0].append(foos[1:]) + tm.assert_index_equal(result, index) + + # empty + result = index.append([]) + tm.assert_index_equal(result, index) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_setops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..da7af98be0a423a3ec0bfe6ccd4263bab84929ac --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_setops.py @@ -0,0 +1,290 @@ +from datetime import datetime + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.core.algorithms import safe_sort + + +def equal_contents(arr1, arr2) -> bool: + """ + Checks if the set of unique elements of arr1 and arr2 are equivalent. + """ + return frozenset(arr1) == frozenset(arr2) + + +class TestIndexSetOps: + @pytest.mark.parametrize( + "method", ["union", "intersection", "difference", "symmetric_difference"] + ) + def test_setops_sort_validation(self, method): + idx1 = pd.Index(["a", "b"]) + idx2 = pd.Index(["b", "c"]) + + with pytest.raises(ValueError, match="The 'sort' keyword only takes"): + getattr(idx1, method)(idx2, sort=2) + + # sort=True is supported as of GH#25151 + getattr(idx1, method)(idx2, sort=True) + + def test_setops_preserve_object_dtype(self): + idx = pd.Index([1, 2, 3], dtype=object) + result = idx.intersection(idx[1:]) + expected = idx[1:] + tm.assert_index_equal(result, expected) + + # if other is not monotonic increasing, intersection goes through + # a different route + result = idx.intersection(idx[1:][::-1]) + tm.assert_index_equal(result, expected) + + result = idx._union(idx[1:], sort=None) + expected = idx + tm.assert_numpy_array_equal(result, expected.values) + + result = idx.union(idx[1:], sort=None) + tm.assert_index_equal(result, expected) + + # if other is not monotonic increasing, _union goes through + # a different route + result = idx._union(idx[1:][::-1], sort=None) + tm.assert_numpy_array_equal(result, expected.values) + + result = idx.union(idx[1:][::-1], sort=None) + tm.assert_index_equal(result, expected) + + def test_union_base(self): + index = pd.Index([0, "a", 1, "b", 2, "c"]) + first = index[3:] + second = index[:5] + + result = first.union(second) + + expected = pd.Index([0, 1, 2, "a", "b", "c"]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("klass", [np.array, pd.Series, list]) + def test_union_different_type_base(self, klass): + # GH 10149 + index = pd.Index([0, "a", 1, "b", 2, "c"]) + first = index[3:] + second = index[:5] + + result = first.union(klass(second.values)) + + assert equal_contents(result, index) + + def test_union_sort_other_incomparable(self): + # https://github.com/pandas-dev/pandas/issues/24959 + idx = pd.Index([1, pd.Timestamp("2000")]) + # default (sort=None) + with tm.assert_produces_warning(RuntimeWarning, match="not supported between"): + result = idx.union(idx[:1]) + + tm.assert_index_equal(result, idx) + + # sort=None + with tm.assert_produces_warning(RuntimeWarning, match="not supported between"): + result = idx.union(idx[:1], sort=None) + tm.assert_index_equal(result, idx) + + # sort=False + result = idx.union(idx[:1], sort=False) + tm.assert_index_equal(result, idx) + + def test_union_sort_other_incomparable_true(self): + idx = pd.Index([1, pd.Timestamp("2000")]) + with pytest.raises(TypeError, match=".*"): + idx.union(idx[:1], sort=True) + + def test_intersection_equal_sort_true(self): + idx = pd.Index(["c", "a", "b"]) + sorted_ = pd.Index(["a", "b", "c"]) + tm.assert_index_equal(idx.intersection(idx, sort=True), sorted_) + + def test_intersection_base(self, sort): + # (same results for py2 and py3 but sortedness not tested elsewhere) + index = pd.Index([0, "a", 1, "b", 2, "c"]) + first = index[:5] + second = index[:3] + + expected = pd.Index([0, 1, "a"]) if sort is None else pd.Index([0, "a", 1]) + result = first.intersection(second, sort=sort) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("klass", [np.array, pd.Series, list]) + def test_intersection_different_type_base(self, klass, sort): + # GH 10149 + index = pd.Index([0, "a", 1, "b", 2, "c"]) + first = index[:5] + second = index[:3] + + result = first.intersection(klass(second.values), sort=sort) + assert equal_contents(result, second) + + def test_intersection_nosort(self): + result = pd.Index(["c", "b", "a"]).intersection(["b", "a"]) + expected = pd.Index(["b", "a"]) + tm.assert_index_equal(result, expected) + + def test_intersection_equal_sort(self): + idx = pd.Index(["c", "a", "b"]) + tm.assert_index_equal(idx.intersection(idx, sort=False), idx) + tm.assert_index_equal(idx.intersection(idx, sort=None), idx) + + def test_intersection_str_dates(self, sort): + dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)] + + i1 = pd.Index(dt_dates, dtype=object) + i2 = pd.Index(["aa"], dtype=object) + result = i2.intersection(i1, sort=sort) + + assert len(result) == 0 + + @pytest.mark.parametrize( + "index2,expected_arr", + [(["B", "D"], ["B"]), (["B", "D", "A"], ["A", "B"])], + ) + def test_intersection_non_monotonic_non_unique(self, index2, expected_arr, sort): + # non-monotonic non-unique + index1 = pd.Index(["A", "B", "A", "C"]) + expected = pd.Index(expected_arr) + result = index1.intersection(pd.Index(index2), sort=sort) + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + def test_difference_base(self, sort): + # (same results for py2 and py3 but sortedness not tested elsewhere) + index = pd.Index([0, "a", 1, "b", 2, "c"]) + first = index[:4] + second = index[3:] + + result = first.difference(second, sort) + expected = pd.Index([0, "a", 1]) + if sort is None: + expected = pd.Index(safe_sort(expected)) + tm.assert_index_equal(result, expected) + + def test_symmetric_difference(self): + # (same results for py2 and py3 but sortedness not tested elsewhere) + index = pd.Index([0, "a", 1, "b", 2, "c"]) + first = index[:4] + second = index[3:] + + result = first.symmetric_difference(second) + expected = pd.Index([0, 1, 2, "a", "c"]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "method,expected,sort", + [ + ( + "intersection", + np.array( + [(1, "A"), (2, "A"), (1, "B"), (2, "B")], + dtype=[("num", int), ("let", "S1")], + ), + False, + ), + ( + "intersection", + np.array( + [(1, "A"), (1, "B"), (2, "A"), (2, "B")], + dtype=[("num", int), ("let", "S1")], + ), + None, + ), + ( + "union", + np.array( + [(1, "A"), (1, "B"), (1, "C"), (2, "A"), (2, "B"), (2, "C")], + dtype=[("num", int), ("let", "S1")], + ), + None, + ), + ], + ) + def test_tuple_union_bug(self, method, expected, sort): + index1 = pd.Index( + np.array( + [(1, "A"), (2, "A"), (1, "B"), (2, "B")], + dtype=[("num", int), ("let", "S1")], + ) + ) + index2 = pd.Index( + np.array( + [(1, "A"), (2, "A"), (1, "B"), (2, "B"), (1, "C"), (2, "C")], + dtype=[("num", int), ("let", "S1")], + ) + ) + + result = getattr(index1, method)(index2, sort=sort) + assert result.ndim == 1 + + expected = pd.Index(expected) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("first_list", [["b", "a"], []]) + @pytest.mark.parametrize("second_list", [["a", "b"], []]) + @pytest.mark.parametrize( + "first_name, second_name, expected_name", + [("A", "B", None), (None, "B", None), ("A", None, None)], + ) + def test_union_name_preservation( + self, first_list, second_list, first_name, second_name, expected_name, sort + ): + first = pd.Index(first_list, name=first_name) + second = pd.Index(second_list, name=second_name) + union = first.union(second, sort=sort) + + vals = set(first_list).union(second_list) + + if sort is None and len(first_list) > 0 and len(second_list) > 0: + expected = pd.Index(sorted(vals), name=expected_name) + tm.assert_index_equal(union, expected) + else: + expected = pd.Index(vals, name=expected_name) + tm.assert_index_equal(union.sort_values(), expected.sort_values()) + + def test_setops_mixed_freq_periods(self, sort): + # GH#55333 - object-dtype Index with mixed-freq Period objects + # should not raise IncompatibleFrequency + ts = pd.Timestamp("2024-01-01") + pers = [ts.to_period(freq) for freq in ["D", "s", "h", "M"]] + + left = pd.Index(pers[:2]) + right = pd.Index(pers[2:]) + assert left.dtype == object + assert right.dtype == object + + warn = RuntimeWarning if sort is not False else None + with tm.assert_produces_warning(warn, match="sort order is undefined"): + result = left.union(right, sort=sort) + assert result.dtype == object + assert len(result) == 4 + + result = left.intersection(right, sort=sort) + expected = pd.Index([], dtype=object) + tm.assert_index_equal(result, expected) + + with tm.assert_produces_warning( + RuntimeWarning, match="sort order is undefined" + ): + result = left.join(right, how="outer") + assert result.dtype == object + assert len(result) == 4 + + @pytest.mark.parametrize( + "diff_type, expected", + [["difference", [1, "B"]], ["symmetric_difference", [1, 2, "B", "C"]]], + ) + def test_difference_object_type(self, diff_type, expected): + # GH 13432 + idx1 = pd.Index([0, 1, "A", "B"]) + idx2 = pd.Index([0, 2, "A", "C"]) + result = getattr(idx1, diff_type)(idx2) + expected = pd.Index(expected) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_where.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_where.py new file mode 100644 index 0000000000000000000000000000000000000000..669be4d57f24ad46cf19f3aafc855558560bad10 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/base_class/test_where.py @@ -0,0 +1,44 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestWhere: + def test_where_intlike_str_doesnt_cast_ints(self): + idx = pd.Index(range(3)) + mask = np.array([True, False, True]) + res = idx.where(mask, "2") + expected = pd.Index([0, "2", 2]) + tm.assert_index_equal(res, expected) + + def test_where_preserves_object_dtype(self): + # https://github.com/pandas-dev/pandas/pull/65653 + idx = pd.Index(list("abc"), dtype="object") + result = idx.where(np.array([True, False, True]), other="x") + expected = pd.Index(["a", "x", "c"], dtype="object") + tm.assert_index_equal(result, expected) + + def test_where_index_with_index(self): + # GH 65685 + idx = pd.Index(range(48)) + mask = np.ones(48, dtype=bool) + + result = idx.where(mask, idx) + expected = idx.copy() + + tm.assert_index_equal(result, expected, exact=False) + + def test_where_index_with_ea_index(self): + # GH 65685 + # Make BOTH indexes an Extension Array (Int64) + idx = pd.Index([1, 2, 3], dtype="Int64") + mask = np.array([False, False, False]) + + other = pd.Index([4, 5, 6], dtype="Int64") + + # If mask is all False, result should be exactly 'other' + result = idx.where(mask, other) + expected = pd.Index([4, 5, 6], dtype="Int64") + + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_append.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_append.py new file mode 100644 index 0000000000000000000000000000000000000000..0afc98d7f430155cb7538d1f80460de4867b58e4 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_append.py @@ -0,0 +1,61 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestAppend: + @pytest.fixture + def ci(self): + categories = list("cab") + return pd.CategoricalIndex(list("aabbca"), categories=categories, ordered=False) + + def test_append(self, ci): + # append cats with the same categories + result = ci[:3].append(ci[3:]) + tm.assert_index_equal(result, ci, exact=True) + + foos = [ci[:1], ci[1:3], ci[3:]] + result = foos[0].append(foos[1:]) + tm.assert_index_equal(result, ci, exact=True) + + def test_append_empty(self, ci): + # empty + result = ci.append([]) + tm.assert_index_equal(result, ci, exact=True) + + def test_append_mismatched_categories(self, ci): + # appending with different categories or reordered is not ok + msg = "all inputs must be Index" + with pytest.raises(TypeError, match=msg): + ci.append(ci.values.set_categories(list("abcd"))) + with pytest.raises(TypeError, match=msg): + ci.append(ci.values.reorder_categories(list("abc"))) + + def test_append_category_objects(self, ci): + # GH#41626 pre-3.0 this used to cast the object-dtype index to + # ci.dtype + # with objects + result = ci.append(pd.Index(["c", "a"])) + expected = pd.Index(list("aabbcaca")) + tm.assert_index_equal(result, expected, exact=True) + + def test_append_non_categories(self, ci): + # invalid objects -> cast to object via concat_compat + result = ci.append(pd.Index(["a", "d"])) + expected = pd.Index(["a", "a", "b", "b", "c", "a", "a", "d"]) + tm.assert_index_equal(result, expected, exact=True) + + def test_append_object(self, ci): + # GH#14298 - if base object is not categorical -> coerce to object + result = pd.Index(["c", "a"]).append(ci) + expected = pd.Index(list("caaabbca")) + tm.assert_index_equal(result, expected, exact=True) + + def test_append_to_another(self): + # hits Index._concat + fst = pd.Index(["a", "b"]) + snd = pd.CategoricalIndex(["d", "e"]) + result = fst.append(snd) + expected = pd.Index(["a", "b", "d", "e"]) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_astype.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..3765b845b5d1433b4749d54dac0d64db54f68ea8 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_astype.py @@ -0,0 +1,91 @@ +from datetime import date + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestAstype: + def test_astype(self): + ci = pd.CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) + + result = ci.astype(object) + tm.assert_index_equal(result, pd.Index(np.array(ci), dtype=object)) + + # this IS equal, but not the same class + assert result.equals(ci) + assert isinstance(result, pd.Index) + assert not isinstance(result, pd.CategoricalIndex) + + # interval + ii = pd.IntervalIndex.from_arrays( + left=[-0.001, 2.0], right=[2, 4], closed="right" + ) + + ci = pd.CategoricalIndex( + pd.Categorical.from_codes([0, 1, -1], categories=ii, ordered=True) + ) + + result = ci.astype("interval") + expected = ii.take([0, 1, -1], allow_fill=True, fill_value=np.nan) + tm.assert_index_equal(result, expected) + + result = pd.IntervalIndex(result.values) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("name", [None, "foo"]) + @pytest.mark.parametrize("dtype_ordered", [True, False]) + @pytest.mark.parametrize("index_ordered", [True, False]) + def test_astype_category(self, name, dtype_ordered, index_ordered): + # GH#18630 + index = pd.CategoricalIndex( + list("aabbca"), categories=list("cab"), ordered=index_ordered + ) + if name: + index = index.rename(name) + + # standard categories + dtype = pd.CategoricalDtype(ordered=dtype_ordered) + result = index.astype(dtype) + expected = pd.CategoricalIndex( + index.tolist(), + name=name, + categories=index.categories, + ordered=dtype_ordered, + ) + tm.assert_index_equal(result, expected) + + # non-standard categories + dtype = pd.CategoricalDtype(index.unique().tolist()[:-1], dtype_ordered) + msg = "Constructing a Categorical with a dtype and values containing" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = index.astype(dtype) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = pd.CategoricalIndex(index.tolist(), name=name, dtype=dtype) + tm.assert_index_equal(result, expected) + + if dtype_ordered is False: + # dtype='category' can't specify ordered, so only test once + result = index.astype("category") + expected = index + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("box", [True, False]) + def test_categorical_date_roundtrip(self, box): + # astype to categorical and back should preserve date objects + v = date(2011, 1, 1) + + obj = pd.Index([v, v]) + assert obj.dtype == object + if box: + obj = obj.array + + cat = obj.astype("category") + + rtrip = cat.astype(object) + assert rtrip.dtype == object + assert type(rtrip[0]) is date diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_category.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_category.py new file mode 100644 index 0000000000000000000000000000000000000000..b46edb11ef722c6aa2935d9bed7d7c477fe73933 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_category.py @@ -0,0 +1,402 @@ +import numpy as np +import pytest + +from pandas._libs import index as libindex +from pandas._libs.arrays import NDArrayBacked +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.core.indexes.api import ( + CategoricalIndex, + Index, +) + + +class TestCategoricalIndex: + @pytest.fixture + def simple_index(self) -> CategoricalIndex: + """ + Fixture that provides a CategoricalIndex. + """ + return CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) + + def test_can_hold_identifiers(self): + idx = CategoricalIndex(list("aabbca"), categories=None, ordered=False) + key = idx[0] + assert idx._can_hold_identifiers_and_holds_name(key) is True + + def test_insert(self, simple_index): + ci = simple_index + categories = ci.categories + + # test 0th element + result = ci.insert(0, "a") + expected = CategoricalIndex(list("aaabbca"), categories=categories) + tm.assert_index_equal(result, expected, exact=True) + + # test Nth element that follows Python list behavior + result = ci.insert(-1, "a") + expected = CategoricalIndex(list("aabbcaa"), categories=categories) + tm.assert_index_equal(result, expected, exact=True) + + # test empty + result = CategoricalIndex([], categories=categories).insert(0, "a") + expected = CategoricalIndex(["a"], categories=categories) + tm.assert_index_equal(result, expected, exact=True) + + # invalid -> cast to object + expected = ci.astype(object).insert(0, "d") + result = ci.insert(0, "d").astype(object) + tm.assert_index_equal(result, expected, exact=True) + + # GH 18295 (test missing) + expected = CategoricalIndex(["a", np.nan, "a", "b", "c", "b"]) + for na in (np.nan, pd.NaT, None): + result = CategoricalIndex(list("aabcb")).insert(1, na) + tm.assert_index_equal(result, expected) + + def test_insert_na_mismatched_dtype(self): + ci = CategoricalIndex([0, 1, 1]) + result = ci.insert(0, pd.NaT) + expected = Index([pd.NaT, 0, 1, 1], dtype=object) + tm.assert_index_equal(result, expected) + + def test_delete(self, simple_index): + ci = simple_index + categories = ci.categories + + result = ci.delete(0) + expected = CategoricalIndex(list("abbca"), categories=categories) + tm.assert_index_equal(result, expected, exact=True) + + result = ci.delete(-1) + expected = CategoricalIndex(list("aabbc"), categories=categories) + tm.assert_index_equal(result, expected, exact=True) + + with tm.external_error_raised((IndexError, ValueError)): + # Either depending on NumPy version + ci.delete(10) + + @pytest.mark.parametrize( + "data, non_lexsorted_data", + [[[1, 2, 3], [9, 0, 1, 2, 3]], [list("abc"), list("fabcd")]], + ) + def test_is_monotonic(self, data, non_lexsorted_data): + c = CategoricalIndex(data) + assert c.is_monotonic_increasing is True + assert c.is_monotonic_decreasing is False + + c = CategoricalIndex(data, ordered=True) + assert c.is_monotonic_increasing is True + assert c.is_monotonic_decreasing is False + + c = CategoricalIndex(data, categories=reversed(data)) + assert c.is_monotonic_increasing is False + assert c.is_monotonic_decreasing is True + + c = CategoricalIndex(data, categories=reversed(data), ordered=True) + assert c.is_monotonic_increasing is False + assert c.is_monotonic_decreasing is True + + # test when data is neither monotonic increasing nor decreasing + reordered_data = [data[0], data[2], data[1]] + c = CategoricalIndex(reordered_data, categories=reversed(data)) + assert c.is_monotonic_increasing is False + assert c.is_monotonic_decreasing is False + + # non lexsorted categories + categories = non_lexsorted_data + + c = CategoricalIndex(categories[:2], categories=categories) + assert c.is_monotonic_increasing is True + assert c.is_monotonic_decreasing is False + + c = CategoricalIndex(categories[1:3], categories=categories) + assert c.is_monotonic_increasing is True + assert c.is_monotonic_decreasing is False + + def test_has_duplicates(self): + idx = CategoricalIndex([0, 0, 0], name="foo") + assert idx.is_unique is False + assert idx.has_duplicates is True + + idx = CategoricalIndex([None, None], categories=[2, 3], name="foo") + assert idx.is_unique is False + assert idx.has_duplicates is True + + idx = CategoricalIndex([None, 1, 2, 3], categories=[1, 2, 3], name="foo") + assert idx.is_unique is True + assert idx.has_duplicates is False + + @pytest.mark.parametrize( + "data, categories, expected", + [ + ( + [1, 1, 1], + [1, 2, 3], + { + "first": np.array([False, True, True]), + "last": np.array([True, True, False]), + False: np.array([True, True, True]), + }, + ), + ( + [None, None, None], + list("abc"), + { + "first": np.array([False, True, True]), + "last": np.array([True, True, False]), + False: np.array([True, True, True]), + }, + ), + ( + [None, "a", "b"], + list("abc"), + { + "first": np.zeros(shape=(3), dtype=np.bool_), + "last": np.zeros(shape=(3), dtype=np.bool_), + False: np.zeros(shape=(3), dtype=np.bool_), + }, + ), + ( + list("abb"), + list("abc"), + { + "first": np.array([False, False, True]), + "last": np.array([False, True, False]), + False: np.array([False, True, True]), + }, + ), + ], + ) + def test_drop_duplicates(self, data, categories, expected): + idx = CategoricalIndex(data, categories=categories, name="foo") + for keep, e in expected.items(): + tm.assert_numpy_array_equal(idx.duplicated(keep=keep), e) + e = idx[~e] + result = idx.drop_duplicates(keep=keep) + tm.assert_index_equal(result, e) + + @pytest.mark.parametrize( + "data, categories, expected_data", + [ + ([1, 1, 1], [1, 2, 3], [1]), + ([1, 1, 1], list("abc"), [np.nan]), + ([1, 2, "a"], [1, 2, 3], [1, 2, np.nan]), + ([2, "a", "b"], list("abc"), [np.nan, "a", "b"]), + ], + ) + def test_unique(self, data, categories, expected_data, ordered): + dtype = pd.CategoricalDtype(categories, ordered=ordered) + + msg = "Constructing a Categorical with a dtype and values containing" + warn = None if expected_data == [1] else Pandas4Warning + with tm.assert_produces_warning(warn, match=msg): + idx = CategoricalIndex(data, dtype=dtype) + expected = CategoricalIndex(expected_data, dtype=dtype) + tm.assert_index_equal(idx.unique(), expected) + + def test_repr_roundtrip(self): + ci = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True) + str(ci) + tm.assert_index_equal(eval(repr(ci)), ci, exact=True) + + # formatting + str(ci) + + # long format + # this is not reprable + ci = CategoricalIndex(np.random.default_rng(2).integers(0, 5, size=100)) + str(ci) + + def test_isin(self): + ci = CategoricalIndex([*list("aabca"), np.nan], categories=["c", "a", "b"]) + tm.assert_numpy_array_equal( + ci.isin(["c"]), np.array([False, False, False, True, False, False]) + ) + tm.assert_numpy_array_equal( + ci.isin(["c", "a", "b"]), np.array([True] * 5 + [False]) + ) + tm.assert_numpy_array_equal( + ci.isin(["c", "a", "b", np.nan]), np.array([True] * 6) + ) + + # mismatched categorical -> coerced to ndarray so doesn't matter + result = ci.isin(ci.set_categories(list("abcdefghi"))) + expected = np.array([True] * 6) + tm.assert_numpy_array_equal(result, expected) + + result = ci.isin(ci.set_categories(list("defghi"))) + expected = np.array([False] * 5 + [True]) + tm.assert_numpy_array_equal(result, expected) + + def test_isin_overlapping_intervals(self): + # GH 34974 + idx = pd.IntervalIndex([pd.Interval(0, 2), pd.Interval(0, 1)]) + result = CategoricalIndex(idx).isin(idx) + expected = np.array([True, True]) + tm.assert_numpy_array_equal(result, expected) + + def test_identical(self): + ci1 = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True) + ci2 = CategoricalIndex(["a", "b"], categories=["a", "b", "c"], ordered=True) + assert ci1.identical(ci1) + assert ci1.identical(ci1.copy()) + assert not ci1.identical(ci2) + + def test_ensure_copied_data(self): + # gh-12309: Check the "copy" argument of each + # Index.__new__ is honored. + # + # Must be tested separately from other indexes because + # self.values is not an ndarray. + index = CategoricalIndex(list("ab") * 5) + + result = CategoricalIndex(index.values, copy=True) + tm.assert_index_equal(index, result) + assert not np.shares_memory(result._data._codes, index._data._codes) + + result = CategoricalIndex(index.values, copy=False) + assert result._data._codes is index._data._codes + + +class TestCategoricalIndex2: + def test_view_i8(self): + # GH#25464 + ci = CategoricalIndex(list("ab") * 50) + msg = "When changing to a larger dtype, its size must be a divisor" + with pytest.raises(ValueError, match=msg): + ci.view("i8") + with pytest.raises(ValueError, match=msg): + ci._data.view("i8") + + ci = ci[:-4] # length divisible by 8 + + res = ci.view("i8") + expected = ci._data.codes.view("i8") + tm.assert_numpy_array_equal(res, expected) + + cat = ci._data + tm.assert_numpy_array_equal(cat.view("i8"), expected) + + @pytest.mark.parametrize( + "dtype, engine_type", + [ + (np.int8, libindex.Int8Engine), + (np.int16, libindex.Int16Engine), + (np.int32, libindex.Int32Engine), + (np.int64, libindex.Int64Engine), + ], + ) + def test_engine_type(self, dtype, engine_type): + if dtype != np.int64: + # num. of uniques required to push CategoricalIndex.codes to a + # dtype (128 categories required for .codes dtype to be int16 etc.) + num_uniques = {np.int8: 1, np.int16: 128, np.int32: 32768}[dtype] + ci = CategoricalIndex(range(num_uniques)) + else: + # having 2**32 - 2**31 categories would be very memory-intensive, + # so we cheat a bit with the dtype + ci = CategoricalIndex(range(32768)) # == 2**16 - 2**(16 - 1) + arr = ci.values._ndarray.astype("int64") + NDArrayBacked.__init__(ci._data, arr, ci.dtype) + assert np.issubdtype(ci.codes.dtype, dtype) + assert isinstance(ci._engine, engine_type) + + @pytest.mark.parametrize( + "func,op_name", + [ + (lambda idx: idx - idx, "__sub__"), + (lambda idx: idx + idx, "__add__"), + (lambda idx: idx - ["a", "b"], "__sub__"), + (lambda idx: idx + ["a", "b"], "__add__"), # noqa: RUF005 + (lambda idx: ["a", "b"] - idx, "__rsub__"), + (lambda idx: ["a", "b"] + idx, "__radd__"), # noqa: RUF005 + ], + ) + def test_disallow_addsub_ops(self, func, op_name): + # GH 10039 + # set ops (+/-) raise TypeError + idx = Index(pd.Categorical(["a", "b"])) + cat_or_list = "'(Categorical|list)' and '(Categorical|list)'" + msg = "|".join( + [ + rf"unsupported operand type\(s\) for [\+-]: {cat_or_list}", + "Object with dtype category cannot perform the numpy op (add|subtract)", + "operation 'r?(add|sub)' not supported for dtype 'str' " + "with dtype 'category'", + ] + ) + with pytest.raises(TypeError, match=msg): + func(idx) + + def test_method_delegation(self): + ci = CategoricalIndex(list("aabbca"), categories=list("cabdef")) + result = ci.set_categories(list("cab")) + tm.assert_index_equal( + result, CategoricalIndex(list("aabbca"), categories=list("cab")) + ) + + ci = CategoricalIndex(list("aabbca"), categories=list("cab")) + result = ci.rename_categories(list("efg")) + tm.assert_index_equal( + result, CategoricalIndex(list("ffggef"), categories=list("efg")) + ) + + # GH18862 (let rename_categories take callables) + result = ci.rename_categories(lambda x: x.upper()) + tm.assert_index_equal( + result, CategoricalIndex(list("AABBCA"), categories=list("CAB")) + ) + + ci = CategoricalIndex(list("aabbca"), categories=list("cab")) + result = ci.add_categories(["d"]) + tm.assert_index_equal( + result, CategoricalIndex(list("aabbca"), categories=list("cabd")) + ) + + ci = CategoricalIndex(list("aabbca"), categories=list("cab")) + result = ci.remove_categories(["c"]) + tm.assert_index_equal( + result, + CategoricalIndex([*list("aabb"), np.nan, "a"], categories=list("ab")), + ) + + ci = CategoricalIndex(list("aabbca"), categories=list("cabdef")) + result = ci.as_unordered() + tm.assert_index_equal(result, ci) + + ci = CategoricalIndex(list("aabbca"), categories=list("cabdef")) + result = ci.as_ordered() + tm.assert_index_equal( + result, + CategoricalIndex(list("aabbca"), categories=list("cabdef"), ordered=True), + ) + + # invalid + msg = "unexpected keyword argument 'inplace'" + with pytest.raises(TypeError, match=msg): + ci.set_categories(list("cab"), inplace=True) + + def test_remove_maintains_order(self): + ci = CategoricalIndex(list("abcdda"), categories=list("abcd")) + result = ci.reorder_categories(["d", "c", "b", "a"], ordered=True) + tm.assert_index_equal( + result, + CategoricalIndex(list("abcdda"), categories=list("dcba"), ordered=True), + ) + result = result.remove_categories(["c"]) + tm.assert_index_equal( + result, + CategoricalIndex( + ["a", "b", np.nan, "d", "d", "a"], categories=list("dba"), ordered=True + ), + ) + + +def test_contains_rangeindex_categories_no_engine(): + ci = CategoricalIndex(range(3)) + assert 2 in ci + assert 5 not in ci + assert "_engine" not in ci._cache diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_constructors.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..93e6b3f2ecdc2d2852e2e2237c8ca863e083b394 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_constructors.py @@ -0,0 +1,146 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestCategoricalIndexConstructors: + def test_construction_disallows_scalar(self): + msg = "must be called with a collection of some kind" + with pytest.raises(TypeError, match=msg): + pd.CategoricalIndex(data=1, categories=list("abcd"), ordered=False) + with pytest.raises(TypeError, match=msg): + pd.CategoricalIndex(categories=list("abcd"), ordered=False) + + def test_construction(self): + ci = pd.CategoricalIndex(list("aabbca"), categories=list("abcd"), ordered=False) + categories = ci.categories + + result = pd.Index(ci) + tm.assert_index_equal(result, ci, exact=True) + assert not result.ordered + + result = pd.Index(ci.values) + tm.assert_index_equal(result, ci, exact=True) + assert not result.ordered + + # empty + result = pd.CategoricalIndex([], categories=categories) + tm.assert_index_equal(result.categories, pd.Index(categories)) + tm.assert_numpy_array_equal(result.codes, np.array([], dtype="int8")) + assert not result.ordered + + # passing categories + result = pd.CategoricalIndex(list("aabbca"), categories=categories) + tm.assert_index_equal(result.categories, pd.Index(categories)) + tm.assert_numpy_array_equal( + result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8") + ) + + c = pd.Categorical(list("aabbca")) + result = pd.CategoricalIndex(c) + tm.assert_index_equal(result.categories, pd.Index(list("abc"))) + tm.assert_numpy_array_equal( + result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8") + ) + assert not result.ordered + + result = pd.CategoricalIndex(c, categories=categories) + tm.assert_index_equal(result.categories, pd.Index(categories)) + tm.assert_numpy_array_equal( + result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8") + ) + assert not result.ordered + + ci = pd.CategoricalIndex(c, categories=list("abcd")) + result = pd.CategoricalIndex(ci) + tm.assert_index_equal(result.categories, pd.Index(categories)) + tm.assert_numpy_array_equal( + result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8") + ) + assert not result.ordered + + msg = "Constructing a Categorical with a dtype and values containing" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = pd.CategoricalIndex(ci, categories=list("ab")) + tm.assert_index_equal(result.categories, pd.Index(list("ab"))) + tm.assert_numpy_array_equal( + result.codes, np.array([0, 0, 1, 1, -1, 0], dtype="int8") + ) + assert not result.ordered + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = pd.CategoricalIndex(ci, categories=list("ab"), ordered=True) + tm.assert_index_equal(result.categories, pd.Index(list("ab"))) + tm.assert_numpy_array_equal( + result.codes, np.array([0, 0, 1, 1, -1, 0], dtype="int8") + ) + assert result.ordered + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = pd.CategoricalIndex(ci, categories=list("ab"), ordered=True) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = pd.CategoricalIndex( + ci, categories=list("ab"), ordered=True, dtype="category" + ) + tm.assert_index_equal(result, expected, exact=True) + + # turn me to an Index + result = pd.Index(np.array(ci)) + assert isinstance(result, pd.Index) + assert not isinstance(result, pd.CategoricalIndex) + + def test_construction_with_dtype(self): + # specify dtype + ci = pd.CategoricalIndex(list("aabbca"), categories=list("abc"), ordered=False) + + result = pd.Index(np.array(ci), dtype="category") + tm.assert_index_equal(result, ci, exact=True) + + result = pd.Index(np.array(ci).tolist(), dtype="category") + tm.assert_index_equal(result, ci, exact=True) + + # these are generally only equal when the categories are reordered + ci = pd.CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) + + result = pd.Index(np.array(ci), dtype="category").reorder_categories( + ci.categories + ) + tm.assert_index_equal(result, ci, exact=True) + + # make sure indexes are handled + idx = pd.Index(range(3)) + expected = pd.CategoricalIndex([0, 1, 2], categories=idx, ordered=True) + result = pd.CategoricalIndex(idx, categories=idx, ordered=True) + tm.assert_index_equal(result, expected, exact=True) + + def test_construction_empty_with_bool_categories(self): + # see GH#22702 + cat = pd.CategoricalIndex([], categories=[True, False]) + categories = sorted(cat.categories.tolist()) + assert categories == [False, True] + + def test_construction_with_categorical_dtype(self): + # construction with CategoricalDtype + # GH#18109 + data, cats, ordered = "a a b b".split(), "c b a".split(), True + dtype = pd.CategoricalDtype(categories=cats, ordered=ordered) + + result = pd.CategoricalIndex(data, dtype=dtype) + expected = pd.CategoricalIndex(data, categories=cats, ordered=ordered) + tm.assert_index_equal(result, expected, exact=True) + + # GH#19032 + result = pd.Index(data, dtype=dtype) + tm.assert_index_equal(result, expected, exact=True) + + # error when combining categories/ordered and dtype kwargs + msg = "Cannot specify `categories` or `ordered` together with `dtype`." + with pytest.raises(ValueError, match=msg): + pd.CategoricalIndex(data, categories=cats, dtype=dtype) + + with pytest.raises(ValueError, match=msg): + pd.CategoricalIndex(data, ordered=ordered, dtype=dtype) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_equals.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_equals.py new file mode 100644 index 0000000000000000000000000000000000000000..746366e5a4c482262f54ff49840e25d4247807a7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_equals.py @@ -0,0 +1,93 @@ +import numpy as np +import pytest + +import pandas as pd + + +class TestEquals: + def test_equals_categorical(self): + ci1 = pd.CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True) + ci2 = pd.CategoricalIndex(["a", "b"], categories=["a", "b", "c"], ordered=True) + + assert ci1.equals(ci1) + assert not ci1.equals(ci2) + assert ci1.equals(ci1.astype(object)) + assert ci1.astype(object).equals(ci1) + + assert (ci1 == ci1).all() + assert not (ci1 != ci1).all() + assert not (ci1 > ci1).all() + assert not (ci1 < ci1).all() + assert (ci1 <= ci1).all() + assert (ci1 >= ci1).all() + + assert not (ci1 == 1).all() + assert (ci1 == pd.Index(["a", "b"])).all() + assert (ci1 == ci1.values).all() + + # invalid comparisons + with pytest.raises(ValueError, match="Lengths must match"): + ci1 == pd.Index(["a", "b", "c"]) + + msg = "Categoricals can only be compared if 'categories' are the same" + with pytest.raises(TypeError, match=msg): + ci1 == ci2 + with pytest.raises(TypeError, match=msg): + ci1 == pd.Categorical(ci1.values, ordered=False) + with pytest.raises(TypeError, match=msg): + ci1 == pd.Categorical(ci1.values, categories=list("abc")) + + # tests + # make sure that we are testing for category inclusion properly + ci = pd.CategoricalIndex(list("aabca"), categories=["c", "a", "b"]) + assert not ci.equals(list("aabca")) + # Same categories, but different order + # Unordered + assert ci.equals(pd.CategoricalIndex(list("aabca"))) + # Ordered + assert not ci.equals(pd.CategoricalIndex(list("aabca"), ordered=True)) + assert ci.equals(ci.copy()) + + ci = pd.CategoricalIndex([*list("aabca"), np.nan], categories=["c", "a", "b"]) + assert not ci.equals(list("aabca")) + assert not ci.equals(pd.CategoricalIndex(list("aabca"))) + assert ci.equals(ci.copy()) + + ci = pd.CategoricalIndex([*list("aabca"), np.nan], categories=["c", "a", "b"]) + assert not ci.equals([*list("aabca"), np.nan]) + assert ci.equals(pd.CategoricalIndex([*list("aabca"), np.nan])) + assert not ci.equals( + pd.CategoricalIndex([*list("aabca"), np.nan], ordered=True) + ) + assert ci.equals(ci.copy()) + + def test_equals_categorical_unordered(self): + # https://github.com/pandas-dev/pandas/issues/16603 + a = pd.CategoricalIndex(["A"], categories=["A", "B"]) + b = pd.CategoricalIndex(["A"], categories=["B", "A"]) + c = pd.CategoricalIndex([None], categories=["B", "A"]) + assert a.equals(b) + assert not a.equals(c) + assert not b.equals(c) + + def test_equals_non_category(self): + # GH#37667 Case where other contains a value not among ci's + # categories ("D") and also contains np.nan + ci = pd.CategoricalIndex(["A", "B", np.nan, np.nan]) + other = pd.Index(["A", "B", "D", np.nan]) + + assert not ci.equals(other) + + def test_equals_multiindex(self): + # dont raise NotImplementedError when calling is_dtype_compat + + mi = pd.MultiIndex.from_arrays([["A", "B", "C", "D"], range(4)]) + ci = mi.to_flat_index().astype("category") + + assert not ci.equals(mi) + + def test_equals_string_dtype(self, any_string_dtype): + # GH#55364 + idx = pd.CategoricalIndex(list("abc"), name="B") + other = pd.Index(["a", "b", "c"], name="B", dtype=any_string_dtype) + assert idx.equals(other) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_fillna.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_fillna.py new file mode 100644 index 0000000000000000000000000000000000000000..0630b55ae066813ad8682447868bb058ba50271a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_fillna.py @@ -0,0 +1,72 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestFillNA: + def test_fillna_categorical(self): + # GH#11343 + idx = pd.CategoricalIndex([1.0, np.nan, 3.0, 1.0], name="x") + # fill by value in categories + exp = pd.CategoricalIndex([1.0, 1.0, 3.0, 1.0], name="x") + tm.assert_index_equal(idx.fillna(1.0), exp) + + cat = idx._data + + # fill by value not in categories raises TypeError on EA, casts on CI + msg = "Cannot setitem on a Categorical with a new category" + with pytest.raises(TypeError, match=msg): + cat.fillna(2.0) + + depr_msg = "'float' is not supported as a fill value for category dtype" + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + result = idx.fillna(2.0) + expected = idx.astype(object).fillna(2.0) + tm.assert_index_equal(result, expected) + + def test_fillna_copies_with_no_nas(self): + # Nothing to fill, should still get a copy for the Categorical method, + # but OK to get a view on CategoricalIndex method + ci = pd.CategoricalIndex([0, 1, 1]) + result = ci.fillna(0) + assert result is not ci + assert tm.shares_memory(result, ci) + + # But at the EA level we always get a copy. + cat = ci._data + result = cat.fillna(0) + assert result._ndarray is not cat._ndarray + assert result._ndarray.base is None + assert not tm.shares_memory(result, cat) + + def test_fillna_tuple_category(self): + # GH#37681 fillna with a tuple that is a valid category + ci = pd.CategoricalIndex([(0, 1), (1, 2), pd.NA]) + result = ci.fillna((0, 1)) + expected = pd.CategoricalIndex([(0, 1), (1, 2), (0, 1)]) + tm.assert_index_equal(result, expected) + + # tuple not in categories -> casts to object, same as scalar behavior + msg = "'tuple' is not supported as a fill value for category dtype" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = ci.fillna((9, 9)) + expected = pd.Index([(0, 1), (1, 2), (9, 9)], tupleize_cols=False) + tm.assert_index_equal(result, expected) + + def test_fillna_validates_with_no_nas(self): + # We validate the fill value even if fillna is a no-op + ci = pd.CategoricalIndex([2, 3, 3]) + cat = ci._data + + msg = "Cannot setitem on a Categorical with a new category" + res = ci.fillna(False) + # nothing to fill, so we dont cast + tm.assert_index_equal(res, ci) + + # Same check directly on the Categorical + with pytest.raises(TypeError, match=msg): + cat.fillna(False) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_formats.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_formats.py new file mode 100644 index 0000000000000000000000000000000000000000..698c8ba2b33d51e3da22b0dcda665b94f5a6c46e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_formats.py @@ -0,0 +1,179 @@ +""" +Tests for CategoricalIndex.__repr__ and related methods. +""" + +import pandas._config.config as cf + +import pandas as pd + + +class TestCategoricalIndexReprStringCategories: + def test_string_categorical_index_repr(self): + # short + idx = pd.CategoricalIndex(["a", "bb", "ccc"]) + expected = ( + "CategoricalIndex(['a', 'bb', 'ccc'], " + "categories=['a', 'bb', 'ccc'],\n" + " ordered=False, dtype='category')" + ) + assert repr(idx) == expected + + def test_categorical_index_repr_multiline(self): + # multiple lines + idx = pd.CategoricalIndex(["a", "bb", "ccc"] * 10) + expected = ( + "CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', " + "'bb', 'ccc', 'a',\n" + " 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', " + "'ccc', 'a', 'bb',\n" + " 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', " + "'a', 'bb', 'ccc'],\n" + " categories=['a', 'bb', 'ccc'], " + "ordered=False, dtype='category')" + ) + assert repr(idx) == expected + + def test_categorical_index_repr_truncated(self): + # truncated + idx = pd.CategoricalIndex(["a", "bb", "ccc"] * 100) + expected = ( + "CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', " + "'bb', 'ccc', 'a',\n" + " ...\n" + " 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', " + "'a', 'bb', 'ccc'],\n" + " categories=['a', 'bb', 'ccc'], " + "ordered=False, dtype='category',\n" + " length=300)" + ) + assert repr(idx) == expected + + def test_categorical_index_repr_many_categories(self): + # larger categories + idx = pd.CategoricalIndex(list("abcdefghijklmmo")) + expected = ( + "CategoricalIndex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', " + "'i', 'j', 'k', 'l',\n" + " 'm', 'm', 'o'],\n" + " categories=['a', 'b', 'c', 'd', ..., " + "'k', 'l', 'm', 'o'],\n" + " ordered=False, dtype='category')" + ) + assert repr(idx) == expected + + def test_categorical_index_repr_unicode(self): + # short + idx = pd.CategoricalIndex(["あ", "いい", "ううう"]) + expected = ( + "CategoricalIndex(['あ', 'いい', 'ううう'], " + "categories=['あ', 'いい', 'ううう'],\n" + " ordered=False, dtype='category')" + ) + assert repr(idx) == expected + + def test_categorical_index_repr_unicode_multiline(self): + # multiple lines + idx = pd.CategoricalIndex(["あ", "いい", "ううう"] * 10) + expected = ( + "CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " + "'あ', 'いい', 'ううう', 'あ',\n" + " 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', " + "'いい', 'ううう', 'あ', 'いい',\n" + " 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい', 'ううう'],\n" + " categories=['あ', 'いい', 'ううう'], " + "ordered=False, dtype='category')" + ) + assert repr(idx) == expected + + def test_categorical_index_repr_unicode_truncated(self): + # truncated + idx = pd.CategoricalIndex(["あ", "いい", "ううう"] * 100) + expected = ( + "CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " + "'あ', 'いい', 'ううう', 'あ',\n" + " ...\n" + " 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい', 'ううう'],\n" + " categories=['あ', 'いい', 'ううう'], " + "ordered=False, dtype='category',\n" + " length=300)" + ) + assert repr(idx) == expected + + def test_categorical_index_repr_unicode_many_categories(self): + # larger categories + idx = pd.CategoricalIndex(list("あいうえおかきくけこさしすせそ")) + expected = ( + "CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', " + "'く', 'け', 'こ', 'さ', 'し',\n" + " 'す', 'せ', 'そ'],\n" + " categories=['あ', 'い', 'う', 'え', ..., " + "'し', 'す', 'せ', 'そ'],\n" + " ordered=False, dtype='category')" + ) + assert repr(idx) == expected + + def test_categorical_index_repr_east_asian_width(self): + with cf.option_context("display.unicode.east_asian_width", True): + # short + idx = pd.CategoricalIndex(["あ", "いい", "ううう"]) + expected = ( + "CategoricalIndex(['あ', 'いい', 'ううう'], " + "categories=['あ', 'いい', 'ううう'],\n" + " ordered=False, dtype='category')" + ) + assert repr(idx) == expected + + def test_categorical_index_repr_east_asian_width_multiline(self): + with cf.option_context("display.unicode.east_asian_width", True): + # multiple lines + idx = pd.CategoricalIndex(["あ", "いい", "ううう"] * 10) + expected = ( + "CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい',\n" + " 'ううう', 'あ', 'いい', 'ううう', 'あ', " + "'いい', 'ううう',\n" + " 'あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい',\n" + " 'ううう', 'あ', 'いい', 'ううう', 'あ', " + "'いい', 'ううう'],\n" + " categories=['あ', 'いい', 'ううう'], " + "ordered=False,\n" + " dtype='category')" + ) + + assert repr(idx) == expected + + def test_categorical_index_repr_east_asian_width_truncated(self): + with cf.option_context("display.unicode.east_asian_width", True): + # truncated + idx = pd.CategoricalIndex(["あ", "いい", "ううう"] * 100) + expected = ( + "CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', " + "'ううう', 'あ', 'いい',\n" + " 'ううう', 'あ',\n" + " ...\n" + " 'ううう', 'あ', 'いい', 'ううう', 'あ', " + "'いい', 'ううう',\n" + " 'あ', 'いい', 'ううう'],\n" + " categories=['あ', 'いい', 'ううう'], " + "ordered=False,\n" + " dtype='category', length=300)" + ) + + assert repr(idx) == expected + + def test_categorical_index_repr_east_asian_width_many_categories(self): + with cf.option_context("display.unicode.east_asian_width", True): + idx = pd.CategoricalIndex(list("あいうえおかきくけこさしすせそ")) + expected = ( + "CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', " + "'く', 'け', 'こ',\n" + " 'さ', 'し', 'す', 'せ', 'そ'],\n" + " categories=['あ', 'い', 'う', 'え', ..., " + "'し', 'す', 'せ', 'そ'],\n" + " ordered=False, dtype='category')" + ) + + assert repr(idx) == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..a5d5958898b157e6cccc5ec196d17db93b1e948a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_indexing.py @@ -0,0 +1,415 @@ +import numpy as np +import pytest + +from pandas.errors import InvalidIndexError + +import pandas as pd +import pandas._testing as tm + + +class TestTake: + def test_take_fill_value(self): + # GH 12631 + + # numeric category + idx = pd.CategoricalIndex([1, 2, 3], name="xxx") + result = idx.take(np.array([1, 0, -1])) + expected = pd.CategoricalIndex([2, 1, 3], name="xxx") + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=np.nan) + expected = pd.CategoricalIndex([2, 1, np.nan], categories=[1, 2, 3], name="xxx") + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = pd.CategoricalIndex([2, 1, 3], name="xxx") + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # object category + idx = pd.CategoricalIndex( + list("CBA"), categories=list("ABC"), ordered=True, name="xxx" + ) + result = idx.take(np.array([1, 0, -1])) + expected = pd.CategoricalIndex( + list("BCA"), categories=list("ABC"), ordered=True, name="xxx" + ) + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=np.nan) + expected = pd.CategoricalIndex( + ["B", "C", np.nan], categories=list("ABC"), ordered=True, name="xxx" + ) + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = pd.CategoricalIndex( + list("BCA"), categories=list("ABC"), ordered=True, name="xxx" + ) + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + msg = "When allow_fill=True, all indices must be >= -1" + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=np.nan) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=np.nan) + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + def test_take_fill_value_datetime(self): + # datetime category + idx = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx") + idx = pd.CategoricalIndex(idx) + result = idx.take(np.array([1, 0, -1])) + expected = pd.DatetimeIndex( + ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx" + ) + expected = pd.CategoricalIndex(expected) + tm.assert_index_equal(result, expected) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=pd.NaT) + expected = pd.DatetimeIndex(["2011-02-01", "2011-01-01", "NaT"], name="xxx") + exp_cats = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"]) + expected = pd.CategoricalIndex(expected, categories=exp_cats) + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = pd.DatetimeIndex( + ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx" + ) + expected = pd.CategoricalIndex(expected) + tm.assert_index_equal(result, expected) + + msg = "When allow_fill=True, all indices must be >= -1" + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=pd.NaT) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=pd.NaT) + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + def test_take_invalid_kwargs(self): + idx = pd.CategoricalIndex([1, 2, 3], name="foo") + indices = [1, 0, -1] + + msg = r"take\(\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg): + idx.take(indices, foo=2) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, out=indices) + + msg = "the 'mode' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, mode="clip") + + +class TestGetLoc: + def test_get_loc(self): + # GH 12531 + cidx1 = pd.CategoricalIndex(list("abcde"), categories=list("edabc")) + idx1 = pd.Index(list("abcde")) + assert cidx1.get_loc("a") == idx1.get_loc("a") + assert cidx1.get_loc("e") == idx1.get_loc("e") + + for i in [cidx1, idx1]: + with pytest.raises(KeyError, match="'NOT-EXIST'"): + i.get_loc("NOT-EXIST") + + # non-unique + cidx2 = pd.CategoricalIndex(list("aacded"), categories=list("edabc")) + idx2 = pd.Index(list("aacded")) + + # results in bool array + res = cidx2.get_loc("d") + tm.assert_numpy_array_equal(res, idx2.get_loc("d")) + tm.assert_numpy_array_equal( + res, np.array([False, False, False, True, False, True]) + ) + # unique element results in scalar + res = cidx2.get_loc("e") + assert res == idx2.get_loc("e") + assert res == 4 + + for i in [cidx2, idx2]: + with pytest.raises(KeyError, match="'NOT-EXIST'"): + i.get_loc("NOT-EXIST") + + # non-unique, sliceable + cidx3 = pd.CategoricalIndex(list("aabbb"), categories=list("abc")) + idx3 = pd.Index(list("aabbb")) + + # results in slice + res = cidx3.get_loc("a") + assert res == idx3.get_loc("a") + assert res == slice(0, 2, None) + + res = cidx3.get_loc("b") + assert res == idx3.get_loc("b") + assert res == slice(2, 5, None) + + for i in [cidx3, idx3]: + with pytest.raises(KeyError, match="'c'"): + i.get_loc("c") + + def test_get_loc_unique(self): + cidx = pd.CategoricalIndex(list("abc")) + result = cidx.get_loc("b") + assert result == 1 + + def test_get_loc_monotonic_nonunique(self): + cidx = pd.CategoricalIndex(list("abbc")) + result = cidx.get_loc("b") + expected = slice(1, 3, None) + assert result == expected + + def test_get_loc_nonmonotonic_nonunique(self): + cidx = pd.CategoricalIndex(list("abcb")) + result = cidx.get_loc("b") + expected = np.array([False, True, False, True], dtype=bool) + tm.assert_numpy_array_equal(result, expected) + + def test_get_loc_nan(self): + # GH#41933 + ci = pd.CategoricalIndex(["A", "B", np.nan]) + res = ci.get_loc(np.nan) + + assert res == 2 + + +class TestGetIndexer: + def test_get_indexer_base(self): + # Determined by cat ordering. + idx = pd.CategoricalIndex(list("cab"), categories=list("cab")) + expected = np.arange(len(idx), dtype=np.intp) + + actual = idx.get_indexer(idx) + tm.assert_numpy_array_equal(expected, actual) + + with pytest.raises(ValueError, match="Invalid fill method"): + idx.get_indexer(idx, method="invalid") + + def test_get_indexer_requires_unique(self): + ci = pd.CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) + oidx = pd.Index(np.array(ci)) + + msg = "Reindexing only valid with uniquely valued Index objects" + + for n in [1, 2, 5, len(ci)]: + finder = oidx[np.random.default_rng(2).integers(0, len(ci), size=n)] + + with pytest.raises(InvalidIndexError, match=msg): + ci.get_indexer(finder) + + # see gh-17323 + # + # Even when indexer is equal to the + # members in the index, we should + # respect duplicates instead of taking + # the fast-track path. + for finder in [list("aabbca"), list("aababca")]: + with pytest.raises(InvalidIndexError, match=msg): + ci.get_indexer(finder) + + def test_get_indexer_non_unique(self): + idx1 = pd.CategoricalIndex(list("aabcde"), categories=list("edabc")) + idx2 = pd.CategoricalIndex(list("abf")) + + for indexer in [idx2, list("abf"), pd.Index(list("abf"))]: + msg = "Reindexing only valid with uniquely valued Index objects" + with pytest.raises(InvalidIndexError, match=msg): + idx1.get_indexer(indexer) + + r1, _ = idx1.get_indexer_non_unique(indexer) + expected = np.array([0, 1, 2, -1], dtype=np.intp) + tm.assert_almost_equal(r1, expected) + + def test_get_indexer_method(self): + idx1 = pd.CategoricalIndex(list("aabcde"), categories=list("edabc")) + idx2 = pd.CategoricalIndex(list("abf")) + + msg = "method pad not yet implemented for CategoricalIndex" + with pytest.raises(NotImplementedError, match=msg): + idx2.get_indexer(idx1, method="pad") + msg = "method backfill not yet implemented for CategoricalIndex" + with pytest.raises(NotImplementedError, match=msg): + idx2.get_indexer(idx1, method="backfill") + + msg = "method nearest not yet implemented for CategoricalIndex" + with pytest.raises(NotImplementedError, match=msg): + idx2.get_indexer(idx1, method="nearest") + + def test_get_indexer_array(self): + arr = np.array( + [pd.Timestamp("1999-12-31 00:00:00"), pd.Timestamp("2000-12-31 00:00:00")], + dtype=object, + ) + cats = [ + pd.Timestamp("1999-12-31 00:00:00"), + pd.Timestamp("2000-12-31 00:00:00"), + ] + ci = pd.CategoricalIndex(cats, categories=cats, ordered=False, dtype="category") + result = ci.get_indexer(arr) + expected = np.array([0, 1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_same_categories_same_order(self): + ci = pd.CategoricalIndex(["a", "b"], categories=["a", "b"]) + + result = ci.get_indexer(pd.CategoricalIndex(["b", "b"], categories=["a", "b"])) + expected = np.array([1, 1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_same_categories_different_order(self): + # https://github.com/pandas-dev/pandas/issues/19551 + ci = pd.CategoricalIndex(["a", "b"], categories=["a", "b"]) + + result = ci.get_indexer(pd.CategoricalIndex(["b", "b"], categories=["b", "a"])) + expected = np.array([1, 1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_nans_in_index_and_target(self): + # GH 45361 + ci = pd.CategoricalIndex([1, 2, np.nan, 3]) + other1 = [2, 3, 4, np.nan] + res1 = ci.get_indexer(other1) + expected1 = np.array([1, 3, -1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(res1, expected1) + other2 = [1, 4, 2, 3] + res2 = ci.get_indexer(other2) + expected2 = np.array([0, -1, 1, 3], dtype=np.intp) + tm.assert_numpy_array_equal(res2, expected2) + + +class TestWhere: + def test_where(self, listlike_box): + klass = listlike_box + + i = pd.CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) + cond = [True] * len(i) + expected = i + result = i.where(klass(cond)) + tm.assert_index_equal(result, expected) + + cond = [False] + [True] * (len(i) - 1) + expected = pd.CategoricalIndex( + [np.nan, *i[1:].tolist()], categories=i.categories + ) + result = i.where(klass(cond)) + tm.assert_index_equal(result, expected) + + def test_where_non_categories(self): + ci = pd.CategoricalIndex(["a", "b", "c", "d"]) + mask = np.array([True, False, True, False]) + + result = ci.where(mask, 2) + expected = pd.Index(["a", 2, "c", 2], dtype=object) + tm.assert_index_equal(result, expected) + + msg = "Cannot setitem on a Categorical with a new category" + with pytest.raises(TypeError, match=msg): + # Test the Categorical method directly + ci._data._where(mask, 2) + + +class TestContains: + def test_contains(self): + ci = pd.CategoricalIndex( + list("aabbca"), categories=list("cabdef"), ordered=False + ) + + assert "a" in ci + assert "z" not in ci + assert "e" not in ci + assert np.nan not in ci + + # assert codes NOT in index + assert 0 not in ci + assert 1 not in ci + + def test_contains_nan(self): + ci = pd.CategoricalIndex([*list("aabbca"), np.nan], categories=list("cabdef")) + assert np.nan in ci + + @pytest.mark.parametrize("unwrap", [True, False]) + def test_contains_na_dtype(self, unwrap): + dti = pd.date_range("2016-01-01", periods=100).insert(0, pd.NaT) + pi = dti.to_period("D") + tdi = dti - dti[-1] + ci = pd.CategoricalIndex(dti) + + obj = ci + if unwrap: + obj = ci._data + + assert np.nan in obj + assert None in obj + assert pd.NaT in obj + assert np.datetime64("NaT", "ns") in obj + assert np.timedelta64("NaT", "ns") not in obj + + obj2 = pd.CategoricalIndex(tdi) + if unwrap: + obj2 = obj2._data + + assert np.nan in obj2 + assert None in obj2 + assert pd.NaT in obj2 + assert np.datetime64("NaT", "ns") not in obj2 + assert np.timedelta64("NaT", "ns") in obj2 + + obj3 = pd.CategoricalIndex(pi) + if unwrap: + obj3 = obj3._data + + assert np.nan in obj3 + assert None in obj3 + assert pd.NaT in obj3 + assert np.datetime64("NaT", "ns") not in obj3 + assert np.timedelta64("NaT", "ns") not in obj3 + + @pytest.mark.parametrize( + "item, expected", + [ + (pd.Interval(0, 1), True), + (1.5, True), + (pd.Interval(0.5, 1.5), False), + ("a", False), + (pd.Timestamp(1), False), + (pd.Timedelta(1), False), + ], + ids=str, + ) + def test_contains_interval(self, item, expected): + # GH 23705 + ci = pd.CategoricalIndex(pd.IntervalIndex.from_breaks(range(3))) + result = item in ci + assert result is expected + + def test_contains_list(self): + # GH#21729 + idx = pd.CategoricalIndex([1, 2, 3]) + + assert "a" not in idx + + with pytest.raises(TypeError, match="unhashable type"): + ["a"] in idx + + with pytest.raises(TypeError, match="unhashable type"): + ["a", "b"] in idx diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_map.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_map.py new file mode 100644 index 0000000000000000000000000000000000000000..f79aee7a9000cffe02e99c2ade143cbc1e86983c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_map.py @@ -0,0 +1,141 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize( + "data, categories", + [ + (list("abcbca"), list("cab")), + (pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)), + ], + ids=["string", "interval"], +) +def test_map_str(data, categories, ordered): + # GH 31202 - override base class since we want to maintain categorical/ordered + index = pd.CategoricalIndex(data, categories=categories, ordered=ordered) + result = index.map(str) + expected = pd.CategoricalIndex( + map(str, data), categories=map(str, categories), ordered=ordered + ) + tm.assert_index_equal(result, expected) + + +def test_map(): + ci = pd.CategoricalIndex(list("ABABC"), categories=list("CBA"), ordered=True) + result = ci.map(lambda x: x.lower()) + exp = pd.CategoricalIndex(list("ababc"), categories=list("cba"), ordered=True) + tm.assert_index_equal(result, exp) + + ci = pd.CategoricalIndex( + list("ABABC"), categories=list("BAC"), ordered=False, name="XXX" + ) + result = ci.map(lambda x: x.lower()) + exp = pd.CategoricalIndex( + list("ababc"), categories=list("bac"), ordered=False, name="XXX" + ) + tm.assert_index_equal(result, exp) + + # GH 12766: Return an index not an array + tm.assert_index_equal( + ci.map(lambda x: 1), pd.Index(np.array([1] * 5, dtype=np.int64), name="XXX") + ) + + # change categories dtype + ci = pd.CategoricalIndex(list("ABABC"), categories=list("BAC"), ordered=False) + + def f(x): + return {"A": 10, "B": 20, "C": 30}.get(x) + + result = ci.map(f) + exp = pd.CategoricalIndex( + [10, 20, 10, 20, 30], categories=[20, 10, 30], ordered=False + ) + tm.assert_index_equal(result, exp) + + result = ci.map(pd.Series([10, 20, 30], index=["A", "B", "C"])) + tm.assert_index_equal(result, exp) + + result = ci.map({"A": 10, "B": 20, "C": 30}) + tm.assert_index_equal(result, exp) + + +def test_map_with_categorical_series(): + # GH 12756 + a = pd.Index([1, 2, 3, 4]) + b = pd.Series(["even", "odd", "even", "odd"], dtype="category") + c = pd.Series(["even", "odd", "even", "odd"]) + + exp = pd.CategoricalIndex(["odd", "even", "odd", np.nan]) + tm.assert_index_equal(a.map(b), exp) + exp = pd.Index(["odd", "even", "odd", np.nan]) + tm.assert_index_equal(a.map(c), exp) + + +@pytest.mark.parametrize( + ("data", "f", "expected"), + ( + ([1, 1, np.nan], pd.isna, pd.CategoricalIndex([False, False, np.nan])), + ([1, 2, np.nan], pd.isna, pd.Index([False, False, np.nan])), + ([1, 1, np.nan], {1: False}, pd.CategoricalIndex([False, False, np.nan])), + ([1, 2, np.nan], {1: False, 2: False}, pd.Index([False, False, np.nan])), + ( + [1, 1, np.nan], + pd.Series([False, False]), + pd.CategoricalIndex([False, False, np.nan]), + ), + ( + [1, 2, np.nan], + pd.Series([False, False, False]), + pd.Index([False, False, np.nan]), + ), + ), +) +def test_map_with_nan_ignore(data, f, expected): # GH 24241 + values = pd.CategoricalIndex(data) + result = values.map(f, na_action="ignore") + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + ("data", "f", "expected"), + ( + ([1, 1, np.nan], pd.isna, pd.Index([False, False, True])), + ([1, 2, np.nan], pd.isna, pd.Index([False, False, True])), + ([1, 1, np.nan], {1: False}, pd.CategoricalIndex([False, False, np.nan])), + ([1, 2, np.nan], {1: False, 2: False}, pd.Index([False, False, np.nan])), + ( + [1, 1, np.nan], + pd.Series([False, False]), + pd.CategoricalIndex([False, False, np.nan]), + ), + ( + [1, 2, np.nan], + pd.Series([False, False, False]), + pd.Index([False, False, np.nan]), + ), + ), +) +def test_map_with_nan_none(data, f, expected): # GH 24241 + values = pd.CategoricalIndex(data) + result = values.map(f, na_action=None) + tm.assert_index_equal(result, expected) + + +def test_map_with_dict_or_series(): + orig_values = ["a", "B", 1, "a"] + new_values = ["one", 2, 3.0, "one"] + cur_index = pd.CategoricalIndex(orig_values, name="XXX") + expected = pd.CategoricalIndex(new_values, name="XXX", categories=[3.0, 2, "one"]) + + mapper = pd.Series(new_values[:-1], index=orig_values[:-1]) + result = cur_index.map(mapper) + # Order of categories in result can be different + tm.assert_index_equal(result, expected) + + mapper = dict(zip(orig_values[:-1], new_values[:-1], strict=True)) + result = cur_index.map(mapper) + # Order of categories in result can be different + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_reindex.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_reindex.py new file mode 100644 index 0000000000000000000000000000000000000000..36b5d635ffb7474d46cc5a39e4d9d7d6c66bc51e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_reindex.py @@ -0,0 +1,73 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestReindex: + def test_reindex_list_non_unique(self): + # GH#11586 + msg = "cannot reindex on an axis with duplicate labels" + ci = pd.CategoricalIndex(["a", "b", "c", "a"]) + with pytest.raises(ValueError, match=msg): + ci.reindex(["a", "c"]) + + def test_reindex_categorical_non_unique(self): + msg = "cannot reindex on an axis with duplicate labels" + ci = pd.CategoricalIndex(["a", "b", "c", "a"]) + with pytest.raises(ValueError, match=msg): + ci.reindex(pd.Categorical(["a", "c"])) + + def test_reindex_list_non_unique_unused_category(self): + msg = "cannot reindex on an axis with duplicate labels" + ci = pd.CategoricalIndex(["a", "b", "c", "a"], categories=["a", "b", "c", "d"]) + with pytest.raises(ValueError, match=msg): + ci.reindex(["a", "c"]) + + def test_reindex_categorical_non_unique_unused_category(self): + msg = "cannot reindex on an axis with duplicate labels" + ci = pd.CategoricalIndex(["a", "b", "c", "a"], categories=["a", "b", "c", "d"]) + with pytest.raises(ValueError, match=msg): + ci.reindex(pd.Categorical(["a", "c"])) + + def test_reindex_duplicate_target(self): + # See GH25459 + cat = pd.CategoricalIndex(["a", "b", "c"], categories=["a", "b", "c", "d"]) + res, indexer = cat.reindex(["a", "c", "c"]) + exp = pd.Index(["a", "c", "c"]) + tm.assert_index_equal(res, exp, exact=True) + tm.assert_numpy_array_equal(indexer, np.array([0, 2, 2], dtype=np.intp)) + + res, indexer = cat.reindex( + pd.CategoricalIndex(["a", "c", "c"], categories=["a", "b", "c", "d"]) + ) + exp = pd.CategoricalIndex(["a", "c", "c"], categories=["a", "b", "c", "d"]) + tm.assert_index_equal(res, exp, exact=True) + tm.assert_numpy_array_equal(indexer, np.array([0, 2, 2], dtype=np.intp)) + + def test_reindex_empty_index(self): + # See GH16770 + c = pd.CategoricalIndex([]) + res, indexer = c.reindex(["a", "b"]) + tm.assert_index_equal(res, pd.Index(["a", "b"]), exact=True) + tm.assert_numpy_array_equal(indexer, np.array([-1, -1], dtype=np.intp)) + + def test_reindex_categorical_added_category(self): + # GH 42424 + ci = pd.CategoricalIndex( + [pd.Interval(0, 1, closed="right"), pd.Interval(1, 2, closed="right")], + ordered=True, + ) + ci_add = pd.CategoricalIndex( + [ + pd.Interval(0, 1, closed="right"), + pd.Interval(1, 2, closed="right"), + pd.Interval(2, 3, closed="right"), + pd.Interval(3, 4, closed="right"), + ], + ordered=True, + ) + result, _ = ci.reindex(ci_add) + expected = ci_add + tm.assert_index_equal(expected, result) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_setops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..447ec7cf1a7dd5b9a4f9d76c34a19d83b2843c20 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/categorical/test_setops.py @@ -0,0 +1,49 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize("method", ["union", "intersection"]) +def test_setop_mismatched_category_order(method): + # GH#55335 unordered CategoricalIndex with same categories in different + # order should give correct results for union/intersection + cats1 = ["a", "b", "c", "d"] + cats2 = ["d", "c", "b", "a"] + id1 = pd.CategoricalIndex(["a", "c"], categories=cats1) + id2 = pd.CategoricalIndex(["d", "b"], categories=cats2) + + result = getattr(id1, method)(id2) + if method == "union": + # sort=None (default) sorts the result + expected = pd.CategoricalIndex(["a", "b", "c", "d"], categories=cats1) + else: + expected = pd.CategoricalIndex([], categories=cats1) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("method", ["union", "intersection"]) +def test_setop_matching_category_order(method): + # GH#55335 - when categories match, the libjoin fastpath should be used + # and produce correct results. Monotonic + unique indexes hit the fastpath. + cats = ["a", "b", "c", "d"] + idx1 = pd.CategoricalIndex(["a", "b", "c"], categories=cats) + idx2 = pd.CategoricalIndex(["b", "c", "d"], categories=cats) + + result = getattr(idx1, method)(idx2) + if method == "union": + expected = pd.CategoricalIndex(["a", "b", "c", "d"], categories=cats) + else: + expected = pd.CategoricalIndex(["b", "c"], categories=cats) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("na_value", [None, np.nan]) +def test_difference_with_na(na_value): + # GH 57318 + ci = pd.CategoricalIndex(["a", "b", "c", None]) + other = pd.Index(["c", na_value]) + result = ci.difference(other) + expected = pd.CategoricalIndex(["a", "b"], categories=["a", "b", "c"]) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/conftest.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..05cff5b74790ba3dbf10cbc5fbbfab0f889d61fd --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/conftest.py @@ -0,0 +1,37 @@ +import numpy as np +import pytest + +import pandas as pd + + +@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 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", "min", "2min", "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, pd.array, pd.Series]) +def listlike_box(request): + """ + Types that may be passed as the indexer to searchsorted. + """ + return request.param diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.py new file mode 100644 index 0000000000000000000000000000000000000000..4cfc208387a8dfa4db332c8f242921d14760d12e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.py @@ -0,0 +1,95 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class DropDuplicates: + def test_drop_duplicates_metadata(self, idx): + # GH#10115 + result = idx.drop_duplicates() + tm.assert_index_equal(idx, result) + assert idx.freq == result.freq + + idx_dup = idx.append(idx) + result = idx_dup.drop_duplicates() + + expected = idx + if not isinstance(idx, pd.PeriodIndex): + # freq is reset except for PeriodIndex + assert idx_dup.freq is None + assert result.freq is None + expected = idx._with_freq(None) + else: + assert result.freq == expected.freq + + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "keep, expected, index", + [ + ( + "first", + np.concatenate(([False] * 10, [True] * 5)), + np.arange(0, 10, dtype=np.int64), + ), + ( + "last", + np.concatenate(([True] * 5, [False] * 10)), + np.arange(5, 15, dtype=np.int64), + ), + ( + False, + np.concatenate(([True] * 5, [False] * 5, [True] * 5)), + np.arange(5, 10, dtype=np.int64), + ), + ], + ) + def test_drop_duplicates(self, keep, expected, index, idx): + # to check Index/Series compat + idx = idx.append(idx[:5]) + + tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected) + expected = idx[~expected] + + result = idx.drop_duplicates(keep=keep) + tm.assert_index_equal(result, expected) + + result = pd.Series(idx).drop_duplicates(keep=keep) + expected = pd.Series(expected, index=index) + tm.assert_series_equal(result, expected) + + +class TestDropDuplicatesPeriodIndex(DropDuplicates): + @pytest.fixture(params=["D", "3D", "h", "2h", "min", "2min", "s", "3s"]) + def freq(self, request): + """ + Fixture to test for different frequencies for PeriodIndex. + """ + return request.param + + @pytest.fixture + def idx(self, freq): + """ + Fixture to get PeriodIndex for 10 periods for different frequencies. + """ + return pd.period_range("2011-01-01", periods=10, freq=freq, name="idx") + + +class TestDropDuplicatesDatetimeIndex(DropDuplicates): + @pytest.fixture + def idx(self, freq_sample): + """ + Fixture to get DatetimeIndex for 10 periods for different frequencies. + """ + return pd.date_range("2011-01-01", freq=freq_sample, periods=10, name="idx") + + +class TestDropDuplicatesTimedeltaIndex(DropDuplicates): + @pytest.fixture + def idx(self, freq_sample): + """ + Fixture to get TimedeltaIndex for 10 periods for different frequencies. + """ + return pd.timedelta_range("1 day", periods=10, freq=freq_sample, name="idx") diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_equals.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_equals.py new file mode 100644 index 0000000000000000000000000000000000000000..e615f703aed8279a914c9343a5f1b5436d5a7a5c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_equals.py @@ -0,0 +1,175 @@ +""" +Tests shared for DatetimeIndex/TimedeltaIndex/PeriodIndex +""" + +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class EqualsTests: + def test_not_equals_numeric(self, index): + assert not index.equals(pd.Index(index.asi8)) + assert not index.equals(pd.Index(index.asi8.astype("u8"))) + assert not index.equals(pd.Index(index.asi8).astype("f8")) + + def test_equals(self, index): + assert index.equals(index) + assert index.equals(index.astype(object)) + assert index.equals(pd.CategoricalIndex(index)) + assert index.equals(pd.CategoricalIndex(index.astype(object))) + + def test_not_equals_non_arraylike(self, index): + assert not index.equals(list(index)) + + def test_not_equals_strings(self, index): + other = pd.Index([str(x) for x in index], dtype=object) + assert not index.equals(other) + assert not index.equals(pd.CategoricalIndex(other)) + + def test_not_equals_misc_strs(self, index): + other = pd.Index(list("abc")) + assert not index.equals(other) + + +class TestPeriodIndexEquals(EqualsTests): + @pytest.fixture + def index(self): + """Fixture for creating a PeriodIndex for use in equality tests.""" + return pd.period_range("2013-01-01", periods=5, freq="D") + + # TODO: de-duplicate with other test_equals2 methods + @pytest.mark.parametrize("freq", ["D", "M"]) + def test_equals2(self, freq): + # GH#13107 + idx = pd.PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq=freq) + assert idx.equals(idx) + assert idx.equals(idx.copy()) + assert idx.equals(idx.astype(object)) + assert idx.astype(object).equals(idx) + assert idx.astype(object).equals(idx.astype(object)) + assert not idx.equals(list(idx)) + assert not idx.equals(pd.Series(idx)) + + idx2 = pd.PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq="h") + assert not idx.equals(idx2) + assert not idx.equals(idx2.copy()) + assert not idx.equals(idx2.astype(object)) + assert not idx.astype(object).equals(idx2) + assert not idx.equals(list(idx2)) + assert not idx.equals(pd.Series(idx2)) + + # same internal, different tz + idx3 = pd.PeriodIndex._simple_new( + idx._values._simple_new(idx._values.asi8, dtype=pd.PeriodDtype("h")) + ) + tm.assert_numpy_array_equal(idx.asi8, idx3.asi8) + assert not idx.equals(idx3) + assert not idx.equals(idx3.copy()) + assert not idx.equals(idx3.astype(object)) + assert not idx.astype(object).equals(idx3) + assert not idx.equals(list(idx3)) + assert not idx.equals(pd.Series(idx3)) + + +class TestDatetimeIndexEquals(EqualsTests): + @pytest.fixture + def index(self): + """Fixture for creating a DatetimeIndex for use in equality tests.""" + return pd.date_range("2013-01-01", periods=5) + + def test_equals2(self): + # GH#13107 + idx = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"]) + assert idx.equals(idx) + assert idx.equals(idx.copy()) + assert idx.equals(idx.astype(object)) + assert idx.astype(object).equals(idx) + assert idx.astype(object).equals(idx.astype(object)) + assert not idx.equals(list(idx)) + assert not idx.equals(pd.Series(idx)) + + idx2 = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"], tz="US/Pacific") + assert not idx.equals(idx2) + assert not idx.equals(idx2.copy()) + assert not idx.equals(idx2.astype(object)) + assert not idx.astype(object).equals(idx2) + assert not idx.equals(list(idx2)) + assert not idx.equals(pd.Series(idx2)) + + # same internal, different tz + idx3 = pd.DatetimeIndex(idx.asi8, tz="US/Pacific") + tm.assert_numpy_array_equal(idx.asi8, idx3.asi8) + assert not idx.equals(idx3) + assert not idx.equals(idx3.copy()) + assert not idx.equals(idx3.astype(object)) + assert not idx.astype(object).equals(idx3) + assert not idx.equals(list(idx3)) + assert not idx.equals(pd.Series(idx3)) + + # check that we do not raise when comparing with OutOfBounds objects + oob = pd.Index([datetime(2500, 1, 1)] * 3, dtype=object) + assert not idx.equals(oob) + assert not idx2.equals(oob) + assert not idx3.equals(oob) + + # check that we do not raise when comparing with OutOfBounds dt64 + oob2 = oob.map(np.datetime64) + assert not idx.equals(oob2) + assert not idx2.equals(oob2) + assert not idx3.equals(oob2) + + @pytest.mark.parametrize("freq", ["B", "C"]) + def test_not_equals_bday(self, freq): + rng = pd.date_range("2009-01-01", "2010-01-01", freq=freq) + assert not rng.equals(list(rng)) + + +class TestTimedeltaIndexEquals(EqualsTests): + @pytest.fixture + def index(self): + """Fixture for creating a TimedeltaIndex for use in equality tests.""" + return pd.timedelta_range("1 day", periods=10) + + def test_equals2(self): + # GH#13107 + idx = pd.TimedeltaIndex(["1 days", "2 days", "NaT"]) + assert idx.equals(idx) + assert idx.equals(idx.copy()) + assert idx.equals(idx.astype(object)) + assert idx.astype(object).equals(idx) + assert idx.astype(object).equals(idx.astype(object)) + assert not idx.equals(list(idx)) + assert not idx.equals(pd.Series(idx)) + + idx2 = pd.TimedeltaIndex(["2 days", "1 days", "NaT"]) + assert not idx.equals(idx2) + assert not idx.equals(idx2.copy()) + assert not idx.equals(idx2.astype(object)) + assert not idx.astype(object).equals(idx2) + assert not idx.astype(object).equals(idx2.astype(object)) + assert not idx.equals(list(idx2)) + assert not idx.equals(pd.Series(idx2)) + + # Check that we dont raise OverflowError on comparisons outside the + # implementation range GH#28532 + oob = pd.Index([timedelta(days=10**6)] * 3, dtype=object) + assert not idx.equals(oob) + assert not idx2.equals(oob) + + oob2 = pd.Index([np.timedelta64(x) for x in oob], dtype=object) + assert (oob == oob2).all() + assert not idx.equals(oob2) + assert not idx2.equals(oob2) + + oob3 = oob.map(np.timedelta64) + assert (oob3 == oob).all() + assert not idx.equals(oob3) + assert not idx2.equals(oob3) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab168bcf3aab825b5870f71db9311ee686fa8e0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.py @@ -0,0 +1,41 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + +dtlike_dtypes = [ + np.dtype("timedelta64[ns]"), + np.dtype("datetime64[ns]"), + pd.DatetimeTZDtype("ns", "Asia/Tokyo"), + pd.PeriodDtype("ns"), +] + + +@pytest.mark.parametrize("ldtype", dtlike_dtypes) +@pytest.mark.parametrize("rdtype", dtlike_dtypes) +def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype): + vals = np.tile(3600 * 10**9 * np.arange(3, dtype=np.int64), 2) + + def construct(dtype): + if dtype is dtlike_dtypes[-1]: + # PeriodArray will try to cast ints to strings + return pd.DatetimeIndex(vals).astype(dtype) + return pd.Index(vals, dtype=dtype) + + left = construct(ldtype) + right = construct(rdtype) + + result = left.get_indexer_non_unique(right) + + if ldtype is rdtype: + ex1 = np.array([0, 3, 1, 4, 2, 5] * 2, dtype=np.intp) + ex2 = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(result[0], ex1) + tm.assert_numpy_array_equal(result[1], ex2) + + else: + no_matches = np.array([-1] * 6, dtype=np.intp) + missing = np.arange(6, dtype=np.intp) + tm.assert_numpy_array_equal(result[0], no_matches) + tm.assert_numpy_array_equal(result[1], missing) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.py new file mode 100644 index 0000000000000000000000000000000000000000..b3d551c6610c1496daf7c4020118be1d3befd00b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.py @@ -0,0 +1,42 @@ +import pandas as pd + + +def test_is_monotonic_with_nat(): + # GH#31437 + # PeriodIndex.is_monotonic_increasing should behave analogously to DatetimeIndex, + # in particular never be monotonic when we have NaT + dti = pd.date_range("2016-01-01", periods=3) + pi = dti.to_period("D") + tdi = pd.Index(dti.view("timedelta64[ns]")) + + for obj in [pi, pi._engine, dti, dti._engine, tdi, tdi._engine]: + if isinstance(obj, pd.Index): + # i.e. not Engines + assert obj.is_monotonic_increasing + assert obj.is_monotonic_increasing + assert not obj.is_monotonic_decreasing + assert obj.is_unique + + dti1 = dti.insert(0, pd.NaT) + pi1 = dti1.to_period("D") + tdi1 = pd.Index(dti1.view("timedelta64[ns]")) + + for obj in [pi1, pi1._engine, dti1, dti1._engine, tdi1, tdi1._engine]: + if isinstance(obj, pd.Index): + # i.e. not Engines + assert not obj.is_monotonic_increasing + assert not obj.is_monotonic_increasing + assert not obj.is_monotonic_decreasing + assert obj.is_unique + + dti2 = dti.insert(3, pd.NaT) + pi2 = dti2.to_period("h") + tdi2 = pd.Index(dti2.view("timedelta64[ns]")) + + for obj in [pi2, pi2._engine, dti2, dti2._engine, tdi2, tdi2._engine]: + if isinstance(obj, pd.Index): + # i.e. not Engines + assert not obj.is_monotonic_increasing + assert not obj.is_monotonic_increasing + assert not obj.is_monotonic_decreasing + assert obj.is_unique diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_nat.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_nat.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd8fce035b75a8fd6b01c8319f7ddceeb143927 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_nat.py @@ -0,0 +1,37 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize( + "index_without_na", + [ + pd.TimedeltaIndex(["1 days", "2 days"]), + pd.PeriodIndex(["2011-01-01", "2011-01-02"], freq="D"), + pd.DatetimeIndex(["2011-01-01", "2011-01-02"]), + pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz="UTC"), + ], +) +def test_nat(index_without_na): + empty_index = index_without_na[:0] + + index_with_na = index_without_na.copy(deep=True) + index_with_na._data[1] = pd.NaT + + assert empty_index._na_value is pd.NaT + assert index_with_na._na_value is pd.NaT + assert index_without_na._na_value is pd.NaT + + idx = index_without_na + assert idx._can_hold_na + + tm.assert_numpy_array_equal(idx._isnan, np.array([False, False])) + assert idx.hasnans is False + + idx = index_with_na + assert idx._can_hold_na + + tm.assert_numpy_array_equal(idx._isnan, np.array([False, True])) + assert idx.hasnans is True diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.py new file mode 100644 index 0000000000000000000000000000000000000000..589e4d863e4c73b4ebe55c7bb12837aa02392cfe --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.py @@ -0,0 +1,308 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def check_freq_ascending(ordered, orig, ascending): + """ + Check the expected freq on a PeriodIndex/DatetimeIndex/TimedeltaIndex + when the original index is generated (or generate-able) with + period_range/date_range/timedelta_range. + """ + if isinstance(ordered, pd.PeriodIndex): + assert ordered.freq == orig.freq + elif isinstance(ordered, (pd.DatetimeIndex, pd.TimedeltaIndex)): + if ascending: + assert ordered.freq.n == orig.freq.n + else: + assert ordered.freq.n == -1 * orig.freq.n + + +def check_freq_nonmonotonic(ordered, orig): + """ + Check the expected freq on a PeriodIndex/DatetimeIndex/TimedeltaIndex + when the original index is _not_ generated (or generate-able) with + period_range/date_range//timedelta_range. + """ + if isinstance(ordered, pd.PeriodIndex): + assert ordered.freq == orig.freq + elif isinstance(ordered, (pd.DatetimeIndex, pd.TimedeltaIndex)): + assert ordered.freq is None + + +class TestSortValues: + @pytest.fixture(params=[pd.DatetimeIndex, pd.TimedeltaIndex, pd.PeriodIndex]) + def non_monotonic_idx(self, request): + if request.param is pd.DatetimeIndex: + return pd.DatetimeIndex(["2000-01-04", "2000-01-01", "2000-01-02"]) + elif request.param is pd.PeriodIndex: + dti = pd.DatetimeIndex(["2000-01-04", "2000-01-01", "2000-01-02"]) + return dti.to_period("D") + else: + return pd.TimedeltaIndex( + ["1 day 00:00:05", "1 day 00:00:01", "1 day 00:00:02"] + ) + + def test_argmin_argmax(self, non_monotonic_idx): + assert non_monotonic_idx.argmin() == 1 + assert non_monotonic_idx.argmax() == 0 + + def test_sort_values(self, non_monotonic_idx): + idx = non_monotonic_idx + ordered = idx.sort_values() + assert ordered.is_monotonic_increasing + ordered = idx.sort_values(ascending=False) + assert ordered[::-1].is_monotonic_increasing + + ordered, dexer = idx.sort_values(return_indexer=True) + assert ordered.is_monotonic_increasing + tm.assert_numpy_array_equal(dexer, np.array([1, 2, 0], dtype=np.intp)) + + ordered, dexer = idx.sort_values(return_indexer=True, ascending=False) + assert ordered[::-1].is_monotonic_increasing + tm.assert_numpy_array_equal(dexer, np.array([0, 2, 1], dtype=np.intp)) + + def check_sort_values_with_freq(self, idx): + ordered = idx.sort_values() + tm.assert_index_equal(ordered, idx) + check_freq_ascending(ordered, idx, True) + + ordered = idx.sort_values(ascending=False) + expected = idx[::-1] + tm.assert_index_equal(ordered, expected) + check_freq_ascending(ordered, idx, False) + + ordered, indexer = idx.sort_values(return_indexer=True) + tm.assert_index_equal(ordered, idx) + tm.assert_numpy_array_equal(indexer, np.array([0, 1, 2], dtype=np.intp)) + check_freq_ascending(ordered, idx, True) + + ordered, indexer = idx.sort_values(return_indexer=True, ascending=False) + expected = idx[::-1] + tm.assert_index_equal(ordered, expected) + tm.assert_numpy_array_equal(indexer, np.array([2, 1, 0], dtype=np.intp)) + check_freq_ascending(ordered, idx, False) + + @pytest.mark.parametrize("freq", ["D", "h"]) + def test_sort_values_with_freq_timedeltaindex(self, freq): + # GH#10295 + idx = pd.timedelta_range(start=f"1{freq}", periods=3, freq=freq).rename("idx") + + self.check_sort_values_with_freq(idx) + + @pytest.mark.parametrize( + "idx", + [ + pd.DatetimeIndex( + ["2011-01-01", "2011-01-02", "2011-01-03"], freq="D", name="idx" + ), + pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], + freq="h", + name="tzidx", + tz="Asia/Tokyo", + ), + ], + ) + def test_sort_values_with_freq_datetimeindex(self, idx): + self.check_sort_values_with_freq(idx) + + @pytest.mark.parametrize("freq", ["D", "2D", "4D"]) + def test_sort_values_with_freq_periodindex(self, freq): + # here with_freq refers to being period_range-like + idx = pd.PeriodIndex( + ["2011-01-01", "2011-01-02", "2011-01-03"], freq=freq, name="idx" + ) + self.check_sort_values_with_freq(idx) + + @pytest.mark.parametrize( + "idx", + [ + pd.PeriodIndex(["2011", "2012", "2013"], name="pidx", freq="Y"), + pd.Index([2011, 2012, 2013], name="idx"), # for compatibility check + ], + ) + def test_sort_values_with_freq_periodindex2(self, idx): + # here with_freq indicates this is period_range-like + self.check_sort_values_with_freq(idx) + + def check_sort_values_without_freq(self, idx, expected): + ordered = idx.sort_values(na_position="first") + tm.assert_index_equal(ordered, expected) + check_freq_nonmonotonic(ordered, idx) + + if not idx.isna().any(): + ordered = idx.sort_values() + tm.assert_index_equal(ordered, expected) + check_freq_nonmonotonic(ordered, idx) + + ordered = idx.sort_values(ascending=False) + tm.assert_index_equal(ordered, expected[::-1]) + check_freq_nonmonotonic(ordered, idx) + + ordered, indexer = idx.sort_values(return_indexer=True, na_position="first") + tm.assert_index_equal(ordered, expected) + + exp = np.array([0, 4, 3, 1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, exp) + check_freq_nonmonotonic(ordered, idx) + + if not idx.isna().any(): + ordered, indexer = idx.sort_values(return_indexer=True) + tm.assert_index_equal(ordered, expected) + + exp = np.array([0, 4, 3, 1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, exp) + check_freq_nonmonotonic(ordered, idx) + + ordered, indexer = idx.sort_values(return_indexer=True, ascending=False) + tm.assert_index_equal(ordered, expected[::-1]) + + exp = np.array([2, 1, 3, 0, 4], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, exp) + check_freq_nonmonotonic(ordered, idx) + + def test_sort_values_without_freq_timedeltaindex(self): + # GH#10295 + + idx = pd.TimedeltaIndex( + ["1 hour", "3 hour", "5 hour", "2 hour ", "1 hour"], name="idx1" + ) + expected = pd.TimedeltaIndex( + ["1 hour", "1 hour", "2 hour", "3 hour", "5 hour"], name="idx1" + ) + self.check_sort_values_without_freq(idx, expected) + + @pytest.mark.parametrize( + "index_dates,expected_dates", + [ + ( + ["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01"], + ["2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05"], + ), + ( + [pd.NaT, "2011-01-03", "2011-01-05", "2011-01-02", pd.NaT], + [pd.NaT, pd.NaT, "2011-01-02", "2011-01-03", "2011-01-05"], + ), + ], + ) + def test_sort_values_without_freq_datetimeindex( + self, index_dates, expected_dates, tz_naive_fixture + ): + tz = tz_naive_fixture + + # without freq + idx = pd.DatetimeIndex(index_dates, tz=tz, name="idx") + expected = pd.DatetimeIndex(expected_dates, tz=tz, name="idx") + + self.check_sort_values_without_freq(idx, expected) + + @pytest.mark.parametrize( + "idx,expected", + [ + ( + pd.PeriodIndex( + [ + "2011-01-01", + "2011-01-03", + "2011-01-05", + "2011-01-02", + "2011-01-01", + ], + freq="D", + name="idx1", + ), + pd.PeriodIndex( + [ + "2011-01-01", + "2011-01-01", + "2011-01-02", + "2011-01-03", + "2011-01-05", + ], + freq="D", + name="idx1", + ), + ), + ( + pd.PeriodIndex( + [ + "2011-01-01", + "2011-01-03", + "2011-01-05", + "2011-01-02", + "2011-01-01", + ], + freq="D", + name="idx2", + ), + pd.PeriodIndex( + [ + "2011-01-01", + "2011-01-01", + "2011-01-02", + "2011-01-03", + "2011-01-05", + ], + freq="D", + name="idx2", + ), + ), + ( + pd.PeriodIndex( + [pd.NaT, "2011-01-03", "2011-01-05", "2011-01-02", pd.NaT], + freq="D", + name="idx3", + ), + pd.PeriodIndex( + [pd.NaT, pd.NaT, "2011-01-02", "2011-01-03", "2011-01-05"], + freq="D", + name="idx3", + ), + ), + ( + pd.PeriodIndex( + ["2011", "2013", "2015", "2012", "2011"], name="pidx", freq="Y" + ), + pd.PeriodIndex( + ["2011", "2011", "2012", "2013", "2015"], name="pidx", freq="Y" + ), + ), + ( + # For compatibility check + pd.Index([2011, 2013, 2015, 2012, 2011], name="idx"), + pd.Index([2011, 2011, 2012, 2013, 2015], name="idx"), + ), + ], + ) + def test_sort_values_without_freq_periodindex(self, idx, expected): + # here without_freq means not generateable by period_range + self.check_sort_values_without_freq(idx, expected) + + def test_sort_values_without_freq_periodindex_nat(self): + # doesn't quite fit into check_sort_values_without_freq + idx = pd.PeriodIndex(["2011", "2013", "NaT", "2011"], name="pidx", freq="D") + expected = pd.PeriodIndex( + ["NaT", "2011", "2011", "2013"], name="pidx", freq="D" + ) + + ordered = idx.sort_values(na_position="first") + tm.assert_index_equal(ordered, expected) + check_freq_nonmonotonic(ordered, idx) + + ordered = idx.sort_values(ascending=False) + tm.assert_index_equal(ordered, expected[::-1]) + check_freq_nonmonotonic(ordered, idx) + + +def test_order_stability_compat(): + # GH#35922. sort_values is stable both for normal and datetime-like Index + pidx = pd.PeriodIndex( + ["2011", "2013", "2015", "2012", "2011"], name="pidx", freq="Y" + ) + iidx = pd.Index([2011, 2013, 2015, 2012, 2011], name="idx") + ordered1, indexer1 = pidx.sort_values(return_indexer=True, ascending=False) + ordered2, indexer2 = iidx.sort_values(return_indexer=True, ascending=False) + tm.assert_numpy_array_equal(indexer1, indexer2) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.py new file mode 100644 index 0000000000000000000000000000000000000000..73f60e103298997110682cc26d9cf0a70fcdf137 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.py @@ -0,0 +1,96 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestValueCounts: + # GH#7735 + + def test_value_counts_unique_datetimeindex(self, tz_naive_fixture): + tz = tz_naive_fixture + orig = pd.date_range("2011-01-01 09:00", freq="h", periods=10, tz=tz) + self._check_value_counts_with_repeats(orig) + + def test_value_counts_unique_timedeltaindex(self): + orig = pd.timedelta_range("1 days 09:00:00", freq="h", periods=10) + self._check_value_counts_with_repeats(orig) + + def test_value_counts_unique_periodindex(self): + orig = pd.period_range("2011-01-01 09:00", freq="h", periods=10) + self._check_value_counts_with_repeats(orig) + + def _check_value_counts_with_repeats(self, orig): + # create repeated values, 'n'th element is repeated by n+1 times + idx = type(orig)( + np.repeat(orig._values, range(1, len(orig) + 1)), dtype=orig.dtype + ) + + exp_idx = orig[::-1] + if not isinstance(exp_idx, pd.PeriodIndex): + exp_idx = exp_idx._with_freq(None) + expected = pd.Series( + range(10, 0, -1), index=exp_idx, dtype="int64", name="count" + ) + + for obj in [idx, pd.Series(idx)]: + tm.assert_series_equal(obj.value_counts(), expected) + + tm.assert_index_equal(idx.unique(), orig, check_freq=False) + + def test_value_counts_unique_datetimeindex2(self, tz_naive_fixture): + tz = tz_naive_fixture + idx = pd.DatetimeIndex( + [ + "2013-01-01 09:00", + "2013-01-01 09:00", + "2013-01-01 09:00", + "2013-01-01 08:00", + "2013-01-01 08:00", + pd.NaT, + ], + tz=tz, + ) + self._check_value_counts_dropna(idx) + + def test_value_counts_unique_timedeltaindex2(self): + idx = pd.TimedeltaIndex( + [ + "1 days 09:00:00", + "1 days 09:00:00", + "1 days 09:00:00", + "1 days 08:00:00", + "1 days 08:00:00", + pd.NaT, + ] + ) + self._check_value_counts_dropna(idx) + + def test_value_counts_unique_periodindex2(self): + idx = pd.PeriodIndex( + [ + "2013-01-01 09:00", + "2013-01-01 09:00", + "2013-01-01 09:00", + "2013-01-01 08:00", + "2013-01-01 08:00", + pd.NaT, + ], + freq="h", + ) + self._check_value_counts_dropna(idx) + + def _check_value_counts_dropna(self, idx): + exp_idx = idx[[2, 3]] + expected = pd.Series([3, 2], index=exp_idx, name="count") + + for obj in [idx, pd.Series(idx)]: + tm.assert_series_equal(obj.value_counts(), expected) + + exp_idx = idx[[2, 3, -1]] + expected = pd.Series([3, 2, 1], index=exp_idx, name="count") + + for obj in [idx, pd.Series(idx)]: + tm.assert_series_equal(obj.value_counts(dropna=False), expected) + + tm.assert_index_equal(idx.unique(), exp_idx) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_asof.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_asof.py new file mode 100644 index 0000000000000000000000000000000000000000..a9172cd4a66dccb244d7e2ce96ae3eaa8741cd29 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_asof.py @@ -0,0 +1,40 @@ +from datetime import timedelta + +import pandas as pd + + +class TestAsOf: + def test_asof_partial(self): + index = pd.date_range("2010-01-01", periods=2, freq="ME") + expected = pd.Timestamp("2010-02-28") + result = index.asof("2010-02") + assert result == expected + assert not isinstance(result, pd.Index) + + def test_asof(self): + index = pd.date_range("2020-01-01", periods=10) + + dt = index[0] + assert index.asof(dt) == dt + assert pd.isna(index.asof(dt - timedelta(1))) + + dt = index[-1] + assert index.asof(dt + timedelta(1)) == dt + + dt = index[0].to_pydatetime() + assert isinstance(index.asof(dt), pd.Timestamp) + + def test_asof_datetime_string(self): + # GH#50946 + + dti = pd.date_range("2021-08-05", "2021-08-10", freq="1D") + + key = "2021-08-09" + res = dti.asof(key) + exp = dti[4] + assert res == exp + + # add a non-midnight time caused a bug + dti2 = pd.DatetimeIndex([*list(dti), "2021-08-11 00:00:01"]) + res = dti2.asof(key) + assert res == exp diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_astype.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..f9cc6cc6ec330d052f7709b853e50c62c3d68b23 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_astype.py @@ -0,0 +1,337 @@ +from datetime import datetime + +import dateutil +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndex: + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_dti_astype_asobject_around_dst_transition(self, tzstr): + # GH#1345 + + # dates around a dst transition + rng = pd.date_range("2/13/2010", "5/6/2010", tz=tzstr) + + objs = rng.astype(object) + for i, x in enumerate(objs): + exval = rng[i] + assert x == exval + assert x.tzinfo == exval.tzinfo + + objs = rng.astype(object) + for i, x in enumerate(objs): + exval = rng[i] + assert x == exval + assert x.tzinfo == exval.tzinfo + + def test_astype(self): + # GH 13149, GH 13209 + idx = pd.DatetimeIndex( + ["2016-05-16", "NaT", pd.NaT, np.nan], dtype="M8[ns]", name="idx" + ) + + result = idx.astype(object) + expected = pd.Index( + [pd.Timestamp("2016-05-16")] + [pd.NaT] * 3, dtype=object, name="idx" + ) + tm.assert_index_equal(result, expected) + + result = idx.astype(np.int64) + expected = pd.Index( + [1463356800000000000] + [-9223372036854775808] * 3, + dtype=np.int64, + name="idx", + ) + tm.assert_index_equal(result, expected) + + def test_astype2(self): + rng = pd.date_range("1/1/2000", periods=10, name="idx") + result = rng.astype("i8") + tm.assert_index_equal(result, pd.Index(rng.asi8, name="idx")) + tm.assert_numpy_array_equal(result.values, rng.asi8) + + def test_astype_uint(self): + arr = pd.date_range("2000", periods=2, name="idx") + + with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"): + arr.astype("uint64") + with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"): + arr.astype("uint32") + + def test_astype_with_tz(self): + # with tz + rng = pd.date_range("1/1/2000", periods=10, tz="US/Eastern") + msg = "Cannot use .astype to convert from timezone-aware" + with pytest.raises(TypeError, match=msg): + # deprecated + rng.astype("datetime64[ns]") + with pytest.raises(TypeError, match=msg): + # check DatetimeArray while we're here deprecated + rng._data.astype("datetime64[ns]") + + def test_astype_tzaware_to_tzaware(self): + # GH 18951: tz-aware to tz-aware + idx = pd.date_range("20170101", periods=4, tz="US/Pacific", unit="ns") + result = idx.astype("datetime64[ns, US/Eastern]") + expected = pd.date_range( + "20170101 03:00:00", periods=4, tz="US/Eastern", unit="ns" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + def test_astype_tznaive_to_tzaware(self): + # GH 18951: tz-naive to tz-aware + idx = pd.date_range("20170101", periods=4) + idx = idx._with_freq(None) # tz_localize does not preserve freq + msg = "Cannot use .astype to convert from timezone-naive" + with pytest.raises(TypeError, match=msg): + # dt64->dt64tz deprecated + idx.astype("datetime64[ns, US/Eastern]") + with pytest.raises(TypeError, match=msg): + # dt64->dt64tz deprecated + idx._data.astype("datetime64[ns, US/Eastern]") + + def test_astype_str_nat(self, using_infer_string): + # GH 13149, GH 13209 + # verify that we are returning NaT as a string (and not unicode) + + idx = pd.DatetimeIndex(["2016-05-16", "NaT", pd.NaT, np.nan]) + result = idx.astype(str) + if using_infer_string: + expected = pd.Index(["2016-05-16", None, None, None], dtype="str") + else: + expected = pd.Index(["2016-05-16", "NaT", "NaT", "NaT"], dtype=object) + tm.assert_index_equal(result, expected) + + def test_astype_str(self): + # test astype string - #10442 + dti = pd.date_range("2012-01-01", periods=4, name="test_name") + result = dti.astype(str) + expected = pd.Index( + ["2012-01-01", "2012-01-02", "2012-01-03", "2012-01-04"], + name="test_name", + dtype="str", + ) + tm.assert_index_equal(result, expected) + + def test_astype_str_tz_and_name(self): + # test astype string with tz and name + dti = pd.date_range("2012-01-01", periods=3, name="test_name", tz="US/Eastern") + result = dti.astype(str) + expected = pd.Index( + [ + "2012-01-01 00:00:00-05:00", + "2012-01-02 00:00:00-05:00", + "2012-01-03 00:00:00-05:00", + ], + name="test_name", + dtype="str", + ) + tm.assert_index_equal(result, expected) + + def test_astype_str_freq_and_name(self): + # test astype string with freqH and name + dti = pd.date_range("1/1/2011", periods=3, freq="h", name="test_name") + result = dti.astype(str) + expected = pd.Index( + ["2011-01-01 00:00:00", "2011-01-01 01:00:00", "2011-01-01 02:00:00"], + name="test_name", + dtype="str", + ) + tm.assert_index_equal(result, expected) + + def test_astype_str_freq_and_tz(self): + # test astype string with freqH and timezone + dti = pd.date_range( + "3/6/2012 00:00", periods=2, freq="h", tz="Europe/London", name="test_name" + ) + result = dti.astype(str) + expected = pd.Index( + ["2012-03-06 00:00:00+00:00", "2012-03-06 01:00:00+00:00"], + dtype="str", + name="test_name", + ) + tm.assert_index_equal(result, expected) + + def test_astype_datetime64(self): + # GH 13149, GH 13209 + idx = pd.DatetimeIndex( + ["2016-05-16", "NaT", pd.NaT, np.nan], dtype="M8[ns]", name="idx" + ) + + result = idx.astype("datetime64[ns]") + tm.assert_index_equal(result, idx) + assert result is not idx + + result = idx.astype("datetime64[ns]", copy=False) + tm.assert_index_equal(result, idx) + assert result is idx + + idx_tz = pd.DatetimeIndex( + ["2016-05-16", "NaT", pd.NaT, np.nan], tz="EST", name="idx" + ) + msg = "Cannot use .astype to convert from timezone-aware" + with pytest.raises(TypeError, match=msg): + # dt64tz->dt64 deprecated + result = idx_tz.astype("datetime64[ns]") + + def test_astype_object(self): + rng = pd.date_range("1/1/2000", periods=20) + + casted = rng.astype("O") + exp_values = list(rng) + + tm.assert_index_equal(casted, pd.Index(exp_values, dtype=np.object_)) + assert casted.tolist() == exp_values + + @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"]) + def test_astype_object_tz(self, tz): + idx = pd.date_range(start="2013-01-01", periods=4, freq="ME", name="idx", tz=tz) + expected_list = [ + pd.Timestamp("2013-01-31", tz=tz), + pd.Timestamp("2013-02-28", tz=tz), + pd.Timestamp("2013-03-31", tz=tz), + pd.Timestamp("2013-04-30", tz=tz), + ] + expected = pd.Index(expected_list, dtype=object, name="idx") + result = idx.astype(object) + tm.assert_index_equal(result, expected) + assert idx.tolist() == expected_list + + def test_astype_object_with_nat(self): + idx = pd.DatetimeIndex( + [datetime(2013, 1, 1), datetime(2013, 1, 2), pd.NaT, datetime(2013, 1, 4)], + name="idx", + ) + expected_list = [ + pd.Timestamp("2013-01-01"), + pd.Timestamp("2013-01-02"), + pd.NaT, + pd.Timestamp("2013-01-04"), + ] + expected = pd.Index(expected_list, dtype=object, name="idx") + result = idx.astype(object) + tm.assert_index_equal(result, expected) + assert idx.tolist() == expected_list + + @pytest.mark.parametrize( + "dtype", + [float, "timedelta64", "timedelta64[ns]", "datetime64", "datetime64[D]"], + ) + def test_astype_raises(self, dtype): + # GH 13149, GH 13209 + idx = pd.DatetimeIndex(["2016-05-16", "NaT", pd.NaT, np.nan]) + msg = "Cannot cast DatetimeIndex to dtype" + if dtype == "datetime64": + msg = "Casting to unit-less dtype 'datetime64' is not supported" + with pytest.raises(TypeError, match=msg): + idx.astype(dtype) + + def test_index_convert_to_datetime_array(self): + def _check_rng(rng): + converted = rng.to_pydatetime() + assert isinstance(converted, np.ndarray) + for x, stamp in zip(converted, rng, strict=True): + assert isinstance(x, datetime) + assert x == stamp.to_pydatetime() + assert x.tzinfo == stamp.tzinfo + + rng = pd.date_range("20090415", "20090519") + rng_eastern = pd.date_range("20090415", "20090519", tz="US/Eastern") + rng_utc = pd.date_range("20090415", "20090519", tz="utc") + + _check_rng(rng) + _check_rng(rng_eastern) + _check_rng(rng_utc) + + def test_index_convert_to_datetime_array_explicit_pytz(self): + pytz = pytest.importorskip("pytz") + + def _check_rng(rng): + converted = rng.to_pydatetime() + assert isinstance(converted, np.ndarray) + for x, stamp in zip(converted, rng, strict=True): + assert isinstance(x, datetime) + assert x == stamp.to_pydatetime() + assert x.tzinfo == stamp.tzinfo + + rng = pd.date_range("20090415", "20090519") + rng_eastern = pd.date_range( + "20090415", "20090519", tz=pytz.timezone("US/Eastern") + ) + rng_utc = pd.date_range("20090415", "20090519", tz=pytz.utc) + + _check_rng(rng) + _check_rng(rng_eastern) + _check_rng(rng_utc) + + def test_index_convert_to_datetime_array_dateutil(self): + def _check_rng(rng): + converted = rng.to_pydatetime() + assert isinstance(converted, np.ndarray) + for x, stamp in zip(converted, rng, strict=True): + assert isinstance(x, datetime) + assert x == stamp.to_pydatetime() + assert x.tzinfo == stamp.tzinfo + + rng = pd.date_range("20090415", "20090519") + rng_eastern = pd.date_range("20090415", "20090519", tz="dateutil/US/Eastern") + rng_utc = pd.date_range("20090415", "20090519", tz=dateutil.tz.tzutc()) + + _check_rng(rng) + _check_rng(rng_eastern) + _check_rng(rng_utc) + + @pytest.mark.parametrize( + "tz, dtype", + [["US/Pacific", "datetime64[ns, US/Pacific]"], [None, "datetime64[ns]"]], + ) + def test_integer_index_astype_datetime(self, tz, dtype): + # GH 20997, 20964, 24559 + val = [pd.Timestamp("2018-01-01", tz=tz).as_unit("ns")._value] + result = pd.Index(val, name="idx").astype(dtype) + expected = pd.DatetimeIndex(["2018-01-01"], tz=tz, name="idx").as_unit("ns") + tm.assert_index_equal(result, expected) + + def test_dti_astype_period(self): + idx = pd.DatetimeIndex([pd.NaT, "2011-01-01", "2011-02-01"], name="idx") + + res = idx.astype("period[M]") + exp = pd.PeriodIndex(["NaT", "2011-01", "2011-02"], freq="M", name="idx") + tm.assert_index_equal(res, exp) + + res = idx.astype("period[3M]") + exp = pd.PeriodIndex(["NaT", "2011-01", "2011-02"], freq="3M", name="idx") + tm.assert_index_equal(res, exp) + + +class TestAstype: + @pytest.mark.parametrize("tz", [None, "US/Central"]) + def test_astype_category(self, tz): + obj = pd.date_range("2000", periods=2, tz=tz, name="idx", unit="ns") + result = obj.astype("category") + dti = pd.DatetimeIndex(["2000-01-01", "2000-01-02"], tz=tz).as_unit("ns") + expected = pd.CategoricalIndex( + dti, + name="idx", + ) + tm.assert_index_equal(result, expected, check_freq=False) + + result = obj._data.astype("category") + expected = expected.values + tm.assert_categorical_equal(result, expected, check_freq=False) + + @pytest.mark.parametrize("tz", [None, "US/Central"]) + def test_astype_array_fallback(self, tz): + obj = pd.date_range("2000", periods=2, tz=tz, name="idx") + result = obj.astype(bool) + expected = pd.Index(np.array([True, True]), name="idx") + tm.assert_index_equal(result, expected) + + result = obj._data.astype(bool) + expected = np.array([True, True]) + tm.assert_numpy_array_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_delete.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..185417ad90dc299e89cbeb63f9ef6f36bbe0caa3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_delete.py @@ -0,0 +1,111 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDelete: + def test_delete(self, unit): + idx = pd.date_range( + start="2000-01-01", periods=5, freq="ME", name="idx", unit=unit + ) + + # preserve freq + expected_0 = pd.date_range( + start="2000-02-01", periods=4, freq="ME", name="idx", unit=unit + ) + expected_4 = pd.date_range( + start="2000-01-01", periods=4, freq="ME", name="idx", unit=unit + ) + + # reset freq to None + expected_1 = pd.DatetimeIndex( + ["2000-01-31", "2000-03-31", "2000-04-30", "2000-05-31"], + freq=None, + name="idx", + ).as_unit(unit) + + cases = { + 0: expected_0, + -5: expected_0, + -1: expected_4, + 4: expected_4, + 1: expected_1, + } + for n, expected in cases.items(): + result = idx.delete(n) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + + with pytest.raises((IndexError, ValueError), match="out of bounds"): + # either depending on numpy version + idx.delete(5) + + @pytest.mark.parametrize("tz", [None, "Asia/Tokyo", "US/Pacific"]) + def test_delete2(self, tz): + idx = pd.date_range( + start="2000-01-01 09:00", periods=10, freq="h", name="idx", tz=tz + ) + + expected = pd.date_range( + start="2000-01-01 10:00", periods=9, freq="h", name="idx", tz=tz + ) + result = idx.delete(0) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freqstr == "h" + assert result.tz == expected.tz + + expected = pd.date_range( + start="2000-01-01 09:00", periods=9, freq="h", name="idx", tz=tz + ) + result = idx.delete(-1) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freqstr == "h" + assert result.tz == expected.tz + + def test_delete_slice(self, unit): + idx = pd.date_range( + start="2000-01-01", periods=10, freq="D", name="idx", unit=unit + ) + + # preserve freq + expected_0_2 = pd.date_range( + start="2000-01-04", periods=7, freq="D", name="idx", unit=unit + ) + expected_7_9 = pd.date_range( + start="2000-01-01", periods=7, freq="D", name="idx", unit=unit + ) + + # reset freq to None + expected_3_5 = pd.DatetimeIndex( + [ + "2000-01-01", + "2000-01-02", + "2000-01-03", + "2000-01-07", + "2000-01-08", + "2000-01-09", + "2000-01-10", + ], + freq=None, + name="idx", + ).as_unit(unit) + + cases = { + (0, 1, 2): expected_0_2, + (7, 8, 9): expected_7_9, + (3, 4, 5): expected_3_5, + } + for n, expected in cases.items(): + result = idx.delete(n) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + + result = idx.delete(slice(n[0], n[-1] + 1)) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_factorize.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_factorize.py new file mode 100644 index 0000000000000000000000000000000000000000..c243e7ff957a4c2f4ac6824ccd7efb6ea497dc1b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_factorize.py @@ -0,0 +1,138 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndexFactorize: + def test_factorize(self): + idx1 = pd.DatetimeIndex( + ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"] + ) + + exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) + exp_idx = pd.DatetimeIndex(["2014-01", "2014-02", "2014-03"]) + + arr, idx = idx1.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + arr, idx = idx1.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + # tz must be preserved + idx1 = idx1.tz_localize("Asia/Tokyo") + exp_idx = exp_idx.tz_localize("Asia/Tokyo") + + arr, idx = idx1.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + idx2 = pd.DatetimeIndex( + ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"] + ) + + exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp) + exp_idx = pd.DatetimeIndex(["2014-01", "2014-02", "2014-03"]) + arr, idx = idx2.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp) + exp_idx = pd.DatetimeIndex(["2014-03", "2014-02", "2014-01"]) + arr, idx = idx2.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + @pytest.mark.parametrize("tz", [None, "US/Pacific"]) + def test_factorize_monotonic_decreasing_no_freq(self, tz): + # GH#66046 fastpath for a monotonic decreasing index without a freq + idx = pd.DatetimeIndex(["2014-03", "2014-03", "2014-02", "2014-01"], tz=tz) + assert idx.freq is None + + exp_arr = np.array([0, 0, 1, 2], dtype=np.intp) + exp_idx = pd.DatetimeIndex(["2014-03", "2014-02", "2014-01"], tz=tz) + arr, result_idx = idx.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(result_idx, exp_idx) + + exp_arr = np.array([2, 2, 1, 0], dtype=np.intp) + exp_idx = pd.DatetimeIndex(["2014-01", "2014-02", "2014-03"], tz=tz) + arr, result_idx = idx.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(result_idx, exp_idx) + + def test_factorize_preserves_freq(self): + # GH#38120 freq should be preserved + idx3 = pd.date_range("2000-01", periods=4, freq="ME", tz="Asia/Tokyo") + exp_arr = np.array([0, 1, 2, 3], dtype=np.intp) + + arr, idx = idx3.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, idx3) + assert idx.freq == idx3.freq + + arr, idx = pd.factorize(idx3) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, idx3) + assert idx.freq == idx3.freq + + def test_factorize_tz(self, tz_naive_fixture, index_or_series): + tz = tz_naive_fixture + # GH#13750 + base = pd.date_range("2016-11-05", freq="h", periods=100, tz=tz) + idx = base.repeat(5) + + exp_arr = np.arange(100, dtype=np.intp).repeat(5) + + obj = index_or_series(idx) + + arr, res = obj.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + expected = base._with_freq(None) + tm.assert_index_equal(res, expected) + assert res.freq == expected.freq + + def test_factorize_dst(self, index_or_series): + # GH#13750 + idx = pd.date_range("2016-11-06", freq="h", periods=12, tz="US/Eastern") + obj = index_or_series(idx) + + arr, res = obj.factorize() + tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp)) + tm.assert_index_equal(res, idx, check_freq=False) + if index_or_series is pd.Index: + assert res.freq == idx.freq + + idx = pd.date_range("2016-06-13", freq="h", periods=12, tz="US/Eastern") + obj = index_or_series(idx) + + arr, res = obj.factorize() + tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp)) + tm.assert_index_equal(res, idx, check_freq=False) + if index_or_series is pd.Index: + assert res.freq == idx.freq + + @pytest.mark.parametrize("sort", [True, False]) + def test_factorize_no_freq_non_nano(self, tz_naive_fixture, sort): + # GH#51978 case that does not go through the fastpath based on + # non-None freq + tz = tz_naive_fixture + idx = pd.date_range("2016-11-06", freq="h", periods=5, tz=tz)[[0, 4, 1, 3, 2]] + exp_codes, exp_uniques = idx.factorize(sort=sort) + + res_codes, res_uniques = idx.as_unit("s").factorize(sort=sort) + + tm.assert_numpy_array_equal(res_codes, exp_codes) + tm.assert_index_equal(res_uniques, exp_uniques.as_unit("s")) + + res_codes, res_uniques = idx.as_unit("s").to_series().factorize(sort=sort) + tm.assert_numpy_array_equal(res_codes, exp_codes) + tm.assert_index_equal(res_uniques, exp_uniques.as_unit("s")) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_fillna.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_fillna.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3a9ebe38920497a9a34b22469b7f5371de4159 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_fillna.py @@ -0,0 +1,76 @@ +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndexFillNA: + @pytest.mark.parametrize("tz", ["US/Eastern", "Asia/Tokyo"]) + def test_fillna_datetime64(self, tz): + # GH 11343 + idx = pd.DatetimeIndex(["2011-01-01 09:00", pd.NaT, "2011-01-01 11:00"]) + + exp = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"] + ) + tm.assert_index_equal(idx.fillna(pd.Timestamp("2011-01-01 10:00")), exp) + + # tz mismatch + exp = pd.Index( + [ + pd.Timestamp("2011-01-01 09:00"), + pd.Timestamp("2011-01-01 10:00", tz=tz), + pd.Timestamp("2011-01-01 11:00"), + ], + dtype=object, + ) + # GH#45153 filling with incompatible value (tz-mismatch) is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = idx.fillna(pd.Timestamp("2011-01-01 10:00", tz=tz)) + tm.assert_index_equal(result, exp) + + # object + exp = pd.Index( + [pd.Timestamp("2011-01-01 09:00"), "x", pd.Timestamp("2011-01-01 11:00")], + dtype=object, + ) + # GH#45153 filling with incompatible value is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = idx.fillna("x") + tm.assert_index_equal(result, exp) + + idx = pd.DatetimeIndex(["2011-01-01 09:00", pd.NaT, "2011-01-01 11:00"], tz=tz) + + exp = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], tz=tz + ) + tm.assert_index_equal(idx.fillna(pd.Timestamp("2011-01-01 10:00", tz=tz)), exp) + + exp = pd.Index( + [ + pd.Timestamp("2011-01-01 09:00", tz=tz), + pd.Timestamp("2011-01-01 10:00"), + pd.Timestamp("2011-01-01 11:00", tz=tz), + ], + dtype=object, + ) + # GH#45153 filling tz-aware with tz-naive is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = idx.fillna(pd.Timestamp("2011-01-01 10:00")) + tm.assert_index_equal(result, exp) + + # object + exp = pd.Index( + [ + pd.Timestamp("2011-01-01 09:00", tz=tz), + "x", + pd.Timestamp("2011-01-01 11:00", tz=tz), + ], + dtype=object, + ) + # GH#45153 filling with incompatible value is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = idx.fillna("x") + tm.assert_index_equal(result, exp) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_insert.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_insert.py new file mode 100644 index 0000000000000000000000000000000000000000..d34ca5728b79f45ba1f88a78e8379599a620fcdf --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_insert.py @@ -0,0 +1,274 @@ +from datetime import datetime +import zoneinfo + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestInsert: + @pytest.mark.parametrize( + "null", [None, np.nan, np.datetime64("NaT", "ns"), pd.NaT, pd.NA] + ) + @pytest.mark.parametrize("tz", [None, "UTC", "US/Eastern"]) + def test_insert_nat(self, tz, null): + # GH#16537, GH#18295 (test missing) + + idx = pd.DatetimeIndex(["2017-01-01"], tz=tz) + expected = pd.DatetimeIndex(["NaT", "2017-01-01"], tz=tz) + if tz is not None and isinstance(null, np.datetime64): + expected = pd.Index([null, idx[0]], dtype=object) + + res = idx.insert(0, null) + tm.assert_index_equal(res, expected) + + @pytest.mark.parametrize("tz", [None, "UTC", "US/Eastern"]) + def test_insert_invalid_na(self, tz): + idx = pd.DatetimeIndex(["2017-01-01"], tz=tz) + + item = np.timedelta64("NaT", "ns") + result = idx.insert(0, item) + expected = pd.Index([item, *list(idx)], dtype=object) + tm.assert_index_equal(result, expected) + + def test_insert_empty_preserves_freq(self, tz_naive_fixture): + # GH#33573 + tz = tz_naive_fixture + dti = pd.DatetimeIndex([], tz=tz, freq="D") + item = pd.Timestamp("2017-04-05").tz_localize(tz) + + result = dti.insert(0, item) + assert result.freq == dti.freq + + # But not when we insert an item that doesn't conform to freq + dti = pd.DatetimeIndex([], tz=tz, freq="W-THU") + result = dti.insert(0, item) + assert result.freq is None + + def test_insert(self, unit): + idx = pd.DatetimeIndex( + ["2000-01-04", "2000-01-01", "2000-01-02"], name="idx" + ).as_unit(unit) + + result = idx.insert(2, datetime(2000, 1, 5)) + exp = pd.DatetimeIndex( + ["2000-01-04", "2000-01-01", "2000-01-05", "2000-01-02"], name="idx" + ).as_unit(unit) + tm.assert_index_equal(result, exp) + + # insertion of non-datetime should coerce to object index + result = idx.insert(1, "inserted") + expected = pd.Index( + [ + datetime(2000, 1, 4), + "inserted", + datetime(2000, 1, 1), + datetime(2000, 1, 2), + ], + name="idx", + ) + assert not isinstance(result, pd.DatetimeIndex) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + + def test_insert2(self, unit): + idx = pd.date_range("1/1/2000", periods=3, freq="ME", name="idx", unit=unit) + + # preserve freq + expected_0 = pd.DatetimeIndex( + ["1999-12-31", "2000-01-31", "2000-02-29", "2000-03-31"], + name="idx", + freq="ME", + ).as_unit(unit) + expected_3 = pd.DatetimeIndex( + ["2000-01-31", "2000-02-29", "2000-03-31", "2000-04-30"], + name="idx", + freq="ME", + ).as_unit(unit) + + # reset freq to None + expected_1_nofreq = pd.DatetimeIndex( + ["2000-01-31", "2000-01-31", "2000-02-29", "2000-03-31"], + name="idx", + freq=None, + ).as_unit(unit) + expected_3_nofreq = pd.DatetimeIndex( + ["2000-01-31", "2000-02-29", "2000-03-31", "2000-01-02"], + name="idx", + freq=None, + ).as_unit(unit) + + cases = [ + (0, datetime(1999, 12, 31), expected_0), + (-3, datetime(1999, 12, 31), expected_0), + (3, datetime(2000, 4, 30), expected_3), + (1, datetime(2000, 1, 31), expected_1_nofreq), + (3, datetime(2000, 1, 2), expected_3_nofreq), + ] + + for n, d, expected in cases: + result = idx.insert(n, d) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + + def test_insert3(self, unit): + idx = pd.date_range("1/1/2000", periods=3, freq="ME", name="idx", unit=unit) + + # reset freq to None + result = idx.insert(3, datetime(2000, 1, 2)) + expected = pd.DatetimeIndex( + ["2000-01-31", "2000-02-29", "2000-03-31", "2000-01-02"], + name="idx", + freq=None, + ).as_unit(unit) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq is None + + @pytest.mark.parametrize("tz", ["US/Pacific", "Asia/Singapore"]) + @pytest.mark.parametrize( + "to_ts", + [lambda x: x, lambda x: x.to_pydatetime()], + ids=["Timestamp", "datetime"], + ) + def test_insert4(self, unit, tz, to_ts): + idx = pd.date_range( + "1/1/2000 09:00", periods=6, freq="h", tz=tz, name="idx", unit=unit + ) + # preserve freq + expected = pd.date_range( + "1/1/2000 09:00", periods=7, freq="h", tz=tz, name="idx", unit=unit + ) + tz = zoneinfo.ZoneInfo(tz) + d = to_ts(pd.Timestamp("2000-01-01 15:00", tz=tz)) + result = idx.insert(6, d) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + assert result.tz == expected.tz + + @pytest.mark.parametrize("tz", ["US/Pacific", "Asia/Singapore"]) + @pytest.mark.parametrize( + "to_ts", + [lambda x: x, lambda x: x.to_pydatetime()], + ids=["Timestamp", "datetime"], + ) + def test_insert4_no_freq(self, unit, tz, to_ts): + idx = pd.date_range( + "1/1/2000 09:00", periods=6, freq="h", tz=tz, name="idx", unit=unit + ) + expected = pd.DatetimeIndex( + [ + "2000-01-01 09:00", + "2000-01-01 10:00", + "2000-01-01 11:00", + "2000-01-01 12:00", + "2000-01-01 13:00", + "2000-01-01 14:00", + "2000-01-01 10:00", + ], + name="idx", + tz=tz, + freq=None, + ).as_unit(unit) + # reset freq to None + d = to_ts(pd.Timestamp("2000-01-01 10:00", tz=tz)) + result = idx.insert(6, d) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.tz == expected.tz + assert result.freq is None + + # TODO: also changes DataFrame.__setitem__ with expansion + def test_insert_mismatched_tzawareness(self): + # see GH#7299 + idx = pd.date_range( + "1/1/2000", periods=3, freq="D", tz="Asia/Tokyo", name="idx" + ) + + # mismatched tz-awareness + item = pd.Timestamp("2000-01-04") + result = idx.insert(3, item) + expected = pd.Index( + [*list(idx[:3]), item, *list(idx[3:])], dtype=object, name="idx" + ) + tm.assert_index_equal(result, expected) + + # mismatched tz-awareness + item = datetime(2000, 1, 4) + result = idx.insert(3, item) + expected = pd.Index( + [*list(idx[:3]), item, *list(idx[3:])], dtype=object, name="idx" + ) + tm.assert_index_equal(result, expected) + + # TODO: also changes DataFrame.__setitem__ with expansion + def test_insert_mismatched_tz(self): + # see GH#7299 + # pre-2.0 with mismatched tzs we would cast to object + idx = pd.date_range( + "1/1/2000", periods=3, freq="D", tz="Asia/Tokyo", unit="ns", name="idx" + ) + + # mismatched tz -> cast to object (could reasonably cast to same tz or UTC) + item = pd.Timestamp("2000-01-04", tz="US/Eastern") + result = idx.insert(3, item) + expected = pd.Index( + [*list(idx[:3]), item.tz_convert(idx.tz), *list(idx[3:])], + name="idx", + ) + assert expected.dtype == idx.dtype + tm.assert_index_equal(result, expected) + + item = datetime(2000, 1, 4, tzinfo=zoneinfo.ZoneInfo("US/Eastern")) + result = idx.insert(3, item) + expected = pd.Index( + [*list(idx[:3]), item.astimezone(idx.tzinfo), *list(idx[3:])], + name="idx", + ) + assert expected.dtype == idx.dtype + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "item", [0, np.int64(0), np.float64(0), np.array(0), np.timedelta64(456, "ns")] + ) + def test_insert_mismatched_types_raises(self, tz_aware_fixture, item): + # GH#33703 dont cast these to dt64 + tz = tz_aware_fixture + dti = pd.date_range("2019-11-04", periods=9, freq="-1D", name=9, tz=tz) + + result = dti.insert(1, item) + + if isinstance(item, np.ndarray): + assert item.item() == 0 + expected = pd.Index([dti[0], 0, *list(dti[1:])], dtype=object, name=9) + else: + expected = pd.Index([dti[0], item, *list(dti[1:])], dtype=object, name=9) + + tm.assert_index_equal(result, expected) + + def test_insert_castable_str(self, tz_aware_fixture): + # GH#33703 + tz = tz_aware_fixture + dti = pd.date_range("2019-11-04", periods=3, freq="-1D", name=9, tz=tz) + + value = "2019-11-05" + result = dti.insert(0, value) + + ts = pd.Timestamp(value).tz_localize(tz) + expected = pd.DatetimeIndex([ts, *list(dti)], dtype=dti.dtype, name=9) + tm.assert_index_equal(result, expected, check_freq=False) + + def test_insert_non_castable_str(self, tz_aware_fixture): + # GH#33703 + tz = tz_aware_fixture + dti = pd.date_range("2019-11-04", periods=3, freq="-1D", name=9, tz=tz) + + value = "foo" + result = dti.insert(0, value) + + expected = pd.Index(["foo", *list(dti)], dtype=object, name=9) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_isocalendar.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_isocalendar.py new file mode 100644 index 0000000000000000000000000000000000000000..c1081052c46cbaeb646b9fe35e6830762f7371fc --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_isocalendar.py @@ -0,0 +1,38 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +def test_isocalendar_returns_correct_values_close_to_new_year_with_tz(): + # GH#6538: Check that DatetimeIndex and its TimeStamp elements + # return the same weekofyear accessor close to new year w/ tz + dates = ["2013/12/29", "2013/12/30", "2013/12/31"] + dates = pd.DatetimeIndex(dates, tz="Europe/Brussels") + result = dates.isocalendar() + expected_data_frame = pd.DataFrame( + [[2013, 52, 7], [2014, 1, 1], [2014, 1, 2]], + columns=["year", "week", "day"], + index=dates, + ).astype({"year": "Int32", "week": "UInt32", "day": "UInt32"}) + tm.assert_frame_equal(result, expected_data_frame) + + +def test_dti_timestamp_isocalendar_fields(): + idx = pd.date_range("2020-01-01", periods=10) + expected = tuple(idx.isocalendar().iloc[-1].to_list()) + result = idx[-1].isocalendar() + assert result == expected + + +def test_isocalendar_year_before_year_one(): + # GH#66549 the year column was unsigned, so BC years wrapped, e.g. year -100 + # came out as 4294967196 + dti = pd.DatetimeIndex(np.array(["-0100-03-05", "0001-01-01"], dtype="M8[s]")) + result = dti.isocalendar() + expected = pd.DataFrame( + [[-100, 10, 1], [1, 1, 1]], + columns=["year", "week", "day"], + index=dti, + ).astype({"year": "Int32", "week": "UInt32", "day": "UInt32"}) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_map.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_map.py new file mode 100644 index 0000000000000000000000000000000000000000..e3db3c01aee1ea2ce7ffee424b8663cfcbdf59ef --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_map.py @@ -0,0 +1,55 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestMap: + def test_map(self): + rng = pd.date_range("1/1/2000", periods=10) + + f = lambda x: x.strftime("%Y%m%d") + result = rng.map(f) + exp = pd.Index([f(x) for x in rng]) + tm.assert_index_equal(result, exp) + + def test_map_fallthrough(self, capsys): + # GH#22067, check we don't get warnings about silently ignored errors + dti = pd.date_range("2017-01-01", "2018-01-01", freq="B") + + dti.map(lambda x: pd.Period(year=x.year, month=x.month, freq="M")) + + captured = capsys.readouterr() + assert captured.err == "" + + def test_map_bug_1677(self): + index = pd.DatetimeIndex(["2012-04-25 09:30:00.393000"]) + f = index.asof + + result = index.map(f) + expected = pd.Index([f(index[0])]) + tm.assert_index_equal(result, expected) + + def test_map_tz_aware_to_tz_naive(self): + # GH#57192 a function that strips the tz should give a tz-naive result, + # not silently re-localize back to the original tz + dti = pd.date_range("2024-02-01", "2024-02-03", freq="8h", tz="UTC") + + result = dti.map(lambda ts: ts.normalize().tz_convert(None)) + expected = pd.DatetimeIndex( + [ts.normalize().tz_convert(None) for ts in dti], dtype="M8[us]" + ) + tm.assert_index_equal(result, expected) + assert result.tz is None + + @pytest.mark.parametrize("name", [None, "name"]) + def test_index_map(self, name): + # see GH#20990 + count = 6 + index = pd.date_range("2018-01-01", periods=count, freq="ME", name=name).map( + lambda x: (x.year, x.month) + ) + exp_index = pd.MultiIndex.from_product( + ((2018,), range(1, 7)), names=[name, name] + ) + tm.assert_index_equal(index, exp_index) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_normalize.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..566934954bbefa8de154c4ece9ea63d6b9b813ae --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_normalize.py @@ -0,0 +1,94 @@ +from dateutil.tz import tzlocal +import numpy as np +import pytest + +from pandas.compat import WASM +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +class TestNormalize: + def test_normalize(self): + rng = pd.date_range("1/1/2000 9:30", periods=10, freq="D") + + result = rng.normalize() + expected = pd.date_range("1/1/2000", periods=10, freq="D") + tm.assert_index_equal(result, expected) + + arr_ns = np.array([1380585623454345752, 1380585612343234312]).astype( + "datetime64[ns]" + ) + rng_ns = pd.DatetimeIndex(arr_ns) + rng_ns_normalized = rng_ns.normalize() + + arr_ns = np.array([1380585600000000000, 1380585600000000000]).astype( + "datetime64[ns]" + ) + expected = pd.DatetimeIndex(arr_ns) + tm.assert_index_equal(rng_ns_normalized, expected) + + assert result.is_normalized + assert not rng.is_normalized + + def test_normalize_nat(self): + dti = pd.DatetimeIndex([pd.NaT, pd.Timestamp("2018-01-01 01:00:00")]) + result = dti.normalize() + expected = pd.DatetimeIndex([pd.NaT, pd.Timestamp("2018-01-01")]) + tm.assert_index_equal(result, expected) + + def test_normalize_tz(self): + rng = pd.date_range("1/1/2000 9:30", periods=10, freq="D", tz="US/Eastern") + + result = rng.normalize() # does not preserve freq + expected = pd.date_range("1/1/2000", periods=10, freq="D", tz="US/Eastern") + tm.assert_index_equal(result, expected._with_freq(None), check_freq=False) + + assert result.is_normalized + assert not rng.is_normalized + + rng = pd.date_range("1/1/2000 9:30", periods=10, freq="D", tz="UTC") + + result = rng.normalize() + expected = pd.date_range("1/1/2000", periods=10, freq="D", tz="UTC") + tm.assert_index_equal(result, expected) + + assert result.is_normalized + assert not rng.is_normalized + + rng = pd.date_range("1/1/2000 9:30", periods=10, freq="D", tz=tzlocal()) + result = rng.normalize() # does not preserve freq + expected = pd.date_range("1/1/2000", periods=10, freq="D", tz=tzlocal()) + tm.assert_index_equal(result, expected._with_freq(None), check_freq=False) + + assert result.is_normalized + assert not rng.is_normalized + + @td.skip_if_windows + @pytest.mark.skipif( + WASM, reason="tzset is available only on Unix-like systems, not WASM" + ) + @pytest.mark.parametrize( + "timezone", + [ + "US/Pacific", + "US/Eastern", + "UTC", + "Asia/Kolkata", + "Asia/Shanghai", + "Australia/Canberra", + ], + ) + def test_normalize_tz_local(self, timezone): + # GH#13459 + with tm.set_timezone(timezone): + rng = pd.date_range("1/1/2000 9:30", periods=10, freq="D", tz=tzlocal()) + + result = rng.normalize() + expected = pd.date_range("1/1/2000", periods=10, freq="D", tz=tzlocal()) + expected = expected._with_freq(None) + tm.assert_index_equal(result, expected, check_freq=False) + + assert result.is_normalized + assert not rng.is_normalized diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_repeat.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_repeat.py new file mode 100644 index 0000000000000000000000000000000000000000..303593bebc09bad3e554f7b8aa549c6b24387518 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_repeat.py @@ -0,0 +1,83 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestRepeat: + def test_repeat_range(self, tz_naive_fixture): + rng = pd.date_range("1/1/2000", "1/1/2001") + + result = rng.repeat(5) + assert result.freq is None + assert len(result) == 5 * len(rng) + + def test_repeat_range2(self, tz_naive_fixture, unit): + tz = tz_naive_fixture + index = pd.date_range("2001-01-01", periods=2, freq="D", tz=tz, unit=unit) + exp = pd.DatetimeIndex( + ["2001-01-01", "2001-01-01", "2001-01-02", "2001-01-02"], tz=tz + ).as_unit(unit) + for res in [index.repeat(2), np.repeat(index, 2)]: + tm.assert_index_equal(res, exp) + assert res.freq is None + + def test_repeat_range3(self, tz_naive_fixture, unit): + tz = tz_naive_fixture + index = pd.date_range("2001-01-01", periods=2, freq="2D", tz=tz, unit=unit) + exp = pd.DatetimeIndex( + ["2001-01-01", "2001-01-01", "2001-01-03", "2001-01-03"], tz=tz + ).as_unit(unit) + for res in [index.repeat(2), np.repeat(index, 2)]: + tm.assert_index_equal(res, exp) + assert res.freq is None + + def test_repeat_range4(self, tz_naive_fixture, unit): + tz = tz_naive_fixture + index = pd.DatetimeIndex(["2001-01-01", "NaT", "2003-01-01"], tz=tz).as_unit( + unit + ) + exp = pd.DatetimeIndex( + [ + "2001-01-01", + "2001-01-01", + "2001-01-01", + "NaT", + "NaT", + "NaT", + "2003-01-01", + "2003-01-01", + "2003-01-01", + ], + tz=tz, + ).as_unit(unit) + for res in [index.repeat(3), np.repeat(index, 3)]: + tm.assert_index_equal(res, exp) + assert res.freq is None + + def test_repeat(self, tz_naive_fixture, unit): + tz = tz_naive_fixture + reps = 2 + msg = "the 'axis' parameter is not supported" + + rng = pd.date_range( + start="2016-01-01", periods=2, freq="30Min", tz=tz, unit=unit + ) + + expected_rng = pd.DatetimeIndex( + [ + pd.Timestamp("2016-01-01 00:00:00", tz=tz), + pd.Timestamp("2016-01-01 00:00:00", tz=tz), + pd.Timestamp("2016-01-01 00:30:00", tz=tz), + pd.Timestamp("2016-01-01 00:30:00", tz=tz), + ] + ).as_unit(unit) + + res = rng.repeat(reps) + tm.assert_index_equal(res, expected_rng) + assert res.freq is None + + tm.assert_index_equal(np.repeat(rng, reps), expected_rng) + with pytest.raises(ValueError, match=msg): + np.repeat(rng, reps, axis=1) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_resolution.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..05dd7f40f17d5d112264f09c8d5199491d4b4b4a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_resolution.py @@ -0,0 +1,35 @@ +from dateutil.tz import tzlocal +import pytest + +from pandas.compat import ( + IS64, + WASM, +) + +import pandas as pd + + +@pytest.mark.parametrize( + "freq,expected", + [ + ("YE", "day"), + ("QE", "day"), + ("ME", "day"), + ("D", "day"), + ("h", "hour"), + ("min", "minute"), + ("s", "second"), + ("ms", "millisecond"), + ("us", "microsecond"), + ], +) +@pytest.mark.skipif(WASM, reason="OverflowError received on WASM") +def test_dti_resolution(request, tz_naive_fixture, freq, expected): + tz = tz_naive_fixture + if freq == "YE" and ((not IS64) or WASM) and isinstance(tz, tzlocal): + request.applymarker( + pytest.mark.xfail(reason="OverflowError inside tzlocal past 2038") + ) + + idx = pd.date_range(start="2013-04-01", periods=30, freq=freq, tz=tz) + assert idx.resolution == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_round.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_round.py new file mode 100644 index 0000000000000000000000000000000000000000..114aa22faed3d525a7fdd581e16757a49e07fccc --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_round.py @@ -0,0 +1,257 @@ +import pytest + +from pandas._libs.tslibs import to_offset +from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndexRound: + def test_round_daily(self): + dti = pd.date_range("20130101 09:10:11", periods=5) + result = dti.round("D") + expected = pd.date_range("20130101", periods=5) + tm.assert_index_equal(result, expected, check_freq=False) + + dti = dti.tz_localize("UTC").tz_convert("US/Eastern") + result = dti.round("D") + expected = pd.date_range("20130101", periods=5).tz_localize("US/Eastern") + tm.assert_index_equal(result, expected, check_freq=False) + + result = dti.round("s") + tm.assert_index_equal(result, dti) + + @pytest.mark.parametrize( + "freq, error_msg", + [ + ("YE", " is a non-fixed frequency"), + ("ME", " is a non-fixed frequency"), + ("foobar", "Invalid frequency: foobar"), + ], + ) + def test_round_invalid(self, freq, error_msg): + dti = pd.date_range("20130101 09:10:11", periods=5) + dti = dti.tz_localize("UTC").tz_convert("US/Eastern") + with pytest.raises(ValueError, match=error_msg): + dti.round(freq) + + def test_round(self, tz_naive_fixture, unit): + tz = tz_naive_fixture + rng = pd.date_range( + start="2016-01-01", periods=5, freq="30Min", tz=tz, unit=unit + ) + elt = rng[1] + + expected_rng = pd.DatetimeIndex( + [ + pd.Timestamp("2016-01-01 00:00:00", tz=tz), + pd.Timestamp("2016-01-01 00:00:00", tz=tz), + pd.Timestamp("2016-01-01 01:00:00", tz=tz), + pd.Timestamp("2016-01-01 02:00:00", tz=tz), + pd.Timestamp("2016-01-01 02:00:00", tz=tz), + ] + ).as_unit(unit) + expected_elt = expected_rng[1] + + result = rng.round(freq="h") + tm.assert_index_equal(result, expected_rng) + assert elt.round(freq="h") == expected_elt + + msg = INVALID_FREQ_ERR_MSG + with pytest.raises(ValueError, match=msg): + rng.round(freq="foo") + with pytest.raises(ValueError, match=msg): + elt.round(freq="foo") + + msg = " is a non-fixed frequency" + with pytest.raises(ValueError, match=msg): + rng.round(freq="ME") + with pytest.raises(ValueError, match=msg): + elt.round(freq="ME") + + def test_round2(self, tz_naive_fixture): + tz = tz_naive_fixture + # GH#14440 & GH#15578 + index = pd.DatetimeIndex(["2016-10-17 12:00:00.0015"], tz=tz).as_unit("ns") + result = index.round("ms") + expected = pd.DatetimeIndex(["2016-10-17 12:00:00.002000"], tz=tz).as_unit("ns") + tm.assert_index_equal(result, expected) + + for freq in ["us", "ns"]: + tm.assert_index_equal(index, index.round(freq)) + + def test_round3(self, tz_naive_fixture): + tz = tz_naive_fixture + index = pd.DatetimeIndex(["2016-10-17 12:00:00.00149"], tz=tz).as_unit("ns") + result = index.round("ms") + expected = pd.DatetimeIndex(["2016-10-17 12:00:00.001000"], tz=tz).as_unit("ns") + tm.assert_index_equal(result, expected) + + def test_round4(self, tz_naive_fixture): + index = pd.DatetimeIndex(["2016-10-17 12:00:00.001501031"], dtype="M8[ns]") + result = index.round("10ns") + expected = pd.DatetimeIndex(["2016-10-17 12:00:00.001501030"], dtype="M8[ns]") + tm.assert_index_equal(result, expected) + + ts = "2016-10-17 12:00:00.001501031" + dti = pd.DatetimeIndex([ts], dtype="M8[ns]") + with tm.assert_produces_warning(False): + dti.round("1010ns") + + @pytest.mark.parametrize("method", ["round", "floor", "ceil"]) + @pytest.mark.parametrize( + "unit, freq, freq_unit", + [ + ("s", "700ms", "ms"), + ("s", "2500ms", "ms"), + ("ms", "3us", "us"), + ("us", "300ns", "ns"), + ], + ) + def test_round_freq_not_multiple_of_resolution(self, method, unit, freq, freq_unit): + # GH#67978 freq is neither a multiple nor a divisor of one unit of the + # index resolution, so the result would not be representable. The + # value is deliberately off the freq grid so the second half below is + # not a no-op for any of the parametrizations. + dti = pd.DatetimeIndex(["2020-01-01 00:00:06.500000001"]) + + msg = rf"freq=.* is incompatible with unit={unit}" + with pytest.raises(ValueError, match=msg): + getattr(dti.as_unit(unit), method)(freq) + + finer = dti.as_unit(freq_unit) + result = getattr(finer, method)(freq) + assert not result.equals(finer) + tm.assert_index_equal( + result, getattr(finer.as_unit("ns"), method)(freq).as_unit(freq_unit) + ) + + @pytest.mark.parametrize("method", ["round", "floor", "ceil"]) + @pytest.mark.parametrize("unit, freq", [("s", "250ms"), ("us", "250ns")]) + def test_round_freq_divides_resolution(self, method, unit, freq): + # GH#67978 freq divides one unit of the index resolution evenly, so + # every representable value is already a multiple of freq + dti = pd.DatetimeIndex(["2020-01-01 00:00:06"]).as_unit(unit) + tm.assert_index_equal(getattr(dti, method)(freq), dti) + + def test_no_rounding_occurs(self, tz_naive_fixture): + # GH 21262 + tz = tz_naive_fixture + rng = pd.date_range( + start="2016-01-01", periods=5, freq="2Min", tz=tz, unit="ns" + ) + + expected_rng = pd.DatetimeIndex( + [ + pd.Timestamp("2016-01-01 00:00:00", tz=tz), + pd.Timestamp("2016-01-01 00:02:00", tz=tz), + pd.Timestamp("2016-01-01 00:04:00", tz=tz), + pd.Timestamp("2016-01-01 00:06:00", tz=tz), + pd.Timestamp("2016-01-01 00:08:00", tz=tz), + ] + ).as_unit("ns") + + result = rng.round(freq="2min") + tm.assert_index_equal(result, expected_rng) + + @pytest.mark.parametrize( + "test_input, rounder, freq, expected", + [ + (["2117-01-01 00:00:45"], "floor", "15s", ["2117-01-01 00:00:45"]), + (["2117-01-01 00:00:45"], "ceil", "15s", ["2117-01-01 00:00:45"]), + ( + ["2117-01-01 00:00:45.000000012"], + "floor", + "10ns", + ["2117-01-01 00:00:45.000000010"], + ), + ( + ["1823-01-01 00:00:01.000000012"], + "ceil", + "10ns", + ["1823-01-01 00:00:01.000000020"], + ), + (["1823-01-01 00:00:01"], "floor", "1s", ["1823-01-01 00:00:01"]), + (["1823-01-01 00:00:01"], "ceil", "1s", ["1823-01-01 00:00:01"]), + (["2018-01-01 00:15:00"], "ceil", "15min", ["2018-01-01 00:15:00"]), + (["2018-01-01 00:15:00"], "floor", "15min", ["2018-01-01 00:15:00"]), + (["1823-01-01 03:00:00"], "ceil", "3h", ["1823-01-01 03:00:00"]), + (["1823-01-01 03:00:00"], "floor", "3h", ["1823-01-01 03:00:00"]), + ( + ("NaT", "1823-01-01 00:00:01"), + "floor", + "1s", + ("NaT", "1823-01-01 00:00:01"), + ), + ( + ("NaT", "1823-01-01 00:00:01"), + "ceil", + "1s", + ("NaT", "1823-01-01 00:00:01"), + ), + ], + ) + def test_ceil_floor_edge(self, test_input, rounder, freq, expected): + dt = pd.DatetimeIndex(list(test_input)) + func = getattr(dt, rounder) + result = func(freq) + expected = pd.DatetimeIndex(list(expected)) + assert expected.equals(result) + + @pytest.mark.parametrize( + "start, index_freq, periods", + [("2018-01-01", "12h", 25), ("2018-01-01 0:0:0.124999", "1ns", 1000)], + ) + @pytest.mark.parametrize( + "round_freq", + [ + "2ns", + "3ns", + "4ns", + "5ns", + "6ns", + "7ns", + "250ns", + "500ns", + "750ns", + "1us", + "19us", + "250us", + "500us", + "750us", + "1s", + "2s", + "3s", + "12h", + "1D", + ], + ) + def test_round_int64(self, start, index_freq, periods, round_freq): + dt = pd.date_range(start=start, freq=index_freq, periods=periods, unit="ns") + unit = to_offset(round_freq).nanos + + # test floor + result = dt.floor(round_freq) + diff = dt.asi8 - result.asi8 + mod = result.asi8 % unit + assert (mod == 0).all(), f"floor not a {round_freq} multiple" + assert (0 <= diff).all() and (diff < unit).all(), "floor error" + + # test ceil + result = dt.ceil(round_freq) + diff = result.asi8 - dt.asi8 + mod = result.asi8 % unit + assert (mod == 0).all(), f"ceil not a {round_freq} multiple" + assert (0 <= diff).all() and (diff < unit).all(), "ceil error" + + # test round + result = dt.round(round_freq) + diff = abs(result.asi8 - dt.asi8) + mod = result.asi8 % unit + assert (mod == 0).all(), f"round not a {round_freq} multiple" + assert (diff <= unit // 2).all(), "round error" + if unit % 2 == 0: + assert (result.asi8[diff == unit // 2] % 2 == 0).all(), ( + "round half to even error" + ) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_shift.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..96177f228db29c07fcf7b8ca39f799ed94c26005 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_shift.py @@ -0,0 +1,179 @@ +from datetime import datetime +import zoneinfo + +import pytest + +from pandas.errors import NullFrequencyError + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndexShift: + # ------------------------------------------------------------- + # DatetimeIndex.shift is used in integer addition + + def test_dti_shift_tzaware(self, tz_naive_fixture, unit): + # GH#9903 + tz = tz_naive_fixture + idx = pd.DatetimeIndex([], name="xxx", tz=tz).as_unit(unit) + tm.assert_index_equal(idx.shift(0, freq="h"), idx) + tm.assert_index_equal(idx.shift(3, freq="h"), idx) + + idx = pd.DatetimeIndex( + ["2011-01-01 10:00", "2011-01-01 11:00", "2011-01-01 12:00"], + name="xxx", + tz=tz, + freq="h", + ).as_unit(unit) + tm.assert_index_equal(idx.shift(0, freq="h"), idx) + exp = pd.DatetimeIndex( + ["2011-01-01 13:00", "2011-01-01 14:00", "2011-01-01 15:00"], + name="xxx", + tz=tz, + freq="h", + ).as_unit(unit) + tm.assert_index_equal(idx.shift(3, freq="h"), exp) + exp = pd.DatetimeIndex( + ["2011-01-01 07:00", "2011-01-01 08:00", "2011-01-01 09:00"], + name="xxx", + tz=tz, + freq="h", + ).as_unit(unit) + tm.assert_index_equal(idx.shift(-3, freq="h"), exp) + + def test_dti_shift_freqs(self, unit): + # test shift for DatetimeIndex and non DatetimeIndex + # GH#8083 + drange = pd.date_range("20130101", periods=5, unit=unit) + result = drange.shift(1) + expected = pd.DatetimeIndex( + ["2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05", "2013-01-06"], + dtype=f"M8[{unit}]", + freq="D", + ) + tm.assert_index_equal(result, expected) + + result = drange.shift(-1) + expected = pd.DatetimeIndex( + ["2012-12-31", "2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04"], + dtype=f"M8[{unit}]", + freq="D", + ) + tm.assert_index_equal(result, expected) + + result = drange.shift(3, freq="2D") + expected = pd.DatetimeIndex( + ["2013-01-07", "2013-01-08", "2013-01-09", "2013-01-10", "2013-01-11"], + dtype=f"M8[{unit}]", + freq="D", + ) + tm.assert_index_equal(result, expected) + + def test_dti_shift_int(self, unit): + rng = pd.date_range("1/1/2000", periods=20, unit=unit) + + result = rng + 5 * rng.freq + expected = rng.shift(5) + tm.assert_index_equal(result, expected) + + result = rng - 5 * rng.freq + expected = rng.shift(-5) + tm.assert_index_equal(result, expected) + + def test_dti_shift_no_freq(self, unit): + # GH#19147 + dti = pd.DatetimeIndex(["2011-01-01 10:00", "2011-01-01"], freq=None).as_unit( + unit + ) + with pytest.raises(NullFrequencyError, match="Cannot shift with no freq"): + dti.shift(2) + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_dti_shift_localized(self, tzstr, unit): + dr = pd.date_range("2011/1/1", "2012/1/1", freq="W-FRI", unit=unit) + dr_tz = dr.tz_localize(tzstr) + + result = dr_tz.shift(1, "10min") + assert result.tz == dr_tz.tz + + def test_dti_shift_across_dst(self, unit): + # GH 8616 + idx = pd.date_range( + "2013-11-03", tz="America/Chicago", periods=7, freq="h", unit=unit + ) + ser = pd.Series(index=idx[:-1], dtype=object) + result = ser.shift(freq="h") + expected = pd.Series(index=idx[1:], dtype=object) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "shift, result_time", + [ + [0, "2014-11-14 00:00:00"], + [-1, "2014-11-13 23:00:00"], + [1, "2014-11-14 01:00:00"], + ], + ) + def test_dti_shift_near_midnight(self, shift, result_time, unit): + # GH 8616 + tz = zoneinfo.ZoneInfo("US/Eastern") + dt_est = datetime(2014, 11, 14, 0, tzinfo=tz) + idx = pd.DatetimeIndex([dt_est]).as_unit(unit) + ser = pd.Series(data=[1], index=idx) + result = ser.shift(shift, freq="h") + exp_index = pd.DatetimeIndex([result_time], tz=tz).as_unit(unit) + expected = pd.Series(1, index=exp_index) + tm.assert_series_equal(result, expected) + + def test_shift_periods(self, unit): + # GH#22458 : argument 'n' was deprecated in favor of 'periods' + idx = pd.date_range( + start=datetime(2009, 1, 1), end=datetime(2010, 1, 1), periods=3, unit=unit + ) + tm.assert_index_equal(idx.shift(periods=0), idx) + tm.assert_index_equal(idx.shift(0), idx) + + @pytest.mark.parametrize("freq", ["B", "C"]) + def test_shift_bday(self, freq, unit): + rng = pd.date_range( + datetime(2009, 1, 1), datetime(2010, 1, 1), freq=freq, unit=unit + ) + shifted = rng.shift(5) + assert shifted[0] == rng[5] + assert shifted.freq == rng.freq + + shifted = rng.shift(-5) + assert shifted[5] == rng[0] + assert shifted.freq == rng.freq + + shifted = rng.shift(0) + assert shifted[0] == rng[0] + assert shifted.freq == rng.freq + + def test_shift_bmonth(self, performance_warning, unit): + rng = pd.date_range( + datetime(2009, 1, 1), + datetime(2010, 1, 1), + freq=pd.offsets.BMonthEnd(), + unit=unit, + ) + shifted = rng.shift(1, freq=pd.offsets.BDay()) + assert shifted[0] == rng[0] + pd.offsets.BDay() + + rng = pd.date_range( + datetime(2009, 1, 1), + datetime(2010, 1, 1), + freq=pd.offsets.BMonthEnd(), + unit=unit, + ) + msg = "Non-vectorized DateOffset being applied to Series or DatetimeIndex" + with tm.assert_produces_warning(performance_warning, match=msg): + shifted = rng.shift(1, freq=pd.offsets.CDay()) + assert shifted[0] == rng[0] + pd.offsets.CDay() + + def test_shift_empty(self, unit): + # GH#14811 + dti = pd.date_range(start="2016-10-21", end="2016-10-21", freq="BME", unit=unit) + result = dti.shift(1) + tm.assert_index_equal(result, dti) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_snap.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_snap.py new file mode 100644 index 0000000000000000000000000000000000000000..93dd16d350aff9bfcf4e8ac71ab1ff6331de9b79 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_snap.py @@ -0,0 +1,51 @@ +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize("tz", [None, "Asia/Shanghai", "Europe/Berlin"]) +@pytest.mark.parametrize("name", [None, "my_dti"]) +def test_dti_snap(name, tz, unit): + dti = pd.DatetimeIndex( + [ + "1/1/2002", + "1/2/2002", + "1/3/2002", + "1/4/2002", + "1/5/2002", + "1/6/2002", + "1/7/2002", + ], + name=name, + tz=tz, + freq="D", + ) + dti = dti.as_unit(unit) + + result = dti.snap(freq="W-MON") + msg = "'w-mon' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = pd.date_range( + "12/31/2001", "1/7/2002", name=name, tz=tz, freq="w-mon" + ) + expected = expected.repeat([3, 4]) + expected = expected.as_unit(unit) + tm.assert_index_equal(result, expected) + assert result.tz == expected.tz + assert result.freq is None + assert expected.freq is None + + result = dti.snap(freq="B") + + msg = "'b' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = pd.date_range("1/1/2002", "1/7/2002", name=name, tz=tz, freq="b") + expected = expected.repeat([1, 1, 1, 2, 2]) + expected = expected.as_unit(unit) + tm.assert_index_equal(result, expected) + assert result.tz == expected.tz + assert result.freq is None + assert expected.freq is None diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_frame.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..835f3eef13e7a79c32cf8b23d335b124aa4d57f3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_frame.py @@ -0,0 +1,24 @@ +import pandas as pd +import pandas._testing as tm + + +class TestToFrame: + def test_to_frame_datetime_tz(self): + # GH#25809 + idx = pd.date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC") + result = idx.to_frame() + expected = pd.DataFrame(idx, index=idx) + tm.assert_frame_equal(result, expected) + + def test_to_frame_respects_none_name(self): + # GH#44212 if we explicitly pass name=None, then that should be respected, + # not changed to 0 + # GH-45448 this is first deprecated to only change in the future + idx = pd.date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC") + result = idx.to_frame(name=None) + exp_idx = pd.Index([None], dtype=object) + tm.assert_index_equal(exp_idx, result.columns) + + result = idx.rename("foo").to_frame(name=None) + exp_idx = pd.Index([None], dtype=object) + tm.assert_index_equal(exp_idx, result.columns) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_julian_date.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_julian_date.py new file mode 100644 index 0000000000000000000000000000000000000000..abb9948aad0ad7f01d800079201944272c17894a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_julian_date.py @@ -0,0 +1,54 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDateTimeIndexToJulianDate: + def test_1700(self): + dr = pd.date_range(start=pd.Timestamp("1710-10-01"), periods=5, freq="D") + r1 = pd.Index([x.to_julian_date() for x in dr]) + r2 = dr.to_julian_date() + assert isinstance(r2, pd.Index) and r2.dtype == np.float64 + tm.assert_index_equal(r1, r2) + + def test_2000(self): + dr = pd.date_range(start=pd.Timestamp("2000-02-27"), periods=5, freq="D") + r1 = pd.Index([x.to_julian_date() for x in dr]) + r2 = dr.to_julian_date() + assert isinstance(r2, pd.Index) and r2.dtype == np.float64 + tm.assert_index_equal(r1, r2) + + def test_hour(self): + dr = pd.date_range(start=pd.Timestamp("2000-02-27"), periods=5, freq="h") + r1 = pd.Index([x.to_julian_date() for x in dr]) + r2 = dr.to_julian_date() + assert isinstance(r2, pd.Index) and r2.dtype == np.float64 + tm.assert_index_equal(r1, r2) + + def test_minute(self): + dr = pd.date_range(start=pd.Timestamp("2000-02-27"), periods=5, freq="min") + r1 = pd.Index([x.to_julian_date() for x in dr]) + r2 = dr.to_julian_date() + assert isinstance(r2, pd.Index) and r2.dtype == np.float64 + tm.assert_index_equal(r1, r2) + + def test_second(self): + dr = pd.date_range(start=pd.Timestamp("2000-02-27"), periods=5, freq="s") + r1 = pd.Index([x.to_julian_date() for x in dr]) + r2 = dr.to_julian_date() + assert isinstance(r2, pd.Index) and r2.dtype == np.float64 + tm.assert_index_equal(r1, r2) + + @pytest.mark.parametrize("tz", ["UTC", "US/Pacific", "Europe/London"]) + def test_tz_aware_uses_utc_instant(self, tz): + # GH#54763 to_julian_date should reflect the UTC instant, not wall clock + dr = pd.date_range(start="2000-02-27", periods=5, freq="h", tz=tz) + result = dr.to_julian_date() + expected = pd.Index([ts.to_julian_date() for ts in dr]) + tm.assert_index_equal(result, expected) + # also matches converting to naive UTC up front + tm.assert_index_equal( + result, dr.tz_convert("UTC").tz_localize(None).to_julian_date() + ) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_period.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_period.py new file mode 100644 index 0000000000000000000000000000000000000000..ad3db3d88af70e5ef7d90c54dd23d0d2298ebba7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_period.py @@ -0,0 +1,293 @@ +from datetime import UTC + +import dateutil.tz +from dateutil.tz import tzlocal +import pytest + +from pandas._libs.tslibs.ccalendar import MONTHS +from pandas._libs.tslibs.offsets import MonthEnd +from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG +from pandas.errors import OutOfBoundsDatetime + +import pandas as pd +import pandas._testing as tm + + +class TestToPeriod: + def test_dti_to_period(self): + dti = pd.date_range(start="1/1/2005", end="12/1/2005", freq="ME") + pi1 = dti.to_period() + pi2 = dti.to_period(freq="D") + pi3 = dti.to_period(freq="3D") + + assert pi1[0] == pd.Period("Jan 2005", freq="M") + assert pi2[0] == pd.Period("1/31/2005", freq="D") + assert pi3[0] == pd.Period("1/31/2005", freq="3D") + + assert pi1[-1] == pd.Period("Nov 2005", freq="M") + assert pi2[-1] == pd.Period("11/30/2005", freq="D") + assert pi3[-1], pd.Period("11/30/2005", freq="3D") + + tm.assert_index_equal(pi1, pd.period_range("1/1/2005", "11/1/2005", freq="M")) + tm.assert_index_equal( + pi2, pd.period_range("1/1/2005", "11/1/2005", freq="M").asfreq("D") + ) + tm.assert_index_equal( + pi3, pd.period_range("1/1/2005", "11/1/2005", freq="M").asfreq("3D") + ) + + @pytest.mark.parametrize("month", MONTHS) + def test_to_period_quarterly(self, month): + # make sure we can make the round trip + freq = f"Q-{month}" + rng = pd.period_range("1989Q3", "1991Q3", freq=freq) + stamps = rng.to_timestamp() + result = stamps.to_period(freq) + tm.assert_index_equal(rng, result) + + @pytest.mark.parametrize("off", ["BQE", "QS", "BQS"]) + def test_to_period_quarterlyish(self, off): + rng = pd.date_range("01-Jan-2012", periods=8, freq=off) + prng = rng.to_period() + assert prng.freq == "QE-DEC" + + @pytest.mark.parametrize("off", ["BYE", "YS", "BYS"]) + def test_to_period_annualish(self, off): + rng = pd.date_range("01-Jan-2012", periods=8, freq=off) + prng = rng.to_period() + assert prng.freq == "YE-DEC" + + @pytest.mark.parametrize( + "off, expected_freq", + [ + ("QS-APR", "Q-MAR"), + ("BQS-APR", "Q-MAR"), + ("BQE-APR", "Q-APR"), + # start-offset month is shifted back one; JAN wraps to DEC + ("QS-JAN", "Q-DEC"), + ("QS-DEC", "Q-NOV"), + ], + ) + def test_to_period_quarterly_anchored(self, off, expected_freq): + # GH#36939 - anchored quarter offsets should preserve the anchor + rng = pd.date_range("01-Apr-2012", periods=4, freq=off) + result = rng.to_period() + assert result.freqstr == expected_freq + + @pytest.mark.parametrize( + "dates, expected_freq, expected_periods", + [ + ( + ["2012-01-01", "2012-04-01", "2012-07-01", "2012-10-01"], + "Q-DEC", + ["2012Q1", "2012Q2", "2012Q3", "2012Q4"], + ), + ( + ["2012-02-01", "2012-05-01", "2012-08-01", "2012-11-01"], + "Q-JAN", + ["2013Q1", "2013Q2", "2013Q3", "2013Q4"], + ), + ( + ["2012-03-01", "2012-06-01", "2012-09-01", "2012-12-01"], + "Q-FEB", + ["2013Q1", "2013Q2", "2013Q3", "2013Q4"], + ), + ], + ) + def test_to_period_quarter_start_inferred( + self, dates, expected_freq, expected_periods + ): + # GH#36939 - without a set freq the anchor is only inferred up to + # mod 3; calendar quarter starts must keep the calendar Q-DEC labels + dti = pd.DatetimeIndex(dates) + result = dti.to_period() + expected = pd.PeriodIndex(expected_periods, freq=expected_freq) + tm.assert_index_equal(result, expected) + + # Series.dt.to_period goes through DatetimeArray.to_period, which + # infers the freq itself rather than receiving it from the Index + result2 = pd.Series(dti).dt.to_period() + tm.assert_series_equal(result2, pd.Series(expected)) + + @pytest.mark.parametrize( + "off, expected_freq", + [ + ("YS-APR", "Y-MAR"), + ("BYS-APR", "Y-MAR"), + ("BYE-APR", "Y-APR"), + # start-offset month is shifted back one; JAN wraps to DEC + ("YS-JAN", "Y-DEC"), + ("YS-DEC", "Y-NOV"), + ], + ) + def test_to_period_annual_anchored(self, off, expected_freq): + # GH#36939 - anchored annual offsets should preserve the anchor + rng = pd.date_range("01-Apr-2012", periods=3, freq=off) + result = rng.to_period() + assert result.freqstr == expected_freq + + def test_to_period_monthish(self): + offsets = ["MS", "BME"] + for off in offsets: + rng = pd.date_range("01-Jan-2012", periods=8, freq=off) + prng = rng.to_period() + assert prng.freqstr == "M" + + rng = pd.date_range("01-Jan-2012", periods=8, freq="ME") + prng = rng.to_period() + assert prng.freqstr == "M" + + with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): + pd.date_range("01-Jan-2012", periods=8, freq="EOM") + + @pytest.mark.parametrize( + "freq_offset, freq_period", + [ + ("2ME", "2M"), + (MonthEnd(2), MonthEnd(2)), + ], + ) + def test_dti_to_period_2monthish(self, freq_offset, freq_period): + dti = pd.date_range("2020-01-01", periods=3, freq=freq_offset) + pi = dti.to_period() + + tm.assert_index_equal( + pi, pd.period_range("2020-01", "2020-05", freq=freq_period) + ) + + @pytest.mark.parametrize( + "freq", ["2ME", "1me", "2QE", "2QE-SEP", "1YE", "ye", "2YE-MAR"] + ) + def test_to_period_frequency_M_Q_Y_raises(self, freq): + msg = f"Invalid frequency: {freq}" + + rng = pd.date_range("01-Jan-2012", periods=8, freq="ME") + with pytest.raises(ValueError, match=msg): + rng.to_period(freq) + + def test_to_period_infer(self): + # https://github.com/pandas-dev/pandas/issues/33358 + rng = pd.date_range( + start="2019-12-22 06:40:00+00:00", + end="2019-12-22 08:45:00+00:00", + freq="5min", + ) + + with tm.assert_produces_warning(UserWarning, match="drop timezone info"): + pi1 = rng.to_period("5min") + + with tm.assert_produces_warning(UserWarning, match="drop timezone info"): + pi2 = rng.to_period() + + tm.assert_index_equal(pi1, pi2) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_period_dt64_round_trip(self): + dti = pd.date_range("1/1/2000", "1/7/2002", freq="B", unit="ns") + pi = dti.to_period() + tm.assert_index_equal(pi.to_timestamp(), dti.as_unit("us")) + + dti = pd.date_range("1/1/2000", "1/7/2002", freq="B", unit="ns") + pi = dti.to_period(freq="h") + tm.assert_index_equal(pi.to_timestamp(), dti.as_unit("us")) + + def test_to_period_millisecond(self): + index = pd.DatetimeIndex( + [ + pd.Timestamp("2007-01-01 10:11:12.123456Z"), + pd.Timestamp("2007-01-01 10:11:13.789123Z"), + ] + ) + + with tm.assert_produces_warning(UserWarning, match="drop timezone info"): + period = index.to_period(freq="ms") + assert 2 == len(period) + assert period[0] == pd.Period("2007-01-01 10:11:12.123Z", "ms") + assert period[1] == pd.Period("2007-01-01 10:11:13.789Z", "ms") + + def test_to_period_out_of_bounds_ordinal(self): + # GH#64158 the nanosecond ordinal overflows int64 for these dates; the + # overflow used to be swallowed, giving 1970 epoch periods + dti = pd.date_range("2300-01-01", periods=2, freq="D", unit="s") + msg = "Out of bounds nanosecond timestamp: 2300-01-01" + with pytest.raises(OutOfBoundsDatetime, match=msg): + dti.to_period("ns") + + def test_to_period_microsecond(self): + index = pd.DatetimeIndex( + [ + pd.Timestamp("2007-01-01 10:11:12.123456Z"), + pd.Timestamp("2007-01-01 10:11:13.789123Z"), + ] + ) + + with tm.assert_produces_warning(UserWarning, match="drop timezone info"): + period = index.to_period(freq="us") + assert 2 == len(period) + assert period[0] == pd.Period("2007-01-01 10:11:12.123456Z", "us") + assert period[1] == pd.Period("2007-01-01 10:11:13.789123Z", "us") + + @pytest.mark.parametrize( + "tz", + [ + "US/Eastern", + UTC, + tzlocal(), + "dateutil/US/Eastern", + dateutil.tz.tzutc(), + ], + ) + def test_to_period_tz(self, tz): + ts = pd.date_range("1/1/2000", "2/1/2000", tz=tz) + + with tm.assert_produces_warning(UserWarning, match="drop timezone info"): + result = ts.to_period()[0] + expected = ts[0].to_period(ts.freq) + + assert result == expected + + expected = pd.date_range("1/1/2000", "2/1/2000").to_period() + + with tm.assert_produces_warning(UserWarning, match="drop timezone info"): + result = ts.to_period(ts.freq) + + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("tz", ["Etc/GMT-1", "Etc/GMT+1"]) + def test_to_period_tz_utc_offset_consistency(self, tz): + # GH#22905 + ts = pd.date_range("1/1/2000", "2/1/2000", tz="Etc/GMT-1") + with tm.assert_produces_warning(UserWarning, match="drop timezone info"): + result = ts.to_period()[0] + expected = ts[0].to_period(ts.freq) + assert result == expected + + def test_to_period_nofreq(self): + idx = pd.DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-04"]) + msg = "You must pass a freq argument as current index has none." + with pytest.raises(ValueError, match=msg): + idx.to_period() + + idx = pd.DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"], freq="infer") + assert idx.freqstr == "D" + expected = pd.PeriodIndex(["2000-01-01", "2000-01-02", "2000-01-03"], freq="D") + tm.assert_index_equal(idx.to_period(), expected) + + # GH#7606 + idx = pd.DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"]) + assert idx.freqstr is None + tm.assert_index_equal(idx.to_period(), expected) + + @pytest.mark.parametrize("freq", ["2BME", "SME-15", "2BMS"]) + def test_to_period_offsets_not_supported(self, freq): + # GH#56243 + msg = "|".join( + [ + f"Invalid frequency: {freq}", + f"{freq} is not supported as period frequency", + ] + ) + + ts = pd.date_range("1/1/2012", periods=4, freq=freq) + with pytest.raises(ValueError, match=msg): + ts.to_period() diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_pydatetime.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_pydatetime.py new file mode 100644 index 0000000000000000000000000000000000000000..6eafa94c5a3055948b22c42769fb1bf261df1ec0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_pydatetime.py @@ -0,0 +1,47 @@ +from datetime import ( + UTC, + datetime, +) + +import dateutil.parser +import dateutil.tz +from dateutil.tz import tzlocal +import numpy as np + +import pandas as pd +import pandas._testing as tm +from pandas.tests.indexes.datetimes.test_timezones import FixedOffset + +fixed_off = FixedOffset(-420, "-07:00") + + +class TestToPyDatetime: + def test_dti_to_pydatetime(self): + dt = dateutil.parser.parse("2012-06-13T01:39:00Z") + dt = dt.replace(tzinfo=tzlocal()) + + arr = np.array([dt], dtype=object) + + result = pd.to_datetime(arr, utc=True) + assert result.tz is UTC + + rng = pd.date_range("2012-11-03 03:00", "2012-11-05 03:00", tz=tzlocal()) + arr = rng.to_pydatetime() + result = pd.to_datetime(arr, utc=True) + assert result.tz is UTC + + def test_dti_to_pydatetime_fizedtz(self): + dates = np.array( + [ + datetime(2000, 1, 1, tzinfo=fixed_off), + datetime(2000, 1, 2, tzinfo=fixed_off), + datetime(2000, 1, 3, tzinfo=fixed_off), + ] + ) + dti = pd.DatetimeIndex(dates) + + result = dti.to_pydatetime() + tm.assert_numpy_array_equal(dates, result) + + result = dti._mpl_repr() + tm.assert_numpy_array_equal(dates, result) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_series.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_series.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e2a80e95862548431d83bde5e6440361c7f82b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_to_series.py @@ -0,0 +1,15 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestToSeries: + def test_to_series(self): + naive = pd.DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B") + idx = naive.tz_localize("US/Pacific") + + expected = pd.Series(np.array(idx.tolist(), dtype="object"), name="B") + result = idx.to_series(index=range(2)) + assert expected.dtype == idx.dtype + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_tz_convert.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_tz_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..7342749f96dac12f5c76455c7ff4b958f6681481 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_tz_convert.py @@ -0,0 +1,429 @@ +from datetime import ( + datetime, + timedelta, + timezone, +) + +import dateutil.tz +from dateutil.tz import gettz +import numpy as np +import pytest + +from pandas._libs.tslibs import ( + iNaT, + timezones, +) +from pandas.compat import WASM +from pandas.errors import OutOfBoundsDatetime +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +class TestTZConvert: + def test_tz_convert_nat(self): + # GH#5546 + dates = [pd.NaT] + idx = pd.DatetimeIndex(dates) + idx = idx.tz_localize("US/Pacific") + tm.assert_index_equal(idx, pd.DatetimeIndex(dates, tz="US/Pacific")) + idx = idx.tz_convert("US/Eastern") + tm.assert_index_equal(idx, pd.DatetimeIndex(dates, tz="US/Eastern")) + idx = idx.tz_convert("UTC") + tm.assert_index_equal(idx, pd.DatetimeIndex(dates, tz="UTC")) + + dates = ["2010-12-01 00:00", "2010-12-02 00:00", pd.NaT] + idx = pd.DatetimeIndex(dates) + idx = idx.tz_localize("US/Pacific") + tm.assert_index_equal(idx, pd.DatetimeIndex(dates, tz="US/Pacific")) + idx = idx.tz_convert("US/Eastern") + expected = ["2010-12-01 03:00", "2010-12-02 03:00", pd.NaT] + tm.assert_index_equal(idx, pd.DatetimeIndex(expected, tz="US/Eastern")) + + idx = idx + pd.offsets.Hour(5) + expected = ["2010-12-01 08:00", "2010-12-02 08:00", pd.NaT] + tm.assert_index_equal(idx, pd.DatetimeIndex(expected, tz="US/Eastern")) + idx = idx.tz_convert("US/Pacific") + expected = ["2010-12-01 05:00", "2010-12-02 05:00", pd.NaT] + tm.assert_index_equal(idx, pd.DatetimeIndex(expected, tz="US/Pacific")) + + idx = idx + np.timedelta64(3, "h") + expected = ["2010-12-01 08:00", "2010-12-02 08:00", pd.NaT] + tm.assert_index_equal(idx, pd.DatetimeIndex(expected, tz="US/Pacific")) + + idx = idx.tz_convert("US/Eastern") + expected = ["2010-12-01 11:00", "2010-12-02 11:00", pd.NaT] + tm.assert_index_equal(idx, pd.DatetimeIndex(expected, tz="US/Eastern")) + + @pytest.mark.parametrize("prefix", ["", "dateutil/"]) + def test_dti_tz_convert_compat_timestamp(self, prefix): + strdates = ["1/1/2012", "3/1/2012", "4/1/2012"] + idx = pd.DatetimeIndex(strdates, tz=prefix + "US/Eastern") + + conv = idx[0].tz_convert(prefix + "US/Pacific") + expected = idx.tz_convert(prefix + "US/Pacific")[0] + + assert conv == expected + + def test_dti_tz_convert_hour_overflow_dst(self): + # Regression test for GH#13306 + + # sorted case US/Eastern -> UTC + ts = ["2008-05-12 09:50:00", "2008-12-12 09:50:35", "2009-05-12 09:50:32"] + tt = pd.DatetimeIndex(ts).tz_localize("US/Eastern") + ut = tt.tz_convert("UTC") + expected = pd.Index([13, 14, 13], dtype=np.int32) + tm.assert_index_equal(ut.hour, expected) + + # sorted case UTC -> US/Eastern + ts = ["2008-05-12 13:50:00", "2008-12-12 14:50:35", "2009-05-12 13:50:32"] + tt = pd.DatetimeIndex(ts).tz_localize("UTC") + ut = tt.tz_convert("US/Eastern") + expected = pd.Index([9, 9, 9], dtype=np.int32) + tm.assert_index_equal(ut.hour, expected) + + # unsorted case US/Eastern -> UTC + ts = ["2008-05-12 09:50:00", "2008-12-12 09:50:35", "2008-05-12 09:50:32"] + tt = pd.DatetimeIndex(ts).tz_localize("US/Eastern") + ut = tt.tz_convert("UTC") + expected = pd.Index([13, 14, 13], dtype=np.int32) + tm.assert_index_equal(ut.hour, expected) + + # unsorted case UTC -> US/Eastern + ts = ["2008-05-12 13:50:00", "2008-12-12 14:50:35", "2008-05-12 13:50:32"] + tt = pd.DatetimeIndex(ts).tz_localize("UTC") + ut = tt.tz_convert("US/Eastern") + expected = pd.Index([9, 9, 9], dtype=np.int32) + tm.assert_index_equal(ut.hour, expected) + + @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) + def test_dti_tz_convert_hour_overflow_dst_timestamps(self, tz): + # Regression test for GH#13306 + + # sorted case US/Eastern -> UTC + ts = [ + pd.Timestamp("2008-05-12 09:50:00", tz=tz), + pd.Timestamp("2008-12-12 09:50:35", tz=tz), + pd.Timestamp("2009-05-12 09:50:32", tz=tz), + ] + tt = pd.DatetimeIndex(ts) + ut = tt.tz_convert("UTC") + expected = pd.Index([13, 14, 13], dtype=np.int32) + tm.assert_index_equal(ut.hour, expected) + + # sorted case UTC -> US/Eastern + ts = [ + pd.Timestamp("2008-05-12 13:50:00", tz="UTC"), + pd.Timestamp("2008-12-12 14:50:35", tz="UTC"), + pd.Timestamp("2009-05-12 13:50:32", tz="UTC"), + ] + tt = pd.DatetimeIndex(ts) + ut = tt.tz_convert("US/Eastern") + expected = pd.Index([9, 9, 9], dtype=np.int32) + tm.assert_index_equal(ut.hour, expected) + + # unsorted case US/Eastern -> UTC + ts = [ + pd.Timestamp("2008-05-12 09:50:00", tz=tz), + pd.Timestamp("2008-12-12 09:50:35", tz=tz), + pd.Timestamp("2008-05-12 09:50:32", tz=tz), + ] + tt = pd.DatetimeIndex(ts) + ut = tt.tz_convert("UTC") + expected = pd.Index([13, 14, 13], dtype=np.int32) + tm.assert_index_equal(ut.hour, expected) + + # unsorted case UTC -> US/Eastern + ts = [ + pd.Timestamp("2008-05-12 13:50:00", tz="UTC"), + pd.Timestamp("2008-12-12 14:50:35", tz="UTC"), + pd.Timestamp("2008-05-12 13:50:32", tz="UTC"), + ] + tt = pd.DatetimeIndex(ts) + ut = tt.tz_convert("US/Eastern") + expected = pd.Index([9, 9, 9], dtype=np.int32) + tm.assert_index_equal(ut.hour, expected) + + @pytest.mark.parametrize("freq, n", [("h", 1), ("min", 60), ("s", 3600)]) + def test_dti_tz_convert_trans_pos_plus_1__bug(self, freq, n): + # Regression test for tslib.tz_convert(vals, tz1, tz2). + # See GH#4496 for details. + idx = pd.date_range( + datetime(2011, 3, 26, 23), datetime(2011, 3, 27, 1), freq=freq + ) + idx = idx.tz_localize("UTC") + idx = idx.tz_convert("Europe/Moscow") + + expected = np.repeat(np.array([3, 4, 5]), np.array([n, n, 1])) + tm.assert_index_equal(idx.hour, pd.Index(expected, dtype=np.int32)) + + def test_dti_tz_convert_dst(self): + for freq, n in [("h", 1), ("min", 60), ("s", 3600)]: + # Start DST + idx = pd.date_range( + "2014-03-08 23:00", "2014-03-09 09:00", freq=freq, tz="UTC" + ) + idx = idx.tz_convert("US/Eastern") + expected = np.repeat( + np.array([18, 19, 20, 21, 22, 23, 0, 1, 3, 4, 5]), + np.array([n, n, n, n, n, n, n, n, n, n, 1]), + ) + tm.assert_index_equal(idx.hour, pd.Index(expected, dtype=np.int32)) + + idx = pd.date_range( + "2014-03-08 18:00", "2014-03-09 05:00", freq=freq, tz="US/Eastern" + ) + idx = idx.tz_convert("UTC") + expected = np.repeat( + np.array([23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), + np.array([n, n, n, n, n, n, n, n, n, n, 1]), + ) + tm.assert_index_equal(idx.hour, pd.Index(expected, dtype=np.int32)) + + # End DST + idx = pd.date_range( + "2014-11-01 23:00", "2014-11-02 09:00", freq=freq, tz="UTC" + ) + idx = idx.tz_convert("US/Eastern") + expected = np.repeat( + np.array([19, 20, 21, 22, 23, 0, 1, 1, 2, 3, 4]), + np.array([n, n, n, n, n, n, n, n, n, n, 1]), + ) + tm.assert_index_equal(idx.hour, pd.Index(expected, dtype=np.int32)) + + idx = pd.date_range( + "2014-11-01 18:00", "2014-11-02 05:00", freq=freq, tz="US/Eastern" + ) + idx = idx.tz_convert("UTC") + expected = np.repeat( + np.array([22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), + np.array([n, n, n, n, n, n, n, n, n, n, n, n, 1]), + ) + tm.assert_index_equal(idx.hour, pd.Index(expected, dtype=np.int32)) + + # daily + # Start DST + idx = pd.date_range("2014-03-08 00:00", "2014-03-09 00:00", freq="D", tz="UTC") + idx = idx.tz_convert("US/Eastern") + tm.assert_index_equal(idx.hour, pd.Index([19, 19], dtype=np.int32)) + + idx = pd.date_range( + "2014-03-08 00:00", "2014-03-09 00:00", freq="D", tz="US/Eastern" + ) + idx = idx.tz_convert("UTC") + tm.assert_index_equal(idx.hour, pd.Index([5, 5], dtype=np.int32)) + + # End DST + idx = pd.date_range("2014-11-01 00:00", "2014-11-02 00:00", freq="D", tz="UTC") + idx = idx.tz_convert("US/Eastern") + tm.assert_index_equal(idx.hour, pd.Index([20, 20], dtype=np.int32)) + + idx = pd.date_range( + "2014-11-01 00:00", "2014-11-02 000:00", freq="D", tz="US/Eastern" + ) + idx = idx.tz_convert("UTC") + tm.assert_index_equal(idx.hour, pd.Index([4, 4], dtype=np.int32)) + + def test_tz_convert_roundtrip(self, tz_aware_fixture): + tz = tz_aware_fixture + idx1 = pd.date_range(start="2014-01-01", end="2014-12-31", freq="ME", tz="UTC") + exp1 = pd.date_range(start="2014-01-01", end="2014-12-31", freq="ME") + + idx2 = pd.date_range(start="2014-01-01", end="2014-12-31", freq="D", tz="UTC") + exp2 = pd.date_range(start="2014-01-01", end="2014-12-31", freq="D") + + idx3 = pd.date_range(start="2014-01-01", end="2014-03-01", freq="h", tz="UTC") + exp3 = pd.date_range(start="2014-01-01", end="2014-03-01", freq="h") + + idx4 = pd.date_range(start="2014-08-01", end="2014-10-31", freq="min", tz="UTC") + exp4 = pd.date_range(start="2014-08-01", end="2014-10-31", freq="min") + + for idx, expected in [(idx1, exp1), (idx2, exp2), (idx3, exp3), (idx4, exp4)]: + converted = idx.tz_convert(tz) + reset = converted.tz_convert(None) + tm.assert_index_equal(reset, expected, check_freq=False) + assert reset.tzinfo is None + expected = converted.tz_convert("UTC").tz_localize(None) + expected = expected._with_freq("infer") + tm.assert_index_equal(reset, expected, check_freq=False) + + def test_dti_tz_convert_tzlocal(self): + # GH#13583 + # tz_convert doesn't affect to internal + dti = pd.date_range(start="2001-01-01", end="2001-03-01", tz="UTC") + dti2 = dti.tz_convert(dateutil.tz.tzlocal()) + tm.assert_numpy_array_equal(dti2.asi8, dti.asi8) + + dti = pd.date_range( + start="2001-01-01", end="2001-03-01", tz=dateutil.tz.tzlocal() + ) + dti2 = dti.tz_convert(None) + tm.assert_numpy_array_equal(dti2.asi8, dti.asi8) + + @pytest.mark.parametrize( + "tz", + [ + "US/Eastern", + "dateutil/US/Eastern", + "pytz/US/Eastern", + gettz("US/Eastern"), + ], + ) + def test_dti_tz_convert_utc_to_local_no_modify(self, tz): + if isinstance(tz, str) and tz.startswith("pytz/"): + pytz = pytest.importorskip("pytz") + tz = pytz.timezone(tz.removeprefix("pytz/")) + rng = pd.date_range("3/11/2012", "3/12/2012", freq="h", tz="utc") + rng_eastern = rng.tz_convert(tz) + + # Values are unmodified + tm.assert_numpy_array_equal(rng.asi8, rng_eastern.asi8) + + assert timezones.tz_compare(rng_eastern.tz, timezones.maybe_get_tz(tz)) + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_tz_convert_unsorted(self, tzstr): + dr = pd.date_range("2012-03-09", freq="h", periods=100, tz="utc") + dr = dr.tz_convert(tzstr) + + result = dr[::-1].hour + exp = dr.hour[::-1] + tm.assert_almost_equal(result, exp) + + def test_dti_tz_convert_day_freq_not_preserved(self): + # GH#51716 + dti = pd.date_range("2020-3-28", periods=5, freq="D", tz="Europe/London") + result = dti.tz_convert("UTC") + assert (result == dti).all() + assert result.freq is None + + +def _utc_dti(value): + # Build a UTC-labelled index without going through the eager scalar + # constructor, so that the UTC->local shift is what raises. + return pd.DatetimeIndex(np.array([value], dtype="i8").view("M8[ns]")).tz_localize( + "UTC" + ) + + +@pytest.mark.parametrize( + "tz", + [ + "Europe/Berlin", # zoneinfo tz-rule fast path, val past the last transition + gettz("Europe/Berlin"), # dateutil, so the transition bisect instead + "Etc/GMT-9", # fixed offset + ], +) +def test_dti_utc_to_local_overflow(tz): + # GH#66550 the UTC->local shift was a bare add, so a UTC instant whose wall + # time in tz is past Timestamp.max wrapped by 585 years instead of raising. + # The scalar path already refuses the same conversion. + dti = _utc_dti(pd.Timestamp.max._value).tz_convert(tz) + + with pytest.raises(OutOfBoundsDatetime, match="overflows past"): + dti.tz_localize(None) + + +def test_dti_utc_to_local_underflow(): + # GH#66550 the same wrap at the bottom of the range. US/Pacific is west of + # UTC, so Timestamp.min's wall time there is below Timestamp.min. + dti = _utc_dti(pd.Timestamp.min._value).tz_convert("US/Pacific") + + with pytest.raises(OutOfBoundsDatetime, match="underflows past"): + dti.tz_localize(None) + + +def test_dti_utc_to_local_overflow_message_names_the_target_tz(): + # GH#66550 the only value left to render is the in-bounds UTC instant, so + # without the target tz the message complains about a value that looks fine. + dti = _utc_dti(pd.Timestamp.max._value).tz_convert("Etc/GMT-9") + + msg = "Converting 2262-04-11 23:47:16 to Etc/GMT-9 overflows past" + with pytest.raises(OutOfBoundsDatetime, match=msg): + dti.tz_localize(None) + + +@td.skip_if_windows # `tm.set_timezone` does not work on Windows +@pytest.mark.skipif(WASM, reason="`tm.set_timezone` does not work on WASM") +@td.skip_if_32bit # OverflowError inside tzlocal past 2038 +def test_dti_utc_to_local_overflow_tzlocal(): + # GH#66550 the tzlocal branch of the shift needs the same guard. Pin the + # ambient zone: the wall time only overflows east of UTC. + dti = _utc_dti(pd.Timestamp.max._value) + + with tm.set_timezone("Asia/Tokyo"): + dti = dti.tz_convert(dateutil.tz.tzlocal()) + with pytest.raises(OutOfBoundsDatetime, match="overflows past"): + dti.tz_localize(None) + + +def test_dti_utc_to_local_at_the_boundary_still_converts(): + # GH#66550 one step in from the wrap, and eastward, must keep working + dti = _utc_dti(pd.Timestamp.max._value - 2 * 3600 * 10**9).tz_convert( + "Europe/Berlin" + ) + + result = dti.tz_localize(None) + expected = pd.DatetimeIndex([pd.Timestamp("2262-04-11 23:47:16.854775807")]) + tm.assert_index_equal(result, expected) + + +@pytest.fixture +def dti_local_on_sentinel(): + # A UTC instant that is representable, but whose wall time one hour west of + # UTC is exactly the NaT sentinel. + return ( + pd.DatetimeIndex(np.array([iNaT + 3600 * 10**9], dtype="i8").view("M8[ns]")) + .tz_localize("UTC") + .tz_convert(timezone(timedelta(hours=-1))) + ) + + +@pytest.mark.parametrize( + "func, msg", + [ + (lambda dti: dti.tz_localize(None), "underflows past"), + (lambda dti: dti.year, "underflows past"), + (lambda dti: dti.floor("D"), "underflows past"), + # to_period rejects the wall time as out of bounds for the frequency + # before it gets as far as an ordinal + (lambda dti: dti.to_period("ns"), "Out of bounds nanosecond timestamp"), + ], + ids=["tz_localize", "year", "floor", "to_period_ns"], +) +@pytest.mark.filterwarnings("ignore:Converting to PeriodArray:UserWarning") +def test_dti_local_on_sentinel_raises_where_stored(dti_local_on_sentinel, func, msg): + # GH#66550 the wall time is fine to render, but these consumers store it in + # an i8 buffer where the sentinel reads back as NaT -- tz_localize(None) and + # to_period("ns") silently returned NaT, and the field accessors returned -1. + with pytest.raises(OutOfBoundsDatetime, match=msg): + func(dti_local_on_sentinel) + + +@pytest.mark.filterwarnings("ignore:Converting to PeriodArray:UserWarning") +def test_dti_local_on_sentinel_still_renders(dti_local_on_sentinel): + # GH#66550 ... but the consumers that only render it are correct today and + # must stay that way. + dti = dti_local_on_sentinel + # datetime has no nanoseconds, so to_pydatetime stops at the microsecond + assert str(dti.to_pydatetime()[0]).startswith("1677-09-21 00:12:43.145224") + assert str(dti.astype(object)[0]).startswith("1677-09-21 00:12:43.145224192") + assert dti.strftime("%Y-%m-%d")[0] == "1677-09-21" + assert dti.to_period("D")[0] == pd.Period("1677-09-21", "D") + assert dti.resolution == "nanosecond" + assert not dti.is_normalized + + +@pytest.mark.parametrize( + "tz", [None, "UTC", "US/Pacific", "Etc/GMT-9", timezone(timedelta(hours=-1))] +) +def test_dti_all_nat_is_normalized(tz): + # GH#66550 is_date_array_normalized is the one Localizer loop that does not + # skip NaT before shifting, so the guarded shift needs an explicit exit that + # keeps reporting False rather than flipping an all-NaT array to True. + dti = pd.DatetimeIndex([pd.NaT, pd.NaT]) + if tz is not None: + dti = dti.tz_localize(tz) + + assert not dti.is_normalized diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_tz_localize.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_tz_localize.py new file mode 100644 index 0000000000000000000000000000000000000000..76eb043ce6f99eccbb9634e8b993511c6d49e8ba --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_tz_localize.py @@ -0,0 +1,653 @@ +from datetime import ( + UTC, + datetime, + timedelta, + timezone, +) +from io import BytesIO +import struct +from zoneinfo import ZoneInfo + +import dateutil.tz +from dateutil.tz import gettz +import numpy as np +import pytest + +from pandas.compat import WASM +from pandas.errors import ( + OutOfBoundsDatetime, + Pandas4Warning, +) +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture(params=["pytz/US/Eastern", gettz("US/Eastern"), ZoneInfo("US/Eastern")]) +def tz(request): + if isinstance(request.param, str) and request.param.startswith("pytz/"): + pytz = pytest.importorskip("pytz") + return pytz.timezone(request.param.removeprefix("pytz/")) + return request.param + + +class TestTZLocalize: + def test_tz_localize_shift_onto_nat_sentinel(self, unit): + # GH#66550 Asia/Tokyo's pre-1888 LMT offset is +9:18:59, so this wall + # time shifts to exactly the NaT sentinel. _get_utc_bounds handed that + # value to bisect_right_i8, which requires val >= tdata[0] (one above + # the sentinel), so the following deltas lookup read out of bounds and + # the result was misreported as a nonexistent time. + lmt = np.timedelta64(9 * 3600 + 18 * 60 + 59, "s") + lmt_offset = int(lmt // np.timedelta64(1, unit)) + dti = pd.DatetimeIndex([np.datetime64(-(2**63) + lmt_offset, unit)]) + with pytest.raises(OutOfBoundsDatetime, match="underflows past"): + dti.tz_localize("Asia/Tokyo") + + @pytest.mark.parametrize( + "kwargs", [{}, {"nonexistent": "NaT"}, {"nonexistent": "shift_forward"}] + ) + def test_tz_localize_overflow_past_last_cached_transition(self, kwargs): + # GH#65733 the zoneinfo fallback used past the last cached DST transition + # wrapped instead of reporting an out-of-bounds UTC instant, so an + # ordinary wall time came back as NaT + dti = pd.DatetimeIndex( + [pd.Timestamp(pd.Timestamp.max._value - 2 * 3600 * 10**9)] + ) + + with pytest.raises(OutOfBoundsDatetime, match="overflows past"): + dti.tz_localize("America/New_York", **kwargs) + + @pytest.mark.parametrize( + "tz", [timezone(timedelta(hours=9)), ZoneInfo("Etc/GMT-9")] + ) + def test_tz_localize_fixed_offset_shift_onto_nat_sentinel(self, tz): + # GH#66550 a shift landing exactly on the NaT sentinel is one below the + # minimum representable value, so it underflows. The fixed-offset loop + # only checked for int64 wrap, so it stored the sentinel and the wall time + # read back as missing data. + dti = pd.DatetimeIndex( + np.array([-(2**63) + 9 * 3600 * 10**9], dtype="i8").view("M8[ns]") + ) + + with pytest.raises(OutOfBoundsDatetime, match="underflows past"): + dti.tz_localize(tz) + + @pytest.mark.parametrize( + "tz", [timezone(timedelta(hours=-5)), ZoneInfo("Etc/GMT+5")] + ) + def test_tz_localize_overflow_fixed_offset(self, tz): + # GH#65733 the fixed-offset loop in tz_localize_to_utc shifted to UTC with a + # bare subtraction, so a wall time whose UTC instant is past Timestamp.max + # wrapped to a negative year instead of raising. Needs >= 2 values: for a + # length-1 result DatetimeIndex.tz_localize boxes the lone value, and that + # incidentally catches the overflow downstream. + val = pd.Timestamp.max._value - 2 * 3600 * 10**9 + dti = pd.DatetimeIndex(np.array([val, val - 10**9], dtype="i8").view("M8[ns]")) + + with pytest.raises(OutOfBoundsDatetime, match="overflows past"): + dti.tz_localize(tz) + + @td.skip_if_windows # `tm.set_timezone` does not work on Windows + @pytest.mark.skipif(WASM, reason="`tm.set_timezone` does not work on WASM") + def test_tz_localize_tzlocal_shift_onto_nat_sentinel(self): + # GH#66550 the tzlocal loop needs the same sentinel guard as the + # fixed-offset one above. Pin the ambient zone to +9 so the shift lands + # exactly on the sentinel. + dti = pd.DatetimeIndex( + np.array([-(2**63) + 9 * 3600 * 10**9], dtype="i8").view("M8[ns]") + ) + + with tm.set_timezone("Asia/Tokyo"): + with pytest.raises(OutOfBoundsDatetime, match="underflows past"): + dti.tz_localize(dateutil.tz.tzlocal()) + + @td.skip_if_windows # `tm.set_timezone` does not work on Windows + @pytest.mark.skipif(WASM, reason="`tm.set_timezone` does not work on WASM") + @td.skip_if_32bit # OverflowError inside tzlocal past 2038 + def test_tz_localize_overflow_tzlocal(self): + # GH#65733 same bare-subtraction overflow in the tzlocal loop. Pin the + # ambient zone: the shift only overflows west of UTC. + val = pd.Timestamp.max._value - 2 * 3600 * 10**9 + dti = pd.DatetimeIndex(np.array([val, val - 10**9], dtype="i8").view("M8[ns]")) + + with tm.set_timezone("US/Eastern"): + with pytest.raises(OutOfBoundsDatetime, match="overflows past"): + dti.tz_localize(dateutil.tz.tzlocal()) + + def test_tz_localize_invalidates_freq(self): + # we only preserve freq in unambiguous cases + + # if localized to US/Eastern, this crosses a DST transition + dti = pd.date_range("2014-03-08 23:00", "2014-03-09 09:00", freq="h") + assert dti.freq == "h" + + result = dti.tz_localize(None) # no-op + assert result.freq == "h" + + result = dti.tz_localize("UTC") # unambiguous freq preservation + assert result.freq == "h" + + result = dti.tz_localize("US/Eastern", nonexistent="shift_forward") + assert result.freq is None + assert result.inferred_freq is None # i.e. we are not _too_ strict here + + # Case where we _can_ keep freq because we're length==1 + dti2 = dti[:1] + result = dti2.tz_localize("US/Eastern") + assert result.freq == "h" + + def test_tz_localize_utc_copies(self, utc_fixture): + # GH#46460 + times = ["2015-03-08 01:00", "2015-03-08 02:00", "2015-03-08 03:00"] + index = pd.DatetimeIndex(times) + + res = index.tz_localize(utc_fixture) + assert not tm.shares_memory(res, index) + + res2 = index._data.tz_localize(utc_fixture) + assert not tm.shares_memory(index._data, res2) + + def test_dti_tz_localize_nonexistent_raise_coerce(self): + # GH#13057 + times = ["2015-03-08 01:00", "2015-03-08 02:00", "2015-03-08 03:00"] + index = pd.DatetimeIndex(times) + tz = "US/Eastern" + with pytest.raises(ValueError, match="|".join(times)): + index.tz_localize(tz=tz) + + with pytest.raises(ValueError, match="|".join(times)): + index.tz_localize(tz=tz, nonexistent="raise") + + result = index.tz_localize(tz=tz, nonexistent="NaT") + test_times = ["2015-03-08 01:00-05:00", "NaT", "2015-03-08 03:00-04:00"] + dti = pd.to_datetime(test_times, utc=True) + expected = dti.tz_convert("US/Eastern") + tm.assert_index_equal(result, expected) + + def test_dti_tz_localize_ambiguous_infer(self, tz): + # November 6, 2011, fall back, repeat 2 AM hour + # With no repeated hours, we cannot infer the transition + dr = pd.date_range(datetime(2011, 11, 6, 0), periods=5, freq=pd.offsets.Hour()) + with pytest.raises(ValueError, match="Cannot infer dst time"): + dr.tz_localize(tz) + + def test_dti_tz_localize_ambiguous_infer2(self, tz, unit): + # With repeated hours, we can infer the transition + dr = pd.date_range( + datetime(2011, 11, 6, 0), + periods=5, + freq=pd.offsets.Hour(), + tz=tz, + unit=unit, + ) + times = [ + "11/06/2011 00:00", + "11/06/2011 01:00", + "11/06/2011 01:00", + "11/06/2011 02:00", + "11/06/2011 03:00", + ] + di = pd.DatetimeIndex(times).as_unit(unit) + result = di.tz_localize(tz, ambiguous="infer") + expected = dr._with_freq(None) + tm.assert_index_equal(result, expected) + depr_msg = "The 'ambiguous' keyword in DatetimeIndex is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + result2 = pd.DatetimeIndex(times, tz=tz, ambiguous="infer").as_unit(unit) + tm.assert_index_equal(result2, expected) + + def test_dti_tz_localize_ambiguous_infer3(self, tz): + # When there is no dst transition, nothing special happens + dr = pd.date_range(datetime(2011, 6, 1, 0), periods=10, freq=pd.offsets.Hour()) + localized = dr.tz_localize(tz) + localized_infer = dr.tz_localize(tz, ambiguous="infer") + tm.assert_index_equal(localized, localized_infer) + + def test_dti_tz_localize_ambiguous_times(self, tz): + # March 13, 2011, spring forward, skip from 2 AM to 3 AM + dr = pd.date_range( + datetime(2011, 3, 13, 1, 30), periods=3, freq=pd.offsets.Hour() + ) + with pytest.raises(ValueError, match="2011-03-13 02:30:00"): + dr.tz_localize(tz) + + # after dst transition, it works + dr = pd.date_range( + datetime(2011, 3, 13, 3, 30), periods=3, freq=pd.offsets.Hour(), tz=tz + ) + + # November 6, 2011, fall back, repeat 2 AM hour + dr = pd.date_range( + datetime(2011, 11, 6, 1, 30), periods=3, freq=pd.offsets.Hour() + ) + with pytest.raises(ValueError, match="Cannot infer dst time"): + dr.tz_localize(tz) + + # UTC is OK + dr = pd.date_range( + datetime(2011, 3, 13), periods=48, freq=pd.offsets.Minute(30), tz=UTC + ) + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_dti_tz_localize_pass_dates_to_utc(self, tzstr): + strdates = ["1/1/2012", "3/1/2012", "4/1/2012"] + + idx = pd.DatetimeIndex(strdates) + conv = idx.tz_localize(tzstr) + + fromdates = pd.DatetimeIndex(strdates, tz=tzstr) + + assert conv.tz == fromdates.tz + tm.assert_numpy_array_equal(conv.asi8, fromdates.asi8) + + @pytest.mark.parametrize("prefix", ["", "dateutil/"]) + def test_dti_tz_localize(self, prefix): + tzstr = prefix + "US/Eastern" + dti = pd.date_range(start="1/1/2005", end="1/1/2005 0:00:02.256", freq="ms") + dti2 = dti.tz_localize(tzstr) + + dti_utc = pd.date_range( + start="1/1/2005 05:00", end="1/1/2005 5:00:02.256", freq="ms", tz="utc" + ) + + tm.assert_numpy_array_equal(dti2.to_numpy(), dti_utc.to_numpy()) + + dti3 = dti2.tz_convert(prefix + "US/Pacific") + tm.assert_numpy_array_equal(dti3.to_numpy(), dti_utc.to_numpy()) + + dti = pd.date_range(start="11/6/2011 1:59:59", end="11/6/2011 2:00", freq="ms") + with pytest.raises(ValueError, match="Cannot infer dst time"): + dti.tz_localize(tzstr) + + dti = pd.date_range(start="3/13/2011 1:59:59", end="3/13/2011 2:00", freq="ms") + with pytest.raises(ValueError, match="2011-03-13 02:00:00"): + dti.tz_localize(tzstr) + + def test_dti_tz_localize_utc_conversion(self, tz): + # Localizing to time zone should: + # 1) check for DST ambiguities + # 2) convert to UTC + + rng = pd.date_range("3/10/2012", "3/11/2012", freq="30min") + + converted = rng.tz_localize(tz) + expected_naive = rng + pd.offsets.Hour(5) + tm.assert_numpy_array_equal(converted.asi8, expected_naive.asi8) + + # DST ambiguity, this should fail + rng = pd.date_range("3/11/2012", "3/12/2012", freq="30min") + # Is this really how it should fail?? + with pytest.raises(ValueError, match="2012-03-11 02:00:00"): + rng.tz_localize(tz) + + def test_dti_tz_localize_roundtrip(self, tz_aware_fixture): + # note: this tz tests that a tz-naive index can be localized + # and de-localized successfully, when there are no DST transitions + # in the range. + idx = pd.date_range(start="2014-06-01", end="2014-08-30", freq="15min") + tz = tz_aware_fixture + localized = idx.tz_localize(tz) + # can't localize a tz-aware object + with pytest.raises( + TypeError, match="Already tz-aware, use tz_convert to convert" + ): + localized.tz_localize(tz) + reset = localized.tz_localize(None) + assert reset.tzinfo is None + expected = idx._with_freq(None) + tm.assert_index_equal(reset, expected) + + def test_dti_tz_localize_naive(self): + rng = pd.date_range("1/1/2011", periods=100, freq="h") + + conv = rng.tz_localize("US/Pacific") + exp = pd.date_range("1/1/2011", periods=100, freq="h", tz="US/Pacific") + + tm.assert_index_equal(conv, exp._with_freq(None)) + + def test_dti_tz_localize_tzlocal(self): + # GH#13583 + offset = dateutil.tz.tzlocal().utcoffset(datetime(2011, 1, 1)) + offset = int(offset.total_seconds() * 1000000000) + + dti = pd.date_range(start="2001-01-01", end="2001-03-01", unit="ns") + dti2 = dti.tz_localize(dateutil.tz.tzlocal()) + tm.assert_numpy_array_equal(dti2.asi8 + offset, dti.asi8) + + dti = pd.date_range( + start="2001-01-01", end="2001-03-01", tz=dateutil.tz.tzlocal(), unit="ns" + ) + dti2 = dti.tz_localize(None) + tm.assert_numpy_array_equal(dti2.asi8 - offset, dti.asi8) + + def test_dti_tz_localize_ambiguous_nat(self, tz): + times = [ + "11/06/2011 00:00", + "11/06/2011 01:00", + "11/06/2011 01:00", + "11/06/2011 02:00", + "11/06/2011 03:00", + ] + di = pd.DatetimeIndex(times) + localized = di.tz_localize(tz, ambiguous="NaT") + + times = [ + "11/06/2011 00:00", + np.nan, + np.nan, + "11/06/2011 02:00", + "11/06/2011 03:00", + ] + di_test = pd.DatetimeIndex(times, tz="US/Eastern") + + # left dtype is datetime64[ns, US/Eastern] + # right is datetime64[ns, tzfile('/usr/share/zoneinfo/US/Eastern')] + tm.assert_numpy_array_equal(di_test.asi8, localized.asi8) + + def test_dti_tz_localize_ambiguous_flags(self, tz, unit): + # November 6, 2011, fall back, repeat 2 AM hour + + # Pass in flags to determine right dst transition + dr = pd.date_range( + datetime(2011, 11, 6, 0), + periods=5, + freq=pd.offsets.Hour(), + tz=tz, + unit=unit, + ) + times = [ + "11/06/2011 00:00", + "11/06/2011 01:00", + "11/06/2011 01:00", + "11/06/2011 02:00", + "11/06/2011 03:00", + ] + + # Test tz_localize + di = pd.DatetimeIndex(times).as_unit(unit) + is_dst = [1, 1, 0, 0, 0] + localized = di.tz_localize(tz, ambiguous=is_dst) + expected = dr._with_freq(None) + tm.assert_index_equal(expected, localized, check_freq=False) + + depr_msg = "The 'ambiguous' keyword in DatetimeIndex is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + result = pd.DatetimeIndex(times, tz=tz, ambiguous=is_dst).as_unit(unit) + tm.assert_index_equal(result, expected) + + localized = di.tz_localize(tz, ambiguous=np.array(is_dst)) + tm.assert_index_equal(dr, localized, check_freq=False) + + localized = di.tz_localize(tz, ambiguous=np.array(is_dst).astype("bool")) + tm.assert_index_equal(dr, localized, check_freq=False) + + # Test constructor + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + localized = pd.DatetimeIndex(times, tz=tz, ambiguous=is_dst).as_unit(unit) + tm.assert_index_equal(dr, localized, check_freq=False) + + # Test duplicate times where inferring the dst fails + times += times + di = pd.DatetimeIndex(times).as_unit(unit) + + # When the sizes are incompatible, make sure error is raised + msg = "Length of ambiguous bool-array must be the same size as vals" + with pytest.raises(Exception, match=msg): + di.tz_localize(tz, ambiguous=is_dst) + + # When sizes are compatible and there are repeats ('infer' won't work) + is_dst = np.hstack((is_dst, is_dst)) + localized = di.tz_localize(tz, ambiguous=is_dst) + dr = dr.append(dr) + tm.assert_index_equal(dr, localized) + + def test_dti_tz_localize_ambiguous_flags2(self, tz): + # When there is no dst transition, nothing special happens + dr = pd.date_range(datetime(2011, 6, 1, 0), periods=10, freq=pd.offsets.Hour()) + is_dst = np.array([1] * 10) + localized = dr.tz_localize(tz) + localized_is_dst = dr.tz_localize(tz, ambiguous=is_dst) + tm.assert_index_equal(localized, localized_is_dst) + + def test_dti_tz_localize_bdate_range(self): + dr = pd.bdate_range("1/1/2009", "1/1/2010") + dr_utc = pd.bdate_range("1/1/2009", "1/1/2010", tz=UTC) + localized = dr.tz_localize(UTC) + tm.assert_index_equal(dr_utc, localized) + + @pytest.mark.parametrize( + "start_ts, tz, end_ts, shift", + [ + ["2015-03-29 02:20:00", "Europe/Warsaw", "2015-03-29 03:00:00", "forward"], + [ + "2015-03-29 02:20:00", + "Europe/Warsaw", + "2015-03-29 01:59:59.999999999", + "backward", + ], + [ + "2015-03-29 02:20:00", + "Europe/Warsaw", + "2015-03-29 03:20:00", + timedelta(hours=1), + ], + [ + "2015-03-29 02:20:00", + "Europe/Warsaw", + "2015-03-29 01:20:00", + timedelta(hours=-1), + ], + ["2018-03-11 02:33:00", "US/Pacific", "2018-03-11 03:00:00", "forward"], + [ + "2018-03-11 02:33:00", + "US/Pacific", + "2018-03-11 01:59:59.999999999", + "backward", + ], + [ + "2018-03-11 02:33:00", + "US/Pacific", + "2018-03-11 03:33:00", + timedelta(hours=1), + ], + [ + "2018-03-11 02:33:00", + "US/Pacific", + "2018-03-11 01:33:00", + timedelta(hours=-1), + ], + # GH#40705, GH#40915: shifting across the UTC+0 DST boundary + ["2021-03-28 01:20:00", "Europe/London", "2021-03-28 02:00:00", "forward"], + [ + "2021-03-28 01:20:00", + "Europe/London", + "2021-03-28 00:59:59.999999999", + "backward", + ], + [ + "2021-03-28 01:20:00", + "Europe/London", + "2021-03-28 02:20:00", + timedelta(hours=1), + ], + [ + "2021-03-28 01:20:00", + "Europe/London", + "2021-03-28 00:20:00", + timedelta(hours=-1), + ], + ], + ) + @pytest.mark.parametrize("tz_type", ["", "dateutil/"]) + def test_dti_tz_localize_nonexistent_shift( + self, start_ts, tz, end_ts, shift, tz_type, unit + ): + # GH#8917 + tz = tz_type + tz + if isinstance(shift, str): + shift = "shift_" + shift + dti = pd.DatetimeIndex([pd.Timestamp(start_ts)]).as_unit(unit) + result = dti.tz_localize(tz, nonexistent=shift) + expected = ( + pd.DatetimeIndex([pd.Timestamp(end_ts)]).tz_localize(tz).as_unit(unit) + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("offset", [-1, 1]) + def test_dti_tz_localize_nonexistent_shift_invalid(self, offset, warsaw): + # GH#8917 + tz = warsaw + dti = pd.DatetimeIndex([pd.Timestamp("2015-03-29 02:20:00")]) + msg = "The provided timedelta will relocalize on a nonexistent time" + with pytest.raises(ValueError, match=msg): + dti.tz_localize(tz, nonexistent=timedelta(seconds=offset)) + + def test_dti_tz_localize_nonexistent_shift_overflow(self): + # GH#66697 + dti = pd.DatetimeIndex(["2011-03-13 02:30"]).as_unit("ns") + + with pytest.raises(OutOfBoundsDatetime, match="overflows past"): + dti.tz_localize("US/Eastern", nonexistent=pd.Timedelta.max) + + @pytest.mark.parametrize( + "tz, start_ts", + [ + # US/Eastern has a DST rule past the last cached transition and + # America/Sao_Paulo does not, so the two reach the offset that + # applies by different routes + ("US/Eastern", "2011-03-13 02:30"), + ("America/Sao_Paulo", "2018-11-04 00:30"), + ], + ) + def test_dti_tz_localize_nonexistent_shift_utc_overflow(self, tz, start_ts): + # GH#66697 + ts = pd.Timestamp(start_ts).as_unit("ns") + dti = pd.DatetimeIndex([ts, ts]) + shift = pd.Timestamp.max - ts - pd.Timedelta(hours=1) + + with pytest.raises(OutOfBoundsDatetime, match="overflows past"): + dti.tz_localize(tz, nonexistent=shift) + + +@pytest.mark.parametrize( + "tz", + ["pytz/America/Phoenix", gettz("America/Phoenix"), ZoneInfo("America/Phoenix")], +) +def test_dti_tz_localize_nonexistent_shift_past_last_transition(tz): + # GH#66550 a shift landing past the last cached DST transition indexed the + # deltas array out of bounds, so the same call gave a different answer + # each time. Phoenix stopped observing DST, so its transitions end for + # every tz implementation; a negative UTC offset is needed to reach the bug. + if isinstance(tz, str): + pytz = pytest.importorskip("pytz") + tz = pytz.timezone(tz.removeprefix("pytz/")) + dti = pd.DatetimeIndex([pd.Timestamp("1967-04-30 02:30")]) + shift = pd.Timedelta(days=30_000) + + result = dti.tz_localize(tz, nonexistent=shift) + + expected = pd.DatetimeIndex([dti[0] + shift]).tz_localize(tz) + tm.assert_index_equal(result, expected) + tm.assert_index_equal(result, dti.tz_localize(tz, nonexistent=shift)) + + +def test_dti_tz_localize_nonexistent_timedelta_shift_onto_nat_sentinel(): + # GH#66697 shifting a nonexistent time to a wall time whose UTC instant is + # exactly the NaT sentinel, one below Timestamp.min, used to come back as a + # missing value. Asia/Tokyo's +9 offset is what makes the two line up. + dti = pd.DatetimeIndex([pd.Timestamp("1948-05-02 00:30")]).as_unit("ns") + jst = 9 * 3600 * 10**9 + shift = pd.Timedelta(pd.Timestamp.min._value - 1 + jst - dti.asi8[0], "ns") + + with pytest.raises(OutOfBoundsDatetime, match="underflows past"): + dti.tz_localize("Asia/Tokyo", nonexistent=shift) + + +def _make_tzfile_ending_in_spring_forward(filename): + """ + Build a UTC+11/UTC+12 zone whose final transition is a spring-forward. + + Real zones cannot be used here: a zone that ends this way exists in the IANA + database (e.g. Asia/Anadyr), but most builds of the tz files append a + sentinel transition at the 32-bit epoch rollover, which reuses the offset + already in effect and so hides the case entirely. + """ + abbrevs = b"+11\x00+12\x00" + # (utc offset in seconds, isdst, index into abbrevs) + ttinfos = [(39600, 0, 0), (43200, 0, 4)] + transitions = [ + (int(datetime(2010, 10, 30, 15, tzinfo=UTC).timestamp()), 0), + (int(datetime(2011, 3, 26, 15, tzinfo=UTC).timestamp()), 1), + ] + + data = b"TZif" + b"\x00" + b"\x00" * 15 + data += struct.pack(">6l", 0, 0, 0, len(transitions), len(ttinfos), len(abbrevs)) + data += b"".join(struct.pack(">l", trans) for trans, _ in transitions) + data += bytes(idx for _, idx in transitions) + data += b"".join(struct.pack(">lBB", *ttinfo) for ttinfo in ttinfos) + data += abbrevs + return dateutil.tz.tzfile(BytesIO(data), filename=filename) + + +def test_dti_tz_localize_nonexistent_shift_at_last_transition(): + # GH#66550 when the last transition is a spring-forward, the delta in effect + # after it puts the shifted wall time back before that transition; the + # offset from before it is the one that applies + tz = _make_tzfile_ending_in_spring_forward("/pandas-test/LastTransSpringForward") + dti = pd.DatetimeIndex([pd.Timestamp("2011-03-27 02:30")]) + + result = dti.tz_localize(tz, nonexistent="shift_backward") + + expected = pd.DatetimeIndex( + [pd.Timestamp("2011-03-27 01:59:59.999999")] + ).tz_localize(tz) + tm.assert_index_equal(result, expected) + assert result[0].utcoffset() == timedelta(hours=11) + + +@pytest.mark.parametrize("freq", ["D", "MS", "W-SUN", "BME"]) +def test_dti_tz_localize_preserves_non_tick_freq(freq): + # GH#36575 non-Tick offsets are defined in terms of wall times, which + # tz_localize leaves unchanged, so the freq is still valid + dti = pd.date_range("2020-03-01", periods=8, freq=freq) + + result = dti.tz_localize("Europe/London") + + expected = pd.date_range("2020-03-01", periods=8, freq=freq, tz="Europe/London") + tm.assert_index_equal(result, expected) + assert result.freq == freq + + # round-trip back to tz-naive also keeps the freq + assert result.tz_localize(None).freq == freq + + +def test_dti_tz_localize_non_tick_freq_invalidated_by_shift(): + # GH#36575 shifting nonexistent times changes the wall times, so the + # freq is no longer valid + dti = pd.date_range("2019-09-06", periods=4, freq="D") + + result = dti.tz_localize("America/Santiago", nonexistent="shift_forward") + + assert result[2] == pd.Timestamp("2019-09-08 01:00", tz="America/Santiago") + assert result.freq is None + + +@pytest.mark.parametrize( + "start, kwargs", + [ + # 2020-10-25 01:30 is ambiguous in Europe/London + ("2020-10-24 01:30", {"ambiguous": "NaT"}), + # 2020-03-29 01:30 does not exist in Europe/London + ("2020-03-28 01:30", {"nonexistent": "NaT"}), + ], +) +def test_dti_tz_localize_non_tick_freq_invalidated_by_nat(start, kwargs): + # GH#36575 introducing NaT invalidates the freq + dti = pd.date_range(start, periods=3, freq="D") + + result = dti.tz_localize("Europe/London", **kwargs) + + assert result.isna().any() + assert result.freq is None diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_unique.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_unique.py new file mode 100644 index 0000000000000000000000000000000000000000..013a7da13a61e0ed0897b0261de0b004663d0c2c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/methods/test_unique.py @@ -0,0 +1,73 @@ +from datetime import ( + datetime, + timedelta, +) + +import pandas as pd +import pandas._testing as tm + + +def test_unique(tz_naive_fixture): + idx = pd.DatetimeIndex(["2017"] * 2, tz=tz_naive_fixture) + expected = idx[:1] + + result = idx.unique() + tm.assert_index_equal(result, expected) + # GH#21737 + # Ensure the underlying data is consistent + assert result[0] == expected[0] + + +def test_index_unique(rand_series_with_duplicate_datetimeindex): + dups = rand_series_with_duplicate_datetimeindex + index = dups.index + + uniques = index.unique() + expected = pd.DatetimeIndex( + [ + datetime(2000, 1, 2), + datetime(2000, 1, 3), + datetime(2000, 1, 4), + datetime(2000, 1, 5), + ], + dtype=index.dtype, + ) + assert uniques.dtype == index.dtype # sanity + tm.assert_index_equal(uniques, expected) + assert index.nunique() == 4 + + # GH#2563 + assert isinstance(uniques, pd.DatetimeIndex) + + dups_local = index.tz_localize("US/Eastern") + dups_local.name = "foo" + result = dups_local.unique() + expected = pd.DatetimeIndex(expected, name="foo") + expected = expected.tz_localize("US/Eastern") + assert result.tz is not None + assert result.name == "foo" + tm.assert_index_equal(result, expected) + + +def test_index_unique2(): + # NaT, note this is excluded + arr = [1370745748 + t for t in range(20)] + [pd.NaT._value] + idx = pd.DatetimeIndex(arr * 3) + tm.assert_index_equal(idx.unique(), pd.DatetimeIndex(arr)) + assert idx.nunique() == 20 + assert idx.nunique(dropna=False) == 21 + + +def test_index_unique3(): + arr = [ + pd.Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20) + ] + [pd.NaT] + idx = pd.DatetimeIndex(arr * 3) + tm.assert_index_equal(idx.unique(), pd.DatetimeIndex(arr)) + assert idx.nunique() == 20 + assert idx.nunique(dropna=False) == 21 + + +def test_is_unique_monotonic(rand_series_with_duplicate_datetimeindex): + index = rand_series_with_duplicate_datetimeindex.index + assert not index.is_unique diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_arithmetic.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_arithmetic.py new file mode 100644 index 0000000000000000000000000000000000000000..62ef0f3457ba18b8af8073e4051a7a39c9e15874 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_arithmetic.py @@ -0,0 +1,73 @@ +# Arithmetic tests specific to DatetimeIndex are generally about `freq` +# retention or inference. Other arithmetic tests belong in +# tests/arithmetic/test_datetime64.py + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndexArithmetic: + def test_add_timedelta_preserves_freq(self): + # GH#37295 should hold for any DTI with freq=None or Tick freq + # GH#41943 as of pandas3 Tick does not include Day + tz = "Canada/Eastern" + dti = pd.date_range( + start=pd.Timestamp("2019-03-26 00:00:00-0400", tz=tz), + end=pd.Timestamp("2020-10-17 00:00:00-0400", tz=tz), + freq="12h", + ) + result = dti + pd.Timedelta(days=1) + assert result.freq == dti.freq + + def test_sub_datetime_preserves_freq(self, tz_naive_fixture): + # GH#48818 + # In pandas3 "D" preserves time-of-day across DST transitions, so + # is not preserved by subtraction. Ticks offsets like "24h" + # are still preserved + dti = pd.date_range( + "2016-01-01", + periods=12, + tz=tz_naive_fixture, + freq=pd.offsets.Hour(24), + ) + + res = dti - dti[0] + expected = pd.timedelta_range("0 Days", "11 Days", freq=pd.offsets.Hour(24)) + tm.assert_index_equal(res, expected) + assert res.freq == expected.freq + + def test_sub_datetime_preserves_freq_across_dst(self): + # GH#48818 + ts = pd.Timestamp("2016-03-11", tz="US/Pacific") + dti = pd.date_range(ts, periods=4, unit="ns") + + res = dti - dti[0] + expected = pd.TimedeltaIndex( + [ + pd.Timedelta(days=0), + pd.Timedelta(days=1), + pd.Timedelta(days=2), + pd.Timedelta(days=2, hours=23), + ], + dtype="m8[ns]", + ) + tm.assert_index_equal(res, expected) + assert res.freq == expected.freq + + def test_add_dti_day(self): + # GH#35388 + dti = pd.date_range("2020-03-28", periods=4, freq="D", tz="Europe/Berlin") + result = (dti + dti.freq)[:-1] + expected = dti[1:] + tm.assert_index_equal(result, expected, check_freq=False) + + def test_sub_timestamp_preserves_day_freq(self): + # GH#62094 + dti = pd.date_range("2021-01-01", periods=5, freq="D") + ts = pd.Timestamp("2020-01-01") + + result = dti - ts + + # The one crucial assertion: + assert isinstance(result, pd.TimedeltaIndex) + assert result.freq == dti.freq diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_constructors.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..fbab827d043d23e0fb3eb49954a23ea95fae2d6f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_constructors.py @@ -0,0 +1,1368 @@ +from __future__ import annotations + +from datetime import ( + datetime, + timedelta, + timezone, +) +from functools import partial +from operator import attrgetter +import zoneinfo + +import dateutil +import dateutil.tz +from dateutil.tz import gettz +import numpy as np +import pytest + +from pandas._libs.tslibs import ( + astype_overflowsafe, + timezones, +) +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import DatetimeArray + + +class TestDatetimeIndex: + def test_0d_raises(self): + # GH#69411 used to segfault + arr = np.array(1) + + msg = "Cannot construct DatetimeArray from 0-dim input" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(arr) + with pytest.raises(ValueError, match=msg): + DatetimeArray._from_sequence(arr) + + def test_from_dt64_unsupported_unit(self): + # GH#49292 + val = np.datetime64(1, "D") + result = pd.DatetimeIndex([val], tz="US/Pacific") + + expected = pd.DatetimeIndex([val.astype("M8[s]")], tz="US/Pacific") + tm.assert_index_equal(result, expected) + + def test_explicit_tz_none(self): + # GH#48659 + dti = pd.date_range("2016-01-01", periods=10, tz="UTC", unit="ns") + + msg = "Passed data is timezone-aware, incompatible with 'tz=None'" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(dti, tz=None) + + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(np.array(dti), tz=None) + + msg = "Cannot pass both a timezone-aware dtype and tz=None" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex([], dtype="M8[ns, UTC]", tz=None) + + def test_freq_validation_with_nat(self): + # GH#11587 make sure we get a useful error message when generate_range + # raises + msg = ( + "Inferred frequency None from passed values does not conform " + "to passed frequency D" + ) + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex([pd.NaT, pd.Timestamp("2011-01-01")], freq="D") + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex([pd.NaT, pd.Timestamp("2011-01-01")._value], freq="D") + + # TODO: better place for tests shared by DTI/TDI? + @pytest.mark.parametrize( + "index", + [ + pd.date_range("2016-01-01", periods=5, tz="US/Pacific", unit="ns"), + pd.timedelta_range("1 Day", periods=5), + ], + ) + def test_shallow_copy_inherits_array_freq(self, index): + # If we pass a DTA/TDA to shallow_copy and dont specify a freq, + # we should inherit the array's freq, not our own. + array = index._data + + arr = array[[0, 3, 2, 4, 1]] + + result = index._shallow_copy(arr) + assert result.freq is None + + def test_categorical_preserves_tz(self): + # GH#18664 retain tz when going DTI-->Categorical-->DTI + dti = pd.DatetimeIndex( + [pd.NaT, "2015-01-01", "1999-04-06 15:14:13", "2015-01-01"], tz="US/Eastern" + ) + + for dtobj in [dti, dti._data]: + # works for DatetimeIndex or DatetimeArray + + ci = pd.CategoricalIndex(dtobj) + carr = pd.Categorical(dtobj) + cser = pd.Series(ci) + + for obj in [ci, carr, cser]: + result = pd.DatetimeIndex(obj) + tm.assert_index_equal(result, dti) + + def test_dti_with_period_data_raises(self): + # GH#23675 + data = pd.PeriodIndex(["2016Q1", "2016Q2"], freq="Q") + + with pytest.raises(TypeError, match="PeriodDtype data is invalid"): + pd.DatetimeIndex(data) + + with pytest.raises(TypeError, match="PeriodDtype data is invalid"): + pd.to_datetime(data) + + with pytest.raises(TypeError, match="PeriodDtype data is invalid"): + pd.DatetimeIndex(pd.PeriodIndex(data)) + + with pytest.raises(TypeError, match="PeriodDtype data is invalid"): + pd.to_datetime(pd.PeriodIndex(data)) + + def test_dti_with_timedelta64_data_raises(self): + # GH#23675 deprecated, enforced in GH#29794 + data = np.array([0], dtype="m8[ns]") + msg = r"timedelta64\[ns\] cannot be converted to datetime64" + with pytest.raises(TypeError, match=msg): + pd.DatetimeIndex(data) + + with pytest.raises(TypeError, match=msg): + pd.to_datetime(data) + + with pytest.raises(TypeError, match=msg): + pd.DatetimeIndex(pd.TimedeltaIndex(data)) + + with pytest.raises(TypeError, match=msg): + pd.to_datetime(pd.TimedeltaIndex(data)) + + def test_constructor_from_sparse_array(self): + # https://github.com/pandas-dev/pandas/issues/35843 + values = [ + pd.Timestamp("2012-05-01T01:00:00.000000"), + pd.Timestamp("2016-05-01T01:00:00.000000"), + ] + arr = pd.arrays.SparseArray(values) + result = pd.Index(arr) + assert type(result) is pd.Index + assert result.dtype == arr.dtype + + def test_construction_caching(self): + df = pd.DataFrame( + { + "dt": pd.date_range("20130101", periods=3, unit="ns"), + "dttz": pd.date_range( + "20130101", periods=3, tz=zoneinfo.ZoneInfo("US/Eastern"), unit="ns" + ), + "dt_with_null": [ + pd.Timestamp("20130101"), + pd.NaT, + pd.Timestamp("20130103"), + ], + "dtns": pd.date_range("20130101", periods=3, freq="ns", unit="ns"), + } + ) + assert df.dttz.dtype.tz.key == "US/Eastern" + + @pytest.mark.parametrize( + "kwargs", + [{"tz": "dtype.tz"}, {"dtype": "dtype"}, {"dtype": "dtype", "tz": "dtype.tz"}], + ) + def test_construction_with_alt(self, kwargs, tz_aware_fixture): + tz = tz_aware_fixture + i = pd.date_range("20130101", periods=5, freq="h", tz=tz, unit="ns") + kwargs = {key: attrgetter(val)(i) for key, val in kwargs.items()} + result = pd.DatetimeIndex(i, **kwargs) + tm.assert_index_equal(i, result) + + @pytest.mark.parametrize( + "kwargs", + [{"tz": "dtype.tz"}, {"dtype": "dtype"}, {"dtype": "dtype", "tz": "dtype.tz"}], + ) + def test_construction_with_alt_tz_localize(self, kwargs, tz_aware_fixture): + tz = tz_aware_fixture + i = pd.date_range("20130101", periods=5, freq="h", tz=tz, unit="ns") + i = i._with_freq(None) + kwargs = {key: attrgetter(val)(i) for key, val in kwargs.items()} + + if "tz" in kwargs: + result = pd.DatetimeIndex(i.asi8, tz="UTC").tz_convert(kwargs["tz"]) + + expected = pd.DatetimeIndex(i, **kwargs) + tm.assert_index_equal(result, expected) + + # localize into the provided tz + i2 = pd.DatetimeIndex(i.tz_localize(None).asi8, tz="UTC") + expected = i.tz_localize(None).tz_localize("UTC") + tm.assert_index_equal(i2, expected) + + # incompat tz/dtype + msg = "cannot supply both a tz and a dtype with a tz" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex( + i.tz_localize(None).asi8, + dtype=i.dtype, + tz=zoneinfo.ZoneInfo("US/Hawaii"), + ) + + def test_construction_index_with_mixed_timezones(self): + # gh-11488: no tz results in DatetimeIndex + result = pd.Index( + [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")], name="idx" + ) + exp = pd.DatetimeIndex( + [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")], name="idx" + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is None + + # same tz results in DatetimeIndex + result = pd.Index( + [ + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.Timestamp("2011-01-02 10:00", tz="Asia/Tokyo"), + ], + name="idx", + ) + exp = pd.DatetimeIndex( + [pd.Timestamp("2011-01-01 10:00"), pd.Timestamp("2011-01-02 10:00")], + tz="Asia/Tokyo", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is not None + assert result.tz == exp.tz + + # same tz results in DatetimeIndex (DST) + result = pd.Index( + [ + pd.Timestamp("2011-01-01 10:00", tz="US/Eastern"), + pd.Timestamp("2011-08-01 10:00", tz="US/Eastern"), + ], + name="idx", + ) + exp = pd.DatetimeIndex( + [pd.Timestamp("2011-01-01 10:00"), pd.Timestamp("2011-08-01 10:00")], + tz="US/Eastern", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is not None + assert result.tz == exp.tz + + # Different tz results in Index(dtype=object) + result = pd.Index( + [ + pd.Timestamp("2011-01-01 10:00"), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + name="idx", + ) + exp = pd.Index( + [ + pd.Timestamp("2011-01-01 10:00"), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + dtype="object", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert not isinstance(result, pd.DatetimeIndex) + + result = pd.Index( + [ + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + name="idx", + ) + exp = pd.Index( + [ + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + dtype="object", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert not isinstance(result, pd.DatetimeIndex) + + msg = "Mixed timezones detected. Pass utc=True in to_datetime" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(["2013-11-02 22:00-05:00", "2013-11-03 22:00-06:00"]) + + # length = 1 + result = pd.Index([pd.Timestamp("2011-01-01")], name="idx") + exp = pd.DatetimeIndex([pd.Timestamp("2011-01-01")], name="idx") + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is None + + # length = 1 with tz + result = pd.Index( + [pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo")], name="idx" + ) + exp = pd.DatetimeIndex( + [pd.Timestamp("2011-01-01 10:00")], tz="Asia/Tokyo", name="idx" + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is not None + assert result.tz == exp.tz + + def test_construction_index_with_mixed_timezones_with_NaT(self): + # see gh-11488 + result = pd.Index( + [pd.NaT, pd.Timestamp("2011-01-01"), pd.NaT, pd.Timestamp("2011-01-02")], + name="idx", + ) + exp = pd.DatetimeIndex( + [pd.NaT, pd.Timestamp("2011-01-01"), pd.NaT, pd.Timestamp("2011-01-02")], + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is None + + # Same tz results in DatetimeIndex + result = pd.Index( + [ + pd.NaT, + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.NaT, + pd.Timestamp("2011-01-02 10:00", tz="Asia/Tokyo"), + ], + name="idx", + ) + exp = pd.DatetimeIndex( + [ + pd.NaT, + pd.Timestamp("2011-01-01 10:00"), + pd.NaT, + pd.Timestamp("2011-01-02 10:00"), + ], + tz="Asia/Tokyo", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is not None + assert result.tz == exp.tz + + # same tz results in DatetimeIndex (DST) + result = pd.Index( + [ + pd.Timestamp("2011-01-01 10:00", tz="US/Eastern"), + pd.NaT, + pd.Timestamp("2011-08-01 10:00", tz="US/Eastern"), + ], + name="idx", + ) + exp = pd.DatetimeIndex( + [ + pd.Timestamp("2011-01-01 10:00"), + pd.NaT, + pd.Timestamp("2011-08-01 10:00"), + ], + tz="US/Eastern", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is not None + assert result.tz == exp.tz + + # different tz results in Index(dtype=object) + result = pd.Index( + [ + pd.NaT, + pd.Timestamp("2011-01-01 10:00"), + pd.NaT, + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + name="idx", + ) + exp = pd.Index( + [ + pd.NaT, + pd.Timestamp("2011-01-01 10:00"), + pd.NaT, + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + dtype="object", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert not isinstance(result, pd.DatetimeIndex) + + result = pd.Index( + [ + pd.NaT, + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.NaT, + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + name="idx", + ) + exp = pd.Index( + [ + pd.NaT, + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.NaT, + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + dtype="object", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert not isinstance(result, pd.DatetimeIndex) + + # all NaT + result = pd.Index([pd.NaT, pd.NaT], name="idx") + exp = pd.DatetimeIndex([pd.NaT, pd.NaT], name="idx") + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is None + + def test_construction_dti_with_mixed_timezones(self): + # GH 11488 (not changed, added explicit tests) + + # no tz results in DatetimeIndex + result = pd.DatetimeIndex( + [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")], name="idx" + ) + exp = pd.DatetimeIndex( + [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")], name="idx" + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + + # same tz results in DatetimeIndex + result = pd.DatetimeIndex( + [ + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.Timestamp("2011-01-02 10:00", tz="Asia/Tokyo"), + ], + name="idx", + ) + exp = pd.DatetimeIndex( + [pd.Timestamp("2011-01-01 10:00"), pd.Timestamp("2011-01-02 10:00")], + tz="Asia/Tokyo", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + + # same tz results in DatetimeIndex (DST) + result = pd.DatetimeIndex( + [ + pd.Timestamp("2011-01-01 10:00", tz="US/Eastern"), + pd.Timestamp("2011-08-01 10:00", tz="US/Eastern"), + ], + name="idx", + ) + exp = pd.DatetimeIndex( + [pd.Timestamp("2011-01-01 10:00"), pd.Timestamp("2011-08-01 10:00")], + tz="US/Eastern", + name="idx", + ) + tm.assert_index_equal(result, exp, exact=True) + assert isinstance(result, pd.DatetimeIndex) + + # tz mismatch affecting to tz-aware raises TypeError/ValueError + + msg = "cannot be converted to datetime64" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex( + [ + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + name="idx", + ) + + # pre-2.0 this raised bc of awareness mismatch. in 2.0 with a tz# + # specified we behave as if this was called pointwise, so + # the naive Timestamp is treated as a wall time. + dti = pd.DatetimeIndex( + [ + pd.Timestamp("2011-01-01 10:00"), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + tz="Asia/Tokyo", + name="idx", + ) + expected = pd.DatetimeIndex( + [ + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern").tz_convert( + "Asia/Tokyo" + ), + ], + tz="Asia/Tokyo", + name="idx", + ) + tm.assert_index_equal(dti, expected) + + # pre-2.0 mixed-tz scalars raised even if a tz/dtype was specified. + # as of 2.0 we successfully return the requested tz/dtype + dti = pd.DatetimeIndex( + [ + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + tz="US/Eastern", + name="idx", + ) + expected = pd.DatetimeIndex( + [ + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo").tz_convert( + "US/Eastern" + ), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + tz="US/Eastern", + name="idx", + ) + tm.assert_index_equal(dti, expected) + + # same thing but pass dtype instead of tz + dti = pd.DatetimeIndex( + [ + pd.Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + pd.Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + dtype="M8[us, US/Eastern]", + name="idx", + ) + tm.assert_index_equal(dti, expected) + + def test_construction_base_constructor(self): + arr = [pd.Timestamp("2011-01-01"), pd.NaT, pd.Timestamp("2011-01-03")] + tm.assert_index_equal(pd.Index(arr), pd.DatetimeIndex(arr)) + tm.assert_index_equal(pd.Index(np.array(arr)), pd.DatetimeIndex(np.array(arr))) + + arr = [np.nan, pd.NaT, pd.Timestamp("2011-01-03")] + tm.assert_index_equal(pd.Index(arr), pd.DatetimeIndex(arr)) + tm.assert_index_equal(pd.Index(np.array(arr)), pd.DatetimeIndex(np.array(arr))) + + def test_construction_outofbounds(self): + # GH 13663 + dates = [ + datetime(3000, 1, 1), + datetime(4000, 1, 1), + datetime(5000, 1, 1), + datetime(6000, 1, 1), + ] + exp = pd.Index(dates, dtype="M8[us]") + res = pd.Index(dates) + tm.assert_index_equal(res, exp) + + pd.DatetimeIndex(dates) + + @pytest.mark.parametrize("data", [["1400-01-01"], [datetime(1400, 1, 1)]]) + def test_dti_date_out_of_range(self, data): + # GH#1475 + pd.DatetimeIndex(data) + + def test_construction_with_ndarray(self): + # GH 5152 + dates = [datetime(2013, 10, 7), datetime(2013, 10, 8), datetime(2013, 10, 9)] + data = pd.DatetimeIndex(dates, freq=pd.offsets.BDay()).values + result = pd.DatetimeIndex(data, freq=pd.offsets.BDay()) + expected = pd.DatetimeIndex( + ["2013-10-07", "2013-10-08", "2013-10-09"], dtype="M8[us]", freq="B" + ) + tm.assert_index_equal(result, expected) + + def test_integer_values_and_tz_interpreted_as_utc(self): + # GH-24559 + val = np.datetime64("2000-01-01 00:00:00", "ns") + values = np.array([val.view("i8")]) + + result = pd.DatetimeIndex(values).tz_localize("US/Central") + + expected = pd.DatetimeIndex(["2000-01-01T00:00:00"], dtype="M8[ns, US/Central]") + tm.assert_index_equal(result, expected) + + # but UTC is *not* deprecated. + with tm.assert_produces_warning(None): + result = pd.DatetimeIndex(values, tz="UTC") + expected = pd.DatetimeIndex(["2000-01-01T00:00:00"], dtype="M8[ns, UTC]") + tm.assert_index_equal(result, expected) + + def test_constructor_coverage(self): + msg = r"DatetimeIndex\(\.\.\.\) must be called with a collection" + with pytest.raises(TypeError, match=msg): + pd.DatetimeIndex("1/1/2000") + + # generator expression + gen = (datetime(2000, 1, 1) + timedelta(i) for i in range(10)) + result = pd.DatetimeIndex(gen) + expected = pd.DatetimeIndex( + [datetime(2000, 1, 1) + timedelta(i) for i in range(10)] + ) + tm.assert_index_equal(result, expected) + + # NumPy string array + strings = np.array(["2000-01-01", "2000-01-02", "2000-01-03"]) + result = pd.DatetimeIndex(strings) + expected = pd.DatetimeIndex(strings.astype("O")) + tm.assert_index_equal(result, expected) + + from_ints = pd.DatetimeIndex(expected.as_unit("ns").asi8).as_unit("us") + tm.assert_index_equal(from_ints, expected) + + # string with NaT + strings = np.array(["2000-01-01", "2000-01-02", "NaT"]) + result = pd.DatetimeIndex(strings) + expected = pd.DatetimeIndex(strings.astype("O")) + tm.assert_index_equal(result, expected) + + from_ints = pd.DatetimeIndex(expected.as_unit("ns").asi8).as_unit("us") + tm.assert_index_equal(from_ints, expected) + + # non-conforming + msg = ( + "Inferred frequency None from passed values does not conform " + "to passed frequency D" + ) + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-04"], freq="D") + + @pytest.mark.parametrize("freq", ["YS", "W-SUN"]) + def test_constructor_datetime64_tzformat(self, freq): + # see GH#6572: ISO 8601 format results in stdlib timezone object + idx = pd.date_range( + "2013-01-01T00:00:00-05:00", "2016-01-01T23:59:59-05:00", freq=freq + ) + expected = pd.date_range( + "2013-01-01T00:00:00", + "2016-01-01T23:59:59", + freq=freq, + tz=timezone(timedelta(minutes=-300)), + ) + tm.assert_index_equal(idx, expected) + # Unable to use `US/Eastern` because of DST + expected_i8 = pd.date_range( + "2013-01-01T00:00:00", "2016-01-01T23:59:59", freq=freq, tz="America/Lima" + ) + tm.assert_numpy_array_equal(idx.asi8, expected_i8.asi8) + + idx = pd.date_range( + "2013-01-01T00:00:00+09:00", "2016-01-01T23:59:59+09:00", freq=freq + ) + expected = pd.date_range( + "2013-01-01T00:00:00", + "2016-01-01T23:59:59", + freq=freq, + tz=timezone(timedelta(minutes=540)), + ) + tm.assert_index_equal(idx, expected) + expected_i8 = pd.date_range( + "2013-01-01T00:00:00", "2016-01-01T23:59:59", freq=freq, tz="Asia/Tokyo" + ) + tm.assert_numpy_array_equal(idx.asi8, expected_i8.asi8) + + # Non ISO 8601 format results in dateutil.tz.tzoffset + idx = pd.date_range( + "2013/1/1 0:00:00-5:00", "2016/1/1 23:59:59-5:00", freq=freq + ) + expected = pd.date_range( + "2013-01-01T00:00:00", + "2016-01-01T23:59:59", + freq=freq, + tz=timezone(timedelta(minutes=-300)), + ) + tm.assert_index_equal(idx, expected) + # Unable to use `US/Eastern` because of DST + expected_i8 = pd.date_range( + "2013-01-01T00:00:00", "2016-01-01T23:59:59", freq=freq, tz="America/Lima" + ) + tm.assert_numpy_array_equal(idx.asi8, expected_i8.asi8) + + idx = pd.date_range( + "2013/1/1 0:00:00+9:00", "2016/1/1 23:59:59+09:00", freq=freq + ) + expected = pd.date_range( + "2013-01-01T00:00:00", + "2016-01-01T23:59:59", + freq=freq, + tz=timezone(timedelta(minutes=540)), + ) + tm.assert_index_equal(idx, expected) + expected_i8 = pd.date_range( + "2013-01-01T00:00:00", "2016-01-01T23:59:59", freq=freq, tz="Asia/Tokyo" + ) + tm.assert_numpy_array_equal(idx.asi8, expected_i8.asi8) + + def test_constructor_dtype(self): + # passing a dtype with a tz should localize + idx = pd.DatetimeIndex( + ["2013-01-01", "2013-01-02"], dtype="datetime64[ns, US/Eastern]" + ) + expected = ( + pd.DatetimeIndex(["2013-01-01", "2013-01-02"]) + .as_unit("ns") + .tz_localize("US/Eastern") + ) + tm.assert_index_equal(idx, expected) + + idx = pd.DatetimeIndex(["2013-01-01", "2013-01-02"], tz="US/Eastern").as_unit( + "ns" + ) + tm.assert_index_equal(idx, expected) + + def test_constructor_dtype_tz_mismatch_raises(self): + # if we already have a tz and its not the same, then raise + idx = pd.DatetimeIndex( + ["2013-01-01", "2013-01-02"], dtype="datetime64[ns, US/Eastern]" + ) + + msg = ( + "cannot supply both a tz and a timezone-naive dtype " + r"\(i\.e\. datetime64\[ns\]\)" + ) + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(idx, dtype="datetime64[ns]") + + # this is effectively trying to convert tz's + msg = "data is already tz-aware US/Eastern, unable to set specified tz: CET" + with pytest.raises(TypeError, match=msg): + pd.DatetimeIndex(idx, dtype="datetime64[ns, CET]") + msg = "cannot supply both a tz and a dtype with a tz" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(idx, tz="CET", dtype="datetime64[ns, US/Eastern]") + + result = pd.DatetimeIndex(idx, dtype="datetime64[ns, US/Eastern]") + tm.assert_index_equal(idx, result) + + @pytest.mark.parametrize("dtype", [object, np.int32, np.int64]) + def test_constructor_invalid_dtype_raises(self, dtype): + # GH 23986 + msg = "Unexpected value for 'dtype'" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex([1, 2], dtype=dtype) + + def test_000constructor_resolution(self): + # 2252 + t1 = pd.Timestamp((1352934390 * 1000000000) + 1000000 + 1000 + 1) + idx = pd.DatetimeIndex([t1]) + + assert idx.nanosecond[0] == t1.nanosecond + + def test_disallow_setting_tz(self): + # GH 3746 + dti = pd.DatetimeIndex(["2010"], tz="UTC") + msg = "Cannot directly set timezone" + with pytest.raises(AttributeError, match=msg): + dti.tz = zoneinfo.ZoneInfo("US/Pacific") + + @pytest.mark.parametrize( + "tz", + [ + None, + "America/Los_Angeles", + zoneinfo.ZoneInfo("America/Los_Angeles"), + pd.Timestamp("2000", tz="America/Los_Angeles").tz, + ], + ) + def test_constructor_start_end_with_tz(self, tz): + # GH 18595 + start = pd.Timestamp("2013-01-01 06:00:00", tz="America/Los_Angeles") + end = pd.Timestamp("2013-01-02 06:00:00", tz="America/Los_Angeles") + result = pd.date_range(freq="D", start=start, end=end, tz=tz, unit="ns") + expected = pd.DatetimeIndex( + ["2013-01-01 06:00:00", "2013-01-02 06:00:00"], + dtype="M8[ns, America/Los_Angeles]", + freq="D", + ) + tm.assert_index_equal(result, expected) + # Especially assert that the timezone is consistent for zoneinfo + assert zoneinfo.ZoneInfo("America/Los_Angeles") is result.tz + + @pytest.mark.parametrize("tz", ["US/Pacific", "US/Eastern", "Asia/Tokyo"]) + def test_constructor_with_non_normalized_pytz(self, tz): + # GH 18595 + pytz = pytest.importorskip("pytz") + tz_in = pytz.timezone(tz) + non_norm_tz = pd.Timestamp("2010", tz=tz_in).tz + result = pd.DatetimeIndex(["2010"], tz=non_norm_tz) + assert pytz.timezone(tz) is result.tz + + def test_constructor_timestamp_near_dst(self): + # GH 20854 + ts = [ + pd.Timestamp("2016-10-30 03:00:00+0300", tz="Europe/Helsinki"), + pd.Timestamp("2016-10-30 03:00:00+0200", tz="Europe/Helsinki"), + ] + result = pd.DatetimeIndex(ts).as_unit("ns") + expected = pd.DatetimeIndex( + [ts[0].to_pydatetime(), ts[1].to_pydatetime()] + ).as_unit("ns") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("klass", [pd.Index, pd.DatetimeIndex]) + @pytest.mark.parametrize("box", [np.array, partial(np.array, dtype=object), list]) + @pytest.mark.parametrize( + "tz, dtype", + [("US/Pacific", "datetime64[ns, US/Pacific]"), (None, "datetime64[ns]")], + ) + def test_constructor_with_int_tz(self, klass, box, tz, dtype): + # GH 20997, 20964 + ts = pd.Timestamp("2018-01-01", tz=tz).as_unit("ns") + result = klass(box([ts._value]), dtype=dtype) + expected = klass([ts]) + assert result == expected + + def test_construction_int_rountrip(self, tz_naive_fixture): + # GH 12619, GH#24559 + tz = tz_naive_fixture + + result = 1293858000000000000 + expected = pd.DatetimeIndex([result], tz=tz).asi8[0] + assert result == expected + + def test_construction_from_replaced_timestamps_with_dst(self): + # GH 18785 + index = pd.date_range( + pd.Timestamp(2000, 12, 31), + pd.Timestamp(2005, 12, 31), + freq="YE-DEC", + tz="Australia/Melbourne", + unit="ns", + ) + result = pd.DatetimeIndex([x.replace(month=6, day=1) for x in index]) + expected = pd.DatetimeIndex( + [ + "2000-06-01 00:00:00", + "2001-06-01 00:00:00", + "2002-06-01 00:00:00", + "2003-06-01 00:00:00", + "2004-06-01 00:00:00", + "2005-06-01 00:00:00", + ], + tz="Australia/Melbourne", + ).as_unit("ns") + tm.assert_index_equal(result, expected) + + def test_construction_with_tz_and_tz_aware_dti(self): + # GH 23579 + dti = pd.date_range("2016-01-01", periods=3, tz="US/Central") + msg = "data is already tz-aware US/Central, unable to set specified tz" + with pytest.raises(TypeError, match=msg): + pd.DatetimeIndex(dti, tz="Asia/Tokyo") + + def test_construction_with_nat_and_tzlocal(self): + tz = dateutil.tz.tzlocal() + result = pd.DatetimeIndex(["2018", "NaT"], tz=tz).as_unit("ns") + expected = pd.DatetimeIndex([pd.Timestamp("2018", tz=tz), pd.NaT]).as_unit("ns") + tm.assert_index_equal(result, expected) + + def test_constructor_with_ambiguous_keyword_arg(self): + # GH 35297 + + msg = "The 'ambiguous' keyword in DatetimeIndex is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = pd.DatetimeIndex( + ["2020-11-01 01:00:00", "2020-11-02 01:00:00"], + dtype="datetime64[ns, America/New_York]", + freq="D", + ambiguous=False, + ) + + # ambiguous keyword in start + timezone = "America/New_York" + start = pd.Timestamp(year=2020, month=11, day=1, hour=1).tz_localize( + timezone, ambiguous=False + ) + result = pd.date_range(start=start, periods=2, ambiguous=False, unit="ns") + tm.assert_index_equal(result, expected) + + # ambiguous keyword in end + timezone = "America/New_York" + end = pd.Timestamp(year=2020, month=11, day=2, hour=1).tz_localize( + timezone, ambiguous=False + ) + result = pd.date_range(end=end, periods=2, ambiguous=False, unit="ns") + tm.assert_index_equal(result, expected) + + def test_constructor_with_nonexistent_keyword_arg(self, warsaw): + # GH 35297 + timezone = warsaw + + # nonexistent keyword in start + start = pd.Timestamp("2015-03-29 02:30:00").tz_localize( + timezone, nonexistent="shift_forward" + ) + result = pd.date_range(start=start, periods=2, freq="h", unit="ns") + expected = pd.DatetimeIndex( + [ + pd.Timestamp("2015-03-29 03:00:00+02:00", tz=timezone), + pd.Timestamp("2015-03-29 04:00:00+02:00", tz=timezone), + ] + ).as_unit("ns") + + tm.assert_index_equal(result, expected, check_freq=False) + + # nonexistent keyword in end + end = start + result = pd.date_range(end=end, periods=2, freq="h", unit="ns") + expected = pd.DatetimeIndex( + [ + pd.Timestamp("2015-03-29 01:00:00+01:00", tz=timezone), + pd.Timestamp("2015-03-29 03:00:00+02:00", tz=timezone), + ] + ).as_unit("ns") + + tm.assert_index_equal(result, expected, check_freq=False) + + def test_constructor_no_precision_raises(self): + # GH-24753, GH-24739 + + msg = "with no precision is not allowed" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(["2000"], dtype="datetime64") + + msg = "The 'datetime64' dtype has no unit. Please pass in" + with pytest.raises(ValueError, match=msg): + pd.Index(["2000"], dtype="datetime64") + + def test_constructor_wrong_precision_raises(self): + dti = pd.DatetimeIndex(["2000"], dtype="datetime64[us]") + assert dti.dtype == "M8[us]" + assert dti[0] == pd.Timestamp(2000, 1, 1) + + def test_index_constructor_with_numpy_object_array_and_timestamp_tz_with_nan(self): + # GH 27011 + result = pd.Index( + np.array([pd.Timestamp("2019", tz="UTC"), np.nan], dtype=object) + ) + expected = pd.DatetimeIndex([pd.Timestamp("2019", tz="UTC"), pd.NaT]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "tz", [zoneinfo.ZoneInfo("US/Eastern"), gettz("US/Eastern")] + ) + def test_dti_from_tzaware_datetime(self, tz): + d = [datetime(2012, 8, 19, tzinfo=tz)] + + index = pd.DatetimeIndex(d) + assert timezones.tz_compare(index.tz, tz) + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_dti_tz_constructors(self, tzstr): + """Test different DatetimeIndex constructions with timezone + Follow-up of GH#4229 + """ + arr = ["11/10/2005 08:00:00", "11/10/2005 09:00:00"] + + idx1 = pd.to_datetime(arr).tz_localize(tzstr) + idx2 = pd.date_range( + start="2005-11-10 08:00:00", freq="h", periods=2, tz=tzstr, unit="us" + ) + idx2 = idx2._with_freq(None) # the others all have freq=None + idx3 = pd.DatetimeIndex(arr, tz=tzstr) + idx4 = pd.DatetimeIndex(np.array(arr), tz=tzstr) + + tm.assert_index_equal(idx1, idx2) + tm.assert_index_equal(idx1, idx3) + tm.assert_index_equal(idx1, idx4) + + def test_dti_construction_idempotent(self, unit): + rng = pd.date_range( + "03/12/2012 00:00", periods=10, freq="W-FRI", tz="US/Eastern", unit=unit + ) + rng2 = pd.DatetimeIndex(data=rng, tz="US/Eastern") + tm.assert_index_equal(rng, rng2) + + @pytest.mark.parametrize("prefix", ["", "dateutil/"]) + def test_dti_constructor_static_tzinfo(self, prefix): + # it works! + index = pd.DatetimeIndex([datetime(2012, 1, 1)], tz=prefix + "EST") + index.hour + index[0] + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_dti_convert_datetime_list(self, tzstr): + dr = pd.date_range("2012-06-02", periods=10, tz=tzstr, name="foo") + dr2 = pd.DatetimeIndex(list(dr), name="foo", freq="D") + tm.assert_index_equal(dr, dr2) + + @pytest.mark.parametrize( + "tz", + [ + "pytz/US/Eastern", + gettz("US/Eastern"), + ], + ) + @pytest.mark.parametrize("use_str", [True, False]) + @pytest.mark.parametrize("box_cls", [pd.Timestamp, pd.DatetimeIndex]) + def test_dti_ambiguous_matches_timestamp(self, tz, use_str, box_cls, request): + # GH#47471 check that we get the same raising behavior in the DTI + # constructor and Timestamp constructor + if isinstance(tz, str) and tz.startswith("pytz/"): + pytz = pytest.importorskip("pytz") + tz = pytz.timezone(tz.removeprefix("pytz/")) + dtstr = "2013-11-03 01:59:59.999999" + item = dtstr + if not use_str: + item = pd.Timestamp(dtstr).to_pydatetime() + if box_cls is not pd.Timestamp: + item = [item] + + if not use_str and isinstance(tz, dateutil.tz.tzfile): + # FIXME: The Timestamp constructor here behaves differently than all + # the other cases bc with dateutil/zoneinfo tzinfos we implicitly + # get fold=0. Having this raise is not important, but having the + # behavior be consistent across cases is. + mark = pytest.mark.xfail(reason="We implicitly get fold=0.") + request.applymarker(mark) + + with pytest.raises(ValueError, match=dtstr): + box_cls(item, tz=tz) + + @pytest.mark.parametrize("tz", [None, "UTC", "US/Pacific"]) + def test_dti_constructor_with_non_nano_dtype(self, tz): + # GH#55756, GH#54620 + ts = pd.Timestamp("2999-01-01") + dtype = "M8[us]" + if tz is not None: + dtype = f"M8[us, {tz}]" + vals = [ts, "2999-01-02 03:04:05.678910", 2500] + result = pd.DatetimeIndex(vals, dtype=dtype) + # The 2500 is interpreted as microseconds, consistent with what + # we would get if we created DatetimeIndexes from vals[:2] and vals[2:] + # and concated the results. + pointwise = [ + vals[0].tz_localize(tz), + pd.Timestamp(vals[1], tz=tz), + pd.to_datetime(vals[2], unit="us", utc=True).tz_convert(tz), + ] + exp_vals = [x.as_unit("us").asm8 for x in pointwise] + exp_arr = np.array(exp_vals, dtype="M8[us]") + expected = pd.DatetimeIndex(exp_arr, dtype="M8[us]") + if tz is not None: + expected = expected.tz_localize("UTC").tz_convert(tz) + tm.assert_index_equal(result, expected) + + result2 = pd.DatetimeIndex(np.array(vals, dtype=object), dtype=dtype) + tm.assert_index_equal(result2, expected) + + def test_dti_constructor_with_non_nano_now_today(self): + # GH#55756, GH#57535 + now = pd.Timestamp.now() # noqa: TID251 + today = pd.Timestamp.today() # noqa: TID251 + result = pd.DatetimeIndex(["now", "today"], dtype="M8[s]") + now_after = pd.Timestamp.now() # noqa: TID251 + assert result.dtype == "M8[s]" + + # result should be between the before/after timestamps + assert result[0] >= now.as_unit("s") + assert result[0] <= now_after.as_unit("s") + assert result[1] >= today.as_unit("s") + assert result[1] <= now_after.as_unit("s") + + def test_dti_constructor_object_float_matches_float_dtype(self): + # GH#55780 + arr = np.array([0, np.nan], dtype=np.float64) + arr2 = arr.astype(object) + + dti1 = pd.DatetimeIndex(arr, tz="CET") + dti2 = pd.DatetimeIndex(arr2, tz="CET") + tm.assert_index_equal(dti1, dti2) + + @pytest.mark.parametrize("dtype", ["M8[us]", "M8[us, US/Pacific]"]) + def test_dti_constructor_with_dtype_object_int_matches_int_dtype(self, dtype): + # Going through the object path should match the non-object path + + vals1 = np.arange(5, dtype="i8") * 1000 + vals1[0] = pd.NaT.value + + vals2 = vals1.astype(np.float64) + vals2[0] = np.nan + + vals3 = vals1.astype(object) + # change lib.infer_dtype(vals3) from "integer" so we go through + # array_to_datetime in _sequence_to_dt64 + vals3[0] = pd.NaT + + vals4 = vals2.astype(object) + + res1 = pd.DatetimeIndex(vals1, dtype=dtype) + res2 = pd.DatetimeIndex(vals2, dtype=dtype) + res3 = pd.DatetimeIndex(vals3, dtype=dtype) + res4 = pd.DatetimeIndex(vals4, dtype=dtype) + + expected = pd.DatetimeIndex(vals1.view("M8[us]")) + if res1.tz is not None: + expected = expected.tz_localize("UTC").tz_convert(res1.tz) + tm.assert_index_equal(res1, expected) + tm.assert_index_equal(res2, expected) + tm.assert_index_equal(res3, expected) + tm.assert_index_equal(res4, expected) + + +class TestTimeSeries: + def test_dti_constructor_preserve_dti_freq(self): + rng = pd.date_range("1/1/2000", "1/2/2000", freq="5min") + + rng2 = pd.DatetimeIndex(rng) + assert rng.freq == rng2.freq + + def test_explicit_none_freq(self): + # Explicitly passing freq=None is respected + rng = pd.date_range("1/1/2000", "1/2/2000", freq="5min") + + result = pd.DatetimeIndex(rng, freq=None) + assert result.freq is None + + result = pd.DatetimeIndex(rng._data, freq=None) + assert result.freq is None + + def test_constructor_equivalent_freq(self): + # GH#61086 - equivalent but not equal frequencies should be accepted + dti = pd.date_range("2020-02-01", freq="QS-MAY", periods=3) + + result = pd.DatetimeIndex(dti, freq="QS-FEB") + expected = pd.DatetimeIndex( + ["2020-02-01", "2020-05-01", "2020-08-01"], freq="QS-FEB" + ) + tm.assert_index_equal(result, expected) + + def test_constructor_equivalent_freq_raises(self): + # GH#61086 - non-equivalent frequencies should still raise + dti = pd.date_range("2020-02-01", freq="QS-MAY", periods=3) + + msg = "does not conform to passed frequency" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(dti, freq="QS-JAN") + + @pytest.mark.parametrize( + "data_freq, passed_freq", + [ + # Jan 2000 has 31 days, so the first month-start gap equals 31D/744h + ("MS", "31D"), + ("MS", "744h"), + # Apr 30 2000 is a Sunday, so ME data does not conform to BME even + # though the earlier month-end gaps happen to agree + ("ME", "BME"), + ], + ) + def test_constructor_freq_first_step_coincidence(self, data_freq, passed_freq): + # GH#65012 a passed freq that only agrees with the data on the first + # step must not be pinned; later steps diverge, so it does not conform + dti = pd.date_range("2000-01-01", freq=data_freq, periods=4) + + msg = "does not conform to passed frequency" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(dti, freq=passed_freq) + + def test_constructor_tick_freq_conforming_accepted(self): + # GH#65012 a Tick freq that differs from the inferred (non-Tick) freq + # but genuinely conforms is accepted via the uniform-spacing fast path + dti = pd.date_range("2000-01-01", freq="D", periods=5) # inferred Day + + result = pd.DatetimeIndex(dti, freq="24h") + assert result.freqstr == "24h" + + def test_constructor_tick_freq_tz_aware_across_dst_raises(self): + # GH#65012 a Tick is a fixed step in i8 space even across a DST + # transition, so the uniform-spacing check runs on the (UTC) i8 view + dti = pd.date_range("2021-03-13", freq="2h", periods=4, tz="US/Eastern") + + msg = "does not conform to passed frequency" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(dti, freq="3h") + + def test_constructor_tick_freq_subunit_resolution_raises(self): + # GH#65012 a Tick finer than the index resolution cannot conform even + # if it rounds to the data's step (1500ms -> 1s at second resolution) + dti = pd.date_range("2000-01-01", freq="s", periods=4).as_unit("s") + + msg = "does not conform to passed frequency" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(dti, freq="1500ms") + + def test_dti_constructor_small_int(self, any_int_numpy_dtype): + # see gh-13721 + exp = pd.DatetimeIndex( + [ + "1970-01-01 00:00:00.00000000", + "1970-01-01 00:00:00.00000001", + "1970-01-01 00:00:00.00000002", + ] + ) + + arr = np.array([0, 10, 20], dtype=any_int_numpy_dtype) + tm.assert_index_equal(pd.DatetimeIndex(arr), exp) + + def test_ctor_str_intraday(self): + rng = pd.DatetimeIndex(["1-1-2000 00:00:01"]) + assert rng[0].second == 1 + + def test_index_cast_datetime64_other_units(self): + arr = np.arange(0, 100, 10, dtype=np.int64).view("M8[D]") + idx = pd.Index(arr) + + assert (idx.values == astype_overflowsafe(arr, dtype=np.dtype("M8[ns]"))).all() + + def test_constructor_int64_nocopy(self): + # GH#1624 + arr = np.arange(1000, dtype=np.int64) + index = pd.DatetimeIndex(arr, copy=False) + + arr[50:100] = -1 + assert (index.asi8[50:100] == -1).all() + + arr = np.arange(1000, dtype=np.int64) + index = pd.DatetimeIndex(arr, copy=True) + + arr[50:100] = -1 + assert (index.asi8[50:100] != -1).all() + + @pytest.mark.parametrize( + "freq", + ["ME", "QE", "YE", "D", "B", "bh", "min", "s", "ms", "us", "h", "ns", "C"], + ) + def test_from_freq_recreate_from_data(self, freq): + org = pd.date_range(start="2001/02/01 09:00", freq=freq, periods=1) + idx = pd.DatetimeIndex(org, freq=freq) + tm.assert_index_equal(idx, org) + + org = pd.date_range( + start="2001/02/01 09:00", freq=freq, tz="US/Pacific", periods=1 + ) + idx = pd.DatetimeIndex(org, freq=freq, tz="US/Pacific") + tm.assert_index_equal(idx, org) + + def test_datetimeindex_constructor_misc(self): + arr = ["1/1/2005", "1/2/2005", "Jn 3, 2005", "2005-01-04"] + msg = r"(\(')?Unknown datetime string format(:', 'Jn 3, 2005'\))?" + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(arr) + + arr = ["1/1/2005", "1/2/2005", "1/3/2005", "2005-01-04"] + idx1 = pd.DatetimeIndex(arr) + + arr = [datetime(2005, 1, 1), "1/2/2005", "1/3/2005", "2005-01-04"] + idx2 = pd.DatetimeIndex(arr) + + arr = [pd.Timestamp(datetime(2005, 1, 1)), "1/2/2005", "1/3/2005", "2005-01-04"] + idx3 = pd.DatetimeIndex(arr) + + arr = np.array(["1/1/2005", "1/2/2005", "1/3/2005", "2005-01-04"], dtype="O") + idx4 = pd.DatetimeIndex(arr) + + depr_msg = "keyword in DatetimeIndex is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + idx5 = pd.DatetimeIndex(["12/05/2007", "25/01/2008"], dayfirst=True) + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + idx6 = pd.DatetimeIndex( + ["2007/05/12", "2008/01/25"], dayfirst=False, yearfirst=True + ) + tm.assert_index_equal(idx5, idx6) + + for other in [idx2, idx3, idx4]: + assert (idx1.values == other.values).all() + + def test_dti_constructor_object_dtype_dayfirst_yearfirst_with_tz(self): + # GH#55813 + val = "5/10/16" + + dfirst = pd.Timestamp(2016, 10, 5, tz="US/Pacific") + yfirst = pd.Timestamp(2005, 10, 16, tz="US/Pacific") + + depr_msg = "keyword in DatetimeIndex is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + result1 = pd.DatetimeIndex([val], tz="US/Pacific", dayfirst=True) + expected1 = pd.DatetimeIndex([dfirst]) + tm.assert_index_equal(result1, expected1) + + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + result2 = pd.DatetimeIndex([val], tz="US/Pacific", yearfirst=True) + expected2 = pd.DatetimeIndex([yfirst]) + tm.assert_index_equal(result2, expected2) + + +@pytest.mark.parametrize( + "kwarg, val", + [ + ("dayfirst", True), + ("dayfirst", False), + ("yearfirst", True), + ("yearfirst", False), + ("ambiguous", False), + ("ambiguous", True), + ("ambiguous", "infer"), + ("ambiguous", "NaT"), + ("ambiguous", "raise"), + ("ambiguous", np.array([True])), + ], +) +def test_dti_constructor_deprecated_keywords(kwarg, val): + # GH#55499 explicitly passing a keyword warns even with the default value + msg = f"The '{kwarg}' keyword in DatetimeIndex is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + pd.DatetimeIndex(["2020-01-01"], **{kwarg: val}) + + +def test_dti_freq_validation_wall_time_dst(): + # GH#55499 freq validation compares wall times, so wall-preserving freqs + # spanning a DST transition validate without the ambiguous keyword + vals = pd.DatetimeIndex(["2020-10-31 01:30", "2020-11-01 01:30"]).tz_localize( + "America/New_York", ambiguous=[False, False] + ) + + result = pd.DatetimeIndex(vals, freq="D") + assert result.freq == "D" + tm.assert_numpy_array_equal(result.asi8, vals.asi8) + + setter_result = vals.copy() + setter_result.freq = "D" + assert setter_result.freq == "D" + + msg = "does not conform to passed frequency" + with pytest.raises(ValueError, match=msg): + # Tick freq, so still validated against the UTC values + pd.DatetimeIndex(vals, freq="h") + + # non-Tick freq that does not conform in wall time still raises + naive = pd.DatetimeIndex(["2020-10-31 01:30", "2020-11-01 02:30"]) + with pytest.raises(ValueError, match=msg): + pd.DatetimeIndex(naive.tz_localize("America/New_York"), freq="D") + + +@pytest.mark.parametrize("tz", [zoneinfo.ZoneInfo("US/Eastern"), gettz("US/Eastern")]) +@pytest.mark.parametrize( + "dtstr", + [ + "11/5/2023 01:30", # DST-ambiguous wall time + "3/12/2023 02:30", # nonexistent wall time + ], +) +def test_dti_noniso_dst_transition_matches_timestamp(dtstr, tz): + # GH#66123 dateutil-parsed (non-ISO) strings at ambiguous/nonexistent + # wall times resolve via fold=0 like Timestamp and datetime objects, + # rather than raising like ISO strings + expected = pd.Timestamp(dtstr, tz=tz) + result = pd.DatetimeIndex([dtstr], tz=tz) + assert result[0] == expected + + +def test_dti_noniso_ambiguous_pytz_raises(): + # GH#66123 with pytz, dateutil-parsed strings at ambiguous wall times + # raise, matching the Timestamp constructor + pytz = pytest.importorskip("pytz") + tz = pytz.timezone("US/Eastern") + dtstr = "11/5/2023 01:30" + with pytest.raises(ValueError, match="2023-11-05 01:30:00"): + pd.Timestamp(dtstr, tz=tz) + with pytest.raises(ValueError, match="2023-11-05 01:30:00"): + pd.DatetimeIndex([dtstr], tz=tz) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_date_range.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_date_range.py new file mode 100644 index 0000000000000000000000000000000000000000..3ecfa40622e11b5a5ceee0b691b516d10afd6984 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_date_range.py @@ -0,0 +1,2148 @@ +""" +test date_range, bdate_range construction from the convenience range functions +""" + +from datetime import ( + datetime, + time, + timedelta, +) +import re + +import numpy as np +import pytest + +from pandas._libs.tslibs import timezones +from pandas._libs.tslibs.offsets import ( + BDay, + CDay, + DateOffset, + MonthEnd, + prefix_mapping, +) +from pandas.errors import ( + OutOfBoundsDatetime, + Pandas4Warning, +) +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays.datetimes import _generate_range as generate_range +from pandas.tests.indexes.datetimes.test_timezones import ( + FixedOffset, + fixed_off_no_name, +) + +from pandas.tseries.holiday import USFederalHolidayCalendar + +START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) + + +def _get_expected_range( + begin_to_match, + end_to_match, + both_range, + inclusive_endpoints, +): + """Helper to get expected range from a both inclusive range""" + left_match = begin_to_match == both_range[0] + right_match = end_to_match == both_range[-1] + + if inclusive_endpoints == "left" and right_match: + expected_range = both_range[:-1] + elif inclusive_endpoints == "right" and left_match: + expected_range = both_range[1:] + elif inclusive_endpoints == "neither" and left_match and right_match: + expected_range = both_range[1:-1] + elif inclusive_endpoints == "neither" and right_match: + expected_range = both_range[:-1] + elif inclusive_endpoints == "neither" and left_match: + expected_range = both_range[1:] + elif inclusive_endpoints == "both": + expected_range = both_range[:] + else: + expected_range = both_range[:] + + return expected_range + + +class TestTimestampEquivDateRange: + # Older tests in TestTimeSeries constructed their `stamp` objects + # using `date_range` instead of the `Timestamp` constructor. + # TestTimestampEquivDateRange checks that these are equivalent in the + # pertinent cases. + + def test_date_range_timestamp_equiv(self): + rng = pd.date_range("20090415", "20090519", tz="US/Eastern") + stamp = rng[0] + + ts = pd.Timestamp("20090415", tz="US/Eastern") + assert ts == stamp + + def test_date_range_timestamp_equiv_dateutil(self): + rng = pd.date_range("20090415", "20090519", tz="dateutil/US/Eastern") + stamp = rng[0] + + ts = pd.Timestamp("20090415", tz="dateutil/US/Eastern") + assert ts == stamp + + def test_date_range_timestamp_equiv_explicit_pytz(self): + pytz = pytest.importorskip("pytz") + rng = pd.date_range("20090415", "20090519", tz=pytz.timezone("US/Eastern")) + stamp = rng[0] + + ts = pd.Timestamp("20090415", tz=pytz.timezone("US/Eastern")) + assert ts == stamp + + @td.skip_if_windows + def test_date_range_timestamp_equiv_explicit_dateutil(self): + from pandas._libs.tslibs.timezones import dateutil_gettz as gettz + + rng = pd.date_range("20090415", "20090519", tz=gettz("US/Eastern")) + stamp = rng[0] + + ts = pd.Timestamp("20090415", tz=gettz("US/Eastern")) + assert ts == stamp + + def test_date_range_timestamp_equiv_from_datetime_instance(self): + datetime_instance = datetime(2014, 3, 4) + # build a timestamp with a frequency, since then it supports + # addition/subtraction of integers + timestamp_instance = pd.date_range(datetime_instance, periods=1, freq="D")[0] + + ts = pd.Timestamp(datetime_instance) + assert ts == timestamp_instance + + def test_date_range_timestamp_equiv_preserve_frequency(self): + timestamp_instance = pd.date_range("2014-03-05", periods=1, freq="D")[0] + ts = pd.Timestamp("2014-03-05") + + assert timestamp_instance == ts + + +class TestDateRanges: + def test_date_range_name(self): + idx = pd.date_range(start="2000-01-01", periods=1, freq="YE", name="TEST") + assert idx.name == "TEST" + + def test_date_range_invalid_periods(self): + msg = "periods must be an integer, got foo" + with pytest.raises(TypeError, match=msg): + pd.date_range(start="1/1/2000", periods="foo", freq="D") + + def test_date_range_fractional_period(self): + msg = "periods must be an integer" + with pytest.raises(TypeError, match=msg): + pd.date_range("1/1/2000", periods=10.5) + + @pytest.mark.parametrize("freq", ["2M", "1m", "2SM", "2BQ", "1bq", "2BY"]) + def test_date_range_frequency_M_SM_BQ_BY_raises(self, freq): + msg = f"Invalid frequency: {freq}" + + with pytest.raises(ValueError, match=msg): + pd.date_range("1/1/2000", periods=4, freq=freq) + + def test_date_range_tuple_freq_raises(self): + # GH#34703 + edate = datetime(2000, 1, 1) + with pytest.raises(TypeError, match="pass as a string instead"): + pd.date_range(end=edate, freq=("D", 5), periods=20) + + @pytest.mark.parametrize("freq", ["ns", "us", "ms", "min", "s", "h", "D"]) + def test_date_range_edges(self, freq): + # GH#13672 + td = pd.Timedelta(f"1{freq}") + ts = pd.Timestamp("1970-01-01") + exp_dtype = "M8[us]" if freq != "ns" else "M8[ns]" + + idx = pd.date_range( + start=ts + td, + end=ts + 4 * td, + freq=freq, + ) + exp = pd.DatetimeIndex( + [ts + n * td for n in range(1, 5)], + dtype=exp_dtype, + freq=freq, + ) + tm.assert_index_equal(idx, exp) + + # start after end + idx = pd.date_range( + start=ts + 4 * td, + end=ts + td, + freq=freq, + ) + exp = pd.DatetimeIndex([], dtype=exp_dtype, freq=freq) + tm.assert_index_equal(idx, exp) + + # start matches end + idx = pd.date_range( + start=ts + td, + end=ts + td, + freq=freq, + ) + exp = pd.DatetimeIndex([ts + td], dtype=exp_dtype, freq=freq) + tm.assert_index_equal(idx, exp) + + def test_date_range_near_implementation_bound(self): + # GH#24124 + freq = pd.Timedelta(1) + + with pytest.raises(OutOfBoundsDatetime, match="Cannot generate range with"): + pd.date_range(end=pd.Timestamp.min, periods=2, freq=freq) + + def test_date_range_nat(self): + # GH#11587 + msg = "Neither `start` nor `end` can be NaT" + with pytest.raises(ValueError, match=msg): + pd.date_range(start="2016-01-01", end=pd.NaT, freq="D") + with pytest.raises(ValueError, match=msg): + pd.date_range(start=pd.NaT, end="2016-01-01", freq="D") + + def test_date_range_multiplication_overflow(self): + # GH#24255 + # check that overflows in calculating `addend = periods * stride` + # are caught + with tm.assert_produces_warning(None): + # we should _not_ be seeing an overflow RuntimeWarning + dti = pd.date_range(start="1677-09-22", periods=213503, freq="D") + + assert dti[0] == pd.Timestamp("1677-09-22") + assert len(dti) == 213503 + + msg = "Cannot generate range with" + with pytest.raises(OutOfBoundsDatetime, match=msg): + pd.date_range("1969-05-04", periods=200000000, freq="30000D") + + def test_date_range_unsigned_overflow_handling(self): + # GH#24255 + # case where `addend = periods * stride` overflows int64 bounds + # but not uint64 bounds + dti = pd.date_range(start="1677-09-22", end="2262-04-11", freq="D") + + dti2 = pd.date_range(start=dti[0], periods=len(dti), freq="D") + assert dti2.equals(dti) + + dti3 = pd.date_range(end=dti[-1], periods=len(dti), freq="D") + assert dti3.equals(dti) + + def test_date_range_int64_overflow_non_recoverable(self): + # GH#24255 + # case with start later than 1970-01-01, overflow int64 but not uint64 + msg = "Cannot generate range with" + with pytest.raises(OutOfBoundsDatetime, match=msg): + pd.date_range(start="1970-02-01", periods=106752 * 24, freq="h", unit="ns") + + # case with end before 1970-01-01, overflow int64 but not uint64 + with pytest.raises(OutOfBoundsDatetime, match=msg): + pd.date_range(end="1969-11-14", periods=106752 * 24, freq="h", unit="ns") + + @pytest.mark.slow + @pytest.mark.parametrize( + "s_ts, e_ts", [("2262-02-23", "1969-11-14"), ("1970-02-01", "1677-10-22")] + ) + def test_date_range_int64_overflow_stride_endpoint_different_signs( + self, s_ts, e_ts + ): + # cases where stride * periods overflow int64 and stride/endpoint + # have different signs + start = pd.Timestamp(s_ts) + end = pd.Timestamp(e_ts) + + expected = pd.date_range(start=start, end=end, freq="-1h") + assert expected[0] == start + assert expected[-1] == end + + dti = pd.date_range(end=end, periods=len(expected), freq="-1h") + tm.assert_index_equal(dti, expected) + + def test_date_range_out_of_bounds(self): + # GH#14187 + msg = "Cannot generate range" + with pytest.raises(OutOfBoundsDatetime, match=msg): + pd.date_range("2016-01-01", periods=100000, freq="D", unit="ns") + with pytest.raises(OutOfBoundsDatetime, match=msg): + pd.date_range(end="1763-10-12", periods=100000, freq="D", unit="ns") + + def test_date_range_gen_error(self): + rng = pd.date_range("1/1/2000 00:00", "1/1/2000 00:18", freq="5min") + assert len(rng) == 4 + + def test_date_range_normalize(self): + snap = datetime(2011, 1, 1) + n = 50 + + rng = pd.date_range(snap, periods=n, normalize=False, freq="2D") + + offset = timedelta(2) + expected = pd.DatetimeIndex( + [snap + i * offset for i in range(n)], dtype="M8[us]", freq=offset + ) + + tm.assert_index_equal(rng, expected, check_freq=False) + + rng = pd.date_range("1/1/2000 08:15", periods=n, normalize=False, freq="B") + the_time = time(8, 15) + for val in rng: + assert val.time() == the_time + + def test_date_range_ambiguous_arguments(self): + # #2538 + start = datetime(2011, 1, 1, 5, 3, 40) + end = datetime(2011, 1, 1, 8, 9, 40) + + msg = ( + "Of the four parameters: start, end, periods, and " + "freq, exactly three must be specified" + ) + with pytest.raises(ValueError, match=msg): + pd.date_range(start, end, periods=10, freq="s") + + def test_date_range_convenience_periods(self, unit): + # GH 20808 + result = pd.date_range("2018-04-24", "2018-04-27", periods=3, unit=unit) + expected = pd.DatetimeIndex( + ["2018-04-24 00:00:00", "2018-04-25 12:00:00", "2018-04-27 00:00:00"], + dtype=f"M8[{unit}]", + freq=None, + ) + + tm.assert_index_equal(result, expected) + + # Test if spacing remains linear if tz changes to dst in range + result = pd.date_range( + "2018-04-01 01:00:00", + "2018-04-01 04:00:00", + tz="Australia/Sydney", + periods=3, + unit=unit, + ) + expected = pd.DatetimeIndex( + [ + pd.Timestamp("2018-04-01 01:00:00+1100", tz="Australia/Sydney"), + pd.Timestamp("2018-04-01 02:00:00+1000", tz="Australia/Sydney"), + pd.Timestamp("2018-04-01 04:00:00+1000", tz="Australia/Sydney"), + ] + ).as_unit(unit) + tm.assert_index_equal(result, expected) + + def test_date_range_index_comparison(self): + rng = pd.date_range("2011-01-01", periods=3, tz="US/Eastern") + df = pd.Series(rng).to_frame() + arr = np.array([rng.to_list()]).T + arr2 = np.array([rng]).T + + with pytest.raises(ValueError, match="Unable to coerce to Series"): + rng == df + + with pytest.raises(ValueError, match="Unable to coerce to Series"): + df == rng + + expected = pd.DataFrame([True, True, True]) + + results = df == arr2 + tm.assert_frame_equal(results, expected) + + expected = pd.Series([True, True, True], name=0) + + results = df[0] == arr2[:, 0] + tm.assert_series_equal(results, expected) + + expected = np.array( + [[True, False, False], [False, True, False], [False, False, True]] + ) + results = rng == arr + tm.assert_numpy_array_equal(results, expected) + + @pytest.mark.parametrize( + "start,end,result_tz", + [ + ["20180101", "20180103", "US/Eastern"], + [datetime(2018, 1, 1), datetime(2018, 1, 3), "US/Eastern"], + [pd.Timestamp("20180101"), pd.Timestamp("20180103"), "US/Eastern"], + [ + pd.Timestamp("20180101", tz="US/Eastern"), + pd.Timestamp("20180103", tz="US/Eastern"), + "US/Eastern", + ], + [ + pd.Timestamp("20180101", tz="US/Eastern"), + pd.Timestamp("20180103", tz="US/Eastern"), + None, + ], + ], + ) + def test_date_range_linspacing_tz(self, start, end, result_tz): + # GH 20983 + result = pd.date_range(start, end, periods=3, tz=result_tz) + expected = pd.date_range("20180101", periods=3, freq="D", tz="US/Eastern") + tm.assert_index_equal(result, expected, check_freq=False) + + def test_date_range_timedelta(self): + start = "2020-01-01" + end = "2020-01-11" + rng1 = pd.date_range(start, end, freq="3D") + rng2 = pd.date_range(start, end, freq=timedelta(days=3)) + tm.assert_index_equal(rng1, rng2, check_freq=False) + + def test_range_misspecified(self): + # GH #1095 + msg = ( + "Of the four parameters: start, end, periods, and " + "freq, exactly three must be specified" + ) + + with pytest.raises(ValueError, match=msg): + pd.date_range(start="1/1/2000") + + with pytest.raises(ValueError, match=msg): + pd.date_range(end="1/1/2000") + + with pytest.raises(ValueError, match=msg): + pd.date_range(periods=10) + + with pytest.raises(ValueError, match=msg): + pd.date_range(start="1/1/2000", freq="h") + + with pytest.raises(ValueError, match=msg): + pd.date_range(end="1/1/2000", freq="h") + + with pytest.raises(ValueError, match=msg): + pd.date_range(periods=10, freq="h") + + with pytest.raises(ValueError, match=msg): + pd.date_range() + + def test_compat_replace(self): + # https://github.com/statsmodels/statsmodels/issues/3349 + # replace should take ints/longs for compat + result = pd.date_range( + pd.Timestamp("1960-04-01 00:00:00"), periods=76, freq="QS-JAN" + ) + assert len(result) == 76 + + def test_catch_infinite_loop(self): + offset = pd.offsets.DateOffset(minute=5) + # blow up, don't loop forever + msg = "Offset did not increment date" + with pytest.raises(ValueError, match=msg): + pd.date_range(datetime(2011, 11, 11), datetime(2011, 11, 12), freq=offset) + + def test_construct_over_dst(self, unit): + # GH 20854 + pre_dst = pd.Timestamp("2010-11-07 01:00:00").tz_localize( + "US/Pacific", ambiguous=True + ) + pst_dst = pd.Timestamp("2010-11-07 01:00:00").tz_localize( + "US/Pacific", ambiguous=False + ) + expect_data = [ + pd.Timestamp("2010-11-07 00:00:00", tz="US/Pacific"), + pre_dst, + pst_dst, + ] + expected = pd.DatetimeIndex(expect_data, freq="h").as_unit(unit) + result = pd.date_range( + start="2010-11-7", periods=3, freq="h", tz="US/Pacific", unit=unit + ) + tm.assert_index_equal(result, expected) + + def test_construct_with_different_start_end_string_format(self, unit): + # GH 12064 + result = pd.date_range( + "2013-01-01 00:00:00+09:00", + "2013/01/01 02:00:00+09:00", + freq="h", + unit=unit, + ) + expected = pd.DatetimeIndex( + [ + pd.Timestamp("2013-01-01 00:00:00+09:00"), + pd.Timestamp("2013-01-01 01:00:00+09:00"), + pd.Timestamp("2013-01-01 02:00:00+09:00"), + ], + freq="h", + ).as_unit(unit) + tm.assert_index_equal(result, expected) + + def test_error_with_zero_monthends(self): + msg = r"Offset <0 \* MonthEnds> did not increment date" + with pytest.raises(ValueError, match=msg): + pd.date_range("1/1/2000", "1/1/2001", freq=MonthEnd(0)) + + @pytest.mark.parametrize( + "freq, periods, expected", + [ + ("W-SUN", 3, ["2019-12-29", "2020-01-05", "2020-01-12"]), + ("W-MON", 3, ["2019-12-30", "2020-01-06", "2020-01-13"]), + ("ME", 2, ["2019-11-30", "2019-12-31"]), + ("MS", 2, ["2019-12-01", "2020-01-01"]), + ("QS", 2, ["2019-10-01", "2020-01-01"]), + ], + ) + def test_date_range_end_off_offset_periods(self, freq, periods, expected): + # GH#64834 with end not on the offset, deriving start from + # (end, periods) dropped a period for anchored offsets + result = pd.date_range(end="2020-01-15", periods=periods, freq=freq) + expected = pd.DatetimeIndex(expected, freq=freq) + tm.assert_index_equal(result, expected) + + def test_range_bug(self, unit): + # GH #770 + offset = DateOffset(months=3) + result = pd.date_range("2011-1-1", "2012-1-31", freq=offset, unit=unit) + + start = datetime(2011, 1, 1) + expected = pd.DatetimeIndex( + [start + i * offset for i in range(5)], dtype=f"M8[{unit}]", freq=offset + ) + tm.assert_index_equal(result, expected) + + def test_range_tz_pytz(self): + # see gh-2906 + pytz = pytest.importorskip("pytz") + tz = pytz.timezone("US/Eastern") + start = tz.localize(datetime(2011, 1, 1)) + end = tz.localize(datetime(2011, 1, 3)) + + dr = pd.date_range(start=start, periods=3) + assert dr.tz.zone == tz.zone + assert dr[0] == start + assert dr[2] == end + + dr = pd.date_range(end=end, periods=3) + assert dr.tz.zone == tz.zone + assert dr[0] == start + assert dr[2] == end + + dr = pd.date_range(start=start, end=end) + assert dr.tz.zone == tz.zone + assert dr[0] == start + assert dr[2] == end + + @pytest.mark.parametrize( + "start, end", + [ + [datetime(2014, 3, 6), datetime(2014, 3, 12)], + [datetime(2013, 11, 1), datetime(2013, 11, 6)], + ], + ) + def test_range_tz_dst_straddle_pytz(self, start, end): + pytz = pytest.importorskip("pytz") + tz = pytz.timezone("US/Eastern") + start = pd.Timestamp(start, tz=tz) + end = pd.Timestamp(end, tz=tz) + dr = pd.date_range(start, end, freq="D") + assert dr[0] == start + assert dr[-1] == end + assert np.all(dr.hour == 0) + + dr = pd.date_range(start, end, freq="D", tz=tz) + assert dr[0] == start + assert dr[-1] == end + assert np.all(dr.hour == 0) + + dr = pd.date_range( + start.replace(tzinfo=None), + end.replace(tzinfo=None), + freq="D", + tz=tz, + ) + assert dr[0] == start + assert dr[-1] == end + assert np.all(dr.hour == 0) + + def test_range_tz_dateutil(self): + # see gh-2906 + + # Use maybe_get_tz to fix filename in tz under dateutil. + from pandas._libs.tslibs.timezones import maybe_get_tz + + tz = lambda x: maybe_get_tz("dateutil/" + x) + + start = datetime(2011, 1, 1, tzinfo=tz("US/Eastern")) + end = datetime(2011, 1, 3, tzinfo=tz("US/Eastern")) + + dr = pd.date_range(start=start, periods=3) + assert dr.tz == tz("US/Eastern") + assert dr[0] == start + assert dr[2] == end + + dr = pd.date_range(end=end, periods=3) + assert dr.tz == tz("US/Eastern") + assert dr[0] == start + assert dr[2] == end + + dr = pd.date_range(start=start, end=end) + assert dr.tz == tz("US/Eastern") + assert dr[0] == start + assert dr[2] == end + + @pytest.mark.parametrize("freq", ["1D", "3D", "2ME", "7W", "3h", "YE"]) + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + def test_range_closed(self, freq, tz, inclusive_endpoints_fixture): + # GH#12409, GH#12684 + + begin = pd.Timestamp("2011/1/1", tz=tz) + end = pd.Timestamp("2014/1/1", tz=tz) + + result_range = pd.date_range( + begin, end, inclusive=inclusive_endpoints_fixture, freq=freq + ) + both_range = pd.date_range(begin, end, inclusive="both", freq=freq) + expected_range = _get_expected_range( + begin, end, both_range, inclusive_endpoints_fixture + ) + + tm.assert_index_equal(expected_range, result_range) + + @pytest.mark.parametrize("freq", ["1D", "3D", "2ME", "7W", "3h", "YE"]) + def test_range_with_tz_closed_with_tz_aware_start_end( + self, freq, inclusive_endpoints_fixture + ): + begin = pd.Timestamp("2011/1/1") + end = pd.Timestamp("2014/1/1") + begintz = pd.Timestamp("2011/1/1", tz="US/Eastern") + endtz = pd.Timestamp("2014/1/1", tz="US/Eastern") + + result_range = pd.date_range( + begin, + end, + inclusive=inclusive_endpoints_fixture, + freq=freq, + tz="US/Eastern", + ) + both_range = pd.date_range( + begin, end, inclusive="both", freq=freq, tz="US/Eastern" + ) + expected_range = _get_expected_range( + begintz, + endtz, + both_range, + inclusive_endpoints_fixture, + ) + + tm.assert_index_equal(expected_range, result_range) + + def test_range_closed_boundary(self, inclusive_endpoints_fixture): + # GH#11804 + right_boundary = pd.date_range( + "2015-09-12", + "2015-12-01", + freq="QS-MAR", + inclusive=inclusive_endpoints_fixture, + ) + left_boundary = pd.date_range( + "2015-09-01", + "2015-09-12", + freq="QS-MAR", + inclusive=inclusive_endpoints_fixture, + ) + both_boundary = pd.date_range( + "2015-09-01", + "2015-12-01", + freq="QS-MAR", + inclusive=inclusive_endpoints_fixture, + ) + neither_boundary = pd.date_range( + "2015-09-11", + "2015-09-12", + freq="QS-MAR", + inclusive=inclusive_endpoints_fixture, + ) + + expected_right = both_boundary + expected_left = both_boundary + expected_both = both_boundary + + if inclusive_endpoints_fixture == "right": + expected_left = both_boundary[1:] + elif inclusive_endpoints_fixture == "left": + expected_right = both_boundary[:-1] + elif inclusive_endpoints_fixture == "both": + expected_right = both_boundary[1:] + expected_left = both_boundary[:-1] + + expected_neither = both_boundary[1:-1] + + tm.assert_index_equal(right_boundary, expected_right) + tm.assert_index_equal(left_boundary, expected_left) + tm.assert_index_equal(both_boundary, expected_both) + tm.assert_index_equal(neither_boundary, expected_neither) + + def test_date_range_years_only(self, tz_naive_fixture): + tz = tz_naive_fixture + # GH#6961 + rng1 = pd.date_range("2014", "2015", freq="ME", tz=tz) + expected1 = pd.date_range("2014-01-31", "2014-12-31", freq="ME", tz=tz) + tm.assert_index_equal(rng1, expected1) + + rng2 = pd.date_range("2014", "2015", freq="MS", tz=tz) + expected2 = pd.date_range("2014-01-01", "2015-01-01", freq="MS", tz=tz) + tm.assert_index_equal(rng2, expected2) + + rng3 = pd.date_range("2014", "2020", freq="YE", tz=tz) + expected3 = pd.date_range("2014-12-31", "2019-12-31", freq="YE", tz=tz) + tm.assert_index_equal(rng3, expected3) + + rng4 = pd.date_range("2014", "2020", freq="YS", tz=tz) + expected4 = pd.date_range("2014-01-01", "2020-01-01", freq="YS", tz=tz) + tm.assert_index_equal(rng4, expected4) + + def test_freq_divides_end_in_nanos(self): + # GH 10885 + result_1 = pd.date_range("2005-01-12 10:00", "2005-01-12 16:00", freq="345min") + result_2 = pd.date_range("2005-01-13 10:00", "2005-01-13 16:00", freq="345min") + expected_1 = pd.DatetimeIndex( + ["2005-01-12 10:00:00", "2005-01-12 15:45:00"], + dtype="datetime64[us]", + freq="345min", + tz=None, + ) + expected_2 = pd.DatetimeIndex( + ["2005-01-13 10:00:00", "2005-01-13 15:45:00"], + dtype="datetime64[us]", + freq="345min", + tz=None, + ) + tm.assert_index_equal(result_1, expected_1) + tm.assert_index_equal(result_2, expected_2) + + def test_cached_range_bug(self): + rng = pd.date_range("2010-09-01 05:00:00", periods=50, freq=DateOffset(hours=6)) + assert len(rng) == 50 + assert rng[0] == datetime(2010, 9, 1, 5) + + def test_timezone_comparison_bug(self): + # smoke test + start = pd.Timestamp("20130220 10:00", tz="US/Eastern") + result = pd.date_range(start, periods=2, tz="US/Eastern") + assert len(result) == 2 + + def test_timezone_comparison_assert(self): + start = pd.Timestamp("20130220 10:00", tz="US/Eastern") + msg = "Inferred time zone not equal to passed time zone" + with pytest.raises(AssertionError, match=msg): + pd.date_range(start, periods=2, tz="Europe/Berlin") + + def test_negative_non_tick_frequency_descending_dates(self, tz_aware_fixture): + # GH 23270 + tz = tz_aware_fixture + result = pd.date_range(start="2011-06-01", end="2011-01-01", freq="-1MS", tz=tz) + expected = pd.date_range( + end="2011-06-01", start="2011-01-01", freq="1MS", tz=tz + )[::-1] + tm.assert_index_equal(result, expected) + + def test_range_where_start_equal_end(self, inclusive_endpoints_fixture): + # GH#43394, GH#55293 + start = "2021-09-02" + end = "2021-09-02" + result = pd.date_range( + start=start, end=end, freq="D", inclusive=inclusive_endpoints_fixture + ) + + both_range = pd.date_range(start=start, end=end, freq="D", inclusive="both") + if inclusive_endpoints_fixture == "both": + expected = both_range[:] + else: + # (a, a], [a, a), and (a, a) are all empty + expected = both_range[1:-1] + + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "inclusive, expected_values", + [ + ("both", ["2021-09-02"]), + ("left", []), + ("right", []), + ("neither", []), + ], + ) + def test_start_equal_end_inclusive(self, inclusive, expected_values): + # GH#55293 - when start == end, only inclusive="both" should + # return the singleton; left, right, and neither should all be empty + result = pd.date_range( + start="2021-09-02", end="2021-09-02", freq="D", inclusive=inclusive + ) + expected = pd.DatetimeIndex(expected_values, dtype="datetime64[us]", freq="D") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "inclusive, expected_values", + [ + ("both", ["2020-06-01", "2020-06-02", "2020-06-03", "2020-06-04"]), + ("left", ["2020-06-01", "2020-06-02", "2020-06-03"]), + ("right", ["2020-06-02", "2020-06-03", "2020-06-04"]), + ("neither", ["2020-06-02", "2020-06-03"]), + ], + ) + def test_inclusive_with_periods_and_start(self, inclusive, expected_values): + # GH#46331 - inclusive should filter endpoints even when + # only start+periods is provided (end is not specified) + result = pd.date_range(start="2020-06-01", periods=4, inclusive=inclusive) + expected = pd.DatetimeIndex(expected_values, freq="D") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "inclusive, expected_values", + [ + ("both", ["2020-06-01", "2020-06-02", "2020-06-03", "2020-06-04"]), + ("left", ["2020-06-01", "2020-06-02", "2020-06-03"]), + ("right", ["2020-06-02", "2020-06-03", "2020-06-04"]), + ("neither", ["2020-06-02", "2020-06-03"]), + ], + ) + def test_inclusive_with_periods_and_end(self, inclusive, expected_values): + # GH#46331 - inclusive should filter endpoints even when + # only end+periods is provided (start is not specified) + result = pd.date_range(end="2020-06-04", periods=4, inclusive=inclusive) + expected = pd.DatetimeIndex(expected_values, freq="D") + tm.assert_index_equal(result, expected) + + def test_freq_dateoffset_with_relateivedelta_nanos(self): + # GH 46877 + freq = DateOffset(hours=10, days=57, nanoseconds=3) + result = pd.date_range( + end="1970-01-01 00:00:00", periods=10, freq=freq, name="a" + ) + expected = pd.DatetimeIndex( + [ + "1968-08-02T05:59:59.999999973", + "1968-09-28T15:59:59.999999976", + "1968-11-25T01:59:59.999999979", + "1969-01-21T11:59:59.999999982", + "1969-03-19T21:59:59.999999985", + "1969-05-16T07:59:59.999999988", + "1969-07-12T17:59:59.999999991", + "1969-09-08T03:59:59.999999994", + "1969-11-04T13:59:59.999999997", + "1970-01-01T00:00:00.000000000", + ], + name="a", + ) + tm.assert_index_equal(result, expected, check_freq=False) + + @pytest.mark.parametrize("freq", ["2T", "2L", "1l", "1U", "2N", "2n"]) + def test_frequency_H_T_S_L_U_N_raises(self, freq): + msg = f"Invalid frequency: {freq}" + with pytest.raises(ValueError, match=msg): + pd.date_range("1/1/2000", periods=2, freq=freq) + + @pytest.mark.parametrize( + "freq_depr", ["m", "bm", "CBM", "SM", "BQ", "q-feb", "y-may", "Y-MAY"] + ) + def test_frequency_raises(self, freq_depr): + msg = f"Invalid frequency: {freq_depr}" + + with pytest.raises(ValueError, match=msg): + pd.date_range("1/1/2000", periods=2, freq=freq_depr) + + def test_date_range_bday(self): + sdate = datetime(1999, 12, 25) + idx = pd.date_range(start=sdate, freq="1B", periods=20) + assert len(idx) == 20 + assert idx[0] == sdate + 0 * pd.offsets.BDay() + assert idx.freq == "B" + + @pytest.mark.parametrize("freq", ["200A", "2A-MAY"]) + def test_frequency_A_raises(self, freq): + freq_msg = re.split("[0-9]*", freq, maxsplit=1)[1] + msg = f"Invalid frequency: {freq_msg}" + + with pytest.raises(ValueError, match=msg): + pd.date_range("1/1/2000", periods=2, freq=freq) + + @pytest.mark.parametrize( + "freq,freq_depr", + [ + ("2W", "2w"), + ("2W-WED", "2w-wed"), + ("2B", "2b"), + ("2D", "2d"), + ("2C", "2c"), + ], + ) + def test_date_range_depr_lowercase_frequency(self, freq, freq_depr): + # GH#58998 + depr_msg = ( + f"'{freq_depr[1:]}' is deprecated and will be removed in a future version." + ) + + expected = pd.date_range("1/1/2000", periods=4, freq=freq) + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + result = pd.date_range("1/1/2000", periods=4, freq=freq_depr) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "freq_removed,freq", + [ + ("100A", "Y"), + ("2A-DEC", "Y-DEC"), + ("100AS", "YS"), + ("2AS-MAY", "YS-MAY"), + ], + ) + def test_error_message_for_removed_year_yearbegin_frequencies( + self, freq, freq_removed + ): + msg = f"Did you mean {freq}" + with pytest.raises(ValueError, match=msg): + pd.date_range("1/1/2000", periods=2, freq=freq_removed) + + +class TestDateRangeTZ: + """Tests for date_range with timezones""" + + def test_hongkong_tz_convert(self): + # GH#1673 smoke test + dr = pd.date_range("2012-01-01", "2012-01-10", freq="D", tz="Hongkong") + + # it works! + dr.hour + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_date_range_span_dst_transition(self, tzstr): + # GH#1778 + + # Standard -> Daylight Savings Time + dr = pd.date_range( + "03/06/2012 00:00", periods=200, freq="W-FRI", tz="US/Eastern" + ) + + assert (dr.hour == 0).all() + + dr = pd.date_range("2012-11-02", periods=10, tz=tzstr) + result = dr.hour + expected = pd.Index([0] * 10, dtype="int32") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_date_range_timezone_str_argument(self, tzstr): + tz = timezones.maybe_get_tz(tzstr) + result = pd.date_range("1/1/2000", periods=10, tz=tzstr) + expected = pd.date_range("1/1/2000", periods=10, tz=tz) + + tm.assert_index_equal(result, expected) + + def test_date_range_with_fixed_tz(self): + off = FixedOffset(420, "+07:00") + start = datetime(2012, 3, 11, 5, 0, 0, tzinfo=off) + end = datetime(2012, 6, 11, 5, 0, 0, tzinfo=off) + rng = pd.date_range(start=start, end=end) + assert off == rng.tz + + rng2 = pd.date_range(start, periods=len(rng), tz=off) + tm.assert_index_equal(rng, rng2) + + rng3 = pd.date_range("3/11/2012 05:00:00+07:00", "6/11/2012 05:00:00+07:00") + assert (rng._values == rng3._values).all() + + def test_date_range_with_fixedoffset_noname(self): + off = fixed_off_no_name + start = datetime(2012, 3, 11, 5, 0, 0, tzinfo=off) + end = datetime(2012, 6, 11, 5, 0, 0, tzinfo=off) + rng = pd.date_range(start=start, end=end) + assert off == rng.tz + + idx = pd.Index([start, end]) + assert off == idx.tz + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_date_range_with_tz(self, tzstr): + stamp = pd.Timestamp("3/11/2012 05:00", tz=tzstr) + assert stamp.hour == 5 + + rng = pd.date_range("3/11/2012 04:00", periods=10, freq="h", tz=tzstr) + + assert stamp == rng[1] + + @pytest.mark.parametrize("tz", ["Europe/London", "dateutil/Europe/London"]) + def test_date_range_ambiguous_endpoint(self, tz): + # construction with an ambiguous end-point + # GH#11626 + + with pytest.raises(ValueError, match="Cannot infer dst time"): + pd.date_range( + "2013-10-26 23:00", "2013-10-27 01:00", tz="Europe/London", freq="h" + ) + + times = pd.date_range( + "2013-10-26 23:00", "2013-10-27 01:00", freq="h", tz=tz, ambiguous="infer" + ) + assert times[0] == pd.Timestamp("2013-10-26 23:00", tz=tz) + assert times[-1] == pd.Timestamp("2013-10-27 01:00:00+0000", tz=tz) + + @pytest.mark.parametrize( + "tz, option, expected", + [ + ["US/Pacific", "shift_forward", "2019-03-10 03:00"], + ["dateutil/US/Pacific", "shift_forward", "2019-03-10 03:00"], + ["US/Pacific", "shift_backward", "2019-03-10 01:00"], + ["dateutil/US/Pacific", "shift_backward", "2019-03-10 01:00"], + ["US/Pacific", timedelta(hours=1), "2019-03-10 03:00"], + ], + ) + def test_date_range_nonexistent_endpoint(self, tz, option, expected): + # construction with an nonexistent end-point + + with pytest.raises(ValueError, match="2019-03-10 02:00:00"): + pd.date_range( + "2019-03-10 00:00", "2019-03-10 02:00", tz="US/Pacific", freq="h" + ) + + times = pd.date_range( + "2019-03-10 00:00", "2019-03-10 02:00", freq="h", tz=tz, nonexistent=option + ) + assert times[-1] == pd.Timestamp(expected, tz=tz) + + +class TestGenRangeGeneration: + @pytest.mark.parametrize( + "freqstr,offset", + [ + ("B", BDay()), + ("C", CDay()), + ], + ) + def test_generate(self, freqstr, offset): + rng1 = list(generate_range(START, END, periods=None, offset=offset, unit="ns")) + rng2 = list(generate_range(START, END, periods=None, offset=freqstr, unit="ns")) + assert rng1 == rng2 + + def test_1(self): + rng = list( + generate_range( + start=datetime(2009, 3, 25), + end=None, + periods=2, + offset=BDay(), + unit="ns", + ) + ) + expected = [datetime(2009, 3, 25), datetime(2009, 3, 26)] + assert rng == expected + + def test_2(self): + rng = list( + generate_range( + start=datetime(2008, 1, 1), + end=datetime(2008, 1, 3), + periods=None, + offset=BDay(), + unit="ns", + ) + ) + expected = [datetime(2008, 1, 1), datetime(2008, 1, 2), datetime(2008, 1, 3)] + assert rng == expected + + def test_3(self): + rng = list( + generate_range( + start=datetime(2008, 1, 5), + end=datetime(2008, 1, 6), + periods=None, + offset=BDay(), + unit="ns", + ) + ) + expected = [] + assert rng == expected + + def test_precision_finer_than_offset(self): + # GH#9907 + result1 = pd.date_range( + start="2015-04-15 00:00:03", end="2016-04-22 00:00:00", freq="QE" + ) + result2 = pd.date_range( + start="2015-04-15 00:00:03", end="2015-06-22 00:00:04", freq="W" + ) + expected1_list = [ + "2015-06-30 00:00:03", + "2015-09-30 00:00:03", + "2015-12-31 00:00:03", + "2016-03-31 00:00:03", + ] + expected2_list = [ + "2015-04-19 00:00:03", + "2015-04-26 00:00:03", + "2015-05-03 00:00:03", + "2015-05-10 00:00:03", + "2015-05-17 00:00:03", + "2015-05-24 00:00:03", + "2015-05-31 00:00:03", + "2015-06-07 00:00:03", + "2015-06-14 00:00:03", + "2015-06-21 00:00:03", + ] + expected1 = pd.DatetimeIndex( + expected1_list, dtype="datetime64[us]", freq="QE-DEC", tz=None + ) + expected2 = pd.DatetimeIndex( + expected2_list, dtype="datetime64[us]", freq="W-SUN", tz=None + ) + tm.assert_index_equal(result1, expected1) + tm.assert_index_equal(result2, expected2) + + @pytest.mark.parametrize( + "freq", + [ + pd.offsets.LastWeekOfMonth(1), + pd.offsets.FY5253(1), + ], + ) + def test_generate_range_periods1_no_n0_error(self, freq): + # GH#41563 - offsets that disallow n=0 should not raise + # when periods=1 (which computes 0 * offset internally) + result = pd.date_range("2018-04-01", periods=1, freq=freq) + assert len(result) == 1 + + @pytest.mark.parametrize( + "freq", + [ + "MS", + "QS", + "W-SUN", + "ME", + pd.offsets.LastWeekOfMonth(1), + pd.offsets.FY5253(1), + ], + ) + @pytest.mark.parametrize("periods", [1, 2, 3]) + def test_generate_range_end_off_offset(self, freq, periods): + # GH#64834/GH#65011 with only end + periods, an off-offset end is rolled + # onto the grid (like start), so the result has the requested length and + # stays a valid index; previously periods=1 gave an off-grid Timestamp + # with freq still pinned (an invalid index) and periods>1 gave the wrong + # count. + end = pd.Timestamp("2018-04-17") # a Tuesday: off every freq above + result = pd.date_range(end=end, periods=periods, freq=freq) + + assert len(result) == periods + # round-trip re-pins the freq; raises if any value is off-grid + tm.assert_index_equal(pd.DatetimeIndex(list(result), freq=freq), result) + + dt1, dt2 = "2017-01-01", "2017-01-01" + tz1, tz2 = "US/Eastern", "Europe/London" + + @pytest.mark.parametrize( + "start,end", + [ + (pd.Timestamp(dt1, tz=tz1), pd.Timestamp(dt2)), + (pd.Timestamp(dt1), pd.Timestamp(dt2, tz=tz2)), + (pd.Timestamp(dt1, tz=tz1), pd.Timestamp(dt2, tz=tz2)), + (pd.Timestamp(dt1, tz=tz2), pd.Timestamp(dt2, tz=tz1)), + ], + ) + def test_mismatching_tz_raises_err(self, start, end): + # issue 18488 + msg = "Start and end cannot both be tz-aware with different timezones" + with pytest.raises(TypeError, match=msg): + pd.date_range(start, end) + with pytest.raises(TypeError, match=msg): + pd.date_range(start, end, freq=BDay()) + + +class TestBusinessDateRange: + def test_constructor(self): + pd.bdate_range(START, END, freq=BDay()) + pd.bdate_range(START, periods=20, freq=BDay()) + pd.bdate_range(end=START, periods=20, freq=BDay()) + + msg = "periods must be an integer, got B" + with pytest.raises(TypeError, match=msg): + pd.date_range("2011-1-1", "2012-1-1", "B") + + with pytest.raises(TypeError, match=msg): + pd.bdate_range("2011-1-1", "2012-1-1", "B") + + msg = "freq must be specified for bdate_range; use date_range instead" + with pytest.raises(TypeError, match=msg): + pd.bdate_range(START, END, periods=10, freq=None) + + def test_misc(self): + end = datetime(2009, 5, 13) + dr = pd.bdate_range(end=end, periods=20) + firstDate = end - 19 * BDay() + + assert len(dr) == 20 + assert dr[0] == firstDate + assert dr[-1] == end + + def test_date_parse_failure(self): + badly_formed_date = "2007/100/1" + + msg = "Unknown datetime string format, unable to parse: 2007/100/1" + with pytest.raises(ValueError, match=msg): + pd.Timestamp(badly_formed_date) + + with pytest.raises(ValueError, match=msg): + pd.bdate_range(start=badly_formed_date, periods=10) + + with pytest.raises(ValueError, match=msg): + pd.bdate_range(end=badly_formed_date, periods=10) + + with pytest.raises(ValueError, match=msg): + pd.bdate_range(badly_formed_date, badly_formed_date) + + def test_daterange_bug_456(self): + # GH #456 + rng1 = pd.bdate_range("12/5/2011", "12/5/2011") + rng2 = pd.bdate_range("12/2/2011", "12/5/2011") + assert rng2.freq == BDay() + + result = rng1.union(rng2) + assert isinstance(result, pd.DatetimeIndex) + + def test_bdays_and_open_boundaries(self, inclusive_endpoints_fixture): + # GH 6673 + start = "2018-07-21" # Saturday + end = "2018-07-29" # Sunday + result = pd.date_range( + start, end, freq="B", inclusive=inclusive_endpoints_fixture + ) + + bday_start = "2018-07-23" # Monday + bday_end = "2018-07-27" # Friday + expected = pd.date_range(bday_start, bday_end, freq="D") + tm.assert_index_equal(result, expected, check_freq=False) + # Note: we do _not_ expect the freqs to match here + + def test_bday_near_overflow(self): + # GH#24252 avoid doing unnecessary addition that _would_ overflow + start = pd.Timestamp.max.floor("D").to_pydatetime() + rng = pd.date_range(start, end=None, periods=1, freq="B") + expected = pd.DatetimeIndex([start], freq="B") + tm.assert_index_equal(rng, expected) + + def test_bday_overflow_error(self): + # GH#24252 check that we get OutOfBoundsDatetime and not OverflowError + msg = "Out of bounds nanosecond timestamp" + start = pd.Timestamp.max.floor("D").to_pydatetime() + with pytest.raises(OutOfBoundsDatetime, match=msg): + pd.date_range(start, periods=2, freq="B", unit="ns") + + def test_bdate_range_end_weekend_periods(self): + # GH#64834 + result = pd.bdate_range(end="2026-03-21", periods=3) + expected = pd.DatetimeIndex(["2026-03-18", "2026-03-19", "2026-03-20"]) + tm.assert_index_equal(result, expected, check_freq=False) + + result = pd.bdate_range(end="2026-03-22", periods=3) + tm.assert_index_equal(result, expected, check_freq=False) + + @pytest.mark.parametrize("end", ["2026-03-20", "2026-03-21", "2026-03-22"]) + def test_bdate_range_end_periods_multiple_n(self, end): + # GH#64648 (post-merge): with end+periods and freq="nB" (n>=2), + # the on-offset stride must be anchored at the end (last business + # day <= end), not at the start of the internal buffer. + result = pd.bdate_range(end=end, periods=3, freq="2B") + expected = pd.DatetimeIndex(["2026-03-16", "2026-03-18", "2026-03-20"]) + tm.assert_index_equal(result, expected, check_freq=False) + + result = pd.bdate_range(end=end, periods=3, freq="3B") + expected = pd.DatetimeIndex(["2026-03-12", "2026-03-17", "2026-03-20"]) + tm.assert_index_equal(result, expected, check_freq=False) + + @pytest.mark.parametrize( + "freq, last", + [ + ("B", "2024-01-08 09:00"), + ("C", "2024-01-08 09:00"), + ("2B", "2024-01-05 09:00"), + ("2C", "2024-01-05 09:00"), + ], + ) + def test_date_range_business_freq_start_end_time_of_day(self, freq, last): + # GH#64790: the business-day fast path must not stretch end to start's + # time-of-day, so an end earlier in the day than start drops that boundary + result = pd.date_range("2024-01-01 09:00", "2024-01-09 08:00", freq=freq) + expected = pd.date_range("2024-01-01 09:00", last, freq=freq) + tm.assert_index_equal(result, expected) + assert result[-1] == pd.Timestamp(last) + + def test_date_range_business_start_end_near_timestamp_max(self): + # GH#64648 (post-merge): endpoint arithmetic must not overflow when + # start and end sit within one offset step of Timestamp.max + # (2262-04-11 is a Friday) + start = pd.Timestamp("2262-04-11 10:00").as_unit("ns") + end = pd.Timestamp("2262-04-11 15:00").as_unit("ns") + result = pd.date_range(start, end, freq="B") + expected = pd.DatetimeIndex([start], freq="B") + tm.assert_index_equal(result, expected) + + # one daily step past this start is unrepresentable + start = pd.Timestamp("2262-04-10 23:59:59.999999").as_unit("ns") + end = pd.Timestamp("2262-04-11 01:00").as_unit("ns") + result = pd.date_range(start, end, freq="B") + expected = pd.DatetimeIndex([start], freq="B") + tm.assert_index_equal(result, expected) + + +class TestCustomDateRange: + def test_cdate_range_periods_holidays_starve_buffer(self): + # GH#64648 (post-merge): with periods and a CustomBusinessDay whose + # holidays blank out whole weeks, the fast path must still return + # exactly `periods` business days -- previously a fixed calendar-day + # buffer held too few on-offset days and the result was silently short. + holidays = list(pd.date_range("2024-01-01", "2024-02-29")) + cday = CDay(holidays=holidays) + + result = pd.date_range(start="2024-01-01", periods=6, freq=cday) + expected = pd.DatetimeIndex( + [ + "2024-03-01", + "2024-03-04", + "2024-03-05", + "2024-03-06", + "2024-03-07", + "2024-03-08", + ], + freq=cday, + ) + tm.assert_index_equal(result, expected) + + holidays = list(pd.date_range("2024-01-15", "2024-03-13")) + cday = CDay(holidays=holidays) + result = pd.bdate_range(end="2024-03-15", periods=4, freq=cday) + expected = pd.DatetimeIndex( + ["2024-01-11", "2024-01-12", "2024-03-14", "2024-03-15"], freq=cday + ) + tm.assert_index_equal(result, expected) + + def test_constructor(self): + pd.bdate_range(START, END, freq=CDay()) + pd.bdate_range(START, periods=20, freq=CDay()) + pd.bdate_range(end=START, periods=20, freq=CDay()) + + msg = "periods must be an integer, got C" + with pytest.raises(TypeError, match=msg): + pd.date_range("2011-1-1", "2012-1-1", "C") + + with pytest.raises(TypeError, match=msg): + pd.bdate_range("2011-1-1", "2012-1-1", "C") + + def test_misc(self): + end = datetime(2009, 5, 13) + dr = pd.bdate_range(end=end, periods=20, freq="C") + firstDate = end - 19 * CDay() + + assert len(dr) == 20 + assert dr[0] == firstDate + assert dr[-1] == end + + def test_daterange_bug_456(self): + # GH #456 + rng1 = pd.bdate_range("12/5/2011", "12/5/2011", freq="C") + rng2 = pd.bdate_range("12/2/2011", "12/5/2011", freq="C") + assert rng2.freq == CDay() + + result = rng1.union(rng2) + assert isinstance(result, pd.DatetimeIndex) + + def test_cdaterange(self, unit): + result = pd.bdate_range("2013-05-01", periods=3, freq="C", unit=unit) + expected = pd.DatetimeIndex( + ["2013-05-01", "2013-05-02", "2013-05-03"], dtype=f"M8[{unit}]", freq="C" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + def test_cdaterange_weekmask(self, unit): + result = pd.bdate_range( + "2013-05-01", periods=3, freq="C", weekmask="Sun Mon Tue Wed Thu", unit=unit + ) + expected = pd.DatetimeIndex( + ["2013-05-01", "2013-05-02", "2013-05-05"], + dtype=f"M8[{unit}]", + freq=result.freq, + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + # raise with non-custom freq + msg = ( + "a custom frequency string is required when holidays or " + "weekmask are passed, got frequency B" + ) + with pytest.raises(ValueError, match=msg): + pd.bdate_range("2013-05-01", periods=3, weekmask="Sun Mon Tue Wed Thu") + + def test_cdaterange_holidays(self, unit): + result = pd.bdate_range( + "2013-05-01", periods=3, freq="C", holidays=["2013-05-01"], unit=unit + ) + expected = pd.DatetimeIndex( + ["2013-05-02", "2013-05-03", "2013-05-06"], + dtype=f"M8[{unit}]", + freq=result.freq, + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + # raise with non-custom freq + msg = ( + "a custom frequency string is required when holidays or " + "weekmask are passed, got frequency B" + ) + with pytest.raises(ValueError, match=msg): + pd.bdate_range("2013-05-01", periods=3, holidays=["2013-05-01"]) + + def test_cdaterange_weekmask_and_holidays(self, unit): + result = pd.bdate_range( + "2013-05-01", + periods=3, + freq="C", + weekmask="Sun Mon Tue Wed Thu", + holidays=["2013-05-01"], + unit=unit, + ) + expected = pd.DatetimeIndex( + ["2013-05-02", "2013-05-05", "2013-05-06"], + dtype=f"M8[{unit}]", + freq=result.freq, + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + def test_cdaterange_holidays_weekmask_requires_freqstr(self): + # raise with non-custom freq + msg = ( + "a custom frequency string is required when holidays or " + "weekmask are passed, got frequency B" + ) + with pytest.raises(ValueError, match=msg): + pd.bdate_range( + "2013-05-01", + periods=3, + weekmask="Sun Mon Tue Wed Thu", + holidays=["2013-05-01"], + ) + + @pytest.mark.parametrize( + "freq", [freq for freq in prefix_mapping if freq.upper().startswith("C")] + ) + def test_all_custom_freq(self, freq): + # should not raise + pd.bdate_range( + START, END, freq=freq, weekmask="Mon Wed Fri", holidays=["2009-03-14"] + ) + + bad_freq = freq + "FOO" + msg = f"invalid custom frequency string: {bad_freq}" + with pytest.raises(ValueError, match=msg): + pd.bdate_range(START, END, freq=bad_freq) + + @pytest.mark.parametrize( + "start_end", + [ + ("2018-01-01T00:00:01.000Z", "2018-01-03T00:00:01.000Z"), + ("2018-01-01T00:00:00.010Z", "2018-01-03T00:00:00.010Z"), + ("2001-01-01T00:00:00.010Z", "2001-01-03T00:00:00.010Z"), + ], + ) + def test_range_with_millisecond_resolution(self, start_end): + # https://github.com/pandas-dev/pandas/issues/24110 + start, end = start_end + result = pd.date_range(start=start, end=end, periods=2, inclusive="left") + expected = pd.DatetimeIndex([start], dtype="M8[us, UTC]") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "start,period,expected", + [ + ("2022-07-23 00:00:00+02:00", 1, ["2022-07-25 00:00:00+02:00"]), + ("2022-07-22 00:00:00+02:00", 1, ["2022-07-22 00:00:00+02:00"]), + ( + "2022-07-22 00:00:00+02:00", + 2, + ["2022-07-22 00:00:00+02:00", "2022-07-25 00:00:00+02:00"], + ), + ], + ) + def test_range_with_timezone_and_custombusinessday(self, start, period, expected): + # GH49441 + result = pd.date_range(start=start, periods=period, freq="C") + expected = pd.DatetimeIndex(expected, freq="C").as_unit("us") + tm.assert_index_equal(result, expected) + + def test_data_range_custombusinessday_partial_time(self, unit): + # GH#57456 + offset = pd.offsets.CustomBusinessDay(weekmask="Sun Mon Tue") + start = datetime(2024, 2, 6, 23) + # end datetime is partial and not in the offset + end = datetime(2024, 2, 14, 14) + result = pd.date_range(start, end, freq=offset, unit=unit) + expected = pd.DatetimeIndex( + [ + "2024-02-06 23:00:00", + "2024-02-11 23:00:00", + "2024-02-12 23:00:00", + "2024-02-13 23:00:00", + ], + dtype=f"M8[{unit}]", + freq=offset, + ) + tm.assert_index_equal(result, expected) + + def test_cdaterange_cbh(self): + # GH#62849 + result = pd.bdate_range( + "2009-03-13", + "2009-03-15", + freq="cbh", + weekmask="Mon Wed Fri", + holidays=["2009-03-14"], + ) + expected = pd.DatetimeIndex( + [ + "2009-03-13 09:00:00", + "2009-03-13 10:00:00", + "2009-03-13 11:00:00", + "2009-03-13 12:00:00", + "2009-03-13 13:00:00", + "2009-03-13 14:00:00", + "2009-03-13 15:00:00", + "2009-03-13 16:00:00", + ], + dtype="datetime64[us]", + freq="cbh", + ) + tm.assert_index_equal(result, expected, check_freq=False) + + def test_cdaterange_deprecated_error_CBH(self): + # GH#62849 + msg = "invalid custom frequency string: CBH, did you mean cbh?" + with pytest.raises(ValueError, match=msg): + pd.bdate_range( + START, END, freq="CBH", weekmask="Mon Wed Fri", holidays=["2009-03-14"] + ) + + +class TestDateRangeNonNano: + def test_date_range_reso_validation(self): + msg = "'unit' must be one of 's', 'ms', 'us', 'ns'" + with pytest.raises(ValueError, match=msg): + pd.date_range("2016-01-01", "2016-03-04", periods=3, unit="h") + + def test_date_range_freq_higher_than_reso(self): + # freq being higher-resolution than reso is a problem + msg = "Use a lower freq or a higher unit instead" + with pytest.raises(ValueError, match=msg): + # # TODO give a more useful or informative message? + pd.date_range("2016-01-01", "2016-01-02", freq="ns", unit="ms") + + def test_date_range_freq_matches_reso(self): + # GH#49106 matching reso is OK + dti = pd.date_range("2016-01-01", "2016-01-01 00:00:01", freq="ms", unit="ms") + rng = np.arange(1_451_606_400_000, 1_451_606_401_001, dtype=np.int64) + expected = pd.DatetimeIndex(rng.view("M8[ms]"), freq="ms") + tm.assert_index_equal(dti, expected) + + dti = pd.date_range("2016-01-01", "2016-01-01 00:00:01", freq="us", unit="us") + rng = np.arange(1_451_606_400_000_000, 1_451_606_401_000_001, dtype=np.int64) + expected = pd.DatetimeIndex(rng.view("M8[us]"), freq="us") + tm.assert_index_equal(dti, expected) + + dti = pd.date_range( + "2016-01-01", "2016-01-01 00:00:00.001", freq="ns", unit="ns" + ) + rng = np.arange( + 1_451_606_400_000_000_000, 1_451_606_400_001_000_001, dtype=np.int64 + ) + expected = pd.DatetimeIndex(rng.view("M8[ns]"), freq="ns") + tm.assert_index_equal(dti, expected) + + def test_date_range_freq_lower_than_endpoints(self): + start = pd.Timestamp("2022-10-19 11:50:44.719781") + end = pd.Timestamp("2022-10-19 11:50:47.066458") + + # start and end cannot be cast to "s" unit without lossy rounding, + # so we do not allow this in date_range + with pytest.raises(ValueError, match="Cannot losslessly convert units"): + pd.date_range(start, end, periods=3, unit="s") + + # but we can losslessly cast to "us" + dti = pd.date_range(start, end, periods=2, unit="us") + rng = np.array( + [start.as_unit("us")._value, end.as_unit("us")._value], dtype=np.int64 + ) + expected = pd.DatetimeIndex(rng.view("M8[us]")) + tm.assert_index_equal(dti, expected) + + def test_date_range_non_nano(self): + start = np.datetime64("1066-10-14") # Battle of Hastings + end = np.datetime64("2305-07-13") # Jean-Luc Picard's birthday + + dti = pd.date_range(start, end, freq="D", unit="s") + assert dti.freq == "D" + assert dti.dtype == "M8[s]" + + exp = np.arange( + start.astype("M8[s]").view("i8"), + (end + np.timedelta64(1, "D")).astype("M8[s]").view("i8"), + 24 * 3600, + ).view("M8[s]") + + tm.assert_numpy_array_equal(dti.to_numpy(), exp) + + +class TestDateRangeNonTickFreq: + # Tests revolving around less-common (non-Tick) `freq` keywords. + + def test_date_range_custom_business_month_begin(self, unit): + hcal = USFederalHolidayCalendar() + freq = pd.offsets.CBMonthBegin(calendar=hcal) + dti = pd.date_range(start="20120101", end="20130101", freq=freq, unit=unit) + assert all(freq.is_on_offset(x) for x in dti) + + expected = pd.DatetimeIndex( + [ + "2012-01-03", + "2012-02-01", + "2012-03-01", + "2012-04-02", + "2012-05-01", + "2012-06-01", + "2012-07-02", + "2012-08-01", + "2012-09-04", + "2012-10-01", + "2012-11-01", + "2012-12-03", + ], + dtype=f"M8[{unit}]", + freq=freq, + ) + tm.assert_index_equal(dti, expected) + + def test_date_range_custom_business_month_end(self, unit): + hcal = USFederalHolidayCalendar() + freq = pd.offsets.CBMonthEnd(calendar=hcal) + dti = pd.date_range(start="20120101", end="20130101", freq=freq, unit=unit) + assert all(freq.is_on_offset(x) for x in dti) + + expected = pd.DatetimeIndex( + [ + "2012-01-31", + "2012-02-29", + "2012-03-30", + "2012-04-30", + "2012-05-31", + "2012-06-29", + "2012-07-31", + "2012-08-31", + "2012-09-28", + "2012-10-31", + "2012-11-30", + "2012-12-31", + ], + dtype=f"M8[{unit}]", + freq=freq, + ) + tm.assert_index_equal(dti, expected) + + def test_date_range_with_custom_holidays(self, unit): + # GH#30593 + freq = pd.offsets.CustomBusinessHour(start="15:00", holidays=["2020-11-26"]) + result = pd.date_range( + start="2020-11-25 15:00", periods=4, freq=freq, unit=unit + ) + expected = pd.DatetimeIndex( + [ + "2020-11-25 15:00:00", + "2020-11-25 16:00:00", + "2020-11-27 15:00:00", + "2020-11-27 16:00:00", + ], + dtype=f"M8[{unit}]", + freq=freq, + ) + tm.assert_index_equal(result, expected) + + def test_date_range_businesshour(self, unit): + idx = pd.DatetimeIndex( + [ + "2014-07-04 09:00", + "2014-07-04 10:00", + "2014-07-04 11:00", + "2014-07-04 12:00", + "2014-07-04 13:00", + "2014-07-04 14:00", + "2014-07-04 15:00", + "2014-07-04 16:00", + ], + dtype=f"M8[{unit}]", + freq="bh", + ) + rng = pd.date_range( + "2014-07-04 09:00", "2014-07-04 16:00", freq="bh", unit=unit + ) + tm.assert_index_equal(idx, rng) + + idx = pd.DatetimeIndex( + ["2014-07-04 16:00", "2014-07-07 09:00"], dtype=f"M8[{unit}]", freq="bh" + ) + rng = pd.date_range( + "2014-07-04 16:00", "2014-07-07 09:00", freq="bh", unit=unit + ) + tm.assert_index_equal(idx, rng) + + idx = pd.DatetimeIndex( + [ + "2014-07-04 09:00", + "2014-07-04 10:00", + "2014-07-04 11:00", + "2014-07-04 12:00", + "2014-07-04 13:00", + "2014-07-04 14:00", + "2014-07-04 15:00", + "2014-07-04 16:00", + "2014-07-07 09:00", + "2014-07-07 10:00", + "2014-07-07 11:00", + "2014-07-07 12:00", + "2014-07-07 13:00", + "2014-07-07 14:00", + "2014-07-07 15:00", + "2014-07-07 16:00", + "2014-07-08 09:00", + "2014-07-08 10:00", + "2014-07-08 11:00", + "2014-07-08 12:00", + "2014-07-08 13:00", + "2014-07-08 14:00", + "2014-07-08 15:00", + "2014-07-08 16:00", + ], + dtype=f"M8[{unit}]", + freq="bh", + ) + rng = pd.date_range( + "2014-07-04 09:00", "2014-07-08 16:00", freq="bh", unit=unit + ) + tm.assert_index_equal(idx, rng) + + def test_date_range_business_hour2(self, unit): + idx1 = pd.date_range( + start="2014-07-04 15:00", end="2014-07-08 10:00", freq="bh", unit=unit + ) + idx2 = pd.date_range(start="2014-07-04 15:00", periods=12, freq="bh", unit=unit) + idx3 = pd.date_range(end="2014-07-08 10:00", periods=12, freq="bh", unit=unit) + expected = pd.DatetimeIndex( + [ + "2014-07-04 15:00", + "2014-07-04 16:00", + "2014-07-07 09:00", + "2014-07-07 10:00", + "2014-07-07 11:00", + "2014-07-07 12:00", + "2014-07-07 13:00", + "2014-07-07 14:00", + "2014-07-07 15:00", + "2014-07-07 16:00", + "2014-07-08 09:00", + "2014-07-08 10:00", + ], + dtype=f"M8[{unit}]", + freq="bh", + ) + tm.assert_index_equal(idx1, expected) + tm.assert_index_equal(idx2, expected) + tm.assert_index_equal(idx3, expected) + + idx4 = pd.date_range( + start="2014-07-04 15:45", end="2014-07-08 10:45", freq="bh", unit=unit + ) + idx5 = pd.date_range(start="2014-07-04 15:45", periods=12, freq="bh", unit=unit) + idx6 = pd.date_range(end="2014-07-08 10:45", periods=12, freq="bh", unit=unit) + + expected2 = expected + pd.Timedelta(minutes=45).as_unit(unit) + expected2.freq = "bh" + tm.assert_index_equal(idx4, expected2) + tm.assert_index_equal(idx5, expected2) + tm.assert_index_equal(idx6, expected2) + + def test_date_range_business_hour_short(self, unit): + # GH#49835 + idx4 = pd.date_range(start="2014-07-01 10:00", freq="bh", periods=1, unit=unit) + expected4 = pd.DatetimeIndex( + ["2014-07-01 10:00"], dtype=f"M8[{unit}]", freq="bh" + ) + tm.assert_index_equal(idx4, expected4) + + def test_date_range_year_start(self, unit): + # see GH#9313 + rng = pd.date_range("1/1/2013", "7/1/2017", freq="YS", unit=unit) + exp = pd.DatetimeIndex( + ["2013-01-01", "2014-01-01", "2015-01-01", "2016-01-01", "2017-01-01"], + dtype=f"M8[{unit}]", + freq="YS", + ) + tm.assert_index_equal(rng, exp) + + def test_date_range_year_end(self, unit): + # see GH#9313 + rng = pd.date_range("1/1/2013", "7/1/2017", freq="YE", unit=unit) + exp = pd.DatetimeIndex( + ["2013-12-31", "2014-12-31", "2015-12-31", "2016-12-31"], + dtype=f"M8[{unit}]", + freq="YE", + ) + tm.assert_index_equal(rng, exp) + + def test_date_range_negative_freq_year_end(self, unit): + # GH#11018 + rng = pd.date_range("2011-12-31", freq="-2YE", periods=3, unit=unit) + exp = pd.DatetimeIndex( + ["2011-12-31", "2009-12-31", "2007-12-31"], dtype=f"M8[{unit}]", freq="-2YE" + ) + tm.assert_index_equal(rng, exp) + assert rng.freq == "-2YE" + + def test_date_range_business_year_end_year(self, unit): + # see GH#9313 + rng = pd.date_range("1/1/2013", "7/1/2017", freq="BYE", unit=unit) + exp = pd.DatetimeIndex( + ["2013-12-31", "2014-12-31", "2015-12-31", "2016-12-30"], + dtype=f"M8[{unit}]", + freq="BYE", + ) + tm.assert_index_equal(rng, exp) + + def test_date_range_bms(self, unit): + # GH#1645 + result = pd.date_range("1/1/2000", periods=10, freq="BMS", unit=unit) + + expected = pd.DatetimeIndex( + [ + "2000-01-03", + "2000-02-01", + "2000-03-01", + "2000-04-03", + "2000-05-01", + "2000-06-01", + "2000-07-03", + "2000-08-01", + "2000-09-01", + "2000-10-02", + ], + dtype=f"M8[{unit}]", + freq="BMS", + ) + tm.assert_index_equal(result, expected) + + def test_date_range_semi_month_begin(self, unit): + dates = [ + datetime(2007, 12, 15), + datetime(2008, 1, 1), + datetime(2008, 1, 15), + datetime(2008, 2, 1), + datetime(2008, 2, 15), + datetime(2008, 3, 1), + datetime(2008, 3, 15), + datetime(2008, 4, 1), + datetime(2008, 4, 15), + datetime(2008, 5, 1), + datetime(2008, 5, 15), + datetime(2008, 6, 1), + datetime(2008, 6, 15), + datetime(2008, 7, 1), + datetime(2008, 7, 15), + datetime(2008, 8, 1), + datetime(2008, 8, 15), + datetime(2008, 9, 1), + datetime(2008, 9, 15), + datetime(2008, 10, 1), + datetime(2008, 10, 15), + datetime(2008, 11, 1), + datetime(2008, 11, 15), + datetime(2008, 12, 1), + datetime(2008, 12, 15), + ] + # ensure generating a range with DatetimeIndex gives same result + result = pd.date_range(start=dates[0], end=dates[-1], freq="SMS", unit=unit) + exp = pd.DatetimeIndex(dates, dtype=f"M8[{unit}]", freq="SMS") + tm.assert_index_equal(result, exp) + + def test_date_range_semi_month_end(self, unit): + dates = [ + datetime(2007, 12, 31), + datetime(2008, 1, 15), + datetime(2008, 1, 31), + datetime(2008, 2, 15), + datetime(2008, 2, 29), + datetime(2008, 3, 15), + datetime(2008, 3, 31), + datetime(2008, 4, 15), + datetime(2008, 4, 30), + datetime(2008, 5, 15), + datetime(2008, 5, 31), + datetime(2008, 6, 15), + datetime(2008, 6, 30), + datetime(2008, 7, 15), + datetime(2008, 7, 31), + datetime(2008, 8, 15), + datetime(2008, 8, 31), + datetime(2008, 9, 15), + datetime(2008, 9, 30), + datetime(2008, 10, 15), + datetime(2008, 10, 31), + datetime(2008, 11, 15), + datetime(2008, 11, 30), + datetime(2008, 12, 15), + datetime(2008, 12, 31), + ] + # ensure generating a range with DatetimeIndex gives same result + result = pd.date_range(start=dates[0], end=dates[-1], freq="SME", unit=unit) + exp = pd.DatetimeIndex(dates, dtype=f"M8[{unit}]", freq="SME") + tm.assert_index_equal(result, exp) + + def test_date_range_week_of_month(self, unit): + # GH#20517 + # Note the start here is not on_offset for this freq + result = pd.date_range(start="20110101", periods=1, freq="WOM-1MON", unit=unit) + expected = pd.DatetimeIndex( + ["2011-01-03"], dtype=f"M8[{unit}]", freq="WOM-1MON" + ) + tm.assert_index_equal(result, expected) + + result2 = pd.date_range(start="20110101", periods=2, freq="WOM-1MON", unit=unit) + expected2 = pd.DatetimeIndex( + ["2011-01-03", "2011-02-07"], dtype=f"M8[{unit}]", freq="WOM-1MON" + ) + tm.assert_index_equal(result2, expected2) + + def test_date_range_week_of_month2(self, unit): + # GH#5115, GH#5348 + result = pd.date_range("2013-1-1", periods=4, freq="WOM-1SAT", unit=unit) + expected = pd.DatetimeIndex( + ["2013-01-05", "2013-02-02", "2013-03-02", "2013-04-06"], + dtype=f"M8[{unit}]", + freq="WOM-1SAT", + ) + tm.assert_index_equal(result, expected) + + def test_date_range_negative_freq_month_end(self, unit): + # GH#11018 + rng = pd.date_range("2011-01-31", freq="-2ME", periods=3, unit=unit) + exp = pd.DatetimeIndex( + ["2011-01-31", "2010-11-30", "2010-09-30"], dtype=f"M8[{unit}]", freq="-2ME" + ) + tm.assert_index_equal(rng, exp) + assert rng.freq == "-2ME" + + def test_date_range_fy5253(self, unit): + freq = pd.offsets.FY5253(startingMonth=1, weekday=3, variation="nearest") + dti = pd.date_range( + start="2013-01-01", + periods=2, + freq=freq, + unit=unit, + ) + expected = pd.DatetimeIndex( + ["2013-01-31", "2014-01-30"], dtype=f"M8[{unit}]", freq=freq + ) + + tm.assert_index_equal(dti, expected) + + @pytest.mark.parametrize( + "freqstr,offset", + [ + ("QS", pd.offsets.QuarterBegin(startingMonth=1)), + ("BQE", pd.offsets.BQuarterEnd(startingMonth=12)), + ("W-SUN", pd.offsets.Week(weekday=6)), + ], + ) + def test_date_range_freqstr_matches_offset(self, freqstr, offset): + sdate = datetime(1999, 12, 25) + edate = datetime(2000, 1, 1) + + idx1 = pd.date_range(start=sdate, end=edate, freq=freqstr) + idx2 = pd.date_range(start=sdate, end=edate, freq=offset) + assert len(idx1) == len(idx2) + assert idx1.freq == idx2.freq + + def test_date_range_partial_day_year_end(self, unit): + # GH#56134 + rng = pd.date_range( + start="2021-12-31 00:00:01", + end="2023-10-31 00:00:00", + freq="YE", + unit=unit, + ) + exp = pd.DatetimeIndex( + ["2021-12-31 00:00:01", "2022-12-31 00:00:01"], + dtype=f"M8[{unit}]", + freq="YE", + ) + tm.assert_index_equal(rng, exp) + + def test_date_range_negative_freq_year_end_inbounds(self, unit): + # GH#56147 + rng = pd.date_range( + start="2023-10-31 00:00:00", + end="2021-10-31 00:00:00", + freq="-1YE", + unit=unit, + ) + exp = pd.DatetimeIndex( + ["2022-12-31 00:00:00", "2021-12-31 00:00:00"], + dtype=f"M8[{unit}]", + freq="-1YE", + ) + tm.assert_index_equal(rng, exp) + + def test_date_range_tzaware_endpoints_accept_ambiguous(self): + # https://github.com/pandas-dev/pandas/issues/52908 + start = pd.Timestamp("1916-08-01", tz="Europe/Oslo") + end = pd.Timestamp("1916-12-01", tz="Europe/Oslo") + res = pd.date_range(start, end, freq="MS", ambiguous=True) + exp = pd.date_range( + "1916-08-01", "1916-12-01", freq="MS", tz="Europe/Oslo", ambiguous=True + ) + tm.assert_index_equal(res, exp) + + def test_date_range_tzaware_endpoints_accept_nonexistent(self): + # Europe/London spring-forward: 2015-03-29 01:30 does not exist. + tz = "Europe/London" + start = pd.Timestamp("2015-03-28 01:30", tz=tz) + end = pd.Timestamp("2015-03-30 01:30", tz=tz) + + result = pd.date_range(start, end, freq="D", nonexistent="shift_forward") + + # Build expected by generating naive daily times, then tz_localize so + # the nonexistent handling is applied during localization. + expected = pd.date_range( + "2015-03-28 01:30", "2015-03-30 01:30", freq="D" + ).tz_localize(tz, nonexistent="shift_forward") + tm.assert_index_equal(result, expected, check_freq=False) + + @pytest.mark.parametrize( + "freq, start, end, expected_dates", + [ + ( + "MS", + "2020-02-01 15:00", + "2020-05-01 01:00", + ["2020-02-01 15:00", "2020-03-01 15:00", "2020-04-01 15:00"], + ), + ( + "MS", + "2020-02-01 15:00", + "2020-05-01 23:00", + [ + "2020-02-01 15:00", + "2020-03-01 15:00", + "2020-04-01 15:00", + "2020-05-01 15:00", + ], + ), + ( + "ME", + "2020-01-31 15:00", + "2020-04-30 01:00", + ["2020-01-31 15:00", "2020-02-29 15:00", "2020-03-31 15:00"], + ), + ( + "QS", + "2020-01-01 15:00", + "2020-10-01 01:00", + ["2020-01-01 15:00", "2020-04-01 15:00", "2020-07-01 15:00"], + ), + ( + "YS", + "2020-01-01 15:00", + "2023-01-01 01:00", + ["2020-01-01 15:00", "2021-01-01 15:00", "2022-01-01 15:00"], + ), + ( + # negative freq: end is the lower bound, so the 15:00 boundary + # on end's date is inside [end, start] and is kept + "-1MS", + "2020-05-01 15:00", + "2020-02-01 01:00", + [ + "2020-05-01 15:00", + "2020-04-01 15:00", + "2020-03-01 15:00", + "2020-02-01 15:00", + ], + ), + ( + "-1MS", + "2020-05-01 15:00", + "2020-02-01 16:00", + ["2020-05-01 15:00", "2020-04-01 15:00", "2020-03-01 15:00"], + ), + ], + ) + def test_date_range_end_time_earlier_than_start_time( + self, unit, freq, start, end, expected_dates + ): + # GH#64790: end's time-of-day is not stretched to start's, so every + # entry satisfies start <= date <= end -- GH#35342 wanted a point outside it + result = pd.date_range(start, end, freq=freq, unit=unit) + expected = pd.DatetimeIndex(expected_dates, dtype=f"M8[{unit}]", freq=freq) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("inclusive", ["both", "left", "right", "neither"]) +@pytest.mark.parametrize("freq", ["MS", "ME", "QS", "YS", "B", "C", "D", "12h"]) +def test_date_range_never_exceeds_end(freq, inclusive): + # GH#64790: every offset family obeys the same closed-interval contract; + # the non-Tick paths used to overshoot end, escaping the inclusive= trim + start = pd.Timestamp("2021-01-01 09:00") + end = pd.Timestamp("2022-03-01 08:00") + result = pd.date_range(start, end, freq=freq, inclusive=inclusive) + assert result[0] >= start + assert result[-1] <= end + + +class TestDateRangeUnitInference: + def test_date_range_unit_inference_matching_unit(self, unit): + start = pd.Timestamp("2025-11-25").as_unit(unit) + end = pd.Timestamp("2025-11-26").as_unit(unit) + + dti = pd.date_range(start, end, freq="D") + assert dti.unit == unit + + def test_date_range_unit_inference_mismatched_unit(self, unit): + start = pd.Timestamp("2025-11-25").as_unit(unit) + end = pd.Timestamp("2025-11-26").as_unit("s") + + dti = pd.date_range(start, end, freq="D") + assert dti.unit == unit + + dti = pd.date_range(start, end.as_unit("ns"), freq="D") + assert dti.unit == "ns" + + def test_date_range_unit_inference_tick(self): + start = pd.Timestamp("2025-11-25").as_unit("ms") + end = pd.Timestamp("2025-11-26").as_unit("s") + + dti = pd.date_range(start, end, freq="2000000us") + assert dti.unit == "us" + + dti = pd.date_range(start, end.as_unit("ns"), freq="2000000us") + assert dti.unit == "ns" + + def test_date_range_unit_inference_dateoffset_freq(self): + start = pd.Timestamp("2025-11-25 09:00:00").as_unit("s") + end = pd.Timestamp("2025-11-25 09:00:02").as_unit("s") + + off = DateOffset(microseconds=2_000_000) + dti = pd.date_range(start, end, freq=off) + assert dti.unit == "us" + + off = DateOffset(milliseconds=2) + dti = pd.date_range(start, end, freq=off) + assert dti.unit == "ms" + + end2 = start + pd.Timedelta(microseconds=2).as_unit("us") + off = DateOffset(nanoseconds=2) + dti = pd.date_range(start, end2, freq=off) + assert dti.unit == "ns" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_datetime.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_datetime.py new file mode 100644 index 0000000000000000000000000000000000000000..97310c6ae984d970789eb610d294f62dc8feafa6 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_datetime.py @@ -0,0 +1,151 @@ +import datetime as dt +from datetime import date + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndex: + def test_is_(self): + dti = pd.date_range(start="1/1/2005", end="12/1/2005", freq="ME") + assert dti.is_(dti) + assert dti.is_(dti.view()) + assert not dti.is_(dti.copy()) + + def test_time_overflow_for_32bit_machines(self): + # GH8943. On some machines NumPy defaults to np.int32 (for example, + # 32-bit Linux machines). In the function _generate_regular_range + # found in tseries/index.py, `periods` gets multiplied by `strides` + # (which has value 1e9) and since the max value for np.int32 is ~2e9, + # and since those machines won't promote np.int32 to np.int64, we get + # overflow. + periods = np.long(1000) + + idx1 = pd.date_range(start="2000", periods=periods, freq="s") + assert len(idx1) == periods + + idx2 = pd.date_range(end="2000", periods=periods, freq="s") + assert len(idx2) == periods + + def test_nat(self): + assert pd.DatetimeIndex([np.nan])[0] is pd.NaT + + def test_week_of_month_frequency(self): + # GH 5348: "ValueError: Could not evaluate WOM-1SUN" shouldn't raise + d1 = date(2002, 9, 1) + d2 = date(2013, 10, 27) + d3 = date(2012, 9, 30) + idx1 = pd.DatetimeIndex([d1, d2]) + idx2 = pd.DatetimeIndex([d3]) + result_append = idx1.append(idx2) + expected = pd.DatetimeIndex([d1, d2, d3]) + tm.assert_index_equal(result_append, expected) + result_union = idx1.union(idx2) + expected = pd.DatetimeIndex([d1, d3, d2]) + tm.assert_index_equal(result_union, expected) + + def test_append_nondatetimeindex(self): + rng = pd.date_range("1/1/2000", periods=10) + idx = pd.Index(["a", "b", "c", "d"]) + + result = rng.append(idx) + assert isinstance(result[0], pd.Timestamp) + + def test_misc_coverage(self): + rng = pd.date_range("1/1/2000", periods=5) + result = rng.groupby(rng.day) + assert isinstance(next(iter(result.values()))[0], pd.Timestamp) + + def assert_index_parameters(self, index): + assert index.freq == "40960ns" + msg = "A future version of pandas will return a BaseOffset" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + assert index.inferred_freq == "40960ns" + + def test_ns_index(self): + nsamples = 400 + ns = int(1e9 / 24414) + dtstart = np.datetime64("2012-09-20T00:00:00") + + dt = dtstart + np.arange(nsamples) * np.timedelta64(ns, "ns") + freq = ns * pd.offsets.Nano() + index = pd.DatetimeIndex(dt, freq=freq, name="time") + self.assert_index_parameters(index) + + new_index = pd.date_range(start=index[0], end=index[-1], freq=index.freq) + self.assert_index_parameters(new_index) + + def test_asarray_tz_naive(self): + # This shouldn't produce a warning. + idx = pd.date_range("2000", periods=2, unit="ns") + # M8[ns] by default + result = np.asarray(idx) + + expected = np.array(["2000-01-01", "2000-01-02"], dtype="M8[ns]") + tm.assert_numpy_array_equal(result, expected) + + # optionally, object + result = np.asarray(idx, dtype=object) + + expected = np.array([pd.Timestamp("2000-01-01"), pd.Timestamp("2000-01-02")]) + tm.assert_numpy_array_equal(result, expected) + + def test_asarray_tz_aware(self): + tz = "US/Central" + idx = pd.date_range("2000", periods=2, tz=tz, unit="ns") + expected = np.array(["2000-01-01T06", "2000-01-02T06"], dtype="M8[ns]") + result = np.asarray(idx, dtype="datetime64[ns]") + + tm.assert_numpy_array_equal(result, expected) + + # Old behavior with no warning + result = np.asarray(idx, dtype="M8[ns]") + + tm.assert_numpy_array_equal(result, expected) + + # Future behavior with no warning + expected = np.array( + [pd.Timestamp("2000-01-01", tz=tz), pd.Timestamp("2000-01-02", tz=tz)] + ) + result = np.asarray(idx, dtype=object) + + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("freq", ["2H", "2BH", "2S"]) + def test_CBH_raises(self, freq): + msg = f"Invalid frequency: {freq}" + + with pytest.raises(ValueError, match=msg): + pd.date_range( + dt.datetime(2022, 12, 11), dt.datetime(2022, 12, 13), freq=freq + ) + + @pytest.mark.parametrize("freq", ["2BM", "1bm", "2BQ", "1BQ-MAR", "2BY-JUN", "1by"]) + def test_BM_BQ_BY_raises(self, freq): + msg = f"Invalid frequency: {freq}" + + with pytest.raises(ValueError, match=msg): + pd.date_range(start="2016-02-21", end="2016-08-21", freq=freq) + + @pytest.mark.parametrize("freq", ["2BA-MAR", "1BAS-MAY", "2AS-AUG"]) + def test_BA_BAS_raises(self, freq): + msg = f"Invalid frequency: {freq}" + + with pytest.raises(ValueError, match=msg): + pd.date_range(start="2016-02-21", end="2016-08-21", freq=freq) + + @pytest.mark.parametrize("pa_type", ["date32", "date64"]) + def test_get_indexer_arrow_date_types(self, pa_type): + # GH#62051 - should not raise AttributeError + pa = pytest.importorskip("pyarrow") + + dti = pd.DatetimeIndex(["2017-01-01", "2018-01-01"]) + other = pd.Index(dti, dtype=pd.ArrowDtype(getattr(pa, pa_type)())) + result = dti.get_indexer(other) + expected = np.array([-1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_formats.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_formats.py new file mode 100644 index 0000000000000000000000000000000000000000..32cffff9a856daf9ed043535701f85824362da6d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_formats.py @@ -0,0 +1,318 @@ +from datetime import ( + UTC, + datetime, +) + +import dateutil.tz +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_get_values_for_csv_sub_minute_utc_offset(): + # GH#66547 array formatting routes through Timestamp.isoformat, so a UTC + # offset carrying seconds used to have the fraction spliced into it + dti = pd.DatetimeIndex(["1800-01-01 00:00:00.000000001"], tz="UTC").tz_convert( + "Asia/Tokyo" + ) + expected = np.array(["1800-01-01 09:18:59.000000001+09:18:59"], dtype=object) + + tm.assert_numpy_array_equal(dti._get_values_for_csv(), expected) + tm.assert_numpy_array_equal(pd.Series(dti).astype(str).to_numpy(), expected) + assert expected[0] in repr(dti) + + +def test_get_values_for_csv(): + index = pd.date_range(freq="1D", periods=3, start="2017-01-01") + + # First, with no arguments. + expected = np.array(["2017-01-01", "2017-01-02", "2017-01-03"], dtype=object) + + result = index._get_values_for_csv() + tm.assert_numpy_array_equal(result, expected) + + # No NaN values, so na_rep has no effect + result = index._get_values_for_csv(na_rep="pandas") + tm.assert_numpy_array_equal(result, expected) + + # Make sure date formatting works + expected = np.array(["01-2017-01", "01-2017-02", "01-2017-03"], dtype=object) + + result = index._get_values_for_csv(date_format="%m-%Y-%d") + tm.assert_numpy_array_equal(result, expected) + + # NULL object handling should work + index = pd.DatetimeIndex(["2017-01-01", pd.NaT, "2017-01-03"]) + expected = np.array(["2017-01-01", "NaT", "2017-01-03"], dtype=object) + + result = index._get_values_for_csv(na_rep="NaT") + tm.assert_numpy_array_equal(result, expected) + + expected = np.array(["2017-01-01", "pandas", "2017-01-03"], dtype=object) + + result = index._get_values_for_csv(na_rep="pandas") + tm.assert_numpy_array_equal(result, expected) + + result = index._get_values_for_csv(na_rep="NaT", date_format="%Y-%m-%d %H:%M:%S.%f") + expected = np.array( + ["2017-01-01 00:00:00.000000", "NaT", "2017-01-03 00:00:00.000000"], + dtype=object, + ) + tm.assert_numpy_array_equal(result, expected) + + # invalid format + result = index._get_values_for_csv(na_rep="NaT", date_format="foo") + expected = np.array(["foo", "NaT", "foo"], dtype=object) + tm.assert_numpy_array_equal(result, expected) + + +class TestDatetimeIndexRendering: + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_dti_with_timezone_repr(self, tzstr): + rng = pd.date_range("4/13/2010", "5/6/2010") + + rng_eastern = rng.tz_localize(tzstr) + + rng_repr = repr(rng_eastern) + assert "2010-04-13 00:00:00" in rng_repr + + def test_dti_repr_dates(self): + text = str(pd.to_datetime([datetime(2013, 1, 1), datetime(2014, 1, 1)])) + assert "['2013-01-01'," in text + assert ", '2014-01-01']" in text + + def test_dti_repr_mixed(self): + text = str( + pd.to_datetime( + [datetime(2013, 1, 1), datetime(2014, 1, 1, 12), datetime(2014, 1, 1)] + ) + ) + assert "'2013-01-01 00:00:00'," in text + assert "'2014-01-01 00:00:00']" in text + + def test_dti_repr_short(self): + dr = pd.date_range(start="1/1/2012", periods=1) + repr(dr) + + dr = pd.date_range(start="1/1/2012", periods=2) + repr(dr) + + dr = pd.date_range(start="1/1/2012", periods=3) + repr(dr) + + @pytest.mark.parametrize( + "dates, freq, expected_repr", + [ + ( + ["2012-01-01 00:00:00"], + "60min", + ( + "DatetimeIndex(['2012-01-01 00:00:00'], " + "dtype='datetime64[ns]', freq='60min')" + ), + ), + ( + ["2012-01-01 00:00:00", "2012-01-01 01:00:00"], + "60min", + "DatetimeIndex(['2012-01-01 00:00:00', " + "'2012-01-01 01:00:00'],\n" + " dtype='datetime64[ns]', freq='60min')", + ), + ( + ["2012-01-01"], + "24h", + "DatetimeIndex(['2012-01-01'], dtype='datetime64[ns]', freq='24h')", + ), + ], + ) + def test_dti_repr_time_midnight(self, dates, freq, expected_repr, unit): + # GH53634 + dti = pd.DatetimeIndex(dates, freq).as_unit(unit) + actual_repr = repr(dti) + assert actual_repr == expected_repr.replace("[ns]", f"[{unit}]") + + def test_dti_repr_wraps_at_display_width(self): + # GH#11552 + dti = pd.date_range("2011-01-01", periods=3, freq="D", name="dates") + result = repr(dti) + expected = ( + "DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'],\n" + " dtype='datetime64[us]', name='dates', freq='D')" + ) + assert result == expected + + def test_dti_repr_two_values_wraps_at_display_width(self): + # GH#16334 + dti = pd.DatetimeIndex( + ["2017-01-01 12:00:00.000000001", "2017-01-02 12:00:00.000000001"] + ).tz_localize("US/Eastern") + result = repr(dti) + expected = ( + "DatetimeIndex(['2017-01-01 12:00:00.000000001-05:00',\n" + " '2017-01-02 12:00:00.000000001-05:00'],\n" + " dtype='datetime64[ns, US/Eastern]', freq=None)" + ) + assert result == expected + + def test_dti_representation(self, unit): + idxs = [] + idxs.append(pd.DatetimeIndex([], freq="D")) + idxs.append(pd.DatetimeIndex(["2011-01-01"], freq="D")) + idxs.append(pd.DatetimeIndex(["2011-01-01", "2011-01-02"], freq="D")) + idxs.append( + pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], freq="D") + ) + idxs.append( + pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], + freq="h", + tz="Asia/Tokyo", + ) + ) + idxs.append( + pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", pd.NaT], tz="US/Eastern" + ) + ) + idxs.append( + pd.DatetimeIndex(["2011-01-01 09:00", "2011-01-01 10:00", pd.NaT], tz="UTC") + ) + + exp = [] + exp.append("DatetimeIndex([], dtype='datetime64[ns]', freq='D')") + exp.append("DatetimeIndex(['2011-01-01'], dtype='datetime64[ns]', freq='D')") + exp.append( + "DatetimeIndex(['2011-01-01', '2011-01-02'], " + "dtype='datetime64[ns]', freq='D')" + ) + exp.append( + "DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'], " + "dtype='datetime64[ns]', freq='D')" + ) + exp.append( + "DatetimeIndex(['2011-01-01 09:00:00+09:00', " + "'2011-01-01 10:00:00+09:00', '2011-01-01 11:00:00+09:00']" + ", dtype='datetime64[ns, Asia/Tokyo]', freq='h')" + ) + exp.append( + "DatetimeIndex(['2011-01-01 09:00:00-05:00', " + "'2011-01-01 10:00:00-05:00', 'NaT'], " + "dtype='datetime64[ns, US/Eastern]', freq=None)" + ) + exp.append( + "DatetimeIndex(['2011-01-01 09:00:00+00:00', " + "'2011-01-01 10:00:00+00:00', 'NaT'], " + "dtype='datetime64[ns, UTC]', freq=None)" + "" + ) + + with pd.option_context("display.width", 300): + for index, expected in zip(idxs, exp, strict=True): + index = index.as_unit(unit) + expected = expected.replace("[ns", f"[{unit}") + result = repr(index) + assert result == expected + result = str(index) + assert result == expected + + # TODO: this is a Series.__repr__ test + def test_dti_representation_to_series(self, unit): + idx1 = pd.DatetimeIndex([], freq="D") + idx2 = pd.DatetimeIndex(["2011-01-01"], freq="D") + idx3 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], freq="D") + idx4 = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], freq="D") + idx5 = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], + freq="h", + tz="Asia/Tokyo", + ) + idx6 = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", pd.NaT], tz="US/Eastern" + ) + idx7 = pd.DatetimeIndex(["2011-01-01 09:00", "2011-01-02 10:15"]) + + exp1 = """Series([], dtype: datetime64[ns])""" + + exp2 = "0 2011-01-01\ndtype: datetime64[ns]" + + exp3 = "0 2011-01-01\n1 2011-01-02\ndtype: datetime64[ns]" + + exp4 = "0 2011-01-01\n1 2011-01-02\n2 2011-01-03\ndtype: datetime64[ns]" + + exp5 = ( + "0 2011-01-01 09:00:00+09:00\n" + "1 2011-01-01 10:00:00+09:00\n" + "2 2011-01-01 11:00:00+09:00\n" + "dtype: datetime64[ns, Asia/Tokyo]" + ) + + exp6 = ( + "0 2011-01-01 09:00:00-05:00\n" + "1 2011-01-01 10:00:00-05:00\n" + "2 NaT\n" + "dtype: datetime64[ns, US/Eastern]" + ) + + exp7 = "0 2011-01-01 09:00:00\n1 2011-01-02 10:15:00\ndtype: datetime64[ns]" + + with pd.option_context("display.width", 300): + for idx, expected in zip( + [idx1, idx2, idx3, idx4, idx5, idx6, idx7], + [exp1, exp2, exp3, exp4, exp5, exp6, exp7], + strict=True, + ): + ser = pd.Series(idx.as_unit(unit)) + result = repr(ser) + assert result == expected.replace("[ns", f"[{unit}") + + def test_dti_summary(self): + # GH#9116 + idx1 = pd.DatetimeIndex([], freq="D") + idx2 = pd.DatetimeIndex(["2011-01-01"], freq="D") + idx3 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], freq="D") + idx4 = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], freq="D") + idx5 = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], + freq="h", + tz="Asia/Tokyo", + ) + idx6 = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", pd.NaT], tz="US/Eastern" + ) + + exp1 = "DatetimeIndex: 0 entries\nFreq: D" + + exp2 = "DatetimeIndex: 1 entries, 2011-01-01 to 2011-01-01\nFreq: D" + + exp3 = "DatetimeIndex: 2 entries, 2011-01-01 to 2011-01-02\nFreq: D" + + exp4 = "DatetimeIndex: 3 entries, 2011-01-01 to 2011-01-03\nFreq: D" + + exp5 = ( + "DatetimeIndex: 3 entries, 2011-01-01 09:00:00+09:00 " + "to 2011-01-01 11:00:00+09:00\n" + "Freq: h" + ) + + exp6 = """DatetimeIndex: 3 entries, 2011-01-01 09:00:00-05:00 to NaT""" + + for idx, expected in zip( + [idx1, idx2, idx3, idx4, idx5, idx6], + [exp1, exp2, exp3, exp4, exp5, exp6], + strict=True, + ): + result = idx._summary() + assert result == expected + + @pytest.mark.parametrize("tz", [None, UTC, dateutil.tz.tzutc()]) + @pytest.mark.parametrize("freq", ["B", "C"]) + def test_dti_business_repr_etc_smoke(self, tz, freq): + # only really care that it works + dti = pd.bdate_range( + datetime(2009, 1, 1), datetime(2010, 1, 1), tz=tz, freq=freq + ) + repr(dti) + dti._summary() + dti[2:2]._summary() diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_freq_attr.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_freq_attr.py new file mode 100644 index 0000000000000000000000000000000000000000..9ff65e7dcf850285ad36c7f2088179513a1d4c3d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_freq_attr.py @@ -0,0 +1,57 @@ +import pytest + +import pandas as pd + +from pandas.tseries.offsets import ( + BaseOffset, + BDay, + Day, + Hour, +) + + +class TestFreq: + def test_freq_setter_errors(self): + # GH#20678 + idx = pd.DatetimeIndex(["20180101", "20180103", "20180105"]) + + # setting with an incompatible freq + msg = ( + "Inferred frequency 2D from passed values does not conform to " + "passed frequency 5D" + ) + with pytest.raises(ValueError, match=msg): + idx.freq = "5D" + + # setting with non-freq string + with pytest.raises(ValueError, match="Invalid frequency"): + idx.freq = "foo" + + @pytest.mark.parametrize("values", [["20180101", "20180103", "20180105"], []]) + @pytest.mark.parametrize("freq", ["2D", Day(2), "2B", BDay(2), "48h", Hour(48)]) + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + def test_freq_setter(self, values, freq, tz): + # GH#20678 + idx = pd.DatetimeIndex(values, tz=tz) + + # can set to an offset, converting from string if necessary + idx.freq = freq + assert idx.freq == freq + assert isinstance(idx.freq, BaseOffset) + + # can reset to None + idx.freq = None + assert idx.freq is None + + def test_freq_view_safe(self): + # Setting the freq for one DatetimeIndex shouldn't alter the freq + # for another that views the same data + + dti = pd.date_range("2016-01-01", periods=5) + dta = dti._data + + dti2 = pd.DatetimeIndex(dta)._with_freq(None) + assert dti2.freq is None + + # Original was not altered. freq is now Index-level state. + assert dti.freq == "D" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..0efff3f1728de81dc7fe737532fa9dec7615d7ef --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_indexing.py @@ -0,0 +1,825 @@ +from datetime import ( + date, + datetime, + time, + timedelta, +) + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + +from pandas.tseries.frequencies import to_offset + +START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) + + +class TestGetItem: + def test_getitem_slice_keeps_name(self): + # GH4226 + st = pd.Timestamp("2013-07-01 00:00:00", tz="America/Los_Angeles") + et = pd.Timestamp("2013-07-02 00:00:00", tz="America/Los_Angeles") + dr = pd.date_range(st, et, freq="h", name="timebucket") + assert dr[1:].name == dr.name + + @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"]) + def test_getitem(self, tz): + idx = pd.date_range("2011-01-01", "2011-01-31", freq="D", tz=tz, name="idx") + + result = idx[0] + assert result == pd.Timestamp("2011-01-01", tz=idx.tz) + + result = idx[0:5] + expected = pd.date_range( + "2011-01-01", "2011-01-05", freq="D", tz=idx.tz, name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx[0:10:2] + expected = pd.date_range( + "2011-01-01", "2011-01-09", freq="2D", tz=idx.tz, name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx[-20:-5:3] + expected = pd.date_range( + "2011-01-12", "2011-01-24", freq="3D", tz=idx.tz, name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx[4::-1] + expected = pd.DatetimeIndex( + ["2011-01-05", "2011-01-04", "2011-01-03", "2011-01-02", "2011-01-01"], + dtype=idx.dtype, + freq="-1D", + name="idx", + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + @pytest.mark.parametrize("freq", ["B", "C"]) + def test_dti_business_getitem(self, freq): + rng = pd.bdate_range(START, END, freq=freq) + smaller = rng[:5] + exp = pd.DatetimeIndex(rng.view(np.ndarray)[:5], freq=freq) + tm.assert_index_equal(smaller, exp) + assert smaller.freq == exp.freq + assert smaller.freq == rng.freq + + sliced = rng[::5] + assert sliced.freq == to_offset(freq) * 5 + + fancy_indexed = rng[[4, 3, 2, 1, 0]] + assert len(fancy_indexed) == 5 + assert isinstance(fancy_indexed, pd.DatetimeIndex) + assert fancy_indexed.freq is None + + # 32-bit vs. 64-bit platforms + assert rng[4] == rng[np.int32(4)] + assert rng[4] == rng[np.int64(4)] + + @pytest.mark.parametrize("freq", ["B", "C"]) + def test_dti_business_getitem_matplotlib_hackaround(self, freq): + rng = pd.bdate_range(START, END, freq=freq) + with pytest.raises(ValueError, match="Multi-dimensional indexing"): + # GH#30588 multi-dimensional indexing deprecated + rng[:, None] + + def test_getitem_int_list(self): + dti = pd.date_range(start="1/1/2005", end="12/1/2005", freq="ME") + dti2 = dti[[1, 3, 5]] + + v1 = dti2[0] + v2 = dti2[1] + v3 = dti2[2] + + assert v1 == pd.Timestamp("2/28/2005") + assert v2 == pd.Timestamp("4/30/2005") + assert v3 == pd.Timestamp("6/30/2005") + + # getitem with non-slice drops freq + assert dti2.freq is None + + +class TestWhere: + @pytest.mark.parametrize("is_td", [True, False]) + def test_where_freq_invalidation(self, is_td): + # GH#24555 + index = pd.date_range("20130101", periods=3, tz="US/Eastern") + if is_td: + index = index - index[0] + other = pd.Index([pd.NaT, pd.NaT, *index[2:].tolist()]) + + result = index.where(pd.notna(other), other) + assert result.freq is None + + def test_where_doesnt_retain_freq(self): + dti = pd.date_range("20130101", periods=3, freq="D", name="idx") + cond = [True, True, False] + expected = pd.DatetimeIndex([dti[0], dti[1], dti[0]], freq=None, name="idx") + + result = dti.where(cond, dti[::-1]) + tm.assert_index_equal(result, expected) + + def test_where_other(self): + # other is ndarray or Index + i = pd.date_range("20130101", periods=3, tz="US/Eastern") + + for arr in [np.nan, pd.NaT]: + result = i.where(pd.notna(i), other=arr) + expected = i + tm.assert_index_equal(result, expected, check_freq=False) + + i2 = i.copy() + i2 = pd.Index([pd.NaT, pd.NaT, *i[2:].tolist()]) + result = i.where(pd.notna(i2), i2) + tm.assert_index_equal(result, i2) + + i2 = i.copy() + i2 = pd.Index([pd.NaT, pd.NaT, *i[2:].tolist()]) + result = i.where(pd.notna(i2), i2._values) + tm.assert_index_equal(result, i2) + + def test_where_invalid_dtypes(self): + dti = pd.date_range("20130101", periods=3, tz="US/Eastern", unit="ns") + + tail = dti[2:].tolist() + i2 = pd.Index([pd.NaT, pd.NaT, *tail]) + + mask = pd.notna(i2) + + # passing tz-naive ndarray to tzaware DTI + i2_values = i2.array._ndarray + result = dti.where(mask, i2_values) + expected = pd.Index([pd.NaT, pd.NaT, *tail], dtype=object) + tm.assert_index_equal(result, expected) + + # passing tz-aware DTI to tznaive DTI + naive = dti.tz_localize(None) + result = naive.where(mask, i2) + expected = pd.Index([i2[0], i2[1], *naive[2:].tolist()], dtype=object) + tm.assert_index_equal(result, expected) + + pi = i2.tz_localize(None).to_period("D") + result = dti.where(mask, pi) + expected = pd.Index([pd.NaT, pd.NaT, *tail], dtype=object) + tm.assert_index_equal(result, expected) + + tda = i2.asi8.view("timedelta64[ns]") + result = dti.where(mask, tda) + expected = pd.Index([pd.NaT, pd.NaT, *tail], dtype=object) + tm.assert_index_equal(result, expected) + + result = dti.where(mask, i2.asi8) + expected = pd.Index([pd.NaT._value, pd.NaT._value, *tail], dtype=object) + assert isinstance(expected[0], int) + tm.assert_index_equal(result, expected) + + # non-matching scalar + td = pd.Timedelta(days=4) + result = dti.where(mask, td) + expected = pd.Index([td, td, *tail], dtype=object) + assert expected[0] is td + tm.assert_index_equal(result, expected) + + def test_where_mismatched_nat(self, tz_aware_fixture): + tz = tz_aware_fixture + dti = pd.date_range("2013-01-01", periods=3, tz=tz) + cond = np.array([True, False, True]) + + tdnat = np.timedelta64("NaT", "ns") + expected = pd.Index([dti[0], tdnat, dti[2]], dtype=object) + assert expected[1] is tdnat + + result = dti.where(cond, tdnat) + tm.assert_index_equal(result, expected) + + def test_where_tz(self): + i = pd.date_range("20130101", periods=3, tz="US/Eastern") + result = i.where(pd.notna(i)) + expected = i + tm.assert_index_equal(result, expected, check_freq=False) + + i2 = i.copy() + i2 = pd.Index([pd.NaT, pd.NaT, *i[2:].tolist()]) + result = i.where(pd.notna(i2)) + expected = i2 + tm.assert_index_equal(result, expected) + + +class TestTake: + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_dti_take_dont_lose_meta(self, tzstr): + rng = pd.date_range("1/1/2000", periods=20, tz=tzstr) + + result = rng.take(range(5)) + assert result.tz == rng.tz + assert result.freq == rng.freq + + def test_take_nan_first_datetime(self): + index = pd.DatetimeIndex( + [pd.NaT, pd.Timestamp("20130101"), pd.Timestamp("20130102")] + ) + result = index.take([-1, 0, 1]) + expected = pd.DatetimeIndex([index[-1], index[0], index[1]]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"]) + def test_take(self, tz): + # GH#10295 + idx = pd.date_range("2011-01-01", "2011-01-31", freq="D", name="idx", tz=tz) + + result = idx.take([0]) + assert result == pd.Timestamp("2011-01-01", tz=idx.tz) + + result = idx.take([0, 1, 2]) + expected = pd.date_range( + "2011-01-01", "2011-01-03", freq="D", tz=idx.tz, name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx.take([0, 2, 4]) + expected = pd.date_range( + "2011-01-01", "2011-01-05", freq="2D", tz=idx.tz, name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx.take([7, 4, 1]) + expected = pd.date_range( + "2011-01-08", "2011-01-02", freq="-3D", tz=idx.tz, name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx.take([3, 2, 5]) + expected = pd.DatetimeIndex( + ["2011-01-04", "2011-01-03", "2011-01-06"], + dtype=idx.dtype, + freq=None, + name="idx", + ) + tm.assert_index_equal(result, expected) + assert result.freq is None + + result = idx.take([-3, 2, 5]) + expected = pd.DatetimeIndex( + ["2011-01-29", "2011-01-03", "2011-01-06"], + dtype=idx.dtype, + freq=None, + name="idx", + ) + tm.assert_index_equal(result, expected) + assert result.freq is None + + def test_take_invalid_kwargs(self): + idx = pd.date_range("2011-01-01", "2011-01-31", freq="D", name="idx") + indices = [1, 6, 5, 9, 10, 13, 15, 3] + + msg = r"take\(\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg): + idx.take(indices, foo=2) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, out=indices) + + msg = "the 'mode' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, mode="clip") + + # TODO: This method came from test_datetime; de-dup with version above + @pytest.mark.parametrize("tz", [None, "US/Eastern", "Asia/Tokyo"]) + def test_take2(self, tz): + dates = [ + datetime(2010, 1, 1, 14), + datetime(2010, 1, 1, 15), + datetime(2010, 1, 1, 17), + datetime(2010, 1, 1, 21), + ] + + idx = pd.date_range( + start="2010-01-01 09:00", + end="2010-02-01 09:00", + freq="h", + tz=tz, + name="idx", + ) + expected = pd.DatetimeIndex(dates, freq=None, name="idx", dtype=idx.dtype) + + taken1 = idx.take([5, 6, 8, 12]) + taken2 = idx[[5, 6, 8, 12]] + + for taken in [taken1, taken2]: + tm.assert_index_equal(taken, expected) + assert isinstance(taken, pd.DatetimeIndex) + assert taken.freq is None + assert taken.tz == expected.tz + assert taken.name == expected.name + + def test_take_fill_value(self): + # GH#12631 + idx = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx") + result = idx.take(np.array([1, 0, -1])) + expected = pd.DatetimeIndex( + ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx" + ) + tm.assert_index_equal(result, expected) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=pd.NaT) + expected = pd.DatetimeIndex(["2011-02-01", "2011-01-01", "NaT"], name="xxx") + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False) + expected = pd.DatetimeIndex( + ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx" + ) + tm.assert_index_equal(result, expected) + + msg = "When allow_fill=True, all indices must be >= -1" + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + msg = "out of bounds" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + def test_take_fill_value_with_timezone(self): + idx = pd.DatetimeIndex( + ["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx", tz="US/Eastern" + ) + result = idx.take(np.array([1, 0, -1])) + expected = pd.DatetimeIndex( + ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx", tz="US/Eastern" + ) + tm.assert_index_equal(result, expected) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=pd.NaT) + expected = pd.DatetimeIndex( + ["2011-02-01", "2011-01-01", "NaT"], name="xxx", tz="US/Eastern" + ) + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False) + expected = pd.DatetimeIndex( + ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx", tz="US/Eastern" + ) + tm.assert_index_equal(result, expected) + + msg = "When allow_fill=True, all indices must be >= -1" + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + msg = "out of bounds" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + +class TestGetLoc: + def test_get_loc_key_unit_mismatch(self): + idx = pd.date_range("2000-01-01", periods=3) + key = idx[1].as_unit("ms") + loc = idx.get_loc(key) + assert loc == 1 + assert key in idx + + def test_get_loc_key_unit_mismatch_not_castable(self): + dta = pd.date_range("2000-01-01", periods=3)._data.astype("M8[s]") + dti = pd.DatetimeIndex(dta) + key = dta[0].as_unit("ns") + pd.Timedelta(1) + + with pytest.raises( + KeyError, match=r"Timestamp\('2000-01-01 00:00:00.000000001'\)" + ): + dti.get_loc(key) + + assert key not in dti + + def test_get_loc_time_obj(self): + # time indexing + idx = pd.date_range("2000-01-01", periods=24, freq="h") + + result = idx.get_loc(time(12)) + expected = np.array([12]) + tm.assert_numpy_array_equal(result, expected, check_dtype=False) + + result = idx.get_loc(time(12, 30)) + expected = np.array([]) + tm.assert_numpy_array_equal(result, expected, check_dtype=False) + + def test_get_loc_time_obj2(self): + # GH#8667 + key = time(15, 11, 30) + start = (key.hour * 3600 + key.minute * 60 + key.second) // 30 + step = 24 * 3600 // 30 + n = 3 * step + + idx = pd.date_range("2014-11-26", periods=n, freq="30s") + ts = pd.Series(np.random.default_rng(2).standard_normal(n), index=idx) + locs = np.arange(start, n, step, dtype=np.intp) + assert len(locs) == 3 + + result = ts.index.get_loc(key) + tm.assert_numpy_array_equal(result, locs) + tm.assert_series_equal(ts[key], ts.iloc[locs]) + + left, right = ts.copy(), ts.copy() + left[key] *= -10 + right.iloc[locs] *= -10 + tm.assert_series_equal(left, right) + + def test_get_loc_time_nat(self): + # GH#35114 + # Case where key's total microseconds happens to match iNaT % 1e6 // 1000 + tic = time(minute=12, second=43, microsecond=145224) + dti = pd.DatetimeIndex([pd.NaT]) + + loc = dti.get_loc(tic) + expected = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(loc, expected) + + def test_get_loc_nat(self): + # GH#20464 + index = pd.DatetimeIndex(["1/3/2000", "NaT"]) + assert index.get_loc(pd.NaT) == 1 + + assert index.get_loc(None) == 1 + + assert index.get_loc(np.nan) == 1 + + assert index.get_loc(pd.NA) == 1 + + assert index.get_loc(np.datetime64("NaT", "ns")) == 1 + + with pytest.raises(KeyError, match="NaT"): + index.get_loc(np.timedelta64("NaT", "ns")) + + @pytest.mark.parametrize("key", [pd.Timedelta(0), pd.Timedelta(1), timedelta(0)]) + def test_get_loc_timedelta_invalid_key(self, key): + # GH#20464 + dti = pd.date_range("1970-01-01", periods=10) + msg = "Cannot index DatetimeIndex with [Tt]imedelta" + with pytest.raises(TypeError, match=msg): + dti.get_loc(key) + + def test_get_loc_reasonable_key_error(self): + # GH#1062 + index = pd.DatetimeIndex(["1/3/2000"]) + with pytest.raises(KeyError, match="2000"): + index.get_loc("1/1/2000") + + def test_get_loc_nonmonotonic_missing_label(self): + # GH#7827 a missing label on a non-monotonic DatetimeIndex should + # raise KeyError rather than return an empty array + index = pd.to_datetime(["2000-01-02", "2000-01-01"]) + assert not index.is_monotonic_increasing + with pytest.raises(KeyError, match="1900-01-01"): + index.get_loc("1900-01-01") + with pytest.raises(KeyError, match="1900-01-01"): + index.get_loc(pd.Timestamp("1900-01-01")) + + def test_get_loc_year_str(self): + rng = pd.date_range("1/1/2000", "1/1/2010") + + result = rng.get_loc("2009") + expected = slice(3288, 3653) + assert result == expected + + +class TestContains: + def test_dti_contains_with_duplicates(self): + d = datetime(2011, 12, 5, 20, 30) + ix = pd.DatetimeIndex([d, d]) + assert d in ix + + @pytest.mark.parametrize( + "vals", + [ + [0, 1, 0], + [0, 0, -1], + [0, -1, -1], + ["2015", "2015", "2016"], + ["2015", "2015", "2014"], + ], + ) + def test_contains_nonunique(self, vals): + # GH#9512 + idx = pd.DatetimeIndex(vals) + assert idx[0] in idx + + +class TestGetIndexer: + @td.skip_if_no("pyarrow") + @pytest.mark.parametrize("as_td", [True, False]) + def test_get_indexer_pyarrow(self, as_td): + # GH#62277 + index = pd.date_range("2016-01-01", periods=3) + target = index.astype("timestamp[ns][pyarrow]")[::-1] + if as_td: + # Test duration dtypes while we're here + index = index - index[0] + target = target - target[-1] + + result = index.get_indexer(target) + + expected = np.array([2, 1, 0], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + # Reversed op should work the same + result2 = target.get_indexer(index) + tm.assert_numpy_array_equal(result2, expected) + + def test_get_indexer_date_objs(self): + rng = pd.date_range("1/1/2000", periods=20) + + msg = "Inferring datetime64 from data containing datetime.date objects" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = rng.get_indexer(rng.map(lambda x: x.date())) + expected = rng.get_indexer(rng) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer(self): + idx = pd.date_range("2000-01-01", periods=3) + exp = np.array([0, 1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(idx.get_indexer(idx), exp) + + target = idx[0] + pd.to_timedelta(["-1 hour", "12 hours", "1 day 1 hour"]) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "nearest", tolerance=pd.Timedelta("1 hour")), + np.array([0, -1, 1], dtype=np.intp), + ) + tol_raw = [ + pd.Timedelta("1 hour"), + pd.Timedelta("1 hour"), + pd.Timedelta("1 hour").to_timedelta64(), + ] + tm.assert_numpy_array_equal( + idx.get_indexer( + target, "nearest", tolerance=[np.timedelta64(x) for x in tol_raw] + ), + np.array([0, -1, 1], dtype=np.intp), + ) + tol_bad = [ + pd.Timedelta("2 hour").to_timedelta64(), + pd.Timedelta("1 hour").to_timedelta64(), + "foo", + ] + msg = "Could not convert 'foo' to NumPy timedelta" + with pytest.raises(ValueError, match=msg): + idx.get_indexer(target, "nearest", tolerance=tol_bad) + with pytest.raises(ValueError, match="abbreviation w/o a number"): + idx.get_indexer(idx[[0]], method="nearest", tolerance="foo") + + @pytest.mark.parametrize( + "target", + [ + [date(2020, 1, 1), pd.Timestamp("2020-01-02")], + [pd.Timestamp("2020-01-01"), date(2020, 1, 2)], + ], + ) + def test_get_indexer_mixed_dtypes(self, target): + # https://github.com/pandas-dev/pandas/issues/33741 + values = pd.DatetimeIndex( + [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")] + ) + # GH#62158 mixed date/Timestamp list infers as "date", triggering + # the _maybe_downcast_for_indexing fallback + msg = "Indexing a DatetimeIndex with a sequence of datetime.date" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = values.get_indexer(target) + expected = np.array([0, 1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "target, positions", + [ + ([date(9999, 1, 1), pd.Timestamp("2020-01-01")], [-1, 0]), + ([pd.Timestamp("2020-01-01"), date(9999, 1, 1)], [0, -1]), + ([date(9999, 1, 1), date(9999, 1, 1)], [-1, -1]), + ], + ) + def test_get_indexer_out_of_bounds_date(self, target, positions): + # GH#62158 + values = pd.DatetimeIndex( + [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")] + ) + + msg = "Indexing a DatetimeIndex with a sequence of datetime.date" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = values.get_indexer(target) + expected = np.array(positions, dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_mixed_date_tzaware(self): + # GH#68577 target is not convertible to datetime64, so it is compared + # as object instead of raising "Mixed timezones detected" + ts = pd.Timestamp("2020-01-01", tz="UTC") + values = pd.DatetimeIndex([ts]) + target = pd.Index([date(2020, 1, 1), ts], dtype=object) + + msg = "Inferring datetime64 from data containing datetime.date objects" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = values.get_indexer(target) + expected = np.array([-1, 0], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "US/Central"]) + @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"]) + def test_get_indexer_nat_target(self, tz, method): + # GH#32572 NaT in the target should not be matched + dti = pd.date_range("2020-01-01", periods=5, tz=tz) + target = pd.DatetimeIndex([pd.NaT], dtype=dti.dtype) + result = dti.get_indexer(target, method=method) + expected = np.array([-1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "US/Central"]) + @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"]) + def test_get_indexer_nat_in_target_mixed(self, tz, method): + # GH#32572 NaT entries should get -1, real entries should match normally + dti = pd.date_range("2020-01-01", periods=5, tz=tz) + target = pd.DatetimeIndex( + [pd.NaT, pd.Timestamp("2020-01-03", tz=tz), pd.NaT], dtype=dti.dtype + ) + result = dti.get_indexer(target, method=method) + expected = np.array([-1, 2, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_pad_requires_monotonicity(self): + rng = pd.date_range("1/1/2000", "3/1/2000", freq="B") + + # neither monotonic increasing or decreasing + rng2 = rng[[1, 0, 2]] + + msg = "index must be monotonic increasing or decreasing" + with pytest.raises(ValueError, match=msg): + rng2.get_indexer(rng, method="pad") + + +class TestMaybeCastSliceBound: + def test_maybe_cast_slice_bounds_empty(self): + # GH#14354 + empty_idx = pd.date_range(freq="1h", periods=0, end="2015", unit="ns") + + right = empty_idx._maybe_cast_slice_bound("2015-01-02", "right") + exp = pd.Timestamp("2015-01-02 23:59:59.999999999") + assert right == exp + + left = empty_idx._maybe_cast_slice_bound("2015-01-02", "left") + exp = pd.Timestamp("2015-01-02 00:00:00") + assert left == exp + + def test_maybe_cast_slice_duplicate_monotonic(self): + # https://github.com/pandas-dev/pandas/issues/16515 + idx = pd.DatetimeIndex(["2017", "2017"]) + result = idx._maybe_cast_slice_bound("2017-01-01", "left") + expected = pd.Timestamp("2017-01-01") + assert result == expected + + +class TestGetSliceBounds: + @pytest.mark.parametrize("as_td", [True, False]) + def test_get_slice_bound_mismatched_unit(self, as_td): + # GH#63262 + index = pd.date_range(start="2000-01-01", freq="h", periods=8) + + td = pd.Timedelta(1) + ts = pd.Timestamp("2000-01-01 01:00:00") + start = ts - td + stop = ts + td + if as_td: + index = index - pd.Timestamp(0).as_unit("us") + start = start - pd.Timestamp(0).as_unit("us") + stop = stop - pd.Timestamp(0).as_unit("us") + + left = index.get_slice_bound(start, side="left") + assert left == 1 + right = index.get_slice_bound(stop, side="right") + assert right == 2 + + # The user-facing behavior is slicing with .loc, so let's test that + # explicitly while we're here. + ser = pd.Series(1, index=index) + result = ser.loc[start:stop] + expected = ser.iloc[1:2] + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("box", [date, datetime, pd.Timestamp]) + @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)]) + def test_get_slice_bounds_datetime_within( + self, box, side, expected, tz_aware_fixture + ): + # GH 35690 + tz = tz_aware_fixture + index = pd.bdate_range("2000-01-03", "2000-02-11").tz_localize(tz) + key = box(year=2000, month=1, day=7) + + warn = None if box is not date else Pandas4Warning + msg = "Slicing with a datetime.date object is deprecated" + with tm.assert_produces_warning(warn, match=msg): + if tz is not None: + with pytest.raises(TypeError, match="Cannot compare tz-naive"): + # GH#36148 we require tzawareness-compat as of 2.0 + index.get_slice_bound(key, side=side) + else: + result = index.get_slice_bound(key, side=side) + assert result == expected + + @pytest.mark.parametrize("box", [datetime, pd.Timestamp]) + @pytest.mark.parametrize("side", ["left", "right"]) + @pytest.mark.parametrize("year, expected", [(1999, 0), (2020, 30)]) + def test_get_slice_bounds_datetime_outside( + self, box, side, year, expected, tz_aware_fixture + ): + # GH 35690 + tz = tz_aware_fixture + index = pd.bdate_range("2000-01-03", "2000-02-11").tz_localize(tz) + key = box(year=year, month=1, day=7) + + if tz is not None: + with pytest.raises(TypeError, match="Cannot compare tz-naive"): + # GH#36148 we require tzawareness-compat as of 2.0 + index.get_slice_bound(key, side=side) + else: + result = index.get_slice_bound(key, side=side) + assert result == expected + + @pytest.mark.parametrize("box", [datetime, pd.Timestamp]) + def test_slice_datetime_locs(self, box, tz_aware_fixture): + # GH 34077 + tz = tz_aware_fixture + index = pd.DatetimeIndex(["2010-01-01", "2010-01-03"]).tz_localize(tz) + key = box(2010, 1, 1) + + if tz is not None: + with pytest.raises(TypeError, match="Cannot compare tz-naive"): + # GH#36148 we require tzawareness-compat as of 2.0 + index.slice_locs(key, box(2010, 1, 2)) + else: + result = index.slice_locs(key, box(2010, 1, 2)) + expected = (0, 1) + assert result == expected + + +class TestIndexerBetweenTime: + def test_indexer_between_time(self): + # GH#11818 + rng = pd.date_range("1/1/2000", "1/5/2000", freq="5min") + msg = r"Cannot convert arg \[datetime\.datetime\(2010, 1, 2, 1, 0\)\] to a time" + with pytest.raises(ValueError, match=msg): + rng.indexer_between_time(datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + + @pytest.mark.parametrize("unit", ["us", "ms", "s"]) + def test_indexer_between_time_non_nano(self, unit): + # For simple cases like this, the non-nano indexer_between_time + # should match the nano result + + rng = pd.date_range("1/1/2000", "1/5/2000", freq="5min") + arr_nano = rng._data._ndarray + + arr = arr_nano.astype(f"M8[{unit}]") + + dta = type(rng._data)._simple_new(arr, dtype=arr.dtype) + dti = pd.DatetimeIndex(dta) + assert dti.dtype == arr.dtype + + tic = time(1, 25) + toc = time(2, 29) + + result = dti.indexer_between_time(tic, toc) + expected = rng.indexer_between_time(tic, toc) + tm.assert_numpy_array_equal(result, expected) + + # case with non-zero micros in arguments + tic = time(1, 25, 0, 45678) + toc = time(2, 29, 0, 1234) + + result = dti.indexer_between_time(tic, toc) + expected = rng.indexer_between_time(tic, toc) + tm.assert_numpy_array_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_iter.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_iter.py new file mode 100644 index 0000000000000000000000000000000000000000..6e39fdcc6b03eefa2cf8dd786adcc646cf767286 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_iter.py @@ -0,0 +1,72 @@ +import dateutil.tz +import numpy as np +import pytest + +import pandas as pd +from pandas.core.arrays import datetimelike + + +class TestDatetimeIndexIteration: + @pytest.mark.parametrize( + "tz", [None, "UTC", "US/Central", dateutil.tz.tzoffset(None, -28800)] + ) + def test_iteration_preserves_nanoseconds(self, tz): + # GH#19603 + index = pd.DatetimeIndex( + ["2018-02-08 15:00:00.168456358", "2018-02-08 15:00:00.168456359"], tz=tz + ) + for i, ts in enumerate(index): + assert ts == index[i] # noqa: PLR1736 (unnecessary-list-index-lookup) + + def test_iter_readonly(self): + # GH#28055 ints_to_pydatetime with readonly array + arr = np.array([np.datetime64("2012-02-15T12:00:00.000000000")]) + arr.setflags(write=False) + dti = pd.to_datetime(arr) + list(dti) + + def test_iteration_preserves_tz(self): + # see GH#8890 + index = pd.date_range("2012-01-01", periods=3, freq="h", tz="US/Eastern") + + for i, ts in enumerate(index): + result = ts + expected = index[i] # noqa: PLR1736 (unnecessary-list-index-lookup) + assert result == expected + + def test_iteration_preserves_tz2(self): + index = pd.date_range( + "2012-01-01", periods=3, freq="h", tz=dateutil.tz.tzoffset(None, -28800) + ) + + for i, ts in enumerate(index): + result = ts + expected = index[i] # noqa: PLR1736 (unnecessary-list-index-lookup) + assert result._repr_base == expected._repr_base + assert result == expected + + def test_iteration_preserves_tz3(self): + # GH#9100 + index = pd.DatetimeIndex( + ["2014-12-01 03:32:39.987000-08:00", "2014-12-01 04:12:34.987000-08:00"] + ) + for i, ts in enumerate(index): + result = ts + expected = index[i] # noqa: PLR1736 (unnecessary-list-index-lookup) + assert result._repr_base == expected._repr_base + assert result == expected + + @pytest.mark.parametrize("offset", [-5, -1, 0, 1]) + def test_iteration_over_chunksize(self, offset, monkeypatch): + # GH#21012 + chunksize = 5 + index = pd.date_range( + "2000-01-01 00:00:00", periods=chunksize - offset, freq="min" + ) + num = 0 + with monkeypatch.context() as m: + m.setattr(datetimelike, "_ITER_CHUNKSIZE", chunksize) + for stamp in index: + assert index[num] == stamp + num += 1 + assert num == len(index) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_join.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..1f05f96591b9433bc7836c191c028a8478514414 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_join.py @@ -0,0 +1,183 @@ +from datetime import ( + UTC, + date, + datetime, +) + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + +from pandas.tseries.offsets import ( + BDay, + BMonthEnd, +) + + +class TestJoin: + def test_does_not_convert_mixed_integer(self): + df = pd.DataFrame( + np.ones((3, 2)), columns=pd.date_range("2020-01-01", periods=2) + ) + cols = df.columns.join(df.index, how="outer") + joined = cols.join(df.columns) + assert cols.dtype == np.dtype("O") + assert cols.dtype == joined.dtype + tm.assert_numpy_array_equal(cols.values, joined.values) + + def test_join_self(self, join_type): + index = pd.date_range("1/1/2000", periods=10) + joined = index.join(index, how=join_type) + assert index is joined + + def test_join_with_period_index(self, join_type): + df = pd.DataFrame( + np.ones((10, 2)), + index=pd.date_range("2020-01-01", periods=10), + columns=pd.period_range("2020-01-01", periods=2), + ) + s = df.iloc[:5, 0] + + if join_type == "left": + # GH#63371 a left join keeps the left dtype + expected = df.columns + else: + expected = df.columns.astype("O").join(s.index, how=join_type) + result = df.columns.join(s.index, how=join_type) + tm.assert_index_equal(expected, result) + + def test_join_object_index(self): + rng = pd.date_range("1/1/2000", periods=10) + idx = pd.Index(["a", "b", "c", "d"]) + + result = rng.join(idx, how="outer") + assert isinstance(result[0], pd.Timestamp) + + def test_join_utc_convert(self, join_type): + rng = pd.date_range("1/1/2011", periods=100, freq="h", tz="utc") + + left = rng.tz_convert("US/Eastern") + right = rng.tz_convert("Europe/Berlin") + + result = left.join(left[:-5], how=join_type) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz == left.tz + + result = left.join(right[:-5], how=join_type) + assert isinstance(result, pd.DatetimeIndex) + assert result.tz is UTC + + def test_datetimeindex_union_join_empty(self, sort, using_infer_string): + dti = pd.date_range(start="1/1/2001", end="2/1/2001", freq="D") + empty = pd.Index([]) + + result = dti.union(empty, sort=sort) + if using_infer_string: + assert isinstance(result, pd.DatetimeIndex) + tm.assert_index_equal(result, dti) + else: + expected = dti.astype("O") + tm.assert_index_equal(result, expected) + + result = dti.join(empty) + assert isinstance(result, pd.DatetimeIndex) + tm.assert_index_equal(result, dti) + + def test_join_nonunique(self): + idx1 = pd.to_datetime( + ["2012-11-06 16:00:11.477563", "2012-11-06 16:00:11.477563"] + ) + idx2 = pd.to_datetime( + ["2012-11-06 15:11:09.006507", "2012-11-06 15:11:09.006507"] + ) + rs = idx1.join(idx2, how="outer") + assert rs.is_monotonic_increasing + + @pytest.mark.parametrize("freq", ["B", "C"]) + def test_outer_join(self, freq): + # should just behave as union + start, end = datetime(2009, 1, 1), datetime(2010, 1, 1) + rng = pd.date_range(start=start, end=end, freq=freq) + + # overlapping + left = rng[:10] + right = rng[5:10] + + the_join = left.join(right, how="outer") + assert isinstance(the_join, pd.DatetimeIndex) + + # non-overlapping, gap in middle + left = rng[:5] + right = rng[10:] + + the_join = left.join(right, how="outer") + assert isinstance(the_join, pd.DatetimeIndex) + assert the_join.freq is None + + # non-overlapping, no gap + left = rng[:5] + right = rng[5:10] + + the_join = left.join(right, how="outer") + assert isinstance(the_join, pd.DatetimeIndex) + + # overlapping, but different offset + other = pd.date_range(start, end, freq=BMonthEnd()) + + the_join = rng.join(other, how="outer") + assert isinstance(the_join, pd.DatetimeIndex) + assert the_join.freq is None + + def test_naive_aware_conflicts(self): + start, end = datetime(2009, 1, 1), datetime(2010, 1, 1) + naive = pd.date_range(start, end, freq=BDay(), tz=None) + aware = pd.date_range(start, end, freq=BDay(), tz="Asia/Hong_Kong") + + msg = "tz-naive.*tz-aware" + with pytest.raises(TypeError, match=msg): + naive.join(aware) + + with pytest.raises(TypeError, match=msg): + aware.join(naive) + + @pytest.mark.parametrize("tz", [None, "US/Pacific"]) + def test_join_preserves_freq(self, tz): + # GH#32157 + dti = pd.date_range("2016-01-01", periods=10, tz=tz) + result = dti[:5].join(dti[5:], how="outer") + assert result.freq == dti.freq + tm.assert_index_equal(result, dti) + + result = dti[:5].join(dti[6:], how="outer") + assert result.freq is None + expected = dti.delete(5) + tm.assert_index_equal(result, expected) + + +def test_join_date_objects_with_datetimeindex(): + # GH#62158 + dti = pd.date_range("2016-01-01", periods=3) + date_idx = pd.Index([date(2016, 1, 1), date(2016, 1, 2), date(2016, 1, 3)]) + + msg = "Indexing a DatetimeIndex with a sequence of datetime.date" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = dti.join(date_idx, how="inner") + tm.assert_index_equal(result, dti) + + +def test_join_mixed_date_tzaware_timestamp(): + # GH#68577 the target is not convertible to datetime64, so it is joined as + # object instead of raising "Mixed timezones detected" + ts = pd.Timestamp("2016-01-01", tz="UTC") + dti = pd.DatetimeIndex([ts]) + target = pd.Index([date(2016, 1, 1), ts], dtype=object) + + result, lindexer, _ = dti.join(target, how="right", return_indexers=True) + + tm.assert_index_equal(result, target) + # -1 because a date never matches a tz-aware Timestamp + tm.assert_numpy_array_equal(lindexer, np.array([-1, 0], dtype=np.intp)) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_npfuncs.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_npfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..701a836a44c4e40804284ee279a7337d044580f8 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_npfuncs.py @@ -0,0 +1,13 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestSplit: + def test_split_non_utc(self): + # GH#14042 + indices = pd.date_range("2016-01-01 00:00:00+0200", freq="s", periods=10) + result = np.split(indices, indices_or_sections=[])[0] + expected = indices._with_freq(None) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_ops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0b000204f12b663cfbf4243fb41dc422fd5e62 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_ops.py @@ -0,0 +1,53 @@ +from datetime import datetime + +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndexOps: + def test_infer_freq(self, freq_sample): + # GH 11018 + idx = pd.date_range( + "2011-01-01 09:00:00", freq=freq_sample, periods=10, unit="ns" + ) + result = pd.DatetimeIndex(idx.asi8, freq="infer") + tm.assert_index_equal(idx, result) + assert result.freq == freq_sample + + +@pytest.mark.parametrize("freq", ["B", "C"]) +class TestBusinessDatetimeIndex: + @pytest.fixture + def rng(self, freq): + START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) + return pd.bdate_range(START, END, freq=freq) + + def test_comparison(self, rng): + d = rng[10] + + comp = rng > d + assert comp[11] + assert not comp[9] + + def test_copy(self, rng): + cp = rng.copy() + tm.assert_index_equal(cp, rng) + + def test_identical(self, rng): + t1 = rng.copy() + t2 = rng.copy() + assert t1.identical(t2) + + # name + t1 = t1.rename("foo") + assert t1.equals(t2) + assert not t1.identical(t2) + t2 = t2.rename("foo") + assert t1.identical(t2) + + # freq + t2v = pd.Index(t2.values) + assert t1.equals(t2v) + assert not t1.identical(t2v) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_partial_slicing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_partial_slicing.py new file mode 100644 index 0000000000000000000000000000000000000000..e19908812cb604c7d2d66494c75d59293af6267d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -0,0 +1,592 @@ +"""test partial slicing on Series/Frame""" + +from datetime import datetime + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestSlicing: + def test_string_index_series_name_converted(self): + # GH#1644 + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + index=pd.date_range("1/1/2000", periods=10), + ) + + result = df.loc["1/3/2000"] + assert result.name == df.index[2] + + result = df.T["1/3/2000"] + assert result.name == df.index[2] + + def test_stringified_slice_with_tz(self): + # GH#2658 + start = "2013-01-07" + idx = pd.date_range(start=start, freq="1D", periods=10, tz="US/Eastern") + df = pd.DataFrame(np.arange(10), index=idx) + df["2013-01-14 23:44:34.437768-05:00":] # no exception here + + def test_return_type_doesnt_depend_on_monotonicity(self): + # GH#24892 we get Series back regardless of whether our DTI is monotonic + dti = pd.date_range(start="2015-5-13 23:59:00", freq="min", periods=3) + ser = pd.Series(range(3), index=dti) + + # non-monotonic index + ser2 = pd.Series(range(3), index=[dti[1], dti[0], dti[2]]) + + # key with resolution strictly lower than "min" + key = "2015-5-14 00" + + # monotonic increasing index + result = ser.loc[key] + expected = ser.iloc[1:] + tm.assert_series_equal(result, expected) + + # monotonic decreasing index + result = ser.iloc[::-1].loc[key] + expected = ser.iloc[::-1][:-1] + tm.assert_series_equal(result, expected) + + # non-monotonic index + result2 = ser2.loc[key] + expected2 = ser2.iloc[::2] + tm.assert_series_equal(result2, expected2) + + @pytest.mark.parametrize( + "start, freq, key", + [ + ("2005-01-01", "B", "2005-05"), + ("2005-01-01", "h", "2005-01-10"), + ("2005-01-01 20:00:00", "min", "2005-01-01 22"), + ("2005-01-01 23:59:00", "s", "2005-01-01 23:59"), + ], + ) + def test_partial_date_slice_decreasing_returns_slice(self, start, freq, key): + # monotonic decreasing should use searchsorted fast path + # and return a slice, not an ndarray + dti = pd.date_range(start=start, periods=500, freq=freq) + ser = pd.Series(np.arange(len(dti)), index=dti) + + expected = ser.loc[key].iloc[::-1] + + ser_desc = ser.iloc[::-1] + result = ser_desc.loc[key] + tm.assert_series_equal(result, expected) + + # check that the fast path actually returns a slice + parsed, reso = ser_desc.index._parse_with_reso(key) + indexer = ser_desc.index._partial_date_slice(reso, parsed) + assert isinstance(indexer, slice) + + def test_partial_date_slice_decreasing_out_of_range(self): + dti = pd.date_range(start="2005-01-01", periods=500, freq="D") + ser_desc = pd.Series(np.arange(len(dti)), index=dti[::-1]) + + with pytest.raises(KeyError, match=r"^'2004-01-01'$"): + ser_desc["2004-01-01"] + + with pytest.raises(KeyError, match=r"^'2007-01-01'$"): + ser_desc["2007-01-01"] + + def test_return_type_doesnt_depend_on_monotonicity_higher_reso(self): + # GH#24892 we get Series back regardless of whether our DTI is monotonic + dti = pd.date_range(start="2015-5-13 23:59:00", freq="min", periods=3) + ser = pd.Series(range(3), index=dti) + + # non-monotonic index + ser2 = pd.Series(range(3), index=[dti[1], dti[0], dti[2]]) + + # key with resolution strictly *higher) than "min" + key = "2015-5-14 00:00:00" + + # monotonic increasing index + result = ser.loc[key] + assert result == 1 + + # monotonic decreasing index + result = ser.iloc[::-1].loc[key] + assert result == 1 + + # non-monotonic index + result2 = ser2.loc[key] + assert result2 == 0 + + def test_monotone_DTI_indexing_bug(self): + # GH 19362 + # Testing accessing the first element in a monotonic descending + # partial string indexing. + + df = pd.DataFrame(list(range(5))) + date_list = [ + "2018-01-02", + "2017-02-10", + "2016-03-10", + "2015-03-15", + "2014-03-16", + ] + date_index = pd.DatetimeIndex(date_list) + df["date"] = date_index + expected = pd.DataFrame({0: list(range(5)), "date": date_index}) + tm.assert_frame_equal(df, expected) + + # We get a slice because df.index's resolution is hourly and we + # are slicing with a daily-resolution string. If both were daily, + # we would get a single item back + dti = pd.date_range("20170101 01:00:00", periods=3) + df = pd.DataFrame({"A": [1, 2, 3]}, index=dti[::-1]) + + expected = pd.DataFrame({"A": 1}, index=dti[-1:][::-1]) + result = df.loc["2017-01-03"] + tm.assert_frame_equal(result, expected) + + result2 = df.iloc[::-1].loc["2017-01-03"] + expected2 = expected.iloc[::-1] + tm.assert_frame_equal(result2, expected2) + + def test_slice_year(self): + dti = pd.date_range(freq="B", start=datetime(2005, 1, 1), periods=500) + + s = pd.Series(np.arange(len(dti)), index=dti) + result = s["2005"] + expected = s[s.index.year == 2005] + tm.assert_series_equal(result, expected) + + df = pd.DataFrame(np.random.default_rng(2).random((len(dti), 5)), index=dti) + result = df.loc["2005"] + expected = df[df.index.year == 2005] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "partial_dtime", + [ + "2019", + "2019Q4", + "Dec 2019", + "2019-12-31", + "2019-12-31 23", + "2019-12-31 23:59", + ], + ) + def test_slice_end_of_period_resolution(self, partial_dtime): + # GH#31064 + dti = pd.date_range("2019-12-31 23:59:55.999999999", periods=10, freq="s") + + ser = pd.Series(range(10), index=dti) + # GH#50907 + warn = Pandas4Warning if "Q" in partial_dtime else None + msg = "quarterly string is deprecated" if warn else "" + with tm.assert_produces_warning(warn, match=msg): + result = ser[partial_dtime] + expected = ser.iloc[:5] + tm.assert_series_equal(result, expected) + + def test_slice_quarter(self): + # GH#50907 + dti = pd.date_range(freq="D", start=datetime(2000, 6, 1), periods=500) + + s = pd.Series(np.arange(len(dti)), index=dti) + with tm.assert_produces_warning( + Pandas4Warning, match="quarterly string is deprecated" + ): + assert len(s["2001Q1"]) == 90 + + df = pd.DataFrame(np.random.default_rng(2).random((len(dti), 5)), index=dti) + with tm.assert_produces_warning( + Pandas4Warning, match="quarterly string is deprecated" + ): + assert len(df.loc["1Q01"]) == 90 + + def test_slice_month(self): + dti = pd.date_range(freq="D", start=datetime(2005, 1, 1), periods=500) + s = pd.Series(np.arange(len(dti)), index=dti) + assert len(s["2005-11"]) == 30 + + df = pd.DataFrame(np.random.default_rng(2).random((len(dti), 5)), index=dti) + assert len(df.loc["2005-11"]) == 30 + + tm.assert_series_equal(s["2005-11"], s["11-2005"]) + + def test_partial_slice(self): + rng = pd.date_range(freq="D", start=datetime(2005, 1, 1), periods=500) + s = pd.Series(np.arange(len(rng)), index=rng) + + result = s["2005-05":"2006-02"] + expected = s["20050501":"20060228"] + tm.assert_series_equal(result, expected) + + result = s["2005-05":] + expected = s["20050501":] + tm.assert_series_equal(result, expected) + + result = s[:"2006-02"] + expected = s[:"20060228"] + tm.assert_series_equal(result, expected) + + result = s["2005-1-1"] + assert result == s.iloc[0] + + with pytest.raises(KeyError, match=r"^'2004-12-31'$"): + s["2004-12-31"] + + def test_partial_slice_daily(self): + rng = pd.date_range(freq="h", start=datetime(2005, 1, 31), periods=500) + s = pd.Series(np.arange(len(rng)), index=rng) + + result = s["2005-1-31"] + tm.assert_series_equal(result, s.iloc[:24]) + + with pytest.raises(KeyError, match=r"^'2004-12-31 00'$"): + s["2004-12-31 00"] + + def test_partial_slice_hourly(self): + rng = pd.date_range( + freq="min", start=datetime(2005, 1, 1, 20, 0, 0), periods=500 + ) + s = pd.Series(np.arange(len(rng)), index=rng) + + result = s["2005-1-1"] + tm.assert_series_equal(result, s.iloc[: 60 * 4]) + + result = s["2005-1-1 20"] + tm.assert_series_equal(result, s.iloc[:60]) + + assert s["2005-1-1 20:00"] == s.iloc[0] + with pytest.raises(KeyError, match=r"^'2004-12-31 00:15'$"): + s["2004-12-31 00:15"] + + def test_partial_slice_minutely(self): + rng = pd.date_range( + freq="s", start=datetime(2005, 1, 1, 23, 59, 0), periods=500 + ) + s = pd.Series(np.arange(len(rng)), index=rng) + + result = s["2005-1-1 23:59"] + tm.assert_series_equal(result, s.iloc[:60]) + + result = s["2005-1-1"] + tm.assert_series_equal(result, s.iloc[:60]) + + assert s[pd.Timestamp("2005-1-1 23:59:00")] == s.iloc[0] + with pytest.raises(KeyError, match=r"^'2004-12-31 00:00:00'$"): + s["2004-12-31 00:00:00"] + + def test_partial_slice_second_precision(self): + rng = pd.date_range( + start=datetime(2005, 1, 1, 0, 0, 59, microsecond=999990), + periods=20, + freq="us", + ) + s = pd.Series(np.arange(20), rng) + + tm.assert_series_equal(s["2005-1-1 00:00"], s.iloc[:10]) + tm.assert_series_equal(s["2005-1-1 00:00:59"], s.iloc[:10]) + + tm.assert_series_equal(s["2005-1-1 00:01"], s.iloc[10:]) + tm.assert_series_equal(s["2005-1-1 00:01:00"], s.iloc[10:]) + + assert s[pd.Timestamp("2005-1-1 00:00:59.999990")] == s.iloc[0] + with pytest.raises(KeyError, match="2005-1-1 00:00:00"): + s["2005-1-1 00:00:00"] + + def test_partial_slicing_dataframe(self, using_python_scalars): + # GH14856 + # Test various combinations of string slicing resolution vs. + # index resolution + # - If string resolution is less precise than index resolution, + # string is considered a slice + # - If string resolution is equal to or more precise than index + # resolution, string is considered an exact match + formats = [ + "%Y", + "%Y-%m", + "%Y-%m-%d", + "%Y-%m-%d %H", + "%Y-%m-%d %H:%M", + "%Y-%m-%d %H:%M:%S", + ] + resolutions = ["year", "month", "day", "hour", "minute", "second"] + expected_type = int if using_python_scalars else np.int64 + for rnum, resolution in enumerate(resolutions[2:], 2): + # we check only 'day', 'hour', 'minute' and 'second' + unit = pd.Timedelta("1 " + resolution) + middate = datetime(2012, 1, 1, 0, 0, 0) + index = pd.DatetimeIndex([middate - unit, middate, middate + unit]) + values = [1, 2, 3] + df = pd.DataFrame({"a": values}, index, dtype=np.int64) + assert df.index.resolution == resolution + + # Timestamp with the same resolution as index + # Should be exact match for Series (return scalar) + # and raise KeyError for Frame + for timestamp, expected in zip(index, values, strict=True): + ts_string = timestamp.strftime(formats[rnum]) + # make ts_string as precise as index + result = df["a"][ts_string] + assert type(result) is expected_type + assert result == expected + msg = rf"^'{ts_string}'$" + with pytest.raises(KeyError, match=msg): + df[ts_string] + + # Timestamp with resolution less precise than index + for fmt in formats[:rnum]: + for element, theslice in [[0, slice(None, 1)], [1, slice(1, None)]]: + ts_string = index[element].strftime(fmt) + + # Series should return slice + result = df["a"][ts_string] + expected = df["a"][theslice] + tm.assert_series_equal(result, expected) + + # pre-2.0 df[ts_string] was overloaded to interpret this + # as slicing along index + with pytest.raises(KeyError, match=ts_string): + df[ts_string] + + # Timestamp with resolution more precise than index + # Compatible with existing key + # Should return scalar for Series + # and raise KeyError for Frame + for fmt in formats[rnum + 1 :]: + ts_string = index[1].strftime(fmt) + result = df["a"][ts_string] + assert type(result) is expected_type + assert result == 2 + msg = rf"^'{ts_string}'$" + with pytest.raises(KeyError, match=msg): + df[ts_string] + + # Not compatible with existing key + # Should raise KeyError + for fmt, res in list(zip(formats, resolutions, strict=True))[rnum + 1 :]: + ts = index[1] + pd.Timedelta("1 " + res) + ts_string = ts.strftime(fmt) + msg = rf"^'{ts_string}'$" + with pytest.raises(KeyError, match=msg): + df["a"][ts_string] + with pytest.raises(KeyError, match=msg): + df[ts_string] + + def test_partial_slicing_with_multiindex(self): + # GH 4758 + # partial string indexing with a multi-index buggy + df = pd.DataFrame( + { + "ACCOUNT": ["ACCT1", "ACCT1", "ACCT1", "ACCT2"], + "TICKER": ["ABC", "MNP", "XYZ", "XYZ"], + "val": [1, 2, 3, 4], + }, + index=pd.date_range("2013-06-19 09:30:00", periods=4, freq="5min"), + ) + df_multi = df.set_index(["ACCOUNT", "TICKER"], append=True) + + expected = pd.DataFrame( + [[1]], index=pd.Index(["ABC"], name="TICKER"), columns=["val"] + ) + result = df_multi.loc[("2013-06-19 09:30:00", "ACCT1")] + tm.assert_frame_equal(result, expected) + + expected = df_multi.loc[ + (pd.Timestamp("2013-06-19 09:30:00", tz=None), "ACCT1", "ABC") + ] + result = df_multi.loc[("2013-06-19 09:30:00", "ACCT1", "ABC")] + tm.assert_series_equal(result, expected) + + # partial string indexing on first level, scalar indexing on the other two + result = df_multi.loc[("2013-06-19", "ACCT1", "ABC")] + expected = df_multi.iloc[:1].droplevel([1, 2]) + tm.assert_frame_equal(result, expected) + + def test_partial_slicing_with_multiindex_series(self): + # GH 4294 + # partial slice on a series mi + ser = pd.Series( + range(250), + index=pd.MultiIndex.from_product( + [pd.date_range("2000-1-1", periods=50), range(5)] + ), + ) + + s2 = ser[:-1].copy() + expected = s2["2000-1-4"] + result = s2[pd.Timestamp("2000-1-4")] + tm.assert_series_equal(result, expected) + + result = ser[pd.Timestamp("2000-1-4")] + expected = ser["2000-1-4"] + tm.assert_series_equal(result, expected) + + df2 = pd.DataFrame(ser) + expected = df2.xs("2000-1-4") + result = df2.loc[pd.Timestamp("2000-1-4")] + tm.assert_frame_equal(result, expected) + + def test_xs_matches_loc_after_sort_multiindex(self): + # GH 19451 + # after sort_index, .xs should + # return the same result as .loc + df = pd.DataFrame( + [ + ["2017-01-01", "000001", "a", 4, 5], + ["2017-01-02", "000001", "b", 4, 5], + ["2017-01-01", "000002", "b", 4, 5], + ["2017-01-02", "000002", "b", 4, 5], + ["2017-02-02", "000001", "b", 4, 5], + ["2017-02-03", "000002", "b", 4, 5], + ], + columns=["date", "code", "c", "d", "e"], + ) + df = ( + df.assign(date=pd.to_datetime(df.date)) + .set_index(["date", "code"]) + .sort_index() + ) + expected = df.loc["2017-01", slice(None)] + result = df.xs("2017-01", level=0) + tm.assert_frame_equal(result, expected) + + def test_partial_slice_requires_monotonicity(self): + # Disallowed since 2.0 (GH 37819) + ser = pd.Series(np.arange(10), pd.date_range("2014-01-01", periods=10)) + + nonmonotonic = ser.iloc[[3, 5, 4]] + timestamp = pd.Timestamp("2014-01-10") + with pytest.raises( + KeyError, match="Value based partial slicing on non-monotonic" + ): + nonmonotonic["2014-01-10":] + + # GH#13090 - improved error message for non-monotonic DatetimeIndex + msg = "non-monotonic index with a missing label" + with pytest.raises(KeyError, match=msg): + nonmonotonic[timestamp:] + + with pytest.raises( + KeyError, match="Value based partial slicing on non-monotonic" + ): + nonmonotonic.loc["2014-01-10":] + + with pytest.raises(KeyError, match=msg): + nonmonotonic.loc[timestamp:] + + def test_loc_datetime_length_one(self): + # GH16071 + df = pd.DataFrame( + columns=["1"], + index=pd.date_range("2016-10-01T00:00:00", "2016-10-01T23:59:59"), + ) + result = df.loc[datetime(2016, 10, 1) :] + tm.assert_frame_equal(result, df) + + result = df.loc["2016-10-01T00:00:00":] + tm.assert_frame_equal(result, df) + + @pytest.mark.parametrize( + "start", + [ + "2018-12-02 21:50:00+00:00", + pd.Timestamp("2018-12-02 21:50:00+00:00"), + pd.Timestamp("2018-12-02 21:50:00+00:00").to_pydatetime(), + ], + ) + @pytest.mark.parametrize( + "end", + [ + "2018-12-02 21:52:00+00:00", + pd.Timestamp("2018-12-02 21:52:00+00:00"), + pd.Timestamp("2018-12-02 21:52:00+00:00").to_pydatetime(), + ], + ) + def test_getitem_with_datestring_with_UTC_offset(self, start, end): + # GH 24076 + idx = pd.date_range( + start="2018-12-02 14:50:00-07:00", + end="2018-12-02 14:50:00-07:00", + freq="1min", + ) + df = pd.DataFrame(1, index=idx, columns=["A"]) + result = df[start:end] + expected = df.iloc[0:3, :] + tm.assert_frame_equal(result, expected) + + # GH 16785 + start = str(start) + end = str(end) + with pytest.raises(ValueError, match="Both dates must"): + df[start : end[:-4] + "1:00"] + + df = df.tz_localize(None) + with pytest.raises(ValueError, match="The index must be timezone"): + df[start:end] + + def test_slice_reduce_to_series(self): + # GH 27516 + df = pd.DataFrame( + {"A": range(24)}, index=pd.date_range("2000", periods=24, freq="ME") + ) + expected = pd.Series( + range(12), index=pd.date_range("2000", periods=12, freq="ME"), name="A" + ) + result = df.loc["2000", "A"] + tm.assert_series_equal(result, expected) + + +def test_string_slice_vs_datetime_slice_consistency(): + # GH#13929 - slicing with string endpoints at sub-second frequency + # should produce the same result as slicing with datetime endpoints + index = pd.date_range("2013-01-01 00:00:00", periods=80, freq="50ms") + data = pd.DataFrame({"val": range(len(index))}, index=index) + + str_slice = data.loc["2013-01-01 00:00:01.000":"2013-01-01 00:00:02.000"] + dt_slice = data.loc["2013-01-01 00:00:01.000" : datetime(2013, 1, 1, 0, 0, 2)] + + tm.assert_frame_equal(str_slice, dt_slice) + + +def test_datetimeindex_quarterly_slice_still_warns(): + # GH#50907 slice_locs suppresses the warning for its own internal parse of + # the bounds; the user-facing warning from get_slice_bound must survive + dti = pd.date_range("2001-01-01", periods=500, freq="D") + ser = pd.Series(np.arange(len(dti)), index=dti) + + # one warning per bound; without the suppression the internal parse of each + # bound would double that + with tm.assert_produces_warning( + Pandas4Warning, match="quarterly string is deprecated" + ) as record: + result = ser.loc["2001Q1":"2001Q3"] + assert len(result) == 273 + assert len(record) == 2 + + with tm.assert_produces_warning( + Pandas4Warning, match="quarterly string is deprecated" + ) as record: + assert dti.slice_locs("2001Q1", "2001Q3") == (0, 273) + assert len(record) == 2 + + +@pytest.mark.parametrize( + "offset, reverse", + [(pd.DateOffset(days=1, hours=-2), False), (pd.DateOffset(days=1, hours=2), True)], +) +def test_partial_slice_quarter_generic_dateoffset_freq(offset, reverse): + # GH#48210 a generic DateOffset has no rule_code, and its repr was being + # passed down to the parser as if it were one; any "-" in that repr then + # got read as a quarter anchor + dti = pd.date_range("2022-01-01", periods=60, freq=offset) + if reverse: + dti = dti[::-1] + assert "-" in dti.freqstr + ser = pd.Series(np.arange(len(dti)), index=dti) + + with tm.assert_produces_warning( + Pandas4Warning, match="quarterly string is deprecated" + ): + result = ser["2022Q1"] + tm.assert_series_equal(result, ser) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_pickle.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e7150f318a0f5cf0773798713a692d7ee1ac52 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_pickle.py @@ -0,0 +1,41 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestPickle: + def test_pickle(self, temp_file): + # GH#4606 + idx = pd.to_datetime(["2013-01-01", pd.NaT, "2014-01-06"]) + idx_p = tm.round_trip_pickle(idx, temp_file) + assert idx_p[0] == idx[0] + assert idx_p[1] is pd.NaT + assert idx_p[2] == idx[2] + + def test_pickle_dont_infer_freq(self, temp_file): + # GH#11002 + # don't infer freq + idx = pd.date_range("1750-1-1", "2050-1-1", freq="7D") + idx_p = tm.round_trip_pickle(idx, temp_file) + tm.assert_index_equal(idx, idx_p) + + def test_pickle_after_set_freq(self, temp_file): + dti = pd.date_range("20130101", periods=3, tz="US/Eastern", name="foo") + dti = dti._with_freq(None) + + res = tm.round_trip_pickle(dti, temp_file) + tm.assert_index_equal(res, dti) + + def test_roundtrip_pickle_with_tz(self, temp_file): + # GH#8367 + # round-trip of timezone + index = pd.date_range("20130101", periods=3, tz="US/Eastern", name="foo") + unpickled = tm.round_trip_pickle(index, temp_file) + tm.assert_index_equal(index, unpickled) + + @pytest.mark.parametrize("freq", ["B", "C"]) + def test_pickle_unpickle(self, freq, temp_file): + rng = pd.date_range("2009-01-01", "2010-01-01", freq=freq) + unpickled = tm.round_trip_pickle(rng, temp_file) + assert unpickled.freq == freq diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_reindex.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_reindex.py new file mode 100644 index 0000000000000000000000000000000000000000..3a4de4c920e700a0d43ff13ff03d2e2637471c03 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_reindex.py @@ -0,0 +1,57 @@ +from datetime import timedelta + +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndexReindex: + def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self): + # GH#7774 + index = pd.date_range("2013-01-01", periods=3, tz="US/Eastern", unit="ns") + assert str(index.reindex([])[0].tz) == "US/Eastern" + assert str(index.reindex(np.array([]))[0].tz) == "US/Eastern" + + def test_reindex_with_same_tz_nearest(self): + # GH#32740 + rng_a = pd.date_range( + "2010-01-01", "2010-01-02", periods=24, tz="utc", unit="ns" + ) + rng_b = pd.date_range( + "2010-01-01", "2010-01-02", periods=23, tz="utc", unit="ns" + ) + result1, result2 = rng_a.reindex( + rng_b, method="nearest", tolerance=timedelta(seconds=20) + ) + expected_list1 = [ + "2010-01-01 00:00:00", + "2010-01-01 01:05:27.272727272", + "2010-01-01 02:10:54.545454545", + "2010-01-01 03:16:21.818181818", + "2010-01-01 04:21:49.090909090", + "2010-01-01 05:27:16.363636363", + "2010-01-01 06:32:43.636363636", + "2010-01-01 07:38:10.909090909", + "2010-01-01 08:43:38.181818181", + "2010-01-01 09:49:05.454545454", + "2010-01-01 10:54:32.727272727", + "2010-01-01 12:00:00", + "2010-01-01 13:05:27.272727272", + "2010-01-01 14:10:54.545454545", + "2010-01-01 15:16:21.818181818", + "2010-01-01 16:21:49.090909090", + "2010-01-01 17:27:16.363636363", + "2010-01-01 18:32:43.636363636", + "2010-01-01 19:38:10.909090909", + "2010-01-01 20:43:38.181818181", + "2010-01-01 21:49:05.454545454", + "2010-01-01 22:54:32.727272727", + "2010-01-02 00:00:00", + ] + expected1 = pd.DatetimeIndex( + expected_list1, dtype="datetime64[ns, UTC]", freq=None + ) + expected2 = np.array([0] + [-1] * 21 + [23], dtype=np.dtype("intp")) + tm.assert_index_equal(result1, expected1) + tm.assert_numpy_array_equal(result2, expected2) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_scalar_compat.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_scalar_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4aed2782f8262ee2549a828b3dcdd677db1901 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_scalar_compat.py @@ -0,0 +1,540 @@ +""" +Tests for DatetimeIndex methods behaving like their Timestamp counterparts +""" + +import calendar +from datetime import ( + date, + datetime, + time, +) +import locale +import unicodedata + +import numpy as np +import pytest + +from pandas._libs.tslibs import timezones +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import DatetimeArray + + +class TestDatetimeIndexOps: + def test_dti_no_millisecond_field(self): + msg = "type object 'DatetimeIndex' has no attribute 'millisecond'" + with pytest.raises(AttributeError, match=msg): + pd.DatetimeIndex.millisecond + + msg = "'DatetimeIndex' object has no attribute 'millisecond'" + with pytest.raises(AttributeError, match=msg): + pd.DatetimeIndex([]).millisecond + + def test_dti_time(self): + rng = pd.date_range("1/1/2000", freq="12min", periods=10) + result = pd.Index(rng).time + expected = [t.time() for t in rng] + assert (result == expected).all() + + def test_dti_date(self): + rng = pd.date_range("1/1/2000", freq="12h", periods=10) + result = pd.Index(rng).date + expected = [t.date() for t in rng] + assert (result == expected).all() + + @pytest.mark.parametrize( + "dtype", + [None, "datetime64[ns, CET]", "datetime64[ns, EST]", "datetime64[ns, UTC]"], + ) + def test_dti_date2(self, dtype): + # Regression test for GH#21230 + expected = np.array([date(2018, 6, 4), pd.NaT]) + + index = pd.DatetimeIndex(["2018-06-04 10:00:00", pd.NaT], dtype=dtype) + result = index.date + + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "dtype", + [None, "datetime64[ns, CET]", "datetime64[ns, EST]", "datetime64[ns, UTC]"], + ) + def test_dti_time2(self, dtype): + # Regression test for GH#21267 + expected = np.array([time(10, 20, 30), pd.NaT]) + + index = pd.DatetimeIndex(["2018-06-04 10:20:30", pd.NaT], dtype=dtype) + result = index.time + + tm.assert_numpy_array_equal(result, expected) + + def test_dti_timetz(self, tz_naive_fixture): + # GH#21358 + tz = timezones.maybe_get_tz(tz_naive_fixture) + + expected = np.array([time(10, 20, 30, tzinfo=tz), pd.NaT]) + + index = pd.DatetimeIndex(["2018-06-04 10:20:30", pd.NaT], tz=tz) + result = index.timetz + + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "field", + [ + "day_of_week", + "day_of_year", + "quarter", + "days_in_month", + "is_month_start", + "is_month_end", + "is_quarter_start", + "is_quarter_end", + "is_year_start", + "is_year_end", + ], + ) + def test_dti_timestamp_fields(self, field): + # extra fields from DatetimeIndex like quarter and week + idx = pd.date_range("2020-01-01", periods=10) + expected = getattr(idx, field)[-1] + + result = getattr(pd.Timestamp(idx[-1]), field) + assert result == expected + + def test_dti_nanosecond(self): + dti = pd.DatetimeIndex(np.arange(10)) + expected = pd.Index(np.arange(10, dtype=np.int32)) + + tm.assert_index_equal(dti.nanosecond, expected) + + @pytest.mark.parametrize("prefix", ["", "dateutil/"]) + def test_dti_hour_tzaware(self, prefix): + strdates = ["1/1/2012", "3/1/2012", "4/1/2012"] + rng = pd.DatetimeIndex(strdates, tz=prefix + "US/Eastern") + assert (rng.hour == 0).all() + + # a more unusual time zone, GH#1946 + dr = pd.date_range( + "2011-10-02 00:00", freq="h", periods=10, tz=prefix + "America/Atikokan" + ) + + expected = pd.Index(np.arange(10, dtype=np.int32)) + tm.assert_index_equal(dr.hour, expected) + + # GH#12806 + @pytest.mark.parametrize( + "time_locale", + [None, *tm.get_locales()], + ) + def test_day_name_month_name(self, time_locale): + # Test Monday -> Sunday and January -> December, in that sequence + if time_locale is None: + # If the time_locale is None, day-name and month_name should + # return the english attributes + expected_days = [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", + ] + expected_months = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + ] + else: + with tm.set_locale(time_locale, locale.LC_TIME): + expected_days = calendar.day_name[:] + expected_months = calendar.month_name[1:] + + # GH#11128 + dti = pd.date_range(freq="D", start=datetime(1998, 1, 1), periods=365) + english_days = [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", + ] + for day, name, eng_name in zip( + range(4, 11), expected_days, english_days, strict=True + ): + name = name.capitalize() + assert dti.day_name(locale=time_locale)[day] == name + assert dti.day_name(locale=None)[day] == eng_name + ts = pd.Timestamp(datetime(2016, 4, day)) + assert ts.day_name(locale=time_locale) == name + dti = dti.append(pd.DatetimeIndex([pd.NaT])) + assert np.isnan(dti.day_name(locale=time_locale)[-1]) + ts = pd.Timestamp(pd.NaT) + assert np.isnan(ts.day_name(locale=time_locale)) + + # GH#12805 + dti = pd.date_range(freq="ME", start="2012", end="2013") + result = dti.month_name(locale=time_locale) + expected = pd.Index([month.capitalize() for month in expected_months]) + + # work around different normalization schemes GH#22342 + result = result.str.normalize("NFD") + expected = expected.str.normalize("NFD") + + tm.assert_index_equal(result, expected) + + for item, expected in zip(dti, expected_months, strict=True): + result = item.month_name(locale=time_locale) + expected = expected.capitalize() + + result = unicodedata.normalize("NFD", result) + expected = unicodedata.normalize("NFD", result) + + assert result == expected + dti = dti.append(pd.DatetimeIndex([pd.NaT])) + assert np.isnan(dti.month_name(locale=time_locale)[-1]) + + def test_dti_week(self): + # GH#6538: Check that DatetimeIndex and its TimeStamp elements + # return the same weekofyear accessor close to new year w/ tz + dates = ["2013/12/29", "2013/12/30", "2013/12/31"] + dates = pd.DatetimeIndex(dates, tz="Europe/Brussels") + expected = [52, 1, 1] + assert dates.isocalendar().week.tolist() == expected + assert [d.weekofyear for d in dates] == expected + + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + def test_dti_fields(self, tz): + # GH#13303 + dti = pd.date_range( + freq="D", start=datetime(1998, 1, 1), periods=365, tz=tz, unit="ns" + ) + assert dti.year[0] == 1998 + assert dti.month[0] == 1 + assert dti.day[0] == 1 + assert dti.hour[0] == 0 + assert dti.minute[0] == 0 + assert dti.second[0] == 0 + assert dti.microsecond[0] == 0 + assert dti.day_of_week[0] == 3 + + assert dti.day_of_year[0] == 1 + assert dti.day_of_year[120] == 121 + + assert dti.isocalendar().week.iloc[0] == 1 + assert dti.isocalendar().week.iloc[120] == 18 + + assert dti.quarter[0] == 1 + assert dti.quarter[120] == 2 + + assert dti.days_in_month[0] == 31 + assert dti.days_in_month[90] == 30 + + assert dti.is_month_start[0] + assert not dti.is_month_start[1] + assert dti.is_month_start[31] + assert dti.is_quarter_start[0] + assert dti.is_quarter_start[90] + assert dti.is_year_start[0] + assert not dti.is_year_start[364] + assert not dti.is_month_end[0] + assert dti.is_month_end[30] + assert not dti.is_month_end[31] + assert dti.is_month_end[364] + assert not dti.is_quarter_end[0] + assert not dti.is_quarter_end[30] + assert dti.is_quarter_end[89] + assert dti.is_quarter_end[364] + assert not dti.is_year_end[0] + assert dti.is_year_end[364] + + assert len(dti.year) == 365 + assert len(dti.month) == 365 + assert len(dti.day) == 365 + assert len(dti.hour) == 365 + assert len(dti.minute) == 365 + assert len(dti.second) == 365 + assert len(dti.microsecond) == 365 + assert len(dti.day_of_week) == 365 + assert len(dti.day_of_year) == 365 + assert len(dti.isocalendar()) == 365 + assert len(dti.quarter) == 365 + assert len(dti.is_month_start) == 365 + assert len(dti.is_month_end) == 365 + assert len(dti.is_quarter_start) == 365 + assert len(dti.is_quarter_end) == 365 + assert len(dti.is_year_start) == 365 + assert len(dti.is_year_end) == 365 + + @pytest.mark.parametrize( + "old_attr, new_attr", + [ + ("dayofweek", "day_of_week"), + ("dayofyear", "day_of_year"), + ("daysinmonth", "days_in_month"), + ], + ) + def test_deprecated_day_attrs(self, old_attr, new_attr): + # GH#46768 + dti = pd.date_range(start="1/1/2005", end="12/1/2005", freq="ME") + msg = f"DatetimeIndex.{old_attr} is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + old_val = getattr(dti, old_attr) + tm.assert_index_equal(old_val, getattr(dti, new_attr)) + + def test_field_ops(self): + dti = pd.date_range(freq="D", start="1/1/1998", periods=365) + dti.name = "name" + + # non boolean accessors -> return Index + for accessor in DatetimeArray._field_ops: + if accessor == "weekday": + # GH#12816 weekday is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="weekday"): + res = getattr(dti, accessor) + else: + res = getattr(dti, accessor) + assert len(res) == 365 + assert isinstance(res, pd.Index) + assert res.name == "name" + + # boolean accessors -> return array + for accessor in DatetimeArray._bool_ops: + res = getattr(dti, accessor) + assert len(res) == 365 + assert isinstance(res, np.ndarray) + + # test boolean indexing + res = dti[dti.is_quarter_start] + exp = dti[[0, 90, 181, 273]] + tm.assert_index_equal(res, exp) + res = dti[dti.is_leap_year] + exp = pd.DatetimeIndex([], freq="D", tz=dti.tz, name="name").as_unit(dti.unit) + tm.assert_index_equal(res, exp) + + def test_dti_is_year_quarter_start(self): + dti = pd.date_range(freq="BQE-FEB", start=datetime(1998, 1, 1), periods=4) + + assert sum(dti.is_quarter_start) == 0 + assert sum(dti.is_quarter_end) == 4 + assert sum(dti.is_year_start) == 0 + assert sum(dti.is_year_end) == 1 + + def test_dti_is_month_start(self): + dti = pd.DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"]) + + assert dti.is_month_start[0] == 1 + + def test_dti_is_month_start_custom(self): + # Ensure is_start/end accessors throw ValueError for CustomBusinessDay, + bday_egypt = pd.offsets.CustomBusinessDay(weekmask="Sun Mon Tue Wed Thu") + dti = pd.date_range(datetime(2013, 4, 30), periods=5, freq=bday_egypt) + msg = "Custom business days is not supported by is_month_start" + with pytest.raises(ValueError, match=msg): + dti.is_month_start + + @pytest.mark.parametrize( + "timestamp, freq, periods, expected_values", + [ + ("2017-12-01", "MS", 3, np.array([False, True, False])), + ("2017-12-01", "QS", 3, np.array([True, False, False])), + ("2017-12-01", "YS", 3, np.array([True, True, True])), + ], + ) + def test_dti_dr_is_year_start(self, timestamp, freq, periods, expected_values): + # GH57377 + result = pd.date_range(timestamp, freq=freq, periods=periods).is_year_start + tm.assert_numpy_array_equal(result, expected_values) + + @pytest.mark.parametrize( + "timestamp, freq, periods, expected_values", + [ + ("2017-12-01", "ME", 3, np.array([True, False, False])), + ("2017-12-01", "QE", 3, np.array([True, False, False])), + ("2017-12-01", "YE", 3, np.array([True, True, True])), + ], + ) + def test_dti_dr_is_year_end(self, timestamp, freq, periods, expected_values): + # GH57377 + result = pd.date_range(timestamp, freq=freq, periods=periods).is_year_end + tm.assert_numpy_array_equal(result, expected_values) + + @pytest.mark.parametrize( + "timestamp, freq, periods, expected_values", + [ + ("2017-12-01", "MS", 3, np.array([False, True, False])), + ("2017-12-01", "QS", 3, np.array([True, True, True])), + ("2017-12-01", "YS", 3, np.array([True, True, True])), + ], + ) + def test_dti_dr_is_quarter_start(self, timestamp, freq, periods, expected_values): + # GH57377 + result = pd.date_range(timestamp, freq=freq, periods=periods).is_quarter_start + tm.assert_numpy_array_equal(result, expected_values) + + @pytest.mark.parametrize( + "timestamp, freq, periods, expected_values", + [ + ("2017-12-01", "ME", 3, np.array([True, False, False])), + ("2017-12-01", "QE", 3, np.array([True, True, True])), + ("2017-12-01", "YE", 3, np.array([True, True, True])), + ], + ) + def test_dti_dr_is_quarter_end(self, timestamp, freq, periods, expected_values): + # GH57377 + result = pd.date_range(timestamp, freq=freq, periods=periods).is_quarter_end + tm.assert_numpy_array_equal(result, expected_values) + + @pytest.mark.parametrize( + "timestamp, freq, periods, expected_values", + [ + ("2017-12-01", "MS", 3, np.array([True, True, True])), + ("2017-12-01", "QS", 3, np.array([True, True, True])), + ("2017-12-01", "YS", 3, np.array([True, True, True])), + ], + ) + def test_dti_dr_is_month_start(self, timestamp, freq, periods, expected_values): + # GH57377 + result = pd.date_range(timestamp, freq=freq, periods=periods).is_month_start + tm.assert_numpy_array_equal(result, expected_values) + + @pytest.mark.parametrize( + "timestamp, freq, periods, expected_values", + [ + ("2017-12-01", "ME", 3, np.array([True, True, True])), + ("2017-12-01", "QE", 3, np.array([True, True, True])), + ("2017-12-01", "YE", 3, np.array([True, True, True])), + ], + ) + def test_dti_dr_is_month_end(self, timestamp, freq, periods, expected_values): + # GH57377 + result = pd.date_range(timestamp, freq=freq, periods=periods).is_month_end + tm.assert_numpy_array_equal(result, expected_values) + + def test_dti_is_year_quarter_start_doubledigit_freq(self): + # GH#58523 + dr = pd.date_range("2017-01-01", periods=2, freq="10YS") + assert all(dr.is_year_start) + + dr = pd.date_range("2017-01-01", periods=2, freq="10QS") + assert all(dr.is_quarter_start) + + def test_dti_is_year_start_freq_custom_business_day_with_digit(self): + # GH#58664 + dr = pd.date_range("2020-01-01", periods=2, freq="2C") + msg = "Custom business days is not supported by is_year_start" + with pytest.raises(ValueError, match=msg): + dr.is_year_start + + @pytest.mark.parametrize("freq", ["3BMS", pd.offsets.BusinessMonthBegin(3)]) + def test_dti_is_year_quarter_start_freq_business_month_begin(self, freq): + # GH#58729 + dr = pd.date_range("2020-01-01", periods=5, freq=freq) + result = [x.is_year_start for x in dr] + assert result == [True, False, False, False, True] + + dr = pd.date_range("2020-01-01", periods=4, freq=freq) + result = [x.is_quarter_start for x in dr] + assert all(dr.is_quarter_start) + + def test_dti_is_year_start_freq_two_business_days(self): + # GH#58524 + dr = pd.date_range("2017-01-01", periods=2, freq="2B") + result = dr.is_year_start + expected = np.array([True, False]) + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("freq", ["MS", "QS", "YS"]) +@pytest.mark.parametrize("n", [1, 2, 10]) +@pytest.mark.parametrize( + "dt", + [ + datetime(1960, 1, 1), + datetime(1970, 1, 1), + datetime(1979, 12, 31), + ], +) +def test_against_scalar_parametric(freq, dt, n): + # https://github.com/pandas-dev/pandas/issues/49606 + freq = f"{n}{freq}" + d = pd.date_range(dt, periods=3, freq=freq) + result = list(d.is_year_start) + expected = [x.is_year_start for x in d] + assert result == expected + + +@pytest.mark.parametrize( + "value", + [ + np.iinfo(np.int64).max, # year 292277026596 + 2**32 * 86400 * 365, + -(2**31) * 86400 * 400, + np.iinfo(np.int64).min + 1, + ], +) +def test_day_of_week_year_beyond_int32(value): + # GH#66549 the year was passed to ccalendar.dayofweek as a C int, so + # second-resolution dates beyond year 2**31 got a truncated year + dti = pd.DatetimeIndex(np.array([value], dtype="M8[s]")) + # 1970-01-01 was a Thursday, i.e. day_of_week 3 + expected = (value // 86400 + 3) % 7 + + assert dti.day_of_week[0] == expected + assert dti[0].day_of_week == expected + assert dti[0].weekday() == expected + assert pd.Series(dti).dt.day_of_week[0] == expected + # scalar day_name goes through the same ccalendar helper + assert dti[0].day_name() == calendar.day_name[expected] + + +@pytest.mark.parametrize( + "value, expected", + [ + (np.iinfo(np.int64).max, 292277026596), + (2**32 * 86400 * 365, 4292117654), + (np.iinfo(np.int64).min + 1, -292277022657), + ], +) +def test_year_beyond_int32_raises(value, expected): + # GH#66549 the vectorized year is int32, and used to come back truncated, + # e.g. 219250468 for year 292277026596 + dti = pd.DatetimeIndex(np.array([value], dtype="M8[s]")) + assert dti[0].year == expected + + msg = f"year {expected} is out of range for the int32 result" + with pytest.raises(ValueError, match=msg): + dti.year + with pytest.raises(ValueError, match=msg): + pd.Series(dti).dt.year + with pytest.raises(ValueError, match=f"ISO year {expected}"): + dti.isocalendar() + + +def test_day_of_year_and_is_leap_year_beyond_int32(): + # GH#66549 ccalendar.get_day_of_year took the year as a C int, so both the + # scalar and the array path read the leap status off a truncated year. + # 10143198492 is a leap year, its int32 truncation 1553263900 is not. + dti = pd.DatetimeIndex(np.array(["10143198492-12-29"], dtype="M8[s]")) + + assert dti[0].day_of_year == 364 + assert dti.day_of_year[0] == 364 + assert pd.Series(dti).dt.day_of_year[0] == 364 + + assert dti[0].is_leap_year + assert dti.is_leap_year[0] + assert pd.Series(dti).dt.is_leap_year[0] diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_setops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..1f8bbdadbb218ffc7f4b09042782d05c34ec0911 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_setops.py @@ -0,0 +1,991 @@ +from datetime import ( + UTC, + datetime, + timedelta, + timezone, +) + +import numpy as np +import pytest + +from pandas.compat.numpy import np_version_gt2_6 +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + +from pandas.tseries.offsets import ( + BMonthEnd, + Minute, + MonthEnd, +) + +START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) + + +class TestDatetimeIndexSetOps: + tz = [ + None, + "UTC", + "Asia/Tokyo", + "US/Eastern", + "dateutil/Asia/Singapore", + "dateutil/US/Pacific", + ] + + # TODO: moved from test_datetimelike; dedup with version below + def test_union2(self, sort): + everything = pd.date_range("2020-01-01", periods=10) + first = everything[:5] + second = everything[5:] + union = first.union(second, sort=sort) + tm.assert_index_equal(union, everything) + + @pytest.mark.parametrize("box", [np.array, pd.Series, list]) + def test_union3(self, sort, box): + everything = pd.date_range("2020-01-01", periods=10) + first = everything[:5] + second = everything[5:] + + # GH 10149 support listlike inputs other than Index objects + expected = first.union(second, sort=sort) + case = box(second.values) + result = first.union(case, sort=sort) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("tz", tz) + def test_union(self, tz, sort): + rng1 = pd.date_range("1/1/2000", freq="D", periods=5, tz=tz, unit="ns") + other1 = pd.date_range("1/6/2000", freq="D", periods=5, tz=tz, unit="ns") + expected1 = pd.date_range("1/1/2000", freq="D", periods=10, tz=tz, unit="ns") + expected1_notsorted = pd.DatetimeIndex(list(other1) + list(rng1)) + + rng2 = pd.date_range("1/1/2000", freq="D", periods=5, tz=tz, unit="ns") + other2 = pd.date_range("1/4/2000", freq="D", periods=5, tz=tz, unit="ns") + expected2 = pd.date_range("1/1/2000", freq="D", periods=8, tz=tz, unit="ns") + expected2_notsorted = pd.DatetimeIndex(list(other2) + list(rng2[:3])) + + rng3 = pd.date_range("1/1/2000", freq="D", periods=5, tz=tz, unit="ns") + other3 = pd.DatetimeIndex([], tz=tz).as_unit("ns") + expected3 = pd.date_range("1/1/2000", freq="D", periods=5, tz=tz, unit="ns") + expected3_notsorted = rng3 + + for rng, other, exp, exp_notsorted in [ + (rng1, other1, expected1, expected1_notsorted), + (rng2, other2, expected2, expected2_notsorted), + (rng3, other3, expected3, expected3_notsorted), + ]: + result_union = rng.union(other, sort=sort) + tm.assert_index_equal(result_union, exp) + + result_union = other.union(rng, sort=sort) + if sort is None: + tm.assert_index_equal(result_union, exp) + else: + tm.assert_index_equal(result_union, exp_notsorted, check_freq=False) + + def test_union_coverage(self, sort): + idx = pd.DatetimeIndex(["2000-01-03", "2000-01-01", "2000-01-02"]) + ordered = pd.DatetimeIndex(idx.sort_values(), freq="infer") + result = ordered.union(idx, sort=sort) + tm.assert_index_equal(result, ordered) + + result = ordered[:0].union(ordered, sort=sort) + tm.assert_index_equal(result, ordered) + assert result.freq == ordered.freq + + def test_union_bug_1730(self, sort): + rng_a = pd.date_range("1/1/2012", periods=4, freq="3h") + rng_b = pd.date_range("1/1/2012", periods=4, freq="4h") + + result = rng_a.union(rng_b, sort=sort) + exp = list(rng_a) + list(rng_b[1:]) + if sort is None: + exp = pd.DatetimeIndex(sorted(exp)) + else: + exp = pd.DatetimeIndex(exp) + tm.assert_index_equal(result, exp) + + def test_union_bug_1745(self, sort): + left = pd.DatetimeIndex(["2012-05-11 15:19:49.695000"]) + right = pd.DatetimeIndex( + [ + "2012-05-29 13:04:21.322000", + "2012-05-11 15:27:24.873000", + "2012-05-11 15:31:05.350000", + ] + ) + + result = left.union(right, sort=sort) + exp = pd.DatetimeIndex( + [ + "2012-05-11 15:19:49.695000", + "2012-05-29 13:04:21.322000", + "2012-05-11 15:27:24.873000", + "2012-05-11 15:31:05.350000", + ] + ) + if sort is None: + exp = exp.sort_values() + tm.assert_index_equal(result, exp) + + def test_union_bug_4564(self, sort): + left = pd.date_range("2013-01-01", "2013-02-01") + right = left + pd.DateOffset(minutes=15) + + result = left.union(right, sort=sort) + exp = list(left) + list(right) + if sort is None: + exp = pd.DatetimeIndex(sorted(exp)) + else: + exp = pd.DatetimeIndex(exp) + tm.assert_index_equal(result, exp) + + def test_union_freq_both_none(self, sort): + # GH11086 + expected = pd.bdate_range("20150101", periods=10) + expected._freq = None + + result = expected.union(expected, sort=sort) + tm.assert_index_equal(result, expected) + assert result.freq is None + + def test_union_freq_infer(self): + # When taking the union of two DatetimeIndexes, we infer + # a freq even if the arguments don't have freq. This matches + # TimedeltaIndex behavior. + dti = pd.date_range("2016-01-01", periods=5) + left = dti[[0, 1, 3, 4]] + right = dti[[2, 3, 1]] + + assert left.freq is None + assert right.freq is None + + result = left.union(right) + tm.assert_index_equal(result, dti) + assert result.freq == "D" + + def test_union_sort_false_no_freq(self): + # GH#65191 union(sort=False) can produce a non-monotonic result; + # it must not retain a freq, which previously caused shift to + # silently return an empty index (start > end in _generate_range). + dti = pd.date_range("2016-01-01", periods=5, freq="D") + left = dti[3:] + right = dti[:3] + + result = left.union(right, sort=False) + expected = pd.DatetimeIndex( + ["2016-01-04", "2016-01-05", "2016-01-01", "2016-01-02", "2016-01-03"] + ) + tm.assert_index_equal(result, expected) + assert not result.is_monotonic_increasing + assert result.freq is None + + def test_union_sort_false_other_extends_past_self(self): + # GH#66322 with sort=False and self starting after other, the result + # is non-monotonic, so the fast path does not apply; previously it + # appended only other[:self[0]] and silently dropped the tail. + dti = pd.date_range("2016-01-01", periods=6, freq="MS") + left = dti[2:4] + + result = left.union(dti, sort=False) + expected = pd.DatetimeIndex( + [ + "2016-03-01", + "2016-04-01", + "2016-01-01", + "2016-02-01", + "2016-05-01", + "2016-06-01", + ] + ) + tm.assert_index_equal(result, expected) + assert result.freq is None + + def test_union_dataframe_index(self): + rng1 = pd.date_range("1/1/1999", "1/1/2012", freq="MS") + s1 = pd.Series(np.random.default_rng(2).standard_normal(len(rng1)), rng1) + + rng2 = pd.date_range("1/1/1980", "12/1/2001", freq="MS") + s2 = pd.Series(np.random.default_rng(2).standard_normal(len(rng2)), rng2) + df = pd.DataFrame({"s1": s1, "s2": s2}) + + exp = pd.date_range("1/1/1980", "1/1/2012", freq="MS") + tm.assert_index_equal(df.index, exp) + + def test_union_with_DatetimeIndex(self, sort): + i1 = pd.Index(np.arange(0, 20, 2, dtype=np.int64)) + i2 = pd.date_range(start="2012-01-03 00:00:00", periods=10, freq="D") + # Works + i1.union(i2, sort=sort) + # Fails with "AttributeError: can't set attribute" + i2.union(i1, sort=sort) + + def test_union_same_timezone_different_units(self): + # GH 55238 + idx1 = pd.date_range("2000-01-01", periods=3, tz="UTC").as_unit("ms") + idx2 = pd.date_range("2000-01-01", periods=3, tz="UTC").as_unit("us") + result = idx1.union(idx2) + expected = pd.date_range("2000-01-01", periods=3, tz="UTC").as_unit("us") + tm.assert_index_equal(result, expected) + + def test_union_same_nonzero_timezone_different_units(self): + # GH 60080 - fix timezone being changed to UTC when units differ + # but timezone is the same + tz = "UTC+05:00" + idx1 = pd.date_range("2000-01-01", periods=3, tz=tz).as_unit("us") + idx2 = pd.date_range("2000-01-01", periods=3, tz=tz).as_unit("ns") + + # Check pre-conditions + assert idx1.tz == idx2.tz + assert idx1.dtype != idx2.dtype # Different units + + # Test union preserves timezone when units differ + result = idx1.union(idx2) + expected = pd.date_range("2000-01-01", periods=3, tz=tz).as_unit("ns") + tm.assert_index_equal(result, expected) + + def test_union_different_dates_same_timezone_different_units(self): + # GH 60080 - fix timezone being changed to UTC when units differ + # but timezone is the same + tz = "UTC+05:00" + idx1 = pd.date_range("2000-01-01", periods=3, tz=tz).as_unit("us") + idx3 = pd.date_range("2000-01-03", periods=3, tz=tz).as_unit("us") + + # Test with different dates to ensure it's not just returning one of the inputs + result = idx1.union(idx3) + expected = pd.DatetimeIndex( + ["2000-01-01", "2000-01-02", "2000-01-03", "2000-01-04", "2000-01-05"], + tz=tz, + freq="D", + ).as_unit("us") + tm.assert_index_equal(result, expected) + + def test_intersection_same_timezone_different_units(self): + # GH 60080 - fix timezone being changed to UTC when units differ + # but timezone is the same + tz = "UTC+05:00" + idx1 = pd.date_range("2000-01-01", periods=3, tz=tz).as_unit("us") + idx2 = pd.date_range("2000-01-01", periods=3, tz=tz).as_unit("ns") + + # Check pre-conditions + assert idx1.tz == idx2.tz + assert idx1.dtype != idx2.dtype # Different units + + # Test intersection + result = idx1.intersection(idx2) + expected = pd.date_range("2000-01-01", periods=3, tz=tz) + tm.assert_index_equal(result, expected) + + # Intersection dtype is not commutative + result2 = idx2.intersection(idx1) + tm.assert_index_equal(result2, expected.as_unit("ns")) + + def test_symmetric_difference_same_timezone_different_units(self): + # GH 60080 - fix timezone being changed to UTC when units differ + # but timezone is the same + tz = "UTC+05:00" + idx1 = pd.date_range("2000-01-01", periods=3, tz=tz).as_unit("us") + idx4 = pd.date_range("2000-01-02", periods=3, tz=tz).as_unit("ns") + + # Check pre-conditions + assert idx1.tz == idx4.tz + assert idx1.dtype != idx4.dtype # Different units + + # Test symmetric_difference + result = idx1.symmetric_difference(idx4) + expected = pd.DatetimeIndex(["2000-01-01", "2000-01-04"], tz=tz).as_unit("ns") + tm.assert_index_equal(result, expected) + + # TODO: moved from test_datetimelike; de-duplicate with version below + def test_intersection2(self): + first = pd.date_range("2020-01-01", periods=10) + second = first[5:] + intersect = first.intersection(second) + tm.assert_index_equal(intersect, second) + + # GH 10149 + cases = [klass(second.values) for klass in [np.array, pd.Series, list]] + for case in cases: + result = first.intersection(case) + tm.assert_index_equal(result, second) + + third = pd.Index(["a", "b", "c"]) + result = first.intersection(third) + expected = pd.Index([], dtype=object) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "tz", [None, "Asia/Tokyo", "US/Eastern", "dateutil/US/Pacific"] + ) + def test_intersection(self, tz, sort): + # GH 4690 (with tz) + base = pd.date_range("6/1/2000", "6/30/2000", freq="D", name="idx", unit="ns") + + # if target has the same name, it is preserved + rng2 = pd.date_range("5/15/2000", "6/20/2000", freq="D", name="idx", unit="ns") + expected2 = pd.date_range( + "6/1/2000", "6/20/2000", freq="D", name="idx", unit="ns" + ) + + # if target name is different, it will be reset + rng3 = pd.date_range( + "5/15/2000", "6/20/2000", freq="D", name="other", unit="ns" + ) + expected3 = pd.date_range( + "6/1/2000", "6/20/2000", freq="D", name=None, unit="ns" + ) + + rng4 = pd.date_range("7/1/2000", "7/31/2000", freq="D", name="idx", unit="ns") + expected4 = pd.DatetimeIndex([], freq="D", name="idx", dtype="M8[ns]") + + for rng, expected in [ + (rng2, expected2), + (rng3, expected3), + (rng4, expected4), + ]: + result = base.intersection(rng) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + # non-monotonic + base = pd.DatetimeIndex( + ["2011-01-05", "2011-01-04", "2011-01-02", "2011-01-03"], tz=tz, name="idx" + ).as_unit("ns") + + rng2 = pd.DatetimeIndex( + ["2011-01-04", "2011-01-02", "2011-02-02", "2011-02-03"], tz=tz, name="idx" + ).as_unit("ns") + expected2 = pd.DatetimeIndex( + ["2011-01-04", "2011-01-02"], tz=tz, name="idx" + ).as_unit("ns") + + rng3 = pd.DatetimeIndex( + ["2011-01-04", "2011-01-02", "2011-02-02", "2011-02-03"], + tz=tz, + name="other", + ).as_unit("ns") + expected3 = pd.DatetimeIndex( + ["2011-01-04", "2011-01-02"], tz=tz, name=None + ).as_unit("ns") + + # GH 7880 + rng4 = pd.date_range( + "7/1/2000", "7/31/2000", freq="D", tz=tz, unit="ns", name="idx" + ) + expected4 = pd.DatetimeIndex([], tz=tz, name="idx").as_unit("ns") + assert expected4.freq is None + + for rng, expected in [ + (rng2, expected2), + (rng3, expected3), + (rng4, expected4), + ]: + result = base.intersection(rng, sort=sort) + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + # parametrize over both anchored and non-anchored freqs, as they + # have different code paths + @pytest.mark.parametrize("freq", ["min", "B"]) + def test_intersection_empty(self, tz_aware_fixture, freq): + # empty same freq GH2129 + tz = tz_aware_fixture + rng = pd.date_range("6/1/2000", "6/15/2000", freq=freq, tz=tz) + result = rng[0:0].intersection(rng) + assert len(result) == 0 + assert result.freq == rng.freq + + result = rng.intersection(rng[0:0]) + assert len(result) == 0 + assert result.freq == rng.freq + + # no overlap GH#33604 + check_freq = freq != "min" # We don't preserve freq on non-anchored offsets + result = rng[:3].intersection(rng[-3:]) + tm.assert_index_equal(result, rng[:0], check_freq=check_freq) + + # swapped left and right + result = rng[-3:].intersection(rng[:3]) + tm.assert_index_equal(result, rng[:0], check_freq=check_freq) + + def test_intersection_bug_1708(self): + index_1 = pd.date_range("1/1/2012", periods=4, freq="12h") + index_2 = index_1 + pd.DateOffset(hours=1) + + result = index_1.intersection(index_2) + assert len(result) == 0 + + @pytest.mark.parametrize("tz", tz) + def test_difference(self, tz, sort): + rng_dates = ["1/2/2000", "1/3/2000", "1/1/2000", "1/4/2000", "1/5/2000"] + + rng1 = pd.DatetimeIndex(rng_dates, tz=tz) + other1 = pd.date_range("1/6/2000", freq="D", periods=5, tz=tz) + expected1 = pd.DatetimeIndex(rng_dates, tz=tz) + + rng2 = pd.DatetimeIndex(rng_dates, tz=tz) + other2 = pd.date_range("1/4/2000", freq="D", periods=5, tz=tz) + expected2 = pd.DatetimeIndex(rng_dates[:3], tz=tz) + + rng3 = pd.DatetimeIndex(rng_dates, tz=tz) + other3 = pd.DatetimeIndex([], tz=tz) + expected3 = pd.DatetimeIndex(rng_dates, tz=tz) + + for rng, other, expected in [ + (rng1, other1, expected1), + (rng2, other2, expected2), + (rng3, other3, expected3), + ]: + result_diff = rng.difference(other, sort) + if sort is None and len(other): + # We dont sort (yet?) when empty GH#24959 + expected = expected.sort_values() + tm.assert_index_equal(result_diff, expected) + + def test_difference_freq(self, sort): + # GH14323: difference of DatetimeIndex should not preserve frequency + + index = pd.date_range("20160920", "20160925", freq="D", unit="ns") + other = pd.date_range("20160921", "20160924", freq="D", unit="ns") + expected = pd.DatetimeIndex(["20160920", "20160925"], dtype="M8[ns]", freq=None) + idx_diff = index.difference(other, sort) + tm.assert_index_equal(idx_diff, expected) + tm.assert_attr_equal("freq", idx_diff, expected) + + # preserve frequency when the difference is a contiguous + # subset of the original range + other = pd.date_range("20160922", "20160925", freq="D", unit="ns") + idx_diff = index.difference(other, sort) + expected = pd.DatetimeIndex(["20160920", "20160921"], dtype="M8[ns]", freq="D") + tm.assert_index_equal(idx_diff, expected) + tm.assert_attr_equal("freq", idx_diff, expected) + + def test_datetimeindex_diff(self, sort): + dti1 = pd.date_range(freq="QE-JAN", start=datetime(1997, 12, 31), periods=100) + dti2 = pd.date_range(freq="QE-JAN", start=datetime(1997, 12, 31), periods=98) + assert len(dti1.difference(dti2, sort)) == 2 + + @pytest.mark.parametrize("tz", [None, "Asia/Tokyo", "US/Eastern"]) + def test_setops_preserve_freq(self, tz): + rng = pd.date_range("1/1/2000", "1/1/2002", name="idx", tz=tz) + + result = rng[:50].union(rng[50:100]) + assert result.name == rng.name + assert result.freq == rng.freq + assert result.tz == rng.tz + + result = rng[:50].union(rng[30:100]) + assert result.name == rng.name + assert result.freq == rng.freq + assert result.tz == rng.tz + + result = rng[:50].union(rng[60:100]) + assert result.name == rng.name + assert result.freq is None + assert result.tz == rng.tz + + result = rng[:50].intersection(rng[25:75]) + assert result.name == rng.name + assert result.freqstr == "D" + assert result.tz == rng.tz + + nofreq = pd.DatetimeIndex(list(rng[25:75]), name="other") + result = rng[:50].union(nofreq) + assert result.name is None + assert result.freq == rng.freq + assert result.tz == rng.tz + + result = rng[:50].intersection(nofreq) + assert result.name is None + assert result.freq == rng.freq + assert result.tz == rng.tz + + def test_intersection_non_tick_no_fastpath(self): + # GH#42104 + dti = pd.DatetimeIndex( + [ + "2018-12-31", + "2019-03-31", + "2019-06-30", + "2019-09-30", + "2019-12-31", + "2020-03-31", + ], + freq="QE-DEC", + ) + result = dti[::2].intersection(dti[1::2]) + expected = dti[:0] + tm.assert_index_equal(result, expected, check_freq=False) + + def test_dti_intersection(self): + rng = pd.date_range("1/1/2011", periods=100, freq="h", tz="utc") + + left = rng[10:90][::-1] + right = rng[20:80][::-1] + + assert left.tz == rng.tz + result = left.intersection(right) + assert result.tz == left.tz + + # Note: not difference, as there is no symmetry requirement there + @pytest.mark.parametrize("setop", ["union", "intersection", "symmetric_difference"]) + def test_dti_setop_aware(self, setop): + # non-overlapping + # GH#39328 as of 2.0 we cast these to UTC instead of object + rng = pd.date_range("2012-11-15 00:00:00", periods=6, freq="h", tz="US/Central") + + rng2 = pd.date_range( + "2012-11-15 12:00:00", periods=6, freq="h", tz="US/Eastern" + ) + + result = getattr(rng, setop)(rng2) + + left = rng.tz_convert("UTC") + right = rng2.tz_convert("UTC") + expected = getattr(left, setop)(right) + tm.assert_index_equal(result, expected) + assert result.tz == left.tz + if len(result): + assert result[0].tz is UTC + assert result[-1].tz is UTC + + def test_dti_union_mixed(self): + # GH#21671 + rng = pd.DatetimeIndex([pd.Timestamp("2011-01-01"), pd.NaT]) + rng2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz="Asia/Tokyo") + # numpy>=2.6 object-dtype sort compares the tz-naive and tz-aware + # Timestamps directly, so safe_sort fails and union warns + warn = RuntimeWarning if np_version_gt2_6 else None + with tm.assert_produces_warning(warn, match="sort order is undefined"): + result = rng.union(rng2) + expected = pd.Index( + [ + pd.Timestamp("2011-01-01"), + pd.NaT, + pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), + pd.Timestamp("2012-01-02", tz="Asia/Tokyo"), + ], + dtype=object, + ) + tm.assert_index_equal(result, expected) + + +class TestBusinessDatetimeIndex: + def test_union(self, sort): + rng = pd.bdate_range(START, END) + # overlapping + left = rng[:10] + right = rng[5:10] + + the_union = left.union(right, sort=sort) + assert isinstance(the_union, pd.DatetimeIndex) + + # non-overlapping, gap in middle + left = rng[:5] + right = rng[10:] + + the_union = left.union(right, sort=sort) + assert isinstance(the_union, pd.Index) + + # non-overlapping, no gap + left = rng[:5] + right = rng[5:10] + + the_union = left.union(right, sort=sort) + assert isinstance(the_union, pd.DatetimeIndex) + + # order does not matter + if sort is None: + tm.assert_index_equal(right.union(left, sort=sort), the_union) + else: + expected = pd.DatetimeIndex(list(right) + list(left)) + tm.assert_index_equal( + right.union(left, sort=sort), expected, check_freq=False + ) + + # overlapping, but different offset + rng = pd.date_range(START, END, freq=BMonthEnd()) + + the_union = rng.union(rng, sort=sort) + assert isinstance(the_union, pd.DatetimeIndex) + + def test_union_not_cacheable(self, sort): + rng = pd.date_range("1/1/2000", periods=50, freq=Minute()) + rng1 = rng[10:] + rng2 = rng[:25] + the_union = rng1.union(rng2, sort=sort) + if sort is None: + tm.assert_index_equal(the_union, rng) + else: + expected = pd.DatetimeIndex(list(rng[10:]) + list(rng[:10])) + tm.assert_index_equal(the_union, expected) + + rng1 = rng[10:] + rng2 = rng[15:35] + the_union = rng1.union(rng2, sort=sort) + expected = rng[10:] + tm.assert_index_equal(the_union, expected) + + def test_intersection(self): + rng = pd.date_range("1/1/2000", periods=50, freq=Minute(), unit="ns") + rng1 = rng[10:] + rng2 = rng[:25] + the_int = rng1.intersection(rng2) + expected = rng[10:25] + tm.assert_index_equal(the_int, expected) + assert isinstance(the_int, pd.DatetimeIndex) + assert the_int.freq == rng.freq + + the_int = rng1.intersection(rng2) + tm.assert_index_equal(the_int, expected) + + # non-overlapping + the_int = rng[:10].intersection(rng[10:]) + expected = pd.DatetimeIndex([], freq=Minute()).as_unit("ns") + tm.assert_index_equal(the_int, expected) + + def test_intersection_bug(self): + # GH #771 + a = pd.bdate_range("11/30/2011", "12/31/2011") + b = pd.bdate_range("12/10/2011", "12/20/2011") + result = a.intersection(b) + tm.assert_index_equal(result, b) + assert result.freq == b.freq + + def test_intersection_list(self): + # GH#35876 + # values is not an Index -> no name -> retain "a" + values = [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-02-01")] + idx = pd.DatetimeIndex(values, name="a") + res = idx.intersection(values) + tm.assert_index_equal(res, idx) + + def test_month_range_union_tz_pytz(self, sort): + pytz = pytest.importorskip("pytz") + tz = pytz.timezone("US/Eastern") + + early_start = datetime(2011, 1, 1) + early_end = datetime(2011, 3, 1) + + late_start = datetime(2011, 3, 1) + late_end = datetime(2011, 5, 1) + + early_dr = pd.date_range( + start=early_start, end=early_end, tz=tz, freq=MonthEnd() + ) + late_dr = pd.date_range(start=late_start, end=late_end, tz=tz, freq=MonthEnd()) + + early_dr.union(late_dr, sort=sort) + + @td.skip_if_windows + def test_month_range_union_tz_dateutil(self, sort): + from pandas._libs.tslibs.timezones import dateutil_gettz + + tz = dateutil_gettz("US/Eastern") + + early_start = datetime(2011, 1, 1) + early_end = datetime(2011, 3, 1) + + late_start = datetime(2011, 3, 1) + late_end = datetime(2011, 5, 1) + + early_dr = pd.date_range( + start=early_start, end=early_end, tz=tz, freq=MonthEnd() + ) + late_dr = pd.date_range(start=late_start, end=late_end, tz=tz, freq=MonthEnd()) + + early_dr.union(late_dr, sort=sort) + + @pytest.mark.parametrize("sort", [False, None]) + def test_intersection_duplicates(self, sort): + # GH#38196 + idx1 = pd.Index( + [ + pd.Timestamp("2019-12-13"), + pd.Timestamp("2019-12-12"), + pd.Timestamp("2019-12-12"), + ] + ) + result = idx1.intersection(idx1, sort=sort) + expected = pd.Index([pd.Timestamp("2019-12-13"), pd.Timestamp("2019-12-12")]) + tm.assert_index_equal(result, expected) + + +class TestCustomDatetimeIndex: + def test_union(self, sort): + # overlapping + rng = pd.bdate_range(START, END, freq="C") + left = rng[:10] + right = rng[5:10] + + the_union = left.union(right, sort=sort) + assert isinstance(the_union, pd.DatetimeIndex) + + # non-overlapping, gap in middle + left = rng[:5] + right = rng[10:] + + the_union = left.union(right, sort) + assert isinstance(the_union, pd.Index) + + # non-overlapping, no gap + left = rng[:5] + right = rng[5:10] + + the_union = left.union(right, sort=sort) + assert isinstance(the_union, pd.DatetimeIndex) + + # order does not matter + if sort is None: + tm.assert_index_equal(right.union(left, sort=sort), the_union) + + # overlapping, but different offset + rng = pd.date_range(START, END, freq=BMonthEnd()) + + the_union = rng.union(rng, sort=sort) + assert isinstance(the_union, pd.DatetimeIndex) + + def test_intersection_bug(self): + # GH #771 + a = pd.bdate_range("11/30/2011", "12/31/2011", freq="C") + b = pd.bdate_range("12/10/2011", "12/20/2011", freq="C") + result = a.intersection(b) + tm.assert_index_equal(result, b) + assert result.freq == b.freq + + @pytest.mark.parametrize( + "tz", [None, "UTC", "Europe/Berlin", timezone(timedelta(hours=-1))] + ) + def test_intersection_dst_transition(self, tz): + # GH 46702: Europe/Berlin has DST transition + idx1 = pd.date_range("2020-03-27", periods=5, freq="D", tz=tz) + idx2 = pd.date_range("2020-03-30", periods=5, freq="D", tz=tz) + result = idx1.intersection(idx2) + expected = pd.date_range("2020-03-30", periods=2, freq="D", tz=tz) + tm.assert_index_equal(result, expected) + + # GH#45863 same problem for union + index1 = pd.date_range("2021-10-28", periods=3, freq="D", tz="Europe/London") + index2 = pd.date_range("2021-10-30", periods=4, freq="D", tz="Europe/London") + result = index1.union(index2) + expected = pd.date_range("2021-10-28", periods=6, freq="D", tz="Europe/London") + tm.assert_index_equal(result, expected) + + +def test_union_non_nano_rangelike(): + # GH 59036 + l1 = pd.DatetimeIndex( + ["2024-05-11", "2024-05-12"], dtype="datetime64[us]", name="Date", freq="D" + ) + l2 = pd.DatetimeIndex(["2024-05-13"], dtype="datetime64[us]", name="Date", freq="D") + result = l1.union(l2) + expected = pd.DatetimeIndex( + ["2024-05-11", "2024-05-12", "2024-05-13"], + dtype="datetime64[us]", + name="Date", + freq="D", + ) + tm.assert_index_equal(result, expected) + + +def test_intersection_non_nano_rangelike(): + # GH 59271 + l1 = pd.date_range("2024-01-01", "2024-01-03", unit="s") + l2 = pd.date_range("2024-01-02", "2024-01-04", unit="s") + result = l1.intersection(l2) + expected = pd.DatetimeIndex( + ["2024-01-02", "2024-01-03"], + dtype="datetime64[s]", + freq="D", + ) + tm.assert_index_equal(result, expected) + + +def test_union_across_dst_boundary(): + # GH#62915 union should work when one index ends at DST boundary + # and the other extends past it + index1 = pd.date_range("2025-10-25", "2025-10-26", freq="D", tz="Europe/Helsinki") + index2 = pd.date_range("2025-10-25", "2025-10-28", freq="D", tz="Europe/Helsinki") + result = index1.union(index2) + expected = pd.date_range("2025-10-25", "2025-10-28", freq="D", tz="Europe/Helsinki") + tm.assert_index_equal(result, expected) + + +# ----------------------------------------------------------------- +# _can_fast_intersect alignment checks (GH#44025) +# +# _can_fast_intersect must return False when two DatetimeIndexes with +# matching freq would not "line up", which causes _fast_intersect to +# produce wrong results. Categories of misalignment covered: +# +# 1. Variable-stride offsets (DateOffset / Week(weekday=None)) +# 2. Non-normalizing offsets with different time-of-day +# +# In addition, |n| != 1 offsets deliberately skip the fast path (we don't +# verify phase alignment), falling back to the general intersection. + + +@pytest.mark.parametrize( + "freq", + [ + pd.DateOffset(days=3), + pd.DateOffset(months=1), + pd.DateOffset(months=1, days=5), + pd.DateOffset(weeks=1), + pd.DateOffset(years=1), + ], +) +def test_dateoffset_never_fast(freq): + # GH#44025 DateOffset has no fixed stride + dti1 = pd.date_range("2021-01-01", periods=5, freq=freq) + dti2 = pd.date_range("2021-01-02", periods=5, freq=freq) + assert not dti1._can_fast_intersect(dti2) + + result = dti1.intersection(dti2) + assert len(result) == 0 + + +def test_week_no_weekday_misaligned_not_fast(): + # GH#44025 Week(weekday=None) with different day-of-week means + # the grids don't align so _fast_intersect can't be used. + freq = pd.offsets.Week() + assert freq.weekday is None + + dti1 = pd.date_range("2021-10-04", periods=5, freq=freq) # Monday + dti2 = pd.date_range("2021-10-05", periods=5, freq=freq) # Tuesday + assert not dti1._can_fast_intersect(dti2) + + result = dti1.intersection(dti2) + assert len(result) == 0 + + +def test_week_no_weekday_aligned_fast(): + # GH#44025 Week(weekday=None) with same day-of-week is fast. + freq = pd.offsets.Week() + dti1 = pd.date_range("2021-10-04", periods=5, freq=freq) + dti2 = pd.date_range("2021-10-18", periods=5, freq=freq) + assert dti1._can_fast_intersect(dti2) + + result = dti1.intersection(dti2) + assert set(result) == set(dti1).intersection(set(dti2)) + + +@pytest.mark.parametrize( + "freq", + [ + pd.offsets.CDay(1), + pd.offsets.BDay(1), + pd.offsets.MonthEnd(1), + pd.offsets.Week(weekday=0), + ], +) +def test_intersection_different_times(freq): + # GH#44025 + ts1 = pd.Timestamp("2021-10-13 09:00") + ts2 = pd.Timestamp("2021-10-13 10:00") + dti1 = pd.date_range(start=ts1, periods=10, freq=freq) + dti2 = pd.date_range(start=ts2, periods=10, freq=freq) + assert not dti1._can_fast_intersect(dti2) + + result = dti1.intersection(dti2) + assert len(result) == 0 + + +@pytest.mark.parametrize( + "freq", + [ + pd.offsets.CDay(1), + pd.offsets.BDay(1), + pd.offsets.MonthEnd(1), + pd.offsets.Week(weekday=0), + ], +) +def test_intersection_same_times_fast_path_preserved(freq): + # GH#44025 fast path should still be used when times match + ts = pd.Timestamp("2021-10-13 09:00") + dti1 = pd.date_range(start=ts, periods=10, freq=freq) + dti2 = pd.date_range(start=dti1[2], periods=10, freq=freq) + assert dti1._can_fast_intersect(dti2) + + result = dti1.intersection(dti2) + assert set(result) == set(dti1).intersection(set(dti2)) + assert len(result) > 0 + + +def test_intersection_dst_transition_time_of_day(): + # GH#44025 the check must compare wall-clock time-of-day; the deltas + # from midnight coincide here because wall 03:00 on the 2021-03-14 + # spring-forward day is 2 absolute hours after midnight. + dti1 = pd.date_range("2021-03-14 03:00", periods=5, freq="W-SUN", tz="US/Eastern") + dti2 = pd.date_range("2021-03-21 02:00", periods=5, freq="W-SUN", tz="US/Eastern") + assert not dti1._can_fast_intersect(dti2) + + result = dti1.intersection(dti2) + assert len(result) == 0 + + +def test_normalize_on_offset_does_not_affect_date_range(): + # GH#44025 normalize=True on the offset does not normalize + # date_range output, so different start times still misalign. + freq = pd.offsets.CDay(1, normalize=True) + dti1 = pd.date_range("2021-10-13 09:00", periods=10, freq=freq) + dti2 = pd.date_range("2021-10-13 10:00", periods=10, freq=freq) + assert not dti1._can_fast_intersect(dti2) + + result = dti1.intersection(dti2) + assert len(result) == 0 + + +@pytest.mark.parametrize( + "freq, start1, start2", + [ + # aligned and misaligned start pairs for each |n| > 1 offset; both + # skip the fast path but must still intersect correctly + (pd.offsets.MonthEnd(2), "2021-01-31", "2021-03-31"), + (pd.offsets.MonthEnd(2), "2021-01-31", "2021-02-28"), + (pd.offsets.MonthEnd(3), "2021-01-31", "2021-04-30"), + (pd.offsets.MonthEnd(4), "2021-01-31", "2021-03-31"), + (pd.offsets.QuarterEnd(2), "2021-03-31", "2021-09-30"), + (pd.offsets.QuarterEnd(2), "2021-03-31", "2021-06-30"), + (pd.offsets.YearEnd(2), "2020-12-31", "2022-12-31"), + (pd.offsets.YearEnd(2), "2020-12-31", "2021-12-31"), + (pd.offsets.Week(2, weekday=0), "2021-10-04", "2021-10-18"), + (pd.offsets.Week(2, weekday=0), "2021-10-04", "2021-10-11"), + (pd.offsets.SemiMonthEnd(2), "2021-01-15", "2021-02-15"), + (pd.offsets.SemiMonthEnd(2), "2021-01-15", "2021-01-31"), + # SemiMonthBegin anchors (day 1 and day_of_month) differ from + # SemiMonthEnd (day_of_month and month-end) + (pd.offsets.SemiMonthBegin(2), "2021-01-01", "2021-02-01"), + (pd.offsets.SemiMonthBegin(2), "2021-01-01", "2021-01-15"), + (pd.offsets.HalfYearEnd(2), "2021-06-30", "2022-06-30"), + (pd.offsets.HalfYearEnd(2), "2021-06-30", "2021-12-31"), + (pd.offsets.BDay(2), "2021-10-04", "2021-10-06"), + ], +) +def test_intersection_n_gt1_not_fast_but_correct(freq, start1, start2): + # GH#44025 |n| != 1 ranges deliberately skip the fast path (we don't + # verify phase alignment), but the general intersection must still be + # correct whether or not the two ranges happen to line up. + dti1 = pd.date_range(start1, periods=6, freq=freq) + dti2 = pd.date_range(start2, periods=6, freq=freq) + + assert not dti1._can_fast_intersect(dti2) + + result = dti1.intersection(dti2) + assert set(result) == set(dti1).intersection(set(dti2)) + + +def test_intersection_negative_n_not_fast(): + # GH#44025 with len(self) == 1 the monotonicity check is vacuous, + # so a negative-n freq can pair with a decreasing `other`; |n| != 1 + # means the fast path is skipped and the result is still correct. + freq = pd.offsets.MonthEnd(-1) + dti1 = pd.date_range("2021-06-30", periods=1, freq=freq) + dti2 = pd.date_range("2021-08-31", periods=4, freq=freq) + assert not dti1._can_fast_intersect(dti2) + + result = dti1.intersection(dti2) + assert list(result) == [pd.Timestamp("2021-06-30")] diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_timezones.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_timezones.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcd66d384d1a51ad16a89af963ecfcd9f2c00b6 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/datetimes/test_timezones.py @@ -0,0 +1,238 @@ +""" +Tests for DatetimeIndex timezone-related methods +""" + +from datetime import ( + UTC, + datetime, + timedelta, + tzinfo, +) +import zoneinfo + +from dateutil.tz import gettz +import numpy as np +import pytest + +from pandas._libs.tslibs import ( + conversion, + timezones, +) + +import pandas as pd +import pandas._testing as tm + + +class FixedOffset(tzinfo): + """Fixed offset in minutes east from UTC.""" + + def __init__(self, offset, name) -> None: + self.__offset = timedelta(minutes=offset) + self.__name = name + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return self.__name + + def dst(self, dt): + return timedelta(0) + + +fixed_off_no_name = FixedOffset(-330, None) + + +class TestDatetimeIndexTimezones: + # ------------------------------------------------------------- + # Unsorted + + def test_dti_drop_dont_lose_tz(self): + # GH#2621 + ind = pd.date_range("2012-12-01", periods=10, tz="utc") + ind = ind.drop(ind[-1]) + + assert ind.tz is not None + + def test_dti_tz_conversion_freq(self, tz_naive_fixture): + # GH25241 + t3 = pd.DatetimeIndex(["2019-01-01 10:00"], freq="h") + assert t3.tz_localize(tz=tz_naive_fixture).freq == t3.freq + t4 = pd.DatetimeIndex(["2019-01-02 12:00"], tz="UTC", freq="min") + assert t4.tz_convert(tz="UTC").freq == t4.freq + + def test_drop_dst_boundary(self): + # see gh-18031 + tz = "Europe/Brussels" + freq = "15min" + + start = pd.Timestamp("201710290100", tz=tz) + end = pd.Timestamp("201710290300", tz=tz) + index = pd.date_range(start=start, end=end, freq=freq, unit="ns") + + is_dst = [True] * 7 + [False] * 5 + expected = ( + pd.DatetimeIndex( + [ + "201710290115", + "201710290130", + "201710290145", + "201710290200", + "201710290215", + "201710290230", + "201710290245", + "201710290200", + "201710290215", + "201710290230", + "201710290245", + "201710290300", + ], + ) + .tz_localize(tz, ambiguous=is_dst) + .as_unit("ns") + ) + expected.freq = freq + result = index.drop(index[0]) + tm.assert_index_equal(result, expected) + + def test_date_range_localize(self, unit): + rng = pd.date_range( + "3/11/2012 03:00", periods=15, freq="h", tz="US/Eastern", unit=unit + ) + rng2 = pd.DatetimeIndex( + ["3/11/2012 03:00", "3/11/2012 04:00"], dtype=f"M8[{unit}, US/Eastern]" + ) + rng3 = pd.date_range("3/11/2012 03:00", periods=15, freq="h", unit=unit) + rng3 = rng3.tz_localize("US/Eastern") + + tm.assert_index_equal(rng._with_freq(None), rng3) + + # DST transition time + val = rng[0] + exp = pd.Timestamp("3/11/2012 03:00", tz="US/Eastern") + + assert val.hour == 3 + assert exp.hour == 3 + assert val == exp # same UTC value + tm.assert_index_equal(rng[:2], rng2, check_freq=False) + + def test_date_range_localize2(self, unit): + # Right before the DST transition + rng = pd.date_range( + "3/11/2012 00:00", periods=2, freq="h", tz="US/Eastern", unit=unit + ) + rng2 = pd.DatetimeIndex( + ["3/11/2012 00:00", "3/11/2012 01:00"], + dtype=f"M8[{unit}, US/Eastern]", + freq="h", + ) + tm.assert_index_equal(rng, rng2) + exp = pd.Timestamp("3/11/2012 00:00", tz="US/Eastern") + assert exp.hour == 0 + assert rng[0] == exp + exp = pd.Timestamp("3/11/2012 01:00", tz="US/Eastern") + assert exp.hour == 1 + assert rng[1] == exp + + rng = pd.date_range( + "3/11/2012 00:00", periods=10, freq="h", tz="US/Eastern", unit=unit + ) + assert rng[2].hour == 3 + + def test_timestamp_equality_different_timezones(self): + utc_range = pd.date_range("1/1/2000", periods=20, tz="UTC") + eastern_range = utc_range.tz_convert("US/Eastern") + berlin_range = utc_range.tz_convert("Europe/Berlin") + + for a, b, c in zip(utc_range, eastern_range, berlin_range, strict=True): + assert a == b + assert b == c + assert a == c + + assert (utc_range == eastern_range).all() + assert (utc_range == berlin_range).all() + assert (berlin_range == eastern_range).all() + + def test_dti_equals_with_tz(self): + left = pd.date_range("1/1/2011", periods=100, freq="h", tz="utc") + right = pd.date_range("1/1/2011", periods=100, freq="h", tz="US/Eastern") + + assert not left.equals(right) + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_dti_tz_nat(self, tzstr): + idx = pd.DatetimeIndex([pd.Timestamp("2013-1-1", tz=tzstr), pd.NaT]) + + assert pd.isna(idx[1]) + assert idx[0].tzinfo is not None + + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) + def test_utc_box_timestamp_and_localize(self, tzstr): + tz = timezones.maybe_get_tz(tzstr) + + rng = pd.date_range("3/11/2012", "3/12/2012", freq="h", tz="utc") + rng_eastern = rng.tz_convert(tzstr) + + expected = rng[-1].astimezone(tz) + + stamp = rng_eastern[-1] + assert stamp == expected + assert stamp.tzinfo == expected.tzinfo + + # right tzinfo + rng = pd.date_range("3/13/2012", "3/14/2012", freq="h", tz="utc") + rng_eastern = rng.tz_convert(tzstr) + if "dateutil" in tzstr: + assert "EDT" in repr(rng_eastern[0].tzinfo) or "tzfile" in repr( + rng_eastern[0].tzinfo + ) + + @pytest.mark.parametrize( + "tz", [zoneinfo.ZoneInfo("US/Central"), gettz("US/Central")] + ) + def test_with_tz(self, tz): + # just want it to work + start = datetime(2011, 3, 12, tzinfo=UTC) + dr = pd.bdate_range(start, periods=50, freq=pd.offsets.Hour()) + assert dr.tz is UTC + + # DateRange with naive datetimes + dr = pd.bdate_range("1/1/2005", "1/1/2009", tz=UTC) + dr = pd.bdate_range("1/1/2005", "1/1/2009", tz=tz) + + # normalized + central = dr.tz_convert(tz) + assert central.tz is tz + naive = central[0].to_pydatetime().replace(tzinfo=None) + comp = conversion.localize_pydatetime(naive, tz).tzinfo + assert central[0].tz is comp + + # compare vs a localized tz + naive = dr[0].to_pydatetime().replace(tzinfo=None) + comp = conversion.localize_pydatetime(naive, tz).tzinfo + assert central[0].tz is comp + + # datetimes with tzinfo set + dr = pd.bdate_range( + datetime(2005, 1, 1, tzinfo=UTC), + datetime(2009, 1, 1, tzinfo=UTC), + ) + msg = "Start and end cannot both be tz-aware with different timezones" + with pytest.raises(Exception, match=msg): + pd.bdate_range(datetime(2005, 1, 1, tzinfo=UTC), "1/1/2009", tz=tz) + + @pytest.mark.parametrize( + "tz", [zoneinfo.ZoneInfo("US/Eastern"), gettz("US/Eastern")] + ) + def test_dti_convert_tz_aware_datetime_datetime(self, tz): + # GH#1581 + dates = [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)] + + dates_aware = [conversion.localize_pydatetime(x, tz) for x in dates] + result = pd.DatetimeIndex(dates_aware).as_unit("ns") + assert timezones.tz_compare(result.tz, tz) + + converted = pd.to_datetime(dates_aware, utc=True).as_unit("ns") + ex_vals = np.array([pd.Timestamp(x).as_unit("ns")._value for x in dates_aware]) + tm.assert_numpy_array_equal(converted.asi8, ex_vals) + assert converted.tz is UTC diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_astype.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..1b5af98f43143468606d41a2f104c17079261c18 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_astype.py @@ -0,0 +1,253 @@ +import re + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + IntervalDtype, +) + +import pandas as pd +import pandas._testing as tm + + +class AstypeTests: + """Tests common to IntervalIndex with any subtype""" + + def test_astype_idempotent(self, index): + result = index.astype("interval") + tm.assert_index_equal(result, index) + + result = index.astype(index.dtype) + tm.assert_index_equal(result, index) + + def test_astype_object(self, index): + result = index.astype(object) + expected = pd.Index(index.values, dtype="object") + tm.assert_index_equal(result, expected) + assert not result.equals(index) + + def test_astype_category(self, index): + result = index.astype("category") + expected = pd.CategoricalIndex(index.values) + tm.assert_index_equal(result, expected) + + result = index.astype(CategoricalDtype()) + tm.assert_index_equal(result, expected) + + # non-default params + categories = index.dropna().unique().values[:-1] + dtype = CategoricalDtype(categories=categories, ordered=True) + msg = "Constructing a Categorical with a dtype and values containing" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = index.astype(dtype) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = pd.CategoricalIndex( + index.values, categories=categories, ordered=True + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "dtype", + [ + "int64", + "uint64", + "float64", + "complex128", + "period[M]", + "timedelta64", + "timedelta64[ns]", + "datetime64", + "datetime64[ns]", + "datetime64[ns, US/Eastern]", + ], + ) + def test_astype_cannot_cast(self, index, dtype): + msg = "Cannot cast IntervalIndex to dtype" + with pytest.raises(TypeError, match=msg): + index.astype(dtype) + + def test_astype_invalid_dtype(self, index): + msg = "data type [\"']fake_dtype[\"'] not understood" + with pytest.raises(TypeError, match=msg): + index.astype("fake_dtype") + + +class TestIntSubtype(AstypeTests): + """Tests specific to IntervalIndex with integer-like subtype""" + + indexes = [ + pd.IntervalIndex.from_breaks(np.arange(-10, 11, dtype="int64")), + pd.IntervalIndex.from_breaks(np.arange(100, dtype="uint64"), closed="left"), + ] + + @pytest.fixture(params=indexes) + def index(self, request): + return request.param + + @pytest.mark.parametrize( + "subtype", ["float64", "datetime64[ns]", "timedelta64[ns]"] + ) + def test_subtype_conversion(self, index, subtype): + dtype = IntervalDtype(subtype, index.closed) + result = index.astype(dtype) + expected = pd.IntervalIndex.from_arrays( + index.left.astype(subtype), index.right.astype(subtype), closed=index.closed + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "subtype_start, subtype_end", [("int64", "uint64"), ("uint64", "int64")] + ) + def test_subtype_integer(self, subtype_start, subtype_end): + index = pd.IntervalIndex.from_breaks(np.arange(100, dtype=subtype_start)) + dtype = IntervalDtype(subtype_end, index.closed) + result = index.astype(dtype) + expected = pd.IntervalIndex.from_arrays( + index.left.astype(subtype_end), + index.right.astype(subtype_end), + closed=index.closed, + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.xfail(reason="GH#15832") + def test_subtype_integer_errors(self): + # int64 -> uint64 fails with negative values + index = pd.interval_range(-10, 10) + dtype = IntervalDtype("uint64", "right") + + # Until we decide what the exception message _should_ be, we + # assert something that it should _not_ be. + # We should _not_ be getting a message suggesting that the -10 + # has been wrapped around to a large-positive integer + msg = "^(?!(left side of interval must be <= right side))" + with pytest.raises(ValueError, match=msg): + index.astype(dtype) + + +class TestFloatSubtype(AstypeTests): + """Tests specific to IntervalIndex with float subtype""" + + indexes = [ + pd.interval_range(-10.0, 10.0, closed="neither"), + pd.IntervalIndex.from_arrays( + [-1.5, np.nan, 0.0, 0.0, 1.5], [-0.5, np.nan, 1.0, 1.0, 3.0], closed="both" + ), + ] + + @pytest.fixture(params=indexes) + def index(self, request): + return request.param + + @pytest.mark.parametrize("subtype", ["int64", "uint64"]) + def test_subtype_integer(self, subtype): + index = pd.interval_range(0.0, 10.0) + dtype = IntervalDtype(subtype, "right") + result = index.astype(dtype) + expected = pd.IntervalIndex.from_arrays( + index.left.astype(subtype), index.right.astype(subtype), closed=index.closed + ) + tm.assert_index_equal(result, expected) + + # raises with NA + msg = r"Cannot convert non-finite values \(NA or inf\) to integer" + with pytest.raises(ValueError, match=msg): + index.insert(0, np.nan).astype(dtype) + + @pytest.mark.parametrize("subtype", ["int64", "uint64"]) + def test_subtype_integer_with_non_integer_borders(self, subtype): + index = pd.interval_range(0.0, 3.0, freq=0.25) + dtype = IntervalDtype(subtype, "right") + result = index.astype(dtype) + expected = pd.IntervalIndex.from_arrays( + index.left.astype(subtype), index.right.astype(subtype), closed=index.closed + ) + tm.assert_index_equal(result, expected) + + def test_subtype_integer_errors(self): + # float64 -> uint64 fails with negative values + index = pd.interval_range(-10.0, 10.0) + dtype = IntervalDtype("uint64", "right") + msg = re.escape( + "Cannot convert interval[float64, right] to interval[uint64, right]; " + "subtypes are incompatible" + ) + with pytest.raises(TypeError, match=msg): + index.astype(dtype) + + @pytest.mark.parametrize("subtype", ["datetime64[ns]", "timedelta64[ns]"]) + def test_subtype_datetimelike(self, index, subtype): + dtype = IntervalDtype(subtype, "right") + msg = "Cannot convert .* to .*; subtypes are incompatible" + with pytest.raises(TypeError, match=msg): + index.astype(dtype) + + def test_astype_category(self, index): + super().test_astype_category(index) + + +class TestDatetimelikeSubtype(AstypeTests): + """Tests specific to IntervalIndex with datetime-like subtype""" + + indexes = [ + pd.interval_range(pd.Timestamp("2018-01-01"), periods=10, closed="neither"), + pd.interval_range(pd.Timestamp("2018-01-01"), periods=10).insert(2, pd.NaT), + pd.interval_range(pd.Timestamp("2018-01-01", tz="US/Eastern"), periods=10), + pd.interval_range(pd.Timedelta("0 days"), periods=10, closed="both"), + pd.interval_range(pd.Timedelta("0 days"), periods=10).insert(2, pd.NaT), + ] + + @pytest.fixture(params=indexes) + def index(self, request): + return request.param + + @pytest.mark.parametrize("subtype", ["int64", "uint64"]) + def test_subtype_integer(self, index, subtype): + dtype = IntervalDtype(subtype, "right") + + if subtype != "int64": + msg = ( + r"Cannot convert interval" + r"\[(timedelta64\[us\]|datetime64\[us(, US/Eastern)?\]), .*\] " + r"to interval\[uint64, .*\]" + ) + with pytest.raises(TypeError, match=msg): + index.astype(dtype) + return + + result = index.astype(dtype) + new_left = index.left.astype(subtype) + new_right = index.right.astype(subtype) + + expected = pd.IntervalIndex.from_arrays( + new_left, new_right, closed=index.closed + ) + tm.assert_index_equal(result, expected) + + def test_subtype_float(self, index): + dtype = IntervalDtype("float64", "right") + msg = "Cannot convert .* to .*; subtypes are incompatible" + with pytest.raises(TypeError, match=msg): + index.astype(dtype) + + def test_subtype_datetimelike(self): + # datetime -> timedelta raises + dtype = IntervalDtype("timedelta64[ns]", "right") + msg = "Cannot convert .* to .*; subtypes are incompatible" + + index = pd.interval_range(pd.Timestamp("2018-01-01"), periods=10) + with pytest.raises(TypeError, match=msg): + index.astype(dtype) + + index = pd.interval_range(pd.Timestamp("2018-01-01", tz="CET"), periods=10) + with pytest.raises(TypeError, match=msg): + index.astype(dtype) + + # timedelta -> datetime raises + dtype = IntervalDtype("datetime64[ns]", "right") + index = pd.interval_range(pd.Timedelta("0 days"), periods=10) + with pytest.raises(TypeError, match=msg): + index.astype(dtype) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_constructors.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9ed004bddb6f6dbfefa982a7d0c74d91b906b4 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_constructors.py @@ -0,0 +1,550 @@ +from functools import partial +from itertools import pairwise +import re + +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +from pandas.core.dtypes.common import is_unsigned_integer_dtype +from pandas.core.dtypes.dtypes import IntervalDtype + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import IntervalArray +import pandas.core.common as com + + +class ConstructorTests: + """ + Common tests for all variations of IntervalIndex construction. Input data + to be supplied in breaks format, then converted by the subclass method + get_kwargs_from_breaks to the expected format. + """ + + @pytest.mark.parametrize( + "breaks_and_expected_subtype", + [ + ([3, 14, 15, 92, 653], np.int64), + (np.arange(10, dtype="int64"), np.int64), + (pd.Index(np.arange(-10, 11, dtype=np.int64)), np.int64), + (pd.Index(np.arange(10, 31, dtype=np.uint64)), np.uint64), + (pd.Index(np.arange(20, 30, 0.5), dtype=np.float64), np.float64), + (pd.date_range("20180101", periods=10, unit="ns"), "M8[ns]"), + ( + pd.date_range("20180101", periods=10, tz="US/Eastern", unit="ns"), + "datetime64[ns, US/Eastern]", + ), + (pd.timedelta_range("1 day", periods=10), "m8[us]"), + ], + ) + @pytest.mark.parametrize("name", [None, "foo"]) + def test_constructor(self, constructor, breaks_and_expected_subtype, closed, name): + breaks, expected_subtype = breaks_and_expected_subtype + + result_kwargs = self.get_kwargs_from_breaks(breaks, closed) + + result = constructor(closed=closed, name=name, **result_kwargs) + + assert result.closed == closed + assert result.name == name + assert result.dtype.subtype == expected_subtype + tm.assert_index_equal( + result.left, pd.Index(breaks[:-1], dtype=expected_subtype), check_freq=False + ) + tm.assert_index_equal( + result.right, pd.Index(breaks[1:], dtype=expected_subtype), check_freq=False + ) + + @pytest.mark.parametrize( + "breaks, subtype", + [ + (pd.Index([0, 1, 2, 3, 4], dtype=np.int64), "float64"), + (pd.Index([0, 1, 2, 3, 4], dtype=np.int64), "datetime64[ns]"), + (pd.Index([0, 1, 2, 3, 4], dtype=np.int64), "timedelta64[ns]"), + (pd.Index([0, 1, 2, 3, 4], dtype=np.float64), "int64"), + (pd.date_range("2017-01-01", periods=5, unit="ns"), "int64"), + (pd.timedelta_range("1 day", periods=5), "int64"), + ], + ) + def test_constructor_dtype(self, constructor, breaks, subtype): + # GH 19262: conversion via dtype parameter + expected_kwargs = self.get_kwargs_from_breaks(breaks.astype(subtype)) + expected = constructor(**expected_kwargs) + + result_kwargs = self.get_kwargs_from_breaks(breaks) + iv_dtype = IntervalDtype(subtype, "right") + for dtype in (iv_dtype, str(iv_dtype)): + result = constructor(dtype=dtype, **result_kwargs) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "breaks", + [ + pd.Index([0, 1, 2, 3, 4], dtype=np.int64), + pd.Index([0, 1, 2, 3, 4], dtype=np.uint64), + pd.Index([0, 1, 2, 3, 4], dtype=np.float64), + pd.date_range("2017-01-01", periods=5, unit="ns"), + pd.timedelta_range("1 day", periods=5), + ], + ) + def test_constructor_pass_closed(self, constructor, breaks): + # not passing closed to IntervalDtype, but to IntervalArray constructor + iv_dtype = IntervalDtype(breaks.dtype) + + result_kwargs = self.get_kwargs_from_breaks(breaks) + + for dtype in (iv_dtype, str(iv_dtype)): + with tm.assert_produces_warning(None): + result = constructor(dtype=dtype, closed="left", **result_kwargs) + assert result.dtype.closed == "left" + + @pytest.mark.parametrize("breaks", [[np.nan] * 2, [np.nan] * 4, [np.nan] * 50]) + def test_constructor_nan(self, constructor, breaks, closed): + # GH 18421 + result_kwargs = self.get_kwargs_from_breaks(breaks) + result = constructor(closed=closed, **result_kwargs) + + expected_subtype = np.float64 + expected_values = np.array(breaks[:-1], dtype=object) + + assert result.closed == closed + assert result.dtype.subtype == expected_subtype + tm.assert_numpy_array_equal(np.array(result), expected_values) + + @pytest.mark.parametrize( + "breaks", + [ + [], + np.array([], dtype="int64"), + np.array([], dtype="uint64"), + np.array([], dtype="float64"), + np.array([], dtype="datetime64[ns]"), + np.array([], dtype="timedelta64[ns]"), + ], + ) + def test_constructor_empty(self, constructor, breaks, closed): + # GH 18421 + result_kwargs = self.get_kwargs_from_breaks(breaks) + result = constructor(closed=closed, **result_kwargs) + + expected_values = np.array([], dtype=object) + expected_subtype = getattr(breaks, "dtype", np.int64) + + assert result.empty + assert result.closed == closed + assert result.dtype.subtype == expected_subtype + tm.assert_numpy_array_equal(np.array(result), expected_values) + + @pytest.mark.parametrize( + "breaks", + [ + tuple("0123456789"), + list("abcdefghij"), + np.array(list("abcdefghij"), dtype=object), + np.array(list("abcdefghij"), dtype=" left if not closed_left else val >= left + in_right = val < right if not closed_right else val <= right + if in_left and in_right: + found = idx + break + expected.append(found) + + result = index.get_indexer(query) + tm.assert_numpy_array_equal(result, np.array(expected, dtype="intp")) + + +def test_get_indexer_with_nans_in_target(closed): + # GH#47614 - NaN in scalar target should return -1 + index = pd.IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed) + result = index.get_indexer([0.5, np.nan, 2.5]) + expected = np.array([0, -1, 1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + +def test_get_indexer_non_monotonic_with_scalars(): + # GH#47614 - non-monotonic falls back to IntervalTree + index = pd.IntervalIndex.from_tuples([(2, 3), (0, 1)]) + result = index.get_indexer([0.5, 2.5, 1.5]) + expected = np.array([1, 0, -1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + +def test_get_indexer_scalar_monotonic_datetime(): + # GH#47614 - datetime IntervalIndex with scalar targets + breaks = pd.date_range("2018-01-01", periods=4, unit="ns") + index = pd.IntervalIndex.from_breaks(breaks) + # 2018-01-01T12:00 -> interval 0, 2018-01-05 -> past end, + # 2018-01-02T12:00 -> interval 1 + target = pd.DatetimeIndex( + ["2018-01-01T12:00", "2018-01-05", "2018-01-02T12:00"], dtype="M8[ns]" + ) + result = index.get_indexer(target) + expected = np.array([0, -1, 1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + +def test_get_indexer_scalar_monotonic_timedelta(): + # GH#47614 - timedelta IntervalIndex with scalar targets + breaks = pd.timedelta_range("0 days", periods=4) + index = pd.IntervalIndex.from_breaks(breaks) + target = pd.Index([pd.Timedelta("0.5 days"), pd.Timedelta("3.5 days")]) + result = index.get_indexer(target) + expected = np.array([0, -1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("closed", ["left", "right", "neither"]) +def test_get_indexer_nested_empty_interval(closed): + # GH#26893 an empty interval nested inside another one is not an overlap, + # so the index is usable with get_indexer; the empty one matches nothing + index = pd.IntervalIndex.from_tuples([(0, 3), (1, 1)], closed=closed) + assert index.is_overlapping is False + + result = index.get_indexer([0, 1, 2, 3]) + expected = np.array( + { + "left": [0, 0, 0, -1], + "right": [-1, 0, 0, 0], + "neither": [-1, 0, 0, -1], + }[closed], + dtype="intp", + ) + tm.assert_numpy_array_equal(result, expected) + + # the empty interval is still found by an exact Interval lookup + assert index.get_loc(pd.Interval(1, 1, closed=closed)) == 1 + + +class TestSliceLocs: + def test_slice_locs_with_interval(self): + # increasing monotonically + index = pd.IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)]) + + assert index.slice_locs(start=pd.Interval(0, 2), end=pd.Interval(2, 4)) == ( + 0, + 3, + ) + assert index.slice_locs(start=pd.Interval(0, 2)) == (0, 3) + assert index.slice_locs(end=pd.Interval(2, 4)) == (0, 3) + assert index.slice_locs(end=pd.Interval(0, 2)) == (0, 1) + assert index.slice_locs(start=pd.Interval(2, 4), end=pd.Interval(0, 2)) == ( + 2, + 1, + ) + + # decreasing monotonically + index = pd.IntervalIndex.from_tuples([(2, 4), (1, 3), (0, 2)]) + + assert index.slice_locs(start=pd.Interval(0, 2), end=pd.Interval(2, 4)) == ( + 2, + 1, + ) + assert index.slice_locs(start=pd.Interval(0, 2)) == (2, 3) + assert index.slice_locs(end=pd.Interval(2, 4)) == (0, 1) + assert index.slice_locs(end=pd.Interval(0, 2)) == (0, 3) + assert index.slice_locs(start=pd.Interval(2, 4), end=pd.Interval(0, 2)) == ( + 0, + 3, + ) + + # sorted duplicates + index = pd.IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4)]) + + assert index.slice_locs(start=pd.Interval(0, 2), end=pd.Interval(2, 4)) == ( + 0, + 3, + ) + assert index.slice_locs(start=pd.Interval(0, 2)) == (0, 3) + assert index.slice_locs(end=pd.Interval(2, 4)) == (0, 3) + assert index.slice_locs(end=pd.Interval(0, 2)) == (0, 2) + assert index.slice_locs(start=pd.Interval(2, 4), end=pd.Interval(0, 2)) == ( + 2, + 2, + ) + + # unsorted duplicates + index = pd.IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)]) + + with pytest.raises( + KeyError, + match=re.escape( + '"Cannot get left slice bound for non-unique label: ' + "Interval(0, 2, closed='right')\"" + ), + ): + index.slice_locs(start=pd.Interval(0, 2), end=pd.Interval(2, 4)) + + with pytest.raises( + KeyError, + match=re.escape( + '"Cannot get left slice bound for non-unique label: ' + "Interval(0, 2, closed='right')\"" + ), + ): + index.slice_locs(start=pd.Interval(0, 2)) + + assert index.slice_locs(end=pd.Interval(2, 4)) == (0, 2) + + with pytest.raises( + KeyError, + match=re.escape( + '"Cannot get right slice bound for non-unique label: ' + "Interval(0, 2, closed='right')\"" + ), + ): + index.slice_locs(end=pd.Interval(0, 2)) + + with pytest.raises( + KeyError, + match=re.escape( + '"Cannot get right slice bound for non-unique label: ' + "Interval(0, 2, closed='right')\"" + ), + ): + index.slice_locs(start=pd.Interval(2, 4), end=pd.Interval(0, 2)) + + # another unsorted duplicates + index = pd.IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)]) + + assert index.slice_locs(start=pd.Interval(0, 2), end=pd.Interval(2, 4)) == ( + 0, + 3, + ) + assert index.slice_locs(start=pd.Interval(0, 2)) == (0, 4) + assert index.slice_locs(end=pd.Interval(2, 4)) == (0, 3) + assert index.slice_locs(end=pd.Interval(0, 2)) == (0, 2) + assert index.slice_locs(start=pd.Interval(2, 4), end=pd.Interval(0, 2)) == ( + 2, + 2, + ) + + def test_slice_locs_with_ints_and_floats_succeeds(self): + # increasing non-overlapping + index = pd.IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)]) + + assert index.slice_locs(0, 1) == (0, 1) + assert index.slice_locs(0, 2) == (0, 2) + assert index.slice_locs(0, 3) == (0, 2) + assert index.slice_locs(3, 1) == (2, 1) + assert index.slice_locs(3, 4) == (2, 3) + assert index.slice_locs(0, 4) == (0, 3) + + # decreasing non-overlapping + index = pd.IntervalIndex.from_tuples([(3, 4), (1, 2), (0, 1)]) + assert index.slice_locs(0, 1) == (3, 3) + assert index.slice_locs(0, 2) == (3, 2) + assert index.slice_locs(0, 3) == (3, 1) + assert index.slice_locs(3, 1) == (1, 3) + assert index.slice_locs(3, 4) == (1, 1) + assert index.slice_locs(0, 4) == (3, 1) + + @pytest.mark.parametrize("query", [[0, 1], [0, 2], [0, 3], [0, 4]]) + @pytest.mark.parametrize( + "tuples", + [ + [(0, 2), (1, 3), (2, 4)], + [(2, 4), (1, 3), (0, 2)], + [(0, 2), (0, 2), (2, 4)], + [(0, 2), (2, 4), (0, 2)], + [(0, 2), (0, 2), (2, 4), (1, 3)], + ], + ) + def test_slice_locs_with_ints_and_floats_errors(self, tuples, query): + start, stop = query + index = pd.IntervalIndex.from_tuples(tuples) + with pytest.raises( + KeyError, + match=( + "'can only get slices from an IntervalIndex if bounds are " + "non-overlapping and all monotonic increasing or decreasing'" + ), + ): + index.slice_locs(start, stop) + + +class TestPutmask: + @pytest.mark.parametrize("tz", ["US/Pacific", None]) + def test_putmask_dt64(self, tz): + # GH#37968 + dti = pd.date_range("2016-01-01", periods=9, tz=tz) + idx = pd.IntervalIndex.from_breaks(dti) + mask = np.zeros(idx.shape, dtype=bool) + mask[0:3] = True + + result = idx.putmask(mask, idx[-1]) + expected = pd.IntervalIndex([idx[-1]] * 3 + list(idx[3:])) + tm.assert_index_equal(result, expected) + + def test_putmask_td64(self): + # GH#37968 + dti = pd.date_range("2016-01-01", periods=9, unit="ns") + tdi = dti - dti[0] + idx = pd.IntervalIndex.from_breaks(tdi) + mask = np.zeros(idx.shape, dtype=bool) + mask[0:3] = True + + result = idx.putmask(mask, idx[-1]) + expected = pd.IntervalIndex([idx[-1]] * 3 + list(idx[3:])) + tm.assert_index_equal(result, expected) + + +class TestContains: + # .__contains__, not .contains + + def test_contains_dunder(self): + index = pd.IntervalIndex.from_arrays([0, 1], [1, 2], closed="right") + + # __contains__ requires perfect matches to intervals. + assert 0 not in index + assert 1 not in index + assert 2 not in index + + assert pd.Interval(0, 1, closed="right") in index + assert pd.Interval(0, 2, closed="right") not in index + assert pd.Interval(0, 0.5, closed="right") not in index + assert pd.Interval(3, 5, closed="right") not in index + assert pd.Interval(-1, 0, closed="left") not in index + assert pd.Interval(0, 1, closed="left") not in index + assert pd.Interval(0, 1, closed="both") not in index diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_interval.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_interval.py new file mode 100644 index 0000000000000000000000000000000000000000..6309ac282d1cbf6df8e6d16260bcf8a4cbfb2ab3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_interval.py @@ -0,0 +1,940 @@ +from itertools import permutations +import re + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +import pandas.core.common as com + + +class TestIntervalIndex: + index = pd.IntervalIndex.from_arrays([0, 1], [1, 2]) + + def create_index(self, closed="right"): + return pd.IntervalIndex.from_breaks(range(11), closed=closed) + + def create_index_with_nan(self, closed="right"): + mask = [True, False] + [True] * 8 + return pd.IntervalIndex.from_arrays( + np.where(mask, np.arange(10), np.nan), + np.where(mask, np.arange(1, 11), np.nan), + closed=closed, + ) + + def test_properties(self, closed): + index = self.create_index(closed=closed) + assert len(index) == 10 + assert index.size == 10 + assert index.shape == (10,) + + tm.assert_index_equal(index.left, pd.Index(np.arange(10, dtype=np.int64))) + tm.assert_index_equal(index.right, pd.Index(np.arange(1, 11, dtype=np.int64))) + tm.assert_index_equal( + index.mid, pd.Index(np.arange(0.5, 10.5, dtype=np.float64)) + ) + + assert index.closed == closed + + ivs = [ + pd.Interval(left, right, closed) + for left, right in zip(range(10), range(1, 11), strict=True) + ] + expected = np.array(ivs, dtype=object) + tm.assert_numpy_array_equal(np.asarray(index), expected) + + # with nans + index = self.create_index_with_nan(closed=closed) + assert len(index) == 10 + assert index.size == 10 + assert index.shape == (10,) + + expected_left = pd.Index([0, np.nan, 2, 3, 4, 5, 6, 7, 8, 9]) + expected_right = expected_left + 1 + expected_mid = expected_left + 0.5 + tm.assert_index_equal(index.left, expected_left) + tm.assert_index_equal(index.right, expected_right) + tm.assert_index_equal(index.mid, expected_mid) + + assert index.closed == closed + + ivs = [ + pd.Interval(left, right, closed) if pd.notna(left) else np.nan + for left, right in zip(expected_left, expected_right, strict=True) + ] + expected = np.array(ivs, dtype=object) + tm.assert_numpy_array_equal(np.asarray(index), expected) + + @pytest.mark.parametrize( + "breaks", + [ + [1, 1, 2, 5, 15, 53, 217, 1014, 5335, 31240, 201608], + [-np.inf, -100, -10, 0.5, 1, 1.5, 3.8, 101, 202, np.inf], + pd.date_range("2017-01-01", "2017-01-04", unit="ns"), + pd.date_range("2017-01-01", "2017-01-04", unit="s"), + pd.to_timedelta(["1ns", "2ms", "3s", "4min", "5h", "6D"]), + ], + ) + def test_length(self, closed, breaks): + # GH 18789 + index = pd.IntervalIndex.from_breaks(breaks, closed=closed) + result = index.length + expected = pd.Index(iv.length for iv in index) + tm.assert_index_equal(result, expected) + + # with NA + index = index.insert(1, np.nan) + result = index.length + expected = pd.Index(iv.length if pd.notna(iv) else iv for iv in index) + tm.assert_index_equal(result, expected) + + def test_with_nans(self, closed): + index = self.create_index(closed=closed) + assert index.hasnans is False + + result = index.isna() + expected = np.zeros(len(index), dtype=bool) + tm.assert_numpy_array_equal(result, expected) + + result = index.notna() + expected = np.ones(len(index), dtype=bool) + tm.assert_numpy_array_equal(result, expected) + + index = self.create_index_with_nan(closed=closed) + assert index.hasnans is True + + result = index.isna() + expected = np.array([False, True] + [False] * (len(index) - 2)) + tm.assert_numpy_array_equal(result, expected) + + result = index.notna() + expected = np.array([True, False] + [True] * (len(index) - 2)) + tm.assert_numpy_array_equal(result, expected) + + def test_copy(self, closed): + expected = self.create_index(closed=closed) + + result = expected.copy() + assert result.equals(expected) + + result = expected.copy(deep=True) + assert result.equals(expected) + assert result.left is not expected.left + + def test_ensure_copied_data(self, closed): + # exercise the copy flag in the constructor + + # not copying + index = self.create_index(closed=closed) + result = pd.IntervalIndex(index, copy=False) + tm.assert_numpy_array_equal( + index.left.values, result.left.values, check_same="same" + ) + tm.assert_numpy_array_equal( + index.right.values, result.right.values, check_same="same" + ) + + # by-definition make a copy + result = pd.IntervalIndex(np.array(index), copy=False) + tm.assert_numpy_array_equal( + index.left.values, result.left.values, check_same="copy" + ) + tm.assert_numpy_array_equal( + index.right.values, result.right.values, check_same="copy" + ) + + def test_delete(self, closed): + breaks = np.arange(1, 11, dtype=np.int64) + expected = pd.IntervalIndex.from_breaks(breaks, closed=closed) + result = self.create_index(closed=closed).delete(0) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "data", + [ + pd.interval_range(0, periods=10, closed="neither"), + pd.interval_range(1.7, periods=8, freq=2.5, closed="both"), + pd.interval_range(pd.Timestamp("20170101"), periods=12, closed="left"), + pd.interval_range(pd.Timedelta("1 day"), periods=6, closed="right"), + ], + ) + def test_insert(self, data): + item = data[0] + idx_item = pd.IntervalIndex([item]) + + # start + expected = idx_item.append(data) + result = data.insert(0, item) + tm.assert_index_equal(result, expected) + + # end + expected = data.append(idx_item) + result = data.insert(len(data), item) + tm.assert_index_equal(result, expected) + + # mid + expected = data[:3].append(idx_item).append(data[3:]) + result = data.insert(3, item) + tm.assert_index_equal(result, expected) + + # invalid type + res = data.insert(1, "foo") + expected = data.astype(object).insert(1, "foo") + tm.assert_index_equal(res, expected) + + msg = "can only insert Interval objects and NA into an IntervalArray" + with pytest.raises(TypeError, match=msg): + data._data.insert(1, "foo") + + # invalid closed + msg = "'value.closed' is 'left', expected 'right'." + for closed in {"left", "right", "both", "neither"} - {item.closed}: + msg = f"'value.closed' is '{closed}', expected '{item.closed}'." + bad_item = pd.Interval(item.left, item.right, closed=closed) + res = data.insert(1, bad_item) + expected = data.astype(object).insert(1, bad_item) + tm.assert_index_equal(res, expected) + with pytest.raises(ValueError, match=msg): + data._data.insert(1, bad_item) + + # GH 18295 (test missing) + na_idx = pd.IntervalIndex([np.nan], closed=data.closed) + for na in [np.nan, None, pd.NA]: + expected = data[:1].append(na_idx).append(data[1:]) + result = data.insert(1, na) + tm.assert_index_equal(result, expected) + + if data.left.dtype.kind not in ["m", "M"]: + # trying to insert pd.NaT into a numeric-dtyped Index should cast + expected = data.astype(object).insert(1, pd.NaT) + + msg = "can only insert Interval objects and NA into an IntervalArray" + with pytest.raises(TypeError, match=msg): + data._data.insert(1, pd.NaT) + + result = data.insert(1, pd.NaT) + tm.assert_index_equal(result, expected) + + def test_is_unique_interval(self, closed): + """ + Interval specific tests for is_unique in addition to base class tests + """ + # unique overlapping - distinct endpoints + idx = pd.IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], closed=closed) + assert idx.is_unique is True + + # unique overlapping - shared endpoints + idx = pd.IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed) + assert idx.is_unique is True + + # unique nested + idx = pd.IntervalIndex.from_tuples([(-1, 1), (-2, 2)], closed=closed) + assert idx.is_unique is True + + # unique NaN + idx = pd.IntervalIndex.from_tuples([(np.nan, np.nan)], closed=closed) + assert idx.is_unique is True + + # non-unique NaN + idx = pd.IntervalIndex.from_tuples( + [(np.nan, np.nan), (np.nan, np.nan)], closed=closed + ) + assert idx.is_unique is False + + def test_monotonic(self, closed): + # increasing non-overlapping + idx = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)], closed=closed) + assert idx.is_monotonic_increasing is True + assert idx._is_strictly_monotonic_increasing is True + assert idx.is_monotonic_decreasing is False + assert idx._is_strictly_monotonic_decreasing is False + + # decreasing non-overlapping + idx = pd.IntervalIndex.from_tuples([(4, 5), (2, 3), (1, 2)], closed=closed) + assert idx.is_monotonic_increasing is False + assert idx._is_strictly_monotonic_increasing is False + assert idx.is_monotonic_decreasing is True + assert idx._is_strictly_monotonic_decreasing is True + + # unordered non-overlapping + idx = pd.IntervalIndex.from_tuples([(0, 1), (4, 5), (2, 3)], closed=closed) + assert idx.is_monotonic_increasing is False + assert idx._is_strictly_monotonic_increasing is False + assert idx.is_monotonic_decreasing is False + assert idx._is_strictly_monotonic_decreasing is False + + # increasing overlapping + idx = pd.IntervalIndex.from_tuples([(0, 2), (0.5, 2.5), (1, 3)], closed=closed) + assert idx.is_monotonic_increasing is True + assert idx._is_strictly_monotonic_increasing is True + assert idx.is_monotonic_decreasing is False + assert idx._is_strictly_monotonic_decreasing is False + + # decreasing overlapping + idx = pd.IntervalIndex.from_tuples([(1, 3), (0.5, 2.5), (0, 2)], closed=closed) + assert idx.is_monotonic_increasing is False + assert idx._is_strictly_monotonic_increasing is False + assert idx.is_monotonic_decreasing is True + assert idx._is_strictly_monotonic_decreasing is True + + # unordered overlapping + idx = pd.IntervalIndex.from_tuples([(0.5, 2.5), (0, 2), (1, 3)], closed=closed) + assert idx.is_monotonic_increasing is False + assert idx._is_strictly_monotonic_increasing is False + assert idx.is_monotonic_decreasing is False + assert idx._is_strictly_monotonic_decreasing is False + + # increasing overlapping shared endpoints + idx = pd.IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed) + assert idx.is_monotonic_increasing is True + assert idx._is_strictly_monotonic_increasing is True + assert idx.is_monotonic_decreasing is False + assert idx._is_strictly_monotonic_decreasing is False + + # decreasing overlapping shared endpoints + idx = pd.IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)], closed=closed) + assert idx.is_monotonic_increasing is False + assert idx._is_strictly_monotonic_increasing is False + assert idx.is_monotonic_decreasing is True + assert idx._is_strictly_monotonic_decreasing is True + + # stationary + idx = pd.IntervalIndex.from_tuples([(0, 1), (0, 1)], closed=closed) + assert idx.is_monotonic_increasing is True + assert idx._is_strictly_monotonic_increasing is False + assert idx.is_monotonic_decreasing is True + assert idx._is_strictly_monotonic_decreasing is False + + # empty + idx = pd.IntervalIndex([], closed=closed) + assert idx.is_monotonic_increasing is True + assert idx._is_strictly_monotonic_increasing is True + assert idx.is_monotonic_decreasing is True + assert idx._is_strictly_monotonic_decreasing is True + + def test_is_monotonic_with_nans(self): + # GH#41831 + index = pd.IntervalIndex([np.nan, np.nan]) + + assert not index.is_monotonic_increasing + assert not index._is_strictly_monotonic_increasing + assert not index.is_monotonic_increasing + assert not index._is_strictly_monotonic_decreasing + assert not index.is_monotonic_decreasing + + @pytest.mark.parametrize( + "breaks", + [ + pd.date_range("20180101", periods=4), + pd.date_range("20180101", periods=4, tz="US/Eastern"), + pd.timedelta_range("0 days", periods=4), + ], + ids=lambda x: str(x.dtype), + ) + def test_maybe_convert_i8(self, breaks): + # GH 20636 + index = pd.IntervalIndex.from_breaks(breaks) + + # intervalindex + result = index._maybe_convert_i8(index) + expected = pd.IntervalIndex.from_breaks(breaks.asi8) + tm.assert_index_equal(result, expected) + + # interval + interval = pd.Interval(breaks[0], breaks[1]) + result = index._maybe_convert_i8(interval) + expected = pd.Interval(breaks[0]._value, breaks[1]._value) + assert result == expected + + # datetimelike index + result = index._maybe_convert_i8(breaks) + expected = pd.Index(breaks.asi8) + tm.assert_index_equal(result, expected) + + # datetimelike scalar + result = index._maybe_convert_i8(breaks[0]) + expected = breaks[0]._value + assert result == expected + + # list-like of datetimelike scalars + result = index._maybe_convert_i8(list(breaks)) + expected = pd.Index(breaks.asi8) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "breaks", + [ + pd.date_range("2018-01-01", periods=5), + pd.timedelta_range("0 days", periods=5, unit="us"), + ], + ) + def test_maybe_convert_i8_nat(self, breaks): + # GH 20636 + index = pd.IntervalIndex.from_breaks(breaks) + + to_convert = breaks._constructor([pd.NaT] * 3).as_unit("us") + expected = pd.Index([np.nan] * 3, dtype=np.float64) + result = index._maybe_convert_i8(to_convert) + tm.assert_index_equal(result, expected) + + to_convert = to_convert.insert(0, breaks[0]) + expected = expected.insert(0, float(breaks[0]._value)) + result = index._maybe_convert_i8(to_convert) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "make_key", + [lambda breaks: breaks, list], + ids=["lambda", "list"], + ) + def test_maybe_convert_i8_numeric(self, make_key, any_real_numpy_dtype): + # GH 20636 + breaks = np.arange(5, dtype=any_real_numpy_dtype) + index = pd.IntervalIndex.from_breaks(breaks) + key = make_key(breaks) + + result = index._maybe_convert_i8(key) + kind = breaks.dtype.kind + expected_dtype = {"i": np.int64, "u": np.uint64, "f": np.float64}[kind] + expected = pd.Index(key, dtype=expected_dtype) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "make_key", + [ + pd.IntervalIndex.from_breaks, + lambda breaks: pd.Interval(breaks[0], breaks[1]), + lambda breaks: breaks[0], + ], + ids=["IntervalIndex", "Interval", "scalar"], + ) + def test_maybe_convert_i8_numeric_identical(self, make_key, any_real_numpy_dtype): + # GH 20636 + breaks = np.arange(5, dtype=any_real_numpy_dtype) + index = pd.IntervalIndex.from_breaks(breaks) + key = make_key(breaks) + + # test if _maybe_convert_i8 won't change key if an Interval or IntervalIndex + result = index._maybe_convert_i8(key) + assert result is key + + @pytest.mark.parametrize( + "breaks1, breaks2", + list( + permutations( + [ + pd.date_range("20180101", periods=4), + pd.date_range("20180101", periods=4, tz="US/Eastern"), + pd.timedelta_range("0 days", periods=4), + ], + 2, + ) + ), + ids=lambda x: str(x.dtype), + ) + @pytest.mark.parametrize( + "make_key", + [ + pd.IntervalIndex.from_breaks, + lambda breaks: pd.Interval(breaks[0], breaks[1]), + lambda breaks: breaks, + lambda breaks: breaks[0], + list, + ], + ids=["IntervalIndex", "Interval", "Index", "scalar", "list"], + ) + def test_maybe_convert_i8_errors(self, breaks1, breaks2, make_key): + # GH 20636 + index = pd.IntervalIndex.from_breaks(breaks1) + key = make_key(breaks2) + + msg = ( + f"Cannot index an IntervalIndex of subtype {breaks1.dtype} with " + f"values of dtype {breaks2.dtype}" + ) + msg = re.escape(msg) + with pytest.raises(ValueError, match=msg): + index._maybe_convert_i8(key) + + def test_contains_method(self): + # can select values that are IN the range of a value + i = pd.IntervalIndex.from_arrays([0, 1], [1, 2]) + + expected = np.array([False, False], dtype="bool") + actual = i.contains(0) + tm.assert_numpy_array_equal(actual, expected) + actual = i.contains(3) + tm.assert_numpy_array_equal(actual, expected) + + expected = np.array([True, False], dtype="bool") + actual = i.contains(0.5) + tm.assert_numpy_array_equal(actual, expected) + actual = i.contains(1) + tm.assert_numpy_array_equal(actual, expected) + + # __contains__ not implemented for "interval in interval", follow + # that for the contains method for now + with pytest.raises( + NotImplementedError, match="contains not implemented for two" + ): + i.contains(pd.Interval(0, 1)) + + def test_dropna(self, closed): + expected = pd.IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], closed=closed) + + ii = pd.IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], closed=closed) + result = ii.dropna() + tm.assert_index_equal(result, expected) + + ii = pd.IntervalIndex.from_arrays([0, 1, np.nan], [1, 2, np.nan], closed=closed) + result = ii.dropna() + tm.assert_index_equal(result, expected) + + def test_non_contiguous(self, closed): + index = pd.IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed) + target = [0.5, 1.5, 2.5] + actual = index.get_indexer(target) + expected = np.array([0, -1, 1], dtype="intp") + tm.assert_numpy_array_equal(actual, expected) + + assert 1.5 not in index + + def test_isin(self, closed): + index = self.create_index(closed=closed) + + expected = np.array([True] + [False] * (len(index) - 1)) + result = index.isin(index[:1]) + tm.assert_numpy_array_equal(result, expected) + + result = index.isin([index[0]]) + tm.assert_numpy_array_equal(result, expected) + + other = pd.IntervalIndex.from_breaks(np.arange(-2, 10), closed=closed) + expected = np.array([True] * (len(index) - 1) + [False]) + result = index.isin(other) + tm.assert_numpy_array_equal(result, expected) + + result = index.isin(other.tolist()) + tm.assert_numpy_array_equal(result, expected) + + for other_closed in ["right", "left", "both", "neither"]: + other = self.create_index(closed=other_closed) + expected = np.repeat(closed == other_closed, len(index)) + result = index.isin(other) + tm.assert_numpy_array_equal(result, expected) + + result = index.isin(other.tolist()) + tm.assert_numpy_array_equal(result, expected) + + def test_comparison(self): + actual = pd.Interval(0, 1) < self.index + expected = np.array([False, True]) + tm.assert_numpy_array_equal(actual, expected) + + actual = pd.Interval(0.5, 1.5) < self.index + expected = np.array([False, True]) + tm.assert_numpy_array_equal(actual, expected) + actual = self.index > pd.Interval(0.5, 1.5) + tm.assert_numpy_array_equal(actual, expected) + + actual = self.index == self.index + expected = np.array([True, True]) + tm.assert_numpy_array_equal(actual, expected) + actual = self.index <= self.index + tm.assert_numpy_array_equal(actual, expected) + actual = self.index >= self.index + tm.assert_numpy_array_equal(actual, expected) + + actual = self.index < self.index + expected = np.array([False, False]) + tm.assert_numpy_array_equal(actual, expected) + actual = self.index > self.index + tm.assert_numpy_array_equal(actual, expected) + + actual = self.index == pd.IntervalIndex.from_breaks([0, 1, 2], "left") + tm.assert_numpy_array_equal(actual, expected) + + actual = self.index == self.index.values + tm.assert_numpy_array_equal(actual, np.array([True, True])) + actual = self.index.values == self.index + tm.assert_numpy_array_equal(actual, np.array([True, True])) + actual = self.index <= self.index.values + tm.assert_numpy_array_equal(actual, np.array([True, True])) + actual = self.index != self.index.values + tm.assert_numpy_array_equal(actual, np.array([False, False])) + actual = self.index > self.index.values + tm.assert_numpy_array_equal(actual, np.array([False, False])) + actual = self.index.values > self.index + tm.assert_numpy_array_equal(actual, np.array([False, False])) + + # invalid comparisons + actual = self.index == 0 + tm.assert_numpy_array_equal(actual, np.array([False, False])) + actual = self.index == self.index.left + tm.assert_numpy_array_equal(actual, np.array([False, False])) + + msg = "|".join( + [ + "not supported between instances of 'int' and '.*.Interval'", + r"Invalid comparison between dtype=interval\[int64, right\] and ", + ] + ) + with pytest.raises(TypeError, match=msg): + self.index > 0 + with pytest.raises(TypeError, match=msg): + self.index <= 0 + with pytest.raises(TypeError, match=msg): + self.index > np.arange(2) + + msg = "Lengths must match to compare" + with pytest.raises(ValueError, match=msg): + self.index > np.arange(3) + + def test_missing_values(self, closed): + idx = pd.Index( + [np.nan, pd.Interval(0, 1, closed=closed), pd.Interval(1, 2, closed=closed)] + ) + idx2 = pd.IntervalIndex.from_arrays( + [np.nan, 0, 1], [np.nan, 1, 2], closed=closed + ) + assert idx.equals(idx2) + + msg = ( + "missing values must be missing in the same location both left " + "and right sides" + ) + with pytest.raises(ValueError, match=msg): + pd.IntervalIndex.from_arrays( + [np.nan, 0, 1], np.array([0, 1, 2]), closed=closed + ) + + tm.assert_numpy_array_equal(pd.isna(idx), np.array([True, False, False])) + + def test_sort_values(self, closed): + index = self.create_index(closed=closed) + + result = index.sort_values() + tm.assert_index_equal(result, index) + + result = index.sort_values(ascending=False) + tm.assert_index_equal(result, index[::-1]) + + # with nan + index = pd.IntervalIndex([pd.Interval(1, 2), np.nan, pd.Interval(0, 1)]) + + result = index.sort_values() + expected = pd.IntervalIndex([pd.Interval(0, 1), pd.Interval(1, 2), np.nan]) + tm.assert_index_equal(result, expected) + + result = index.sort_values(ascending=False, na_position="first") + expected = pd.IntervalIndex([np.nan, pd.Interval(1, 2), pd.Interval(0, 1)]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + def test_datetime(self, tz): + start = pd.Timestamp("2000-01-01", tz=tz) + dates = pd.date_range(start=start, periods=10) + index = pd.IntervalIndex.from_breaks(dates) + + # test mid + start = pd.Timestamp("2000-01-01T12:00", tz=tz) + expected = pd.date_range(start=start, periods=9) + tm.assert_index_equal(index.mid, expected, check_freq=False) + + # __contains__ doesn't check individual points + assert pd.Timestamp("2000-01-01", tz=tz) not in index + assert pd.Timestamp("2000-01-01T12", tz=tz) not in index + assert pd.Timestamp("2000-01-02", tz=tz) not in index + iv_true = pd.Interval( + pd.Timestamp("2000-01-02", tz=tz), pd.Timestamp("2000-01-03", tz=tz) + ) + iv_false = pd.Interval( + pd.Timestamp("1999-12-31", tz=tz), pd.Timestamp("2000-01-01", tz=tz) + ) + assert iv_true in index + assert iv_false not in index + + # .contains does check individual points + assert not index.contains(pd.Timestamp("2000-01-01", tz=tz)).any() + assert index.contains(pd.Timestamp("2000-01-01T12", tz=tz)).any() + assert index.contains(pd.Timestamp("2000-01-02", tz=tz)).any() + + # test get_indexer + start = pd.Timestamp("1999-12-31T12:00", tz=tz) + target = pd.date_range(start=start, periods=7, freq="12h") + actual = index.get_indexer(target) + expected = np.array([-1, -1, 0, 0, 1, 1, 2], dtype="intp") + tm.assert_numpy_array_equal(actual, expected) + + start = pd.Timestamp("2000-01-08T18:00", tz=tz) + target = pd.date_range(start=start, periods=7, freq="6h") + actual = index.get_indexer(target) + expected = np.array([7, 7, 8, 8, 8, 8, -1], dtype="intp") + tm.assert_numpy_array_equal(actual, expected) + + def test_append(self, closed): + index1 = pd.IntervalIndex.from_arrays([0, 1], [1, 2], closed=closed) + index2 = pd.IntervalIndex.from_arrays([1, 2], [2, 3], closed=closed) + + result = index1.append(index2) + expected = pd.IntervalIndex.from_arrays( + [0, 1, 1, 2], [1, 2, 2, 3], closed=closed + ) + tm.assert_index_equal(result, expected) + + result = index1.append([index1, index2]) + expected = pd.IntervalIndex.from_arrays( + [0, 1, 0, 1, 1, 2], [1, 2, 1, 2, 2, 3], closed=closed + ) + tm.assert_index_equal(result, expected) + + for other_closed in {"left", "right", "both", "neither"} - {closed}: + index_other_closed = pd.IntervalIndex.from_arrays( + [0, 1], [1, 2], closed=other_closed + ) + result = index1.append(index_other_closed) + expected = index1.astype(object).append(index_other_closed.astype(object)) + tm.assert_index_equal(result, expected) + + def test_is_non_overlapping_monotonic(self, closed): + # Should be True in all cases + tpls = [(0, 1), (2, 3), (4, 5), (6, 7)] + idx = pd.IntervalIndex.from_tuples(tpls, closed=closed) + assert idx.is_non_overlapping_monotonic is True + + idx = pd.IntervalIndex.from_tuples(tpls[::-1], closed=closed) + assert idx.is_non_overlapping_monotonic is True + + # Should be False in all cases (overlapping) + tpls = [(0, 2), (1, 3), (4, 5), (6, 7)] + idx = pd.IntervalIndex.from_tuples(tpls, closed=closed) + assert idx.is_non_overlapping_monotonic is False + + idx = pd.IntervalIndex.from_tuples(tpls[::-1], closed=closed) + assert idx.is_non_overlapping_monotonic is False + + # Should be False in all cases (non-monotonic) + tpls = [(0, 1), (2, 3), (6, 7), (4, 5)] + idx = pd.IntervalIndex.from_tuples(tpls, closed=closed) + assert idx.is_non_overlapping_monotonic is False + + idx = pd.IntervalIndex.from_tuples(tpls[::-1], closed=closed) + assert idx.is_non_overlapping_monotonic is False + + # Should be False for closed='both', otherwise True (GH16560) + if closed == "both": + idx = pd.IntervalIndex.from_breaks(range(4), closed=closed) + assert idx.is_non_overlapping_monotonic is False + else: + idx = pd.IntervalIndex.from_breaks(range(4), closed=closed) + assert idx.is_non_overlapping_monotonic is True + + @pytest.mark.parametrize( + "start, shift, na_value", + [ + (0, 1, np.nan), + (pd.Timestamp("2018-01-01"), pd.Timedelta("1 day"), pd.NaT), + (pd.Timedelta("0 days"), pd.Timedelta("1 day"), pd.NaT), + ], + ) + def test_is_overlapping(self, start, shift, na_value, closed): + # GH 23309 + # see test_interval_tree.py for extensive tests; interface tests here + + # non-overlapping + tuples = [(start + n * shift, start + (n + 1) * shift) for n in (0, 2, 4)] + index = pd.IntervalIndex.from_tuples(tuples, closed=closed) + assert index.is_overlapping is False + + # non-overlapping with NA + tuples = [(na_value, na_value), *tuples, (na_value, na_value)] + index = pd.IntervalIndex.from_tuples(tuples, closed=closed) + assert index.is_overlapping is False + + # overlapping + tuples = [(start + n * shift, start + (n + 2) * shift) for n in range(3)] + index = pd.IntervalIndex.from_tuples(tuples, closed=closed) + assert index.is_overlapping is True + + # overlapping with NA + tuples = [(na_value, na_value), *tuples, (na_value, na_value)] + index = pd.IntervalIndex.from_tuples(tuples, closed=closed) + assert index.is_overlapping is True + + # common endpoints + tuples = [(start + n * shift, start + (n + 1) * shift) for n in range(3)] + index = pd.IntervalIndex.from_tuples(tuples, closed=closed) + result = index.is_overlapping + expected = closed == "both" + assert result is expected + + # common endpoints with NA + tuples = [(na_value, na_value), *tuples, (na_value, na_value)] + index = pd.IntervalIndex.from_tuples(tuples, closed=closed) + result = index.is_overlapping + assert result is expected + + # intervals with duplicate left values + a = [10, 15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85] + b = [15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90] + index = pd.IntervalIndex.from_arrays(a, b, closed="right") + result = index.is_overlapping + assert result is False + + @pytest.mark.parametrize( + "tuples", + [ + zip(range(10), range(1, 11), strict=True), + zip( + pd.date_range("20170101", periods=10), + pd.date_range("20170101", periods=10), + strict=True, + ), + zip( + pd.timedelta_range("0 days", periods=10), + pd.timedelta_range("1 day", periods=10), + strict=True, + ), + ], + ) + def test_to_tuples(self, tuples): + # GH 18756 + tuples = list(tuples) + idx = pd.IntervalIndex.from_tuples(tuples) + result = idx.to_tuples() + expected = pd.Index(com.asarray_tuplesafe(tuples)) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "tuples", + [ + [*list(zip(range(10), range(1, 11), strict=True)), np.nan], + [ + *list( + zip( + pd.date_range("20170101", periods=10), + pd.date_range("20170101", periods=10), + strict=True, + ) + ), + np.nan, + ], + [ + *list( + zip( + pd.timedelta_range("0 days", periods=10), + pd.timedelta_range("1 day", periods=10), + strict=True, + ) + ), + np.nan, + ], + ], + ) + @pytest.mark.parametrize("na_tuple", [True, False]) + def test_to_tuples_na(self, tuples, na_tuple): + # GH 18756 + idx = pd.IntervalIndex.from_tuples(tuples) + result = idx.to_tuples(na_tuple=na_tuple) + + # check the non-NA portion + expected_notna = pd.Index(com.asarray_tuplesafe(tuples[:-1])) + result_notna = result[:-1] + tm.assert_index_equal(result_notna, expected_notna) + + # check the NA portion + result_na = result[-1] + if na_tuple: + assert isinstance(result_na, tuple) + assert len(result_na) == 2 + assert all(pd.isna(x) for x in result_na) + else: + assert pd.isna(result_na) + + def test_nbytes(self): + # GH 19209 + left = np.arange(0, 4, dtype="i8") + right = np.arange(1, 5, dtype="i8") + + result = pd.IntervalIndex.from_arrays(left, right).nbytes + expected = 64 # 4 * 8 * 2 + assert result == expected + + @pytest.mark.parametrize("name", [None, "foo"]) + def test_set_closed(self, name, closed, other_closed): + # GH 21670 + index = pd.interval_range(0, 5, closed=closed, name=name) + result = index.set_closed(other_closed) + expected = pd.interval_range(0, 5, closed=other_closed, name=name) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("bad_closed", ["foo", 10, "LEFT", True, False]) + def test_set_closed_errors(self, bad_closed): + # GH 21670 + index = pd.interval_range(0, 5) + msg = f"invalid option for 'closed': {bad_closed}" + with pytest.raises(ValueError, match=msg): + index.set_closed(bad_closed) + + def test_is_all_dates(self): + # GH 23576 + year_2017 = pd.Interval( + pd.Timestamp("2017-01-01 00:00:00"), pd.Timestamp("2018-01-01 00:00:00") + ) + year_2017_index = pd.IntervalIndex([year_2017]) + assert not year_2017_index._is_all_dates + + +def test_from_arrays_mismatched_signedness_raises(): + # GH 55715 + left = np.array([0, 1, 2], dtype="int64") + right = np.array([1, 2, 3], dtype="uint64") + with pytest.raises(TypeError, match="matching signedness"): + pd.IntervalIndex.from_arrays(left, right) + + +@pytest.mark.parametrize( + "left, right", + [ + # right overflows int64 -> right.dtype becomes object + pytest.param([0], [2**64], id="right-overflows"), + # left overflows int64 -> left.dtype becomes object (mirror case, + # already raised before this fix; kept here so both sides are + # covered by the same parametrization) + pytest.param([-(2**64)], [0], id="left-overflows"), + ], +) +def test_interval_index_endpoint_dtype_mismatch_raises(left, right): + # GH 66518 + msg = "category, object, and string subtypes are not supported for IntervalIndex" + with pytest.raises(TypeError, match=msg): + pd.IntervalIndex.from_arrays(left, right) + + +def test_dir(): + # GH#27571 dir(interval_index) should not raise + index = pd.IntervalIndex.from_arrays([0, 1], [1, 2]) + result = dir(index) + assert "str" not in result + + +def test_searchsorted_different_argument_classes(listlike_box): + # https://github.com/pandas-dev/pandas/issues/32762 + values = pd.IntervalIndex([pd.Interval(0, 1), pd.Interval(1, 2)]) + result = values.searchsorted(listlike_box(values)) + expected = np.array([0, 1], dtype=result.dtype) + tm.assert_numpy_array_equal(result, expected) + + result = values._data.searchsorted(listlike_box(values)) + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize( + "arg", [[1, 2], ["a", "b"], [pd.Timestamp("2020-01-01", tz="Europe/London")] * 2] +) +def test_searchsorted_invalid_argument(arg): + values = pd.IntervalIndex([pd.Interval(0, 1), pd.Interval(1, 2)]) + msg = "'<' not supported between instances of 'pandas._libs.interval.Interval' and " + with pytest.raises(TypeError, match=msg): + values.searchsorted(arg) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_interval_range.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_interval_range.py new file mode 100644 index 0000000000000000000000000000000000000000..cc9e6c8034b3ebcb1d0b71dd085a61d68cf79a57 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_interval_range.py @@ -0,0 +1,392 @@ +from datetime import timedelta + +import numpy as np +import pytest + +from pandas.core.dtypes.common import is_integer + +import pandas as pd +import pandas._testing as tm + +from pandas.tseries.offsets import Day + + +@pytest.fixture(params=[None, "foo"]) +def name(request): + return request.param + + +class TestIntervalRange: + @pytest.mark.parametrize("freq, periods", [(1, 100), (2.5, 40), (5, 20), (25, 4)]) + def test_constructor_numeric(self, closed, name, freq, periods): + start, end = 0, 100 + breaks = np.arange(101, step=freq) + if breaks.dtype.kind == "f": + breaks = breaks.astype(np.float64) + else: + breaks = breaks.astype(np.int64) + expected = pd.IntervalIndex.from_breaks(breaks, name=name, closed=closed) + + # defined from start/end/freq + result = pd.interval_range( + start=start, end=end, freq=freq, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + # defined from start/periods/freq + result = pd.interval_range( + start=start, periods=periods, freq=freq, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + # defined from end/periods/freq + result = pd.interval_range( + end=end, periods=periods, freq=freq, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + # GH 20976: linspace behavior defined from start/end/periods + result = pd.interval_range( + start=start, end=end, periods=periods, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + @pytest.mark.parametrize( + "freq, periods", [("D", 364), ("2D", 182), ("22D18h", 16), ("ME", 11)] + ) + def test_constructor_timestamp(self, closed, name, freq, periods, tz): + start, end = pd.Timestamp("20180101", tz=tz), pd.Timestamp("20181231", tz=tz) + breaks = pd.date_range(start=start, end=end, freq=freq) + expected = pd.IntervalIndex.from_breaks(breaks, name=name, closed=closed) + + # defined from start/end/freq + result = pd.interval_range( + start=start, end=end, freq=freq, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + # defined from start/periods/freq + result = pd.interval_range( + start=start, periods=periods, freq=freq, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + # defined from end/periods/freq + result = pd.interval_range( + end=end, periods=periods, freq=freq, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + # GH 20976: linspace behavior defined from start/end/periods + if not breaks.freq.n == 1 and tz is None: + result = pd.interval_range( + start=start, end=end, periods=periods, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "freq, periods", [("D", 100), ("2D12h", 40), ("5D", 20), ("25D", 4)] + ) + def test_constructor_timedelta(self, closed, name, freq, periods): + start, end = pd.Timedelta("0 days"), pd.Timedelta("100 days") + breaks = pd.timedelta_range(start=start, end=end, freq=freq) + expected = pd.IntervalIndex.from_breaks(breaks, name=name, closed=closed) + + # defined from start/end/freq + result = pd.interval_range( + start=start, end=end, freq=freq, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + # defined from start/periods/freq + result = pd.interval_range( + start=start, periods=periods, freq=freq, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + # defined from end/periods/freq + result = pd.interval_range( + end=end, periods=periods, freq=freq, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + # GH 20976: linspace behavior defined from start/end/periods + result = pd.interval_range( + start=start, end=end, periods=periods, name=name, closed=closed + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "start, end, freq, expected_endpoint", + [ + (0, 10, 3, 9), + (0, 10, 1.5, 9), + (0.5, 10, 3, 9.5), + (pd.Timedelta("0D"), pd.Timedelta("10D"), "2D4h", pd.Timedelta("8D16h")), + ( + pd.Timestamp("2018-01-01"), + pd.Timestamp("2018-02-09"), + "MS", + pd.Timestamp("2018-02-01"), + ), + ( + pd.Timestamp("2018-01-01", tz="US/Eastern"), + pd.Timestamp("2018-01-20", tz="US/Eastern"), + "5D12h", + pd.Timestamp("2018-01-17 12:00:00", tz="US/Eastern"), + ), + ], + ) + def test_early_truncation(self, start, end, freq, expected_endpoint): + # index truncates early if freq causes end to be skipped + result = pd.interval_range(start=start, end=end, freq=freq) + result_endpoint = result.right[-1] + assert result_endpoint == expected_endpoint + + @pytest.mark.parametrize( + "start, end, freq", + [(0.5, None, None), (None, 4.5, None), (0.5, None, 1.5), (None, 6.5, 1.5)], + ) + def test_no_invalid_float_truncation(self, start, end, freq): + # GH 21161 + if freq is None: + breaks = [0.5, 1.5, 2.5, 3.5, 4.5] + else: + breaks = [0.5, 2.0, 3.5, 5.0, 6.5] + expected = pd.IntervalIndex.from_breaks(breaks) + + result = pd.interval_range(start=start, end=end, periods=4, freq=freq) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "start, mid, end", + [ + ( + pd.Timestamp("2018-03-10", tz="US/Eastern"), + pd.Timestamp("2018-03-10 23:30:00", tz="US/Eastern"), + pd.Timestamp("2018-03-12", tz="US/Eastern"), + ), + ( + pd.Timestamp("2018-11-03", tz="US/Eastern"), + pd.Timestamp("2018-11-04 00:30:00", tz="US/Eastern"), + pd.Timestamp("2018-11-05", tz="US/Eastern"), + ), + ], + ) + def test_linspace_dst_transition(self, start, mid, end): + # GH 20976: linspace behavior defined from start/end/periods + # accounts for the hour gained/lost during DST transition + start = start.as_unit("ns") + mid = mid.as_unit("ns") + end = end.as_unit("ns") + result = pd.interval_range(start=start, end=end, periods=2) + expected = pd.IntervalIndex.from_breaks([start, mid, end]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("freq", [2, 2.0]) + @pytest.mark.parametrize("end", [10, 10.0]) + @pytest.mark.parametrize("start", [0, 0.0]) + def test_float_subtype(self, start, end, freq): + # Has float subtype if any of start/end/freq are float, even if all + # resulting endpoints can safely be upcast to integers + + # defined from start/end/freq + index = pd.interval_range(start=start, end=end, freq=freq) + result = index.dtype.subtype + expected = "int64" if is_integer(start + end + freq) else "float64" + assert result == expected + + # defined from start/periods/freq + index = pd.interval_range(start=start, periods=5, freq=freq) + result = index.dtype.subtype + expected = "int64" if is_integer(start + freq) else "float64" + assert result == expected + + # defined from end/periods/freq + index = pd.interval_range(end=end, periods=5, freq=freq) + result = index.dtype.subtype + expected = "int64" if is_integer(end + freq) else "float64" + assert result == expected + + # GH 20976: linspace behavior defined from start/end/periods + index = pd.interval_range(start=start, end=end, periods=5) + result = index.dtype.subtype + expected = "int64" if is_integer(start + end) else "float64" + assert result == expected + + @pytest.mark.parametrize( + "start, end, expected", + [ + (np.int8(1), np.int8(10), np.dtype("int8")), + (np.int8(1), np.float16(10), np.dtype("float64")), + (np.float32(1), np.float32(10), np.dtype("float32")), + (1, 10, np.dtype("int64")), + (1, 10.0, np.dtype("float64")), + ], + ) + def test_interval_dtype(self, start, end, expected): + result = pd.interval_range(start=start, end=end).dtype.subtype + assert result == expected + + def test_interval_range_fractional_period(self): + # float value for periods + msg = "periods must be an integer, got 10.5" + ts = pd.Timestamp("2024-03-25") + with pytest.raises(TypeError, match=msg): + pd.interval_range(ts, periods=10.5) + + def test_constructor_coverage(self): + # equivalent timestamp-like start/end + start, end = pd.Timestamp("2017-01-01"), pd.Timestamp("2017-01-15") + expected = pd.interval_range(start=start, end=end) + + result = pd.interval_range(start=start.to_pydatetime(), end=end.to_pydatetime()) + tm.assert_index_equal(result, expected) + + result = pd.interval_range(start=start.asm8, end=end.asm8) + tm.assert_index_equal(result, expected) + + # equivalent freq with timestamp + equiv_freq = [ + "D", + Day(), + pd.Timedelta(days=1), + timedelta(days=1), + pd.DateOffset(days=1), + ] + for freq in equiv_freq: + result = pd.interval_range(start=start, end=end, freq=freq) + tm.assert_index_equal(result, expected) + + # equivalent timedelta-like start/end + start, end = ( + pd.Timedelta(days=1).as_unit("us"), + pd.Timedelta(days=10).as_unit("us"), + ) + expected = pd.interval_range(start=start, end=end) + + result = pd.interval_range( + start=start.to_pytimedelta(), end=end.to_pytimedelta() + ) + tm.assert_index_equal(result, expected) + + result = pd.interval_range(start=start.asm8, end=end.asm8) + tm.assert_index_equal(result, expected) + + # equivalent freq with timedelta + equiv_freq = ["D", Day(), pd.Timedelta(days=1), timedelta(days=1)] + for freq in equiv_freq: + result = pd.interval_range(start=start, end=end, freq=freq) + tm.assert_index_equal(result, expected) + + def test_errors(self): + # not enough params + msg = ( + "Of the four parameters: start, end, periods, and freq, " + "exactly three must be specified" + ) + + with pytest.raises(ValueError, match=msg): + pd.interval_range(start=0) + + with pytest.raises(ValueError, match=msg): + pd.interval_range(end=5) + + with pytest.raises(ValueError, match=msg): + pd.interval_range(periods=2) + + with pytest.raises(ValueError, match=msg): + pd.interval_range() + + # too many params + with pytest.raises(ValueError, match=msg): + pd.interval_range(start=0, end=5, periods=6, freq=1.5) + + # mixed units + msg = "start, end, freq need to be type compatible" + with pytest.raises(TypeError, match=msg): + pd.interval_range(start=0, end=pd.Timestamp("20130101"), freq=2) + + with pytest.raises(TypeError, match=msg): + pd.interval_range(start=0, end=pd.Timedelta("1 day"), freq=2) + + with pytest.raises(TypeError, match=msg): + pd.interval_range(start=0, end=10, freq="D") + + with pytest.raises(TypeError, match=msg): + pd.interval_range(start=pd.Timestamp("20130101"), end=10, freq="D") + + with pytest.raises(TypeError, match=msg): + pd.interval_range( + start=pd.Timestamp("20130101"), end=pd.Timedelta("1 day"), freq="D" + ) + + with pytest.raises(TypeError, match=msg): + pd.interval_range( + start=pd.Timestamp("20130101"), end=pd.Timestamp("20130110"), freq=2 + ) + + with pytest.raises(TypeError, match=msg): + pd.interval_range(start=pd.Timedelta("1 day"), end=10, freq="D") + + with pytest.raises(TypeError, match=msg): + pd.interval_range( + start=pd.Timedelta("1 day"), end=pd.Timestamp("20130110"), freq="D" + ) + + with pytest.raises(TypeError, match=msg): + pd.interval_range( + start=pd.Timedelta("1 day"), end=pd.Timedelta("10 days"), freq=2 + ) + + # invalid periods + msg = "periods must be an integer, got foo" + with pytest.raises(TypeError, match=msg): + pd.interval_range(start=0, periods="foo") + + # invalid start + msg = "start must be numeric or datetime-like, got foo" + with pytest.raises(ValueError, match=msg): + pd.interval_range(start="foo", periods=10) + + # invalid end + msg = r"end must be numeric or datetime-like, got \(0, 1\]" + with pytest.raises(ValueError, match=msg): + pd.interval_range(end=pd.Interval(0, 1), periods=10) + + # invalid freq for datetime-like + msg = "freq must be numeric or convertible to DateOffset, got foo" + with pytest.raises(ValueError, match=msg): + pd.interval_range(start=0, end=10, freq="foo") + + with pytest.raises(ValueError, match=msg): + pd.interval_range(start=pd.Timestamp("20130101"), periods=10, freq="foo") + + with pytest.raises(ValueError, match=msg): + pd.interval_range(end=pd.Timedelta("1 day"), periods=10, freq="foo") + + # mixed tz + start = pd.Timestamp("2017-01-01", tz="US/Eastern") + end = pd.Timestamp("2017-01-07", tz="US/Pacific") + msg = "Start and end cannot both be tz-aware with different timezones" + with pytest.raises(TypeError, match=msg): + pd.interval_range(start=start, end=end) + + def test_float_freq(self): + # GH 54477 + result = pd.interval_range(0, 1, freq=0.1) + expected = pd.IntervalIndex.from_breaks([0 + 0.1 * n for n in range(11)]) + tm.assert_index_equal(result, expected) + + result = pd.interval_range(0, 1, freq=0.6) + expected = pd.IntervalIndex.from_breaks([0, 0.6]) + tm.assert_index_equal(result, expected) + + def test_interval_range_float32_start_int_freq(self): + # GH 58964 + result = pd.interval_range(start=np.float32(0), end=2, freq=1) + expected = pd.IntervalIndex.from_tuples( + [(0.0, 1.0), (1.0, 2.0)], dtype="interval[float64, right]" + ) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_interval_tree.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_interval_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..06d08f25109bab914a66a0a7a24cd717339f9758 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_interval_tree.py @@ -0,0 +1,212 @@ +from itertools import permutations + +import numpy as np +import pytest + +from pandas._libs.interval import IntervalTree + +import pandas._testing as tm + + +@pytest.fixture(params=[1, 2, 10]) +def leaf_size(request): + """ + Fixture to specify IntervalTree leaf_size parameter; to be used with the + tree fixture. + """ + return request.param + + +@pytest.fixture( + params=[ + np.arange(5, dtype="int64"), + np.arange(5, dtype="uint64"), + np.arange(5, dtype="float64"), + np.array([0, 1, 2, 3, 4, np.nan], dtype="float64"), + ] +) +def tree(request, leaf_size): + left = request.param + return IntervalTree(left, left + 2, leaf_size=leaf_size) + + +class TestIntervalTree: + def test_get_indexer(self, tree): + result = tree.get_indexer(np.array([1.0, 5.5, 6.5])) + expected = np.array([0, 4, -1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + with pytest.raises( + KeyError, match="'indexer does not intersect a unique set of intervals'" + ): + tree.get_indexer(np.array([3.0])) + + @pytest.mark.parametrize( + "dtype, target_value, target_dtype", + [("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")], + ) + def test_get_indexer_overflow(self, dtype, target_value, target_dtype): + left, right = np.array([0, 1], dtype=dtype), np.array([1, 2], dtype=dtype) + tree = IntervalTree(left, right) + + result = tree.get_indexer(np.array([target_value], dtype=target_dtype)) + expected = np.array([-1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_non_unique(self, tree): + indexer, missing = tree.get_indexer_non_unique(np.array([1.0, 2.0, 6.5])) + + result = indexer[:1] + expected = np.array([0], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + result = np.sort(indexer[1:3]) + expected = np.array([0, 1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + result = np.sort(indexer[3:]) + expected = np.array([-1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + result = missing + expected = np.array([2], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "dtype, target_value, target_dtype", + [("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")], + ) + def test_get_indexer_non_unique_overflow(self, dtype, target_value, target_dtype): + left, right = np.array([0, 2], dtype=dtype), np.array([1, 3], dtype=dtype) + tree = IntervalTree(left, right) + target = np.array([target_value], dtype=target_dtype) + + result_indexer, result_missing = tree.get_indexer_non_unique(target) + expected_indexer = np.array([-1], dtype="intp") + tm.assert_numpy_array_equal(result_indexer, expected_indexer) + + expected_missing = np.array([0], dtype="intp") + tm.assert_numpy_array_equal(result_missing, expected_missing) + + @pytest.mark.parametrize("dtype", ["int64", "float64", "uint64"]) + def test_duplicates(self, dtype): + left = np.array([0, 0, 0], dtype=dtype) + tree = IntervalTree(left, left + 1) + + with pytest.raises( + KeyError, match="'indexer does not intersect a unique set of intervals'" + ): + tree.get_indexer(np.array([0.5])) + + indexer, missing = tree.get_indexer_non_unique(np.array([0.5])) + result = np.sort(indexer) + expected = np.array([0, 1, 2], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + result = missing + expected = np.array([], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("leaf_size", [1, 10, 100, 10000]) + def test_get_indexer_closed(self, closed, leaf_size): + x = np.arange(1000, dtype="float64") + found = x.astype("intp") + not_found = (-1 * np.ones(1000)).astype("intp") + + tree = IntervalTree(x, x + 0.5, closed=closed, leaf_size=leaf_size) + tm.assert_numpy_array_equal(found, tree.get_indexer(x + 0.25)) + + expected = found if tree.closed_left else not_found + tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.0)) + + expected = found if tree.closed_right else not_found + tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.5)) + + @pytest.mark.parametrize( + "left, right, expected", + [ + (np.array([0, 1, 4], dtype="int64"), np.array([2, 3, 5]), True), + (np.array([0, 1, 2], dtype="int64"), np.array([5, 4, 3]), True), + (np.array([0, 1, np.nan]), np.array([5, 4, np.nan]), True), + (np.array([0, 2, 4], dtype="int64"), np.array([1, 3, 5]), False), + (np.array([0, 2, np.nan]), np.array([1, 3, np.nan]), False), + ], + ) + @pytest.mark.parametrize("order", [list(x) for x in permutations(range(3))]) + def test_is_overlapping(self, closed, order, left, right, expected): + # GH 23309 + tree = IntervalTree(left[order], right[order], closed=closed) + result = tree.is_overlapping + assert result is expected + + @pytest.mark.parametrize("order", [list(x) for x in permutations(range(3))]) + def test_is_overlapping_endpoints(self, closed, order): + """shared endpoints are marked as overlapping""" + # GH 23309 + left, right = np.arange(3, dtype="int64"), np.arange(1, 4) + tree = IntervalTree(left[order], right[order], closed=closed) + result = tree.is_overlapping + expected = closed == "both" + assert result is expected + + @pytest.mark.parametrize( + "left, right", + [ + (np.array([], dtype="int64"), np.array([], dtype="int64")), + (np.array([0], dtype="int64"), np.array([1], dtype="int64")), + (np.array([np.nan]), np.array([np.nan])), + (np.array([np.nan] * 3), np.array([np.nan] * 3)), + ], + ) + def test_is_overlapping_trivial(self, closed, left, right): + # GH 23309 + tree = IntervalTree(left, right, closed=closed) + assert tree.is_overlapping is False + + def test_construction_overflow(self): + # GH 25485 + left, right = np.arange(101, dtype="int64"), [np.iinfo(np.int64).max] * 101 + tree = IntervalTree(left, right) + + # pivot should be average of left/right medians + result = tree.root.pivot + expected = (50 + np.iinfo(np.int64).max) / 2 + assert result == expected + + @pytest.mark.parametrize( + "left, right, expected", + [ + ([-np.inf, 1.0], [1.0, 2.0], 0.0), + ([-np.inf, -2.0], [-2.0, -1.0], -2.0), + ([-2.0, -1.0], [-1.0, np.inf], 0.0), + ([1.0, 2.0], [2.0, np.inf], 2.0), + ], + ) + def test_inf_bound_infinite_recursion(self, left, right, expected): + # GH 46658 + + tree = IntervalTree(left * 101, right * 101) + + result = tree.root.pivot + assert result == expected + + +@pytest.mark.parametrize("closed", ["left", "right", "neither"]) +@pytest.mark.parametrize("order", [list(x) for x in permutations(range(3))]) +def test_is_overlapping_empty_interval(closed, order): + # GH#26893 an empty interval contains no points, so nesting one inside + # another interval is not an overlap + left = np.array([0, 1, 5], dtype="int64") + right = np.array([3, 1, 6], dtype="int64") + tree = IntervalTree(left[order], right[order], closed=closed) + assert tree.is_overlapping is False + + +@pytest.mark.parametrize("closed", ["left", "right", "neither"]) +def test_is_overlapping_empty_interval_hides_overlap(closed): + # GH#26893 dropping the empty interval must not hide the overlap between + # the two intervals it sits between + left = np.array([0, 1, 2], dtype="int64") + right = np.array([3, 1, 4], dtype="int64") + tree = IntervalTree(left, right, closed=closed) + assert tree.is_overlapping is True diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_join.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..b1034139b6e4a13f62d56334df95cb3b00ca5728 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_join.py @@ -0,0 +1,40 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def range_index(): + return pd.RangeIndex(3, name="range_index") + + +@pytest.fixture +def interval_index(): + return pd.IntervalIndex.from_tuples( + [(0.0, 1.0), (1.0, 2.0), (1.5, 2.5)], name="interval_index" + ) + + +def test_join_overlapping_in_mi_to_same_intervalindex(range_index, interval_index): + # GH-45661 + multi_index = pd.MultiIndex.from_product([interval_index, range_index]) + result = multi_index.join(interval_index) + + tm.assert_index_equal(result, multi_index) + + +def test_join_overlapping_to_multiindex_with_same_interval(range_index, interval_index): + # GH-45661 + multi_index = pd.MultiIndex.from_product([interval_index, range_index]) + result = interval_index.join(multi_index) + + tm.assert_index_equal(result, multi_index) + + +def test_join_overlapping_interval_to_another_intervalindex(interval_index): + # GH-45661 + flipped_interval_index = interval_index[::-1] + result = interval_index.join(flipped_interval_index) + + tm.assert_index_equal(result, interval_index) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_pickle.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..66748ef3f76a7f044e8f213e635e7ed159409642 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_pickle.py @@ -0,0 +1,10 @@ +import pandas as pd +import pandas._testing as tm + + +class TestPickle: + def test_pickle_round_trip_closed(self, closed, temp_file): + # https://github.com/pandas-dev/pandas/issues/35658 + idx = pd.IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed) + result = tm.round_trip_pickle(idx, temp_file) + tm.assert_index_equal(result, idx) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_setops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..e4784149778899eb723d94482b1767bea48f9f1c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/interval/test_setops.py @@ -0,0 +1,205 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def monotonic_index(start, end, dtype="int64", closed="right"): + return pd.IntervalIndex.from_breaks( + np.arange(start, end, dtype=dtype), closed=closed + ) + + +def empty_index(dtype="int64", closed="right"): + return pd.IntervalIndex(np.array([], dtype=dtype), closed=closed) + + +class TestIntervalIndex: + def test_union(self, closed, sort): + index = monotonic_index(0, 11, closed=closed) + other = monotonic_index(5, 13, closed=closed) + + expected = monotonic_index(0, 13, closed=closed) + result = index[::-1].union(other, sort=sort) + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + + result = other[::-1].union(index, sort=sort) + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + + tm.assert_index_equal(index.union(index, sort=sort), index) + tm.assert_index_equal(index.union(index[:1], sort=sort), index) + + def test_union_empty_result(self, closed, sort): + # GH 19101: empty result, same dtype + index = empty_index(dtype="int64", closed=closed) + result = index.union(index, sort=sort) + tm.assert_index_equal(result, index) + + # GH 19101: empty result, different numeric dtypes -> common dtype is f8 + other = empty_index(dtype="float64", closed=closed) + result = index.union(other, sort=sort) + expected = other + tm.assert_index_equal(result, expected) + + other = index.union(index, sort=sort) + tm.assert_index_equal(result, expected) + + other = empty_index(dtype="uint64", closed=closed) + result = index.union(other, sort=sort) + tm.assert_index_equal(result, expected) + + result = other.union(index, sort=sort) + tm.assert_index_equal(result, expected) + + def test_intersection(self, closed, sort): + index = monotonic_index(0, 11, closed=closed) + other = monotonic_index(5, 13, closed=closed) + + expected = monotonic_index(5, 11, closed=closed) + result = index[::-1].intersection(other, sort=sort) + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + + result = other[::-1].intersection(index, sort=sort) + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + + tm.assert_index_equal(index.intersection(index, sort=sort), index) + + # GH 26225: nested intervals + index = pd.IntervalIndex.from_tuples([(1, 2), (1, 3), (1, 4), (0, 2)]) + other = pd.IntervalIndex.from_tuples([(1, 2), (1, 3)]) + expected = pd.IntervalIndex.from_tuples([(1, 2), (1, 3)]) + result = index.intersection(other) + tm.assert_index_equal(result, expected) + + # GH 26225 + index = pd.IntervalIndex.from_tuples([(0, 3), (0, 2)]) + other = pd.IntervalIndex.from_tuples([(0, 2), (1, 3)]) + expected = pd.IntervalIndex.from_tuples([(0, 2)]) + result = index.intersection(other) + tm.assert_index_equal(result, expected) + + # GH 26225: duplicate nan element + index = pd.IntervalIndex([np.nan, np.nan]) + other = pd.IntervalIndex([np.nan]) + expected = pd.IntervalIndex([np.nan]) + result = index.intersection(other) + tm.assert_index_equal(result, expected) + + def test_intersection_empty_result(self, closed, sort): + index = monotonic_index(0, 11, closed=closed) + + # GH 19101: empty result, same dtype + other = monotonic_index(300, 314, closed=closed) + expected = empty_index(dtype="int64", closed=closed) + result = index.intersection(other, sort=sort) + tm.assert_index_equal(result, expected) + + # GH 19101: empty result, different numeric dtypes -> common dtype is float64 + other = monotonic_index(300, 314, dtype="float64", closed=closed) + result = index.intersection(other, sort=sort) + expected = other[:0] + tm.assert_index_equal(result, expected) + + other = monotonic_index(300, 314, dtype="uint64", closed=closed) + result = index.intersection(other, sort=sort) + tm.assert_index_equal(result, expected) + + def test_intersection_duplicates(self): + # GH#38743 + index = pd.IntervalIndex.from_tuples([(1, 2), (1, 2), (2, 3), (3, 4)]) + other = pd.IntervalIndex.from_tuples([(1, 2), (2, 3)]) + expected = pd.IntervalIndex.from_tuples([(1, 2), (2, 3)]) + result = index.intersection(other) + tm.assert_index_equal(result, expected) + + def test_difference(self, closed, sort): + index = pd.IntervalIndex.from_arrays([1, 0, 3, 2], [1, 2, 3, 4], closed=closed) + result = index.difference(index[:1], sort=sort) + expected = index[1:] + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + # GH 19101: empty result, same dtype + result = index.difference(index, sort=sort) + expected = empty_index(dtype="int64", closed=closed) + tm.assert_index_equal(result, expected) + + # GH 19101: empty result, different dtypes + other = pd.IntervalIndex.from_arrays( + index.left.astype("float64"), index.right, closed=closed + ) + result = index.difference(other, sort=sort) + tm.assert_index_equal(result, expected) + + def test_symmetric_difference(self, closed, sort): + index = monotonic_index(0, 11, closed=closed) + result = index[1:].symmetric_difference(index[:-1], sort=sort) + expected = pd.IntervalIndex([index[0], index[-1]]) + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + + # GH 19101: empty result, same dtype + result = index.symmetric_difference(index, sort=sort) + expected = empty_index(dtype="int64", closed=closed) + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + + # GH 19101: empty result, different dtypes + other = pd.IntervalIndex.from_arrays( + index.left.astype("float64"), index.right, closed=closed + ) + result = index.symmetric_difference(other, sort=sort) + expected = empty_index(dtype="float64", closed=closed) + tm.assert_index_equal(result, expected) + + @pytest.mark.filterwarnings("ignore:'<' not supported between:RuntimeWarning") + @pytest.mark.parametrize( + "op_name", ["union", "intersection", "difference", "symmetric_difference"] + ) + def test_set_incompatible_types(self, closed, op_name, sort): + index = monotonic_index(0, 11, closed=closed) + set_op = getattr(index, op_name) + + # TODO: standardize return type of non-union setops type(self vs other) + # non-IntervalIndex + if op_name == "difference": + expected = index + else: + expected = getattr(index.astype("O"), op_name)(pd.Index([1, 2, 3])) + result = set_op(pd.Index([1, 2, 3]), sort=sort) + tm.assert_index_equal(result, expected) + + # mixed closed -> cast to object + for other_closed in {"right", "left", "both", "neither"} - {closed}: + other = monotonic_index(0, 11, closed=other_closed) + expected = getattr(index.astype(object), op_name)(other, sort=sort) + if op_name == "difference": + expected = index + result = set_op(other, sort=sort) + tm.assert_index_equal(result, expected) + + # GH 19016: incompatible dtypes -> cast to object + other = pd.interval_range(pd.Timestamp("20180101"), periods=9, closed=closed) + expected = getattr(index.astype(object), op_name)(other, sort=sort) + if op_name == "difference": + expected = index + result = set_op(other, sort=sort) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/conftest.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c0d1e28c82f089562ee134e2854fb08134f6f0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/conftest.py @@ -0,0 +1,24 @@ +import numpy as np +import pytest + +import pandas as pd + + +# Note: identical the "multi" entry in the top-level "index" fixture +@pytest.fixture +def idx(): + # a MultiIndex used to test the general functionality of the + # general functionality of this object + major_axis = pd.Index(["foo", "bar", "baz", "qux"]) + minor_axis = pd.Index(["one", "two"]) + + major_codes = np.array([0, 0, 1, 2, 3, 3]) + minor_codes = np.array([0, 1, 0, 1, 0, 1]) + index_names = ["first", "second"] + mi = pd.MultiIndex( + levels=[major_axis, minor_axis], + codes=[major_codes, minor_codes], + names=index_names, + verify_integrity=False, + ) + return mi diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_analytics.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_analytics.py new file mode 100644 index 0000000000000000000000000000000000000000..cf039beb7b96567bfd286f147ef533e8ecf48cd0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_analytics.py @@ -0,0 +1,290 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_infer_objects(idx): + with pytest.raises(NotImplementedError, match="to_frame"): + idx.infer_objects() + + +def test_shift(idx): + # GH8083 test the base class for shift + msg = ( + "This method is only implemented for DatetimeIndex, PeriodIndex and " + "TimedeltaIndex; Got type MultiIndex" + ) + with pytest.raises(NotImplementedError, match=msg): + idx.shift(1) + with pytest.raises(NotImplementedError, match=msg): + idx.shift(1, 2) + + +def test_groupby(idx): + groups = idx.groupby(np.array([1, 1, 1, 2, 2, 2])) + labels = idx.tolist() + exp = {1: labels[:3], 2: labels[3:]} + tm.assert_dict_equal(groups, exp) + + # GH5620 + groups = idx.groupby(idx) + exp = {key: [key] for key in idx} + tm.assert_dict_equal(groups, exp) + + +def test_truncate_multiindex(): + # GH 34564 for MultiIndex level names check + major_axis = pd.Index(list(range(4))) + minor_axis = pd.Index(list(range(2))) + + major_codes = np.array([0, 0, 1, 2, 3, 3]) + minor_codes = np.array([0, 1, 0, 1, 0, 1]) + + index = pd.MultiIndex( + levels=[major_axis, minor_axis], + codes=[major_codes, minor_codes], + names=["L1", "L2"], + ) + + result = index.truncate(before=1) + assert "foo" not in result.levels[0] + assert 1 in result.levels[0] + assert index.names == result.names + + result = index.truncate(after=1) + assert 2 not in result.levels[0] + assert 1 in result.levels[0] + assert index.names == result.names + + result = index.truncate(before=1, after=2) + assert len(result.levels[0]) == 2 + assert index.names == result.names + + msg = "after < before" + with pytest.raises(ValueError, match=msg): + index.truncate(3, 1) + + +# TODO: reshape + + +def test_reorder_levels(idx): + # this blows up + with pytest.raises(IndexError, match="^Too many levels"): + idx.reorder_levels([2, 1, 0]) + + +def test_numpy_repeat(): + reps = 2 + numbers = [1, 2, 3] + names = np.array(["foo", "bar"]) + + m = pd.MultiIndex.from_product([numbers, names], names=names) + expected = pd.MultiIndex.from_product([numbers, names.repeat(reps)], names=names) + tm.assert_index_equal(np.repeat(m, reps), expected) + + msg = "the 'axis' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.repeat(m, reps, axis=1) + + +def test_append_mixed_dtypes(): + # GH 13660 + dti = pd.date_range("2011-01-01", freq="ME", periods=3) + dti_tz = pd.date_range("2011-01-01", freq="ME", periods=3, tz="US/Eastern") + pi = pd.period_range("2011-01", freq="M", periods=3) + + mi = pd.MultiIndex.from_arrays( + [[1, 2, 3], [1.1, np.nan, 3.3], ["a", "b", "c"], dti, dti_tz, pi] + ) + assert mi.nlevels == 6 + + res = mi.append(mi) + exp = pd.MultiIndex.from_arrays( + [ + [1, 2, 3, 1, 2, 3], + [1.1, np.nan, 3.3, 1.1, np.nan, 3.3], + ["a", "b", "c", "a", "b", "c"], + dti.append(dti), + dti_tz.append(dti_tz), + pi.append(pi), + ] + ) + tm.assert_index_equal(res, exp, check_freq=False) + + other = pd.MultiIndex.from_arrays( + [ + ["x", "y", "z"], + ["x", "y", "z"], + ["x", "y", "z"], + ["x", "y", "z"], + ["x", "y", "z"], + ["x", "y", "z"], + ] + ) + + res = mi.append(other) + exp = pd.MultiIndex.from_arrays( + [ + [1, 2, 3, "x", "y", "z"], + [1.1, np.nan, 3.3, "x", "y", "z"], + ["a", "b", "c", "x", "y", "z"], + dti.append(pd.Index(["x", "y", "z"])), + dti_tz.append(pd.Index(["x", "y", "z"])), + pi.append(pd.Index(["x", "y", "z"])), + ] + ) + tm.assert_index_equal(res, exp, check_freq=False) + + +def test_iter(idx): + result = list(idx) + expected = [ + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ] + assert result == expected + + +def test_sub(idx): + first = idx + + # - now raises (previously was set op difference) + msg = "cannot perform __sub__ with this index type: MultiIndex" + with pytest.raises(TypeError, match=msg): + first - idx[-3:] + with pytest.raises(TypeError, match=msg): + idx[-3:] - first + with pytest.raises(TypeError, match=msg): + idx[-3:] - first.tolist() + msg = "cannot perform __rsub__ with this index type: MultiIndex" + with pytest.raises(TypeError, match=msg): + first.tolist() - idx[-3:] + + +def test_map(idx): + # callable + index = idx + + result = index.map(lambda x: x) + tm.assert_index_equal(result, index) + + +@pytest.mark.parametrize( + "mapper", + [ + lambda values, idx: {i: e for e, i in zip(values, idx, strict=True)}, + lambda values, idx: pd.Series(values, idx), + ], +) +def test_map_dictlike(idx, mapper): + identity = mapper(idx.values, idx) + + # we don't infer to uint64 dtype for a dict + if idx.dtype == np.uint64 and isinstance(identity, dict): + expected = idx.astype("int64") + else: + expected = idx + + result = idx.map(identity) + tm.assert_index_equal(result, expected) + + # empty mappable + expected = pd.Index([np.nan] * len(idx)) + result = idx.map(mapper(expected, idx)) + tm.assert_index_equal(result, expected) + + +@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 func: func.__name__, +) +def test_numpy_ufuncs(idx, func): + # test ufuncs of numpy. see: + # https://numpy.org/doc/stable/reference/ufuncs.html + + expected_exception = TypeError + msg = ( + "loop of ufunc does not support argument 0 of type tuple which " + f"has no callable {func.__name__} method" + ) + with pytest.raises(expected_exception, match=msg): + func(idx) + + +@pytest.mark.parametrize( + "func", + [np.isfinite, np.isinf, np.isnan, np.signbit], + ids=lambda func: func.__name__, +) +def test_numpy_type_funcs(idx, func): + msg = ( + f"ufunc '{func.__name__}' not supported for the input types, and the inputs " + "could not be safely coerced to any supported types according to " + "the casting rule ''safe''" + ) + with pytest.raises(TypeError, match=msg): + func(idx) + + +def test_categorical_multiindex_preserved_after_arithmetic(): + # GH#42785 - CategoricalIndex levels should be preserved after + # division when the divisor has fewer levels (alignment/broadcasting). + # The bug specifically lost CategoricalIndex on leftmost levels. + v0 = pd.CategoricalIndex([10, 20, 30], name="V0") + v1 = pd.CategoricalIndex(["B", "A"], name="V1") + v2 = pd.CategoricalIndex(["X", "Y"], name="V2") + mi = pd.MultiIndex.from_product([v0, v1, v2]) + + ser = pd.Series(range(12), index=mi) + norm = ser.groupby(level=["V1", "V2"]).sum() + result = ser.div(norm) + + for level_idx in range(result.index.nlevels): + assert isinstance(result.index.levels[level_idx], pd.CategoricalIndex) + + +def test_map_multiindex_mixed_length_tuple_dict_keys(): + # GH#40115 mapping a MultiIndex with a dict whose keys are *mixed-length* + # tuples must not raise InvalidIndexError: the mapper key index has to stay + # a flat object Index rather than being tupleized into a MultiIndex + mi = pd.MultiIndex.from_tuples([("a", "a1"), ("c", "c1"), ("f", "f1")]) + mapping = {("a",): "xA", ("c", "c1"): "C1", ("f",): "xF"} + result = mi.map(mapping) + expected = pd.Index([np.nan, "C1", np.nan]) + tm.assert_index_equal(result, expected) + + # a dict that matches none of the (2-tuple) entries yields all-NaN, not a + # raise -- the minimal repro reduced by the maintainer + result_none = mi.map({("a",): "xA", ("z", "z1"): "zz"}) + tm.assert_index_equal(result_none, pd.Index([np.nan, np.nan, np.nan])) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_astype.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..29908537fbe590328ac586e05f90f3cc24cab9ab --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_astype.py @@ -0,0 +1,30 @@ +import numpy as np +import pytest + +from pandas.core.dtypes.dtypes import CategoricalDtype + +import pandas._testing as tm + + +def test_astype(idx): + expected = idx.copy() + actual = idx.astype("O") + tm.assert_copy(actual.levels, expected.levels) + tm.assert_copy(actual.codes, expected.codes) + assert actual.names == list(expected.names) + + with pytest.raises(TypeError, match="^Setting.*dtype.*object"): + idx.astype(np.dtype(int)) + + +@pytest.mark.parametrize("ordered", [True, False]) +def test_astype_category(idx, ordered): + # GH 18630 + msg = "> 1 ndim Categorical are not supported at this time" + with pytest.raises(NotImplementedError, match=msg): + idx.astype(CategoricalDtype(ordered=ordered)) + + if ordered is False: + # dtype='category' defaults to ordered=False, so only test once + with pytest.raises(NotImplementedError, match=msg): + idx.astype("category") diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_compat.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..c312195917263bdc5f0db07c3680e6002fe03866 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_compat.py @@ -0,0 +1,121 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_numeric_compat(idx): + with pytest.raises(TypeError, match="cannot perform __mul__"): + idx * 1 + + with pytest.raises(TypeError, match="cannot perform __rmul__"): + 1 * idx + + div_err = "cannot perform __truediv__" + with pytest.raises(TypeError, match=div_err): + idx / 1 + + div_err = div_err.replace(" __", " __r") + with pytest.raises(TypeError, match=div_err): + 1 / idx + + with pytest.raises(TypeError, match="cannot perform __floordiv__"): + idx // 1 + + with pytest.raises(TypeError, match="cannot perform __rfloordiv__"): + 1 // idx + + +@pytest.mark.parametrize("method", ["all", "any", "__invert__"]) +def test_logical_compat(idx, method): + msg = f"cannot perform {method}" + + with pytest.raises(TypeError, match=msg): + getattr(idx, method)() + + +def test_inplace_mutation_resets_values(): + levels = [["a", "b", "c"], [4]] + levels2 = [[1, 2, 3], ["a"]] + codes = [[0, 1, 0, 2, 2, 0], [0, 0, 0, 0, 0, 0]] + + mi1 = pd.MultiIndex(levels=levels, codes=codes) + mi2 = pd.MultiIndex(levels=levels2, codes=codes) + + # instantiating MultiIndex should not access/cache _.values + assert "_values" not in mi1._cache + assert "_values" not in mi2._cache + + vals = mi1.values.copy() + vals2 = mi2.values.copy() + + # accessing .values should cache ._values + assert mi1._values is mi1._cache["_values"] + assert mi1.values is mi1._cache["_values"] + assert isinstance(mi1._cache["_values"], np.ndarray) + + # Make sure level setting works + new_vals = mi1.set_levels(levels2).values + tm.assert_almost_equal(vals2, new_vals) + + # Doesn't drop _values from _cache [implementation detail] + tm.assert_almost_equal(mi1._cache["_values"], vals) + + # ...and values is still same too + tm.assert_almost_equal(mi1.values, vals) + + # Make sure label setting works too + codes2 = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] + exp_values = np.empty((6,), dtype=object) + exp_values[:] = [(1, "a")] * 6 + + # Must be 1d array of tuples + assert exp_values.shape == (6,) + + new_mi = mi2.set_codes(codes2) + assert "_values" not in new_mi._cache + new_values = new_mi.values + assert "_values" in new_mi._cache + + # Shouldn't change cache + tm.assert_almost_equal(mi2._cache["_values"], vals2) + + # Should have correct values + tm.assert_almost_equal(exp_values, new_values) + + +def test_boxable_categorical_values(): + cat = pd.Categorical(pd.date_range("2012-01-01", periods=3, freq="h")) + result = pd.MultiIndex.from_product([["a", "b", "c"], cat]).values + expected = pd.Series( + [ + ("a", pd.Timestamp("2012-01-01 00:00:00")), + ("a", pd.Timestamp("2012-01-01 01:00:00")), + ("a", pd.Timestamp("2012-01-01 02:00:00")), + ("b", pd.Timestamp("2012-01-01 00:00:00")), + ("b", pd.Timestamp("2012-01-01 01:00:00")), + ("b", pd.Timestamp("2012-01-01 02:00:00")), + ("c", pd.Timestamp("2012-01-01 00:00:00")), + ("c", pd.Timestamp("2012-01-01 01:00:00")), + ("c", pd.Timestamp("2012-01-01 02:00:00")), + ] + ).values + tm.assert_numpy_array_equal(result, expected) + result = pd.DataFrame({"a": ["a", "b", "c"], "b": cat, "c": np.array(cat)}).values + expected = pd.DataFrame( + { + "a": ["a", "b", "c"], + "b": [ + pd.Timestamp("2012-01-01 00:00:00"), + pd.Timestamp("2012-01-01 01:00:00"), + pd.Timestamp("2012-01-01 02:00:00"), + ], + "c": [ + pd.Timestamp("2012-01-01 00:00:00"), + pd.Timestamp("2012-01-01 01:00:00"), + pd.Timestamp("2012-01-01 02:00:00"), + ], + } + ).values + tm.assert_numpy_array_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_constructors.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e35ce76b77bcf65183578aae2a4598dfe51cd5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_constructors.py @@ -0,0 +1,881 @@ +from datetime import ( + date, + datetime, +) +import itertools + +import numpy as np +import pytest + +from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike + +import pandas as pd +import pandas._testing as tm + + +def test_constructor_single_level(): + result = pd.MultiIndex( + levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"] + ) + assert isinstance(result, pd.MultiIndex) + expected = pd.Index(["foo", "bar", "baz", "qux"], name="first") + tm.assert_index_equal(result.levels[0], expected) + assert result.names == ["first"] + + +def test_constructor_no_levels(): + msg = "non-zero number of levels/codes" + with pytest.raises(ValueError, match=msg): + pd.MultiIndex(levels=[], codes=[]) + + msg = "Must pass both levels and codes" + with pytest.raises(TypeError, match=msg): + pd.MultiIndex(levels=[]) + with pytest.raises(TypeError, match=msg): + pd.MultiIndex(codes=[]) + + +def test_constructor_nonhashable_names(): + # GH 20527 + levels = [[1, 2], ["one", "two"]] + codes = [[0, 0, 1, 1], [0, 1, 0, 1]] + names = (["foo"], ["bar"]) + msg = r"MultiIndex\.name must be a hashable type" + with pytest.raises(TypeError, match=msg): + pd.MultiIndex(levels=levels, codes=codes, names=names) + + # With .rename() + mi = pd.MultiIndex( + levels=[[1, 2], ["one", "two"]], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=("foo", "bar"), + ) + renamed = [["fooo"], ["barr"]] + with pytest.raises(TypeError, match=msg): + mi.rename(names=renamed) + + # With .set_names() + with pytest.raises(TypeError, match=msg): + mi.set_names(names=renamed) + + +def test_constructor_mismatched_codes_levels(idx): + codes = [np.array([1]), np.array([2]), np.array([3])] + levels = ["a"] + + msg = "Length of levels and codes must be the same" + with pytest.raises(ValueError, match=msg): + pd.MultiIndex(levels=levels, codes=codes) + + length_error = ( + r"On level 0, code max \(3\) >= length of level \(1\)\. " + "NOTE: this index is in an inconsistent state" + ) + label_error = r"Unequal code lengths: \[4, 2\]" + code_value_error = r"On level 0, code value \(-2\) < -1" + + # important to check that it's looking at the right thing. + with pytest.raises(ValueError, match=length_error): + pd.MultiIndex(levels=[["a"], ["b"]], codes=[[0, 1, 2, 3], [0, 3, 4, 1]]) + + with pytest.raises(ValueError, match=label_error): + pd.MultiIndex(levels=[["a"], ["b"]], codes=[[0, 0, 0, 0], [0, 0]]) + + # external API + with pytest.raises(ValueError, match=length_error): + idx.copy().set_levels([["a"], ["b"]]) + + with pytest.raises(ValueError, match=label_error): + idx.copy().set_codes([[0, 0, 0, 0], [0, 0]]) + + # test set_codes with verify_integrity=False + # the setting should not raise any value error + idx.copy().set_codes(codes=[[0, 0, 0, 0], [0, 0]], verify_integrity=False) + + # code value smaller than -1 + with pytest.raises(ValueError, match=code_value_error): + pd.MultiIndex(levels=[["a"], ["b"]], codes=[[0, -2], [0, 0]]) + + +def test_na_levels(): + # GH26408 + # test if codes are re-assigned value -1 for levels + # with missing values (NaN, NaT, None) + result = pd.MultiIndex( + levels=[[np.nan, None, pd.NaT, 128, 2]], codes=[[0, -1, 1, 2, 3, 4]] + ) + expected = pd.MultiIndex( + levels=[[np.nan, None, pd.NaT, 128, 2]], codes=[[-1, -1, -1, -1, 3, 4]] + ) + tm.assert_index_equal(result, expected) + + result = pd.MultiIndex( + levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[0, -1, 1, 2, 3, 4]] + ) + expected = pd.MultiIndex( + levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[-1, -1, 1, -1, 3, -1]] + ) + tm.assert_index_equal(result, expected) + + # verify set_levels and set_codes + result = pd.MultiIndex( + levels=[[1, 2, 3, 4, 5]], codes=[[0, -1, 1, 2, 3, 4]] + ).set_levels([[np.nan, "s", pd.NaT, 128, None]]) + tm.assert_index_equal(result, expected) + + result = pd.MultiIndex( + levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[1, 2, 2, 2, 2, 2]] + ).set_codes([[0, -1, 1, 2, 3, 4]]) + tm.assert_index_equal(result, expected) + + +def test_copy_in_constructor(): + levels = np.array(["a", "b", "c"]) + codes = np.array([1, 1, 2, 0, 0, 1, 1]) + val = codes[0] + mi = pd.MultiIndex(levels=[levels, levels], codes=[codes, codes], copy=True) + assert mi.codes[0][0] == val + codes[0] = 15 + assert mi.codes[0][0] == val + val = levels[0] + levels[0] = "PANDA" + assert mi.levels[0][0] == val + + +# ---------------------------------------------------------------------------- +# from_arrays +# ---------------------------------------------------------------------------- +def test_from_arrays(idx): + arrays = [ + np.asarray(lev).take(level_codes) + for lev, level_codes in zip(idx.levels, idx.codes, strict=True) + ] + + # list of arrays as input + result = pd.MultiIndex.from_arrays(arrays, names=idx.names) + tm.assert_index_equal(result, idx) + + # infer correctly + result = pd.MultiIndex.from_arrays([[pd.NaT, pd.Timestamp("20130101")], ["a", "b"]]) + assert result.levels[0].equals(pd.Index([pd.Timestamp("20130101")])) + assert result.levels[1].equals(pd.Index(["a", "b"])) + + +def test_from_arrays_iterator(idx): + # GH 18434 + arrays = [ + np.asarray(lev).take(level_codes) + for lev, level_codes in zip(idx.levels, idx.codes, strict=True) + ] + + # iterator as input + result = pd.MultiIndex.from_arrays(iter(arrays), names=idx.names) + tm.assert_index_equal(result, idx) + + # invalid iterator input + msg = "Input must be a list / sequence of array-likes." + with pytest.raises(TypeError, match=msg): + pd.MultiIndex.from_arrays(0) + + +def test_from_arrays_tuples(idx): + arrays = tuple( + tuple(np.asarray(lev).take(level_codes)) + for lev, level_codes in zip(idx.levels, idx.codes, strict=True) + ) + + # tuple of tuples as input + result = pd.MultiIndex.from_arrays(arrays, names=idx.names) + tm.assert_index_equal(result, idx) + + +@pytest.mark.parametrize( + ("idx1", "idx2"), + [ + ( + pd.period_range("2011-01-01", freq="D", periods=3), + pd.period_range("2015-01-01", freq="h", periods=3), + ), + ( + pd.date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern"), + pd.date_range("2015-01-01 10:00", freq="h", periods=3, tz="Asia/Tokyo"), + ), + ( + pd.timedelta_range("1 days", freq="D", periods=3), + pd.timedelta_range("2 hours", freq="h", periods=3), + ), + ], +) +def test_from_arrays_index_series_period_datetimetz_and_timedelta(idx1, idx2): + result = pd.MultiIndex.from_arrays([idx1, idx2]) + tm.assert_index_equal(result.get_level_values(0), idx1, check_freq=False) + tm.assert_index_equal(result.get_level_values(1), idx2, check_freq=False) + + result2 = pd.MultiIndex.from_arrays([pd.Series(idx1), pd.Series(idx2)]) + tm.assert_index_equal(result2.get_level_values(0), idx1, check_freq=False) + tm.assert_index_equal(result2.get_level_values(1), idx2, check_freq=False) + + tm.assert_index_equal(result, result2, check_freq=False) + + +def test_from_arrays_index_datetimelike_mixed(): + idx1 = pd.date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern") + idx2 = pd.date_range("2015-01-01 10:00", freq="h", periods=3) + idx3 = pd.timedelta_range("1 days", freq="D", periods=3) + idx4 = pd.period_range("2011-01-01", freq="D", periods=3) + + result = pd.MultiIndex.from_arrays([idx1, idx2, idx3, idx4]) + tm.assert_index_equal(result.get_level_values(0), idx1, check_freq=False) + tm.assert_index_equal(result.get_level_values(1), idx2, check_freq=False) + tm.assert_index_equal(result.get_level_values(2), idx3, check_freq=False) + tm.assert_index_equal(result.get_level_values(3), idx4) + + result2 = pd.MultiIndex.from_arrays( + [pd.Series(idx1), pd.Series(idx2), pd.Series(idx3), pd.Series(idx4)] + ) + tm.assert_index_equal(result2.get_level_values(0), idx1, check_freq=False) + tm.assert_index_equal(result2.get_level_values(1), idx2, check_freq=False) + tm.assert_index_equal(result2.get_level_values(2), idx3, check_freq=False) + tm.assert_index_equal(result2.get_level_values(3), idx4) + + tm.assert_index_equal(result, result2, check_freq=False) + + +def test_from_arrays_index_series_categorical(): + # GH13743 + idx1 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=False) + idx2 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=True) + + result = pd.MultiIndex.from_arrays([idx1, idx2]) + tm.assert_index_equal(result.get_level_values(0), idx1) + tm.assert_index_equal(result.get_level_values(1), idx2) + + result2 = pd.MultiIndex.from_arrays([pd.Series(idx1), pd.Series(idx2)]) + tm.assert_index_equal(result2.get_level_values(0), idx1) + tm.assert_index_equal(result2.get_level_values(1), idx2) + + result3 = pd.MultiIndex.from_arrays([idx1.values, idx2.values]) + tm.assert_index_equal(result3.get_level_values(0), idx1) + tm.assert_index_equal(result3.get_level_values(1), idx2) + + +def test_from_arrays_empty(): + # 0 levels + msg = "Must pass non-zero number of levels/codes" + with pytest.raises(ValueError, match=msg): + pd.MultiIndex.from_arrays(arrays=[]) + + # 1 level + result = pd.MultiIndex.from_arrays(arrays=[[]], names=["A"]) + assert isinstance(result, pd.MultiIndex) + expected = pd.Index([], name="A") + tm.assert_index_equal(result.levels[0], expected) + assert result.names == ["A"] + + # N levels + for N in [2, 3]: + arrays = [[]] * N + names = list("ABC")[:N] + result = pd.MultiIndex.from_arrays(arrays=arrays, names=names) + expected = pd.MultiIndex(levels=[[]] * N, codes=[[]] * N, names=names) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "invalid_sequence_of_arrays", + [ + 1, + [1], + [1, 2], + [[1], 2], + [1, [2]], + "a", + ["a"], + ["a", "b"], + [["a"], "b"], + (1,), + (1, 2), + ([1], 2), + (1, [2]), + ("a",), + ("a", "b"), + (["a"], "b"), + [(1,), 2], + [1, (2,)], + [("a",), "b"], + ((1,), 2), + (1, (2,)), + (("a",), "b"), + ], +) +def test_from_arrays_invalid_input(invalid_sequence_of_arrays): + msg = "Input must be a list / sequence of array-likes" + with pytest.raises(TypeError, match=msg): + pd.MultiIndex.from_arrays(arrays=invalid_sequence_of_arrays) + + +@pytest.mark.parametrize( + "idx1, idx2", [([1, 2, 3], ["a", "b"]), ([], ["a", "b"]), ([1, 2, 3], [])] +) +def test_from_arrays_different_lengths(idx1, idx2): + # see gh-13599 + msg = "^all arrays must be same length$" + with pytest.raises(ValueError, match=msg): + pd.MultiIndex.from_arrays([idx1, idx2]) + + +def test_from_arrays_respects_none_names(): + # GH27292 + a = pd.Series([1, 2, 3], name="foo") + b = pd.Series(["a", "b", "c"], name="bar") + + result = pd.MultiIndex.from_arrays([a, b], names=None) + expected = pd.MultiIndex( + levels=[[1, 2, 3], ["a", "b", "c"]], codes=[[0, 1, 2], [0, 1, 2]], names=None + ) + + tm.assert_index_equal(result, expected) + + +# ---------------------------------------------------------------------------- +# from_tuples +# ---------------------------------------------------------------------------- +def test_from_tuples(): + msg = "Cannot infer number of levels from empty list" + with pytest.raises(TypeError, match=msg): + pd.MultiIndex.from_tuples([]) + + expected = pd.MultiIndex( + levels=[[1, 3], [2, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"] + ) + + # input tuples + result = pd.MultiIndex.from_tuples(((1, 2), (3, 4)), names=["a", "b"]) + tm.assert_index_equal(result, expected) + + +def test_from_tuples_iterator(): + # GH 18434 + # input iterator for tuples + expected = pd.MultiIndex( + levels=[[1, 3], [2, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"] + ) + + result = pd.MultiIndex.from_tuples( + zip([1, 3], [2, 4], strict=True), names=["a", "b"] + ) + tm.assert_index_equal(result, expected) + + # input non-iterables + msg = "Input must be list-like of tuples." + with pytest.raises(TypeError, match=msg): + pd.MultiIndex.from_tuples(0) + + +def test_from_tuples_empty(): + # GH 16777 + result = pd.MultiIndex.from_tuples([], names=["a", "b"]) + expected = pd.MultiIndex.from_arrays(arrays=[[], []], names=["a", "b"]) + tm.assert_index_equal(result, expected) + + +def test_from_tuples_index_values(idx): + result = pd.MultiIndex.from_tuples(idx) + assert (result.values == idx.values).all() + + +def test_tuples_with_name_string(): + # GH 15110 and GH 14848 + + li = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] + msg = "Names should be list-like for a MultiIndex" + with pytest.raises(ValueError, match=msg): + pd.Index(li, name="abc") + with pytest.raises(ValueError, match=msg): + pd.Index(li, name="a") + + +def test_from_tuples_with_tuple_label(): + # GH 15457 + expected = pd.DataFrame( + [[2, 1, 2], [4, (1, 2), 3]], columns=["a", "b", "c"] + ).set_index(["a", "b"]) + idx = pd.MultiIndex.from_tuples([(2, 1), (4, (1, 2))], names=("a", "b")) + result = pd.DataFrame([2, 3], columns=["c"], index=idx) + tm.assert_frame_equal(expected, result) + + +@pytest.mark.parametrize( + "keys, expected", + [ + ((("l1",), ("l1", "l2")), (("l1", np.nan), ("l1", "l2"))), + ((("l1", "l2"), ("l1",)), (("l1", "l2"), ("l1", np.nan))), + ], +) +def test_from_tuples_with_various_tuple_lengths(keys, expected): + # GH 60695 + idx = pd.MultiIndex.from_tuples(keys) + assert tuple(idx) == expected + + +# ---------------------------------------------------------------------------- +# from_product +# ---------------------------------------------------------------------------- +def test_from_product_empty_zero_levels(): + # 0 levels + msg = "Must pass non-zero number of levels/codes" + with pytest.raises(ValueError, match=msg): + pd.MultiIndex.from_product([]) + + +def test_from_product_empty_one_level(): + result = pd.MultiIndex.from_product([[]], names=["A"]) + expected = pd.Index([], name="A") + tm.assert_index_equal(result.levels[0], expected) + assert result.names == ["A"] + + +@pytest.mark.parametrize( + "first, second", [([], []), (["foo", "bar", "baz"], []), ([], ["a", "b", "c"])] +) +def test_from_product_empty_two_levels(first, second): + names = ["A", "B"] + result = pd.MultiIndex.from_product([first, second], names=names) + expected = pd.MultiIndex(levels=[first, second], codes=[[], []], names=names) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("N", list(range(4))) +def test_from_product_empty_three_levels(N): + # GH12258 + names = ["A", "B", "C"] + lvl2 = list(range(N)) + result = pd.MultiIndex.from_product([[], lvl2, []], names=names) + expected = pd.MultiIndex(levels=[[], lvl2, []], codes=[[], [], []], names=names) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "invalid_input", [1, [1], [1, 2], [[1], 2], "a", ["a"], ["a", "b"], [["a"], "b"]] +) +def test_from_product_invalid_input(invalid_input): + msg = "|".join( + ["Input must be a list / sequence of iterables", "Input must be list-like"] + ) + with pytest.raises(TypeError, match=msg): + pd.MultiIndex.from_product(iterables=invalid_input) + + +def test_from_product_datetimeindex(): + dt_index = pd.date_range("2000-01-01", periods=2) + mi = pd.MultiIndex.from_product([[1, 2], dt_index]) + etalon = construct_1d_object_array_from_listlike( + [ + (1, pd.Timestamp("2000-01-01")), + (1, pd.Timestamp("2000-01-02")), + (2, pd.Timestamp("2000-01-01")), + (2, pd.Timestamp("2000-01-02")), + ] + ) + tm.assert_numpy_array_equal(mi.values, etalon) + + +def test_from_product_preserves_datetime_date(): + # GH#28152 python datetime.date labels must not be upcast to Timestamp + day = date(2019, 2, 2) + mi = pd.MultiIndex.from_product([[day, day], [2, 3]]) + assert mi[0] == (day, 2) + assert type(mi[0][0]) is date + + # from_tuples is explicitly called out in the issue as having the same bug + mt = pd.MultiIndex.from_tuples([(day, 2), (day, 3)]) + assert type(mt[0][0]) is date + + +def test_from_product_rangeindex(): + # RangeIndex is preserved by factorize, so preserved in levels + rng = pd.Index(range(5)) + other = ["a", "b"] + mi = pd.MultiIndex.from_product([rng, other]) + tm.assert_index_equal(mi._levels[0], rng, exact=True) + + +@pytest.mark.parametrize("ordered", [False, True]) +@pytest.mark.parametrize("f", [lambda x: x, lambda x: pd.Series(x), lambda x: x.values]) +def test_from_product_index_series_categorical(ordered, f): + # GH13743 + first = ["foo", "bar"] + + idx = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=ordered) + expected = pd.CategoricalIndex( + list("abcaab") + list("abcaab"), categories=list("bac"), ordered=ordered + ) + + result = pd.MultiIndex.from_product([first, f(idx)]) + tm.assert_index_equal(result.get_level_values(1), expected) + + +def test_from_product(): + first = ["foo", "bar", "buz"] + second = ["a", "b", "c"] + names = ["first", "second"] + result = pd.MultiIndex.from_product([first, second], names=names) + + tuples = [ + ("foo", "a"), + ("foo", "b"), + ("foo", "c"), + ("bar", "a"), + ("bar", "b"), + ("bar", "c"), + ("buz", "a"), + ("buz", "b"), + ("buz", "c"), + ] + expected = pd.MultiIndex.from_tuples(tuples, names=names) + + tm.assert_index_equal(result, expected) + + +def test_from_product_iterator(): + # GH 18434 + first = ["foo", "bar", "buz"] + second = ["a", "b", "c"] + names = ["first", "second"] + tuples = [ + ("foo", "a"), + ("foo", "b"), + ("foo", "c"), + ("bar", "a"), + ("bar", "b"), + ("bar", "c"), + ("buz", "a"), + ("buz", "b"), + ("buz", "c"), + ] + expected = pd.MultiIndex.from_tuples(tuples, names=names) + + # iterator as input + result = pd.MultiIndex.from_product(iter([first, second]), names=names) + tm.assert_index_equal(result, expected) + + # Invalid non-iterable input + msg = "Input must be a list / sequence of iterables." + with pytest.raises(TypeError, match=msg): + pd.MultiIndex.from_product(0) + + +@pytest.mark.parametrize( + "a, b, expected_names", + [ + ( + pd.Series([1, 2, 3], name="foo"), + pd.Series(["a", "b"], name="bar"), + ["foo", "bar"], + ), + (pd.Series([1, 2, 3], name="foo"), ["a", "b"], ["foo", None]), + ([1, 2, 3], ["a", "b"], None), + ], +) +def test_from_product_infer_names(a, b, expected_names): + # GH27292 + result = pd.MultiIndex.from_product([a, b]) + expected = pd.MultiIndex( + levels=[[1, 2, 3], ["a", "b"]], + codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], + names=expected_names, + ) + tm.assert_index_equal(result, expected) + + +def test_from_product_respects_none_names(): + # GH27292 + a = pd.Series([1, 2, 3], name="foo") + b = pd.Series(["a", "b"], name="bar") + + result = pd.MultiIndex.from_product([a, b], names=None) + expected = pd.MultiIndex( + levels=[[1, 2, 3], ["a", "b"]], + codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], + names=None, + ) + tm.assert_index_equal(result, expected) + + +def test_from_product_readonly(): + # GH#15286 passing read-only array to from_product + a = np.array(range(3)) + b = ["a", "b"] + expected = pd.MultiIndex.from_product([a, b]) + + a.setflags(write=False) + result = pd.MultiIndex.from_product([a, b]) + tm.assert_index_equal(result, expected) + + +def test_create_index_existing_name(idx): + # GH11193, when an existing index is passed, and a new name is not + # specified, the new index should inherit the previous object name + index = idx + index.names = ["foo", "bar"] + result = pd.Index(index) + expected = pd.Index( + pd.Index( + [ + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ], + dtype="object", + ) + ) + tm.assert_index_equal(result, expected) + + result = pd.Index(index, name="A") + expected = pd.Index( + pd.Index( + [ + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ], + dtype="object", + ), + name="A", + ) + tm.assert_index_equal(result, expected) + + +# ---------------------------------------------------------------------------- +# from_frame +# ---------------------------------------------------------------------------- +def test_from_frame(): + # GH 22420 + df = pd.DataFrame( + [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], columns=["L1", "L2"] + ) + expected = pd.MultiIndex.from_tuples( + [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")], names=["L1", "L2"] + ) + result = pd.MultiIndex.from_frame(df) + tm.assert_index_equal(expected, result) + + +def test_from_frame_missing_values_multiIndex(): + # GH 39984 + pa = pytest.importorskip("pyarrow") + + df = pd.DataFrame( + { + "a": pd.Series([1, 2, None], dtype="Int64"), + "b": pd.Float64Dtype().__from_arrow__(pa.array([0.2, None, None])), + } + ) + multi_indexed = pd.MultiIndex.from_frame(df) + expected = pd.MultiIndex.from_arrays( + [ + pd.Series([1, 2, None], dtype="Int64"), + pd.Float64Dtype().__from_arrow__(pa.array([0.2, None, None])), + ], + names=["a", "b"], + ) + tm.assert_index_equal(multi_indexed, expected) + + +@pytest.mark.parametrize( + "non_frame", + [ + pd.Series([1, 2, 3, 4]), + [1, 2, 3, 4], + [[1, 2], [3, 4], [5, 6]], + pd.Index([1, 2, 3, 4]), + np.array([[1, 2], [3, 4], [5, 6]]), + 27, + ], +) +def test_from_frame_error(non_frame): + # GH 22420 + with pytest.raises(TypeError, match="Input must be a DataFrame"): + pd.MultiIndex.from_frame(non_frame) + + +def test_from_frame_dtype_fidelity(): + # GH 22420 + df = pd.DataFrame( + { + "dates": pd.date_range("19910905", periods=6, tz="US/Eastern"), + "a": [1, 1, 1, 2, 2, 2], + "b": pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True), + "c": ["x", "x", "y", "z", "x", "y"], + } + ) + original_dtypes = df.dtypes.to_dict() + + expected_mi = pd.MultiIndex.from_arrays( + [ + pd.date_range("19910905", periods=6, tz="US/Eastern"), + [1, 1, 1, 2, 2, 2], + pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True), + ["x", "x", "y", "z", "x", "y"], + ], + names=["dates", "a", "b", "c"], + ) + mi = pd.MultiIndex.from_frame(df) + mi_dtypes = {name: mi.levels[i].dtype for i, name in enumerate(mi.names)} + + tm.assert_index_equal(expected_mi, mi, check_freq=False) + assert original_dtypes == mi_dtypes + + +@pytest.mark.parametrize( + "names_in,names_out", [(None, [("L1", "x"), ("L2", "y")]), (["x", "y"], ["x", "y"])] +) +def test_from_frame_valid_names(names_in, names_out): + # GH 22420 + df = pd.DataFrame( + [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], + columns=pd.MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), + ) + mi = pd.MultiIndex.from_frame(df, names=names_in) + assert mi.names == names_out + + +@pytest.mark.parametrize( + "names,expected_error_msg", + [ + ("bad_input", "Names should be list-like for a MultiIndex"), + (["a", "b", "c"], "Length of names must match number of levels in MultiIndex"), + ], +) +def test_from_frame_invalid_names(names, expected_error_msg): + # GH 22420 + df = pd.DataFrame( + [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], + columns=pd.MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), + ) + with pytest.raises(ValueError, match=expected_error_msg): + pd.MultiIndex.from_frame(df, names=names) + + +def test_index_equal_empty_iterable(): + # #16844 + a = pd.MultiIndex(levels=[[], []], codes=[[], []], names=["a", "b"]) + b = pd.MultiIndex.from_arrays(arrays=[[], []], names=["a", "b"]) + tm.assert_index_equal(a, b) + + +def test_raise_invalid_sortorder(): + # Test that the MultiIndex constructor raise when an incorrect sortorder is given + # GH#28518 + + levels = [[0, 1], [0, 1, 2]] + + # Correct sortorder + pd.MultiIndex( + levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], sortorder=2 + ) + + with pytest.raises(ValueError, match=r".* sortorder 2 with lexsort_depth 1.*"): + pd.MultiIndex( + levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=2 + ) + + with pytest.raises(ValueError, match=r".* sortorder 1 with lexsort_depth 0.*"): + pd.MultiIndex( + levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=1 + ) + + +def test_datetimeindex(): + idx1 = pd.DatetimeIndex( + ["2013-04-01 9:00", "2013-04-02 9:00", "2013-04-03 9:00"] * 2, tz="Asia/Tokyo" + ) + idx2 = pd.date_range("2010/01/01", periods=6, freq="ME", tz="US/Eastern") + idx = pd.MultiIndex.from_arrays([idx1, idx2]) + + expected1 = pd.DatetimeIndex( + ["2013-04-01 9:00", "2013-04-02 9:00", "2013-04-03 9:00"], tz="Asia/Tokyo" + ) + + tm.assert_index_equal(idx.levels[0], expected1) + tm.assert_index_equal(idx.levels[1], idx2) + + # from datetime combos + # GH 7888 + date1 = np.datetime64("2011-01-01") + date2 = datetime(2011, 1, 1) + date3 = pd.Timestamp("2011-01-01") + + for d1, d2 in itertools.product([date1, date2, date3], [date1, date2, date3]): + index = pd.MultiIndex.from_product([[d1], [d2]]) + assert isinstance(index.levels[0], pd.DatetimeIndex) + assert isinstance(index.levels[1], pd.DatetimeIndex) + + # but NOT date objects, matching Index behavior + date4 = date(2011, 1, 1) + index = pd.MultiIndex.from_product([[date4], [date2]]) + assert not isinstance(index.levels[0], pd.DatetimeIndex) + assert isinstance(index.levels[1], pd.DatetimeIndex) + + +def test_constructor_with_tz(): + 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" + ) + + result = pd.MultiIndex.from_arrays([index, columns]) + + assert result.names == ["dt1", "dt2"] + tm.assert_index_equal(result.levels[0], index) + tm.assert_index_equal(result.levels[1], columns) + + result = pd.MultiIndex.from_arrays([pd.Series(index), pd.Series(columns)]) + + assert result.names == ["dt1", "dt2"] + tm.assert_index_equal(result.levels[0], index) + tm.assert_index_equal(result.levels[1], columns) + + +def test_multiindex_inference_consistency(): + # check that inference behavior matches the base class + + v = date(2011, 1, 1) + + arr = [v, v] + + idx = pd.Index(arr) + assert idx.dtype == object + + mi = pd.MultiIndex.from_arrays([arr]) + lev = mi.levels[0] + assert lev.dtype == object + + mi = pd.MultiIndex.from_product([arr]) + lev = mi.levels[0] + assert lev.dtype == object + + mi = pd.MultiIndex.from_tuples([(x,) for x in arr]) + lev = mi.levels[0] + assert lev.dtype == object + + +def test_dtype_representation(using_infer_string): + # GH#46900 + pmidx = pd.MultiIndex.from_arrays([[1], ["a"]], names=[("a", "b"), ("c", "d")]) + result = pmidx.dtypes + exp = "object" if not using_infer_string else pd.StringDtype(na_value=np.nan) + expected = pd.Series( + ["int64", exp], + index=pd.MultiIndex.from_tuples([("a", "b"), ("c", "d")]), + dtype=object, + ) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_conversion.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..1d04ccb1d6d9d5a332f52be55c4b6dfd35b50118 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_conversion.py @@ -0,0 +1,197 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_to_numpy(idx): + result = idx.to_numpy() + exp = idx.values + tm.assert_numpy_array_equal(result, exp) + + +def test_array_interface(idx): + # https://github.com/pandas-dev/pandas/pull/60046 + result = np.asarray(idx) + expected = np.empty((6,), dtype=object) + expected[:] = [ + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ] + tm.assert_numpy_array_equal(result, expected) + + # it always gives a copy by default, but the values are cached, so results + # are still sharing memory + result_copy1 = np.asarray(idx) + result_copy2 = np.asarray(idx) + assert np.may_share_memory(result_copy1, result_copy2) + + # with explicit copy=True, then it is an actual copy + result_copy1 = np.array(idx, copy=True) + result_copy2 = np.array(idx, copy=True) + assert not np.may_share_memory(result_copy1, result_copy2) + + # for MultiIndex, copy=False is never allowed + with pytest.raises(ValueError, match="Unable to avoid copy while creating"): + np.array(idx, copy=False) + + +def test_to_frame(): + tuples = [(1, "one"), (1, "two"), (2, "one"), (2, "two")] + + index = pd.MultiIndex.from_tuples(tuples) + result = index.to_frame(index=False) + expected = pd.DataFrame(tuples) + tm.assert_frame_equal(result, expected) + + result = index.to_frame() + expected.index = index + tm.assert_frame_equal(result, expected) + + tuples = [(1, "one"), (1, "two"), (2, "one"), (2, "two")] + index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"]) + result = index.to_frame(index=False) + expected = pd.DataFrame(tuples) + expected.columns = ["first", "second"] + tm.assert_frame_equal(result, expected) + + result = index.to_frame() + expected.index = index + tm.assert_frame_equal(result, expected) + + # See GH-22580 + index = pd.MultiIndex.from_tuples(tuples) + result = index.to_frame(index=False, name=["first", "second"]) + expected = pd.DataFrame(tuples) + expected.columns = ["first", "second"] + tm.assert_frame_equal(result, expected) + + result = index.to_frame(name=["first", "second"]) + expected.index = index + expected.columns = ["first", "second"] + tm.assert_frame_equal(result, expected) + + msg = "'name' must be a list / sequence of column names." + with pytest.raises(TypeError, match=msg): + index.to_frame(name="first") + + msg = "'name' should have same length as number of levels on index." + with pytest.raises(ValueError, match=msg): + index.to_frame(name=["first"]) + + # Tests for datetime index + index = pd.MultiIndex.from_product([range(5), pd.date_range("20130101", periods=3)]) + result = index.to_frame(index=False) + expected = pd.DataFrame( + { + 0: np.repeat(np.arange(5, dtype="int64"), 3), + 1: np.tile(pd.date_range("20130101", periods=3), 5), + } + ) + tm.assert_frame_equal(result, expected) + + result = index.to_frame() + expected.index = index + tm.assert_frame_equal(result, expected) + + # See GH-22580 + result = index.to_frame(index=False, name=["first", "second"]) + expected = pd.DataFrame( + { + "first": np.repeat(np.arange(5, dtype="int64"), 3), + "second": np.tile(pd.date_range("20130101", periods=3), 5), + } + ) + tm.assert_frame_equal(result, expected) + + result = index.to_frame(name=["first", "second"]) + expected.index = index + tm.assert_frame_equal(result, expected) + + +def test_to_frame_dtype_fidelity(): + # GH 22420 + mi = pd.MultiIndex.from_arrays( + [ + pd.date_range("19910905", periods=6, tz="US/Eastern"), + [1, 1, 1, 2, 2, 2], + pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True), + ["x", "x", "y", "z", "x", "y"], + ], + names=["dates", "a", "b", "c"], + ) + original_dtypes = {name: mi.levels[i].dtype for i, name in enumerate(mi.names)} + + expected_df = pd.DataFrame( + { + "dates": pd.date_range("19910905", periods=6, tz="US/Eastern"), + "a": [1, 1, 1, 2, 2, 2], + "b": pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True), + "c": ["x", "x", "y", "z", "x", "y"], + } + ) + df = mi.to_frame(index=False) + df_dtypes = df.dtypes.to_dict() + + tm.assert_frame_equal(df, expected_df) + assert original_dtypes == df_dtypes + + +def test_to_frame_resulting_column_order(): + # GH 22420 + expected = ["z", 0, "a"] + mi = pd.MultiIndex.from_arrays( + [["a", "b", "c"], ["x", "y", "z"], ["q", "w", "e"]], names=expected + ) + result = mi.to_frame().columns.tolist() + assert result == expected + + +def test_to_frame_duplicate_labels(): + # GH 45245 + data = [(1, 2), (3, 4)] + names = ["a", "a"] + index = pd.MultiIndex.from_tuples(data, names=names) + with pytest.raises(ValueError, match="Cannot create duplicate column labels"): + index.to_frame() + + result = index.to_frame(allow_duplicates=True) + expected = pd.DataFrame(data, index=index, columns=names) + tm.assert_frame_equal(result, expected) + + names = [None, 0] + index = pd.MultiIndex.from_tuples(data, names=names) + with pytest.raises(ValueError, match="Cannot create duplicate column labels"): + index.to_frame() + + result = index.to_frame(allow_duplicates=True) + expected = pd.DataFrame(data, index=index, columns=[0, 0]) + tm.assert_frame_equal(result, expected) + + +def test_to_frame_column_rangeindex(): + mi = pd.MultiIndex.from_arrays([[1, 2], ["a", "b"]]) + result = mi.to_frame().columns + expected = pd.RangeIndex(2) + tm.assert_index_equal(result, expected, exact=True) + + +def test_to_flat_index(idx): + expected = pd.Index( + ( + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ), + tupleize_cols=False, + ) + result = idx.to_flat_index() + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_copy.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..bbee5cecc6ac5abf8da4e0e44f5b6c43a109185d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_copy.py @@ -0,0 +1,96 @@ +from copy import ( + copy, + deepcopy, +) + +import pytest + +import pandas as pd +import pandas._testing as tm + + +def assert_multiindex_copied(copy, original): + # Levels should be (at least, shallow copied) + tm.assert_copy(copy.levels, original.levels) + tm.assert_almost_equal(copy.codes, original.codes) + + # Labels doesn't matter which way copied + tm.assert_almost_equal(copy.codes, original.codes) + assert copy.codes is not original.codes + + # Names doesn't matter which way copied + assert copy.names == original.names + assert copy.names is not original.names + + # Sort order should be copied + assert copy.sortorder == original.sortorder + + +def test_copy(idx): + i_copy = idx.copy() + + assert_multiindex_copied(i_copy, idx) + + +def test_shallow_copy(idx): + i_copy = idx._view() + + assert_multiindex_copied(i_copy, idx) + + +def test_view(idx): + i_view = idx.view() + assert_multiindex_copied(i_view, idx) + + +@pytest.mark.parametrize("func", [copy, deepcopy]) +def test_copy_and_deepcopy(func): + idx = pd.MultiIndex( + levels=[["foo", "bar"], ["fizz", "buzz"]], + codes=[[0, 0, 0, 1], [0, 0, 1, 1]], + names=["first", "second"], + ) + idx_copy = func(idx) + assert idx_copy is not idx + assert idx_copy.equals(idx) + + +@pytest.mark.parametrize("deep", [True, False]) +def test_copy_method(deep): + idx = pd.MultiIndex( + levels=[["foo", "bar"], ["fizz", "buzz"]], + codes=[[0, 0, 0, 1], [0, 0, 1, 1]], + names=["first", "second"], + ) + idx_copy = idx.copy(deep=deep) + assert idx_copy.equals(idx) + + +@pytest.mark.parametrize("deep", [True, False]) +@pytest.mark.parametrize( + "kwarg, value", + [ + ("names", ["third", "fourth"]), + ], +) +def test_copy_method_kwargs(deep, kwarg, value): + # gh-12309: Check that the "name" argument as well other kwargs are honored + idx = pd.MultiIndex( + levels=[["foo", "bar"], ["fizz", "buzz"]], + codes=[[0, 0, 0, 1], [0, 0, 1, 1]], + names=["first", "second"], + ) + idx_copy = idx.copy(**{kwarg: value, "deep": deep}) + assert getattr(idx_copy, kwarg) == value + + +def test_copy_deep_false_retains_id(): + # GH#47878 + idx = pd.MultiIndex( + levels=[["foo", "bar"], ["fizz", "buzz"]], + codes=[[0, 0, 0, 1], [0, 0, 1, 1]], + names=["first", "second"], + ) + + res = idx.copy(deep=False) + assert res._id is idx._id diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_drop.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_drop.py new file mode 100644 index 0000000000000000000000000000000000000000..596d929594314a0236f1183a31ff4aa9eea66847 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_drop.py @@ -0,0 +1,185 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_drop(idx): + dropped = idx.drop([("foo", "two"), ("qux", "one")]) + + index = pd.MultiIndex.from_tuples([("foo", "two"), ("qux", "one")]) + dropped2 = idx.drop(index) + + expected = idx[[0, 2, 3, 5]] + tm.assert_index_equal(dropped, expected) + tm.assert_index_equal(dropped2, expected) + + dropped = idx.drop(["bar"]) + expected = idx[[0, 1, 3, 4, 5]] + tm.assert_index_equal(dropped, expected) + + dropped = idx.drop("foo") + expected = idx[[2, 3, 4, 5]] + tm.assert_index_equal(dropped, expected) + + index = pd.MultiIndex.from_tuples([("bar", "two")]) + with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"): + idx.drop([("bar", "two")]) + with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"): + idx.drop(index) + with pytest.raises(KeyError, match=r"^'two'$"): + idx.drop(["foo", "two"]) + + # partially correct argument + mixed_index = pd.MultiIndex.from_tuples([("qux", "one"), ("bar", "two")]) + with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"): + idx.drop(mixed_index) + + # error='ignore' + dropped = idx.drop(index, errors="ignore") + expected = idx[[0, 1, 2, 3, 4, 5]] + tm.assert_index_equal(dropped, expected) + + dropped = idx.drop(mixed_index, errors="ignore") + expected = idx[[0, 1, 2, 3, 5]] + tm.assert_index_equal(dropped, expected) + + dropped = idx.drop(["foo", "two"], errors="ignore") + expected = idx[[2, 3, 4, 5]] + tm.assert_index_equal(dropped, expected) + + # mixed partial / full drop + dropped = idx.drop(["foo", ("qux", "one")]) + expected = idx[[2, 3, 5]] + tm.assert_index_equal(dropped, expected) + + # mixed partial / full drop / error='ignore' + mixed_index = ["foo", ("qux", "one"), "two"] + with pytest.raises(KeyError, match=r"^'two'$"): + idx.drop(mixed_index) + dropped = idx.drop(mixed_index, errors="ignore") + expected = idx[[2, 3, 5]] + tm.assert_index_equal(dropped, expected) + + +def test_droplevel_with_names(idx): + index = idx[idx.get_loc("foo")] + dropped = index.droplevel(0) + assert dropped.name == "second" + + index = pd.MultiIndex( + levels=[pd.Index(range(4)), pd.Index(range(4)), pd.Index(range(4))], + codes=[ + np.array([0, 0, 1, 2, 2, 2, 3, 3]), + np.array([0, 1, 0, 0, 0, 1, 0, 1]), + np.array([1, 0, 1, 1, 0, 0, 1, 0]), + ], + names=["one", "two", "three"], + ) + dropped = index.droplevel(0) + assert dropped.names == ("two", "three") + + dropped = index.droplevel("two") + expected = index.droplevel(1) + assert dropped.equals(expected) + + +def test_droplevel_list(): + index = pd.MultiIndex( + levels=[pd.Index(range(4)), pd.Index(range(4)), pd.Index(range(4))], + codes=[ + np.array([0, 0, 1, 2, 2, 2, 3, 3]), + np.array([0, 1, 0, 0, 0, 1, 0, 1]), + np.array([1, 0, 1, 1, 0, 0, 1, 0]), + ], + names=["one", "two", "three"], + ) + + dropped = index[:2].droplevel(["three", "one"]) + expected = index[:2].droplevel(2).droplevel(0) + assert dropped.equals(expected) + + dropped = index[:2].droplevel([]) + expected = index[:2] + assert dropped.equals(expected) + + msg = ( + "Cannot remove 3 levels from an index with 3 levels: " + "at least one level must be left" + ) + with pytest.raises(ValueError, match=msg): + index[:2].droplevel(["one", "two", "three"]) + + with pytest.raises(KeyError, match="'Level four not found'"): + index[:2].droplevel(["one", "four"]) + + +def test_drop_not_lexsorted(performance_warning): + # GH 12078 + + # define the lexsorted version of the multi-index + tuples = [("a", ""), ("b1", "c1"), ("b2", "c2")] + lexsorted_mi = pd.MultiIndex.from_tuples(tuples, names=["b", "c"]) + assert lexsorted_mi._is_lexsorted() + + # and the not-lexsorted version + df = pd.DataFrame( + columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]] + ) + df = df.pivot_table(index="a", columns=["b", "c"], values="d") + df = df.reset_index() + not_lexsorted_mi = df.columns + assert not not_lexsorted_mi._is_lexsorted() + + # compare the results + tm.assert_index_equal(lexsorted_mi, not_lexsorted_mi) + msg = "dropping on a non-lexsorted multi-index without a level parameter" + with tm.assert_produces_warning(performance_warning, match=msg): + tm.assert_index_equal(lexsorted_mi.drop("a"), not_lexsorted_mi.drop("a")) + + +def test_drop_with_nan_in_index(nulls_fixture): + # GH#18853 + mi = pd.MultiIndex.from_tuples([("blah", nulls_fixture)], names=["name", "date"]) + msg = r"labels \[Timestamp\('2001-01-01 00:00:00'\)\] not found in level" + with pytest.raises(KeyError, match=msg): + mi.drop(pd.Timestamp("2001"), level="date") + + +@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") +def test_drop_with_non_monotonic_duplicates(): + # GH#33494 + mi = pd.MultiIndex.from_tuples([(1, 2), (2, 3), (1, 2)]) + result = mi.drop((1, 2)) + expected = pd.MultiIndex.from_tuples([(2, 3)]) + tm.assert_index_equal(result, expected) + + +def test_single_level_drop_partially_missing_elements(): + # GH 37820 + + mi = pd.MultiIndex.from_tuples([(1, 2), (2, 2), (3, 2)]) + msg = r"labels \[4\] not found in level" + with pytest.raises(KeyError, match=msg): + mi.drop(4, level=0) + with pytest.raises(KeyError, match=msg): + mi.drop([1, 4], level=0) + msg = r"labels \[nan\] not found in level" + with pytest.raises(KeyError, match=msg): + mi.drop([np.nan], level=0) + with pytest.raises(KeyError, match=msg): + mi.drop([np.nan, 1, 2, 3], level=0) + + mi = pd.MultiIndex.from_tuples([(np.nan, 1), (1, 2)]) + msg = r"labels \['a'\] not found in level" + with pytest.raises(KeyError, match=msg): + mi.drop([np.nan, 1, "a"], level=0) + + +def test_droplevel_multiindex_one_level(): + # GH#37208 + index = pd.MultiIndex.from_tuples([(2,)], names=("b",)) + result = index.droplevel([]) + expected = pd.Index([2], name="b") + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_duplicates.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_duplicates.py new file mode 100644 index 0000000000000000000000000000000000000000..0f261fe47bc37b712e2a88e63df4739ce842f09e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_duplicates.py @@ -0,0 +1,370 @@ +from itertools import product +import re + +import numpy as np +import pytest + +from pandas._libs import hashtable + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def idx_dup(): + # compare tests/indexes/multi/conftest.py + major_axis = pd.Index(["foo", "bar", "baz", "qux"]) + minor_axis = pd.Index(["one", "two"]) + + major_codes = np.array([0, 0, 1, 0, 1, 1]) + minor_codes = np.array([0, 1, 0, 1, 0, 1]) + index_names = ["first", "second"] + mi = pd.MultiIndex( + levels=[major_axis, minor_axis], + codes=[major_codes, minor_codes], + names=index_names, + verify_integrity=False, + ) + return mi + + +@pytest.mark.parametrize("names", [None, ["first", "second"]]) +def test_unique(names): + mi = pd.MultiIndex.from_arrays([[1, 2, 1, 2], [1, 1, 1, 2]], names=names) + + res = mi.unique() + exp = pd.MultiIndex.from_arrays([[1, 2, 2], [1, 1, 2]], names=mi.names) + tm.assert_index_equal(res, exp) + + mi = pd.MultiIndex.from_arrays([list("aaaa"), list("abab")], names=names) + res = mi.unique() + exp = pd.MultiIndex.from_arrays([list("aa"), list("ab")], names=mi.names) + tm.assert_index_equal(res, exp) + + mi = pd.MultiIndex.from_arrays([list("aaaa"), list("aaaa")], names=names) + res = mi.unique() + exp = pd.MultiIndex.from_arrays([["a"], ["a"]], names=mi.names) + tm.assert_index_equal(res, exp) + + # GH #20568 - empty MI + mi = pd.MultiIndex.from_arrays([[], []], names=names) + res = mi.unique() + tm.assert_index_equal(mi, res) + + +def test_unique_datetimelike(): + idx1 = pd.DatetimeIndex( + ["2015-01-01", "2015-01-01", "2015-01-01", "2015-01-01", "NaT", "NaT"] + ) + idx2 = pd.DatetimeIndex( + ["2015-01-01", "2015-01-01", "2015-01-02", "2015-01-02", "NaT", "2015-01-01"], + tz="Asia/Tokyo", + ) + result = pd.MultiIndex.from_arrays([idx1, idx2]).unique() + + eidx1 = pd.DatetimeIndex(["2015-01-01", "2015-01-01", "NaT", "NaT"]) + eidx2 = pd.DatetimeIndex( + ["2015-01-01", "2015-01-02", "NaT", "2015-01-01"], tz="Asia/Tokyo" + ) + exp = pd.MultiIndex.from_arrays([eidx1, eidx2]) + tm.assert_index_equal(result, exp) + + +@pytest.mark.parametrize("level", [0, "first", 1, "second"]) +def test_unique_level(idx, level): + # GH #17896 - with level= argument + result = idx.unique(level=level) + expected = idx.get_level_values(level).unique() + tm.assert_index_equal(result, expected) + + # With already unique level + mi = pd.MultiIndex.from_arrays( + [[1, 3, 2, 4], [1, 3, 2, 5]], names=["first", "second"] + ) + result = mi.unique(level=level) + expected = mi.get_level_values(level) + tm.assert_index_equal(result, expected) + + # With empty MI + mi = pd.MultiIndex.from_arrays([[], []], names=["first", "second"]) + result = mi.unique(level=level) + expected = mi.get_level_values(level) + tm.assert_index_equal(result, expected) + + +def test_duplicate_multiindex_codes(): + # GH 17464 + # Make sure that a MultiIndex with duplicate levels throws a ValueError + msg = r"Level values must be unique. Duplicate values on level 0: \[[A', ]+\]" + with pytest.raises(ValueError, match=msg): + mi = pd.MultiIndex([["A"] * 10, range(10)], [[0] * 10, range(10)]) + + # And that using set_levels with duplicate levels fails + mi = pd.MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]]) + msg = r"Level values must be unique. Duplicate values on level 0: \[[AB', ]+\]" + with pytest.raises(ValueError, match=msg): + mi.set_levels([["A", "B", "A", "A", "B"], [2, 1, 3, -2, 5]]) + + +def test_duplicate_level_message_reports_only_duplicates(): + # GH 19432 - the message names the colliding values instead of dumping the + # whole level, and shows both members so 1 vs 1.0 reads as a collision + levels = [pd.Index([1, 1.0], dtype=object), range(3)] + msg = re.escape( + "Level values must be unique. Duplicate values on level 0: [1, 1.0]" + ) + with pytest.raises(ValueError, match=msg): + pd.MultiIndex(levels=levels, codes=[[0, 1], [1, 1]]) + + +def test_duplicate_level_message_truncates_long_levels(): + # GH 19432 - a large level must not produce a megabyte-long message + level = list(range(200)) + [0] * 20 + with pytest.raises(ValueError, match="Level values must be unique") as err: + pd.MultiIndex(levels=[level, range(3)], codes=[[0, 1], [1, 1]]) + msg = str(err.value) + assert len(msg) < 200 + assert "... (21 total)" in msg + + +@pytest.mark.parametrize("names", [["a", "b", "a"], [1, 1, 2], [1, "a", 1]]) +def test_duplicate_level_names(names): + # GH18872, GH19029 + mi = pd.MultiIndex.from_product([[0, 1]] * 3, names=names) + assert mi.names == names + + # With .rename() + mi = pd.MultiIndex.from_product([[0, 1]] * 3) + mi = mi.rename(names) + assert mi.names == names + + # With .rename(., level=) + mi.rename(names[1], level=1, inplace=True) + mi = mi.rename([names[0], names[2]], level=[0, 2]) + assert mi.names == names + + +def test_duplicate_meta_data(): + # GH 10115 + mi = pd.MultiIndex( + levels=[[0, 1], [0, 1, 2]], codes=[[0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]] + ) + + for idx in [ + mi, + mi.set_names([None, None]), + mi.set_names([None, "Num"]), + mi.set_names(["Upper", "Num"]), + ]: + assert idx.has_duplicates + assert idx.drop_duplicates().names == idx.names + + +def test_has_duplicates(idx, idx_dup): + # see fixtures + assert idx.is_unique is True + assert idx.has_duplicates is False + assert idx_dup.is_unique is False + assert idx_dup.has_duplicates is True + + mi = pd.MultiIndex( + levels=[[0, 1], [0, 1, 2]], codes=[[0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]] + ) + assert mi.is_unique is False + assert mi.has_duplicates is True + + # single instance of NaN + mi_nan = pd.MultiIndex( + levels=[["a", "b"], [0, 1]], codes=[[-1, 0, 0, 1, 1], [-1, 0, 1, 0, 1]] + ) + assert mi_nan.is_unique is True + assert mi_nan.has_duplicates is False + + # multiple instances of NaN + mi_nan_dup = pd.MultiIndex( + levels=[["a", "b"], [0, 1]], codes=[[-1, -1, 0, 0, 1, 1], [-1, -1, 0, 1, 0, 1]] + ) + assert mi_nan_dup.is_unique is False + assert mi_nan_dup.has_duplicates is True + + +def test_has_duplicates_from_tuples(): + # GH 9075 + t = [ + ("x", "out", "z", 5, "y", "in", "z", 169), + ("x", "out", "z", 7, "y", "in", "z", 119), + ("x", "out", "z", 9, "y", "in", "z", 135), + ("x", "out", "z", 13, "y", "in", "z", 145), + ("x", "out", "z", 14, "y", "in", "z", 158), + ("x", "out", "z", 16, "y", "in", "z", 122), + ("x", "out", "z", 17, "y", "in", "z", 160), + ("x", "out", "z", 18, "y", "in", "z", 180), + ("x", "out", "z", 20, "y", "in", "z", 143), + ("x", "out", "z", 21, "y", "in", "z", 128), + ("x", "out", "z", 22, "y", "in", "z", 129), + ("x", "out", "z", 25, "y", "in", "z", 111), + ("x", "out", "z", 28, "y", "in", "z", 114), + ("x", "out", "z", 29, "y", "in", "z", 121), + ("x", "out", "z", 31, "y", "in", "z", 126), + ("x", "out", "z", 32, "y", "in", "z", 155), + ("x", "out", "z", 33, "y", "in", "z", 123), + ("x", "out", "z", 12, "y", "in", "z", 144), + ] + + mi = pd.MultiIndex.from_tuples(t) + assert not mi.has_duplicates + + +@pytest.mark.parametrize("nlevels", [4, 8]) +@pytest.mark.parametrize("with_nulls", [True, False]) +def test_has_duplicates_overflow(nlevels, with_nulls): + # handle int64 overflow if possible + # no overflow with 4 + # overflow possible with 8 + codes = np.tile(np.arange(500), 2) + level = np.arange(500) + + if with_nulls: # inject some null values + codes[500] = -1 # common nan value + codes = [codes.copy() for i in range(nlevels)] + for i in range(nlevels): + codes[i][500 + i - nlevels // 2] = -1 + + codes += [np.array([-1, 1]).repeat(500)] + else: + codes = [codes] * nlevels + [np.arange(2).repeat(500)] + + levels = [level] * nlevels + [[0, 1]] + + # no dups + mi = pd.MultiIndex(levels=levels, codes=codes) + assert not mi.has_duplicates + + # with a dup + if with_nulls: + + def f(a): + return np.insert(a, 1000, a[0]) + + codes = list(map(f, codes)) + mi = pd.MultiIndex(levels=levels, codes=codes) + else: + values = mi.values.tolist() + mi = pd.MultiIndex.from_tuples([*values, values[0]]) + + assert mi.has_duplicates + + +@pytest.mark.parametrize( + "keep, expected", + [ + ("first", [False, False, False, True, True, False]), + ("last", [False, True, True, False, False, False]), + (False, [False, True, True, True, True, False]), + ], +) +def test_duplicated(idx_dup, keep, expected): + result = idx_dup.duplicated(keep=keep) + expected = np.array(expected) + tm.assert_numpy_array_equal(result, expected) + + +def test_duplicated_matches_hashtable(keep): + # GH 9125 + n, k = 6, 10 + levels = [np.arange(n), [str(i) for i in range(n)], 1000 + np.arange(n)] + rng = np.random.default_rng(2) + codes = [rng.choice(n, k * n) for _ in levels] + mi = pd.MultiIndex(levels=levels, codes=codes) + + result = mi.duplicated(keep=keep) + expected = hashtable.duplicated(mi.values, keep=keep) + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("val", [101, 102]) +def test_duplicated_with_nan(val): + # GH5873 + mi = pd.MultiIndex.from_arrays([[101, val], [3.5, np.nan]]) + assert not mi.has_duplicates + + tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(2, dtype="bool")) + + +@pytest.mark.parametrize("n", range(1, 6)) +@pytest.mark.parametrize("m", range(1, 5)) +def test_duplicated_with_nan_multi_shape(n, m): + # GH5873 + # all possible unique combinations, including nan + codes = product(range(-1, n), range(-1, m)) + mi = pd.MultiIndex( + levels=[list("abcde")[:n], list("WXYZ")[:m]], + codes=np.random.default_rng(2).permutation(list(codes)).T, + ) + assert len(mi) == (n + 1) * (m + 1) + assert not mi.has_duplicates + + tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(len(mi), dtype="bool")) + + +def test_duplicated_drop_duplicates(): + # GH#4060 + idx = pd.MultiIndex.from_arrays(([1, 2, 3, 1, 2, 3], [1, 1, 1, 1, 2, 2])) + + expected = np.array([False, False, False, True, False, False], dtype=bool) + duplicated = idx.duplicated() + tm.assert_numpy_array_equal(duplicated, expected) + assert duplicated.dtype == bool + expected = pd.MultiIndex.from_arrays(([1, 2, 3, 2, 3], [1, 1, 1, 2, 2])) + tm.assert_index_equal(idx.drop_duplicates(), expected) + + expected = np.array([True, False, False, False, False, False]) + duplicated = idx.duplicated(keep="last") + tm.assert_numpy_array_equal(duplicated, expected) + assert duplicated.dtype == bool + expected = pd.MultiIndex.from_arrays(([2, 3, 1, 2, 3], [1, 1, 1, 2, 2])) + tm.assert_index_equal(idx.drop_duplicates(keep="last"), expected) + + expected = np.array([True, False, False, True, False, False]) + duplicated = idx.duplicated(keep=False) + tm.assert_numpy_array_equal(duplicated, expected) + assert duplicated.dtype == bool + expected = pd.MultiIndex.from_arrays(([2, 3, 2, 3], [1, 1, 2, 2])) + tm.assert_index_equal(idx.drop_duplicates(keep=False), expected) + + +def test_duplicated_series_complex_numbers(complex_dtype): + # GH 17927 + expected = pd.Series( + [False, False, False, True, False, False, False, True, False, True], + dtype=bool, + ) + result = pd.Series( + [ + np.nan + np.nan * 1j, + 0, + 1j, + 1j, + 1, + 1 + 1j, + 1 + 2j, + 1 + 1j, + np.nan, + np.nan + np.nan * 1j, + ], + dtype=complex_dtype, + ).duplicated() + tm.assert_series_equal(result, expected) + + +def test_midx_unique_ea_dtype(): + # GH#48335 + vals_a = pd.Series([1, 2, pd.NA, pd.NA], dtype="Int64") + vals_b = np.array([1, 2, 3, 3]) + midx = pd.MultiIndex.from_arrays([vals_a, vals_b], names=["a", "b"]) + result = midx.unique() + + exp_vals_a = pd.Series([1, 2, pd.NA], dtype="Int64") + exp_vals_b = np.array([1, 2, 3]) + expected = pd.MultiIndex.from_arrays([exp_vals_a, exp_vals_b], names=["a", "b"]) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_equivalence.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_equivalence.py new file mode 100644 index 0000000000000000000000000000000000000000..d10f36de2250f4bc2d172b8b863dfb07a0f4bf7b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_equivalence.py @@ -0,0 +1,294 @@ +import numpy as np +import pytest + +from pandas.core.dtypes.common import is_any_real_numeric_dtype + +import pandas as pd +import pandas._testing as tm +from pandas.core.indexes.frozen import FrozenList + + +def test_equals(idx): + assert idx.equals(idx) + assert idx.equals(idx.copy()) + assert idx.equals(idx.astype(object)) + assert idx.equals(idx.to_flat_index()) + assert idx.equals(idx.to_flat_index().astype("category")) + + assert not idx.equals(list(idx)) + assert not idx.equals(np.array(idx)) + + same_values = pd.Index(idx, dtype=object) + assert idx.equals(same_values) + assert same_values.equals(idx) + + if idx.nlevels == 1: + # do not test MultiIndex + assert not idx.equals(pd.Series(idx)) + + +def test_equals_op(idx): + # GH9947, GH10637 + index_a = idx + + 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] + with pytest.raises(ValueError, match="Lengths must match"): + 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="Lengths must match"): + 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 = pd.Series(array_a) + series_b = pd.Series(array_b) + series_c = pd.Series(array_c) + series_d = pd.Series(array_d) + with pytest.raises(ValueError, match="Lengths must match"): + index_a == series_b + + tm.assert_series_equal(index_a == series_a, pd.Series(expected1)) + tm.assert_series_equal(index_a == series_c, pd.Series(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, pd.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, pd.Series(expected3)) + + +def test_compare_tuple(): + # GH#21517 + mi = pd.MultiIndex.from_product([[1, 2]] * 2) + + all_false = np.array([False, False, False, False]) + + result = mi == mi[0] + expected = np.array([True, False, False, False]) + tm.assert_numpy_array_equal(result, expected) + + result = mi != mi[0] + tm.assert_numpy_array_equal(result, ~expected) + + result = mi < mi[0] + tm.assert_numpy_array_equal(result, all_false) + + result = mi <= mi[0] + tm.assert_numpy_array_equal(result, expected) + + result = mi > mi[0] + tm.assert_numpy_array_equal(result, ~expected) + + result = mi >= mi[0] + tm.assert_numpy_array_equal(result, ~all_false) + + +def test_compare_tuple_strs(): + # GH#34180 + + mi = pd.MultiIndex.from_tuples([("a", "b"), ("b", "c"), ("c", "a")]) + + result = mi == ("c", "a") + expected = np.array([False, False, True]) + tm.assert_numpy_array_equal(result, expected) + + result = mi == ("c",) + expected = np.array([False, False, False]) + tm.assert_numpy_array_equal(result, expected) + + +def test_equals_multi(idx): + assert idx.equals(idx) + assert not idx.equals(idx.values) + assert idx.equals(pd.Index(idx.values)) + + assert idx.equal_levels(idx) + assert not idx.equals(idx[:-1]) + assert not idx.equals(idx[-1]) + + # different number of levels + index = pd.MultiIndex( + levels=[ + pd.Index(list(range(4))), + pd.Index(list(range(4))), + pd.Index(list(range(4))), + ], + codes=[ + np.array([0, 0, 1, 2, 2, 2, 3, 3]), + np.array([0, 1, 0, 0, 0, 1, 0, 1]), + np.array([1, 0, 1, 1, 0, 0, 1, 0]), + ], + ) + + index2 = pd.MultiIndex(levels=index.levels[:-1], codes=index.codes[:-1]) + assert not index.equals(index2) + assert not index.equal_levels(index2) + + # levels are different + major_axis = pd.Index(list(range(4))) + minor_axis = pd.Index(list(range(2))) + + major_codes = np.array([0, 0, 1, 2, 2, 3]) + minor_codes = np.array([0, 1, 0, 0, 1, 0]) + + index = pd.MultiIndex( + levels=[major_axis, minor_axis], codes=[major_codes, minor_codes] + ) + assert not idx.equals(index) + assert not idx.equal_levels(index) + + # some of the labels are different + major_axis = pd.Index(["foo", "bar", "baz", "qux"]) + minor_axis = pd.Index(["one", "two"]) + + major_codes = np.array([0, 0, 2, 2, 3, 3]) + minor_codes = np.array([0, 1, 0, 1, 0, 1]) + + index = pd.MultiIndex( + levels=[major_axis, minor_axis], codes=[major_codes, minor_codes] + ) + assert not idx.equals(index) + + +def test_identical(idx): + mi = idx.copy() + mi2 = idx.copy() + assert mi.identical(mi2) + + mi = mi.set_names(["new1", "new2"]) + assert mi.equals(mi2) + assert not mi.identical(mi2) + + mi2 = mi2.set_names(["new1", "new2"]) + assert mi.identical(mi2) + + mi4 = pd.Index(mi.tolist(), tupleize_cols=False) + assert not mi.identical(mi4) + assert mi.equals(mi4) + + +def test_equals_operator(idx): + # GH9785 + assert (idx == idx).all() + + +def test_equals_missing_values(): + # make sure take is not using -1 + i = pd.MultiIndex.from_tuples([(0, pd.NaT), (0, pd.Timestamp("20130101"))]) + result = i[0:1].equals(i[0]) + assert not result + result = i[1:2].equals(i[1]) + assert not result + + +def test_equals_missing_values_differently_sorted(): + # GH#38439 + mi1 = pd.MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)]) + mi2 = pd.MultiIndex.from_tuples([(np.nan, np.nan), (81.0, np.nan)]) + assert not mi1.equals(mi2) + + mi2 = pd.MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)]) + assert mi1.equals(mi2) + + +def test_is_(): + mi = pd.MultiIndex.from_tuples(zip(range(10), range(10), strict=True)) + assert mi.is_(mi) + assert mi.is_(mi.view()) + assert mi.is_(mi.view().view().view().view()) + mi2 = mi.view() + # names are metadata, they don't change id + mi2.names = ["A", "B"] + assert mi2.is_(mi) + assert mi.is_(mi2) + + assert not mi.is_(mi.set_names(["C", "D"])) + # levels are inherent properties, they change identity + mi3 = mi2.set_levels([list(range(10)), list(range(10))]) + assert not mi3.is_(mi2) + # shouldn't change + assert mi2.is_(mi) + mi4 = mi3.view() + + # GH 17464 - Remove duplicate MultiIndex levels + mi4 = mi4.set_levels([list(range(10)), list(range(10))]) + assert not mi4.is_(mi3) + mi5 = mi.view() + mi5 = mi5.set_levels(mi5.levels) + assert not mi5.is_(mi) + + +def test_is_all_dates(idx): + assert not idx._is_all_dates + + +def test_is_numeric(idx): + # MultiIndex is never numeric + assert not is_any_real_numeric_dtype(idx) + + +def test_multiindex_compare(): + # GH 21149 + # Ensure comparison operations for MultiIndex with nlevels == 1 + # behave consistently with those for MultiIndex with nlevels > 1 + + midx = pd.MultiIndex.from_product([[0, 1]]) + + # Equality self-test: MultiIndex object vs self + expected = pd.Series([True, True]) + result = pd.Series(midx == midx) + tm.assert_series_equal(result, expected) + + # Greater than comparison: MultiIndex object vs self + expected = pd.Series([False, False]) + result = pd.Series(midx > midx) + tm.assert_series_equal(result, expected) + + +def test_equals_ea_int_regular_int(): + # GH#46026 + mi1 = pd.MultiIndex.from_arrays([pd.Index([1, 2], dtype="Int64"), [3, 4]]) + mi2 = pd.MultiIndex.from_arrays([[1, 2], [3, 4]]) + assert not mi1.equals(mi2) + assert not mi2.equals(mi1) + + +def test_multiindex_equals_different_bit_widths(): + # GH#65700 - MultiIndex.equals should be value-based, not byte-based. + # There is no user-facing way to construct cross-dtype codes naturally; + # this reproduces the internal regression found in #65192. + midx1 = pd.MultiIndex.from_product([["a", "b", "c"], [1, 2]]) + midx2 = pd.MultiIndex.from_product([["a", "b", "c"], [1, 2]]) + midx2._codes = FrozenList([midx2.codes[0].astype("int64"), midx2.codes[1]]) + assert midx1.equals(midx2) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_formats.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_formats.py new file mode 100644 index 0000000000000000000000000000000000000000..759baf768fd501211ef5fd6a5479e6cf1e31cbc1 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_formats.py @@ -0,0 +1,203 @@ +import numpy as np +import pytest + +import pandas as pd + + +def test_repr_with_unicode_data(): + with pd.option_context("display.encoding", "UTF-8"): + d = {"a": ["\u05d0", 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]} + index = pd.DataFrame(d).set_index(["a", "b"]).index + assert "\\" not in repr(index) # we don't want unicode-escaped + + +def test_repr_roundtrip_raises(): + mi = pd.MultiIndex.from_product([list("ab"), range(3)], names=["first", "second"]) + msg = "Must pass both levels and codes" + with pytest.raises(TypeError, match=msg): + eval(repr(mi), dict(vars(pd))) + + +def test_unicode_string_with_unicode(): + d = {"a": ["\u05d0", 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]} + idx = pd.DataFrame(d).set_index(["a", "b"]).index + str(idx) + + +def test_repr_max_seq_item_setting(idx): + # GH10182 + idx = idx.repeat(50) + with pd.option_context("display.max_seq_items", None): + repr(idx) + assert "..." not in str(idx) + + +class TestRepr: + def test_unicode_repr_issues(self): + levels = [pd.Index(["a/\u03c3", "b/\u03c3", "c/\u03c3"]), pd.Index([0, 1])] + codes = [np.arange(3).repeat(2), np.tile(np.arange(2), 3)] + index = pd.MultiIndex(levels=levels, codes=codes) + + repr(index.levels) + repr(index.get_level_values(1)) + + def test_repr_max_seq_items_equal_to_n(self, idx): + # display.max_seq_items == n + with pd.option_context("display.max_seq_items", 6): + result = idx.__repr__() + expected = """\ +MultiIndex([('foo', 'one'), + ('foo', 'two'), + ('bar', 'one'), + ('baz', 'two'), + ('qux', 'one'), + ('qux', 'two')], + names=['first', 'second'])""" + assert result == expected + + def test_repr(self, idx): + result = idx[:1].__repr__() + expected = """\ +MultiIndex([('foo', 'one')], + names=['first', 'second'])""" + assert result == expected + + result = idx.__repr__() + expected = """\ +MultiIndex([('foo', 'one'), + ('foo', 'two'), + ('bar', 'one'), + ('baz', 'two'), + ('qux', 'one'), + ('qux', 'two')], + names=['first', 'second'])""" + assert result == expected + + with pd.option_context("display.max_seq_items", 5): + result = idx.__repr__() + expected = """\ +MultiIndex([('foo', 'one'), + ('foo', 'two'), + ... + ('qux', 'one'), + ('qux', 'two')], + names=['first', 'second'], length=6)""" + assert result == expected + + # display.max_seq_items == 1 + with pd.option_context("display.max_seq_items", 1): + result = idx.__repr__() + expected = """\ +MultiIndex([... + ('qux', 'two')], + names=['first', ...], length=6)""" + assert result == expected + + def test_rjust(self): + n = 1000 + ci = pd.CategoricalIndex(list("a" * n) + (["abc"] * n)) + dti = pd.date_range("2000-01-01", freq="s", periods=n * 2) + mi = pd.MultiIndex.from_arrays([ci, ci.codes + 9, dti], names=["a", "b", "dti"]) + result = mi[:1].__repr__() + expected = """\ +MultiIndex([('a', 9, '2000-01-01 00:00:00')], + names=['a', 'b', 'dti'])""" + assert result == expected + + result = mi[::500].__repr__() + expected = """\ +MultiIndex([( 'a', 9, '2000-01-01 00:00:00'), + ( 'a', 9, '2000-01-01 00:08:20'), + ('abc', 10, '2000-01-01 00:16:40'), + ('abc', 10, '2000-01-01 00:25:00')], + names=['a', 'b', 'dti'])""" + assert result == expected + + result = mi.__repr__() + expected = """\ +MultiIndex([( 'a', 9, '2000-01-01 00:00:00'), + ( 'a', 9, '2000-01-01 00:00:01'), + ( 'a', 9, '2000-01-01 00:00:02'), + ( 'a', 9, '2000-01-01 00:00:03'), + ( 'a', 9, '2000-01-01 00:00:04'), + ( 'a', 9, '2000-01-01 00:00:05'), + ( 'a', 9, '2000-01-01 00:00:06'), + ( 'a', 9, '2000-01-01 00:00:07'), + ( 'a', 9, '2000-01-01 00:00:08'), + ( 'a', 9, '2000-01-01 00:00:09'), + ... + ('abc', 10, '2000-01-01 00:33:10'), + ('abc', 10, '2000-01-01 00:33:11'), + ('abc', 10, '2000-01-01 00:33:12'), + ('abc', 10, '2000-01-01 00:33:13'), + ('abc', 10, '2000-01-01 00:33:14'), + ('abc', 10, '2000-01-01 00:33:15'), + ('abc', 10, '2000-01-01 00:33:16'), + ('abc', 10, '2000-01-01 00:33:17'), + ('abc', 10, '2000-01-01 00:33:18'), + ('abc', 10, '2000-01-01 00:33:19')], + names=['a', 'b', 'dti'], length=2000)""" + assert result == expected + + def test_tuple_width(self): + n = 1000 + ci = pd.CategoricalIndex(list("a" * n) + (["abc"] * n)) + dti = pd.date_range("2000-01-01", freq="s", periods=n * 2) + levels = [ci, ci.codes + 9, dti, dti, dti] + names = ["a", "b", "dti_1", "dti_2", "dti_3"] + mi = pd.MultiIndex.from_arrays(levels, names=names) + result = mi[:1].__repr__() + expected = """MultiIndex([('a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...)], + names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])""" # noqa: E501 + assert result == expected + + result = mi[:10].__repr__() + expected = """\ +MultiIndex([('a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...), + ('a', 9, '2000-01-01 00:00:01', '2000-01-01 00:00:01', ...), + ('a', 9, '2000-01-01 00:00:02', '2000-01-01 00:00:02', ...), + ('a', 9, '2000-01-01 00:00:03', '2000-01-01 00:00:03', ...), + ('a', 9, '2000-01-01 00:00:04', '2000-01-01 00:00:04', ...), + ('a', 9, '2000-01-01 00:00:05', '2000-01-01 00:00:05', ...), + ('a', 9, '2000-01-01 00:00:06', '2000-01-01 00:00:06', ...), + ('a', 9, '2000-01-01 00:00:07', '2000-01-01 00:00:07', ...), + ('a', 9, '2000-01-01 00:00:08', '2000-01-01 00:00:08', ...), + ('a', 9, '2000-01-01 00:00:09', '2000-01-01 00:00:09', ...)], + names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])""" + assert result == expected + + result = mi.__repr__() + expected = """\ +MultiIndex([( 'a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...), + ( 'a', 9, '2000-01-01 00:00:01', '2000-01-01 00:00:01', ...), + ( 'a', 9, '2000-01-01 00:00:02', '2000-01-01 00:00:02', ...), + ( 'a', 9, '2000-01-01 00:00:03', '2000-01-01 00:00:03', ...), + ( 'a', 9, '2000-01-01 00:00:04', '2000-01-01 00:00:04', ...), + ( 'a', 9, '2000-01-01 00:00:05', '2000-01-01 00:00:05', ...), + ( 'a', 9, '2000-01-01 00:00:06', '2000-01-01 00:00:06', ...), + ( 'a', 9, '2000-01-01 00:00:07', '2000-01-01 00:00:07', ...), + ( 'a', 9, '2000-01-01 00:00:08', '2000-01-01 00:00:08', ...), + ( 'a', 9, '2000-01-01 00:00:09', '2000-01-01 00:00:09', ...), + ... + ('abc', 10, '2000-01-01 00:33:10', '2000-01-01 00:33:10', ...), + ('abc', 10, '2000-01-01 00:33:11', '2000-01-01 00:33:11', ...), + ('abc', 10, '2000-01-01 00:33:12', '2000-01-01 00:33:12', ...), + ('abc', 10, '2000-01-01 00:33:13', '2000-01-01 00:33:13', ...), + ('abc', 10, '2000-01-01 00:33:14', '2000-01-01 00:33:14', ...), + ('abc', 10, '2000-01-01 00:33:15', '2000-01-01 00:33:15', ...), + ('abc', 10, '2000-01-01 00:33:16', '2000-01-01 00:33:16', ...), + ('abc', 10, '2000-01-01 00:33:17', '2000-01-01 00:33:17', ...), + ('abc', 10, '2000-01-01 00:33:18', '2000-01-01 00:33:18', ...), + ('abc', 10, '2000-01-01 00:33:19', '2000-01-01 00:33:19', ...)], + names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'], length=2000)""" + assert result == expected + + def test_multiindex_long_element(self): + # Non-regression test towards GH#52960 + data = pd.MultiIndex.from_tuples([("c" * 62,)]) + + expected = ( + "MultiIndex([('cccccccccccccccccccccccccccccccccccccccc" + "cccccccccccccccccccccc',)],\n )" + ) + assert str(data) == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_get_level_values.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_get_level_values.py new file mode 100644 index 0000000000000000000000000000000000000000..c18f1f9ac6ece69ad2c98477340ccbd6804d073d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_get_level_values.py @@ -0,0 +1,123 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestGetLevelValues: + def test_get_level_values_box_datetime64(self): + dates = pd.date_range("1/1/2000", periods=4) + levels = [dates, [0, 1]] + codes = [[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]] + + index = pd.MultiIndex(levels=levels, codes=codes) + + assert isinstance(index.get_level_values(0)[0], pd.Timestamp) + + +def test_get_level_values(idx): + result = idx.get_level_values(0) + expected = pd.Index(["foo", "foo", "bar", "baz", "qux", "qux"], name="first") + tm.assert_index_equal(result, expected) + assert result.name == "first" + + result = idx.get_level_values("first") + expected = idx.get_level_values(0) + tm.assert_index_equal(result, expected) + + # GH 10460 + index = pd.MultiIndex( + levels=[pd.CategoricalIndex(["A", "B"]), pd.CategoricalIndex([1, 2, 3])], + codes=[np.array([0, 0, 0, 1, 1, 1]), np.array([0, 1, 2, 0, 1, 2])], + ) + + exp = pd.CategoricalIndex(["A", "A", "A", "B", "B", "B"]) + tm.assert_index_equal(index.get_level_values(0), exp) + exp = pd.CategoricalIndex([1, 2, 3, 1, 2, 3]) + tm.assert_index_equal(index.get_level_values(1), exp) + + +def test_get_level_values_all_na(): + # GH#17924 when level entirely consists of nan + arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]] + index = pd.MultiIndex.from_arrays(arrays) + result = index.get_level_values(0) + expected = pd.Index([np.nan, np.nan, np.nan], dtype=np.float64) + tm.assert_index_equal(result, expected) + + result = index.get_level_values(1) + expected = pd.Index(["a", np.nan, 1], dtype=object) + tm.assert_index_equal(result, expected) + + +def test_get_level_values_int_with_na(): + # GH#17924 + arrays = [["a", "b", "b"], [1, np.nan, 2]] + index = pd.MultiIndex.from_arrays(arrays) + result = index.get_level_values(1) + expected = pd.Index([1, np.nan, 2]) + tm.assert_index_equal(result, expected) + + arrays = [["a", "b", "b"], [np.nan, np.nan, 2]] + index = pd.MultiIndex.from_arrays(arrays) + result = index.get_level_values(1) + expected = pd.Index([np.nan, np.nan, 2]) + tm.assert_index_equal(result, expected) + + +def test_get_level_values_na(): + arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]] + index = pd.MultiIndex.from_arrays(arrays) + result = index.get_level_values(0) + expected = pd.Index([np.nan, np.nan, np.nan]) + tm.assert_index_equal(result, expected) + + result = index.get_level_values(1) + expected = pd.Index(["a", np.nan, 1]) + tm.assert_index_equal(result, expected) + + arrays = [["a", "b", "b"], pd.DatetimeIndex([0, 1, pd.NaT])] + index = pd.MultiIndex.from_arrays(arrays) + result = index.get_level_values(1) + expected = pd.DatetimeIndex([0, 1, pd.NaT]) + tm.assert_index_equal(result, expected) + + arrays = [[], []] + index = pd.MultiIndex.from_arrays(arrays) + result = index.get_level_values(0) + expected = pd.Index([], dtype=object) + tm.assert_index_equal(result, expected) + + +def test_get_level_values_when_periods(): + # GH33131. See also discussion in GH32669. + # This test can probably be removed when PeriodIndex._engine is removed. + idx = pd.MultiIndex.from_arrays( + [pd.PeriodIndex([pd.Period("2019Q1"), pd.Period("2019Q2")], name="b")] + ) + idx2 = pd.MultiIndex.from_arrays( + [idx._get_level_values(level) for level in range(idx.nlevels)] + ) + assert all(x.is_monotonic_increasing for x in idx2.levels) + + +def test_values_loses_freq_of_underlying_index(): + # GH#49054 + idx = pd.DatetimeIndex(pd.date_range("20200101", periods=3, freq="BME")) + expected = idx.copy(deep=True) + idx2 = pd.Index([1, 2, 3]) + midx = pd.MultiIndex(levels=[idx, idx2], codes=[[0, 1, 2], [0, 1, 2]]) + midx.values + assert idx.freq is not None + tm.assert_index_equal(idx, expected) + + +def test_get_level_values_gets_frequency_correctly(): + # GH#57949 GH#58327 + datetime_index = pd.date_range( + start=pd.to_datetime("1/1/2018"), periods=4, freq="YS" + ) + other_index = ["A"] + multi_index = pd.MultiIndex.from_product([datetime_index, other_index]) + + assert multi_index.get_level_values(0).freq == datetime_index.freq diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_get_set.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_get_set.py new file mode 100644 index 0000000000000000000000000000000000000000..04538ce63165e91f10d1e985727476399fec0a05 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_get_set.py @@ -0,0 +1,406 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +from pandas.core.dtypes.dtypes import DatetimeTZDtype + +import pandas as pd +import pandas._testing as tm + + +def test_get_level_number_integer(idx): + idx.names = [1, 0] + assert idx._get_level_number(1) == 0 + assert idx._get_level_number(0) == 1 + msg = "Too many levels: Index has only 2 levels, not 3" + with pytest.raises(IndexError, match=msg): + idx._get_level_number(2) + with pytest.raises(KeyError, match="Level fourth not found"): + idx._get_level_number("fourth") + + +def test_get_dtypes(using_infer_string): + # Test MultiIndex.dtypes (# Gh37062) + idx_multitype = pd.MultiIndex.from_product( + [ + [1, 2, 3], + ["a", "b", "c"], + pd.date_range("20200101", periods=2, tz="UTC", unit="ns"), + ], + names=["int", "string", "dt"], + ) + + exp = "object" if not using_infer_string else pd.StringDtype(na_value=np.nan) + expected = pd.Series( + { + "int": np.dtype("int64"), + "string": exp, + "dt": DatetimeTZDtype(tz="utc"), + } + ) + tm.assert_series_equal(expected, idx_multitype.dtypes) + + +def test_get_dtypes_no_level_name(using_infer_string): + # Test MultiIndex.dtypes (# GH38580 ) + idx_multitype = pd.MultiIndex.from_product( + [ + [1, 2, 3], + ["a", "b", "c"], + pd.date_range("20200101", periods=2, tz="UTC", unit="ns"), + ], + ) + exp = "object" if not using_infer_string else pd.StringDtype(na_value=np.nan) + expected = pd.Series( + { + "level_0": np.dtype("int64"), + "level_1": exp, + "level_2": DatetimeTZDtype(tz="utc"), + } + ) + tm.assert_series_equal(expected, idx_multitype.dtypes) + + +def test_get_dtypes_duplicate_level_names(using_infer_string): + # Test MultiIndex.dtypes with non-unique level names (# GH45174) + result = pd.MultiIndex.from_product( + [ + [1, 2, 3], + ["a", "b", "c"], + pd.date_range("20200101", periods=2, tz="UTC", unit="ns"), + ], + names=["A", "A", "A"], + ).dtypes + exp = "object" if not using_infer_string else pd.StringDtype(na_value=np.nan) + expected = pd.Series( + [np.dtype("int64"), exp, DatetimeTZDtype(tz="utc")], + index=["A", "A", "A"], + ) + tm.assert_series_equal(result, expected) + + +def test_get_level_number_out_of_bounds(multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + with pytest.raises(IndexError, match="Too many levels"): + frame.index._get_level_number(2) + with pytest.raises(IndexError, match="not a valid level number"): + frame.index._get_level_number(-3) + + +def test_set_name_methods(idx): + # so long as these are synonyms, we don't need to test set_names + index_names = ["first", "second"] + assert idx.rename == idx.set_names + new_names = [name + "SUFFIX" for name in index_names] + ind = idx.set_names(new_names) + assert idx.names == index_names + assert ind.names == new_names + msg = "Length of names must match number of levels in MultiIndex" + with pytest.raises(ValueError, match=msg): + ind.set_names(new_names + new_names) + new_names2 = [name + "SUFFIX2" for name in new_names] + res = ind.set_names(new_names2, inplace=True) + assert res is None + assert ind.names == new_names2 + + # set names for specific level (# GH7792) + ind = idx.set_names(new_names[0], level=0) + assert idx.names == index_names + assert ind.names == [new_names[0], index_names[1]] + + res = ind.set_names(new_names2[0], level=0, inplace=True) + assert res is None + assert ind.names == [new_names2[0], index_names[1]] + + # set names for multiple levels + ind = idx.set_names(new_names, level=[0, 1]) + assert idx.names == index_names + assert ind.names == new_names + + res = ind.set_names(new_names2, level=[0, 1], inplace=True) + assert res is None + assert ind.names == new_names2 + + +def test_set_levels_codes_directly(idx): + # setting levels/codes directly raises AttributeError + + levels = idx.levels + new_levels = [[lev + "a" for lev in level] for level in levels] + + codes = idx.codes + major_codes, minor_codes = codes + major_codes = [(x + 1) % 3 for x in major_codes] + minor_codes = [(x + 1) % 1 for x in minor_codes] + new_codes = [major_codes, minor_codes] + + msg = "Can't set attribute" + with pytest.raises(AttributeError, match=msg): + idx.levels = new_levels + + msg = "property 'codes' of 'MultiIndex' object has no setter" + with pytest.raises(AttributeError, match=msg): + idx.codes = new_codes + + +def test_set_levels(idx): + # side note - you probably wouldn't want to use levels and codes + # directly like this - but it is possible. + original_index = idx.copy() + levels = idx.levels + codes = idx.codes + names = idx.names + new_levels = [[lev + "a" for lev in level] for level in levels] + + # level changing [w/o mutation] + result = idx.set_levels(new_levels) + expected = pd.MultiIndex(levels=new_levels, codes=codes, names=names) + tm.assert_index_equal(result, expected) + tm.assert_index_equal(idx, original_index) + + # level changing specific level [w/o mutation] + result = idx.set_levels(new_levels[0], level=0) + expected = pd.MultiIndex( + levels=[new_levels[0], levels[1]], codes=codes, names=names + ) + tm.assert_index_equal(result, expected) + tm.assert_index_equal(idx, original_index) + + result = idx.set_levels(new_levels[1], level=1) + expected = pd.MultiIndex( + levels=[levels[0], new_levels[1]], codes=codes, names=names + ) + tm.assert_index_equal(result, expected) + tm.assert_index_equal(idx, original_index) + + # level changing multiple levels [w/o mutation] + result = idx.set_levels(new_levels, level=[0, 1]) + expected = pd.MultiIndex(levels=new_levels, codes=codes, names=names) + tm.assert_index_equal(result, expected) + tm.assert_index_equal(idx, original_index) + + # illegal level changing should not change levels + # GH 13754 + with pytest.raises(ValueError, match="^On"): + idx.set_levels(["c"], level=0) + tm.assert_index_equal(idx, original_index) + + with pytest.raises(ValueError, match="^On"): + idx.set_codes([0, 1, 2, 3, 4, 5], level=0) + tm.assert_index_equal(idx, original_index) + + with pytest.raises(TypeError, match="^Levels"): + idx.set_levels("c", level=0) + tm.assert_index_equal(idx, original_index) + + with pytest.raises(TypeError, match="^Codes"): + idx.set_codes(1, level=0) + tm.assert_index_equal(idx, original_index) + + +def test_set_codes(idx): + # side note - you probably wouldn't want to use levels and codes + # directly like this - but it is possible. + original_index = idx.copy() + levels = idx.levels + codes = idx.codes + names = idx.names + major_codes, minor_codes = codes + major_codes = [(x + 1) % 3 for x in major_codes] + minor_codes = [(x + 1) % 1 for x in minor_codes] + new_codes = [major_codes, minor_codes] + + # changing codes w/o mutation + result = idx.set_codes(new_codes) + expected = pd.MultiIndex(levels=levels, codes=new_codes, names=names) + tm.assert_index_equal(result, expected) + tm.assert_index_equal(idx, original_index) + + # codes changing specific level w/o mutation + result = idx.set_codes(new_codes[0], level=0) + expected = pd.MultiIndex(levels=levels, codes=[new_codes[0], codes[1]], names=names) + tm.assert_index_equal(result, expected) + tm.assert_index_equal(idx, original_index) + + result = idx.set_codes(new_codes[1], level=1) + expected = pd.MultiIndex(levels=levels, codes=[codes[0], new_codes[1]], names=names) + tm.assert_index_equal(result, expected) + tm.assert_index_equal(idx, original_index) + + # codes changing multiple levels w/o mutation + result = idx.set_codes(new_codes, level=[0, 1]) + expected = pd.MultiIndex(levels=levels, codes=new_codes, names=names) + tm.assert_index_equal(result, expected) + tm.assert_index_equal(idx, original_index) + + # label changing for levels of different magnitude of categories + ind = pd.MultiIndex.from_tuples([(0, i) for i in range(130)]) + new_codes = range(129, -1, -1) + expected = pd.MultiIndex.from_tuples([(0, i) for i in new_codes]) + + # [w/o mutation] + result = ind.set_codes(codes=new_codes, level=1) + tm.assert_index_equal(result, expected) + + +def test_set_levels_codes_names_bad_input(idx): + levels, codes = idx.levels, idx.codes + names = idx.names + + with pytest.raises(ValueError, match="Length of levels"): + idx.set_levels([levels[0]]) + + with pytest.raises(ValueError, match="Length of codes"): + idx.set_codes([codes[0]]) + + with pytest.raises(ValueError, match="Length of names"): + idx.set_names([names[0]]) + + # shouldn't scalar data error, instead should demand list-like + with pytest.raises(TypeError, match="list of lists-like"): + idx.set_levels(levels[0]) + + # shouldn't scalar data error, instead should demand list-like + with pytest.raises(TypeError, match="list of lists-like"): + idx.set_codes(codes[0]) + + # shouldn't scalar data error, instead should demand list-like + with pytest.raises(TypeError, match="list-like"): + idx.set_names(names[0]) + + # should have equal lengths + with pytest.raises(TypeError, match="list of lists-like"): + idx.set_levels(levels[0], level=[0, 1]) + + with pytest.raises(TypeError, match="list-like"): + idx.set_levels(levels, level=0) + + # should have equal lengths + with pytest.raises(TypeError, match="list of lists-like"): + idx.set_codes(codes[0], level=[0, 1]) + + with pytest.raises(TypeError, match="list-like"): + idx.set_codes(codes, level=0) + + # GH#66287 nested value with a scalar level + with pytest.raises(TypeError, match="must be list-like, not a list of list-likes"): + idx.set_levels([levels[0]], level=0) + + with pytest.raises(TypeError, match="must be list-like, not a list of list-likes"): + idx.set_codes([codes[0]], level=0) + + # should have equal lengths + with pytest.raises(ValueError, match="Length of names"): + idx.set_names(names[0], level=[0, 1]) + + with pytest.raises(TypeError, match="Names must be a"): + idx.set_names(names, level=0) + + +@pytest.mark.parametrize("inplace", [True, False]) +def test_set_names_with_nlevel_1(inplace): + # GH 21149 + # Ensure that .set_names for MultiIndex with + # nlevels == 1 does not raise any errors + expected = pd.MultiIndex(levels=[[0, 1]], codes=[[0, 1]], names=["first"]) + m = pd.MultiIndex.from_product([[0, 1]]) + result = m.set_names("first", level=0, inplace=inplace) + + if inplace: + result = m + + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("ordered", [True, False]) +def test_set_levels_categorical(ordered): + # GH13854 + index = pd.MultiIndex.from_arrays([list("xyzx"), [0, 1, 2, 3]]) + + cidx = pd.CategoricalIndex(list("bac"), ordered=ordered) + result = index.set_levels(cidx, level=0) + expected = pd.MultiIndex(levels=[cidx, [0, 1, 2, 3]], codes=index.codes) + tm.assert_index_equal(result, expected) + + result_lvl = result.get_level_values(0) + expected_lvl = pd.CategoricalIndex( + list("bacb"), categories=cidx.categories, ordered=cidx.ordered + ) + tm.assert_index_equal(result_lvl, expected_lvl) + + +def test_set_value_keeps_names(): + # motivating example from #3742 + lev1 = ["hans", "hans", "hans", "grethe", "grethe", "grethe"] + lev2 = ["1", "2", "3"] * 2 + idx = pd.MultiIndex.from_arrays([lev1, lev2], names=["Name", "Number"]) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((6, 4)), + columns=["one", "two", "three", "four"], + index=idx, + ) + df = df.sort_index() + assert df.index.names == ("Name", "Number") + with tm.assert_produces_warning(Pandas4Warning, match="does not exist"): + df.at[("grethe", "4"), "one"] = 99.34 + assert df.index.names == ("Name", "Number") + + +def test_set_levels_with_iterable(): + # GH23273 + sizes = [1, 2, 3] + colors = ["black"] * 3 + index = pd.MultiIndex.from_arrays([sizes, colors], names=["size", "color"]) + + result = index.set_levels(map(int, ["3", "2", "1"]), level="size") + + expected_sizes = [3, 2, 1] + expected = pd.MultiIndex.from_arrays( + [expected_sizes, colors], names=["size", "color"] + ) + tm.assert_index_equal(result, expected) + + +def test_set_empty_level(): + # GH#48636 + midx = pd.MultiIndex.from_arrays([[]], names=["A"]) + result = midx.set_levels(pd.DatetimeIndex([]), level=0) + expected = pd.MultiIndex.from_arrays([pd.DatetimeIndex([])], names=["A"]) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("level", [None, ["A", "B"]]) +def test_set_levels_codes_empty_outer_raises(level): + # GH#16147 an empty outer sequence should raise a clear ValueError + # rather than IndexError when level is None or list-like + midx = pd.MultiIndex(levels=[[], []], codes=[[], []], names=["A", "B"]) + with pytest.raises(ValueError, match="non-zero number of levels"): + midx.set_levels([], level=level) + with pytest.raises(ValueError, match="Length of codes must match"): + midx.set_codes([], level=level) + + +def test_set_levels_pos_args_removal(): + # https://github.com/pandas-dev/pandas/issues/41485 + idx = pd.MultiIndex.from_tuples( + [ + (1, "one"), + (3, "one"), + ], + names=["foo", "bar"], + ) + with pytest.raises(TypeError, match="positional arguments"): + idx.set_levels(["a", "b", "c"], 0) + + with pytest.raises(TypeError, match="positional arguments"): + idx.set_codes([[0, 1], [1, 0]], 0) + + +def test_set_levels_categorical_keep_dtype(): + # GH#52125 + midx = pd.MultiIndex.from_arrays([[5, 6]]) + result = midx.set_levels(levels=pd.Categorical([1, 2]), level=0) + expected = pd.MultiIndex.from_arrays([pd.Categorical([1, 2])]) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..07eabe456321f1f88f1c461a4ab0ad01a02ac28d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_indexing.py @@ -0,0 +1,1622 @@ +from collections import namedtuple +from datetime import timedelta +import re + +import numpy as np +import pytest + +from pandas._libs import index as libindex +from pandas.compat import PY312 +from pandas.errors import ( + InvalidIndexError, + UnsortedIndexError, +) + +import pandas as pd +import pandas._testing as tm + + +class TestSliceLocs: + def test_slice_locs_partial(self, idx): + sorted_idx, _ = idx.sortlevel(0) + + result = sorted_idx.slice_locs(("foo", "two"), ("qux", "one")) + assert result == (1, 5) + + result = sorted_idx.slice_locs(None, ("qux", "one")) + assert result == (0, 5) + + result = sorted_idx.slice_locs(("foo", "two"), None) + assert result == (1, len(sorted_idx)) + + result = sorted_idx.slice_locs("bar", "baz") + assert result == (2, 4) + + def test_slice_locs(self): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((50, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=50, freq="B"), + ) + stacked = df.stack() + idx = stacked.index + + slob = slice(*idx.slice_locs(df.index[5], df.index[15])) + sliced = stacked[slob] + expected = df[5:16].stack() + tm.assert_almost_equal(sliced.values, expected.values) + + slob = slice( + *idx.slice_locs( + df.index[5] + timedelta(seconds=30), + df.index[15] - timedelta(seconds=30), + ) + ) + sliced = stacked[slob] + expected = df[6:15].stack() + tm.assert_almost_equal(sliced.values, expected.values) + + def test_slice_locs_with_type_mismatch(self): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ) + stacked = df.stack() + idx = stacked.index + with pytest.raises(TypeError, match="^Level type mismatch"): + idx.slice_locs((1, 3)) + with pytest.raises(TypeError, match="^Level type mismatch"): + idx.slice_locs(df.index[5] + timedelta(seconds=30), (5, 2)) + df = pd.DataFrame( + np.ones((5, 5)), + index=pd.Index([f"i-{i}" for i in range(5)], name="a"), + columns=pd.Index([f"i-{i}" for i in range(5)], name="a"), + ) + stacked = df.stack() + idx = stacked.index + with pytest.raises(TypeError, match="^Level type mismatch"): + idx.slice_locs(timedelta(seconds=30)) + # TODO: Try creating a UnicodeDecodeError in exception message + with pytest.raises(TypeError, match="^Level type mismatch"): + idx.slice_locs(df.index[1], (16, "a")) + + def test_slice_locs_not_sorted(self): + index = pd.MultiIndex( + levels=[ + pd.Index(np.arange(4)), + pd.Index(np.arange(4)), + pd.Index(np.arange(4)), + ], + codes=[ + np.array([0, 0, 1, 2, 2, 2, 3, 3]), + np.array([0, 1, 0, 0, 0, 1, 0, 1]), + np.array([1, 0, 1, 1, 0, 0, 1, 0]), + ], + ) + msg = "Key length.*was greater than MultiIndex lexsort depth" + with pytest.raises(KeyError, match=msg): + index.slice_locs((1, 0, 1), (2, 1, 0)) + + # works + sorted_index, _ = index.sortlevel(0) + # should there be a test case here??? + sorted_index.slice_locs((1, 0, 1), (2, 1, 0)) + + def test_slice_locs_not_contained(self): + # some searchsorted action + + index = pd.MultiIndex( + levels=[[0, 2, 4, 6], [0, 2, 4]], + codes=[[0, 0, 0, 1, 1, 2, 3, 3, 3], [0, 1, 2, 1, 2, 2, 0, 1, 2]], + ) + + result = index.slice_locs((1, 0), (5, 2)) + assert result == (3, 6) + + result = index.slice_locs(1, 5) + assert result == (3, 6) + + result = index.slice_locs((2, 2), (5, 2)) + assert result == (3, 6) + + result = index.slice_locs(2, 5) + assert result == (3, 6) + + result = index.slice_locs((1, 0), (6, 3)) + assert result == (3, 8) + + result = index.slice_locs(-1, 10) + assert result == (0, len(index)) + + @pytest.mark.parametrize( + "index_arr,expected,start_idx,end_idx", + [ + ([[np.nan, "a", "b"], ["c", "d", "e"]], (0, 3), np.nan, None), + ([[np.nan, "a", "b"], ["c", "d", "e"]], (0, 3), np.nan, "b"), + ([[np.nan, "a", "b"], ["c", "d", "e"]], (0, 3), np.nan, ("b", "e")), + ([["a", "b", "c"], ["d", np.nan, "e"]], (1, 3), ("b", np.nan), None), + ([["a", "b", "c"], ["d", np.nan, "e"]], (1, 3), ("b", np.nan), "c"), + ([["a", "b", "c"], ["d", np.nan, "e"]], (1, 3), ("b", np.nan), ("c", "e")), + ], + ) + def test_slice_locs_with_missing_value( + self, index_arr, expected, start_idx, end_idx + ): + # issue 19132 + idx = pd.MultiIndex.from_arrays(index_arr) + result = idx.slice_locs(start=start_idx, end=end_idx) + assert result == expected + + +class TestPutmask: + def test_putmask_with_wrong_mask(self, idx): + # GH18368 + + msg = "putmask: mask and data must be the same size" + with pytest.raises(ValueError, match=msg): + idx.putmask(np.ones(len(idx) + 1, np.bool_), 1) + + with pytest.raises(ValueError, match=msg): + idx.putmask(np.ones(len(idx) - 1, np.bool_), 1) + + with pytest.raises(ValueError, match=msg): + idx.putmask("foo", 1) + + def test_putmask_multiindex_other(self): + # GH#43212 `value` is also a MultiIndex + + left = pd.MultiIndex.from_tuples([(np.nan, 6), (np.nan, 6), ("a", 4)]) + right = pd.MultiIndex.from_tuples([("a", 1), ("a", 1), ("d", 1)]) + mask = np.array([True, True, False]) + + result = left.putmask(mask, right) + + expected = pd.MultiIndex.from_tuples([right[0], right[1], left[2]]) + tm.assert_index_equal(result, expected) + + def test_putmask_keep_dtype(self, any_numeric_ea_dtype): + # GH#49830 + midx = pd.MultiIndex.from_arrays( + [pd.Series([1, 2, 3], dtype=any_numeric_ea_dtype), [10, 11, 12]] + ) + midx2 = pd.MultiIndex.from_arrays( + [pd.Series([5, 6, 7], dtype=any_numeric_ea_dtype), [-1, -2, -3]] + ) + result = midx.putmask([True, False, False], midx2) + expected = pd.MultiIndex.from_arrays( + [pd.Series([5, 2, 3], dtype=any_numeric_ea_dtype), [-1, 11, 12]] + ) + tm.assert_index_equal(result, expected) + + def test_putmask_keep_dtype_shorter_value(self, any_numeric_ea_dtype): + # GH#49830 + midx = pd.MultiIndex.from_arrays( + [pd.Series([1, 2, 3], dtype=any_numeric_ea_dtype), [10, 11, 12]] + ) + midx2 = pd.MultiIndex.from_arrays( + [pd.Series([5], dtype=any_numeric_ea_dtype), [-1]] + ) + result = midx.putmask([True, False, False], midx2) + expected = pd.MultiIndex.from_arrays( + [pd.Series([5, 2, 3], dtype=any_numeric_ea_dtype), [-1, 11, 12]] + ) + tm.assert_index_equal(result, expected) + + +class TestGetIndexer: + def test_get_indexer(self): + major_axis = pd.Index(np.arange(4)) + minor_axis = pd.Index(np.arange(2)) + + major_codes = np.array([0, 0, 1, 2, 2, 3, 3], dtype=np.intp) + minor_codes = np.array([0, 1, 0, 0, 1, 0, 1], dtype=np.intp) + + index = pd.MultiIndex( + levels=[major_axis, minor_axis], codes=[major_codes, minor_codes] + ) + idx1 = index[:5] + idx2 = index[[1, 3, 5]] + + r1 = idx1.get_indexer(idx2) + tm.assert_almost_equal(r1, np.array([1, 3, -1], dtype=np.intp)) + + r1 = idx2.get_indexer(idx1, method="pad") + e1 = np.array([-1, 0, 0, 1, 1], dtype=np.intp) + tm.assert_almost_equal(r1, e1) + + r2 = idx2.get_indexer(idx1[::-1], method="pad") + tm.assert_almost_equal(r2, e1[::-1]) + + rffill1 = idx2.get_indexer(idx1, method="ffill") + tm.assert_almost_equal(r1, rffill1) + + r1 = idx2.get_indexer(idx1, method="backfill") + e1 = np.array([0, 0, 1, 1, 2], dtype=np.intp) + tm.assert_almost_equal(r1, e1) + + r2 = idx2.get_indexer(idx1[::-1], method="backfill") + tm.assert_almost_equal(r2, e1[::-1]) + + rbfill1 = idx2.get_indexer(idx1, method="bfill") + tm.assert_almost_equal(r1, rbfill1) + + # pass non-MultiIndex + r1 = idx1.get_indexer(idx2.values) + rexp1 = idx1.get_indexer(idx2) + tm.assert_almost_equal(r1, rexp1) + + r1 = idx1.get_indexer([1, 2, 3]) + assert (r1 == [-1, -1, -1]).all() + + # create index with duplicates + idx1 = pd.Index(list(range(10)) + list(range(10))) + idx2 = pd.Index(list(range(20))) + + msg = "Reindexing only valid with uniquely valued Index objects" + with pytest.raises(InvalidIndexError, match=msg): + idx1.get_indexer(idx2) + + def test_get_indexer_nearest(self): + midx = pd.MultiIndex.from_tuples([("a", 1), ("b", 2)]) + msg = ( + "method='nearest' not implemented yet for MultiIndex; see GitHub issue 9365" + ) + with pytest.raises(NotImplementedError, match=msg): + midx.get_indexer(["a"], method="nearest") + msg = "tolerance not implemented yet for MultiIndex" + with pytest.raises(NotImplementedError, match=msg): + midx.get_indexer(["a"], method="pad", tolerance=2) + + def test_get_indexer_categorical_time(self): + # https://github.com/pandas-dev/pandas/issues/21390 + midx = pd.MultiIndex.from_product( + [ + pd.Categorical(["a", "b", "c"]), + pd.Categorical(pd.date_range("2012-01-01", periods=3, freq="h")), + ] + ) + result = midx.get_indexer(midx) + tm.assert_numpy_array_equal(result, np.arange(9, dtype=np.intp)) + + @pytest.mark.parametrize( + "index_arr,labels,expected", + [ + ( + [[1, np.nan, 2], [3, 4, 5]], + [1, np.nan, 2], + np.array([-1, -1, -1], dtype=np.intp), + ), + ([[1, np.nan, 2], [3, 4, 5]], [(np.nan, 4)], np.array([1], dtype=np.intp)), + ([[1, 2, 3], [np.nan, 4, 5]], [(1, np.nan)], np.array([0], dtype=np.intp)), + ( + [[1, 2, 3], [np.nan, 4, 5]], + [np.nan, 4, 5], + np.array([-1, -1, -1], dtype=np.intp), + ), + ], + ) + def test_get_indexer_with_missing_value(self, index_arr, labels, expected): + # issue 19132 + idx = pd.MultiIndex.from_arrays(index_arr) + result = idx.get_indexer(labels) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_methods(self): + # https://github.com/pandas-dev/pandas/issues/29896 + # test getting an indexer for another index with different methods + # confirms that getting an indexer without a filling method, getting an + # indexer and backfilling, and getting an indexer and padding all behave + # correctly in the case where all of the target values fall in between + # several levels in the MultiIndex into which they are getting an indexer + # + # visually, the MultiIndexes used in this test are: + # mult_idx_1: + # 0: -1 0 + # 1: 2 + # 2: 3 + # 3: 4 + # 4: 0 0 + # 5: 2 + # 6: 3 + # 7: 4 + # 8: 1 0 + # 9: 2 + # 10: 3 + # 11: 4 + # + # mult_idx_2: + # 0: 0 1 + # 1: 3 + # 2: 4 + mult_idx_1 = pd.MultiIndex.from_product([[-1, 0, 1], [0, 2, 3, 4]]) + mult_idx_2 = pd.MultiIndex.from_product([[0], [1, 3, 4]]) + + indexer = mult_idx_1.get_indexer(mult_idx_2) + expected = np.array([-1, 6, 7], dtype=indexer.dtype) + tm.assert_almost_equal(expected, indexer) + + backfill_indexer = mult_idx_1.get_indexer(mult_idx_2, method="backfill") + expected = np.array([5, 6, 7], dtype=backfill_indexer.dtype) + tm.assert_almost_equal(expected, backfill_indexer) + + # ensure the legacy "bfill" option functions identically to "backfill" + backfill_indexer = mult_idx_1.get_indexer(mult_idx_2, method="bfill") + expected = np.array([5, 6, 7], dtype=backfill_indexer.dtype) + tm.assert_almost_equal(expected, backfill_indexer) + + pad_indexer = mult_idx_1.get_indexer(mult_idx_2, method="pad") + expected = np.array([4, 6, 7], dtype=pad_indexer.dtype) + tm.assert_almost_equal(expected, pad_indexer) + + # ensure the legacy "ffill" option functions identically to "pad" + pad_indexer = mult_idx_1.get_indexer(mult_idx_2, method="ffill") + expected = np.array([4, 6, 7], dtype=pad_indexer.dtype) + tm.assert_almost_equal(expected, pad_indexer) + + @pytest.mark.parametrize("method", ["pad", "ffill", "backfill", "bfill", "nearest"]) + def test_get_indexer_methods_raise_for_non_monotonic(self, method): + # 53452 + mi = pd.MultiIndex.from_arrays([[0, 4, 2], [0, 4, 2]]) + if method == "nearest": + err = NotImplementedError + msg = "not implemented yet for MultiIndex" + else: + err = ValueError + msg = "index must be monotonic increasing or decreasing" + with pytest.raises(err, match=msg): + mi.get_indexer([(1, 1)], method=method) + + def test_get_indexer_three_or_more_levels(self): + # https://github.com/pandas-dev/pandas/issues/29896 + # tests get_indexer() on MultiIndexes with 3+ levels + # visually, these are + # mult_idx_1: + # 0: 1 2 5 + # 1: 7 + # 2: 4 5 + # 3: 7 + # 4: 6 5 + # 5: 7 + # 6: 3 2 5 + # 7: 7 + # 8: 4 5 + # 9: 7 + # 10: 6 5 + # 11: 7 + # + # mult_idx_2: + # 0: 1 1 8 + # 1: 1 5 9 + # 2: 1 6 7 + # 3: 2 1 6 + # 4: 2 7 6 + # 5: 2 7 8 + # 6: 3 6 8 + mult_idx_1 = pd.MultiIndex.from_product([[1, 3], [2, 4, 6], [5, 7]]) + mult_idx_2 = pd.MultiIndex.from_tuples( + [ + (1, 1, 8), + (1, 5, 9), + (1, 6, 7), + (2, 1, 6), + (2, 7, 7), + (2, 7, 8), + (3, 6, 8), + ] + ) + # sanity check + assert mult_idx_1.is_monotonic_increasing + assert mult_idx_1.is_unique + assert mult_idx_2.is_monotonic_increasing + assert mult_idx_2.is_unique + + # show the relationships between the two + assert mult_idx_2[0] < mult_idx_1[0] + assert mult_idx_1[3] < mult_idx_2[1] < mult_idx_1[4] + assert mult_idx_1[5] == mult_idx_2[2] + assert mult_idx_1[5] < mult_idx_2[3] < mult_idx_1[6] + assert mult_idx_1[5] < mult_idx_2[4] < mult_idx_1[6] + assert mult_idx_1[5] < mult_idx_2[5] < mult_idx_1[6] + assert mult_idx_1[-1] < mult_idx_2[6] + + indexer_no_fill = mult_idx_1.get_indexer(mult_idx_2) + expected = np.array([-1, -1, 5, -1, -1, -1, -1], dtype=indexer_no_fill.dtype) + tm.assert_almost_equal(expected, indexer_no_fill) + + # test with backfilling + indexer_backfilled = mult_idx_1.get_indexer(mult_idx_2, method="backfill") + expected = np.array([0, 4, 5, 6, 6, 6, -1], dtype=indexer_backfilled.dtype) + tm.assert_almost_equal(expected, indexer_backfilled) + + # now, the same thing, but forward-filled (aka "padded") + indexer_padded = mult_idx_1.get_indexer(mult_idx_2, method="pad") + expected = np.array([-1, 3, 5, 5, 5, 5, 11], dtype=indexer_padded.dtype) + tm.assert_almost_equal(expected, indexer_padded) + + # now, do the indexing in the other direction + assert mult_idx_2[0] < mult_idx_1[0] < mult_idx_2[1] + assert mult_idx_2[0] < mult_idx_1[1] < mult_idx_2[1] + assert mult_idx_2[0] < mult_idx_1[2] < mult_idx_2[1] + assert mult_idx_2[0] < mult_idx_1[3] < mult_idx_2[1] + assert mult_idx_2[1] < mult_idx_1[4] < mult_idx_2[2] + assert mult_idx_2[2] == mult_idx_1[5] + assert mult_idx_2[5] < mult_idx_1[6] < mult_idx_2[6] + assert mult_idx_2[5] < mult_idx_1[7] < mult_idx_2[6] + assert mult_idx_2[5] < mult_idx_1[8] < mult_idx_2[6] + assert mult_idx_2[5] < mult_idx_1[9] < mult_idx_2[6] + assert mult_idx_2[5] < mult_idx_1[10] < mult_idx_2[6] + assert mult_idx_2[5] < mult_idx_1[11] < mult_idx_2[6] + + indexer = mult_idx_2.get_indexer(mult_idx_1) + expected = np.array( + [-1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1], dtype=indexer.dtype + ) + tm.assert_almost_equal(expected, indexer) + + backfill_indexer = mult_idx_2.get_indexer(mult_idx_1, method="bfill") + expected = np.array( + [1, 1, 1, 1, 2, 2, 6, 6, 6, 6, 6, 6], dtype=backfill_indexer.dtype + ) + tm.assert_almost_equal(expected, backfill_indexer) + + pad_indexer = mult_idx_2.get_indexer(mult_idx_1, method="pad") + expected = np.array( + [0, 0, 0, 0, 1, 2, 5, 5, 5, 5, 5, 5], dtype=pad_indexer.dtype + ) + tm.assert_almost_equal(expected, pad_indexer) + + def test_get_indexer_crossing_levels(self): + # https://github.com/pandas-dev/pandas/issues/29896 + # tests a corner case with get_indexer() with MultiIndexes where, when we + # need to "carry" across levels, proper tuple ordering is respected + # + # the MultiIndexes used in this test, visually, are: + # mult_idx_1: + # 0: 1 1 1 1 + # 1: 2 + # 2: 2 1 + # 3: 2 + # 4: 1 2 1 1 + # 5: 2 + # 6: 2 1 + # 7: 2 + # 8: 2 1 1 1 + # 9: 2 + # 10: 2 1 + # 11: 2 + # 12: 2 2 1 1 + # 13: 2 + # 14: 2 1 + # 15: 2 + # + # mult_idx_2: + # 0: 1 3 2 2 + # 1: 2 3 2 2 + mult_idx_1 = pd.MultiIndex.from_product([[1, 2]] * 4) + mult_idx_2 = pd.MultiIndex.from_tuples([(1, 3, 2, 2), (2, 3, 2, 2)]) + + # show the tuple orderings, which get_indexer() should respect + assert mult_idx_1[7] < mult_idx_2[0] < mult_idx_1[8] + assert mult_idx_1[-1] < mult_idx_2[1] + + indexer = mult_idx_1.get_indexer(mult_idx_2) + expected = np.array([-1, -1], dtype=indexer.dtype) + tm.assert_almost_equal(expected, indexer) + + backfill_indexer = mult_idx_1.get_indexer(mult_idx_2, method="bfill") + expected = np.array([8, -1], dtype=backfill_indexer.dtype) + tm.assert_almost_equal(expected, backfill_indexer) + + pad_indexer = mult_idx_1.get_indexer(mult_idx_2, method="ffill") + expected = np.array([7, 15], dtype=pad_indexer.dtype) + tm.assert_almost_equal(expected, pad_indexer) + + def test_get_indexer_kwarg_validation(self): + # GH#41918 + mi = pd.MultiIndex.from_product([range(3), ["A", "B"]]) + + msg = "limit argument only valid if doing pad, backfill or nearest" + with pytest.raises(ValueError, match=msg): + mi.get_indexer(mi[:-1], limit=4) + + msg = "tolerance argument only valid if doing pad, backfill or nearest" + with pytest.raises(ValueError, match=msg): + mi.get_indexer(mi[:-1], tolerance="piano") + + def test_get_indexer_nan(self): + # GH#37222 + idx1 = pd.MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"]) + idx2 = pd.MultiIndex.from_product([["A"], [np.nan, 2.0]], names=["id1", "id2"]) + expected = np.array([-1, 1]) + result = idx2.get_indexer(idx1) + tm.assert_numpy_array_equal(result, expected, check_dtype=False) + result = idx1.get_indexer(idx2) + tm.assert_numpy_array_equal(result, expected, check_dtype=False) + + +def test_getitem(idx): + # scalar + assert idx[2] == ("bar", "one") + + # slice + result = idx[2:5] + expected = idx[[2, 3, 4]] + assert result.equals(expected) + + # boolean + result = idx[[True, False, True, False, True, True]] + result2 = idx[np.array([True, False, True, False, True, True])] + expected = idx[[0, 2, 4, 5]] + assert result.equals(expected) + assert result2.equals(expected) + + +def test_getitem_scalar_result_type(using_python_scalars): + # GH#64266 + mi = pd.MultiIndex.from_arrays([[1, 2], [1.5, 2.5]]) + result = mi[1] + assert result == (2, 2.5) + if using_python_scalars: + assert type(result[0]) is int + assert type(result[1]) is float + else: + assert isinstance(result[0], np.integer) + assert isinstance(result[1], np.floating) + + +def test_getitem_group_select(idx): + sorted_idx, _ = idx.sortlevel(0) + assert sorted_idx.get_loc("baz") == slice(3, 4) + assert sorted_idx.get_loc("foo") == slice(0, 2) + + +@pytest.mark.parametrize("box", [list, pd.Index]) +def test_getitem_bool_index_all(box): + # GH#22533 + ind1 = box([True] * 5) + idx = pd.MultiIndex.from_tuples([(10, 1), (20, 2), (30, 3), (40, 4), (50, 5)]) + tm.assert_index_equal(idx[ind1], idx) + + ind2 = box([True, False, True, False, False]) + expected = pd.MultiIndex.from_tuples([(10, 1), (30, 3)]) + tm.assert_index_equal(idx[ind2], expected) + + +@pytest.mark.parametrize("box", [list, pd.Index]) +def test_getitem_bool_index_single(box): + # GH#22533 + ind1 = box([True]) + idx = pd.MultiIndex.from_tuples([(10, 1)]) + tm.assert_index_equal(idx[ind1], idx) + + ind2 = box([False]) + expected = pd.MultiIndex( + levels=[np.array([], dtype=np.int64), np.array([], dtype=np.int64)], + codes=[[], []], + ) + tm.assert_index_equal(idx[ind2], expected) + + +class TestGetLoc: + def test_get_loc(self, idx): + assert idx.get_loc(("foo", "two")) == 1 + assert idx.get_loc(("baz", "two")) == 3 + with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"): + idx.get_loc(("bar", "two")) + with pytest.raises(KeyError, match=r"^'quux'$"): + idx.get_loc("quux") + + # 3 levels + index = pd.MultiIndex( + levels=[ + pd.Index(np.arange(4)), + pd.Index(np.arange(4)), + pd.Index(np.arange(4)), + ], + codes=[ + np.array([0, 0, 1, 2, 2, 2, 3, 3]), + np.array([0, 1, 0, 0, 0, 1, 0, 1]), + np.array([1, 0, 1, 1, 0, 0, 1, 0]), + ], + ) + with pytest.raises(KeyError, match=r"^\(1, 1\)$"): + index.get_loc((1, 1)) + assert index.get_loc((2, 0)) == slice(3, 5) + + def test_get_loc_duplicates(self): + index = pd.Index([2, 2, 2, 2]) + result = index.get_loc(2) + expected = slice(0, 4) + assert result == expected + + index = pd.Index(["c", "a", "a", "b", "b"]) + rs = index.get_loc("c") + xp = 0 + assert rs == xp + + with pytest.raises(KeyError, match="2"): + index.get_loc(2) + + def test_get_loc_level(self): + index = pd.MultiIndex( + levels=[ + pd.Index(np.arange(4)), + pd.Index(np.arange(4)), + pd.Index(np.arange(4)), + ], + codes=[ + np.array([0, 0, 1, 2, 2, 2, 3, 3]), + np.array([0, 1, 0, 0, 0, 1, 0, 1]), + np.array([1, 0, 1, 1, 0, 0, 1, 0]), + ], + ) + loc, new_index = index.get_loc_level((0, 1)) + expected = slice(1, 2) + exp_index = index[expected].droplevel(0).droplevel(0) + assert loc == expected + assert new_index.equals(exp_index) + + loc, new_index = index.get_loc_level((0, 1, 0)) + expected = 1 + assert loc == expected + assert new_index is None + + with pytest.raises(KeyError, match=r"^\(2, 2\)$"): + index.get_loc_level((2, 2)) + # GH 22221: unused label + with pytest.raises(KeyError, match=r"^2$"): + index.drop(2).get_loc_level(2) + # Unused label on unsorted level: + with pytest.raises(KeyError, match=r"^2$"): + index.drop(1, level=2).get_loc_level(2, level=2) + + index = pd.MultiIndex( + levels=[[2000], list(range(4))], + codes=[np.array([0, 0, 0, 0]), np.array([0, 1, 2, 3])], + ) + result, new_index = index.get_loc_level((2000, slice(None, None))) + expected = slice(None, None) + assert result == expected + assert new_index.equals(index.droplevel(0)) + + @pytest.mark.parametrize("dtype1", [int, float, bool, str]) + @pytest.mark.parametrize("dtype2", [int, float, bool, str]) + def test_get_loc_multiple_dtypes(self, dtype1, dtype2): + # GH 18520 + levels = [np.array([0, 1]).astype(dtype1), np.array([0, 1]).astype(dtype2)] + idx = pd.MultiIndex.from_product(levels) + assert idx.get_loc(idx[2]) == 2 + + @pytest.mark.parametrize("level", [0, 1]) + @pytest.mark.parametrize("dtypes", [[int, float], [float, int]]) + def test_get_loc_implicit_cast(self, level, dtypes): + # GH 18818, GH 15994 : as flat index, cast int to float and vice-versa + levels = [["a", "b"], ["c", "d"]] + key = ["b", "d"] + lev_dtype, key_dtype = dtypes + levels[level] = np.array([0, 1], dtype=lev_dtype) + key[level] = key_dtype(1) + idx = pd.MultiIndex.from_product(levels) + assert idx.get_loc(tuple(key)) == 3 + + @pytest.mark.parametrize("dtype", [bool, object]) + def test_get_loc_cast_bool(self, dtype): + # GH 19086 : int is casted to bool, but not vice-versa (for object dtype) + # With bool dtype, we don't cast in either direction. + levels = [pd.Index([False, True], dtype=dtype), np.arange(2, dtype="int64")] + idx = pd.MultiIndex.from_product(levels) + + if dtype is bool: + with pytest.raises(KeyError, match=r"^\(0, 1\)$"): + assert idx.get_loc((0, 1)) == 1 + with pytest.raises(KeyError, match=r"^\(1, 0\)$"): + assert idx.get_loc((1, 0)) == 2 + else: + # We use python object comparisons, which treat 0 == False and 1 == True + assert idx.get_loc((0, 1)) == 1 + assert idx.get_loc((1, 0)) == 2 + + with pytest.raises(KeyError, match=r"^\(False, True\)$"): + idx.get_loc((False, True)) + with pytest.raises(KeyError, match=r"^\(True, False\)$"): + idx.get_loc((True, False)) + + @pytest.mark.parametrize("level", [0, 1]) + def test_get_loc_nan(self, level, nulls_fixture): + # GH 18485 : NaN in MultiIndex + levels = [["a", "b"], ["c", "d"]] + key = ["b", "d"] + levels[level] = np.array([0, nulls_fixture], dtype=type(nulls_fixture)) + key[level] = nulls_fixture + idx = pd.MultiIndex.from_product(levels) + assert idx.get_loc(tuple(key)) == 3 + + def test_get_loc_missing_nan(self): + # GH 8569 + idx = pd.MultiIndex.from_arrays([[1.0, 2.0], [3.0, 4.0]]) + assert isinstance(idx.get_loc(1), slice) + with pytest.raises(KeyError, match=r"^3$"): + idx.get_loc(3) + with pytest.raises(KeyError, match=r"^nan$"): + idx.get_loc(np.nan) + with pytest.raises(InvalidIndexError, match=r"\[nan\]"): + # listlike/non-hashable raises TypeError + idx.get_loc([np.nan]) + + def test_get_loc_with_values_including_missing_values(self): + # issue 19132 + idx = pd.MultiIndex.from_product([[np.nan, 1]] * 2) + expected = slice(0, 2, None) + assert idx.get_loc(np.nan) == expected + + idx = pd.MultiIndex.from_arrays([[np.nan, 1, 2, np.nan]]) + expected = np.array([True, False, False, True]) + tm.assert_numpy_array_equal(idx.get_loc(np.nan), expected) + + idx = pd.MultiIndex.from_product([[np.nan, 1]] * 3) + expected = slice(2, 4, None) + assert idx.get_loc((np.nan, 1)) == expected + + def test_get_loc_duplicates2(self): + # TODO: de-duplicate with test_get_loc_duplicates above? + index = pd.MultiIndex( + levels=[["D", "B", "C"], [0, 26, 27, 37, 57, 67, 75, 82]], + codes=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]], + names=["tag", "day"], + ) + + assert index.get_loc("D") == slice(0, 3) + + def test_get_loc_past_lexsort_depth(self, performance_warning): + # GH#30053 + idx = pd.MultiIndex( + levels=[["a"], [0, 7], [1]], + codes=[[0, 0], [1, 0], [0, 0]], + names=["x", "y", "z"], + sortorder=0, + ) + key = ("a", 7) + + msg = "indexing past lexsort depth may impact performance" + with tm.assert_produces_warning(performance_warning, match=msg): + # PerformanceWarning: indexing past lexsort depth may impact performance + result = idx.get_loc(key) + + assert result == slice(0, 1, None) + + def test_multiindex_get_loc_list_raises(self): + # GH#35878 + idx = pd.MultiIndex.from_tuples([("a", 1), ("b", 2)]) + msg = r"\[\]" + with pytest.raises(InvalidIndexError, match=msg): + idx.get_loc([]) + + def test_get_loc_nested_tuple_raises_keyerror(self): + # raise KeyError, not TypeError + mi = pd.MultiIndex.from_product([range(3), range(4), range(5), range(6)]) + key = ((2, 3, 4), "foo") + + with pytest.raises(KeyError, match=re.escape(str(key))): + mi.get_loc(key) + + def test_get_loc_string_key_on_numeric_level(self): + # GH#60104 - string key on integer level should raise KeyError, + # not return wrong results due to numpy searchsorted cross-dtype bug + mi = pd.MultiIndex.from_product([[2000, 2001], ["a", "b"], ["x", "y"]]) + df = pd.DataFrame({"value": range(8)}, index=mi) + + with pytest.raises(KeyError, match="2000"): + df.loc[("2000",)] + with pytest.raises(KeyError, match="a"): + df.loc[("2000", "a")] + with pytest.raises(KeyError, match="GIBBERISH"): + df.loc[("2000", "GIBBERISH")] + + # Valid lookups should still work + result = df.loc[(2000, "a")] + assert len(result) == 2 + result = df.loc[(2000,)] + assert len(result) == 4 + + +class TestWhere: + def test_where(self): + i = pd.MultiIndex.from_tuples([("A", 1), ("A", 2)]) + + msg = r"\.where is not supported for MultiIndex operations" + with pytest.raises(NotImplementedError, match=msg): + i.where(True) + + def test_where_array_like(self, listlike_box): + mi = pd.MultiIndex.from_tuples([("A", 1), ("A", 2)]) + cond = [False, True] + msg = r"\.where is not supported for MultiIndex operations" + with pytest.raises(NotImplementedError, match=msg): + mi.where(listlike_box(cond)) + + +class TestContains: + def test_contains_top_level(self): + midx = pd.MultiIndex.from_product([["A", "B"], [1, 2]]) + assert "A" in midx + assert "A" not in midx._engine + + def test_contains_with_nat(self): + # MI with a NaT + mi = pd.MultiIndex( + levels=[["C"], pd.date_range("2012-01-01", periods=5)], + codes=[[0, 0, 0, 0, 0, 0], [-1, 0, 1, 2, 3, 4]], + names=[None, "B"], + ) + assert ("C", pd.Timestamp("2012-01-01")) in mi + for val in mi.values: + assert val in mi + + def test_contains(self, idx): + assert ("foo", "two") in idx + assert ("bar", "two") not in idx + assert None not in idx + + def test_contains_with_missing_value(self): + # GH#19132 + idx = pd.MultiIndex.from_arrays([[1, np.nan, 2]]) + assert np.nan in idx + + idx = pd.MultiIndex.from_arrays([[1, 2], [np.nan, 3]]) + assert np.nan not in idx + assert (1, np.nan) in idx + + def test_multiindex_contains_dropped(self): + # GH#19027 + # test that dropped MultiIndex levels are not in the MultiIndex + # despite continuing to be in the MultiIndex's levels + idx = pd.MultiIndex.from_product([[1, 2], [3, 4]]) + assert 2 in idx + idx = idx.drop(2) + + # drop implementation keeps 2 in the levels + assert 2 in idx.levels[0] + # but it should no longer be in the index itself + assert 2 not in idx + + # also applies to strings + idx = pd.MultiIndex.from_product([["a", "b"], ["c", "d"]]) + assert "a" in idx + idx = idx.drop("a") + assert "a" in idx.levels[0] + assert "a" not in idx + + def test_contains_td64_level(self): + # GH#24570 + tx = pd.timedelta_range("09:30:00", "16:00:00", freq="30 min") + idx = pd.MultiIndex.from_arrays([tx, np.arange(len(tx))]) + assert tx[0] in idx + assert "element_not_exit" not in idx + assert "0 day 09:30:00" in idx + + def test_large_mi_contains(self, monkeypatch): + # GH#10645 + with monkeypatch.context(): + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 10) + result = pd.MultiIndex.from_arrays([range(10), range(10)]) + assert (10, 0) not in result + + +def test_timestamp_multiindex_indexer(): + # https://github.com/pandas-dev/pandas/issues/26944 + idx = pd.MultiIndex.from_product( + [ + pd.date_range("2019-01-01T00:15:33", periods=100, freq="h", name="date"), + ["x"], + [3], + ] + ) + df = pd.DataFrame({"foo": np.arange(len(idx))}, idx) + result = df.loc[pd.IndexSlice["2019-1-2":, "x", :], "foo"] + qidx = pd.MultiIndex.from_product( + [ + pd.date_range( + start="2019-01-02T00:15:33", + end="2019-01-05T03:15:33", + freq="h", + name="date", + ), + ["x"], + [3], + ] + ) + should_be = pd.Series(data=np.arange(24, len(qidx) + 24), index=qidx, name="foo") + tm.assert_series_equal(result, should_be) + + +@pytest.mark.parametrize( + "index_arr,expected,target,algo", + [ + ([[np.nan, "a", "b"], ["c", "d", "e"]], 0, np.nan, "left"), + ([[np.nan, "a", "b"], ["c", "d", "e"]], 1, (np.nan, "c"), "right"), + ([["a", "b", "c"], ["d", np.nan, "d"]], 1, ("b", np.nan), "left"), + ], +) +def test_get_slice_bound_with_missing_value(index_arr, expected, target, algo): + # issue 19132 + idx = pd.MultiIndex.from_arrays(index_arr) + result = idx.get_slice_bound(target, side=algo) + assert result == expected + + +@pytest.mark.parametrize( + "index_arr,expected,start_idx,end_idx", + [ + ([[np.nan, 1, 2], [3, 4, 5]], slice(0, 2, None), np.nan, 1), + ([[np.nan, 1, 2], [3, 4, 5]], slice(0, 3, None), np.nan, (2, 5)), + ([[1, 2, 3], [4, np.nan, 5]], slice(1, 3, None), (2, np.nan), 3), + ([[1, 2, 3], [4, np.nan, 5]], slice(1, 3, None), (2, np.nan), (3, 5)), + ], +) +def test_slice_indexer_with_missing_value(index_arr, expected, start_idx, end_idx): + # issue 19132 + idx = pd.MultiIndex.from_arrays(index_arr) + result = idx.slice_indexer(start=start_idx, end=end_idx) + assert result == expected + + +@pytest.mark.parametrize( + "N, expected_dtype", + [ + (1, "uint8"), # 2*4*N = 8 + (2, "uint16"), # 2*4*N = 16 + (4, "uint32"), # 2*4*N = 32 + (8, "uint64"), # 2*4*N = 64 + (10, "object"), # 2*4*N = 80 + ], +) +def test_pyint_engine(N, expected_dtype): + # GH#18519 : when combinations of codes cannot be represented in 64 + # bits, the index underlying the MultiIndex engine works with Python + # integers, rather than uint64. + keys = [ + tuple(arr) + for arr in [ + [0] * 4 * N, + [1] * 4 * N, + [np.nan] * N + [0] * 3 * N, + [0] * N + [1] * 3 * N, + [np.nan] * N + [1] * 2 * N + [0] * N, + ] + ] + # Each level contains 3 elements (NaN, 0, 1), and it's represented + # in 2 bits to store 4 possible values (0=notfound, 1=NaN, 2=0, 3=1), for + # a total of 2*N*4 = 80 > 64 bits where N=10 and the number of levels is N*4. + # If we were using a 64 bit engine and truncating the first levels, the + # fourth and fifth keys would collide; if truncating the last levels, the + # fifth and sixth; if rotating bits rather than shifting, the third and fifth. + + index = pd.MultiIndex.from_tuples(keys) + assert index._engine.values.dtype == expected_dtype + + for idx, key_value in enumerate(keys): + assert index.get_loc(key_value) == idx + + expected = np.arange(idx + 1, dtype=np.intp) + result = index.get_indexer([keys[i] for i in expected]) + tm.assert_numpy_array_equal(result, expected) + + # With missing key: + idces = range(len(keys)) + expected = np.array([-1, *list(idces)], dtype=np.intp) + missing = tuple([0, 1, 0, 1] * N) + result = index.get_indexer([missing] + [keys[i] for i in idces]) + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize( + "keys,expected", + [ + ((slice(None), [5, 4]), [1, 0]), + ((slice(None), [4, 5]), [0, 1]), + (([True, False, True], [4, 6]), [0, 2]), + (([True, False, True], [6, 4]), [0, 2]), + ((2, [4, 5]), [0, 1]), + ((2, [5, 4]), [1, 0]), + (([2], [4, 5]), [0, 1]), + (([2], [5, 4]), [1, 0]), + ], +) +def test_get_locs_reordering(keys, expected): + # GH48384 + idx = pd.MultiIndex.from_arrays( + [ + [2, 2, 1], + [4, 5, 6], + ] + ) + result = idx.get_locs(keys) + expected = np.array(expected, dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +def test_get_locs_list_like_basic(): + # GH#55786 - vectorized path for list-like keys + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + result = idx.get_locs((["a"], [1, 3])) + expected = np.array([0, 2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +def test_get_locs_list_like_with_nan(): + # GH#55786 - NaN labels are stored as code -1 + idx = pd.MultiIndex.from_arrays([["a", "a", "b"], [1.0, np.nan, 2.0]]) + result = idx.get_locs((["a"], [np.nan])) + expected = np.array([1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +def test_get_locs_list_like_with_nan_and_valid(): + # GH#55786 - mix of NaN and valid labels + idx = pd.MultiIndex.from_arrays([["a", "a", "a"], [1.0, np.nan, 2.0]]) + result = idx.get_locs((slice(None), [1.0, np.nan])) + expected = np.array([0, 1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +def test_get_locs_list_like_missing_raises(): + # GH#55786 - missing labels raise KeyError + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2]]) + with pytest.raises(KeyError, match="99"): + idx.get_locs((["a"], [1, 99])) + + +def test_get_locs_list_like_nan_not_in_level(): + # GH#55786 - NaN in query but not in index raises KeyError + idx = pd.MultiIndex.from_product([["a"], [1, 2]]) + with pytest.raises(KeyError, match="nan"): + idx.get_locs((["a"], [np.nan])) + + +@pytest.mark.parametrize( + "level", + [ + pd.date_range("2020-01-01", "2020-03-31", freq="D"), + pd.period_range("2020-01-01", "2020-03-31", freq="D"), + ], +) +@pytest.mark.parametrize("keys", [["2020-02"], ["2020-02", "2020-03"]]) +def test_get_locs_list_like_partial_string(level, keys): + # GH#64807 - a list-like of partial-string keys on a level that supports + # partial indexing (Datetime/Period) must match the same rows as the + # scalar key, not just the exact-coerced timestamp. + idx = pd.MultiIndex.from_product([level, ["a", "b"]]) + + result = idx.get_locs([keys]) + expected = np.concatenate([idx.get_locs([key]) for key in keys]) + expected.sort() + tm.assert_numpy_array_equal(result, expected) + + +def test_get_locs_list_like_partial_string_missing_raises(): + # GH#64807 - a partial-string key absent from the level still raises KeyError + level = pd.date_range("2020-01-01", "2020-03-31", freq="D") + idx = pd.MultiIndex.from_product([level, ["a", "b"]]) + with pytest.raises(KeyError, match="2021-01"): + idx.get_locs([["2021-01"]]) + + +@pytest.mark.parametrize( + "make_key", + [ + lambda: range(1, 3), + lambda: (val for val in [1, 2]), + lambda: {1, 2}, + lambda: {1: None, 2: None}, + ], +) +def test_get_locs_list_like_not_a_list(make_key): + # GH#64807 - a level key that is list-like but neither a list nor an array + # (range/generator/set/dict) must select the same rows as the equivalent + # list. Ordering is a separate matter: reordering an unordered container + # raises here, both before and after GH#64807. + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + result = idx.get_locs((["a"], make_key())) + expected = np.array([0, 1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +def test_get_locs_list_like_not_a_list_with_na(): + # GH#64807 - the NA inside a non-list list-like has to survive into the code + # bookkeeping; isna() on the container itself is a scalar, not elementwise + idx = pd.MultiIndex.from_arrays([["a", "a", "a"], [1.0, np.nan, 3.0]]) + result = idx.get_locs((slice(None), {1.0: 0, np.nan: 0})) + tm.assert_numpy_array_equal(result, np.array([0, 1], dtype=np.intp)) + + +@pytest.mark.parametrize( + "labels", [[frozenset({1}), frozenset({2})], [range(2), range(3)]] +) +def test_get_locs_hashable_list_like_label(labels): + # GH#64807 - a hashable list-like may be a level label rather than a + # sequence of labels, so it must not be materialized before the lookup + idx = pd.MultiIndex.from_arrays([labels, ["x", "y"]]) + result = idx.get_locs((labels[0], slice(None))) + tm.assert_numpy_array_equal(result, np.array([0], dtype=np.intp)) + + +def test_get_locs_generator_reordering(): + # GH#64807 - the generator must survive long enough to reorder the result + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + result = idx.get_locs((["a"], (val for val in [3, 1]))) + tm.assert_numpy_array_equal(result, np.array([2, 0], dtype=np.intp)) + + +def test_get_locs_list_like_loc(): + # GH#64807 - .loc with a non-list list-like level key + idx = pd.MultiIndex.from_product([["a", "b"], [0, 1, 2]]) + df = pd.DataFrame({"x": range(6)}, index=idx) + result = df.loc[(["a"], range(2)), :] + expected = df.iloc[[0, 1]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("keys", [([], [1, 2]), (["a"], []), ([], [])]) +def test_get_locs_list_like_empty(keys): + # GH#64807 - an empty level key matches nothing rather than raising + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + result = idx.get_locs(keys) + expected = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +def test_get_locs_list_like_empty_typed(): + # GH#64807 - an empty key that is not object dtype reaches the vectorized + # branch, where it has to short-circuit the levels after it rather than let + # them raise. An empty *list* is object dtype and takes the strict path. + idx = pd.MultiIndex.from_product([[1, 2], [1, 2, 3]]) + result = idx.get_locs((np.array([], dtype=np.int64), [1])) + tm.assert_numpy_array_equal(result, np.array([], dtype=np.intp)) + + +@pytest.mark.parametrize("extra", [slice(4, 6), 3, [3], np.array([3])]) +def test_get_locs_too_many_levels(extra): + # GH#45762 - a key with more entries than the index has levels is too + # long, whatever the extra entry is; the lexsort depth is not the problem + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + msg = r"Key length \(3\) exceeds index depth \(2\)" + with pytest.raises(KeyError, match=msg): + idx.get_locs([slice("a", "b"), slice(1, 2), extra]) + + +def test_get_locs_too_many_levels_reports_full_length(): + # GH#45762 - the message reports what the caller passed, as get_loc does, + # not the length left after the exempt trailing entries are discounted + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + msg = r"Key length \(4\) exceeds index depth \(2\)" + with pytest.raises(KeyError, match=msg): + idx.get_locs([["a"], 1, "c", slice(None)]) + + +def test_get_locs_too_many_levels_loc(): + # GH#45762 + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + df = pd.DataFrame({"x": range(6)}, index=idx) + msg = r"Key length \(3\) exceeds index depth \(2\)" + with pytest.raises(KeyError, match=msg): + df.loc[pd.IndexSlice["a":"b", 1:2, 4:6], :] + + +@pytest.mark.parametrize("pad", [1, 2]) +@pytest.mark.parametrize( + "filler", [slice(None), [True, True, False, False, False, False]] +) +def test_get_locs_trailing_non_level_keys_allowed(pad, filler): + # GH#45762 - a trailing entry that consumes no level does not make the key + # too long: a null slice is skipped, and a bool indexer picks positions + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + result = idx.get_locs([["a"], slice(1, 2)] + [filler] * pad) + tm.assert_numpy_array_equal(result, np.array([0, 1], dtype=np.intp)) + + +def test_get_locs_trailing_bool_indexer_narrows(): + # GH#45762 - the exempt trailing bool indexer still selects, it is only + # discounted from the length + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + mask = [True, False, True, False, True, False] + result = idx.get_locs([slice("a", "b"), slice(1, 2), mask]) + tm.assert_numpy_array_equal(result, np.array([0, 4], dtype=np.intp)) + + +def test_get_locs_iterator_bool_indexer_not_counted_as_level(): + # GH#45762 a bool indexer consumes no level, including when it arrives as an + # iterator -- is_bool_indexer reads an unmaterialized one as a level key + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + mask = [True, True, False, False, False, False] + + expected = idx.get_locs([["a"], slice(1, 2), mask]) + result = idx.get_locs([["a"], slice(1, 2), iter(mask)]) + + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("pos", [0, 2]) +def test_get_locs_too_many_levels_ellipsis(pos): + # GH#45762 - an Ellipsis is never supported, so the length check must not + # shadow the message that says so + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + key = [slice("a", "b"), slice(1, 2)] + key.insert(pos, ...) + with pytest.raises(NotImplementedError, match="does not support.*Ellipsis"): + idx.get_locs(key) + + +def test_get_loc_level_too_many_levels(): + # GH#45762 - get_loc and get_locs both report the length; a key holding a + # slice used to reach the level loop here and leak an IndexError + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + msg = r"Key length \(3\) exceeds index depth \(2\)" + with pytest.raises(KeyError, match=msg): + idx.get_loc_level(("a", slice(None), 4)) + + +def test_get_loc_level_long_tuple_level_label(): + # GH#45762 - the length check must not preempt a tuple that is a label in + # level 0 rather than one key per level + idx = pd.MultiIndex.from_arrays([[("a", 1, 4), ("b", 2, 5)], ["x", "y"]]) + _, new_index = idx.get_loc_level(("a", 1, 4)) + tm.assert_index_equal(new_index, pd.Index(["x"], dtype=idx.levels[1].dtype)) + + +def test_slice_locs_too_many_levels(): + # GH#45762 - the index is fully lexsorted, so blaming the lexsort depth + # for a key deeper than the index is misleading + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + assert idx._is_lexsorted() + msg = r"Key length \(3\) exceeds index depth \(2\)" + with pytest.raises(KeyError, match=msg): + idx.slice_locs(("a", 1, 4)) + + +def test_slice_locs_lexsort_depth_still_reported(): + # GH#45762 - a key the index really is too unsorted for keeps the + # lexsort-depth message + idx = pd.MultiIndex.from_tuples([("b", 2), ("a", 1), ("b", 1)]) + assert idx._lexsort_depth == 0 + msg = r"Key length \(2\) was greater than MultiIndex lexsort depth \(0\)" + with pytest.raises(UnsortedIndexError, match=msg): + idx.slice_locs(("a", 1)) + + +@pytest.mark.skipif(not PY312, reason="a slice is unhashable before 3.12") +@pytest.mark.parametrize("dtype", [None, object]) +def test_get_locs_list_like_slice_label(dtype): + # GH#64807 - a slice is hashable from Python 3.12 on, so it arrives as a + # level label; resolving it must not depend on the level's dtype + idx = pd.MultiIndex.from_product([["a"], pd.Index([1, 2, 3], dtype=dtype)]) + result = idx.get_locs((["a"], [slice(1, 2)])) + tm.assert_numpy_array_equal(result, np.array([0, 1], dtype=np.intp)) + + +@pytest.mark.skipif(not PY312, reason="a slice is unhashable before 3.12") +def test_get_locs_list_like_slice_label_mixed_level(): + # GH#64807 - a level that infers as "mixed", just as the slice key does, + # gets past the dtype gate, so the slice needs recognizing on its own + level = pd.Index([(1,), (2,), (3,)], dtype=object) + assert level.inferred_type == "mixed" + idx = pd.MultiIndex.from_product([["a"], level]) + result = idx.get_locs((["a"], [slice((1,), (2,))])) + tm.assert_numpy_array_equal(result, np.array([0, 1], dtype=np.intp)) + + +@pytest.mark.parametrize("dtype", [None, object]) +def test_get_locs_list_like_unhashable_after_missing(dtype): + # GH#64807 - an unhashable entry is not a label, but it must not preempt an + # earlier label that is merely missing. The tuple level infers as "mixed", + # like the key, so nothing else routes it off the vectorized path. + labels = [(1,), (2,), (3,)] if dtype is object else [1, 2, 3] + missing, unhashable = ((9,), [1, 2]) if dtype is object else ("missing", [1, 2]) + idx = pd.MultiIndex.from_product([["a"], pd.Index(labels, dtype=dtype)]) + + with pytest.raises(KeyError, match=re.escape(str(missing))): + idx.get_locs((["a"], [missing, unhashable])) + with pytest.raises(InvalidIndexError, match=re.escape(str([unhashable, missing]))): + idx.get_locs((["a"], [unhashable, missing])) + + +def test_get_locs_list_like_unsupported_timedelta_unit(): + # GH#64807 - an Index cannot hold a month-unit timedelta, so building one + # from the key must not turn a lookup into ValueError + level = pd.Index( + np.array([np.timedelta64(1, "M"), np.timedelta64(2, "M")], dtype=object), + dtype=object, + ) + idx = pd.MultiIndex.from_arrays([["x", "y"], level]) + result = idx.get_locs((slice(None), [np.timedelta64(1, "M")])) + tm.assert_numpy_array_equal(result, np.array([0], dtype=np.intp)) + + idx = pd.MultiIndex.from_product([["x"], pd.date_range("2020", periods=3)]) + with pytest.raises(KeyError, match="1"): + idx.get_locs((slice(None), [np.timedelta64(1, "M")])) + + +def test_get_locs_list_like_interval_level(): + # GH#64807 - an IntervalIndex level matches a numeric key by containment, + # the same as a flat IntervalIndex does for a list-like key + level = pd.IntervalIndex.from_breaks([0.0, 1.0, 2.0, 3.0]) + idx = pd.MultiIndex.from_product([["a"], level]) + result = idx.get_locs((["a"], [0.5, 2.5])) + tm.assert_numpy_array_equal(result, np.array([0, 2], dtype=np.intp)) + + +def test_get_locs_list_like_categorical_overlapping_interval_level(): + # GH#64807 - a CategoricalIndex reports itself unique whatever its + # categories do, so overlapping interval categories still need the + # per-label path + categories = pd.IntervalIndex.from_tuples([(0, 2), (1, 3)]) + level = pd.CategoricalIndex( + pd.Categorical.from_codes([0, 1], dtype=pd.CategoricalDtype(categories)) + ) + assert level._index_as_unique and not level.categories._index_as_unique + idx = pd.MultiIndex.from_arrays([["a", "b"], level]) + # the lookups the per-label path makes work + tm.assert_numpy_array_equal( + idx.get_locs((slice(None), [pd.Interval(0, 2)])), np.array([0], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_locs((slice(None), [0.5])), np.array([0], dtype=np.intp) + ) + + +def test_get_locs_list_like_float16_key(): + # GH#64807 - an Index cannot hold float16 at all, so building one from the + # key must not turn a lookup into NotImplementedError + idx = pd.MultiIndex.from_product([["a"], [1.0, 2.0, 3.0]]) + result = idx.get_locs((["a"], [np.float16(1.0)])) + tm.assert_numpy_array_equal(result, np.array([0], dtype=np.intp)) + + idx = pd.MultiIndex.from_product([["a"], pd.date_range("2020", periods=3)]) + with pytest.raises(KeyError, match="1.0"): + idx.get_locs((["a"], [np.float16(1.0)])) + + +def test_get_locs_list_like_nan_key_without_nan_rows(): + # GH#64807 - a NaN key must raise when the data carries no NA rows, even + # though NaN is looked up without needing a level entry + idx = pd.MultiIndex.from_arrays([["a", "a"], [1.0, 2.0]]) + with pytest.raises(KeyError, match="nan"): + idx.get_locs((slice(None), [np.nan])) + + +def test_get_locs_list_like_categorical_level(): + # GH#64807 - smoke test for a CategoricalIndex level, which no other case + # in this file covers + idx = pd.MultiIndex.from_product([pd.CategoricalIndex(list("abc")), [1, 2]]) + result = idx.get_locs((["a", "c"], slice(None))) + tm.assert_numpy_array_equal(result, np.array([0, 1, 4, 5], dtype=np.intp)) + + +@pytest.mark.parametrize( + "keys, match", + [ + ((["a", "b"], slice(None)), "['a', 'b']"), + ((["b"], slice(None)), "['b']"), + ], +) +def test_get_locs_list_like_unused_level_raises(keys, match): + # GH#64807 - a label present in the level but unused by any code is missing, + # just as it is when passed as a scalar + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]])[:3] + assert "b" in idx.levels[0] + with pytest.raises(KeyError, match=re.escape(match)): + idx.get_locs(keys) + + +def test_get_locs_list_like_nan_code_vs_last_level_label(): + # GH#64807 - the -1 code standing for NaN must not wrap around onto the + # last level entry, which would both leak the NaN row in... + idx = pd.MultiIndex.from_arrays([["a"] * 3, [1.0, np.nan, 2.0]]) + result = idx.get_locs((["a"], [2.0])) + tm.assert_numpy_array_equal(result, np.array([2], dtype=np.intp)) + + # ...and make an unused last label look used + idx = pd.MultiIndex.from_arrays([["a"] * 4, [1.0, np.nan, 1.0, 2.0]])[:3] + assert 2.0 in idx.levels[1] + with pytest.raises(KeyError, match=re.escape("[2.0]")): + idx.get_locs((["a"], [2.0])) + + +def test_get_locs_list_like_na_label_against_na_in_level(): + # GH#64807 - a level can carry an NA entry of its own that no code uses, + # while the NA rows carry code -1 (e.g. concatenating a + # groupby(dropna=False) result with an ordinary NaN-indexed frame, then + # dropping rows). get_indexer matches an NA label to that entry, so it must + # not be mistaken for a label the level does not have. + idx = pd.MultiIndex( + levels=[pd.Index(["a"]), pd.Index([1.0, np.nan, 2.0])], codes=[[0, 0], [-1, 0]] + ) + expected = idx.get_locs((slice(None), np.nan)) + result = idx.get_locs((slice(None), [np.nan])) + tm.assert_numpy_array_equal(result, expected) + + # and a genuinely missing label alongside it must still raise + with pytest.raises(KeyError, match=re.escape("[nan, 9.9]")): + idx.get_locs((slice(None), [np.nan, 9.9])) + + +def test_get_locs_list_like_na_label_not_matched_to_level_entry(): + # GH#64807 - get_indexer can match an NA label to an NA entry of the level, + # but the scalar path always resolves NA to code -1, so the list path has + # to select the -1 rows only and agree with it + idx = pd.MultiIndex.from_arrays([["a"] * 3, [1.0, np.nan, 3.0]]) + idx = idx.set_levels(pd.Index([1.0, np.nan]), level=1, verify_integrity=False) + assert idx.levels[1].hasnans + + expected = np.array([1], dtype=np.intp) + tm.assert_numpy_array_equal(idx.get_locs((slice(None), [np.nan])), expected) + tm.assert_numpy_array_equal(idx.get_locs((slice(None), np.nan)), expected) + + +def test_get_locs_list_like_multiindex_key(): + # GH#64807 - tuple-valued level labels, so the key itself is a MultiIndex. + # isna() answers per tuple *element*, which for a single label broadcasts + # against the codes silently and for several of them does not broadcast at + # all, so both lengths are worth covering. + idx = pd.MultiIndex.from_arrays([[("x", 1), ("y", 2), ("z", 3)], list("abc")]) + result = idx.get_locs((pd.Index([("x", 1), ("y", 2), ("z", 3)]), slice(None))) + tm.assert_numpy_array_equal(result, np.array([0, 1, 2], dtype=np.intp)) + + result = idx.get_locs((pd.Index([("x", 1)]), slice(None))) + tm.assert_numpy_array_equal(result, np.array([0], dtype=np.intp)) + + +def test_get_locs_list_like_mixed_type_key(): + # GH#64807 - a list-like key resolves through get_indexer, which cannot + # convert an object-dtype target mixing strings and Timedeltas, so it + # reports the string as missing. A flat Index rejects the same key, even + # though the scalar path parses "1 days". + idx = pd.MultiIndex.from_product([["a"], pd.timedelta_range("1 day", periods=3)]) + key = ["1 days", pd.Timedelta("2 days")] + with pytest.raises(KeyError, match="1 days"): + idx.get_locs((["a"], key)) + with pytest.raises(KeyError, match="1 days"): + pd.Series(range(3), index=idx.levels[1]).loc[key] + + tm.assert_numpy_array_equal( + idx.get_locs((["a"], "1 days")), np.array([0], dtype=np.intp) + ) + + +def test_get_locs_list_like_float32_level(): + # GH#64807 - a float64 key never equals a float32 label once get_indexer + # widens the level to hold it, matching what a flat Index does. The scalar + # path is not held to that; the two are not expected to agree here. + idx = pd.MultiIndex.from_arrays( + [["a", "a", "b"], np.array([1.1, 2.2, 1.1], dtype=np.float32)] + ) + with pytest.raises(KeyError, match="1.1"): + idx.get_locs((slice(None), [1.1])) + with pytest.raises(KeyError, match="1.1"): + pd.Series(range(2), index=idx.levels[1]).loc[[1.1]] + + tm.assert_numpy_array_equal( + idx.get_locs((slice(None), 1.1)), np.array([0, 2], dtype=np.intp) + ) + + +def test_get_locs_list_like_na_in_object_container(): + # GH#64807 - pd.NA alongside a real label leaves the key container object + # dtype; the NA still has to be recognized and matched to the -1 codes + idx = pd.MultiIndex( + levels=[pd.Index(["a", "b"]), pd.Index([1.1, 2.2])], + codes=[[0, 0, 1], [0, -1, 0]], + ) + # the key order puts the 1.1 rows ahead of the NA row + result = idx.get_locs((slice(None), [1.1, pd.NA])) + tm.assert_numpy_array_equal(result, np.array([0, 2, 1], dtype=np.intp)) + + +def test_get_locs_list_like_signed_unsigned_level(): + # GH#64807 - get_indexer reconciles a signed level and an unsigned key + # through float64, colliding two labels above 2**53 and selecting the + # wrong row; a flat Index resolves the same key correctly + idx = pd.MultiIndex.from_arrays([["a", "b"], [2**53, 2**53 + 1]]) + key = pd.array([2**53], dtype="UInt64") + tm.assert_numpy_array_equal( + idx.get_locs((slice(None), key)), np.array([0], dtype=np.intp) + ) + assert pd.Series(range(2), index=idx.levels[1]).loc[key].tolist() == [0] + + +def test_get_locs_list_like_categorical_key(): + # GH#64807 - a Categorical key against an object level of tuple labels: + # a label the level lacks still raises rather than matching + level = pd.Index([(1,), (2,), (3,)], dtype=object) + idx = pd.MultiIndex( + levels=[pd.Index(list("abc")), level], + codes=[[0, 1, 2], [0, 1, 2]], + verify_integrity=False, + ) + with pytest.raises(KeyError, match="9"): + idx.get_locs((slice(None), pd.Categorical([(1,), 9]))) + + +def test_get_locs_list_like_narrow_int_level(): + # GH#64807 - a wider integer holds every value of a narrower one, so an + # int64 key still matches an int32 level exactly (no float widening) + idx = pd.MultiIndex.from_product([["a"], pd.Index(np.arange(5, dtype="int32"))]) + result = idx.get_locs((["a"], [1, 3])) + tm.assert_numpy_array_equal(result, np.array([1, 3], dtype=np.intp)) + + +def test_get_locs_list_like_ragged_tuple_labels(): + # GH#64807 - a tuple key of tuple-valued labels must not be tupleized into + # a single label by Index() + idx = pd.MultiIndex.from_arrays([[("x", 1), ("y", 2, 3)], ["a", "b"]]) + expected = np.array([0, 1], dtype=np.intp) + tm.assert_numpy_array_equal( + idx.get_locs(((("x", 1), ("y", 2, 3)), slice(None))), expected + ) + tm.assert_numpy_array_equal( + idx.get_locs(([("x", 1), ("y", 2, 3)], slice(None))), expected + ) + + +def test_get_locs_list_like_wide_level(): + # GH#64807 - slicing a MultiIndex leaves its levels untrimmed, so the level + # can be bigger than the codes; unused labels must still raise there + idx = pd.MultiIndex.from_product([list("abcde"), [1]])[:2] + assert len(idx.levels[0]) > len(idx.codes[0]) + + result = idx.get_locs((["a", "b"], slice(None))) + tm.assert_numpy_array_equal(result, np.array([0, 1], dtype=np.intp)) + + with pytest.raises(KeyError, match=re.escape("['a', 'c']")): + idx.get_locs((["a", "c"], slice(None))) + + +@pytest.mark.parametrize( + "keys, expected", [([1.5], [0, 1]), ([pd.Interval(0, 2)], [0])] +) +def test_get_locs_list_like_overlapping_interval_level(keys, expected): + # GH#64807 - an overlapping IntervalIndex level cannot use get_indexer; a + # label there can match several level entries, e.g. 1.5 is in both + level = pd.IntervalIndex.from_tuples([(0, 2), (1, 3)]) + idx = pd.MultiIndex.from_product([["a", "b"], level]) + result = idx.get_locs((["a"], keys)) + tm.assert_numpy_array_equal(result, np.array(expected, dtype=np.intp)) + + +def test_get_indexer_for_multiindex_with_nans(nulls_fixture): + # GH37222 + idx1 = pd.MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"]) + idx2 = pd.MultiIndex.from_product( + [["A"], [nulls_fixture, 2.0]], names=["id1", "id2"] + ) + + result = idx2.get_indexer(idx1) + expected = np.array([-1, 1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = idx1.get_indexer(idx2) + expected = np.array([-1, 1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +def test_get_loc_namedtuple_behaves_like_tuple(): + # GH57922 + NamedIndex = namedtuple("NamedIndex", ("a", "b")) + multi_idx = pd.MultiIndex.from_tuples( + [NamedIndex("i1", "i2"), NamedIndex("i3", "i4"), NamedIndex("i5", "i6")] + ) + for idx in (multi_idx, multi_idx.to_flat_index()): + assert idx.get_loc(NamedIndex("i1", "i2")) == 0 + assert idx.get_loc(NamedIndex("i3", "i4")) == 1 + assert idx.get_loc(NamedIndex("i5", "i6")) == 2 + assert idx.get_loc(("i1", "i2")) == 0 + assert idx.get_loc(("i3", "i4")) == 1 + assert idx.get_loc(("i5", "i6")) == 2 + multi_idx = pd.MultiIndex.from_tuples([("i1", "i2"), ("i3", "i4"), ("i5", "i6")]) + for idx in (multi_idx, multi_idx.to_flat_index()): + assert idx.get_loc(NamedIndex("i1", "i2")) == 0 + assert idx.get_loc(NamedIndex("i3", "i4")) == 1 + assert idx.get_loc(NamedIndex("i5", "i6")) == 2 + assert idx.get_loc(("i1", "i2")) == 0 + assert idx.get_loc(("i3", "i4")) == 1 + assert idx.get_loc(("i5", "i6")) == 2 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_integrity.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_integrity.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8ea0e58d8ca61fe3a28b5f7e94b90cec0dbecf --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_integrity.py @@ -0,0 +1,285 @@ +import re + +import numpy as np +import pytest + +from pandas._libs import index as libindex + +from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike + +import pandas as pd +import pandas._testing as tm + + +def test_labels_dtypes(): + # GH 8456 + i = pd.MultiIndex.from_tuples([("A", 1), ("A", 2)]) + assert i.codes[0].dtype == "int8" + assert i.codes[1].dtype == "int8" + + i = pd.MultiIndex.from_product([["a"], range(40)]) + assert i.codes[1].dtype == "int8" + i = pd.MultiIndex.from_product([["a"], range(400)]) + assert i.codes[1].dtype == "int16" + i = pd.MultiIndex.from_product([["a"], range(40000)]) + assert i.codes[1].dtype == "int32" + + i = pd.MultiIndex.from_product([["a"], range(1000)]) + assert (i.codes[0] >= 0).all() + assert (i.codes[1] >= 0).all() + + +def test_values_boxed(): + tuples = [ + (1, pd.Timestamp("2000-01-01")), + (2, pd.NaT), + (3, pd.Timestamp("2000-01-03")), + (1, pd.Timestamp("2000-01-04")), + (2, pd.Timestamp("2000-01-02")), + (3, pd.Timestamp("2000-01-03")), + ] + result = pd.MultiIndex.from_tuples(tuples) + expected = construct_1d_object_array_from_listlike(tuples) + tm.assert_numpy_array_equal(result.values, expected) + # Check that code branches for boxed values produce identical results + tm.assert_numpy_array_equal(result.values[:4], result[:4].values) + + +def test_values_multiindex_datetimeindex(): + # Test to ensure we hit the boxing / nobox part of MI.values + ints = np.arange(10**18, 10**18 + 5) + naive = pd.DatetimeIndex(ints) + + aware = pd.DatetimeIndex(ints, tz="US/Central") + + idx = pd.MultiIndex.from_arrays([naive, aware]) + result = idx.values + + outer = pd.DatetimeIndex([x[0] for x in result]) + tm.assert_index_equal(outer, naive) + + inner = pd.DatetimeIndex([x[1] for x in result]) + tm.assert_index_equal(inner, aware) + + # n_lev > n_lab + result = idx[:2].values + + outer = pd.DatetimeIndex([x[0] for x in result]) + tm.assert_index_equal(outer, naive[:2]) + + inner = pd.DatetimeIndex([x[1] for x in result]) + tm.assert_index_equal(inner, aware[:2]) + + +def test_values_multiindex_periodindex(): + # Test to ensure we hit the boxing / nobox part of MI.values + ints = np.arange(2007, 2012) + strs = [str(x) for x in ints] + pidx = pd.PeriodIndex(strs, freq="D") + + idx = pd.MultiIndex.from_arrays([ints, pidx]) + result = idx.values + + outer = pd.Index([x[0] for x in result]) + tm.assert_index_equal(outer, pd.Index(ints, dtype=np.int64)) + + inner = pd.PeriodIndex([x[1] for x in result]) + tm.assert_index_equal(inner, pidx) + + # n_lev > n_lab + result = idx[:2].values + + outer = pd.Index([x[0] for x in result]) + tm.assert_index_equal(outer, pd.Index(ints[:2], dtype=np.int64)) + + inner = pd.PeriodIndex([x[1] for x in result]) + tm.assert_index_equal(inner, pidx[:2]) + + +def test_consistency(): + # need to construct an overflow + major_axis = list(range(70000)) + minor_axis = list(range(10)) + + major_codes = np.arange(70000) + minor_codes = np.repeat(range(10), 7000) + + # the fact that is works means it's consistent + index = pd.MultiIndex( + levels=[major_axis, minor_axis], codes=[major_codes, minor_codes] + ) + + # inconsistent + major_codes = np.array([0, 0, 1, 1, 1, 2, 2, 3, 3]) + minor_codes = np.array([0, 1, 0, 1, 1, 0, 1, 0, 1]) + index = pd.MultiIndex( + levels=[major_axis, minor_axis], codes=[major_codes, minor_codes] + ) + + assert index.is_unique is False + + +@pytest.mark.slow +def test_hash_collisions(monkeypatch): + # non-smoke test that we don't get hash collisions + size_cutoff = 50 + with monkeypatch.context() as m: + m.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) + index = pd.MultiIndex.from_product( + [np.arange(8), np.arange(8)], names=["one", "two"] + ) + result = index.get_indexer(index.values) + tm.assert_numpy_array_equal(result, np.arange(len(index), dtype="intp")) + + for i in [0, 1, len(index) - 2, len(index) - 1]: + result = index.get_loc(index[i]) + assert result == i + + +def test_dims(): + pass + + +def test_take_invalid_kwargs(): + vals = [["A", "B"], [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")]] + idx = pd.MultiIndex.from_product(vals, names=["str", "dt"]) + indices = [1, 2] + + msg = r"take\(\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg): + idx.take(indices, foo=2) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, out=indices) + + msg = "the 'mode' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, mode="clip") + + +def test_isna_behavior(idx): + # should not segfault GH5123 + # NOTE: if MI representation changes, may make sense to allow + # isna(MI) + msg = "isna is not defined for MultiIndex" + with pytest.raises(NotImplementedError, match=msg): + pd.isna(idx) + + +def test_large_multiindex_error(monkeypatch): + # GH12527 + size_cutoff = 50 + with monkeypatch.context() as m: + m.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) + df_below_cutoff = pd.DataFrame( + 1, + index=pd.MultiIndex.from_product([[1, 2], range(size_cutoff - 1)]), + columns=["dest"], + ) + with pytest.raises(KeyError, match=r"^\(-1, 0\)$"): + df_below_cutoff.loc[(-1, 0), "dest"] + with pytest.raises(KeyError, match=r"^\(3, 0\)$"): + df_below_cutoff.loc[(3, 0), "dest"] + df_above_cutoff = pd.DataFrame( + 1, + index=pd.MultiIndex.from_product([[1, 2], range(size_cutoff + 1)]), + columns=["dest"], + ) + with pytest.raises(KeyError, match=r"^\(-1, 0\)$"): + df_above_cutoff.loc[(-1, 0), "dest"] + with pytest.raises(KeyError, match=r"^\(3, 0\)$"): + df_above_cutoff.loc[(3, 0), "dest"] + + +def test_mi_attribute_error(): + # GH 18165 + r = range(50) + df = pd.DataFrame({"a": r, "b": r}, index=pd.MultiIndex.from_arrays([r, r])) + + msg = "'Series' object has no attribute 'foo'" + with pytest.raises(AttributeError, match=msg): + df["a"].foo() + + +def test_can_hold_identifiers(idx): + key = idx[0] + assert idx._can_hold_identifiers_and_holds_name(key) is True + + +def test_metadata_immutable(idx): + levels, codes = idx.levels, idx.codes + # shouldn't be able to set at either the top level or base level + mutable_regex = re.compile("does not support mutable operations") + with pytest.raises(TypeError, match=mutable_regex): + levels[0] = levels[0] + with pytest.raises(TypeError, match=mutable_regex): + levels[0][0] = levels[0][0] + # ditto for labels + with pytest.raises(TypeError, match=mutable_regex): + codes[0] = codes[0] + with pytest.raises(ValueError, match="assignment destination is read-only"): + codes[0][0] = codes[0][0] + # and for names + names = idx.names + with pytest.raises(TypeError, match=mutable_regex): + names[0] = names[0] + + +def test_level_setting_resets_attributes(): + ind = pd.MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]]) + assert ind.is_monotonic_increasing + ind = ind.set_levels([["A", "B"], [1, 3, 2]]) + # if this fails, probably didn't reset the cache correctly. + assert not ind.is_monotonic_increasing + + +def test_rangeindex_fallback_coercion_bug(): + # GH 12893 + df1 = pd.DataFrame(np.arange(100).reshape((10, 10))) + df2 = pd.DataFrame(np.arange(100).reshape((10, 10))) + df = pd.concat( + {"df1": df1.stack(), "df2": df2.stack()}, + axis=1, + ) + df.index.names = ["fizz", "buzz"] + + expected = pd.DataFrame( + {"df2": np.arange(100), "df1": np.arange(100)}, + index=pd.MultiIndex.from_product( + [range(10), range(10)], names=["fizz", "buzz"] + ), + ) + tm.assert_frame_equal(df, expected, check_like=True) + + result = df.index.get_level_values("fizz") + expected = pd.Index(np.arange(10, dtype=np.int64), name="fizz").repeat(10) + tm.assert_index_equal(result, expected) + + result = df.index.get_level_values("buzz") + expected = pd.Index(np.tile(np.arange(10, dtype=np.int64), 10), name="buzz") + tm.assert_index_equal(result, expected) + + +def test_memory_usage(idx): + result = idx.memory_usage() + if len(idx): + idx.get_loc(idx[0]) + result2 = idx.memory_usage() + result3 = idx.memory_usage(deep=True) + + # RangeIndex, IntervalIndex + # don't have engines + if not isinstance(idx, (pd.RangeIndex, pd.IntervalIndex)): + assert result2 > result + + if idx.inferred_type == "object": + assert result3 > result2 + + else: + # we report 0 for no-length + assert result == 0 + + +def test_nlevels(idx): + assert idx.nlevels == 2 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_isin.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_isin.py new file mode 100644 index 0000000000000000000000000000000000000000..18915c9e056b5698515514c64113954a9d521c2b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_isin.py @@ -0,0 +1,137 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_isin_nan(): + idx = pd.MultiIndex.from_arrays([["foo", "bar"], [1.0, np.nan]]) + tm.assert_numpy_array_equal(idx.isin([("bar", np.nan)]), np.array([False, True])) + tm.assert_numpy_array_equal( + idx.isin([("bar", float("nan"))]), np.array([False, True]) + ) + + +def test_isin_missing(nulls_fixture): + # GH48905 + mi1 = pd.MultiIndex.from_tuples([(1, nulls_fixture)]) + mi2 = pd.MultiIndex.from_tuples([(1, 1), (1, 2)]) + result = mi2.isin(mi1) + expected = np.array([False, False]) + tm.assert_numpy_array_equal(result, expected) + + +def test_isin(): + values = [("foo", 2), ("bar", 3), ("quux", 4)] + + idx = pd.MultiIndex.from_arrays([["qux", "baz", "foo", "bar"], np.arange(4)]) + result = idx.isin(values) + expected = np.array([False, False, True, True]) + tm.assert_numpy_array_equal(result, expected) + + # empty, return dtype bool + idx = pd.MultiIndex.from_arrays([[], []]) + result = idx.isin(values) + assert len(result) == 0 + assert result.dtype == np.bool_ + + +def test_isin_level_kwarg(): + idx = pd.MultiIndex.from_arrays([["qux", "baz", "foo", "bar"], np.arange(4)]) + + vals_0 = ["foo", "bar", "quux"] + vals_1 = [2, 3, 10] + + expected = np.array([False, False, True, True]) + tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=0)) + tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=-2)) + + tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=1)) + tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=-1)) + + msg = "Too many levels: Index has only 2 levels, not 6" + with pytest.raises(IndexError, match=msg): + idx.isin(vals_0, level=5) + msg = "Too many levels: Index has only 2 levels, -5 is not a valid level number" + with pytest.raises(IndexError, match=msg): + idx.isin(vals_0, level=-5) + + with pytest.raises(KeyError, match=r"'Level 1\.0 not found'"): + idx.isin(vals_0, level=1.0) + with pytest.raises(KeyError, match=r"'Level -1\.0 not found'"): + idx.isin(vals_1, level=-1.0) + with pytest.raises(KeyError, match="'Level A not found'"): + idx.isin(vals_1, level="A") + + idx.names = ["A", "B"] + tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level="A")) + tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level="B")) + + with pytest.raises(KeyError, match="'Level C not found'"): + idx.isin(vals_1, level="C") + + +@pytest.mark.parametrize( + "labels,expected,level", + [ + ([("b", np.nan)], [False, False, True], None), + ([np.nan, "a"], [True, True, False], 0), + (["d", np.nan], [False, True, True], 1), + ], +) +def test_isin_multi_index_with_missing_value(labels, expected, level): + # GH 19132 + midx = pd.MultiIndex.from_arrays([[np.nan, "a", "b"], ["c", "d", np.nan]]) + result = midx.isin(labels, level=level) + expected = np.array(expected) + tm.assert_numpy_array_equal(result, expected) + + +def test_isin_empty(): + # GH#51599 + midx = pd.MultiIndex.from_arrays([[1, 2], [3, 4]]) + result = midx.isin([]) + expected = np.array([False, False]) + tm.assert_numpy_array_equal(result, expected) + + +def test_isin_generator(): + # GH#52568 + midx = pd.MultiIndex.from_tuples([(1, 2)]) + result = midx.isin(x for x in [(1, 2)]) + expected = np.array([True]) + tm.assert_numpy_array_equal(result, expected) + + +def test_isin_scalar_values_raises_gh20252(): + # GH#20252 + midx = pd.MultiIndex.from_arrays([[1, 2, 3], ["a", "b", "c"]]) + msg = ( + "MultiIndex.isin expects an iterable of tuples of length 2 " + r"\(the number of levels\); got a scalar \(1\) at position 0\. " + "To match on a single level, pass the level= argument\\." + ) + with pytest.raises(ValueError, match=msg): + midx.isin([1, 2]) + + +@pytest.mark.parametrize( + "values, bad_len, position", + [ + ([("foo", "one", "B"), ("bar",)], 1, 1), + ([("foo", "one")], 2, 0), + ([("foo", "one", "B"), ("bar", "two", "A", "x")], 4, 1), + ], +) +def test_isin_wrong_length_tuples_raises_gh26622(values, bad_len, position): + # GH#26622 short tuples used to silently give wrong results + midx = pd.MultiIndex.from_product([["foo", "bar"], ["one", "two"], ["A", "B"]]) + msg = ( + "MultiIndex.isin expects an iterable of tuples of length 3 " + rf"\(the number of levels\); got an element of length {bad_len} at " + rf"position {position}\. To match on a single level, pass the " + "level= argument\\." + ) + with pytest.raises(ValueError, match=msg): + midx.isin(values) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_join.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..b609b70ace5d750fdf2f48088ea28a9d97438420 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_join.py @@ -0,0 +1,268 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize("other", [["three", "one", "two"], ["one"], ["one", "three"]]) +def test_join_level(idx, other, join_type): + other = pd.Index(other) + join_index, lidx, ridx = other.join( + idx, how=join_type, level="second", return_indexers=True + ) + + exp_level = other.join(idx.levels[1], how=join_type) + assert join_index.levels[0].equals(idx.levels[0]) + assert join_index.levels[1].equals(exp_level) + + # pare down levels + mask = np.array([x[1] in exp_level for x in idx], dtype=bool) + exp_values = idx.values[mask] + tm.assert_numpy_array_equal(join_index.values, exp_values) + + if join_type in ("outer", "inner"): + join_index2, ridx2, lidx2 = idx.join( + other, how=join_type, level="second", return_indexers=True + ) + + assert join_index.equals(join_index2) + tm.assert_numpy_array_equal(lidx, lidx2) + if ridx is None: + assert ridx == ridx2 + else: + tm.assert_numpy_array_equal(ridx, ridx2) + tm.assert_numpy_array_equal(join_index2.values, exp_values) + + +def test_join_level_corner_case(idx): + # some corner cases + index = pd.Index(["three", "one", "two"]) + result = index.join(idx, level="second") + assert isinstance(result, pd.MultiIndex) + + with pytest.raises(TypeError, match="Join.*MultiIndex.*ambiguous"): + idx.join(idx, level=1) + + +def test_join_self(idx, join_type): + result = idx.join(idx, how=join_type) + expected = idx + if join_type == "outer": + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + +def test_join_multi(): + # GH 10665 + midx = pd.MultiIndex.from_product([np.arange(4), np.arange(4)], names=["a", "b"]) + idx = pd.Index([1, 2, 5], name="b") + + # inner + jidx, lidx, ridx = midx.join(idx, how="inner", return_indexers=True) + exp_idx = pd.MultiIndex.from_product([np.arange(4), [1, 2]], names=["a", "b"]) + exp_lidx = np.array([1, 2, 5, 6, 9, 10, 13, 14], dtype=np.intp) + exp_ridx = np.array([0, 1, 0, 1, 0, 1, 0, 1], dtype=np.intp) + tm.assert_index_equal(jidx, exp_idx) + tm.assert_numpy_array_equal(lidx, exp_lidx) + tm.assert_numpy_array_equal(ridx, exp_ridx) + # flip + jidx, ridx, lidx = idx.join(midx, how="inner", return_indexers=True) + tm.assert_index_equal(jidx, exp_idx) + tm.assert_numpy_array_equal(lidx, exp_lidx) + tm.assert_numpy_array_equal(ridx, exp_ridx) + + # keep MultiIndex + jidx, lidx, ridx = midx.join(idx, how="left", return_indexers=True) + exp_ridx = np.array( + [-1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1], dtype=np.intp + ) + tm.assert_index_equal(jidx, midx) + assert lidx is None + tm.assert_numpy_array_equal(ridx, exp_ridx) + # flip + jidx, ridx, lidx = idx.join(midx, how="right", return_indexers=True) + tm.assert_index_equal(jidx, midx) + assert lidx is None + tm.assert_numpy_array_equal(ridx, exp_ridx) + + +def test_join_multi_wrong_order(): + # GH 25760 + # GH 28956 + + midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"]) + midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"]) + + join_idx, lidx, ridx = midx1.join(midx2, return_indexers=True) + + exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp) + + tm.assert_index_equal(midx1, join_idx) + assert lidx is None + tm.assert_numpy_array_equal(ridx, exp_ridx) + + +def test_join_multi_return_indexers(): + # GH 34074 + + midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4], [5, 6]], names=["a", "b", "c"]) + midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"]) + + result = midx1.join(midx2, return_indexers=False) + tm.assert_index_equal(result, midx1) + + +def test_join_overlapping_interval_level(): + # GH 44096 + idx_1 = pd.MultiIndex.from_tuples( + [ + (1, pd.Interval(0.0, 1.0)), + (1, pd.Interval(1.0, 2.0)), + (1, pd.Interval(2.0, 5.0)), + (2, pd.Interval(0.0, 1.0)), + (2, pd.Interval(1.0, 3.0)), # interval limit is here at 3.0, not at 2.0 + (2, pd.Interval(3.0, 5.0)), + ], + names=["num", "interval"], + ) + + idx_2 = pd.MultiIndex.from_tuples( + [ + (1, pd.Interval(2.0, 5.0)), + (1, pd.Interval(0.0, 1.0)), + (1, pd.Interval(1.0, 2.0)), + (2, pd.Interval(3.0, 5.0)), + (2, pd.Interval(0.0, 1.0)), + (2, pd.Interval(1.0, 3.0)), + ], + names=["num", "interval"], + ) + + expected = pd.MultiIndex.from_tuples( + [ + (1, pd.Interval(0.0, 1.0)), + (1, pd.Interval(1.0, 2.0)), + (1, pd.Interval(2.0, 5.0)), + (2, pd.Interval(0.0, 1.0)), + (2, pd.Interval(1.0, 3.0)), + (2, pd.Interval(3.0, 5.0)), + ], + names=["num", "interval"], + ) + result = idx_1.join(idx_2, how="outer") + + tm.assert_index_equal(result, expected) + + +def test_join_midx_ea(): + # GH#49277 + midx = pd.MultiIndex.from_arrays( + [pd.Series([1, 1, 3], dtype="Int64"), pd.Series([1, 2, 3], dtype="Int64")], + names=["a", "b"], + ) + midx2 = pd.MultiIndex.from_arrays( + [pd.Series([1], dtype="Int64"), pd.Series([3], dtype="Int64")], names=["a", "c"] + ) + result = midx.join(midx2, how="inner") + expected = pd.MultiIndex.from_arrays( + [ + pd.Series([1, 1], dtype="Int64"), + pd.Series([1, 2], dtype="Int64"), + pd.Series([3, 3], dtype="Int64"), + ], + names=["a", "b", "c"], + ) + tm.assert_index_equal(result, expected) + + +def test_join_midx_string(): + # GH#49277 + midx = pd.MultiIndex.from_arrays( + [ + pd.Series(["a", "a", "c"], dtype=pd.StringDtype()), + pd.Series(["a", "b", "c"], dtype=pd.StringDtype()), + ], + names=["a", "b"], + ) + midx2 = pd.MultiIndex.from_arrays( + [ + pd.Series(["a"], dtype=pd.StringDtype()), + pd.Series(["c"], dtype=pd.StringDtype()), + ], + names=["a", "c"], + ) + result = midx.join(midx2, how="inner") + expected = pd.MultiIndex.from_arrays( + [ + pd.Series(["a", "a"], dtype=pd.StringDtype()), + pd.Series(["a", "b"], dtype=pd.StringDtype()), + pd.Series(["c", "c"], dtype=pd.StringDtype()), + ], + names=["a", "b", "c"], + ) + tm.assert_index_equal(result, expected) + + +def test_join_multi_with_nan(): + # GH29252 + df1 = pd.DataFrame( + data={"col1": [1.1, 1.2]}, + index=pd.MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"]), + ) + df2 = pd.DataFrame( + data={"col2": [2.1, 2.2]}, + index=pd.MultiIndex.from_product([["A"], [np.nan, 2.0]], names=["id1", "id2"]), + ) + result = df1.join(df2) + expected = pd.DataFrame( + data={"col1": [1.1, 1.2], "col2": [np.nan, 2.2]}, + index=pd.MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"]), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("val", [0, 5]) +def test_join_dtypes(any_numeric_ea_dtype, val): + # GH#49830 + midx = pd.MultiIndex.from_arrays( + [pd.Series([1, 2], dtype=any_numeric_ea_dtype), [3, 4]] + ) + midx2 = pd.MultiIndex.from_arrays( + [pd.Series([1, val, val], dtype=any_numeric_ea_dtype), [3, 4, 4]] + ) + result = midx.join(midx2, how="outer") + expected = pd.MultiIndex.from_arrays( + [pd.Series([val, val, 1, 2], dtype=any_numeric_ea_dtype), [4, 4, 3, 4]] + ).sort_values() + tm.assert_index_equal(result, expected) + + +def test_join_dtypes_all_nan(any_numeric_ea_dtype): + # GH#49830 + midx = pd.MultiIndex.from_arrays( + [pd.Series([1, 2], dtype=any_numeric_ea_dtype), [np.nan, np.nan]] + ) + midx2 = pd.MultiIndex.from_arrays( + [pd.Series([1, 0, 0], dtype=any_numeric_ea_dtype), [np.nan, np.nan, np.nan]] + ) + result = midx.join(midx2, how="outer") + expected = pd.MultiIndex.from_arrays( + [ + pd.Series([0, 0, 1, 2], dtype=any_numeric_ea_dtype), + [np.nan, np.nan, np.nan, np.nan], + ] + ) + tm.assert_index_equal(result, expected) + + +def test_join_index_levels(): + # GH#53093 + midx = pd.MultiIndex.from_tuples([("a", "2019-02-01"), ("a", "2019-02-01")]) + midx2 = pd.MultiIndex.from_tuples([("a", "2019-01-31")]) + result = midx.join(midx2, how="outer") + expected = pd.MultiIndex.from_tuples( + [("a", "2019-01-31"), ("a", "2019-02-01"), ("a", "2019-02-01")] + ) + tm.assert_index_equal(result.levels[1], expected.levels[1]) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_lexsort.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_lexsort.py new file mode 100644 index 0000000000000000000000000000000000000000..9b96b3a0eb26bfb81500510d6de922d6802b1470 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_lexsort.py @@ -0,0 +1,46 @@ +import pandas as pd + + +class TestIsLexsorted: + def test_is_lexsorted(self): + levels = [[0, 1], [0, 1, 2]] + + index = pd.MultiIndex( + levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]] + ) + assert index._is_lexsorted() + + index = pd.MultiIndex( + levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]] + ) + assert not index._is_lexsorted() + + index = pd.MultiIndex( + levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]] + ) + assert not index._is_lexsorted() + assert index._lexsort_depth == 0 + + +class TestLexsortDepth: + def test_lexsort_depth(self): + # Test that lexsort_depth return the correct sortorder + # when it was given to the MultiIndex const. + # GH#28518 + + levels = [[0, 1], [0, 1, 2]] + + index = pd.MultiIndex( + levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], sortorder=2 + ) + assert index._lexsort_depth == 2 + + index = pd.MultiIndex( + levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=1 + ) + assert index._lexsort_depth == 1 + + index = pd.MultiIndex( + levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=0 + ) + assert index._lexsort_depth == 0 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_missing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_missing.py new file mode 100644 index 0000000000000000000000000000000000000000..e42fe5f6935e0bea912196c1a22fcc6985847913 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_missing.py @@ -0,0 +1,112 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_fillna(idx): + # GH 11343 + msg = "fillna is not defined for MultiIndex" + with pytest.raises(NotImplementedError, match=msg): + idx.fillna(idx[0]) + + +def test_dropna(): + # GH 6194 + idx = pd.MultiIndex.from_arrays( + [ + [1, np.nan, 3, np.nan, 5], + [1, 2, np.nan, np.nan, 5], + ["a", "b", "c", np.nan, "e"], + ] + ) + + exp = pd.MultiIndex.from_arrays([[1, 5], [1, 5], ["a", "e"]]) + tm.assert_index_equal(idx.dropna(), exp) + tm.assert_index_equal(idx.dropna(how="any"), exp) + + exp = pd.MultiIndex.from_arrays( + [[1, np.nan, 3, 5], [1, 2, np.nan, 5], ["a", "b", "c", "e"]] + ) + tm.assert_index_equal(idx.dropna(how="all"), exp) + + msg = "invalid how option: xxx" + with pytest.raises(ValueError, match=msg): + idx.dropna(how="xxx") + + # GH26408 + # test if missing values are dropped for multiindex constructed + # from codes and values + idx = pd.MultiIndex( + levels=[[np.nan, None, pd.NaT, "128", 2], [np.nan, None, pd.NaT, "128", 2]], + codes=[[0, -1, 1, 2, 3, 4], [0, -1, 3, 3, 3, 4]], + ) + expected = pd.MultiIndex.from_arrays([["128", 2], ["128", 2]]) + tm.assert_index_equal(idx.dropna(), expected) + tm.assert_index_equal(idx.dropna(how="any"), expected) + + expected = pd.MultiIndex.from_arrays( + [[np.nan, np.nan, "128", 2], ["128", "128", "128", 2]] + ) + tm.assert_index_equal(idx.dropna(how="all"), expected) + + +def test_nulls(idx): + # this is really a smoke test for the methods + # as these are adequately tested for function elsewhere + + msg = "isna is not defined for MultiIndex" + with pytest.raises(NotImplementedError, match=msg): + idx.isna() + + +@pytest.mark.xfail(reason="isna is not defined for MultiIndex") +def test_hasnans_isnans(idx): + # GH 11343, added tests for hasnans / isnans + index = idx.copy() + + # cases in indices doesn't include NaN + expected = np.array([False] * len(index), dtype=bool) + tm.assert_numpy_array_equal(index._isnan, expected) + assert index.hasnans is False + + index = idx.copy() + values = index.values + values[1] = np.nan + + index = type(idx)(values) + + expected = np.array([False] * len(index), dtype=bool) + expected[1] = True + tm.assert_numpy_array_equal(index._isnan, expected) + assert index.hasnans is True + + +def test_nan_stays_float(): + # GH 7031 + idx0 = pd.MultiIndex( + levels=[["A", "B"], []], codes=[[1, 0], [-1, -1]], names=[0, 1] + ) + idx1 = pd.MultiIndex(levels=[["C"], ["D"]], codes=[[0], [0]], names=[0, 1]) + idxm = idx0.join(idx1, how="outer") + assert pd.isna(idx0.get_level_values(1)).all() + # the following failed in 0.14.1 + assert pd.isna(idxm.get_level_values(1)[:-1]).all() + + df0 = pd.DataFrame([[1, 2]], index=idx0) + df1 = pd.DataFrame([[3, 4]], index=idx1) + dfm = df0 - df1 + assert pd.isna(df0.index.get_level_values(1)).all() + # the following failed in 0.14.1 + assert pd.isna(dfm.index.get_level_values(1)[:-1]).all() + + +def test_tuples_have_na(): + index = pd.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]], + ) + + assert pd.isna(index[4][0]) + assert pd.isna(index.values[4][0]) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_monotonic.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_monotonic.py new file mode 100644 index 0000000000000000000000000000000000000000..da888e78a38fab5d3c8a4353eae1f59c32e9f28e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_monotonic.py @@ -0,0 +1,185 @@ +import numpy as np +import pytest + +import pandas as pd + + +def test_is_monotonic_increasing_lexsorted(lexsorted_two_level_string_multiindex): + # string ordering + mi = lexsorted_two_level_string_multiindex + assert mi.is_monotonic_increasing is False + assert pd.Index(mi.values).is_monotonic_increasing is False + assert mi._is_strictly_monotonic_increasing is False + assert pd.Index(mi.values)._is_strictly_monotonic_increasing is False + + +def test_is_monotonic_increasing(): + i = pd.MultiIndex.from_product([np.arange(10), np.arange(10)], names=["one", "two"]) + assert i.is_monotonic_increasing is True + assert i._is_strictly_monotonic_increasing is True + assert pd.Index(i.values).is_monotonic_increasing is True + assert i._is_strictly_monotonic_increasing is True + + i = pd.MultiIndex.from_product( + [np.arange(10, 0, -1), np.arange(10)], names=["one", "two"] + ) + assert i.is_monotonic_increasing is False + assert i._is_strictly_monotonic_increasing is False + assert pd.Index(i.values).is_monotonic_increasing is False + assert pd.Index(i.values)._is_strictly_monotonic_increasing is False + + i = pd.MultiIndex.from_product( + [np.arange(10), np.arange(10, 0, -1)], names=["one", "two"] + ) + assert i.is_monotonic_increasing is False + assert i._is_strictly_monotonic_increasing is False + assert pd.Index(i.values).is_monotonic_increasing is False + assert pd.Index(i.values)._is_strictly_monotonic_increasing is False + + i = pd.MultiIndex.from_product([[1.0, np.nan, 2.0], ["a", "b", "c"]]) + assert i.is_monotonic_increasing is False + assert i._is_strictly_monotonic_increasing is False + assert pd.Index(i.values).is_monotonic_increasing is False + assert pd.Index(i.values)._is_strictly_monotonic_increasing is False + + i = pd.MultiIndex( + levels=[["bar", "baz", "foo", "qux"], ["mom", "next", "zenith"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["first", "second"], + ) + assert i.is_monotonic_increasing is True + assert pd.Index(i.values).is_monotonic_increasing is True + assert i._is_strictly_monotonic_increasing is True + assert pd.Index(i.values)._is_strictly_monotonic_increasing is True + + # mixed levels, hits the TypeError + i = pd.MultiIndex( + levels=[ + [1, 2, 3, 4], + [ + "gb00b03mlx29", + "lu0197800237", + "nl0000289783", + "nl0000289965", + "nl0000301109", + ], + ], + codes=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]], + names=["household_id", "asset_id"], + ) + + assert i.is_monotonic_increasing is False + assert i._is_strictly_monotonic_increasing is False + + # empty + i = pd.MultiIndex.from_arrays([[], []]) + assert i.is_monotonic_increasing is True + assert pd.Index(i.values).is_monotonic_increasing is True + assert i._is_strictly_monotonic_increasing is True + assert pd.Index(i.values)._is_strictly_monotonic_increasing is True + + +def test_is_monotonic_decreasing(): + i = pd.MultiIndex.from_product( + [np.arange(9, -1, -1), np.arange(9, -1, -1)], names=["one", "two"] + ) + assert i.is_monotonic_decreasing is True + assert i._is_strictly_monotonic_decreasing is True + assert pd.Index(i.values).is_monotonic_decreasing is True + assert i._is_strictly_monotonic_decreasing is True + + i = pd.MultiIndex.from_product( + [np.arange(10), np.arange(10, 0, -1)], names=["one", "two"] + ) + assert i.is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False + assert pd.Index(i.values).is_monotonic_decreasing is False + assert pd.Index(i.values)._is_strictly_monotonic_decreasing is False + + i = pd.MultiIndex.from_product( + [np.arange(10, 0, -1), np.arange(10)], names=["one", "two"] + ) + assert i.is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False + assert pd.Index(i.values).is_monotonic_decreasing is False + assert pd.Index(i.values)._is_strictly_monotonic_decreasing is False + + i = pd.MultiIndex.from_product([[2.0, np.nan, 1.0], ["c", "b", "a"]]) + assert i.is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False + assert pd.Index(i.values).is_monotonic_decreasing is False + assert pd.Index(i.values)._is_strictly_monotonic_decreasing is False + + # string ordering + i = pd.MultiIndex( + levels=[["qux", "foo", "baz", "bar"], ["three", "two", "one"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["first", "second"], + ) + assert i.is_monotonic_decreasing is False + assert pd.Index(i.values).is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False + assert pd.Index(i.values)._is_strictly_monotonic_decreasing is False + + i = pd.MultiIndex( + levels=[["qux", "foo", "baz", "bar"], ["zenith", "next", "mom"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["first", "second"], + ) + assert i.is_monotonic_decreasing is True + assert pd.Index(i.values).is_monotonic_decreasing is True + assert i._is_strictly_monotonic_decreasing is True + assert pd.Index(i.values)._is_strictly_monotonic_decreasing is True + + # mixed levels, hits the TypeError + i = pd.MultiIndex( + levels=[ + [4, 3, 2, 1], + [ + "nl0000301109", + "nl0000289965", + "nl0000289783", + "lu0197800237", + "gb00b03mlx29", + ], + ], + codes=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]], + names=["household_id", "asset_id"], + ) + + assert i.is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False + + # empty + i = pd.MultiIndex.from_arrays([[], []]) + assert i.is_monotonic_decreasing is True + assert pd.Index(i.values).is_monotonic_decreasing is True + assert i._is_strictly_monotonic_decreasing is True + assert pd.Index(i.values)._is_strictly_monotonic_decreasing is True + + +def test_is_strictly_monotonic_increasing(): + idx = pd.MultiIndex( + levels=[["bar", "baz"], ["mom", "next"]], codes=[[0, 0, 1, 1], [0, 0, 0, 1]] + ) + assert idx.is_monotonic_increasing is True + assert idx._is_strictly_monotonic_increasing is False + + +def test_is_strictly_monotonic_decreasing(): + idx = pd.MultiIndex( + levels=[["baz", "bar"], ["next", "mom"]], codes=[[0, 0, 1, 1], [0, 0, 0, 1]] + ) + assert idx.is_monotonic_decreasing is True + assert idx._is_strictly_monotonic_decreasing is False + + +@pytest.mark.parametrize("attr", ["is_monotonic_increasing", "is_monotonic_decreasing"]) +@pytest.mark.parametrize( + "values", + [[(np.nan,), (1,), (2,)], [(1,), (np.nan,), (2,)], [(1,), (2,), (np.nan,)]], +) +def test_is_monotonic_with_nans(values, attr): + # GH: 37220 + idx = pd.MultiIndex.from_tuples(values, names=["test"]) + assert getattr(idx, attr) is False diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_names.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_names.py new file mode 100644 index 0000000000000000000000000000000000000000..1790bdebaec15740285acb71aefb5181b960da26 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_names.py @@ -0,0 +1,202 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +def check_level_names(index, names): + assert [level.name for level in index.levels] == list(names) + + +def test_slice_keep_name(): + x = pd.MultiIndex.from_tuples([("a", "b"), (1, 2), ("c", "d")], names=["x", "y"]) + assert x[1:].names == x.names + + +def test_index_name_retained(): + # GH9857 + result = pd.DataFrame({"x": [1, 2, 6], "y": [2, 2, 8], "z": [-5, 0, 5]}) + result = result.set_index("z") + result.loc[10] = [9, 10] + df_expected = pd.DataFrame( + {"x": [1, 2, 6, 9], "y": [2, 2, 8, 10], "z": [-5, 0, 5, 10]} + ) + df_expected = df_expected.set_index("z") + tm.assert_frame_equal(result, df_expected) + + +def test_changing_names(idx): + assert [level.name for level in idx.levels] == ["first", "second"] + + view = idx.view() + copy = idx.copy() + shallow_copy = idx._view() + + # changing names should not change level names on object + new_names = [name + "a" for name in idx.names] + idx.names = new_names + check_level_names(idx, ["firsta", "seconda"]) + + # and not on copies + check_level_names(view, ["first", "second"]) + check_level_names(copy, ["first", "second"]) + check_level_names(shallow_copy, ["first", "second"]) + + # and copies shouldn't change original + shallow_copy.names = [name + "c" for name in shallow_copy.names] + check_level_names(idx, ["firsta", "seconda"]) + + +def test_take_preserve_name(idx): + taken = idx.take([3, 0, 1]) + assert taken.names == idx.names + + +def test_copy_names(): + # Check that adding a "names" parameter to the copy is honored + # GH14302 + multi_idx = pd.MultiIndex.from_tuples( + [(1, 2), (3, 4)], names=["MyName1", "MyName2"] + ) + multi_idx1 = multi_idx.copy() + + assert multi_idx.equals(multi_idx1) + assert multi_idx.names == ["MyName1", "MyName2"] + assert multi_idx1.names == ["MyName1", "MyName2"] + + multi_idx2 = multi_idx.copy(names=["NewName1", "NewName2"]) + + assert multi_idx.equals(multi_idx2) + assert multi_idx.names == ["MyName1", "MyName2"] + assert multi_idx2.names == ["NewName1", "NewName2"] + + multi_idx3 = multi_idx.copy(name=["NewName1", "NewName2"]) + + assert multi_idx.equals(multi_idx3) + assert multi_idx.names == ["MyName1", "MyName2"] + assert multi_idx3.names == ["NewName1", "NewName2"] + + # gh-35592 + with pytest.raises(ValueError, match="Length of new names must be 2, got 1"): + multi_idx.copy(names=["mario"]) + + with pytest.raises(TypeError, match="MultiIndex.name must be a hashable type"): + multi_idx.copy(names=[["mario"], ["luigi"]]) + + +def test_names(idx): + # names are assigned in setup + assert idx.names == ["first", "second"] + level_names = [level.name for level in idx.levels] + assert level_names == idx.names + + # setting bad names on existing + index = idx + with pytest.raises(ValueError, match="^Length of names"): + setattr(index, "names", [*list(index.names), "third"]) + with pytest.raises(ValueError, match="^Length of names"): + setattr(index, "names", []) + + # initializing with bad names (should always be equivalent) + major_axis, minor_axis = idx.levels + major_codes, minor_codes = idx.codes + with pytest.raises(ValueError, match="^Length of names"): + pd.MultiIndex( + levels=[major_axis, minor_axis], + codes=[major_codes, minor_codes], + names=["first"], + ) + with pytest.raises(ValueError, match="^Length of names"): + pd.MultiIndex( + levels=[major_axis, minor_axis], + codes=[major_codes, minor_codes], + names=["first", "second", "third"], + ) + + # names are assigned on index, but not transferred to the levels + index.names = ["a", "b"] + level_names = [level.name for level in index.levels] + assert level_names == ["a", "b"] + + +def test_duplicate_level_names_access_raises(idx): + # GH19029 + idx.names = ["foo", "foo"] + with pytest.raises(ValueError, match="name foo occurs multiple times"): + idx._get_level_number("foo") + + +def test_get_names_from_levels(): + idx = pd.MultiIndex.from_product([["a"], [1, 2]], names=["a", "b"]) + + assert idx.levels[0].name == "a" + assert idx.levels[1].name == "b" + + +def test_setting_names_from_levels_raises(): + idx = pd.MultiIndex.from_product([["a"], [1, 2]], names=["a", "b"]) + with pytest.raises(RuntimeError, match="set_names"): + idx.levels[0].name = "foo" + + with pytest.raises(RuntimeError, match="set_names"): + idx.levels[1].name = "foo" + + new = pd.Series(1, index=idx.levels[0]) + with pytest.raises(RuntimeError, match="set_names"): + new.index.name = "bar" + + assert pd.Index._no_setting_name is False + assert pd.RangeIndex._no_setting_name is False + + +@pytest.mark.parametrize("func", ["rename", "set_names"]) +@pytest.mark.parametrize( + "rename_dict, exp_names", + [ + ({"x": "z"}, ["z", "y", "z"]), + ({"x": "z", "y": "x"}, ["z", "x", "z"]), + ({"y": "z"}, ["x", "z", "x"]), + ({}, ["x", "y", "x"]), + ({"z": "a"}, ["x", "y", "x"]), + ({"y": "z", "a": "b"}, ["x", "z", "x"]), + ], +) +def test_name_mi_with_dict_like_duplicate_names(func, rename_dict, exp_names): + # GH#20421 + mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4], [5, 6]], names=["x", "y", "x"]) + result = getattr(mi, func)(rename_dict) + expected = pd.MultiIndex.from_arrays([[1, 2], [3, 4], [5, 6]], names=exp_names) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("func", ["rename", "set_names"]) +@pytest.mark.parametrize( + "rename_dict, exp_names", + [ + ({"x": "z"}, ["z", "y"]), + ({"x": "z", "y": "x"}, ["z", "x"]), + ({"a": "z"}, ["x", "y"]), + ({}, ["x", "y"]), + ], +) +def test_name_mi_with_dict_like(func, rename_dict, exp_names): + # GH#20421 + mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["x", "y"]) + result = getattr(mi, func)(rename_dict) + expected = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=exp_names) + tm.assert_index_equal(result, expected) + + +def test_index_name_with_dict_like_raising(): + # GH#20421 + ix = pd.Index([1, 2]) + msg = "Can only pass dict-like as `names` for MultiIndex." + with pytest.raises(TypeError, match=msg): + ix.set_names({"x": "z"}) + + +def test_multiindex_name_and_level_raising(): + # GH#20421 + mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["x", "y"]) + with pytest.raises(TypeError, match="Can not pass level for dictlike `names`."): + mi.set_names(names={"x": "z"}, level={"x": "z"}) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_partial_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_partial_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..507bc961121221dfad00c740395eaddc7c71674f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_partial_indexing.py @@ -0,0 +1,143 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def df(): + # c1 + # 2016-01-01 00:00:00 a 0 + # b 1 + # c 2 + # 2016-01-01 12:00:00 a 3 + # b 4 + # c 5 + # 2016-01-02 00:00:00 a 6 + # b 7 + # c 8 + # 2016-01-02 12:00:00 a 9 + # b 10 + # c 11 + # 2016-01-03 00:00:00 a 12 + # b 13 + # c 14 + dr = pd.date_range("2016-01-01", "2016-01-03", freq="12h") + abc = ["a", "b", "c"] + mi = pd.MultiIndex.from_product([dr, abc]) + frame = pd.DataFrame({"c1": range(15)}, index=mi) + return frame + + +def test_partial_string_matching_single_index(df): + # partial string matching on a single index + for df_swap in [df.swaplevel(), df.swaplevel(0), df.swaplevel(0, 1)]: + df_swap = df_swap.sort_index() + just_a = df_swap.loc["a"] + result = just_a.loc["2016-01-01"] + expected = df.loc[pd.IndexSlice[:, "a"], :].iloc[0:2] + expected.index = expected.index.droplevel(1) + tm.assert_frame_equal(result, expected) + + +def test_get_loc_partial_timestamp_multiindex(df): + mi = df.index + key = ("2016-01-01", "a") + loc = mi.get_loc(key) + + expected = np.zeros(len(mi), dtype=bool) + expected[[0, 3]] = True + tm.assert_numpy_array_equal(loc, expected) + + key2 = ("2016-01-02", "a") + loc2 = mi.get_loc(key2) + expected2 = np.zeros(len(mi), dtype=bool) + expected2[[6, 9]] = True + tm.assert_numpy_array_equal(loc2, expected2) + + key3 = ("2016-01", "a") + loc3 = mi.get_loc(key3) + expected3 = np.zeros(len(mi), dtype=bool) + expected3[mi.get_level_values(1).get_loc("a")] = True + tm.assert_numpy_array_equal(loc3, expected3) + + key4 = ("2016", "a") + loc4 = mi.get_loc(key4) + expected4 = expected3 + tm.assert_numpy_array_equal(loc4, expected4) + + # non-monotonic + taker = np.arange(len(mi), dtype=np.intp) + taker[::2] = taker[::-2] + mi2 = mi.take(taker) + loc5 = mi2.get_loc(key) + expected5 = np.zeros(len(mi2), dtype=bool) + expected5[[3, 14]] = True + tm.assert_numpy_array_equal(loc5, expected5) + + +def test_partial_string_timestamp_multiindex(df): + # GH10331 + df_swap = df.swaplevel(0, 1).sort_index() + SLC = pd.IndexSlice + + # indexing with IndexSlice + result = df.loc[SLC["2016-01-01":"2016-02-01", :], :] + expected = df + tm.assert_frame_equal(result, expected) + + # match on secondary index + result = df_swap.loc[SLC[:, "2016-01-01":"2016-01-01"], :] + expected = df_swap.iloc[[0, 1, 5, 6, 10, 11]] + tm.assert_frame_equal(result, expected) + + # partial string match on year only + result = df.loc["2016"] + expected = df + tm.assert_frame_equal(result, expected) + + # partial string match on date + result = df.loc["2016-01-01"] + expected = df.iloc[0:6] + tm.assert_frame_equal(result, expected) + + # partial string match on date and hour, from middle + result = df.loc["2016-01-02 12"] + # hourly resolution, same as index.levels[0], so we are _not_ slicing on + # that level, so that level gets dropped + expected = df.iloc[9:12].droplevel(0) + tm.assert_frame_equal(result, expected) + + # partial string match on secondary index + result = df_swap.loc[SLC[:, "2016-01-02"], :] + expected = df_swap.iloc[[2, 3, 7, 8, 12, 13]] + tm.assert_frame_equal(result, expected) + + # tuple selector with partial string match on date + # "2016-01-01" has daily resolution, so _is_ a slice on the first level. + result = df.loc[("2016-01-01", "a"), :] + expected = df.iloc[[0, 3]] + expected = df.iloc[[0, 3]].droplevel(1) + tm.assert_frame_equal(result, expected) + + # Slicing date on first level should break (of course) bc the DTI is the + # second level on df_swap + with pytest.raises(KeyError, match="'2016-01-01'"): + df_swap.loc["2016-01-01"] + + +def test_partial_string_timestamp_multiindex_str_key_raises(df): + # Even though this syntax works on a single index, this is somewhat + # ambiguous and we don't want to extend this behavior forward to work + # in multi-indexes. This would amount to selecting a scalar from a + # column. + with pytest.raises(KeyError, match="'2016-01-01'"): + df["2016-01-01"] + + +def test_partial_string_timestamp_multiindex_daily_resolution(df): + # GH12685 (partial string with daily resolution or below) + result = df.loc[pd.IndexSlice["2013-03":"2013-03", :], :] + expected = df.iloc[118:180] + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_pickle.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..20cd42dd92232591f2d0f1174dc86483f419cf8a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_pickle.py @@ -0,0 +1,27 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_pickle_compat_construction(): + # this is testing for pickle compat + # need an object to create with + with pytest.raises(TypeError, match="Must pass both levels and codes"): + pd.MultiIndex() + + +def test_multiindex_datetime64ns_pickle_roundtrip(tmp_path): + # GH#63078 - pickling a MultiIndex with datetime64[ns] level raised + # NotImplementedError in NDArrayBacked.__setstate__ + df = pd.DataFrame( + { + "date": [np.datetime64("20110101", "ns")], + "id": [1], + "val": [1], + } + ).set_index(["date", "id"]) + + result = tm.round_trip_pickle(df, tmp_path / "test.pkl") + tm.assert_frame_equal(result, df) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_reindex.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_reindex.py new file mode 100644 index 0000000000000000000000000000000000000000..6123366fbed232c1efab0a36f7e44083abedac11 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_reindex.py @@ -0,0 +1,182 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_reindex(idx): + result, indexer = idx.reindex(list(idx[:4])) + assert isinstance(result, pd.MultiIndex) + assert result.names == ["first", "second"] + assert [level.name for level in result.levels] == ["first", "second"] + + result, indexer = idx.reindex(list(idx)) + assert isinstance(result, pd.MultiIndex) + assert indexer is None + assert result.names == ["first", "second"] + assert [level.name for level in result.levels] == ["first", "second"] + + +def test_reindex_level(idx): + index = pd.Index(["one"]) + + target, indexer = idx.reindex(index, level="second") + target2, indexer2 = index.reindex(idx, level="second") + + exp_index = idx.join(index, level="second", how="right") + exp_index2 = idx.join(index, level="second", how="left") + + assert target.equals(exp_index) + exp_indexer = np.array([0, 2, 4]) + tm.assert_numpy_array_equal(indexer, exp_indexer, check_dtype=False) + + assert target2.equals(exp_index2) + exp_indexer2 = np.array([0, -1, 0, -1, 0, -1]) + tm.assert_numpy_array_equal(indexer2, exp_indexer2, check_dtype=False) + + with pytest.raises(TypeError, match="Fill method not supported"): + idx.reindex(idx, method="pad", level="second") + + +def test_reindex_preserves_names_when_target_is_list_or_ndarray(idx): + # GH6552 + idx = idx.copy() + target = idx.copy() + idx.names = target.names = [None, None] + + other_dtype = pd.MultiIndex.from_product([[1, 2], [3, 4]]) + + # list & ndarray cases + assert idx.reindex([])[0].names == [None, None] + assert idx.reindex(np.array([]))[0].names == [None, None] + assert idx.reindex(target.tolist())[0].names == [None, None] + assert idx.reindex(target.values)[0].names == [None, None] + assert idx.reindex(other_dtype.tolist())[0].names == [None, None] + assert idx.reindex(other_dtype.values)[0].names == [None, None] + + idx.names = ["foo", "bar"] + assert idx.reindex([])[0].names == ["foo", "bar"] + assert idx.reindex(np.array([]))[0].names == ["foo", "bar"] + assert idx.reindex(target.tolist())[0].names == ["foo", "bar"] + assert idx.reindex(target.values)[0].names == ["foo", "bar"] + assert idx.reindex(other_dtype.tolist())[0].names == ["foo", "bar"] + assert idx.reindex(other_dtype.values)[0].names == ["foo", "bar"] + + +def test_reindex_lvl_preserves_names_when_target_is_list_or_array(): + # GH7774 + idx = pd.MultiIndex.from_product([[0, 1], ["a", "b"]], names=["foo", "bar"]) + assert idx.reindex([], level=0)[0].names == ["foo", "bar"] + assert idx.reindex([], level=1)[0].names == ["foo", "bar"] + + +def test_reindex_lvl_preserves_type_if_target_is_empty_list_or_array( + using_infer_string, +): + # GH7774 + idx = pd.MultiIndex.from_product([[0, 1], ["a", "b"]]) + assert idx.reindex([], level=0)[0].levels[0].dtype.type == np.int64 + exp = np.object_ if not using_infer_string else str + assert idx.reindex([], level=1)[0].levels[1].dtype.type == exp + + # case with EA levels + cat = pd.Categorical(["foo", "bar"]) + dti = pd.date_range("2016-01-01", periods=2, tz="US/Pacific") + mi = pd.MultiIndex.from_product([cat, dti]) + assert mi.reindex([], level=0)[0].levels[0].dtype == cat.dtype + assert mi.reindex([], level=1)[0].levels[1].dtype == dti.dtype + + +def test_reindex_base(idx): + expected = np.arange(idx.size, dtype=np.intp) + + actual = idx.get_indexer(idx) + tm.assert_numpy_array_equal(expected, actual) + + with pytest.raises(ValueError, match="Invalid fill method"): + idx.get_indexer(idx, method="invalid") + + +def test_reindex_non_unique(): + idx = pd.MultiIndex.from_tuples([(0, 0), (1, 1), (1, 1), (2, 2)]) + a = pd.Series(np.arange(4), index=idx) + new_idx = pd.MultiIndex.from_tuples([(0, 0), (1, 1), (2, 2)]) + + msg = "cannot handle a non-unique multi-index!" + with pytest.raises(ValueError, match=msg): + a.reindex(new_idx) + + +@pytest.mark.parametrize("values", [[["a"], ["x"]], [[], []]]) +def test_reindex_empty_with_level(values): + # GH41170 + idx = pd.MultiIndex.from_arrays(values) + result, result_indexer = idx.reindex(np.array(["b"]), level=0) + expected = pd.MultiIndex(levels=[["b"], values[1]], codes=[[], []]) + expected_indexer = np.array([], dtype=result_indexer.dtype) + tm.assert_index_equal(result, expected) + tm.assert_numpy_array_equal(result_indexer, expected_indexer) + + +def test_reindex_not_all_tuples(): + keys = [("i", "i"), ("i", "j"), ("j", "i"), "j"] + mi = pd.MultiIndex.from_tuples(keys[:-1]) + idx = pd.Index(keys) + res, indexer = mi.reindex(idx) + + tm.assert_index_equal(res, idx) + expected = np.array([0, 1, 2, -1], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + +def test_reindex_flat_non_object_target(): + # GH#26460 reindexing a unique MultiIndex with a non-object (e.g. integer) + # flat target that matches nothing should return the flat target, not raise + mi = pd.MultiIndex.from_tuples([(4, 8), (4, 10)]) + idx = pd.Index([8, 10]) + res, indexer = mi.reindex(idx) + + tm.assert_index_equal(res, idx) + expected = np.array([-1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + +def test_reindex_limit_arg_with_multiindex(): + # GH21247 + + idx = pd.MultiIndex.from_tuples([(3, "A"), (4, "A"), (4, "B")]) + + df = pd.Series([0.02, 0.01, 0.012], index=idx) + + new_idx = pd.MultiIndex.from_tuples( + [ + (3, "A"), + (3, "B"), + (4, "A"), + (4, "B"), + (4, "C"), + (5, "B"), + (5, "C"), + (6, "B"), + (6, "C"), + ] + ) + + with pytest.raises( + ValueError, + match="limit argument only valid if doing pad, backfill or nearest reindexing", + ): + df.reindex(new_idx, fill_value=0, limit=1) + + +def test_reindex_with_none_in_nested_multiindex(): + # GH42883 + index = pd.MultiIndex.from_tuples([(("a", None), 1), (("b", None), 2)]) + index2 = pd.MultiIndex.from_tuples([(("b", None), 2), (("a", None), 1)]) + df1_dtype = pd.DataFrame([1, 2], index=index) + df2_dtype = pd.DataFrame([2, 1], index=index2) + + result = df1_dtype.reindex_like(df2_dtype) + expected = df2_dtype + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_reshape.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_reshape.py new file mode 100644 index 0000000000000000000000000000000000000000..e974f5a23f94c16cf09ce2aab8b608a04b6623f5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_reshape.py @@ -0,0 +1,241 @@ +from datetime import ( + date, + datetime, +) +import zoneinfo + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_insert(idx): + # key contained in all levels + new_index = idx.insert(0, ("bar", "two")) + assert new_index.equal_levels(idx) + assert new_index[0] == ("bar", "two") + + # key not contained in all levels + new_index = idx.insert(0, ("abc", "three")) + + exp0 = pd.Index([*list(idx.levels[0]), "abc"], name="first") + tm.assert_index_equal(new_index.levels[0], exp0) + assert new_index.names == ["first", "second"] + + exp1 = pd.Index([*list(idx.levels[1]), "three"], name="second") + tm.assert_index_equal(new_index.levels[1], exp1) + assert new_index[0] == ("abc", "three") + + # key wrong length + msg = "Item must have length equal to number of levels" + with pytest.raises(ValueError, match=msg): + idx.insert(0, ("foo2",)) + + left = pd.DataFrame([["a", "b", 0], ["b", "d", 1]], columns=["1st", "2nd", "3rd"]) + left = left.set_index(["1st", "2nd"]) + ts = left["3rd"].copy(deep=True) + + left.loc[("b", "x"), "3rd"] = 2 + left.loc[("b", "a"), "3rd"] = -1 + left.loc[("b", "b"), "3rd"] = 3 + left.loc[("a", "x"), "3rd"] = 4 + left.loc[("a", "w"), "3rd"] = 5 + left.loc[("a", "a"), "3rd"] = 6 + + ts.loc[("b", "x")] = 2 + ts.loc["b", "a"] = -1 + ts.loc[("b", "b")] = 3 + ts.loc["a", "x"] = 4 + ts.loc[("a", "w")] = 5 + ts.loc["a", "a"] = 6 + + right = pd.DataFrame( + [ + ["a", "b", 0], + ["b", "d", 1], + ["b", "x", 2], + ["b", "a", -1], + ["b", "b", 3], + ["a", "x", 4], + ["a", "w", 5], + ["a", "a", 6], + ], + columns=["1st", "2nd", "3rd"], + ) + right = right.set_index(["1st", "2nd"]) + tm.assert_frame_equal(left, right) + tm.assert_series_equal(ts, right["3rd"]) + + +def test_insert2(): + # GH9250 + idx = ( + [("test1", i) for i in range(5)] + + [("test2", i) for i in range(6)] + + [("test", 17), ("test", 18)] + ) + + left = pd.Series(np.linspace(0, 10, 11), pd.MultiIndex.from_tuples(idx[:-2])) + + left.loc[("test", 17)] = 11 + left.loc[("test", 18)] = 12 + + right = pd.Series(np.linspace(0, 12, 13), pd.MultiIndex.from_tuples(idx)) + + tm.assert_series_equal(left, right) + + +def test_append(idx): + result = idx[:3].append(idx[3:]) + assert result.equals(idx) + + foos = [idx[:1], idx[1:3], idx[3:]] + result = foos[0].append(foos[1:]) + assert result.equals(idx) + + # empty + result = idx.append([]) + assert result.equals(idx) + + +def test_append_index(): + idx1 = pd.Index([1.1, 1.2, 1.3]) + idx2 = pd.date_range("2011-01-01", freq="D", periods=3, tz="Asia/Tokyo") + idx3 = pd.Index(["A", "B", "C"]) + + midx_lv2 = pd.MultiIndex.from_arrays([idx1, idx2]) + midx_lv3 = pd.MultiIndex.from_arrays([idx1, idx2, idx3]) + + result = idx1.append(midx_lv2) + + # see gh-7112 + tz = zoneinfo.ZoneInfo("Asia/Tokyo") + expected_tuples = [ + (1.1, datetime(2011, 1, 1, tzinfo=tz)), + (1.2, datetime(2011, 1, 2, tzinfo=tz)), + (1.3, datetime(2011, 1, 3, tzinfo=tz)), + ] + expected = pd.Index([1.1, 1.2, 1.3, *expected_tuples]) + tm.assert_index_equal(result, expected) + + result = midx_lv2.append(idx1) + expected = pd.Index([*expected_tuples, 1.1, 1.2, 1.3]) + tm.assert_index_equal(result, expected) + + result = midx_lv2.append(midx_lv2) + expected = pd.MultiIndex.from_arrays([idx1.append(idx1), idx2.append(idx2)]) + tm.assert_index_equal(result, expected, check_freq=False) + + result = midx_lv2.append(midx_lv3) + tm.assert_index_equal(result, expected, check_freq=False) + + result = midx_lv3.append(midx_lv2) + expected = pd.Index._simple_new( + np.array( + [ + (1.1, datetime(2011, 1, 1, tzinfo=tz), "A"), + (1.2, datetime(2011, 1, 2, tzinfo=tz), "B"), + (1.3, datetime(2011, 1, 3, tzinfo=tz), "C"), + *expected_tuples, + ], + dtype=object, + ), + None, + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("name, exp", [("b", "b"), ("c", None)]) +def test_append_names_match(name, exp): + # GH#48288 + midx = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) + midx2 = pd.MultiIndex.from_arrays([[3], [5]], names=["a", name]) + result = midx.append(midx2) + expected = pd.MultiIndex.from_arrays([[1, 2, 3], [3, 4, 5]], names=["a", exp]) + tm.assert_index_equal(result, expected) + + +def test_append_names_dont_match(): + # GH#48288 + midx = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) + midx2 = pd.MultiIndex.from_arrays([[3], [5]], names=["x", "y"]) + result = midx.append(midx2) + expected = pd.MultiIndex.from_arrays([[1, 2, 3], [3, 4, 5]], names=None) + tm.assert_index_equal(result, expected) + + +def test_append_mixed_date_tzaware_timestamp(): + # GH#68577 the combined level cannot be converted to datetime64, so it + # stays object instead of raising "Mixed timezones detected" + ts = pd.Timestamp("2001-01-01", tz="UTC") + mi1 = pd.MultiIndex.from_arrays( + [pd.Index([date(2001, 1, 1)], dtype=object), pd.Index(["foo"], dtype=object)] + ) + mi2 = pd.MultiIndex.from_arrays([pd.Index([ts]), pd.Index(["bar"], dtype=object)]) + + result = mi1.append(mi2) + + expected = pd.MultiIndex.from_arrays( + [ + pd.Index([date(2001, 1, 1), ts], dtype=object), + pd.Index(["foo", "bar"], dtype=object), + ] + ) + tm.assert_index_equal(result, expected) + + +def test_append_overlapping_interval_levels(): + # GH 54934 + ivl1 = pd.IntervalIndex.from_breaks([0.0, 1.0, 2.0]) + ivl2 = pd.IntervalIndex.from_breaks([0.5, 1.5, 2.5]) + mi1 = pd.MultiIndex.from_product([ivl1, ivl1]) + mi2 = pd.MultiIndex.from_product([ivl2, ivl2]) + result = mi1.append(mi2) + expected = pd.MultiIndex.from_tuples( + [ + (pd.Interval(0.0, 1.0), pd.Interval(0.0, 1.0)), + (pd.Interval(0.0, 1.0), pd.Interval(1.0, 2.0)), + (pd.Interval(1.0, 2.0), pd.Interval(0.0, 1.0)), + (pd.Interval(1.0, 2.0), pd.Interval(1.0, 2.0)), + (pd.Interval(0.5, 1.5), pd.Interval(0.5, 1.5)), + (pd.Interval(0.5, 1.5), pd.Interval(1.5, 2.5)), + (pd.Interval(1.5, 2.5), pd.Interval(0.5, 1.5)), + (pd.Interval(1.5, 2.5), pd.Interval(1.5, 2.5)), + ] + ) + tm.assert_index_equal(result, expected) + + +def test_repeat(): + reps = 2 + numbers = [1, 2, 3] + names = np.array(["foo", "bar"]) + + m = pd.MultiIndex.from_product([numbers, names], names=names) + expected = pd.MultiIndex.from_product([numbers, names.repeat(reps)], names=names) + tm.assert_index_equal(m.repeat(reps), expected) + + +def test_insert_base(idx): + result = idx[1:4] + + # test 0th element + assert idx[0:4].equals(result.insert(0, idx[0])) + + +def test_delete_base(idx): + expected = idx[1:] + result = idx.delete(0) + assert result.equals(expected) + assert result.name == expected.name + + expected = idx[:-1] + result = idx.delete(-1) + assert result.equals(expected) + assert result.name == expected.name + + msg = "index 6 is out of bounds for axis 0 with size 6" + with pytest.raises(IndexError, match=msg): + idx.delete(len(idx)) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_setops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef879bc08f7a3510dc08c55ed426c525907b828 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_setops.py @@ -0,0 +1,847 @@ +from datetime import date + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.api.types import ( + is_float_dtype, + is_unsigned_integer_dtype, +) + + +@pytest.mark.parametrize("case", [0.5, "xxx"]) +@pytest.mark.parametrize( + "method", ["intersection", "union", "difference", "symmetric_difference"] +) +def test_set_ops_error_cases(idx, case, sort, method): + # non-iterable input + msg = "Input must be Index or array-like" + with pytest.raises(TypeError, match=msg): + getattr(idx, method)(case, sort=sort) + + +@pytest.mark.parametrize("klass", [pd.MultiIndex, np.array, pd.Series, list]) +def test_intersection_base(idx, sort, klass): + first = idx[2::-1] # first 3 elements reversed + second = idx[:5] + + if klass is not pd.MultiIndex: + second = klass(second.values) + + intersect = first.intersection(second, sort=sort) + if sort is None: + expected = first.sort_values() + else: + expected = first + tm.assert_index_equal(intersect, expected) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.intersection([1, 2, 3], sort=sort) + + +@pytest.mark.arm_slow +@pytest.mark.parametrize("klass", [pd.MultiIndex, np.array, pd.Series, list]) +def test_union_base(idx, sort, klass): + first = idx[::-1] + second = idx[:5] + + if klass is not pd.MultiIndex: + second = klass(second.values) + + union = first.union(second, sort=sort) + if sort is None: + expected = first.sort_values() + else: + expected = first + tm.assert_index_equal(union, expected) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.union([1, 2, 3], sort=sort) + + +def test_difference_base(idx, sort): + second = idx[4:] + answer = idx[:4] + result = idx.difference(second, sort=sort) + + if sort is None: + answer = answer.sort_values() + + assert result.equals(answer) + tm.assert_index_equal(result, answer) + + # GH 10149 + cases = [klass(second.values) for klass in [np.array, pd.Series, list]] + for case in cases: + result = idx.difference(case, sort=sort) + tm.assert_index_equal(result, answer) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + idx.difference([1, 2, 3], sort=sort) + + +def test_symmetric_difference(idx, sort): + first = idx[1:] + second = idx[:-1] + answer = idx[[-1, 0]] + result = first.symmetric_difference(second, sort=sort) + + if sort is None: + answer = answer.sort_values() + + tm.assert_index_equal(result, answer) + + # GH 10149 + cases = [klass(second.values) for klass in [np.array, pd.Series, list]] + for case in cases: + result = first.symmetric_difference(case, sort=sort) + tm.assert_index_equal(result, answer) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.symmetric_difference([1, 2, 3], sort=sort) + + +def test_multiindex_symmetric_difference(): + # GH 13490 + idx = pd.MultiIndex.from_product([["a", "b"], ["A", "B"]], names=["a", "b"]) + result = idx.symmetric_difference(idx) + assert result.names == idx.names + + idx2 = idx.copy().rename(["A", "B"]) + result = idx.symmetric_difference(idx2) + assert result.names == [None, None] + + +def test_empty(idx): + # GH 15270 + assert not idx.empty + assert idx[:0].empty + + +def test_difference(idx, sort): + first = idx + result = first.difference(idx[-3:], sort=sort) + vals = idx[:-3].values + + if sort is None: + vals = sorted(vals) + + expected = pd.MultiIndex.from_tuples(vals, sortorder=0, names=idx.names) + + assert isinstance(result, pd.MultiIndex) + assert result.equals(expected) + assert result.names == idx.names + tm.assert_index_equal(result, expected) + + # empty difference: reflexive + result = idx.difference(idx, sort=sort) + expected = idx[:0] + assert result.equals(expected) + assert result.names == idx.names + + # empty difference: superset + result = idx[-3:].difference(idx, sort=sort) + expected = idx[:0] + assert result.equals(expected) + assert result.names == idx.names + + # empty difference: degenerate + result = idx[:0].difference(idx, sort=sort) + expected = idx[:0] + assert result.equals(expected) + assert result.names == idx.names + + # names not the same + chunklet = idx[-3:] + chunklet.names = ["foo", "baz"] + result = first.difference(chunklet, sort=sort) + assert result.names == (None, None) + + # empty, but non-equal + result = idx.difference(idx.sortlevel(1)[0], sort=sort) + assert len(result) == 0 + + # raise Exception called with non-MultiIndex + result = first.difference(first.values, sort=sort) + assert result.equals(first[:0]) + + # name from empty array + result = first.difference([], sort=sort) + assert first.equals(result) + assert first.names == result.names + + # name from non-empty array + result = first.difference([("foo", "one")], sort=sort) + expected = pd.MultiIndex.from_tuples( + [("bar", "one"), ("baz", "two"), ("foo", "two"), ("qux", "one"), ("qux", "two")] + ) + expected.names = first.names + assert first.names == result.names + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.difference([1, 2, 3, 4, 5], sort=sort) + + +def test_difference_sort_special(): + # GH-24959 + idx = pd.MultiIndex.from_product([[1, 0], ["a", "b"]]) + # sort=None, the default + result = idx.difference([]) + tm.assert_index_equal(result, idx) + + +def test_difference_sort_special_true(): + idx = pd.MultiIndex.from_product([[1, 0], ["a", "b"]]) + result = idx.difference([], sort=True) + expected = pd.MultiIndex.from_product([[0, 1], ["a", "b"]]) + tm.assert_index_equal(result, expected) + + +def test_difference_sort_incomparable(): + # GH-24959 + idx = pd.MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]]) + + other = pd.MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]]) + # sort=None, the default + msg = "sort order is undefined for incomparable objects" + with tm.assert_produces_warning(RuntimeWarning, match=msg): + result = idx.difference(other) + tm.assert_index_equal(result, idx) + + # sort=False + result = idx.difference(other, sort=False) + tm.assert_index_equal(result, idx) + + +def test_difference_sort_incomparable_true(): + idx = pd.MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]]) + other = pd.MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]]) + + # TODO: this is raising in constructing a Categorical when calling + # algos.safe_sort. Should we catch and re-raise with a better message? + msg = "'values' is not ordered, please explicitly specify the categories order " + with pytest.raises(TypeError, match=msg): + idx.difference(other, sort=True) + + +def test_union(idx, sort): + piece1 = idx[:5][::-1] + piece2 = idx[3:] + + the_union = piece1.union(piece2, sort=sort) + + if sort in (None, False): + tm.assert_index_equal(the_union.sort_values(), idx.sort_values()) + else: + tm.assert_index_equal(the_union, idx) + + # corner case, pass self or empty thing: + the_union = idx.union(idx, sort=sort) + tm.assert_index_equal(the_union, idx) + + the_union = idx.union(idx[:0], sort=sort) + tm.assert_index_equal(the_union, idx) + + tuples = idx.values + result = idx[:4].union(tuples[4:], sort=sort) + if sort is None: + tm.assert_index_equal(result.sort_values(), idx.sort_values()) + else: + assert result.equals(idx) + + +@pytest.mark.parametrize("tz", [None, "UTC"]) +def test_union_mixed_date_timestamp(tz): + # GH#61807, GH#68577 the combined level keeps object dtype instead of raising + ts = pd.Timestamp("2001-01-01", tz=tz) + left = pd.MultiIndex.from_arrays( + [pd.Index([date(2001, 1, 1)], dtype=object), pd.Index(["foo"], dtype=object)] + ) + right = pd.MultiIndex.from_arrays([pd.Index([ts]), pd.Index(["bar"], dtype=object)]) + + with tm.assert_produces_warning( + Pandas4Warning, + match="Inferring datetime64 from data containing datetime.date objects", + ): + result = left.union(right, sort=False) + + expected = pd.MultiIndex.from_arrays( + [ + pd.Index([date(2001, 1, 1), ts], dtype=object), + pd.Index(["foo", "bar"], dtype=object), + ] + ) + tm.assert_index_equal(result, expected) + + +def test_union_with_regular_index(idx, using_infer_string): + other = pd.Index(["A", "B", "C"]) + + result = other.union(idx) + assert ("foo", "one") in result + assert "B" in result + + if using_infer_string: + with pytest.raises(NotImplementedError, match="Can only union"): + idx.union(other) + else: + msg = "The values in the array are unorderable" + with tm.assert_produces_warning(RuntimeWarning, match=msg): + result2 = idx.union(other) + # This is more consistent now, if sorting fails then we don't sort at all + # in the MultiIndex case. + assert not result.equals(result2) + + +def test_intersection(idx, sort): + piece1 = idx[:5][::-1] + piece2 = idx[3:] + + the_int = piece1.intersection(piece2, sort=sort) + + if sort in (None, True): + tm.assert_index_equal(the_int, idx[3:5]) + else: + tm.assert_index_equal(the_int.sort_values(), idx[3:5]) + + # corner case, pass self + the_int = idx.intersection(idx, sort=sort) + tm.assert_index_equal(the_int, idx) + + # empty intersection: disjoint + empty = idx[:2].intersection(idx[2:], sort=sort) + expected = idx[:0] + assert empty.equals(expected) + + tuples = idx.values + result = idx.intersection(tuples) + assert result.equals(idx) + + +@pytest.mark.parametrize( + "method", ["intersection", "union", "difference", "symmetric_difference"] +) +def test_setop_with_categorical(idx, sort, method): + other = idx.to_flat_index().astype("category") + res_names = [None] * idx.nlevels + + result = getattr(idx, method)(other, sort=sort) + expected = getattr(idx, method)(idx, sort=sort).rename(res_names) + tm.assert_index_equal(result, expected) + + result = getattr(idx, method)(other[:5], sort=sort) + expected = getattr(idx, method)(idx[:5], sort=sort).rename(res_names) + tm.assert_index_equal(result, expected) + + +def test_intersection_non_object(idx, sort): + other = pd.Index(range(3), name="foo") + + result = idx.intersection(other, sort=sort) + expected = pd.MultiIndex(levels=idx.levels, codes=[[]] * idx.nlevels, names=None) + tm.assert_index_equal(result, expected, exact=True) + + # if we pass a length-0 ndarray (i.e. no name, we retain our idx.name) + result = idx.intersection(np.asarray(other)[:0], sort=sort) + expected = pd.MultiIndex( + levels=idx.levels, codes=[[]] * idx.nlevels, names=idx.names + ) + tm.assert_index_equal(result, expected, exact=True) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + # With non-zero length non-index, we try and fail to convert to tuples + idx.intersection(np.asarray(other), sort=sort) + + +def test_intersect_equal_sort(): + # GH-24959 + idx = pd.MultiIndex.from_product([[1, 0], ["a", "b"]]) + tm.assert_index_equal(idx.intersection(idx, sort=False), idx) + tm.assert_index_equal(idx.intersection(idx, sort=None), idx) + + +def test_intersect_equal_sort_true(): + idx = pd.MultiIndex.from_product([[1, 0], ["a", "b"]]) + expected = pd.MultiIndex.from_product([[0, 1], ["a", "b"]]) + result = idx.intersection(idx, sort=True) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("slice_", [slice(None), slice(0)]) +def test_union_sort_other_empty(slice_): + # https://github.com/pandas-dev/pandas/issues/24959 + idx = pd.MultiIndex.from_product([[1, 0], ["a", "b"]]) + + # default, sort=None + other = idx[slice_] + tm.assert_index_equal(idx.union(other), idx) + tm.assert_index_equal(other.union(idx), idx) + + # sort=False + tm.assert_index_equal(idx.union(other, sort=False), idx) + + +def test_union_sort_other_empty_sort(): + idx = pd.MultiIndex.from_product([[1, 0], ["a", "b"]]) + other = idx[:0] + result = idx.union(other, sort=True) + expected = pd.MultiIndex.from_product([[0, 1], ["a", "b"]]) + tm.assert_index_equal(result, expected) + + +def test_union_sort_other_incomparable(): + # https://github.com/pandas-dev/pandas/issues/24959 + idx = pd.MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]]) + + # default, sort=None + with tm.assert_produces_warning(RuntimeWarning, match="are unorderable"): + result = idx.union(idx[:1]) + tm.assert_index_equal(result, idx) + + # sort=False + result = idx.union(idx[:1], sort=False) + tm.assert_index_equal(result, idx) + + +def test_union_sort_other_incomparable_sort(): + idx = pd.MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]]) + msg = "'<' not supported between instances of 'Timestamp' and 'int'" + with pytest.raises(TypeError, match=msg): + idx.union(idx[:1], sort=True) + + +def test_union_non_object_dtype_raises(): + # GH#32646 raise NotImplementedError instead of less-informative error + mi = pd.MultiIndex.from_product([["a", "b"], [1, 2]]) + + idx = mi.levels[1] + + msg = "Can only union MultiIndex with MultiIndex or Index of tuples" + with pytest.raises(NotImplementedError, match=msg): + mi.union(idx) + + +def test_union_empty_self_different_names(): + # GH#38423 + mi = pd.MultiIndex.from_arrays([[]]) + mi2 = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) + result = mi.union(mi2) + expected = pd.MultiIndex.from_arrays([[1, 2], [3, 4]]) + tm.assert_index_equal(result, expected) + + +def test_union_multiindex_empty_rangeindex(): + # GH#41234 + mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) + ri = pd.RangeIndex(0) + + result_left = mi.union(ri) + tm.assert_index_equal(mi, result_left, check_names=False) + + result_right = ri.union(mi) + tm.assert_index_equal(mi, result_right, check_names=False) + + +@pytest.mark.parametrize( + "method", ["union", "intersection", "difference", "symmetric_difference"] +) +def test_setops_sort_validation(method): + idx1 = pd.MultiIndex.from_product([["a", "b"], [1, 2]]) + idx2 = pd.MultiIndex.from_product([["b", "c"], [1, 2]]) + + with pytest.raises(ValueError, match="The 'sort' keyword only takes"): + getattr(idx1, method)(idx2, sort=2) + + # sort=True is supported as of GH#25151 + getattr(idx1, method)(idx2, sort=True) + + +@pytest.mark.parametrize("val", [pd.NA, 100]) +def test_difference_keep_ea_dtypes(any_numeric_ea_dtype, val): + # GH#48606 + midx = pd.MultiIndex.from_arrays( + [pd.Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None] + ) + midx2 = pd.MultiIndex.from_arrays( + [pd.Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]] + ) + result = midx.difference(midx2) + expected = pd.MultiIndex.from_arrays( + [pd.Series([1], dtype=any_numeric_ea_dtype), [2]] + ) + tm.assert_index_equal(result, expected) + + result = midx.difference(midx.sort_values(ascending=False)) + expected = pd.MultiIndex.from_arrays( + [pd.Series([], dtype=any_numeric_ea_dtype), pd.Series([], dtype=np.int64)], + names=["a", None], + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("val", [pd.NA, 5]) +def test_symmetric_difference_keeping_ea_dtype(any_numeric_ea_dtype, val): + # GH#48607 + midx = pd.MultiIndex.from_arrays( + [pd.Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None] + ) + midx2 = pd.MultiIndex.from_arrays( + [pd.Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]] + ) + result = midx.symmetric_difference(midx2) + expected = pd.MultiIndex.from_arrays( + [pd.Series([1, 1, val], dtype=any_numeric_ea_dtype), [1, 2, 3]] + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + ("tuples", "exp_tuples"), + [ + ([("val1", "test1")], [("val1", "test1")]), + ([("val1", "test1"), ("val1", "test1")], [("val1", "test1")]), + ( + [("val2", "test2"), ("val1", "test1")], + [("val2", "test2"), ("val1", "test1")], + ), + ], +) +def test_intersect_with_duplicates(tuples, exp_tuples): + # GH#36915 + left = pd.MultiIndex.from_tuples(tuples, names=["first", "second"]) + right = pd.MultiIndex.from_tuples( + [("val1", "test1"), ("val1", "test1"), ("val2", "test2")], + names=["first", "second"], + ) + result = left.intersection(right) + expected = pd.MultiIndex.from_tuples(exp_tuples, names=["first", "second"]) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "data, names, expected", + [ + ((1,), None, [None, None]), + ((1,), ["a"], [None, None]), + ((1,), ["b"], [None, None]), + ((1, 2), ["c", "d"], [None, None]), + ((1, 2), ["b", "a"], [None, None]), + ((1, 2, 3), ["a", "b", "c"], [None, None]), + ((1, 2), ["a", "c"], ["a", None]), + ((1, 2), ["c", "b"], [None, "b"]), + ((1, 2), ["a", "b"], ["a", "b"]), + ((1, 2), [None, "b"], [None, "b"]), + ], +) +def test_maybe_match_names(data, names, expected): + # GH#38323 + mi = pd.MultiIndex.from_tuples([], names=["a", "b"]) + mi2 = pd.MultiIndex.from_tuples([data], names=names) + result = mi._maybe_match_names(mi2) + assert result == expected + + +def test_intersection_equal_different_names(): + # GH#30302 + mi1 = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["c", "b"]) + mi2 = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) + + result = mi1.intersection(mi2) + expected = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=[None, "b"]) + tm.assert_index_equal(result, expected) + + +def test_intersection_different_names(): + # GH#38323 + mi = pd.MultiIndex.from_arrays([[1], [3]], names=["c", "b"]) + mi2 = pd.MultiIndex.from_arrays([[1], [3]]) + result = mi.intersection(mi2) + tm.assert_index_equal(result, mi2) + + +def test_intersection_with_missing_values_on_both_sides(nulls_fixture): + # GH#38623 + mi1 = pd.MultiIndex.from_arrays( + [[3, nulls_fixture, 4, nulls_fixture], [1, 2, 4, 2]] + ) + mi2 = pd.MultiIndex.from_arrays([[3, nulls_fixture, 3], [1, 2, 4]]) + result = mi1.intersection(mi2) + expected = pd.MultiIndex.from_arrays([[3, nulls_fixture], [1, 2]]) + tm.assert_index_equal(result, expected) + + +def test_union_with_missing_values_on_both_sides(nulls_fixture): + # GH#38623 + mi1 = pd.MultiIndex.from_arrays([[1, nulls_fixture]]) + mi2 = pd.MultiIndex.from_arrays([[1, nulls_fixture, 3]]) + result = mi1.union(mi2) + expected = pd.MultiIndex.from_arrays([[1, 3, nulls_fixture]]) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["float64", "Float64"]) +@pytest.mark.parametrize("sort", [None, False]) +def test_union_nan_got_duplicated(dtype, sort): + # GH#38977, GH#49010 + mi1 = pd.MultiIndex.from_arrays([pd.array([1.0, np.nan], dtype=dtype), [2, 3]]) + mi2 = pd.MultiIndex.from_arrays( + [pd.array([1.0, np.nan, 3.0], dtype=dtype), [2, 3, 4]] + ) + result = mi1.union(mi2, sort=sort) + if sort is None: + expected = pd.MultiIndex.from_arrays( + [pd.array([1.0, 3.0, np.nan], dtype=dtype), [2, 4, 3]] + ) + else: + expected = mi2 + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("val", [4, 1]) +def test_union_keep_ea_dtype(any_numeric_ea_dtype, val): + # GH#48505 + + arr1 = pd.Series([val, 2], dtype=any_numeric_ea_dtype) + arr2 = pd.Series([2, 1], dtype=any_numeric_ea_dtype) + midx = pd.MultiIndex.from_arrays([arr1, [1, 2]], names=["a", None]) + midx2 = pd.MultiIndex.from_arrays([arr2, [2, 1]]) + result = midx.union(midx2) + if val == 4: + expected = pd.MultiIndex.from_arrays( + [pd.Series([1, 2, 4], dtype=any_numeric_ea_dtype), [1, 2, 1]] + ) + else: + expected = pd.MultiIndex.from_arrays( + [pd.Series([1, 2], dtype=any_numeric_ea_dtype), [1, 2]] + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("dupe_val", [3, pd.NA]) +def test_union_with_duplicates_keep_ea_dtype(dupe_val, any_numeric_ea_dtype): + # GH48900 + mi1 = pd.MultiIndex.from_arrays( + [ + pd.Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype), + pd.Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype), + ] + ) + mi2 = pd.MultiIndex.from_arrays( + [ + pd.Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), + pd.Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), + ] + ) + result = mi1.union(mi2) + expected = pd.MultiIndex.from_arrays( + [ + pd.Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), + pd.Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), + ] + ) + tm.assert_index_equal(result, expected) + + +def test_union_duplicates(index_sortable, request): + # GH#38977 + index = index_sortable + if index.empty or isinstance(index, (pd.IntervalIndex, pd.CategoricalIndex)): + pytest.skip(f"No duplicates in an empty {type(index).__name__}") + + values = index.unique().tolist() + mi1 = pd.MultiIndex.from_arrays([values, [1] * len(values)]) + mi2 = pd.MultiIndex.from_arrays([[values[0], *values], [1] * (len(values) + 1)]) + result = mi2.union(mi1) + expected = mi2.sort_values() + tm.assert_index_equal(result, expected) + + if ( + is_unsigned_integer_dtype(mi2.levels[0]) + and (mi2.get_level_values(0) < 2**63).all() + ): + # GH#47294 - union uses lib.fast_zip, converting data to Python integers + # and loses type information. Result is then unsigned only when values are + # sufficiently large to require unsigned dtype. This happens only if other + # has dups or one of both have missing values + expected = expected.set_levels( + [expected.levels[0].astype(np.int64), expected.levels[1]] + ) + elif is_float_dtype(mi2.levels[0]): + # mi2 has duplicates witch is a different path than above, Fix that path + # to use correct float dtype? + expected = expected.set_levels( + [expected.levels[0].astype(float), expected.levels[1]] + ) + + result = mi1.union(mi2) + tm.assert_index_equal(result, expected) + + +def test_union_keep_dtype_precision(any_real_numeric_dtype): + # GH#48498 + arr1 = pd.Series([4, 1, 1], dtype=any_real_numeric_dtype) + arr2 = pd.Series([1, 4], dtype=any_real_numeric_dtype) + midx = pd.MultiIndex.from_arrays([arr1, [2, 1, 1]], names=["a", None]) + midx2 = pd.MultiIndex.from_arrays([arr2, [1, 2]], names=["a", None]) + + result = midx.union(midx2) + expected = pd.MultiIndex.from_arrays( + ([pd.Series([1, 1, 4], dtype=any_real_numeric_dtype), [1, 1, 2]]), + names=["a", None], + ) + tm.assert_index_equal(result, expected) + + +def test_union_keep_ea_dtype_with_na(any_numeric_ea_dtype): + # GH#48498 + arr1 = pd.Series([4, pd.NA], dtype=any_numeric_ea_dtype) + arr2 = pd.Series([1, pd.NA], dtype=any_numeric_ea_dtype) + midx = pd.MultiIndex.from_arrays([arr1, [2, 1]], names=["a", None]) + midx2 = pd.MultiIndex.from_arrays([arr2, [1, 2]]) + result = midx.union(midx2) + expected = pd.MultiIndex.from_arrays( + [pd.Series([1, 4, pd.NA, pd.NA], dtype=any_numeric_ea_dtype), [1, 2, 1, 2]] + ) + tm.assert_index_equal(result, expected) + + +def test_union_duplicates_different_names(): + # GH#62059 + mi1 = pd.MultiIndex.from_tuples([(1, "a"), (2, "b")], names=["x", "y"]) + mi2 = pd.MultiIndex.from_tuples([(2, "b"), (3, "c"), (2, "b")]) + + result = mi1.union(mi2) + expected = pd.MultiIndex.from_tuples( + [(1, "a"), (2, "b"), (2, "b"), (3, "c")], names=[None, None] + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "levels1, levels2, codes1, codes2, names", + [ + ( + [["a", "b", "c"], [0, ""]], + [["c", "d", "b"], [""]], + [[0, 1, 2], [1, 1, 1]], + [[0, 1, 2], [0, 0, 0]], + ["name1", "name2"], + ), + ], +) +def test_intersection_lexsort_depth(levels1, levels2, codes1, codes2, names): + # GH#25169 + mi1 = pd.MultiIndex(levels=levels1, codes=codes1, names=names) + mi2 = pd.MultiIndex(levels=levels2, codes=codes2, names=names) + mi_int = mi1.intersection(mi2) + assert mi_int._lexsort_depth == 2 + + +@pytest.mark.parametrize( + "a", + [pd.Categorical(["a", "b"], categories=["a", "b"]), ["a", "b"]], +) +@pytest.mark.parametrize("b_ordered", [True, False]) +def test_intersection_with_non_lex_sorted_categories(a, b_ordered): + # GH#49974 + other = ["1", "2"] + b = pd.Categorical(["a", "b"], categories=["b", "a"], ordered=b_ordered) + df1 = pd.DataFrame({"x": a, "y": other}) + df2 = pd.DataFrame({"x": b, "y": other}) + + expected = pd.MultiIndex.from_arrays([a, other], names=["x", "y"]) + + res1 = pd.MultiIndex.from_frame(df1).intersection( + pd.MultiIndex.from_frame(df2.sort_values(["x", "y"])) + ) + res2 = pd.MultiIndex.from_frame(df1).intersection(pd.MultiIndex.from_frame(df2)) + res3 = pd.MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection( + pd.MultiIndex.from_frame(df2) + ) + res4 = pd.MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection( + pd.MultiIndex.from_frame(df2.sort_values(["x", "y"])) + ) + + tm.assert_index_equal(res1, expected) + tm.assert_index_equal(res2, expected) + tm.assert_index_equal(res3, expected) + tm.assert_index_equal(res4, expected) + + +@pytest.mark.parametrize("val", [pd.NA, 100]) +def test_intersection_keep_ea_dtypes(val, any_numeric_ea_dtype): + # GH#48604 + midx = pd.MultiIndex.from_arrays( + [pd.Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None] + ) + midx2 = pd.MultiIndex.from_arrays( + [pd.Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]] + ) + result = midx.intersection(midx2) + expected = pd.MultiIndex.from_arrays( + [pd.Series([2], dtype=any_numeric_ea_dtype), [1]] + ) + tm.assert_index_equal(result, expected) + + +def test_union_with_na_when_constructing_dataframe(): + # GH43222 + series1 = pd.Series( + (1,), + index=pd.MultiIndex.from_arrays( + [pd.Series([None], dtype="str"), pd.Series([None], dtype="str")] + ), + ) + series2 = pd.Series( + (10, 20), index=pd.MultiIndex.from_tuples(((None, None), ("a", "b"))) + ) + result = pd.DataFrame([series1, series2]) + expected = pd.DataFrame({(np.nan, np.nan): [1.0, 10.0], ("a", "b"): [np.nan, 20.0]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "method", ["difference", "intersection", "symmetric_difference"] +) +def test_setops_pyarrow_timestamp_level(method): + # GH#61382 setops must match a list of tuples against a pyarrow-backed + # timestamp level (the list becomes a numpy-backed level internally) + pytest.importorskip("pyarrow") + mi = pd.MultiIndex.from_arrays( + [ + pd.Series([1, 2], dtype="int64[pyarrow]"), + pd.Series(["1900-01-01", "1901-06-15"], dtype="timestamp[ns][pyarrow]"), + ], + names=["id", "date"], + ) + + result = getattr(mi, method)([mi[0]]) + # intersection keeps the matched row, (symmetric_)difference drops it + expected = mi[:1] if method == "intersection" else mi[1:] + tm.assert_index_equal(result, expected) + + +def test_multiindex_difference_preserves_categorical_levels(): + # GH#40080 set operations on a MultiIndex must preserve categorical level + # dtypes instead of downcasting them to their underlying type + cat = pd.CategoricalDtype(categories=[1, 2, 3, 4]) + df = pd.DataFrame( + {"a": [1, 2, 3, 4, 3, 2, 1], "b": [4, 3, 2, 3, 1, 2, 3]}, dtype=cat + ) + mi = df.set_index(["a", "b"]).index + # difference, union and intersection are all named in the issue and were + # all downcasting the categorical levels + for method in ("difference", "union", "intersection"): + result = getattr(mi, method)(mi[:3]) + assert isinstance(result.get_level_values(0).dtype, pd.CategoricalDtype) + assert isinstance(result.get_level_values(1).dtype, pd.CategoricalDtype) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_sorting.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_sorting.py new file mode 100644 index 0000000000000000000000000000000000000000..612e9f4d88ca74880ea089e39efc808d88a81ced --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_sorting.py @@ -0,0 +1,358 @@ +import numpy as np +import pytest + +from pandas.errors import UnsortedIndexError + +import pandas as pd +import pandas._testing as tm +from pandas.core.indexes.frozen import FrozenList + + +def test_sortlevel(idx): + tuples = list(idx) + np.random.default_rng(2).shuffle(tuples) + + index = pd.MultiIndex.from_tuples(tuples) + + sorted_idx, _ = index.sortlevel(0) + expected = pd.MultiIndex.from_tuples(sorted(tuples)) + assert sorted_idx.equals(expected) + + sorted_idx, _ = index.sortlevel(0, ascending=False) + assert sorted_idx.equals(expected[::-1]) + + sorted_idx, _ = index.sortlevel(1) + by1 = sorted(tuples, key=lambda x: (x[1], x[0])) + expected = pd.MultiIndex.from_tuples(by1) + assert sorted_idx.equals(expected) + + sorted_idx, _ = index.sortlevel(1, ascending=False) + assert sorted_idx.equals(expected[::-1]) + + +def test_sortlevel_not_sort_remaining(): + mi = pd.MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC")) + sorted_idx, _ = mi.sortlevel("A", sort_remaining=False) + assert sorted_idx.equals(mi) + + +def test_sortlevel_deterministic(): + tuples = [ + ("bar", "one"), + ("foo", "two"), + ("qux", "two"), + ("foo", "one"), + ("baz", "two"), + ("qux", "one"), + ] + + index = pd.MultiIndex.from_tuples(tuples) + + sorted_idx, _ = index.sortlevel(0) + expected = pd.MultiIndex.from_tuples(sorted(tuples)) + assert sorted_idx.equals(expected) + + sorted_idx, _ = index.sortlevel(0, ascending=False) + assert sorted_idx.equals(expected[::-1]) + + sorted_idx, _ = index.sortlevel(1) + by1 = sorted(tuples, key=lambda x: (x[1], x[0])) + expected = pd.MultiIndex.from_tuples(by1) + assert sorted_idx.equals(expected) + + sorted_idx, _ = index.sortlevel(1, ascending=False) + assert sorted_idx.equals(expected[::-1]) + + +def test_sortlevel_na_position(): + # GH#51612 + midx = pd.MultiIndex.from_tuples([(1, np.nan), (1, 1)]) + result = midx.sortlevel(level=[0, 1], na_position="last")[0] + expected = pd.MultiIndex.from_tuples([(1, 1), (1, np.nan)]) + tm.assert_index_equal(result, expected) + + +def test_numpy_argsort(idx): + result = np.argsort(idx) + expected = idx.argsort() + 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(type(idx), (pd.CategoricalIndex, pd.RangeIndex)): + msg = "the 'axis' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.argsort(idx, axis=1) + + msg = "the 'kind' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.argsort(idx, kind="mergesort") + + msg = "the 'order' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.argsort(idx, order=("a", "b")) + + +def test_unsortedindex(): + # GH 11897 + mi = pd.MultiIndex.from_tuples( + [("z", "a"), ("x", "a"), ("y", "b"), ("x", "b"), ("y", "a"), ("z", "b")], + names=["one", "two"], + ) + df = pd.DataFrame([[i, 10 * i] for i in range(6)], index=mi, columns=["one", "two"]) + + # GH 16734: not sorted, but no real slicing + result = df.loc(axis=0)["z", "a"] + expected = df.iloc[0] + tm.assert_series_equal(result, expected) + + msg = ( + "MultiIndex slicing requires the index to be lexsorted: " + r"slicing on levels \[1\], lexsort depth 0" + ) + with pytest.raises(UnsortedIndexError, match=msg): + df.loc(axis=0)["z", slice("a")] + df2 = df.sort_index() + assert len(df2.loc(axis=0)["z", :]) == 2 + + with pytest.raises(KeyError, match="'q'"): + df2.loc(axis=0)["q", :] + + +def test_unsortedindex_doc_examples(): + # https://pandas.pydata.org/pandas-docs/stable/advanced.html#sorting-a-multiindex + dfm = pd.DataFrame( + { + "jim": [0, 0, 1, 1], + "joe": ["x", "x", "z", "y"], + "jolie": np.random.default_rng(2).random(4), + } + ) + + dfm = dfm.set_index(["jim", "joe"]) + # Full-length key uses the engine directly; no PerformanceWarning + dfm.loc[(1, "z")] + + msg = r"Key length \(2\) was greater than MultiIndex lexsort depth \(1\)" + with pytest.raises(UnsortedIndexError, match=msg): + dfm.loc[(0, "y") : (1, "z")] + + assert not dfm.index._is_lexsorted() + assert dfm.index._lexsort_depth == 1 + + # sort it + dfm = dfm.sort_index() + dfm.loc[(1, "z")] + dfm.loc[(0, "y") : (1, "z")] + + assert dfm.index._is_lexsorted() + assert dfm.index._lexsort_depth == 2 + + +def test_reconstruct_sort(): + # starts off lexsorted & monotonic + mi = pd.MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]]) + assert mi.is_monotonic_increasing + recons = mi._sort_levels_monotonic() + assert recons.is_monotonic_increasing + assert mi is recons + + assert mi.equals(recons) + assert pd.Index(mi.values).equals(pd.Index(recons.values)) + + # cannot convert to lexsorted + mi = pd.MultiIndex.from_tuples( + [("z", "a"), ("x", "a"), ("y", "b"), ("x", "b"), ("y", "a"), ("z", "b")], + names=["one", "two"], + ) + assert not mi.is_monotonic_increasing + recons = mi._sort_levels_monotonic() + assert not recons.is_monotonic_increasing + assert mi.equals(recons) + assert pd.Index(mi.values).equals(pd.Index(recons.values)) + + # cannot convert to lexsorted + mi = pd.MultiIndex( + levels=[["b", "d", "a"], [1, 2, 3]], + codes=[[0, 1, 0, 2], [2, 0, 0, 1]], + names=["col1", "col2"], + ) + assert not mi.is_monotonic_increasing + recons = mi._sort_levels_monotonic() + assert not recons.is_monotonic_increasing + assert mi.equals(recons) + assert pd.Index(mi.values).equals(pd.Index(recons.values)) + + +def test_reconstruct_remove_unused(): + # xref to GH 2770 + df = pd.DataFrame( + [["deleteMe", 1, 9], ["keepMe", 2, 9], ["keepMeToo", 3, 9]], + columns=["first", "second", "third"], + ) + df2 = df.set_index(["first", "second"], drop=False) + df2 = df2[df2["first"] != "deleteMe"] + + # removed levels are there + expected = pd.MultiIndex( + levels=[["deleteMe", "keepMe", "keepMeToo"], [1, 2, 3]], + codes=[[1, 2], [1, 2]], + names=["first", "second"], + ) + result = df2.index + tm.assert_index_equal(result, expected) + + expected = pd.MultiIndex( + levels=[["keepMe", "keepMeToo"], [2, 3]], + codes=[[0, 1], [0, 1]], + names=["first", "second"], + ) + result = df2.index.remove_unused_levels() + tm.assert_index_equal(result, expected) + + # idempotent + result2 = result.remove_unused_levels() + tm.assert_index_equal(result2, expected) + assert result2.is_(result) + + +@pytest.mark.parametrize( + "first_type,second_type", [("int64", "int64"), ("datetime64[D]", "str")] +) +def test_remove_unused_levels_large(first_type, second_type): + # GH16556 + + # because tests should be deterministic (and this test in particular + # checks that levels are removed, which is not the case for every + # random input): + rng = np.random.default_rng(10) # seed is arbitrary value that works + + size = 1 << 16 + df = pd.DataFrame( + { + "first": rng.integers(0, 1 << 13, size).astype(first_type), + "second": rng.integers(0, 1 << 10, size).astype(second_type), + "third": rng.random(size), + } + ) + df = df.groupby(["first", "second"]).sum() + df = df[df.third < 0.1] + + result = df.index.remove_unused_levels() + assert len(result.levels[0]) < len(df.index.levels[0]) + assert len(result.levels[1]) < len(df.index.levels[1]) + assert result.equals(df.index) + + expected = df.reset_index().set_index(["first", "second"]).index + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("level0", [["a", "d", "b"], ["a", "d", "b", "unused"]]) +@pytest.mark.parametrize( + "level1", [["w", "x", "y", "z"], ["w", "x", "y", "z", "unused"]] +) +def test_remove_unused_nan(level0, level1): + # GH 18417 + mi = pd.MultiIndex( + levels=[level0, level1], codes=[[0, 2, -1, 1, -1], [0, 1, 2, 3, 2]] + ) + + result = mi.remove_unused_levels() + tm.assert_index_equal(result, mi) + for level in 0, 1: + assert "unused" not in result.levels[level] + + +def test_argsort(idx): + result = idx.argsort() + expected = idx.values.argsort() + tm.assert_numpy_array_equal(result, expected) + + +def test_remove_unused_levels_with_nan(): + # GH 37510 + idx = pd.Index([(1, np.nan), (3, 4)]).rename(["id1", "id2"]) + idx = idx.set_levels(["a", np.nan], level="id1") + idx = idx.remove_unused_levels() + result = idx.levels + expected = FrozenList([["a", np.nan], [4]]) + assert str(result) == str(expected) + + +def test_sort_values_nan(): + # GH48495, GH48626 + midx = pd.MultiIndex( + levels=[["A", "B", "C"], ["D"]], codes=[[1, 0, 2], [-1, -1, 0]] + ) + result = midx.sort_values() + expected = pd.MultiIndex( + levels=[["A", "B", "C"], ["D"]], codes=[[0, 1, 2], [-1, -1, 0]] + ) + tm.assert_index_equal(result, expected) + + +def test_sort_values_incomparable(): + # GH48495 + mi = pd.MultiIndex.from_arrays( + [ + [1, pd.Timestamp("2000-01-01")], + [3, 4], + ] + ) + match = "'<' not supported between instances of 'Timestamp' and 'int'" + with pytest.raises(TypeError, match=match): + mi.sort_values() + + +def test_sortlevel_incomparable(): + # GH#21136 + mi = pd.MultiIndex.from_arrays( + [ + pd.Series( + [pd.Timestamp("2011-04-09"), pd.Timestamp("2010-04-09"), "2009/4/9"], + dtype=object, + ), + [2, 1, 3], + ], + names=["a", "c"], + ) + with pytest.raises(TypeError, match="not supported between instances of"): + mi.sortlevel("a") + + +@pytest.mark.parametrize("na_position", ["first", "last"]) +@pytest.mark.parametrize("dtype", ["float64", "Int64", "Float64"]) +def test_sort_values_with_na_na_position(dtype, na_position): + # 51612 + arrays = [ + pd.Series([1, 1, 2], dtype=dtype), + pd.Series([1, None, 3], dtype=dtype), + ] + index = pd.MultiIndex.from_arrays(arrays) + result = index.sort_values(na_position=na_position) + if na_position == "first": + arrays = [ + pd.Series([1, 1, 2], dtype=dtype), + pd.Series([None, 1, 3], dtype=dtype), + ] + else: + arrays = [ + pd.Series([1, 1, 2], dtype=dtype), + pd.Series([1, None, 3], dtype=dtype), + ] + expected = pd.MultiIndex.from_arrays(arrays) + tm.assert_index_equal(result, expected) + + +def test_sort_unnecessary_warning(): + # GH#55386 + midx = pd.MultiIndex.from_tuples([(1.5, 2), (3.5, 3), (0, 1)]) + midx = midx.set_levels([2.5, np.nan, 1], level=0) + result = midx.sort_values() + expected = pd.MultiIndex.from_tuples([(1, 3), (2.5, 1), (np.nan, 2)]) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_take.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_take.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5b41c6d59e36932144f291035e0e69fa498182 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_take.py @@ -0,0 +1,72 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_take(idx): + indexer = [4, 3, 0, 2] + result = idx.take(indexer) + expected = idx[indexer] + assert result.equals(expected) + + # GH 10791 + msg = "'MultiIndex' object has no attribute 'freq'" + with pytest.raises(AttributeError, match=msg): + idx.freq + + +def test_take_invalid_kwargs(idx): + indices = [1, 2] + + msg = r"take\(\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg): + idx.take(indices, foo=2) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, out=indices) + + msg = "the 'mode' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, mode="clip") + + +def test_take_fill_value(): + # GH 12631 + vals = [["A", "B"], [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")]] + idx = pd.MultiIndex.from_product(vals, names=["str", "dt"]) + + result = idx.take(np.array([1, 0, -1])) + exp_vals = [ + ("A", pd.Timestamp("2011-01-02")), + ("A", pd.Timestamp("2011-01-01")), + ("B", pd.Timestamp("2011-01-02")), + ] + expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"]) + tm.assert_index_equal(result, expected) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=True) + exp_vals = [ + ("A", pd.Timestamp("2011-01-02")), + ("A", pd.Timestamp("2011-01-01")), + (np.nan, pd.NaT), + ] + expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"]) + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False) + exp_vals = [ + ("A", pd.Timestamp("2011-01-02")), + ("A", pd.Timestamp("2011-01-01")), + ("B", pd.Timestamp("2011-01-02")), + ] + expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"]) + tm.assert_index_equal(result, expected) + + msg = "index -5 is out of bounds for( axis 0 with)? size 4" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_util.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b1d699b44b5cfb86a6a3f9d4dbee52a5cd00dfd3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/multi/test_util.py @@ -0,0 +1,60 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.core.indexes.multi 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 = pd.date_range("2000-01-01", periods=2) + result1, result2 = (pd.Index(y).day for y in cartesian_product([x, x])) + expected1 = pd.Index([1, 1, 2, 2], dtype=np.int32) + expected2 = pd.Index([1, 2, 1, 2], dtype=np.int32) + tm.assert_index_equal(result1, expected1) + tm.assert_index_equal(result2, expected2) + + @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!" + + dims = [np.arange(0, 22, dtype=np.int16) for i in range(12)] + [ + (np.arange(15128, dtype=np.int16)), + ] + with pytest.raises(ValueError, match=msg): + cartesian_product(X=dims) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_astype.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3272a3a7d3cd5480ef53e959d7b911740275a2 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_astype.py @@ -0,0 +1,91 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestAstype: + def test_astype_float64_to_uint64(self): + # GH#45309 used to incorrectly return Index with int64 dtype + idx = pd.Index([0.0, 5.0, 10.0, 15.0, 20.0], dtype=np.float64) + result = idx.astype("u8") + expected = pd.Index([0, 5, 10, 15, 20], dtype=np.uint64) + tm.assert_index_equal(result, expected, exact=True) + + idx_with_negatives = idx - 10 + with pytest.raises(ValueError, match="losslessly"): + idx_with_negatives.astype(np.uint64) + + def test_astype_float64_to_object(self): + float_index = pd.Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=np.float64) + result = float_index.astype(object) + assert result.equals(float_index) + assert float_index.equals(result) + assert isinstance(result, pd.Index) and result.dtype == object + + def test_astype_float64_mixed_to_object(self): + # mixed int-float + idx = pd.Index([1.5, 2, 3, 4, 5], dtype=np.float64) + idx.name = "foo" + result = idx.astype(object) + assert result.equals(idx) + assert idx.equals(result) + assert isinstance(result, pd.Index) and result.dtype == object + + @pytest.mark.parametrize("dtype", ["int16", "int32", "int64"]) + def test_astype_float64_to_int_dtype(self, dtype): + # GH#12881 + # a float astype int + idx = pd.Index([0, 1, 2], dtype=np.float64) + result = idx.astype(dtype) + expected = pd.Index([0, 1, 2], dtype=dtype) + tm.assert_index_equal(result, expected, exact=True) + + idx = pd.Index([0, 1.1, 2], dtype=np.float64) + result = idx.astype(dtype) + expected = pd.Index([0, 1, 2], dtype=dtype) + tm.assert_index_equal(result, expected, exact=True) + + @pytest.mark.parametrize("dtype", ["float32", "float64"]) + def test_astype_float64_to_float_dtype(self, dtype): + # GH#12881 + # a float astype int + idx = pd.Index([0, 1, 2], dtype=np.float64) + result = idx.astype(dtype) + assert isinstance(result, pd.Index) and result.dtype == dtype + + @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"]) + def test_astype_float_to_datetimelike(self, dtype): + # GH#49660 pre-2.0 Index.astype from floating to M8/m8/Period raised, + # inconsistent with Series.astype + idx = pd.Index([0, 1.1, 2], dtype=np.float64) + + result = idx.astype(dtype) + if dtype[0] == "M": + expected = pd.to_datetime(idx.values) + else: + expected = pd.to_timedelta(idx.values) + tm.assert_index_equal(result, expected) + + # check that we match Series behavior + result = idx.to_series().set_axis(range(3)).astype(dtype) + expected = expected.to_series().set_axis(range(3)) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("dtype", [int, "int16", "int32", "int64"]) + @pytest.mark.parametrize("non_finite", [np.inf, np.nan]) + def test_cannot_cast_inf_to_int(self, non_finite, dtype): + # GH#13149 + idx = pd.Index([1, 2, non_finite], dtype=np.float64) + + msg = r"Cannot convert non-finite values \(NA or inf\) to integer" + with pytest.raises(ValueError, match=msg): + idx.astype(dtype) + + def test_astype_from_object(self): + index = pd.Index([1.0, np.nan, 0.2], dtype="object") + result = index.astype(float) + expected = pd.Index([1.0, np.nan, 0.2], dtype=np.float64) + assert result.dtype == expected.dtype + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..361066c2761082a9b6a48318a38f3efb18a741c2 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_indexing.py @@ -0,0 +1,625 @@ +import numpy as np +import pytest + +from pandas.errors import InvalidIndexError + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import ( + ArrowExtensionArray, + FloatingArray, +) + + +class TestGetLoc: + def test_get_loc(self): + index = pd.Index([0, 1, 2]) + assert index.get_loc(1) == 1 + + def test_get_loc_raises_bad_label(self): + index = pd.Index([0, 1, 2]) + with pytest.raises(InvalidIndexError, match=r"\[1, 2\]"): + index.get_loc([1, 2]) + + def test_get_loc_float64(self): + idx = pd.Index([0.0, 1.0, 2.0], dtype=np.float64) + + with pytest.raises(KeyError, match="^'foo'$"): + idx.get_loc("foo") + with pytest.raises(KeyError, match=r"^1\.5$"): + idx.get_loc(1.5) + with pytest.raises(KeyError, match="^True$"): + idx.get_loc(True) + with pytest.raises(KeyError, match="^False$"): + idx.get_loc(False) + + def test_get_loc_na(self): + idx = pd.Index([np.nan, 1, 2], dtype=np.float64) + assert idx.get_loc(1) == 1 + assert idx.get_loc(np.nan) == 0 + + idx = pd.Index([np.nan, 1, np.nan], dtype=np.float64) + assert idx.get_loc(1) == 1 + + # representable by slice [0:2:2] + msg = "'Cannot get left slice bound for non-unique label: nan'" + with pytest.raises(KeyError, match=msg): + idx.slice_locs(np.nan) + # not representable by slice + idx = pd.Index([np.nan, 1, np.nan, np.nan], dtype=np.float64) + assert idx.get_loc(1) == 1 + msg = "'Cannot get left slice bound for non-unique label: nan" + with pytest.raises(KeyError, match=msg): + idx.slice_locs(np.nan) + + def test_get_loc_missing_nan(self): + # GH#8569 + idx = pd.Index([1, 2], dtype=np.float64) + assert idx.get_loc(1) == 0 + with pytest.raises(KeyError, match=r"^3$"): + idx.get_loc(3) + with pytest.raises(KeyError, match="^nan$"): + idx.get_loc(np.nan) + with pytest.raises(InvalidIndexError, match=r"\[nan\]"): + # listlike/non-hashable raises TypeError + idx.get_loc([np.nan]) + + @pytest.mark.parametrize( + "vals", [[1], [1.0], [pd.Timestamp("2019-12-31")], ["test"]] + ) + def test_get_loc_float_index_nan_with_method(self, vals): + # GH#39382 + idx = pd.Index(vals) + with pytest.raises(KeyError, match="nan"): + idx.get_loc(np.nan) + + @pytest.mark.parametrize("dtype", ["f8", "i8", "u8"]) + def test_get_loc_numericindex_none_raises(self, dtype): + # case that goes through searchsorted and key is non-comparable to values + arr = np.arange(10**7, dtype=dtype) + idx = pd.Index(arr) + with pytest.raises(KeyError, match="None"): + idx.get_loc(None) + + def test_get_loc_overflows(self): + # unique but non-monotonic goes through IndexEngine.mapping.get_item + idx = pd.Index([0, 2, 1]) + + val = np.iinfo(np.int64).max + 1 + + with pytest.raises(KeyError, match=str(val)): + idx.get_loc(val) + with pytest.raises(KeyError, match=str(val)): + idx._engine.get_loc(val) + + +class TestGetIndexer: + def test_get_indexer(self): + index1 = pd.Index([1, 2, 3, 4, 5]) + index2 = pd.Index([2, 4, 6]) + + r1 = index1.get_indexer(index2) + e1 = np.array([1, 3, -1], dtype=np.intp) + tm.assert_almost_equal(r1, e1) + + @pytest.mark.parametrize("reverse", [True, False]) + @pytest.mark.parametrize( + "expected,method", + [ + ([-1, 0, 0, 1, 1], "pad"), + ([-1, 0, 0, 1, 1], "ffill"), + ([0, 0, 1, 1, 2], "backfill"), + ([0, 0, 1, 1, 2], "bfill"), + ], + ) + def test_get_indexer_methods(self, reverse, expected, method): + index1 = pd.Index([1, 2, 3, 4, 5]) + index2 = pd.Index([2, 4, 6]) + expected = np.array(expected, dtype=np.intp) + if reverse: + index1 = index1[::-1] + expected = expected[::-1] + + result = index2.get_indexer(index1, method=method) + tm.assert_almost_equal(result, expected) + + def test_get_indexer_invalid(self): + # GH10411 + index = pd.Index(np.arange(10)) + + with pytest.raises(ValueError, match="tolerance argument"): + index.get_indexer([1, 0], tolerance=1) + + with pytest.raises(ValueError, match="limit argument"): + index.get_indexer([1, 0], limit=1) + + @pytest.mark.parametrize( + "method, tolerance, indexer, expected", + [ + ("pad", None, [0, 5, 9], [0, 5, 9]), + ("backfill", None, [0, 5, 9], [0, 5, 9]), + ("nearest", None, [0, 5, 9], [0, 5, 9]), + ("pad", 0, [0, 5, 9], [0, 5, 9]), + ("backfill", 0, [0, 5, 9], [0, 5, 9]), + ("nearest", 0, [0, 5, 9], [0, 5, 9]), + ("pad", None, [0.2, 1.8, 8.5], [0, 1, 8]), + ("backfill", None, [0.2, 1.8, 8.5], [1, 2, 9]), + ("nearest", None, [0.2, 1.8, 8.5], [0, 2, 9]), + ("pad", 1, [0.2, 1.8, 8.5], [0, 1, 8]), + ("backfill", 1, [0.2, 1.8, 8.5], [1, 2, 9]), + ("nearest", 1, [0.2, 1.8, 8.5], [0, 2, 9]), + ("pad", 0.2, [0.2, 1.8, 8.5], [0, -1, -1]), + ("backfill", 0.2, [0.2, 1.8, 8.5], [-1, 2, -1]), + ("nearest", 0.2, [0.2, 1.8, 8.5], [0, 2, -1]), + ], + ) + def test_get_indexer_nearest(self, method, tolerance, indexer, expected): + index = pd.Index(np.arange(10)) + + actual = index.get_indexer(indexer, method=method, tolerance=tolerance) + tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp)) + + @pytest.mark.parametrize("listtype", [list, tuple, pd.Series, np.array]) + @pytest.mark.parametrize( + "tolerance, expected", + [ + [[0.3, 0.3, 0.1], [0, 2, -1]], + [[0.2, 0.1, 0.1], [0, -1, -1]], + [[0.1, 0.5, 0.5], [-1, 2, 9]], + ], + ) + def test_get_indexer_nearest_listlike_tolerance( + self, tolerance, expected, listtype + ): + index = pd.Index(np.arange(10)) + + actual = index.get_indexer( + [0.2, 1.8, 8.5], method="nearest", tolerance=listtype(tolerance) + ) + tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp)) + + @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"]) + def test_get_indexer_nan_target(self, method): + # GH#32572 NaN in the target should not be matched + index = pd.Index([1.0, 2.0, 3.0, 4.0, 5.0]) + target = pd.Index([np.nan]) + result = index.get_indexer(target, method=method) + expected = np.array([-1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_nearest_error(self): + index = pd.Index(np.arange(10)) + with pytest.raises(ValueError, match="limit argument"): + index.get_indexer([1, 0], method="nearest", limit=1) + + with pytest.raises(ValueError, match="tolerance size must match"): + index.get_indexer([1, 0], method="nearest", tolerance=[1, 2, 3]) + + @pytest.mark.parametrize( + "method,expected", + [("pad", [8, 7, 0]), ("backfill", [9, 8, 1]), ("nearest", [9, 7, 0])], + ) + def test_get_indexer_nearest_decreasing(self, method, expected): + index = pd.Index(np.arange(10))[::-1] + + actual = index.get_indexer([0, 5, 9], method=method) + tm.assert_numpy_array_equal(actual, np.array([9, 4, 0], dtype=np.intp)) + + actual = index.get_indexer([0.2, 1.8, 8.5], method=method) + tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp)) + + @pytest.mark.parametrize("idx_dtype", ["int64", "float64", "uint64", "range"]) + @pytest.mark.parametrize("method", ["get_indexer", "get_indexer_non_unique"]) + def test_get_indexer_numeric_index_boolean_target(self, method, idx_dtype): + # GH 16877 + + if idx_dtype == "range": + numeric_index = pd.RangeIndex(4) + else: + numeric_index = pd.Index(np.arange(4, dtype=idx_dtype)) + + other = pd.Index([True, False, True]) + + result = getattr(numeric_index, method)(other) + expected = np.array([-1, -1, -1], dtype=np.intp) + if method == "get_indexer": + tm.assert_numpy_array_equal(result, expected) + else: + missing = np.arange(3, dtype=np.intp) + tm.assert_numpy_array_equal(result[0], expected) + tm.assert_numpy_array_equal(result[1], missing) + + @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"]) + def test_get_indexer_with_method_numeric_vs_bool(self, method): + left = pd.Index([1, 2, 3]) + right = pd.Index([True, False]) + + with pytest.raises(TypeError, match="Cannot compare"): + left.get_indexer(right, method=method) + + with pytest.raises(TypeError, match="Cannot compare"): + right.get_indexer(left, method=method) + + def test_get_indexer_numeric_vs_bool(self): + left = pd.Index([1, 2, 3]) + right = pd.Index([True, False]) + + res = left.get_indexer(right) + expected = -1 * np.ones(len(right), dtype=np.intp) + tm.assert_numpy_array_equal(res, expected) + + res = right.get_indexer(left) + expected = -1 * np.ones(len(left), dtype=np.intp) + tm.assert_numpy_array_equal(res, expected) + + res = left.get_indexer_non_unique(right)[0] + expected = -1 * np.ones(len(right), dtype=np.intp) + tm.assert_numpy_array_equal(res, expected) + + res = right.get_indexer_non_unique(left)[0] + expected = -1 * np.ones(len(left), dtype=np.intp) + tm.assert_numpy_array_equal(res, expected) + + def test_get_indexer_float64(self): + idx = pd.Index([0.0, 1.0, 2.0], dtype=np.float64) + tm.assert_numpy_array_equal( + idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp) + ) + + target = [-0.1, 0.5, 1.1] + tm.assert_numpy_array_equal( + idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp) + ) + + def test_get_indexer_nan(self): + # GH#7820 + result = pd.Index([1, 2, np.nan], dtype=np.float64).get_indexer([np.nan]) + expected = np.array([2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_int64(self): + index = pd.Index(range(0, 20, 2), dtype=np.int64) + target = pd.Index(np.arange(10), dtype=np.int64) + indexer = index.get_indexer(target) + expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + target = pd.Index(np.arange(10), dtype=np.int64) + indexer = index.get_indexer(target, method="pad") + expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + target = pd.Index(np.arange(10), dtype=np.int64) + indexer = index.get_indexer(target, method="backfill") + expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + def test_get_indexer_uint64(self): + index_large = pd.Index( + [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25], + dtype=np.uint64, + ) + target = pd.Index(np.arange(10).astype("uint64") * 5 + 2**63) + indexer = index_large.get_indexer(target) + expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + target = pd.Index(np.arange(10).astype("uint64") * 5 + 2**63) + indexer = index_large.get_indexer(target, method="pad") + expected = np.array([0, 0, 1, 2, 3, 4, 4, 4, 4, 4], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + target = pd.Index(np.arange(10).astype("uint64") * 5 + 2**63) + indexer = index_large.get_indexer(target, method="backfill") + expected = np.array([0, 1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + @pytest.mark.parametrize("val, val2", [(4, 5), (4, 4), (4, pd.NA), (pd.NA, pd.NA)]) + def test_get_loc_masked(self, val, val2, any_numeric_ea_and_arrow_dtype): + # GH#39133 + idx = pd.Index([1, 2, 3, val, val2], dtype=any_numeric_ea_and_arrow_dtype) + result = idx.get_loc(2) + assert result == 1 + + with pytest.raises(KeyError, match="9"): + idx.get_loc(9) + + def test_get_loc_masked_na(self, any_numeric_ea_and_arrow_dtype): + # GH#39133 + idx = pd.Index([1, 2, pd.NA], dtype=any_numeric_ea_and_arrow_dtype) + result = idx.get_loc(pd.NA) + assert result == 2 + + idx = pd.Index([1, 2, pd.NA, pd.NA], dtype=any_numeric_ea_and_arrow_dtype) + result = idx.get_loc(pd.NA) + tm.assert_numpy_array_equal(result, np.array([False, False, True, True])) + + idx = pd.Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype) + with pytest.raises(KeyError, match="NA"): + idx.get_loc(pd.NA) + + def test_get_loc_masked_na_and_nan(self, using_nan_is_na): + # GH#39133 + mask = np.array([False, False, True, False]) + if using_nan_is_na: + mask[-1] = True + + idx = pd.Index(FloatingArray(np.array([1, 2, 1, np.nan]), mask=mask)) + if using_nan_is_na: + # NaN and NA are consistently treated as the same + result = idx.get_loc(pd.NA) + expected = np.array([False, False, True, True]) + tm.assert_numpy_array_equal(result, expected) + result = idx.get_loc(np.nan) + tm.assert_numpy_array_equal(result, expected) + else: + result = idx.get_loc(pd.NA) + assert result == 2 + result = idx.get_loc(np.nan) + assert result == 3 + + idx = pd.Index( + FloatingArray(np.array([1, 2, 1.0]), mask=np.array([False, False, True])) + ) + result = idx.get_loc(pd.NA) + assert result == 2 + if using_nan_is_na: + result = idx.get_loc(np.nan) + assert result == 2 + else: + with pytest.raises(KeyError, match="nan"): + idx.get_loc(np.nan) + + mask = np.array([False, False, False]) + if using_nan_is_na: + mask[-1] = True + idx = pd.Index(FloatingArray(np.array([1, 2, np.nan]), mask=mask)) + result = idx.get_loc(np.nan) + assert result == 2 + if using_nan_is_na: + result = idx.get_loc(pd.NA) + assert result == 2 + else: + with pytest.raises(KeyError, match="NA"): + idx.get_loc(pd.NA) + + @pytest.mark.parametrize("val", [4, 2]) + def test_get_indexer_masked_na(self, any_numeric_ea_and_arrow_dtype, val): + # GH#39133 + idx = pd.Index([1, 2, pd.NA, 3, val], dtype=any_numeric_ea_and_arrow_dtype) + result = idx.get_indexer_for([1, pd.NA, 5]) + expected = np.array([0, 2, -1]) + tm.assert_numpy_array_equal(result, expected, check_dtype=False) + + @pytest.mark.parametrize("dtype", ["boolean", "bool[pyarrow]"]) + def test_get_indexer_masked_na_boolean(self, dtype): + # GH#39133 + if dtype == "bool[pyarrow]": + pytest.importorskip("pyarrow") + idx = pd.Index([True, False, pd.NA], dtype=dtype) + result = idx.get_loc(False) + assert result == 1 + result = idx.get_loc(pd.NA) + assert result == 2 + + def test_get_indexer_arrow_dictionary_target(self): + pa = pytest.importorskip("pyarrow") + target = pd.Index( + ArrowExtensionArray( + pa.array([1, 2], type=pa.dictionary(pa.int8(), pa.int8())) + ) + ) + idx = pd.Index([1]) + + result = idx.get_indexer(target) + expected = np.array([0, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result_1, result_2 = idx.get_indexer_non_unique(target) + expected_1, expected_2 = ( + np.array([0, -1], dtype=np.intp), + np.array([1], dtype=np.intp), + ) + tm.assert_numpy_array_equal(result_1, expected_1) + tm.assert_numpy_array_equal(result_2, expected_2) + + +class TestWhere: + @pytest.mark.parametrize( + "index", + [ + pd.Index(np.arange(5, dtype="float64")), + pd.Index(range(0, 20, 2), dtype=np.int64), + pd.Index(np.arange(5, dtype="uint64")), + ], + ) + def test_where(self, listlike_box, index): + cond = [True] * len(index) + expected = index + result = index.where(listlike_box(cond)) + + cond = [False] + [True] * (len(index) - 1) + expected = pd.Index([index._na_value, *index[1:].tolist()], dtype=np.float64) + result = index.where(listlike_box(cond)) + tm.assert_index_equal(result, expected) + + def test_where_uint64(self): + idx = pd.Index([0, 6, 2], dtype=np.uint64) + mask = np.array([False, True, False]) + other = np.array([1], dtype=np.int64) + + expected = pd.Index([1, 6, 1], dtype=np.uint64) + + result = idx.where(mask, other) + tm.assert_index_equal(result, expected) + + result = idx.putmask(~mask, other) + tm.assert_index_equal(result, expected) + + def test_where_infers_type_instead_of_trying_to_convert_string_to_float(self): + # GH 32413 + index = pd.Index([1, np.nan]) + cond = index.notna() + other = pd.Index(["a", "b"], dtype="string") + + expected = pd.Index([1.0, "b"]) + result = index.where(cond, other) + + tm.assert_index_equal(result, expected) + + +class TestTake: + @pytest.mark.parametrize("idx_dtype", [np.float64, np.int64, np.uint64]) + def test_take_preserve_name(self, idx_dtype): + index = pd.Index([1, 2, 3, 4], dtype=idx_dtype, name="foo") + taken = index.take([3, 0, 1]) + assert index.name == taken.name + + def test_take_fill_value_float64(self): + # GH 12631 + idx = pd.Index([1.0, 2.0, 3.0], name="xxx", dtype=np.float64) + result = idx.take(np.array([1, 0, -1])) + expected = pd.Index([2.0, 1.0, 3.0], dtype=np.float64, name="xxx") + tm.assert_index_equal(result, expected) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=np.nan) + expected = pd.Index([2.0, 1.0, np.nan], dtype=np.float64, name="xxx") + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False) + expected = pd.Index([2.0, 1.0, 3.0], dtype=np.float64, name="xxx") + tm.assert_index_equal(result, expected) + + msg = "When allow_fill=True, all indices must be >= -1" + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + @pytest.mark.parametrize("dtype", [np.int64, np.uint64]) + def test_take_fill_value_ints(self, dtype): + # see gh-12631 + idx = pd.Index([1, 2, 3], dtype=dtype, name="xxx") + result = idx.take(np.array([1, 0, -1])) + expected = pd.Index([2, 1, 3], dtype=dtype, name="xxx") + tm.assert_index_equal(result, expected) + + # fill_value on integer Index produces object dtype to hold NA + result = idx.take(np.array([1, 0, -1]), fill_value=np.nan) + expected = pd.Index([2, 1, np.nan], name="xxx") + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False) + expected = pd.Index([2, 1, 3], dtype=dtype, name="xxx") + tm.assert_index_equal(result, expected) + + msg = "When allow_fill=True, all indices must be >= -1" + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + +class TestContains: + @pytest.mark.parametrize("dtype", [np.float64, np.int64, np.uint64]) + def test_contains_none(self, dtype): + # GH#35788 should return False, not raise TypeError + index = pd.Index([0, 1, 2, 3, 4], dtype=dtype) + assert None not in index + + def test_contains_float64_nans(self): + index = pd.Index([1.0, 2.0, np.nan], dtype=np.float64) + assert np.nan in index + + def test_contains_float64_not_nans(self): + index = pd.Index([1.0, 2.0, np.nan], dtype=np.float64) + assert 1.0 in index + + +class TestSliceLocs: + @pytest.mark.parametrize("dtype", [int, float]) + def test_slice_locs(self, dtype): + index = pd.Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype)) + n = len(index) + + assert index.slice_locs(start=2) == (2, n) + assert index.slice_locs(start=3) == (3, n) + assert index.slice_locs(3, 8) == (3, 6) + assert index.slice_locs(5, 10) == (3, n) + assert index.slice_locs(end=8) == (0, 6) + assert index.slice_locs(end=9) == (0, 7) + + # reversed + index2 = index[::-1] + assert index2.slice_locs(8, 2) == (2, 6) + assert index2.slice_locs(7, 3) == (2, 5) + + @pytest.mark.parametrize("dtype", [int, float]) + def test_slice_locs_float_locs(self, dtype): + index = pd.Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype)) + n = len(index) + assert index.slice_locs(5.0, 10.0) == (3, n) + assert index.slice_locs(4.5, 10.5) == (3, 8) + + index2 = index[::-1] + assert index2.slice_locs(8.5, 1.5) == (2, 6) + assert index2.slice_locs(10.5, -1) == (0, n) + + @pytest.mark.parametrize("dtype", [int, float]) + def test_slice_locs_dup_numeric(self, dtype): + index = pd.Index(np.array([10, 12, 12, 14], dtype=dtype)) + assert index.slice_locs(12, 12) == (1, 3) + assert index.slice_locs(11, 13) == (1, 3) + + index2 = index[::-1] + assert index2.slice_locs(12, 12) == (1, 3) + assert index2.slice_locs(13, 11) == (1, 3) + + def test_slice_locs_na(self): + index = pd.Index([np.nan, 1, 2]) + assert index.slice_locs(1) == (1, 3) + assert index.slice_locs(np.nan) == (0, 3) + + index = pd.Index([0, np.nan, np.nan, 1, 2]) + assert index.slice_locs(np.nan) == (1, 5) + + def test_slice_locs_na_raises(self): + index = pd.Index([np.nan, 1, 2]) + msg = "non-monotonic index with a missing label 1.5" + with pytest.raises(KeyError, match=msg): + index.slice_locs(start=1.5) + + with pytest.raises(KeyError, match=msg): + index.slice_locs(end=1.5) + + +class TestGetSliceBounds: + @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)]) + def test_get_slice_bounds_within(self, side, expected): + index = pd.Index(range(6)) + result = index.get_slice_bound(4, side=side) + assert result == expected + + @pytest.mark.parametrize("side", ["left", "right"]) + @pytest.mark.parametrize("bound, expected", [(-1, 0), (10, 6)]) + def test_get_slice_bounds_outside(self, side, expected, bound): + index = pd.Index(range(6)) + result = index.get_slice_bound(bound, side=side) + assert result == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_join.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..737b36469ccb9e4e6de311a0e8102295823f314c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_join.py @@ -0,0 +1,368 @@ +import numpy as np +import pytest + +import pandas._testing as tm +from pandas.core.indexes.api import Index + + +class TestJoinInt64Index: + def test_join_non_unique(self): + left = Index([4, 4, 3, 3]) + + joined, lidx, ridx = left.join(left, return_indexers=True) + + exp_joined = Index([4, 4, 4, 4, 3, 3, 3, 3]) + tm.assert_index_equal(joined, exp_joined) + + exp_lidx = np.array([0, 0, 1, 1, 2, 2, 3, 3], dtype=np.intp) + tm.assert_numpy_array_equal(lidx, exp_lidx) + + exp_ridx = np.array([0, 1, 0, 1, 2, 3, 2, 3], dtype=np.intp) + tm.assert_numpy_array_equal(ridx, exp_ridx) + + def test_join_inner(self): + index = Index(range(0, 20, 2), dtype=np.int64, name="lhs") + other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64, name="rhs") + other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64, name="rhs") + + # not monotonic + res, lidx, ridx = index.join(other, how="inner", return_indexers=True) + + eres = Index([2, 12], dtype=np.int64, name="lhs") + elidx = np.array([1, 6], dtype=np.intp) + eridx = np.array([4, 1], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres, exact="equiv") + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index.join(other_mono, how="inner", return_indexers=True) + + res2 = index.intersection(other_mono).set_names(["lhs"]) + tm.assert_index_equal(res, res2, exact="equiv") + + elidx = np.array([1, 6], dtype=np.intp) + eridx = np.array([1, 4], dtype=np.intp) + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres, exact="equiv") + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_left(self): + index = Index(range(0, 20, 2), dtype=np.int64, name="lhs") + other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64, name="rhs") + other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64, name="rhs") + + # not monotonic + res, lidx, ridx = index.join(other, how="left", return_indexers=True) + eres = index + eridx = np.array([-1, 4, -1, -1, -1, -1, 1, -1, -1, -1], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index.join(other_mono, how="left", return_indexers=True) + eridx = np.array([-1, 1, -1, -1, -1, -1, 4, -1, -1, -1], dtype=np.intp) + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + # non-unique + idx = Index([1, 1, 2, 5], name="rhs") + idx2 = Index([1, 2, 5, 7, 9], name="lhs") + res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True) + eres = Index([1, 1, 2, 5, 7, 9], name="lhs") # 1 is in idx2, so it should be x2 + eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_right(self): + index = Index(range(0, 20, 2), dtype=np.int64, name="lhs") + other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64, name="rhs") + other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64, name="rhs") + + # not monotonic + res, lidx, ridx = index.join(other, how="right", return_indexers=True) + eres = other + elidx = np.array([-1, 6, -1, -1, 1, -1], dtype=np.intp) + + assert isinstance(other, Index) and other.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + assert ridx is None + + # monotonic + res, lidx, ridx = index.join(other_mono, how="right", return_indexers=True) + eres = other_mono + elidx = np.array([-1, 1, -1, -1, 6, -1], dtype=np.intp) + assert isinstance(other, Index) and other.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + assert ridx is None + + # non-unique + idx = Index([1, 1, 2, 5], name="lhs") + idx2 = Index([1, 2, 5, 7, 9], name="rhs") + res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True) + eres = Index([1, 1, 2, 5, 7, 9], name="rhs") # 1 is in idx2, so it should be x2 + elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_non_int_index(self): + index = Index(range(0, 20, 2), dtype=np.int64) + other = Index([3, 6, 7, 8, 10], dtype=object) + + outer = index.join(other, how="outer") + outer2 = other.join(index, how="outer") + expected = Index([0, 2, 3, 4, 6, 7, 8, 10, 12, 14, 16, 18]) + tm.assert_index_equal(outer, outer2) + tm.assert_index_equal(outer, expected) + + inner = index.join(other, how="inner") + inner2 = other.join(index, how="inner") + expected = Index([6, 8, 10]) + tm.assert_index_equal(inner, inner2) + tm.assert_index_equal(inner, expected) + + left = index.join(other, how="left") + tm.assert_index_equal(left, index) + + left2 = other.join(index, how="left") + tm.assert_index_equal(left2, other) + + right = index.join(other, how="right") + tm.assert_index_equal(right, other) + + right2 = other.join(index, how="right") + tm.assert_index_equal(right2, index) + + def test_join_outer(self): + index = Index(range(0, 20, 2), dtype=np.int64) + other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64) + other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64) + + # not monotonic + # guarantee of sortedness + res, lidx, ridx = index.join(other, how="outer", return_indexers=True) + noidx_res = index.join(other, how="outer") + tm.assert_index_equal(res, noidx_res) + + eres = Index([0, 1, 2, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 25], dtype=np.int64) + elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp) + eridx = np.array( + [-1, 3, 4, -1, 5, -1, 0, -1, -1, 1, -1, -1, -1, 2], dtype=np.intp + ) + + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index.join(other_mono, how="outer", return_indexers=True) + noidx_res = index.join(other_mono, how="outer") + tm.assert_index_equal(res, noidx_res) + + elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp) + eridx = np.array( + [-1, 0, 1, -1, 2, -1, 3, -1, -1, 4, -1, -1, -1, 5], dtype=np.intp + ) + assert isinstance(res, Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + +class TestJoinUInt64Index: + @pytest.fixture + def index_large(self): + # large values used in TestUInt64Index where no compat needed with int64/float64 + large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25] + return Index(large, dtype=np.uint64) + + def test_join_inner(self, index_large): + other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64")) + other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")) + + # not monotonic + res, lidx, ridx = index_large.join(other, how="inner", return_indexers=True) + + # no guarantee of sortedness, so sort for comparison purposes + ind = res.argsort() + res = res.take(ind) + lidx = lidx.take(ind) + ridx = ridx.take(ind) + + eres = Index(2**63 + np.array([10, 25], dtype="uint64")) + elidx = np.array([1, 4], dtype=np.intp) + eridx = np.array([5, 2], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index_large.join( + other_mono, how="inner", return_indexers=True + ) + + res2 = index_large.intersection(other_mono) + tm.assert_index_equal(res, res2) + + elidx = np.array([1, 4], dtype=np.intp) + eridx = np.array([3, 5], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_left(self, index_large): + other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64")) + other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")) + + # not monotonic + res, lidx, ridx = index_large.join(other, how="left", return_indexers=True) + eres = index_large + eridx = np.array([-1, 5, -1, -1, 2], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index_large.join(other_mono, how="left", return_indexers=True) + eridx = np.array([-1, 3, -1, -1, 5], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + # non-unique + idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64")) + idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64")) + res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True) + + # 1 is in idx2, so it should be x2 + eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64")) + eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_right(self, index_large): + other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64")) + other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")) + + # not monotonic + res, lidx, ridx = index_large.join(other, how="right", return_indexers=True) + eres = other + elidx = np.array([-1, -1, 4, -1, -1, 1], dtype=np.intp) + + tm.assert_numpy_array_equal(lidx, elidx) + assert isinstance(other, Index) and other.dtype == np.uint64 + tm.assert_index_equal(res, eres) + assert ridx is None + + # monotonic + res, lidx, ridx = index_large.join( + other_mono, how="right", return_indexers=True + ) + eres = other_mono + elidx = np.array([-1, -1, -1, 1, -1, 4], dtype=np.intp) + + assert isinstance(other, Index) and other.dtype == np.uint64 + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_index_equal(res, eres) + assert ridx is None + + # non-unique + idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64")) + idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64")) + res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True) + + # 1 is in idx2, so it should be x2 + eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64")) + elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_non_int_index(self, index_large): + other = Index(2**63 + np.array([1, 5, 7, 10, 20], dtype="uint64"), dtype=object) + + outer = index_large.join(other, how="outer") + outer2 = other.join(index_large, how="outer") + expected = Index(2**63 + np.array([0, 1, 5, 7, 10, 15, 20, 25], dtype="uint64")) + tm.assert_index_equal(outer, outer2) + tm.assert_index_equal(outer, expected) + + inner = index_large.join(other, how="inner") + inner2 = other.join(index_large, how="inner") + expected = Index(2**63 + np.array([10, 20], dtype="uint64")) + tm.assert_index_equal(inner, inner2) + tm.assert_index_equal(inner, expected) + + left = index_large.join(other, how="left") + tm.assert_index_equal(left, index_large) + + left2 = other.join(index_large, how="left") + tm.assert_index_equal(left2, other) + + right = index_large.join(other, how="right") + tm.assert_index_equal(right, other) + + right2 = other.join(index_large, how="right") + tm.assert_index_equal(right2, index_large) + + def test_join_outer(self, index_large): + other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64")) + other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")) + + # not monotonic + # guarantee of sortedness + res, lidx, ridx = index_large.join(other, how="outer", return_indexers=True) + noidx_res = index_large.join(other, how="outer") + tm.assert_index_equal(res, noidx_res) + + eres = Index(2**63 + np.array([0, 1, 2, 7, 10, 12, 15, 20, 25], dtype="uint64")) + elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp) + eridx = np.array([-1, 3, 4, 0, 5, 1, -1, -1, 2], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # monotonic + res, lidx, ridx = index_large.join( + other_mono, how="outer", return_indexers=True + ) + noidx_res = index_large.join(other_mono, how="outer") + tm.assert_index_equal(res, noidx_res) + + elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp) + eridx = np.array([-1, 0, 1, 2, 3, 4, -1, -1, 5], dtype=np.intp) + + assert isinstance(res, Index) and res.dtype == np.uint64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_numeric.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_numeric.py new file mode 100644 index 0000000000000000000000000000000000000000..48945818524972eb40861980d8009217f9b875b5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_numeric.py @@ -0,0 +1,549 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestFloatNumericIndex: + @pytest.fixture(params=[np.float64, np.float32]) + def dtype(self, request): + return request.param + + @pytest.fixture + def mixed_index(self, dtype): + return pd.Index([1.5, 2, 3, 4, 5], dtype=dtype) + + @pytest.fixture + def float_index(self, dtype): + return pd.Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype) + + @pytest.mark.parametrize( + "index_data", + [ + [1.5, 2, 3, 4, 5], + [0.0, 2.5, 5.0, 7.5, 10.0], + [5, 4, 3, 2, 1.5], + [10.0, 7.5, 5.0, 2.5, 0.0], + ], + ids=["mixed", "float", "mixed_dec", "float_dec"], + ) + def test_repr_roundtrip(self, index_data, dtype): + index = pd.Index(index_data, dtype=dtype) + tm.assert_index_equal(eval(repr(index), dict(vars(pd))), index, exact=True) + + def check_coerce(self, a, b, is_float_index=True): + assert a.equals(b) + tm.assert_index_equal(a, b, exact=False) + if is_float_index: + assert isinstance(b, pd.Index) + else: + assert type(b) is pd.Index + + def test_constructor_from_list_no_dtype(self): + index = pd.Index([1.5, 2.5, 3.5]) + assert index.dtype == np.float64 + + def test_constructor(self, dtype): + index_cls = pd.Index + + # explicit construction + index = index_cls([1, 2, 3, 4, 5], dtype=dtype) + + assert isinstance(index, index_cls) + assert index.dtype == dtype + + expected = np.array([1, 2, 3, 4, 5], dtype=dtype) + tm.assert_numpy_array_equal(index.values, expected) + + index = index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype) + assert isinstance(index, index_cls) + assert index.dtype == dtype + + index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype) + assert isinstance(index, index_cls) + assert index.dtype == dtype + + index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype) + assert isinstance(index, index_cls) + assert index.dtype == dtype + + index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype) + assert isinstance(index, index_cls) + assert index.dtype == dtype + + index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype) + assert isinstance(index, index_cls) + assert index.dtype == dtype + + # nan handling + result = index_cls([np.nan, np.nan], dtype=dtype) + assert pd.isna(result.values).all() + + result = index_cls(np.array([np.nan]), dtype=dtype) + assert pd.isna(result.values).all() + + def test_constructor_invalid(self): + index_cls = pd.Index + cls_name = index_cls.__name__ + # invalid + msg = ( + rf"{cls_name}\(\.\.\.\) must be called with a collection of " + r"some kind, 0\.0 was passed" + ) + with pytest.raises(TypeError, match=msg): + index_cls(0.0) + + def test_constructor_coerce(self, mixed_index, float_index): + self.check_coerce(mixed_index, pd.Index([1.5, 2, 3, 4, 5])) + self.check_coerce(float_index, pd.Index(np.arange(5) * 2.5)) + + result = pd.Index(np.array(np.arange(5) * 2.5, dtype=object)) + assert result.dtype == object # as of 2.0 to match Series + self.check_coerce(float_index, result.astype("float64")) + + def test_constructor_explicit(self, mixed_index, float_index): + # these don't auto convert + self.check_coerce( + float_index, + pd.Index((np.arange(5) * 2.5), dtype=object), + is_float_index=False, + ) + self.check_coerce( + mixed_index, pd.Index([1.5, 2, 3, 4, 5], dtype=object), is_float_index=False + ) + + def test_type_coercion_fail(self, any_int_numpy_dtype): + # see gh-15832 + msg = "Trying to coerce float values to integers" + with pytest.raises(ValueError, match=msg): + pd.Index([1, 2, 3.5], dtype=any_int_numpy_dtype) + + def test_equals_numeric(self): + index_cls = pd.Index + + idx = index_cls([1.0, 2.0]) + assert idx.equals(idx) + assert idx.identical(idx) + + idx2 = index_cls([1.0, 2.0]) + assert idx.equals(idx2) + + idx = index_cls([1.0, np.nan]) + assert idx.equals(idx) + assert idx.identical(idx) + + idx2 = index_cls([1.0, np.nan]) + assert idx.equals(idx2) + + @pytest.mark.parametrize( + "other", + ( + pd.Index([1, 2], dtype=np.int64), + pd.Index([1.0, 2.0], dtype=object), + pd.Index([1, 2], dtype=object), + ), + ) + def test_equals_numeric_other_index_type(self, other): + idx = pd.Index([1.0, 2.0]) + assert idx.equals(other) + assert other.equals(idx) + + @pytest.mark.parametrize( + "vals", + [ + pd.date_range("2016-01-01", periods=3), + pd.timedelta_range("1 Day", periods=3), + ], + ) + def test_lookups_datetimelike_values(self, vals, dtype): + # If we have datetime64 or timedelta64 values, make sure they are + # wrapped correctly GH#31163 + ser = pd.Series(vals, index=range(3, 6)) + ser.index = ser.index.astype(dtype) + + expected = vals[1] + + result = ser[4.0] + assert isinstance(result, type(expected)) and result == expected + result = ser[4] + assert isinstance(result, type(expected)) and result == expected + + result = ser.loc[4.0] + assert isinstance(result, type(expected)) and result == expected + result = ser.loc[4] + assert isinstance(result, type(expected)) and result == expected + + result = ser.at[4.0] + assert isinstance(result, type(expected)) and result == expected + # GH#31329 .at[4] should cast to 4.0, matching .loc behavior + result = ser.at[4] + assert isinstance(result, type(expected)) and result == expected + + result = ser.iloc[1] + assert isinstance(result, type(expected)) and result == expected + + result = ser.iat[1] + assert isinstance(result, type(expected)) and result == expected + + def test_doesnt_contain_all_the_things(self): + idx = pd.Index([np.nan]) + assert not idx.isin([0]).item() + assert not idx.isin([1]).item() + assert idx.isin([np.nan]).item() + + def test_nan_multiple_containment(self): + index_cls = pd.Index + + idx = index_cls([1.0, np.nan]) + tm.assert_numpy_array_equal(idx.isin([1.0]), np.array([True, False])) + tm.assert_numpy_array_equal(idx.isin([2.0, np.pi]), np.array([False, False])) + tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, True])) + tm.assert_numpy_array_equal(idx.isin([1.0, np.nan]), np.array([True, True])) + idx = index_cls([1.0, 2.0]) + tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, False])) + + def test_fillna_float64(self): + index_cls = pd.Index + # GH 11343 + idx = pd.Index([1.0, np.nan, 3.0], dtype=float, name="x") + # can't downcast + exp = pd.Index([1.0, 0.1, 3.0], name="x") + tm.assert_index_equal(idx.fillna(0.1), exp, exact=True) + + # downcast + exp = index_cls([1.0, 2.0, 3.0], name="x") + tm.assert_index_equal(idx.fillna(2), exp) + + # object + exp = pd.Index([1.0, "obj", 3.0], name="x") + # GH#45153 filling with incompatible value is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + tm.assert_index_equal(idx.fillna("obj"), exp, exact=True) + + def test_logical_compat(self, dtype): + idx = pd.Index(np.arange(5, dtype=dtype)) + assert idx.all() == idx.values.all() + assert idx.any() == idx.values.any() + + assert idx.all() == idx.to_series().all() + assert idx.any() == idx.to_series().any() + + +class TestNumericInt: + @pytest.fixture + def dtype(self, any_int_numpy_dtype): + return np.dtype(any_int_numpy_dtype) + + @pytest.fixture + def simple_index(self, dtype): + return pd.Index(range(0, 20, 2), dtype=dtype) + + def test_is_monotonic(self): + index_cls = pd.Index + + index = index_cls([1, 2, 3, 4]) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index._is_strictly_monotonic_increasing is True + assert index.is_monotonic_decreasing is False + assert index._is_strictly_monotonic_decreasing is False + + index = index_cls([4, 3, 2, 1]) + assert index.is_monotonic_increasing is False + assert index._is_strictly_monotonic_increasing is False + assert index._is_strictly_monotonic_decreasing is True + + index = index_cls([1]) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True + + def test_is_strictly_monotonic(self): + index_cls = pd.Index + + index = index_cls([1, 1, 2, 3]) + assert index.is_monotonic_increasing is True + assert index._is_strictly_monotonic_increasing is False + + index = index_cls([3, 2, 1, 1]) + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_decreasing is False + + index = index_cls([1, 1]) + assert index.is_monotonic_increasing + assert index.is_monotonic_decreasing + assert not index._is_strictly_monotonic_increasing + assert not index._is_strictly_monotonic_decreasing + + def test_logical_compat(self, simple_index): + idx = simple_index + assert idx.all() == idx.values.all() + assert idx.any() == idx.values.any() + + def test_identical(self, simple_index, dtype): + index = simple_index + + idx = pd.Index(index.copy()) + assert idx.identical(index) + + same_values_different_type = pd.Index(idx, dtype=object) + assert not idx.identical(same_values_different_type) + + idx = index.astype(dtype=object) + idx = idx.rename("foo") + same_values = pd.Index(idx, dtype=object) + assert same_values.identical(idx) + + assert not idx.identical(index) + assert pd.Index(same_values, name="foo", dtype=object).identical(idx) + + assert not index.astype(dtype=object).identical(index.astype(dtype=dtype)) + + def test_cant_or_shouldnt_cast(self, dtype): + msg = r"invalid literal for int\(\) with base 10: 'foo'" + + # can't + data = ["foo", "bar", "baz"] + with pytest.raises(ValueError, match=msg): + pd.Index(data, dtype=dtype) + + def test_view_index(self, simple_index): + index = simple_index + msg = "Cannot change data-type" + with pytest.raises(TypeError, match=msg): + index.view(pd.Index) + + def test_prevent_casting(self, simple_index): + index = simple_index + result = index.astype("O") + assert result.dtype == np.object_ + + +class TestIntNumericIndex: + @pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8]) + def dtype(self, request): + return request.param + + def test_constructor_from_list_no_dtype(self): + index = pd.Index([1, 2, 3]) + assert index.dtype == np.int64 + + def test_constructor(self, dtype): + index_cls = pd.Index + + # scalar raise Exception + msg = ( + rf"{index_cls.__name__}\(\.\.\.\) must be called with a collection of some " + "kind, 5 was passed" + ) + with pytest.raises(TypeError, match=msg): + index_cls(5) + + # copy + # pass list, coerce fine + index = index_cls([-5, 0, 1, 2], dtype=dtype) + arr = index.values.copy() + new_index = index_cls(arr, copy=True) + tm.assert_index_equal(new_index, index, exact=True) + val = int(arr[0]) + 3000 + + # this should not change index + if dtype != np.int8: + # NEP 50 won't allow assignment that would overflow + arr[0] = val + assert new_index[0] != val + + if dtype == np.int64: + # pass list, coerce fine + index = index_cls([-5, 0, 1, 2], dtype=dtype) + expected = pd.Index([-5, 0, 1, 2], dtype=dtype) + tm.assert_index_equal(index, expected) + + # from iterable + index = index_cls(iter([-5, 0, 1, 2]), dtype=dtype) + expected = index_cls([-5, 0, 1, 2], dtype=dtype) + tm.assert_index_equal(index, expected, exact=True) + + # interpret list-like + expected = index_cls([5, 0], dtype=dtype) + for cls in [pd.Index, index_cls]: + for idx in [ + cls([5, 0], dtype=dtype), + cls(np.array([5, 0]), dtype=dtype), + cls(pd.Series([5, 0]), dtype=dtype), + ]: + tm.assert_index_equal(idx, expected) + + def test_constructor_corner(self, dtype): + index_cls = pd.Index + + arr = np.array([1, 2, 3, 4], dtype=object) + + index = index_cls(arr, dtype=dtype) + assert index.values.dtype == index.dtype + if dtype == np.int64: + without_dtype = pd.Index(arr) + # as of 2.0 we do not infer a dtype when we get an object-dtype + # ndarray of numbers, matching Series behavior + assert without_dtype.dtype == object + + tm.assert_index_equal(index, without_dtype.astype(np.int64)) + + # preventing casting + arr = np.array([1, "2", 3, "4"], dtype=object) + msg = "Trying to coerce object values to integers" + with pytest.raises(ValueError, match=msg): + index_cls(arr, dtype=dtype) + + def test_constructor_coercion_signed_to_unsigned( + self, + any_unsigned_int_numpy_dtype, + ): + # see gh-15832 + msg = "|".join( + [ + "Trying to coerce negative values to unsigned integers", + "The elements provided in the data cannot all be casted", + ] + ) + with pytest.raises(OverflowError, match=msg): + pd.Index([-1], dtype=any_unsigned_int_numpy_dtype) + + def test_constructor_np_signed(self, any_signed_int_numpy_dtype): + # GH#47475 + scalar = np.dtype(any_signed_int_numpy_dtype).type(1) + result = pd.Index([scalar]) + expected = pd.Index([1], dtype=any_signed_int_numpy_dtype) + tm.assert_index_equal(result, expected, exact=True) + + def test_constructor_np_unsigned(self, any_unsigned_int_numpy_dtype): + # GH#47475 + scalar = np.dtype(any_unsigned_int_numpy_dtype).type(1) + result = pd.Index([scalar]) + expected = pd.Index([1], dtype=any_unsigned_int_numpy_dtype) + tm.assert_index_equal(result, expected, exact=True) + + def test_coerce_list(self): + # coerce things + arr = pd.Index([1, 2, 3, 4]) + assert isinstance(arr, pd.Index) + + # but not if explicit dtype passed + arr = pd.Index([1, 2, 3, 4], dtype=object) + assert type(arr) is pd.Index + + +class TestFloat16Index: + # float 16 indexes not supported + # GH 49535 + def test_constructor(self): + index_cls = pd.Index + dtype = np.float16 + + msg = "float16 indexes are not supported" + + # explicit construction + with pytest.raises(NotImplementedError, match=msg): + index_cls([1, 2, 3, 4, 5], dtype=dtype) + + with pytest.raises(NotImplementedError, match=msg): + index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype) + + with pytest.raises(NotImplementedError, match=msg): + index_cls([1.0, 2, 3, 4, 5], dtype=dtype) + + with pytest.raises(NotImplementedError, match=msg): + index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype) + + with pytest.raises(NotImplementedError, match=msg): + index_cls([1.0, 2, 3, 4, 5], dtype=dtype) + + with pytest.raises(NotImplementedError, match=msg): + index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype) + + # nan handling + with pytest.raises(NotImplementedError, match=msg): + index_cls([np.nan, np.nan], dtype=dtype) + + with pytest.raises(NotImplementedError, match=msg): + index_cls(np.array([np.nan]), dtype=dtype) + + +@pytest.mark.parametrize( + "box", + [list, lambda x: np.array(x, dtype=object), lambda x: pd.Index(x, dtype=object)], +) +def test_uint_index_does_not_convert_to_float64(box): + # https://github.com/pandas-dev/pandas/issues/28279 + # https://github.com/pandas-dev/pandas/issues/28023 + series = pd.Series( + [0, 1, 2, 3, 4, 5], + index=[ + 7606741985629028552, + 17876870360202815256, + 17876870360202815256, + 13106359306506049338, + 8991270399732411471, + 8991270399732411472, + ], + ) + + result = series.loc[box([7606741985629028552, 17876870360202815256])] + + expected = pd.Index( + [7606741985629028552, 17876870360202815256, 17876870360202815256], + dtype="uint64", + ) + tm.assert_index_equal(result.index, expected) + + tm.assert_equal(result, series.iloc[:3]) + + +def test_float64_index_equals(): + # https://github.com/pandas-dev/pandas/issues/35217 + float_index = pd.Index([1.0, 2, 3]) + string_index = pd.Index(["1", "2", "3"]) + + result = float_index.equals(string_index) + assert result is False + + result = string_index.equals(float_index) + assert result is False + + +def test_map_dtype_inference_unsigned_to_signed(): + # GH#44609 cases where we don't retain dtype + idx = pd.Index([1, 2, 3], dtype=np.uint64) + result = idx.map(lambda x: -x) + expected = pd.Index([-1, -2, -3], dtype=np.int64) + tm.assert_index_equal(result, expected) + + +def test_map_dtype_inference_overflows(): + # GH#44609 case where we have to upcast + idx = pd.Index(np.array([1, 2, 3], dtype=np.int8)) + result = idx.map(lambda x: x * 1000) + # TODO: we could plausibly try to infer down to int16 here + expected = pd.Index([1000, 2000, 3000], dtype=np.int64) + tm.assert_index_equal(result, expected) + + +def test_view_to_datetimelike(): + # GH#55710 + idx = pd.Index([1, 2, 3]) + res = idx.view("m8[s]") + expected = pd.TimedeltaIndex(idx.values.view("m8[s]")) + tm.assert_index_equal(res, expected) + + res2 = idx.view("m8[D]") + expected2 = idx.values.view("m8[D]") + tm.assert_numpy_array_equal(res2, expected2) + + res3 = idx.view("M8[h]") + expected3 = idx.values.view("M8[h]") + tm.assert_numpy_array_equal(res3, expected3) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_setops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..6589f694a9ff4f73b41dc014aa4ff4dce74e14a3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/numeric/test_setops.py @@ -0,0 +1,175 @@ +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest + +import pandas._testing as tm +from pandas.core.indexes.api import ( + Index, + RangeIndex, +) + + +@pytest.fixture +def index_large(): + # large values used in TestUInt64Index where no compat needed with int64/float64 + large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25] + return Index(large, dtype=np.uint64) + + +class TestSetOps: + @pytest.mark.parametrize("dtype", ["f8", "u8", "i8"]) + def test_union_non_numeric(self, dtype): + # corner case, non-numeric + index = Index(np.arange(5, dtype=dtype), dtype=dtype) + assert index.dtype == dtype + + other = Index( + [datetime(2011, 1, 1) + timedelta(i) for i in range(4)], dtype=object + ) + result = index.union(other) + expected = Index(np.concatenate((index, other))) + tm.assert_index_equal(result, expected) + + result = other.union(index) + expected = Index(np.concatenate((other, index))) + tm.assert_index_equal(result, expected) + + def test_intersection(self): + index = Index(range(5), dtype=np.int64) + + other = Index([1, 2, 3, 4, 5]) + result = index.intersection(other) + expected = Index(range(1, 5)) + tm.assert_index_equal(result, expected) + + result = other.intersection(index) + expected = Index( + np.sort(np.asarray(np.intersect1d(index.values, other.values))) + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["int64", "uint64"]) + def test_int_float_union_dtype(self, dtype): + # https://github.com/pandas-dev/pandas/issues/26778 + # [u]int | float -> float + index = Index([0, 2, 3], dtype=dtype) + other = Index([0.5, 1.5], dtype=np.float64) + expected = Index([0.0, 0.5, 1.5, 2.0, 3.0], dtype=np.float64) + result = index.union(other) + tm.assert_index_equal(result, expected) + + result = other.union(index) + tm.assert_index_equal(result, expected) + + def test_range_float_union_dtype(self): + # https://github.com/pandas-dev/pandas/issues/26778 + index = RangeIndex(start=0, stop=3) + other = Index([0.5, 1.5], dtype=np.float64) + result = index.union(other) + expected = Index([0.0, 0.5, 1, 1.5, 2.0], dtype=np.float64) + tm.assert_index_equal(result, expected) + + result = other.union(index) + tm.assert_index_equal(result, expected) + + def test_range_uint64_union_dtype(self): + # https://github.com/pandas-dev/pandas/issues/26778 + index = RangeIndex(start=0, stop=3) + other = Index([0, 10], dtype=np.uint64) + result = index.union(other) + expected = Index([0, 1, 2, 10], dtype=object) + tm.assert_index_equal(result, expected) + + result = other.union(index) + tm.assert_index_equal(result, expected) + + def test_float64_index_difference(self): + # https://github.com/pandas-dev/pandas/issues/35217 + float_index = Index([1.0, 2, 3]) + string_index = Index(["1", "2", "3"]) + + result = float_index.difference(string_index) + tm.assert_index_equal(result, float_index) + + result = string_index.difference(float_index) + tm.assert_index_equal(result, string_index) + + def test_intersection_uint64_outside_int64_range(self): + index_large = Index( + [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25], + dtype=np.uint64, + ) + other = Index([2**63, 2**63 + 5, 2**63 + 10, 2**63 + 15, 2**63 + 20]) + result = index_large.intersection(other) + expected = Index(np.sort(np.intersect1d(index_large.values, other.values))) + tm.assert_index_equal(result, expected) + + result = other.intersection(index_large) + expected = Index( + np.sort(np.asarray(np.intersect1d(index_large.values, other.values))) + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "index2_name,keeps_name", + [ + ("index", True), + ("other", False), + ], + ) + def test_intersection_monotonic(self, index2_name, keeps_name, sort): + index2 = Index([4, 7, 6, 5, 3], name=index2_name) + index1 = Index([5, 3, 2, 4, 1], name="index") + expected = Index([5, 3, 4]) + + if keeps_name: + expected.name = "index" + + result = index1.intersection(index2, sort=sort) + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + def test_symmetric_difference(self, sort): + # smoke + index1 = Index([5, 2, 3, 4], name="index1") + index2 = Index([2, 3, 4, 1]) + result = index1.symmetric_difference(index2, sort=sort) + expected = Index([5, 1]) + if sort is not None: + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result, expected.sort_values()) + assert result.name is None + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + +class TestSetOpsSort: + @pytest.mark.parametrize("slice_", [slice(None), slice(0)]) + def test_union_sort_other_special(self, slice_): + # https://github.com/pandas-dev/pandas/issues/24959 + + idx = Index([1, 0, 2]) + # default, sort=None + other = idx[slice_] + tm.assert_index_equal(idx.union(other), idx) + tm.assert_index_equal(other.union(idx), idx) + + # sort=False + tm.assert_index_equal(idx.union(other, sort=False), idx) + + @pytest.mark.parametrize("slice_", [slice(None), slice(0)]) + def test_union_sort_special_true(self, slice_): + idx = Index([1, 0, 2]) + # default, sort=None + other = idx[slice_] + + result = idx.union(other, sort=True) + expected = Index([0, 1, 2]) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/object/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/object/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/object/test_astype.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/object/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..b995e2690719e25b1691d24c55d66e4c4ed78f13 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/object/test_astype.py @@ -0,0 +1,12 @@ +import pytest + +import pandas as pd + + +def test_astype_invalid_nas_to_tdt64_raises(): + # GH#45722 don't cast np.datetime64 NaTs to timedelta64 NaT + idx = pd.Index([pd.NaT.asm8] * 2, dtype=object) + + msg = r"Invalid type for timedelta scalar: " + with pytest.raises(TypeError, match=msg): + idx.astype("m8[ns]") diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/object/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/object/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..f83c283bfacb4e885be4afcc4647d26bdaf8e44f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/object/test_indexing.py @@ -0,0 +1,224 @@ +from decimal import Decimal + +import numpy as np +import pytest + +from pandas._libs.missing import is_matching_na +from pandas.compat.numpy import np_version_gt2_2 + +import pandas as pd +import pandas._testing as tm + + +class TestGetIndexer: + @pytest.mark.parametrize( + "method,expected", + [ + ("pad", [-1, 0, 1, 1]), + ("backfill", [0, 0, 1, -1]), + ], + ) + def test_get_indexer_strings(self, method, expected): + expected = np.array(expected, dtype=np.intp) + index = pd.Index(["b", "c"], dtype=object) + actual = index.get_indexer(["a", "b", "c", "d"], method=method) + + tm.assert_numpy_array_equal(actual, expected) + + def test_get_indexer_strings_raises(self): + index = pd.Index(["b", "c"], dtype=object) + + # object-dtype string subtraction goes through the Python operator + msg = r"unsupported operand type\(s\) for -: 'str' and 'str'" + with pytest.raises(TypeError, match=msg): + index.get_indexer(["a", "b", "c", "d"], method="nearest") + + with pytest.raises(TypeError, match=msg): + index.get_indexer(["a", "b", "c", "d"], method="pad", tolerance=2) + + with pytest.raises(TypeError, match=msg): + index.get_indexer( + ["a", "b", "c", "d"], method="pad", tolerance=[2, 2, 2, 2] + ) + + def test_get_indexer_with_NA_values( + self, unique_nulls_fixture, unique_nulls_fixture2 + ): + # GH#22332 + # check pairwise, that no pair of na values + # is mangled + if unique_nulls_fixture is unique_nulls_fixture2: + return # skip it, values are not unique + arr = np.array([unique_nulls_fixture, unique_nulls_fixture2], dtype=object) + index = pd.Index(arr, dtype=object) + result = index.get_indexer( + pd.Index( + [unique_nulls_fixture, unique_nulls_fixture2, "Unknown"], dtype=object + ) + ) + expected = np.array([0, 1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_infer_string_missing_values(self): + # ensure the passed list is not cast to string but to object so that + # the None value is matched in the index + # https://github.com/pandas-dev/pandas/issues/55834 + idx = pd.Index(["a", "b", None], dtype="object") + result = idx.get_indexer([None, "x"]) + expected = np.array([2, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +class TestGetIndexerNonUnique: + def test_get_indexer_non_unique_nas(self, nulls_fixture): + # even though this isn't non-unique, this should still work + index = pd.Index(["a", "b", nulls_fixture], dtype=object) + indexer, missing = index.get_indexer_non_unique([nulls_fixture]) + + expected_indexer = np.array([2], dtype=np.intp) + expected_missing = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected_indexer) + tm.assert_numpy_array_equal(missing, expected_missing) + + # actually non-unique + index = pd.Index(["a", nulls_fixture, "b", nulls_fixture], dtype=object) + indexer, missing = index.get_indexer_non_unique([nulls_fixture]) + + expected_indexer = np.array([1, 3], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected_indexer) + tm.assert_numpy_array_equal(missing, expected_missing) + + # matching-but-not-identical nans + if is_matching_na(nulls_fixture, float("NaN")): + index = pd.Index(["a", float("NaN"), "b", float("NaN")], dtype=object) + match_but_not_identical = True + elif is_matching_na(nulls_fixture, Decimal("NaN")): + index = pd.Index(["a", Decimal("NaN"), "b", Decimal("NaN")], dtype=object) + match_but_not_identical = True + else: + match_but_not_identical = False + + if match_but_not_identical: + indexer, missing = index.get_indexer_non_unique([nulls_fixture]) + + expected_indexer = np.array([1, 3], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected_indexer) + tm.assert_numpy_array_equal(missing, expected_missing) + + def test_get_indexer_non_unique_np_nats(self, np_nat_fixture, np_nat_fixture2): + expected_missing = np.array([], dtype=np.intp) + # matching-but-not-identical nats + if is_matching_na(np_nat_fixture, np_nat_fixture2): + # ensure nats are different objects + index = pd.Index( + np.array( + ["2021-10-02", np_nat_fixture.copy(), np_nat_fixture2.copy()], + dtype=object, + ), + dtype=object, + ) + # pass as index to prevent target from being casted to DatetimeIndex + indexer, missing = index.get_indexer_non_unique( + pd.Index([np_nat_fixture], dtype=object) + ) + expected_indexer = np.array([1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected_indexer) + tm.assert_numpy_array_equal(missing, expected_missing) + # dt64nat vs td64nat + else: + try: + np_nat_fixture == np_nat_fixture2 + except (TypeError, OverflowError): + # Numpy will raise on uncomparable types, like + # np.datetime64('NaT', 'Y') and np.datetime64('NaT', 'ps') + # https://github.com/numpy/numpy/issues/22762 + return + index = pd.Index( + np.array( + [ + "2021-10-02", + np_nat_fixture, + np_nat_fixture2, + np_nat_fixture, + np_nat_fixture2, + ], + dtype=object, + ), + dtype=object, + ) + # pass as index to prevent target from being casted to DatetimeIndex + indexer, missing = index.get_indexer_non_unique( + pd.Index([np_nat_fixture], dtype=object) + ) + expected_indexer = np.array([1, 3], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected_indexer) + tm.assert_numpy_array_equal(missing, expected_missing) + + +class TestMixedResolutionDatetime64: + # GH#50690 - object-dtype Index with mixed-resolution datetime64 values + # should respect the invariant x == y => hash(x) == hash(y) + + _xfail_np_hash = pytest.mark.xfail( + not np_version_gt2_2, + reason="numpy < 2.2 violates hash invariant for mixed-resolution datetime64", + ) + + @pytest.fixture + def dt_ms(self): + return np.datetime64(1, "ms") + + @pytest.fixture + def dt_us(self): + return np.datetime64(1000, "us") + + @_xfail_np_hash + def test_contains(self, dt_ms, dt_us): + # GH#50690 + left = pd.Index([dt_ms], dtype=object) + right = pd.Index([dt_us], dtype=object) + + assert dt_us in left + assert dt_ms in right + + @_xfail_np_hash + def test_get_loc(self, dt_ms, dt_us): + # GH#50690 + left = pd.Index([dt_ms], dtype=object) + right = pd.Index([dt_us], dtype=object) + + assert left.get_loc(dt_us) == 0 + assert right.get_loc(dt_ms) == 0 + + def test_get_indexer_monotonic(self, dt_ms, dt_us): + # GH#50690 - monotonic case uses binary search, not hashtable + left = pd.Index([dt_ms], dtype=object) + right = pd.Index([dt_us], dtype=object) + + result = left.get_indexer(right) + expected = np.array([0], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @_xfail_np_hash + def test_get_indexer_non_monotonic(self, dt_ms, dt_us): + # GH#50690 - non-monotonic case uses hashtable; this is where + # the hash invariant violation caused incorrect results + sec = np.datetime64("9999-01-01", "s") + day = np.datetime64("2016-01-01", "D") + idx = pd.Index([dt_ms, sec, day], dtype=object) + + result = idx.get_indexer(pd.Index([dt_us], dtype=object)) + expected = np.array([0], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @_xfail_np_hash + def test_get_indexer_non_unique(self, dt_ms, dt_us): + # GH#50690 + idx = pd.Index([dt_ms, "foo", dt_ms], dtype=object) + + indexer, missing = idx.get_indexer_non_unique(pd.Index([dt_us], dtype=object)) + + expected_indexer = np.array([0, 2], dtype=np.intp) + expected_missing = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected_indexer) + tm.assert_numpy_array_equal(missing, expected_missing) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_asfreq.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_asfreq.py new file mode 100644 index 0000000000000000000000000000000000000000..15ada5f8b00a454aef1c528fe53dfcbcdce026bd --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_asfreq.py @@ -0,0 +1,194 @@ +import re + +import pytest + +import pandas as pd +import pandas._testing as tm + +from pandas.tseries import offsets + + +class TestPeriodIndex: + def test_asfreq(self): + pi1 = pd.period_range(freq="Y", start="1/1/2001", end="1/1/2001") + pi2 = pd.period_range(freq="Q", start="1/1/2001", end="1/1/2001") + pi3 = pd.period_range(freq="M", start="1/1/2001", end="1/1/2001") + pi4 = pd.period_range(freq="D", start="1/1/2001", end="1/1/2001") + pi5 = pd.period_range(freq="h", start="1/1/2001", end="1/1/2001 00:00") + pi6 = pd.period_range(freq="Min", start="1/1/2001", end="1/1/2001 00:00") + pi7 = pd.period_range(freq="s", start="1/1/2001", end="1/1/2001 00:00:00") + + assert pi1.asfreq("Q", "s") == pi2 + assert pi1.asfreq("Q", "s") == pi2 + assert pi1.asfreq("M", "start") == pi3 + assert pi1.asfreq("D", "StarT") == pi4 + assert pi1.asfreq("h", "beGIN") == pi5 + assert pi1.asfreq("Min", "s") == pi6 + assert pi1.asfreq("s", "s") == pi7 + + assert pi2.asfreq("Y", "s") == pi1 + assert pi2.asfreq("M", "s") == pi3 + assert pi2.asfreq("D", "s") == pi4 + assert pi2.asfreq("h", "s") == pi5 + assert pi2.asfreq("Min", "s") == pi6 + assert pi2.asfreq("s", "s") == pi7 + + assert pi3.asfreq("Y", "s") == pi1 + assert pi3.asfreq("Q", "s") == pi2 + assert pi3.asfreq("D", "s") == pi4 + assert pi3.asfreq("h", "s") == pi5 + assert pi3.asfreq("Min", "s") == pi6 + assert pi3.asfreq("s", "s") == pi7 + + assert pi4.asfreq("Y", "s") == pi1 + assert pi4.asfreq("Q", "s") == pi2 + assert pi4.asfreq("M", "s") == pi3 + assert pi4.asfreq("h", "s") == pi5 + assert pi4.asfreq("Min", "s") == pi6 + assert pi4.asfreq("s", "s") == pi7 + + assert pi5.asfreq("Y", "s") == pi1 + assert pi5.asfreq("Q", "s") == pi2 + assert pi5.asfreq("M", "s") == pi3 + assert pi5.asfreq("D", "s") == pi4 + assert pi5.asfreq("Min", "s") == pi6 + assert pi5.asfreq("s", "s") == pi7 + + assert pi6.asfreq("Y", "s") == pi1 + assert pi6.asfreq("Q", "s") == pi2 + assert pi6.asfreq("M", "s") == pi3 + assert pi6.asfreq("D", "s") == pi4 + assert pi6.asfreq("h", "s") == pi5 + assert pi6.asfreq("s", "s") == pi7 + + assert pi7.asfreq("Y", "s") == pi1 + assert pi7.asfreq("Q", "s") == pi2 + assert pi7.asfreq("M", "s") == pi3 + assert pi7.asfreq("D", "s") == pi4 + assert pi7.asfreq("h", "s") == pi5 + assert pi7.asfreq("Min", "s") == pi6 + + msg = "how must be one of 'start', 'end', 's', 'e', got 'foo'" + with pytest.raises(ValueError, match=msg): + pi7.asfreq("T", "foo") + result1 = pi1.asfreq("3M") + result2 = pi1.asfreq("M") + expected = pd.period_range(freq="M", start="2001-12", end="2001-12") + tm.assert_numpy_array_equal(result1.asi8, expected.asi8) + assert result1.freqstr == "3M" + tm.assert_numpy_array_equal(result2.asi8, expected.asi8) + assert result2.freqstr == "M" + + def test_asfreq_nat(self): + idx = pd.PeriodIndex(["2011-01", "2011-02", "NaT", "2011-04"], freq="M") + result = idx.asfreq(freq="Q") + expected = pd.PeriodIndex(["2011Q1", "2011Q1", "NaT", "2011Q2"], freq="Q") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("freq", ["D", "3D"]) + def test_asfreq_mult_pi(self, freq): + pi = pd.PeriodIndex(["2001-01", "2001-02", "NaT", "2001-03"], freq="2M") + + result = pi.asfreq(freq) + exp = pd.PeriodIndex( + ["2001-02-28", "2001-03-31", "NaT", "2001-04-30"], freq=freq + ) + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + result = pi.asfreq(freq, how="S") + exp = pd.PeriodIndex( + ["2001-01-01", "2001-02-01", "NaT", "2001-03-01"], freq=freq + ) + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + def test_asfreq_combined_pi(self): + pi = pd.PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="h") + exp = pd.PeriodIndex( + ["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="25h" + ) + for freq, how in zip(["1D1h", "1h1D"], ["S", "E"], strict=True): + result = pi.asfreq(freq, how=how) + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + for freq in ["1D1h", "1h1D"]: + pi = pd.PeriodIndex( + ["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq=freq + ) + result = pi.asfreq("h") + exp = pd.PeriodIndex( + ["2001-01-02 00:00", "2001-01-03 02:00", "NaT"], freq="h" + ) + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + pi = pd.PeriodIndex( + ["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq=freq + ) + result = pi.asfreq("h", how="S") + exp = pd.PeriodIndex( + ["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="h" + ) + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + def test_astype_asfreq(self): + pi1 = pd.PeriodIndex(["2011-01-01", "2011-02-01", "2011-03-01"], freq="D") + exp = pd.PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M") + tm.assert_index_equal(pi1.asfreq("M"), exp) + tm.assert_index_equal(pi1.astype("period[M]"), exp) + + exp = pd.PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="3M") + tm.assert_index_equal(pi1.asfreq("3M"), exp) + tm.assert_index_equal(pi1.astype("period[3M]"), exp) + + def test_asfreq_with_different_n(self): + ser = pd.Series([1, 2], index=pd.PeriodIndex(["2020-01", "2020-03"], freq="2M")) + result = ser.asfreq("M") + + excepted = pd.Series( + [1, 2], index=pd.PeriodIndex(["2020-02", "2020-04"], freq="M") + ) + tm.assert_series_equal(result, excepted) + + @pytest.mark.parametrize( + "freq", + [ + "2BMS", + "2YS-MAR", + "2bh", + offsets.MonthBegin(2), + offsets.BusinessMonthEnd(2), + ], + ) + def test_pi_asfreq_not_supported_frequency(self, freq): + # GH#55785, GH#56945 + msg = "|".join( + [ + f"Invalid frequency: {freq}", + re.escape(f"{freq} is not supported as period frequency"), + "bh is not supported as period frequency", + ] + ) + + pi = pd.PeriodIndex(["2020-01-01", "2021-01-01"], freq="M") + with pytest.raises(ValueError, match=msg): + pi.asfreq(freq=freq) + + @pytest.mark.parametrize( + "freq", + [ + "2BME", + "2YE-MAR", + "2QE", + ], + ) + def test_pi_asfreq_invalid_frequency(self, freq): + # GH#55785 + msg = f"Invalid frequency: {freq}" + + pi = pd.PeriodIndex(["2020-01-01", "2021-01-01"], freq="M") + with pytest.raises(ValueError, match=msg): + pi.asfreq(freq=freq) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_astype.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..f832adacefd9d5ef6163c729ccf9e5a10bc84de7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_astype.py @@ -0,0 +1,153 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestPeriodIndexAsType: + @pytest.mark.parametrize("dtype", [float, "timedelta64", "timedelta64[ns]"]) + def test_astype_raises(self, dtype): + # GH#13149, GH#13209 + idx = pd.PeriodIndex(["2016-05-16", "NaT", pd.NaT, np.nan], freq="D") + msg = "Cannot cast PeriodIndex to dtype" + with pytest.raises(TypeError, match=msg): + idx.astype(dtype) + + def test_astype_conversion(self, using_infer_string): + # GH#13149, GH#13209 + idx = pd.PeriodIndex( + ["2016-05-16", "NaT", pd.NaT, np.nan], freq="D", name="idx" + ) + + result = idx.astype(object) + expected = pd.Index( + [pd.Period("2016-05-16", freq="D")] + [pd.Period(pd.NaT, freq="D")] * 3, + dtype="object", + name="idx", + ) + tm.assert_index_equal(result, expected) + + result = idx.astype(np.int64) + expected = pd.Index( + [16937] + [-9223372036854775808] * 3, dtype=np.int64, name="idx" + ) + tm.assert_index_equal(result, expected) + + result = idx.astype(str) + if using_infer_string: + expected = pd.Index( + [str(x) if x is not pd.NaT else None for x in idx], + name="idx", + dtype="str", + ) + else: + expected = pd.Index([str(x) for x in idx], name="idx", dtype=object) + tm.assert_index_equal(result, expected) + + idx = pd.period_range("1990", "2009", freq="Y", name="idx") + result = idx.astype("i8") + tm.assert_index_equal(result, pd.Index(idx.asi8, name="idx")) + tm.assert_numpy_array_equal(result.values, idx.asi8) + + def test_astype_uint(self): + arr = pd.period_range("2000", periods=2, name="idx") + + with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"): + arr.astype("uint64") + with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"): + arr.astype("uint32") + + def test_astype_object(self): + idx = pd.PeriodIndex([], freq="M") + + exp = np.array([], dtype=object) + tm.assert_numpy_array_equal(idx.astype(object).values, exp) + tm.assert_numpy_array_equal(idx._mpl_repr(), idx.asi8) + + idx = pd.PeriodIndex(["2011-01", pd.NaT], freq="M") + + exp = np.array([pd.Period("2011-01", freq="M"), pd.NaT], dtype=object) + tm.assert_numpy_array_equal(idx.astype(object).values, exp) + tm.assert_numpy_array_equal(idx._mpl_repr(), idx.asi8) + + exp = np.array([pd.Period("2011-01-01", freq="D"), pd.NaT], dtype=object) + idx = pd.PeriodIndex(["2011-01-01", pd.NaT], freq="D") + tm.assert_numpy_array_equal(idx.astype(object).values, exp) + tm.assert_numpy_array_equal(idx._mpl_repr(), idx.asi8) + + # TODO: de-duplicate this version (from test_ops) with the one above + # (from test_period) + def test_astype_object2(self): + idx = pd.period_range(start="2013-01-01", periods=4, freq="M", name="idx") + expected_list = [ + pd.Period("2013-01-31", freq="M"), + pd.Period("2013-02-28", freq="M"), + pd.Period("2013-03-31", freq="M"), + pd.Period("2013-04-30", freq="M"), + ] + expected = pd.Index(expected_list, dtype=object, name="idx") + result = idx.astype(object) + assert isinstance(result, pd.Index) + assert result.dtype == object + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert idx.tolist() == expected_list + + idx = pd.PeriodIndex( + ["2013-01-01", "2013-01-02", "NaT", "2013-01-04"], freq="D", name="idx" + ) + expected_list = [ + pd.Period("2013-01-01", freq="D"), + pd.Period("2013-01-02", freq="D"), + pd.Period("NaT", freq="D"), + pd.Period("2013-01-04", freq="D"), + ] + expected = pd.Index(expected_list, dtype=object, name="idx") + result = idx.astype(object) + assert isinstance(result, pd.Index) + assert result.dtype == object + tm.assert_index_equal(result, expected) + for i in [0, 1, 3]: + assert result[i] == expected[i] + assert result[2] is pd.NaT + assert result.name == expected.name + + result_list = idx.tolist() + for i in [0, 1, 3]: + assert result_list[i] == expected_list[i] + assert result_list[2] is pd.NaT + + def test_astype_category(self): + obj = pd.period_range("2000", periods=2, name="idx") + result = obj.astype("category") + expected = pd.CategoricalIndex( + [pd.Period("2000-01-01", freq="D"), pd.Period("2000-01-02", freq="D")], + name="idx", + ) + tm.assert_index_equal(result, expected) + + result = obj._data.astype("category") + expected = expected.values + tm.assert_categorical_equal(result, expected) + + def test_astype_array_fallback(self): + obj = pd.period_range("2000", periods=2, name="idx") + result = obj.astype(bool) + expected = pd.Index(np.array([True, True]), name="idx") + tm.assert_index_equal(result, expected) + + result = obj._data.astype(bool) + expected = np.array([True, True]) + tm.assert_numpy_array_equal(result, expected) + + def test_period_astype_to_timestamp(self, unit): + # GH#55958 + pi = pd.PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M") + + exp = pd.DatetimeIndex( + ["2011-01-01", "2011-02-01", "2011-03-01"], tz="US/Eastern" + ).as_unit(unit) + res = pi.astype(f"datetime64[{unit}, US/Eastern]") + tm.assert_index_equal(res, exp) + assert res.freq == exp.freq diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_factorize.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_factorize.py new file mode 100644 index 0000000000000000000000000000000000000000..afd2947a95effaaf4b8db479850ce4621c96f1a9 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_factorize.py @@ -0,0 +1,41 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestFactorize: + def test_factorize_period(self): + idx1 = pd.PeriodIndex( + ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"], + freq="M", + ) + + exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) + exp_idx = pd.PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M") + + arr, idx = idx1.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + + arr, idx = idx1.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + + def test_factorize_period_nonmonotonic(self): + idx2 = pd.PeriodIndex( + ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"], + freq="M", + ) + exp_idx = pd.PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M") + + exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp) + arr, idx = idx2.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + + exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp) + exp_idx = pd.PeriodIndex(["2014-03", "2014-02", "2014-01"], freq="M") + arr, idx = idx2.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_fillna.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_fillna.py new file mode 100644 index 0000000000000000000000000000000000000000..fb9ef530a7c1a7c4d17497037bb4052652d783d1 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_fillna.py @@ -0,0 +1,42 @@ +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestFillNA: + def test_fillna_period(self): + # GH#11343 + idx = pd.PeriodIndex(["2011-01-01 09:00", pd.NaT, "2011-01-01 11:00"], freq="h") + + exp = pd.PeriodIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], freq="h" + ) + result = idx.fillna(pd.Period("2011-01-01 10:00", freq="h")) + tm.assert_index_equal(result, exp) + + exp = pd.Index( + [ + pd.Period("2011-01-01 09:00", freq="h"), + "x", + pd.Period("2011-01-01 11:00", freq="h"), + ], + dtype=object, + ) + # GH#45153 filling with incompatible value is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = idx.fillna("x") + tm.assert_index_equal(result, exp) + + exp = pd.Index( + [ + pd.Period("2011-01-01 09:00", freq="h"), + pd.Period("2011-01-01", freq="D"), + pd.Period("2011-01-01 11:00", freq="h"), + ], + dtype=object, + ) + # GH#45153 filling with incompatible value is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = idx.fillna(pd.Period("2011-01-01", freq="D")) + tm.assert_index_equal(result, exp) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_insert.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_insert.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2157c506a629edd3d81252e39b4c6858aa762e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_insert.py @@ -0,0 +1,16 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestInsert: + @pytest.mark.parametrize("na", [np.nan, pd.NaT, None]) + def test_insert(self, na): + # GH#18295 (test missing) + expected = pd.PeriodIndex( + ["2017Q1", pd.NaT, "2017Q2", "2017Q3", "2017Q4"], freq="Q" + ) + result = pd.period_range("2017Q1", periods=4, freq="Q").insert(1, na) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_is_full.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_is_full.py new file mode 100644 index 0000000000000000000000000000000000000000..9c19ab371806f79fd2bf055e8800909212ede5d5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_is_full.py @@ -0,0 +1,32 @@ +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + +msg = "PeriodIndex.is_full is deprecated" + + +@pytest.mark.parametrize( + "years, expected", + [ + (["2005", "2007", "2009"], False), + (["2005", "2006", "2007"], True), + (["2005", "2005", "2007"], False), + (["2005", "2005", "2006"], True), + ([], True), + ], +) +def test_is_full(years, expected): + index = pd.PeriodIndex(years, freq="Y") + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = index.is_full + assert result is expected + + +def test_is_full_not_monotonic(): + index = pd.PeriodIndex(["2006", "2005", "2005"], freq="Y") + with tm.assert_produces_warning(Pandas4Warning, match=msg): + with pytest.raises(ValueError, match="Index is not monotonic"): + index.is_full diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_repeat.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_repeat.py new file mode 100644 index 0000000000000000000000000000000000000000..7f9741b3674c4e4f3c87a9dee9b73c7a3e9d7c0c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_repeat.py @@ -0,0 +1,23 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestRepeat: + @pytest.mark.parametrize("use_numpy", [True, False]) + @pytest.mark.parametrize( + "index", + [ + pd.period_range("2000-01-01", periods=3, freq="D"), + pd.period_range("2001-01-01", periods=3, freq="2D"), + pd.PeriodIndex(["2001-01", "NaT", "2003-01"], freq="M"), + ], + ) + def test_repeat_freqstr(self, index, use_numpy): + # GH#10183 + expected = pd.PeriodIndex([per for per in index for _ in range(3)]) + result = np.repeat(index, 3) if use_numpy else index.repeat(3) + tm.assert_index_equal(result, expected) + assert result.freqstr == index.freqstr diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_shift.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc98d0195ca6dd386e935c12539214a93150fec --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_shift.py @@ -0,0 +1,119 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestPeriodIndexShift: + # --------------------------------------------------------------- + # PeriodIndex.shift is used by __add__ and __sub__ + + def test_pi_shift_ndarray(self): + idx = pd.PeriodIndex( + ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx" + ) + result = idx.shift(np.array([1, 2, 3, 4])) + expected = pd.PeriodIndex( + ["2011-02", "2011-04", "NaT", "2011-08"], freq="M", name="idx" + ) + tm.assert_index_equal(result, expected) + + result = idx.shift(np.array([1, -2, 3, -4])) + expected = pd.PeriodIndex( + ["2011-02", "2010-12", "NaT", "2010-12"], freq="M", name="idx" + ) + tm.assert_index_equal(result, expected) + + def test_shift(self): + pi1 = pd.period_range(freq="Y", start="1/1/2001", end="12/1/2009") + pi2 = pd.period_range(freq="Y", start="1/1/2002", end="12/1/2010") + + tm.assert_index_equal(pi1.shift(0), pi1) + + assert len(pi1) == len(pi2) + tm.assert_index_equal(pi1.shift(1), pi2) + + pi1 = pd.period_range(freq="Y", start="1/1/2001", end="12/1/2009") + pi2 = pd.period_range(freq="Y", start="1/1/2000", end="12/1/2008") + assert len(pi1) == len(pi2) + tm.assert_index_equal(pi1.shift(-1), pi2) + + pi1 = pd.period_range(freq="M", start="1/1/2001", end="12/1/2009") + pi2 = pd.period_range(freq="M", start="2/1/2001", end="1/1/2010") + assert len(pi1) == len(pi2) + tm.assert_index_equal(pi1.shift(1), pi2) + + pi1 = pd.period_range(freq="M", start="1/1/2001", end="12/1/2009") + pi2 = pd.period_range(freq="M", start="12/1/2000", end="11/1/2009") + assert len(pi1) == len(pi2) + tm.assert_index_equal(pi1.shift(-1), pi2) + + pi1 = pd.period_range(freq="D", start="1/1/2001", end="12/1/2009") + pi2 = pd.period_range(freq="D", start="1/2/2001", end="12/2/2009") + assert len(pi1) == len(pi2) + tm.assert_index_equal(pi1.shift(1), pi2) + + pi1 = pd.period_range(freq="D", start="1/1/2001", end="12/1/2009") + pi2 = pd.period_range(freq="D", start="12/31/2000", end="11/30/2009") + assert len(pi1) == len(pi2) + tm.assert_index_equal(pi1.shift(-1), pi2) + + def test_shift_corner_cases(self): + # GH#9903 + idx = pd.PeriodIndex([], name="xxx", freq="h") + + msg = "`freq` argument is not supported for PeriodIndex.shift" + with pytest.raises(TypeError, match=msg): + # period shift doesn't accept freq + idx.shift(1, freq="h") + + tm.assert_index_equal(idx.shift(0), idx) + tm.assert_index_equal(idx.shift(3), idx) + + idx = pd.PeriodIndex( + ["2011-01-01 10:00", "2011-01-01 11:00", "2011-01-01 12:00"], + name="xxx", + freq="h", + ) + tm.assert_index_equal(idx.shift(0), idx) + exp = pd.PeriodIndex( + ["2011-01-01 13:00", "2011-01-01 14:00", "2011-01-01 15:00"], + name="xxx", + freq="h", + ) + tm.assert_index_equal(idx.shift(3), exp) + exp = pd.PeriodIndex( + ["2011-01-01 07:00", "2011-01-01 08:00", "2011-01-01 09:00"], + name="xxx", + freq="h", + ) + tm.assert_index_equal(idx.shift(-3), exp) + + def test_shift_nat(self): + idx = pd.PeriodIndex( + ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx" + ) + result = idx.shift(1) + expected = pd.PeriodIndex( + ["2011-02", "2011-03", "NaT", "2011-05"], freq="M", name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + + def test_shift_gh8083(self): + # test shift for PeriodIndex + # GH#8083 + drange = pd.period_range("20130101", periods=5, freq="D") + result = drange.shift(1) + expected = pd.PeriodIndex( + ["2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05", "2013-01-06"], + freq="D", + ) + tm.assert_index_equal(result, expected) + + def test_shift_periods(self): + # GH #22458 : argument 'n' was deprecated in favor of 'periods' + idx = pd.period_range(freq="Y", start="1/1/2001", end="12/1/2009") + tm.assert_index_equal(idx.shift(periods=0), idx) + tm.assert_index_equal(idx.shift(0), idx) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_to_timestamp.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_to_timestamp.py new file mode 100644 index 0000000000000000000000000000000000000000..00e959307ac935aa871a86248b15814d71140da0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/methods/test_to_timestamp.py @@ -0,0 +1,197 @@ +from datetime import datetime + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestToTimestamp: + def test_to_timestamp_non_contiguous(self): + # GH#44100 + dti = pd.date_range("2021-10-18", periods=9, freq="D", unit="ns") + pi = dti.to_period() + + result = pi[::2].to_timestamp() + expected = dti[::2].as_unit("us") + tm.assert_index_equal(result, expected) + + result = pi._data[::2].to_timestamp() + expected = dti._data[::2].as_unit("us") + tm.assert_datetime_array_equal(result, expected) + + result = pi[::-1].to_timestamp() + expected = dti[::-1].as_unit("us") + tm.assert_index_equal(result, expected) + + result = pi._data[::-1].to_timestamp() + expected = dti._data[::-1].as_unit("us") + tm.assert_datetime_array_equal(result, expected) + + result = pi[::2][::-1].to_timestamp() + expected = dti[::2][::-1].as_unit("us") + tm.assert_index_equal(result, expected) + + result = pi._data[::2][::-1].to_timestamp() + expected = dti._data[::2][::-1].as_unit("us") + tm.assert_datetime_array_equal(result, expected) + + def test_to_timestamp_freq(self): + idx = pd.period_range("2017", periods=12, freq="Y-DEC") + result = idx.to_timestamp() + expected = pd.date_range("2017", periods=12, freq="YS-JAN") + tm.assert_index_equal(result, expected) + + def test_to_timestamp_pi_nat(self): + # GH#7228 + index = pd.PeriodIndex(["NaT", "2011-01", "2011-02"], freq="M", name="idx") + + result = index.to_timestamp("D") + expected = pd.DatetimeIndex( + [pd.NaT, datetime(2011, 1, 1), datetime(2011, 2, 1)], + dtype="M8[us]", + name="idx", + ) + tm.assert_index_equal(result, expected) + assert result.name == "idx" + + result2 = result.to_period(freq="M") + tm.assert_index_equal(result2, index) + assert result2.name == "idx" + + result3 = result.to_period(freq="3M") + exp = pd.PeriodIndex(["NaT", "2011-01", "2011-02"], freq="3M", name="idx") + tm.assert_index_equal(result3, exp) + assert result3.freqstr == "3M" + + msg = "Frequency must be positive, because it represents span: -2Y" + with pytest.raises(ValueError, match=msg): + result.to_period(freq="-2Y") + + def test_to_timestamp_preserve_name(self): + index = pd.period_range(freq="Y", start="1/1/2001", end="12/1/2009", name="foo") + assert index.name == "foo" + + conv = index.to_timestamp("D") + assert conv.name == "foo" + + def test_to_timestamp_quarterly_bug(self): + years = np.arange(1960, 2000).repeat(4) + quarters = np.tile(list(range(1, 5)), 40) + + pindex = pd.PeriodIndex.from_fields(year=years, quarter=quarters) + + stamps = pindex.to_timestamp("D", "end") + expected = pd.DatetimeIndex([x.to_timestamp("D", "end") for x in pindex]) + tm.assert_index_equal(stamps, expected) + assert stamps.freq == expected.freq + + def test_to_timestamp_pi_mult(self): + idx = pd.PeriodIndex(["2011-01", "NaT", "2011-02"], freq="2M", name="idx") + + result = idx.to_timestamp() + expected = pd.DatetimeIndex( + ["2011-01-01", "NaT", "2011-02-01"], dtype="M8[us]", name="idx" + ) + tm.assert_index_equal(result, expected) + + result = idx.to_timestamp(how="E") + expected = pd.DatetimeIndex( + ["2011-02-28", "NaT", "2011-03-31"], dtype="M8[us]", name="idx" + ) + expected = expected + pd.Timedelta(1, "D") - pd.Timedelta(1, "us") + tm.assert_index_equal(result, expected) + + def test_to_timestamp_pi_combined(self): + idx = pd.period_range(start="2011", periods=2, freq="1D1h", name="idx") + + result = idx.to_timestamp() + expected = pd.DatetimeIndex( + ["2011-01-01 00:00", "2011-01-02 01:00"], dtype="M8[us]", name="idx" + ) + tm.assert_index_equal(result, expected) + + result = idx.to_timestamp(how="E") + expected = pd.DatetimeIndex( + ["2011-01-02 00:59:59", "2011-01-03 01:59:59"], name="idx", dtype="M8[us]" + ) + expected = expected + pd.Timedelta(1, "s") - pd.Timedelta(1, "us") + tm.assert_index_equal(result, expected) + + result = idx.to_timestamp(how="E", freq="h") + expected = pd.DatetimeIndex( + ["2011-01-02 00:00", "2011-01-03 01:00"], dtype="M8[us]", name="idx" + ) + expected = expected + pd.Timedelta(1, "h") - pd.Timedelta(1, "us") + tm.assert_index_equal(result, expected) + + def test_to_timestamp_1703(self): + index = pd.period_range("1/1/2012", periods=4, freq="D") + + result = index.to_timestamp() + assert result[0] == pd.Timestamp("1/1/2012") + + +def test_ms_to_timestamp_error_message(): + # https://github.com/pandas-dev/pandas/issues/58974#issuecomment-2164265446 + ix = pd.period_range("2000", periods=3, freq="M") + with pytest.raises(ValueError, match="for Period, please use 'M' instead of 'MS'"): + ix.to_timestamp("MS") + + +@pytest.mark.parametrize("freq", ["ns", "1ns"]) +def test_to_timestamp_nanosecond_target(freq): + # GH#63760 a target freq that normalizes to nanoseconds must give a + # nanosecond-unit result rather than misinterpreting the ordinal + pi = pd.period_range("2020-01-01", periods=3, freq="D") + result = pi.to_timestamp(freq) + expected = pd.date_range("2020-01-01", periods=3, freq="D", unit="ns") + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("freq", ["D", "s", "us"]) +def test_to_timestamp_from_nanosecond_period(freq): + # GH#63760 converting a nanosecond PeriodIndex with a coarser target must + # yield a microsecond DatetimeIndex, not reinterpret the value as ns + pi = pd.period_range("2020-01-01", periods=3, freq="ns") + result = pi.to_timestamp(freq) + expected = pd.DatetimeIndex(["2020-01-01"] * 3, dtype="M8[us]") + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("freq", ["ns", "1ns"]) +def test_to_timestamp_end_nanosecond_target(freq): + # GH#63760 how="end" keeps nanosecond precision for a target freq that + # normalizes to nanoseconds + pi = pd.period_range("2020-01-01", periods=2, freq="D") + result = pi.to_timestamp(freq, how="E") + expected = pd.DatetimeIndex( + ["2020-01-01 23:59:59.999999999", "2020-01-02 23:59:59.999999999"], + dtype="M8[ns]", + ) + tm.assert_index_equal(result, expected) + + +def test_to_timestamp_end_from_nanosecond_period(): + # GH#63760 nanosecond periods keep their nanosecond end bounds with a + # coarser target freq + pi = pd.period_range("2020-01-01", periods=2, freq="ns") + result = pi.to_timestamp("D", how="E") + expected = pd.DatetimeIndex( + ["2020-01-01 00:00:00", "2020-01-01 00:00:00.000000001"], dtype="M8[ns]" + ) + tm.assert_index_equal(result, expected) + + +def test_to_timestamp_end_bday_nanosecond_target(): + # GH#63760 the B roll-forward path keeps nanosecond precision too + msg = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + pi = pd.period_range("2020-01-02", periods=2, freq="B") + result = pi.to_timestamp("ns", how="E") + expected = pd.DatetimeIndex( + ["2020-01-02 23:59:59.999999999", "2020-01-03 23:59:59.999999999"], + dtype="M8[ns]", + ) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/test_constructors.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc59783e525fb5b4a129de4da6aafee657e5c74 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/period/test_constructors.py @@ -0,0 +1,897 @@ +import re + +import numpy as np +import pytest + +from pandas._libs.tslibs.period import IncompatibleFrequency +from pandas.errors import ( + OutOfBoundsDatetime, + Pandas4Warning, +) + +from pandas.core.dtypes.dtypes import PeriodDtype + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import PeriodArray + + +class TestPeriodIndexDisallowedFreqs: + @pytest.mark.parametrize( + "freq,freq_depr", + [ + ("2M", "2ME"), + ("2Q-MAR", "2QE-MAR"), + ("2Y-FEB", "2YE-FEB"), + ("2M", "2me"), + ("2Q-MAR", "2qe-MAR"), + ("2Y-FEB", "2yE-feb"), + ], + ) + def test_period_index_offsets_frequency_error_message(self, freq, freq_depr): + # GH#52064 + msg = f"Invalid frequency: {freq_depr}" + + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex(["2020-01-01", "2020-01-02"], freq=freq_depr) + + with pytest.raises(ValueError, match=msg): + pd.period_range(start="2020-01-01", end="2020-01-02", freq=freq_depr) + + @pytest.mark.parametrize( + "freq", + ["2SME", "2sme", "2BYE", "2Bye", "2CBME"], + ) + def test_period_index_frequency_invalid_freq(self, freq): + # GH#9586 + msg = f"Invalid frequency: {freq}" + + with pytest.raises(ValueError, match=msg): + pd.period_range("2020-01", "2020-05", freq=freq) + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex(["2020-01", "2020-05"], freq=freq) + + @pytest.mark.parametrize("freq", ["2BQE-SEP", "2BYE-MAR", "2BME"]) + def test_period_index_from_datetime_index_invalid_freq(self, freq): + # GH#56899 + msg = f"Invalid frequency: {freq}" + + rng = pd.date_range("01-Jan-2012", periods=8, freq=freq) + with pytest.raises(ValueError, match=msg): + rng.to_period() + + @pytest.mark.parametrize("freq_depr", ["2T", "1l", "2U", "n"]) + def test_period_index_T_L_U_N_raises(self, freq_depr): + # GH#9586 + msg = f"Invalid frequency: {freq_depr}" + + with pytest.raises(ValueError, match=msg): + pd.period_range("2020-01", "2020-05", freq=freq_depr) + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex(["2020-01", "2020-05"], freq=freq_depr) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + @pytest.mark.filterwarnings("ignore:Period with BDay freq:FutureWarning") + @pytest.mark.parametrize( + "freq,freq_depr", + [("2W", "2w"), ("2W-FRI", "2w-fri"), ("2D", "2d"), ("2B", "2b")], + ) + def test_period_index_depr_lowercase_frequency(self, freq, freq_depr): + # GH#58998 + msg = ( + f"'{freq_depr[1:]}' is deprecated and will be removed in a future version." + ) + + with tm.assert_produces_warning( + Pandas4Warning, match=msg, raise_on_extra_warnings=False + ): + result = pd.PeriodIndex(["2020-01-01", "2020-01-02"], freq=freq_depr) + + expected = pd.PeriodIndex(["2020-01-01", "2020-01-02"], freq=freq) + tm.assert_index_equal(result, expected) + + with tm.assert_produces_warning( + Pandas4Warning, match=msg, raise_on_extra_warnings=False + ): + result = pd.period_range( + start="2020-01-01", end="2020-01-02", freq=freq_depr + ) + + expected = pd.period_range(start="2020-01-01", end="2020-01-02", freq=freq) + tm.assert_index_equal(result, expected) + + +def test_period_index_from_series_inferred_freq_deprecated(): + # GH#64241 + data = np.arange(5, dtype=np.int64).view("M8[D]").astype("M8[ns]") + dti = pd.Index(data) + assert dti.freq is None + ser = pd.Series(dti) + + msg = "Constructing PeriodArray from a Series of datetime64 data" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = pd.PeriodIndex(ser) + expected = pd.PeriodIndex(dti, freq="D") + tm.assert_index_equal(result, expected) + + +class TestPeriodIndex: + def test_from_ordinals(self): + pd.Period(ordinal=-1000, freq="Y") + pd.Period(ordinal=0, freq="Y") + + idx1 = pd.PeriodIndex.from_ordinals(ordinals=[-1, 0, 1], freq="Y") + idx2 = pd.PeriodIndex.from_ordinals(ordinals=np.array([-1, 0, 1]), freq="Y") + tm.assert_index_equal(idx1, idx2) + + def test_construction_base_constructor(self): + # GH 13664 + arr = [pd.Period("2011-01", freq="M"), pd.NaT, pd.Period("2011-03", freq="M")] + tm.assert_index_equal(pd.Index(arr), pd.PeriodIndex(arr)) + tm.assert_index_equal(pd.Index(np.array(arr)), pd.PeriodIndex(np.array(arr))) + + arr = [np.nan, pd.NaT, pd.Period("2011-03", freq="M")] + tm.assert_index_equal(pd.Index(arr), pd.PeriodIndex(arr)) + tm.assert_index_equal(pd.Index(np.array(arr)), pd.PeriodIndex(np.array(arr))) + + arr = [pd.Period("2011-01", freq="M"), pd.NaT, pd.Period("2011-03", freq="D")] + tm.assert_index_equal(pd.Index(arr), pd.Index(arr, dtype=object)) + + tm.assert_index_equal( + pd.Index(np.array(arr)), pd.Index(np.array(arr), dtype=object) + ) + + def test_base_constructor_with_period_dtype(self): + dtype = PeriodDtype("D") + values = ["2011-01-01", "2012-03-04", "2014-05-01"] + result = pd.Index(values, dtype=dtype) + + expected = pd.PeriodIndex(values, dtype=dtype) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "values_constructor", + [list, np.array, pd.PeriodIndex, PeriodArray._from_sequence], + ) + def test_index_object_dtype(self, values_constructor): + # Index(periods, dtype=object) is an Index (not a PeriodIndex) + periods = [ + pd.Period("2011-01", freq="M"), + pd.NaT, + pd.Period("2011-03", freq="M"), + ] + values = values_constructor(periods) + result = pd.Index(values, dtype=object) + + assert type(result) is pd.Index + tm.assert_numpy_array_equal(result.values, np.array(values)) + + def test_constructor_use_start_freq(self): + # GH #1118 + msg1 = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg1): + p = pd.Period("4/2/2012", freq="B") + msg2 = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg2): + expected = pd.period_range(start="4/2/2012", periods=10, freq="B") + + with tm.assert_produces_warning(FutureWarning, match=msg2): + index = pd.period_range(start=p, periods=10) + tm.assert_index_equal(index, expected) + + def test_constructor_field_arrays(self): + # GH #1264 + + years = np.arange(1990, 2010).repeat(4)[2:-2] + quarters = np.tile(np.arange(1, 5), 20)[2:-2] + + index = pd.PeriodIndex.from_fields(year=years, quarter=quarters, freq="Q-DEC") + expected = pd.period_range("1990Q3", "2009Q2", freq="Q-DEC") + tm.assert_index_equal(index, expected) + + index2 = pd.PeriodIndex.from_fields(year=years, quarter=quarters, freq="2Q-DEC") + tm.assert_numpy_array_equal(index.asi8, index2.asi8) + + index = pd.PeriodIndex.from_fields(year=years, quarter=quarters) + tm.assert_index_equal(index, expected) + + years = [2007, 2007, 2007] + months = [1, 2] + + msg = "Mismatched Period array lengths" + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex.from_fields(year=years, month=months, freq="M") + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex.from_fields(year=years, month=months, freq="2M") + + years = [2007, 2007, 2007] + months = [1, 2, 3] + idx = pd.PeriodIndex.from_fields(year=years, month=months, freq="M") + exp = pd.period_range("2007-01", periods=3, freq="M") + tm.assert_index_equal(idx, exp) + + @pytest.mark.parametrize("starting_month", range(1, 13)) + def test_from_fields_quarterly_anchors(self, starting_month): + # GH#55784 from_fields rejected any quarterly freq not anchored on + # December, even though the equivalent scalar Period works. + freq = pd.offsets.QuarterEnd(startingMonth=starting_month) + result = pd.PeriodIndex.from_fields(year=[2014], quarter=[3], freq=freq) + expected = pd.Period(year=2014, quarter=3, freq=freq) + assert result[0] == expected + assert result.dtype == PeriodDtype(freq) + + def test_from_fields_quarterly_rejects_non_quarterly_freq(self): + # GH#55784 from_fields should reject non-quarterly frequencies + # when the ``quarter`` field is supplied. + msg = "freq must be a quarterly frequency" + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex.from_fields( + year=[2014], quarter=[3], freq=pd.offsets.MonthEnd() + ) + + def test_constructor_nano(self): + idx = pd.period_range( + start=pd.Period(ordinal=1, freq="ns"), + end=pd.Period(ordinal=4, freq="ns"), + freq="ns", + ) + exp = pd.PeriodIndex( + [ + pd.Period(ordinal=1, freq="ns"), + pd.Period(ordinal=2, freq="ns"), + pd.Period(ordinal=3, freq="ns"), + pd.Period(ordinal=4, freq="ns"), + ], + freq="ns", + ) + tm.assert_index_equal(idx, exp) + + def test_constructor_arrays_negative_year(self): + years = np.arange(1960, 2000, dtype=np.int64).repeat(4) + quarters = np.tile(np.array([1, 2, 3, 4], dtype=np.int64), 40) + pindex = pd.PeriodIndex.from_fields(year=years, quarter=quarters) + + tm.assert_index_equal(pindex.year, pd.Index(years)) + tm.assert_index_equal(pindex.quarter, pd.Index(quarters)) + + def test_constructor_invalid_quarters(self): + msg = "Quarter must be 1 <= q <= 4" + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex.from_fields( + year=range(2000, 2004), quarter=list(range(4)), freq="Q-DEC" + ) + + def test_constructor_field_arrays_quarter_no_freq(self): + # Quarter with no explicit freq infers Q-DEC + years = np.array([2020, 2020, 2020, 2020], dtype=np.int64) + quarters = np.array([1, 2, 3, 4], dtype=np.int64) + result = pd.PeriodIndex.from_fields(year=years, quarter=quarters) + expected = pd.PeriodIndex( + [pd.Period(year=2020, quarter=q, freq="Q-DEC") for q in range(1, 5)] + ) + tm.assert_index_equal(result, expected) + + def test_constructor_field_arrays_hourly(self): + # Test non-quarter path with all 6 fields + result = pd.PeriodIndex.from_fields( + year=[2020, 2020], + month=[1, 6], + day=[15, 20], + hour=[10, 22], + minute=[30, 45], + second=[5, 59], + freq="s", + ) + expected = pd.PeriodIndex( + [ + pd.Period("2020-01-15 10:30:05", freq="s"), + pd.Period("2020-06-20 22:45:59", freq="s"), + ] + ) + tm.assert_index_equal(result, expected) + + def test_constructor_field_arrays_empty(self): + # Empty arrays should produce empty PeriodIndex + result = pd.PeriodIndex.from_fields(year=[], month=[], freq="M") + expected = pd.PeriodIndex([], dtype="period[M]") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("field", ["year", "month"]) + def test_constructor_field_arrays_outside_int32(self, field): + # Fields outside int32 range must raise instead of wrapping silently + fields = {"year": [2000, 2000], "month": [3, 3]} + fields[field] = [fields[field][0], 2**32 + 3] + with pytest.raises(OverflowError, match="value too large"): + pd.PeriodIndex.from_fields(**fields, freq="M") + + def test_constructor_field_arrays_tuple(self): + # GH#65921 a tuple is array-like and must be treated as such, not + # silently repeated as if it were a scalar + result = pd.PeriodIndex.from_fields(year=(2020, 2021), month=[1, 2], freq="M") + expected = pd.PeriodIndex(["2020-01", "2021-02"], freq="M") + tm.assert_index_equal(result, expected) + + def test_constructor_field_arrays_tuple_mismatched_length(self): + # GH#65921 a genuinely mismatched tuple length must raise instead of + # reading out of bounds + msg = "Mismatched Period array lengths" + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex.from_fields(year=(2020, 2021, 2022), month=[1, 2], freq="M") + + @pytest.mark.parametrize( + "kwargs", [{"month": [1, 2], "freq": "M"}, {"quarter": [1, 2]}] + ) + def test_constructor_field_arrays_nan_raises(self, kwargs): + # GH#65921 NaN must raise rather than silently casting to a garbage + # ordinal (e.g. Period("0-01")) + msg = "cannot convert float NaN to integer" + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex.from_fields(year=[np.nan, 2020], **kwargs) + + def test_period_range_fractional_period(self): + msg = "periods must be an integer, got 10.5" + with pytest.raises(TypeError, match=msg): + pd.period_range("2007-01", periods=10.5, freq="M") + + def test_constructor_with_without_freq(self): + # GH53687 + start = pd.Period("2002-01-01 00:00", freq="30min") + exp = pd.period_range(start=start, periods=5, freq=start.freq) + result = pd.period_range(start=start, periods=5) + tm.assert_index_equal(exp, result) + + def test_constructor_fromarraylike(self): + idx = pd.period_range("2007-01", periods=20, freq="M") + + # values is an array of Period, thus can retrieve freq + vals = np.asarray(idx, dtype=object) + tm.assert_index_equal(pd.PeriodIndex(vals), idx) + tm.assert_index_equal(pd.PeriodIndex(list(vals)), idx) + + msg = "freq not specified and cannot be inferred" + depr_msg = "Passing integer data" + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex(idx.asi8) + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex(list(idx.asi8)) + + msg = "'Period' object is not iterable" + with pytest.raises(TypeError, match=msg): + pd.PeriodIndex(data=pd.Period("2007", freq="Y")) + + result = pd.PeriodIndex(iter(idx)) + tm.assert_index_equal(result, idx) + + result = pd.PeriodIndex(idx) + tm.assert_index_equal(result, idx) + + result = pd.PeriodIndex(idx, freq="M") + tm.assert_index_equal(result, idx) + + result = pd.PeriodIndex(idx, freq=pd.offsets.MonthEnd()) + tm.assert_index_equal(result, idx) + assert result.freq == "ME" + + def test_constructor_fromarraylike_freq_data_mismatch_converts2(self): + idx = pd.period_range("2007-01", periods=20, freq="M") + + result = pd.PeriodIndex(idx, freq="2M") + tm.assert_index_equal(result, idx.asfreq("2M")) + assert result.freq == "2ME" + + result = pd.PeriodIndex(idx, freq=pd.offsets.MonthEnd(2)) + tm.assert_index_equal(result, idx.asfreq("2M")) + assert result.freq == "2ME" + + result = pd.PeriodIndex(idx, freq="D") + exp = idx.asfreq("D", "e") + tm.assert_index_equal(result, exp) + + # Same for PeriodArray + result = PeriodArray._from_sequence(idx, dtype="period[2M]") + tm.assert_period_array_equal(result, idx.asfreq("2M").array) + assert result.freq == "2ME" + + result = PeriodArray._from_sequence( + idx, dtype=PeriodDtype(pd.offsets.MonthEnd(2)) + ) + tm.assert_period_array_equal(result, idx.asfreq("2M").array) + assert result.freq == "2ME" + + result = PeriodArray._from_sequence(idx, dtype="period[D]") + exp = idx.asfreq("D", "e").array + tm.assert_period_array_equal(result, exp) + + def test_constructor_datetime64arr(self): + vals = np.arange(100000, 100000 + 10000, 100, dtype=np.int64) + vals = vals.view(np.dtype("M8[us]")) + + pi = pd.PeriodIndex(vals, freq="D") + + expected = pd.PeriodIndex(vals.astype("M8[ns]"), freq="D") + tm.assert_index_equal(pi, expected) + + @pytest.mark.parametrize( + "val", [2**32 + 1985, 10**18, 2**31 - 1, -(2**32), 100000, 999] + ) + def test_constructor_int_array_out_of_bounds(self, val): + # GH#64158 an integer that Period(int) rejects is rejected here too, + # with the same error; these used to silently wrap or give a bogus + # year. The parser's wording moves with the dateutil and python + # version, so take the scalar's error as the expected one. + try: + pd.Period(str(val), freq="Y") + except ValueError as err: + expected = err + else: + raise AssertionError(f"Period({val}) did not raise") + + arr = np.array([val], dtype=np.int64) + depr_msg = "Passing integer data" + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + with pytest.raises(type(expected), match=re.escape(str(expected))): + pd.PeriodIndex(arr, freq="Y") + + @pytest.mark.filterwarnings( + "ignore:Passing integer data:pandas.errors.Pandas4Warning" + ) + @pytest.mark.parametrize("dtype", [np.int64, object]) + def test_constructor_int_array_out_of_bounds_ordinal(self, dtype): + # GH#64158 year 2300 is representable at most freqs but its nanosecond + # ordinal overflows int64; the overflow used to be swallowed, giving + # a 1970 epoch entry in the middle of valid ones + arr = np.array([2000, 2300, 2001], dtype=dtype) + msg = "Out of bounds nanosecond timestamp: 2300-01-01" + with pytest.raises(OutOfBoundsDatetime, match=msg): + pd.PeriodIndex(arr, freq="ns") + + @pytest.mark.parametrize("dtype", [np.int64, object]) + @pytest.mark.parametrize("val", [2000, 200701, 20000101]) + def test_constructor_int_array_matches_scalar(self, val, dtype): + # GH#64158 the int64-array path read the integer as a literal calendar + # year, so it disagreed with Period(int, freq) and with the + # object-dtype path for anything but a four-digit year + expected = pd.PeriodIndex([pd.Period(str(val), freq="D")]) + + depr_msg = "Passing integer data" + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + result = pd.PeriodIndex(np.array([val], dtype=dtype), freq="D") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("box", [None, "series", "index"]) + def test_constructor_datetime64arr_ok(self, box): + # https://github.com/pandas-dev/pandas/issues/23438 + data = pd.date_range("2017", periods=4, freq="ME") + if box is None: + data = data._values + elif box == "series": + data = pd.Series(data) + + result = pd.PeriodIndex(data, freq="D") + expected = pd.PeriodIndex( + ["2017-01-31", "2017-02-28", "2017-03-31", "2017-04-30"], freq="D" + ) + tm.assert_index_equal(result, expected) + + def test_constructor_dtype(self): + # passing a dtype with a tz should localize + idx = pd.PeriodIndex(["2013-01", "2013-03"], dtype="period[M]") + exp = pd.PeriodIndex(["2013-01", "2013-03"], freq="M") + tm.assert_index_equal(idx, exp) + assert idx.dtype == "period[M]" + + idx = pd.PeriodIndex(["2013-01-05", "2013-03-05"], dtype="period[3D]") + exp = pd.PeriodIndex(["2013-01-05", "2013-03-05"], freq="3D") + tm.assert_index_equal(idx, exp) + assert idx.dtype == "period[3D]" + + def test_constructor_freq_data_mismatch_converts(self): + # if we already have a freq and its not the same, then asfreq + # (not changed) + idx = pd.PeriodIndex(["2013-01-01", "2013-01-02"], freq="D") + + res = pd.PeriodIndex(idx, dtype="period[M]") + exp = pd.PeriodIndex(["2013-01", "2013-01"], freq="M") + tm.assert_index_equal(res, exp) + assert res.dtype == "period[M]" + + res = pd.PeriodIndex(idx, freq="M") + tm.assert_index_equal(res, exp) + assert res.dtype == "period[M]" + + # Same thing with PeriodArray._from_sequence + res = PeriodArray._from_sequence(idx, dtype="period[M]") + tm.assert_period_array_equal(res, exp.array) + + def test_constructor_mismatched_freq_vs_dtype(self): + msg = "specified freq and dtype are different" + with pytest.raises(IncompatibleFrequency, match=msg): + pd.PeriodIndex(["2011-01"], freq="M", dtype="period[D]") + + def test_constructor_empty(self): + idx = pd.PeriodIndex([], freq="M") + assert isinstance(idx, pd.PeriodIndex) + assert len(idx) == 0 + assert idx.freq == "ME" + + with pytest.raises(ValueError, match="freq not specified"): + pd.PeriodIndex([]) + + def test_constructor_pi_nat(self): + idx = pd.PeriodIndex( + [pd.Period("2011-01", freq="M"), pd.NaT, pd.Period("2011-01", freq="M")] + ) + exp = pd.PeriodIndex(["2011-01", "NaT", "2011-01"], freq="M") + tm.assert_index_equal(idx, exp) + + idx = pd.PeriodIndex( + np.array( + [pd.Period("2011-01", freq="M"), pd.NaT, pd.Period("2011-01", freq="M")] + ) + ) + tm.assert_index_equal(idx, exp) + + idx = pd.PeriodIndex( + [ + pd.NaT, + pd.NaT, + pd.Period("2011-01", freq="M"), + pd.Period("2011-01", freq="M"), + ] + ) + exp = pd.PeriodIndex(["NaT", "NaT", "2011-01", "2011-01"], freq="M") + tm.assert_index_equal(idx, exp) + + idx = pd.PeriodIndex( + np.array( + [ + pd.NaT, + pd.NaT, + pd.Period("2011-01", freq="M"), + pd.Period("2011-01", freq="M"), + ] + ) + ) + tm.assert_index_equal(idx, exp) + + idx = pd.PeriodIndex([pd.NaT, pd.NaT, "2011-01", "2011-01"], freq="M") + tm.assert_index_equal(idx, exp) + + with pytest.raises(ValueError, match="freq not specified"): + pd.PeriodIndex([pd.NaT, pd.NaT]) + + with pytest.raises(ValueError, match="freq not specified"): + pd.PeriodIndex(np.array([pd.NaT, pd.NaT])) + + with pytest.raises(ValueError, match="freq not specified"): + pd.PeriodIndex(["NaT", "NaT"]) + + with pytest.raises(ValueError, match="freq not specified"): + pd.PeriodIndex(np.array(["NaT", "NaT"])) + + def test_constructor_incompat_freq(self): + msg = "Input has different freq=D from PeriodIndex\\(freq=M\\)" + + with pytest.raises(IncompatibleFrequency, match=msg): + pd.PeriodIndex( + [pd.Period("2011-01", freq="M"), pd.NaT, pd.Period("2011-01", freq="D")] + ) + + with pytest.raises(IncompatibleFrequency, match=msg): + pd.PeriodIndex( + np.array( + [ + pd.Period("2011-01", freq="M"), + pd.NaT, + pd.Period("2011-01", freq="D"), + ] + ) + ) + + # first element is NaT + with pytest.raises(IncompatibleFrequency, match=msg): + pd.PeriodIndex( + [pd.NaT, pd.Period("2011-01", freq="M"), pd.Period("2011-01", freq="D")] + ) + + with pytest.raises(IncompatibleFrequency, match=msg): + pd.PeriodIndex( + np.array( + [ + pd.NaT, + pd.Period("2011-01", freq="M"), + pd.Period("2011-01", freq="D"), + ] + ) + ) + + def test_constructor_mixed(self): + idx = pd.PeriodIndex(["2011-01", pd.NaT, pd.Period("2011-01", freq="M")]) + exp = pd.PeriodIndex(["2011-01", "NaT", "2011-01"], freq="M") + tm.assert_index_equal(idx, exp) + + idx = pd.PeriodIndex(["NaT", pd.NaT, pd.Period("2011-01", freq="M")]) + exp = pd.PeriodIndex(["NaT", "NaT", "2011-01"], freq="M") + tm.assert_index_equal(idx, exp) + + idx = pd.PeriodIndex([pd.Period("2011-01-01", freq="D"), pd.NaT, "2012-01-01"]) + exp = pd.PeriodIndex(["2011-01-01", "NaT", "2012-01-01"], freq="D") + tm.assert_index_equal(idx, exp) + + @pytest.mark.parametrize("floats", [[1.1, 2.1], np.array([1.1, 2.1])]) + def test_constructor_floats(self, floats): + msg = "PeriodArray does not allow floating point in construction" + with pytest.raises(TypeError, match=msg): + pd.PeriodIndex(floats) + with pytest.raises(TypeError, match=msg): + PeriodArray._from_sequence(floats) + + # But if they are all-NaN we allow it + + pi = pd.PeriodIndex([np.nan], freq="D") + assert pi.isna().all() + parr = PeriodArray._from_sequence([np.nan], dtype="period[D]") + assert parr.isna().all() + + def test_constructor_year_and_quarter(self): + year = pd.Series([2001, 2002, 2003]) + quarter = year - 2000 + idx = pd.PeriodIndex.from_fields(year=year, quarter=quarter) + strs = [f"{t[0]:d}Q{t[1]:d}" for t in zip(quarter, year, strict=True)] + lops = list(map(pd.Period, strs)) + p = pd.PeriodIndex(lops) + tm.assert_index_equal(p, idx) + + def test_constructor_freq_mult(self): + # GH #7811 + pidx = pd.period_range(start="2014-01", freq="2M", periods=4) + expected = pd.PeriodIndex( + ["2014-01", "2014-03", "2014-05", "2014-07"], freq="2M" + ) + tm.assert_index_equal(pidx, expected) + + pidx = pd.period_range(start="2014-01-02", end="2014-01-15", freq="3D") + expected = pd.PeriodIndex( + ["2014-01-02", "2014-01-05", "2014-01-08", "2014-01-11", "2014-01-14"], + freq="3D", + ) + tm.assert_index_equal(pidx, expected) + + pidx = pd.period_range(end="2014-01-01 17:00", freq="4h", periods=3) + expected = pd.PeriodIndex( + ["2014-01-01 09:00", "2014-01-01 13:00", "2014-01-01 17:00"], freq="4h" + ) + tm.assert_index_equal(pidx, expected) + + msg = "Frequency must be positive, because it represents span: -1M" + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex(["2011-01"], freq="-1M") + + msg = "Frequency must be positive, because it represents span: 0M" + with pytest.raises(ValueError, match=msg): + pd.PeriodIndex(["2011-01"], freq="0M") + + msg = "Frequency must be positive, because it represents span: 0M" + with pytest.raises(ValueError, match=msg): + pd.period_range("2011-01", periods=3, freq="0M") + + @pytest.mark.parametrize( + "freq_offset, freq_period", + [ + ("YE", "Y"), + ("ME", "M"), + ("D", "D"), + ("min", "min"), + ("s", "s"), + ], + ) + @pytest.mark.parametrize("mult", [1, 2, 3, 4, 5]) + def test_constructor_freq_mult_dti_compat(self, mult, freq_offset, freq_period): + freqstr_offset = str(mult) + freq_offset + freqstr_period = str(mult) + freq_period + pidx = pd.period_range(start="2014-04-01", freq=freqstr_period, periods=10) + expected = pd.date_range( + start="2014-04-01", freq=freqstr_offset, periods=10 + ).to_period(freqstr_period) + tm.assert_index_equal(pidx, expected) + + @pytest.mark.parametrize("mult", [1, 2, 3, 4, 5]) + def test_constructor_freq_mult_dti_compat_month(self, mult): + pidx = pd.period_range(start="2014-04-01", freq=f"{mult}M", periods=10) + expected = pd.date_range( + start="2014-04-01", freq=f"{mult}ME", periods=10 + ).to_period(f"{mult}M") + tm.assert_index_equal(pidx, expected) + + def test_constructor_freq_combined(self): + for freq in ["1D1h", "1h1D"]: + pidx = pd.PeriodIndex(["2016-01-01", "2016-01-02"], freq=freq) + expected = pd.PeriodIndex( + ["2016-01-01 00:00", "2016-01-02 00:00"], freq="25h" + ) + for freq in ["1D1h", "1h1D"]: + pidx = pd.period_range(start="2016-01-01", periods=2, freq=freq) + expected = pd.PeriodIndex( + ["2016-01-01 00:00", "2016-01-02 01:00"], freq="25h" + ) + tm.assert_index_equal(pidx, expected) + + def test_period_range_length(self): + pi = pd.period_range(freq="Y", start="1/1/2001", end="12/1/2009") + assert len(pi) == 9 + + pi = pd.period_range(freq="Q", start="1/1/2001", end="12/1/2009") + assert len(pi) == 4 * 9 + + pi = pd.period_range(freq="M", start="1/1/2001", end="12/1/2009") + assert len(pi) == 12 * 9 + + pi = pd.period_range(freq="D", start="1/1/2001", end="12/31/2009") + assert len(pi) == 365 * 9 + 2 + + msg = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + pi = pd.period_range(freq="B", start="1/1/2001", end="12/31/2009") + assert len(pi) == 261 * 9 + + pi = pd.period_range(freq="h", start="1/1/2001", end="12/31/2001 23:00") + assert len(pi) == 365 * 24 + + pi = pd.period_range(freq="Min", start="1/1/2001", end="1/1/2001 23:59") + assert len(pi) == 24 * 60 + + pi = pd.period_range(freq="s", start="1/1/2001", end="1/1/2001 23:59:59") + assert len(pi) == 24 * 60 * 60 + + with tm.assert_produces_warning(FutureWarning, match=msg): + start = pd.Period("02-Apr-2005", "B") + i1 = pd.period_range(start=start, periods=20) + assert len(i1) == 20 + assert i1.freq == start.freq + assert i1[0] == start + + end_intv = pd.Period("2006-12-31", "W") + i1 = pd.period_range(end=end_intv, periods=10) + assert len(i1) == 10 + assert i1.freq == end_intv.freq + assert i1[-1] == end_intv + + msg = "'w' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(Pandas4Warning, match=msg): + end_intv = pd.Period("2006-12-31", "1w") + i2 = pd.period_range(end=end_intv, periods=10) + assert len(i1) == len(i2) + assert (i1 == i2).all() + assert i1.freq == i2.freq + + def test_infer_freq_from_first_element(self): + msg = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + start = pd.Period("02-Apr-2005", "B") + end_intv = pd.Period("2005-05-01", "B") + pd.period_range(start=start, end=end_intv) + + # infer freq from first element + i2 = pd.PeriodIndex([end_intv, pd.Period("2005-05-05", "B")]) + assert len(i2) == 2 + assert i2[0] == end_intv + + with tm.assert_produces_warning(FutureWarning, match=msg): + i2 = pd.PeriodIndex(np.array([end_intv, pd.Period("2005-05-05", "B")])) + assert len(i2) == 2 + assert i2[0] == end_intv + + def test_mixed_freq_raises(self): + # Mixed freq should fail + msg = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + end_intv = pd.Period("2005-05-01", "B") + + vals = [end_intv, pd.Period("2006-12-31", "W")] + msg = r"Input has different freq=W-SUN from PeriodIndex\(freq=B\)" + depr_msg = r"PeriodDtype\[B\] is deprecated" + with pytest.raises(IncompatibleFrequency, match=msg): + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + pd.PeriodIndex(vals) + vals = np.array(vals) + with pytest.raises(IncompatibleFrequency, match=msg): + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + pd.PeriodIndex(vals) + + @pytest.mark.parametrize( + "freq", ["M", "Q", "Y", "D", "B", "min", "s", "ms", "us", "ns", "h"] + ) + @pytest.mark.filterwarnings( + r"ignore:Period with BDay freq is deprecated:FutureWarning" + ) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_recreate_from_data(self, freq): + org = pd.period_range(start="2001/04/01", freq=freq, periods=1) + idx = pd.PeriodIndex(np.asarray(org, dtype=object), freq=freq) + tm.assert_index_equal(idx, org) + + def test_map_with_string_constructor(self): + raw = ["2005", "2007", "2009"] + index = pd.PeriodIndex(raw, freq="Y") + + expected = pd.Index([str(num) for num in raw]) + res = index.map(str) + + # should return an Index + assert isinstance(res, pd.Index) + + # preserve element types + assert all(isinstance(resi, str) for resi in res) + + # lastly, values should compare equal + tm.assert_index_equal(res, expected) + + +class TestSimpleNew: + def test_constructor_simple_new(self): + idx = pd.period_range("2007-01", name="p", periods=2, freq="M") + + with pytest.raises(AssertionError, match=""): + idx._simple_new(idx, name="p") + + result = idx._simple_new(idx._data, name="p") + tm.assert_index_equal(result, idx) + + msg = "Should be numpy array of type i8" + with pytest.raises(AssertionError, match=msg): + # Need ndarray, not int64 Index + type(idx._data)._simple_new(pd.Index(idx.asi8), dtype=idx.dtype) + + arr = type(idx._data)._simple_new(idx.asi8, dtype=idx.dtype) + result = idx._simple_new(arr, name="p") + tm.assert_index_equal(result, idx) + + def test_constructor_simple_new_empty(self): + # GH13079 + idx = pd.PeriodIndex([], freq="M", name="p") + with pytest.raises(AssertionError, match=""): + idx._simple_new(idx, name="p") + + result = idx._simple_new(idx._data, name="p") + tm.assert_index_equal(result, idx) + + @pytest.mark.parametrize("floats", [[1.1, 2.1], np.array([1.1, 2.1])]) + def test_period_index_simple_new_disallows_floats(self, floats): + with pytest.raises(AssertionError, match=""): + pd.RangeIndex("1", "10", "1") + with pytest.raises(TypeError, match=r"Wrong type \"): + pd.RangeIndex(1.1, 10.2, 1.3) + + # invalid passed type + with pytest.raises( + ValueError, + match="Incorrect `dtype` passed: expected signed integer, received float64", + ): + pd.RangeIndex(1, 5, dtype="float64") + + +@pytest.mark.parametrize( + "seq", + [ + # uint64 above INT64_MAX would silently wrap to a negative range + np.array([2**63, 2**63 + 1, 2**63 + 2], dtype=np.uint64), + # a two-element key whose step overflows int64 + np.array([np.iinfo(np.int64).min, np.iinfo(np.int64).max], dtype=np.int64), + # a step that overflows int64 from one extreme end + np.array([0, np.iinfo(np.int64).max], dtype=np.int64), + # not a range, but its elements satisfy is_sequence_range's modular + # (uint64) check: the true value at index 2 is 2**63, which wraps to the + # bit pattern of INT64_MIN -- must still be rejected + np.array([0, 2**62, np.iinfo(np.int64).min], dtype=np.int64), + ], +) +def test_maybe_sequence_to_range_extreme_ints_not_converted(seq): + # GH#64148 don't build an incorrect range for integer sequences whose + # conversion to a range would overflow/wrap int64 + result = maybe_sequence_to_range(seq) + tm.assert_numpy_array_equal(result, seq) + + +def test_maybe_sequence_to_range_still_converts_representable(): + # GH#64148 sequences that fit in the int64 domain are still converted + assert maybe_sequence_to_range(np.array([10, 11, 12], dtype=np.int64)) == range( + 10, 13 + ) + # a genuinely negative arithmetic progression is still converted + assert maybe_sequence_to_range([-5, -4, -3]) == range(-5, -2) + # uint64 values that fit in int64 are still converted + assert maybe_sequence_to_range(np.array([1, 2, 3], dtype=np.uint64)) == range(1, 4) + # a genuine range spanning more than INT64_MAX: the intermediate + # ``2 * step`` overflows int64, but the range is still representable and + # must be converted exactly (GH#64148 UBSAN signed-overflow regression) + span = np.array([-(2**62) - 1, -1, 2**62 - 1], dtype=np.int64) + result = maybe_sequence_to_range(span) + assert result == range(-(2**62) - 1, 2**63 - 1, 2**62) + assert list(result) == span.tolist() diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..28b2832526426f591d95bf995e20d4792af0c81e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_indexing.py @@ -0,0 +1,183 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestGetIndexer: + def test_get_indexer(self): + index = pd.RangeIndex(start=0, stop=20, step=2) + target = pd.RangeIndex(10) + indexer = index.get_indexer(target) + expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + def test_get_indexer_pad(self): + index = pd.RangeIndex(start=0, stop=20, step=2) + target = pd.RangeIndex(10) + indexer = index.get_indexer(target, method="pad") + expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + def test_get_indexer_backfill(self): + index = pd.RangeIndex(start=0, stop=20, step=2) + target = pd.RangeIndex(10) + indexer = index.get_indexer(target, method="backfill") + expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + def test_get_indexer_limit(self): + # GH#28631 + idx = pd.RangeIndex(4) + target = pd.RangeIndex(6) + result = idx.get_indexer(target, method="pad", limit=1) + expected = np.array([0, 1, 2, 3, 3, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("stop", [0, -1, -2]) + def test_get_indexer_decreasing(self, stop): + # GH#28678 + index = pd.RangeIndex(7, stop, -3) + result = index.get_indexer(range(9)) + expected = np.array([-1, 2, -1, -1, 1, -1, -1, 0, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_int64_min_no_overflow(self): + # GH#64148 a target near INT64_MIN overflowed ``target - start`` and was + # reported as a spurious (out-of-bounds) match instead of -1 + index = pd.RangeIndex(10, 13) + target = np.array([np.iinfo(np.int64).min, 10, 11, 12, 13], dtype=np.int64) + result = index.get_indexer(target) + expected = np.array([-1, 0, 1, 2, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_uint64_above_int64_max(self): + # GH#64148 uint64 targets above INT64_MAX must not spuriously match + index = pd.RangeIndex(0, 3) + target = np.array([2**63, 0, 1, 5], dtype=np.uint64) + result = index.get_indexer(target) + expected = np.array([-1, 0, 1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_span_exceeds_int64_max(self): + # GH#64148 offsets beyond INT64_MAX overflowed the int64 subtraction, + # returning garbage indexers (e.g. -2) for genuine members + index = pd.RangeIndex(-(2**62) - 1, 2**63 - 1, 2**62) + assert list(index) == [-(2**62) - 1, -1, 2**62 - 1] + target = np.array([2**62 - 1, -1, 5, -(2**62) - 1], dtype=np.int64) + result = index.get_indexer(target) + expected = np.array([2, 1, -1, 0], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_decreasing_span_exceeds_int64_max(self): + # GH#64148 the same overflow through the reversed-range path + index = pd.RangeIndex(2**62 - 1, -(2**62) - 2, -(2**62)) + assert list(index) == [2**62 - 1, -1, -(2**62) - 1] + target = np.array( + [np.iinfo(np.int64).min, -1, 2**62 - 1, -(2**62) - 1], dtype=np.int64 + ) + result = index.get_indexer(target) + expected = np.array([-1, 1, 0, 2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_missing_value_casting_string_dtype(self): + # GH#55833 + idx = pd.Index(["a", "b", None]) + result = idx.get_indexer([None]) + expected = np.array([2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = idx.get_indexer([None, True]) + expected = np.array([2, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +class TestTake: + def test_take_preserve_name(self): + index = pd.RangeIndex(1, 5, name="foo") + taken = index.take([3, 0, 1]) + assert index.name == taken.name + + def test_take_fill_value(self): + # GH#12631 + idx = pd.RangeIndex(1, 4, name="xxx") + result = idx.take(np.array([1, 0, -1])) + expected = pd.Index([2, 1, 3], dtype=np.int64, name="xxx") + tm.assert_index_equal(result, expected) + + # fill_value: RangeIndex falls back to Index (which can hold NA) + result = idx.take(np.array([1, 0, -1]), fill_value=np.nan) + expected = pd.Index([2, 1, np.nan], name="xxx") + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False) + expected = pd.Index([2, 1, 3], dtype=np.int64, name="xxx") + tm.assert_index_equal(result, expected) + + msg = "When allow_fill=True, all indices must be >= -1" + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + def test_take_raises_index_error(self): + idx = pd.RangeIndex(1, 4, name="xxx") + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + msg = "index -4 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -4])) + + # no errors + result = idx.take(np.array([1, -3])) + expected = pd.RangeIndex(start=2, stop=0, step=-1, name="xxx") + tm.assert_index_equal(result, expected, exact=True) + + def test_take_accepts_empty_array(self): + idx = pd.RangeIndex(1, 4, name="foo") + result = idx.take(np.array([])) + expected = pd.RangeIndex(start=0, stop=0, step=1, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + # empty index + idx = pd.RangeIndex(0, name="foo") + result = idx.take(np.array([])) + expected = pd.RangeIndex(start=0, stop=0, step=1, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + def test_take_accepts_non_int64_array(self): + idx = pd.RangeIndex(1, 4, name="foo") + result = idx.take(np.array([2, 1], dtype=np.uint32)) + expected = pd.RangeIndex(start=3, stop=1, step=-1, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + def test_take_when_index_has_step(self): + idx = pd.RangeIndex(1, 11, 3, name="foo") # [1, 4, 7, 10] + result = idx.take(np.array([1, 0, -1, -4])) + expected = pd.Index([4, 1, 10, 1], dtype=np.int64, name="foo") + tm.assert_index_equal(result, expected) + + def test_take_when_index_has_negative_step(self): + idx = pd.RangeIndex(11, -4, -2, name="foo") # [11, 9, 7, 5, 3, 1, -1, -3] + result = idx.take(np.array([1, 0, -1, -8])) + expected = pd.Index([9, 11, -3, 11], dtype=np.int64, name="foo") + tm.assert_index_equal(result, expected) + + +class TestWhere: + def test_where_putmask_range_cast(self): + # GH#43240 + idx = pd.RangeIndex(0, 5, name="test") + + mask = np.array([True, True, False, False, False]) + result = idx.putmask(mask, 10) + expected = pd.Index([10, 10, 2, 3, 4], dtype=np.int64, name="test") + tm.assert_index_equal(result, expected) + + result = idx.where(~mask, 10) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_join.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..e9994c0c888daee14e51b018b20d9a78d34fe8cb --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_join.py @@ -0,0 +1,322 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestJoin: + def test_join_outer(self): + # join with Index[int64] + index = pd.RangeIndex(start=0, stop=20, step=2) + other = pd.Index(np.arange(25, 14, -1, dtype=np.int64)) + + res, lidx, ridx = index.join(other, how="outer", return_indexers=True) + noidx_res = index.join(other, how="outer") + tm.assert_index_equal(res, noidx_res) + + eres = pd.Index( + [0, 2, 4, 6, 8, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] + ) + elidx = np.array( + [0, 1, 2, 3, 4, 5, 6, 7, -1, 8, -1, 9, -1, -1, -1, -1, -1, -1, -1], + dtype=np.intp, + ) + eridx = np.array( + [-1, -1, -1, -1, -1, -1, -1, -1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0], + dtype=np.intp, + ) + + assert isinstance(res, pd.Index) and res.dtype == np.dtype(np.int64) + assert not isinstance(res, pd.RangeIndex) + tm.assert_index_equal(res, eres, exact=True) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # join with RangeIndex + other = pd.RangeIndex(25, 14, -1) + + res, lidx, ridx = index.join(other, how="outer", return_indexers=True) + noidx_res = index.join(other, how="outer") + tm.assert_index_equal(res, noidx_res) + + assert isinstance(res, pd.Index) and res.dtype == np.int64 + assert not isinstance(res, pd.RangeIndex) + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_inner(self): + # Join with non-RangeIndex + index = pd.RangeIndex(start=0, stop=20, step=2) + other = pd.Index(np.arange(25, 14, -1, dtype=np.int64)) + + res, lidx, ridx = index.join(other, how="inner", return_indexers=True) + + # no guarantee of sortedness, so sort for comparison purposes + ind = res.argsort() + res = res.take(ind) + lidx = lidx.take(ind) + ridx = ridx.take(ind) + + eres = pd.Index([16, 18]) + elidx = np.array([8, 9], dtype=np.intp) + eridx = np.array([9, 7], dtype=np.intp) + + assert isinstance(res, pd.Index) and res.dtype == np.int64 + tm.assert_index_equal(res, eres, exact="equiv") + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + # Join two RangeIndex + other = pd.RangeIndex(25, 14, -1) + + res, lidx, ridx = index.join(other, how="inner", return_indexers=True) + + assert isinstance(res, pd.RangeIndex) + tm.assert_index_equal(res, eres, exact="equiv") + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_left(self): + # Join with Index[int64] + index = pd.RangeIndex(start=0, stop=20, step=2) + other = pd.Index(np.arange(25, 14, -1, dtype=np.int64)) + + res, lidx, ridx = index.join(other, how="left", return_indexers=True) + eres = index + eridx = np.array([-1, -1, -1, -1, -1, -1, -1, -1, 9, 7], dtype=np.intp) + + assert isinstance(res, pd.RangeIndex) + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + # Join withRangeIndex + other = pd.Index(np.arange(25, 14, -1, dtype=np.int64)) + + res, lidx, ridx = index.join(other, how="left", return_indexers=True) + + assert isinstance(res, pd.RangeIndex) + tm.assert_index_equal(res, eres) + assert lidx is None + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_right(self): + # Join with Index[int64] + index = pd.RangeIndex(start=0, stop=20, step=2) + other = pd.Index(np.arange(25, 14, -1, dtype=np.int64)) + + res, lidx, ridx = index.join(other, how="right", return_indexers=True) + eres = other + elidx = np.array([-1, -1, -1, -1, -1, -1, -1, 9, -1, 8, -1], dtype=np.intp) + + assert isinstance(other, pd.Index) and other.dtype == np.int64 + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + assert ridx is None + + # Join withRangeIndex + other = pd.RangeIndex(25, 14, -1) + + res, lidx, ridx = index.join(other, how="right", return_indexers=True) + eres = other + + assert isinstance(other, pd.RangeIndex) + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + assert ridx is None + + def test_join_non_int_index(self): + index = pd.RangeIndex(start=0, stop=20, step=2) + other = pd.Index([3, 6, 7, 8, 10], dtype=object) + + outer = index.join(other, how="outer") + outer2 = other.join(index, how="outer") + expected = pd.Index([0, 2, 3, 4, 6, 7, 8, 10, 12, 14, 16, 18]) + tm.assert_index_equal(outer, outer2) + tm.assert_index_equal(outer, expected) + + inner = index.join(other, how="inner") + inner2 = other.join(index, how="inner") + expected = pd.Index([6, 8, 10]) + tm.assert_index_equal(inner, inner2) + tm.assert_index_equal(inner, expected) + + left = index.join(other, how="left") + tm.assert_index_equal(left, index) + + left2 = other.join(index, how="left") + tm.assert_index_equal(left2, other) + + right = index.join(other, how="right") + tm.assert_index_equal(right, other) + + right2 = other.join(index, how="right") + tm.assert_index_equal(right2, index) + + def test_join_non_unique(self): + index = pd.RangeIndex(start=0, stop=20, step=2) + other = pd.Index([4, 4, 3, 3]) + + res, lidx, ridx = index.join(other, return_indexers=True) + + eres = pd.Index([0, 2, 4, 4, 6, 8, 10, 12, 14, 16, 18]) + elidx = np.array([0, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.intp) + eridx = np.array([-1, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1], dtype=np.intp) + + tm.assert_index_equal(res, eres) + tm.assert_numpy_array_equal(lidx, elidx) + tm.assert_numpy_array_equal(ridx, eridx) + + def test_join_self(self, join_type): + index = pd.RangeIndex(start=0, stop=20, step=2) + joined = index.join(index, how=join_type) + assert index is joined + + +@pytest.mark.parametrize( + "left, right, expected, expected_lidx, expected_ridx, how", + [ + [pd.RangeIndex(2), pd.RangeIndex(3), pd.RangeIndex(2), None, [0, 1], "left"], + [pd.RangeIndex(2), pd.RangeIndex(2), pd.RangeIndex(2), None, None, "left"], + [ + pd.RangeIndex(2), + pd.RangeIndex(20, 22), + pd.RangeIndex(2), + None, + [-1, -1], + "left", + ], + [ + pd.RangeIndex(2), + pd.RangeIndex(3), + pd.RangeIndex(3), + [0, 1, -1], + None, + "right", + ], + [pd.RangeIndex(2), pd.RangeIndex(2), pd.RangeIndex(2), None, None, "right"], + [ + pd.RangeIndex(2), + pd.RangeIndex(20, 22), + pd.RangeIndex(20, 22), + [-1, -1], + None, + "right", + ], + [pd.RangeIndex(2), pd.RangeIndex(3), pd.RangeIndex(2), [0, 1], [0, 1], "inner"], + [pd.RangeIndex(2), pd.RangeIndex(2), pd.RangeIndex(2), None, None, "inner"], + [pd.RangeIndex(2), pd.RangeIndex(1, 3), pd.RangeIndex(1, 2), [1], [0], "inner"], + [ + pd.RangeIndex(2), + pd.RangeIndex(3), + pd.RangeIndex(3), + [0, 1, -1], + [0, 1, 2], + "outer", + ], + [pd.RangeIndex(2), pd.RangeIndex(2), pd.RangeIndex(2), None, None, "outer"], + [ + pd.RangeIndex(2), + pd.RangeIndex(2, 4), + pd.RangeIndex(4), + [0, 1, -1, -1], + [-1, -1, 0, 1], + "outer", + ], + [pd.RangeIndex(2), pd.RangeIndex(0), pd.RangeIndex(2), None, [-1, -1], "left"], + [pd.RangeIndex(2), pd.RangeIndex(0), pd.RangeIndex(0), [], None, "right"], + [pd.RangeIndex(2), pd.RangeIndex(0), pd.RangeIndex(0), [], None, "inner"], + [pd.RangeIndex(2), pd.RangeIndex(0), pd.RangeIndex(2), None, [-1, -1], "outer"], + ], +) +@pytest.mark.parametrize( + "right_type", [pd.RangeIndex, lambda x: pd.Index(list(x), dtype=x.dtype)] +) +def test_join_preserves_rangeindex( + left, right, expected, expected_lidx, expected_ridx, how, right_type +): + result, lidx, ridx = left.join(right_type(right), how=how, return_indexers=True) + tm.assert_index_equal(result, expected, exact=True) + + if expected_lidx is None: + assert lidx is expected_lidx + else: + exp_lidx = np.array(expected_lidx, dtype=np.intp) + tm.assert_numpy_array_equal(lidx, exp_lidx) + + if expected_ridx is None: + assert ridx is expected_ridx + else: + exp_ridx = np.array(expected_ridx, dtype=np.intp) + tm.assert_numpy_array_equal(ridx, exp_ridx) + + +def test_rangeindex_can_use_libjoin_is_false(): + # GH#54646 - RangeIndex should not use libjoin fastpath + # because _get_join_target allocates memory via np.arange + index = pd.RangeIndex(5) + assert not index._can_use_libjoin + + +def test_join_disjoint_rangeindexes_outer(): + # GH#54646 - outer join of disjoint RangeIndexes should be sorted + idx1 = pd.RangeIndex(3, 6) # [3, 4, 5] + idx2 = pd.RangeIndex(0, 3) # [0, 1, 2] + + result, lidx, ridx = idx1.join(idx2, how="outer", return_indexers=True) + + expected = pd.RangeIndex(0, 6) + tm.assert_index_equal(result, expected, exact=True) + exp_lidx = np.array([-1, -1, -1, 0, 1, 2], dtype=np.intp) + exp_ridx = np.array([0, 1, 2, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(lidx, exp_lidx) + tm.assert_numpy_array_equal(ridx, exp_ridx) + + +def test_join_overlapping_rangeindexes_outer(): + # GH#54646 + idx1 = pd.RangeIndex(0, 5) # [0, 1, 2, 3, 4] + idx2 = pd.RangeIndex(3, 8) # [3, 4, 5, 6, 7] + + result, lidx, ridx = idx1.join(idx2, how="outer", return_indexers=True) + + expected = pd.RangeIndex(0, 8) + tm.assert_index_equal(result, expected, exact=True) + exp_lidx = np.array([0, 1, 2, 3, 4, -1, -1, -1], dtype=np.intp) + exp_ridx = np.array([-1, -1, -1, 0, 1, 2, 3, 4], dtype=np.intp) + tm.assert_numpy_array_equal(lidx, exp_lidx) + tm.assert_numpy_array_equal(ridx, exp_ridx) + + +def test_join_rangeindex_with_int_index(): + # GH#54646 - RangeIndex join with non-RangeIndex should still work + idx1 = pd.RangeIndex(5) + idx2 = pd.Index(np.arange(3, 8, dtype=np.int64)) + + result, lidx, ridx = idx1.join(idx2, how="inner", return_indexers=True) + + expected = pd.RangeIndex(3, 5) + tm.assert_index_equal(result, expected, exact=True) + + +def test_join_rangeindex_self(): + # GH#54646 - joining a RangeIndex with itself should return self + index = pd.RangeIndex(10) + for how in ["left", "right", "inner", "outer"]: + result = index.join(index, how=how) + assert result is index + + +def test_join_rangeindex_unconvertible_fallback(): + # GH#54646 - when other cannot be converted to RangeIndex, + # RangeIndex._join_monotonic raises NotImplementedError and + # falls back to _join_via_get_indexer + idx1 = pd.RangeIndex(5) + idx2 = pd.Index([0, 1, 3, 7, 9], dtype=np.int64) # not a valid range + + result, lidx, ridx = idx1.join(idx2, how="inner", return_indexers=True) + + expected = pd.Index([0, 1, 3], dtype=np.int64) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_range.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_range.py new file mode 100644 index 0000000000000000000000000000000000000000..6fb6a35f657cc112dc24e69b81bac4636410212e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_range.py @@ -0,0 +1,966 @@ +import numpy as np +import pytest + +from pandas.core.dtypes.common import ensure_platform_int + +import pandas as pd +import pandas._testing as tm +import pandas.core.indexes.range as range_module +from pandas.core.indexes.range import min_fitting_element + + +class TestRangeIndex: + @pytest.fixture + def simple_index(self): + return pd.RangeIndex(start=0, stop=20, step=2) + + def test_constructor_unwraps_index(self): + result = pd.RangeIndex(1, 3) + expected = np.array([1, 2], dtype=np.int64) + 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_too_many_names(self, simple_index): + index = simple_index + with pytest.raises(ValueError, match="^Length"): + index.names = ["roger", "harold"] + + @pytest.mark.parametrize( + "index, start, stop, step", + [ + (pd.RangeIndex(5), 0, 5, 1), + (pd.RangeIndex(0, 5), 0, 5, 1), + (pd.RangeIndex(5, step=2), 0, 5, 2), + (pd.RangeIndex(1, 5, 2), 1, 5, 2), + ], + ) + def test_start_stop_step_attrs(self, index, start, stop, step): + # GH 25710 + assert index.start == start + assert index.stop == stop + assert index.step == step + + def test_copy(self): + i = pd.RangeIndex(5, name="Foo") + i_copy = i.copy() + assert i_copy is not i + assert i_copy.identical(i) + assert i_copy._range == range(0, 5, 1) + assert i_copy.name == "Foo" + + def test_repr(self): + i = pd.RangeIndex(5, name="Foo") + result = repr(i) + expected = "RangeIndex(start=0, stop=5, step=1, name='Foo')" + assert result == expected + + result = eval(result, dict(vars(pd))) + tm.assert_index_equal(result, i, exact=True) + + i = pd.RangeIndex(5, 0, -1) + result = repr(i) + expected = "RangeIndex(start=5, stop=0, step=-1)" + assert result == expected + + result = eval(result, dict(vars(pd))) + tm.assert_index_equal(result, i, exact=True) + + def test_repr_wraps_at_display_width(self): + # GH#11552 + idx = pd.RangeIndex(100, name="my_long_index_name") + + with pd.option_context("display.width", 40): + result = repr(idx) + expected = ( + "RangeIndex(start=0, stop=100, step=1,\n" + " name='my_long_index_name')" + ) + assert result == expected + + def test_insert(self): + idx = pd.RangeIndex(5, name="Foo") + result = idx[1:4] + + # test 0th element + tm.assert_index_equal(idx[0:4], result.insert(0, idx[0]), exact="equiv") + + # GH 18295 (test missing) + expected = pd.Index([0, np.nan, 1, 2, 3, 4], dtype=np.float64) + for na in [np.nan, None, pd.NA]: + result = pd.RangeIndex(5).insert(1, na) + tm.assert_index_equal(result, expected) + + result = pd.RangeIndex(5).insert(1, pd.NaT) + expected = pd.Index([0, pd.NaT, 1, 2, 3, 4], dtype=object) + tm.assert_index_equal(result, expected) + + def test_insert_edges_preserves_rangeindex(self): + idx = pd.Index(range(4, 9, 2)) + + result = idx.insert(0, 2) + expected = pd.Index(range(2, 9, 2)) + tm.assert_index_equal(result, expected, exact=True) + + result = idx.insert(3, 10) + expected = pd.Index(range(4, 11, 2)) + tm.assert_index_equal(result, expected, exact=True) + + def test_insert_middle_preserves_rangeindex(self): + # insert in the middle + idx = pd.Index(range(0, 3, 2)) + result = idx.insert(1, 1) + expected = pd.Index(range(3)) + tm.assert_index_equal(result, expected, exact=True) + + idx = idx * 2 + result = idx.insert(1, 2) + expected = expected * 2 + tm.assert_index_equal(result, expected, exact=True) + + def test_delete(self): + idx = pd.RangeIndex(5, name="Foo") + expected = idx[1:] + result = idx.delete(0) + tm.assert_index_equal(result, expected, exact=True) + assert result.name == expected.name + + expected = idx[:-1] + result = idx.delete(-1) + tm.assert_index_equal(result, expected, exact=True) + assert result.name == expected.name + + msg = "index 5 is out of bounds for axis 0 with size 5" + with pytest.raises((IndexError, ValueError), match=msg): + # either depending on numpy version + result = idx.delete(len(idx)) + + def test_delete_preserves_rangeindex(self): + idx = pd.Index(range(2), name="foo") + + result = idx.delete([1]) + expected = pd.Index(range(1), name="foo") + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(1) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_preserves_rangeindex_middle(self): + idx = pd.Index(range(3), name="foo") + result = idx.delete(1) + expected = idx[::2] + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(-2) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_preserves_rangeindex_list_at_end(self): + idx = pd.RangeIndex(0, 6, 1) + + loc = [2, 3, 4, 5] + result = idx.delete(loc) + expected = idx[:2] + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(loc[::-1]) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_preserves_rangeindex_list_middle(self): + idx = pd.RangeIndex(0, 6, 1) + + loc = [1, 2, 3, 4] + result = idx.delete(loc) + expected = pd.RangeIndex(0, 6, 5) + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(loc[::-1]) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_all_preserves_rangeindex(self): + idx = pd.RangeIndex(0, 6, 1) + + loc = [0, 1, 2, 3, 4, 5] + result = idx.delete(loc) + expected = idx[:0] + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(loc[::-1]) + tm.assert_index_equal(result, expected, exact=True) + + def test_delete_not_preserving_rangeindex(self): + idx = pd.RangeIndex(0, 6, 1) + + loc = [0, 3, 5] + result = idx.delete(loc) + expected = pd.Index([1, 2, 4]) + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(loc[::-1]) + tm.assert_index_equal(result, expected, exact=True) + + def test_view(self): + i = pd.RangeIndex(0, name="Foo") + i_view = i.view() + assert i_view.name == "Foo" + + i_view = i.view("i8") + tm.assert_numpy_array_equal(i.values, i_view) + + def test_dtype(self, simple_index): + index = simple_index + assert index.dtype == np.int64 + + def test_cache(self): + # GH 26565, GH26617, GH35432, GH53387 + # This test checks whether _cache has been set. + # Calling RangeIndex._cache["_data"] creates an int64 array of the same length + # as the RangeIndex and stores it in _cache. + idx = pd.RangeIndex(0, 100, 10) + + assert idx._cache == {} + + repr(idx) + assert idx._cache == {} + + str(idx) + assert idx._cache == {} + + idx.get_loc(20) + assert idx._cache == {} + + 90 in idx # True + assert idx._cache == {} + + 91 in idx # False + assert idx._cache == {} + + idx.all() + assert idx._cache == {} + + idx.any() + assert idx._cache == {} + + for _ in idx: + pass + assert idx._cache == {} + + df = pd.DataFrame({"a": range(10)}, index=idx) + + # df.__repr__ should not populate index cache + str(df) + assert idx._cache == {} + + df.loc[50] + assert idx._cache == {} + + with pytest.raises(KeyError, match="51"): + df.loc[51] + assert idx._cache == {} + + df.loc[10:50] + assert idx._cache == {} + + df.iloc[5:10] + assert idx._cache == {} + + # after calling take, _cache may contain other keys, but not "_data" + idx.take([3, 0, 1]) + assert "_data" not in idx._cache + + df.loc[[50]] + assert "_data" not in idx._cache + + df.iloc[[5, 6, 7, 8, 9]] + assert "_data" not in idx._cache + + # idx._cache should contain a _data entry after call to idx._data + idx._data + assert isinstance(idx._data, np.ndarray) + assert idx._data is idx._data # check cached value is reused + assert "_data" in idx._cache + expected = np.arange(0, 100, 10, dtype="int64") + tm.assert_numpy_array_equal(idx._cache["_data"], expected) + + def test_is_monotonic(self): + index = pd.RangeIndex(0, 20, 2) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is False + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is False + + index = pd.RangeIndex(4, 0, -1) + assert index.is_monotonic_increasing is False + assert index._is_strictly_monotonic_increasing is False + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_decreasing is True + + index = pd.RangeIndex(1, 2) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True + + index = pd.RangeIndex(2, 1) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True + + index = pd.RangeIndex(1, 1) + assert index.is_monotonic_increasing is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True + + @pytest.mark.parametrize( + "left,right", + [ + (pd.RangeIndex(0, 9, 2), pd.RangeIndex(0, 10, 2)), + (pd.RangeIndex(0), pd.RangeIndex(1, -1, 3)), + (pd.RangeIndex(1, 2, 3), pd.RangeIndex(1, 3, 4)), + (pd.RangeIndex(0, -9, -2), pd.RangeIndex(0, -10, -2)), + ], + ) + def test_equals_range(self, left, right): + assert left.equals(right) + assert right.equals(left) + + def test_logical_compat(self, simple_index): + idx = simple_index + assert idx.all() == idx.values.all() + assert idx.any() == idx.values.any() + + def test_identical(self, simple_index): + index = simple_index + i = pd.Index(index.copy()) + assert i.identical(index) + + # we don't allow object dtype for RangeIndex + if isinstance(index, pd.RangeIndex): + return + + same_values_different_type = pd.Index(i, dtype=object) + assert not i.identical(same_values_different_type) + + i = index.copy(dtype=object) + i = i.rename("foo") + same_values = pd.Index(i, dtype=object) + assert same_values.identical(index.copy(dtype=object)) + + assert not i.identical(index) + assert pd.Index(same_values, name="foo", dtype=object).identical(i) + + assert not index.copy(dtype=object).identical(index.copy(dtype="int64")) + + def test_nbytes(self): + # memory savings vs int index + idx = pd.RangeIndex(0, 1000) + assert idx.nbytes < pd.Index(idx._values).nbytes / 10 + + # constant memory usage + i2 = pd.RangeIndex(0, 10) + assert idx.nbytes == i2.nbytes + + def test_nbytes_pypy_compat(self, monkeypatch): + # GH#46176 sys.getsizeof always raises TypeError on PyPy unless + # a default is provided; nbytes must keep working there. + def pypy_getsizeof(obj, default=None): + if default is None: + raise TypeError("PyPy") + return default + + monkeypatch.setattr(range_module, "getsizeof", pypy_getsizeof) + idx = pd.RangeIndex(0, 1000) + assert isinstance(idx.nbytes, int) + assert idx.memory_usage() == idx.nbytes + + @pytest.mark.parametrize( + "start,stop,step", + [ + # can't + ("foo", "bar", "baz"), + # shouldn't + ("0", "1", "2"), + ], + ) + def test_cant_or_shouldnt_cast(self, start, stop, step): + msg = f"Wrong type {type(start)} for value {start}" + with pytest.raises(TypeError, match=msg): + pd.RangeIndex(start, stop, step) + + def test_view_index(self, simple_index): + index = simple_index + msg = "Cannot change data-type" + with pytest.raises(TypeError, match=msg): + index.view(pd.Index) + + def test_prevent_casting(self, simple_index): + index = simple_index + result = index.astype("O") + assert result.dtype == np.object_ + + def test_repr_roundtrip(self, simple_index): + index = simple_index + tm.assert_index_equal(eval(repr(index), dict(vars(pd))), index) + + def test_slice_keep_name(self): + idx = pd.RangeIndex(1, 2, name="asdf") + assert idx.name == idx[1:].name + + @pytest.mark.parametrize( + "index", + [ + pd.RangeIndex(start=0, stop=20, step=2, name="foo"), + pd.RangeIndex(start=18, stop=-1, step=-2, name="bar"), + ], + ids=["index_inc", "index_dec"], + ) + def test_has_duplicates(self, index): + assert index.is_unique + assert not index.has_duplicates + + def test_extended_gcd(self, simple_index): + index = simple_index + result = index._extended_gcd(6, 10) + assert result[0] == result[1] * 6 + result[2] * 10 + assert 2 == result[0] + + result = index._extended_gcd(10, 6) + assert 2 == result[1] * 10 + result[2] * 6 + assert 2 == result[0] + + def test_min_fitting_element(self): + result = min_fitting_element(0, 2, 1) + assert 2 == result + + result = min_fitting_element(1, 1, 1) + assert 1 == result + + result = min_fitting_element(18, -2, 1) + assert 2 == result + + result = min_fitting_element(5, -1, 1) + assert 1 == result + + big_num = 500000000000000000000000 + + result = min_fitting_element(5, 1, big_num) + assert big_num == result + + def test_slice_specialised(self, simple_index): + index = simple_index + index.name = "foo" + + # scalar indexing + res = index[1] + expected = 2 + assert res == expected + + res = index[-1] + expected = 18 + assert res == expected + + # slicing + # slice value completion + index_slice = index[:] + expected = index + tm.assert_index_equal(index_slice, expected) + + # positive slice values + index_slice = index[7:10:2] + expected = pd.Index([14, 18], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + # negative slice values + index_slice = index[-1:-5:-2] + expected = pd.Index([18, 14], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + # stop overshoot + index_slice = index[2:100:4] + expected = pd.Index([4, 12], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + # reverse + index_slice = index[::-1] + expected = pd.Index(index.values[::-1], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + index_slice = index[-8::-1] + expected = pd.Index([4, 2, 0], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + index_slice = index[-40::-1] + expected = pd.Index(np.array([], dtype=np.int64), name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + index_slice = index[40::-1] + expected = pd.Index(index.values[40::-1], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + index_slice = index[10::-1] + expected = pd.Index(index.values[::-1], name="foo") + tm.assert_index_equal(index_slice, expected, exact="equiv") + + @pytest.mark.parametrize("step", set(range(-5, 6)) - {0}) + def test_len_specialised(self, step): + # make sure that our len is the same as np.arange calc + start, stop = (0, 5) if step > 0 else (5, 0) + + arr = np.arange(start, stop, step) + index = pd.RangeIndex(start, stop, step) + assert len(index) == len(arr) + + index = pd.RangeIndex(stop, start, step) + assert len(index) == 0 + + @pytest.mark.parametrize( + "indices, expected", + [ + ([pd.RangeIndex(1, 12, 5)], pd.RangeIndex(1, 12, 5)), + ([pd.RangeIndex(0, 6, 4)], pd.RangeIndex(0, 6, 4)), + ([pd.RangeIndex(1, 3), pd.RangeIndex(3, 7)], pd.RangeIndex(1, 7)), + ([pd.RangeIndex(1, 5, 2), pd.RangeIndex(5, 6)], pd.RangeIndex(1, 6, 2)), + ([pd.RangeIndex(1, 3, 2), pd.RangeIndex(4, 7, 3)], pd.RangeIndex(1, 7, 3)), + ( + [pd.RangeIndex(-4, 3, 2), pd.RangeIndex(4, 7, 2)], + pd.RangeIndex(-4, 7, 2), + ), + ([pd.RangeIndex(-4, -8), pd.RangeIndex(-8, -12)], pd.RangeIndex(0, 0)), + ([pd.RangeIndex(-4, -8), pd.RangeIndex(3, -4)], pd.RangeIndex(0, 0)), + ([pd.RangeIndex(-4, -8), pd.RangeIndex(3, 5)], pd.RangeIndex(3, 5)), + ([pd.RangeIndex(-4, -2), pd.RangeIndex(3, 5)], pd.Index([-4, -3, 3, 4])), + ([pd.RangeIndex(-2), pd.RangeIndex(3, 5)], pd.RangeIndex(3, 5)), + ([pd.RangeIndex(2), pd.RangeIndex(2)], pd.Index([0, 1, 0, 1])), + ( + [pd.RangeIndex(2), pd.RangeIndex(2, 5), pd.RangeIndex(5, 8, 4)], + pd.RangeIndex(0, 6), + ), + ( + [pd.RangeIndex(2), pd.RangeIndex(3, 5), pd.RangeIndex(5, 8, 4)], + pd.Index([0, 1, 3, 4, 5]), + ), + ( + [pd.RangeIndex(-2, 2), pd.RangeIndex(2, 5), pd.RangeIndex(5, 8, 4)], + pd.RangeIndex(-2, 6), + ), + ([pd.RangeIndex(3), pd.Index([-1, 3, 15])], pd.Index([0, 1, 2, -1, 3, 15])), + ( + [pd.RangeIndex(3), pd.Index([-1, 3.1, 15.0])], + pd.Index([0, 1, 2, -1, 3.1, 15.0]), + ), + ( + [pd.RangeIndex(3), pd.Index(["a", None, 14])], + pd.Index([0, 1, 2, "a", None, 14]), + ), + ( + [pd.RangeIndex(3, 1), pd.Index(["a", None, 14])], + pd.Index(["a", None, 14]), + ), + ], + ) + def test_append(self, indices, expected): + # GH16212 + result = indices[0].append(indices[1:]) + tm.assert_index_equal(result, expected, exact=True) + + if len(indices) == 2: + # Append single item rather than list + result2 = indices[0].append(indices[1]) + tm.assert_index_equal(result2, expected, exact=True) + + def test_engineless_lookup(self): + # GH 16685 + # Standard lookup on RangeIndex should not require the engine to be + # created + idx = pd.RangeIndex(2, 10, 3) + + assert idx.get_loc(5) == 1 + tm.assert_numpy_array_equal( + idx.get_indexer([2, 8]), ensure_platform_int(np.array([0, 2])) + ) + with pytest.raises(KeyError, match="3"): + idx.get_loc(3) + + assert "_engine" not in idx._cache + + # Different types of scalars can be excluded immediately, no need to + # use the _engine + with pytest.raises(KeyError, match="'a'"): + idx.get_loc("a") + + assert "_engine" not in idx._cache + + @pytest.mark.parametrize( + "ri", + [ + pd.RangeIndex(0, -1, -1), + pd.RangeIndex(0, 1, 1), + pd.RangeIndex(1, 3, 2), + pd.RangeIndex(0, -1, -2), + pd.RangeIndex(-3, -5, -2), + ], + ) + def test_append_len_one(self, ri): + # GH39401 + result = ri.append([]) + tm.assert_index_equal(result, ri, exact=True) + + @pytest.mark.parametrize("base", [pd.RangeIndex(0, 2), pd.Index([0, 1])]) + def test_isin_range(self, base): + # GH#41151 + values = pd.RangeIndex(0, 1) + result = base.isin(values) + expected = np.array([True, False]) + tm.assert_numpy_array_equal(result, expected) + + def test_sort_values_key(self): + # GH#43666, GH#52764 + sort_order = {8: 2, 6: 0, 4: 8, 2: 10, 0: 12} + values = pd.RangeIndex(0, 10, 2) + result = values.sort_values(key=lambda x: x.map(sort_order)) + expected = pd.Index([6, 8, 4, 2, 0], dtype="int64") + tm.assert_index_equal(result, expected, check_exact=True) + + # check this matches the Series.sort_values behavior + ser = values.to_series() + result2 = ser.sort_values(key=lambda x: x.map(sort_order)) + tm.assert_series_equal(result2, expected.to_series(), check_exact=True) + + def test_range_index_rsub_by_const(self): + # GH#53255 + result = 3 - pd.RangeIndex(0, 4, 1) + expected = pd.RangeIndex(3, -1, -1) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "rng, decimals", + [ + [range(5), 0], + [range(5), 2], + [range(10, 30, 10), -1], + [range(30, 10, -10), -1], + ], +) +def test_range_round_returns_rangeindex(rng, decimals): + ri = pd.RangeIndex(rng) + expected = ri.copy() + result = ri.round(decimals=decimals) + tm.assert_index_equal(result, expected, exact=True) + + +@pytest.mark.parametrize( + "rng, decimals", + [ + [range(10, 30, 1), -1], + [range(30, 10, -1), -1], + [range(11, 14), -10], + ], +) +def test_range_round_returns_index(rng, decimals): + ri = pd.RangeIndex(rng) + expected = pd.Index(list(rng)).round(decimals=decimals) + result = ri.round(decimals=decimals) + tm.assert_index_equal(result, expected, exact=True) + + +def test_reindex_1_value_returns_rangeindex(): + ri = pd.RangeIndex(0, 10, 2, name="foo") + result, result_indexer = ri.reindex([2]) + expected = pd.RangeIndex(2, 4, 2, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + expected_indexer = np.array([1], dtype=np.intp) + tm.assert_numpy_array_equal(result_indexer, expected_indexer) + + +def test_reindex_empty_returns_rangeindex(): + ri = pd.RangeIndex(0, 10, 2, name="foo") + result, result_indexer = ri.reindex([]) + expected = pd.RangeIndex(0, 0, 2, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + expected_indexer = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(result_indexer, expected_indexer) + + +def test_insert_empty_0_loc(): + ri = pd.RangeIndex(0, step=10, name="foo") + result = ri.insert(0, 5) + expected = pd.RangeIndex(5, 15, 10, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +def test_append_non_rangeindex_return_rangeindex(): + ri = pd.RangeIndex(1) + result = ri.append(pd.Index([1])) + expected = pd.RangeIndex(2) + tm.assert_index_equal(result, expected, exact=True) + + +def test_append_non_rangeindex_return_index(): + ri = pd.RangeIndex(1) + result = ri.append(pd.Index([1, 3, 4])) + expected = pd.Index([0, 1, 3, 4]) + tm.assert_index_equal(result, expected, exact=True) + + +def test_reindex_returns_rangeindex(): + ri = pd.RangeIndex(2, name="foo") + result, result_indexer = ri.reindex([1, 2, 3]) + expected = pd.RangeIndex(1, 4, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + expected_indexer = np.array([1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result_indexer, expected_indexer) + + +def test_reindex_returns_index(): + ri = pd.RangeIndex(4, name="foo") + result, result_indexer = ri.reindex([0, 1, 3]) + expected = pd.Index([0, 1, 3], name="foo") + tm.assert_index_equal(result, expected, exact=True) + + expected_indexer = np.array([0, 1, 3], dtype=np.intp) + tm.assert_numpy_array_equal(result_indexer, expected_indexer) + + +def test_take_return_rangeindex(): + ri = pd.RangeIndex(5, name="foo") + result = ri.take([]) + expected = pd.RangeIndex(0, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + result = ri.take([3, 4]) + expected = pd.RangeIndex(3, 5, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +def test__getitem__boolean_numpyextensionarray(): + ri = pd.RangeIndex(1) + result = ri[pd.arrays.NumpyExtensionArray(np.array([True]))] + tm.assert_index_equal(ri, result) + + +@pytest.mark.parametrize( + "container", + [np.array, pd.Series, lambda x: pd.arrays.NumpyExtensionArray(np.array(x))], + ids=["numpy-array", "series", "numpy-extension-array"], +) +def test__getitem__boolean_arraylike(container): + ri = pd.RangeIndex(5) + result = ri[container([True, True, False, False, True])] + expected = pd.Index([0, 1, 4], dtype="int64") + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "rng, exp_rng", + [ + [range(5), range(3, 4)], + [range(0, -10, -2), range(-6, -8, -2)], + [range(0, 10, 2), range(6, 8, 2)], + ], +) +def test_take_1_value_returns_rangeindex(rng, exp_rng): + ri = pd.RangeIndex(rng, name="foo") + result = ri.take([3]) + expected = pd.RangeIndex(exp_rng, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +def test_append_one_nonempty_preserve_step(): + expected = pd.RangeIndex(0, -1, -1) + result = pd.RangeIndex(0).append([expected]) + tm.assert_index_equal(result, expected, exact=True) + + +def test_getitem_boolmask_all_true(): + ri = pd.RangeIndex(3, name="foo") + expected = ri.copy() + result = ri[[True] * 3] + tm.assert_index_equal(result, expected, exact=True) + + +def test_getitem_boolmask_all_false(): + ri = pd.RangeIndex(3, name="foo") + result = ri[[False] * 3] + expected = pd.RangeIndex(0, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +def test_getitem_boolmask_returns_rangeindex(): + ri = pd.RangeIndex(3, name="foo") + result = ri[[False, True, True]] + expected = pd.RangeIndex(1, 3, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + result = ri[[True, False, True]] + expected = pd.RangeIndex(0, 3, 2, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +def test_getitem_boolmask_returns_index(): + ri = pd.RangeIndex(4, name="foo") + result = ri[[True, True, False, True]] + expected = pd.Index([0, 1, 3], name="foo") + tm.assert_index_equal(result, expected) + + +def test_getitem_boolmask_wrong_length(): + ri = pd.RangeIndex(4, name="foo") + with pytest.raises(IndexError, match="Boolean index has wrong length"): + ri[[True]] + + +def test_pos_returns_rangeindex(): + ri = pd.RangeIndex(2, name="foo") + expected = ri.copy() + result = +ri + tm.assert_index_equal(result, expected, exact=True) + + +def test_neg_returns_rangeindex(): + ri = pd.RangeIndex(2, name="foo") + result = -ri + expected = pd.RangeIndex(0, -2, -1, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + ri = pd.RangeIndex(-2, 2, name="foo") + result = -ri + expected = pd.RangeIndex(2, -2, -1, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +@pytest.mark.parametrize( + "rng, exp_rng", + [ + [range(0), range(0)], + [range(10), range(10)], + [range(-2, 1, 1), range(2, -1, -1)], + [range(0, -10, -1), range(0, 10, 1)], + ], +) +def test_abs_returns_rangeindex(rng, exp_rng): + ri = pd.RangeIndex(rng, name="foo") + expected = pd.RangeIndex(exp_rng, name="foo") + result = abs(ri) + tm.assert_index_equal(result, expected, exact=True) + + +def test_abs_returns_index(): + ri = pd.RangeIndex(-2, 2, name="foo") + result = abs(ri) + expected = pd.Index([2, 1, 0, 1], name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +@pytest.mark.parametrize( + "rng", + [ + range(0), + range(5), + range(0, -5, -1), + range(-2, 2, 1), + range(2, -2, -2), + range(0, 5, 2), + ], +) +def test_invert_returns_rangeindex(rng): + ri = pd.RangeIndex(rng, name="foo") + result = ~ri + assert isinstance(result, pd.RangeIndex) + expected = ~pd.Index(list(rng), name="foo") + tm.assert_index_equal(result, expected, exact=False) + + +@pytest.mark.parametrize( + "rng", + [ + range(0, 5, 1), + range(0, 5, 2), + range(10, 15, 1), + range(10, 5, -1), + range(10, 5, -2), + range(5, 0, -1), + ], +) +@pytest.mark.parametrize("meth", ["argmax", "argmin"]) +def test_arg_min_max(rng, meth): + ri = pd.RangeIndex(rng) + idx = pd.Index(list(rng)) + assert getattr(ri, meth)() == getattr(idx, meth)() + + +@pytest.mark.parametrize("meth", ["argmin", "argmax"]) +def test_empty_argmin_argmax_raises(meth): + with pytest.raises(ValueError, match=f"attempt to get {meth} of an empty sequence"): + getattr(pd.RangeIndex(0), meth)() + + +def test_getitem_integers_return_rangeindex(): + result = pd.RangeIndex(0, 10, 2, name="foo")[[0, -1]] + expected = pd.RangeIndex(start=0, stop=16, step=8, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + result = pd.RangeIndex(0, 10, 2, name="foo")[[3]] + expected = pd.RangeIndex(start=6, stop=8, step=2, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +def test_getitem_empty_return_rangeindex(): + result = pd.RangeIndex(0, 10, 2, name="foo")[[]] + expected = pd.RangeIndex(start=0, stop=0, step=1, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +def test_getitem_integers_return_index(): + result = pd.RangeIndex(0, 10, 2, name="foo")[[0, 1, -1]] + expected = pd.Index([0, 2, 8], dtype="int64", name="foo") + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("normalize", [True, False]) +@pytest.mark.parametrize( + "rng", + [ + range(3), + range(0), + range(0, 3, 2), + range(3, -3, -2), + ], +) +def test_value_counts(sort, dropna, ascending, normalize, rng): + ri = pd.RangeIndex(rng, name="A") + result = ri.value_counts( + normalize=normalize, sort=sort, ascending=ascending, dropna=dropna + ) + expected = pd.Index(list(rng), name="A").value_counts( + normalize=normalize, sort=sort, ascending=ascending, dropna=dropna + ) + tm.assert_series_equal(result, expected, check_index_type=False) + + +@pytest.mark.parametrize("side", ["left", "right"]) +@pytest.mark.parametrize("value", [0, -5, 5, -3, np.array([-5, -3, 0, 5])]) +def test_searchsorted(side, value, using_python_scalars): + ri = pd.RangeIndex(-3, 3, 2) + result = ri.searchsorted(value=value, side=side) + expected = pd.Index(list(ri)).searchsorted(value=value, side=side) + if isinstance(value, int): + assert result == expected + # GH#64266 + if using_python_scalars: + assert type(result) is int + else: + assert isinstance(result, np.integer) + else: + tm.assert_numpy_array_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_setops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..b83a62267582ae05140d2db2794e4330041fb42f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/ranges/test_setops.py @@ -0,0 +1,517 @@ +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestRangeIndexSetOps: + @pytest.mark.parametrize("dtype", [None, "int64", "uint64"]) + def test_intersection_mismatched_dtype(self, dtype): + # check that we cast to float, not object + index = pd.RangeIndex(start=0, stop=20, step=2, name="foo") + index = pd.Index(index, dtype=dtype) + + flt = index.astype(np.float64) + + # bc index.equals(flt), we go through fastpath and get RangeIndex back + result = index.intersection(flt) + tm.assert_index_equal(result, index, exact=True) + + result = flt.intersection(index) + tm.assert_index_equal(result, flt, exact=True) + + # neither empty, not-equals + result = index.intersection(flt[1:]) + tm.assert_index_equal(result, flt[1:], exact=True) + + result = flt[1:].intersection(index) + tm.assert_index_equal(result, flt[1:], exact=True) + + # empty other + result = index.intersection(flt[:0]) + tm.assert_index_equal(result, flt[:0], exact=True) + + result = flt[:0].intersection(index) + tm.assert_index_equal(result, flt[:0], exact=True) + + def test_intersection_empty(self, sort, names): + # name retention on empty intersections + index = pd.RangeIndex(start=0, stop=20, step=2, name=names[0]) + + # empty other + result = index.intersection(index[:0].rename(names[1]), sort=sort) + tm.assert_index_equal(result, index[:0].rename(names[2]), exact=True) + + # empty self + result = index[:0].intersection(index.rename(names[1]), sort=sort) + tm.assert_index_equal(result, index[:0].rename(names[2]), exact=True) + + def test_intersection(self, sort): + # intersect with Index with dtype int64 + index = pd.RangeIndex(start=0, stop=20, step=2) + other = pd.Index(np.arange(1, 6)) + result = index.intersection(other, sort=sort) + expected = pd.Index(np.sort(np.intersect1d(index.values, other.values))) + tm.assert_index_equal(result, expected, exact="equiv") + + result = other.intersection(index, sort=sort) + expected = pd.Index( + np.sort(np.asarray(np.intersect1d(index.values, other.values))) + ) + tm.assert_index_equal(result, expected) + + # intersect with increasing RangeIndex + other = pd.RangeIndex(1, 6) + result = index.intersection(other, sort=sort) + expected = pd.Index(np.sort(np.intersect1d(index.values, other.values))) + tm.assert_index_equal(result, expected, exact="equiv") + + # intersect with decreasing RangeIndex + other = pd.RangeIndex(5, 0, -1) + result = index.intersection(other, sort=sort) + expected = pd.Index(np.sort(np.intersect1d(index.values, other.values))) + tm.assert_index_equal(result, expected, exact="equiv") + + # reversed (GH 17296) + result = other.intersection(index, sort=sort) + tm.assert_index_equal(result, expected, exact="equiv") + + # GH 17296: intersect two decreasing RangeIndexes + first = pd.RangeIndex(10, -2, -2) + other = pd.RangeIndex(5, -4, -1) + expected = pd.RangeIndex(start=4, stop=-2, step=-2) + result = first.intersection(other, sort=sort) + tm.assert_index_equal(result, expected) + + # reversed + result = other.intersection(first, sort=sort) + tm.assert_index_equal(result, expected) + + index = pd.RangeIndex(5, name="foo") + + # intersect of non-overlapping indices + other = pd.RangeIndex(5, 10, 1, name="foo") + result = index.intersection(other, sort=sort) + expected = pd.RangeIndex(0, 0, 1, name="foo") + tm.assert_index_equal(result, expected) + + other = pd.RangeIndex(-1, -5, -1) + result = index.intersection(other, sort=sort) + expected = pd.RangeIndex(0, 0, 1) + tm.assert_index_equal(result, expected) + + # intersection of empty indices + other = pd.RangeIndex(0, 0, 1) + result = index.intersection(other, sort=sort) + expected = pd.RangeIndex(0, 0, 1) + tm.assert_index_equal(result, expected) + + result = other.intersection(index, sort=sort) + tm.assert_index_equal(result, expected) + + def test_intersection_non_overlapping_gcd(self, sort, names): + # intersection of non-overlapping values based on start value and gcd + index = pd.RangeIndex(1, 10, 2, name=names[0]) + other = pd.RangeIndex(0, 10, 4, name=names[1]) + result = index.intersection(other, sort=sort) + expected = pd.RangeIndex(0, 0, 1, name=names[2]) + tm.assert_index_equal(result, expected) + + def test_union_noncomparable(self, sort): + # corner case, Index with non-int64 dtype + index = pd.RangeIndex(start=0, stop=20, step=2) + other = pd.Index( + [datetime(2011, 1, 1) + timedelta(i) for i in range(4)], dtype=object + ) + result = index.union(other, sort=sort) + expected = pd.Index(np.concatenate((index, other))) + tm.assert_index_equal(result, expected) + + result = other.union(index, sort=sort) + expected = pd.Index(np.concatenate((other, index))) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "idx1, idx2, expected_sorted, expected_notsorted", + [ + ( + pd.RangeIndex(0, 10, 1), + pd.RangeIndex(0, 10, 1), + pd.RangeIndex(0, 10, 1), + pd.RangeIndex(0, 10, 1), + ), + ( + pd.RangeIndex(0, 10, 1), + pd.RangeIndex(5, 20, 1), + pd.RangeIndex(0, 20, 1), + pd.RangeIndex(0, 20, 1), + ), + ( + pd.RangeIndex(0, 10, 1), + pd.RangeIndex(10, 20, 1), + pd.RangeIndex(0, 20, 1), + pd.RangeIndex(0, 20, 1), + ), + ( + pd.RangeIndex(0, -10, -1), + pd.RangeIndex(0, -10, -1), + pd.RangeIndex(0, -10, -1), + pd.RangeIndex(0, -10, -1), + ), + ( + pd.RangeIndex(0, -10, -1), + pd.RangeIndex(-10, -20, -1), + pd.RangeIndex(-19, 1, 1), + pd.RangeIndex(0, -20, -1), + ), + ( + pd.RangeIndex(0, 10, 2), + pd.RangeIndex(1, 10, 2), + pd.RangeIndex(0, 10, 1), + pd.Index(list(range(0, 10, 2)) + list(range(1, 10, 2))), + ), + ( + pd.RangeIndex(0, 11, 2), + pd.RangeIndex(1, 12, 2), + pd.RangeIndex(0, 12, 1), + pd.Index(list(range(0, 11, 2)) + list(range(1, 12, 2))), + ), + ( + pd.RangeIndex(0, 21, 4), + pd.RangeIndex(-2, 24, 4), + pd.RangeIndex(-2, 24, 2), + pd.Index(list(range(0, 21, 4)) + list(range(-2, 24, 4))), + ), + ( + pd.RangeIndex(0, -20, -2), + pd.RangeIndex(-1, -21, -2), + pd.RangeIndex(-19, 1, 1), + pd.Index(list(range(0, -20, -2)) + list(range(-1, -21, -2))), + ), + ( + pd.RangeIndex(0, 100, 5), + pd.RangeIndex(0, 100, 20), + pd.RangeIndex(0, 100, 5), + pd.RangeIndex(0, 100, 5), + ), + ( + pd.RangeIndex(0, -100, -5), + pd.RangeIndex(5, -100, -20), + pd.RangeIndex(-95, 10, 5), + pd.Index([*list(range(0, -100, -5)), 5]), + ), + ( + pd.RangeIndex(0, -11, -1), + pd.RangeIndex(1, -12, -4), + pd.RangeIndex(-11, 2, 1), + pd.Index([*list(range(0, -11, -1)), 1, -11]), + ), + (pd.RangeIndex(0), pd.RangeIndex(0), pd.RangeIndex(0), pd.RangeIndex(0)), + ( + pd.RangeIndex(0, -10, -2), + pd.RangeIndex(0), + pd.RangeIndex(0, -10, -2), + pd.RangeIndex(0, -10, -2), + ), + ( + pd.RangeIndex(0, 100, 2), + pd.RangeIndex(100, 150, 200), + pd.RangeIndex(0, 102, 2), + pd.RangeIndex(0, 102, 2), + ), + ( + pd.RangeIndex(0, -100, -2), + pd.RangeIndex(-100, 50, 102), + pd.RangeIndex(-100, 4, 2), + pd.Index([*list(range(0, -100, -2)), -100, 2]), + ), + ( + pd.RangeIndex(0, -100, -1), + pd.RangeIndex(0, -50, -3), + pd.RangeIndex(-99, 1, 1), + pd.RangeIndex(0, -100, -1), + ), + ( + pd.RangeIndex(0, 1, 1), + pd.RangeIndex(5, 6, 10), + pd.RangeIndex(0, 6, 5), + pd.RangeIndex(0, 10, 5), + ), + ( + pd.RangeIndex(0, 10, 5), + pd.RangeIndex(-5, -6, -20), + pd.RangeIndex(-5, 10, 5), + pd.Index([0, 5, -5]), + ), + ( + pd.RangeIndex(0, 3, 1), + pd.RangeIndex(4, 5, 1), + pd.Index([0, 1, 2, 4]), + pd.Index([0, 1, 2, 4]), + ), + ( + pd.RangeIndex(0, 10, 1), + pd.Index([], dtype=np.int64), + pd.RangeIndex(0, 10, 1), + pd.RangeIndex(0, 10, 1), + ), + ( + pd.RangeIndex(0), + pd.Index([1, 5, 6]), + pd.Index([1, 5, 6]), + pd.Index([1, 5, 6]), + ), + # GH 43885 + ( + pd.RangeIndex(0, 10), + pd.RangeIndex(0, 5), + pd.RangeIndex(0, 10), + pd.RangeIndex(0, 10), + ), + ], + ids=lambda x: repr(x) if isinstance(x, pd.RangeIndex) else x, + ) + def test_union_sorted(self, idx1, idx2, expected_sorted, expected_notsorted): + res1 = idx1.union(idx2, sort=None) + tm.assert_index_equal(res1, expected_sorted, exact=True) + + res1 = idx1.union(idx2, sort=False) + tm.assert_index_equal(res1, expected_notsorted, exact=True) + + res2 = idx2.union(idx1, sort=None) + res3 = pd.Index(idx1._values, name=idx1.name).union(idx2, sort=None) + tm.assert_index_equal(res2, expected_sorted, exact=True) + tm.assert_index_equal(res3, expected_sorted, exact="equiv") + + def test_union_same_step_misaligned(self): + # GH#44019 + left = pd.RangeIndex(range(0, 20, 4)) + right = pd.RangeIndex(range(1, 21, 4)) + + result = left.union(right) + expected = pd.Index([0, 1, 4, 5, 8, 9, 12, 13, 16, 17]) + tm.assert_index_equal(result, expected, exact=True) + + def test_difference(self): + # GH#12034 Cases where we operate against another RangeIndex and may + # get back another RangeIndex + obj = pd.RangeIndex.from_range(range(1, 10), name="foo") + + result = obj.difference(obj) + expected = pd.RangeIndex.from_range(range(0), name="foo") + tm.assert_index_equal(result, expected, exact=True) + + result = obj.difference(expected.rename("bar")) + tm.assert_index_equal(result, obj.rename(None), exact=True) + + result = obj.difference(obj[:3]) + tm.assert_index_equal(result, obj[3:], exact=True) + + result = obj.difference(obj[-3:]) + tm.assert_index_equal(result, obj[:-3], exact=True) + + # Flipping the step of 'other' doesn't affect the result, but + # flipping the stepof 'self' does when sort=None + result = obj[::-1].difference(obj[-3:]) + tm.assert_index_equal(result, obj[:-3], exact=True) + + result = obj[::-1].difference(obj[-3:], sort=False) + tm.assert_index_equal(result, obj[:-3][::-1], exact=True) + + result = obj[::-1].difference(obj[-3:][::-1]) + tm.assert_index_equal(result, obj[:-3], exact=True) + + result = obj[::-1].difference(obj[-3:][::-1], sort=False) + tm.assert_index_equal(result, obj[:-3][::-1], exact=True) + + result = obj.difference(obj[2:6]) + expected = pd.Index([1, 2, 7, 8, 9], name="foo") + tm.assert_index_equal(result, expected, exact=True) + + def test_difference_sort(self): + # GH#44085 ensure we respect the sort keyword + + idx = pd.Index(range(4))[::-1] + other = pd.Index(range(3, 4)) + + result = idx.difference(other) + expected = pd.Index(range(3)) + tm.assert_index_equal(result, expected, exact=True) + + result = idx.difference(other, sort=False) + expected = expected[::-1] + tm.assert_index_equal(result, expected, exact=True) + + # case where the intersection is empty + other = range(10, 12) + result = idx.difference(other, sort=None) + expected = idx[::-1] + tm.assert_index_equal(result, expected, exact=True) + + def test_difference_mismatched_step(self): + obj = pd.RangeIndex.from_range(range(1, 10), name="foo") + + result = obj.difference(obj[::2]) + expected = obj[1::2] + tm.assert_index_equal(result, expected, exact=True) + + result = obj[::-1].difference(obj[::2], sort=False) + tm.assert_index_equal(result, expected[::-1], exact=True) + + result = obj.difference(obj[1::2]) + expected = obj[::2] + tm.assert_index_equal(result, expected, exact=True) + + result = obj[::-1].difference(obj[1::2], sort=False) + tm.assert_index_equal(result, expected[::-1], exact=True) + + def test_difference_interior_overlap_endpoints_preserved(self): + left = pd.RangeIndex(range(4)) + right = pd.RangeIndex(range(1, 3)) + + result = left.difference(right) + expected = pd.RangeIndex(0, 4, 3) + assert expected.tolist() == [0, 3] + tm.assert_index_equal(result, expected, exact=True) + + def test_difference_endpoints_overlap_interior_preserved(self): + left = pd.RangeIndex(-8, 20, 7) + right = pd.RangeIndex(13, -9, -3) + + result = left.difference(right) + expected = pd.RangeIndex(-1, 13, 7) + assert expected.tolist() == [-1, 6] + tm.assert_index_equal(result, expected, exact=True) + + def test_difference_interior_non_preserving(self): + # case with intersection of length 1 but RangeIndex is not preserved + idx = pd.Index(range(10)) + + other = idx[3:4] + result = idx.difference(other) + expected = pd.Index([0, 1, 2, 4, 5, 6, 7, 8, 9]) + tm.assert_index_equal(result, expected, exact=True) + + # case with other.step / self.step > 2 + other = idx[::3] + result = idx.difference(other) + expected = pd.Index([1, 2, 4, 5, 7, 8]) + tm.assert_index_equal(result, expected, exact=True) + + # cases with only reaching one end of left + obj = pd.Index(range(20)) + other = obj[:10:2] + result = obj.difference(other) + expected = pd.Index([1, 3, 5, 7, 9, *list(range(10, 20))]) + tm.assert_index_equal(result, expected, exact=True) + + other = obj[1:11:2] + result = obj.difference(other) + expected = pd.Index([0, 2, 4, 6, 8, 10, *list(range(11, 20))]) + tm.assert_index_equal(result, expected, exact=True) + + def test_symmetric_difference(self): + # GH#12034 Cases where we operate against another RangeIndex and may + # get back another RangeIndex + left = pd.RangeIndex.from_range(range(1, 10), name="foo") + + result = left.symmetric_difference(left) + expected = pd.RangeIndex.from_range(range(0), name="foo") + tm.assert_index_equal(result, expected) + + result = left.symmetric_difference(expected.rename("bar")) + tm.assert_index_equal(result, left.rename(None)) + + result = left[:-2].symmetric_difference(left[2:]) + expected = pd.Index([1, 2, 8, 9], name="foo") + tm.assert_index_equal(result, expected, exact=True) + + right = pd.RangeIndex.from_range(range(10, 15)) + + result = left.symmetric_difference(right) + expected = pd.RangeIndex.from_range(range(1, 15)) + tm.assert_index_equal(result, expected) + + result = left.symmetric_difference(right[1:]) + expected = pd.Index([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]) + tm.assert_index_equal(result, expected, exact=True) + + def test_symmetric_difference_descending(self): + # GH#68264 the result was returned in descending order instead of + # sorted when one side was an empty RangeIndex and the surviving + # side was a negative-step RangeIndex + left = pd.RangeIndex(-2, -5, -2) + empty = pd.RangeIndex(0, 0) + + result = left.symmetric_difference(empty) + expected = pd.RangeIndex(-4, 0, 2) + tm.assert_index_equal(result, expected, exact=True) + + result = empty.symmetric_difference(left) + expected = pd.RangeIndex(-4, 0, 2) + tm.assert_index_equal(result, expected, exact=True) + + result = left.symmetric_difference(pd.RangeIndex(0)) + expected = pd.RangeIndex(-4, 0, 2) + tm.assert_index_equal(result, expected, exact=True) + + +def assert_range_or_not_is_rangelike(index): + """ + Check that we either have a RangeIndex or that this index *cannot* + be represented as a RangeIndex. + """ + if not isinstance(index, pd.RangeIndex) and len(index) > 0: + diff = index[:-1] - index[1:] + assert not (diff == diff[0]).all() + + +RANGE_SPECS = [ + (0, 10, 1), + (10, 0, -1), + (-20, 20, 5), + (20, -20, -5), + (1, 1, 1), + (-5, 5, 2), + (0, 20, 3), + (5, -5, -2), + (0, 6, 2), + (2, 3, 1), + (-8, 20, 7), + (13, -9, -3), + (0, 4, 1), + (1, 3, 1), + (0, 10, 2), + (1, 10, 2), +] + + +@pytest.mark.parametrize("start1,stop1,step1", RANGE_SPECS) +@pytest.mark.parametrize("start2,stop2,step2", RANGE_SPECS) +def test_range_difference(start1, stop1, step1, start2, stop2, step2): + # test that + # a) we match Index[int64].difference and + # b) we return RangeIndex whenever it is possible to do so. + left = pd.RangeIndex(start1, stop1, step1) + right = pd.RangeIndex(start2, stop2, step2) + + result = left.difference(right, sort=None) + assert_range_or_not_is_rangelike(result) + + left_int64 = pd.Index(left.to_numpy()) + right_int64 = pd.Index(right.to_numpy()) + + alt = left_int64.difference(right_int64, sort=None) + tm.assert_index_equal(result, alt, exact="equiv") + + result = left.difference(right, sort=False) + assert_range_or_not_is_rangelike(result) + + alt = left_int64.difference(right_int64, sort=False) + tm.assert_index_equal(result, alt, exact="equiv") diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/string/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/string/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/string/test_astype.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/string/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..b6fafc32e0da74d55f91c7ca203c024c06710ecd --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/string/test_astype.py @@ -0,0 +1,18 @@ +import pandas as pd +import pandas._testing as tm + + +def test_astype_str_from_bytes(): + # https://github.com/pandas-dev/pandas/issues/38607 + # GH#49658 pre-2.0 Index called .values.astype(str) here, which effectively + # did a .decode() on the bytes object. In 2.0 we go through + # ensure_string_array which does f"{val}" + idx = pd.Index(["あ", b"a"], dtype="object") + result = idx.astype(str) + expected = pd.Index(["あ", "a"], dtype="str") + tm.assert_index_equal(result, expected) + + # while we're here, check that Series.astype behaves the same + result = pd.Series(idx).astype(str) + expected = pd.Series(expected, dtype="str") + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/string/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/string/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..ec3d0996aae866d2a3d3b4e8f48878642377971f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/string/test_indexing.py @@ -0,0 +1,197 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def _isnan(val): + try: + return val is not pd.NA and np.isnan(val) + except TypeError: + return False + + +def _equivalent_na(dtype, null): + if dtype.na_value is pd.NA and null is pd.NA: + return True + elif _isnan(dtype.na_value) and _isnan(null): + return True + else: + return False + + +class TestGetLoc: + def test_get_loc(self, any_string_dtype): + index = pd.Index(["a", "b", "c"], dtype=any_string_dtype) + assert index.get_loc("b") == 1 + + def test_get_loc_raises(self, any_string_dtype): + index = pd.Index(["a", "b", "c"], dtype=any_string_dtype) + with pytest.raises(KeyError, match="d"): + index.get_loc("d") + + def test_get_loc_invalid_value(self, any_string_dtype): + index = pd.Index(["a", "b", "c"], dtype=any_string_dtype) + with pytest.raises(KeyError, match="1"): + index.get_loc(1) + + def test_get_loc_non_unique(self, any_string_dtype): + index = pd.Index(["a", "b", "a"], dtype=any_string_dtype) + result = index.get_loc("a") + expected = np.array([True, False, True]) + tm.assert_numpy_array_equal(result, expected) + + def test_get_loc_non_missing(self, any_string_dtype, nulls_fixture): + index = pd.Index(["a", "b", "c"], dtype=any_string_dtype) + with pytest.raises(KeyError): + index.get_loc(nulls_fixture) + + def test_get_loc_missing(self, any_string_dtype, nulls_fixture): + index = pd.Index(["a", "b", nulls_fixture], dtype=any_string_dtype) + assert index.get_loc(nulls_fixture) == 2 + + +class TestGetIndexer: + @pytest.mark.parametrize( + "method,expected", + [ + ("pad", [-1, 0, 1, 1]), + ("backfill", [0, 0, 1, -1]), + ], + ) + def test_get_indexer_strings(self, any_string_dtype, method, expected): + expected = np.array(expected, dtype=np.intp) + index = pd.Index(["b", "c"], dtype=any_string_dtype) + actual = index.get_indexer(["a", "b", "c", "d"], method=method) + + tm.assert_numpy_array_equal(actual, expected) + + def test_get_indexer_strings_raises(self, any_string_dtype): + index = pd.Index(["b", "c"], dtype=any_string_dtype) + + msg = "|".join( + [ + "operation 'sub' not supported for dtype 'str", + r"unsupported operand type\(s\) for -: 'str' and 'str'", + ] + ) + with pytest.raises(TypeError, match=msg): + index.get_indexer(["a", "b", "c", "d"], method="nearest") + + with pytest.raises(TypeError, match=msg): + index.get_indexer(["a", "b", "c", "d"], method="pad", tolerance=2) + + with pytest.raises(TypeError, match=msg): + index.get_indexer( + ["a", "b", "c", "d"], method="pad", tolerance=[2, 2, 2, 2] + ) + + @pytest.mark.parametrize("null", [None, np.nan, float("nan"), pd.NA]) + def test_get_indexer_missing(self, any_string_dtype, null, using_infer_string): + # NaT and Decimal("NaN") from null_fixture are not supported for string dtype + index = pd.Index(["a", "b", null], dtype=any_string_dtype) + result = index.get_indexer(["a", null, "c"]) + if using_infer_string: + expected = np.array([0, 2, -1], dtype=np.intp) + elif any_string_dtype == "string" and not _equivalent_na( + any_string_dtype, null + ): + expected = np.array([0, -1, -1], dtype=np.intp) + else: + expected = np.array([0, 2, -1], dtype=np.intp) + + tm.assert_numpy_array_equal(result, expected) + + +class TestGetIndexerNonUnique: + @pytest.mark.parametrize("null", [None, np.nan, float("nan"), pd.NA]) + def test_get_indexer_non_unique_nas( + self, any_string_dtype, null, using_infer_string + ): + index = pd.Index(["a", "b", null], dtype=any_string_dtype) + indexer, missing = index.get_indexer_non_unique(["a", null]) + + if using_infer_string: + expected_indexer = np.array([0, 2], dtype=np.intp) + expected_missing = np.array([], dtype=np.intp) + elif any_string_dtype == "string" and not _equivalent_na( + any_string_dtype, null + ): + expected_indexer = np.array([0, -1], dtype=np.intp) + expected_missing = np.array([1], dtype=np.intp) + else: + expected_indexer = np.array([0, 2], dtype=np.intp) + expected_missing = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected_indexer) + tm.assert_numpy_array_equal(missing, expected_missing) + + # actually non-unique + index = pd.Index(["a", null, "b", null], dtype=any_string_dtype) + indexer, missing = index.get_indexer_non_unique(["a", null]) + + if using_infer_string: + expected_indexer = np.array([0, 1, 3], dtype=np.intp) + elif any_string_dtype == "string" and not _equivalent_na( + any_string_dtype, null + ): + pass + else: + expected_indexer = np.array([0, 1, 3], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected_indexer) + tm.assert_numpy_array_equal(missing, expected_missing) + + +class TestSliceLocs: + @pytest.mark.parametrize( + "in_slice,expected", + [ + (pd.IndexSlice[::-1], "yxdcb"), + (pd.IndexSlice["b":"y":-1], ""), + (pd.IndexSlice["b"::-1], "b"), + (pd.IndexSlice[:"b":-1], "yxdcb"), + (pd.IndexSlice[:"y":-1], "y"), + (pd.IndexSlice["y"::-1], "yxdcb"), + (pd.IndexSlice["y"::-4], "yb"), + # absent labels + (pd.IndexSlice[:"a":-1], "yxdcb"), + (pd.IndexSlice[:"a":-2], "ydb"), + (pd.IndexSlice["z"::-1], "yxdcb"), + (pd.IndexSlice["z"::-3], "yc"), + (pd.IndexSlice["m"::-1], "dcb"), + (pd.IndexSlice[:"m":-1], "yx"), + (pd.IndexSlice["a":"a":-1], ""), + (pd.IndexSlice["z":"z":-1], ""), + (pd.IndexSlice["m":"m":-1], ""), + ], + ) + def test_slice_locs_negative_step(self, in_slice, expected, any_string_dtype): + index = pd.Index(list("bcdxy"), dtype=any_string_dtype) + + s_start, s_stop = index.slice_locs(in_slice.start, in_slice.stop, in_slice.step) + result = index[s_start : s_stop : in_slice.step] + expected = pd.Index(list(expected), dtype=any_string_dtype) + tm.assert_index_equal(result, expected) + + def test_slice_locs_negative_step_oob(self, any_string_dtype): + index = pd.Index(list("bcdxy"), dtype=any_string_dtype) + + result = index[-10:5:1] + tm.assert_index_equal(result, index) + + result = index[4:-10:-1] + expected = pd.Index(list("yxdcb"), dtype=any_string_dtype) + tm.assert_index_equal(result, expected) + + def test_slice_locs_dup(self, any_string_dtype): + index = pd.Index(["a", "a", "b", "c", "d", "d"], dtype=any_string_dtype) + assert index.slice_locs("a", "d") == (0, 6) + assert index.slice_locs(end="d") == (0, 6) + assert index.slice_locs("a", "c") == (0, 4) + assert index.slice_locs("b", "d") == (2, 6) + + index2 = index[::-1] + assert index2.slice_locs("d", "a") == (0, 6) + assert index2.slice_locs(end="a") == (0, 6) + assert index2.slice_locs("d", "b") == (0, 4) + assert index2.slice_locs("c", "a") == (2, 6) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_any_index.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_any_index.py new file mode 100644 index 0000000000000000000000000000000000000000..154cff897144778e7987c24f76ec79a2339751b9 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_any_index.py @@ -0,0 +1,183 @@ +""" +Tests that can be parametrized over _any_ Index object. +""" + +import re + +import numpy as np +import pytest + +from pandas.errors import InvalidIndexError + +import pandas as pd +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_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] + + +def test_map_identity_mapping(index, request, using_infer_string): + # GH#12766 + if ( + not using_infer_string + and isinstance(index.dtype, pd.StringDtype) + and index.dtype.storage == "python" + ): + mark = pytest.mark.xfail(reason="Does not preserve dtype") + request.applymarker(mark) + + result = index.map(lambda x: x) + if index.dtype == object and (result.dtype in (bool, "string")): + 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", check_freq=False) + + +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, temp_file): + result = tm.round_trip_pickle(index, temp_file) + 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, temp_file): + original_name, index.name = index.name, "foo" + unpickled = tm.round_trip_pickle(index, temp_file) + assert index.equals(unpickled) + index.name = original_name + + +class TestIndexing: + def test_getitem_0d_ndarray(self, index): + # GH#55601 + if len(index) == 0: + pytest.skip(reason="Test assumes non-empty index") + key = np.array(0) + result = index[key] + + assert result == index[0] + + 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/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_base.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e7aaa531b2b051728c8ba6bb51fb6854a6b7d6 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_base.py @@ -0,0 +1,1996 @@ +from collections import defaultdict +from datetime import datetime +from functools import partial +import math +import operator +import re + +import numpy as np +import pytest + +from pandas.compat import IS64 +from pandas.errors import ( + InvalidIndexError, + Pandas4Warning, +) +import pandas.util._test_decorators as td + +from pandas.core.dtypes.common import ( + is_any_real_numeric_dtype, + is_numeric_dtype, + is_object_dtype, +) + +import pandas as pd +import pandas._testing as tm +from pandas.core.indexes.api import ( + Index, + MultiIndex, + _get_combined_index, + ensure_index, + ensure_index_from_sequences, + union_indexes, +) +from pandas.testing import assert_series_equal + + +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) + + def test_constructor_copy(self, using_infer_string): + index = Index(list("abc"), name="name") + arr = np.array(index) + new_index = Index(arr, copy=True, name="name") + assert isinstance(new_index, Index) + assert new_index.name == "name" + if using_infer_string: + tm.assert_extension_array_equal( + new_index.values, pd.array(arr, dtype="str") + ) + else: + 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", + [ + pd.date_range( + "2015-01-01 10:00", + freq="D", + periods=3, + tz="US/Eastern", + name="Green Eggs & Ham", + ), # DTI with tz + pd.date_range("2015-01-01 10:00", freq="D", periods=3), # DTI no tz + pd.timedelta_range("1 days", freq="D", periods=3), # td + pd.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)) + assert result.dtype == np.dtype(object) + if isinstance(index, pd.DatetimeIndex): + # 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) + else: + result = Index(index) + + tm.assert_index_equal(result, index) + + @pytest.mark.parametrize( + "index,has_tz", + [ + ( + pd.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 + (pd.period_range("2015-01-01", freq="D", periods=3), False), # period + ], + ) + def test_constructor_from_series_dtlike(self, index, has_tz): + result = Index(pd.Series(index)) + tm.assert_index_equal(result, index, check_freq=False) + + 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 = pd.DatetimeIndex(dts, freq="MS") + + s = pd.Series(pd.to_datetime(dts)) + result = pd.DatetimeIndex(s, freq="MS") + + tm.assert_index_equal(result, expected) + + def test_constructor_from_frame_series_freq(self, using_infer_string): + # 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 = pd.DatetimeIndex(dts, freq="MS") + + df = pd.DataFrame(np.random.default_rng(2).random((5, 3))) + df["date"] = dts + result = pd.DatetimeIndex(df["date"], freq="MS") + dtype = object if not using_infer_string else "str" + assert df["date"].dtype == dtype + expected.name = "date" + tm.assert_index_equal(result, expected) + + expected = pd.Series(dts, name="date") + tm.assert_series_equal(df["date"], expected) + + # GH 6274 + # infer freq of same + if not using_infer_string: + # Doesn't work with arrow strings + msg = "A future version of pandas will return a BaseOffset" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + 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) + + def test_index_replace_scalar(self): + idx = Index([1, 2, 3]) + + result = idx.replace(2, 9) + + expected = Index([1, 9, 3]) + + tm.assert_index_equal(result, expected) + + def test_index_replace_dict(self): + idx = Index(["a", "b", "c"]) + + result = idx.replace({"b": "x"}) + + expected = Index(["a", "x", "c"]) + + tm.assert_index_equal(result, expected) + + def test_index_replace_preserves_name(self): + idx = Index([1, 2, 3], name="test") + + result = idx.replace(2, 9) + + assert result.name == "test" + + @pytest.mark.parametrize( + "idx", + [ + pd.date_range("2020-01-01", periods=3), + pd.date_range("2020-01-01", periods=3, tz="US/Pacific"), + pd.timedelta_range("1 day", periods=3), + pd.period_range("2020-01-01", periods=3, freq="D"), + pd.IntervalIndex.from_breaks([0, 1, 2, 3]), + ], + ) + def test_index_replace_widening_to_object(self, idx): + # GH#65099 replacement that widens to object used to raise AssertionError + result = idx.replace(idx[1], "foo") + + expected = Index([idx[0], "foo", idx[2]], dtype=object) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "idx, value, expected", + [ + ( + pd.date_range("2020-01-01", periods=3, unit="s"), + pd.Timestamp("2020-01-02 00:00:00.000001"), + pd.DatetimeIndex( + ["2020-01-01", "2020-01-02 00:00:00.000001", "2020-01-03"], + dtype="datetime64[us]", + ), + ), + ( + pd.IntervalIndex.from_breaks([0, 1, 2, 3]), + pd.Interval(0.5, 1.5), + pd.IntervalIndex.from_tuples([(0.0, 1.0), (0.5, 1.5), (2.0, 3.0)]), + ), + ], + ) + def test_index_replace_changing_dtype_keeps_subclass(self, idx, value, expected): + # guard against over-correcting GH#65099: these already worked before the fix + result = idx.replace(idx[1], value) + + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "idx, expected", + [ + (pd.RangeIndex(5), Index([0, 1, 2, 3, 4], dtype="int64")), + (Index(["a", "b"], dtype=object), Index(["a", "b"], dtype=object)), + ], + ) + def test_index_replace_no_op_dtype(self, idx, expected): + # GH#65099 a no-op replace demotes RangeIndex and preserves object rather than + # re-inferring it, both matching Series.replace + result = idx.replace(999, -1) + + tm.assert_index_equal(result, expected, exact=True) + + def test_index_replace_regex(self): + idx = Index(["foo", "bar", "baz"]) + result = idx.replace("^ba", "x", regex=True) + expected = Index(["foo", "xr", "xz"]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "klass,dtype,na_val", + [ + (Index, np.float64, np.nan), + (pd.DatetimeIndex, "datetime64[s]", 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, pd.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 = pd.date_range("2011-01-01", periods=5, unit="ns") + 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 = pd.DatetimeIndex(arg).tz_localize(tz_naive_fixture) + tm.assert_index_equal(result, index, check_freq=False) + 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, check_freq=False) + + if attr == "asi8": + if err: + with pytest.raises(TypeError, match=msg): + pd.DatetimeIndex(arg).astype(dtype) + else: + result = pd.DatetimeIndex(arg).astype(dtype) + tm.assert_index_equal(result, index, check_freq=False) + else: + result = klass(arg, dtype=dtype) + tm.assert_index_equal(result, index, check_freq=False) + + if attr == "asi8": + result = pd.DatetimeIndex(list(arg)).tz_localize(tz_naive_fixture) + tm.assert_index_equal(result, index, check_freq=False) + 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, check_freq=False) + + if attr == "asi8": + if err: + with pytest.raises(TypeError, match=msg): + pd.DatetimeIndex(list(arg)).astype(dtype) + else: + result = pd.DatetimeIndex(list(arg)).astype(dtype) + tm.assert_index_equal(result, index, check_freq=False) + else: + result = klass(list(arg), dtype=dtype) + tm.assert_index_equal(result, index, check_freq=False) + + @pytest.mark.parametrize("attr", ["values", "asi8"]) + @pytest.mark.parametrize("klass", [Index, pd.TimedeltaIndex]) + def test_constructor_dtypes_timedelta(self, attr, klass): + index = pd.timedelta_range("1 days", periods=5, unit="ns") + 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, + pd.CategoricalIndex, + pd.DatetimeIndex, + pd.TimedeltaIndex, + ], + ) + def test_constructor_empty(self, value, klass): + empty = klass(value) + assert isinstance(empty, klass) + assert not len(empty) + + @pytest.mark.parametrize( + "empty,klass", + [ + (pd.PeriodIndex([], freq="D"), pd.PeriodIndex), + (pd.PeriodIndex(iter([]), freq="D"), pd.PeriodIndex), + (pd.PeriodIndex((_ for _ in []), freq="D"), pd.PeriodIndex), + (pd.RangeIndex(step=1), pd.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" + 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, request, using_infer_string): + if dtype is np.bool_ and using_infer_string and index.dtype == "string": + request.applymarker(pytest.mark.xfail(reason="numpy behavior is buggy")) + empty_arr = np.array([], dtype=dtype) + empty_index = type(index)([], dtype=index.dtype) + + assert index[[]].identical(empty_index) + if dtype == np.bool_: + with pytest.raises(ValueError, match="length of the boolean indexer"): + assert index[empty_arr].identical(empty_index) + else: + 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" + 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 = pd.date_range("2019-01-01", periods=10) + first_cat = index.union(date_index) + second_cat = index.union(index) + + appended = Index(np.append(index, date_index.astype("O"))) + + tm.assert_index_equal(first_cat, appended) + tm.assert_index_equal(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 = Index(np.arange(3), dtype=np.int64) + result = index.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], strict=True)) + reduced_index = multi_index.map(lambda x: x[0]) + tm.assert_index_equal(reduced_index, Index(first_level)) + + @pytest.mark.parametrize( + "index", + [ + pd.date_range("2020-01-01", freq="D", periods=10), + pd.period_range("2020-01-01", freq="D", periods=10), + pd.timedelta_range("1 day", periods=10), + ], + ) + def test_map_tseries_indices_return_index(self, index): + 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 = pd.DatetimeIndex( + pd.date_range("2020-01-01", periods=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, strict=True)}, + lambda values, index: pd.Series(values, index), + ], + ) + def test_map_dictlike_simple(self, mapper): + # GH 12756 + expected = Index(["foo", "bar", "baz"]) + index = Index(np.arange(3), dtype=np.int64) + 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, strict=True)}, + lambda values, index: pd.Series(values, index), + ], + ) + def test_map_dictlike(self, index, mapper, request, using_infer_string): + # GH 12756 + if isinstance(index, pd.CategoricalIndex): + pytest.skip("Tested in test_categorical") + elif not index.is_unique: + pytest.skip("Cannot map duplicated index") + if ( + not using_infer_string + and isinstance(index.dtype, pd.StringDtype) + and index.dtype.storage == "python" + ): + mark = pytest.mark.xfail(reason="map does not retain dtype") + request.applymarker(mark) + + 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", + [ + pd.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) + + 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, using_infer_string): + if using_infer_string and index.dtype == "string" and expected: + expected = False + assert is_object_dtype(index) is expected + + def test_summary(self, index): + index._summary() + + def test_logical_compat(self, all_boolean_reductions, simple_index): + index = simple_index + left = getattr(index, all_boolean_reductions)() + assert left == getattr(index.values, all_boolean_reductions)() + right = getattr(index.to_series(), all_boolean_reductions)() + # 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=".* not found in axis"): + 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=re.escape("[4] not found in axis")): + 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"], dtype=object) + + 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) + + 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, pd.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(2011, 1, 1), 7]) + assert not getattr(index, attr) + + @pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}]) + @pytest.mark.parametrize( + "index,expected", + [ + (["qux", "baz", "foo", "bar"], [False, False, True, True]), + ([], []), # empty + ], + ) + def test_isin(self, values, index, expected): + index = Index(index) + result = index.isin(values) + expected = np.array(expected, dtype=bool) + tm.assert_numpy_array_equal(result, expected) + + def test_isin_nan_common_object( + self, nulls_fixture, nulls_fixture2, using_infer_string + ): + # Test cartesian product of null fixtures and ensure that we don't + # mangle the various types (save a corner case with PyPy) + idx = Index(["a", nulls_fixture]) + + # 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( + idx.isin([nulls_fixture2]), + np.array([False, True]), + ) + + elif nulls_fixture is nulls_fixture2: # should preserve NA type + tm.assert_numpy_array_equal( + idx.isin([nulls_fixture2]), + np.array([False, True]), + ) + + elif using_infer_string and idx.dtype == "string": + tm.assert_numpy_array_equal( + idx.isin([nulls_fixture2]), + np.array([False, True]), + ) + + else: + tm.assert_numpy_array_equal( + idx.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 a NaN we do not have .isin(nulls_fixture) + msg = ( + r"float\(\) argument must be a string or a (real )?number, " + f"not {type(nulls_fixture).__name__!r}" + ) + 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", + [ + ["qux", "baz", "foo", "bar"], + np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float64), + ], + ) + def test_isin_level_kwarg(self, level, index): + index = Index(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", [[], pd.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) + + def test_isin_string_null(self, string_dtype_no_object): + # GH#55821 + index = Index(["a", "b"], dtype=string_dtype_no_object) + result = index.isin([None]) + expected = np.array([False, False]) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "values", + [ + [1, 2, 3, 4], + [1.0, 2.0, 3.0, 4.0], + [True, True, True, True], + ["foo", "bar", "baz", "qux"], + pd.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 + + def test_slice_is_unique(self): + # GH 57911 + index = Index([1, 1, 2, 3, 4]) + assert not index.is_unique + filtered_index = index[2:].copy() + assert filtered_index.is_unique + + def test_slice_is_montonic(self): + """Test that is_monotonic_decreasing is correct on slices.""" + # GH 57911 + index = Index([1, 2, 3, 3]) + assert not index.is_monotonic_decreasing + + filtered_index = index[2:].copy() + assert filtered_index.is_monotonic_decreasing + assert filtered_index.is_monotonic_increasing + + filtered_index = index[1:].copy() + assert not filtered_index.is_monotonic_decreasing + assert filtered_index.is_monotonic_increasing + + filtered_index = index[:].copy() + assert not filtered_index.is_monotonic_decreasing + assert filtered_index.is_monotonic_increasing + + @pytest.mark.parametrize( + "index", + [ + "string", + "datetime", + "int64", + "int32", + "uint64", + "uint32", + "float64", + "float32", + ], + indirect=True, + ) + def test_join_self(self, index, join_type): + result = index.join(index, how=join_type) + expected = index + if join_type == "outer": + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + @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)), + pd.date_range("2020-01-01", periods=10), + MultiIndex.from_tuples([("foo", "1"), ("bar", "3")]), + pd.period_range(start="2000", end="2010", freq="Y"), + ], + ) + 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 = pd.Series(range(4), index=index) + + result = s[s.index.str.startswith("a")] + expected = pd.Series(range(2), index=["a1", "a2"]) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "index,expected", [(list("abcd"), True), (range(4), False)] + ) + def test_tab_completion(self, index, expected): + # GH 9910 + index = Index(index) + 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 = pd.date_range("2020-01-01", periods=10) + + with tm.assert_produces_warning(RuntimeWarning, match="not supported between"): + result = left_index.join(right_index, how="outer") + + with tm.assert_produces_warning(RuntimeWarning, match="not supported between"): + expected = left_index.astype(object).union(right_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=np.nan) + expected = Index(["B", "A", np.nan], name="xxx") + tm.assert_index_equal(result, expected) + + # fill_value is respected (not discarded in favor of _na_value) + result = index.take(np.array([1, 0, -1]), fill_value="X") + expected = Index(["B", "A", "X"], name="xxx") + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = index.take(np.array([1, 0, -1]), allow_fill=False) + 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, 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 + pd.date_range("20130101", periods=3).values, + pd.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 == index.dtype.type + + def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self): + # GH7774 + index = Index(list("abc")) + labels = pd.DatetimeIndex([]) + dtype = np.datetime64 + 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.DataFrame( + [3, 6], + columns=["c"], + index=MultiIndex.from_arrays([[1, 4], [2, 5]], names=["a", "b"]), + ) + + result = df.index == mi + tm.assert_numpy_array_equal(result, expected) + + def test_equals_op_multiindex_identify(self): + df = pd.DataFrame( + [3, 6], + columns=["c"], + index=MultiIndex.from_arrays([[1, 4], [2, 5]], names=["a", "b"]), + ) + + 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.DataFrame( + [3, 6], + columns=["c"], + index=MultiIndex.from_arrays([[1, 4], [2, 5]], names=["a", "b"]), + ) + + with pytest.raises(ValueError, match="Lengths must match"): + df.index == index + + def test_equals_op_index_vs_mi_same_length(self, using_infer_string): + 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, pd.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) + + def test_assert_index_equal_exact_equiv_default_deprecated(self): + # GH#57436 + result = Index([0, 1, 2, 3], dtype=np.int64) + expected = pd.RangeIndex(0, 4) + msg = "The default value of 'equiv' for the `exact` parameter is deprecated " + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "indexes, expected, expected_all_equal", + [ + ( + [Index(["a", "b"]), Index(["a", "b"])], + Index(["a", "b"]), + True, + ), + ( + [Index(["a", "b"]), Index(["b", "c"])], + Index(["a", "b", "c"]), + False, + ), + ], + ) + def test_union_indexes_returns_all_equal( + self, indexes, expected, expected_all_equal + ): + # GH#65393 + result, all_equal = union_indexes(indexes, sort=False) + + tm.assert_index_equal(result, expected) + assert all_equal is expected_all_equal + + +class TestMixedIntIndex: + # (GH 13514) tests for mixed int/str indexes where ints and strings + # are not comparable + @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 = pd.Series(2, index=first) + s2 = pd.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", + [ + ( + pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]), + pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]), + ), + ( + pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", pd.NaT]), + pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]), + ), + ( + pd.TimedeltaIndex(["1 days", "2 days", "3 days"]), + pd.TimedeltaIndex(["1 days", "2 days", "3 days"]), + ), + ( + pd.TimedeltaIndex([pd.NaT, "1 days", "2 days", "3 days", pd.NaT]), + pd.TimedeltaIndex(["1 days", "2 days", "3 days"]), + ), + ( + pd.PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"), + pd.PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"), + ), + ( + pd.PeriodIndex(["2012-02", "2012-04", "NaT", "2012-05"], freq="M"), + pd.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 + + @pytest.mark.parametrize("dtype", ["f8", "m8[ns]", "M8[us]"]) + @pytest.mark.parametrize("unique_first", [True, False]) + def test_is_monotonic_unique_na(self, dtype, unique_first): + # GH 55755 + index = Index([None, 1, 1], dtype=dtype) + if unique_first: + assert index.is_unique is False + assert index.is_monotonic_increasing is False + assert index.is_monotonic_decreasing is False + else: + assert index.is_monotonic_increasing is False + assert index.is_monotonic_decreasing is False + assert index.is_unique 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) + + def test_index_with_tuple_bool(self): + # GH34123 + 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, 4]], None, Index([1, 2, 4])), + ([[1, 2, 4]], ["name"], Index([1, 2, 4], name="name")), + ([[1, 2, 3]], None, pd.RangeIndex(1, 4)), + ([[1, 2, 3]], ["name"], pd.RangeIndex(1, 4, 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, exact=True) + + 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 = pd.RangeIndex(0) + 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( + "klass", + [ + partial(pd.CategoricalIndex, data=[1]), + partial(pd.DatetimeIndex, data=["2020-01-01"]), + partial(pd.PeriodIndex, data=["2020-01-01"]), + partial(pd.TimedeltaIndex, data=["1 day"]), + partial(pd.RangeIndex, start=range(1)), + partial(pd.IntervalIndex, data=[pd.Interval(0, 1)]), + partial(Index, data=["a"], dtype=object), + partial(MultiIndex, levels=[1], codes=[0]), + ], +) +def test_index_subclass_constructor_wrong_kwargs(klass): + # GH #19348 + with pytest.raises(TypeError, match="unexpected keyword argument"): + klass(foo="bar") + + +def test_deprecated_fastpath(): + msg = "unexpected 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): + pd.RangeIndex(0, 5, 2, name="test", fastpath=True) + + with pytest.raises(TypeError, match=msg): + pd.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 = pd.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 = pd.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], + [pd.DatetimeIndex, {}], + [pd.TimedeltaIndex, {}], + pytest.param( + pd.PeriodIndex, + {"freq": "Y"}, + marks=pytest.mark.filterwarnings( + "ignore:Passing integer data:pandas.errors.Pandas4Warning" + ), + ), + ], +) +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) + + +@td.skip_if_no("pyarrow") +def test_is_monotonic_pyarrow_list_type(): + # GH 57333 + import pyarrow as pa + + idx = Index([[1], [2, 3]], dtype=pd.ArrowDtype(pa.list_(pa.int64()))) + assert not idx.is_monotonic_increasing + assert not idx.is_monotonic_decreasing + + +def test_index_equals_different_string_dtype(string_dtype_no_object): + # GH 61099 + idx_obj = Index(["a", "b", "c"]) + idx_str = Index(["a", "b", "c"], dtype=string_dtype_no_object) + + assert idx_obj.equals(idx_str) + assert idx_str.equals(idx_obj) + + +def test_index_comparison_different_string_dtype(string_dtype_no_object): + # GH 61099 + idx = Index(["a", "b", "c"]) + s_obj = pd.Series([1, 2, 3], index=idx) + s_str = pd.Series([4, 5, 6], index=idx.astype(string_dtype_no_object)) + + expected = pd.Series([True, True, True], index=["a", "b", "c"]) + result = s_obj < s_str + assert_series_equal(result, expected) + + result = s_str > s_obj + expected.index = idx.astype(string_dtype_no_object) + assert_series_equal(result, expected) + + +def test_get_level_values_boolean_names(): + # GH#62169 + idx_true = Index(["a", "b"], name=True) + result = idx_true.get_level_values(True) + tm.assert_index_equal(idx_true, result) + + idx_false = Index(["a", "b"], name=False) + result = idx_false.get_level_values(False) + tm.assert_index_equal(idx_false, result) + + msg = r"Requested level \(False\) does not match index name \(True\)" + with pytest.raises(KeyError, match=msg): + idx_true.get_level_values(False) + + result = idx_true.get_level_values(0) + tm.assert_index_equal(idx_true, result) + + +def test_get_level_values_na_type_matching(): + # GH#62169 + idx_nan = Index(["a", "b"], name=np.nan) + result = idx_nan.get_level_values(np.nan) + tm.assert_index_equal(idx_nan, result) + + idx_na = Index(["a", "b"], name=pd.NA) + result = idx_na.get_level_values(pd.NA) + tm.assert_index_equal(idx_na, result) + + idx_nat = Index(["a", "b"], name=pd.NaT) + result = idx_nat.get_level_values(pd.NaT) + tm.assert_index_equal(idx_nat, result) + + msg = r"Requested level \(.+\) does not match index name \(.+\)" + with pytest.raises(KeyError, match=msg): + idx_nan.get_level_values(pd.NA) + + with pytest.raises(KeyError, match=msg): + idx_na.get_level_values(np.nan) + + with pytest.raises(KeyError, match=msg): + idx_nat.get_level_values(np.nan) + + +def test_get_level_values_integer_names(): + # GH#62169 + idx_5 = Index(["a", "b"], name=5) + result = idx_5.get_level_values(5) + tm.assert_index_equal(idx_5, result) + + result = idx_5.get_level_values(0) + tm.assert_index_equal(idx_5, result) + + result = idx_5.get_level_values(-1) + tm.assert_index_equal(idx_5, result) + + idx_0 = Index(["a", "b"], name=0) + result = idx_0.get_level_values(0) + tm.assert_index_equal(idx_0, result) + + idx_neg1 = Index(["a", "b"], name=-1) + result = idx_neg1.get_level_values(-1) + tm.assert_index_equal(idx_neg1, result) + + msg = r"Too many levels: Index has only 1 level" + with pytest.raises(IndexError, match=msg): + idx_5.get_level_values(1) + + +@pytest.mark.parametrize("wrap", [str, np.str_]) +@pytest.mark.parametrize("dtype", [object, "str"]) +def test_slice_locs_quarterly_string_bounds_no_deprecation_warning(dtype, wrap): + # GH#50907 slice_locs parses str bounds internally to compare UTC offsets; + # on a non-datetime Index nothing is being parsed as a datetime, so a + # quarterly-looking label must not trigger the deprecation + idx = Index(["2000Q1", "2000Q2", "2000Q3"], dtype=dtype) + ser = pd.Series(np.arange(len(idx)), index=idx) + + with tm.assert_produces_warning(None): + result = ser.loc[wrap("2000Q1") : wrap("2000Q2")] + tm.assert_series_equal(result, ser.iloc[:2]) + + with tm.assert_produces_warning(None): + assert idx.slice_locs(wrap("2000Q1"), wrap("2000Q2")) == (0, 2) + + +@pytest.mark.parametrize("wrap", [str, np.str_]) +def test_slice_locs_quarterly_string_bound_utc_offset_check(wrap): + # GH#50907 recognizing the quarterly bound without warning must not lose the + # GH#16785 offset comparison; a quarterly string is always naive. GH#45580 + # the bound may be an np.str_, which the opted-out parser rejects. + idx = Index(["a", "b", "c"]) + + with tm.assert_produces_warning(None): + with pytest.raises(ValueError, match="Both dates must"): + idx.slice_locs(wrap("2000Q1"), "2000-06-01 00:00:00+06:00") + + +@pytest.mark.parametrize( + "left, right, expected, exp_lidx, exp_ridx", + [ + ( + Index(["x", "y"], dtype=pd.StringDtype(na_value=np.nan)), + Index(["x", "x", 1], dtype=object), + Index(["x", "x", "y"], dtype=pd.StringDtype(na_value=np.nan)), + np.array([0, 0, 1], dtype=np.intp), + np.array([0, 1, -1], dtype=np.intp), + ), + ( + Index([3, 1, 2], dtype=np.int64), + Index(["a", 1], dtype=object), + Index([3, 1, 2], dtype=np.int64), + None, + np.array([-1, 1, -1], dtype=np.intp), + ), + ], +) +def test_join_mismatched_dtypes_keeps_dtype_of_kept_side( + left, right, expected, exp_lidx, exp_ridx +): + # GH#63371 + result, lidx, ridx = left.join(right, how="left", return_indexers=True) + tm.assert_index_equal(result, expected) + tm.assert_equal(lidx, exp_lidx) + tm.assert_numpy_array_equal(ridx, exp_ridx) + + result, ridx, lidx = right.join(left, how="right", return_indexers=True) + tm.assert_index_equal(result, expected) + tm.assert_equal(lidx, exp_lidx) + tm.assert_numpy_array_equal(ridx, exp_ridx) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_common.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..0423ac9476481833fc3acc7ed18e69b67c7b0954 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_common.py @@ -0,0 +1,552 @@ +""" +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.errors import Pandas4Warning + +from pandas.core.dtypes.common import ( + is_integer_dtype, + is_numeric_dtype, +) + +import pandas as pd +import pandas._testing as tm + + +class TestCommon: + @pytest.mark.parametrize("name", [None, "new_name"]) + def test_to_frame(self, name, index_flat): + # 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 + + 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, exact=not isinstance(index, pd.RangeIndex) + ) + + # nans: + if not index._can_hold_na: + pytest.skip("Skip na-check if index cannot hold na") + + vals = index._values.copy()[[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) + + 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.applymarker(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) + + if index.is_monotonic_increasing or 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 + + ss_left = index.searchsorted(value, side="left") + assert expected_left == ss_left + + ss_right = index.searchsorted(value, side="right") + assert expected_right == ss_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") + + def test_drop_duplicates(self, index_flat, keep): + # MultiIndex is tested separately + index = index_flat + if isinstance(index, pd.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) + + def test_drop_duplicates_no_duplicates(self, index_flat): + # MultiIndex is tested separately + index = index_flat + + # make unique index + if isinstance(index, pd.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) + + 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, pd.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, pd.MultiIndex): + index.names = ["idx" + str(i) for i in range(index.nlevels)] + else: + index.name = "idx" + + warn = ( + np.exceptions.ComplexWarning + if index.dtype.kind == "c" and dtype in ["float64", "int64", "uint64"] + else None + ) + + is_pyarrow_str = str(index.dtype) == "string[pyarrow]" and dtype == "category" + try: + # Some of these conversions cannot succeed so we use a try / except + msg = "Casting complex values to real discards the imaginary part" + with tm.assert_produces_warning( + warn, + raise_on_extra_warnings=is_pyarrow_str, + check_stacklevel=False, + match=msg, + ): + result = index.astype(dtype) + except (ValueError, TypeError, NotImplementedError, SystemError): + return + + if isinstance(index, pd.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.parametrize("na_position", [None, "middle"]) +def test_sort_values_invalid_na_position(index_with_missing_sortable, na_position): + with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"): + index_with_missing_sortable.sort_values(na_position=na_position) + + +@pytest.mark.parametrize("na_position", ["first", "last"]) +def test_sort_values_with_missing(index_with_missing_sortable, na_position): + # GH 35584. Test that sort_values works with missing values, + # sort non-missing and place missing according to na_position + + index_with_missing = index_with_missing_sortable + + 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_sort_values_natsort_key(): + # GH#56081 + def split_convert(s): + return tuple(int(x) for x in s.split(".")) + + idx = pd.Index(["1.9", "2.0", "1.11", "1.10"]) + expected = pd.Index(["1.9", "1.10", "1.11", "2.0"]) + result = idx.sort_values(key=lambda x: tuple(map(split_convert, x))) + tm.assert_index_equal(result, expected) + + +def test_ndarray_compat_properties(index): + if isinstance(index, pd.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, (pd.RangeIndex, pd.MultiIndex)): + # These two are not backed by an ndarray + assert idx.nbytes == values.nbytes + + # test for validity + idx.nbytes + idx._values.nbytes + + +def test_compare_read_only_array(): + # GH#57130 + arr = np.array([], dtype=object) + arr.flags.writeable = False + idx = pd.Index(arr) + result = idx > 69 + assert result.dtype == bool + + +def test_to_frame_column_rangeindex(): + idx = pd.Index([1]) + result = idx.to_frame().columns + expected = pd.RangeIndex(1) + tm.assert_index_equal(result, expected, exact=True) + + +def test_to_frame_name_tuple_multiindex(): + idx = pd.Index([1]) + result = idx.to_frame(name=(1, 2)) + expected = pd.DataFrame( + [1], columns=pd.MultiIndex.from_arrays([[1], [2]]), index=idx + ) + tm.assert_frame_equal(result, expected) + + +def test_join_series_deprecated(): + # GH#62897 + idx = pd.Index([1, 2]) + ser = pd.Series([1, 2, 2]) + with tm.assert_produces_warning( + Pandas4Warning, match="Passing .* to .* is deprecated" + ): + idx.join(ser) + + +@pytest.mark.parametrize( + "data, dtype", + [ + ([1, None], "Int64"), + ([1.0, None], "Float64"), + ([True, None], "boolean"), + ([1, None], "int64[pyarrow]"), + ([1.0, None], "category"), + ], +) +def test_fillna_incompatible_value_deprecated_ea_dtype(data, dtype): + # GH#25288 the casting deprecation also applies to Index with an + # ExtensionArray dtype, which used to cast to object silently + if "pyarrow" in dtype: + pytest.importorskip("pyarrow") + idx = pd.Index(data, dtype=dtype) + + msg = "'str' is not supported as a fill value" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = idx.fillna("x") + + expected = pd.Index([data[0], "x"], dtype=object) + tm.assert_index_equal(result, expected) + + # a value the dtype can hold is unaffected + with tm.assert_produces_warning(None): + result = idx.fillna(data[0]) + tm.assert_index_equal(result, pd.Index([data[0], data[0]], dtype=dtype)) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_datetimelike.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_datetimelike.py new file mode 100644 index 0000000000000000000000000000000000000000..d555bd3d528cb8e180f7cc3912d9caa633ccfc72 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_datetimelike.py @@ -0,0 +1,166 @@ +"""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 + + result = type(simple_index)(idx) + tm.assert_index_equal(result, idx) + + msg = "Cannot change data-type" + with pytest.raises(TypeError, match=msg): + idx.view(type(simple_index)) + + 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, check_freq=False) + + # 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, strict=True)}, + lambda values, index: pd.Series(values, index, dtype=object), + ], + ) + 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) + + 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.to_timedelta([pd.NaT, 10, 10], unit=unit).as_unit(unit) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_engines.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_engines.py new file mode 100644 index 0000000000000000000000000000000000000000..468c2240c8192098a6ff75a5a2d0210c8108a176 --- /dev/null +++ b/venv/lib/python3.14/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/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_frozen.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_frozen.py new file mode 100644 index 0000000000000000000000000000000000000000..f5e3744fe9aef0024fb8d615fdd87db8d2f63e60 --- /dev/null +++ b/venv/lib/python3.14/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) # noqa: RUF005 + expected = FrozenList(lst + [1, 2, 3]) # noqa: RUF005 + self.check_result(result, expected) + + result = (1, 2, 3) + container # noqa: RUF005 + expected = FrozenList([1, 2, 3] + lst) # noqa: RUF005 + self.check_result(result, expected) + + def test_iadd(self, container, lst): + q = r = container + + q += [5] + self.check_result(q, lst + [5]) # noqa: RUF005 + + # 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]) # noqa: RUF005 + 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/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_index_new.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_index_new.py new file mode 100644 index 0000000000000000000000000000000000000000..13e2174e15f992cd469aeb6c2a3b21805b775e7b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_index_new.py @@ -0,0 +1,433 @@ +""" +Tests for the Index constructor conducting inference. +""" + +from datetime import ( + UTC, + datetime, + timedelta, +) +from decimal import Decimal + +import numpy as np +import pytest + +from pandas._libs.tslibs.timezones import maybe_get_tz + +import pandas as pd +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 = pd.Index(arr) + assert res.dtype == object + + # since the point is matching Series behavior, let's double check + assert pd.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 = pd.Index(arr) + assert res.dtype == object + + # since the point is matching Series behavior, let's double check + assert pd.Series(arr).dtype == object + + @pytest.mark.parametrize("val", [pd.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 = [pd.NaT, val] + + idx = pd.Index(values) + assert idx.dtype == "datetime64[s]" and idx.isna().all() + + idx = pd.Index(values[::-1]) + assert idx.dtype == "datetime64[s]" and idx.isna().all() + + idx = pd.Index(np.array(values, dtype=object)) + assert idx.dtype == "datetime64[s]" and idx.isna().all() + + idx = pd.Index(np.array(values, dtype=object)[::-1]) + assert idx.dtype == "datetime64[s]" 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 = pd.Index(vtype(values)) + expected = pd.MultiIndex.from_tuples(values) + tm.assert_index_equal(result, expected) + + def test_constructor_int_dtype_float(self, any_int_numpy_dtype): + # GH#18400 + expected = pd.Index([0, 1, 2, 3], dtype=any_int_numpy_dtype) + result = pd.Index([0.0, 1.0, 2.0, 3.0], dtype=any_int_numpy_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 = pd.Index(vals, dtype=bool) + else: + index = pd.Index(vals) + + assert type(index) is pd.Index + assert index.dtype == bool + + def test_constructor_categorical_to_object(self): + # GH#32167 Categorical data and dtype=object should return object-dtype + ci = pd.CategoricalIndex(range(5)) + result = pd.Index(ci, dtype=object) + assert not isinstance(result, pd.CategoricalIndex) + + def test_constructor_infer_periodindex(self): + xp = pd.period_range("2012-1-1", freq="M", periods=3) + rs = pd.Index(xp) + tm.assert_index_equal(rs, xp) + assert isinstance(rs, pd.PeriodIndex) + + def test_from_list_of_periods(self): + rng = pd.period_range("1/1/2000", periods=20, freq="D") + periods = list(rng) + + result = pd.Index(periods) + assert isinstance(result, pd.PeriodIndex) + + @pytest.mark.parametrize("pos", [0, 1]) + @pytest.mark.parametrize( + "klass,dtype,ctor", + [ + (pd.DatetimeIndex, "datetime64[ns]", np.datetime64("nat", "ns")), + (pd.TimedeltaIndex, "timedelta64[ns]", np.timedelta64("NaT", "ns")), + ], + ) + 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([pd.NaT, pd.NaT]) + if dtype[0] == "d": + # we infer all-NaT as second resolution + expected = expected.astype("M8[ns]") + if dtype[0] == "t": + # we infer all-NaT as second resolution + expected = expected.astype("m8[ns]") + assert expected.dtype == dtype + data = [ctor] + data.insert(pos, nulls_fixture) + + if nulls_fixture is pd.NA: + expected = pd.Index([pd.NA, pd.NaT]) + mark = pytest.mark.xfail(reason="Broken with np.NaT ctor; see GH 31884") + request.applymarker(mark) + + result = pd.Index(data) + + tm.assert_index_equal(result, expected) + + result = pd.Index(np.array(data, dtype=object)) + + 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", "ns"), np.timedelta64("NaT", "ns")] + if swap_objs: + data = data[::-1] + + expected = pd.Index(data, dtype=object) + tm.assert_index_equal(pd.Index(data), expected) + tm.assert_index_equal(pd.Index(np.array(data, dtype=object)), expected) + + @pytest.mark.parametrize("swap_objs", [True, False]) + def test_constructor_datetime_and_datetime64(self, swap_objs): + data = [ + pd.Timestamp(2021, 6, 8, 9, 42), + np.datetime64("2011-01-01T09:42:00", "s"), + ] + if swap_objs: + data = data[::-1] + expected = pd.DatetimeIndex(data) + + tm.assert_index_equal(pd.Index(data), expected) + tm.assert_index_equal(pd.Index(np.array(data, dtype=object)), expected) + + def test_constructor_datetimes_mixed_tzs(self): + # https://github.com/pandas-dev/pandas/pull/55793/files#r1383719998 + tz = maybe_get_tz("US/Central") + dt1 = datetime(2020, 1, 1, tzinfo=tz) + dt2 = datetime(2020, 1, 1, tzinfo=UTC) + result = pd.Index([dt1, dt2]) + expected = pd.Index([dt1, dt2], dtype=object) + tm.assert_index_equal(result, expected) + + def test_constructor_preserves_byteorder(self): + # GH#43042 non-native byteorder (and the values) must be preserved + arr = np.array([0, 256, 2**40], dtype=">i8") + expected = [0, 256, 2**40] + + # inferred from a big-endian ndarray + result = pd.Index(arr) + assert result.dtype == np.dtype(">i8") + assert result.tolist() == expected + + # explicit big-endian dtype from a python list + result = pd.Index([0, 256, 2**40], dtype=">i8") + assert result.dtype == np.dtype(">i8") + assert result.tolist() == 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 = pd.array([0], dtype=any_numeric_ea_dtype) + + idx = pd.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 = pd.Index(range(5)) + + result = pd.Index(rng, dtype=dtype) + assert result.dtype == dtype + + result = pd.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 = pd.Categorical([1, 2, 3]) + + result = pd.Index(cat, dtype=dtype) + assert result.dtype == dtype + + def test_constructor_categorical_values_mismatched_dtype(self): + dti = pd.date_range("2016-01-01", periods=3) + cat = pd.Categorical(dti) + result = pd.Index(cat, dti.dtype) + tm.assert_index_equal(result, dti, check_freq=False) + + dti2 = dti.tz_localize("Asia/Tokyo") + cat2 = pd.Categorical(dti2) + result = pd.Index(cat2, dti2.dtype) + tm.assert_index_equal(result, dti2, check_freq=False) + + ii = pd.IntervalIndex.from_breaks(range(5)) + cat3 = pd.Categorical(ii) + result = pd.Index(cat3, dtype=ii.dtype) + tm.assert_index_equal(result, ii) + + def test_constructor_ea_values_mismatched_categorical_dtype(self): + dti = pd.date_range("2016-01-01", periods=3) + result = pd.Index(dti, dtype="category") + expected = pd.CategoricalIndex(dti) + tm.assert_index_equal(result, expected, check_freq=False) + + dti2 = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") + result = pd.Index(dti2, dtype="category") + expected = pd.CategoricalIndex(dti2) + tm.assert_index_equal(result, expected, check_freq=False) + + def test_constructor_period_values_mismatched_dtype(self): + pi = pd.period_range("2016-01-01", periods=3, freq="D") + result = pd.Index(pi, dtype="category") + expected = pd.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 = pd.timedelta_range("4 Days", periods=5) + result = pd.Index(tdi, dtype="category") + expected = pd.CategoricalIndex(tdi) + tm.assert_index_equal(result, expected, check_freq=False) + + def test_constructor_interval_values_mismatched_dtype(self): + dti = pd.date_range("2016-01-01", periods=3) + ii = pd.IntervalIndex.from_breaks(dti) + result = pd.Index(ii, dtype="category") + expected = pd.CategoricalIndex(ii) + tm.assert_index_equal(result, expected) + + def test_constructor_datetime64_values_mismatched_period_dtype(self): + dti = pd.date_range("2016-01-01", periods=3) + result = pd.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): + pd.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 = pd.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 = pd.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 = pd.Index(vals, dtype="category") + assert isinstance(index, pd.CategoricalIndex) + + @pytest.mark.parametrize("cast_index", [True, False]) + @pytest.mark.parametrize( + "vals", + [ + np.array([np.datetime64("2011-01-01"), np.datetime64("2011-01-02")]), + [datetime(2011, 1, 1), datetime(2011, 1, 2)], + ], + ) + def test_constructor_dtypes_to_datetime(self, cast_index, vals): + vals = pd.Index(vals) + if cast_index: + index = pd.Index(vals, dtype=object) + assert isinstance(index, pd.Index) + assert index.dtype == object + else: + index = pd.Index(vals) + assert isinstance(index, pd.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 = pd.Index(vals, dtype=object) + assert isinstance(index, pd.Index) + assert index.dtype == object + else: + index = pd.Index(vals) + assert isinstance(index, pd.TimedeltaIndex) + + def test_pass_timedeltaindex_to_index(self): + rng = pd.timedelta_range("1 days", "10 days") + idx = pd.Index(rng, dtype=object) + + expected = pd.Index(rng.to_pytimedelta(), dtype=object) + + tm.assert_numpy_array_equal(idx.values, expected.values) + + def test_pass_datetimeindex_to_index(self): + # GH#1396 + rng = pd.date_range("1/1/2000", "3/1/2000") + idx = pd.Index(rng, dtype=object) + + expected = pd.Index(rng.to_pydatetime(), dtype=object) + + tm.assert_numpy_array_equal(idx.values, expected.values) + + +class TestIndexConstructorUnwrapping: + # Test passing different arraylike values to pd.Index + + @pytest.mark.parametrize("klass", [pd.Index, pd.DatetimeIndex]) + def test_constructor_from_series_dt64(self, klass): + stamps = [ + pd.Timestamp("20110101"), + pd.Timestamp("20120101"), + pd.Timestamp("20130101"), + ] + expected = pd.DatetimeIndex(stamps) + ser = pd.Series(stamps) + result = klass(ser) + tm.assert_index_equal(result, expected) + + def test_constructor_no_pandas_array(self): + ser = pd.Series([1, 2, 3]) + result = pd.Index(ser.array) + expected = pd.Index([1, 2, 3]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "array", + [ + np.arange(5), + np.array(["a", "b", "c"]), + pd.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, copy=None) -> np.ndarray: + return self.array + + expected = pd.Index(array) + result = pd.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): + pd.Index([np.iinfo(np.uint64).max - 1], dtype="int64") diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..99a5440ade4055adc12443ffeacfbf086ef80403 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_indexing.py @@ -0,0 +1,479 @@ +""" +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.compat import PY314 +from pandas.errors import InvalidIndexError + +from pandas.core.dtypes.common import ( + is_float_dtype, + is_scalar, +) + +import pandas as pd +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, (pd.DatetimeIndex, pd.PeriodIndex, pd.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 = pd.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", + [ + ([0, 1, 2], 2), + ([0, 1, "2"], "2"), + ([0, 1, 2, np.inf, 4], 4), + ([0, 1, 2, np.nan, 4], 4), + ([0, 1, 2, np.inf], np.inf), + ([0, 1, 2, np.nan], np.nan), + ], + ) + def test_index_contains(self, index, val): + index = pd.Index(index) + assert val in index + + @pytest.mark.parametrize( + "index,val", + [ + (pd.Index([0, 1, 2]), "2"), + (pd.Index([0, 1, "2"]), 2), + (pd.Index([0, 1, 2, np.inf]), 4), + (pd.Index([0, 1, 2, np.nan]), 4), + (pd.Index([0, 1, 2, np.inf]), np.nan), + (pd.Index([0, 1, 2, np.nan]), np.inf), + # Checking if np.inf in int64 Index should not cause an OverflowError + # Related to GH 16957 + (pd.Index([0, 1, 2], dtype=np.int64), np.inf), + (pd.Index([0, 1, 2], dtype=np.int64), np.nan), + (pd.Index([0, 1, 2], dtype=np.uint64), np.inf), + (pd.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("val", [0, "2"]) + def test_mixed_index_contains(self, val): + # GH#19860 + index = pd.Index([0, 1, "2"]) + assert val in index + + @pytest.mark.parametrize("val", ["1", 2]) + def test_mixed_index_not_contains(self, index, val): + # GH#19860 + index = pd.Index([0, 1, "2"]) + 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 = pd.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, pd.MultiIndex): + return # TODO: do we want this to raise? + + msg = "unhashable type: 'list'" + with pytest.raises(TypeError, match=msg): + [] in index + + if PY314: + container_or_iterable = "a container or iterable" + else: + container_or_iterable = "iterable" + + 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 " + f"{container_or_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, + ( + pd.DatetimeIndex, + pd.TimedeltaIndex, + pd.PeriodIndex, + pd.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, + ( + pd.DatetimeIndex, + pd.TimedeltaIndex, + pd.PeriodIndex, + pd.IntervalIndex, + pd.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 = pd.Index([1, 2, pd.NA, pd.NA], dtype="Int64") + result = idx.get_loc(pd.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 = pd.Index([1, 2, pd.NA, pd.NA], dtype="Int64") + result = idx.get_indexer_for(pd.Index([1, pd.NA], dtype="Int64")) + expected = np.array([0, 2, 3], dtype=result.dtype) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_for_mixed_tuples(self): + # GH#41882 + idx = pd.Index(["i", "i", "j"]) + other = pd.Index([("i", "i"), ("i", "j"), ("j", "i"), "j"]) + result = idx.get_indexer_for(other) + expected = np.array([-1, -1, -1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +class TestPairwiseIndexer: + def test_pairwise_indexer(self): + # GH#67446 + idx = pd.Index(["a", "a", "b"]) + target = pd.Index(["a", "a", "b", "c"]) + result = idx._pairwise_indexer(target) + expected = np.array([0, 1, 2, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_pairwise_indexer_unsorted(self): + # GH#67446 + idx = pd.Index(["b", "a", "a"]) + target = pd.Index(["a", "a", "b"]) + result = idx._pairwise_indexer(target) + expected = np.array([1, 2, 0], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_pairwise_indexer_more_occurrences_in_target(self): + # GH#67446 + idx = pd.Index(["a", "b"]) + target = pd.Index(["a", "a", "b", "b"]) + result = idx._pairwise_indexer(target) + expected = np.array([0, -1, 1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_pairwise_indexer_unique_matches_get_indexer(self, index): + # GH#67446 + if not index._index_as_unique or isinstance(index, pd.MultiIndex): + pytest.skip("covered by duplicate-specific tests") + result = index._pairwise_indexer(index) + expected = index.get_indexer(index) + tm.assert_numpy_array_equal(result, expected) + + def test_pairwise_indexer_overlapping_intervals(self): + # GH#67446 + # get_indexer raises for overlapping intervals; exact matching is used + idx = pd.IntervalIndex.from_tuples([(0, 2), (1, 3), (0, 2)]) + target = pd.IntervalIndex.from_tuples([(0, 2), (0, 2), (1, 3), (4, 5)]) + result = idx._pairwise_indexer(target) + expected = np.array([0, 2, 1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_pairwise_indexer_empty(self): + # GH#67446 + idx = pd.Index([], dtype=object) + target = pd.Index(["a", "a"], dtype=object) + result = idx._pairwise_indexer(target) + expected = np.array([-1, -1], dtype=np.intp) + 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, pd.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( + "dtype, expected", + [ + ("int64", 2), + ("float64", 2.0), + ("Int64", 2), + ("category", 2), + ("datetime64[ns]", pd.Timestamp(2)), + ], +) +def test_getitem_scalar_result_type(dtype, expected, using_python_scalars): + # GH#64266 + idx = pd.Index([1, 2, 3], dtype=dtype) + result = idx[1] + assert result == expected + if using_python_scalars or isinstance(expected, pd.Timestamp): + assert type(result) is type(expected) + else: + assert isinstance(result, np.generic) + + +def test_getitem_object_dtype_preserves_numpy_scalars(): + # GH#64266 + value = np.int8(1) + idx = pd.Index([value, np.int8(2)], dtype=object) + with pd.option_context("future.python_scalars", True): + result = idx[0] + assert result is value + + +@pytest.mark.parametrize("idx", [[1, 2, 3], [0.1, 0.2, 0.3], ["a", "b", "c"]]) +def test_getitem_deprecated_float(idx): + # https://github.com/pandas-dev/pandas/issues/34191 + idx = pd.Index(idx) + 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), + ), + ( + pd.DatetimeIndex(["2020-08-05", pd.NaT, pd.NaT]), + [pd.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), + pd.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 = pd.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 = pd.Index([1.0, 2.0]) + target = pd.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)) + + +def test_get_indexer_non_unique_longdouble(): + # GH#66125 longdouble has no typed fastpath and must use the fallback + # (on platforms where longdouble is a distinct 16-byte dtype, the index + # is backed by ObjectEngine holding the raw longdouble ndarray) + index = pd.Index(np.array([1.0, 2.0, 2.0], dtype=np.longdouble)) + target = pd.Index(np.array([2.0, 3.0], dtype=np.longdouble)) + + result_idx, result_missing = index.get_indexer_non_unique(target) + + tm.assert_numpy_array_equal(result_idx, np.array([1, 2, -1], dtype=np.intp)) + tm.assert_numpy_array_equal(result_missing, np.array([1], dtype=np.intp)) + + +@pytest.mark.parametrize( + "dtype, target_values", + [ + ("Int64", [1, 2]), + ("Float64", [1.0, 2.0]), + ("boolean", [True, False]), + ("int64", [1, 2]), + ("float64", [1.0, 2.0]), + ("object", ["a", "b"]), + ], +) +def test_get_indexer_non_unique_empty_index(dtype, target_values): + # GH#64674 (masked) / GH#54746 (non-masked): an empty index reindexed + # against a non-empty target raised ZeroDivisionError in the binary-search + # heuristic. An empty index matches nothing, so every target is missing. + index = pd.Index([], dtype=dtype) + target = pd.Index(target_values, dtype=dtype) + + result_idx, result_missing = index.get_indexer_non_unique(target) + + tm.assert_numpy_array_equal(result_idx, np.array([-1, -1], dtype=np.intp)) + tm.assert_numpy_array_equal(result_missing, np.array([0, 1], dtype=np.intp)) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_numpy_compat.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_numpy_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..6768e3f076b72f41af71ef4c3173e2beea03bd97 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_numpy_compat.py @@ -0,0 +1,182 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.api.types import ( + is_complex_dtype, + is_numeric_dtype, +) +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 = pd.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 pd.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, (pd.DatetimeIndex, pd.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) + + out = np.empty(index.shape, dtype=bool) + func(index, out=out) + tm.assert_index_equal(pd.Index(out), result) + else: + with tm.external_error_raised(TypeError): + func(index) + + elif isinstance(index, pd.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) + assert isinstance(result, pd.Index) + if not isinstance(index.dtype, np.dtype): + # e.g. Int64 we expect to get BooleanArray back + assert isinstance(result.dtype, pd.BooleanDtype) + else: + assert isinstance(result.dtype, np.dtype) + + out = np.empty(index.shape, dtype=bool) + func(index, out=out) + + if not isinstance(index.dtype, np.dtype): + tm.assert_index_equal(result, pd.Index(out, dtype="boolean")) + else: + tm.assert_index_equal(result, pd.Index(out)) + + 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_sortable, func): + # TODO: overlap with tests.series.test_ufunc.test_reductions + index = index_sortable + if len(index) == 0: + pytest.skip("Test doesn't make sense for empty index.") + + if isinstance(index, pd.CategoricalIndex) and index.dtype.ordered is False: + with pytest.raises(TypeError, match="is not ordered for"): + func.reduce(index) + return + + 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 pd.isna(result): + assert pd.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 = pd.Index([1, 2, 3, 4], dtype="int64") + idx2 = pd.Index([3, 4, 5, 6], dtype="int64") + + with tm.assert_produces_warning(None): + result = func(idx1, idx2) + + expected = pd.Index(func(idx1.values, idx2.values)) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_old_base.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_old_base.py new file mode 100644 index 0000000000000000000000000000000000000000..fcf550fa6f769b82408a3c6b803036d8b935a471 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_old_base.py @@ -0,0 +1,996 @@ +from __future__ import annotations + +from datetime import datetime +import weakref + +import numpy as np +import pytest + +from pandas._libs.tslibs import Timestamp +from pandas.compat import PY315 +from pandas.errors import Pandas4Warning + +from pandas.core.dtypes.common import ( + is_integer_dtype, + is_numeric_dtype, +) +from pandas.core.dtypes.dtypes import CategoricalDtype + +import pandas as pd +import pandas._testing as tm +import pandas.core.algorithms as algos +from pandas.core.arrays import BaseMaskedArray + + +class TestBase: + @pytest.fixture( + params=[ + pd.RangeIndex(start=0, stop=20, step=2), + pd.Index(np.arange(5, dtype=np.float64)), + pd.Index(np.arange(5, dtype=np.float32)), + pd.Index(np.arange(5, dtype=np.uint64)), + pd.Index(range(0, 20, 2), dtype=np.int64), + pd.Index(range(0, 20, 2), dtype=np.int32), + pd.Index(range(0, 20, 2), dtype=np.int16), + pd.Index(range(0, 20, 2), dtype=np.int8), + pd.Index(list("abcde")), + pd.Index([0, "a", 1, "b", 2, "c"]), + 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", + ), + pd.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, pd.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\)", + r"'NoneType' object is not iterable", + ] + ) + 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, (pd.DatetimeIndex, pd.TimedeltaIndex, pd.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, pd.MultiIndex): + expected.name = "foo" + result = pd.Index(expected) + tm.assert_index_equal(result, expected) + + result = pd.Index(expected, name="bar") + expected.name = "bar" + tm.assert_index_equal(result, expected) + else: + expected.names = ["foo", "bar"] + result = pd.Index(expected) + tm.assert_index_equal( + result, + pd.Index( + pd.Index( + [ + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ], + dtype="object", + ), + names=["foo", "bar"], + ), + ) + + result = pd.Index(expected, names=["A", "B"]) + tm.assert_index_equal( + result, + pd.Index( + pd.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, pd.MultiIndex) + if type(idx) is pd.Index: + pytest.skip("Not applicable for Index") + if is_numeric_dtype(simple_index.dtype) or isinstance( + simple_index, pd.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 in (object, "string"): + 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: + if idx.dtype.kind == "M": + msg = "'(any|all)' with datetime64 dtypes is not supported" + else: + msg = "does not support operation '(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, pd.IntervalIndex): + pytest.skip(f"Not a valid repr for {type(simple_index).__name__}") + idx = simple_index + tm.assert_index_equal(eval(repr(idx), dict(vars(pd))), idx) + + def test_repr_max_seq_item_setting(self, simple_index): + # GH10182 + if isinstance(simple_index, pd.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) + + def test_ensure_copied_data(self, index): + # Check the "copy" argument of each Index.__new__ is honoured + # GH12309 + init_kwargs = {} + if isinstance(index, pd.PeriodIndex): + # Needs "freq" specification: + init_kwargs["freq"] = index.freq + elif isinstance(index, (pd.RangeIndex, pd.MultiIndex, pd.CategoricalIndex)): + pytest.skip( + "RangeIndex cannot be initialized from data, " + "MultiIndex and CategoricalIndex are tested separately" + ) + elif index.dtype == object and index.inferred_type in ["boolean", "string"]: + init_kwargs["dtype"] = index.dtype + + index_type = type(index) + result = index_type(index._values, copy=True, **init_kwargs) + if isinstance(index, (pd.DatetimeIndex, pd.TimedeltaIndex)): + index = index._with_freq(None) + + tm.assert_index_equal(index, result) + + if isinstance(index, pd.PeriodIndex): + result = index_type(index._values, copy=False, **init_kwargs) + tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same") + elif isinstance(index, pd.IntervalIndex): + # checked in test_interval.py + pass + elif type(index) is pd.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 ( + isinstance(index.dtype, pd.StringDtype) + and index.dtype.storage == "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 ( + isinstance(index.dtype, pd.StringDtype) + and index.dtype.storage == "pyarrow" + ): + assert tm.shares_memory(result._values, index._values) + else: + raise NotImplementedError(index.dtype) + else: + result = index_type(index._values, copy=False, **init_kwargs) + if isinstance(index, (pd.DatetimeIndex, pd.TimedeltaIndex)): + # ._values returns DatetimeArray/TimedeltaArray; check + # underlying ndarray is shared + tm.assert_numpy_array_equal( + index._values._ndarray, + result._values._ndarray, + check_same="same", + ) + elif isinstance(index.dtype, np.dtype): + tm.assert_numpy_array_equal( + index._values, result._values, check_same="same" + ) + else: + assert result._values is index._values + + 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, (pd.RangeIndex, pd.IntervalIndex)) and not ( + type(index) is pd.Index and not isinstance(index.dtype, np.dtype) + ): + assert result2 > result + + if index.inferred_type == "object": + assert result3 > result2 + + def test_memory_usage_doesnt_trigger_engine(self, index): + index._cache.clear() + assert "_engine" not in index._cache + + res_without_engine = index.memory_usage() + assert "_engine" not in index._cache + + # explicitly load and cache the engine + _ = index._engine + assert "_engine" in index._cache + + res_with_engine = index.memory_usage() + + # the empty engine doesn't affect the result even when initialized with values, + # because engine.sizeof() doesn't consider the content of engine.values + assert res_with_engine == res_without_engine + + if len(index) == 0: + assert res_without_engine == 0 + assert res_with_engine == 0 + else: + assert res_without_engine > 0 + assert res_with_engine > 0 + + def test_argsort(self, index_sortable): + index = index_sortable + if isinstance(index, pd.CategoricalIndex): + pytest.skip(f"{type(self).__name__} separately tested") + + result = index.argsort() + expected = np.array(index).argsort() + tm.assert_numpy_array_equal(result, expected) + + def test_numpy_argsort(self, index_sortable): + index = index_sortable + 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, (pd.CategoricalIndex, pd.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, (pd.IntervalIndex, pd.PeriodIndex) + ) or is_numeric_dtype(simple_index.dtype): + pytest.skip("Tested elsewhere.") + klass = listlike_box + + idx = simple_index + if isinstance(idx, (pd.DatetimeIndex, pd.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 = pd.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): + # GH#51363 + trimmed = index[1:4] + + if not len(index): + pytest.skip("Not applicable for empty index") + + result = trimmed.insert(0, index[0]) + assert index[0:4].equals(result) + + def test_insert_out_of_bounds(self, index, using_infer_string): + # 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" + elif PY315: + msg = "slice indices must be integers or have an __index__ method" + else: + msg = "slice indices must be integers or None or have an __index__ method" + + if using_infer_string: + if str(index.dtype) in {"str", "string", "category"}: + msg = "loc must be an integer between" + elif index.dtype == "object" and len(index) == 0: + msg = "loc must be an integer between" + err = TypeError + + 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, pd.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) + + def test_equals(self, index): + if isinstance(index, pd.IntervalIndex): + pytest.skip(f"{type(index).__name__} tested elsewhere") + + is_ea_idx = type(index) is pd.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, pd.RangeIndex) and not is_ea_idx: + same_values = pd.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(pd.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] + + # the Index length check raises before NumPy can attempt to broadcast + msg = "Lengths must match" + 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 = pd.Series(array_a) + series_b = pd.Series(array_b) + series_c = pd.Series(array_c) + series_d = pd.Series(array_d) + with pytest.raises(ValueError, match=msg): + index_a == series_b + + tm.assert_series_equal(index_a == series_a, pd.Series(expected1)) + tm.assert_series_equal(index_a == series_c, pd.Series(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, pd.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, pd.Series(expected3)) + + 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, pd.Index) and is_integer_dtype(index.dtype): + pytest.skip(f"Not relevant for Index with {index.dtype}") + elif isinstance(index, pd.MultiIndex): + idx = index.copy(deep=True) + msg = "fillna 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) + + 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, pd.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 = pd.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) + expected = simple_index + if join_type == "outer": + expected = algos.safe_sort(expected) + tm.assert_index_equal(joined, expected) + + def test_map(self, simple_index): + # callable + if isinstance(simple_index, (pd.TimedeltaIndex, pd.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", check_freq=False) + + @pytest.mark.parametrize( + "mapper", + [ + lambda values, index: {i: e for e, i in zip(values, index, strict=True)}, + lambda values, index: pd.Series(values, index), + ], + ) + def test_map_dictlike(self, mapper, simple_index, request): + idx = simple_index + if isinstance(idx, (pd.DatetimeIndex, pd.TimedeltaIndex, pd.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 = pd.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, pd.CategoricalIndex): + pytest.skip("See test_map.py") + idx = simple_index + result = idx.map(str) + expected = pd.Index([str(x) for x in idx]) + 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 = pd.CategoricalIndex(idx, name=name, ordered=ordered) + tm.assert_index_equal(result, expected, exact=True, check_freq=False) + + # non-standard categories + dtype = CategoricalDtype(idx.unique().tolist()[:-1], ordered) + msg = "Constructing a Categorical with a dtype and values containing" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = idx.astype(dtype, copy=copy) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + expected = pd.CategoricalIndex(idx, name=name, dtype=dtype) + tm.assert_index_equal(result, expected, exact=True, check_freq=False) + + if ordered is False: + # dtype='category' defaults to ordered=False, so only test once + result = idx.astype("category", copy=copy) + expected = pd.CategoricalIndex(idx, name=name) + tm.assert_index_equal(result, expected, exact=True, check_freq=False) + + 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.copy() + ref = weakref.ref(index) + index._engine + del index + assert ref() is None + + def test_getitem_2d_deprecated(self, simple_index): + # GH#30588, GH#31479 + if isinstance(simple_index, pd.IntervalIndex): + pytest.skip("Tested elsewhere") + idx = simple_index + msg = "|".join(["Multi-dimensional indexing", "too many", "only"]) + with pytest.raises((ValueError, IndexError), match=msg): + idx[:, None] + + if not isinstance(idx, pd.RangeIndex): + # GH#44051 RangeIndex already raised pre-2.0 with a different message + with pytest.raises((ValueError, IndexError), match=msg): + idx[True] + with pytest.raises((ValueError, IndexError), 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 = pd.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", tz="UTC"), + Timestamp("2011-12-01", tz="UTC"), + ] + 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, exact=False, check_exact=True, check_freq=False + ) + tm.assert_index_equal( + result[N:], index, exact=False, check_exact=True, check_freq=False + ) + + alt = index.take(list(range(N)) * 2) + tm.assert_index_equal(result, alt, check_exact=True, check_freq=False) + + def test_inv(self, simple_index, using_infer_string): + idx = simple_index + + if idx.dtype.kind in ["i", "u"]: + res = ~idx + expected = pd.Index(~idx.values, name=idx.name) + tm.assert_index_equal(res, expected, exact="equiv") + + # check that we are matching Series behavior + res2 = ~pd.Series(idx) + tm.assert_series_equal(res2, pd.Series(expected)) + else: + if idx.dtype.kind == "f": + msg = "ufunc 'invert' not supported for the input types" + else: + msg = "|".join( + ["bad operand", "__invert__ is not supported for string dtype"] + ) + with pytest.raises(TypeError, match=msg): + ~idx + + # check that we get the same behavior with Series + with pytest.raises(TypeError, match=msg): + ~pd.Series(idx) + + +class TestNumericBase: + @pytest.fixture( + params=[ + pd.RangeIndex(start=0, stop=20, step=2), + pd.Index(np.arange(5, dtype=np.float64)), + pd.Index(np.arange(5, dtype=np.float32)), + pd.Index(np.arange(5, dtype=np.uint64)), + pd.Index(range(0, 20, 2), dtype=np.int64), + pd.Index(range(0, 20, 2), dtype=np.int32), + pd.Index(range(0, 20, 2), dtype=np.int16), + pd.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, pd.RangeIndex): + pytest.skip("Tested elsewhere.") + index_cls = type(simple_index) + dtype = simple_index.dtype + + idx = pd.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, pd.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) + + msg = "Cannot change data-type" + with pytest.raises(TypeError, match=msg): + # GH#55709 + idx.view(index_cls) + + 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 = pd.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 = pd.Index([index[0], pd.NaT, *list(index[1:])], dtype=object) + else: + expected = pd.Index([index[0], np.nan, *list(index[1:])]) + # GH#43921 we preserve float dtype + if index.dtype.kind == "f": + expected = pd.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 pd.RangeIndex: + idx = pd.RangeIndex(5) + else: + idx = index_cls(np.arange(5, dtype="int64")) + + # float conversions + arr = np.arange(5, dtype="int64") * 3.2 + expected = pd.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 = pd.Index(arr, dtype=np.float64) + a = np.zeros(5, dtype="float64") + result = fidx - a + tm.assert_index_equal(result, expected) + + expected = pd.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 pd.Index and result.dtype == complex_dtype + + def test_cast_string(self, simple_index): + if isinstance(simple_index, pd.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/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_setops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..956fbeb1385f7456a925d76bbc6ee792665de31f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_setops.py @@ -0,0 +1,1043 @@ +""" +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._config import using_string_dtype + +from pandas._libs import lib +import pandas.util._test_decorators as td + +from pandas.core.dtypes.cast import find_common_type + +import pandas as pd +import pandas._testing as tm +from pandas.api.types import ( + is_signed_integer_dtype, + pandas_dtype, +) + + +def equal_contents(arr1, arr2) -> bool: + """ + Checks if the set of unique elements of arr1 and arr2 are equivalent. + """ + return frozenset(arr1) == frozenset(arr2) + + +@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 + + +def test_union_same_types(index_sortable): + # Union with a non-unique, non-monotonic index raises error + # Only needed for bool index factory + idx1 = index_sortable.sort_values() + idx2 = index_sortable.sort_values() + assert idx1.union(idx2).dtype == idx1.dtype + + +def test_union_different_types(index_flat_sortable, index_flat2_sortable): + # This test only considers combinations of indices + # GH 23525 + idx1 = index_flat_sortable + idx2 = index_flat2_sortable + + if using_string_dtype() and len(idx1) == 0 and idx1.dtype == object: + # GH#60797 a zero-length object-dtype Index is ignored when determining + # the resulting dtype + common_dtype = idx2.dtype + elif using_string_dtype() and len(idx2) == 0 and idx2.dtype == object: + common_dtype = idx1.dtype + else: + 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 + + 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( + "idx1,idx2", + [ + (pd.Index(np.arange(5), dtype=np.int64), pd.RangeIndex(5)), + ( + pd.Index(np.arange(5), dtype=np.float64), + pd.Index(np.arange(5), dtype=np.int64), + ), + (pd.Index(np.arange(5), dtype=np.float64), pd.RangeIndex(5)), + ( + pd.Index(np.arange(5), dtype=np.float64), + pd.Index(np.arange(5), dtype=np.uint64), + ), + ], +) +def test_compatible_inconsistent_pairs(idx1, idx2): + # GH 23525 + 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 = pd.Index([], dtype=left, name=names[0]) + b = pd.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 = pd.Index(values) + b = pd.Index([3, 3]) + result = a.intersection(b) + expected = pd.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) + + def test_intersection_base(self, index): + if isinstance(index, pd.CategoricalIndex): + pytest.skip(f"Not relevant for {type(index).__name__}") + + first = index[:5].unique() + second = index[:3].unique() + intersect = first.intersection(second) + tm.assert_index_equal(intersect, second) + + if isinstance(index.dtype, pd.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 equal_contents(result, second) + + if isinstance(index, pd.MultiIndex): + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.intersection([1, 2, 3]) + + def test_union_base(self, index_sortable): + index = index_sortable.unique() + first = index[3:] + second = index[:5] + everything = index + + union = first.union(second) + tm.assert_index_equal(union.sort_values(), everything.sort_values()) + + if isinstance(index.dtype, pd.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 equal_contents(result, everything) + + if isinstance(index, pd.MultiIndex): + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.union([1, 2, 3]) + + 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, pd.CategoricalIndex): + answer = [] + else: + answer = index[4:] + result = first.difference(second, sort) + assert equal_contents(result, answer) + + # GH#10149 + cases = [second.to_numpy(), second.to_series(), second.to_list()] + for case in cases: + result = first.difference(case, sort) + assert equal_contents(result, answer) + + if isinstance(index, pd.MultiIndex): + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.difference([1, 2, 3], sort) + + def test_symmetric_difference(self, index_sortable, using_infer_string, request): + index = index_sortable + if ( + using_infer_string + and index.dtype == "object" + and index.inferred_type == "string" + ): + request.applymarker(pytest.mark.xfail(reason="TODO: infer_string")) + if isinstance(index, pd.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) + tm.assert_index_equal(result.sort_values(), answer.sort_values()) + + # GH#10149 + cases = [second.to_numpy(), second.to_series(), second.to_list()] + for case in cases: + result = first.symmetric_difference(case) + assert equal_contents(result, answer) + + if isinstance(index, pd.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: + index = index_flat.unique() + else: + 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_sortable, fname, sname, expected_name): + if not index_flat_sortable.is_unique: + index = index_flat_sortable.unique() + else: + index = index_flat_sortable + + # 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: + index = index_flat.unique() + else: + 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_sortable, fname, sname, expected_name): + if not index_flat_sortable.is_unique: + index = index_flat_sortable.unique() + else: + index = index_flat_sortable + + # 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) + + def test_intersection_name_retention_with_nameless(self, index): + if isinstance(index, pd.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, pd.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.parametrize( + "method", ["intersection", "union", "difference", "symmetric_difference"] +) +def test_setop_with_categorical(index_flat, sort, method, using_infer_string): + # MultiIndex tested separately in tests.indexes.multi.test_setops + index = index_flat + + other = index.astype("category") + exact = "equiv" if isinstance(index, pd.RangeIndex) else True + + result = getattr(index, method)(other, sort=sort) + expected = getattr(index, method)(index, sort=sort) + if ( + using_infer_string + and index.empty + and method in ("union", "symmetric_difference") + ): + expected = expected.astype("category") + tm.assert_index_equal(result, expected, exact=exact) + + result = getattr(index, method)(other[:5], sort=sort) + expected = getattr(index, method)(index[:5], sort=sort) + if ( + using_infer_string + and index.empty + and method in ("union", "symmetric_difference") + ): + expected = expected.astype("category") + 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 = pd.Index([1, 2, 2, 3], dtype=dtype) + b = pd.Index([3, 3, 4], dtype=dtype) + + expected = pd.Index([1, 2, 2, 3, 3, 4], dtype=dtype) + if isinstance(a, pd.CategoricalIndex): + expected = pd.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 = pd.Index([1, 0, 0], dtype=dtype) + b = pd.Index([0, 1], dtype=dtype) + expected = pd.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 = pd.Index([1, 2, 2, 3]) + b = pd.Index(["1", "0", "0"]) + expected = pd.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 = pd.Index([0, 0, 1]) + b = pd.Index([0, 0, 1, 2]) + result = a.union(b) + expected = pd.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 = pd.Index([np.nan, 1, 2, 2]) + b = pd.Index([np.nan, dup, 1, 2]) + result = a.union(b, sort=False) + expected = pd.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 = pd.RangeIndex(1, 100, 6) + idx2 = pd.RangeIndex(1, 50, 3) + result = idx1.union(idx2, sort=True) + expected = pd.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 = pd.Index([1, 0, 2], dtype=dtype) + b = pd.Index([0, 0, 1], dtype=dtype) + expected = pd.Index([0, 0, 1, 2], dtype=dtype) + if isinstance(a, pd.CategoricalIndex): + expected = pd.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 = pd.CategoricalIndex([1, 2, np.nan]) + assert ci.categories.dtype.kind == "i" + + idx = pd.Index([1, 2]) + + result = idx.union(ci) + expected = pd.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 = pd.Index(dt_dates, dtype=object) + index2 = pd.Index(["aa"], dtype=object) + result = index2.intersection(index1) + + expected = pd.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 in (None, False): + tm.assert_index_equal(intersect.sort_values(), second.sort_values()) + else: + tm.assert_index_equal(intersect, second) + + # Corner cases + inter = first.intersection(first, sort=sort) + assert inter is not first + + @pytest.mark.parametrize( + "index2_name,keeps_name", + [ + ("index", True), # preserve same name + ("other", False), # drop diff names + (None, False), + ], + ) + def test_intersection_name_preservation(self, index2_name, keeps_name, sort): + index2 = pd.Index([3, 4, 5, 6, 7], name=index2_name) + index1 = pd.Index([1, 2, 3, 4, 5], name="index") + expected = pd.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 = pd.Index([1, 2], name="i1") + i2 = pd.Index([5, 6], name="i2") + i3 = pd.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 = pd.Index([1, 2], name="j1") + j2 = pd.Index([], name="j2") + j3 = pd.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 in (None, False): + tm.assert_index_equal(union.sort_values(), everything.sort_values()) + else: + tm.assert_index_equal(union, everything) + + @pytest.mark.parametrize("klass", [np.array, pd.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 in (None, False): + tm.assert_index_equal(result.sort_values(), everything.sort_values()) + else: + tm.assert_index_equal(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) + # GH#63169 - identity is not preserved to prevent shared mutable state + assert union is not first + + # This should no longer be the same object, since [] is not consistent, + # both objects will be recast to dtype('O') + union = first.union(pd.Index([], dtype=first.dtype), sort=sort) + assert union is not first + + union = pd.Index([], dtype=first.dtype).union(first, sort=sort) + assert union is not first + + @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) + + if sort is True: + tm.assert_index_equal(result, answer) + else: + answer.name = second_name + tm.assert_index_equal(result.sort_values(), answer.sort_values()) + + if expected is None: + assert result.name is None + else: + assert result.name == expected + + def test_difference_empty_arg(self, index, sort): + first = index.copy() + first = first[5:20] + first.name = "name" + result = first.difference([], sort) + expected = index[5:20].unique() + expected.name = "name" + tm.assert_index_equal(result, expected) + + def test_difference_should_not_compare(self): + # GH 55113 + left = pd.Index([1, 1]) + right = pd.Index([True]) + result = left.difference(right) + expected = pd.Index([1]) + tm.assert_index_equal(result, expected) + + @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 = pd.Index([3, pd.Timestamp("2000"), 1]) + b = pd.Index([2, pd.Timestamp("1999"), 1]) + op = operator.methodcaller(opname, b) + + with tm.assert_produces_warning(RuntimeWarning, match="not supported between"): + # sort=None, the default + result = op(a) + expected = pd.Index([3, pd.Timestamp("2000"), 2, pd.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 = pd.Index([3, pd.Timestamp("2000"), 1]) + b = pd.Index([2, pd.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 = pd.MultiIndex.from_tuples( + zip(["foo", "bar", "baz"], [1, 2, 3], strict=True) + ) + index2 = pd.MultiIndex.from_tuples([("foo", 1), ("bar", 3)]) + result = index1.symmetric_difference(index2, sort=sort) + expected = pd.MultiIndex.from_tuples([("bar", 2), ("baz", 3), ("bar", 3)]) + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "index2,expected", + [ + ([0, 1, np.nan], [2.0, 3.0, 0.0]), + ([0, 1], [np.nan, 2.0, 3.0, 0.0]), + ], + ) + def test_symmetric_difference_missing(self, index2, expected, sort): + index2 = pd.Index(index2) + expected = pd.Index(expected) + # GH#13514 change: {nan} - {nan} == {} + # (GH#6444, sorting of nans, is no longer an issue) + index1 = pd.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 = pd.Index([1, 2, 3, 4], name="index1") + index2 = np.array([2, 3, 4, 5]) + expected = pd.Index([1, 5], name="index1") + result = index1.symmetric_difference(index2, sort=sort) + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + assert result.name == "index1" + + result = index1.symmetric_difference(index2, result_name="new_name", sort=sort) + expected.name = "new_name" + if sort in (None, True): + tm.assert_index_equal(result, expected) + else: + tm.assert_index_equal(result.sort_values(), expected) + assert result.name == "new_name" + + def test_union_ea_dtypes(self, any_numeric_ea_and_arrow_dtype): + # GH#51365 + idx = pd.Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype) + idx2 = pd.Index([3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype) + result = idx.union(idx2) + expected = pd.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 = pd.Index(["a"], dtype=any_string_dtype) + idx2 = pd.Index(["b"], dtype=any_string_dtype) + result = idx1.union(idx2) + expected = pd.Index(["a", "b"], dtype=any_string_dtype) + tm.assert_index_equal(result, expected) + + @td.skip_if_no("pyarrow") + def test_union_pyarrow_timestamp(self): + # GH#58421 + left = pd.Index(["2020-01-01"], dtype="timestamp[s][pyarrow]") + right = pd.Index(["2020-01-02"], dtype="timestamp[s][pyarrow]") + + res = left.union(right) + expected = pd.Index(["2020-01-01", "2020-01-02"], dtype=left.dtype) + tm.assert_index_equal(res, expected) + + +def test_intersection_mutation_safety(): + # GH#63169 + index1 = pd.Index([0, 1], name="original") + index2 = pd.Index([0, 1], name="original") + + result = index1.intersection(index2) + + assert result is not index1 + assert result is not index2 + + tm.assert_index_equal(result, index1) + assert result.name == "original" + + index1.name = "changed" + + assert result.name == "original" + assert index1.name == "changed" + + +def test_union_mutation_safety(): + # GH#63169 + index1 = pd.Index([0, 1], name="original") + index2 = pd.Index([0, 1], name="original") + + result = index1.union(index2) + + assert result is not index1 + assert result is not index2 + + tm.assert_index_equal(result, index1) + assert result.name == "original" + + index1.name = "changed" + + assert result.name == "original" + assert index1.name == "changed" + + +def test_union_mutation_safety_other(): + # GH#63169 + index1 = pd.Index([0, 1], name="original") + index2 = pd.Index([0, 1], name="original") + + result = index1.union(index2) + + assert result is not index2 + + tm.assert_index_equal(result, index2) + assert result.name == "original" + + index2.name = "changed" + + assert result.name == "original" + assert index2.name == "changed" + + +def test_multiindex_intersection_mutation_safety(): + # GH#63169 + mi1 = pd.MultiIndex.from_tuples([("a", 1), ("b", 2)], names=["x", "y"]) + mi2 = pd.MultiIndex.from_tuples([("a", 1), ("b", 2)], names=["x", "y"]) + + result = mi1.intersection(mi2) + assert result is not mi1 + + mi1.names = ["changed1", "changed2"] + assert result.names == ["x", "y"] + + +def test_multiindex_union_mutation_safety(): + # GH#63169 + mi1 = pd.MultiIndex.from_tuples([("a", 1), ("b", 2)], names=["x", "y"]) + mi2 = pd.MultiIndex.from_tuples([("a", 1), ("b", 2)], names=["x", "y"]) + + result = mi1.union(mi2) + assert result is not mi1 + + mi1.names = ["changed1", "changed2"] + assert result.names == ["x", "y"] + + +def test_union_disjoint_monotonic_sorted(): + # GH#54646 - union of two disjoint monotonic-increasing Index objects + # should be sorted when sort is not False, even though both inputs are + # individually monotonic. + idx1 = pd.Index([5, 6, 7]) + idx2 = pd.Index([1, 2, 3]) + + result = idx1.union(idx2, sort=None) + expected = pd.Index([1, 2, 3, 5, 6, 7]) + tm.assert_index_equal(result, expected) + + result_false = idx1.union(idx2, sort=False) + expected_false = pd.Index([5, 6, 7, 1, 2, 3]) + tm.assert_index_equal(result_false, expected_false) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_subclass.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_subclass.py new file mode 100644 index 0000000000000000000000000000000000000000..e244b80dc15e3740c9257545fe43d6671d2594a0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/test_subclass.py @@ -0,0 +1,38 @@ +""" +Tests involving custom Index subclasses +""" + +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class CustomIndex(pd.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 = pd.Index(["string", 1, 2, 3], dtype=object) + tm.assert_index_equal(result, expected) + + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((2, 3)), + columns=idx, + index=pd.Index([1, 2], name="string"), + ) + result = df.reset_index() + tm.assert_index_equal(result.columns, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_astype.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f004f85ec7eaa69d28f705be31a5cae61708c1 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_astype.py @@ -0,0 +1,178 @@ +from datetime import timedelta + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import TimedeltaArray + + +class TestTimedeltaIndex: + def test_astype_object(self): + idx = pd.timedelta_range(start="1 days", periods=4, freq="D", name="idx") + expected_list = [ + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + pd.Timedelta("3 days"), + pd.Timedelta("4 days"), + ] + result = idx.astype(object) + expected = pd.Index(expected_list, dtype=object, name="idx") + tm.assert_index_equal(result, expected) + assert idx.tolist() == expected_list + + def test_astype_object_with_nat(self): + idx = pd.TimedeltaIndex( + [timedelta(days=1), timedelta(days=2), pd.NaT, timedelta(days=4)], + name="idx", + ) + expected_list = [ + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + pd.NaT, + pd.Timedelta("4 days"), + ] + result = idx.astype(object) + expected = pd.Index(expected_list, dtype=object, name="idx") + tm.assert_index_equal(result, expected) + assert idx.tolist() == expected_list + + def test_astype(self, using_infer_string): + # GH 13149, GH 13209 + idx = pd.TimedeltaIndex([1e14, "NaT", pd.NaT, np.nan], name="idx") + + result = idx.astype(object) + expected = pd.Index( + [pd.Timedelta("1 days 03:46:40")] + [pd.NaT] * 3, dtype=object, name="idx" + ) + tm.assert_index_equal(result, expected) + + result = idx.astype(np.int64) + expected = pd.Index( + [100000000000000] + [-9223372036854775808] * 3, dtype=np.int64, name="idx" + ) + tm.assert_index_equal(result, expected) + + result = idx.astype(str) + if using_infer_string: + expected = pd.Index( + [str(x) if x is not pd.NaT else None for x in idx], + name="idx", + dtype="str", + ) + else: + expected = pd.Index([str(x) for x in idx], name="idx", dtype=object) + tm.assert_index_equal(result, expected) + + rng = pd.timedelta_range("1 days", periods=10) + result = rng.astype("i8") + tm.assert_index_equal(result, pd.Index(rng.asi8)) + tm.assert_numpy_array_equal(rng.asi8, result.values) + + def test_astype_uint(self): + arr = pd.timedelta_range("1h", periods=2) + + with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"): + arr.astype("uint64") + with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"): + arr.astype("uint32") + + def test_astype_timedelta64(self): + # GH 13149, GH 13209 + idx = pd.TimedeltaIndex([1e14, "NaT", pd.NaT, np.nan]) + + msg = ( + r"Cannot convert from timedelta64\[ns\] to timedelta64. " + "Supported resolutions are 's', 'ms', 'us', 'ns'" + ) + with pytest.raises(ValueError, match=msg): + idx.astype("timedelta64") + + result = idx.astype("timedelta64[ns]") + tm.assert_index_equal(result, idx) + assert result is not idx + + result = idx.astype("timedelta64[ns]", copy=False) + tm.assert_index_equal(result, idx) + assert result is idx + + def test_astype_to_td64d_raises(self, index_or_series): + # We don't support "D" reso + scalar = pd.Timedelta(days=31) + td = index_or_series( + [scalar, scalar, scalar + timedelta(minutes=5, seconds=3), pd.NaT], + dtype="m8[ns]", + ) + msg = ( + r"Cannot convert from timedelta64\[ns\] to timedelta64\[D\]. " + "Supported resolutions are 's', 'ms', 'us', 'ns'" + ) + with pytest.raises(ValueError, match=msg): + td.astype("timedelta64[D]") + + def test_astype_ms_to_s(self, index_or_series): + scalar = pd.Timedelta(days=31) + td = index_or_series( + [scalar, scalar, scalar + timedelta(minutes=5, seconds=3), pd.NaT], + dtype="m8[ns]", + ) + + exp_values = np.asarray(td).astype("m8[s]") + exp_tda = TimedeltaArray._simple_new(exp_values, dtype=exp_values.dtype) + expected = index_or_series(exp_tda) + assert expected.dtype == "m8[s]" + result = td.astype("timedelta64[s]") + tm.assert_equal(result, expected) + + def test_astype_freq_conversion(self): + # pre-2.0 td64 astype converted to float64. now for supported units + # (s, ms, us, ns) this converts to the requested dtype. + # This matches TDA and Series + tdi = pd.timedelta_range("1 Day", periods=30) + + res = tdi.astype("m8[s]") + exp_values = np.asarray(tdi).astype("m8[s]") + exp_tda = TimedeltaArray._simple_new(exp_values, dtype=exp_values.dtype) + expected = pd.Index(exp_tda) + expected._freq = tdi.freq + assert expected.dtype == "m8[s]" + tm.assert_index_equal(res, expected) + + # check this matches Series and TimedeltaArray + exp_arr = expected._values + + res = tdi._data.astype("m8[s]") + tm.assert_equal(res, exp_arr) + + res = tdi.to_series().astype("m8[s]") + tm.assert_equal(res._values, exp_arr) + + @pytest.mark.parametrize("dtype", [float, "datetime64", "datetime64[ns]"]) + def test_astype_raises(self, dtype): + # GH 13149, GH 13209 + idx = pd.TimedeltaIndex([1e14, "NaT", pd.NaT, np.nan]) + msg = "Cannot cast TimedeltaIndex to dtype" + with pytest.raises(TypeError, match=msg): + idx.astype(dtype) + + def test_astype_category(self): + obj = pd.timedelta_range("1h", periods=2, freq="h") + + result = obj.astype("category") + expected = pd.CategoricalIndex(pd.timedelta_range("1h", periods=2, freq="h")) + tm.assert_index_equal(result, expected, check_freq=False) + + result = obj._data.astype("category") + expected = expected.values + tm.assert_categorical_equal(result, expected, check_freq=False) + + def test_astype_array_fallback(self): + obj = pd.timedelta_range("1h", periods=2) + result = obj.astype(bool) + expected = pd.Index(np.array([True, True])) + tm.assert_index_equal(result, expected) + + result = obj._data.astype(bool) + expected = np.array([True, True]) + tm.assert_numpy_array_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_factorize.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_factorize.py new file mode 100644 index 0000000000000000000000000000000000000000..7fb197ec7b07577fa04020bb80704518ff46749f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_factorize.py @@ -0,0 +1,53 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestTimedeltaIndexFactorize: + def test_factorize(self): + idx1 = pd.TimedeltaIndex(["1 day", "1 day", "2 day", "2 day", "3 day", "3 day"]) + + exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) + exp_idx = pd.TimedeltaIndex(["1 day", "2 day", "3 day"]) + + arr, idx = idx1.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + arr, idx = idx1.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + def test_factorize_monotonic_decreasing_no_freq(self): + # GH#66046 fastpath for a monotonic decreasing index without a freq + idx = pd.TimedeltaIndex(["3 days", "3 days", "2 days", "1 days"]) + assert idx.freq is None + + exp_arr = np.array([0, 0, 1, 2], dtype=np.intp) + exp_idx = pd.TimedeltaIndex(["3 days", "2 days", "1 days"]) + arr, result_idx = idx.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(result_idx, exp_idx) + + exp_arr = np.array([2, 2, 1, 0], dtype=np.intp) + exp_idx = pd.TimedeltaIndex(["1 days", "2 days", "3 days"]) + arr, result_idx = idx.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(result_idx, exp_idx) + + def test_factorize_preserves_freq(self): + # GH#38120 freq should be preserved + idx3 = pd.timedelta_range("1 day", periods=4, freq="s") + exp_arr = np.array([0, 1, 2, 3], dtype=np.intp) + arr, idx = idx3.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, idx3) + assert idx.freq == idx3.freq + + arr, idx = pd.factorize(idx3) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, idx3) + assert idx.freq == idx3.freq diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_fillna.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_fillna.py new file mode 100644 index 0000000000000000000000000000000000000000..404facc7928cd7a41c5ce58178faccca6eedfd7a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_fillna.py @@ -0,0 +1,24 @@ +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestFillNA: + def test_fillna_timedelta(self): + # GH#11343 + idx = pd.TimedeltaIndex(["1 day", pd.NaT, "3 day"]) + + exp = pd.TimedeltaIndex(["1 day", "2 day", "3 day"]) + tm.assert_index_equal(idx.fillna(pd.Timedelta("2 day")), exp) + + exp = pd.TimedeltaIndex(["1 day", "3 hour", "3 day"]) + idx.fillna(pd.Timedelta("3 hour")) + + exp = pd.Index( + [pd.Timedelta("1 day"), "x", pd.Timedelta("3 day")], dtype=object + ) + # GH#45153 filling with incompatible value is deprecated + with tm.assert_produces_warning(Pandas4Warning, match="fill value"): + result = idx.fillna("x") + tm.assert_index_equal(result, exp) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_insert.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_insert.py new file mode 100644 index 0000000000000000000000000000000000000000..5b3dcb512354477a036b805e5492613a3957b012 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_insert.py @@ -0,0 +1,144 @@ +from datetime import timedelta + +import numpy as np +import pytest + +from pandas._libs import lib + +import pandas as pd +import pandas._testing as tm + + +class TestTimedeltaIndexInsert: + def test_insert(self): + idx = pd.TimedeltaIndex(["4day", "1day", "2day"], name="idx") + + result = idx.insert(2, timedelta(days=5)) + exp = pd.TimedeltaIndex(["4day", "1day", "5day", "2day"], name="idx") + tm.assert_index_equal(result, exp) + + # insertion of non-datetime should coerce to object index + result = idx.insert(1, "inserted") + expected = pd.Index( + [ + pd.Timedelta("4day"), + "inserted", + pd.Timedelta("1day"), + pd.Timedelta("2day"), + ], + name="idx", + ) + assert not isinstance(result, pd.TimedeltaIndex) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + + idx = pd.timedelta_range("1day 00:00:01", periods=3, freq="s", name="idx") + + # preserve freq + expected_0 = pd.TimedeltaIndex( + ["1day", "1day 00:00:01", "1day 00:00:02", "1day 00:00:03"], + name="idx", + freq="s", + ) + expected_3 = pd.TimedeltaIndex( + ["1day 00:00:01", "1day 00:00:02", "1day 00:00:03", "1day 00:00:04"], + name="idx", + freq="s", + ) + + # reset freq to None + expected_1_nofreq = pd.TimedeltaIndex( + ["1day 00:00:01", "1day 00:00:01", "1day 00:00:02", "1day 00:00:03"], + name="idx", + freq=None, + ) + expected_3_nofreq = pd.TimedeltaIndex( + ["1day 00:00:01", "1day 00:00:02", "1day 00:00:03", "1day 00:00:05"], + name="idx", + freq=None, + ) + + cases = [ + (0, pd.Timedelta("1day"), expected_0), + (-3, pd.Timedelta("1day"), expected_0), + (3, pd.Timedelta("1day 00:00:04"), expected_3), + (1, pd.Timedelta("1day 00:00:01"), expected_1_nofreq), + (3, pd.Timedelta("1day 00:00:05"), expected_3_nofreq), + ] + + for n, d, expected in cases: + result = idx.insert(n, d) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + + @pytest.mark.parametrize( + "null", [None, np.nan, np.timedelta64("NaT", "ns"), pd.NaT, pd.NA] + ) + def test_insert_nat(self, null): + # GH 18295 (test missing) + idx = pd.timedelta_range("1day", "3day") + result = idx.insert(1, null) + expected = pd.TimedeltaIndex(["1day", pd.NaT, "2day", "3day"]) + tm.assert_index_equal(result, expected) + + def test_insert_invalid_na(self): + idx = pd.TimedeltaIndex(["4day", "1day", "2day"], name="idx") + + item = np.datetime64("NaT", "ns") + result = idx.insert(0, item) + + expected = pd.Index([item, *list(idx)], dtype=object, name="idx") + tm.assert_index_equal(result, expected) + + # Also works if we pass a different dt64nat object + item2 = np.datetime64("NaT", "ns") + result = idx.insert(0, item2) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "item", [0, np.int64(0), np.float64(0), np.array(0), np.datetime64(456, "us")] + ) + def test_insert_mismatched_types_raises(self, item): + # GH#33703 dont cast these to td64 + tdi = pd.TimedeltaIndex(["4day", "1day", "2day"], name="idx") + + result = tdi.insert(1, item) + + expected = pd.Index( + [tdi[0], lib.item_from_zerodim(item), *list(tdi[1:])], + dtype=object, + name="idx", + ) + tm.assert_index_equal(result, expected) + + def test_insert_castable_str(self): + idx = pd.timedelta_range("1day", "3day") + + result = idx.insert(0, "1 Day") + + expected = pd.TimedeltaIndex([idx[0], *list(idx)]) + tm.assert_index_equal(result, expected) + + def test_insert_non_castable_str(self): + idx = pd.timedelta_range("1day", "3day") + + result = idx.insert(0, "foo") + + expected = pd.Index(["foo", *list(idx)], dtype=object) + tm.assert_index_equal(result, expected) + + def test_insert_empty(self): + # Corner case inserting with length zero doesn't raise IndexError + # GH#33573 for freq preservation + idx = pd.timedelta_range("1 Day", periods=3) + td = idx[0] + + result = idx[:0].insert(0, td) + assert result.freq == "D" + + with pytest.raises(IndexError, match="loc must be an integer between"): + result = idx[:0].insert(1, td) + + with pytest.raises(IndexError, match="loc must be an integer between"): + result = idx[:0].insert(-1, td) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_repeat.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_repeat.py new file mode 100644 index 0000000000000000000000000000000000000000..8983209b0639c7067031c6a94cee8238cf33de98 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_repeat.py @@ -0,0 +1,31 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestRepeat: + def test_repeat(self): + index = pd.timedelta_range("1 days", periods=2, freq="D") + exp = pd.TimedeltaIndex(["1 days", "1 days", "2 days", "2 days"]) + for res in [index.repeat(2), np.repeat(index, 2)]: + tm.assert_index_equal(res, exp) + assert res.freq is None + + index = pd.TimedeltaIndex(["1 days", "NaT", "3 days"]) + exp = pd.TimedeltaIndex( + [ + "1 days", + "1 days", + "1 days", + "NaT", + "NaT", + "NaT", + "3 days", + "3 days", + "3 days", + ] + ) + for res in [index.repeat(3), np.repeat(index, 3)]: + tm.assert_index_equal(res, exp) + assert res.freq is None diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_resolution.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..40b9cbee0dc4b90f1882ad2ef91523a41d1de9fc --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_resolution.py @@ -0,0 +1,29 @@ +import pytest + +import pandas as pd + + +@pytest.mark.parametrize( + "timedelta_val,expected", + [ + ("1 day", "day"), + ("1 hour", "hour"), + ("1 minute", "minute"), + ("1 second", "second"), + ("1 millisecond", "millisecond"), + ("1 microsecond", "microsecond"), + ], +) +def test_tdi_resolution(timedelta_val, expected): + # GH#65186 + tdi = pd.TimedeltaIndex([timedelta_val]) + assert tdi.resolution == expected + + +def test_tdi_resolution_no_freq(): + # GH#65186 resolution should work even without a freq + tdi = pd.TimedeltaIndex(["1 day", "2 days", "4 days"]) + assert tdi.resolution == "day" + + tdi = pd.TimedeltaIndex(["1 day 2 hours", "3 days"]) + assert tdi.resolution == "hour" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_shift.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..e13162dc9d5222f1fa393c014200a4a24828d0ca --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/methods/test_shift.py @@ -0,0 +1,77 @@ +import pytest + +from pandas.errors import NullFrequencyError + +import pandas as pd +import pandas._testing as tm + + +class TestTimedeltaIndexShift: + # ------------------------------------------------------------- + # TimedeltaIndex.shift is used by __add__/__sub__ + + def test_tdi_shift_empty(self): + # GH#9903 + idx = pd.TimedeltaIndex([], name="xxx") + tm.assert_index_equal(idx.shift(0, freq="h"), idx) + tm.assert_index_equal(idx.shift(3, freq="h"), idx) + + def test_tdi_shift_hours(self): + # GH#9903 + idx = pd.TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx") + tm.assert_index_equal(idx.shift(0, freq="h"), idx) + exp = pd.TimedeltaIndex(["8 hours", "9 hours", "12 hours"], name="xxx") + tm.assert_index_equal(idx.shift(3, freq="h"), exp) + exp = pd.TimedeltaIndex(["2 hours", "3 hours", "6 hours"], name="xxx") + tm.assert_index_equal(idx.shift(-3, freq="h"), exp) + + def test_tdi_shift_minutes(self): + # GH#9903 + idx = pd.TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx") + tm.assert_index_equal(idx.shift(0, freq="min"), idx) + exp = pd.TimedeltaIndex(["05:03:00", "06:03:00", "9:03:00"], name="xxx") + tm.assert_index_equal(idx.shift(3, freq="min"), exp) + exp = pd.TimedeltaIndex(["04:57:00", "05:57:00", "8:57:00"], name="xxx") + tm.assert_index_equal(idx.shift(-3, freq="min"), exp) + + def test_tdi_shift_int(self): + # GH#8083 + tdi = pd.to_timedelta(range(5), unit="D") + trange = tdi._with_freq("infer") + pd.offsets.Hour(1) + result = trange.shift(1) + expected = pd.TimedeltaIndex( + [ + "1 days 01:00:00", + "2 days 01:00:00", + "3 days 01:00:00", + "4 days 01:00:00", + "5 days 01:00:00", + ], + freq="D", + dtype="m8[us]", + ) + tm.assert_index_equal(result, expected) + + def test_tdi_shift_nonstandard_freq(self): + # GH#8083 + tdi = pd.to_timedelta(range(5), unit="D") + trange = tdi._with_freq("infer") + pd.offsets.Hour(1) + result = trange.shift(3, freq="2D 1s") + expected = pd.TimedeltaIndex( + [ + "6 days 01:00:03", + "7 days 01:00:03", + "8 days 01:00:03", + "9 days 01:00:03", + "10 days 01:00:03", + ], + freq="D", + dtype="m8[us]", + ) + tm.assert_index_equal(result, expected) + + def test_shift_no_freq(self): + # GH#19147 + tdi = pd.TimedeltaIndex(["1 days 01:00:00", "2 days 01:00:00"], freq=None) + with pytest.raises(NullFrequencyError, match="Cannot shift with no freq"): + tdi.shift(2) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_arithmetic.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_arithmetic.py new file mode 100644 index 0000000000000000000000000000000000000000..30fe35e0a5444ece48e7b713bd5ccf208e735273 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_arithmetic.py @@ -0,0 +1,47 @@ +# Arithmetic tests for TimedeltaIndex are generally about the result's `freq` attribute. +# Other cases can be shared in tests.arithmetic.test_timedelta64 +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestTimedeltaIndexArithmetic: + def test_arithmetic_zero_freq(self): + # GH#51575 don't get a .freq with freq.n = 0 + tdi = pd.timedelta_range(0, periods=100, freq="ns") + result = tdi / 2 + assert result.freq is None + expected = tdi[:50].repeat(2) + tm.assert_index_equal(result, expected) + + result2 = tdi // 2 + assert result2.freq is None + expected2 = expected + tm.assert_index_equal(result2, expected2) + + result3 = tdi * 0 + assert result3.freq is None + expected3 = tdi[:1].repeat(100) + tm.assert_index_equal(result3, expected3) + + def test_tdi_division(self, index_or_series): + # doc example + + scalar = pd.Timedelta(days=31) + td = index_or_series( + [scalar, scalar, scalar + pd.Timedelta(minutes=5, seconds=3), pd.NaT], + dtype="m8[ns]", + ) + + result = td / np.timedelta64(1, "D") + expected = index_or_series( + [31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan] + ) + tm.assert_equal(result, expected) + + result = td / np.timedelta64(1, "s") + expected = index_or_series( + [31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan] + ) + tm.assert_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_constructors.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..de5b24d2b4ac42abc0fc2bdf77620b86d016fb9a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_constructors.py @@ -0,0 +1,274 @@ +from datetime import timedelta + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays.timedeltas import TimedeltaArray + + +class TestTimedeltaIndex: + def test_0d_raises(self): + # GH#69411 used to segfault + arr = np.array(1) + + msg = "Cannot construct TimedeltaArray from 0-dim input" + with pytest.raises(ValueError, match=msg): + pd.TimedeltaIndex(arr) + with pytest.raises(ValueError, match=msg): + TimedeltaArray._from_sequence(arr) + + def test_array_of_dt64_nat_raises(self): + # GH#39462 + nat = np.datetime64("NaT", "ns") + arr = np.array([nat], dtype=object) + + msg = "Invalid type for timedelta scalar" + with pytest.raises(TypeError, match=msg): + pd.TimedeltaIndex(arr) + + with pytest.raises(TypeError, match=msg): + TimedeltaArray._from_sequence(arr, dtype="m8[ns]") + + with pytest.raises(TypeError, match=msg): + pd.to_timedelta(arr) + + def test_int64_nocopy(self): + # GH#23539 check that a copy isn't made when we pass int64 data + # and copy=False + arr = np.arange(10, dtype=np.int64) + tdi = pd.TimedeltaIndex(arr, copy=False) + assert tdi._data._ndarray.base is arr + + def test_infer_from_tdi(self): + # GH#23539 + # fast-path for inferring a frequency if the passed data already + # has one + tdi = pd.timedelta_range("1 second", periods=10**7, freq="1s") + + result = pd.TimedeltaIndex(tdi, freq="infer") + assert result.freq == tdi.freq + + # check that inferred_freq was not called by checking that the + # value has not been cached + assert "inferred_freq" not in getattr(result, "_cache", {}) + + def test_infer_from_tdi_mismatch(self): + # GH#23539 + # fast-path for invalidating a frequency if the passed data already + # has one and it does not match the `freq` input + tdi = pd.timedelta_range("1 second", periods=100, freq="1s") + + msg = ( + "Inferred frequency .* from passed values does " + "not conform to passed frequency" + ) + with pytest.raises(ValueError, match=msg): + pd.TimedeltaIndex(tdi, freq="D") + + with pytest.raises(ValueError, match=msg): + pd.TimedeltaIndex(tdi._data, freq="D") + + def test_dt64_data_invalid(self): + # GH#23539 + # passing tz-aware DatetimeIndex raises, naive or ndarray[datetime64] + # raise as of GH#29794 + dti = pd.date_range("2016-01-01", periods=3) + + msg = "cannot be converted to timedelta64" + with pytest.raises(TypeError, match=msg): + pd.TimedeltaIndex(dti.tz_localize("Europe/Brussels")) + + with pytest.raises(TypeError, match=msg): + pd.TimedeltaIndex(dti) + + with pytest.raises(TypeError, match=msg): + pd.TimedeltaIndex(np.asarray(dti)) + + def test_float64_ns_rounded(self): + # GH#23539 without specifying a unit, floats are regarded as nanos, + # and fractional portions are truncated + tdi = pd.TimedeltaIndex([2.3, 9.7]) + expected = pd.TimedeltaIndex([2, 9]) + tm.assert_index_equal(tdi, expected) + + # integral floats are non-lossy + tdi = pd.TimedeltaIndex([2.0, 9.0]) + expected = pd.TimedeltaIndex([2, 9]) + tm.assert_index_equal(tdi, expected) + + # NaNs get converted to NaT + tdi = pd.TimedeltaIndex([2.0, np.nan]) + expected = pd.TimedeltaIndex([pd.Timedelta(nanoseconds=2), pd.NaT]) + tm.assert_index_equal(tdi, expected) + + def test_float64_unit_conversion(self): + # GH#23539 + tdi = pd.to_timedelta([1.5, 2.25], unit="D") + expected = pd.TimedeltaIndex( + [pd.Timedelta(days=1.5), pd.Timedelta(days=2.25)], dtype="m8[ns]" + ) + tm.assert_index_equal(tdi, expected) + + def test_construction_base_constructor(self): + arr = [pd.Timedelta("1 days"), pd.NaT, pd.Timedelta("3 days")] + tm.assert_index_equal(pd.Index(arr), pd.TimedeltaIndex(arr)) + tm.assert_index_equal(pd.Index(np.array(arr)), pd.TimedeltaIndex(np.array(arr))) + + arr = [np.nan, pd.NaT, pd.Timedelta("1 days")] + tm.assert_index_equal(pd.Index(arr), pd.TimedeltaIndex(arr)) + tm.assert_index_equal(pd.Index(np.array(arr)), pd.TimedeltaIndex(np.array(arr))) + + def test_constructor(self): + expected = pd.TimedeltaIndex( + [ + "1 days", + "1 days 00:00:05", + "2 days", + "2 days 00:00:02", + "0 days 00:00:03", + ] + ) + result = pd.TimedeltaIndex( + [ + "1 days", + "1 days, 00:00:05", + np.timedelta64(2, "D"), + timedelta(days=2, seconds=2), + pd.offsets.Second(3), + ] + ) + tm.assert_index_equal(result, expected) + + def test_constructor_iso(self): + # GH #21877 + expected = pd.timedelta_range("1s", periods=9, freq="s") + durations = [f"P0DT0H0M{i}S" for i in range(1, 10)] + result = pd.to_timedelta(durations) + tm.assert_index_equal(result, expected, check_freq=False) + + def test_timedelta_range_fractional_period(self): + msg = "periods must be an integer" + with pytest.raises(TypeError, match=msg): + pd.timedelta_range("1 days", periods=10.5) + + def test_constructor_coverage(self): + msg = "periods must be an integer, got foo" + with pytest.raises(TypeError, match=msg): + pd.timedelta_range(start="1 days", periods="foo", freq="D") + + msg = ( + r"TimedeltaIndex\(\.\.\.\) must be called with a collection of some kind, " + "'1 days' was passed" + ) + with pytest.raises(TypeError, match=msg): + pd.TimedeltaIndex("1 days") + + # generator expression + gen = (timedelta(i) for i in range(10)) + result = pd.TimedeltaIndex(gen) + expected = pd.TimedeltaIndex([timedelta(i) for i in range(10)]) + tm.assert_index_equal(result, expected) + + # NumPy string array + strings = np.array(["1 days", "2 days", "3 days"]) + result = pd.TimedeltaIndex(strings) + expected = pd.to_timedelta([1, 2, 3], unit="D").as_unit("us") + tm.assert_index_equal(result, expected) + + from_ints = pd.TimedeltaIndex(expected.as_unit("ns").asi8) + tm.assert_index_equal(from_ints, expected.as_unit("ns")) + + # non-conforming freq + msg = ( + "Inferred frequency None from passed values does not conform to " + "passed frequency D" + ) + with pytest.raises(ValueError, match=msg): + pd.TimedeltaIndex(["1 days", "2 days", "4 days"], freq="D") + + msg = ( + "Of the four parameters: start, end, periods, and freq, exactly " + "three must be specified" + ) + with pytest.raises(ValueError, match=msg): + pd.timedelta_range(periods=10, freq="D") + + def test_constructor_name(self): + idx = pd.timedelta_range(start="1 days", periods=1, freq="D", name="TEST") + assert idx.name == "TEST" + + # GH10025 + idx2 = pd.TimedeltaIndex(idx, name="something else") + assert idx2.name == "something else" + + def test_constructor_no_precision_raises(self): + # GH-24753, GH-24739 + + msg = "with no precision is not allowed" + with pytest.raises(ValueError, match=msg): + pd.TimedeltaIndex(["2000"], dtype="timedelta64") + + msg = "The 'timedelta64' dtype has no unit. Please pass in" + with pytest.raises(ValueError, match=msg): + pd.Index(["2000"], dtype="timedelta64") + + def test_constructor_wrong_precision_raises(self): + msg = "Supported timedelta64 resolutions are 's', 'ms', 'us', 'ns'" + with pytest.raises(ValueError, match=msg): + pd.TimedeltaIndex(["2000"], dtype="timedelta64[D]") + + # "timedelta64[us]" was unsupported pre-2.0, but now this works. + tdi = pd.TimedeltaIndex(["2000"], dtype="timedelta64[us]") + assert tdi.dtype == "m8[us]" + + def test_explicit_none_freq(self): + # Explicitly passing freq=None is respected + tdi = pd.timedelta_range(1, periods=5) + assert tdi.freq is not None + + result = pd.TimedeltaIndex(tdi, freq=None) + assert result.freq is None + + result = pd.TimedeltaIndex(tdi._data, freq=None) + assert result.freq is None + + def test_from_categorical(self): + tdi = pd.timedelta_range(1, periods=5) + + cat = pd.Categorical(tdi) + + result = pd.TimedeltaIndex(cat) + tm.assert_index_equal(result, tdi, check_freq=False) + + ci = pd.CategoricalIndex(tdi) + result = pd.TimedeltaIndex(ci) + tm.assert_index_equal(result, tdi, check_freq=False) + + @pytest.mark.parametrize( + "unit,unit_depr", + [ + ("W", "w"), + ("D", "d"), + ("min", "MIN"), + ("s", "S"), + ("h", "H"), + ("ms", "MS"), + ("us", "US"), + ], + ) + def test_unit_deprecated(self, unit, unit_depr): + # GH#52536, GH#59051 + msg = f"'{unit_depr}' is deprecated and will be removed in a future version." + + expected = pd.TimedeltaIndex([f"1{unit}", f"2{unit}"]) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = pd.TimedeltaIndex([f"1{unit_depr}", f"2{unit_depr}"]) + tm.assert_index_equal(result, expected) + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + tdi = pd.to_timedelta([1, 2], unit=unit_depr) + tm.assert_index_equal(tdi, expected.as_unit("us")) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_delete.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..dc4aa6aefe186424f67e52548bf1fc455d4fdd6b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_delete.py @@ -0,0 +1,72 @@ +import pandas as pd +import pandas._testing as tm + + +class TestTimedeltaIndexDelete: + def test_delete(self): + idx = pd.timedelta_range(start="1 Days", periods=5, freq="D", name="idx") + + # preserve freq + expected_0 = pd.timedelta_range(start="2 Days", periods=4, freq="D", name="idx") + expected_4 = pd.timedelta_range(start="1 Days", periods=4, freq="D", name="idx") + + # reset freq to None + expected_1 = pd.TimedeltaIndex( + ["1 day", "3 day", "4 day", "5 day"], freq=None, name="idx" + ) + + cases = { + 0: expected_0, + -5: expected_0, + -1: expected_4, + 4: expected_4, + 1: expected_1, + } + for n, expected in cases.items(): + result = idx.delete(n) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + + with tm.external_error_raised((IndexError, ValueError)): + # either depending on numpy version + idx.delete(5) + + def test_delete_slice(self): + idx = pd.timedelta_range(start="1 days", periods=10, freq="D", name="idx") + + # preserve freq + expected_0_2 = pd.timedelta_range( + start="4 days", periods=7, freq="D", name="idx" + ) + expected_7_9 = pd.timedelta_range( + start="1 days", periods=7, freq="D", name="idx" + ) + + # reset freq to None + expected_3_5 = pd.TimedeltaIndex( + ["1 D", "2 D", "3 D", "7 D", "8 D", "9 D", "10D"], freq=None, name="idx" + ) + + cases = { + (0, 1, 2): expected_0_2, + (7, 8, 9): expected_7_9, + (3, 4, 5): expected_3_5, + } + for n, expected in cases.items(): + result = idx.delete(n) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + + result = idx.delete(slice(n[0], n[-1] + 1)) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + + def test_delete_doesnt_infer_freq(self): + # GH#30655 behavior matches DatetimeIndex + + tdi = pd.TimedeltaIndex(["1 Day", "2 Days", None, "3 Days", "4 Days"]) + result = tdi.delete(2) + assert result.freq is None diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_formats.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_formats.py new file mode 100644 index 0000000000000000000000000000000000000000..759e93165d01711cb216eb3778e56a7c4f8f4687 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_formats.py @@ -0,0 +1,106 @@ +import pytest + +import pandas as pd + + +class TestTimedeltaIndexRendering: + def test_repr_round_days_non_nano(self): + # GH#55405 + # we should get "1 days", not "1 days 00:00:00" with non-nano + tdi = pd.TimedeltaIndex(["1 days"], freq="D").as_unit("s") + result = repr(tdi) + expected = "TimedeltaIndex(['1 days'], dtype='timedelta64[s]', freq='D')" + assert result == expected + + result2 = repr(pd.Series(tdi)) + expected2 = "0 1 days\ndtype: timedelta64[s]" + assert result2 == expected2 + + @pytest.mark.parametrize("method", ["__repr__", "__str__"]) + def test_representation(self, method): + idx1 = pd.TimedeltaIndex([], freq="D", dtype="m8[ns]") + idx2 = pd.TimedeltaIndex(["1 days"], freq="D") + idx3 = pd.TimedeltaIndex(["1 days", "2 days"], freq="D") + idx4 = pd.TimedeltaIndex(["1 days", "2 days", "3 days"], freq="D") + idx5 = pd.TimedeltaIndex(["1 days 00:00:01", "2 days", "3 days"]) + + exp1 = "TimedeltaIndex([], dtype='timedelta64[ns]', freq='D')" + + exp2 = "TimedeltaIndex(['1 days'], dtype='timedelta64[us]', freq='D')" + + exp3 = "TimedeltaIndex(['1 days', '2 days'], dtype='timedelta64[us]', freq='D')" + + exp4 = ( + "TimedeltaIndex(['1 days', '2 days', '3 days'], " + "dtype='timedelta64[us]', freq='D')" + ) + + exp5 = ( + "TimedeltaIndex(['1 days 00:00:01', '2 days 00:00:00', " + "'3 days 00:00:00'], dtype='timedelta64[us]', freq=None)" + ) + + with pd.option_context("display.width", 300): + for idx, expected in zip( + [idx1, idx2, idx3, idx4, idx5], + [exp1, exp2, exp3, exp4, exp5], + strict=True, + ): + result = getattr(idx, method)() + assert result == expected + + # TODO: this is a Series.__repr__ test + def test_representation_to_series(self): + idx1 = pd.TimedeltaIndex([], freq="D", dtype="m8[ns]") + idx2 = pd.TimedeltaIndex(["1 days"], freq="D") + idx3 = pd.TimedeltaIndex(["1 days", "2 days"], freq="D") + idx4 = pd.TimedeltaIndex(["1 days", "2 days", "3 days"], freq="D") + idx5 = pd.TimedeltaIndex(["1 days 00:00:01", "2 days", "3 days"]) + + exp1 = """Series([], dtype: timedelta64[ns])""" + + exp2 = "0 1 days\ndtype: timedelta64[us]" + + exp3 = "0 1 days\n1 2 days\ndtype: timedelta64[us]" + + exp4 = "0 1 days\n1 2 days\n2 3 days\ndtype: timedelta64[us]" + + exp5 = ( + "0 1 days 00:00:01\n" + "1 2 days 00:00:00\n" + "2 3 days 00:00:00\n" + "dtype: timedelta64[us]" + ) + + with pd.option_context("display.width", 300): + for idx, expected in zip( + [idx1, idx2, idx3, idx4, idx5], + [exp1, exp2, exp3, exp4, exp5], + strict=True, + ): + result = repr(pd.Series(idx)) + assert result == expected + + def test_summary(self): + # GH#9116 + idx1 = pd.TimedeltaIndex([], freq="D", dtype="m8[ns]") + idx2 = pd.TimedeltaIndex(["1 days"], freq="D") + idx3 = pd.TimedeltaIndex(["1 days", "2 days"], freq="D") + idx4 = pd.TimedeltaIndex(["1 days", "2 days", "3 days"], freq="D") + idx5 = pd.TimedeltaIndex(["1 days 00:00:01", "2 days", "3 days"]) + + exp1 = "TimedeltaIndex: 0 entries\nFreq: D" + + exp2 = "TimedeltaIndex: 1 entries, 1 days to 1 days\nFreq: D" + + exp3 = "TimedeltaIndex: 2 entries, 1 days to 2 days\nFreq: D" + + exp4 = "TimedeltaIndex: 3 entries, 1 days to 3 days\nFreq: D" + + exp5 = "TimedeltaIndex: 3 entries, 1 days 00:00:01 to 3 days 00:00:00" + + for idx, expected in zip( + [idx1, idx2, idx3, idx4, idx5], [exp1, exp2, exp3, exp4, exp5], strict=True + ): + result = idx._summary() + assert result == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_freq_attr.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_freq_attr.py new file mode 100644 index 0000000000000000000000000000000000000000..4273b9974bfa2cf864f1856449ce10852e91fb1f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_freq_attr.py @@ -0,0 +1,69 @@ +import pytest + +import pandas as pd + +from pandas.tseries.offsets import ( + BaseOffset, + Day, + Hour, + MonthEnd, +) + + +class TestFreq: + @pytest.mark.parametrize("values", [["0 days", "2 days", "4 days"], []]) + @pytest.mark.parametrize("freq", ["2D", Day(2), "48h", Hour(48)]) + def test_freq_setter(self, values, freq): + # GH#20678 + idx = pd.TimedeltaIndex(values) + + # can set to an offset, converting from string if necessary + idx.freq = freq + assert idx.freq == freq + assert isinstance(idx.freq, BaseOffset) + + # can reset to None + idx.freq = None + assert idx.freq is None + + def test_with_freq_empty_requires_tick(self): + idx = pd.TimedeltaIndex([]) + + off = MonthEnd(1) + msg = "TimedeltaArray/Index freq must be a Tick" + with pytest.raises(TypeError, match=msg): + idx._with_freq(off) + + def test_freq_setter_errors(self): + # GH#20678 + idx = pd.TimedeltaIndex(["0 days", "2 days", "4 days"]) + + # setting with an incompatible freq + msg = ( + "Inferred frequency 2D from passed values does not conform to " + "passed frequency 5D" + ) + with pytest.raises(ValueError, match=msg): + idx.freq = "5D" + + # setting with a non-fixed frequency + msg = r"<2 \* BusinessDays> is a non-fixed frequency" + with pytest.raises(ValueError, match=msg): + idx.freq = "2B" + + # setting with non-freq string + with pytest.raises(ValueError, match="Invalid frequency"): + idx.freq = "foo" + + def test_freq_view_safe(self): + # Setting the freq for one TimedeltaIndex shouldn't alter the freq + # for another that views the same data + + tdi = pd.TimedeltaIndex(["0 days", "2 days", "4 days"], freq="2D") + tda = tdi._data + + tdi2 = pd.TimedeltaIndex(tda)._with_freq(None) + assert tdi2.freq is None + + # Original was not altered. freq is now Index-level state. + assert tdi.freq == "2D" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..65cc051cc21f28cbb5cd9e8ff5861584fbff32d9 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_indexing.py @@ -0,0 +1,534 @@ +from datetime import datetime +import re + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestGetItem: + def test_getitem_slice_keeps_name(self): + # GH#4226, GH#59051 + msg = "'d' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(Pandas4Warning, match=msg): + tdi = pd.timedelta_range("1d", "5d", freq="h", name="timebucket") + assert tdi[1:].name == tdi.name + + def test_getitem(self): + idx1 = pd.timedelta_range("1 day", "31 day", freq="D", name="idx") + + for idx in [idx1]: + result = idx[0] + assert result == pd.Timedelta("1 day") + + result = idx[0:5] + expected = pd.timedelta_range("1 day", "5 day", freq="D", name="idx") + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx[0:10:2] + expected = pd.timedelta_range("1 day", "9 day", freq="2D", name="idx") + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx[-20:-5:3] + expected = pd.timedelta_range("12 day", "24 day", freq="3D", name="idx") + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx[4::-1] + expected = pd.TimedeltaIndex( + ["5 day", "4 day", "3 day", "2 day", "1 day"], freq="-1D", name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + @pytest.mark.parametrize( + "key", + [ + pd.Timestamp("1970-01-01"), + pd.Timestamp("1970-01-02"), + datetime(1970, 1, 1), + pd.Timestamp("1970-01-03").to_datetime64(), + # non-matching NA values + np.datetime64("NaT", "ns"), + ], + ) + def test_timestamp_invalid_key(self, key): + # GH#20464 + tdi = pd.timedelta_range(0, periods=10) + with pytest.raises(KeyError, match=re.escape(repr(key))): + tdi.get_loc(key) + + +class TestGetLoc: + def test_get_loc_key_unit_mismatch(self): + idx = pd.to_timedelta(["0 days", "1 days", "2 days"]) + key = idx[1].as_unit("ms") + loc = idx.get_loc(key) + assert loc == 1 + + def test_get_loc_key_unit_mismatch_not_castable(self): + tdi = pd.to_timedelta(["0 days", "1 days", "2 days"]).astype("m8[s]") + assert tdi.dtype == "m8[s]" + key = tdi[0].as_unit("ns") + pd.Timedelta(1) + + with pytest.raises(KeyError, match=r"Timedelta\('0 days 00:00:00.000000001'\)"): + tdi.get_loc(key) + + assert key not in tdi + + def test_get_loc(self): + idx = pd.to_timedelta(["0 days", "1 days", "2 days"]) + + # GH 16909 + assert idx.get_loc(idx[1].to_timedelta64()) == 1 + + # GH 16896 + assert idx.get_loc("0 days") == 0 + + def test_get_loc_nat(self): + tidx = pd.TimedeltaIndex(["1 days 01:00:00", "NaT", "2 days 01:00:00"]) + + assert tidx.get_loc(pd.NaT) == 1 + assert tidx.get_loc(None) == 1 + assert tidx.get_loc(float("nan")) == 1 + assert tidx.get_loc(np.nan) == 1 + + +class TestGetIndexer: + def test_get_indexer(self): + idx = pd.to_timedelta(["0 days", "1 days", "2 days"]) + tm.assert_numpy_array_equal( + idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp) + ) + + target = pd.to_timedelta(["-1 hour", "12 hours", "1 day 1 hour"]) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp) + ) + + res = idx.get_indexer(target, "nearest", tolerance=pd.Timedelta("1 hour")) + tm.assert_numpy_array_equal(res, np.array([0, -1, 1], dtype=np.intp)) + + @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"]) + def test_get_indexer_nat_target(self, method): + # GH#32572 NaT in the target should not be matched + tdi = pd.to_timedelta(["0 days", "1 days", "2 days"]) + target = pd.TimedeltaIndex([pd.NaT]) + result = tdi.get_indexer(target, method=method) + expected = np.array([-1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +class TestWhere: + def test_where_doesnt_retain_freq(self): + tdi = pd.timedelta_range("1 day", periods=3, freq="D", name="idx") + cond = [True, True, False] + expected = pd.TimedeltaIndex([tdi[0], tdi[1], tdi[0]], freq=None, name="idx") + + result = tdi.where(cond, tdi[::-1]) + tm.assert_index_equal(result, expected) + + def test_where_invalid_dtypes(self, fixed_now_ts): + tdi = pd.timedelta_range("1 day", periods=3, freq="D", name="idx") + + tail = tdi[2:].tolist() + i2 = pd.Index([pd.NaT, pd.NaT, *tail]) + mask = pd.notna(i2) + + expected = pd.Index( + [pd.NaT._value, pd.NaT._value, *tail], dtype=object, name="idx" + ) + assert isinstance(expected[0], int) + result = tdi.where(mask, i2.asi8) + tm.assert_index_equal(result, expected) + + ts = i2 + fixed_now_ts + expected = pd.Index([ts[0], ts[1], *tail], dtype=object, name="idx") + result = tdi.where(mask, ts) + tm.assert_index_equal(result, expected) + + per = (i2 + fixed_now_ts).to_period("D") + expected = pd.Index([per[0], per[1], *tail], dtype=object, name="idx") + result = tdi.where(mask, per) + tm.assert_index_equal(result, expected) + + ts = fixed_now_ts + expected = pd.Index([ts, ts, *tail], dtype=object, name="idx") + result = tdi.where(mask, ts) + tm.assert_index_equal(result, expected) + + def test_where_mismatched_nat(self): + tdi = pd.timedelta_range("1 day", periods=3, freq="D", name="idx") + cond = np.array([True, False, False]) + + dtnat = np.datetime64("NaT", "ns") + expected = pd.Index([tdi[0], dtnat, dtnat], dtype=object, name="idx") + assert expected[2] is dtnat + result = tdi.where(cond, dtnat) + tm.assert_index_equal(result, expected) + + +class TestTake: + def test_take(self): + # GH 10295 + idx1 = pd.timedelta_range("1 day", "31 day", freq="D", name="idx") + + for idx in [idx1]: + result = idx.take([0]) + assert result == pd.Timedelta("1 day") + + result = idx.take([-1]) + assert result == pd.Timedelta("31 day") + + result = idx.take([0, 1, 2]) + expected = pd.timedelta_range("1 day", "3 day", freq="D", name="idx") + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx.take([0, 2, 4]) + expected = pd.timedelta_range("1 day", "5 day", freq="2D", name="idx") + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx.take([7, 4, 1]) + expected = pd.timedelta_range("8 day", "2 day", freq="-3D", name="idx") + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + result = idx.take([3, 2, 5]) + expected = pd.TimedeltaIndex(["4 day", "3 day", "6 day"], name="idx") + tm.assert_index_equal(result, expected) + assert result.freq is None + + result = idx.take([-3, 2, 5]) + expected = pd.TimedeltaIndex(["29 day", "3 day", "6 day"], name="idx") + tm.assert_index_equal(result, expected) + assert result.freq is None + + def test_take_invalid_kwargs(self): + idx = pd.timedelta_range("1 day", "31 day", freq="D", name="idx") + indices = [1, 6, 5, 9, 10, 13, 15, 3] + + msg = r"take\(\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg): + idx.take(indices, foo=2) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, out=indices) + + msg = "the 'mode' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, mode="clip") + + def test_take_equiv_getitem(self): + tds = ["1day 02:00:00", "1 day 04:00:00", "1 day 10:00:00"] + idx = pd.timedelta_range(start="1D", end="2D", freq="h", name="idx") + expected = pd.TimedeltaIndex(tds, freq=None, name="idx") + + taken1 = idx.take([2, 4, 10]) + taken2 = idx[[2, 4, 10]] + + for taken in [taken1, taken2]: + tm.assert_index_equal(taken, expected) + assert isinstance(taken, pd.TimedeltaIndex) + assert taken.freq is None + assert taken.name == expected.name + + def test_take_fill_value(self): + # GH 12631 + idx = pd.TimedeltaIndex(["1 days", "2 days", "3 days"], name="xxx") + result = idx.take(np.array([1, 0, -1])) + expected = pd.TimedeltaIndex(["2 days", "1 days", "3 days"], name="xxx") + tm.assert_index_equal(result, expected) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=pd.NaT) + expected = pd.TimedeltaIndex(["2 days", "1 days", "NaT"], name="xxx") + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False) + expected = pd.TimedeltaIndex(["2 days", "1 days", "3 days"], name="xxx") + tm.assert_index_equal(result, expected) + + msg = "When allow_fill=True, all indices must be >= -1" + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + +class TestMaybeCastSliceBound: + @pytest.fixture(params=["increasing", "decreasing", None]) + def monotonic(self, request): + return request.param + + @pytest.fixture + def tdi(self, monotonic): + tdi = pd.timedelta_range("1 Day", periods=10) + if monotonic == "decreasing": + tdi = tdi[::-1] + elif monotonic is None: + taker = np.arange(10, dtype=np.intp) + np.random.default_rng(2).shuffle(taker) + tdi = tdi.take(taker) + return tdi + + def test_maybe_cast_slice_bound_invalid_str(self, tdi): + # test the low-level _maybe_cast_slice_bound and that we get the + # expected exception+message all the way up the stack + msg = ( + "cannot do slice indexing on TimedeltaIndex with these " + r"indexers \[foo\] of type str" + ) + with pytest.raises(TypeError, match=msg): + tdi._maybe_cast_slice_bound("foo", side="left") + with pytest.raises(TypeError, match=msg): + tdi.get_slice_bound("foo", side="left") + with pytest.raises(TypeError, match=msg): + tdi.slice_locs("foo", None, None) + + def test_slice_invalid_str_with_timedeltaindex( + self, tdi, frame_or_series, indexer_sl + ): + obj = frame_or_series(range(10), index=tdi) + + msg = ( + "cannot do slice indexing on TimedeltaIndex with these " + r"indexers \[foo\] of type str" + ) + with pytest.raises(TypeError, match=msg): + indexer_sl(obj)["foo":] + with pytest.raises(TypeError, match=msg): + indexer_sl(obj)["foo":-1] + with pytest.raises(TypeError, match=msg): + indexer_sl(obj)[:"foo"] + with pytest.raises(TypeError, match=msg): + indexer_sl(obj)[tdi[0] : "foo"] + + +class TestStringSliceResolution: + """Tests for GH#33603 - string resolution for TimedeltaIndex slicing.""" + + def test_string_slice_reso_seconds_not_minutes(self): + # GH#33603 - "720s" should have second resolution, not minute, + # even though 720s = 12 minutes exactly + tdi = pd.timedelta_range("710s", "721s", freq="s") + df = pd.DataFrame({"dummy": np.arange(len(tdi))}, index=tdi) + + result = df["710s":"720s"] + expected = df[ + (df.index >= pd.Timedelta("710s")) & (df.index < pd.Timedelta("721s")) + ] + tm.assert_frame_equal(result, expected) + + def test_string_slice_reso_value_not_elevated(self): + # GH#33603 - "60s" should have second resolution, not minute; + # "3600s" should have second resolution, not hour + tdi = pd.timedelta_range("0s", "7200s", freq="100ms") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser["59s":"60s"] + expected = ser[ + (ser.index >= pd.Timedelta("59s")) & (ser.index < pd.Timedelta("61s")) + ] + tm.assert_series_equal(result, expected) + + result = ser["3599s":"3600s"] + expected = ser[ + (ser.index >= pd.Timedelta("3599s")) & (ser.index < pd.Timedelta("3601s")) + ] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_day_with_zero_hours(self): + # GH#33603 - "2D 0 hours" should have hour resolution, not day + ser = pd.Series( + np.arange(100), + index=pd.timedelta_range("1 days", periods=100, freq="h"), + ) + result = ser[:"2D 0 hours"] + expected = ser[ser.index < pd.Timedelta("2D 1h")] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_120s_not_minutes(self): + # GH#33603 - "120s" should have second resolution, not minute, + # even though 120s = 2 minutes exactly + tdi = pd.timedelta_range("115s", "125s", freq="100ms") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:"120s"] + expected = ser[ser.index < pd.Timedelta("121s")] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_units_out_of_order(self): + # GH#33603 - the finest unit in the string determines the resolution, + # regardless of the order the units appear in + tdi = pd.timedelta_range("115s", "200s", freq="100ms") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:"120s 0 days"] + expected = ser[ser.index < pd.Timedelta("121s")] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_2000ms_not_seconds(self): + # GH#33603 - "2000ms" should have millisecond resolution, not second, + # even though 2000ms = 2s exactly + tdi = pd.timedelta_range("1900ms", "2100ms", freq="100us") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:"2000ms"] + expected = ser[ser.index < pd.Timedelta("2001ms")] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_hh_mm_ss_exact_hour(self): + # GH#33603 - "1:00:00" should have second resolution, not hour, + # even though it is exactly 1 hour + tdi = pd.timedelta_range("0:59:55", periods=200, freq="100ms") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:"1:00:00"] + expected = ser[ser.index < pd.Timedelta("1:00:01")] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_hh_mm_ss_exact_minute(self): + # GH#33603 - "1:01:00" should have second resolution, not minute, + # even though the seconds component is zero + tdi = pd.timedelta_range("1:00:55", periods=200, freq="100ms") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:"1:01:00"] + expected = ser[ser.index < pd.Timedelta("1:01:01")] + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "index_unit, label", + [("s", "2000ms"), ("ms", "2000us"), ("us", "2000ns")], + ) + def test_string_slice_non_nano_finer_reso(self, index_unit, label): + # GH#33603 - a string in a finer unit than the index must not + # invert the bounds; e.g. "2000ms" == 2s should match on a m8[s] index + tdi = pd.timedelta_range("0s", periods=5, freq="s", unit=index_unit) + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:label] + expected = ser[ser.index <= pd.Timedelta(label)] + tm.assert_series_equal(result, expected) + + def test_string_slice_non_nano_finer_reso_non_monotonic(self): + # GH#33603 - inverted bounds raised a bogus "non-monotonic index" + # KeyError even though 2000ms == 2s is present in the index + tdi = pd.TimedeltaIndex(["5s", "2s", "7s"], dtype="m8[s]") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:"2000ms"] + expected = ser.iloc[:2] + tm.assert_series_equal(result, expected) + + def test_string_slice_non_nano_unrepresentable(self): + # GH#33603 - a string not representable in the index unit + # matches nothing + tdi = pd.timedelta_range("0s", periods=5, freq="s", unit="s") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc["1500ms":"1500ms"] + tm.assert_series_equal(result, ser.iloc[:0]) + + def test_string_slice_reso_iso_seconds_not_minutes(self): + # GH#33603 - ISO "PT120S" has second resolution, not minute, + # even though 120s = 2 minutes exactly + tdi = pd.timedelta_range("115s", "200s", freq="100ms") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:"PT120S"] + expected = ser[ser.index < pd.Timedelta("121s")] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_iso_minutes(self): + # GH#33603 - ISO "PT2M" has minute resolution + tdi = pd.timedelta_range("110s", "200s", freq="s") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:"PT2M"] + expected = ser[ser.index < pd.Timedelta("3min")] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_iso_hours(self): + # GH#33603 - ISO "P1DT12H" has hour resolution + ser = pd.Series( + np.arange(100), + index=pd.timedelta_range("1 days", periods=100, freq="h"), + ) + result = ser.loc[:"P1DT12H"] + expected = ser[ser.index < pd.Timedelta("1D 13h")] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_iso_day_vs_zero_hours(self): + # GH#33603 - a bare ISO "P2D" has day resolution, but the "T0H" + # marker in "P2DT0H" forces hour resolution even though both are + # exactly 2 days + ser = pd.Series( + np.arange(100), + index=pd.timedelta_range("1 days", periods=100, freq="h"), + ) + result = ser.loc[:"P2D"] + expected = ser[ser.index < pd.Timedelta("3D")] + tm.assert_series_equal(result, expected) + + result = ser.loc[:"P2DT0H"] + expected = ser[ser.index < pd.Timedelta("2D 1h")] + tm.assert_series_equal(result, expected) + + def test_string_slice_reso_trailing_zero_fraction(self): + # GH#33603 - sub-second precision comes from the value, so trailing + # zeros are not significant: "0:0:1.100000" resolves to millisecond + # (1.1s == 1100ms), not microsecond + tdi = pd.timedelta_range("1099ms", "1102ms", freq="100us") + ser = pd.Series(np.arange(len(tdi)), index=tdi) + + result = ser.loc[:"0:0:1.100000"] + expected = ser[ser.index < pd.Timedelta("1101ms")] + tm.assert_series_equal(result, expected) + + +class TestContains: + def test_contains_nonunique(self): + # GH#9512 + for vals in ( + [0, 1, 0], + [0, 0, -1], + [0, -1, -1], + ["00:01:00", "00:01:00", "00:02:00"], + ["00:01:00", "00:01:00", "00:00:01"], + ): + idx = pd.TimedeltaIndex(vals) + assert idx[0] in idx + + def test_contains(self): + # Checking for any NaT-like objects + # GH#13603, GH#59051 + msg = "'d' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(Pandas4Warning, match=msg): + td = pd.to_timedelta(range(5), unit="d") + pd.offsets.Hour(1) + for v in [pd.NaT, None, float("nan"), np.nan]: + assert v not in td + + td = pd.to_timedelta([pd.NaT]) + for v in [pd.NaT, None, float("nan"), np.nan]: + assert v in td diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_join.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..56b1f0be0d9557a4709ffb967fe0ef4e3de2893c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_join.py @@ -0,0 +1,44 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +class TestJoin: + def test_append_join_nondatetimeindex(self): + rng = pd.timedelta_range("1 days", periods=10) + idx = pd.Index(["a", "b", "c", "d"]) + + result = rng.append(idx) + assert isinstance(result[0], pd.Timedelta) + + # it works + rng.join(idx, how="outer") + + def test_join_self(self, join_type): + index = pd.timedelta_range("1 day", periods=10) + joined = index.join(index, how=join_type) + tm.assert_index_equal(index, joined) + + def test_does_not_convert_mixed_integer(self): + df = pd.DataFrame( + np.ones((5, 5)), columns=pd.timedelta_range("1 day", periods=5) + ) + + cols = df.columns.join(df.index, how="outer") + joined = cols.join(df.columns) + assert cols.dtype == np.dtype("O") + assert cols.dtype == joined.dtype + tm.assert_index_equal(cols, joined) + + def test_join_preserves_freq(self): + # GH#32157 + tdi = pd.timedelta_range("1 day", periods=10) + result = tdi[:5].join(tdi[5:], how="outer") + assert result.freq == tdi.freq + tm.assert_index_equal(result, tdi) + + result = tdi[:5].join(tdi[6:], how="outer") + assert result.freq is None + expected = tdi.delete(5) + tm.assert_index_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_ops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ca073863aabb96896f6eb3c80b33b6c93a12964c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_ops.py @@ -0,0 +1,11 @@ +import pandas as pd +import pandas._testing as tm + + +class TestTimedeltaIndexOps: + def test_infer_freq(self, freq_sample): + # GH#11018 + idx = pd.timedelta_range("1", freq=freq_sample, periods=10) + result = pd.TimedeltaIndex(idx.asi8, freq="infer") + tm.assert_index_equal(idx, result) + assert result.freq == freq_sample diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_pickle.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..83c8f8c97d081424a71f4e4890a2bde71b989e92 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_pickle.py @@ -0,0 +1,11 @@ +import pandas as pd +import pandas._testing as tm + + +class TestPickle: + def test_pickle_after_set_freq(self, temp_file): + tdi = pd.timedelta_range("1 day", periods=4, freq="s") + tdi = tdi._with_freq(None) + + res = tm.round_trip_pickle(tdi, temp_file) + tm.assert_index_equal(res, tdi) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_scalar_compat.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_scalar_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..058726cdc692aaa871b29f8bc57d05b3d906c29a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_scalar_compat.py @@ -0,0 +1,141 @@ +""" +Tests for TimedeltaIndex methods behaving like their Timedelta counterparts +""" + +import numpy as np +import pytest + +from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +class TestVectorizedTimedelta: + def test_tdi_total_seconds(self): + # GH#10939 + # test index + rng = pd.timedelta_range("1 days, 10:11:12.100123456", periods=2, freq="s") + expt = [ + 1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456.0 / 1e9, + 1 * 86400 + 10 * 3600 + 11 * 60 + 13 + 100123456.0 / 1e9, + ] + tm.assert_almost_equal(rng.total_seconds(), pd.Index(expt)) + + # test Series + ser = pd.Series(rng) + s_expt = pd.Series(expt, index=[0, 1]) + tm.assert_series_equal(ser.dt.total_seconds(), s_expt) + + # with nat + ser[1] = np.nan + s_expt = pd.Series( + [1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456.0 / 1e9, np.nan], + index=[0, 1], + ) + tm.assert_series_equal(ser.dt.total_seconds(), s_expt) + + def test_tdi_total_seconds_all_nat(self): + # with both nat + ser = pd.Series([np.nan, np.nan], dtype="timedelta64[ns]") + result = ser.dt.total_seconds() + expected = pd.Series([np.nan, np.nan]) + tm.assert_series_equal(result, expected) + + def test_tdi_round(self): + td = pd.timedelta_range(start="16801 days", periods=5, freq="30Min") + elt = td[1] + + expected_rng = pd.TimedeltaIndex( + [ + pd.Timedelta("16801 days 00:00:00"), + pd.Timedelta("16801 days 00:00:00"), + pd.Timedelta("16801 days 01:00:00"), + pd.Timedelta("16801 days 02:00:00"), + pd.Timedelta("16801 days 02:00:00"), + ] + ) + expected_elt = expected_rng[1] + + tm.assert_index_equal(td.round(freq="h"), expected_rng) + assert elt.round(freq="h") == expected_elt + + msg = INVALID_FREQ_ERR_MSG + with pytest.raises(ValueError, match=msg): + td.round(freq="foo") + with pytest.raises(ValueError, match=msg): + elt.round(freq="foo") + + msg = " is a non-fixed frequency" + with pytest.raises(ValueError, match=msg): + td.round(freq="ME") + with pytest.raises(ValueError, match=msg): + elt.round(freq="ME") + + @pytest.mark.parametrize( + "freq,msg", + [ + ("YE", " is a non-fixed frequency"), + ("ME", " is a non-fixed frequency"), + ("foobar", "Invalid frequency: foobar"), + ], + ) + def test_tdi_round_invalid(self, freq, msg): + t1 = pd.timedelta_range("1 days", periods=3, freq="1 min 2 s 3 us") + + with pytest.raises(ValueError, match=msg): + t1.round(freq) + with pytest.raises(ValueError, match=msg): + # Same test for TimedeltaArray + t1._data.round(freq) + + # TODO: de-duplicate with test_tdi_round + def test_round(self): + t1 = pd.timedelta_range("1 days", periods=3, freq="1 min 2 s 3 us") + t2 = -1 * t1 + t1a = pd.timedelta_range("1 days", periods=3, freq="1 min 2 s") + t1c = pd.TimedeltaIndex(np.array([1, 1, 1], "m8[D]")).as_unit("us") + + # note that negative times round DOWN! so don't give whole numbers + msg = "'d' is deprecated and will be removed in a future version." + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + for freq, s1, s2 in [ + ("ns", t1, t2), + ("us", t1, t2), + ( + "ms", + t1a, + pd.TimedeltaIndex( + ["-1 days +00:00:00", "-2 days +23:58:58", "-2 days +23:57:56"] + ), + ), + ( + "s", + t1a, + pd.TimedeltaIndex( + ["-1 days +00:00:00", "-2 days +23:58:58", "-2 days +23:57:56"] + ), + ), + ("12min", t1c, pd.TimedeltaIndex(["-1 days", "-1 days", "-1 days"])), + ("h", t1c, pd.TimedeltaIndex(["-1 days", "-1 days", "-1 days"])), + ("d", t1c, -1 * t1c), + ]: + r1 = t1.round(freq) + r2 = t2.round(freq) + + tm.assert_index_equal(r1, s1) + tm.assert_index_equal(r2, s2) + + def test_components(self): + rng = pd.timedelta_range("1 days, 10:11:12", periods=2, freq="s") + rng.components + + # with nat + s = pd.Series(rng) + s[1] = np.nan + + result = s.dt.components + assert not result.iloc[0].isna().all() + assert result.iloc[1].isna().all() diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_searchsorted.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_searchsorted.py new file mode 100644 index 0000000000000000000000000000000000000000..6f8fec6b0615898bfd012b34717a80f1807a4954 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_searchsorted.py @@ -0,0 +1,26 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestSearchSorted: + def test_searchsorted_different_argument_classes(self, listlike_box): + idx = pd.TimedeltaIndex(["1 day", "2 days", "3 days"]) + result = idx.searchsorted(listlike_box(idx)) + expected = np.arange(len(idx), dtype=result.dtype) + tm.assert_numpy_array_equal(result, expected) + + result = idx._data.searchsorted(listlike_box(idx)) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "arg", + [[1, 2], ["a", "b"], [pd.Timestamp("2020-01-01", tz="Europe/London")] * 2], + ) + def test_searchsorted_invalid_argument_dtype(self, arg): + idx = pd.TimedeltaIndex(["1 day", "2 days", "3 days"]) + msg = "value should be a 'Timedelta', 'NaT', or array of those. Got" + with pytest.raises(TypeError, match=msg): + idx.searchsorted(arg) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_setops.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..633bba96637192732dfc7c96e33eb20d0c6a1ca6 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_setops.py @@ -0,0 +1,276 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + +from pandas.tseries.offsets import Hour + + +class TestTimedeltaIndex: + def test_union(self): + i1 = pd.timedelta_range("1day", periods=5) + i2 = pd.timedelta_range("3day", periods=5) + result = i1.union(i2) + expected = pd.timedelta_range("1day", periods=7) + tm.assert_index_equal(result, expected) + + i1 = pd.Index(np.arange(0, 20, 2, dtype=np.int64)) + i2 = pd.timedelta_range(start="1 day", periods=10, freq="D") + i1.union(i2) # Works + i2.union(i1) # Fails with "AttributeError: can't set attribute" + + def test_union_sort_false(self): + tdi = pd.timedelta_range("1day", periods=5) + + left = tdi[3:] + right = tdi[:3] + + # Check that we are testing the desired code path + assert left._can_fast_union(right) + + result = left.union(right) + tm.assert_index_equal(result, tdi) + + result = left.union(right, sort=False) + expected = pd.TimedeltaIndex(["4 Days", "5 Days", "1 Days", "2 Day", "3 Days"]) + tm.assert_index_equal(result, expected) + # GH#65191 the sort=False result is non-monotonic, so it must not + # retain a freq; otherwise e.g. shift silently returns an empty index. + assert result.freq is None + + def test_union_sort_false_other_extends_past_self(self): + # GH#66322 with sort=False and self starting after other, the result + # is non-monotonic, so the fast path does not apply; previously the + # tail past self[-1] was silently dropped. + tdi = pd.timedelta_range("1day", periods=6) + left = tdi[2:4] + + result = left.union(tdi, sort=False) + expected = pd.TimedeltaIndex( + ["3 Days", "4 Days", "1 Days", "2 Days", "5 Days", "6 Days"] + ) + tm.assert_index_equal(result, expected) + assert result.freq is None + + def test_union_coverage(self): + # GH#59051 + msg = "'d' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(Pandas4Warning, match=msg): + idx = pd.TimedeltaIndex(["3d", "1d", "2d"]) + ordered = pd.TimedeltaIndex(idx.sort_values(), freq="infer") + result = ordered.union(idx) + tm.assert_index_equal(result, ordered) + + result = ordered[:0].union(ordered) + tm.assert_index_equal(result, ordered) + assert result.freq == ordered.freq + + def test_union_bug_1730(self): + rng_a = pd.timedelta_range("1 day", periods=4, freq="3h") + rng_b = pd.timedelta_range("1 day", periods=4, freq="4h") + + result = rng_a.union(rng_b) + exp = pd.TimedeltaIndex(sorted(set(rng_a) | set(rng_b))) + tm.assert_index_equal(result, exp) + + def test_union_bug_1745(self): + left = pd.TimedeltaIndex(["1 day 15:19:49.695000"]) + right = pd.TimedeltaIndex( + ["2 day 13:04:21.322000", "1 day 15:27:24.873000", "1 day 15:31:05.350000"] + ) + + result = left.union(right) + exp = pd.TimedeltaIndex(sorted(set(left) | set(right))) + tm.assert_index_equal(result, exp) + + def test_union_bug_4564(self): + left = pd.timedelta_range("1 day", "30D") + right = left + pd.offsets.Minute(15) + + result = left.union(right) + exp = pd.TimedeltaIndex(sorted(set(left) | set(right))) + tm.assert_index_equal(result, exp) + + def test_union_freq_infer(self): + # When taking the union of two TimedeltaIndexes, we infer + # a freq even if the arguments don't have freq. This matches + # DatetimeIndex behavior. + tdi = pd.timedelta_range("1 Day", periods=5) + left = tdi[[0, 1, 3, 4]] + right = tdi[[2, 3, 1]] + + assert left.freq is None + assert right.freq is None + + result = left.union(right) + tm.assert_index_equal(result, tdi) + assert result.freq == "D" + + def test_intersection_bug_1708(self): + index_1 = pd.timedelta_range("1 day", periods=4, freq="h") + index_2 = index_1 + pd.offsets.Hour(5) + + result = index_1.intersection(index_2) + assert len(result) == 0 + + index_1 = pd.timedelta_range("1 day", periods=4, freq="h") + index_2 = index_1 + pd.offsets.Hour(1) + + result = index_1.intersection(index_2) + expected = pd.timedelta_range("1 day 01:00:00", periods=3, freq="h") + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq + + def test_intersection_equal(self, sort): + # GH 24471 Test intersection outcome given the sort keyword + # GH#63169 intersection returns a copy to prevent shared mutable state + first = pd.timedelta_range("1 day", periods=4, freq="h") + second = pd.timedelta_range("1 day", periods=4, freq="h") + intersect = first.intersection(second, sort=sort) + if sort is None: + tm.assert_index_equal(intersect, second.sort_values()) + tm.assert_index_equal(intersect, second) + + # Corner cases + inter = first.intersection(first, sort=sort) + assert inter is not first + tm.assert_index_equal(inter, first) + + @pytest.mark.parametrize("period_1, period_2", [(0, 4), (4, 0)]) + def test_intersection_zero_length(self, period_1, period_2, sort): + # GH 24471 test for non overlap the intersection should be zero length + index_1 = pd.timedelta_range("1 day", periods=period_1, freq="h") + index_2 = pd.timedelta_range("1 day", periods=period_2, freq="h") + expected = pd.timedelta_range("1 day", periods=0, freq="h") + result = index_1.intersection(index_2, sort=sort) + tm.assert_index_equal(result, expected) + + def test_zero_length_input_index(self, sort): + # GH 24966 test for 0-len intersections are copied + index_1 = pd.timedelta_range("1 day", periods=0, freq="h") + index_2 = pd.timedelta_range("1 day", periods=3, freq="h") + result = index_1.intersection(index_2, sort=sort) + assert index_1 is not result + assert index_2 is not result + tm.assert_copy(result, index_1) + + @pytest.mark.parametrize( + "rng, expected", + # if target has the same name, it is preserved + [ + ( + pd.timedelta_range("1 day", periods=5, freq="h", name="idx"), + pd.timedelta_range("1 day", periods=4, freq="h", name="idx"), + ), + # if target name is different, it will be reset + ( + pd.timedelta_range("1 day", periods=5, freq="h", name="other"), + pd.timedelta_range("1 day", periods=4, freq="h", name=None), + ), + # if no overlap exists return empty index + ( + pd.timedelta_range("1 day", periods=10, freq="h", name="idx")[5:], + pd.TimedeltaIndex([], freq="h", name="idx", dtype="m8[us]"), + ), + ], + ) + def test_intersection(self, rng, expected, sort): + # GH 4690 (with tz) + base = pd.timedelta_range("1 day", periods=4, freq="h", name="idx") + result = base.intersection(rng, sort=sort) + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + + @pytest.mark.parametrize( + "rng, expected", + # part intersection works + [ + ( + pd.TimedeltaIndex(["5 hour", "2 hour", "4 hour", "9 hour"], name="idx"), + pd.TimedeltaIndex(["2 hour", "4 hour"], name="idx"), + ), + # reordered part intersection + ( + pd.TimedeltaIndex( + ["2 hour", "5 hour", "5 hour", "1 hour"], name="other" + ), + pd.TimedeltaIndex(["1 hour", "2 hour"], name=None), + ), + # reversed index + ( + pd.TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx")[ + ::-1 + ], + pd.TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx"), + ), + ], + ) + def test_intersection_non_monotonic(self, rng, expected, sort): + # 24471 non-monotonic + base = pd.TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx") + result = base.intersection(rng, sort=sort) + if sort is None: + expected = expected.sort_values() + # if reversed order, frequency is still the same + if all(base == rng[::-1]): + expected = expected._with_freq("infer") + tm.assert_index_equal(result, expected) + assert result.name == expected.name + + if all(base == rng[::-1]) and sort is None: + assert isinstance(result.freq, Hour) + else: + assert result.freq is None + + +class TestTimedeltaIndexDifference: + def test_difference_freq(self, sort): + # GH14323: Difference of TimedeltaIndex should not preserve frequency + + index = pd.timedelta_range("0 days", "5 days", freq="D") + + other = pd.timedelta_range("1 days", "4 days", freq="D") + expected = pd.TimedeltaIndex(["0 days", "5 days"], freq=None) + idx_diff = index.difference(other, sort) + tm.assert_index_equal(idx_diff, expected) + tm.assert_attr_equal("freq", idx_diff, expected) + + # preserve frequency when the difference is a contiguous + # subset of the original range + other = pd.timedelta_range("2 days", "5 days", freq="D") + idx_diff = index.difference(other, sort) + expected = pd.TimedeltaIndex(["0 days", "1 days"], freq="D") + tm.assert_index_equal(idx_diff, expected) + tm.assert_attr_equal("freq", idx_diff, expected) + + def test_difference_sort(self, sort): + index = pd.TimedeltaIndex( + ["5 days", "3 days", "2 days", "4 days", "1 days", "0 days"] + ) + + other = pd.timedelta_range("1 days", "4 days", freq="D") + idx_diff = index.difference(other, sort) + + expected = pd.TimedeltaIndex(["5 days", "0 days"], freq=None) + + if sort is None: + expected = expected.sort_values() + + tm.assert_index_equal(idx_diff, expected) + tm.assert_attr_equal("freq", idx_diff, expected) + + other = pd.timedelta_range("2 days", "5 days", freq="D") + idx_diff = index.difference(other, sort) + expected = pd.TimedeltaIndex(["1 days", "0 days"], freq=None) + + if sort is None: + expected = expected.sort_values() + + tm.assert_index_equal(idx_diff, expected) + tm.assert_attr_equal("freq", idx_diff, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_timedelta.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_timedelta.py new file mode 100644 index 0000000000000000000000000000000000000000..9f7c77bea32f904b5b7a35e614e6ffafa94501ac --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -0,0 +1,58 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestTimedeltaIndex: + def test_misc_coverage(self): + rng = pd.timedelta_range("1 day", periods=5) + result = rng.groupby(rng.days) + assert isinstance(next(iter(result.values()))[0], pd.Timedelta) + + def test_map(self): + # test_map_dictlike generally tests + + rng = pd.timedelta_range("1 day", periods=10) + + f = lambda x: x.days + result = rng.map(f) + exp = pd.Index([f(x) for x in rng], dtype=np.int64) + tm.assert_index_equal(result, exp) + + def test_fields(self): + rng = pd.timedelta_range("1 days, 10:11:12.100123456", periods=2, freq="s") + tm.assert_index_equal(rng.days, pd.Index([1, 1], dtype=np.int64)) + tm.assert_index_equal( + rng.seconds, + pd.Index( + [10 * 3600 + 11 * 60 + 12, 10 * 3600 + 11 * 60 + 13], dtype=np.int32 + ), + ) + tm.assert_index_equal( + rng.microseconds, + pd.Index([100 * 1000 + 123, 100 * 1000 + 123], dtype=np.int32), + ) + tm.assert_index_equal(rng.nanoseconds, pd.Index([456, 456], dtype=np.int32)) + + msg = "'TimedeltaIndex' object has no attribute '{}'" + with pytest.raises(AttributeError, match=msg.format("hours")): + rng.hours + with pytest.raises(AttributeError, match=msg.format("minutes")): + rng.minutes + with pytest.raises(AttributeError, match=msg.format("milliseconds")): + rng.milliseconds + + # with nat + s = pd.Series(rng) + s[1] = np.nan + + tm.assert_series_equal(s.dt.days, pd.Series([1, np.nan], index=range(2))) + tm.assert_series_equal( + s.dt.seconds, pd.Series([10 * 3600 + 11 * 60 + 12, np.nan], index=range(2)) + ) + + # preserve name (GH15589) + rng.name = "name" + assert rng.days.name == "name" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_timedelta_range.py b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_timedelta_range.py new file mode 100644 index 0000000000000000000000000000000000000000..92b15290515fe3b041b5853f0a01d14fc47f2283 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexes/timedeltas/test_timedelta_range.py @@ -0,0 +1,191 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + +from pandas.tseries.offsets import ( + Day, + Second, +) + + +class TestTimedeltas: + def test_timedelta_range_unit(self): + # GH#49824 + tdi = pd.timedelta_range("0 Days", periods=10, freq="100000D", unit="s") + exp_arr = (np.arange(10, dtype="i8") * 100_000).view("m8[D]").astype("m8[s]") + tm.assert_numpy_array_equal(tdi.to_numpy(), exp_arr) + + def test_timedelta_range(self): + expected = ( + pd.to_timedelta(np.arange(5), unit="D").as_unit("us")._with_freq("infer") + ) + result = pd.timedelta_range("0 days", periods=5, freq="D") + tm.assert_index_equal(result, expected) + + expected = ( + pd.to_timedelta(np.arange(11), unit="D").as_unit("us")._with_freq("infer") + ) + result = pd.timedelta_range("0 days", "10 days", freq="D") + tm.assert_index_equal(result, expected) + + expected = ( + pd.to_timedelta(np.arange(5), unit="D").as_unit("us") + Second(2) + Day() + )._with_freq("infer") + result = pd.timedelta_range("1 days, 00:00:02", "5 days, 00:00:02", freq="D") + tm.assert_index_equal(result, expected) + + expected = ( + pd.to_timedelta([1, 3, 5, 7, 9], unit="D").as_unit("us") + Second(2) + )._with_freq("infer") + result = pd.timedelta_range("1 days, 00:00:02", periods=5, freq="2D") + tm.assert_index_equal(result, expected) + + expected = ( + pd.to_timedelta(np.arange(50), unit="min").as_unit("us") * 30 + )._with_freq("infer") + result = pd.timedelta_range("0 days", freq="30min", periods=50) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("depr_unit, unit", [("H", "hour"), ("S", "second")]) + def test_timedelta_units_H_S_deprecated(self, depr_unit, unit): + # GH#52536 + depr_msg = ( + f"'{depr_unit}' is deprecated and will be removed in a future version." + ) + expected = pd.to_timedelta(np.arange(5), unit=unit) + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + result = pd.to_timedelta(np.arange(5), unit=depr_unit) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("unit", ["T", "t", "L", "l", "U", "u", "N", "n"]) + def test_timedelta_unit_T_L_U_N_raises(self, unit): + msg = f"invalid unit abbreviation: {unit}" + + with pytest.raises(ValueError, match=msg): + pd.to_timedelta(np.arange(5), unit=unit) + + @pytest.mark.parametrize( + "periods, freq", [(3, "2D"), (5, "D"), (6, "19h12min"), (7, "16h"), (9, "12h")] + ) + def test_linspace_behavior(self, periods, freq): + # GH 20976 + result = pd.timedelta_range(start="0 days", end="4 days", periods=periods) + expected = pd.timedelta_range(start="0 days", end="4 days", freq=freq) + tm.assert_index_equal(result, expected, check_freq=False) + + def test_timedelta_range_H_raises(self): + # GH#52536 + msg = "Invalid frequency: H" + + with pytest.raises(ValueError, match=msg): + pd.timedelta_range(start="0 days", end="4 days", freq="19H12min") + + def test_timedelta_range_T_raises(self): + msg = "Invalid frequency: T" + + with pytest.raises(ValueError, match=msg): + pd.timedelta_range(start="0 days", end="4 days", freq="19h12T") + + def test_errors(self): + # not enough params + msg = ( + "Of the four parameters: start, end, periods, and freq, " + "exactly three must be specified" + ) + with pytest.raises(ValueError, match=msg): + pd.timedelta_range(start="0 days") + + with pytest.raises(ValueError, match=msg): + pd.timedelta_range(end="5 days") + + with pytest.raises(ValueError, match=msg): + pd.timedelta_range(periods=2) + + with pytest.raises(ValueError, match=msg): + pd.timedelta_range() + + # too many params + with pytest.raises(ValueError, match=msg): + pd.timedelta_range(start="0 days", end="5 days", periods=10, freq="h") + + @pytest.mark.parametrize( + "start, end, freq, expected_periods", + [ + ("1D", "10D", "2D", (10 - 1) // 2 + 1), + ("2D", "30D", "3D", (30 - 2) // 3 + 1), + ("2s", "50s", "5s", (50 - 2) // 5 + 1), + # tests that worked before GH 33498: + ("4D", "16D", "3D", (16 - 4) // 3 + 1), + ("8D", "16D", "40s", (16 * 3600 * 24 - 8 * 3600 * 24) // 40 + 1), + ], + ) + def test_timedelta_range_freq_divide_end(self, start, end, freq, expected_periods): + # GH 33498 only the cases where `(end % freq) == 0` used to fail + res = pd.timedelta_range(start=start, end=end, freq=freq) + assert pd.Timedelta(start) == res[0] + assert pd.Timedelta(end) >= res[-1] + assert len(res) == expected_periods + + def test_timedelta_range_infer_freq(self): + # https://github.com/pandas-dev/pandas/issues/35897 + result = pd.timedelta_range("0s", "1s", periods=31) + assert result.freq is None + + @pytest.mark.parametrize( + "freq_depr, start, end", + [ + ( + "3.5l", + "05:03:01", + "05:03:10", + ), + ( + "2.5T", + "5 hours", + "5 hours 8 minutes", + ), + ( + "3.5S", + "05:03:01", + "05:03:10", + ), + ], + ) + def test_timedelta_range_removed_freq(self, freq_depr, start, end): + # GH#59143 + msg = f"Invalid frequency: {freq_depr}" + with pytest.raises(ValueError, match=msg): + pd.timedelta_range(start=start, end=end, freq=freq_depr) + + +class TestTimedeltaRangeUnitInference: + def test_timedelta_range_unit_inference_matching_unit(self, unit): + start = pd.Timedelta(0).as_unit(unit) + end = pd.Timedelta(days=1).as_unit(unit) + + tdi = pd.timedelta_range(start, end, freq="D") + assert tdi.unit == unit + + def test_timedelta_range_unit_inference_mismatched_unit(self, unit): + start = pd.Timedelta(0).as_unit(unit) + end = pd.Timedelta(days=1).as_unit("s") + + tdi = pd.timedelta_range(start, end, freq="D") + assert tdi.unit == unit + + tdi = pd.timedelta_range(start, end.as_unit("ns"), freq="D") + assert tdi.unit == "ns" + + def test_timedelta_range_unit_inference_tick(self): + start = pd.Timedelta(0).as_unit("ms") + end = pd.Timedelta(days=1).as_unit("s") + + tdi = pd.timedelta_range(start, end, freq="2000000us") + assert tdi.unit == "us" + + tdi = pd.timedelta_range(start, end.as_unit("ns"), freq="2000000us") + assert tdi.unit == "ns" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/common.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/common.py new file mode 100644 index 0000000000000000000000000000000000000000..a33fb1e6979ec48625d0c4bcd451fe2e64333e16 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/common.py @@ -0,0 +1,41 @@ +"""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/venv/lib/python3.14/site-packages/pandas/tests/indexing/interval/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/interval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/interval/test_interval.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/interval/test_interval.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e3d315b5cc83a6ae10d852a3ccb8951a41ae7e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/interval/test_interval.py @@ -0,0 +1,243 @@ +import numpy as np +import pytest + +from pandas._libs import index as libindex + +import pandas as pd +import pandas._testing as tm + + +class TestIntervalIndex: + @pytest.fixture + def series_with_interval_index(self): + return pd.Series(np.arange(5), pd.IntervalIndex.from_breaks(np.arange(6))) + + def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl): + ser = series_with_interval_index.copy() + + expected = ser.iloc[:3] + tm.assert_series_equal(expected, indexer_sl(ser)[:3]) + tm.assert_series_equal(expected, indexer_sl(ser)[:2.5]) + tm.assert_series_equal(expected, indexer_sl(ser)[0.1:2.5]) + if indexer_sl is tm.loc: + tm.assert_series_equal(expected, ser.loc[-1:3]) + + expected = ser.iloc[1:4] + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]]) + tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]]) + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]]) + + expected = ser.iloc[2:5] + tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2]) + + @pytest.mark.parametrize("direction", ["increasing", "decreasing"]) + def test_getitem_nonoverlapping_monotonic(self, direction, closed, indexer_sl): + tpls = [(0, 1), (2, 3), (4, 5)] + if direction == "decreasing": + tpls = tpls[::-1] + + idx = pd.IntervalIndex.from_tuples(tpls, closed=closed) + ser = pd.Series(list("abc"), idx) + + for key, expected in zip(idx.left, ser, strict=True): + if idx.closed_left: + assert indexer_sl(ser)[key] == expected + else: + with pytest.raises(KeyError, match=str(key)): + indexer_sl(ser)[key] + + for key, expected in zip(idx.right, ser, strict=True): + if idx.closed_right: + assert indexer_sl(ser)[key] == expected + else: + with pytest.raises(KeyError, match=str(key)): + indexer_sl(ser)[key] + + for key, expected in zip(idx.mid, ser, strict=True): + assert indexer_sl(ser)[key] == expected + + def test_getitem_non_matching(self, series_with_interval_index, indexer_sl): + ser = series_with_interval_index.copy() + + # this is a departure from our current + # indexing scheme, but simpler + with pytest.raises(KeyError, match=r"\[-1\] not in index"): + indexer_sl(ser)[[-1, 3, 4, 5]] + + with pytest.raises(KeyError, match=r"\[-1\] not in index"): + indexer_sl(ser)[[-1, 3]] + + def test_loc_getitem_large_series(self, monkeypatch): + size_cutoff = 20 + with monkeypatch.context(): + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) + ser = pd.Series( + np.arange(size_cutoff), + index=pd.IntervalIndex.from_breaks(np.arange(size_cutoff + 1)), + ) + + result1 = ser.loc[:8] + result2 = ser.loc[0:8] + result3 = ser.loc[0:8:1] + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) + + def test_loc_getitem_frame(self): + # CategoricalIndex with IntervalIndex categories + df = pd.DataFrame({"A": range(10)}) + ser = pd.cut(df.A, 5) + df["B"] = ser + df = df.set_index("B") + + result = df.loc[4] + expected = df.iloc[4:6] + tm.assert_frame_equal(result, expected) + + with pytest.raises(KeyError, match="10"): + df.loc[10] + + # single list-like + result = df.loc[[4]] + expected = df.iloc[4:6] + tm.assert_frame_equal(result, expected) + + # non-unique + result = df.loc[[4, 5]] + expected = df.take([4, 5, 4, 5]) + tm.assert_frame_equal(result, expected) + + msg = ( + r"None of \[Index\(\[10\], dtype='object', name='B'\)\] " + r"are in the \[index\]" + ) + with pytest.raises(KeyError, match=msg): + df.loc[[10]] + + # partial missing + with pytest.raises(KeyError, match=r"\[10\] not in index"): + df.loc[[10, 4]] + + def test_getitem_interval_with_nans(self, frame_or_series, indexer_sl): + # GH#41831 + + index = pd.IntervalIndex([np.nan, np.nan]) + key = index[:-1] + + obj = frame_or_series(range(2), index=index) + if frame_or_series is pd.DataFrame and indexer_sl is tm.setitem: + obj = obj.T + + result = indexer_sl(obj)[key] + expected = obj + + tm.assert_equal(result, expected) + + def test_setitem_interval_with_slice(self): + # GH#54722 + ii = pd.IntervalIndex.from_breaks(range(4, 15)) + ser = pd.Series(range(10), index=ii) + + orig = ser.copy() + + # This should be a no-op (used to raise) + ser.loc[1:3] = 20 + tm.assert_series_equal(ser, orig) + + ser.loc[6:8] = 19 + orig.iloc[1:4] = 19 + tm.assert_series_equal(ser, orig) + + ser2 = pd.Series(range(5), index=ii[::2]) + orig2 = ser2.copy() + + # this used to raise + ser2.loc[6:8] = 22 # <- raises on main, sets on branch + orig2.iloc[1] = 22 + tm.assert_series_equal(ser2, orig2) + + ser2.loc[5:7] = 21 + orig2.iloc[:2] = 21 + tm.assert_series_equal(ser2, orig2) + + +class TestIntervalIndexInsideMultiIndex: + def test_mi_intervalindex_slicing_with_scalar(self): + # GH#27456 + ii = pd.IntervalIndex.from_arrays( + [0, 1, 10, 11, 0, 1, 10, 11], [1, 2, 11, 12, 1, 2, 11, 12], name="MP" + ) + idx = pd.MultiIndex.from_arrays( + [ + pd.Index(["FC", "FC", "FC", "FC", "OWNER", "OWNER", "OWNER", "OWNER"]), + pd.Index( + ["RID1", "RID1", "RID2", "RID2", "RID1", "RID1", "RID2", "RID2"] + ), + ii, + ] + ) + + idx.names = ["Item", "RID", "MP"] + df = pd.DataFrame({"value": [1, 2, 3, 4, 5, 6, 7, 8]}) + df.index = idx + + query_df = pd.DataFrame( + { + "Item": ["FC", "OWNER", "FC", "OWNER", "OWNER"], + "RID": ["RID1", "RID1", "RID1", "RID2", "RID2"], + "MP": [0.2, 1.5, 1.6, 11.1, 10.9], + } + ) + + query_df = query_df.sort_index() + + idx = pd.MultiIndex.from_arrays([query_df.Item, query_df.RID, query_df.MP]) + query_df.index = idx + result = df.value.loc[query_df.index] + + # the IntervalIndex level is indexed with floats, which map to + # the intervals containing them. Matching the behavior we would get + # with _only_ an IntervalIndex, we get an IntervalIndex level back. + sliced_level = ii.take([0, 1, 1, 3, 2]) + expected_index = pd.MultiIndex.from_arrays( + [idx.get_level_values(0), idx.get_level_values(1), sliced_level] + ) + expected = pd.Series([1, 6, 2, 8, 7], index=expected_index, name="value") + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("base", [101, 1010]) + def test_reindex_behavior_with_interval_index(self, base): + # GH 51826 + + ser = pd.Series( + range(base), + index=pd.IntervalIndex.from_arrays(range(base), range(1, base + 1)), + ) + expected_result = pd.Series([np.nan, 0], index=[np.nan, 1.0], dtype=float) + result = ser.reindex(index=[np.nan, 1.0]) + tm.assert_series_equal(result, expected_result) + + def test_multiindex_with_interval_index(self): + # for GH#25298 + intIndex = pd.IntervalIndex.from_arrays([1, 5, 8, 13, 16], [4, 9, 12, 17, 20]) + multiIndex = pd.MultiIndex.from_arrays([["a", "a", "b", "b", "c"], intIndex]) + data = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)] + df = pd.DataFrame(data, index=multiIndex) + result = df.loc[("b", 16)] + expected = pd.Series([7, 8], name=("b", pd.Interval(13, 17, closed="right"))) + tm.assert_series_equal(result, expected) + + +def test_categorical_interval_index_getitem_scalar(): + # GH#27437 + # Scalar indexing on Series with CategoricalIndex of Intervals + # should use interval membership (point-in-interval lookup) + ser = pd.Series( + ["a", "b", "c", "d", "e"], + index=pd.CategoricalIndex(pd.IntervalIndex.from_breaks(range(6))), + ) + # 0.5 is in (0, 1], 1.5 is in (1, 2], etc. + assert ser[0.5] == "a" + assert ser[1.5] == "b" + # Points on boundaries: 1 is in (0, 1] (right-closed) + assert ser[1] == "a" + assert ser[2] == "b" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/interval/test_interval_new.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/interval/test_interval_new.py new file mode 100644 index 0000000000000000000000000000000000000000..6968c5edab82b3aaac6c463fc0c8a7ae4824855b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/interval/test_interval_new.py @@ -0,0 +1,227 @@ +import re + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestIntervalIndex: + @pytest.fixture + def series_with_interval_index(self): + """ + Fixture providing a Series with an IntervalIndex. + """ + return pd.Series(np.arange(5), pd.IntervalIndex.from_breaks(np.arange(6))) + + def test_loc_with_interval(self, series_with_interval_index, indexer_sl): + # loc with single label / list of labels: + # - Intervals: only exact matches + # - scalars: those that contain it + + ser = series_with_interval_index.copy() + + expected = 0 + result = indexer_sl(ser)[pd.Interval(0, 1)] + assert result == expected + + expected = ser.iloc[3:5] + result = indexer_sl(ser)[[pd.Interval(3, 4), pd.Interval(4, 5)]] + tm.assert_series_equal(expected, result) + + # missing or not exact + with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='left')")): + indexer_sl(ser)[pd.Interval(3, 5, closed="left")] + + with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")): + indexer_sl(ser)[pd.Interval(3, 5)] + + with pytest.raises( + KeyError, match=re.escape("Interval(-2, 0, closed='right')") + ): + indexer_sl(ser)[pd.Interval(-2, 0)] + + with pytest.raises(KeyError, match=re.escape("Interval(5, 6, closed='right')")): + indexer_sl(ser)[pd.Interval(5, 6)] + + def test_loc_with_scalar(self, series_with_interval_index, indexer_sl): + # loc with single label / list of labels: + # - Intervals: only exact matches + # - scalars: those that contain it + + ser = series_with_interval_index.copy() + + assert indexer_sl(ser)[1] == 0 + assert indexer_sl(ser)[1.5] == 1 + assert indexer_sl(ser)[2] == 1 + + expected = ser.iloc[1:4] + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]]) + tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]]) + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]]) + + expected = ser.iloc[[1, 1, 2, 1]] + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2, 2.5, 1.5]]) + + expected = ser.iloc[2:5] + tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2]) + + def test_loc_with_slices(self, series_with_interval_index, indexer_sl): + # loc with slices: + # - Interval objects: only works with exact matches + # - scalars: only works for non-overlapping, monotonic intervals, + # and start/stop select location based on the interval that + # contains them: + # (slice_loc(start, stop) == (idx.get_loc(start), idx.get_loc(stop)) + + ser = series_with_interval_index.copy() + + # slice of interval + + expected = ser.iloc[:3] + result = indexer_sl(ser)[pd.Interval(0, 1) : pd.Interval(2, 3)] + tm.assert_series_equal(expected, result) + + expected = ser.iloc[3:] + result = indexer_sl(ser)[pd.Interval(3, 4) :] + tm.assert_series_equal(expected, result) + + msg = "Interval objects are not currently supported" + with pytest.raises(NotImplementedError, match=msg): + indexer_sl(ser)[pd.Interval(3, 6) :] + + with pytest.raises(NotImplementedError, match=msg): + indexer_sl(ser)[pd.Interval(3, 4, closed="left") :] + + def test_slice_step_ne1(self, series_with_interval_index): + # GH#31658 slice of scalar with step != 1 + ser = series_with_interval_index.copy() + expected = ser.iloc[0:4:2] + + result = ser[0:4:2] + tm.assert_series_equal(result, expected) + + result2 = ser[0:4][::2] + tm.assert_series_equal(result2, expected) + + def test_slice_float_start_stop(self, series_with_interval_index): + # GH#31658 slicing with integers is positional, with floats is not + # supported + ser = series_with_interval_index.copy() + + msg = "label-based slicing with step!=1 is not supported for IntervalIndex" + with pytest.raises(ValueError, match=msg): + ser[1.5:9.5:2] + + def test_slice_interval_step(self, series_with_interval_index): + # GH#31658 allows for integer step!=1, not Interval step + ser = series_with_interval_index.copy() + msg = "label-based slicing with step!=1 is not supported for IntervalIndex" + with pytest.raises(ValueError, match=msg): + ser[0 : 4 : pd.Interval(0, 1)] + + def test_loc_with_overlap(self, indexer_sl): + idx = pd.IntervalIndex.from_tuples([(1, 5), (3, 7)]) + ser = pd.Series(range(len(idx)), index=idx) + + # scalar + expected = ser + result = indexer_sl(ser)[4] + tm.assert_series_equal(expected, result) + + result = indexer_sl(ser)[[4]] + tm.assert_series_equal(expected, result) + + # interval + expected = 0 + result = indexer_sl(ser)[pd.Interval(1, 5)] + assert expected == result + + expected = ser + result = indexer_sl(ser)[[pd.Interval(1, 5), pd.Interval(3, 7)]] + tm.assert_series_equal(expected, result) + + with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")): + indexer_sl(ser)[pd.Interval(3, 5)] + + msg = ( + r"None of \[IntervalIndex\(\[\(3, 5\]\], " + r"dtype='interval\[int64, right\]'\)\] are in the \[index\]" + ) + with pytest.raises(KeyError, match=msg): + indexer_sl(ser)[[pd.Interval(3, 5)]] + + # slices with interval (only exact matches) + expected = ser + result = indexer_sl(ser)[pd.Interval(1, 5) : pd.Interval(3, 7)] + tm.assert_series_equal(expected, result) + + msg = ( + "'can only get slices from an IntervalIndex if bounds are " + "non-overlapping and all monotonic increasing or decreasing'" + ) + with pytest.raises(KeyError, match=msg): + indexer_sl(ser)[pd.Interval(1, 6) : pd.Interval(3, 8)] + + if indexer_sl is tm.loc: + # slices with scalar raise for overlapping intervals + # TODO KeyError is the appropriate error? + with pytest.raises(KeyError, match=msg): + ser.loc[1:4] + + def test_non_unique(self, indexer_sl): + idx = pd.IntervalIndex.from_tuples([(1, 3), (3, 7)]) + ser = pd.Series(range(len(idx)), index=idx) + + result = indexer_sl(ser)[pd.Interval(1, 3)] + assert result == 0 + + result = indexer_sl(ser)[[pd.Interval(1, 3)]] + expected = ser.iloc[0:1] + tm.assert_series_equal(expected, result) + + def test_non_unique_moar(self, indexer_sl): + idx = pd.IntervalIndex.from_tuples([(1, 3), (1, 3), (3, 7)]) + ser = pd.Series(range(len(idx)), index=idx) + + expected = ser.iloc[[0, 1]] + result = indexer_sl(ser)[pd.Interval(1, 3)] + tm.assert_series_equal(expected, result) + + expected = ser + result = indexer_sl(ser)[pd.Interval(1, 3) :] + tm.assert_series_equal(expected, result) + + expected = ser.iloc[[0, 1]] + result = indexer_sl(ser)[[pd.Interval(1, 3)]] + tm.assert_series_equal(expected, result) + + def test_loc_getitem_missing_key_error_message( + self, frame_or_series, series_with_interval_index + ): + # GH#27365 + ser = series_with_interval_index.copy() + obj = frame_or_series(ser) + with pytest.raises(KeyError, match=r"\[6\]"): + obj.loc[[4, 5, 6]] + + +@pytest.mark.parametrize( + "intervals", + [ + ([pd.Interval(-np.inf, 0.0), pd.Interval(0.0, 1.0)]), + ([pd.Interval(-np.inf, -2.0), pd.Interval(-2.0, -1.0)]), + ([pd.Interval(-1.0, 0.0), pd.Interval(0.0, np.inf)]), + ([pd.Interval(1.0, 2.0), pd.Interval(2.0, np.inf)]), + ], +) +def test_repeating_interval_index_with_infs(intervals): + # GH 46658 + + interval_index = pd.Index(intervals * 51) + + expected = np.arange(1, 102, 2, dtype=np.intp) + result = interval_index.get_indexer_for([intervals[1]]) + + tm.assert_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_chaining_and_caching.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_chaining_and_caching.py new file mode 100644 index 0000000000000000000000000000000000000000..78b6e19015316cb2a3010ddbf058be2338b45317 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_chaining_and_caching.py @@ -0,0 +1,84 @@ +import numpy as np + +from pandas._libs import index as libindex + +import pandas as pd +import pandas._testing as tm + + +def test_detect_chained_assignment(): + # Inplace ops, originally from: + # https://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug + a = [12, 23] + b = [123, None] + c = [1234, 2345] + d = [12345, 23456] + tuples = [("eyes", "left"), ("eyes", "right"), ("ears", "left"), ("ears", "right")] + events = { + ("eyes", "left"): a, + ("eyes", "right"): b, + ("ears", "left"): c, + ("ears", "right"): d, + } + multiind = pd.MultiIndex.from_tuples(tuples, names=["part", "side"]) + zed = pd.DataFrame(events, index=["a", "b"], columns=multiind) + + with tm.raises_chained_assignment_error(): + zed["eyes"]["right"].fillna(value=555, inplace=True) + + +def test_cache_updating(): + # 5216 + # make sure that we don't try to set a dead cache + a = np.random.default_rng(2).random((10, 3)) + df = pd.DataFrame(a, columns=["x", "y", "z"]) + df_original = df.copy() + tuples = [(i, j) for i in range(5) for j in range(2)] + index = pd.MultiIndex.from_tuples(tuples) + df.index = index + + # setting via chained assignment + # but actually works, since everything is a view + + with tm.raises_chained_assignment_error(): + df.loc[0]["z"].iloc[0] = 1.0 + + assert df.loc[(0, 0), "z"] == df_original.loc[0, "z"] + + # correct setting + df.loc[(0, 0), "z"] = 2 + result = df.loc[(0, 0), "z"] + assert result == 2 + + +def test_indexer_caching(monkeypatch): + # GH5727 + # make sure that indexers are in the _internal_names_set + size_cutoff = 20 + with monkeypatch.context(): + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) + index = pd.MultiIndex.from_arrays( + [np.arange(size_cutoff), np.arange(size_cutoff)] + ) + s = pd.Series(np.zeros(size_cutoff), index=index) + + # setitem + s[s == 0] = 1 + expected = pd.Series(np.ones(size_cutoff), index=index) + tm.assert_series_equal(s, expected) + + +def test_set_names_only_clears_level_cache(): + mi = pd.MultiIndex.from_arrays([range(4), range(4)], names=["a", "b"]) + mi.dtypes + mi.is_monotonic_increasing + mi._engine + mi.levels + old_cache_keys = sorted(mi._cache.keys()) + assert old_cache_keys == ["_engine", "dtypes", "is_monotonic_increasing", "levels"] + mi.names = ["A", "B"] + new_cache_keys = sorted(mi._cache.keys()) + assert new_cache_keys == ["_engine", "dtypes", "is_monotonic_increasing"] + new_levels = mi.levels + tm.assert_index_equal(new_levels[0], pd.RangeIndex(4, name="A")) + tm.assert_index_equal(new_levels[1], pd.RangeIndex(4, name="B")) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_datetime.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_datetime.py new file mode 100644 index 0000000000000000000000000000000000000000..7139a636589acc2b97d160f4555784fd21299e91 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_datetime.py @@ -0,0 +1,43 @@ +from datetime import datetime + +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +def test_multiindex_period_datetime(): + # GH4861, using datetime in period of multiindex raises exception + + idx1 = pd.Index(["a", "a", "a", "b", "b"]) + idx2 = pd.period_range("2012-01", periods=len(idx1), freq="M") + s = pd.Series(np.random.default_rng(2).standard_normal(len(idx1)), [idx1, idx2]) + + # try Period as index + expected = s.iloc[0] + result = s.loc["a", pd.Period("2012-01")] + assert result == expected + + # try datetime as index + result = s.loc["a", datetime(2012, 1, 1)] + assert result == expected + + +def test_multiindex_datetime_columns(): + # GH35015, using datetime as column indices raises exception + + mi = pd.MultiIndex.from_tuples( + [(pd.to_datetime("02/29/2020"), pd.to_datetime("03/01/2020"))], names=["a", "b"] + ) + + df = pd.DataFrame([], columns=mi) + + expected_df = pd.DataFrame( + [], + columns=pd.MultiIndex.from_arrays( + [[pd.to_datetime("02/29/2020")], [pd.to_datetime("03/01/2020")]], + names=["a", "b"], + ), + ) + + tm.assert_frame_equal(df, expected_df) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_getitem.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_getitem.py new file mode 100644 index 0000000000000000000000000000000000000000..f80482c79c8a6385792c8a3413b46fca0f2179d5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_getitem.py @@ -0,0 +1,416 @@ +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.core.indexing import IndexingError + +# ---------------------------------------------------------------------------- +# test indexing of Series with multi-level Index +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "access_method", + [lambda s, x: s[:, x], lambda s, x: s.loc[:, x], lambda s, x: s.xs(x, level=1)], +) +@pytest.mark.parametrize( + "level1_value, expected", + [(0, pd.Series([1], index=[0])), (1, pd.Series([2, 3], index=[1, 2]))], +) +def test_series_getitem_multiindex(access_method, level1_value, expected): + # GH 6018 + # series regression getitem with a multi-index + + mi = pd.MultiIndex.from_tuples([(0, 0), (1, 1), (2, 1)], names=["A", "B"]) + ser = pd.Series([1, 2, 3], index=mi) + expected.index.name = "A" + + result = access_method(ser, level1_value) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("level0_value", ["D", "A"]) +def test_series_getitem_duplicates_multiindex(level0_value): + # GH 5725 the 'A' happens to be a valid Timestamp so the doesn't raise + # the appropriate error, only in PY3 of course! + + index = pd.MultiIndex( + levels=[[level0_value, "B", "C"], [0, 26, 27, 37, 57, 67, 75, 82]], + codes=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]], + names=["tag", "day"], + ) + arr = np.random.default_rng(2).standard_normal((len(index), 1)) + df = pd.DataFrame(arr, index=index, columns=["val"]) + + # confirm indexing on missing value raises KeyError + if level0_value != "A": + with pytest.raises(KeyError, match=r"^'A'$"): + df.val["A"] + + with pytest.raises(KeyError, match=r"^'X'$"): + df.val["X"] + + result = df.val[level0_value] + expected = pd.Series( + arr.ravel()[0:3], name="val", index=pd.Index([26, 37, 57], name="day") + ) + tm.assert_series_equal(result, expected) + + +def test_series_getitem(multiindex_year_month_day_dataframe_random_data, indexer_sl): + s = multiindex_year_month_day_dataframe_random_data["A"] + expected = s.reindex(s.index[42:65]) + expected.index = expected.index.droplevel(0).droplevel(0) + + result = indexer_sl(s)[2000, 3] + tm.assert_series_equal(result, expected) + + +def test_series_getitem_returns_scalar( + multiindex_year_month_day_dataframe_random_data, indexer_sl +): + s = multiindex_year_month_day_dataframe_random_data["A"] + expected = s.iloc[49] + + result = indexer_sl(s)[2000, 3, 10] + assert result == expected + + +@pytest.mark.parametrize( + "indexer,expected_error,expected_error_msg", + [ + (lambda s: s.__getitem__((2000, 3, 4)), KeyError, r"^\(2000, 3, 4\)$"), + (lambda s: s[(2000, 3, 4)], KeyError, r"^\(2000, 3, 4\)$"), + (lambda s: s.loc[(2000, 3, 4)], KeyError, r"^\(2000, 3, 4\)$"), + (lambda s: s.loc[(2000, 3, 4, 5)], IndexingError, "Too many indexers"), + ( + lambda s: s.__getitem__(len(s)), + KeyError, + "100", + ), # match should include len(s) + (lambda s: s[len(s)], KeyError, "100"), # match should include len(s) + ( + lambda s: s.iloc[len(s)], + IndexError, + "single positional indexer is out-of-bounds", + ), + ], +) +def test_series_getitem_indexing_errors( + multiindex_year_month_day_dataframe_random_data, + indexer, + expected_error, + expected_error_msg, +): + s = multiindex_year_month_day_dataframe_random_data["A"] + with pytest.raises(expected_error, match=expected_error_msg): + indexer(s) + + +def test_series_getitem_corner_generator( + multiindex_year_month_day_dataframe_random_data, +): + s = multiindex_year_month_day_dataframe_random_data["A"] + result = s[(x > 0 for x in s)] + expected = s[s > 0] + tm.assert_series_equal(result, expected) + + +# ---------------------------------------------------------------------------- +# test indexing of DataFrame with multi-level Index +# ---------------------------------------------------------------------------- + + +def test_getitem_simple(multiindex_dataframe_random_data): + df = multiindex_dataframe_random_data.T + expected = df.values[:, 0] + result = df["foo", "one"].values + tm.assert_almost_equal(result, expected) + + +@pytest.mark.parametrize( + "indexer,expected_error_msg", + [ + (lambda df: df[("foo", "four")], r"^\('foo', 'four'\)$"), + (lambda df: df["foobar"], r"^'foobar'$"), + ], +) +def test_frame_getitem_simple_key_error( + multiindex_dataframe_random_data, indexer, expected_error_msg +): + df = multiindex_dataframe_random_data.T + with pytest.raises(KeyError, match=expected_error_msg): + indexer(df) + + +def test_tuple_string_column_names(): + # GH#50372 + mi = pd.MultiIndex.from_tuples([("a", "aa"), ("a", "ab"), ("b", "ba"), ("b", "bb")]) + df = pd.DataFrame([range(4), range(1, 5), range(2, 6)], columns=mi) + with tm.assert_produces_warning(Pandas4Warning, match="Setting a new column"): + df["single_index"] = 0 + + df_flat = df.copy() + df_flat.columns = df_flat.columns.to_flat_index() + df_flat["new_single_index"] = 0 + + result = df_flat[[("a", "aa"), "new_single_index"]] + expected = pd.DataFrame( + [[0, 0], [1, 0], [2, 0]], columns=pd.Index([("a", "aa"), "new_single_index"]) + ) + tm.assert_frame_equal(result, expected) + + +def test_frame_getitem_multicolumn_empty_level(): + df = pd.DataFrame({"a": ["1", "2", "3"], "b": ["2", "3", "4"]}) + df.columns = [ + ["level1 item1", "level1 item2"], + ["", "level2 item2"], + ["level3 item1", "level3 item2"], + ] + + result = df["level1 item1"] + expected = pd.DataFrame( + [["1"], ["2"], ["3"]], index=df.index, columns=["level3 item1"] + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "indexer,expected_slice", + [ + (lambda df: df["foo"], slice(3)), + (lambda df: df["bar"], slice(3, 5)), + (lambda df: df.loc[:, "bar"], slice(3, 5)), + ], +) +def test_frame_getitem_toplevel( + multiindex_dataframe_random_data, indexer, expected_slice +): + df = multiindex_dataframe_random_data.T + expected = df.reindex(columns=df.columns[expected_slice]) + expected.columns = expected.columns.droplevel(0) + result = indexer(df) + tm.assert_frame_equal(result, expected) + + +def test_frame_mixed_depth_get(): + arrays = [ + ["a", "top", "top", "routine1", "routine1", "routine2"], + ["", "OD", "OD", "result1", "result2", "result1"], + ["", "wx", "wy", "", "", ""], + ] + + tuples = sorted(zip(*arrays, strict=True)) + index = pd.MultiIndex.from_tuples(tuples) + df = pd.DataFrame(np.random.default_rng(2).standard_normal((4, 6)), columns=index) + + result = df["a"] + expected = df["a", "", ""].rename("a") + tm.assert_series_equal(result, expected) + + result = df["routine1", "result1"] + expected = df["routine1", "result1", ""] + expected = expected.rename(("routine1", "result1")) + tm.assert_series_equal(result, expected) + + +def test_frame_getitem_nan_multiindex(nulls_fixture): + # GH#29751 + # loc on a multiindex containing nan values + n = nulls_fixture # for code readability + cols = ["a", "b", "c"] + df = pd.DataFrame( + [[11, n, 13], [21, n, 23], [31, n, 33], [41, n, 43]], + columns=cols, + ).set_index(["a", "b"]) + df["c"] = df["c"].astype("int64") + + idx = (21, n) + result = df.loc[:idx] + expected = pd.DataFrame([[11, n, 13], [21, n, 23]], columns=cols).set_index( + ["a", "b"] + ) + expected["c"] = expected["c"].astype("int64") + tm.assert_frame_equal(result, expected) + + result = df.loc[idx:] + expected = pd.DataFrame( + [[21, n, 23], [31, n, 33], [41, n, 43]], columns=cols + ).set_index(["a", "b"]) + expected["c"] = expected["c"].astype("int64") + tm.assert_frame_equal(result, expected) + + idx1, idx2 = (21, n), (31, n) + result = df.loc[idx1:idx2] + expected = pd.DataFrame([[21, n, 23], [31, n, 33]], columns=cols).set_index( + ["a", "b"] + ) + expected["c"] = expected["c"].astype("int64") + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "indexer,expected", + [ + ( + (["b"], ["bar", np.nan]), + ( + pd.DataFrame( + [[2, 3], [5, 6]], + columns=pd.MultiIndex.from_tuples([("b", "bar"), ("b", np.nan)]), + dtype="int64", + ) + ), + ), + ( + (["a", "b"]), + ( + pd.DataFrame( + [[1, 2, 3], [4, 5, 6]], + columns=pd.MultiIndex.from_tuples( + [("a", "foo"), ("b", "bar"), ("b", np.nan)] + ), + dtype="int64", + ) + ), + ), + ( + (["b"]), + ( + pd.DataFrame( + [[2, 3], [5, 6]], + columns=pd.MultiIndex.from_tuples([("b", "bar"), ("b", np.nan)]), + dtype="int64", + ) + ), + ), + ( + (["b"], ["bar"]), + ( + pd.DataFrame( + [[2], [5]], + columns=pd.MultiIndex.from_tuples([("b", "bar")]), + dtype="int64", + ) + ), + ), + ( + (["b"], [np.nan]), + ( + pd.DataFrame( + [[3], [6]], + columns=pd.MultiIndex( + codes=[[1], [-1]], levels=[["a", "b"], ["bar", "foo"]] + ), + dtype="int64", + ) + ), + ), + (("b", np.nan), pd.Series([3, 6], dtype="int64", name=("b", np.nan))), + ], +) +def test_frame_getitem_nan_cols_multiindex( + indexer, + expected, + nulls_fixture, +): + # Slicing MultiIndex including levels with nan values, for more information + # see GH#25154 + df = pd.DataFrame( + [[1, 2, 3], [4, 5, 6]], + columns=pd.MultiIndex.from_tuples( + [("a", "foo"), ("b", "bar"), ("b", nulls_fixture)] + ), + dtype="int64", + ) + + result = df.loc[:, indexer] + tm.assert_equal(result, expected) + + +# ---------------------------------------------------------------------------- +# test indexing of DataFrame with multi-level Index with duplicates +# ---------------------------------------------------------------------------- + + +@pytest.fixture +def dataframe_with_duplicate_index(): + """Fixture for DataFrame used in tests for gh-4145 and gh-4146""" + data = [["a", "d", "e", "c", "f", "b"], [1, 4, 5, 3, 6, 2], [1, 4, 5, 3, 6, 2]] + index = ["h1", "h3", "h5"] + columns = pd.MultiIndex( + levels=[["A", "B"], ["A1", "A2", "B1", "B2"]], + codes=[[0, 0, 0, 1, 1, 1], [0, 3, 3, 0, 1, 2]], + names=["main", "sub"], + ) + return pd.DataFrame(data, index=index, columns=columns) + + +@pytest.mark.parametrize( + "indexer", [lambda df: df[("A", "A1")], lambda df: df.loc[:, ("A", "A1")]] +) +def test_frame_mi_access(dataframe_with_duplicate_index, indexer): + # GH#4145, GH#42102 + df = dataframe_with_duplicate_index + expected = pd.Series( + ["a", 1, 1], index=pd.Index(["h1", "h3", "h5"]), name=("A", "A1") + ) + + result = indexer(df) + tm.assert_series_equal(result, expected) + + +def test_frame_mi_access_returns_series(dataframe_with_duplicate_index): + # GH 4146, not returning a block manager when selecting a unique index + # from a duplicate index + # as of 4879, this returns a Series (which is similar to what happens + # with a non-unique) + df = dataframe_with_duplicate_index + expected = pd.Series(["a", 1, 1], index=["h1", "h3", "h5"], name="A1") + result = df["A"]["A1"] + tm.assert_series_equal(result, expected) + + +def test_frame_mi_access_returns_frame(dataframe_with_duplicate_index): + # selecting a non_unique from the 2nd level + df = dataframe_with_duplicate_index + expected = pd.DataFrame( + [["d", 4, 4], ["e", 5, 5]], + index=pd.Index(["B2", "B2"], name="sub"), + columns=["h1", "h3", "h5"], + ).T + result = df["A"]["B2"] + tm.assert_frame_equal(result, expected) + + +def test_frame_mi_empty_slice(): + # GH 15454 + df = pd.DataFrame(0, index=range(2), columns=pd.MultiIndex.from_product([[1], [2]])) + result = df[[]] + expected = pd.DataFrame( + index=[0, 1], columns=pd.MultiIndex(levels=[[1], [2]], codes=[[], []]) + ) + tm.assert_frame_equal(result, expected) + + +def test_loc_empty_multiindex(): + # GH#36936 + arrays = [["a", "a", "b", "a"], ["a", "a", "b", "b"]] + index = pd.MultiIndex.from_arrays(arrays, names=("idx1", "idx2")) + df = pd.DataFrame([1, 2, 3, 4], index=index, columns=["value"]) + + # loc on empty multiindex == loc with False mask + empty_multiindex = df.loc[df.loc[:, "value"] == 0, :].index + result = df.loc[empty_multiindex, :] + expected = df.loc[[False] * len(df.index), :] + tm.assert_frame_equal(result, expected) + + # replacing value with loc on empty multiindex + df.loc[df.loc[df.loc[:, "value"] == 0].index, "value"] = 5 + result = df + expected = pd.DataFrame([1, 2, 3, 4], index=index, columns=["value"]) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_iloc.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_iloc.py new file mode 100644 index 0000000000000000000000000000000000000000..605d67baa754f893d94b6fef6dfde951ee483e00 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_iloc.py @@ -0,0 +1,169 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def simple_multiindex_dataframe(): + """ + Factory function to create simple 3 x 3 dataframe with + both columns and row MultiIndex using supplied data or + random data by default. + """ + + data = np.random.default_rng(2).standard_normal((3, 3)) + return pd.DataFrame( + data, columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]] + ) + + +@pytest.mark.parametrize( + "indexer, expected", + [ + ( + lambda df: df.iloc[0], + lambda arr: pd.Series(arr[0], index=[[2, 2, 4], [6, 8, 10]], name=(4, 8)), + ), + ( + lambda df: df.iloc[2], + lambda arr: pd.Series(arr[2], index=[[2, 2, 4], [6, 8, 10]], name=(8, 12)), + ), + ( + lambda df: df.iloc[:, 2], + lambda arr: pd.Series( + arr[:, 2], index=[[4, 4, 8], [8, 10, 12]], name=(4, 10) + ), + ), + ], +) +def test_iloc_returns_series(indexer, expected, simple_multiindex_dataframe): + df = simple_multiindex_dataframe + arr = df.values + result = indexer(df) + expected = expected(arr) + tm.assert_series_equal(result, expected) + + +def test_iloc_returns_dataframe(simple_multiindex_dataframe): + df = simple_multiindex_dataframe + result = df.iloc[[0, 1]] + expected = df.xs(4, drop_level=False) + tm.assert_frame_equal(result, expected) + + +def test_iloc_returns_scalar(simple_multiindex_dataframe): + df = simple_multiindex_dataframe + arr = df.values + result = df.iloc[2, 2] + expected = arr[2, 2] + assert result == expected + + +def test_iloc_getitem_multiple_items(): + # GH 5528 + tup = zip(*[["a", "a", "b", "b"], ["x", "y", "x", "y"]], strict=True) + index = pd.MultiIndex.from_tuples(tup) + df = pd.DataFrame(np.random.default_rng(2).standard_normal((4, 4)), index=index) + result = df.iloc[[2, 3]] + expected = df.xs("b", drop_level=False) + tm.assert_frame_equal(result, expected) + + +def test_iloc_getitem_labels(): + # this is basically regular indexing + arr = np.random.default_rng(2).standard_normal((4, 3)) + df = pd.DataFrame( + arr, + columns=[["i", "i", "j"], ["A", "A", "B"]], + index=[["i", "i", "j", "k"], ["X", "X", "Y", "Y"]], + ) + result = df.iloc[2, 2] + expected = arr[2, 2] + assert result == expected + + +def test_frame_getitem_slice(multiindex_dataframe_random_data): + df = multiindex_dataframe_random_data + result = df.iloc[:4] + expected = df[:4] + tm.assert_frame_equal(result, expected) + + +def test_frame_setitem_slice(multiindex_dataframe_random_data): + df = multiindex_dataframe_random_data + df.iloc[:4] = 0 + + assert (df.values[:4] == 0).all() + assert (df.values[4:] != 0).all() + + +def test_indexing_ambiguity_bug_1678(): + # GH 1678 + columns = pd.MultiIndex.from_tuples( + [("Ohio", "Green"), ("Ohio", "Red"), ("Colorado", "Green")] + ) + index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), ("b", 2)]) + + df = pd.DataFrame(np.arange(12).reshape((4, 3)), index=index, columns=columns) + + result = df.iloc[:, 1] + expected = df.loc[:, ("Ohio", "Red")] + tm.assert_series_equal(result, expected) + + +def test_iloc_integer_locations(): + # GH 13797 + data = [ + ["str00", "str01"], + ["str10", "str11"], + ["str20", "srt21"], + ["str30", "str31"], + ["str40", "str41"], + ] + + index = pd.MultiIndex.from_tuples( + [("CC", "A"), ("CC", "B"), ("CC", "B"), ("BB", "a"), ("BB", "b")] + ) + + expected = pd.DataFrame(data) + df = pd.DataFrame(data, index=index) + + result = pd.DataFrame([[df.iloc[r, c] for c in range(2)] for r in range(5)]) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data, indexes, values, expected_k", + [ + # test without indexer value in first level of MultiIndex + ([[2, 22, 5], [2, 33, 6]], [0, -1, 1], [2, 3, 1], [7, 10]), + # test like code sample 1 in the issue + ([[1, 22, 555], [1, 33, 666]], [0, -1, 1], [200, 300, 100], [755, 1066]), + # test like code sample 2 in the issue + ([[1, 3, 7], [2, 4, 8]], [0, -1, 1], [10, 10, 1000], [17, 1018]), + # test like code sample 3 in the issue + ([[1, 11, 4], [2, 22, 5], [3, 33, 6]], [0, -1, 1], [4, 7, 10], [8, 15, 13]), + ], +) +def test_iloc_setitem_int_multiindex_series(data, indexes, values, expected_k): + # GH17148 + df = pd.DataFrame(data=data, columns=["i", "j", "k"]) + df = df.set_index(["i", "j"]) + + series = df.k.copy() + for i, v in zip(indexes, values, strict=True): + series.iloc[i] += v + + df["k"] = expected_k + expected = df.k + tm.assert_series_equal(series, expected) + + +def test_getitem_iloc(multiindex_dataframe_random_data): + df = multiindex_dataframe_random_data + result = df.iloc[2] + expected = df.xs(df.index[2]) + tm.assert_series_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_indexing_slow.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_indexing_slow.py new file mode 100644 index 0000000000000000000000000000000000000000..bf6ec5dd1f119be164bf31e9a109d920a51315e6 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_indexing_slow.py @@ -0,0 +1,112 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def m(): + return 5 + + +@pytest.fixture +def n(): + return 100 + + +@pytest.fixture +def cols(): + return ["jim", "joe", "jolie", "joline", "jolia"] + + +@pytest.fixture +def vals(n): + vals = [ + np.random.default_rng(2).integers(0, 10, n), + np.random.default_rng(2).choice(list("abcdefghij"), n), + np.random.default_rng(2).choice( + pd.date_range("20141009", periods=10).tolist(), n + ), + np.random.default_rng(2).choice(list("ZYXWVUTSRQ"), n), + np.random.default_rng(2).standard_normal(n), + ] + vals = list(map(tuple, zip(*vals, strict=True))) + return vals + + +@pytest.fixture +def keys(n, m, vals): + # bunch of keys for testing + keys = [ + np.random.default_rng(2).integers(0, 11, m), + np.random.default_rng(2).choice(list("abcdefghijk"), m), + np.random.default_rng(2).choice( + pd.date_range("20141009", periods=11).tolist(), m + ), + np.random.default_rng(2).choice(list("ZYXWVUTSRQP"), m), + ] + keys = list(map(tuple, zip(*keys, strict=True))) + keys += [t[:-1] for t in vals[:: n // m]] + return keys + + +# covers both unique index and non-unique index +@pytest.fixture +def df(vals, cols): + return pd.DataFrame(vals, columns=cols) + + +@pytest.fixture +def a(df): + return pd.concat([df, df]) + + +@pytest.fixture +def b(df, cols): + return df.drop_duplicates(subset=cols[:-1]) + + +@pytest.mark.slow +@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") +@pytest.mark.parametrize("lexsort_depth", list(range(5))) +@pytest.mark.parametrize("frame_fixture", ["a", "b"]) +def test_multiindex_get_loc(request, lexsort_depth, keys, frame_fixture, cols): + # GH7724, GH2646 + + frame = request.getfixturevalue(frame_fixture) + if lexsort_depth == 0: + df = frame.copy(deep=False) + else: + df = frame.sort_values(by=cols[:lexsort_depth]) + + mi = df.set_index(cols[:-1]) + assert not mi.index._lexsort_depth < lexsort_depth + for key in keys: + mask = np.ones(len(df), dtype=bool) + + # test for all partials of this key + for i, k in enumerate(key): + mask &= df.iloc[:, i] == k + + if not mask.any(): + assert key[: i + 1] not in mi.index + continue + + assert key[: i + 1] in mi.index + right = df[mask].copy(deep=False) + + if i + 1 != len(key): # partial key + right = right.drop(cols[: i + 1], axis=1) + right = right.set_index(cols[i + 1 : -1]) + tm.assert_frame_equal(mi.loc[key[: i + 1]], right) + + else: # full key + right = right.set_index(cols[:-1]) + if len(right) == 1: # single hit + right = pd.Series( + right["jolia"].values, name=right.index[0], index=["jolia"] + ) + tm.assert_series_equal(mi.loc[key[: i + 1]], right) + else: # multi hit + tm.assert_frame_equal(mi.loc[key[: i + 1]], right) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_loc.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_loc.py new file mode 100644 index 0000000000000000000000000000000000000000..722e575bb683e7f99e0e73f7a8c21e6e8381a0f3 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_loc.py @@ -0,0 +1,1139 @@ +import numpy as np +import pytest + +from pandas.errors import ( + IndexingError, + Pandas4Warning, +) + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def frame_random_data_integer_multi_index(): + levels = [[0, 1], [0, 1, 2]] + codes = [[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]] + index = pd.MultiIndex(levels=levels, codes=codes) + return pd.DataFrame(np.random.default_rng(2).standard_normal((6, 2)), index=index) + + +class TestMultiIndexLoc: + @pytest.mark.parametrize("has_ref", [True, False]) + def test_loc_setitem_frame_with_multiindex( + self, multiindex_dataframe_random_data, has_ref + ): + frame = multiindex_dataframe_random_data + if has_ref: + view = frame[:] + frame.loc[("bar", "two"), "B"] = 5 + assert frame.loc[("bar", "two"), "B"] == 5 + + # with integer labels + df = frame.copy() + df.columns = list(range(3)) + if has_ref: + view = df[:] # noqa: F841 + df.loc[("bar", "two"), 1] = 7 + assert df.loc[("bar", "two"), 1] == 7 + + def test_loc_getitem_general(self, any_real_numpy_dtype): + # GH#2817 + dtype = any_real_numpy_dtype + data = { + "amount": {0: 700, 1: 600, 2: 222, 3: 333, 4: 444}, + "col": {0: 3.5, 1: 3.5, 2: 4.0, 3: 4.0, 4: 4.0}, + "num": {0: 12, 1: 11, 2: 12, 3: 12, 4: 12}, + } + df = pd.DataFrame(data) + df = df.astype({"col": dtype, "num": dtype}) + df = df.set_index(keys=["col", "num"]) + key = 4.0, 12 + + tm.assert_frame_equal(df.loc[key], df.iloc[2:]) + + # this is ok + df = df.sort_index() + res = df.loc[key] + + # col has float dtype, result should be float64 Index + col_arr = np.array([4.0] * 3, dtype=dtype) + year_arr = np.array([12] * 3, dtype=dtype) + index = pd.MultiIndex.from_arrays([col_arr, year_arr], names=["col", "num"]) + expected = pd.DataFrame({"amount": [222, 333, 444]}, index=index) + tm.assert_frame_equal(res, expected) + + def test_loc_getitem_multiindex_missing_label_raises(self): + # GH#21593 + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + + with pytest.raises(KeyError, match=r"^2$"): + df.loc[2] + + def test_loc_getitem_list_of_tuples_with_multiindex( + self, multiindex_year_month_day_dataframe_random_data + ): + ser = multiindex_year_month_day_dataframe_random_data["A"] + expected = ser.reindex(ser.index[49:51]) + result = ser.loc[[(2000, 3, 10), (2000, 3, 13)]] + tm.assert_series_equal(result, expected) + + def test_loc_getitem_series(self): + # GH14730 + # passing a series as a key with a MultiIndex + index = pd.MultiIndex.from_product([[1, 2, 3], ["A", "B", "C"]]) + x = pd.Series(index=index, data=range(9), dtype=np.float64) + y = pd.Series([1, 3]) + expected = pd.Series( + data=[0, 1, 2, 6, 7, 8], + index=pd.MultiIndex.from_product([[1, 3], ["A", "B", "C"]]), + dtype=np.float64, + ) + result = x.loc[y] + tm.assert_series_equal(result, expected) + + result = x.loc[[1, 3]] + tm.assert_series_equal(result, expected) + + # GH15424 + y1 = pd.Series([1, 3], index=[1, 2]) + result = x.loc[y1] + tm.assert_series_equal(result, expected) + + empty = pd.Series(data=[], dtype=np.float64) + expected = pd.Series( + [], + index=pd.MultiIndex(levels=index.levels, codes=[[], []]), + dtype=np.float64, + ) + result = x.loc[empty] + tm.assert_series_equal(result, expected) + + def test_loc_getitem_array(self): + # GH15434 + # passing an array as a key with a MultiIndex + index = pd.MultiIndex.from_product([[1, 2, 3], ["A", "B", "C"]]) + x = pd.Series(index=index, data=range(9), dtype=np.float64) + y = np.array([1, 3]) + expected = pd.Series( + data=[0, 1, 2, 6, 7, 8], + index=pd.MultiIndex.from_product([[1, 3], ["A", "B", "C"]]), + dtype=np.float64, + ) + result = x.loc[y] + tm.assert_series_equal(result, expected) + + # empty array: + empty = np.array([]) + expected = pd.Series( + [], + index=pd.MultiIndex(levels=index.levels, codes=[[], []]), + dtype="float64", + ) + result = x.loc[empty] + tm.assert_series_equal(result, expected) + + # 0-dim array (scalar): + scalar = np.int64(1) + expected = pd.Series(data=[0, 1, 2], index=["A", "B", "C"], dtype=np.float64) + result = x.loc[scalar] + tm.assert_series_equal(result, expected) + + def test_loc_multiindex_labels(self): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[["i", "i", "j"], ["A", "A", "B"]], + index=[["i", "i", "j"], ["X", "X", "Y"]], + ) + + # the first 2 rows + expected = df.iloc[[0, 1]].droplevel(0) + result = df.loc["i"] + tm.assert_frame_equal(result, expected) + + # 2nd (last) column + expected = df.iloc[:, [2]].droplevel(0, axis=1) + result = df.loc[:, "j"] + tm.assert_frame_equal(result, expected) + + # bottom right corner + expected = df.iloc[[2], [2]].droplevel(0).droplevel(0, axis=1) + result = df.loc["j"].loc[:, "j"] + tm.assert_frame_equal(result, expected) + + # with a tuple + expected = df.iloc[[0, 1]] + result = df.loc[("i", "X")] + tm.assert_frame_equal(result, expected) + + def test_loc_multiindex_ints(self): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + expected = df.iloc[[0, 1]].droplevel(0) + result = df.loc[4] + tm.assert_frame_equal(result, expected) + + def test_loc_multiindex_missing_label_raises(self): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + + with pytest.raises(KeyError, match=r"^2$"): + df.loc[2] + + @pytest.mark.parametrize("key, pos", [([2, 4], [0, 1]), ([2], []), ([2, 3], [])]) + def test_loc_multiindex_list_missing_label(self, key, pos): + # GH 27148 - lists with missing labels _do_ raise + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + + with pytest.raises(KeyError, match="not in index"): + df.loc[key] + + def test_loc_multiindex_too_many_dims_raises(self): + # GH 14885 + s = pd.Series( + range(8), + index=pd.MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]), + ) + + with pytest.raises(KeyError, match=r"^\('a', 'b'\)$"): + s.loc["a", "b"] + with pytest.raises(KeyError, match=r"^\('a', 'd', 'g'\)$"): + s.loc["a", "d", "g"] + with pytest.raises(IndexingError, match="Too many indexers"): + s.loc["a", "d", "g", "j"] + + def test_loc_multiindex_indexer_none(self): + # GH6788 + # multi-index indexer is None (meaning take all) + attributes = ["Attribute" + str(i) for i in range(1)] + attribute_values = ["Value" + str(i) for i in range(5)] + + index = pd.MultiIndex.from_product([attributes, attribute_values]) + df = 0.1 * np.random.default_rng(2).standard_normal((10, 1 * 5)) + 0.5 + df = pd.DataFrame(df, columns=index) + result = df[attributes] + tm.assert_frame_equal(result, df) + + # GH 7349 + # loc with a multi-index seems to be doing fallback + df = pd.DataFrame( + np.arange(12).reshape(-1, 1), + index=pd.MultiIndex.from_product([[1, 2, 3, 4], [1, 2, 3]]), + ) + + expected = df.loc[([1, 2],), :] + result = df.loc[[1, 2]] + tm.assert_frame_equal(result, expected) + + def test_loc_multiindex_incomplete(self): + # GH 7399 + # incomplete indexers + s = pd.Series( + np.arange(15, dtype="int64"), + pd.MultiIndex.from_product([range(5), ["a", "b", "c"]]), + ) + expected = s.loc[:, "a":"c"] + + result = s.loc[0:4, "a":"c"] + tm.assert_series_equal(result, expected) + + result = s.loc[:4, "a":"c"] + tm.assert_series_equal(result, expected) + + result = s.loc[0:, "a":"c"] + tm.assert_series_equal(result, expected) + + # GH 7400 + # multiindexer getitem with list of indexers skips wrong element + s = pd.Series( + np.arange(15, dtype="int64"), + pd.MultiIndex.from_product([range(5), ["a", "b", "c"]]), + ) + expected = s.iloc[[6, 7, 8, 12, 13, 14]] + result = s.loc[2:4:2, "a":"c"] + tm.assert_series_equal(result, expected) + + def test_get_loc_single_level(self): + single_level = pd.MultiIndex( + levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"] + ) + s = pd.Series( + np.random.default_rng(2).standard_normal(len(single_level)), + index=single_level, + ) + for k in single_level.values: + s[k] + + def test_loc_getitem_int_slice(self): + # GH 3053 + # loc should treat integer slices like label slices + + index = pd.MultiIndex.from_product([[6, 7, 8], ["a", "b"]]) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((6, 6)), index, index + ) + result = df.loc[6:8, :] + expected = df + tm.assert_frame_equal(result, expected) + + index = pd.MultiIndex.from_product([[10, 20, 30], ["a", "b"]]) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((6, 6)), index, index + ) + result = df.loc[20:30, :] + expected = df.iloc[2:] + tm.assert_frame_equal(result, expected) + + # doc examples + result = df.loc[10, :] + expected = df.iloc[0:2] + expected.index = ["a", "b"] + tm.assert_frame_equal(result, expected) + + result = df.loc[:, 10] + expected = df[10] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "indexer_type_1", (list, tuple, set, slice, np.ndarray, pd.Series, pd.Index) + ) + @pytest.mark.parametrize( + "indexer_type_2", (list, tuple, set, slice, np.ndarray, pd.Series, pd.Index) + ) + def test_loc_getitem_nested_indexer(self, indexer_type_1, indexer_type_2): + # GH #19686 + # .loc should work with nested indexers which can be + # any list-like objects (see `is_list_like` (`pandas.api.types`)) or slices + + def convert_nested_indexer(indexer_type, keys): + if indexer_type == np.ndarray: + return np.array(keys) + if indexer_type == slice: + return slice(*keys) + return indexer_type(keys) + + a = [10, 20, 30] + b = [1, 2, 3] + index = pd.MultiIndex.from_product([a, b]) + df = pd.DataFrame( + np.arange(len(index), dtype="int64"), index=index, columns=["Data"] + ) + + keys = ([10, 20], [2, 3]) + types = (indexer_type_1, indexer_type_2) + + # check indexers with all the combinations of nested objects + # of all the valid types + indexer = tuple( + convert_nested_indexer(indexer_type, k) + for indexer_type, k in zip(types, keys, strict=True) + ) + if indexer_type_1 is set or indexer_type_2 is set: + with pytest.raises(TypeError, match="as an indexer is not supported"): + df.loc[indexer, "Data"] + + return + else: + result = df.loc[indexer, "Data"] + expected = pd.Series( + [1, 2, 4, 5], name="Data", index=pd.MultiIndex.from_product(keys) + ) + + tm.assert_series_equal(result, expected) + + def test_multiindex_loc_one_dimensional_tuple(self, frame_or_series): + # GH#37711 + mi = pd.MultiIndex.from_tuples([("a", "A"), ("b", "A")]) + obj = frame_or_series([1, 2], index=mi) + obj.loc[("a",)] = 0 + expected = frame_or_series([0, 2], index=mi) + tm.assert_equal(obj, expected) + + @pytest.mark.parametrize("indexer", [("a",), ("a")]) + def test_multiindex_one_dimensional_tuple_columns(self, indexer): + # GH#37711 + mi = pd.MultiIndex.from_tuples([("a", "A"), ("b", "A")]) + obj = pd.DataFrame([1, 2], index=mi) + obj.loc[indexer, :] = 0 + expected = pd.DataFrame([0, 2], index=mi) + tm.assert_frame_equal(obj, expected) + + @pytest.mark.parametrize( + "indexer, exp_value", [(slice(None), 1.0), ((1, 2), np.nan)] + ) + def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value): + # GH#39147 + mi = pd.MultiIndex.from_tuples([(1, 2), (3, 4)]) + df = pd.DataFrame([[1, 2], [3, 4]], index=mi, columns=["a", "b"]) + df.loc[indexer, ["c", "d"]] = 1.0 + expected = pd.DataFrame( + [[1, 2, 1.0, 1.0], [3, 4, exp_value, exp_value]], + index=mi, + columns=["a", "b", "c", "d"], + ) + tm.assert_frame_equal(df, expected) + + def test_multiindex_setitem_axis_set(self): + # GH#58116 + dates = pd.date_range("2001-01-01", freq="D", periods=2) + ids = ["i1", "i2", "i3"] + index = pd.MultiIndex.from_product([dates, ids], names=["date", "identifier"]) + df = pd.DataFrame(0.0, index=index, columns=["A", "B"]) + df.loc(axis=0)["2001-01-01", ["i1", "i3"]] = None + + expected = pd.DataFrame( + [ + [None, None], + [0.0, 0.0], + [None, None], + [0.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + ], + index=index, + columns=["A", "B"], + ) + + tm.assert_frame_equal(df, expected) + + def test_sorted_multiindex_after_union(self): + # GH#44752 + midx = pd.MultiIndex.from_product( + [pd.date_range("20110101", periods=2), pd.Index(["a", "b"])] + ) + ser1 = pd.Series(1, index=midx) + ser2 = pd.Series(1, index=midx[:2]) + df = pd.concat([ser1, ser2], axis=1) + expected = df.copy() + result = df.loc["2011-01-01":"2011-01-02"] + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame({0: ser1, 1: ser2}) + result = df.loc["2011-01-01":"2011-01-02"] + tm.assert_frame_equal(result, expected) + + df = pd.concat([ser1, ser2.reindex(ser1.index)], axis=1) + result = df.loc["2011-01-01":"2011-01-02"] + tm.assert_frame_equal(result, expected) + + def test_loc_no_second_level_index(self): + # GH#43599 + df = pd.DataFrame( + index=pd.MultiIndex.from_product([list("ab"), list("cd"), list("e")]), + columns=["Val"], + ) + res = df.loc[np.s_[:, "c", :]] + expected = pd.DataFrame( + index=pd.MultiIndex.from_product([list("ab"), list("e")]), columns=["Val"] + ) + tm.assert_frame_equal(res, expected) + + def test_loc_multi_index_key_error(self): + # GH 51892 + df = pd.DataFrame( + { + (1, 2): ["a", "b", "c"], + (1, 3): ["d", "e", "f"], + (2, 2): ["g", "h", "i"], + (2, 4): ["j", "k", "l"], + } + ) + with pytest.raises(KeyError, match=r"(1, 4)"): + df.loc[0, (1, 4)] + + +@pytest.mark.parametrize( + "indexer, pos", + [ + ([], []), # empty ok + (["A"], slice(3)), + (["A", "D"], []), # "D" isn't present -> raise + (["D", "E"], []), # no values found -> raise + (["D"], []), # same, with single item list: GH 27148 + (pd.IndexSlice[:, ["foo"]], slice(2, None, 3)), + (pd.IndexSlice[:, ["foo", "bah"]], slice(2, None, 3)), + ], +) +def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos): + # GH 7866 + # multi-index slicing with missing indexers + idx = pd.MultiIndex.from_product( + [["A", "B", "C"], ["foo", "bar", "baz"]], names=["one", "two"] + ) + ser = pd.Series(np.arange(9, dtype="int64"), index=idx).sort_index() + expected = ser.iloc[pos] + + if expected.size == 0 and indexer != []: + with pytest.raises(KeyError, match=str(indexer)): + ser.loc[indexer] + elif indexer == (slice(None), ["foo", "bah"]): + # "bah" is not in idx.levels[1], raising KeyError enforced in 2.0 + with pytest.raises(KeyError, match="'bah'"): + ser.loc[indexer] + else: + result = ser.loc[indexer] + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("columns_indexer", [([], slice(None)), (["foo"], [])]) +def test_loc_getitem_duplicates_multiindex_empty_indexer(columns_indexer): + # GH 8737 + # empty indexer + multi_index = pd.MultiIndex.from_product((["foo", "bar", "baz"], ["alpha", "beta"])) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 6)), + index=range(5), + columns=multi_index, + ) + df = df.sort_index(level=0, axis=1) + + expected = pd.DataFrame(index=range(5), columns=multi_index.reindex([])[0]) + result = df.loc[:, columns_indexer] + tm.assert_frame_equal(result, expected) + + +def test_loc_getitem_duplicates_multiindex_non_scalar_type_object(): + # regression from < 0.14.0 + # GH 7914 + df = pd.DataFrame( + [[np.mean, np.median], ["mean", "median"]], + columns=pd.MultiIndex.from_tuples([("functs", "mean"), ("functs", "median")]), + index=["function", "name"], + ) + result = df.loc["function", ("functs", "mean")] + expected = np.mean + assert result == expected + + +def test_loc_getitem_unique_key_in_nonunique_multiindex(): + # GH#42102 - unique key in a non-unique MultiIndex should return scalar + mi = pd.MultiIndex.from_tuples([(0, 0), (1, 0), (1, 0)]) + ser = pd.Series(range(3), index=mi) + + # (0, 0) is unique even though the overall index is non-unique + result = ser.loc[(0, 0)] + assert result == 0 + assert not isinstance(result, pd.Series) + + # (1, 0) is duplicated, should still return a Series + result = ser.loc[(1, 0)] + assert isinstance(result, pd.Series) + + # DataFrame column case: unique key in non-unique column MultiIndex + columns = pd.MultiIndex.from_tuples([("A", "x"), ("B", "y"), ("B", "y")]) + df = pd.DataFrame([[1, 2, 3]], columns=columns) + result = df[("A", "x")] + assert isinstance(result, pd.Series) + + +def test_loc_getitem_tuple_plus_slice(): + # GH 671 + df = pd.DataFrame( + { + "a": np.arange(10), + "b": np.arange(10), + "c": np.random.default_rng(2).standard_normal(10), + "d": np.random.default_rng(2).standard_normal(10), + } + ).set_index(["a", "b"]) + expected = df.loc[0, 0] + result = df.loc[(0, 0), :] + tm.assert_series_equal(result, expected) + + +def test_loc_getitem_int(frame_random_data_integer_multi_index): + df = frame_random_data_integer_multi_index + result = df.loc[1] + expected = df[-3:] + expected.index = expected.index.droplevel(0) + tm.assert_frame_equal(result, expected) + + +def test_loc_getitem_int_raises_exception(frame_random_data_integer_multi_index): + df = frame_random_data_integer_multi_index + with pytest.raises(KeyError, match=r"^3$"): + df.loc[3] + + +def test_loc_getitem_lowerdim_corner(multiindex_dataframe_random_data): + df = multiindex_dataframe_random_data + + # test setup - check key not in dataframe + with pytest.raises(KeyError, match=r"^\('bar', 'three'\)$"): + df.loc[("bar", "three"), "B"] + + # in theory should be inserting in a sorted space???? + df.loc[("bar", "three"), "B"] = 0 + expected = 0 + result = df.sort_index().loc[("bar", "three"), "B"] + assert result == expected + + +def test_loc_setitem_single_column_slice(): + # case from https://github.com/pandas-dev/pandas/issues/27841 + df = pd.DataFrame( + "string", + index=list("abcd"), + columns=pd.MultiIndex.from_product([["Main"], ("another", "one")]), + ) + with tm.assert_produces_warning(Pandas4Warning, match="Setting a new column"): + df["labels"] = "a" + df.loc[:, "labels"] = df.index + tm.assert_numpy_array_equal(np.asarray(df["labels"]), np.asarray(df.index)) + + # test with non-object block + df = pd.DataFrame( + np.nan, + index=range(4), + columns=pd.MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]), + ) + expected = df.copy() + df.loc[:, "B"] = np.arange(4) + expected.iloc[:, 2] = np.arange(4) + tm.assert_frame_equal(df, expected) + + +def test_loc_nan_multiindex(using_infer_string): + # GH 5286 + tups = [ + ("Good Things", "C", np.nan), + ("Good Things", "R", np.nan), + ("Bad Things", "C", np.nan), + ("Bad Things", "T", np.nan), + ("Okay Things", "N", "B"), + ("Okay Things", "N", "D"), + ("Okay Things", "B", np.nan), + ("Okay Things", "D", np.nan), + ] + df = pd.DataFrame( + np.ones((8, 4)), + columns=pd.Index(["d1", "d2", "d3", "d4"]), + index=pd.MultiIndex.from_tuples(tups, names=["u1", "u2", "u3"]), + ) + result = df.loc["Good Things"].loc["C"] + expected = pd.DataFrame( + np.ones((1, 4)), + index=pd.Index( + [np.nan], + dtype="object" if not using_infer_string else "str", + name="u3", + ), + columns=pd.Index(["d1", "d2", "d3", "d4"]), + ) + tm.assert_frame_equal(result, expected) + + +def test_loc_period_string_indexing(): + # GH 9892 + a = pd.period_range("2013Q1", "2013Q4", freq="Q") + i = (1111, 2222, 3333) + idx = pd.MultiIndex.from_product((a, i), names=("Period", "CVR")) + df = pd.DataFrame( + index=idx, + columns=( + "OMS", + "OMK", + "RES", + "DRIFT_IND", + "OEVRIG_IND", + "FIN_IND", + "VARE_UD", + "LOEN_UD", + "FIN_UD", + ), + ) + result = df.loc[("2013Q1", 1111), "OMS"] + + alt = df.loc[(a[0], 1111), "OMS"] + assert np.isnan(alt) + + # Because the resolution of the string matches, it is an exact lookup, + # not a slice + assert np.isnan(result) + + alt = df.loc[("2013Q1", 1111), "OMS"] + assert np.isnan(alt) + + +def test_loc_datetime_mask_slicing(): + # GH 16699 + dt_idx = pd.to_datetime(["2017-05-04", "2017-05-05"]) + m_idx = pd.MultiIndex.from_product([dt_idx, dt_idx], names=["Idx1", "Idx2"]) + df = pd.DataFrame( + data=[[1, 2], [3, 4], [5, 6], [7, 6]], index=m_idx, columns=["C1", "C2"] + ) + result = df.loc[(dt_idx[0], (df.index.get_level_values(1) > "2017-05-04")), "C1"] + expected = pd.Series( + [3], + name="C1", + index=pd.MultiIndex.from_tuples( + [(pd.Timestamp("2017-05-04"), pd.Timestamp("2017-05-05"))], + names=["Idx1", "Idx2"], + ), + ) + tm.assert_series_equal(result, expected) + + +def test_loc_datetime_series_tuple_slicing(): + # https://github.com/pandas-dev/pandas/issues/35858 + date = pd.Timestamp("2000") + ser = pd.Series( + 1, + index=pd.MultiIndex.from_tuples([("a", date)], names=["a", "b"]), + name="c", + ) + result = ser.loc[:, [date]] + tm.assert_series_equal(result, ser) + + +def test_loc_with_mi_indexer(): + # https://github.com/pandas-dev/pandas/issues/35351 + df = pd.DataFrame( + data=[["a", 1], ["a", 0], ["b", 1], ["c", 2]], + index=pd.MultiIndex.from_tuples( + [(0, 1), (1, 0), (1, 1), (1, 1)], names=["index", "date"] + ), + columns=["author", "price"], + ) + idx = pd.MultiIndex.from_tuples([(0, 1), (1, 1)], names=["index", "date"]) + result = df.loc[idx, :] + expected = pd.DataFrame( + [["a", 1], ["b", 1], ["c", 2]], + index=pd.MultiIndex.from_tuples( + [(0, 1), (1, 1), (1, 1)], names=["index", "date"] + ), + columns=["author", "price"], + ) + tm.assert_frame_equal(result, expected) + + +def test_loc_mi_with_level1_named_0(): + # GH#37194 + dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") + + ser = pd.Series(range(3), index=dti) + df = ser.to_frame() + df[1] = dti + + df2 = df.set_index(0, append=True) + assert df2.index.names == (None, 0) + df2.index.get_loc(dti[0]) # smoke test + + result = df2.loc[dti[0]] + expected = df2.iloc[[0]].droplevel(None) + tm.assert_frame_equal(result, expected) + + ser2 = df2[1] + assert ser2.index.names == (None, 0) + + result = ser2.loc[dti[0]] + expected = ser2.iloc[[0]].droplevel(None) + tm.assert_series_equal(result, expected) + + +def test_getitem_str_slice(): + # GH#15928 + df = pd.DataFrame( + [ + ["20160525 13:30:00.023", "MSFT", "51.95", "51.95"], + ["20160525 13:30:00.048", "GOOG", "720.50", "720.93"], + ["20160525 13:30:00.076", "AAPL", "98.55", "98.56"], + ["20160525 13:30:00.131", "AAPL", "98.61", "98.62"], + ["20160525 13:30:00.135", "MSFT", "51.92", "51.95"], + ["20160525 13:30:00.135", "AAPL", "98.61", "98.62"], + ], + columns="time,ticker,bid,ask".split(","), + ) + df2 = df.set_index(["ticker", "time"]).sort_index() + + res = df2.loc[("AAPL", slice("2016-05-25 13:30:00")), :].droplevel(0) + expected = df2.loc["AAPL"].loc[slice("2016-05-25 13:30:00"), :] + tm.assert_frame_equal(res, expected) + + +def test_3levels_leading_period_index(): + # GH#24091 + pi = pd.PeriodIndex( + ["20181101 1100", "20181101 1200", "20181102 1300", "20181102 1400"], + name="datetime", + freq="D", + ) + lev2 = ["A", "A", "Z", "W"] + lev3 = ["B", "C", "Q", "F"] + mi = pd.MultiIndex.from_arrays([pi, lev2, lev3]) + + ser = pd.Series(range(4), index=mi, dtype=np.float64) + result = ser.loc[(pi[0], "A", "B")] + assert result == 0.0 + + +class TestKeyErrorsWithMultiIndex: + def test_missing_keys_raises_keyerror(self): + # GH#27420 KeyError, not TypeError + df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=["A", "B", "C"]) + df2 = df.set_index(["A", "B"]) + + with pytest.raises(KeyError, match="6"): + df2.loc[(1, 6)] + + def test_missing_key_raises_keyerror2(self): + # GH#21168 KeyError, not "IndexingError: Too many indexers" + ser = pd.Series(-1, index=pd.MultiIndex.from_product([[0, 1]] * 2)) + + with pytest.raises(KeyError, match=r"\(0, 3\)"): + ser.loc[0, 3] + + def test_missing_key_combination(self): + # GH: 19556 + mi = pd.MultiIndex.from_arrays( + [ + np.array(["a", "a", "b", "b"]), + np.array(["1", "2", "2", "3"]), + np.array(["c", "d", "c", "d"]), + ], + names=["one", "two", "three"], + ) + df = pd.DataFrame(np.random.default_rng(2).random((4, 3)), index=mi) + msg = r"\('b', '1', slice\(None, None, None\)\)" + with pytest.raises(KeyError, match=msg): + df.loc[("b", "1", slice(None)), :] + with pytest.raises(KeyError, match=msg): + df.index.get_locs(("b", "1", slice(None))) + with pytest.raises(KeyError, match=r"\('b', '1'\)"): + df.loc[("b", "1"), :] + + +def test_getitem_loc_commutability(multiindex_year_month_day_dataframe_random_data): + df = multiindex_year_month_day_dataframe_random_data + ser = df["A"] + result = ser[2000, 5] + expected = df.loc[2000, 5]["A"] + tm.assert_series_equal(result, expected) + + +def test_loc_with_nan(): + # GH: 27104 + df = pd.DataFrame( + {"col": [1, 2, 5], "ind1": ["a", "d", np.nan], "ind2": [1, 4, 5]} + ).set_index(["ind1", "ind2"]) + result = df.loc[["a"]] + expected = pd.DataFrame( + {"col": [1]}, + index=pd.MultiIndex.from_tuples([("a", 1)], names=["ind1", "ind2"]), + ) + tm.assert_frame_equal(result, expected) + + result = df.loc["a"] + expected = pd.DataFrame({"col": [1]}, index=pd.Index([1], name="ind2")) + tm.assert_frame_equal(result, expected) + + +def test_getitem_non_found_tuple(): + # GH: 25236 + df = pd.DataFrame([[1, 2, 3, 4]], columns=["a", "b", "c", "d"]).set_index( + ["a", "b", "c"] + ) + with pytest.raises(KeyError, match=r"\(2\.0, 2\.0, 3\.0\)"): + df.loc[(2.0, 2.0, 3.0)] + + +def test_get_loc_datetime_index(): + # GH#24263 + index = pd.date_range("2001-01-01", periods=100) + mi = pd.MultiIndex.from_arrays([index]) + # Check if get_loc matches for Index and MultiIndex + assert mi.get_loc("2001-01") == slice(0, 31, None) + assert index.get_loc("2001-01") == slice(0, 31, None) + + loc = mi[::2].get_loc("2001-01") + expected = index[::2].get_loc("2001-01") + assert loc == expected + + loc = mi.repeat(2).get_loc("2001-01") + expected = index.repeat(2).get_loc("2001-01") + assert loc == expected + + loc = mi.append(mi).get_loc("2001-01") + expected = index.append(index).get_loc("2001-01") + # TODO: standardize return type for MultiIndex.get_loc + tm.assert_numpy_array_equal(loc.nonzero()[0], expected) + + +def test_loc_setitem_indexer_differently_ordered(): + # GH#34603 + mi = pd.MultiIndex.from_product([["a", "b"], [0, 1]]) + df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], index=mi) + + indexer = ("a", [1, 0]) + df.loc[indexer, :] = np.array([[9, 10], [11, 12]]) + expected = pd.DataFrame([[11, 12], [9, 10], [5, 6], [7, 8]], index=mi) + tm.assert_frame_equal(df, expected) + + +def test_loc_getitem_index_differently_ordered_slice_none(): + # GH#31330 + df = pd.DataFrame( + [[1, 2], [3, 4], [5, 6], [7, 8]], + index=[["a", "a", "b", "b"], [1, 2, 1, 2]], + columns=["a", "b"], + ) + result = df.loc[(slice(None), [2, 1]), :] + expected = pd.DataFrame( + [[3, 4], [7, 8], [1, 2], [5, 6]], + index=[["a", "b", "a", "b"], [2, 2, 1, 1]], + columns=["a", "b"], + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("indexer", [[1, 2, 7, 6, 2, 3, 8, 7], [1, 2, 7, 6, 3, 8]]) +def test_loc_getitem_index_differently_ordered_slice_none_duplicates(indexer): + # GH#40978 + df = pd.DataFrame( + [1] * 8, + index=pd.MultiIndex.from_tuples( + [(1, 1), (1, 2), (1, 7), (1, 6), (2, 2), (2, 3), (2, 8), (2, 7)] + ), + columns=["a"], + ) + result = df.loc[(slice(None), indexer), :] + expected = pd.DataFrame( + [1] * 8, + index=[[1, 1, 2, 1, 2, 1, 2, 2], [1, 2, 2, 7, 7, 6, 3, 8]], + columns=["a"], + ) + tm.assert_frame_equal(result, expected) + + result = df.loc[df.index.isin(indexer, level=1), :] + tm.assert_frame_equal(result, df) + + +def test_loc_getitem_drops_levels_for_one_row_dataframe(): + # GH#10521 "x" and "z" are both scalar indexing, so those levels are dropped + mi = pd.MultiIndex.from_arrays([["x"], ["y"], ["z"]], names=["a", "b", "c"]) + df = pd.DataFrame({"d": [0]}, index=mi) + expected = df.droplevel([0, 2]) + result = df.loc["x", :, "z"] + tm.assert_frame_equal(result, expected) + + ser = pd.Series([0], index=mi) + result = ser.loc["x", :, "z"] + expected = pd.Series([0], index=pd.Index(["y"], name="b")) + tm.assert_series_equal(result, expected) + + +def test_mi_columns_loc_list_label_order(): + # GH 10710 + cols = pd.MultiIndex.from_product([["A", "B", "C"], [1, 2]]) + df = pd.DataFrame(np.zeros((5, 6)), columns=cols) + result = df.loc[:, ["B", "A"]] + expected = pd.DataFrame( + np.zeros((5, 4)), + columns=pd.MultiIndex.from_tuples([("B", 1), ("B", 2), ("A", 1), ("A", 2)]), + ) + tm.assert_frame_equal(result, expected) + + +def test_mi_partial_indexing_list_raises(): + # GH 13501 + frame = pd.DataFrame( + np.arange(12).reshape((4, 3)), + index=[["a", "a", "b", "b"], [1, 2, 1, 2]], + columns=[["Ohio", "Ohio", "Colorado"], ["Green", "Red", "Green"]], + ) + frame.index.names = ["key1", "key2"] + frame.columns.names = ["state", "color"] + with pytest.raises(KeyError, match="\\[2\\] not in index"): + frame.loc[["b", 2], "Colorado"] + + +def test_mi_indexing_list_nonexistent_raises(): + # GH 15452 + s = pd.Series(range(4), index=pd.MultiIndex.from_product([[1, 2], ["a", "b"]])) + with pytest.raises(KeyError, match="\\['not' 'found'\\] not in index"): + s.loc[["not", "found"]] + + +def test_mi_add_cell_missing_row_non_unique(): + # GH 16018 + result = pd.DataFrame( + [[1, 2, 5, 6], [3, 4, 7, 8]], + index=["a", "a"], + columns=pd.MultiIndex.from_product([[1, 2], ["A", "B"]]), + ) + result.loc["c"] = -1 + result.loc["c", (1, "A")] = 3 + result.loc["d", (1, "A")] = 3 + expected = pd.DataFrame( + [ + [1, 2.0, 5.0, 6.0], + [3, 4.0, 7.0, 8.0], + [3, -1.0, -1, -1], + [3, np.nan, np.nan, np.nan], + ], + index=["a", "a", "c", "d"], + columns=pd.MultiIndex.from_product([[1, 2], ["A", "B"]]), + ) + tm.assert_frame_equal(result, expected) + + +def test_loc_get_scalar_casting_to_float(using_python_scalars): + # GH#41369 + df = pd.DataFrame( + {"a": 1.0, "b": 2}, + index=pd.MultiIndex.from_arrays([[3], [4]], names=["c", "d"]), + ) + expected_type = int if using_python_scalars else np.int64 + result = df.loc[(3, 4), "b"] + assert result == 2 + assert type(result) is expected_type + result = df.loc[[(3, 4)], "b"].iloc[0] + assert result == 2 + assert type(result) is expected_type + + +def test_loc_empty_single_selector_with_names(): + # GH 19517 + idx = pd.MultiIndex.from_product([["a", "b"], ["A", "B"]], names=[1, 0]) + s2 = pd.Series(index=idx, dtype=np.float64) + result = s2.loc["a"] + expected = pd.Series([np.nan, np.nan], index=pd.Index(["A", "B"], name=0)) + tm.assert_series_equal(result, expected) + + +def test_loc_keyerror_rightmost_key_missing(): + # GH 20951 + + df = pd.DataFrame( + { + "A": [100, 100, 200, 200, 300, 300], + "B": [10, 10, 20, 21, 31, 33], + "C": range(6), + } + ) + df = df.set_index(["A", "B"]) + with pytest.raises(KeyError, match="^1$"): + df.loc[(100, 1)] + + +def test_multindex_series_loc_with_tuple_label(): + # GH#43908 + mi = pd.MultiIndex.from_tuples([(1, 2), (3, (4, 5))]) + ser = pd.Series([1, 2], index=mi) + result = ser.loc[(3, (4, 5))] + assert result == 2 + + +def test_loc_np_datetime64_key_on_object_dt64_level(): + # GH#64689 (revert) + # Verify MultiIndex.loc works with np.datetime64 key on object-dtype level + # holding datetime64 values without the datetime64-to-date conversion. + mi = pd.MultiIndex.from_arrays( + [ + pd.Index( + [np.datetime64("2023-01-01", "s")] * 2, + dtype=object, + ), + ["A", "B"], + ["X", "Y"], + ], + ) + df = pd.DataFrame({"val": [1, 2]}, index=mi) + result = df.loc[(np.datetime64("2023-01-01", "s"), "A")] + expected = pd.DataFrame({"val": [1]}, index=pd.Index(["X"])) + tm.assert_frame_equal(result, expected) + + +def test_loc_multiindex_with_overlapping_interval_single_match(): + # GH#27456 - tuple .loc on MultiIndex with overlapping IntervalIndex + # level returned Series instead of scalar when only one interval matched + idx = pd.MultiIndex.from_arrays( + [ + pd.Index(["label1", "label1", "label2", "label2"]), + pd.IntervalIndex.from_arrays([1, 3, 1, 2], [3, 4, 2, 4]), + ] + ) + ser = pd.Series([1, 2, 3, 4], index=idx, name="Value") + + result = ser.loc[("label1", 1.5)] + expected = ser.loc["label1"].loc[1.5] + assert result == expected == 1 + + +def test_loc_multiindex_with_overlapping_interval_multiple_matches(): + # GH#27456 - tuple .loc on MultiIndex where the scalar falls in + # multiple overlapping intervals for the same outer label; + # the intervals in the level are non-contiguous (get_loc returns + # a boolean array, not a slice) + idx = pd.MultiIndex.from_arrays( + [ + pd.Index(["A", "A", "B", "B"]), + pd.IntervalIndex.from_arrays([1, 0, 0.5, 2], [3, 2, 0.8, 4]), + ] + ) + ser = pd.Series([10, 20, 30, 40], index=idx, name="Value") + + result = ser.loc[("A", 1.5)] + expected = np.array([10, 20], dtype=result.values.dtype) + tm.assert_numpy_array_equal(result.values, expected) + + +def test_loc_multiindex_interval_level_inf_break(): + # GH#46699 - .loc with a tuple/list-of-tuples key on a MultiIndex whose + # inner IntervalIndex level has breaks at +/-inf used to raise ValueError + # from the engine when the scalar fell in the inf-bounded interval. + left = pd.DataFrame( + {"Result": [101, 102, 103]}, + index=pd.IntervalIndex.from_breaks( + [-np.inf, 35, 59, np.inf], closed="left", name="age" + ), + ) + right = pd.DataFrame( + {"Result": [1, 2, 3, 4]}, + index=pd.IntervalIndex.from_breaks( + [-np.inf, 35, 59, 70, np.inf], closed="left", name="age" + ), + ) + mapper = pd.concat([left, right], axis=0, keys=[False, True], names=["children"]) + + # scalar tuple: 99 falls in the [59, inf) interval of the False group + result = mapper.loc[(False, 99)] + tm.assert_series_equal(result, mapper.iloc[2]) + + # list of tuples, one of which falls in the [59, inf) interval + result = mapper.loc[[(False, 45), (False, 99)], :] + tm.assert_frame_equal(result, mapper.iloc[[1, 2]]) + + +@pytest.mark.parametrize("pad", [2, 3]) +def test_loc_scalar_level_key_trailing_null_slices(pad): + # GH#45762 - the key-length guard must discount the trailing null slices + # .loc leaves on the key, or df.loc["a", :, :] stops dropping level 0. + # pad starts at 2: a 2-tuple is split into row and column selectors by .loc, + # so only a deeper key reaches the guard + mi = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]]) + df = pd.DataFrame({"x": range(6), "y": range(6)}, index=mi) + expected = pd.DataFrame({"x": range(3), "y": range(3)}, index=pd.Index([1, 2, 3])) + + result = df.loc[("a",) + (slice(None),) * pad] + tm.assert_frame_equal(result, expected) + + result = df.xs(("a",) + (slice(None),) * pad) + tm.assert_frame_equal(result, expected) + + result = df["x"].loc[("a",) + (slice(None),) * pad] + tm.assert_series_equal(result, expected["x"]) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_multiindex.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_multiindex.py new file mode 100644 index 0000000000000000000000000000000000000000..211ba49a6b9bac2a27e55ece322f8f2308e7862c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_multiindex.py @@ -0,0 +1,322 @@ +import numpy as np +import pytest + +import pandas._libs.index as libindex +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays.boolean import BooleanDtype + + +class TestMultiIndexBasic: + def test_multiindex_perf_warn(self, performance_warning): + df = pd.DataFrame( + { + "jim": [0, 0, 1, 1], + "joe": ["x", "x", "z", "y"], + "jolie": np.random.default_rng(2).random(4), + } + ).set_index(["jim", "joe"]) + + # Full-length key uses the engine directly; no PerformanceWarning + df.loc[(1, "z")] + + # Partial key still goes through lexsort path + df = df.iloc[[2, 1, 3, 0]] + msg = "indexing past lexsort depth may impact performance" + with tm.assert_produces_warning(performance_warning, match=msg): + df.loc[(0,)] + + @pytest.mark.parametrize("offset", [-5, 5]) + def test_indexing_over_hashtable_size_cutoff(self, monkeypatch, offset): + size_cutoff = 20 + n = size_cutoff + offset + + with monkeypatch.context(): + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) + s = pd.Series( + np.arange(n), pd.MultiIndex.from_arrays((["a"] * n, np.arange(n))) + ) + + # hai it works! + assert s[("a", 5)] == 5 + assert s[("a", 6)] == 6 + assert s[("a", 7)] == 7 + + def test_multi_nan_indexing(self): + # GH 3588 + df = pd.DataFrame( + { + "a": ["R1", "R2", np.nan, "R4"], + "b": ["C1", "C2", "C3", "C4"], + "c": [10, 15, np.nan, 20], + } + ) + result = df.set_index(["a", "b"], drop=False) + expected = pd.DataFrame( + { + "a": ["R1", "R2", np.nan, "R4"], + "b": ["C1", "C2", "C3", "C4"], + "c": [10, 15, np.nan, 20], + }, + index=[ + pd.Index(["R1", "R2", np.nan, "R4"], name="a"), + pd.Index(["C1", "C2", "C3", "C4"], name="b"), + ], + ) + tm.assert_frame_equal(result, expected) + + def test_exclusive_nat_column_indexing(self): + # GH 38025 + # test multi indexing when one column exclusively contains NaT values + df = pd.DataFrame( + { + "a": [pd.NaT, pd.NaT, pd.NaT, pd.NaT], + "b": ["C1", "C2", "C3", "C4"], + "c": [10, 15, np.nan, 20], + } + ) + df = df.set_index(["a", "b"]) + expected = pd.DataFrame( + { + "c": [10, 15, np.nan, 20], + }, + index=[ + pd.Index([pd.NaT, pd.NaT, pd.NaT, pd.NaT], name="a"), + pd.Index(["C1", "C2", "C3", "C4"], name="b"), + ], + ) + tm.assert_frame_equal(df, expected) + + def test_nested_tuples_duplicates(self): + # GH#30892 + + dti = pd.to_datetime(["20190101", "20190101", "20190102"]) + idx = pd.Index(["a", "a", "c"]) + mi = pd.MultiIndex.from_arrays([dti, idx], names=["index1", "index2"]) + + df = pd.DataFrame({"c1": [1, 2, 3], "c2": [np.nan, np.nan, np.nan]}, index=mi) + + expected = pd.DataFrame({"c1": df["c1"], "c2": [1.0, 1.0, np.nan]}, index=mi) + + df2 = df.copy(deep=True) + df2.loc[(dti[0], "a"), "c2"] = 1.0 + tm.assert_frame_equal(df2, expected) + + df3 = df.copy(deep=True) + df3.loc[[(dti[0], "a")], "c2"] = 1.0 + tm.assert_frame_equal(df3, expected) + + def test_multiindex_with_datatime_level_preserves_freq(self): + # https://github.com/pandas-dev/pandas/issues/35563 + idx = pd.Index(range(2), name="A") + dti = pd.date_range("2020-01-01", periods=7, freq="D", name="B") + mi = pd.MultiIndex.from_product([idx, dti]) + df = pd.DataFrame(np.random.default_rng(2).standard_normal((14, 2)), index=mi) + result = df.loc[0].index + tm.assert_index_equal(result, dti) + assert result.freq == dti.freq + + def test_multiindex_complex(self): + # GH#42145 + complex_data = [1 + 2j, 4 - 3j, 10 - 1j] + non_complex_data = [3, 4, 5] + result = pd.DataFrame( + { + "x": complex_data, + "y": non_complex_data, + "z": non_complex_data, + } + ) + result = result.set_index(["x", "y"]) + expected = pd.DataFrame( + {"z": non_complex_data}, + index=pd.MultiIndex.from_arrays( + [complex_data, non_complex_data], + names=("x", "y"), + ), + ) + tm.assert_frame_equal(result, expected) + + def test_rename_multiindex_with_duplicates(self): + # GH 38015 + mi = pd.MultiIndex.from_tuples([("A", "cat"), ("B", "cat"), ("B", "cat")]) + df = pd.DataFrame(index=mi) + df = df.rename(index={"A": "Apple"}, level=0) + + mi2 = pd.MultiIndex.from_tuples([("Apple", "cat"), ("B", "cat"), ("B", "cat")]) + expected = pd.DataFrame(index=mi2) + tm.assert_frame_equal(df, expected) + + def test_series_align_multiindex_with_nan_overlap_only(self): + # GH 38439 + mi1 = pd.MultiIndex.from_arrays([[81.0, np.nan], [np.nan, np.nan]]) + mi2 = pd.MultiIndex.from_arrays([[np.nan, 82.0], [np.nan, np.nan]]) + ser1 = pd.Series([1, 2], index=mi1) + ser2 = pd.Series([1, 2], index=mi2) + result1, result2 = ser1.align(ser2) + + mi = pd.MultiIndex.from_arrays([[81.0, 82.0, np.nan], [np.nan, np.nan, np.nan]]) + expected1 = pd.Series([1.0, np.nan, 2.0], index=mi) + expected2 = pd.Series([np.nan, 2.0, 1.0], index=mi) + + tm.assert_series_equal(result1, expected1) + tm.assert_series_equal(result2, expected2) + + def test_series_align_multiindex_with_nan(self): + # GH 38439 + mi1 = pd.MultiIndex.from_arrays([[81.0, np.nan], [np.nan, np.nan]]) + mi2 = pd.MultiIndex.from_arrays([[np.nan, 81.0], [np.nan, np.nan]]) + ser1 = pd.Series([1, 2], index=mi1) + ser2 = pd.Series([1, 2], index=mi2) + result1, result2 = ser1.align(ser2) + + mi = pd.MultiIndex.from_arrays([[81.0, np.nan], [np.nan, np.nan]]) + expected1 = pd.Series([1, 2], index=mi) + expected2 = pd.Series([2, 1], index=mi) + + tm.assert_series_equal(result1, expected1) + tm.assert_series_equal(result2, expected2) + + def test_nunique_smoke(self): + # GH 34019 + n = pd.DataFrame([[1, 2], [1, 2]]).set_index([0, 1]).index.nunique() + assert n == 1 + + def test_multiindex_repeated_keys(self): + # GH19414 + tm.assert_series_equal( + pd.Series([1, 2], pd.MultiIndex.from_arrays([["a", "b"]])).loc[ + ["a", "a", "b", "b"] + ], + pd.Series([1, 1, 2, 2], pd.MultiIndex.from_arrays([["a", "a", "b", "b"]])), + ) + + def test_multiindex_with_na_missing_key(self): + # GH46173 + df = pd.DataFrame.from_dict( + { + ("foo",): [1, 2, 3], + ("bar",): [5, 6, 7], + (None,): [8, 9, 0], + } + ) + with pytest.raises(KeyError, match="missing_key"): + df[[("missing_key",)]] + + def test_multiindex_dtype_preservation(self): + # GH51261 + columns = pd.MultiIndex.from_tuples([("A", "B")], names=["lvl1", "lvl2"]) + df = pd.DataFrame(["value"], columns=columns).astype("category") + df_no_multiindex = df["A"] + assert isinstance(df_no_multiindex["B"].dtype, pd.CategoricalDtype) + + # geopandas 1763 analogue + df = pd.DataFrame( + [[1, 0], [0, 1]], + columns=[ + ["foo", "foo"], + ["location", "location"], + ["x", "y"], + ], + ) + with tm.assert_produces_warning(Pandas4Warning, match="Setting a new column"): + df = df.assign(bools=pd.Series([True, False], dtype="boolean")) + assert isinstance(df["bools"].dtype, BooleanDtype) + + def test_multiindex_from_tuples_with_nan(self): + # GH#23578 + result = pd.MultiIndex.from_tuples([("a", "b", "c"), np.nan, ("d", "", "")]) + expected = pd.MultiIndex.from_tuples( + [("a", "b", "c"), (np.nan, np.nan, np.nan), ("d", "", "")] + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("operation", ["div", "mul", "add", "sub"]) + def test_groupyby_rename_categories_operation_with_multiindex(self, operation): + # GH#51500 + data = pd.DataFrame( + [["C", "B", "B"], ["B", "A", "A"], ["B", "A", "B"]], columns=["0", "1", "2"] + ) + data["0"] = data["0"].astype("category") + data["0"] = data["0"].cat.rename_categories({"C": "B", "B": "C"}) + + a = data.groupby(by=["0", "1"])["2"].value_counts() + b = data.groupby(by=["0", "1"]).size() + + result = getattr(a, operation)(b) + expected = getattr(a, operation)(b.sort_index(ascending=False)) + + tm.assert_series_equal(result, expected) + + def test_multiindex_assign_aligns_as_implicit_tuple(self): + # GH 61841 + cols = pd.MultiIndex.from_tuples([("A", "B")]) + df1 = pd.DataFrame([[i] for i in range(3)], columns=cols) + df2 = df1.copy() + df3 = df1.copy() + s1 = df1["A"].rolling(2).mean() + s2 = s1.copy() + s3 = s1.copy() + + msg = "Setting a new column" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df2["C"] = s2 + df3[("C", "")] = s3 + tm.assert_frame_equal(df2, df3) + + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df1["C"] = s1 + tm.assert_frame_equal(df1, df2) + tm.assert_frame_equal(df1, df3) + + # setting again, now an existing column, does not warn + with tm.assert_produces_warning(None): + df1["C"] = s1 + tm.assert_frame_equal(df1, df2) + tm.assert_frame_equal(df1, df3) + + df1["C"] = s1 * 2 + tm.assert_series_equal(df1["C"], df2["C"] * 2) + + def test_multiindex_assign_alignment_with_non_string_dtype(self): + # GH 62518 + columns = pd.MultiIndex.from_arrays( + [["a", "a", "z", "z"], pd.Categorical([1, 2, 1, 2])] + ) + + meta = pd.DataFrame(columns=columns, dtype=object) + meta["z"] = meta["z"].astype("int64") + + result = pd.DataFrame( + data={ + ("a", 1): pd.Series([], dtype=object), + ("a", 2): pd.Series([], dtype=object), + ("z", 1): pd.Series([], dtype="int64"), + ("z", 2): pd.Series([], dtype="int64"), + }, + columns=columns, + ) + + tm.assert_frame_equal(meta, result) + + def test_multiindex_assign_alignment_with_object_dtype(self): + # https://github.com/pandas-dev/pandas/issues/65118 + # second level of the multiindex is object dtype, and the value of + # that level is 0 for the single column we are setting + + columns = pd.MultiIndex.from_tuples( + [("A", "M"), ("A", 0), ("B", 1), ("B", 2), ("C", 0)] + ) + df = pd.DataFrame(np.arange(20, dtype=float).reshape(4, 5), columns=columns) + + df["A"] = df["A"] / 100 + df["B"] = df["B"] / 100 + # this case specifically was the buggy one + df["C"] = df["C"] / 100 + + expected = pd.DataFrame( + np.arange(20, dtype=float).reshape(4, 5) / 100, columns=columns + ) + tm.assert_frame_equal(df, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_partial.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_partial.py new file mode 100644 index 0000000000000000000000000000000000000000..78a4da51294363771409930d1912ed3e9197a5e9 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_partial.py @@ -0,0 +1,250 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestMultiIndexPartial: + def test_getitem_partial_int(self): + # GH 12416 + # with single item + l1 = [10, 20] + l2 = ["a", "b"] + df = pd.DataFrame(index=range(2), columns=pd.MultiIndex.from_product([l1, l2])) + expected = pd.DataFrame(index=range(2), columns=l2) + result = df[20] + tm.assert_frame_equal(result, expected) + + # with list + expected = pd.DataFrame( + index=range(2), columns=pd.MultiIndex.from_product([l1[1:], l2]) + ) + result = df[[20]] + tm.assert_frame_equal(result, expected) + + # missing item: + with pytest.raises(KeyError, match="1"): + df[1] + with pytest.raises(KeyError, match=r"'\[1\] not in index'"): + df[[1]] + + def test_series_slice_partial(self): + pass + + def test_xs_partial( + self, + multiindex_dataframe_random_data, + multiindex_year_month_day_dataframe_random_data, + ): + frame = multiindex_dataframe_random_data + ymd = multiindex_year_month_day_dataframe_random_data + result = frame.xs("foo") + result2 = frame.loc["foo"] + expected = frame.T["foo"].T + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, result2) + + result = ymd.xs((2000, 4)) + expected = ymd.loc[2000, 4] + tm.assert_frame_equal(result, expected) + + # ex from #1796 + index = pd.MultiIndex( + levels=[["foo", "bar"], ["one", "two"], [-1, 1]], + codes=[ + [0, 0, 0, 0, 1, 1, 1, 1], + [0, 0, 1, 1, 0, 0, 1, 1], + [0, 1, 0, 1, 0, 1, 0, 1], + ], + ) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((8, 4)), + index=index, + columns=list("abcd"), + ) + + result = df.xs(("foo", "one")) + expected = df.loc["foo", "one"] + tm.assert_frame_equal(result, expected) + + def test_getitem_partial(self, multiindex_year_month_day_dataframe_random_data): + ymd = multiindex_year_month_day_dataframe_random_data + ymd = ymd.T + result = ymd[2000, 2] + + expected = ymd.reindex(columns=ymd.columns[ymd.columns.codes[1] == 1]) + expected.columns = expected.columns.droplevel(0).droplevel(0) + tm.assert_frame_equal(result, expected) + + def test_fancy_slice_partial( + self, + multiindex_dataframe_random_data, + multiindex_year_month_day_dataframe_random_data, + ): + frame = multiindex_dataframe_random_data + result = frame.loc["bar":"baz"] + expected = frame[3:7] + tm.assert_frame_equal(result, expected) + + ymd = multiindex_year_month_day_dataframe_random_data + result = ymd.loc[(2000, 2) : (2000, 4)] + lev = ymd.index.codes[1] + expected = ymd[(lev >= 1) & (lev <= 3)] + tm.assert_frame_equal(result, expected) + + def test_getitem_partial_column_select(self): + idx = pd.MultiIndex( + codes=[[0, 0, 0], [0, 1, 1], [1, 0, 1]], + levels=[["a", "b"], ["x", "y"], ["p", "q"]], + ) + df = pd.DataFrame(np.random.default_rng(2).random((3, 2)), index=idx) + + result = df.loc[("a", "y"), :] + expected = df.loc[("a", "y")] + tm.assert_frame_equal(result, expected) + + result = df.loc[("a", "y"), [1, 0]] + expected = df.loc[("a", "y")][[1, 0]] + tm.assert_frame_equal(result, expected) + + with pytest.raises(KeyError, match=r"\('a', 'foo'\)"): + df.loc[("a", "foo"), :] + + def test_partial_set( + self, + multiindex_year_month_day_dataframe_random_data, + ): + # GH #397 + ymd = multiindex_year_month_day_dataframe_random_data + df = ymd.copy() + exp = ymd.copy() + df.loc[2000, 4] = 0 + exp.iloc[65:85] = 0 + tm.assert_frame_equal(df, exp) + + with tm.raises_chained_assignment_error(): + df["A"].loc[2000, 4] = 1 + df.loc[(2000, 4), "A"] = 1 + exp.iloc[65:85, 0] = 1 + tm.assert_frame_equal(df, exp) + + df.loc[2000] = 5 + exp.iloc[:100] = 5 + tm.assert_frame_equal(df, exp) + + # this works...for now + with tm.raises_chained_assignment_error(): + df["A"].iloc[14] = 5 + assert df["A"].iloc[14] == exp["A"].iloc[14] + + @pytest.mark.parametrize("dtype", [int, float]) + def test_getitem_intkey_leading_level( + self, multiindex_year_month_day_dataframe_random_data, dtype + ): + # GH#33355 dont fall-back to positional when leading level is int + ymd = multiindex_year_month_day_dataframe_random_data + levels = ymd.index.levels + ymd.index = ymd.index.set_levels([levels[0].astype(dtype), *levels[1:]]) + ser = ymd["A"] + mi = ser.index + assert isinstance(mi, pd.MultiIndex) + if dtype is int: + assert mi.levels[0].dtype == np.dtype(int) + else: + assert mi.levels[0].dtype == np.float64 + + assert 14 not in mi.levels[0] + assert not mi.levels[0]._should_fallback_to_positional + assert not mi._should_fallback_to_positional + + with pytest.raises(KeyError, match="14"): + ser[14] + + # --------------------------------------------------------------------- + + def test_setitem_multiple_partial(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + expected = frame.copy() + result = frame.copy() + result.loc[["foo", "bar"]] = 0 + expected.loc["foo"] = 0 + expected.loc["bar"] = 0 + tm.assert_frame_equal(result, expected) + + expected = frame.copy() + result = frame.copy() + result.loc["foo":"bar"] = 0 + expected.loc["foo"] = 0 + expected.loc["bar"] = 0 + tm.assert_frame_equal(result, expected) + + expected = frame["A"].copy() + result = frame["A"].copy() + result.loc[["foo", "bar"]] = 0 + expected.loc["foo"] = 0 + expected.loc["bar"] = 0 + tm.assert_series_equal(result, expected) + + expected = frame["A"].copy() + result = frame["A"].copy() + result.loc["foo":"bar"] = 0 + expected.loc["foo"] = 0 + expected.loc["bar"] = 0 + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "indexer, exp_idx, exp_values", + [ + ( + slice("2019-2", None), + pd.DatetimeIndex(["2019-02-01"], dtype="M8[ns]"), + [2, 3], + ), + ( + slice(None, "2019-2"), + pd.date_range("2019", periods=2, freq="MS", unit="ns"), + [0, 1, 2, 3], + ), + ], + ) + def test_partial_getitem_loc_datetime(self, indexer, exp_idx, exp_values): + # GH: 25165 + date_idx = pd.date_range("2019", periods=2, freq="MS", unit="ns") + df = pd.DataFrame( + list(range(4)), + index=pd.MultiIndex.from_product([date_idx, [0, 1]], names=["x", "y"]), + ) + expected = pd.DataFrame( + exp_values, + index=pd.MultiIndex.from_product([exp_idx, [0, 1]], names=["x", "y"]), + ) + result = df[indexer] + tm.assert_frame_equal(result, expected) + result = df.loc[indexer] + tm.assert_frame_equal(result, expected) + + result = df.loc(axis=0)[indexer] + tm.assert_frame_equal(result, expected) + + result = df.loc[indexer, :] + tm.assert_frame_equal(result, expected) + + df2 = df.swaplevel(0, 1).sort_index() + expected = expected.swaplevel(0, 1).sort_index() + + result = df2.loc[:, indexer, :] + tm.assert_frame_equal(result, expected) + + +def test_loc_getitem_partial_both_axis(): + # gh-12660 + iterables = [["a", "b"], [2, 1]] + columns = pd.MultiIndex.from_product(iterables, names=["col1", "col2"]) + rows = pd.MultiIndex.from_product(iterables, names=["row1", "row2"]) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), index=rows, columns=columns + ) + expected = df.iloc[:2, 2:].droplevel("row1").droplevel("col1", axis=1) + result = df.loc["a", "b"] + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_setitem.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_setitem.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1ef8c1bb17e92b3fcfe99eb268c477b87f526d --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_setitem.py @@ -0,0 +1,705 @@ +import re + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +def assert_equal(a, b): + assert a == b + + +class TestMultiIndexSetItem: + def check(self, target, indexers, value, compare_fn=assert_equal, expected=None): + target.loc[indexers] = value + result = target.loc[indexers] + if expected is None: + expected = value + compare_fn(result, expected) + + def test_setitem_multiindex(self): + # GH#7190 + cols = ["A", "w", "l", "a", "x", "X", "d", "profit"] + index = pd.MultiIndex.from_product( + [np.arange(0, 100), np.arange(0, 80)], names=["time", "firm"] + ) + t, n = 0, 2 + + df = pd.DataFrame( + np.nan, + columns=cols, + index=index, + ) + self.check(target=df, indexers=((t, n), "X"), value=0) + + df = pd.DataFrame(-999, columns=cols, index=index) + self.check(target=df, indexers=((t, n), "X"), value=1) + + df = pd.DataFrame(columns=cols, index=index) + self.check(target=df, indexers=((t, n), "X"), value=2) + + # gh-7218: assigning with 0-dim arrays + df = pd.DataFrame(-999, columns=cols, index=index) + self.check( + target=df, + indexers=((t, n), "X"), + value=np.array(3), + expected=3, + ) + + def test_setitem_multiindex2(self): + # GH#5206 + df = pd.DataFrame( + np.arange(25).reshape(5, 5), columns="A,B,C,D,E".split(","), dtype=float + ) + df["F"] = 99 + row_selection = df["A"] % 2 == 0 + col_selection = ["B", "C"] + df.loc[row_selection, col_selection] = df["F"] + output = pd.DataFrame(99.0, index=[0, 2, 4], columns=["B", "C"]) + tm.assert_frame_equal(df.loc[row_selection, col_selection], output) + self.check( + target=df, + indexers=(row_selection, col_selection), + value=df["F"], + compare_fn=tm.assert_frame_equal, + expected=output, + ) + + def test_setitem_multiindex3(self): + # GH#11372 + idx = pd.MultiIndex.from_product( + [["A", "B", "C"], pd.date_range("2015-01-01", "2015-04-01", freq="MS")] + ) + cols = pd.MultiIndex.from_product( + [["foo", "bar"], pd.date_range("2016-01-01", "2016-02-01", freq="MS")] + ) + + df = pd.DataFrame( + np.random.default_rng(2).random((12, 4)), index=idx, columns=cols + ) + + subidx = pd.MultiIndex.from_arrays( + [["A", "A"], pd.date_range("2015-01-01", "2015-02-01", freq="MS")] + ) + subcols = pd.MultiIndex.from_arrays( + [["foo", "foo"], pd.date_range("2016-01-01", "2016-02-01", freq="MS")] + ) + + vals = pd.DataFrame( + np.random.default_rng(2).random((2, 2)), index=subidx, columns=subcols + ) + self.check( + target=df, + indexers=(subidx, subcols), + value=vals, + compare_fn=tm.assert_frame_equal, + ) + # set all columns + vals = pd.DataFrame( + np.random.default_rng(2).random((2, 4)), index=subidx, columns=cols + ) + self.check( + target=df, + indexers=(subidx, slice(None, None, None)), + value=vals, + compare_fn=tm.assert_frame_equal, + ) + # identity + copy = df.copy() + self.check( + target=df, + indexers=(df.index, df.columns), + value=df, + compare_fn=tm.assert_frame_equal, + expected=copy, + ) + + def test_multiindex_setitem(self): + # GH 3738 + # setting with a multi-index right hand side + arrays = [ + np.array(["bar", "bar", "baz", "qux", "qux", "bar"]), + np.array(["one", "two", "one", "one", "two", "one"]), + np.arange(0, 6, 1), + ] + + df_orig = pd.DataFrame( + np.random.default_rng(2).standard_normal((6, 3)), + index=arrays, + columns=["A", "B", "C"], + ).sort_index() + + expected = df_orig.loc[["bar"]] * 2 + df = df_orig.copy() + df.loc[["bar"]] *= 2 + tm.assert_frame_equal(df.loc[["bar"]], expected) + + # raise because these have differing levels + msg = "cannot align on a multi-index with out specifying the join levels" + with pytest.raises(TypeError, match=msg): + df.loc["bar"] *= 2 + + def test_multiindex_setitem2(self): + # from SO + # https://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation + df_orig = pd.DataFrame.from_dict( + { + "price": { + ("DE", "Coal", "Stock"): 2, + ("DE", "Gas", "Stock"): 4, + ("DE", "Elec", "Demand"): 1, + ("FR", "Gas", "Stock"): 5, + ("FR", "Solar", "SupIm"): 0, + ("FR", "Wind", "SupIm"): 0, + } + } + ) + df_orig.index = pd.MultiIndex.from_tuples( + df_orig.index, names=["Sit", "Com", "Type"] + ) + + expected = df_orig.copy() + expected.iloc[[0, 1, 3]] *= 2 + + idx = pd.IndexSlice + df = df_orig.copy() + df.loc[idx[:, :, "Stock"], :] *= 2 + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc[idx[:, :, "Stock"], "price"] *= 2 + tm.assert_frame_equal(df, expected) + + def test_multiindex_assignment(self): + # GH3777 part 2 + + # mixed dtype + df = pd.DataFrame( + np.random.default_rng(2).integers(5, 10, size=9).reshape(3, 3), + columns=list("abc"), + index=[[4, 4, 8], [8, 10, 12]], + ) + df["d"] = np.nan + arr = np.array([0.0, 1.0]) + + df.loc[4, "d"] = arr + tm.assert_series_equal(df.loc[4, "d"], pd.Series(arr, index=[8, 10], name="d")) + + def test_multiindex_assignment_single_dtype(self): + # GH3777 part 2b + # single dtype + arr = np.array([0.0, 1.0]) + + df = pd.DataFrame( + np.random.default_rng(2).integers(5, 10, size=9).reshape(3, 3), + columns=list("abc"), + index=[[4, 4, 8], [8, 10, 12]], + dtype=np.int64, + ) + + # arr can be losslessly cast to int, so this setitem is inplace + df.loc[4, "c"] = arr + exp = pd.Series(arr, index=[8, 10], name="c", dtype="int64") + result = df.loc[4, "c"] + tm.assert_series_equal(result, exp) + + # arr + 0.5 cannot be cast losslessly to int, so we upcast + with pytest.raises(TypeError, match="Invalid value"): + df.loc[4, "c"] = arr + 0.5 + # Upcast so that we can add .5 + df = df.astype({"c": "float64"}) + df.loc[4, "c"] = arr + 0.5 + + # scalar ok + df.loc[4, "c"] = 10 + exp = pd.Series(10, index=[8, 10], name="c", dtype="float64") + tm.assert_series_equal(df.loc[4, "c"], exp) + + # invalid assignments + msg = "Must have equal len keys and value when setting with an iterable" + with pytest.raises(ValueError, match=msg): + df.loc[4, "c"] = [0, 1, 2, 3] + + with pytest.raises(ValueError, match=msg): + df.loc[4, "c"] = [0] + + # But with a length-1 listlike column indexer this behaves like + # `df.loc[4, "c"] = 0 + df.loc[4, ["c"]] = [0] + assert (df.loc[4, "c"] == 0).all() + + def test_groupby_example(self): + # groupby example + NUM_ROWS = 100 + NUM_COLS = 10 + col_names = ["A" + num for num in map(str, np.arange(NUM_COLS).tolist())] + index_cols = col_names[:5] + + df = pd.DataFrame( + np.random.default_rng(2).integers(5, size=(NUM_ROWS, NUM_COLS)), + dtype=np.int64, + columns=col_names, + ) + df = df.set_index(index_cols).sort_index() + grp = df.groupby(level=index_cols[:4]) + df["new_col"] = np.nan + + # we are actually operating on a copy here + # but in this case, that's ok + for name, df2 in grp: + new_vals = np.arange(df2.shape[0]) + df.loc[name, "new_col"] = new_vals + + def test_series_setitem(self, multiindex_year_month_day_dataframe_random_data): + ymd = multiindex_year_month_day_dataframe_random_data + s = ymd["A"] + + s[2000, 3] = np.nan + assert pd.isna(s.values[42:65]).all() + assert pd.notna(s.values[:42]).all() + assert pd.notna(s.values[65:]).all() + + s[2000, 3, 10] = np.nan + assert pd.isna(s.iloc[49]) + + with pytest.raises(KeyError, match="49"): + # GH#33355 dont fall-back to positional when leading level is int + s[49] + + def test_frame_getitem_setitem_boolean(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + df = frame.T.copy() + values = df.values.copy() + + result = df[df > 0] + expected = df.where(df > 0) + tm.assert_frame_equal(result, expected) + + df[df > 0] = 5 + values[values > 0] = 5 + tm.assert_almost_equal(df.values, values) + + df[df == 5] = 0 + values[values == 5] = 0 + tm.assert_almost_equal(df.values, values) + + # a df that needs alignment first + df[df[:-1] < 0] = 2 + np.putmask(values[:-1], values[:-1] < 0, 2) + tm.assert_almost_equal(df.values, values) + + with pytest.raises(TypeError, match="boolean values only"): + df[df * 0] = 2 + + def test_frame_getitem_setitem_multislice(self): + levels = [["t1", "t2"], ["a", "b", "c"]] + codes = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]] + midx = pd.MultiIndex(codes=codes, levels=levels, names=[None, "id"]) + df = pd.DataFrame({"value": [1, 2, 3, 7, 8]}, index=midx) + + result = df.loc[:, "value"] + tm.assert_series_equal(df["value"], result) + + result = df.loc[df.index[1:3], "value"] + tm.assert_series_equal(df["value"][1:3], result) + + result = df.loc[:, :] + tm.assert_frame_equal(df, result) + + result = df + df.loc[:, "value"] = 10 + result["value"] = 10 + tm.assert_frame_equal(df, result) + + df.loc[:, :] = 10 + tm.assert_frame_equal(df, result) + + def test_frame_setitem_multi_column(self): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=[["a", "a", "b", "b"], [0, 1, 0, 1]], + ) + + cp = df.copy() + cp["a"] = cp["b"] + tm.assert_frame_equal(cp["a"], cp["b"]) + + # set with ndarray + cp = df.copy() + cp["a"] = cp["b"].values + tm.assert_frame_equal(cp["a"], cp["b"]) + + def test_frame_setitem_multi_column2(self): + # --------------------------------------- + # GH#1803 + columns = pd.MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]) + df = pd.DataFrame(index=[1, 3, 5], columns=columns) + + # Works, but adds a column instead of updating the two existing ones + df["A"] = 0.0 # Doesn't work + assert (df["A"].values == 0).all() + + # it broadcasts + df["B", "1"] = [1, 2, 3] + df["A"] = df["B", "1"] + + sliced_a1 = df["A", "1"] + sliced_a2 = df["A", "2"] + sliced_b1 = df["B", "1"] + tm.assert_series_equal(sliced_a1, sliced_b1, check_names=False) + tm.assert_series_equal(sliced_a2, sliced_b1, check_names=False) + assert sliced_a1.name == ("A", "1") + assert sliced_a2.name == ("A", "2") + assert sliced_b1.name == ("B", "1") + + def test_loc_getitem_tuple_plus_columns( + self, multiindex_year_month_day_dataframe_random_data + ): + # GH #1013 + ymd = multiindex_year_month_day_dataframe_random_data + df = ymd[:5] + + result = df.loc[(2000, 1, 6), ["A", "B", "C"]] + expected = df.loc[2000, 1, 6][["A", "B", "C"]] + tm.assert_series_equal(result, expected) + + def test_loc_getitem_setitem_slice_integers(self, frame_or_series): + index = pd.MultiIndex( + levels=[[0, 1, 2], [0, 2]], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]] + ) + + obj = pd.DataFrame( + np.random.default_rng(2).standard_normal((len(index), 4)), + index=index, + columns=["a", "b", "c", "d"], + ) + obj = tm.get_obj(obj, frame_or_series) + + res = obj.loc[1:2] + exp = obj.reindex(obj.index[2:]) + tm.assert_equal(res, exp) + + obj.loc[1:2] = 7 + assert (obj.loc[1:2] == 7).values.all() + + def test_setitem_change_dtype(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + dft = frame.T + s = dft["foo", "two"] + dft["foo", "two"] = s > s.median() + tm.assert_series_equal(dft["foo", "two"], s > s.median()) + # assert isinstance(dft._data.blocks[1].items, MultiIndex) + + reindexed = dft.reindex(columns=[("foo", "two")]) + tm.assert_series_equal(reindexed["foo", "two"], s > s.median()) + + def test_set_column_scalar_with_loc(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + subset = frame.index[[1, 4, 5]] + + frame.loc[subset] = 99 + assert (frame.loc[subset].values == 99).all() + + frame_original = frame.copy() + col = frame["B"] + col[subset] = 97 + # chained setitem doesn't work with CoW + tm.assert_frame_equal(frame, frame_original) + + def test_nonunique_assignment_1750(self): + df = pd.DataFrame( + [[1, 1, "x", "X"], [1, 1, "y", "Y"], [1, 2, "z", "Z"]], columns=list("ABCD") + ) + + df = df.set_index(["A", "B"]) + mi = pd.MultiIndex.from_tuples([(1, 1)]) + + df.loc[mi, "C"] = "_" + + assert (df.xs((1, 1))["C"] == "_").all() + + def test_astype_assignment_with_dups(self): + # GH 4686 + # assignment with dups that has a dtype change + cols = pd.MultiIndex.from_tuples([("A", "1"), ("B", "1"), ("A", "2")]) + df = pd.DataFrame(np.arange(3).reshape((1, 3)), columns=cols, dtype=object) + index = df.index.copy() + + df["A"] = df["A"].astype(np.float64) + tm.assert_index_equal(df.index, index) + + def test_setitem_nonmonotonic(self): + # https://github.com/pandas-dev/pandas/issues/31449 + index = pd.MultiIndex.from_tuples( + [("a", "c"), ("b", "x"), ("a", "d")], names=["l1", "l2"] + ) + df = pd.DataFrame(data=[0, 1, 2], index=index, columns=["e"]) + df.loc["a", "e"] = np.arange(99, 101, dtype="int64") + expected = pd.DataFrame({"e": [99, 1, 100]}, index=index) + tm.assert_frame_equal(df, expected) + + +class TestSetitemWithExpansionMultiIndex: + def test_setitem_new_column_mixed_depth(self): + arrays = [ + ["a", "top", "top", "routine1", "routine1", "routine2"], + ["", "OD", "OD", "result1", "result2", "result1"], + ["", "wx", "wy", "", "", ""], + ] + + tuples = sorted(zip(*arrays, strict=True)) + index = pd.MultiIndex.from_tuples(tuples) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 6)), columns=index + ) + + result = df.copy() + expected = df.copy() + with tm.assert_produces_warning(Pandas4Warning, match="Setting a new column"): + result["b"] = [1, 2, 3, 4] + expected["b", "", ""] = [1, 2, 3, 4] + tm.assert_frame_equal(result, expected) + + def test_setitem_new_column_all_na(self): + # GH#1534 + mix = pd.MultiIndex.from_tuples([("1a", "2a"), ("1a", "2b"), ("1a", "2c")]) + df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], index=mix) + s = pd.Series({(1, 1): 1, (1, 2): 2}) + df["new"] = s + assert df["new"].isna().all() + + def test_setitem_enlargement_keep_index_names(self): + # GH#53053 + mi = pd.MultiIndex.from_tuples([(1, 2, 3)], names=["i1", "i2", "i3"]) + df = pd.DataFrame(data=[[10, 20, 30]], index=mi, columns=["A", "B", "C"]) + df.loc[(0, 0, 0)] = df.loc[(1, 2, 3)] + mi_expected = pd.MultiIndex.from_tuples( + [(1, 2, 3), (0, 0, 0)], names=["i1", "i2", "i3"] + ) + expected = pd.DataFrame( + data=[[10, 20, 30], [10, 20, 30]], + index=mi_expected, + columns=["A", "B", "C"], + ) + tm.assert_frame_equal(df, expected) + + def test_setitem_enlargement_multiindex_with_none(self): + # GH#59153 + # enlarging a DataFrame with a MultiIndex containing None values + index = pd.MultiIndex.from_tuples( + [("A", "a1"), ("A", "a2"), ("B", "b1"), ("B", None)] + ) + df = pd.DataFrame([(0.0, 6.0), (1.0, 5.0), (2.0, 4.0), (3.0, 7.0)], index=index) + df.loc[("A", None), :] = [12.0, 13.0] + expected_index = pd.MultiIndex.from_tuples( + [("A", "a1"), ("A", "a2"), ("B", "b1"), ("B", None), ("A", None)] + ) + expected = pd.DataFrame( + [[0.0, 6.0], [1.0, 5.0], [2.0, 4.0], [3.0, 7.0], [12.0, 13.0]], + index=expected_index, + columns=[0, 1], + ) + tm.assert_frame_equal(df, expected, check_index_type=False) + + +def test_frame_setitem_view_direct(multiindex_dataframe_random_data): + # this works because we are modifying the underlying array + # really a no-no + df = multiindex_dataframe_random_data.T + with pytest.raises(ValueError, match="read-only"): + df["foo"].values[:] = 0 + assert (df["foo"].values != 0).all() + + +def test_frame_setitem_copy_raises(multiindex_dataframe_random_data): + # will raise/warn as its chained assignment + df = multiindex_dataframe_random_data.T + with tm.raises_chained_assignment_error(): + df["foo"]["one"] = 2 + + +def test_frame_setitem_copy_no_write(multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data.T + expected = frame + df = frame.copy() + with tm.raises_chained_assignment_error(): + df["foo"]["one"] = 2 + + tm.assert_frame_equal(df, expected) + + +def test_frame_setitem_partial_multiindex(): + # GH 54875 + df = pd.DataFrame( + { + "a": [1, 2, 3], + "b": [3, 4, 5], + "c": 6, + "d": 7, + } + ).set_index(["a", "b", "c"]) + ser = pd.Series(8, index=df.index.droplevel("c")) + result = df.copy() + result["d"] = ser + expected = df.copy() + expected["d"] = 8 + tm.assert_frame_equal(result, expected) + + +def test_loc_scalar_setitem_scalar_column_multiindex_columns(): + # GH#13474 adding a scalar (non-tuple) column to a frame with MultiIndex + # columns should give scalar .loc access and correct in-place augmented + # assignment, rather than returning a 1-element Series / writing NaN + df = pd.DataFrame(0, index=range(2), columns=pd.MultiIndex.from_product([[1], [2]])) + msg = "Setting a new column on a DataFrame with a MultiIndex" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + # GH#17024 padding the scalar key is deprecated + df["oth"] = 1 + + # getitem returns a scalar, not a 1-element Series + assert df.loc[0, "oth"] == 1 + # while the column-slice form stays a Series (the dimensionality the issue + # was retitled around) + assert isinstance(df.loc[:, "oth"], pd.Series) + + df.loc[0, "oth"] += 1 + assert df.loc[0, "oth"] == 2 + assert df.loc[1, "oth"] == 1 + # the augmented assignment must not coerce the column to float / NaN + assert df[("oth", "")].tolist() == [2, 1] + + +def test_loc_scalar_key_expansion_warns(): + # GH#17024 - deprecate .loc expansion with non-tuple key on MultiIndex + df = pd.DataFrame( + [[1, 2], [3, 4]], + index=pd.MultiIndex.from_product([["a", "b"], ["c"]]), + ) + msg = "Setting a new row on a DataFrame with a MultiIndex" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.loc["all"] = [5, 6] + + +def test_loc_scalar_key_expansion_empty_warns(): + # GH#17024 - deprecate .loc expansion with non-tuple key on empty DataFrame + df = pd.DataFrame( + columns=[0, 1], + index=pd.MultiIndex.from_tuples([], names=["x", "y"]), + ) + msg = "Setting a new row on a DataFrame with a MultiIndex" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.loc["all"] = [5, 6] + + +def test_loc_scalar_key_expansion_zero_columns_warns(): + # GH#17024 - the GH#17895 zero-columns path pads the MultiIndex too + df = pd.DataFrame(index=pd.MultiIndex.from_tuples([], names=["x", "y"])) + msg = "Setting a new row on a DataFrame with a MultiIndex" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.loc["all"] = [5, 6] + assert df.index.tolist() == [("all", "")] + + +def test_loc_tuple_key_expansion_no_warning(): + # GH#17024 - full-length tuple key should not warn + mi = pd.MultiIndex.from_tuples([("a", "b", "c")], names=["x", "y", "z"]) + df = pd.DataFrame([[1, 2]], index=mi) + with tm.assert_produces_warning(None): + df.loc[("d", "e", "f")] = [5, 6] + assert isinstance(df.index, pd.MultiIndex) + + +def test_loc_tuple_key_expansion_two_levels_no_warning(): + # GH#17024 - the recommended replacement for df.loc["x"] = values; with + # a two-level MultiIndex the column slice is needed to avoid the tuple + # being interpreted as (row_key, column_key) + df = pd.DataFrame( + [[1, 2], [3, 4]], + index=pd.MultiIndex.from_product([["a", "b"], ["c"]]), + ) + with tm.assert_produces_warning(None): + df.loc[("x", ""), :] = [5, 6] + assert isinstance(df.index, pd.MultiIndex) + assert df.index[-1] == ("x", "") + + +def test_loc_series_scalar_key_expansion_warns(): + # GH#17024 - deprecate .loc expansion with non-tuple key on Series MultiIndex + ser = pd.Series( + [1, 2], + index=pd.MultiIndex.from_product([["a", "b"], ["c"]]), + ) + msg = "Setting a new value on a Series with a MultiIndex" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + ser.loc["all"] = 5 + + +def test_loc_series_tuple_key_expansion_no_warning(): + # GH#17024 - full-length tuple key on Series should not warn + mi = pd.MultiIndex.from_tuples([("a", "b")], names=["x", "y"]) + ser = pd.Series([1], index=mi) + with tm.assert_produces_warning(None): + ser.loc[("d", "e")] = 5 + + +def test_setitem_new_column_multiindex_scalar_key_warns(): + # GH#17024 - df["scalar"] = values should warn when columns is MultiIndex + mi = pd.MultiIndex.from_tuples([("a", "b")], names=["x", "y"]) + df = pd.DataFrame([[1]], columns=mi) + msg = "Setting a new column on a DataFrame with a MultiIndex" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df["new"] = [2] + + +def test_setitem_new_column_multiindex_full_tuple_no_warning(): + # GH#17024 - df[("a", "b")] = values should not warn + mi = pd.MultiIndex.from_tuples([("a", "b")], names=["x", "y"]) + df = pd.DataFrame([[1]], columns=mi) + with tm.assert_produces_warning(None): + df[("c", "d")] = [2] + assert isinstance(df.columns, pd.MultiIndex) + + +def test_assign_multiindex_columns_warns(): + # GH#17024 - keyword arguments cannot be tuples, so the warning points at + # df[full_tuple] = ... rather than at an impossible tuple keyword + mi = pd.MultiIndex.from_tuples([("a", "b")], names=["x", "y"]) + df = pd.DataFrame([[1]], columns=mi) + msg = re.escape("DataFrame.assign cannot take a tuple key; use df[('new', '')]") + with tm.assert_produces_warning(Pandas4Warning, match=msg): + result = df.assign(new=[2]) + assert result.columns.tolist() == [("a", "b"), ("new", "")] + + +def test_assign_multiindex_columns_existing_key_no_warning(): + # GH#17024 - a key that matches existing columns is not an expansion + mi = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")], names=["x", "y"]) + df = pd.DataFrame([[1, 2]], columns=mi) + with tm.assert_produces_warning(None): + result = df.assign(a=[3]) + assert result.columns.tolist() == [("a", "b"), ("a", "c")] + assert result.iloc[0].tolist() == [3, 3] + + +def test_insert_multiindex_scalar_key_warns(): + # GH#17024 - df.insert with a non-tuple key pads MultiIndex columns + mi = pd.MultiIndex.from_tuples([("a", "b")], names=["x", "y"]) + df = pd.DataFrame([[1]], columns=mi) + msg = "Setting a new column on a DataFrame with a MultiIndex" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.insert(1, "new", [2]) + assert df.columns.tolist() == [("a", "b"), ("new", "")] + + +def test_insert_multiindex_full_tuple_no_warning(): + # GH#17024 - df.insert with a full-length tuple key should not warn + mi = pd.MultiIndex.from_tuples([("a", "b")], names=["x", "y"]) + df = pd.DataFrame([[1]], columns=mi) + with tm.assert_produces_warning(None): + df.insert(1, ("c", "d"), [2]) + assert df.columns.tolist() == [("a", "b"), ("c", "d")] diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_slice.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_slice.py new file mode 100644 index 0000000000000000000000000000000000000000..ca17449a79c31fe76e8cbaa16e7117cac3d78099 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_slice.py @@ -0,0 +1,805 @@ +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest + +from pandas.errors import UnsortedIndexError + +import pandas as pd +import pandas._testing as tm +from pandas.tests.indexing.common import _mklbl + + +class TestMultiIndexSlicers: + def test_per_axis_per_level_getitem(self): + # GH6134 + # example test case + ix = pd.MultiIndex.from_product( + [_mklbl("A", 5), _mklbl("B", 7), _mklbl("C", 4), _mklbl("D", 2)] + ) + df = pd.DataFrame(np.arange(len(ix.to_numpy())), index=ix) + + result = df.loc[(slice("A1", "A3"), slice(None), ["C1", "C3"]), :] + expected = df.loc[ + [ + ( + a, + b, + c, + d, + ) + for a, b, c, d in df.index.values + if a in ("A1", "A2", "A3") and c in ("C1", "C3") + ] + ] + tm.assert_frame_equal(result, expected) + + expected = df.loc[ + [ + ( + a, + b, + c, + d, + ) + for a, b, c, d in df.index.values + if a in ("A1", "A2", "A3") and c in ("C1", "C2", "C3") + ] + ] + result = df.loc[(slice("A1", "A3"), slice(None), slice("C1", "C3")), :] + tm.assert_frame_equal(result, expected) + + # test multi-index slicing with per axis and per index controls + index = pd.MultiIndex.from_tuples( + [("A", 1), ("A", 2), ("A", 3), ("B", 1)], names=["one", "two"] + ) + columns = pd.MultiIndex.from_tuples( + [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], + names=["lvl0", "lvl1"], + ) + + df = pd.DataFrame( + np.arange(16, dtype="int64").reshape(4, 4), index=index, columns=columns + ) + df = df.sort_index(axis=0).sort_index(axis=1) + + # identity + result = df.loc[(slice(None), slice(None)), :] + tm.assert_frame_equal(result, df) + result = df.loc[(slice(None), slice(None)), (slice(None), slice(None))] + tm.assert_frame_equal(result, df) + result = df.loc[:, (slice(None), slice(None))] + tm.assert_frame_equal(result, df) + + # index + result = df.loc[(slice(None), [1]), :] + expected = df.iloc[[0, 3]] + tm.assert_frame_equal(result, expected) + + result = df.loc[(slice(None), 1), :] + expected = df.iloc[[0, 3]] + tm.assert_frame_equal(result, expected) + + # columns + result = df.loc[:, (slice(None), ["foo"])] + expected = df.iloc[:, [1, 3]] + tm.assert_frame_equal(result, expected) + + # both + result = df.loc[(slice(None), 1), (slice(None), ["foo"])] + expected = df.iloc[[0, 3], [1, 3]] + tm.assert_frame_equal(result, expected) + + result = df.loc["A", "a"] + expected = pd.DataFrame( + {"bar": [1, 5, 9], "foo": [0, 4, 8]}, + index=pd.Index([1, 2, 3], name="two"), + columns=pd.Index(["bar", "foo"], name="lvl1"), + ) + tm.assert_frame_equal(result, expected) + + result = df.loc[(slice(None), [1, 2]), :] + expected = df.iloc[[0, 1, 3]] + tm.assert_frame_equal(result, expected) + + # multi-level series + s = pd.Series(np.arange(len(ix.to_numpy())), index=ix) + result = s.loc["A1":"A3", :, ["C1", "C3"]] + expected = s.loc[ + [ + ( + a, + b, + c, + d, + ) + for a, b, c, d in s.index.values + if a in ("A1", "A2", "A3") and c in ("C1", "C3") + ] + ] + tm.assert_series_equal(result, expected) + + # boolean indexers + result = df.loc[(slice(None), df.loc[:, ("a", "bar")] > 5), :] + expected = df.iloc[[2, 3]] + tm.assert_frame_equal(result, expected) + + msg = ( + "cannot index with a boolean indexer " + "that is not the same length as the index" + ) + with pytest.raises(ValueError, match=msg): + df.loc[(slice(None), np.array([True, False])), :] + + with pytest.raises(KeyError, match=r"\[1\] not in index"): + # slice(None) is on the index, [1] is on the columns, but 1 is + # not in the columns, so we raise + # This used to treat [1] as positional GH#16396 + df.loc[slice(None), [1]] + + # not lexsorted + assert df.index._lexsort_depth == 2 + df = df.sort_index(level=1, axis=0) + assert df.index._lexsort_depth == 0 + + msg = ( + "MultiIndex slicing requires the index to be " + r"lexsorted: slicing on levels \[1\], lexsort depth 0" + ) + with pytest.raises(UnsortedIndexError, match=msg): + df.loc[(slice(None), slice("bar")), :] + + # GH 16734: not sorted, but no real slicing + result = df.loc[(slice(None), df.loc[:, ("a", "bar")] > 5), :] + tm.assert_frame_equal(result, df.iloc[[1, 3], :]) + + def test_multiindex_slicers_non_unique(self): + # GH 7106 + # non-unique mi index support + df = ( + pd.DataFrame( + { + "A": ["foo", "foo", "foo", "foo"], + "B": ["a", "a", "a", "a"], + "C": [1, 2, 1, 3], + "D": [1, 2, 3, 4], + } + ) + .set_index(["A", "B", "C"]) + .sort_index() + ) + assert not df.index.is_unique + expected = ( + pd.DataFrame( + {"A": ["foo", "foo"], "B": ["a", "a"], "C": [1, 1], "D": [1, 3]} + ) + .set_index(["A", "B", "C"]) + .sort_index() + ) + result = df.loc[(slice(None), slice(None), 1), :] + tm.assert_frame_equal(result, expected) + + # this is equivalent of an xs expression + result = df.xs(1, level=2, drop_level=False) + tm.assert_frame_equal(result, expected) + + df = ( + pd.DataFrame( + { + "A": ["foo", "foo", "foo", "foo"], + "B": ["a", "a", "a", "a"], + "C": [1, 2, 1, 2], + "D": [1, 2, 3, 4], + } + ) + .set_index(["A", "B", "C"]) + .sort_index() + ) + assert not df.index.is_unique + expected = ( + pd.DataFrame( + {"A": ["foo", "foo"], "B": ["a", "a"], "C": [1, 1], "D": [1, 3]} + ) + .set_index(["A", "B", "C"]) + .sort_index() + ) + result = df.loc[(slice(None), slice(None), 1), :] + assert not result.index.is_unique + tm.assert_frame_equal(result, expected) + + # GH12896 + # numpy-implementation dependent bug + ints = [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 12, + 13, + 14, + 14, + 16, + 17, + 18, + 19, + 200000, + 200000, + ] + n = len(ints) + idx = pd.MultiIndex.from_arrays([["a"] * n, ints]) + result = pd.Series([1] * n, index=idx) + result = result.sort_index() + result = result.loc[(slice(None), slice(100000))] + expected = pd.Series([1] * (n - 2), index=idx[:-2]).sort_index() + tm.assert_series_equal(result, expected) + + def test_multiindex_slicers_datetimelike(self): + # GH 7429 + # buggy/inconsistent behavior when slicing with datetime-like + dates = [datetime(2012, 1, 1, 12, 12, 12) + timedelta(days=i) for i in range(6)] + freq = [1, 2] + index = pd.MultiIndex.from_product([dates, freq], names=["date", "frequency"]) + + df = pd.DataFrame( + np.arange(6 * 2 * 4, dtype="int64").reshape(-1, 4), + index=index, + columns=list("ABCD"), + ) + + # multi-axis slicing + idx = pd.IndexSlice + expected = df.iloc[[0, 2, 4], [0, 1]] + result = df.loc[ + ( + slice( + pd.Timestamp("2012-01-01 12:12:12"), + pd.Timestamp("2012-01-03 12:12:12"), + ), + slice(1, 1), + ), + slice("A", "B"), + ] + tm.assert_frame_equal(result, expected) + + result = df.loc[ + ( + idx[ + pd.Timestamp("2012-01-01 12:12:12") : pd.Timestamp( + "2012-01-03 12:12:12" + ) + ], + idx[1:1], + ), + slice("A", "B"), + ] + tm.assert_frame_equal(result, expected) + + result = df.loc[ + ( + slice( + pd.Timestamp("2012-01-01 12:12:12"), + pd.Timestamp("2012-01-03 12:12:12"), + ), + 1, + ), + slice("A", "B"), + ] + tm.assert_frame_equal(result, expected) + + # with strings + result = df.loc[ + (slice("2012-01-01 12:12:12", "2012-01-03 12:12:12"), slice(1, 1)), + slice("A", "B"), + ] + tm.assert_frame_equal(result, expected) + + result = df.loc[ + (idx["2012-01-01 12:12:12":"2012-01-03 12:12:12"], 1), idx["A", "B"] + ] + tm.assert_frame_equal(result, expected) + + def test_multiindex_slicers_edges(self): + # GH 8132 + # various edge cases + df = pd.DataFrame( + { + "A": ["A0"] * 5 + ["A1"] * 5 + ["A2"] * 5, + "B": ["B0", "B0", "B1", "B1", "B2"] * 3, + "DATE": [ + "2013-06-11", + "2013-07-02", + "2013-07-09", + "2013-07-30", + "2013-08-06", + "2013-06-11", + "2013-07-02", + "2013-07-09", + "2013-07-30", + "2013-08-06", + "2013-09-03", + "2013-10-01", + "2013-07-09", + "2013-08-06", + "2013-09-03", + ], + "VALUES": [22, 35, 14, 9, 4, 40, 18, 4, 2, 5, 1, 2, 3, 4, 2], + } + ) + + df["DATE"] = pd.to_datetime(df["DATE"]) + df1 = df.set_index(["A", "B", "DATE"]) + df1 = df1.sort_index() + + # A1 - Get all values under "A0" and "A1" + result = df1.loc[(slice("A1")), :] + expected = df1.iloc[0:10] + tm.assert_frame_equal(result, expected) + + # A2 - Get all values from the start to "A2" + result = df1.loc[(slice("A2")), :] + expected = df1 + tm.assert_frame_equal(result, expected) + + # A3 - Get all values under "B1" or "B2" + result = df1.loc[(slice(None), slice("B1", "B2")), :] + expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13, 14]] + tm.assert_frame_equal(result, expected) + + # A4 - Get all values between 2013-07-02 and 2013-07-09 + result = df1.loc[(slice(None), slice(None), slice("20130702", "20130709")), :] + expected = df1.iloc[[1, 2, 6, 7, 12]] + tm.assert_frame_equal(result, expected) + + # B1 - Get all values in B0 that are also under A0, A1 and A2 + result = df1.loc[(slice("A2"), slice("B0")), :] + expected = df1.iloc[[0, 1, 5, 6, 10, 11]] + tm.assert_frame_equal(result, expected) + + # B2 - Get all values in B0, B1 and B2 (similar to what #2 is doing for + # the As) + result = df1.loc[(slice(None), slice("B2")), :] + expected = df1 + tm.assert_frame_equal(result, expected) + + # B3 - Get all values from B1 to B2 and up to 2013-08-06 + result = df1.loc[(slice(None), slice("B1", "B2"), slice("2013-08-06")), :] + expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13]] + tm.assert_frame_equal(result, expected) + + # B4 - Same as A4 but the start of the date slice is not a key. + # shows indexing on a partial selection slice + result = df1.loc[(slice(None), slice(None), slice("20130701", "20130709")), :] + expected = df1.iloc[[1, 2, 6, 7, 12]] + tm.assert_frame_equal(result, expected) + + def test_per_axis_per_level_doc_examples(self): + # test index maker + idx = pd.IndexSlice + + # from indexing.rst / advanced + index = pd.MultiIndex.from_product( + [_mklbl("A", 4), _mklbl("B", 2), _mklbl("C", 4), _mklbl("D", 2)] + ) + columns = pd.MultiIndex.from_tuples( + [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], + names=["lvl0", "lvl1"], + ) + df = pd.DataFrame( + np.arange(len(index) * len(columns), dtype="int64").reshape( + (len(index), len(columns)) + ), + index=index, + columns=columns, + ) + result = df.loc[(slice("A1", "A3"), slice(None), ["C1", "C3"]), :] + expected = df.loc[ + [ + ( + a, + b, + c, + d, + ) + for a, b, c, d in df.index.values + if a in ("A1", "A2", "A3") and c in ("C1", "C3") + ] + ] + tm.assert_frame_equal(result, expected) + result = df.loc[idx["A1":"A3", :, ["C1", "C3"]], :] + tm.assert_frame_equal(result, expected) + + result = df.loc[(slice(None), slice(None), ["C1", "C3"]), :] + expected = df.loc[ + [ + ( + a, + b, + c, + d, + ) + for a, b, c, d in df.index.values + if c in ("C1", "C3") + ] + ] + tm.assert_frame_equal(result, expected) + result = df.loc[idx[:, :, ["C1", "C3"]], :] + tm.assert_frame_equal(result, expected) + + # not sorted + msg = ( + "MultiIndex slicing requires the index to be lexsorted: " + r"slicing on levels \[1\], lexsort depth 1" + ) + with pytest.raises(UnsortedIndexError, match=msg): + df.loc["A1", ("a", slice("foo"))] + + # GH 16734: not sorted, but no real slicing + tm.assert_frame_equal( + df.loc["A1", (slice(None), "foo")], df.loc["A1"].iloc[:, [0, 2]] + ) + + df = df.sort_index(axis=1) + + # slicing + df.loc["A1", (slice(None), "foo")] + df.loc[(slice(None), slice(None), ["C1", "C3"]), (slice(None), "foo")] + + # setitem + df.loc(axis=0)[:, :, ["C1", "C3"]] = -10 + + def test_loc_axis_arguments(self): + index = pd.MultiIndex.from_product( + [_mklbl("A", 4), _mklbl("B", 2), _mklbl("C", 4), _mklbl("D", 2)] + ) + columns = pd.MultiIndex.from_tuples( + [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], + names=["lvl0", "lvl1"], + ) + df = ( + pd.DataFrame( + np.arange(len(index) * len(columns), dtype="int64").reshape( + (len(index), len(columns)) + ), + index=index, + columns=columns, + ) + .sort_index() + .sort_index(axis=1) + ) + + # axis 0 + result = df.loc(axis=0)["A1":"A3", :, ["C1", "C3"]] + expected = df.loc[ + [ + ( + a, + b, + c, + d, + ) + for a, b, c, d in df.index.values + if a in ("A1", "A2", "A3") and c in ("C1", "C3") + ] + ] + tm.assert_frame_equal(result, expected) + + result = df.loc(axis="index")[:, :, ["C1", "C3"]] + expected = df.loc[ + [ + ( + a, + b, + c, + d, + ) + for a, b, c, d in df.index.values + if c in ("C1", "C3") + ] + ] + tm.assert_frame_equal(result, expected) + + # axis 1 + result = df.loc(axis=1)[:, "foo"] + expected = df.loc[:, (slice(None), "foo")] + tm.assert_frame_equal(result, expected) + + result = df.loc(axis="columns")[:, "foo"] + expected = df.loc[:, (slice(None), "foo")] + tm.assert_frame_equal(result, expected) + + # invalid axis + for i in [-1, 2, "foo"]: + msg = f"No axis named {i} for object type DataFrame" + with pytest.raises(ValueError, match=msg): + df.loc(axis=i)[:, :, ["C1", "C3"]] + + def test_loc_axis_single_level_multi_col_indexing_multiindex_col_df(self): + # GH29519 + df = pd.DataFrame( + np.arange(27).reshape(3, 9), + columns=pd.MultiIndex.from_product( + [["a1", "a2", "a3"], ["b1", "b2", "b3"]] + ), + ) + result = df.loc(axis=1)["a1":"a2"] + expected = df.iloc[:, :-3] + + tm.assert_frame_equal(result, expected) + + def test_loc_axis_single_level_single_col_indexing_multiindex_col_df(self): + # GH29519 + df = pd.DataFrame( + np.arange(27).reshape(3, 9), + columns=pd.MultiIndex.from_product( + [["a1", "a2", "a3"], ["b1", "b2", "b3"]] + ), + ) + result = df.loc(axis=1)["a1"] + expected = df.iloc[:, :3] + expected.columns = ["b1", "b2", "b3"] + + tm.assert_frame_equal(result, expected) + + def test_loc_ax_single_level_indexer_simple_df(self): + # GH29519 + # test single level indexing on single index column data frame + df = pd.DataFrame(np.arange(9).reshape(3, 3), columns=["a", "b", "c"]) + result = df.loc(axis=1)["a"] + expected = pd.Series(np.array([0, 3, 6]), name="a") + tm.assert_series_equal(result, expected) + + def test_per_axis_per_level_setitem(self): + # test index maker + idx = pd.IndexSlice + + # test multi-index slicing with per axis and per index controls + index = pd.MultiIndex.from_tuples( + [("A", 1), ("A", 2), ("A", 3), ("B", 1)], names=["one", "two"] + ) + columns = pd.MultiIndex.from_tuples( + [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], + names=["lvl0", "lvl1"], + ) + + df_orig = pd.DataFrame( + np.arange(16, dtype="int64").reshape(4, 4), index=index, columns=columns + ) + df_orig = df_orig.sort_index(axis=0).sort_index(axis=1) + + # identity + df = df_orig.copy() + df.loc[(slice(None), slice(None)), :] = 100 + expected = df_orig.copy() + expected.iloc[:, :] = 100 + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc(axis=0)[:, :] = 100 + expected = df_orig.copy() + expected.iloc[:, :] = 100 + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc[(slice(None), slice(None)), (slice(None), slice(None))] = 100 + expected = df_orig.copy() + expected.iloc[:, :] = 100 + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc[:, (slice(None), slice(None))] = 100 + expected = df_orig.copy() + expected.iloc[:, :] = 100 + tm.assert_frame_equal(df, expected) + + # index + df = df_orig.copy() + df.loc[(slice(None), [1]), :] = 100 + expected = df_orig.copy() + expected.iloc[[0, 3]] = 100 + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc[(slice(None), 1), :] = 100 + expected = df_orig.copy() + expected.iloc[[0, 3]] = 100 + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc(axis=0)[:, 1] = 100 + expected = df_orig.copy() + expected.iloc[[0, 3]] = 100 + tm.assert_frame_equal(df, expected) + + # columns + df = df_orig.copy() + df.loc[:, (slice(None), ["foo"])] = 100 + expected = df_orig.copy() + expected.iloc[:, [1, 3]] = 100 + tm.assert_frame_equal(df, expected) + + # both + df = df_orig.copy() + df.loc[(slice(None), 1), (slice(None), ["foo"])] = 100 + expected = df_orig.copy() + expected.iloc[[0, 3], [1, 3]] = 100 + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc[idx[:, 1], idx[:, ["foo"]]] = 100 + expected = df_orig.copy() + expected.iloc[[0, 3], [1, 3]] = 100 + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc["A", "a"] = 100 + expected = df_orig.copy() + expected.iloc[0:3, 0:2] = 100 + tm.assert_frame_equal(df, expected) + + # setting with a list-like + df = df_orig.copy() + df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array( + [[100, 100], [100, 100]], dtype="int64" + ) + expected = df_orig.copy() + expected.iloc[[0, 3], [1, 3]] = 100 + tm.assert_frame_equal(df, expected) + + # not enough values + df = df_orig.copy() + + msg = "setting an array element with a sequence." + with pytest.raises(ValueError, match=msg): + df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array( + [[100], [100, 100]], dtype="int64" + ) + + msg = "Must have equal len keys and value when setting with an iterable" + with pytest.raises(ValueError, match=msg): + df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array( + [100, 100, 100, 100], dtype="int64" + ) + + # with an alignable rhs + df = df_orig.copy() + df.loc[(slice(None), 1), (slice(None), ["foo"])] = ( + df.loc[(slice(None), 1), (slice(None), ["foo"])] * 5 + ) + expected = df_orig.copy() + expected.iloc[[0, 3], [1, 3]] = expected.iloc[[0, 3], [1, 3]] * 5 + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc[(slice(None), 1), (slice(None), ["foo"])] *= df.loc[ + (slice(None), 1), (slice(None), ["foo"]) + ] + expected = df_orig.copy() + expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]] + tm.assert_frame_equal(df, expected) + + rhs = df_orig.loc[(slice(None), 1), (slice(None), ["foo"])].copy() + rhs.loc[:, ("c", "bah")] = 10 + df = df_orig.copy() + df.loc[(slice(None), 1), (slice(None), ["foo"])] *= rhs + expected = df_orig.copy() + expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]] + tm.assert_frame_equal(df, expected) + + def test_multiindex_label_slicing_with_negative_step(self): + ser = pd.Series( + np.arange(20), pd.MultiIndex.from_product([list("abcde"), np.arange(4)]) + ) + SLC = pd.IndexSlice + + tm.assert_indexing_slices_equivalent(ser, SLC[::-1], SLC[::-1]) + + tm.assert_indexing_slices_equivalent(ser, SLC["d"::-1], SLC[15::-1]) + tm.assert_indexing_slices_equivalent(ser, SLC[("d",) :: -1], SLC[15::-1]) + + tm.assert_indexing_slices_equivalent(ser, SLC[:"d":-1], SLC[:11:-1]) + tm.assert_indexing_slices_equivalent(ser, SLC[: ("d",) : -1], SLC[:11:-1]) + + tm.assert_indexing_slices_equivalent(ser, SLC["d":"b":-1], SLC[15:3:-1]) + tm.assert_indexing_slices_equivalent(ser, SLC[("d",) : "b" : -1], SLC[15:3:-1]) + tm.assert_indexing_slices_equivalent(ser, SLC["d" : ("b",) : -1], SLC[15:3:-1]) + tm.assert_indexing_slices_equivalent( + ser, SLC[("d",) : ("b",) : -1], SLC[15:3:-1] + ) + tm.assert_indexing_slices_equivalent(ser, SLC["b":"d":-1], SLC[:0]) + + tm.assert_indexing_slices_equivalent(ser, SLC[("c", 2) :: -1], SLC[10::-1]) + tm.assert_indexing_slices_equivalent(ser, SLC[: ("c", 2) : -1], SLC[:9:-1]) + tm.assert_indexing_slices_equivalent( + ser, SLC[("e", 0) : ("c", 2) : -1], SLC[16:9:-1] + ) + + def test_multiindex_slice_first_level(self): + # GH 12697 + freq = ["a", "b", "c", "d"] + idx = pd.MultiIndex.from_product([freq, range(500)]) + df = pd.DataFrame(list(range(2000)), index=idx, columns=["Test"]) + df_slice = df.loc[pd.IndexSlice[:, 30:70], :] + result = df_slice.loc["a"] + expected = pd.DataFrame( + list(range(30, 71)), columns=["Test"], index=range(30, 71) + ) + tm.assert_frame_equal(result, expected) + result = df_slice.loc["d"] + expected = pd.DataFrame( + list(range(1530, 1571)), columns=["Test"], index=range(30, 71) + ) + tm.assert_frame_equal(result, expected) + + def test_int_series_slicing(self, multiindex_year_month_day_dataframe_random_data): + ymd = multiindex_year_month_day_dataframe_random_data + s = ymd["A"] + result = s[5:] + expected = s.reindex(s.index[5:]) + tm.assert_series_equal(result, expected) + + s = ymd["A"].copy() + exp = ymd["A"].copy() + s[5:] = 0 + exp.iloc[5:] = 0 + tm.assert_numpy_array_equal(s.values, exp.values) + + result = ymd[5:] + expected = ymd.reindex(s.index[5:]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "dtype, loc, iloc", + [ + # dtype = int, step = -1 + ("int", slice(None, None, -1), slice(None, None, -1)), + ("int", slice(3, None, -1), slice(3, None, -1)), + ("int", slice(None, 1, -1), slice(None, 0, -1)), + ("int", slice(3, 1, -1), slice(3, 0, -1)), + # dtype = int, step = -2 + ("int", slice(None, None, -2), slice(None, None, -2)), + ("int", slice(3, None, -2), slice(3, None, -2)), + ("int", slice(None, 1, -2), slice(None, 0, -2)), + ("int", slice(3, 1, -2), slice(3, 0, -2)), + # dtype = str, step = -1 + ("str", slice(None, None, -1), slice(None, None, -1)), + ("str", slice("d", None, -1), slice(3, None, -1)), + ("str", slice(None, "b", -1), slice(None, 0, -1)), + ("str", slice("d", "b", -1), slice(3, 0, -1)), + # dtype = str, step = -2 + ("str", slice(None, None, -2), slice(None, None, -2)), + ("str", slice("d", None, -2), slice(3, None, -2)), + ("str", slice(None, "b", -2), slice(None, 0, -2)), + ("str", slice("d", "b", -2), slice(3, 0, -2)), + ], + ) + def test_loc_slice_negative_stepsize(self, dtype, loc, iloc): + # GH#38071 + labels = { + "str": list("abcde"), + "int": range(5), + }[dtype] + + mi = pd.MultiIndex.from_arrays([labels] * 2) + df = pd.DataFrame(1.0, index=mi, columns=["A"]) + + SLC = pd.IndexSlice + + expected = df.iloc[iloc, :] + result_get_loc = df.loc[SLC[loc], :] + result_get_locs_level_0 = df.loc[SLC[loc, :], :] + result_get_locs_level_1 = df.loc[SLC[:, loc], :] + + tm.assert_frame_equal(result_get_loc, expected) + tm.assert_frame_equal(result_get_locs_level_0, expected) + tm.assert_frame_equal(result_get_locs_level_1, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_sorted.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_sorted.py new file mode 100644 index 0000000000000000000000000000000000000000..e2eaa9a41ecdd9e47723d7a22c0bb1d2f3a17bdf --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/multiindex/test_sorted.py @@ -0,0 +1,147 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestMultiIndexSorted: + def test_getitem_multilevel_index_tuple_not_sorted(self): + index_columns = list("abc") + df = pd.DataFrame( + [[0, 1, 0, "x"], [0, 0, 1, "y"]], columns=[*index_columns, "data"] + ) + df = df.set_index(index_columns) + query_index = df.index[:1] + rs = df.loc[query_index, "data"] + + xp_idx = pd.MultiIndex.from_tuples([(0, 1, 0)], names=["a", "b", "c"]) + xp = pd.Series(["x"], index=xp_idx, name="data") + tm.assert_series_equal(rs, xp) + + def test_getitem_slice_not_sorted(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + df = frame.sort_index(level=1).T + + # buglet with int typechecking + result = df.iloc[:, : np.int32(3)] + expected = df.reindex(columns=df.columns[:3]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("key", [None, lambda x: x]) + def test_frame_getitem_not_sorted2(self, key): + # 13431 + df = pd.DataFrame( + { + "col1": ["b", "d", "b", "a"], + "col2": [3, 1, 1, 2], + "data": ["one", "two", "three", "four"], + } + ) + + df2 = df.set_index(["col1", "col2"]) + df2_original = df2.copy() + + df2.index = df2.index.set_levels(["b", "d", "a"], level="col1") + df2.index = df2.index.set_codes([0, 1, 0, 2], level="col1") + assert not df2.index.is_monotonic_increasing + + assert df2_original.index.equals(df2.index) + expected = df2.sort_index(key=key) + assert expected.index.is_monotonic_increasing + + result = df2.sort_index(level=0, key=key) + assert result.index.is_monotonic_increasing + tm.assert_frame_equal(result, expected) + + def test_sort_values_key(self): + arrays = [ + ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + ] + tuples = zip(*arrays, strict=True) + index = pd.MultiIndex.from_tuples(tuples) + index = index.sort_values( # sort by third letter + key=lambda x: x.map(lambda entry: entry[2]) + ) + result = pd.DataFrame(range(8), index=index) + + arrays = [ + ["foo", "foo", "bar", "bar", "qux", "qux", "baz", "baz"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + ] + tuples = zip(*arrays, strict=True) + index = pd.MultiIndex.from_tuples(tuples) + expected = pd.DataFrame(range(8), index=index) + + tm.assert_frame_equal(result, expected) + + def test_argsort_with_na(self): + # GH48495 + arrays = [ + pd.array([2, pd.NA, 1], dtype="Int64"), + pd.array([1, 2, 3], dtype="Int64"), + ] + index = pd.MultiIndex.from_arrays(arrays) + result = index.argsort() + expected = np.array([2, 0, 1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_sort_values_with_na(self): + # GH48495 + arrays = [ + pd.array([2, pd.NA, 1], dtype="Int64"), + pd.array([1, 2, 3], dtype="Int64"), + ] + index = pd.MultiIndex.from_arrays(arrays) + index = index.sort_values() + result = pd.DataFrame(range(3), index=index) + + arrays = [ + pd.array([1, 2, pd.NA], dtype="Int64"), + pd.array([3, 1, 2], dtype="Int64"), + ] + index = pd.MultiIndex.from_arrays(arrays) + expected = pd.DataFrame(range(3), index=index) + + tm.assert_frame_equal(result, expected) + + def test_frame_getitem_not_sorted(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + df = frame.T + df["foo", "four"] = "foo" + + arrays = [np.array(x) for x in zip(*df.columns.values, strict=True)] + + result = df["foo"] + result2 = df.loc[:, "foo"] + expected = df.reindex(columns=df.columns[arrays[0] == "foo"]) + expected.columns = expected.columns.droplevel(0) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) + + df = df.T + result = df.xs("foo") + result2 = df.loc["foo"] + expected = df.reindex(df.index[arrays[0] == "foo"]) + expected.index = expected.index.droplevel(0) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) + + def test_series_getitem_not_sorted(self): + arrays = [ + ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + ] + tuples = zip(*arrays, strict=True) + index = pd.MultiIndex.from_tuples(tuples) + s = pd.Series(np.random.default_rng(2).standard_normal(8), index=index) + + arrays = [np.array(x) for x in zip(*index.values, strict=True)] + + result = s["qux"] + result2 = s.loc["qux"] + expected = s[arrays[0] == "qux"] + expected.index = expected.index.droplevel(0) + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result2, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_at.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_at.py new file mode 100644 index 0000000000000000000000000000000000000000..efb13304a03b79b3fd25e68a0b6c7b17bc8405fb --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_at.py @@ -0,0 +1,367 @@ +from datetime import ( + UTC, + datetime, +) +from decimal import Decimal + +import numpy as np +import pytest + +from pandas.errors import ( + InvalidIndexError, + Pandas4Warning, +) + +import pandas as pd +import pandas._testing as tm + + +def test_at_dateoffset_columns(): + # GH#20948 - .at with DateOffset columns + offsets = pd.Series(data=[-15, -10, -5, 0, 5, 10, 15], dtype=float).map( + pd.DateOffset + ) + df = pd.DataFrame(index=[0, 1], columns=pd.Index(offsets)) + + # read access + result = df.at[0, offsets[0]] + assert result is np.nan + + # write access + df.at[0, offsets[0]] = 1 + assert df.at[0, offsets[0]] == 1 + + +def test_at_multiindex_partial_date_string(): + # GH#43395 - .at with partial date string on MultiIndex with DatetimeIndex level + timestamps = pd.DatetimeIndex( + ["2021-08-01", "2021-08-01 12:00", "2021-08-02", "2021-08-02 12:00"] + ) + index = pd.MultiIndex.from_product( + [["A", "B"], timestamps], names=["ticker", "timestamp"] + ) + df = pd.DataFrame({"col": range(len(index))}, index=index) + + # DataFrame.at with partial date string should not raise TypeError + result = df.at[("A", "2021-08-02"), "col"] + expected = np.array([2, 3], dtype=np.int64) + tm.assert_numpy_array_equal(result, expected) + + # Series.at with partial date string + ser = df["col"] + result = ser.at[("A", "2021-08-02")] + expected = pd.Series( + [2, 3], + index=pd.MultiIndex.from_arrays( + [ + ["A", "A"], + pd.DatetimeIndex( + ["2021-08-02", "2021-08-02 12:00"], + dtype="datetime64[us]", + ), + ], + names=["ticker", "timestamp"], + ), + name="col", + ) + tm.assert_series_equal(result, expected) + + +def test_at_incompatible_type_decimal(): + # GH#22740 - .at should not silently discard incompatible type + df = pd.DataFrame({"A": [1, 2, 3]}) + with pytest.raises(TypeError, match="Invalid value"): + df.at[0, "A"] = Decimal("1") + + +def test_at_timezone(): + # https://github.com/pandas-dev/pandas/issues/33544 + result = pd.DataFrame({"foo": [datetime(2000, 1, 1)]}) + with pytest.raises(TypeError, match="Invalid value"): + result.at[0, "foo"] = datetime(2000, 1, 2, tzinfo=UTC) + + +def test_selection_methods_of_assigned_col(): + # GH 29282 + df = pd.DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]}) + df2 = pd.DataFrame(data={"c": [7, 8, 9]}, index=[2, 1, 0]) + df["c"] = df2["c"] + df.at[1, "c"] = 11 + result = df + expected = pd.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 = pd.Series([9, 11, 7], name="c") + tm.assert_series_equal(result, expected) + + result = df[["c"]] + expected = pd.DataFrame({"c": [9, 11, 7]}) + tm.assert_frame_equal(result, expected) + + +class TestAtSetItem: + def test_at_setitem_mixed_index_assignment(self): + # GH#19860 + ser = pd.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 = pd.DataFrame( + index=range(3), columns=range(3), dtype=pd.CategoricalDtype(["foo", "bar"]) + ) + df.at[1, 1] = "foo" + + expected = pd.DataFrame( + [ + [np.nan, np.nan, np.nan], + [np.nan, "foo", np.nan], + [np.nan, np.nan, np.nan], + ], + dtype=pd.CategoricalDtype(["foo", "bar"]), + ) + + tm.assert_frame_equal(df, expected) + + def test_at_setitem_multiindex(self): + df = pd.DataFrame( + np.zeros((3, 2), dtype="int64"), + columns=pd.MultiIndex.from_tuples([("a", 0), ("a", 1)]), + ) + df.at[0, "a"] = 10 + expected = pd.DataFrame( + [[10, 10], [0, 0], [0, 0]], + columns=pd.MultiIndex.from_tuples([("a", 0), ("a", 1)]), + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("row", (pd.Timestamp("2019-01-01"), "2019-01-01")) + def test_at_datetime_index(self, row): + # Set float64 dtype to avoid upcast when setting .5 + df = pd.DataFrame( + data=[[1] * 2], index=pd.DatetimeIndex(data=["2019-01-01", "2019-01-02"]) + ).astype({0: "float64"}) + expected = pd.DataFrame( + data=[[0.5, 1], [1.0, 1]], + index=pd.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 = ( + pd.Timestamp("2017-08-05 00:00:00+0100", tz=tz_naive_fixture) + if tz_naive_fixture is not None + else pd.Timestamp("2017-08-05 00:00:00+0100") + ) + result = pd.Series(ts) + with tm.assert_produces_warning(Pandas4Warning, match="does not exist"): + result.at[1] = ts + expected = pd.Series([ts, ts]) + tm.assert_series_equal(result, expected) + + def test_at_setitem_expansion_deprecated_dataframe(self): + # GH#48323 + df = pd.DataFrame({"a": [1, 2]}) + msg = "Setting a value on a DataFrame via .at with a key" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.at[5, "a"] = 6 + expected = pd.DataFrame({"a": [1, 2, 6]}, index=[0, 1, 5]) + tm.assert_frame_equal(df, expected) + + def test_at_setitem_expansion_deprecated_series(self): + # GH#48323 + ser = pd.Series([1, 2], index=[0, 1]) + msg = "Setting a value on a Series via .at with a key" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + ser.at[5] = 6 + expected = pd.Series([1, 2, 6], index=[0, 1, 5]) + tm.assert_series_equal(ser, expected) + + def test_at_setitem_expansion_deprecated_new_column(self): + # GH#48323 - new column (existing row) also expands + df = pd.DataFrame({"a": [1, 2]}) + msg = "Setting a value on a DataFrame via .at with a key" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.at[0, "b"] = 99 + assert "b" in df.columns + + def test_at_setitem_expansion_deprecated_new_column_multiindex_rows(self): + # GH#48323 - new column on a frame with MultiIndex rows + mi = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1)]) + df = pd.DataFrame({"x": [1, 2, 3]}, index=mi) + msg = "Setting a value on a DataFrame via .at with a key" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.at[("a", 1), "y"] = 99 + assert "y" in df.columns + + def test_at_setitem_expansion_deprecated_new_column_multiindex_cols(self): + # GH#48323 - new tuple column on a frame with MultiIndex columns + df = pd.DataFrame( + [[1, 2], [3, 4]], + columns=pd.MultiIndex.from_tuples([("a", 1), ("a", 2)]), + ) + msg = "Setting a value on a DataFrame via .at with a key" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + df.at[0, ("b", 1)] = 99 + assert ("b", 1) in df.columns + + def test_at_setitem_no_warning_existing_key(self): + # GH#48323 - no warning for existing keys + df = pd.DataFrame({"a": [1, 2]}) + with tm.assert_produces_warning(None): + df.at[0, "a"] = 99 + assert df.at[0, "a"] == 99 + + ser = pd.Series([1, 2]) + with tm.assert_produces_warning(None): + ser.at[0] = 99 + assert ser.at[0] == 99 + + +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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + new_row = [6, 7] + with pytest.raises( + InvalidIndexError, + match=".at-based indexing can only have scalar indexers; use .loc instead", + ): + df.at[5] = new_row + + def test_at_getitem_mixed_index_no_fallback(self): + # GH#19860 + ser = pd.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 = pd.CategoricalIndex([3, 4]) + + arr = np.arange(4).reshape(2, 2) + frame = pd.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 = pd.DataFrame(index=["a"], columns=["col1", "col2"]) + new_row = [123, 15] + with pytest.raises( + InvalidIndexError, + match=".at-based indexing can only have scalar indexers; use .loc instead", + ): + df.at["a"] = new_row + + @pytest.mark.parametrize("key", [lambda df: df["b"] == 6, [0, 1], np.array([0, 1])]) + def test_at_setitem_nonscalar_indexer_raises(self, key): + # GH#51866 - .at setitem with a mask/list/array indexer should raise a + # clear error directing the user to .loc, not the misleading + # "scalar value" message + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + indexer = key(df) if callable(key) else key + with pytest.raises( + InvalidIndexError, + match=".at-based indexing can only have scalar indexers; use .loc instead", + ): + df.at[indexer, "b"] = 9.0 + + @pytest.mark.parametrize("key", [lambda ser: ser > 2, [0, 1], np.array([0, 1])]) + def test_at_setitem_series_nonscalar_indexer_raises(self, key): + # GH#51866 - Series .at setitem with a non-scalar indexer should raise a + # clear error rather than dumping the raw indexer + ser = pd.Series([1, 2, 3, 4]) + indexer = key(ser) if callable(key) else key + with pytest.raises( + InvalidIndexError, + match=".at-based indexing can only have scalar indexers; use .loc instead", + ): + ser.at[indexer] = 9.0 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_categorical.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..f51c4ae893f8de6789653dfe96180ecf96c72bc8 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_categorical.py @@ -0,0 +1,606 @@ +import re + +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def df(): + return pd.DataFrame( + { + "A": np.arange(6, dtype="int64"), + }, + index=pd.CategoricalIndex( + list("aabbca"), dtype=pd.CategoricalDtype(list("cab")), name="B" + ), + ) + + +@pytest.fixture +def df2(): + return pd.DataFrame( + { + "A": np.arange(6, dtype="int64"), + }, + index=pd.CategoricalIndex( + list("aabbca"), dtype=pd.CategoricalDtype(list("cabe")), name="B" + ), + ) + + +class TestCategoricalIndex: + def test_loc_scalar(self, df): + dtype = pd.CategoricalDtype(list("cab")) + result = df.loc["a"] + bidx = pd.Series(list("aaa"), name="B").astype(dtype) + assert bidx.dtype == dtype + + expected = pd.DataFrame({"A": [0, 1, 5]}, index=pd.Index(bidx)) + tm.assert_frame_equal(result, expected) + + df = df.copy() + df.loc["a"] = 20 + bidx2 = pd.Series(list("aabbca"), name="B").astype(dtype) + assert bidx2.dtype == dtype + expected = pd.DataFrame( + { + "A": [20, 20, 2, 3, 4, 20], + }, + index=pd.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 categories + df.loc["a"] = 20 + + # Setting a new row on an existing column + df3 = df.copy() + df3.loc["d", "A"] = 10 + bidx3 = pd.Index(list("aabbcad"), name="B") + expected3 = pd.DataFrame( + { + "A": [20, 20, 2, 3, 4, 20, 10], + }, + index=pd.Index(bidx3), + ) + tm.assert_frame_equal(df3, expected3) + + def test_loc_setitem_with_expansion_non_category_new_column(self, df): + # Setting-with-expansion with a new key "d" that is not among categories + # Setting a new row _and_ new column + df.loc["a"] = 20 + + df4 = df.copy() + df4.loc["d", "C"] = 10 + + bidx3 = pd.Index(list("aabbcad"), name="B") + expected3 = pd.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=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 = pd.Series(pd.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 = pd.DataFrame({"value": (np.arange(100) + 1).astype("int64")}) + df["D"] = pd.cut(df.value, bins=[0, 25, 50, 75, 100]) + + expected = pd.Series([11, pd.Interval(0, 25)], index=["value", "D"], name=10) + result = df.iloc[10] + tm.assert_series_equal(result, expected) + + expected = pd.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 = pd.Series([9, pd.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 = pd.Categorical( + ["a", "c", "b", "c", "c", "c", "c"], categories=["a", "b", "c"] + ) + idx = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) + values = [1, 2, 3, 4, 5, 6, 7] + df = pd.DataFrame({"cats": cats, "values": values}, index=idx) + + # the expected values + cats2 = pd.Categorical(["b", "c"], categories=["a", "b", "c"]) + idx2 = pd.Index(["j", "k"]) + values2 = [3, 4] + + # 2:4,: | "j":"k",: + exp_df = pd.DataFrame({"cats": cats2, "values": values2}, index=idx2) + + # :,"cats" | :,0 + exp_col = pd.Series(cats, index=idx, name="cats") + + # "j",: | 2,: + exp_row = pd.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, pd.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, pd.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, pd.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, pd.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, pd.CategoricalDtype) + + res_df = df.iloc[[2, 3]] + tm.assert_frame_equal(res_df, exp_df) + assert isinstance(res_df["cats"].dtype, pd.CategoricalDtype) + + res_col = df.iloc[:, 0] + tm.assert_series_equal(res_col, exp_col) + assert isinstance(res_col.dtype, pd.CategoricalDtype) + + res_df = df.iloc[:, slice(0, 2)] + tm.assert_frame_equal(res_df, df) + assert isinstance(res_df["cats"].dtype, pd.CategoricalDtype) + + res_df = df.iloc[:, [0, 1]] + tm.assert_frame_equal(res_df, df) + assert isinstance(res_df["cats"].dtype, pd.CategoricalDtype) + + def test_slicing_doc_examples(self): + # GH 7918 + cats = pd.Categorical( + ["a", "b", "b", "b", "c", "c", "c"], categories=["a", "b", "c"] + ) + idx = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) + values = [1, 2, 2, 2, 3, 4, 5] + df = pd.DataFrame({"cats": cats, "values": values}, index=idx) + + result = df.iloc[2:4, :] + expected = pd.DataFrame( + { + "cats": pd.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 = pd.Series(["category", "int64"], ["cats", "values"], dtype=object) + tm.assert_series_equal(result, expected) + + result = df.loc["h":"j", "cats"] + expected = pd.Series( + pd.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 = pd.DataFrame( + {"cats": pd.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 = pd.CategoricalIndex( + list("aaabbe"), categories=list("cabe"), name="B" + ) + expected = pd.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 = pd.CategoricalIndex(["a", "b", "c"]) + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index) + + # unique slice + res = df.loc[["a", "b"]] + exp_index = pd.CategoricalIndex(["a", "b"], categories=index.categories) + exp = pd.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 = pd.CategoricalIndex(["a", "a", "b"], categories=index.categories) + exp = pd.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 = pd.CategoricalIndex(["a", "b", "a"]) + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index) + + # unique slice + res = df.loc[["a", "b"]] + exp = pd.DataFrame( + {"A": [1, 3, 2], "B": [4, 6, 5]}, index=pd.CategoricalIndex(["a", "a", "b"]) + ) + tm.assert_frame_equal(res, exp, check_index_type=True) + + # duplicated slice + res = df.loc[["a", "a", "b"]] + exp = pd.DataFrame( + {"A": [1, 3, 1, 3, 2], "B": [4, 6, 4, 6, 5]}, + index=pd.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 = pd.CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde")) + df = pd.DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=index) + + res = df.loc[["a", "b"]] + exp = pd.DataFrame( + {"A": [1, 3, 2], "B": [5, 7, 6]}, + index=pd.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 = pd.DataFrame( + {"A": [1, 3, 1, 3, 2], "B": [5, 7, 5, 7, 6]}, + index=pd.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 = pd.CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde")) + df = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + index=list("ABC"), + columns=list("XYZ"), + ) + cdf = df.copy() + cdf.index = pd.CategoricalIndex(df.index) + cdf.columns = pd.CategoricalIndex(df.columns) + + expect = pd.Series(df.loc["A", :], index=cdf.columns, name="A") + tm.assert_series_equal(cdf.loc["A", :], expect) + + expect = pd.Series(df.loc[:, "X"], index=cdf.index, name="X") + tm.assert_series_equal(cdf.loc[:, "X"], expect) + + exp_index = pd.CategoricalIndex(list("AB"), categories=["A", "B", "C"]) + expect = pd.DataFrame( + df.loc[["A", "B"], :], columns=cdf.columns, index=exp_index + ) + tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect) + + exp_columns = pd.CategoricalIndex(list("XY"), categories=["X", "Y", "Z"]) + expect = pd.DataFrame( + df.loc[:, ["X", "Y"]], index=cdf.index, columns=exp_columns + ) + tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect) + + @pytest.mark.parametrize( + "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))] + ) + @pytest.mark.filterwarnings( + "ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning" + ) + def test_ix_categorical_index_non_unique(self, infer_string): + # non-unique + with pd.option_context("future.infer_string", infer_string): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + index=list("ABA"), + columns=list("XYX"), + ) + cdf = df.copy() + cdf.index = pd.CategoricalIndex(df.index) + cdf.columns = pd.CategoricalIndex(df.columns) + + exp_index = pd.CategoricalIndex(list("AA"), categories=["A", "B"]) + expect = pd.DataFrame(df.loc["A", :], columns=cdf.columns, index=exp_index) + tm.assert_frame_equal(cdf.loc["A", :], expect) + + exp_columns = pd.CategoricalIndex(list("XX"), categories=["X", "Y"]) + expect = pd.DataFrame(df.loc[:, "X"], index=cdf.index, columns=exp_columns) + tm.assert_frame_equal(cdf.loc[:, "X"], expect) + + expect = pd.DataFrame( + df.loc[["A", "B"], :], + columns=cdf.columns, + index=pd.CategoricalIndex(list("AAB")), + ) + tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect) + + expect = pd.DataFrame( + df.loc[:, ["X", "Y"]], + index=cdf.index, + columns=pd.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 = pd.DataFrame( + [[1, 2], [3, 4], [5, 6]], index=pd.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 + [pd.Interval(1, 4), pd.Interval(4, 6), pd.Interval(6, 9)], + [ + pd.Timestamp(2019, 1, 1), + pd.Timestamp(2019, 2, 1), + pd.Timestamp(2019, 3, 1), + ], + [pd.Timedelta(1, "D"), pd.Timedelta(2, "D"), pd.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 = pd.CategoricalIndex(idx_values, ordered=ordered) + df = pd.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 = pd.Series(["foo"], index=["A"], name=idx_values[0]) + tm.assert_series_equal(result, expected) + + # list selection + result = df.loc[idx_values[:2]] + expected = pd.DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"]) + tm.assert_frame_equal(result, expected) + + # slice selection + result = df.loc[sl] + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx) + tm.assert_frame_equal(result, expected) + + def test_getitem_categorical_with_nan(self): + # GH#41933 + ci = pd.CategoricalIndex(["A", "B", np.nan]) + + ser = pd.Series(range(3), index=ci) + + assert ser[np.nan] == 2 + assert ser.loc[np.nan] == 2 + + df = pd.DataFrame(ser) + assert df.loc[np.nan, 0] == 2 + assert df.loc[np.nan][0] == 2 + + def test_getitem_row_categorical_with_nan(self): + # GH#58954 + df = pd.DataFrame({"a": [1, 2], "b": pd.CategoricalIndex([1, None])}) + + res = df.iloc[1] + expected = pd.Series([2, np.nan], index=df.columns, name=1) + tm.assert_series_equal(res, expected) + + res = df.loc[1] + tm.assert_series_equal(res, expected) + + def test_getitem_row_categorical_with_nan_bool(self): + # GH#58954 + df = pd.DataFrame({"a": [True, False], "b": pd.CategoricalIndex([False, None])}) + + res = df.iloc[1] + expected = pd.Series([False, np.nan], index=df.columns, dtype=object, name=1) + tm.assert_series_equal(res, expected) + + res = df.loc[1] + tm.assert_series_equal(res, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_chaining_and_caching.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_chaining_and_caching.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ffc0e385a158fde6876e53cb410c962c4040be --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_chaining_and_caching.py @@ -0,0 +1,357 @@ +from string import ascii_letters + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestCaching: + @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 = pd.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): + # GH 7084 + # not updating cache on series setting with slices + expected = pd.DataFrame( + {"A": [600, 600, 600]}, index=pd.date_range("5/7/2014", "5/9/2014") + ) + out = pd.DataFrame( + {"A": [0, 0, 0]}, index=pd.date_range("5/7/2014", "5/9/2014") + ) + df = pd.DataFrame({"C": ["A", "A", "A"], "D": [100, 200, 300]}) + + # loop through df to update out + six = pd.Timestamp("5/7/2014") + eix = pd.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 = pd.DataFrame( + {"A": [0, 0, 0]}, index=pd.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"] + with tm.raises_chained_assignment_error(): + out[row["C"]][six:eix] = v + + tm.assert_frame_equal(out, out_original) + tm.assert_series_equal(out["A"], out_original["A"]) + + out = pd.DataFrame( + {"A": [0, 0, 0]}, index=pd.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"]) + + +class TestChaining: + def test_setitem_chained_setfault(self): + # GH6026 + data = ["right", "left", "left", "left", "right", "left", "timeout"] + + df = pd.DataFrame({"response": np.array(data)}) + mask = df.response == "timeout" + with tm.raises_chained_assignment_error(): + df.response[mask] = "none" + tm.assert_frame_equal(df, pd.DataFrame({"response": data})) + + recarray = np.rec.fromarrays([data], names=["response"]) + df = pd.DataFrame(recarray) + mask = df.response == "timeout" + with tm.raises_chained_assignment_error(): + df.response[mask] = "none" + tm.assert_frame_equal(df, pd.DataFrame({"response": data})) + + df = pd.DataFrame({"response": data, "response1": data}) + df_original = df.copy() + mask = df.response == "timeout" + with tm.raises_chained_assignment_error(): + df.response[mask] = "none" + tm.assert_frame_equal(df, df_original) + + # GH 6056 + expected = pd.DataFrame({"A": [np.nan, "bar", "bah", "foo", "bar"]}) + df = pd.DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])}) + with tm.raises_chained_assignment_error(): + df["A"].iloc[0] = np.nan + expected = pd.DataFrame({"A": ["foo", "bar", "bah", "foo", "bar"]}) + result = df.head() + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])}) + with tm.raises_chained_assignment_error(): + 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): + # work with the chain + df = pd.DataFrame(np.arange(4).reshape(2, 2), columns=list("AB"), dtype="int64") + df_original = df.copy() + + 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) + + @pytest.mark.arm_slow + def test_detect_chained_assignment_raises(self): + # test with the chaining + df = pd.DataFrame( + { + "A": pd.Series(range(2), dtype="int64"), + "B": np.array(np.arange(2, 4), dtype=np.float64), + } + ) + df_original = df.copy() + 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) + + @pytest.mark.arm_slow + def test_detect_chained_assignment_fails(self): + # Using a copy (the chain), fails + df = pd.DataFrame( + { + "A": pd.Series(range(2), dtype="int64"), + "B": np.array(np.arange(2, 4), dtype=np.float64), + } + ) + + with tm.raises_chained_assignment_error(): + df.loc[0]["A"] = -5 + + @pytest.mark.arm_slow + def test_detect_chained_assignment_doc_example(self): + # Doc example + df = pd.DataFrame( + { + "a": ["one", "one", "two", "three", "two", "one", "six"], + "c": pd.Series(range(7), dtype="int64"), + } + ) + + indexer = df.a.str.startswith("o") + with tm.raises_chained_assignment_error(): + df[indexer]["c"] = 42 + + @pytest.mark.arm_slow + def test_detect_chained_assignment_object_dtype(self): + df = pd.DataFrame( + {"A": pd.Series(["aaa", "bbb", "ccc"], dtype=object), "B": [1, 2, 3]} + ) + df_original = df.copy() + + with tm.raises_chained_assignment_error(): + df["A"][0] = 111 + tm.assert_frame_equal(df, df_original) + + @pytest.mark.arm_slow + def test_detect_chained_assignment_is_copy_pickle(self, temp_file): + # gh-5475: Make sure that is_copy is picked up reconstruction + df = pd.DataFrame({"A": [1, 2]}) + + path = str(temp_file) + 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_str(self): + idxs = np.random.default_rng(2).integers(len(ascii_letters), size=(100, 2)) + idxs.sort(axis=1) + strings = [ascii_letters[x[0] : x[1]] for x in idxs] + + df = pd.DataFrame(strings, columns=["letters"]) + 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_sorting(self): + df = pd.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 = pd.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): + # from SO: + # https://stackoverflow.com/questions/24054495/potential-bug-setting-value-for-undefined-column-using-iloc + df = pd.DataFrame(np.arange(0, 9), columns=["count"]) + df["group"] = "b" + df_original = df.copy() + with tm.raises_chained_assignment_error(): + df.iloc[0:5]["group"] = "a" + tm.assert_frame_equal(df, df_original) + + @pytest.mark.arm_slow + def test_detect_chained_assignment_changing_dtype(self): + # Mixed type setting but same dtype & changing dtype + df = pd.DataFrame( + { + "A": pd.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() + + with tm.raises_chained_assignment_error(): + df.loc[2]["D"] = "foo" + with tm.raises_chained_assignment_error(): + df.loc[2]["C"] = "foo" + tm.assert_frame_equal(df, df_original) + # TODO: Use tm.raises_chained_assignment_error() when PDEP-6 is enforced + with pytest.raises(TypeError, match="Invalid value"): + with tm.raises_chained_assignment_error(): + df["C"][2] = "foo" + + def test_setting_with_copy_bug(self): + # operating on a copy + df = pd.DataFrame( + {"a": list(range(4)), "b": list("ab.."), "c": ["a", "b", np.nan, "d"]} + ) + df_original = df.copy() + mask = pd.isna(df.c) + with tm.raises_chained_assignment_error(): + df[["c"]][mask] = df[["b"]][mask] + tm.assert_frame_equal(df, df_original) + + def test_setting_with_copy_bug_no_warning(self): + # invalid warning as we are returning a new object + # GH 8730 + df1 = pd.DataFrame( + {"x": pd.Series(["a", "b", "c"]), "y": pd.Series(["d", "e", "f"])} + ) + df2 = df1[["x"]] + + # this should not raise + df2["y"] = ["g", "h", "i"] + + def test_detect_chained_assignment_warnings_errors(self): + df = pd.DataFrame({"A": ["aaa", "bbb", "ccc"], "B": [1, 2, 3]}) + with tm.raises_chained_assignment_error(): + df.loc[0]["A"] = 111 + + @pytest.mark.parametrize("rhs", [3, pd.DataFrame({0: [1, 2, 3, 4]})]) + def test_detect_chained_assignment_warning_stacklevel(self, rhs): + # GH#42570 + df = pd.DataFrame(np.arange(25).reshape(5, 5)) + df_original = df.copy() + chained = df.loc[:3] + chained[2] = rhs + tm.assert_frame_equal(df, df_original) + + def test_chained_getitem_with_lists(self): + # GH6394 + # Regression in chained getitem indexing with embedded list-like from + # 0.12 + + df = pd.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 = pd.DataFrame( + np.zeros((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + ) + 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): + # 10264 + df = pd.DataFrame( + np.zeros((5, 5), dtype="int64"), + columns=["a", "b", "c", "d", "e"], + index=range(5), + ) + df["f"] = 0 + df_orig = df.copy() + with pytest.raises(ValueError, match="read-only"): + df.f.values[3] = 1 + tm.assert_frame_equal(df, df_orig) + + def test_iloc_setitem_chained_assignment(self): + # GH#3970 + df = pd.DataFrame({"aa": range(5), "bb": [2.2] * 5}) + df["cc"] = 0.0 + + ck = [True] * len(df) + + with tm.raises_chained_assignment_error(): + df["bb"].iloc[0] = 0.13 + + # GH#3970 this lookup used to break the chained setting to 0.15 + df.iloc[ck] + + with tm.raises_chained_assignment_error(): + df["bb"].iloc[0] = 0.15 + + assert df["bb"].iloc[0] == 2.2 + + def test_getitem_loc_assignment_slice_state(self): + # GH 13569 + df = pd.DataFrame({"a": [10, 20, 30]}) + with tm.raises_chained_assignment_error(): + df["a"].loc[4] = 40 + tm.assert_frame_equal(df, pd.DataFrame({"a": [10, 20, 30]})) + tm.assert_series_equal(df["a"], pd.Series([10, 20, 30], name="a")) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_check_indexer.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_check_indexer.py new file mode 100644 index 0000000000000000000000000000000000000000..975a31b873792c6afe59a23e5fef43b56ce7e46e --- /dev/null +++ b/venv/lib/python3.14/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/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_coercion.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_coercion.py new file mode 100644 index 0000000000000000000000000000000000000000..af6ba2660f78d42c77a3e723a5aa30d1b95dcefd --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_coercion.py @@ -0,0 +1,900 @@ +from __future__ import annotations + +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest + +from pandas.compat import ( + IS64, + is_platform_windows, +) +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + +############################################################### +# Index / Series common tests which may trigger dtype coercions +############################################################### + + +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=pd.Index(list("abcd"), dtype=object)) + assert obj.index.dtype == object + + exp_index = pd.Index([*list("abcd"), val], dtype=object) + 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"), dtype=object) + assert obj.dtype == object + + exp = pd.Index(["a", coerced_val, "b", "c", "d"], dtype=object) + 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), + # When float_numpy_dtype=float32, this is not the case + # see the correction below + (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 + + if dtype == "float32" and coerced_val == 1.1: + # Hack, in the 2nd test case, since 1.1 can be losslessly cast to float32 + # the expected dtype will be float32 if the original dtype was float32 + coerced_dtype = np.float32 + 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").as_unit("s"), "datetime64[ns]"), + ( + pd.Timestamp("2012-01-01", tz="US/Eastern").as_unit("s"), + "datetime64[ns, US/Eastern]", + ), + ], + ids=["datetime64", "datetime64tz"], + ) + @pytest.mark.parametrize( + "insert_value", + [ + pd.Timestamp("2012-01-01").as_unit("s"), + pd.Timestamp("2012-01-01", tz="Asia/Tokyo").as_unit("s"), + 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 + ).as_unit("ns") + 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, + ).as_unit("ns") + self._assert_insert_conversion(obj, fill_val, exp, exp_dtype) + + if fill_val.tz: + # mismatched tzawareness + ts = pd.Timestamp("2012-01-01").as_unit("s") + 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").as_unit("s") + 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").as_unit("s") + 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[us]" + + # 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[us]" + ) + + for item in [pd.Timestamp("2012-01-01").as_unit("s"), 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").as_unit("s"), + pd.Timestamp("2012-01-01").as_unit("s"), + 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"), dtype=object) + 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, index_or_series, fill_val, exp_dtype): + klass = index_or_series + + 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").as_unit("s"), "datetime64[ns]"), + (pd.Timestamp("2012-01-01", tz="US/Eastern").as_unit("s"), 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", unit="ns")._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).as_unit("us"), 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" + + def _assert_fillna_conversion(self, original, value, expected, expected_dtype): + """test coercion triggered by fillna""" + target = original.copy() + # GH#45153 filling with incompatible value requiring casting is deprecated + warn = None + if expected_dtype != target.dtype: + warn = Pandas4Warning + with tm.assert_produces_warning(warn, match="fill value"): + 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"], dtype=object) + assert obj.dtype == object + + exp = klass(["a", fill_val, "c", "d"], dtype=object) + 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").as_unit("s"), "datetime64[s]"), + (pd.Timestamp("2012-01-01", tz="US/Eastern").as_unit("s"), 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").as_unit("s"), + pd.NaT, + pd.Timestamp("2011-01-03").as_unit("s"), + pd.Timestamp("2011-01-04").as_unit("s"), + ] + ) + assert obj.dtype == "datetime64[s]" + + exp = klass( + [ + pd.Timestamp("2011-01-01").as_unit("s"), + fill_val, + pd.Timestamp("2011-01-03").as_unit("s"), + pd.Timestamp("2011-01-04").as_unit("s"), + ] + ) + 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").as_unit("s"), + "datetime64[s, US/Eastern]", + ), + (pd.Timestamp("2012-01-01").as_unit("s"), object), + # pre-2.0 with a mismatched tz we would get object result + ( + pd.Timestamp("2012-01-01", tz="Asia/Tokyo").as_unit("s"), + "datetime64[s, 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).as_unit("s"), + pd.NaT, + pd.Timestamp("2011-01-03", tz=tz).as_unit("s"), + pd.Timestamp("2011-01-04", tz=tz).as_unit("s"), + ] + ) + assert obj.dtype == "datetime64[s, 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).as_unit("s"), + fv, + pd.Timestamp("2011-01-03", tz=tz).as_unit("s"), + pd.Timestamp("2011-01-04", tz=tz).as_unit("s"), + ] + ) + 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").as_unit("s"), + pd.Timestamp("2012-01-01").as_unit("s"), + 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").as_unit("s"), + pd.Timestamp("2012-01-01").as_unit("s"), + 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").as_unit("s"), + pd.Timestamp("2011-01-03").as_unit("s"), + ] + + 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).as_unit("s"), + pd.Timestamp("2011-01-03", tz=tz).as_unit("s"), + ] + + rep["timedelta64[us]"] = [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[us]", + ] + ) + 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[us]", + ], + 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], strict=True)) + 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, to_key, from_key, replacer): + index = pd.Index([3, 4], name="xxx") + obj = pd.Series(self.rep[from_key], index=index, name="yyy") + obj = obj.astype(from_key) + 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 + + 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") + + result = obj.replace(replacer) + tm.assert_series_equal(result, exp, check_dtype=False) + + @pytest.mark.parametrize( + "to_key", + ["timedelta64[us]", "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, to_key, from_key, replacer, using_infer_string + ): + index = pd.Index([3, 4], name="xyz") + obj = pd.Series(self.rep[from_key], index=index, name="yyy").dt.as_unit("ns") + assert obj.dtype == from_key + + exp = pd.Series(self.rep[to_key], index=index, name="yyy") + if using_infer_string and to_key == "object": + assert exp.dtype == "string" + else: + assert exp.dtype == to_key + + result = obj.replace(replacer) + tm.assert_series_equal(result, exp, check_dtype=False) + + @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, to_key, from_key, replacer): + index = pd.Index([3, 4], name="xyz") + obj = pd.Series(self.rep[from_key], index=index, name="yyy").dt.as_unit("ns") + assert obj.dtype == from_key + + 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) + elif to_key == from_key: + exp = exp.dt.as_unit("ns") + + result = obj.replace(replacer) + tm.assert_series_equal(result, exp, check_dtype=False) + + @pytest.mark.xfail(reason="Test not implemented") + def test_replace_series_period(self): + raise NotImplementedError diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_datetime.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_datetime.py new file mode 100644 index 0000000000000000000000000000000000000000..89cb5cee1a5c75dd1135d5605db46212709523d5 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_datetime.py @@ -0,0 +1,206 @@ +import re + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndex: + def test_get_loc_naive_dti_aware_str_deprecated(self): + # GH#46903 + ts = pd.Timestamp("20130101")._value + dti = pd.DatetimeIndex([ts + 50 + i for i in range(100)]) + ser = pd.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 = pd.Index( + pd.date_range("20130101", periods=3, tz="US/Eastern"), name="foo" + ) + dr = pd.date_range("20130110", periods=3) + df = pd.DataFrame({"A": idx, "B": dr}) + df["C"] = idx + df.iloc[1, 1] = pd.NaT + df.iloc[1, 2] = pd.NaT + + expected = pd.Series( + [pd.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 = pd.DataFrame( + {"a": pd.date_range("2014-01-01", periods=10, tz="UTC", unit="ns")} + ) + result = df.iloc[5] + expected = pd.Series( + [pd.Timestamp("2014-01-06 00:00:00+0000", tz="UTC")], + index=["a"], + name=5, + dtype="M8[ns, UTC]", + ) + 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 = pd.Series( + [pd.Timestamp("2016-03-30 14:35:25", tz="Europe/Brussels")] + ).to_frame() + + df = pd.concat([df, df]).reset_index(drop=True) + expected = pd.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 = pd.date_range("2015-01-01", periods=2, tz="utc") + + ser = pd.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 = pd.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 = pd.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 = pd.DataFrame({"a": [10]}, index=index) + result = df.loc[df.index[0]] + expected = pd.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 = pd.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=[pd.Timestamp(x) for x in keys], + ) + result = obj[keys[1] : keys[2]] + expected = frame_or_series( + [2, 3], + index=[ + pd.Timestamp(keys[1]), + pd.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=pd.date_range("2020", freq="D", periods=5).astype( + "timestamp[us][pyarrow]" + ), + ) + result = obj.loc[obj.index[:-3]] + expected = frame_or_series( + range(2), + index=pd.date_range("2020", freq="D", periods=2).astype( + "timestamp[us][pyarrow]" + ), + ) + tm.assert_equal(result, expected) + + +def test_loc_setitem_integer_on_datetimeindex_no_error(): + # GH#22040 - loc with integer key on DatetimeIndex should not + # raise TypeError (it enlarges the DataFrame with the new key) + index = pd.date_range("2018-01-01", periods=2) + df = pd.DataFrame({"col1": [1.0, 2.0], "col2": [3.0, 4.0]}, index=index) + # This previously raised TypeError: cannot insert DatetimeIndex + # with incompatible label + df.loc[0, "col1"] = 0 + expected = pd.DataFrame( + {"col1": [1.0, 2.0, 0.0], "col2": [3.0, 4.0, np.nan]}, + index=pd.Index([pd.Timestamp("2018-01-01"), pd.Timestamp("2018-01-02"), 0]), + ) + tm.assert_frame_equal(df, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_floats.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_floats.py new file mode 100644 index 0000000000000000000000000000000000000000..068fe21047b788212781475a317fd223cbba7a65 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_floats.py @@ -0,0 +1,674 @@ +import numpy as np +import pytest + +from pandas.compat import PY315 + +import pandas as pd +import pandas._testing as tm + + +def gen_obj(klass, index): + if klass is pd.Series: + obj = pd.Series(np.arange(len(index)), index=index) + else: + obj = pd.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, pd.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", + [ + pd.Index(list("abcde")), + pd.Index(list("abcde"), dtype="category"), + pd.date_range("2020-01-01", periods=5), + pd.timedelta_range("1 day", periods=5), + pd.period_range("2020-01-01", periods=5), + ], + ) + def test_scalar_non_numeric(self, index, frame_or_series, indexer_sl): + # GH 4892 + # float_indexers should raise exceptions + # on appropriate Index types & accessors + + s = gen_obj(frame_or_series, index) + + # 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", + [ + pd.Index(list("abcde")), + pd.Index(list("abcde"), dtype="category"), + pd.date_range("2020-01-01", periods=5), + pd.timedelta_range("1 day", periods=5), + pd.period_range("2020-01-01", periods=5), + ], + ) + def test_scalar_non_numeric_series_fallback(self, index): + # starting in 3.0, integer keys are always treated as labels, no longer + # fall back to positional. + s = pd.Series(np.arange(len(index)), index=index) + + with pytest.raises(KeyError, match="3"): + s[3] + with pytest.raises(KeyError, match="^3.0$"): + s[3.0] + + def test_scalar_with_mixed(self, indexer_sl): + s2 = pd.Series([1, 2, 3], index=["a", "b", "c"]) + s3 = pd.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: + # as of 3.0, __getitem__ no longer falls back to positional + with pytest.raises(KeyError, match="^1$"): + s3[1] + + 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", [pd.Index(np.arange(5), dtype=np.int64), pd.RangeIndex(5)] + ) + def test_scalar_integer(self, index, 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 + 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, pd.Series): + + def compare(x, y): + assert x == y + + expected = 100 + else: + compare = tm.assert_series_equal + if getitem: + expected = pd.Series(100, index=range(len(obj)), name=3) + else: + expected = pd.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", [pd.Index(np.arange(5), dtype=np.int64), pd.RangeIndex(5)] + ) + def test_scalar_integer_contains_float(self, index, frame_or_series): + # contains + # integer index + 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 = pd.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", + [ + pd.Index(list("abcde"), dtype=object), + pd.date_range("2020-01-01", periods=5), + pd.timedelta_range("1 day", periods=5), + pd.period_range("2020-01-01", periods=5), + ], + ) + @pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]) + def test_slice_non_numeric(self, index, idx, frame_or_series, indexer_sli): + # GH 4892 + # float_indexers should raise exceptions + # on appropriate Index types & accessors + + 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 + if PY315: + msg = "slice indices must be integers or have an __index__ method" + else: + 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 [ + (pd.Index(np.arange(5, dtype=np.int64)), False), + (pd.RangeIndex(5), False), + (pd.Index(np.arange(5, dtype=np.int64) + 10), True), + ]: + # s is an in-range index + s = pd.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 = pd.Series(range(2, 6), index=range(2, 6)) + + result = s[2:4] + expected = s.iloc[2:4] + tm.assert_series_equal(result, expected) + + klass = pd.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", [pd.Index(np.arange(5), dtype=np.int64), pd.RangeIndex(5)] + ) + def test_slice_integer_frame_getitem(self, index): + # similar to above, but on the getitem dim (of a DataFrame) + s = pd.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", [pd.Index(np.arange(5), dtype=np.int64), pd.RangeIndex(5)] + ) + def test_float_slice_getitem_with_integer_index_raises(self, idx, index): + # similar to above, but on the getitem dim (of a DataFrame) + s = pd.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 = pd.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 = pd.Index([1.5, 2, 3, 4.5, 5]) + s = pd.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 = pd.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 = pd.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 = pd.Series([2, 0], index=pd.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 = pd.Series([2, 0], index=pd.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) + + # all should return the same as we are slicing 'the same' + 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(result2, result3) + tm.assert_series_equal(result2, result4) + + # 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, pd.Series([1, 2], index=[2.5, 5.0])) + + result = indexer_sl(s)[[2.5]] + tm.assert_series_equal(result, pd.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 = pd.Series(ser, dtype=dtype) + result = s.value_counts() + assert result.index.dtype == dtype + str(result) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_iat.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_iat.py new file mode 100644 index 0000000000000000000000000000000000000000..1bcab6e83aa8a69b9f8797dff05687a397530af1 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_iat.py @@ -0,0 +1,26 @@ +import numpy as np + +import pandas as pd + + +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 = pd.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 = pd.period_range("1/1/2001", periods=10) + ser = pd.Series(np.random.default_rng(2).standard_normal(10), index=index) + expected = ser[index[0]] + result = ser.iat[0] + assert expected == result diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_iloc.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_iloc.py new file mode 100644 index 0000000000000000000000000000000000000000..66b94c3376d839b2dfdd79159da50798f46d2a4c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_iloc.py @@ -0,0 +1,2526 @@ +"""test positional based indexing with iloc""" + +from array import array as std_array +from collections import deque +from datetime import datetime +import re + +import numpy as np +import pytest + +from pandas.errors import IndexingError +import pandas.util._test_decorators as td + +import pandas as pd +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 DuckSequence: + """A sequence implementing only __len__/__getitem__, so not is_list_like.""" + + def __init__(self, data) -> None: + self.data = list(data) + + def __len__(self) -> int: + return len(self.data) + + def __getitem__(self, key): + return self.data[key] + + +class GetitemOnly: + """Subscriptable but unsized, so np.asarray treats it as a scalar.""" + + def __getitem__(self, key): + return key + + +class TestiLoc: + @pytest.mark.parametrize("key", [2, -1, [0, 1, 2]]) + @pytest.mark.parametrize( + "index", + [ + pd.Index(list("abcd"), dtype=object), + pd.Index([2, 4, "null", 8], dtype=object), + pd.date_range("20130101", periods=4), + pd.Index(range(0, 8, 2), dtype=np.float64), + pd.Index([]), + ], + ) + def test_iloc_getitem_int_and_list_int(self, key, frame_or_series, index, request): + obj = frame_or_series(range(len(index)), index=index) + 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], + pd.Index(range(3)), + np.asarray([0, 1, 2]), + ], + ) + def test_iloc_setitem_fullcol_categorical(self, indexer_li, key): + frame = pd.DataFrame({0: range(3)}, dtype=object) + + cat = pd.Categorical(["alpha", "beta", "gamma"]) + + assert frame._mgr.blocks[0]._can_hold_element(cat) + + df = frame.copy() + orig_vals = df.values + + indexer_li(df)[key, 0] = cat + + expected = pd.DataFrame({0: cat}).astype(object) + 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 = pd.DataFrame({0: np.array([0, 1, 2], dtype=object), 1: range(3)}) + df = frame.copy() + indexer_li(df)[key, 0] = cat + expected = pd.DataFrame( + {0: pd.Series(cat.astype(object), dtype=object), 1: range(3)} + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_iloc_setitem_ea_inplace( + self, frame_or_series, index_or_series_or_array, has_ref + ): + # GH#38952 Case with not setting a full column + # IntegerArray without NAs + arr = pd.array([1, 2, 3, 4]) + obj = frame_or_series(arr.to_numpy("i8")) + if has_ref: + view = obj[:] # noqa: F841 + + if frame_or_series is pd.Series: + values = obj.values + else: + values = obj._mgr.blocks[0].values + + if frame_or_series is pd.Series: + obj.iloc[:2] = index_or_series_or_array(arr[2:]) + else: + obj.iloc[:2, 0] = index_or_series_or_array(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 not has_ref: + if frame_or_series is pd.Series: + assert obj.values is not values + assert np.shares_memory(obj.values, 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 = pd.Index([1, 2, 1]) + ser = pd.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 = pd.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 + dfl = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("AB") + ) + tm.assert_frame_equal( + dfl.iloc[:, 2:3], + pd.DataFrame( + index=dfl.index, columns=pd.Index([], dtype=dfl.columns.dtype) + ), + ) + tm.assert_frame_equal(dfl.iloc[:, 1:3], dfl.iloc[:, [1]]) + tm.assert_frame_equal(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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.Series(["a"], index=["A"]) + result = expected.iloc[[-1]] + tm.assert_series_equal(result, expected) + + def test_iloc_getitem_dups(self): + # GH 6766 + df1 = pd.DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}]) + df2 = pd.DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}]) + df = pd.concat([df1, df2], axis=1) + + # cross-sectional indexing + result = df.iloc[0, 0] + assert pd.isna(result) + + result = df.iloc[0, :] + expected = pd.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 = pd.DataFrame( + [ + {"A": 1, "B": 2, "C": 3}, + {"A": 100, "B": 200, "C": 300}, + {"A": 1000, "B": 2000, "C": 3000}, + ] + ) + + expected = pd.DataFrame([{"A": 1, "B": 2, "C": 3}]) + tm.assert_frame_equal(df.iloc[[0]], expected) + + expected = pd.DataFrame( + [{"A": 1, "B": 2, "C": 3}, {"A": 100, "B": 200, "C": 300}] + ) + tm.assert_frame_equal(df.iloc[[0, 1]], expected) + + expected = pd.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 = pd.DataFrame( + [ + {"A": 1, "B": 2, "C": 3}, + {"A": 100, "B": 200, "C": 300}, + {"A": 1000, "B": 2000, "C": 3000}, + ] + ) + + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame( + [ + {"A": 1, "B": 2, "C": 3}, + {"A": 100, "B": 200, "C": 300}, + {"A": 1000, "B": 2000, "C": 3000}, + ] + ) + + expected = pd.DataFrame( + [{"A": 1, "B": 2, "C": 3}, {"A": 100, "B": 200, "C": 300}] + ) + result = df.iloc[:2] + tm.assert_frame_equal(result, expected) + + expected = pd.DataFrame([{"A": 100, "B": 200}], index=[1]) + result = df.iloc[1:2, 0:2] + tm.assert_frame_equal(result, expected) + + expected = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=["A", "A", "B", "B"], + ) + df2 = pd.DataFrame( + np.random.default_rng(2).integers(0, 10, size=20).reshape(10, 2), + columns=["A", "C"], + ) + + # axis=1 + df = pd.concat([df1, df2], axis=1) + tm.assert_frame_equal(df.iloc[:, :4], df1) + tm.assert_frame_equal(df.iloc[:, 4:], df2) + + df = pd.concat([df2, df1], axis=1) + tm.assert_frame_equal(df.iloc[:, :2], df2) + tm.assert_frame_equal(df.iloc[:, 2:], df1) + + exp = pd.concat([df2, df1.iloc[:, [0]]], axis=1) + tm.assert_frame_equal(df.iloc[:, 0:3], exp) + + # axis=0 + df = pd.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) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_iloc_setitem(sel, has_ref): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), + index=np.arange(0, 8, 2), + columns=np.arange(0, 12, 3), + ) + if has_ref: + view = df[:] # noqa: F841 + + 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 = pd.Series(0, index=[4, 5, 6]) + s.iloc[1:2] += 1 + expected = pd.Series([0, 1, 0], index=[4, 5, 6]) + tm.assert_series_equal(s, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_iloc_setitem_axis_argument(self, has_ref): + # GH45032 + df = pd.DataFrame([[6, "c", 10], [7, "d", 11], [8, "e", 12]]) + df[1] = df[1].astype(object) + if has_ref: + view = df[:] + expected = pd.DataFrame([[6, "c", 10], [7, "d", 11], [5, 5, 5]]) + expected[1] = expected[1].astype(object) + df.iloc(axis=0)[2] = 5 + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame([[6, "c", 10], [7, "d", 11], [8, "e", 12]]) + df[1] = df[1].astype(object) + if has_ref: + view = df[:] # noqa: F841 + expected = pd.DataFrame([[6, "c", 5], [7, "d", 5], [8, "e", 5]]) + expected[1] = expected[1].astype(object) + df.iloc(axis=1)[2] = 5 + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_iloc_setitem_list(self, has_ref): + # setitem with an iloc list + df = pd.DataFrame( + np.arange(9).reshape((3, 3)), index=["A", "B", "C"], columns=["A", "B", "C"] + ) + if has_ref: + view = df[:] # noqa: F841 + df.iloc[[0, 1], [1, 2]] + df.iloc[[0, 1], [1, 2]] += 100 + + expected = pd.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 = pd.Series([0, 1, 2, 3]) + expected = pd.Series([0, -1, -2, 3]) + + s = s_orig.copy() + s.iloc[pd.Series([1, 2])] = [-1, -2] + tm.assert_series_equal(s, expected) + + s = s_orig.copy() + s.iloc[pd.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 = pd.DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}]) + df2 = pd.DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}]) + df = pd.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 = pd.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): + # Same as the "assign back to self" check in test_iloc_setitem_dups + # but on a DataFrame with multiple blocks + df = pd.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") + assert len(df._mgr.blocks) == 1 + + # if the assigned values cannot be held by existing integer arrays, + # we raise + with pytest.raises(TypeError, match="Invalid value"): + df.iloc[:, 0] = df.iloc[:, 0] + 0.5 + + 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) + + def test_iloc_setitem_unordered_column_indexer_referenced_block(self): + # GH#65446 assignment was silently lost when the block was referenced + # by another object and the column indexer was not sorted + df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}) + df_orig = df.copy() + ref = df[["A", "B"]] + df.iloc[:, [1, 0]] = pd.DataFrame({"A": [10, 20], "B": [30, 40]}) + df._mgr._verify_integrity() + expected = pd.DataFrame({"A": [30, 40], "B": [10, 20]}) + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(ref, df_orig) + + def test_iloc_setitem_duplicate_column_indexer_referenced_block(self): + # GH#65446 + df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}) + df_orig = df.copy() + ref = df[["A", "B"]] + df.iloc[:, [0, 0]] = np.array([[10, 30], [20, 40]]) + df._mgr._verify_integrity() + expected = pd.DataFrame({"A": [30, 40], "B": [3, 4]}) + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(ref, df_orig) + + def test_iloc_setitem_frame_swap_columns(self): + # GH#65446 positional swap when the RHS shares data with the target + df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}) + df.iloc[:, [1, 0]] = df[["A", "B"]] + expected = pd.DataFrame({"A": [3, 4], "B": [1, 2]}) + tm.assert_frame_equal(df, expected) + + def test_iloc_setitem_unordered_row_and_column_indexer_referenced_block(self): + # GH#65446 a list row indexer combined with an unsorted column indexer + # must set the full cross product + df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}) + df_orig = df.copy() + ref = df[["A", "B"]] + df.iloc[[1, 0], [1, 0]] = np.array([[10, 20], [30, 40]]) + df._mgr._verify_integrity() + expected = pd.DataFrame({"A": [40, 20], "B": [30, 10]}) + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(ref, df_orig) + + @pytest.mark.parametrize("dtype", ["float64", "M8[s]"]) + def test_iloc_setitem_reversed_slice_column_indexer_referenced_block(self, dtype): + # GH#65446 a slice column indexer takes the cross product with the + # row indexer; on a referenced frame it became an array instead + df = pd.DataFrame( + np.arange(12, dtype="i8").reshape(4, 3).astype(dtype), columns=list("abc") + ) + df_orig = df.copy() + ref = df[["a", "b", "c"]] + value = np.arange(100, 106, dtype="i8").reshape(2, 3).astype(dtype) + df.iloc[[2, 0], ::-1] = value + df._mgr._verify_integrity() + expected = df_orig.copy() + expected.iloc[2] = value[0, ::-1] + expected.iloc[0] = value[1, ::-1] + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(ref, df_orig) + + @pytest.mark.parametrize("dtype", ["float64", "M8[s]"]) + @pytest.mark.parametrize( + "key, shape", + [ + (([2, 0], slice(0, 2)), (2, 2)), + (([2, 0], slice(2, None, -2)), (2, 2)), + # these keys reject a 2-D value even on an unreferenced frame + ((range(2, 0, -1), [0, 2]), None), + (((2, 1), [0, 2]), None), + ((pd.array([2, 1], dtype="Int64"), [0, 2]), None), + ((np.array([2, 1]), range(0, 3, 2)), None), + ((np.array([2, 1]), pd.array([0, 2], dtype="Int64")), None), + ((np.array([0, 2]), None), None), + (([2, 1, 0], Ellipsis), (3, 3)), + ((Ellipsis, [2, 0, 1]), (4, 3)), + ((np.array([True, False, True, False]), slice(None, None, -1)), (2, 3)), + ((np.array([[1, 0]]), slice(None, None, -1)), (2, 3)), + ], + ) + def test_iloc_setitem_referenced_block_matches_unreferenced( + self, key, shape, dtype + ): + # GH#65446 a distinct value per cell, so a transposed or reordered + # write shows up; a scalar still tells a cross product from a + # pointwise write + df = pd.DataFrame( + np.arange(12, dtype="i8").reshape(4, 3).astype(dtype), columns=list("abc") + ) + df_orig = df.copy() + if shape is None: + value = df_orig.iloc[3, 1] + else: + value = np.arange(100, 100 + np.prod(shape), dtype="i8").reshape(shape) + value = value.astype(dtype) + + expected = df.copy() + expected.iloc[key] = value + ref = df[["a", "b", "c"]] + df.iloc[key] = value + df._mgr._verify_integrity() + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(ref, df_orig) + + def test_loc_setitem_boolean_row_mask_reversed_slice_referenced_block(self): + # GH#65446 a reversed label slice reaches the same path through loc + df = pd.DataFrame( + np.arange(12).reshape(4, 3).astype("float64"), columns=list("abc") + ) + df_orig = df.copy() + ref = df[["a", "b", "c"]] + df.loc[[True, False, True, False], "c":"a":-1] = 99.0 + df._mgr._verify_integrity() + expected = df_orig.copy() + expected.iloc[[0, 2]] = 99.0 + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(ref, df_orig) + + # 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 = pd.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 = pd.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 = pd.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): + # multi axis slicing issue with single block + # surfaced in GH 6059 + + arr = np.random.default_rng(2).standard_normal((6, 4)) + index = pd.date_range("20130101", periods=6) + columns = list("ABCD") + df = pd.DataFrame(arr, index=index, columns=columns) + + # defines ref_locs + df.describe() + + result = df.iloc[3:5, 0:2] + + expected = pd.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] + + expected = pd.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 = pd.DataFrame(arr, index=index, columns=columns) + + df._mgr.blocks[0].mgr_locs + result = df.iloc[1:5, 2:4] + expected = pd.DataFrame(arr[1:5, 2:4], index=index[1:5], columns=columns[2:4]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_iloc_setitem_series(self, has_ref): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + index=list("abcdefghij"), + columns=list("ABCD"), + ) + if has_ref: + view = df[:] # noqa: F841 + + 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 = pd.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 = pd.Series([-1] * 6) + s.iloc[0::2] = [0, 2, 4] + s.iloc[1::2] = [1, 3, 5] + result = s + expected = pd.Series([0, 1, 2, 3, 4, 5]) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_iloc_setitem_list_of_lists(self, has_ref): + # GH 7551 + # list-of-list is set incorrectly in mixed vs. single dtyped frames + df = pd.DataFrame( + {"A": np.arange(5, dtype="int64"), "B": np.arange(5, 10, dtype="int64")} + ) + if has_ref: + view = df[:] + df.iloc[2:4] = [[10, 11], [12, 13]] + expected = pd.DataFrame({"A": [0, 1, 10, 12, 4], "B": [5, 6, 11, 13, 9]}) + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame( + {"A": ["a", "b", "c", "d", "e"], "B": np.arange(5, 10, dtype="int64")} + ) + if has_ref: + view = df[:] # noqa: F841 + df.iloc[2:4] = [["x", 11], ["y", 13]] + expected = pd.DataFrame( + {"A": ["a", "b", "x", "y", "e"], "B": [5, 6, 11, 13, 9]} + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + @pytest.mark.parametrize("value", [[[1], [2, 3]], [[2, 3], [1]]]) + def test_setitem_ragged_list_of_lists_raises(self, indexer, value): + # GH#64229 + df = pd.DataFrame({"a": [0.0, 0.0], "b": [0, 0], "c": [0.0, 0.0]}) + with pytest.raises(ValueError, match="Must have equal len keys"): + if indexer == "loc": + df.loc[:, ["a", "c"]] = value + else: + df.iloc[:, [0, 2]] = value + + @pytest.mark.parametrize( + "box", + [np.array, pd.Series, pd.Index, pd.array], + ids=["ndarray", "Series", "Index", "pd.array"], + ) + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + @pytest.mark.parametrize("nrows", [2, 3]) + def test_setitem_split_path_list_of_arrays_is_2d(self, indexer, nrows, box): + # GH#64230 a list of 1-D array-likes is a 2D value (a list of rows), + # just like a list of lists / an ndarray; the split path used to + # transpose it into columns instead. + df = pd.DataFrame( + { + "a": np.zeros(nrows), + "b": np.zeros(nrows, dtype="int64"), + "c": np.zeros(nrows), + } + ) + rows = [[2 * i + 1, 2 * i + 2] for i in range(nrows)] + value = [box(row) for row in rows] + if indexer == "loc": + df.loc[:, ["a", "c"]] = value + else: + df.iloc[:, [0, 2]] = value + + arr = np.array(rows, dtype="float64") + expected = pd.DataFrame( + {"a": arr[:, 0], "b": np.zeros(nrows, dtype="int64"), "c": arr[:, 1]} + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "value", + [ + [pd.Series([1, 2], index=[5, 6]), pd.Series([3, 4], index=["p", "q"])], + # only value[0] decides that this is 2D, but every row gets unwrapped + [[1, 2], pd.Series([3, 4], index=["p", "q"])], + [pd.Index([1, 2]), pd.Series([3, 4], index=["p", "q"])], + # labels that DO resolve positionally, to a different answer: this + # catches a label-based read by the value, not by an exception + [pd.Series([1, 2], index=[1, 0]), pd.Series([3, 4], index=[1, 0])], + ], + ids=["all-series", "list-first", "index-first", "reversed-labels"], + ) + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_series_not_aligned(self, indexer, value): + # GH#64230 Series rows are read positionally, not by label + df = pd.DataFrame({"a": [0.0, 0.0], "b": np.zeros(2, dtype="int64")}) + if indexer == "loc": + df.loc[:, ["a", "b"]] = value + else: + df.iloc[:, [0, 1]] = value + + expected = pd.DataFrame({"a": [1.0, 3.0], "b": [2, 4]}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "box", + [np.array, pd.Series, pd.Index, pd.array], + ids=["ndarray", "Series", "Index", "pd.array"], + ) + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_arrays_single_column(self, indexer, box): + # GH#64230 a list of 1-D array-likes targeting a single column is a + # shape mismatch, same as a list of lists; unlike mismatched-length + # tuples (GH#65264) arrays are not scalar-like, so no per-cell storage + df = pd.DataFrame({"a": np.zeros(2, dtype=object), "b": [0, 0]}) + value = [box([1, 2]), box([3, 4])] + msg = "Must have equal len keys and value when setting with an ndarray" + with pytest.raises(ValueError, match=msg): + if indexer == "loc": + df.loc[:, ["a"]] = value + else: + df.iloc[:, [0]] = value + + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_mismatched_tuples_single_column(self, indexer): + # GH#37629 mismatched-length tuples into a single column are cell values, + # even when the column key is a list rather than a scalar label + df = pd.DataFrame({"a": np.zeros(2, dtype=object), "b": [0, 0]}) + value = [(1, 2), (3, 4)] + if indexer == "loc": + df.loc[:, ["a"]] = value + else: + df.iloc[:, [0]] = value + + expected = pd.DataFrame( + {"a": pd.Series([(1, 2), (3, 4)], dtype=object), "b": [0, 0]} + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_mismatched_tuples_arrow_list_column(self, indexer): + # GH#65264 the per-cell hatch keys on the target being a single column, + # not on it being object dtype + pa = pytest.importorskip("pyarrow") + dtype = pd.ArrowDtype(pa.list_(pa.int64())) + df = pd.DataFrame({"a": pd.array([[9], [9]], dtype=dtype), "b": [0, 0]}) + value = [(1, 2), (3, 4)] + if indexer == "loc": + df.loc[:, ["a"]] = value + else: + df.iloc[:, [0]] = value + + expected = pd.DataFrame( + {"a": pd.array([[1, 2], [3, 4]], dtype=dtype), "b": [0, 0]} + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "box", + [np.array, pd.Series, pd.Index, pd.array, tuple], + ids=["ndarray", "Series", "Index", "pd.array", "tuple"], + ) + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_len1_arrays_single_column(self, indexer, box): + # GH#64230 len-1 rows into a single column is the shape that *does* + # match, the counterpart to the mismatch above. Tuples go this route + # too, like every other box (GH#65264) + df = pd.DataFrame({"a": np.zeros(2), "b": [0, 0]}) + value = [box([1]), box([2])] + if indexer == "loc": + df.loc[:, ["a"]] = value + else: + df.iloc[:, [0]] = value + + expected = pd.DataFrame({"a": [1.0, 2.0], "b": [0, 0]}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "box", + [np.array, pd.Series, pd.Index, pd.array], + ids=["ndarray", "Series", "Index", "pd.array"], + ) + def test_setitem_split_path_list_of_arrays_expansion(self, box): + # GH#64230 rows are split across the target columns when one of them is + # created by the setitem + df = pd.DataFrame({"a": [0.0, 0.0]}) + # spell the rows int64: the row dtype carries into the created column, + # and a bare np.array would be int32 on 32-bit platforms + df.loc[:, ["a", "new"]] = [ + box(np.array([1, 2], dtype=np.int64)), + box(np.array([3, 4], dtype=np.int64)), + ] + + expected = pd.DataFrame({"a": [1.0, 3.0], "new": [2, 4]}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "box", [list, deque, tuple], ids=["list", "deque", "tuple"] + ) + def test_setitem_split_path_heterogeneous_rows(self, box): + # GH#64230 mixed element types survive the row unwrap, and do so + # identically whichever container the row arrives in + df = pd.DataFrame( + { + "a": np.zeros(2, dtype=object), + "b": np.zeros(2, dtype=object), + "z": np.zeros(2, dtype="int64"), + } + ) + df.iloc[:, [0, 1]] = [box([1, "x"]), box([2, "y"])] + + expected = pd.DataFrame( + { + "a": pd.Series([1, 2], dtype=object), + "b": pd.Series(["x", "y"], dtype=object), + "z": np.zeros(2, dtype="int64"), + } + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_masked_arrays(self, indexer): + # GH#64230 a masked row keeps pd.NA; np.asarray would make it nan + df = pd.DataFrame( + { + "a": pd.Series([0, 0], dtype="Int64"), + "b": pd.Series([0, 0], dtype="Int64"), + } + ) + value = [ + pd.array([1, pd.NA], dtype="Int64"), + pd.array([pd.NA, 4], dtype="Int64"), + ] + if indexer == "loc": + df.loc[:, ["a", "b"]] = value + else: + df.iloc[:, [0, 1]] = value + + expected = pd.DataFrame( + { + "a": pd.array([1, pd.NA], dtype="Int64"), + "b": pd.array([pd.NA, 4], dtype="Int64"), + } + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("chunked", [False, True]) + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_pyarrow_arrays(self, indexer, chunked): + # GH#64230 a foreign array indexes positionally but hands back a boxed + # scalar, so rows go through np.asarray instead of row[i]; with an + # object dtype target the boxed scalars would be stored silently + pa = pytest.importorskip("pyarrow") + if chunked: + value = [pa.chunked_array([["p", "q"]]), pa.chunked_array([["r", "s"]])] + else: + value = [pa.array(["p", "q"]), pa.array(["r", "s"])] + # "z" keeps the frame multi-block, so this takes the split path + df = pd.DataFrame( + { + "a": np.zeros(2, dtype=object), + "b": np.zeros(2, dtype=object), + "z": np.zeros(2, dtype="int64"), + } + ) + if indexer == "loc": + df.loc[:, ["a", "b"]] = value + else: + df.iloc[:, [0, 1]] = value + + expected = pd.DataFrame( + { + "a": pd.Series(["p", "r"], dtype=object), + "b": pd.Series(["q", "s"], dtype=object), + "z": np.zeros(2, dtype="int64"), + } + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "box", + [np.array, pd.Series, pd.Index, pd.array], + ids=["ndarray", "Series", "Index", "pd.array"], + ) + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_arrays_object_cell(self, indexer, box): + # GH#64230 being a 2D value takes precedence over the nested-data-into- + # a-single-object-cell branch, so this is a shape mismatch rather than + # a list stored in df.iloc[0, 0] + df = pd.DataFrame({"a": np.zeros(2, dtype=object), "b": [0, 0]}) + value = [box([1, 2]), box([3, 4])] + msg = "Must have equal len keys and value when setting with an ndarray" + with pytest.raises(ValueError, match=msg): + if indexer == "loc": + df.loc[0, "a"] = value + else: + df.iloc[0, 0] = value + + @pytest.mark.parametrize( + "box", + [deque, lambda data: std_array("q", data), DuckSequence], + ids=["deque", "array.array", "duck"], + ) + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_sequences(self, indexer, box): + # GH#64230 rows need not be array-likes; any sized, subscriptable, + # non-mapping sequence is a row, as it was when this went through + # np.asarray + df = pd.DataFrame({"a": [0.0, 0.0], "b": np.zeros(2, dtype="int64")}) + value = [box([1, 2]), box([3, 4])] + if indexer == "loc": + df.loc[:, ["a", "b"]] = value + else: + df.iloc[:, [0, 1]] = value + + expected = pd.DataFrame({"a": [1.0, 3.0], "b": [2, 4]}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_ranges(self, indexer): + # GH#64230 range is a sequence, so a list of them is a list of rows + df = pd.DataFrame({"a": [0.0, 0.0], "b": np.zeros(2, dtype="int64")}) + if indexer == "loc": + df.loc[:, ["a", "b"]] = [range(1, 3), range(3, 5)] + else: + df.iloc[:, [0, 1]] = [range(1, 3), range(3, 5)] + + expected = pd.DataFrame({"a": [1.0, 3.0], "b": [2, 4]}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "value", + [ + [{1, 2}, {3, 4}], + [dict.fromkeys([1, 2]), dict.fromkeys([3, 4])], + # bytes and classes are sized and subscriptable, but np.asarray + # never treated them as rows either + [b"ab", b"cd"], + [list, dict], + [GetitemOnly(), GetitemOnly()], + ], + ids=["set", "dict", "bytes", "type", "unsized"], + ) + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_non_sequences(self, indexer, value): + # GH#64230 these are not subscriptable non-mapping sequences, so they + # are values for one column each rather than rows + df = pd.DataFrame( + {"a": np.zeros(2, dtype=object), "b": np.zeros(2, dtype=object)} + ) + if indexer == "loc": + df.loc[0, ["a", "b"]] = value + else: + df.iloc[0, [0, 1]] = value + + expected = pd.DataFrame( + { + "a": np.array([value[0], 0], dtype=object), + "b": np.array([value[1], 0], dtype=object), + } + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_0d_arrays(self, indexer): + # GH#64230 0-d array elements are scalars, not rows, so a list of + # them is not a 2D value; set one scalar per column + df = pd.DataFrame({"a": [0.0, 0.0], "b": [0, 0], "c": [0.0, 0.0]}) + value = [np.array(1.0), np.array(2.0)] + if indexer == "loc": + df.loc[0, ["a", "c"]] = value + else: + df.iloc[0, [0, 2]] = value + + expected = pd.DataFrame({"a": [1.0, 0.0], "b": [0, 0], "c": [2.0, 0.0]}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", ["loc", "iloc"]) + def test_setitem_split_path_list_of_2d_arrays(self, indexer): + # GH#64230 2-D array elements make the value 3D, not 2D; they get + # stored per-cell in an object column + df = pd.DataFrame({"a": np.zeros(2, dtype=object), "b": [0, 0]}) + value = [np.ones((2, 2)), np.zeros((2, 2))] + if indexer == "loc": + df.loc[:, ["a"]] = value + else: + df.iloc[:, [0]] = value + + result = df["a"].tolist() + assert len(result) == 2 + tm.assert_numpy_array_equal(result[0], value[0]) + tm.assert_numpy_array_equal(result[1], value[1]) + + @pytest.mark.parametrize("has_ref", [True, False]) + @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, has_ref, 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 = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]).astype({"A": object}) + if has_ref: + view = df[:] # noqa: F841 + 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 60994, iloc with a mask (of a series) should return accordingly + df = pd.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 = "Unalignable boolean Series provided as indexer" + with pytest.raises(IndexingError, 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 = pd.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", + ("locs", ".loc"): "Unalignable boolean Series provided as indexer", + ("locs", ".iloc"): "Unalignable boolean Series provided as indexer", + } + + # 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 = pd.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) as err: + answer = str(err) + + key = ( + idx, + method, + ) + expected_result = expected.get(key) + + # Fix the assertion to check for substring match + if ( + idx is None or (idx == "index" and method != ".iloc") + ) and "0b" in expected_result: + # For successful numeric results, exact match is needed + assert expected_result == answer, ( + f"[{key}] does not match [{answer}]" + ) + else: + # For error messages, substring match is sufficient + assert expected_result in answer, f"[{key}] not found in [{answer}]" + + def test_iloc_with_numpy_bool_array(self): + df = pd.DataFrame(list(range(5)), index=list("ABCDE"), columns=["a"]) + result = df.iloc[np.array([True, False, True, False, True], dtype=bool)] + expected = pd.DataFrame({"a": [0, 2, 4]}, index=["A", "C", "E"]) + tm.assert_frame_equal(result, expected) + + def test_iloc_series_mask_with_index_mismatch_raises(self): + df = pd.DataFrame(list(range(5)), index=list("ABCDE"), columns=["a"]) + mask = df.a % 2 == 0 + msg = "Unalignable boolean Series provided as indexer" + with pytest.raises(IndexingError, match=msg): + df.iloc[pd.Series([True] * len(mask), dtype=bool)] + + def test_iloc_series_mask_all_true(self): + df = pd.DataFrame(list(range(5)), columns=["a"]) + mask = pd.Series([True] * len(df), dtype=bool) + result = df.iloc[mask] + tm.assert_frame_equal(result, df) + + def test_iloc_series_mask_alternate_true(self): + df = pd.DataFrame(list(range(5)), columns=["a"]) + mask = pd.Series([True, False, True, False, True], dtype=bool) + result = df.iloc[mask] + expected = pd.DataFrame({"a": [0, 2, 4]}, index=[0, 2, 4]) + tm.assert_frame_equal(result, expected) + + def test_iloc_non_unique_indexing(self): + # GH 4017, non-unique indexing (on the axis) + df = pd.DataFrame({"A": [0.1] * 3000, "B": [1] * 3000}) + idx = np.arange(30) * 99 + expected = df.iloc[idx] + + df3 = pd.concat([df, 2 * df, 3 * df]) + result = df3.iloc[idx] + + tm.assert_frame_equal(result, expected) + + df2 = pd.DataFrame({"A": [0.1] * 1000, "B": [1] * 1000}) + df2 = pd.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 = pd.DataFrame( + np.ones((5, 2)), + index=pd.Index([f"i-{i}" for i in range(5)], name="a"), + columns=pd.Index([f"i-{i}" for i in range(2)], name="a"), + ) + # 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): + # GH13873 + original_df = pd.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] + assert (sliced_df["a"] == [1, 2, 3]).all() + + original_series = pd.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] + # shallow copy not updated (CoW) + assert all(sliced_series[:3] == [1, 2, 3]) + + def test_indexing_zerodim_np_array(self): + # GH24919 + df = pd.DataFrame([[1, 2], [3, 4]]) + result = df.iloc[np.array(0)] + s = pd.Series([1, 2], name=0) + tm.assert_series_equal(result, s) + + def test_series_indexing_zerodim_np_array(self): + # GH24919 + s = pd.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 = pd.Categorical(["A", "B", "C"]) + df = pd.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 = pd.Categorical(["C", "B", "A"], categories=["A", "B", "C"]) + tm.assert_categorical_equal(cat, expected) + + def test_iloc_with_boolean_operation(self): + # GH 20627 + result = pd.DataFrame([[0, 1], [2, 3], [4, 5], [6, np.nan]]) + result.iloc[result.index <= 2] *= 2 + expected = pd.DataFrame([[0, 2], [4, 6], [8, 10], [6, np.nan]]) + tm.assert_frame_equal(result, expected) + + result.iloc[result.index > 2] *= 2 + expected = pd.DataFrame([[0, 2], [4, 6], [8, 10], [12, np.nan]]) + tm.assert_frame_equal(result, expected) + + result.iloc[[True, True, False, False]] *= 2 + expected = pd.DataFrame([[0, 4], [8, 12], [8, 10], [12, np.nan]]) + tm.assert_frame_equal(result, expected) + + result.iloc[[False, False, True, True]] /= 2 + expected = pd.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 = pd.DataFrame({"x": pd.Categorical("a b c d e".split())}) + result = df.iloc[0] + raw_cat = pd.Categorical(["a"], categories=["a", "b", "c", "d", "e"]) + expected = pd.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 = pd.Series([1, 2, 3]).astype("category") + + # get slice + result = ser.iloc[0:2] + expected = pd.Series([1, 2]).astype(pd.CategoricalDtype([1, 2, 3])) + tm.assert_series_equal(result, expected) + + # get list of indexes + result = ser.iloc[[0, 1]] + expected = pd.Series([1, 2]).astype(pd.CategoricalDtype([1, 2, 3])) + tm.assert_series_equal(result, expected) + + # get boolean array + result = ser.iloc[[True, False, False]] + expected = pd.Series([1]).astype(pd.CategoricalDtype([1, 2, 3])) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("value", [None, pd.NaT, np.nan]) + def test_iloc_setitem_td64_values_cast_na(self, value): + # GH#18586 + series = pd.Series([0, 1, 2], dtype="timedelta64[ns]") + series.iloc[0] = value + expected = pd.Series([pd.NaT, 1, 2], dtype="timedelta64[ns]") + tm.assert_series_equal(series, expected) + + @pytest.mark.parametrize("not_na", [pd.Interval(0, 1), "a", 1.0]) + def test_setitem_mix_of_nan_and_interval(self, not_na, nulls_fixture): + # GH#27937 + dtype = pd.CategoricalDtype(categories=[not_na]) + ser = pd.Series( + [nulls_fixture, nulls_fixture, nulls_fixture, nulls_fixture], dtype=dtype + ) + ser.iloc[:3] = [nulls_fixture, not_na, nulls_fixture] + exp = pd.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 = pd.Index([]) + obj = pd.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 + + def test_iloc_getitem_read_only_values(self, indexer_li): + # GH#10043 this is fundamentally a test for iloc, but test loc while + # we're here + rw_array = np.eye(10) + rw_df = pd.DataFrame(rw_array) + + ro_array = np.eye(10) + ro_array.setflags(write=False) + ro_df = pd.DataFrame(ro_array) + + tm.assert_frame_equal( + indexer_li(rw_df)[[1, 2, 3]], indexer_li(ro_df)[[1, 2, 3]] + ) + tm.assert_frame_equal(indexer_li(rw_df)[[1]], indexer_li(ro_df)[[1]]) + tm.assert_series_equal(indexer_li(rw_df)[1], indexer_li(ro_df)[1]) + tm.assert_frame_equal(indexer_li(rw_df)[1:3], indexer_li(ro_df)[1:3]) + + def test_iloc_getitem_readonly_key(self): + # GH#17192 iloc with read-only array raising TypeError + df = pd.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 = pd.DataFrame(columns=["a"], index=[0]) + df.iloc[0, 0] = pd.Series([1, 2, 3]) + expected = pd.DataFrame({"a": [pd.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 = pd.DataFrame({"flag": ["x", "y", "z"], "value": [1, 3, 4]}) + indexer = klass([True, False, False]) + df.iloc[indexer, 1] = df.iloc[indexer, 1] * 2 + expected = pd.DataFrame({"flag": ["x", "y", "z"], "value": [2, 3, 4]}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + @pytest.mark.parametrize("indexer", [[1], slice(1, 2)]) + def test_iloc_setitem_pure_position_based(self, indexer, has_ref): + # GH#22046 + df1 = pd.DataFrame({"a2": [11, 12, 13], "b2": [14, 15, 16]}) + df2 = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) + if has_ref: + view = df2[:] # noqa: F841 + df2.iloc[:, indexer] = df1.iloc[:, [0]] + expected = pd.DataFrame({"a": [1, 2, 3], "b": [11, 12, 13], "c": [7, 8, 9]}) + tm.assert_frame_equal(df2, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_iloc_setitem_dictionary_value(self, has_ref): + # GH#37728 + df = pd.DataFrame({"x": [1, 2], "y": [2, 2]}) + if has_ref: + view = df[:] + rhs = {"x": 9, "y": 99} + df.iloc[1] = rhs + expected = pd.DataFrame({"x": [1, 9], "y": [2, 99]}) + tm.assert_frame_equal(df, expected) + + # GH#38335 same thing, mixed dtypes + df = pd.DataFrame({"x": [1, 2], "y": [2.0, 2.0]}) + if has_ref: + view = df[:] # noqa: F841 + df.iloc[1] = rhs + expected = pd.DataFrame({"x": [1, 9], "y": [2.0, 99.0]}) + tm.assert_frame_equal(df, expected) + + def test_iloc_getitem_float_duplicates(self): + df = pd.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 = pd.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 = pd.DataFrame(index=[0, 1], columns=[0]) + df.iloc[1, 0] = TO(1) + df.iloc[1, 0] = TO(2) + + result = pd.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 = pd.DataFrame(index=[0, 1], columns=[0]) + df.iloc[1, 0] = TO(1) + df.iloc[1, 0] = np.nan + result = pd.DataFrame(index=[0, 1], columns=[0]) + + tm.assert_frame_equal(result, df) + + def test_iloc_getitem_with_duplicates(self): + df = pd.DataFrame( + np.random.default_rng(2).random((3, 3)), + columns=list("ABC"), + index=list("aab"), + ) + + result = df.iloc[0] + assert isinstance(result, pd.Series) + tm.assert_almost_equal(result.values, df.values[0]) + + result = df.T.iloc[:, 0] + assert isinstance(result, pd.Series) + tm.assert_almost_equal(result.values, df.values[0]) + + def test_iloc_getitem_with_duplicates2(self): + # GH#2259 + df = pd.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 = pd.DataFrame({pd.Interval(1, 2): [1, 2]}) + + result = df.iloc[0] + expected = pd.Series({pd.Interval(1, 2): 1}, name=0) + tm.assert_series_equal(result, expected) + + result = df.iloc[:, 0] + expected = pd.Series([1, 2], name=pd.Interval(1, 2)) + tm.assert_series_equal(result, expected) + + result = df.copy() + result.iloc[:, 0] += 1 + expected = pd.DataFrame({pd.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 = pd.Series([0, 1, 2]) + ser.iloc[indexing_func([True, False, True])] = rhs_func([5, 10]) + expected = pd.Series([5, 1, 10]) + tm.assert_series_equal(ser, expected) + + df = pd.DataFrame({"a": [0, 1, 2]}) + df.iloc[indexing_func([True, False, True])] = rhs_func([[5], [10]]) + expected = pd.DataFrame({"a": [5, 1, 10]}) + tm.assert_frame_equal(df, expected) + + def test_iloc_getitem_slice_negative_step_ea_block(self): + # GH#44551 + df = pd.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 = pd.DataFrame({"B": df["B"], "A": df["A"]}) + tm.assert_frame_equal(res, expected) + + @pytest.mark.parametrize( + "indexer, values, expected_values", + [ + (slice(None, None, -2), [11, 5, 15], [15, 13, 5, 9, 11]), + (slice(None, None, -1), [11, 5, 15, 9, 3], [3, 9, 15, 5, 11]), + (slice(3, None, -1), [11, 5, 15, 9], [9, 15, 5, 11, 3]), + ], + ) + def test_iloc_setitem_slice_negative_step_none_bounds( + self, indexer, values, expected_values + ): + # GH#66100 length_of_indexer previously returned a negative length + # for negative-step slices with start/stop left as None, causing + # a spurious "different length than the value" ValueError + ser = pd.Series([2, 13, 7, 9, 3], index=["a", "b", "c", "d", "e"]) + ser.iloc[indexer] = values + expected = pd.Series(expected_values, index=["a", "b", "c", "d", "e"]) + tm.assert_series_equal(ser, expected) + + def test_iloc_setitem_slice_negative_step_full_reverse(self): + # GH#66100 + ser = pd.Series([2, 13, 7, 9, 3], index=["a", "b", "c", "d", "e"]) + ser.iloc[::-2] = [11, 5, 15] + expected = pd.Series([15, 13, 5, 9, 11], index=["a", "b", "c", "d", "e"]) + tm.assert_series_equal(ser, expected) + + def test_iloc_setitem_2d_ndarray_into_ea_block(self): + # GH#44703 + df = pd.DataFrame({"status": ["a", "b", "c"]}, dtype="category") + df.iloc[np.array([0, 1]), np.array([0])] = np.array([["a"], ["a"]]) + + expected = pd.DataFrame({"status": ["a", "a", "c"]}, dtype=df["status"].dtype) + tm.assert_frame_equal(df, expected) + + def test_iloc_getitem_int_single_ea_block_view(self): + # GH#45241 + # TODO: make an extension interface test for this? + arr = pd.interval_range(1, 10.0)._values + df = pd.DataFrame(arr, copy=False) + + # 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, using_infer_string): + # GH#20511 + df = pd.DataFrame({"A": ["2022-01-01", "2022-01-02"], "B": ["2021", "2022"]}) + + if using_infer_string: + with pytest.raises(TypeError, match="Invalid value"): + df.iloc[:, [0]] = pd.DataFrame({"A": pd.to_datetime(["2021", "2022"])}) + else: + df.iloc[:, [0]] = pd.DataFrame({"A": pd.to_datetime(["2021", "2022"])}) + expected = pd.DataFrame( + { + "A": [ + pd.Timestamp("2021-01-01 00:00:00"), + pd.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 pd.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 + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_iloc_getitem_setitem_fancy_exceptions(self, float_frame, has_ref): + with pytest.raises(IndexingError, match="Too many indexers"): + float_frame.iloc[:, :, :] + + if has_ref: + view = float_frame[:] # noqa: F841 + 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 = pd.DataFrame({"a": [1, 2, 3]}) + indexer = pd.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 = pd.DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}]) + df2 = pd.DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}]) + df = pd.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 = pd.DataFrame([[0, "str", "str2"]], columns=["a", "b", "b"]) + + df.iloc[:, 2] = ["str3"] + + expected = pd.DataFrame([[0, "str", "str3"]], columns=["a", "b", "b"]) + tm.assert_frame_equal(df, expected) + + def test_iloc_setitem_series_duplicate_columns(self): + df = pd.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 = pd.DataFrame( + [[init_value, "str", "str2"]], columns=["a", "b", "b"], dtype=object + ) + + # 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 = pd.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 = pd.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 = pd.DataFrame( + {"X": [1, 2, 3, 4], "Y": pd.Series(list("aabb"), dtype=object)}, + 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): + ser = pd.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 + tm.assert_series_equal(ser, ser_original) + + # 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 = pd.Series([0, 1, 2], index=[0, 1, 0]) + assert ser.iloc[2] == 2 + + def test_iloc_setitem_pure_position_based(self): + # GH#22046 + ser1 = pd.Series([1, 2, 3]) + ser2 = pd.Series([4, 5, 6], index=[1, 0, 2]) + ser1.iloc[1:3] = ser2.iloc[1:3] + expected = pd.Series([1, 5, 6]) + tm.assert_series_equal(ser1, expected) + + def test_iloc_nullable_int64_size_1_nan(self): + # GH 31861 + result = pd.DataFrame({"a": ["test"], "b": [np.nan]}) + + ser = pd.Series([pd.NA], name="b", dtype="Int64") + with pytest.raises(TypeError, match="Invalid value"): + result.loc[:, "b"] = ser + + def test_iloc_arrow_extension_array(self): + # GH#61311 + pytest.importorskip("pyarrow") + df = pd.DataFrame({"a": [1, 2], "c": [0, 2], "d": ["c", "a"]}) + df_arrow = pd.DataFrame( + {"a": [1, 2], "c": [0, 2], "d": ["c", "a"]} + ).convert_dtypes(dtype_backend="pyarrow") + expected = df.iloc[:, df["c"]] + result = df_arrow.iloc[:, df_arrow["c"]] + tm.assert_frame_equal(result, expected, check_dtype=False) + + @td.skip_if_no("pyarrow") + def test_setitem_pyarrow_int_series(self): + # GH#62462 + ser = pd.Series([1, 2, 3], dtype="int64[pyarrow]") + idx = pd.Index([0, 1]) + vals = pd.Series([7, 8], dtype="int64[pyarrow]") + + ser.iloc[idx] = vals + + expected = pd.Series([7, 8, 3], dtype="int64[pyarrow]") + tm.assert_series_equal(ser, expected) + + +@pytest.mark.parametrize( + "row_key", + [ + [0, 1, 2], + slice(0, 3), + range(3), + np.array([True, True, True, False]), + pd.Series([0, 1, 2]), + pd.Index([0, 1, 2]), + ], +) +@pytest.mark.parametrize("col_key", [[1], slice(1, 2), np.array([False, True, False])]) +def test_iloc_setitem_single_column_key_1d_value(row_key, col_key): + # GH#68021 a length-1 column key makes the selection (N, 1), which a + # length-N 1-D value could not be broadcast into on a single-block frame + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + df.iloc[row_key, col_key] = [1.0, 2.0, 3.0] + + expected = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + expected["b"] = [1.0, 2.0, 3.0, 0.0] + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_single_column_key_1d_value_datetimelike(): + # GH#68021 the 2D DatetimeArray block hit the same broadcast failure, but + # surfaced it as OutOfBoundsDatetime from the upcast fallback + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")).astype("M8[ns]") + + df.iloc[[0, 1, 2], [1]] = pd.to_datetime([1, 2, 3], unit="ns") + + expected = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")).astype("M8[ns]") + expected["b"] = pd.to_datetime([1, 2, 3, 0], unit="ns") + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_single_column_key_list_of_tuples(): + # GH#68021 a list of tuples that do not match the number of selected columns + # is per-cell values, and reached the same broadcast failure + df = pd.DataFrame({col: np.array([1, 2, 3, 4], dtype=object) for col in "abc"}) + + df.iloc[[0, 1, 2], [1]] = [(1, 2), (3, 4), (5, 6)] + + expected = pd.DataFrame( + {col: np.array([1, 2, 3, 4], dtype=object) for col in "abc"} + ) + expected["b"] = pd.array([(1, 2), (3, 4), (5, 6), 4], dtype=object) + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_single_column_key_tuples_matching_width_still_2d(): + # GH#68021 length-1 tuples do match the one selected column, so they are a + # 2-D value and still flatten; the per-cell path must not swallow them + df = pd.DataFrame({col: np.array([1, 2, 3, 4], dtype=object) for col in "abc"}) + + df.iloc[[0, 1, 2], [1]] = [(1,), (3,), (5,)] + + expected = pd.DataFrame( + {col: np.array([1, 2, 3, 4], dtype=object) for col in "abc"} + ) + expected["b"] = pd.array([1, 3, 5, 4], dtype=object) + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_single_column_key_length_mismatch_still_raises(): + # GH#68021 the per-column path must not swallow a genuine length mismatch. + # The message is numpy's rather than pandas' because a single-block frame + # takes the non-split path; that divergence is deliberate, see GH#65241 and + # test_loc_setitem_int_row_length_mismatch_message. + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + with pytest.raises(ValueError, match="setting an array element with a sequence"): + df.iloc[[0, 1], [1]] = [1.0, 2.0, 3.0] + + +def test_iloc_setitem_single_column_key_2d_value_unchanged(): + # GH#68021 an (N, 1) value already matched the selection and must keep + # taking the whole-block path + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + df.iloc[[0, 1, 2], [1]] = np.array([[1.0], [2.0], [3.0]]) + + expected = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + expected["b"] = [1.0, 2.0, 3.0, 0.0] + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_single_column_key_length_one_value_broadcasts(): + # GH#68021 a length-1 value broadcasts to every selected row; the length + # check must not turn that into a per-row assignment + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + df.iloc[[0, 1, 2], [1]] = [9.0] + + expected = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + expected["b"] = [9.0, 9.0, 9.0, 0.0] + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_scalar_row_multiple_columns_unchanged(): + # GH#68021 a scalar row key with several columns stays row-wise + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + df.iloc[0, [0, 1]] = [5.0, 6.0] + + expected = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + expected.iloc[0, 0] = 5.0 + expected.iloc[0, 1] = 6.0 + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_scalar_row_single_column_unchanged(): + # GH#68021 a scalar row key selects one cell, not a column to fill; this is + # the case that reaches the guard's is_scalar(indexer[0]) clause, since + # length_of_indexer(0) == 1 == len(value) would otherwise match + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + df.iloc[0, [1]] = [5.0] + + expected = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + expected.iloc[0, 1] = 5.0 + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize( + "row_key", + [ + pd.array([0, 1, 2], dtype="Int64"), + pd.array([True, True, True, False], dtype="boolean"), + pd.Categorical([0, 1, 2]), + (0, 1, 2), + ], +) +def test_iloc_setitem_single_column_key_row_key_length_of_indexer_cannot_measure( + row_key, +): + # GH#68021 length_of_indexer does not know these row keys and raises + # AssertionError for them, so they have to keep taking the whole-block + # path instead of the per-column one + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + df.iloc[row_key, [1]] = [1.0, 2.0, 3.0] + + expected = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + expected["b"] = [1.0, 2.0, 3.0, 0.0] + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_boolean_column_key_selecting_one_column(): + # GH#68021 _ensure_iterable_column_indexer leaves a list of bools alone, so + # the per-column path would have taken True for a position + df = pd.DataFrame(np.zeros((5, 1)), columns=["a"]) + + df.iloc[range(3), [True]] = [1.0, 2.0, 3.0] + + expected = pd.DataFrame(np.zeros((5, 1)), columns=["a"]) + expected["a"] = [1.0, 2.0, 3.0, 0.0, 0.0] + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize("row_key", [[], np.array([False, False, False, False])]) +def test_iloc_setitem_single_column_key_empty_selection_is_noop(row_key): + # GH#68021 an empty selection with an empty value is a no-op, as it already + # was on the mixed-dtype split path + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + df.iloc[row_key, [1]] = [] + + tm.assert_frame_equal(df, pd.DataFrame(np.zeros((4, 3)), columns=list("abc"))) + + +@pytest.mark.parametrize("row_key", [np.array(0), np.array([[0], [1]])]) +def test_iloc_setitem_single_column_key_non_1d_row_key_keeps_clear_error(row_key): + # GH#68021 length_of_indexer cannot measure these, so they keep taking the + # whole-block path and its clearer message + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + with pytest.raises(ValueError, match="Cross index must be 1 dimensional"): + df.iloc[row_key, [1]] = [1.0, 2.0] + + +def test_iloc_setitem_out_of_bounds_boolean_column_key_raises(): + # GH#68021 a too-long boolean column key whose True lands past the last + # column used to be silently discarded here. Note this pins the + # out-of-bounds position, not the key's length: a too-long key whose True + # is in bounds is still accepted, as it already was on the split path. + df = pd.DataFrame({"a": pd.array([1, 2, 3, 4], dtype="Int64")}) + + with pytest.raises(IndexError, match="single positional indexer is out-of-bounds"): + df.iloc[range(3), np.array([False, True, False])] = [1, 2, 3] + + +def test_iloc_setitem_null_slice_column_key_single_column_frame(): + # GH#68021 on a one-column frame a null slice also selects exactly one + # column, so it hits the same (N, 1) selection + df = pd.DataFrame({"a": [0.0, 1.0, 2.0, 3.0]}) + + df.iloc[[0, 1, 2], :] = [10.0, 20.0, 30.0] + + tm.assert_frame_equal(df, pd.DataFrame({"a": [10.0, 20.0, 30.0, 3.0]})) + + +def test_iloc_setitem_boolean_index_row_key(): + # GH#68021 on a single-block frame this raised the same + # "setting an array element with a sequence" as every other row key; it + # reaches length_of_indexer, and so the Index.sum() crash, only via the + # new per-column route + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + df.iloc[pd.Index([True, True, True, False]), [1]] = [1.0, 2.0, 3.0] + + expected = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + expected["b"] = [1.0, 2.0, 3.0, 0.0] + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_boolean_index_row_key_mixed_dtype(): + # GH#68021 this is where the Index.sum() crash was already reachable: the + # split path measures the row key, so it raised AttributeError on main + df = pd.DataFrame({"a": np.zeros(4), "b": np.zeros(4), "c": list("wxyz")}) + + df.iloc[pd.Index([True, True, True, False]), [1]] = [1.0, 2.0, 3.0] + + expected = pd.DataFrame({"a": np.zeros(4), "b": np.zeros(4), "c": list("wxyz")}) + expected["b"] = [1.0, 2.0, 3.0, 0.0] + tm.assert_frame_equal(df, expected) + + +def test_iloc_setitem_series_boolean_index_row_key(): + # GH#68021 an object-dtype Series reaches length_of_indexer from + # Block.setitem's num_set, a different call site than the DataFrame paths + ser = pd.Series([1, 2, 3, 4], dtype=object) + + ser.iloc[pd.Index([True, True, False, False])] = ["a", "b"] + + tm.assert_series_equal(ser, pd.Series(["a", "b", 3, 4], dtype=object)) + + +def _datetimelike_values(ints, dtype): + # ``ints`` as the i8 values of ``dtype``, keeping the shape + if dtype == "period[D]": + return pd.arrays.PeriodArray(ints.ravel(), dtype=dtype).reshape(ints.shape) + if dtype == "M8[ns, UTC]": + values = pd.array(ints.ravel().view("M8[ns]")).tz_localize("UTC") + return values.reshape(ints.shape) + return ints.view(dtype) + + +_ROW_KEYS = [ + 1, + [2, 0], + slice(None, None, -1), + np.array([True, False, True, False]), + [], + ..., +] +_COL_KEYS = [0, [2, 0], slice(None, None, 2), [2, 1, 0], []] + + +class TestILocSetItem2DDatetimelikeBlock: + @pytest.mark.parametrize("dtype", ["M8[s]", "m8[s]"]) + def test_1d_value_broadcasts(self, dtype): + # GH#68521 the 2D datetimelike block stores columns first, so a 1-D value + # was broadcast down rows instead of across the selected columns + arr = np.arange(12).reshape(4, 3).astype("i8") + # copy so a write-through to ``arr`` can't make the comparison vacuous + df = pd.DataFrame(arr.copy().view(dtype), columns=list("abc")) + + df.iloc[[2, 0], ::-1] = np.array([100, 101, 102], dtype="i8").view(dtype) + + arr[[2, 0], ::-1] = [100, 101, 102] + expected = pd.DataFrame(arr.view(dtype), columns=list("abc")) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("dtype", ["M8[s]", "m8[s]", "M8[ns, UTC]", "period[D]"]) + @pytest.mark.parametrize( + "key", + [ + (row_key, col_key) + for row_key in _ROW_KEYS + for col_key in _COL_KEYS + if not (isinstance(row_key, int) and isinstance(col_key, int)) + ] + + [ + (range(2), range(2)), + ([2, 0],), + (None,), + (None, ...), + (np.array([[1], [2]]),), + (np.array([[1, 2]]),), + (slice(None), np.array([[0, 2]])), + ], + ) + def test_matches_numeric(self, dtype, key): + # GH#68521 a 2D datetimelike block writes the cells a NumPy-backed frame + # does, and raises where it raises + ints = np.arange(12, dtype="i8").reshape(4, 3) + if len(key) == 2 and all( + isinstance(entry, (list, np.ndarray)) for entry in key + ): + # iloc takes the outer product of two list-likes, like np.ix_ + shape = ints[np.ix_(*key)].shape + else: + shape = ints[key].shape + value_shapes = {shape, shape[:1], shape[-1:], shape[::-1]} + if len(shape) == 2: + value_shapes |= {(shape[0], 1), (1, *shape)} + + for value_shape in value_shapes: + numeric = pd.DataFrame(ints.copy()) + df = pd.DataFrame(_datetimelike_values(ints, dtype)) + value = np.arange(100, 100 + np.prod(value_shape), dtype="i8") + value = value.reshape(value_shape) + try: + numeric.iloc[key] = value + except (ValueError, IndexError): + with pytest.raises((ValueError, IndexError)): + df.iloc[key] = _datetimelike_values(value, dtype) + else: + df.iloc[key] = _datetimelike_values(value, dtype) + expected = pd.DataFrame(_datetimelike_values(numeric.to_numpy(), dtype)) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "box", + [ + list, + tuple, + pd.Index, + pd.Series, + pd.array, + pd.Categorical, + lambda x: [str(pd.Timestamp(v)) for v in x], + ], + ) + def test_1d_value_not_ndarray(self, box): + # GH#68521 these spellings of a 1-D value wrote the wrong cells silently too + arr = np.arange(12).reshape(4, 3).astype("i8") + df = pd.DataFrame(arr.copy().view("M8[s]"), columns=list("abc")) + + df.iloc[[2, 0], ::2] = box(np.array([100, 101], dtype="i8").view("M8[s]")) + + arr[[2, 0], ::2] = [100, 101] + expected = pd.DataFrame(arr.view("M8[s]"), columns=list("abc")) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("dtype", ["M8[s]", "m8[s]"]) + def test_0d_row_key(self, dtype): + # GH#68521 a 0-d ndarray row key selects one row, like an int + arr = np.arange(12).reshape(4, 3).astype("i8") + df = pd.DataFrame(arr.copy().view(dtype), columns=list("abc")) + + df.iloc[np.array(1)] = np.array([100, 101, 102], dtype="i8").view(dtype) + + arr[1] = [100, 101, 102] + expected = pd.DataFrame(arr.view(dtype), columns=list("abc")) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("col_key", [slice(None, None, -1), [2, 1, 0]]) + def test_shape_mismatch_message(self, col_key): + # GH#68521 a value that cannot be broadcast is a shape problem; the upcast + # fallback reported it as a datetime resolution one + arr = np.arange(12).reshape(4, 3).astype("i8") + df = pd.DataFrame(arr.view("M8[s]"), columns=list("abc")) + + msg = ( + r"shape mismatch: value array of shape \(2,\) could not be broadcast " + r"to indexing result of shape \(2,3\)" + ) + with pytest.raises(ValueError, match=msg): + df.iloc[[2, 0], col_key] = np.array([100, 101], dtype="i8").view("M8[s]") + + def test_row_vector_into_one_row(self): + # GH#68521 numpy drops the row vector's leading length-1 axis; this raised + # because the value was transposed into a column vector + arr = np.arange(12).reshape(4, 3).astype("i8") + df = pd.DataFrame(arr.copy().view("M8[s]"), columns=list("abc")) + + value = np.array([[100, 101, 102]]) + df.iloc[1] = value.astype("i8").view("M8[s]") + + arr[1] = value + tm.assert_frame_equal(df, pd.DataFrame(arr.view("M8[s]"), columns=list("abc"))) + + +def test_iloc_setitem_1d_ea_block_shape_mismatch_keeps_its_message(): + # GH#68521 the broadcast message is for 2D blocks only; a Series keeps its + # dtype error + ser = pd.Series(np.arange(4).astype("i8").view("M8[s]")) + + with pytest.raises(TypeError, match="Invalid value"): + ser.iloc[0] = [1, 2] + + +@pytest.mark.parametrize( + "dtype", + [ + "Int64", + # string dtypes + ("python", np.nan), + pytest.param(("pyarrow", np.nan), marks=td.skip_if_no("pyarrow")), + ], +) +@pytest.mark.parametrize( + "box", + [ + list, + np.array, + pytest.param( + lambda x: pd.Series(x, index=["a"]), + marks=pytest.mark.xfail(reason="Series indexer fails"), + ), + pd.Index, + pd.array, + ], + # [np.array], + ids=["list", "ndarray", "Series", "Index", "pd.array"], +) +def test_iloc_setitem_single_column_frame_ea_dtype(dtype, box): + # https://github.com/pandas-dev/pandas/issues/66527 + # column boolean mask that sets into the single column of a 1-column df + if isinstance(dtype, tuple): + dtype = pd.StringDtype(*dtype) + df = pd.DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)}) + + # setting with a 2d dataframe + df.iloc[:, box([True])] = df * 2 + + expected = pd.DataFrame({"a": pd.array([1, 2, 3], dtype=dtype) * 2}) + tm.assert_frame_equal(df, expected) + + df.iloc[[0, 1], box([True])] = df.iloc[[0, 1], :] * 2 + + arr = pd.array([1, 2, 3], dtype=dtype) * 2 + arr[[0, 1]] = arr[[0, 1]] * 2 + expected = pd.DataFrame({"a": arr}) + tm.assert_frame_equal(df, expected) + + # setting with a scalar + df = pd.DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)}) + scalar = df.iloc[1, 0] + + df.iloc[:, box([True])] = scalar + + expected = pd.DataFrame({"a": pd.array([scalar] * 3, dtype=dtype)}) + tm.assert_frame_equal(df, expected) + + df.iloc[[0, 1], box([True])] = scalar * 2 + + expected = pd.DataFrame( + {"a": pd.array([scalar * 2, scalar * 2, scalar], dtype=dtype)} + ) + tm.assert_frame_equal(df, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_indexers.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_indexers.py new file mode 100644 index 0000000000000000000000000000000000000000..04e7833327d2236e3be7f6855d3424938704f30f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_indexers.py @@ -0,0 +1,116 @@ +# Tests aimed at pandas.core.indexers +import numpy as np +import pytest + +import pandas as pd +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_length_of_indexer_boolean_index(): + # GH#68021 the boolean branch used indexer.sum(), which Index does not have + assert length_of_indexer(pd.Index([True, False, True])) == 2 + assert length_of_indexer(pd.Series([True, False, True])) == 2 + + +@pytest.mark.parametrize( + "start, stop, step, target_len, expected", + [ + # GH#66100 negative step with None bounds previously returned + # negative lengths + (None, None, -1, 7, 7), + (None, None, -2, 7, 4), + (None, None, -3, 7, 3), + (4, None, -2, 7, 3), + (None, 0, -2, 7, 3), + (None, 1, -1, 7, 5), + (3, None, -1, 7, 4), + # explicit (non-None) bounds with negative step already worked + (4, 0, -2, 7, 2), + (6, 0, -1, 7, 6), + (5, 1, -2, 7, 2), + (-1, -5, -1, 7, 4), + # positive step, including GH#9995 non-divisible-step case + (1, None, 2, 6, 3), + (None, None, 1, 7, 7), + (1, 5, 2, 7, 2), + (None, None, None, 7, 7), + (2, None, None, 7, 5), + ], +) +def test_length_of_indexer_slice(start, stop, step, target_len, expected): + target = np.arange(target_len) + indexer = slice(start, stop, step) + result = length_of_indexer(indexer, target) + assert result == expected + # cross-check against the actual sliced length, the real source of truth + assert result == len(target[indexer]) + + +@pytest.mark.parametrize( + "start, stop, step, expected", + [ + (10, 0, -3, 4), + (0, 1, 5, 1), + ], +) +def test_length_of_indexer_range_overflow(start, stop, step, expected): + # https://github.com/pandas-dev/pandas/pull/63872 + indexer = range(start, stop, step) + result = length_of_indexer(indexer) + assert result == expected + + +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/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..f4f463631c812ab0d5ec439ef80e001941c1caed --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_indexing.py @@ -0,0 +1,1282 @@ +"""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 +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 = pd.DataFrame(index=pd.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 = pd.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 = pd.DataFrame(index=pd.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 + + def test_getitem_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)) + + msgs = [] + if frame_or_series is pd.Series and indexer_sli in [tm.setitem, tm.iloc]: + msgs.append(r"Wrong number of dimensions. values.ndim > ndim \[3 > 1\]") + if frame_or_series is pd.Series or indexer_sli is tm.iloc: + msgs.append(r"Buffer has wrong number of dimensions \(expected 1, got 3\)") + if indexer_sli is tm.loc or ( + frame_or_series is pd.Series and indexer_sli is tm.setitem + ): + msgs.append("Cannot index with multidimensional key") + if frame_or_series is pd.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 pd.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] + + 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)) + + err = ValueError + if indexer_sli is tm.iloc: + msg = f"Cannot set values with ndim > {obj.ndim}" + elif indexer_sli is tm.setitem and frame_or_series is pd.DataFrame: + # __setitem__ with a 3D key treats it as a boolean mask + msg = "Array conditional must be same shape as self" + else: + msg = "Index data must be 1-dimensional" + + with pytest.raises(err, match=msg): + idxr[nd3] = 0 + + def test_getitem_ndarray_0d(self): + # GH#24924 + key = np.array(0) + + # dataframe __getitem__ + df = pd.DataFrame([[1, 2], [3, 4]]) + result = df[key] + expected = pd.Series([1, 3], name=0) + tm.assert_series_equal(result, expected) + + # series __getitem__ + ser = pd.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 = pd.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 = pd.Index([1, 2, np.inf], dtype=np.float64) + tm.assert_index_equal(result, expected) + + def test_setitem_dtype_upcast(self): + # GH3216 + df = pd.DataFrame([{"a": 1}, {"a": 3, "b": 2}]) + df["c"] = np.nan + assert df["c"].dtype == np.float64 + + with pytest.raises(TypeError, match="Invalid value"): + df.loc[0, "c"] = "foo" + + @pytest.mark.parametrize("val", [3.14, "wxyz"]) + def test_setitem_dtype_upcast2(self, val): + # GH10280 + df = pd.DataFrame( + np.arange(6, dtype="int64").reshape(2, 3), + index=list("ab"), + columns=["foo", "bar", "baz"], + ) + + left = df.copy() + with pytest.raises(TypeError, match="Invalid value"): + left.loc["a", "bar"] = val + + def test_setitem_dtype_upcast3(self): + left = pd.DataFrame( + np.arange(6, dtype="int64").reshape(2, 3) / 10.0, + index=list("ab"), + columns=["foo", "bar", "baz"], + ) + with pytest.raises(TypeError, match="Invalid value"): + left.loc["a", "bar"] = "wxyz" + + def test_dups_fancy_indexing(self): + # GH 3455 + + df = pd.DataFrame(np.eye(3), columns=["a", "a", "b"]) + result = df[["b", "a"]].columns + expected = pd.Index(["b", "a", "a"]) + tm.assert_index_equal(result, expected) + + def test_dups_fancy_indexing_across_dtypes(self): + # across dtypes + df = pd.DataFrame( + [[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("aaaaaaa") + ) + result = pd.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 = pd.DataFrame( + {"test": [5, 7, 9, 11], "test1": [4.0, 5, 6, 7], "other": list("abcd")}, + index=["A", "A", "B", "C"], + ) + rows = ["C", "B"] + expected = pd.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[pd.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, using_infer_string): + # List containing only missing label + dfnu = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), index=list("AABCD") + ) + if using_infer_string: + with pytest.raises( + KeyError, + match=re.escape( + "\"None of [Index(['E'], dtype='str')] are in the [index]\"" + ), + ): + dfnu.loc[["E"]] + else: + 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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.Series(range(3), index=[1, 1, 3]) + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame( + { + "FC": ["a", np.nan, "a", "b", "a", "b"], + "PF": [0, 0, 0, 0, 1, 1], + "col1": pd.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 = pd.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 = pd.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"].copy() + tm.assert_frame_equal(df, expected) + + def test_setitem_list(self): + # GH 6043 + # iloc with a list + df = pd.DataFrame(index=[0, 1], columns=[0]) + df.iloc[1, 0] = [1, 2, 3] + df.iloc[1, 0] = [1, 2] + + result = pd.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 = pd.DataFrame([1], pd.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 = pd.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, using_infer_string): + # GH4312 (iloc) + df_orig = pd.DataFrame( + [["1", "2", "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG") + ) + df_orig[list("ABCDG")] = df_orig[list("ABCDG")].astype(object) + + 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 = pd.DataFrame( + [[1, 2, "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG") + ) + expected[list("CDG")] = expected[list("CDG")].astype(object) + 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 = pd.DataFrame( + [[1, "2", "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG") + ) + expected[list("ABCDG")] = expected[list("ABCDG")].astype(object) + tm.assert_frame_equal(df, expected) + + df = df_orig.copy() + + df.loc[:, ["B", "C"]] = df.loc[:, ["B", "C"]].astype(np.int64) + expected = pd.DataFrame( + [["1", 2, 3, ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG") + ) + expected[list("ABCDG")] = expected[list("ABCDG")].astype(object) + tm.assert_frame_equal(df, expected) + + def test_astype_assignment_full_replacements(self): + # full replacements / no nans + df = pd.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 = pd.DataFrame({"A": [1.0, 2.0, 3.0, 4.0]}) + tm.assert_frame_equal(df, expected) + + df = pd.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( + "dtype, ea_dtype", + [ + ("float64", "Int64"), + ("float64", "Float64"), + ("bool", "boolean"), + ], + ) + @pytest.mark.parametrize("box", [pd.Series, pd.Index]) + def test_iloc_setitem_ea_dtype_series(self, dtype, ea_dtype, box): + # GH#47776 + if dtype == "bool": + df = pd.DataFrame({"A": [True, False, True]}) + val = box([False, True, False], dtype=ea_dtype) + else: + df = pd.DataFrame({"A": [1.0, 2.0, 3.0]}) + val = box([4, 5, 6], dtype=ea_dtype) + + df.iloc[:, 0] = val + expected = pd.DataFrame({"A": val.to_numpy(dtype=dtype)}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "col_dtype, ea_dtype, bad_value, good_value", + [ + ("uint64", "Int64", -1, 5), + ("uint64", "int64[pyarrow]", -1, 5), + ("float32", "Float64", 1e300, 5.0), + ("float32", "double[pyarrow]", 1e300, 5.0), + ], + ) + @pytest.mark.parametrize("box", [pd.Series, pd.Index]) + def test_iloc_setitem_ea_dtype_lossy_raises( + self, col_dtype, ea_dtype, bad_value, good_value, box + ): + # GH#47776 - a NA-free nullable/arrow EA whose values don't fit the + # target numpy dtype must raise, not silently wrap (-1 -> 2**64-1) or + # overflow (1e300 -> inf). + if "pyarrow" in ea_dtype: + pytest.importorskip("pyarrow") + + df = pd.DataFrame({"A": np.zeros(3, dtype=col_dtype)}) + lossy = box([bad_value, good_value, good_value], dtype=ea_dtype) + with pytest.raises(TypeError, match="Invalid value"): + df.iloc[:, 0] = lossy + + # a value that does fit is still assigned inplace, retaining the dtype + fits = box([good_value, good_value, good_value], dtype=ea_dtype) + df.iloc[:, 0] = fits + expected = pd.DataFrame({"A": fits.to_numpy(dtype=col_dtype)}) + 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 [pd.Series(range(5)), pd.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 = pd.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 [pd.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 = pd.DataFrame( + { + 0.0: np.random.default_rng(2).random(10), + 1.0: np.random.default_rng(2).random(10), + } + ) + df["a"] = 10 + + expected = pd.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 = pd.DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}, index=[1.0, 2.0, 3.0]) + df.loc[df.index[:2]] = 1 + expected = pd.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 = pd.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 = pd.DataFrame(xs, columns=cols, index=list("abcde"), dtype="int64") + + # right hand side; permute the indices and multiply 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 pytest.raises(TypeError, match="Invalid value"): + 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 = pd.Index(idx) + ser = pd.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 = pd.Index([-5, 0, 5], name="z") + df = pd.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 = pd.DataFrame({"x": [1, 2, 6], "y": [2.0, 2.0, 8.0]}, index=index) + df.loc[5] = rhs + expected = pd.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 = pd.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 = pd.Series(index=range(size), dtype=np.float64) + s.loc[range(1)] = 42 + tm.assert_series_equal(s.loc[range(1)], pd.Series(42.0, index=range(1))) + + s.loc[range(2)] = 43 + tm.assert_series_equal(s.loc[range(2)], pd.Series(43.0, index=range(2))) + + def test_partial_boolean_frame_indexing(self): + # GH 17170 + df = pd.DataFrame( + np.arange(9.0).reshape(3, 3), index=list("abc"), columns=list("ABC") + ) + index_df = pd.DataFrame(1, index=list("ab"), columns=list("AB")) + result = df[index_df.notnull()] + expected = pd.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_period_column_slicing(self): + # GH#60273 The transpose operation creates a single 5x1 block of PeriodDtype + # Make sure it is reindexed correctly + df = pd.DataFrame( + pd.period_range("2021-01-01", periods=5, freq="D"), + columns=["A"], + ).T + result = df[[0, 1, 2]] + expected = pd.DataFrame( + [ + [ + pd.Period("2021-01-01", freq="D"), + pd.Period("2021-01-02", freq="D"), + pd.Period("2021-01-03", freq="D"), + ] + ], + index=["A"], + columns=[0, 1, 2], + ) + tm.assert_frame_equal(result, expected) + + def test_no_reference_cycle(self): + df = pd.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 = pd.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)], + [pd.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 = pd.DataFrame({"foo": start_data}) + start_dataframe.loc[0, ["foo"]] = None + + expected_dataframe = pd.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 = pd.DataFrame({"foo": start_data}) + start_dataframe[start_dataframe["foo"] == start_dataframe["foo"][0]] = None + + expected_dataframe = pd.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 = pd.DataFrame({"foo": start_data}) + start_dataframe.loc[start_dataframe["foo"] == start_dataframe["foo"][0]] = None + + expected_dataframe = pd.DataFrame({"foo": expected_result}) + tm.assert_frame_equal(start_dataframe, expected_dataframe) + + def test_none_coercion_mixed_dtypes(self): + start_dataframe = pd.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 = pd.DataFrame( + { + "a": [np.nan, 2, 3], + "b": [np.nan, 2.0, 3.0], + "c": [pd.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 = pd.date_range("2016-01-01", periods=3, tz=tz) + ser = pd.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, pd.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 = pd.date_range("2016-01-01", periods=3, tz=tz) + ser = pd.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", pd.offsets.Hour(4)]) + def test_setitem_td64_scalar(self, indexer_sli, scalar): + # dispatching _can_hold_element to underling TimedeltaArray + tdi = pd.timedelta_range("1 Day", periods=3) + ser = pd.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, pd.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 = pd.timedelta_range("1 Day", periods=3) + ser = pd.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 = pd.DataFrame( + { + "A": pd.array([1, 2], dtype="Int64"), + "B": pd.array([3, 4], dtype="Int64"), + }, + index=["a", "b"], + ) + expected = pd.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 = pd.DataFrame( + { + "A": pd.array([1, 2], dtype="Int64"), + "B": np.array([1, 2], dtype="int64"), + }, + index=["a", "b"], + ) + result = df.loc["a"] + expected = pd.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 = pd.DataFrame( + {"A": pd.array([1, 2], dtype="Int64"), "B": np.array(["a", "b"])}, + index=["a", "b"], + ) + result = df.loc["a"] + expected = pd.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", + [(pd.Series([10]), (0, 0)), (pd.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 = pd.Series([10]) + res = indexer_li(ser)[[0, 0]] + exp = pd.Series([10, 10], index=pd.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 = pd.DataFrame({"A": [1, 2, 3]}) + # NumPy rejects the nested value while building the column + msg = "setting an array element with a sequence" + with pytest.raises(ValueError, match=msg): + df.loc[0, "B"] = value + + # Update for object dtype: We DO preserve nested data now (Fixes #57962) + df = pd.DataFrame({"A": [1, 2, 3], "B": np.array([1, "a", "b"], dtype=object)}) + + # Perform the assignment (this used to be inside the pytest.raises block) + df.loc[0, "B"] = value + + # Use the author's original intended assertions + 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 = pd.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 = pd.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 = pd.DataFrame({"A": [1, 2, 3]}) + df.loc[0, "B"] = value + expected = pd.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 = pd.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 = pd.Series([1.0, 2.0, 3.0]) + if isinstance(value, np.ndarray): + indexer_sli(ser)[0] = value + expected = pd.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 = pd.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_scalar_setitem_tuple_into_object_column(): + # GH#26333 - assigning a tuple to a single cell of an object-dtype column + # that already holds tuples should store it as-is, not raise on length + df = pd.DataFrame({"a": [1, 2, 3], "b": [(1, 2), (1, 2, 3), (3, 4)]}) + + df.loc[0, "b"] = (7, 8, 9) + assert df.loc[0, "b"] == (7, 8, 9) + + # .at takes the same path + df.at[1, "b"] = (4, 5) + assert df.at[1, "b"] == (4, 5) + + expected = pd.DataFrame({"a": [1, 2, 3], "b": [(7, 8, 9), (4, 5), (3, 4)]}) + tm.assert_frame_equal(df, expected) + + +def test_loc_setitem_list_of_tuples_on_object_column(): + # GH#37629 - assigning list of tuples to object-dtype column + # with a boolean mask on a mixed-dtype DataFrame + df = pd.DataFrame({"a": [1, 1, 2, 1], "b": [(1, 1, 0)] * 4}) + + # list of tuples matching selected row count + df.loc[df["a"] == 1, "b"] = [(0, 0, 1), (0, 0, 1), (0, 0, 1)] + expected = pd.DataFrame( + {"a": [1, 1, 2, 1], "b": [(0, 0, 1), (0, 0, 1), (1, 1, 0), (0, 0, 1)]} + ) + tm.assert_frame_equal(df, expected) + # verify tuples are preserved as tuples + assert isinstance(df["b"].iloc[0], tuple) + + # doubly-nested list: [[(tuple)]] treated as 2D with 1 row x 1 col, + # tuple value broadcast to all matching rows + df2 = pd.DataFrame({"a": [1, 1, 2, 1], "b": [(1, 1, 0)] * 4}) + df2.loc[df2["a"] == 1, "b"] = [[(0, 0, 1)]] + tm.assert_frame_equal(df2, expected) + + +@pytest.mark.parametrize("value", [[[1, 2], [3, 4], [5, 6]], [(1, 2), (3, 4), (5, 6)]]) +def test_loc_setitem_2d_list_on_object_frame(value): + # GH#65264 - a list of lists/tuples assigned to a 2D object block is a + # genuine 2D value; its rows must not be wrapped into single object cells + df = pd.DataFrame({"a": [10, 20, 30], "b": [40, 50, 60]}, dtype=object) + df.loc[:, :] = value + expected = pd.DataFrame({"a": [1, 3, 5], "b": [2, 4, 6]}, dtype=object) + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize( + "value", + [ + [(10, 20, 30), (40, 50, 60)], + [[10, 20, 30], [40, 50, 60]], + np.array([[10, 20, 30], [40, 50, 60]]), + ], + ids=["tuples", "lists", "ndarray"], +) +def test_setitem_2d_value_wrong_shape_multi_column(value, indexer_li): + # GH#65264 a 2D value whose rows don't match the target column count must + # raise however the rows are spelled + df = pd.DataFrame({"a": ["x", "y", "z"], "b": [1, 2, 3], "c": [4.0, 5.0, 6.0]}) + key = ["b", "c"] if indexer_li is tm.loc else [1, 2] + + msg = "Must have equal len keys and value when setting with an ndarray" + with pytest.raises(ValueError, match=msg): + indexer_li(df)[:, key] = value + + +@pytest.mark.parametrize( + "value", + [ + [(1, 2, 3), (4, 5, 6)], + [[1, 2, 3], [4, 5, 6]], + np.array([[1, 2, 3], [4, 5, 6]]), + ], + ids=["tuples", "lists", "ndarray"], +) +def test_setitem_2d_value_scalar_row_multi_column(value, indexer_li): + # GH#65264 one nested value per column under a scalar row key is a 2D value + # on the split path, so a row that is not len(key) long has to raise + df = pd.DataFrame( + { + "a": np.array([None] * 3, dtype=object), + "b": np.array([None] * 3, dtype=object), + "c": [1, 2, 3], + } + ) + key = ["a", "b"] if indexer_li is tm.loc else [0, 1] + + msg = "Must have equal len keys and value when setting with an ndarray" + with pytest.raises(ValueError, match=msg): + indexer_li(df)[0, key] = value + + +@pytest.mark.parametrize( + "value", + [ + [(1, 2, 3), (4, 5, 6), (7, 8, 9)], + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], + np.arange(1, 10).reshape(3, 3), + ], + ids=["tuples", "lists", "ndarray"], +) +def test_setitem_2d_value_wrong_shape_all_false_mask(value, indexer_li): + # GH#65264 the shape mismatch must be caught even when the row mask selects + # nothing: a value as long as the frame reaches the zero-length carve-out + df = pd.DataFrame({"a": ["x", "y", "z"], "b": [1, 2, 3], "c": [4.0, 5.0, 6.0]}) + key = ["b", "c"] if indexer_li is tm.loc else [1, 2] + + msg = "Must have equal len keys and value when setting with an ndarray" + with pytest.raises(ValueError, match=msg): + indexer_li(df)[np.zeros(3, dtype=bool), key] = value + + +def test_object_dtype_series_set_series_element(): + # GH 48933 + s1 = pd.Series(dtype="O", index=["a", "b"]) + + s1["a"] = pd.Series() + s1.loc["b"] = pd.Series() + + tm.assert_series_equal(s1.loc["a"], pd.Series()) + tm.assert_series_equal(s1.loc["b"], pd.Series()) + + s2 = pd.Series(dtype="O", index=["a", "b"]) + + s2.iloc[1] = pd.Series() + tm.assert_series_equal(s2.iloc[1], pd.Series()) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_loc.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_loc.py new file mode 100644 index 0000000000000000000000000000000000000000..427fa5b618640c5da4ed42de038c55f50e3c60e6 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_loc.py @@ -0,0 +1,4311 @@ +"""test label based indexing with loc""" + +from collections import namedtuple +import contextlib +from datetime import ( + date, + datetime, + time, + timedelta, +) +import re + +from dateutil.tz import gettz +import numpy as np +import pytest + +from pandas._libs import index as libindex +from pandas.errors import ( + IndexingError, + Pandas4Warning, +) +import pandas.util._test_decorators as td + +import pandas as pd +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 = pd.DataFrame({"A": series}) + df.loc[:, "A"] = new_series + expected = pd.DataFrame({"A": expected_ser}) + tm.assert_frame_equal(df.isna(), expected) + tm.assert_frame_equal(df.notna(), ~expected) + + +@pytest.mark.parametrize("key", [[1, 2], slice(1, 3)]) +def test_loc_dtype(key): + # GH 60600, # GH 63071 + df = pd.DataFrame([["a", 1.0, 2.0], ["b", 3.0, 4.0]]) + result = df.loc[0, key] + expected = pd.Series([1.0, 2.0], index=[1, 2], dtype=float, name=0) + tm.assert_series_equal(result, expected) + + +class TestLoc: + def test_loc_dateoffset_columns(self): + # GH#20948 - .loc with DateOffset columns + offsets = pd.Series(data=[-15, -10, -5, 0, 5, 10, 15], dtype=float).map( + pd.DateOffset + ) + df = pd.DataFrame(index=[0, 1], columns=pd.Index(offsets)) + + # read access + result = df.loc[0, offsets[0]] + assert result is np.nan + + # write access + df.loc[0, offsets[0]] = 1 + assert df.loc[0, offsets[0]] == 1 + + def test_none_values_on_string_columns(self, using_infer_string): + # Issue #32218 + df = pd.DataFrame(["1", "2", None], columns=["a"], dtype=object) + assert df.loc[2, "a"] is None + + df = pd.DataFrame(["1", "2", None], columns=["a"], dtype="str") + if using_infer_string: + assert np.isnan(df.loc[2, "a"]) + else: + assert df.loc[2, "a"] is None + + def test_loc_getitem_int(self, frame_or_series): + # int label + obj = frame_or_series(range(3), index=pd.Index(list("abc"), dtype=object)) + check_indexing_smoketest_or_raises(obj, "loc", 2, fails=KeyError) + + def test_loc_getitem_label(self, frame_or_series): + # label + obj = frame_or_series() + check_indexing_smoketest_or_raises(obj, "loc", "c", fails=KeyError) + + @pytest.mark.parametrize("key", ["f", 20]) + @pytest.mark.parametrize( + "index", + [ + pd.Index(list("abcd"), dtype=object), + pd.Index([2, 4, "null", 8], dtype=object), + pd.date_range("20130101", periods=4), + pd.Index(range(0, 8, 2), dtype=np.float64), + pd.Index([]), + ], + ) + def test_loc_getitem_label_out_of_range(self, key, index, frame_or_series): + obj = frame_or_series(range(len(index)), index=index) + # out of range label + check_indexing_smoketest_or_raises(obj, "loc", key, fails=KeyError) + + @pytest.mark.parametrize("key", [[0, 1, 2], [1, 3.0, "A"]]) + @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64]) + def test_loc_getitem_label_list(self, key, dtype, frame_or_series): + obj = frame_or_series(range(3), index=pd.Index([0, 1, 2], dtype=dtype)) + # list of labels + check_indexing_smoketest_or_raises(obj, "loc", key, fails=KeyError) + + @pytest.mark.parametrize( + "index", + [ + None, + pd.Index([0, 1, 2], dtype=np.int64), + pd.Index([0, 1, 2], dtype=np.uint64), + pd.Index([0, 1, 2], dtype=np.float64), + pd.MultiIndex.from_arrays([range(3), range(3)]), + ], + ) + @pytest.mark.parametrize( + "key", [[0, 1, 2], [0, 2, 10], [3, 6, 7], [(1, 3), (1, 4), (2, 5)]] + ) + def test_loc_getitem_label_list_with_missing(self, key, index, frame_or_series): + if index is None: + obj = frame_or_series() + else: + obj = frame_or_series(range(len(index)), index=index) + check_indexing_smoketest_or_raises(obj, "loc", key, fails=KeyError) + + @pytest.mark.parametrize("dtype", [np.int64, np.uint64]) + def test_loc_getitem_label_list_fails(self, dtype, frame_or_series): + # fails + obj = frame_or_series(range(3), pd.Index([0, 1, 2], dtype=dtype)) + check_indexing_smoketest_or_raises( + obj, "loc", [20, 30, 40], axes=1, fails=KeyError + ) + + def test_loc_getitem_bool(self, frame_or_series): + obj = frame_or_series() + # boolean indexers + b = [True, False, True, False] + + check_indexing_smoketest_or_raises(obj, "loc", b, fails=IndexError) + + @pytest.mark.parametrize( + "slc, indexes, axes, fails", + [ + [ + slice(1, 3), + [ + pd.Index(list("abcd"), dtype=object), + pd.Index([2, 4, "null", 8], dtype=object), + None, + pd.date_range("20130101", periods=4), + pd.Index(range(0, 12, 3), dtype=np.float64), + ], + None, + TypeError, + ], + [ + slice("20130102", "20130104"), + [pd.date_range("20130101", periods=4)], + 1, + TypeError, + ], + [slice(2, 8), [pd.Index([2, 4, "null", 8], dtype=object)], 0, TypeError], + [slice(2, 8), [pd.Index([2, 4, "null", 8], dtype=object)], 1, KeyError], + [slice(2, 4, 2), [pd.Index([2, 4, "null", 8], dtype=object)], 0, TypeError], + ], + ) + def test_loc_getitem_label_slice(self, slc, indexes, axes, fails, frame_or_series): + # label slices (with ints) + + # real label slices + + # GH 14316 + for index in indexes: + if index is None: + obj = frame_or_series() + else: + obj = frame_or_series(range(len(index)), index=index) + check_indexing_smoketest_or_raises( + obj, + "loc", + slc, + axes=axes, + fails=fails, + ) + + def test_setitem_from_duplicate_axis(self): + # GH#34034 + df = pd.DataFrame( + [[20, "a"], [200, "a"], [200, "a"]], + columns=["col1", "col2"], + index=[10, 1, 1], + ) + df.loc[1, "col1"] = np.arange(2) + expected = pd.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 = pd.DataFrame( + data={ + "channel": [1, 2, 3], + "A": ["String 1", np.nan, "String 2"], + "B": [ + pd.Timestamp("2019-06-11 11:00:00"), + pd.NaT, + pd.Timestamp("2019-06-11 12:00:00"), + ], + } + ) + df2 = pd.DataFrame( + data={"A": ["String 3"], "B": [pd.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 = pd.DataFrame( + data={ + "channel": [1, 2, 3], + "A": ["String 1", "String 3", "String 2"], + "B": [ + pd.Timestamp("2019-06-11 11:00:00"), + pd.Timestamp("2019-06-11 12:00:00"), + pd.Timestamp("2019-06-11 12:00:00"), + ], + } + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "obj, key, exp", + [ + ( + pd.DataFrame([[1]], columns=pd.Index([False])), + pd.IndexSlice[:, False], + pd.Series([1], name=False), + ), + (pd.Series([1], index=pd.Index([False])), False, 1), + ( + pd.DataFrame([[1]], index=pd.Index([False])), + False, + pd.Series([1], name=False), + ), + ], + ) + def test_loc_getitem_single_boolean_arg(self, obj, key, exp): + # GH 44322 + res = obj.loc[key] + if isinstance(exp, (pd.DataFrame, pd.Series)): + tm.assert_equal(res, exp) + else: + assert res == exp + + @pytest.mark.parametrize( + "data", + [ + [datetime(2025, 10, 30)], + [pd.Timestamp(2025, 10, 30)] * 2, + [pd.Timedelta(1)], + [pd.Timedelta(1), pd.Timedelta(2)], + ], + ) + def test_loc_empty_slice_assignment_with_datetime(self, data): + # issue #50942 + # empty slice assignment with datetime or timedelta should not raise exceptions + mask = [False] * len(data) + + df = pd.DataFrame(data=data, columns=["A"]) + expected = df.copy() + df.loc[mask] = df + tm.assert_frame_equal(df, expected) + + +class TestLocBaseIndependent: + # Tests for loc that do not depend on subclassing Base + def test_loc_npstr(self): + # GH#45580 + df = pd.DataFrame(index=pd.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', 'Y-DEC'\), 'foo', 'bar'", + (pd.Period("2019"), "foo", "bar"), + ), + ( + r"Period\('2019', 'Y-DEC'\), 'y1', 'bar'", + (pd.Period("2019"), "y1", "bar"), + ), + ( + r"Period\('2019', 'Y-DEC'\), 'foo', 'z1'", + (pd.Period("2019"), "foo", "z1"), + ), + ( + r"Period\('2018', 'Y-DEC'\), Period\('2016', 'Y-DEC'\), 'bar'", + (pd.Period("2018"), pd.Period("2016"), "bar"), + ), + ( + r"Period\('2018', 'Y-DEC'\), 'foo', 'y1'", + (pd.Period("2018"), "foo", "y1"), + ), + ( + r"Period\('2017', 'Y-DEC'\), 'foo', Period\('2015', 'Y-DEC'\)", + (pd.Period("2017"), "foo", pd.Period("2015")), + ), + ( + r"Period\('2017', 'Y-DEC'\), 'z1', 'bar'", + (pd.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 = pd.DataFrame( + { + "A": [pd.Period("2019"), "x1", "x2"], + "B": [pd.Period("2018"), pd.Period("2016"), "y1"], + "C": [pd.Period("2017"), "z1", pd.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 = pd.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 an ndarray + df = pd.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 = pd.DataFrame( + [[1, 2, "foo", "bar", pd.Timestamp("20130101")]], + columns=["a", "a", "a", "a", "a"], + index=[1], + ) + expected = pd.Series( + [1, 2, "foo", "bar", pd.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_nonunique_string_index(self): + # GH#22500 - .loc setitem with non-unique string index should behave + # consistently with non-unique numeric index + idx = pd.Index(["a", "b", "a"], name="idx") + df = pd.DataFrame({"val": 1.0}, index=idx) + df_10 = pd.DataFrame({"val": 10.0}, index=idx) + expected = pd.DataFrame({"val": [10.0, 1.0, 10.0]}, index=idx) + + # scalar string key + result = df.copy() + result.loc["a", "val"] = df_10.loc["a", "val"] + tm.assert_frame_equal(result, expected) + + # single-element tuple + result = df.copy() + result.loc[("a",), "val"] = df_10.loc[("a",), "val"] + tm.assert_frame_equal(result, expected) + + # boolean mask cross-assignment + result = df.copy() + mask = result.index == "a" + result.loc[mask, "val"] = df_10.loc[mask, "val"] + tm.assert_frame_equal(result, expected) + + def test_loc_setitem_dups(self): + # GH 6541 + df_orig = pd.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 = pd.DataFrame( + {"a": [0, 1, 1], "b": pd.Series([100, 200, 300], dtype="uint32")} + ) + ix = df1["a"] == 1 + newb1 = df1.loc[ix, "b"] + 1 + df1.loc[ix, "b"] = newb1 + expected = pd.DataFrame( + {"a": [0, 1, 1], "b": pd.Series([100, 201, 301], dtype="uint32")} + ) + tm.assert_frame_equal(df1, expected) + + # assigning a new type should get the inferred type + df2 = pd.DataFrame({"a": [0, 1, 1], "b": [100, 200, 300]}, dtype="uint64") + ix = df1["a"] == 1 + newb2 = df2.loc[ix, "b"] + with pytest.raises(TypeError, match="Invalid value"): + df1.loc[ix, "b"] = newb2 + + def test_loc_setitem_dtype(self): + # GH31340 + df = pd.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 = pd.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_loc_setitem_partial_series_preserves_other_columns_dtype(self): + # GH#66105 + df = pd.DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8], "C": [9, 10, 11, 12]}) + df.loc[df["A"] > 1, "B"] = pd.Series([99], index=[2]) + + expected = pd.DataFrame( + { + "A": [1, 2, 3, 4], + "B": [5.0, np.nan, 99.0, np.nan], + "C": [9, 10, 11, 12], + } + ) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_partial_series_preserves_large_int_values(self): + # GH#66105 + df = pd.DataFrame({"A": [2**53 + 1, 2**53 + 3, 2**53 + 5], "B": [1, 2, 3]}) + df.loc[df.index > 0, "B"] = pd.Series([99], index=[1]) + + expected = pd.DataFrame( + { + "A": [2**53 + 1, 2**53 + 3, 2**53 + 5], + "B": [1.0, 99.0, np.nan], + } + ) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_partial_series_multiple_columns(self): + # GH#66105 + df = pd.DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8], "C": [9, 10, 11, 12]}) + df.loc[df["A"] > 1, ["B", "C"]] = pd.Series([99], index=[2]) + + expected = pd.DataFrame( + { + "A": [1, 2, 3, 4], + "B": [5.0, np.nan, 99.0, np.nan], + "C": [9.0, np.nan, 99.0, np.nan], + } + ) + tm.assert_frame_equal(df, expected) + + def test_getitem_label_list_with_missing(self): + s = pd.Series(range(3), index=["a", "b", "c"]) + + # consistency + with pytest.raises(KeyError, match="not in index"): + s[["a", "d"]] + + s = pd.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 = pd.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 = pd.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 \[columns\]\"" + ) + 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 = pd.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[pd.Index(["4"], dtype=object)] + + 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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame({"a": [pd.Timestamp("20130101")], "b": [1]}).iloc[0] + expected = pd.Series([pd.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 pd.DataFrame( + { + "date": pd.date_range("2000-01-01", "2000-01-5"), + "val": pd.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 + df = frame_for_consistency.copy() + with pytest.raises(TypeError, match="Invalid value"): + df.loc[:, "date"] = val + + 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 + + df = frame_for_consistency.copy() + with pytest.raises(TypeError, match="Invalid value"): + df.loc[:, "date"] = "foo" + + 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 + df = frame_for_consistency.copy() + with pytest.raises(TypeError, match="Invalid value"): + df.loc[:, "date"] = 1.0 + + def test_loc_setitem_consistency_single_row(self): + # GH 15494 + # setting on frame with single row + df = pd.DataFrame({"date": pd.Series([pd.Timestamp("20180101")])}) + with pytest.raises(TypeError, match="Invalid value"): + df.loc[:, "date"] = "string" + + 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 = pd.DataFrame(columns=["x", "y"]) + df = pd.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 = pd.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, using_infer_string): + # .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 = pd.MultiIndex.from_arrays(levels, names=["Region", "Site", "RespondentID"]) + + clevels = [ + ["Respondent", "Respondent", "Respondent", "OtherCat", "OtherCat"], + ["Something", "StartDate", "EndDate", "Yes/No", "SomethingElse"], + ] + cols = pd.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 = pd.DataFrame(values, index=mi, columns=cols) + + ctx = contextlib.nullcontext() + if using_infer_string: + ctx = pytest.raises(TypeError, match="Invalid value") + + with ctx: + df.loc[:, ("Respondent", "StartDate")] = pd.to_datetime( + df.loc[:, ("Respondent", "StartDate")] + ) + with ctx: + df.loc[:, ("Respondent", "EndDate")] = pd.to_datetime( + df.loc[:, ("Respondent", "EndDate")] + ) + + if using_infer_string: + # infer-objects won't infer stuff anymore + return + + df = df.infer_objects() + + # 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 + with pytest.raises(TypeError, match="Invalid value"): + df.loc[:, ("Respondent", "Duration")] = df.loc[ + :, ("Respondent", "Duration") + ] / pd.Timedelta(60_000_000_000) + + @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 = pd.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 = pd.Series(df.loc[:, "expected"], name=unit) + tm.assert_series_equal(df.loc[:, unit], expected) + + def test_loc_modify_datetime(self): + # see gh-28837 + df = pd.DataFrame.from_dict( + {"date": [1485264372711, 1485265925110, 1540215845888, 1540282121025]} + ) + + df["date_dt"] = pd.to_datetime(df["date"], unit="ms", cache=True).dt.as_unit( + "us" + ) + + df.loc[:, "date_dt_cp"] = df.loc[:, "date_dt"] + df.loc[[2, 3], "date_dt_cp"] = df.loc[[2, 3], "date_dt"] + + expected = pd.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(pd.to_datetime) + + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_loc_setitem_frame_with_reindex(self, has_ref): + # GH#6254 setting issue + df = pd.DataFrame(index=[3, 5, 4], columns=["A"], dtype=float) + if has_ref: + view = df[:] # noqa: F841 + 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 = pd.Series([2, 3, 1], index=[3, 5, 4], dtype=float) + expected = pd.DataFrame({"A": ser}) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_frame_with_reindex_mixed(self): + # GH#40480 + df = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame({"A": [3.0, 2.0, 1.0], "B": "string"}, index=[1, 2, 3]) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_loc_setitem_empty_frame(self, has_ref): + # 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 = pd.DataFrame(index=index) + df["A"] = np.nan + if has_ref: + view = df[:] # noqa: F841 + 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 = pd.Series(val1, index=keys1, dtype=np.float64) + serb = pd.Series(val2, index=keys2) + expected = pd.DataFrame( + {"A": sera, "B": serb}, columns=pd.Index(["A", "B"]) + ).reindex(index=index) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_loc_setitem_frame(self, has_ref): + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), + index=list("abcd"), + columns=list("ABCD"), + ) + if has_ref: + view = df[:] # noqa: F841 + + 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 = pd.DataFrame({"A": [1, 2, 3], "B": np.nan}) + df.loc[df.B > df.A, "B"] = df.A + expected = pd.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 = pd.DataFrame({1: [1, 2], 2: [3, 4], "a": ["a", "b"]}) + + result = df.loc[0, [1, 2]] + expected = pd.Series( + [1, 3], index=pd.Index([1, 2], dtype=object), dtype="int64", name=0 + ) + tm.assert_series_equal(result, expected) + + expected = pd.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_getitem_single_row_mixed_dtype_subset(self): + # GH#37346 selecting a single row with a list of same-dtype columns + # from a mixed-dtype frame preserves the column dtype rather than + # upcasting to the frame's interleaved dtype + df = pd.DataFrame({"a": [1], "b": [0.1]}) + + result = df.loc[0, ["a"]] + expected = pd.Series([1], index=pd.Index(["a"]), dtype="int64", name=0) + tm.assert_series_equal(result, expected) + assert result.values.dtype == np.int64 + + def test_loc_setitem_frame_multiples(self): + # multiple setting + df = pd.DataFrame( + {"A": ["foo", "bar", "baz"], "B": pd.Series(range(3), dtype=np.int64)} + ) + rhs = df.loc[1:2] + rhs.index = df.index[0:2] + df.loc[0:1] = rhs + expected = pd.DataFrame( + {"A": ["bar", "baz", "baz"], "B": pd.Series([1, 2, 2], dtype=np.int64)} + ) + tm.assert_frame_equal(df, expected) + + # multiple setting with frame on rhs (with M8) + df = pd.DataFrame( + { + "date": pd.date_range("2000-01-01", "2000-01-5", unit="ns"), + "val": pd.Series(range(5), dtype=np.int64), + } + ) + expected = pd.DataFrame( + { + "date": [ + pd.Timestamp("20000101"), + pd.Timestamp("20000102"), + pd.Timestamp("20000101"), + pd.Timestamp("20000102"), + pd.Timestamp("20000103"), + ], + "val": pd.Series([0, 1, 0, 1, 2], dtype=np.int64), + } + ) + expected["date"] = expected["date"].astype("M8[ns]") + 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 = pd.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, + pd.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], + pd.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), + pd.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]], + pd.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), + pd.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"]), + pd.DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]), + pd.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 = pd.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 = pd.DataFrame( + {"date": [pd.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 = pd.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 = pd.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 = [ + pd.to_datetime(42).tz_localize("UTC"), + pd.to_datetime(666).tz_localize("UTC"), + ] + expected = pd.Series(vals, index=pd.Index(["foo", "bar"])) + + ser = pd.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 we are non monotonic + df = pd.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 = pd.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 = pd.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 = pd.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.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( + [ + pd.DataFrame( + np.random.default_rng(2).standard_normal((length, len(columns))), + index=np.arange(length), + columns=columns, + ), + pd.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]), + pd.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 = pd.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 = pd.DataFrame( + np.ones((5, 2)), + index=pd.Index([f"i-{i}" for i in range(5)], name="a"), + columns=pd.Index([f"i-{i}" for i in range(2)], name="a"), + ) + # 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): + # GH13873 + + original_df = pd.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] + assert (sliced_df["a"] == [1, 2, 3]).all() + + # These should not return copies + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 4))) + assert df[0] is not df.loc[:, 0] + + # Same tests for Series + original_series = pd.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] + assert all(sliced_series[:3] == [1, 2, 3]) + + def test_loc_copy_vs_view(self, request): + # GH 15631 + x = pd.DataFrame(zip(range(3), range(3), strict=True), 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 = pd.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 = pd.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 = pd.DataFrame( + {"x": data, "y": np.array([np.nan] * len(data), dtype=object)} + ) + + # appends to fit length of data + df = pd.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 = pd.DataFrame( + {"x": data, "y": np.array([np.nan] * len(data), dtype=object)} + ) + + df = pd.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 = pd.DataFrame({"x": [1.0], "y": [np.nan]}) + df = pd.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 = pd.DataFrame(columns=["x", "y"]) + df.index = df.index.astype(np.int64) + msg = r"None of .*Index.* are in the \[index\]" + with pytest.raises(KeyError, match=msg): + df.loc[[0, 1], "x"] = data + + msg = "setting an array element with a sequence." + with pytest.raises(ValueError, match=msg): + df.loc[0:2, "x"] = data + + def test_indexing_zerodim_np_array(self): + # GH24924 + df = pd.DataFrame([[1, 2], [3, 4]]) + result = df.loc[np.array(0)] + s = pd.Series([1, 2], name=0) + tm.assert_series_equal(result, s) + + def test_series_indexing_zerodim_np_array(self): + # GH24924 + s = pd.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 = pd.Series(data, index=range(2010, 2020)) + + result = pd.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, using_infer_string): + # GH#20388 + + col_data = [str(np.random.default_rng(2).random() * 1e-12) for _ in range(5)] + result = pd.DataFrame(col_data, columns=["A"]) + expected = pd.DataFrame(col_data, columns=["A"]) + tm.assert_frame_equal(result, expected) + + # assigning with loc/iloc attempts to set the values inplace, which + # in this case is successful + if using_infer_string: + with pytest.raises(TypeError, match="Invalid value"): + result.loc[result.index, "A"] = [float(x) for x in col_data] + else: + result.loc[result.index, "A"] = [float(x) for x in col_data] + expected = pd.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#38896 + result["A"] = [float(x) for x in col_data] + expected = pd.DataFrame(col_data, columns=["A"], dtype=float) + tm.assert_frame_equal(result, expected) + + def test_loc_getitem_time_object(self, frame_or_series): + rng = pd.date_range("1/1/2000", "1/5/2000", freq="5min") + mask = (rng.hour == 9) & (rng.minute == 30) + + obj = pd.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.complex128, np.float64, np.int64, bool]) + 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 = pd.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, pd.SparseDtype(dtype, np.array(0, dtype=dtype).item())) + tm.assert_numpy_array_equal(result, expected) + + def test_loc_getitem_listlike_all_retains_sparse(self): + df = pd.DataFrame({"A": pd.array([0, 0], dtype=pd.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 = pd.DataFrame.sparse.from_spmatrix(sp_sparse.eye(5)) + result = df.loc[range(2)] + expected = pd.DataFrame( + [[1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0]], + dtype=pd.SparseDtype("float64", 0.0), + ) + tm.assert_frame_equal(result, expected) + + result = df.loc[range(2)].loc[range(1)] + expected = pd.DataFrame( + [[1.0, 0.0, 0.0, 0.0, 0.0]], dtype=pd.SparseDtype("float64", 0.0) + ) + tm.assert_frame_equal(result, expected) + + def test_loc_getitem_sparse_series(self): + # GH34687 + s = pd.Series([1.0, 0.0, 0.0, 0.0, 0.0], dtype=pd.SparseDtype("float64", 0.0)) + + result = s.loc[range(2)] + expected = pd.Series([1.0, 0.0], dtype=pd.SparseDtype("float64", 0.0)) + tm.assert_series_equal(result, expected) + + result = s.loc[range(3)].loc[range(2)] + expected = pd.Series([1.0, 0.0], dtype=pd.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 = pd.DataFrame( + [[1.0, 0.0, 1.5], [0.0, 2.0, 0.0]], dtype=pd.SparseDtype(float) + ) + result = getattr(df, indexer)[0] + expected = pd.Series([1.0, 0.0, 1.5], dtype=pd.SparseDtype(float), name=0) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("key_type", [iter, np.array, pd.Series, pd.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 = pd.DataFrame(np.random.default_rng(2).normal(size=(10, 4))) + df.index = pd.timedelta_range(start="0s", periods=10, freq="s") + expected = df.loc[pd.Timedelta("0s") :, :] + result = df.loc["0s":, :] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("val,expected", [(2**63 - 1, 1), (2**63, 2)]) + def test_loc_getitem_uint64_scalar(self, val, expected): + # see GH#19399 + df = pd.DataFrame([1, 2], index=[2**63 - 1, 2**63]) + result = df.loc[val] + expected = pd.Series([expected]) + 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 = pd.Series(["a", "b", "c"], index=pd.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 = pd.to_timedelta(range(10), unit="s") + df = pd.DataFrame({"x": range(10)}, dtype="int64", index=tdi) + + df.loc[df.index[indexer], "x"] = 20 + + expected = pd.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 an int/... column uses the values of + # the Categorical + df = pd.DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")}) + with pytest.raises(TypeError, match="Invalid value"): + df.loc[1:2, "a"] = pd.Categorical(["b", "b"], categories=["a", "b"]) + df.loc[2:3, "b"] = pd.Categorical(["b", "b"], categories=["a", "b"]) + + def test_loc_setitem_single_row_categorical(self, using_infer_string): + # GH#25495 + df = pd.DataFrame({"Alpha": ["a"], "Numeric": [0]}) + categories = pd.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 = pd.Series(categories, index=df.index, name="Alpha").astype( + object if not using_infer_string else "str" + ) + tm.assert_series_equal(result, expected) + + # double-check that the non-loc setting retains categoricalness + df["Alpha"] = categories + tm.assert_series_equal(df["Alpha"], pd.Series(categories, name="Alpha")) + + def test_loc_setitem_datetime_coercion(self): + # GH#1048 + df = pd.DataFrame({"c": [pd.Timestamp("2010-10-01")] * 3}) + df.loc[0:1, "c"] = np.datetime64("2008-08-08") + assert pd.Timestamp("2008-08-08") == df.loc[0, "c"] + assert pd.Timestamp("2008-08-08") == df.loc[1, "c"] + with pytest.raises(TypeError, match="Invalid value"): + df.loc[2, "c"] = date(2005, 5, 5) + + @pytest.mark.parametrize("idxer", ["var", ["var"]]) + def test_loc_setitem_datetimeindex_tz(self, idxer, tz_naive_fixture): + # GH#11365 + tz = tz_naive_fixture + idx = pd.date_range(start="2015-07-12", periods=3, freq="h", tz=tz) + expected = pd.DataFrame(1.2, index=idx, columns=["var"]) + # if result started off with object dtype, then the .loc.__setitem__ + # below would retain object dtype + result = pd.DataFrame(index=idx, columns=["var"], dtype=np.float64) + if idxer == "var": + with pytest.raises(TypeError, match="Invalid value"): + result.loc[:, idxer] = expected + else: + # See https://github.com/pandas-dev/pandas/issues/56223 + result.loc[:, idxer] = expected + tm.assert_frame_equal(result, expected) + + def test_loc_setitem_time_key(self): + index = pd.date_range("2012-01-01", "2012-01-05", freq="30min") + df = pd.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 + 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 + 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 = pd.MultiIndex.from_tuples([("A", 4), ("B", "3"), ("A", "2")]) + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi) + obj = df.copy() + obj.loc[:, key] = np.zeros((2, 2), dtype="int64") + expected = pd.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 = pd.Series([1, 2, 3], dtype=any_int_numpy_dtype) + series.loc[0] = 4 + expected = pd.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 = pd.Series(10 * [np.timedelta64(10, "m")]) + ser.loc[[1, 2, 3]] = np.timedelta64(20, "m") + expected = pd.Series(10 * [np.timedelta64(10, "m")]) + expected.loc[[1, 2, 3]] = pd.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 = pd.Series(range(2), dtype="float64") + + msg = "setting an array element with a sequence." + with pytest.raises(ValueError, match=msg): + ser.loc[range(2)] = data + + 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 = pd.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 = pd.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 = pd.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 = pd.Index( + [(1,), (1, 2)], + name="A", + tupleize_cols=False, + ) + df = pd.DataFrame(index=idx) + + result = df.loc[[tpl]] + idx = pd.Index([tpl], name="A", tupleize_cols=False) + expected = pd.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 = pd.Index([idx1, idx2], name="composite_index", tupleize_cols=False) + df = pd.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, using_infer_string): + df = pd.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 = pd.Series( + [np.nan, "qux", np.nan, "qux", np.nan], + dtype=object if not using_infer_string else "str", + ).values + tm.assert_almost_equal(df["str"].values, expected) + + def test_loc_setitem_cast2(self): + # GH#7704 + # dtype conversion on setting + df = pd.DataFrame( + np.random.default_rng(2).random((30, 3)), columns=tuple("ABC") + ) + df["event"] = np.nan + with pytest.raises(TypeError, match="Invalid value"): + df.loc[10, "event"] = "foo" + + def test_loc_setitem_cast3(self): + # Test that data type is preserved . GH#5782 + df = pd.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) + + def test_loc_setitem_numpy_frame_categorical_value(self): + # GH#52927 + df = pd.DataFrame({"a": [1, 1, 1, 1, 1], "b": ["a", "a", "a", "a", "a"]}) + df.loc[1:2, "a"] = pd.Categorical([2, 2], categories=[1, 2]) + + expected = pd.DataFrame({"a": [1, 2, 2, 1, 1], "b": ["a", "a", "a", "a", "a"]}) + tm.assert_frame_equal(df, expected) + + def test_loc_with_nat_in_tzaware_index(self): + # GH#54409 + timestamp = pd.to_datetime("2023-01-01", utc=True) + df = pd.DataFrame( + { + "index": pd.Series([pd.NaT, timestamp]), + "value": pd.Series([0, 1]), + } + ).set_index("index") + + # Works fine when mixing NaT and valid values + result = df.loc[ + pd.Series([pd.NaT, timestamp, timestamp], dtype=df.index.dtype), + "value", + ] + expected = [0, 1, 1] + assert result.tolist() == expected + + # Regression check: all-NaT lookup should return [0], not raise + result = df.loc[ + pd.Series([pd.NaT], dtype=df.index.dtype), + "value", + ] + assert result.tolist() == [0] + + +class TestLocWithEllipsis: + @pytest.fixture + def indexer(self, indexer_li): + # Test iloc while we're here + return indexer_li + + @pytest.fixture + def obj(self, series_with_simple_index, frame_or_series): + obj = series_with_simple_index + if frame_or_series is not pd.Series: + obj = obj.to_frame() + return obj + + def test_loc_iloc_getitem_ellipsis(self, obj, indexer): + result = indexer(obj)[...] + tm.assert_equal(result, obj) + + 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, pd.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 = pd.DataFrame(np.arange(25).reshape(5, 5), **kwargs) + exp_index = pd.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 = pd.MultiIndex.from_product([[0], [1, 1]]) + ser = pd.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 = pd.Series([None], pd.MultiIndex.from_arrays([["Level1"], ["Level2"]])) + result = ser.loc[("Level1", "Level2")] + assert result is None + + midx = pd.MultiIndex.from_product([["Level1"], ["Level2_a", "Level2_b"]]) + ser = pd.Series([None] * len(midx), dtype=object, index=midx) + result = ser.loc[("Level1", "Level2_a")] + assert result is None + + ser = pd.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 = pd.MultiIndex.from_tuples( + zip( + ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + strict=True, + ), + names=["first", "second"], + ) + + result = pd.Series([1, 1, 1, 1, 1, 1, 1, 1], index=index) + result.loc[("baz", "one") : ("foo", "two")] = 100 + + expected = pd.Series([1, 1, 100, 100, 100, 100, 1, 1], index=index) + + tm.assert_series_equal(result, expected) + + def test_loc_setitem_multiindex_boolean_mask(self): + # GH#22500 - boolean mask assignment with MultiIndex + midx = pd.MultiIndex.from_tuples( + [(1, "a"), (1, "b"), (2, "a"), (2, "b")], names=["num", "let"] + ) + df = pd.DataFrame({"val": 1.0}, index=midx) + df_10 = pd.DataFrame({"val": 10.0}, index=midx) + expected = pd.DataFrame({"val": [10.0, 1.0, 1.0, 1.0]}, index=midx) + + result = df.copy() + mask = result.index == (1, "a") + result.loc[mask, "val"] = df_10.loc[mask, "val"] + tm.assert_frame_equal(result, expected) + + def test_loc_getitem_slice_datetime_objs_with_datetimeindex(self): + times = pd.date_range("2000-01-01", freq="10min", periods=10) + ser = pd.Series(range(10), 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 = pd.DataFrame( + {"a": range(10), "b": range(10)}, + index=pd.date_range("2010-01-01", "2010-01-10", unit="ns"), + ) + result = df.loc[["2010-01-01", "2010-01-05"], ["a", "b"]] + expected = pd.DataFrame( + {"a": [0, 4], "b": [0, 4]}, + index=pd.DatetimeIndex(["2010-01-01", "2010-01-05"]).as_unit("ns"), + ) + 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 = pd.MultiIndex.from_tuples( + [ + ("foo", "bar"), + ("foo", "bar"), + ("bah", "bam"), + ("bah", "bam"), + ("foo", "bar"), + ("bah", "bam"), + ], + names=["A", "B"], + ) + df = pd.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 = pd.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 = pd.Series(["a", "b", "c"], dtype="category") + # 0 is not among the categories, so the dtype changes (GH#62369) + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + result.loc[3] = 0 + expected = pd.Series(["a", "b", "c", 0], dtype="object") + tm.assert_series_equal(result, expected) + + def test_additional_categorical_element_loc(self): + # GH#47677 + result = pd.Series(["a", "b", "c"], dtype="category") + result.loc[3] = "a" + expected = pd.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 = pd.Series( + [1, 2, 3], + dtype=pd.CategoricalDtype(pd.Index([1, 2, 3], dtype=any_numeric_ea_dtype)), + ) + # enlarge + srs.loc[3] = np.nan + expected = pd.Series( + [1, 2, 3, np.nan], + dtype=pd.CategoricalDtype(pd.Index([1, 2, 3], dtype=any_numeric_ea_dtype)), + ) + tm.assert_series_equal(srs, expected) + # set into + srs.loc[1] = np.nan + expected = pd.Series( + [1, np.nan, 3, np.nan], + dtype=pd.CategoricalDtype(pd.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 = pd.Series(["a", "b", "c"], dtype="category") + srs_enlarge.loc[3] = na + + srs_setinto = pd.Series(["a", "b", "c", "a"], dtype="category") + srs_setinto.loc[3] = na + + tm.assert_series_equal(srs_enlarge, srs_setinto) + expected = pd.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 = pd.DataFrame( + data=np.arange(2, 22, 2), + index=pd.MultiIndex( + levels=[pd.CategoricalIndex(["a", "b"]), range(10)], + codes=[[0] * 5 + [1] * 5, range(10)], + names=["Index1", "Index2"], + ), + ) + + expected = pd.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 = pd.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 = pd.MultiIndex.from_arrays([lev1, lev2]) + ser = pd.Series([0, 1], index=mi) + result = ser.loc[:, "bar"] + + # TODO: should we have name="bar"? + expected = pd.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 = pd.MultiIndex.from_product( + [list("ab"), list("xy"), [1, 2]], names=["ab", "xy", "num"] + ) + ser = pd.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: + @td.skip_if_no("pyarrow") + def test_loc_setitem_with_expansion_preserves_ea_dtype(self): + # GH#41626 retain index.dtype in setitem-with-expansion + idx = pd.Index([pd.Timestamp(0).date()], dtype="date32[pyarrow]") + df = pd.DataFrame({"A": range(1)}, index=idx) + item = pd.Timestamp("1970-01-02").date() + + df.loc[item] = 1 + + exp_index = pd.Index([idx[0], item], dtype=idx.dtype) + tm.assert_index_equal(df.index, exp_index) + + ser = df["A"].iloc[:-1] + ser.loc[item] = 1 + tm.assert_index_equal(ser.index, exp_index) + + @pytest.mark.parametrize("dtype", ["Int64", "int64[pyarrow]"]) + def test_loc_setitem_with_expansion_fractional_not_truncated(self, dtype): + # Assigning a fractional float to an integer EA column should + # promote to float, not silently truncate. + if dtype == "int64[pyarrow]": + pytest.importorskip("pyarrow") + df = pd.DataFrame({"A": pd.array([1, 2, 3], dtype=dtype)}) + # the promotion warns since 2.5 cannot be held by the integer + # dtype (GH#62369) + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + df.loc[len(df)] = [2.5] + assert df["A"].dtype.kind == "f" + assert df.loc[len(df) - 1, "A"] == 2.5 + + def test_loc_setitem_with_expansion_large_dataframe(self, monkeypatch): + # GH#10692 + size_cutoff = 50 + with monkeypatch.context() as m: + m.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) + # RangeIndex lookups bypass the engine + index = pd.Index(np.arange(size_cutoff)) + result = pd.DataFrame({"x": range(size_cutoff)}, index=index, dtype="int64") + result.loc[size_cutoff] = size_cutoff + expected = pd.DataFrame({"x": range(size_cutoff + 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 = pd.Series(dtype=object) + ser.loc[1] = 1 + tm.assert_series_equal(ser, pd.Series([1], index=range(1, 2))) + ser.loc[3] = 3 + tm.assert_series_equal(ser, pd.Series([1, 3], index=[1, 3])) + + def test_loc_setitem_empty_series_float(self): + # GH#5226 + + # partially set with an empty object series + ser = pd.Series(dtype=object) + ser.loc[1] = 1.0 + tm.assert_series_equal(ser, pd.Series([1.0], index=range(1, 2))) + ser.loc[3] = 3.0 + tm.assert_series_equal(ser, pd.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 = pd.Series(dtype=object) + ser.loc["foo"] = 1 + tm.assert_series_equal(ser, pd.Series([1], index=pd.Index(["foo"]))) + ser.loc["bar"] = 3 + tm.assert_series_equal(ser, pd.Series([1, 3], index=pd.Index(["foo", "bar"]))) + ser.loc[3] = 4 + tm.assert_series_equal( + ser, pd.Series([1, 3, 4], index=pd.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 = pd.Series([0], index=[idxs[0]]) + for ts in idxs: + result.loc[ts] = 1 + expected = pd.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, using_infer_string): + # GH#9516, GH#51363 changed in 3.0 to not cast on Index.insert + dt1 = pd.Timestamp("20130101 09:00:00") + dt2 = pd.Timestamp("20130101 10:00:00") + df = pd.DataFrame() + df.loc[conv(dt1), "one"] = 100 + df.loc[conv(dt2), "one"] = 200 + + expected = pd.DataFrame( + {"one": [100.0, 200.0]}, + index=pd.Index( + [conv(dt1), conv(dt2)], dtype=None if using_infer_string else object + ), + columns=pd.Index(["one"]), + ) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_categorical_column_retains_dtype(self, ordered): + # GH16360 + result = pd.DataFrame({"A": [1]}) + result.loc[:, "B"] = pd.Categorical(["b"], ordered=ordered) + expected = pd.DataFrame({"A": [1], "B": pd.Categorical(["b"], ordered=ordered)}) + tm.assert_frame_equal(result, expected) + + def test_loc_setitem_with_expansion_and_existing_dst(self): + # GH#18308 + start = pd.Timestamp("2017-10-29 00:00:00+0200", tz="Europe/Madrid") + end = pd.Timestamp("2017-10-29 03:00:00+0100", tz="Europe/Madrid") + ts = pd.Timestamp("2016-10-10 03:00:00", tz="Europe/Madrid") + idx = pd.date_range(start, end, inclusive="left", freq="h") + assert ts not in idx # i.e. result.loc setitem is with-expansion + + result = pd.DataFrame(index=idx, columns=["value"]) + result.loc[ts, "value"] = 12 + expected = pd.DataFrame( + [np.nan] * len(idx) + [12], + index=idx.append(pd.DatetimeIndex([ts])), + columns=["value"], + dtype=object, + ) + tm.assert_frame_equal(result, expected) + + def test_setitem_with_expansion(self): + # indexing - setting an element + df = pd.DataFrame( + data=pd.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 = pd.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"] + pd.Timedelta("1s").as_unit("s") + 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 = pd.DataFrame() + df.loc[0, 0] = 1 + df.loc[1, 1] = 2 + df.loc[0, np.inf] = 3 + + result = df.columns + expected = pd.Index([0, 1, np.inf], dtype=np.float64) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("has_ref", [True, False]) + def test_loc_setitem_with_expansion_nonunique_index(self, index, has_ref): + # 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 = pd.DataFrame(arr, index=index) + + # 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, pd.MultiIndex): + assert exp_index[-1][0] == key + else: + assert exp_index[-1] == key + exp_data = np.arange(N + 1).astype(np.int64) + expected = pd.DataFrame(exp_data, index=exp_index) + + is_mi = isinstance(index, pd.MultiIndex) + warn = Pandas4Warning if is_mi else None + mi_msg = "Setting a new row on a DataFrame with a MultiIndex" + ser_mi_msg = "Setting a new value on a Series with a MultiIndex" + + # Add new row, but no new columns + df = orig.copy() + if has_ref: + view = df[:] + with tm.assert_produces_warning(warn, match=mi_msg): + df.loc[key, 0] = N + tm.assert_frame_equal(df, expected) + + # add new row on a Series + ser = orig.copy()[0] + if has_ref: + view = ser[:] + with tm.assert_produces_warning(warn, match=ser_mi_msg): + 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() + if has_ref: + view = df[:] # noqa: F841 + with tm.assert_produces_warning(warn, match=mi_msg): + df.loc[key, 1] = N + expected = pd.DataFrame( + {0: [*list(arr), np.nan], 1: [np.nan] * N + [float(N)]}, + index=exp_index, + ) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_with_expansion_preserves_nullable_int( + self, any_numeric_ea_dtype + ): + # GH#42099 + ser = pd.Series([0, 1, 2, 3], dtype=any_numeric_ea_dtype) + df = pd.DataFrame({"data": ser}) + + result = pd.DataFrame(index=df.index) + result.loc[df.index, "data"] = ser + + tm.assert_frame_equal(result, df, check_column_type=False) + + result = pd.DataFrame(index=df.index) + result.loc[df.index, "data"] = ser._values + tm.assert_frame_equal(result, df, check_column_type=False) + + def test_loc_setitem_with_expansion_str_list_partial(self): + # GH#42099 — partial assignment of a list of strings used to fill + # unselected rows with the literal string "n" (truncated "nan"). + df = pd.DataFrame(index=range(4)) + df.loc[[0, 1, 2], "data"] = ["a", "b", "c"] + expected = pd.DataFrame({"data": ["a", "b", "c", np.nan]}, index=range(4)) + tm.assert_frame_equal(df, expected, check_column_type=False) + + def test_loc_setitem_with_expansion_bool_list_partial(self): + # GH#42099 — partial assignment of a list of bools used to raise + # TypeError because the column was initialized as float64. + df = pd.DataFrame(index=range(4)) + df.loc[[0, 1, 2], "data"] = [True, False, True] + expected = pd.DataFrame( + {"data": [True, False, True, np.nan]}, index=range(4), dtype=object + ) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_with_expansion_dict_partial(self): + # GH#65418 — partial assignment of a dict used to write the dict keys + # positionally instead of aligning its values by key. + df = pd.DataFrame({"a": [10, 20, 30, 40]}) + df.loc[[0, 1, 2], "data"] = {0: "x", 1: "y", 2: "z"} + expected = pd.DataFrame( + {"a": [10, 20, 30, 40], "data": ["x", "y", "z", np.nan]} + ) + tm.assert_frame_equal(df, expected, check_column_type=False) + + # a dict aligns by key, so it matches the equivalent Series and the + # non-expansion (existing-column / null-slice) paths + alt = pd.DataFrame({"a": [10, 20, 30, 40]}) + alt.loc[[0, 1, 2], "data"] = pd.Series({0: "x", 1: "y", 2: "z"}) + tm.assert_frame_equal(df, alt, check_column_type=False) + + def test_loc_setitem_datetimeindex_str_column_name(self): + # GH#47006 - string column name that could be parsed as a datetime + # should not be interpreted as a row indexer + index = pd.DatetimeIndex(["2035-01-01 01:00:00", "2036-01-01 00:00:00"]) + df = pd.DataFrame(index=index) + df.loc[:, "110735"] = 0 + expected = pd.DataFrame({"110735": [0, 0]}, index=index) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_datetimeindex_str_column_name_in_index(self): + # GH#15815 - string column name that parses to a date which *is* + # present in the DatetimeIndex must still be a new column, not a row key + index = pd.date_range("2016-11-01", "2016-12-01", freq="h") + df = pd.DataFrame(index=index, columns=pd.Index([], name="Id")) + df.loc[:, "111916"] = pd.Series(2.0, index=index) + expected = pd.DataFrame( + 2.0, index=index, columns=pd.Index(["111916"], name="Id") + ) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_ea_not_full_column(self): + # GH#39163 + df = pd.DataFrame({"A": range(5)}) + + val = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") + + df.loc[[0, 1, 2], "B"] = val + + bex = val.append(pd.DatetimeIndex([pd.NaT, pd.NaT], dtype=val.dtype)) + expected = pd.DataFrame({"A": range(5), "B": bex}) + assert expected.dtypes["B"] == val.dtype + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_expansion_both(self): + # GH#47503 + ct_arr = np.array([[70, 150], [66, 81]]) + df = pd.DataFrame( + data=ct_arr, + columns=["Outstanding", "Not Outstanding"], + index=["Bank", "Credit Union"], + ) + ctot = df.copy() + + df.loc["Total", :] = ctot.sum(axis=0) + df.loc[:, "Total"] = ctot.sum(axis=1) + + expected = pd.DataFrame( + { + "Outstanding": np.array([70, 66, 136]), + "Not Outstanding": np.array([150, 81, 231]), + "Total": [220, 147, np.nan], + }, + index=["Bank", "Credit Union", "Total"], + ) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_with_expansion_dtype_retention(self): + # GH#6485 + df = pd.DataFrame({"a": range(10)}, dtype="i4") + df.loc[10] = 10 + + expected = pd.DataFrame({"a": range(11)}, dtype="i4") + tm.assert_frame_equal(df, expected) + + ser = df["a"].iloc[:-1] + ser.loc[10] = 10 + tm.assert_series_equal(ser, expected["a"]) + + def test_loc_setitem_with_expansion_dtype_retention_empty(self): + # GH#6485 + df = pd.DataFrame({"a": pd.Series([], dtype="i8")}) + df.loc[0, "a"] = 3 + + expected = pd.DataFrame({"a": [3]}, dtype="i8") + tm.assert_frame_equal(df, expected) + + ser = df["a"].iloc[:-1] + ser.loc[0] = 3 + tm.assert_series_equal(ser, expected["a"]) + + def test_loc_setitem_with_expansion_multi_column(self): + # GH#15231 + df = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"]) + df.loc[2] = pd.Series({"a": 7}) + + expected = pd.DataFrame({"a": [1, 3, 7], "b": [2, 4, np.nan]}) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_with_expansion_categorical(self): + # GH#25383 + df = pd.DataFrame( + { + "reg": [0, 1, 2], + "cat": pd.Categorical(["a", "b", "b"], categories=["a", "b", "c", "d"]), + } + ) + df.loc[3] = (3, "c") + + expected = pd.DataFrame( + { + "reg": [0, 1, 2, 3], + "cat": pd.Categorical( + ["a", "b", "b", "c"], categories=["a", "b", "c", "d"] + ), + } + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.xfail( + reason="Pending decision on whether to special-case empty cases." + ) + def test_loc_setitem_with_expansion_empty_stays_object(self): + # GH#31805 + df = pd.DataFrame(columns=["A", "B", "C"]) + df.loc[0] = [2015, 1, 7.0] + + expected = pd.DataFrame({"A": [2015], "B": [1], "C": [7.0]}, dtype=object) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_with_expansion_retains_ea_dtype(self): + # GH#32346 + ser = pd.Series([1, 2, 3], dtype="Int64") + ser.loc[3] = 4 + expected = pd.Series([1, 2, 3, 4], dtype="Int64") + tm.assert_series_equal(ser, expected) + + @td.skip_if_no("pyarrow") + def test_setitem_with_expansion_pyarrow_scalar_retains_dtype(self): + # GH#52235 + ts1 = pd.Timestamp("2025-09-15") + ts2 = pd.Timestamp("2025-09-16") + ser = pd.Series([ts1], dtype="date32[pyarrow]") + + import pyarrow as pa + + item = pa.scalar(ts2, type="date32") + + ser[1] = item + + expected = pd.Series([ts1, ts2], dtype="date32[pyarrow]") + tm.assert_series_equal(ser, expected) + + @pytest.mark.parametrize("unit", ["s", "ms", "us"]) + @pytest.mark.parametrize( + "values, item", + [ + ( + pd.to_datetime(["2020-01-01", "2020-01-02"]), + pd.Timestamp("2020-01-03"), + ), + (pd.to_timedelta([1, 2], unit="D"), pd.Timedelta(days=3)), + ], + ) + def test_loc_setitem_with_expansion_datetimelike_retains_dtype( + self, values, item, unit + ): + # GH#62523 naive datetime64/timedelta64 setitem-with-expansion used to + # raise AttributeError instead of retaining dtype + # GH#66402 a coarser-than-us unit used to be widened to us, since the + # scalar is constructed at us and inference re-derives the unit from it + values = values.as_unit(unit) + ser = pd.Series(values) + ser.loc[2] = item + expected = pd.Series([*values, item], dtype=values.dtype) + tm.assert_series_equal(ser, expected) + + # a missing (NaT) value should behave the same way + ser2 = pd.Series(values) + ser2.loc[2] = pd.NaT + expected2 = pd.Series([*values, pd.NaT], dtype=values.dtype) + tm.assert_series_equal(ser2, expected2) + + @td.skip_if_no("pyarrow") + def test_loc_setitem_with_expansion_pyarrow_finer_resolution(self): + # GH#62523 expanding with a finer-resolution value that cannot be cast + # down to the original coarser unit should keep the finer unit rather + # than raising ArrowInvalid. The unit change warns since the second + # resolution cannot hold the value (GH#62369). + ser = pd.Series( + pd.to_datetime(["2020-01-01", "2020-01-02"]), dtype="timestamp[s][pyarrow]" + ) + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + ser.loc[2] = pd.Timestamp("2020-01-03 00:00:00.123456") + expected = pd.Series( + [ + pd.Timestamp("2020-01-01"), + pd.Timestamp("2020-01-02"), + pd.Timestamp("2020-01-03 00:00:00.123456"), + ], + dtype="timestamp[us][pyarrow]", + ) + tm.assert_series_equal(ser, expected) + + @pytest.mark.parametrize( + "dtype, item", + [ + # used to raise: pyarrow lets an OverflowError out of the cast. + # Spelled out rather than "str" so the case survives with + # future.infer_string disabled + (pd.StringDtype(na_value=np.nan), 2**70), + # used to raise: BaseMaskedArray._from_sequence rejects NaT + ("Int64", pd.NaT), + # used to land on an arrow period/interval type, which concat + # then coerced back into the int64 column + ("int64[pyarrow]", pd.Period("2021-01-01", freq="D")), + ("int64[pyarrow]", pd.Interval(5, 6)), + # used to raise in _post_expansion_casting, GH#70233 + ("int64[pyarrow]", 2**70), + ], + ) + def test_loc_setitem_with_expansion_lossy_pre_cast(self, dtype, item): + # GH#65431 the pre-cast is only an optimization; when it raises or + # lands on another dtype, the column widens to object + if "pyarrow" in str(dtype): + pytest.importorskip("pyarrow") + df = pd.DataFrame({"a": pd.Series([1, 2], dtype=dtype)}) + original = list(df["a"]) + + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + df.loc[2] = [item] + + expected = pd.DataFrame({"a": pd.Series([*original, item], dtype=object)}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "dtype, item", + [ + (pd.StringDtype(na_value=np.nan), 2**70), + ("Int64", pd.NaT), + ("boolean", pd.NaT), + ("int64[pyarrow]", 2**70), + ], + ) + def test_loc_setitem_with_expansion_series_cannot_hold(self, dtype, item): + # GH#70233 a value the dtype cannot hold used to raise instead of + # widening to object + if "pyarrow" in str(dtype): + pytest.importorskip("pyarrow") + ser = pd.Series([1, 0], dtype=dtype) + original = list(ser) + + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + ser.loc[2] = item + + expected = pd.Series([*original, item], dtype=object) + tm.assert_series_equal(ser, expected) + + def test_loc_setitem_with_expansion_all_na_str_large_int(self): + # GH#70233 the value must not be rounded through float64 + pytest.importorskip("pyarrow") + dtype = pd.StringDtype("pyarrow", na_value=np.nan) + ser = pd.Series([np.nan, np.nan], dtype=dtype) + + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + ser.loc[2] = 2**64 - 1 + + expected = pd.Series([np.nan, np.nan, 2**64 - 1], dtype=object) + tm.assert_series_equal(ser, expected) + + def test_loc_setitem_with_expansion_sparse_na(self): + # GH#65431 pre-casting NaN gives Sparse[float64, nan], not the column's + # Sparse[int64, 0]; adopting it used to turn the appended NaN into 0 + df = pd.DataFrame({"a": pd.arrays.SparseArray([0, 1, 2], fill_value=0)}) + + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + df.loc[3] = [np.nan] + + expected = pd.DataFrame({"a": pd.arrays.SparseArray([0.0, 1.0, 2.0, np.nan])}) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_with_expansion_multiindex_retains_dtypes(self): + # GH#17026 + mi = pd.MultiIndex.from_tuples([("a", "c"), ("b", "c"), ("c", "d")]) + expected = pd.DataFrame([[1, 2], [3, 4], [5, 6]], index=mi) + + df = expected.iloc[:-1] + df.loc[("c", "d"), :] = [5, 6] + + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_with_expansion_new_row_and_new_columns(self): + # GH#58316 + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + df.loc["x", ["C", "D"]] = 91 + expected = pd.DataFrame( + { + "A": [1.0, 2.0, 3.0, np.nan], + "B": [4.0, 5.0, 6.0, np.nan], + "C": [np.nan, np.nan, np.nan, 91.0], + "D": [np.nan, np.nan, np.nan, 91.0], + }, + index=pd.Index([0, 1, 2, "x"]), + ) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_with_expansion_duplicate_columns(self): + # GH#58317 + df = pd.DataFrame( + [[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]], + columns=["D", "B", "C", "A"], + ) + item = pd.DataFrame( + [[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]], + columns=["A", "B", "C", "X"], + index=[3, 2, 1], + ) + df.loc[[True, False, True], ["B", "E", "B"]] = item + expected = pd.DataFrame( + [ + [1, np.nan, np.nan, 3, 4, np.nan], + [4, 5.0, 5.0, 6, 7, np.nan], + [7, 5.0, 5.0, 9, 10, np.nan], + ], + columns=["D", "B", "B", "C", "A", "E"], + ) + tm.assert_frame_equal(df, expected) + + +class TestLocCallable: + def test_frame_loc_getitem_callable(self): + # GH#11485 + df = pd.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 = pd.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 = pd.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 = pd.DataFrame( + {"X": [1, 2, 3, 4], "Y": pd.Series(list("aabb"), dtype=object)}, + 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 = pd.DataFrame( + {"col1": ["a", "b", "c"], "col2": [1, 2, 3]}, + index=pd.to_datetime(["2020-08-01", "2020-07-02", "2020-08-05"]), + ) + expected = pd.DataFrame( + {"col1": ["a", "c"], "col2": [1, 3]}, + index=pd.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 = pd.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 = pd.DataFrame({"x": range(3)}, index=pd.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=pd.DatetimeIndex( + [ + pd.Timestamp("2019-12-30"), + pd.Timestamp("2020-01-01"), + pd.Timestamp("2019-12-25"), + pd.Timestamp("2020-01-02 23:59:59.999999999"), + pd.Timestamp("2019-12-19"), + ], + tz=tz_aware_fixture, + ), + ) + expected = frame_or_series( + [1] * 2, + index=pd.DatetimeIndex( + [ + pd.Timestamp("2020-01-01"), + pd.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 = pd.DataFrame( + np.arange(4.0, dtype="float64"), + index=[datetime(2001, 1, i, 10, 00) for i in [1, 2, 3, 4]], + ) + + # duplicates + df_dups = pd.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 = pd.date_range( + "2017-10-29 01:30:00", tz="Europe/Berlin", periods=5, freq="30 min" + ) + series2 = pd.Series([0, 1, 2, 3, 4], index=idx) + + t_1 = pd.Timestamp("2017-10-29 02:30:00+02:00", tz="Europe/Berlin") + t_2 = pd.Timestamp("2017-10-29 02:00:00+01:00", tz="Europe/Berlin") + result = series2.loc[t_1:t_2] + expected = pd.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"), + pd.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 = pd.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 = pd.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 = pd.Series(range(11), pd.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=[pd.Timestamp("2016"), pd.Timestamp("2019"), pd.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 = pd.DataFrame({"test": 1, 1: 2, 2: 3}, index=[0]) + expected = pd.DataFrame( + data=[[2, 3]], index=[0], columns=pd.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=pd.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 = pd.DataFrame({"x": range(10)}) + df.index = pd.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, strict=True): + result = df.copy() + result.loc[cond, "x"] = 10 + + expected = pd.DataFrame( + data, + index=pd.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 = pd.date_range("20010101", periods=4, tz=tz) + df = pd.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 = pd.DataFrame( + np.arange(6.0).reshape(3, 2), + columns=list("AB"), + index=pd.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 = pd.Timedelta(0) + td2 = pd.Timedelta(28767471428571405) + df = pd.DataFrame({"col": pd.Series([td1, td2])}) + df_copy = df.copy() + ser = pd.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) + + 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 = pd.DataFrame(values, index=expected.index, columns=expected.columns) + tm.assert_frame_equal(float_frame, expected) + + def test_loc_setitem_ndframe_values_alignment(self): + # GH#45501 + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + df.loc[[False, False, True], ["a"]] = pd.DataFrame( + {"a": [10, 20, 30]}, index=[2, 1, 0] + ) + + expected = pd.DataFrame({"a": [1, 2, 10], "b": [4, 5, 6]}) + tm.assert_frame_equal(df, expected) + + # same thing with Series RHS + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + df.loc[[False, False, True], ["a"]] = pd.Series([10, 11, 12], index=[2, 1, 0]) + tm.assert_frame_equal(df, expected) + + # same thing but setting "a" instead of ["a"] + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + df.loc[[False, False, True], "a"] = pd.Series([10, 11, 12], index=[2, 1, 0]) + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + df_orig = df.copy() + ser = df["a"] + ser.loc[[False, False, True]] = pd.Series([10, 11, 12], index=[2, 1, 0]) + tm.assert_frame_equal(df, df_orig) + + def test_loc_indexer_empty_broadcast(self): + # GH#51450 + df = pd.DataFrame({"a": [], "b": []}, dtype=object) + expected = df.copy() + df.loc[np.array([], dtype=np.bool_), ["a"]] = df["a"].copy() + tm.assert_frame_equal(df, expected) + + def test_loc_indexer_all_false_broadcast(self): + # GH#51450 + df = pd.DataFrame({"a": ["x"], "b": ["y"]}, dtype=object) + expected = df.copy() + df.loc[np.array([False], dtype=np.bool_), ["a"]] = df["b"].copy() + tm.assert_frame_equal(df, expected) + + def test_loc_indexer_length_one(self): + # GH#51435 + df = pd.DataFrame({"a": ["x"], "b": ["y"]}, dtype=object) + expected = pd.DataFrame({"a": ["y"], "b": ["y"]}, dtype=object) + df.loc[np.array([True], dtype=np.bool_), ["a"]] = df["b"].copy() + 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 = pd.CategoricalIndex(["A", "B", np.nan]) + ser = pd.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 = pd.Series([2, 5, 8, 11], pd.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 = pd.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 = pd.date_range("2011-01-01", "2011-01-02", freq="D", name="idx") + if to_period: + idx = idx.to_period("D") + ser = pd.Series([0.1, 0.2], index=idx, name="s") + + keys = [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")] + if to_period: + keys = [x.to_period("D") for x in keys] + result = ser.loc[keys] + exp = pd.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 = [ + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-01"), + ] + if to_period: + keys = [x.to_period("D") for x in keys] + exp = pd.Series( + [0.2, 0.2, 0.1], index=pd.Index(keys, name="idx", dtype=idx.dtype), name="s" + ) + result = ser.loc[keys] + tm.assert_series_equal(result, exp, check_index_type=True) + + keys = [ + pd.Timestamp("2011-01-03"), + pd.Timestamp("2011-01-02"), + pd.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#17110 - loc should preserve the original index name, + # not adopt the key's index name + df = pd.DataFrame( + [[1, 2], [4, 5], [7, 8]], + index=["cobra", "viper", "sidewinder"], + columns=["max_speed", "shield"], + ) + expected = df.iloc[:2] + result = df.loc[pd.Index(["cobra", "viper"], name="foo")] + tm.assert_frame_equal(result, expected) + assert result.index.name is None + + def test_loc_setitem_single_column_listlike_value(self): + # GH#44103 + df = pd.DataFrame({"a": [None, "two"]}, index=[0, 1], dtype="string") + df.loc[0, ["a"]] = ["one"] + expected = pd.DataFrame({"a": ["one", "two"]}, index=[0, 1], dtype="string") + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_single_column_ea_value(self): + # GH#44103 + df = pd.DataFrame({"a": [None, "two"]}, index=[0, 1], dtype="string") + df.loc[0, ["a"]] = pd.array(["one"], dtype="string") + expected = pd.DataFrame({"a": ["one", "two"]}, index=[0, 1], dtype="string") + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_multi_column_listlike_value(self): + # GH#44103 - multi-column assignment with a list-like value on a + # single-block DataFrame (EA dtype) + df = pd.DataFrame( + {"a": [None, "two"], "b": ["1", "2"]}, index=[0, 1], dtype="string" + ) + df.loc[0, ["a", "b"]] = ["new_a", "new_b"] + expected = pd.DataFrame( + {"a": ["new_a", "two"], "b": ["new_b", "2"]}, + index=[0, 1], + dtype="string", + ) + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize( + "indexer_name, col_key", + [ + ("loc", ["a", "b"]), + ("iloc", [0, 1]), + ("loc", [True, True]), + ("loc", slice("a", "b")), + ("iloc", slice(0, 2)), + ], +) +@pytest.mark.parametrize( + "value", + [ + [[1, 2], [3, 4]], + [(1, 2), (3, 4)], + [[1, 2], [3, 4, 5]], + ([1, 2], [3, 4]), + ([1, 2], [3, 4, 5]), + ], +) +def test_setitem_int_row_listlike_cols_nested_value(indexer_name, col_key, value): + # GH#65241 the GH#44103 fix forced the split path for a scalar row plus + # list-like columns on any single-block frame; on non-extension blocks + # that transposed nested values and raised on ragged ones + df = pd.DataFrame({"a": [1, "x"], "b": [2, "y"]}, dtype=object) + assert df._mgr.is_single_block and not df._mgr.blocks[0].is_extension + + getattr(df, indexer_name)[0, col_key] = value + + expected = pd.DataFrame({"a": [value[0], "x"], "b": [value[1], "y"]}, dtype=object) + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize("indexer_name, col_key", [("loc", ["a"]), ("iloc", [0])]) +def test_setitem_int_row_single_col_nested_value(indexer_name, col_key): + # GH#65241 the split path raised ValueError for a length-1 list of lists + df = pd.DataFrame({"a": [1, "x"], "b": [2, "y"]}, dtype=object) + + getattr(df, indexer_name)[0, col_key] = [[1, 2]] + + expected = pd.DataFrame({"a": [[1, 2], "x"], "b": [2, "y"]}, dtype=object) + tm.assert_frame_equal(df, expected) + + +def test_loc_setitem_int_row_length_mismatch_message(): + # GH#65241 a numpy-dtype single-block frame takes the non-split path, where + # numpy raises; frames that take the split path get pandas' message + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + assert df._mgr.is_single_block + with pytest.raises(ValueError, match="setting an array element with a sequence"): + df.loc[0, ["a", "b"]] = [7, 8, 9] + + df2 = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": ["u", "v"]}) + assert not df2._mgr.is_single_block + msg = "Must have equal len keys and value when setting with an iterable" + with pytest.raises(ValueError, match=msg): + df2.loc[0, ["a", "b"]] = [7, 8, 9] + + +@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 = pd.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 = pd.DataFrame(rand_data) + result.loc[:, 0.5] = np.nan + expected_data = np.hstack((rand_data, np.array([np.nan] * 8).reshape(8, 1))) + expected = pd.DataFrame(expected_data, columns=[0.0, 1.0, 2.0, 3.0, 0.5]) + tm.assert_frame_equal(result, expected) + + result = pd.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 = pd.DataFrame( + np.ones((10, 8)), + index=tuple("ABCDEFGHIJ"), + columns=pd.MultiIndex.from_tuples(cols), + ) + result = df.loc(axis=1)[(2014, 9) : (2015, 8)] + expected = pd.DataFrame( + np.ones((10, 4)), + index=tuple("ABCDEFGHIJ"), + columns=pd.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 = pd.DataFrame( + "a", index=range(2), columns=pd.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 = pd.Series(range(2), pd.Index([1, 2.0], dtype=object)) + + result = ser.loc[1] + assert result == 0 + + +def test_loc_with_positional_slice_raises(): + # GH#31840 + ser = pd.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 = pd.date_range("2016-01-01", periods=3) + df = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), + columns=["a", "b", "c"], + index=pd.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 = pd.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 = pd.date_range("1/1/2000", periods=8) + cols = ["A", "B", "C", "D", "E", "F"] + exp = pd.DataFrame(vals, index=idx, columns=cols) + exp.loc[exp.index[1], ("A", "B")] = np.nan + vals[1][0:2] = np.nan + res = pd.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 = pd.MultiIndex.from_product([lev1, lev2, lev3], names=["x", "y", "z"]) + df = pd.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])] + + # GH#18631 all three levels are scalar-indexed so all are dropped; + # the tuple (0, 1) is a scalar label in level y, not a sequence of labels. + # df.loc[:, full_key] should match df[full_key] + expected_loc = df[(lev1[0], lev2[0], lev3[0])] + tm.assert_series_equal(result, expected_loc) + + expected_xs = df.iloc[:, :1] + alt = df.xs((lev1[0], lev2[0], lev3[0]), level=[0, 1, 2], axis=1) + tm.assert_frame_equal(alt, expected_xs) + + # 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 = pd.DataFrame( + data=np.array([[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, pd.NA, pd.NA]]).T, + columns=["a", "b", "c"], + dtype="Int64", + ) + df2 = df.set_index("c") + assert df2.index.dtype == "Int64" + + res = df2.loc[1] + expected = pd.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 = pd.DataFrame([1, 2, 3, 4], columns=["col1"], dtype="uint8") + with pytest.raises(TypeError, match="Invalid value"): + df.loc[2, "col1"] = value # value that can't be held in uint8 + + +@pytest.mark.parametrize( + "fill_val,exp_dtype", + [ + (pd.Timestamp("2022-01-06"), "datetime64[ns]"), + (pd.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 = pd.DatetimeIndex(data, tz=fill_val.tz, dtype=exp_dtype) + df = pd.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 = pd.DatetimeIndex(data, dtype=exp_dtype) + tm.assert_index_equal(df.index, expected_index, exact=True) + + +def test_loc_set_int_dtype(): + # GH#23326 + df = pd.DataFrame([list("abc")]) + df.loc[:, "col1"] = 5 + + expected = pd.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 = pd.PeriodIndex( + ["20181101 1100", "20181101 1200", "20181102 1300", "20181102 1400"], + name="datetime", + freq="B", + ) + mi_series = pd.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 = pd.DataFrame( + { + "strings": pd.Series(["A", "B", "C"], dtype="string[pyarrow]"), + "ids": pd.Series([True, True, False]), + } + ) + new_value = pd.Series(["X", "Y"]) + df.loc[df.ids, "strings"] = new_value + + expected_df = pd.DataFrame( + { + "strings": pd.Series(["X", "Y", "C"], dtype="string[pyarrow]"), + "ids": pd.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 = pd.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 = pd.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))] + msg = "non-monotonic index with a missing label 3" + with pytest.raises(KeyError, match=msg): + s2.loc[3:11] + with pytest.raises(KeyError, match=msg): + 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 = pd.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 = pd.Series( + pd.date_range("2011-01-01", periods=3, tz="US/Eastern"), + index=["a", "b", "c"], + ) + s2 = ser.copy() + expected = pd.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 = pd.Series([arr, 0, 0, 0, 0], index=list("abcde"), dtype=object) + + ser = pd.Series(0, index=list("abcde"), dtype=object) + ser.loc["a"] = arr + tm.assert_series_equal(ser, expected) + + ser = pd.Series(0, index=list("abcde"), dtype=object) + ser.iloc[0] = arr + tm.assert_series_equal(ser, expected) + + @pytest.mark.parametrize("indexer", [pd.IndexSlice["A", :], ("A", slice(None))]) + def test_loc_series_getitem_too_many_dimensions(self, indexer): + # GH#35349 + ser = pd.Series( + index=pd.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 = pd.DataFrame({"A": ["abc", "def"], "B": ["ghi", "jkl"]}, dtype=dtype) + df.loc[0, :] = {"A": "newA", "B": "newB"} + + expected = pd.DataFrame( + {"A": ["newA", "def"], "B": ["newB", "jkl"]}, dtype=dtype + ) + + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_dict_timedelta_multiple_set(self): + # GH 16309 + result = pd.DataFrame(columns=["time", "value"]) + result.loc[1] = {"time": pd.Timedelta(6, unit="s"), "value": "foo"} + result.loc[1] = {"time": pd.Timedelta(6, unit="s"), "value": "foo"} + expected = pd.DataFrame( + [[pd.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 = pd.DataFrame(index=[1, 2], columns=["a"]) + df.loc[1, ["b", "c"]] = [6, 7] + + expected = pd.DataFrame( + { + "a": pd.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 = pd.Series(range(20), index=index) + assert series.loc["2000-01-14"] == 9 + + def test_loc_nonunique_masked_index(self): + # GH 57027 + ids = list(range(11)) + index = pd.Index(ids * 1000, dtype="Int64") + df = pd.DataFrame({"val": np.arange(len(index), dtype=np.intp)}, index=index) + result = df.loc[ids] + expected = pd.DataFrame( + {"val": index.argsort(kind="stable").astype(np.intp)}, + index=pd.Index(np.array(ids).repeat(1000), dtype="Int64"), + ) + tm.assert_frame_equal(result, expected) + + def test_loc_index_alignment_for_series(self): + # GH #56024 + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + other = pd.Series([200, 999], index=[1, 0]) + df.loc[:, "a"] = other + expected = pd.DataFrame({"a": [999, 200], "b": [3, 4]}) + tm.assert_frame_equal(expected, df) + + @pytest.mark.parametrize("dtype", ["str", object]) + def test_loc_reindexing_of_empty_index(self, dtype): + # GH 57735 + df = pd.DataFrame(index=[1, 1, 2, 2], data=["1", "1", "2", "2"], dtype=dtype) + df.loc[pd.Series([False] * 4, index=df.index, name=0), 0] = df[0] + expected = pd.DataFrame( + index=[1, 1, 2, 2], data=["1", "1", "2", "2"], dtype=dtype + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "df, row_index, col_index, expected_df", + [ + [ + pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list("ABC")), + slice(0, 3), + ["A", "B", "C"], + pd.DataFrame([[10, 10, 10], [20, 20, 20]], columns=list("ABC")), + ], + [ + pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list("ABC")), + slice(None), + ["A", "B", "C"], + pd.DataFrame([[10, 10, 10], [20, 20, 20]], columns=list("ABC")), + ], + [ + pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("ABC")), + [True, True, True], + ["A", "B", "C"], + pd.DataFrame( + [[10, 10, 10], [20, 20, 20], [30, 30, 30]], columns=list("ABC") + ), + ], + [ + pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("ABC")), + slice(0, 4), + ["A", "B", "C"], + pd.DataFrame( + [[10, 10, 10], [20, 20, 20], [30, 30, 30]], columns=list("ABC") + ), + ], + [ + pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("ABC")), + slice(None), + slice("A", "C"), + pd.DataFrame( + [[10, 10, 10], [20, 20, 20], [30, 30, 30]], columns=list("ABC") + ), + ], + [ + pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("ABC")), + slice(None), + pd.Series( + { + "A": True, + "C": False, + "B": True, + } + ), + pd.DataFrame( + [[10, 10, 3], [20, 20, 6], [30, 30, 9]], columns=list("ABC") + ), + ], + ], + ) + def test_loc_set_series_to_multiple_columns( + self, df, row_index, col_index, expected_df + ): + # GH 59933 + df.loc[row_index, col_index] = pd.Series([10, 20, 30]) + tm.assert_frame_equal(df, expected_df) + + def test_loc_setitem_matching_index(self): + # GH 25548 + s = pd.Series(0.0, index=list("abcd")) + s1 = pd.Series(1.0, index=list("ab")) + s2 = pd.Series(2.0, index=list("xy")) + + # Test matching indices + s.loc[["a", "b"]] = s1 + + result = s[["a", "b"]] + expected = s1 + tm.assert_series_equal(result, expected) + + # Test unmatched indices + s.loc[["a", "b"]] = s2 + + result = s[["a", "b"]] + expected = pd.Series([np.nan, np.nan], index=["a", "b"]) + tm.assert_series_equal(result, expected) + + +def test_loc_setitem_extension_array_into_object_series(): + # GH#42437 - assigning an ExtensionArray with array-like elements + # to an object-dtype Series via .loc should not raise + pa = pytest.importorskip("pyarrow") + + arr = pd.array([[1, 2], [3, 4], [5, 6]], dtype=pd.ArrowDtype(pa.list_(pa.int64()))) + ser = pd.Series([None, None, None], dtype=object) + ser.loc[:] = arr + expected = pd.Series(list(arr), dtype=object) + tm.assert_series_equal(ser, expected) + + +def test_loc_setitem_expansion_incompatible_dtype_warns(): + # GH#62369 silent dtype change during setitem-with-expansion + df = pd.DataFrame({"a": [1, 2], "b": [3.0, 4.0]}) + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + df.loc[2] = ["x", "y"] + assert df["a"].dtype == object + assert df["b"].dtype == object + + +def test_loc_setitem_expansion_empty_frame_warns(using_infer_string): + # GH#62369 an explicitly-typed empty column is a meaningful dtype, so a + # zero-row frame warns on an incompatible expansion just like a Series + df = pd.DataFrame({"a": pd.Series([], dtype=np.float64)}) + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + df.loc[0] = "x" + expected_dtype = "str" if using_infer_string else object + assert df["a"].dtype == expected_dtype + + +def test_loc_setitem_expansion_ea_column_warns(): + # GH#62369 EA-dtyped columns participate in the expansion deprecation + df = pd.DataFrame({"a": pd.Series([1, 2], dtype="Int64"), "b": [1.5, 2.5]}) + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + df.loc[2] = ["x", "y"] + assert df["a"].dtype == object + assert df["b"].dtype == object + + +def test_loc_setitem_expansion_placeholder_column_no_warning(): + # GH#62369 a column materialized during indexer preprocessing carries a + # np.void NA-proxy placeholder dtype, which is not meaningful to retain, + # so creating it via expansion does not warn + df = pd.DataFrame() + with tm.assert_produces_warning(None): + df.loc[0, "a"] = 5 + assert df["a"].dtype == np.float64 + + +def test_loc_getitem_list_integer_columns_preserves_order(): + # GH#15824 selecting integer-labeled columns with a list must keep the + # requested order even when an extra (non-integer) column is present, so + # that the integer labels are not treated positionally + df = pd.DataFrame([[3, 4], [2, 3]], index=["a", "c"], columns=[1, 0]) + df["odds"] = df[1] / df[0] + result = df.loc[["a", "c"], [1, 0]] + expected = pd.DataFrame( + [[3, 4], [2, 3]], index=["a", "c"], columns=pd.Index([1, 0], dtype=object) + ) + tm.assert_frame_equal(result, expected) + + # the maintainer's canonical MRE uses an integer row index too (integer + # labels on both axes -- the case most prone to positional confusion) + df_int = pd.DataFrame( + np.arange(9).reshape(3, 3), columns=pd.Index([1, 0, "str"], dtype=object) + ) + tm.assert_index_equal( + df_int.loc[[0, 1], [1, 0]].columns, pd.Index([1, 0], dtype=object) + ) + + +@pytest.mark.parametrize("indexer", ["loc", "at"]) +@pytest.mark.parametrize("cast_bar", [False, True]) +def test_setitem_list_into_cell_independent_of_other_column_dtype(indexer, cast_bar): + # GH#25806 assigning a list into a single cell stores the list itself, and + # the result must not depend on an unrelated column's dtype + df = pd.DataFrame([{"foo": None, "bar": None}], index=["a"]) + if cast_bar: + df["bar"] = df["bar"].astype(float) + getattr(df, indexer)["a", "foo"] = ["123"] + assert df.loc["a", "foo"] == ["123"] + + +def test_at_setitem_list_into_cell_categorical_index(): + # GH#25806 scenario 4: with .at the bug only surfaced once the index was + # categorical (with an object index .at already worked) + df = pd.DataFrame([{"foo": None, "bar": None}], index=["a"]) + df["bar"] = df["bar"].astype(float) + df.index = df.index.astype("category") + df.at["a", "foo"] = ["123"] + assert df.loc["a", "foo"] == ["123"] + + +def test_loc_setitem_multi_element_list_into_cell(): + # GH#25806 a multi-element list into a single cell used to raise + # ValueError ("Must have equal len keys and value"); it must store the list + df = pd.DataFrame([{"foo": None, "bar": None}], index=["a"]) + df.loc["a", "foo"] = ["123", "456"] + assert df.loc["a", "foo"] == ["123", "456"] + + +@td.skip_if_no("pyarrow") +def test_loc_setitem_row_expansion_int_ea_float_value(): + # GH#65094 row expansion casts each column back to its original dtype; an + # integral float above 2**53 used to raise ArrowInvalid for ArrowDtype and + # saturate to the dtype's max for masked dtypes + df = pd.DataFrame( + { + "arrow": pd.array([1, 2], dtype="int64[pyarrow]"), + "masked": pd.array([1, 2], dtype="Int64"), + "numpy": [1, 2], + } + ) + + with tm.assert_produces_warning(Pandas4Warning, match="incompatible dtype"): + df.loc[2] = [1.7e18, 2.0**63, 3.0] + + expected = pd.DataFrame( + { + "arrow": pd.array([1, 2, 1700000000000000000], dtype="int64[pyarrow]"), + "masked": pd.array([1.0, 2.0, 2.0**63], dtype="Float64"), + "numpy": [1, 2, 3], + } + ) + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize( + "row_key", [[0, 1, 2], slice(0, 2), np.array([True, True, True, False])] +) +@pytest.mark.parametrize("col_key", [["b"], slice("b", "b")]) +def test_loc_setitem_single_column_key_1d_value(row_key, col_key): + # GH#68021 a column key selecting exactly one column makes the selection + # (N, 1), which a length-N 1-D value could not be broadcast into on a + # single-block frame. .loc reaches the same code path as .iloc only after + # label->position conversion and _maybe_mask_setitem_value. + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + + df.loc[row_key, col_key] = [1.0, 2.0, 3.0] + + expected = pd.DataFrame(np.zeros((4, 3)), columns=list("abc")) + expected["b"] = [1.0, 2.0, 3.0, 0.0] + tm.assert_frame_equal(df, expected) + + +def test_loc_setitem_single_column_key_1d_value_non_unique_index(): + # GH#68021 a duplicated label expands the row selection, so two labels can + # select three rows and consume a length-3 value + df = pd.DataFrame(np.zeros((4, 3)), columns=list("abc"), index=["w", "x", "x", "z"]) + + df.loc[["w", "x"], ["b"]] = [1.0, 2.0, 3.0] + + expected = pd.DataFrame( + np.zeros((4, 3)), columns=list("abc"), index=["w", "x", "x", "z"] + ) + expected["b"] = [1.0, 2.0, 3.0, 0.0] + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize( + "dtype", + [ + "Int64", + # string dtypes + ("python", np.nan), + pytest.param(("pyarrow", np.nan), marks=td.skip_if_no("pyarrow")), + ], +) +@pytest.mark.parametrize( + "box", + [list, np.array, lambda x: pd.Series(x, index=["a"]), pd.Index, pd.array], + ids=["list", "ndarray", "Series", "Index", "pd.array"], +) +def test_loc_setitem_single_column_frame_ea_dtype(dtype, box): + # https://github.com/pandas-dev/pandas/issues/66527 + # column boolean mask that sets into the single column of a 1-column df + if isinstance(dtype, tuple): + dtype = pd.StringDtype(*dtype) + df = pd.DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)}) + + # setting with a 2d dataframe + df.loc[:, box([True])] = df * 2 + + expected = pd.DataFrame({"a": pd.array([1, 2, 3], dtype=dtype) * 2}) + tm.assert_frame_equal(df, expected) + + df.loc[[0, 1], box([True])] = df.loc[[0, 1], :] * 2 + + arr = pd.array([1, 2, 3], dtype=dtype) * 2 + arr[[0, 1]] = arr[[0, 1]] * 2 + expected = pd.DataFrame({"a": arr}) + tm.assert_frame_equal(df, expected) + + # setting with a scalar + df = pd.DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)}) + scalar = df.iloc[1, 0] + + df.loc[:, box([True])] = scalar + + expected = pd.DataFrame({"a": pd.array([scalar] * 3, dtype=dtype)}) + tm.assert_frame_equal(df, expected) + + df.loc[[0, 1], box([True])] = scalar * 2 + + expected = pd.DataFrame( + {"a": pd.array([scalar * 2, scalar * 2, scalar], dtype=dtype)} + ) + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize( + "dtype", + ["float64", "Float64"], +) +@pytest.mark.parametrize( + "box", + [list, np.array, lambda x: pd.Series(x, index=["a"]), pd.Index, pd.array], + ids=["list", "ndarray", "Series", "Index", "pd.array"], +) +def test_loc_setitem_empty_boolean_column_mask(dtype, box): + # https://github.com/pandas-dev/pandas/issues/66255 + df = pd.DataFrame({"a": [1, 2, 3, np.nan]}, dtype=dtype) + df_orig = df.copy() + + # setting scalar + df.loc[:, box([False])] = 100 + + tm.assert_frame_equal(df, df_orig) + + +@pytest.mark.parametrize( + "dtype", + [ + "float64", + pytest.param( + "Float64", + marks=pytest.mark.xfail(reason="Setting frame causes AssertionError"), + ), + ], +) +@pytest.mark.parametrize( + "box", + # Series boolean key needs to be aligned with the indexed axis + [list, np.array, lambda x: pd.Series(x, index=["a"]), pd.Index, pd.array], + ids=["list", "ndarray", "Series", "Index", "pd.array"], +) +def test_loc_setitem_empty_boolean_column_mask_frame_value(dtype, box): + # https://github.com/pandas-dev/pandas/issues/66255 + df = pd.DataFrame({"a": [1, 2, 3, np.nan]}, dtype=dtype) + df_orig = df.copy() + + # setting frame + df.loc[:, box([False])] = df * 2 + + tm.assert_frame_equal(df, df_orig) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_na_indexing.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_na_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ad350a64e4dcd3310ddcdbdf17892c5220af24 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_na_indexing.py @@ -0,0 +1,74 @@ +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] + 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/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_partial.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_partial.py new file mode 100644 index 0000000000000000000000000000000000000000..a6881d816f3a2519e4656f9902e58a09a88f6f9a --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_partial.py @@ -0,0 +1,709 @@ +""" +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 + +from pandas.errors import Pandas4Warning + +import pandas as pd +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 = pd.DataFrame({}, index=pd.RangeIndex(0, name="df_index")) + series = pd.Series(1.23, index=pd.RangeIndex(4, name="series_index")) + + df["series"] = series + expected = pd.DataFrame( + {"series": [1.23] * 4}, + index=pd.RangeIndex(4, name="df_index"), + columns=pd.Index(["series"]), + ) + + 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 = pd.DataFrame() + series = pd.Series(1.23, index=pd.RangeIndex(4, name="series_index")) + df["series"] = series + expected = pd.DataFrame( + {"series": [1.23] * 4}, + index=pd.RangeIndex(4, name="series_index"), + columns=pd.Index(["series"]), + ) + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_zerolen_series_columns_align(self): + # columns will align + df = pd.DataFrame(columns=["A", "B"]) + df.loc[0] = pd.Series(1, index=range(4)) + expected = pd.DataFrame(columns=["A", "B"], index=[0], dtype=np.float64) + tm.assert_frame_equal(df, expected) + + # columns will align + df = pd.DataFrame(columns=["A", "B"]) + df.loc[0] = pd.Series(1, index=["B"]) + + exp = pd.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 = pd.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 = pd.DataFrame(columns=["A", "B"]) + df.loc[3] = [6, 7] # length matches len(df.columns) --> OK! + + exp = pd.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 = pd.DataFrame() + + # GH#17895 setting a row on a DataFrame with no columns + # should expand the index + df.loc[1] = 1 + expected = pd.DataFrame(index=pd.Index([1])) + tm.assert_frame_equal(df, expected) + + df2 = pd.DataFrame() + df2.loc[1] = pd.Series([1], index=["foo"]) + tm.assert_frame_equal(df2, expected) + + df3 = pd.DataFrame() + msg = "cannot set a frame with no defined index and a scalar" + with pytest.raises(ValueError, match=msg): + df3.loc[:, 1] = 1 + + def test_partial_set_empty_frame_existing_label(self): + # GH#17895 setting row on DataFrame with no columns is a no-op + # when the label is already in the index + df = pd.DataFrame(index=[1, 2, 3]) + df.loc[1] = 3 + expected = pd.DataFrame(index=pd.Index([1, 2, 3])) + tm.assert_frame_equal(df, expected) + + def test_partial_set_empty_frame_new_label(self): + # GH#17895 setting row on DataFrame with no columns expands + # the index when the label is new + df = pd.DataFrame(index=[1, 2, 3]) + df.loc[4] = 3 + expected = pd.DataFrame(index=pd.Index([1, 2, 3, 4])) + tm.assert_frame_equal(df, expected) + + def test_partial_set_empty_frame2(self): + # these work as they don't really change + # anything but the index + # GH#5632 + expected = pd.DataFrame( + columns=pd.Index(["foo"]), index=pd.Index([], dtype="object") + ) + + df = pd.DataFrame(index=pd.Index([], dtype="object")) + df["foo"] = pd.Series([], dtype="object") + + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame(index=pd.Index([])) + df["foo"] = pd.Series(df.index) + + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame(index=pd.Index([])) + df["foo"] = df.index + + tm.assert_frame_equal(df, expected) + + def test_partial_set_empty_frame3(self): + expected = pd.DataFrame( + columns=pd.Index(["foo"]), index=pd.Index([], dtype="int64") + ) + expected["foo"] = expected["foo"].astype("float64") + + df = pd.DataFrame(index=pd.Index([], dtype="int64")) + df["foo"] = [] + + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame(index=pd.Index([], dtype="int64")) + df["foo"] = pd.Series(np.arange(len(df)), dtype="float64") + + tm.assert_frame_equal(df, expected) + + def test_partial_set_empty_frame4(self): + df = pd.DataFrame(index=pd.Index([], dtype="int64")) + df["foo"] = range(len(df)) + + expected = pd.DataFrame( + columns=pd.Index(["foo"]), index=pd.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 = pd.DataFrame() + tm.assert_index_equal(df.columns, pd.RangeIndex(0)) + df2 = pd.DataFrame() + df2[1] = pd.Series([1], index=["foo"]) + df.loc[:, 1] = pd.Series([1], index=["foo"]) + tm.assert_frame_equal(df, pd.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 = pd.DataFrame( + {0: pd.Series(1, index=range(4))}, columns=["A", "B", 0] + ) + + df = pd.DataFrame(columns=["A", "B"]) + df[0] = pd.Series(1, index=range(4)) + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame(columns=["A", "B"]) + df.loc[:, 0] = pd.Series(1, index=range(4)) + 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 = pd.DataFrame( + columns=["A", "B", "New"], index=pd.Index([], dtype="int64") + ) + expected["A"] = expected["A"].astype("int64") + expected["B"] = expected["B"].astype("float64") + expected["New"] = expected["New"].astype("float64") + + df = pd.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 = pd.DataFrame(columns=["a", "b", "c c", "d"]) + expected["d"] = expected["d"].astype("int64") + df = pd.DataFrame(columns=["a", "b", "c c"]) + df["d"] = 3 + tm.assert_frame_equal(df, expected) + tm.assert_series_equal(df["c c"], pd.Series(name="c c", dtype=object)) + + # reindex columns is ok + df = pd.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 = pd.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 = pd.DataFrame(pd.Series(dtype=object)) + expected = pd.DataFrame({0: pd.Series(dtype=object)}) + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame(pd.Series(name="foo", dtype=object)) + expected = pd.DataFrame({"foo": pd.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 = pd.DataFrame(index=[0]) + df = df.copy() + df["a"] = 0 + expected = pd.DataFrame(0, index=[0], columns=pd.Index(["a"])) + tm.assert_frame_equal(df, expected) + + def test_partial_set_empty_frame_empty_consistencies(self, using_infer_string): + # GH#6171 + # consistency on empty frames + df = pd.DataFrame(columns=["x", "y"]) + df["x"] = [1, 2] + expected = pd.DataFrame({"x": [1, 2], "y": [np.nan, np.nan]}) + tm.assert_frame_equal(df, expected, check_dtype=False) + + df = pd.DataFrame(columns=["x", "y"]) + df["x"] = ["1", "2"] + expected = pd.DataFrame( + { + "x": pd.Series( + ["1", "2"], + dtype=object if not using_infer_string else "str", + ), + "y": pd.Series([np.nan, np.nan], dtype=object), + } + ) + tm.assert_frame_equal(df, expected) + + df = pd.DataFrame(columns=["x", "y"]) + df.loc[0, "x"] = 1 + expected = pd.DataFrame({"x": [1], "y": [np.nan]}) + tm.assert_frame_equal(df, expected, check_dtype=False) + + +class TestPartialSetting: + # Prior to GH#62523, the 5.0 case was cast to float, which did not match the + # behavior when setting 5.0 in non-expansion cases + @pytest.mark.parametrize("item", [5, 5.0]) + def test_partial_setting(self, indexer_sl, item): + # GH2578, allow ix and friends to partially set + + # series + ser = pd.Series([1, 2, 3]) + expected = pd.Series([1, 2, 3, 5], index=[0, 1, 2, 5]) + + indexer_sl(ser)[5] = item + tm.assert_series_equal(ser, expected) + + def test_cannot_expand_with_iloc_iat(self): + # iloc/iat raise + ser = pd.Series([1, 2, 3]) + + msg = "iloc cannot enlarge its target object" + with pytest.raises(IndexError, match=msg): + ser.iloc[3] = 5.0 + + msg = "index 3 is out of bounds for axis 0 with size 3" + with pytest.raises(IndexError, match=msg): + ser.iat[3] = 5.0 + + def test_partial_setting_frame(self): + df_orig = pd.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" + with pytest.raises(IndexError, match=msg): + df.iat[4, 2] = 5.0 + + # row setting where it exists + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.DataFrame({"A": [0, 2, 4], "B": pd.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 = pd.date_range("1/1/2000", periods=8) + df_orig = pd.DataFrame( + np.random.default_rng(2).standard_normal((8, 4)), + index=dates, + columns=["A", "B", "C", "D"], + ) + + expected = pd.concat( + [df_orig, pd.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() + with tm.assert_produces_warning(Pandas4Warning, match="does not exist"): + df.at[dates[-1] + dates.freq, "A"] = 7 + tm.assert_frame_equal(df, expected) + + exp_other = pd.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() + with tm.assert_produces_warning(Pandas4Warning, match="does not exist"): + 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 = pd.DataFrame([[True, 1], [False, 2]], columns=["female", "fitness"]) + + s = df.loc[1].copy() + s.name = 2 + expected = pd.concat([df, pd.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 = pd.Series([0.1, 0.2], index=[1, 2]) + + # loc equiv to .reindex + expected = pd.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 = pd.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 = pd.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 = pd.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 = pd.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 = pd.Series([0.1, 0.2, 0.3], index=[1, 2, 3]) + expected = pd.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 = pd.Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]) + expected = pd.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 = pd.Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]) + expected = pd.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 = pd.Series([0.1, 0.2, 0.3, 0.4], index=[4, 5, 6, 7]) + expected = pd.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 = pd.Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]) + expected = pd.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 = pd.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 = pd.Index([1, 2], dtype="int64", name="idx") + ser = pd.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 = pd.Index([2, 2, 1], dtype="int64", name="idx") + expected = pd.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 = pd.Index([1, 2, 3], dtype="int64", name="idx") + with pytest.raises(KeyError, match="not in index"): + pd.Series([0.1, 0.2, 0.3], index=idx, name="s").loc[[3, 4, 4]] + + idx = pd.Index([1, 2, 3, 4], dtype="int64", name="idx") + with pytest.raises(KeyError, match="not in index"): + pd.Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[5, 3, 3]] + + idx = pd.Index([1, 2, 3, 4], dtype="int64", name="idx") + with pytest.raises(KeyError, match="not in index"): + pd.Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[5, 4, 4]] + + idx = pd.Index([4, 5, 6, 7], dtype="int64", name="idx") + with pytest.raises(KeyError, match="not in index"): + pd.Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[7, 2, 2]] + + idx = pd.Index([1, 2, 3, 4], dtype="int64", name="idx") + with pytest.raises(KeyError, match="not in index"): + pd.Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[4, 5, 5]] + + # iloc + exp_idx = pd.Index([2, 2, 1, 1], dtype="int64", name="idx") + expected = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ) + df = orig.copy() + + df.loc[key, :] = df.iloc[0] + ex_index = pd.Index( + [*list(orig.index), key], dtype=object, name=orig.index.name + ) + ex_data = np.concatenate([orig.values, df.iloc[[0]].values], axis=0) + expected = pd.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 = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=10, freq="B"), + ) + + # allow object conversion here + df = orig.copy() + df.loc["a", :] = df.iloc[0] + ser = pd.Series(df.iloc[0], name="a") + exp = pd.concat([orig, pd.DataFrame(ser).T.infer_objects()]) + tm.assert_frame_equal(df, exp) + tm.assert_index_equal(df.index, pd.Index([*orig.index.tolist(), "a"])) + assert df.index.dtype == "object" + + @pytest.mark.parametrize( + "idx,labels,expected_idx", + [ + ( + pd.period_range(start="2000", periods=20, freq="D"), + ["2000-01-04", "2000-01-08", "2000-01-12"], + [ + pd.Period("2000-01-04", freq="D"), + pd.Period("2000-01-08", freq="D"), + pd.Period("2000-01-12", freq="D"), + ], + ), + ( + pd.date_range(start="2000", periods=20, freq="D", unit="s"), + ["2000-01-04", "2000-01-08", "2000-01-12"], + [ + pd.Timestamp("2000-01-04").as_unit("s"), + pd.Timestamp("2000-01-08").as_unit("s"), + pd.Timestamp("2000-01-12").as_unit("s"), + ], + ), + ( + 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 pd.Series: + tm.assert_series_equal(expected, obj[labels]) + + @pytest.mark.parametrize( + "idx,labels", + [ + ( + pd.period_range(start="2000", periods=20, freq="D"), + ["2000-01-04", "2000-01-30"], + ), + ( + pd.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 = pd.Series(range(20), index=idx) + df = pd.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", + [ + ( + pd.period_range(start="2000", periods=20, freq="D"), + pd.Index(["4D", "8D"], dtype=object), + ( + r"None of \[Index\(\['4D', '8D'\], dtype='object'\)\] " + r"are in the \[index\]" + ), + ), + ( + pd.date_range(start="2000", periods=20, freq="D"), + pd.Index(["4D", "8D"], dtype=object), + ( + r"None of \[Index\(\['4D', '8D'\], dtype='object'\)\] " + r"are in the \[index\]" + ), + ), + ( + pd.timedelta_range(start="1 day", periods=20), + pd.Index(["2000-01-04", "2000-01-08"], dtype=object), + ( + 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 = pd.Series(range(20), index=idx) + df = pd.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 = pd.DataFrame(range(len(index)), index=index) + expected = pd.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/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_scalar.py b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..3be8a09306b3508051ce120c7e44fe8ea8263ceb --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/indexing/test_scalar.py @@ -0,0 +1,309 @@ +"""test scalar indexing, including at and iat""" + +from datetime import ( + datetime, + timedelta, +) +import itertools + +import numpy as np +import pytest + +import pandas as pd +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("dtype", [np.int64, np.uint64]) + def test_iat_set_ints(self, dtype, frame_or_series): + f = frame_or_series(range(3), index=pd.Index([0, 1, 2], dtype=dtype)) + 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( + "index", + [ + pd.Index(list("abcd"), dtype=object), + pd.date_range("20130101", periods=4), + pd.Index(range(0, 8, 2), dtype=np.float64), + ], + ) + def test_iat_set_other(self, index, frame_or_series): + f = frame_or_series(range(len(index)), index=index) + msg = "iAt based indexing can only have integer indexers" + idx = next(generate_indices(f, False)) + with pytest.raises(ValueError, match=msg): + f.iat[idx] = 1 + + @pytest.mark.parametrize( + "index", + [ + pd.Index(list("abcd"), dtype=object), + pd.date_range("20130101", periods=4), + pd.Index(range(0, 8, 2), dtype=np.float64), + pd.Index(range(0, 8, 2), dtype=np.uint64), + pd.Index(range(0, 8, 2), dtype=np.int64), + ], + ) + def test_at_set_ints_other(self, index, frame_or_series): + f = frame_or_series(range(len(index)), index=index) + 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 = pd.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 = pd.date_range("1/1/2000", periods=8) + df = pd.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", + [ + [ + pd.Series(["2014-01-01", "2014-02-02"], dtype="datetime64[ns]"), + pd.Timestamp("2014-02-02"), + ], + [ + pd.Series(["1 days", "2 days"], dtype="timedelta64[ns]"), + pd.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 = pd.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 = pd.Series([2, 3], [2, 2], dtype="int64") + tm.assert_series_equal(result, expected) + + df = s.to_frame() + result = df.iloc[2] + expected = pd.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 = pd.DataFrame(arr, columns=["A", "A"]) + + result = df.at[0, "A"] + expected = df.iloc[0].copy() + + 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 = pd.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 = pd.DataFrame( + { + "name": ["John", "Anderson"], + "date": [ + pd.Timestamp(2017, 3, 13, 13, 32, 56), + pd.Timestamp(2017, 2, 16, 12, 10, 3), + ], + } + ) + df["date"] = df["date"].dt.tz_localize("Asia/Shanghai") + + expected = pd.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 = pd.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 = pd.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 = pd.DataFrame({"a": [0.0, 1.0], "b": [4, 5]}) + result.iat[0, 0] = None + expected = pd.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 = pd.date_range("2016-01-01", periods=3) + tdi = dti - dti + ser = pd.Series(dti.to_pydatetime(), dtype=object) + ser2 = pd.Series(tdi.to_pytimedelta(), dtype=object) + df = pd.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, pd.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, pd.Timedelta) + + +def test_at_with_tuple_index_get(): + # GH 26989 + # DataFrame.at getter works with Index of tuples + df = pd.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 = pd.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 = pd.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 = pd.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 = pd.Series((0, 1), index=[[False, True]]) + result = s2.at[False] + assert result == 0 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/interchange/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/interchange/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/interchange/test_impl.py b/venv/lib/python3.14/site-packages/pandas/tests/interchange/test_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..ec434d0b454347f8138a76c158d3b6b433d17ce4 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/interchange/test_impl.py @@ -0,0 +1,702 @@ +from datetime import ( + UTC, + datetime, +) + +import numpy as np +import pytest + +from pandas._libs.tslibs import iNaT +from pandas.compat import is_platform_windows +from pandas.compat.pyarrow import pa_version_under22p0 +from pandas.errors import Pandas4Warning + +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.mark.parametrize("data", [("ordered", True), ("unordered", False)]) +def test_categorical_dtype(data): + data_categorical = { + "ordered": pd.Categorical(list("testdata") * 30, ordered=True), + "unordered": pd.Categorical(list("testdata") * 30, ordered=False), + } + df = pd.DataFrame({"A": (data_categorical[data[0]])}) + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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"]) + ) + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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__() + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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__() + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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__() + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + result = from_dataframe(exchange_df) + expected = pd.DataFrame({"weekday": ["Mon", "Tue"]}) + tm.assert_frame_equal(result, expected) + + # check round-trip + # Don't check stacklevel as PyArrow calls the deprecated `__dataframe__` method. + with tm.assert_produces_warning( + Pandas4Warning, match="Interchange", check_stacklevel=False + ): + 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__() + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + result = from_dataframe(exchange_df) + expected = pd.DataFrame({"arr": expected_values}) + tm.assert_frame_equal(result, expected) + + # check round-trip + # Don't check stacklevel as PyArrow calls the deprecated `__dataframe__` method. + with tm.assert_produces_warning( + Pandas4Warning, match="Interchange", check_stacklevel=False + ): + 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) + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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) + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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]), + } + ) + + 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 + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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]), + } + ) + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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 = { + "separator data": [ + "abC|DeF,Hik", + "234,3245.67", + "gSaf,qWer|Gre", + "asd3,4sad|", + np.nan, + ] + } + test_str_data = string_data["separator data"] + [""] + df = pd.DataFrame({"A": test_str_data}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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:] + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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, ()]}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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]}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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) + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + tm.assert_frame_equal(df, from_dataframe(df.__dataframe__())) + + +def test_categorical_to_numpy_dlpack(): + # https://github.com/pandas-dev/pandas/issues/48393 + df = pd.DataFrame({"A": pd.Categorical(["a", "b", "a"])}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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", "14.0.0") + from pyarrow.interchange import from_dataframe as pa_from_dataframe + + expected = pd.DataFrame(data) + # Don't check stacklevel as PyArrow calls the deprecated `__dataframe__` method. + with tm.assert_produces_warning( + Pandas4Warning, match="Interchange", check_stacklevel=False + ): + arrow_df = pa_from_dataframe(expected) + result = from_dataframe(arrow_df) + tm.assert_frame_equal(result, expected, check_column_type=False) + + +def test_multi_chunk_pyarrow() -> None: + pa = pytest.importorskip("pyarrow", "14.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="Cannot do zero copy conversion into multi-column DataFrame block", + ): + pd.api.interchange.from_dataframe(table, allow_copy=False) + + +def test_multi_chunk_column() -> None: + pytest.importorskip("pyarrow", "11.0.0") + ser = pd.Series([1, 2, None], dtype="Int64[pyarrow]") + df = pd.concat([ser, ser], ignore_index=True).to_frame("a") + df_orig = df.copy() + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + with pytest.raises( + RuntimeError, + match="Found multi-chunk pyarrow array, but `allow_copy` is False", + ): + pd.api.interchange.from_dataframe(df.__dataframe__(allow_copy=False)) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + result = pd.api.interchange.from_dataframe(df.__dataframe__(allow_copy=True)) + # Interchange protocol defaults to creating numpy-backed columns, so currently this + # is 'float64'. + expected = pd.DataFrame({"a": [1.0, 2.0, None, 1.0, 2.0, None]}, dtype="float64") + tm.assert_frame_equal(result, expected) + + # Check that the rechunking we did didn't modify the original DataFrame. + tm.assert_frame_equal(df, df_orig) + assert len(df["a"].array._pa_array.chunks) == 2 + assert len(df_orig["a"].array._pa_array.chunks) == 2 + + +def test_timestamp_ns_pyarrow(): + # GH 56712 + pytest.importorskip("pyarrow", "11.0.0") + timestamp_args = { + "year": 2000, + "month": 1, + "day": 1, + "hour": 1, + "minute": 1, + "second": 1, + } + df = pd.Series( + [datetime(**timestamp_args)], + dtype="timestamp[ns][pyarrow]", + name="col0", + ).to_frame() + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + dfi = df.__dataframe__() + result = pd.api.interchange.from_dataframe(dfi)["col0"].item() + + expected = pd.Timestamp(**timestamp_args) + assert result == expected + + +@pytest.mark.parametrize("tz", ["UTC", "US/Pacific"]) +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}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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 pa_version_under22p0: + 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.applymarker(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__() + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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 + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + pd.api.interchange.from_dataframe(df) + + +def test_empty_string_column(): + # https://github.com/pandas-dev/pandas/issues/56703 + df = pd.DataFrame({"a": []}, dtype=str) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + df2 = df.__dataframe__() + result = pd.api.interchange.from_dataframe(df2) + tm.assert_frame_equal(df, result) + + +def test_large_string(): + # GH#56702 + pytest.importorskip("pyarrow") + df = pd.DataFrame({"a": ["x"]}, dtype="large_string[pyarrow]") + # Don't check stacklevel as PyArrow calls the deprecated `__dataframe__` method. + with tm.assert_produces_warning( + Pandas4Warning, match="Interchange", check_stacklevel=False + ): + result = pd.api.interchange.from_dataframe(df.__dataframe__()) + expected = pd.DataFrame({"a": ["x"]}, dtype="str") + tm.assert_frame_equal(result, expected) + + +def test_non_str_names(): + # https://github.com/pandas-dev/pandas/issues/56701 + df = pd.Series([1, 2, 3], name=0).to_frame() + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + names = df.__dataframe__().column_names() + assert names == ["0"] + + +def test_non_str_names_w_duplicates(): + # https://github.com/pandas-dev/pandas/issues/56701 + df = pd.DataFrame({"0": [1, 2, 3], 0: [4, 5, 6]}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + dfi = df.__dataframe__() + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + with pytest.raises( + TypeError, + match=( + "Expected a Series, got a DataFrame. This likely happened because you " + "called __dataframe__ on a DataFrame which, after converting column " + r"names to string, resulted in duplicated names: Index\(\['0', '0'\], " + r"dtype='(str|object)'\). Please rename these columns before using the " + "interchange protocol." + ), + ): + pd.api.interchange.from_dataframe(dfi, allow_copy=False) + + +@pytest.mark.parametrize( + ("data", "dtype", "expected_dtype"), + [ + ([1, 2, None], "Int64", "int64"), + ([1, 2, None], "Int64[pyarrow]", "int64"), + ([1, 2, None], "Int8", "int8"), + ([1, 2, None], "Int8[pyarrow]", "int8"), + ( + [1, 2, None], + "UInt64", + "uint64", + ), + ( + [1, 2, None], + "UInt64[pyarrow]", + "uint64", + ), + ([1.0, 2.25, None], "Float32", "float32"), + ([1.0, 2.25, None], "Float32[pyarrow]", "float32"), + ([True, False, None], "boolean", "bool"), + ([True, False, None], "boolean[pyarrow]", "bool"), + (["much ado", "about", None], pd.StringDtype(na_value=np.nan), "large_string"), + (["much ado", "about", None], "string[pyarrow]", "large_string"), + ( + [datetime(2020, 1, 1), datetime(2020, 1, 2), None], + "timestamp[ns][pyarrow]", + "timestamp[ns]", + ), + ( + [datetime(2020, 1, 1), datetime(2020, 1, 2), None], + "timestamp[us][pyarrow]", + "timestamp[us]", + ), + ( + [ + datetime(2020, 1, 1, tzinfo=UTC), + datetime(2020, 1, 2, tzinfo=UTC), + None, + ], + "timestamp[us, Asia/Kathmandu][pyarrow]", + "timestamp[us, tz=Asia/Kathmandu]", + ), + ], +) +def test_pandas_nullable_with_missing_values( + data: list, dtype: str, expected_dtype: str +) -> None: + # https://github.com/pandas-dev/pandas/issues/57643 + # https://github.com/pandas-dev/pandas/issues/57664 + pa = pytest.importorskip("pyarrow", "14.0.0") + import pyarrow.interchange as pai + + if expected_dtype == "timestamp[us, tz=Asia/Kathmandu]": + expected_dtype = pa.timestamp("us", "Asia/Kathmandu") + + df = pd.DataFrame({"a": data}, dtype=dtype) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + result = pai.from_dataframe(df.__dataframe__())["a"] + assert result.type == expected_dtype + assert result[0].as_py() == data[0] + assert result[1].as_py() == data[1] + assert result[2].as_py() is None + + +@pytest.mark.parametrize( + ("data", "dtype", "expected_dtype"), + [ + ([1, 2, 3], "Int64", "int64"), + ([1, 2, 3], "Int64[pyarrow]", "int64"), + ([1, 2, 3], "Int8", "int8"), + ([1, 2, 3], "Int8[pyarrow]", "int8"), + ( + [1, 2, 3], + "UInt64", + "uint64", + ), + ( + [1, 2, 3], + "UInt64[pyarrow]", + "uint64", + ), + ([1.0, 2.25, 5.0], "Float32", "float32"), + ([1.0, 2.25, 5.0], "Float32[pyarrow]", "float32"), + ([True, False, False], "boolean", "bool"), + ([True, False, False], "boolean[pyarrow]", "bool"), + ( + ["much ado", "about", "nothing"], + pd.StringDtype(na_value=np.nan), + "large_string", + ), + (["much ado", "about", "nothing"], "string[pyarrow]", "large_string"), + ( + [datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3)], + "timestamp[ns][pyarrow]", + "timestamp[ns]", + ), + ( + [datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3)], + "timestamp[us][pyarrow]", + "timestamp[us]", + ), + ( + [ + datetime(2020, 1, 1, tzinfo=UTC), + datetime(2020, 1, 2, tzinfo=UTC), + datetime(2020, 1, 3, tzinfo=UTC), + ], + "timestamp[us, Asia/Kathmandu][pyarrow]", + "timestamp[us, tz=Asia/Kathmandu]", + ), + ], +) +def test_pandas_nullable_without_missing_values( + data: list, dtype: str, expected_dtype: str +) -> None: + # https://github.com/pandas-dev/pandas/issues/57643 + pa = pytest.importorskip("pyarrow", "14.0.0") + import pyarrow.interchange as pai + + if expected_dtype == "timestamp[us, tz=Asia/Kathmandu]": + expected_dtype = pa.timestamp("us", "Asia/Kathmandu") + + df = pd.DataFrame({"a": data}, dtype=dtype) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + result = pai.from_dataframe(df.__dataframe__())["a"] + assert result.type == expected_dtype + assert result[0].as_py() == data[0] + assert result[1].as_py() == data[1] + assert result[2].as_py() == data[2] + + +def test_string_validity_buffer() -> None: + # https://github.com/pandas-dev/pandas/issues/57761 + pytest.importorskip("pyarrow", "11.0.0") + df = pd.DataFrame({"a": ["x"]}, dtype="large_string[pyarrow]") + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + result = df.__dataframe__().get_column_by_name("a").get_buffers()["validity"] + assert result is None + + +def test_string_validity_buffer_no_missing() -> None: + # https://github.com/pandas-dev/pandas/issues/57762 + pytest.importorskip("pyarrow", "11.0.0") + df = pd.DataFrame({"a": ["x", None]}, dtype="large_string[pyarrow]") + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + validity = df.__dataframe__().get_column_by_name("a").get_buffers()["validity"] + assert validity is not None + result = validity[1] + expected = (DtypeKind.BOOL, 1, ArrowCTypes.BOOL, "=") + assert result == expected + + +def test_empty_dataframe(): + # https://github.com/pandas-dev/pandas/issues/56700 + df = pd.DataFrame({"a": []}, dtype="int8") + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + dfi = df.__dataframe__() + result = pd.api.interchange.from_dataframe(dfi, allow_copy=False) + expected = pd.DataFrame({"a": []}, dtype="int8") + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + ("data", "expected_dtype", "expected_buffer_dtype"), + [ + ( + pd.Series(["a", "b", "a"], dtype="category"), + (DtypeKind.CATEGORICAL, 8, "c", "="), + (DtypeKind.INT, 8, "c", "|"), + ), + ( + pd.Series( + [datetime(2022, 1, 1), datetime(2022, 1, 2), datetime(2022, 1, 3)], + dtype="M8[ns]", + ), + (DtypeKind.DATETIME, 64, "tsn:", "="), + (DtypeKind.INT, 64, ArrowCTypes.INT64, "="), + ), + ( + pd.Series(["a", "bc", None]), + (DtypeKind.STRING, 8, ArrowCTypes.STRING, "="), + (DtypeKind.UINT, 8, ArrowCTypes.UINT8, "="), + ), + ( + pd.Series([1, 2, 3]), + (DtypeKind.INT, 64, ArrowCTypes.INT64, "="), + (DtypeKind.INT, 64, ArrowCTypes.INT64, "="), + ), + ( + pd.Series([1.5, 2, 3]), + (DtypeKind.FLOAT, 64, ArrowCTypes.FLOAT64, "="), + (DtypeKind.FLOAT, 64, ArrowCTypes.FLOAT64, "="), + ), + ], +) +def test_buffer_dtype_categorical( + data: pd.Series, + expected_dtype: tuple[DtypeKind, int, str, str], + expected_buffer_dtype: tuple[DtypeKind, int, str, str], +) -> None: + # https://github.com/pandas-dev/pandas/issues/54781 + df = pd.DataFrame({"data": data}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + dfi = df.__dataframe__() + col = dfi.get_column_by_name("data") + assert col.dtype == expected_dtype + assert col.get_buffers()["data"][1] == expected_buffer_dtype + + +def test_from_dataframe_list_dtype(): + pa = pytest.importorskip("pyarrow", "14.0.0") + data = {"a": [[1, 2], [4, 5, 6]]} + tbl = pa.table(data) + result = from_dataframe(tbl) + expected = pd.DataFrame(data) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/interchange/test_spec_conformance.py b/venv/lib/python3.14/site-packages/pandas/tests/interchange/test_spec_conformance.py new file mode 100644 index 0000000000000000000000000000000000000000..8f7754f1e290fd44e88af491349110a15b6885a7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/interchange/test_spec_conformance.py @@ -0,0 +1,189 @@ +""" +A verbatim copy (vendored) of the spec tests. +Taken from https://github.com/data-apis/dataframe-api +""" + +import ctypes +import math + +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + + +@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) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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 + } + ) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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]}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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]}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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, + ) + + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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]} + ) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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))}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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))}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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]}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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}) + with tm.assert_produces_warning(Pandas4Warning, match="Interchange"): + 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/venv/lib/python3.14/site-packages/pandas/tests/interchange/test_utils.py b/venv/lib/python3.14/site-packages/pandas/tests/interchange/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a47bc2752ff32f5eb7630a3960e7611242cb73e3 --- /dev/null +++ b/venv/lib/python3.14/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/venv/lib/python3.14/site-packages/pandas/tests/internals/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/internals/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/internals/test_api.py b/venv/lib/python3.14/site-packages/pandas/tests/internals/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..9368105a1fa5b192e7b223529e527390b9d6d7bf --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/internals/test_api.py @@ -0,0 +1,178 @@ +""" +Tests for the pseudo-public API implemented in internals/api.py and exposed +in core.internals +""" + +import datetime + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm +from pandas.api.internals import create_dataframe_from_blocks +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", + "api", + "ops", + ] + expected = [ + "make_block", + "BlockManager", + "SingleBlockManager", + "concatenate_managers", + ] + + result = [x for x in dir(internals) if not x.startswith("__")] + assert set(result) == set(expected + modules), set(result) ^ set(expected + modules) + + +@pytest.mark.parametrize( + "name", + [ + "Block", + "ExtensionBlock", + ], +) +def test_deprecations(name): + # GH#55139 + msg = f"{name} is deprecated.* Use public APIs instead" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + getattr(internals, name) + + +def test_make_block_2d_with_dti(): + # GH#41168 + dti = pd.date_range("2012", periods=3, tz="UTC") + + msg = "make_block is deprecated" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + blk = api.make_block(dti, placement=[0]) + + assert blk.shape == (1, 3) + assert blk.values.shape == (1, 3) + + +def test_create_block_manager_from_blocks_deprecated(): + # GH#33892 + # If they must, downstream packages should get this from internals.api, + # not internals. + msg = ( + "create_block_manager_from_blocks is deprecated and will be " + "removed in a future version. Use public APIs instead" + ) + with tm.assert_produces_warning(Pandas4Warning, match=msg): + internals.create_block_manager_from_blocks + + +def test_maybe_infer_ndim_deprecated(): + # GH#40226 + msg = "maybe_infer_ndim is deprecated and will be removed in a future version." + arr = np.arange(5) + bp = pd._libs.internals.BlockPlacement([1]) + with tm.assert_produces_warning(DeprecationWarning, match=msg): + internals.api.maybe_infer_ndim(arr, bp, 1) + + +def test_create_dataframe_from_blocks(float_frame): + block = float_frame._mgr.blocks[0] + index = float_frame.index.copy() + columns = float_frame.columns.copy() + + result = create_dataframe_from_blocks( + [(block.values, block.mgr_locs.as_array)], index=index, columns=columns + ) + tm.assert_frame_equal(result, float_frame) + + +def test_create_dataframe_from_blocks_types(): + df = pd.DataFrame( + { + "int": list(range(1, 4)), + "uint": np.arange(3, 6).astype("uint8"), + "float": [2.0, np.nan, 3.0], + "bool": np.array([True, False, True]), + "boolean": pd.array([True, False, None], dtype="boolean"), + "string": list("abc"), + "datetime": pd.date_range("20130101", periods=3), + "datetimetz": pd.date_range("20130101", periods=3).tz_localize( + "Europe/Brussels" + ), + "timedelta": pd.timedelta_range("1 day", periods=3), + "period": pd.period_range("2012-01-01", periods=3, freq="D"), + "categorical": pd.Categorical(["a", "b", "a"]), + "interval": pd.IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)]), + } + ) + + result = create_dataframe_from_blocks( + [(block.values, block.mgr_locs.as_array) for block in df._mgr.blocks], + index=df.index, + columns=df.columns, + ) + tm.assert_frame_equal(result, df) + + +def test_create_dataframe_from_blocks_datetimelike(): + # extension dtypes that have an exact matching numpy dtype can also be + # be passed as a numpy array + index, columns = pd.RangeIndex(3), pd.Index(["a", "b", "c", "d"]) + + block_array1 = np.arange( + datetime.datetime(2020, 1, 1), + datetime.datetime(2020, 1, 7), + step=datetime.timedelta(1), + ).reshape((2, 3)) + block_array2 = np.arange( + datetime.timedelta(1), datetime.timedelta(7), step=datetime.timedelta(1) + ).reshape((2, 3)) + result = create_dataframe_from_blocks( + [(block_array1, np.array([0, 2])), (block_array2, np.array([1, 3]))], + index=index, + columns=columns, + ) + expected = pd.DataFrame( + { + "a": pd.date_range("2020-01-01", periods=3, unit="us"), + "b": pd.timedelta_range("1 days", periods=3, unit="us"), + "c": pd.date_range("2020-01-04", periods=3, unit="us"), + "d": pd.timedelta_range("4 days", periods=3, unit="us"), + } + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "array", + [ + pd.date_range("2020-01-01", periods=3), + pd.date_range("2020-01-01", periods=3, tz="UTC"), + pd.period_range("2012-01-01", periods=3, freq="D"), + pd.timedelta_range("1 day", periods=3), + ], +) +def test_create_dataframe_from_blocks_1dEA(array): + # ExtensionArrays can be passed as 1D even if stored under the hood as 2D + df = pd.DataFrame({"a": array}) + + block = df._mgr.blocks[0] + result = create_dataframe_from_blocks( + [(block.values[0], block.mgr_locs.as_array)], index=df.index, columns=df.columns + ) + tm.assert_frame_equal(result, df) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/internals/test_internals.py b/venv/lib/python3.14/site-packages/pandas/tests/internals/test_internals.py new file mode 100644 index 0000000000000000000000000000000000000000..7530c09fc1ff87a72e85a6a13d902a07d2a1c350 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/internals/test_internals.py @@ -0,0 +1,1584 @@ +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 +from pandas.errors import Pandas4Warning + +from pandas.core.dtypes.common import is_scalar + +import pandas as pd +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, +) + + +@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 = pd.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 = pd.Categorical([1, 1, 2, 2, 3, 3, 3, 3, 4, 4]) + elif typestr in ("category2",): + values = pd.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=()), + pd.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 = pd.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] + [pd.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, temp_file): + blk = create_block(typ, data) + assert_block_equal(tm.round_trip_pickle(blk, temp_file), 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(deep=True) + assert cop is not fblock + assert_block_equal(fblock, cop) + + def test_delete(self, fblock): + newb = fblock.copy(deep=True) + 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(deep=True) + 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(deep=True) + 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(deep=True) + + 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 = pd.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 = pd.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 = list(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, strict=True): + 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" + + mgr = BlockManager(blocks, axes) + with pytest.raises(AssertionError, match=msg): + 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, temp_file): + mgr2 = tm.round_trip_pickle(mgr, temp_file) + tm.assert_frame_equal( + pd.DataFrame._from_mgr(mgr, axes=mgr.axes), + pd.DataFrame._from_mgr(mgr2, axes=mgr2.axes), + ) + + # 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, temp_file): + mgr = create_mgr(mgr_string) + mgr2 = tm.round_trip_pickle(mgr, temp_file) + tm.assert_frame_equal( + pd.DataFrame._from_mgr(mgr, axes=mgr.axes), + pd.DataFrame._from_mgr(mgr2, axes=mgr2.axes), + ) + + def test_categorical_block_pickle(self, temp_file): + mgr = create_mgr("a: category") + mgr2 = tm.round_trip_pickle(mgr, temp_file) + tm.assert_frame_equal( + pd.DataFrame._from_mgr(mgr, axes=mgr.axes), + pd.DataFrame._from_mgr(mgr2, axes=mgr2.axes), + ) + + smgr = create_single_mgr("category") + smgr2 = tm.round_trip_pickle(smgr, temp_file) + tm.assert_series_equal( + pd.Series()._constructor_from_mgr(smgr, axes=smgr.axes), + pd.Series()._constructor_from_mgr(smgr2, axes=smgr2.axes), + ) + + def test_iget(self): + cols = pd.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, pd.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, strict=True): + # view assertion + tm.assert_equal(cp_blk.values, blk.values) + if isinstance(blk.values, np.ndarray): + assert cp_blk.values.base.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, strict=True): + 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, using_infer_string): + 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() + _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() + dtype = "str" if using_infer_string else np.object_ + assert new_mgr.iget(0).dtype == dtype + assert new_mgr.iget(1).dtype == dtype + assert new_mgr.iget(2).dtype == dtype + 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() + assert new_mgr.iget(0).dtype == dtype + assert new_mgr.iget(1).dtype == dtype + assert new_mgr.iget(2).dtype == dtype + 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) + assert not reindexed.is_consolidated() + + tm.assert_index_equal(reindexed.items, pd.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): + 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, pd.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, + ) + tm.assert_almost_equal( + mgr.iget(mgr.items.get_loc("float")).internal_values(), + np.array([1.0, 1.0, 1.0]), + ) + + def test_get_bool_data(self): + 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, pd.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) + tm.assert_numpy_array_equal( + mgr.iget(mgr.items.get_loc("bool")).internal_values(), + np.array([True, True, 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 + + +class TestGetDtypesCache: + # GH#65382 get_dtypes caches the per-column dtypes array on the manager; + # block-mutating operations clear it so it does not keep old blocks alive. + + @staticmethod + def _prime_cache(df): + df.dtypes + assert df._mgr._dtypes_cache is not None + # fills _interleaved_dtype only when there are several blocks + df.iloc[0] + + def test_get_dtypes_returns_copy(self): + df = pd.DataFrame({"a": [1, 2], "b": [1.5, 2.5]}) + mgr = df._mgr + result = mgr.get_dtypes() + assert mgr._dtypes_cache is not None + assert result is not mgr._dtypes_cache[1] + + # mutating the returned array must not corrupt the cache + result[0] = np.dtype("float64") + assert mgr.get_dtypes()[0] == np.dtype("int64") + + def test_iset_multi_column_block_invalidates(self): + # iset replacing one column of a multi-column block with a new dtype + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + self._prime_cache(df) + + df["a"] = np.array([1.5, 2.5]) + assert df._mgr._dtypes_cache is None + expected = pd.Series([np.dtype("float64"), np.dtype("int64")], index=["a", "b"]) + tm.assert_series_equal(df.dtypes, expected) + + def test_iset_single_block_invalidates(self): + # _iset_single fastpath: the column is its own single-column block + df = pd.DataFrame({"a": [1, 2], "b": [1.5, 2.5]}) + self._prime_cache(df) + + df["a"] = np.array([1 + 2j, 3 + 4j]) + assert df._mgr._dtypes_cache is None + assert df._mgr._interleaved_dtype is None + expected = pd.Series( + [np.dtype("complex128"), np.dtype("float64")], index=["a", "b"] + ) + tm.assert_series_equal(df.dtypes, expected) + + def test_insert_invalidates(self): + df = pd.DataFrame({"a": [1, 2], "c": [1.5, 2.5]}) + self._prime_cache(df) + + df.insert(1, "b", np.array([1.5, 2.5])) + assert df._mgr._dtypes_cache is None + assert df._mgr._interleaved_dtype is None + expected = pd.Series( + [np.dtype("int64"), np.dtype("float64"), np.dtype("float64")], + index=["a", "b", "c"], + ) + tm.assert_series_equal(df.dtypes, expected) + + def test_delitem_dtypes_correct(self): + # idelete returns a new manager, which starts with an empty cache + df = pd.DataFrame({"a": [1, 2], "b": [1.5, 2.5]}) + self._prime_cache(df) + + del df["a"] + assert df._mgr._dtypes_cache is None + expected = pd.Series([np.dtype("float64")], index=["b"]) + tm.assert_series_equal(df.dtypes, expected) + + def test_inplace_setitem_same_dtype_keeps_cache_valid(self): + # same-dtype in-place value writes do not change per-column dtypes, + # so the cache may legitimately survive; dtypes must stay correct + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + self._prime_cache(df) + + df.iloc[0, 0] = 10 + expected = pd.Series([np.dtype("int64")] * 2, index=["a", "b"]) + tm.assert_series_equal(df.dtypes, expected) + + def test_iset_split_block_with_reference_dtypes_correct(self): + # with a live reference, in-place setitem goes through + # _iset_split_block (Copy-on-Write); dtypes are unchanged + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + view = df[:] + self._prime_cache(df) + + df.iloc[0, 0] = 10 + # cleared so the caches do not keep the replaced block alive + assert df._mgr._dtypes_cache is None + assert df._mgr._interleaved_dtype is None + expected = pd.Series([np.dtype("int64")] * 2, index=["a", "b"]) + tm.assert_series_equal(df.dtypes, expected) + tm.assert_frame_equal(view, pd.DataFrame({"a": [1, 2], "b": [3, 4]})) + + def test_stale_array_not_used_when_blocks_replaced(self): + # GH#68446 get_dtypes must not keep returning an array it built from + # blocks that a write replaced while it was computing. + df = pd.DataFrame( + {"a": pd.array([1], dtype="Int64"), "b": pd.array([2], dtype="Int64")} + ) + mgr = df._mgr + blocks = mgr.blocks + + class WriteWhileReadingDtypes: + # stands in for a write landing while get_dtypes walks mgr.blocks + def __init__(self, block) -> None: + self.block = block + + @property + def dtype(self): + mgr.blocks = blocks # the write must not see this stand-in + df["b"] = np.array([1.5]) + return self.block.dtype + + mgr._dtypes_cache = None + mgr.blocks = (WriteWhileReadingDtypes(blocks[0]), *blocks[1:]) + mgr.get_dtypes() + + expected = pd.Series([pd.Int64Dtype(), np.dtype("float64")], index=["a", "b"]) + tm.assert_series_equal(df.dtypes, expected) + + def test_entry_stored_after_write_not_used(self): + # GH#68446 a reader racing a write can store its entry after the write + # has invalidated the cache + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + self._prime_cache(df) + stale = df._mgr._dtypes_cache + + df["a"] = np.array([1.5, 2.5]) + df._mgr._dtypes_cache = stale + + expected = pd.Series([np.dtype("float64"), np.dtype("int64")], index=["a", "b"]) + tm.assert_series_equal(df.dtypes, expected) + + +@pytest.mark.parametrize("method", ["row", "to_numpy"]) +def test_interleaved_dtype_entry_stored_after_write_not_used(method): + # GH#68446 same race as TestGetDtypesCache.test_entry_stored_after_write_not_used; + # a stale common dtype would silently truncate 1.5 to 1 + df = pd.DataFrame({"a": [1, 2], "b": np.array([3, 4], dtype="int32")}) + df.iloc[0] + stale = df._mgr._interleaved_dtype + assert stale is not None + + df["b"] = np.array([1.5, 2.5]) + df._mgr._interleaved_dtype = stale + + if method == "row": + result = df.iloc[0] + expected = pd.Series([1.0, 1.5], index=["a", "b"], name=0) + tm.assert_series_equal(result, expected) + else: + result = df.to_numpy() + expected = np.array([[1.0, 1.5], [2.0, 2.5]]) + tm.assert_numpy_array_equal(result, expected) + + +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.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, pd.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, pd.Index(["foo", "bar", "baz"]), fill_value + ) + assert_reindex_axis_is_ok( + mgr, ax, pd.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, pd.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, + pd.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, + pd.Index(["foo", "bar", "baz"]), + np.array([0, 0, 0]), + fill_value, + ) + assert_reindex_indexer_is_ok( + mgr, + ax, + pd.Index(["foo", "bar", "baz"]), + np.array([-1, 0, -1]), + fill_value, + ) + assert_reindex_indexer_is_ok( + mgr, + ax, + pd.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, + pd.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, 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 = pd.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 = pd.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 = pd.IntervalIndex.from_breaks(arr[:-1], closed="neither") + elem = element(ii2) + with pytest.raises(TypeError, match="Invalid value"): + self.check_series_setitem(elem, ii, False) + assert not blk._can_hold_element(elem) + + ii3 = pd.IntervalIndex.from_breaks( + [pd.Timestamp(1), pd.Timestamp(3), pd.Timestamp(4)] + ) + elem = element(ii3) + with pytest.raises(TypeError, match="Invalid value"): + self.check_series_setitem(elem, ii, False) + assert not blk._can_hold_element(elem) + + ii4 = pd.IntervalIndex.from_breaks( + [pd.Timedelta(1), pd.Timedelta(3), pd.Timedelta(4)] + ) + elem = element(ii4) + with pytest.raises(TypeError, match="Invalid value"): + self.check_series_setitem(elem, ii, False) + assert not blk._can_hold_element(elem) + + def test_period_can_hold_element_emptylist(self): + pi = pd.period_range("2016", periods=3, freq="Y") + 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 = pd.period_range("2016", periods=3, freq="Y") + + 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 pytest.raises(TypeError, match="Invalid value"): + self.check_series_setitem(elem, pi, False) + + dti = pi.to_timestamp("s")[:-1] + elem = element(dti) + with pytest.raises(TypeError, match="Invalid value"): + self.check_series_setitem(elem, pi, False) + + def test_period_reindex_axis(self): + # GH#60273 Test reindexing of block with PeriodDtype + pi = pd.period_range("2020", periods=5, freq="Y") + blk = new_block(pi._data.reshape(5, 1), BlockPlacement(slice(5)), ndim=2) + mgr = BlockManager( + blocks=(blk,), axes=[pd.Index(np.arange(5)), pd.Index(["a"])] + ) + reindexed = mgr.reindex_axis(pd.Index([0, 2, 4]), axis=0) + result = pd.DataFrame._from_mgr(reindexed, axes=reindexed.axes) + expected = pd.DataFrame([[pi[0], pi[2], pi[4]]], columns=[0, 2, 4], index=["a"]) + tm.assert_frame_equal(result, expected) + + 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: pd.Index, inplace: bool): + arr = index._data.copy() + ser = pd.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._values is arr # i.e. setting was done inplace + else: + assert ser.dtype == object + + +class TestShouldStore: + def test_should_store_categorical(self): + cat = pd.Categorical(["A", "B", "C"]) + df = pd.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\]" + + depr_msg = "make_block is deprecated" + with pytest.raises(ValueError, match=msg): + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + make_block(values, placement, ndim=2) + + +def test_block_shape(): + idx = pd.Index([0, 1, 2, 3, 4]) + a = pd.Series([1, 2, 3]).reindex(idx) + b = pd.Series(pd.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])) + + depr_msg = "make_block is deprecated" + warn = DeprecationWarning if block_maker is make_block else None + + # NumpyExtensionArray, no dtype + with tm.assert_produces_warning(warn, match=depr_msg): + 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 + with tm.assert_produces_warning(warn, match=depr_msg): + 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 accepts dtype keyword + # ndarray, NumpyEADtype + with tm.assert_produces_warning(warn, match=depr_msg): + 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/venv/lib/python3.14/site-packages/pandas/tests/io/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/conftest.py b/venv/lib/python3.14/site-packages/pandas/tests/io/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..1c47d9b52b2d022314f1a971691431551aa39cba --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/conftest.py @@ -0,0 +1,190 @@ +import os +import uuid + +import pytest + +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", "simple_dataset.feather") + + +@pytest.fixture +def xml_file(datapath): + return datapath("io", "data", "xml", "books.xml") + + +@pytest.fixture(scope="session") +def aws_credentials(monkeysession): + """Mocked AWS Credentials for moto.""" + monkeysession.setenv("AWS_ACCESS_KEY_ID", "testing") + monkeysession.setenv("AWS_SECRET_ACCESS_KEY", "testing") + monkeysession.setenv("AWS_SECURITY_TOKEN", "testing") + monkeysession.setenv("AWS_SESSION_AWS_SESSION_TOKEN", "testing") + monkeysession.setenv("AWS_DEFAULT_REGION", "us-east-1") + + +@pytest.fixture(scope="session") +def moto_server(aws_credentials): + url = os.environ.get("PANDAS_MOTO_URL") + if url: + yield url + else: + moto_server = pytest.importorskip("moto.server") + server = moto_server.ThreadedMotoServer(port=0) + server.start() + host, port = server.get_host_and_port() + yield f"http://{host}:{port}" + server.stop() + + +@pytest.fixture +def moto_s3_resource(moto_server): + boto3 = pytest.importorskip("boto3") + s3 = boto3.resource("s3", endpoint_url=moto_server) + return s3 + + +@pytest.fixture(scope="session") +def s3so(moto_server): + return { + "client_kwargs": { + "endpoint_url": moto_server, + } + } + + +@pytest.fixture +def s3_bucket_public(moto_s3_resource): + """ + Create a public S3 bucket using moto. + """ + bucket_name = f"pandas-test-{uuid.uuid4()}" + bucket = moto_s3_resource.Bucket(bucket_name) + bucket.create(ACL="public-read") + yield bucket + bucket.objects.delete() + bucket.delete() + + +@pytest.fixture +def s3_bucket_private(moto_s3_resource): + """ + Create a private S3 bucket using moto. + """ + bucket_name = f"cant_get_it-{uuid.uuid4()}" + bucket = moto_s3_resource.Bucket(bucket_name) + bucket.create(ACL="private") + yield bucket + bucket.objects.delete() + bucket.delete() + + +@pytest.fixture +def s3_bucket_public_with_data( + s3_bucket_public, 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_bucket_public.put_object(Key=s3_key, Body=f) + return s3_bucket_public + + +@pytest.fixture +def s3_bucket_private_with_data( + s3_bucket_private, 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_bucket_private.put_object(Key=s3_key, Body=f) + return s3_bucket_private + + +_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] diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/excel/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_odf.py b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_odf.py new file mode 100644 index 0000000000000000000000000000000000000000..97670f3dee9c083015531cfaf0b4674c2540ca8e --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_odf.py @@ -0,0 +1,190 @@ +import functools +import uuid + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + +pytest.importorskip("odf") + + +@pytest.fixture +def ext(): + return ".ods" + + +@pytest.fixture +def tmp_excel(ext, tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}{ext}" + tmp.touch() + return str(tmp) + + +from odf.opendocument import OpenDocumentSpreadsheet +from odf.table import ( + CoveredTableCell, + Table, + TableCell, + TableRow, +) + + +@pytest.fixture(autouse=True) +def cd_and_set_engine(monkeypatch, datapath): + func = functools.partial(pd.read_excel, engine="odf") + monkeypatch.setattr(pd, "read_excel", func) + monkeypatch.chdir(datapath("io", "data", "excel")) + + +def test_read_invalid_types_raises(): + # the invalid_value_type.ods required manually editing + # of the included content.xml file + with pytest.raises(ValueError, match="Unrecognized type awesome_new_type"): + pd.read_excel("invalid_value_type.ods") + + +def test_read_writer_table(): + # Also test reading tables from a text OpenDocument file + # (.odt) + index = pd.Index(["Row 1", "Row 2", "Row 3"], name="Header") + expected = pd.DataFrame( + [[1, np.nan, 7], [2, np.nan, 8], [3, np.nan, 9]], + index=index, + columns=["Column 1", "Unnamed: 2", "Column 3"], + ) + + result = pd.read_excel("writertable.odt", sheet_name="Table1", index_col=0) + + tm.assert_frame_equal(result, expected) + + +def test_read_newlines_between_xml_elements_table(): + # GH#45598 + expected = pd.DataFrame( + [[1.0, 4.0, 7], [np.nan, np.nan, 8], [3.0, 6.0, 9]], + columns=["Column 1", "Column 2", "Column 3"], + ) + + result = pd.read_excel("test_newlines.ods") + + tm.assert_frame_equal(result, expected) + + +def test_read_unempty_cells(): + expected = pd.DataFrame( + [1, np.nan, 3, np.nan, 5], + columns=["Column 1"], + ) + + result = pd.read_excel("test_unempty_cells.ods") + + tm.assert_frame_equal(result, expected) + + +def test_read_cell_annotation(): + expected = pd.DataFrame( + ["test", np.nan, "test 3"], + columns=["Column 1"], + ) + + result = pd.read_excel("test_cell_annotation.ods") + + tm.assert_frame_equal(result, expected) + + +def test_read_covered_table_cell_value(tmp_excel): + # GH#66579 + doc = OpenDocumentSpreadsheet() + sheet = Table(name="Sheet1") + doc.spreadsheet.addElement(sheet) + + row0 = TableRow() + sheet.addElement(row0) + row0.addElement(TableCell(valuetype="float", value="1")) + row0.addElement(TableCell(valuetype="float", value="100")) + + row1 = TableRow() + sheet.addElement(row1) + row1.addElement(CoveredTableCell(valuetype="float", value="42")) + row1.addElement(TableCell(valuetype="float", value="200")) + + row2 = TableRow() + sheet.addElement(row2) + row2.addElement(CoveredTableCell(valuetype="float")) + row2.addElement(TableCell(valuetype="float", value="300")) + + row3 = TableRow() + sheet.addElement(row3) + row3.addElement(CoveredTableCell(valuetype="void")) + row3.addElement(TableCell(valuetype="float", value="400")) + + row4 = TableRow() + sheet.addElement(row4) + row4.addElement(CoveredTableCell(valuetype="boolean", booleanvalue="true")) + row4.addElement(TableCell(valuetype="float", value="500")) + + doc.save(tmp_excel) + + result = pd.read_excel(tmp_excel, header=None) + + expected = pd.DataFrame( + [ + [1, 100], + [42, 200], + [np.nan, 300], + [np.nan, 400], + [np.nan, 500], + ] + ) + + tm.assert_frame_equal(result, expected) + + +def test_read_cell_line_breaks(tmp_excel): + # GH#55728, GH#53924 a line break inside a cell is stored either as a + # element or as a further paragraph + from odf.opendocument import OpenDocumentSpreadsheet + from odf.table import ( + Table, + TableCell, + TableRow, + ) + from odf.text import ( + LineBreak, + P, + ) + + def _row(cell: TableCell) -> TableRow: + row = TableRow() + row.addElement(cell) + return row + + doc = OpenDocumentSpreadsheet() + table = Table(name="Sheet1") + + header = TableCell(valuetype="string") + header.addElement(P(text="Column 1")) + table.addElement(_row(header)) + + line_break = TableCell(valuetype="string") + paragraph = P() + paragraph.addText("break1") + paragraph.addElement(LineBreak()) + paragraph.addText("break2") + line_break.addElement(paragraph) + table.addElement(_row(line_break)) + + paragraphs = TableCell(valuetype="string") + paragraphs.addElement(P(text="para1")) + paragraphs.addElement(P(text="para2")) + table.addElement(_row(paragraphs)) + + doc.spreadsheet.addElement(table) + doc.save(tmp_excel) + + result = pd.read_excel(tmp_excel) + + expected = pd.DataFrame({"Column 1": ["break1\nbreak2", "para1\npara2"]}) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_odswriter.py b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_odswriter.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3a5d94672c70ead6e52f4bd90fa0da68017fe7 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_odswriter.py @@ -0,0 +1,148 @@ +from datetime import ( + date, + datetime, +) +import re +import uuid + +import pytest + +import pandas as pd +import pandas._testing as tm + +from pandas.io.excel import ExcelWriter + +odf = pytest.importorskip("odf") + + +@pytest.fixture +def ext(): + return ".ods" + + +@pytest.fixture +def tmp_excel(ext, tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}{ext}" + tmp.touch() + return str(tmp) + + +def test_write_append_mode_raises(tmp_excel): + msg = "Append mode is not supported with odf!" + + with pytest.raises(ValueError, match=msg): + ExcelWriter(tmp_excel, engine="odf", mode="a") + + +@pytest.mark.parametrize("engine_kwargs", [None, {"kwarg": 1}]) +def test_engine_kwargs(tmp_excel, engine_kwargs): + # GH 42286 + # GH 43445 + # test for error: OpenDocumentSpreadsheet does not accept any arguments + if engine_kwargs is not None: + error = re.escape( + "OpenDocumentSpreadsheet() got an unexpected keyword argument 'kwarg'" + ) + with pytest.raises( + TypeError, + match=error, + ): + ExcelWriter(tmp_excel, engine="odf", engine_kwargs=engine_kwargs) + else: + with ExcelWriter(tmp_excel, engine="odf", engine_kwargs=engine_kwargs) as _: + pass + + +def test_book_and_sheets_consistent(tmp_excel): + # GH#45687 - Ensure sheets is updated if user modifies book + with ExcelWriter(tmp_excel) as writer: + assert writer.sheets == {} + table = odf.table.Table(name="test_name") + writer.book.spreadsheet.addElement(table) + assert writer.sheets == {"test_name": table} + + +@pytest.mark.parametrize( + ["value", "cell_value_type", "cell_value_attribute", "cell_value"], + argvalues=[ + (True, "boolean", "boolean-value", "true"), + ("test string", "string", "string-value", "test string"), + (1, "float", "value", "1"), + (1.5, "float", "value", "1.5"), + ( + datetime(2010, 10, 10, 10, 10, 10), + "date", + "date-value", + "2010-10-10T10:10:10", + ), + (date(2010, 10, 10), "date", "date-value", "2010-10-10"), + ], +) +def test_cell_value_type( + tmp_excel, value, cell_value_type, cell_value_attribute, cell_value +): + # GH#54994 ODS: cell attributes should follow specification + # http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html#refTable13 + from odf.namespaces import OFFICENS + from odf.table import ( + TableCell, + TableRow, + ) + + table_cell_name = TableCell().qname + + pd.DataFrame([[value]]).to_excel(tmp_excel, header=False, index=False) + + with pd.ExcelFile(tmp_excel) as wb: + sheet = wb._reader.get_sheet_by_index(0) + sheet_rows = sheet.getElementsByType(TableRow) + sheet_cells = [ + x + for x in sheet_rows[0].childNodes + if hasattr(x, "qname") and x.qname == table_cell_name + ] + + cell = sheet_cells[0] + assert cell.attributes.get((OFFICENS, "value-type")) == cell_value_type + assert cell.attributes.get((OFFICENS, cell_value_attribute)) == cell_value + + +def test_cell_value_with_line_break(tmp_excel): + # GH#55728 a newline is written as a element, since a + # newline in the paragraph text itself is collapsed by ODF consumers + from odf.table import ( + TableCell, + TableRow, + ) + from odf.text import ( + LineBreak, + P, + ) + + table_cell_name = TableCell().qname + + pd.DataFrame([["line1\nline2"]]).to_excel(tmp_excel, header=False, index=False) + + with pd.ExcelFile(tmp_excel) as wb: + sheet = wb._reader.get_sheet_by_index(0) + sheet_rows = sheet.getElementsByType(TableRow) + sheet_cells = [ + x + for x in sheet_rows[0].childNodes + if hasattr(x, "qname") and x.qname == table_cell_name + ] + + paragraphs = sheet_cells[0].getElementsByType(P) + assert len(paragraphs) == 1 + assert len(paragraphs[0].getElementsByType(LineBreak)) == 1 + assert "\n" not in str(paragraphs[0]) + + +def test_line_break_round_trip(tmp_excel): + # GH#55728 writing and reading back preserves the line breaks + expected = pd.DataFrame({"a": ["line1\nline2", "no break", "a\nb\nc"]}) + + expected.to_excel(tmp_excel, index=False) + result = pd.read_excel(tmp_excel) + + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_openpyxl.py b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_openpyxl.py new file mode 100644 index 0000000000000000000000000000000000000000..ab79544838d337662e533006049d22585db4b1bd --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_openpyxl.py @@ -0,0 +1,584 @@ +import contextlib +from pathlib import Path +import re +import uuid + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + +from pandas.io.excel import ( + ExcelWriter, + _base as _excel_base, + _OpenpyxlWriter, +) +from pandas.io.excel._openpyxl import OpenpyxlReader + +openpyxl = pytest.importorskip("openpyxl") + +# These tests read xlsx back with the default engine; the pending +# calamine-default change (GH#56542) is not what they exercise. +pytestmark = pytest.mark.filterwarnings( + "ignore:The default engine for reading:pandas.errors.Pandas4Warning" +) + + +@pytest.fixture +def ext(): + return ".xlsx" + + +@pytest.fixture +def tmp_excel(ext, tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}{ext}" + tmp.touch() + return str(tmp) + + +def test_to_excel_styleconverter(): + from openpyxl import styles + + hstyle = { + "font": {"color": "00FF0000", "bold": True}, + "borders": {"top": "thin", "right": "thin", "bottom": "thin", "left": "thin"}, + "alignment": {"horizontal": "center", "vertical": "top"}, + "fill": {"patternType": "solid", "fgColor": {"rgb": "006666FF", "tint": 0.3}}, + "number_format": {"format_code": "0.00"}, + "protection": {"locked": True, "hidden": False}, + } + + font_color = styles.Color("00FF0000") + font = styles.Font(bold=True, color=font_color) + side = styles.Side(style=styles.borders.BORDER_THIN) + border = styles.Border(top=side, right=side, bottom=side, left=side) + alignment = styles.Alignment(horizontal="center", vertical="top") + fill_color = styles.Color(rgb="006666FF", tint=0.3) + fill = styles.PatternFill(patternType="solid", fgColor=fill_color) + + number_format = "0.00" + + protection = styles.Protection(locked=True, hidden=False) + + kw = _OpenpyxlWriter._convert_to_style_kwargs(hstyle) + assert kw["font"] == font + assert kw["border"] == border + assert kw["alignment"] == alignment + assert kw["fill"] == fill + assert kw["number_format"] == number_format + assert kw["protection"] == protection + + +def test_write_cells_merge_styled(tmp_excel): + from pandas.io.formats.excel import ExcelCell + + sheet_name = "merge_styled" + + sty_b1 = {"font": {"color": "00FF0000"}} + sty_a2 = {"font": {"color": "0000FF00"}} + + initial_cells = [ + ExcelCell(col=1, row=0, val=42, style=sty_b1), + ExcelCell(col=0, row=1, val=99, style=sty_a2), + ] + + sty_merged = {"font": {"color": "000000FF", "bold": True}} + sty_kwargs = _OpenpyxlWriter._convert_to_style_kwargs(sty_merged) + openpyxl_sty_merged = sty_kwargs["font"] + merge_cells = [ + ExcelCell( + col=0, row=0, val="pandas", mergestart=1, mergeend=1, style=sty_merged + ) + ] + + with _OpenpyxlWriter(tmp_excel) as writer: + writer._write_cells(initial_cells, sheet_name=sheet_name) + writer._write_cells(merge_cells, sheet_name=sheet_name) + + wks = writer.sheets[sheet_name] + xcell_b1 = wks["B1"] + xcell_a2 = wks["A2"] + assert xcell_b1.font == openpyxl_sty_merged + assert xcell_a2.font == openpyxl_sty_merged + + +@pytest.mark.parametrize("iso_dates", [True, False]) +def test_engine_kwargs_write(tmp_excel, iso_dates): + # GH 42286 GH 43445 + engine_kwargs = {"iso_dates": iso_dates} + with ExcelWriter( + tmp_excel, engine="openpyxl", engine_kwargs=engine_kwargs + ) as writer: + assert writer.book.iso_dates == iso_dates + # ExcelWriter won't allow us to close without writing something + pd.DataFrame().to_excel(writer) + + +def test_engine_kwargs_append_invalid(tmp_excel): + # GH 43445 + # test whether an invalid engine kwargs actually raises + pd.DataFrame(["hello", "world"]).to_excel(tmp_excel) + with pytest.raises( + TypeError, + match=re.escape( + "load_workbook() got an unexpected keyword argument 'apple_banana'" + ), + ): + with ExcelWriter( + tmp_excel, + engine="openpyxl", + mode="a", + engine_kwargs={"apple_banana": "fruit"}, + ) as writer: + # ExcelWriter needs us to write something to close properly + pd.DataFrame(["good"]).to_excel(writer, sheet_name="Sheet2") + + +@pytest.mark.parametrize("data_only, expected", [(True, 0), (False, "=1+1")]) +def test_engine_kwargs_append_data_only(tmp_excel, data_only, expected): + # GH 43445 + # tests whether the data_only engine_kwarg actually works well for + # openpyxl's load_workbook + pd.DataFrame(["=1+1"]).to_excel(tmp_excel) + with ExcelWriter( + tmp_excel, engine="openpyxl", mode="a", engine_kwargs={"data_only": data_only} + ) as writer: + assert writer.sheets["Sheet1"]["B2"].value == expected + # ExcelWriter needs us to writer something to close properly? + pd.DataFrame().to_excel(writer, sheet_name="Sheet2") + + # ensure that data_only also works for reading + # and that formulas/values roundtrip + assert ( + pd.read_excel( + tmp_excel, + sheet_name="Sheet1", + engine="openpyxl", + engine_kwargs={"data_only": data_only}, + ).iloc[0, 1] + == expected + ) + + +@pytest.mark.parametrize("kwarg_name", ["read_only", "data_only"]) +@pytest.mark.parametrize("kwarg_value", [True, False]) +def test_engine_kwargs_append_reader(datapath, ext, kwarg_name, kwarg_value): + # GH 55027 + # test that `read_only` and `data_only` can be passed to + # `openpyxl.reader.excel.load_workbook` via `engine_kwargs` + filename = datapath("io", "data", "excel", "test1" + ext) + with contextlib.closing( + OpenpyxlReader(filename, engine_kwargs={kwarg_name: kwarg_value}) + ) as reader: + assert getattr(reader.book, kwarg_name) == kwarg_value + + +@pytest.mark.parametrize( + "mode,expected", [("w", ["baz"]), ("a", ["foo", "bar", "baz"])] +) +def test_write_append_mode(tmp_excel, mode, expected): + df = pd.DataFrame([1], columns=["baz"]) + + wb = openpyxl.Workbook() + wb.worksheets[0].title = "foo" + wb.worksheets[0]["A1"].value = "foo" + wb.create_sheet("bar") + wb.worksheets[1]["A1"].value = "bar" + wb.save(tmp_excel) + + with ExcelWriter(tmp_excel, engine="openpyxl", mode=mode) as writer: + df.to_excel(writer, sheet_name="baz", index=False) + + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb2: + result = [sheet.title for sheet in wb2.worksheets] + assert result == expected + + for index, cell_value in enumerate(expected): + assert wb2.worksheets[index]["A1"].value == cell_value + + +@pytest.mark.parametrize( + "if_sheet_exists,num_sheets,expected", + [ + ("new", 2, ["apple", "banana"]), + ("replace", 1, ["pear"]), + ("overlay", 1, ["pear", "banana"]), + ], +) +def test_if_sheet_exists_append_modes(tmp_excel, if_sheet_exists, num_sheets, expected): + # GH 40230 + df1 = pd.DataFrame({"fruit": ["apple", "banana"]}) + df2 = pd.DataFrame({"fruit": ["pear"]}) + + df1.to_excel(tmp_excel, engine="openpyxl", sheet_name="foo", index=False) + with ExcelWriter( + tmp_excel, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists + ) as writer: + df2.to_excel(writer, sheet_name="foo", index=False) + + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + assert len(wb.sheetnames) == num_sheets + assert wb.sheetnames[0] == "foo" + result = pd.read_excel(wb, "foo", engine="openpyxl") + assert list(result["fruit"]) == expected + if len(wb.sheetnames) == 2: + result = pd.read_excel(wb, wb.sheetnames[1], engine="openpyxl") + tm.assert_frame_equal(result, df2) + + +@pytest.mark.parametrize( + "startrow, startcol, greeting, goodbye", + [ + (0, 0, ["poop", "world"], ["goodbye", "people"]), + (0, 1, ["hello", "world"], ["poop", "people"]), + (1, 0, ["hello", "poop"], ["goodbye", "people"]), + (1, 1, ["hello", "world"], ["goodbye", "poop"]), + ], +) +def test_append_overlay_startrow_startcol( + tmp_excel, startrow, startcol, greeting, goodbye +): + df1 = pd.DataFrame( + {"greeting": ["hello", "world"], "goodbye": ["goodbye", "people"]} + ) + df2 = pd.DataFrame(["poop"]) + + df1.to_excel(tmp_excel, engine="openpyxl", sheet_name="poo", index=False) + with ExcelWriter( + tmp_excel, engine="openpyxl", mode="a", if_sheet_exists="overlay" + ) as writer: + # use startrow+1 because we don't have a header + df2.to_excel( + writer, + index=False, + header=False, + startrow=startrow + 1, + startcol=startcol, + sheet_name="poo", + ) + + result = pd.read_excel(tmp_excel, sheet_name="poo", engine="openpyxl") + expected = pd.DataFrame({"greeting": greeting, "goodbye": goodbye}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "if_sheet_exists,msg", + [ + ( + "invalid", + "'invalid' is not valid for if_sheet_exists. Valid options " + "are 'error', 'new', 'replace' and 'overlay'.", + ), + ( + "error", + "Sheet 'foo' already exists and if_sheet_exists is set to 'error'.", + ), + ( + None, + "Sheet 'foo' already exists and if_sheet_exists is set to 'error'.", + ), + ], +) +def test_if_sheet_exists_raises(tmp_excel, if_sheet_exists, msg): + # GH 40230 + df = pd.DataFrame({"fruit": ["pear"]}) + df.to_excel(tmp_excel, sheet_name="foo", engine="openpyxl") + with pytest.raises(ValueError, match=re.escape(msg)): + with ExcelWriter( + tmp_excel, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists + ) as writer: + df.to_excel(writer, sheet_name="foo") + + +def test_to_excel_with_openpyxl_engine(tmp_excel): + # GH 29854 + df1 = pd.DataFrame({"A": np.linspace(1, 10, 10)}) + df2 = pd.DataFrame({"B": np.linspace(1, 20, 10)}) + df = pd.concat([df1, df2], axis=1) + styled = df.style.map( + lambda val: f"color: {'red' if val < 0 else 'black'}" + ).highlight_max() + + styled.to_excel(tmp_excel, engine="openpyxl") + + +@pytest.mark.parametrize("read_only", [True, False]) +def test_read_workbook(datapath, ext, read_only): + # GH 39528 + filename = datapath("io", "data", "excel", "test1" + ext) + with contextlib.closing( + openpyxl.load_workbook(filename, read_only=read_only) + ) as wb: + result = pd.read_excel(wb, engine="openpyxl") + expected = pd.read_excel(filename) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "header, expected_data", + [ + ( + 0, + { + "Title": [np.nan, "A", 1, 2, 3], + "Unnamed: 1": [np.nan, "B", 4, 5, 6], + "Unnamed: 2": [np.nan, "C", 7, 8, 9], + }, + ), + (2, {"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}), + ], +) +@pytest.mark.parametrize( + "filename", ["dimension_missing", "dimension_small", "dimension_large"] +) +# When read_only is None, use read_excel instead of a workbook +@pytest.mark.parametrize("read_only", [True, False, None]) +def test_read_with_bad_dimension( + datapath, ext, header, expected_data, filename, read_only +): + # GH 38956, 39001 - no/incorrect dimension information + path = datapath("io", "data", "excel", f"{filename}{ext}") + if read_only is None: + result = pd.read_excel(path, header=header) + else: + with contextlib.closing( + openpyxl.load_workbook(path, read_only=read_only) + ) as wb: + result = pd.read_excel(wb, engine="openpyxl", header=header) + expected = pd.DataFrame(expected_data) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "filename", ["dimension_missing", "dimension_small", "dimension_large"] +) +def test_read_with_bad_dimension_skiprows_callable_all( + datapath, ext, filename, monkeypatch +): + # GH 64027 + path = datapath("io", "data", "excel", f"{filename}{ext}") + with monkeypatch.context() as m: + m.setattr(_excel_base, "EXCEL_ROWS_MAX", 10) + result = pd.read_excel(path, skiprows=lambda _: True, nrows=1) + expected = pd.DataFrame() + tm.assert_frame_equal(result, expected) + + +def test_append_mode_file(tmp_excel): + # GH 39576 + df = pd.DataFrame() + + df.to_excel(tmp_excel, engine="openpyxl") + + with ExcelWriter( + tmp_excel, mode="a", engine="openpyxl", if_sheet_exists="new" + ) as writer: + df.to_excel(writer) + + # make sure that zip files are not concatenated by making sure that + # "docProps/app.xml" only occurs twice in the file + data = Path(tmp_excel).read_bytes() + first = data.find(b"docProps/app.xml") + second = data.find(b"docProps/app.xml", first + 1) + third = data.find(b"docProps/app.xml", second + 1) + assert second != -1 and third == -1 + + +# When read_only is None, use read_excel instead of a workbook +@pytest.mark.parametrize("read_only", [True, False, None]) +def test_read_with_empty_trailing_rows(datapath, ext, read_only): + # GH 39181 + path = datapath("io", "data", "excel", f"empty_trailing_rows{ext}") + if read_only is None: + result = pd.read_excel(path) + else: + with contextlib.closing( + openpyxl.load_workbook(path, read_only=read_only) + ) as wb: + result = pd.read_excel(wb, engine="openpyxl") + expected = pd.DataFrame( + { + "Title": [np.nan, "A", 1, 2, 3], + "Unnamed: 1": [np.nan, "B", 4, 5, 6], + "Unnamed: 2": [np.nan, "C", 7, 8, 9], + } + ) + tm.assert_frame_equal(result, expected) + + +# When read_only is None, use read_excel instead of a workbook +@pytest.mark.parametrize("read_only", [True, False, None]) +def test_read_empty_with_blank_row(datapath, ext, read_only): + # GH 39547 - empty excel file with a row that has no data + path = datapath("io", "data", "excel", f"empty_with_blank_row{ext}") + if read_only is None: + result = pd.read_excel(path) + else: + with contextlib.closing( + openpyxl.load_workbook(path, read_only=read_only) + ) as wb: + result = pd.read_excel(wb, engine="openpyxl") + expected = pd.DataFrame() + tm.assert_frame_equal(result, expected) + + +def test_book_and_sheets_consistent(tmp_excel): + # GH#45687 - Ensure sheets is updated if user modifies book + with ExcelWriter(tmp_excel, engine="openpyxl") as writer: + assert writer.sheets == {} + sheet = writer.book.create_sheet("test_name", 0) + assert writer.sheets == {"test_name": sheet} + + +def test_ints_spelled_with_decimals(datapath, ext): + # GH 46988 - openpyxl returns this sheet with floats + path = datapath("io", "data", "excel", f"ints_spelled_with_decimals{ext}") + result = pd.read_excel(path) + expected = pd.DataFrame(range(2, 12), columns=[1]) + tm.assert_frame_equal(result, expected) + + +def test_read_multiindex_header_no_index_names(datapath, ext): + # GH#47487 + path = datapath("io", "data", "excel", f"multiindex_no_index_names{ext}") + result = pd.read_excel(path, index_col=[0, 1, 2], header=[0, 1, 2]) + expected = pd.DataFrame( + [[np.nan, "x", "x", "x"], ["x", np.nan, np.nan, np.nan]], + columns=pd.MultiIndex.from_tuples( + [("X", "Y", "A1"), ("X", "Y", "A2"), ("XX", "YY", "B1"), ("XX", "YY", "B2")] + ), + index=pd.MultiIndex.from_tuples([("A", "AA", "AAA"), ("A", "BB", "BBB")]), + ) + tm.assert_frame_equal(result, expected) + + +def test_read_excel_book_dimensions_preserved(tmp_excel): + # GH#63010 - reading should not permanently reset the dimensions of the + # worksheet handle available through ExcelFile.book + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + df.to_excel(tmp_excel, index=False) + + with pd.ExcelFile(tmp_excel, engine="openpyxl") as excel_file: + sheet = excel_file.book["Sheet1"] + assert (sheet.max_row, sheet.max_column) == (3, 2) + + result = pd.read_excel(excel_file, sheet_name="Sheet1") + + assert (sheet.max_row, sheet.max_column) == (3, 2) + + tm.assert_frame_equal(result, df) + + +class TestWriteOnly: + """Tests for write_only mode (GH#41681).""" + + def test_write_only_not_default(self, tmp_excel): + with ExcelWriter(tmp_excel, engine="openpyxl") as writer: + assert writer.book.write_only is False + pd.DataFrame().to_excel(writer) + + def test_write_only_opt_in(self, tmp_excel): + with ExcelWriter( + tmp_excel, engine="openpyxl", engine_kwargs={"write_only": True} + ) as writer: + assert writer.book.write_only is True + pd.DataFrame().to_excel(writer) + + def test_write_only_not_set_in_append_mode(self, tmp_excel): + pd.DataFrame().to_excel(tmp_excel, engine="openpyxl") + with ExcelWriter(tmp_excel, engine="openpyxl", mode="a") as writer: + assert writer.book.write_only is False + pd.DataFrame().to_excel(writer, sheet_name="Sheet2") + + def test_write_only_roundtrip(self, tmp_excel): + # Verify basic data integrity through write-only path + df = pd.DataFrame({"col1": [1, 2, 3], "col2": ["a", "b", "c"]}) + df.to_excel( + tmp_excel, + engine="openpyxl", + engine_kwargs={"write_only": True}, + index=False, + ) + result = pd.read_excel(tmp_excel, engine="openpyxl") + tm.assert_frame_equal(result, df) + + def test_write_only_multiple_sheets(self, tmp_excel): + df1 = pd.DataFrame({"a": [1, 2]}) + df2 = pd.DataFrame({"b": [3, 4]}) + with ExcelWriter( + tmp_excel, engine="openpyxl", engine_kwargs={"write_only": True} + ) as writer: + df1.to_excel(writer, sheet_name="one", index=False) + df2.to_excel(writer, sheet_name="two", index=False) + result1 = pd.read_excel(tmp_excel, sheet_name="one", engine="openpyxl") + result2 = pd.read_excel(tmp_excel, sheet_name="two", engine="openpyxl") + tm.assert_frame_equal(result1, df1) + tm.assert_frame_equal(result2, df2) + + def test_write_only_freeze_panes(self, tmp_excel): + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) + df.to_excel( + tmp_excel, + engine="openpyxl", + engine_kwargs={"write_only": True}, + freeze_panes=(1, 1), + ) + wb = openpyxl.load_workbook(tmp_excel) + ws = wb.active + assert ws.freeze_panes == "B2" + + def test_write_only_merge_cells(self, tmp_excel): + # MultiIndex columns produce merged header cells + df = pd.DataFrame( + [[1, 2]], + columns=pd.MultiIndex.from_tuples([("a", "x"), ("a", "y")]), + ) + df.to_excel( + tmp_excel, + engine="openpyxl", + engine_kwargs={"write_only": True}, + ) + wb = openpyxl.load_workbook(tmp_excel) + ws = wb.active + assert len(ws.merged_cells.ranges) > 0 + + def test_write_only_styling(self, tmp_excel): + from pandas.io.formats.excel import ExcelCell + + styled_cells = [ + ExcelCell( + row=0, + col=0, + val="styled", + style={"font": {"bold": True, "color": "00FF0000"}}, + ), + ] + with _OpenpyxlWriter(tmp_excel, engine_kwargs={"write_only": True}) as writer: + writer._write_cells(styled_cells, sheet_name="Sheet1") + + wb = openpyxl.load_workbook(tmp_excel) + ws = wb["Sheet1"] + cell = ws["A1"] + assert cell.value == "styled" + assert cell.font.bold is True + assert cell.font.color.rgb == "00FF0000" + + def test_write_only_startrow_startcol(self, tmp_excel): + df = pd.DataFrame({"a": [1]}) + df.to_excel( + tmp_excel, + engine="openpyxl", + engine_kwargs={"write_only": True}, + startrow=3, + startcol=2, + index=False, + ) + wb = openpyxl.load_workbook(tmp_excel) + ws = wb.active + # Header at row 4 (startrow=3, 1-indexed), col C (startcol=2, 1-indexed) + assert ws.cell(row=4, column=3).value == "a" + assert ws.cell(row=5, column=3).value == 1 + # Cells before start should be empty + assert ws.cell(row=1, column=1).value is None diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_readers.py b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_readers.py new file mode 100644 index 0000000000000000000000000000000000000000..986748bff5917016d3a30eb6bf81dc6f61cd4cf0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_readers.py @@ -0,0 +1,1922 @@ +from __future__ import annotations + +from datetime import ( + datetime, + time, +) +from functools import partial +from io import BytesIO +import os +from pathlib import Path +import platform +import re +from urllib.error import URLError +import uuid +from zipfile import BadZipFile + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + +import pandas.io.excel._base as _excel_base + +read_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"] +engine_params = [ + # Add any engines to test here + # When defusedxml is installed it triggers deprecation warnings for + # xlrd and openpyxl, so catch those here + pytest.param( + "xlrd", + marks=[ + td.skip_if_no("xlrd"), + pytest.mark.filterwarnings( + "ignore:The xlrd engine is deprecated:pandas.errors.Pandas4Warning" + ), + ], + ), + pytest.param( + "openpyxl", + marks=[ + td.skip_if_no("openpyxl"), + ], + ), + pytest.param( + None, + marks=[ + td.skip_if_no("xlrd"), + pytest.mark.filterwarnings( + "ignore:The xlrd engine is deprecated:pandas.errors.Pandas4Warning" + ), + pytest.mark.filterwarnings( + "ignore:The default engine for reading:pandas.errors.Pandas4Warning" + ), + ], + ), + pytest.param( + "pyxlsb", + marks=[ + td.skip_if_no("pyxlsb"), + pytest.mark.filterwarnings( + "ignore:The pyxlsb engine is deprecated:pandas.errors.Pandas4Warning" + ), + ], + ), + pytest.param("odf", marks=td.skip_if_no("odf")), + pytest.param("calamine", marks=td.skip_if_no("python_calamine")), +] + + +def _is_valid_engine_ext_pair(engine, read_ext: str) -> bool: + """ + Filter out invalid (engine, ext) pairs instead of skipping, as that + produces 500+ pytest.skips. + """ + engine = engine.values[0] + if engine == "openpyxl" and read_ext == ".xls": + return False + if engine == "odf" and read_ext != ".ods": + return False + if read_ext == ".ods" and engine not in {"odf", "calamine"}: + return False + if engine == "pyxlsb" and read_ext != ".xlsb": + return False + if read_ext == ".xlsb" and engine not in {"pyxlsb", "calamine"}: + return False + if engine == "xlrd" and read_ext != ".xls": + return False + return True + + +def _transfer_marks(engine, read_ext): + """ + engine gives us a pytest.param object with some marks, read_ext is just + a string. We need to generate a new pytest.param inheriting the marks. + """ + values = (*engine.values, read_ext) + new_param = pytest.param(values, marks=engine.marks) + return new_param + + +@pytest.fixture( + params=[ + _transfer_marks(eng, ext) + for eng in engine_params + for ext in read_ext_params + if _is_valid_engine_ext_pair(eng, ext) + ], + ids=str, +) +def engine_and_read_ext(request): + """ + Fixture for Excel reader engine and read_ext, only including valid pairs. + """ + return request.param + + +@pytest.fixture +def engine(engine_and_read_ext): + engine, read_ext = engine_and_read_ext + return engine + + +@pytest.fixture +def read_ext(engine_and_read_ext): + engine, read_ext = engine_and_read_ext + return read_ext + + +@pytest.fixture +def tmp_excel(read_ext, tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}{read_ext}" + tmp.touch() + return str(tmp) + + +@pytest.fixture +def df_ref(datapath): + """ + Obtain the reference data from read_csv with the Python engine. + """ + filepath = datapath("io", "data", "csv", "test1.csv") + df_ref = pd.read_csv(filepath, index_col=0, parse_dates=True, engine="python") + return df_ref + + +def get_exp_unit(read_ext: str, engine: str | None) -> str: + return "us" + + +def adjust_expected(expected: pd.DataFrame, read_ext: str, engine: str | None) -> None: + expected.index.name = None + unit = get_exp_unit(read_ext, engine) + # error: "Index" has no attribute "as_unit" + expected.index = expected.index.as_unit(unit) # type: ignore[attr-defined] + + +def xfail_datetimes_with_pyxlsb(engine, request): + if engine == "pyxlsb": + request.applymarker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) + + +@td.skip_if_no("openpyxl") +@td.skip_if_no("python_calamine") +@pytest.mark.parametrize("ext", ["xlsx", "xlsm"]) +def test_read_excel_default_engine_deprecated(datapath, ext): + # GH#56542 - the default xlsx/xlsm reader engine will change to calamine. + # xlsm files are format-sniffed as xlsx, so both get the 'xlsx' warning. + path = datapath("io", "data", "excel", f"test1.{ext}") + + msg = "The default engine for reading 'xlsx' files will change" + with tm.assert_produces_warning(Pandas4Warning, match=msg): + pd.read_excel(path) + + # passing an explicit engine silences the warning + for engine in ("openpyxl", "calamine"): + with tm.assert_produces_warning(None): + pd.read_excel(path, engine=engine) + + # setting the io.excel.xlsx.reader option silences the warning + with pd.option_context("io.excel.xlsx.reader", "openpyxl"): + with tm.assert_produces_warning(None): + pd.read_excel(path) + + +class TestReaders: + @pytest.mark.parametrize("col", [[True, None, False], [True], [True, False]]) + def test_read_excel_type_check(self, col, tmp_excel, read_ext): + # GH 58159 + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") + df = pd.DataFrame({"bool_column": col}, dtype="boolean") + df.to_excel(tmp_excel, index=False) + df2 = pd.read_excel(tmp_excel, dtype={"bool_column": "boolean"}) + tm.assert_frame_equal(df, df2) + + def test_read_excel_int_bool_mix_type_check(self, tmp_excel, read_ext): + # GH 60088 + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") + + df1 = pd.DataFrame( + { + "a": [True, True], + "b": [1, True], + "c": [True, 1], + "d": [False, 0], + "e": [0, False], + "f": [False, False], + }, + dtype=object, + ) + df1.to_excel(tmp_excel, index=False) + + df2 = pd.read_excel(tmp_excel, dtype=object) + + tm.assert_frame_equal(df1, df2) + + for idx, row in df2.iterrows(): + for col in df2.columns: + val = row[col] + exp_val = df1.iloc[idx][col] + # Check if values match + assert val == exp_val, ( + f"Mismatch at Row {idx} Column {col}: {val} != {exp_val}" + ) + # Check if types match + assert type(val) == type(exp_val), ( + f"Type mismatch at Row {idx} Column {col}: " + f"{type(val)} != {type(exp_val)}" + ) + + def test_pass_none_type(self, datapath): + # GH 58159 + f_path = datapath("io", "data", "excel", "test_none_type.xlsx") + + with pd.ExcelFile(f_path, engine="openpyxl") as excel: + parsed = pd.read_excel( + excel, + sheet_name="Sheet1", + keep_default_na=True, + na_values=["nan", "None", "abcd"], + dtype="boolean", + engine="openpyxl", + ) + expected = pd.DataFrame( + {"Test": [True, None, False, None, False, None, True]}, + dtype="boolean", + ) + + tm.assert_frame_equal(parsed, expected) + + @pytest.fixture(autouse=True) + def cd_and_set_engine(self, engine, datapath, monkeypatch): + """ + Change directory and set engine for read_excel calls. + """ + func = partial(pd.read_excel, engine=engine) + monkeypatch.chdir(datapath("io", "data", "excel")) + monkeypatch.setattr(pd, "read_excel", func) + + def test_engine_used(self, read_ext, engine): + # GH 38884 + expected_defaults = { + "xlsx": "openpyxl", + "xlsm": "openpyxl", + "xlsb": "pyxlsb", + "xls": "xlrd", + "ods": "odf", + } + + with open("test1" + read_ext, "rb") as f: + with pd.ExcelFile(f, engine=engine) as excel_file: + result = excel_file.engine + + if engine is not None: + expected = engine + else: + expected = expected_defaults[read_ext[1:]] + assert result == expected + + def test_engine_kwargs(self, read_ext, engine): + # GH#52214 + expected_defaults = { + "xlsx": {"foo": "abcd"}, + "xlsm": {"foo": 123}, + "xlsb": {"foo": "True"}, + "xls": {"foo": True}, + "ods": {"foo": "abcd"}, + } + + if engine in {"xlrd", "pyxlsb"}: + msg = re.escape(r"open_workbook() got an unexpected keyword argument 'foo'") + elif engine == "odf": + msg = re.escape(r"load() got an unexpected keyword argument 'foo'") + else: + msg = re.escape(r"load_workbook() got an unexpected keyword argument 'foo'") + + if engine is not None: + with pytest.raises(TypeError, match=msg): + pd.read_excel( + "test1" + read_ext, + sheet_name="Sheet1", + index_col=0, + engine_kwargs=expected_defaults[read_ext[1:]], + ) + + def test_usecols_int(self, read_ext): + # usecols as int + msg = "Passing an integer for `usecols`" + with pytest.raises(ValueError, match=msg): + pd.read_excel( + "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=3 + ) + + # usecols as int + with pytest.raises(ValueError, match=msg): + pd.read_excel( + "test1" + read_ext, + sheet_name="Sheet2", + skiprows=[1], + index_col=0, + usecols=3, + ) + + def test_usecols_list(self, request, engine, read_ext, df_ref): + xfail_datetimes_with_pyxlsb(engine, request) + + expected = df_ref[["B", "C"]] + adjust_expected(expected, read_ext, engine) + + df1 = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=[0, 2, 3] + ) + df2 = pd.read_excel( + "test1" + read_ext, + sheet_name="Sheet2", + skiprows=[1], + index_col=0, + usecols=[0, 2, 3], + ) + + # TODO add index to xls file) + tm.assert_frame_equal(df1, expected) + tm.assert_frame_equal(df2, expected) + + def test_usecols_str(self, request, engine, read_ext, df_ref): + xfail_datetimes_with_pyxlsb(engine, request) + + expected = df_ref[["A", "B", "C"]] + adjust_expected(expected, read_ext, engine) + + df2 = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A:D" + ) + df3 = pd.read_excel( + "test1" + read_ext, + sheet_name="Sheet2", + skiprows=[1], + index_col=0, + usecols="A:D", + ) + + # TODO add index to xls, read xls ignores index name ? + tm.assert_frame_equal(df2, expected) + tm.assert_frame_equal(df3, expected) + + expected = df_ref[["B", "C"]] + adjust_expected(expected, read_ext, engine) + + df2 = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,C,D" + ) + df3 = pd.read_excel( + "test1" + read_ext, + sheet_name="Sheet2", + skiprows=[1], + index_col=0, + usecols="A,C,D", + ) + # TODO add index to xls file + tm.assert_frame_equal(df2, expected) + tm.assert_frame_equal(df3, expected) + + df2 = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,C:D" + ) + df3 = pd.read_excel( + "test1" + read_ext, + sheet_name="Sheet2", + skiprows=[1], + index_col=0, + usecols="A,C:D", + ) + tm.assert_frame_equal(df2, expected) + tm.assert_frame_equal(df3, expected) + + @pytest.mark.parametrize( + "usecols", [[0, 1, 3], [0, 3, 1], [1, 0, 3], [1, 3, 0], [3, 0, 1], [3, 1, 0]] + ) + def test_usecols_diff_positional_int_columns_order( + self, request, engine, read_ext, usecols, df_ref + ): + xfail_datetimes_with_pyxlsb(engine, request) + + expected = df_ref[["A", "C"]] + adjust_expected(expected, read_ext, engine) + + result = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=usecols + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("usecols", [["B", "D"], ["D", "B"]]) + def test_usecols_diff_positional_str_columns_order(self, read_ext, usecols, df_ref): + expected = df_ref[["B", "D"]] + expected.index = range(len(expected)) + + result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", usecols=usecols) + tm.assert_frame_equal(result, expected) + + def test_read_excel_without_slicing(self, request, engine, read_ext, df_ref): + xfail_datetimes_with_pyxlsb(engine, request) + + expected = df_ref + adjust_expected(expected, read_ext, engine) + + result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0) + tm.assert_frame_equal(result, expected) + + def test_usecols_excel_range_str(self, request, engine, read_ext, df_ref): + xfail_datetimes_with_pyxlsb(engine, request) + + expected = df_ref[["C", "D"]] + adjust_expected(expected, read_ext, engine) + + result = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,D:E" + ) + tm.assert_frame_equal(result, expected) + + def test_usecols_excel_range_str_invalid(self, read_ext): + msg = "Invalid column name: E1" + + with pytest.raises(ValueError, match=msg): + pd.read_excel("test1" + read_ext, sheet_name="Sheet1", usecols="D:E1") + + def test_index_col_label_error(self, read_ext): + msg = "list indices must be integers.*, not str" + + with pytest.raises(TypeError, match=msg): + pd.read_excel( + "test1" + read_ext, + sheet_name="Sheet1", + index_col=["A"], + usecols=["A", "C"], + ) + + def test_index_col_str(self, read_ext): + # see gh-52716 + result = pd.read_excel("test1" + read_ext, sheet_name="Sheet3", index_col="A") + expected = pd.DataFrame( + columns=["B", "C", "D", "E", "F"], index=pd.Index([], name="A") + ) + tm.assert_frame_equal(result, expected) + + def test_index_col_empty(self, read_ext): + # see gh-9208 + result = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet3", index_col=["A", "B", "C"] + ) + expected = pd.DataFrame( + columns=["D", "E", "F"], + index=pd.MultiIndex(levels=[[]] * 3, codes=[[]] * 3, names=["A", "B", "C"]), + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("index_col", [None, 2]) + def test_index_col_with_unnamed(self, read_ext, index_col): + # see gh-18792 + result = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet4", index_col=index_col + ) + expected = pd.DataFrame( + [["i1", "a", "x"], ["i2", "b", "y"]], columns=["Unnamed: 0", "col1", "col2"] + ) + if index_col: + expected = expected.set_index(expected.columns[index_col]) + + tm.assert_frame_equal(result, expected) + + def test_usecols_pass_non_existent_column(self, read_ext): + msg = ( + "Usecols do not match columns, " + "columns expected but not found: " + r"\['E'\]" + ) + + with pytest.raises(ValueError, match=msg): + pd.read_excel("test1" + read_ext, usecols=["E"]) + + def test_usecols_wrong_type(self, read_ext): + msg = ( + "'usecols' must either be list-like of " + "all strings, all unicode, all integers or a callable." + ) + + with pytest.raises(ValueError, match=msg): + pd.read_excel("test1" + read_ext, usecols=["E1", 0]) + + def test_excel_stop_iterator(self, read_ext): + parsed = pd.read_excel("test2" + read_ext, sheet_name="Sheet1") + expected = pd.DataFrame([["aaaa", "bbbbb"]], columns=["Test", "Test1"]) + tm.assert_frame_equal(parsed, expected) + + def test_excel_cell_error_na(self, request, engine, read_ext): + xfail_datetimes_with_pyxlsb(engine, request) + + # https://github.com/tafia/calamine/issues/355 + if engine == "calamine" and read_ext == ".ods": + request.applymarker( + pytest.mark.xfail(reason="Calamine can't extract error from ods files") + ) + + parsed = pd.read_excel("test3" + read_ext, sheet_name="Sheet1") + expected = pd.DataFrame([[np.nan]], columns=["Test"]) + tm.assert_frame_equal(parsed, expected) + + def test_excel_table(self, request, engine, read_ext, df_ref): + xfail_datetimes_with_pyxlsb(engine, request) + + expected = df_ref + adjust_expected(expected, read_ext, engine) + + df1 = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0) + df2 = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet2", skiprows=[1], index_col=0 + ) + # TODO add index to file + tm.assert_frame_equal(df1, expected) + tm.assert_frame_equal(df2, expected) + + df3 = pd.read_excel( + "test1" + read_ext, sheet_name="Sheet1", index_col=0, skipfooter=1 + ) + tm.assert_frame_equal(df3, df1.iloc[:-1]) + + def test_reader_special_dtypes(self, request, engine, read_ext): + xfail_datetimes_with_pyxlsb(engine, request) + + unit = get_exp_unit(read_ext, engine) + expected = pd.DataFrame.from_dict( + { + "IntCol": [1, 2, -3, 4, 0], + "FloatCol": [1.25, 2.25, 1.83, 1.92, 0.0000000005], + "BoolCol": [True, False, True, True, False], + "StrCol": [1, 2, 3, 4, 5], + "Str2Col": ["a", 3, "c", "d", "e"], + "DateCol": pd.Index( + [ + datetime(2013, 10, 30), + datetime(2013, 10, 31), + datetime(1905, 1, 1), + datetime(2013, 12, 14), + datetime(2015, 3, 14), + ], + dtype=f"M8[{unit}]", + ), + }, + ) + basename = "test_types" + + # should read in correctly and infer types + actual = pd.read_excel(basename + read_ext, sheet_name="Sheet1") + tm.assert_frame_equal(actual, expected) + + # if not coercing number, then int comes in as float + float_expected = expected.copy() + float_expected.loc[float_expected.index[1], "Str2Col"] = 3.0 + actual = pd.read_excel(basename + read_ext, sheet_name="Sheet1") + tm.assert_frame_equal(actual, float_expected) + + # check setting Index (assuming xls and xlsx are the same here) + for icol, name in enumerate(expected.columns): + actual = pd.read_excel( + basename + read_ext, sheet_name="Sheet1", index_col=icol + ) + exp = expected.set_index(name) + tm.assert_frame_equal(actual, exp) + + expected["StrCol"] = expected["StrCol"].apply(str) + actual = pd.read_excel( + basename + read_ext, sheet_name="Sheet1", converters={"StrCol": str} + ) + tm.assert_frame_equal(actual, expected) + + # GH8212 - support for converters and missing values + def test_reader_converters(self, read_ext): + basename = "test_converters" + + expected = pd.DataFrame.from_dict( + { + "IntCol": [1, 2, -3, -1000, 0], + "FloatCol": [12.5, np.nan, 18.3, 19.2, 0.000000005], + "BoolCol": ["Found", "Found", "Found", "Not found", "Found"], + "StrCol": ["1", np.nan, "3", "4", "5"], + } + ) + + converters = { + "IntCol": lambda x: int(x) if x != "" else -1000, + "FloatCol": lambda x: 10 * x if x else np.nan, + 2: lambda x: "Found" if x != "" else "Not found", + 3: lambda x: str(x) if x else "", + } + + # should read in correctly and set types of single cells (not array + # dtypes) + actual = pd.read_excel( + basename + read_ext, sheet_name="Sheet1", converters=converters + ) + tm.assert_frame_equal(actual, expected) + + def test_reader_dtype(self, read_ext): + # GH 8212 + basename = "testdtype" + actual = pd.read_excel(basename + read_ext) + + expected = pd.DataFrame( + { + "a": [1, 2, 3, 4], + "b": [2.5, 3.5, 4.5, 5.5], + "c": [1, 2, 3, 4], + "d": [1.0, 2.0, np.nan, 4.0], + } + ) + + tm.assert_frame_equal(actual, expected) + + actual = pd.read_excel( + basename + read_ext, dtype={"a": "float64", "b": "float32", "c": str} + ) + + expected["a"] = expected["a"].astype("float64") + expected["b"] = expected["b"].astype("float32") + expected["c"] = pd.Series(["001", "002", "003", "004"], dtype="str") + tm.assert_frame_equal(actual, expected) + + msg = "Unable to convert column d to type int64" + with pytest.raises(ValueError, match=msg): + pd.read_excel(basename + read_ext, dtype={"d": "int64"}) + + @pytest.mark.parametrize( + "dtype,expected", + [ + ( + None, + { + "a": [1, 2, 3, 4], + "b": [2.5, 3.5, 4.5, 5.5], + "c": [1, 2, 3, 4], + "d": [1.0, 2.0, np.nan, 4.0], + }, + ), + ( + {"a": "float64", "b": "float32", "c": str, "d": str}, + { + "a": pd.Series([1, 2, 3, 4], dtype="float64"), + "b": pd.Series([2.5, 3.5, 4.5, 5.5], dtype="float32"), + "c": pd.Series(["001", "002", "003", "004"], dtype="str"), + "d": pd.Series(["1", "2", np.nan, "4"], dtype="str"), + }, + ), + ], + ) + def test_reader_dtype_str(self, read_ext, dtype, expected): + # see gh-20377 + basename = "testdtype" + + actual = pd.read_excel(basename + read_ext, dtype=dtype) + expected = pd.DataFrame(expected) + tm.assert_frame_equal(actual, expected) + + def test_dtype_backend(self, read_ext, dtype_backend, engine, tmp_excel): + # GH#36712 + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") + + df = pd.DataFrame( + { + "a": pd.Series([1, 3], dtype="Int64"), + "b": pd.Series([2.5, 4.5], dtype="Float64"), + "c": pd.Series([True, False], dtype="boolean"), + "d": pd.Series(["a", "b"], dtype="string"), + "e": pd.Series([pd.NA, 6], dtype="Int64"), + "f": pd.Series([pd.NA, 7.5], dtype="Float64"), + "g": pd.Series([pd.NA, True], dtype="boolean"), + "h": pd.Series([pd.NA, "a"], dtype="string"), + "i": pd.Series([pd.Timestamp("2019-12-31")] * 2), + "j": pd.Series([pd.NA, pd.NA], dtype="Int64"), + } + ) + df.to_excel(tmp_excel, sheet_name="test", index=False) + result = pd.read_excel( + tmp_excel, sheet_name="test", dtype_backend=dtype_backend + ) + if dtype_backend == "pyarrow": + import pyarrow as pa + + from pandas.arrays import ArrowExtensionArray + + expected = pd.DataFrame( + { + col: ArrowExtensionArray(pa.array(df[col], from_pandas=True)) + for col in df.columns + } + ) + + # pandas uses large_string by default, but pyarrow infers string + expected["d"] = expected["d"].astype(pd.ArrowDtype(pa.string())) + expected["h"] = expected["h"].astype(pd.ArrowDtype(pa.string())) + # pyarrow by default infers timestamp resolution as us, not ns + expected["i"] = ArrowExtensionArray( + expected["i"].array._pa_array.cast(pa.timestamp(unit="us")) + ) + # pyarrow supports a null type, so don't have to default to Int64 + expected["j"] = ArrowExtensionArray(pa.array([None, None])) + else: + expected = df + unit = get_exp_unit(read_ext, engine) + expected["i"] = expected["i"].astype(f"M8[{unit}]") + + tm.assert_frame_equal(result, expected) + + def test_dtype_backend_and_dtype(self, read_ext, tmp_excel): + # GH#36712 + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") + + df = pd.DataFrame({"a": [np.nan, 1.0], "b": [2.5, np.nan]}) + df.to_excel(tmp_excel, sheet_name="test", index=False) + result = pd.read_excel( + tmp_excel, + sheet_name="test", + dtype_backend="numpy_nullable", + dtype="float64", + ) + tm.assert_frame_equal(result, df) + + def test_dtype_backend_string(self, read_ext, string_storage, tmp_excel): + # GH#36712 + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") + + df = pd.DataFrame( + { + "a": np.array(["a", "b"], dtype=np.object_), + "b": np.array(["x", pd.NA], dtype=np.object_), + } + ) + df.to_excel(tmp_excel, sheet_name="test", index=False) + + with pd.option_context("mode.string_storage", string_storage): + result = pd.read_excel( + tmp_excel, sheet_name="test", dtype_backend="numpy_nullable" + ) + + expected = pd.DataFrame( + { + "a": pd.Series(["a", "b"], dtype=pd.StringDtype(string_storage)), + "b": pd.Series(["x", None], dtype=pd.StringDtype(string_storage)), + } + ) + # the storage of the str columns' Index is also affected by the + # string_storage setting -> ignore that for checking the result + tm.assert_frame_equal(result, expected, check_column_type=False) + + def test_dtype_category_infers_numeric_and_bool(self, read_ext, tmp_excel): + # GH#56044 read_excel shares read_csv's category inference, matching + # the types these columns get without dtype="category" + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") + + df = pd.DataFrame({"a": ["1", "2", "1"], "b": ["True", "False", "True"]}) + df.to_excel(tmp_excel, sheet_name="test", index=False) + + result = pd.read_excel(tmp_excel, sheet_name="test", dtype="category") + + expected = pd.DataFrame( + {"a": pd.Categorical([1, 2, 1]), "b": pd.Categorical([True, False, True])} + ) + tm.assert_frame_equal(result, expected) + + def test_dtype_category_native_cells(self, read_ext, tmp_excel): + # GH#56044 as above for cells that are natively typed rather than + # text, which reach the inference as Python ints/floats/bools + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") + + df = pd.DataFrame( + {"a": [1, 2, 1], "b": [3.5, 4.5, 3.5], "c": [True, False, True]} + ) + df.to_excel(tmp_excel, sheet_name="test", index=False) + + result = pd.read_excel(tmp_excel, sheet_name="test", dtype="category") + + expected = pd.DataFrame({col: pd.Categorical(vals) for col, vals in df.items()}) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtypes, exp_value", [({}, 1), ({"a.1": "int64"}, 1)]) + def test_dtype_mangle_dup_cols(self, read_ext, dtypes, exp_value): + # GH#35211 + basename = "df_mangle_dup_col_dtypes" + dtype_dict = {"a": object, **dtypes} + dtype_dict_copy = dtype_dict.copy() + # GH#42462 + result = pd.read_excel(basename + read_ext, dtype=dtype_dict) + expected = pd.DataFrame( + { + "a": pd.Series([1], dtype=object), + "a.1": pd.Series([exp_value], dtype=object if not dtypes else None), + } + ) + assert dtype_dict == dtype_dict_copy, "dtype dict changed" + tm.assert_frame_equal(result, expected) + + def test_reader_spaces(self, read_ext): + # see gh-32207 + basename = "test_spaces" + + actual = pd.read_excel(basename + read_ext) + expected = pd.DataFrame( + { + "testcol": [ + "this is great", + "4 spaces", + "1 trailing ", + " 1 leading", + "2 spaces multiple times", + ] + } + ) + tm.assert_frame_equal(actual, expected) + + # gh-36122, gh-35802 + @pytest.mark.parametrize( + "basename,expected", + [ + ("gh-35802", pd.DataFrame({"COLUMN": ["Test (1)"]})), + ("gh-36122", pd.DataFrame(columns=["got 2nd sa"])), + ], + ) + def test_read_excel_ods_nested_xml(self, engine, read_ext, basename, expected): + # see gh-35802 + if engine != "odf": + pytest.skip(f"Skipped for engine: {engine}") + + actual = pd.read_excel(basename + read_ext) + tm.assert_frame_equal(actual, expected) + + def test_reading_all_sheets(self, read_ext): + # Test reading all sheet names by setting sheet_name to None, + # Ensure a dict is returned. + # See PR #9450 + basename = "test_multisheet" + dfs = pd.read_excel(basename + read_ext, sheet_name=None) + # ensure this is not alphabetical to test order preservation + expected_keys = ["Charlie", "Alpha", "Beta"] + tm.assert_contains_all(expected_keys, dfs.keys()) + # Issue 9930 + # Ensure sheet order is preserved + assert expected_keys == list(dfs.keys()) + + def test_reading_multiple_specific_sheets(self, read_ext): + # Test reading specific sheet names by specifying a mixed list + # of integers and strings, and confirm that duplicated sheet + # references (positions/names) are removed properly. + # Ensure a dict is returned + # See PR #9450 + basename = "test_multisheet" + # Explicitly request duplicates. Only the set should be returned. + expected_keys = [2, "Charlie", "Charlie"] + dfs = pd.read_excel(basename + read_ext, sheet_name=expected_keys) + expected_keys = list(set(expected_keys)) + tm.assert_contains_all(expected_keys, dfs.keys()) + assert len(expected_keys) == len(dfs.keys()) + + def test_reading_all_sheets_with_blank(self, read_ext): + # Test reading all sheet names by setting sheet_name to None, + # In the case where some sheets are blank. + # Issue #11711 + basename = "blank_with_header" + dfs = pd.read_excel(basename + read_ext, sheet_name=None) + expected_keys = ["Sheet1", "Sheet2", "Sheet3"] + tm.assert_contains_all(expected_keys, dfs.keys()) + + # GH6403 + def test_read_excel_blank(self, read_ext): + actual = pd.read_excel("blank" + read_ext, sheet_name="Sheet1") + tm.assert_frame_equal(actual, pd.DataFrame()) + + def test_read_excel_blank_with_header(self, read_ext): + expected = pd.DataFrame(columns=["col_1", "col_2"]) + actual = pd.read_excel("blank_with_header" + read_ext, sheet_name="Sheet1") + tm.assert_frame_equal(actual, expected) + + def test_exception_message_includes_sheet_name(self, read_ext): + # GH 48706 + with pytest.raises(ValueError, match=r" \(sheet: Sheet1\)$"): + pd.read_excel("blank_with_header" + read_ext, header=[1], sheet_name=None) + with pytest.raises(ZeroDivisionError, match=r" \(sheet: Sheet1\)$"): + pd.read_excel("test1" + read_ext, usecols=lambda x: 1 / 0, sheet_name=None) + + def test_date_conversion_overflow(self, request, engine, read_ext): + # GH 10001 : pandas.ExcelFile ignore parse_dates=False + xfail_datetimes_with_pyxlsb(engine, request) + + expected = pd.DataFrame( + [ + [pd.Timestamp("2016-03-12"), "Marc Johnson"], + [pd.Timestamp("2016-03-16"), "Jack Black"], + [1e20, "Timothy Brown"], + ], + columns=["DateColWithBigInt", "StringCol"], + ) + + if engine == "openpyxl": + request.applymarker( + pytest.mark.xfail(reason="Maybe not supported by openpyxl") + ) + + if engine is None and read_ext in (".xlsx", ".xlsm"): + # GH 35029 + request.applymarker( + pytest.mark.xfail(reason="Defaults to openpyxl, maybe not supported") + ) + + result = pd.read_excel("testdateoverflow" + read_ext) + tm.assert_frame_equal(result, expected) + + def test_sheet_name(self, request, read_ext, engine, df_ref): + xfail_datetimes_with_pyxlsb(engine, request) + + filename = "test1" + sheet_name = "Sheet1" + + expected = df_ref + adjust_expected(expected, read_ext, engine) + + df1 = pd.read_excel( + filename + read_ext, sheet_name=sheet_name, index_col=0 + ) # doc + df2 = pd.read_excel(filename + read_ext, index_col=0, sheet_name=sheet_name) + + tm.assert_frame_equal(df1, expected) + tm.assert_frame_equal(df2, expected) + + def test_excel_read_buffer(self, read_ext): + pth = "test1" + read_ext + expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0) + with open(pth, "rb") as f: + actual = pd.read_excel(f, sheet_name="Sheet1", index_col=0) + tm.assert_frame_equal(expected, actual) + + def test_bad_engine_raises(self): + bad_engine = "foo" + with pytest.raises(ValueError, match="Unknown engine: foo"): + pd.read_excel("", engine=bad_engine) + + @pytest.mark.parametrize( + "sheet_name", + [3, [0, 3], [3, 0], "Sheet4", ["Sheet1", "Sheet4"], ["Sheet4", "Sheet1"]], + ) + def test_bad_sheetname_raises(self, read_ext, sheet_name): + # GH 39250 + msg = "|".join( + ["Worksheet index 3 is invalid", "Worksheet named 'Sheet4' not found"] + ) + with pytest.raises(ValueError, match=msg): + pd.read_excel("blank" + read_ext, sheet_name=sheet_name) + + def test_missing_file_raises(self, read_ext): + bad_file = f"foo{read_ext}" + # CI tests with other languages, translates to "No such file or directory" + match = "|".join( + [ + "(No such file or directory", + "没有那个文件或目录", + "File o directory non esistente)", + ] + ) + with pytest.raises(FileNotFoundError, match=match): + pd.read_excel(bad_file) + + def test_corrupt_bytes_raises(self, engine): + bad_stream = b"foo" + if engine is None: + error = ValueError + msg = ( + "Excel file format cannot be determined, you must " + "specify an engine manually." + ) + elif engine == "xlrd": + from xlrd import XLRDError + + error = XLRDError + msg = ( + "Unsupported format, or corrupt file: Expected BOF record; found b'foo'" + ) + elif engine == "calamine": + from python_calamine import CalamineError + + error = CalamineError + msg = "Cannot detect file format" + else: + error = BadZipFile + msg = "File is not a zip file" + with pytest.raises(error, match=msg): + pd.read_excel(BytesIO(bad_stream)) + + @pytest.mark.network + @pytest.mark.single_cpu + def test_read_from_http_url(self, httpserver, read_ext): + with open("test1" + read_ext, "rb") as f: + httpserver.serve_content(content=f.read()) + url_table = pd.read_excel(httpserver.url) + local_table = pd.read_excel("test1" + read_ext) + tm.assert_frame_equal(url_table, local_table) + + @pytest.mark.single_cpu + def test_read_from_s3_url(self, read_ext, s3_bucket_public, s3so): + with open("test1" + read_ext, "rb") as f: + s3_bucket_public.put_object(Key="test1" + read_ext, Body=f) + + url = f"s3://{s3_bucket_public.name}/test1" + read_ext + + url_table = pd.read_excel(url, storage_options=s3so) + local_table = pd.read_excel("test1" + read_ext) + tm.assert_frame_equal(url_table, local_table) + + @pytest.mark.single_cpu + def test_read_from_s3_object(self, read_ext, s3_bucket_public, s3so): + # GH 38788 + with open("test1" + read_ext, "rb") as f: + s3_bucket_public.put_object(Key="test1" + read_ext, Body=f) + + import s3fs + + s3 = s3fs.S3FileSystem(**s3so) + + with s3.open(f"s3://{s3_bucket_public.name}/test1" + read_ext) as f: + url_table = pd.read_excel(f) + + local_table = pd.read_excel("test1" + read_ext) + tm.assert_frame_equal(url_table, local_table) + + @pytest.mark.slow + def test_read_from_file_url(self, read_ext, datapath): + # FILE + localtable = os.path.join(datapath("io", "data", "excel"), "test1" + read_ext) + local_table = pd.read_excel(localtable) + + try: + url_table = pd.read_excel("file://localhost/" + localtable) + except URLError: + # fails on some systems + platform_info = " ".join(platform.uname()).strip() + pytest.skip(f"failing on {platform_info}") + + tm.assert_frame_equal(url_table, local_table) + + def test_read_from_pathlib_path(self, read_ext): + # GH12655 + str_path = "test1" + read_ext + expected = pd.read_excel(str_path, sheet_name="Sheet1", index_col=0) + + path_obj = Path("test1" + read_ext) + actual = pd.read_excel(path_obj, sheet_name="Sheet1", index_col=0) + + tm.assert_frame_equal(expected, actual) + + def test_close_from_py_localpath(self, read_ext): + # GH31467 + str_path = os.path.join("test1" + read_ext) + with open(str_path, "rb") as f: + x = pd.read_excel(f, sheet_name="Sheet1", index_col=0) + del x + # should not throw an exception because the passed file was closed + f.read() + + def test_reader_seconds(self, request, engine, read_ext): + xfail_datetimes_with_pyxlsb(engine, request) + + # GH 55045 + if engine == "calamine" and read_ext == ".ods": + request.applymarker( + pytest.mark.xfail( + reason="ODS file contains bad datetime (seconds as text)" + ) + ) + + # Test reading times with and without milliseconds. GH5945. + expected = pd.DataFrame.from_dict( + { + "Time": [ + time(1, 2, 3), + time(2, 45, 56, 100000), + time(4, 29, 49, 200000), + time(6, 13, 42, 300000), + time(7, 57, 35, 400000), + time(9, 41, 28, 500000), + time(11, 25, 21, 600000), + time(13, 9, 14, 700000), + time(14, 53, 7, 800000), + time(16, 37, 0, 900000), + time(18, 20, 54), + ] + } + ) + + actual = pd.read_excel("times_1900" + read_ext, sheet_name="Sheet1") + tm.assert_frame_equal(actual, expected) + + actual = pd.read_excel("times_1904" + read_ext, sheet_name="Sheet1") + tm.assert_frame_equal(actual, expected) + + def test_read_excel_multiindex(self, request, engine, read_ext): + # see gh-4679 + xfail_datetimes_with_pyxlsb(engine, request) + + unit = get_exp_unit(read_ext, engine) + + mi = pd.MultiIndex.from_product([["foo", "bar"], ["a", "b"]]) + mi_file = "testmultiindex" + read_ext + + # "mi_column" sheet + expected = pd.DataFrame( + [ + [1, 2.5, pd.Timestamp("2015-01-01"), True], + [2, 3.5, pd.Timestamp("2015-01-02"), False], + [3, 4.5, pd.Timestamp("2015-01-03"), False], + [4, 5.5, pd.Timestamp("2015-01-04"), True], + ], + columns=mi, + ) + expected[mi[2]] = expected[mi[2]].astype(f"M8[{unit}]") + + actual = pd.read_excel( + mi_file, sheet_name="mi_column", header=[0, 1], index_col=0 + ) + tm.assert_frame_equal(actual, expected) + + # "mi_index" sheet + expected.index = mi + expected.columns = ["a", "b", "c", "d"] + + actual = pd.read_excel(mi_file, sheet_name="mi_index", index_col=[0, 1]) + tm.assert_frame_equal(actual, expected) + + # "both" sheet + expected.columns = mi + + actual = pd.read_excel( + mi_file, sheet_name="both", index_col=[0, 1], header=[0, 1] + ) + tm.assert_frame_equal(actual, expected) + + # "mi_index_name" sheet + expected.columns = ["a", "b", "c", "d"] + expected.index = mi.set_names(["ilvl1", "ilvl2"]) + + actual = pd.read_excel(mi_file, sheet_name="mi_index_name", index_col=[0, 1]) + tm.assert_frame_equal(actual, expected) + + # "mi_column_name" sheet + expected.index = range(4) + expected.columns = mi.set_names(["c1", "c2"]) + actual = pd.read_excel( + mi_file, sheet_name="mi_column_name", header=[0, 1], index_col=0 + ) + tm.assert_frame_equal(actual, expected) + + # see gh-11317 + # "name_with_int" sheet + expected.columns = mi.set_levels([1, 2], level=1).set_names(["c1", "c2"]) + + actual = pd.read_excel( + mi_file, sheet_name="name_with_int", index_col=0, header=[0, 1] + ) + tm.assert_frame_equal(actual, expected) + + # "both_name" sheet + expected.columns = mi.set_names(["c1", "c2"]) + expected.index = mi.set_names(["ilvl1", "ilvl2"]) + + actual = pd.read_excel( + mi_file, sheet_name="both_name", index_col=[0, 1], header=[0, 1] + ) + tm.assert_frame_equal(actual, expected) + + # "both_skiprows" sheet + actual = pd.read_excel( + mi_file, + sheet_name="both_name_skiprows", + index_col=[0, 1], + header=[0, 1], + skiprows=2, + ) + tm.assert_frame_equal(actual, expected) + + @pytest.mark.parametrize( + "sheet_name,idx_lvl2", + [ + ("both_name_blank_after_mi_name", [np.nan, "b", "a", "b"]), + ("both_name_multiple_blanks", [np.nan] * 4), + ], + ) + def test_read_excel_multiindex_blank_after_name( + self, request, engine, read_ext, sheet_name, idx_lvl2 + ): + # GH34673 + xfail_datetimes_with_pyxlsb(engine, request) + + mi_file = "testmultiindex" + read_ext + mi = pd.MultiIndex.from_product( + [["foo", "bar"], ["a", "b"]], names=["c1", "c2"] + ) + + unit = get_exp_unit(read_ext, engine) + expected = pd.DataFrame( + [ + [1, 2.5, pd.Timestamp("2015-01-01"), True], + [2, 3.5, pd.Timestamp("2015-01-02"), False], + [3, 4.5, pd.Timestamp("2015-01-03"), False], + [4, 5.5, pd.Timestamp("2015-01-04"), True], + ], + columns=mi, + index=pd.MultiIndex.from_arrays( + (["foo", "foo", "bar", "bar"], idx_lvl2), + names=["ilvl1", "ilvl2"], + ), + ) + expected[mi[2]] = expected[mi[2]].astype(f"M8[{unit}]") + result = pd.read_excel( + mi_file, + sheet_name=sheet_name, + index_col=[0, 1], + header=[0, 1], + ) + tm.assert_frame_equal(result, expected) + + def test_read_excel_multiindex_header_only(self, read_ext): + # see gh-11733. + # + # Don't try to parse a header name if there isn't one. + mi_file = "testmultiindex" + read_ext + result = pd.read_excel(mi_file, sheet_name="index_col_none", header=[0, 1]) + + exp_columns = pd.MultiIndex.from_product([("A", "B"), ("key", "val")]) + expected = pd.DataFrame([[1, 2, 3, 4]] * 2, columns=exp_columns) + tm.assert_frame_equal(result, expected) + + def test_excel_old_index_format(self, read_ext): + # see gh-4679 + filename = "test_index_name_pre17" + read_ext + + # We detect headers to determine if index names exist, so + # that "index" name in the "names" version of the data will + # now be interpreted as rows that include null data. + data = np.array( + [ + [np.nan, np.nan, np.nan, np.nan, np.nan], + ["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"], + ["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"], + ["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"], + ["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"], + ["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"], + ], + dtype=object, + ) + columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"] + mi = pd.MultiIndex( + levels=[ + ["R0", "R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"], + ["R1", "R_l1_g0", "R_l1_g1", "R_l1_g2", "R_l1_g3", "R_l1_g4"], + ], + codes=[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]], + names=[None, None], + ) + si = pd.Index( + ["R0", "R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"], name=None + ) + + expected = pd.DataFrame(data, index=si, columns=columns) + + actual = pd.read_excel(filename, sheet_name="single_names", index_col=0) + tm.assert_frame_equal(actual, expected) + + expected.index = mi + + actual = pd.read_excel(filename, sheet_name="multi_names", index_col=[0, 1]) + tm.assert_frame_equal(actual, expected) + + # The analogous versions of the "names" version data + # where there are explicitly no names for the indices. + data = np.array( + [ + ["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"], + ["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"], + ["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"], + ["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"], + ["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"], + ] + ) + columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"] + mi = pd.MultiIndex( + levels=[ + ["R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"], + ["R_l1_g0", "R_l1_g1", "R_l1_g2", "R_l1_g3", "R_l1_g4"], + ], + codes=[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], + names=[None, None], + ) + si = pd.Index( + ["R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"], name=None + ) + + expected = pd.DataFrame(data, index=si, columns=columns) + + actual = pd.read_excel(filename, sheet_name="single_no_names", index_col=0) + tm.assert_frame_equal(actual, expected) + + expected.index = mi + + actual = pd.read_excel(filename, sheet_name="multi_no_names", index_col=[0, 1]) + tm.assert_frame_equal(actual, expected) + + def test_read_excel_bool_header_arg(self, read_ext): + # GH 6114 + msg = "Passing a bool to header is invalid" + for arg in [True, False]: + with pytest.raises(TypeError, match=msg): + pd.read_excel("test1" + read_ext, header=arg) + + def test_read_excel_skiprows(self, request, engine, read_ext): + # GH 4903 + xfail_datetimes_with_pyxlsb(engine, request) + + unit = get_exp_unit(read_ext, engine) + + actual = pd.read_excel( + "testskiprows" + read_ext, sheet_name="skiprows_list", skiprows=[0, 2] + ) + expected = pd.DataFrame( + [ + [1, 2.5, pd.Timestamp("2015-01-01"), True], + [2, 3.5, pd.Timestamp("2015-01-02"), False], + [3, 4.5, pd.Timestamp("2015-01-03"), False], + [4, 5.5, pd.Timestamp("2015-01-04"), True], + ], + columns=["a", "b", "c", "d"], + ) + expected["c"] = expected["c"].astype(f"M8[{unit}]") + tm.assert_frame_equal(actual, expected) + + actual = pd.read_excel( + "testskiprows" + read_ext, + sheet_name="skiprows_list", + skiprows=np.array([0, 2]), + ) + tm.assert_frame_equal(actual, expected) + + # GH36435 + actual = pd.read_excel( + "testskiprows" + read_ext, + sheet_name="skiprows_list", + skiprows=lambda x: x in [0, 2], + ) + tm.assert_frame_equal(actual, expected) + + actual = pd.read_excel( + "testskiprows" + read_ext, + sheet_name="skiprows_list", + skiprows=3, + names=["a", "b", "c", "d"], + ) + expected = pd.DataFrame( + [ + # [1, 2.5, pd.Timestamp("2015-01-01"), True], + [2, 3.5, pd.Timestamp("2015-01-02"), False], + [3, 4.5, pd.Timestamp("2015-01-03"), False], + [4, 5.5, pd.Timestamp("2015-01-04"), True], + ], + columns=["a", "b", "c", "d"], + ) + expected["c"] = expected["c"].astype(f"M8[{unit}]") + tm.assert_frame_equal(actual, expected) + + def test_read_excel_skiprows_callable_not_in(self, request, engine, read_ext): + # GH 4903 + xfail_datetimes_with_pyxlsb(engine, request) + unit = get_exp_unit(read_ext, engine) + + actual = pd.read_excel( + "testskiprows" + read_ext, + sheet_name="skiprows_list", + skiprows=lambda x: x not in [1, 3, 5], + ) + expected = pd.DataFrame( + [ + [1, 2.5, pd.Timestamp("2015-01-01"), True], + # [2, 3.5, pd.Timestamp("2015-01-02"), False], + [3, 4.5, pd.Timestamp("2015-01-03"), False], + # [4, 5.5, pd.Timestamp("2015-01-04"), True], + ], + columns=["a", "b", "c", "d"], + ) + expected["c"] = expected["c"].astype(f"M8[{unit}]") + tm.assert_frame_equal(actual, expected) + + def test_read_excel_skiprows_callable_all(self, read_ext, monkeypatch): + # GH 64027 + with monkeypatch.context() as m: + m.setattr(_excel_base, "EXCEL_ROWS_MAX", 10) + actual = pd.read_excel("test1" + read_ext, skiprows=lambda _: True, nrows=1) + expected = pd.DataFrame() + tm.assert_frame_equal(actual, expected) + + def test_read_excel_nrows(self, read_ext): + # GH 16645 + num_rows_to_pull = 5 + actual = pd.read_excel("test1" + read_ext, nrows=num_rows_to_pull) + expected = pd.read_excel("test1" + read_ext) + expected = expected[:num_rows_to_pull] + tm.assert_frame_equal(actual, expected) + + def test_read_excel_nrows_greater_than_nrows_in_file(self, read_ext): + # GH 16645 + expected = pd.read_excel("test1" + read_ext) + num_records_in_file = len(expected) + num_rows_to_pull = num_records_in_file + 10 + actual = pd.read_excel("test1" + read_ext, nrows=num_rows_to_pull) + tm.assert_frame_equal(actual, expected) + + def test_read_excel_nrows_non_integer_parameter(self, read_ext): + # GH 16645 + msg = "'nrows' must be an integer >=0" + with pytest.raises(ValueError, match=msg): + pd.read_excel("test1" + read_ext, nrows="5") + + @pytest.mark.parametrize( + "filename,sheet_name,header,index_col,skiprows", + [ + ("testmultiindex", "mi_column", [0, 1], 0, None), + ("testmultiindex", "mi_index", None, [0, 1], None), + ("testmultiindex", "both", [0, 1], [0, 1], None), + ("testmultiindex", "mi_column_name", [0, 1], 0, None), + ("testskiprows", "skiprows_list", None, None, [0, 2]), + ("testskiprows", "skiprows_list", None, None, lambda x: x in (0, 2)), + ], + ) + def test_read_excel_nrows_params( + self, read_ext, filename, sheet_name, header, index_col, skiprows + ): + """ + For various parameters, we should get the same result whether we + limit the rows during load (nrows=3) or after (df.iloc[:3]). + """ + # GH 46894 + expected = pd.read_excel( + filename + read_ext, + sheet_name=sheet_name, + header=header, + index_col=index_col, + skiprows=skiprows, + ).iloc[:3] + actual = pd.read_excel( + filename + read_ext, + sheet_name=sheet_name, + header=header, + index_col=index_col, + skiprows=skiprows, + nrows=3, + ) + tm.assert_frame_equal(actual, expected) + + def test_deprecated_kwargs(self, read_ext): + with pytest.raises(TypeError, match="but 3 positional arguments"): + pd.read_excel("test1" + read_ext, "Sheet1", 0) + + def test_no_header_with_list_index_col(self, read_ext): + # GH 31783 + file_name = "testmultiindex" + read_ext + data = [("B", "B"), ("key", "val"), (3, 4), (3, 4)] + idx = pd.MultiIndex.from_tuples( + [("A", "A"), ("key", "val"), (1, 2), (1, 2)], names=(0, 1) + ) + expected = pd.DataFrame(data, index=idx, columns=(2, 3)) + result = pd.read_excel( + file_name, sheet_name="index_col_none", index_col=[0, 1], header=None + ) + tm.assert_frame_equal(expected, result) + + def test_one_col_noskip_blank_line(self, read_ext): + # GH 39808 + file_name = "one_col_blank_line" + read_ext + data = [0.5, np.nan, 1, 2] + expected = pd.DataFrame(data, columns=["numbers"]) + result = pd.read_excel(file_name) + tm.assert_frame_equal(result, expected) + + def test_multiheader_two_blank_lines(self, read_ext): + # GH 40442 + file_name = "testmultiindex" + read_ext + columns = pd.MultiIndex.from_tuples([("a", "A"), ("b", "B")]) + data = [[np.nan, np.nan], [np.nan, np.nan], [1, 3], [2, 4]] + expected = pd.DataFrame(data, columns=columns) + result = pd.read_excel( + file_name, sheet_name="mi_column_empty_rows", header=[0, 1] + ) + tm.assert_frame_equal(result, expected) + + def test_trailing_blanks(self, read_ext): + """ + Sheets can contain blank cells with no data. Some of our readers + were including those cells, creating many empty rows and columns + """ + file_name = "trailing_blanks" + read_ext + result = pd.read_excel(file_name) + assert result.shape == (3, 3) + + def test_ignore_chartsheets_by_str(self, request, engine, read_ext): + # GH 41448 + if read_ext == ".ods": + pytest.skip("chartsheets do not exist in the ODF format") + if engine == "pyxlsb": + request.applymarker( + pytest.mark.xfail( + reason="pyxlsb can't distinguish chartsheets from worksheets" + ) + ) + with pytest.raises(ValueError, match="Worksheet named 'Chart1' not found"): + pd.read_excel("chartsheet" + read_ext, sheet_name="Chart1") + + def test_ignore_chartsheets_by_int(self, request, engine, read_ext): + # GH 41448 + if read_ext == ".ods": + pytest.skip("chartsheets do not exist in the ODF format") + if engine == "pyxlsb": + request.applymarker( + pytest.mark.xfail( + reason="pyxlsb can't distinguish chartsheets from worksheets" + ) + ) + with pytest.raises( + ValueError, match="Worksheet index 1 is invalid, 1 worksheets found" + ): + pd.read_excel("chartsheet" + read_ext, sheet_name=1) + + def test_euro_decimal_format(self, read_ext): + # copied from read_csv + result = pd.read_excel("test_decimal" + read_ext, decimal=",", skiprows=1) + expected = pd.DataFrame( + [ + [1, 1521.1541, 187101.9543, "ABC", "poi", 4.738797819], + [2, 121.12, 14897.76, "DEF", "uyt", 0.377320872], + [3, 878.158, 108013.434, "GHI", "rez", 2.735694704], + ], + columns=["Id", "Number1", "Number2", "Text1", "Text2", "Number3"], + ) + tm.assert_frame_equal(result, expected) + + +class TestExcelFileRead: + def test_raises_bytes_input(self, engine, read_ext): + # GH 53830 + msg = "Expected file path name or file-like object" + with pytest.raises(TypeError, match=msg): + with open("test1" + read_ext, "rb") as f: + pd.read_excel(f.read(), engine=engine) + + @pytest.fixture(autouse=True) + def cd_and_set_engine(self, engine, datapath, monkeypatch): + """ + Change directory and set engine for ExcelFile objects. + """ + func = partial(pd.ExcelFile, engine=engine) + monkeypatch.chdir(datapath("io", "data", "excel")) + monkeypatch.setattr(pd, "ExcelFile", func) + + def test_engine_used(self, read_ext, engine): + expected_defaults = { + "xlsx": "openpyxl", + "xlsm": "openpyxl", + "xlsb": "pyxlsb", + "xls": "xlrd", + "ods": "odf", + } + + with pd.ExcelFile("test1" + read_ext) as excel: + result = excel.engine + + if engine is not None: + expected = engine + else: + expected = expected_defaults[read_ext[1:]] + assert result == expected + + def test_excel_passes_na(self, read_ext): + with pd.ExcelFile("test4" + read_ext) as excel: + parsed = pd.read_excel( + excel, sheet_name="Sheet1", keep_default_na=False, na_values=["apple"] + ) + expected = pd.DataFrame( + [["NA"], [1], ["NA"], [np.nan], ["rabbit"]], columns=["Test"] + ) + tm.assert_frame_equal(parsed, expected) + + with pd.ExcelFile("test4" + read_ext) as excel: + parsed = pd.read_excel( + excel, sheet_name="Sheet1", keep_default_na=True, na_values=["apple"] + ) + expected = pd.DataFrame( + [[np.nan], [1], [np.nan], [np.nan], ["rabbit"]], columns=["Test"] + ) + tm.assert_frame_equal(parsed, expected) + + # 13967 + with pd.ExcelFile("test5" + read_ext) as excel: + parsed = pd.read_excel( + excel, sheet_name="Sheet1", keep_default_na=False, na_values=["apple"] + ) + expected = pd.DataFrame( + [["1.#QNAN"], [1], ["nan"], [np.nan], ["rabbit"]], columns=["Test"] + ) + tm.assert_frame_equal(parsed, expected) + + with pd.ExcelFile("test5" + read_ext) as excel: + parsed = pd.read_excel( + excel, sheet_name="Sheet1", keep_default_na=True, na_values=["apple"] + ) + expected = pd.DataFrame( + [[np.nan], [1], [np.nan], [np.nan], ["rabbit"]], columns=["Test"] + ) + tm.assert_frame_equal(parsed, expected) + + @pytest.mark.parametrize("na_filter", [None, True, False]) + def test_excel_passes_na_filter(self, read_ext, na_filter): + # gh-25453 + kwargs = {} + + if na_filter is not None: + kwargs["na_filter"] = na_filter + + with pd.ExcelFile("test5" + read_ext) as excel: + parsed = pd.read_excel( + excel, + sheet_name="Sheet1", + keep_default_na=True, + na_values=["apple"], + **kwargs, + ) + + if na_filter is False: + expected = [["1.#QNAN"], [1], ["nan"], ["apple"], ["rabbit"]] + else: + expected = [[np.nan], [1], [np.nan], [np.nan], ["rabbit"]] + + expected = pd.DataFrame(expected, columns=["Test"]) + tm.assert_frame_equal(parsed, expected) + + def test_excel_bool_kwarg_not_bool(self, read_ext): + # GH#68341 a non-bool was taken for its truthiness + msg = 'For argument "na_filter" expected type bool' + with pd.ExcelFile("test1" + read_ext) as excel: + with pytest.raises(ValueError, match=msg): + pd.read_excel(excel, sheet_name="Sheet1", na_filter="False") + + def test_excel_table_sheet_by_index(self, request, engine, read_ext, df_ref): + xfail_datetimes_with_pyxlsb(engine, request) + + expected = df_ref + adjust_expected(expected, read_ext, engine) + + with pd.ExcelFile("test1" + read_ext) as excel: + df1 = pd.read_excel(excel, sheet_name=0, index_col=0) + df2 = pd.read_excel(excel, sheet_name=1, skiprows=[1], index_col=0) + tm.assert_frame_equal(df1, expected) + tm.assert_frame_equal(df2, expected) + + depr_msg = "ExcelFile.parse is deprecated" + with pd.ExcelFile("test1" + read_ext) as excel: + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + df1 = excel.parse(0, index_col=0) + df2 = excel.parse(1, skiprows=[1], index_col=0) + tm.assert_frame_equal(df1, expected) + tm.assert_frame_equal(df2, expected) + + with pd.ExcelFile("test1" + read_ext) as excel: + df3 = pd.read_excel(excel, sheet_name=0, index_col=0, skipfooter=1) + tm.assert_frame_equal(df3, df1.iloc[:-1]) + + with pd.ExcelFile("test1" + read_ext) as excel: + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + df3 = excel.parse(0, index_col=0, skipfooter=1) + + tm.assert_frame_equal(df3, df1.iloc[:-1]) + + def test_sheet_name(self, request, engine, read_ext, df_ref): + xfail_datetimes_with_pyxlsb(engine, request) + + expected = df_ref + adjust_expected(expected, read_ext, engine) + + filename = "test1" + sheet_name = "Sheet1" + + depr_msg = "ExcelFile.parse is deprecated" + with pd.ExcelFile(filename + read_ext) as excel: + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + df1_parse = excel.parse(sheet_name=sheet_name, index_col=0) # doc + + with pd.ExcelFile(filename + read_ext) as excel: + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + df2_parse = excel.parse(index_col=0, sheet_name=sheet_name) + + tm.assert_frame_equal(df1_parse, expected) + tm.assert_frame_equal(df2_parse, expected) + + @pytest.mark.parametrize( + "sheet_name", + [3, [0, 3], [3, 0], "Sheet4", ["Sheet1", "Sheet4"], ["Sheet4", "Sheet1"]], + ) + def test_bad_sheetname_raises(self, read_ext, sheet_name): + # GH 39250 + msg = "|".join( + ["Worksheet index 3 is invalid", "Worksheet named 'Sheet4' not found"] + ) + depr_msg = "ExcelFile.parse is deprecated" + with pytest.raises(ValueError, match=msg): + with pd.ExcelFile("blank" + read_ext) as excel: + with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): + excel.parse(sheet_name=sheet_name) + + def test_excel_read_buffer(self, engine, read_ext): + pth = "test1" + read_ext + expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0, engine=engine) + + with open(pth, "rb") as f: + with pd.ExcelFile(f) as xls: + actual = pd.read_excel(xls, sheet_name="Sheet1", index_col=0) + + tm.assert_frame_equal(expected, actual) + + def test_reader_closes_file(self, engine, read_ext): + with open("test1" + read_ext, "rb") as f: + with pd.ExcelFile(f) as xlsx: + # parses okay + pd.read_excel(xlsx, sheet_name="Sheet1", index_col=0, engine=engine) + + assert f.closed + + def test_conflicting_excel_engines(self, read_ext): + # GH 26566 + msg = "Engine should not be specified when passing an ExcelFile" + + with pd.ExcelFile("test1" + read_ext) as xl: + with pytest.raises(ValueError, match=msg): + pd.read_excel(xl, engine="foo") + + def test_excel_read_binary(self, engine, read_ext): + # GH 15914 + expected = pd.read_excel("test1" + read_ext, engine=engine) + + with open("test1" + read_ext, "rb") as f: + data = f.read() + + actual = pd.read_excel(BytesIO(data), engine=engine) + tm.assert_frame_equal(expected, actual) + + def test_excel_read_binary_via_read_excel(self, read_ext, engine): + # GH 38424 + with open("test1" + read_ext, "rb") as f: + result = pd.read_excel(f, engine=engine) + expected = pd.read_excel("test1" + read_ext, engine=engine) + tm.assert_frame_equal(result, expected) + + @pytest.mark.filterwarnings( + "ignore:The default engine for reading:pandas.errors.Pandas4Warning" + ) + def test_read_excel_header_index_out_of_range(self, engine): + # GH#43143 + with open("df_header_oob.xlsx", "rb") as f: + with pytest.raises(ValueError, match="exceeds maximum"): + pd.read_excel(f, header=[0, 1]) + + @pytest.mark.filterwarnings( + "ignore:The default engine for reading:pandas.errors.Pandas4Warning" + ) + @pytest.mark.parametrize("filename", ["df_empty.xlsx", "df_equals.xlsx"]) + def test_header_with_index_col(self, filename): + # GH 33476 + idx = pd.Index(["Z"], name="I2") + cols = pd.MultiIndex.from_tuples( + [("A", "B"), ("A", "B.1")], names=["I11", "I12"] + ) + expected = pd.DataFrame([[1, 3]], index=idx, columns=cols, dtype="int64") + result = pd.read_excel( + filename, sheet_name="Sheet1", index_col=0, header=[0, 1] + ) + tm.assert_frame_equal(expected, result) + + def test_read_datetime_multiindex(self, request, engine, read_ext): + # GH 34748 + xfail_datetimes_with_pyxlsb(engine, request) + + f = "test_datetime_mi" + read_ext + with pd.ExcelFile(f) as excel: + actual = pd.read_excel(excel, header=[0, 1], index_col=0, engine=engine) + + unit = get_exp_unit(read_ext, engine) + + dti = pd.DatetimeIndex(["2020-02-29", "2020-03-01"], dtype=f"M8[{unit}]") + expected_column_index = pd.MultiIndex.from_arrays( + [dti[:1], dti[1:]], + names=[ + dti[0].to_pydatetime(), + dti[1].to_pydatetime(), + ], + ) + expected = pd.DataFrame([], index=[], columns=expected_column_index) + + tm.assert_frame_equal(expected, actual) + + def test_engine_invalid_option(self, read_ext): + # read_ext includes the '.' hence the weird formatting + with pytest.raises(ValueError, match="Value must be one of *"): + with pd.option_context(f"io.excel{read_ext}.reader", "abc"): + pass + + def test_ignore_chartsheets(self, request, engine, read_ext): + # GH 41448 + if read_ext == ".ods": + pytest.skip("chartsheets do not exist in the ODF format") + if engine == "pyxlsb": + request.applymarker( + pytest.mark.xfail( + reason="pyxlsb can't distinguish chartsheets from worksheets" + ) + ) + with pd.ExcelFile("chartsheet" + read_ext) as excel: + assert excel.sheet_names == ["Sheet1"] + + def test_corrupt_files_closed(self, engine, tmp_excel): + # GH41778 + errors = (BadZipFile,) + if engine is None: + pytest.skip(f"Invalid test for engine={engine}") + elif engine == "xlrd": + import xlrd + + errors = (BadZipFile, xlrd.biffh.XLRDError) + elif engine == "calamine": + from python_calamine import CalamineError + + errors = (CalamineError,) + + Path(tmp_excel).write_text("corrupt", encoding="utf-8") + expected_warning = Pandas4Warning if engine in {"xlrd", "pyxlsb"} else False + msg = f"The {engine} engine is deprecated" + with tm.assert_produces_warning(expected_warning, match=msg): + try: + pd.ExcelFile(tmp_excel, engine=engine) + except errors: + pass + + +@td.skip_if_no("pyxlsb") +def test_pyxlsb_engine_deprecated(datapath): + # GH#56542 + path = datapath("io", "data", "excel", "test1.xlsb") + with tm.assert_produces_warning( + Pandas4Warning, match="pyxlsb engine is deprecated" + ): + pd.read_excel(path, engine="pyxlsb") + + +@pytest.mark.filterwarnings( + "ignore:The (xlrd|pyxlsb) engine is deprecated:pandas.errors.Pandas4Warning" +) +@pytest.mark.parametrize( + "engine, module_name, read_ext, load", + [ + ("xlrd", "xlrd", ".xls", lambda mod, path: mod.open_workbook(path)), + ("openpyxl", "openpyxl", ".xlsx", lambda mod, path: mod.load_workbook(path)), + ("odf", "odf.opendocument", ".ods", lambda mod, path: mod.load(path)), + ("pyxlsb", "pyxlsb", ".xlsb", lambda mod, path: mod.open_workbook(path)), + ( + "calamine", + "python_calamine", + ".xlsx", + lambda mod, path: mod.CalamineWorkbook.from_path(path), + ), + ], +) +def test_read_workbook_infers_engine(datapath, engine, module_name, read_ext, load): + # GH#46352 + module = pytest.importorskip(module_name) + path = datapath("io", "data", "excel", f"test1{read_ext}") + expected = pd.read_excel(path, engine=engine, index_col=0) + + with pd.ExcelFile(load(module, path)) as xl: + assert xl.engine == engine + result = pd.read_excel(load(module, path), index_col=0) + tm.assert_frame_equal(result, expected) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_style.py b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_style.py new file mode 100644 index 0000000000000000000000000000000000000000..b8ce216b510dcfa368495c64e6929205b992f238 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_style.py @@ -0,0 +1,350 @@ +import contextlib +import uuid + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + +from pandas.io.excel import ExcelWriter +from pandas.io.formats.excel import ExcelFormatter + +pytest.importorskip("jinja2") +# jinja2 is currently required for Styler.__init__(). Technically Styler.to_excel +# could compute styles and render to excel without jinja2, since there is no +# 'template' file, but this needs the import error to delayed until render time. + + +@pytest.fixture +def tmp_excel(tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}.xlsx" + tmp.touch() + return str(tmp) + + +def assert_equal_cell_styles(cell1, cell2): + # TODO: should find a better way to check equality + assert cell1.alignment.__dict__ == cell2.alignment.__dict__ + assert cell1.border.__dict__ == cell2.border.__dict__ + assert cell1.fill.__dict__ == cell2.fill.__dict__ + assert cell1.font.__dict__ == cell2.font.__dict__ + assert cell1.number_format == cell2.number_format + assert cell1.protection.__dict__ == cell2.protection.__dict__ + + +def test_styler_default_values(tmp_excel): + # GH 54154 + openpyxl = pytest.importorskip("openpyxl") + df = pd.DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 1, "B": 2, "C": 3}]) + + with ExcelWriter(tmp_excel, engine="openpyxl") as writer: + df.to_excel(writer, sheet_name="custom") + + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # Check font, spacing, indentation + assert wb["custom"].cell(1, 1).font.bold is False + assert wb["custom"].cell(1, 1).alignment.horizontal is None + assert wb["custom"].cell(1, 1).alignment.vertical is None + + # Check border + assert wb["custom"].cell(1, 1).border.bottom.color is None + assert wb["custom"].cell(1, 1).border.top.color is None + assert wb["custom"].cell(1, 1).border.left.color is None + assert wb["custom"].cell(1, 1).border.right.color is None + + +@pytest.mark.parametrize("engine", ["xlsxwriter", "openpyxl"]) +def test_styler_to_excel_unstyled(engine, tmp_excel): + # compare DataFrame.to_excel and Styler.to_excel when no styles applied + pytest.importorskip(engine) + df = pd.DataFrame(np.random.default_rng(2).standard_normal((2, 2))) + with ExcelWriter(tmp_excel, engine=engine) as writer: + df.to_excel(writer, sheet_name="dataframe") + df.style.to_excel(writer, sheet_name="unstyled") + + openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + for col1, col2 in zip( + wb["dataframe"].columns, + wb["unstyled"].columns, + strict=True, + ): + assert len(col1) == len(col2) + for cell1, cell2 in zip(col1, col2, strict=True): + assert cell1.value == cell2.value + assert_equal_cell_styles(cell1, cell2) + + +shared_style_params = [ + ( + "background-color: #111222", + ["fill", "fgColor", "rgb"], + {"xlsxwriter": "FF111222", "openpyxl": "00111222"}, + ), + ( + "color: #111222", + ["font", "color", "value"], + {"xlsxwriter": "FF111222", "openpyxl": "00111222"}, + ), + ("font-family: Arial;", ["font", "name"], "arial"), + ("font-weight: bold;", ["font", "b"], True), + ("font-style: italic;", ["font", "i"], True), + ("text-decoration: underline;", ["font", "u"], "single"), + ("number-format: $??,???.00;", ["number_format"], "$??,???.00"), + ("text-align: left;", ["alignment", "horizontal"], "left"), + ( + "vertical-align: bottom;", + ["alignment", "vertical"], + {"xlsxwriter": None, "openpyxl": "bottom"}, # xlsxwriter Fails + ), + ("vertical-align: middle;", ["alignment", "vertical"], "center"), + # Border widths + ("border-left: 2pt solid red", ["border", "left", "style"], "medium"), + ("border-left: 1pt dotted red", ["border", "left", "style"], "dotted"), + ("border-left: 2pt dotted red", ["border", "left", "style"], "mediumDashDotDot"), + ("border-left: 1pt dashed red", ["border", "left", "style"], "dashed"), + ("border-left: 2pt dashed red", ["border", "left", "style"], "mediumDashed"), + ("border-left: 1pt solid red", ["border", "left", "style"], "thin"), + ("border-left: 3pt solid red", ["border", "left", "style"], "thick"), + # Border expansion + ( + "border-left: 2pt solid #111222", + ["border", "left", "color", "rgb"], + {"xlsxwriter": "FF111222", "openpyxl": "00111222"}, + ), + ("border: 1pt solid red", ["border", "top", "style"], "thin"), + ( + "border: 1pt solid #111222", + ["border", "top", "color", "rgb"], + {"xlsxwriter": "FF111222", "openpyxl": "00111222"}, + ), + ("border: 1pt solid red", ["border", "right", "style"], "thin"), + ( + "border: 1pt solid #111222", + ["border", "right", "color", "rgb"], + {"xlsxwriter": "FF111222", "openpyxl": "00111222"}, + ), + ("border: 1pt solid red", ["border", "bottom", "style"], "thin"), + ( + "border: 1pt solid #111222", + ["border", "bottom", "color", "rgb"], + {"xlsxwriter": "FF111222", "openpyxl": "00111222"}, + ), + ("border: 1pt solid red", ["border", "left", "style"], "thin"), + ( + "border: 1pt solid #111222", + ["border", "left", "color", "rgb"], + {"xlsxwriter": "FF111222", "openpyxl": "00111222"}, + ), + # Border styles + ( + "border-left-style: hair; border-left-color: black", + ["border", "left", "style"], + "hair", + ), +] + + +def test_styler_custom_style(tmp_excel): + # GH 54154 + css_style = "background-color: #111222" + openpyxl = pytest.importorskip("openpyxl") + df = pd.DataFrame([{"A": 1, "B": 2}, {"A": 1, "B": 2}]) + + with ExcelWriter(tmp_excel, engine="openpyxl") as writer: + styler = df.style.map(lambda x: css_style) + styler.to_excel(writer, sheet_name="custom", index=False) + + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # Check font, spacing, indentation + assert wb["custom"].cell(1, 1).font.bold is False + assert wb["custom"].cell(1, 1).alignment.horizontal is None + assert wb["custom"].cell(1, 1).alignment.vertical is None + + # Check border + assert wb["custom"].cell(1, 1).border.bottom.color is None + assert wb["custom"].cell(1, 1).border.top.color is None + assert wb["custom"].cell(1, 1).border.left.color is None + assert wb["custom"].cell(1, 1).border.right.color is None + + # Check background color + assert wb["custom"].cell(2, 1).fill.fgColor.index == "00111222" + assert wb["custom"].cell(3, 1).fill.fgColor.index == "00111222" + assert wb["custom"].cell(2, 2).fill.fgColor.index == "00111222" + assert wb["custom"].cell(3, 2).fill.fgColor.index == "00111222" + + +@pytest.mark.parametrize("engine", ["xlsxwriter", "openpyxl"]) +@pytest.mark.parametrize("css, attrs, expected", shared_style_params) +def test_styler_to_excel_basic(engine, css, attrs, expected, tmp_excel): + pytest.importorskip(engine) + df = pd.DataFrame(np.random.default_rng(2).standard_normal((1, 1))) + styler = df.style.map(lambda x: css) + + with ExcelWriter(tmp_excel, engine=engine) as writer: + df.to_excel(writer, sheet_name="dataframe") + styler.to_excel(writer, sheet_name="styled") + + openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # test unstyled data cell does not have expected styles + # test styled cell has expected styles + u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) + for attr in attrs: + u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr) + + if isinstance(expected, dict): + assert u_cell is None or u_cell != expected[engine] + assert s_cell == expected[engine] + else: + assert u_cell is None or u_cell != expected + assert s_cell == expected + + +@pytest.mark.parametrize("engine", ["xlsxwriter", "openpyxl"]) +@pytest.mark.parametrize("css, attrs, expected", shared_style_params) +def test_styler_to_excel_basic_indexes(engine, css, attrs, expected, tmp_excel): + pytest.importorskip(engine) + df = pd.DataFrame(np.random.default_rng(2).standard_normal((1, 1))) + + styler = df.style + styler.map_index(lambda x: css, axis=0) + styler.map_index(lambda x: css, axis=1) + + null_styler = df.style + null_styler.map(lambda x: "null: css;") + null_styler.map_index(lambda x: "null: css;", axis=0) + null_styler.map_index(lambda x: "null: css;", axis=1) + + with ExcelWriter(tmp_excel, engine=engine) as writer: + null_styler.to_excel(writer, sheet_name="null_styled") + styler.to_excel(writer, sheet_name="styled") + + openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # test null styled index cells does not have expected styles + # test styled cell has expected styles + ui_cell, si_cell = wb["null_styled"].cell(2, 1), wb["styled"].cell(2, 1) + uc_cell, sc_cell = wb["null_styled"].cell(1, 2), wb["styled"].cell(1, 2) + for attr in attrs: + ui_cell, si_cell = getattr(ui_cell, attr, None), getattr(si_cell, attr) + uc_cell, sc_cell = getattr(uc_cell, attr, None), getattr(sc_cell, attr) + + if isinstance(expected, dict): + assert ui_cell is None or ui_cell != expected[engine] + assert si_cell == expected[engine] + assert uc_cell is None or uc_cell != expected[engine] + assert sc_cell == expected[engine] + else: + assert ui_cell is None or ui_cell != expected + assert si_cell == expected + assert uc_cell is None or uc_cell != expected + assert sc_cell == expected + + +# From https://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles.borders.html +# Note: Leaving behavior of "width"-type styles undefined; user should use border-width +# instead +excel_border_styles = [ + # "thin", + "dashed", + "mediumDashDot", + "dashDotDot", + "hair", + "dotted", + "mediumDashDotDot", + # "medium", + "double", + "dashDot", + "slantDashDot", + # "thick", + "mediumDashed", +] + + +@pytest.mark.parametrize("engine", ["xlsxwriter", "openpyxl"]) +@pytest.mark.parametrize("border_style", excel_border_styles) +def test_styler_to_excel_border_style(engine, border_style, tmp_excel): + css = f"border-left: {border_style} black thin" + attrs = ["border", "left", "style"] + expected = border_style + + pytest.importorskip(engine) + df = pd.DataFrame(np.random.default_rng(2).standard_normal((1, 1))) + styler = df.style.map(lambda x: css) + + with ExcelWriter(tmp_excel, engine=engine) as writer: + df.to_excel(writer, sheet_name="dataframe") + styler.to_excel(writer, sheet_name="styled") + + openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # test unstyled data cell does not have expected styles + # test styled cell has expected styles + u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) + for attr in attrs: + u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr) + + if isinstance(expected, dict): + assert u_cell is None or u_cell != expected[engine] + assert s_cell == expected[engine] + else: + assert u_cell is None or u_cell != expected + assert s_cell == expected + + +def test_styler_custom_converter(tmp_excel): + openpyxl = pytest.importorskip("openpyxl") + + def custom_converter(css): + return {"font": {"color": {"rgb": "111222"}}} + + df = pd.DataFrame(np.random.default_rng(2).standard_normal((1, 1))) + styler = df.style.map(lambda x: "color: #888999") + with ExcelWriter(tmp_excel, engine="openpyxl") as writer: + ExcelFormatter(styler, style_converter=custom_converter).write( + writer, sheet_name="custom" + ) + + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + assert wb["custom"].cell(2, 2).font.color.value == "00111222" + + +@pytest.mark.single_cpu +@pytest.mark.filterwarnings( + "ignore:The default engine for reading:pandas.errors.Pandas4Warning" +) +def test_styler_to_s3(s3_bucket_public, s3so): + # GH#46381 + mock_bucket_name = s3_bucket_public.name + target_file = f"{uuid.uuid4()}.xlsx" + df = pd.DataFrame({"x": [1, 2, 3], "y": [2, 4, 6]}) + styler = df.style.set_sticky(axis="index") + uri = f"s3://{mock_bucket_name}/{target_file}" + styler.to_excel(uri, storage_options=s3so) + result = pd.read_excel(uri, index_col=0, storage_options=s3so) + tm.assert_frame_equal(result, df) + + +@pytest.mark.parametrize("merge_cells", [True, False, "columns"]) +def test_format_hierarchical_rows_periodindex(merge_cells): + # GH#60099 + df = pd.DataFrame( + {"A": [1, 2]}, + index=pd.MultiIndex.from_arrays( + [ + pd.period_range(start="2006-10-06", end="2006-10-07", freq="D"), + ["X", "Y"], + ], + names=["date", "category"], + ), + ) + formatter = ExcelFormatter(df, merge_cells=merge_cells) + formatted_cells = formatter._format_hierarchical_rows() + + for cell in formatted_cells: + if cell.row != 0 and cell.col == 0: + assert isinstance(cell.val, pd.Timestamp), ( + "Period should be converted to Timestamp" + ) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_writers.py b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_writers.py new file mode 100644 index 0000000000000000000000000000000000000000..3543c9d4b7693797258796761c80abffc110e5ff --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_writers.py @@ -0,0 +1,1780 @@ +import contextlib +from datetime import ( + date, + datetime, + timedelta, +) +from decimal import Decimal +from functools import partial +from io import BytesIO +import os +import pathlib +import re +import uuid + +import numpy as np +import pytest + +from pandas.compat._optional import import_optional_dependency +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + +from pandas.io.excel import ( + ExcelFile, + ExcelWriter, + _OpenpyxlWriter, + _XlsxWriter, + register_writer, +) +from pandas.io.excel._util import _writers + +# Roundtrip tests read xlsx/xlsm back with the default engine; the pending +# calamine-default change (GH#56542) is not what these tests exercise. +pytestmark = pytest.mark.filterwarnings( + "ignore:The default engine for reading:pandas.errors.Pandas4Warning" +) + + +def get_exp_unit(path: str) -> str: + return "us" + + +@pytest.fixture +def frame(float_frame): + """ + Returns the first ten items in fixture "float_frame". + """ + return float_frame[:10] + + +@pytest.fixture(params=[True, False, "columns"]) +def merge_cells(request): + return request.param + + +@pytest.fixture +def tmp_excel(ext, tmp_path): + """ + Fixture to open file for use in each test case. + """ + tmp = tmp_path / f"{uuid.uuid4()}{ext}" + tmp.touch() + return str(tmp) + + +@pytest.fixture +def set_engine(engine, ext): + """ + Fixture to set engine for use in each test case. + + Rather than requiring `engine=...` to be provided explicitly as an + argument in each test, this fixture sets a global option to dictate + which engine should be used to write Excel files. After executing + the test it rolls back said change to the global option. + """ + option_name = f"io.excel.{ext.strip('.')}.writer" + with pd.option_context(option_name, engine): + yield + + +@pytest.mark.parametrize( + "ext", + [ + pytest.param(".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]), + pytest.param(".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]), + pytest.param( + ".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")] + ), + pytest.param(".ods", marks=td.skip_if_no("odf")), + ], +) +class TestRoundTrip: + @pytest.mark.parametrize( + "header,expected", + [(None, [np.nan] * 4), (0, {"Unnamed: 0": [np.nan] * 3})], + ) + def test_read_one_empty_col_no_header(self, tmp_excel, header, expected): + # xref gh-12292 + filename = "no_header" + df = pd.DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) + + df.to_excel(tmp_excel, sheet_name=filename, index=False, header=False) + result = pd.read_excel( + tmp_excel, sheet_name=filename, usecols=[0], header=header + ) + expected = pd.DataFrame(expected) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "header,expected_extra", + [(None, [0]), (0, [])], + ) + def test_read_one_empty_col_with_header(self, tmp_excel, header, expected_extra): + filename = "with_header" + df = pd.DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) + + df.to_excel(tmp_excel, sheet_name="with_header", index=False, header=True) + result = pd.read_excel( + tmp_excel, sheet_name=filename, usecols=[0], header=header + ) + expected = pd.DataFrame(expected_extra + [np.nan] * 4) + tm.assert_frame_equal(result, expected) + + def test_set_column_names_in_parameter(self, tmp_excel): + # GH 12870 : pass down column names associated with + # keyword argument names + refdf = pd.DataFrame([[1, "foo"], [2, "bar"], [3, "baz"]], columns=["a", "b"]) + + with ExcelWriter(tmp_excel) as writer: + refdf.to_excel(writer, sheet_name="Data_no_head", header=False, index=False) + refdf.to_excel(writer, sheet_name="Data_with_head", index=False) + + refdf.columns = ["A", "B"] + + with ExcelFile(tmp_excel) as reader: + xlsdf_no_head = pd.read_excel( + reader, sheet_name="Data_no_head", header=None, names=["A", "B"] + ) + xlsdf_with_head = pd.read_excel( + reader, + sheet_name="Data_with_head", + index_col=None, + names=["A", "B"], + ) + + tm.assert_frame_equal(xlsdf_no_head, refdf) + tm.assert_frame_equal(xlsdf_with_head, refdf) + + def test_creating_and_reading_multiple_sheets(self, tmp_excel): + # see gh-9450 + # + # Test reading multiple sheets, from a runtime + # created Excel file with multiple sheets. + def tdf(col_sheet_name): + d, i = [11, 22, 33], [1, 2, 3] + return pd.DataFrame(d, i, columns=[col_sheet_name]) + + sheets = ["AAA", "BBB", "CCC"] + + dfs = [tdf(s) for s in sheets] + dfs = dict(zip(sheets, dfs, strict=True)) + + with ExcelWriter(tmp_excel) as ew: + for sheetname, df in dfs.items(): + df.to_excel(ew, sheet_name=sheetname) + + dfs_returned = pd.read_excel(tmp_excel, sheet_name=sheets, index_col=0) + + for s in sheets: + tm.assert_frame_equal(dfs[s], dfs_returned[s]) + + def test_read_excel_multiindex_empty_level(self, tmp_excel): + # see gh-12453 + df = pd.DataFrame( + { + ("One", "x"): {0: 1}, + ("Two", "X"): {0: 3}, + ("Two", "Y"): {0: 7}, + ("Zero", ""): {0: 0}, + } + ) + + expected = pd.DataFrame( + { + ("One", "x"): {0: 1}, + ("Two", "X"): {0: 3}, + ("Two", "Y"): {0: 7}, + ("Zero", "Unnamed: 4_level_1"): {0: 0}, + } + ) + + df.to_excel(tmp_excel) + actual = pd.read_excel(tmp_excel, header=[0, 1], index_col=0) + tm.assert_frame_equal(actual, expected) + + df = pd.DataFrame( + { + ("Beg", ""): {0: 0}, + ("Middle", "x"): {0: 1}, + ("Tail", "X"): {0: 3}, + ("Tail", "Y"): {0: 7}, + } + ) + + expected = pd.DataFrame( + { + ("Beg", "Unnamed: 1_level_1"): {0: 0}, + ("Middle", "x"): {0: 1}, + ("Tail", "X"): {0: 3}, + ("Tail", "Y"): {0: 7}, + } + ) + + df.to_excel(tmp_excel) + actual = pd.read_excel(tmp_excel, header=[0, 1], index_col=0) + tm.assert_frame_equal(actual, expected) + + @pytest.mark.parametrize("c_idx_names", ["a", None]) + @pytest.mark.parametrize("r_idx_names", ["b", None]) + @pytest.mark.parametrize("c_idx_levels", [1, 3]) + @pytest.mark.parametrize("r_idx_levels", [1, 3]) + def test_excel_multindex_roundtrip( + self, + tmp_excel, + c_idx_names, + r_idx_names, + c_idx_levels, + r_idx_levels, + ): + # see gh-4679 + # Empty name case current read in as + # unnamed levels, not Nones. + check_names = bool(r_idx_names) or r_idx_levels <= 1 + + if c_idx_levels == 1: + columns = pd.Index(list("abcde")) + else: + columns = pd.MultiIndex.from_arrays( + [range(5) for _ in range(c_idx_levels)], + names=[f"{c_idx_names}-{i}" for i in range(c_idx_levels)], + ) + if r_idx_levels == 1: + index = pd.Index(list("ghijk")) + else: + index = pd.MultiIndex.from_arrays( + [range(5) for _ in range(r_idx_levels)], + names=[f"{r_idx_names}-{i}" for i in range(r_idx_levels)], + ) + df = pd.DataFrame( + 1.1 * np.ones((5, 5)), + columns=columns, + index=index, + ) + df.to_excel(tmp_excel) + + act = pd.read_excel( + tmp_excel, + index_col=list(range(r_idx_levels)), + header=list(range(c_idx_levels)), + ) + tm.assert_frame_equal(df, act, check_names=check_names) + + df.iloc[0, :] = np.nan + df.to_excel(tmp_excel) + + act = pd.read_excel( + tmp_excel, + index_col=list(range(r_idx_levels)), + header=list(range(c_idx_levels)), + ) + tm.assert_frame_equal(df, act, check_names=check_names) + + df.iloc[-1, :] = np.nan + df.to_excel(tmp_excel) + act = pd.read_excel( + tmp_excel, + index_col=list(range(r_idx_levels)), + header=list(range(c_idx_levels)), + ) + tm.assert_frame_equal(df, act, check_names=check_names) + + def test_read_excel_parse_dates(self, tmp_excel): + # see gh-11544, gh-12051 + df = pd.DataFrame( + {"col": [1, 2, 3], "date_strings": pd.date_range("2012-01-01", periods=3)} + ) + df2 = df.copy() + df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y") + + df2.to_excel(tmp_excel) + + res = pd.read_excel(tmp_excel, index_col=0) + tm.assert_frame_equal(df2, res) + + res = pd.read_excel(tmp_excel, parse_dates=["date_strings"], index_col=0) + expected = df[:] + expected["date_strings"] = expected["date_strings"].astype("M8[us]") + tm.assert_frame_equal(res, expected) + + res = pd.read_excel( + tmp_excel, parse_dates=["date_strings"], date_format="%m/%d/%Y", index_col=0 + ) + expected["date_strings"] = expected["date_strings"].astype("M8[us]") + tm.assert_frame_equal(expected, res) + + def test_multiindex_interval_datetimes(self, tmp_excel): + # GH 30986 + midx = pd.MultiIndex.from_arrays( + [ + range(4), + pd.interval_range( + start=pd.Timestamp("2020-01-01"), periods=4, freq="6ME" + ), + ] + ) + df = pd.DataFrame(range(4), index=midx) + df.to_excel(tmp_excel) + result = pd.read_excel(tmp_excel, index_col=[0, 1]) + expected = pd.DataFrame( + range(4), + pd.MultiIndex.from_arrays( + [ + range(4), + [ + "(2020-01-31 00:00:00, 2020-07-31 00:00:00]", + "(2020-07-31 00:00:00, 2021-01-31 00:00:00]", + "(2021-01-31 00:00:00, 2021-07-31 00:00:00]", + "(2021-07-31 00:00:00, 2022-01-31 00:00:00]", + ], + ] + ), + columns=pd.Index([0]), + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("merge_cells", [True, False, "columns"]) + def test_excel_round_trip_with_periodindex(self, tmp_excel, merge_cells): + # GH#60099 + df = pd.DataFrame( + {"A": [1, 2]}, + index=pd.MultiIndex.from_arrays( + [ + pd.period_range(start="2006-10-06", end="2006-10-07", freq="D"), + ["X", "Y"], + ], + names=["date", "category"], + ), + ) + df.to_excel(tmp_excel, merge_cells=merge_cells) + result = pd.read_excel(tmp_excel, index_col=[0, 1]) + expected = pd.DataFrame( + {"A": [1, 2]}, + pd.MultiIndex.from_arrays( + [ + [ + pd.to_datetime("2006-10-06 00:00:00").as_unit("s"), + pd.to_datetime("2006-10-07 00:00:00").as_unit("s"), + ], + ["X", "Y"], + ], + names=["date", "category"], + ), + ) + time_format = "datetime64[us]" + expected.index = expected.index.set_levels( + expected.index.levels[0].astype(time_format), level=0 + ) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "engine,ext", + [ + pytest.param( + "openpyxl", + ".xlsx", + marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")], + ), + pytest.param( + "openpyxl", + ".xlsm", + marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")], + ), + pytest.param( + "xlsxwriter", + ".xlsx", + marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")], + ), + pytest.param("odf", ".ods", marks=td.skip_if_no("odf")), + ], +) +@pytest.mark.usefixtures("set_engine") +class TestExcelWriter: + def test_excel_sheet_size(self, tmp_excel): + # GH 26080 + breaking_row_count = 2**20 + 1 + breaking_col_count = 2**14 + 1 + # purposely using two arrays to prevent memory issues while testing + row_arr = np.zeros(shape=(breaking_row_count, 1)) + col_arr = np.zeros(shape=(1, breaking_col_count)) + row_df = pd.DataFrame(row_arr) + col_df = pd.DataFrame(col_arr) + + msg = "sheet is too large" + with pytest.raises(ValueError, match=msg): + row_df.to_excel(tmp_excel) + + with pytest.raises(ValueError, match=msg): + col_df.to_excel(tmp_excel) + + def test_excel_sheet_by_name_raise(self, tmp_excel): + gt = pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 2)), + index=pd.Index(list(range(10))), + ) + gt.to_excel(tmp_excel) + + with ExcelFile(tmp_excel) as xl: + df = pd.read_excel(xl, sheet_name=0, index_col=0) + + tm.assert_frame_equal(gt, df) + + msg = "Worksheet named '0' not found" + with pytest.raises(ValueError, match=msg): + pd.read_excel(xl, "0") + + def test_excel_writer_context_manager(self, frame, tmp_excel): + with ExcelWriter(tmp_excel) as writer: + frame.to_excel(writer, sheet_name="Data1") + frame2 = frame.copy() + frame2.columns = frame.columns[::-1] + frame2.to_excel(writer, sheet_name="Data2") + + with ExcelFile(tmp_excel) as reader: + found_df = pd.read_excel(reader, sheet_name="Data1", index_col=0) + found_df2 = pd.read_excel(reader, sheet_name="Data2", index_col=0) + + tm.assert_frame_equal(found_df, frame) + tm.assert_frame_equal(found_df2, frame2) + + def test_roundtrip(self, frame, tmp_excel): + frame = frame.copy() + frame.iloc[:5, frame.columns.get_loc("A")] = np.nan + + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) + + # test roundtrip + frame.to_excel(tmp_excel, sheet_name="test1") + recons = pd.read_excel(tmp_excel, sheet_name="test1", index_col=0) + tm.assert_frame_equal(frame, recons) + + frame.to_excel(tmp_excel, sheet_name="test1", index=False) + recons = pd.read_excel(tmp_excel, sheet_name="test1", index_col=None) + recons.index = frame.index + tm.assert_frame_equal(frame, recons) + + frame.to_excel(tmp_excel, sheet_name="test1", na_rep="NA") + recons = pd.read_excel( + tmp_excel, sheet_name="test1", index_col=0, na_values=["NA"] + ) + tm.assert_frame_equal(frame, recons) + + # GH 3611 + frame.to_excel(tmp_excel, sheet_name="test1", na_rep="88") + recons = pd.read_excel( + tmp_excel, sheet_name="test1", index_col=0, na_values=["88"] + ) + tm.assert_frame_equal(frame, recons) + + frame.to_excel(tmp_excel, sheet_name="test1", na_rep="88") + recons = pd.read_excel( + tmp_excel, sheet_name="test1", index_col=0, na_values=[88, 88.0] + ) + tm.assert_frame_equal(frame, recons) + + # GH 6573 + frame.to_excel(tmp_excel, sheet_name="Sheet1") + recons = pd.read_excel(tmp_excel, index_col=0) + tm.assert_frame_equal(frame, recons) + + frame.to_excel(tmp_excel, sheet_name="0") + recons = pd.read_excel(tmp_excel, index_col=0) + tm.assert_frame_equal(frame, recons) + + # GH 8825 Pandas Series should provide to_excel method + s = frame["A"] + s.to_excel(tmp_excel) + recons = pd.read_excel(tmp_excel, index_col=0) + tm.assert_frame_equal(s.to_frame(), recons) + + def test_mixed(self, frame, tmp_excel): + mixed_frame = frame.copy() + mixed_frame["foo"] = "bar" + + mixed_frame.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0) + tm.assert_frame_equal(mixed_frame, recons) + + def test_ts_frame(self, tmp_excel): + unit = get_exp_unit(tmp_excel) + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=pd.Index(list("ABCD")), + index=pd.date_range("2000-01-01", periods=5, freq="B"), + ) + + # freq doesn't round-trip + index = pd.DatetimeIndex(np.asarray(df.index), freq=None) + df.index = index + + expected = df[:] + expected.index = expected.index.as_unit(unit) + + df.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0) + tm.assert_frame_equal(expected, recons) + + def test_basics_with_nan(self, frame, tmp_excel): + frame = frame.copy() + frame.iloc[:5, frame.columns.get_loc("A")] = np.nan + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) + + @pytest.mark.parametrize("np_type", [np.int8, np.int16, np.int32, np.int64]) + def test_int_types(self, np_type, tmp_excel): + # Test np.int values read come back as int + # (rather than float which is Excel's format). + df = pd.DataFrame( + np.random.default_rng(2).integers(-10, 10, size=(10, 2)), + dtype=np_type, + index=pd.Index(list(range(10))), + ) + df.to_excel(tmp_excel, sheet_name="test1") + + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0) + + int_frame = df.astype(np.int64) + tm.assert_frame_equal(int_frame, recons) + + recons2 = pd.read_excel(tmp_excel, sheet_name="test1", index_col=0) + tm.assert_frame_equal(int_frame, recons2) + + @pytest.mark.parametrize("np_type", [np.float16, np.float32, np.float64]) + def test_float_types(self, np_type, tmp_excel): + # Test np.float values read come back as float. + df = pd.DataFrame( + np.random.default_rng(2).random(10), + dtype=np_type, + index=pd.Index(list(range(10))), + ) + df.to_excel(tmp_excel, sheet_name="test1") + + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( + np_type + ) + + tm.assert_frame_equal(df, recons) + + def test_bool_types(self, tmp_excel): + # Test np.bool_ values read come back as float. + df = pd.DataFrame( + [1, 0, True, False], dtype=np.bool_, index=pd.Index(list(range(4))) + ) + df.to_excel(tmp_excel, sheet_name="test1") + + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( + np.bool_ + ) + + tm.assert_frame_equal(df, recons) + + def test_inf_roundtrip(self, tmp_excel): + df = pd.DataFrame( + [(1, np.inf), (2, 3), (5, -np.inf)], index=pd.Index(list(range(3))) + ) + df.to_excel(tmp_excel, sheet_name="test1") + + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0) + + tm.assert_frame_equal(df, recons) + + def test_sheets(self, frame, tmp_excel): + # freq doesn't round-trip + unit = get_exp_unit(tmp_excel) + tsframe = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=pd.Index(list("ABCD")), + index=pd.date_range("2000-01-01", periods=5, freq="B"), + ) + + index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) + tsframe.index = index + + expected = tsframe[:] + expected.index = expected.index.as_unit(unit) + + frame = frame.copy() + frame.iloc[:5, frame.columns.get_loc("A")] = np.nan + + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) + + # Test writing to separate sheets + with ExcelWriter(tmp_excel) as writer: + frame.to_excel(writer, sheet_name="test1") + tsframe.to_excel(writer, sheet_name="test2") + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0) + tm.assert_frame_equal(frame, recons) + recons = pd.read_excel(reader, sheet_name="test2", index_col=0) + tm.assert_frame_equal(expected, recons) + assert 2 == len(reader.sheet_names) + assert "test1" == reader.sheet_names[0] + assert "test2" == reader.sheet_names[1] + + def test_colaliases(self, frame, tmp_excel): + frame = frame.copy() + frame.iloc[:5, frame.columns.get_loc("A")] = np.nan + + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) + + # column aliases + col_aliases = pd.Index(["AA", "X", "Y", "Z"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=col_aliases) + with ExcelFile(tmp_excel) as reader: + rs = pd.read_excel(reader, sheet_name="test1", index_col=0) + xp = frame.copy() + xp.columns = col_aliases + tm.assert_frame_equal(xp, rs) + + def test_roundtrip_indexlabels(self, merge_cells, frame, tmp_excel): + frame = frame.copy() + frame.iloc[:5, frame.columns.get_loc("A")] = np.nan + + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) + + # test index_label + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0 + df.to_excel( + tmp_excel, sheet_name="test1", index_label=["test"], merge_cells=merge_cells + ) + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( + np.int64 + ) + df.index.names = ["test"] + assert df.index.names == recons.index.names + + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0 + df.to_excel( + tmp_excel, + sheet_name="test1", + index_label=["test", "dummy", "dummy2"], + merge_cells=merge_cells, + ) + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( + np.int64 + ) + df.index.names = ["test"] + assert df.index.names == recons.index.names + + df = ( + pd.DataFrame( + np.random.default_rng(2).standard_normal((10, 2)), + index=pd.Index(list(range(10))), + ) + >= 0 + ) + df.to_excel( + tmp_excel, sheet_name="test1", index_label="test", merge_cells=merge_cells + ) + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( + np.int64 + ) + df.index.names = ["test"] + tm.assert_frame_equal(df, recons.astype(bool)) + + frame.to_excel( + tmp_excel, + sheet_name="test1", + columns=["A", "B", "C", "D"], + index=False, + merge_cells=merge_cells, + ) + # take 'A' and 'B' as indexes (same row as cols 'C', 'D') + df = frame.copy() + df = df.set_index(["A", "B"]) + + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) + tm.assert_frame_equal(df, recons) + + def test_excel_roundtrip_indexname(self, merge_cells, tmp_excel): + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 4))) + df.index.name = "foo" + + df.to_excel(tmp_excel, merge_cells=merge_cells) + + with ExcelFile(tmp_excel) as xf: + result = pd.read_excel(xf, sheet_name=xf.sheet_names[0], index_col=0) + + tm.assert_frame_equal(result, df) + assert result.index.name == "foo" + + def test_excel_roundtrip_datetime(self, merge_cells, tmp_excel): + # datetime.date, not sure what to test here exactly + unit = get_exp_unit(tmp_excel) + + # freq does not round-trip + tsframe = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=pd.Index(list("ABCD")), + index=pd.date_range("2000-01-01", periods=5, freq="B"), + ) + index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) + tsframe.index = index + + tsf = tsframe.copy() + + tsf.index = [x.date() for x in tsframe.index] + tsf.to_excel(tmp_excel, sheet_name="test1", merge_cells=merge_cells) + + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0) + + expected = tsframe[:] + expected.index = expected.index.as_unit(unit) + tm.assert_frame_equal(expected, recons) + + def test_excel_date_datetime_format(self, ext, tmp_excel, tmp_path): + # see gh-4133 + # + # Excel output format strings + unit = get_exp_unit(tmp_excel) + df = pd.DataFrame( + [ + [date(2014, 1, 31), date(1999, 9, 24)], + [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)], + ], + index=["DATE", "DATETIME"], + columns=["X", "Y"], + ) + df_expected = pd.DataFrame( + [ + [datetime(2014, 1, 31), datetime(1999, 9, 24)], + [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)], + ], + index=["DATE", "DATETIME"], + columns=["X", "Y"], + ) + df_expected = df_expected.astype(f"M8[{unit}]") + + filename2 = tmp_path / f"tmp2{ext}" + filename2.touch() + with ExcelWriter(tmp_excel) as writer1: + df.to_excel(writer1, sheet_name="test1") + + with ExcelWriter( + filename2, + date_format="DD.MM.YYYY", + datetime_format="DD.MM.YYYY HH-MM-SS", + ) as writer2: + df.to_excel(writer2, sheet_name="test1") + + with ExcelFile(tmp_excel) as reader1: + rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0) + + with ExcelFile(filename2) as reader2: + rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0) + + # TODO: why do we get different units? + rs2 = rs2.astype(f"M8[{unit}]") + + tm.assert_frame_equal(rs1, rs2) + + # Since the reader returns a datetime object for dates, + # we need to use df_expected to check the result. + tm.assert_frame_equal(rs2, df_expected) + + def test_to_excel_interval_no_labels(self, tmp_excel, using_infer_string): + # see gh-19242 + # + # Test writing Interval without labels. + df = pd.DataFrame( + np.random.default_rng(2).integers(-10, 10, size=(20, 1)), dtype=np.int64 + ) + expected = df.copy() + + df["new"] = pd.cut(df[0], 10) + expected["new"] = pd.cut(expected[0], 10).astype( + str if not using_infer_string else "str" + ) + + df.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0) + tm.assert_frame_equal(expected, recons) + + def test_to_excel_interval_labels(self, tmp_excel): + # see gh-19242 + # + # Test writing Interval with labels. + df = pd.DataFrame( + np.random.default_rng(2).integers(-10, 10, size=(20, 1)), dtype=np.int64 + ) + expected = df.copy() + intervals = pd.cut( + df[0], 10, labels=["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] + ) + df["new"] = intervals + expected["new"] = pd.Series(list(intervals)) + + df.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0) + tm.assert_frame_equal(expected, recons) + + def test_to_excel_timedelta(self, tmp_excel): + # see gh-19242, gh-9155 + # + # Test writing timedelta to xls. + df = pd.DataFrame( + np.random.default_rng(2).integers(-10, 10, size=(20, 1)), + columns=["A"], + dtype=np.int64, + ) + expected = df.copy() + + df["new"] = df["A"].apply(lambda x: timedelta(seconds=x)) + expected["new"] = expected["A"].apply( + lambda x: timedelta(seconds=x).total_seconds() / 86400 + ) + + df.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=0) + tm.assert_frame_equal(expected, recons) + + def test_to_excel_periodindex(self, tmp_excel): + # xp has a PeriodIndex + df = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=pd.Index(list("ABCD")), + index=pd.date_range("2000-01-01", periods=5, freq="B"), + ) + xp = df.resample("ME").mean().to_period("M") + + xp.to_excel(tmp_excel, sheet_name="sht1") + + with ExcelFile(tmp_excel) as reader: + rs = pd.read_excel(reader, sheet_name="sht1", index_col=0) + tm.assert_frame_equal(xp, rs.to_period("M")) + + def test_to_excel_multiindex(self, merge_cells, frame, tmp_excel): + arrays = np.arange(len(frame.index) * 2, dtype=np.int64).reshape(2, -1) + new_index = pd.MultiIndex.from_arrays(arrays, names=["first", "second"]) + frame.index = new_index + + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + + # round trip + frame.to_excel(tmp_excel, sheet_name="test1", merge_cells=merge_cells) + with ExcelFile(tmp_excel) as reader: + df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) + tm.assert_frame_equal(frame, df) + + # GH13511 + def test_to_excel_multiindex_nan_label(self, merge_cells, tmp_excel): + df = pd.DataFrame( + { + "A": [None, 2, 3], + "B": [10, 20, 30], + "C": np.random.default_rng(2).random(3), + } + ) + df = df.set_index(["A", "B"]) + + df.to_excel(tmp_excel, merge_cells=merge_cells) + df1 = pd.read_excel(tmp_excel, index_col=[0, 1]) + tm.assert_frame_equal(df, df1) + + # Test for Issue 11328. If column indices are integers, make + # sure they are handled correctly for either setting of + # merge_cells + def test_to_excel_multiindex_cols(self, merge_cells, tmp_excel): + # GH#11328 + frame = pd.DataFrame( + { + "A": [1, 2, 3], + "B": [4, 5, 6], + "C": [7, 8, 9], + } + ) + arrays = np.arange(len(frame.index) * 2, dtype=np.int64).reshape(2, -1) + new_index = pd.MultiIndex.from_arrays(arrays, names=["first", "second"]) + frame.index = new_index + + new_cols_index = pd.MultiIndex.from_tuples([(40, 1), (40, 2), (50, 1)]) + frame.columns = new_cols_index + frame.to_excel(tmp_excel, sheet_name="test1", merge_cells=merge_cells) + + # Check round trip + with ExcelFile(tmp_excel) as reader: + result = pd.read_excel( + reader, sheet_name="test1", header=[0, 1], index_col=[0, 1] + ) + tm.assert_frame_equal(result, frame) + + # GH#60274 + # Check with header/index_col None to determine which cells were merged + with ExcelFile(tmp_excel) as reader: + result = pd.read_excel( + reader, sheet_name="test1", header=None, index_col=None + ) + expected = pd.DataFrame( + { + 0: [np.nan, np.nan, "first", 0, 1, 2], + 1: [np.nan, np.nan, "second", 3, 4, 5], + 2: [40.0, 1.0, np.nan, 1.0, 2.0, 3.0], + 3: [np.nan, 2.0, np.nan, 4.0, 5.0, 6.0], + 4: [50.0, 1.0, np.nan, 7.0, 8.0, 9.0], + } + ) + if not merge_cells: + # MultiIndex column value is repeated + expected.loc[0, 3] = 40.0 + tm.assert_frame_equal(result, expected) + + def test_to_excel_multiindex_dates(self, merge_cells, tmp_excel): + # try multiindex with dates + unit = get_exp_unit(tmp_excel) + tsframe = pd.DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=pd.Index(list("ABCD")), + index=pd.date_range("2000-01-01", periods=5, freq="B"), + ) + tsframe.index = pd.MultiIndex.from_arrays( + [ + tsframe.index.as_unit(unit), + np.arange(len(tsframe.index), dtype=np.int64), + ], + names=["time", "foo"], + ) + + tsframe.to_excel(tmp_excel, sheet_name="test1", merge_cells=merge_cells) + with ExcelFile(tmp_excel) as reader: + recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) + + tm.assert_frame_equal(tsframe, recons, check_freq=False) + assert recons.index.names == ("time", "foo") + + def test_to_excel_multiindex_no_write_index(self, tmp_excel): + # Test writing and re-reading a MI without the index. GH 5616. + + # Initial non-MI frame. + frame1 = pd.DataFrame({"a": [10, 20], "b": [30, 40], "c": [50, 60]}) + + # Add a MI. + frame2 = frame1.copy() + multi_index = pd.MultiIndex.from_tuples([(70, 80), (90, 100)]) + frame2.index = multi_index + + # Write out to Excel without the index. + frame2.to_excel(tmp_excel, sheet_name="test1", index=False) + + # Read it back in. + with ExcelFile(tmp_excel) as reader: + frame3 = pd.read_excel(reader, sheet_name="test1") + + # Test that it is the same as the initial frame. + tm.assert_frame_equal(frame1, frame3) + + def test_to_excel_empty_multiindex(self, tmp_excel): + # GH 19543. + expected = pd.DataFrame([], columns=[0, 1, 2]) + + df = pd.DataFrame( + [], index=pd.MultiIndex.from_tuples([], names=[0, 1]), columns=[2] + ) + df.to_excel(tmp_excel, sheet_name="test1") + + with ExcelFile(tmp_excel) as reader: + result = pd.read_excel(reader, sheet_name="test1") + tm.assert_frame_equal( + result, expected, check_index_type=False, check_dtype=False + ) + + def test_to_excel_empty_multiindex_both_axes(self, tmp_excel): + # GH 57696 + df = pd.DataFrame( + [], + index=pd.MultiIndex.from_tuples([], names=[0, 1]), + columns=pd.MultiIndex.from_tuples([("A", "B")]), + ) + df.to_excel(tmp_excel) + result = pd.read_excel(tmp_excel, header=[0, 1], index_col=[0, 1]) + tm.assert_frame_equal(result, df) + + def test_to_excel_float_format(self, tmp_excel): + df = pd.DataFrame( + [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + df.to_excel(tmp_excel, sheet_name="test1", float_format="%.2f") + + with ExcelFile(tmp_excel) as reader: + result = pd.read_excel(reader, sheet_name="test1", index_col=0) + + expected = pd.DataFrame( + [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + tm.assert_frame_equal(result, expected) + + def test_to_excel_datatypes_preserved(self, tmp_excel): + # Test that when writing and reading Excel with dtype=object, + # datatypes are preserved, except Decimals which should be + # stored as floats + + # see gh-49598 + df = pd.DataFrame( + [ + [1.23, "1.23", Decimal("1.23")], + [4.56, "4.56", Decimal("4.56")], + ], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + df.to_excel(tmp_excel) + + with ExcelFile(tmp_excel) as reader: + result = pd.read_excel(reader, index_col=0, dtype=object) + + expected = pd.DataFrame( + [ + [1.23, "1.23", 1.23], + [4.56, "4.56", 4.56], + ], + index=["A", "B"], + columns=["X", "Y", "Z"], + dtype=object, + ) + tm.assert_frame_equal(result, expected) + + def test_to_excel_output_encoding(self, tmp_excel): + # Avoid mixed inferred_type. + df = pd.DataFrame( + [["\u0192", "\u0193", "\u0194"], ["\u0195", "\u0196", "\u0197"]], + index=["A\u0192", "B"], + columns=["X\u0193", "Y", "Z"], + ) + + df.to_excel(tmp_excel, sheet_name="TestSheet") + result = pd.read_excel(tmp_excel, sheet_name="TestSheet", index_col=0) + tm.assert_frame_equal(result, df) + + def test_to_excel_unicode_filename(self, ext, tmp_path): + filename = tmp_path / f"\u0192u.{ext}" + filename.touch() + df = pd.DataFrame( + [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + df.to_excel(filename, sheet_name="test1", float_format="%.2f") + + with ExcelFile(filename) as reader: + result = pd.read_excel(reader, sheet_name="test1", index_col=0) + + expected = pd.DataFrame( + [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("use_headers", [True, False]) + @pytest.mark.parametrize("r_idx_nlevels", [1, 2, 3]) + @pytest.mark.parametrize("c_idx_nlevels", [1, 2, 3]) + def test_excel_010_hemstring( + self, merge_cells, c_idx_nlevels, r_idx_nlevels, use_headers, tmp_excel + ): + def roundtrip(data, header=True, parser_hdr=0, index=True): + data.to_excel( + tmp_excel, header=header, merge_cells=merge_cells, index=index + ) + + with ExcelFile(tmp_excel) as xf: + return pd.read_excel( + xf, sheet_name=xf.sheet_names[0], header=parser_hdr + ) + + # Basic test. + parser_header = 0 if use_headers else None + res = roundtrip(pd.DataFrame([0]), use_headers, parser_header) + + assert res.shape == (1, 2) + assert res.iloc[0, 0] is not np.nan + + # More complex tests with multi-index. + nrows = 5 + ncols = 3 + + # ensure limited functionality in 0.10 + # override of gh-2370 until sorted out in 0.11 + + if c_idx_nlevels == 1: + columns = pd.Index([f"a-{i}" for i in range(ncols)], dtype=object) + else: + columns = pd.MultiIndex.from_arrays( + [range(ncols) for _ in range(c_idx_nlevels)], + names=[f"i-{i}" for i in range(c_idx_nlevels)], + ) + if r_idx_nlevels == 1: + index = pd.Index([f"b-{i}" for i in range(nrows)], dtype=object) + else: + index = pd.MultiIndex.from_arrays( + [range(nrows) for _ in range(r_idx_nlevels)], + names=[f"j-{i}" for i in range(r_idx_nlevels)], + ) + + df = pd.DataFrame( + np.ones((nrows, ncols)), + columns=columns, + index=index, + ) + + # This if will be removed once multi-column Excel writing + # is implemented. For now fixing gh-9794. + if c_idx_nlevels > 1: + msg = ( + "Writing to Excel with MultiIndex columns and no index " + "\\('index'=False\\) is not yet implemented." + ) + with pytest.raises(NotImplementedError, match=msg): + roundtrip(df, use_headers, index=False) + else: + res = roundtrip(df, use_headers) + + if use_headers: + assert res.shape == (nrows, ncols + r_idx_nlevels) + else: + # First row taken as columns. + assert res.shape == (nrows - 1, ncols + r_idx_nlevels) + + # No NaNs. + for r in range(len(res.index)): + for c in range(len(res.columns)): + assert res.iloc[r, c] is not np.nan + + def test_duplicated_columns(self, tmp_excel): + # see gh-5235 + df = pd.DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B"]) + df.to_excel(tmp_excel, sheet_name="test1") + expected = pd.DataFrame( + [[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B.1"] + ) + + # By default, we mangle. + result = pd.read_excel(tmp_excel, sheet_name="test1", index_col=0) + tm.assert_frame_equal(result, expected) + + # see gh-11007, gh-10970 + df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A", "B"]) + df.to_excel(tmp_excel, sheet_name="test1") + + result = pd.read_excel(tmp_excel, sheet_name="test1", index_col=0) + expected = pd.DataFrame( + [[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A.1", "B.1"] + ) + tm.assert_frame_equal(result, expected) + + # see gh-10982 + df.to_excel(tmp_excel, sheet_name="test1", index=False, header=False) + result = pd.read_excel(tmp_excel, sheet_name="test1", header=None) + + expected = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]]) + tm.assert_frame_equal(result, expected) + + def test_duplicated_multiindex_columns(self, tmp_excel): + # GH#19395 reading a sheet with duplicate MultiIndex columns used to + # raise an uninformative "Length of new names must be 1" ValueError; + # now the duplicate is mangled like read_csv does. + df = pd.DataFrame([[0, 1], [2, 3]], columns=[["A", "A"], ["A", "A"]]) + df.to_excel(tmp_excel) + + result = pd.read_excel(tmp_excel, header=[0, 1], index_col=0) + expected = pd.DataFrame( + [[0, 1], [2, 3]], + columns=pd.MultiIndex.from_tuples([("A", "A"), ("A", "A.1")]), + ) + tm.assert_frame_equal(result, expected) + + def test_swapped_columns(self, tmp_excel): + # Test for issue #5427. + write_frame = pd.DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]}) + write_frame.to_excel(tmp_excel, sheet_name="test1", columns=["B", "A"]) + + read_frame = pd.read_excel(tmp_excel, sheet_name="test1", header=0) + + tm.assert_series_equal(write_frame["A"], read_frame["A"]) + tm.assert_series_equal(write_frame["B"], read_frame["B"]) + + def test_invalid_columns(self, tmp_excel): + # see gh-10982 + write_frame = pd.DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]}) + + with pytest.raises(KeyError, match="Not all names specified"): + write_frame.to_excel(tmp_excel, sheet_name="test1", columns=["B", "C"]) + + with pytest.raises( + KeyError, match="Passed columns are not all present in the dataframe" + ): + write_frame.to_excel(tmp_excel, sheet_name="test1", columns=["C", "D"]) + + @pytest.mark.parametrize( + "to_excel_index,read_excel_index_col", + [ + (True, 0), # Include index in write to file + (False, None), # Dont include index in write to file + ], + ) + def test_write_subset_columns( + self, tmp_excel, to_excel_index, read_excel_index_col + ): + # GH 31677 + write_frame = pd.DataFrame({"A": [1, 1, 1], "B": [2, 2, 2], "C": [3, 3, 3]}) + write_frame.to_excel( + tmp_excel, + sheet_name="col_subset_bug", + columns=["A", "B"], + index=to_excel_index, + ) + + expected = write_frame[["A", "B"]] + read_frame = pd.read_excel( + tmp_excel, sheet_name="col_subset_bug", index_col=read_excel_index_col + ) + + tm.assert_frame_equal(expected, read_frame) + + def test_comment_arg(self, tmp_excel): + # see gh-18735 + # + # Test the comment argument functionality to pd.read_excel. + + # Create file to read in. + df = pd.DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) + df.to_excel(tmp_excel, sheet_name="test_c") + + # Read file without comment arg. + result1 = pd.read_excel(tmp_excel, sheet_name="test_c", index_col=0) + + result1.iloc[1, 0] = None + result1.iloc[1, 1] = None + result1.iloc[2, 1] = None + + result2 = pd.read_excel( + tmp_excel, sheet_name="test_c", comment="#", index_col=0 + ) + tm.assert_frame_equal(result1, result2) + + def test_comment_default(self, tmp_excel): + # Re issue #18735 + # Test the comment argument default to pd.read_excel + + # Create file to read in + df = pd.DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) + df.to_excel(tmp_excel, sheet_name="test_c") + + # Read file with default and explicit comment=None + result1 = pd.read_excel(tmp_excel, sheet_name="test_c") + result2 = pd.read_excel(tmp_excel, sheet_name="test_c", comment=None) + tm.assert_frame_equal(result1, result2) + + def test_comment_used(self, tmp_excel): + # see gh-18735 + # + # Test the comment argument is working as expected when used. + + # Create file to read in. + df = pd.DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) + df.to_excel(tmp_excel, sheet_name="test_c") + + # Test read_frame_comment against manually produced expected output. + expected = pd.DataFrame({"A": ["one", None, "one"], "B": ["two", None, None]}) + result = pd.read_excel(tmp_excel, sheet_name="test_c", comment="#", index_col=0) + tm.assert_frame_equal(result, expected) + + def test_comment_empty_line(self, tmp_excel): + # Re issue #18735 + # Test that pd.read_excel ignores commented lines at the end of file + + df = pd.DataFrame({"a": ["1", "#2"], "b": ["2", "3"]}) + df.to_excel(tmp_excel, index=False) + + # Test that all-comment lines at EoF are ignored + expected = pd.DataFrame({"a": [1], "b": [2]}) + result = pd.read_excel(tmp_excel, comment="#") + tm.assert_frame_equal(result, expected) + + def test_datetimes(self, tmp_excel): + # Test writing and reading datetimes. For issue #9139. (xref #9185) + unit = get_exp_unit(tmp_excel) + datetimes = [ + datetime(2013, 1, 13, 1, 2, 3), + datetime(2013, 1, 13, 2, 45, 56), + datetime(2013, 1, 13, 4, 29, 49), + datetime(2013, 1, 13, 6, 13, 42), + datetime(2013, 1, 13, 7, 57, 35), + datetime(2013, 1, 13, 9, 41, 28), + datetime(2013, 1, 13, 11, 25, 21), + datetime(2013, 1, 13, 13, 9, 14), + datetime(2013, 1, 13, 14, 53, 7), + datetime(2013, 1, 13, 16, 37, 0), + datetime(2013, 1, 13, 18, 20, 52), + ] + + write_frame = pd.DataFrame({"A": datetimes}) + write_frame.to_excel(tmp_excel, sheet_name="Sheet1") + read_frame = pd.read_excel(tmp_excel, sheet_name="Sheet1", header=0) + + expected = write_frame.astype(f"M8[{unit}]") + tm.assert_series_equal(expected["A"], read_frame["A"]) + + def test_bytes_io(self, engine): + # see gh-7074 + with BytesIO() as bio: + df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 2))) + + # Pass engine explicitly, as there is no file path to infer from. + with ExcelWriter(bio, engine=engine) as writer: + df.to_excel(writer) + + bio.seek(0) + reread_df = pd.read_excel(bio, index_col=0) + tm.assert_frame_equal(df, reread_df) + + def test_engine_kwargs(self, engine, tmp_excel): + # GH#52368 + df = pd.DataFrame([{"A": 1, "B": 2}, {"A": 3, "B": 4}]) + + msgs = { + "odf": r"OpenDocumentSpreadsheet() got an unexpected keyword " + r"argument 'foo'", + "openpyxl": r"__init__() got an unexpected keyword argument 'foo'", + "xlsxwriter": r"__init__() got an unexpected keyword argument 'foo'", + } + + msgs["openpyxl"] = ( + "Workbook.__init__() got an unexpected keyword argument 'foo'" + ) + msgs["xlsxwriter"] = ( + "Workbook.__init__() got an unexpected keyword argument 'foo'" + ) + + # Handle change in error message for openpyxl (write and append mode) + if engine == "openpyxl" and not os.path.exists(tmp_excel): + msgs["openpyxl"] = ( + r"load_workbook() got an unexpected keyword argument 'foo'" + ) + + with pytest.raises(TypeError, match=re.escape(msgs[engine])): + df.to_excel( + tmp_excel, + engine=engine, + engine_kwargs={"foo": "bar"}, + ) + + def test_write_lists_dict(self, tmp_excel): + # see gh-8188. + df = pd.DataFrame( + { + "mixed": ["a", ["b", "c"], {"d": "e", "f": 2}], + "numeric": [1, 2, 3.0], + "str": ["apple", "banana", "cherry"], + } + ) + df.to_excel(tmp_excel, sheet_name="Sheet1") + read = pd.read_excel(tmp_excel, sheet_name="Sheet1", header=0, index_col=0) + + expected = df.copy() + expected.mixed = expected.mixed.apply(str) + expected.numeric = expected.numeric.astype("int64") + + tm.assert_frame_equal(read, expected) + + def test_render_as_column_name(self, tmp_excel): + # see gh-34331 + df = pd.DataFrame({"render": [1, 2], "data": [3, 4]}) + df.to_excel(tmp_excel, sheet_name="Sheet1") + read = pd.read_excel(tmp_excel, "Sheet1", index_col=0) + expected = df + tm.assert_frame_equal(read, expected) + + def test_true_and_false_value_options(self, tmp_excel): + # see gh-13347 + df = pd.DataFrame([["foo", "bar"]], columns=["col1", "col2"], dtype=object) + expected = df.replace({"foo": True, "bar": False}).astype("bool") + + df.to_excel(tmp_excel) + read_frame = pd.read_excel( + tmp_excel, true_values=["foo"], false_values=["bar"], index_col=0 + ) + tm.assert_frame_equal(read_frame, expected) + + def test_freeze_panes(self, tmp_excel): + # see gh-15160 + expected = pd.DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"]) + expected.to_excel(tmp_excel, sheet_name="Sheet1", freeze_panes=(1, 1)) + + result = pd.read_excel(tmp_excel, index_col=0) + tm.assert_frame_equal(result, expected) + + def test_path_path_lib(self, engine, tmp_excel): + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD")), + index=pd.Index([f"i-{i}" for i in range(30)]), + ) + writer = partial(df.to_excel, engine=engine) + + reader = partial(pd.read_excel, index_col=0) + result = tm.round_trip_pathlib(writer, reader, pathlib.Path(tmp_excel)) + tm.assert_frame_equal(result, df) + + def test_merged_cell_custom_objects(self, tmp_excel): + # see GH-27006 + mi = pd.MultiIndex.from_tuples( + [ + (pd.Period("2018"), pd.Period("2018Q1")), + (pd.Period("2018"), pd.Period("2018Q2")), + ] + ) + expected = pd.DataFrame(np.ones((2, 2), dtype="int64"), columns=mi) + expected.to_excel(tmp_excel) + result = pd.read_excel(tmp_excel, header=[0, 1], index_col=0) + # need to convert PeriodIndexes to standard Indexes for assert equal + expected.columns = expected.columns.set_levels( + [[str(i) for i in mi.levels[0]], [str(i) for i in mi.levels[1]]], + level=[0, 1], + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype", [None, object]) + def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, tmp_excel): + # GH 27008, GH 7056 + tz = tz_aware_fixture + data = pd.Timestamp("2019", tz=tz) + df = pd.DataFrame([data], dtype=dtype) + with pytest.raises(ValueError, match="Excel does not support"): + df.to_excel(tmp_excel) + + data = data.to_pydatetime() + df = pd.DataFrame([data], dtype=dtype) + with pytest.raises(ValueError, match="Excel does not support"): + df.to_excel(tmp_excel) + + def test_excel_duplicate_columns_with_names(self, tmp_excel): + # GH#39695 + df = pd.DataFrame({"A": [0, 1], "B": [10, 11]}) + df.to_excel(tmp_excel, columns=["A", "B", "A"], index=False) + + result = pd.read_excel(tmp_excel) + expected = pd.DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"]) + tm.assert_frame_equal(result, expected) + + def test_if_sheet_exists_raises(self, tmp_excel): + # GH 40230 + msg = "if_sheet_exists is only valid in append mode (mode='a')" + + with pytest.raises(ValueError, match=re.escape(msg)): + ExcelWriter(tmp_excel, if_sheet_exists="replace") + + def test_excel_writer_empty_frame(self, engine, tmp_excel): + # GH#45793 + with ExcelWriter(tmp_excel, engine=engine) as writer: + pd.DataFrame().to_excel(writer) + result = pd.read_excel(tmp_excel) + expected = pd.DataFrame() + tm.assert_frame_equal(result, expected) + + def test_to_excel_empty_frame(self, engine, tmp_excel): + # GH#45793 + pd.DataFrame().to_excel(tmp_excel, engine=engine) + result = pd.read_excel(tmp_excel) + expected = pd.DataFrame() + tm.assert_frame_equal(result, expected) + + def test_to_excel_raising_warning_when_cell_character_exceed_limit(self): + # GH#56954 + df = pd.DataFrame({"A": ["a" * 32768]}) + msg = r"Cell contents too long, truncated to 32767 characters" + with tm.assert_produces_warning( + UserWarning, match=msg, raise_on_extra_warnings=False + ): + buf = BytesIO() + df.to_excel(buf) + + @pytest.mark.parametrize("with_index", [True, False]) + def test_autofilter(self, engine, with_index, tmp_excel): + # GH 61194 + df = pd.DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 4, "B": 5, "C": 6}]) + + if engine in ["odf"]: + with pytest.raises( + ValueError, match="Autofilter is not supported with odf!" + ): + df.to_excel(tmp_excel, engine=engine, autofilter=True, index=False) + else: + df.to_excel(tmp_excel, engine=engine, autofilter=True, index=with_index) + + openpyxl = pytest.importorskip( + "openpyxl" + ) # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + ws = wb.active + + assert ws.auto_filter.ref is not None + assert ws.auto_filter.ref == "A1:D3" if with_index else "A1:C3" + + def test_autofilter_with_startrow_startcol(self, engine, tmp_excel): + # GH 61194 + df = pd.DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 4, "B": 5, "C": 6}]) + + if engine in ["odf"]: + # odf does not support autofilter + with pytest.raises( + ValueError, match="Autofilter is not supported with odf!" + ): + df.to_excel(tmp_excel, engine=engine, autofilter=True, index=False) + else: + df.to_excel( + tmp_excel, engine=engine, autofilter=True, startrow=10, startcol=10 + ) + + openpyxl = pytest.importorskip( + "openpyxl" + ) # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + ws = wb.active + assert ws.auto_filter.ref is not None + # Autofiler range moved by 10x10 cells + assert ws.auto_filter.ref == "K11:N13" + + @pytest.mark.parametrize("merge_cells", [True, False]) + def test_autofilter_with_multiindex_index(self, engine, tmp_excel, merge_cells): + # GH 61194 + df = pd.DataFrame( + { + "animal": ("horse", "horse", "dog", "dog"), + "color of fur": ("black", "white", "grey", "black"), + "name": ("Blacky", "Wendy", "Rufus", "Catchy"), + } + ) + # setup hierarchical index + mi_df = df.set_index(["animal", "color of fur"]) + if engine in ["odf"]: + # odf does not support autofilter + with pytest.raises( + ValueError, match="Autofilter is not supported with odf!" + ): + mi_df.to_excel( + tmp_excel, + engine=engine, + autofilter=True, + index=False, + merge_cells=merge_cells, + ) + elif merge_cells: + # multiindex and merge cells cannot be used simultaneously + with pytest.raises( + ValueError, + match="Excel filters merged cells by showing only the first row. " + "'autofilter' and 'merge_cells' cannot be used simultaneously.", + ): + mi_df.to_excel( + tmp_excel, + engine=engine, + autofilter=True, + index=True, + merge_cells=merge_cells, + ) + else: + mi_df.to_excel( + tmp_excel, + engine=engine, + autofilter=True, + index=True, + merge_cells=merge_cells, + ) + + # validate autofilter range + openpyxl = pytest.importorskip( + "openpyxl" + ) # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + ws = wb.active + + assert ws.auto_filter.ref is not None + assert ws.auto_filter.ref == "A1:C5" + + @pytest.mark.parametrize("merge_cells", [True, False]) + def test_autofilter_with_multiindex_columns(self, engine, tmp_excel, merge_cells): + # GH 61194 + columns = pd.MultiIndex( + levels=[["x", "y"], ["w", "t"]], + codes=[[0, 0, 1], [0, 1, 0]], + ) + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=columns) + + if engine in ["odf"]: + # odf does not support autofilter + with pytest.raises( + ValueError, match="Autofilter is not supported with odf!" + ): + df.to_excel( + tmp_excel, + engine=engine, + autofilter=True, + index=False, + merge_cells=merge_cells, + ) + elif merge_cells: + # multiindex and merge cells cannot be used simultaneously + with pytest.raises( + ValueError, + match="Excel filters merged cells by showing only the first row. " + "'autofilter' and 'merge_cells' cannot be used simultaneously.", + ): + df.to_excel( + tmp_excel, + engine=engine, + autofilter=True, + index=True, + merge_cells=merge_cells, + ) + else: + df.to_excel( + tmp_excel, + engine=engine, + autofilter=True, + index=True, + merge_cells=merge_cells, + ) + + # validate autofilter range + openpyxl = pytest.importorskip( + "openpyxl" + ) # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + ws = wb.active + + assert ws.auto_filter.ref is not None + assert ws.auto_filter.ref == "A2:D5" + + +class TestExcelWriterEngineTests: + @pytest.mark.parametrize( + "klass,ext", + [ + pytest.param(_XlsxWriter, ".xlsx", marks=td.skip_if_no("xlsxwriter")), + pytest.param(_OpenpyxlWriter, ".xlsx", marks=td.skip_if_no("openpyxl")), + ], + ) + def test_ExcelWriter_dispatch(self, klass, ext, tmp_excel): + with ExcelWriter(tmp_excel) as writer: + if ext == ".xlsx" and bool( + import_optional_dependency("xlsxwriter", errors="ignore") + ): + # xlsxwriter has preference over openpyxl if both installed + assert isinstance(writer, _XlsxWriter) + else: + assert isinstance(writer, klass) + + def test_ExcelWriter_dispatch_raises(self): + with pytest.raises(ValueError, match="No engine"): + ExcelWriter("nothing") + + def test_register_writer(self, tmp_path): + class DummyClass(ExcelWriter): + called_save = False + called_write_cells = False + called_sheets = False + _supported_extensions = ("xlsx", "xls") + _engine = "dummy" + + def book(self): + pass + + def _save(self): + type(self).called_save = True + + def _write_cells(self, *args, **kwargs): + type(self).called_write_cells = True + + @property + def sheets(self): + type(self).called_sheets = True + + @classmethod + def assert_called_and_reset(cls): + assert cls.called_save + assert cls.called_write_cells + assert not cls.called_sheets + cls.called_save = False + cls.called_write_cells = False + + register_writer(DummyClass) + + with pd.option_context("io.excel.xlsx.writer", "dummy"): + filepath = tmp_path / "something.xlsx" + filepath.touch() + with ExcelWriter(filepath) as writer: + assert isinstance(writer, DummyClass) + df = pd.DataFrame( + ["a"], + columns=pd.Index(["b"], name="foo"), + index=pd.Index(["c"], name="bar"), + ) + df.to_excel(filepath) + DummyClass.assert_called_and_reset() + + filepath2 = tmp_path / "something2.xlsx" + filepath2.touch() + df.to_excel(filepath2, engine="dummy") + DummyClass.assert_called_and_reset() + + +@td.skip_if_no("xlrd") +@td.skip_if_no("openpyxl") +class TestFSPath: + def test_excelfile_fspath(self, tmp_path): + path = tmp_path / "foo.xlsx" + path.touch() + df = pd.DataFrame({"A": [1, 2]}) + df.to_excel(path) + with ExcelFile(path) as xl: + result = os.fspath(xl) + assert result == str(path) + + def test_excelwriter_fspath(self, tmp_path): + path = tmp_path / "foo.xlsx" + path.touch() + with ExcelWriter(path) as writer: + assert os.fspath(writer) == str(path) + + +@pytest.mark.parametrize("klass", _writers.values()) +def test_subclass_attr(klass): + # testing that subclasses of ExcelWriter don't have public attributes (issue 49602) + attrs_base = {name for name in dir(ExcelWriter) if not name.startswith("_")} + attrs_klass = {name for name in dir(klass) if not name.startswith("_")} + assert not attrs_base.symmetric_difference(attrs_klass) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_xlrd.py b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_xlrd.py new file mode 100644 index 0000000000000000000000000000000000000000..6e35b84baa10e60d0c843df60db8de7f24065273 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_xlrd.py @@ -0,0 +1,111 @@ +import io +import sys + +import numpy as np +import pytest + +from pandas.errors import Pandas4Warning + +import pandas as pd +import pandas._testing as tm + +from pandas.io.excel import ExcelFile +from pandas.io.excel._base import inspect_excel_format + +xlrd = pytest.importorskip("xlrd") + +pytestmark = pytest.mark.filterwarnings( + "ignore:The xlrd engine is deprecated:pandas.errors.Pandas4Warning" +) + + +@pytest.fixture +def read_ext_xlrd(): + """ + Valid extensions for reading Excel files with xlrd. + + Similar to read_ext, but excludes .ods, .xlsb, and for xlrd>2 .xlsx, .xlsm + """ + return ".xls" + + +def test_read_xlrd_book(read_ext_xlrd, datapath): + engine = "xlrd" + sheet_name = "Sheet1" + pth = datapath("io", "data", "excel", "test1.xls") + with xlrd.open_workbook(pth) as book: + with ExcelFile(book, engine=engine) as xl: + result = pd.read_excel(xl, sheet_name=sheet_name, index_col=0) + + expected = pd.read_excel( + book, sheet_name=sheet_name, engine=engine, index_col=0 + ) + tm.assert_frame_equal(result, expected) + + +def test_read_xlsx_fails(datapath): + # GH 29375 + from xlrd.biffh import XLRDError + + path = datapath("io", "data", "excel", "test1.xlsx") + with pytest.raises(XLRDError, match="Excel xlsx file; not supported"): + pd.read_excel(path, engine="xlrd") + + +def test_nan_in_xls(datapath): + # GH 54564 + path = datapath("io", "data", "excel", "test6.xls") + + expected = pd.DataFrame({0: np.r_[0, 2].astype("int64"), 1: np.r_[1, np.nan]}) + + result = pd.read_excel(path, header=None) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "file_header", + [ + b"\x09\x00\x04\x00\x07\x00\x10\x00", + b"\x09\x02\x06\x00\x00\x00\x10\x00", + b"\x09\x04\x06\x00\x00\x00\x10\x00", + b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", + ], +) +def test_read_old_xls_files(file_header): + # GH 41226 + f = io.BytesIO(file_header) + assert inspect_excel_format(f) == "xls" + + +def test_xlrd_engine_deprecated(datapath): + # GH#56542 + path = datapath("io", "data", "excel", "test1.xls") + with tm.assert_produces_warning(Pandas4Warning, match="xlrd engine is deprecated"): + pd.read_excel(path, engine="xlrd") + + +def test_read_xlrd_book_no_engine(datapath): + # GH#68086 - a Book has "read" but no "seek", so it passes is_file_like + # and used to reach inspect_excel_format instead of the xlrd branch + sheet_name = "Sheet1" + pth = datapath("io", "data", "excel", "test1.xls") + expected = pd.read_excel(pth, sheet_name=sheet_name, engine="xlrd", index_col=0) + + with xlrd.open_workbook(pth) as book: + with ExcelFile(book) as xl: + assert xl.engine == "xlrd" + result = pd.read_excel(xl, sheet_name=sheet_name, index_col=0) + with xlrd.open_workbook(pth) as book: + from_book = pd.read_excel(book, sheet_name=sheet_name, index_col=0) + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(from_book, expected) + + +def test_read_excel_does_not_import_xlrd(datapath, monkeypatch): + # GH#56692 - the xlrd.Book check must not import xlrd + monkeypatch.delitem(sys.modules, "xlrd", raising=False) + with pd.option_context("io.excel.xlsx.reader", "openpyxl"): + pd.read_excel(datapath("io", "data", "excel", "test1.xlsx")) + assert "xlrd" not in sys.modules diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_xlsxwriter.py b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_xlsxwriter.py new file mode 100644 index 0000000000000000000000000000000000000000..397ef0aeba088ec7fb7551f0a0b23022ad18316b --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/excel/test_xlsxwriter.py @@ -0,0 +1,86 @@ +import contextlib +import uuid + +import pytest + +import pandas as pd + +from pandas.io.excel import ExcelWriter + +xlsxwriter = pytest.importorskip("xlsxwriter") + + +@pytest.fixture +def ext(): + return ".xlsx" + + +@pytest.fixture +def tmp_excel(ext, tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}{ext}" + tmp.touch() + return str(tmp) + + +def test_column_format(tmp_excel): + # Test that column formats are applied to cells. Test for issue #9167. + # Applicable to xlsxwriter only. + openpyxl = pytest.importorskip("openpyxl") + + frame = pd.DataFrame({"A": [123456, 123456], "B": [123456, 123456]}) + + with ExcelWriter(tmp_excel) as writer: + frame.to_excel(writer) + + # Add a number format to col B and ensure it is applied to cells. + num_format = "#,##0" + write_workbook = writer.book + write_worksheet = write_workbook.worksheets()[0] + col_format = write_workbook.add_format({"num_format": num_format}) + write_worksheet.set_column("B:B", None, col_format) + + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as read_workbook: + try: + read_worksheet = read_workbook["Sheet1"] + except TypeError: + # compat + read_worksheet = read_workbook.get_sheet_by_name(name="Sheet1") + + # Get the number format from the cell. + try: + cell = read_worksheet["B2"] + except TypeError: + # compat + cell = read_worksheet.cell("B2") + + try: + read_num_format = cell.number_format + except AttributeError: + read_num_format = cell.style.number_format._format_code + + assert read_num_format == num_format + + +def test_write_append_mode_raises(tmp_excel): + msg = "Append mode is not supported with xlsxwriter!" + + with pytest.raises(ValueError, match=msg): + ExcelWriter(tmp_excel, engine="xlsxwriter", mode="a") + + +@pytest.mark.parametrize("nan_inf_to_errors", [True, False]) +def test_engine_kwargs(tmp_excel, nan_inf_to_errors): + # GH 42286 + engine_kwargs = {"options": {"nan_inf_to_errors": nan_inf_to_errors}} + with ExcelWriter( + tmp_excel, engine="xlsxwriter", engine_kwargs=engine_kwargs + ) as writer: + assert writer.book.nan_inf_to_errors == nan_inf_to_errors + + +def test_book_and_sheets_consistent(tmp_excel): + # GH#45687 - Ensure sheets is updated if user modifies book + with ExcelWriter(tmp_excel, engine="xlsxwriter") as writer: + assert writer.sheets == {} + sheet = writer.book.add_worksheet("test_name") + assert writer.sheets == {"test_name": sheet} diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/__init__.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_bar.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_bar.py new file mode 100644 index 0000000000000000000000000000000000000000..62572192260b0898fe8ed23682ed938010c78e67 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_bar.py @@ -0,0 +1,358 @@ +import io + +import numpy as np +import pytest + +import pandas as pd + +pytest.importorskip("jinja2") + + +def bar_grad(a=None, b=None, c=None, d=None): + """Used in multiple tests to simplify formatting of expected result""" + ret = [("width", "10em")] + if all(x is None for x in [a, b, c, d]): + return ret + return [ + *ret, + ( + "background", + f"linear-gradient(90deg,{','.join([x for x in [a, b, c, d] if x])})", + ), + ] + + +def no_bar(): + return bar_grad() + + +def bar_to(x, color="#d65f5f"): + return bar_grad(f" {color} {x:.1f}%", f" transparent {x:.1f}%") + + +def bar_from_to(x, y, color="#d65f5f"): + return bar_grad( + f" transparent {x:.1f}%", + f" {color} {x:.1f}%", + f" {color} {y:.1f}%", + f" transparent {y:.1f}%", + ) + + +@pytest.fixture +def df_pos(): + return pd.DataFrame([[1], [2], [3]]) + + +@pytest.fixture +def df_neg(): + return pd.DataFrame([[-1], [-2], [-3]]) + + +@pytest.fixture +def df_mix(): + return pd.DataFrame([[-3], [1], [2]]) + + +@pytest.mark.parametrize( + "align, exp", + [ + ("left", [no_bar(), bar_to(50), bar_to(100)]), + ("right", [bar_to(100), bar_from_to(50, 100), no_bar()]), + ("mid", [bar_to(33.33), bar_to(66.66), bar_to(100)]), + ("zero", [bar_from_to(50, 66.7), bar_from_to(50, 83.3), bar_from_to(50, 100)]), + ("mean", [bar_to(50), no_bar(), bar_from_to(50, 100)]), + (2.0, [bar_to(50), no_bar(), bar_from_to(50, 100)]), + (np.median, [bar_to(50), no_bar(), bar_from_to(50, 100)]), + ], +) +def test_align_positive_cases(df_pos, align, exp): + # test different align cases for all positive values + result = df_pos.style.bar(align=align)._compute().ctx + expected = {(0, 0): exp[0], (1, 0): exp[1], (2, 0): exp[2]} + assert result == expected + + +@pytest.mark.parametrize( + "align, exp", + [ + ("left", [bar_to(100), bar_to(50), no_bar()]), + ("right", [no_bar(), bar_from_to(50, 100), bar_to(100)]), + ("mid", [bar_from_to(66.66, 100), bar_from_to(33.33, 100), bar_to(100)]), + ("zero", [bar_from_to(33.33, 50), bar_from_to(16.66, 50), bar_to(50)]), + ("mean", [bar_from_to(50, 100), no_bar(), bar_to(50)]), + (-2.0, [bar_from_to(50, 100), no_bar(), bar_to(50)]), + (np.median, [bar_from_to(50, 100), no_bar(), bar_to(50)]), + ], +) +def test_align_negative_cases(df_neg, align, exp): + # test different align cases for all negative values + result = df_neg.style.bar(align=align)._compute().ctx + expected = {(0, 0): exp[0], (1, 0): exp[1], (2, 0): exp[2]} + assert result == expected + + +@pytest.mark.parametrize( + "align, exp", + [ + ("left", [no_bar(), bar_to(80), bar_to(100)]), + ("right", [bar_to(100), bar_from_to(80, 100), no_bar()]), + ("mid", [bar_to(60), bar_from_to(60, 80), bar_from_to(60, 100)]), + ("zero", [bar_to(50), bar_from_to(50, 66.66), bar_from_to(50, 83.33)]), + ("mean", [bar_to(50), bar_from_to(50, 66.66), bar_from_to(50, 83.33)]), + (-0.0, [bar_to(50), bar_from_to(50, 66.66), bar_from_to(50, 83.33)]), + (np.nanmedian, [bar_to(50), no_bar(), bar_from_to(50, 62.5)]), + ], +) +@pytest.mark.parametrize("nans", [True, False]) +def test_align_mixed_cases(df_mix, align, exp, nans): + # test different align cases for mixed positive and negative values + # also test no impact of NaNs and no_bar + expected = {(0, 0): exp[0], (1, 0): exp[1], (2, 0): exp[2]} + if nans: + df_mix.loc[3, :] = np.nan + expected.update({(3, 0): no_bar()}) + result = df_mix.style.bar(align=align)._compute().ctx + assert result == expected + + +@pytest.mark.parametrize( + "align, exp", + [ + ( + "left", + { + "index": [[no_bar(), no_bar()], [bar_to(100), bar_to(100)]], + "columns": [[no_bar(), bar_to(100)], [no_bar(), bar_to(100)]], + "none": [[no_bar(), bar_to(33.33)], [bar_to(66.66), bar_to(100)]], + }, + ), + ( + "mid", + { + "index": [[bar_to(33.33), bar_to(50)], [bar_to(100), bar_to(100)]], + "columns": [[bar_to(50), bar_to(100)], [bar_to(75), bar_to(100)]], + "none": [[bar_to(25), bar_to(50)], [bar_to(75), bar_to(100)]], + }, + ), + ( + "zero", + { + "index": [ + [bar_from_to(50, 66.66), bar_from_to(50, 75)], + [bar_from_to(50, 100), bar_from_to(50, 100)], + ], + "columns": [ + [bar_from_to(50, 75), bar_from_to(50, 100)], + [bar_from_to(50, 87.5), bar_from_to(50, 100)], + ], + "none": [ + [bar_from_to(50, 62.5), bar_from_to(50, 75)], + [bar_from_to(50, 87.5), bar_from_to(50, 100)], + ], + }, + ), + ( + 2, + { + "index": [ + [bar_to(50), no_bar()], + [bar_from_to(50, 100), bar_from_to(50, 100)], + ], + "columns": [ + [bar_to(50), no_bar()], + [bar_from_to(50, 75), bar_from_to(50, 100)], + ], + "none": [ + [bar_from_to(25, 50), no_bar()], + [bar_from_to(50, 75), bar_from_to(50, 100)], + ], + }, + ), + ], +) +@pytest.mark.parametrize("axis", ["index", "columns", "none"]) +def test_align_axis(align, exp, axis): + # test all axis combinations with positive values and different aligns + data = pd.DataFrame([[1, 2], [3, 4]]) + result = ( + data.style.bar(align=align, axis=None if axis == "none" else axis) + ._compute() + .ctx + ) + expected = { + (0, 0): exp[axis][0][0], + (0, 1): exp[axis][0][1], + (1, 0): exp[axis][1][0], + (1, 1): exp[axis][1][1], + } + assert result == expected + + +@pytest.mark.parametrize( + "values, vmin, vmax", + [ + ("positive", 1.5, 2.5), + ("negative", -2.5, -1.5), + ("mixed", -2.5, 1.5), + ], +) +@pytest.mark.parametrize("nullify", [None, "vmin", "vmax"]) # test min/max separately +@pytest.mark.parametrize("align", ["left", "right", "zero", "mid"]) +def test_vmin_vmax_clipping(df_pos, df_neg, df_mix, values, vmin, vmax, nullify, align): + # test that clipping occurs if any vmin > data_values or vmax < data_values + if align == "mid": # mid acts as left or right in each case + if values == "positive": + align = "left" + elif values == "negative": + align = "right" + df = {"positive": df_pos, "negative": df_neg, "mixed": df_mix}[values] + vmin = None if nullify == "vmin" else vmin + vmax = None if nullify == "vmax" else vmax + + clip_df = df.where(df <= (vmax if vmax else 999), other=vmax) + clip_df = clip_df.where(clip_df >= (vmin if vmin else -999), other=vmin) + + result = ( + df.style.bar(align=align, vmin=vmin, vmax=vmax, color=["red", "green"]) + ._compute() + .ctx + ) + expected = clip_df.style.bar(align=align, color=["red", "green"])._compute().ctx + assert result == expected + + +@pytest.mark.parametrize( + "values, vmin, vmax", + [ + ("positive", 0.5, 4.5), + ("negative", -4.5, -0.5), + ("mixed", -4.5, 4.5), + ], +) +@pytest.mark.parametrize("nullify", [None, "vmin", "vmax"]) # test min/max separately +@pytest.mark.parametrize("align", ["left", "right", "zero", "mid"]) +def test_vmin_vmax_widening(df_pos, df_neg, df_mix, values, vmin, vmax, nullify, align): + # test that widening occurs if any vmax > data_values or vmin < data_values + if align == "mid": # mid acts as left or right in each case + if values == "positive": + align = "left" + elif values == "negative": + align = "right" + df = {"positive": df_pos, "negative": df_neg, "mixed": df_mix}[values] + vmin = None if nullify == "vmin" else vmin + vmax = None if nullify == "vmax" else vmax + + # cast to float64 up front so appending float vmin/vmax does not + # change the dtype (GH#62369 deprecation) + expand_df = df.copy().astype(np.float64) + expand_df.loc[3, :], expand_df.loc[4, :] = vmin, vmax + + result = ( + df.style.bar(align=align, vmin=vmin, vmax=vmax, color=["red", "green"]) + ._compute() + .ctx + ) + expected = expand_df.style.bar(align=align, color=["red", "green"])._compute().ctx + assert result.items() <= expected.items() + + +def test_numerics(): + # test data is preselected for numeric values + data = pd.DataFrame([[1, "a"], [2, "b"]]) + result = data.style.bar()._compute().ctx + assert (0, 1) not in result + assert (1, 1) not in result + + +@pytest.mark.parametrize( + "align, exp", + [ + ("left", [no_bar(), bar_to(100, "green")]), + ("right", [bar_to(100, "red"), no_bar()]), + ("mid", [bar_to(25, "red"), bar_from_to(25, 100, "green")]), + ("zero", [bar_from_to(33.33, 50, "red"), bar_from_to(50, 100, "green")]), + ], +) +def test_colors_mixed(align, exp): + data = pd.DataFrame([[-1], [3]]) + result = data.style.bar(align=align, color=["red", "green"])._compute().ctx + assert result == {(0, 0): exp[0], (1, 0): exp[1]} + + +def test_bar_align_height(): + # test when keyword height is used 'no-repeat center' and 'background-size' present + data = pd.DataFrame([[1], [2]]) + result = data.style.bar(align="left", height=50)._compute().ctx + bg_s = "linear-gradient(90deg, #d65f5f 100.0%, transparent 100.0%) no-repeat center" + expected = { + (0, 0): [("width", "10em")], + (1, 0): [ + ("width", "10em"), + ("background", bg_s), + ("background-size", "100% 50.0%"), + ], + } + assert result == expected + + +def test_bar_value_error_raises(): + df = pd.DataFrame({"A": [-100, -60, -30, -20]}) + + msg = "`align` should be in {'left', 'right', 'mid', 'mean', 'zero'} or" + with pytest.raises(ValueError, match=msg): + df.style.bar(align="poorly", color=["#d65f5f", "#5fba7d"]).to_html() + + msg = r"`width` must be a value in \[0, 100\]" + with pytest.raises(ValueError, match=msg): + df.style.bar(width=200).to_html() + + msg = r"`height` must be a value in \[0, 100\]" + with pytest.raises(ValueError, match=msg): + df.style.bar(height=200).to_html() + + +def test_bar_color_and_cmap_error_raises(): + df = pd.DataFrame({"A": [1, 2, 3, 4]}) + msg = "`color` and `cmap` cannot both be given" + # Test that providing both color and cmap raises a ValueError + with pytest.raises(ValueError, match=msg): + df.style.bar(color="#d65f5f", cmap="viridis").to_html() + + +def test_bar_invalid_color_type_error_raises(): + df = pd.DataFrame({"A": [1, 2, 3, 4]}) + msg = ( + r"`color` must be string or list or tuple of 2 strings," + r"\(eg: color=\['#d65f5f', '#5fba7d'\]\)" + ) + # Test that providing an invalid color type raises a ValueError + with pytest.raises(ValueError, match=msg): + df.style.bar(color=123).to_html() + + # Test that providing a color list with more than two elements raises a ValueError + with pytest.raises(ValueError, match=msg): + df.style.bar(color=["#d65f5f", "#5fba7d", "#abcdef"]).to_html() + + +def test_styler_bar_with_NA_values(): + df1 = pd.DataFrame({"A": [1, 2, pd.NA, 4]}) + df2 = pd.DataFrame([[pd.NA, pd.NA], [pd.NA, pd.NA]]) + expected_substring = "style type=" + html_output1 = df1.style.bar(subset="A").to_html() + html_output2 = df2.style.bar(align="left", axis=None).to_html() + assert expected_substring in html_output1 + assert expected_substring in html_output2 + + +def test_style_bar_with_pyarrow_NA_values(): + pytest.importorskip("pyarrow") + data = """name,age,test1,test2,teacher + Adam,15,95.0,80,Ashby + Bob,16,81.0,82,Ashby + Dave,16,89.0,84,Jones + Fred,15,,88,Jones""" + df = pd.read_csv(io.StringIO(data), dtype_backend="pyarrow") + expected_substring = "style type=" + html_output = df.style.bar(subset="test1").to_html() + assert expected_substring in html_output diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_exceptions.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..49d2fcb60d4efa50ba5720a42add5fff463d8733 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_exceptions.py @@ -0,0 +1,41 @@ +import pytest + +jinja2 = pytest.importorskip("jinja2") + +import pandas as pd + +from pandas.io.formats.style import Styler + + +@pytest.fixture +def df(): + return pd.DataFrame( + data=[[0, -0.609], [1, -1.228]], + columns=["A", "B"], + index=["x", "y"], + ) + + +@pytest.fixture +def styler(df): + return Styler(df, uuid_len=0) + + +def test_concat_bad_columns(styler): + msg = "`other.data` must have same columns as `Styler.data" + with pytest.raises(ValueError, match=msg): + styler.concat(pd.DataFrame([[1, 2]]).style) + + +def test_concat_bad_type(styler): + msg = "`other` must be of type `Styler`" + with pytest.raises(TypeError, match=msg): + styler.concat(pd.DataFrame([[1, 2]])) + + +def test_concat_bad_index_levels(styler, df): + df = df.copy() + df.index = pd.MultiIndex.from_tuples([(0, 0), (1, 1)]) + msg = "number of index levels must be same in `other`" + with pytest.raises(ValueError, match=msg): + styler.concat(df.style) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_format.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..e2fed940f8eaa2193ea783d87193d47ce0e88e82 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_format.py @@ -0,0 +1,692 @@ +from types import MappingProxyType + +import numpy as np +import pytest + +import pandas as pd + +pytest.importorskip("jinja2") +from pandas.io.formats.style import Styler +from pandas.io.formats.style_render import _str_escape + + +@pytest.fixture +def df(): + return pd.DataFrame( + data=[[0, -0.609], [1, -1.228]], + columns=["A", "B"], + index=["x", "y"], + ) + + +@pytest.fixture +def styler(df): + return Styler(df, uuid_len=0) + + +@pytest.fixture +def df_multi(): + return ( + pd.DataFrame( + data=np.arange(16).reshape(4, 4), + columns=pd.MultiIndex.from_product([["A", "B"], ["a", "b"]]), + index=pd.MultiIndex.from_product([["X", "Y"], ["x", "y"]]), + ) + .rename_axis(["0_0", "0_1"], axis=0) + .rename_axis(["1_0", "1_1"], axis=1) + ) + + +@pytest.fixture +def styler_multi(df_multi): + return Styler(df_multi, uuid_len=0) + + +def test_display_format(styler): + ctx = styler.format("{:0.1f}")._translate(True, True) + assert all(["display_value" in c for c in row] for row in ctx["body"]) + assert all([len(c["display_value"]) <= 3 for c in row[1:]] for row in ctx["body"]) + assert len(ctx["body"][0][1]["display_value"].lstrip("-")) <= 3 + + +@pytest.mark.parametrize("index", [True, False]) +@pytest.mark.parametrize("columns", [True, False]) +def test_display_format_index(styler, index, columns): + exp_index = ["x", "y"] + if index: + styler.format_index(lambda v: v.upper(), axis=0) # test callable + exp_index = ["X", "Y"] + + exp_columns = ["A", "B"] + if columns: + styler.format_index("*{}*", axis=1) # test string + exp_columns = ["*A*", "*B*"] + + ctx = styler._translate(True, True) + + for r, row in enumerate(ctx["body"]): + assert row[0]["display_value"] == exp_index[r] + + for c, col in enumerate(ctx["head"][1:]): + assert col["display_value"] == exp_columns[c] + + +def test_format_dict(styler): + ctx = styler.format({"A": "{:0.1f}", "B": "{0:.2%}"})._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "0.0" + assert ctx["body"][0][2]["display_value"] == "-60.90%" + + +def test_format_mapping(styler: Styler) -> None: + """Accept read-only mappings for column formatters.""" + formatter = MappingProxyType({"A": "{:0.1f}", "B": "{0:.2%}"}) + ctx = styler.format(formatter)._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "0.0" + assert ctx["body"][0][2]["display_value"] == "-60.90%" + + +def test_format_index_dict(styler): + ctx = styler.format_index({0: lambda v: v.upper()})._translate(True, True) + for i, val in enumerate(["X", "Y"]): + assert ctx["body"][i][0]["display_value"] == val + + +def test_format_index_mapping(styler: Styler) -> None: + """Accept read-only mappings for index formatters.""" + formatter = MappingProxyType({0: lambda value: value.upper()}) + ctx = styler.format_index(formatter)._translate(True, True) + for row_idx, value in enumerate(["X", "Y"]): + assert ctx["body"][row_idx][0]["display_value"] == value + + +def test_format_string(styler): + ctx = styler.format("{:.2f}")._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "0.00" + assert ctx["body"][0][2]["display_value"] == "-0.61" + assert ctx["body"][1][1]["display_value"] == "1.00" + assert ctx["body"][1][2]["display_value"] == "-1.23" + + +def test_format_callable(styler): + ctx = styler.format(lambda v: "neg" if v < 0 else "pos")._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "pos" + assert ctx["body"][0][2]["display_value"] == "neg" + assert ctx["body"][1][1]["display_value"] == "pos" + assert ctx["body"][1][2]["display_value"] == "neg" + + +def test_format_with_na_rep(): + # GH 21527 28358 + df = pd.DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"]) + + ctx = df.style.format(None, na_rep="-")._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "-" + assert ctx["body"][0][2]["display_value"] == "-" + + ctx = df.style.format("{:.2%}", na_rep="-")._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "-" + assert ctx["body"][0][2]["display_value"] == "-" + assert ctx["body"][1][1]["display_value"] == "110.00%" + assert ctx["body"][1][2]["display_value"] == "120.00%" + + ctx = df.style.format("{:.2%}", na_rep="-", subset=["B"])._translate(True, True) + assert ctx["body"][0][2]["display_value"] == "-" + assert ctx["body"][1][2]["display_value"] == "120.00%" + + +def test_format_index_with_na_rep(): + df = pd.DataFrame([[1, 2, 3, 4, 5]], columns=["A", None, np.nan, pd.NaT, pd.NA]) + ctx = df.style.format_index(None, na_rep="--", axis=1)._translate(True, True) + assert ctx["head"][0][1]["display_value"] == "A" + for i in [2, 3, 4, 5]: + assert ctx["head"][0][i]["display_value"] == "--" + + +def test_format_non_numeric_na(): + # GH 21527 28358 + df = pd.DataFrame( + { + "object": [None, np.nan, "foo"], + "datetime": [None, pd.NaT, pd.Timestamp("20120101")], + } + ) + ctx = df.style.format(None, na_rep="-")._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "-" + assert ctx["body"][0][2]["display_value"] == "-" + assert ctx["body"][1][1]["display_value"] == "-" + assert ctx["body"][1][2]["display_value"] == "-" + + +@pytest.mark.parametrize( + "func, attr, kwargs", + [ + ("format", "_display_funcs", {}), + ("format_index", "_display_funcs_index", {"axis": 0}), + ("format_index", "_display_funcs_columns", {"axis": 1}), + ], +) +def test_format_clear(styler, func, attr, kwargs): + assert (0, 0) not in getattr(styler, attr) # using default + getattr(styler, func)("{:.2f}", **kwargs) + assert (0, 0) in getattr(styler, attr) # formatter is specified + getattr(styler, func)(**kwargs) + assert (0, 0) not in getattr(styler, attr) # formatter cleared to default + + +@pytest.mark.parametrize( + "escape, exp", + [ + ("html", "<>&"%$#_{}~^\\~ ^ \\ "), + ( + "latex", + '<>\\&"\\%\\$\\#\\_\\{\\}\\textasciitilde \\textasciicircum ' + "\\textbackslash \\textasciitilde \\space \\textasciicircum \\space " + "\\textbackslash \\space ", + ), + ], +) +def test_format_escape_html(escape, exp): + chars = '<>&"%$#_{}~^\\~ ^ \\ ' + df = pd.DataFrame([[chars]]) + + s = Styler(df, uuid_len=0).format("&{0}&", escape=None) + expected = f'&{chars}&' + assert expected in s.to_html() + + # only the value should be escaped before passing to the formatter + s = Styler(df, uuid_len=0).format("&{0}&", escape=escape) + expected = f'&{exp}&' + assert expected in s.to_html() + + # also test format_index() + styler = Styler(pd.DataFrame(columns=[chars]), uuid_len=0) + styler.format_index("&{0}&", escape=None, axis=1) + assert styler._translate(True, True)["head"][0][1]["display_value"] == f"&{chars}&" + styler.format_index("&{0}&", escape=escape, axis=1) + assert styler._translate(True, True)["head"][0][1]["display_value"] == f"&{exp}&" + + +@pytest.mark.parametrize( + "chars, expected", + [ + ( + r"$ \$&%#_{}~^\ $ &%#_{}~^\ $", + "".join( + [ + r"$ \$&%#_{}~^\ $ ", + r"\&\%\#\_\{\}\textasciitilde \textasciicircum ", + r"\textbackslash \space \$", + ] + ), + ), + ( + r"\( &%#_{}~^\ \) &%#_{}~^\ \(", + "".join( + [ + r"\( &%#_{}~^\ \) ", + r"\&\%\#\_\{\}\textasciitilde \textasciicircum ", + r"\textbackslash \space \textbackslash (", + ] + ), + ), + ( + r"$\&%#_{}^\$", + r"\$\textbackslash \&\%\#\_\{\}\textasciicircum \textbackslash \$", + ), + ( + r"$ \frac{1}{2} $ \( \frac{1}{2} \)", + "".join( + [ + r"$ \frac{1}{2} $", + r" \textbackslash ( \textbackslash frac\{1\}\{2\} \textbackslash )", + ] + ), + ), + ], +) +def test_format_escape_latex_math(chars, expected): + # GH 51903 + # latex-math escape works for each DataFrame cell separately. If we have + # a combination of dollar signs and brackets, the dollar sign would apply. + df = pd.DataFrame([[chars]]) + s = df.style.format("{0}", escape="latex-math") + assert s._translate(True, True)["body"][0][1]["display_value"] == expected + + +def test_format_escape_na_rep(): + # tests the na_rep is not escaped + df = pd.DataFrame([['<>&"', None]]) + s = Styler(df, uuid_len=0).format("X&{0}>X", escape="html", na_rep="&") + ex = 'X&<>&">X' + expected2 = '&' + assert ex in s.to_html() + assert expected2 in s.to_html() + + # also test for format_index() + df = pd.DataFrame(columns=['<>&"', None]) + styler = Styler(df, uuid_len=0) + styler.format_index("X&{0}>X", escape="html", na_rep="&", axis=1) + ctx = styler._translate(True, True) + assert ctx["head"][0][1]["display_value"] == "X&<>&">X" + assert ctx["head"][0][2]["display_value"] == "&" + + +def test_format_escape_floats(styler): + # test given formatter for number format is not impacted by escape + s = styler.format("{:.1f}", escape="html") + for expected in [">0.0<", ">1.0<", ">-1.2<", ">-0.6<"]: + assert expected in s.to_html() + # tests precision of floats is not impacted by escape + s = styler.format(precision=1, escape="html") + for expected in [">0<", ">1<", ">-1.2<", ">-0.6<"]: + assert expected in s.to_html() + + +@pytest.mark.parametrize("formatter", [5, True, [2.0]]) +@pytest.mark.parametrize("func", ["format", "format_index"]) +def test_format_raises(styler, formatter, func): + with pytest.raises(TypeError, match="expected str or callable"): + getattr(styler, func)(formatter) + + +@pytest.mark.parametrize( + "precision, expected", + [ + (1, ["1.0", "2.0", "3.2", "4.6"]), + (2, ["1.00", "2.01", "3.21", "4.57"]), + (3, ["1.000", "2.009", "3.212", "4.566"]), + ], +) +def test_format_with_precision(precision, expected): + # Issue #13257 + df = pd.DataFrame( + [[1.0, 2.0090, 3.2121, 4.566]], columns=[1.0, 2.0090, 3.2121, 4.566] + ) + styler = Styler(df) + styler.format(precision=precision) + styler.format_index(precision=precision, axis=1) + + ctx = styler._translate(True, True) + for col, exp in enumerate(expected): + assert ctx["body"][0][col + 1]["display_value"] == exp # format test + assert ctx["head"][0][col + 1]["display_value"] == exp # format_index test + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize( + "level, expected", + [ + (0, ["X", "X", "_", "_"]), # level int + ("zero", ["X", "X", "_", "_"]), # level name + (1, ["_", "_", "X", "X"]), # other level int + ("one", ["_", "_", "X", "X"]), # other level name + ([0, 1], ["X", "X", "X", "X"]), # both levels + ([0, "zero"], ["X", "X", "_", "_"]), # level int and name simultaneous + ([0, "one"], ["X", "X", "X", "X"]), # both levels as int and name + (["one", "zero"], ["X", "X", "X", "X"]), # both level names, reversed + ], +) +def test_format_index_level(axis, level, expected): + midx = pd.MultiIndex.from_arrays([["_", "_"], ["_", "_"]], names=["zero", "one"]) + df = pd.DataFrame([[1, 2], [3, 4]]) + if axis == 0: + df.index = midx + else: + df.columns = midx + + styler = df.style.format_index(lambda v: "X", level=level, axis=axis) + ctx = styler._translate(True, True) + + if axis == 0: # compare index + result = [ctx["body"][s][0]["display_value"] for s in range(2)] + result += [ctx["body"][s][1]["display_value"] for s in range(2)] + else: # compare columns + result = [ctx["head"][0][s + 1]["display_value"] for s in range(2)] + result += [ctx["head"][1][s + 1]["display_value"] for s in range(2)] + + assert expected == result + + +def test_format_subset(): + df = pd.DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"]) + ctx = df.style.format( + {"a": "{:0.1f}", "b": "{0:.2%}"}, subset=pd.IndexSlice[0, :] + )._translate(True, True) + expected = "0.1" + raw_11 = "1.123400" + assert ctx["body"][0][1]["display_value"] == expected + assert ctx["body"][1][1]["display_value"] == raw_11 + assert ctx["body"][0][2]["display_value"] == "12.34%" + + ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, :])._translate(True, True) + assert ctx["body"][0][1]["display_value"] == expected + assert ctx["body"][1][1]["display_value"] == raw_11 + + ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice["a"])._translate(True, True) + assert ctx["body"][0][1]["display_value"] == expected + assert ctx["body"][0][2]["display_value"] == "0.123400" + + ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, "a"])._translate( + True, True + ) + assert ctx["body"][0][1]["display_value"] == expected + assert ctx["body"][1][1]["display_value"] == raw_11 + + ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[[0, 1], ["a"]])._translate( + True, True + ) + assert ctx["body"][0][1]["display_value"] == expected + assert ctx["body"][1][1]["display_value"] == "1.1" + assert ctx["body"][0][2]["display_value"] == "0.123400" + assert ctx["body"][1][2]["display_value"] == raw_11 + + +@pytest.mark.parametrize("formatter", [None, "{:,.1f}"]) +@pytest.mark.parametrize("decimal", [".", "*"]) +@pytest.mark.parametrize("precision", [None, 2]) +@pytest.mark.parametrize("func, col", [("format", 1), ("format_index", 0)]) +def test_format_thousands(formatter, decimal, precision, func, col): + styler = pd.DataFrame([[1000000.123456789]], index=[1000000.123456789]).style + result = getattr(styler, func)( # testing float + thousands="_", formatter=formatter, decimal=decimal, precision=precision + )._translate(True, True) + assert "1_000_000" in result["body"][0][col]["display_value"] + + styler = pd.DataFrame([[1000000]], index=[1000000]).style + result = getattr(styler, func)( # testing int + thousands="_", formatter=formatter, decimal=decimal, precision=precision + )._translate(True, True) + assert "1_000_000" in result["body"][0][col]["display_value"] + + styler = pd.DataFrame( + [[1 + 1000000.123456789j]], index=[1 + 1000000.123456789j] + ).style + result = getattr(styler, func)( # testing complex + thousands="_", formatter=formatter, decimal=decimal, precision=precision + )._translate(True, True) + assert "1_000_000" in result["body"][0][col]["display_value"] + + +@pytest.mark.parametrize("formatter", [None, "{:,.4f}"]) +@pytest.mark.parametrize("thousands", [None, ",", "*"]) +@pytest.mark.parametrize("precision", [None, 4]) +@pytest.mark.parametrize("func, col", [("format", 1), ("format_index", 0)]) +def test_format_decimal(formatter, thousands, precision, func, col): + styler = pd.DataFrame([[1000000.123456789]], index=[1000000.123456789]).style + result = getattr(styler, func)( # testing float + decimal="_", formatter=formatter, thousands=thousands, precision=precision + )._translate(True, True) + assert "000_123" in result["body"][0][col]["display_value"] + + styler = pd.DataFrame( + [[1 + 1000000.123456789j]], index=[1 + 1000000.123456789j] + ).style + result = getattr(styler, func)( # testing complex + decimal="_", formatter=formatter, thousands=thousands, precision=precision + )._translate(True, True) + assert "000_123" in result["body"][0][col]["display_value"] + + +def test_str_escape_error(): + msg = "`escape` only permitted in {'html', 'latex', 'latex-math'}, got " + with pytest.raises(ValueError, match=msg): + _str_escape("text", "bad_escape") + + with pytest.raises(ValueError, match=msg): + _str_escape("text", []) + + _str_escape(2.00, "bad_escape") # OK since dtype is float + + +def test_long_int_formatting(): + df = pd.DataFrame(data=[[1234567890123456789]], columns=["test"]) + styler = df.style + ctx = styler._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "1234567890123456789" + + styler = df.style.format(thousands="_") + ctx = styler._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "1_234_567_890_123_456_789" + + +def test_format_options(): + df = pd.DataFrame({"int": [2000, 1], "float": [1.009, None], "str": ["&<", "&~"]}) + ctx = df.style._translate(True, True) + + # test option: na_rep + assert ctx["body"][1][2]["display_value"] == "nan" + with pd.option_context("styler.format.na_rep", "MISSING"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][1][2]["display_value"] == "MISSING" + + # test option: decimal and precision + assert ctx["body"][0][2]["display_value"] == "1.009000" + with pd.option_context("styler.format.decimal", "_"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][2]["display_value"] == "1_009000" + with pd.option_context("styler.format.precision", 2): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][2]["display_value"] == "1.01" + + # test option: thousands + assert ctx["body"][0][1]["display_value"] == "2000" + with pd.option_context("styler.format.thousands", "_"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][1]["display_value"] == "2_000" + + # test option: escape + assert ctx["body"][0][3]["display_value"] == "&<" + assert ctx["body"][1][3]["display_value"] == "&~" + with pd.option_context("styler.format.escape", "html"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][3]["display_value"] == "&<" + with pd.option_context("styler.format.escape", "latex"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][1][3]["display_value"] == "\\&\\textasciitilde " + with pd.option_context("styler.format.escape", "latex-math"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][1][3]["display_value"] == "\\&\\textasciitilde " + + # test option: formatter + with pd.option_context("styler.format.formatter", {"int": "{:,.2f}"}): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][1]["display_value"] == "2,000.00" + + +def test_precision_zero(df): + styler = Styler(df, precision=0) + ctx = styler._translate(True, True) + assert ctx["body"][0][2]["display_value"] == "-1" + assert ctx["body"][1][2]["display_value"] == "-1" + + +@pytest.mark.parametrize( + "formatter, exp", + [ + (lambda x: f"{x:.3f}", "9.000"), + ("{:.2f}", "9.00"), + ({0: "{:.1f}"}, "9.0"), + (None, "9"), + ], +) +def test_formatter_options_validator(formatter, exp): + df = pd.DataFrame([[9]]) + with pd.option_context("styler.format.formatter", formatter): + assert f" {exp} " in df.style.to_latex() + + +def test_formatter_options_raises(): + msg = "Value must be an instance of" + with pytest.raises(ValueError, match=msg): + with pd.option_context("styler.format.formatter", ["bad", "type"]): + pd.DataFrame().style.to_latex() + + +def test_1level_multiindex(): + # GH 43383 + midx = pd.MultiIndex.from_product([[1, 2]], names=[""]) + df = pd.DataFrame(-1, index=midx, columns=[0, 1]) + ctx = df.style._translate(True, True) + assert ctx["body"][0][0]["display_value"] == "1" + assert ctx["body"][0][0]["is_visible"] is True + assert ctx["body"][1][0]["display_value"] == "2" + assert ctx["body"][1][0]["is_visible"] is True + + +def test_boolean_format(): + # gh 46384: booleans do not collapse to integer representation on display + df = pd.DataFrame([[True, False]]) + ctx = df.style._translate(True, True) + assert ctx["body"][0][1]["display_value"] is True + assert ctx["body"][0][2]["display_value"] is False + + +@pytest.mark.parametrize( + "hide, labels", + [ + (False, [1, 2]), + (True, [1, 2, 3, 4]), + ], +) +def test_relabel_raise_length(styler_multi, hide, labels): + if hide: + styler_multi.hide(axis=0, subset=[("X", "x"), ("Y", "y")]) + with pytest.raises(ValueError, match="``labels`` must be of length equal"): + styler_multi.relabel_index(labels=labels) + + +def test_relabel_index(styler_multi): + labels = [(1, 2), (3, 4)] + styler_multi.hide(axis=0, subset=[("X", "x"), ("Y", "y")]) + styler_multi.relabel_index(labels=labels) + ctx = styler_multi._translate(True, True) + assert {"value": "X", "display_value": 1}.items() <= ctx["body"][0][0].items() + assert {"value": "y", "display_value": 2}.items() <= ctx["body"][0][1].items() + assert {"value": "Y", "display_value": 3}.items() <= ctx["body"][1][0].items() + assert {"value": "x", "display_value": 4}.items() <= ctx["body"][1][1].items() + + +def test_relabel_columns(styler_multi): + labels = [(1, 2), (3, 4)] + styler_multi.hide(axis=1, subset=[("A", "a"), ("B", "b")]) + styler_multi.relabel_index(axis=1, labels=labels) + ctx = styler_multi._translate(True, True) + assert {"value": "A", "display_value": 1}.items() <= ctx["head"][0][3].items() + assert {"value": "B", "display_value": 3}.items() <= ctx["head"][0][4].items() + assert {"value": "b", "display_value": 2}.items() <= ctx["head"][1][3].items() + assert {"value": "a", "display_value": 4}.items() <= ctx["head"][1][4].items() + + +def test_relabel_roundtrip(styler): + styler.relabel_index(["{}", "{}"]) + ctx = styler._translate(True, True) + assert {"value": "x", "display_value": "x"}.items() <= ctx["body"][0][0].items() + assert {"value": "y", "display_value": "y"}.items() <= ctx["body"][1][0].items() + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize( + "level, expected", + [ + (0, ["X", "one"]), # level int + ("zero", ["X", "one"]), # level name + (1, ["zero", "X"]), # other level int + ("one", ["zero", "X"]), # other level name + ([0, 1], ["X", "X"]), # both levels + ([0, "zero"], ["X", "one"]), # level int and name simultaneous + ([0, "one"], ["X", "X"]), # both levels as int and name + (["one", "zero"], ["X", "X"]), # both level names, reversed + ], +) +def test_format_index_names_level(axis, level, expected): + midx = pd.MultiIndex.from_arrays([["_", "_"], ["_", "_"]], names=["zero", "one"]) + df = pd.DataFrame([[1, 2], [3, 4]]) + if axis == 0: + df.index = midx + else: + df.columns = midx + + styler = df.style.format_index_names(lambda v: "X", level=level, axis=axis) + ctx = styler._translate(True, True) + + if axis == 0: # compare index + result = [ctx["head"][1][s]["display_value"] for s in range(2)] + else: # compare columns + result = [ctx["head"][s][0]["display_value"] for s in range(2)] + assert expected == result + + +@pytest.mark.parametrize( + "attr, kwargs", + [ + ("_display_funcs_index_names", {"axis": 0}), + ("_display_funcs_column_names", {"axis": 1}), + ], +) +def test_format_index_names_clear(styler, attr, kwargs): + assert 0 not in getattr(styler, attr) # using default + styler.format_index_names("{:.2f}", **kwargs) + assert 0 in getattr(styler, attr) # formatter is specified + styler.format_index_names(**kwargs) + assert 0 not in getattr(styler, attr) # formatter cleared to default + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_format_index_names_callable(styler_multi, axis): + ctx = styler_multi.format_index_names( + lambda v: v.replace("_", "A"), axis=axis + )._translate(True, True) + result = [ + ctx["head"][2][0]["display_value"], + ctx["head"][2][1]["display_value"], + ctx["head"][0][1]["display_value"], + ctx["head"][1][1]["display_value"], + ] + if axis == 0: + expected = ["0A0", "0A1", "1_0", "1_1"] + else: + expected = ["0_0", "0_1", "1A0", "1A1"] + assert result == expected + + +def test_format_index_names_dict(styler_multi): + ctx = ( + styler_multi.format_index_names({"0_0": "{:<<5}"}) + .format_index_names({"1_1": "{:>>4}"}, axis=1) + ._translate(True, True) + ) + assert ctx["head"][2][0]["display_value"] == "0_0<<" + assert ctx["head"][1][1]["display_value"] == ">1_1" + + +def test_format_index_names_mapping(styler_multi: Styler) -> None: + """Accept read-only mappings for index-name formatters.""" + index_formatter = MappingProxyType({"0_0": "{:<<5}"}) + column_formatter = MappingProxyType({"1_1": "{:>>4}"}) + ctx = ( + styler_multi.format_index_names(index_formatter) + .format_index_names(column_formatter, axis=1) + ._translate(True, True) + ) + assert ctx["head"][2][0]["display_value"] == "0_0<<" + assert ctx["head"][1][1]["display_value"] == ">1_1" + + +def test_format_index_names_with_hidden_levels(styler_multi): + ctx = styler_multi._translate(True, True) + full_head_height = len(ctx["head"]) + full_head_width = len(ctx["head"][0]) + assert full_head_height == 3 + assert full_head_width == 6 + + ctx = ( + styler_multi.hide(axis=0, level=1) + .hide(axis=1, level=1) + .format_index_names("{:>>4}", axis=1) + .format_index_names("{:!<5}") + ._translate(True, True) + ) + assert len(ctx["head"]) == full_head_height - 1 + assert len(ctx["head"][0]) == full_head_width - 1 + assert ctx["head"][0][0]["display_value"] == ">1_0" + assert ctx["head"][1][0]["display_value"] == "0_0!!" diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_highlight.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_highlight.py new file mode 100644 index 0000000000000000000000000000000000000000..060f58a1826e8863cf2c95cb3e1a284a603c8ce0 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_highlight.py @@ -0,0 +1,220 @@ +import numpy as np +import pytest + +import pandas as pd + +pytest.importorskip("jinja2") + +from pandas.io.formats.style import Styler + + +@pytest.fixture(params=[(None, "float64"), (pd.NA, "Int64")]) +def df(request): + # GH 45804 + dtype = request.param[1] + item = np.nan if dtype == "float64" else pd.NA + return pd.DataFrame( + {"A": [0, item, 10], "B": [1, request.param[0], 2]}, dtype=request.param[1] + ) + + +@pytest.fixture +def styler(df): + return Styler(df, uuid_len=0) + + +def test_highlight_null(styler): + result = styler.highlight_null()._compute().ctx + expected = { + (1, 0): [("background-color", "red")], + (1, 1): [("background-color", "red")], + } + assert result == expected + + +def test_highlight_null_subset(styler): + # GH 31345 + result = ( + styler.highlight_null(color="red", subset=["A"]) + .highlight_null(color="green", subset=["B"]) + ._compute() + .ctx + ) + expected = { + (1, 0): [("background-color", "red")], + (1, 1): [("background-color", "green")], + } + assert result == expected + + +@pytest.mark.parametrize("f", ["highlight_min", "highlight_max"]) +def test_highlight_minmax_basic(df, f): + expected = { + (0, 1): [("background-color", "red")], + # ignores NaN row, + (2, 0): [("background-color", "red")], + } + if f == "highlight_min": + df = -df + result = getattr(df.style, f)(axis=1, color="red")._compute().ctx + assert result == expected + + +@pytest.mark.parametrize("f", ["highlight_min", "highlight_max"]) +@pytest.mark.parametrize( + "kwargs", + [ + {"axis": None, "color": "red"}, # test axis + {"axis": 0, "subset": ["A"], "color": "red"}, # test subset and ignores NaN + {"axis": None, "props": "background-color: red"}, # test props + ], +) +def test_highlight_minmax_ext(df, f, kwargs): + expected = {(2, 0): [("background-color", "red")]} + if f == "highlight_min": + df = -df + result = getattr(df.style, f)(**kwargs)._compute().ctx + assert result == expected + + +@pytest.mark.parametrize("f", ["highlight_min", "highlight_max"]) +@pytest.mark.parametrize("axis", [None, 0, 1]) +def test_highlight_minmax_nulls(f, axis): + # GH 42750 + expected = { + (1, 0): [("background-color", "yellow")], + (1, 1): [("background-color", "yellow")], + } + if axis == 1: + expected.update({(2, 1): [("background-color", "yellow")]}) + + if f == "highlight_max": + df = pd.DataFrame({"a": [pd.NA, 1, None], "b": [np.nan, 1, -1]}) + else: + df = pd.DataFrame({"a": [pd.NA, -1, None], "b": [np.nan, -1, 1]}) + + result = getattr(df.style, f)(axis=axis)._compute().ctx + assert result == expected + + +@pytest.mark.parametrize( + "kwargs", + [ + {"left": 0, "right": 1}, # test basic range + {"left": 0, "right": 1, "props": "background-color: yellow"}, # test props + {"left": -100, "right": 100, "subset": pd.IndexSlice[[0, 1], :]}, # test subset + {"left": 0, "subset": pd.IndexSlice[[0, 1], :]}, # test no right + {"right": 1}, # test no left + {"left": [0, 0, 11], "axis": 0}, # test left as sequence + { + "left": pd.DataFrame({"A": [0, 0, 11], "B": [1, 1, 11]}), + "axis": None, + }, # axis + {"left": 0, "right": [0, 1], "axis": 1}, # test sequence right + ], +) +def test_highlight_between(styler, kwargs): + expected = { + (0, 0): [("background-color", "yellow")], + (0, 1): [("background-color", "yellow")], + } + result = styler.highlight_between(**kwargs)._compute().ctx + assert result == expected + + +@pytest.mark.parametrize( + "arg, map, axis", + [ + ("left", [1, 2], 0), # 0 axis has 3 elements not 2 + ("left", [1, 2, 3], 1), # 1 axis has 2 elements not 3 + ("left", np.array([[1, 2], [1, 2]]), None), # df is (2,3) not (2,2) + ("right", [1, 2], 0), # same tests as above for 'right' not 'left' + ("right", [1, 2, 3], 1), # .. + ("right", np.array([[1, 2], [1, 2]]), None), # .. + ], +) +def test_highlight_between_raises(arg, styler, map, axis): + msg = f"supplied '{arg}' is not correct shape" + with pytest.raises(ValueError, match=msg): + styler.highlight_between(**{arg: map, "axis": axis})._compute() + + +def test_highlight_between_raises2(styler): + msg = "values can be 'both', 'left', 'right', or 'neither'" + with pytest.raises(ValueError, match=msg): + styler.highlight_between(inclusive="badstring")._compute() + + with pytest.raises(ValueError, match=msg): + styler.highlight_between(inclusive=1)._compute() + + +@pytest.mark.parametrize( + "inclusive, expected", + [ + ( + "both", + { + (0, 0): [("background-color", "yellow")], + (0, 1): [("background-color", "yellow")], + }, + ), + ("neither", {}), + ("left", {(0, 0): [("background-color", "yellow")]}), + ("right", {(0, 1): [("background-color", "yellow")]}), + ], +) +def test_highlight_between_inclusive(styler, inclusive, expected): + kwargs = {"left": 0, "right": 1, "subset": pd.IndexSlice[[0, 1], :]} + result = styler.highlight_between(**kwargs, inclusive=inclusive)._compute() + assert result.ctx == expected + + +@pytest.mark.parametrize( + "kwargs", + [ + {"q_left": 0.5, "q_right": 1, "axis": 0}, # base case + {"q_left": 0.5, "q_right": 1, "axis": None}, # test axis + {"q_left": 0, "q_right": 1, "subset": pd.IndexSlice[2, :]}, # test subset + {"q_left": 0.5, "axis": 0}, # test no high + {"q_right": 1, "subset": pd.IndexSlice[2, :], "axis": 1}, # test no low + {"q_left": 0.5, "axis": 0, "props": "background-color: yellow"}, # tst prop + ], +) +def test_highlight_quantile(styler, kwargs): + expected = { + (2, 0): [("background-color", "yellow")], + (2, 1): [("background-color", "yellow")], + } + result = styler.highlight_quantile(**kwargs)._compute().ctx + assert result == expected + + +@pytest.mark.parametrize( + "f,kwargs", + [ + ("highlight_min", {"axis": 1, "subset": pd.IndexSlice[1, :]}), + ("highlight_max", {"axis": 0, "subset": [0]}), + ("highlight_quantile", {"axis": None, "q_left": 0.6, "q_right": 0.8}), + ("highlight_between", {"subset": [0]}), + ], +) +@pytest.mark.parametrize( + "dtype", + [ + int, + float, + "datetime64[ns]", + str, + "timedelta64[ns]", + ], +) +def test_all_highlight_dtypes(f, kwargs, dtype): + df = pd.DataFrame([[0, 10], [20, 30]], dtype=dtype) + if f == "highlight_quantile" and isinstance(df.iloc[0, 0], (str)): + return None # quantile incompatible with str + if f == "highlight_between": + kwargs["left"] = df.iloc[1, 0] # set the range low for testing + + expected = {(1, 0): [("background-color", "yellow")]} + result = getattr(df.style, f)(**kwargs)._compute().ctx + assert result == expected diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_html.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_html.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ee5fb3850feee79dce9fbf22c1f931168c7f9c --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_html.py @@ -0,0 +1,1039 @@ +import pathlib +from textwrap import ( + dedent, + indent, +) + +import numpy as np +import pytest + +import pandas as pd + +jinja2 = pytest.importorskip("jinja2") +from pandas.io.formats.style import Styler + + +@pytest.fixture +def env(): + project_dir = pathlib.Path(__file__).parent.parent.parent.parent.parent.resolve() + template_dir = project_dir / "io" / "formats" / "templates" + loader = jinja2.FileSystemLoader(template_dir) + env = jinja2.Environment(loader=loader, trim_blocks=True) + return env + + +@pytest.fixture +def styler(): + return Styler(pd.DataFrame([[2.61], [2.69]], index=["a", "b"], columns=["A"])) + + +@pytest.fixture +def styler_mi(): + midx = pd.MultiIndex.from_product([["a", "b"], ["c", "d"]]) + return Styler(pd.DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=midx)) + + +@pytest.fixture +def styler_multi(): + df = pd.DataFrame( + data=np.arange(16).reshape(4, 4), + columns=pd.MultiIndex.from_product( + [["A", "B"], ["a", "b"]], names=["A&", "b&"] + ), + index=pd.MultiIndex.from_product([["X", "Y"], ["x", "y"]], names=["X>", "y_"]), + ) + return Styler(df) + + +@pytest.fixture +def tpl_style(env): + return env.get_template("html_style.tpl") + + +@pytest.fixture +def tpl_table(env): + return env.get_template("html_table.tpl") + + +def test_html_template_extends_options(datapath): + # make sure if templates are edited tests are updated as are setup fixtures + # to understand the dependency + path = datapath("..", "io", "formats", "templates", "html.tpl") + with open(path, encoding="utf-8") as file: + result = file.read() + assert "{% include html_style_tpl %}" in result + assert "{% include html_table_tpl %}" in result + + +def test_exclude_styles(styler): + result = styler.to_html(exclude_styles=True, doctype_html=True) + expected = dedent( + """\ + + + + + + + + + + + + + + + + + + + + + + + +
 A
a2.610000
b2.690000
+ + + """ + ) + assert result == expected + + +def test_w3_html_format(styler): + styler.set_uuid("").set_table_styles([{"selector": "th", "props": "att2:v2;"}]).map( + lambda x: "att1:v1;" + ).set_table_attributes('class="my-cls1" style="attr3:v3;"').set_td_classes( + pd.DataFrame(["my-cls2"], index=["a"], columns=["A"]) + ).format("{:.1f}").set_caption("A comprehensive test") + expected = dedent( + """\ + + + + + + + + + + + + + + + + + + + +
A comprehensive test
 A
a2.6
b2.7
+ """ + ) + assert expected == styler.to_html() + + +def test_colspan_w3(): + # GH 36223 + df = pd.DataFrame(data=[[1, 2]], columns=[["l0", "l0"], ["l1a", "l1b"]]) + styler = Styler(df, uuid="_", cell_ids=False) + assert 'l0' in styler.to_html() + + +def test_rowspan_w3(): + # GH 38533 + df = pd.DataFrame(data=[[1, 2]], index=[["l0", "l0"], ["l1a", "l1b"]]) + styler = Styler(df, uuid="_", cell_ids=False) + assert 'l0' in styler.to_html() + + +def test_styles(styler): + styler.set_uuid("abc") + styler.set_table_styles([{"selector": "td", "props": "color: red;"}]) + result = styler.to_html(doctype_html=True) + expected = dedent( + """\ + + + + + + + + + + + + + + + + + + + + + + + + +
 A
a2.610000
b2.690000
+ + + """ + ) + assert result == expected + + +def test_doctype(styler): + result = styler.to_html(doctype_html=False) + assert "" not in result + assert "" not in result + assert "" not in result + assert "" not in result + + +def test_doctype_encoding(styler): + with pd.option_context("styler.render.encoding", "ASCII"): + result = styler.to_html(doctype_html=True) + assert '' in result + result = styler.to_html(doctype_html=True, encoding="ANSI") + assert '' in result + + +def test_bold_headers_arg(styler): + result = styler.to_html(bold_headers=True) + assert "th {\n font-weight: bold;\n}" in result + result = styler.to_html() + assert "th {\n font-weight: bold;\n}" not in result + + +def test_caption_arg(styler): + result = styler.to_html(caption="foo bar") + assert "foo bar" in result + result = styler.to_html() + assert "foo bar" not in result + + +def test_block_names(tpl_style, tpl_table): + # catch accidental removal of a block + expected_style = { + "before_style", + "style", + "table_styles", + "before_cellstyle", + "cellstyle", + } + expected_table = { + "before_table", + "table", + "caption", + "thead", + "tbody", + "after_table", + "before_head_rows", + "head_tr", + "after_head_rows", + "before_rows", + "tr", + "after_rows", + } + result1 = set(tpl_style.blocks) + assert result1 == expected_style + + result2 = set(tpl_table.blocks) + assert result2 == expected_table + + +def test_from_custom_template_table(tmpdir): + p = tmpdir.mkdir("tpl").join("myhtml_table.tpl") + p.write( + dedent( + """\ + {% extends "html_table.tpl" %} + {% block table %} +

{{custom_title}}

+ {{ super() }} + {% endblock table %}""" + ) + ) + result = Styler.from_custom_template(str(tmpdir.join("tpl")), "myhtml_table.tpl") + assert issubclass(result, Styler) + assert result.env is not Styler.env + assert result.template_html_table is not Styler.template_html_table + styler = result(pd.DataFrame({"A": [1, 2]})) + assert "

My Title

\n\n\n + {{ super() }} + {% endblock style %}""" + ) + ) + result = Styler.from_custom_template( + str(tmpdir.join("tpl")), html_style="myhtml_style.tpl" + ) + assert issubclass(result, Styler) + assert result.env is not Styler.env + assert result.template_html_style is not Styler.template_html_style + styler = result(pd.DataFrame({"A": [1, 2]})) + assert '\n\nfull cap" in styler.to_html() + + +@pytest.mark.parametrize("index", [False, True]) +@pytest.mark.parametrize("columns", [False, True]) +@pytest.mark.parametrize("index_name", [True, False]) +def test_sticky_basic(styler, index, columns, index_name): + if index_name: + styler.index.name = "some text" + if index: + styler.set_sticky(axis=0) + if columns: + styler.set_sticky(axis=1) + + left_css = ( + "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n" + " left: 0px;\n z-index: {1};\n}}" + ) + top_css = ( + "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n" + " top: {1}px;\n z-index: {2};\n{3}}}" + ) + + res = styler.set_uuid("").to_html() + + # test index stickys over thead and tbody + assert (left_css.format("thead tr th:nth-child(1)", "3 !important") in res) is index + assert (left_css.format("tbody tr th:nth-child(1)", "1") in res) is index + + # test column stickys including if name row + assert ( + top_css.format("thead tr:nth-child(1) th", "0", "2", " height: 25px;\n") in res + ) is (columns and index_name) + assert ( + top_css.format("thead tr:nth-child(2) th", "25", "2", " height: 25px;\n") + in res + ) is (columns and index_name) + assert (top_css.format("thead tr:nth-child(1) th", "0", "2", "") in res) is ( + columns and not index_name + ) + + +@pytest.mark.parametrize("index", [False, True]) +@pytest.mark.parametrize("columns", [False, True]) +def test_sticky_mi(styler_mi, index, columns): + if index: + styler_mi.set_sticky(axis=0) + if columns: + styler_mi.set_sticky(axis=1) + + left_css = ( + "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n" + " left: {1}px;\n min-width: 75px;\n max-width: 75px;\n z-index: {2};\n}}" + ) + top_css = ( + "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n" + " top: {1}px;\n height: 25px;\n z-index: {2};\n}}" + ) + + res = styler_mi.set_uuid("").to_html() + + # test the index stickys for thead and tbody over both levels + assert ( + left_css.format("thead tr th:nth-child(1)", "0", "3 !important") in res + ) is index + assert (left_css.format("tbody tr th.level0", "0", "1") in res) is index + assert ( + left_css.format("thead tr th:nth-child(2)", "75", "3 !important") in res + ) is index + assert (left_css.format("tbody tr th.level1", "75", "1") in res) is index + + # test the column stickys for each level row + assert (top_css.format("thead tr:nth-child(1) th", "0", "2") in res) is columns + assert (top_css.format("thead tr:nth-child(2) th", "25", "2") in res) is columns + + +@pytest.mark.parametrize("index", [False, True]) +@pytest.mark.parametrize("columns", [False, True]) +@pytest.mark.parametrize("levels", [[1], ["one"], "one"]) +def test_sticky_levels(styler_mi, index, columns, levels): + styler_mi.index.names, styler_mi.columns.names = ["zero", "one"], ["zero", "one"] + if index: + styler_mi.set_sticky(axis=0, levels=levels) + if columns: + styler_mi.set_sticky(axis=1, levels=levels) + + left_css = ( + "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n" + " left: {1}px;\n min-width: 75px;\n max-width: 75px;\n z-index: {2};\n}}" + ) + top_css = ( + "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n" + " top: {1}px;\n height: 25px;\n z-index: {2};\n}}" + ) + + res = styler_mi.set_uuid("").to_html() + + # test no sticking of level0 + assert "#T_ thead tr th:nth-child(1)" not in res + assert "#T_ tbody tr th.level0" not in res + assert "#T_ thead tr:nth-child(1) th" not in res + + # test sticking level1 + assert ( + left_css.format("thead tr th:nth-child(2)", "0", "3 !important") in res + ) is index + assert (left_css.format("tbody tr th.level1", "0", "1") in res) is index + assert (top_css.format("thead tr:nth-child(2) th", "0", "2") in res) is columns + + +def test_sticky_raises(styler): + with pytest.raises(ValueError, match="No axis named bad for object type DataFrame"): + styler.set_sticky(axis="bad") + + +@pytest.mark.parametrize( + "sparse_index, sparse_columns", + [(True, True), (True, False), (False, True), (False, False)], +) +def test_sparse_options(sparse_index, sparse_columns): + cidx = pd.MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")]) + ridx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=ridx, columns=cidx) + styler = df.style + + default_html = styler.to_html() # defaults under pd.options to (True , True) + + with pd.option_context( + "styler.sparse.index", sparse_index, "styler.sparse.columns", sparse_columns + ): + html1 = styler.to_html() + assert (html1 == default_html) is (sparse_index and sparse_columns) + html2 = styler.to_html(sparse_index=sparse_index, sparse_columns=sparse_columns) + assert html1 == html2 + + +@pytest.mark.parametrize("index", [True, False]) +@pytest.mark.parametrize("columns", [True, False]) +def test_map_header_cell_ids(styler, index, columns): + # GH 41893 + func = lambda v: "attr: val;" + styler.uuid, styler.cell_ids = "", False + if index: + styler.map_index(func, axis="index") + if columns: + styler.map_index(func, axis="columns") + + result = styler.to_html() + + # test no data cell ids + assert '2.610000' in result + assert '2.690000' in result + + # test index header ids where needed and css styles + assert ( + 'a' in result + ) is index + assert ( + 'b' in result + ) is index + assert ("#T__level0_row0, #T__level0_row1 {\n attr: val;\n}" in result) is index + + # test column header ids where needed and css styles + assert ( + 'A' in result + ) is columns + assert ("#T__level0_col0 {\n attr: val;\n}" in result) is columns + + +@pytest.mark.parametrize("rows", [True, False]) +@pytest.mark.parametrize("cols", [True, False]) +def test_maximums(styler_mi, rows, cols): + result = styler_mi.to_html( + max_rows=2 if rows else None, + max_columns=2 if cols else None, + ) + + assert ">5" in result # [[0,1], [4,5]] always visible + assert (">8" in result) is not rows # first trimmed vertical element + assert (">2" in result) is not cols # first trimmed horizontal element + + +def test_replaced_css_class_names(): + css = { + "row_heading": "ROWHEAD", + # "col_heading": "COLHEAD", + "index_name": "IDXNAME", + # "col": "COL", + "row": "ROW", + # "col_trim": "COLTRIM", + "row_trim": "ROWTRIM", + "level": "LEVEL", + "data": "DATA", + "blank": "BLANK", + } + midx = pd.MultiIndex.from_product([["a", "b"], ["c", "d"]]) + styler_mi = Styler( + pd.DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=midx), + uuid_len=0, + ).set_table_styles(css_class_names=css) + styler_mi.index.names = ["n1", "n2"] + # GH#42934: index and columns no longer alias when the same Index is passed + # to the DataFrame constructor, so set the column names explicitly. + styler_mi.columns.names = ["n1", "n2"] + styler_mi.hide(styler_mi.index[1:], axis=0) + styler_mi.hide(styler_mi.columns[1:], axis=1) + styler_mi.map_index(lambda v: "color: red;", axis=0) + styler_mi.map_index(lambda v: "color: green;", axis=1) + styler_mi.map(lambda v: "color: blue;") + expected = dedent( + """\ + + + + + + + + + + + + + + + + + + + + + + + + + + +
 n1a
 n2c
n1n2 
ac0
+ """ + ) + result = styler_mi.to_html() + assert result == expected + + +def test_include_css_style_rules_only_for_visible_cells(styler_mi): + # GH 43619 + result = ( + styler_mi.set_uuid("") + .map(lambda v: "color: blue;") + .hide(styler_mi.data.columns[1:], axis="columns") + .hide(styler_mi.data.index[1:], axis="index") + .to_html() + ) + expected_styles = dedent( + """\ + + """ + ) + assert expected_styles in result + + +def test_include_css_style_rules_only_for_visible_index_labels(styler_mi): + # GH 43619 + result = ( + styler_mi.set_uuid("") + .map_index(lambda v: "color: blue;", axis="index") + .hide(styler_mi.data.columns, axis="columns") + .hide(styler_mi.data.index[1:], axis="index") + .to_html() + ) + expected_styles = dedent( + """\ + + """ + ) + assert expected_styles in result + + +def test_include_css_style_rules_only_for_visible_column_labels(styler_mi): + # GH 43619 + result = ( + styler_mi.set_uuid("") + .map_index(lambda v: "color: blue;", axis="columns") + .hide(styler_mi.data.columns[1:], axis="columns") + .hide(styler_mi.data.index, axis="index") + .to_html() + ) + expected_styles = dedent( + """\ + + """ + ) + assert expected_styles in result + + +def test_hiding_index_columns_multiindex_alignment(): + # gh 43644 + midx = pd.MultiIndex.from_product( + [["i0", "j0"], ["i1"], ["i2", "j2"]], names=["i-0", "i-1", "i-2"] + ) + cidx = pd.MultiIndex.from_product( + [["c0"], ["c1", "d1"], ["c2", "d2"]], names=["c-0", "c-1", "c-2"] + ) + df = pd.DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=cidx) + styler = Styler(df, uuid_len=0) + styler.hide(level=1, axis=0).hide(level=0, axis=1) + styler.hide([("j0", "i1", "j2")], axis=0) + styler.hide([("c0", "d1", "d2")], axis=1) + result = styler.to_html() + expected = dedent( + """\ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 c-1c1d1
 c-2c2d2c2
i-0i-2   
i0i2012
j2456
j0i28910
+ """ + ) + assert result == expected + + +def test_hiding_index_columns_multiindex_trimming(): + # gh 44272 + df = pd.DataFrame(np.arange(64).reshape(8, 8)) + df.columns = pd.MultiIndex.from_product([[0, 1, 2, 3], [0, 1]]) + df.index = pd.MultiIndex.from_product([[0, 1, 2, 3], [0, 1]]) + df.index.names, df.columns.names = ["a", "b"], ["c", "d"] + styler = Styler(df, cell_ids=False, uuid_len=0) + styler.hide([(0, 0), (0, 1), (1, 0)], axis=1).hide([(0, 0), (0, 1), (1, 0)], axis=0) + with pd.option_context("styler.render.max_rows", 4, "styler.render.max_columns", 4): + result = styler.to_html() + + expected = dedent( + """\ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 c123
 d1010...
ab     
1127282930...
2035363738...
143444546...
3051525354...
.....................
+ """ + ) + + assert result == expected + + +@pytest.mark.parametrize("type", ["data", "index"]) +@pytest.mark.parametrize( + "text, exp, found", + [ + ("no link, just text", False, ""), + ("subdomain not www: sub.web.com", False, ""), + ("www subdomain: www.web.com other", True, "www.web.com"), + ("scheme full structure: http://www.web.com", True, "http://www.web.com"), + ("scheme no top-level: http://www.web", True, "http://www.web"), + ("no scheme, no top-level: www.web", False, "www.web"), + ("https scheme: https://www.web.com", True, "https://www.web.com"), + ("ftp scheme: ftp://www.web", True, "ftp://www.web"), + ("ftps scheme: ftps://www.web", True, "ftps://www.web"), + ("subdirectories: www.web.com/directory", True, "www.web.com/directory"), + ("Multiple domains: www.1.2.3.4", True, "www.1.2.3.4"), + ("with port: http://web.com:80", True, "http://web.com:80"), + ( + "full net_loc scheme: http://user:pass@web.com", + True, + "http://user:pass@web.com", + ), + ( + "with valid special chars: http://web.com/,.':;~!@#$*()[]", + True, + "http://web.com/,.':;~!@#$*()[]", + ), + ], +) +def test_rendered_links(type, text, exp, found): + if type == "data": + df = pd.DataFrame([text]) + styler = df.style.format(hyperlinks="html") + else: + df = pd.DataFrame([0], index=[text]) + styler = df.style.format_index(hyperlinks="html") + + rendered = f'{found}' + result = styler.to_html() + assert (rendered in result) is exp + assert (text in result) is not exp # test conversion done when expected and not + + +def test_multiple_rendered_links(): + links = ("www.a.b", "http://a.c", "https://a.d", "ftp://a.e") + df = pd.DataFrame(["text {} {} text {} {}".format(*links)]) + result = df.style.format(hyperlinks="html").to_html() + href = '{0}' + for link in links: + assert href.format(link) in result + assert href.format("text") not in result + + +def test_concat(styler): + other = styler.data.agg(["mean"]).style + styler.concat(other).set_uuid("X") + result = styler.to_html() + fp = "foot0_" + expected = dedent( + f"""\ + + b + 2.690000 + + + mean + 2.650000 + + + + """ + ) + assert expected in result + + +def test_concat_recursion(styler): + df = styler.data + styler1 = styler + styler2 = Styler(df.agg(["mean"]), precision=3) + styler3 = Styler(df.agg(["mean"]), precision=4) + styler1.concat(styler2.concat(styler3)).set_uuid("X") + result = styler.to_html() + # notice that the second concat (last of the output html), + # there are two `foot_` in the id and class + fp1 = "foot0_" + fp2 = "foot0_foot0_" + expected = dedent( + f"""\ + + b + 2.690000 + + + mean + 2.650 + + + mean + 2.6500 + + + + """ + ) + assert expected in result + + +def test_concat_chain(styler): + df = styler.data + styler1 = styler + styler2 = Styler(df.agg(["mean"]), precision=3) + styler3 = Styler(df.agg(["mean"]), precision=4) + styler1.concat(styler2).concat(styler3).set_uuid("X") + result = styler.to_html() + fp1 = "foot0_" + fp2 = "foot1_" + expected = dedent( + f"""\ + + b + 2.690000 + + + mean + 2.650 + + + mean + 2.6500 + + + + """ + ) + assert expected in result + + +def test_concat_combined(): + def html_lines(foot_prefix: str): + assert foot_prefix.endswith("_") or foot_prefix == "" + fp = foot_prefix + return indent( + dedent( + f"""\ + + a + 2.610000 + + + b + 2.690000 + + """ + ), + prefix=" " * 4, + ) + + df = pd.DataFrame([[2.61], [2.69]], index=["a", "b"], columns=["A"]) + s1 = df.style.highlight_max(color="red") + s2 = df.style.highlight_max(color="green") + s3 = df.style.highlight_max(color="blue") + s4 = df.style.highlight_max(color="yellow") + + result = s1.concat(s2).concat(s3.concat(s4)).set_uuid("X").to_html() + expected_css = dedent( + """\ + + """ + ) + expected_table = ( + dedent( + """\ + + + + + + + + + """ + ) + + html_lines("") + + html_lines("foot0_") + + html_lines("foot1_") + + html_lines("foot1_foot0_") + + dedent( + """\ + +
 A
+ """ + ) + ) + assert expected_css + expected_table == result + + +def test_to_html_na_rep_non_scalar_data(datapath): + # GH47103 + df = pd.DataFrame([{"a": 1, "b": [1, 2, 3], "c": np.nan}]) + result = df.style.format(na_rep="-").to_html(table_uuid="test") + expected = """\ + + + + + + + + + + + + + + + + + + +
 abc
01[1, 2, 3]-
+""" + assert result == expected + + +@pytest.mark.parametrize("escape_axis_0", [True, False]) +@pytest.mark.parametrize("escape_axis_1", [True, False]) +def test_format_index_names(styler_multi, escape_axis_0, escape_axis_1): + if escape_axis_0: + styler_multi.format_index_names(axis=0, escape="html") + expected_index = ["X>", "y_"] + else: + expected_index = ["X>", "y_"] + + if escape_axis_1: + styler_multi.format_index_names(axis=1, escape="html") + expected_columns = ["A&", "b&"] + else: + expected_columns = ["A&", "b&"] + + result = styler_multi.to_html(table_uuid="test") + for expected_str in expected_index + expected_columns: + assert f"{expected_str}" in result diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_matplotlib.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_matplotlib.py new file mode 100644 index 0000000000000000000000000000000000000000..88e7fdaca8eed3ba1917c816236892c6c6783882 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_matplotlib.py @@ -0,0 +1,301 @@ +import numpy as np +import pytest + +import pandas as pd + +mpl = pytest.importorskip("matplotlib") +pytest.importorskip("jinja2") + +from pandas.io.formats.style import Styler + +pytestmark = pytest.mark.usefixtures("mpl_cleanup") + + +@pytest.fixture +def df(): + return pd.DataFrame([[1, 2], [2, 4]], columns=["A", "B"]) + + +@pytest.fixture +def styler(df): + return Styler(df, uuid_len=0) + + +@pytest.fixture +def df_blank(): + return pd.DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"]) + + +@pytest.fixture +def styler_blank(df_blank): + return Styler(df_blank, uuid_len=0) + + +@pytest.mark.parametrize("f", ["background_gradient", "text_gradient"]) +def test_function_gradient(styler, f): + for c_map in [None, "YlOrRd"]: + result = getattr(styler, f)(cmap=c_map)._compute().ctx + assert all("#" in x[0][1] for x in result.values()) + assert result[(0, 0)] == result[(0, 1)] + assert result[(1, 0)] == result[(1, 1)] + + +@pytest.mark.parametrize("f", ["background_gradient", "text_gradient"]) +def test_background_gradient_color(styler, f): + result = getattr(styler, f)(subset=pd.IndexSlice[1, "A"])._compute().ctx + if f == "background_gradient": + assert result[(1, 0)] == [("background-color", "#fff7fb"), ("color", "#000000")] + elif f == "text_gradient": + assert result[(1, 0)] == [("color", "#fff7fb")] + + +@pytest.mark.parametrize( + "axis, expected", + [ + (0, ["low", "low", "high", "high"]), + (1, ["low", "high", "low", "high"]), + (None, ["low", "mid", "mid", "high"]), + ], +) +@pytest.mark.parametrize("f", ["background_gradient", "text_gradient"]) +def test_background_gradient_axis(styler, axis, expected, f): + if f == "background_gradient": + colors = { + "low": [("background-color", "#f7fbff"), ("color", "#000000")], + "mid": [("background-color", "#abd0e6"), ("color", "#000000")], + "high": [("background-color", "#08306b"), ("color", "#f1f1f1")], + } + elif f == "text_gradient": + colors = { + "low": [("color", "#f7fbff")], + "mid": [("color", "#abd0e6")], + "high": [("color", "#08306b")], + } + result = getattr(styler, f)(cmap="Blues", axis=axis)._compute().ctx + for i, cell in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]): + assert result[cell] == colors[expected[i]] + + +@pytest.mark.parametrize( + "cmap, expected", + [ + ( + "PuBu", + { + (4, 5): [("background-color", "#86b0d3"), ("color", "#000000")], + (4, 6): [("background-color", "#83afd3"), ("color", "#f1f1f1")], + }, + ), + ( + "YlOrRd", + { + (4, 8): [("background-color", "#fd913e"), ("color", "#000000")], + (4, 9): [("background-color", "#fd8f3d"), ("color", "#f1f1f1")], + }, + ), + ( + None, + { + (7, 0): [("background-color", "#48c16e"), ("color", "#f1f1f1")], + (7, 1): [("background-color", "#4cc26c"), ("color", "#000000")], + }, + ), + ], +) +def test_text_color_threshold(cmap, expected): + # GH 39888 + df = pd.DataFrame(np.arange(100).reshape(10, 10)) + result = df.style.background_gradient(cmap=cmap, axis=None)._compute().ctx + for k in expected.keys(): + assert result[k] == expected[k] + + +def test_background_gradient_vmin_vmax(): + # GH 12145 + df = pd.DataFrame(range(5)) + ctx = df.style.background_gradient(vmin=1, vmax=3)._compute().ctx + assert ctx[(0, 0)] == ctx[(1, 0)] + assert ctx[(4, 0)] == ctx[(3, 0)] + + +def test_background_gradient_int64(): + # GH 28869 + df1 = pd.Series(range(3)).to_frame() + df2 = pd.Series(range(3), dtype="Int64").to_frame() + ctx1 = df1.style.background_gradient()._compute().ctx + ctx2 = df2.style.background_gradient()._compute().ctx + assert ctx2[(0, 0)] == ctx1[(0, 0)] + assert ctx2[(1, 0)] == ctx1[(1, 0)] + assert ctx2[(2, 0)] == ctx1[(2, 0)] + + +@pytest.mark.parametrize( + "axis, gmap, expected", + [ + ( + 0, + [1, 2], + { + (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")], + (1, 0): [("background-color", "#023858"), ("color", "#f1f1f1")], + (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")], + (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")], + }, + ), + ( + 1, + [1, 2], + { + (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")], + (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")], + (0, 1): [("background-color", "#023858"), ("color", "#f1f1f1")], + (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")], + }, + ), + ( + None, + np.array([[2, 1], [1, 2]]), + { + (0, 0): [("background-color", "#023858"), ("color", "#f1f1f1")], + (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")], + (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")], + (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")], + }, + ), + ], +) +def test_background_gradient_gmap_array(styler_blank, axis, gmap, expected): + # tests when gmap is given as a sequence and converted to ndarray + result = styler_blank.background_gradient(axis=axis, gmap=gmap)._compute().ctx + assert result == expected + + +@pytest.mark.parametrize( + "gmap, axis", [([1, 2, 3], 0), ([1, 2], 1), (np.array([[1, 2], [1, 2]]), None)] +) +def test_background_gradient_gmap_array_raises(gmap, axis): + # test when gmap as converted ndarray is bad shape + df = pd.DataFrame([[0, 0, 0], [0, 0, 0]]) + msg = "supplied 'gmap' is not correct shape" + with pytest.raises(ValueError, match=msg): + df.style.background_gradient(gmap=gmap, axis=axis)._compute() + + +@pytest.mark.parametrize( + "gmap", + [ + pd.DataFrame( # reverse the columns + [[2, 1], [1, 2]], columns=["B", "A"], index=["X", "Y"] + ), + pd.DataFrame( # reverse the index + [[2, 1], [1, 2]], columns=["A", "B"], index=["Y", "X"] + ), + pd.DataFrame( # reverse the index and columns + [[1, 2], [2, 1]], columns=["B", "A"], index=["Y", "X"] + ), + pd.DataFrame( # add unnecessary columns + [[1, 2, 3], [2, 1, 3]], columns=["A", "B", "C"], index=["X", "Y"] + ), + pd.DataFrame( # add unnecessary index + [[1, 2], [2, 1], [3, 3]], columns=["A", "B"], index=["X", "Y", "Z"] + ), + ], +) +@pytest.mark.parametrize( + "subset, exp_gmap", # exp_gmap is underlying map DataFrame should conform to + [ + (None, [[1, 2], [2, 1]]), + (["A"], [[1], [2]]), # slice only column "A" in data and gmap + (["B", "A"], [[2, 1], [1, 2]]), # reverse the columns in data + (pd.IndexSlice["X", :], [[1, 2]]), # slice only index "X" in data and gmap + (pd.IndexSlice[["Y", "X"], :], [[2, 1], [1, 2]]), # reverse the index in data + ], +) +def test_background_gradient_gmap_dataframe_align(styler_blank, gmap, subset, exp_gmap): + # test gmap given as DataFrame that it aligns to the data including subset + expected = styler_blank.background_gradient(axis=None, gmap=exp_gmap, subset=subset) + result = styler_blank.background_gradient(axis=None, gmap=gmap, subset=subset) + assert expected._compute().ctx == result._compute().ctx + + +@pytest.mark.parametrize( + "gmap, axis, exp_gmap", + [ + (pd.Series([2, 1], index=["Y", "X"]), 0, [[1, 1], [2, 2]]), # reverse the index + (pd.Series([2, 1], index=["B", "A"]), 1, [[1, 2], [1, 2]]), # reverse the cols + (pd.Series([1, 2, 3], index=["X", "Y", "Z"]), 0, [[1, 1], [2, 2]]), # add idx + (pd.Series([1, 2, 3], index=["A", "B", "C"]), 1, [[1, 2], [1, 2]]), # add col + ], +) +def test_background_gradient_gmap_series_align(styler_blank, gmap, axis, exp_gmap): + # test gmap given as Series that it aligns to the data including subset + expected = styler_blank.background_gradient(axis=None, gmap=exp_gmap)._compute() + result = styler_blank.background_gradient(axis=axis, gmap=gmap)._compute() + assert expected.ctx == result.ctx + + +@pytest.mark.parametrize("axis", [1, 0]) +def test_background_gradient_gmap_wrong_dataframe(styler_blank, axis): + # test giving a gmap in DataFrame but with wrong axis + gmap = pd.DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]) + msg = "'gmap' is a DataFrame but underlying data for operations is a Series" + with pytest.raises(ValueError, match=msg): + styler_blank.background_gradient(gmap=gmap, axis=axis)._compute() + + +def test_background_gradient_gmap_wrong_series(styler_blank): + # test giving a gmap in Series form but with wrong axis + msg = "'gmap' is a Series but underlying data for operations is a DataFrame" + gmap = pd.Series([1, 2], index=["X", "Y"]) + with pytest.raises(ValueError, match=msg): + styler_blank.background_gradient(gmap=gmap, axis=None)._compute() + + +def test_background_gradient_nullable_dtypes(): + # GH 50712 + df1 = pd.DataFrame([[1], [0], [np.nan]], dtype=float) + df2 = pd.DataFrame([[1], [0], [None]], dtype="Int64") + + ctx1 = df1.style.background_gradient()._compute().ctx + ctx2 = df2.style.background_gradient()._compute().ctx + assert ctx1 == ctx2 + + +@pytest.mark.parametrize( + "cmap", + ["PuBu", mpl.colormaps["PuBu"]], +) +def test_bar_colormap(cmap): + data = pd.DataFrame([[1, 2], [3, 4]]) + ctx = data.style.bar(cmap=cmap, axis=None)._compute().ctx + pubu_colors = { + (0, 0): "#d0d1e6", + (1, 0): "#056faf", + (0, 1): "#73a9cf", + (1, 1): "#023858", + } + for k, v in pubu_colors.items(): + assert v in ctx[k][1][1] + + +def test_bar_color_raises(df): + msg = "`color` must be string or list or tuple of 2 strings" + with pytest.raises(ValueError, match=msg): + df.style.bar(color={"a", "b"}).to_html() + with pytest.raises(ValueError, match=msg): + df.style.bar(color=["a", "b", "c"]).to_html() + + msg = "`color` and `cmap` cannot both be given" + with pytest.raises(ValueError, match=msg): + df.style.bar(color="something", cmap="something else").to_html() + + +@pytest.mark.parametrize("plot_method", ["scatter", "hexbin"]) +def test_pass_colormap_instance(df, plot_method): + # https://github.com/pandas-dev/pandas/issues/49374 + cmap = mpl.colors.ListedColormap([[1, 1, 1], [0, 0, 0]]) + df["c"] = df.A + df.B + kwargs = {"x": "A", "y": "B", "c": "c", "colormap": cmap} + if plot_method == "hexbin": + kwargs["C"] = kwargs.pop("c") + getattr(df.plot, plot_method)(**kwargs) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_non_unique.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_non_unique.py new file mode 100644 index 0000000000000000000000000000000000000000..770a8a67aab9180e2d6d6400bce6971aa60370f1 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_non_unique.py @@ -0,0 +1,143 @@ +from textwrap import dedent + +import pytest + +import pandas as pd + +pytest.importorskip("jinja2") + +from pandas.io.formats.style import Styler + + +@pytest.fixture +def df(): + return pd.DataFrame( + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], + index=["i", "j", "j"], + columns=["c", "d", "d"], + dtype=float, + ) + + +@pytest.fixture +def styler(df): + return Styler(df, uuid_len=0) + + +def test_format_non_unique(df): + # GH 41269 + + # test dict + html = df.style.format({"d": "{:.1f}"}).to_html() + for val in ["1.000000<", "4.000000<", "7.000000<"]: + assert val in html + for val in ["2.0<", "3.0<", "5.0<", "6.0<", "8.0<", "9.0<"]: + assert val in html + + # test subset + html = df.style.format(precision=1, subset=pd.IndexSlice["j", "d"]).to_html() + for val in ["1.000000<", "4.000000<", "7.000000<", "2.000000<", "3.000000<"]: + assert val in html + for val in ["5.0<", "6.0<", "8.0<", "9.0<"]: + assert val in html + + +@pytest.mark.parametrize("func", ["apply", "map"]) +def test_apply_map_non_unique_raises(df, func): + # GH 41269 + if func == "apply": + op = lambda s: ["color: red;"] * len(s) + else: + op = lambda v: "color: red;" + + with pytest.raises(KeyError, match="`Styler.apply` and `.map` are not"): + getattr(df.style, func)(op)._compute() + + +def test_table_styles_dict_non_unique_index(styler): + styles = styler.set_table_styles( + {"j": [{"selector": "td", "props": "a: v;"}]}, axis=1 + ).table_styles + assert styles == [ + {"selector": "td.row1", "props": [("a", "v")]}, + {"selector": "td.row2", "props": [("a", "v")]}, + ] + + +def test_table_styles_dict_non_unique_columns(styler): + styles = styler.set_table_styles( + {"d": [{"selector": "td", "props": "a: v;"}]}, axis=0 + ).table_styles + assert styles == [ + {"selector": "td.col1", "props": [("a", "v")]}, + {"selector": "td.col2", "props": [("a", "v")]}, + ] + + +def test_tooltips_non_unique_raises(styler): + # ttips has unique keys + ttips = pd.DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"]) + styler.set_tooltips(ttips=ttips) # OK + + # ttips has non-unique columns + ttips = pd.DataFrame([["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"]) + with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"): + styler.set_tooltips(ttips=ttips) + + # ttips has non-unique index + ttips = pd.DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"]) + with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"): + styler.set_tooltips(ttips=ttips) + + +def test_set_td_classes_non_unique_raises(styler): + # classes has unique keys + classes = pd.DataFrame( + [["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"] + ) + styler.set_td_classes(classes=classes) # OK + + # classes has non-unique columns + classes = pd.DataFrame( + [["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"] + ) + with pytest.raises(KeyError, match="Classes render only if `classes` has unique"): + styler.set_td_classes(classes=classes) + + # classes has non-unique index + classes = pd.DataFrame( + [["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"] + ) + with pytest.raises(KeyError, match="Classes render only if `classes` has unique"): + styler.set_td_classes(classes=classes) + + +def test_hide_columns_non_unique(styler): + ctx = styler.hide(["d"], axis="columns")._translate(True, True) + + assert ctx["head"][0][1]["display_value"] == "c" + assert ctx["head"][0][1]["is_visible"] is True + + assert ctx["head"][0][2]["display_value"] == "d" + assert ctx["head"][0][2]["is_visible"] is False + + assert ctx["head"][0][3]["display_value"] == "d" + assert ctx["head"][0][3]["is_visible"] is False + + assert ctx["body"][0][1]["is_visible"] is True + assert ctx["body"][0][2]["is_visible"] is False + assert ctx["body"][0][3]["is_visible"] is False + + +def test_latex_non_unique(styler): + result = styler.to_latex() + assert result == dedent( + """\ + \\begin{tabular}{lrrr} + & c & d & d \\\\ + i & 1.000000 & 2.000000 & 3.000000 \\\\ + j & 4.000000 & 5.000000 & 6.000000 \\\\ + j & 7.000000 & 8.000000 & 9.000000 \\\\ + \\end{tabular} + """ + ) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_style.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_style.py new file mode 100644 index 0000000000000000000000000000000000000000..31e8a3f0313a7ca202a5dea20158ebc9f79fd10f --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_style.py @@ -0,0 +1,1608 @@ +import contextlib +import copy +import re +from textwrap import dedent + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + +jinja2 = pytest.importorskip("jinja2") +from pandas.io.formats.style import ( # isort:skip + Styler, +) +from pandas.io.formats.style_render import ( + _get_level_lengths, + _get_trimming_maximums, + maybe_convert_css_to_tuples, + non_reducing_slice, +) + + +@pytest.fixture +def mi_df(): + return pd.DataFrame( + [[1, 2], [3, 4]], + index=pd.MultiIndex.from_product([["i0"], ["i1_a", "i1_b"]]), + columns=pd.MultiIndex.from_product([["c0"], ["c1_a", "c1_b"]]), + dtype=int, + ) + + +@pytest.fixture +def mi_styler(mi_df): + return Styler(mi_df, uuid_len=0) + + +@pytest.fixture +def mi_styler_comp(mi_styler): + # comprehensively add features to mi_styler + mi_styler = mi_styler._copy(deepcopy=True) + mi_styler.css = {**mi_styler.css, "row": "ROW", "col": "COL"} + mi_styler.uuid_len = 5 + mi_styler.uuid = "abcde" + mi_styler.set_caption("capt") + mi_styler.set_table_styles([{"selector": "a", "props": "a:v;"}]) + mi_styler.hide(axis="columns") + mi_styler.hide([("c0", "c1_a")], axis="columns", names=True) + mi_styler.hide(axis="index") + mi_styler.hide([("i0", "i1_a")], axis="index", names=True) + mi_styler.set_table_attributes('class="box"') + other = mi_styler.data.agg(["mean"]) + other.index = pd.MultiIndex.from_product([[""], other.index]) + mi_styler.concat(other.style) + mi_styler.format(na_rep="MISSING", precision=3) + mi_styler.format_index(precision=2, axis=0) + mi_styler.format_index(precision=4, axis=1) + mi_styler.highlight_max(axis=None) + mi_styler.map_index(lambda x: "color: white;", axis=0) + mi_styler.map_index(lambda x: "color: black;", axis=1) + mi_styler.set_td_classes( + pd.DataFrame( + [["a", "b"], ["a", "c"]], index=mi_styler.index, columns=mi_styler.columns + ) + ) + mi_styler.set_tooltips( + pd.DataFrame( + [["a2", "b2"], ["a2", "c2"]], + index=mi_styler.index, + columns=mi_styler.columns, + ) + ) + mi_styler.format_index_names(escape="html", axis=0) + mi_styler.format_index_names(escape="html", axis=1) + return mi_styler + + +@pytest.fixture +def blank_value(): + return " " + + +@pytest.fixture +def df(): + df = pd.DataFrame({"A": [0, 1], "B": np.random.default_rng(2).standard_normal(2)}) + return df + + +@pytest.fixture +def styler(df): + df = pd.DataFrame({"A": [0, 1], "B": np.random.default_rng(2).standard_normal(2)}) + return Styler(df) + + +@pytest.mark.parametrize( + "sparse_columns, exp_cols", + [ + ( + True, + [ + {"is_visible": True, "attributes": 'colspan="2"', "value": "c0"}, + {"is_visible": False, "attributes": "", "value": "c0"}, + ], + ), + ( + False, + [ + {"is_visible": True, "attributes": "", "value": "c0"}, + {"is_visible": True, "attributes": "", "value": "c0"}, + ], + ), + ], +) +def test_mi_styler_sparsify_columns(mi_styler, sparse_columns, exp_cols): + exp_l1_c0 = {"is_visible": True, "attributes": "", "display_value": "c1_a"} + exp_l1_c1 = {"is_visible": True, "attributes": "", "display_value": "c1_b"} + + ctx = mi_styler._translate(True, sparse_columns) + + assert exp_cols[0].items() <= ctx["head"][0][2].items() + assert exp_cols[1].items() <= ctx["head"][0][3].items() + assert exp_l1_c0.items() <= ctx["head"][1][2].items() + assert exp_l1_c1.items() <= ctx["head"][1][3].items() + + +@pytest.mark.parametrize( + "sparse_index, exp_rows", + [ + ( + True, + [ + {"is_visible": True, "attributes": 'rowspan="2"', "value": "i0"}, + {"is_visible": False, "attributes": "", "value": "i0"}, + ], + ), + ( + False, + [ + {"is_visible": True, "attributes": "", "value": "i0"}, + {"is_visible": True, "attributes": "", "value": "i0"}, + ], + ), + ], +) +def test_mi_styler_sparsify_index(mi_styler, sparse_index, exp_rows): + exp_l1_r0 = {"is_visible": True, "attributes": "", "display_value": "i1_a"} + exp_l1_r1 = {"is_visible": True, "attributes": "", "display_value": "i1_b"} + + ctx = mi_styler._translate(sparse_index, True) + + assert exp_rows[0].items() <= ctx["body"][0][0].items() + assert exp_rows[1].items() <= ctx["body"][1][0].items() + assert exp_l1_r0.items() <= ctx["body"][0][1].items() + assert exp_l1_r1.items() <= ctx["body"][1][1].items() + + +def test_mi_styler_sparsify_options(mi_styler): + with pd.option_context("styler.sparse.index", False): + html1 = mi_styler.to_html() + with pd.option_context("styler.sparse.index", True): + html2 = mi_styler.to_html() + + assert html1 != html2 + + with pd.option_context("styler.sparse.columns", False): + html1 = mi_styler.to_html() + with pd.option_context("styler.sparse.columns", True): + html2 = mi_styler.to_html() + + assert html1 != html2 + + +@pytest.mark.parametrize( + "rn, cn, max_els, max_rows, max_cols, exp_rn, exp_cn", + [ + (100, 100, 100, None, None, 12, 6), # reduce to (12, 6) < 100 elements + (1000, 3, 750, None, None, 250, 3), # dynamically reduce rows to 250, keep cols + (4, 1000, 500, None, None, 4, 125), # dynamically reduce cols to 125, keep rows + (1000, 3, 750, 10, None, 10, 3), # overwrite above dynamics with max_row + (4, 1000, 500, None, 5, 4, 5), # overwrite above dynamics with max_col + (100, 100, 700, 50, 50, 25, 25), # rows cols below given maxes so < 700 elmts + ], +) +def test_trimming_maximum(rn, cn, max_els, max_rows, max_cols, exp_rn, exp_cn): + rn, cn = _get_trimming_maximums( + rn, cn, max_els, max_rows, max_cols, scaling_factor=0.5 + ) + assert (rn, cn) == (exp_rn, exp_cn) + + +@pytest.mark.parametrize( + "option, val", + [ + ("styler.render.max_elements", 6), + ("styler.render.max_rows", 3), + ], +) +def test_render_trimming_rows(option, val): + # test auto and specific trimming of rows + df = pd.DataFrame(np.arange(120).reshape(60, 2)) + with pd.option_context(option, val): + ctx = df.style._translate(True, True) + assert len(ctx["head"][0]) == 3 # index + 2 data cols + assert len(ctx["body"]) == 4 # 3 data rows + trimming row + assert len(ctx["body"][0]) == 3 # index + 2 data cols + + +@pytest.mark.parametrize( + "option, val", + [ + ("styler.render.max_elements", 6), + ("styler.render.max_columns", 2), + ], +) +def test_render_trimming_cols(option, val): + # test auto and specific trimming of cols + df = pd.DataFrame(np.arange(30).reshape(3, 10)) + with pd.option_context(option, val): + ctx = df.style._translate(True, True) + assert len(ctx["head"][0]) == 4 # index + 2 data cols + trimming col + assert len(ctx["body"]) == 3 # 3 data rows + assert len(ctx["body"][0]) == 4 # index + 2 data cols + trimming col + + +def test_render_trimming_mi(): + midx = pd.MultiIndex.from_product([[1, 2], [1, 2, 3]]) + df = pd.DataFrame(np.arange(36).reshape(6, 6), columns=midx, index=midx) + with pd.option_context("styler.render.max_elements", 4): + ctx = df.style._translate(True, True) + + assert len(ctx["body"][0]) == 5 # 2 indexes + 2 data cols + trimming row + assert {"attributes": 'rowspan="2"'}.items() <= ctx["body"][0][0].items() + assert {"class": "data row0 col_trim"}.items() <= ctx["body"][0][4].items() + assert {"class": "data row_trim col_trim"}.items() <= ctx["body"][2][4].items() + assert len(ctx["body"]) == 3 # 2 data rows + trimming row + + +def test_render_empty_mi(): + # GH 43305 + df = pd.DataFrame( + index=pd.MultiIndex.from_product([["A"], [0, 1]], names=[None, "one"]) + ) + expected = dedent( + """\ + > + + +   + one + + + """ + ) + assert expected in df.style.to_html() + + +@pytest.mark.parametrize("comprehensive", [True, False]) +@pytest.mark.parametrize("render", [True, False]) +@pytest.mark.parametrize("deepcopy", [True, False]) +def test_copy(comprehensive, render, deepcopy, mi_styler, mi_styler_comp): + styler = mi_styler_comp if comprehensive else mi_styler + styler.uuid_len = 5 + + s2 = copy.deepcopy(styler) if deepcopy else copy.copy(styler) # make copy and check + assert s2 is not styler + + if render: + styler.to_html() + + excl = [ + "cellstyle_map", # render time vars.. + "cellstyle_map_columns", + "cellstyle_map_index", + "template_latex", # render templates are class level + "template_html", + "template_html_style", + "template_html_table", + ] + if not deepcopy: # check memory locations are equal for all included attributes + for attr in [a for a in styler.__dict__ if (not callable(a) and a not in excl)]: + assert id(getattr(s2, attr)) == id(getattr(styler, attr)) + else: # check memory locations are different for nested or mutable vars + shallow = [ + "data", + "columns", + "index", + "uuid_len", + "uuid", + "caption", + "cell_ids", + "hide_index_", + "hide_columns_", + "hide_index_names", + "hide_column_names", + "table_attributes", + ] + for attr in shallow: + assert id(getattr(s2, attr)) == id(getattr(styler, attr)) + + for attr in [ + a + for a in styler.__dict__ + if (not callable(a) and a not in excl and a not in shallow) + ]: + if getattr(s2, attr) is None: + assert id(getattr(s2, attr)) == id(getattr(styler, attr)) + else: + assert id(getattr(s2, attr)) != id(getattr(styler, attr)) + + +@pytest.mark.parametrize("deepcopy", [True, False]) +def test_inherited_copy(mi_styler, deepcopy): + # Ensure that the inherited class is preserved when a Styler object is copied. + # GH 52728 + class CustomStyler(Styler): + pass + + custom_styler = CustomStyler(mi_styler.data) + custom_styler_copy = ( + copy.deepcopy(custom_styler) if deepcopy else copy.copy(custom_styler) + ) + assert isinstance(custom_styler_copy, CustomStyler) + + +def test_clear(mi_styler_comp): + # NOTE: if this test fails for new features then 'mi_styler_comp' should be updated + # to ensure proper testing of the 'copy', 'clear', 'export' methods with new feature + # GH 40675 + styler = mi_styler_comp + styler._compute() # execute applied methods + + clean_copy = Styler(styler.data, uuid=styler.uuid) + + excl = [ + "data", + "index", + "columns", + "uuid", + "uuid_len", # uuid is set to be the same on styler and clean_copy + "cell_ids", + "cellstyle_map", # execution time only + "cellstyle_map_columns", # execution time only + "cellstyle_map_index", # execution time only + "template_latex", # render templates are class level + "template_html", + "template_html_style", + "template_html_table", + ] + # tests vars are not same vals on obj and clean copy before clear (except for excl) + for attr in [a for a in styler.__dict__ if not (callable(a) or a in excl)]: + res = getattr(styler, attr) == getattr(clean_copy, attr) + if hasattr(res, "__iter__") and len(res) > 0: + assert not all(res) # some element in iterable differs + elif hasattr(res, "__iter__") and len(res) == 0: + pass # empty array + else: + assert not res # explicit var differs + + # test vars have same vales on obj and clean copy after clearing + styler.clear() + for attr in [a for a in styler.__dict__ if not callable(a)]: + res = getattr(styler, attr) == getattr(clean_copy, attr) + assert all(res) if hasattr(res, "__iter__") else res + + +def test_export(mi_styler_comp, mi_styler): + exp_attrs = [ + "_todo", + "hide_index_", + "hide_index_names", + "hide_columns_", + "hide_column_names", + "table_attributes", + "table_styles", + "css", + ] + for attr in exp_attrs: + check = getattr(mi_styler, attr) == getattr(mi_styler_comp, attr) + assert not ( + all(check) if (hasattr(check, "__iter__") and len(check) > 0) else check + ) + + export = mi_styler_comp.export() + used = mi_styler.use(export) + for attr in exp_attrs: + check = getattr(used, attr) == getattr(mi_styler_comp, attr) + assert all(check) if (hasattr(check, "__iter__") and len(check) > 0) else check + + used.to_html() + + +def test_hide_raises(mi_styler): + msg = "`subset` and `level` cannot be passed simultaneously" + with pytest.raises(ValueError, match=msg): + mi_styler.hide(axis="index", subset="something", level="something else") + + msg = "`level` must be of type `int`, `str` or list of such" + with pytest.raises(ValueError, match=msg): + mi_styler.hide(axis="index", level={"bad": 1, "type": 2}) + + +@pytest.mark.parametrize("level", [1, "one", [1], ["one"]]) +def test_hide_index_level(mi_styler, level): + mi_styler.index.names, mi_styler.columns.names = ["zero", "one"], ["zero", "one"] + ctx = mi_styler.hide(axis="index", level=level)._translate(False, True) + assert len(ctx["head"][0]) == 3 + assert len(ctx["head"][1]) == 3 + assert len(ctx["head"][2]) == 4 + assert ctx["head"][2][0]["is_visible"] + assert not ctx["head"][2][1]["is_visible"] + + assert ctx["body"][0][0]["is_visible"] + assert not ctx["body"][0][1]["is_visible"] + assert ctx["body"][1][0]["is_visible"] + assert not ctx["body"][1][1]["is_visible"] + + +@pytest.mark.parametrize("level", [1, "one", [1], ["one"]]) +@pytest.mark.parametrize("names", [True, False]) +def test_hide_columns_level(mi_styler, level, names): + mi_styler.columns.names = ["zero", "one"] + if names: + mi_styler.index.names = ["zero", "one"] + ctx = mi_styler.hide(axis="columns", level=level)._translate(True, False) + assert len(ctx["head"]) == (2 if names else 1) + + +@pytest.mark.parametrize("method", ["map", "apply"]) +@pytest.mark.parametrize("axis", ["index", "columns"]) +def test_apply_map_header(method, axis): + # GH 41893 + df = pd.DataFrame({"A": [0, 0], "B": [1, 1]}, index=["C", "D"]) + func = { + "apply": lambda s: ["attr: val" if ("A" in v or "C" in v) else "" for v in s], + "map": lambda v: "attr: val" if ("A" in v or "C" in v) else "", + } + + # test execution added to todo + result = getattr(df.style, f"{method}_index")(func[method], axis=axis) + assert len(result._todo) == 1 + assert len(getattr(result, f"ctx_{axis}")) == 0 + + # test ctx object on compute + result._compute() + expected = { + (0, 0): [("attr", "val")], + } + assert getattr(result, f"ctx_{axis}") == expected + + +@pytest.mark.parametrize("method", ["apply", "map"]) +@pytest.mark.parametrize("axis", ["index", "columns"]) +def test_apply_map_header_mi(mi_styler, method, axis): + # GH 41893 + func = { + "apply": lambda s: ["attr: val;" if "b" in v else "" for v in s], + "map": lambda v: "attr: val" if "b" in v else "", + } + result = getattr(mi_styler, f"{method}_index")(func[method], axis=axis)._compute() + expected = {(1, 1): [("attr", "val")]} + assert getattr(result, f"ctx_{axis}") == expected + + +def test_apply_map_header_raises(mi_styler): + # GH 41893 + with pytest.raises(ValueError, match="No axis named bad for object type DataFrame"): + mi_styler.map_index(lambda v: "attr: val;", axis="bad")._compute() + + +class TestStyler: + def test_init_non_pandas(self): + msg = "``data`` must be a Series or DataFrame" + with pytest.raises(TypeError, match=msg): + Styler([1, 2, 3]) + + def test_init_series(self): + result = Styler(pd.Series([1, 2])) + assert result.data.ndim == 2 + + def test_repr_html_ok(self, styler): + styler._repr_html_() + + def test_repr_html_mathjax(self, styler): + # gh-19824 / 41395 + assert "tex2jax_ignore" not in styler._repr_html_() + assert "mathjax_ignore" not in styler._repr_html_() + + with pd.option_context("styler.html.mathjax", False): + assert "tex2jax_ignore" in styler._repr_html_() + assert "mathjax_ignore" in styler._repr_html_() + + def test_update_ctx(self, styler): + styler._update_ctx(pd.DataFrame({"A": ["color: red", "color: blue"]})) + expected = {(0, 0): [("color", "red")], (1, 0): [("color", "blue")]} + assert styler.ctx == expected + + def test_update_ctx_flatten_multi_and_trailing_semi(self, styler): + attrs = pd.DataFrame({"A": ["color: red; foo: bar", "color:blue ; foo: baz;"]}) + styler._update_ctx(attrs) + expected = { + (0, 0): [("color", "red"), ("foo", "bar")], + (1, 0): [("color", "blue"), ("foo", "baz")], + } + assert styler.ctx == expected + + def test_render(self): + df = pd.DataFrame({"A": [0, 1]}) + style = lambda x: pd.Series(["color: red", "color: blue"], name=x.name) + s = Styler(df, uuid="AB").apply(style) + s.to_html() + # it worked? + + def test_multiple_render(self, df): + # GH 39396 + s = Styler(df, uuid_len=0).map(lambda x: "color: red;", subset=["A"]) + s.to_html() # do 2 renders to ensure css styles not duplicated + assert ( + '" in s.to_html() + ) + + def test_render_empty_dfs(self): + empty_df = pd.DataFrame() + es = Styler(empty_df) + es.to_html() + # An index but no columns + pd.DataFrame(columns=["a"]).style.to_html() + # A column but no index + pd.DataFrame(index=["a"]).style.to_html() + # No IndexError raised? + + def test_render_double(self): + df = pd.DataFrame({"A": [0, 1]}) + style = lambda x: pd.Series( + ["color: red; border: 1px", "color: blue; border: 2px"], name=x.name + ) + s = Styler(df, uuid="AB").apply(style) + s.to_html() + # it worked? + + def test_set_properties(self): + df = pd.DataFrame({"A": [0, 1]}) + result = df.style.set_properties(color="white", size="10px")._compute().ctx + # order is deterministic + v = [("color", "white"), ("size", "10px")] + expected = {(0, 0): v, (1, 0): v} + assert result.keys() == expected.keys() + for v1, v2 in zip(result.values(), expected.values(), strict=True): + assert sorted(v1) == sorted(v2) + + def test_set_properties_subset(self): + df = pd.DataFrame({"A": [0, 1]}) + result = ( + df.style.set_properties(subset=pd.IndexSlice[0, "A"], color="white") + ._compute() + .ctx + ) + expected = {(0, 0): [("color", "white")]} + assert result == expected + + def test_empty_index_name_doesnt_display(self, blank_value): + # https://github.com/pandas-dev/pandas/pull/12090#issuecomment-180695902 + df = pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}) + result = df.style._translate(True, True) + assert len(result["head"]) == 1 + expected = { + "class": "blank level0", + "type": "th", + "value": blank_value, + "is_visible": True, + "display_value": blank_value, + } + assert expected.items() <= result["head"][0][0].items() + + def test_index_name(self): + # https://github.com/pandas-dev/pandas/issues/11655 + df = pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}) + result = df.set_index("A").style._translate(True, True) + expected = { + "class": "index_name level0", + "type": "th", + "value": "A", + "is_visible": True, + "display_value": "A", + } + assert expected.items() <= result["head"][1][0].items() + + def test_numeric_columns(self): + # https://github.com/pandas-dev/pandas/issues/12125 + # smoke test for _translate + df = pd.DataFrame({0: [1, 2, 3]}) + df.style._translate(True, True) + + def test_apply_axis(self): + df = pd.DataFrame({"A": [0, 0], "B": [1, 1]}) + f = lambda x: [f"val: {x.max()}" for v in x] + result = df.style.apply(f, axis=1) + assert len(result._todo) == 1 + assert len(result.ctx) == 0 + result._compute() + expected = { + (0, 0): [("val", "1")], + (0, 1): [("val", "1")], + (1, 0): [("val", "1")], + (1, 1): [("val", "1")], + } + assert result.ctx == expected + + result = df.style.apply(f, axis=0) + expected = { + (0, 0): [("val", "0")], + (0, 1): [("val", "1")], + (1, 0): [("val", "0")], + (1, 1): [("val", "1")], + } + result._compute() + assert result.ctx == expected + result = df.style.apply(f) # default + result._compute() + assert result.ctx == expected + + @pytest.mark.parametrize("axis", [0, 1]) + def test_apply_series_return(self, axis): + # GH 42014 + df = pd.DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"]) + + # test Series return where len(Series) < df.index or df.columns but labels OK + func = lambda s: pd.Series(["color: red;"], index=["Y"]) + result = df.style.apply(func, axis=axis)._compute().ctx + assert result[(1, 1)] == [("color", "red")] + assert result[(1 - axis, axis)] == [("color", "red")] + + # test Series return where labels align but different order + func = lambda s: pd.Series(["color: red;", "color: blue;"], index=["Y", "X"]) + result = df.style.apply(func, axis=axis)._compute().ctx + assert result[(0, 0)] == [("color", "blue")] + assert result[(1, 1)] == [("color", "red")] + assert result[(1 - axis, axis)] == [("color", "red")] + assert result[(axis, 1 - axis)] == [("color", "blue")] + + @pytest.mark.parametrize("index", [False, True]) + @pytest.mark.parametrize("columns", [False, True]) + def test_apply_dataframe_return(self, index, columns): + # GH 42014 + df = pd.DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"]) + idxs = ["X", "Y"] if index else ["Y"] + cols = ["X", "Y"] if columns else ["Y"] + df_styles = pd.DataFrame("color: red;", index=idxs, columns=cols) + result = df.style.apply(lambda x: df_styles, axis=None)._compute().ctx + + assert result[(1, 1)] == [("color", "red")] # (Y,Y) styles always present + assert (result[(0, 1)] == [("color", "red")]) is index # (X,Y) only if index + assert (result[(1, 0)] == [("color", "red")]) is columns # (Y,X) only if cols + assert (result[(0, 0)] == [("color", "red")]) is (index and columns) # (X,X) + + @pytest.mark.parametrize( + "slice_", + [ + pd.IndexSlice[:], + pd.IndexSlice[:, ["A"]], + pd.IndexSlice[[1], :], + pd.IndexSlice[[1], ["A"]], + pd.IndexSlice[:2, ["A", "B"]], + ], + ) + @pytest.mark.parametrize("axis", [0, 1]) + def test_apply_subset(self, slice_, axis, df): + def h(x, color="bar"): + return pd.Series(f"color: {color}", index=x.index, name=x.name) + + result = df.style.apply(h, axis=axis, subset=slice_, color="baz")._compute().ctx + expected = { + (r, c): [("color", "baz")] + for r, row in enumerate(df.index) + for c, col in enumerate(df.columns) + if row in df.loc[slice_].index and col in df.loc[slice_].columns + } + assert result == expected + + @pytest.mark.parametrize( + "slice_", + [ + pd.IndexSlice[:], + pd.IndexSlice[:, ["A"]], + pd.IndexSlice[[1], :], + pd.IndexSlice[[1], ["A"]], + pd.IndexSlice[:2, ["A", "B"]], + ], + ) + def test_map_subset(self, slice_, df): + result = df.style.map(lambda x: "color:baz;", subset=slice_)._compute().ctx + expected = { + (r, c): [("color", "baz")] + for r, row in enumerate(df.index) + for c, col in enumerate(df.columns) + if row in df.loc[slice_].index and col in df.loc[slice_].columns + } + assert result == expected + + @pytest.mark.parametrize( + "slice_", + [ + pd.IndexSlice[:, pd.IndexSlice["x", "A"]], + pd.IndexSlice[:, pd.IndexSlice[:, "A"]], + pd.IndexSlice[:, pd.IndexSlice[:, ["A", "C"]]], # missing col element + pd.IndexSlice[pd.IndexSlice["a", 1], :], + pd.IndexSlice[pd.IndexSlice[:, 1], :], + pd.IndexSlice[pd.IndexSlice[:, [1, 3]], :], # missing row element + pd.IndexSlice[:, ("x", "A")], + pd.IndexSlice[("a", 1), :], + ], + ) + def test_map_subset_multiindex(self, slice_): + # GH 19861 + # edited for GH 33562 + if ( + isinstance(slice_[-1], tuple) + and isinstance(slice_[-1][-1], list) + and "C" in slice_[-1][-1] + ): + ctx = pytest.raises(KeyError, match="C") + elif ( + isinstance(slice_[0], tuple) + and isinstance(slice_[0][1], list) + and 3 in slice_[0][1] + ): + ctx = pytest.raises(KeyError, match="3") + else: + ctx = contextlib.nullcontext() + + idx = pd.MultiIndex.from_product([["a", "b"], [1, 2]]) + col = pd.MultiIndex.from_product([["x", "y"], ["A", "B"]]) + df = pd.DataFrame( + np.random.default_rng(2).random((4, 4)), columns=col, index=idx + ) + + with ctx: + df.style.map(lambda x: "color: red;", subset=slice_).to_html() + + def test_map_subset_multiindex_code(self): + # https://github.com/pandas-dev/pandas/issues/25858 + # Checks styler.map works with multiindex when codes are provided + codes = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) + columns = pd.MultiIndex( + levels=[["a", "b"], ["%", "#"]], codes=codes, names=["", ""] + ) + df = pd.DataFrame( + [[1, -1, 1, 1], [-1, 1, 1, 1]], index=["hello", "world"], columns=columns + ) + pct_subset = pd.IndexSlice[:, pd.IndexSlice[:, "%":"%"]] + + def color_negative_red(val): + color = "red" if val < 0 else "black" + return f"color: {color}" + + df.loc[pct_subset] + df.style.map(color_negative_red, subset=pct_subset) + + @pytest.mark.parametrize( + "stylefunc", ["background_gradient", "bar", "text_gradient"] + ) + def test_subset_for_boolean_cols(self, stylefunc): + # GH47838 + df = pd.DataFrame( + [ + [1, 2], + [3, 4], + ], + columns=[False, True], + ) + styled = getattr(df.style, stylefunc)() + styled._compute() + assert set(styled.ctx) == {(0, 0), (0, 1), (1, 0), (1, 1)} + + def test_empty(self): + df = pd.DataFrame({"A": [1, 0]}) + s = df.style + s.ctx = {(0, 0): [("color", "red")], (1, 0): [("", "")]} + + result = s._translate(True, True)["cellstyle"] + expected = [ + {"props": [("color", "red")], "selectors": ["row0_col0"]}, + {"props": [("", "")], "selectors": ["row1_col0"]}, + ] + assert result == expected + + def test_duplicate(self): + df = pd.DataFrame({"A": [1, 0]}) + s = df.style + s.ctx = {(0, 0): [("color", "red")], (1, 0): [("color", "red")]} + + result = s._translate(True, True)["cellstyle"] + expected = [ + {"props": [("color", "red")], "selectors": ["row0_col0", "row1_col0"]} + ] + assert result == expected + + def test_init_with_na_rep(self): + # GH 21527 28358 + df = pd.DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"]) + + ctx = Styler(df, na_rep="NA")._translate(True, True) + assert ctx["body"][0][1]["display_value"] == "NA" + assert ctx["body"][0][2]["display_value"] == "NA" + + def test_caption(self, df): + styler = Styler(df, caption="foo") + result = styler.to_html() + assert all(["caption" in result, "foo" in result]) + + styler = df.style + result = styler.set_caption("baz") + assert styler is result + assert styler.caption == "baz" + + def test_uuid(self, df): + styler = Styler(df, uuid="abc123") + result = styler.to_html() + assert "abc123" in result + + styler = df.style + result = styler.set_uuid("aaa") + assert result is styler + assert result.uuid == "aaa" + + def test_unique_id(self): + # See https://github.com/pandas-dev/pandas/issues/16780 + df = pd.DataFrame({"a": [1, 3, 5, 6], "b": [2, 4, 12, 21]}) + result = df.style.to_html(uuid="test") + assert "test" in result + ids = re.findall('id="(.*?)"', result) + assert np.unique(ids).size == len(ids) + + def test_table_styles(self, df): + style = [{"selector": "th", "props": [("foo", "bar")]}] # default format + styler = Styler(df, table_styles=style) + result = " ".join(styler.to_html().split()) + assert "th { foo: bar; }" in result + + styler = df.style + result = styler.set_table_styles(style) + assert styler is result + assert styler.table_styles == style + + # GH 39563 + style = [{"selector": "th", "props": "foo:bar;"}] # css string format + styler = df.style.set_table_styles(style) + result = " ".join(styler.to_html().split()) + assert "th { foo: bar; }" in result + + def test_table_styles_multiple(self, df): + ctx = df.style.set_table_styles( + [ + {"selector": "th,td", "props": "color:red;"}, + {"selector": "tr", "props": "color:green;"}, + ] + )._translate(True, True)["table_styles"] + assert ctx == [ + {"selector": "th", "props": [("color", "red")]}, + {"selector": "td", "props": [("color", "red")]}, + {"selector": "tr", "props": [("color", "green")]}, + ] + + def test_table_styles_dict_multiple_selectors(self, df): + # GH 44011 + result = df.style.set_table_styles( + { + "B": [ + {"selector": "th,td", "props": [("border-left", "2px solid black")]} + ] + } + )._translate(True, True)["table_styles"] + + expected = [ + {"selector": "th.col1", "props": [("border-left", "2px solid black")]}, + {"selector": "td.col1", "props": [("border-left", "2px solid black")]}, + ] + + assert result == expected + + def test_maybe_convert_css_to_tuples(self): + expected = [("a", "b"), ("c", "d e")] + assert maybe_convert_css_to_tuples("a:b;c:d e;") == expected + assert maybe_convert_css_to_tuples("a: b ;c: d e ") == expected + expected = [] + assert maybe_convert_css_to_tuples("") == expected + + # issue #59623 + expected = [("a", "b"), ("c", "url('data:123')")] + assert maybe_convert_css_to_tuples("a:b;c: url('data:123');") == expected + + # if no value, return attr and empty string + expected = [("a", ""), ("c", "")] + assert maybe_convert_css_to_tuples("a:;c: ") == expected + + def test_maybe_convert_css_to_tuples_err(self): + msg = ( + "Styles supplied as string must follow CSS rule formats, " + "for example 'attr: val;'. 'err' was given." + ) + with pytest.raises(ValueError, match=msg): + maybe_convert_css_to_tuples("err") + + def test_table_attributes(self, df): + attributes = 'class="foo" data-bar' + styler = Styler(df, table_attributes=attributes) + result = styler.to_html() + assert 'class="foo" data-bar' in result + + result = df.style.set_table_attributes(attributes).to_html() + assert 'class="foo" data-bar' in result + + def test_apply_none(self): + def f(x): + return pd.DataFrame( + np.where(x == x.max(), "color: red", ""), + index=x.index, + columns=x.columns, + ) + + result = pd.DataFrame([[1, 2], [3, 4]]).style.apply(f, axis=None)._compute().ctx + assert result[(1, 1)] == [("color", "red")] + + def test_trim(self, df): + result = df.style.to_html() # trim=True + assert result.count("#") == 0 + + result = df.style.highlight_max().to_html() + assert result.count("#") == len(df.columns) + + def test_export(self, df, styler): + f = lambda x: "color: red" if x > 0 else "color: blue" + g = lambda x, z: f"color: {z}" + style1 = styler + style1.map(f).map(g, z="b").highlight_max()._compute() # = render + result = style1.export() + style2 = df.style + style2.use(result) + assert style1._todo == style2._todo + style2.to_html() + + def test_bad_apply_shape(self): + df = pd.DataFrame([[1, 2], [3, 4]], index=["A", "B"], columns=["X", "Y"]) + + msg = "resulted in the apply method collapsing to a Series." + with pytest.raises(ValueError, match=msg): + df.style._apply(lambda x: "x") + + msg = "created invalid {} labels" + with pytest.raises(ValueError, match=msg.format("index")): + df.style._apply(lambda x: [""]) + + with pytest.raises(ValueError, match=msg.format("index")): + df.style._apply(lambda x: ["", "", "", ""]) + + with pytest.raises(ValueError, match=msg.format("index")): + df.style._apply(lambda x: pd.Series(["a:v;", ""], index=["A", "C"]), axis=0) + + with pytest.raises(ValueError, match=msg.format("columns")): + df.style._apply(lambda x: ["", "", ""], axis=1) + + with pytest.raises(ValueError, match=msg.format("columns")): + df.style._apply(lambda x: pd.Series(["a:v;", ""], index=["X", "Z"]), axis=1) + + msg = "returned ndarray with wrong shape" + with pytest.raises(ValueError, match=msg): + df.style._apply(lambda x: np.array([[""], [""]]), axis=None) + + def test_apply_bad_return(self): + def f(x): + return "" + + df = pd.DataFrame([[1, 2], [3, 4]]) + msg = ( + "must return a DataFrame or ndarray when passed to `Styler.apply` " + "with axis=None" + ) + with pytest.raises(TypeError, match=msg): + df.style._apply(f, axis=None) + + @pytest.mark.parametrize("axis", ["index", "columns"]) + def test_apply_bad_labels(self, axis): + def f(x): + return pd.DataFrame(**{axis: ["bad", "labels"]}) + + df = pd.DataFrame([[1, 2], [3, 4]]) + msg = f"created invalid {axis} labels." + with pytest.raises(ValueError, match=msg): + df.style._apply(f, axis=None) + + def test_get_level_lengths(self): + index = pd.MultiIndex.from_product([["a", "b"], [0, 1, 2]]) + expected = { + (0, 0): 3, + (0, 3): 3, + (1, 0): 1, + (1, 1): 1, + (1, 2): 1, + (1, 3): 1, + (1, 4): 1, + (1, 5): 1, + } + result = _get_level_lengths(index, sparsify=True, max_index=100) + tm.assert_dict_equal(result, expected) + + expected = { + (0, 0): 1, + (0, 1): 1, + (0, 2): 1, + (0, 3): 1, + (0, 4): 1, + (0, 5): 1, + (1, 0): 1, + (1, 1): 1, + (1, 2): 1, + (1, 3): 1, + (1, 4): 1, + (1, 5): 1, + } + result = _get_level_lengths(index, sparsify=False, max_index=100) + tm.assert_dict_equal(result, expected) + + def test_get_level_lengths_un_sorted(self): + index = pd.MultiIndex.from_arrays([[1, 1, 2, 1], ["a", "b", "b", "d"]]) + expected = { + (0, 0): 2, + (0, 2): 1, + (0, 3): 1, + (1, 0): 1, + (1, 1): 1, + (1, 2): 1, + (1, 3): 1, + } + result = _get_level_lengths(index, sparsify=True, max_index=100) + tm.assert_dict_equal(result, expected) + + expected = { + (0, 0): 1, + (0, 1): 1, + (0, 2): 1, + (0, 3): 1, + (1, 0): 1, + (1, 1): 1, + (1, 2): 1, + (1, 3): 1, + } + result = _get_level_lengths(index, sparsify=False, max_index=100) + tm.assert_dict_equal(result, expected) + + def test_mi_sparse_index_names(self, blank_value): + # Test the class names and displayed value are correct on rendering MI names + df = pd.DataFrame( + {"A": [1, 2]}, + index=pd.MultiIndex.from_arrays( + [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"] + ), + ) + result = df.style._translate(True, True) + head = result["head"][1] + expected = [ + { + "class": "index_name level0", + "display_value": "idx_level_0", + "is_visible": True, + }, + { + "class": "index_name level1", + "display_value": "idx_level_1", + "is_visible": True, + }, + { + "class": "blank col0", + "display_value": blank_value, + "is_visible": True, + }, + ] + for i, expected_dict in enumerate(expected): + assert expected_dict.items() <= head[i].items() + + def test_mi_sparse_column_names(self, blank_value): + df = pd.DataFrame( + np.arange(16).reshape(4, 4), + index=pd.MultiIndex.from_arrays( + [["a", "a", "b", "a"], [0, 1, 1, 2]], + names=["idx_level_0", "idx_level_1"], + ), + columns=pd.MultiIndex.from_arrays( + [["C1", "C1", "C2", "C2"], [1, 0, 1, 0]], names=["colnam_0", "colnam_1"] + ), + ) + result = Styler(df, cell_ids=False)._translate(True, True) + + for level in [0, 1]: + head = result["head"][level] + expected = [ + { + "class": "blank", + "display_value": blank_value, + "is_visible": True, + }, + { + "class": f"index_name level{level}", + "display_value": f"colnam_{level}", + "is_visible": True, + }, + ] + for i, expected_dict in enumerate(expected): + assert expected_dict.items() <= head[i].items() + + def test_hide_column_headers(self, df, styler): + ctx = styler.hide(axis="columns")._translate(True, True) + assert len(ctx["head"]) == 0 # no header entries with an unnamed index + + df.index.name = "some_name" + ctx = df.style.hide(axis="columns")._translate(True, True) + assert len(ctx["head"]) == 1 + # index names still visible, changed in #42101, reverted in 43404 + + def test_hide_single_index(self, df): + # GH 14194 + # single unnamed index + ctx = df.style._translate(True, True) + assert ctx["body"][0][0]["is_visible"] + assert ctx["head"][0][0]["is_visible"] + ctx2 = df.style.hide(axis="index")._translate(True, True) + assert not ctx2["body"][0][0]["is_visible"] + assert not ctx2["head"][0][0]["is_visible"] + + # single named index + ctx3 = df.set_index("A").style._translate(True, True) + assert ctx3["body"][0][0]["is_visible"] + assert len(ctx3["head"]) == 2 # 2 header levels + assert ctx3["head"][0][0]["is_visible"] + + ctx4 = df.set_index("A").style.hide(axis="index")._translate(True, True) + assert not ctx4["body"][0][0]["is_visible"] + assert len(ctx4["head"]) == 1 # only 1 header levels + assert not ctx4["head"][0][0]["is_visible"] + + def test_hide_multiindex(self): + # GH 14194 + df = pd.DataFrame( + {"A": [1, 2], "B": [1, 2]}, + index=pd.MultiIndex.from_arrays( + [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"] + ), + ) + ctx1 = df.style._translate(True, True) + # tests for 'a' and '0' + assert ctx1["body"][0][0]["is_visible"] + assert ctx1["body"][0][1]["is_visible"] + # check for blank header rows + assert len(ctx1["head"][0]) == 4 # two visible indexes and two data columns + + ctx2 = df.style.hide(axis="index")._translate(True, True) + # tests for 'a' and '0' + assert not ctx2["body"][0][0]["is_visible"] + assert not ctx2["body"][0][1]["is_visible"] + # check for blank header rows + assert len(ctx2["head"][0]) == 3 # one hidden (col name) and two data columns + assert not ctx2["head"][0][0]["is_visible"] + + def test_hide_columns_single_level(self, df): + # GH 14194 + # test hiding single column + ctx = df.style._translate(True, True) + assert ctx["head"][0][1]["is_visible"] + assert ctx["head"][0][1]["display_value"] == "A" + assert ctx["head"][0][2]["is_visible"] + assert ctx["head"][0][2]["display_value"] == "B" + assert ctx["body"][0][1]["is_visible"] # col A, row 1 + assert ctx["body"][1][2]["is_visible"] # col B, row 1 + + ctx = df.style.hide("A", axis="columns")._translate(True, True) + assert not ctx["head"][0][1]["is_visible"] + assert not ctx["body"][0][1]["is_visible"] # col A, row 1 + assert ctx["body"][1][2]["is_visible"] # col B, row 1 + + # test hiding multiple columns + ctx = df.style.hide(["A", "B"], axis="columns")._translate(True, True) + assert not ctx["head"][0][1]["is_visible"] + assert not ctx["head"][0][2]["is_visible"] + assert not ctx["body"][0][1]["is_visible"] # col A, row 1 + assert not ctx["body"][1][2]["is_visible"] # col B, row 1 + + def test_hide_columns_index_mult_levels(self): + # GH 14194 + # setup dataframe with multiple column levels and indices + i1 = pd.MultiIndex.from_arrays( + [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"] + ) + i2 = pd.MultiIndex.from_arrays( + [["b", "b"], [0, 1]], names=["col_level_0", "col_level_1"] + ) + df = pd.DataFrame([[1, 2], [3, 4]], index=i1, columns=i2) + ctx = df.style._translate(True, True) + # column headers + assert ctx["head"][0][2]["is_visible"] + assert ctx["head"][1][2]["is_visible"] + assert ctx["head"][1][3]["display_value"] == "1" + # indices + assert ctx["body"][0][0]["is_visible"] + # data + assert ctx["body"][1][2]["is_visible"] + assert ctx["body"][1][2]["display_value"] == "3" + assert ctx["body"][1][3]["is_visible"] + assert ctx["body"][1][3]["display_value"] == "4" + + # hide top column level, which hides both columns + ctx = df.style.hide("b", axis="columns")._translate(True, True) + assert not ctx["head"][0][2]["is_visible"] # b + assert not ctx["head"][1][2]["is_visible"] # 0 + assert not ctx["body"][1][2]["is_visible"] # 3 + assert ctx["body"][0][0]["is_visible"] # index + + # hide first column only + ctx = df.style.hide([("b", 0)], axis="columns")._translate(True, True) + assert not ctx["head"][0][2]["is_visible"] # b + assert ctx["head"][0][3]["is_visible"] # b + assert not ctx["head"][1][2]["is_visible"] # 0 + assert not ctx["body"][1][2]["is_visible"] # 3 + assert ctx["body"][1][3]["is_visible"] + assert ctx["body"][1][3]["display_value"] == "4" + + # hide second column and index + ctx = df.style.hide([("b", 1)], axis=1).hide(axis=0)._translate(True, True) + assert not ctx["body"][0][0]["is_visible"] # index + assert len(ctx["head"][0]) == 3 + assert ctx["head"][0][1]["is_visible"] # b + assert ctx["head"][1][1]["is_visible"] # 0 + assert not ctx["head"][1][2]["is_visible"] # 1 + assert not ctx["body"][1][3]["is_visible"] # 4 + assert ctx["body"][1][2]["is_visible"] + assert ctx["body"][1][2]["display_value"] == "3" + + # hide top row level, which hides both rows so body empty + ctx = df.style.hide("a", axis="index")._translate(True, True) + assert ctx["body"] == [] + + # hide first row only + ctx = df.style.hide(("a", 0), axis="index")._translate(True, True) + for i in [0, 1, 2, 3]: + assert "row1" in ctx["body"][0][i]["class"] # row0 not included in body + assert ctx["body"][0][i]["is_visible"] + + def test_pipe(self, df): + def set_caption_from_template(styler, a, b): + return styler.set_caption(f"Dataframe with a = {a} and b = {b}") + + styler = df.style.pipe(set_caption_from_template, "A", b="B") + assert "Dataframe with a = A and b = B" in styler.to_html() + + # Test with an argument that is a (callable, keyword_name) pair. + def f(a, b, styler): + return (a, b, styler) + + styler = df.style + result = styler.pipe((f, "styler"), a=1, b=2) + assert result == (1, 2, styler) + + def test_no_cell_ids(self): + # GH 35588 + # GH 35663 + df = pd.DataFrame(data=[[0]]) + styler = Styler(df, uuid="_", cell_ids=False) + styler.to_html() + s = styler.to_html() # render twice to ensure ctx is not updated + assert s.find('') != -1 + + @pytest.mark.parametrize( + "classes", + [ + pd.DataFrame( + data=[["", "test-class"], [np.nan, None]], + columns=["A", "B"], + index=["a", "b"], + ), + pd.DataFrame(data=[["test-class"]], columns=["B"], index=["a"]), + pd.DataFrame( + data=[["test-class", "unused"]], columns=["B", "C"], index=["a"] + ), + ], + ) + def test_set_data_classes(self, classes): + # GH 36159 + df = pd.DataFrame(data=[[0, 1], [2, 3]], columns=["A", "B"], index=["a", "b"]) + s = Styler(df, uuid_len=0, cell_ids=False).set_td_classes(classes).to_html() + assert '0' in s + assert '1' in s + assert '2' in s + assert '3' in s + # GH 39317 + s = Styler(df, uuid_len=0, cell_ids=True).set_td_classes(classes).to_html() + assert '0' in s + assert '1' in s + assert '2' in s + assert '3' in s + + def test_set_data_classes_reindex(self): + # GH 39317 + df = pd.DataFrame( + data=[[0, 1, 2], [3, 4, 5], [6, 7, 8]], columns=[0, 1, 2], index=[0, 1, 2] + ) + classes = pd.DataFrame( + data=[["mi", "ma"], ["mu", "mo"]], + columns=[0, 2], + index=[0, 2], + ) + s = Styler(df, uuid_len=0).set_td_classes(classes).to_html() + assert '0' in s + assert '2' in s + assert '4' in s + assert '6' in s + assert '8' in s + + def test_chaining_table_styles(self): + # GH 35607 + df = pd.DataFrame(data=[[0, 1], [1, 2]], columns=["A", "B"]) + styler = df.style.set_table_styles( + [{"selector": "", "props": [("background-color", "yellow")]}] + ).set_table_styles( + [{"selector": ".col0", "props": [("background-color", "blue")]}], + overwrite=False, + ) + assert len(styler.table_styles) == 2 + + def test_column_and_row_styling(self): + # GH 35607 + df = pd.DataFrame(data=[[0, 1], [1, 2]], columns=["A", "B"]) + s = Styler(df, uuid_len=0) + s = s.set_table_styles({"A": [{"selector": "", "props": [("color", "blue")]}]}) + assert "#T_ .col0 {\n color: blue;\n}" in s.to_html() + s = s.set_table_styles( + {0: [{"selector": "", "props": [("color", "blue")]}]}, axis=1 + ) + assert "#T_ .row0 {\n color: blue;\n}" in s.to_html() + + @pytest.mark.parametrize("len_", [1, 5, 32, 33, 100]) + def test_uuid_len(self, len_): + # GH 36345 + df = pd.DataFrame(data=[["A"]]) + s = Styler(df, uuid_len=len_, cell_ids=False).to_html() + strt = s.find('id="T_') + end = s[strt + 6 :].find('"') + if len_ > 32: + assert end == 32 + else: + assert end == len_ + + @pytest.mark.parametrize("len_", [-2, "bad", None]) + def test_uuid_len_raises(self, len_): + # GH 36345 + df = pd.DataFrame(data=[["A"]]) + msg = "``uuid_len`` must be an integer in range \\[0, 32\\]." + with pytest.raises(TypeError, match=msg): + Styler(df, uuid_len=len_, cell_ids=False).to_html() + + @pytest.mark.parametrize( + "slc", + [ + pd.IndexSlice[:, :], + pd.IndexSlice[:, 1], + pd.IndexSlice[1, :], + pd.IndexSlice[[1], [1]], + pd.IndexSlice[1, [1]], + pd.IndexSlice[[1], 1], + pd.IndexSlice[1], + pd.IndexSlice[1, 1], + slice(None, None, None), + [0, 1], + np.array([0, 1]), + pd.Series([0, 1]), + ], + ) + def test_non_reducing_slice(self, slc): + df = pd.DataFrame([[0, 1], [2, 3]]) + + tslice_ = non_reducing_slice(slc) + assert isinstance(df.loc[tslice_], pd.DataFrame) + + @pytest.mark.parametrize("box", [list, pd.Series, np.array]) + def test_list_slice(self, box): + # like dataframe getitem + subset = box(["A"]) + + df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["A", "B"]) + expected = pd.IndexSlice[:, ["A"]] + + result = non_reducing_slice(subset) + tm.assert_frame_equal(df.loc[result], df.loc[expected]) + + def test_non_reducing_slice_on_multiindex(self): + # GH 19861 + dic = { + ("a", "d"): [1, 4], + ("a", "c"): [2, 3], + ("b", "c"): [3, 2], + ("b", "d"): [4, 1], + } + df = pd.DataFrame(dic, index=[0, 1]) + idx = pd.IndexSlice + slice_ = idx[:, idx["b", "d"]] + tslice_ = non_reducing_slice(slice_) + + result = df.loc[tslice_] + expected = pd.DataFrame({("b", "d"): [4, 1]}) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "slice_", + [ + pd.IndexSlice[:, :], + # check cols + pd.IndexSlice[:, pd.IndexSlice[["a"]]], # inferred deeper need list + pd.IndexSlice[:, pd.IndexSlice[["a"], ["c"]]], # inferred deeper need list + pd.IndexSlice[:, pd.IndexSlice["a", "c", :]], + pd.IndexSlice[:, pd.IndexSlice["a", :, "e"]], + pd.IndexSlice[:, pd.IndexSlice[:, "c", "e"]], + pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d"], :]], # check list + pd.IndexSlice[ + :, pd.IndexSlice["a", ["c", "d", "-"], :] + ], # don't allow missing + pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d", "-"], "e"]], # no slice + # check rows + pd.IndexSlice[pd.IndexSlice[["U"]], :], # inferred deeper need list + pd.IndexSlice[pd.IndexSlice[["U"], ["W"]], :], # inferred deeper need list + pd.IndexSlice[pd.IndexSlice["U", "W", :], :], + pd.IndexSlice[pd.IndexSlice["U", :, "Y"], :], + pd.IndexSlice[pd.IndexSlice[:, "W", "Y"], :], + pd.IndexSlice[pd.IndexSlice[:, "W", ["Y", "Z"]], :], # check list + pd.IndexSlice[ + pd.IndexSlice[:, "W", ["Y", "Z", "-"]], : + ], # don't allow missing + pd.IndexSlice[pd.IndexSlice["U", "W", ["Y", "Z", "-"]], :], # no slice + # check simultaneous + pd.IndexSlice[pd.IndexSlice[:, "W", "Y"], pd.IndexSlice["a", "c", :]], + ], + ) + def test_non_reducing_multi_slice_on_multiindex(self, slice_): + # GH 33562 + cols = pd.MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]) + idxs = pd.MultiIndex.from_product([["U", "V"], ["W", "X"], ["Y", "Z"]]) + df = pd.DataFrame(np.arange(64).reshape(8, 8), columns=cols, index=idxs) + + for lvl in [0, 1]: + key = slice_[lvl] + if isinstance(key, tuple): + for subkey in key: + if isinstance(subkey, list) and "-" in subkey: + # not present in the index level, raises KeyError since 2.0 + with pytest.raises(KeyError, match="-"): + df.loc[slice_] + return + + expected = df.loc[slice_] + result = df.loc[non_reducing_slice(slice_)] + tm.assert_frame_equal(result, expected) + + +def test_hidden_index_names(mi_df): + mi_df.index.names = ["Lev0", "Lev1"] + mi_styler = mi_df.style + ctx = mi_styler._translate(True, True) + assert len(ctx["head"]) == 3 # 2 column index levels + 1 index names row + + mi_styler.hide(axis="index", names=True) + ctx = mi_styler._translate(True, True) + assert len(ctx["head"]) == 2 # index names row is unparsed + for i in range(4): + assert ctx["body"][0][i]["is_visible"] # 2 index levels + 2 data values visible + + mi_styler.hide(axis="index", level=1) + ctx = mi_styler._translate(True, True) + assert len(ctx["head"]) == 2 # index names row is still hidden + assert ctx["body"][0][0]["is_visible"] is True + assert ctx["body"][0][1]["is_visible"] is False + + +def test_hidden_column_names(mi_df): + mi_df.columns.names = ["Lev0", "Lev1"] + mi_styler = mi_df.style + ctx = mi_styler._translate(True, True) + assert ctx["head"][0][1]["display_value"] == "Lev0" + assert ctx["head"][1][1]["display_value"] == "Lev1" + + mi_styler.hide(names=True, axis="columns") + ctx = mi_styler._translate(True, True) + assert ctx["head"][0][1]["display_value"] == " " + assert ctx["head"][1][1]["display_value"] == " " + + mi_styler.hide(level=0, axis="columns") + ctx = mi_styler._translate(True, True) + assert len(ctx["head"]) == 1 # no index names and only one visible column headers + assert ctx["head"][0][1]["display_value"] == " " + + +@pytest.mark.parametrize("caption", [1, ("a", "b", "c"), (1, "s")]) +def test_caption_raises(mi_styler, caption): + msg = "`caption` must be either a string or 2-tuple of strings." + with pytest.raises(ValueError, match=msg): + mi_styler.set_caption(caption) + + +def test_hiding_headers_over_index_no_sparsify(): + # GH 43464 + midx = pd.MultiIndex.from_product([[1, 2], ["a", "a", "b"]]) + df = pd.DataFrame(9, index=midx, columns=[0]) + ctx = df.style._translate(False, False) + assert len(ctx["body"]) == 6 + ctx = df.style.hide((1, "a"), axis=0)._translate(False, False) + assert len(ctx["body"]) == 4 + assert "row2" in ctx["body"][0][0]["class"] + + +def test_hiding_headers_over_columns_no_sparsify(): + # GH 43464 + midx = pd.MultiIndex.from_product([[1, 2], ["a", "a", "b"]]) + df = pd.DataFrame(9, columns=midx, index=[0]) + ctx = df.style._translate(False, False) + for ix in [(0, 1), (0, 2), (1, 1), (1, 2)]: + assert ctx["head"][ix[0]][ix[1]]["is_visible"] is True + ctx = df.style.hide((1, "a"), axis="columns")._translate(False, False) + for ix in [(0, 1), (0, 2), (1, 1), (1, 2)]: + assert ctx["head"][ix[0]][ix[1]]["is_visible"] is False + + +def test_get_level_lengths_mi_hidden(): + # GH 43464 + index = pd.MultiIndex.from_arrays( + [[1, 1, 1, 2, 2, 2], ["a", "a", "b", "a", "a", "b"]] + ) + expected = { + (0, 2): 1, + (0, 3): 1, + (0, 4): 1, + (0, 5): 1, + (1, 2): 1, + (1, 3): 1, + (1, 4): 1, + (1, 5): 1, + } + result = _get_level_lengths( + index, + sparsify=False, + max_index=100, + hidden_elements=[0, 1, 0, 1], # hidden element can repeat if duplicated index + ) + tm.assert_dict_equal(result, expected) + + +def test_row_trimming_hide_index(): + # gh 43703 + df = pd.DataFrame([[1], [2], [3], [4], [5]]) + with pd.option_context("styler.render.max_rows", 2): + ctx = df.style.hide([0, 1], axis="index")._translate(True, True) + assert len(ctx["body"]) == 3 + for r, val in enumerate(["3", "4", "..."]): + assert ctx["body"][r][1]["display_value"] == val + + +def test_row_trimming_hide_index_mi(): + # gh 44247 + df = pd.DataFrame([[1], [2], [3], [4], [5]]) + df.index = pd.MultiIndex.from_product([[0], [0, 1, 2, 3, 4]]) + with pd.option_context("styler.render.max_rows", 2): + ctx = df.style.hide([(0, 0), (0, 1)], axis="index")._translate(True, True) + assert len(ctx["body"]) == 3 + + # level 0 index headers (sparsified) + assert {"value": 0, "attributes": 'rowspan="2"', "is_visible": True}.items() <= ctx[ + "body" + ][0][0].items() + assert {"value": 0, "attributes": "", "is_visible": False}.items() <= ctx["body"][ + 1 + ][0].items() + assert {"value": "...", "is_visible": True}.items() <= ctx["body"][2][0].items() + + for r, val in enumerate(["2", "3", "..."]): + assert ctx["body"][r][1]["display_value"] == val # level 1 index headers + for r, val in enumerate(["3", "4", "..."]): + assert ctx["body"][r][2]["display_value"] == val # data values + + +def test_col_trimming_hide_columns(): + # gh 44272 + df = pd.DataFrame([[1, 2, 3, 4, 5]]) + with pd.option_context("styler.render.max_columns", 2): + ctx = df.style.hide([0, 1], axis="columns")._translate(True, True) + + assert len(ctx["head"][0]) == 6 # blank, [0, 1 (hidden)], [2 ,3 (visible)], + trim + for c, vals in enumerate([(1, False), (2, True), (3, True), ("...", True)]): + assert ctx["head"][0][c + 2]["value"] == vals[0] + assert ctx["head"][0][c + 2]["is_visible"] == vals[1] + + assert len(ctx["body"][0]) == 6 # index + 2 hidden + 2 visible + trimming col + + +def test_no_empty_apply(mi_styler): + # 45313 + mi_styler.apply(lambda s: ["a:v;"] * 2, subset=[False, False]) + mi_styler._compute() + + +@pytest.mark.parametrize("format", ["html", "latex", "string"]) +def test_output_buffer(mi_styler, format, temp_file): + # gh 47053 + getattr(mi_styler, f"to_{format}")(temp_file) diff --git a/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_to_latex.py b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_to_latex.py new file mode 100644 index 0000000000000000000000000000000000000000..609d6682373128bf7832c98f3039cc3ba38e0023 --- /dev/null +++ b/venv/lib/python3.14/site-packages/pandas/tests/io/formats/style/test_to_latex.py @@ -0,0 +1,1098 @@ +from textwrap import dedent + +import numpy as np +import pytest + +import pandas as pd + +pytest.importorskip("jinja2") +from pandas.io.formats.style import Styler +from pandas.io.formats.style_render import ( + _parse_latex_cell_styles, + _parse_latex_css_conversion, + _parse_latex_header_span, + _parse_latex_table_styles, + _parse_latex_table_wrapping, +) + + +@pytest.fixture +def df(): + return pd.DataFrame( + {"A": [0, 1], "B": [-0.61, -1.22], "C": pd.Series(["ab", "cd"], dtype=object)} + ) + + +@pytest.fixture +def df_ext(): + return pd.DataFrame( + {"A": [0, 1, 2], "B": [-0.61, -1.22, -2.22], "C": ["ab", "cd", "de"]} + ) + + +@pytest.fixture +def styler(df): + return Styler(df, uuid_len=0, precision=2) + + +def test_minimal_latex_tabular(styler): + expected = dedent( + """\ + \\begin{tabular}{lrrl} + & A & B & C \\\\ + 0 & 0 & -0.61 & ab \\\\ + 1 & 1 & -1.22 & cd \\\\ + \\end{tabular} + """ + ) + assert styler.to_latex() == expected + + +def test_tabular_hrules(styler): + expected = dedent( + """\ + \\begin{tabular}{lrrl} + \\toprule + & A & B & C \\\\ + \\midrule + 0 & 0 & -0.61 & ab \\\\ + 1 & 1 & -1.22 & cd \\\\ + \\bottomrule + \\end{tabular} + """ + ) + assert styler.to_latex(hrules=True) == expected + + +def test_tabular_custom_hrules(styler): + styler.set_table_styles( + [ + {"selector": "toprule", "props": ":hline"}, + {"selector": "bottomrule", "props": ":otherline"}, + ] + ) # no midrule + expected = dedent( + """\ + \\begin{tabular}{lrrl} + \\hline + & A & B & C \\\\ + 0 & 0 & -0.61 & ab \\\\ + 1 & 1 & -1.22 & cd \\\\ + \\otherline + \\end{tabular} + """ + ) + assert styler.to_latex() == expected + + +def test_column_format(styler): + # default setting is already tested in `test_latex_minimal_tabular` + styler.set_table_styles([{"selector": "column_format", "props": ":cccc"}]) + + assert "\\begin{tabular}{rrrr}" in styler.to_latex(column_format="rrrr") + styler.set_table_styles([{"selector": "column_format", "props": ":r|r|cc"}]) + assert "\\begin{tabular}{r|r|cc}" in styler.to_latex() + + +def test_siunitx_cols(styler): + expected = dedent( + """\ + \\begin{tabular}{lSSl} + {} & {A} & {B} & {C} \\\\ + 0 & 0 & -0.61 & ab \\\\ + 1 & 1 & -1.22 & cd \\\\ + \\end{tabular} + """ + ) + assert styler.to_latex(siunitx=True) == expected + + +def test_position(styler): + assert "\\begin{table}[h!]" in styler.to_latex(position="h!") + assert "\\end{table}" in styler.to_latex(position="h!") + styler.set_table_styles([{"selector": "position", "props": ":b!"}]) + assert "\\begin{table}[b!]" in styler.to_latex() + assert "\\end{table}" in styler.to_latex() + + +@pytest.mark.parametrize("env", [None, "longtable"]) +def test_label(styler, env): + assert "\n\\label{text}" in styler.to_latex(label="text", environment=env) + styler.set_table_styles([{"selector": "label", "props": ":{more §text}"}]) + assert "\n\\label{more :text}" in styler.to_latex(environment=env) + + +def test_position_float_raises(styler): + msg = "`position_float` should be one of 'raggedright', 'raggedleft', 'centering'," + with pytest.raises(ValueError, match=msg): + styler.to_latex(position_float="bad_string") + + msg = "`position_float` cannot be used in 'longtable' `environment`" + with pytest.raises(ValueError, match=msg): + styler.to_latex(position_float="centering", environment="longtable") + + +@pytest.mark.parametrize("label", [(None, ""), ("text", "\\label{text}")]) +@pytest.mark.parametrize("position", [(None, ""), ("h!", "{table}[h!]")]) +@pytest.mark.parametrize("caption", [(None, ""), ("text", "\\caption{text}")]) +@pytest.mark.parametrize("column_format", [(None, ""), ("rcrl", "{tabular}{rcrl}")]) +@pytest.mark.parametrize("position_float", [(None, ""), ("centering", "\\centering")]) +def test_kwargs_combinations( + styler, label, position, caption, column_format, position_float +): + result = styler.to_latex( + label=label[0], + position=position[0], + caption=caption[0], + column_format=column_format[0], + position_float=position_float[0], + ) + assert label[1] in result + assert position[1] in result + assert caption[1] in result + assert column_format[1] in result + assert position_float[1] in result + + +def test_custom_table_styles(styler): + styler.set_table_styles( + [ + {"selector": "mycommand", "props": ":{myoptions}"}, + {"selector": "mycommand2", "props": ":{myoptions2}"}, + ] + ) + expected = dedent( + """\ + \\begin{table} + \\mycommand{myoptions} + \\mycommand2{myoptions2} + """ + ) + assert expected in styler.to_latex() + + +def test_cell_styling(styler): + styler.highlight_max(props="itshape:;Huge:--wrap;") + expected = dedent( + """\ + \\begin{tabular}{lrrl} + & A & B & C \\\\ + 0 & 0 & \\itshape {\\Huge -0.61} & ab \\\\ + 1 & \\itshape {\\Huge 1} & -1.22 & \\itshape {\\Huge cd} \\\\ + \\end{tabular} + """ + ) + assert expected == styler.to_latex() + + +def test_multiindex_columns(df): + cidx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df.columns = cidx + expected = dedent( + """\ + \\begin{tabular}{lrrl} + & \\multicolumn{2}{r}{A} & B \\\\ + & a & b & c \\\\ + 0 & 0 & -0.61 & ab \\\\ + 1 & 1 & -1.22 & cd \\\\ + \\end{tabular} + """ + ) + s = df.style.format(precision=2) + assert expected == s.to_latex() + + # non-sparse + expected = dedent( + """\ + \\begin{tabular}{lrrl} + & A & A & B \\\\ + & a & b & c \\\\ + 0 & 0 & -0.61 & ab \\\\ + 1 & 1 & -1.22 & cd \\\\ + \\end{tabular} + """ + ) + s = df.style.format(precision=2) + assert expected == s.to_latex(sparse_columns=False) + + +def test_multiindex_row(df_ext): + ridx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df_ext.index = ridx + expected = dedent( + """\ + \\begin{tabular}{llrrl} + & & A & B & C \\\\ + \\multirow[c]{2}{*}{A} & a & 0 & -0.61 & ab \\\\ + & b & 1 & -1.22 & cd \\\\ + B & c & 2 & -2.22 & de \\\\ + \\end{tabular} + """ + ) + styler = df_ext.style.format(precision=2) + result = styler.to_latex() + assert expected == result + + # non-sparse + expected = dedent( + """\ + \\begin{tabular}{llrrl} + & & A & B & C \\\\ + A & a & 0 & -0.61 & ab \\\\ + A & b & 1 & -1.22 & cd \\\\ + B & c & 2 & -2.22 & de \\\\ + \\end{tabular} + """ + ) + result = styler.to_latex(sparse_index=False) + assert expected == result + + +def test_multirow_naive(df_ext): + ridx = pd.MultiIndex.from_tuples([("X", "x"), ("X", "y"), ("Y", "z")]) + df_ext.index = ridx + expected = dedent( + """\ + \\begin{tabular}{llrrl} + & & A & B & C \\\\ + X & x & 0 & -0.61 & ab \\\\ + & y & 1 & -1.22 & cd \\\\ + Y & z & 2 & -2.22 & de \\\\ + \\end{tabular} + """ + ) + styler = df_ext.style.format(precision=2) + result = styler.to_latex(multirow_align="naive") + assert expected == result + + +def test_multiindex_row_and_col(df_ext): + cidx = pd.MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")]) + ridx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df_ext.index, df_ext.columns = ridx, cidx + expected = dedent( + """\ + \\begin{tabular}{llrrl} + & & \\multicolumn{2}{l}{Z} & Y \\\\ + & & a & b & c \\\\ + \\multirow[b]{2}{*}{A} & a & 0 & -0.61 & ab \\\\ + & b & 1 & -1.22 & cd \\\\ + B & c & 2 & -2.22 & de \\\\ + \\end{tabular} + """ + ) + styler = df_ext.style.format(precision=2) + result = styler.to_latex(multirow_align="b", multicol_align="l") + assert result == expected + + # non-sparse + expected = dedent( + """\ + \\begin{tabular}{llrrl} + & & Z & Z & Y \\\\ + & & a & b & c \\\\ + A & a & 0 & -0.61 & ab \\\\ + A & b & 1 & -1.22 & cd \\\\ + B & c & 2 & -2.22 & de \\\\ + \\end{tabular} + """ + ) + result = styler.to_latex(sparse_index=False, sparse_columns=False) + assert result == expected + + +@pytest.mark.parametrize( + "multicol_align, siunitx, header", + [ + ("naive-l", False, " & A & &"), + ("naive-r", False, " & & & A"), + ("naive-l", True, "{} & {A} & {} & {}"), + ("naive-r", True, "{} & {} & {} & {A}"), + ], +) +def test_multicol_naive(df, multicol_align, siunitx, header): + ridx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("A", "c")]) + df.columns = ridx + level1 = " & a & b & c" if not siunitx else "{} & {a} & {b} & {c}" + col_format = "lrrl" if not siunitx else "lSSl" + expected = dedent( + f"""\ + \\begin{{tabular}}{{{col_format}}} + {header} \\\\ + {level1} \\\\ + 0 & 0 & -0.61 & ab \\\\ + 1 & 1 & -1.22 & cd \\\\ + \\end{{tabular}} + """ + ) + styler = df.style.format(precision=2) + result = styler.to_latex(multicol_align=multicol_align, siunitx=siunitx) + assert expected == result + + +def test_multi_options(df_ext): + cidx = pd.MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")]) + ridx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df_ext.index, df_ext.columns = ridx, cidx + styler = df_ext.style.format(precision=2) + + expected = dedent( + """\ + & & \\multicolumn{2}{r}{Z} & Y \\\\ + & & a & b & c \\\\ + \\multirow[c]{2}{*}{A} & a & 0 & -0.61 & ab \\\\ + """ + ) + result = styler.to_latex() + assert expected in result + + with pd.option_context("styler.latex.multicol_align", "l"): + assert " & & \\multicolumn{2}{l}{Z} & Y \\\\" in styler.to_latex() + + with pd.option_context("styler.latex.multirow_align", "b"): + assert "\\multirow[b]{2}{*}{A} & a & 0 & -0.61 & ab \\\\" in styler.to_latex() + + +def test_multiindex_columns_hidden(): + df = pd.DataFrame([[1, 2, 3, 4]]) + df.columns = pd.MultiIndex.from_tuples([("A", 1), ("A", 2), ("A", 3), ("B", 1)]) + s = df.style + assert "{tabular}{lrrrr}" in s.to_latex() + s.set_table_styles([]) # reset the position command + s.hide([("A", 2)], axis="columns") + assert "{tabular}{lrrr}" in s.to_latex() + + +@pytest.mark.parametrize( + "option, value", + [ + ("styler.sparse.index", True), + ("styler.sparse.index", False), + ("styler.sparse.columns", True), + ("styler.sparse.columns", False), + ], +) +def test_sparse_options(df_ext, option, value): + cidx = pd.MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")]) + ridx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df_ext.index, df_ext.columns = ridx, cidx + styler = df_ext.style + + latex1 = styler.to_latex() + with pd.option_context(option, value): + latex2 = styler.to_latex() + assert (latex1 == latex2) is value + + +def test_hidden_index(styler): + styler.hide(axis="index") + expected = dedent( + """\ + \\begin{tabular}{rrl} + A & B & C \\\\ + 0 & -0.61 & ab \\\\ + 1 & -1.22 & cd \\\\ + \\end{tabular} + """ + ) + assert styler.to_latex() == expected + + +@pytest.mark.parametrize("environment", ["table", "figure*", None]) +def test_comprehensive(df_ext, environment): + # test as many low level features simultaneously as possible + cidx = pd.MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")]) + ridx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df_ext.index, df_ext.columns = ridx, cidx + stlr = df_ext.style + stlr.set_caption("mycap") + stlr.set_table_styles( + [ + {"selector": "label", "props": ":{fig§item}"}, + {"selector": "position", "props": ":h!"}, + {"selector": "position_float", "props": ":centering"}, + {"selector": "column_format", "props": ":rlrlr"}, + {"selector": "toprule", "props": ":toprule"}, + {"selector": "midrule", "props": ":midrule"}, + {"selector": "bottomrule", "props": ":bottomrule"}, + {"selector": "rowcolors", "props": ":{3}{pink}{}"}, # custom command + ] + ) + stlr.highlight_max(axis=0, props="textbf:--rwrap;cellcolor:[rgb]{1,1,0.6}--rwrap") + stlr.highlight_max(axis=None, props="Huge:--wrap;", subset=[("Z", "a"), ("Z", "b")]) + + expected = ( + """\ +\\begin{table}[h!] +\\centering +\\caption{mycap} +\\label{fig:item} +\\rowcolors{3}{pink}{} +\\begin{tabular}{rlrlr} +\\toprule + & & \\multicolumn{2}{r}{Z} & Y \\\\ + & & a & b & c \\\\ +\\midrule +\\multirow[c]{2}{*}{A} & a & 0 & \\textbf{\\cellcolor[rgb]{1,1,0.6}{-0.61}} & ab \\\\ + & b & 1 & -1.22 & cd \\\\ +B & c & \\textbf{\\cellcolor[rgb]{1,1,0.6}{{\\Huge 2}}} & -2.22 & """ + """\ +\\textbf{\\cellcolor[rgb]{1,1,0.6}{de}} \\\\ +\\bottomrule +\\end{tabular} +\\end{table} +""" + ).replace("table", environment if environment else "table") + result = stlr.format(precision=2).to_latex(environment=environment) + assert result == expected + + +def test_environment_option(styler): + with pd.option_context("styler.latex.environment", "bar-env"): + assert "\\begin{bar-env}" in styler.to_latex() + assert "\\begin{foo-env}" in styler.to_latex(environment="foo-env") + + +def test_parse_latex_table_styles(styler): + styler.set_table_styles( + [ + {"selector": "foo", "props": [("attr", "value")]}, + {"selector": "bar", "props": [("attr", "overwritten")]}, + {"selector": "bar", "props": [("attr", "baz"), ("attr2", "ignored")]}, + {"selector": "label", "props": [("", "{fig§item}")]}, + ] + ) + assert _parse_latex_table_styles(styler.table_styles, "bar") == "baz" + + # test '§' replaced by ':' [for CSS compatibility] + assert _parse_latex_table_styles(styler.table_styles, "label") == "{fig:item}" + + +def test_parse_latex_cell_styles_basic(): # test nesting + cell_style = [("itshape", "--rwrap"), ("cellcolor", "[rgb]{0,1,1}--rwrap")] + expected = "\\itshape{\\cellcolor[rgb]{0,1,1}{text}}" + assert _parse_latex_cell_styles(cell_style, "text") == expected + + +@pytest.mark.parametrize( + "wrap_arg, expected", + [ # test wrapping + ("", "\\ "), + ("--wrap", "{\\ }"), + ("--nowrap", "\\ "), + ("--lwrap", "{\\} "), + ("--dwrap", "{\\}{}"), + ("--rwrap", "\\{}"), + ], +) +def test_parse_latex_cell_styles_braces(wrap_arg, expected): + cell_style = [("", f"{wrap_arg}")] + assert _parse_latex_cell_styles(cell_style, "") == expected + + +def test_parse_latex_header_span(): + cell = {"attributes": 'colspan="3"', "display_value": "text", "cellstyle": []} + expected = "\\multicolumn{3}{Y}{text}" + assert _parse_latex_header_span(cell, "X", "Y") == expected + + cell = {"attributes": 'rowspan="5"', "display_value": "text", "cellstyle": []} + expected = "\\multirow[X]{5}{*}{text}" + assert _parse_latex_header_span(cell, "X", "Y") == expected + + cell = {"display_value": "text", "cellstyle": []} + assert _parse_latex_header_span(cell, "X", "Y") == "text" + + cell = {"display_value": "text", "cellstyle": [("bfseries", "--rwrap")]} + assert _parse_latex_header_span(cell, "X", "Y") == "\\bfseries{text}" + + +def test_parse_latex_table_wrapping(styler): + styler.set_table_styles( + [ + {"selector": "toprule", "props": ":value"}, + {"selector": "bottomrule", "props": ":value"}, + {"selector": "midrule", "props": ":value"}, + {"selector": "column_format", "props": ":value"}, + ] + ) + assert _parse_latex_table_wrapping(styler.table_styles, styler.caption) is False + assert _parse_latex_table_wrapping(styler.table_styles, "some caption") is True + styler.set_table_styles( + [ + {"selector": "not-ignored", "props": ":value"}, + ], + overwrite=False, + ) + assert _parse_latex_table_wrapping(styler.table_styles, None) is True + + +def test_short_caption(styler): + result = styler.to_latex(caption=("full cap", "short cap")) + assert "\\caption[short cap]{full cap}" in result + + +@pytest.mark.parametrize( + "css, expected", + [ + ([("color", "red")], [("color", "{red}")]), # test color and input format types + ( + [("color", "rgb(128, 128, 128 )")], + [("color", "[rgb]{0.502, 0.502, 0.502}")], + ), + ( + [("color", "rgb(128, 50%, 25% )")], + [("color", "[rgb]{0.502, 0.500, 0.250}")], + ), + ( + [("color", "rgba(128,128,128,1)")], + [("color", "[rgb]{0.502, 0.502, 0.502}")], + ), + ([("color", "#FF00FF")], [("color", "[HTML]{FF00FF}")]), + ([("color", "#F0F")], [("color", "[HTML]{FF00FF}")]), + ([("font-weight", "bold")], [("bfseries", "")]), # test font-weight and types + ([("font-weight", "bolder")], [("bfseries", "")]), + ([("font-weight", "normal")], []), + ([("background-color", "red")], [("cellcolor", "{red}--lwrap")]), + ( + [("background-color", "#FF00FF")], # test background-color command and wrap + [("cellcolor", "[HTML]{FF00FF}--lwrap")], + ), + ([("font-style", "italic")], [("itshape", "")]), # test font-style and types + ([("font-style", "oblique")], [("slshape", "")]), + ([("font-style", "normal")], []), + ([("color", "red /*--dwrap*/")], [("color", "{red}--dwrap")]), # css comments + ([("background-color", "red /* --dwrap */")], [("cellcolor", "{red}--dwrap")]), + ], +) +def test_parse_latex_css_conversion(css, expected): + result = _parse_latex_css_conversion(css) + assert result == expected + + +@pytest.mark.parametrize( + "env, inner_env", + [ + (None, "tabular"), + ("table", "tabular"), + ("longtable", "longtable"), + ], +) +@pytest.mark.parametrize( + "convert, exp", [(True, "bfseries"), (False, "font-weightbold")] +) +def test_parse_latex_css_convert_minimal(styler, env, inner_env, convert, exp): + # parameters ensure longtable template is also tested + styler.highlight_max(props="font-weight:bold;") + result = styler.to_latex(convert_css=convert, environment=env) + expected = dedent( + f"""\ + 0 & 0 & \\{exp} -0.61 & ab \\\\ + 1 & \\{exp} 1 & -1.22 & \\{exp} cd \\\\ + \\end{{{inner_env}}} + """ + ) + assert expected in result + + +def test_parse_latex_css_conversion_option(): + css = [("command", "option--latex--wrap")] + expected = [("command", "option--wrap")] + result = _parse_latex_css_conversion(css) + assert result == expected + + +def test_styler_object_after_render(styler): + # GH 42320 + pre_render = styler._copy(deepcopy=True) + styler.to_latex( + column_format="rllr", + position="h", + position_float="centering", + hrules=True, + label="my lab", + caption="my cap", + ) + + assert pre_render.table_styles == styler.table_styles + assert pre_render.caption == styler.caption + + +def test_longtable_comprehensive(styler): + result = styler.to_latex( + environment="longtable", hrules=True, label="fig:A", caption=("full", "short") + ) + expected = dedent( + """\ + \\begin{longtable}{lrrl} + \\caption[short]{full} \\label{fig:A} \\\\ + \\toprule + & A & B & C \\\\ + \\midrule + \\endfirsthead + \\caption[]{full} \\\\ + \\toprule + & A & B & C \\\\ + \\midrule + \\endhead + \\midrule + \\multicolumn{4}{r}{Continued on next page} \\\\ + \\midrule + \\endfoot + \\bottomrule + \\endlastfoot + 0 & 0 & -0.61 & ab \\\\ + 1 & 1 & -1.22 & cd \\\\ + \\end{longtable} + """ + ) + assert result == expected + + +def test_longtable_minimal(styler): + result = styler.to_latex(environment="longtable") + expected = dedent( + """\ + \\begin{longtable}{lrrl} + & A & B & C \\\\ + \\endfirsthead + & A & B & C \\\\ + \\endhead + \\multicolumn{4}{r}{Continued on next page} \\\\ + \\endfoot + \\endlastfoot + 0 & 0 & -0.61 & ab \\\\ + 1 & 1 & -1.22 & cd \\\\ + \\end{longtable} + """ + ) + assert result == expected + + +@pytest.mark.parametrize( + "sparse, exp, siunitx", + [ + (True, "{} & \\multicolumn{2}{r}{A} & {B}", True), + (False, "{} & {A} & {A} & {B}", True), + (True, " & \\multicolumn{2}{r}{A} & B", False), + (False, " & A & A & B", False), + ], +) +def test_longtable_multiindex_columns(df, sparse, exp, siunitx): + cidx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df.columns = cidx + with_si = "{} & {a} & {b} & {c} \\\\" + without_si = " & a & b & c \\\\" + expected = dedent( + f"""\ + \\begin{{longtable}}{{l{"SS" if siunitx else "rr"}l}} + {exp} \\\\ + {with_si if siunitx else without_si} + \\endfirsthead + {exp} \\\\ + {with_si if siunitx else without_si} + \\endhead + """ + ) + result = df.style.to_latex( + environment="longtable", sparse_columns=sparse, siunitx=siunitx + ) + assert expected in result + + +@pytest.mark.parametrize( + "caption, cap_exp", + [ + ("full", ("{full}", "")), + (("full", "short"), ("{full}", "[short]")), + ], +) +@pytest.mark.parametrize("label, lab_exp", [(None, ""), ("tab:A", " \\label{tab:A}")]) +def test_longtable_caption_label(styler, caption, cap_exp, label, lab_exp): + cap_exp1 = f"\\caption{cap_exp[1]}{cap_exp[0]}" + cap_exp2 = f"\\caption[]{cap_exp[0]}" + + expected = dedent( + f"""\ + {cap_exp1}{lab_exp} \\\\ + & A & B & C \\\\ + \\endfirsthead + {cap_exp2} \\\\ + """ + ) + assert expected in styler.to_latex( + environment="longtable", caption=caption, label=label + ) + + +@pytest.mark.parametrize("index", [True, False]) +@pytest.mark.parametrize( + "columns, siunitx", + [ + (True, True), + (True, False), + (False, False), + ], +) +def test_apply_map_header_render_mi(df_ext, index, columns, siunitx): + cidx = pd.MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")]) + ridx = pd.MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df_ext.index, df_ext.columns = ridx, cidx + styler = df_ext.style + + func = lambda v: "bfseries: --rwrap" if "A" in v or "Z" in v or "c" in v else None + + if index: + styler.map_index(func, axis="index") + if columns: + styler.map_index(func, axis="columns") + + result = styler.to_latex(siunitx=siunitx) + + expected_index = dedent( + """\ + \\multirow[c]{2}{*}{\\bfseries{A}} & a & 0 & -0.610000 & ab \\\\ + \\bfseries{} & b & 1 & -1.220000 & cd \\\\ + B & \\bfseries{c} & 2 & -2.220000 & de \\\\ + """ + ) + assert (expected_index in result) is index + + exp_cols_si = dedent( + """\ + {} & {} & \\multicolumn{2}{r}{\\bfseries{Z}} & {Y} \\\\ + {} & {} & {a} & {b} & {\\bfseries{c}} \\\\ + """ + ) + exp_cols_no_si = """\ + & & \\multicolumn{2}{r}{\\bfseries{Z}} & Y \\\\ + & & a & b & \\bfseries{c} \\\\ +""" + assert ((exp_cols_si if siunitx else exp_cols_no_si) in result) is columns + + +def test_repr_option(styler): + assert "